@eloxiv/daemon 0.0.0-stage → 0.1.1

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 (119) 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 +102 -0
  12. package/dist/Client.d.ts.map +1 -0
  13. package/dist/Client.js +482 -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/PersonSession.d.ts +49 -0
  48. package/dist/PersonSession.d.ts.map +1 -0
  49. package/dist/PersonSession.js +173 -0
  50. package/dist/PersonSession.js.map +1 -0
  51. package/dist/Secrets.d.ts +21 -0
  52. package/dist/Secrets.d.ts.map +1 -0
  53. package/dist/Secrets.js +204 -0
  54. package/dist/Secrets.js.map +1 -0
  55. package/dist/SecureUrl.d.ts +11 -0
  56. package/dist/SecureUrl.d.ts.map +1 -0
  57. package/dist/SecureUrl.js +23 -0
  58. package/dist/SecureUrl.js.map +1 -0
  59. package/dist/State.d.ts +77 -0
  60. package/dist/State.d.ts.map +1 -0
  61. package/dist/State.js +38 -0
  62. package/dist/State.js.map +1 -0
  63. package/dist/Terminals.d.ts +49 -0
  64. package/dist/Terminals.d.ts.map +1 -0
  65. package/dist/Terminals.js +203 -0
  66. package/dist/Terminals.js.map +1 -0
  67. package/dist/bin-node.d.ts +2 -0
  68. package/dist/bin-node.d.ts.map +1 -0
  69. package/dist/bin-node.js +4 -0
  70. package/dist/bin-node.js.map +1 -0
  71. package/dist/bin.d.ts +2 -0
  72. package/dist/bin.d.ts.map +1 -0
  73. package/dist/bin.js +4 -0
  74. package/dist/bin.js.map +1 -0
  75. package/dist/index.d.ts +18 -0
  76. package/dist/index.d.ts.map +1 -0
  77. package/dist/index.js +18 -0
  78. package/dist/index.js.map +1 -0
  79. package/dist/runtime/bun.d.ts +11 -0
  80. package/dist/runtime/bun.d.ts.map +1 -0
  81. package/dist/runtime/bun.js +20 -0
  82. package/dist/runtime/bun.js.map +1 -0
  83. package/dist/runtime/node.d.ts +11 -0
  84. package/dist/runtime/node.d.ts.map +1 -0
  85. package/dist/runtime/node.js +21 -0
  86. package/dist/runtime/node.js.map +1 -0
  87. package/dist/testing.d.ts +25 -0
  88. package/dist/testing.d.ts.map +1 -0
  89. package/dist/testing.js +27 -0
  90. package/dist/testing.js.map +1 -0
  91. package/fixtures/claude-code-env-vars.txt +409 -0
  92. package/fixtures/fake-acp-agent.mjs +222 -0
  93. package/fixtures/fake-harness.mjs +299 -0
  94. package/fixtures/recorded/claude-code.jsonl +7 -0
  95. package/fixtures/recorded/codex.jsonl +6 -0
  96. package/package.json +64 -3
  97. package/scripts/build-sidecar.ts +86 -0
  98. package/src/Acp.ts +292 -0
  99. package/src/Canonical.ts +9 -0
  100. package/src/Client.ts +590 -0
  101. package/src/Commands.ts +427 -0
  102. package/src/Config.ts +179 -0
  103. package/src/Daemon.ts +1092 -0
  104. package/src/Harness.ts +839 -0
  105. package/src/Http.ts +563 -0
  106. package/src/KernelLink.ts +197 -0
  107. package/src/LocalAuth.ts +301 -0
  108. package/src/Main.ts +281 -0
  109. package/src/PersonSession.ts +203 -0
  110. package/src/Secrets.ts +226 -0
  111. package/src/SecureUrl.ts +21 -0
  112. package/src/State.ts +109 -0
  113. package/src/Terminals.ts +227 -0
  114. package/src/bin-node.ts +4 -0
  115. package/src/bin.ts +4 -0
  116. package/src/index.ts +17 -0
  117. package/src/runtime/bun.ts +29 -0
  118. package/src/runtime/node.ts +30 -0
  119. package/src/testing.ts +43 -0
package/src/Main.ts ADDED
@@ -0,0 +1,281 @@
1
+ /**
2
+ * Platform-neutral start-up: build the daemon's core, announce readiness once listening, start the runner in
3
+ * headless mode, watch the stdin lifeline, and map shutdown to a clean exit; and the one-shot commands
4
+ * (`pair`, `status`, `unpair`). `runtime/bun` and `runtime/node` supply the HTTP server.
5
+ */
6
+ import type { DaemonStatus } from "@eloxiv/contracts"
7
+ import { mkdirSync, readFileSync } from "node:fs"
8
+ import { resolve, sep } from "node:path"
9
+ import { Cause, Effect, Exit, Layer } from "effect"
10
+ import { HttpServer } from "effect/http"
11
+ import type { Teardown } from "effect/Runtime"
12
+ import type { SyncSqliteDatabase } from "@eloxiv/client/storage"
13
+ import type { Effect as EffectType } from "effect/Effect"
14
+ import { readHostSecret, readyLine, resolveConfig, type DaemonConfig } from "./Config.ts"
15
+ import type { ClientApp } from "./Client.ts"
16
+ import { controlSecretPath, Daemon, type DaemonOptions } from "./Daemon.ts"
17
+ import { DaemonHttp, trustedOriginsFor } from "./Http.ts"
18
+ import { selectSecretStore } from "./Secrets.ts"
19
+
20
+ /** `release` in the compiled sidecar (`build:sidecar` defines it), `development` when run from source. */
21
+ declare const ELOXIV_DAEMON_BUILD: string | undefined
22
+ export const DAEMON_BUILD: string = typeof ELOXIV_DAEMON_BUILD === "string" ? ELOXIV_DAEMON_BUILD : "development"
23
+
24
+ /** The port the platform server actually bound (differs from the config when it asked for 0). */
25
+ export const boundPort = Effect.gen(function* () {
26
+ const server = yield* HttpServer.HttpServer
27
+ return server.address._tag === "UnixPathAddress" ? 0 : server.address.port
28
+ })
29
+
30
+ /** The daemon's core for a config: its state directory, secret store and harnesses. */
31
+ export const createDaemon = async (
32
+ config: Pick<DaemonConfig, "stateDir" | "secretStore" | "headless" | "trustedOrigins" | "workspace" | "hostSecret"> &
33
+ Partial<Pick<DaemonConfig, "commands" | "toolsOnly">>,
34
+ overrides: Partial<DaemonOptions> = {},
35
+ ): Promise<Daemon> => {
36
+ mkdirSync(config.stateDir, { recursive: true, mode: 0o700 })
37
+ const stateDir = resolve(config.stateDir)
38
+ const workspace = config.workspace === undefined ? undefined : resolve(config.workspace)
39
+ // A harness works in its workspace: it must never be the state directory (the credential's file store, the
40
+ // control secret, state.json) or inside it. The state directory may be inside the workspace (a home directory as
41
+ // the workspace, the default state under it): file commands exclude it (`Commands.ts`).
42
+ if (workspace !== undefined && (workspace === stateDir || workspace.startsWith(`${stateDir}${sep}`))) {
43
+ throw new Error(`The workspace (${workspace}) must be outside the state directory (${stateDir})`)
44
+ }
45
+ if (workspace !== undefined) mkdirSync(workspace, { recursive: true })
46
+ return new Daemon({
47
+ mode: config.headless ? "headless" : "desktop",
48
+ stateDir: config.stateDir,
49
+ secrets: await selectSecretStore(config.secretStore, config.stateDir),
50
+ hostSecret: config.hostSecret,
51
+ trustedOrigins: config.trustedOrigins ?? trustedOriginsFor(DAEMON_BUILD),
52
+ workspace,
53
+ commands: config.commands,
54
+ toolsOnly: config.toolsOnly,
55
+ ...overrides,
56
+ })
57
+ }
58
+
59
+ /**
60
+ * Once listening: tell the core its port, start the runner (headless; pairing first when `--kernel` is given
61
+ * and the device is not paired), and print the ready line.
62
+ */
63
+ const started = (daemon: Daemon, config: Pick<DaemonConfig, "headless" | "kernelUrl" | "name">) =>
64
+ Effect.gen(function* () {
65
+ daemon.port = yield* boundPort
66
+ // Device commands, in either mode, once paired (a pairing completed later starts them too).
67
+ if (daemon.paired) daemon.startCommands()
68
+ // LocalClient: the stored person session is checked in the background (the kernel may not be up yet).
69
+ if (daemon.client !== undefined) void daemon.client.start()
70
+ if (config.headless) {
71
+ if (daemon.paired) daemon.startRunner()
72
+ else if (config.kernelUrl !== undefined) {
73
+ const pairing = yield* Effect.promise(() =>
74
+ daemon.startKernelPairing(config.kernelUrl!, { name: config.name, kind: "runner" }),
75
+ )
76
+ // The code goes to a person at a terminal only, never to a log (`eloxiv-daemon pairing-code` reads it).
77
+ if (process.stderr.isTTY) {
78
+ process.stderr.write(
79
+ `To pair this runner, confirm the code ${pairing.started.userCode} at ${pairing.started.verificationUri}\n`,
80
+ )
81
+ }
82
+ pairing.done.then(
83
+ () => daemon.startRunner(),
84
+ (error: unknown) => daemon.log(`pairing failed: ${String(error)}`),
85
+ )
86
+ } else {
87
+ daemon.log("headless, but not paired: run `eloxiv-daemon pair --kernel <url> --runner` or pass --kernel")
88
+ }
89
+ }
90
+ if (daemon.options.announce !== false) yield* Effect.sync(() => process.stdout.write(`${readyLine(daemon.port)}\n`))
91
+ })
92
+
93
+ /** The runner settings of a config, as `daemonLayer` takes them. */
94
+ export const runnerOf = (config: Partial<Pick<DaemonConfig, "headless" | "kernelUrl" | "name">>) => ({
95
+ headless: config.headless ?? false,
96
+ kernelUrl: config.kernelUrl,
97
+ name: config.name,
98
+ })
99
+
100
+ /**
101
+ * The daemon application over some platform `HttpServer` layer, which must already be bound to the configured
102
+ * host and port. The server stays in the output so callers can read the bound address.
103
+ */
104
+ export const daemonLayer = <E, R>(
105
+ server: Layer.Layer<HttpServer.HttpServer, E, R>,
106
+ daemon: Daemon,
107
+ config: Pick<DaemonConfig, "headless" | "kernelUrl" | "name"> = {
108
+ headless: false,
109
+ kernelUrl: undefined,
110
+ name: undefined,
111
+ },
112
+ ) =>
113
+ DaemonHttp(daemon).pipe(
114
+ Layer.tap(() => started(daemon, config)),
115
+ Layer.provideMerge(server),
116
+ )
117
+
118
+ /** Completes when stdin reaches end of file (the parent closed its end or died). */
119
+ export const stdinClosed = Effect.callback<void>((resume) => {
120
+ const done = () => resume(Effect.void)
121
+ process.stdin.once("end", done)
122
+ process.stdin.once("close", done)
123
+ process.stdin.resume()
124
+ return Effect.sync(() => {
125
+ process.stdin.off("end", done)
126
+ process.stdin.off("close", done)
127
+ process.stdin.pause()
128
+ })
129
+ })
130
+
131
+ /** Run the daemon until interrupted (SIGTERM/SIGINT) or, with the lifeline, until stdin closes. */
132
+ export const program = <E, R>(app: Layer.Layer<never, E, R>, config: Pick<DaemonConfig, "stdinLifeline">) => {
133
+ const serve = Layer.launch(app)
134
+ return config.stdinLifeline ? Effect.raceFirst(serve, stdinClosed) : serve
135
+ }
136
+
137
+ /** Shutting down on a signal or on the lifeline is a clean exit (0); anything else is 1. */
138
+ export const teardown: Teardown = (exit, onExit) => {
139
+ const clean = Exit.isSuccess(exit) || Cause.hasInterruptsOnly(exit.cause)
140
+ onExit(clean ? 0 : 1)
141
+ // runMain only exits by itself after a signal or a failure; the lifeline path ends here.
142
+ if (clean) process.exit(0)
143
+ }
144
+
145
+ /**
146
+ * `approve-client`: the person at this machine approves a local client's pairing with the running daemon (the
147
+ * port from `ELOXIV_DAEMON_PORT` or --port), acting as the host through the control secret in the state
148
+ * directory. Without an id it lists the pending requests; with one it approves it and prints the code to type
149
+ * into the client.
150
+ */
151
+ const approveClient = async (config: DaemonConfig): Promise<number> => {
152
+ const secret = readFileSync(controlSecretPath(config.stateDir), "utf8").trim()
153
+ const base = `http://127.0.0.1:${config.port}`
154
+ const headers = { authorization: `Bearer ${secret}`, "content-type": "application/json" }
155
+ if (config.pairingId === undefined) {
156
+ const pending = (await (await fetch(`${base}/local/pairings`, { headers })).json()) as ReadonlyArray<{
157
+ pairingId: string
158
+ clientName: string
159
+ kind: string
160
+ approved: boolean
161
+ }>
162
+ if (pending.length === 0) process.stdout.write("No local client is waiting to pair.\n")
163
+ for (const entry of pending) {
164
+ process.stdout.write(
165
+ `${entry.pairingId} ${entry.kind} ${JSON.stringify(entry.clientName)}${entry.approved ? " (approved)" : ""}\n`,
166
+ )
167
+ }
168
+ return 0
169
+ }
170
+ const answer = await fetch(`${base}/local/pairings/${encodeURIComponent(config.pairingId)}/approve`, {
171
+ method: "POST",
172
+ headers,
173
+ body: "{}",
174
+ })
175
+ if (!answer.ok) {
176
+ process.stdout.write(`Could not approve ${config.pairingId}: ${await answer.text()}\n`)
177
+ return 1
178
+ }
179
+ const approved = (await answer.json()) as { code: string; clientName: string }
180
+ process.stdout.write(`Approved ${JSON.stringify(approved.clientName)}. Type this code into it: ${approved.code}\n`)
181
+ return 0
182
+ }
183
+
184
+ /**
185
+ * `pairing-code`: the kernel pairing code of the running daemon (the port from `ELOXIV_DAEMON_PORT` or --port),
186
+ * read through the control secret in the state directory, for the person at this machine. The daemon never logs it.
187
+ */
188
+ const pairingCode = async (config: DaemonConfig): Promise<number> => {
189
+ const secret = readFileSync(controlSecretPath(config.stateDir), "utf8").trim()
190
+ const answer = await fetch(`http://127.0.0.1:${config.port}/status`, {
191
+ headers: { authorization: `Bearer ${secret}` },
192
+ })
193
+ if (!answer.ok) {
194
+ process.stdout.write(`Could not read the daemon's status: ${await answer.text()}\n`)
195
+ return 1
196
+ }
197
+ const status = (await answer.json()) as DaemonStatus
198
+ if (status.kernel.userCode === null) {
199
+ process.stdout.write(`No kernel pairing is in progress (this device is ${status.kernel.state}).\n`)
200
+ return 1
201
+ }
202
+ process.stdout.write(
203
+ `Confirm the code ${status.kernel.userCode} at ${status.kernel.verificationUri ?? status.kernel.url ?? "the kernel"}\n`,
204
+ )
205
+ return 0
206
+ }
207
+
208
+ /**
209
+ * `pair`, `status`, `unpair`, `approve-client` and `pairing-code`: one-shot commands, printing to stdout. Resolves to
210
+ * the exit code.
211
+ */
212
+ export const runCommand = async (config: DaemonConfig): Promise<number> => {
213
+ // They talk to the running daemon; starting a second core here would replace that daemon's control secret.
214
+ if (config.command === "approve-client") return approveClient(config)
215
+ if (config.command === "pairing-code") return pairingCode(config)
216
+ const daemon = await createDaemon(config)
217
+ switch (config.command) {
218
+ case "pair": {
219
+ const pairing = await daemon.startKernelPairing(config.kernelUrl!, {
220
+ name: config.name,
221
+ kind: config.runner ? "runner" : "desktop",
222
+ })
223
+ process.stdout.write(
224
+ `To pair this device, sign in at ${pairing.started.verificationUri} and confirm the code ${pairing.started.userCode}\n` +
225
+ `(${pairing.started.verificationUriComplete}). Waiting...\n`,
226
+ )
227
+ try {
228
+ await pairing.done
229
+ } catch (error) {
230
+ process.stdout.write(`Pairing failed: ${String(error instanceof Error ? error.message : error)}\n`)
231
+ return 1
232
+ }
233
+ const kernel = daemon.state.current.kernel!
234
+ process.stdout.write(
235
+ `Paired as device ${kernel.deviceId} in ${kernel.orgId}; the credential is in the ${daemon.options.secrets.kind} store.\n`,
236
+ )
237
+ return 0
238
+ }
239
+ case "status":
240
+ process.stdout.write(`${JSON.stringify(await daemon.status(), null, 2)}\n`)
241
+ return 0
242
+ case "unpair":
243
+ await daemon.unpair()
244
+ process.stdout.write("Unpaired: the credential was deleted (revoke the device on the kernel too).\n")
245
+ return 0
246
+ case "serve":
247
+ return 0
248
+ }
249
+ }
250
+
251
+ /** What a runtime entry (`runtime/bun`, `runtime/node`) gives `mainFor`: its server layer, run-main and SQLite. */
252
+ export interface RuntimeEntry {
253
+ readonly serverLayer: (config: DaemonConfig, daemon: Daemon) => Layer.Layer<never, unknown>
254
+ readonly runMain: (effect: EffectType<unknown, unknown>, options: { readonly teardown: Teardown }) => void
255
+ readonly openSqlite: (path: string) => SyncSqliteDatabase
256
+ }
257
+
258
+ /**
259
+ * The daemon's main for a runtime: the generic sidecar (`bin.ts`), or an app's own with `clientApp` (what it serves
260
+ * LocalClient for, decision 14). One-shot commands run and exit; `serve` runs until interrupted or the lifeline ends.
261
+ */
262
+ export const mainFor =
263
+ (entry: RuntimeEntry) =>
264
+ (
265
+ argv: ReadonlyArray<string> = process.argv.slice(2),
266
+ env: Record<string, string | undefined> = process.env,
267
+ options: { readonly clientApp?: ClientApp | undefined } = {},
268
+ ) => {
269
+ // The host's secret leaves the environment at once: nothing the daemon starts inherits it.
270
+ const config = { ...resolveConfig(argv, env), hostSecret: readHostSecret(env) }
271
+ if (config.command !== "serve") {
272
+ void runCommand(config).then((code) => process.exit(code))
273
+ return
274
+ }
275
+ const overrides =
276
+ options.clientApp === undefined ? {} : { clientApp: options.clientApp, sqlite: entry.openSqlite, env }
277
+ const app = Layer.unwrap(
278
+ Effect.promise(() => createDaemon(config, overrides)).pipe(Effect.map((d) => entry.serverLayer(config, d))),
279
+ )
280
+ entry.runMain(program(app, config), { teardown })
281
+ }
@@ -0,0 +1,203 @@
1
+ /**
2
+ * The daemon's person session for LocalClient (the client core's `SessionStore`): the token in the OS secret store
3
+ * (or its file fallback) under its own key (`personSessionKey`), as before, and the context last open with it
4
+ * remembered for the client core's offline start (`recall`, `remember`, `forgetContext`), so a daemon started without
5
+ * the network serves the person's replica of that organisation from disk at once.
6
+ *
7
+ * - **The remembered context is not a secret, but it is bound to the token.** It is kept in the state directory
8
+ * (`person-context.json`, 0600, written atomically) with a SHA-256 digest of the token it was open with, never the
9
+ * token, and recalled only while the secret store still holds that token.
10
+ * - **It goes with its session.** Forgotten whenever the session is (`clear`, `clearIf`: the context first, so a failure
11
+ * between the two leaves a session that reopens nothing offline), when another token is saved, and alone
12
+ * (`forgetContext`, that token's only).
13
+ * - **Failures are errors.** A read or write the secret store or the file system refuses rejects, never an empty
14
+ * answer for a read of the session, so the core retries a forgetting or forgets the context instead.
15
+ * - **One writer.** Every write and every recall goes through one queue, so `clearIf` compares and clears atomically
16
+ * with the others; a recall reads the context only after the secret store answered, so a context another instance
17
+ * forgot meanwhile is not returned. One daemon per canonical state directory (`lockPersonState`): a second refuses.
18
+ * - **Forgetting has two protections.** The context file is unlinked first and the token deleted from the secret store
19
+ * regardless; a context file that cannot be unlinked (a state directory not writable now) is still harmless once
20
+ * the secret store no longer holds its token (read back), since nothing is recalled without it. Only when both stay
21
+ * does the forgetting reject.
22
+ */
23
+ import type { Account, RememberedContext, SessionStore } from "@eloxiv/client"
24
+ import { createHash } from "node:crypto"
25
+ import { existsSync, readFileSync, realpathSync, renameSync, rmSync, writeFileSync } from "node:fs"
26
+ import { join } from "node:path"
27
+ import type { SecretStore } from "./Secrets.ts"
28
+
29
+ /** Where the context remembered with the person session is kept (beside `state.json`). */
30
+ export const personContextPath = (stateDir: string) => join(stateDir, "person-context.json")
31
+
32
+ /** The lock a daemon serving LocalClient holds on its state directory (beside `state.json`). */
33
+ export const personStateLockPath = (stateDir: string) => join(stateDir, "person-session.lock")
34
+
35
+ /** Canonical state directories locked in this process. */
36
+ const lockedHere = new Set<string>()
37
+ const alive = (pid: number) => {
38
+ if (!Number.isInteger(pid) || pid <= 0) return false
39
+ try {
40
+ process.kill(pid, 0)
41
+ return true
42
+ } catch (error) {
43
+ return (error as { readonly code?: unknown }).code === "EPERM"
44
+ }
45
+ }
46
+
47
+ /**
48
+ * Take the state directory for one daemon's person session (its canonical path: a symlink or `dir/.` is the same
49
+ * one): a lock file holding this process's id, created exclusively. Another daemon's lock (in this process, or a
50
+ * process still running) refuses with an error; one a process that is gone left behind is taken over. Best effort
51
+ * against two daemons taking over the same stale lock at the same instant. A state directory that does not exist holds
52
+ * no person session to share (the daemon creates it before it serves one): nothing to lock.
53
+ */
54
+ export const lockPersonState = (stateDir: string): { readonly release: () => void } => {
55
+ if (!existsSync(stateDir)) return { release: () => undefined }
56
+ const canonical = realpathSync(stateDir)
57
+ const path = personStateLockPath(canonical)
58
+ const taken = () => new Error(`Another daemon already uses the state directory ${canonical}`)
59
+ if (lockedHere.has(canonical)) throw taken()
60
+ for (let attempt = 0; ; attempt++) {
61
+ try {
62
+ writeFileSync(path, `${process.pid}\n`, { flag: "wx", mode: 0o600 })
63
+ break
64
+ } catch (error) {
65
+ if ((error as { readonly code?: unknown }).code !== "EEXIST") throw error
66
+ if (attempt > 0) throw taken()
67
+ let owner = Number.NaN
68
+ try {
69
+ owner = Number.parseInt(readFileSync(path, "utf8"), 10)
70
+ } catch {
71
+ // Unreadable or gone: taken over below (an exclusive create still decides).
72
+ }
73
+ if (owner !== process.pid && alive(owner)) throw taken()
74
+ rmSync(path, { force: true })
75
+ }
76
+ }
77
+ lockedHere.add(canonical)
78
+ let released = false
79
+ return {
80
+ release: () => {
81
+ if (released) return
82
+ released = true
83
+ lockedHere.delete(canonical)
84
+ rmSync(path, { force: true })
85
+ },
86
+ }
87
+ }
88
+
89
+ const digest = (token: string) => createHash("sha256").update(token).digest("hex")
90
+
91
+ export interface PersonSessionStoreOptions {
92
+ readonly secrets: SecretStore
93
+ /** The secret-store key (`personSessionKey(stateDir)`). */
94
+ readonly key: string
95
+ /** The remembered context's file (`personContextPath(stateDir)`). */
96
+ readonly contextPath: string
97
+ /** Told each token read or written (`undefined` once forgotten): the service's scrub keeps the last one. */
98
+ readonly onChange?: ((token: string | undefined) => void) | undefined
99
+ }
100
+
101
+ export const personSessionStore = (options: PersonSessionStoreOptions): SessionStore => {
102
+ const { secrets, key, contextPath } = options
103
+ const onChange = options.onChange ?? (() => undefined)
104
+
105
+ /** Writes, one at a time, in order (a failed one does not stop the next). */
106
+ let queue: Promise<unknown> = Promise.resolve()
107
+ const serial = <A>(task: () => Promise<A>): Promise<A> => {
108
+ const next = queue.then(task, task)
109
+ queue = next.catch(() => undefined)
110
+ return next
111
+ }
112
+
113
+ /** The remembered context and its token's digest, or nothing (absent, torn, or of another shape). */
114
+ const remembered = (): { readonly digest: string; readonly context: RememberedContext } | undefined => {
115
+ if (!existsSync(contextPath)) return undefined
116
+ try {
117
+ const parsed = JSON.parse(readFileSync(contextPath, "utf8")) as {
118
+ readonly tokenDigest?: unknown
119
+ readonly user?: { readonly id?: unknown; readonly email?: unknown; readonly name?: unknown }
120
+ readonly organization?: { readonly orgId?: unknown; readonly name?: unknown; readonly roles?: unknown }
121
+ }
122
+ const { tokenDigest, user, organization } = parsed
123
+ if (typeof tokenDigest !== "string" || typeof user?.id !== "string" || typeof user.email !== "string")
124
+ return undefined
125
+ if (typeof user.name !== "string" || typeof organization?.orgId !== "string") return undefined
126
+ if (typeof organization.name !== "string" || !Array.isArray(organization.roles)) return undefined
127
+ return {
128
+ digest: tokenDigest,
129
+ context: {
130
+ user: { id: user.id, email: user.email, name: user.name },
131
+ organization: {
132
+ orgId: organization.orgId,
133
+ name: organization.name,
134
+ roles: organization.roles.filter((r): r is string => typeof r === "string"),
135
+ },
136
+ },
137
+ }
138
+ } catch {
139
+ return undefined
140
+ }
141
+ }
142
+ const forgetContextFile = () => rmSync(contextPath, { force: true })
143
+ const writeContext = (token: string, context: RememberedContext) => {
144
+ const temporary = `${contextPath}.${process.pid}.tmp`
145
+ writeFileSync(temporary, `${JSON.stringify({ tokenDigest: digest(token), ...context })}\n`, { mode: 0o600 })
146
+ renameSync(temporary, contextPath)
147
+ }
148
+ /**
149
+ * Forget the session and its context (inside `serial`): the context first, and the token whether or not the context
150
+ * file let go. A context file that stays is harmless once the secret store no longer holds its token (read back:
151
+ * `recall` needs it), so only both staying rejects.
152
+ */
153
+ const forgetSession = async () => {
154
+ let stays: unknown
155
+ try {
156
+ forgetContextFile()
157
+ } catch (error) {
158
+ stays = error
159
+ }
160
+ await secrets.delete(key)
161
+ onChange(undefined)
162
+ if (stays !== undefined && (await secrets.get(key)) !== undefined) throw stays
163
+ }
164
+
165
+ return {
166
+ load: async () => {
167
+ const token = await secrets.get(key)
168
+ onChange(token)
169
+ return token
170
+ },
171
+ save: (token: string, _account?: Account) =>
172
+ serial(async () => {
173
+ // Another token's session: what was remembered with the previous one goes first.
174
+ if ((await secrets.get(key)) !== token) forgetContextFile()
175
+ await secrets.set(key, token)
176
+ onChange(token)
177
+ }),
178
+ clear: () => serial(forgetSession),
179
+ clearIf: (token) =>
180
+ serial(async () => {
181
+ if ((await secrets.get(key)) === token) await forgetSession()
182
+ }),
183
+ recall: (token) =>
184
+ serial(async () => {
185
+ // The secret store first, then the file: a context forgotten meanwhile (by another instance) is not returned.
186
+ if ((await secrets.get(key)) !== token) return undefined
187
+ const kept = remembered()
188
+ return kept !== undefined && kept.digest === digest(token) ? kept.context : undefined
189
+ }),
190
+ remember: (token, context) =>
191
+ serial(async () => {
192
+ // Only for the session stored now: a late write for a session forgotten meanwhile keeps nothing.
193
+ if ((await secrets.get(key)) !== token) return
194
+ writeContext(token, context)
195
+ }),
196
+ forgetContext: (token) =>
197
+ serial(async () => {
198
+ // Another token's context stays (it is recalled only for that token); one that cannot be read goes too.
199
+ const kept = remembered()
200
+ if (kept === undefined || kept.digest === digest(token)) forgetContextFile()
201
+ }),
202
+ }
203
+ }