typevault 0.6.1 → 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.
@@ -1,11 +1,14 @@
1
+ import { existsSync, readdirSync } from 'node:fs'
2
+
1
3
  import { encodeSecretKey, generateSecretKey, publicKeyOf, seal, type SecretKey } from './crypto'
2
- import { utf8 } from './encoding'
4
+ import { canonicalJson, utf8 } from './encoding'
3
5
  import { sealEntry, type SignerRef, signerOf } from './entries'
4
6
  import { TypeVaultError } from './errors'
5
- import { wrapPath } from './keyring'
6
- import { type Tier, tiersDoc, includersOf, reach, type VaultState } from './state'
7
+ import { ownerWrapPath, wrapPath } from './keyring'
8
+ import { auditChainOf, handover, ownerDoc, readOwner, signAuditChain } from './owner-trust'
9
+ import { type Tier, tiersDoc, includersOf, reach, type VaultState, membersDoc, signersDoc, ceilingsDoc } from './state'
7
10
  import type { Txn } from './txn'
8
- import type { Vault } from './vault'
11
+ import type { ScanProblem, StoredEntry, Vault } from './vault'
9
12
 
10
13
  export type RotateContext = {
11
14
  readonly vault: Vault
@@ -17,6 +20,51 @@ export type RotateContext = {
17
20
  readonly exposed: boolean
18
21
  }
19
22
 
23
+ export async function rotateOwner(context: RotateContext): Promise<readonly string[]> {
24
+ const { vault, state, txn } = context
25
+ // Git doesn't take the vault lock, so owner.json can change under a rotation. The handover extends the owner document
26
+ // this rotation validated, and is staged only while owner.json still is exactly that document.
27
+ const previous = { recipient: state.owner.recipient, signPublic: state.owner.signPublic, handovers: state.handovers }
28
+ const unchanged = () => {
29
+ const current = readOwner(vault.layout)
30
+ const { recipient, signPublic, handovers } = current
31
+ if (
32
+ canonicalJson({ recipient, signPublic, handovers }) !== canonicalJson(previous) ||
33
+ auditChainOf(current) !== state.origin
34
+ )
35
+ throw new TypeVaultError('conflict', 'owner.json changed while rotating the owner key; pull and retry')
36
+ }
37
+ unchanged()
38
+ const owner = await generateSecretKey({ kind: 'owner' })
39
+ const pub = await publicKeyOf(owner)
40
+ const encoded = utf8(encodeSecretKey(owner))
41
+ for (const [name, member] of Object.entries(state.members)) {
42
+ if (member.owner) txn.put(ownerWrapPath(name), await seal([member.recipient], encoded))
43
+ }
44
+ txn.put('members.json', membersDoc(state.members, owner, state.seqs.members + 1))
45
+ txn.put('signers.json', signersDoc(state.signers, owner, state.seqs.signers + 1))
46
+ txn.put('ceilings.json', ceilingsDoc(state.ceilings, owner, state.seqs.ceilings + 1))
47
+ const affected = await rotateTiers({ ...context, owner, state: { ...state, owner: pub } }, Object.keys(state.tiers))
48
+ unchanged()
49
+ // The new owner endorses the same audit chain, so the vault's committed audit anchors keep their name.
50
+ const audit = signAuditChain(state.origin, owner, pub.signPublic)
51
+ txn.put('owner.json', ownerDoc(pub, handover(previous, context.owner, pub), audit))
52
+ return affected
53
+ }
54
+
55
+ const unaccountedEntryFiles = (
56
+ vault: Vault,
57
+ entries: readonly StoredEntry[],
58
+ problems: readonly ScanProblem[],
59
+ ): readonly string[] => {
60
+ const accounted = new Set([
61
+ ...entries.map(({ envelope }) => `${envelope.id}.json`),
62
+ ...problems.map(({ file }) => file),
63
+ ])
64
+ const files = existsSync(vault.layout.entries) ? readdirSync(vault.layout.entries) : []
65
+ return files.filter((file) => file.endsWith('.json') && !accounted.has(file))
66
+ }
67
+
20
68
  const signedBy = (signer: SignerRef, tier: string): boolean =>
21
69
  (signer.kind === 'tier' && signer.tier === tier) ||
22
70
  (signer.kind === 'cert' && signer.cert.issuer.kind === 'tier' && signer.cert.issuer.tier === tier)
@@ -29,7 +77,8 @@ const signedBy = (signer: SignerRef, tier: string): boolean =>
29
77
  */
30
78
  export async function rotateTiers(context: RotateContext, names: readonly string[]): Promise<readonly string[]> {
31
79
  const { vault, owner, state, txn, exposed } = context
32
- if (names.length === 0) return []
80
+ const ownerChanged = state.owner.signPublic !== vault.state.owner.signPublic
81
+ if (names.length === 0 && !ownerChanged) return []
33
82
  const rotated = new Map<string, { readonly key: SecretKey; readonly tier: Tier }>()
34
83
  for (const name of new Set(names)) {
35
84
  const meta = state.tiers[name]
@@ -71,7 +120,19 @@ export async function rotateTiers(context: RotateContext, names: readonly string
71
120
  const reached = new Set([...rotated.keys()].flatMap((name) => [...reach(state.tiers, name)]))
72
121
  const affected: string[] = []
73
122
  const now = new Date().toISOString()
74
- const { entries } = await vault.scan()
123
+ const { entries, problems } = await vault.scan()
124
+ // A scan leaves out entries no held key opens. An owner rotation must re-seal every one of them, or the ones it misses
125
+ // stay sealed to the old keys alone, so each entry file has to be read or reported.
126
+ const unopened = ownerChanged ? unaccountedEntryFiles(vault, entries, problems) : []
127
+ if (ownerChanged && problems.length + unopened.length > 0) {
128
+ const files = [...problems, ...unopened.map((file) => ({ file, reason: 'its tier key cannot be opened' }))]
129
+ .map(({ file, reason }) => `${file} (${reason})`)
130
+ .join(', ')
131
+ throw new TypeVaultError(
132
+ 'tampered',
133
+ `cannot rotate the owner while entries are unreadable: ${files}. Run typevault doctor; move a file you can't vouch for out of entries/ (or restore it from git), then retry`,
134
+ )
135
+ }
75
136
  for (const { envelope, payload } of entries) {
76
137
  const reachable = reached.has(envelope.tier)
77
138
  if (!reachable && ![...rotated.keys()].some((name) => signedBy(envelope.signer, name))) continue
package/src/core/state.ts CHANGED
@@ -5,9 +5,9 @@ import { z } from 'zod'
5
5
  import { type PublicKey, type SecretKey, sign, verifySignature } from './crypto'
6
6
  import { canonicalJson, type Json, utf8 } from './encoding'
7
7
  import { TypeVaultError } from './errors'
8
- import { atomicWrite, ensureDir } from './fsx'
9
8
  import { readJsonFile } from './json-file'
10
9
  import type { Layout } from './layout'
10
+ import { auditChainOf, type Owner, PublicKeySchema, readOwner as verifiedOwner, trustOwner } from './owner-trust'
11
11
  import { RevisionMarks } from './revisions'
12
12
 
13
13
  export type Tier = {
@@ -42,6 +42,10 @@ export type ManifestSeqs = {
42
42
 
43
43
  export type VaultState = {
44
44
  readonly owner: PublicKey
45
+ /** The vault's first owner key, its audit identity: signed by the current owner and pinned on this machine. */
46
+ readonly origin: string
47
+ /** The verified handover chain that led to `owner`. */
48
+ readonly handovers: Owner['handovers']
45
49
  /** Each manifest's sequence number: every signed change bumps it, and a lower one is a rollback. */
46
50
  readonly seqs: ManifestSeqs
47
51
  readonly tiers: Tiers
@@ -61,7 +65,6 @@ export function parseMemberName(name: string): string {
61
65
  return name
62
66
  }
63
67
 
64
- const PublicKeySchema = z.object({ recipient: z.string().startsWith('age1'), signPublic: z.string() })
65
68
  const TierSchema = PublicKeySchema.extend({ includes: z.array(z.string()), gen: z.number().int().positive() })
66
69
  const seq = z.number().int().positive()
67
70
  const TiersBody = z.object({ v: z.literal(1), seq, tiers: z.record(z.string(), TierSchema) })
@@ -83,7 +86,6 @@ const SignersBody = z.object({
83
86
  signers: z.record(z.string(), z.object({ signPublic: z.string(), tiers: z.array(z.string()) })),
84
87
  })
85
88
  const CeilingsBody = z.object({ v: z.literal(1), seq, ceilings: z.record(z.string(), z.string()) })
86
- const TrustSchema = z.object({ ownerSignPublic: z.string() })
87
89
 
88
90
  export const signedDoc = (body: Json, key: SecretKey): string =>
89
91
  `${JSON.stringify({ body, sig: sign(key.signSecret, utf8(canonicalJson(body))) }, null, 2)}\n`
@@ -106,24 +108,6 @@ function readSigned<T extends Json>(path: string, schema: z.ZodType<T>, owner: P
106
108
  return parsed.data
107
109
  }
108
110
 
109
- /** The owner key is trusted on first use (or pinned via TYPEVAULT_OWNER); a changed key is tampering. */
110
- function checkTrust(layout: Layout, owner: PublicKey, env: Readonly<Record<string, string | undefined>>): void {
111
- const pinned = env['TYPEVAULT_OWNER']
112
- if (pinned !== undefined && pinned !== '') {
113
- if (pinned !== owner.signPublic) throw new TypeVaultError('tampered', 'vault owner does not match TYPEVAULT_OWNER')
114
- return
115
- }
116
- if (!existsSync(layout.trustFile)) {
117
- ensureDir(layout.root, 0o700)
118
- atomicWrite(layout.trustFile, JSON.stringify({ ownerSignPublic: owner.signPublic }), 0o600)
119
- return
120
- }
121
- const trust = readJsonFile(layout.trustFile, TrustSchema)
122
- if (trust.ownerSignPublic !== owner.signPublic) {
123
- throw new TypeVaultError('tampered', 'vault owner key changed since this machine first trusted it')
124
- }
125
- }
126
-
127
111
  export function readOwner(layout: Layout): PublicKey {
128
112
  if (!existsSync(layout.ownerFile))
129
113
  throw new TypeVaultError('not_found', `no vault at ${layout.vault} (run typevault init)`)
@@ -131,14 +115,25 @@ export function readOwner(layout: Layout): PublicKey {
131
115
  }
132
116
 
133
117
  export function loadState(layout: Layout, env: Readonly<Record<string, string | undefined>> = process.env): VaultState {
134
- const owner = readOwner(layout)
135
- checkTrust(layout, owner, env)
118
+ const owner = verifiedOwner(layout)
136
119
  const tiers = readSigned(layout.tiersFile, TiersBody, owner)
137
120
  const members = readSigned(layout.membersFile, MembersBody, owner)
138
121
  const signers = readSigned(layout.signersFile, SignersBody, owner)
139
122
  const ceilings = readSigned(layout.ceilingsFile, CeilingsBody, owner)
140
123
  // An older, still validly signed manifest from git history would resurrect removed signers or ceilings.
141
124
  const marks = new RevisionMarks(layout.revisionsFile)
125
+ if (!marks.accept('owner:handovers', owner.handovers.length)) {
126
+ throw new TypeVaultError('tampered', 'owner.json has fewer handovers than this machine has seen')
127
+ }
128
+ // The current owner signs the audit chain, so trusting that owner authenticates it. A machine also pins the first
129
+ // chain it trusted, so no later owner.json can move its audit anchors elsewhere.
130
+ const auditChain = auditChainOf(owner)
131
+ const pinned = `owner:audit:${auditChain}`
132
+ if (!marks.allows('owner:audit', 0) && marks.allows(pinned, 0)) {
133
+ throw new TypeVaultError('tampered', 'owner.json names a different audit chain than this machine trusted')
134
+ }
135
+ marks.accept('owner:audit', 1)
136
+ marks.accept(pinned, 1)
142
137
  for (const [name, doc] of [
143
138
  ['tiers', tiers],
144
139
  ['members', members],
@@ -152,9 +147,12 @@ export function loadState(layout: Layout, env: Readonly<Record<string, string |
152
147
  )
153
148
  }
154
149
  }
150
+ trustOwner(layout, owner, env['TYPEVAULT_OWNER'])
155
151
  marks.save()
156
152
  return {
157
153
  owner,
154
+ origin: auditChain,
155
+ handovers: owner.handovers,
158
156
  seqs: { tiers: tiers.seq, members: members.seq, signers: signers.seq, ceilings: ceilings.seq },
159
157
  tiers: tiers.tiers,
160
158
  members: members.members,
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. */
package/src/core/vault.ts CHANGED
@@ -86,9 +86,29 @@ export function resolveName(tiers: Tiers, copies: readonly StoredEntry[]): Store
86
86
  }
87
87
 
88
88
  /** An opened vault directory plus the keys this process holds. All reads and writes go through the vault lock. */
89
+ const pendingTxn = (layout: Layout): boolean => existsSync(layout.txnDir) && readdirSync(layout.txnDir).length > 0
90
+
91
+ /**
92
+ * Runs `read` under the shared vault lock, never on a half-applied transaction: a rotation re-signs manifests and wraps
93
+ * before owner.json, so an unlocked or unrecovered read could mix generations. A transaction left by a writer that died
94
+ * is rolled forward first; one that appears while waiting for the lock sends the read around again.
95
+ */
96
+ export async function readSnapshot<T>(layout: Layout, env: Env, read: () => Promise<T>): Promise<T> {
97
+ // Recovery rewrites the journal, and the vault lock doesn't reach another host sharing this state directory.
98
+ refuseForeignDaemon(layout, env)
99
+ for (;;) {
100
+ if (pendingTxn(layout)) await withLock(layout.lockFile, 'exclusive', async () => recoverTxns(layout))
101
+ const snapshot = await withLock(layout.lockFile, 'shared', async () =>
102
+ pendingTxn(layout) ? undefined : { value: await read() },
103
+ )
104
+ if (snapshot !== undefined) return snapshot.value
105
+ }
106
+ }
107
+
89
108
  export class Vault {
90
109
  readonly layout: Layout
91
110
  readonly #keys: readonly SecretKey[]
111
+ readonly #openedOwner: string
92
112
  readonly #env: Env
93
113
  readonly #member: string | undefined
94
114
  #state: VaultState
@@ -98,6 +118,7 @@ export class Vault {
98
118
  this.layout = layout
99
119
  this.#keys = keys
100
120
  this.#env = env
121
+ this.#openedOwner = state.owner.signPublic
101
122
  this.#member = member
102
123
  this.#state = state
103
124
  this.#keyring = new Keyring(layout, state, keys)
@@ -105,21 +126,24 @@ export class Vault {
105
126
 
106
127
  /** Opens the vault with `keys`. An owner member's key also brings the owner key it unwraps. */
107
128
  static async open(layout: Layout, keys: readonly SecretKey[], env: Env = process.env): Promise<Vault> {
108
- refuseForeignDaemon(layout, env)
109
- if (existsSync(layout.txnDir) && readdirSync(layout.txnDir).length > 0) {
110
- await withLock(layout.lockFile, 'exclusive', async () => recoverTxns(layout))
111
- }
112
- const state = loadState(layout, env)
113
- const owner = await unwrapOwner(layout, state, keys)
114
- const [member] = await heldMembers(state, keys)
115
- const all = owner === undefined || keys.includes(owner) ? keys : [...keys, owner]
116
- return new Vault(layout, all, env, state, member?.name)
129
+ return readSnapshot(layout, env, async () => {
130
+ const state = loadState(layout, env)
131
+ const owner = await unwrapOwner(layout, state, keys)
132
+ const [member] = await heldMembers(state, keys)
133
+ const all = owner === undefined || keys.includes(owner) ? keys : [...keys, owner]
134
+ return new Vault(layout, all, env, state, member?.name)
135
+ })
117
136
  }
118
137
 
119
138
  get state(): VaultState {
120
139
  return this.#state
121
140
  }
122
141
 
142
+ /** The audit anchors file this vault's validated state names: the only one its audit writes checkpoint to. */
143
+ get anchorsFile(): string {
144
+ return this.layout.anchorsFileFor(this.#state.origin)
145
+ }
146
+
123
147
  get keyring(): Keyring {
124
148
  return this.#keyring
125
149
  }
@@ -135,8 +159,20 @@ export class Vault {
135
159
 
136
160
  /** Re-reads owner-signed state; call after another process may have changed it. */
137
161
  refresh(): void {
162
+ this.reload()
163
+ if (this.#state.owner.signPublic !== this.#openedOwner) {
164
+ throw new TypeVaultError(
165
+ 'locked',
166
+ 'the vault owner rotated; reopen the vault (for a session, run typevault lock then typevault unlock)',
167
+ )
168
+ }
169
+ }
170
+
171
+ /** Apply committed state without transferring an already-open handle's authority across a handover. */
172
+ reload(): void {
138
173
  this.#state = loadState(this.layout, this.#env)
139
- this.#keyring = new Keyring(this.layout, this.#state, this.#keys)
174
+ const keys = this.#state.owner.signPublic === this.#openedOwner ? this.#keys : []
175
+ this.#keyring = new Keyring(this.layout, this.#state, keys)
140
176
  }
141
177
 
142
178
  /** Every entry this process can open. Untrustworthy files are reported, never returned. */
@@ -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 {
@@ -66,13 +68,17 @@ export function adminRoutes(context: DaemonContext, ceiling: Ceiling): Readonly<
66
68
  label: body.label,
67
69
  ceiling: ceiling.name,
68
70
  })
69
- await appendAudit(context.vault.layout, {
70
- action: 'grant.issue',
71
- mode: 'live',
72
- grant: record.id,
73
- label: record.label,
74
- tiers: record.tiers,
75
- })
71
+ await appendAudit(
72
+ context.vault.layout,
73
+ {
74
+ action: 'grant.issue',
75
+ mode: 'live',
76
+ grant: record.id,
77
+ label: record.label,
78
+ tiers: record.tiers,
79
+ },
80
+ context.vault.anchorsFile,
81
+ )
76
82
  return json({ token, id: record.id, exp: record.exp })
77
83
  },
78
84
  '/v1/grants': async () => json(context.grants.list().filter(ownedBy(ceiling, await currentTier(context, ceiling)))),
@@ -84,14 +90,18 @@ export function adminRoutes(context: DaemonContext, ceiling: Ceiling): Readonly<
84
90
  (record) => owned(record) && (record.id === id || (label !== undefined && record.label === label)),
85
91
  )
86
92
  for (const grant of revoked) context.sessions.delete(grant)
87
- await appendAudit(context.vault.layout, {
88
- action: 'grant.revoke',
89
- mode: 'live',
90
- entries: [],
91
- tiers: [],
92
- ...(label === undefined ? {} : { label }),
93
- ...(id === undefined ? {} : { grant: id }),
94
- })
93
+ await appendAudit(
94
+ context.vault.layout,
95
+ {
96
+ action: 'grant.revoke',
97
+ mode: 'live',
98
+ entries: [],
99
+ tiers: [],
100
+ ...(label === undefined ? {} : { label }),
101
+ ...(id === undefined ? {} : { grant: id }),
102
+ },
103
+ context.vault.anchorsFile,
104
+ )
95
105
  return json({ revoked })
96
106
  },
97
107
  '/v1/audit': async (request) => {
@@ -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[]
@@ -167,13 +210,17 @@ export function agentRoutes(context: DaemonContext): Readonly<Record<string, Han
167
210
  ceiling: grant.record.ceiling,
168
211
  })
169
212
  const { record } = issued
170
- await appendAudit(context.vault.layout, {
171
- action: 'grant.derive',
172
- mode: 'live',
173
- grant: record.id,
174
- label: record.label,
175
- tiers: record.tiers,
176
- })
213
+ await appendAudit(
214
+ context.vault.layout,
215
+ {
216
+ action: 'grant.derive',
217
+ mode: 'live',
218
+ grant: record.id,
219
+ label: record.label,
220
+ tiers: record.tiers,
221
+ },
222
+ context.vault.anchorsFile,
223
+ )
177
224
  return json({ token: issued.token, id: record.id, exp: record.exp })
178
225
  },
179
226
  '/v1/request': async (request) => {
@@ -186,10 +233,49 @@ export function agentRoutes(context: DaemonContext): Readonly<Record<string, Han
186
233
  ),
187
234
  )
188
235
  },
189
- // 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
+ },
190
276
  '/v1/attach': async (request) => {
191
- const { record } = session(context, request).grant
192
- 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) {
193
279
  throw new TypeVaultError('denied', 'only an unlocked session can be shared with a worktree')
194
280
  }
195
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