typevault 0.7.0 → 0.8.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "typevault",
3
- "version": "0.7.0",
3
+ "version": "0.8.0",
4
4
  "description": "CLI-first secrets vault for agents",
5
5
  "homepage": "https://github.com/typeclaw/typevault#readme",
6
6
  "bugs": {
package/src/access/env.ts CHANGED
@@ -101,6 +101,7 @@ function readField(field: Field, now: Date): string {
101
101
  case 'secret':
102
102
  case 'text':
103
103
  case 'oauth':
104
+ case 'passkey':
104
105
  return fieldValue(field)
105
106
  default:
106
107
  return assertNever(field)
@@ -39,7 +39,7 @@ const valueOf = (entry: StoredEntry): EntryValue =>
39
39
  */
40
40
  export class ScopedVault implements Access {
41
41
  readonly #vault: Vault
42
- readonly #chain: ScopeChain
42
+ #chain: ScopeChain
43
43
  readonly #identity: ScopedIdentity
44
44
  readonly #handedOut = new Set<string>()
45
45
 
@@ -63,6 +63,11 @@ export class ScopedVault implements Access {
63
63
  )
64
64
  }
65
65
 
66
+ /** A new scope for the same grant; the values handed out so far stay remembered for redaction. */
67
+ rescope(chain: ScopeChain): void {
68
+ this.#chain = chain
69
+ }
70
+
66
71
  #allows(entry: StoredEntry): boolean {
67
72
  return allowsEntry(this.#chain, this.#vault.state, entry.envelope.tier, entry.payload.name)
68
73
  }
@@ -114,6 +119,7 @@ export class ScopedVault implements Access {
114
119
  case 'secret':
115
120
  case 'text':
116
121
  case 'totp':
122
+ case 'passkey':
117
123
  break
118
124
  default:
119
125
  throw new TypeVaultError('invalid', `unexpected field ${JSON.stringify(field satisfies never)}`)
@@ -14,7 +14,7 @@ import { parseEntryName } from '../../core/naming'
14
14
  import { Vault } from '../../core/vault'
15
15
  import { GrantStore } from '../../daemon/grants'
16
16
  import { stopDaemon } from '../../daemon/spawn'
17
- import { layoutFrom, openAdmin, openDirect, openPublic, wantsGlobal } from '../context'
17
+ import { layoutFrom, openDirect, openPublic, runAdmin, wantsGlobal } from '../context'
18
18
  import { csv, note, print, table } from '../output'
19
19
  import { ensureIdentity, identityArgs } from './members'
20
20
 
@@ -74,23 +74,29 @@ export const tier = defineCommand({
74
74
  add: defineCommand({
75
75
  meta: { name: 'add' },
76
76
  args: named,
77
- run: async ({ args }) => (await openAdmin(process.env)).addTier(args.name),
77
+ run: async ({ args }) => void (await runAdmin(process.env, { op: 'tier.add', name: args.name })),
78
78
  }),
79
79
  rm: defineCommand({
80
80
  meta: { name: 'rm' },
81
81
  args: named,
82
- run: async ({ args }) => (await openAdmin(process.env)).removeTier(args.name),
82
+ run: async ({ args }) => void (await runAdmin(process.env, { op: 'tier.rm', name: args.name })),
83
83
  }),
84
84
  include: defineCommand({
85
85
  meta: { name: 'include', description: '<tier> reaches everything <included> reaches' },
86
86
  args: pair,
87
- run: async ({ args }) => (await openAdmin(process.env)).include(args.tier, args.included),
87
+ run: async ({ args }) =>
88
+ void (await runAdmin(process.env, { op: 'tier.include', tier: args.tier, included: args.included })),
88
89
  }),
89
90
  exclude: defineCommand({
90
91
  meta: { name: 'exclude', description: 'Drop an include and rotate the included tier' },
91
92
  args: pair,
92
93
  async run({ args }) {
93
- printRotation(args.included, await (await openAdmin(process.env)).exclude(args.tier, args.included))
94
+ const { affected } = await runAdmin(process.env, {
95
+ op: 'tier.exclude',
96
+ tier: args.tier,
97
+ included: args.included,
98
+ })
99
+ printRotation(args.included, affected)
94
100
  },
95
101
  }),
96
102
  },
@@ -121,7 +127,7 @@ export const key = defineCommand({
121
127
  },
122
128
  args: named,
123
129
  async run({ args }) {
124
- printRotation(args.name, await (await openAdmin(process.env)).rotate(args.name))
130
+ printRotation(args.name, (await runAdmin(process.env, { op: 'key.rotate', name: args.name })).affected)
125
131
  },
126
132
  }),
127
133
  },
@@ -140,12 +146,13 @@ export const ceiling = defineCommand({
140
146
  set: defineCommand({
141
147
  meta: { name: 'set' },
142
148
  args: { name: { type: 'positional', required: true }, tier: { type: 'positional', required: true } },
143
- run: async ({ args }) => (await openAdmin(process.env)).setCeiling(args.name, args.tier),
149
+ run: async ({ args }) =>
150
+ void (await runAdmin(process.env, { op: 'ceiling.set', name: args.name, tier: args.tier })),
144
151
  }),
145
152
  rm: defineCommand({
146
153
  meta: { name: 'rm' },
147
154
  args: named,
148
- run: async ({ args }) => (await openAdmin(process.env)).removeCeiling(args.name),
155
+ run: async ({ args }) => void (await runAdmin(process.env, { op: 'ceiling.rm', name: args.name })),
149
156
  }),
150
157
  },
151
158
  })
@@ -169,12 +176,18 @@ export const signer = defineCommand({
169
176
  publicKey: { type: 'positional', required: true, description: 'Base64 Ed25519 public key' },
170
177
  tiers: { type: 'string', required: true, description: 'Comma-separated tiers, or *' },
171
178
  },
172
- run: async ({ args }) => (await openAdmin(process.env)).setSigner(args.id, args.publicKey, csv(args.tiers)),
179
+ run: async ({ args }) =>
180
+ void (await runAdmin(process.env, {
181
+ op: 'signer.add',
182
+ id: args.id,
183
+ publicKey: args.publicKey,
184
+ tiers: csv(args.tiers),
185
+ })),
173
186
  }),
174
187
  rm: defineCommand({
175
188
  meta: { name: 'rm' },
176
189
  args: named,
177
- run: async ({ args }) => (await openAdmin(process.env)).removeSigner(args.name),
190
+ run: async ({ args }) => void (await runAdmin(process.env, { op: 'signer.rm', name: args.name })),
178
191
  }),
179
192
  },
180
193
  })
@@ -188,14 +188,21 @@ export const set = defineCommand({
188
188
  }
189
189
  const type = suggested[field] ?? previous[field]?.type ?? 'secret'
190
190
  switch (type) {
191
- case 'oauth': {
191
+ case 'oauth':
192
+ case 'passkey': {
193
+ const label = type === 'oauth' ? 'OAuth' : 'Passkey'
192
194
  if (!args.stdin || args['stdin-json'])
193
- throw new TypeVaultError('invalid', 'OAuth values need --stdin-json with a typed oauth field object')
195
+ throw new TypeVaultError('invalid', `${label} values need --stdin-json with a typed ${type} field object`)
194
196
  try {
195
197
  typed[field] = FieldSchema.parse({ type, value: JSON.parse(value) })
196
198
  } catch (error) {
197
199
  if (error instanceof SyntaxError || error instanceof z.ZodError)
198
- throw new TypeVaultError('invalid', 'OAuth stdin needs a JSON object with an access_token')
200
+ throw new TypeVaultError(
201
+ 'invalid',
202
+ type === 'oauth'
203
+ ? 'OAuth stdin needs a JSON object with an access_token'
204
+ : 'Passkey stdin needs a JSON object with rp_id, credential_id, private_key (base64url) and discoverable, plus user_handle when discoverable is true',
205
+ )
199
206
  throw error
200
207
  }
201
208
  break
@@ -258,10 +265,10 @@ function checkPrompt(
258
265
  if (args.stdin || args['stdin-json'] || args.web)
259
266
  throw new TypeVaultError('invalid', '--prompt cannot be combined with --stdin, --stdin-json or --web')
260
267
  // Enter ends the prompt, so a pasted multi-line key would be cut at its first line.
261
- if (type === 'oauth' || target === PRESETS.ssh.input)
268
+ if (type === 'oauth' || type === 'passkey' || target === PRESETS.ssh.input)
262
269
  throw new TypeVaultError(
263
270
  'invalid',
264
- `pass ${type === 'oauth' ? 'OAuth JSON' : 'an SSH key'} with --stdin, not --prompt`,
271
+ `pass ${type === 'oauth' ? 'OAuth JSON' : type === 'passkey' ? 'passkey JSON' : 'an SSH key'} with --stdin, not --prompt`,
265
272
  )
266
273
  if (!process.stdin.isTTY)
267
274
  throw new TypeVaultError('invalid', '--prompt needs a terminal; pipe the secret with --stdin')
@@ -4,7 +4,6 @@ import { userInfo } from 'node:os'
4
4
  import { defineCommand } from 'citty'
5
5
 
6
6
  import { parseTtl } from '../../access/scope'
7
- import { Admin } from '../../core/admin'
8
7
  import { publicKeyOf } from '../../core/crypto'
9
8
  import { TypeVaultError } from '../../core/errors'
10
9
  import { atomicWrite } from '../../core/fsx'
@@ -32,9 +31,8 @@ import {
32
31
  DEFAULT_SESSION_MS,
33
32
  findLayout,
34
33
  layoutFrom,
35
- openAdmin,
36
- openDirect,
37
34
  openPublic,
35
+ runAdmin,
38
36
  unlockSession,
39
37
  worktreeSessions,
40
38
  type Env,
@@ -130,7 +128,13 @@ export const member = defineCommand({
130
128
  if (tiers.length === 0 && args.owner !== true)
131
129
  throw new TypeVaultError('invalid', 'member add needs --tier or --owner')
132
130
  const pub = decodeMemberPublic(args.publicKey)
133
- await (await openAdmin(process.env)).addMember(args.name, { ...pub, owner: args.owner === true, tiers })
131
+ await runAdmin(process.env, {
132
+ op: 'member.add',
133
+ name: args.name,
134
+ publicKey: args.publicKey,
135
+ owner: args.owner === true,
136
+ tiers,
137
+ })
134
138
  print(`added ${pub.kind} member ${args.name}${tiers.length === 0 ? '' : ` (rotated ${tiers.join(', ')})`}`)
135
139
  note('commit the vault so they can pull it')
136
140
  },
@@ -139,14 +143,10 @@ export const member = defineCommand({
139
143
  meta: { name: 'rm', description: 'Remove a member and rotate every tier they reached' },
140
144
  args: { name: { type: 'positional', required: true } },
141
145
  async run({ args }) {
142
- const vault = await openDirect(process.env)
143
- const previous = vault.state.owner.signPublic
144
- const before = Object.keys(vault.state.members)
145
- const affected = await new Admin(vault).removeMember(args.name)
146
- const removed = before.filter((name) => vault.state.members[name] === undefined)
146
+ const { affected, removed, ownerRotated } = await runAdmin(process.env, { op: 'member.rm', name: args.name })
147
147
  print(`removed ${removed.join(', ')}`)
148
148
  if (removed.length > 1) note(`${removed.join(', ')} shared one key, so all of them were removed.`)
149
- if (vault.state.owner.signPublic !== previous) {
149
+ if (ownerRotated) {
150
150
  note(
151
151
  'Owner key rotated. Commit the vault; members must pull it. For an open session, run typevault lock then typevault unlock.',
152
152
  )
@@ -247,7 +247,7 @@ export const unlock = defineCommand({
247
247
  const env = process.env
248
248
  const ttlMs = args.for === undefined ? DEFAULT_SESSION_MS : parseTtl(args.for)
249
249
  if (ttlMs > MAX_TIMER_MS) throw new TypeVaultError('invalid', '--for is too long (at most 24 days)')
250
- const started = await unlockSession(env, passwords(), ttlMs)
250
+ const started = (await unlockSession(env, passwords(), ttlMs)) !== undefined
251
251
  const id = vaultIdOf((await openPublic(env)).state.owner.signPublic)
252
252
  print(started ? `unlocked vault ${id} for ${args.for}` : `vault ${id} is already unlocked`)
253
253
  },
@@ -7,8 +7,8 @@ import { ScopedVault } from '../access/scoped'
7
7
  import { readSealedGrant } from '../access/sealed'
8
8
  import { SealedAccess } from '../access/sealed-access'
9
9
  import type { Access, EntryValue } from '../access/types'
10
- import { Admin } from '../core/admin'
11
- import type { SecretKey } from '../core/crypto'
10
+ import { type AdminOp, type AdminResult, runAdminOp } from '../core/admin'
11
+ import { randomToken, type SecretKey, sign } from '../core/crypto'
12
12
  import { TypeVaultError } from '../core/errors'
13
13
  import { atomicWrite } from '../core/fsx'
14
14
  import {
@@ -26,9 +26,13 @@ import { readSnapshot, Vault } from '../core/vault'
26
26
  import { worktreeVaults } from '../core/worktrees'
27
27
  import { callDaemon, isDaemonAlive } from '../daemon/client'
28
28
  import { LiveAccess } from '../daemon/live-access'
29
+ import { ownerWindowMessage } from '../daemon/owner-window'
30
+ import { ChallengeSchema } from '../daemon/protocol'
29
31
  import { ensureDaemon, LOCKED_MESSAGE, startSession, stopDaemon } from '../daemon/spawn'
30
32
  import { note } from './output'
33
+ import { ownerChange } from './owner-change'
31
34
  import { type Passwords, passwords, passwordsFromStdin } from './password'
35
+ import { promptHeader, touchIdReason, UNLOCK, unlockRequest } from './requester'
32
36
 
33
37
  export type Env = Readonly<Record<string, string | undefined>>
34
38
 
@@ -62,33 +66,41 @@ export function layoutFrom(env: Env, cwd: string = process.cwd()): Layout {
62
66
  * The vault opened with this member's own key: direct mode, for owners and issuers. A machine member's key is at
63
67
  * hand; a human types their password, since only the daemon keeps an unlocked key around.
64
68
  */
65
- export async function openDirect(env: Env): Promise<Vault> {
69
+ export async function openDirect(env: Env, purpose = UNLOCK): Promise<Vault> {
66
70
  const layout = layoutFrom(env)
67
71
  const machine = machineKeys(env)
68
72
  const identity = readIdentity(env)
69
73
  if (machine.length === 0 && identity === undefined) {
70
74
  throw new TypeVaultError('denied', 'no grant and no identity here (set TYPEVAULT_GRANT, or run typevault join)')
71
75
  }
72
- const keys = machine.length > 0 ? machine : [await unlockHuman(env, identity, passwords())]
76
+ const keys = machine.length > 0 ? machine : [await unlockHuman(env, identity, passwords(), purpose)]
73
77
  return Vault.open(layout, keys, env)
74
78
  }
75
79
 
76
80
  /**
77
81
  * A person's member key: through Touch ID when they turned it on and are at this Mac's terminal, else (or when Touch
78
82
  * ID fails) their password. Without a terminal it stays the password's error, so an agent can't raise the dialog.
79
- * At a Mac with Touch ID that they haven't turned on, the password prompt suggests it.
83
+ * At a Mac with Touch ID that they haven't turned on, the password prompt suggests it. Both say who asks and why, so a
84
+ * person running several agents knows which one wants `purpose`.
80
85
  */
81
- export async function unlockHuman(env: Env, identity: Identity | undefined, passwords: Passwords): Promise<SecretKey> {
86
+ export async function unlockHuman(
87
+ env: Env,
88
+ identity: Identity | undefined,
89
+ passwords: Passwords,
90
+ purpose = UNLOCK,
91
+ ): Promise<SecretKey> {
82
92
  if (identity === undefined) throw new TypeVaultError('not_found', 'no identity here (run typevault init or join)')
83
93
  if (identity.kind === 'machine') return unlockIdentity(identity)
84
- const atThisMac = process.platform === 'darwin' && process.stdin.isTTY === true && !passwordsFromStdin()
94
+ const atTerminal = process.stdin.isTTY === true && !passwordsFromStdin()
95
+ const request = atTerminal ? await unlockRequest(purpose, findLayout(env)) : undefined
96
+ const atThisMac = process.platform === 'darwin' && request !== undefined
85
97
  if (identity.touchId === undefined) {
86
98
  // The tip is optional: a probe that fails must not stand between the person and their password prompt.
87
99
  const tip = atThisMac && (await touchIdAvailable().catch(() => false))
88
100
  if (tip) note('tip: skip the password next time with `typevault touch-id enable`')
89
101
  } else if (atThisMac) {
90
102
  try {
91
- return await unlockIdentityWithTouchId(env, identity, identity.touchId)
103
+ return await unlockIdentityWithTouchId(env, identity, identity.touchId, touchIdReason(request))
92
104
  } catch (error) {
93
105
  if (!(error instanceof TypeVaultError)) throw error
94
106
  note(`${error.message}; asking for your password instead`)
@@ -97,18 +109,24 @@ export async function unlockHuman(env: Env, identity: Identity | undefined, pass
97
109
  }
98
110
  }
99
111
  }
112
+ if (request !== undefined) note(promptHeader(request))
100
113
  return unlockIdentity(identity, await passwords.ask(`Password for ${identity.name}: `))
101
114
  }
102
115
 
103
116
  /**
104
117
  * Unlocks a human member's session: their key goes to a daemon that holds it for `ttlMs`, and this user's CLI
105
- * reads through the session grant it writes. Returns false when a session already runs.
118
+ * reads through the session grant it writes. Returns the key it unlocked with, or undefined when a session already runs.
106
119
  */
107
- export async function unlockSession(env: Env, passwords: Passwords, ttlMs: number): Promise<boolean> {
120
+ export async function unlockSession(
121
+ env: Env,
122
+ passwords: Passwords,
123
+ ttlMs: number,
124
+ purpose = UNLOCK,
125
+ ): Promise<SecretKey | undefined> {
108
126
  const layout = layoutFrom(env)
109
- if (await hasSession(layout)) return false
127
+ if (await hasSession(layout)) return undefined
110
128
  const identity = readIdentity(env)
111
- const key = await unlockHuman(env, identity, passwords)
129
+ const key = await unlockHuman(env, identity, passwords, purpose)
112
130
  const vault = await Vault.open(layout, [key], env)
113
131
  if (vault.member === undefined) {
114
132
  throw new TypeVaultError(
@@ -124,7 +142,7 @@ export async function unlockSession(env: Env, passwords: Passwords, ttlMs: numbe
124
142
  note('replaced a running daemon that held no unlocked session')
125
143
  }
126
144
  await startSession(layout, env, key, ttlMs)
127
- return true
145
+ return key
128
146
  }
129
147
 
130
148
  const hasSession = async (layout: Layout): Promise<boolean> =>
@@ -169,7 +187,49 @@ function refreshSealedCopy(vault: Vault, identity: Identity & { readonly kind: '
169
187
  /** The vault's public, owner-signed state, readable without any key. */
170
188
  export const openPublic = (env: Env): Promise<Vault> => Vault.open(layoutFrom(env), [], env)
171
189
 
172
- export const openAdmin = async (env: Env): Promise<Admin> => new Admin(await openDirect(env))
190
+ /**
191
+ * An owner change. A machine member makes it with its own key, and a process under a grant never borrows the person's
192
+ * session for one. A person's goes through their unlocked session (unlocking it first, as a read does), proving they
193
+ * are there with the key that unlock used, or else asking for it once the session's owner window has closed.
194
+ */
195
+ export async function runAdmin(env: Env, request: AdminOp): Promise<AdminResult> {
196
+ const direct = machineKeys(env).length > 0 || isSet(env['TYPEVAULT_GRANT'])
197
+ const result = direct
198
+ ? await runAdminOp(await openDirect(env, OWNER_CHANGE), request)
199
+ : await sessionAdmin(env, request)
200
+ if (!result.reloaded) {
201
+ note(
202
+ 'the change committed, but the vault could not be reloaded after it: run typevault lock, then typevault unlock',
203
+ )
204
+ }
205
+ return result
206
+ }
207
+
208
+ async function sessionAdmin(env: Env, request: AdminOp): Promise<AdminResult> {
209
+ // Unlocking a locked vault here also approves the change, so that prompt says so too.
210
+ const { access, unlockedWith } = await sessionAccess(env, OWNER_CHANGE)
211
+ const { open, nonce } = await access.call('/v1/admin/challenge', {}, ChallengeSchema)
212
+ const key = open ? undefined : (unlockedWith ?? (await ownerKey(env)))
213
+ const proof = key === undefined ? undefined : { nonce, signature: sign(key.signSecret, ownerWindowMessage(nonce)) }
214
+ const body = { request, change: randomToken(16), ...(proof === undefined ? {} : { proof }) }
215
+ const { unserved, scopeRefreshed, ...result } = await ownerChange(access, layoutFrom(env), body)
216
+ if (!scopeRefreshed && result.reloaded) {
217
+ note('this session does not reach the tiers the change added yet: run typevault lock, then typevault unlock')
218
+ }
219
+ for (const name of unserved) {
220
+ note(`ceiling "${name}" is set, but its admin socket didn't open: run typevault lock, then typevault unlock`)
221
+ }
222
+ return result
223
+ }
224
+
225
+ async function ownerKey(env: Env): Promise<SecretKey> {
226
+ if (!process.stdin.isTTY && !passwordsFromStdin()) {
227
+ throw new TypeVaultError('locked', 'owner changes need your password or Touch ID: run this at a terminal')
228
+ }
229
+ return unlockHuman(env, readIdentity(env), passwords(), OWNER_CHANGE)
230
+ }
231
+
232
+ const OWNER_CHANGE = 'approve an owner change'
173
233
 
174
234
  export type ResolvedAccess =
175
235
  | { readonly kind: 'live'; readonly access: LiveAccess }
@@ -181,7 +241,7 @@ export async function resolveAccess(env: Env): Promise<ResolvedAccess> {
181
241
  const grant = env['TYPEVAULT_GRANT']?.trim()
182
242
  if (grant === undefined || grant === '') {
183
243
  const machine = machineKeys(env)
184
- if (machine.length === 0) return { kind: 'live', access: await sessionAccess(env) }
244
+ if (machine.length === 0) return { kind: 'live', access: (await sessionAccess(env)).access }
185
245
  const tier = env['TYPEVAULT_TIER']
186
246
  const vault = await Vault.open(layoutFrom(env), machine, env)
187
247
  const ownTiers = vault.member === undefined ? [] : (vault.state.members[vault.member]?.tiers ?? [])
@@ -202,11 +262,16 @@ export async function resolveAccess(env: Env): Promise<ResolvedAccess> {
202
262
 
203
263
  /**
204
264
  * A human member's CLI reads through the unlocked session's grant. On a terminal a locked vault asks for the
205
- * password right away; anywhere else (an agent) it stays locked until a human unlocks it.
265
+ * password right away; anywhere else (an agent) it stays locked until a human unlocks it. `unlockedWith` is the key a
266
+ * person just unlocked with here.
206
267
  */
207
- async function sessionAccess(env: Env): Promise<LiveAccess> {
268
+ async function sessionAccess(
269
+ env: Env,
270
+ purpose = UNLOCK,
271
+ ): Promise<{ readonly access: LiveAccess; readonly unlockedWith?: SecretKey }> {
208
272
  const layout = layoutFrom(env)
209
273
  await checkOwnerPin(layout, env)
274
+ let unlockedWith: SecretKey | undefined
210
275
  if (!(await hasSession(layout)) && !(await shareWorktreeSession(layout, env))) {
211
276
  const identity = readIdentity(env)
212
277
  if (identity === undefined) {
@@ -214,11 +279,12 @@ async function sessionAccess(env: Env): Promise<LiveAccess> {
214
279
  }
215
280
  const canAsk = process.stdin.isTTY || passwordsFromStdin()
216
281
  if (identity.kind !== 'human' || !canAsk) throw new TypeVaultError('locked', LOCKED_MESSAGE)
217
- await unlockSession(env, passwords(), DEFAULT_SESSION_MS)
282
+ unlockedWith = await unlockSession(env, passwords(), DEFAULT_SESSION_MS, purpose)
218
283
  }
219
284
  // A session daemon from another release fails here instead of misreading this CLI's requests.
220
285
  await ensureDaemon(layout, env)
221
- return new LiveAccess(layout.agentSocket, readFileSync(layout.sessionFile, 'utf8').trim())
286
+ const access = new LiveAccess(layout.agentSocket, readFileSync(layout.sessionFile, 'utf8').trim())
287
+ return unlockedWith === undefined ? { access } : { access, unlockedWith }
222
288
  }
223
289
 
224
290
  /**
package/src/cli/index.ts CHANGED
@@ -10,6 +10,7 @@ import { audit, grant } from './commands/grant'
10
10
  import { identity, joinCommand, lock, member, passwd, touchId, unlock } from './commands/members'
11
11
  import { importCommand, redact, request, run, scrub } from './commands/run'
12
12
  import { readPasswordsFromStdin } from './password'
13
+ import { commandIs, commandPath } from './requester'
13
14
 
14
15
  const main = defineCommand({
15
16
  meta: { name: 'typevault', version: PACKAGE_VERSION, description: 'A CLI-first secrets vault for agents' },
@@ -62,6 +63,7 @@ if (argv.slice(0, split).some(isGlobalFlag)) process.env['TYPEVAULT_GLOBAL'] = '
62
63
  if (argv.slice(0, split).includes(PASSWORD_STDIN)) readPasswordsFromStdin()
63
64
  const ownArgs = argv.slice(0, split).filter((arg) => !isGlobalFlag(arg) && arg !== PASSWORD_STDIN)
64
65
  const rawArgs = [...ownArgs, ...argv.slice(split)]
66
+ commandIs(commandPath(main, rawArgs))
65
67
  const wantsUsage = ownArgs.length === 0 || ownArgs.some((arg) => arg === '--help' || arg === '-h')
66
68
  const wantsVersion = ownArgs.length === 1 && (ownArgs[0] === '--version' || ownArgs[0] === '-v')
67
69
 
@@ -77,7 +79,8 @@ if (wantsUsage || wantsVersion) {
77
79
  process.exit(1)
78
80
  }
79
81
  // citty's usage errors (unknown command, missing argument): its own runner prints usage for them.
80
- if (error instanceof Error && error.name === 'CLIError') await runMain(main)
82
+ // The same normalized arguments the prompts were built from: citty rejects them again before any command runs.
83
+ if (error instanceof Error && error.name === 'CLIError') await runMain(main, { rawArgs })
81
84
  else {
82
85
  const message = error instanceof Error ? error.message : 'unexpected error'
83
86
  process.stderr.write(`typevault: ${message.replaceAll(/[\r\n]+/g, ' ')}\n`)
@@ -0,0 +1,100 @@
1
+ import type { z } from 'zod'
2
+
3
+ import { TypeVaultError } from '../core/errors'
4
+ import type { Layout } from '../core/layout'
5
+ import { isDaemonAlive } from '../daemon/client'
6
+ import type { LiveAccess } from '../daemon/live-access'
7
+ import { OWNER_CHANGE_KEEP_MS, readOutcome, settledResult } from '../daemon/owner-changes'
8
+ import { AdminResultSchema, AdmittedSchema, AdminWaitedSchema } from '../daemon/protocol'
9
+
10
+ const TRANSPORT_RETRIES = 5
11
+
12
+ type Outcome = z.infer<typeof AdminResultSchema>
13
+
14
+ // The client wraps what the transport threw (fetch, a timeout, a cut-off body); an error of our own wrapping another is not.
15
+ const lostInTransport = (error: unknown): error is TypeVaultError =>
16
+ error instanceof TypeVaultError && error.cause instanceof Error && !(error.cause instanceof TypeVaultError)
17
+
18
+ /**
19
+ * Admits an owner change under the caller's own id and polls until its outcome arrives. After an answer lost in
20
+ * transport, the id's receipt decides what happened before anything is sent again: a change the daemon already took
21
+ * (which may have rotated the owner or outlived the session since) is collected, and only a definite miss within the
22
+ * daemon's retry window is sent again. A change that failed is reported with its own error, never sent again. Once the
23
+ * daemon is gone, the outcome it kept in the run directory answers. Without either, the outcome is unknown, never
24
+ * reported as a failure.
25
+ */
26
+ export async function ownerChange(
27
+ access: Pick<LiveAccess, 'call'>,
28
+ layout: Pick<Layout, 'run' | 'agentSocket'>,
29
+ body: { readonly change: string },
30
+ ): Promise<Outcome> {
31
+ const { change } = body
32
+ const sentAt = Date.now()
33
+ let admission: 'unsent' | 'unsure' | 'admitted' = 'unsent'
34
+ let resent = false
35
+ let sentOnce = false
36
+ const unknown = (cause: unknown) =>
37
+ new TypeVaultError(
38
+ 'unavailable',
39
+ "the session stopped answering, so this owner change's outcome is unknown: check the vault before running it again",
40
+ { cause },
41
+ )
42
+ // A change's own errors come back as receipt states, so a refused poll is the daemon's: one that can't serve this
43
+ // receipt (another release's, say) says nothing of the change, and the receipt saved on disk may.
44
+ const poll = async () => {
45
+ try {
46
+ return await access.call('/v1/admin/wait', { change }, AdminWaitedSchema)
47
+ } catch (error) {
48
+ if (lostInTransport(error)) throw error
49
+ const kept = readOutcome(layout.run, change, AdminResultSchema)
50
+ if (kept !== undefined) return kept
51
+ throw unknown(error)
52
+ }
53
+ }
54
+ for (let failures = 0; ;) {
55
+ try {
56
+ if (admission === 'unsure') {
57
+ const waited = await poll()
58
+ if (waited.state === 'unknown') {
59
+ if (resent || Date.now() - sentAt >= OWNER_CHANGE_KEEP_MS) throw unknown(undefined)
60
+ admission = 'unsent'
61
+ } else {
62
+ admission = 'admitted'
63
+ if (waited.state !== 'running') return settledResult(waited)
64
+ failures = 0
65
+ continue
66
+ }
67
+ }
68
+ if (admission === 'unsent') {
69
+ const resending = sentOnce
70
+ sentOnce = true
71
+ admission = 'unsure'
72
+ try {
73
+ await access.call('/v1/admin', body, AdmittedSchema)
74
+ } catch (error) {
75
+ // A refused resend says nothing of the original request, which may have been admitted late and changed what the
76
+ // daemon accepts (an owner rotation): its receipt decides, and the resend is not tried again.
77
+ if (!resending || lostInTransport(error)) throw error
78
+ resent = true
79
+ continue
80
+ }
81
+ admission = 'admitted'
82
+ }
83
+ const waited = await poll()
84
+ // An admitted change has a receipt for as long as its window lasts: without one, nothing can say what happened.
85
+ if (waited.state === 'unknown') throw unknown(undefined)
86
+ if (waited.state !== 'running') return settledResult(waited)
87
+ failures = 0
88
+ } catch (error) {
89
+ if (!lostInTransport(error)) throw error
90
+ const kept = readOutcome(layout.run, change, AdminResultSchema)
91
+ if (kept !== undefined) return settledResult(kept)
92
+ if (++failures >= TRANSPORT_RETRIES || !(await isDaemonAlive(layout.agentSocket))) {
93
+ // A draining daemon may have saved the outcome and closed while it was probed.
94
+ const late = readOutcome(layout.run, change, AdminResultSchema)
95
+ if (late !== undefined) return settledResult(late)
96
+ throw unknown(error)
97
+ }
98
+ }
99
+ }
100
+ }