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
@@ -1,3 +1,5 @@
1
+ import { pipeline } from 'node:stream/promises'
2
+
1
3
  import { defineCommand } from 'citty'
2
4
  import { z } from 'zod'
3
5
 
@@ -5,14 +7,31 @@ import { envEligible, envFor, explicitNames, resolveEnvRefs, secretValues } from
5
7
  import { appendAudit } from '../../audit/log'
6
8
  import { signerOf } from '../../core/entries'
7
9
  import { TypeVaultError } from '../../core/errors'
8
- import { ENTRY_NAME_SYNTAX } from '../../core/naming'
10
+ import { ENTRY_NAME_SYNTAX, matchesOnly } from '../../core/naming'
9
11
  import { importFrom, ONEPASSWORD_VIAS, type ImportSource, type OnePasswordVia, read1Password } from '../../import'
10
12
  import { createRedactor, type Redactor, scrubFile } from '../../redact'
11
13
  import { openDirect, resolveAccess } from '../context'
12
14
  import { csv, note, print, readStdin, repeated } from '../output'
13
15
 
14
- async function pump(stream: ReadableStream<Uint8Array>, redactor: Redactor, sink: NodeJS.WriteStream): Promise<void> {
15
- for await (const chunk of stream.pipeThrough(redactor.stream())) sink.write(chunk)
16
+ async function pump(
17
+ stream: ReadableStream<Uint8Array>,
18
+ redactor: Redactor,
19
+ sink: NodeJS.WriteStream,
20
+ onClosed: () => void = () => {},
21
+ ): Promise<void> {
22
+ const isClosed = (error: unknown): boolean =>
23
+ error instanceof Error && 'code' in error && (error.code === 'EPIPE' || error.code === 'ENOTCONN')
24
+ const onError = (error: Error) => {
25
+ if (isClosed(error)) onClosed()
26
+ }
27
+ sink.on('error', onError)
28
+ try {
29
+ await pipeline(stream.pipeThrough(redactor.stream()), sink, { end: false })
30
+ } catch (error) {
31
+ if (!isClosed(error)) throw error
32
+ } finally {
33
+ sink.off('error', onError)
34
+ }
16
35
  }
17
36
 
18
37
  export const run = defineCommand({
@@ -27,8 +46,10 @@ export const run = defineCommand({
27
46
  if (command.length === 0)
28
47
  throw new TypeVaultError('invalid', 'usage: typevault run [--only ...] -- <command> [args...]')
29
48
  const access = (await resolveAccess(process.env)).access
30
- const only = csv(args.only)
49
+ const only = repeated(rawArgs.slice(0, dash), '--only').flatMap(csv)
31
50
  const values = await access.values(only, args.reason)
51
+ const unmatched = only.filter((pattern) => !values.some((value) => matchesOnly(value.name, [pattern])))
52
+ if (unmatched.length > 0) note(`warning: --only matched no entries: ${unmatched.join(', ')}`)
32
53
  const policy = { ownTiers: await access.ownTiers(), explicit: explicitNames(only) }
33
54
  const env = envFor(values, new Date(), policy)
34
55
  // The child gets its secrets, never the key or grant that opens the vault.
@@ -41,20 +62,60 @@ export const run = defineCommand({
41
62
  if (skipped.length > 0) note(`not loaded (from included tiers; name them in --only): ${skipped.join(', ')}`)
42
63
  const clash = Object.keys(refs.env).find((name) => Object.hasOwn(env, name))
43
64
  if (clash !== undefined)
44
- throw new TypeVaultError('conflict', `${clash} is both a tv:// reference and an entry's variable`)
65
+ throw new TypeVaultError('conflict', `${clash} is both a typevault:// reference and an entry's variable`)
45
66
  const redactor = createRedactor([
46
67
  ...secretValues([...values, ...refs.values]),
47
68
  ...Object.values(env),
48
69
  ...Object.values(refs.env),
49
70
  ])
50
- const child = Bun.spawn(command, {
51
- env: { ...inherited, ...env, ...refs.env },
52
- stdin: 'inherit',
53
- stdout: 'pipe',
54
- stderr: 'pipe',
55
- })
56
- await Promise.all([pump(child.stdout, redactor, process.stdout), pump(child.stderr, redactor, process.stderr)])
57
- process.exitCode = await child.exited
71
+ const child = (() => {
72
+ try {
73
+ return Bun.spawn(command, {
74
+ env: { ...inherited, ...env, ...refs.env },
75
+ // Own the group so descendants receive forwarded signals, and terminal Ctrl-C reaches them only once.
76
+ detached: process.platform !== 'win32',
77
+ stdin: 'inherit',
78
+ stdout: 'pipe',
79
+ stderr: 'pipe',
80
+ })
81
+ } catch (error) {
82
+ if (error instanceof Error && 'code' in error && (error.code === 'ENOENT' || error.code === 'EACCES')) {
83
+ note(error.message)
84
+ return error.code === 'ENOENT' ? 127 : 126
85
+ }
86
+ throw error
87
+ }
88
+ })()
89
+ if (typeof child === 'number') {
90
+ process.exitCode = child
91
+ return
92
+ }
93
+ const signals = ['SIGTERM', 'SIGINT', 'SIGHUP'] as const
94
+ const forward = (signal: NodeJS.Signals): void => {
95
+ if (process.platform === 'win32') {
96
+ child.kill(signal)
97
+ return
98
+ }
99
+ try {
100
+ process.kill(-child.pid, signal)
101
+ } catch (error) {
102
+ // The group may have exited before its exit notification was handled.
103
+ if (!(error instanceof Error && 'code' in error && error.code === 'ESRCH')) throw error
104
+ }
105
+ }
106
+ // A closed reader must not leave the child or its descendants blocked on their output pipes.
107
+ const onClosed = () => forward('SIGKILL')
108
+ for (const signal of signals) process.on(signal, forward)
109
+ try {
110
+ const [code] = await Promise.all([
111
+ child.exited,
112
+ pump(child.stdout, redactor, process.stdout, onClosed),
113
+ pump(child.stderr, redactor, process.stderr, onClosed),
114
+ ])
115
+ process.exitCode = code
116
+ } finally {
117
+ for (const signal of signals) process.off(signal, forward)
118
+ }
58
119
  },
59
120
  })
60
121
 
@@ -65,6 +126,12 @@ async function redactorFor(): Promise<Redactor> {
65
126
  resolved.kind === 'direct'
66
127
  ? secretValues(await resolved.access.values([], 'redact'))
67
128
  : await resolved.access.readValues()
129
+ if (!values.some((value) => Array.from(value).length >= 4)) {
130
+ throw new TypeVaultError(
131
+ 'unavailable',
132
+ 'No redactable values are available; use the still-active grant that read the secrets',
133
+ )
134
+ }
68
135
  return createRedactor(values)
69
136
  }
70
137
 
@@ -83,14 +150,62 @@ export const scrub = defineCommand({
83
150
  },
84
151
  args: { files: { type: 'positional', description: 'Files to scrub', required: true } },
85
152
  async run({ args, rawArgs }) {
86
- const redactor = await redactorFor()
87
- const files = rawArgs.filter((arg) => !arg.startsWith('-'))
153
+ const dash = rawArgs.indexOf('--')
154
+ const before = dash === -1 ? rawArgs : rawArgs.slice(0, dash)
155
+ const option = before.find((arg) => arg.startsWith('-'))
156
+ if (option !== undefined) throw new TypeVaultError('invalid', `Unknown scrub option: ${option}`)
157
+ const files = dash === -1 ? before : [...before, ...rawArgs.slice(dash + 1)]
88
158
  if (files.length === 0) throw new TypeVaultError('invalid', `usage: typevault scrub <file>... (got ${args.files})`)
89
- for (const file of files) if (await scrubFile(file, redactor)) print(file)
159
+ const redactor = await redactorFor()
160
+ for (const file of files) {
161
+ try {
162
+ if (await scrubFile(file, redactor)) print(file)
163
+ } catch (error) {
164
+ if (!(error instanceof TypeVaultError)) throw error
165
+ note(`typevault: ${error.message}`)
166
+ process.exitCode = 1
167
+ }
168
+ }
90
169
  },
91
170
  })
92
171
 
93
- const RequestResponse = z.object({ id: z.string(), url: z.string(), code: z.string() })
172
+ const RequestResponse = z.object({ id: z.string(), url: z.string(), code: z.string(), expiresAt: z.number() })
173
+ const RequestDone = z.object({ stored: z.string() })
174
+ const REQUEST_POLL_MS = 30_000
175
+
176
+ type RequestWaitAccess = {
177
+ call<T>(path: string, body: unknown, schema: z.ZodType<T>, timeoutMs?: number): Promise<T>
178
+ }
179
+
180
+ type RequestWait = {
181
+ readonly id: string
182
+ readonly expiresAt: number
183
+ }
184
+
185
+ type RequestWaitOptions = {
186
+ readonly pollMs?: number
187
+ readonly now?: () => number
188
+ }
189
+
190
+ export async function waitForRequest(
191
+ access: RequestWaitAccess,
192
+ request: RequestWait,
193
+ options: RequestWaitOptions = {},
194
+ ): Promise<z.infer<typeof RequestDone>> {
195
+ const now = options.now ?? Date.now
196
+ const pollMs = options.pollMs ?? REQUEST_POLL_MS
197
+ while (true) {
198
+ const remaining = request.expiresAt - now()
199
+ if (remaining <= 0) throw new TypeVaultError('expired', 'the request expired')
200
+ try {
201
+ return await access.call('/v1/request/wait', { id: request.id }, RequestDone, Math.min(pollMs, remaining))
202
+ } catch (error) {
203
+ if (error instanceof TypeVaultError && error.cause instanceof Error && error.cause.name === 'TimeoutError')
204
+ continue
205
+ throw error
206
+ }
207
+ }
208
+ }
94
209
 
95
210
  export const request = defineCommand({
96
211
  meta: { name: 'request', description: 'Ask a human for a secret through a one-time web page (live grants)' },
@@ -112,12 +227,7 @@ export const request = defineCommand({
112
227
  }
113
228
  const opened = await resolved.access.call('/v1/request', body, RequestResponse)
114
229
  print(`Send this link to the human: ${opened.url}\nMatch code: ${opened.code} (post it in the chat too)`)
115
- const done = await resolved.access.call(
116
- '/v1/request/wait',
117
- { id: opened.id },
118
- z.object({ stored: z.string() }),
119
- 11 * 60_000,
120
- )
230
+ const done = await waitForRequest(resolved.access, opened)
121
231
  print(`stored as ${done.stored}`)
122
232
  },
123
233
  })
@@ -27,7 +27,10 @@ export type Env = Readonly<Record<string, string | undefined>>
27
27
  const isSet = (value: string | undefined): boolean => value !== undefined && value !== ''
28
28
 
29
29
  /** `-g` (`TYPEVAULT_GLOBAL`) or an explicit `TYPEVAULT_DIR` selects the global vault; otherwise the project's. */
30
- export const wantsGlobal = (env: Env): boolean => isSet(env['TYPEVAULT_GLOBAL']) || isSet(env['TYPEVAULT_DIR'])
30
+ export const wantsGlobal = (env: Env): boolean => {
31
+ const global = env['TYPEVAULT_GLOBAL']?.toLowerCase()
32
+ return (isSet(global) && global !== '0' && global !== 'false') || isSet(env['TYPEVAULT_DIR'])
33
+ }
31
34
 
32
35
  /** The selected vault, or undefined when no project vault is found from `cwd`. Never falls back to the global one. */
33
36
  export function findLayout(env: Env, cwd: string = process.cwd()): Layout | undefined {
@@ -114,9 +117,14 @@ async function shareWorktreeSession(layout: Layout, env: Env): Promise<boolean>
114
117
  const [unlocked] = await worktreeSessions(layout, env)
115
118
  if (unlocked === undefined) return false
116
119
  const token = readFileSync(unlocked.sessionFile, 'utf8').trim()
117
- await callDaemon(unlocked.agentSocket, '/v1/attach', { vault: layout.vault }, z.object({ ok: z.literal(true) }), {
118
- token,
119
- })
120
+ try {
121
+ await callDaemon(unlocked.agentSocket, '/v1/attach', { vault: layout.vault }, z.object({ ok: z.literal(true) }), {
122
+ token,
123
+ })
124
+ } catch (error) {
125
+ if (error instanceof TypeVaultError) return false
126
+ throw error
127
+ }
120
128
  return true
121
129
  }
122
130
 
package/src/cli/index.ts CHANGED
@@ -75,6 +75,11 @@ if (wantsUsage) {
75
75
  }
76
76
  // citty's usage errors (unknown command, missing argument): its own runner prints usage for them.
77
77
  if (error instanceof Error && error.name === 'CLIError') await runMain(main)
78
- else throw error
78
+ else {
79
+ const message = error instanceof Error ? error.message : 'unexpected error'
80
+ process.stderr.write(`typevault: ${message.replaceAll(/[\r\n]+/g, ' ')}\n`)
81
+ if (process.env['TYPEVAULT_DEBUG'] === '1') console.error(error)
82
+ process.exit(1)
83
+ }
79
84
  }
80
85
  }
@@ -22,27 +22,41 @@ export type WebEntry = {
22
22
  export async function promptFields(
23
23
  entry: WebEntry,
24
24
  show: (url: string, code: string) => void,
25
+ options: { readonly ttlMs?: number } = {},
25
26
  ): Promise<Record<string, Field>> {
26
27
  const identity = await generateX25519Identity()
27
28
  const server = await startPromptServer()
28
29
  try {
29
30
  const code = matchCode()
30
- const handle = server.open({
31
- name: entry.name,
32
- ...(entry.preset === undefined ? {} : { preset: entry.preset }),
33
- tier: entry.tier ?? 'your default tier',
34
- reason: `Store ${entry.name} from your terminal`,
35
- requester: 'typevault set',
36
- code,
37
- recipients: [await identityToRecipient(identity)],
38
- expiresAt: new Date(Date.now() + TTL_MS),
39
- })
31
+ const handle = server.open(
32
+ {
33
+ name: entry.name,
34
+ ...(entry.preset === undefined ? {} : { preset: entry.preset }),
35
+ tier: entry.tier ?? 'your default tier',
36
+ reason: `Store ${entry.name} from your terminal`,
37
+ requester: 'typevault set',
38
+ code,
39
+ recipients: [await identityToRecipient(identity)],
40
+ expiresAt: new Date(Date.now() + (options.ttlMs ?? TTL_MS)),
41
+ },
42
+ { validate: true },
43
+ )
40
44
  show(handle.url, code)
41
- const payload = decodePayload(await unseal([identity], await handle.done))
42
- if (payload.name !== entry.name) {
43
- throw new TypeVaultError('tampered', 'the submitted secret does not match this entry')
45
+ try {
46
+ const payload = decodePayload(await unseal([identity], await handle.done))
47
+ if (payload.name !== entry.name) {
48
+ throw new TypeVaultError('tampered', 'the submitted secret does not match this entry')
49
+ }
50
+ await handle.accept()
51
+ return { ...payload.fields }
52
+ } catch (error) {
53
+ await handle.reject(
54
+ error instanceof TypeVaultError
55
+ ? error
56
+ : new TypeVaultError('unavailable', 'the submitted secret could not be read'),
57
+ )
58
+ throw error
44
59
  }
45
- return { ...payload.fields }
46
60
  } finally {
47
61
  await server.stop()
48
62
  }
package/src/core/admin.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { encodeSecretKey, generateSecretKey, type PublicKey, publicKeyOf, seal, type SecretKey } from './crypto'
2
- import { utf8 } from './encoding'
2
+ import { fromBase64, utf8 } from './encoding'
3
3
  import { signerOf } from './entries'
4
4
  import { TypeVaultError } from './errors'
5
5
  import { ownerWrapPath, wrapPath } from './keyring'
@@ -128,11 +128,14 @@ export class Admin {
128
128
  return affected
129
129
  }
130
130
 
131
- /** New key generation for `name`. Returns the names of every entry it could reach, now flagged for rotation. */
131
+ /** Rotates every tier `name` reaches. Returns their entry names, now flagged for rotation at the source. */
132
132
  async rotate(name: string): Promise<readonly string[]> {
133
133
  let affected: readonly string[] = []
134
134
  await this.#mutate(async (state, txn) => {
135
- affected = await rotateTiers({ vault: this.#vault, owner: this.#owner, state, txn, exposed: true }, [name])
135
+ affected = await rotateTiers(
136
+ { vault: this.#vault, owner: this.#owner, state, txn, exposed: true },
137
+ reachOf(state, [name]),
138
+ )
136
139
  })
137
140
  return affected
138
141
  }
@@ -178,17 +181,30 @@ export class Admin {
178
181
  return affected
179
182
  }
180
183
 
181
- setSigner(id: string, signPublic: string, tiers: readonly string[]): Promise<void> {
182
- return this.#mutate(async (state, txn) => {
184
+ async setSigner(id: string, signPublic: string, tiers: readonly string[]): Promise<void> {
185
+ const name = parseTierName(id)
186
+ let key: Uint8Array
187
+ try {
188
+ key = fromBase64(signPublic)
189
+ } catch (error) {
190
+ if (error instanceof Error) throw new TypeVaultError('invalid', 'signer public key is not valid base64')
191
+ throw error
192
+ }
193
+ if (key.length !== 32) throw new TypeVaultError('invalid', 'signer public key must be 32 bytes')
194
+ if (tiers.length === 0) throw new TypeVaultError('invalid', 'signer needs at least one tier')
195
+ await this.#mutate(async (state, txn) => {
196
+ const unknown = tiers.find((tier) => tier !== '*' && state.tiers[tier] === undefined)
197
+ if (unknown !== undefined) throw new TypeVaultError('not_found', `no tier "${unknown}"`)
183
198
  txn.put(
184
199
  'signers.json',
185
- signersDoc({ ...state.signers, [id]: { signPublic, tiers } }, this.#owner, state.seqs.signers + 1),
200
+ signersDoc({ ...state.signers, [name]: { signPublic, tiers } }, this.#owner, state.seqs.signers + 1),
186
201
  )
187
202
  })
188
203
  }
189
204
 
190
205
  removeSigner(id: string): Promise<void> {
191
206
  return this.#mutate(async (state, txn) => {
207
+ if (state.signers[id] === undefined) throw new TypeVaultError('not_found', `no signer "${id}"`)
192
208
  const { [id]: _removed, ...rest } = state.signers
193
209
  txn.put('signers.json', signersDoc(rest, this.#owner, state.seqs.signers + 1))
194
210
  })
@@ -206,6 +222,7 @@ export class Admin {
206
222
 
207
223
  removeCeiling(name: string): Promise<void> {
208
224
  return this.#mutate(async (state, txn) => {
225
+ if (state.ceilings[name] === undefined) throw new TypeVaultError('not_found', `no ceiling "${name}"`)
209
226
  const { [name]: _removed, ...rest } = state.ceilings
210
227
  txn.put('ceilings.json', ceilingsDoc(rest, this.#owner, state.seqs.ceilings + 1))
211
228
  })
@@ -15,7 +15,7 @@ export type DoctorReport = {
15
15
  readonly needsRotation: readonly string[]
16
16
  }
17
17
 
18
- const CONFLICT = /^<<<<<<< [^\n]*\n([\s\S]*?)^=======\n([\s\S]*?)^>>>>>>> [^\n]*\n?/m
18
+ const CONFLICT = /^<<<<<<< [^\n]*\n([\s\S]*?)^=======\n([\s\S]*?)^>>>>>>> [^\n]*\n?/gm
19
19
 
20
20
  function parseSide(text: string): Envelope | undefined {
21
21
  try {
@@ -31,12 +31,11 @@ function parseSide(text: string): Envelope | undefined {
31
31
  function resolveMerge(vault: Vault, file: string): boolean {
32
32
  const path = join(vault.layout.entries, file)
33
33
  const text = readFileSync(path, 'utf8')
34
- const match = CONFLICT.exec(text)
35
- if (match === null) return false
36
- const before = text.slice(0, match.index)
37
- const after = text.slice(match.index + match[0].length)
38
- const sides = [match[1] ?? '', match[2] ?? '']
39
- .map((side) => parseSide(before + side + after))
34
+ const ours = text.replace(CONFLICT, '$1')
35
+ if (ours === text) return false
36
+ const theirs = text.replace(CONFLICT, '$2')
37
+ const sides = [ours, theirs]
38
+ .map(parseSide)
40
39
  .filter((side): side is Envelope => side !== undefined && verifyEnvelope(side, vault.state) === undefined)
41
40
  const winner = sides.reduce<Envelope | undefined>(
42
41
  (best, side) =>
@@ -17,8 +17,8 @@ export type ErrorCode =
17
17
  export class TypeVaultError extends Error {
18
18
  readonly code: ErrorCode
19
19
 
20
- constructor(code: ErrorCode, message: string) {
21
- super(message)
20
+ constructor(code: ErrorCode, message: string, options?: ErrorOptions) {
21
+ super(message, options)
22
22
  this.name = 'TypeVaultError'
23
23
  this.code = code
24
24
  }
@@ -1,9 +1,10 @@
1
- import { existsSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
1
+ import { existsSync, rmSync, writeFileSync } from 'node:fs'
2
2
 
3
3
  import { z } from 'zod'
4
4
 
5
5
  import { randomHex } from './crypto'
6
6
  import { TypeVaultError } from './errors'
7
+ import { readJsonFile } from './json-file'
7
8
  import { hostId, type Layout } from './layout'
8
9
 
9
10
  type Env = Readonly<Record<string, string | undefined>>
@@ -62,16 +63,18 @@ export function claimDaemon(layout: Layout, env: Env): DaemonClaim {
62
63
 
63
64
  function readHolder(layout: Layout): Holder | undefined {
64
65
  if (!existsSync(layout.daemonHolder)) return undefined
65
- let text: string
66
66
  try {
67
- text = readFileSync(layout.daemonHolder, 'utf8')
67
+ return readJsonFile(layout.daemonHolder, HolderSchema)
68
68
  } catch (error) {
69
69
  if (isCode(error, 'ENOENT')) return undefined
70
+ if (error instanceof TypeVaultError && error.code === 'tampered') {
71
+ throw new TypeVaultError(
72
+ 'tampered',
73
+ `${layout.daemonHolder} is malformed; if its daemon is gone for good, delete this file and retry`,
74
+ )
75
+ }
70
76
  throw error
71
77
  }
72
- const parsed = HolderSchema.safeParse(JSON.parse(text))
73
- if (!parsed.success) throw new TypeVaultError('tampered', `${layout.daemonHolder} is malformed`)
74
- return parsed.data
75
78
  }
76
79
 
77
80
  const inUse = (layout: Layout, holder: Holder): TypeVaultError =>
@@ -1,4 +1,4 @@
1
- import { existsSync, readFileSync } from 'node:fs'
1
+ import { existsSync } from 'node:fs'
2
2
  import { join } from 'node:path'
3
3
 
4
4
  import { z } from 'zod'
@@ -13,7 +13,8 @@ import {
13
13
  } from './crypto'
14
14
  import { fromBase64Url, fromUtf8, toBase64Url, utf8 } from './encoding'
15
15
  import { TypeVaultError } from './errors'
16
- import { assertNoSymlinks, atomicWrite } from './fsx'
16
+ import { assertNoSymlinks, atomicWrite, ensureDir } from './fsx'
17
+ import { readJsonFile } from './json-file'
17
18
  import { configDir, type Layout } from './layout'
18
19
  import { generateSecretKeyCode, openWithPassword, sealWithPassword } from './password'
19
20
  import { type MemberKind, parseMemberName } from './state'
@@ -61,10 +62,11 @@ export const identityPath = (env: Env): string => join(configDir(env), 'identity
61
62
 
62
63
  export function readIdentity(env: Env): Identity | undefined {
63
64
  const path = identityPath(env)
64
- return existsSync(path) ? IdentitySchema.parse(JSON.parse(readFileSync(path, 'utf8'))) : undefined
65
+ return existsSync(path) ? readJsonFile(path, IdentitySchema) : undefined
65
66
  }
66
67
 
67
68
  export function writeIdentity(env: Env, identity: Identity): void {
69
+ ensureDir(configDir(env), 0o700)
68
70
  atomicWrite(identityPath(env), `${JSON.stringify(identity, null, 2)}\n`, 0o600)
69
71
  }
70
72
 
@@ -0,0 +1,20 @@
1
+ import { readFileSync } from 'node:fs'
2
+
3
+ import { z } from 'zod'
4
+
5
+ import { TypeVaultError } from './errors'
6
+
7
+ /** Syntax and schema failures in persisted state are corruption, never request-body errors. */
8
+ export function parseJsonText<T>(path: string, text: string, schema: z.ZodType<T>): T {
9
+ try {
10
+ return schema.parse(JSON.parse(text))
11
+ } catch (error) {
12
+ if (error instanceof SyntaxError || error instanceof z.ZodError) {
13
+ throw new TypeVaultError('tampered', `${path} is malformed; repair or restore this file before retrying`)
14
+ }
15
+ throw error
16
+ }
17
+ }
18
+
19
+ export const readJsonFile = <T>(path: string, schema: z.ZodType<T>): T =>
20
+ parseJsonText(path, readFileSync(path, 'utf8'), schema)
@@ -1,10 +1,12 @@
1
- import { existsSync, readFileSync, realpathSync } from 'node:fs'
1
+ import { existsSync, realpathSync } from 'node:fs'
2
2
  import { homedir, hostname } from 'node:os'
3
3
  import { dirname, join, resolve } from 'node:path'
4
4
 
5
+ import { z } from 'zod'
6
+
5
7
  import { sha256Hex } from './crypto'
6
8
  import { utf8 } from './encoding'
7
- import { TypeVaultError } from './errors'
9
+ import { readJsonFile } from './json-file'
8
10
 
9
11
  export type Layout = {
10
12
  /** `global`: one vault per user, `~/.typevault/`. `local`: a `.typevault/` committed in a project. */
@@ -111,11 +113,7 @@ function vaultLayout(scope: Layout['scope'], dir: string, env: Env): Layout {
111
113
  }
112
114
 
113
115
  function ownerSignPublic(vault: string): string {
114
- const owner: unknown = JSON.parse(readFileSync(join(vault, 'owner.json'), 'utf8'))
115
- if (typeof owner !== 'object' || owner === null || !('signPublic' in owner) || typeof owner.signPublic !== 'string') {
116
- throw new TypeVaultError('tampered', `${join(vault, 'owner.json')} is malformed`)
117
- }
118
- return owner.signPublic
116
+ return readJsonFile(join(vault, 'owner.json'), z.object({ signPublic: z.string() })).signPublic
119
117
  }
120
118
 
121
119
  // A home directory reached through a symlink (macOS's /tmp, say) is still the same directory.
@@ -25,22 +25,22 @@ const SEGMENT = /^[a-z0-9]+(?:-[a-z0-9]+)*$/
25
25
  const MAX_SEGMENTS = 2
26
26
 
27
27
  /**
28
- * The one way to point at an entry: `tv://<service>[/<account>][#<field>]`. `typevault://` is an alias, and the
29
- * scheme may be left out (`github/bot#password`) as shorthand. Every name, `--only` pattern and env reference goes
30
- * through the parsers below.
28
+ * The one way to point at an entry: `typevault://<service>[/<account>][#<field>]`. The scheme may be left out
29
+ * (`github/bot#password`) as shorthand. Every name, `--only` pattern and env reference goes through the parsers
30
+ * below.
31
31
  */
32
- export const ENTRY_NAME_SYNTAX = 'tv://<service>[/<account>]'
32
+ export const ENTRY_NAME_SYNTAX = 'typevault://<service>[/<account>]'
33
33
  export const ENTRY_REF_SYNTAX = `${ENTRY_NAME_SYNTAX}[#<field>]`
34
34
 
35
- const REF_SCHEME = /^(?:tv|typevault):\/\//i
35
+ const REF_SCHEME = /^typevault:\/\//i
36
36
 
37
- /** True when `input` carries the `tv://` (or `typevault://`) scheme, as an env value `run` resolves. */
37
+ /** True when `input` carries the `typevault://` scheme, as an env value `run` resolves. */
38
38
  export const hasRefScheme = (input: string): boolean => REF_SCHEME.test(input.trim())
39
39
 
40
40
  /** An `--only` pattern (a name or a glob) in the form names are stored in: no scheme, lowercase. */
41
41
  export const entryPattern = (input: string): string => input.trim().replace(REF_SCHEME, '').toLowerCase()
42
42
 
43
- /** Parses `[tv://]<service>[/<account>]`. Names are case-insensitive and stored lowercase, without the scheme. */
43
+ /** Parses `[typevault://]<service>[/<account>]`. Names are case-insensitive, stored lowercase and without the scheme. */
44
44
  export function parseEntryName(input: string): EntryName {
45
45
  const name = entryPattern(input)
46
46
  const segments = name.split('/')
@@ -68,7 +68,7 @@ export const isFieldName = (field: string): boolean =>
68
68
  field.trim() === field &&
69
69
  !/[\p{Cc}=]/u.test(field)
70
70
 
71
- /** Parses `[tv://]<service>[/<account>][#<field>]`. The field is everything after the first `#`. */
71
+ /** Parses `[typevault://]<service>[/<account>][#<field>]`. The field is everything after the first `#`. */
72
72
  export function parseEntryRef(input: string): EntryRef {
73
73
  const hash = input.indexOf('#')
74
74
  if (hash === -1) return { name: parseEntryName(input), field: undefined }
@@ -156,7 +156,7 @@ function assertNever(value: never): never {
156
156
  /**
157
157
  * `github/bot` + `password` becomes `GITHUB_BOT_PASSWORD`, and `Secret Access Key` becomes `..._SECRET_ACCESS_KEY`.
158
158
  * Undefined when no letter or digit of the field survives (a non-Latin name): such a field is reachable only
159
- * through a `tv://` ref.
159
+ * through a `typevault://` ref.
160
160
  */
161
161
  export function deriveEnvName(name: EntryName, field: string): string | undefined {
162
162
  if (field === '$default') return name.toUpperCase().replace(/[/-]/g, '_')
@@ -197,9 +197,12 @@ const RESERVED_ENV = new RegExp(
197
197
  'EDITOR|VISUAL|PAGER|BROWSER|MANPAGER|LESS\\w*|SSH_ASKPASS\\w*|SSH_AUTH_SOCK|GIT_\\w*',
198
198
  // interpreters and loaders
199
199
  'NODE_OPTIONS|NODE_PATH|NODE_EXTRA_CA_CERTS|PYTHONPATH|PYTHONHOME|PYTHONSTARTUP|RUBYOPT|RUBYLIB|PERL5OPT|PERL5LIB|PERLLIB',
200
+ 'NODE_TLS_REJECT_UNAUTHORIZED|CLASSPATH|GEM_PATH|GEM_HOME|GCONV_PATH',
200
201
  'JAVA_TOOL_OPTIONS|_JAVA_OPTIONS|JDK_JAVA_OPTIONS|LD_\\w*|DYLD_\\w*|BUN_\\w*|NPM_CONFIG_\\w*',
201
202
  // where traffic goes and which certificates it trusts
202
- 'HTTPS?_PROXY|ALL_PROXY|NO_PROXY|SSL_CERT_FILE|SSL_CERT_DIR|REQUESTS_CA_BUNDLE|CURL_CA_BUNDLE',
203
+ '\\w*_PROXY|SOCKS_\\w*|\\w*_CA_BUNDLE|\\w*_CA_CERTS|\\w*CERT_FILE|SSL_CERT_DIR|SSLKEYLOGFILE',
204
+ // tool config directories, without reserving unrelated names such as CUSTOMER_HOME
205
+ 'CURL_HOME|WGETRC',
203
206
  // package managers and toolchains that fetch or run code
204
207
  'PIP_\\w*|UV_\\w*|CARGO_\\w*|RUSTC_WRAPPER|RUSTC|GOFLAGS|GOPROXY|GONOSUMDB|GOPRIVATE|DOCKER_HOST|DOCKER_CONFIG',
205
208
  'TYPEVAULT_\\w*',
@@ -53,13 +53,13 @@ function parsePayload(value: unknown, code: 'invalid' | 'tampered'): z.infer<typ
53
53
  const parsed = PayloadSchema.safeParse(value)
54
54
  if (!parsed.success)
55
55
  throw new TypeVaultError(code, `malformed entry payload: ${parsed.error.issues[0]?.message ?? 'invalid'}`)
56
- const { env } = parsed.data
57
- if (env !== undefined && !isUsableEnvName(env)) throw new TypeVaultError(code, `${env} is not a usable env name`)
58
56
  return parsed.data
59
57
  }
60
58
 
61
59
  export function encodePayload(payload: EntryPayload): Uint8Array {
62
60
  parsePayload(payload, 'invalid')
61
+ const { env } = payload
62
+ if (env !== undefined && !isUsableEnvName(env)) throw new TypeVaultError('invalid', `${env} is not a usable env name`)
63
63
  return utf8(JSON.stringify(payload))
64
64
  }
65
65
 
@@ -1,8 +1,9 @@
1
- import { existsSync, readFileSync } from 'node:fs'
1
+ import { existsSync } from 'node:fs'
2
2
 
3
3
  import { z } from 'zod'
4
4
 
5
5
  import { atomicWrite } from './fsx'
6
+ import { readJsonFile } from './json-file'
6
7
 
7
8
  const MarksSchema = z.record(z.string(), z.number().int())
8
9
 
@@ -17,7 +18,7 @@ export class RevisionMarks {
17
18
 
18
19
  constructor(path: string) {
19
20
  this.#path = path
20
- this.#marks = existsSync(path) ? MarksSchema.parse(JSON.parse(readFileSync(path, 'utf8'))) : {}
21
+ this.#marks = existsSync(path) ? readJsonFile(path, MarksSchema) : {}
21
22
  }
22
23
 
23
24
  /** False when `rev` is older than a revision already seen for `id`. */