← Public packages
@tannerlinsley/imessage
Read, search, draft, and explicitly send iMessages on a Mac, using only built-in macOS tools.
Files
import { test } from "node:test";
import assert from "node:assert/strict";
import { registerHooks } from "node:module";
import { mkdtempSync, writeFileSync, readFileSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { pathToFileURL } from "node:url";
import { spawnSync } from "node:child_process";
import { nativeScript, draft, validateDraft } from "../src/core.ts";
import { nativeSource } from "../src/native.ts";
const root = mkdtempSync(join(tmpdir(), "imessage-tests-"));
const stub = join(root, "runtime.mjs");
writeFileSync(
stub,
`export const kody={command:new Proxy({}, {get:(_target,key)=>key==='run'?new Proxy(async p=>{globalThis.__hostCalls.push(p);return globalThis.__hostResult;},{get:()=>undefined}):undefined})};`,
);
registerHooks({
resolve(specifier, context, next) {
if (specifier === "kody:runtime") return { url: pathToFileURL(stub).href, shortCircuit: true };
return next(specifier, context);
},
});
const state = globalThis as any;
state.__hostCalls = [];
state.__hostResult = {
exitCode: 0,
stdout: JSON.stringify({
ok: true,
result: { status: "uncertain", retrySafe: false },
}),
};
const { default: send } = await import("../src/send.ts");
const { default: search } = await import("../src/search.ts");
const { default: history } = await import("../src/messages.ts");
const { default: conversations } = await import("../src/conversations.ts");
const { default: status } = await import("../src/index.ts");
const db = join(root, "chat.db");
const body = Buffer.from(
readFileSync(new URL("./body.b64", import.meta.url), "utf8"),
"base64",
).toString("hex");
const sql = `CREATE TABLE chat (guid TEXT, chat_identifier TEXT, display_name TEXT, service_name TEXT);
CREATE TABLE handle (id TEXT);
CREATE TABLE chat_handle_join (chat_id INTEGER,handle_id INTEGER);
CREATE TABLE message (guid TEXT,text TEXT,attributedBody BLOB,date INTEGER,is_from_me INTEGER,handle_id INTEGER);
CREATE TABLE chat_message_join (chat_id INTEGER,message_id INTEGER);
CREATE TABLE message_attachment_join (message_id INTEGER,attachment_id INTEGER);
INSERT INTO chat VALUES ('iMessage;-;fixture@example.invalid','fixture@example.invalid','Fixture','iMessage');
INSERT INTO chat VALUES ('SMS;-;+15555550100','+15555550100',NULL,'SMS');
INSERT INTO handle VALUES ('fixture@example.invalid'),('+15555550100');
INSERT INTO chat_handle_join VALUES(1,1),(2,2);
INSERT INTO message VALUES('a','Dinner tomorrow',NULL,700000000000000000,0,1);
INSERT INTO message VALUES('b','No match',NULL,700000001000000000,1,1);
INSERT INTO message VALUES('c',NULL,X'${body}',700000002000000000,0,1);
INSERT INTO message VALUES('d','DINNER tonight',NULL,700000003000000000,1,1);
INSERT INTO message VALUES('e',NULL,X'00ff',700000004000000000,0,1);
INSERT INTO chat_message_join VALUES (1,1),(1,2),(1,3),(1,4),(1,5);`;
const setup = spawnSync("/usr/bin/sqlite3", [db], {
input: sql,
encoding: "utf8",
});
assert.equal(setup.status, 0, setup.stderr);
function native(input: Record<string, unknown>, suffix = "") {
// Only tests replace the fixed Messages path. No database override is exposed by the package.
const script =
nativeSource +
`\nfunction database(){return ${JSON.stringify(db)};}\n` +
"\nfunction contactsAccess(){return {authorization:'denied',readable:false,issue:'Fixture permission denied'};}\n" +
suffix +
`\nfunction run(){return JSON.stringify(nativeMain(${JSON.stringify(input)}));}`;
const p = spawnSync("/usr/bin/osascript", ["-l", "JavaScript", "-"], {
input: script,
encoding: "utf8",
timeout: 15000,
maxBuffer: 4 * 1024 * 1024,
});
assert.equal(p.status, 0, p.stderr);
return JSON.parse(p.stdout.trim());
}
test("draft preserves exact text, rejects changed intent and ambiguous targets", async () => {
const d = await draft({
target: { recipient: "test@example.invalid" },
text: ' Exact "text" 🚀\n',
});
assert.equal(d.text, ' Exact "text" 🚀\n');
assert.deepEqual(await validateDraft(d), d);
await assert.rejects(validateDraft({ ...d, text: "changed" }), /draft changed/);
await assert.rejects(draft({ target: { recipient: "Alice" }, text: "hi" }), /exact E.164/);
await assert.rejects(
draft({
target: { recipient: "test@example.invalid", chatId: 1 },
text: "hi",
}),
/exactly one/,
);
await assert.rejects(draft({ target: { chatId: 1 }, text: "hi", send: true }), /Unknown/);
});
test("send defaults to a host-free preview and rejects guessed confirmation fields", async () => {
state.__hostCalls = [];
const d = await draft({
target: { chatId: 1 },
text: "Synthetic test, do not send",
});
assert.equal(((await send({ draft: d })) as any).dryRun, true);
assert.equal(((await send({ draft: d, confirmSend: false })) as any).sent, false);
await assert.rejects(send({ draft: d, confirmSend: "true" } as any), /boolean/);
await assert.rejects(send({ draft: d, send: true } as any), /Unknown/);
await assert.rejects(
send({ draft: { ...d, text: "changed" }, confirmSend: true }),
/draft changed/,
);
assert.equal(state.__hostCalls.length, 0);
});
test("confirmed send uses only the mock host and keeps payload off host arguments", async () => {
state.__hostCalls = [];
const d = await draft({
target: { recipient: "test@example.invalid" },
text: 'Synthetic "quote"\n$(touch /tmp/never)',
});
await send({ draft: d, confirmSend: true });
assert.equal(state.__hostCalls.length, 1);
const c = state.__hostCalls[0];
assert.deepEqual(c.args, ["-l", "JavaScript", "-"]);
assert.equal(c.file, "/usr/bin/osascript");
assert.ok(c.stdin.includes("Synthetic"));
assert.ok(!c.args.join(" ").includes("Synthetic"));
state.__hostResult = { exitCode: 0, stdout: "invalid" };
assert.equal(((await send({ draft: d, confirmSend: true })) as any).status, "uncertain");
state.__hostResult = { exitCode: 1, stdout: "" };
assert.equal(((await send({ draft: d, confirmSend: true })) as any).retrySafe, false);
});
test("read boundaries reject invalid IDs, extra keys, date ranges and limits", async () => {
await assert.rejects(history({ chatId: 0 }), /chatId/);
await assert.rejects(history({ chatId: 1, limit: 51 }), /limit/);
await assert.rejects(search({ query: "x", scanLimit: 201 }), /scanLimit/);
await assert.rejects(search({ query: "x", after: "2026-01-01" }), /timezone/);
await assert.rejects(
search({
query: "x",
after: "2026-02-01T00:00:00Z",
before: "2026-01-01T00:00:00Z",
}),
/earlier/,
);
await assert.rejects(search({ query: "x", fromMe: "false" } as any), /boolean/);
await assert.rejects(conversations({ service: 123 } as any), /service/);
await assert.rejects(status({ extra: true } as any), /Unknown/);
});
test("native status and conversations work on a synthetic SQLite database", () => {
assert.equal(native({ action: "status" }).result.readable, true);
const p = native({ action: "conversations", limit: 1 });
assert.equal(p.ok, true);
assert.equal(p.result.hasMore, true);
assert.equal(p.result.nextBeforeChatId, 2);
const q = native({ action: "conversations", limit: 20, beforeChatId: 2 });
assert.deepEqual(q.result.conversations[0].participants, ["fixture@example.invalid"]);
});
test("native reader decodes real Foundation archives and reports unsupported bodies", () => {
const p = native({ action: "messages", chatId: 1, limit: 10, scanLimit: 10 });
assert.equal(p.ok, true, JSON.stringify(p));
assert.equal(p.result.unreadableTextRows, 1);
assert.equal(
p.result.messages.find((x: any) => x.id === 3).text,
"Synthetic message ✓ hello 'quoted' 🚀",
);
assert.equal(p.result.messages.find((x: any) => x.id === 3).textSource, "attributed");
assert.equal(p.result.messages[0].textSource, "unavailable");
assert.ok(!JSON.stringify(p).includes("bodyHex"));
});
test("literal search paginates by scanned rows without skipping matches", () => {
const first = native({
action: "search",
query: "dinner",
limit: 1,
scanLimit: 5,
}).result;
assert.deepEqual(
first.messages.map((x: any) => x.id),
[4],
);
assert.equal(first.nextBeforeMessageId, 4);
const second = native({
action: "search",
query: "dinner",
limit: 1,
scanLimit: 5,
beforeMessageId: first.nextBeforeMessageId,
}).result;
assert.deepEqual(
second.messages.map((x: any) => x.id),
[1],
);
assert.equal(second.hasMore, false);
const capped = native({
action: "search",
query: "dinner",
limit: 10,
scanLimit: 1,
}).result;
assert.equal(capped.messages.length, 0);
assert.equal(capped.hasMore, true);
assert.equal(capped.nextBeforeMessageId, 5);
const quoted = native({
action: "search",
query: "' OR 1=1 --",
limit: 10,
scanLimit: 10,
}).result;
assert.equal(quoted.messages.length, 0);
const archived = native({
action: "search",
query: "quoted",
limit: 10,
scanLimit: 10,
}).result;
assert.equal(archived.messages[0].id, 3);
});
test("search respects date and direction filters", () => {
const page = native({
action: "search",
query: "dinner",
fromMe: true,
after: "2023-03-08T20:26:42Z",
limit: 10,
scanLimit: 10,
});
assert.equal(page.ok, true);
assert.deepEqual(
page.result.messages.map((x: any) => x.id),
[4],
);
});
test("send refuses service mismatch before automation, and automation errors are never retried", () => {
const refuse = native({ action: "send", chatId: 2, text: "Never send" });
assert.equal(refuse.ok, false);
assert.match(refuse.error, /service matches/);
// This task replacement refuses any osascript execution. sqlite3 remains real against the fixture.
const suffix = `var realTask=task; var automationCalls=0; task=function(file,args){if(file==='/usr/bin/osascript'){automationCalls++;return {code:1,stdout:'',stderr:'not authorized -1743'};}return realTask(file,args);};`;
const fail = native(
{ action: "send", recipient: "test@example.invalid", text: "Never send" },
suffix,
);
assert.equal(fail.result.status, "uncertain");
assert.equal(fail.result.retrySafe, false);
const sms = native({ action: "send", chatId: 2, service: "SMS", text: "Never send" }, suffix);
assert.equal(sms.ok, true);
assert.equal(sms.result.status, "uncertain");
assert.match(sms.result.issue, /Automation/);
});
process.on("exit", () => rmSync(root, { recursive: true, force: true }));
test("SMS and RCS require an existing chat, and changing service invalidates a draft", async () => {
for (const service of ["SMS", "RCS"]) {
const d = await draft({
target: { chatId: 1 },
text: "Synthetic preview only",
service,
});
assert.equal(d.service, service);
assert.deepEqual(await validateDraft(d), d);
await assert.rejects(
draft({
target: { recipient: "test@example.invalid" },
text: "hi",
service,
}),
/existing chatId/,
);
await assert.rejects(validateDraft({ ...d, service: "iMessage" }), /draft changed/);
assert.equal(((await send({ draft: d, confirmSend: false })) as any).sent, false);
}
});
test("Contacts enrichment preserves raw addresses, handles ambiguity and caches per handle", () => {
const suffix = `
var fetchCount=0;
function contactsAccess(){return {authorization:'authorized',readable:true,issue:null};}
function fetchContacts(){fetchCount++;return [{id:'one',name:'Fixture Person'}];}
`;
const page = native({ action: "messages", chatId: 1, limit: 10, scanLimit: 10 }, suffix).result;
assert.equal(page.contactLookup.readable, true);
assert.equal(page.messages.find((m) => !m.isFromMe).senderName, "Fixture Person");
assert.equal(page.messages.find((m) => !m.isFromMe).sender, "fixture@example.invalid");
assert.equal(page.messages.find((m) => m.isFromMe).senderName, null);
const ambiguous = native(
{ action: "conversations", limit: 10 },
suffix +
`
function fetchContacts(){return [{id:'one',name:'Same Name'},{id:'two',name:'Same Name'}];}`,
).result;
assert.equal(ambiguous.conversations.find((c) => c.id === 1).contactName, null);
assert.equal(
ambiguous.conversations.find((c) => c.id === 1).participantContacts[0].contacts.length,
2,
);
const denied = native(
{ action: "messages", chatId: 1, limit: 10, scanLimit: 10 },
`function fetchContacts(){throw new Error('Must not fetch without permission');}`,
).result;
assert.equal(denied.contactLookup.authorization, "denied");
assert.equal(denied.messages[0].senderName, null);
});
test("Contacts queries report ambiguity and truncation, deny implicit prompts, and validate inputs", async () => {
const { default: contacts } = await import("../src/contacts.ts");
await assert.rejects(contacts({ query: "A", handle: "a@example.invalid" }), /exactly one/);
await assert.rejects(contacts({ query: "A", requestAccess: "yes" } as any), /boolean/);
await assert.rejects(contacts({ query: "A", limit: 51 }), /integer/);
const blocked = native(
{ action: "contacts", query: "Fixture", limit: 1, requestAccess: false },
`function fetchContacts(){throw new Error('Should not fetch');}`,
);
assert.equal(blocked.ok, false);
assert.match(blocked.error, /CONTACTS_ACCESS_REQUIRED/);
const found = native(
{ action: "contacts", query: "Fixture", limit: 1 },
`
function contactsAccess(){return {authorization:'authorized',readable:true,issue:null};}
function fetchContacts(){return [{id:'one',name:'Fixture',phoneNumbers:['+15555550100'],emailAddresses:[]},{id:'one',name:'Fixture'},{id:'two',name:'Fixture',phoneNumbers:[],emailAddresses:[]}];}
`,
).result;
assert.equal(found.contacts.length, 1);
assert.equal(found.ambiguous, true);
assert.equal(found.hasMore, true);
const broken = native(
{ action: "messages", chatId: 1, limit: 10, scanLimit: 10 },
`
function contactsAccess(){return {authorization:'authorized',readable:true,issue:null};}
function fetchContacts(){throw new Error('Contacts unavailable');}
`,
).result;
assert.equal(broken.messages.length, 5);
assert.equal(broken.contactLookup.authorization, "unavailable");
});
test("participant filtering matches exact normalized addresses without suffix or email-dot guesses", () => {
assert.equal(
native({ action: "conversations", participant: "FIXTURE@example.invalid", limit: 10 }).result
.conversations.length,
1,
);
assert.equal(
native({ action: "conversations", participant: "fix.ture@example.invalid", limit: 10 }).result
.conversations.length,
0,
);
assert.equal(
native({ action: "conversations", participant: "+1 (555) 555-0100", limit: 10 }).result
.conversations[0].id,
2,
);
assert.equal(
native({ action: "conversations", participant: "0100", limit: 10 }).result.conversations.length,
0,
);
});
test("the real Contacts bridge formats a synthetic contact without reading the contact store", () => {
const result = native(
{ action: "contacts", query: "Fixture", limit: 10 },
`
function contactsAccess(){return {authorization:'authorized',readable:true,issue:null};}
var fixture=$.CNMutableContact.alloc.init;
fixture.givenName='Fixture';fixture.familyName='Person';
fixture.phoneNumbers=$.NSArray.arrayWithObject($.CNLabeledValue.labeledValueWithLabelValue('mobile',$.CNPhoneNumber.phoneNumberWithStringValue('+15555550100')));
fixture.emailAddresses=$.NSArray.arrayWithObject($.CNLabeledValue.labeledValueWithLabelValue('home','fixture@example.invalid'));
contactStore={unifiedContactsMatchingPredicateKeysToFetchError:function(predicate,keys,error){return $.NSArray.arrayWithObject(fixture);}};
`,
);
assert.equal(result.ok, true, JSON.stringify(result));
assert.equal(result.result.contacts[0].name, "Fixture Person");
assert.deepEqual(result.result.contacts[0].phoneNumbers, ["+15555550100"]);
assert.deepEqual(result.result.contacts[0].emailAddresses, ["fixture@example.invalid"]);
});