typevault 0.9.0 → 0.10.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/scoped.ts +96 -7
- package/src/core/naming.ts +1 -1
- package/src/core/passkey.ts +82 -0
- package/src/core/payload.ts +3 -3
- package/src/core/vault.ts +39 -1
package/package.json
CHANGED
package/src/access/scoped.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { appendAudit, type AuditEvent, type AuditMode } from '../audit/log'
|
|
2
|
+
import { canonicalJson, type Json } from '../core/encoding'
|
|
2
3
|
import { signerOf } from '../core/entries'
|
|
3
4
|
import { TypeVaultError } from '../core/errors'
|
|
4
5
|
import { withLock } from '../core/lock'
|
|
@@ -31,6 +32,16 @@ export type ScopedIdentity = {
|
|
|
31
32
|
readonly defaultTier?: string
|
|
32
33
|
}
|
|
33
34
|
|
|
35
|
+
// Writes that keep landing during each refresh retry are a writer storm, not a race to wait out.
|
|
36
|
+
const REFRESH_ATTEMPTS = 3
|
|
37
|
+
|
|
38
|
+
// Key order means nothing in a field, so a writer that re-serializes an OAuth map must not look like a replacement.
|
|
39
|
+
const sameEnvelope = (a: StoredEntry, b: StoredEntry): boolean =>
|
|
40
|
+
canonicalJson(a.envelope as unknown as Json) === canonicalJson(b.envelope as unknown as Json)
|
|
41
|
+
|
|
42
|
+
const sameField = (a: Field | undefined, b: Field | undefined): boolean =>
|
|
43
|
+
a !== undefined && b !== undefined && canonicalJson(a as Json) === canonicalJson(b as Json)
|
|
44
|
+
|
|
34
45
|
const valueOf = (entry: StoredEntry): EntryValue =>
|
|
35
46
|
toValue(entry.envelope.tier, entry.envelope.id, entry.envelope.rev, entry.payload)
|
|
36
47
|
|
|
@@ -83,6 +94,13 @@ export class ScopedVault implements Access {
|
|
|
83
94
|
return [...byName.values()].flatMap((copies) => resolveName(this.#vault.state.tiers, copies) ?? [])
|
|
84
95
|
}
|
|
85
96
|
|
|
97
|
+
/** The copy of `name` this scope sees, chosen as `#visible` chooses it, without resolving any other name. */
|
|
98
|
+
async #visibleCopy(name: EntryName): Promise<StoredEntry | undefined> {
|
|
99
|
+
const { entries } = await this.#vault.scan()
|
|
100
|
+
const copies = entries.filter((entry) => entry.payload.name === name && this.#allows(entry))
|
|
101
|
+
return resolveName(this.#vault.state.tiers, copies)
|
|
102
|
+
}
|
|
103
|
+
|
|
86
104
|
async unreadableEntries(): Promise<number> {
|
|
87
105
|
return (await this.#vault.scan()).problems.length
|
|
88
106
|
}
|
|
@@ -134,9 +152,80 @@ export class ScopedVault implements Access {
|
|
|
134
152
|
return changed ? this.#storeRefreshed(entry, fields) : entry
|
|
135
153
|
}
|
|
136
154
|
|
|
155
|
+
/**
|
|
156
|
+
* Stores the refreshed OAuth fields of `entry`. The provider call ran outside the vault lock, so another write may
|
|
157
|
+
* have landed since `entry` was read: the write is a compare-and-swap, and after a conflict only the OAuth fields
|
|
158
|
+
* still holding the value refreshed from are replaced, leaving every other change as it was. The re-read goes
|
|
159
|
+
* through this grant's scope against the vault's current tiers, so an entry the grant lost meanwhile is neither
|
|
160
|
+
* written nor returned. A removed or replaced entry gets nothing, and neither does one whose refreshed fields were
|
|
161
|
+
* all rewritten by someone else: there is nothing left to store, so it is returned as it stands.
|
|
162
|
+
*/
|
|
137
163
|
async #storeRefreshed(entry: StoredEntry, fields: Readonly<Record<string, Field>>): Promise<StoredEntry> {
|
|
164
|
+
const refreshed = Object.entries(fields).filter(([field, value]) => value !== entry.payload.fields[field])
|
|
165
|
+
let current = entry
|
|
166
|
+
for (let attempt = 0; attempt < REFRESH_ATTEMPTS; attempt++) {
|
|
167
|
+
const read = current
|
|
168
|
+
const merged = { ...read.payload.fields }
|
|
169
|
+
let applied = false
|
|
170
|
+
for (const [field, value] of refreshed) {
|
|
171
|
+
if (!sameField(current.payload.fields[field], entry.payload.fields[field])) continue
|
|
172
|
+
merged[field] = value
|
|
173
|
+
applied = true
|
|
174
|
+
}
|
|
175
|
+
if (!applied) return current
|
|
176
|
+
try {
|
|
177
|
+
const stored = await this.#vault.put(
|
|
178
|
+
this.#refreshInput(current, merged),
|
|
179
|
+
signerOf(await this.#refreshKey(current)),
|
|
180
|
+
// A refresh replaces short-lived tokens, not the credentials a rotation warning is about.
|
|
181
|
+
{
|
|
182
|
+
copy: read.envelope.id,
|
|
183
|
+
ifRev: read.envelope.rev,
|
|
184
|
+
rotates: false,
|
|
185
|
+
// Access can be withdrawn, or another copy can come to win the name in this scope, without this copy's
|
|
186
|
+
// revision changing, so both are judged under the lock, not just here. Two writes from one sealed bundle
|
|
187
|
+
// even share an id and revision, so the copy must also be byte for byte the one this attempt read.
|
|
188
|
+
allows: (found, copies) => {
|
|
189
|
+
if (!this.#allows(found)) return false
|
|
190
|
+
const winner = resolveName(
|
|
191
|
+
this.#vault.state.tiers,
|
|
192
|
+
copies.filter((copy) => this.#allows(copy)),
|
|
193
|
+
)
|
|
194
|
+
if (winner?.envelope.id !== found.envelope.id || !sameEnvelope(found, read)) {
|
|
195
|
+
throw new TypeVaultError(
|
|
196
|
+
'conflict',
|
|
197
|
+
`${found.payload.name} changed while its token was refreshed; read it again`,
|
|
198
|
+
)
|
|
199
|
+
}
|
|
200
|
+
return true
|
|
201
|
+
},
|
|
202
|
+
},
|
|
203
|
+
)
|
|
204
|
+
await this.#audit({ action: 'refresh', entries: [entry.payload.name] })
|
|
205
|
+
return stored
|
|
206
|
+
} catch (error) {
|
|
207
|
+
if (!(error instanceof TypeVaultError) || error.code !== 'conflict') throw error
|
|
208
|
+
}
|
|
209
|
+
// The copy this grant sees, chosen as `values()` chose it, so a same-name copy in another tier never stands in.
|
|
210
|
+
const found = await this.#visibleCopy(entry.payload.name)
|
|
211
|
+
if (found === undefined) throw new TypeVaultError('not_found', `no entry named ${entry.payload.name}`)
|
|
212
|
+
if (found.envelope.id !== entry.envelope.id) {
|
|
213
|
+
throw new TypeVaultError(
|
|
214
|
+
'conflict',
|
|
215
|
+
`${entry.payload.name} changed while its token was refreshed; read it again`,
|
|
216
|
+
)
|
|
217
|
+
}
|
|
218
|
+
current = found
|
|
219
|
+
}
|
|
220
|
+
throw new TypeVaultError(
|
|
221
|
+
'conflict',
|
|
222
|
+
`${entry.payload.name} kept changing while its token was refreshed; read it again`,
|
|
223
|
+
)
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
#refreshInput(entry: StoredEntry, fields: Readonly<Record<string, Field>>) {
|
|
138
227
|
const { name, env, origin, tags } = entry.payload
|
|
139
|
-
|
|
228
|
+
return {
|
|
140
229
|
name,
|
|
141
230
|
fields,
|
|
142
231
|
tier: entry.envelope.tier,
|
|
@@ -144,8 +233,11 @@ export class ScopedVault implements Access {
|
|
|
144
233
|
...(env === undefined ? {} : { env }),
|
|
145
234
|
...(origin === undefined ? {} : { origin }),
|
|
146
235
|
}
|
|
147
|
-
|
|
148
|
-
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
// A read must not promote the original writer's metadata to the reader's authority. Reuse its owner/tier key when
|
|
239
|
+
// held; certificates and unavailable signing keys narrow to the entry's own tier.
|
|
240
|
+
async #refreshKey(entry: StoredEntry) {
|
|
149
241
|
const { signer, tier } = entry.envelope
|
|
150
242
|
const original =
|
|
151
243
|
signer.kind === 'owner'
|
|
@@ -155,10 +247,7 @@ export class ScopedVault implements Access {
|
|
|
155
247
|
: undefined
|
|
156
248
|
const key = original ?? (await this.#vault.keyring.unlock(tier))
|
|
157
249
|
if (key === undefined) throw new TypeVaultError('denied', `no key here can refresh tier "${tier}"`)
|
|
158
|
-
|
|
159
|
-
const refreshed = await this.#vault.put(input, signerOf(key), { rotates: false })
|
|
160
|
-
await this.#audit({ action: 'refresh', entries: [name] })
|
|
161
|
-
return refreshed
|
|
250
|
+
return key
|
|
162
251
|
}
|
|
163
252
|
|
|
164
253
|
#remember(value: EntryValue): EntryValue {
|
package/src/core/naming.ts
CHANGED
|
@@ -3,7 +3,7 @@ import { TypeVaultError } from './errors'
|
|
|
3
3
|
|
|
4
4
|
export type FieldType = 'secret' | 'text' | 'totp' | 'oauth' | 'passkey'
|
|
5
5
|
/**
|
|
6
|
-
* A WebAuthn credential. The ids and the PKCS#8 P-256
|
|
6
|
+
* A WebAuthn credential. The ids and the PKCS#8 private key (P-256, Ed25519 or RSA, as the site chose) are base64url without padding. A discoverable
|
|
7
7
|
* credential (a site can find it with no allow-list, for username-less sign-in) always has its user handle.
|
|
8
8
|
*/
|
|
9
9
|
export type Passkey = {
|
package/src/core/passkey.ts
CHANGED
|
@@ -8,6 +8,16 @@ const P256_ALGORITHM = hex.decode('301306072a8648ce3d020106082a8648ce3d030107')
|
|
|
8
8
|
// The prime256v1 OID, as ECPrivateKey's optional parameters repeat it.
|
|
9
9
|
const P256_CURVE = hex.decode('06082a8648ce3d030107')
|
|
10
10
|
|
|
11
|
+
// An Ed25519 key in PKCS#8 as RFC 8410 and Chromium write it: version 0, id-Ed25519, then the 32-byte seed.
|
|
12
|
+
const ED25519_PREFIX = hex.decode('302e020100300506032b657004220420')
|
|
13
|
+
// The AlgorithmIdentifier of an RSA key: rsaEncryption, then NULL parameters.
|
|
14
|
+
const RSA_ALGORITHM = hex.decode('300d06092a864886f70d0101010500')
|
|
15
|
+
// BoringSSL, which Chromium's virtual authenticator imports keys with, takes RSA moduli of 512 to 16384 bits and
|
|
16
|
+
// public exponents of at most 33 bits.
|
|
17
|
+
const MIN_RSA_BITS = 512
|
|
18
|
+
const MAX_RSA_BITS = 16_384
|
|
19
|
+
const MAX_RSA_EXPONENT_BITS = 33
|
|
20
|
+
|
|
11
21
|
// Chrome DevTools restores a credential's signature counter only up to UINT32_MAX.
|
|
12
22
|
export const MAX_SIGN_COUNT = 4_294_967_295
|
|
13
23
|
// WebAuthn, and Chrome DevTools with it, caps a user handle at 64 bytes.
|
|
@@ -27,6 +37,78 @@ export function decodeBase64Url(text: string): Uint8Array | undefined {
|
|
|
27
37
|
}
|
|
28
38
|
}
|
|
29
39
|
|
|
40
|
+
/**
|
|
41
|
+
* True for a private key Chromium's virtual authenticator creates and imports: ES256 (P-256), EdDSA (Ed25519) or
|
|
42
|
+
* RS256 (RSA), each in PKCS#8. A site picks the algorithm, so a passkey may hold any of the three.
|
|
43
|
+
*/
|
|
44
|
+
export function isPasskeyPrivateKey(pkcs8: Uint8Array): boolean {
|
|
45
|
+
return isP256PrivateKey(pkcs8) || isEd25519PrivateKey(pkcs8) || isRsaPrivateKey(pkcs8)
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function isEd25519PrivateKey(pkcs8: Uint8Array): boolean {
|
|
49
|
+
return pkcs8.length === ED25519_PREFIX.length + 32 && equal(pkcs8.subarray(0, ED25519_PREFIX.length), ED25519_PREFIX)
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
// A two-prime RSA key in DER as Chromium's BoringSSL imports it: rsaEncryption with NULL parameters, then an
|
|
53
|
+
// RSAPrivateKey of version 0 and eight minimal positive integers, nothing left over, and numbers that agree with one
|
|
54
|
+
// another the way BoringSSL's own key check requires. Pure, so the browser prompt page can bundle it.
|
|
55
|
+
function isRsaPrivateKey(pkcs8: Uint8Array): boolean {
|
|
56
|
+
const outer = tlv(pkcs8, 0)
|
|
57
|
+
if (outer?.tag !== 0x30 || outer.next !== pkcs8.length) return false
|
|
58
|
+
const version = tlv(pkcs8, outer.start)
|
|
59
|
+
if (version?.tag !== 0x02 || !equal(pkcs8.subarray(version.start, version.next), [0x00])) return false
|
|
60
|
+
const algorithm = tlv(pkcs8, version.next)
|
|
61
|
+
if (algorithm?.tag !== 0x30 || !equal(pkcs8.subarray(version.next, algorithm.next), RSA_ALGORITHM)) return false
|
|
62
|
+
const wrapped = tlv(pkcs8, algorithm.next)
|
|
63
|
+
if (wrapped?.tag !== 0x04 || wrapped.next !== outer.next) return false
|
|
64
|
+
const rsaKey = tlv(pkcs8, wrapped.start)
|
|
65
|
+
if (rsaKey?.tag !== 0x30 || rsaKey.next !== wrapped.next) return false
|
|
66
|
+
const numbers: bigint[] = []
|
|
67
|
+
let at = rsaKey.start
|
|
68
|
+
for (let i = 0; i < 9; i++) {
|
|
69
|
+
const field = tlv(pkcs8, at)
|
|
70
|
+
if (field?.tag !== 0x02 || field.next > rsaKey.next) return false
|
|
71
|
+
const value = positiveInteger(pkcs8.subarray(field.start, field.next), i === 0)
|
|
72
|
+
if (value === undefined) return false
|
|
73
|
+
numbers.push(value)
|
|
74
|
+
at = field.next
|
|
75
|
+
}
|
|
76
|
+
if (at !== rsaKey.next) return false
|
|
77
|
+
const [keyVersion, n, e, d, p, q, dp, dq, qi] = numbers as [
|
|
78
|
+
bigint,
|
|
79
|
+
bigint,
|
|
80
|
+
bigint,
|
|
81
|
+
bigint,
|
|
82
|
+
bigint,
|
|
83
|
+
bigint,
|
|
84
|
+
bigint,
|
|
85
|
+
bigint,
|
|
86
|
+
bigint,
|
|
87
|
+
]
|
|
88
|
+
const bits = n.toString(2).length
|
|
89
|
+
if (keyVersion !== 0n || bits < MIN_RSA_BITS || bits > MAX_RSA_BITS || n % 2n === 0n) return false
|
|
90
|
+
if (e.toString(2).length > MAX_RSA_EXPONENT_BITS || d >= n) return false
|
|
91
|
+
if (p <= 1n || q <= 1n || p * q !== n || e < 3n || e % 2n === 0n) return false
|
|
92
|
+
return (
|
|
93
|
+
(e * d) % (p - 1n) === 1n % (p - 1n) &&
|
|
94
|
+
(e * d) % (q - 1n) === 1n % (q - 1n) &&
|
|
95
|
+
dp === d % (p - 1n) &&
|
|
96
|
+
dq === d % (q - 1n) &&
|
|
97
|
+
qi < p &&
|
|
98
|
+
(qi * q) % p === 1n
|
|
99
|
+
)
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
// A DER INTEGER's content as a non-negative number: minimal (no needless leading zero byte) and not negative. Only the
|
|
103
|
+
// version may be zero.
|
|
104
|
+
function positiveInteger(content: Uint8Array, mayBeZero: boolean): bigint | undefined {
|
|
105
|
+
const first = content[0]
|
|
106
|
+
if (first === undefined || first >= 0x80) return undefined
|
|
107
|
+
if (first === 0x00 && content.length > 1 && (content[1] ?? 0) < 0x80) return undefined
|
|
108
|
+
const value = BigInt(`0x${hex.encode(content)}`)
|
|
109
|
+
return value === 0n && !mayBeZero ? undefined : value
|
|
110
|
+
}
|
|
111
|
+
|
|
30
112
|
/**
|
|
31
113
|
* True for a PKCS#8 ECDSA P-256 private key that Chromium's virtual authenticator imports: BoringSSL's parser reads
|
|
32
114
|
* every field, so the whole structure is checked, not just the scalar. That is a 32-byte scalar in range, the curve
|
package/src/core/payload.ts
CHANGED
|
@@ -3,7 +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,
|
|
6
|
+
import { decodeBase64Url, isPasskeyPrivateKey, isUserHandle, MAX_SIGN_COUNT } from './passkey'
|
|
7
7
|
|
|
8
8
|
/** The plaintext sealed inside an entry file: everything except the tier is secret. */
|
|
9
9
|
export type EntryPayload = {
|
|
@@ -45,8 +45,8 @@ export const FieldSchema = z.discriminatedUnion('type', [
|
|
|
45
45
|
credential_id: Base64UrlSchema,
|
|
46
46
|
private_key: z.string().refine((key) => {
|
|
47
47
|
const bytes = decodeBase64Url(key)
|
|
48
|
-
return bytes !== undefined &&
|
|
49
|
-
}, 'expected a PKCS#8 P-256 private key in base64url'),
|
|
48
|
+
return bytes !== undefined && isPasskeyPrivateKey(bytes)
|
|
49
|
+
}, 'expected a PKCS#8 P-256, Ed25519 or RSA private key in base64url'),
|
|
50
50
|
discoverable: z.boolean(),
|
|
51
51
|
user_handle: z
|
|
52
52
|
.string()
|
package/src/core/vault.ts
CHANGED
|
@@ -45,6 +45,18 @@ export type PutOptions = {
|
|
|
45
45
|
readonly ifId?: string
|
|
46
46
|
/** False for a write that changes fields without rotating the entry's credentials (an OAuth refresh, a counter). */
|
|
47
47
|
readonly rotates?: boolean
|
|
48
|
+
/**
|
|
49
|
+
* Replace exactly the copy with this id instead of the copy the name resolves to: a scoped writer's own copy of a
|
|
50
|
+
* name that several tiers hold. A copy no longer stored is a conflict.
|
|
51
|
+
*/
|
|
52
|
+
readonly copy?: string
|
|
53
|
+
/**
|
|
54
|
+
* Judges the copy being replaced under the write lock, against the state that lock just loaded, given every verified
|
|
55
|
+
* copy of the name: a scoped writer's own check that it may still write that copy, and that the copy is still the
|
|
56
|
+
* one its scope resolves the name to. An owner-backed vault would otherwise pass any copy it can open. Refused is
|
|
57
|
+
* not found.
|
|
58
|
+
*/
|
|
59
|
+
readonly allows?: (found: StoredEntry, copies: readonly StoredEntry[]) => boolean
|
|
48
60
|
readonly base?: EntryBase
|
|
49
61
|
}
|
|
50
62
|
|
|
@@ -69,6 +81,12 @@ function parseJson(bytes: Uint8Array): unknown {
|
|
|
69
81
|
}
|
|
70
82
|
}
|
|
71
83
|
|
|
84
|
+
function copyIn(copies: readonly StoredEntry[], name: EntryName, id: string): StoredEntry {
|
|
85
|
+
const copy = copies.find((entry) => entry.envelope.id === id)
|
|
86
|
+
if (copy === undefined) throw new TypeVaultError('conflict', `${name} no longer has the copy ${id}`)
|
|
87
|
+
return copy
|
|
88
|
+
}
|
|
89
|
+
|
|
72
90
|
const sameFields = (a: Readonly<Record<string, Field>>, b: Readonly<Record<string, Field>>): boolean =>
|
|
73
91
|
JSON.stringify(Object.entries(a).sort()) === JSON.stringify(Object.entries(b).sort())
|
|
74
92
|
|
|
@@ -247,6 +265,11 @@ export class Vault {
|
|
|
247
265
|
)
|
|
248
266
|
}
|
|
249
267
|
|
|
268
|
+
async #copies(name: EntryName): Promise<readonly StoredEntry[]> {
|
|
269
|
+
const { entries } = await this.scan()
|
|
270
|
+
return entries.filter((entry) => entry.payload.name === name)
|
|
271
|
+
}
|
|
272
|
+
|
|
250
273
|
/** The envelope that writing `input` over `found` (or a blind writer's `base`) produces. */
|
|
251
274
|
async #draft(
|
|
252
275
|
input: EntryInput,
|
|
@@ -292,7 +315,22 @@ export class Vault {
|
|
|
292
315
|
*/
|
|
293
316
|
put(input: EntryInput, signer: SignerContext, options: PutOptions = {}): Promise<StoredEntry> {
|
|
294
317
|
return withLock(this.layout.lockFile, 'exclusive', async () => {
|
|
295
|
-
const
|
|
318
|
+
const copies =
|
|
319
|
+
options.copy === undefined && options.allows === undefined ? undefined : await this.#copies(input.name)
|
|
320
|
+
const found =
|
|
321
|
+
copies === undefined
|
|
322
|
+
? await this.find(input.name)
|
|
323
|
+
: options.copy === undefined
|
|
324
|
+
? resolveName(this.#state.tiers, copies)
|
|
325
|
+
: copyIn(copies, input.name, options.copy)
|
|
326
|
+
if (
|
|
327
|
+
found !== undefined &&
|
|
328
|
+
copies !== undefined &&
|
|
329
|
+
options.allows !== undefined &&
|
|
330
|
+
!options.allows(found, copies)
|
|
331
|
+
) {
|
|
332
|
+
throw new TypeVaultError('not_found', `no entry named ${input.name}`)
|
|
333
|
+
}
|
|
296
334
|
const stored = await this.#draft(input, found, options, signer)
|
|
297
335
|
atomicWrite(
|
|
298
336
|
join(this.layout.entries, `${stored.envelope.id}.json`),
|