typevault 0.7.0 → 0.7.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.
package/src/core/txn.ts CHANGED
@@ -50,7 +50,18 @@ function checkRel(rel: string): string {
50
50
  return path
51
51
  }
52
52
 
53
- /** Stages every file, writes the commit marker, then applies. Caller must hold the exclusive vault lock. */
53
+ /** Applying a transaction failed after its commit marker: it is committed, and recovery rolls it forward. */
54
+ export class MarkedCommitted extends Error {
55
+ constructor(cause: unknown) {
56
+ super('the transaction is committed, but applying it failed', { cause })
57
+ this.name = 'MarkedCommitted'
58
+ }
59
+ }
60
+
61
+ /**
62
+ * Stages every file, writes the commit marker, then applies. Caller must hold the exclusive vault lock. A failure
63
+ * before the marker leaves nothing behind; one after it is a MarkedCommitted.
64
+ */
54
65
  export function commitTxn(layout: Layout, txn: Txn): void {
55
66
  if (txn.isEmpty) return
56
67
  const dir = join(layout.txnDir, randomHex(8))
@@ -58,8 +69,19 @@ export function commitTxn(layout: Layout, txn: Txn): void {
58
69
  const puts = [...txn.puts.keys()]
59
70
  puts.forEach((rel, index) => atomicWrite(join(dir, 'files', String(index)), txn.puts.get(rel) ?? new Uint8Array()))
60
71
  atomicWrite(join(dir, 'manifest.json'), JSON.stringify({ puts, removes: [...txn.removes] }))
61
- atomicWrite(join(dir, COMMITTED), '')
62
- applyTxn(layout, dir)
72
+ const marker = join(dir, COMMITTED)
73
+ try {
74
+ atomicWrite(marker, '')
75
+ } catch (error) {
76
+ // The marker renames into place before its directory syncs: once it is there, recovery rolls the change forward.
77
+ if (existsSync(marker)) throw new MarkedCommitted(error)
78
+ throw error
79
+ }
80
+ try {
81
+ applyTxn(layout, dir)
82
+ } catch (error) {
83
+ throw new MarkedCommitted(error)
84
+ }
63
85
  }
64
86
 
65
87
  /** Idempotent: a crash halfway through is finished by running it again. */
@@ -1,9 +1,11 @@
1
1
  import { z } from 'zod'
2
2
 
3
+ import packageJson from '../../package.json' with { type: 'json' }
4
+
3
5
  /**
4
- * This release's version, read once when the module loads: a daemon reports it, so a CLI from another release knows
5
- * not to talk to it. Read any later, an idle daemon would report the version of a package upgraded under it.
6
+ * This release's version, fixed when the module loads: a daemon reports it, so a CLI from another release knows not
7
+ * to talk to it. Read any later, an idle daemon would report the version of a package upgraded under it. A static
8
+ * import (not a file read beside the source) is inlined by the bundler, so a program built with
9
+ * `bun build --compile` reports it too.
6
10
  */
7
- export const PACKAGE_VERSION = z
8
- .object({ version: z.string() })
9
- .parse(await Bun.file(new URL('../../package.json', import.meta.url)).json()).version
11
+ export const PACKAGE_VERSION = z.object({ version: z.string() }).parse(packageJson).version
@@ -13,12 +13,14 @@ export type Ceiling = { readonly name: string; readonly tier: string | '*' }
13
13
 
14
14
  /**
15
15
  * The ceiling this socket holds right now, `undefined` once removed. Read per request: the owner may lower or remove
16
- * it while the daemon runs, and the socket must not keep granting what it was started with.
16
+ * it while the daemon runs, and the socket must not keep granting what it was started with. Without a signed ceiling,
17
+ * `default` is the owner's uncapped socket whenever this daemon holds the owner key, even if one was signed at startup.
17
18
  */
18
19
  async function currentTier(context: DaemonContext, ceiling: Ceiling): Promise<string | undefined> {
19
20
  const { vault } = context
20
21
  await withLock(vault.layout.lockFile, 'shared', async () => vault.refresh())
21
- return vault.state.ceilings[ceiling.name] ?? (ceiling.tier === '*' ? '*' : undefined)
22
+ const uncapped = ceiling.name === 'default' && vault.keyring.owner !== undefined
23
+ return vault.state.ceilings[ceiling.name] ?? (uncapped ? '*' : undefined)
22
24
  }
23
25
 
24
26
  function checkCeiling(context: DaemonContext, ceiling: string | undefined, tiers: readonly string[]): void {
@@ -3,12 +3,18 @@ import { randomBytes } from 'node:crypto'
3
3
  import { parseTtl } from '../access/scope'
4
4
  import { ScopedVault } from '../access/scoped'
5
5
  import { appendAudit } from '../audit/log'
6
+ import { type AdminResult, runAdminOp } from '../core/admin'
6
7
  import { TypeVaultError } from '../core/errors'
7
8
  import type { Vault } from '../core/vault'
8
9
  import { PACKAGE_VERSION } from '../core/version'
9
10
  import { type GrantStore, type ResolvedGrant, SESSION_CEILING } from './grants'
10
11
  import { type Handler, json, parseBody } from './http'
12
+ import { OWNER_CHANGE_POLL_MS, type OwnerChanges, readOutcome } from './owner-changes'
13
+ import type { OwnerWindow } from './owner-window'
11
14
  import {
15
+ AdminBody,
16
+ AdminResultSchema,
17
+ AdminWaitBody,
12
18
  AttachBody,
13
19
  DeriveBody,
14
20
  ImportBody,
@@ -33,8 +39,16 @@ export type DaemonContext = {
33
39
  readonly sessionTiers?: readonly string[]
34
40
  /** An unlocked session's: starts the same session in another worktree of this vault's repository, until `exp`. */
35
41
  readonly attach?: (vault: string, exp: number) => Promise<void>
42
+ /** An unlocked session's: when its owner changes go through. */
43
+ readonly ownerWindow?: OwnerWindow
44
+ /** An unlocked session's: opens the admin socket of a ceiling an owner change just set; returns those that failed. */
45
+ readonly serveNewCeilings?: () => readonly string[]
46
+ /** An unlocked session's: the owner changes it admitted, run one at a time. */
47
+ readonly ownerChanges?: OwnerChanges<OwnerChangeResult>
36
48
  }
37
49
 
50
+ export type OwnerChangeResult = AdminResult & { readonly unserved: readonly string[]; readonly scopeRefreshed: boolean }
51
+
38
52
  function bearer(request: Request): string {
39
53
  const header = request.headers.get('authorization') ?? ''
40
54
  if (!header.startsWith('Bearer ')) throw new TypeVaultError('denied', 'missing grant (set TYPEVAULT_GRANT)')
@@ -60,6 +74,35 @@ function session(context: DaemonContext, request: Request): { grant: ResolvedGra
60
74
  return { grant, access }
61
75
  }
62
76
 
77
+ /** The unlocked session's own grant: a grant derived from it (an agent's) can't share it or change the vault's owner state. */
78
+ function ownSession(context: DaemonContext, request: Request, refusal: string): ResolvedGrant {
79
+ const { grant } = session(context, request)
80
+ if (grant.record.ceiling !== SESSION_CEILING || grant.record.parent !== undefined) {
81
+ throw new TypeVaultError('denied', refusal)
82
+ }
83
+ return grant
84
+ }
85
+
86
+ const OWNER_ONLY = 'owner changes go through an unlocked session only'
87
+
88
+ /**
89
+ * A session reaches every tier its key does, as when it opened: a tier an owner change added or included among them. Its
90
+ * cached scope is updated in place, keeping the values it handed out for redaction, and only once the grant is saved,
91
+ * so the two never disagree. False when finding those tiers or saving the grant failed.
92
+ */
93
+ async function refreshScope(context: DaemonContext, grant: ResolvedGrant): Promise<boolean> {
94
+ let tiers: string[]
95
+ try {
96
+ tiers = [...(await context.vault.keyring.reachableTiers())].sort()
97
+ context.grants.retier(grant.record.id, tiers)
98
+ } catch (error) {
99
+ console.error('typevault daemon: widening the session grant after an owner change failed', error)
100
+ return false
101
+ }
102
+ context.sessions.get(grant.record.id)?.rescope([{ tiers, only: grant.record.only }])
103
+ return true
104
+ }
105
+
63
106
  type StagedImport = {
64
107
  readonly grant: string
65
108
  readonly parts: Uint8Array[]
@@ -190,10 +233,49 @@ export function agentRoutes(context: DaemonContext): Readonly<Record<string, Han
190
233
  ),
191
234
  )
192
235
  },
193
- // Only the session's own grant shares it: a grant derived from it (an agent's) can't widen itself to a worktree.
236
+ '/v1/admin/challenge': async (request) => {
237
+ ownSession(context, request, OWNER_ONLY)
238
+ const window = context.ownerWindow
239
+ if (window === undefined) throw new TypeVaultError('denied', OWNER_ONLY)
240
+ return json({ open: window.isOpen, nonce: window.challenge() })
241
+ },
242
+ '/v1/admin': async (request) => {
243
+ const grant = ownSession(context, request, OWNER_ONLY)
244
+ const { ownerWindow: window, ownerChanges } = context
245
+ if (window === undefined || ownerChanges === undefined) throw new TypeVaultError('denied', OWNER_ONLY)
246
+ const { request: op, proof, change } = await parseBody(request, AdminBody)
247
+ // A caller that lost the answer asks again under the same id: that change already has, or will have, its outcome.
248
+ if (ownerChanges.has(change)) return json({ change })
249
+ if (proof !== undefined) {
250
+ const { vault } = context
251
+ const member = vault.member === undefined ? undefined : vault.state.members[vault.member]
252
+ if (member === undefined) throw new TypeVaultError('denied', 'this session holds no member key to prove')
253
+ window.open(proof.nonce, proof.signature, member.signPublic)
254
+ }
255
+ if (!window.isOpen) throw new TypeVaultError('locked', 'owner changes need your password or Touch ID again')
256
+ ownerChanges.admit(change, async () => {
257
+ const result = await runAdminOp(context.vault, op)
258
+ // Committed: what follows can't undo it, so a failure there is reported beside the result, never instead of it.
259
+ // A vault left on its old state can't say what the session now reaches; its next refresh reloads it or fails closed.
260
+ const scopeRefreshed = result.reloaded && (await refreshScope(context, grant))
261
+ return { ...result, scopeRefreshed, unserved: context.serveNewCeilings?.() ?? [] }
262
+ })
263
+ return json({ change })
264
+ },
265
+ // The change's own random id authorizes collecting its outcome, which names no secret value: the session that
266
+ // admitted it may have expired meanwhile, and the caller must still learn what to rotate at the source.
267
+ '/v1/admin/wait': async (request) => {
268
+ const { change, waitMs } = await parseBody(request, AdminWaitBody)
269
+ // A daemon with no owner queue (say a machine member's, started after a session drained a change and stopped)
270
+ // answers from the receipts that session left in the run directory.
271
+ if (context.ownerChanges === undefined) {
272
+ return json(readOutcome(context.vault.layout.run, change, AdminResultSchema) ?? { state: 'unknown' })
273
+ }
274
+ return json(await context.ownerChanges.wait(change, waitMs ?? OWNER_CHANGE_POLL_MS))
275
+ },
194
276
  '/v1/attach': async (request) => {
195
- const { record } = session(context, request).grant
196
- if (context.attach === undefined || record.ceiling !== SESSION_CEILING || record.parent !== undefined) {
277
+ const { record } = ownSession(context, request, 'only an unlocked session can be shared with a worktree')
278
+ if (context.attach === undefined) {
197
279
  throw new TypeVaultError('denied', 'only an unlocked session can be shared with a worktree')
198
280
  }
199
281
  const { vault } = await parseBody(request, AttachBody)
@@ -16,7 +16,7 @@ const CODES: readonly ErrorCode[] = [
16
16
  'no_vault',
17
17
  'not_member',
18
18
  ]
19
- const toCode = (code: string): ErrorCode => CODES.find((known) => known === code) ?? 'unavailable'
19
+ export const toCode = (code: string): ErrorCode => CODES.find((known) => known === code) ?? 'unavailable'
20
20
 
21
21
  export type CallOptions = { readonly token?: string; readonly timeoutMs?: number }
22
22
 
@@ -45,11 +45,20 @@ export async function callDaemon<T>(
45
45
  if (error.name === 'TimeoutError') {
46
46
  throw new TypeVaultError('unavailable', 'the typevault daemon request timed out', { cause: error })
47
47
  }
48
- throw new TypeVaultError('unavailable', `the typevault daemon is not reachable at ${socket}`)
48
+ throw new TypeVaultError('unavailable', `the typevault daemon is not reachable at ${socket}`, { cause: error })
49
+ }
50
+ throw error
51
+ }
52
+ let payload: unknown
53
+ try {
54
+ payload = await response.json()
55
+ } catch (error) {
56
+ // A reply cut off after its headers was lost in transport like a dropped connection: it is no answer from the daemon.
57
+ if (error instanceof Error) {
58
+ throw new TypeVaultError('unavailable', 'the typevault daemon reply was cut off', { cause: error })
49
59
  }
50
60
  throw error
51
61
  }
52
- const payload: unknown = await response.json()
53
62
  if (!response.ok) {
54
63
  const parsed = ErrorSchema.safeParse(payload)
55
64
  throw parsed.success
@@ -13,10 +13,13 @@ import { loadState, readOwner } from '../core/state'
13
13
  import { readSnapshot, Vault } from '../core/vault'
14
14
  import { worktreeVaults } from '../core/worktrees'
15
15
  import { adminRoutes, type Ceiling } from './admin-routes'
16
- import { agentRoutes, type DaemonContext } from './agent-routes'
16
+ import { agentRoutes, type DaemonContext, type OwnerChangeResult } from './agent-routes'
17
17
  import { isDaemonAlive } from './client'
18
18
  import { GrantStore, SESSION_CEILING } from './grants'
19
19
  import { errorResponse, json, router } from './http'
20
+ import { OwnerChanges } from './owner-changes'
21
+ import { OwnerWindow } from './owner-window'
22
+ import { AdminResultSchema } from './protocol'
20
23
  import { type PromptOptions, PromptRequests } from './requests'
21
24
  import { LOCKED_MESSAGE, startSession, stopDaemon } from './spawn'
22
25
 
@@ -100,7 +103,7 @@ async function serve(options: DaemonOptions, claim: DaemonClaim, releaseLock: ()
100
103
  if (vault.keyring.owner === undefined && vault.member === undefined) {
101
104
  throw new TypeVaultError('denied', 'this key is not a member of the vault')
102
105
  }
103
- const ceilings = ceilingsOf(vault)
106
+ const ceilings = [...ceilingsOf(vault)]
104
107
  if (ceilings.length === 0 && options.session === undefined)
105
108
  throw new TypeVaultError('invalid', 'no ceilings configured (typevault ceiling set <name> <tier>)')
106
109
 
@@ -144,13 +147,22 @@ async function serve(options: DaemonOptions, claim: DaemonClaim, releaseLock: ()
144
147
  requests: new PromptRequests(vault, options.prompt ?? {}),
145
148
  ...(options.session === undefined
146
149
  ? {}
147
- : { sessionTiers: member?.tiers ?? [], ...(attach === undefined ? {} : { attach }) }),
150
+ : {
151
+ sessionTiers: member?.tiers ?? [],
152
+ ownerWindow: new OwnerWindow(),
153
+ ownerChanges: new OwnerChanges<OwnerChangeResult>(layout.run, AdminResultSchema),
154
+ serveNewCeilings: () => serveNewCeilings(),
155
+ ...(attach === undefined ? {} : { attach }),
156
+ }),
148
157
  }
149
158
  // A shared session whose source is gone answers nothing but ping (how `stopDaemon` finds it) until it stops.
150
159
  const bound =
151
160
  (fetch: (request: Request) => Promise<Response>) =>
152
161
  async (request: Request): Promise<Response> => {
153
- if (new URL(request.url).pathname === '/v1/ping') return fetch(request)
162
+ const path = new URL(request.url).pathname
163
+ // Collecting an owner change's outcome reads only this daemon's memory: it must not queue behind the vault lock that
164
+ // change holds, and it keeps answering while a shared session whose source ended drains that change.
165
+ if (path === '/v1/ping' || path === '/v1/admin/wait') return fetch(request)
154
166
  if (!sourceAlive()) return errorResponse(new TypeVaultError('locked', LOCKED_MESSAGE))
155
167
  try {
156
168
  // Includes cached redaction values and worktree attachment: neither necessarily scans the vault. The snapshot
@@ -168,11 +180,11 @@ async function serve(options: DaemonOptions, claim: DaemonClaim, releaseLock: ()
168
180
  if (process.platform !== 'win32') chmodSync(path, 0o600)
169
181
  return server
170
182
  }
183
+ const serveCeiling = (ceiling: Ceiling) =>
184
+ listen(layout.adminSocket(ceiling.name), bound(router(adminRoutes(context, ceiling))))
171
185
  const servers = [
172
186
  listen(layout.agentSocket, bound(router(agentRoutes(context)))),
173
- ...ceilings.map((ceiling) =>
174
- listen(layout.adminSocket(ceiling.name), bound(router(adminRoutes(context, ceiling)))),
175
- ),
187
+ ...ceilings.map(serveCeiling),
176
188
  listen(
177
189
  layout.controlSocket,
178
190
  router({
@@ -184,6 +196,23 @@ async function serve(options: DaemonOptions, claim: DaemonClaim, releaseLock: ()
184
196
  }),
185
197
  ),
186
198
  ]
199
+ // A ceiling set through this session gets its socket right away; stopping removes it with the others. One whose socket
200
+ // can't open stays untracked, so the next owner change tries again, and is returned: the change itself committed.
201
+ const serveNewCeilings = (): readonly string[] => {
202
+ const unserved: string[] = []
203
+ for (const ceiling of ceilingsOf(vault)) {
204
+ if (ceilings.some((served) => served.name === ceiling.name)) continue
205
+ try {
206
+ servers.push(serveCeiling(ceiling))
207
+ } catch (error) {
208
+ console.error(`typevault daemon: opening the admin socket of ceiling "${ceiling.name}" failed`, error)
209
+ unserved.push(ceiling.name)
210
+ continue
211
+ }
212
+ ceilings.push(ceiling)
213
+ }
214
+ return unserved
215
+ }
187
216
  atomicWrite(join(layout.run, 'daemon.pid'), String(process.pid), 0o600)
188
217
  const session = options.session === undefined ? undefined : await openSession(context, options.session.ttlMs)
189
218
  const adopt = (): void => {
@@ -205,8 +234,12 @@ async function serve(options: DaemonOptions, claim: DaemonClaim, releaseLock: ()
205
234
  clearInterval(watch)
206
235
  stopping = true
207
236
  try {
237
+ // Closed before the first wait, so nothing is admitted while attachments settle. A change still running would
238
+ // otherwise persist grants or open sockets after cleanup.
239
+ const ownerChanges = context.ownerChanges?.stop()
208
240
  // An attachment still starting would otherwise leave its worktree unlocked after this stop.
209
241
  await Promise.allSettled(attaching)
242
+ await ownerChanges
210
243
  // The claim was cleared and someone else's daemon now owns the grants, session and run files. Saving this
211
244
  // daemon's stale grant store or removing those files would undo its successor's, so only local resources go.
212
245
  if (!claim.owns()) {
@@ -58,10 +58,12 @@ export class GrantStore {
58
58
  this.#records = existsSync(path) ? readJsonFile(path, z.array(RecordSchema)) : []
59
59
  }
60
60
 
61
- #save(): void {
61
+ /** Writes `records` first, so a failed write leaves the grants in memory as they are on disk. */
62
+ #save(records: readonly GrantRecord[] = this.#records): void {
62
63
  const now = Date.now()
63
- this.#records = this.#records.filter((record) => Date.parse(record.exp) > now)
64
- atomicWrite(this.#path, JSON.stringify(this.#records), 0o600)
64
+ const live = records.filter((record) => Date.parse(record.exp) > now)
65
+ atomicWrite(this.#path, JSON.stringify(live), 0o600)
66
+ this.#records = live
65
67
  }
66
68
 
67
69
  issue(request: GrantRequest): { readonly token: string; readonly record: GrantRecord } {
@@ -117,6 +119,10 @@ export class GrantStore {
117
119
  return { record, chain: chain.map(({ tiers, only }) => ({ tiers, only })) }
118
120
  }
119
121
 
122
+ retier(id: string, tiers: readonly string[]): void {
123
+ this.#save(this.#records.map((record) => (record.id === id ? { ...record, tiers: [...tiers] } : record)))
124
+ }
125
+
120
126
  /** Whether grant `id` and all its ancestors are still unrevoked and unexpired. */
121
127
  isLive(id: string): boolean {
122
128
  for (let link = this.#records.find((r) => r.id === id); link !== undefined;) {
@@ -0,0 +1,203 @@
1
+ import { existsSync, readdirSync, readFileSync, rmSync, statSync } from 'node:fs'
2
+ import { join } from 'node:path'
3
+
4
+ import { z } from 'zod'
5
+
6
+ import { UncertainChange } from '../core/admin'
7
+ import { TypeVaultError } from '../core/errors'
8
+ import { atomicWrite, ensureDir } from '../core/fsx'
9
+ import { toCode } from './client'
10
+
11
+ /** Under Bun's 10-second idle timeout, which also cuts a request whose handler hasn't answered yet. */
12
+ export const OWNER_CHANGE_POLL_MS = 5_000
13
+ /** How long an outcome stays readable, and so how long admitting the same id again is recognized as a retry. */
14
+ export const OWNER_CHANGE_KEEP_MS = 10 * 60_000
15
+ export const OwnerChangeId = z.string().regex(/^[A-Za-z0-9_-]{22}$/, 'not an owner change id')
16
+
17
+ const ChangeErrorSchema = z.object({ code: z.string(), message: z.string() })
18
+ const Outcome = z.union([
19
+ z.object({ result: z.unknown() }),
20
+ z.object({ error: ChangeErrorSchema }),
21
+ z.object({ uncertain: ChangeErrorSchema }),
22
+ ])
23
+ type Outcome = z.infer<typeof Outcome>
24
+ export type ChangeError = { readonly code: string; readonly message: string }
25
+ /**
26
+ * A settled change: what it returned, the error it failed with, or, committed by its marker but not yet written, an
27
+ * uncertain outcome the vault finishes later. None is the same as having no receipt.
28
+ */
29
+ export type Settled<T> =
30
+ | { readonly state: 'done'; readonly result: T }
31
+ | { readonly state: 'failed'; readonly error: ChangeError }
32
+ | { readonly state: 'uncertain'; readonly error: ChangeError }
33
+ export type Waited<T> = Settled<T> | { readonly state: 'running' } | { readonly state: 'unknown' }
34
+
35
+ const outcomesDir = (run: string): string => join(run, 'owner-changes')
36
+ const outcomePath = (run: string, id: string): string => join(outcomesDir(run), `${OwnerChangeId.parse(id)}.json`)
37
+
38
+ const missing = (error: unknown): boolean => error instanceof Error && 'code' in error && error.code === 'ENOENT'
39
+
40
+ /** Whether the receipt at `path` is past its window; one removed meanwhile counts as past it. */
41
+ function expired(path: string): boolean {
42
+ try {
43
+ return statSync(path).mtimeMs + OWNER_CHANGE_KEEP_MS <= Date.now()
44
+ } catch (error) {
45
+ if (missing(error)) return true
46
+ throw error
47
+ }
48
+ }
49
+
50
+ // Cleanup only: a receipt removed meanwhile is already gone, and one that can't be removed is refused on reads anyway.
51
+ function remove(path: string): void {
52
+ try {
53
+ rmSync(path)
54
+ } catch (error) {
55
+ if (!missing(error)) console.error('typevault daemon: removing an expired owner-change outcome failed', error)
56
+ }
57
+ }
58
+
59
+ export function readOutcome<T>(run: string, id: string, schema: z.ZodType<T>): Settled<T> | undefined {
60
+ const path = outcomePath(run, id)
61
+ if (!existsSync(path)) return undefined
62
+ if (expired(path)) {
63
+ remove(path)
64
+ return undefined
65
+ }
66
+ const outcome = Outcome.parse(JSON.parse(readFileSync(path, 'utf8')))
67
+ if ('error' in outcome) return { state: 'failed', error: outcome.error }
68
+ if ('uncertain' in outcome) return { state: 'uncertain', error: outcome.uncertain }
69
+ return { state: 'done', result: schema.parse(outcome.result) }
70
+ }
71
+
72
+ /** The settled change's own result, or its own error thrown. */
73
+ export function settledResult<T>(settled: Settled<T>): T {
74
+ if (settled.state === 'done') return settled.result
75
+ throw new TypeVaultError(toCode(settled.error.code), settled.error.message)
76
+ }
77
+
78
+ /**
79
+ * Owner changes through a session, one at a time, so each publishes its effects in commit order. A rotation can outlast
80
+ * any one request, and the session itself, so a change is admitted at once under the caller's own random id, the
81
+ * receipt it polls with, and its outcome is kept for a while: in memory, and in the run directory for a caller whose
82
+ * daemon stopped meanwhile. Within that window, admitting an id again changes nothing, so a caller that lost the answer
83
+ * can ask again; past it, the id is unknown.
84
+ * Stopping admits nothing new, cancels what hasn't started and waits for the one running.
85
+ */
86
+ export class OwnerChanges<T> {
87
+ readonly #run: string
88
+ readonly #schema: z.ZodType<T>
89
+ #tail: Promise<unknown> = Promise.resolve()
90
+ #stopping = false
91
+ readonly #changes = new Map<string, { readonly settled: Promise<Settled<T>>; settledAt?: number }>()
92
+
93
+ constructor(run: string, schema: z.ZodType<T>) {
94
+ this.#run = run
95
+ this.#schema = schema
96
+ this.#prune()
97
+ }
98
+
99
+ has(id: string): boolean {
100
+ const change = this.#change(id)
101
+ if (change !== undefined) return true
102
+ const path = outcomePath(this.#run, id)
103
+ return existsSync(path) && !expired(path)
104
+ }
105
+
106
+ admit(id: string, run: () => Promise<T>): void {
107
+ if (this.has(id)) return
108
+ if (this.#stopping) throw new TypeVaultError('locked', 'this session is locking: nothing changed')
109
+ this.#prune()
110
+ const done = this.#tail.then(() => {
111
+ if (this.#stopping)
112
+ throw new TypeVaultError('locked', 'the session locked before this change started: nothing changed')
113
+ return run()
114
+ })
115
+ const settled = done.then(
116
+ (result): Settled<T> => ({ state: 'done', result }),
117
+ (error: unknown): Settled<T> =>
118
+ error instanceof UncertainChange
119
+ ? { state: 'uncertain', error: { code: error.code, message: error.message } }
120
+ : { state: 'failed', error: outcomeError(error) },
121
+ )
122
+ this.#changes.set(id, { settled })
123
+ this.#tail = settled.then((outcome) => this.#keep(id, onDisk(outcome)))
124
+ }
125
+
126
+ async wait(id: string, waitMs: number): Promise<Waited<T>> {
127
+ const settled = this.#change(id)?.settled
128
+ if (settled === undefined) return readOutcome(this.#run, id, this.#schema) ?? { state: 'unknown' }
129
+ const { promise: timedOut, resolve } = Promise.withResolvers<Waited<T>>()
130
+ const timer = setTimeout(() => resolve({ state: 'running' }), waitMs)
131
+ try {
132
+ return await Promise.race([settled, timedOut])
133
+ } finally {
134
+ clearTimeout(timer)
135
+ }
136
+ }
137
+
138
+ /** Closes admission at once; settles once the running change has finished and its outcome is kept. */
139
+ stop(): Promise<void> {
140
+ this.#stopping = true
141
+ return this.#tail.then(() => undefined)
142
+ }
143
+
144
+ // The change has settled whatever happens here: a receipt that can't be written leaves it in memory only, and never
145
+ // stops the next change or a drain.
146
+ #change(id: string): { readonly settled: Promise<Settled<T>>; settledAt?: number } | undefined {
147
+ const change = this.#changes.get(id)
148
+ if (change?.settledAt !== undefined && change.settledAt + OWNER_CHANGE_KEEP_MS <= Date.now()) {
149
+ this.#changes.delete(id)
150
+ return undefined
151
+ }
152
+ return change
153
+ }
154
+
155
+ #keep(id: string, outcome: Outcome): void {
156
+ const change = this.#changes.get(id)
157
+ if (change !== undefined) change.settledAt = Date.now()
158
+ setTimeout(() => this.#changes.delete(id), OWNER_CHANGE_KEEP_MS).unref()
159
+ try {
160
+ ensureDir(outcomesDir(this.#run), 0o700)
161
+ atomicWrite(outcomePath(this.#run, id), JSON.stringify(outcome), 0o600)
162
+ } catch (error) {
163
+ console.error('typevault daemon: keeping the outcome of an owner change on disk failed', error)
164
+ }
165
+ }
166
+
167
+ #prune(): void {
168
+ const dir = outcomesDir(this.#run)
169
+ let files: string[]
170
+ try {
171
+ files = existsSync(dir) && statSync(dir).isDirectory() ? readdirSync(dir) : []
172
+ } catch (error) {
173
+ console.error('typevault daemon: listing owner-change outcomes failed', error)
174
+ return
175
+ }
176
+ for (const file of files) {
177
+ const path = join(dir, file)
178
+ try {
179
+ if (expired(path)) remove(path)
180
+ } catch (error) {
181
+ console.error('typevault daemon: checking an owner-change outcome failed', error)
182
+ }
183
+ }
184
+ }
185
+ }
186
+
187
+ function onDisk<T>(settled: Settled<T>): Outcome {
188
+ switch (settled.state) {
189
+ case 'done':
190
+ return { result: settled.result }
191
+ case 'failed':
192
+ return { error: settled.error }
193
+ case 'uncertain':
194
+ return { uncertain: settled.error }
195
+ }
196
+ }
197
+
198
+ function outcomeError(error: unknown): ChangeError {
199
+ if (error instanceof TypeVaultError) return { code: error.code, message: error.message }
200
+ // Unexpected failures stay out of outcomes, as out of responses: they may carry details an agent shouldn't see.
201
+ console.error('typevault daemon: owner change failed', error)
202
+ return { code: 'unavailable', message: 'internal daemon error' }
203
+ }
@@ -0,0 +1,41 @@
1
+ import { randomToken, verifySignature } from '../core/crypto'
2
+ import { utf8 } from '../core/encoding'
3
+ import { TypeVaultError } from '../core/errors'
4
+
5
+ export const OWNER_WINDOW_MS = 5 * 60_000
6
+ const CHALLENGE_TTL_MS = 5 * 60_000
7
+
8
+ export const ownerWindowMessage = (nonce: string): Uint8Array => utf8(`typevault owner window ${nonce}`)
9
+
10
+ /**
11
+ * Agents run as the same user and can read the session token, so a session alone never makes owner changes: they go
12
+ * through only within a few minutes of a proof, a challenge signed with the member's own key, which only an owner
13
+ * command makes. It starts closed, so an unlock for reading opens nothing. A chain of owner commands asks once; an
14
+ * agent can't open the window itself.
15
+ */
16
+ export class OwnerWindow {
17
+ #until = 0
18
+ readonly #challenges = new Map<string, number>()
19
+
20
+ get isOpen(): boolean {
21
+ return Date.now() < this.#until
22
+ }
23
+
24
+ challenge(): string {
25
+ const now = Date.now()
26
+ for (const [nonce, exp] of this.#challenges) if (exp <= now) this.#challenges.delete(nonce)
27
+ const nonce = randomToken(16)
28
+ this.#challenges.set(nonce, now + CHALLENGE_TTL_MS)
29
+ return nonce
30
+ }
31
+
32
+ /** Each challenge works once, so a captured proof can't reopen the window. */
33
+ open(nonce: string, signature: string, signPublic: string): void {
34
+ const exp = this.#challenges.get(nonce)
35
+ this.#challenges.delete(nonce)
36
+ if (exp === undefined || exp <= Date.now() || !verifySignature(signPublic, ownerWindowMessage(nonce), signature)) {
37
+ throw new TypeVaultError('denied', 'that proof does not allow owner changes')
38
+ }
39
+ this.#until = Date.now() + OWNER_WINDOW_MS
40
+ }
41
+ }
@@ -2,6 +2,7 @@ import { z } from 'zod'
2
2
 
3
3
  import { isPreset, parseEntryName } from '../core/naming'
4
4
  import { FieldsSchema } from '../core/payload'
5
+ import { OwnerChangeId } from './owner-changes'
5
6
 
6
7
  const name = z.string().transform((value) => parseEntryName(value))
7
8
  const preset = z.string().refine(isPreset, 'unknown preset').optional()
@@ -51,3 +52,46 @@ export const GrantBody = z.object({
51
52
  })
52
53
  export const RevokeBody = z.object({ id: z.string().optional(), label: z.string().optional() })
53
54
  export const AuditBody = z.object({ label: z.string().optional() })
55
+ const named = z.object({
56
+ op: z.enum(['tier.add', 'tier.rm', 'key.rotate', 'ceiling.rm', 'signer.rm', 'member.rm']),
57
+ name: z.string(),
58
+ })
59
+ export const AdminBody = z.object({
60
+ request: z.union([
61
+ named,
62
+ z.object({ op: z.enum(['tier.include', 'tier.exclude']), tier: z.string(), included: z.string() }),
63
+ z.object({ op: z.literal('ceiling.set'), name: z.string(), tier: z.string() }),
64
+ z.object({ op: z.literal('signer.add'), id: z.string(), publicKey: z.string(), tiers }),
65
+ z.object({ op: z.literal('member.add'), name: z.string(), publicKey: z.string(), owner: z.boolean(), tiers }),
66
+ ]),
67
+ proof: z.object({ nonce: z.string().max(64), signature: z.string().max(200) }).optional(),
68
+ /** The caller's own id for this change: admitting it again changes nothing. */
69
+ change: OwnerChangeId,
70
+ })
71
+ export const AdminResultSchema = z.object({
72
+ affected: z.array(z.string()),
73
+ removed: z.array(z.string()),
74
+ ownerRotated: z.boolean(),
75
+ /** False when the change committed but the session's vault couldn't be reloaded after it. */
76
+ reloaded: z.boolean(),
77
+ /** Ceilings the change set whose admin sockets the session couldn't open. */
78
+ unserved: z.array(z.string()),
79
+ /** False when the change committed but the session's grant couldn't be widened to the tiers it now reaches. */
80
+ scopeRefreshed: z.boolean(),
81
+ })
82
+ export const ChallengeSchema = z.object({ open: z.boolean(), nonce: z.string() })
83
+ export const AdmittedSchema = z.object({ change: OwnerChangeId })
84
+ export const AdminWaitBody = z.object({
85
+ change: OwnerChangeId,
86
+ waitMs: z.number().int().min(0).max(5_000).optional(),
87
+ })
88
+ export const AdminWaitedSchema = z.discriminatedUnion('state', [
89
+ z.object({ state: z.literal('running') }),
90
+ /** No receipt for that id: never admitted, or past its window. */
91
+ z.object({ state: z.literal('unknown') }),
92
+ z.object({ state: z.literal('done'), result: AdminResultSchema }),
93
+ /** The change itself failed with this error. */
94
+ z.object({ state: z.literal('failed'), error: z.object({ code: z.string(), message: z.string() }) }),
95
+ /** Committed by its marker but not yet written: the vault finishes it when next opened. */
96
+ z.object({ state: z.literal('uncertain'), error: z.object({ code: z.string(), message: z.string() }) }),
97
+ ])