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,231 @@
1
+ /**
2
+ * @module node-opcua-role-set-common
3
+ *
4
+ * Consolidated, single-file persistence archive for the whole RoleSet
5
+ * configuration (identity mappings, custom Role definitions, application/
6
+ * endpoint restrictions — and, in the future, the UserManagement store).
7
+ *
8
+ * The archive is JSON so most of it stays human-readable and diffable, while
9
+ * the identity mappings — which are OPC UA `ExtensionObject`s with a canonical
10
+ * binary encoding — are embedded as a base64 blob (reusing the proven binary
11
+ * encoder instead of re-inventing a lossy JSON form).
12
+ *
13
+ * Writes are **atomic** (temp file + rename) so a crash can never leave a
14
+ * half-written archive. When an operator-supplied `secret` is given the whole
15
+ * payload is encrypted at rest with AES-256-GCM (key derived via scrypt); the
16
+ * envelope is itself JSON with base64 fields. Without a secret the archive is
17
+ * plain JSON — relying on filesystem permissions / OS-level encryption, which
18
+ * is the appropriate baseline for config that already stores only salted,
19
+ * one-way password hashes.
20
+ */
21
+ import { createCipheriv, createDecipheriv, randomBytes, scryptSync } from "node:crypto";
22
+ import { promises as fs } from "node:fs";
23
+ import { dirname } from "node:path";
24
+ import { BinaryStream } from "node-opcua-binary-stream";
25
+ import { decodeIdentityStore, encodeIdentityStore, identityStoreBinaryStoreSize } from "./binary_persistence.js";
26
+ import type { IIdentityMappingStore } from "./identity_mapping_store.js";
27
+ import type { SerializedRoleRestriction } from "./role_restriction_store.js";
28
+ import type { SerializedUserRecord } from "./user_management_store.js";
29
+
30
+ export const ROLE_SET_ARCHIVE_VERSION = 1;
31
+
32
+ /** Persisted definition of a custom Role (so its GUID NodeId survives a restart). */
33
+ export interface PersistedCustomRole {
34
+ nodeId: string;
35
+ roleName: string;
36
+ namespaceUri?: string;
37
+ }
38
+
39
+ /** The whole RoleSet configuration, ready to be serialized to one file. */
40
+ export interface RoleSetArchive {
41
+ version: number;
42
+ /** base64 of the OPC UA binary identity-mapping store. */
43
+ identities?: string;
44
+ roles?: PersistedCustomRole[];
45
+ restrictions?: SerializedRoleRestriction[];
46
+ /** UserManagement users with salted scrypt hashes (never clear passwords). */
47
+ users?: SerializedUserRecord[];
48
+ }
49
+
50
+ /** Encode the identity store as a base64 string (reuses the binary encoder). */
51
+ export function identitiesToBase64(store: IIdentityMappingStore): string {
52
+ const size = identityStoreBinaryStoreSize(store);
53
+ const stream = new BinaryStream(Buffer.alloc(size));
54
+ encodeIdentityStore(store, stream);
55
+ return (stream.buffer as Buffer).subarray(0, stream.length).toString("base64");
56
+ }
57
+
58
+ /** Decode a base64 identity blob back into the store (merges; empty → no-op). */
59
+ export function identitiesFromBase64(store: IIdentityMappingStore, base64: string | undefined): void {
60
+ if (!base64) return;
61
+ const buffer = Buffer.from(base64, "base64");
62
+ if (buffer.length === 0) return;
63
+ decodeIdentityStore(store, new BinaryStream(buffer));
64
+ }
65
+
66
+ /** Encryption envelope written in place of the plain archive when a secret is set. */
67
+ interface EncryptedEnvelope {
68
+ version: number;
69
+ encrypted: true;
70
+ kdf: "scrypt";
71
+ salt: string; // base64
72
+ iv: string; // base64
73
+ tag: string; // base64 GCM auth tag
74
+ data: string; // base64 ciphertext of the JSON archive
75
+ }
76
+
77
+ function encrypt(plaintext: string, secret: string): EncryptedEnvelope {
78
+ const salt = randomBytes(16);
79
+ const iv = randomBytes(12);
80
+ const key = scryptSync(secret, salt, 32);
81
+ const cipher = createCipheriv("aes-256-gcm", key, iv);
82
+ const enc = Buffer.concat([cipher.update(plaintext, "utf8"), cipher.final()]);
83
+ return {
84
+ version: ROLE_SET_ARCHIVE_VERSION,
85
+ encrypted: true,
86
+ kdf: "scrypt",
87
+ salt: salt.toString("base64"),
88
+ iv: iv.toString("base64"),
89
+ tag: cipher.getAuthTag().toString("base64"),
90
+ data: enc.toString("base64")
91
+ };
92
+ }
93
+
94
+ function decrypt(env: EncryptedEnvelope, secret: string): string {
95
+ const key = scryptSync(secret, Buffer.from(env.salt, "base64"), 32);
96
+ const decipher = createDecipheriv("aes-256-gcm", key, Buffer.from(env.iv, "base64"));
97
+ decipher.setAuthTag(Buffer.from(env.tag, "base64"));
98
+ return Buffer.concat([decipher.update(Buffer.from(env.data, "base64")), decipher.final()]).toString("utf8");
99
+ }
100
+
101
+ export interface ArchiveIO {
102
+ /** When set, the archive is encrypted at rest (AES-256-GCM, key derived from this secret via scrypt). */
103
+ secret?: string;
104
+ }
105
+
106
+ /** Atomically write the archive (optionally encrypted) to `filePath`. */
107
+ export async function writeArchive(filePath: string, archive: RoleSetArchive, io?: ArchiveIO): Promise<void> {
108
+ const json = JSON.stringify(archive, null, 2);
109
+ const payload = io?.secret ? JSON.stringify(encrypt(json, io.secret), null, 2) : json;
110
+ await fs.mkdir(dirname(filePath), { recursive: true });
111
+ // write to a temp file then rename — rename is atomic and replaces the target
112
+ // (libuv sets MOVEFILE_REPLACE_EXISTING on Windows), so readers never see a
113
+ // partially written archive.
114
+ const tmp = `${filePath}.tmp`;
115
+ await fs.writeFile(tmp, payload, "utf8");
116
+ await fs.rename(tmp, filePath);
117
+ }
118
+
119
+ /** Read the archive (decrypting if needed). Missing/empty file → undefined. */
120
+ export async function readArchive(filePath: string, io?: ArchiveIO): Promise<RoleSetArchive | undefined> {
121
+ let text: string;
122
+ try {
123
+ text = await fs.readFile(filePath, "utf8");
124
+ } catch (err) {
125
+ if ((err as NodeJS.ErrnoException).code === "ENOENT") return undefined;
126
+ throw err;
127
+ }
128
+ if (!text.trim()) return undefined;
129
+
130
+ let parsed: RoleSetArchive | EncryptedEnvelope;
131
+ try {
132
+ parsed = JSON.parse(text);
133
+ } catch (err) {
134
+ throw new Error(`readArchive: '${filePath}' is not a valid archive (JSON parse failed): ${(err as Error).message}`);
135
+ }
136
+
137
+ if ((parsed as EncryptedEnvelope).encrypted) {
138
+ if (!io?.secret) {
139
+ throw new Error(`readArchive: '${filePath}' is encrypted but no secret was provided`);
140
+ }
141
+ try {
142
+ parsed = JSON.parse(decrypt(parsed as EncryptedEnvelope, io.secret)) as RoleSetArchive;
143
+ } catch (err) {
144
+ throw new Error(`readArchive: cannot decrypt '${filePath}' (wrong secret or corrupt): ${(err as Error).message}`);
145
+ }
146
+ }
147
+
148
+ const result = parsed as RoleSetArchive;
149
+ // Future-proofing: refuse an archive written by a newer, incompatible format
150
+ // rather than silently dropping the fields we don't understand. Older minor
151
+ // versions are forward-compatible (unknown fields are simply ignored).
152
+ if (typeof result.version !== "number") {
153
+ throw new Error(`readArchive: '${filePath}' has no version field — not a RoleSet archive`);
154
+ }
155
+ if (result.version > ROLE_SET_ARCHIVE_VERSION) {
156
+ throw new Error(
157
+ `readArchive: '${filePath}' was written by a newer archive format (version ${result.version} > ${ROLE_SET_ARCHIVE_VERSION}); upgrade node-opcua to read it`
158
+ );
159
+ }
160
+ return result;
161
+ }
162
+
163
+ /** A snapshot provider for one archive section (returns the current state, or undefined to omit). */
164
+ type SectionProvider<T> = () => T | undefined;
165
+
166
+ /**
167
+ * Coordinates a single consolidated archive shared by several stores.
168
+ *
169
+ * `installRoleSet` and `installUserManagement` each register the section(s) they
170
+ * own (identities/roles/restrictions vs. users) and call {@link save} after a
171
+ * mutation; the coordinator gathers **all** registered sections and rewrites the
172
+ * one file atomically — so neither installer clobbers the other's data. Pass the
173
+ * same `ArchiveStore` instance to both to keep everything in one file.
174
+ *
175
+ * A section with **no** registered provider is not dropped: its last loaded value
176
+ * is preserved on save. This makes the result independent of install order — even
177
+ * a mutation between the two installs cannot lose the not-yet-registered sections.
178
+ */
179
+ export class ArchiveStore {
180
+ private readonly _io: ArchiveIO;
181
+ private _identities?: SectionProvider<string>;
182
+ private _roles?: SectionProvider<PersistedCustomRole[]>;
183
+ private _restrictions?: SectionProvider<SerializedRoleRestriction[]>;
184
+ private _users?: SectionProvider<SerializedUserRecord[]>;
185
+ /** Last archive read from disk — used to preserve sections that have no provider yet. */
186
+ private _loaded?: RoleSetArchive;
187
+
188
+ constructor(
189
+ public readonly filePath: string,
190
+ io?: ArchiveIO
191
+ ) {
192
+ this._io = io ?? {};
193
+ }
194
+
195
+ public setIdentitiesProvider(fn: SectionProvider<string>): void {
196
+ this._identities = fn;
197
+ }
198
+ public setRolesProvider(fn: SectionProvider<PersistedCustomRole[]>): void {
199
+ this._roles = fn;
200
+ }
201
+ public setRestrictionsProvider(fn: SectionProvider<SerializedRoleRestriction[]>): void {
202
+ this._restrictions = fn;
203
+ }
204
+ public setUsersProvider(fn: SectionProvider<SerializedUserRecord[]>): void {
205
+ this._users = fn;
206
+ }
207
+
208
+ /** Read the persisted archive (missing file → undefined) and remember it for {@link save}. */
209
+ public async load(): Promise<RoleSetArchive | undefined> {
210
+ this._loaded = await readArchive(this.filePath, this._io);
211
+ return this._loaded;
212
+ }
213
+
214
+ /**
215
+ * Atomically rewrite the archive. A registered provider is authoritative for
216
+ * its section; a section with no provider falls back to the last loaded value
217
+ * so it is never clobbered (install-order independence).
218
+ */
219
+ public async save(): Promise<void> {
220
+ const archive: RoleSetArchive = {
221
+ version: ROLE_SET_ARCHIVE_VERSION,
222
+ identities: this._identities ? this._identities() : this._loaded?.identities,
223
+ roles: this._roles ? this._roles() : this._loaded?.roles,
224
+ restrictions: this._restrictions ? this._restrictions() : this._loaded?.restrictions,
225
+ users: this._users ? this._users() : this._loaded?.users
226
+ };
227
+ await writeArchive(this.filePath, archive, this._io);
228
+ // keep the fallback snapshot in sync with what is now on disk
229
+ this._loaded = archive;
230
+ }
231
+ }
@@ -0,0 +1,119 @@
1
+ /**
2
+ * @module node-opcua-role-set-common
3
+ *
4
+ * Binary persistence for identity-to-role mappings.
5
+ *
6
+ * File format (all OPC UA binary encoding):
7
+ * UInt32 — number of roles
8
+ * For each role:
9
+ * NodeId — role NodeId
10
+ * Variant(ExtensionObject[]) — identity mapping rules as Variant array
11
+ */
12
+ import { promises as fs } from "node:fs";
13
+ import { dirname } from "node:path";
14
+ import { decodeNodeId, decodeUInt32, encodeNodeId, encodeUInt32 } from "node-opcua-basic-types";
15
+ import { BinaryStream, BinaryStreamSizeCalculator } from "node-opcua-binary-stream";
16
+ import type { NodeId } from "node-opcua-nodeid";
17
+ import { IdentityMappingRuleType } from "node-opcua-types";
18
+ import { DataType, Variant, VariantArrayType } from "node-opcua-variant";
19
+
20
+ import type { IIdentityMappingStore } from "./identity_mapping_store.js";
21
+
22
+ /**
23
+ * Build a Variant wrapping an array of IdentityMappingRuleType for a role.
24
+ */
25
+ function makeRulesVariant(rules: IdentityMappingRuleType[]): Variant {
26
+ return new Variant({
27
+ dataType: DataType.ExtensionObject,
28
+ arrayType: VariantArrayType.Array,
29
+ value: rules
30
+ });
31
+ }
32
+
33
+ /**
34
+ * Calculate the exact binary size of the encoded store.
35
+ */
36
+ export function identityStoreBinaryStoreSize(store: IIdentityMappingStore): number {
37
+ const sizeCalculator = new BinaryStreamSizeCalculator();
38
+ encodeIdentityStore(store, sizeCalculator);
39
+ return sizeCalculator.length;
40
+ }
41
+
42
+ /**
43
+ * Encode the full store content into a binary stream.
44
+ */
45
+ export function encodeIdentityStore(store: IIdentityMappingStore, stream: BinaryStream | BinaryStreamSizeCalculator): void {
46
+ const roleIds = store.getRoleIds();
47
+ encodeUInt32(roleIds.length, stream);
48
+ for (const roleId of roleIds) {
49
+ encodeNodeId(roleId, stream);
50
+ const rules = store.getIdentitiesForRole(roleId);
51
+ const variant = makeRulesVariant(rules);
52
+ variant.encode(stream);
53
+ }
54
+ }
55
+
56
+ /**
57
+ * Decode the full store content from a binary stream.
58
+ * Existing store content is **not** cleared — decoded entries are merged.
59
+ */
60
+ export function decodeIdentityStore(store: IIdentityMappingStore, stream: BinaryStream): void {
61
+ const roleCount = decodeUInt32(stream);
62
+ for (let i = 0; i < roleCount; i++) {
63
+ const roleId: NodeId = decodeNodeId(stream);
64
+ const variant = new Variant();
65
+ variant.decode(stream);
66
+ if (variant.arrayType === VariantArrayType.Array && Array.isArray(variant.value)) {
67
+ for (const rule of variant.value) {
68
+ if (rule instanceof IdentityMappingRuleType) {
69
+ store.addIdentity(roleId, rule);
70
+ }
71
+ }
72
+ }
73
+ }
74
+ }
75
+
76
+ /**
77
+ * Save identity store to a binary file.
78
+ *
79
+ * Uses {@link BinaryStreamSizeCalculator} for exact buffer sizing.
80
+ * Creates the directory if it doesn't exist.
81
+ */
82
+ export async function saveToBinaryFile(store: IIdentityMappingStore, filePath: string): Promise<void> {
83
+ const size = identityStoreBinaryStoreSize(store);
84
+ const stream = new BinaryStream(Buffer.alloc(size));
85
+ encodeIdentityStore(store, stream);
86
+
87
+ const buffer = (stream.buffer as Buffer).subarray(0, stream.length);
88
+ await fs.mkdir(dirname(filePath), { recursive: true });
89
+ await fs.writeFile(filePath, buffer);
90
+ }
91
+
92
+ /**
93
+ * Load identity store from a binary file.
94
+ *
95
+ * If the file does not exist, the store is left unchanged (no error). A
96
+ * corrupt/truncated file is reported as a clear `Error` (naming the path)
97
+ * rather than a cryptic decoding failure, so the operator can react instead
98
+ * of the Server silently losing the role configuration.
99
+ */
100
+ export async function loadFromBinaryFile(store: IIdentityMappingStore, filePath: string): Promise<void> {
101
+ let buffer: Buffer;
102
+ try {
103
+ buffer = await fs.readFile(filePath);
104
+ } catch (err) {
105
+ if ((err as NodeJS.ErrnoException).code === "ENOENT") {
106
+ return; // missing file → no-op
107
+ }
108
+ throw err;
109
+ }
110
+ if (buffer.length === 0) {
111
+ return; // empty file → no-op
112
+ }
113
+ const stream = new BinaryStream(buffer);
114
+ try {
115
+ decodeIdentityStore(store, stream);
116
+ } catch (err) {
117
+ throw new Error(`loadFromBinaryFile: '${filePath}' appears to be corrupt or truncated: ${(err as Error).message}`);
118
+ }
119
+ }
@@ -0,0 +1,42 @@
1
+ /**
2
+ * @module node-opcua-role-set-common
3
+ */
4
+ import type { NodeId } from "node-opcua-nodeid";
5
+ import type { AnonymousIdentityToken, IdentityMappingRuleType, UserNameIdentityToken, X509IdentityToken } from "node-opcua-types";
6
+
7
+ /**
8
+ * Union of all user identity token types (OPC 10000-4).
9
+ * Mirrors the type from node-opcua-address-space but avoids
10
+ * pulling in the heavy address-space dependency.
11
+ */
12
+ export type AnyUserIdentityToken = AnonymousIdentityToken | UserNameIdentityToken | X509IdentityToken;
13
+
14
+ /**
15
+ * Store for identity-to-role mappings (OPC 10000-18 §4.4).
16
+ *
17
+ * Each mapping associates an {@link IdentityMappingRuleType} with a role NodeId.
18
+ * The store resolves which roles a given user identity token grants.
19
+ */
20
+ export interface IIdentityMappingStore {
21
+ /**
22
+ * Add an identity mapping rule for a role.
23
+ *
24
+ * @returns `true` if the rule was added, `false` if an equivalent rule
25
+ * already existed (the store is idempotent — duplicates are never stored).
26
+ * Callers binding the OPC UA `AddIdentity` Method use this to return
27
+ * `Bad_AlreadyExists` (OPC 10000-18 §4.4.5).
28
+ */
29
+ addIdentity(roleId: NodeId, rule: IdentityMappingRuleType): boolean;
30
+
31
+ /** Remove an identity mapping rule. Returns true if found and removed. */
32
+ removeIdentity(roleId: NodeId, rule: IdentityMappingRuleType): boolean;
33
+
34
+ /** Get all identity mapping rules for a given role. */
35
+ getIdentitiesForRole(roleId: NodeId): IdentityMappingRuleType[];
36
+
37
+ /** Get all role NodeIds that have at least one mapping. */
38
+ getRoleIds(): NodeId[];
39
+
40
+ /** Resolve which roles are granted by a user identity token. */
41
+ resolveRoles(token: AnyUserIdentityToken): NodeId[];
42
+ }
@@ -0,0 +1,150 @@
1
+ /**
2
+ * @module node-opcua-role-set-common
3
+ */
4
+
5
+ import { exploreCertificate, makeSHA1Thumbprint } from "node-opcua-crypto";
6
+ import { type NodeId, resolveNodeId, sameNodeId } from "node-opcua-nodeid";
7
+ import {
8
+ AnonymousIdentityToken,
9
+ IdentityCriteriaType,
10
+ IdentityMappingRuleType,
11
+ UserNameIdentityToken,
12
+ X509IdentityToken
13
+ } from "node-opcua-types";
14
+
15
+ import type { AnyUserIdentityToken, IIdentityMappingStore } from "./identity_mapping_store.js";
16
+ import { matchX509Subject } from "./x509_subject.js";
17
+
18
+ /**
19
+ * In-memory implementation of {@link IIdentityMappingStore}.
20
+ *
21
+ * Uses a `Map<string, IdentityMappingRuleType[]>` keyed by
22
+ * the role NodeId string representation.
23
+ */
24
+ export class InMemoryIdentityMappingStore implements IIdentityMappingStore {
25
+ private readonly _map = new Map<string, IdentityMappingRuleType[]>();
26
+
27
+ public addIdentity(roleId: NodeId, rule: IdentityMappingRuleType): boolean {
28
+ const key = roleId.toString();
29
+ let arr = this._map.get(key);
30
+ if (!arr) {
31
+ arr = [];
32
+ this._map.set(key, arr);
33
+ }
34
+ // Idempotent: skip if already present
35
+ if (arr.some((r) => r.criteriaType === rule.criteriaType && r.criteria === rule.criteria)) {
36
+ return false;
37
+ }
38
+ arr.push(
39
+ new IdentityMappingRuleType({
40
+ criteriaType: rule.criteriaType,
41
+ criteria: rule.criteria
42
+ })
43
+ );
44
+ return true;
45
+ }
46
+
47
+ public removeIdentity(roleId: NodeId, rule: IdentityMappingRuleType): boolean {
48
+ const key = roleId.toString();
49
+ const arr = this._map.get(key);
50
+ if (!arr) {
51
+ return false;
52
+ }
53
+ const idx = arr.findIndex((r) => r.criteriaType === rule.criteriaType && r.criteria === rule.criteria);
54
+ if (idx < 0) {
55
+ return false;
56
+ }
57
+ arr.splice(idx, 1);
58
+ if (arr.length === 0) {
59
+ this._map.delete(key);
60
+ }
61
+ return true;
62
+ }
63
+
64
+ public getIdentitiesForRole(roleId: NodeId): IdentityMappingRuleType[] {
65
+ const arr = this._map.get(roleId.toString());
66
+ if (!arr) {
67
+ return [];
68
+ }
69
+ return arr.map(
70
+ (r) =>
71
+ new IdentityMappingRuleType({
72
+ criteriaType: r.criteriaType,
73
+ criteria: r.criteria
74
+ })
75
+ );
76
+ }
77
+
78
+ public getRoleIds(): NodeId[] {
79
+ const result: NodeId[] = [];
80
+ for (const key of this._map.keys()) {
81
+ result.push(resolveNodeId(key));
82
+ }
83
+ return result;
84
+ }
85
+
86
+ public resolveRoles(token: AnyUserIdentityToken): NodeId[] {
87
+ const matched: NodeId[] = [];
88
+ for (const [key, rules] of this._map) {
89
+ for (const rule of rules) {
90
+ if (matchesRule(rule, token)) {
91
+ const roleId = resolveNodeId(key);
92
+ if (!matched.find((r) => sameNodeId(r, roleId))) {
93
+ matched.push(roleId);
94
+ }
95
+ break; // one match per role is enough
96
+ }
97
+ }
98
+ }
99
+ return matched;
100
+ }
101
+ }
102
+
103
+ /**
104
+ * Check if a single identity mapping rule matches a user identity token.
105
+ *
106
+ * For `X509Subject` criteria, see {@link matchX509Subject}: both the full
107
+ * ordered DN format (OPC 10000-18 §4.4.3) and a plain Common Name are accepted.
108
+ *
109
+ * @see OPC 10000-18 §4.4 IdentityMappingRuleType
110
+ */
111
+ function matchesRule(rule: IdentityMappingRuleType, token: AnyUserIdentityToken): boolean {
112
+ switch (rule.criteriaType) {
113
+ case IdentityCriteriaType.Anonymous:
114
+ return token instanceof AnonymousIdentityToken;
115
+
116
+ case IdentityCriteriaType.AuthenticatedUser:
117
+ return !(token instanceof AnonymousIdentityToken);
118
+
119
+ case IdentityCriteriaType.UserName:
120
+ return token instanceof UserNameIdentityToken && token.userName === rule.criteria;
121
+
122
+ case IdentityCriteriaType.Thumbprint: {
123
+ if (!(token instanceof X509IdentityToken) || !token.certificateData) {
124
+ return false;
125
+ }
126
+ const certBuffer = token.certificateData instanceof Buffer ? token.certificateData : Buffer.from(token.certificateData);
127
+ const thumbprint = makeSHA1Thumbprint(certBuffer).toString("hex").toUpperCase();
128
+ const expected = (rule.criteria ?? "").toUpperCase().replace(/[\s:]/g, "");
129
+ return thumbprint === expected;
130
+ }
131
+
132
+ case IdentityCriteriaType.X509Subject: {
133
+ if (!(token instanceof X509IdentityToken) || !token.certificateData) {
134
+ return false;
135
+ }
136
+ try {
137
+ const certBuffer =
138
+ token.certificateData instanceof Buffer ? token.certificateData : Buffer.from(token.certificateData);
139
+ const info = exploreCertificate(certBuffer);
140
+ const subject = info.tbsCertificate.subject ?? {};
141
+ return matchX509Subject(rule.criteria ?? "", subject);
142
+ } catch {
143
+ return false;
144
+ }
145
+ }
146
+
147
+ default:
148
+ return false;
149
+ }
150
+ }
@@ -0,0 +1,55 @@
1
+ /**
2
+ * @module node-opcua-role-set-common
3
+ */
4
+
5
+ export {
6
+ type ArchiveIO,
7
+ ArchiveStore,
8
+ identitiesFromBase64,
9
+ identitiesToBase64,
10
+ type PersistedCustomRole,
11
+ ROLE_SET_ARCHIVE_VERSION,
12
+ type RoleSetArchive,
13
+ readArchive,
14
+ writeArchive
15
+ } from "./archive.js";
16
+ export {
17
+ decodeIdentityStore,
18
+ encodeIdentityStore,
19
+ identityStoreBinaryStoreSize,
20
+ loadFromBinaryFile,
21
+ saveToBinaryFile
22
+ } from "./binary_persistence.js";
23
+ export type { AnyUserIdentityToken, IIdentityMappingStore } from "./identity_mapping_store.js";
24
+ export { InMemoryIdentityMappingStore } from "./in_memory_store.js";
25
+ export {
26
+ applicationComplies,
27
+ deserializeRestrictions,
28
+ type EndpointCriteria,
29
+ endpointComplies,
30
+ InMemoryRoleRestrictionStore,
31
+ type IRoleRestrictionStore,
32
+ loadRestrictionsFromFile,
33
+ type ResolutionContext,
34
+ type SerializedRoleRestriction,
35
+ saveRestrictionsToFile,
36
+ serializeRestrictions
37
+ } from "./role_restriction_store.js";
38
+ export {
39
+ type AuthenticationResult,
40
+ InMemoryUserManagementStore,
41
+ type IUserManagementStore,
42
+ type ModifyUserOptions,
43
+ type PasswordPolicy,
44
+ type SerializedUserRecord,
45
+ type UserRecord
46
+ } from "./user_management_store.js";
47
+ export { WellKnownRoleIds, WellKnownRoles } from "./well_known_role_ids.js";
48
+ export {
49
+ canonicalizeX509Subject,
50
+ certificateSubjectPairs,
51
+ matchX509Subject,
52
+ parseX509SubjectCriteria,
53
+ X509_SUBJECT_ORDER,
54
+ type X509SubjectName
55
+ } from "./x509_subject.js";