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,41 @@
1
+ import { randomToken, verifySignature } from '../core/crypto'
2
+ import { utf8 } from '../core/encoding'
3
+ import { TypeVaultError } from '../core/errors'
4
+
5
+ export const OWNER_WINDOW_MS = 5 * 60_000
6
+ const CHALLENGE_TTL_MS = 5 * 60_000
7
+
8
+ export const ownerWindowMessage = (nonce: string): Uint8Array => utf8(`typevault owner window ${nonce}`)
9
+
10
+ /**
11
+ * Agents run as the same user and can read the session token, so a session alone never makes owner changes: they go
12
+ * through only within a few minutes of a proof, a challenge signed with the member's own key, which only an owner
13
+ * command makes. It starts closed, so an unlock for reading opens nothing. A chain of owner commands asks once; an
14
+ * agent can't open the window itself.
15
+ */
16
+ export class OwnerWindow {
17
+ #until = 0
18
+ readonly #challenges = new Map<string, number>()
19
+
20
+ get isOpen(): boolean {
21
+ return Date.now() < this.#until
22
+ }
23
+
24
+ challenge(): string {
25
+ const now = Date.now()
26
+ for (const [nonce, exp] of this.#challenges) if (exp <= now) this.#challenges.delete(nonce)
27
+ const nonce = randomToken(16)
28
+ this.#challenges.set(nonce, now + CHALLENGE_TTL_MS)
29
+ return nonce
30
+ }
31
+
32
+ /** Each challenge works once, so a captured proof can't reopen the window. */
33
+ open(nonce: string, signature: string, signPublic: string): void {
34
+ const exp = this.#challenges.get(nonce)
35
+ this.#challenges.delete(nonce)
36
+ if (exp === undefined || exp <= Date.now() || !verifySignature(signPublic, ownerWindowMessage(nonce), signature)) {
37
+ throw new TypeVaultError('denied', 'that proof does not allow owner changes')
38
+ }
39
+ this.#until = Date.now() + OWNER_WINDOW_MS
40
+ }
41
+ }
@@ -2,6 +2,7 @@ import { z } from 'zod'
2
2
 
3
3
  import { isPreset, parseEntryName } from '../core/naming'
4
4
  import { FieldsSchema } from '../core/payload'
5
+ import { OwnerChangeId } from './owner-changes'
5
6
 
6
7
  const name = z.string().transform((value) => parseEntryName(value))
7
8
  const preset = z.string().refine(isPreset, 'unknown preset').optional()
@@ -51,3 +52,46 @@ export const GrantBody = z.object({
51
52
  })
52
53
  export const RevokeBody = z.object({ id: z.string().optional(), label: z.string().optional() })
53
54
  export const AuditBody = z.object({ label: z.string().optional() })
55
+ const named = z.object({
56
+ op: z.enum(['tier.add', 'tier.rm', 'key.rotate', 'ceiling.rm', 'signer.rm', 'member.rm']),
57
+ name: z.string(),
58
+ })
59
+ export const AdminBody = z.object({
60
+ request: z.union([
61
+ named,
62
+ z.object({ op: z.enum(['tier.include', 'tier.exclude']), tier: z.string(), included: z.string() }),
63
+ z.object({ op: z.literal('ceiling.set'), name: z.string(), tier: z.string() }),
64
+ z.object({ op: z.literal('signer.add'), id: z.string(), publicKey: z.string(), tiers }),
65
+ z.object({ op: z.literal('member.add'), name: z.string(), publicKey: z.string(), owner: z.boolean(), tiers }),
66
+ ]),
67
+ proof: z.object({ nonce: z.string().max(64), signature: z.string().max(200) }).optional(),
68
+ /** The caller's own id for this change: admitting it again changes nothing. */
69
+ change: OwnerChangeId,
70
+ })
71
+ export const AdminResultSchema = z.object({
72
+ affected: z.array(z.string()),
73
+ removed: z.array(z.string()),
74
+ ownerRotated: z.boolean(),
75
+ /** False when the change committed but the session's vault couldn't be reloaded after it. */
76
+ reloaded: z.boolean(),
77
+ /** Ceilings the change set whose admin sockets the session couldn't open. */
78
+ unserved: z.array(z.string()),
79
+ /** False when the change committed but the session's grant couldn't be widened to the tiers it now reaches. */
80
+ scopeRefreshed: z.boolean(),
81
+ })
82
+ export const ChallengeSchema = z.object({ open: z.boolean(), nonce: z.string() })
83
+ export const AdmittedSchema = z.object({ change: OwnerChangeId })
84
+ export const AdminWaitBody = z.object({
85
+ change: OwnerChangeId,
86
+ waitMs: z.number().int().min(0).max(5_000).optional(),
87
+ })
88
+ export const AdminWaitedSchema = z.discriminatedUnion('state', [
89
+ z.object({ state: z.literal('running') }),
90
+ /** No receipt for that id: never admitted, or past its window. */
91
+ z.object({ state: z.literal('unknown') }),
92
+ z.object({ state: z.literal('done'), result: AdminResultSchema }),
93
+ /** The change itself failed with this error. */
94
+ z.object({ state: z.literal('failed'), error: z.object({ code: z.string(), message: z.string() }) }),
95
+ /** Committed by its marker but not yet written: the vault finishes it when next opened. */
96
+ z.object({ state: z.literal('uncertain'), error: z.object({ code: z.string(), message: z.string() }) }),
97
+ ])
@@ -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
+ }
@@ -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
- throw new TypeVaultError('invalid', 'OAuth import requires typed fields')
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
@@ -9,6 +9,7 @@ export {
9
9
  type EntryRef,
10
10
  type FieldType,
11
11
  type Field,
12
+ type Passkey,
12
13
  type Preset,
13
14
  PRESETS,
14
15
  defaultField,
@@ -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':