diff --git a/CHANGELOG.md b/CHANGELOG.md index 2d1f0073..614743b8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,23 @@ Anything that changes what the dashboard, the admin or a widget can do gets a li (`package.json`, `server/package.json`, `ui/package.json`, `server/src/version.ts`) and is tagged `vX.Y.Z`. +## Unreleased + +### Added +- **Messages verification-code provider.** Adds the local, default-off provider for the companion + [Sietch Messages widget PR #16](https://github.com/fdussert/fremkit-sietch/pull/16); the widget + is not bundled here, and its trusted integration remains separate. When integrated, codes are + written as concealed, temporary, current-Mac-only pasteboard content. The provider schedules a + conditional clear after 60 seconds; if cleanup startup or execution fails, it attempts an + immediate conditional clear. If macOS refuses both cleanup attempts, the code may remain on the + pasteboard. A cleanup startup failure is returned as a generic copy failure; a later cleaner + failure is logged without exposing the code. + +### Fixed + +- **Messages 2FA now names a missing Full Disk Access grant.** A macOS denial used to surface as + a generic "could not be read"; the command now asks to enable Full Disk Access for Fremkit. + ## 0.5.0 — 2026-10-19 ### Added diff --git a/SECURITY.md b/SECURITY.md index 61d2eb71..a2929e61 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -436,9 +436,11 @@ the Dock badges, and supervises the server process. and the programs it runs (such as `fremkit-scan`) to the helper as their responsible app, so a file-access grant made to "Fremkit Helper" — Files and Folders, or Full Disk Access — is also the server's. -- **Full Disk Access is optional.** Only the disk map benefits from it: without it, the folders - macOS protects are shown as unreadable. With it, the helper, the server and every provider can - read every file of the account. Grant it only if you want those folders measured. +- **Full Disk Access is optional.** The disk map and the Messages 2FA provider can benefit from + it: without it, protected folders are shown as unreadable and Messages lookup fails. With it, + the helper, the server and every provider can read every file of the account. Grant it only if + you want those features, and leave the separate Messages 2FA privacy setting off unless you + want a built-in widget to read recent incoming messages after an explicit copy request. - **It is signed with a self-signed identity** created by `scripts/create-signing-identity.sh` ("Fremkit Helper Dev"), because macOS ties TCC grants to the signature: without a stable one you would re-approve the permissions after every build. @@ -465,7 +467,9 @@ These are real and not fixed. They are here so you can decide whether they matte [docs/connections.md](docs/connections.md#what-the-tls-does-and-does-not-prove). - **A same-user process is out of scope.** It can read your keychain, your config and your clipboard without going through Fremkit at all — and the access secret's token file, which is - readable by your account by design so the scripts can use it. + readable by your account by design so the scripts can use it. If macOS grants Full Disk Access + and you enable the separate Messages 2FA privacy setting, it can also ask Fremkit's local + command to copy a recent incoming verification code; that setting is off by default. - **The widgets' own files are served without the secret** (see above), so a page you visit can find out which widgets are installed, though not how they are set up or what they show. - **The registry is trusted to be curated, not to be safe.** An installed widget can do diff --git a/server/src/app.ts b/server/src/app.ts index b9ecc4f2..a8fbeff9 100644 --- a/server/src/app.ts +++ b/server/src/app.ts @@ -61,6 +61,7 @@ import { isSafeBackgroundName } from './config/schema.js' import { backupRoutes } from './backup/routes.js' import { bambuRoutes } from './bambu/routes.js' import { createShortcutsProvider } from './providers/shortcuts.js' +import { createMessages2FAProvider } from './providers/messages-2fa.js' import { createServiceStatusProvider } from './providers/service-status.js' import { createSystemProvider } from './providers/system.js' import { createDiskMapProvider } from './providers/disk-map.js' @@ -308,6 +309,7 @@ export async function buildApp(opts: AppOptions): Promise { registry.register(createDiskMapProvider({ dataDir: opts.dataDir })) // Registered here, not in providers/index.ts, because that is where the config store lives. registry.register(createShortcutsProvider(undefined, instances)) + registry.register(createMessages2FAProvider({ enabled: () => store.get().privacy.messages2FA })) registry.register(createServiceStatusProvider({}, instances)) // A paired device may set only its own screen's brightness: see mayCommandBrightness. Read // at command time, so a device moved to another screen (or unpaired) is judged as it is now. diff --git a/server/src/config/migrate.ts b/server/src/config/migrate.ts index bc052515..a34a35e0 100644 --- a/server/src/config/migrate.ts +++ b/server/src/config/migrate.ts @@ -192,7 +192,7 @@ function readV3(raw: unknown, version: unknown): V3Config { connections: [], secrets: { backend: defaultSecretsBackend() }, locale: defaultLocale(), - privacy: { claudeAccountUsage: false, showAccountEmail: false, codexAccount: false, codexHistorySources: [], macmonTemperature: false }, + privacy: { claudeAccountUsage: false, showAccountEmail: false, codexAccount: false, codexHistorySources: [], macmonTemperature: false, messages2FA: false }, // A v1 config predates the marketplace by a long way; nothing can have been installed. marketplace: { installed: {} }, pages: v1.pages.map((p) => ({ diff --git a/server/src/config/schema.ts b/server/src/config/schema.ts index c45bd0f5..05d31ddb 100644 --- a/server/src/config/schema.ts +++ b/server/src/config/schema.ts @@ -355,6 +355,8 @@ export const PrivacySchema = z.object({ codexHistorySources: z.array(HistorySourceSchema).max(10).default([]), /** Read CPU temperature from the optional local macmon executable. */ macmonTemperature: z.boolean().default(false), + /** Read recent Messages for a verification code only after a separate, explicit opt-in. */ + messages2FA: z.boolean().default(false), }).prefault({}) /** @@ -481,7 +483,7 @@ export const DEFAULT_CONFIG: Config = { connections: [], secrets: { backend: defaultSecretsBackend() }, locale: defaultLocale(), - privacy: { claudeAccountUsage: false, showAccountEmail: false, codexAccount: false, codexHistorySources: [], macmonTemperature: false }, + privacy: { claudeAccountUsage: false, showAccountEmail: false, codexAccount: false, codexHistorySources: [], macmonTemperature: false, messages2FA: false }, labs: { devices: false, companion: false }, marketplace: { installed: {} }, widgets: { diff --git a/server/src/demo/providers.ts b/server/src/demo/providers.ts index dd4521c3..2283d965 100644 --- a/server/src/demo/providers.ts +++ b/server/src/demo/providers.ts @@ -1,5 +1,6 @@ import { z } from 'zod' import type { Provider } from '../providers/types.js' +import { tr } from '../i18n.js' import type { Config } from '../config/schema.js' import { findInstance, type InstanceLookup } from '../config/instances.js' import { resolveServices, type ServiceResult } from '../providers/service-status.js' @@ -62,6 +63,7 @@ export function createDemoProviders(opts: DemoProviderOptions): Provider[] { { channel: 'cleanshot', commands: { run: ACTED } }, rtkProvider(now), { channel: 'shortcuts', commands: { open: ACTED } }, + { channel: 'messages-2fa', commands: { copyLatest: async () => ({ ok: false, error: tr(undefined, 'messages2fa.noneFound') }) } }, serviceStatusProvider(now, opts.instances ?? ((id) => findInstance(opts.config(), id))), ] } diff --git a/server/src/demo/seed.ts b/server/src/demo/seed.ts index e8f7cdca..abcae3ee 100644 --- a/server/src/demo/seed.ts +++ b/server/src/demo/seed.ts @@ -124,7 +124,7 @@ export function demoConfig(locale: 'fr' | 'en' = 'en'): Config { // A file next to the config, never the keychain: a demo has nothing to keep secret. secrets: { backend: 'file' }, locale, - privacy: { claudeAccountUsage: true, showAccountEmail: false, codexAccount: true, codexHistorySources: ['cli', 'vscode', 'appServer'], macmonTemperature: false }, + privacy: { claudeAccountUsage: true, showAccountEmail: false, codexAccount: true, codexHistorySources: ['cli', 'vscode', 'appServer'], macmonTemperature: false, messages2FA: false }, marketplace: { installed: {} }, // As on a fresh install: the iPad screens stay an experimental feature until it is ticked. labs: { devices: false, companion: false }, diff --git a/server/src/i18n.ts b/server/src/i18n.ts index af540130..3b1211c4 100644 --- a/server/src/i18n.ts +++ b/server/src/i18n.ts @@ -37,6 +37,14 @@ const fr = { // app.ts — the global request gate 'provider.invalidPayload': 'charge utile invalide', + 'messages2fa.disabled': 'activez la recherche de codes Messages dans les réglages de confidentialité', + 'messages2fa.localOnly': 'disponible uniquement depuis ce Mac', + 'messages2fa.invalidRequest': 'requête invalide', + 'messages2fa.rateLimited': 'attendez quelques secondes avant de rechercher un autre code', + 'messages2fa.readFailed': 'impossible de lire Messages', + 'messages2fa.permission': 'autorisez l’accès complet au disque pour Fremkit dans Réglages Système', + 'messages2fa.noneFound': 'aucun code de vérification récent trouvé', + 'messages2fa.copyFailed': 'impossible de copier le code', 'clipboard.unknownEntry': 'entrée inconnue', 'serviceStatus.invalidHost': 'hôte invalide', 'serviceStatus.invalidHostPort': 'hôte:port invalide', @@ -333,6 +341,14 @@ const en: Record = { 'config.degraded': 'configuration on disk is unreadable: fix data/fremkit.json then restart the server', 'provider.invalidPayload': 'invalid payload', + 'messages2fa.disabled': 'enable Messages code lookup in Privacy settings', + 'messages2fa.localOnly': 'available only from this Mac', + 'messages2fa.invalidRequest': 'invalid request', + 'messages2fa.rateLimited': 'wait a few seconds before looking up another code', + 'messages2fa.readFailed': 'Messages could not be read', + 'messages2fa.permission': 'grant Fremkit Full Disk Access in System Settings', + 'messages2fa.noneFound': 'no recent verification code found', + 'messages2fa.copyFailed': 'the code could not be copied', 'clipboard.unknownEntry': 'unknown entry', 'serviceStatus.invalidHost': 'invalid host', 'serviceStatus.invalidHostPort': 'invalid host:port', diff --git a/server/src/providers/messages-2fa.ts b/server/src/providers/messages-2fa.ts new file mode 100644 index 00000000..fb3e1dca --- /dev/null +++ b/server/src/providers/messages-2fa.ts @@ -0,0 +1,319 @@ +import { execFile, spawn, type ChildProcess } from 'node:child_process' +import { homedir } from 'node:os' +import { join } from 'node:path' +import { z } from 'zod' +import type { CommandContext, Provider } from './types.js' +import type { Pasteboard } from './clipboard.js' +import { tr } from '../i18n.js' + +const MESSAGES_DB = join(homedir(), 'Library', 'Messages', 'chat.db') +const APPLE_EPOCH_MS = 978_307_200_000 +const WINDOW_MS = 5 * 60_000 +const QUERY_LIMIT = 100 +const COMMAND_TIMEOUT_MS = 2_500 +// 100 rows can contain either 4 KiB of JSON-escaped text or 4 KiB of hex BLOB data. +// Keep the whole result bounded while allowing the full recent-message window through. +const MAX_QUERY_OUTPUT_BYTES = 3 * 1024 * 1024 +const CODE_LENGTH = /^\d{4,8}$/ +const MAX_ATTRIBUTED_BODY_BYTES = 4_096 +const REQUEST_COOLDOWN_MS = 5_000 +const RequestSchema = z.null() + +// The code enters osascript only on stdin; the source is constant and no widget value is in argv. +// AppKit marks it concealed/transient and limits Universal Clipboard to this Mac. It prints only +// the pasteboard change count so a detached cleanup process can clear the code after one minute. +const WRITE_CODE_SCRIPT = `ObjC.import('AppKit'); +ObjC.import('Foundation'); +const data = $.NSFileHandle.fileHandleWithStandardInput.readDataToEndOfFile; +const value = $.NSString.alloc.initWithDataEncoding(data, $.NSUTF8StringEncoding); +if (!value) throw new Error('invalid input'); +const board = $.NSPasteboard.generalPasteboard; +const ownedChangeCount = Number(board.prepareForNewContentsWithOptions($.NSPasteboardContentsCurrentHostOnly)); +if (!Number.isSafeInteger(ownedChangeCount)) throw new Error('pasteboard write failed'); +if (!board.setStringForType(value, $.NSPasteboardTypeString)) throw new Error('pasteboard write failed'); +if (!board.setDataForType($.NSData.data, 'org.nspasteboard.ConcealedType')) throw new Error('pasteboard write failed'); +if (!board.setDataForType($.NSData.data, 'org.nspasteboard.TransientType')) throw new Error('pasteboard write failed'); +if (Number(board.changeCount) !== ownedChangeCount) throw new Error('pasteboard write failed'); +String(ownedChangeCount);` + +const CLEAR_CODE_SCRIPT = `ObjC.import('AppKit'); +ObjC.import('Foundation'); +const args = $.NSProcessInfo.processInfo.arguments; +const expected = Number(ObjC.unwrap(args.lastObject)); +$.NSThread.sleepForTimeInterval(60); +const board = $.NSPasteboard.generalPasteboard; +if (Number(board.changeCount) === expected) board.clearContents();` + +type ScriptExecutor = (script: string, args: string[], stdin?: string) => Promise +type CleanupSpawner = (changeCount: number) => ChildProcess + +const executeAppleScript: ScriptExecutor = (script, args, stdin) => new Promise((resolve, reject) => { + const child = execFile('osascript', ['-l', 'JavaScript', '-e', script, ...args], { + timeout: COMMAND_TIMEOUT_MS, + maxBuffer: 1024, + shell: false, + }, (error, stdout) => { + if (error) reject(new Error('pasteboard operation failed')) + else resolve(stdout) + }) + if (stdin !== undefined) child.stdin?.end(stdin) +}) + +const spawnCleanup: CleanupSpawner = (changeCount) => spawn('osascript', [ + '-l', 'JavaScript', '-e', CLEAR_CODE_SCRIPT, String(changeCount), +], { detached: true, stdio: 'ignore' }) + +function reportCleanupFailure(): void { + console.error('Messages code pasteboard cleanup failed.') +} + +export function createMessagePasteboardWriter( + dependencies: { executeScript?: ScriptExecutor; spawnCleanup?: CleanupSpawner } = {}, +): Pick { + const runScript = dependencies.executeScript ?? executeAppleScript + const startCleanup = dependencies.spawnCleanup ?? spawnCleanup + const clearIfUnchanged = async (changeCount: number): Promise => { + await runScript(CLEAR_IF_UNCHANGED_SCRIPT, [String(changeCount)]) + } + + return { + write: async (text) => { + const stdout = await runScript(WRITE_CODE_SCRIPT, [], text) + const changeCount = Number(stdout.trim()) + if (!Number.isSafeInteger(changeCount)) throw new Error('pasteboard write failed') + + try { + const cleanup = startCleanup(changeCount) + await new Promise((resolve, reject) => { + let started = false + cleanup.once('error', (error) => { + if (!started) reject(error) + else void clearIfUnchanged(changeCount).catch(reportCleanupFailure) + }) + cleanup.once('spawn', () => { + started = true + cleanup.unref() + resolve() + }) + cleanup.once('exit', (code) => { + if (code !== 0) void clearIfUnchanged(changeCount).catch(reportCleanupFailure) + }) + }) + } catch { + try { await clearIfUnchanged(changeCount) } + catch { reportCleanupFailure() } + throw new Error('pasteboard cleanup could not be started') + } + }, + } +} + +const CLEAR_IF_UNCHANGED_SCRIPT = `ObjC.import('AppKit'); +ObjC.import('Foundation'); +const args = $.NSProcessInfo.processInfo.arguments; +const expected = Number(ObjC.unwrap(args.lastObject)); +const board = $.NSPasteboard.generalPasteboard; +if (Number(board.changeCount) === expected) board.clearContents();` + +const messagePasteboard: Pick = createMessagePasteboardWriter() + +interface MessageRow { + text?: string + attributedHex?: string + date?: number | string +} + +type Run = (file: string, args: string[]) => Promise + +interface Messages2FAOptions { + databasePath?: string + now?: () => number + run?: Run + pasteboard?: Pick + enabled?: () => boolean +} + +const PERMISSION_DENIED = /authorization denied|operation not permitted/i + +const defaultRun: Run = (file, args) => new Promise((resolve, reject) => { + execFile(file, args, { timeout: COMMAND_TIMEOUT_MS, maxBuffer: MAX_QUERY_OUTPUT_BYTES, shell: false }, (error, stdout, stderr) => { + if (error) { + reject(new Error(PERMISSION_DENIED.test(`${stderr}\n${error.message}`) ? 'permission-denied' : 'read-failed')) + } else resolve(stdout) + }) +}) + +function timestampBounds(now: number): { appleSeconds: number; appleNanoseconds: number } { + const cutoff = now - WINDOW_MS - APPLE_EPOCH_MS + return { appleSeconds: Math.floor(cutoff / 1000), appleNanoseconds: Math.floor(cutoff * 1_000_000) } +} + +function appleDateToUnixMs(value: unknown): number | undefined { + const date = typeof value === 'number' ? value : typeof value === 'string' ? Number(value) : NaN + if (!Number.isFinite(date) || date <= 0) return undefined + const unixMs = date > 1_000_000_000_000 + ? date / 1_000_000 + APPLE_EPOCH_MS + : date * 1000 + APPLE_EPOCH_MS + return Number.isFinite(unixMs) ? unixMs : undefined +} + +function normalize(text: string): string { + return text.normalize('NFD').replace(/\p{Diacritic}/gu, '').toLowerCase() +} + +function hasVerificationContext(text: string, start: number, end: number): boolean { + const segmentStart = Math.max(text.lastIndexOf('.', start), text.lastIndexOf('!', start), text.lastIndexOf('?', start), text.lastIndexOf('\n', start), text.lastIndexOf('…', start)) + 1 + const boundaries = [text.indexOf('.', end), text.indexOf('!', end), text.indexOf('?', end), text.indexOf('\n', end), text.indexOf('…', end)].filter((i) => i >= 0) + const segmentEnd = boundaries.length ? Math.min(...boundaries) : text.length + const segment = normalize(text.slice(segmentStart, segmentEnd)) + const codeOffset = normalize(text.slice(segmentStart, start)).length + const beforeCode = segment.slice(0, codeOffset) + const context = segment + if (/(?:account\s+)?(?:ending|ends?\s+in|ending\s+with|last\s+digits?|se\s+termine\s+par)\s*\S{0,18}$/i.test(beforeCode)) return false + if (/\b\d{1,4}[/-]\d{1,2}[/-]\d{1,4}\b|\b\d{4}-\d{2}-\d{2}\b/.test(context)) { + const dates = [...context.matchAll(/\b\d{1,4}[/-]\d{1,2}[/-]\d{1,4}\b|\b\d{4}-\d{2}-\d{2}\b/g)] + if (dates.some((date) => date.index !== undefined && codeOffset >= date.index && codeOffset < date.index + date[0].length)) return false + } + const codeMarker = /\b(?:passcode|otp)\b|\byour\s+code\b|\bcode\s+is\s+your\b|\b(?:verification|security|authentication|authenticator|one[ -]?time)\s+code\b|\bcode\s+(?:de\s+)?(?:verification|security|connexion|securite|acces|confirmation)\b|\bcode\b.{0,18}\b(?:is|est)\b/ + return codeMarker.test(context) +} + +function verificationCode(text: string): string | undefined { + const pattern = /(? MAX_ATTRIBUTED_BODY_BYTES * 2 || hex.length % 2 !== 0 || !/^[0-9a-f]+$/i.test(hex)) return undefined + const bytes = Buffer.from(hex, 'hex') + const isTypedstream = bytes.length >= 13 && bytes[0] === 4 && bytes[1] === 11 && bytes.subarray(2, 13).toString('ascii') === 'streamtyped' + if (!isTypedstream) { + // Keep compatibility with older/test databases that stored plain UTF-8 in attributedBody; + // reject binary/control-heavy payloads rather than heuristically scraping them. + try { + const plain = new TextDecoder('utf-8', { fatal: true }).decode(bytes) + return plain && !/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/.test(plain) ? plain : undefined + } catch { + return undefined + } + } + + // Messages stores NSAttributedString bodies as NSArchiver typedstreams. The actual plaintext + // is the unshared NSString value immediately following its class declaration. Parse its + // length prefix as bytes; decoding the whole archive as SQLite TEXT stops at embedded NULs. + const stringClass = Buffer.from('NSString', 'ascii') + const classIndex = bytes.indexOf(stringClass, 13) + if (classIndex < 0) return undefined + const classEnd = classIndex + stringClass.length + const markerIndex = bytes.indexOf(0x2b, classEnd) + if (markerIndex < classEnd || markerIndex - classEnd > 32) return undefined + + let cursor = markerIndex + 1 + const tag = bytes[cursor++] + let length: number + if (tag <= 0x7f) length = tag + else if (tag === 0x81 && cursor + 2 <= bytes.length) { + length = bytes.readUInt16LE(cursor) + cursor += 2 + } else if (tag === 0x82 && cursor + 4 <= bytes.length) { + length = bytes.readUInt32LE(cursor) + cursor += 4 + } else if (tag === 0x83 && cursor + 8 <= bytes.length) { + const longLength = bytes.readBigUInt64LE(cursor) + if (longLength > BigInt(MAX_ATTRIBUTED_BODY_BYTES)) return undefined + length = Number(longLength) + cursor += 8 + } else return undefined + + if (length <= 0 || length > MAX_ATTRIBUTED_BODY_BYTES || cursor + length > bytes.length) return undefined + try { + return new TextDecoder('utf-8', { fatal: true }).decode(bytes.subarray(cursor, cursor + length)) + } catch { + return undefined + } +} + +async function latestVerificationCode( + databasePath: string, + now: number, + run: Run, +): Promise { + const bounds = timestampBounds(now) + const query = `SELECT coalesce(m.text, '') AS text, + CASE WHEN m.text IS NULL OR m.text = '' THEN coalesce(hex(m.attributedBody), '') ELSE '' END AS attributedHex, + m.date FROM message AS m + WHERE m.is_from_me = 0 AND (m.text IS NOT NULL OR m.attributedBody IS NOT NULL) + AND length(coalesce(m.text, '')) <= 4096 + AND (m.attributedBody IS NULL OR length(m.attributedBody) <= ${MAX_ATTRIBUTED_BODY_BYTES}) + AND ((m.date > 1000000000000 AND m.date >= ${bounds.appleNanoseconds}) + OR (m.date <= 1000000000000 AND m.date >= ${bounds.appleSeconds})) + AND NOT EXISTS ( + SELECT 1 FROM chat_message_join AS cmj JOIN chat AS c ON c.ROWID = cmj.chat_id + WHERE cmj.message_id = m.ROWID AND c.style = 43 + ) + ORDER BY m.date DESC LIMIT ${QUERY_LIMIT};` + const stdout = await run('/usr/bin/sqlite3', [ + '-readonly', '-json', '-batch', + '-cmd', 'PRAGMA query_only=ON;', + '-cmd', '.timeout 1000', + databasePath, + query, + ]) + let rows: unknown + try { rows = JSON.parse(stdout || '[]') } catch { throw new Error('Messages could not be read.') } + const parsed = z.array(z.object({ text: z.string().max(4096), attributedHex: z.string().max(MAX_ATTRIBUTED_BODY_BYTES * 2), date: z.union([z.number(), z.string()]) })).safeParse(rows) + if (!parsed.success) throw new Error('Messages could not be read.') + + for (const row of parsed.data as MessageRow[]) { + const sentAt = appleDateToUnixMs(row.date) + if (sentAt === undefined || sentAt < now - WINDOW_MS || sentAt > now + 60_000) continue + const body = row.text || decodeTypedstreamAttributedBody(row.attributedHex ?? '') || '' + const code = verificationCode(body) + if (code) return code + } + return undefined +} + +/** Reads only recent incoming message text on an explicit local tap; never polls or logs content. */ +export function createMessages2FAProvider(options: Messages2FAOptions = {}): Provider { + const databasePath = options.databasePath ?? MESSAGES_DB + const now = options.now ?? Date.now + const run = options.run ?? defaultRun + const pasteboard = options.pasteboard ?? messagePasteboard + const enabled = options.enabled ?? (() => false) + let lastRequestAt: number | undefined + + return { + channel: 'messages-2fa', + commands: { + copyLatest: async (payload: unknown, context?: CommandContext) => { + if (context?.loopback !== true) return { ok: false, error: tr(undefined, 'messages2fa.localOnly') } + if (!enabled()) return { ok: false, error: tr(undefined, 'messages2fa.disabled') } + if (!RequestSchema.safeParse(payload).success) return { ok: false, error: tr(undefined, 'messages2fa.invalidRequest') } + const requestedAt = now() + if (lastRequestAt !== undefined && requestedAt - lastRequestAt < REQUEST_COOLDOWN_MS) { + return { ok: false, error: tr(undefined, 'messages2fa.rateLimited') } + } + lastRequestAt = requestedAt + let code: string | undefined + try { code = await latestVerificationCode(databasePath, requestedAt, run) } catch (error) { + const denied = error instanceof Error && error.message === 'permission-denied' + return { ok: false, error: tr(undefined, denied ? 'messages2fa.permission' : 'messages2fa.readFailed') } + } + if (!code) return { ok: false, error: tr(undefined, 'messages2fa.noneFound') } + try { await pasteboard.write(code) } catch { + return { ok: false, error: tr(undefined, 'messages2fa.copyFailed') } + } + // Keep the OTP on the local pasteboard only; never return it over the widget bridge. + return { ok: true } + }, + }, + } +} diff --git a/server/src/widgets/manifest.ts b/server/src/widgets/manifest.ts index 792c4306..7e14d98f 100644 --- a/server/src/widgets/manifest.ts +++ b/server/src/widgets/manifest.ts @@ -182,14 +182,14 @@ const ChannelSchema = z.string().min(1).refine((channel) => { * `widgets/`, which ships with the server and is reviewed with it. Unlike `RESERVED_CHANNELS`, the * schema alone cannot say: it does not know where a manifest came from. */ -export const BUILTIN_ONLY_CHANNELS: ReadonlySet = new Set(['disk-map', 'clipboard', 'companion']) +export const BUILTIN_ONLY_CHANNELS: ReadonlySet = new Set(['disk-map', 'clipboard', 'companion', 'messages-2fa']) /** * Channels any widget may read but only a built-in one may command. `brightness` changes the * screen itself: a registry widget may show the level, and the built-in widget, the admin and * the helper are what set it. Refused in an installed manifest's `commands`, like the above. */ -export const BUILTIN_ONLY_COMMANDS: ReadonlySet = new Set(['brightness']) +export const BUILTIN_ONLY_COMMANDS: ReadonlySet = new Set(['brightness', 'messages-2fa']) /** * Whether a list of `commands` covers a channel: the literal name, or a `type:*` entry for one diff --git a/server/test/config-migration.test.ts b/server/test/config-migration.test.ts index 89e52fb7..222ee116 100644 --- a/server/test/config-migration.test.ts +++ b/server/test/config-migration.test.ts @@ -183,6 +183,13 @@ describe('privacy settings on an older config', () => { it('starts off for a config that does not show the widget', () => { const cfg = migrateConfig({ version: 2, pages: [page([widget('clock')])] }) expect(cfg.privacy.claudeAccountUsage).toBe(false) + expect(cfg.privacy.messages2FA).toBe(false) + }) + + it('keeps the Messages lookup opt-in off for existing configs unless they carry the setting', () => { + expect(migrateConfig({ ...DEFAULT_CONFIG, privacy: { ...DEFAULT_CONFIG.privacy, messages2FA: true } }).privacy.messages2FA).toBe(true) + expect(migrateConfig({ ...DEFAULT_CONFIG, privacy: { ...DEFAULT_CONFIG.privacy, messages2FA: false } }).privacy.messages2FA).toBe(false) + expect(migrateConfig({ ...DEFAULT_CONFIG, privacy: { claudeAccountUsage: false } }).privacy.messages2FA).toBe(false) }) it('starts on for a config that already shows it on a page', () => { diff --git a/server/test/demo.test.ts b/server/test/demo.test.ts index 0874f917..b83d90a9 100644 --- a/server/test/demo.test.ts +++ b/server/test/demo.test.ts @@ -126,6 +126,9 @@ describe('demo mode', () => { const volume = providers.find((p) => p.channel === 'volume')! await volume.commands!.set({ level: 12 }) expect(((await volume.poll!()) as { level: number }).level).toBe(12) + const messages2FA = providers.find((p) => p.channel === 'messages-2fa')! + await expect(messages2FA.commands!.copyLatest(null, { loopback: true, paired: false })) + .resolves.toMatchObject({ ok: false }) const status = providers.find((p) => p.channel === 'service-status')! const probe = await status.commands!.probe({ instanceId: 'service-status-1' }) as { ok: boolean; results: unknown[] } expect(probe.ok).toBe(true) diff --git a/server/test/messages-2fa.test.ts b/server/test/messages-2fa.test.ts new file mode 100644 index 00000000..ebb87fd0 --- /dev/null +++ b/server/test/messages-2fa.test.ts @@ -0,0 +1,375 @@ +import { execFileSync } from 'node:child_process' +import { EventEmitter } from 'node:events' +import { mkdtemp, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { runInNewContext } from 'node:vm' +import { afterEach, describe, expect, it, vi } from 'vitest' +import { createMessagePasteboardWriter, createMessages2FAProvider } from '../src/providers/messages-2fa.js' +import { tr } from '../src/i18n.js' + +const dirs: string[] = [] +const APPLE_EPOCH_MS = 978_307_200_000 +const LONG_TYPEDSTREAM_VERIFIED = 'BAtzdHJlYW10eXBlZIHoA4QBQISEhBJOU0F0dHJpYnV0ZWRTdHJpbmcAhIQITlNPYmplY3QAhZKEhIQITlNTdHJpbmcBlIQBK4GjAFlvdXIgdmVyaWZpY2F0aW9uIGNvZGUgaXMgNDgzOTIxIEFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUGGhAJpSQGBowCShISEDE5TRGljdGlvbmFyeQCUhAFpAIaG' +const LONG_TYPEDSTREAM_FIXTURE = 'BAtzdHJlYW10eXBlZIHoA4QBQISEhBJOU0F0dHJpYnV0ZWRTdHJpbmcAhIQITlNPYmplY3QAhZKEhIQITlNTdHJpbmcBlIQBK4GjAFlvdXIgdmVyaWZpY2F0aW9uIGNvZGUgaXMgNDgzOTIxIEFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUGGhAJpSQGBowCShISEDE5TRGljdGlvbmFyeQCUhAFpAIaG' +// Synthetic Foundation NSArchiver/typedstream archive of an attributed string. Keeping this +// fixture local and synthetic exercises the same BLOB shape used by Messages without reading +// or retaining any user's chat database content. +const ATTRIBUTED_TYPEDSTREAM_BASE64 = 'BAtzdHJlYW10eXBlZIHoA4QBQISEhBJOU0F0dHJpYnV0ZWRTdHJpbmcAhIQITlNPYmplY3QAhZKEhIQITlNTdHJpbmcBlIQBKyBZb3VyIHZlcmlmaWNhdGlvbiBjb2RlIGlzIDQ4MzkyMYaEAmlJASCShISEDE5TRGljdGlvbmFyeQCUhAFpAZKElpYQZXhhbXBsZUF0dHJpYnV0ZYaShJaWCXN5bnRoZXRpY4aGhg==' +const LONG_ATTRIBUTED_TYPEDSTREAM_BASE64 = 'BAtzdHJlYW10eXBlZIHoA4QBQISEhBJOU0F0dHJpYnV0ZWRTdHJpbmcAhIQITlNPYmplY3QAhZKEhIQITlNTdHJpbmcBlIQBK4GjAEFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUEgWW91ciB2ZXJpZmljYXRpb24gY29kZSBpcyA0ODM5MjGGhAJpSQGBowCShISEDE5TRGljdGlvbmFyeQCUhAFpAIaG' + +async function fixtureDatabase(sql: string): Promise { + const dir = await mkdtemp(join(tmpdir(), 'fremkit-messages-2fa-')) + dirs.push(dir) + const path = join(dir, 'chat.db') + execFileSync('/usr/bin/sqlite3', [path, `CREATE TABLE chat (ROWID INTEGER PRIMARY KEY, style INTEGER); + CREATE TABLE chat_message_join (message_id INTEGER, chat_id INTEGER); + ${sql}`]) + return path +} + +afterEach(async () => { + await Promise.all(dirs.splice(0).map(dir => rm(dir, { recursive: true, force: true }))) +}) + +describe('Messages 2FA provider', () => { + it('copies a recent incoming verification code on explicit local request', async () => { + const now = Date.now() + const date = Math.floor((now - APPLE_EPOCH_MS - 60_000) * 1_000_000) + const databasePath = await fixtureDatabase(`CREATE TABLE message (text TEXT, attributedBody BLOB, is_from_me INTEGER, date INTEGER); + INSERT INTO message VALUES ('Your verification code is 482913', NULL, 0, ${date});`) + const pasteboard = { write: vi.fn(async (_text: string) => {}) } + const provider = createMessages2FAProvider({ databasePath, now: () => now, pasteboard, enabled: () => true }) + + await expect(provider.commands?.copyLatest(null, { loopback: true, paired: false })) + .resolves.toEqual({ ok: true }) + expect(pasteboard.write).toHaveBeenCalledWith('482913') + }) + + it('finds verification text stored only in attributedBody', async () => { + const now = Date.now() + const date = Math.floor((now - APPLE_EPOCH_MS - 60_000) * 1_000_000) + const databasePath = await fixtureDatabase(`CREATE TABLE message (text TEXT, attributedBody BLOB, is_from_me INTEGER, date INTEGER); + INSERT INTO message VALUES (NULL, CAST('Your verification code is 734206' AS BLOB), 0, ${date});`) + const pasteboard = { write: vi.fn(async (_text: string) => {}) } + const provider = createMessages2FAProvider({ databasePath, now: () => now, pasteboard, enabled: () => true }) + + await expect(provider.commands?.copyLatest(null, { loopback: true, paired: false })) + .resolves.toEqual({ ok: true }) + expect(pasteboard.write).toHaveBeenCalledWith('734206') + }) + + it('extracts and copies a synthetic Foundation typedstream attributedBody', async () => { + const now = Date.now() + const date = Math.floor((now - APPLE_EPOCH_MS - 60_000) * 1_000_000) + const typedstreamHex = Buffer.from(ATTRIBUTED_TYPEDSTREAM_BASE64, 'base64').toString('hex') + const databasePath = await fixtureDatabase(`CREATE TABLE message (text TEXT, attributedBody BLOB, is_from_me INTEGER, date INTEGER); + INSERT INTO message VALUES (NULL, X'${typedstreamHex}', 0, ${date});`) + const pasteboard = { write: vi.fn(async (_text: string) => {}) } + const provider = createMessages2FAProvider({ databasePath, now: () => now, pasteboard, enabled: () => true }) + + await expect(provider.commands?.copyLatest(null, { loopback: true, paired: false })) + .resolves.toEqual({ ok: true }) + expect(pasteboard.write).toHaveBeenCalledWith('483921') + }) + + it('reads typedstream lengths that use the two-byte prefix', async () => { + const now = Date.now() + const date = Math.floor((now - APPLE_EPOCH_MS - 60_000) * 1_000_000) + const typedstreamHex = Buffer.from(LONG_TYPEDSTREAM_VERIFIED, 'base64').toString('hex') + const databasePath = await fixtureDatabase(`CREATE TABLE message (text TEXT, attributedBody BLOB, is_from_me INTEGER, date INTEGER); + INSERT INTO message VALUES (NULL, X'${typedstreamHex}', 0, ${date});`) + const pasteboard = { write: vi.fn(async (_text: string) => {}) } + const provider = createMessages2FAProvider({ databasePath, now: () => now, pasteboard, enabled: () => true }) + + await expect(provider.commands?.copyLatest(null, { loopback: true, paired: false })) + .resolves.toEqual({ ok: true }) + expect(pasteboard.write).toHaveBeenCalledWith('483921') + }) + + it('reads a full bounded result set with large attributed bodies', async () => { + const now = Date.now() + const date = Math.floor((now - APPLE_EPOCH_MS - 60_000) * 1_000_000) + const databasePath = await fixtureDatabase(`CREATE TABLE message (text TEXT, attributedBody BLOB, is_from_me INTEGER, date INTEGER); + WITH RECURSIVE seq(n) AS (SELECT 1 UNION ALL SELECT n + 1 FROM seq WHERE n < 100) + INSERT INTO message + SELECT 'Your verification code is 483921' || replace(hex(zeroblob(4064)), '00', char(1)), + zeroblob(${4096}), 0, ${date} - (100 - n) * 1000000000 + FROM seq;`) + const pasteboard = { write: vi.fn(async (_text: string) => {}) } + const provider = createMessages2FAProvider({ databasePath, now: () => now, pasteboard, enabled: () => true }) + + await expect(provider.commands?.copyLatest(null, { loopback: true, paired: false })) + .resolves.toEqual({ ok: true }) + expect(pasteboard.write).toHaveBeenCalledWith('483921') + }) + + it('ignores outgoing, expired and unrelated numeric messages', async () => { + const now = Date.now() + const recent = Math.floor((now - APPLE_EPOCH_MS - 60_000) * 1_000_000) + const old = Math.floor((now - APPLE_EPOCH_MS - 6 * 60_000) * 1_000_000) + const databasePath = await fixtureDatabase(`CREATE TABLE message (text TEXT, attributedBody BLOB, is_from_me INTEGER, date INTEGER); + INSERT INTO message VALUES ('Security code 111111', NULL, 1, ${recent}); + INSERT INTO message VALUES ('Verification code 222222', NULL, 0, ${old}); + INSERT INTO message VALUES ('Order number 333333', NULL, 0, ${recent}); + INSERT INTO message VALUES ('Le digicode c''est 4821, et le login wifi…', NULL, 0, ${recent});`) + const pasteboard = { write: vi.fn(async (_text: string) => {}) } + const provider = createMessages2FAProvider({ databasePath, now: () => now, pasteboard, enabled: () => true }) + + await expect(provider.commands?.copyLatest(null, { loopback: true, paired: false })) + .resolves.toEqual({ ok: false, error: tr(undefined, 'messages2fa.noneFound') }) + expect(pasteboard.write).not.toHaveBeenCalled() + }) + + it('refuses remote callers without reading Messages or touching the pasteboard', async () => { + const run = vi.fn(async () => '[]') + const pasteboard = { write: vi.fn(async (_text: string) => {}) } + const provider = createMessages2FAProvider({ run, pasteboard, enabled: () => true }) + + await expect(provider.commands?.copyLatest(null, { loopback: false, paired: false })) + .resolves.toEqual({ ok: false, error: tr(undefined, 'messages2fa.localOnly') }) + expect(run).not.toHaveBeenCalled() + expect(pasteboard.write).not.toHaveBeenCalled() + }) + + it('reports a dedicated permission error when macOS denies access to the database', async () => { + const run = vi.fn(async () => { throw new Error('permission-denied') }) + const pasteboard = { write: vi.fn(async (_text: string) => {}) } + const provider = createMessages2FAProvider({ run, pasteboard, enabled: () => true }) + + await expect(provider.commands?.copyLatest(null, { loopback: true, paired: false })) + .resolves.toEqual({ ok: false, error: tr(undefined, 'messages2fa.permission') }) + expect(pasteboard.write).not.toHaveBeenCalled() + }) + + it('fails closed on unsupported database schemas without exposing database content', async () => { + const databasePath = await fixtureDatabase('CREATE TABLE unsupported (body TEXT);') + const provider = createMessages2FAProvider({ databasePath, enabled: () => true }) + + await expect(provider.commands?.copyLatest(null, { loopback: true, paired: false })) + .resolves.toEqual({ ok: false, error: tr(undefined, 'messages2fa.readFailed') }) + }) + + it('does not expose a code or raw database error if copying fails', async () => { + const now = Date.now() + const date = Math.floor((now - APPLE_EPOCH_MS - 60_000) * 1_000_000) + const databasePath = await fixtureDatabase(`CREATE TABLE message (text TEXT, attributedBody BLOB, is_from_me INTEGER, date INTEGER); + INSERT INTO message VALUES ('Passcode 765432', NULL, 0, ${date});`) + const pasteboard = { write: vi.fn(async (_text: string) => { throw new Error('secret-bearing system error') }) } + const provider = createMessages2FAProvider({ databasePath, now: () => now, pasteboard, enabled: () => true }) + + await expect(provider.commands?.copyLatest(null, { loopback: true, paired: false })) + .resolves.toEqual({ ok: false, error: tr(undefined, 'messages2fa.copyFailed') }) + }) + + it('prefers an actual code phrase and skips account endings and dates', async () => { + const now = Date.now() + const recent = Math.floor((now - APPLE_EPOCH_MS - 30_000) * 1_000_000) + const databasePath = await fixtureDatabase(`CREATE TABLE message (text TEXT, attributedBody BLOB, is_from_me INTEGER, date INTEGER); + INSERT INTO message VALUES ('A sign-in to the account ending 4821 … Your code: 739201', NULL, 0, ${recent} + 2); + INSERT INTO message VALUES ('New login on 19/10/2026 … Verification code 482913', NULL, 0, ${recent}); + INSERT INTO message VALUES ('Votre code de connexion / de sécurité est 739201', NULL, 0, ${recent} - 1); + INSERT INTO message VALUES ('Your verification code is 888888', NULL, 0, ${recent} + 1); + INSERT INTO chat (style) VALUES (43); + INSERT INTO chat_message_join VALUES (3, 1);`) + const pasteboard = { write: vi.fn(async (_text: string) => {}) } + const provider = createMessages2FAProvider({ databasePath, now: () => now, pasteboard, enabled: () => true }) + + await expect(provider.commands?.copyLatest(null, { loopback: true, paired: false })) + .resolves.toEqual({ ok: true }) + expect(pasteboard.write).toHaveBeenCalledWith('739201') + }) + + it('does not copy a verification code from a group chat', async () => { + const now = Date.now() + const recent = Math.floor((now - APPLE_EPOCH_MS - 30_000) * 1_000_000) + const databasePath = await fixtureDatabase(`CREATE TABLE message (text TEXT, attributedBody BLOB, is_from_me INTEGER, date INTEGER); + INSERT INTO message VALUES ('Your verification code is 888888', NULL, 0, ${recent}); + INSERT INTO chat (style) VALUES (43); + INSERT INTO chat_message_join VALUES (1, 1);`) + const pasteboard = { write: vi.fn(async (_text: string) => {}) } + const provider = createMessages2FAProvider({ databasePath, now: () => now, pasteboard, enabled: () => true }) + + await expect(provider.commands?.copyLatest(null, { loopback: true, paired: false })) + .resolves.toEqual({ ok: false, error: tr(undefined, 'messages2fa.noneFound') }) + expect(pasteboard.write).not.toHaveBeenCalled() + }) + + it('recognizes a French verification-code phrase', async () => { + const now = Date.now() + const recent = Math.floor((now - APPLE_EPOCH_MS - 30_000) * 1_000_000) + const databasePath = await fixtureDatabase(`CREATE TABLE message (text TEXT, attributedBody BLOB, is_from_me INTEGER, date INTEGER); + INSERT INTO message VALUES ('Votre code de connexion / de sécurité est 739201', NULL, 0, ${recent});`) + const pasteboard = { write: vi.fn(async (_text: string) => {}) } + const provider = createMessages2FAProvider({ databasePath, now: () => now, pasteboard, enabled: () => true }) + + await expect(provider.commands?.copyLatest(null, { loopback: true, paired: false })) + .resolves.toEqual({ ok: true }) + expect(pasteboard.write).toHaveBeenCalledWith('739201') + }) + + it('does not read Messages until its separate privacy setting is enabled', async () => { + const run = vi.fn(async () => '[]') + const pasteboard = { write: vi.fn(async (_text: string) => {}) } + const provider = createMessages2FAProvider({ run, pasteboard, enabled: () => false }) + + await expect(provider.commands?.copyLatest(null, { loopback: true, paired: false })) + .resolves.toEqual({ ok: false, error: tr(undefined, 'messages2fa.disabled') }) + expect(run).not.toHaveBeenCalled() + expect(pasteboard.write).not.toHaveBeenCalled() + }) + + it('rate-limits repeated copy requests before spawning another database query', async () => { + let now = 10_000 + const run = vi.fn(async () => '[]') + const provider = createMessages2FAProvider({ run, now: () => now, enabled: () => true }) + const context = { loopback: true, paired: false } + + await provider.commands?.copyLatest(null, context) + now += 1_000 + await expect(provider.commands?.copyLatest(null, context)) + .resolves.toEqual({ ok: false, error: tr(undefined, 'messages2fa.rateLimited') }) + expect(run).toHaveBeenCalledTimes(1) + }) +}) + +describe('Messages 2FA pasteboard expiry', () => { + it.each(['after-string', 'after-concealed-marker', 'after-transient-marker', 'before-final-change-count'] as const)( + 'does not arm cleanup for a new clipboard owner when ownership changes %s', + async (interleave) => { + let changeCount = 40 + let owned = false + let writes = 0 + let value = '' + const board = { + prepareForNewContentsWithOptions: () => { owned = true; return changeCount }, + setStringForType: (next: string) => { + if (!owned) return false + value = next + if (interleave === 'after-string') { owned = false; value = 'unrelated clipboard'; changeCount += 1 } + return true + }, + setDataForType: () => { + if (!owned) return false + writes += 1 + if (interleave === 'after-concealed-marker' && writes === 1) { + owned = false + value = 'unrelated clipboard' + changeCount += 1 + } + if (interleave === 'after-transient-marker' && writes === 2) { + owned = false + value = 'unrelated clipboard' + changeCount += 1 + } + return true + }, + get changeCount() { + if (interleave === 'before-final-change-count' && writes === 2) { + owned = false + value = 'unrelated clipboard' + changeCount += 1 + } + return changeCount + }, + } + const executeScript = vi.fn(async (script: string, _args: string[], stdin?: string) => { + const context = { + ObjC: { import: (_framework: string) => {} }, + $: { + NSFileHandle: { fileHandleWithStandardInput: { readDataToEndOfFile: Buffer.from(stdin ?? '') } }, + NSString: { alloc: { initWithDataEncoding: (data: Buffer) => data.toString('utf8') } }, + NSUTF8StringEncoding: 4, + NSPasteboard: { get generalPasteboard() { return board } }, + NSPasteboardContentsCurrentHostOnly: 1, + NSPasteboardTypeString: 'public.utf8-plain-text', + NSData: { data: Buffer.alloc(0) }, + }, + } + return `${runInNewContext(script, context) ?? ''}\n` + }) + const spawnCleanup = vi.fn(() => { + const child = Object.assign(new EventEmitter(), { unref: vi.fn() }) + queueMicrotask(() => child.emit('spawn')) + return child as never + }) + const writer = createMessagePasteboardWriter({ executeScript, spawnCleanup }) + + await expect(writer.write('482913')).rejects.toThrow('pasteboard write failed') + expect(spawnCleanup).not.toHaveBeenCalled() + expect(value).toBe('unrelated clipboard') + }, + ) + + it('uses the acquired ownership count for cleanup after all marker writes succeed', async () => { + let changeCount = 70 + const board = { + prepareForNewContentsWithOptions: () => changeCount, + setStringForType: () => true, + setDataForType: () => true, + get changeCount() { return changeCount }, + } + const child = Object.assign(new EventEmitter(), { unref: vi.fn() }) + const executeScript = vi.fn(async (script: string, _args: string[], stdin?: string) => { + const context = { + ObjC: { import: (_framework: string) => {} }, + $: { + NSFileHandle: { fileHandleWithStandardInput: { readDataToEndOfFile: Buffer.from(stdin ?? '') } }, + NSString: { alloc: { initWithDataEncoding: (data: Buffer) => data.toString('utf8') } }, + NSUTF8StringEncoding: 4, + NSPasteboard: { get generalPasteboard() { return board } }, + NSPasteboardContentsCurrentHostOnly: 1, + NSPasteboardTypeString: 'public.utf8-plain-text', + NSData: { data: Buffer.alloc(0) }, + }, + } + return `${runInNewContext(script, context) ?? ''}\n` + }) + const spawnCleanup = vi.fn(() => { + queueMicrotask(() => child.emit('spawn')) + return child as never + }) + const writer = createMessagePasteboardWriter({ executeScript, spawnCleanup }) + + await expect(writer.write('482913')).resolves.toBeUndefined() + expect(spawnCleanup).toHaveBeenCalledWith(70) + }) + + it('conditionally clears the copied value if the cleanup child fails to start', async () => { + const child = Object.assign(new EventEmitter(), { unref: vi.fn() }) + const executeScript = vi.fn(async (script: string, _args: string[], _stdin?: string) => script.includes('String(ownedChangeCount)') ? '41\n' : '') + const spawnCleanup = vi.fn(() => child as never) + const writer = createMessagePasteboardWriter({ executeScript, spawnCleanup }) + const result = writer.write('739201') + await vi.waitFor(() => expect(spawnCleanup).toHaveBeenCalledTimes(1)) + + child.emit('error', new Error('synthetic spawn failure')) + + await expect(result).rejects.toThrow('pasteboard cleanup could not be started') + expect(executeScript).toHaveBeenCalledTimes(2) + expect(executeScript.mock.calls[0]?.[1]).toEqual([]) + expect(executeScript.mock.calls[0]?.[2]).toBe('739201') + expect(spawnCleanup).toHaveBeenCalledWith(41) + expect(executeScript.mock.calls[1]?.[0]).toContain('board.clearContents()') + expect(executeScript.mock.calls[1]?.[1]).toEqual(['41']) + }) + + it('conditionally clears the copied value if a started cleanup child exits unsuccessfully', async () => { + const child = Object.assign(new EventEmitter(), { unref: vi.fn() }) + const executeScript = vi.fn(async (script: string, _args: string[], _stdin?: string) => script.includes('String(ownedChangeCount)') ? '42\n' : '') + const spawnCleanup = vi.fn(() => child as never) + const writer = createMessagePasteboardWriter({ executeScript, spawnCleanup }) + const result = writer.write('482913') + await vi.waitFor(() => expect(spawnCleanup).toHaveBeenCalledTimes(1)) + + child.emit('spawn') + await expect(result).resolves.toBeUndefined() + child.emit('exit', 1) + await vi.waitFor(() => expect(executeScript).toHaveBeenCalledTimes(2)) + expect(executeScript.mock.calls[0]?.[1]).toEqual([]) + expect(executeScript.mock.calls[0]?.[2]).toBe('482913') + expect(spawnCleanup).toHaveBeenCalledWith(42) + expect(executeScript.mock.calls[1]?.[0]).toContain('board.clearContents()') + expect(executeScript.mock.calls[1]?.[1]).toEqual(['42']) + }) +}) diff --git a/server/test/widget-catalog.test.ts b/server/test/widget-catalog.test.ts index 16128900..7ea40061 100644 --- a/server/test/widget-catalog.test.ts +++ b/server/test/widget-catalog.test.ts @@ -117,6 +117,7 @@ describe('WidgetCatalog with an installed folder', () => { await into(installed, 'poke', { ...valid('poke'), commands: ['disk-map'] }) await widget('clipboard', { ...valid('clipboard'), subscriptions: ['clipboard'], commands: ['clipboard'] }) await into(installed, 'paste', { ...valid('paste'), subscriptions: ['clipboard'] }) + await into(installed, 'messages-2fa-widget', { ...valid('messages-2fa-widget'), commands: ['messages-2fa'] }) const cat = new WidgetCatalog(dir, installed) await cat.scan() expect(cat.entry('disk-map')!.manifest.commands).toEqual(['disk-map']) @@ -124,7 +125,8 @@ describe('WidgetCatalog with an installed folder', () => { expect(cat.get('poke')).toBeUndefined() expect(cat.entry('clipboard')!.manifest.subscriptions).toEqual(['clipboard']) expect(cat.get('paste')).toBeUndefined() - expect(cat.errors.map((e) => e.id).sort()).toEqual(['paste', 'peek', 'poke']) + expect(cat.get('messages-2fa-widget')).toBeUndefined() + expect(cat.errors.map((e) => e.id).sort()).toEqual(['messages-2fa-widget', 'paste', 'peek', 'poke']) expect(cat.errors.find((e) => e.id === 'peek')!.error).toContain('disk-map') expect(cat.errors.find((e) => e.id === 'paste')!.error).toContain('clipboard') }) diff --git a/server/test/widget-manifest.test.ts b/server/test/widget-manifest.test.ts index 60e4f34f..66091b08 100644 --- a/server/test/widget-manifest.test.ts +++ b/server/test/widget-manifest.test.ts @@ -243,6 +243,11 @@ describe('channels a manifest may not ask for', () => { expect(builtinOnlyChannels({ ...m, commands: [] })).toEqual(['brightness']) }) + it('reserves the Messages 2FA command for built-in widgets', () => { + const m = ManifestSchema.parse({ ...base, commands: ['messages-2fa'] }) + expect(builtinOnlyChannels(m)).toEqual(['messages-2fa']) + }) + it('names the reason', () => { const parsed = ManifestSchema.safeParse({ ...base, subscriptions: ['config'] }) expect(parsed.success).toBe(false) diff --git a/ui/src/admin/settings/PrivacyPane.vue b/ui/src/admin/settings/PrivacyPane.vue index ede790b0..9330f6a1 100644 --- a/ui/src/admin/settings/PrivacyPane.vue +++ b/ui/src/admin/settings/PrivacyPane.vue @@ -35,6 +35,9 @@ function setCodexSource(source: CodexSource, on: boolean): void { function setMacmonTemperature(on: boolean): void { s.apply((c) => { c.privacy.macmonTemperature = on }) } +function setMessages2FA(on: boolean): void { + s.apply((c) => { c.privacy.messages2FA = on }) +} /** * Off, the server leaves the account e-mail out of every snapshot it publishes; this box does * not hide it in a widget, it decides whether any widget is sent it at all. @@ -79,6 +82,10 @@ function setShowAccountEmail(on: boolean): void { :label="t('admin.inspector.screen.macmonTemperature')" @update:model-value="setMacmonTemperature($event)" />

{{ t('admin.inspector.screen.macmonTemperature.hint') }}

+ +

{{ t('admin.inspector.screen.messages2FA.hint') }}

diff --git a/ui/src/shared/locales/en.ts b/ui/src/shared/locales/en.ts index c14194c7..ff36e93d 100644 --- a/ui/src/shared/locales/en.ts +++ b/ui/src/shared/locales/en.ts @@ -404,6 +404,8 @@ export const en: Record = { 'admin.inspector.screen.accountEmail.hint': 'Off by default. Widgets that show an account then get the plan and the sign-in method, never the e-mail address: the server leaves it out of what it sends. Once on, the address is sent to every widget that reads an account channel — a widget installed from the marketplace included — and appears on the screen.', 'admin.inspector.screen.macmonTemperature': 'Read the CPU temperature with macmon', 'admin.inspector.screen.macmonTemperature.hint': 'Off by default. macmon is a third-party open-source tool that Fremkit does not install. Install it yourself with brew install macmon. On Apple Silicon, the server runs only /opt/homebrew/bin/macmon or /usr/local/bin/macmon every 10 seconds for one sample. The reading stays on this Mac. If unavailable, Fremkit shows the system temperature when known.', + 'admin.inspector.screen.messages2FA': 'Allow Messages verification-code lookup', + 'admin.inspector.screen.messages2FA.hint': 'Off by default, including after an upgrade. When enabled, an eligible built-in widget can request only recent incoming Messages after you tap copy. macOS Full Disk Access is also required; granting it does not enable this setting. The copied code is marked concealed and temporary, stays on this Mac, and Fremkit schedules a conditional clear after 60 seconds. If macOS refuses both the scheduled clear and an immediate retry, the code may remain on the clipboard.', 'admin.inspector.screen.about': 'About', 'admin.inspector.screen.about.version': 'Fremkit {version}', 'admin.inspector.screen.labs': 'Experimental features', diff --git a/ui/src/shared/locales/fr.ts b/ui/src/shared/locales/fr.ts index ccc2f687..5b7f4876 100644 --- a/ui/src/shared/locales/fr.ts +++ b/ui/src/shared/locales/fr.ts @@ -404,6 +404,8 @@ export const fr: Record = { 'admin.inspector.screen.accountEmail.hint': 'Désactivé par défaut. Les widgets qui affichent un compte reçoivent alors le forfait et le mode de connexion, jamais l’adresse e-mail : le serveur la retire de ce qu’il envoie. Une fois activé, l’adresse est envoyée à chaque widget qui lit un canal de compte — y compris un widget installé depuis la marketplace — et apparaît à l’écran.', 'admin.inspector.screen.macmonTemperature': 'Lire la température du CPU avec macmon', 'admin.inspector.screen.macmonTemperature.hint': 'Désactivé par défaut. macmon est un outil tiers libre que Fremkit n’installe pas. Installez-le vous-même avec brew install macmon. Sur Apple Silicon, le serveur lance uniquement /opt/homebrew/bin/macmon ou /usr/local/bin/macmon toutes les 10 secondes pour une mesure. Celle-ci reste sur ce Mac. Si indisponible, Fremkit affiche la température système lorsqu’elle est connue.', + 'admin.inspector.screen.messages2FA': 'Autoriser la recherche de codes dans Messages', + 'admin.inspector.screen.messages2FA.hint': 'Désactivé par défaut, y compris après une mise à niveau. Une fois activé, un widget intégré autorisé peut demander uniquement les messages reçus récemment lorsque vous touchez Copier. L’accès complet au disque de macOS est également nécessaire ; l’accorder n’active pas ce réglage. Le code copié est marqué comme masqué et temporaire, reste sur ce Mac, et Fremkit programme un effacement conditionnel après 60 secondes. Si macOS refuse cet effacement et une nouvelle tentative immédiate, le code peut rester dans le presse-papiers.', 'admin.inspector.screen.about': 'À propos', 'admin.inspector.screen.about.version': 'Fremkit {version}', 'admin.inspector.screen.labs': 'Fonctions expérimentales', diff --git a/ui/src/shared/types.ts b/ui/src/shared/types.ts index 0e1e8f49..41913ec0 100644 --- a/ui/src/shared/types.ts +++ b/ui/src/shared/types.ts @@ -144,6 +144,8 @@ export interface Privacy { codexHistorySources: ('cli' | 'vscode' | 'exec' | 'appServer' | 'subAgent' | 'subAgentReview' | 'subAgentCompact' | 'subAgentThreadSpawn' | 'subAgentOther' | 'unknown')[] /** Use the optional local macmon executable for Apple Silicon CPU temperature. */ macmonTemperature: boolean + /** Permit an explicit local request to read a recent Messages verification code. */ + messages2FA?: boolean } /**