@noy-db/on-recovery 0.7.0-pre.9 → 0.7.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.
Files changed (2) hide show
  1. package/README.md +63 -99
  2. package/package.json +4 -3
package/README.md CHANGED
@@ -14,10 +14,10 @@ pnpm add @noy-db/on-recovery
14
14
 
15
15
  **Protects against:**
16
16
  - Primary authentication becoming unavailable (forgotten secret, lost passkey device, OIDC provider down)
17
- - Code replay — each code burns on successful unlock by deleting its keyring entry
17
+ - Code replay — the hub burns each entry on successful recovery
18
18
 
19
19
  **Does NOT protect against:**
20
- - Physical theft of printed codes — assume paper compromise → user calls `revokeAllRecoveryCodes` + re-enrolls
20
+ - Physical theft of printed codes — assume paper compromise → call `db.team.rotateRecovery(vault, { profile: 'paper' })` for a fresh sheet (replaces, never appends; gated by the `rotate-recovery` policy gate)
21
21
  - User enrolling without actually printing — the calling application must enforce this UX
22
22
 
23
23
  Recovery codes should NEVER be the only unlock method on a vault. Enroll secret / WebAuthn / OIDC first, then recovery codes as a fallback.
@@ -38,127 +38,105 @@ Input is lenient: whitespace, hyphens, lowercase are all stripped before validat
38
38
 
39
39
  ## Security model
40
40
 
41
- Each code is processed through:
41
+ This package is a **thin code-generator + parser layer over the hub's
42
+ `mintPaperRecoveryEntry` primitive**. The crypto lives in the hub, and it
43
+ wraps the vault's **DEK set** — never the KEK:
42
44
 
43
45
  ```
44
46
  wrappingKey = PBKDF2-SHA256(
45
47
  password = normalizeCode(code),
46
- salt = perCodeRandomSalt, // Stored alongside wrapped KEK
47
- iterations = 600_000, // Matches hub's secret derivation
48
+ salt = perEntryRandomSalt,
49
+ iterations = 600_000, // matches hub's secret derivation
48
50
  length = 256 // bits
49
51
  )
50
52
 
51
- wrappedKEK = AES-KW(kek, wrappingKey)
53
+ entry = AES-GCM(dekSet, wrappingKey) + salt + codeId + enrolledAt
52
54
  ```
53
55
 
54
- The `wrappedKEK + salt + codeId` goes into the keyring under a `_recovery_<N>` entry. On unlock, PBKDF2 re-derives the wrapping key from the user-typed code + salt, and AES-KW unwraps the KEK.
56
+ Entries live in the vault's `_meta/recovery-paper` document. On recovery the
57
+ hub re-derives the wrapping key from the typed code, unwraps the DEK set, and
58
+ re-wraps it under the user's **new** secret.
59
+
60
+ > **History — why there is no KEK path.** Until `0.1.0-pre.8` this package
61
+ > wrapped the KEK directly (`unwrapKEKFromRecovery`, `wrapKEKForRecovery`).
62
+ > That required an **extractable KEK**, which the hub's key derivation
63
+ > deliberately disallows — the same asymmetry that made `on-password`
64
+ > unreachable from a real consumer. All unlock tiers were unified on the
65
+ > wrap-DEKs primitive (#26 Path C, #38 Option A), and the KEK-wrapping API
66
+ > was removed. Do not look for it; nothing here can hand you a KEK.
55
67
 
56
68
  ## Usage
57
69
 
58
- This package provides the **crypto layer only**. Storage, audit, rate-limiting, and burn-on-use are application-layer concerns handled by hub's keyring + audit-ledger APIs.
70
+ This package does exactly three things: generate printable codes, parse and
71
+ normalize user input, and format normalized codes for display. Storage,
72
+ matching, burn-on-use, auditing, and rotation are all **hub** concerns.
59
73
 
60
74
  ### Enrollment (after primary unlock)
61
75
 
62
76
  ```ts
63
77
  import { generateRecoveryCodeSet } from '@noy-db/on-recovery'
64
78
 
65
- // After the user unlocks with secret, offer recovery-code enrollment
79
+ // The DEK set proves possession and is what the codes wrap.
80
+ const keyring = await db.team.getKeyring('acme')
66
81
  const { codes, entries } = await generateRecoveryCodeSet({
67
- count: 10, // 8-20 is reasonable; default 10
68
- kek: currentKEK, // The vault's currently-unwrapped KEK
82
+ deks: keyring.deks,
83
+ count: 10, // 8-20 is reasonable; default 10
69
84
  })
70
85
 
71
86
  // Show `codes` to the user ONCE — print, download, copy. Do NOT store them.
72
87
  displayRecoveryCodes(codes)
73
- downloadRecoveryCodes(codes)
74
-
75
- // Persist `entries` to the vault's keyring. Each entry is safe to
76
- // store on disk it holds only the salt + wrapped KEK + codeId.
77
- for (const entry of entries) {
78
- await vault.keyring.put(`_recovery_${entry.codeId}`, entry)
79
- }
80
-
81
- // Write an audit-ledger entry
82
- await vault.ledger.append({
83
- type: 'on-recovery:enroll',
84
- actor: currentUserId,
85
- codeCount: entries.length,
86
- timestamp: new Date().toISOString(),
87
- })
88
+
89
+ // Persist `entries` — each holds only salt + wrapped DEK set + codeId,
90
+ // safe to store. The hub appends them to `_meta/recovery-paper`.
91
+ await db.team.enrollRecovery('acme', { profile: 'paper', entries })
88
92
  ```
89
93
 
90
- ### Unlock (when primary auth is unavailable)
94
+ ### Recovery (when primary auth is unavailable)
95
+
96
+ `parseRecoveryCode` classifies input **before** any expensive derivation, so
97
+ a transcription error never counts against a rate limit:
91
98
 
92
99
  ```ts
93
- import { parseRecoveryCode, unwrapKEKFromRecovery } from '@noy-db/on-recovery'
100
+ import { parseRecoveryCode } from '@noy-db/on-recovery'
94
101
 
95
102
  const parsed = parseRecoveryCode(userInput)
103
+ if (parsed.status === 'invalid-format') return showError('not a recovery code')
104
+ if (parsed.status === 'invalid-checksum') return showError('check for typos') // transcription, not a guess
105
+ ```
106
+
107
+ The recovery itself is one hub call. It finds the matching entry, burns it,
108
+ sets the new secret, and by default **auto-rotates the remaining codes** so
109
+ the sheet in the safe stays fully usable:
96
110
 
97
- if (parsed.status === 'invalid-format') {
98
- // User typed junk show "not a valid recovery code" without counting against rate limit
99
- return showError('format')
100
- }
101
- if (parsed.status === 'invalid-checksum') {
102
- // Well-formed but checksum wrong — transcription error, not a guess
103
- return showError('checksum')
104
- }
105
-
106
- // Find which enrolled entry this code matches
107
- const allEntries = await vault.keyring.list({ prefix: '_recovery_' })
108
-
109
- for (const entry of allEntries) {
110
- try {
111
- const kek = await unwrapKEKFromRecovery(parsed.code, entry)
112
-
113
- // Match! Burn this entry — delete the keyring record so the code
114
- // can never be replayed.
115
- await vault.keyring.delete(`_recovery_${entry.codeId}`)
116
-
117
- // Write an audit-ledger entry
118
- await vault.ledger.append({
119
- type: 'on-recovery:unlock',
120
- actor: currentUserId,
121
- codesRemaining: allEntries.length - 1,
122
- timestamp: new Date().toISOString(),
123
- })
124
-
125
- return kek
126
- } catch {
127
- // Wrong entry, try next
128
- }
129
- }
130
-
131
- // No matching entry — counts against the host app's rate limit
132
- await vault.ledger.append({
133
- type: 'on-recovery:unlock-failed',
134
- actor: currentUserId,
135
- reason: 'not-found',
136
- timestamp: new Date().toISOString(),
111
+ ```ts
112
+ const { newCodes } = await db.recoverSecret('acme', {
113
+ newSecret,
114
+ recoveryProof: { profile: 'paper', payload: { code: parsed.code } },
137
115
  })
138
- throw new Error('no matching recovery code')
116
+ if (newCodes.length > 0) showCodesToUser(newCodes) // show-once, same as enrollment
139
117
  ```
140
118
 
141
- ### Revocation (after a suspected paper leak)
119
+ ### Fresh sheet (lost printout / suspected paper leak)
142
120
 
143
121
  ```ts
144
- // Scan all recovery entries, delete each.
145
- const allEntries = await vault.keyring.list({ prefix: '_recovery_' })
146
- for (const entry of allEntries) {
147
- await vault.keyring.delete(`_recovery_${entry.codeId}`)
148
- }
149
- // Optionally re-enroll a fresh set.
122
+ const { newCodes } = await db.team.rotateRecovery('acme', { profile: 'paper' })
123
+ showCodesToUser(newCodes)
150
124
  ```
151
125
 
126
+ Replaces (never appends) the paper sheet in a single envelope write. Under
127
+ `STRICT_POLICY` this requires an off-device factor proof, so a stolen
128
+ unlocked laptop cannot silently mint a sheet for the attacker.
129
+
152
130
  ## API
153
131
 
154
132
  ```ts
155
133
  // Generate a full enrollment
156
134
  async function generateRecoveryCodeSet(options: {
157
- count?: number // Default 10, clamped to 1..100
158
- kek: CryptoKey // Currently-unwrapped KEK
135
+ count?: number // Default 10, clamped to 1..100
136
+ deks: Map<string, CryptoKey> // The vault's current DEK set
159
137
  }): Promise<{
160
- codes: string[] // Show to user once, then forget
161
- entries: RecoveryCodeEntry[] // Persist to keyring
138
+ codes: string[] // Show to user once, then forget
139
+ entries: PaperRecoveryEntry[] // Persist via db.team.enrollRecovery
162
140
  }>
163
141
 
164
142
  // Parse + normalize user input
@@ -169,30 +147,16 @@ type ParseResult =
169
147
  | { status: 'invalid-checksum' } // Format OK, checksum wrong
170
148
  | { status: 'invalid-format' } // Not a valid code shape
171
149
 
172
- // Attempt to unwrap the KEK with a code + an entry; throws on mismatch
173
- async function unwrapKEKFromRecovery(
174
- code: string, // The normalized code from parseRecoveryCode
175
- entry: RecoveryCodeEntry, // One of the enrolled entries
176
- ): Promise<CryptoKey>
177
-
178
- // Lower-level helpers (for advanced use cases)
150
+ // Re-hyphenate a normalized code for display
179
151
  function formatRecoveryCode(normalized: string): string
180
- async function deriveRecoveryWrappingKey(code: string, salt: Uint8Array): Promise<CryptoKey>
181
- async function wrapKEKForRecovery(kek: CryptoKey, code: string, salt: Uint8Array): Promise<Uint8Array>
182
-
183
- interface RecoveryCodeEntry {
184
- codeId: string // ULID — caller uses this to delete the entry on burn
185
- salt: string // Base64
186
- wrappedKEK: string // Base64
187
- enrolledAt: string // ISO timestamp
188
- }
189
152
  ```
190
153
 
191
- ## Performance
154
+ `PaperRecoveryEntry` (`{ codeId, enrolledAt, salt, wrapped DEK blob }`) is the
155
+ hub's type — this package mints it via the hub and never defines its own.
192
156
 
193
- PBKDF2 with 600K iterations takes ~500ms per derive on modern hardware. Generating 10 codes enrolls in ~5 seconds (serial) — acceptable for a one-time enrollment flow; show a loading indicator. Unlock is a single derive per attempt (~500ms).
157
+ ## Performance
194
158
 
195
- If you need faster enrollment (e.g., a CLI test), you can parallelize via `Promise.all`.
159
+ PBKDF2 with 600K iterations takes ~500ms per derive on modern hardware. Generating 10 codes enrolls in ~5 seconds (serial) acceptable for a one-time enrollment flow; show a loading indicator. Recovery is a single derive per attempt (~500ms).
196
160
 
197
161
  ## License
198
162
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@noy-db/on-recovery",
3
- "version": "0.7.0-pre.9",
3
+ "version": "0.7.0",
4
4
  "description": "One-time printable recovery codes for noy-db — last-resort vault unlock when the secret, passkey, and OIDC provider are all unavailable. Base32 + checksum codes, PBKDF2-derived wrapping keys, burn-on-use. Part of the @noy-db/on-* authentication family.",
5
5
  "license": "MIT",
6
6
  "author": "vLannaAi <vicio@lanna.ai>",
@@ -32,10 +32,11 @@
32
32
  "node": ">=22.0.0"
33
33
  },
34
34
  "peerDependencies": {
35
- "@noy-db/hub": "^0.7.0-pre.9"
35
+ "@noy-db/hub": "^0.7.0"
36
36
  },
37
37
  "devDependencies": {
38
- "@noy-db/hub": "0.7.0-pre.9"
38
+ "happy-dom": "^18.0.0",
39
+ "@noy-db/hub": "0.7.0"
39
40
  },
40
41
  "keywords": [
41
42
  "noy-db",