| 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 { stateDir } from "./registry.mjs"; |
| 22 | |
| 23 | const ID_RE = /^[a-zA-Z0-9][a-zA-Z0-9._-]{0,63}$/; |
| 24 | const consentPath = () => path.join(stateDir(), "consent.json"); |
| 25 | |
| 26 | /** computerId -> Map(key -> {decision, name?, at}) — session-scoped, dies with the server. */ |
| 27 | const session = new Map(); |
| 28 | function sessionMap(computerId) { |
| 29 | let m = session.get(computerId); |
| 30 | if (!m) { m = new Map(); session.set(computerId, m); } |
| 31 | return m; |
| 32 | } |
| 33 | |
| 34 | function load() { |
| 35 | try { |
| 36 | const raw = JSON.parse(fs.readFileSync(consentPath(), "utf8")); |
| 37 | if (!raw || typeof raw !== "object" || !raw.computers) throw new Error("bad shape"); |
| 38 | return raw; |
| 39 | } catch { |
| 40 | return { version: 1, computers: {} }; |
| 41 | } |
| 42 | } |
| 43 | |
| 44 | function save(data) { |
| 45 | fs.mkdirSync(stateDir(), { recursive: true }); |
| 46 | const tmp = consentPath() + ".tmp"; |
| 47 | fs.writeFileSync(tmp, JSON.stringify(data, null, 2) + "\n"); |
| 48 | fs.renameSync(tmp, consentPath()); |
| 49 | } |
| 50 | |
| 51 | /** |
| 52 | * Identity keys for an app reference. name/bundle match the native resolver's |
| 53 | * case-insensitive compare, so keys normalize lowercase. pid entries are |
| 54 | * session-only — a pid never outlives its process, so persisting one would |
| 55 | * grant (or deny) whichever app inherits the number next. |
| 56 | */ |
| 57 | export function appKeys(ref) { |
| 58 | const keys = []; |
| 59 | if (!ref || typeof ref !== "object") return keys; |
| 60 | if (typeof ref.bundle_id === "string" && ref.bundle_id.trim()) keys.push(`bundle:${ref.bundle_id.trim().toLowerCase()}`); |
| 61 | // A ".app" suffix is a filesystem spelling, not part of the name — the |
| 62 | // native resolver strips it, and so must the ledger. |
| 63 | if (typeof ref.name === "string" && ref.name.trim()) keys.push(`name:${ref.name.trim().replace(/\.app$/i, "").toLowerCase()}`); |
| 64 | if (Number.isInteger(ref.pid) && ref.pid > 0) keys.push(`pid:${ref.pid}`); |
| 65 | return keys; |
| 66 | } |
| 67 | |
| 68 | /** Split a caller-supplied app string into identity keys. */ |
| 69 | export function parseAppArg({ app, name, bundle_id, pid } = {}) { |
| 70 | const ref = {}; |
| 71 | if (typeof bundle_id === "string" && bundle_id.trim()) ref.bundle_id = bundle_id.trim(); |
| 72 | if (typeof name === "string" && name.trim()) ref.name = name.trim(); |
| 73 | if (Number.isInteger(pid) && pid > 0) ref.pid = pid; |
| 74 | if (typeof app === "string" && app.trim() && !Object.keys(ref).length) { |
| 75 | const s = app.trim(); |
| 76 | if (/^pid:\d+$/i.test(s)) ref.pid = Number(s.slice(4)); |
| 77 | else if (/^\d+$/.test(s)) ref.pid = Number(s); |
| 78 | // ".app" is a filename spelling and always means a name — it must be |
| 79 | // checked before the reverse-DNS shape, which it also satisfies. |
| 80 | else if (/\.app$/i.test(s)) ref.name = s.replace(/\.app$/i, ""); |
| 81 | // Reverse-DNS shape (com.foo.bar, no spaces) reads as a bundle id. |
| 82 | else if (/^[A-Za-z0-9-]+(\.[A-Za-z0-9-]+)+$/.test(s) && !s.includes(" ")) ref.bundle_id = s; |
| 83 | else ref.name = s; |
| 84 | } |
| 85 | return appKeys(ref); |
| 86 | } |
| 87 | |
| 88 | function persistedEntries(computerId) { |
| 89 | return load().computers[computerId]?.apps ?? {}; |
| 90 | } |
| 91 | |
| 92 | /** |
| 93 | * The newest decision among matching keys wins — session entries are checked |
| 94 | * alongside persisted ones, so "always deny" followed by "allow once" yields |
| 95 | * allow, and "always allow" followed by a session deny yields deny. Returns |
| 96 | * {state: allowed|denied|undecided, via, persisted}. |
| 97 | */ |
| 98 | export function decisionFor(computerId, keys) { |
| 99 | let best = null; |
| 100 | const consider = (entry, key, persisted) => { |
| 101 | if (!entry || (entry.decision !== "allow" && entry.decision !== "deny")) return; |
| 102 | // A session entry may itself be backed by disk (remember:true writes |
| 103 | // both layers and marks the session copy) — durability is honest, not |
| 104 | // just "which map won". |
| 105 | const durable = persisted || entry.persisted === true; |
| 106 | if (!best || String(entry.at ?? "") > String(best.at ?? "")) best = { ...entry, via: key, persisted: durable }; |
| 107 | }; |
| 108 | const sm = session.get(computerId); |
| 109 | for (const key of keys) { |
| 110 | consider(sm?.get(key), key, false); |
| 111 | consider(persistedEntries(computerId)[key], key, true); |
| 112 | } |
| 113 | if (!best) return { state: "undecided" }; |
| 114 | return { state: best.decision === "deny" ? "denied" : "allowed", via: best.via, persisted: best.persisted, name: best.name ?? null }; |
| 115 | } |
| 116 | |
| 117 | /** Record a decision under every given key. Session-only unless remember. */ |
| 118 | export function record(computerId, keys, decision, { remember = false, name = null } = {}) { |
| 119 | if (!ID_RE.test(computerId)) throw Object.assign(new Error(`bad computer id "${computerId}"`), { code: "bad_args" }); |
| 120 | if (decision !== "allow" && decision !== "deny") throw Object.assign(new Error(`decision must be "allow" or "deny"`), { code: "bad_args" }); |
| 121 | const at = new Date().toISOString(); |
| 122 | const entry = { decision, at, ...(name ? { name } : {}) }; |
| 123 | // pid keys never persist — see appKeys. |
| 124 | const persistable = keys.filter((k) => !k.startsWith("pid:")); |
| 125 | if (remember && persistable.length) { |
| 126 | const data = load(); |
| 127 | const apps = (data.computers[computerId] ??= { apps: {} }).apps ??= {}; |
| 128 | for (const key of persistable) apps[key] = { ...entry }; |
| 129 | save(data); |
| 130 | } |
| 131 | const sm = sessionMap(computerId); |
| 132 | const backed = new Set(remember ? persistable : []); |
| 133 | for (const key of keys) sm.set(key, { ...entry, ...(backed.has(key) ? { persisted: true } : {}) }); |
| 134 | return { keys, decision, persisted: remember && persistable.length > 0 }; |
| 135 | } |
| 136 | |
| 137 | /** |
| 138 | * Copy an already-made decision onto a resolved identity's other keys — an |
| 139 | * allow for "Safari" also covers bundle:com.apple.safari once open_application |
| 140 | * resolves it, so the next request under a different spelling does not |
| 141 | * re-prompt. Aliases land at the same layer (session or persisted) as the |
| 142 | * decision they extend. |
| 143 | */ |
| 144 | export function alias(computerId, keys, { persisted = false, name = null } = {}) { |
| 145 | const at = new Date().toISOString(); |
| 146 | const sm = sessionMap(computerId); |
| 147 | const entry = { decision: "allow", at, ...(name ? { name } : {}) }; |
| 148 | let durableKeys = new Set(); |
| 149 | if (persisted) { |
| 150 | const data = load(); |
| 151 | const apps = (data.computers[computerId] ??= { apps: {} }).apps ??= {}; |
| 152 | for (const key of keys.filter((k) => !k.startsWith("pid:"))) apps[key] ??= { ...entry }; |
| 153 | save(data); |
| 154 | // A key already persisted as deny stays deny on disk — the marker only |
| 155 | // goes on keys whose disk entry is actually this allow. |
| 156 | durableKeys = new Set(keys.filter((k) => apps[k]?.decision === "allow")); |
| 157 | } |
| 158 | for (const key of keys) sm.set(key, { ...entry, ...(durableKeys.has(key) ? { persisted: true } : {}) }); |
| 159 | } |
| 160 | |
| 161 | /** Remove every trace of the given keys (and foreground when asked) at both layers. */ |
| 162 | export function revoke(computerId, keys) { |
| 163 | const sm = session.get(computerId); |
| 164 | let removed = 0; |
| 165 | for (const key of keys) if (sm?.delete(key)) removed++; |
| 166 | const data = load(); |
| 167 | const apps = data.computers[computerId]?.apps; |
| 168 | if (apps) { |
| 169 | for (const key of keys) if (delete apps[key]) removed++; |
| 170 | save(data); |
| 171 | } |
| 172 | return { removed }; |
| 173 | } |
| 174 | |
| 175 | export function foregroundDecision(computerId) { |
| 176 | const s = session.get(computerId)?.get("scope:foreground"); |
| 177 | const p = load().computers[computerId]?.foreground; |
| 178 | const pick = [s && { ...s, persisted: s.persisted === true }, p && { ...p, persisted: true }] |
| 179 | .filter(Boolean) |
| 180 | .sort((a, b) => String(b.at).localeCompare(String(a.at)))[0]; |
| 181 | if (!pick || (pick.decision !== "allow" && pick.decision !== "deny")) return { state: "undecided" }; |
| 182 | return { state: pick.decision === "deny" ? "denied" : "allowed", persisted: pick.persisted }; |
| 183 | } |
| 184 | |
| 185 | export function recordForeground(computerId, decision, { remember = false } = {}) { |
| 186 | const at = new Date().toISOString(); |
| 187 | sessionMap(computerId).set("scope:foreground", { decision, at, ...(remember ? { persisted: true } : {}) }); |
| 188 | if (remember) { |
| 189 | const data = load(); |
| 190 | (data.computers[computerId] ??= {}).foreground = { decision, at }; |
| 191 | save(data); |
| 192 | } |
| 193 | return { scope: "foreground", decision, persisted: remember }; |
| 194 | } |
| 195 | |
| 196 | export function revokeForeground(computerId) { |
| 197 | const sm = session.get(computerId); |
| 198 | let removed = sm?.delete("scope:foreground") ? 1 : 0; |
| 199 | const data = load(); |
| 200 | if (data.computers[computerId]?.foreground) { delete data.computers[computerId].foreground; removed++; save(data); } |
| 201 | return { removed }; |
| 202 | } |
| 203 | |
| 204 | /** Merged view for consent status: persisted entries overlaid with this session's. */ |
| 205 | export function status(computerId) { |
| 206 | const apps = {}; |
| 207 | for (const [key, entry] of Object.entries(persistedEntries(computerId))) apps[key] = { ...entry, source: "persisted" }; |
| 208 | for (const [key, entry] of session.get(computerId) ?? []) { |
| 209 | if (key === "scope:foreground") continue; |
| 210 | apps[key] = { ...entry, source: entry.persisted === true ? "persisted" : "session" }; |
| 211 | } |
| 212 | const fg = foregroundDecision(computerId); |
| 213 | return { computer: computerId, apps, foreground: fg.state === "undecided" ? null : fg }; |
| 214 | } |
| 215 | |
| 216 | /** Drop this session's grants for a computer whose route went away. */ |
| 217 | export function dropSession(computerId) { |
| 218 | session.delete(computerId); |
| 219 | } |
| 220 |