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.
@@ -0,0 +1,240 @@
1
+ import { existsSync } from 'node:fs'
2
+ import { homedir } from 'node:os'
3
+ import { basename, dirname } from 'node:path'
4
+
5
+ import { type ArgsDef, type CommandDef, parseArgs } from 'citty'
6
+
7
+ import type { Layout } from '../core/layout'
8
+ import { table } from './output'
9
+
10
+ /**
11
+ * Who asks for a password or a touch, and why: which program ran this command (the agent session, when an agent did),
12
+ * which vault, the command, the working directory, and the `--reason` it gave. With several agents running, this
13
+ * tells them apart. Everything but `purpose` comes from outside (argv, the process table, the filesystem), so the
14
+ * prompts render each field as one line of printable text.
15
+ */
16
+ export type UnlockRequest = {
17
+ readonly purpose: string
18
+ readonly program?: string
19
+ readonly vault: string
20
+ readonly where: string
21
+ readonly command: string
22
+ readonly reason?: string
23
+ }
24
+
25
+ export async function unlockRequest(purpose: string, layout: Layout | undefined): Promise<UnlockRequest> {
26
+ const program = await parentProgram().catch(() => undefined)
27
+ const cwd = process.cwd()
28
+ const home = homedir()
29
+ const where = cwd === home || cwd.startsWith(`${home}/`) ? `~${cwd.slice(home.length)}` : cwd
30
+ const reason = command.reason
31
+ return {
32
+ purpose,
33
+ ...(program === undefined ? {} : { program }),
34
+ vault:
35
+ layout?.scope === 'global' ? 'the global vault' : basename(layout === undefined ? cwd : dirname(layout.vault)),
36
+ where,
37
+ command: commandOf(command.args),
38
+ ...(reason === undefined ? {} : { reason }),
39
+ }
40
+ }
41
+
42
+ /**
43
+ * "typevault is trying to <this>." The caller's reason completes the sentence; the dialog wraps at about 30
44
+ * characters, so it names only what a person decides on. The "for <program> in <vault>" tail is always ours, so a
45
+ * misleading reason still shows who gave it. The command and working directory are in the terminal.
46
+ */
47
+ export function touchIdReason(request: UnlockRequest): string {
48
+ const program = request.program === undefined ? '' : ` for ${shown(request.program)}`
49
+ return `${wanted(request)}${program} in ${shown(request.vault)}`
50
+ }
51
+
52
+ /** The lines above a password prompt. */
53
+ export function promptHeader(request: UnlockRequest): string {
54
+ const rows = [
55
+ [' vault', shown(request.vault)],
56
+ [' command', shown(request.command)],
57
+ [' in', shown(request.where)],
58
+ ]
59
+ const program = request.program === undefined ? 'A command' : shown(request.program)
60
+ return `${program} wants to ${wanted(request)}\n${table(rows)}`
61
+ }
62
+
63
+ /**
64
+ * The nearest ancestor that is a program of its own: shells and launchers in between are skipped, and a script run
65
+ * by an interpreter is named by its script. `ps` lists `pid ppid args`, one process per line.
66
+ */
67
+ export function programIn(ps: string, parent: number): string | undefined {
68
+ const processes = new Map<number, { readonly ppid: number; readonly args: readonly string[] }>()
69
+ for (const line of ps.split('\n')) {
70
+ const [pid, ppid, ...args] = line.trim().split(/\s+/)
71
+ if (pid !== undefined && ppid !== undefined && args.length > 0)
72
+ processes.set(Number(pid), { ppid: Number(ppid), args })
73
+ }
74
+ let pid = parent
75
+ for (let depth = 0; depth < 32 && pid > 1; depth += 1) {
76
+ const found = processes.get(pid)
77
+ if (found === undefined) return undefined
78
+ const name = programName(found.args)
79
+ if (name !== undefined && !PASS_THROUGH.has(name)) return name
80
+ pid = found.ppid
81
+ }
82
+ return undefined
83
+ }
84
+
85
+ const SHELLS = ['sh', 'bash', 'zsh', 'fish', 'dash', 'ksh', 'tcsh', 'csh', 'nu']
86
+ const LAUNCHERS = [
87
+ 'env',
88
+ 'login',
89
+ 'sudo',
90
+ 'nohup',
91
+ 'timeout',
92
+ 'xargs',
93
+ 'npm',
94
+ 'npx',
95
+ 'pnpm',
96
+ 'yarn',
97
+ 'bunx',
98
+ 'typevault',
99
+ ]
100
+ const PASS_THROUGH = new Set([...SHELLS, ...LAUNCHERS])
101
+ const INTERPRETERS = new Set(['node', 'bun', 'deno', 'python', 'python3', 'ruby'])
102
+ export const UNLOCK = 'unlock your vault'
103
+ const SHOWN_LENGTH = 80
104
+ const REASON = '--reason'
105
+
106
+ // Never `ps` from PATH: this runs before authentication, and a project can put its own `ps` first on PATH.
107
+ const PS = ['/bin/ps', '/usr/bin/ps'].find((path) => existsSync(path))
108
+
109
+ async function parentProgram(): Promise<string | undefined> {
110
+ if (PS === undefined) return undefined
111
+ const ps = Bun.spawn([PS, '-A', '-o', 'pid=,ppid=,args='], { stdout: 'pipe', stderr: 'ignore' })
112
+ const [out, code] = await Promise.all([new Response(ps.stdout).text(), ps.exited])
113
+ return code === 0 ? programIn(out, process.ppid) : undefined
114
+ }
115
+
116
+ /**
117
+ * A script run by an interpreter is named by its file only in the plain script form: the script path right after the
118
+ * interpreter. Any option first (inline code like `node -e ...` or `python -cCODE`, an option whose value could be
119
+ * anything, `ps` splitting a quoted argument) means the interpreter's name, so no source or option value shows.
120
+ */
121
+ function programName(args: readonly string[]): string | undefined {
122
+ const [first, script] = args
123
+ if (first === undefined) return undefined
124
+ // A login shell is listed as `-zsh`.
125
+ const name = basename(first).replace(/^-/, '')
126
+ if (!INTERPRETERS.has(name)) return name
127
+ if (script === undefined || script.startsWith('-') || !(script.includes('/') || SCRIPT_FILE.test(script))) {
128
+ return name
129
+ }
130
+ return basename(script).replace(SCRIPT_FILE, '')
131
+ }
132
+
133
+ const SCRIPT_FILE = /\.[cm]?[jt]sx?$|\.py$|\.rb$/
134
+
135
+ /**
136
+ * The command citty dispatches to: the words naming it (`set`, `tier add`), the arguments citty was given (global
137
+ * flags already taken out), and its `--reason` as citty parses it for that command, the value it audits. A command
138
+ * that declares no `--reason` has none: the prompts never re-parse argv, so they can't read a field or an entry name
139
+ * as a reason.
140
+ */
141
+ export type Dispatched = {
142
+ readonly words: readonly string[]
143
+ readonly args: readonly string[]
144
+ readonly reason?: string
145
+ }
146
+
147
+ let command: Dispatched = { words: [], args: [] }
148
+
149
+ /** Set by the CLI entry point to the command citty dispatches to. */
150
+ export function commandIs(dispatched: Dispatched): void {
151
+ command = dispatched
152
+ }
153
+
154
+ type CommandLevel = Pick<CommandDef, 'args' | 'subCommands'>
155
+
156
+ /**
157
+ * The command citty dispatches to (`tier add`), found the way citty finds it: at each level, the first argument that
158
+ * isn't an option or an option's value, up to `--`. Never an argument.
159
+ */
160
+ export function commandPath(root: CommandLevel, rawArgs: readonly string[]): Dispatched {
161
+ const words: string[] = []
162
+ let level = root
163
+ let args = rawArgs
164
+ for (;;) {
165
+ const subCommands = level.subCommands
166
+ const listed = typeof subCommands === 'object' && !(subCommands instanceof Promise)
167
+ const index = listed ? subCommandIndex(args, level.args) : -1
168
+ const name = args[index]
169
+ const next = listed && name !== undefined ? subCommands[name] : undefined
170
+ if (name === undefined || typeof next !== 'object' || next instanceof Promise) {
171
+ const reason = reasonOf(args, argsOf(level.args))
172
+ return { words, args: rawArgs, ...(reason === undefined ? {} : { reason }) }
173
+ }
174
+ words.push(name)
175
+ level = next
176
+ args = args.slice(index + 1)
177
+ }
178
+ }
179
+
180
+ function reasonOf(args: readonly string[], defs: ArgsDef): string | undefined {
181
+ if (!takesValue(REASON, defs)) return undefined
182
+ try {
183
+ const reason: unknown = parseArgs([...args], defs)['reason']
184
+ return typeof reason === 'string' && reason !== '' ? reason : undefined
185
+ } catch (error) {
186
+ // citty rejects these arguments the same way before the command runs, so no prompt shows to need a reason.
187
+ if (error instanceof Error && error.name === 'CLIError') return undefined
188
+ throw error
189
+ }
190
+ }
191
+
192
+ const argsOf = (argsDef: CommandLevel['args']): ArgsDef =>
193
+ typeof argsDef === 'object' && !(argsDef instanceof Promise) ? argsDef : {}
194
+
195
+ function subCommandIndex(args: readonly string[], argsDef: CommandLevel['args']): number {
196
+ const defs = argsOf(argsDef)
197
+ for (let index = 0; index < args.length; index += 1) {
198
+ const arg = args[index] ?? ''
199
+ if (arg === '--') return -1
200
+ if (!arg.startsWith('-')) return index
201
+ if (!arg.includes('=') && takesValue(arg, defs)) index += 1
202
+ }
203
+ return -1
204
+ }
205
+
206
+ function takesValue(flag: string, defs: ArgsDef): boolean {
207
+ const name = flag.replace(/^-{1,2}/, '')
208
+ return Object.entries(defs).some(
209
+ ([key, def]) =>
210
+ (def.type === 'string' || def.type === 'enum') &&
211
+ (camel(key) === camel(name) || [def.alias ?? []].flat().includes(name)),
212
+ )
213
+ }
214
+
215
+ const camel = (text: string): string => text.replaceAll(/-([a-z])/g, (_, letter: string) => letter.toUpperCase())
216
+
217
+ /**
218
+ * The command and, for `run`, the child's program name: never an argument's value, since an entry name, a
219
+ * `--field password=...` or a child's arguments can hold a secret, and the prompt may show before they are rejected.
220
+ */
221
+ function commandOf(argv: readonly string[]): string {
222
+ const child = command.words[0] === 'run' && argv.includes('--') ? argv[argv.indexOf('--') + 1] : undefined
223
+ return ['typevault', ...command.words, ...(child === undefined ? [] : ['--', basename(child)])].join(' ')
224
+ }
225
+
226
+ /**
227
+ * The caller's reason stands in for a plain unlock. Any other purpose (an owner change, which the same touch approves)
228
+ * is always said, the reason after it, so a reason can't hide what the touch allows.
229
+ */
230
+ function wanted(request: UnlockRequest): string {
231
+ const reason = request.reason === undefined ? '' : shown(request.reason)
232
+ if (reason === '') return request.purpose
233
+ return request.purpose === UNLOCK ? reason : `${request.purpose} to ${reason}`
234
+ }
235
+
236
+ /** One line of printable text: control, format and line-separator characters could redraw or fake the prompt. */
237
+ function shown(text: string): string {
238
+ const line = text.replaceAll(/[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]+/gu, ' ').trim()
239
+ return line.length > SHOWN_LENGTH ? `${line.slice(0, SHOWN_LENGTH - 1)}…` : line
240
+ }
package/src/core/admin.ts CHANGED
@@ -2,6 +2,7 @@ import { encodeSecretKey, generateSecretKey, type PublicKey, publicKeyOf, seal,
2
2
  import { fromBase64, utf8 } from './encoding'
3
3
  import { signerOf } from './entries'
4
4
  import { TypeVaultError } from './errors'
5
+ import { decodeMemberPublic } from './identity'
5
6
  import { ownerWrapPath, wrapPath } from './keyring'
6
7
  import { withLock } from './lock'
7
8
  import { rotateOwner, rotateTiers } from './rotate'
@@ -18,7 +19,7 @@ import {
18
19
  signersDoc,
19
20
  type VaultState,
20
21
  } from './state'
21
- import { commitTxn, Txn } from './txn'
22
+ import { commitTxn, MarkedCommitted, recoverTxns, Txn } from './txn'
22
23
  import type { Vault } from './vault'
23
24
 
24
25
  export type NewMember = PublicKey & {
@@ -31,6 +32,42 @@ export type NewMember = PublicKey & {
31
32
  const reachOf = (state: VaultState, tiers: readonly string[]): readonly string[] =>
32
33
  [...new Set(tiers.flatMap((tier) => [...reach(state.tiers, tier)]))].sort()
33
34
 
35
+ /**
36
+ * A change that committed, after which the vault couldn't be reloaded: its result stands, and the vault keeps the state
37
+ * it had until its next refresh tries again.
38
+ */
39
+ /**
40
+ * A change committed by its marker whose files couldn't be applied yet: the vault completes it when next opened. It
41
+ * keeps the code of what stopped it (a symlink planted in the vault stays `tampered`), but never stands for a failure.
42
+ */
43
+ export class UncertainChange extends TypeVaultError {
44
+ constructor(cause: unknown) {
45
+ const reason = cause instanceof TypeVaultError ? ` (${cause.message})` : ''
46
+ super(
47
+ cause instanceof TypeVaultError ? cause.code : 'unavailable',
48
+ `the change was committed but its files could not be written yet${reason}; the vault finishes it when next opened, so check it before running this again`,
49
+ { cause },
50
+ )
51
+ this.name = 'UncertainChange'
52
+ }
53
+ }
54
+
55
+ export type MemberRemoval = {
56
+ readonly affected: readonly string[]
57
+ readonly removed: readonly string[]
58
+ readonly ownerRotated: boolean
59
+ }
60
+
61
+ export class CommittedChange extends Error {
62
+ readonly result: unknown
63
+
64
+ constructor(result: unknown, cause: unknown) {
65
+ super('the change committed, but the vault could not be reloaded', { cause })
66
+ this.name = 'CommittedChange'
67
+ this.result = result
68
+ }
69
+ }
70
+
34
71
  /** Owner-only changes to tiers, members, signers and ceilings. Each one lands as a single transaction. */
35
72
  export class Admin {
36
73
  readonly #vault: Vault
@@ -48,8 +85,22 @@ export class Admin {
48
85
  this.#vault.refresh()
49
86
  const txn = new Txn()
50
87
  const result = await build(this.#vault.state, txn)
51
- commitTxn(this.#vault.layout, txn)
52
- this.#vault.reload()
88
+ try {
89
+ commitTxn(this.#vault.layout, txn)
90
+ } catch (error) {
91
+ if (!(error instanceof MarkedCommitted)) throw error
92
+ // Committed by its marker: rolling it forward now confirms it; failing that, its outcome is uncertain, never a failure.
93
+ try {
94
+ recoverTxns(this.#vault.layout)
95
+ } catch (recovery) {
96
+ throw new UncertainChange(recovery)
97
+ }
98
+ }
99
+ try {
100
+ this.#vault.reload()
101
+ } catch (error) {
102
+ throw new CommittedChange(result, error)
103
+ }
53
104
  return result
54
105
  })
55
106
  }
@@ -112,9 +163,8 @@ export class Admin {
112
163
  * Drops an include and rotates the included tier in one transaction: a crash leaves both or neither, never a
113
164
  * dropped include whose old wrap still opens the included tier.
114
165
  */
115
- async exclude(tier: string, included: string): Promise<readonly string[]> {
116
- let affected: readonly string[] = []
117
- await this.#mutate(async (state, txn) => {
166
+ exclude(tier: string, included: string): Promise<readonly string[]> {
167
+ return this.#mutate(async (state, txn) => {
118
168
  const holder = state.tiers[tier]
119
169
  if (holder === undefined || !holder.includes.includes(included)) {
120
170
  throw new TypeVaultError('not_found', `"${tier}" does not include "${included}"`)
@@ -122,23 +172,15 @@ export class Admin {
122
172
  const updated = { ...holder, includes: holder.includes.filter((name) => name !== included) }
123
173
  // Rotating removes the included tier's old generation, the dropped wrap with it, and rewrites tiers.json.
124
174
  const context = { vault: this.#vault, owner: this.#owner, txn, exposed: true }
125
- affected = await rotateTiers({ ...context, state: { ...state, tiers: { ...state.tiers, [tier]: updated } } }, [
126
- included,
127
- ])
175
+ return rotateTiers({ ...context, state: { ...state, tiers: { ...state.tiers, [tier]: updated } } }, [included])
128
176
  })
129
- return affected
130
177
  }
131
178
 
132
179
  /** Rotates every tier `name` reaches. Returns their entry names, now flagged for rotation at the source. */
133
- async rotate(name: string): Promise<readonly string[]> {
134
- let affected: readonly string[] = []
135
- await this.#mutate(async (state, txn) => {
136
- affected = await rotateTiers(
137
- { vault: this.#vault, owner: this.#owner, state, txn, exposed: true },
138
- reachOf(state, [name]),
139
- )
140
- })
141
- return affected
180
+ rotate(name: string): Promise<readonly string[]> {
181
+ return this.#mutate(async (state, txn) =>
182
+ rotateTiers({ vault: this.#vault, owner: this.#owner, state, txn, exposed: true }, reachOf(state, [name])),
183
+ )
142
184
  }
143
185
 
144
186
  /**
@@ -168,9 +210,10 @@ export class Admin {
168
210
  * Drops a member and rotates every tier they reached, in one transaction: a crash leaves both or neither, never a
169
211
  * removed member whose keys still open new ciphertext. Returns the entries they could read, now flagged for
170
212
  * rotation: what they already decrypted can only be revoked at each secret's source. Any other name listing the same
171
- * key goes too: it would otherwise keep that key's access.
213
+ * key goes too: it would otherwise keep that key's access. Also returns who was removed and whether the owner key
214
+ * rotated, as found under the transaction's own lock.
172
215
  */
173
- removeMember(name: string): Promise<readonly string[]> {
216
+ removeMember(name: string): Promise<MemberRemoval> {
174
217
  return this.#mutate(async (state, txn) => {
175
218
  const member = state.members[name]
176
219
  if (member === undefined) throw new TypeVaultError('not_found', `no member "${name}"`)
@@ -179,22 +222,21 @@ export class Admin {
179
222
  Object.entries(state.members).filter(([, other]) => other.recipient !== member.recipient),
180
223
  )
181
224
  const context = { vault: this.#vault, owner: this.#owner, state: { ...state, members }, txn, exposed: true }
182
- for (const [gone] of removed) txn.remove(`members/${gone}.key`)
225
+ const names = removed.map(([gone]) => gone)
226
+ for (const gone of names) txn.remove(`members/${gone}.key`)
183
227
  if (removed.some(([, gone]) => gone.owner)) {
184
228
  if (!Object.values(members).some((remaining) => remaining.owner)) {
185
229
  throw new TypeVaultError('invalid', `"${name}" is the last owner; add another owner first`)
186
230
  }
187
231
  for (const [gone, { owner }] of removed) if (owner) txn.remove(ownerWrapPath(gone))
188
- return rotateOwner(context)
232
+ return { affected: await rotateOwner(context), removed: names, ownerRotated: true }
189
233
  }
190
234
  txn.put('members.json', membersDoc(members, this.#owner, state.seqs.members + 1))
191
- return rotateTiers(
192
- context,
193
- reachOf(
194
- state,
195
- removed.flatMap(([, gone]) => gone.tiers),
196
- ),
235
+ const tiers = reachOf(
236
+ state,
237
+ removed.flatMap(([, gone]) => gone.tiers),
197
238
  )
239
+ return { affected: await rotateTiers(context, tiers), removed: names, ownerRotated: false }
198
240
  })
199
241
  }
200
242
 
@@ -249,3 +291,83 @@ export class Admin {
249
291
  return signerOf(this.#owner)
250
292
  }
251
293
  }
294
+
295
+ /** One owner change, as the CLI asks it: run here in direct mode, or by an unlocked session's daemon. */
296
+ export type AdminOp =
297
+ | {
298
+ readonly op: 'tier.add' | 'tier.rm' | 'key.rotate' | 'ceiling.rm' | 'signer.rm' | 'member.rm'
299
+ readonly name: string
300
+ }
301
+ | { readonly op: 'tier.include' | 'tier.exclude'; readonly tier: string; readonly included: string }
302
+ | { readonly op: 'ceiling.set'; readonly name: string; readonly tier: string }
303
+ | { readonly op: 'signer.add'; readonly id: string; readonly publicKey: string; readonly tiers: readonly string[] }
304
+ | {
305
+ readonly op: 'member.add'
306
+ readonly name: string
307
+ readonly publicKey: string
308
+ readonly owner: boolean
309
+ readonly tiers: readonly string[]
310
+ }
311
+
312
+ export type AdminResult = {
313
+ /** Entries flagged for rotation at their source. */
314
+ readonly affected: readonly string[]
315
+ /** Members `member.rm` removed: every name sharing the removed key. */
316
+ readonly removed: readonly string[]
317
+ readonly ownerRotated: boolean
318
+ /** False when the change committed but the vault couldn't be reloaded after it. */
319
+ readonly reloaded: boolean
320
+ }
321
+
322
+ export const runAdminOp = (vault: Vault, request: AdminOp): Promise<AdminResult> => dispatch(new Admin(vault), request)
323
+
324
+ /**
325
+ * A change's own result, also when it committed but the vault couldn't be reloaded after it. Every Admin method returns
326
+ * its transaction's result, so the result a CommittedChange carries is of that method's type.
327
+ */
328
+ async function committed<T>(change: Promise<T>): Promise<{ readonly value: T; readonly reloaded: boolean }> {
329
+ try {
330
+ return { value: await change, reloaded: true }
331
+ } catch (error) {
332
+ if (error instanceof CommittedChange) return { value: error.result as T, reloaded: false }
333
+ throw error
334
+ }
335
+ }
336
+
337
+ const NONE = { affected: [], removed: [], ownerRotated: false } as const
338
+
339
+ async function dispatch(admin: Admin, request: AdminOp): Promise<AdminResult> {
340
+ const plain = async (change: Promise<void>) => ({ ...NONE, reloaded: (await committed(change)).reloaded })
341
+ const rotation = async (change: Promise<readonly string[]>) => {
342
+ const { value, reloaded } = await committed(change)
343
+ return { ...NONE, affected: value, reloaded }
344
+ }
345
+ switch (request.op) {
346
+ case 'tier.add':
347
+ return plain(admin.addTier(request.name))
348
+ case 'tier.rm':
349
+ return plain(admin.removeTier(request.name))
350
+ case 'tier.include':
351
+ return plain(admin.include(request.tier, request.included))
352
+ case 'tier.exclude':
353
+ return rotation(admin.exclude(request.tier, request.included))
354
+ case 'key.rotate':
355
+ return rotation(admin.rotate(request.name))
356
+ case 'ceiling.set':
357
+ return plain(admin.setCeiling(request.name, request.tier))
358
+ case 'ceiling.rm':
359
+ return plain(admin.removeCeiling(request.name))
360
+ case 'signer.add':
361
+ return plain(admin.setSigner(request.id, request.publicKey, request.tiers))
362
+ case 'signer.rm':
363
+ return plain(admin.removeSigner(request.name))
364
+ case 'member.add': {
365
+ const pub = decodeMemberPublic(request.publicKey)
366
+ return plain(admin.addMember(request.name, { ...pub, owner: request.owner, tiers: request.tiers }))
367
+ }
368
+ case 'member.rm': {
369
+ const { value, reloaded } = await committed(admin.removeMember(request.name))
370
+ return { ...value, reloaded }
371
+ }
372
+ }
373
+ }
@@ -125,8 +125,13 @@ export const sealMemberKeyForTouchId = (env: Env, key: SecretKey): Promise<Touch
125
125
  enableTouchId(env, utf8(encodeSecretKey(key)))
126
126
 
127
127
  /** The member key through Touch ID; it must be this identity's own, whatever identity.json was given. */
128
- export async function unlockIdentityWithTouchId(env: Env, identity: Identity, seal: TouchIdSeal): Promise<SecretKey> {
129
- const key = decodeSecretKey(fromUtf8(await openWithTouchId(env, seal)))
128
+ export async function unlockIdentityWithTouchId(
129
+ env: Env,
130
+ identity: Identity,
131
+ seal: TouchIdSeal,
132
+ reason: string,
133
+ ): Promise<SecretKey> {
134
+ const key = decodeSecretKey(fromUtf8(await openWithTouchId(env, seal, reason)))
130
135
  const pub = await publicKeyOf(key)
131
136
  if (key.role.kind !== 'member' || pub.recipient !== identity.recipient || pub.signPublic !== identity.signPublic) {
132
137
  throw new TypeVaultError('tampered', "the Touch ID copy is not this identity's key")
@@ -1,9 +1,24 @@
1
+ import { fromBase64Url, toBase64 } from './encoding'
1
2
  import { TypeVaultError } from './errors'
2
3
 
3
- export type FieldType = 'secret' | 'text' | 'totp' | 'oauth'
4
+ export type FieldType = 'secret' | 'text' | 'totp' | 'oauth' | 'passkey'
5
+ /**
6
+ * A WebAuthn credential. The ids and the PKCS#8 P-256 private key are base64url without padding. A discoverable
7
+ * credential (a site can find it with no allow-list, for username-less sign-in) always has its user handle.
8
+ */
9
+ export type Passkey = {
10
+ readonly rp_id: string
11
+ readonly credential_id: string
12
+ readonly private_key: string
13
+ readonly discoverable: boolean
14
+ readonly user_handle?: string
15
+ readonly user_name?: string
16
+ readonly sign_count?: number
17
+ }
4
18
  export type Field =
5
19
  | { readonly type: 'secret' | 'text' | 'totp'; readonly value: string }
6
20
  | { readonly type: 'oauth'; readonly value: Readonly<Record<string, string>> }
21
+ | { readonly type: 'passkey'; readonly value: Passkey }
7
22
  export const PRESETS = {
8
23
  password: { fields: { username: 'text', password: 'secret', totp: 'totp', url: 'text' }, input: 'password' },
9
24
  api_key: { fields: { $default: 'secret' }, input: '$default' },
@@ -131,6 +146,12 @@ export function resolveField(fields: Readonly<Record<string, Field>>, wanted: st
131
146
  const part = field.value[wanted.slice(dot + 1)]
132
147
  return part === undefined ? undefined : { type: 'secret', value: part }
133
148
  }
149
+ case 'passkey': {
150
+ const name = wanted.slice(dot + 1)
151
+ const part = Object.hasOwn(field.value, name) ? field.value[name as keyof Passkey] : undefined
152
+ if (part === undefined) return undefined
153
+ return { type: name === 'private_key' ? 'secret' : 'text', value: String(part) }
154
+ }
134
155
  case 'secret':
135
156
  case 'text':
136
157
  case 'totp':
@@ -143,6 +164,8 @@ export function fieldValue(field: Field): string {
143
164
  switch (field.type) {
144
165
  case 'oauth':
145
166
  return field.value['access_token'] ?? ''
167
+ case 'passkey':
168
+ return JSON.stringify(field.value)
146
169
  case 'secret':
147
170
  case 'text':
148
171
  case 'totp':
@@ -155,6 +178,12 @@ export function fieldStrings(field: Field): readonly string[] {
155
178
  switch (field.type) {
156
179
  case 'oauth':
157
180
  return Object.values(field.value)
181
+ case 'passkey':
182
+ // Chrome's DevTools protocol carries the same key in standard base64.
183
+ return [
184
+ ...Object.values(field.value).filter((part) => typeof part === 'string'),
185
+ toBase64(fromBase64Url(field.value.private_key)),
186
+ ]
158
187
  case 'secret':
159
188
  case 'text':
160
189
  case 'totp':
@@ -0,0 +1,94 @@
1
+ import { p256 } from '@noble/curves/nist.js'
2
+ import { hex } from '@scure/base'
3
+
4
+ import { fromBase64Url, toBase64Url } from './encoding'
5
+
6
+ // The AlgorithmIdentifier of an EC key on P-256: id-ecPublicKey, then prime256v1.
7
+ const P256_ALGORITHM = hex.decode('301306072a8648ce3d020106082a8648ce3d030107')
8
+ // The prime256v1 OID, as ECPrivateKey's optional parameters repeat it.
9
+ const P256_CURVE = hex.decode('06082a8648ce3d030107')
10
+
11
+ // Chrome DevTools restores a credential's signature counter only up to UINT32_MAX.
12
+ export const MAX_SIGN_COUNT = 4_294_967_295
13
+ // WebAuthn, and Chrome DevTools with it, caps a user handle at 64 bytes.
14
+ const MAX_USER_HANDLE_BYTES = 64
15
+
16
+ export function isUserHandle(text: string): boolean {
17
+ const bytes = decodeBase64Url(text)
18
+ return bytes !== undefined && bytes.length <= MAX_USER_HANDLE_BYTES
19
+ }
20
+
21
+ export function decodeBase64Url(text: string): Uint8Array | undefined {
22
+ try {
23
+ const bytes = fromBase64Url(text)
24
+ return text !== '' && toBase64Url(bytes) === text ? bytes : undefined
25
+ } catch {
26
+ return undefined
27
+ }
28
+ }
29
+
30
+ /**
31
+ * True for a PKCS#8 ECDSA P-256 private key that Chromium's virtual authenticator imports: BoringSSL's parser reads
32
+ * every field, so the whole structure is checked, not just the scalar. That is a 32-byte scalar in range, the curve
33
+ * parameters if repeated, the public key if present (it must be the scalar's), and no bytes left over at any level.
34
+ */
35
+ export function isP256PrivateKey(pkcs8: Uint8Array): boolean {
36
+ const outer = tlv(pkcs8, 0)
37
+ if (outer?.tag !== 0x30 || outer.next !== pkcs8.length) return false
38
+ const version = tlv(pkcs8, outer.start)
39
+ if (version?.tag !== 0x02 || !equal(pkcs8.subarray(version.start, version.next), [0x00])) return false
40
+ const algorithm = tlv(pkcs8, version.next)
41
+ if (algorithm?.tag !== 0x30 || !equal(pkcs8.subarray(version.next, algorithm.next), P256_ALGORITHM)) return false
42
+ const wrapped = tlv(pkcs8, algorithm.next)
43
+ if (wrapped?.tag !== 0x04 || wrapped.next !== outer.next) return false
44
+ const ecKey = tlv(pkcs8, wrapped.start)
45
+ if (ecKey?.tag !== 0x30 || ecKey.next !== wrapped.next) return false
46
+ const ecVersion = tlv(pkcs8, ecKey.start)
47
+ if (ecVersion?.tag !== 0x02 || !equal(pkcs8.subarray(ecVersion.start, ecVersion.next), [0x01])) return false
48
+ const scalarField = tlv(pkcs8, ecVersion.next)
49
+ if (scalarField?.tag !== 0x04 || scalarField.next - scalarField.start !== 32) return false
50
+ const scalar = pkcs8.subarray(scalarField.start, scalarField.next)
51
+ if (!p256.utils.isValidSecretKey(scalar)) return false
52
+ let at = scalarField.next
53
+ const parameters = tlv(pkcs8, at)
54
+ if (at < ecKey.next && parameters?.tag === 0xa0) {
55
+ if (!equal(pkcs8.subarray(parameters.start, parameters.next), P256_CURVE)) return false
56
+ at = parameters.next
57
+ }
58
+ const publicKey = tlv(pkcs8, at)
59
+ if (at < ecKey.next && publicKey?.tag === 0xa1) {
60
+ const bits = tlv(pkcs8, publicKey.start)
61
+ if (bits?.tag !== 0x03 || bits.next !== publicKey.next || pkcs8[bits.start] !== 0x00) return false
62
+ if (!equal(pkcs8.subarray(bits.start + 1, bits.next), p256.getPublicKey(scalar, false))) return false
63
+ at = publicKey.next
64
+ }
65
+ return at === ecKey.next
66
+ }
67
+
68
+ type Tlv = { readonly tag: number; readonly start: number; readonly next: number }
69
+
70
+ // One DER tag-length-value at `at`: the content runs from `start` to `next`. Lengths past 0xffff never occur here.
71
+ // DER, and BoringSSL with it, takes only the shortest length encoding, so a long form that fits a shorter one fails.
72
+ function tlv(bytes: Uint8Array, at: number): Tlv | undefined {
73
+ const tag = bytes[at]
74
+ const first = bytes[at + 1]
75
+ if (tag === undefined || first === undefined) return undefined
76
+ let length = first
77
+ let start = at + 2
78
+ if (first === 0x81 || first === 0x82) {
79
+ const size = first - 0x80
80
+ length = 0
81
+ for (let i = 0; i < size; i++) {
82
+ const byte = bytes[start + i]
83
+ if (byte === undefined) return undefined
84
+ length = length * 256 + byte
85
+ }
86
+ if (length < (size === 1 ? 0x80 : 0x100)) return undefined
87
+ start += size
88
+ } else if (first > 0x7f) return undefined
89
+ const next = start + length
90
+ return next > bytes.length ? undefined : { tag, start, next }
91
+ }
92
+
93
+ const equal = (bytes: Uint8Array, expected: ArrayLike<number>): boolean =>
94
+ bytes.length === expected.length && bytes.every((byte, i) => byte === expected[i])