typevault 0.1.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 (76) hide show
  1. package/README.md +156 -115
  2. package/package.json +14 -2
  3. package/src/access/env.ts +77 -17
  4. package/src/access/keys.ts +14 -14
  5. package/src/access/schemas.ts +6 -12
  6. package/src/access/scope.ts +14 -9
  7. package/src/access/scoped.ts +118 -44
  8. package/src/access/sealed-access.ts +50 -23
  9. package/src/access/sealed.ts +56 -31
  10. package/src/access/types.ts +27 -30
  11. package/src/admin.ts +68 -0
  12. package/src/audit/log.ts +28 -12
  13. package/src/cli/commands/admin.ts +93 -48
  14. package/src/cli/commands/daemon.ts +42 -17
  15. package/src/cli/commands/entries.ts +195 -60
  16. package/src/cli/commands/grant.ts +24 -22
  17. package/src/cli/commands/members.ts +307 -0
  18. package/src/cli/commands/run.ts +191 -44
  19. package/src/cli/context.ts +163 -15
  20. package/src/cli/index.ts +33 -5
  21. package/src/cli/password.ts +74 -0
  22. package/src/cli/web-prompt.ts +79 -0
  23. package/src/core/admin.ts +144 -76
  24. package/src/core/adopt.ts +40 -9
  25. package/src/core/crypto.ts +6 -4
  26. package/src/core/doctor.ts +15 -16
  27. package/src/core/entries.ts +66 -52
  28. package/src/core/errors.ts +8 -2
  29. package/src/core/fsx.ts +7 -3
  30. package/src/core/holder.ts +87 -0
  31. package/src/core/identity.ts +132 -0
  32. package/src/core/init.ts +73 -23
  33. package/src/core/json-file.ts +20 -0
  34. package/src/core/keyring.ts +100 -56
  35. package/src/core/layout.ts +143 -26
  36. package/src/core/lock.ts +128 -16
  37. package/src/core/naming.ts +150 -50
  38. package/src/core/password.ts +111 -0
  39. package/src/core/payload.ts +42 -38
  40. package/src/core/revisions.ts +11 -6
  41. package/src/core/rotate.ts +59 -42
  42. package/src/core/state.ts +102 -54
  43. package/src/core/txn.ts +9 -7
  44. package/src/core/vault.ts +108 -46
  45. package/src/core/worktrees.ts +51 -0
  46. package/src/daemon/admin-routes.ts +33 -21
  47. package/src/daemon/agent-routes.ts +31 -11
  48. package/src/daemon/client.ts +24 -2
  49. package/src/daemon/daemon.ts +218 -33
  50. package/src/daemon/grants.ts +25 -7
  51. package/src/daemon/http.ts +11 -2
  52. package/src/daemon/live-access.ts +8 -4
  53. package/src/daemon/protocol.ts +17 -12
  54. package/src/daemon/requests.ts +75 -51
  55. package/src/daemon/spawn.ts +218 -9
  56. package/src/export/1password.ts +157 -0
  57. package/src/import/1password-live.ts +399 -0
  58. package/src/import/1password.ts +26 -5
  59. package/src/import/bitwarden.ts +3 -3
  60. package/src/import/csv.ts +1 -1
  61. package/src/import/dotenv.ts +4 -3
  62. package/src/import/index.ts +1 -0
  63. package/src/import/keepass.ts +2 -2
  64. package/src/import/lastpass.ts +2 -2
  65. package/src/import/shared.ts +67 -10
  66. package/src/import/typeclaw.ts +2 -2
  67. package/src/import/types.ts +1 -1
  68. package/src/index.ts +58 -0
  69. package/src/owner.ts +156 -0
  70. package/src/prompt/browser.ts +48 -15
  71. package/src/prompt/index.ts +121 -64
  72. package/src/prompt/page.ts +27 -11
  73. package/src/prompt/styles.ts +64 -34
  74. package/src/prompt/types.ts +7 -4
  75. package/src/redact/index.ts +48 -12
  76. package/src/redact/scrub-file.ts +15 -7
@@ -0,0 +1,307 @@
1
+ import { existsSync, readFileSync } from 'node:fs'
2
+ import { userInfo } from 'node:os'
3
+
4
+ import { defineCommand } from 'citty'
5
+
6
+ import { parseTtl } from '../../access/scope'
7
+ import { publicKeyOf } from '../../core/crypto'
8
+ import { TypeVaultError } from '../../core/errors'
9
+ import { atomicWrite } from '../../core/fsx'
10
+ import {
11
+ createIdentity,
12
+ decodeMemberPublic,
13
+ encodeMemberPublic,
14
+ type Identity,
15
+ memberPublicOfIdentity,
16
+ openMemberKey,
17
+ readIdentity,
18
+ sealedCopyPath,
19
+ sealMemberKey,
20
+ writeIdentity,
21
+ } from '../../core/identity'
22
+ import { type Layout, localLayout, vaultIdOf } from '../../core/layout'
23
+ import { readOwner } from '../../core/state'
24
+ import { Vault } from '../../core/vault'
25
+ import { worktreeVaults } from '../../core/worktrees'
26
+ import { endLiveGrants, stopDaemon } from '../../daemon/spawn'
27
+ import { export1Password, identityTitle } from '../../export/1password'
28
+ import { ONEPASSWORD_VIAS } from '../../import/1password-live'
29
+ import {
30
+ DEFAULT_SESSION_MS,
31
+ findLayout,
32
+ layoutFrom,
33
+ openAdmin,
34
+ openPublic,
35
+ unlockSession,
36
+ worktreeSessions,
37
+ type Env,
38
+ } from '../context'
39
+ import { csv, note, print, table } from '../output'
40
+ import { newPassword, passwords } from '../password'
41
+
42
+ export const identityArgs = {
43
+ name: { type: 'string', description: 'Your member name, the first time (default: your OS user name)' },
44
+ machine: { type: 'boolean', description: 'A machine identity (CI, an agent host): no password, key kept here' },
45
+ } as const
46
+
47
+ type IdentityArgs = {
48
+ readonly name?: string | undefined
49
+ readonly machine?: boolean | undefined
50
+ }
51
+
52
+ /** This device's identity, created on first use. A new human identity prints its Secret Key once. */
53
+ export async function ensureIdentity(env: Env, args: IdentityArgs): Promise<Identity> {
54
+ const existing = readIdentity(env)
55
+ if (existing !== undefined) {
56
+ if (args.name !== undefined && args.name !== existing.name) {
57
+ throw new TypeVaultError('conflict', `this device is already "${existing.name}"`)
58
+ }
59
+ return existing
60
+ }
61
+ const kind = args.machine === true ? 'machine' : 'human'
62
+ const name = args.name ?? defaultName()
63
+ const password = kind === 'human' ? await newPassword(passwords()) : undefined
64
+ const { identity } = await createIdentity(name, kind, password)
65
+ writeIdentity(env, identity)
66
+ if (identity.kind === 'human') {
67
+ note(`created identity "${name}". Your Secret Key:\n\n ${identity.secretKey}\n`)
68
+ note('Save it with your password (a password manager, or on paper): on a new device both are needed to')
69
+ note('get back in (`typevault identity restore`). It stays on this device; never commit it.')
70
+ } else note(`created machine identity "${name}"`)
71
+ return identity
72
+ }
73
+
74
+ const defaultName = (): string =>
75
+ userInfo()
76
+ .username.toLowerCase()
77
+ .replace(/[^a-z0-9]+/g, '-')
78
+ .replace(/^-+|-+$/g, '') || 'me'
79
+
80
+ export const joinCommand = defineCommand({
81
+ meta: { name: 'join', description: 'Ask to join this vault: prints the line an owner runs to add you' },
82
+ args: identityArgs,
83
+ async run({ args }) {
84
+ const env = process.env
85
+ const layout = layoutFrom(env)
86
+ const identity = await ensureIdentity(env, args)
87
+ const vault = await Vault.open(layout, [], env)
88
+ if (vault.state.members[identity.name] !== undefined) return print(`"${identity.name}" is already a member`)
89
+ if (identity.kind === 'human') {
90
+ const copy = sealedCopyPath(layout, identity.name)
91
+ atomicWrite(copy, identity.sealedKey)
92
+ note(`wrote ${copy} (sealed by your password); commit it`)
93
+ }
94
+ note('ask an owner to run:')
95
+ print(
96
+ `typevault member add ${identity.name} ${encodeMemberPublic(memberPublicOfIdentity(identity))} --tier <tiers>`,
97
+ )
98
+ },
99
+ })
100
+
101
+ export const member = defineCommand({
102
+ meta: { name: 'member', description: 'Who can open this vault: people and machines (owner)' },
103
+ subCommands: {
104
+ ls: defineCommand({
105
+ meta: { name: 'ls' },
106
+ async run() {
107
+ const env = process.env
108
+ const { members } = (await openPublic(env)).state
109
+ print(
110
+ table([
111
+ ['MEMBER', 'KIND', 'OWNER', 'TIERS'],
112
+ ...Object.entries(members).map(([name, m]) => [name, m.kind, m.owner ? 'yes' : '', m.tiers.join(', ')]),
113
+ ]),
114
+ )
115
+ },
116
+ }),
117
+ add: defineCommand({
118
+ meta: { name: 'add', description: 'Add a member from the line `typevault join` printed; rotates their tiers' },
119
+ args: {
120
+ name: { type: 'positional', required: true },
121
+ publicKey: { type: 'positional', required: true, description: 'tvp1:... from `typevault join`' },
122
+ tier: { type: 'string', description: 'Comma-separated tiers whose keys they get' },
123
+ owner: { type: 'boolean', description: 'Also an owner: manages tiers, members and grants' },
124
+ },
125
+ async run({ args }) {
126
+ const tiers = csv(args.tier)
127
+ if (tiers.length === 0 && args.owner !== true)
128
+ throw new TypeVaultError('invalid', 'member add needs --tier or --owner')
129
+ const pub = decodeMemberPublic(args.publicKey)
130
+ await (await openAdmin(process.env)).addMember(args.name, { ...pub, owner: args.owner === true, tiers })
131
+ print(`added ${pub.kind} member ${args.name}${tiers.length === 0 ? '' : ` (rotated ${tiers.join(', ')})`}`)
132
+ note('commit the vault so they can pull it')
133
+ },
134
+ }),
135
+ rm: defineCommand({
136
+ meta: { name: 'rm', description: 'Remove a member and rotate every tier they reached' },
137
+ args: { name: { type: 'positional', required: true } },
138
+ async run({ args }) {
139
+ const affected = await (await openAdmin(process.env)).removeMember(args.name)
140
+ print(`removed ${args.name}`)
141
+ if (affected.length === 0) return
142
+ note('They may have kept what they read. Rotate these secrets at their source, then re-set them:')
143
+ for (const name of affected) note(` ${name}`)
144
+ },
145
+ }),
146
+ },
147
+ })
148
+
149
+ export const identity = defineCommand({
150
+ meta: { name: 'identity', description: "This device's member identity" },
151
+ subCommands: {
152
+ show: defineCommand({
153
+ meta: { name: 'show', description: 'Your name, kind and public key (safe to share)' },
154
+ run() {
155
+ const current = readIdentity(process.env)
156
+ if (current === undefined) throw new TypeVaultError('not_found', 'no identity yet (run typevault init or join)')
157
+ print(
158
+ table([
159
+ ['NAME', current.name],
160
+ ['KIND', current.kind],
161
+ ['PUBLIC KEY', encodeMemberPublic(memberPublicOfIdentity(current))],
162
+ ]),
163
+ )
164
+ },
165
+ }),
166
+ restore: defineCommand({
167
+ meta: { name: 'restore', description: 'Set up a new device from your Secret Key, password and this vault' },
168
+ args: { name: { type: 'positional', required: true } },
169
+ async run({ args }) {
170
+ const env = process.env
171
+ if (readIdentity(env) !== undefined) throw new TypeVaultError('conflict', 'this device already has an identity')
172
+ const layout = layoutFrom(env)
173
+ const copy = sealedCopyPath(layout, args.name)
174
+ if (!existsSync(copy)) throw new TypeVaultError('not_found', `this vault has no sealed key for "${args.name}"`)
175
+ const source = passwords()
176
+ const secretKey = await source.ask('Secret Key: ')
177
+ const sealedKey = readFileSync(copy, 'utf8')
178
+ const key = await openMemberKey(sealedKey, await source.ask('Password: '), secretKey)
179
+ const pub = await publicKeyOf(key)
180
+ const listed = (await Vault.open(layout, [], env)).state.members[args.name]
181
+ if (key.role.kind !== 'member' || key.role.name !== args.name || listed?.recipient !== pub.recipient) {
182
+ throw new TypeVaultError('tampered', `the sealed key does not belong to member "${args.name}"`)
183
+ }
184
+ writeIdentity(env, { v: 1, kind: 'human', name: args.name, secretKey, sealedKey, ...pub })
185
+ print(`restored identity "${args.name}"`)
186
+ },
187
+ }),
188
+ export: defineCommand({
189
+ meta: { name: 'export', description: 'Store your Secret Key (or a machine key) in 1Password' },
190
+ args: {
191
+ to: { type: 'string', required: true, description: '1password' },
192
+ via: { type: 'string', description: `${ONEPASSWORD_VIAS.join(' | ')} (default: op when installed, else sdk)` },
193
+ account: { type: 'string', description: '1Password account (required with sdk or several op accounts)' },
194
+ vault: { type: 'string', required: true, description: '1Password vault' },
195
+ title: { type: 'string', description: 'Item title (default: TypeVault identity <name>)' },
196
+ replace: { type: 'boolean', description: 'Archive an existing item with the same title' },
197
+ },
198
+ async run({ args }) {
199
+ if (args.to !== '1password') throw new TypeVaultError('invalid', '--to must be 1password')
200
+ const via = ONEPASSWORD_VIAS.find((candidate) => candidate === args.via)
201
+ if (args.via !== undefined && via === undefined) {
202
+ throw new TypeVaultError('invalid', `--via must be one of: ${ONEPASSWORD_VIAS.join(', ')}`)
203
+ }
204
+ const current = readIdentity(process.env)
205
+ if (current === undefined) throw new TypeVaultError('not_found', 'no identity yet (run typevault init or join)')
206
+ const item = {
207
+ title: args.title ?? identityTitle(current.name),
208
+ credential: current.kind === 'human' ? current.secretKey : current.key,
209
+ details: {
210
+ name: current.name,
211
+ kind: current.kind,
212
+ 'public key': encodeMemberPublic(memberPublicOfIdentity(current)),
213
+ },
214
+ }
215
+ const used = await export1Password(item, {
216
+ ...(via === undefined ? {} : { via }),
217
+ ...(args.account === undefined ? {} : { account: args.account }),
218
+ vault: args.vault,
219
+ replace: args.replace === true,
220
+ })
221
+ print(`stored "${item.title}" in 1Password vault "${args.vault}" (via ${used})`)
222
+ if (current.kind === 'machine') note(`use it: TYPEVAULT_KEY="op://${args.vault}/${item.title}/credential"`)
223
+ },
224
+ }),
225
+ },
226
+ })
227
+
228
+ const MAX_TIMER_MS = 2 ** 31 - 1
229
+
230
+ export const unlock = defineCommand({
231
+ meta: { name: 'unlock', description: 'Unlock this vault for a while, so you and your agents can use it' },
232
+ args: { for: { type: 'string', default: '8h', description: 'How long, e.g. 30m, 8h' } },
233
+ async run({ args }) {
234
+ const env = process.env
235
+ const ttlMs = args.for === undefined ? DEFAULT_SESSION_MS : parseTtl(args.for)
236
+ if (ttlMs > MAX_TIMER_MS) throw new TypeVaultError('invalid', '--for is too long (at most 24 days)')
237
+ const started = await unlockSession(env, passwords(), ttlMs)
238
+ const id = vaultIdOf((await openPublic(env)).state.owner.signPublic)
239
+ print(started ? `unlocked vault ${id} for ${args.for}` : `vault ${id} is already unlocked`)
240
+ },
241
+ })
242
+
243
+ export const lock = defineCommand({
244
+ meta: { name: 'lock', description: 'Lock this vault now: stops the daemon and ends every session and live grant' },
245
+ async run() {
246
+ const layout = findLayout(process.env)
247
+ if (layout === undefined) throw new TypeVaultError('not_found', 'no vault here')
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
+ )
279
+ let locked = false
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)
284
+ }
285
+ print(locked ? 'locked' : 'already locked')
286
+ },
287
+ })
288
+
289
+ export const passwd = defineCommand({
290
+ meta: { name: 'passwd', description: 'Change your password (your key and every vault stay the same)' },
291
+ async run() {
292
+ const env = process.env
293
+ const current = readIdentity(env)
294
+ if (current?.kind !== 'human') throw new TypeVaultError('invalid', 'only a human identity has a password')
295
+ const source = passwords()
296
+ const key = await openMemberKey(current.sealedKey, await source.ask('Current password: '), current.secretKey)
297
+ const sealedKey = await sealMemberKey(key, await newPassword(source), current.secretKey)
298
+ writeIdentity(env, { ...current, sealedKey })
299
+ print('password changed')
300
+ const layout = findLayout(env)
301
+ const copy = layout === undefined ? undefined : sealedCopyPath(layout, current.name)
302
+ if (copy !== undefined && existsSync(copy)) {
303
+ atomicWrite(copy, sealedKey)
304
+ note(`updated ${copy}; commit it. Other vaults pick up the change on your next unlock there.`)
305
+ }
306
+ },
307
+ })
@@ -1,17 +1,37 @@
1
+ import { pipeline } from 'node:stream/promises'
2
+
1
3
  import { defineCommand } from 'citty'
2
4
  import { z } from 'zod'
3
5
 
4
- import { envEligible, envFor, explicitNames, secretValues } from '../../access/env'
6
+ import { envEligible, envFor, explicitNames, resolveEnvRefs, secretValues } from '../../access/env'
5
7
  import { appendAudit } from '../../audit/log'
6
8
  import { signerOf } from '../../core/entries'
7
9
  import { TypeVaultError } from '../../core/errors'
8
- import { importFrom, type ImportSource } from '../../import'
10
+ import { ENTRY_NAME_SYNTAX, matchesOnly } from '../../core/naming'
11
+ import { importFrom, ONEPASSWORD_VIAS, type ImportSource, type OnePasswordVia, read1Password } from '../../import'
9
12
  import { createRedactor, type Redactor, scrubFile } from '../../redact'
10
13
  import { openDirect, resolveAccess } from '../context'
11
- import { csv, note, print, readStdin } from '../output'
14
+ import { csv, note, print, readStdin, repeated } from '../output'
12
15
 
13
- async function pump(stream: ReadableStream<Uint8Array>, redactor: Redactor, sink: NodeJS.WriteStream): Promise<void> {
14
- 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
+ }
15
35
  }
16
36
 
17
37
  export const run = defineCommand({
@@ -26,23 +46,76 @@ export const run = defineCommand({
26
46
  if (command.length === 0)
27
47
  throw new TypeVaultError('invalid', 'usage: typevault run [--only ...] -- <command> [args...]')
28
48
  const access = (await resolveAccess(process.env)).access
29
- const only = csv(args.only)
49
+ const only = repeated(rawArgs.slice(0, dash), '--only').flatMap(csv)
30
50
  const values = await access.values(only, args.reason)
31
- const policy = { ownGroups: await access.ownGroups(), explicit: explicitNames(only) }
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(', ')}`)
53
+ const policy = { ownTiers: await access.ownTiers(), explicit: explicitNames(only) }
32
54
  const env = envFor(values, new Date(), policy)
33
- const skipped = values.filter((value) => !envEligible(value, policy)).map((value) => value.name)
34
- if (skipped.length > 0) note(`not loaded (from included groups; name them in --only): ${skipped.join(', ')}`)
35
- const redactor = createRedactor([...secretValues(values), ...Object.values(env)])
36
55
  // The child gets its secrets, never the key or grant that opens the vault.
37
56
  const inherited = Object.fromEntries(Object.entries(process.env).filter(([name]) => !name.startsWith('TYPEVAULT_')))
38
- const child = Bun.spawn(command, {
39
- env: { ...inherited, ...env },
40
- stdin: 'inherit',
41
- stdout: 'pipe',
42
- stderr: 'pipe',
43
- })
44
- await Promise.all([pump(child.stdout, redactor, process.stdout), pump(child.stderr, redactor, process.stderr)])
45
- process.exitCode = await child.exited
57
+ const refs = await resolveEnvRefs(inherited, (name) => access.get(name, args.reason), new Date())
58
+ const referenced = new Set(refs.values.map((value) => value.name))
59
+ const skipped = values
60
+ .filter((value) => !envEligible(value, policy) && !referenced.has(value.name))
61
+ .map((value) => value.name)
62
+ if (skipped.length > 0) note(`not loaded (from included tiers; name them in --only): ${skipped.join(', ')}`)
63
+ const clash = Object.keys(refs.env).find((name) => Object.hasOwn(env, name))
64
+ if (clash !== undefined)
65
+ throw new TypeVaultError('conflict', `${clash} is both a typevault:// reference and an entry's variable`)
66
+ const redactor = createRedactor([
67
+ ...secretValues([...values, ...refs.values]),
68
+ ...Object.values(env),
69
+ ...Object.values(refs.env),
70
+ ])
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
+ }
46
119
  },
47
120
  })
48
121
 
@@ -53,6 +126,12 @@ async function redactorFor(): Promise<Redactor> {
53
126
  resolved.kind === 'direct'
54
127
  ? secretValues(await resolved.access.values([], 'redact'))
55
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
+ }
56
135
  return createRedactor(values)
57
136
  }
58
137
 
@@ -71,21 +150,69 @@ export const scrub = defineCommand({
71
150
  },
72
151
  args: { files: { type: 'positional', description: 'Files to scrub', required: true } },
73
152
  async run({ args, rawArgs }) {
74
- const redactor = await redactorFor()
75
- 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)]
76
158
  if (files.length === 0) throw new TypeVaultError('invalid', `usage: typevault scrub <file>... (got ${args.files})`)
77
- 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
+ }
78
169
  },
79
170
  })
80
171
 
81
- 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
+ }
82
209
 
83
210
  export const request = defineCommand({
84
211
  meta: { name: 'request', description: 'Ask a human for a secret through a one-time web page (live grants)' },
85
212
  args: {
86
- name: { type: 'positional', required: true },
87
- type: { type: 'string', required: true, description: 'Entry type' },
88
- group: { type: 'string', description: "Group (defaults to your grant's group)" },
213
+ name: { type: 'positional', description: ENTRY_NAME_SYNTAX, required: true },
214
+ preset: { type: 'string', description: 'Optional field preset' },
215
+ tier: { type: 'string', description: "Tier (defaults to your grant's tier)" },
89
216
  reason: { type: 'string', required: true, description: 'Shown to the human' },
90
217
  },
91
218
  async run({ args }) {
@@ -94,54 +221,74 @@ export const request = defineCommand({
94
221
  throw new TypeVaultError('unavailable', 'request needs a live grant (the daemon hosts the page)')
95
222
  const body = {
96
223
  name: args.name,
97
- type: args.type,
224
+ preset: args.preset,
98
225
  reason: args.reason,
99
- ...(args.group === undefined ? {} : { group: args.group }),
226
+ ...(args.tier === undefined ? {} : { tier: args.tier }),
100
227
  }
101
228
  const opened = await resolved.access.call('/v1/request', body, RequestResponse)
102
229
  print(`Send this link to the human: ${opened.url}\nMatch code: ${opened.code} (post it in the chat too)`)
103
- const done = await resolved.access.call(
104
- '/v1/request/wait',
105
- { id: opened.id },
106
- z.object({ stored: z.string() }),
107
- 11 * 60_000,
108
- )
230
+ const done = await waitForRequest(resolved.access, opened)
109
231
  print(`stored as ${done.stored}`)
110
232
  },
111
233
  })
112
234
 
113
235
  const SOURCES = ['dotenv', 'typeclaw', '1password', 'bitwarden', 'lastpass', 'keepass', 'csv'] as const
114
236
  const isSource = (value: string): value is ImportSource => SOURCES.some((source) => source === value)
237
+ const isVia = (value: string): value is OnePasswordVia => ONEPASSWORD_VIAS.some((via) => via === value)
115
238
 
116
239
  export const importCommand = defineCommand({
117
- meta: { name: 'import', description: 'Import a password-manager export into a group (operator, one transaction)' },
240
+ meta: {
241
+ name: 'import',
242
+ description: 'Import a password-manager export, or 1Password directly, into a tier (owner, one transaction)',
243
+ },
118
244
  args: {
119
245
  source: { type: 'positional', required: true, description: SOURCES.join(' | ') },
120
- path: { type: 'positional', required: true },
121
- group: { type: 'string', required: true },
246
+ path: { type: 'positional', required: false, description: 'Export file (omit it to read 1Password directly)' },
247
+ tier: { type: 'string', required: true },
122
248
  'password-stdin': { type: 'boolean', description: 'Read the KeePass password from stdin' },
249
+ via: { type: 'string', description: `1Password without a path: ${ONEPASSWORD_VIAS.join(' | ')} (default sdk)` },
250
+ account: { type: 'string', description: '1Password account, repeatable (required with --via sdk)' },
251
+ vault: { type: 'string', description: '1Password vault, repeatable (default: every vault)' },
252
+ tag: { type: 'string', description: 'Only 1Password items with this tag, repeatable' },
123
253
  },
124
- async run({ args }) {
254
+ async run({ args, rawArgs }) {
125
255
  if (!isSource(args.source)) throw new TypeVaultError('invalid', `source must be one of: ${SOURCES.join(', ')}`)
256
+ const live = args.source === '1password' && args.path === undefined
257
+ if (!live && args.path === undefined) {
258
+ throw new TypeVaultError('invalid', 'usage: typevault import <source> <path> --tier <tier>')
259
+ }
260
+ if (!live && (args.via ?? args.account ?? args.vault ?? args.tag) !== undefined) {
261
+ throw new TypeVaultError('invalid', '--via, --account, --vault and --tag apply only to 1password without a path')
262
+ }
263
+ const via = args.via ?? 'sdk'
264
+ if (!isVia(via)) throw new TypeVaultError('invalid', `--via must be one of: ${ONEPASSWORD_VIAS.join(', ')}`)
126
265
  const vault = await openDirect(process.env)
127
266
  const password = args['password-stdin'] ? await readStdin() : undefined
128
- const result = await importFrom(args.source, { path: args.path, ...(password === undefined ? {} : { password }) })
129
- const group = args.group
267
+ const result =
268
+ args.path === undefined
269
+ ? await read1Password({
270
+ via,
271
+ accounts: repeated(rawArgs, '--account'),
272
+ vaults: repeated(rawArgs, '--vault'),
273
+ tags: repeated(rawArgs, '--tag'),
274
+ })
275
+ : await importFrom(args.source, { path: args.path, ...(password === undefined ? {} : { password }) })
276
+ const tier = args.tier
130
277
  const stored = await vault.putMany(
131
- result.entries.map((entry) => ({ ...entry, group })),
278
+ result.entries.map((entry) => ({ ...entry, tier })),
132
279
  async (target) => {
133
- const key = vault.keyring.operator ?? (await vault.keyring.unlock(target))
134
- if (key === undefined) throw new TypeVaultError('denied', `no key here can write group "${target}"`)
280
+ const key = vault.keyring.owner ?? (await vault.keyring.unlock(target))
281
+ if (key === undefined) throw new TypeVaultError('denied', `no key here can write tier "${target}"`)
135
282
  return signerOf(key)
136
283
  },
137
284
  )
138
285
  await appendAudit(vault.layout, {
139
286
  action: 'import',
140
287
  mode: 'direct',
141
- groups: [group],
288
+ tiers: [tier],
142
289
  entries: stored.map((e) => e.payload.name),
143
290
  })
144
291
  for (const warning of result.warnings) note(`warning: ${warning}`)
145
- note(`imported ${stored.length} entries into ${group}`)
292
+ note(`imported ${stored.length} entries into ${tier}`)
146
293
  },
147
294
  })