typevault 0.2.0 → 0.3.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 (45) hide show
  1. package/README.md +10 -10
  2. package/package.json +1 -1
  3. package/src/access/env.ts +3 -3
  4. package/src/access/scope.ts +7 -2
  5. package/src/access/scoped.ts +22 -4
  6. package/src/access/sealed-access.ts +5 -0
  7. package/src/access/sealed.ts +25 -12
  8. package/src/access/types.ts +2 -0
  9. package/src/audit/log.ts +15 -4
  10. package/src/cli/commands/admin.ts +7 -2
  11. package/src/cli/commands/daemon.ts +10 -3
  12. package/src/cli/commands/entries.ts +31 -7
  13. package/src/cli/commands/grant.ts +12 -2
  14. package/src/cli/commands/members.ts +40 -14
  15. package/src/cli/commands/run.ts +133 -23
  16. package/src/cli/context.ts +12 -4
  17. package/src/cli/index.ts +6 -1
  18. package/src/cli/web-prompt.ts +28 -14
  19. package/src/core/admin.ts +23 -6
  20. package/src/core/doctor.ts +6 -7
  21. package/src/core/errors.ts +2 -2
  22. package/src/core/holder.ts +9 -6
  23. package/src/core/identity.ts +5 -3
  24. package/src/core/json-file.ts +20 -0
  25. package/src/core/layout.ts +5 -7
  26. package/src/core/naming.ts +13 -10
  27. package/src/core/payload.ts +2 -2
  28. package/src/core/revisions.ts +3 -2
  29. package/src/core/state.ts +16 -8
  30. package/src/core/txn.ts +4 -3
  31. package/src/core/worktrees.ts +18 -6
  32. package/src/daemon/agent-routes.ts +2 -0
  33. package/src/daemon/client.ts +9 -2
  34. package/src/daemon/daemon.ts +9 -2
  35. package/src/daemon/grants.ts +4 -3
  36. package/src/daemon/http.ts +8 -2
  37. package/src/daemon/live-access.ts +4 -0
  38. package/src/daemon/requests.ts +65 -36
  39. package/src/daemon/spawn.ts +42 -12
  40. package/src/import/dotenv.ts +2 -1
  41. package/src/prompt/index.ts +121 -64
  42. package/src/prompt/page.ts +8 -0
  43. package/src/prompt/types.ts +4 -1
  44. package/src/redact/index.ts +48 -12
  45. 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
@@ -105,11 +105,11 @@ More: [vaults, members and git history](docs/vaults-and-members.md).
105
105
  ### Running with secrets
106
106
 
107
107
  `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.
108
+ redacts the child's output. A variable whose value is a `typevault://` reference gets that field, so you pick the name.
109
109
 
110
110
  ```mermaid
111
111
  flowchart LR
112
- agent[Agent] -- "typevault run -- ./deploy.sh" --> load["Load entries and tv:// references"]
112
+ agent[Agent] -- "typevault run -- ./deploy.sh" --> load["Load entries and typevault:// references"]
113
113
  daemon[Daemon] -- "values, through the grant" --> load
114
114
  load -- "env vars, never PATH, NODE_OPTIONS, ..." --> child["./deploy.sh"]
115
115
  child -- "stdout, stderr" --> redact[Redact values]
@@ -117,8 +117,8 @@ flowchart LR
117
117
  ```
118
118
 
119
119
  ```sh
120
- DATABASE_URL=tv://postgres/prod#url typevault run -- ./migrate.sh
121
- typevault run --only tv://github/bot -- ./login.sh
120
+ DATABASE_URL=typevault://postgres/prod#url typevault run -- ./migrate.sh
121
+ typevault run --only typevault://github/bot -- ./login.sh
122
122
  ```
123
123
 
124
124
  More: [naming, field types and what `run` loads](docs/entries.md).
@@ -141,7 +141,7 @@ sequenceDiagram
141
141
  B->>B: encrypts to the tier
142
142
  B->>D: ciphertext only, safe through tunnels and proxies
143
143
  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
144
+ D-->>A: stored as typevault://resend, the value never comes back
145
145
  ```
146
146
 
147
147
  ```sh
@@ -167,7 +167,7 @@ const grant = await createAdmin({ ceiling: 'bot' }).grant({ tiers: ['member'], t
167
167
 
168
168
  // ...and the agent side reads through it (live via the daemon, or sealed in-process).
169
169
  const vault = await createClient({ grant })
170
- const { fields } = await vault.get(parseEntryName('tv://openai'), 'send the weekly digest')
170
+ const { fields } = await vault.get(parseEntryName('typevault://openai'), 'send the weekly digest')
171
171
 
172
172
  // Nothing is redacted for you: scrub anything that can reach output.
173
173
  const redactor = createRedactor(await vault.readValues())
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "typevault",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "description": "CLI-first secrets vault for agents",
5
5
  "homepage": "https://github.com/typeclaw/typevault#readme",
6
6
  "bugs": {
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>>,
@@ -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
  }
@@ -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 }) })
@@ -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
 
@@ -51,6 +51,8 @@ export function entryInputOf(input: SetInput, tier: string) {
51
51
  /** What a CLI command can do with secrets, whether the values come from a daemon, a sealed grant or a local key. */
52
52
  export interface Access {
53
53
  list(): Promise<readonly EntrySummary[]>
54
+ /** How many entry files `list` left out because they don't verify or can't be read. */
55
+ unreadableEntries(): Promise<number>
54
56
  get(name: EntryName, reason?: string): Promise<EntryValue>
55
57
  values(only: readonly string[], reason?: string): Promise<readonly EntryValue[]>
56
58
  set(input: SetInput): Promise<EntrySummary>
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,30 @@ 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. A daemon from before an upgrade lacks the route, and its listing is still good. */
28
+ async function noteUnreadableEntries(access: Access): Promise<void> {
29
+ let unreadable: number
30
+ try {
31
+ unreadable = await access.unreadableEntries()
32
+ } catch (error) {
33
+ if (error instanceof TypeVaultError && error.code === 'not_found') {
34
+ return note(
35
+ 'this daemon is too old to report entry files it skips: restart it (typevault daemon stop) to see them',
36
+ )
37
+ }
38
+ throw error
39
+ }
40
+ if (unreadable > 0)
41
+ note(`${unreadable} entry file(s) could not be trusted or read and are not listed: run typevault doctor`)
42
+ }
43
+
26
44
  export const ls = defineCommand({
27
45
  meta: { name: 'ls', description: 'List the entries your grant reaches' },
28
46
  args: { json: { type: 'boolean', description: 'Print JSON' } },
29
47
  async run({ args }) {
30
- const entries = await (await accessOf(process.env)).list()
48
+ const access = await accessOf(process.env)
49
+ const entries = await access.list()
50
+ await noteUnreadableEntries(access)
31
51
  if (args.json) return print(JSON.stringify(entries, null, 2))
32
52
  const rows = entries.map((e) => [
33
53
  e.name,
@@ -152,11 +172,9 @@ export const set = defineCommand({
152
172
  const given = parseFields(repeated(rawArgs, '--field'), { ...known, ...suggested })
153
173
  const tier = args.tier ?? existing?.tier ?? process.env['TYPEVAULT_TIER']
154
174
  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
- : {}
175
+ const stdin = args.stdin || args['stdin-json'] ? await readStdin() : undefined
176
+ if (args.stdin && stdin === '') throw new TypeVaultError('invalid', '--stdin did not contain a value')
177
+ const fromStdin = args['stdin-json'] ? parseFieldsJson(stdin ?? '') : args.stdin ? { [target]: stdin ?? '' } : {}
160
178
  const typed: Record<string, Field> = {}
161
179
  for (const [field, value] of Object.entries(fromStdin)) {
162
180
  if (typeof value !== 'string') {
@@ -195,13 +213,19 @@ export const set = defineCommand({
195
213
  : {}
196
214
  const fields = { ...given, ...typed, ...fromWeb }
197
215
  const merged = { ...(args.replace ? {} : previous), ...fields }
216
+ if (Object.keys(merged).length === 0) {
217
+ throw new TypeVaultError('invalid', 'set needs at least one field')
218
+ }
198
219
  if (args.env !== undefined && defaultFieldOf(merged) === undefined) {
199
220
  throw new TypeVaultError(
200
221
  'invalid',
201
222
  '--env names the default field, but this entry has several fields and no $default',
202
223
  )
203
224
  }
204
- const ifRev = args['if-rev'] === undefined ? undefined : z.coerce.number().int().parse(args['if-rev'])
225
+ const ifRev = args['if-rev'] === undefined ? undefined : Number(args['if-rev'])
226
+ if (ifRev !== undefined && !Number.isInteger(ifRev)) {
227
+ throw new TypeVaultError('invalid', `--if-rev must be a revision number, not "${args['if-rev']}"`)
228
+ }
205
229
  const tags = csv(args.tag)
206
230
  const stored = await access.set({
207
231
  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
  },