From 016343f456798c832f7465d657465bc0534ed9aa Mon Sep 17 00:00:00 2001 From: flash2do Date: Thu, 5 Nov 2026 23:54:00 -0800 Subject: [PATCH 1/7] Let a remote agent ring the Mac to ask for the relay A Linux box or cloud agent whose calls get 503 mac_offline had no way to ask for the relay: the Mac only dials the Worker while the relay is on. The Worker now takes a second, low-privilege Mac socket, the doorbell, authenticated with an HMAC of the relay secret so no new Worker secret is needed, and a POST /.keysrs/doorbell from the agent's own client token or pairing. Only SHA-256 hashes of those reach the Mac, one ring at a time and at most every ten seconds; the Mac's answer becomes the agent's status. --- Relay/src/protocol.js | 71 +++++++++ Relay/src/worker.js | 202 ++++++++++++++++++++++++-- Relay/test/doorbell.test.js | 279 ++++++++++++++++++++++++++++++++++++ 3 files changed, 543 insertions(+), 9 deletions(-) create mode 100644 Relay/test/doorbell.test.js diff --git a/Relay/src/protocol.js b/Relay/src/protocol.js index e6a7b4f..6b686d0 100644 --- a/Relay/src/protocol.js +++ b/Relay/src/protocol.js @@ -46,6 +46,77 @@ export const LIMITS = Object.freeze({ holdRecheckMs: 1_000, }); +// The doorbell (docs/relay.md, The doorbell): a second, low-privilege socket the +// Mac may keep open while its relay is off, which carries nothing but "an agent +// asks for the relay" and the Mac's answer. Both paths start with a dot, which +// no Keysrs key name can, so neither can shadow a key. +export const DOORBELL = Object.freeze({ + listenPath: "/.keysrs/doorbell/listen", + ringPath: "/.keysrs/doorbell", + keyPrefix: "ksfd_", + // HMAC context for the doorbell key; Relay.swift's DoorbellKey uses the same. + keyContext: "keysrs relay doorbell v1", + // How long a ringer waits for the Mac's answer by default, and at most + // (`?wait=`): long enough to walk to the Mac and touch the sensor. + ringWaitMs: 60_000, + maxRingWaitMs: 120_000, + // At most one ring reaches the Mac this often, whoever rings: the Worker + // checks no credential, so this is what keeps a stranger who knows the URL + // from making the Mac look up hashes all day. + ringIntervalMs: 10_000, +}); + +// The two credentials a ring may carry, in the shape the Mac mints them +// (24 random bytes, lower-case hex). Anything else never reaches the Mac. +const CLIENT_TOKEN = /^ksfc_[0-9a-f]{48}$/; +const PAIRING = /^ksfp_[0-9a-f]{48}$/; + +/// The client token and pairing a ring presents, read from the same headers the +/// gateway reads them from, and only as SHA-256 hex: the Mac stores both as +/// those hashes, so it can look them up, and the doorbell socket never carries +/// a credential someone who took over that socket could spend. +export async function ringCredentials(headers) { + let client = null; + const auth = (headers.get("authorization") || "").trim().split(/\s+/, 2); + if (auth.length === 2 && auth[0].toLowerCase() === "bearer" && CLIENT_TOKEN.test(auth[1])) client = auth[1]; + if (!client) { + for (const name of ["x-ksf-client", "x-api-key", "x-goog-api-key", "api-key"]) { + const value = (headers.get(name) || "").trim(); + if (CLIENT_TOKEN.test(value)) { + client = value; + break; + } + } + } + const pairValue = (headers.get("x-ksf-pair") || "").trim(); + const pair = PAIRING.test(pairValue) ? pairValue : null; + return { + client: client ? await sha256Hex(client) : null, + pair: pair ? await sha256Hex(pair) : null, + }; +} + +export async function sha256Hex(text) { + return hex(new Uint8Array(await crypto.subtle.digest("SHA-256", utf8.encode(text)))); +} + +/// The doorbell key for a relay secret: `ksfd_` + HMAC-SHA256(secret, context) +/// in hex. The Worker derives it from RELAY_SECRET, so turning the doorbell on +/// needs no second Worker secret; the Mac derives it once, under Touch ID, and +/// keeps only it. It cannot be turned back into the relay secret. +export async function doorbellKey(secret) { + if (typeof secret !== "string" || !secret) return ""; + const key = await crypto.subtle.importKey("raw", utf8.encode(secret), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]); + const mac = await crypto.subtle.sign("HMAC", key, utf8.encode(DOORBELL.keyContext)); + return DOORBELL.keyPrefix + hex(new Uint8Array(mac)); +} + +function hex(bytes) { + let out = ""; + for (const b of bytes) out += b.toString(16).padStart(2, "0"); + return out; +} + /// The limits a deployment runs with. The timeout knobs exist for the offline /// test suite only; RELAY_OFFLINE_GRACE_MS is a real setting, where 0 means /// "answer mac_offline at once" and anything above the cap is held to it. diff --git a/Relay/src/worker.js b/Relay/src/worker.js index 6f3bea0..e204b02 100644 --- a/Relay/src/worker.js +++ b/Relay/src/worker.js @@ -10,7 +10,7 @@ // console output is a one-line note on an unexpected frame, without payload. import { DurableObject } from "cloudflare:workers"; -import { BODYLESS_STATUS, FRAME, PROTOCOL, STRIP_RESPONSE, decodeFrame, encodeFrame, limitsFrom, secretMatches, stripRequestHeader } from "./protocol.js"; +import { BODYLESS_STATUS, DOORBELL, FRAME, PROTOCOL, STRIP_RESPONSE, decodeFrame, doorbellKey, encodeFrame, limitsFrom, ringCredentials, secretMatches, stripRequestHeader } from "./protocol.js"; const DOCS = "https://github.com/gshost1/Keysreallysafe/blob/main/docs/relay.md"; const utf8d = new TextDecoder(); @@ -27,8 +27,11 @@ function json(status, object, extraHeaders) { // The Worker's own answers an agent may simply send again, and how long to wait // first where a wait makes sense (docs/relay.md, the error table). -const RETRY_AFTER = { mac_offline: "30", relay_busy: "5" }; -const RETRYABLE = new Set(["mac_offline", "relay_busy", "mac_disconnected"]); +const RETRY_AFTER = { mac_offline: "30", relay_busy: "5", doorbell_offline: "60", doorbell_busy: "10", doorbell_mac_locked: "300" }; +const RETRYABLE = new Set([ + "mac_offline", "relay_busy", "mac_disconnected", + "doorbell_offline", "doorbell_busy", "doorbell_mac_locked", "doorbell_not_now", "doorbell_unavailable", +]); // The Mac's pairing refusals are the agent's to fix on the Mac (pair, renew, // re-scope), so the agent hears 403 rather than the 502 every other Mac error // gets (docs/relay.md, the pairing section). They are not in RETRYABLE or @@ -47,10 +50,42 @@ const MiB = 1024 * 1024; const duration = (ms) => (ms % 1000 === 0 ? `${ms / 1000} s` : `${ms} ms`); const size = (n) => (n % MiB === 0 ? `${n / MiB} MiB` : `${n} bytes`); -function refusal(status, code, message) { +function refusal(status, code, message, retryAfter) { const body = { error: code, message }; if (RETRYABLE.has(code)) body.retryable = true; - return json(status, body, RETRY_AFTER[code] ? { "retry-after": RETRY_AFTER[code] } : undefined); + const wait = retryAfter ?? RETRY_AFTER[code]; + return json(status, body, wait ? { "retry-after": String(wait) } : undefined); +} + +const NO_DOORBELL = "the Mac's doorbell is not connected: Keysrs is not running, its doorbell is off (keys relay doorbell on), or the Mac is asleep or offline"; +const ASKING = "the Mac is asking for Touch ID; ring again in a while, or just call: a request waits up to a minute for the relay"; + +/// The Mac's answer to a ring as the ringer's response (docs/relay.md, The +/// doorbell). The Mac says only which case applies; the wording is the Worker's. +function ringAnswer(answer) { + switch (answer.result) { + case "on": + return json(200, { relay: "on", message: "the relay is on; call https:////… as usual" }); + case "pending": + case "timeout": + return json(202, { relay: "off", state: "asking", message: ASKING, retryable: true }, { "retry-after": "15" }); + case "declined": + return refusal(403, "doorbell_declined", "the person at the Mac declined to turn the relay on"); + case "refused": + return refusal(403, "doorbell_refused", "the Mac does not know this client token or pairing as a live one, so it asked nobody"); + case "away": + return refusal(503, "doorbell_mac_locked", "the Mac's screen is locked, so nobody is there to approve the relay"); + case "not_now": { + const after = Number.isInteger(answer.retry_after) && answer.retry_after > 0 ? Math.min(answer.retry_after, 3600) : 600; + return refusal(429, "doorbell_not_now", "the Mac asked recently and is not asking again yet", after); + } + case "unavailable": + return refusal(503, "doorbell_unavailable", `the Mac could not turn the relay on${answer.message ? `: ${answer.message}` : ""}`); + case "offline": + return refusal(503, "doorbell_offline", NO_DOORBELL); + default: + return refusal(502, "doorbell_error", "the Mac answered the doorbell with something this Worker does not know"); + } } class RelayError extends Error { @@ -105,6 +140,41 @@ export default { // job and should travel no further than this function. return hub.fetch(new Request(url.origin + "/connect", { headers: { upgrade: "websocket" } })); } + if (url.pathname === DOORBELL.listenPath) { + if (request.method !== "GET") return json(405, { error: "method_not_allowed" }, { allow: "GET" }); + // The doorbell key is derived from the relay secret, so a Worker without + // one has no doorbell either. + const expected = await doorbellKey(env.RELAY_SECRET); + if (!(await secretMatches(bearer(request), expected))) { + return json(401, { error: "unauthorized" }, { "www-authenticate": 'Bearer realm="keysrs-relay"' }); + } + if ((request.headers.get("upgrade") || "").toLowerCase() !== "websocket") { + return json(426, { error: "upgrade_required", message: `${DOORBELL.listenPath} is the Mac's doorbell WebSocket endpoint` }, { upgrade: "websocket" }); + } + if (request.headers.get("x-keysrs-relay-protocol") !== PROTOCOL) { + return json(400, { + error: "unsupported_protocol", + message: `this Worker speaks relay protocol ${PROTOCOL}; update keys or redeploy the Worker from the same checkout`, + }); + } + return hub.fetch(new Request(url.origin + DOORBELL.listenPath, { headers: { upgrade: "websocket" } })); + } + if (url.pathname === DOORBELL.ringPath) { + if (request.method !== "POST") return json(405, { error: "method_not_allowed" }, { allow: "POST" }); + // Only the hashes travel on: the Durable Object, and the Mac after it, + // never hold the ringer's token. + const credentials = await ringCredentials(request.headers); + if (!credentials.client && !credentials.pair) { + return refusal(401, "doorbell_credential_required", "ring with the client token (Authorization: Bearer ksfc_…) or the pairing (X-KSF-Pair: ksfp_…) this Mac gave you"); + } + const wait = url.searchParams.get("wait"); + const ring = new URL(url.origin + DOORBELL.ringPath); + if (wait !== null) ring.searchParams.set("wait", wait); + return hub.fetch(new Request(ring, { + method: "POST", + headers: { "x-ring-client": credentials.client || "", "x-ring-pair": credentials.pair || "" }, + })); + } return hub.fetch(request); }, }; @@ -124,6 +194,12 @@ export class RelayHub extends DurableObject { this.heldBytes = 0; /** @type {Set<() => void>} wakes the requests waiting for a Mac */ this.waiters = new Set(); + // The one ring waiting for the Mac's answer, and when the last ring was + // sent to it (docs/relay.md, The doorbell). Memory only: a ring is an + // open HTTP request, which keeps this object awake for as long as it waits. + /** @type {{ id: string, ws: WebSocket, resolve: (answer: object) => void } | null} */ + this.ringing = null; + this.lastRingAt = 0; // Answered by the runtime without waking a hibernated object. this.ctx.setWebSocketAutoResponse(new WebSocketRequestResponsePair("ping", "pong")); } @@ -131,6 +207,8 @@ export class RelayHub extends DurableObject { async fetch(request) { const url = new URL(request.url); if (url.pathname === "/connect") return this.connect(); + if (url.pathname === DOORBELL.listenPath) return this.listen(); + if (url.pathname === DOORBELL.ringPath) return this.ring(request, url); return this.relay(request, url); } @@ -139,10 +217,21 @@ export class RelayHub extends DurableObject { /// to sleep or lost its network leaves its socket open here, and a request sent /// into it would hang until the Mac came back only to fail. mac() { + return this.newest("mac"); + } + + /// The Mac's doorbell socket, by the same rule as its relay socket. + doorbell() { + return this.newest("doorbell"); + } + + /// The most recently accepted open socket of one kind that has been heard + /// from within the silence limit. + newest(tag) { const now = Date.now(); let best = null; let bestAt = -1; - for (const ws of this.ctx.getWebSockets()) { + for (const ws of this.ctx.getWebSockets(tag)) { if (ws.readyState !== 1 /* OPEN */) continue; const at = ws.deserializeAttachment()?.connectedAt ?? 0; if (!this.heardRecently(ws, at, now)) continue; @@ -191,17 +280,78 @@ export class RelayHub extends DurableObject { const [client, server] = Object.values(pair); // One Mac per relay: a reconnecting Mac must not wait for a stale socket // to time out, so the newcomer wins and the old socket is told why. - for (const old of this.ctx.getWebSockets()) { + for (const old of this.ctx.getWebSockets("mac")) { this.failAll(old, 502, "mac_disconnected", "the Mac reconnected while this request was in flight; it may be retried"); try { old.close(4000, "replaced"); } catch { /* already gone */ } } - this.ctx.acceptWebSocket(server); - server.serializeAttachment({ connectedAt: Date.now() }); + this.ctx.acceptWebSocket(server, ["mac"]); + server.serializeAttachment({ connectedAt: Date.now(), kind: "mac" }); // The requests that arrived while no Mac was here go to this one. for (const wake of [...this.waiters]) wake(); + // A ring waiting for the Mac's answer has its answer: the relay is here. + this.ringing?.resolve({ result: "on" }); + return new Response(null, { status: 101, webSocket: client }); + } + + /// The Mac's doorbell socket. Like the relay, a newcomer replaces the old one. + listen() { + const pair = new WebSocketPair(); + const [client, server] = Object.values(pair); + for (const old of this.ctx.getWebSockets("doorbell")) { + if (this.ringing?.ws === old) this.ringing.resolve({ result: "offline" }); + try { old.close(4000, "replaced"); } catch { /* already gone */ } + } + this.ctx.acceptWebSocket(server, ["doorbell"]); + server.serializeAttachment({ connectedAt: Date.now(), kind: "doorbell" }); return new Response(null, { status: 101, webSocket: client }); } + /// One ring: sent to the Mac's doorbell, answered with the Mac's word, or + /// with "asking" once the ringer's wait is over. The Mac decides everything + /// about a ring; what this does is keep rings rare and one at a time. + async ring(request, url) { + if (this.mac()) return ringAnswer({ result: "on" }); + const bell = this.doorbell(); + if (!bell) return refusal(503, "doorbell_offline", NO_DOORBELL); + if (this.ringing) return refusal(503, "doorbell_busy", "another ring is waiting for the Mac's answer"); + const now = Date.now(); + const since = now - this.lastRingAt; + if (since < DOORBELL.ringIntervalMs) { + return refusal(503, "doorbell_busy", "the Mac was rung moments ago", Math.ceil((DOORBELL.ringIntervalMs - since) / 1000)); + } + let waitMs = DOORBELL.ringWaitMs; + const asked = url.searchParams.get("wait"); + if (asked !== null && /^[0-9]{1,4}$/.test(asked)) waitMs = Math.min(Number(asked) * 1000, DOORBELL.maxRingWaitMs); + + const id = Array.from(crypto.getRandomValues(new Uint8Array(16)), (b) => b.toString(16).padStart(2, "0")).join(""); + let timer = null; + const answered = new Promise((resolve) => { + const ring = { + id, + ws: bell, + resolve: (answer) => { + if (this.ringing === ring) this.ringing = null; + clearTimeout(timer); + resolve(answer); + }, + }; + this.ringing = ring; + timer = setTimeout(() => ring.resolve({ result: "timeout" }), waitMs); + }); + this.lastRingAt = now; + try { + bell.send(JSON.stringify({ + type: "ring", + id, + client: request.headers.get("x-ring-client") || null, + pair: request.headers.get("x-ring-pair") || null, + })); + } catch { + this.ringing?.resolve({ result: "offline" }); + } + return ringAnswer(await answered); + } + allocId() { const buf = new Uint32Array(1); for (;;) { @@ -548,6 +698,10 @@ export class RelayHub extends DurableObject { } webSocketMessage(ws, message) { + if (ws.deserializeAttachment()?.kind === "doorbell") { + this.doorbellMessage(ws, message); + return; + } if (typeof message === "string") { // The auto-response table normally answers this; a runtime without it // still gets a pong. Anything else is not part of the protocol. @@ -617,11 +771,41 @@ export class RelayHub extends DurableObject { } } + /// The doorbell speaks text: the keepalive and the Mac's JSON answers. A + /// binary frame, or an answer to a ring that is not waiting, is ignored or + /// closes the socket; it can never reach a ringer it was not meant for. + doorbellMessage(ws, message) { + if (typeof message !== "string") { + ws.close(1003, "binary frames are not part of the doorbell"); + return; + } + if (message === "ping") { + try { ws.send("pong"); } catch { /* closing */ } + return; + } + let answer; + try { + answer = message.length <= 2048 ? JSON.parse(message) : null; + } catch { + answer = null; + } + if (!answer || answer.type !== "answer" || typeof answer.id !== "string") return; + const ring = this.ringing; + if (!ring || ring.ws !== ws || ring.id !== answer.id) return; + ring.resolve({ + result: typeof answer.result === "string" ? answer.result : "", + retry_after: answer.retry_after, + message: typeof answer.message === "string" && answer.message.length <= 512 ? answer.message : "", + }); + } + webSocketClose(ws) { + if (this.ringing?.ws === ws) this.ringing.resolve({ result: "offline" }); this.failAll(ws, 502, "mac_disconnected", MAC_DROPPED); } webSocketError(ws) { + if (this.ringing?.ws === ws) this.ringing.resolve({ result: "offline" }); this.failAll(ws, 502, "mac_disconnected", "the Mac's connection failed while this request was in flight; it may be retried"); } } diff --git a/Relay/test/doorbell.test.js b/Relay/test/doorbell.test.js new file mode 100644 index 0000000..280b188 --- /dev/null +++ b/Relay/test/doorbell.test.js @@ -0,0 +1,279 @@ +// The doorbell (docs/relay.md, The doorbell), offline inside workerd like the +// relay suite. The "Mac" here holds two sockets the test opens itself: the +// doorbell and, where a test needs it, the relay. +import { SELF, env, runInDurableObject } from "cloudflare:test"; +import { afterEach, beforeEach, describe, expect, it } from "vitest"; +import { DOORBELL, doorbellKey, ringCredentials, sha256Hex } from "../src/protocol.js"; + +const ORIGIN = "https://relay.test"; +const hub = () => env.RELAY.get(env.RELAY.idFromName("mac")); +const open = []; + +// Shapes the Mac mints; never real credentials. +const CLIENT = "ksfc_" + "ab".repeat(24); +const CLIENT_HASH = "5a973ced9266a68474a00fddbe4ee925fcf572a98b55d8a5cf32b1f004511ed7"; +const PAIR = "ksfp_" + "cd".repeat(24); +const PAIR_HASH = "b44ce610e52b8257c00c602edcdbd676521d3bade907dfc0321ced7d88e414b3"; +// HMAC-SHA256(RELAY_SECRET from vitest.config.js, DOORBELL.keyContext); the +// Swift side's DoorbellKey test pins the same value. +const KEY = "ksfd_8e08d4cec8c525bf32a5136871d5275b83fa0d3a18a18025153bc5108c6a5bcf"; + +beforeEach(async () => { + // Every test starts with no socket and no ring throttle: the 10 s spacing is + // the Worker's rule, and tests that check it set it up themselves. + await runInDurableObject(hub(), (h) => { + for (const ws of h.ctx.getWebSockets()) { + try { ws.close(1000, "test reset"); } catch { /* already closing */ } + } + h.ringing = null; + h.lastRingAt = 0; + }); +}); + +afterEach(() => { + for (const ws of open.splice(0)) { + try { ws.close(1000, "test done"); } catch { /* already closed */ } + } +}); + +function withTimeout(promise, ms, what) { + let timer; + const bomb = new Promise((_, reject) => { + timer = setTimeout(() => reject(new Error(`timed out waiting for ${what}`)), ms); + }); + return Promise.race([promise, bomb]).finally(() => clearTimeout(timer)); +} + +function socketOf(res) { + const ws = res.webSocket; + ws.accept(); + open.push(ws); + const messages = []; + const waiters = []; + ws.addEventListener("message", (event) => { + messages.push(event.data); + for (const wake of waiters.splice(0)) wake(); + }); + const closed = new Promise((resolve) => { + ws.addEventListener("close", (event) => resolve({ code: event.code, reason: event.reason })); + }); + async function next() { + return withTimeout((async () => { + for (;;) { + if (messages.length) return messages.shift(); + await new Promise((wake) => waiters.push(wake)); + } + })(), 5000, "a doorbell message"); + } + return { ws, next, closed, messages }; +} + +async function listen(headers = {}) { + const res = await SELF.fetch(`${ORIGIN}${DOORBELL.listenPath}`, { + headers: { upgrade: "websocket", authorization: `Bearer ${KEY}`, "x-keysrs-relay-protocol": "1", ...headers }, + }); + expect(res.status).toBe(101); + return socketOf(res); +} + +async function connectRelay() { + const res = await SELF.fetch(`${ORIGIN}/connect`, { + headers: { upgrade: "websocket", authorization: `Bearer ${env.RELAY_SECRET}`, "x-keysrs-relay-protocol": "1" }, + }); + expect(res.status).toBe(101); + return socketOf(res); +} + +function ring(headers = { authorization: `Bearer ${CLIENT}` }, query = "") { + return SELF.fetch(`${ORIGIN}${DOORBELL.ringPath}${query}`, { method: "POST", headers }); +} + +/// Rings, reads the ring the Mac got, answers it with `answer`, and returns +/// the ringer's response. +async function ringAnswered(answer, headers) { + const bell = await listen(); + const pending = ring(headers); + const got = JSON.parse(await bell.next()); + bell.ws.send(JSON.stringify({ type: "answer", id: got.id, ...answer })); + return { res: await pending, got, bell }; +} + +describe("the doorbell key", () => { + it("is HMAC-SHA256 of the relay secret under the fixed context, as the Mac derives it", async () => { + expect(await doorbellKey(env.RELAY_SECRET)).toBe(KEY); + expect(await doorbellKey("")).toBe(""); + expect(await doorbellKey(undefined)).toBe(""); + }); + + it("opens the doorbell and nothing else: the relay secret is refused there, the doorbell key at /connect", async () => { + const wrong = await SELF.fetch(`${ORIGIN}${DOORBELL.listenPath}`, { + headers: { upgrade: "websocket", authorization: `Bearer ${env.RELAY_SECRET}`, "x-keysrs-relay-protocol": "1" }, + }); + expect(wrong.status).toBe(401); + const relay = await SELF.fetch(`${ORIGIN}/connect`, { + headers: { upgrade: "websocket", authorization: `Bearer ${KEY}`, "x-keysrs-relay-protocol": "1" }, + }); + expect(relay.status).toBe(401); + }); + + it("answers the listen handshake's other mistakes like /connect does", async () => { + const noUpgrade = await SELF.fetch(`${ORIGIN}${DOORBELL.listenPath}`, { headers: { authorization: `Bearer ${KEY}` } }); + expect(noUpgrade.status).toBe(426); + const oldProtocol = await SELF.fetch(`${ORIGIN}${DOORBELL.listenPath}`, { + headers: { upgrade: "websocket", authorization: `Bearer ${KEY}`, "x-keysrs-relay-protocol": "0" }, + }); + expect(oldProtocol.status).toBe(400); + const post = await SELF.fetch(`${ORIGIN}${DOORBELL.listenPath}`, { method: "POST" }); + expect(post.status).toBe(405); + }); +}); + +describe("ring credentials", () => { + it("are read from the gateway's headers and kept only as SHA-256 hex", async () => { + expect(await sha256Hex(CLIENT)).toBe(CLIENT_HASH); + expect(await ringCredentials(new Headers({ authorization: `Bearer ${CLIENT}`, "x-ksf-pair": PAIR }))).toEqual({ client: CLIENT_HASH, pair: PAIR_HASH }); + expect(await ringCredentials(new Headers({ "x-api-key": CLIENT }))).toEqual({ client: CLIENT_HASH, pair: null }); + expect(await ringCredentials(new Headers({ "x-ksf-pair": PAIR }))).toEqual({ client: null, pair: PAIR_HASH }); + }); + + it("ignore anything not shaped like a Keysrs token: a provider key, a grant, upper-case hex", async () => { + for (const value of ["sk-ant-api03-not-a-keysrs-token", "ksf_" + "ab".repeat(24), "ksfc_" + "AB".repeat(24), "ksfc_short"]) { + expect(await ringCredentials(new Headers({ authorization: `Bearer ${value}`, "x-api-key": value }))).toEqual({ client: null, pair: null }); + } + }); +}); + +describe("ringing", () => { + it("needs a client token or a pairing before anything reaches the Mac", async () => { + const bell = await listen(); + const res = await ring({}); + expect(res.status).toBe(401); + expect((await res.json()).error).toBe("doorbell_credential_required"); + const get = await SELF.fetch(`${ORIGIN}${DOORBELL.ringPath}`); + expect(get.status).toBe(405); + expect(bell.messages).toEqual([]); + }); + + it("says when no doorbell is listening, as a retryable 503", async () => { + const res = await ring(); + expect(res.status).toBe(503); + expect(res.headers.get("retry-after")).toBe("60"); + expect(await res.json()).toMatchObject({ error: "doorbell_offline", retryable: true }); + }); + + it("hands the Mac the hashes, never the token, and answers 200 once the Mac says on", async () => { + const { res, got } = await ringAnswered({ result: "on" }, { authorization: `Bearer ${CLIENT}`, "x-ksf-pair": PAIR }); + expect(got).toEqual({ type: "ring", id: expect.stringMatching(/^[0-9a-f]{32}$/), client: CLIENT_HASH, pair: PAIR_HASH }); + expect(JSON.stringify(got)).not.toContain(CLIENT); + expect(JSON.stringify(got)).not.toContain(PAIR); + expect(res.status).toBe(200); + expect(await res.json()).toMatchObject({ relay: "on" }); + }); + + it("maps each of the Mac's answers to its documented status", async () => { + const cases = [ + [{ result: "declined" }, 403, "doorbell_declined", undefined], + [{ result: "refused" }, 403, "doorbell_refused", undefined], + [{ result: "away" }, 503, "doorbell_mac_locked", "300"], + [{ result: "not_now", retry_after: 420 }, 429, "doorbell_not_now", "420"], + [{ result: "not_now", retry_after: 999999 }, 429, "doorbell_not_now", "3600"], + [{ result: "unavailable", message: "the gateway is not running" }, 503, "doorbell_unavailable", undefined], + [{ result: "something new" }, 502, "doorbell_error", undefined], + ]; + for (const [answer, status, code, retryAfter] of cases) { + await runInDurableObject(hub(), (h) => { h.lastRingAt = 0; }); + const { res, bell } = await ringAnswered(answer); + expect(res.status, code).toBe(status); + const body = await res.json(); + expect(body.error).toBe(code); + if (retryAfter) expect(res.headers.get("retry-after")).toBe(retryAfter); + if (answer.result === "unavailable") expect(body.message).toContain("the gateway is not running"); + if (answer.result === "declined" || answer.result === "refused") expect(body.retryable).toBeUndefined(); + bell.ws.close(1000, "next case"); + } + }); + + it("answers 202 asking while the Mac's prompt is up, and when the ringer's wait runs out", async () => { + const { res } = await ringAnswered({ result: "pending" }); + expect(res.status).toBe(202); + expect(await res.json()).toMatchObject({ relay: "off", state: "asking", retryable: true }); + + await runInDurableObject(hub(), (h) => { h.lastRingAt = 0; }); + const bell = await listen(); + const quick = await ring(undefined, "?wait=1"); + expect(quick.status).toBe(202); + expect(JSON.parse(bell.messages[0]).type).toBe("ring"); + }); + + it("answers 200 at once while the relay is connected, without ringing the Mac", async () => { + const bell = await listen(); + await connectRelay(); + const res = await ring(); + expect(res.status).toBe(200); + expect(bell.messages).toEqual([]); + }); + + it("answers 200 when the relay connects while the ring waits, even before the Mac's answer", async () => { + const bell = await listen(); + const pending = ring(); + expect(JSON.parse(await bell.next()).type).toBe("ring"); + await connectRelay(); + const res = await pending; + expect(res.status).toBe(200); + // The relay connecting does not close the doorbell, nor the other way round. + expect(bell.ws.readyState).toBe(1); + const second = await listen(); + await runInDurableObject(hub(), (h) => { + expect(h.ctx.getWebSockets("mac").length).toBe(1); + expect(h.ctx.getWebSockets("doorbell").filter((ws) => ws.readyState === 1).length).toBe(1); + }); + expect((await bell.closed).code).toBe(4000); + expect(second.ws.readyState).toBe(1); + }); + + it("rings one at a time and no more than every ten seconds", async () => { + const bell = await listen(); + const first = ring(); + const got = JSON.parse(await bell.next()); + const busy = await ring(); + expect(busy.status).toBe(503); + expect((await busy.json()).error).toBe("doorbell_busy"); + bell.ws.send(JSON.stringify({ type: "answer", id: got.id, result: "declined" })); + expect((await first).status).toBe(403); + const soon = await ring(); + expect(soon.status).toBe(503); + expect((await soon.json()).error).toBe("doorbell_busy"); + expect(Number(soon.headers.get("retry-after"))).toBeGreaterThan(0); + expect(Number(soon.headers.get("retry-after"))).toBeLessThanOrEqual(10); + expect(bell.messages).toEqual([]); + }); + + it("fails a waiting ring with doorbell_offline when the doorbell drops", async () => { + const bell = await listen(); + const pending = ring(); + await bell.next(); + bell.ws.close(1000, "Mac went away"); + const res = await pending; + expect(res.status).toBe(503); + expect((await res.json()).error).toBe("doorbell_offline"); + }); + + it("ignores an answer for another ring, and closes a doorbell that sends binary", async () => { + const bell = await listen(); + const pending = ring(undefined, "?wait=1"); + const got = JSON.parse(await bell.next()); + bell.ws.send(JSON.stringify({ type: "answer", id: "0".repeat(32), result: "on" })); + bell.ws.send("not json"); + const res = await pending; + expect(res.status).toBe(202); + expect(got.id).not.toBe("0".repeat(32)); + bell.ws.send(new Uint8Array([1, 2, 3])); + expect((await bell.closed).code).toBe(1003); + }); + + it("answers the keepalive on the doorbell", async () => { + const bell = await listen(); + bell.ws.send("ping"); + expect(await bell.next()).toBe("pong"); + }); +}); From 6a1df060de3338fed706a3194db8337d7a1e0e14 Mon Sep 17 00:00:00 2001 From: flash2do Date: Fri, 6 Nov 2026 00:06:37 -0800 Subject: [PATCH 2/7] Answer the doorbell on the Mac with a Touch ID that names who rang The Worker can now ring, but the Mac had nothing listening while the relay was off. Keysrs.app keeps the doorbell socket open from launch once the person turns it on (keys relay doorbell on, one Touch ID to derive the key), checks each ring's hash against live client tokens and pairings, answers away, pending or not_now without a prompt where nobody should be asked, and otherwise asks for Touch ID naming the token that rang before turning the relay on as keys relay on would. Setup re-derives the key; reset, purge and the kill switch turn the doorbell off and delete it. --- Sources/KeysCore/AppRuntime.swift | 3 + Sources/KeysCore/CLI.swift | 76 ++- Sources/KeysCore/HTTPServer.swift | 21 +- Sources/KeysCore/KeysService.swift | 189 +++++++- Sources/KeysCore/RelayDoorbell.swift | 446 ++++++++++++++++++ .../RelayDoorbellTests.swift | 424 +++++++++++++++++ docs/agents.md | 11 +- docs/cloud-agents.md | 4 +- docs/relay.md | 138 +++++- 9 files changed, 1293 insertions(+), 19 deletions(-) create mode 100644 Sources/KeysCore/RelayDoorbell.swift create mode 100644 Tests/KeysreallysafeTests/RelayDoorbellTests.swift diff --git a/Sources/KeysCore/AppRuntime.swift b/Sources/KeysCore/AppRuntime.swift index 712f427..ff0973b 100644 --- a/Sources/KeysCore/AppRuntime.swift +++ b/Sources/KeysCore/AppRuntime.swift @@ -120,6 +120,7 @@ enum AppRuntime { DispatchQueue.global(qos: .utility).async { service.sweepHeldTokens() } // Before the site serves, so every relay the menu or the dashboard turns on logs here. service.relayHost = RelayHost(log: { logFile.write("relay " + $0) }) + service.doorbellHost = DoorbellHost(log: { logFile.write("relay " + $0) }) // The app owns notifications: the authorization ask and the local-state poll // both run from the app process, never from a CLI or MCP subprocess. let notifications = AppNotifier(preferences: service.preferences) @@ -134,6 +135,8 @@ enum AppRuntime { throw error } guard let server = startedServer else { throw AppError.http("Keysrs could not start its dashboard.") } + // A doorbell the person left on listens again, without Touch ID: it can only ask. + service.startDoorbellAtLaunch() let link = FileManager.default.homeDirectoryForCurrentUser.appendingPathComponent(".local/bin/keys") if CommandLineLink.repairRetired(link: link, retired: root.appendingPathComponent("bin/keys"), binary: binary) { log("command line link moved from the retired runtime to Keysrs.app") diff --git a/Sources/KeysCore/CLI.swift b/Sources/KeysCore/CLI.swift index 54bcea4..a78aeb1 100644 --- a/Sources/KeysCore/CLI.swift +++ b/Sources/KeysCore/CLI.swift @@ -2234,7 +2234,7 @@ struct RelayCommand: ParsableCommand { """, subcommands: [ RelaySetupCommand.self, RelayRunCommand.self, RelayOnCommand.self, RelayOffCommand.self, - RelayStatusCommand.self, RelayResetCommand.self, RelayPairCommand.self, + RelayStatusCommand.self, RelayResetCommand.self, RelayPairCommand.self, RelayDoorbellCommand.self, ], defaultSubcommand: RelayRunCommand.self ) @@ -2262,12 +2262,74 @@ struct RelayCommand: ParsableCommand { return line } + /// The `doorbell` line of `keys relay status`: the choice, and the app's socket if it answers. + static func doorbellLine(enabled: Bool, app: [String: Any]?) -> String { + guard enabled else { return "off" } + guard let app else { return "on (Keysrs is not running, so nobody is listening)" } + switch JSONValue.string(app["doorbell_state"]) { + case "connected": return "on, listening" + case "connecting": return "on, connecting" + case "waiting": + return "on, not connected; retrying" + (JSONValue.string(app["doorbell_last_error"]).map { " (\($0))" } ?? "") + default: return "on, but not listening; run keys relay doorbell on" + } + } + /// The `pairing` line of `keys relay status`: the mode and the live count. static func pairingLine(required: Bool, active: Int) -> String { "\(required ? "required" : "off"), \(active) active" } } +struct RelayDoorbellCommand: ParsableCommand { + static let configuration = CommandConfiguration( + commandName: "doorbell", + abstract: "Let agents ask for the relay while it is off (on: one Touch ID), or not (off, the default).", + discussion: """ + With the doorbell on, Keysrs keeps one more outbound socket to your Worker while it \ + runs. An agent holding one of your client tokens or pairings rings with \ + POST https:///.keysrs/doorbell; this Mac then shows a Touch ID prompt \ + naming that token, and approving it turns the relay on as keys relay on would. \ + Nothing is turned on without that prompt, and a ring with an unknown token, or one \ + while the screen is locked, asks nobody. docs/relay.md, The doorbell. + """ + ) + + @Argument(help: "on, off or status.") var state: String + + func run() throws { try run(launch: .production) } + + func run(launch: AppLaunchSeam, control: URL? = nil, out: (String) -> Void = { print($0) }) throws { + let enabled: Bool + switch state.lowercased() { + case "on": enabled = true + case "off": enabled = false + case "status": + let service = try AppFactory.makeService() + let app = (try? ControlClient.connect(control: control ?? ControlFile.url(beside: service.catalog.path))) + .flatMap { try? $0.call(method: "GET", path: "/api/relay", expect: 200, timeout: 5) } + out("doorbell \(RelayCommand.doorbellLine(enabled: service.doorbellEnabled(), app: app))") + return + default: throw AppError.usage("usage: keys relay doorbell on|off|status") + } + // The app holds the doorbell, as it holds the relay; it asks for the Touch ID. + let client = try AppConnection.connect(control: control, launch: launch).controlClient + if enabled { fputs("Touch ID in Keysrs…\n", stderr) } + let obj = try client.call(method: "POST", path: "/api/relay", body: ["doorbell": enabled], expect: 200) + guard enabled else { + out("doorbell off: agents that ring get 503 doorbell_offline") + return + } + let ring = JSONValue.string(obj["url"]).flatMap { URL(string: $0) }.map(RelayURL.doorbellRingURL) ?? "https:///.keysrs/doorbell" + out(""" + doorbell on: Keysrs listens while it runs, and asks you for Touch ID when an agent rings. + An agent rings with its client token (and its pairing, if pairing is required): + curl -X POST \(ring) -H "Authorization: Bearer $KEYSRS_TOKEN" -H "X-KSF-Pair: $KEYSRS_PAIR" + The Worker must be redeployed from this checkout once to have a doorbell (cd Relay && npx wrangler deploy). + """) + } +} + struct RelayPairCommand: ParsableCommand { static let configuration = CommandConfiguration( commandName: "pair", @@ -2584,9 +2646,10 @@ struct RelayStatusCommand: ParsableCommand { print("set up with: keys relay setup --url https://.workers.dev") } let control = ControlFile.url(beside: service.catalog.path) - if let client = try? ControlClient.connect(control: control), - let obj = try? client.call(method: "GET", path: "/api/relay", expect: 200, timeout: 5) - { + let app = (try? ControlClient.connect(control: control)) + .flatMap { try? $0.call(method: "GET", path: "/api/relay", expect: 200, timeout: 5) } + print("doorbell \(RelayCommand.doorbellLine(enabled: service.doorbellEnabled(), app: app))") + if let obj = app { print("app \(RelayCommand.appLine(obj))") } if let held = RelayLock.holder(at: service.relayLockURL), !held.isApp(control: control) { @@ -2640,6 +2703,11 @@ struct RelayResetCommand: ParsableCommand { _ = try client.call(method: "POST", path: "/api/relay", body: ["enabled": false], expect: 200) out("turned off the relay in Keysrs") } + // The app's doorbell holds the key in memory; it goes off with the relay it rings for. + if JSONValue.bool(obj["doorbell"]) == true { + _ = try client.call(method: "POST", path: "/api/relay", body: ["doorbell": false], expect: 200) + out("turned off the doorbell in Keysrs") + } } try service.resetRelay() out("relay forgotten on this Mac; on the Cloudflare side run: cd Relay && npx wrangler secret delete RELAY_SECRET (or npx wrangler delete)") diff --git a/Sources/KeysCore/HTTPServer.swift b/Sources/KeysCore/HTTPServer.swift index aabc4d8..31f46e2 100644 --- a/Sources/KeysCore/HTTPServer.swift +++ b/Sources/KeysCore/HTTPServer.swift @@ -575,11 +575,12 @@ final class APIHandler: @unchecked Sendable { } /// `enabled` turns this process's relay on (Touch ID here) or off, `stay_awake` and - /// `awake_while_shared` are the idle-sleep choices; any of them, and nothing else. + /// `awake_while_shared` are the idle-sleep choices, `doorbell` lets agents ask for the + /// relay (Touch ID here to turn it on); any of them, and nothing else. private func relaySet(_ request: HTTPRequest) throws -> HTTPResponse { let obj = try jsonBody(request) - guard !obj.isEmpty, Set(obj.keys).isSubset(of: ["enabled", "stay_awake", "awake_while_shared"]) else { - return HTTPResponse.json(400, ["error": "send enabled, stay_awake, awake_while_shared or a mix"]) + guard !obj.isEmpty, Set(obj.keys).isSubset(of: ["enabled", "stay_awake", "awake_while_shared", "doorbell"]) else { + return HTTPResponse.json(400, ["error": "send enabled, stay_awake, awake_while_shared, doorbell or a mix"]) } func flag(_ key: String) throws -> Bool? { guard obj.keys.contains(key) else { return nil } @@ -590,6 +591,7 @@ final class APIHandler: @unchecked Sendable { if let stayAwake = try flag("stay_awake") { try service.setRelayStayAwake(stayAwake) } if let shared = try flag("awake_while_shared") { try service.setRelayAwakeWhileShared(shared) } if let enabled { _ = try service.setRelay(enabled: enabled) } + if let doorbell = try flag("doorbell") { _ = try service.setDoorbell(enabled: doorbell) } return HTTPResponse.json(200, Self.relayJSON(service.relayReport())) } @@ -750,9 +752,22 @@ final class APIHandler: @unchecked Sendable { "active_shares": report.activeShares, "pairing_required": report.pairingRequired, "active_pairings": report.activePairings, + // The doorbell: the person's choice, and its socket while it runs. Never the key. + "doorbell": report.doorbellEnabled, + "doorbell_state": Self.phaseName(report.doorbell.on ? report.doorbell.state.phase : .stopped), + "doorbell_last_error": (report.doorbell.on ? report.doorbell.state.lastError : nil) ?? NSNull(), ] } + static func phaseName(_ phase: RelayClient.Phase) -> String { + switch phase { + case .stopped: return "off" + case .connecting: return "connecting" + case .connected: return "connected" + case .waiting: return "waiting" + } + } + private func clientsList(_ name: String) throws -> HTTPResponse { let now = Date() return HTTPResponse.json(200, [ diff --git a/Sources/KeysCore/KeysService.swift b/Sources/KeysCore/KeysService.swift index ef4fa7f..92bc441 100644 --- a/Sources/KeysCore/KeysService.swift +++ b/Sources/KeysCore/KeysService.swift @@ -69,6 +69,14 @@ final class KeysService: @unchecked Sendable { /// The relay this process runs when it is turned on from the menu, the dashboard or /// `keys relay on`. AppRuntime swaps in one that logs to menubar.log before the site serves. var relayHost = RelayHost() + /// The relay's doorbell (docs/relay.md, The doorbell). The app replaces it with one that + /// logs to menubar.log; tests inject a fake dialer. + var doorbellHost = DoorbellHost() + /// How often a ring may become a Touch ID prompt; tests inject a shorter one. + var doorbellGate = DoorbellGate() + /// Whether the screen is locked, for the doorbell: a prompt behind the lock screen + /// reaches nobody. Tests inject it; nothing else reads it. + var screenLocked: @Sendable () -> Bool = { ScreenLock.isLocked() } /// The app-owned notification service. nil in every non-app process (CLI, MCP, /// tests that do not inject one), so a gateway trip or a pending ask warns only /// from the running app. @@ -1678,12 +1686,20 @@ final class KeysService: @unchecked Sendable { try catalog.setMeta(Self.relayURLMetaKey, url.absoluteString) try catalog.setMeta(Self.relayURLMetaKey + "_secret_hint", RelaySecret.hint(secret)) } + // The doorbell key is derived from the secret just replaced. With the new secret in + // hand, under the Touch ID this setup already took, the doorbell follows it rather + // than keep a key the Worker will refuse once it has the new secret too. + if doorbellEnabled() { + let key = DoorbellKey.derive(relaySecret: secret) + try storeDoorbellKey(key, in: store) + if doorbellHost.isOn { startDoorbell(origin: url, key: key) } + } return (url, secret) } /// The URL and secret `keys relay` connects with. Presence first: the secret is a /// credential and leaves the store only for a connection the person is starting. - func relayCredentials(urlOverride: String? = nil) throws -> (url: URL, secret: String) { + func relayCredentials(urlOverride: String? = nil, reason: String? = nil) throws -> (url: URL, secret: String) { let status = relayStatus() guard let url = try urlOverride.map(RelayURL.validate) ?? status.url else { throw AppError.usage("no relay is set up; run: keys relay setup --url https://.workers.dev") @@ -1694,7 +1710,7 @@ final class KeysService: @unchecked Sendable { guard status.secretHint != nil else { throw AppError.usage("no relay secret is stored; run: keys relay setup --url \(url.absoluteString)") } - try presence.require(reason: "connect the relay to \(url.host ?? url.absoluteString)") + try presence.require(reason: reason ?? "connect the relay to \(url.host ?? url.absoluteString)") let secret: String do { secret = try store.get(name: Self.relaySecretName) @@ -1867,7 +1883,10 @@ final class KeysService: @unchecked Sendable { /// just revoked and the gateway refuses it. @discardableResult func stopRelayForRevoke() -> Bool { - relayToggleLock.withLock { + // The doorbell goes too: after a kill switch every ring would be refused anyway, + // and turning it back on costs a Touch ID like the relay. + stopDoorbell() + return relayToggleLock.withLock { let wasOn = relayHost.isOn relayHost.stop() return wasOn @@ -1889,6 +1908,9 @@ final class KeysService: @unchecked Sendable { /// so `keys relay status` and /api/relay can show the mode without a second question. var pairingRequired = false var activePairings = 0 + /// The doorbell: the person's choice and the socket as it stands. + var doorbellEnabled = false + var doorbell = DoorbellHost.Status(on: false, state: RelayClient.State()) } func relayReport() -> RelayReport { @@ -1905,14 +1927,16 @@ final class KeysService: @unchecked Sendable { awakeWhileShared: preferences.relayAwakeWhileShared, activeShares: ((try? shares()) ?? []).filter { $0.isActive(now: now) }.count, pairingRequired: relayPairingRequired(), - activePairings: pairings.filter { $0.isActive(now: now) }.count + activePairings: pairings.filter { $0.isActive(now: now) }.count, + doorbellEnabled: doorbellEnabled(), + doorbell: doorbellHost.status ) } /// Turns this process's relay on, with one presence check because the secret leaves the /// Keychain, or off. It stays on until turned off or the process quits; nothing turns it /// back on at launch, like the gateway forgets its keys. - func setRelay(enabled: Bool) throws -> RelayReport { + func setRelay(enabled: Bool, presenceReason: String? = nil) throws -> RelayReport { try requireGatewayOwner() try relayToggleLock.withLock { guard enabled else { @@ -1935,7 +1959,7 @@ final class KeysService: @unchecked Sendable { } catch let busy as RelayLock.Held { throw AppError.usage(busy.appRefusal) } - let (origin, secret) = try relayCredentials() + let (origin, secret) = try relayCredentials(reason: presenceReason) relayHost.setStayAwake(preferences.relayStayAwake) relayHost.setStayAwakeWhileShared(preferences.relayAwakeWhileShared, live: shareLiveCheck()) relayHost.start(origin: origin, secret: secret, gatewayPort: port, relayLock: held, pairing: relayPairingVerifier()) @@ -1972,12 +1996,164 @@ final class KeysService: @unchecked Sendable { /// Forgets the URL and deletes the secret. The Worker keeps its copy until /// `wrangler secret delete RELAY_SECRET`, which the command reminds the person of. func resetRelay() throws { + doorbellHost.stop() if let relaySecrets { do { try relaySecrets.delete(name: Self.relaySecretName) } catch AppError.notFound {} + do { try relaySecrets.delete(name: DoorbellKey.accountName) } catch AppError.notFound {} } try catalog.withTransaction { try catalog.deleteMeta(Self.relayURLMetaKey) try catalog.deleteMeta(Self.relayURLMetaKey + "_secret_hint") + try catalog.deleteMeta(Self.doorbellMetaKey) + } + } + + // MARK: - Relay doorbell (docs/relay.md, The doorbell) + + /// The person's choice, in the catalog's meta table beside the relay URL. Absent is off. + static let doorbellMetaKey = "relay_doorbell" + + func doorbellEnabled() -> Bool { + (try? catalog.metaValue(Self.doorbellMetaKey)) == "1" + } + + private func storeDoorbellKey(_ key: String, in store: any SecretStore) throws { + do { + try store.replace(name: DoorbellKey.accountName, secret: key) + } catch AppError.notFound { + try store.add(name: DoorbellKey.accountName, secret: key) + } + } + + /// Turns the doorbell on, with one Touch ID because the key is derived from the relay + /// secret, or off, with none. On, it stays on across launches until turned off, the relay + /// is reset or the kill switch runs: unlike the relay, it can reach nothing, so starting + /// it at launch opens no way in. What it can do is ask, and the answer is a Touch ID here. + func setDoorbell(enabled: Bool) throws -> RelayReport { + try requireGatewayOwner() + guard enabled else { + stopDoorbell() + return relayReport() + } + if doorbellEnabled(), doorbellHost.isOn { return relayReport() } + guard relayStatus().configured else { + throw AppError.usage( + "no relay is set up; deploy the Worker (docs/relay.md), then run: keys relay setup --url https://.workers.dev" + ) + } + let store = try relayStore() + let (origin, secret) = try relayCredentials( + reason: "let agents ring this Mac to ask for the relay at \(relayStatus().url?.host ?? "your Worker")" + ) + let key = DoorbellKey.derive(relaySecret: secret) + try storeDoorbellKey(key, in: store) + try catalog.setMeta(Self.doorbellMetaKey, "1") + startDoorbell(origin: origin, key: key) + return relayReport() + } + + /// Off, and the key leaves the Keychain: turning it on again derives it again. + func stopDoorbell() { + doorbellHost.stop() + try? catalog.deleteMeta(Self.doorbellMetaKey) + if let relaySecrets { + do { try relaySecrets.delete(name: DoorbellKey.accountName) } catch {} + } + } + + /// At launch, in the app: the doorbell the person left on starts again with the stored + /// key, without Touch ID. Anything missing leaves it off and says so in the log. + func startDoorbellAtLaunch() { + guard doorbellEnabled() else { return } + guard let origin = relayStatus().url, let store = relaySecrets, + let key = try? store.get(name: DoorbellKey.accountName), DoorbellKey.looksLikeKey(key) + else { + doorbellHost.log("doorbell left off: its key or the relay URL is missing; run keys relay doorbell on") + return + } + startDoorbell(origin: origin, key: key) + } + + private func startDoorbell(origin: URL, key: String) { + // Re-read before each dial; catalog and relay store only, never a prompt. + let catalog = self.catalog + let store = relaySecrets + let current: @Sendable () -> (url: URL, key: String)? = { + guard (try? catalog.metaValue(KeysService.doorbellMetaKey)) == "1", + let raw = (try? catalog.metaValue(KeysService.relayURLMetaKey)).flatMap({ $0 }), + let url = try? RelayURL.validate(raw), + let key = try? store?.get(name: DoorbellKey.accountName), DoorbellKey.looksLikeKey(key) + else { return nil } + return (url, key) + } + doorbellHost.start(origin: origin, key: key, current: current) { [weak self] ring in + guard let self else { return .unavailable("Keysrs is quitting") } + return self.answerDoorbellRing(ring) + } + } + + /// Who rang: the label of a live client token or pairing whose hash the ring carries, or + /// nil. While pairing is required only a pairing counts, as it would for a relayed call. + /// Catalog reads only, like the relay's pairing check: no Keychain, no prompt. + func doorbellRinger(_ ring: DoorbellRing, now: Date = Date()) -> String? { + func equal(_ a: String, _ b: String) -> Bool { ConstantTime.equal(a.utf8, b.utf8) } + if let hash = ring.pairHash, let pairing = try? catalog.relayPairing(tokenHash: hash), + equal(pairing.tokenHash, hash), pairing.isActive(now: now) + { + return pairing.label + } + if relayPairingRequired() { return nil } + if let hash = ring.clientHash, let client = try? catalog.gatewayClient(tokenHash: hash), + client.isActive(now: now), let stored = try? catalog.tokenHash(clientID: client.id), equal(stored, hash) + { + return client.label + } + return nil + } + + /// One ring, decided here. Everything that needs no person is decided first, so a ring + /// from a stranger, or a ring while the screen is locked, never shows a prompt; then the + /// gate keeps prompts rare; then Touch ID, naming who rang, turns the relay on exactly as + /// `keys relay on` would. + func answerDoorbellRing(_ ring: DoorbellRing, now: @Sendable () -> Date = { Date() }) -> DoorbellAnswer { + if relayHost.isOn { return .on } + guard let ringer = doorbellRinger(ring, now: now()) else { + doorbellHost.log("doorbell: a ring with no live client token or pairing; asked nobody") + return .refused + } + let quoted = "\"\(ringer.prefix(80))\"" + if screenLocked() { + doorbellHost.log("doorbell: \(quoted) rang while the screen is locked; asked nobody") + return .away + } + switch doorbellGate.admit(now: now()) { + case .pending: + return .pending + case .notNow(let after): + doorbellHost.log("doorbell: \(quoted) rang; not asking again for \(after)s") + return .notNow(retryAfter: after) + case .prompt: + break + } + doorbellHost.log("doorbell: \(quoted) rang; asking for Touch ID") + do { + let host = relayStatus().url?.host ?? "your Worker" + _ = try setRelay(enabled: true, presenceReason: "turn on the relay: \(quoted) asked through \(host)") + doorbellGate.finished(declined: false, now: now()) + doorbellHost.log("doorbell: relay turned on for \(quoted)") + return .on + } catch AppError.authCancelled, AppError.authFailed { + doorbellGate.finished(declined: true, now: now()) + doorbellHost.log("doorbell: declined for \(quoted)") + return .declined + } catch { + doorbellGate.finished(declined: false, now: now()) + doorbellHost.log("doorbell: could not turn the relay on for \(quoted): \(error)") + // Only the Mac's own usage refusals (a relay running in a Terminal, no gateway) + // travel back to the agent; anything else stays in the log. + if case AppError.usage(let message) = error { return .unavailable(message) } + if case AppError.authUnavailable = error { return .unavailable("Touch ID could not be shown on the Mac") } + return .unavailable("see menubar.log on the Mac") } } @@ -2191,6 +2367,7 @@ final class KeysService: @unchecked Sendable { } revokeGrants(reason: "purge", caller: "purge") try secrets.deleteAll() + doorbellHost.stop() try relaySecrets?.deleteAll() try heldTokens?.deleteAll() // A catalog the 0.15 app never launched against still carries the meter's tables. diff --git a/Sources/KeysCore/RelayDoorbell.swift b/Sources/KeysCore/RelayDoorbell.swift new file mode 100644 index 0000000..6d7539c --- /dev/null +++ b/Sources/KeysCore/RelayDoorbell.swift @@ -0,0 +1,446 @@ +import CoreGraphics +import CryptoKit +import Foundation + +/// The doorbell (docs/relay.md, The doorbell): while the relay is off, the app may keep one +/// more outbound socket to the same Worker, which carries nothing but "an agent asks for the +/// relay" and this Mac's answer. Turning the relay on still takes a Touch ID, here, by the +/// person at the Mac. The doorbell is a signal plane only: it carries no request, no key, no +/// token, and it cannot turn anything on by itself. +/// +/// Its credential is the doorbell key, derived from the relay secret (`DoorbellKey`), so the +/// Worker needs no second secret; it is kept apart from the relay secret because it has to be +/// readable at launch, without Touch ID, and it cannot be turned back into the relay secret. +enum DoorbellKey { + static let prefix = "ksfd_" + /// The HMAC context; Relay/src/protocol.js (DOORBELL.keyContext) uses the same bytes. + static let context = "keysrs relay doorbell v1" + /// The account under the relay's Keychain service that holds the derived key. + static let accountName = "doorbell" + + static func derive(relaySecret: String) -> String { + let mac = HMAC.authenticationCode( + for: Data(context.utf8), using: SymmetricKey(data: Data(relaySecret.utf8)) + ) + return prefix + Hex.encode(Data(mac)) + } + + static func looksLikeKey(_ value: String) -> Bool { + value.hasPrefix(prefix) && value.count == prefix.count + 64 + } +} + +extension RelayProtocol { + static let doorbellListenPath = "/.keysrs/doorbell/listen" + static let doorbellRingPath = "/.keysrs/doorbell" +} + +extension RelayURL { + static func doorbellListenURL(_ origin: URL) -> URL { + var components = URLComponents(url: origin, resolvingAgainstBaseURL: false)! + components.scheme = components.scheme == "http" ? "ws" : "wss" + components.path = RelayProtocol.doorbellListenPath + return components.url! + } + + /// Where an agent rings. + static func doorbellRingURL(_ origin: URL) -> String { + origin.absoluteString + RelayProtocol.doorbellRingPath + } +} + +/// One ring as the Worker frames it: an id to answer by and the SHA-256 hex of the client +/// token and pairing the agent rang with. The Worker never forwards the credentials +/// themselves, so whoever holds this socket learns nothing they could spend. +struct DoorbellRing: Equatable { + var id: String + var clientHash: String? + var pairHash: String? + + static func parse(_ text: String) -> DoorbellRing? { + guard text.utf8.count <= 4096, + let object = (try? JSONSerialization.jsonObject(with: Data(text.utf8))) as? [String: Any], + object["type"] as? String == "ring", + let id = object["id"] as? String, id.count == 32, id.allSatisfy(\.isHexDigit) + else { return nil } + func hash(_ key: String) -> String? { + guard let value = object[key] as? String, value.count == 64, + value.allSatisfy({ $0.isHexDigit && !$0.isUppercase }) else { return nil } + return value + } + return DoorbellRing(id: id, clientHash: hash("client"), pairHash: hash("pair")) + } +} + +/// This Mac's answer to a ring. The Worker turns each into the agent's status +/// (docs/relay.md, the doorbell's table); the Mac says only which case applies. +enum DoorbellAnswer: Equatable { + /// The relay is on, or was just turned on. + case on + /// A Touch ID prompt for an earlier ring is still up. + case pending + /// The person at the Mac cancelled the prompt. + case declined + /// The credential is not a live client token or pairing here; nobody was asked. + case refused + /// The screen is locked, so nobody is there to ask. + case away + /// Asked too recently; ring again after `retryAfter` seconds. + case notNow(retryAfter: Int) + /// The relay could not be turned on for a reason the person has to fix on the Mac. + case unavailable(String) + + var result: String { + switch self { + case .on: return "on" + case .pending: return "pending" + case .declined: return "declined" + case .refused: return "refused" + case .away: return "away" + case .notNow: return "not_now" + case .unavailable: return "unavailable" + } + } + + func json(id: String) -> String { + var object: [String: Any] = ["type": "answer", "id": id, "result": result] + if case .notNow(let after) = self { object["retry_after"] = after } + // The message is one of the Mac's own refusals, already free of secrets; cut to what + // the Worker passes on. + if case .unavailable(let message) = self { object["message"] = String(message.prefix(400)) } + let data = (try? JSONSerialization.data(withJSONObject: object, options: [.sortedKeys])) ?? Data() + return String(decoding: data, as: UTF8.self) + } +} + +/// How often a ring may become a Touch ID prompt. The Worker already spaces rings ten seconds +/// apart; this is the Mac's own bound, because the Worker is not trusted: one prompt at a +/// time, none for `cooldown` after the person declined one, and at most `perHour` an hour. +/// A prompt nobody can dismiss by accident is the point of Touch ID, and a stream of them +/// would wear that down. +final class DoorbellGate: @unchecked Sendable { + enum Admission: Equatable { + case prompt + case pending + case notNow(retryAfter: Int) + } + + static let defaultCooldown: TimeInterval = 600 + static let defaultPerHour = 6 + + private let lock = NSLock() + private let cooldown: TimeInterval + private let perHour: Int + private var prompting = false + private var declinedAt: Date? + private var prompts: [Date] = [] + + init(cooldown: TimeInterval = DoorbellGate.defaultCooldown, perHour: Int = DoorbellGate.defaultPerHour) { + self.cooldown = cooldown + self.perHour = perHour + } + + /// Takes the one prompt slot, or says why not. A `.prompt` must be followed by `finished`. + func admit(now: Date) -> Admission { + lock.withLock { + if prompting { return .pending } + if let declinedAt, now.timeIntervalSince(declinedAt) < cooldown { + return .notNow(retryAfter: Self.seconds(cooldown - now.timeIntervalSince(declinedAt))) + } + prompts.removeAll { now.timeIntervalSince($0) >= 3600 } + if prompts.count >= perHour, let oldest = prompts.first { + return .notNow(retryAfter: Self.seconds(3600 - now.timeIntervalSince(oldest))) + } + prompting = true + prompts.append(now) + return .prompt + } + } + + func finished(declined: Bool, now: Date) { + lock.withLock { + prompting = false + if declined { declinedAt = now } + } + } + + private static func seconds(_ interval: TimeInterval) -> Int { + max(1, Int(interval.rounded(.up))) + } +} + +/// Whether the console session's screen is locked. A prompt shown behind the lock screen +/// reaches nobody, so a ring then is answered "away" without one. +enum ScreenLock { + static func isLocked() -> Bool { + guard let session = CGSessionCopyCurrentDictionary() as? [String: Any] else { return false } + return (session["CGSSessionScreenIsLocked"] as? Bool) ?? ((session["CGSSessionScreenIsLocked"] as? Int) == 1) + } +} + +/// Holds the doorbell socket: dials, answers the keepalive, hands each ring to `onRing` off +/// the receive loop, sends the answer back, and redials with the relay's backoff until +/// cancelled. It never turns anything on: `onRing` is the service's, and it asks for Touch ID. +final class DoorbellClient: @unchecked Sendable { + struct Options { + var url: URL + var key: String + var pingInterval: TimeInterval = RelayProtocol.pingInterval + var maxBackoff: TimeInterval = 60 + var stableAfter: TimeInterval = 60 + /// Rings handled at once, and per minute. The Worker sends one ring at a time, ten + /// seconds apart; a Worker that does not is not trusted to, and what it sends beyond + /// these is answered `not_now` without reaching the service. + var maxConcurrentRings = 4 + var maxRingsPerMinute = 30 + } + + let options: Options + let dialer: any RelayDialer + /// Status lines; never given the key, a hash or a token. + let log: @Sendable (String) -> Void + let onRing: @Sendable (DoorbellRing) -> DoorbellAnswer + /// Read before every dial: the Worker URL and doorbell key as they are stored now, so a + /// `keys relay setup` in another process (a new secret, so a new key) reaches a doorbell + /// that is already running, and a reset there ends it. nil ends the loop. + let current: (@Sendable () -> (url: URL, key: String)?)? + let sleep: @Sendable (TimeInterval) async throws -> Void + let jitter: @Sendable () -> Double + let now: @Sendable () -> Date + private let lock = NSLock() + private var phase = RelayClient.Phase.stopped + private var lastError: String? + private var lastReceived = Date.distantPast + private var ringsOpen = 0 + private var ringTimes: [Date] = [] + private let ringQueue = DispatchQueue(label: "keysreallysafe.relay.doorbell", attributes: .concurrent) + + init( + options: Options, + dialer: any RelayDialer = URLSessionRelayDialer(), + log: @escaping @Sendable (String) -> Void, + onRing: @escaping @Sendable (DoorbellRing) -> DoorbellAnswer, + current: (@Sendable () -> (url: URL, key: String)?)? = nil, + sleep: @escaping @Sendable (TimeInterval) async throws -> Void = { try await Task.sleep(nanoseconds: UInt64($0 * 1_000_000_000)) }, + jitter: @escaping @Sendable () -> Double = { Double.random(in: 0.8...1.2) }, + now: @escaping @Sendable () -> Date = { Date() } + ) { + self.options = options + self.dialer = dialer + self.log = log + self.onRing = onRing + self.current = current + self.sleep = sleep + self.jitter = jitter + self.now = now + } + + var state: RelayClient.State { + lock.withLock { RelayClient.State(phase: phase, lastError: lastError, inflight: 0) } + } + + var connectHeaders: [String: String] { Self.headers(key: options.key) } + + static func headers(key: String) -> [String: String] { + ["Authorization": "Bearer \(key)", RelayProtocol.protocolHeader: RelayProtocol.version] + } + + private func enter(_ next: RelayClient.Phase) { + lock.withLock { + phase = next + if case .connected = next { lastError = nil } + } + } + + private func failed(_ line: String) { + lock.withLock { lastError = line } + log(line) + } + + func backoff(failures: Int) -> TimeInterval { + min(options.maxBackoff, pow(2.0, Double(max(0, failures - 1)))) * jitter() + } + + func run() async { + var failures = 0 + defer { enter(.stopped) } + while !Task.isCancelled { + let started = Date() + var target = (url: options.url, key: options.key) + if let current { + guard let stored = current() else { + log("doorbell off: its key or the relay URL is no longer stored on this Mac") + break + } + target = stored + } + let host = target.url.host ?? target.url.absoluteString + enter(.connecting) + do { + let socket = try await dialer.connect(url: RelayURL.doorbellListenURL(target.url), headers: Self.headers(key: target.key)) + if Task.isCancelled { + socket.close() + break + } + enter(.connected(since: now())) + log("doorbell listening at \(host)") + try await serve(socket) + } catch is CancellationError { + break + } catch { + if Task.isCancelled { break } + if let dial = error as? RelayDialError, dial.status == 401 { + // The doorbell key is derived from the relay secret: a 401 means the two + // sides hold different secrets, and the relay's own fix applies. + failed("the Worker refused the doorbell key (401): the Worker and this Mac hold different relay secrets; " + + "run keys relay setup, `npx wrangler secret put RELAY_SECRET`, then keys relay doorbell on") + } else if let dial = error as? RelayDialError, let status = dial.status, [404, 426, 502, 503].contains(status) { + // A Worker from before the doorbell relays this path like any call: it + // waits for a Mac and answers 503, or the gateway answers 404. + failed("the Worker answered \(status) instead of opening the doorbell; it may predate it, so redeploy it from this checkout (cd Relay && npx wrangler deploy)") + } else { + failed(error is RelayDialError ? "doorbell: \(error)" : "doorbell connection to \(host) lost: \(error.localizedDescription)") + } + } + if Task.isCancelled { break } + if Date().timeIntervalSince(started) >= options.stableAfter { failures = 0 } + failures += 1 + let delay = backoff(failures: failures) + enter(.waiting(until: now().addingTimeInterval(delay))) + do { try await sleep(delay) } catch { break } + } + } + + /// Reads messages until the socket fails, with the relay's keepalive: a ping every + /// interval, and silence for two of them counts as a dead socket. + func serve(_ socket: any RelaySocket) async throws { + lock.withLock { lastReceived = now() } + let pinger = Task { [weak self, options, sleep] in + while !Task.isCancelled { + try await sleep(options.pingInterval) + guard let self else { return } + let silence = self.now().timeIntervalSince(self.lock.withLock { self.lastReceived }) + if silence > 2 * options.pingInterval { + self.log("doorbell: nothing heard from the Worker for \(Int(silence.rounded()))s; reconnecting") + socket.close() + return + } + socket.sendText("ping") { [weak self] error in + guard error != nil, let self else { return } + self.log("doorbell keepalive ping failed; reconnecting") + socket.close() + } + } + } + defer { + pinger.cancel() + socket.close() + } + while true { + try Task.checkCancellation() + let message = try await withTaskCancellationHandler { + try await socket.receive() + } onCancel: { + socket.close() + } + lock.withLock { lastReceived = now() } + guard case .text(let text) = message, text != "pong" else { continue } + guard let ring = DoorbellRing.parse(text) else { continue } + guard admitRing() else { + socket.sendText(DoorbellAnswer.notNow(retryAfter: 60).json(id: ring.id)) { _ in } + continue + } + // The answer may wait for a Touch ID prompt for minutes; the receive loop must + // keep reading pongs meanwhile, so the ring is answered on its own thread. + let onRing = self.onRing + ringQueue.async { [weak self] in + let answer = onRing(ring) + self?.lock.withLock { self?.ringsOpen -= 1 } + socket.sendText(answer.json(id: ring.id)) { _ in } + } + } + } +} + +extension DoorbellClient { + /// Takes a ring slot within the per-socket bounds, or refuses. + fileprivate func admitRing() -> Bool { + lock.withLock { + let at = now() + ringTimes.removeAll { at.timeIntervalSince($0) >= 60 } + guard ringsOpen < options.maxConcurrentRings, ringTimes.count < options.maxRingsPerMinute else { return false } + ringsOpen += 1 + ringTimes.append(at) + return true + } + } +} + +/// The doorbell as the app runs it: one DoorbellClient from the moment it is started (at +/// launch when the person turned it on, or by `keys relay doorbell on`) until it is stopped. +final class DoorbellHost: @unchecked Sendable { + struct Status: Equatable { + var on: Bool + var state: RelayClient.State + } + + private struct Running { + var client: DoorbellClient + var task: Task + var done: DispatchSemaphore + } + + let log: @Sendable (String) -> Void + private let dialer: any RelayDialer + private let lock = NSLock() + private var running: Running? + + init( + log: @escaping @Sendable (String) -> Void = { line in FileHandle.standardError.write(Data("doorbell \(line)\n".utf8)) }, + dialer: any RelayDialer = URLSessionRelayDialer() + ) { + self.log = log + self.dialer = dialer + } + + var isOn: Bool { lock.withLock { running != nil } } + + var status: Status { + let state = lock.withLock { running?.client.state } + return Status(on: state != nil, state: state ?? RelayClient.State()) + } + + /// Starts listening, replacing a doorbell already running (a new key after relay setup). + func start( + origin: URL, key: String, + current: (@Sendable () -> (url: URL, key: String)?)? = nil, + onRing: @escaping @Sendable (DoorbellRing) -> DoorbellAnswer + ) { + let client = DoorbellClient(options: .init(url: origin, key: key), dialer: dialer, log: log, onRing: onRing, current: current) + let done = DispatchSemaphore(value: 0) + let task = Task.detached { + await client.run() + done.signal() + } + // Swapped under the lock, so two starts at once leave exactly one loop running. + let replaced = lock.withLock { () -> Running? in + defer { running = Running(client: client, task: task, done: done) } + return running + } + if let replaced { + replaced.task.cancel() + _ = replaced.done.wait(timeout: .now() + 2) + } + log("doorbell on; agents ring \(RelayURL.doorbellRingURL(origin)) to ask for the relay") + } + + func stop(wait: TimeInterval = 2, quiet: Bool = false) { + guard let stopping = lock.withLock({ () -> Running? in + defer { running = nil } + return running + }) else { return } + stopping.task.cancel() + _ = stopping.done.wait(timeout: .now() + wait) + if !quiet { log("doorbell off") } + } +} diff --git a/Tests/KeysreallysafeTests/RelayDoorbellTests.swift b/Tests/KeysreallysafeTests/RelayDoorbellTests.swift new file mode 100644 index 0000000..6a3ea3b --- /dev/null +++ b/Tests/KeysreallysafeTests/RelayDoorbellTests.swift @@ -0,0 +1,424 @@ +import Foundation +import XCTest +@testable import KeysCore + +/// The doorbell (docs/relay.md, The doorbell): its key, its wire, how often a ring may become +/// a prompt, its socket loop, and how the service answers a ring. Offline: fake sockets, a +/// recording presence gate, memory secret stores and a temp catalog. +final class RelayDoorbellTests: XCTestCase { + private let origin = URL(string: "https://keysrs-relay.me.workers.dev")! + + // MARK: key and wire + + func testTheKeyMatchesTheWorkersDerivation() { + // Relay/test/doorbell.test.js pins the same value for the same secret. + XCTAssertEqual( + DoorbellKey.derive(relaySecret: "ksfr_test_secret_for_offline_tests_only"), + "ksfd_8e08d4cec8c525bf32a5136871d5275b83fa0d3a18a18025153bc5108c6a5bcf" + ) + let key = DoorbellKey.derive(relaySecret: RelaySecret.generate()) + XCTAssertTrue(DoorbellKey.looksLikeKey(key)) + XCTAssertFalse(DoorbellKey.looksLikeKey(RelaySecret.generate())) + XCTAssertNotEqual(DoorbellKey.derive(relaySecret: RelaySecret.generate()), key, "a new relay secret, a new key") + } + + func testTheListenURLAndRingURLLiveUnderADotPathNoKeyNameCanTake() { + XCTAssertEqual(RelayURL.doorbellListenURL(origin).absoluteString, "wss://keysrs-relay.me.workers.dev/.keysrs/doorbell/listen") + XCTAssertEqual(RelayURL.doorbellListenURL(URL(string: "http://127.0.0.1:8787")!).absoluteString, "ws://127.0.0.1:8787/.keysrs/doorbell/listen") + XCTAssertEqual(RelayURL.doorbellRingURL(origin), "https://keysrs-relay.me.workers.dev/.keysrs/doorbell") + XCTAssertThrowsError(try KeyName.validate(".keysrs")) + } + + func testARingParsesOnlyInTheWorkersShape() { + let id = String(repeating: "a1", count: 16) + let hash = String(repeating: "0f", count: 32) + XCTAssertEqual( + DoorbellRing.parse(#"{"type":"ring","id":"\#(id)","client":"\#(hash)","pair":null}"#), + DoorbellRing(id: id, clientHash: hash, pairHash: nil) + ) + XCTAssertNil(DoorbellRing.parse(#"{"type":"answer","id":"\#(id)"}"#)) + XCTAssertNil(DoorbellRing.parse(#"{"type":"ring","id":"short"}"#)) + XCTAssertNil(DoorbellRing.parse("pong")) + // A hash in any other shape is no hash: it cannot match a stored one anyway. + let upper = DoorbellRing.parse(#"{"type":"ring","id":"\#(id)","client":"\#(hash.uppercased())","pair":"ksfp_x"}"#) + XCTAssertEqual(upper, DoorbellRing(id: id, clientHash: nil, pairHash: nil)) + } + + func testAnAnswerCarriesTheResultAndOnlyWhatTheWorkerPassesOn() throws { + func object(_ answer: DoorbellAnswer) throws -> [String: Any] { + try XCTUnwrap(JSONSerialization.jsonObject(with: Data(answer.json(id: "abc").utf8)) as? [String: Any]) + } + XCTAssertEqual(try object(.on) as NSDictionary, ["type": "answer", "id": "abc", "result": "on"]) + XCTAssertEqual(try object(.notNow(retryAfter: 42))["retry_after"] as? Int, 42) + XCTAssertEqual(try object(.away)["result"] as? String, "away") + let long = try object(.unavailable(String(repeating: "x", count: 1000))) + XCTAssertEqual((long["message"] as? String)?.count, 400) + } + + // MARK: gate + + func testTheGateAllowsOnePromptAtATimeAndBacksOffAfterADecline() { + let gate = DoorbellGate(cooldown: 600, perHour: 6) + let t0 = Date(timeIntervalSince1970: 1_000_000) + XCTAssertEqual(gate.admit(now: t0), .prompt) + XCTAssertEqual(gate.admit(now: t0), .pending, "a prompt is up") + gate.finished(declined: true, now: t0) + XCTAssertEqual(gate.admit(now: t0.addingTimeInterval(1)), .notNow(retryAfter: 599)) + XCTAssertEqual(gate.admit(now: t0.addingTimeInterval(600)), .prompt, "the cooldown is over") + gate.finished(declined: false, now: t0.addingTimeInterval(600)) + } + + func testTheGateCapsPromptsPerHour() { + let gate = DoorbellGate(cooldown: 600, perHour: 3) + let t0 = Date(timeIntervalSince1970: 1_000_000) + for i in 0..<3 { + let at = t0.addingTimeInterval(Double(i) * 60) + XCTAssertEqual(gate.admit(now: at), .prompt) + gate.finished(declined: false, now: at) + } + XCTAssertEqual(gate.admit(now: t0.addingTimeInterval(200)), .notNow(retryAfter: 3400)) + XCTAssertEqual(gate.admit(now: t0.addingTimeInterval(3600)), .prompt, "the first prompt aged out") + } + + // MARK: client + + func testTheClientListensWithTheKeyAnswersRingsAndIgnoresTheRest() async throws { + let socket = FakeRelaySocket() + let dialer = FakeRelayDialer([.success(socket)]) + let seen = LockedValue<[DoorbellRing]>([]) + let key = DoorbellKey.derive(relaySecret: RelaySecret.generate()) + let client = DoorbellClient( + options: .init(url: origin, key: key, pingInterval: 3600), + dialer: dialer, + log: { _ in }, + onRing: { ring in + seen.set(seen.get() + [ring]) + return .declined + }, + sleep: { _ in throw CancellationError() } + ) + let task = Task { await client.run() } + let id = String(repeating: "b2", count: 16) + socket.pushText("pong") + socket.pushText("not json") + socket.pushText(#"{"type":"ring","id":"\#(id)","client":null,"pair":null}"#) + try await until("the answer") { socket.pings.contains { $0.contains(id) } } + let answer = try XCTUnwrap(socket.pings.first { $0.contains(id) }) + XCTAssertEqual( + try JSONSerialization.jsonObject(with: Data(answer.utf8)) as? NSDictionary, + ["type": "answer", "id": id, "result": "declined"] + ) + XCTAssertEqual(seen.get().map(\.id), [id], "only the ring reached onRing") + let attempt = try XCTUnwrap(dialer.attempts.first) + XCTAssertEqual(attempt.0, RelayURL.doorbellListenURL(origin)) + XCTAssertEqual(attempt.1["Authorization"], "Bearer \(key)") + XCTAssertEqual(attempt.1[RelayProtocol.protocolHeader], RelayProtocol.version) + socket.drop() + await task.value + } + + func testRingsBeyondTheBoundsAreAnsweredNotNowWithoutReachingTheService() async throws { + let socket = FakeRelaySocket() + let release = DispatchSemaphore(value: 0) + let calls = LockedValue(0) + var options = DoorbellClient.Options(url: origin, key: DoorbellKey.derive(relaySecret: RelaySecret.generate()), pingInterval: 3600) + options.maxConcurrentRings = 1 + let client = DoorbellClient( + options: options, + dialer: FakeRelayDialer([.success(socket)]), + log: { _ in }, + onRing: { _ in + calls.set(calls.get() + 1) + release.wait() + return .on + }, + sleep: { _ in throw CancellationError() } + ) + let task = Task { await client.run() } + let first = String(repeating: "c3", count: 16), second = String(repeating: "d4", count: 16) + socket.pushText(#"{"type":"ring","id":"\#(first)","client":null,"pair":null}"#) + try await until("the first ring to be handled") { calls.get() == 1 } + socket.pushText(#"{"type":"ring","id":"\#(second)","client":null,"pair":null}"#) + try await until("the second ring's answer") { socket.pings.contains { $0.contains(second) } } + XCTAssertTrue(try XCTUnwrap(socket.pings.first { $0.contains(second) }).contains("not_now")) + XCTAssertEqual(calls.get(), 1, "the second ring never reached the service") + release.signal() + try await until("the first ring's answer") { socket.pings.contains { $0.contains(first) } } + socket.drop() + await task.value + } + + func testEachDialReadsTheStoredKeyAndAGoneKeyEndsTheLoop() async throws { + let first = FakeRelaySocket() + let dialer = FakeRelayDialer([.success(first), .success(FakeRelaySocket())]) + let stored = LockedValue<(url: URL, key: String)?>((origin, DoorbellKey.derive(relaySecret: RelaySecret.generate()))) + let lines = LockedValue<[String]>([]) + let client = DoorbellClient( + options: .init(url: origin, key: "ksfd_stale", pingInterval: 3600), + dialer: dialer, + log: { line in lines.set(lines.get() + [line]) }, + onRing: { _ in .refused }, + current: { stored.get() }, + sleep: { _ in try await Task.sleep(nanoseconds: 1_000_000) } + ) + let task = Task { await client.run() } + try await until("the first dial") { dialer.attempts.count == 1 } + XCTAssertEqual(dialer.attempts[0].1["Authorization"], "Bearer \(stored.get()!.key)", "the stored key, not the one it started with") + stored.set(nil) + first.drop() + await task.value + XCTAssertEqual(dialer.attempts.count, 1, "no dial once the key is gone") + XCTAssertTrue(lines.get().contains { $0.contains("no longer stored") }, "\(lines.get())") + } + + func testAFourOhOneSaysTheTwoSidesHoldDifferentSecrets() async throws { + let lines = LockedValue<[String]>([]) + let client = DoorbellClient( + options: .init(url: origin, key: DoorbellKey.derive(relaySecret: RelaySecret.generate())), + dialer: FakeRelayDialer([.failure(RelayDialError(status: 401, message: "refused"))]), + log: { line in lines.set(lines.get() + [line]) }, + onRing: { _ in .refused }, + sleep: { _ in throw CancellationError() } + ) + await client.run() + XCTAssertTrue(lines.get().contains { $0.contains("different relay secrets") }, "\(lines.get())") + XCTAssertTrue(client.state.lastError?.contains("keys relay doorbell on") == true) + } + + // MARK: service + + private func service() throws -> (KeysService, RecordingPresenceGate, FakeRelayDialer) { + let (db, _) = try makeDB() + let (service, gate) = makeGatedService(db: db) + let dialer = FakeRelayDialer([]) + service.doorbellHost = DoorbellHost(log: { _ in }, dialer: dialer) + service.relayHost = RelayHost(log: { _ in }, dialer: FakeRelayDialer([]), blocker: FakeSleepBlocker()) + service.screenLocked = { false } + return (service, gate, dialer) + } + + private func ring(client: String? = nil, pair: String? = nil) -> DoorbellRing { + DoorbellRing( + id: Hex.encode(SecureRandom.bytes(16)), + clientHash: client.map(GatewayClientToken.hash), + pairHash: pair.map(RelayPairing.hash) + ) + } + + func testTurningTheDoorbellOnTakesOneTouchIDAndKeepsOnlyTheDerivedKey() throws { + let (service, gate, _) = try service() + XCTAssertThrowsError(try service.setDoorbell(enabled: true)) { error in + XCTAssertTrue("\(error)".contains("no relay is set up"), "\(error)") + } + XCTAssertEqual(gate.reasons, [], "refused before Touch ID") + let (_, secret) = try service.setupRelay(url: origin.absoluteString) + let before = gate.reasons.count + + let report = try service.setDoorbell(enabled: true) + XCTAssertEqual(gate.reasons.count, before + 1) + XCTAssertEqual(gate.reasons.last, "let agents ring this Mac to ask for the relay at keysrs-relay.me.workers.dev") + XCTAssertTrue(report.doorbellEnabled) + XCTAssertTrue(report.doorbell.on) + XCTAssertFalse(report.host.on, "the doorbell turns nothing else on") + let stored = try XCTUnwrap(service.relaySecrets).get(name: DoorbellKey.accountName) + XCTAssertEqual(stored, DoorbellKey.derive(relaySecret: secret)) + XCTAssertEqual(try XCTUnwrap(service.relaySecrets).get(name: KeysService.relaySecretName), secret, "the relay secret stays as it was") + + let json = APIHandler.relayJSON(service.relayReport()) + XCTAssertEqual(json["doorbell"] as? Bool, true) + XCTAssertFalse(String(decoding: try JSONValue.data(json), as: UTF8.self).contains(stored), "the key never leaves in the status") + + _ = try service.setDoorbell(enabled: true) + XCTAssertEqual(gate.reasons.count, before + 1, "already on asks for nothing") + + let off = try service.setDoorbell(enabled: false) + XCTAssertFalse(off.doorbellEnabled) + XCTAssertFalse(off.doorbell.on) + XCTAssertThrowsError(try XCTUnwrap(service.relaySecrets).get(name: DoorbellKey.accountName), "off forgets the key") + XCTAssertEqual(gate.reasons.count, before + 1, "off asks for nothing") + } + + func testACancelledPromptLeavesTheDoorbellOff() throws { + let (service, gate, _) = try service() + _ = try service.setupRelay(url: origin.absoluteString) + gate.error = .authCancelled + XCTAssertThrowsError(try service.setDoorbell(enabled: true)) + XCTAssertFalse(service.doorbellEnabled()) + XCTAssertFalse(service.doorbellHost.isOn) + XCTAssertThrowsError(try XCTUnwrap(service.relaySecrets).get(name: DoorbellKey.accountName)) + } + + func testLaunchStartsALeftOnDoorbellWithoutTouchID() throws { + let (service, gate, dialer) = try service() + _ = try service.setupRelay(url: origin.absoluteString) + _ = try service.setDoorbell(enabled: true) + service.doorbellHost.stop() + let prompts = gate.reasons.count + + service.startDoorbellAtLaunch() + XCTAssertTrue(service.doorbellHost.isOn) + XCTAssertEqual(gate.reasons.count, prompts) + _ = dialer + + // A missing key leaves it off rather than asking at launch. + service.doorbellHost.stop() + try XCTUnwrap(service.relaySecrets).delete(name: DoorbellKey.accountName) + service.startDoorbellAtLaunch() + XCTAssertFalse(service.doorbellHost.isOn) + XCTAssertEqual(gate.reasons.count, prompts) + } + + func testSetupAgainRederivesTheKeyAndResetForgetsIt() throws { + let (service, _, _) = try service() + _ = try service.setupRelay(url: origin.absoluteString) + _ = try service.setDoorbell(enabled: true) + let (_, second) = try service.setupRelay(url: origin.absoluteString) + XCTAssertEqual(try XCTUnwrap(service.relaySecrets).get(name: DoorbellKey.accountName), DoorbellKey.derive(relaySecret: second)) + XCTAssertTrue(service.doorbellHost.isOn) + + try service.resetRelay() + XCTAssertFalse(service.doorbellEnabled()) + XCTAssertFalse(service.doorbellHost.isOn) + XCTAssertThrowsError(try XCTUnwrap(service.relaySecrets).get(name: DoorbellKey.accountName)) + } + + func testTheKillSwitchTurnsTheDoorbellOff() throws { + let (service, _, _) = try service() + _ = try service.setupRelay(url: origin.absoluteString) + _ = try service.setDoorbell(enabled: true) + service.stopRelayForRevoke() + XCTAssertFalse(service.doorbellEnabled()) + XCTAssertFalse(service.doorbellHost.isOn) + } + + func testARingWithoutALiveCredentialAsksNobody() throws { + let (service, gate, _) = try service() + try service.add(name: "demo", provider: "anthropic", kind: "runtime", notes: "", secret: fixtureSecret) + _ = try service.setupRelay(url: origin.absoluteString) + // Issuing takes its own Touch ID; the rings below must take none. + let (token, issued) = try service.issueGatewayClient(name: "demo", label: "ci box") + _ = try service.revokeGatewayClient(name: "demo", id: issued.id) + let (expiring, _) = try service.issueGatewayClient(name: "demo", label: "old", days: 1) + let prompts = gate.reasons.count + + XCTAssertEqual(service.answerDoorbellRing(ring()), .refused) + XCTAssertEqual(service.answerDoorbellRing(ring(client: GatewayClientToken.generate())), .refused, "never issued") + XCTAssertEqual(service.answerDoorbellRing(ring(client: token)), .refused, "revoked") + XCTAssertEqual(service.answerDoorbellRing(ring(client: expiring), now: { Date().addingTimeInterval(2 * 86_400) }), .refused, "expired") + XCTAssertEqual(gate.reasons.count, prompts) + } + + func testARingFromALiveTokenAsksForTouchIDNamingItAndTurnsTheRelayOn() throws { + let (service, gate, _) = try service() + try service.add(name: "demo", provider: "anthropic", kind: "runtime", notes: "", secret: fixtureSecret) + _ = try service.setupRelay(url: origin.absoluteString) + _ = try service.startGateway(port: 0) + defer { + service.stopRelay() + service.stopGateway() + } + let (token, _) = try service.issueGatewayClient(name: "demo", label: "hetzner box") + + service.screenLocked = { true } + let prompts = gate.reasons.count + XCTAssertEqual(service.answerDoorbellRing(ring(client: token)), .away) + XCTAssertEqual(gate.reasons.count, prompts, "nobody to ask behind the lock screen") + + service.screenLocked = { false } + XCTAssertEqual(service.answerDoorbellRing(ring(client: token)), .on) + XCTAssertEqual(gate.reasons.last, #"turn on the relay: "hetzner box" asked through keysrs-relay.me.workers.dev"#) + XCTAssertTrue(service.relayHost.isOn) + + let after = gate.reasons.count + XCTAssertEqual(service.answerDoorbellRing(ring(client: token)), .on, "already on") + XCTAssertEqual(gate.reasons.count, after) + } + + func testADeclineIsAnsweredAndTheNextRingWaitsOutTheCooldown() throws { + let (service, gate, _) = try service() + try service.add(name: "demo", provider: "anthropic", kind: "runtime", notes: "", secret: fixtureSecret) + _ = try service.setupRelay(url: origin.absoluteString) + _ = try service.startGateway(port: 0) + defer { service.stopGateway() } + let (token, _) = try service.issueGatewayClient(name: "demo", label: "agent") + + gate.error = .authCancelled + XCTAssertEqual(service.answerDoorbellRing(ring(client: token)), .declined) + XCTAssertFalse(service.relayHost.isOn) + let prompts = gate.reasons.count + guard case .notNow(let after) = service.answerDoorbellRing(ring(client: token)) else { + return XCTFail("the next ring is held back") + } + XCTAssertGreaterThan(after, 500) + XCTAssertEqual(gate.reasons.count, prompts) + } + + func testARelayThatCannotStartIsUnavailableWithTheMacsOwnReason() throws { + let (service, _, _) = try service() + try service.add(name: "demo", provider: "anthropic", kind: "runtime", notes: "", secret: fixtureSecret) + _ = try service.setupRelay(url: origin.absoluteString) + let (token, _) = try service.issueGatewayClient(name: "demo", label: "agent") + // No gateway in this process: the relay would have nothing to reach. + guard case .unavailable(let message) = service.answerDoorbellRing(ring(client: token)) else { + return XCTFail("expected unavailable") + } + XCTAssertTrue(message.contains("gateway is not running"), message) + } + + func testWhilePairingIsRequiredOnlyAPairingRings() throws { + let (service, gate, _) = try service() + try service.add(name: "demo", provider: "anthropic", kind: "runtime", notes: "", secret: fixtureSecret) + _ = try service.setupRelay(url: origin.absoluteString) + _ = try service.startGateway(port: 0) + defer { + service.stopRelay() + service.stopGateway() + } + let (token, _) = try service.issueGatewayClient(name: "demo", label: "agent") + let (credential, _) = try service.issueRelayPairing(label: "paired box", keys: ["demo"]) + try service.setRelayPairingRequired(true) + let prompts = gate.reasons.count + + XCTAssertEqual(service.answerDoorbellRing(ring(client: token)), .refused) + XCTAssertEqual(gate.reasons.count, prompts) + XCTAssertEqual(service.answerDoorbellRing(ring(client: token, pair: credential)), .on) + XCTAssertTrue(gate.reasons.last?.contains(#""paired box""#) == true, "\(gate.reasons)") + } + + func testTheAPITogglesTheDoorbellAndReportsIt() throws { + let (service, gate, _) = try service() + _ = try service.setupRelay(url: origin.absoluteString) + let web = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString, isDirectory: true) + let handler = APIHandler(service: service, webRoot: web) + let on = handle(handler, method: "POST", path: "/api/relay", body: try JSONValue.data(["doorbell": true])) + XCTAssertEqual(on.status, 200, String(decoding: on.body, as: UTF8.self)) + let object = try XCTUnwrap(JSONSerialization.jsonObject(with: on.body) as? [String: Any]) + XCTAssertEqual(object["doorbell"] as? Bool, true) + XCTAssertNotNil(object["doorbell_state"] as? String) + XCTAssertTrue(gate.reasons.last?.hasPrefix("let agents ring this Mac") == true) + + let bad = handle(handler, method: "POST", path: "/api/relay", body: try JSONValue.data(["doorbell": "yes"])) + XCTAssertEqual(bad.status, 400) + let off = handle(handler, method: "POST", path: "/api/relay", body: try JSONValue.data(["doorbell": false])) + XCTAssertEqual(off.status, 200) + XCTAssertFalse(service.doorbellEnabled()) + } + + func testStatusLines() { + XCTAssertEqual(RelayCommand.doorbellLine(enabled: false, app: nil), "off") + XCTAssertEqual(RelayCommand.doorbellLine(enabled: true, app: nil), "on (Keysrs is not running, so nobody is listening)") + XCTAssertEqual(RelayCommand.doorbellLine(enabled: true, app: ["doorbell_state": "connected"]), "on, listening") + XCTAssertEqual( + RelayCommand.doorbellLine(enabled: true, app: ["doorbell_state": "waiting", "doorbell_last_error": "401"]), + "on, not connected; retrying (401)" + ) + } + + private func until(_ what: String, timeout: TimeInterval = 5, _ check: () -> Bool) async throws { + let deadline = Date().addingTimeInterval(timeout) + while !check() { + if Date() > deadline { throw RelayDialError(status: nil, message: "timed out waiting for \(what)") } + try await Task.sleep(nanoseconds: 10_000_000) + } + } +} diff --git a/docs/agents.md b/docs/agents.md index a856d63..babc9af 100644 --- a/docs/agents.md +++ b/docs/agents.md @@ -376,7 +376,12 @@ without opening a port on the Mac. For a managed agent that accepts no inbound SSH — GitHub Actions, Claude Code or Codex cloud sessions, Modal, E2B — the relay is the other route. Both keep every check this page describes; the details and the per-agent snippets are in [cloud-agents.md](cloud-agents.md) -and [relay.md](relay.md). +and [relay.md](relay.md). An agent there that gets 503 `mac_offline` while +the user has the doorbell on can ask for the relay with `POST +https:///.keysrs/doorbell` and its client token. The user then +approves with Touch ID on the Mac: 200 means the relay is on, 202 means the +prompt is still up. Ring once and wait, don't loop: the Mac backs off after +a decline. ## Unwrapping an env file @@ -523,7 +528,9 @@ the parts that bind an agent, stated as rules: closes — that is the protocol, its MCP client keeps it open, so only a client starts it. `keys tunnel --print` prints the ssh command instead; `keys relay on`, `off` and `status` control the app's relay without - blocking. `keys dashboard` is safe in a script: it fronts the app's + blocking, and `keys relay doorbell on|off|status` the doorbell, which lets + an agent on another machine ask for the relay (docs/relay.md, The + doorbell). `keys dashboard` is safe in a script: it fronts the app's window (launching Keysrs when needed), prints one line and returns. - **`keys rm` exits 0 even when the confirm was declined.** Check the output for `cancelled`. An agent should never pass `--yes`, and should diff --git a/docs/cloud-agents.md b/docs/cloud-agents.md index c3fe54b..6b2cef7 100644 --- a/docs/cloud-agents.md +++ b/docs/cloud-agents.md @@ -6,7 +6,9 @@ vault without the key ever leaving the Mac. The mechanism is the same gateway a local agent uses, carried over an SSH reverse forward. For an agent you cannot SSH into (a managed runner or cloud sandbox), [relay.md](relay.md) describes `keys relay`, which carries the same gateway through a Worker you deploy -yourself; the token rules below apply to it unchanged. +yourself; the token rules below apply to it unchanged. With the relay off, +such an agent can ring the relay's doorbell to ask for it, and you approve +with Touch ID on the Mac ([relay.md](relay.md), The doorbell). The rules that make this safe are the same ones the local gateway follows: diff --git a/docs/relay.md b/docs/relay.md index 4aa27a7..00c5e8b 100644 --- a/docs/relay.md +++ b/docs/relay.md @@ -173,6 +173,105 @@ rejection to its default 502 with the code preserved — a refusal either way, so the mismatch fails closed. Redeploying the Worker from this checkout turns the 502 into the precise 403. +## The doorbell + +The relay is off until you turn it on, and an agent on another machine whose +calls get 503 `mac_offline` has no way to tell the Mac. The doorbell is that +way: with it on, an agent asks for the relay, and the Mac asks you. + +```sh +keys relay doorbell on # one Touch ID; stays on across launches +keys relay doorbell status # off, or on and whether Keysrs is listening +keys relay doorbell off # no Touch ID +``` + +The agent rings with the client token it already has, plus its pairing if +the Mac requires pairing: + +```sh +curl -X POST "https:///.keysrs/doorbell" \ + -H "Authorization: Bearer $KEYSRS_TOKEN" -H "X-KSF-Pair: $KEYSRS_PAIR" +``` + +The Mac checks the ring, and if it passes, shows a Touch ID prompt that names +the token or pairing that rang (`turn on the relay: "hetzner box" asked +through `). Approving it turns the relay on exactly as `keys +relay on` would, and the ring is answered 200. Nothing turns the relay on +without that prompt. The Worker needs redeploying from this checkout once +(`cd Relay && npx wrangler deploy`); it needs no new secret. + +**Two planes.** The doorbell is a second socket from the Mac to the same +Worker, kept apart from the relay on purpose. The relay carries requests and +needs the relay secret, which leaves the Keychain only after Touch ID, so it +cannot start on its own at launch. The doorbell carries no request, key or +token, only "an agent asks" and the Mac's answer, so it can start at launch +without Touch ID. Its credential is the **doorbell key**, `ksfd_` + +HMAC-SHA256(relay secret, `keysrs relay doorbell v1`) in hex. The Worker works +it out from `RELAY_SECRET`. The Mac works it out once, under the Touch ID that +`keys relay doorbell on` costs, and keeps it in the Keychain under the relay's +service, account `doorbell`. It cannot be turned back into the relay secret, +and the Worker refuses it at `/connect`, as it refuses the relay secret on the +doorbell. `keys relay setup` works the key out again from the new secret. +`keys relay doorbell off`, `keys relay reset`, `keys revoke --all` and `keys +purge` delete it. + +**The wire.** The Mac opens `GET /.keysrs/doorbell/listen` with `Upgrade: +websocket`, `Authorization: Bearer ` and +`X-Keysrs-Relay-Protocol: 1`, answered like `/connect` (401, 426, 400). Its +frames are text: the same `ping`/`pong` keepalive and silence rules as the +relay, and JSON. A newer doorbell socket replaces an older one (4000 +`replaced`), and the relay socket and the doorbell socket never replace each +other. Both paths start with a dot, so no key name can shadow them. + +``` +Worker → Mac {"type":"ring","id":"<32 hex>","client":""|null,"pair":""|null} +Mac → Worker {"type":"answer","id":"","result":"…","retry_after":,"message":"…"} +``` + +A ring is `POST /.keysrs/doorbell`, with an optional `?wait=` (60 by +default, 120 at most). The Worker reads the client token from the headers the +gateway reads it from (`Authorization: Bearer`, `X-KSF-Client`, `x-api-key`, +`x-goog-api-key`, `api-key`) and the pairing from `X-KSF-Pair`. It checks only +their shape, and forwards **only their SHA-256 hashes**, the form the Mac +stores them in. Whoever holds the doorbell socket never sees a credential they +could spend. The Worker sends at most one ring at a time, and no more than one +every ten seconds. A ring while the relay is connected is answered 200 without +reaching the Mac. A relay that connects while a ring waits answers it 200. + +**The Mac decides.** In this order, and only the last step asks anyone: + +1. The relay is already on → `on`. +2. The hash is not a live (unrevoked, unexpired) client token or pairing on + this Mac → `refused`. While pairing is required, only a pairing counts, as + for a relayed call. +3. The screen is locked → `away`. A prompt behind the lock screen reaches + nobody. +4. A prompt for an earlier ring is still up → `pending`. You declined one in + the last ten minutes, or six prompts have been shown in the last hour → + `not_now`, with when to try again. +5. Touch ID, naming who rang. Approved → the relay turns on → `on`. Cancelled + → `declined`, and the ten-minute quiet period starts. The relay cannot + start (no gateway, `keys relay` running in a Terminal) → `unavailable`, + with the Mac's own reason. + +Every ring and its outcome is a `relay doorbell:` line in menubar.log, with +the token's label and never a hash. + +| status | answer | meaning | +|--------|------------------------------|-----------------------------------------------------------| +| 200 | `{"relay":"on"}` | the relay is on; call the Worker as usual | +| 202 | `{"state":"asking"}` | the Mac is showing the prompt, or the wait ran out; `Retry-After: 15` | +| 401 | `doorbell_credential_required` | no client token or pairing in the Keysrs shape; the Mac was not rung | +| 403 | `doorbell_refused` | the Mac does not know the token or pairing as a live one | +| 403 | `doorbell_declined` | the person at the Mac cancelled the prompt | +| 429 | `doorbell_not_now` | the Mac asked recently; `Retry-After` says when it asks again | +| 503 | `doorbell_offline` | no doorbell is listening: Keysrs not running, the doorbell off, or the Mac asleep or offline; `Retry-After: 60` | +| 503 | `doorbell_busy` | another ring is waiting, or the last was under ten seconds ago; `Retry-After` | +| 503 | `doorbell_mac_locked` | the Mac's screen is locked; `Retry-After: 300` | +| 503 | `doorbell_unavailable` | the relay could not start; the message says why | + +The 503s and the 429 carry `"retryable": true`, and the two 403s do not. + ## Sharing keys with another machine `keys share` is the short way to give one machine — a Linux box, a VPS, a @@ -500,11 +599,16 @@ Mac side with a fake socket against the real gateway on loopback, and idle-sleep assertion with a fake in place of IOKit, `/api/relay`). The Worker suite also pins the pairing surface: each of the four `pairing_*` ERROR codes becoming its 403 with no retry guidance, the other Mac codes staying 502, and -`x-ksf-pair` passing through into the REQUEST frame untouched. On the Mac +`x-ksf-pair` passing through into the REQUEST frame untouched, and +`test/doorbell.test.js` the doorbell: its key, hashes in place of +credentials, each answer's status, one ring at a time, and the relay and +doorbell sockets leaving each other alone. On the Mac side `RelayTests` covers the verification (accept; missing, unknown and malformed credentials; expiry at the boundary; revocation across a reconnect; out-of-scope keys; the credential stripped before replay) and -`RelayPairingTests` the management surface (issue, list, revoke, require +`RelayDoorbellTests` the doorbell (the key matching the Worker's, the ring +and answer shapes, the prompt bounds, and each way a ring is answered without +a prompt), `RelayPairingTests` the management surface (issue, list, revoke, require on/off — including the one Touch ID that turning enforcement off costs, the token-gated `/api/relay/pairings/required` toggle route that `keys relay pair require` delegates to through the control file, and the fail-closed refusal @@ -619,13 +723,34 @@ running it, as a key is while the gateway holds it; the dashboard's `/api/relay` reports the state and the Worker URL, never the secret or its hint. +Someone who learns the **doorbell key** — it sits in the Keychain without a +Touch ID gate, because the doorbell starts at launch — can take over the +doorbell socket. They then get the rings, which carry SHA-256 hashes and no +credential, and can stop rings from reaching the Mac. They cannot open the +relay socket, cannot work out the relay secret, and cannot make the Mac show +a prompt: only the Worker rings, and the Worker rings whoever holds the +newest doorbell socket. `keys relay setup` (a new secret, hence a new key) +and `wrangler secret put RELAY_SECRET` shut them out. + +Someone who controls the **Worker** can ring the Mac whenever they like, with +any hash they have seen pass. That shows you a Touch ID prompt, naming one of +your own tokens, no more than the Mac's own bounds allow: one at a time, none +for ten minutes after you decline, six an hour. Approving one only turns the +relay on. Every request through it still needs a valid token, which is the +position such an attacker is already in. If a prompt you did not expect +appears, cancel it, and treat it like a leaked relay secret. + Someone who learns the **Worker URL** alone can send it requests and burn your Cloudflare request quota, and will be told whether the Mac is online. While the Mac is away they can also fill the 32 waiting slots and the 32 MiB of kept bodies, a minute at a time, so that your agents get `relay_busy` instead of waiting; that is all the window adds. Every one of those requests is refused on the Mac without a token, the waiting ones included once it is -back. +back. They cannot ring the Mac without one of your tokens either: the Worker +sends no ring without a credential in the right shape, and the Mac answers a +hash it does not know with `refused`, asking nobody. Distinguishing `refused` +from the other answers tells them whether a guessed 24-byte token exists, +which the gateway's 401 already tells them for a relayed call. ## What changes in the privacy contract @@ -634,6 +759,13 @@ back. moment you turn it on (one Touch ID) until you turn it off or quit, never at launch by itself, or while `keys relay` runs in a Terminal. One relay at a time. +- With the doorbell on (off by default, `keys relay doorbell on`, one Touch + ID), Keysrs.app also holds a **second** outbound connection to the same + Worker for as long as it runs, from launch, carrying rings and answers and + nothing else. It holds the doorbell key (`ksfd_…`, derived from the relay + secret), stored in the Keychain under the relay's service and account + `doorbell`. A ring reaches the Mac as hashes, and turns nothing on without + a Touch ID. Nothing new binds on the Mac; the gateway and dashboard stay on `127.0.0.1`. - Key values still never leave the Mac. Request bodies still never reach the From ca7ece163f15e72a4780562e86c1754925d70705 Mon Sep 17 00:00:00 2001 From: flash2do Date: Fri, 6 Nov 2026 00:15:08 -0800 Subject: [PATCH 3/7] Keep a doorbell prompt from holding up the kill switch Code review found that a ring's Touch ID prompt ran inside the lock that keys relay off and revoke --all take, so a prompt nobody answered left the kill switch hanging, and an approval that landed after the doorbell was turned off or the token revoked still turned the relay on. The prompt now runs outside that lock and both are checked again after it. Also: rings are spaced per caller address so a made-up token cannot lock out real agents, the Mac caps rings it handles, refusals that never showed a prompt no longer count against the hour, a doorbell loop that ended by itself reads as off, and a restart no longer races the old socket. --- Relay/src/protocol.js | 12 +- Relay/src/worker.js | 25 +++- Relay/test/doorbell.test.js | 23 +++- Sources/KeysCore/KeysService.swift | 109 +++++++++++++----- Sources/KeysCore/RelayDoorbell.swift | 46 +++++--- .../RelayDoorbellTests.swift | 71 +++++++++++- docs/guide.md | 6 +- docs/relay.md | 27 +++-- 8 files changed, 251 insertions(+), 68 deletions(-) diff --git a/Relay/src/protocol.js b/Relay/src/protocol.js index 6b686d0..8862fdf 100644 --- a/Relay/src/protocol.js +++ b/Relay/src/protocol.js @@ -54,16 +54,20 @@ export const DOORBELL = Object.freeze({ listenPath: "/.keysrs/doorbell/listen", ringPath: "/.keysrs/doorbell", keyPrefix: "ksfd_", - // HMAC context for the doorbell key; Relay.swift's DoorbellKey uses the same. + // HMAC context for the doorbell key; DoorbellKey in + // Sources/KeysCore/RelayDoorbell.swift uses the same bytes. keyContext: "keysrs relay doorbell v1", // How long a ringer waits for the Mac's answer by default, and at most // (`?wait=`): long enough to walk to the Mac and touch the sensor. ringWaitMs: 60_000, maxRingWaitMs: 120_000, - // At most one ring reaches the Mac this often, whoever rings: the Worker - // checks no credential, so this is what keeps a stranger who knows the URL - // from making the Mac look up hashes all day. + // One ring per caller address this often. The Worker checks no credential, + // so a single spacing for everyone would let a stranger with a made-up token + // hold it and keep every real agent out; per address, they hold only their + // own. The Mac bounds what reaches it on top (4 at once, 30 a minute). ringIntervalMs: 10_000, + // Addresses remembered for that spacing, at most; memory only, never stored. + maxRingCallers: 1024, }); // The two credentials a ring may carry, in the shape the Mac mints them diff --git a/Relay/src/worker.js b/Relay/src/worker.js index e204b02..07c29f4 100644 --- a/Relay/src/worker.js +++ b/Relay/src/worker.js @@ -172,7 +172,12 @@ export default { if (wait !== null) ring.searchParams.set("wait", wait); return hub.fetch(new Request(ring, { method: "POST", - headers: { "x-ring-client": credentials.client || "", "x-ring-pair": credentials.pair || "" }, + headers: { + "x-ring-client": credentials.client || "", + "x-ring-pair": credentials.pair || "", + // For the per-address spacing only; it stays in the Durable Object's memory. + "x-ring-from": request.headers.get("cf-connecting-ip") || "", + }, })); } return hub.fetch(request); @@ -199,7 +204,8 @@ export class RelayHub extends DurableObject { // open HTTP request, which keeps this object awake for as long as it waits. /** @type {{ id: string, ws: WebSocket, resolve: (answer: object) => void } | null} */ this.ringing = null; - this.lastRingAt = 0; + /** @type {Map} caller address -> when it last rang */ + this.ringTimes = new Map(); // Answered by the runtime without waking a hibernated object. this.ctx.setWebSocketAutoResponse(new WebSocketRequestResponsePair("ping", "pong")); } @@ -315,9 +321,16 @@ export class RelayHub extends DurableObject { if (!bell) return refusal(503, "doorbell_offline", NO_DOORBELL); if (this.ringing) return refusal(503, "doorbell_busy", "another ring is waiting for the Mac's answer"); const now = Date.now(); - const since = now - this.lastRingAt; - if (since < DOORBELL.ringIntervalMs) { - return refusal(503, "doorbell_busy", "the Mac was rung moments ago", Math.ceil((DOORBELL.ringIntervalMs - since) / 1000)); + for (const [from, at] of this.ringTimes) { + if (now - at >= DOORBELL.ringIntervalMs) this.ringTimes.delete(from); + } + const from = request.headers.get("x-ring-from") || ""; + const last = this.ringTimes.get(from); + if (last !== undefined) { + return refusal(503, "doorbell_busy", "you rang moments ago", Math.ceil((DOORBELL.ringIntervalMs - (now - last)) / 1000)); + } + if (this.ringTimes.size >= DOORBELL.maxRingCallers) { + return refusal(503, "doorbell_busy", "too many callers rang in the last few seconds"); } let waitMs = DOORBELL.ringWaitMs; const asked = url.searchParams.get("wait"); @@ -338,7 +351,7 @@ export class RelayHub extends DurableObject { this.ringing = ring; timer = setTimeout(() => ring.resolve({ result: "timeout" }), waitMs); }); - this.lastRingAt = now; + this.ringTimes.set(from, now); try { bell.send(JSON.stringify({ type: "ring", diff --git a/Relay/test/doorbell.test.js b/Relay/test/doorbell.test.js index 280b188..dcdefe0 100644 --- a/Relay/test/doorbell.test.js +++ b/Relay/test/doorbell.test.js @@ -26,7 +26,7 @@ beforeEach(async () => { try { ws.close(1000, "test reset"); } catch { /* already closing */ } } h.ringing = null; - h.lastRingAt = 0; + h.ringTimes.clear(); }); }); @@ -181,7 +181,7 @@ describe("ringing", () => { [{ result: "something new" }, 502, "doorbell_error", undefined], ]; for (const [answer, status, code, retryAfter] of cases) { - await runInDurableObject(hub(), (h) => { h.lastRingAt = 0; }); + await runInDurableObject(hub(), (h) => { h.ringTimes.clear(); }); const { res, bell } = await ringAnswered(answer); expect(res.status, code).toBe(status); const body = await res.json(); @@ -198,7 +198,7 @@ describe("ringing", () => { expect(res.status).toBe(202); expect(await res.json()).toMatchObject({ relay: "off", state: "asking", retryable: true }); - await runInDurableObject(hub(), (h) => { h.lastRingAt = 0; }); + await runInDurableObject(hub(), (h) => { h.ringTimes.clear(); }); const bell = await listen(); const quick = await ring(undefined, "?wait=1"); expect(quick.status).toBe(202); @@ -231,7 +231,7 @@ describe("ringing", () => { expect(second.ws.readyState).toBe(1); }); - it("rings one at a time and no more than every ten seconds", async () => { + it("rings one at a time and no more than every ten seconds per caller", async () => { const bell = await listen(); const first = ring(); const got = JSON.parse(await bell.next()); @@ -248,6 +248,21 @@ describe("ringing", () => { expect(bell.messages).toEqual([]); }); + it("spaces rings per caller, so a stranger's rings do not lock out another agent", async () => { + const bell = await listen(); + // A made-up token from one address: refused on the Mac, and spacing that address only. + const stranger = ring({ authorization: `Bearer ksfc_${"ef".repeat(24)}`, "cf-connecting-ip": "203.0.113.9" }); + const first = JSON.parse(await bell.next()); + bell.ws.send(JSON.stringify({ type: "answer", id: first.id, result: "refused" })); + expect((await stranger).status).toBe(403); + expect((await ring({ authorization: `Bearer ksfc_${"ef".repeat(24)}`, "cf-connecting-ip": "203.0.113.9" })).status).toBe(503); + const agent = ring({ authorization: `Bearer ${CLIENT}`, "cf-connecting-ip": "198.51.100.4" }); + const second = JSON.parse(await bell.next()); + expect(second.client).toBe(CLIENT_HASH); + bell.ws.send(JSON.stringify({ type: "answer", id: second.id, result: "on" })); + expect((await agent).status).toBe(200); + }); + it("fails a waiting ring with doorbell_offline when the doorbell drops", async () => { const bell = await listen(); const pending = ring(); diff --git a/Sources/KeysCore/KeysService.swift b/Sources/KeysCore/KeysService.swift index 92bc441..5ee7a36 100644 --- a/Sources/KeysCore/KeysService.swift +++ b/Sources/KeysCore/KeysService.swift @@ -1711,6 +1711,11 @@ final class KeysService: @unchecked Sendable { throw AppError.usage("no relay secret is stored; run: keys relay setup --url \(url.absoluteString)") } try presence.require(reason: reason ?? "connect the relay to \(url.host ?? url.absoluteString)") + return (url, try storedRelaySecret(store, url: url)) + } + + /// The secret itself. Only ever called right after a presence check that was for it. + private func storedRelaySecret(_ store: any SecretStore, url: URL) throws -> String { let secret: String do { secret = try store.get(name: Self.relaySecretName) @@ -1720,7 +1725,7 @@ final class KeysService: @unchecked Sendable { guard RelaySecret.looksLikeSecret(secret) else { throw AppError.usage("the stored relay secret is not one keys relay setup made; run keys relay setup again") } - return (url, secret) + return secret } var relayLockURL: URL { RelayLock.url(beside: catalog.path) } @@ -1936,7 +1941,7 @@ final class KeysService: @unchecked Sendable { /// Turns this process's relay on, with one presence check because the secret leaves the /// Keychain, or off. It stays on until turned off or the process quits; nothing turns it /// back on at launch, like the gateway forgets its keys. - func setRelay(enabled: Bool, presenceReason: String? = nil) throws -> RelayReport { + func setRelay(enabled: Bool) throws -> RelayReport { try requireGatewayOwner() try relayToggleLock.withLock { guard enabled else { @@ -1944,29 +1949,44 @@ final class KeysService: @unchecked Sendable { return } if relayHost.isOn { return } - // Everything that can be refused without the secret is refused before Touch ID. - guard relayStatus().configured else { - throw AppError.usage( - "no relay is set up; deploy the Worker (docs/relay.md), then run: keys relay setup --url https://.workers.dev" - ) - } - guard let port = gatewayLock.withLock({ gatewayListener?.boundPort }) else { - throw AppError.usage("the gateway is not running in this process, so the relay would have nothing to reach") - } - let held: RelayLock - do { - held = try RelayLock(at: relayLockURL) - } catch let busy as RelayLock.Held { - throw AppError.usage(busy.appRefusal) - } - let (origin, secret) = try relayCredentials(reason: presenceReason) - relayHost.setStayAwake(preferences.relayStayAwake) - relayHost.setStayAwakeWhileShared(preferences.relayAwakeWhileShared, live: shareLiveCheck()) - relayHost.start(origin: origin, secret: secret, gatewayPort: port, relayLock: held, pairing: relayPairingVerifier()) + try startRelayLocked { try relayCredentials() } } return relayReport() } + /// Under relayToggleLock, with the relay off: everything that can be refused without the + /// secret is refused before `credentials`, which is where Touch ID is asked (or was just + /// asked, for the doorbell), and then the relay starts. + private func startRelayLocked(_ credentials: () throws -> (url: URL, secret: String)) throws { + if let refusal = relayStartRefusal() { throw AppError.usage(refusal) } + guard let port = gatewayLock.withLock({ gatewayListener?.boundPort }) else { + throw AppError.usage("the gateway is not running in this process, so the relay would have nothing to reach") + } + let held: RelayLock + do { + held = try RelayLock(at: relayLockURL) + } catch let busy as RelayLock.Held { + throw AppError.usage(busy.appRefusal) + } + let (origin, secret) = try credentials() + relayHost.setStayAwake(preferences.relayStayAwake) + relayHost.setStayAwakeWhileShared(preferences.relayAwakeWhileShared, live: shareLiveCheck()) + relayHost.start(origin: origin, secret: secret, gatewayPort: port, relayLock: held, pairing: relayPairingVerifier()) + } + + /// Why the relay could not start right now, checked without the secret, a prompt or a lock: + /// not set up, no gateway, or `keys relay` holding the one relay in a Terminal. + private func relayStartRefusal() -> String? { + guard relayStatus().configured else { + return "no relay is set up; deploy the Worker (docs/relay.md), then run: keys relay setup --url https://.workers.dev" + } + guard gatewayLock.withLock({ gatewayListener?.boundPort }) != nil else { + return "the gateway is not running in this process, so the relay would have nothing to reach" + } + if !relayHost.isOn, let held = RelayLock.holder(at: relayLockURL) { return held.appRefusal } + return nil + } + /// Whether the relay keeps the Mac from idle sleep while relayed calls are open. Off /// unless the person turns it on; stored, so it applies the next time the relay is on. func setRelayStayAwake(_ on: Bool) throws { @@ -2126,6 +2146,12 @@ final class KeysService: @unchecked Sendable { doorbellHost.log("doorbell: \(quoted) rang while the screen is locked; asked nobody") return .away } + // A relay that could not start anyway is said so before anyone is asked, and before + // the gate counts a prompt that would never be shown. + if let refusal = relayStartRefusal() { + doorbellHost.log("doorbell: \(quoted) rang; the relay cannot start: \(refusal)") + return .unavailable(refusal) + } switch doorbellGate.admit(now: now()) { case .pending: return .pending @@ -2136,18 +2162,47 @@ final class KeysService: @unchecked Sendable { break } doorbellHost.log("doorbell: \(quoted) rang; asking for Touch ID") + let host = relayStatus().url?.host ?? "your Worker" + // Touch ID outside relayToggleLock: a prompt nobody is there to answer must not hold + // up the kill switch or `keys relay off`, which take that lock. What made the ring + // worth asking about is checked again once the person has answered: the doorbell may + // have been turned off, or the kill switch run, or the token revoked, while it was up. do { - let host = relayStatus().url?.host ?? "your Worker" - _ = try setRelay(enabled: true, presenceReason: "turn on the relay: \(quoted) asked through \(host)") - doorbellGate.finished(declined: false, now: now()) - doorbellHost.log("doorbell: relay turned on for \(quoted)") - return .on + try presence.require(reason: "turn on the relay: \(quoted) asked through \(host)") } catch AppError.authCancelled, AppError.authFailed { doorbellGate.finished(declined: true, now: now()) doorbellHost.log("doorbell: declined for \(quoted)") return .declined } catch { - doorbellGate.finished(declined: false, now: now()) + // No prompt was shown, so none is counted. + doorbellGate.finished(declined: false, prompted: false, now: now()) + doorbellHost.log("doorbell: could not ask for Touch ID for \(quoted): \(error)") + return .unavailable("Touch ID could not be shown on the Mac") + } + doorbellGate.finished(declined: false, now: now()) + guard doorbellEnabled() else { + doorbellHost.log("doorbell: approved for \(quoted), but the doorbell was turned off meanwhile; relay left off") + return .unavailable("the doorbell was turned off on the Mac") + } + guard doorbellRinger(ring, now: now()) != nil else { + doorbellHost.log("doorbell: approved for \(quoted), but its token is no longer live; relay left off") + return .refused + } + do { + try requireGatewayOwner() + try relayToggleLock.withLock { + if relayHost.isOn { return } + try startRelayLocked { + // The person approved this start a moment ago; the secret is read for it. + guard let url = relayStatus().url else { + throw AppError.usage("no relay is set up; run: keys relay setup --url https://.workers.dev") + } + return (url, try storedRelaySecret(try relayStore(), url: url)) + } + } + doorbellHost.log("doorbell: relay turned on for \(quoted)") + return .on + } catch { doorbellHost.log("doorbell: could not turn the relay on for \(quoted): \(error)") // Only the Mac's own usage refusals (a relay running in a Terminal, no gateway) // travel back to the agent; anything else stays in the log. diff --git a/Sources/KeysCore/RelayDoorbell.swift b/Sources/KeysCore/RelayDoorbell.swift index 6d7539c..cad4e44 100644 --- a/Sources/KeysCore/RelayDoorbell.swift +++ b/Sources/KeysCore/RelayDoorbell.swift @@ -157,10 +157,13 @@ final class DoorbellGate: @unchecked Sendable { } } - func finished(declined: Bool, now: Date) { + /// `prompted` false: the prompt never appeared (Touch ID unavailable), so it is not + /// counted against the hour. + func finished(declined: Bool, prompted: Bool = true, now: Date) { lock.withLock { prompting = false if declined { declinedAt = now } + if !prompted, !prompts.isEmpty { prompts.removeLast() } } } @@ -393,6 +396,9 @@ final class DoorbellHost: @unchecked Sendable { let log: @Sendable (String) -> Void private let dialer: any RelayDialer private let lock = NSLock() + /// Held across a whole start or stop, so the old loop is gone before a new one dials: + /// two doorbell sockets would evict each other at the Worker. + private let transition = NSLock() private var running: Running? init( @@ -416,31 +422,39 @@ final class DoorbellHost: @unchecked Sendable { current: (@Sendable () -> (url: URL, key: String)?)? = nil, onRing: @escaping @Sendable (DoorbellRing) -> DoorbellAnswer ) { + transition.lock() + defer { transition.unlock() } + stopLocked(wait: 2) let client = DoorbellClient(options: .init(url: origin, key: key), dialer: dialer, log: log, onRing: onRing, current: current) let done = DispatchSemaphore(value: 0) - let task = Task.detached { - await client.run() - done.signal() - } - // Swapped under the lock, so two starts at once leave exactly one loop running. - let replaced = lock.withLock { () -> Running? in - defer { running = Running(client: client, task: task, done: done) } - return running - } - if let replaced { - replaced.task.cancel() - _ = replaced.done.wait(timeout: .now() + 2) + lock.withLock { + let task = Task.detached { [weak self] in + await client.run() + // A loop that ended by itself (its key gone) is off, so turning it on again + // starts a new one instead of finding this one "on". + self?.lock.withLock { if self?.running?.client === client { self?.running = nil } } + done.signal() + } + running = Running(client: client, task: task, done: done) } log("doorbell on; agents ring \(RelayURL.doorbellRingURL(origin)) to ask for the relay") } - func stop(wait: TimeInterval = 2, quiet: Bool = false) { + func stop(wait: TimeInterval = 2) { + transition.lock() + defer { transition.unlock() } + if stopLocked(wait: wait) { log("doorbell off") } + } + + /// Under `transition`. Says whether a loop was running. + @discardableResult + private func stopLocked(wait: TimeInterval) -> Bool { guard let stopping = lock.withLock({ () -> Running? in defer { running = nil } return running - }) else { return } + }) else { return false } stopping.task.cancel() _ = stopping.done.wait(timeout: .now() + wait) - if !quiet { log("doorbell off") } + return true } } diff --git a/Tests/KeysreallysafeTests/RelayDoorbellTests.swift b/Tests/KeysreallysafeTests/RelayDoorbellTests.swift index 6a3ea3b..b83e4e3 100644 --- a/Tests/KeysreallysafeTests/RelayDoorbellTests.swift +++ b/Tests/KeysreallysafeTests/RelayDoorbellTests.swift @@ -190,7 +190,8 @@ final class RelayDoorbellTests: XCTestCase { private func service() throws -> (KeysService, RecordingPresenceGate, FakeRelayDialer) { let (db, _) = try makeDB() let (service, gate) = makeGatedService(db: db) - let dialer = FakeRelayDialer([]) + // Sockets nobody feeds stay open, as a listening doorbell does. + let dialer = FakeRelayDialer((0..<8).map { _ in .success(FakeRelaySocket()) }) service.doorbellHost = DoorbellHost(log: { _ in }, dialer: dialer) service.relayHost = RelayHost(log: { _ in }, dialer: FakeRelayDialer([]), blocker: FakeSleepBlocker()) service.screenLocked = { false } @@ -318,6 +319,7 @@ final class RelayDoorbellTests: XCTestCase { service.stopGateway() } let (token, _) = try service.issueGatewayClient(name: "demo", label: "hetzner box") + _ = try service.setDoorbell(enabled: true) service.screenLocked = { true } let prompts = gate.reasons.count @@ -365,6 +367,72 @@ final class RelayDoorbellTests: XCTestCase { XCTAssertTrue(message.contains("gateway is not running"), message) } + /// The kill switch run while the prompt is up must not wait for it (it would deadlock + /// here if the prompt held the relay's toggle lock), and an approval that lands after it + /// turns nothing on. + func testTheKillSwitchDuringThePromptWinsOverTheApproval() throws { + let (service, gate, _) = try service() + try service.add(name: "demo", provider: "anthropic", kind: "runtime", notes: "", secret: fixtureSecret) + _ = try service.setupRelay(url: origin.absoluteString) + _ = try service.startGateway(port: 0) + defer { + service.stopRelay() + service.stopGateway() + } + let (token, _) = try service.issueGatewayClient(name: "demo", label: "agent") + _ = try service.setDoorbell(enabled: true) + gate.duringNextPrompt = { _ = service.stopRelayForRevoke() } + + XCTAssertEqual(service.answerDoorbellRing(ring(client: token)), .unavailable("the doorbell was turned off on the Mac")) + XCTAssertFalse(service.relayHost.isOn) + XCTAssertFalse(service.doorbellEnabled()) + } + + func testATokenRevokedWhileThePromptIsUpTurnsNothingOn() throws { + let (service, gate, _) = try service() + try service.add(name: "demo", provider: "anthropic", kind: "runtime", notes: "", secret: fixtureSecret) + _ = try service.setupRelay(url: origin.absoluteString) + _ = try service.startGateway(port: 0) + defer { + service.stopRelay() + service.stopGateway() + } + let (token, issued) = try service.issueGatewayClient(name: "demo", label: "agent") + _ = try service.setDoorbell(enabled: true) + gate.duringNextPrompt = { _ = try service.revokeGatewayClient(name: "demo", id: issued.id) } + + XCTAssertEqual(service.answerDoorbellRing(ring(client: token)), .refused) + XCTAssertFalse(service.relayHost.isOn) + } + + func testRingsTheRelayCouldNotServeAreNotCountedAgainstTheHour() throws { + let (service, gate, _) = try service() + try service.add(name: "demo", provider: "anthropic", kind: "runtime", notes: "", secret: fixtureSecret) + _ = try service.setupRelay(url: origin.absoluteString) + let (token, _) = try service.issueGatewayClient(name: "demo", label: "agent") + _ = try service.setDoorbell(enabled: true) + let prompts = gate.reasons.count + for _ in 0..<(DoorbellGate.defaultPerHour + 2) { + guard case .unavailable = service.answerDoorbellRing(ring(client: token)) else { return XCTFail("no gateway yet") } + } + XCTAssertEqual(gate.reasons.count, prompts, "nobody was asked") + _ = try service.startGateway(port: 0) + defer { + service.stopRelay() + service.stopGateway() + } + XCTAssertEqual(service.answerDoorbellRing(ring(client: token)), .on, "the hour's allowance is untouched") + } + + func testADoorbellWhoseLoopEndedIsOffAndStartsAgain() async throws { + let host = DoorbellHost(log: { _ in }, dialer: FakeRelayDialer([])) + host.start(origin: origin, key: "ksfd_x", current: { nil }, onRing: { _ in .refused }) + try await until("the loop to end by itself") { !host.isOn } + host.start(origin: origin, key: "ksfd_x", onRing: { _ in .refused }) + XCTAssertTrue(host.isOn) + host.stop() + } + func testWhilePairingIsRequiredOnlyAPairingRings() throws { let (service, gate, _) = try service() try service.add(name: "demo", provider: "anthropic", kind: "runtime", notes: "", secret: fixtureSecret) @@ -377,6 +445,7 @@ final class RelayDoorbellTests: XCTestCase { let (token, _) = try service.issueGatewayClient(name: "demo", label: "agent") let (credential, _) = try service.issueRelayPairing(label: "paired box", keys: ["demo"]) try service.setRelayPairingRequired(true) + _ = try service.setDoorbell(enabled: true) let prompts = gate.reasons.count XCTAssertEqual(service.answerDoorbellRing(ring(client: token)), .refused) diff --git a/docs/guide.md b/docs/guide.md index eaf6cd0..4a98709 100644 --- a/docs/guide.md +++ b/docs/guide.md @@ -84,7 +84,11 @@ Touch ID). On a Mac whose 0.9.x install was never upgraded, `keys autostart Terminal), and feeds what arrives into the same loopback gateway with the same token checks. Relayed requests can additionally be restricted to agents you have paired with the Mac. Keys never leave the Mac over it; see - [docs/relay.md](relay.md). + [docs/relay.md](relay.md). If you turn the relay's doorbell on (off by + default, one Touch ID), Keysrs also keeps a second outbound connection to + the same Worker from launch, which only lets an agent holding one of your + tokens ask for the relay: nothing turns on until you approve a Touch ID + prompt on the Mac. - The app sends no analytics or telemetry. - Update checks send one cookieless request to GitHub's public latest-release API and read only the release's version and download diff --git a/docs/relay.md b/docs/relay.md index 00c5e8b..2966171 100644 --- a/docs/relay.md +++ b/docs/relay.md @@ -234,9 +234,15 @@ gateway reads it from (`Authorization: Bearer`, `X-KSF-Client`, `x-api-key`, `x-goog-api-key`, `api-key`) and the pairing from `X-KSF-Pair`. It checks only their shape, and forwards **only their SHA-256 hashes**, the form the Mac stores them in. Whoever holds the doorbell socket never sees a credential they -could spend. The Worker sends at most one ring at a time, and no more than one -every ten seconds. A ring while the relay is connected is answered 200 without -reaching the Mac. A relay that connects while a ring waits answers it 200. +could spend. The Worker sends one ring at a time, and takes at most one ring +every ten seconds from each caller address. The spacing is per address +because the Worker cannot tell a real token from a made-up one: one spacing +for everyone would let a stranger keep every real agent out. The Mac adds its +own bounds on top, whatever the Worker sends: four rings at once and thirty a +minute, past which it answers `not_now` without looking. A ring while the +relay is connected is answered 200 without reaching the Mac, which tells a +stranger with a well-shaped token no more than a relayed call's 503 already +does. A relay that connects while a ring waits answers it 200. **The Mac decides.** In this order, and only the last step asks anyone: @@ -245,14 +251,17 @@ reaching the Mac. A relay that connects while a ring waits answers it 200. this Mac → `refused`. While pairing is required, only a pairing counts, as for a relayed call. 3. The screen is locked → `away`. A prompt behind the lock screen reaches - nobody. + nobody. The relay could not start anyway (no gateway, `keys relay` running + in a Terminal) → `unavailable`, with the Mac's own reason. 4. A prompt for an earlier ring is still up → `pending`. You declined one in the last ten minutes, or six prompts have been shown in the last hour → `not_now`, with when to try again. -5. Touch ID, naming who rang. Approved → the relay turns on → `on`. Cancelled - → `declined`, and the ten-minute quiet period starts. The relay cannot - start (no gateway, `keys relay` running in a Terminal) → `unavailable`, - with the Mac's own reason. +5. Touch ID, naming who rang. Cancelled → `declined`, and the ten-minute + quiet period starts. Approved → the doorbell must still be on and the token + still live, since either can change while the prompt is up. Then the relay + turns on → `on`. The prompt is shown outside the lock that turning the + relay on and off shares, so `keys relay off` and the kill switch never wait + for a prompt that nobody answers. Every ring and its outcome is a `relay doorbell:` line in menubar.log, with the token's label and never a hash. @@ -266,7 +275,7 @@ the token's label and never a hash. | 403 | `doorbell_declined` | the person at the Mac cancelled the prompt | | 429 | `doorbell_not_now` | the Mac asked recently; `Retry-After` says when it asks again | | 503 | `doorbell_offline` | no doorbell is listening: Keysrs not running, the doorbell off, or the Mac asleep or offline; `Retry-After: 60` | -| 503 | `doorbell_busy` | another ring is waiting, or the last was under ten seconds ago; `Retry-After` | +| 503 | `doorbell_busy` | another ring is waiting, or this address rang under ten seconds ago; `Retry-After` | | 503 | `doorbell_mac_locked` | the Mac's screen is locked; `Retry-After: 300` | | 503 | `doorbell_unavailable` | the relay could not start; the message says why | From d33f8e2a49d309300fbacccb474689c4230db854 Mon Sep 17 00:00:00 2001 From: flash2do Date: Fri, 6 Nov 2026 00:24:21 -0800 Subject: [PATCH 4/7] Read the fake relay dialer's attempts under its lock ThreadSanitizer on CI caught the doorbell test polling FakeRelayDialer's attempts while the loop under test appended to them under the dialer's lock; the read now takes the same lock. --- Tests/KeysreallysafeTests/RelayTests.swift | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/Tests/KeysreallysafeTests/RelayTests.swift b/Tests/KeysreallysafeTests/RelayTests.swift index 27a55ca..d5e53dd 100644 --- a/Tests/KeysreallysafeTests/RelayTests.swift +++ b/Tests/KeysreallysafeTests/RelayTests.swift @@ -76,7 +76,9 @@ final class FakeRelaySocket: RelaySocket, @unchecked Sendable { final class FakeRelayDialer: RelayDialer, @unchecked Sendable { private let lock = NSLock() private var outcomes: [Result] - private(set) var attempts: [(URL, [String: String])] = [] + private var recorded: [(URL, [String: String])] = [] + /// Read under the lock: a test may poll it while the loop under test is still dialing. + var attempts: [(URL, [String: String])] { lock.withLock { recorded } } init(_ outcomes: [Result]) { self.outcomes = outcomes @@ -84,7 +86,7 @@ final class FakeRelayDialer: RelayDialer, @unchecked Sendable { func connect(url: URL, headers: [String: String]) async throws -> any RelaySocket { let next: Result? = lock.withLock { - attempts.append((url, headers)) + recorded.append((url, headers)) return outcomes.isEmpty ? nil : outcomes.removeFirst() } guard let next else { throw CancellationError() } From b81b5f54e030f6437fe5a1e114c1189646d74381 Mon Sep 17 00:00:00 2001 From: flash2do Date: Fri, 6 Nov 2026 00:26:14 -0800 Subject: [PATCH 5/7] Approve keys relay doorbell in the app launch caller map The full suite pins which commands may launch the app and which read it gracefully; the doorbell verbs follow keys relay on/off and keys relay status, so they join those two sets. --- Tests/KeysreallysafeTests/AppLaunchSeamTests.swift | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/Tests/KeysreallysafeTests/AppLaunchSeamTests.swift b/Tests/KeysreallysafeTests/AppLaunchSeamTests.swift index 11b21f2..952f025 100644 --- a/Tests/KeysreallysafeTests/AppLaunchSeamTests.swift +++ b/Tests/KeysreallysafeTests/AppLaunchSeamTests.swift @@ -389,7 +389,7 @@ final class AppLaunchSeamTests: XCTestCase { Set(seamRouted.keys), ["GrantCommand", "GrantsCommand", "RevokeCommand", "RenewCommand", "GatewayCommand", "WrapCommand", "AgentCommand", "RelayOnCommand", "RelayOffCommand", "TunnelCommand", "RelayRunCommand", - "DashboardCommand", "ClientTokenCommand", "ClientIssueCommand"], + "DashboardCommand", "ClientTokenCommand", "ClientIssueCommand", "RelayDoorbellCommand"], "exactly the eligible population routes through AppConnection.connect" ) @@ -401,13 +401,15 @@ final class AppLaunchSeamTests: XCTestCase { // call inline, and the pin below covers the shared helper. // UnwrapCommand is the onboarding slice's `keys unwrap`: it deliberately // keeps the plain client and never auto-launches (a script gets exit 6). + // `keys relay doorbell` mirrors the relay verbs: on and off launch the app like + // keys relay on, status reads it gracefully like keys relay status. // The `keys share` verbs mirror client and pair issue: the running app when // there is one, the catalog otherwise, and no launch. let graceful = blocks.filter { _, body in body.contains("ControlClient.connect") } XCTAssertEqual( Set(graceful.keys), ["ListCommand", "ProvidersCommand", "ClientIssueCommand", "AgentCommand", "RelayPairIssueCommand", - "RelayPairRequireCommand", "RelayStatusCommand", "UnwrapCommand", + "RelayPairRequireCommand", "RelayStatusCommand", "RelayDoorbellCommand", "UnwrapCommand", "ShareIssueCommand", "ShareRevokeCommand", "ShareAwakeCommand"], "exactly the graceful population keeps the plain control client" ) From 33596aab4a1af23f31893187eac953c72989802b Mon Sep 17 00:00:00 2001 From: flash2do Date: Fri, 6 Nov 2026 00:34:57 -0800 Subject: [PATCH 6/7] Wait for the relay to connect before asserting its socket closed Two RelayHostTests turned the relay off right after turning it on and then asserted the fake socket was closed. When the stop landed before the loop had dialed, there was no socket to close and the test failed on timing alone (seen on this PR's ThreadSanitizer runs and on main). Both now wait for the connection first. --- Tests/KeysreallysafeTests/RelayHostTests.swift | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/Tests/KeysreallysafeTests/RelayHostTests.swift b/Tests/KeysreallysafeTests/RelayHostTests.swift index b759e89..5a43d11 100644 --- a/Tests/KeysreallysafeTests/RelayHostTests.swift +++ b/Tests/KeysreallysafeTests/RelayHostTests.swift @@ -359,6 +359,17 @@ final class RelayHostTests: XCTestCase { // MARK: service and API + /// Until the relay's loop has its socket. A stop that lands first cancels the dial, and + /// a test asserting the socket was closed then fails on timing alone. + private func waitConnected(_ service: KeysService, timeout: TimeInterval = 5) throws { + let deadline = Date().addingTimeInterval(timeout) + while true { + if case .connected = service.relayHost.status.state.phase { return } + if Date() > deadline { throw RelayDialError(status: nil, message: "the relay never connected") } + Thread.sleep(forTimeInterval: 0.01) + } + } + private func gatedService() throws -> (KeysService, RecordingPresenceGate) { let (db, _) = try makeDB() return makeGatedService(db: db) @@ -402,6 +413,9 @@ final class RelayHostTests: XCTestCase { _ = try service.setRelay(enabled: true) XCTAssertEqual(gate.reasons.count, afterSetup + 1, "already on asks for nothing") + // Off before the loop has dialed leaves no socket to close; wait for the one the + // assertion below is about. + try waitConnected(service) let off = try service.setRelay(enabled: false) XCTAssertFalse(off.host.on) XCTAssertTrue(socket.closed) @@ -427,6 +441,7 @@ final class RelayHostTests: XCTestCase { } XCTAssertTrue(try service.setRelay(enabled: true).host.on) + try waitConnected(service) let prompts = gate.reasons.count let scoped = try revokeAll(["key": "demo"]) From 574121cd43abaadd0ff9636a7dcf853292c0be49 Mon Sep 17 00:00:00 2001 From: flash2do Date: Fri, 6 Nov 2026 10:44:03 -0800 Subject: [PATCH 7/7] Prevent stale doorbell approvals and preserve existing relay sockets A completed shutdown could be followed by a pending approval starting the relay. Serialize final validity and start with shutdown, invalidate outstanding approvals on off, and serialize credential revocation through the catalog transaction while keeping Touch ID outside the toggle lock. Workers retain pre-update hibernating sockets without doorbell tags. Discover and replace those legacy relay sockets by their attachment without treating doorbells as relays; cover both blockers with deterministic offline regressions. --- Relay/src/worker.js | 18 ++- Relay/test/doorbell.test.js | 54 ++++++++ Sources/KeysCore/KeysService.swift | 84 ++++++++---- .../RelayDoorbellTests.swift | 122 ++++++++++++++++++ 4 files changed, 247 insertions(+), 31 deletions(-) diff --git a/Relay/src/worker.js b/Relay/src/worker.js index 07c29f4..9258ef9 100644 --- a/Relay/src/worker.js +++ b/Relay/src/worker.js @@ -231,13 +231,25 @@ export class RelayHub extends DurableObject { return this.newest("doorbell"); } + /// Deferred Worker updates keep hibernating sockets alive. Before the doorbell, + /// /connect accepted untagged sockets with only connectedAt in the attachment. + /// They are still relay sockets, including when a new Mac replaces the old one. + /// Doorbells always have an explicit kind and must never enter that fallback. + sockets(kind) { + return this.ctx.getWebSockets().filter((ws) => { + const attachment = ws.deserializeAttachment(); + return attachment?.kind === kind || + (kind === "mac" && attachment?.kind === undefined && Number.isFinite(attachment?.connectedAt)); + }); + } + /// The most recently accepted open socket of one kind that has been heard /// from within the silence limit. newest(tag) { const now = Date.now(); let best = null; let bestAt = -1; - for (const ws of this.ctx.getWebSockets(tag)) { + for (const ws of this.sockets(tag)) { if (ws.readyState !== 1 /* OPEN */) continue; const at = ws.deserializeAttachment()?.connectedAt ?? 0; if (!this.heardRecently(ws, at, now)) continue; @@ -286,7 +298,7 @@ export class RelayHub extends DurableObject { const [client, server] = Object.values(pair); // One Mac per relay: a reconnecting Mac must not wait for a stale socket // to time out, so the newcomer wins and the old socket is told why. - for (const old of this.ctx.getWebSockets("mac")) { + for (const old of this.sockets("mac")) { this.failAll(old, 502, "mac_disconnected", "the Mac reconnected while this request was in flight; it may be retried"); try { old.close(4000, "replaced"); } catch { /* already gone */ } } @@ -303,7 +315,7 @@ export class RelayHub extends DurableObject { listen() { const pair = new WebSocketPair(); const [client, server] = Object.values(pair); - for (const old of this.ctx.getWebSockets("doorbell")) { + for (const old of this.sockets("doorbell")) { if (this.ringing?.ws === old) this.ringing.resolve({ result: "offline" }); try { old.close(4000, "replaced"); } catch { /* already gone */ } } diff --git a/Relay/test/doorbell.test.js b/Relay/test/doorbell.test.js index dcdefe0..255a79b 100644 --- a/Relay/test/doorbell.test.js +++ b/Relay/test/doorbell.test.js @@ -292,3 +292,57 @@ describe("ringing", () => { expect(await bell.next()).toBe("pong"); }); }); + + +describe("relay sockets kept across the doorbell Worker update", () => { + function legacyRelay(h) { + const [client, server] = Object.values(new WebSocketPair()); + // The pre-doorbell Worker accepted without tags or a kind attachment. + h.ctx.acceptWebSocket(server); + server.serializeAttachment({ connectedAt: Date.now() }); + client.accept(); + return { client, server }; + } + + it("discovers a legacy relay and reports it on without ringing the doorbell", async () => { + await runInDurableObject(hub(), async (h) => { + const legacy = legacyRelay(h); + const bell = h.listen().webSocket; + bell.accept(); + try { + expect(h.mac()).toBe(legacy.server); + expect(h.doorbell().deserializeAttachment().kind).toBe("doorbell"); + const request = new Request(`${ORIGIN}${DOORBELL.ringPath}`, { method: "POST" }); + expect((await h.fetch(request)).status).toBe(200); + expect(h.ringing).toBeNull(); + expect(legacy.server.readyState).toBe(1); + } finally { + legacy.client.close(1000, "test done"); + bell.close(1000, "test done"); + } + }); + }); + + it("replaces the legacy relay on reconnect without closing the doorbell", async () => { + await runInDurableObject(hub(), async (h) => { + const legacy = legacyRelay(h); + const bell = h.listen().webSocket; + bell.accept(); + const closed = new Promise((resolve) => legacy.client.addEventListener("close", resolve)); + const current = h.connect().webSocket; + current.accept(); + try { + // Check synchronously too: a tag-only replacement would leave it OPEN. + expect(legacy.server.readyState).not.toBe(1); + const event = await withTimeout(closed, 5000, "legacy relay replacement"); + expect({ code: event.code, reason: event.reason }).toEqual({ code: 4000, reason: "replaced" }); + expect(h.mac().deserializeAttachment().kind).toBe("mac"); + expect(h.doorbell().readyState).toBe(1); + } finally { + legacy.client.close(1000, "test done"); + current.close(1000, "test done"); + bell.close(1000, "test done"); + } + }); + }); +}); diff --git a/Sources/KeysCore/KeysService.swift b/Sources/KeysCore/KeysService.swift index 5ee7a36..ee74f9f 100644 --- a/Sources/KeysCore/KeysService.swift +++ b/Sources/KeysCore/KeysService.swift @@ -97,6 +97,9 @@ final class KeysService: @unchecked Sendable { /// Held while the relay is turned on or off, so two toggles at once (menu and dashboard) /// cannot both find it off and race for the lock. private let relayToggleLock = NSLock() + /// A shutdown cancels approvals already in flight, even if the doorbell stays enabled + /// (relay off) or is enabled again before Touch ID returns. Under relayToggleLock. + private var relayApprovalGeneration: UInt64 = 0 var checker: any ProviderCheckFetching = ProviderCheckHTTP() /// The persisted app choices (menu-bar item, updates, relay, welcome). let preferences: AppPreferences @@ -1890,8 +1893,8 @@ final class KeysService: @unchecked Sendable { func stopRelayForRevoke() -> Bool { // The doorbell goes too: after a kill switch every ring would be refused anyway, // and turning it back on costs a Touch ID like the relay. - stopDoorbell() return relayToggleLock.withLock { + stopDoorbellLocked() let wasOn = relayHost.isOn relayHost.stop() return wasOn @@ -1945,6 +1948,7 @@ final class KeysService: @unchecked Sendable { try requireGatewayOwner() try relayToggleLock.withLock { guard enabled else { + relayApprovalGeneration &+= 1 relayHost.stop() return } @@ -2010,21 +2014,27 @@ final class KeysService: @unchecked Sendable { /// For quitting: no presence, no owner check, whatever is in progress. func stopRelay() { - relayHost.stop() + relayToggleLock.withLock { + relayApprovalGeneration &+= 1 + relayHost.stop() + } } /// Forgets the URL and deletes the secret. The Worker keeps its copy until /// `wrangler secret delete RELAY_SECRET`, which the command reminds the person of. func resetRelay() throws { - doorbellHost.stop() - if let relaySecrets { - do { try relaySecrets.delete(name: Self.relaySecretName) } catch AppError.notFound {} - do { try relaySecrets.delete(name: DoorbellKey.accountName) } catch AppError.notFound {} - } - try catalog.withTransaction { - try catalog.deleteMeta(Self.relayURLMetaKey) - try catalog.deleteMeta(Self.relayURLMetaKey + "_secret_hint") - try catalog.deleteMeta(Self.doorbellMetaKey) + try relayToggleLock.withLock { + relayApprovalGeneration &+= 1 + doorbellHost.stop() + if let relaySecrets { + do { try relaySecrets.delete(name: Self.relaySecretName) } catch AppError.notFound {} + do { try relaySecrets.delete(name: DoorbellKey.accountName) } catch AppError.notFound {} + } + try catalog.withTransaction { + try catalog.deleteMeta(Self.relayURLMetaKey) + try catalog.deleteMeta(Self.relayURLMetaKey + "_secret_hint") + try catalog.deleteMeta(Self.doorbellMetaKey) + } } } @@ -2074,6 +2084,12 @@ final class KeysService: @unchecked Sendable { /// Off, and the key leaves the Keychain: turning it on again derives it again. func stopDoorbell() { + relayToggleLock.withLock { stopDoorbellLocked() } + } + + /// Caller holds relayToggleLock, also used for the final ring validation and start. + private func stopDoorbellLocked() { + relayApprovalGeneration &+= 1 doorbellHost.stop() try? catalog.deleteMeta(Self.doorbellMetaKey) if let relaySecrets { @@ -2136,6 +2152,7 @@ final class KeysService: @unchecked Sendable { /// gate keeps prompts rare; then Touch ID, naming who rang, turns the relay on exactly as /// `keys relay on` would. func answerDoorbellRing(_ ring: DoorbellRing, now: @Sendable () -> Date = { Date() }) -> DoorbellAnswer { + let approvalGeneration = relayToggleLock.withLock { relayApprovalGeneration } if relayHost.isOn { return .on } guard let ringer = doorbellRinger(ring, now: now()) else { doorbellHost.log("doorbell: a ring with no live client token or pairing; asked nobody") @@ -2180,28 +2197,39 @@ final class KeysService: @unchecked Sendable { return .unavailable("Touch ID could not be shown on the Mac") } doorbellGate.finished(declined: false, now: now()) - guard doorbellEnabled() else { - doorbellHost.log("doorbell: approved for \(quoted), but the doorbell was turned off meanwhile; relay left off") - return .unavailable("the doorbell was turned off on the Mac") - } - guard doorbellRinger(ring, now: now()) != nil else { - doorbellHost.log("doorbell: approved for \(quoted), but its token is no longer live; relay left off") - return .refused - } + // Evaluate the injected clock outside the lock too: only the final state reads and + // start belong in the critical section, never a callback that can shut us down. + let approvedAt = now() do { try requireGatewayOwner() - try relayToggleLock.withLock { - if relayHost.isOn { return } - try startRelayLocked { - // The person approved this start a moment ago; the secret is read for it. - guard let url = relayStatus().url else { - throw AppError.usage("no relay is set up; run: keys relay setup --url https://.workers.dev") + let answer: DoorbellAnswer = try relayToggleLock.withLock { + guard doorbellEnabled() else { + doorbellHost.log("doorbell: approved for \(quoted), but the doorbell was turned off meanwhile; relay left off") + return .unavailable("the doorbell was turned off on the Mac") + } + guard approvalGeneration == relayApprovalGeneration else { + return .unavailable("the relay was turned off on the Mac") + } + // BEGIN IMMEDIATE serializes the live-credential check and start with + // every catalog revoke, including share/unwrap and another process. + return try catalog.withTransaction { + guard doorbellRinger(ring, now: approvedAt) != nil else { + doorbellHost.log("doorbell: approved for \(quoted), but its token is no longer live; relay left off") + return .refused + } + if relayHost.isOn { return .on } + try startRelayLocked { + // The person approved this start a moment ago; the secret is read for it. + guard let url = relayStatus().url else { + throw AppError.usage("no relay is set up; run: keys relay setup --url https://.workers.dev") + } + return (url, try storedRelaySecret(try relayStore(), url: url)) } - return (url, try storedRelaySecret(try relayStore(), url: url)) + return .on } } - doorbellHost.log("doorbell: relay turned on for \(quoted)") - return .on + if answer == .on { doorbellHost.log("doorbell: relay turned on for \(quoted)") } + return answer } catch { doorbellHost.log("doorbell: could not turn the relay on for \(quoted): \(error)") // Only the Mac's own usage refusals (a relay running in a Terminal, no gateway) diff --git a/Tests/KeysreallysafeTests/RelayDoorbellTests.swift b/Tests/KeysreallysafeTests/RelayDoorbellTests.swift index b83e4e3..1711892 100644 --- a/Tests/KeysreallysafeTests/RelayDoorbellTests.swift +++ b/Tests/KeysreallysafeTests/RelayDoorbellTests.swift @@ -8,6 +8,30 @@ import XCTest final class RelayDoorbellTests: XCTestCase { private let origin = URL(string: "https://keysrs-relay.me.workers.dev")! + func testKillAfterEnabledCheckCannotReopenRelay() throws { + final class Clock: @unchecked Sendable { + let lock = NSLock() + var calls = 0 + func next(_ service: KeysService) -> Date { + let count = lock.withLock { calls += 1; return calls } + if count == 4 { _ = service.stopRelayForRevoke() } + return Date() + } + } + let (service, _, _) = try service() + try service.add(name: "demo", provider: "anthropic", kind: "runtime", notes: "", secret: fixtureSecret) + _ = try service.setupRelay(url: origin.absoluteString) + _ = try service.startGateway(port: 0) + defer { service.stopRelay(); service.stopGateway() } + let (token, _) = try service.issueGatewayClient(name: "demo", label: "agent") + _ = try service.setDoorbell(enabled: true) + let clock = Clock() + let answer = service.answerDoorbellRing(ring(client: token), now: { clock.next(service) }) + XCTAssertFalse(service.doorbellEnabled()) + XCTAssertFalse(service.relayHost.isOn, "kill completed before start, so relay must remain off") + XCTAssertNotEqual(answer, .on) + } + // MARK: key and wire func testTheKeyMatchesTheWorkersDerivation() { @@ -405,6 +429,104 @@ final class RelayDoorbellTests: XCTestCase { XCTAssertFalse(service.relayHost.isOn) } + /// Run each shutdown both inside Touch ID and at the old check/start boundary. The + /// synchronous callbacks make the ordering deterministic, and deadlock if a prompt + /// accidentally holds relayToggleLock. No scheduler delays are needed. + private func assertPendingApprovalCancelled( + expected: DoorbellAnswer, + _ cancel: @escaping @Sendable (KeysService, Int64) throws -> Void + ) throws { + for atFinalCheck in [false, true] { + let (service, gate, _) = try service() + try service.add(name: "demo", provider: "anthropic", kind: "runtime", notes: "", secret: fixtureSecret) + _ = try service.setupRelay(url: origin.absoluteString) + _ = try service.startGateway(port: 0) + defer { + service.stopRelay() + service.stopGateway() + service.stopDoorbell() + } + let (token, issued) = try service.issueGatewayClient(name: "demo", label: "agent") + _ = try service.setDoorbell(enabled: true) + let calls = LockedValue(0) + let failure = LockedValue(nil) + if !atFinalCheck { + gate.duringNextPrompt = { try cancel(service, issued.id) } + } + let answer = service.answerDoorbellRing(ring(client: token), now: { + let count = calls.get() + 1 + calls.set(count) + // Initial ringer, gate admission, gate completion, final validation. + if atFinalCheck && count == 4 { + do { try cancel(service, issued.id) } + catch { failure.set(String(describing: error)) } + } + return Date() + }) + XCTAssertNil(failure.get()) + XCTAssertEqual(answer, expected, "at final check: \(atFinalCheck)") + XCTAssertFalse(service.relayHost.isOn) + } + } + + func testDoorbellOffCancelsAPendingApproval() throws { + try assertPendingApprovalCancelled(expected: .unavailable("the doorbell was turned off on the Mac")) { service, _ in + _ = try service.setDoorbell(enabled: false) + } + } + + func testDoorbellOffThenOnDoesNotReuseTheOldApproval() throws { + try assertPendingApprovalCancelled(expected: .unavailable("the relay was turned off on the Mac")) { service, _ in + _ = try service.setDoorbell(enabled: false) + _ = try service.setDoorbell(enabled: true) + } + } + + func testRelayOffCancelsAPendingApprovalWhileLeavingTheDoorbellEnabled() throws { + try assertPendingApprovalCancelled(expected: .unavailable("the relay was turned off on the Mac")) { service, _ in + _ = try service.setRelay(enabled: false) + XCTAssertTrue(service.doorbellEnabled()) + } + } + + func testProcessShutdownCancelsAPendingApproval() throws { + try assertPendingApprovalCancelled(expected: .unavailable("the relay was turned off on the Mac")) { service, _ in + service.stopRelay() + } + } + + func testRevokeAllCancelsAPendingApproval() throws { + try assertPendingApprovalCancelled(expected: .unavailable("the doorbell was turned off on the Mac")) { service, _ in + let handler = APIHandler(service: service, webRoot: service.catalog.path.deletingLastPathComponent()) + let response = handle(handler, method: "POST", path: "/api/mcp/revoke_all", body: Data("{}".utf8)) + XCTAssertEqual(response.status, 200) + XCTAssertTrue(try service.catalog.allGatewayClients().allSatisfy { $0.revokedAt != nil }) + } + } + + func testTokenRevokeCancelsAPendingApprovalAtBothBoundaries() throws { + try assertPendingApprovalCancelled(expected: .refused) { service, id in + _ = try service.revokeGatewayClient(name: "demo", id: id) + } + } + + func testPairingRevokeDuringThePromptTurnsNothingOn() throws { + let (service, gate, _) = try service() + try service.add(name: "demo", provider: "anthropic", kind: "runtime", notes: "", secret: fixtureSecret) + _ = try service.setupRelay(url: origin.absoluteString) + _ = try service.startGateway(port: 0) + defer { + service.stopRelay() + service.stopGateway() + service.stopDoorbell() + } + let (pair, _) = try service.issueRelayPairing(label: "agent", keys: ["demo"]) + _ = try service.setDoorbell(enabled: true) + gate.duringNextPrompt = { _ = try service.revokeRelayPairing("agent") } + XCTAssertEqual(service.answerDoorbellRing(ring(pair: pair)), .refused) + XCTAssertFalse(service.relayHost.isOn) + } + func testRingsTheRelayCouldNotServeAreNotCountedAgainstTheHour() throws { let (service, gate, _) = try service() try service.add(name: "demo", provider: "anthropic", kind: "runtime", notes: "", secret: fixtureSecret)