import { execFile } from 'node:child_process'; import { mkdtemp, readFile, rm, stat, writeFile } from 'node:fs/promises'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { fileURLToPath } from 'node:url'; import { promisify } from 'node:util'; import { setTimeout as delay } from 'node:timers/promises'; // Only messages we author may be printed in full. SDK errors can include // addresses, paths, or message content. export class BridgeError extends Error {} class HeicConversionError extends Error {} // Filter the sender and conversation before fetching any attachment. export async function incomingMessage(client, event, chatGuid, recipient) { if ( event.type !== 'message.received' || event.chatGuid?.toLowerCase() !== chatGuid.toLowerCase() || event.isFromMe !== false ) { return null; } const message = event.message; if ( message.isFromMe !== false || message.itemType !== 'normal' || message.isSystemMessage || message.isServiceMessage || message.reaction || message.sender?.service !== 'iMessage' || message.sender.address?.toLowerCase() !== recipient.toLowerCase() || !message.guid ) { return null; } let content = message.content; const notes = []; if (content?.text?.includes('\uFFFC') && !content.attachments?.length) { // A replay can contain Apple's attachment placeholder without its metadata. try { const stored = await client.messages.get(message.guid); if ( stored.guid === message.guid && !stored.isFromMe && stored.sender?.address?.toLowerCase() === recipient.toLowerCase() && stored.chatGuids?.some( (guid) => guid.toLowerCase() === chatGuid.toLowerCase(), ) ) { content = stored.content; } } catch { // Preserve the caption and continue replay even if the attachment expired. } if (!content?.attachments?.length) notes.push('[An attachment was unavailable.]'); } const attachments = (content?.attachments ?? []).filter( (item) => item.guid && !item.isHidden && !item.isSticker && !item.isOutgoing, ); const caption = content?.text?.replaceAll('\uFFFC', '') ?? ''; if (!caption.trim() && !attachments.length && !notes.length) return null; const images = []; let remaining = 10 * 1024 * 1024; for (const item of attachments.slice(0, 8)) { const unknownType = process.platform === 'linux' && (!item.mimeType || item.mimeType === 'application/octet-stream'); if ( (unknownType && /\.(mov|mp4|m4v)$/i.test(item.fileName)) || (!unknownType && !/^image\//i.test(item.mimeType) && !/\.(jpe?g|png|webp|heic|heif)$/i.test(item.fileName)) ) { notes.push('[Non-image attachment omitted.]'); continue; } try { const ready = await transferred(client, item); const bytes = await downloadPhoto(client, ready, remaining, unknownType); if (!bytes) { notes.push('[Non-image attachment omitted.]'); continue; } images.push(bytes.toString('base64')); remaining -= bytes.length; } catch (error) { notes.push( error instanceof HeicConversionError ? '[Could not convert this HEIC photo. Please resend it as JPEG or PNG.]' : '[An image attachment could not be loaded.]', ); } } if (attachments.length > 8) notes.push('[Additional attachments omitted.]'); return { guid: message.guid, text: [caption, ...notes].filter(Boolean).join('\n'), images, }; } const modelImageLimit = 5 * 1024 * 1024; const downloadLimit = 25 * 1024 * 1024; const transferWaitMs = 30_000; const transferPollMs = 500; const run = promisify(execFile); // A transfer still in flight has no bytes to fetch. Admission advances the // daemon's checkpoint, so downloading one now would turn a temporary state // into a permanently missing photo. Wait for the transfer instead; only a // failed transfer is final. async function transferred(client, item) { let info = item; let state = info.transferState; const deadline = Date.now() + transferWaitMs; while (state === 'pending' || state === 'transferring') { if (Date.now() >= deadline) throw new BridgeError('Photo transfer did not finish'); await delay(transferPollMs); info = await client.attachments.get(item.guid); state = info.transferState; } if (state === 'failed') throw new BridgeError('Photo transfer failed'); return info; } function isSupportedImage(bytes) { return ( bytes.subarray(0, 3).equals(Buffer.from([0xff, 0xd8, 0xff])) || bytes.subarray(0, 8).equals(Buffer.from('89504e470d0a1a0a', 'hex')) || (bytes.toString('latin1', 0, 4) === 'RIFF' && bytes.toString('latin1', 8, 12) === 'WEBP') ); } // The file type box names a major brand and, after the version, compatible brands. function isHeif(bytes) { if (bytes.length < 16 || bytes.toString('latin1', 4, 8) !== 'ftyp') return false; const size = bytes.readUInt32BE(0); const header = size === 1 ? 16 : 8; if (bytes.length < header + 8) return false; const length = size === 1 ? bytes.readBigUInt64BE(8) : BigInt(size || bytes.length); if (length < BigInt(header + 8)) return false; const end = Math.min(Number(length), bytes.length, 4096); for (let offset = header; offset + 4 <= end; offset += 4) { if ( offset !== header + 4 && /^(heic|heix|hevc|hevx|heim|heis|hevm|hevs|mif1|msf1)$/.test( bytes.toString('latin1', offset, offset + 4), ) ) return true; } return false; } export function needsHeicConversion(item, bytes) { // A corrupt HEIC can lose its brand box. Keep the recovery note specific // when Photon supplied a HEIC label, even if the bytes are unreadable. const labeledHeic = /^image\/hei[cf]$/i.test(item.mimeType) || /\.hei[cf]$/i.test(item.fileName); return isHeif(bytes) || (labeledHeic && !isSupportedImage(bytes)); } async function downloadPhoto(client, item, remaining, unknownType) { const imageBudget = Math.min(remaining, modelImageLimit); if (imageBudget <= 0 || item.totalBytes > downloadLimit) throw new BridgeError('Photo too large'); const stream = client.attachments.downloadStream(item.guid); const timer = setTimeout(() => { void stream.close(); }, 15000); const chunks = []; let size = 0; try { for await (const frame of stream) { if (frame.type === 'companionChunk') break; // Live Photo motion track if (frame.type !== 'primaryChunk') continue; size += frame.data.byteLength; if (size > downloadLimit) throw new BridgeError('Photo too large'); chunks.push(frame.data); } } finally { clearTimeout(timer); await stream.close(); } if (!size) throw new BridgeError('Empty photo'); let bytes = Buffer.concat(chunks, size); const linuxHeic = process.platform === 'linux' && needsHeicConversion(item, bytes); if (unknownType && !linuxHeic && !isSupportedImage(bytes)) return null; // ImageIO handles the iPhone camera's HEIC format and orientation on macOS. if ( linuxHeic || (process.platform === 'darwin' && (item.mimeType !== 'image/png' || size > modelImageLimit || bytes.includes(Buffer.from('eXIf')))) ) { const dir = await mkdtemp(join(tmpdir(), 'albedo-photon-')); try { const src = join(dir, 'photo'); const dest = join(dir, 'photo.jpg'); await writeFile(src, bytes); if (linuxHeic) { const script = fileURLToPath( new URL('./normalize-heic.py', import.meta.url), ); await run('python3', ['-Es', script, src, dest], { timeout: 15000 }); } else { await run( '/usr/bin/osascript', [ '-l', 'JavaScript', fileURLToPath(new URL('./normalize-photo.js', import.meta.url)), src, dest, ], { timeout: 15000 }, ); } if ((await stat(dest)).size > imageBudget) throw new BridgeError('Photo too large'); bytes = await readFile(dest); } catch (error) { if (linuxHeic) throw new HeicConversionError(); throw error; } finally { await rm(dir, { recursive: true, force: true }); } } if (bytes.length > imageBudget) throw new BridgeError('Photo too large'); return bytes; } function validSequence(value) { return Number.isSafeInteger(value) && value >= 0; } // Each finite replay captures its own head. Only an acknowledged frame can // become the resume cursor, including the baseline from a new pairing. export async function replayBatch( client, { recipient, chatGuid, sequence, publish, idleTimeoutMs = 15000 }, ) { let previous = sequence; const stream = client.events.catchUp(sequence ?? undefined); const iterator = stream[Symbol.asyncIterator](); try { for (;;) { const timeout = new AbortController(); let next; try { next = await Promise.race([ iterator.next(), delay(idleTimeoutMs, undefined, { signal: timeout.signal }).then( () => { throw new BridgeError('Photon replay stopped making progress'); }, ), ]); } finally { timeout.abort(); } if (next.done) break; const event = next.value; if (event.type === 'catchup.complete') { if ( !validSequence(event.headSequence) || event.headSequence < (previous ?? 0) ) { throw new BridgeError('Invalid Photon replay head'); } if (sequence === null || previous !== event.headSequence) { await publish(event.headSequence, null); } return event.headSequence; } if ( !validSequence(event.sequence) || (previous !== null && event.sequence <= previous) ) { throw new BridgeError('Invalid Photon replay order'); } previous = event.sequence; if (sequence !== null) { await publish( event.sequence, await incomingMessage(client, event, chatGuid, recipient), ); } } throw new BridgeError('Photon replay ended before its checkpoint'); } finally { await stream.close?.(); await iterator.return?.(); } }