node-opcua-role-set-common 2.174.0 → 2.175.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.
@@ -1,6 +1,9 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.InMemoryUserManagementStore = void 0;
4
+ exports.serializeUser = serializeUser;
5
+ exports.credentialRecord = credentialRecord;
6
+ exports.validateUserConfiguration = validateUserConfiguration;
4
7
  /**
5
8
  * @module node-opcua-role-set-common
6
9
  *
@@ -9,13 +12,54 @@ exports.InMemoryUserManagementStore = void 0;
9
12
  *
10
13
  * The store implements the behaviour of the AddUser / ModifyUser / RemoveUser
11
14
  * / ChangePassword Methods and the password policy (PasswordLength range and
12
- * the password-option requirements). Passwords are never stored in clear:
13
- * each is salted and hashed with scrypt.
15
+ * the password-option requirements). Passwords are never stored in clear: each
16
+ * is kept as a self-describing PHC credential string (scrypt by default; other
17
+ * schemes such as bcrypt coexist and are migrated on login — see
18
+ * {@link HasherRegistry}). Credential operations are **async** so an external
19
+ * verifier (LDAP/argon2) can be plugged in without another interface change.
14
20
  */
15
- const node_crypto_1 = require("node:crypto");
16
21
  const node_opcua_status_code_1 = require("node-opcua-status-code");
17
22
  const node_opcua_types_1 = require("node-opcua-types");
23
+ const password_hasher_js_1 = require("./password_hasher.js");
18
24
  const has = (mask, bit) => (mask & bit) === bit;
25
+ /** A record is legacy (v1) when it carries raw `salt`+`hash` instead of a `credential`. */
26
+ function isLegacyRecord(r) {
27
+ return typeof r.credential !== "string";
28
+ }
29
+ /** Shared default scrypt hasher used by the offline {@link serializeUser} helper. */
30
+ const offlineScrypt = new password_hasher_js_1.ScryptHasher();
31
+ /**
32
+ * Produce a {@link SerializedUserRecord} (scrypt PHC credential) from a
33
+ * clear-text password — **offline**, without a store.
34
+ *
35
+ * Use this to keep clear-text passwords out of version control / config: run it
36
+ * once at deploy time and commit only the returned record, then seed it through
37
+ * `importUsers` (or `createRoleBasedSecurity`'s `passwordHash`). The record is
38
+ * interchangeable with what {@link InMemoryUserManagementStore.exportUsers}
39
+ * produces, so `authenticate` accepts the original clear-text password.
40
+ */
41
+ async function serializeUser(userName, password, options) {
42
+ return {
43
+ userName,
44
+ credential: await offlineScrypt.hash(password),
45
+ userConfiguration: options?.userConfiguration ?? node_opcua_types_1.UserConfigurationMask.None,
46
+ description: options?.description ?? ""
47
+ };
48
+ }
49
+ /**
50
+ * Wrap an **already-hashed** PHC credential string (e.g. a legacy `$2b$…`
51
+ * bcrypt hash) into a {@link SerializedUserRecord} — no clear text, no
52
+ * re-hashing. The credential is verified by whichever registered scheme owns
53
+ * its prefix, and (for non-default schemes) upgraded on next login.
54
+ */
55
+ function credentialRecord(userName, credential, options) {
56
+ return {
57
+ userName,
58
+ credential,
59
+ userConfiguration: options?.userConfiguration ?? node_opcua_types_1.UserConfigurationMask.None,
60
+ description: options?.description ?? ""
61
+ };
62
+ }
19
63
  /**
20
64
  * In-memory implementation of {@link IUserManagementStore}.
21
65
  *
@@ -24,12 +68,18 @@ const has = (mask, bit) => (mask & bit) === bit;
24
68
  class InMemoryUserManagementStore {
25
69
  _users = new Map();
26
70
  _policy;
27
- constructor(policy) {
71
+ _registry;
72
+ _onCredentialUpgraded;
73
+ constructor(policy, options) {
28
74
  this._policy = policy ?? {};
75
+ this._registry = options?.registry ?? (0, password_hasher_js_1.defaultHasherRegistry)();
29
76
  }
30
77
  get policy() {
31
78
  return this._policy;
32
79
  }
80
+ setOnCredentialUpgraded(fn) {
81
+ this._onCredentialUpgraded = fn;
82
+ }
33
83
  hasUser(userName) {
34
84
  return this._users.has(userName);
35
85
  }
@@ -43,24 +93,25 @@ class InMemoryUserManagementStore {
43
93
  exportUsers() {
44
94
  return [...this._users.values()].map((u) => ({
45
95
  userName: u.userName,
46
- salt: u.salt.toString("base64"),
47
- hash: u.hash.toString("base64"),
96
+ credential: u.credential,
48
97
  userConfiguration: u.userConfiguration,
49
98
  description: u.description
50
99
  }));
51
100
  }
52
101
  importUsers(records) {
53
102
  for (const r of records) {
103
+ // v1 archives stored raw scrypt salt+hash — migrate to a $scrypt$ PHC
104
+ // credential on read (lossless: same algorithm and parameters).
105
+ const credential = isLegacyRecord(r) ? (0, password_hasher_js_1.scryptPhc)(r.salt, r.hash) : r.credential;
54
106
  this._users.set(r.userName, {
55
107
  userName: r.userName,
56
- salt: Buffer.from(r.salt, "base64"),
57
- hash: Buffer.from(r.hash, "base64"),
108
+ credential,
58
109
  userConfiguration: r.userConfiguration,
59
110
  description: r.description
60
111
  });
61
112
  }
62
113
  }
63
- addUser(userName, password, userConfiguration, description) {
114
+ async addUser(userName, password, userConfiguration, description) {
64
115
  if (this._users.has(userName)) {
65
116
  return node_opcua_status_code_1.StatusCodes.BadAlreadyExists;
66
117
  }
@@ -71,10 +122,11 @@ class InMemoryUserManagementStore {
71
122
  if (!this.isPasswordValid(password)) {
72
123
  return node_opcua_status_code_1.StatusCodes.BadOutOfRange;
73
124
  }
74
- this._users.set(userName, { userName, ...this.hashPassword(password), userConfiguration, description });
125
+ const credential = await this._registry.hash(password);
126
+ this._users.set(userName, { userName, credential, userConfiguration, description });
75
127
  return node_opcua_status_code_1.StatusCodes.Good;
76
128
  }
77
- modifyUser(userName, options, callerUserName) {
129
+ async modifyUser(userName, options, callerUserName) {
78
130
  const user = this._users.get(userName);
79
131
  if (!user) {
80
132
  return node_opcua_status_code_1.StatusCodes.BadNotFound;
@@ -100,9 +152,7 @@ class InMemoryUserManagementStore {
100
152
  }
101
153
  // All checks passed — apply the changes
102
154
  if (options.modifyPassword) {
103
- const { salt, hash } = this.hashPassword(options.password ?? "");
104
- user.salt = salt;
105
- user.hash = hash;
155
+ user.credential = await this._registry.hash(options.password ?? "");
106
156
  }
107
157
  if (options.modifyUserConfiguration) {
108
158
  user.userConfiguration = nextConfig;
@@ -126,7 +176,7 @@ class InMemoryUserManagementStore {
126
176
  this._users.delete(userName);
127
177
  return node_opcua_status_code_1.StatusCodes.Good;
128
178
  }
129
- changePassword(userName, oldPassword, newPassword) {
179
+ async changePassword(userName, oldPassword, newPassword) {
130
180
  const user = this._users.get(userName);
131
181
  // Unknown user is treated as an invalid old password (§5.2.8)
132
182
  if (!user) {
@@ -135,7 +185,7 @@ class InMemoryUserManagementStore {
135
185
  if (has(user.userConfiguration, node_opcua_types_1.UserConfigurationMask.NoChangeByUser)) {
136
186
  return node_opcua_status_code_1.StatusCodes.BadNotSupported;
137
187
  }
138
- if (!this.verify(user, oldPassword)) {
188
+ if (!(await this._registry.verify(oldPassword, user.credential))) {
139
189
  return node_opcua_status_code_1.StatusCodes.BadIdentityTokenInvalid;
140
190
  }
141
191
  if (oldPassword === newPassword) {
@@ -144,22 +194,26 @@ class InMemoryUserManagementStore {
144
194
  if (!this.isPasswordValid(newPassword)) {
145
195
  return node_opcua_status_code_1.StatusCodes.BadOutOfRange;
146
196
  }
147
- const { salt, hash } = this.hashPassword(newPassword);
148
- user.salt = salt;
149
- user.hash = hash;
197
+ user.credential = await this._registry.hash(newPassword);
150
198
  // A successful change clears the MustChangePassword flag (§5.2.8)
151
199
  user.userConfiguration &= ~node_opcua_types_1.UserConfigurationMask.MustChangePassword;
152
200
  return node_opcua_status_code_1.StatusCodes.Good;
153
201
  }
154
- authenticate(userName, password) {
202
+ async authenticate(userName, password) {
155
203
  const user = this._users.get(userName);
156
204
  // A disabled user behaves like a user that does not exist (§5.2.3)
157
205
  if (!user || has(user.userConfiguration, node_opcua_types_1.UserConfigurationMask.Disabled)) {
158
206
  return { statusCode: node_opcua_status_code_1.StatusCodes.BadUserAccessDenied, mustChangePassword: false };
159
207
  }
160
- if (!this.verify(user, password)) {
208
+ if (!(await this._registry.verify(password, user.credential))) {
161
209
  return { statusCode: node_opcua_status_code_1.StatusCodes.BadUserAccessDenied, mustChangePassword: false };
162
210
  }
211
+ // Upgrade-on-login: transparently re-hash a legacy/drifted credential with
212
+ // the default scheme (e.g. bcrypt → scrypt) now that we hold the clear text.
213
+ if (this._registry.needsRehash(user.credential)) {
214
+ user.credential = await this._registry.hash(password);
215
+ this._onCredentialUpgraded?.(userName);
216
+ }
163
217
  if (has(user.userConfiguration, node_opcua_types_1.UserConfigurationMask.MustChangePassword)) {
164
218
  return { statusCode: node_opcua_status_code_1.StatusCodes.GoodPasswordChangeRequired, mustChangePassword: true };
165
219
  }
@@ -182,15 +236,6 @@ class InMemoryUserManagementStore {
182
236
  return false;
183
237
  return true;
184
238
  }
185
- hashPassword(password) {
186
- const salt = (0, node_crypto_1.randomBytes)(16);
187
- const hash = (0, node_crypto_1.scryptSync)(password, salt, 64);
188
- return { salt, hash };
189
- }
190
- verify(user, password) {
191
- const candidate = (0, node_crypto_1.scryptSync)(password, user.salt, 64);
192
- return candidate.length === user.hash.length && (0, node_crypto_1.timingSafeEqual)(candidate, user.hash);
193
- }
194
239
  }
195
240
  exports.InMemoryUserManagementStore = InMemoryUserManagementStore;
196
241
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"user_management_store.js","sourceRoot":"","sources":["../source/user_management_store.ts"],"names":[],"mappings":";;;AAAA;;;;;;;;;;GAUG;AACH,6CAAuE;AACvE,mEAAsE;AACtE,uDAAyD;AAyEzD,MAAM,GAAG,GAAG,CAAC,IAA2B,EAAE,GAA0B,EAAW,EAAE,CAAC,CAAC,IAAI,GAAG,GAAG,CAAC,KAAK,GAAG,CAAC;AAEvG;;;;GAIG;AACH,MAAa,2BAA2B;IACnB,MAAM,GAAG,IAAI,GAAG,EAAwB,CAAC;IACzC,OAAO,CAAiB;IAEzC,YAAY,MAAuB;QAC/B,IAAI,CAAC,OAAO,GAAG,MAAM,IAAI,EAAE,CAAC;IAChC,CAAC;IAED,IAAW,MAAM;QACb,OAAO,IAAI,CAAC,OAAO,CAAC;IACxB,CAAC;IAEM,OAAO,CAAC,QAAgB;QAC3B,OAAO,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;IACrC,CAAC;IAEM,QAAQ;QACX,OAAO,CAAC,GAAG,IAAI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AED,mEAAmE;IAC5D,eAAe,CAAC,QAAgB;QACnC,MAAM,CAAC,GAAG,IAAI,CAAC,OAAO,CAAC;QACvB,IAAI,CAAC,CAAC,SAAS,IAAI,QAAQ,CAAC,MAAM,GAAG,CAAC,CAAC,SAAS;YAAE,OAAO,KAAK,CAAC;QAC/D,IAAI,CAAC,CAAC,SAAS,IAAI,QAAQ,CAAC,MAAM,GAAG,CAAC,CAAC,SAAS;YAAE,OAAO,KAAK,CAAC;QAC/D,IAAI,CAAC,CAAC,gBAAgB,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,QAAQ,CAAC;YAAE,OAAO,KAAK,CAAC;QAChE,IAAI,CAAC,CAAC,gBAAgB,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,QAAQ,CAAC;YAAE,OAAO,KAAK,CAAC;QAChE,IAAI,CAAC,CAAC,YAAY,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,QAAQ,CAAC;YAAE,OAAO,KAAK,CAAC;QAC5D,IAAI,CAAC,CAAC,cAAc,IAAI,CAAC,cAAc,CAAC,IAAI,CAAC,QAAQ,CAAC;YAAE,OAAO,KAAK,CAAC;QACrE,OAAO,IAAI,CAAC;IAChB,CAAC;CACJ;AA1LD,kEA0LC;AAED;;;;;GAKG;AACH,SAAgB,yBAAyB,CAAC,IAA2B;IACjE,IAAI,GAAG,CAAC,IAAI,EAAE,wCAAqB,CAAC,kBAAkB,CAAC,IAAI,GAAG,CAAC,IAAI,EAAE,wCAAqB,CAAC,cAAc,CAAC,EAAE,CAAC;QACzG,OAAO,oCAAW,CAAC,qBAAqB,CAAC;IAC7C,CAAC;IACD,OAAO,IAAI,CAAC;AAChB,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "node-opcua-role-set-common",
3
- "version": "2.174.0",
3
+ "version": "2.175.0",
4
4
  "description": "pure nodejs OPCUA SDK - role-set common types and identity stores (OPC 10000-18)",
5
5
  "scripts": {
6
6
  "build": "tsc -b",
@@ -16,6 +16,7 @@
16
16
  "npm": ">=10.x"
17
17
  },
18
18
  "dependencies": {
19
+ "bcryptjs": "3.0.3",
19
20
  "node-opcua-basic-types": "2.174.0",
20
21
  "node-opcua-binary-stream": "2.173.0",
21
22
  "node-opcua-constants": "2.174.0",
@@ -43,7 +44,7 @@
43
44
  "internet of things"
44
45
  ],
45
46
  "homepage": "http://node-opcua.github.io/",
46
- "gitHead": "064029878247adf2fa5d14a8124e1930431e2428",
47
+ "gitHead": "b15c534b0f03502d30c49934c36291368bdacb80",
47
48
  "files": [
48
49
  "dist",
49
50
  "source"
package/source/archive.ts CHANGED
@@ -25,9 +25,15 @@ import { BinaryStream } from "node-opcua-binary-stream";
25
25
  import { decodeIdentityStore, encodeIdentityStore, identityStoreBinaryStoreSize } from "./binary_persistence.js";
26
26
  import type { IIdentityMappingStore } from "./identity_mapping_store.js";
27
27
  import type { SerializedRoleRestriction } from "./role_restriction_store.js";
28
- import type { SerializedUserRecord } from "./user_management_store.js";
28
+ import type { LegacySerializedUserRecord, SerializedUserRecord } from "./user_management_store.js";
29
29
 
30
- export const ROLE_SET_ARCHIVE_VERSION = 1;
30
+ /**
31
+ * v1: users stored as raw scrypt `{salt, hash}`.
32
+ * v2: users stored as a self-describing PHC `credential` string (scrypt/bcrypt/…).
33
+ * v1 archives are still read (records are migrated on import); v2 archives are
34
+ * rejected by a v1 reader via the version check.
35
+ */
36
+ export const ROLE_SET_ARCHIVE_VERSION = 2;
31
37
 
32
38
  /** Persisted definition of a custom Role (so its GUID NodeId survives a restart). */
33
39
  export interface PersistedCustomRole {
@@ -43,8 +49,12 @@ export interface RoleSetArchive {
43
49
  identities?: string;
44
50
  roles?: PersistedCustomRole[];
45
51
  restrictions?: SerializedRoleRestriction[];
46
- /** UserManagement users with salted scrypt hashes (never clear passwords). */
47
- users?: SerializedUserRecord[];
52
+ /**
53
+ * UserManagement users, credentials only (never clear passwords). v2 writes
54
+ * PHC {@link SerializedUserRecord}s; v1 archives are read as
55
+ * {@link LegacySerializedUserRecord}s and migrated on import.
56
+ */
57
+ users?: (SerializedUserRecord | LegacySerializedUserRecord)[];
48
58
  }
49
59
 
50
60
  /** Encode the identity store as a base64 string (reuses the binary encoder). */
package/source/index.ts CHANGED
@@ -22,6 +22,14 @@ export {
22
22
  } from "./binary_persistence.js";
23
23
  export type { AnyUserIdentityToken, IIdentityMappingStore } from "./identity_mapping_store.js";
24
24
  export { InMemoryIdentityMappingStore } from "./in_memory_store.js";
25
+ export {
26
+ BcryptHasher,
27
+ defaultHasherRegistry,
28
+ HasherRegistry,
29
+ type PasswordHasher,
30
+ ScryptHasher,
31
+ scryptPhc
32
+ } from "./password_hasher.js";
25
33
  export {
26
34
  applicationComplies,
27
35
  deserializeRestrictions,
@@ -37,12 +45,16 @@ export {
37
45
  } from "./role_restriction_store.js";
38
46
  export {
39
47
  type AuthenticationResult,
48
+ credentialRecord,
40
49
  InMemoryUserManagementStore,
41
50
  type IUserManagementStore,
51
+ type LegacySerializedUserRecord,
42
52
  type ModifyUserOptions,
43
53
  type PasswordPolicy,
44
54
  type SerializedUserRecord,
45
- type UserRecord
55
+ serializeUser,
56
+ type UserRecord,
57
+ validateUserConfiguration
46
58
  } from "./user_management_store.js";
47
59
  export { WellKnownRoleIds, WellKnownRoles } from "./well_known_role_ids.js";
48
60
  export {
@@ -0,0 +1,200 @@
1
+ /**
2
+ * @module node-opcua-role-set-common
3
+ *
4
+ * Pluggable password hashing (OPC 10000-18 §5 credentials).
5
+ *
6
+ * Each stored credential is a single self-describing **PHC / modular-crypt
7
+ * string** so multiple schemes can coexist and be told apart by prefix:
8
+ *
9
+ * ```
10
+ * scrypt: $scrypt$ln=<log2N>,r=<r>,p=<p>$<b64 salt>$<b64 hash>
11
+ * bcrypt: $2b$<cost>$<22-char salt><31-char hash> (bcrypt's native format)
12
+ * ```
13
+ *
14
+ * A {@link HasherRegistry} verifies a credential by routing on its prefix and
15
+ * always *hashes* new credentials with the configured default (scrypt — Node
16
+ * core, zero extra dependency). Because non-default schemes report
17
+ * {@link PasswordHasher.needsRehash}=true, a store can transparently migrate a
18
+ * legacy credential to the default algorithm on the next successful login
19
+ * ("upgrade-on-login"). Additional schemes (bcrypt today, LDAP/argon2 later)
20
+ * are just more {@link PasswordHasher}s in the registry.
21
+ */
22
+ import { randomBytes, scryptSync, timingSafeEqual } from "node:crypto";
23
+ import bcrypt from "bcryptjs";
24
+
25
+ /** A single password-hashing scheme. All operations are async (LDAP/argon2-ready). */
26
+ export interface PasswordHasher {
27
+ /** Canonical scheme id, e.g. `"scrypt"`, `"bcrypt"`. */
28
+ readonly id: string;
29
+ /** PHC prefixes this hasher verifies, e.g. `["$scrypt$"]` or `["$2a$", "$2b$", "$2y$"]`. */
30
+ readonly prefixes: readonly string[];
31
+ /** Hash a clear-text password into a full PHC string. */
32
+ hash(password: string): Promise<string>;
33
+ /** Verify a clear-text password against a PHC string produced by this scheme. */
34
+ verify(password: string, phc: string): Promise<boolean>;
35
+ /** True when a credential should be re-hashed after a successful login (e.g. cost drifted). */
36
+ needsRehash?(phc: string): boolean;
37
+ }
38
+
39
+ // ---------------------------------------------------------------------------
40
+ // scrypt (default — Node core, no extra dependency)
41
+ // ---------------------------------------------------------------------------
42
+
43
+ const SCRYPT_N = 16384; // ln = 14
44
+ const SCRYPT_R = 8;
45
+ const SCRYPT_P = 1;
46
+ const SCRYPT_KEYLEN = 64;
47
+ const SCRYPT_SALT_BYTES = 16;
48
+ const SCRYPT_LN = Math.log2(SCRYPT_N);
49
+
50
+ // Upper bounds on the work factors accepted from a stored credential string.
51
+ // A tampered/poisoned credential (e.g. an edited archive) must not be able to
52
+ // set huge parameters and cause resource exhaustion during login, so anything
53
+ // out of range is rejected (parseScrypt returns null → verify() fails closed).
54
+ // The default (ln=14, r=8, p=1) sits comfortably below these limits.
55
+ const SCRYPT_LN_MAX = 20; // N = 2^20 (~1M) — beyond any legitimate configuration here
56
+ const SCRYPT_R_MAX = 32;
57
+ const SCRYPT_P_MAX = 16;
58
+
59
+ interface ParsedScrypt {
60
+ ln: number;
61
+ r: number;
62
+ p: number;
63
+ salt: Buffer;
64
+ hash: Buffer;
65
+ }
66
+
67
+ /** Build the canonical scrypt PHC string from a base64 salt + hash. */
68
+ export function scryptPhc(saltB64: string, hashB64: string, params?: { ln?: number; r?: number; p?: number }): string {
69
+ const ln = params?.ln ?? SCRYPT_LN;
70
+ const r = params?.r ?? SCRYPT_R;
71
+ const p = params?.p ?? SCRYPT_P;
72
+ return `$scrypt$ln=${ln},r=${r},p=${p}$${saltB64}$${hashB64}`;
73
+ }
74
+
75
+ function parseScrypt(phc: string): ParsedScrypt | null {
76
+ // $scrypt$ln=14,r=8,p=1$<salt>$<hash>
77
+ const m = /^\$scrypt\$ln=(\d+),r=(\d+),p=(\d+)\$([^$]+)\$([^$]+)$/.exec(phc);
78
+ if (!m) return null;
79
+ const ln = Number(m[1]);
80
+ const r = Number(m[2]);
81
+ const p = Number(m[3]);
82
+ // Reject out-of-range work factors so a tampered credential can't force an
83
+ // absurd scryptSync cost. Fails closed: verify() treats null as "no match".
84
+ if (ln < 1 || ln > SCRYPT_LN_MAX || r < 1 || r > SCRYPT_R_MAX || p < 1 || p > SCRYPT_P_MAX) {
85
+ return null;
86
+ }
87
+ return {
88
+ ln,
89
+ r,
90
+ p,
91
+ salt: Buffer.from(m[4], "base64"),
92
+ hash: Buffer.from(m[5], "base64")
93
+ };
94
+ }
95
+
96
+ export class ScryptHasher implements PasswordHasher {
97
+ public readonly id = "scrypt";
98
+ public readonly prefixes = ["$scrypt$"] as const;
99
+
100
+ public async hash(password: string): Promise<string> {
101
+ const salt = randomBytes(SCRYPT_SALT_BYTES);
102
+ const hash = scryptSync(password, salt, SCRYPT_KEYLEN, { N: SCRYPT_N, r: SCRYPT_R, p: SCRYPT_P });
103
+ return scryptPhc(salt.toString("base64"), hash.toString("base64"));
104
+ }
105
+
106
+ public async verify(password: string, phc: string): Promise<boolean> {
107
+ const parsed = parseScrypt(phc);
108
+ if (!parsed) return false;
109
+ const candidate = scryptSync(password, parsed.salt, parsed.hash.length, {
110
+ N: 2 ** parsed.ln,
111
+ r: parsed.r,
112
+ p: parsed.p
113
+ });
114
+ return candidate.length === parsed.hash.length && timingSafeEqual(candidate, parsed.hash);
115
+ }
116
+
117
+ public needsRehash(phc: string): boolean {
118
+ const parsed = parseScrypt(phc);
119
+ // Re-hash if unparsable or the work factors drifted below the current defaults.
120
+ return !parsed || parsed.ln !== SCRYPT_LN || parsed.r !== SCRYPT_R || parsed.p !== SCRYPT_P;
121
+ }
122
+ }
123
+
124
+ // ---------------------------------------------------------------------------
125
+ // bcrypt (verify-only default: migrated to scrypt on next login)
126
+ // ---------------------------------------------------------------------------
127
+
128
+ export class BcryptHasher implements PasswordHasher {
129
+ public readonly id = "bcrypt";
130
+ public readonly prefixes = ["$2a$", "$2b$", "$2y$"] as const;
131
+
132
+ public constructor(private readonly _cost = 10) {}
133
+
134
+ public async hash(password: string): Promise<string> {
135
+ return bcrypt.hash(password, this._cost);
136
+ }
137
+
138
+ public async verify(password: string, phc: string): Promise<boolean> {
139
+ return bcrypt.compare(password, phc);
140
+ }
141
+
142
+ // bcrypt is only kept for interop/migration — always upgrade to the default.
143
+ public needsRehash(): boolean {
144
+ return true;
145
+ }
146
+ }
147
+
148
+ // ---------------------------------------------------------------------------
149
+ // Registry — hash with the default, verify by routing on the PHC prefix
150
+ // ---------------------------------------------------------------------------
151
+
152
+ export class HasherRegistry {
153
+ private readonly _all: PasswordHasher[];
154
+
155
+ public constructor(
156
+ private readonly _default: PasswordHasher,
157
+ others: readonly PasswordHasher[] = []
158
+ ) {
159
+ this._all = [_default, ...others];
160
+ }
161
+
162
+ public get defaultId(): string {
163
+ return this._default.id;
164
+ }
165
+
166
+ /** Hash a new/changed password with the configured default scheme. */
167
+ public hash(password: string): Promise<string> {
168
+ return this._default.hash(password);
169
+ }
170
+
171
+ /** Verify against whichever registered scheme owns the credential's prefix. */
172
+ public async verify(password: string, phc: string): Promise<boolean> {
173
+ const hasher = this._find(phc);
174
+ return hasher ? hasher.verify(password, phc) : false;
175
+ }
176
+
177
+ /**
178
+ * True when the credential should be re-hashed with the default after a
179
+ * successful login: a different scheme than the default, or the same scheme
180
+ * reporting drifted parameters.
181
+ */
182
+ public needsRehash(phc: string): boolean {
183
+ const hasher = this._find(phc);
184
+ if (!hasher) return false;
185
+ if (hasher !== this._default) return true;
186
+ return hasher.needsRehash ? hasher.needsRehash(phc) : false;
187
+ }
188
+
189
+ private _find(phc: string): PasswordHasher | undefined {
190
+ return this._all.find((h) => h.prefixes.some((prefix) => phc.startsWith(prefix)));
191
+ }
192
+ }
193
+
194
+ /**
195
+ * Default registry: **scrypt** hashes and verifies (Node core), **bcrypt**
196
+ * verifies legacy credentials and is upgraded to scrypt on next login.
197
+ */
198
+ export function defaultHasherRegistry(): HasherRegistry {
199
+ return new HasherRegistry(new ScryptHasher(), [new BcryptHasher()]);
200
+ }