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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "typevault",
3
- "version": "0.6.1",
3
+ "version": "0.7.1",
4
4
  "description": "CLI-first secrets vault for agents",
5
5
  "homepage": "https://github.com/typeclaw/typevault#readme",
6
6
  "bugs": {
@@ -39,7 +39,7 @@ const valueOf = (entry: StoredEntry): EntryValue =>
39
39
  */
40
40
  export class ScopedVault implements Access {
41
41
  readonly #vault: Vault
42
- readonly #chain: ScopeChain
42
+ #chain: ScopeChain
43
43
  readonly #identity: ScopedIdentity
44
44
  readonly #handedOut = new Set<string>()
45
45
 
@@ -51,12 +51,21 @@ export class ScopedVault implements Access {
51
51
 
52
52
  #audit(event: Omit<AuditEvent, 'mode' | 'grant' | 'label'>): Promise<void> {
53
53
  const { mode, grant, label } = this.#identity
54
- return appendAudit(this.#vault.layout, {
55
- ...event,
56
- mode,
57
- ...(grant === undefined ? {} : { grant }),
58
- ...(label === undefined ? {} : { label }),
59
- })
54
+ return appendAudit(
55
+ this.#vault.layout,
56
+ {
57
+ ...event,
58
+ mode,
59
+ ...(grant === undefined ? {} : { grant }),
60
+ ...(label === undefined ? {} : { label }),
61
+ },
62
+ this.#vault.anchorsFile,
63
+ )
64
+ }
65
+
66
+ /** A new scope for the same grant; the values handed out so far stay remembered for redaction. */
67
+ rescope(chain: ScopeChain): void {
68
+ this.#chain = chain
60
69
  }
61
70
 
62
71
  #allows(entry: StoredEntry): boolean {
@@ -47,11 +47,15 @@ export class SealedAccess implements Access {
47
47
  return Vault.open(this.#layout, [], this.#env)
48
48
  }
49
49
 
50
- /** Best effort: a sealed grant may run where no vault directory exists. */
51
- async #audit(event: Omit<AuditEvent, 'mode' | 'grant' | 'label'>): Promise<void> {
50
+ /**
51
+ * Best effort: a sealed grant may run where no vault directory exists. Writes pass the anchors file of the vault they
52
+ * opened; reads don't open it, so they have none.
53
+ */
54
+ async #audit(event: Omit<AuditEvent, 'mode' | 'grant' | 'label'>, anchorsFile?: string): Promise<void> {
52
55
  const layout = this.#layout
53
56
  if (layout === undefined || !existsSync(layout.ownerFile)) return
54
- await appendAudit(layout, { ...event, mode: 'sealed', grant: this.#bundle.id, label: this.#bundle.label })
57
+ const record = { ...event, mode: 'sealed' as const, grant: this.#bundle.id, label: this.#bundle.label }
58
+ await appendAudit(layout, record, anchorsFile ?? layout.fixedAnchorsFile)
55
59
  }
56
60
 
57
61
  async list(): Promise<readonly EntrySummary[]> {
@@ -97,7 +101,7 @@ export class SealedAccess implements Access {
97
101
  { ref: { kind: 'cert', cert: bundle.write.cert }, signSecret: sealedSigningSecret(bundle) },
98
102
  { ...(ifRev === undefined ? {} : { ifRev }), ...(prior === undefined ? {} : { base: prior }) },
99
103
  )
100
- await this.#audit({ action: 'write', entries: [input.name], tiers: [tier] })
104
+ await this.#audit({ action: 'write', entries: [input.name], tiers: [tier] }, vault.anchorsFile)
101
105
  const { envelope, payload } = stored
102
106
  return {
103
107
  name: payload.name,
@@ -129,7 +133,7 @@ export class SealedAccess implements Access {
129
133
  allowsEntry([{ tiers: cert.tiers, only: cert.only }], vault.state, envelope.tier, name) &&
130
134
  signerAuthority({ kind: 'cert', cert }, envelope.tier, vault.state, new Date().toISOString()) !== undefined,
131
135
  )
132
- await this.#audit({ action: 'remove', entries: [name] })
136
+ await this.#audit({ action: 'remove', entries: [name] }, vault.anchorsFile)
133
137
  }
134
138
 
135
139
  async move(from: EntryName, to: EntryName): Promise<void> {
@@ -71,14 +71,18 @@ export async function issueSealedGrant(vault: Vault, request: SealedRequest): Pr
71
71
  const write = { signSecret: toBase64(signing.signSecret), cert }
72
72
  const identity = await generateX25519Identity()
73
73
  const sealed = await seal([await identityToRecipient(identity)], utf8(JSON.stringify({ ...bundle, write })))
74
- await appendAudit(vault.layout, {
75
- action: 'grant.issue',
76
- mode: 'sealed',
77
- grant: id,
78
- label: request.label,
79
- tiers: request.tiers,
80
- entries: granted.map((value) => value.name),
81
- })
74
+ await appendAudit(
75
+ vault.layout,
76
+ {
77
+ action: 'grant.issue',
78
+ mode: 'sealed',
79
+ grant: id,
80
+ label: request.label,
81
+ tiers: request.tiers,
82
+ entries: granted.map((value) => value.name),
83
+ },
84
+ vault.anchorsFile,
85
+ )
82
86
  return `${PREFIX}${toBase64Url(utf8(identity))}.${toBase64Url(sealed)}`
83
87
  }
84
88
 
package/src/audit/log.ts CHANGED
@@ -1,5 +1,15 @@
1
- import { appendFileSync, closeSync, existsSync, fsyncSync, openSync, readFileSync, readSync, statSync } from 'node:fs'
2
- import { dirname, relative } from 'node:path'
1
+ import {
2
+ appendFileSync,
3
+ closeSync,
4
+ existsSync,
5
+ fsyncSync,
6
+ openSync,
7
+ readdirSync,
8
+ readFileSync,
9
+ readSync,
10
+ statSync,
11
+ } from 'node:fs'
12
+ import { basename, dirname, relative } from 'node:path'
3
13
 
4
14
  import { z } from 'zod'
5
15
 
@@ -75,15 +85,46 @@ export function readAudit(layout: Layout): readonly AuditRecord[] {
75
85
  .map((line) => parseJsonText(layout.auditLog, line, RecordSchema))
76
86
  }
77
87
 
78
- function writeAnchor(layout: Layout, last: AuditRecord): void {
79
- // The anchors live in the committed vault: a pulled symlink there must not redirect this append.
80
- assertNoSymlinks(dirname(layout.vault), relative(dirname(layout.vault), layout.anchorsFile))
81
- ensureDir(dirname(layout.anchorsFile))
82
- appendLine(layout.anchorsFile, JSON.stringify({ seq: last.seq, hash: last.hash, at: last.at }))
88
+ /** Another state-directory chain's anchors file beside `anchorsFile`, when `anchorsFile` is one. A vault has only one. */
89
+ function otherStateAnchors(anchorsFile: string): string | undefined {
90
+ const name = basename(anchorsFile)
91
+ const dir = dirname(anchorsFile)
92
+ if (!name.startsWith('state-') || !existsSync(dir)) return undefined
93
+ return readdirSync(dir).find((file) => file.startsWith('state-') && file.endsWith('.jsonl') && file !== name)
83
94
  }
84
95
 
85
- /** Appends one hash-chained record; every 100th record's head is anchored in the (committable) vault. */
86
- export function appendAudit(layout: Layout, event: AuditEvent): Promise<void> {
96
+ function writeAnchor(layout: Layout, anchorsFile: string, last: AuditRecord): void {
97
+ assertInVault(layout, anchorsFile)
98
+ ensureDir(dirname(anchorsFile))
99
+ appendLine(anchorsFile, JSON.stringify({ seq: last.seq, hash: last.hash, at: last.at }))
100
+ }
101
+
102
+ // The anchors live in the committed vault: a pulled symlink there must not redirect a read or an append.
103
+ const assertInVault = (layout: Layout, anchorsFile: string): void =>
104
+ assertNoSymlinks(dirname(layout.vault), relative(dirname(layout.vault), anchorsFile))
105
+
106
+ /**
107
+ * The last checkpoint's seq, for catching up deferred ones. An anchors file it can't read or parse gives undefined
108
+ * rather than throwing: this runs after the operation being audited took effect, checkpoint writes keep their own
109
+ * checks, and verification reports the damage.
110
+ */
111
+ function lastAnchoredSeq(layout: Layout, anchorsFile: string): number | undefined {
112
+ try {
113
+ assertInVault(layout, anchorsFile)
114
+ if (!existsSync(anchorsFile)) return 0
115
+ const last = readFileSync(anchorsFile, 'utf8').trimEnd().split('\n').at(-1)
116
+ return last === undefined || last === '' ? 0 : AnchorSchema.parse(JSON.parse(last)).seq
117
+ } catch {
118
+ return undefined
119
+ }
120
+ }
121
+
122
+ /**
123
+ * Appends one hash-chained record; every 100th record's head is anchored in the (committable) vault. `anchorsFile` is
124
+ * the one a validated vault state names. Without it, a state-directory chain has no trusted destination: the record
125
+ * stays in the local log and its checkpoint waits for the next write that has one.
126
+ */
127
+ export function appendAudit(layout: Layout, event: AuditEvent, anchorsFile = layout.fixedAnchorsFile): Promise<void> {
87
128
  return withLock(layout.auditLock, 'exclusive', async () => {
88
129
  ensureDir(layout.audit, 0o700)
89
130
  const last = readLast(layout)
@@ -91,15 +132,19 @@ export function appendAudit(layout: Layout, event: AuditEvent): Promise<void> {
91
132
  const unhashed = { ...fields, seq: (last?.seq ?? 0) + 1, at: new Date().toISOString(), prev: last?.hash ?? GENESIS }
92
133
  const record = { ...unhashed, hash: hashOf(unhashed) }
93
134
  appendLine(layout.auditLog, JSON.stringify(record))
94
- if (record.seq % ANCHOR_EVERY === 0) writeAnchor(layout, record)
135
+ if (anchorsFile === undefined) return
136
+ const anchored = record.seq % ANCHOR_EVERY === 0 ? undefined : lastAnchoredSeq(layout, anchorsFile)
137
+ const due = record.seq % ANCHOR_EVERY === 0 || (anchored !== undefined && record.seq - anchored >= ANCHOR_EVERY)
138
+ if (due) writeAnchor(layout, anchorsFile, record)
95
139
  })
96
140
  }
97
141
 
98
- /** Anchors the current head now, e.g. when the daemon stops. */
99
- export function anchorAudit(layout: Layout): Promise<void> {
142
+ /** Anchors the current head now, in the anchors file a validated vault state names. */
143
+ export function anchorAudit(layout: Layout, anchorsFile = layout.fixedAnchorsFile): Promise<void> {
100
144
  return withLock(layout.auditLock, 'exclusive', async () => {
101
145
  const last = readAudit(layout).at(-1)
102
- if (last !== undefined) writeAnchor(layout, last)
146
+ if (anchorsFile === undefined || last === undefined) return
147
+ writeAnchor(layout, anchorsFile, last)
103
148
  })
104
149
  }
105
150
 
@@ -107,17 +152,25 @@ export type AuditVerdict =
107
152
  | { readonly ok: true; readonly records: number }
108
153
  | { readonly ok: false; readonly reason: string }
109
154
 
110
- /** Recomputes the chain and checks every anchor against it. A log too damaged to read fails the check. */
111
- export function verifyAudit(layout: Layout): AuditVerdict {
155
+ /**
156
+ * Recomputes the chain and checks every anchor against it. A log too damaged to read fails the check. `anchorsFile`
157
+ * defaults to the one owner.json names; pass the one a validated vault state names instead.
158
+ */
159
+ export function verifyAudit(layout: Layout, anchorsFile = layout.anchorsFile): AuditVerdict {
112
160
  try {
113
- return verifyChain(layout)
161
+ return verifyChain(layout, anchorsFile)
114
162
  } catch (error) {
115
163
  if (error instanceof TypeVaultError && error.code === 'tampered') return { ok: false, reason: error.message }
116
164
  throw error
117
165
  }
118
166
  }
119
167
 
120
- function verifyChain(layout: Layout): AuditVerdict {
168
+ function verifyChain(layout: Layout, anchorsFile: string): AuditVerdict {
169
+ // A vault's state-directory chain never changes name, so anchors under another name mean the owner history this
170
+ // machine accepted (on first use) isn't the one they were made for: report it rather than skip anchors it can't check.
171
+ // Only verification checks this, so a stray anchors file can't keep the vault from opening.
172
+ const other = otherStateAnchors(anchorsFile)
173
+ if (other !== undefined) return { ok: false, reason: `anchors exist for another audit chain (${other})` }
121
174
  const records = readAudit(layout)
122
175
  let prev = GENESIS
123
176
  const heads = new Map<number, string>()
@@ -130,7 +183,7 @@ function verifyChain(layout: Layout): AuditVerdict {
130
183
  heads.set(record.seq, hash)
131
184
  prev = hash
132
185
  }
133
- const anchors = [layout.legacyAnchorsFile, layout.anchorsFile].flatMap((file) =>
186
+ const anchors = [layout.legacyAnchorsFile, anchorsFile].flatMap((file) =>
134
187
  existsSync(file)
135
188
  ? readFileSync(file, 'utf8')
136
189
  .split('\n')
@@ -14,7 +14,7 @@ import { parseEntryName } from '../../core/naming'
14
14
  import { Vault } from '../../core/vault'
15
15
  import { GrantStore } from '../../daemon/grants'
16
16
  import { stopDaemon } from '../../daemon/spawn'
17
- import { layoutFrom, openAdmin, openDirect, openPublic, wantsGlobal } from '../context'
17
+ import { layoutFrom, openDirect, openPublic, runAdmin, wantsGlobal } from '../context'
18
18
  import { csv, note, print, table } from '../output'
19
19
  import { ensureIdentity, identityArgs } from './members'
20
20
 
@@ -74,23 +74,29 @@ export const tier = defineCommand({
74
74
  add: defineCommand({
75
75
  meta: { name: 'add' },
76
76
  args: named,
77
- run: async ({ args }) => (await openAdmin(process.env)).addTier(args.name),
77
+ run: async ({ args }) => void (await runAdmin(process.env, { op: 'tier.add', name: args.name })),
78
78
  }),
79
79
  rm: defineCommand({
80
80
  meta: { name: 'rm' },
81
81
  args: named,
82
- run: async ({ args }) => (await openAdmin(process.env)).removeTier(args.name),
82
+ run: async ({ args }) => void (await runAdmin(process.env, { op: 'tier.rm', name: args.name })),
83
83
  }),
84
84
  include: defineCommand({
85
85
  meta: { name: 'include', description: '<tier> reaches everything <included> reaches' },
86
86
  args: pair,
87
- run: async ({ args }) => (await openAdmin(process.env)).include(args.tier, args.included),
87
+ run: async ({ args }) =>
88
+ void (await runAdmin(process.env, { op: 'tier.include', tier: args.tier, included: args.included })),
88
89
  }),
89
90
  exclude: defineCommand({
90
91
  meta: { name: 'exclude', description: 'Drop an include and rotate the included tier' },
91
92
  args: pair,
92
93
  async run({ args }) {
93
- printRotation(args.included, await (await openAdmin(process.env)).exclude(args.tier, args.included))
94
+ const { affected } = await runAdmin(process.env, {
95
+ op: 'tier.exclude',
96
+ tier: args.tier,
97
+ included: args.included,
98
+ })
99
+ printRotation(args.included, affected)
94
100
  },
95
101
  }),
96
102
  },
@@ -121,7 +127,7 @@ export const key = defineCommand({
121
127
  },
122
128
  args: named,
123
129
  async run({ args }) {
124
- printRotation(args.name, await (await openAdmin(process.env)).rotate(args.name))
130
+ printRotation(args.name, (await runAdmin(process.env, { op: 'key.rotate', name: args.name })).affected)
125
131
  },
126
132
  }),
127
133
  },
@@ -140,12 +146,13 @@ export const ceiling = defineCommand({
140
146
  set: defineCommand({
141
147
  meta: { name: 'set' },
142
148
  args: { name: { type: 'positional', required: true }, tier: { type: 'positional', required: true } },
143
- run: async ({ args }) => (await openAdmin(process.env)).setCeiling(args.name, args.tier),
149
+ run: async ({ args }) =>
150
+ void (await runAdmin(process.env, { op: 'ceiling.set', name: args.name, tier: args.tier })),
144
151
  }),
145
152
  rm: defineCommand({
146
153
  meta: { name: 'rm' },
147
154
  args: named,
148
- run: async ({ args }) => (await openAdmin(process.env)).removeCeiling(args.name),
155
+ run: async ({ args }) => void (await runAdmin(process.env, { op: 'ceiling.rm', name: args.name })),
149
156
  }),
150
157
  },
151
158
  })
@@ -169,12 +176,18 @@ export const signer = defineCommand({
169
176
  publicKey: { type: 'positional', required: true, description: 'Base64 Ed25519 public key' },
170
177
  tiers: { type: 'string', required: true, description: 'Comma-separated tiers, or *' },
171
178
  },
172
- run: async ({ args }) => (await openAdmin(process.env)).setSigner(args.id, args.publicKey, csv(args.tiers)),
179
+ run: async ({ args }) =>
180
+ void (await runAdmin(process.env, {
181
+ op: 'signer.add',
182
+ id: args.id,
183
+ publicKey: args.publicKey,
184
+ tiers: csv(args.tiers),
185
+ })),
173
186
  }),
174
187
  rm: defineCommand({
175
188
  meta: { name: 'rm' },
176
189
  args: named,
177
- run: async ({ args }) => (await openAdmin(process.env)).removeSigner(args.name),
190
+ run: async ({ args }) => void (await runAdmin(process.env, { op: 'signer.rm', name: args.name })),
178
191
  }),
179
192
  },
180
193
  })
@@ -209,7 +222,8 @@ export const doctor = defineCommand({
209
222
  `same name in several tiers: ${dup} (if the tiers are unrelated, reads of it fail: keep one with \`typevault rm <name> --tier <g>\`)`,
210
223
  )
211
224
  for (const name of report.needsRotation) print(`needs rotation: ${name}`)
212
- const audit = verifyAudit(vault.layout)
225
+ // Anchors from the owner chain this vault was opened against, not from rereading owner.json.
226
+ const audit = verifyAudit(vault.layout, vault.layout.anchorsFileFor(vault.state.origin))
213
227
  print(audit.ok ? `audit: ok (${audit.records} records)` : `audit: BROKEN: ${audit.reason}`)
214
228
  if (report.problems.length > 0 || !audit.ok) process.exitCode = 1
215
229
  },
@@ -9,6 +9,8 @@ import { issueSealedGrant } from '../../access/sealed'
9
9
  import { GrantInfoSchema, IssuedSchema } from '../../admin'
10
10
  import { readAudit, verifyAudit } from '../../audit/log'
11
11
  import { TypeVaultError } from '../../core/errors'
12
+ import { loadState } from '../../core/state'
13
+ import { readSnapshot } from '../../core/vault'
12
14
  import { adminCall, layoutFrom, openDirect } from '../context'
13
15
  import { csv, print, table } from '../output'
14
16
 
@@ -72,7 +74,11 @@ export const audit = defineCommand({
72
74
  async run({ args }) {
73
75
  const layout = layoutFrom(process.env)
74
76
  if (args.verify) {
75
- const verdict = verifyAudit(layout)
77
+ // The anchors file comes from the owner chain that just passed the trust check, not from rereading owner.json.
78
+ const verdict = await readSnapshot(layout, process.env, async () => {
79
+ const { origin } = loadState(layout, process.env)
80
+ return verifyAudit(layout, layout.anchorsFileFor(origin))
81
+ })
76
82
  print(verdict.ok ? `ok (${verdict.records} records)` : `BROKEN: ${verdict.reason}`)
77
83
  if (!verdict.ok) process.exitCode = 1
78
84
  return
@@ -21,7 +21,7 @@ import {
21
21
  writeIdentity,
22
22
  } from '../../core/identity'
23
23
  import { type Layout, localLayout, vaultIdOf } from '../../core/layout'
24
- import { readOwner } from '../../core/state'
24
+ import { readOwner } from '../../core/owner-trust'
25
25
  import { Vault } from '../../core/vault'
26
26
  import { worktreeVaults } from '../../core/worktrees'
27
27
  import { endLiveGrants, stopDaemon } from '../../daemon/spawn'
@@ -31,8 +31,8 @@ import {
31
31
  DEFAULT_SESSION_MS,
32
32
  findLayout,
33
33
  layoutFrom,
34
- openAdmin,
35
34
  openPublic,
35
+ runAdmin,
36
36
  unlockSession,
37
37
  worktreeSessions,
38
38
  type Env,
@@ -128,7 +128,13 @@ export const member = defineCommand({
128
128
  if (tiers.length === 0 && args.owner !== true)
129
129
  throw new TypeVaultError('invalid', 'member add needs --tier or --owner')
130
130
  const pub = decodeMemberPublic(args.publicKey)
131
- await (await openAdmin(process.env)).addMember(args.name, { ...pub, owner: args.owner === true, tiers })
131
+ await runAdmin(process.env, {
132
+ op: 'member.add',
133
+ name: args.name,
134
+ publicKey: args.publicKey,
135
+ owner: args.owner === true,
136
+ tiers,
137
+ })
132
138
  print(`added ${pub.kind} member ${args.name}${tiers.length === 0 ? '' : ` (rotated ${tiers.join(', ')})`}`)
133
139
  note('commit the vault so they can pull it')
134
140
  },
@@ -137,8 +143,14 @@ export const member = defineCommand({
137
143
  meta: { name: 'rm', description: 'Remove a member and rotate every tier they reached' },
138
144
  args: { name: { type: 'positional', required: true } },
139
145
  async run({ args }) {
140
- const affected = await (await openAdmin(process.env)).removeMember(args.name)
141
- print(`removed ${args.name}`)
146
+ const { affected, removed, ownerRotated } = await runAdmin(process.env, { op: 'member.rm', name: args.name })
147
+ print(`removed ${removed.join(', ')}`)
148
+ if (removed.length > 1) note(`${removed.join(', ')} shared one key, so all of them were removed.`)
149
+ if (ownerRotated) {
150
+ note(
151
+ 'Owner key rotated. Commit the vault; members must pull it. For an open session, run typevault lock then typevault unlock.',
152
+ )
153
+ }
142
154
  if (affected.length === 0) return
143
155
  note('They may have kept what they read. Rotate these secrets at their source, then re-set them:')
144
156
  for (const name of affected) note(` ${name}`)
@@ -235,7 +247,7 @@ export const unlock = defineCommand({
235
247
  const env = process.env
236
248
  const ttlMs = args.for === undefined ? DEFAULT_SESSION_MS : parseTtl(args.for)
237
249
  if (ttlMs > MAX_TIMER_MS) throw new TypeVaultError('invalid', '--for is too long (at most 24 days)')
238
- const started = await unlockSession(env, passwords(), ttlMs)
250
+ const started = (await unlockSession(env, passwords(), ttlMs)) !== undefined
239
251
  const id = vaultIdOf((await openPublic(env)).state.owner.signPublic)
240
252
  print(started ? `unlocked vault ${id} for ${args.for}` : `vault ${id} is already unlocked`)
241
253
  },
@@ -248,9 +260,11 @@ export const lock = defineCommand({
248
260
  if (layout === undefined) throw new TypeVaultError('not_found', 'no vault here')
249
261
  const env = process.env
250
262
  // An owner that can't be read doesn't prove another vault, so lock still reaches it.
251
- const ownerOf = (target: Layout): string | undefined => {
263
+ // Every key the signature-verified handover chain passed through, ending at the current one.
264
+ const ownerOf = (target: Layout): { readonly keys: ReadonlySet<string> } | undefined => {
252
265
  try {
253
- return readOwner(target).signPublic
266
+ const owner = readOwner(target)
267
+ return { keys: new Set([...owner.handovers.map(({ from }) => from), owner.signPublic]) }
254
268
  } catch (error) {
255
269
  if (error instanceof TypeVaultError) return undefined
256
270
  throw error
@@ -263,7 +277,9 @@ export const lock = defineCommand({
263
277
  .map((vault) => localLayout(vault, env))
264
278
  .filter((worktree) => {
265
279
  const other = ownerOf(worktree)
266
- return own === undefined || other === undefined || other === own
280
+ // Any owner key both verified chains passed through: the same vault on another generation (one that hasn't pulled
281
+ // a rotation yet) or rotated independently from a common owner. Claimed origins alone could disagree.
282
+ return own === undefined || other === undefined || [...other.keys].some((key) => own.keys.has(key))
267
283
  })
268
284
  // A session unlocked in any other worktree would only be shared here again on the next read, so it stops too, but
269
285
  // the grants of a different vault are its own.
@@ -7,8 +7,8 @@ import { ScopedVault } from '../access/scoped'
7
7
  import { readSealedGrant } from '../access/sealed'
8
8
  import { SealedAccess } from '../access/sealed-access'
9
9
  import type { Access, EntryValue } from '../access/types'
10
- import { Admin } from '../core/admin'
11
- import type { SecretKey } from '../core/crypto'
10
+ import { type AdminOp, type AdminResult, runAdminOp } from '../core/admin'
11
+ import { randomToken, type SecretKey, sign } from '../core/crypto'
12
12
  import { TypeVaultError } from '../core/errors'
13
13
  import { atomicWrite } from '../core/fsx'
14
14
  import {
@@ -22,12 +22,15 @@ import { findLocalVault, globalLayout, type Layout, localLayout } from '../core/
22
22
  import type { EntryName } from '../core/naming'
23
23
  import { loadState } from '../core/state'
24
24
  import { touchIdAvailable } from '../core/touch-id'
25
- import { Vault } from '../core/vault'
25
+ import { readSnapshot, Vault } from '../core/vault'
26
26
  import { worktreeVaults } from '../core/worktrees'
27
27
  import { callDaemon, isDaemonAlive } from '../daemon/client'
28
28
  import { LiveAccess } from '../daemon/live-access'
29
+ import { ownerWindowMessage } from '../daemon/owner-window'
30
+ import { ChallengeSchema } from '../daemon/protocol'
29
31
  import { ensureDaemon, LOCKED_MESSAGE, startSession, stopDaemon } from '../daemon/spawn'
30
32
  import { note } from './output'
33
+ import { ownerChange } from './owner-change'
31
34
  import { type Passwords, passwords, passwordsFromStdin } from './password'
32
35
 
33
36
  export type Env = Readonly<Record<string, string | undefined>>
@@ -102,11 +105,11 @@ export async function unlockHuman(env: Env, identity: Identity | undefined, pass
102
105
 
103
106
  /**
104
107
  * Unlocks a human member's session: their key goes to a daemon that holds it for `ttlMs`, and this user's CLI
105
- * reads through the session grant it writes. Returns false when a session already runs.
108
+ * reads through the session grant it writes. Returns the key it unlocked with, or undefined when a session already runs.
106
109
  */
107
- export async function unlockSession(env: Env, passwords: Passwords, ttlMs: number): Promise<boolean> {
110
+ export async function unlockSession(env: Env, passwords: Passwords, ttlMs: number): Promise<SecretKey | undefined> {
108
111
  const layout = layoutFrom(env)
109
- if (await hasSession(layout)) return false
112
+ if (await hasSession(layout)) return undefined
110
113
  const identity = readIdentity(env)
111
114
  const key = await unlockHuman(env, identity, passwords)
112
115
  const vault = await Vault.open(layout, [key], env)
@@ -124,7 +127,7 @@ export async function unlockSession(env: Env, passwords: Passwords, ttlMs: numbe
124
127
  note('replaced a running daemon that held no unlocked session')
125
128
  }
126
129
  await startSession(layout, env, key, ttlMs)
127
- return true
130
+ return key
128
131
  }
129
132
 
130
133
  const hasSession = async (layout: Layout): Promise<boolean> =>
@@ -169,7 +172,44 @@ function refreshSealedCopy(vault: Vault, identity: Identity & { readonly kind: '
169
172
  /** The vault's public, owner-signed state, readable without any key. */
170
173
  export const openPublic = (env: Env): Promise<Vault> => Vault.open(layoutFrom(env), [], env)
171
174
 
172
- export const openAdmin = async (env: Env): Promise<Admin> => new Admin(await openDirect(env))
175
+ /**
176
+ * An owner change. A machine member makes it with its own key, and a process under a grant never borrows the person's
177
+ * session for one. A person's goes through their unlocked session (unlocking it first, as a read does), proving they
178
+ * are there with the key that unlock used, or else asking for it once the session's owner window has closed.
179
+ */
180
+ export async function runAdmin(env: Env, request: AdminOp): Promise<AdminResult> {
181
+ const direct = machineKeys(env).length > 0 || isSet(env['TYPEVAULT_GRANT'])
182
+ const result = direct ? await runAdminOp(await openDirect(env), request) : await sessionAdmin(env, request)
183
+ if (!result.reloaded) {
184
+ note(
185
+ 'the change committed, but the vault could not be reloaded after it: run typevault lock, then typevault unlock',
186
+ )
187
+ }
188
+ return result
189
+ }
190
+
191
+ async function sessionAdmin(env: Env, request: AdminOp): Promise<AdminResult> {
192
+ const { access, unlockedWith } = await sessionAccess(env)
193
+ const { open, nonce } = await access.call('/v1/admin/challenge', {}, ChallengeSchema)
194
+ const key = open ? undefined : (unlockedWith ?? (await ownerKey(env)))
195
+ const proof = key === undefined ? undefined : { nonce, signature: sign(key.signSecret, ownerWindowMessage(nonce)) }
196
+ const body = { request, change: randomToken(16), ...(proof === undefined ? {} : { proof }) }
197
+ const { unserved, scopeRefreshed, ...result } = await ownerChange(access, layoutFrom(env), body)
198
+ if (!scopeRefreshed && result.reloaded) {
199
+ note('this session does not reach the tiers the change added yet: run typevault lock, then typevault unlock')
200
+ }
201
+ for (const name of unserved) {
202
+ note(`ceiling "${name}" is set, but its admin socket didn't open: run typevault lock, then typevault unlock`)
203
+ }
204
+ return result
205
+ }
206
+
207
+ async function ownerKey(env: Env): Promise<SecretKey> {
208
+ if (!process.stdin.isTTY && !passwordsFromStdin()) {
209
+ throw new TypeVaultError('locked', 'owner changes need your password or Touch ID: run this at a terminal')
210
+ }
211
+ return unlockHuman(env, readIdentity(env), passwords())
212
+ }
173
213
 
174
214
  export type ResolvedAccess =
175
215
  | { readonly kind: 'live'; readonly access: LiveAccess }
@@ -181,7 +221,7 @@ export async function resolveAccess(env: Env): Promise<ResolvedAccess> {
181
221
  const grant = env['TYPEVAULT_GRANT']?.trim()
182
222
  if (grant === undefined || grant === '') {
183
223
  const machine = machineKeys(env)
184
- if (machine.length === 0) return { kind: 'live', access: await sessionAccess(env) }
224
+ if (machine.length === 0) return { kind: 'live', access: (await sessionAccess(env)).access }
185
225
  const tier = env['TYPEVAULT_TIER']
186
226
  const vault = await Vault.open(layoutFrom(env), machine, env)
187
227
  const ownTiers = vault.member === undefined ? [] : (vault.state.members[vault.member]?.tiers ?? [])
@@ -190,7 +230,7 @@ export async function resolveAccess(env: Env): Promise<ResolvedAccess> {
190
230
  }
191
231
  if (grant.startsWith('tvl1.')) {
192
232
  const layout = layoutFrom(env)
193
- checkOwnerPin(layout, env)
233
+ await checkOwnerPin(layout, env)
194
234
  await ensureDaemon(layout, env)
195
235
  return { kind: 'live', access: new LiveAccess(layout.agentSocket, grant) }
196
236
  }
@@ -202,11 +242,13 @@ export async function resolveAccess(env: Env): Promise<ResolvedAccess> {
202
242
 
203
243
  /**
204
244
  * A human member's CLI reads through the unlocked session's grant. On a terminal a locked vault asks for the
205
- * password right away; anywhere else (an agent) it stays locked until a human unlocks it.
245
+ * password right away; anywhere else (an agent) it stays locked until a human unlocks it. `unlockedWith` is the key a
246
+ * person just unlocked with here.
206
247
  */
207
- async function sessionAccess(env: Env): Promise<LiveAccess> {
248
+ async function sessionAccess(env: Env): Promise<{ readonly access: LiveAccess; readonly unlockedWith?: SecretKey }> {
208
249
  const layout = layoutFrom(env)
209
- checkOwnerPin(layout, env)
250
+ await checkOwnerPin(layout, env)
251
+ let unlockedWith: SecretKey | undefined
210
252
  if (!(await hasSession(layout)) && !(await shareWorktreeSession(layout, env))) {
211
253
  const identity = readIdentity(env)
212
254
  if (identity === undefined) {
@@ -214,19 +256,20 @@ async function sessionAccess(env: Env): Promise<LiveAccess> {
214
256
  }
215
257
  const canAsk = process.stdin.isTTY || passwordsFromStdin()
216
258
  if (identity.kind !== 'human' || !canAsk) throw new TypeVaultError('locked', LOCKED_MESSAGE)
217
- await unlockSession(env, passwords(), DEFAULT_SESSION_MS)
259
+ unlockedWith = await unlockSession(env, passwords(), DEFAULT_SESSION_MS)
218
260
  }
219
261
  // A session daemon from another release fails here instead of misreading this CLI's requests.
220
262
  await ensureDaemon(layout, env)
221
- return new LiveAccess(layout.agentSocket, readFileSync(layout.sessionFile, 'utf8').trim())
263
+ const access = new LiveAccess(layout.agentSocket, readFileSync(layout.sessionFile, 'utf8').trim())
264
+ return unlockedWith === undefined ? { access } : { access, unlockedWith }
222
265
  }
223
266
 
224
267
  /**
225
268
  * A live connection reads through a daemon that may have trusted the owner without this process's pin, so a set
226
269
  * `TYPEVAULT_OWNER` is checked against the vault here, before anything is read through it.
227
270
  */
228
- function checkOwnerPin(layout: Layout, env: Env): void {
229
- if (isSet(env['TYPEVAULT_OWNER'])) loadState(layout, env)
271
+ async function checkOwnerPin(layout: Layout, env: Env): Promise<void> {
272
+ if (isSet(env['TYPEVAULT_OWNER'])) await readSnapshot(layout, env, async () => loadState(layout, env))
230
273
  }
231
274
 
232
275
  /**
package/src/cli/index.ts CHANGED
@@ -2,6 +2,7 @@
2
2
  import { defineCommand, runCommand, runMain } from 'citty'
3
3
 
4
4
  import { TypeVaultError } from '../core/errors'
5
+ import { PACKAGE_VERSION } from '../core/version'
5
6
  import { ceiling, doctor, tier, init, key, signer } from './commands/admin'
6
7
  import { daemon } from './commands/daemon'
7
8
  import { get, ls, mv, otp, rm, set, whoami } from './commands/entries'
@@ -11,7 +12,7 @@ import { importCommand, redact, request, run, scrub } from './commands/run'
11
12
  import { readPasswordsFromStdin } from './password'
12
13
 
13
14
  const main = defineCommand({
14
- meta: { name: 'typevault', description: 'A CLI-first secrets vault for agents' },
15
+ meta: { name: 'typevault', version: PACKAGE_VERSION, description: 'A CLI-first secrets vault for agents' },
15
16
  args: {
16
17
  global: { type: 'boolean', alias: 'g', description: 'Use the global vault instead of the project vault' },
17
18
  'vault-password-stdin': {
@@ -62,9 +63,10 @@ if (argv.slice(0, split).includes(PASSWORD_STDIN)) readPasswordsFromStdin()
62
63
  const ownArgs = argv.slice(0, split).filter((arg) => !isGlobalFlag(arg) && arg !== PASSWORD_STDIN)
63
64
  const rawArgs = [...ownArgs, ...argv.slice(split)]
64
65
  const wantsUsage = ownArgs.length === 0 || ownArgs.some((arg) => arg === '--help' || arg === '-h')
66
+ const wantsVersion = ownArgs.length === 1 && (ownArgs[0] === '--version' || ownArgs[0] === '-v')
65
67
 
66
- if (wantsUsage) {
67
- await runMain(main)
68
+ if (wantsUsage || wantsVersion) {
69
+ await runMain(main, { rawArgs: ownArgs })
68
70
  } else {
69
71
  try {
70
72
  // no-excuse-ok: catch (top-level CLI boundary turns typed errors into a one-line message)