typevault 0.2.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/README.md +13 -12
  2. package/package.json +2 -2
  3. package/src/access/env.ts +3 -3
  4. package/src/access/schemas.ts +3 -1
  5. package/src/access/scope.ts +7 -2
  6. package/src/access/scoped.ts +47 -10
  7. package/src/access/sealed-access.ts +12 -1
  8. package/src/access/sealed.ts +25 -12
  9. package/src/access/types.ts +7 -0
  10. package/src/audit/log.ts +15 -4
  11. package/src/cli/commands/admin.ts +7 -2
  12. package/src/cli/commands/daemon.ts +10 -3
  13. package/src/cli/commands/entries.ts +21 -7
  14. package/src/cli/commands/grant.ts +12 -2
  15. package/src/cli/commands/members.ts +40 -14
  16. package/src/cli/commands/run.ts +141 -44
  17. package/src/cli/context.ts +14 -4
  18. package/src/cli/index.ts +6 -1
  19. package/src/cli/output.ts +5 -1
  20. package/src/cli/web-prompt.ts +28 -14
  21. package/src/core/admin.ts +23 -6
  22. package/src/core/doctor.ts +6 -7
  23. package/src/core/errors.ts +2 -2
  24. package/src/core/holder.ts +25 -9
  25. package/src/core/identity.ts +5 -3
  26. package/src/core/json-file.ts +20 -0
  27. package/src/core/layout.ts +51 -8
  28. package/src/core/naming.ts +40 -32
  29. package/src/core/payload.ts +7 -3
  30. package/src/core/revisions.ts +3 -2
  31. package/src/core/state.ts +16 -8
  32. package/src/core/txn.ts +4 -3
  33. package/src/core/vault.ts +45 -5
  34. package/src/core/version.ts +9 -0
  35. package/src/core/worktrees.ts +18 -6
  36. package/src/daemon/agent-routes.ts +80 -3
  37. package/src/daemon/client.ts +20 -2
  38. package/src/daemon/daemon.ts +9 -2
  39. package/src/daemon/grants.ts +4 -3
  40. package/src/daemon/http.ts +8 -2
  41. package/src/daemon/live-access.ts +19 -0
  42. package/src/daemon/protocol.ts +7 -0
  43. package/src/daemon/requests.ts +65 -36
  44. package/src/daemon/spawn.ts +68 -14
  45. package/src/import/1password-live.ts +55 -16
  46. package/src/import/1password.ts +6 -4
  47. package/src/import/bitwarden.ts +3 -8
  48. package/src/import/dotenv.ts +2 -1
  49. package/src/import/keepass.ts +4 -5
  50. package/src/import/lastpass.ts +0 -1
  51. package/src/import/shared.ts +57 -5
  52. package/src/import/types.ts +1 -1
  53. package/src/prompt/index.ts +121 -64
  54. package/src/prompt/page.ts +8 -0
  55. package/src/prompt/types.ts +4 -1
  56. package/src/redact/index.ts +48 -12
  57. package/src/redact/scrub-file.ts +15 -7
package/README.md CHANGED
@@ -40,8 +40,8 @@ Requires Bun ≥ 1.3.
40
40
  typevault init # creates .typevault/ here; the first time, also your password and Secret Key
41
41
  typevault unlock # once per session (8h by default); your agents read through it
42
42
 
43
- printf '%s' "$OPENAI_KEY" | typevault set tv://openai --preset api_key --stdin
44
- typevault set tv://anthropic --preset api_key # from a terminal: type it in a one-time local page
43
+ printf '%s' "$OPENAI_KEY" | typevault set typevault://openai --preset api_key --stdin
44
+ typevault set typevault://anthropic --preset api_key # from a terminal: type it in a one-time local page
45
45
 
46
46
  export TYPEVAULT_GRANT=$(typevault grant --tier default --label session:abc)
47
47
  typevault run -- ./deploy.sh # OPENAI and ANTHROPIC arrive as env vars; output is redacted
@@ -62,11 +62,11 @@ sequenceDiagram
62
62
  participant I as Issuer
63
63
  participant D as Daemon
64
64
  participant A as Agent
65
- I->>D: grant --tier member --only 'tv://github/*' --ttl 30m --label ci:deploy
65
+ I->>D: grant --tier member --only 'typevault://github/*' --ttl 30m --label ci:deploy
66
66
  Note over I,D: through its admin socket, never above its ceiling
67
67
  D-->>I: live grant (tvl1.…)
68
68
  I->>A: TYPEVAULT_GRANT
69
- A->>D: read tv://github/bot, with a reason
69
+ A->>D: read typevault://github/bot, with a reason
70
70
  D->>D: check tiers, names and TTL, then log the read
71
71
  D-->>A: value, into run's child only
72
72
  I->>D: grant revoke --label ci:deploy
@@ -100,16 +100,17 @@ typevault member add bob tvp1:... --tier default # rotates every tier bob reache
100
100
  typevault join --machine --name ci # CI or an agent host: no password, its own key
101
101
  ```
102
102
 
103
- More: [vaults, members and git history](docs/vaults-and-members.md).
103
+ More: [vaults, members and git history](docs/vaults-and-members.md), and [working with a teammate](docs/vaults-and-members.md#working-with-a-teammate):
104
+ what each person does by hand.
104
105
 
105
106
  ### Running with secrets
106
107
 
107
108
  `run` loads what the grant reaches as env vars, never sets loader variables like `PATH` or `NODE_OPTIONS`, and
108
- redacts the child's output. A variable whose value is a `tv://` reference gets that field, so you pick the name.
109
+ redacts the child's output. A variable whose value is a `typevault://` reference gets that field, so you pick the name.
109
110
 
110
111
  ```mermaid
111
112
  flowchart LR
112
- agent[Agent] -- "typevault run -- ./deploy.sh" --> load["Load entries and tv:// references"]
113
+ agent[Agent] -- "typevault run -- ./deploy.sh" --> load["Load entries and typevault:// references"]
113
114
  daemon[Daemon] -- "values, through the grant" --> load
114
115
  load -- "env vars, never PATH, NODE_OPTIONS, ..." --> child["./deploy.sh"]
115
116
  child -- "stdout, stderr" --> redact[Redact values]
@@ -117,8 +118,8 @@ flowchart LR
117
118
  ```
118
119
 
119
120
  ```sh
120
- DATABASE_URL=tv://postgres/prod#url typevault run -- ./migrate.sh
121
- typevault run --only tv://github/bot -- ./login.sh
121
+ DATABASE_URL=typevault://postgres/prod#url typevault run -- ./migrate.sh
122
+ typevault run --only typevault://github/bot -- ./login.sh
122
123
  ```
123
124
 
124
125
  More: [naming, field types and what `run` loads](docs/entries.md).
@@ -141,7 +142,7 @@ sequenceDiagram
141
142
  B->>B: encrypts to the tier
142
143
  B->>D: ciphertext only, safe through tunnels and proxies
143
144
  D->>D: decrypts, checks it is the requested entry, re-encrypts, signs, stores
144
- D-->>A: stored as tv://resend, the value never comes back
145
+ D-->>A: stored as typevault://resend, the value never comes back
145
146
  ```
146
147
 
147
148
  ```sh
@@ -167,7 +168,7 @@ const grant = await createAdmin({ ceiling: 'bot' }).grant({ tiers: ['member'], t
167
168
 
168
169
  // ...and the agent side reads through it (live via the daemon, or sealed in-process).
169
170
  const vault = await createClient({ grant })
170
- const { fields } = await vault.get(parseEntryName('tv://openai'), 'send the weekly digest')
171
+ const { fields } = await vault.get(parseEntryName('typevault://openai'), 'send the weekly digest')
171
172
 
172
173
  // Nothing is redacted for you: scrub anything that can reach output.
173
174
  const redactor = createRedactor(await vault.readValues())
@@ -190,7 +191,7 @@ use grants, `run` and references.
190
191
  git clone https://github.com/typeclaw/typevault
191
192
  cd typevault
192
193
  bun install
193
- bun test
194
+ bun run test
194
195
  ```
195
196
 
196
197
  Pre-commit checks (all must pass):
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "typevault",
3
- "version": "0.2.0",
3
+ "version": "0.4.0",
4
4
  "description": "CLI-first secrets vault for agents",
5
5
  "homepage": "https://github.com/typeclaw/typevault#readme",
6
6
  "bugs": {
@@ -31,7 +31,7 @@
31
31
  "format": "oxfmt --write .",
32
32
  "format:check": "oxfmt --check .",
33
33
  "check": "bun run typecheck && bun run lint && bun run format:check",
34
- "test": "bun test"
34
+ "test": "bun test --parallel"
35
35
  },
36
36
  "dependencies": {
37
37
  "@1password/sdk": "^0.5.0",
package/src/access/env.ts CHANGED
@@ -59,9 +59,9 @@ export function envFor(values: readonly EntryValue[], now: Date, policy: EnvPoli
59
59
  export type ResolvedRefs = { readonly env: Readonly<Record<string, string>>; readonly values: readonly EntryValue[] }
60
60
 
61
61
  /**
62
- * Replaces each variable whose whole value is a `tv://` reference (`FOO=tv://github/bot#password`) with the
63
- * referenced field, the default one when none is named. The caller picked the variable, but a lower tier can
64
- * still write the value, so loader variables are refused here as they are for entries.
62
+ * Replaces each variable whose whole value is a `typevault://` reference (`FOO=typevault://github/bot#password`)
63
+ * with the referenced field, the default one when none is named. The caller picked the variable, but a lower tier
64
+ * can still write the value, so loader variables are refused here as they are for entries.
65
65
  */
66
66
  export async function resolveEnvRefs(
67
67
  env: Readonly<Record<string, string | undefined>>,
@@ -21,6 +21,7 @@ export const EntryValueSchema = z.object({
21
21
  fields: FieldsSchema,
22
22
  env: z.string().optional(),
23
23
  origin: z.string().optional(),
24
+ source: z.string().optional(),
24
25
  trustedWriter: z.boolean().optional(),
25
26
  })
26
27
 
@@ -29,11 +30,12 @@ export function toSummaryValue(parsed: z.infer<typeof EntrySummarySchema>): Entr
29
30
  }
30
31
 
31
32
  export function toEntryValue(parsed: z.infer<typeof EntryValueSchema>): EntryValue {
32
- const { env, origin, trustedWriter, ...rest } = parsed
33
+ const { env, origin, source, trustedWriter, ...rest } = parsed
33
34
  return {
34
35
  ...rest,
35
36
  ...(env === undefined ? {} : { env }),
36
37
  ...(origin === undefined ? {} : { origin }),
38
+ ...(source === undefined ? {} : { source }),
37
39
  ...(trustedWriter === undefined ? {} : { trustedWriter }),
38
40
  }
39
41
  }
@@ -31,8 +31,13 @@ export function parseTtl(text: string): number {
31
31
  case 's':
32
32
  case 'm':
33
33
  case 'h':
34
- case 'd':
35
- return amount * UNITS[unit]
34
+ case 'd': {
35
+ const ms = amount * UNITS[unit]
36
+ if (ms <= 0 || ms > 3650 * UNITS.d) {
37
+ throw new TypeVaultError('invalid', 'TTL must be greater than zero and at most 3650 days')
38
+ }
39
+ return ms
40
+ }
36
41
  default:
37
42
  throw new TypeVaultError('invalid', `invalid TTL unit "${unit}"`)
38
43
  }
@@ -22,6 +22,8 @@ export type ScopedIdentity = {
22
22
  readonly mode: AuditMode
23
23
  readonly grant?: string
24
24
  readonly label?: string
25
+ /** The owner's own session, never a grant delegated from it. */
26
+ readonly owner?: boolean
25
27
  /** Tiers held directly; see `Access.ownTiers`. */
26
28
  readonly ownTiers?: readonly string[]
27
29
  /** Tier used by `set` when the caller names none. */
@@ -71,6 +73,10 @@ export class ScopedVault implements Access {
71
73
  return [...byName.values()].flatMap((copies) => resolveName(this.#vault.state.tiers, copies) ?? [])
72
74
  }
73
75
 
76
+ async unreadableEntries(): Promise<number> {
77
+ return (await this.#vault.scan()).problems.length
78
+ }
79
+
74
80
  async #find(name: EntryName): Promise<StoredEntry> {
75
81
  const entry = await this.#vault.find(name)
76
82
  if (entry === undefined || !this.#allows(entry)) throw new TypeVaultError('not_found', `no entry named ${name}`)
@@ -78,9 +84,10 @@ export class ScopedVault implements Access {
78
84
  }
79
85
 
80
86
  async #signerFor(tier: string): Promise<ReturnType<typeof signerOf>> {
81
- // Direct mode is the key holder acting itself, so the owner signs as the owner. The daemon writes on behalf
82
- // of grants and signs with the tier's own key, so a grant's writes never look owner-authored.
83
- const owner = this.#identity.mode === 'direct' ? this.#vault.keyring.owner : undefined
87
+ // The owner signs its own writes in direct mode or its own session. Delegated grants use tier keys,
88
+ // so a grant's writes never look owner-authored.
89
+ const owner =
90
+ this.#identity.mode === 'direct' || this.#identity.owner === true ? this.#vault.keyring.owner : undefined
84
91
  const key = owner ?? (await this.#vault.keyring.unlock(tier)) ?? this.#vault.keyring.owner
85
92
  if (key === undefined) throw new TypeVaultError('denied', `no key here can write tier "${tier}"`)
86
93
  return signerOf(key)
@@ -126,7 +133,18 @@ export class ScopedVault implements Access {
126
133
  ...(env === undefined ? {} : { env }),
127
134
  ...(origin === undefined ? {} : { origin }),
128
135
  }
129
- const refreshed = await this.#vault.put(input, await this.#signerFor(entry.envelope.tier))
136
+ // A read must not promote the original writer's metadata to the reader's authority. Reuse its owner/tier
137
+ // key when held; certificates and unavailable signing keys narrow to the entry's own tier.
138
+ const { signer, tier } = entry.envelope
139
+ const original =
140
+ signer.kind === 'owner'
141
+ ? this.#vault.keyring.owner
142
+ : signer.kind === 'tier'
143
+ ? await this.#vault.keyring.unlock(signer.tier)
144
+ : undefined
145
+ const key = original ?? (await this.#vault.keyring.unlock(tier))
146
+ if (key === undefined) throw new TypeVaultError('denied', `no key here can refresh tier "${tier}"`)
147
+ const refreshed = await this.#vault.put(input, signerOf(key))
130
148
  await this.#audit({ action: 'refresh', entries: [name] })
131
149
  return refreshed
132
150
  }
@@ -182,13 +200,32 @@ export class ScopedVault implements Access {
182
200
  throw new TypeVaultError('invalid', `choose a tier with --tier (one of: ${writable.join(', ')})${viaEnv}`)
183
201
  }
184
202
 
185
- async #write(input: SetInput, tier: string): Promise<EntrySummary> {
186
- if (
187
- !allowsTier(this.#chain, this.#vault.state, tier) ||
188
- !allowsEntry(this.#chain, this.#vault.state, tier, input.name)
189
- ) {
190
- throw new TypeVaultError('denied', `this grant cannot write ${input.name} in tier "${tier}"`)
203
+ /**
204
+ * Writes every input into `tier` as one transaction (an import): all of them land, or none do. As in `set`, the
205
+ * scope is checked under the write's lock against freshly read state.
206
+ */
207
+ importEntries(inputs: readonly SetInput[], tier: string): Promise<readonly EntrySummary[]> {
208
+ return withLock(this.#vault.layout.lockFile, 'exclusive', async () => {
209
+ this.#vault.refresh()
210
+ for (const input of inputs) this.#checkWritable(input.name, tier)
211
+ const stored = await this.#vault.putMany(
212
+ inputs.map((input) => entryInputOf(input, tier)),
213
+ (target) => this.#signerFor(target),
214
+ (found) => this.#allows(found),
215
+ )
216
+ await this.#audit({ action: 'import', entries: stored.map((entry) => entry.payload.name), tiers: [tier] })
217
+ return stored.map((entry) => toSummary(valueOf(entry)))
218
+ })
219
+ }
220
+
221
+ #checkWritable(name: EntryName, tier: string): void {
222
+ if (!allowsTier(this.#chain, this.#vault.state, tier) || !allowsEntry(this.#chain, this.#vault.state, tier, name)) {
223
+ throw new TypeVaultError('denied', `this grant cannot write ${name} in tier "${tier}"`)
191
224
  }
225
+ }
226
+
227
+ async #write(input: SetInput, tier: string): Promise<EntrySummary> {
228
+ this.#checkWritable(input.name, tier)
192
229
  const existing = await this.#vault.find(input.name)
193
230
  if (existing !== undefined && !this.#allows(existing)) {
194
231
  throw new TypeVaultError('denied', `the name ${input.name} is not available to this grant`)
@@ -58,6 +58,11 @@ export class SealedAccess implements Access {
58
58
  return this.#live().entries.map(toSummary)
59
59
  }
60
60
 
61
+ /** Its entries travel inside the sealed bundle, so there are no files here to fail. */
62
+ async unreadableEntries(): Promise<number> {
63
+ return 0
64
+ }
65
+
61
66
  async get(name: EntryName, reason?: string): Promise<EntryValue> {
62
67
  const entry = this.#entry(name)
63
68
  await this.#audit({ action: 'read', entries: [name], ...(reason === undefined ? {} : { reason }) })
@@ -128,7 +133,13 @@ export class SealedAccess implements Access {
128
133
 
129
134
  async move(from: EntryName, to: EntryName): Promise<void> {
130
135
  const entry = this.#entry(from)
131
- await this.set({ name: to, fields: entry.fields, tier: entry.tier, tags: entry.tags })
136
+ await this.set({
137
+ name: to,
138
+ fields: entry.fields,
139
+ tier: entry.tier,
140
+ tags: entry.tags,
141
+ ...(entry.source === undefined ? {} : { source: entry.source }),
142
+ })
132
143
  await this.remove(from)
133
144
  }
134
145
 
@@ -95,19 +95,32 @@ async function memberTierKey(vault: Vault, tiers: readonly string[]): Promise<Se
95
95
 
96
96
  /** Opens `tvg1:...` or `@/path/to/file` holding one. */
97
97
  export async function readSealedGrant(raw: string): Promise<SealedBundle> {
98
- const text = (raw.startsWith('@') ? readFileSync(raw.slice(1), 'utf8') : raw).trim()
99
- const [identity, ciphertext] = text.slice(PREFIX.length).split('.')
100
- if (!text.startsWith(PREFIX) || identity === undefined || ciphertext === undefined) {
101
- throw new TypeVaultError('invalid', 'not a sealed typevault grant')
98
+ let text = raw
99
+ if (raw.startsWith('@')) {
100
+ try {
101
+ text = readFileSync(raw.slice(1), 'utf8')
102
+ } catch (error) {
103
+ if (!(error instanceof Error)) throw error
104
+ throw new TypeVaultError('invalid', `cannot read the sealed grant file "${raw.slice(1)}"`)
105
+ }
102
106
  }
103
- const plaintext = await unseal([fromUtf8(fromBase64Url(identity))], fromBase64Url(ciphertext))
104
- const parsed = BundleSchema.safeParse(JSON.parse(fromUtf8(plaintext)))
105
- if (!parsed.success) throw new TypeVaultError('invalid', 'malformed sealed grant')
106
- const { tiers, only, entries, ...rest } = parsed.data
107
- return {
108
- ...rest,
109
- scope: { tiers, only },
110
- entries: entries.map(toEntryValue),
107
+ try {
108
+ const token = text.trim()
109
+ const [identity, ciphertext, extra] = token.slice(PREFIX.length).split('.')
110
+ if (!token.startsWith(PREFIX) || !identity || !ciphertext || extra !== undefined) {
111
+ throw new TypeVaultError('invalid', 'not a sealed typevault grant')
112
+ }
113
+ const plaintext = await unseal([fromUtf8(fromBase64Url(identity))], fromBase64Url(ciphertext))
114
+ const parsed = BundleSchema.parse(JSON.parse(fromUtf8(plaintext)))
115
+ const { tiers, only, entries, ...rest } = parsed
116
+ return {
117
+ ...rest,
118
+ scope: { tiers, only },
119
+ entries: entries.map(toEntryValue),
120
+ }
121
+ } catch (error) {
122
+ if (!(error instanceof Error)) throw error
123
+ throw new TypeVaultError('invalid', 'TYPEVAULT_GRANT is not a sealed typevault grant')
111
124
  }
112
125
  }
113
126
 
@@ -19,6 +19,7 @@ export type EntryValue = EntrySummary & {
19
19
  readonly fields: Readonly<Record<string, Field>>
20
20
  readonly env?: string
21
21
  readonly origin?: string
22
+ readonly source?: string
22
23
  /** Written by the owner or by a key that reaches all of the reader's own tiers: its `--env` override counts. */
23
24
  readonly trustedWriter?: boolean
24
25
  }
@@ -29,6 +30,8 @@ export type SetInput = {
29
30
  readonly tier?: string | undefined
30
31
  readonly env?: string | undefined
31
32
  readonly origin?: string | undefined
33
+ /** Kept by a blind writer (a sealed grant) that moves an imported entry. */
34
+ readonly source?: string | undefined
32
35
  readonly tags?: readonly string[] | undefined
33
36
  readonly ifRev?: number | undefined
34
37
  }
@@ -44,6 +47,7 @@ export function entryInputOf(input: SetInput, tier: string) {
44
47
  tier,
45
48
  ...(input.env === undefined ? {} : { env: input.env }),
46
49
  ...(input.origin === undefined ? {} : { origin: input.origin }),
50
+ ...(input.source === undefined ? {} : { source: input.source }),
47
51
  ...(input.tags === undefined ? {} : { tags: input.tags }),
48
52
  }
49
53
  }
@@ -51,6 +55,8 @@ export function entryInputOf(input: SetInput, tier: string) {
51
55
  /** What a CLI command can do with secrets, whether the values come from a daemon, a sealed grant or a local key. */
52
56
  export interface Access {
53
57
  list(): Promise<readonly EntrySummary[]>
58
+ /** How many entry files `list` left out because they don't verify or can't be read. */
59
+ unreadableEntries(): Promise<number>
54
60
  get(name: EntryName, reason?: string): Promise<EntryValue>
55
61
  values(only: readonly string[], reason?: string): Promise<readonly EntryValue[]>
56
62
  set(input: SetInput): Promise<EntrySummary>
@@ -76,6 +82,7 @@ export function toValue(tier: string, id: string, rev: number, payload: EntryPay
76
82
  fields: payload.fields,
77
83
  ...(payload.env === undefined ? {} : { env: payload.env }),
78
84
  ...(payload.origin === undefined ? {} : { origin: payload.origin }),
85
+ ...(payload.source === undefined ? {} : { source: payload.source }),
79
86
  }
80
87
  }
81
88
 
package/src/audit/log.ts CHANGED
@@ -5,7 +5,9 @@ import { z } from 'zod'
5
5
 
6
6
  import { sha256Hex } from '../core/crypto'
7
7
  import { canonicalJson, type Json, utf8 } from '../core/encoding'
8
+ import { TypeVaultError } from '../core/errors'
8
9
  import { assertNoSymlinks, ensureDir } from '../core/fsx'
10
+ import { parseJsonText } from '../core/json-file'
9
11
  import type { Layout } from '../core/layout'
10
12
  import { withLock } from '../core/lock'
11
13
 
@@ -57,7 +59,7 @@ function readLast(layout: Layout): AuditRecord | undefined {
57
59
  .split('\n')
58
60
  .filter((line) => line !== '')
59
61
  const last = lines.at(-1)
60
- if (lines.length > 1 && last !== undefined) return RecordSchema.parse(JSON.parse(last))
62
+ if (lines.length > 1 && last !== undefined) return parseJsonText(layout.auditLog, last, RecordSchema)
61
63
  } finally {
62
64
  closeSync(fd)
63
65
  }
@@ -70,7 +72,7 @@ export function readAudit(layout: Layout): readonly AuditRecord[] {
70
72
  return readFileSync(layout.auditLog, 'utf8')
71
73
  .split('\n')
72
74
  .filter((line) => line !== '')
73
- .map((line) => RecordSchema.parse(JSON.parse(line)))
75
+ .map((line) => parseJsonText(layout.auditLog, line, RecordSchema))
74
76
  }
75
77
 
76
78
  function writeAnchor(layout: Layout, last: AuditRecord): void {
@@ -105,8 +107,17 @@ export type AuditVerdict =
105
107
  | { readonly ok: true; readonly records: number }
106
108
  | { readonly ok: false; readonly reason: string }
107
109
 
108
- /** Recomputes the chain and checks every anchor against it. */
110
+ /** Recomputes the chain and checks every anchor against it. A log too damaged to read fails the check. */
109
111
  export function verifyAudit(layout: Layout): AuditVerdict {
112
+ try {
113
+ return verifyChain(layout)
114
+ } catch (error) {
115
+ if (error instanceof TypeVaultError && error.code === 'tampered') return { ok: false, reason: error.message }
116
+ throw error
117
+ }
118
+ }
119
+
120
+ function verifyChain(layout: Layout): AuditVerdict {
110
121
  const records = readAudit(layout)
111
122
  let prev = GENESIS
112
123
  const heads = new Map<number, string>()
@@ -124,7 +135,7 @@ export function verifyAudit(layout: Layout): AuditVerdict {
124
135
  ? readFileSync(file, 'utf8')
125
136
  .split('\n')
126
137
  .filter((line) => line !== '')
127
- .map((line) => AnchorSchema.parse(JSON.parse(line)))
138
+ .map((line) => parseJsonText(file, line, AnchorSchema))
128
139
  : [],
129
140
  )
130
141
  const broken = anchors.find((anchor) => heads.get(anchor.seq) !== anchor.hash)
@@ -12,8 +12,9 @@ import { founderOf, initGlobalVault, initLocalVault } from '../../core/init'
12
12
  import { globalLayout, type Layout, LOCAL_VAULT_DIR, localLayout } from '../../core/layout'
13
13
  import { parseEntryName } from '../../core/naming'
14
14
  import { Vault } from '../../core/vault'
15
+ import { GrantStore } from '../../daemon/grants'
15
16
  import { stopDaemon } from '../../daemon/spawn'
16
- import { openAdmin, openDirect, openPublic, wantsGlobal } from '../context'
17
+ import { layoutFrom, openAdmin, openDirect, openPublic, wantsGlobal } from '../context'
17
18
  import { csv, note, print, table } from '../output'
18
19
  import { ensureIdentity, identityArgs } from './members'
19
20
 
@@ -114,7 +115,10 @@ export const key = defineCommand({
114
115
  meta: { name: 'key', description: 'Rotate tier keys (owner)' },
115
116
  subCommands: {
116
117
  rotate: defineCommand({
117
- meta: { name: 'rotate', description: 'New key generation; flags every secret the old key reached' },
118
+ meta: {
119
+ name: 'rotate',
120
+ description: 'Rotate every reachable tier key; flag their secrets for rotation at source',
121
+ },
118
122
  args: named,
119
123
  async run({ args }) {
120
124
  printRotation(args.name, await (await openAdmin(process.env)).rotate(args.name))
@@ -186,6 +190,7 @@ export const doctor = defineCommand({
186
190
  },
187
191
  },
188
192
  async run({ args }) {
193
+ new GrantStore(layoutFrom(process.env).grantsFile)
189
194
  const vault = await openDirect(process.env)
190
195
  if (args.fix === true) {
191
196
  const adoption = await adoptCertWrites(vault, { expired: csv(args['adopt-expired'] ?? '').map(parseExpiredPin) })
@@ -4,6 +4,7 @@ import { z } from 'zod'
4
4
  import { machineKeys } from '../../access/keys'
5
5
  import { parseTtl } from '../../access/scope'
6
6
  import { decodeSecretKey } from '../../core/crypto'
7
+ import { TypeVaultError } from '../../core/errors'
7
8
  import { localLayout } from '../../core/layout'
8
9
  import { isDaemonAlive } from '../../daemon/client'
9
10
  import { startDaemon } from '../../daemon/daemon'
@@ -11,8 +12,14 @@ import { ensureDaemon, stopDaemon } from '../../daemon/spawn'
11
12
  import { adminCall, DEFAULT_SESSION_MS, layoutFrom } from '../context'
12
13
  import { note, print, readStdin } from '../output'
13
14
 
14
- const port = (value: string | undefined): number | undefined =>
15
- value === undefined || value === '' ? undefined : z.coerce.number().int().parse(value)
15
+ function promptPortOf(value: string | undefined): number | undefined {
16
+ if (value === undefined || value === '') return undefined
17
+ const port = Number(value)
18
+ if (!Number.isInteger(port) || port < 0 || port > 65_535) {
19
+ throw new TypeVaultError('invalid', `TYPEVAULT_PROMPT_PORT must be a port number, not "${value}"`)
20
+ }
21
+ return port
22
+ }
16
23
 
17
24
  export const daemon = defineCommand({
18
25
  meta: { name: 'daemon', description: 'The background issuer (usually started automatically)' },
@@ -33,7 +40,7 @@ export const daemon = defineCommand({
33
40
  },
34
41
  async run({ args }) {
35
42
  const env = process.env
36
- const promptPort = port(env['TYPEVAULT_PROMPT_PORT'])
43
+ const promptPort = promptPortOf(env['TYPEVAULT_PROMPT_PORT'])
37
44
  const publicUrl = env['TYPEVAULT_PUBLIC_URL']
38
45
  const fromStdin = args['key-stdin'] === true
39
46
  const ttlMs = args.ttl === undefined ? undefined : parseTtl(args.ttl)
@@ -1,6 +1,7 @@
1
1
  import { defineCommand } from 'citty'
2
2
  import { z } from 'zod'
3
3
 
4
+ import type { Access } from '../../access/types'
4
5
  import { TypeVaultError } from '../../core/errors'
5
6
  import {
6
7
  ENTRY_NAME_SYNTAX,
@@ -23,11 +24,20 @@ import { accessOf, resolveAccess } from '../context'
23
24
  import { csv, note, print, readStdin, repeated, table } from '../output'
24
25
  import { openBrowser, promptFields } from '../web-prompt'
25
26
 
27
+ /** Runs after the listing it annotates. */
28
+ async function noteUnreadableEntries(access: Access): Promise<void> {
29
+ const unreadable = await access.unreadableEntries()
30
+ if (unreadable > 0)
31
+ note(`${unreadable} entry file(s) could not be trusted or read and are not listed: run typevault doctor`)
32
+ }
33
+
26
34
  export const ls = defineCommand({
27
35
  meta: { name: 'ls', description: 'List the entries your grant reaches' },
28
36
  args: { json: { type: 'boolean', description: 'Print JSON' } },
29
37
  async run({ args }) {
30
- const entries = await (await accessOf(process.env)).list()
38
+ const access = await accessOf(process.env)
39
+ const entries = await access.list()
40
+ await noteUnreadableEntries(access)
31
41
  if (args.json) return print(JSON.stringify(entries, null, 2))
32
42
  const rows = entries.map((e) => [
33
43
  e.name,
@@ -152,11 +162,9 @@ export const set = defineCommand({
152
162
  const given = parseFields(repeated(rawArgs, '--field'), { ...known, ...suggested })
153
163
  const tier = args.tier ?? existing?.tier ?? process.env['TYPEVAULT_TIER']
154
164
  const target = preset?.input ?? defaultFieldOf(previous) ?? '$default'
155
- const fromStdin = args['stdin-json']
156
- ? parseFieldsJson(await readStdin())
157
- : args.stdin
158
- ? { [target]: await readStdin() }
159
- : {}
165
+ const stdin = args.stdin || args['stdin-json'] ? await readStdin() : undefined
166
+ if (args.stdin && stdin === '') throw new TypeVaultError('invalid', '--stdin did not contain a value')
167
+ const fromStdin = args['stdin-json'] ? parseFieldsJson(stdin ?? '') : args.stdin ? { [target]: stdin ?? '' } : {}
160
168
  const typed: Record<string, Field> = {}
161
169
  for (const [field, value] of Object.entries(fromStdin)) {
162
170
  if (typeof value !== 'string') {
@@ -195,13 +203,19 @@ export const set = defineCommand({
195
203
  : {}
196
204
  const fields = { ...given, ...typed, ...fromWeb }
197
205
  const merged = { ...(args.replace ? {} : previous), ...fields }
206
+ if (Object.keys(merged).length === 0) {
207
+ throw new TypeVaultError('invalid', 'set needs at least one field')
208
+ }
198
209
  if (args.env !== undefined && defaultFieldOf(merged) === undefined) {
199
210
  throw new TypeVaultError(
200
211
  'invalid',
201
212
  '--env names the default field, but this entry has several fields and no $default',
202
213
  )
203
214
  }
204
- const ifRev = args['if-rev'] === undefined ? undefined : z.coerce.number().int().parse(args['if-rev'])
215
+ const ifRev = args['if-rev'] === undefined ? undefined : Number(args['if-rev'])
216
+ if (ifRev !== undefined && !Number.isInteger(ifRev)) {
217
+ throw new TypeVaultError('invalid', `--if-rev must be a revision number, not "${args['if-rev']}"`)
218
+ }
205
219
  const tags = csv(args.tag)
206
220
  const stored = await access.set({
207
221
  name,
@@ -1,4 +1,4 @@
1
- import { watch } from 'node:fs'
1
+ import { existsSync, watch } from 'node:fs'
2
2
 
3
3
  import { defineCommand } from 'citty'
4
4
  import { z } from 'zod'
@@ -85,6 +85,16 @@ export const audit = defineCommand({
85
85
  shown = records.length
86
86
  }
87
87
  show()
88
- if (args.follow) await new Promise<never>(() => watch(layout.auditLog, show))
88
+ if (args.follow) {
89
+ if (!existsSync(layout.auditLog)) {
90
+ throw new TypeVaultError(
91
+ 'not_found',
92
+ `no audit log at ${layout.auditLog}; retry after the first audited action`,
93
+ )
94
+ }
95
+ await new Promise<never>((_resolve, reject) => {
96
+ watch(layout.auditLog, show).on('error', reject)
97
+ })
98
+ }
89
99
  },
90
100
  })
@@ -19,9 +19,11 @@ import {
19
19
  sealMemberKey,
20
20
  writeIdentity,
21
21
  } from '../../core/identity'
22
- import { vaultIdOf } from '../../core/layout'
22
+ import { type Layout, localLayout, vaultIdOf } from '../../core/layout'
23
+ import { readOwner } from '../../core/state'
23
24
  import { Vault } from '../../core/vault'
24
- import { stopDaemon } from '../../daemon/spawn'
25
+ import { worktreeVaults } from '../../core/worktrees'
26
+ import { endLiveGrants, stopDaemon } from '../../daemon/spawn'
25
27
  import { export1Password, identityTitle } from '../../export/1password'
26
28
  import { ONEPASSWORD_VIAS } from '../../import/1password-live'
27
29
  import {
@@ -239,22 +241,46 @@ export const unlock = defineCommand({
239
241
  })
240
242
 
241
243
  export const lock = defineCommand({
242
- meta: { name: 'lock', description: 'Lock this vault now: stops the daemon and ends every session' },
244
+ meta: { name: 'lock', description: 'Lock this vault now: stops the daemon and ends every session and live grant' },
243
245
  async run() {
244
246
  const layout = findLayout(process.env)
245
247
  if (layout === undefined) throw new TypeVaultError('not_found', 'no vault here')
246
- // A session unlocked in another worktree would only be shared here again on the next read.
247
- const worktrees = await worktreeSessions(layout, process.env)
248
+ const env = process.env
249
+ // An owner that can't be read doesn't prove another vault, so lock still reaches it.
250
+ const ownerOf = (target: Layout): string | undefined => {
251
+ try {
252
+ return readOwner(target).signPublic
253
+ } catch (error) {
254
+ if (error instanceof TypeVaultError) return undefined
255
+ throw error
256
+ }
257
+ }
258
+ const own = ownerOf(layout)
259
+ const vaults = layout.scope === 'local' ? await worktreeVaults(layout.vault) : []
260
+ // A grant issued in a worktree outlives its daemon, so this vault's worktrees all count, running or not.
261
+ const sameVault = vaults
262
+ .map((vault) => localLayout(vault, env))
263
+ .filter((worktree) => {
264
+ const other = ownerOf(worktree)
265
+ return own === undefined || other === undefined || other === own
266
+ })
267
+ // A session unlocked in any other worktree would only be shared here again on the next read, so it stops too, but
268
+ // the grants of a different vault are its own.
269
+ const sessions = await worktreeSessions(layout, env)
270
+ const otherSessions = sessions.filter((session) => !sameVault.some((worktree) => worktree.vault === session.vault))
271
+ const stop = (target: Layout): Promise<boolean> =>
272
+ stopDaemon(target).then(
273
+ () => true,
274
+ (error: unknown) => {
275
+ if (error instanceof TypeVaultError && error.code === 'not_found') return false
276
+ throw error
277
+ },
278
+ )
248
279
  let locked = false
249
- for (const target of [...worktrees, layout]) {
250
- locked =
251
- (await stopDaemon(target).then(
252
- () => true,
253
- (error: unknown) => {
254
- if (error instanceof TypeVaultError && error.code === 'not_found') return false
255
- throw error
256
- },
257
- )) || locked
280
+ for (const target of otherSessions) locked = (await stop(target)) || locked
281
+ for (const target of [...sameVault, layout]) {
282
+ locked = (await stop(target)) || locked
283
+ await endLiveGrants(target, env)
258
284
  }
259
285
  print(locked ? 'locked' : 'already locked')
260
286
  },