typevault 0.1.0 → 0.2.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 (72) 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 +7 -7
  7. package/src/access/scoped.ts +100 -44
  8. package/src/access/sealed-access.ts +45 -23
  9. package/src/access/sealed.ts +33 -21
  10. package/src/access/types.ts +25 -30
  11. package/src/admin.ts +68 -0
  12. package/src/audit/log.ts +14 -9
  13. package/src/cli/commands/admin.ts +87 -47
  14. package/src/cli/commands/daemon.ts +33 -15
  15. package/src/cli/commands/entries.ts +166 -55
  16. package/src/cli/commands/grant.ts +12 -20
  17. package/src/cli/commands/members.ts +281 -0
  18. package/src/cli/commands/run.ts +61 -24
  19. package/src/cli/context.ts +155 -15
  20. package/src/cli/index.ts +27 -4
  21. package/src/cli/password.ts +74 -0
  22. package/src/cli/web-prompt.ts +65 -0
  23. package/src/core/admin.ts +125 -74
  24. package/src/core/adopt.ts +40 -9
  25. package/src/core/crypto.ts +6 -4
  26. package/src/core/doctor.ts +9 -9
  27. package/src/core/entries.ts +66 -52
  28. package/src/core/errors.ts +6 -0
  29. package/src/core/fsx.ts +7 -3
  30. package/src/core/holder.ts +84 -0
  31. package/src/core/identity.ts +130 -0
  32. package/src/core/init.ts +73 -23
  33. package/src/core/keyring.ts +100 -56
  34. package/src/core/layout.ts +145 -26
  35. package/src/core/lock.ts +128 -16
  36. package/src/core/naming.ts +146 -49
  37. package/src/core/password.ts +111 -0
  38. package/src/core/payload.ts +42 -38
  39. package/src/core/revisions.ts +8 -4
  40. package/src/core/rotate.ts +59 -42
  41. package/src/core/state.ts +88 -48
  42. package/src/core/txn.ts +5 -4
  43. package/src/core/vault.ts +108 -46
  44. package/src/core/worktrees.ts +39 -0
  45. package/src/daemon/admin-routes.ts +33 -21
  46. package/src/daemon/agent-routes.ts +29 -11
  47. package/src/daemon/client.ts +15 -0
  48. package/src/daemon/daemon.ts +210 -32
  49. package/src/daemon/grants.ts +21 -4
  50. package/src/daemon/http.ts +3 -0
  51. package/src/daemon/live-access.ts +4 -4
  52. package/src/daemon/protocol.ts +17 -12
  53. package/src/daemon/requests.ts +17 -22
  54. package/src/daemon/spawn.ts +188 -9
  55. package/src/export/1password.ts +157 -0
  56. package/src/import/1password-live.ts +399 -0
  57. package/src/import/1password.ts +26 -5
  58. package/src/import/bitwarden.ts +3 -3
  59. package/src/import/csv.ts +1 -1
  60. package/src/import/dotenv.ts +2 -2
  61. package/src/import/index.ts +1 -0
  62. package/src/import/keepass.ts +2 -2
  63. package/src/import/lastpass.ts +2 -2
  64. package/src/import/shared.ts +67 -10
  65. package/src/import/typeclaw.ts +2 -2
  66. package/src/import/types.ts +1 -1
  67. package/src/index.ts +58 -0
  68. package/src/owner.ts +156 -0
  69. package/src/prompt/browser.ts +48 -15
  70. package/src/prompt/page.ts +19 -11
  71. package/src/prompt/styles.ts +64 -34
  72. package/src/prompt/types.ts +3 -3
@@ -1,14 +1,15 @@
1
1
  import { defineCommand } from 'citty'
2
2
  import { z } from 'zod'
3
3
 
4
- import { envEligible, envFor, explicitNames, secretValues } from '../../access/env'
4
+ import { envEligible, envFor, explicitNames, resolveEnvRefs, secretValues } from '../../access/env'
5
5
  import { appendAudit } from '../../audit/log'
6
6
  import { signerOf } from '../../core/entries'
7
7
  import { TypeVaultError } from '../../core/errors'
8
- import { importFrom, type ImportSource } from '../../import'
8
+ import { ENTRY_NAME_SYNTAX } from '../../core/naming'
9
+ import { importFrom, ONEPASSWORD_VIAS, type ImportSource, type OnePasswordVia, read1Password } from '../../import'
9
10
  import { createRedactor, type Redactor, scrubFile } from '../../redact'
10
11
  import { openDirect, resolveAccess } from '../context'
11
- import { csv, note, print, readStdin } from '../output'
12
+ import { csv, note, print, readStdin, repeated } from '../output'
12
13
 
13
14
  async function pump(stream: ReadableStream<Uint8Array>, redactor: Redactor, sink: NodeJS.WriteStream): Promise<void> {
14
15
  for await (const chunk of stream.pipeThrough(redactor.stream())) sink.write(chunk)
@@ -28,15 +29,26 @@ export const run = defineCommand({
28
29
  const access = (await resolveAccess(process.env)).access
29
30
  const only = csv(args.only)
30
31
  const values = await access.values(only, args.reason)
31
- const policy = { ownGroups: await access.ownGroups(), explicit: explicitNames(only) }
32
+ const policy = { ownTiers: await access.ownTiers(), explicit: explicitNames(only) }
32
33
  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
34
  // The child gets its secrets, never the key or grant that opens the vault.
37
35
  const inherited = Object.fromEntries(Object.entries(process.env).filter(([name]) => !name.startsWith('TYPEVAULT_')))
36
+ const refs = await resolveEnvRefs(inherited, (name) => access.get(name, args.reason), new Date())
37
+ const referenced = new Set(refs.values.map((value) => value.name))
38
+ const skipped = values
39
+ .filter((value) => !envEligible(value, policy) && !referenced.has(value.name))
40
+ .map((value) => value.name)
41
+ if (skipped.length > 0) note(`not loaded (from included tiers; name them in --only): ${skipped.join(', ')}`)
42
+ const clash = Object.keys(refs.env).find((name) => Object.hasOwn(env, name))
43
+ if (clash !== undefined)
44
+ throw new TypeVaultError('conflict', `${clash} is both a tv:// reference and an entry's variable`)
45
+ const redactor = createRedactor([
46
+ ...secretValues([...values, ...refs.values]),
47
+ ...Object.values(env),
48
+ ...Object.values(refs.env),
49
+ ])
38
50
  const child = Bun.spawn(command, {
39
- env: { ...inherited, ...env },
51
+ env: { ...inherited, ...env, ...refs.env },
40
52
  stdin: 'inherit',
41
53
  stdout: 'pipe',
42
54
  stderr: 'pipe',
@@ -83,9 +95,9 @@ const RequestResponse = z.object({ id: z.string(), url: z.string(), code: z.stri
83
95
  export const request = defineCommand({
84
96
  meta: { name: 'request', description: 'Ask a human for a secret through a one-time web page (live grants)' },
85
97
  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)" },
98
+ name: { type: 'positional', description: ENTRY_NAME_SYNTAX, required: true },
99
+ preset: { type: 'string', description: 'Optional field preset' },
100
+ tier: { type: 'string', description: "Tier (defaults to your grant's tier)" },
89
101
  reason: { type: 'string', required: true, description: 'Shown to the human' },
90
102
  },
91
103
  async run({ args }) {
@@ -94,9 +106,9 @@ export const request = defineCommand({
94
106
  throw new TypeVaultError('unavailable', 'request needs a live grant (the daemon hosts the page)')
95
107
  const body = {
96
108
  name: args.name,
97
- type: args.type,
109
+ preset: args.preset,
98
110
  reason: args.reason,
99
- ...(args.group === undefined ? {} : { group: args.group }),
111
+ ...(args.tier === undefined ? {} : { tier: args.tier }),
100
112
  }
101
113
  const opened = await resolved.access.call('/v1/request', body, RequestResponse)
102
114
  print(`Send this link to the human: ${opened.url}\nMatch code: ${opened.code} (post it in the chat too)`)
@@ -112,36 +124,61 @@ export const request = defineCommand({
112
124
 
113
125
  const SOURCES = ['dotenv', 'typeclaw', '1password', 'bitwarden', 'lastpass', 'keepass', 'csv'] as const
114
126
  const isSource = (value: string): value is ImportSource => SOURCES.some((source) => source === value)
127
+ const isVia = (value: string): value is OnePasswordVia => ONEPASSWORD_VIAS.some((via) => via === value)
115
128
 
116
129
  export const importCommand = defineCommand({
117
- meta: { name: 'import', description: 'Import a password-manager export into a group (operator, one transaction)' },
130
+ meta: {
131
+ name: 'import',
132
+ description: 'Import a password-manager export, or 1Password directly, into a tier (owner, one transaction)',
133
+ },
118
134
  args: {
119
135
  source: { type: 'positional', required: true, description: SOURCES.join(' | ') },
120
- path: { type: 'positional', required: true },
121
- group: { type: 'string', required: true },
136
+ path: { type: 'positional', required: false, description: 'Export file (omit it to read 1Password directly)' },
137
+ tier: { type: 'string', required: true },
122
138
  'password-stdin': { type: 'boolean', description: 'Read the KeePass password from stdin' },
139
+ via: { type: 'string', description: `1Password without a path: ${ONEPASSWORD_VIAS.join(' | ')} (default sdk)` },
140
+ account: { type: 'string', description: '1Password account, repeatable (required with --via sdk)' },
141
+ vault: { type: 'string', description: '1Password vault, repeatable (default: every vault)' },
142
+ tag: { type: 'string', description: 'Only 1Password items with this tag, repeatable' },
123
143
  },
124
- async run({ args }) {
144
+ async run({ args, rawArgs }) {
125
145
  if (!isSource(args.source)) throw new TypeVaultError('invalid', `source must be one of: ${SOURCES.join(', ')}`)
146
+ const live = args.source === '1password' && args.path === undefined
147
+ if (!live && args.path === undefined) {
148
+ throw new TypeVaultError('invalid', 'usage: typevault import <source> <path> --tier <tier>')
149
+ }
150
+ if (!live && (args.via ?? args.account ?? args.vault ?? args.tag) !== undefined) {
151
+ throw new TypeVaultError('invalid', '--via, --account, --vault and --tag apply only to 1password without a path')
152
+ }
153
+ const via = args.via ?? 'sdk'
154
+ if (!isVia(via)) throw new TypeVaultError('invalid', `--via must be one of: ${ONEPASSWORD_VIAS.join(', ')}`)
126
155
  const vault = await openDirect(process.env)
127
156
  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
157
+ const result =
158
+ args.path === undefined
159
+ ? await read1Password({
160
+ via,
161
+ accounts: repeated(rawArgs, '--account'),
162
+ vaults: repeated(rawArgs, '--vault'),
163
+ tags: repeated(rawArgs, '--tag'),
164
+ })
165
+ : await importFrom(args.source, { path: args.path, ...(password === undefined ? {} : { password }) })
166
+ const tier = args.tier
130
167
  const stored = await vault.putMany(
131
- result.entries.map((entry) => ({ ...entry, group })),
168
+ result.entries.map((entry) => ({ ...entry, tier })),
132
169
  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}"`)
170
+ const key = vault.keyring.owner ?? (await vault.keyring.unlock(target))
171
+ if (key === undefined) throw new TypeVaultError('denied', `no key here can write tier "${target}"`)
135
172
  return signerOf(key)
136
173
  },
137
174
  )
138
175
  await appendAudit(vault.layout, {
139
176
  action: 'import',
140
177
  mode: 'direct',
141
- groups: [group],
178
+ tiers: [tier],
142
179
  entries: stored.map((e) => e.payload.name),
143
180
  })
144
181
  for (const warning of result.warnings) note(`warning: ${warning}`)
145
- note(`imported ${stored.length} entries into ${group}`)
182
+ note(`imported ${stored.length} entries into ${tier}`)
146
183
  },
147
184
  })
@@ -1,30 +1,137 @@
1
+ import { existsSync, readFileSync } from 'node:fs'
2
+
1
3
  import { z } from 'zod'
2
4
 
3
- import { loadLocalKeys } from '../access/keys'
5
+ import { machineKeys } from '../access/keys'
4
6
  import { ScopedVault } from '../access/scoped'
5
7
  import { readSealedGrant } from '../access/sealed'
6
8
  import { SealedAccess } from '../access/sealed-access'
7
9
  import type { Access } from '../access/types'
8
10
  import { Admin } from '../core/admin'
11
+ import type { SecretKey } from '../core/crypto'
9
12
  import { TypeVaultError } from '../core/errors'
10
- import { type Layout, layoutOf, resolveRoot } from '../core/layout'
13
+ import { atomicWrite } from '../core/fsx'
14
+ import { type Identity, readIdentity, sealedCopyPath, unlockIdentity } from '../core/identity'
15
+ import { findLocalVault, globalLayout, type Layout, localLayout } from '../core/layout'
16
+ import { loadState } from '../core/state'
11
17
  import { Vault } from '../core/vault'
12
- import { callDaemon } from '../daemon/client'
18
+ import { worktreeVaults } from '../core/worktrees'
19
+ import { callDaemon, isDaemonAlive } from '../daemon/client'
13
20
  import { LiveAccess } from '../daemon/live-access'
14
- import { ensureDaemon } from '../daemon/spawn'
21
+ import { ensureDaemon, LOCKED_MESSAGE, startSession, stopDaemon } from '../daemon/spawn'
22
+ import { note } from './output'
23
+ import { type Passwords, passwords, passwordsFromStdin } from './password'
15
24
 
16
25
  export type Env = Readonly<Record<string, string | undefined>>
17
26
 
18
- export const layoutFrom = (env: Env): Layout => layoutOf(resolveRoot(env))
27
+ const isSet = (value: string | undefined): boolean => value !== undefined && value !== ''
28
+
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'])
19
31
 
20
- /** The vault opened with this machine's own keys: direct mode, for the operator and launchers. */
32
+ /** The selected vault, or undefined when no project vault is found from `cwd`. Never falls back to the global one. */
33
+ export function findLayout(env: Env, cwd: string = process.cwd()): Layout | undefined {
34
+ if (wantsGlobal(env)) return globalLayout(env)
35
+ const dir = findLocalVault(cwd, env)
36
+ return dir === undefined ? undefined : localLayout(dir, env)
37
+ }
38
+
39
+ export function layoutFrom(env: Env, cwd: string = process.cwd()): Layout {
40
+ const layout = findLayout(env, cwd)
41
+ if (layout === undefined) {
42
+ throw new TypeVaultError(
43
+ 'not_found',
44
+ 'no vault here (run `typevault init` to create one, or pass -g for the global vault)',
45
+ )
46
+ }
47
+ return layout
48
+ }
49
+
50
+ /**
51
+ * The vault opened with this member's own key: direct mode, for owners and issuers. A machine member's key is at
52
+ * hand; a human types their password, since only the daemon keeps an unlocked key around.
53
+ */
21
54
  export async function openDirect(env: Env): Promise<Vault> {
22
55
  const layout = layoutFrom(env)
23
- const keys = loadLocalKeys(layout, env)
24
- if (keys.length === 0) throw new TypeVaultError('denied', 'no grant and no key here (set TYPEVAULT_GRANT)')
25
- return Vault.open(layout.root, keys, env)
56
+ const machine = machineKeys(env)
57
+ const identity = readIdentity(env)
58
+ if (machine.length === 0 && identity === undefined) {
59
+ throw new TypeVaultError('denied', 'no grant and no identity here (set TYPEVAULT_GRANT, or run typevault join)')
60
+ }
61
+ const keys = machine.length > 0 ? machine : [await unlockHuman(identity, passwords())]
62
+ return Vault.open(layout, keys, env)
26
63
  }
27
64
 
65
+ async function unlockHuman(identity: Identity | undefined, passwords: Passwords): Promise<SecretKey> {
66
+ if (identity === undefined) throw new TypeVaultError('not_found', 'no identity here (run typevault init or join)')
67
+ if (identity.kind === 'machine') return unlockIdentity(identity)
68
+ return unlockIdentity(identity, await passwords.ask(`Password for ${identity.name}: `))
69
+ }
70
+
71
+ /**
72
+ * Unlocks a human member's session: their key goes to a daemon that holds it for `ttlMs`, and this user's CLI
73
+ * reads through the session grant it writes. Returns false when a session already runs.
74
+ */
75
+ export async function unlockSession(env: Env, passwords: Passwords, ttlMs: number): Promise<boolean> {
76
+ const layout = layoutFrom(env)
77
+ if (await hasSession(layout)) return false
78
+ const identity = readIdentity(env)
79
+ const key = await unlockHuman(identity, passwords)
80
+ const vault = await Vault.open(layout, [key], env)
81
+ if (vault.member === undefined) {
82
+ throw new TypeVaultError(
83
+ 'denied',
84
+ `${identity?.name ?? 'you'} is not a member of this vault (share \`typevault identity show\` with an owner)`,
85
+ )
86
+ }
87
+ if (identity?.kind === 'human') refreshSealedCopy(vault, identity)
88
+ // A daemon without a session (a machine member's, or one left from before the vault was re-created) holds no key
89
+ // of this person's, so it can't serve them: the session replaces it.
90
+ if (await isDaemonAlive(layout.agentSocket)) {
91
+ await stopDaemon(layout)
92
+ note('replaced a running daemon that held no unlocked session')
93
+ }
94
+ await startSession(layout, env, key, ttlMs)
95
+ return true
96
+ }
97
+
98
+ const hasSession = async (layout: Layout): Promise<boolean> =>
99
+ existsSync(layout.sessionFile) && (await isDaemonAlive(layout.agentSocket))
100
+
101
+ /** This vault in the repository's other worktrees, where a session is unlocked: one unlock serves them all. */
102
+ export async function worktreeSessions(layout: Layout, env: Env): Promise<readonly Layout[]> {
103
+ if (layout.scope !== 'local') return []
104
+ const sessions: Layout[] = []
105
+ for (const vault of await worktreeVaults(layout.vault)) {
106
+ const worktree = localLayout(vault, env)
107
+ if (await hasSession(worktree)) sessions.push(worktree)
108
+ }
109
+ return sessions
110
+ }
111
+
112
+ /** Starts here the session unlocked in another worktree, if any; that worktree's daemon checks this is one. */
113
+ async function shareWorktreeSession(layout: Layout, env: Env): Promise<boolean> {
114
+ const [unlocked] = await worktreeSessions(layout, env)
115
+ if (unlocked === undefined) return false
116
+ 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
+ return true
121
+ }
122
+
123
+ /** After `passwd`, the copy committed in this vault still opens with the old password until it is replaced. */
124
+ function refreshSealedCopy(vault: Vault, identity: Identity & { readonly kind: 'human' }): void {
125
+ const copy = sealedCopyPath(vault.layout, identity.name)
126
+ if (existsSync(copy) && readFileSync(copy, 'utf8') !== identity.sealedKey) {
127
+ atomicWrite(copy, identity.sealedKey)
128
+ note(`updated ${copy} to your current password; commit it`)
129
+ }
130
+ }
131
+
132
+ /** The vault's public, owner-signed state, readable without any key. */
133
+ export const openPublic = (env: Env): Promise<Vault> => Vault.open(layoutFrom(env), [], env)
134
+
28
135
  export const openAdmin = async (env: Env): Promise<Admin> => new Admin(await openDirect(env))
29
136
 
30
137
  export type ResolvedAccess =
@@ -34,25 +141,58 @@ export type ResolvedAccess =
34
141
 
35
142
  /** `TYPEVAULT_GRANT` decides: `tvl1.` live via the daemon, `tvg1:`/`@path` sealed, unset = direct mode. */
36
143
  export async function resolveAccess(env: Env): Promise<ResolvedAccess> {
37
- const layout = layoutFrom(env)
38
144
  const grant = env['TYPEVAULT_GRANT']?.trim()
39
145
  if (grant === undefined || grant === '') {
40
- const group = env['TYPEVAULT_GROUP']
41
- const vault = await openDirect(env)
42
- const ownGroups = vault.keys.flatMap((key) => (key.role.kind === 'group' ? [key.role.group] : []))
43
- const identity = { mode: 'direct' as const, ownGroups, ...(group === undefined ? {} : { defaultGroup: group }) }
146
+ const machine = machineKeys(env)
147
+ if (machine.length === 0) return { kind: 'live', access: await sessionAccess(env) }
148
+ const tier = env['TYPEVAULT_TIER']
149
+ const vault = await Vault.open(layoutFrom(env), machine, env)
150
+ const ownTiers = vault.member === undefined ? [] : (vault.state.members[vault.member]?.tiers ?? [])
151
+ const identity = { mode: 'direct' as const, ownTiers, ...(tier === undefined ? {} : { defaultTier: tier }) }
44
152
  return { kind: 'direct', access: new ScopedVault(vault, [], identity) }
45
153
  }
46
154
  if (grant.startsWith('tvl1.')) {
155
+ const layout = layoutFrom(env)
156
+ checkOwnerPin(layout, env)
47
157
  await ensureDaemon(layout, env)
48
158
  return { kind: 'live', access: new LiveAccess(layout.agentSocket, grant) }
49
159
  }
50
160
  if (grant.startsWith('tvg1:') || grant.startsWith('@')) {
51
- return { kind: 'sealed', access: new SealedAccess(await readSealedGrant(grant), layout.root, env) }
161
+ return { kind: 'sealed', access: new SealedAccess(await readSealedGrant(grant), findLayout(env), env) }
52
162
  }
53
163
  throw new TypeVaultError('invalid', 'TYPEVAULT_GRANT is not a typevault grant')
54
164
  }
55
165
 
166
+ /**
167
+ * A human member's CLI reads through the unlocked session's grant. On a terminal a locked vault asks for the
168
+ * password right away; anywhere else (an agent) it stays locked until a human unlocks it.
169
+ */
170
+ async function sessionAccess(env: Env): Promise<LiveAccess> {
171
+ const layout = layoutFrom(env)
172
+ checkOwnerPin(layout, env)
173
+ if (!(await hasSession(layout)) && !(await shareWorktreeSession(layout, env))) {
174
+ const identity = readIdentity(env)
175
+ if (identity === undefined) {
176
+ throw new TypeVaultError('denied', 'no grant and no identity here (set TYPEVAULT_GRANT, or run typevault join)')
177
+ }
178
+ const canAsk = process.stdin.isTTY || passwordsFromStdin()
179
+ if (identity.kind !== 'human' || !canAsk) throw new TypeVaultError('locked', LOCKED_MESSAGE)
180
+ await unlockSession(env, passwords(), DEFAULT_SESSION_MS)
181
+ }
182
+ return new LiveAccess(layout.agentSocket, readFileSync(layout.sessionFile, 'utf8').trim())
183
+ }
184
+
185
+ /**
186
+ * A live connection reads through a daemon that may have trusted the owner without this process's pin, so a set
187
+ * `TYPEVAULT_OWNER` is checked against the vault here, before anything is read through it.
188
+ */
189
+ function checkOwnerPin(layout: Layout, env: Env): void {
190
+ if (isSet(env['TYPEVAULT_OWNER'])) loadState(layout, env)
191
+ }
192
+
193
+ /** How long an unlocked session lasts unless `unlock --for` says otherwise. */
194
+ export const DEFAULT_SESSION_MS = 8 * 60 * 60_000
195
+
56
196
  export const accessOf = async (env: Env): Promise<Access> => (await resolveAccess(env)).access
57
197
 
58
198
  /** A call on this process's admin socket (`TYPEVAULT_CEILING`, default `default`), starting the daemon if needed. */
package/src/cli/index.ts CHANGED
@@ -2,17 +2,32 @@
2
2
  import { defineCommand, runCommand, runMain } from 'citty'
3
3
 
4
4
  import { TypeVaultError } from '../core/errors'
5
- import { ceiling, doctor, group, init, key, signer } from './commands/admin'
5
+ import { ceiling, doctor, tier, init, key, signer } from './commands/admin'
6
6
  import { daemon } from './commands/daemon'
7
7
  import { get, ls, mv, otp, rm, set, whoami } from './commands/entries'
8
8
  import { audit, grant } from './commands/grant'
9
+ import { identity, joinCommand, lock, member, passwd, unlock } from './commands/members'
9
10
  import { importCommand, redact, request, run, scrub } from './commands/run'
11
+ import { readPasswordsFromStdin } from './password'
10
12
 
11
13
  const main = defineCommand({
12
14
  meta: { name: 'typevault', description: 'A CLI-first secrets vault for agents' },
15
+ args: {
16
+ global: { type: 'boolean', alias: 'g', description: 'Use the global vault instead of the project vault' },
17
+ 'vault-password-stdin': {
18
+ type: 'boolean',
19
+ description: 'Read your TypeVault password(s) from stdin, one per line (for scripts)',
20
+ },
21
+ },
13
22
  subCommands: {
14
23
  init,
15
- group,
24
+ join: joinCommand,
25
+ member,
26
+ identity,
27
+ unlock,
28
+ lock,
29
+ passwd,
30
+ tier,
16
31
  ceiling,
17
32
  signer,
18
33
  key,
@@ -35,8 +50,16 @@ const main = defineCommand({
35
50
  },
36
51
  })
37
52
 
38
- const rawArgs = process.argv.slice(2)
39
- const ownArgs = rawArgs.includes('--') ? rawArgs.slice(0, rawArgs.indexOf('--')) : rawArgs
53
+ const argv = process.argv.slice(2)
54
+ const split = argv.includes('--') ? argv.indexOf('--') : argv.length
55
+ const isGlobalFlag = (arg: string): boolean => arg === '-g' || arg === '--global'
56
+ const PASSWORD_STDIN = '--vault-password-stdin'
57
+ // -g and --vault-password-stdin apply to every command, so they are taken out here; anything after `--` belongs to
58
+ // the child of `run`.
59
+ if (argv.slice(0, split).some(isGlobalFlag)) process.env['TYPEVAULT_GLOBAL'] = '1'
60
+ if (argv.slice(0, split).includes(PASSWORD_STDIN)) readPasswordsFromStdin()
61
+ const ownArgs = argv.slice(0, split).filter((arg) => !isGlobalFlag(arg) && arg !== PASSWORD_STDIN)
62
+ const rawArgs = [...ownArgs, ...argv.slice(split)]
40
63
  const wantsUsage = ownArgs.length === 0 || ownArgs.some((arg) => arg === '--help' || arg === '-h')
41
64
 
42
65
  if (wantsUsage) {
@@ -0,0 +1,74 @@
1
+ import { TypeVaultError } from '../core/errors'
2
+
3
+ export type Passwords = { readonly ask: (question: string) => Promise<string> }
4
+
5
+ let fromStdin = false
6
+ let stdinLines: Promise<string[]> | undefined
7
+ let nextLine = 0
8
+
9
+ /** Set by the global `--vault-password-stdin` flag: passwords are read from stdin, one per line, instead of a terminal. */
10
+ export function readPasswordsFromStdin(): void {
11
+ fromStdin = true
12
+ }
13
+
14
+ export const passwordsFromStdin = (): boolean => fromStdin
15
+
16
+ export function passwords(): Passwords {
17
+ if (!fromStdin) return { ask: promptHidden }
18
+ return {
19
+ ask: async () => {
20
+ stdinLines ??= Bun.stdin.text().then((text) => text.split(/\r?\n/))
21
+ const line = (await stdinLines)[nextLine++]
22
+ if (line === undefined || line === '')
23
+ throw new TypeVaultError('invalid', '--vault-password-stdin needs one password per line')
24
+ return line
25
+ },
26
+ }
27
+ }
28
+
29
+ /** A new password: asked twice on a terminal so a typo can't lock the owner out. */
30
+ export async function newPassword(source: Passwords): Promise<string> {
31
+ const password = await source.ask('New password: ')
32
+ if (!fromStdin && (await source.ask('Repeat it: ')) !== password) {
33
+ throw new TypeVaultError('invalid', 'the passwords do not match')
34
+ }
35
+ return password
36
+ }
37
+
38
+ async function promptHidden(question: string): Promise<string> {
39
+ const { stdin, stderr } = process
40
+ if (!stdin.isTTY) {
41
+ throw new TypeVaultError(
42
+ 'locked',
43
+ 'no terminal to ask for your TypeVault password (pass --vault-password-stdin to pipe it)',
44
+ )
45
+ }
46
+ stderr.write(question)
47
+ stdin.setRawMode(true)
48
+ stdin.resume()
49
+ const { promise, resolve, reject } = Promise.withResolvers<string>()
50
+ let typed = ''
51
+ const finish = (): void => {
52
+ stdin.off('data', onData)
53
+ stdin.setRawMode(false)
54
+ stdin.pause()
55
+ stderr.write('\n')
56
+ }
57
+ const onData = (chunk: Buffer): void => {
58
+ for (const char of chunk.toString('utf8')) {
59
+ if (char === '\r' || char === '\n') {
60
+ finish()
61
+ resolve(typed)
62
+ return
63
+ }
64
+ if (char === '\u0003') {
65
+ finish()
66
+ reject(new TypeVaultError('invalid', 'cancelled'))
67
+ return
68
+ }
69
+ typed = char === '\u007f' || char === '\b' ? [...typed].slice(0, -1).join('') : typed + char
70
+ }
71
+ }
72
+ stdin.on('data', onData)
73
+ return promise
74
+ }
@@ -0,0 +1,65 @@
1
+ import { generateX25519Identity, identityToRecipient } from 'age-encryption'
2
+
3
+ import { unseal } from '../core/crypto'
4
+ import { TypeVaultError } from '../core/errors'
5
+ import type { EntryName, Field, Preset } from '../core/naming'
6
+ import { decodePayload } from '../core/payload'
7
+ import { matchCode } from '../daemon/requests'
8
+ import { startPromptServer } from '../prompt'
9
+
10
+ const TTL_MS = 10 * 60_000
11
+
12
+ export type WebEntry = {
13
+ readonly name: EntryName
14
+ readonly preset?: Preset | undefined
15
+ readonly tier: string | undefined
16
+ }
17
+
18
+ /**
19
+ * Collects an entry's fields on the local one-time page. The page encrypts to a throwaway key held only by this
20
+ * process, which then stores the fields like `--stdin` would, so it works whatever access the caller has.
21
+ */
22
+ export async function promptFields(
23
+ entry: WebEntry,
24
+ show: (url: string, code: string) => void,
25
+ ): Promise<Record<string, Field>> {
26
+ const identity = await generateX25519Identity()
27
+ const server = await startPromptServer()
28
+ try {
29
+ 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
+ })
40
+ 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')
44
+ }
45
+ return { ...payload.fields }
46
+ } finally {
47
+ await server.stop()
48
+ }
49
+ }
50
+
51
+ export function openBrowser(url: string): boolean {
52
+ const command =
53
+ process.platform === 'darwin'
54
+ ? ['open', url]
55
+ : process.platform === 'win32'
56
+ ? ['cmd', '/c', 'start', '', url]
57
+ : ['xdg-open', url]
58
+ try {
59
+ Bun.spawn(command, { stdio: ['ignore', 'ignore', 'ignore'] }).unref()
60
+ return true
61
+ } catch (error) {
62
+ if (error instanceof Error) return false
63
+ throw error
64
+ }
65
+ }