node-opcua-role-set-common 2.174.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/LICENSE +22 -0
  2. package/README.md +142 -0
  3. package/dist/archive.d.ts +71 -0
  4. package/dist/archive.js +189 -0
  5. package/dist/archive.js.map +1 -0
  6. package/dist/binary_persistence.d.ts +31 -0
  7. package/dist/binary_persistence.js +119 -0
  8. package/dist/binary_persistence.js.map +1 -0
  9. package/dist/identity_mapping_store.d.ts +36 -0
  10. package/dist/identity_mapping_store.js +3 -0
  11. package/dist/identity_mapping_store.js.map +1 -0
  12. package/dist/in_memory_store.d.ts +20 -0
  13. package/dist/in_memory_store.js +129 -0
  14. package/dist/in_memory_store.js.map +1 -0
  15. package/dist/index.d.ts +11 -0
  16. package/dist/index.js +41 -0
  17. package/dist/index.js.map +1 -0
  18. package/dist/role_restriction_store.d.ts +93 -0
  19. package/dist/role_restriction_store.js +205 -0
  20. package/dist/role_restriction_store.js.map +1 -0
  21. package/dist/user_management_store.d.ts +83 -0
  22. package/dist/user_management_store.js +208 -0
  23. package/dist/user_management_store.js.map +1 -0
  24. package/dist/well_known_role_ids.d.ts +36 -0
  25. package/dist/well_known_role_ids.js +44 -0
  26. package/dist/well_known_role_ids.js.map +1 -0
  27. package/dist/x509_subject.d.ts +44 -0
  28. package/dist/x509_subject.js +78 -0
  29. package/dist/x509_subject.js.map +1 -0
  30. package/package.json +51 -0
  31. package/source/archive.ts +231 -0
  32. package/source/binary_persistence.ts +119 -0
  33. package/source/identity_mapping_store.ts +42 -0
  34. package/source/in_memory_store.ts +150 -0
  35. package/source/index.ts +55 -0
  36. package/source/role_restriction_store.ts +270 -0
  37. package/source/user_management_store.ts +288 -0
  38. package/source/well_known_role_ids.ts +42 -0
  39. package/source/x509_subject.ts +84 -0
@@ -0,0 +1,270 @@
1
+ /**
2
+ * @module node-opcua-role-set-common
3
+ *
4
+ * Per-Role application & endpoint restrictions (OPC 10000-18 §4.4.1, §4.4.7-10)
5
+ * and the matching rules that decide whether a Session complies with them.
6
+ *
7
+ * A Role is granted only if the UserIdentityToken matches **and** the Client
8
+ * application complies with the `Applications` restriction **and** the Endpoint
9
+ * used complies with the `Endpoints` restriction.
10
+ */
11
+ import { promises as fs } from "node:fs";
12
+ import { dirname } from "node:path";
13
+ import { type NodeId, resolveNodeId } from "node-opcua-nodeid";
14
+ import { MessageSecurityMode } from "node-opcua-types";
15
+
16
+ /** An endpoint restriction entry (mirrors the EndpointType DataType, §4.4.2). */
17
+ export interface EndpointCriteria {
18
+ endpointUrl?: string;
19
+ securityMode?: MessageSecurityMode;
20
+ securityPolicyUri?: string;
21
+ transportProfileUri?: string;
22
+ }
23
+
24
+ /**
25
+ * The Session attributes evaluated against a Role's application/endpoint
26
+ * restrictions. Built from the SessionContext (client certificate ApplicationUri,
27
+ * SecureChannel security mode/policy, the Endpoint used).
28
+ */
29
+ export interface ResolutionContext {
30
+ applicationUri?: string | null;
31
+ securityMode?: MessageSecurityMode;
32
+ endpointUrl?: string;
33
+ securityPolicyUri?: string;
34
+ transportProfileUri?: string;
35
+ }
36
+
37
+ /** Per-Role application & endpoint restriction configuration. */
38
+ export interface IRoleRestrictionStore {
39
+ /** Add an ApplicationUri to a Role's Applications list. @returns false if already present. */
40
+ addApplication(roleId: NodeId, applicationUri: string): boolean;
41
+ /** Remove an ApplicationUri. @returns false if not present. */
42
+ removeApplication(roleId: NodeId, applicationUri: string): boolean;
43
+ getApplications(roleId: NodeId): string[];
44
+ /** Set ApplicationsExclude (include-list when false, exclude-list when true). */
45
+ setApplicationsExclude(roleId: NodeId, exclude: boolean): void;
46
+ /** ApplicationsExclude — defaults to TRUE when the Applications list is empty (§4.4.1). */
47
+ getApplicationsExclude(roleId: NodeId): boolean;
48
+
49
+ addEndpoint(roleId: NodeId, endpoint: EndpointCriteria): boolean;
50
+ removeEndpoint(roleId: NodeId, endpoint: EndpointCriteria): boolean;
51
+ getEndpoints(roleId: NodeId): EndpointCriteria[];
52
+ setEndpointsExclude(roleId: NodeId, exclude: boolean): void;
53
+ getEndpointsExclude(roleId: NodeId): boolean;
54
+
55
+ /** NodeIds of the Roles that have any restriction configured. */
56
+ getRestrictedRoleIds(): NodeId[];
57
+
58
+ /** True when the Session complies with the Role's application & endpoint restrictions. */
59
+ complies(roleId: NodeId, context: ResolutionContext): boolean;
60
+ }
61
+
62
+ const isSigned = (mode: MessageSecurityMode | undefined): boolean =>
63
+ mode === MessageSecurityMode.Sign || mode === MessageSecurityMode.SignAndEncrypt;
64
+
65
+ function sameEndpoint(a: EndpointCriteria, b: EndpointCriteria): boolean {
66
+ return (
67
+ (a.endpointUrl ?? "") === (b.endpointUrl ?? "") &&
68
+ (a.securityMode ?? MessageSecurityMode.Invalid) === (b.securityMode ?? MessageSecurityMode.Invalid) &&
69
+ (a.securityPolicyUri ?? "") === (b.securityPolicyUri ?? "") &&
70
+ (a.transportProfileUri ?? "") === (b.transportProfileUri ?? "")
71
+ );
72
+ }
73
+
74
+ /**
75
+ * Does the Session's application comply with an `Applications` restriction?
76
+ *
77
+ * - Empty list → no restriction (granted).
78
+ * - Non-empty list → the Session must use at least a **signed** channel (§4.4.1).
79
+ * Then, with `exclude=false` the ApplicationUri must be **in** the list;
80
+ * with `exclude=true` it must **not** be in the list.
81
+ */
82
+ export function applicationComplies(applications: string[], exclude: boolean, context: ResolutionContext): boolean {
83
+ if (applications.length === 0) {
84
+ return true;
85
+ }
86
+ if (!isSigned(context.securityMode)) {
87
+ return false;
88
+ }
89
+ const inList = context.applicationUri != null && applications.includes(context.applicationUri);
90
+ return exclude ? !inList : inList;
91
+ }
92
+
93
+ /** Does an endpoint entry match the Session's endpoint? Default-valued fields are ignored (§4.4.2). */
94
+ function endpointEntryMatches(entry: EndpointCriteria, context: ResolutionContext): boolean {
95
+ if (entry.endpointUrl && entry.endpointUrl !== context.endpointUrl) return false;
96
+ if (
97
+ entry.securityMode !== undefined &&
98
+ entry.securityMode !== MessageSecurityMode.Invalid &&
99
+ entry.securityMode !== context.securityMode
100
+ ) {
101
+ return false;
102
+ }
103
+ if (entry.securityPolicyUri && entry.securityPolicyUri !== context.securityPolicyUri) return false;
104
+ if (entry.transportProfileUri && entry.transportProfileUri !== context.transportProfileUri) return false;
105
+ return true;
106
+ }
107
+
108
+ /**
109
+ * Does the Session's endpoint comply with an `Endpoints` restriction?
110
+ * Empty list → no restriction. `exclude=false` → the endpoint must match one
111
+ * entry; `exclude=true` → it must match none.
112
+ */
113
+ export function endpointComplies(endpoints: EndpointCriteria[], exclude: boolean, context: ResolutionContext): boolean {
114
+ if (endpoints.length === 0) {
115
+ return true;
116
+ }
117
+ const anyMatch = endpoints.some((e) => endpointEntryMatches(e, context));
118
+ return exclude ? !anyMatch : anyMatch;
119
+ }
120
+
121
+ interface RoleRestriction {
122
+ applications: string[];
123
+ applicationsExclude?: boolean;
124
+ endpoints: EndpointCriteria[];
125
+ endpointsExclude?: boolean;
126
+ }
127
+
128
+ /** In-memory implementation of {@link IRoleRestrictionStore}. */
129
+ export class InMemoryRoleRestrictionStore implements IRoleRestrictionStore {
130
+ private readonly _map = new Map<string, RoleRestriction>();
131
+
132
+ /** Get-or-create the entry — for mutations only. */
133
+ private getOrCreate(roleId: NodeId): RoleRestriction {
134
+ const key = roleId.toString();
135
+ let r = this._map.get(key);
136
+ if (!r) {
137
+ r = { applications: [], endpoints: [] };
138
+ this._map.set(key, r);
139
+ }
140
+ return r;
141
+ }
142
+
143
+ /** Read the entry without creating one. */
144
+ private peek(roleId: NodeId): RoleRestriction | undefined {
145
+ return this._map.get(roleId.toString());
146
+ }
147
+
148
+ public getRestrictedRoleIds(): NodeId[] {
149
+ return [...this._map.keys()].map((k) => resolveNodeId(k));
150
+ }
151
+
152
+ public addApplication(roleId: NodeId, applicationUri: string): boolean {
153
+ const r = this.getOrCreate(roleId);
154
+ if (r.applications.includes(applicationUri)) return false;
155
+ r.applications.push(applicationUri);
156
+ return true;
157
+ }
158
+ public removeApplication(roleId: NodeId, applicationUri: string): boolean {
159
+ const r = this.peek(roleId);
160
+ const i = r ? r.applications.indexOf(applicationUri) : -1;
161
+ if (!r || i < 0) return false;
162
+ r.applications.splice(i, 1);
163
+ return true;
164
+ }
165
+ public getApplications(roleId: NodeId): string[] {
166
+ return [...(this.peek(roleId)?.applications ?? [])];
167
+ }
168
+ public setApplicationsExclude(roleId: NodeId, exclude: boolean): void {
169
+ this.getOrCreate(roleId).applicationsExclude = exclude;
170
+ }
171
+ public getApplicationsExclude(roleId: NodeId): boolean {
172
+ const r = this.peek(roleId);
173
+ // default TRUE when the list is empty (§4.4.1), otherwise FALSE (include list)
174
+ return r?.applicationsExclude ?? (r?.applications.length ?? 0) === 0;
175
+ }
176
+
177
+ public addEndpoint(roleId: NodeId, endpoint: EndpointCriteria): boolean {
178
+ const r = this.getOrCreate(roleId);
179
+ if (r.endpoints.some((e) => sameEndpoint(e, endpoint))) return false;
180
+ r.endpoints.push({ ...endpoint });
181
+ return true;
182
+ }
183
+ public removeEndpoint(roleId: NodeId, endpoint: EndpointCriteria): boolean {
184
+ const r = this.peek(roleId);
185
+ const i = r ? r.endpoints.findIndex((e) => sameEndpoint(e, endpoint)) : -1;
186
+ if (!r || i < 0) return false;
187
+ r.endpoints.splice(i, 1);
188
+ return true;
189
+ }
190
+ public getEndpoints(roleId: NodeId): EndpointCriteria[] {
191
+ return (this.peek(roleId)?.endpoints ?? []).map((e) => ({ ...e }));
192
+ }
193
+ public setEndpointsExclude(roleId: NodeId, exclude: boolean): void {
194
+ this.getOrCreate(roleId).endpointsExclude = exclude;
195
+ }
196
+ public getEndpointsExclude(roleId: NodeId): boolean {
197
+ const r = this.peek(roleId);
198
+ return r?.endpointsExclude ?? (r?.endpoints.length ?? 0) === 0;
199
+ }
200
+
201
+ public complies(roleId: NodeId, context: ResolutionContext): boolean {
202
+ const r = this.peek(roleId);
203
+ if (!r) {
204
+ return true; // no restriction configured
205
+ }
206
+ return (
207
+ applicationComplies(r.applications, this.getApplicationsExclude(roleId), context) &&
208
+ endpointComplies(r.endpoints, this.getEndpointsExclude(roleId), context)
209
+ );
210
+ }
211
+ }
212
+
213
+ /** Serializable form of a Role's restrictions (for persistence). */
214
+ export interface SerializedRoleRestriction {
215
+ nodeId: string;
216
+ applications: string[];
217
+ applicationsExclude: boolean;
218
+ endpoints: EndpointCriteria[];
219
+ endpointsExclude: boolean;
220
+ }
221
+
222
+ /** Snapshot the restriction store to a JSON-serializable array. */
223
+ export function serializeRestrictions(store: IRoleRestrictionStore): SerializedRoleRestriction[] {
224
+ return store.getRestrictedRoleIds().map((roleId) => ({
225
+ nodeId: roleId.toString(),
226
+ applications: store.getApplications(roleId),
227
+ applicationsExclude: store.getApplicationsExclude(roleId),
228
+ endpoints: store.getEndpoints(roleId),
229
+ endpointsExclude: store.getEndpointsExclude(roleId)
230
+ }));
231
+ }
232
+
233
+ /** Load a serialized snapshot into the restriction store (merges). */
234
+ export function deserializeRestrictions(store: IRoleRestrictionStore, data: SerializedRoleRestriction[]): void {
235
+ for (const r of data) {
236
+ const roleId = resolveNodeId(r.nodeId);
237
+ for (const app of r.applications) {
238
+ store.addApplication(roleId, app);
239
+ }
240
+ store.setApplicationsExclude(roleId, r.applicationsExclude);
241
+ for (const ep of r.endpoints) {
242
+ store.addEndpoint(roleId, ep);
243
+ }
244
+ store.setEndpointsExclude(roleId, r.endpointsExclude);
245
+ }
246
+ }
247
+
248
+ /** Persist the restriction store to a JSON file. */
249
+ export async function saveRestrictionsToFile(store: IRoleRestrictionStore, filePath: string): Promise<void> {
250
+ await fs.mkdir(dirname(filePath), { recursive: true });
251
+ await fs.writeFile(filePath, JSON.stringify(serializeRestrictions(store), null, 2), "utf8");
252
+ }
253
+
254
+ /** Load the restriction store from a JSON file (missing file → no-op). */
255
+ export async function loadRestrictionsFromFile(store: IRoleRestrictionStore, filePath: string): Promise<void> {
256
+ let text: string;
257
+ try {
258
+ text = await fs.readFile(filePath, "utf8");
259
+ } catch (err) {
260
+ if ((err as NodeJS.ErrnoException).code === "ENOENT") {
261
+ return;
262
+ }
263
+ throw err;
264
+ }
265
+ try {
266
+ deserializeRestrictions(store, JSON.parse(text) as SerializedRoleRestriction[]);
267
+ } catch (err) {
268
+ throw new Error(`loadRestrictionsFromFile: '${filePath}' appears to be corrupt: ${(err as Error).message}`);
269
+ }
270
+ }
@@ -0,0 +1,288 @@
1
+ /**
2
+ * @module node-opcua-role-set-common
3
+ *
4
+ * User management store (OPC 10000-18 §5) — provides the local user list and
5
+ * password lifecycle used by the `UserName` identity criteria.
6
+ *
7
+ * The store implements the behaviour of the AddUser / ModifyUser / RemoveUser
8
+ * / ChangePassword Methods and the password policy (PasswordLength range and
9
+ * the password-option requirements). Passwords are never stored in clear:
10
+ * each is salted and hashed with scrypt.
11
+ */
12
+ import { randomBytes, scryptSync, timingSafeEqual } from "node:crypto";
13
+ import { type StatusCode, StatusCodes } from "node-opcua-status-code";
14
+ import { UserConfigurationMask } from "node-opcua-types";
15
+
16
+ /**
17
+ * Password requirements (OPC 10000-18 §5.2.1-2: PasswordLength range and
18
+ * PasswordOptionsMask). A length of 0 means "no limit".
19
+ */
20
+ export interface PasswordPolicy {
21
+ minLength?: number;
22
+ maxLength?: number;
23
+ requireUpperCase?: boolean;
24
+ requireLowerCase?: boolean;
25
+ requireDigit?: boolean;
26
+ requireSpecial?: boolean;
27
+ }
28
+
29
+ /** Public view of a configured user (no secret material). */
30
+ export interface UserRecord {
31
+ userName: string;
32
+ userConfiguration: UserConfigurationMask;
33
+ description: string;
34
+ }
35
+
36
+ /**
37
+ * Persisted user record — includes the salted scrypt hash (base64), never the
38
+ * clear password. Suitable for storing in the consolidated archive.
39
+ */
40
+ export interface SerializedUserRecord {
41
+ userName: string;
42
+ salt: string; // base64
43
+ hash: string; // base64
44
+ userConfiguration: UserConfigurationMask;
45
+ description: string;
46
+ }
47
+
48
+ /** Result of authenticating a user at ActivateSession time. */
49
+ export interface AuthenticationResult {
50
+ /** `Good`, `GoodPasswordChangeRequired`, or a `Bad_` code on failure. */
51
+ statusCode: StatusCode;
52
+ /** True when the user must change the password before gaining roles. */
53
+ mustChangePassword: boolean;
54
+ }
55
+
56
+ export interface ModifyUserOptions {
57
+ modifyPassword?: boolean;
58
+ password?: string;
59
+ modifyUserConfiguration?: boolean;
60
+ userConfiguration?: UserConfigurationMask;
61
+ modifyDescription?: boolean;
62
+ description?: string;
63
+ }
64
+
65
+ export interface IUserManagementStore {
66
+ addUser(userName: string, password: string, userConfiguration: UserConfigurationMask, description: string): StatusCode;
67
+ modifyUser(userName: string, options: ModifyUserOptions, callerUserName?: string): StatusCode;
68
+ removeUser(userName: string, callerUserName?: string): StatusCode;
69
+ changePassword(userName: string, oldPassword: string, newPassword: string): StatusCode;
70
+ authenticate(userName: string, password: string): AuthenticationResult;
71
+ getUsers(): UserRecord[];
72
+ hasUser(userName: string): boolean;
73
+ /** Export every user (with salted hash) for persistence. Optional: only stores that support persistence. */
74
+ exportUsers?(): SerializedUserRecord[];
75
+ /** Load persisted users (with salted hash), replacing any existing entry of the same name. */
76
+ importUsers?(records: SerializedUserRecord[]): void;
77
+ }
78
+
79
+ interface InternalUser {
80
+ userName: string;
81
+ salt: Buffer;
82
+ hash: Buffer;
83
+ userConfiguration: UserConfigurationMask;
84
+ description: string;
85
+ }
86
+
87
+ const has = (mask: UserConfigurationMask, bit: UserConfigurationMask): boolean => (mask & bit) === bit;
88
+
89
+ /**
90
+ * In-memory implementation of {@link IUserManagementStore}.
91
+ *
92
+ * @see OPC 10000-18 §5.2
93
+ */
94
+ export class InMemoryUserManagementStore implements IUserManagementStore {
95
+ private readonly _users = new Map<string, InternalUser>();
96
+ private readonly _policy: PasswordPolicy;
97
+
98
+ constructor(policy?: PasswordPolicy) {
99
+ this._policy = policy ?? {};
100
+ }
101
+
102
+ public get policy(): PasswordPolicy {
103
+ return this._policy;
104
+ }
105
+
106
+ public hasUser(userName: string): boolean {
107
+ return this._users.has(userName);
108
+ }
109
+
110
+ public getUsers(): UserRecord[] {
111
+ return [...this._users.values()].map((u) => ({
112
+ userName: u.userName,
113
+ userConfiguration: u.userConfiguration,
114
+ description: u.description
115
+ }));
116
+ }
117
+
118
+ public exportUsers(): SerializedUserRecord[] {
119
+ return [...this._users.values()].map((u) => ({
120
+ userName: u.userName,
121
+ salt: u.salt.toString("base64"),
122
+ hash: u.hash.toString("base64"),
123
+ userConfiguration: u.userConfiguration,
124
+ description: u.description
125
+ }));
126
+ }
127
+
128
+ public importUsers(records: SerializedUserRecord[]): void {
129
+ for (const r of records) {
130
+ this._users.set(r.userName, {
131
+ userName: r.userName,
132
+ salt: Buffer.from(r.salt, "base64"),
133
+ hash: Buffer.from(r.hash, "base64"),
134
+ userConfiguration: r.userConfiguration,
135
+ description: r.description
136
+ });
137
+ }
138
+ }
139
+
140
+ public addUser(userName: string, password: string, userConfiguration: UserConfigurationMask, description: string): StatusCode {
141
+ if (this._users.has(userName)) {
142
+ return StatusCodes.BadAlreadyExists;
143
+ }
144
+ const configError = validateUserConfiguration(userConfiguration);
145
+ if (configError) {
146
+ return configError;
147
+ }
148
+ if (!this.isPasswordValid(password)) {
149
+ return StatusCodes.BadOutOfRange;
150
+ }
151
+ this._users.set(userName, { userName, ...this.hashPassword(password), userConfiguration, description });
152
+ return StatusCodes.Good;
153
+ }
154
+
155
+ public modifyUser(userName: string, options: ModifyUserOptions, callerUserName?: string): StatusCode {
156
+ const user = this._users.get(userName);
157
+ if (!user) {
158
+ return StatusCodes.BadNotFound;
159
+ }
160
+ if (options.modifyPassword) {
161
+ if (!this.isPasswordValid(options.password ?? "")) {
162
+ return StatusCodes.BadOutOfRange;
163
+ }
164
+ }
165
+ let nextConfig = user.userConfiguration;
166
+ if (options.modifyUserConfiguration) {
167
+ nextConfig = options.userConfiguration ?? UserConfigurationMask.None;
168
+ const configError = validateUserConfiguration(nextConfig);
169
+ if (configError) {
170
+ return configError;
171
+ }
172
+ // Cannot disable the user that calls the Method (§5.2.6)
173
+ if (
174
+ callerUserName === userName &&
175
+ has(nextConfig, UserConfigurationMask.Disabled) &&
176
+ !has(user.userConfiguration, UserConfigurationMask.Disabled)
177
+ ) {
178
+ return StatusCodes.BadInvalidSelfReference;
179
+ }
180
+ }
181
+
182
+ // All checks passed — apply the changes
183
+ if (options.modifyPassword) {
184
+ const { salt, hash } = this.hashPassword(options.password ?? "");
185
+ user.salt = salt;
186
+ user.hash = hash;
187
+ }
188
+ if (options.modifyUserConfiguration) {
189
+ user.userConfiguration = nextConfig;
190
+ }
191
+ if (options.modifyDescription) {
192
+ user.description = options.description ?? "";
193
+ }
194
+ return StatusCodes.Good;
195
+ }
196
+
197
+ public removeUser(userName: string, callerUserName?: string): StatusCode {
198
+ const user = this._users.get(userName);
199
+ if (!user) {
200
+ return StatusCodes.BadNotFound;
201
+ }
202
+ if (callerUserName === userName) {
203
+ return StatusCodes.BadInvalidSelfReference;
204
+ }
205
+ if (has(user.userConfiguration, UserConfigurationMask.NoDelete)) {
206
+ return StatusCodes.BadNotSupported;
207
+ }
208
+ this._users.delete(userName);
209
+ return StatusCodes.Good;
210
+ }
211
+
212
+ public changePassword(userName: string, oldPassword: string, newPassword: string): StatusCode {
213
+ const user = this._users.get(userName);
214
+ // Unknown user is treated as an invalid old password (§5.2.8)
215
+ if (!user) {
216
+ return StatusCodes.BadIdentityTokenInvalid;
217
+ }
218
+ if (has(user.userConfiguration, UserConfigurationMask.NoChangeByUser)) {
219
+ return StatusCodes.BadNotSupported;
220
+ }
221
+ if (!this.verify(user, oldPassword)) {
222
+ return StatusCodes.BadIdentityTokenInvalid;
223
+ }
224
+ if (oldPassword === newPassword) {
225
+ return StatusCodes.BadAlreadyExists;
226
+ }
227
+ if (!this.isPasswordValid(newPassword)) {
228
+ return StatusCodes.BadOutOfRange;
229
+ }
230
+ const { salt, hash } = this.hashPassword(newPassword);
231
+ user.salt = salt;
232
+ user.hash = hash;
233
+ // A successful change clears the MustChangePassword flag (§5.2.8)
234
+ user.userConfiguration &= ~UserConfigurationMask.MustChangePassword;
235
+ return StatusCodes.Good;
236
+ }
237
+
238
+ public authenticate(userName: string, password: string): AuthenticationResult {
239
+ const user = this._users.get(userName);
240
+ // A disabled user behaves like a user that does not exist (§5.2.3)
241
+ if (!user || has(user.userConfiguration, UserConfigurationMask.Disabled)) {
242
+ return { statusCode: StatusCodes.BadUserAccessDenied, mustChangePassword: false };
243
+ }
244
+ if (!this.verify(user, password)) {
245
+ return { statusCode: StatusCodes.BadUserAccessDenied, mustChangePassword: false };
246
+ }
247
+ if (has(user.userConfiguration, UserConfigurationMask.MustChangePassword)) {
248
+ return { statusCode: StatusCodes.GoodPasswordChangeRequired, mustChangePassword: true };
249
+ }
250
+ return { statusCode: StatusCodes.Good, mustChangePassword: false };
251
+ }
252
+
253
+ /** Validate a candidate password against the configured policy. */
254
+ public isPasswordValid(password: string): boolean {
255
+ const p = this._policy;
256
+ if (p.minLength && password.length < p.minLength) return false;
257
+ if (p.maxLength && password.length > p.maxLength) return false;
258
+ if (p.requireUpperCase && !/[A-Z]/.test(password)) return false;
259
+ if (p.requireLowerCase && !/[a-z]/.test(password)) return false;
260
+ if (p.requireDigit && !/[0-9]/.test(password)) return false;
261
+ if (p.requireSpecial && !/[^A-Za-z0-9]/.test(password)) return false;
262
+ return true;
263
+ }
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
+ }
276
+
277
+ /**
278
+ * Validate a UserConfigurationMask combination (OPC 10000-18 §5.2.3):
279
+ * MustChangePassword is invalid when NoChangeByUser is also set.
280
+ *
281
+ * @returns a `Bad_ConfigurationError` StatusCode, or `null` if valid.
282
+ */
283
+ function validateUserConfiguration(mask: UserConfigurationMask): StatusCode | null {
284
+ if (has(mask, UserConfigurationMask.MustChangePassword) && has(mask, UserConfigurationMask.NoChangeByUser)) {
285
+ return StatusCodes.BadConfigurationError;
286
+ }
287
+ return null;
288
+ }
@@ -0,0 +1,42 @@
1
+ /**
2
+ * @module node-opcua-role-set-common
3
+ *
4
+ * Pre-built NodeId objects for the OPC UA Well-Known Roles
5
+ * (OPC 10000-3 §4.8.2).
6
+ *
7
+ * These save callers from repeatedly calling `resolveNodeId(WellKnownRoles.X)`.
8
+ */
9
+
10
+ import { WellKnownRoles } from "node-opcua-constants";
11
+ import { makeNodeId } from "node-opcua-nodeid";
12
+
13
+ // Re-export so consumers only need to import from role-set-common
14
+ export { WellKnownRoles } from "node-opcua-constants";
15
+
16
+ /**
17
+ * Pre-built NodeId objects for OPC UA Well-Known Roles.
18
+ *
19
+ * Usage:
20
+ * ```ts
21
+ * import { WellKnownRoleIds } from "node-opcua-role-set-common";
22
+ * store.addIdentity(WellKnownRoleIds.SecurityAdmin, rule);
23
+ * ```
24
+ */
25
+ export const WellKnownRoleIds = {
26
+ /** Very limited access for anonymous Sessions. */
27
+ Anonymous: makeNodeId(WellKnownRoles.Anonymous),
28
+ /** Limited access for valid non-anonymous credentials. */
29
+ AuthenticatedUser: makeNodeId(WellKnownRoles.AuthenticatedUser),
30
+ /** Browse, read live/historical data, subscribe. */
31
+ Observer: makeNodeId(WellKnownRoles.Observer),
32
+ /** Observer + write some live data, call some Methods. */
33
+ Operator: makeNodeId(WellKnownRoles.Operator),
34
+ /** Browse, read/write config, read historical, call Methods, subscribe. */
35
+ Engineer: makeNodeId(WellKnownRoles.Engineer),
36
+ /** Browse, read live/historical data, call Methods, subscribe. */
37
+ Supervisor: makeNodeId(WellKnownRoles.Supervisor),
38
+ /** Change non-security related configuration. */
39
+ ConfigureAdmin: makeNodeId(WellKnownRoles.ConfigureAdmin),
40
+ /** Change security related settings. */
41
+ SecurityAdmin: makeNodeId(WellKnownRoles.SecurityAdmin)
42
+ } as const;
@@ -0,0 +1,84 @@
1
+ /**
2
+ * @module node-opcua-role-set-common
3
+ *
4
+ * Helpers for matching an `X509Subject` identity mapping rule against a
5
+ * certificate subject, following the ordered Distinguished Name format
6
+ * defined in OPC 10000-18 §4.4.3 (Table 10).
7
+ */
8
+
9
+ /**
10
+ * Subject attributes of a certificate, as exposed by
11
+ * `exploreCertificate(...).tbsCertificate.subject` (node-opcua-crypto).
12
+ */
13
+ export interface X509SubjectName {
14
+ commonName?: string;
15
+ organizationName?: string;
16
+ organizationUnitName?: string;
17
+ localityName?: string;
18
+ stateOrProvinceName?: string;
19
+ countryName?: string;
20
+ }
21
+
22
+ /**
23
+ * Order of the X509 subject name attributes (OPC 10000-18 §4.4.3, Table 10).
24
+ *
25
+ * Only the attributes that {@link X509SubjectName} exposes are mappable here
26
+ * (CN, O, OU, L, S, C). DC, dnQualifier and serialNumber are listed for
27
+ * completeness/ordering but are not extracted from certificates.
28
+ */
29
+ export const X509_SUBJECT_ORDER = ["CN", "O", "OU", "DC", "L", "S", "C", "dnQualifier", "serialNumber"];
30
+
31
+ /** Build the canonical `Name="Value"/...` string from ordered name/value pairs. */
32
+ export function canonicalizeX509Subject(pairs: Array<[string, string]>): string {
33
+ return pairs
34
+ .map((pair, index) => ({ pair, index }))
35
+ .filter(({ pair }) => X509_SUBJECT_ORDER.includes(pair[0]))
36
+ .sort((a, b) => {
37
+ const d = X509_SUBJECT_ORDER.indexOf(a.pair[0]) - X509_SUBJECT_ORDER.indexOf(b.pair[0]);
38
+ return d !== 0 ? d : a.index - b.index;
39
+ })
40
+ .map(({ pair }) => `${pair[0]}="${pair[1]}"`)
41
+ .join("/");
42
+ }
43
+
44
+ /** Parse a `CN="..."/O="..."` criteria String into ordered name/value pairs. */
45
+ export function parseX509SubjectCriteria(criteria: string): Array<[string, string]> {
46
+ const pairs: Array<[string, string]> = [];
47
+ const re = /([A-Za-z]+)\s*=\s*"((?:[^"])*)"/g;
48
+ for (const m of criteria.matchAll(re)) {
49
+ pairs.push([m[1], m[2]]);
50
+ }
51
+ return pairs;
52
+ }
53
+
54
+ /** Build ordered name/value pairs from a certificate subject. */
55
+ export function certificateSubjectPairs(subject: X509SubjectName): Array<[string, string]> {
56
+ const pairs: Array<[string, string]> = [];
57
+ if (subject.commonName) pairs.push(["CN", subject.commonName]);
58
+ if (subject.organizationName) pairs.push(["O", subject.organizationName]);
59
+ if (subject.organizationUnitName) pairs.push(["OU", subject.organizationUnitName]);
60
+ if (subject.localityName) pairs.push(["L", subject.localityName]);
61
+ if (subject.stateOrProvinceName) pairs.push(["S", subject.stateOrProvinceName]);
62
+ if (subject.countryName) pairs.push(["C", subject.countryName]);
63
+ return pairs;
64
+ }
65
+
66
+ /**
67
+ * Test whether an `X509Subject` criteria matches a certificate subject.
68
+ *
69
+ * Two criteria formats are accepted:
70
+ * - the full ordered DN format (e.g. `CN="Jane Doe"/O="ACME"`), in which case
71
+ * **every** mappable subject attribute present in the certificate must be
72
+ * present in the criteria and vice-versa;
73
+ * - a plain Common Name string (legacy/simplified), compared against the
74
+ * certificate's `commonName` only.
75
+ */
76
+ export function matchX509Subject(criteria: string, subject: X509SubjectName): boolean {
77
+ const trimmed = (criteria ?? "").trim();
78
+ if (/[A-Za-z]+\s*=\s*"/.test(trimmed)) {
79
+ return (
80
+ canonicalizeX509Subject(certificateSubjectPairs(subject)) === canonicalizeX509Subject(parseX509SubjectCriteria(trimmed))
81
+ );
82
+ }
83
+ return (subject.commonName ?? "") === trimmed;
84
+ }