| 1 | // Per-app consent ledger: which applications this host may drive on each |
| 2 | // computer, and whether it may take the shared pointer/foreground at all. |
| 3 | // |
| 4 | // The model is the one the on-computer agent products converged on: the app, |
| 5 | // not the tool, is the unit of trust. The first call that targets an app — |
| 6 | // binding input to it, observing it by name, or acting through a bound or |
| 7 | // element target — refuses with consent_required until a decision exists. |
| 8 | // Decisions are "allow" or "deny"; a bare grant lives for this server session |
| 9 | // (the host asks again next task), remember:true persists it to consent.json. |
| 10 | // |
| 11 | // Two scopes: |
| 12 | // apps — keyed by resolved identity (bundle id, name, pid) |
| 13 | // foreground — darwin activate:true, the shared-desktop escalation |
| 14 | // |
| 15 | // This is a model-level ledger, not an OS sandbox: a determined agent with |
| 16 | // another channel could still reach an app. What it buys is the honest part — |
| 17 | // no accidental touches, every first contact visible, and a deny the host can |
| 18 | // actually enforce on this surface. |
| 19 | import fs from "node:fs"; |
| 20 | import path from "node:path"; |
| 21 | import crypto from "node:crypto"; |
| 22 | import { stateDir } from "./registry.mjs"; |
| 23 | |
| 24 | // Persisted allows are signed. consent.json is a file any process of this |
| 25 | // user can write, so an allow counts only when it carries a MAC under the |
| 26 | // ledger key the host keeps in its secret store (sent over the host channel, |
| 27 | // see server.mjs). Denies need no signature: they only narrow. Without a |
| 28 | // ledger key, allows live for the session only. |
| 29 | let ledgerKey = null; |
| 30 | export function setLedgerKey(key) { ledgerKey = Buffer.isBuffer(key) && key.length >= 32 ? key : null; } |
| 31 | function entryMac(computerId, key, entry) { |
| 32 | return crypto.createHmac("sha256", ledgerKey).update(`${computerId}\0${key}\0${entry.decision}\0${entry.at ?? ""}`).digest("hex"); |
| 33 | } |
| 34 | function signed(computerId, key, entry) { |
| 35 | return entry.decision === "allow" && ledgerKey ? { ...entry, mac: entryMac(computerId, key, entry) } : entry; |
| 36 | } |
| 37 | /** A persisted entry that may be honored: any deny, or an allow whose MAC verifies. */ |
| 38 | function honored(computerId, key, entry) { |
| 39 | if (!entry || typeof entry !== "object") return false; |
| 40 | if (entry.decision === "deny") return true; |
| 41 | if (entry.decision !== "allow" || !ledgerKey || typeof entry.mac !== "string") return false; |
| 42 | const expected = Buffer.from(entryMac(computerId, key, entry), "hex"); |
| 43 | const given = /^[0-9a-f]+$/i.test(entry.mac) ? Buffer.from(entry.mac, "hex") : Buffer.alloc(0); |
| 44 | return given.length === expected.length && crypto.timingSafeEqual(given, expected); |
| 45 | } |
| 46 | |
| 47 | const ID_RE = /^[a-zA-Z0-9][a-zA-Z0-9._-]{0,63}$/; |
| 48 | const consentPath = () => path.join(stateDir(), "consent.json"); |
| 49 | |
| 50 | /** computerId -> Map(key -> {decision, name?, at}) — session-scoped, dies with the server. */ |
| 51 | const session = new Map(); |
| 52 | function sessionMap(computerId) { |
| 53 | let m = session.get(computerId); |
| 54 | if (!m) { m = new Map(); session.set(computerId, m); } |
| 55 | return m; |
| 56 | } |
| 57 | |
| 58 | function load() { |
| 59 | try { |
| 60 | const raw = JSON.parse(fs.readFileSync(consentPath(), "utf8")); |
| 61 | if (!raw || typeof raw !== "object" || !raw.computers) throw new Error("bad shape"); |
| 62 | return raw; |
| 63 | } catch { |
| 64 | return { version: 1, computers: {} }; |
| 65 | } |
| 66 | } |
| 67 | |
| 68 | function save(data) { |
| 69 | fs.mkdirSync(stateDir(), { recursive: true }); |
| 70 | const tmp = consentPath() + ".tmp"; |
| 71 | fs.writeFileSync(tmp, JSON.stringify(data, null, 2) + "\n"); |
| 72 | fs.renameSync(tmp, consentPath()); |
| 73 | } |
| 74 | |
| 75 | /** |
| 76 | * Identity keys for an app reference. name/bundle match the native resolver's |
| 77 | * case-insensitive compare, so keys normalize lowercase. pid entries are |
| 78 | * session-only — a pid never outlives its process, so persisting one would |
| 79 | * grant (or deny) whichever app inherits the number next. |
| 80 | */ |
| 81 | export function appKeys(ref) { |
| 82 | const keys = []; |
| 83 | if (!ref || typeof ref !== "object") return keys; |
| 84 | if (typeof ref.bundle_id === "string" && ref.bundle_id.trim()) keys.push(`bundle:${ref.bundle_id.trim().toLowerCase()}`); |
| 85 | // A ".app" suffix is a filesystem spelling, not part of the name — the |
| 86 | // native resolver strips it, and so must the ledger. |
| 87 | if (typeof ref.name === "string" && ref.name.trim()) keys.push(`name:${ref.name.trim().replace(/\.app$/i, "").toLowerCase()}`); |
| 88 | if (Number.isInteger(ref.pid) && ref.pid > 0) keys.push(`pid:${ref.pid}`); |
| 89 | return keys; |
| 90 | } |
| 91 | |
| 92 | /** Split a caller-supplied app string into identity keys. */ |
| 93 | export function parseAppArg({ app, name, bundle_id, pid } = {}) { |
| 94 | const ref = {}; |
| 95 | if (typeof bundle_id === "string" && bundle_id.trim()) ref.bundle_id = bundle_id.trim(); |
| 96 | if (typeof name === "string" && name.trim()) ref.name = name.trim(); |
| 97 | if (Number.isInteger(pid) && pid > 0) ref.pid = pid; |
| 98 | if (typeof app === "string" && app.trim() && !Object.keys(ref).length) { |
| 99 | const s = app.trim(); |
| 100 | if (/^pid:\d+$/i.test(s)) ref.pid = Number(s.slice(4)); |
| 101 | else if (/^\d+$/.test(s)) ref.pid = Number(s); |
| 102 | // ".app" is a filename spelling and always means a name — it must be |
| 103 | // checked before the reverse-DNS shape, which it also satisfies. |
| 104 | else if (/\.app$/i.test(s)) ref.name = s.replace(/\.app$/i, ""); |
| 105 | // Reverse-DNS shape (com.foo.bar, no spaces) reads as a bundle id. |
| 106 | else if (/^[A-Za-z0-9-]+(\.[A-Za-z0-9-]+)+$/.test(s) && !s.includes(" ")) ref.bundle_id = s; |
| 107 | else ref.name = s; |
| 108 | } |
| 109 | return appKeys(ref); |
| 110 | } |
| 111 | |
| 112 | function persistedEntries(computerId) { |
| 113 | const apps = load().computers[computerId]?.apps ?? {}; |
| 114 | return Object.fromEntries(Object.entries(apps).filter(([key, entry]) => honored(computerId, key, entry))); |
| 115 | } |
| 116 | |
| 117 | /** |
| 118 | * The newest decision among matching keys wins — session entries are checked |
| 119 | * alongside persisted ones, so "always deny" followed by "allow once" yields |
| 120 | * allow, and "always allow" followed by a session deny yields deny. Returns |
| 121 | * {state: allowed|denied|undecided, via, persisted}. |
| 122 | */ |
| 123 | export function decisionFor(computerId, keys) { |
| 124 | let best = null; |
| 125 | const consider = (entry, key, persisted) => { |
| 126 | if (!entry || (entry.decision !== "allow" && entry.decision !== "deny")) return; |
| 127 | // A session entry may itself be backed by disk (remember:true writes |
| 128 | // both layers and marks the session copy) — durability is honest, not |
| 129 | // just "which map won". |
| 130 | const durable = persisted || entry.persisted === true; |
| 131 | if (!best || String(entry.at ?? "") > String(best.at ?? "")) best = { ...entry, via: key, persisted: durable }; |
| 132 | }; |
| 133 | const sm = session.get(computerId); |
| 134 | for (const key of keys) { |
| 135 | consider(sm?.get(key), key, false); |
| 136 | consider(persistedEntries(computerId)[key], key, true); |
| 137 | } |
| 138 | if (!best) return { state: "undecided" }; |
| 139 | return { state: best.decision === "deny" ? "denied" : "allowed", via: best.via, persisted: best.persisted, name: best.name ?? null }; |
| 140 | } |
| 141 | |
| 142 | /** Record a decision under every given key. Session-only unless remember. */ |
| 143 | export function record(computerId, keys, decision, { remember = false, name = null } = {}) { |
| 144 | if (!ID_RE.test(computerId)) throw Object.assign(new Error(`bad computer id "${computerId}"`), { code: "bad_args" }); |
| 145 | if (decision !== "allow" && decision !== "deny") throw Object.assign(new Error(`decision must be "allow" or "deny"`), { code: "bad_args" }); |
| 146 | const at = new Date().toISOString(); |
| 147 | const entry = { decision, at, ...(name ? { name } : {}) }; |
| 148 | // pid keys never persist — see appKeys. An allow persists only when it |
| 149 | // can be signed. |
| 150 | const persistable = keys.filter((k) => !k.startsWith("pid:")); |
| 151 | const persist = remember && persistable.length > 0 && (decision === "deny" || ledgerKey != null); |
| 152 | if (persist) { |
| 153 | const data = load(); |
| 154 | const apps = (data.computers[computerId] ??= { apps: {} }).apps ??= {}; |
| 155 | for (const key of persistable) apps[key] = signed(computerId, key, { ...entry }); |
| 156 | save(data); |
| 157 | } |
| 158 | const sm = sessionMap(computerId); |
| 159 | const backed = new Set(persist ? persistable : []); |
| 160 | for (const key of keys) sm.set(key, { ...entry, ...(backed.has(key) ? { persisted: true } : {}) }); |
| 161 | return { keys, decision, persisted: persist }; |
| 162 | } |
| 163 | |
| 164 | /** |
| 165 | * Copy an already-made decision onto a resolved identity's other keys — an |
| 166 | * allow for "Safari" also covers bundle:com.apple.safari once open_application |
| 167 | * resolves it, so the next request under a different spelling does not |
| 168 | * re-prompt. Aliases land at the same layer (session or persisted) as the |
| 169 | * decision they extend. |
| 170 | */ |
| 171 | export function alias(computerId, keys, { persisted = false, name = null } = {}) { |
| 172 | const at = new Date().toISOString(); |
| 173 | const sm = sessionMap(computerId); |
| 174 | const entry = { decision: "allow", at, ...(name ? { name } : {}) }; |
| 175 | let durableKeys = new Set(); |
| 176 | if (persisted && ledgerKey) { |
| 177 | const data = load(); |
| 178 | const apps = (data.computers[computerId] ??= { apps: {} }).apps ??= {}; |
| 179 | for (const key of keys.filter((k) => !k.startsWith("pid:"))) { |
| 180 | if (!honored(computerId, key, apps[key])) apps[key] = signed(computerId, key, { ...entry }); |
| 181 | } |
| 182 | save(data); |
| 183 | // A key already persisted as deny stays deny on disk — the marker only |
| 184 | // goes on keys whose disk entry is actually this allow. |
| 185 | durableKeys = new Set(keys.filter((k) => apps[k]?.decision === "allow" && honored(computerId, k, apps[k]))); |
| 186 | } |
| 187 | for (const key of keys) sm.set(key, { ...entry, ...(durableKeys.has(key) ? { persisted: true } : {}) }); |
| 188 | } |
| 189 | |
| 190 | /** Remove every trace of the given keys (and foreground when asked) at both layers. */ |
| 191 | export function revoke(computerId, keys) { |
| 192 | const sm = session.get(computerId); |
| 193 | let removed = 0; |
| 194 | for (const key of keys) if (sm?.delete(key)) removed++; |
| 195 | const data = load(); |
| 196 | const apps = data.computers[computerId]?.apps; |
| 197 | if (apps) { |
| 198 | for (const key of keys) if (delete apps[key]) removed++; |
| 199 | save(data); |
| 200 | } |
| 201 | return { removed }; |
| 202 | } |
| 203 | |
| 204 | export function foregroundDecision(computerId) { |
| 205 | const s = session.get(computerId)?.get("scope:foreground"); |
| 206 | const stored = load().computers[computerId]?.foreground; |
| 207 | const p = honored(computerId, "scope:foreground", stored) ? stored : null; |
| 208 | const pick = [s && { ...s, persisted: s.persisted === true }, p && { ...p, persisted: true }] |
| 209 | .filter(Boolean) |
| 210 | .sort((a, b) => String(b.at).localeCompare(String(a.at)))[0]; |
| 211 | if (!pick || (pick.decision !== "allow" && pick.decision !== "deny")) return { state: "undecided" }; |
| 212 | return { state: pick.decision === "deny" ? "denied" : "allowed", persisted: pick.persisted }; |
| 213 | } |
| 214 | |
| 215 | export function recordForeground(computerId, decision, { remember = false } = {}) { |
| 216 | const at = new Date().toISOString(); |
| 217 | const persist = remember && (decision === "deny" || ledgerKey != null); |
| 218 | sessionMap(computerId).set("scope:foreground", { decision, at, ...(persist ? { persisted: true } : {}) }); |
| 219 | if (persist) { |
| 220 | const data = load(); |
| 221 | (data.computers[computerId] ??= {}).foreground = signed(computerId, "scope:foreground", { decision, at }); |
| 222 | save(data); |
| 223 | } |
| 224 | return { scope: "foreground", decision, persisted: persist }; |
| 225 | } |
| 226 | |
| 227 | export function revokeForeground(computerId) { |
| 228 | const sm = session.get(computerId); |
| 229 | let removed = sm?.delete("scope:foreground") ? 1 : 0; |
| 230 | const data = load(); |
| 231 | if (data.computers[computerId]?.foreground) { delete data.computers[computerId].foreground; removed++; save(data); } |
| 232 | return { removed }; |
| 233 | } |
| 234 | |
| 235 | /** Merged view for consent status: persisted entries overlaid with this session's. */ |
| 236 | export function status(computerId) { |
| 237 | const apps = {}; |
| 238 | for (const [key, entry] of Object.entries(persistedEntries(computerId))) apps[key] = { ...entry, source: "persisted" }; |
| 239 | for (const [key, entry] of session.get(computerId) ?? []) { |
| 240 | if (key === "scope:foreground") continue; |
| 241 | apps[key] = { ...entry, source: entry.persisted === true ? "persisted" : "session" }; |
| 242 | } |
| 243 | const fg = foregroundDecision(computerId); |
| 244 | return { computer: computerId, apps, foreground: fg.state === "undecided" ? null : fg }; |
| 245 | } |
| 246 | |
| 247 | /** Drop this session's grants for a computer whose route went away. */ |
| 248 | export function dropSession(computerId) { |
| 249 | session.delete(computerId); |
| 250 | } |
| 251 |