@noy-db/on-recovery 0.4.0-pre.4 → 0.4.0-pre.5

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/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # @noy-db/on-recovery
2
2
 
3
- One-time printable recovery codes for noy-db. The **last-resort unlock path** when the primary authentication (passphrase, WebAuthn, OIDC) is unavailable. Codes are generated once, shown to the user once, printed on paper, stored in a safe. Each code unlocks the vault exactly **one time** and then burns itself.
3
+ One-time printable recovery codes for noy-db. The **last-resort unlock path** when the primary authentication (secret, WebAuthn, OIDC) is unavailable. Codes are generated once, shown to the user once, printed on paper, stored in a safe. Each code unlocks the vault exactly **one time** and then burns itself.
4
4
 
5
5
  Part of the `@noy-db/on-*` authentication family. Sibling packages: `on-webauthn`, `on-oidc`, `on-magic-link`, `on-pin`.
6
6
 
@@ -13,14 +13,14 @@ pnpm add @noy-db/on-recovery
13
13
  ## Threat model
14
14
 
15
15
  **Protects against:**
16
- - Primary authentication becoming unavailable (forgotten passphrase, lost passkey device, OIDC provider down)
16
+ - Primary authentication becoming unavailable (forgotten secret, lost passkey device, OIDC provider down)
17
17
  - Code replay — each code burns on successful unlock by deleting its keyring entry
18
18
 
19
19
  **Does NOT protect against:**
20
20
  - Physical theft of printed codes — assume paper compromise → user calls `revokeAllRecoveryCodes` + re-enrolls
21
21
  - User enrolling without actually printing — the calling application must enforce this UX
22
22
 
23
- Recovery codes should NEVER be the only unlock method on a vault. Enroll passphrase / WebAuthn / OIDC first, then recovery codes as a fallback.
23
+ Recovery codes should NEVER be the only unlock method on a vault. Enroll secret / WebAuthn / OIDC first, then recovery codes as a fallback.
24
24
 
25
25
  ## Code format
26
26
 
@@ -44,7 +44,7 @@ Each code is processed through:
44
44
  wrappingKey = PBKDF2-SHA256(
45
45
  password = normalizeCode(code),
46
46
  salt = perCodeRandomSalt, // Stored alongside wrapped KEK
47
- iterations = 600_000, // Matches hub's passphrase derivation
47
+ iterations = 600_000, // Matches hub's secret derivation
48
48
  length = 256 // bits
49
49
  )
50
50
 
@@ -62,7 +62,7 @@ This package provides the **crypto layer only**. Storage, audit, rate-limiting,
62
62
  ```ts
63
63
  import { generateRecoveryCodeSet } from '@noy-db/on-recovery'
64
64
 
65
- // After the user unlocks with passphrase, offer recovery-code enrollment
65
+ // After the user unlocks with secret, offer recovery-code enrollment
66
66
  const { codes, entries } = await generateRecoveryCodeSet({
67
67
  count: 10, // 8-20 is reasonable; default 10
68
68
  kek: currentKEK, // The vault's currently-unwrapped KEK
package/dist/index.d.ts CHANGED
@@ -34,16 +34,16 @@ import { PaperRecoveryEntry } from '@noy-db/hub';
34
34
  * import { generateRecoveryCodeSet, parseRecoveryCode } from '@noy-db/on-recovery'
35
35
  *
36
36
  * // ENROLL — after the user unlocks at tier 1, mint N codes
37
- * const keyring = await db.getKeyring('acme')
37
+ * const keyring = await db.team.getKeyring('acme')
38
38
  * const { codes, entries } = await generateRecoveryCodeSet({ deks: keyring.deks, count: 10 })
39
39
  * showCodesToUser(codes)
40
- * await db.enrollRecovery('acme', { profile: 'paper', entries })
40
+ * await db.team.enrollRecovery('acme', { profile: 'paper', entries })
41
41
  *
42
- * // RECOVER — user types one back later (handled by db.recoverPassphrase)
42
+ * // RECOVER — user types one back later (handled by db.recoverSecret)
43
43
  * const parsed = parseRecoveryCode(userInput)
44
44
  * if (parsed.status !== 'valid') return handleInvalid(parsed.status)
45
- * await db.recoverPassphrase('acme', {
46
- * newPassphrase,
45
+ * await db.team.recoverSecret('acme', {
46
+ * newSecret,
47
47
  * recoveryProof: { profile: 'paper', payload: { code: parsed.code } },
48
48
  * })
49
49
  * ```
@@ -56,7 +56,7 @@ interface GenerateRecoveryCodeSetOptions {
56
56
  /** Number of codes to generate. Default 10. Reasonable: 8-20. */
57
57
  count?: number;
58
58
  /**
59
- * The vault's current DEK set (typically `(await db.getKeyring(vault)).deks`).
59
+ * The vault's current DEK set (typically `(await db.team.getKeyring(vault)).deks`).
60
60
  * Required — proves possession and is the input the hub's
61
61
  * `mintPaperRecoveryEntry` needs.
62
62
  */
@@ -74,11 +74,11 @@ type ParseResult = {
74
74
  /**
75
75
  * Generate a fresh recovery-code set. Returned `codes` must be shown
76
76
  * to the user exactly once (print/save); `entries` go into the vault
77
- * via `db.enrollRecovery({ profile: 'paper', entries })`.
77
+ * via `db.team.enrollRecovery({ profile: 'paper', entries })`.
78
78
  *
79
79
  * Internally calls the hub's `mintPaperRecoveryEntry` once per code.
80
80
  * The hub's wrap-DEKs format is preserved end-to-end — `db.enrollRecovery`
81
- * stores the entries verbatim and `db.recoverPassphrase` consumes them
81
+ * stores the entries verbatim and `db.recoverSecret` consumes them
82
82
  * via `unwrapDeksFromPaperEntry`.
83
83
  */
84
84
  declare function generateRecoveryCodeSet(opts: GenerateRecoveryCodeSetOptions): Promise<{
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts"],"sourcesContent":["/**\n * **@noy-db/on-recovery** — printable recovery codes for noy-db.\n *\n * The last-resort unlock path when the primary authentication is\n * unavailable. Codes are designed to be printed on paper and stored\n * in a safe — each code unlocks the vault exactly once and then is\n * burned by deleting its `_meta/recovery-paper` entry.\n *\n * Part of the `@noy-db/on-*` authentication family.\n *\n * ## Format (Option A)\n *\n * This package is now a **thin code-generator + parser layer over\n * the hub's `mintPaperRecoveryEntry` primitive**. Its job is exactly\n * three things:\n *\n * 1. Generate printable Base32 codes with checksums (the user-facing\n * string format).\n * 2. Parse user input back into a normalized code (whitespace /\n * hyphen / case insensitive).\n * 3. Delegate the wrapping crypto to the hub via\n * `mintPaperRecoveryEntry(deks, code, codeId)`.\n *\n * This delegation aligns recovery with the hub's wrap-DEKs primitive\n * (the same shape used by `@noy-db/on-pin` and now `@noy-db/on-password`\n * after the wrap-DEKs path change). It eliminates the format mismatch\n * that made the previous package version unusable with `db.enrollRecovery`.\n *\n * ## Usage\n *\n * ```ts\n * import { generateRecoveryCodeSet, parseRecoveryCode } from '@noy-db/on-recovery'\n *\n * // ENROLL — after the user unlocks at tier 1, mint N codes\n * const keyring = await db.getKeyring('acme')\n * const { codes, entries } = await generateRecoveryCodeSet({ deks: keyring.deks, count: 10 })\n * showCodesToUser(codes)\n * await db.enrollRecovery('acme', { profile: 'paper', entries })\n *\n * // RECOVER — user types one back later (handled by db.recoverPassphrase)\n * const parsed = parseRecoveryCode(userInput)\n * if (parsed.status !== 'valid') return handleInvalid(parsed.status)\n * await db.recoverPassphrase('acme', {\n * newPassphrase,\n * recoveryProof: { profile: 'paper', payload: { code: parsed.code } },\n * })\n * ```\n *\n * @packageDocumentation\n */\n\nimport { generateULID, mintPaperRecoveryEntry, type PaperRecoveryEntry } from '@noy-db/hub'\n\n// Constants ────────────────────────────────────────────────────────────\n\n/** RFC 4648 Base32 alphabet — A-Z + 2-7, no ambiguous chars. */\nconst BASE32_ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'\n\n/** Characters to ignore on input (whitespace, hyphens, lowercase). */\nconst STRIPPABLE = /[\\s\\-_]/g\n\n/** How many random bytes of entropy per code. */\nconst CODE_ENTROPY_BYTES = 15 // 15 bytes = 120 bits = exactly 24 Base32 chars (clean groups of 4)\n\n/** Length of the checksum portion (Base32 chars). */\nconst CHECKSUM_LEN = 4 // 24 body + 4 checksum = 28 chars = 7 groups of 4\n\n// Types ────────────────────────────────────────────────────────────────\n\n/** Options for `generateRecoveryCodeSet()`. */\nexport interface GenerateRecoveryCodeSetOptions {\n /** Number of codes to generate. Default 10. Reasonable: 8-20. */\n count?: number\n /**\n * The vault's current DEK set (typically `(await db.getKeyring(vault)).deks`).\n * Required — proves possession and is the input the hub's\n * `mintPaperRecoveryEntry` needs.\n */\n deks: Map<string, CryptoKey>\n}\n\n/** Result of `parseRecoveryCode()`. */\nexport type ParseResult =\n | { status: 'valid'; code: string } // Normalized, checksum-verified\n | { status: 'invalid-checksum' } // Format OK, checksum wrong\n | { status: 'invalid-format' } // Not a valid code shape\n\n// Code generation ──────────────────────────────────────────────────────\n\n/**\n * Generate a fresh recovery-code set. Returned `codes` must be shown\n * to the user exactly once (print/save); `entries` go into the vault\n * via `db.enrollRecovery({ profile: 'paper', entries })`.\n *\n * Internally calls the hub's `mintPaperRecoveryEntry` once per code.\n * The hub's wrap-DEKs format is preserved end-to-end — `db.enrollRecovery`\n * stores the entries verbatim and `db.recoverPassphrase` consumes them\n * via `unwrapDeksFromPaperEntry`.\n */\nexport async function generateRecoveryCodeSet(\n opts: GenerateRecoveryCodeSetOptions,\n): Promise<{ codes: string[]; entries: PaperRecoveryEntry[] }> {\n const count = opts.count ?? 10\n if (!Number.isInteger(count) || count < 1 || count > 100) {\n throw new Error(`on-recovery: count must be 1-100 (got ${count})`)\n }\n\n const codes: string[] = []\n const entries: PaperRecoveryEntry[] = []\n\n for (let i = 0; i < count; i++) {\n const raw = generateRawCode()\n const formatted = formatCodeForDisplay(raw)\n // The hub stores entries keyed on the NORMALIZED code (raw, no\n // hyphens). Mint with the normalized form so `db.recoverPassphrase`'s\n // `normalizePaperCode(input)` matches at unlock time.\n const entry = await mintPaperRecoveryEntry(opts.deks, raw, generateULID())\n codes.push(formatted)\n entries.push(entry)\n }\n\n return { codes, entries }\n}\n\n// Code parsing + normalization ─────────────────────────────────────────\n\n/**\n * Parse user input into a normalized recovery code. Accepts whitespace,\n * hyphens, and lowercase — strips them all. Verifies the checksum.\n */\nexport function parseRecoveryCode(input: string): ParseResult {\n const normalized = input.toUpperCase().replace(STRIPPABLE, '')\n\n const expectedLen = base32CharsForBytes(CODE_ENTROPY_BYTES) + CHECKSUM_LEN\n if (normalized.length !== expectedLen) {\n return { status: 'invalid-format' }\n }\n for (const ch of normalized) {\n if (!BASE32_ALPHABET.includes(ch)) {\n return { status: 'invalid-format' }\n }\n }\n\n const bodyLen = normalized.length - CHECKSUM_LEN\n const body = normalized.slice(0, bodyLen)\n const checksum = normalized.slice(bodyLen)\n\n if (computeChecksum(body) !== checksum) {\n return { status: 'invalid-checksum' }\n }\n\n return { status: 'valid', code: normalized }\n}\n\n/**\n * Format a normalized recovery code for display (groups of 4, hyphenated).\n * Inverse of the strip-hyphens step in `parseRecoveryCode`.\n */\nexport function formatRecoveryCode(normalizedCode: string): string {\n const groups: string[] = []\n for (let i = 0; i < normalizedCode.length; i += 4) {\n groups.push(normalizedCode.slice(i, i + 4))\n }\n return groups.join('-')\n}\n\n// Internals ────────────────────────────────────────────────────────────\n\nfunction generateRawCode(): string {\n const entropy = crypto.getRandomValues(new Uint8Array(CODE_ENTROPY_BYTES))\n const body = base32Encode(entropy)\n const checksum = computeChecksum(body)\n return body + checksum\n}\n\nfunction formatCodeForDisplay(rawNormalized: string): string {\n return formatRecoveryCode(rawNormalized)\n}\n\n/**\n * Deterministic 4-character checksum over Base32 body. Catches\n * transcription errors (single-char swaps, shifted digits) with very\n * high probability.\n *\n * Uses a simple polynomial hash reduced modulo the Base32 alphabet\n * size (32). Four output chars = 20 bits ≈ 1-in-1M false positive.\n */\nfunction computeChecksum(body: string): string {\n let h = 0\n for (let i = 0; i < body.length; i++) {\n const v = BASE32_ALPHABET.indexOf(body[i]!)\n h = (h * 33 + v) >>> 0\n }\n const chars: string[] = []\n for (let i = 0; i < CHECKSUM_LEN; i++) {\n chars.push(BASE32_ALPHABET[(h >>> (i * 5)) & 0x1f]!)\n }\n return chars.join('')\n}\n\nfunction base32CharsForBytes(n: number): number {\n return Math.ceil((n * 8) / 5)\n}\n\nfunction base32Encode(bytes: Uint8Array): string {\n let bits = 0\n let value = 0\n let out = ''\n for (let i = 0; i < bytes.length; i++) {\n value = (value << 8) | bytes[i]!\n bits += 8\n while (bits >= 5) {\n bits -= 5\n out += BASE32_ALPHABET[(value >>> bits) & 0x1f]\n }\n }\n if (bits > 0) {\n out += BASE32_ALPHABET[(value << (5 - bits)) & 0x1f]\n }\n return out\n}\n"],"mappings":";AAmDA,SAAS,cAAc,8BAAuD;AAK9E,IAAM,kBAAkB;AAGxB,IAAM,aAAa;AAGnB,IA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AO,KAAK,eAAe,MAAM,GAAG,IAAI,CAAC,CAAC;AAAA,EAC5C;AACA,SAAO,OAAO,KAAK,GAAG;AACxB;AAIA,SAAS,kBAA0B;AACjC,QAAM,UAAU,OAAO,gBAAgB,IAAI,WAAW,kBAAkB,CAAC;AACzE,QAAM,OAAO,aAAa,OAAO;AACjC,QAAM,WAAW,gBAAgB,IAAI;AACrC,SAAO,OAAO;AAChB;AAEA,SAAS,qBAAqB,eAA+B;AAC3D,SAAO,mBAAmB,aAAa;AACzC;AAUA,SAAS,gBAAgB,MAAsB;AAC7C,MAAI,IAAI;AACR,WAAS,IAAI,GAAG,IAAI,KAAK,QAAQ,KAAK;AACpC,UAAM,IAAI,gBAAgB,QAAQ,KAAK,CAAC,CAAE;AAC1C,QAAK,IAAI,KAAK,MAAO;AAAA,EACvB;AACA,QAAM,QAAkB,CAAC;AACzB,WAAS,IAAI,GAAG,IAAI,cAAc,KAAK;AACrC,UAAM,KAAK,gBAAiB,MAAO,IAAI,IAAM,EAAI,CAAE;AAAA,EACrD;AACA,SAAO,MAAM,KAAK,EAAE;AACtB;AAEA,SAAS,oBAAoB,GAAmB;AAC9C,SAAO,KAAK,KAAM,IAAI,IAAK,CAAC;AAC9B;AAEA,SAAS,aAAa,OAA2B;AAC/C,MAAI,OAAO;AACX,MAAI,QAAQ;AACZ,MAAI,MAAM;AACV,WAAS,IAAI,GAAG,IAAI,MAAM,QAAQ,KAAK;AACrC,YAAS,SAAS,IAAK,MAAM,CAAC;AAC9B,YAAQ;AACR,WAAO,QAAQ,GAAG;AAChB,cAAQ;AACR,aAAO,gBAAiB,UAAU,OAAQ,EAAI;AAAA,IAChD;AAAA,EACF;AACA,MAAI,OAAO,GAAG;AACZ,WAAO,gBAAiB,SAAU,IAAI,OAAS,EAAI;AAAA,EACrD;AACA,SAAO;AACT;","names":[]}
1
+ {"version":3,"sources":["../src/index.ts"],"sourcesContent":["/**\n * **@noy-db/on-recovery** — printable recovery codes for noy-db.\n *\n * The last-resort unlock path when the primary authentication is\n * unavailable. Codes are designed to be printed on paper and stored\n * in a safe — each code unlocks the vault exactly once and then is\n * burned by deleting its `_meta/recovery-paper` entry.\n *\n * Part of the `@noy-db/on-*` authentication family.\n *\n * ## Format (Option A)\n *\n * This package is now a **thin code-generator + parser layer over\n * the hub's `mintPaperRecoveryEntry` primitive**. Its job is exactly\n * three things:\n *\n * 1. Generate printable Base32 codes with checksums (the user-facing\n * string format).\n * 2. Parse user input back into a normalized code (whitespace /\n * hyphen / case insensitive).\n * 3. Delegate the wrapping crypto to the hub via\n * `mintPaperRecoveryEntry(deks, code, codeId)`.\n *\n * This delegation aligns recovery with the hub's wrap-DEKs primitive\n * (the same shape used by `@noy-db/on-pin` and now `@noy-db/on-password`\n * after the wrap-DEKs path change). It eliminates the format mismatch\n * that made the previous package version unusable with `db.enrollRecovery`.\n *\n * ## Usage\n *\n * ```ts\n * import { generateRecoveryCodeSet, parseRecoveryCode } from '@noy-db/on-recovery'\n *\n * // ENROLL — after the user unlocks at tier 1, mint N codes\n * const keyring = await db.team.getKeyring('acme')\n * const { codes, entries } = await generateRecoveryCodeSet({ deks: keyring.deks, count: 10 })\n * showCodesToUser(codes)\n * await db.team.enrollRecovery('acme', { profile: 'paper', entries })\n *\n * // RECOVER — user types one back later (handled by db.recoverSecret)\n * const parsed = parseRecoveryCode(userInput)\n * if (parsed.status !== 'valid') return handleInvalid(parsed.status)\n * await db.team.recoverSecret('acme', {\n * newSecret,\n * recoveryProof: { profile: 'paper', payload: { code: parsed.code } },\n * })\n * ```\n *\n * @packageDocumentation\n */\n\nimport { generateULID, mintPaperRecoveryEntry, type PaperRecoveryEntry } from '@noy-db/hub'\n\n// Constants ────────────────────────────────────────────────────────────\n\n/** RFC 4648 Base32 alphabet — A-Z + 2-7, no ambiguous chars. */\nconst BASE32_ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'\n\n/** Characters to ignore on input (whitespace, hyphens, lowercase). */\nconst STRIPPABLE = /[\\s\\-_]/g\n\n/** How many random bytes of entropy per code. */\nconst CODE_ENTROPY_BYTES = 15 // 15 bytes = 120 bits = exactly 24 Base32 chars (clean groups of 4)\n\n/** Length of the checksum portion (Base32 chars). */\nconst CHECKSUM_LEN = 4 // 24 body + 4 checksum = 28 chars = 7 groups of 4\n\n// Types ────────────────────────────────────────────────────────────────\n\n/** Options for `generateRecoveryCodeSet()`. */\nexport interface GenerateRecoveryCodeSetOptions {\n /** Number of codes to generate. Default 10. Reasonable: 8-20. */\n count?: number\n /**\n * The vault's current DEK set (typically `(await db.team.getKeyring(vault)).deks`).\n * Required — proves possession and is the input the hub's\n * `mintPaperRecoveryEntry` needs.\n */\n deks: Map<string, CryptoKey>\n}\n\n/** Result of `parseRecoveryCode()`. */\nexport type ParseResult =\n | { status: 'valid'; code: string } // Normalized, checksum-verified\n | { status: 'invalid-checksum' } // Format OK, checksum wrong\n | { status: 'invalid-format' } // Not a valid code shape\n\n// Code generation ──────────────────────────────────────────────────────\n\n/**\n * Generate a fresh recovery-code set. Returned `codes` must be shown\n * to the user exactly once (print/save); `entries` go into the vault\n * via `db.team.enrollRecovery({ profile: 'paper', entries })`.\n *\n * Internally calls the hub's `mintPaperRecoveryEntry` once per code.\n * The hub's wrap-DEKs format is preserved end-to-end — `db.enrollRecovery`\n * stores the entries verbatim and `db.recoverSecret` consumes them\n * via `unwrapDeksFromPaperEntry`.\n */\nexport async function generateRecoveryCodeSet(\n opts: GenerateRecoveryCodeSetOptions,\n): Promise<{ codes: string[]; entries: PaperRecoveryEntry[] }> {\n const count = opts.count ?? 10\n if (!Number.isInteger(count) || count < 1 || count > 100) {\n throw new Error(`on-recovery: count must be 1-100 (got ${count})`)\n }\n\n const codes: string[] = []\n const entries: PaperRecoveryEntry[] = []\n\n for (let i = 0; i < count; i++) {\n const raw = generateRawCode()\n const formatted = formatCodeForDisplay(raw)\n // The hub stores entries keyed on the NORMALIZED code (raw, no\n // hyphens). Mint with the normalized form so `db.recoverSecret`'s\n // `normalizePaperCode(input)` matches at unlock time.\n const entry = await mintPaperRecoveryEntry(opts.deks, raw, generateULID())\n codes.push(formatted)\n entries.push(entry)\n }\n\n return { codes, entries }\n}\n\n// Code parsing + normalization ─────────────────────────────────────────\n\n/**\n * Parse user input into a normalized recovery code. Accepts whitespace,\n * hyphens, and lowercase — strips them all. Verifies the checksum.\n */\nexport function parseRecoveryCode(input: string): ParseResult {\n const normalized = input.toUpperCase().replace(STRIPPABLE, '')\n\n const expectedLen = base32CharsForBytes(CODE_ENTROPY_BYTES) + CHECKSUM_LEN\n if (normalized.length !== expectedLen) {\n return { status: 'invalid-format' }\n }\n for (const ch of normalized) {\n if (!BASE32_ALPHABET.includes(ch)) {\n return { status: 'invalid-format' }\n }\n }\n\n const bodyLen = normalized.length - CHECKSUM_LEN\n const body = normalized.slice(0, bodyLen)\n const checksum = normalized.slice(bodyLen)\n\n if (computeChecksum(body) !== checksum) {\n return { status: 'invalid-checksum' }\n }\n\n return { status: 'valid', code: normalized }\n}\n\n/**\n * Format a normalized recovery code for display (groups of 4, hyphenated).\n * Inverse of the strip-hyphens step in `parseRecoveryCode`.\n */\nexport function formatRecoveryCode(normalizedCode: string): string {\n const groups: string[] = []\n for (let i = 0; i < normalizedCode.length; i += 4) {\n groups.push(normalizedCode.slice(i, i + 4))\n }\n return groups.join('-')\n}\n\n// Internals ────────────────────────────────────────────────────────────\n\nfunction generateRawCode(): string {\n const entropy = crypto.getRandomValues(new Uint8Array(CODE_ENTROPY_BYTES))\n const body = base32Encode(entropy)\n const checksum = computeChecksum(body)\n return body + checksum\n}\n\nfunction formatCodeForDisplay(rawNormalized: string): string {\n return formatRecoveryCode(rawNormalized)\n}\n\n/**\n * Deterministic 4-character checksum over Base32 body. Catches\n * transcription errors (single-char swaps, shifted digits) with very\n * high probability.\n *\n * Uses a simple polynomial hash reduced modulo the Base32 alphabet\n * size (32). Four output chars = 20 bits ≈ 1-in-1M false positive.\n */\nfunction computeChecksum(body: string): string {\n let h = 0\n for (let i = 0; i < body.length; i++) {\n const v = BASE32_ALPHABET.indexOf(body[i]!)\n h = (h * 33 + v) >>> 0\n }\n const chars: string[] = []\n for (let i = 0; i < CHECKSUM_LEN; i++) {\n chars.push(BASE32_ALPHABET[(h >>> (i * 5)) & 0x1f]!)\n }\n return chars.join('')\n}\n\nfunction base32CharsForBytes(n: number): number {\n return Math.ceil((n * 8) / 5)\n}\n\nfunction base32Encode(bytes: Uint8Array): string {\n let bits = 0\n let value = 0\n let out = ''\n for (let i = 0; i < bytes.length; i++) {\n value = (value << 8) | bytes[i]!\n bits += 8\n while (bits >= 5) {\n bits -= 5\n out += BASE32_ALPHABET[(value >>> bits) & 0x1f]\n }\n }\n if (bits > 0) {\n out += BASE32_ALPHABET[(value << (5 - bits)) & 0x1f]\n }\n return out\n}\n"],"mappings":";AAmDA,SAAS,cAAc,8BAAuD;AAK9E,IAAM,kBAAkB;AAGxB,IAAM,aAAa;AAGnB,IAAM,qBAAqB;AAG3B,IAAM,eAAe;AAkCrB,eAAsB,wBACpB,MAC6D;AAC7D,QAAM,QAAQ,KAAK,SAAS;AAC5B,MAAI,CAAC,OAAO,UAAU,KAAK,KAAK,QAAQ,KAAK,QAAQ,KAAK;AACxD,UAAM,IAAI,MAAM,yCAAyC,KAAK,GAAG;AAAA,EACnE;AAEA,QAAM,QAAkB,CAAC;AACzB,QAAM,UAAgC,CAAC;AAEvC,WAAS,IAAI,GAAG,IAAI,OAAO,KAAK;AAC9B,UAAM,MAAM,gBAAgB;AAC5B,UAAM,YAAY,qBAAqB,GAAG;AAI1C,UAAM,QAAQ,MAAM,uBAAuB,KAAK,MAAM,KAAK,aAAa,CAAC;AACzE,UAAM,KAAK,SAAS;AACpB,YAAQ,KAAK,KAAK;AAAA,EACpB;AAEA,SAAO,EAAE,OAAO,QAAQ;AAC1B;AAQO,SAAS,kBAAkB,OAA4B;AAC5D,QAAM,aAAa,MAAM,YAAY,EAAE,QAAQ,YAAY,EAAE;AAE7D,QAAM,cAAc,oBAAoB,k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AO,MAAM,KAAK,EAAE;AACtB;AAEA,SAAS,oBAAoB,GAAmB;AAC9C,SAAO,KAAK,KAAM,IAAI,IAAK,CAAC;AAC9B;AAEA,SAAS,aAAa,OAA2B;AAC/C,MAAI,OAAO;AACX,MAAI,QAAQ;AACZ,MAAI,MAAM;AACV,WAAS,IAAI,GAAG,IAAI,MAAM,QAAQ,KAAK;AACrC,YAAS,SAAS,IAAK,MAAM,CAAC;AAC9B,YAAQ;AACR,WAAO,QAAQ,GAAG;AAChB,cAAQ;AACR,aAAO,gBAAiB,UAAU,OAAQ,EAAI;AAAA,IAChD;AAAA,EACF;AACA,MAAI,OAAO,GAAG;AACZ,WAAO,gBAAiB,SAAU,IAAI,OAAS,EAAI;AAAA,EACrD;AACA,SAAO;AACT;","names":[]}
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@noy-db/on-recovery",
3
- "version": "0.4.0-pre.4",
4
- "description": "One-time printable recovery codes for noy-db — last-resort vault unlock when the passphrase, 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.",
3
+ "version": "0.4.0-pre.5",
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>",
7
7
  "homepage": "https://github.com/vLannaAi/noy-db/tree/main/packages/on-recovery#readme",
@@ -32,10 +32,10 @@
32
32
  "node": ">=22.0.0"
33
33
  },
34
34
  "peerDependencies": {
35
- "@noy-db/hub": "0.4.0-pre.4"
35
+ "@noy-db/hub": "0.4.0-pre.5"
36
36
  },
37
37
  "devDependencies": {
38
- "@noy-db/hub": "0.4.0-pre.4"
38
+ "@noy-db/hub": "0.4.0-pre.5"
39
39
  },
40
40
  "keywords": [
41
41
  "noy-db",