typevault 0.7.1 → 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 +1 -1
- package/src/access/env.ts +1 -0
- package/src/access/scoped.ts +1 -0
- package/src/cli/commands/entries.ts +12 -5
- package/src/cli/context.ts +36 -13
- package/src/cli/index.ts +4 -1
- package/src/cli/requester.ts +240 -0
- package/src/core/identity.ts +7 -2
- package/src/core/naming.ts +30 -1
- package/src/core/passkey.ts +94 -0
- package/src/core/payload.ts +31 -0
- package/src/core/touch-id.ts +2 -1
- package/src/import/bitwarden.ts +68 -0
- package/src/import/shared.ts +5 -1
- package/src/index.ts +1 -0
- package/src/prompt/browser.ts +1 -0
package/package.json
CHANGED
package/src/access/env.ts
CHANGED
package/src/access/scoped.ts
CHANGED
|
@@ -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',
|
|
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(
|
|
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')
|
package/src/cli/context.ts
CHANGED
|
@@ -32,6 +32,7 @@ import { ensureDaemon, LOCKED_MESSAGE, startSession, stopDaemon } from '../daemo
|
|
|
32
32
|
import { note } from './output'
|
|
33
33
|
import { ownerChange } from './owner-change'
|
|
34
34
|
import { type Passwords, passwords, passwordsFromStdin } from './password'
|
|
35
|
+
import { promptHeader, touchIdReason, UNLOCK, unlockRequest } from './requester'
|
|
35
36
|
|
|
36
37
|
export type Env = Readonly<Record<string, string | undefined>>
|
|
37
38
|
|
|
@@ -65,33 +66,41 @@ export function layoutFrom(env: Env, cwd: string = process.cwd()): Layout {
|
|
|
65
66
|
* The vault opened with this member's own key: direct mode, for owners and issuers. A machine member's key is at
|
|
66
67
|
* hand; a human types their password, since only the daemon keeps an unlocked key around.
|
|
67
68
|
*/
|
|
68
|
-
export async function openDirect(env: Env): Promise<Vault> {
|
|
69
|
+
export async function openDirect(env: Env, purpose = UNLOCK): Promise<Vault> {
|
|
69
70
|
const layout = layoutFrom(env)
|
|
70
71
|
const machine = machineKeys(env)
|
|
71
72
|
const identity = readIdentity(env)
|
|
72
73
|
if (machine.length === 0 && identity === undefined) {
|
|
73
74
|
throw new TypeVaultError('denied', 'no grant and no identity here (set TYPEVAULT_GRANT, or run typevault join)')
|
|
74
75
|
}
|
|
75
|
-
const keys = machine.length > 0 ? machine : [await unlockHuman(env, identity, passwords())]
|
|
76
|
+
const keys = machine.length > 0 ? machine : [await unlockHuman(env, identity, passwords(), purpose)]
|
|
76
77
|
return Vault.open(layout, keys, env)
|
|
77
78
|
}
|
|
78
79
|
|
|
79
80
|
/**
|
|
80
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
|
|
81
82
|
* ID fails) their password. Without a terminal it stays the password's error, so an agent can't raise the dialog.
|
|
82
|
-
* 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`.
|
|
83
85
|
*/
|
|
84
|
-
export async function unlockHuman(
|
|
86
|
+
export async function unlockHuman(
|
|
87
|
+
env: Env,
|
|
88
|
+
identity: Identity | undefined,
|
|
89
|
+
passwords: Passwords,
|
|
90
|
+
purpose = UNLOCK,
|
|
91
|
+
): Promise<SecretKey> {
|
|
85
92
|
if (identity === undefined) throw new TypeVaultError('not_found', 'no identity here (run typevault init or join)')
|
|
86
93
|
if (identity.kind === 'machine') return unlockIdentity(identity)
|
|
87
|
-
const
|
|
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
|
|
88
97
|
if (identity.touchId === undefined) {
|
|
89
98
|
// The tip is optional: a probe that fails must not stand between the person and their password prompt.
|
|
90
99
|
const tip = atThisMac && (await touchIdAvailable().catch(() => false))
|
|
91
100
|
if (tip) note('tip: skip the password next time with `typevault touch-id enable`')
|
|
92
101
|
} else if (atThisMac) {
|
|
93
102
|
try {
|
|
94
|
-
return await unlockIdentityWithTouchId(env, identity, identity.touchId)
|
|
103
|
+
return await unlockIdentityWithTouchId(env, identity, identity.touchId, touchIdReason(request))
|
|
95
104
|
} catch (error) {
|
|
96
105
|
if (!(error instanceof TypeVaultError)) throw error
|
|
97
106
|
note(`${error.message}; asking for your password instead`)
|
|
@@ -100,6 +109,7 @@ export async function unlockHuman(env: Env, identity: Identity | undefined, pass
|
|
|
100
109
|
}
|
|
101
110
|
}
|
|
102
111
|
}
|
|
112
|
+
if (request !== undefined) note(promptHeader(request))
|
|
103
113
|
return unlockIdentity(identity, await passwords.ask(`Password for ${identity.name}: `))
|
|
104
114
|
}
|
|
105
115
|
|
|
@@ -107,11 +117,16 @@ export async function unlockHuman(env: Env, identity: Identity | undefined, pass
|
|
|
107
117
|
* Unlocks a human member's session: their key goes to a daemon that holds it for `ttlMs`, and this user's CLI
|
|
108
118
|
* reads through the session grant it writes. Returns the key it unlocked with, or undefined when a session already runs.
|
|
109
119
|
*/
|
|
110
|
-
export async function unlockSession(
|
|
120
|
+
export async function unlockSession(
|
|
121
|
+
env: Env,
|
|
122
|
+
passwords: Passwords,
|
|
123
|
+
ttlMs: number,
|
|
124
|
+
purpose = UNLOCK,
|
|
125
|
+
): Promise<SecretKey | undefined> {
|
|
111
126
|
const layout = layoutFrom(env)
|
|
112
127
|
if (await hasSession(layout)) return undefined
|
|
113
128
|
const identity = readIdentity(env)
|
|
114
|
-
const key = await unlockHuman(env, identity, passwords)
|
|
129
|
+
const key = await unlockHuman(env, identity, passwords, purpose)
|
|
115
130
|
const vault = await Vault.open(layout, [key], env)
|
|
116
131
|
if (vault.member === undefined) {
|
|
117
132
|
throw new TypeVaultError(
|
|
@@ -179,7 +194,9 @@ export const openPublic = (env: Env): Promise<Vault> => Vault.open(layoutFrom(en
|
|
|
179
194
|
*/
|
|
180
195
|
export async function runAdmin(env: Env, request: AdminOp): Promise<AdminResult> {
|
|
181
196
|
const direct = machineKeys(env).length > 0 || isSet(env['TYPEVAULT_GRANT'])
|
|
182
|
-
const result = direct
|
|
197
|
+
const result = direct
|
|
198
|
+
? await runAdminOp(await openDirect(env, OWNER_CHANGE), request)
|
|
199
|
+
: await sessionAdmin(env, request)
|
|
183
200
|
if (!result.reloaded) {
|
|
184
201
|
note(
|
|
185
202
|
'the change committed, but the vault could not be reloaded after it: run typevault lock, then typevault unlock',
|
|
@@ -189,7 +206,8 @@ export async function runAdmin(env: Env, request: AdminOp): Promise<AdminResult>
|
|
|
189
206
|
}
|
|
190
207
|
|
|
191
208
|
async function sessionAdmin(env: Env, request: AdminOp): Promise<AdminResult> {
|
|
192
|
-
|
|
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)
|
|
193
211
|
const { open, nonce } = await access.call('/v1/admin/challenge', {}, ChallengeSchema)
|
|
194
212
|
const key = open ? undefined : (unlockedWith ?? (await ownerKey(env)))
|
|
195
213
|
const proof = key === undefined ? undefined : { nonce, signature: sign(key.signSecret, ownerWindowMessage(nonce)) }
|
|
@@ -208,9 +226,11 @@ async function ownerKey(env: Env): Promise<SecretKey> {
|
|
|
208
226
|
if (!process.stdin.isTTY && !passwordsFromStdin()) {
|
|
209
227
|
throw new TypeVaultError('locked', 'owner changes need your password or Touch ID: run this at a terminal')
|
|
210
228
|
}
|
|
211
|
-
return unlockHuman(env, readIdentity(env), passwords())
|
|
229
|
+
return unlockHuman(env, readIdentity(env), passwords(), OWNER_CHANGE)
|
|
212
230
|
}
|
|
213
231
|
|
|
232
|
+
const OWNER_CHANGE = 'approve an owner change'
|
|
233
|
+
|
|
214
234
|
export type ResolvedAccess =
|
|
215
235
|
| { readonly kind: 'live'; readonly access: LiveAccess }
|
|
216
236
|
| { readonly kind: 'sealed'; readonly access: SealedAccess }
|
|
@@ -245,7 +265,10 @@ export async function resolveAccess(env: Env): Promise<ResolvedAccess> {
|
|
|
245
265
|
* password right away; anywhere else (an agent) it stays locked until a human unlocks it. `unlockedWith` is the key a
|
|
246
266
|
* person just unlocked with here.
|
|
247
267
|
*/
|
|
248
|
-
async function sessionAccess(
|
|
268
|
+
async function sessionAccess(
|
|
269
|
+
env: Env,
|
|
270
|
+
purpose = UNLOCK,
|
|
271
|
+
): Promise<{ readonly access: LiveAccess; readonly unlockedWith?: SecretKey }> {
|
|
249
272
|
const layout = layoutFrom(env)
|
|
250
273
|
await checkOwnerPin(layout, env)
|
|
251
274
|
let unlockedWith: SecretKey | undefined
|
|
@@ -256,7 +279,7 @@ async function sessionAccess(env: Env): Promise<{ readonly access: LiveAccess; r
|
|
|
256
279
|
}
|
|
257
280
|
const canAsk = process.stdin.isTTY || passwordsFromStdin()
|
|
258
281
|
if (identity.kind !== 'human' || !canAsk) throw new TypeVaultError('locked', LOCKED_MESSAGE)
|
|
259
|
-
unlockedWith = await unlockSession(env, passwords(), DEFAULT_SESSION_MS)
|
|
282
|
+
unlockedWith = await unlockSession(env, passwords(), DEFAULT_SESSION_MS, purpose)
|
|
260
283
|
}
|
|
261
284
|
// A session daemon from another release fails here instead of misreading this CLI's requests.
|
|
262
285
|
await ensureDaemon(layout, env)
|
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
|
-
|
|
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,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/identity.ts
CHANGED
|
@@ -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(
|
|
129
|
-
|
|
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")
|
package/src/core/naming.ts
CHANGED
|
@@ -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])
|
package/src/core/payload.ts
CHANGED
|
@@ -3,6 +3,7 @@ import { z } from 'zod'
|
|
|
3
3
|
import { fromUtf8, utf8 } from './encoding'
|
|
4
4
|
import { TypeVaultError } from './errors'
|
|
5
5
|
import { type EntryName, type Field, isFieldName, isUsableEnvName, parseEntryName } from './naming'
|
|
6
|
+
import { decodeBase64Url, isP256PrivateKey, isUserHandle, MAX_SIGN_COUNT } from './passkey'
|
|
6
7
|
|
|
7
8
|
/** The plaintext sealed inside an entry file: everything except the tier is secret. */
|
|
8
9
|
export type EntryPayload = {
|
|
@@ -19,6 +20,10 @@ export type EntryPayload = {
|
|
|
19
20
|
readonly needsRotation?: boolean
|
|
20
21
|
}
|
|
21
22
|
|
|
23
|
+
const Base64UrlSchema = z
|
|
24
|
+
.string()
|
|
25
|
+
.refine((text) => decodeBase64Url(text) !== undefined, 'expected canonical base64url without padding')
|
|
26
|
+
|
|
22
27
|
export const FieldSchema = z.discriminatedUnion('type', [
|
|
23
28
|
z.object({ type: z.literal('secret'), value: z.string() }).strict(),
|
|
24
29
|
z.object({ type: z.literal('text'), value: z.string() }).strict(),
|
|
@@ -31,6 +36,32 @@ export const FieldSchema = z.discriminatedUnion('type', [
|
|
|
31
36
|
.refine((value) => typeof value['access_token'] === 'string', 'OAuth requires access_token'),
|
|
32
37
|
})
|
|
33
38
|
.strict(),
|
|
39
|
+
z
|
|
40
|
+
.object({
|
|
41
|
+
type: z.literal('passkey'),
|
|
42
|
+
value: z
|
|
43
|
+
.object({
|
|
44
|
+
rp_id: z.string().min(1),
|
|
45
|
+
credential_id: Base64UrlSchema,
|
|
46
|
+
private_key: z.string().refine((key) => {
|
|
47
|
+
const bytes = decodeBase64Url(key)
|
|
48
|
+
return bytes !== undefined && isP256PrivateKey(bytes)
|
|
49
|
+
}, 'expected a PKCS#8 P-256 private key in base64url'),
|
|
50
|
+
discoverable: z.boolean(),
|
|
51
|
+
user_handle: z
|
|
52
|
+
.string()
|
|
53
|
+
.refine(isUserHandle, 'expected a user handle of at most 64 bytes in canonical base64url')
|
|
54
|
+
.exactOptional(),
|
|
55
|
+
user_name: z.string().exactOptional(),
|
|
56
|
+
sign_count: z.number().int().nonnegative().max(MAX_SIGN_COUNT).exactOptional(),
|
|
57
|
+
})
|
|
58
|
+
.strict()
|
|
59
|
+
.refine(
|
|
60
|
+
(value) => !value.discoverable || value.user_handle !== undefined,
|
|
61
|
+
'a discoverable passkey needs its user_handle',
|
|
62
|
+
),
|
|
63
|
+
})
|
|
64
|
+
.strict(),
|
|
34
65
|
])
|
|
35
66
|
export const FieldsSchema = z.record(z.string().refine(isFieldName), FieldSchema)
|
|
36
67
|
|
package/src/core/touch-id.ts
CHANGED
|
@@ -81,7 +81,8 @@ export async function touchIdAvailable(): Promise<boolean> {
|
|
|
81
81
|
return hasTouchId()
|
|
82
82
|
}
|
|
83
83
|
|
|
84
|
-
|
|
84
|
+
/** `reason` completes the dialog's "typevault is trying to <reason>." */
|
|
85
|
+
export async function openWithTouchId(env: Env, seal: TouchIdSeal, reason: string): Promise<Uint8Array> {
|
|
85
86
|
const { exchangeWithEnclave } = await import('./secure-enclave')
|
|
86
87
|
return openFromEnclave(seal, (handle, ephemeral) => exchangeWithEnclave(env, handle, ephemeral, reason))
|
|
87
88
|
}
|
package/src/import/bitwarden.ts
CHANGED
|
@@ -1,6 +1,10 @@
|
|
|
1
|
+
import { hex } from '@scure/base'
|
|
1
2
|
import { z } from 'zod'
|
|
2
3
|
|
|
4
|
+
import { toBase64Url } from '../core/encoding'
|
|
3
5
|
import { TypeVaultError } from '../core/errors'
|
|
6
|
+
import type { Field, Passkey } from '../core/naming'
|
|
7
|
+
import { decodeBase64Url, isP256PrivateKey, isUserHandle, MAX_SIGN_COUNT } from '../core/passkey'
|
|
4
8
|
import { collectEntries, parseExternal, parseJson, type ImportItem } from './shared'
|
|
5
9
|
import type { ImportResult } from './types'
|
|
6
10
|
|
|
@@ -16,11 +20,24 @@ const ItemSchema = z.object({
|
|
|
16
20
|
password: TextSchema,
|
|
17
21
|
totp: TextSchema,
|
|
18
22
|
uris: z.array(z.object({ uri: TextSchema })).nullish(),
|
|
23
|
+
// Checked in the login branch, so a malformed passkey list costs only itself, not its login or the import.
|
|
24
|
+
fido2Credentials: z.unknown().optional(),
|
|
19
25
|
})
|
|
20
26
|
.nullish(),
|
|
21
27
|
sshKey: z.object({ privateKey: TextSchema, publicKey: TextSchema }).nullish(),
|
|
22
28
|
})
|
|
23
29
|
const ExportSchema = z.object({ items: z.array(ItemSchema) })
|
|
30
|
+
const CredentialSchema = z.object({
|
|
31
|
+
credentialId: z.string(),
|
|
32
|
+
keyAlgorithm: TextSchema,
|
|
33
|
+
keyCurve: TextSchema,
|
|
34
|
+
keyValue: z.string(),
|
|
35
|
+
rpId: z.string(),
|
|
36
|
+
userHandle: TextSchema,
|
|
37
|
+
userName: TextSchema,
|
|
38
|
+
counter: TextSchema,
|
|
39
|
+
discoverable: TextSchema,
|
|
40
|
+
})
|
|
24
41
|
|
|
25
42
|
export function parseBitwarden(text: string): ImportResult {
|
|
26
43
|
const raw = parseJson(text, z.object({ encrypted: z.boolean().optional() }).passthrough(), 'Bitwarden')
|
|
@@ -35,6 +52,19 @@ export function parseBitwarden(text: string): ImportResult {
|
|
|
35
52
|
switch (item.type) {
|
|
36
53
|
case 1: {
|
|
37
54
|
const url = item.login?.uris?.find((uri) => uri.uri)?.uri ?? undefined
|
|
55
|
+
const passkeys: Record<string, Field> = {}
|
|
56
|
+
const list = item.login?.fido2Credentials ?? []
|
|
57
|
+
if (!Array.isArray(list)) warnings.push("skipped a Bitwarden login's passkeys: they are not a list")
|
|
58
|
+
for (const raw of Array.isArray(list) ? list : []) {
|
|
59
|
+
const credential = CredentialSchema.safeParse(raw)
|
|
60
|
+
const value = credential.success ? passkeyOf(credential.data) : undefined
|
|
61
|
+
if (value === undefined) {
|
|
62
|
+
warnings.push('skipped a Bitwarden passkey that is not a usable P-256 key with a readable id')
|
|
63
|
+
continue
|
|
64
|
+
}
|
|
65
|
+
const count = Object.keys(passkeys).length
|
|
66
|
+
passkeys[count === 0 ? 'passkey' : `passkey_${count + 1}`] = { type: 'passkey', value }
|
|
67
|
+
}
|
|
38
68
|
items.push({
|
|
39
69
|
...common,
|
|
40
70
|
preset: 'password',
|
|
@@ -43,6 +73,7 @@ export function parseBitwarden(text: string): ImportResult {
|
|
|
43
73
|
password: item.login?.password ?? undefined,
|
|
44
74
|
totp: item.login?.totp ?? undefined,
|
|
45
75
|
url,
|
|
76
|
+
...passkeys,
|
|
46
77
|
},
|
|
47
78
|
...(url === undefined ? {} : { url }),
|
|
48
79
|
})
|
|
@@ -67,3 +98,40 @@ export function parseBitwarden(text: string): ImportResult {
|
|
|
67
98
|
}
|
|
68
99
|
return collectEntries(items, warnings)
|
|
69
100
|
}
|
|
101
|
+
|
|
102
|
+
const GUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
|
|
103
|
+
|
|
104
|
+
function passkeyOf(credential: z.infer<typeof CredentialSchema>): Passkey | undefined {
|
|
105
|
+
if (credential.keyAlgorithm !== 'ECDSA' || credential.keyCurve !== 'P-256' || credential.rpId === '') return undefined
|
|
106
|
+
const id = credentialIdOf(credential.credentialId)
|
|
107
|
+
const key = base64url(credential.keyValue)
|
|
108
|
+
if (id === undefined || key === undefined || !isP256PrivateKey(decodeBase64Url(key) ?? new Uint8Array()))
|
|
109
|
+
return undefined
|
|
110
|
+
const normalized = credential.userHandle ? base64url(credential.userHandle) : undefined
|
|
111
|
+
const handle = normalized !== undefined && isUserHandle(normalized) ? normalized : undefined
|
|
112
|
+
const discoverable = credential.discoverable === 'true'
|
|
113
|
+
if ((credential.userHandle && handle === undefined) || (discoverable && handle === undefined)) return undefined
|
|
114
|
+
// A counter Chrome can't restore makes the passkey unusable; resetting it would look like a cloned key to the site.
|
|
115
|
+
const counter = credential.counter ? Number(credential.counter) : 0
|
|
116
|
+
if (!Number.isSafeInteger(counter) || counter < 0 || counter > MAX_SIGN_COUNT) return undefined
|
|
117
|
+
return {
|
|
118
|
+
rp_id: credential.rpId,
|
|
119
|
+
credential_id: id,
|
|
120
|
+
private_key: key,
|
|
121
|
+
discoverable,
|
|
122
|
+
...(handle === undefined ? {} : { user_handle: handle }),
|
|
123
|
+
...(credential.userName ? { user_name: credential.userName } : {}),
|
|
124
|
+
...(counter > 0 ? { sign_count: counter } : {}),
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
// Bitwarden keeps a credential id it generated as a GUID of the raw 16 bytes, and any other id as `b64.<base64url>`.
|
|
129
|
+
function credentialIdOf(id: string): string | undefined {
|
|
130
|
+
if (id.startsWith('b64.')) return base64url(id.slice(4))
|
|
131
|
+
return GUID.test(id) ? toBase64Url(hex.decode(id.replaceAll('-', '').toLowerCase())) : undefined
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
function base64url(text: string): string | undefined {
|
|
135
|
+
const value = text.replaceAll('+', '-').replaceAll('/', '_').replace(/=+$/, '')
|
|
136
|
+
return decodeBase64Url(value) === undefined ? undefined : value
|
|
137
|
+
}
|
package/src/import/shared.ts
CHANGED
|
@@ -81,7 +81,11 @@ export function collectEntries(items: readonly ImportItem[], warnings: readonly
|
|
|
81
81
|
fields[field] = { type, value }
|
|
82
82
|
break
|
|
83
83
|
case 'oauth':
|
|
84
|
-
|
|
84
|
+
case 'passkey':
|
|
85
|
+
throw new TypeVaultError(
|
|
86
|
+
'invalid',
|
|
87
|
+
`${type === 'oauth' ? 'OAuth' : 'Passkey'} import requires typed fields`,
|
|
88
|
+
)
|
|
85
89
|
default:
|
|
86
90
|
throw new TypeVaultError('invalid', `unexpected field type ${type satisfies never}`)
|
|
87
91
|
}
|
package/src/index.ts
CHANGED
package/src/prompt/browser.ts
CHANGED
|
@@ -110,6 +110,7 @@ function initialize(): void {
|
|
|
110
110
|
const type = types[input.name] ?? 'secret'
|
|
111
111
|
switch (type) {
|
|
112
112
|
case 'oauth':
|
|
113
|
+
case 'passkey':
|
|
113
114
|
return [input.name, FieldSchema.parse({ type, value: JSON.parse(input.value) })]
|
|
114
115
|
case 'secret':
|
|
115
116
|
case 'text':
|