Skip to content

Black Friday

Annual Pro is $90 for the first year, normally $120. Or start monthly at $6 for two months, then $12.

Ends Dec 4, 11:59 PM PT.

Create an account
← Public packages

@tannerlinsley/imessage

Read, search, draft, and explicitly send iMessages on a Mac, using only built-in macOS tools.

FollowFork

Files

native.ts

208 lines · 15.1 KB · TypeScript
// Uses only Foundation, AppKit, sqlite3, and Messages automation shipped with macOS.
export const nativeSource = String.raw`
ObjC.import('Foundation');
ObjC.import('AppKit');
ObjC.import('Contacts');
function task(file, args) {
  var p = $.NSTask.alloc.init;
  p.launchPath = file;
  p.arguments = args;
  var out = $.NSPipe.pipe, err = $.NSPipe.pipe;
  p.standardOutput = out; p.standardError = err;
  p.launch;
  var stdout = $.NSString.alloc.initWithDataEncoding(out.fileHandleForReading.readDataToEndOfFile, $.NSUTF8StringEncoding);
  var stderr = $.NSString.alloc.initWithDataEncoding(err.fileHandleForReading.readDataToEndOfFile, $.NSUTF8StringEncoding);
  p.waitUntilExit;
  return {code:p.terminationStatus, stdout:ObjC.unwrap(stdout) || '', stderr:ObjC.unwrap(stderr) || ''};
}
function sqlString(s) { return "'" + String(s).replace(/'/g, "''") + "'"; }
function database() { return ObjC.unwrap($.NSHomeDirectory()) + '/Library/Messages/chat.db'; }
function query(sql) {
  var result = task('/usr/bin/sqlite3', ['-readonly', '-json', '-cmd', '.timeout 3000', database(), sql]);
  if (result.code !== 0) {
    if (/not permitted|authorization denied|unable to open database|permission denied/i.test(result.stderr))
      throw new Error('MESSAGES_ACCESS_REQUIRED: Grant Full Disk Access to the app running the Kody daemon (Kody Desktop for desktop runs), then restart it. Messages must be signed in on this Mac.');
    throw new Error('MESSAGES_DATABASE_ERROR: The local Messages database could not be read. Its schema may be unsupported.');
  }
  return result.stdout.trim() ? JSON.parse(result.stdout) : [];
}
function columns(table) { return query('PRAGMA table_info(' + table + ')').map(function(c){return c.name;}); }
function attributedText(hex) {
  if (!hex) return {text:'', source:'unavailable'};
  try {
    // Decode Apple's own NSAttributedString archive, never evaluate its text.
    var data = $.NSMutableData.data;
    var bytes = [];
    for(var i=0;i<hex.length;i+=2) bytes.push(parseInt(hex.slice(i,i+2),16));
    var encoded = '';
    var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
    for(var j=0;j<bytes.length;j+=3){var a=bytes[j], b=bytes[j+1], c=bytes[j+2];
      encoded += chars[a>>2] + chars[((a&3)<<4)|((b||0)>>4)] + (b===undefined?'=':chars[((b&15)<<2)|((c||0)>>6)]) + (c===undefined?'=':chars[c&63]);}
    data = $.NSData.alloc.initWithBase64EncodedStringOptions(encoded,0);
    var decoded = $.NSUnarchiver.unarchiveObjectWithData(data);
    var text = ObjC.unwrap(decoded.string);
    if(typeof text !== 'string') throw new Error('Not an attributed string');
    return {text:text, source:'attributed'};
  } catch(e) { return {text:'',source:'unavailable'}; }
}

function contactsAccess() {
  var value=Number($.CNContactStore.authorizationStatusForEntityType(0));
  var names=['not-determined','restricted','denied','authorized','limited'];
  var state=names[value]||'unavailable';
  return {authorization:state,readable:state==='authorized'||state==='limited',
    issue:state==='authorized'?null:state==='limited'?'Only contacts shared with Kody are visible.':'Allow Contacts access for the app running the daemon. Kody Desktop needs version 0.1.5 or newer. Full Disk Access does not grant Contacts access.'};
}
var contactStore;
function fetchContacts(predicate, includeAddresses) {
  if(!contactStore) contactStore=$.CNContactStore.alloc.init;
  var error=Ref();
  var keysList=[$.CNContactIdentifierKey,$.CNContactGivenNameKey,$.CNContactMiddleNameKey,$.CNContactFamilyNameKey,$.CNContactNicknameKey,$.CNContactOrganizationNameKey,$.CNContactFormatter.descriptorForRequiredKeysForStyle(0)];
  if(includeAddresses) keysList=keysList.concat([$.CNContactPhoneNumbersKey,$.CNContactEmailAddressesKey]);
  var keys=$.NSMutableArray.alloc.init;
  keysList.forEach(function(key){keys.addObject(key);});
  var rows=contactStore.unifiedContactsMatchingPredicateKeysToFetchError(predicate,keys,error);
  if(error[0]) throw new Error('CONTACTS_ACCESS_REQUIRED: Contacts could not be read. Check Contacts permission for Kody Desktop or the actual daemon host.');
  var result=[];
  for(var i=0;i<Number(rows.count);i++){
    var c=rows.objectAtIndex(i);
    var name=ObjC.unwrap($.CNContactFormatter.stringFromContactStyle(c,0))||ObjC.unwrap(c.nickname)||ObjC.unwrap(c.organizationName)||'';
    var phones=[],emails=[];
    for(var j=0;includeAddresses && j<Number(c.phoneNumbers.count);j++) phones.push(ObjC.unwrap(c.phoneNumbers.objectAtIndex(j).value.stringValue));
    for(var k=0;includeAddresses && k<Number(c.emailAddresses.count);k++) emails.push(ObjC.unwrap(c.emailAddresses.objectAtIndex(k).value));
    result.push({id:ObjC.unwrap(c.identifier),name:name,phoneNumbers:phones,emailAddresses:emails});
  }
  return result;
}
function contactPredicate(handle) {
  return handle.indexOf('@')>=0 ? $.CNContact.predicateForContactsMatchingEmailAddress(handle) : $.CNContact.predicateForContactsMatchingPhoneNumber($.CNPhoneNumber.phoneNumberWithStringValue(handle));
}
var handleContactsCache={};
function resolveHandle(handle,access) {
  if(!handle || !access.readable) return [];
  var key='$'+handle;
  if(!Object.prototype.hasOwnProperty.call(handleContactsCache,key)) {
    try {handleContactsCache[key]=fetchContacts(contactPredicate(handle),false).map(function(c){return {id:c.id,name:c.name};});}
    catch(e){access.authorization='unavailable';access.readable=false;access.issue=String(e.message||e);return [];}
  }
  return handleContactsCache[key];
}
function normalizedHandle(value) {
  return value.indexOf('@')>=0?value.toLowerCase():value.replace(/[\s()+.\-]/g,'');
}
function contactSearch(p) {
  var access=contactsAccess();
  if(!access.readable && !(access.authorization==='not-determined' && p.requestAccess))
    throw new Error('CONTACTS_ACCESS_REQUIRED: '+access.issue+' Use contacts({query,requestAccess:true}) to request initial access.');
  // On macOS the first contact-store fetch requests consent. Never do this during ordinary message reads.
  var predicate=p.handle?contactPredicate(p.handle):$.CNContact.predicateForContactsMatchingName(p.query);
  var all=fetchContacts(predicate,true), seen={};
  all=all.filter(function(c){if(seen[c.id])return false;seen[c.id]=true;return true;});
  return {contacts:all.slice(0,p.limit),hasMore:all.length>p.limit,ambiguous:all.length>1,contactLookup:contactsAccess()};
}
function enrichMessages(page) {
  var access=contactsAccess();
  page.messages.forEach(function(m){
    m.senderContacts=m.isFromMe?[]:resolveHandle(m.sender,access);
    m.senderName=m.senderContacts.length===1?m.senderContacts[0].name:null;
    // Chat titles are preserved. Names are separate from addresses and are never used to choose a recipient.
  });
  page.contactLookup=access;
  return page;
}

function messageRow(row) {
  var decoded = row.text !== null && row.text !== '' ? {text:row.text, source:'plain'} : attributedText(row.bodyHex);
  var text = decoded.text;
  return {id:row.id,chatId:row.chatId,chatGuid:row.chatGuid,chatName:row.chatName,service:row.service,
    sender:row.sender,isFromMe:!!row.isFromMe,createdAt:row.createdAt,
    text:text.slice(0,8000),textTruncated:text.length>8000,textSource:decoded.source,
    attachmentCount:row.attachmentCount,searchTextTruncated:row.originalTextLength>65536,_fullText:text};
}
function messages(p) {
  var cols=columns('message');
  if(cols.indexOf('text')<0 || cols.indexOf('date')<0) throw new Error('UNSUPPORTED_MESSAGES_SCHEMA');
  var where=['1=1'];
  if(p.chatId) where.push('c.ROWID='+p.chatId);
  if(p.beforeMessageId) where.push('m.ROWID<'+p.beforeMessageId);
  if(p.after) where.push("(CASE WHEN abs(m.date)>1000000000000 THEN m.date/1000000000.0 ELSE m.date END)+978307200 >= "+(Date.parse(p.after)/1000));
  if(p.before) where.push("(CASE WHEN abs(m.date)>1000000000000 THEN m.date/1000000000.0 ELSE m.date END)+978307200 < "+(Date.parse(p.before)/1000));
  if(p.service) where.push('c.service_name='+sqlString(p.service));
  if(p.fromMe!==undefined) where.push('m.is_from_me='+(p.fromMe?1:0));
  var body=cols.indexOf('attributedBody')>=0 ? 'CASE WHEN length(m.attributedBody)<=65536 THEN hex(m.attributedBody) ELSE NULL END' : 'NULL';
  var rows=query('SELECT m.ROWID AS id,c.ROWID AS chatId,c.guid AS chatGuid,COALESCE(NULLIF(c.display_name,\'\'),c.chat_identifier) AS chatName,c.service_name AS service,h.id AS sender,m.is_from_me AS isFromMe,'+
    "strftime('%Y-%m-%dT%H:%M:%fZ',(CASE WHEN abs(m.date)>1000000000000 THEN m.date/1000000000.0 ELSE m.date END)+978307200,'unixepoch') AS createdAt,"+
    'substr(m.text,1,65536) AS text,length(m.text) AS originalTextLength,'+body+' AS bodyHex,(SELECT COUNT(*) FROM message_attachment_join a WHERE a.message_id=m.ROWID) AS attachmentCount '+
    'FROM message m JOIN chat_message_join cm ON cm.message_id=m.ROWID JOIN chat c ON c.ROWID=cm.chat_id LEFT JOIN handle h ON h.ROWID=m.handle_id '+
    'WHERE '+where.join(' AND ')+' GROUP BY m.ROWID ORDER BY m.ROWID DESC LIMIT '+(p.scanLimit+1));
  var result=[], scanned=0, unreadable=0, truncated=0, last=null;
  var needle=p.query && p.query.toLowerCase();
  for(var i=0;i<Math.min(rows.length,p.scanLimit);i++){
    var row=messageRow(rows[i]); scanned++; last=row.id;
    if(row.textSource==='unavailable') unreadable++;
    if(row.searchTextTruncated) truncated++;
    var match=!needle || row._fullText.toLowerCase().indexOf(needle)>=0;
    delete row._fullText;
    if(match) result.push(row);
    if(result.length>=p.limit) break;
  }
  var hasMore=scanned<rows.length;
  return {messages:result,scanned:scanned,unreadableTextRows:unreadable,searchTruncatedRows:truncated,hasMore:hasMore,nextBeforeMessageId:hasMore?last:null,order:'newest-stored-first'};
}
function nativeMain(p) {
 var sendStarted=false;
 try {
  if(p.action==='status'){
    var exists=$.NSFileManager.defaultManager.fileExistsAtPath(database());
    var info={contacts:contactsAccess(),platform:'macOS',osVersion:ObjC.unwrap($.NSProcessInfo.processInfo.operatingSystemVersionString),databaseExists:!!exists,readable:false,extraSoftwareRequired:false};
    if(!exists) {info.issue='Open Messages and sign in on this Mac. If already signed in, grant Full Disk Access to Kody Desktop (or the daemon host) and restart it.'; return {ok:true,result:info};}
    try {query('SELECT 1 FROM message LIMIT 1'); info.readable=true;}catch(e){info.issue=String(e.message||e);}
    return {ok:true,result:info};
  }
  if(p.action==='contacts') return {ok:true,result:contactSearch(p)};
  if(p.action==='conversations'){
    var where=p.service?' WHERE c.service_name='+sqlString(p.service):'';
    if(p.participant) where+=(where?' AND ':' WHERE ')+"EXISTS (SELECT 1 FROM chat_handle_join ph JOIN handle h ON h.ROWID=ph.handle_id WHERE ph.chat_id=c.ROWID AND (CASE WHEN instr(h.id,'@')>0 THEN lower(h.id) ELSE replace(replace(replace(replace(replace(replace(h.id,' ',''),'+',''),'(',''),')',''),'-',''),'.','') END)="+sqlString(normalizedHandle(p.participant))+')';
    if(p.beforeChatId) where+=(where?' AND ':' WHERE ')+'c.ROWID<'+p.beforeChatId;
    var rows=query('SELECT c.ROWID AS id,c.guid AS guid,c.chat_identifier AS identifier,COALESCE(NULLIF(c.display_name,\'\'),c.chat_identifier) AS name,c.service_name AS service,'+
      '(SELECT group_concat(h.id,char(31)) FROM chat_handle_join ch JOIN handle h ON h.ROWID=ch.handle_id WHERE ch.chat_id=c.ROWID) AS handles FROM chat c'+where+' ORDER BY c.ROWID DESC LIMIT '+(p.limit+1));
    var more=rows.length>p.limit;rows=rows.slice(0,p.limit);
    var access=contactsAccess();
    rows.forEach(function(r){r.participants=r.handles?r.handles.split(String.fromCharCode(31)):[];delete r.handles;r.participantContacts=r.participants.map(function(h){return {handle:h,contacts:resolveHandle(h,access)};});r.contactName=r.participantContacts.length===1&&r.participantContacts[0].contacts.length===1?r.participantContacts[0].contacts[0].name:null;});
    return {ok:true,result:{contactLookup:access,conversations:rows,hasMore:more,nextBeforeChatId:more?rows[rows.length-1].id:null,order:'newest-created-first'}};
  }
  if(p.action==='messages'||p.action==='search') return {ok:true,result:enrichMessages(messages(p))};
  if(p.action==='send'){
    // Readability is required before any send so an accepted send can be checked.
    var before=query('SELECT COALESCE(MAX(ROWID),0) AS id FROM message')[0].id;
    var target=p.recipient;
    var service=p.service||'iMessage';
    var chat=null;
    if(p.chatId){
      chat=query('SELECT guid,service_name FROM chat WHERE ROWID='+p.chatId)[0];
      if(!chat || chat.service_name!==service || !chat.guid) throw new Error('Choose an existing conversation whose service matches the reviewed draft (iMessage, SMS, or RCS).');
      target=chat.guid;
    }
    var script=p.chatId?
      'on run argv\ntell application "Messages"\nsend (item 2 of argv) to chat id (item 1 of argv)\nend tell\nend run':
      'on run argv\ntell application "Messages"\nset imService to first service whose service type is iMessage\nset destination to buddy (item 1 of argv) of imService\nsend (item 2 of argv) to destination\nend tell\nend run';
    var sent;
    try { sendStarted=true; sent=task('/usr/bin/osascript',['-e',script,target,p.text]); }
    catch(e){return {ok:true,result:{status:'uncertain',retrySafe:false,issue:'Messages automation did not return a reliable result. Inspect Messages before sending again.'}};}
    if(sent.code!==0) return {ok:true,result:{status:'uncertain',retrySafe:false,issue:/1743|not authorized|not permitted/i.test(sent.stderr)?'Allow the app running the daemon to control Messages in System Settings > Privacy & Security > Automation. Check Messages before retrying.':'Messages automation reported an error. Inspect the conversation before retrying.'}};
    // AppleScript acceptance is not a remote delivery receipt. Check for a new local row.
    var found=[];
    for(var attempt=0;attempt<8;attempt++){
      var condition=p.chatId?'cm.chat_id='+p.chatId:'h.id='+sqlString(p.recipient);
      found=query('SELECT DISTINCT m.ROWID AS id,m.guid AS guid,cm.chat_id AS chatId FROM message m JOIN chat_message_join cm ON cm.message_id=m.ROWID JOIN chat c ON c.ROWID=cm.chat_id LEFT JOIN handle h ON h.ROWID=m.handle_id WHERE m.ROWID>'+before+' AND m.is_from_me=1 AND c.service_name='+sqlString(service)+' AND '+condition+' ORDER BY m.ROWID DESC LIMIT 10');
      var confirmed=found.filter(function(r){var page=messages({chatId:r.chatId,beforeMessageId:r.id+1,limit:1,scanLimit:1});return page.messages[0] && page.messages[0].id===r.id && page.messages[0].text===p.text;});
      if(confirmed.length===1) return {ok:true,result:{status:'recorded',retrySafe:false,messageId:confirmed[0].id,messageGuid:confirmed[0].guid,chatId:confirmed[0].chatId,service:service,remoteDeliveryConfirmed:false}};
      if(confirmed.length>1) break;
      $.NSThread.sleepForTimeInterval(1);
    }
    return {ok:true,result:{status:'uncertain',retrySafe:false,issue:'Messages accepted the request, but a unique outgoing database row was not confirmed. Inspect Messages before sending again.'}};
  }
  throw new Error('Unknown native action.');
 }catch(e){if(sendStarted)return {ok:true,result:{status:'uncertain',retrySafe:false,issue:'The send could not be verified. Inspect Messages before sending again.'}};return {ok:false,error:String(e.message||e)};}
}
`;