@eloxiv/daemon 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (114) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +6 -2
  3. package/dist/Acp.d.ts +8 -0
  4. package/dist/Acp.d.ts.map +1 -0
  5. package/dist/Acp.js +268 -0
  6. package/dist/Acp.js.map +1 -0
  7. package/dist/Canonical.d.ts +3 -0
  8. package/dist/Canonical.d.ts.map +1 -0
  9. package/dist/Canonical.js +12 -0
  10. package/dist/Canonical.js.map +1 -0
  11. package/dist/Client.d.ts +100 -0
  12. package/dist/Client.d.ts.map +1 -0
  13. package/dist/Client.js +474 -0
  14. package/dist/Client.js.map +1 -0
  15. package/dist/Commands.d.ts +85 -0
  16. package/dist/Commands.d.ts.map +1 -0
  17. package/dist/Commands.js +370 -0
  18. package/dist/Commands.js.map +1 -0
  19. package/dist/Config.d.ts +74 -0
  20. package/dist/Config.d.ts.map +1 -0
  21. package/dist/Config.js +126 -0
  22. package/dist/Config.js.map +1 -0
  23. package/dist/Daemon.d.ts +243 -0
  24. package/dist/Daemon.d.ts.map +1 -0
  25. package/dist/Daemon.js +965 -0
  26. package/dist/Daemon.js.map +1 -0
  27. package/dist/Harness.d.ts +133 -0
  28. package/dist/Harness.d.ts.map +1 -0
  29. package/dist/Harness.js +734 -0
  30. package/dist/Harness.js.map +1 -0
  31. package/dist/Http.d.ts +15 -0
  32. package/dist/Http.d.ts.map +1 -0
  33. package/dist/Http.js +548 -0
  34. package/dist/Http.js.map +1 -0
  35. package/dist/KernelLink.d.ts +145 -0
  36. package/dist/KernelLink.d.ts.map +1 -0
  37. package/dist/KernelLink.js +109 -0
  38. package/dist/KernelLink.js.map +1 -0
  39. package/dist/LocalAuth.d.ts +99 -0
  40. package/dist/LocalAuth.d.ts.map +1 -0
  41. package/dist/LocalAuth.js +225 -0
  42. package/dist/LocalAuth.js.map +1 -0
  43. package/dist/Main.d.ts +51 -0
  44. package/dist/Main.d.ts.map +1 -0
  45. package/dist/Main.js +219 -0
  46. package/dist/Main.js.map +1 -0
  47. package/dist/Secrets.d.ts +21 -0
  48. package/dist/Secrets.d.ts.map +1 -0
  49. package/dist/Secrets.js +204 -0
  50. package/dist/Secrets.js.map +1 -0
  51. package/dist/SecureUrl.d.ts +11 -0
  52. package/dist/SecureUrl.d.ts.map +1 -0
  53. package/dist/SecureUrl.js +23 -0
  54. package/dist/SecureUrl.js.map +1 -0
  55. package/dist/State.d.ts +77 -0
  56. package/dist/State.d.ts.map +1 -0
  57. package/dist/State.js +38 -0
  58. package/dist/State.js.map +1 -0
  59. package/dist/Terminals.d.ts +49 -0
  60. package/dist/Terminals.d.ts.map +1 -0
  61. package/dist/Terminals.js +203 -0
  62. package/dist/Terminals.js.map +1 -0
  63. package/dist/bin-node.d.ts +2 -0
  64. package/dist/bin-node.d.ts.map +1 -0
  65. package/dist/bin-node.js +4 -0
  66. package/dist/bin-node.js.map +1 -0
  67. package/dist/bin.d.ts +2 -0
  68. package/dist/bin.d.ts.map +1 -0
  69. package/dist/bin.js +4 -0
  70. package/dist/bin.js.map +1 -0
  71. package/dist/index.d.ts +17 -0
  72. package/dist/index.d.ts.map +1 -0
  73. package/dist/index.js +17 -0
  74. package/dist/index.js.map +1 -0
  75. package/dist/runtime/bun.d.ts +11 -0
  76. package/dist/runtime/bun.d.ts.map +1 -0
  77. package/dist/runtime/bun.js +20 -0
  78. package/dist/runtime/bun.js.map +1 -0
  79. package/dist/runtime/node.d.ts +11 -0
  80. package/dist/runtime/node.d.ts.map +1 -0
  81. package/dist/runtime/node.js +21 -0
  82. package/dist/runtime/node.js.map +1 -0
  83. package/dist/testing.d.ts +25 -0
  84. package/dist/testing.d.ts.map +1 -0
  85. package/dist/testing.js +27 -0
  86. package/dist/testing.js.map +1 -0
  87. package/fixtures/claude-code-env-vars.txt +409 -0
  88. package/fixtures/fake-acp-agent.mjs +222 -0
  89. package/fixtures/fake-harness.mjs +299 -0
  90. package/fixtures/recorded/claude-code.jsonl +7 -0
  91. package/fixtures/recorded/codex.jsonl +6 -0
  92. package/package.json +64 -3
  93. package/scripts/build-sidecar.ts +86 -0
  94. package/src/Acp.ts +292 -0
  95. package/src/Canonical.ts +9 -0
  96. package/src/Client.ts +585 -0
  97. package/src/Commands.ts +427 -0
  98. package/src/Config.ts +179 -0
  99. package/src/Daemon.ts +1092 -0
  100. package/src/Harness.ts +839 -0
  101. package/src/Http.ts +563 -0
  102. package/src/KernelLink.ts +197 -0
  103. package/src/LocalAuth.ts +301 -0
  104. package/src/Main.ts +281 -0
  105. package/src/Secrets.ts +226 -0
  106. package/src/SecureUrl.ts +21 -0
  107. package/src/State.ts +109 -0
  108. package/src/Terminals.ts +227 -0
  109. package/src/bin-node.ts +4 -0
  110. package/src/bin.ts +4 -0
  111. package/src/index.ts +16 -0
  112. package/src/runtime/bun.ts +29 -0
  113. package/src/runtime/node.ts +30 -0
  114. package/src/testing.ts +43 -0
@@ -0,0 +1,197 @@
1
+ /**
2
+ * The daemon's side of the kernel's device endpoints (the Daemon contract), with the device credential. The
3
+ * credential is read from the secret store for every request and never leaves this module except in the
4
+ * `authorization` header of a request to the kernel.
5
+ */
6
+ import type {
7
+ ClaimedCommand,
8
+ ClaimedTurn,
9
+ CommandKind,
10
+ CompleteCommand,
11
+ CompleteTurn,
12
+ DeviceCapabilities,
13
+ PushSubscriptionInfo,
14
+ DeviceInfo,
15
+ DeviceSession,
16
+ HarnessEvent,
17
+ PairingPollResult,
18
+ PairingRequest,
19
+ PairingStarted,
20
+ RelaySession,
21
+ } from "@eloxiv/contracts"
22
+ import { DEVICE_PATHS } from "@eloxiv/contracts"
23
+
24
+ /** The kernel refused the device credential: the device was revoked (or its person left the organisation). */
25
+ export class DeviceRevoked extends Error {
26
+ override readonly name = "DeviceRevoked"
27
+ }
28
+
29
+ /** The kernel answered with an error status. */
30
+ export class KernelError extends Error {
31
+ override readonly name = "KernelError"
32
+ readonly status: number
33
+ readonly tag: string
34
+ constructor(status: number, tag: string, message: string) {
35
+ super(message)
36
+ this.status = status
37
+ this.tag = tag
38
+ }
39
+ }
40
+
41
+ const base = (url: string) => url.replace(/\/+$/u, "")
42
+
43
+ const text = (value: unknown, fallback: string) => (typeof value === "string" ? value : fallback)
44
+
45
+ const parse = async (response: Response) => {
46
+ const text = await response.text()
47
+ let body: unknown = undefined
48
+ try {
49
+ body = text.length === 0 ? {} : JSON.parse(text)
50
+ } catch {
51
+ body = { _tag: "InvalidResponse", message: text.slice(0, 200) }
52
+ }
53
+ return body as Record<string, unknown>
54
+ }
55
+
56
+ /** How long a kernel request may take before it is abandoned (ms): no request waits forever. */
57
+ export const KERNEL_TIMEOUT_MS = 30_000
58
+
59
+ /** `signal`, also aborted after `timeoutMs`. */
60
+ const withTimeout = (timeoutMs: number, signal?: AbortSignal) =>
61
+ signal === undefined ? AbortSignal.timeout(timeoutMs) : AbortSignal.any([signal, AbortSignal.timeout(timeoutMs)])
62
+
63
+ const request = async <A>(
64
+ url: string,
65
+ path: string,
66
+ init: {
67
+ method?: string
68
+ body?: unknown
69
+ credential?: string
70
+ signal?: AbortSignal | undefined
71
+ timeoutMs?: number | undefined
72
+ },
73
+ ): Promise<A> => {
74
+ const headers: Record<string, string> = { accept: "application/json" }
75
+ if (init.body !== undefined) headers["content-type"] = "application/json"
76
+ if (init.credential !== undefined) headers["authorization"] = `Bearer ${init.credential}`
77
+ const response = await fetch(`${base(url)}${path}`, {
78
+ method: init.method ?? "POST",
79
+ headers,
80
+ ...(init.body === undefined ? {} : { body: JSON.stringify(init.body) }),
81
+ signal: withTimeout(init.timeoutMs ?? KERNEL_TIMEOUT_MS, init.signal),
82
+ })
83
+ const body = await parse(response)
84
+ if (response.status === 401 && init.credential !== undefined) {
85
+ throw new DeviceRevoked(text(body["message"], "The kernel refused the device credential"))
86
+ }
87
+ if (!response.ok) {
88
+ throw new KernelError(response.status, text(body["_tag"], "Error"), text(body["message"], String(response.status)))
89
+ }
90
+ return body as A
91
+ }
92
+
93
+ /** How long a relayed call may take (ms). */
94
+ export const RELAY_TIMEOUT_MS = 10 * 60 * 1000
95
+
96
+ /** Pairing: no credential yet. */
97
+ export const startPairing = (url: string, input: PairingRequest) =>
98
+ request<PairingStarted>(url, DEVICE_PATHS.pairStart, { body: input })
99
+
100
+ export const pollPairing = (url: string, pairingId: string, pollSecret: string) =>
101
+ request<PairingPollResult>(url, DEVICE_PATHS.pairPoll, { body: { pairingId, pollSecret } })
102
+
103
+ /** The kernel, as a device: every call reads the credential afresh. */
104
+ export class KernelLink {
105
+ readonly url: string
106
+ private readonly credential: () => Promise<string | undefined>
107
+ private readonly timeoutMs: number
108
+ constructor(
109
+ url: string,
110
+ credential: () => Promise<string | undefined>,
111
+ options: { readonly timeoutMs?: number | undefined } = {},
112
+ ) {
113
+ this.url = url
114
+ this.credential = credential
115
+ this.timeoutMs = options.timeoutMs ?? KERNEL_TIMEOUT_MS
116
+ }
117
+
118
+ private async call<A>(
119
+ path: string,
120
+ body?: unknown,
121
+ method = "POST",
122
+ signal?: AbortSignal,
123
+ timeoutMs = this.timeoutMs,
124
+ ): Promise<A> {
125
+ const credential = await this.credential()
126
+ if (credential === undefined) throw new DeviceRevoked("This daemon holds no device credential")
127
+ return request<A>(this.url, path, { method, body, credential, signal, timeoutMs })
128
+ }
129
+
130
+ me = () => this.call<DeviceInfo>(DEVICE_PATHS.me, undefined, "GET")
131
+
132
+ /** A relay session; for a turn (`turnId`), one that carries the authority of the call that queued the turn. */
133
+ relaySession = (purpose: string, ttlSeconds: number, turnId?: string) =>
134
+ this.call<RelaySession>(DEVICE_PATHS.relaySession, {
135
+ purpose,
136
+ ttlSeconds: Math.max(60, Math.ceil(ttlSeconds)),
137
+ ...(turnId === undefined ? {} : { turnId }),
138
+ })
139
+
140
+ nextTurn = (waitMs: number, fresh: boolean, signal?: AbortSignal) =>
141
+ this.call<{ turn: ClaimedTurn | null }>(
142
+ DEVICE_PATHS.turnsNext,
143
+ { waitMs, fresh },
144
+ "POST",
145
+ signal,
146
+ waitMs + this.timeoutMs,
147
+ )
148
+
149
+ appendEvents = (turnId: string, lease: string, events: ReadonlyArray<HarnessEvent & { readonly seq: number }>) =>
150
+ this.call<{ accepted: number; stop: boolean }>(DEVICE_PATHS.turnsEvents, { turnId, lease, events })
151
+
152
+ completeTurn = (input: CompleteTurn) =>
153
+ this.call<{ settled: boolean; duplicate: boolean }>(DEVICE_PATHS.turnsComplete, input)
154
+
155
+ reportSessions = (sessions: ReadonlyArray<DeviceSession>) =>
156
+ this.call<{ recorded: number }>(DEVICE_PATHS.sessions, { sessions })
157
+
158
+ nextCommand = (kinds: ReadonlyArray<CommandKind>, waitMs: number, signal?: AbortSignal) =>
159
+ this.call<{ command: ClaimedCommand | null }>(
160
+ DEVICE_PATHS.commandsNext,
161
+ { kinds, waitMs },
162
+ "POST",
163
+ signal,
164
+ waitMs + this.timeoutMs,
165
+ )
166
+
167
+ completeCommand = (input: CompleteCommand) =>
168
+ this.call<{ settled: boolean; duplicate: boolean }>(DEVICE_PATHS.commandsComplete, input)
169
+
170
+ checkCommand = (input: { readonly commandId: string; readonly lease: string }) =>
171
+ this.call<{ stop: boolean }>(DEVICE_PATHS.commandsCheck, input)
172
+
173
+ reportCapabilities = (capabilities: DeviceCapabilities) =>
174
+ this.call<DeviceInfo>(DEVICE_PATHS.capabilities, { capabilities })
175
+
176
+ registerPush = (subscription: PushSubscriptionInfo | null) =>
177
+ this.call<{ registered: boolean }>(DEVICE_PATHS.push, { subscription })
178
+
179
+ /**
180
+ * Forward a request to the kernel with `token` (the device credential when omitted): the relay. Only the
181
+ * status, the content type and MCP's session headers come back; the body is the kernel's.
182
+ */
183
+ forward = async (
184
+ path: string,
185
+ init: { method: string; headers: Record<string, string>; body?: string | null; token?: string | undefined },
186
+ ): Promise<Response> => {
187
+ const token = init.token ?? (await this.credential())
188
+ if (token === undefined) throw new DeviceRevoked("This daemon holds no device credential")
189
+ return fetch(`${base(this.url)}${path}`, {
190
+ method: init.method,
191
+ headers: { ...init.headers, authorization: `Bearer ${token}` },
192
+ ...(init.body === undefined || init.body === null ? {} : { body: init.body }),
193
+ // Relayed calls (an MCP stream among them) may take longer than the device endpoints, never forever.
194
+ signal: AbortSignal.timeout(RELAY_TIMEOUT_MS),
195
+ })
196
+ }
197
+ }
@@ -0,0 +1,301 @@
1
+ /**
2
+ * Who may talk to the daemon over loopback, and how each is authenticated (per client):
3
+ *
4
+ * - the **host** (the Tauri app that started the daemon as its sidecar) holds a per-launch secret it handed the
5
+ * daemon in `ELOXIV_DAEMON_HOST_SECRET` and gives its webview; the person at the daemon's machine acts as the
6
+ * host through `eloxiv-daemon approve-client`, which reads the daemon's control secret from its private state
7
+ * directory;
8
+ * - **local clients** (the shell in a browser, a browser extension, a CLI) pair once. A client asks to pair; the
9
+ * host **approves** the request (the desktop app's prompt, or `eloxiv-daemon approve-client`), which shows the
10
+ * person a ten-character code; the client exchanges the approved pairing and its code for a token (`elxl_...`,
11
+ * stored by the daemon only as a SHA-256 hash). A code alone is never enough, and the code is never logged;
12
+ * - **harnesses** get a token for one turn, valid only for the relay and MCP while that turn runs, optionally
13
+ * limited to some Eloxiv actions.
14
+ *
15
+ * Against guessing: codes carry 50 bits (ten symbols of 32), each pairing allows a few wrong codes, every wrong
16
+ * code anywhere counts against one budget whose exhaustion locks all confirmations out for exponentially longer,
17
+ * and pairings started per window are capped.
18
+ *
19
+ * Every request except `GET /health` is also checked for its `Host` (a loopback name with the daemon's port,
20
+ * against DNS rebinding) and, when it carries one, its `Origin` (one of the trusted origins).
21
+ */
22
+ import { DEVICE_CREDENTIAL_PREFIX } from "@eloxiv/contracts"
23
+ import { randomBytes, randomUUID, timingSafeEqual } from "node:crypto"
24
+ import { sha256Hex, type LocalClient, type StateFile } from "./State.ts"
25
+
26
+ export type ClientKind = "host" | "shell" | "browser-extension" | "cli" | "computer-use" | "desktop-app" | "harness"
27
+
28
+ export interface AuthenticatedClient {
29
+ readonly id: string
30
+ readonly kind: ClientKind
31
+ readonly name: string
32
+ /** For a harness: the turn it runs, its agent session for the kernel, and its idempotency scope. */
33
+ readonly turn?: HarnessGrant | undefined
34
+ }
35
+
36
+ export interface HarnessGrant {
37
+ readonly turnId: string
38
+ /** The kernel agent session the relay uses for this turn's calls (agent-originated). */
39
+ readonly agentToken: string
40
+ /** For runner turns: tool calls get idempotency keys derived from the turn, so a re-run replays. */
41
+ readonly idempotencyScope: string | undefined
42
+ /** The Eloxiv actions (by name) the turn may call; undefined: every action the person's policy allows. */
43
+ readonly actions?: ReadonlySet<string> | undefined
44
+ }
45
+
46
+ export type LocalAuthStatus = 401 | 403 | 404 | 409 | 410 | 429
47
+
48
+ export class LocalAuthError extends Error {
49
+ readonly status: LocalAuthStatus
50
+ readonly tag: string
51
+ readonly detail: Record<string, unknown>
52
+ constructor(status: LocalAuthStatus, tag: string, message: string, detail: Record<string, unknown> = {}) {
53
+ super(message)
54
+ this.status = status
55
+ this.tag = tag
56
+ this.detail = detail
57
+ }
58
+ }
59
+
60
+ interface Pending {
61
+ readonly code: string
62
+ readonly expiresAt: number
63
+ readonly clientName: string
64
+ readonly kind: LocalClient["kind"]
65
+ approved: boolean
66
+ attempts: number
67
+ }
68
+
69
+ /** Crockford's base 32: no I, L, O or U, so a code read aloud or retyped is unambiguous. */
70
+ const ALPHABET = "0123456789ABCDEFGHJKMNPQRSTVWXYZ"
71
+ const CODE_LENGTH = 10
72
+
73
+ const newCode = () => {
74
+ // 256 is a multiple of 32: taking each byte mod 32 is uniform.
75
+ const symbols = [...randomBytes(CODE_LENGTH)].map((byte) => ALPHABET[byte % 32]!)
76
+ return `${symbols.slice(0, 5).join("")}-${symbols.slice(5).join("")}`
77
+ }
78
+
79
+ /** What a person typed, normalised: upper case, separators dropped, look-alikes mapped as Crockford does. */
80
+ export const normaliseCode = (code: string) =>
81
+ code.toUpperCase().replaceAll(/[\s-]/gu, "").replaceAll("O", "0").replaceAll(/[IL]/gu, "1")
82
+
83
+ const token = () => `${DEVICE_CREDENTIAL_PREFIX.local}${randomBytes(32).toString("base64url")}`
84
+
85
+ const same = (a: string, b: string) => {
86
+ const left = Buffer.from(sha256Hex(a), "hex")
87
+ const right = Buffer.from(sha256Hex(b), "hex")
88
+ return timingSafeEqual(left, right)
89
+ }
90
+
91
+ export interface LocalPairingOptions {
92
+ /** How long a local pairing code stays valid (ms, default 5 minutes). */
93
+ readonly codeTtlMs?: number | undefined
94
+ /** Wrong codes before one local pairing is discarded (default 3). */
95
+ readonly maxAttempts?: number | undefined
96
+ /** Pairings started per window (default 5 per 10 minutes). */
97
+ readonly startLimit?: number | undefined
98
+ readonly startWindowMs?: number | undefined
99
+ /** Wrong codes, across every pairing, before confirmations are locked out (default 3). */
100
+ readonly failureBudget?: number | undefined
101
+ /** The first lockout (ms, default 2 s); each further wrong code doubles it, up to an hour. */
102
+ readonly lockoutBaseMs?: number | undefined
103
+ }
104
+
105
+ export interface LocalAuthOptions extends LocalPairingOptions {
106
+ readonly hostSecret?: string | undefined
107
+ /** The control secret `eloxiv-daemon approve-client` reads from the state directory (acts as the host). */
108
+ readonly controlSecret?: string | undefined
109
+ readonly trustedOrigins: ReadonlyArray<string>
110
+ readonly log: (line: string) => void
111
+ }
112
+
113
+ const MAX_LOCKOUT_MS = 60 * 60 * 1000
114
+
115
+ export class LocalAuth {
116
+ readonly #pending = new Map<string, Pending>()
117
+ readonly #harness = new Map<string, AuthenticatedClient>()
118
+ readonly #starts: Array<number> = []
119
+ #failures = 0
120
+ #lockedUntil = 0
121
+ #port = 0
122
+
123
+ private readonly state: StateFile
124
+ private readonly options: LocalAuthOptions
125
+ constructor(state: StateFile, options: LocalAuthOptions) {
126
+ this.state = state
127
+ this.options = options
128
+ }
129
+
130
+ /** The port the daemon listens on (Host checks need it). */
131
+ set port(port: number) {
132
+ this.#port = port
133
+ }
134
+
135
+ /** Requests must name the daemon by a loopback host and its own port: a rebound DNS name is refused. */
136
+ checkHost(host: string | undefined) {
137
+ const allowed = [`127.0.0.1:${this.#port}`, `localhost:${this.#port}`, `[::1]:${this.#port}`]
138
+ if (host === undefined || !allowed.includes(host.toLowerCase())) {
139
+ throw new LocalAuthError(403, "ForbiddenHost", "Requests must address the daemon on loopback")
140
+ }
141
+ }
142
+
143
+ /** A browser request from a page that is not one of the trusted origins is refused outright (not just by CORS). */
144
+ checkOrigin(origin: string | undefined) {
145
+ if (origin === undefined) return
146
+ if (!this.options.trustedOrigins.includes(origin)) {
147
+ throw new LocalAuthError(403, "ForbiddenOrigin", `Origin ${origin} may not use the daemon`)
148
+ }
149
+ }
150
+
151
+ authenticate(authorization: string | undefined): AuthenticatedClient {
152
+ const match = authorization === undefined ? null : /^Bearer\s+(\S+)\s*$/iu.exec(authorization)
153
+ const presented = match?.[1]
154
+ if (presented === undefined) throw new LocalAuthError(401, "Unauthenticated", "A local client token is required")
155
+ if (this.options.hostSecret !== undefined && same(presented, this.options.hostSecret)) {
156
+ return { id: "host", kind: "host", name: "host" }
157
+ }
158
+ if (this.options.controlSecret !== undefined && same(presented, this.options.controlSecret)) {
159
+ return { id: "control", kind: "host", name: "control" }
160
+ }
161
+ const hash = sha256Hex(presented)
162
+ const harness = this.#harness.get(hash)
163
+ if (harness !== undefined) return harness
164
+ const client = this.state.current.localClients.find((c) => c.tokenHash === hash)
165
+ if (client === undefined) throw new LocalAuthError(401, "Unauthenticated", "Unknown or revoked local client token")
166
+ return { id: client.id, kind: client.kind, name: client.name }
167
+ }
168
+
169
+ // --- local pairing -------------------------------------------------------------------------------------------
170
+
171
+ startPairing(
172
+ request: { readonly clientName?: string | undefined; readonly kind?: LocalClient["kind"] | undefined } = {},
173
+ ) {
174
+ const now = Date.now()
175
+ for (const [id, entry] of this.#pending) if (entry.expiresAt <= now) this.#pending.delete(id)
176
+ const window = this.options.startWindowMs ?? 10 * 60 * 1000
177
+ while (this.#starts.length > 0 && this.#starts[0]! <= now - window) this.#starts.shift()
178
+ if (this.#starts.length >= (this.options.startLimit ?? 5) || this.#pending.size >= 20) {
179
+ throw new LocalAuthError(429, "PairingRateLimited", "Too many pairings were started; try again later", {
180
+ retryAfterMs: Math.max(1, (this.#starts[0] ?? now) + window - now),
181
+ })
182
+ }
183
+ this.#starts.push(now)
184
+ const pairingId = randomUUID()
185
+ const clientName = (request.clientName ?? "a local client").slice(0, 100)
186
+ this.#pending.set(pairingId, {
187
+ code: newCode(),
188
+ expiresAt: now + (this.options.codeTtlMs ?? 5 * 60 * 1000),
189
+ clientName,
190
+ kind: request.kind ?? "cli",
191
+ approved: false,
192
+ attempts: 0,
193
+ })
194
+ // The code is never logged: the host (or `eloxiv-daemon approve-client`) shows it when it approves.
195
+ this.options.log(
196
+ `${JSON.stringify(clientName)} asks to pair (${pairingId}): approve it in the desktop app or with \`eloxiv-daemon approve-client\``,
197
+ )
198
+ return { pairingId, expiresAt: new Date(now + (this.options.codeTtlMs ?? 5 * 60 * 1000)).toISOString() }
199
+ }
200
+
201
+ /** Pending local pairings with their codes, for the host to show (never to other clients). */
202
+ pendingPairings() {
203
+ const now = Date.now()
204
+ return [...this.#pending.entries()]
205
+ .filter(([, entry]) => entry.expiresAt > now)
206
+ .map(([pairingId, entry]) => ({
207
+ pairingId,
208
+ code: entry.code,
209
+ clientName: entry.clientName,
210
+ kind: entry.kind,
211
+ approved: entry.approved,
212
+ expiresAt: new Date(entry.expiresAt).toISOString(),
213
+ }))
214
+ }
215
+
216
+ /** The host approves a pending pairing: only then can its code be exchanged for a token. */
217
+ approvePairing(pairingId: string) {
218
+ const entry = this.#pending.get(pairingId)
219
+ if (entry === undefined || entry.expiresAt <= Date.now()) {
220
+ throw new LocalAuthError(404, "PairingNotFound", "No pending pairing with this id")
221
+ }
222
+ entry.approved = true
223
+ return { pairingId, code: entry.code, clientName: entry.clientName }
224
+ }
225
+
226
+ /** A wrong guess anywhere: it counts against the global budget, and past it every confirmation waits. */
227
+ #fail(): void {
228
+ this.#failures += 1
229
+ const budget = this.options.failureBudget ?? 3
230
+ if (this.#failures >= budget) {
231
+ const base = this.options.lockoutBaseMs ?? 2_000
232
+ this.#lockedUntil = Date.now() + Math.min(base * 2 ** (this.#failures - budget), MAX_LOCKOUT_MS)
233
+ }
234
+ }
235
+
236
+ confirmPairing(input: {
237
+ readonly pairingId: string
238
+ readonly code: string
239
+ readonly clientName: string
240
+ readonly kind?: LocalClient["kind"] | undefined
241
+ }) {
242
+ const now = Date.now()
243
+ if (now < this.#lockedUntil) {
244
+ throw new LocalAuthError(429, "PairingLocked", "Too many wrong pairing codes; wait before trying again", {
245
+ retryAfterMs: this.#lockedUntil - now,
246
+ })
247
+ }
248
+ const entry = this.#pending.get(input.pairingId)
249
+ if (entry === undefined) {
250
+ this.#fail()
251
+ throw new LocalAuthError(404, "PairingNotFound", "No pending pairing with this id")
252
+ }
253
+ if (entry.expiresAt <= now) {
254
+ this.#pending.delete(input.pairingId)
255
+ throw new LocalAuthError(410, "PairingExpired", "The pairing code has expired")
256
+ }
257
+ if (!entry.approved) {
258
+ this.#fail()
259
+ throw new LocalAuthError(403, "PairingNotApproved", "The pairing has not been approved on this machine yet")
260
+ }
261
+ if (!same(entry.code, normaliseCode(input.code).replace(/^(.{5})(.{5})$/u, "$1-$2"))) {
262
+ entry.attempts += 1
263
+ this.#fail()
264
+ const attemptsLeft = Math.max(0, (this.options.maxAttempts ?? 3) - entry.attempts)
265
+ if (attemptsLeft === 0) this.#pending.delete(input.pairingId)
266
+ throw new LocalAuthError(403, "PairingCodeMismatch", "Wrong code", { attemptsLeft })
267
+ }
268
+ if (input.kind !== undefined && input.kind !== entry.kind) {
269
+ // The host approved this kind; a confirmation may not change it (a companion must not become a desktop-app).
270
+ this.#pending.delete(input.pairingId)
271
+ this.#fail()
272
+ throw new LocalAuthError(403, "PairingKindMismatch", "The kind differs from the pairing the host approved")
273
+ }
274
+ this.#pending.delete(input.pairingId)
275
+ this.#failures = 0
276
+ const secret = token()
277
+ const client: LocalClient = {
278
+ id: randomUUID(),
279
+ name: input.clientName,
280
+ kind: entry.kind,
281
+ tokenHash: sha256Hex(secret),
282
+ pairedAt: new Date().toISOString(),
283
+ }
284
+ this.state.update((state) => ({ ...state, localClients: [...state.localClients, client] }))
285
+ return { clientId: client.id, token: secret, kind: client.kind }
286
+ }
287
+
288
+ unpair(clientId: string) {
289
+ this.state.update((state) => ({ ...state, localClients: state.localClients.filter((c) => c.id !== clientId) }))
290
+ }
291
+
292
+ // --- harness grants ------------------------------------------------------------------------------------------
293
+
294
+ /** A token for a harness running one turn; revoked when the turn ends. */
295
+ grantHarness(grant: HarnessGrant): { readonly token: string; readonly revoke: () => void } {
296
+ const secret = token()
297
+ const hash = sha256Hex(secret)
298
+ this.#harness.set(hash, { id: `harness:${grant.turnId}`, kind: "harness", name: grant.turnId, turn: grant })
299
+ return { token: secret, revoke: () => this.#harness.delete(hash) }
300
+ }
301
+ }