node-opcua-role-set-common 2.174.0 → 2.175.1
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 +48 -0
- package/dist/archive.d.ts +14 -4
- package/dist/archive.js +7 -1
- package/dist/archive.js.map +1 -1
- package/dist/in_memory_store.js +14 -5
- package/dist/in_memory_store.js.map +1 -1
- package/dist/index.d.ts +2 -1
- package/dist/index.js +10 -1
- package/dist/index.js.map +1 -1
- package/dist/password_hasher.d.ts +57 -0
- package/dist/password_hasher.js +172 -0
- package/dist/password_hasher.js.map +1 -0
- package/dist/user_management_store.d.ts +86 -17
- package/dist/user_management_store.js +75 -30
- package/dist/user_management_store.js.map +1 -1
- package/package.json +11 -10
- package/source/archive.ts +14 -4
- package/source/in_memory_store.ts +19 -7
- package/source/index.ts +13 -1
- package/source/password_hasher.ts +200 -0
- package/source/user_management_store.ts +125 -45
|
@@ -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
|
+
}
|
|
@@ -6,13 +6,17 @@
|
|
|
6
6
|
*
|
|
7
7
|
* The store implements the behaviour of the AddUser / ModifyUser / RemoveUser
|
|
8
8
|
* / ChangePassword Methods and the password policy (PasswordLength range and
|
|
9
|
-
* the password-option requirements). Passwords are never stored in clear:
|
|
10
|
-
*
|
|
9
|
+
* the password-option requirements). Passwords are never stored in clear: each
|
|
10
|
+
* is kept as a self-describing PHC credential string (scrypt by default; other
|
|
11
|
+
* schemes such as bcrypt coexist and are migrated on login — see
|
|
12
|
+
* {@link HasherRegistry}). Credential operations are **async** so an external
|
|
13
|
+
* verifier (LDAP/argon2) can be plugged in without another interface change.
|
|
11
14
|
*/
|
|
12
|
-
import { randomBytes, scryptSync, timingSafeEqual } from "node:crypto";
|
|
13
15
|
import { type StatusCode, StatusCodes } from "node-opcua-status-code";
|
|
14
16
|
import { UserConfigurationMask } from "node-opcua-types";
|
|
15
17
|
|
|
18
|
+
import { defaultHasherRegistry, type HasherRegistry, ScryptHasher, scryptPhc } from "./password_hasher.js";
|
|
19
|
+
|
|
16
20
|
/**
|
|
17
21
|
* Password requirements (OPC 10000-18 §5.2.1-2: PasswordLength range and
|
|
18
22
|
* PasswordOptionsMask). A length of 0 means "no limit".
|
|
@@ -34,10 +38,25 @@ export interface UserRecord {
|
|
|
34
38
|
}
|
|
35
39
|
|
|
36
40
|
/**
|
|
37
|
-
* Persisted user record —
|
|
38
|
-
*
|
|
41
|
+
* Persisted user record (archive v2) — the credential is a self-describing PHC
|
|
42
|
+
* string (e.g. `$scrypt$…` / `$2b$…`), never a clear password. Suitable for
|
|
43
|
+
* storing in the consolidated archive.
|
|
39
44
|
*/
|
|
40
45
|
export interface SerializedUserRecord {
|
|
46
|
+
userName: string;
|
|
47
|
+
/** PHC / modular-crypt credential string (scheme self-described by its prefix). */
|
|
48
|
+
credential: string;
|
|
49
|
+
userConfiguration: UserConfigurationMask;
|
|
50
|
+
description: string;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* Legacy (archive v1) persisted record — raw scrypt `salt`+`hash` (base64).
|
|
55
|
+
* Accepted by {@link IUserManagementStore.importUsers} and read-migrated to a
|
|
56
|
+
* `$scrypt$…` {@link SerializedUserRecord} credential, so old archives keep
|
|
57
|
+
* working with **no forced password resets**.
|
|
58
|
+
*/
|
|
59
|
+
export interface LegacySerializedUserRecord {
|
|
41
60
|
userName: string;
|
|
42
61
|
salt: string; // base64
|
|
43
62
|
hash: string; // base64
|
|
@@ -63,29 +82,85 @@ export interface ModifyUserOptions {
|
|
|
63
82
|
}
|
|
64
83
|
|
|
65
84
|
export interface IUserManagementStore {
|
|
66
|
-
addUser(userName: string, password: string, userConfiguration: UserConfigurationMask, description: string): StatusCode
|
|
67
|
-
modifyUser(userName: string, options: ModifyUserOptions, callerUserName?: string): StatusCode
|
|
85
|
+
addUser(userName: string, password: string, userConfiguration: UserConfigurationMask, description: string): Promise<StatusCode>;
|
|
86
|
+
modifyUser(userName: string, options: ModifyUserOptions, callerUserName?: string): Promise<StatusCode>;
|
|
68
87
|
removeUser(userName: string, callerUserName?: string): StatusCode;
|
|
69
|
-
changePassword(userName: string, oldPassword: string, newPassword: string): StatusCode
|
|
70
|
-
authenticate(userName: string, password: string): AuthenticationResult
|
|
88
|
+
changePassword(userName: string, oldPassword: string, newPassword: string): Promise<StatusCode>;
|
|
89
|
+
authenticate(userName: string, password: string): Promise<AuthenticationResult>;
|
|
71
90
|
getUsers(): UserRecord[];
|
|
72
91
|
hasUser(userName: string): boolean;
|
|
73
|
-
/** Export every user (with
|
|
92
|
+
/** Export every user (with its PHC credential) for persistence. Optional: only stores that support persistence. */
|
|
74
93
|
exportUsers?(): SerializedUserRecord[];
|
|
75
|
-
/** Load persisted users (
|
|
76
|
-
importUsers?(records: SerializedUserRecord[]): void;
|
|
94
|
+
/** Load persisted users (v2 credential or legacy v1 salt+hash), replacing any existing entry of the same name. */
|
|
95
|
+
importUsers?(records: readonly (SerializedUserRecord | LegacySerializedUserRecord)[]): void;
|
|
96
|
+
/**
|
|
97
|
+
* Optional: register a callback fired when a credential is transparently
|
|
98
|
+
* re-hashed during {@link authenticate} (upgrade-on-login), so a persistence
|
|
99
|
+
* layer can flush the new hash.
|
|
100
|
+
*/
|
|
101
|
+
setOnCredentialUpgraded?(fn: (userName: string) => void): void;
|
|
77
102
|
}
|
|
78
103
|
|
|
79
104
|
interface InternalUser {
|
|
80
105
|
userName: string;
|
|
81
|
-
|
|
82
|
-
|
|
106
|
+
/** PHC credential string. */
|
|
107
|
+
credential: string;
|
|
83
108
|
userConfiguration: UserConfigurationMask;
|
|
84
109
|
description: string;
|
|
85
110
|
}
|
|
86
111
|
|
|
87
112
|
const has = (mask: UserConfigurationMask, bit: UserConfigurationMask): boolean => (mask & bit) === bit;
|
|
88
113
|
|
|
114
|
+
/** A record is legacy (v1) when it carries raw `salt`+`hash` instead of a `credential`. */
|
|
115
|
+
function isLegacyRecord(r: SerializedUserRecord | LegacySerializedUserRecord): r is LegacySerializedUserRecord {
|
|
116
|
+
return typeof (r as SerializedUserRecord).credential !== "string";
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/** Shared default scrypt hasher used by the offline {@link serializeUser} helper. */
|
|
120
|
+
const offlineScrypt = new ScryptHasher();
|
|
121
|
+
|
|
122
|
+
/**
|
|
123
|
+
* Produce a {@link SerializedUserRecord} (scrypt PHC credential) from a
|
|
124
|
+
* clear-text password — **offline**, without a store.
|
|
125
|
+
*
|
|
126
|
+
* Use this to keep clear-text passwords out of version control / config: run it
|
|
127
|
+
* once at deploy time and commit only the returned record, then seed it through
|
|
128
|
+
* `importUsers` (or `createRoleBasedSecurity`'s `passwordHash`). The record is
|
|
129
|
+
* interchangeable with what {@link InMemoryUserManagementStore.exportUsers}
|
|
130
|
+
* produces, so `authenticate` accepts the original clear-text password.
|
|
131
|
+
*/
|
|
132
|
+
export async function serializeUser(
|
|
133
|
+
userName: string,
|
|
134
|
+
password: string,
|
|
135
|
+
options?: { userConfiguration?: UserConfigurationMask; description?: string }
|
|
136
|
+
): Promise<SerializedUserRecord> {
|
|
137
|
+
return {
|
|
138
|
+
userName,
|
|
139
|
+
credential: await offlineScrypt.hash(password),
|
|
140
|
+
userConfiguration: options?.userConfiguration ?? UserConfigurationMask.None,
|
|
141
|
+
description: options?.description ?? ""
|
|
142
|
+
};
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/**
|
|
146
|
+
* Wrap an **already-hashed** PHC credential string (e.g. a legacy `$2b$…`
|
|
147
|
+
* bcrypt hash) into a {@link SerializedUserRecord} — no clear text, no
|
|
148
|
+
* re-hashing. The credential is verified by whichever registered scheme owns
|
|
149
|
+
* its prefix, and (for non-default schemes) upgraded on next login.
|
|
150
|
+
*/
|
|
151
|
+
export function credentialRecord(
|
|
152
|
+
userName: string,
|
|
153
|
+
credential: string,
|
|
154
|
+
options?: { userConfiguration?: UserConfigurationMask; description?: string }
|
|
155
|
+
): SerializedUserRecord {
|
|
156
|
+
return {
|
|
157
|
+
userName,
|
|
158
|
+
credential,
|
|
159
|
+
userConfiguration: options?.userConfiguration ?? UserConfigurationMask.None,
|
|
160
|
+
description: options?.description ?? ""
|
|
161
|
+
};
|
|
162
|
+
}
|
|
163
|
+
|
|
89
164
|
/**
|
|
90
165
|
* In-memory implementation of {@link IUserManagementStore}.
|
|
91
166
|
*
|
|
@@ -94,15 +169,22 @@ const has = (mask: UserConfigurationMask, bit: UserConfigurationMask): boolean =
|
|
|
94
169
|
export class InMemoryUserManagementStore implements IUserManagementStore {
|
|
95
170
|
private readonly _users = new Map<string, InternalUser>();
|
|
96
171
|
private readonly _policy: PasswordPolicy;
|
|
172
|
+
private readonly _registry: HasherRegistry;
|
|
173
|
+
private _onCredentialUpgraded?: (userName: string) => void;
|
|
97
174
|
|
|
98
|
-
constructor(policy?: PasswordPolicy) {
|
|
175
|
+
constructor(policy?: PasswordPolicy, options?: { registry?: HasherRegistry }) {
|
|
99
176
|
this._policy = policy ?? {};
|
|
177
|
+
this._registry = options?.registry ?? defaultHasherRegistry();
|
|
100
178
|
}
|
|
101
179
|
|
|
102
180
|
public get policy(): PasswordPolicy {
|
|
103
181
|
return this._policy;
|
|
104
182
|
}
|
|
105
183
|
|
|
184
|
+
public setOnCredentialUpgraded(fn: (userName: string) => void): void {
|
|
185
|
+
this._onCredentialUpgraded = fn;
|
|
186
|
+
}
|
|
187
|
+
|
|
106
188
|
public hasUser(userName: string): boolean {
|
|
107
189
|
return this._users.has(userName);
|
|
108
190
|
}
|
|
@@ -118,26 +200,32 @@ export class InMemoryUserManagementStore implements IUserManagementStore {
|
|
|
118
200
|
public exportUsers(): SerializedUserRecord[] {
|
|
119
201
|
return [...this._users.values()].map((u) => ({
|
|
120
202
|
userName: u.userName,
|
|
121
|
-
|
|
122
|
-
hash: u.hash.toString("base64"),
|
|
203
|
+
credential: u.credential,
|
|
123
204
|
userConfiguration: u.userConfiguration,
|
|
124
205
|
description: u.description
|
|
125
206
|
}));
|
|
126
207
|
}
|
|
127
208
|
|
|
128
|
-
public importUsers(records: SerializedUserRecord[]): void {
|
|
209
|
+
public importUsers(records: readonly (SerializedUserRecord | LegacySerializedUserRecord)[]): void {
|
|
129
210
|
for (const r of records) {
|
|
211
|
+
// v1 archives stored raw scrypt salt+hash — migrate to a $scrypt$ PHC
|
|
212
|
+
// credential on read (lossless: same algorithm and parameters).
|
|
213
|
+
const credential = isLegacyRecord(r) ? scryptPhc(r.salt, r.hash) : r.credential;
|
|
130
214
|
this._users.set(r.userName, {
|
|
131
215
|
userName: r.userName,
|
|
132
|
-
|
|
133
|
-
hash: Buffer.from(r.hash, "base64"),
|
|
216
|
+
credential,
|
|
134
217
|
userConfiguration: r.userConfiguration,
|
|
135
218
|
description: r.description
|
|
136
219
|
});
|
|
137
220
|
}
|
|
138
221
|
}
|
|
139
222
|
|
|
140
|
-
public addUser(
|
|
223
|
+
public async addUser(
|
|
224
|
+
userName: string,
|
|
225
|
+
password: string,
|
|
226
|
+
userConfiguration: UserConfigurationMask,
|
|
227
|
+
description: string
|
|
228
|
+
): Promise<StatusCode> {
|
|
141
229
|
if (this._users.has(userName)) {
|
|
142
230
|
return StatusCodes.BadAlreadyExists;
|
|
143
231
|
}
|
|
@@ -148,11 +236,12 @@ export class InMemoryUserManagementStore implements IUserManagementStore {
|
|
|
148
236
|
if (!this.isPasswordValid(password)) {
|
|
149
237
|
return StatusCodes.BadOutOfRange;
|
|
150
238
|
}
|
|
151
|
-
|
|
239
|
+
const credential = await this._registry.hash(password);
|
|
240
|
+
this._users.set(userName, { userName, credential, userConfiguration, description });
|
|
152
241
|
return StatusCodes.Good;
|
|
153
242
|
}
|
|
154
243
|
|
|
155
|
-
public modifyUser(userName: string, options: ModifyUserOptions, callerUserName?: string): StatusCode {
|
|
244
|
+
public async modifyUser(userName: string, options: ModifyUserOptions, callerUserName?: string): Promise<StatusCode> {
|
|
156
245
|
const user = this._users.get(userName);
|
|
157
246
|
if (!user) {
|
|
158
247
|
return StatusCodes.BadNotFound;
|
|
@@ -181,9 +270,7 @@ export class InMemoryUserManagementStore implements IUserManagementStore {
|
|
|
181
270
|
|
|
182
271
|
// All checks passed — apply the changes
|
|
183
272
|
if (options.modifyPassword) {
|
|
184
|
-
|
|
185
|
-
user.salt = salt;
|
|
186
|
-
user.hash = hash;
|
|
273
|
+
user.credential = await this._registry.hash(options.password ?? "");
|
|
187
274
|
}
|
|
188
275
|
if (options.modifyUserConfiguration) {
|
|
189
276
|
user.userConfiguration = nextConfig;
|
|
@@ -209,7 +296,7 @@ export class InMemoryUserManagementStore implements IUserManagementStore {
|
|
|
209
296
|
return StatusCodes.Good;
|
|
210
297
|
}
|
|
211
298
|
|
|
212
|
-
public changePassword(userName: string, oldPassword: string, newPassword: string): StatusCode {
|
|
299
|
+
public async changePassword(userName: string, oldPassword: string, newPassword: string): Promise<StatusCode> {
|
|
213
300
|
const user = this._users.get(userName);
|
|
214
301
|
// Unknown user is treated as an invalid old password (§5.2.8)
|
|
215
302
|
if (!user) {
|
|
@@ -218,7 +305,7 @@ export class InMemoryUserManagementStore implements IUserManagementStore {
|
|
|
218
305
|
if (has(user.userConfiguration, UserConfigurationMask.NoChangeByUser)) {
|
|
219
306
|
return StatusCodes.BadNotSupported;
|
|
220
307
|
}
|
|
221
|
-
if (!this.verify(
|
|
308
|
+
if (!(await this._registry.verify(oldPassword, user.credential))) {
|
|
222
309
|
return StatusCodes.BadIdentityTokenInvalid;
|
|
223
310
|
}
|
|
224
311
|
if (oldPassword === newPassword) {
|
|
@@ -227,23 +314,27 @@ export class InMemoryUserManagementStore implements IUserManagementStore {
|
|
|
227
314
|
if (!this.isPasswordValid(newPassword)) {
|
|
228
315
|
return StatusCodes.BadOutOfRange;
|
|
229
316
|
}
|
|
230
|
-
|
|
231
|
-
user.salt = salt;
|
|
232
|
-
user.hash = hash;
|
|
317
|
+
user.credential = await this._registry.hash(newPassword);
|
|
233
318
|
// A successful change clears the MustChangePassword flag (§5.2.8)
|
|
234
319
|
user.userConfiguration &= ~UserConfigurationMask.MustChangePassword;
|
|
235
320
|
return StatusCodes.Good;
|
|
236
321
|
}
|
|
237
322
|
|
|
238
|
-
public authenticate(userName: string, password: string): AuthenticationResult {
|
|
323
|
+
public async authenticate(userName: string, password: string): Promise<AuthenticationResult> {
|
|
239
324
|
const user = this._users.get(userName);
|
|
240
325
|
// A disabled user behaves like a user that does not exist (§5.2.3)
|
|
241
326
|
if (!user || has(user.userConfiguration, UserConfigurationMask.Disabled)) {
|
|
242
327
|
return { statusCode: StatusCodes.BadUserAccessDenied, mustChangePassword: false };
|
|
243
328
|
}
|
|
244
|
-
if (!this.verify(
|
|
329
|
+
if (!(await this._registry.verify(password, user.credential))) {
|
|
245
330
|
return { statusCode: StatusCodes.BadUserAccessDenied, mustChangePassword: false };
|
|
246
331
|
}
|
|
332
|
+
// Upgrade-on-login: transparently re-hash a legacy/drifted credential with
|
|
333
|
+
// the default scheme (e.g. bcrypt → scrypt) now that we hold the clear text.
|
|
334
|
+
if (this._registry.needsRehash(user.credential)) {
|
|
335
|
+
user.credential = await this._registry.hash(password);
|
|
336
|
+
this._onCredentialUpgraded?.(userName);
|
|
337
|
+
}
|
|
247
338
|
if (has(user.userConfiguration, UserConfigurationMask.MustChangePassword)) {
|
|
248
339
|
return { statusCode: StatusCodes.GoodPasswordChangeRequired, mustChangePassword: true };
|
|
249
340
|
}
|
|
@@ -261,17 +352,6 @@ export class InMemoryUserManagementStore implements IUserManagementStore {
|
|
|
261
352
|
if (p.requireSpecial && !/[^A-Za-z0-9]/.test(password)) return false;
|
|
262
353
|
return true;
|
|
263
354
|
}
|
|
264
|
-
|
|
265
|
-
private hashPassword(password: string): { salt: Buffer; hash: Buffer } {
|
|
266
|
-
const salt = randomBytes(16);
|
|
267
|
-
const hash = scryptSync(password, salt, 64);
|
|
268
|
-
return { salt, hash };
|
|
269
|
-
}
|
|
270
|
-
|
|
271
|
-
private verify(user: InternalUser, password: string): boolean {
|
|
272
|
-
const candidate = scryptSync(password, user.salt, 64);
|
|
273
|
-
return candidate.length === user.hash.length && timingSafeEqual(candidate, user.hash);
|
|
274
|
-
}
|
|
275
355
|
}
|
|
276
356
|
|
|
277
357
|
/**
|
|
@@ -280,7 +360,7 @@ export class InMemoryUserManagementStore implements IUserManagementStore {
|
|
|
280
360
|
*
|
|
281
361
|
* @returns a `Bad_ConfigurationError` StatusCode, or `null` if valid.
|
|
282
362
|
*/
|
|
283
|
-
function validateUserConfiguration(mask: UserConfigurationMask): StatusCode | null {
|
|
363
|
+
export function validateUserConfiguration(mask: UserConfigurationMask): StatusCode | null {
|
|
284
364
|
if (has(mask, UserConfigurationMask.MustChangePassword) && has(mask, UserConfigurationMask.NoChangeByUser)) {
|
|
285
365
|
return StatusCodes.BadConfigurationError;
|
|
286
366
|
}
|