@noy-db/on-password 0.1.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/LICENSE +21 -0
- package/dist/index.cjs +154 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +114 -0
- package/dist/index.d.ts +114 -0
- package/dist/index.js +123 -0
- package/dist/index.js.map +1 -0
- package/package.json +67 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 vLannaAi
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
|
|
20
|
+
// src/index.ts
|
|
21
|
+
var index_exports = {};
|
|
22
|
+
__export(index_exports, {
|
|
23
|
+
PASSWORD_DEFAULT_MIN_LENGTH: () => PASSWORD_DEFAULT_MIN_LENGTH,
|
|
24
|
+
PASSWORD_PBKDF2_ITERATIONS: () => PASSWORD_PBKDF2_ITERATIONS,
|
|
25
|
+
PasswordInvalidError: () => PasswordInvalidError,
|
|
26
|
+
PasswordTooWeakError: () => PasswordTooWeakError,
|
|
27
|
+
enrollPasswordAuthenticator: () => enrollPasswordAuthenticator,
|
|
28
|
+
unwrapKekWithPassword: () => unwrapKekWithPassword,
|
|
29
|
+
verifyPasswordSlot: () => verifyPasswordSlot
|
|
30
|
+
});
|
|
31
|
+
module.exports = __toCommonJS(index_exports);
|
|
32
|
+
var PASSWORD_PBKDF2_ITERATIONS = 6e5;
|
|
33
|
+
var PASSWORD_DEFAULT_MIN_LENGTH = 12;
|
|
34
|
+
var SALT_BYTES = 32;
|
|
35
|
+
var subtle = globalThis.crypto.subtle;
|
|
36
|
+
var PasswordTooWeakError = class extends Error {
|
|
37
|
+
code = "PASSWORD_TOO_WEAK";
|
|
38
|
+
minLength;
|
|
39
|
+
constructor(minLength, message) {
|
|
40
|
+
super(
|
|
41
|
+
message ?? `Password must be at least ${String(minLength)} characters. For accounts with a separate tier-1 phrase, prefer a longer password or pair with TOTP/email-OTP via @noy-db/on-totp or @noy-db/on-email-otp.`
|
|
42
|
+
);
|
|
43
|
+
this.name = "PasswordTooWeakError";
|
|
44
|
+
this.minLength = minLength;
|
|
45
|
+
}
|
|
46
|
+
};
|
|
47
|
+
var PasswordInvalidError = class extends Error {
|
|
48
|
+
code = "PASSWORD_INVALID";
|
|
49
|
+
constructor(message = "Password does not unlock this slot.") {
|
|
50
|
+
super(message);
|
|
51
|
+
this.name = "PasswordInvalidError";
|
|
52
|
+
}
|
|
53
|
+
};
|
|
54
|
+
async function enrollPasswordAuthenticator(keyring, options) {
|
|
55
|
+
const minLength = options.minLength ?? PASSWORD_DEFAULT_MIN_LENGTH;
|
|
56
|
+
if (options.password.length < minLength) {
|
|
57
|
+
throw new PasswordTooWeakError(minLength);
|
|
58
|
+
}
|
|
59
|
+
if (options.pattern && !options.pattern.test(options.password)) {
|
|
60
|
+
throw new PasswordTooWeakError(
|
|
61
|
+
minLength,
|
|
62
|
+
`Password does not match the configured pattern: ${options.pattern.toString()}.`
|
|
63
|
+
);
|
|
64
|
+
}
|
|
65
|
+
if (!keyring.kek) {
|
|
66
|
+
throw new Error(
|
|
67
|
+
"enrollPasswordAuthenticator: the supplied keyring has no KEK in memory. Tier-3 quick-resume keyrings cannot enrol new tier-2 slots; re-authenticate at tier 1 first."
|
|
68
|
+
);
|
|
69
|
+
}
|
|
70
|
+
const salt = crypto.getRandomValues(new Uint8Array(SALT_BYTES));
|
|
71
|
+
const wrappingKey = await derivePasswordWrappingKey(options.password, salt);
|
|
72
|
+
const wrapped = await subtle.wrapKey("raw", keyring.kek, wrappingKey, "AES-KW");
|
|
73
|
+
return {
|
|
74
|
+
id: options.id ?? "password-daily",
|
|
75
|
+
method: "password",
|
|
76
|
+
wrapped_kek: bytesToBase64(new Uint8Array(wrapped)),
|
|
77
|
+
meta: {
|
|
78
|
+
salt: bytesToBase64(salt),
|
|
79
|
+
minLength,
|
|
80
|
+
...options.pattern !== void 0 ? { pattern: options.pattern.source } : {}
|
|
81
|
+
},
|
|
82
|
+
enrolled_via_tier: options.enrolledViaTier ?? 1
|
|
83
|
+
};
|
|
84
|
+
}
|
|
85
|
+
async function unwrapKekWithPassword(slot, password) {
|
|
86
|
+
const meta = slot.meta;
|
|
87
|
+
if (typeof meta.salt !== "string") {
|
|
88
|
+
throw new PasswordInvalidError(
|
|
89
|
+
"Password slot is missing the per-slot salt \u2014 keyring may be corrupted."
|
|
90
|
+
);
|
|
91
|
+
}
|
|
92
|
+
const salt = base64ToBytes(meta.salt);
|
|
93
|
+
const wrappingKey = await derivePasswordWrappingKey(password, salt);
|
|
94
|
+
try {
|
|
95
|
+
return await subtle.unwrapKey(
|
|
96
|
+
"raw",
|
|
97
|
+
base64ToBytes(slot.wrapped_kek),
|
|
98
|
+
wrappingKey,
|
|
99
|
+
"AES-KW",
|
|
100
|
+
{ name: "AES-KW", length: 256 },
|
|
101
|
+
false,
|
|
102
|
+
["wrapKey", "unwrapKey"]
|
|
103
|
+
);
|
|
104
|
+
} catch {
|
|
105
|
+
throw new PasswordInvalidError();
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
async function verifyPasswordSlot(slot, password, options) {
|
|
109
|
+
const kek = await unwrapKekWithPassword(slot, password);
|
|
110
|
+
return options.materialize(kek);
|
|
111
|
+
}
|
|
112
|
+
async function derivePasswordWrappingKey(password, salt) {
|
|
113
|
+
const ikm = await subtle.importKey(
|
|
114
|
+
"raw",
|
|
115
|
+
new TextEncoder().encode(password),
|
|
116
|
+
"PBKDF2",
|
|
117
|
+
false,
|
|
118
|
+
["deriveKey"]
|
|
119
|
+
);
|
|
120
|
+
return subtle.deriveKey(
|
|
121
|
+
{
|
|
122
|
+
name: "PBKDF2",
|
|
123
|
+
salt,
|
|
124
|
+
iterations: PASSWORD_PBKDF2_ITERATIONS,
|
|
125
|
+
hash: "SHA-256"
|
|
126
|
+
},
|
|
127
|
+
ikm,
|
|
128
|
+
{ name: "AES-KW", length: 256 },
|
|
129
|
+
false,
|
|
130
|
+
["wrapKey", "unwrapKey"]
|
|
131
|
+
);
|
|
132
|
+
}
|
|
133
|
+
function bytesToBase64(bytes) {
|
|
134
|
+
let s = "";
|
|
135
|
+
for (const b of bytes) s += String.fromCharCode(b);
|
|
136
|
+
return btoa(s);
|
|
137
|
+
}
|
|
138
|
+
function base64ToBytes(b64) {
|
|
139
|
+
const s = atob(b64);
|
|
140
|
+
const out = new Uint8Array(s.length);
|
|
141
|
+
for (let i = 0; i < s.length; i++) out[i] = s.charCodeAt(i);
|
|
142
|
+
return out;
|
|
143
|
+
}
|
|
144
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
145
|
+
0 && (module.exports = {
|
|
146
|
+
PASSWORD_DEFAULT_MIN_LENGTH,
|
|
147
|
+
PASSWORD_PBKDF2_ITERATIONS,
|
|
148
|
+
PasswordInvalidError,
|
|
149
|
+
PasswordTooWeakError,
|
|
150
|
+
enrollPasswordAuthenticator,
|
|
151
|
+
unwrapKekWithPassword,
|
|
152
|
+
verifyPasswordSlot
|
|
153
|
+
});
|
|
154
|
+
//# sourceMappingURL=index.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["/**\n * **@noy-db/on-password** — tier-2 daily-password authenticator slot.\n *\n * The user's tier-1 *phrase* is the rarely-typed master that derives\n * the KEK. This package adds a SEPARATE secret — a daily-typed\n * password — as a tier-2 slot in the multi-slot keyring. The two\n * credentials have:\n *\n * - **Different lifecycles** — the phrase rotates yearly; the password\n * rotates per the developer's policy.\n * - **Different strength rules** — the phrase is validated against the\n * phrase format (issue #7); the password is validated against a\n * length / regex rule the developer chooses.\n * - **Different storage** — the phrase derives the KEK; the password\n * derives a wrapping key that wraps the SAME KEK in its own\n * keyring slot (LUKS pattern).\n *\n * The slot is added to the keyring via `db.enrollAuthenticator`; the\n * KEK is recovered via `db.unlockViaAuthenticator` — both routes hit\n * the policy gate engine (issue #9).\n *\n * @see docs/subsystems/session-tiers.md → Tier 2 — `on-password`\n *\n * @packageDocumentation\n */\nimport type {\n EnrollAuthenticatorOptions,\n KeyringAuthenticator,\n UnlockedKeyring,\n} from '@noy-db/hub'\n\n/** PBKDF2 iteration count — matches the tier-1 phrase derivation. */\nexport const PASSWORD_PBKDF2_ITERATIONS = 600_000\n\n/** Default minimum password length. Override per-app via `enrollPasswordAuthenticator`. */\nexport const PASSWORD_DEFAULT_MIN_LENGTH = 12\n\n/** Per-slot salt size. */\nconst SALT_BYTES = 32\n\nconst subtle = globalThis.crypto.subtle\n\n// ─── Errors ────────────────────────────────────────────────────────────\n\nexport class PasswordTooWeakError extends Error {\n readonly code = 'PASSWORD_TOO_WEAK' as const\n readonly minLength: number\n constructor(minLength: number, message?: string) {\n super(\n message ??\n `Password must be at least ${String(minLength)} characters. ` +\n 'For accounts with a separate tier-1 phrase, prefer a longer password ' +\n 'or pair with TOTP/email-OTP via @noy-db/on-totp or @noy-db/on-email-otp.',\n )\n this.name = 'PasswordTooWeakError'\n this.minLength = minLength\n }\n}\n\nexport class PasswordInvalidError extends Error {\n readonly code = 'PASSWORD_INVALID' as const\n constructor(message = 'Password does not unlock this slot.') {\n super(message)\n this.name = 'PasswordInvalidError'\n }\n}\n\n// ─── Public API ────────────────────────────────────────────────────────\n\n/** Options for {@link enrollPasswordAuthenticator}. */\nexport interface EnrollPasswordOptions {\n /** Slot id. Default: `'password-daily'`. */\n readonly id?: string\n /** Daily password the user will type. Distinct from the tier-1 phrase. */\n readonly password: string\n /** Minimum length. Default 12. */\n readonly minLength?: number\n /** Optional regex the password must satisfy in addition to length. */\n readonly pattern?: RegExp\n /** Tier the active session held when enrolling. Default 1. */\n readonly enrolledViaTier?: 1 | 2\n}\n\n/**\n * Build the keyring slot for a tier-2 password authenticator. Returns\n * an `EnrollAuthenticatorOptions` value the caller hands to\n * `db.enrollAuthenticator(vault, slot)` — separating the cryptographic\n * step (this function) from the persistence step (the hub) keeps the\n * package small and lets the hub's policy gate run between the two.\n *\n * Usage:\n *\n * ```ts\n * import { enrollPasswordAuthenticator } from '@noy-db/on-password'\n *\n * const slot = await enrollPasswordAuthenticator(unlocked, {\n * password: 'daily-password-2026',\n * minLength: 14,\n * })\n * await db.enrollAuthenticator('acme', slot, {\n * factors: [{ kind: 'totp' }],\n * })\n * ```\n */\nexport async function enrollPasswordAuthenticator(\n keyring: UnlockedKeyring,\n options: EnrollPasswordOptions,\n): Promise<EnrollAuthenticatorOptions> {\n const minLength = options.minLength ?? PASSWORD_DEFAULT_MIN_LENGTH\n if (options.password.length < minLength) {\n throw new PasswordTooWeakError(minLength)\n }\n if (options.pattern && !options.pattern.test(options.password)) {\n throw new PasswordTooWeakError(\n minLength,\n `Password does not match the configured pattern: ${options.pattern.toString()}.`,\n )\n }\n\n if (!keyring.kek) {\n throw new Error(\n 'enrollPasswordAuthenticator: the supplied keyring has no KEK in memory. ' +\n 'Tier-3 quick-resume keyrings cannot enrol new tier-2 slots; re-authenticate at tier 1 first.',\n )\n }\n\n const salt = crypto.getRandomValues(new Uint8Array(SALT_BYTES))\n const wrappingKey = await derivePasswordWrappingKey(options.password, salt)\n const wrapped = await subtle.wrapKey('raw', keyring.kek, wrappingKey, 'AES-KW')\n\n return {\n id: options.id ?? 'password-daily',\n method: 'password',\n wrapped_kek: bytesToBase64(new Uint8Array(wrapped)),\n meta: {\n salt: bytesToBase64(salt),\n minLength,\n ...(options.pattern !== undefined ? { pattern: options.pattern.source } : {}),\n },\n enrolled_via_tier: options.enrolledViaTier ?? 1,\n }\n}\n\n/**\n * Recover the KEK from a password slot's `wrapped_kek` ciphertext.\n * Returns the unwrapped KEK as a non-extractable `CryptoKey` ready for\n * AES-KW unwrap of DEKs. Used inside the verify callback passed to\n * `db.unlockViaAuthenticator`.\n *\n * @throws {@link PasswordInvalidError} when the password is wrong.\n */\nexport async function unwrapKekWithPassword(\n slot: KeyringAuthenticator,\n password: string,\n): Promise<CryptoKey> {\n const meta = slot.meta as { salt?: unknown }\n if (typeof meta.salt !== 'string') {\n throw new PasswordInvalidError(\n 'Password slot is missing the per-slot salt — keyring may be corrupted.',\n )\n }\n const salt = base64ToBytes(meta.salt)\n const wrappingKey = await derivePasswordWrappingKey(password, salt)\n try {\n return await subtle.unwrapKey(\n 'raw',\n base64ToBytes(slot.wrapped_kek) as BufferSource,\n wrappingKey,\n 'AES-KW',\n { name: 'AES-KW', length: 256 },\n false,\n ['wrapKey', 'unwrapKey'],\n )\n } catch {\n throw new PasswordInvalidError()\n }\n}\n\n/**\n * Hub-friendly verify callback. Pass to `db.unlockViaAuthenticator`:\n *\n * ```ts\n * const unlocked = await db.unlockViaAuthenticator('acme', 'password-daily',\n * (slot) => verifyPasswordSlot(slot, 'daily-password-2026', { adapter: store, vault: 'acme', userId: 'alice' }),\n * )\n * ```\n *\n * The callback re-loads the keyring file via the supplied adapter,\n * unwraps every DEK with the recovered KEK, and returns the\n * `UnlockedKeyring` the hub installs in its keyring cache.\n *\n * @throws {@link PasswordInvalidError} when the password is wrong.\n */\nexport async function verifyPasswordSlot(\n slot: KeyringAuthenticator,\n password: string,\n options: VerifyPasswordSlotOptions,\n): Promise<UnlockedKeyring> {\n const kek = await unwrapKekWithPassword(slot, password)\n return options.materialize(kek)\n}\n\n/** Adapter shape required by {@link verifyPasswordSlot}. */\nexport interface VerifyPasswordSlotOptions {\n /**\n * Caller-supplied \"given the recovered KEK, build the\n * `UnlockedKeyring`\" routine. The hub provides the standard\n * implementation in {@link buildUnlockedKeyringFromKek}; consumers\n * with non-standard storage (e.g. encrypted browser-extension\n * stores) can pass their own.\n */\n readonly materialize: (kek: CryptoKey) => Promise<UnlockedKeyring>\n}\n\n// ─── Helpers ───────────────────────────────────────────────────────────\n\nasync function derivePasswordWrappingKey(\n password: string,\n salt: Uint8Array,\n): Promise<CryptoKey> {\n const ikm = await subtle.importKey(\n 'raw',\n new TextEncoder().encode(password),\n 'PBKDF2',\n false,\n ['deriveKey'],\n )\n return subtle.deriveKey(\n {\n name: 'PBKDF2',\n salt: salt as BufferSource,\n iterations: PASSWORD_PBKDF2_ITERATIONS,\n hash: 'SHA-256',\n },\n ikm,\n { name: 'AES-KW', length: 256 },\n false,\n ['wrapKey', 'unwrapKey'],\n )\n}\n\nfunction bytesToBase64(bytes: Uint8Array): string {\n let s = ''\n for (const b of bytes) s += String.fromCharCode(b)\n return btoa(s)\n}\n\nfunction base64ToBytes(b64: string): Uint8Array {\n const s = atob(b64)\n const out = new Uint8Array(s.length)\n for (let i = 0; i < s.length; i++) out[i] = s.charCodeAt(i)\n return out\n}\n"],"mappings":"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","names":[]}
|
package/dist/index.d.cts
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
import { UnlockedKeyring, EnrollAuthenticatorOptions, KeyringAuthenticator } from '@noy-db/hub';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* **@noy-db/on-password** — tier-2 daily-password authenticator slot.
|
|
5
|
+
*
|
|
6
|
+
* The user's tier-1 *phrase* is the rarely-typed master that derives
|
|
7
|
+
* the KEK. This package adds a SEPARATE secret — a daily-typed
|
|
8
|
+
* password — as a tier-2 slot in the multi-slot keyring. The two
|
|
9
|
+
* credentials have:
|
|
10
|
+
*
|
|
11
|
+
* - **Different lifecycles** — the phrase rotates yearly; the password
|
|
12
|
+
* rotates per the developer's policy.
|
|
13
|
+
* - **Different strength rules** — the phrase is validated against the
|
|
14
|
+
* phrase format (issue #7); the password is validated against a
|
|
15
|
+
* length / regex rule the developer chooses.
|
|
16
|
+
* - **Different storage** — the phrase derives the KEK; the password
|
|
17
|
+
* derives a wrapping key that wraps the SAME KEK in its own
|
|
18
|
+
* keyring slot (LUKS pattern).
|
|
19
|
+
*
|
|
20
|
+
* The slot is added to the keyring via `db.enrollAuthenticator`; the
|
|
21
|
+
* KEK is recovered via `db.unlockViaAuthenticator` — both routes hit
|
|
22
|
+
* the policy gate engine (issue #9).
|
|
23
|
+
*
|
|
24
|
+
* @see docs/subsystems/session-tiers.md → Tier 2 — `on-password`
|
|
25
|
+
*
|
|
26
|
+
* @packageDocumentation
|
|
27
|
+
*/
|
|
28
|
+
|
|
29
|
+
/** PBKDF2 iteration count — matches the tier-1 phrase derivation. */
|
|
30
|
+
declare const PASSWORD_PBKDF2_ITERATIONS = 600000;
|
|
31
|
+
/** Default minimum password length. Override per-app via `enrollPasswordAuthenticator`. */
|
|
32
|
+
declare const PASSWORD_DEFAULT_MIN_LENGTH = 12;
|
|
33
|
+
declare class PasswordTooWeakError extends Error {
|
|
34
|
+
readonly code: "PASSWORD_TOO_WEAK";
|
|
35
|
+
readonly minLength: number;
|
|
36
|
+
constructor(minLength: number, message?: string);
|
|
37
|
+
}
|
|
38
|
+
declare class PasswordInvalidError extends Error {
|
|
39
|
+
readonly code: "PASSWORD_INVALID";
|
|
40
|
+
constructor(message?: string);
|
|
41
|
+
}
|
|
42
|
+
/** Options for {@link enrollPasswordAuthenticator}. */
|
|
43
|
+
interface EnrollPasswordOptions {
|
|
44
|
+
/** Slot id. Default: `'password-daily'`. */
|
|
45
|
+
readonly id?: string;
|
|
46
|
+
/** Daily password the user will type. Distinct from the tier-1 phrase. */
|
|
47
|
+
readonly password: string;
|
|
48
|
+
/** Minimum length. Default 12. */
|
|
49
|
+
readonly minLength?: number;
|
|
50
|
+
/** Optional regex the password must satisfy in addition to length. */
|
|
51
|
+
readonly pattern?: RegExp;
|
|
52
|
+
/** Tier the active session held when enrolling. Default 1. */
|
|
53
|
+
readonly enrolledViaTier?: 1 | 2;
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* Build the keyring slot for a tier-2 password authenticator. Returns
|
|
57
|
+
* an `EnrollAuthenticatorOptions` value the caller hands to
|
|
58
|
+
* `db.enrollAuthenticator(vault, slot)` — separating the cryptographic
|
|
59
|
+
* step (this function) from the persistence step (the hub) keeps the
|
|
60
|
+
* package small and lets the hub's policy gate run between the two.
|
|
61
|
+
*
|
|
62
|
+
* Usage:
|
|
63
|
+
*
|
|
64
|
+
* ```ts
|
|
65
|
+
* import { enrollPasswordAuthenticator } from '@noy-db/on-password'
|
|
66
|
+
*
|
|
67
|
+
* const slot = await enrollPasswordAuthenticator(unlocked, {
|
|
68
|
+
* password: 'daily-password-2026',
|
|
69
|
+
* minLength: 14,
|
|
70
|
+
* })
|
|
71
|
+
* await db.enrollAuthenticator('acme', slot, {
|
|
72
|
+
* factors: [{ kind: 'totp' }],
|
|
73
|
+
* })
|
|
74
|
+
* ```
|
|
75
|
+
*/
|
|
76
|
+
declare function enrollPasswordAuthenticator(keyring: UnlockedKeyring, options: EnrollPasswordOptions): Promise<EnrollAuthenticatorOptions>;
|
|
77
|
+
/**
|
|
78
|
+
* Recover the KEK from a password slot's `wrapped_kek` ciphertext.
|
|
79
|
+
* Returns the unwrapped KEK as a non-extractable `CryptoKey` ready for
|
|
80
|
+
* AES-KW unwrap of DEKs. Used inside the verify callback passed to
|
|
81
|
+
* `db.unlockViaAuthenticator`.
|
|
82
|
+
*
|
|
83
|
+
* @throws {@link PasswordInvalidError} when the password is wrong.
|
|
84
|
+
*/
|
|
85
|
+
declare function unwrapKekWithPassword(slot: KeyringAuthenticator, password: string): Promise<CryptoKey>;
|
|
86
|
+
/**
|
|
87
|
+
* Hub-friendly verify callback. Pass to `db.unlockViaAuthenticator`:
|
|
88
|
+
*
|
|
89
|
+
* ```ts
|
|
90
|
+
* const unlocked = await db.unlockViaAuthenticator('acme', 'password-daily',
|
|
91
|
+
* (slot) => verifyPasswordSlot(slot, 'daily-password-2026', { adapter: store, vault: 'acme', userId: 'alice' }),
|
|
92
|
+
* )
|
|
93
|
+
* ```
|
|
94
|
+
*
|
|
95
|
+
* The callback re-loads the keyring file via the supplied adapter,
|
|
96
|
+
* unwraps every DEK with the recovered KEK, and returns the
|
|
97
|
+
* `UnlockedKeyring` the hub installs in its keyring cache.
|
|
98
|
+
*
|
|
99
|
+
* @throws {@link PasswordInvalidError} when the password is wrong.
|
|
100
|
+
*/
|
|
101
|
+
declare function verifyPasswordSlot(slot: KeyringAuthenticator, password: string, options: VerifyPasswordSlotOptions): Promise<UnlockedKeyring>;
|
|
102
|
+
/** Adapter shape required by {@link verifyPasswordSlot}. */
|
|
103
|
+
interface VerifyPasswordSlotOptions {
|
|
104
|
+
/**
|
|
105
|
+
* Caller-supplied "given the recovered KEK, build the
|
|
106
|
+
* `UnlockedKeyring`" routine. The hub provides the standard
|
|
107
|
+
* implementation in {@link buildUnlockedKeyringFromKek}; consumers
|
|
108
|
+
* with non-standard storage (e.g. encrypted browser-extension
|
|
109
|
+
* stores) can pass their own.
|
|
110
|
+
*/
|
|
111
|
+
readonly materialize: (kek: CryptoKey) => Promise<UnlockedKeyring>;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
export { type EnrollPasswordOptions, PASSWORD_DEFAULT_MIN_LENGTH, PASSWORD_PBKDF2_ITERATIONS, PasswordInvalidError, PasswordTooWeakError, type VerifyPasswordSlotOptions, enrollPasswordAuthenticator, unwrapKekWithPassword, verifyPasswordSlot };
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
import { UnlockedKeyring, EnrollAuthenticatorOptions, KeyringAuthenticator } from '@noy-db/hub';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* **@noy-db/on-password** — tier-2 daily-password authenticator slot.
|
|
5
|
+
*
|
|
6
|
+
* The user's tier-1 *phrase* is the rarely-typed master that derives
|
|
7
|
+
* the KEK. This package adds a SEPARATE secret — a daily-typed
|
|
8
|
+
* password — as a tier-2 slot in the multi-slot keyring. The two
|
|
9
|
+
* credentials have:
|
|
10
|
+
*
|
|
11
|
+
* - **Different lifecycles** — the phrase rotates yearly; the password
|
|
12
|
+
* rotates per the developer's policy.
|
|
13
|
+
* - **Different strength rules** — the phrase is validated against the
|
|
14
|
+
* phrase format (issue #7); the password is validated against a
|
|
15
|
+
* length / regex rule the developer chooses.
|
|
16
|
+
* - **Different storage** — the phrase derives the KEK; the password
|
|
17
|
+
* derives a wrapping key that wraps the SAME KEK in its own
|
|
18
|
+
* keyring slot (LUKS pattern).
|
|
19
|
+
*
|
|
20
|
+
* The slot is added to the keyring via `db.enrollAuthenticator`; the
|
|
21
|
+
* KEK is recovered via `db.unlockViaAuthenticator` — both routes hit
|
|
22
|
+
* the policy gate engine (issue #9).
|
|
23
|
+
*
|
|
24
|
+
* @see docs/subsystems/session-tiers.md → Tier 2 — `on-password`
|
|
25
|
+
*
|
|
26
|
+
* @packageDocumentation
|
|
27
|
+
*/
|
|
28
|
+
|
|
29
|
+
/** PBKDF2 iteration count — matches the tier-1 phrase derivation. */
|
|
30
|
+
declare const PASSWORD_PBKDF2_ITERATIONS = 600000;
|
|
31
|
+
/** Default minimum password length. Override per-app via `enrollPasswordAuthenticator`. */
|
|
32
|
+
declare const PASSWORD_DEFAULT_MIN_LENGTH = 12;
|
|
33
|
+
declare class PasswordTooWeakError extends Error {
|
|
34
|
+
readonly code: "PASSWORD_TOO_WEAK";
|
|
35
|
+
readonly minLength: number;
|
|
36
|
+
constructor(minLength: number, message?: string);
|
|
37
|
+
}
|
|
38
|
+
declare class PasswordInvalidError extends Error {
|
|
39
|
+
readonly code: "PASSWORD_INVALID";
|
|
40
|
+
constructor(message?: string);
|
|
41
|
+
}
|
|
42
|
+
/** Options for {@link enrollPasswordAuthenticator}. */
|
|
43
|
+
interface EnrollPasswordOptions {
|
|
44
|
+
/** Slot id. Default: `'password-daily'`. */
|
|
45
|
+
readonly id?: string;
|
|
46
|
+
/** Daily password the user will type. Distinct from the tier-1 phrase. */
|
|
47
|
+
readonly password: string;
|
|
48
|
+
/** Minimum length. Default 12. */
|
|
49
|
+
readonly minLength?: number;
|
|
50
|
+
/** Optional regex the password must satisfy in addition to length. */
|
|
51
|
+
readonly pattern?: RegExp;
|
|
52
|
+
/** Tier the active session held when enrolling. Default 1. */
|
|
53
|
+
readonly enrolledViaTier?: 1 | 2;
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* Build the keyring slot for a tier-2 password authenticator. Returns
|
|
57
|
+
* an `EnrollAuthenticatorOptions` value the caller hands to
|
|
58
|
+
* `db.enrollAuthenticator(vault, slot)` — separating the cryptographic
|
|
59
|
+
* step (this function) from the persistence step (the hub) keeps the
|
|
60
|
+
* package small and lets the hub's policy gate run between the two.
|
|
61
|
+
*
|
|
62
|
+
* Usage:
|
|
63
|
+
*
|
|
64
|
+
* ```ts
|
|
65
|
+
* import { enrollPasswordAuthenticator } from '@noy-db/on-password'
|
|
66
|
+
*
|
|
67
|
+
* const slot = await enrollPasswordAuthenticator(unlocked, {
|
|
68
|
+
* password: 'daily-password-2026',
|
|
69
|
+
* minLength: 14,
|
|
70
|
+
* })
|
|
71
|
+
* await db.enrollAuthenticator('acme', slot, {
|
|
72
|
+
* factors: [{ kind: 'totp' }],
|
|
73
|
+
* })
|
|
74
|
+
* ```
|
|
75
|
+
*/
|
|
76
|
+
declare function enrollPasswordAuthenticator(keyring: UnlockedKeyring, options: EnrollPasswordOptions): Promise<EnrollAuthenticatorOptions>;
|
|
77
|
+
/**
|
|
78
|
+
* Recover the KEK from a password slot's `wrapped_kek` ciphertext.
|
|
79
|
+
* Returns the unwrapped KEK as a non-extractable `CryptoKey` ready for
|
|
80
|
+
* AES-KW unwrap of DEKs. Used inside the verify callback passed to
|
|
81
|
+
* `db.unlockViaAuthenticator`.
|
|
82
|
+
*
|
|
83
|
+
* @throws {@link PasswordInvalidError} when the password is wrong.
|
|
84
|
+
*/
|
|
85
|
+
declare function unwrapKekWithPassword(slot: KeyringAuthenticator, password: string): Promise<CryptoKey>;
|
|
86
|
+
/**
|
|
87
|
+
* Hub-friendly verify callback. Pass to `db.unlockViaAuthenticator`:
|
|
88
|
+
*
|
|
89
|
+
* ```ts
|
|
90
|
+
* const unlocked = await db.unlockViaAuthenticator('acme', 'password-daily',
|
|
91
|
+
* (slot) => verifyPasswordSlot(slot, 'daily-password-2026', { adapter: store, vault: 'acme', userId: 'alice' }),
|
|
92
|
+
* )
|
|
93
|
+
* ```
|
|
94
|
+
*
|
|
95
|
+
* The callback re-loads the keyring file via the supplied adapter,
|
|
96
|
+
* unwraps every DEK with the recovered KEK, and returns the
|
|
97
|
+
* `UnlockedKeyring` the hub installs in its keyring cache.
|
|
98
|
+
*
|
|
99
|
+
* @throws {@link PasswordInvalidError} when the password is wrong.
|
|
100
|
+
*/
|
|
101
|
+
declare function verifyPasswordSlot(slot: KeyringAuthenticator, password: string, options: VerifyPasswordSlotOptions): Promise<UnlockedKeyring>;
|
|
102
|
+
/** Adapter shape required by {@link verifyPasswordSlot}. */
|
|
103
|
+
interface VerifyPasswordSlotOptions {
|
|
104
|
+
/**
|
|
105
|
+
* Caller-supplied "given the recovered KEK, build the
|
|
106
|
+
* `UnlockedKeyring`" routine. The hub provides the standard
|
|
107
|
+
* implementation in {@link buildUnlockedKeyringFromKek}; consumers
|
|
108
|
+
* with non-standard storage (e.g. encrypted browser-extension
|
|
109
|
+
* stores) can pass their own.
|
|
110
|
+
*/
|
|
111
|
+
readonly materialize: (kek: CryptoKey) => Promise<UnlockedKeyring>;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
export { type EnrollPasswordOptions, PASSWORD_DEFAULT_MIN_LENGTH, PASSWORD_PBKDF2_ITERATIONS, PasswordInvalidError, PasswordTooWeakError, type VerifyPasswordSlotOptions, enrollPasswordAuthenticator, unwrapKekWithPassword, verifyPasswordSlot };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
// src/index.ts
|
|
2
|
+
var PASSWORD_PBKDF2_ITERATIONS = 6e5;
|
|
3
|
+
var PASSWORD_DEFAULT_MIN_LENGTH = 12;
|
|
4
|
+
var SALT_BYTES = 32;
|
|
5
|
+
var subtle = globalThis.crypto.subtle;
|
|
6
|
+
var PasswordTooWeakError = class extends Error {
|
|
7
|
+
code = "PASSWORD_TOO_WEAK";
|
|
8
|
+
minLength;
|
|
9
|
+
constructor(minLength, message) {
|
|
10
|
+
super(
|
|
11
|
+
message ?? `Password must be at least ${String(minLength)} characters. For accounts with a separate tier-1 phrase, prefer a longer password or pair with TOTP/email-OTP via @noy-db/on-totp or @noy-db/on-email-otp.`
|
|
12
|
+
);
|
|
13
|
+
this.name = "PasswordTooWeakError";
|
|
14
|
+
this.minLength = minLength;
|
|
15
|
+
}
|
|
16
|
+
};
|
|
17
|
+
var PasswordInvalidError = class extends Error {
|
|
18
|
+
code = "PASSWORD_INVALID";
|
|
19
|
+
constructor(message = "Password does not unlock this slot.") {
|
|
20
|
+
super(message);
|
|
21
|
+
this.name = "PasswordInvalidError";
|
|
22
|
+
}
|
|
23
|
+
};
|
|
24
|
+
async function enrollPasswordAuthenticator(keyring, options) {
|
|
25
|
+
const minLength = options.minLength ?? PASSWORD_DEFAULT_MIN_LENGTH;
|
|
26
|
+
if (options.password.length < minLength) {
|
|
27
|
+
throw new PasswordTooWeakError(minLength);
|
|
28
|
+
}
|
|
29
|
+
if (options.pattern && !options.pattern.test(options.password)) {
|
|
30
|
+
throw new PasswordTooWeakError(
|
|
31
|
+
minLength,
|
|
32
|
+
`Password does not match the configured pattern: ${options.pattern.toString()}.`
|
|
33
|
+
);
|
|
34
|
+
}
|
|
35
|
+
if (!keyring.kek) {
|
|
36
|
+
throw new Error(
|
|
37
|
+
"enrollPasswordAuthenticator: the supplied keyring has no KEK in memory. Tier-3 quick-resume keyrings cannot enrol new tier-2 slots; re-authenticate at tier 1 first."
|
|
38
|
+
);
|
|
39
|
+
}
|
|
40
|
+
const salt = crypto.getRandomValues(new Uint8Array(SALT_BYTES));
|
|
41
|
+
const wrappingKey = await derivePasswordWrappingKey(options.password, salt);
|
|
42
|
+
const wrapped = await subtle.wrapKey("raw", keyring.kek, wrappingKey, "AES-KW");
|
|
43
|
+
return {
|
|
44
|
+
id: options.id ?? "password-daily",
|
|
45
|
+
method: "password",
|
|
46
|
+
wrapped_kek: bytesToBase64(new Uint8Array(wrapped)),
|
|
47
|
+
meta: {
|
|
48
|
+
salt: bytesToBase64(salt),
|
|
49
|
+
minLength,
|
|
50
|
+
...options.pattern !== void 0 ? { pattern: options.pattern.source } : {}
|
|
51
|
+
},
|
|
52
|
+
enrolled_via_tier: options.enrolledViaTier ?? 1
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
async function unwrapKekWithPassword(slot, password) {
|
|
56
|
+
const meta = slot.meta;
|
|
57
|
+
if (typeof meta.salt !== "string") {
|
|
58
|
+
throw new PasswordInvalidError(
|
|
59
|
+
"Password slot is missing the per-slot salt \u2014 keyring may be corrupted."
|
|
60
|
+
);
|
|
61
|
+
}
|
|
62
|
+
const salt = base64ToBytes(meta.salt);
|
|
63
|
+
const wrappingKey = await derivePasswordWrappingKey(password, salt);
|
|
64
|
+
try {
|
|
65
|
+
return await subtle.unwrapKey(
|
|
66
|
+
"raw",
|
|
67
|
+
base64ToBytes(slot.wrapped_kek),
|
|
68
|
+
wrappingKey,
|
|
69
|
+
"AES-KW",
|
|
70
|
+
{ name: "AES-KW", length: 256 },
|
|
71
|
+
false,
|
|
72
|
+
["wrapKey", "unwrapKey"]
|
|
73
|
+
);
|
|
74
|
+
} catch {
|
|
75
|
+
throw new PasswordInvalidError();
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
async function verifyPasswordSlot(slot, password, options) {
|
|
79
|
+
const kek = await unwrapKekWithPassword(slot, password);
|
|
80
|
+
return options.materialize(kek);
|
|
81
|
+
}
|
|
82
|
+
async function derivePasswordWrappingKey(password, salt) {
|
|
83
|
+
const ikm = await subtle.importKey(
|
|
84
|
+
"raw",
|
|
85
|
+
new TextEncoder().encode(password),
|
|
86
|
+
"PBKDF2",
|
|
87
|
+
false,
|
|
88
|
+
["deriveKey"]
|
|
89
|
+
);
|
|
90
|
+
return subtle.deriveKey(
|
|
91
|
+
{
|
|
92
|
+
name: "PBKDF2",
|
|
93
|
+
salt,
|
|
94
|
+
iterations: PASSWORD_PBKDF2_ITERATIONS,
|
|
95
|
+
hash: "SHA-256"
|
|
96
|
+
},
|
|
97
|
+
ikm,
|
|
98
|
+
{ name: "AES-KW", length: 256 },
|
|
99
|
+
false,
|
|
100
|
+
["wrapKey", "unwrapKey"]
|
|
101
|
+
);
|
|
102
|
+
}
|
|
103
|
+
function bytesToBase64(bytes) {
|
|
104
|
+
let s = "";
|
|
105
|
+
for (const b of bytes) s += String.fromCharCode(b);
|
|
106
|
+
return btoa(s);
|
|
107
|
+
}
|
|
108
|
+
function base64ToBytes(b64) {
|
|
109
|
+
const s = atob(b64);
|
|
110
|
+
const out = new Uint8Array(s.length);
|
|
111
|
+
for (let i = 0; i < s.length; i++) out[i] = s.charCodeAt(i);
|
|
112
|
+
return out;
|
|
113
|
+
}
|
|
114
|
+
export {
|
|
115
|
+
PASSWORD_DEFAULT_MIN_LENGTH,
|
|
116
|
+
PASSWORD_PBKDF2_ITERATIONS,
|
|
117
|
+
PasswordInvalidError,
|
|
118
|
+
PasswordTooWeakError,
|
|
119
|
+
enrollPasswordAuthenticator,
|
|
120
|
+
unwrapKekWithPassword,
|
|
121
|
+
verifyPasswordSlot
|
|
122
|
+
};
|
|
123
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["/**\n * **@noy-db/on-password** — tier-2 daily-password authenticator slot.\n *\n * The user's tier-1 *phrase* is the rarely-typed master that derives\n * the KEK. This package adds a SEPARATE secret — a daily-typed\n * password — as a tier-2 slot in the multi-slot keyring. The two\n * credentials have:\n *\n * - **Different lifecycles** — the phrase rotates yearly; the password\n * rotates per the developer's policy.\n * - **Different strength rules** — the phrase is validated against the\n * phrase format (issue #7); the password is validated against a\n * length / regex rule the developer chooses.\n * - **Different storage** — the phrase derives the KEK; the password\n * derives a wrapping key that wraps the SAME KEK in its own\n * keyring slot (LUKS pattern).\n *\n * The slot is added to the keyring via `db.enrollAuthenticator`; the\n * KEK is recovered via `db.unlockViaAuthenticator` — both routes hit\n * the policy gate engine (issue #9).\n *\n * @see docs/subsystems/session-tiers.md → Tier 2 — `on-password`\n *\n * @packageDocumentation\n */\nimport type {\n EnrollAuthenticatorOptions,\n KeyringAuthenticator,\n UnlockedKeyring,\n} from '@noy-db/hub'\n\n/** PBKDF2 iteration count — matches the tier-1 phrase derivation. */\nexport const PASSWORD_PBKDF2_ITERATIONS = 600_000\n\n/** Default minimum password length. Override per-app via `enrollPasswordAuthenticator`. */\nexport const PASSWORD_DEFAULT_MIN_LENGTH = 12\n\n/** Per-slot salt size. */\nconst SALT_BYTES = 32\n\nconst subtle = globalThis.crypto.subtle\n\n// ─── Errors ────────────────────────────────────────────────────────────\n\nexport class PasswordTooWeakError extends Error {\n readonly code = 'PASSWORD_TOO_WEAK' as const\n readonly minLength: number\n constructor(minLength: number, message?: string) {\n super(\n message ??\n `Password must be at least ${String(minLength)} characters. ` +\n 'For accounts with a separate tier-1 phrase, prefer a longer password ' +\n 'or pair with TOTP/email-OTP via @noy-db/on-totp or @noy-db/on-email-otp.',\n )\n this.name = 'PasswordTooWeakError'\n this.minLength = minLength\n }\n}\n\nexport class PasswordInvalidError extends Error {\n readonly code = 'PASSWORD_INVALID' as const\n constructor(message = 'Password does not unlock this slot.') {\n super(message)\n this.name = 'PasswordInvalidError'\n }\n}\n\n// ─── Public API ────────────────────────────────────────────────────────\n\n/** Options for {@link enrollPasswordAuthenticator}. */\nexport interface EnrollPasswordOptions {\n /** Slot id. Default: `'password-daily'`. */\n readonly id?: string\n /** Daily password the user will type. Distinct from the tier-1 phrase. */\n readonly password: string\n /** Minimum length. Default 12. */\n readonly minLength?: number\n /** Optional regex the password must satisfy in addition to length. */\n readonly pattern?: RegExp\n /** Tier the active session held when enrolling. Default 1. */\n readonly enrolledViaTier?: 1 | 2\n}\n\n/**\n * Build the keyring slot for a tier-2 password authenticator. Returns\n * an `EnrollAuthenticatorOptions` value the caller hands to\n * `db.enrollAuthenticator(vault, slot)` — separating the cryptographic\n * step (this function) from the persistence step (the hub) keeps the\n * package small and lets the hub's policy gate run between the two.\n *\n * Usage:\n *\n * ```ts\n * import { enrollPasswordAuthenticator } from '@noy-db/on-password'\n *\n * const slot = await enrollPasswordAuthenticator(unlocked, {\n * password: 'daily-password-2026',\n * minLength: 14,\n * })\n * await db.enrollAuthenticator('acme', slot, {\n * factors: [{ kind: 'totp' }],\n * })\n * ```\n */\nexport async function enrollPasswordAuthenticator(\n keyring: UnlockedKeyring,\n options: EnrollPasswordOptions,\n): Promise<EnrollAuthenticatorOptions> {\n const minLength = options.minLength ?? PASSWORD_DEFAULT_MIN_LENGTH\n if (options.password.length < minLength) {\n throw new PasswordTooWeakError(minLength)\n }\n if (options.pattern && !options.pattern.test(options.password)) {\n throw new PasswordTooWeakError(\n minLength,\n `Password does not match the configured pattern: ${options.pattern.toString()}.`,\n )\n }\n\n if (!keyring.kek) {\n throw new Error(\n 'enrollPasswordAuthenticator: the supplied keyring has no KEK in memory. ' +\n 'Tier-3 quick-resume keyrings cannot enrol new tier-2 slots; re-authenticate at tier 1 first.',\n )\n }\n\n const salt = crypto.getRandomValues(new Uint8Array(SALT_BYTES))\n const wrappingKey = await derivePasswordWrappingKey(options.password, salt)\n const wrapped = await subtle.wrapKey('raw', keyring.kek, wrappingKey, 'AES-KW')\n\n return {\n id: options.id ?? 'password-daily',\n method: 'password',\n wrapped_kek: bytesToBase64(new Uint8Array(wrapped)),\n meta: {\n salt: bytesToBase64(salt),\n minLength,\n ...(options.pattern !== undefined ? { pattern: options.pattern.source } : {}),\n },\n enrolled_via_tier: options.enrolledViaTier ?? 1,\n }\n}\n\n/**\n * Recover the KEK from a password slot's `wrapped_kek` ciphertext.\n * Returns the unwrapped KEK as a non-extractable `CryptoKey` ready for\n * AES-KW unwrap of DEKs. Used inside the verify callback passed to\n * `db.unlockViaAuthenticator`.\n *\n * @throws {@link PasswordInvalidError} when the password is wrong.\n */\nexport async function unwrapKekWithPassword(\n slot: KeyringAuthenticator,\n password: string,\n): Promise<CryptoKey> {\n const meta = slot.meta as { salt?: unknown }\n if (typeof meta.salt !== 'string') {\n throw new PasswordInvalidError(\n 'Password slot is missing the per-slot salt — keyring may be corrupted.',\n )\n }\n const salt = base64ToBytes(meta.salt)\n const wrappingKey = await derivePasswordWrappingKey(password, salt)\n try {\n return await subtle.unwrapKey(\n 'raw',\n base64ToBytes(slot.wrapped_kek) as BufferSource,\n wrappingKey,\n 'AES-KW',\n { name: 'AES-KW', length: 256 },\n false,\n ['wrapKey', 'unwrapKey'],\n )\n } catch {\n throw new PasswordInvalidError()\n }\n}\n\n/**\n * Hub-friendly verify callback. Pass to `db.unlockViaAuthenticator`:\n *\n * ```ts\n * const unlocked = await db.unlockViaAuthenticator('acme', 'password-daily',\n * (slot) => verifyPasswordSlot(slot, 'daily-password-2026', { adapter: store, vault: 'acme', userId: 'alice' }),\n * )\n * ```\n *\n * The callback re-loads the keyring file via the supplied adapter,\n * unwraps every DEK with the recovered KEK, and returns the\n * `UnlockedKeyring` the hub installs in its keyring cache.\n *\n * @throws {@link PasswordInvalidError} when the password is wrong.\n */\nexport async function verifyPasswordSlot(\n slot: KeyringAuthenticator,\n password: string,\n options: VerifyPasswordSlotOptions,\n): Promise<UnlockedKeyring> {\n const kek = await unwrapKekWithPassword(slot, password)\n return options.materialize(kek)\n}\n\n/** Adapter shape required by {@link verifyPasswordSlot}. */\nexport interface VerifyPasswordSlotOptions {\n /**\n * Caller-supplied \"given the recovered KEK, build the\n * `UnlockedKeyring`\" routine. The hub provides the standard\n * implementation in {@link buildUnlockedKeyringFromKek}; consumers\n * with non-standard storage (e.g. encrypted browser-extension\n * stores) can pass their own.\n */\n readonly materialize: (kek: CryptoKey) => Promise<UnlockedKeyring>\n}\n\n// ─── Helpers ───────────────────────────────────────────────────────────\n\nasync function derivePasswordWrappingKey(\n password: string,\n salt: Uint8Array,\n): Promise<CryptoKey> {\n const ikm = await subtle.importKey(\n 'raw',\n new TextEncoder().encode(password),\n 'PBKDF2',\n false,\n ['deriveKey'],\n )\n return subtle.deriveKey(\n {\n name: 'PBKDF2',\n salt: salt as BufferSource,\n iterations: PASSWORD_PBKDF2_ITERATIONS,\n hash: 'SHA-256',\n },\n ikm,\n { name: 'AES-KW', length: 256 },\n false,\n ['wrapKey', 'unwrapKey'],\n )\n}\n\nfunction bytesToBase64(bytes: Uint8Array): string {\n let s = ''\n for (const b of bytes) s += String.fromCharCode(b)\n return btoa(s)\n}\n\nfunction base64ToBytes(b64: string): Uint8Array {\n const s = atob(b64)\n const out = new Uint8Array(s.length)\n for (let i = 0; i < s.length; i++) out[i] = s.charCodeAt(i)\n return out\n}\n"],"mappings":"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","names":[]}
|
package/package.json
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@noy-db/on-password",
|
|
3
|
+
"version": "0.1.0-pre.5",
|
|
4
|
+
"description": "Tier-2 daily-password authenticator slot for noy-db. PBKDF2-SHA256 600K wraps the KEK in its own keyring slot, distinct from the rarely-typed tier-1 phrase. Pair with @noy-db/on-email-otp or @noy-db/on-totp for the SaaS UX.",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"author": "vLannaAi <vicio@lanna.ai>",
|
|
7
|
+
"homepage": "https://github.com/vLannaAi/noy-db/tree/main/packages/on-password#readme",
|
|
8
|
+
"repository": {
|
|
9
|
+
"type": "git",
|
|
10
|
+
"url": "git+https://github.com/vLannaAi/noy-db.git",
|
|
11
|
+
"directory": "packages/on-password"
|
|
12
|
+
},
|
|
13
|
+
"bugs": {
|
|
14
|
+
"url": "https://github.com/vLannaAi/noy-db/issues"
|
|
15
|
+
},
|
|
16
|
+
"type": "module",
|
|
17
|
+
"sideEffects": false,
|
|
18
|
+
"exports": {
|
|
19
|
+
".": {
|
|
20
|
+
"import": {
|
|
21
|
+
"types": "./dist/index.d.ts",
|
|
22
|
+
"default": "./dist/index.js"
|
|
23
|
+
},
|
|
24
|
+
"require": {
|
|
25
|
+
"types": "./dist/index.d.cts",
|
|
26
|
+
"default": "./dist/index.cjs"
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
},
|
|
30
|
+
"main": "./dist/index.cjs",
|
|
31
|
+
"module": "./dist/index.js",
|
|
32
|
+
"types": "./dist/index.d.ts",
|
|
33
|
+
"files": [
|
|
34
|
+
"dist",
|
|
35
|
+
"README.md",
|
|
36
|
+
"LICENSE"
|
|
37
|
+
],
|
|
38
|
+
"engines": {
|
|
39
|
+
"node": ">=18.0.0"
|
|
40
|
+
},
|
|
41
|
+
"peerDependencies": {
|
|
42
|
+
"@noy-db/hub": "0.1.0-pre.5"
|
|
43
|
+
},
|
|
44
|
+
"devDependencies": {
|
|
45
|
+
"@noy-db/hub": "0.1.0-pre.5"
|
|
46
|
+
},
|
|
47
|
+
"keywords": [
|
|
48
|
+
"noy-db",
|
|
49
|
+
"auth",
|
|
50
|
+
"on-password",
|
|
51
|
+
"tier-2",
|
|
52
|
+
"password",
|
|
53
|
+
"pbkdf2",
|
|
54
|
+
"keyring-slot",
|
|
55
|
+
"zero-knowledge"
|
|
56
|
+
],
|
|
57
|
+
"publishConfig": {
|
|
58
|
+
"access": "public",
|
|
59
|
+
"tag": "latest"
|
|
60
|
+
},
|
|
61
|
+
"scripts": {
|
|
62
|
+
"build": "tsup",
|
|
63
|
+
"test": "vitest run",
|
|
64
|
+
"lint": "eslint src/",
|
|
65
|
+
"typecheck": "tsc --noEmit"
|
|
66
|
+
}
|
|
67
|
+
}
|