@decaf-ts/for-fabric 0.1.42 → 0.1.44

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 (37) hide show
  1. package/dist/for-fabric.cjs +1 -1
  2. package/dist/for-fabric.cjs.map +1 -1
  3. package/dist/for-fabric.js +1 -1
  4. package/dist/for-fabric.js.map +1 -1
  5. package/lib/client/services/FabricIdentityService.cjs +280 -0
  6. package/lib/client/services/FabricIdentityService.d.ts +88 -0
  7. package/lib/client/services/FabricIdentityService.js.map +1 -0
  8. package/lib/client/services/RegistrationRequestBuilder.cjs +91 -0
  9. package/lib/client/services/RegistrationRequestBuilder.d.ts +19 -0
  10. package/lib/client/services/RegistrationRequestBuilder.js.map +1 -0
  11. package/lib/client/services/index.cjs +2 -0
  12. package/lib/client/services/index.d.ts +2 -0
  13. package/lib/client/services/index.js.map +1 -1
  14. package/lib/contracts/FabricContractSequence.cjs +3 -48
  15. package/lib/contracts/FabricContractSequence.d.ts +0 -16
  16. package/lib/contracts/FabricContractSequence.js.map +1 -1
  17. package/lib/contracts/logging.cjs +3 -0
  18. package/lib/contracts/logging.js.map +1 -1
  19. package/lib/esm/client/services/FabricIdentityService.d.ts +88 -0
  20. package/lib/esm/client/services/FabricIdentityService.js +273 -0
  21. package/lib/esm/client/services/FabricIdentityService.js.map +1 -0
  22. package/lib/esm/client/services/RegistrationRequestBuilder.d.ts +19 -0
  23. package/lib/esm/client/services/RegistrationRequestBuilder.js +87 -0
  24. package/lib/esm/client/services/RegistrationRequestBuilder.js.map +1 -0
  25. package/lib/esm/client/services/index.d.ts +2 -0
  26. package/lib/esm/client/services/index.js +2 -0
  27. package/lib/esm/client/services/index.js.map +1 -1
  28. package/lib/esm/contracts/FabricContractSequence.d.ts +0 -16
  29. package/lib/esm/contracts/FabricContractSequence.js +4 -49
  30. package/lib/esm/contracts/FabricContractSequence.js.map +1 -1
  31. package/lib/esm/contracts/logging.js +3 -0
  32. package/lib/esm/contracts/logging.js.map +1 -1
  33. package/lib/esm/version.d.ts +1 -1
  34. package/lib/esm/version.js +1 -1
  35. package/lib/version.cjs +1 -1
  36. package/lib/version.d.ts +1 -1
  37. package/package.json +1 -1
@@ -69,6 +69,9 @@ class ContractLogger extends logging_1.MiniLogger {
69
69
  case logging_1.LogLevel.error:
70
70
  method = this.logger.error;
71
71
  break;
72
+ case logging_1.LogLevel.warn:
73
+ method = this.logger.warn;
74
+ break;
72
75
  case logging_1.LogLevel.silly:
73
76
  method = this.logger.silly;
74
77
  break;
@@ -1 +1 @@
1
- {"version":3,"file":"logging.js","sourceRoot":"","sources":["../../src/contracts/logging.ts"],"names":[],"mappings":";;;AAAA,+CAQ2B;AAG3B,2DAAwD;AAExD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6BG;AACH,MAAa,cAAe,SAAQ,oBAAU;IAM5C,YACE,OAAe,EACf,IAAwC,EACxC,GAAS;QAET,KAAK,CAAC,OAAO,EAAE,IAAI,CAAC,CAAC;QAErB,IAAI,CAAC,GAAG,EAAE,CAAC;YACT,IAAI,CAAC,MAAM,GAAG,IAAI,oBAAU,CAAC,OAAO,EAAE,IAAI,CAAC,CAAC;QAC9C,CAAC;aAAM,CAAC;YACN,IAAI,CAAC,MAAM,GAAG,GAAG,CAAC,OAAO,CAAC,SAAS,CAAC,OAAO,CAAsB,CAAC;QACpE,CAAC;IACH,CAAC;IAED;;;;;;;OAOG;IACgB,GAAG,CACpB,KAAe,EACf,GAAuB,EACvB,KAAa;QAEb,IACE,0BAAgB,CAAC,IAAI,CAAC,MAAM,CAAC,OAAO,CAAa,CAAC;YAClD,0BAAgB,CAAC,KAAK,CAAC;YAEvB,OAAO;QAET,IAAI,MAAM,CAAC;QACX,QAAQ,KAAK,EAAE,CAAC;YACd,KAAK,kBAAQ,CAAC,IAAI;gBAChB,MAAM,GAAG,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC;gBAC1B,MAAM;YACR,KAAK,kBAAQ,CAAC,OAAO;gB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AAED;;;;;;;;;GASG;AACH,MAAM,OAAO,GAAkB,CAC7B,MAAe,EACf,MAA+B,EAC/B,GAAS,EACT,EAAE;IACF,OAAO,IAAI,cAAc,CACvB,MAAM,IAAI,cAAc,CAAC,IAAI,EAC7B,MAAM,IAAI,EAAE,EACZ,GAAU,CACX,CAAC;AACJ,CAAC,CAAC;AAEF,gDAAgD;AAChD,iBAAO,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC"}
@@ -0,0 +1,88 @@
1
+ import { AuthorizationError, ClientBasedService, Context, MaybeContextualArg } from "@decaf-ts/core";
2
+ import FabricCAServices, { AffiliationService, IdentityService, IEnrollResponse, IServiceResponse } from "fabric-ca-client";
3
+ import { CAConfig, Credentials } from "../../shared/types";
4
+ import { ConflictError } from "@decaf-ts/db-decorators";
5
+ import { CertificateResponse, FabricIdentity, GetCertificatesRequest } from "../../shared/fabric-types";
6
+ import { User } from "fabric-common";
7
+ import { CA_ROLE } from "./constants";
8
+ import { IKeyValueAttribute } from "./FabricEnrollmentService";
9
+ import { Identity } from "../../shared/index";
10
+ export declare class FabricIdentityService extends ClientBasedService<FabricCAServices, CAConfig> {
11
+ protected _user: User;
12
+ constructor();
13
+ protected get rootClient(): {
14
+ newCertificateService: any;
15
+ };
16
+ protected get user(): User;
17
+ protected get certificates(): any;
18
+ protected get affiliations(): AffiliationService;
19
+ protected get identities(): IdentityService;
20
+ protected getUser(cfg: CAConfig, ctx: Context): Promise<User>;
21
+ initialize(...args: MaybeContextualArg<any>): Promise<{
22
+ config: CAConfig;
23
+ client: FabricCAServices;
24
+ }>;
25
+ getCertificates(...args: MaybeContextualArg<any>): Promise<string[]>;
26
+ getCertificates(request: GetCertificatesRequest, ...args: MaybeContextualArg<any>): Promise<string[]>;
27
+ getCertificates<MAP extends boolean>(doMap: MAP, ...args: MaybeContextualArg<any>): Promise<MAP extends false ? CertificateResponse : string[]>;
28
+ getCertificates<MAP extends boolean>(request: GetCertificatesRequest, doMap: MAP, ...args: MaybeContextualArg<any>): Promise<MAP extends false ? CertificateResponse : string[]>;
29
+ getIdentities(ctx: Context): Promise<FabricIdentity[]>;
30
+ /**
31
+ * @description Retrieve affiliations from the CA.
32
+ * @summary Queries the CA for the list of affiliations available under the configured CA.
33
+ * @return {string} The affiliations result payload.
34
+ */
35
+ getAffiliations(ctx: Context): Promise<any>;
36
+ protected parseError(e: Error): AuthorizationError | ConflictError;
37
+ /**
38
+ * @description Read identity details from the CA by enrollment ID.
39
+ * @summary Retrieves and validates a single identity, throwing NotFoundError when missing.
40
+ * @param {string} enrollmentId - Enrollment ID to lookup.
41
+ * @return {Promise<FabricIdentity>} The identity details stored in the CA.
42
+ */
43
+ read(enrollmentId: string, ...args: MaybeContextualArg<any>): Promise<FabricIdentity>;
44
+ /**
45
+ * @description Register a new identity with the CA.
46
+ * @summary Submits a registration request for a new enrollment ID, returning the enrollment secret upon success.
47
+ * @param {Credentials} model - Credentials containing userName and password for the new identity.
48
+ * @param {boolean} [isSuperUser=false] - Whether to register the identity as a super user.
49
+ * @param {string} [affiliation=""] - Affiliation string (e.g., org1.department1).
50
+ * @param {CA_ROLE | string} [userRole] - Role to assign to the identity.
51
+ * @param {IKeyValueAttribute} [attrs] - Optional attributes to attach to the identity.
52
+ * @param {number} [maxEnrollments] - Maximum number of enrollments allowed for the identity.
53
+ * @return {Promise<string>} The enrollment secret for the registered identity.
54
+ */
55
+ register(model: Credentials, isSuperUser?: boolean, affiliation?: string, userRole?: CA_ROLE | string, attrs?: IKeyValueAttribute, maxEnrollments?: number, ...args: MaybeContextualArg<any>): Promise<string>;
56
+ protected static identityFromEnrollment(enrollment: IEnrollResponse, mspId: string, ctx: Context): Identity;
57
+ /**
58
+ * @description Enroll an identity with the CA using a registration secret.
59
+ * @summary Exchanges the enrollment ID and secret for certificates, returning a constructed Identity model.
60
+ * @param {string} enrollmentId - Enrollment ID to enroll.
61
+ * @param {string} registration - Enrollment secret returned at registration time.
62
+ * @return {Promise<Identity>} The enrolled identity object with credentials.
63
+ */
64
+ enroll(enrollmentId: string, registration: string, ...args: MaybeContextualArg<any>): Promise<Identity>;
65
+ /**
66
+ * @description Register and enroll a new identity in one step.
67
+ * @summary Registers a new enrollment ID with the CA and immediately exchanges the secret to enroll, returning the created Identity.
68
+ * @param {Credentials} model - Credentials for the new identity containing userName and password.
69
+ * @param {boolean} [isSuperUser=false] - Whether to register the identity as a super user.
70
+ * @param {string} [affiliation=""] - Affiliation string (e.g., org1.department1).
71
+ * @param {CA_ROLE | string} [userRole] - Role to assign to the identity.
72
+ * @param {IKeyValueAttribute} [attrs] - Optional attributes to attach to the identity.
73
+ * @param {number} [maxEnrollments] - Maximum number of enrollments allowed for the identity.
74
+ * @return {Promise<Identity>} The enrolled identity.
75
+ */
76
+ registerAndEnroll(model: Credentials, isSuperUser?: boolean, affiliation?: string, userRole?: CA_ROLE | string, attrs?: IKeyValueAttribute, maxEnrollments?: number, ...args: MaybeContextualArg<any>): Promise<Identity>;
77
+ /**
78
+ * Revokes the enrollment of an identity with the specified enrollment ID.
79
+ *
80
+ * @param enrollmentId - The enrollment ID of the identity to be revoked.
81
+ *
82
+ * @returns A Promise that resolves to the result of the revocation operation.
83
+ *
84
+ * @throws {NotFoundError} If the enrollment with the specified ID does not exist.
85
+ * @throws {InternalError} If there is an error during the revocation process.
86
+ */
87
+ revoke(enrollmentId: string, ...args: MaybeContextualArg<any>): Promise<IServiceResponse>;
88
+ }
@@ -0,0 +1,273 @@
1
+ import { AuthorizationError, ClientBasedService, Context, } from "@decaf-ts/core";
2
+ import FabricCAServices from "fabric-ca-client";
3
+ import { ConflictError, InternalError, NotFoundError, } from "@decaf-ts/db-decorators";
4
+ import { CoreUtils } from "./../../shared/utils.js";
5
+ import { RegistrationError } from "./../../shared/errors.js";
6
+ import { Identity } from "./../../shared/index.js";
7
+ import { CryptoUtils } from "./../../shared/crypto.js";
8
+ export class FabricIdentityService extends ClientBasedService {
9
+ constructor() {
10
+ super();
11
+ }
12
+ get rootClient() {
13
+ return this.client["_FabricCaServices"];
14
+ }
15
+ get user() {
16
+ if (!this._user)
17
+ throw new InternalError("Fabric identity service not properly setup: missing user");
18
+ return this._user;
19
+ }
20
+ get certificates() {
21
+ return this.rootClient.newCertificateService();
22
+ }
23
+ get affiliations() {
24
+ return this.client.newAffiliationService();
25
+ }
26
+ get identities() {
27
+ return this.client.newIdentityService();
28
+ }
29
+ async getUser(cfg, ctx) {
30
+ const log = ctx.logger.for(this.getUser);
31
+ const { caName, caCert, caKey, url, hsm } = cfg;
32
+ log.info(`Creating CA user for ${caName} at ${url}`);
33
+ log.verbose(`Retrieving CA certificate from ${caCert}`);
34
+ const certificate = await CoreUtils.getFirstDirFileNameContent(caCert);
35
+ let key;
36
+ if (!hsm) {
37
+ if (!caKey) {
38
+ throw new InternalError(`Missing caKey configuration for CA ${caName}. Provide a key directory or configure HSM support.`);
39
+ }
40
+ log.debug(`Retrieving CA key from ${caKey}`);
41
+ key = await CoreUtils.getFirstDirFileNameContent(caKey);
42
+ }
43
+ else {
44
+ log.debug(`Using HSM configuration for CA ${caName} with library ${hsm.library}`);
45
+ }
46
+ log.debug(`Loading Admin user for ca ${caName}`);
47
+ this._user = await CoreUtils.getCAUser("admin", key, certificate, caName, {
48
+ hsm,
49
+ });
50
+ return this._user;
51
+ }
52
+ async initialize(...args) {
53
+ const { log, ctx } = await this.logCtx(args, this.initialize, true);
54
+ const [config] = args;
55
+ if (!config)
56
+ throw new InternalError("Missing Fabric CA configuration");
57
+ const { url, tls, caName } = config;
58
+ log.info(`Initializing CA Client for CA ${config.caName} at ${config.url}`);
59
+ const { trustedRoots, verify } = tls;
60
+ const root = trustedRoots[0];
61
+ log.debug(`Retrieving CA certificate from ${root}. cwd: ${process.cwd()}`);
62
+ const certificate = await CoreUtils.getFileContent(root);
63
+ log.debug(`CA Certificate: ${certificate.toString()}`);
64
+ const client = new FabricCAServices(url, {
65
+ trustedRoots: Buffer.from(certificate),
66
+ verify,
67
+ }, caName);
68
+ const user = await this.getUser(config, ctx);
69
+ log.debug(`CA user loaded: ${user.getName()}`);
70
+ return {
71
+ config,
72
+ client,
73
+ };
74
+ }
75
+ async getCertificates(request, doMap = true, ...args) {
76
+ if (request instanceof Context) {
77
+ args = [request];
78
+ doMap = true;
79
+ request = undefined;
80
+ }
81
+ else if (typeof request === "boolean") {
82
+ doMap = request;
83
+ request = undefined;
84
+ }
85
+ else if (typeof doMap !== "boolean") {
86
+ args = [doMap, ...args];
87
+ doMap = true;
88
+ }
89
+ const { log } = await this.logCtx(args, this.getCertificates, true);
90
+ log.debug(`Retrieving certificates${request ? ` for ${request.id}` : ""} for CA ${this.config.caName}`);
91
+ const response = (await this.certificates.getCertificates(request || {}, this.user)).result;
92
+ log.verbose(`Found ${response.certs.length} certificates`);
93
+ log.debug(response.certs);
94
+ return (doMap ? response.certs.map((c) => c.PEM) : response);
95
+ }
96
+ async getIdentities(ctx) {
97
+ const log = ctx.logger.for(this.getIdentities);
98
+ log.verbose(`Retrieving Identities under CA ${this.config.caName}`);
99
+ const response = (await this.identities.getAll(this.user))
100
+ .result;
101
+ log.verbose(`Found ${response.identities.length} Identities`);
102
+ log.debug(response.identities);
103
+ return response.identities;
104
+ }
105
+ /**
106
+ * @description Retrieve affiliations from the CA.
107
+ * @summary Queries the CA for the list of affiliations available under the configured CA.
108
+ * @return {string} The affiliations result payload.
109
+ */
110
+ async getAffiliations(ctx) {
111
+ const log = ctx.logger.for(this.getAffiliations);
112
+ log.verbose(`Retrieving Affiliations under CA ${this.config.caName}`);
113
+ const response = (await this.affiliations.getAll(this.user)).result;
114
+ log.verbose(`Found ${response.a.length} Affiliations`);
115
+ log.debug(JSON.stringify(response));
116
+ return response;
117
+ }
118
+ parseError(e) {
119
+ const regexp = /.*code:\s(\d+).*?message:\s["'](.+)["']/gs;
120
+ const match = regexp.exec(e.message);
121
+ if (!match)
122
+ return new RegistrationError(e);
123
+ const [, code, message] = match;
124
+ switch (code) {
125
+ case "74":
126
+ case "71":
127
+ return new ConflictError(message);
128
+ case "20":
129
+ return new AuthorizationError(message);
130
+ default:
131
+ return new RegistrationError(message);
132
+ }
133
+ }
134
+ /**
135
+ * @description Read identity details from the CA by enrollment ID.
136
+ * @summary Retrieves and validates a single identity, throwing NotFoundError when missing.
137
+ * @param {string} enrollmentId - Enrollment ID to lookup.
138
+ * @return {Promise<FabricIdentity>} The identity details stored in the CA.
139
+ */
140
+ async read(enrollmentId, ...args) {
141
+ const { log } = await this.logCtx(args, this.read, true);
142
+ log.verbose(`Retrieving identity with enrollment ID ${enrollmentId}`);
143
+ let result;
144
+ try {
145
+ result = await this.identities.getOne(enrollmentId, this.user);
146
+ }
147
+ catch (e) {
148
+ throw new NotFoundError(`Couldn't find enrollment with id ${enrollmentId}: ${e}`);
149
+ }
150
+ if (!result.success)
151
+ throw new NotFoundError(`Couldn't find enrollment with id ${enrollmentId}: ${result.errors.join("\n")}`);
152
+ return result.result;
153
+ }
154
+ /**
155
+ * @description Register a new identity with the CA.
156
+ * @summary Submits a registration request for a new enrollment ID, returning the enrollment secret upon success.
157
+ * @param {Credentials} model - Credentials containing userName and password for the new identity.
158
+ * @param {boolean} [isSuperUser=false] - Whether to register the identity as a super user.
159
+ * @param {string} [affiliation=""] - Affiliation string (e.g., org1.department1).
160
+ * @param {CA_ROLE | string} [userRole] - Role to assign to the identity.
161
+ * @param {IKeyValueAttribute} [attrs] - Optional attributes to attach to the identity.
162
+ * @param {number} [maxEnrollments] - Maximum number of enrollments allowed for the identity.
163
+ * @return {Promise<string>} The enrollment secret for the registered identity.
164
+ */
165
+ async register(model, isSuperUser = false, affiliation = "", userRole, attrs, maxEnrollments, ...args) {
166
+ const { log } = await this.logCtx(args, this.register, true);
167
+ let registration;
168
+ try {
169
+ const { userName, password } = model;
170
+ const props = {
171
+ enrollmentID: userName,
172
+ enrollmentSecret: password,
173
+ affiliation: affiliation,
174
+ userRole: userRole,
175
+ attrs: attrs,
176
+ maxEnrollments: maxEnrollments,
177
+ };
178
+ registration = await this.client.register(props, this.user);
179
+ log.info(`Registration for ${userName} created with user type ${userRole ?? "Undefined Role"} ${isSuperUser ? "as super user" : ""}`);
180
+ }
181
+ catch (e) {
182
+ throw this.parseError(e);
183
+ }
184
+ return registration;
185
+ }
186
+ static identityFromEnrollment(enrollment, mspId, ctx) {
187
+ const log = ctx.logger.for(this.identityFromEnrollment);
188
+ const { certificate, key, rootCertificate } = enrollment;
189
+ log.verbose(`Generating Identity from certificate ${certificate} in msp ${mspId}`);
190
+ const clientId = CryptoUtils.fabricIdFromCertificate(certificate);
191
+ const id = CryptoUtils.encode(clientId);
192
+ log.debug(`Identity ${clientId} and encodedId ${id}`);
193
+ return new Identity({
194
+ id: id,
195
+ credentials: {
196
+ id: id,
197
+ certificate: certificate,
198
+ privateKey: key.toBytes(),
199
+ rootCertificate: rootCertificate,
200
+ },
201
+ mspId: mspId,
202
+ });
203
+ }
204
+ /**
205
+ * @description Enroll an identity with the CA using a registration secret.
206
+ * @summary Exchanges the enrollment ID and secret for certificates, returning a constructed Identity model.
207
+ * @param {string} enrollmentId - Enrollment ID to enroll.
208
+ * @param {string} registration - Enrollment secret returned at registration time.
209
+ * @return {Promise<Identity>} The enrolled identity object with credentials.
210
+ */
211
+ async enroll(enrollmentId, registration, ...args) {
212
+ const { log, ctx } = await this.logCtx(args, this.enroll, true);
213
+ let identity;
214
+ try {
215
+ log.debug(`Enrolling ${enrollmentId}`);
216
+ const enrollment = await this.client.enroll({
217
+ enrollmentID: enrollmentId,
218
+ enrollmentSecret: registration,
219
+ });
220
+ identity = FabricIdentityService.identityFromEnrollment(enrollment, this.config.caName, ctx);
221
+ log.info(`Successfully enrolled ${enrollmentId} under ${this.config.caName} as ${identity.id}`);
222
+ }
223
+ catch (e) {
224
+ throw this.parseError(e);
225
+ }
226
+ return identity;
227
+ }
228
+ /**
229
+ * @description Register and enroll a new identity in one step.
230
+ * @summary Registers a new enrollment ID with the CA and immediately exchanges the secret to enroll, returning the created Identity.
231
+ * @param {Credentials} model - Credentials for the new identity containing userName and password.
232
+ * @param {boolean} [isSuperUser=false] - Whether to register the identity as a super user.
233
+ * @param {string} [affiliation=""] - Affiliation string (e.g., org1.department1).
234
+ * @param {CA_ROLE | string} [userRole] - Role to assign to the identity.
235
+ * @param {IKeyValueAttribute} [attrs] - Optional attributes to attach to the identity.
236
+ * @param {number} [maxEnrollments] - Maximum number of enrollments allowed for the identity.
237
+ * @return {Promise<Identity>} The enrolled identity.
238
+ */
239
+ async registerAndEnroll(model, isSuperUser = false, affiliation = "", userRole, attrs, maxEnrollments, ...args) {
240
+ const { ctx } = await this.logCtx(args, this.registerAndEnroll, true);
241
+ const registration = await this.register(model, isSuperUser, affiliation, userRole, attrs, maxEnrollments, ctx);
242
+ const { userName } = model;
243
+ return this.enroll(userName, registration, ctx);
244
+ }
245
+ /**
246
+ * Revokes the enrollment of an identity with the specified enrollment ID.
247
+ *
248
+ * @param enrollmentId - The enrollment ID of the identity to be revoked.
249
+ *
250
+ * @returns A Promise that resolves to the result of the revocation operation.
251
+ *
252
+ * @throws {NotFoundError} If the enrollment with the specified ID does not exist.
253
+ * @throws {InternalError} If there is an error during the revocation process.
254
+ */
255
+ async revoke(enrollmentId, ...args) {
256
+ const { log } = await this.logCtx(args, this.revoke, true);
257
+ log.verbose(`Revoking identity with enrollment ID ${enrollmentId}`);
258
+ const identity = await this.read(enrollmentId);
259
+ if (!identity)
260
+ throw new NotFoundError(`Could not find enrollment with id ${enrollmentId}`);
261
+ let result;
262
+ try {
263
+ result = await this.client.revoke({ enrollmentID: identity.id, reason: "User Deletion" }, this.user);
264
+ }
265
+ catch (e) {
266
+ throw new InternalError(`Could not revoke enrollment with id ${enrollmentId}: ${e}`);
267
+ }
268
+ if (!result.success)
269
+ throw new InternalError(`Could not revoke enrollment with id ${enrollmentId}: ${result.errors.join("\n")}`);
270
+ return result;
271
+ }
272
+ }
273
+ //# sourceMappingURL=FabricIdentityService.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"FabricIdentityService.js","sourceRoot":"","sources":["../../../../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yValueAttribute } from "fabric-ca-client";
2
+ import { CA_ROLE } from "./constants";
3
+ import { Model } from "@decaf-ts/decorator-validation";
4
+ export declare class RegistrationRequestBuilder extends Model {
5
+ affiliation: string;
6
+ attrs?: IKeyValueAttribute[];
7
+ enrollmentID: string;
8
+ enrollmentSecret: string;
9
+ maxEnrollments?: number;
10
+ role: string;
11
+ build(): IRegisterRequest;
12
+ setAffiliation(value: string): this;
13
+ addAttr(attr: IKeyValueAttribute): this;
14
+ setAttrs(value: IKeyValueAttribute[]): this;
15
+ setEnrollmentID(value: string): this;
16
+ setEnrollmentSecret(value: string): this;
17
+ setMaxEnrollments(value: number): this;
18
+ setRole(value: CA_ROLE | string): this;
19
+ }
@@ -0,0 +1,87 @@
1
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6
+ };
7
+ var __metadata = (this && this.__metadata) || function (k, v) {
8
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
9
+ };
10
+ import { min, minlength, Model, required, } from "@decaf-ts/decorator-validation";
11
+ import { ValidationError } from "@decaf-ts/db-decorators";
12
+ export class RegistrationRequestBuilder extends Model {
13
+ constructor() {
14
+ super(...arguments);
15
+ this.affiliation = "";
16
+ }
17
+ build() {
18
+ const errs = this.hasErrors();
19
+ if (errs)
20
+ throw new ValidationError(errs.toString());
21
+ const response = {
22
+ enrollmentID: this.enrollmentID,
23
+ enrollmentSecret: this.enrollmentSecret,
24
+ role: this.role,
25
+ affiliation: this.affiliation,
26
+ };
27
+ if (typeof this.maxEnrollments !== "undefined")
28
+ response.maxEnrollments = this.maxEnrollments;
29
+ if (this.attrs)
30
+ response.attrs = this.attrs;
31
+ return response;
32
+ }
33
+ setAffiliation(value) {
34
+ this.affiliation = value;
35
+ return this;
36
+ }
37
+ addAttr(attr) {
38
+ this.attrs = this.attrs || [];
39
+ this.attrs.push(attr);
40
+ return this;
41
+ }
42
+ setAttrs(value) {
43
+ this.attrs = value;
44
+ return this;
45
+ }
46
+ setEnrollmentID(value) {
47
+ this.enrollmentID = value;
48
+ return this;
49
+ }
50
+ setEnrollmentSecret(value) {
51
+ this.enrollmentSecret = value;
52
+ return this;
53
+ }
54
+ setMaxEnrollments(value) {
55
+ this.maxEnrollments = value;
56
+ return this;
57
+ }
58
+ setRole(value) {
59
+ this.role = value;
60
+ return this;
61
+ }
62
+ }
63
+ __decorate([
64
+ required(),
65
+ __metadata("design:type", String)
66
+ ], RegistrationRequestBuilder.prototype, "affiliation", void 0);
67
+ __decorate([
68
+ minlength(1),
69
+ __metadata("design:type", Array)
70
+ ], RegistrationRequestBuilder.prototype, "attrs", void 0);
71
+ __decorate([
72
+ required(),
73
+ __metadata("design:type", String)
74
+ ], RegistrationRequestBuilder.prototype, "enrollmentID", void 0);
75
+ __decorate([
76
+ required(),
77
+ __metadata("design:type", String)
78
+ ], RegistrationRequestBuilder.prototype, "enrollmentSecret", void 0);
79
+ __decorate([
80
+ min(0),
81
+ __metadata("design:type", Number)
82
+ ], RegistrationRequestBuilder.prototype, "maxEnrollments", void 0);
83
+ __decorate([
84
+ required(),
85
+ __metadata("design:type", String)
86
+ ], RegistrationRequestBuilder.prototype, "role", void 0);
87
+ //# sourceMappingURL=RegistrationRequestBuilder.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"RegistrationRequestBuilder.js","sourceRoot":"","sources":["../../../../src/client/services/RegistrationRequestBuilder.ts"],"names":[],"mappings":";;;;;;;;;AAEA,OAAO,EACL,GAAG,EACH,SAAS,EACT,KAAK,EACL,QAAQ,GACT,MAA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AmB,CAAC,KAAa;QAC/B,IAAI,CAAC,gBAAgB,GAAG,KAAK,CAAC;QAC9B,OAAO,IAAI,CAAC;IACd,CAAC;IAED,iBAAiB,CAAC,KAAa;QAC7B,IAAI,CAAC,cAAc,GAAG,KAAK,CAAC;QAC5B,OAAO,IAAI,CAAC;IACd,CAAC;IAED,OAAO,CAAC,KAAuB;QAC7B,IAAI,CAAC,IAAI,GAAG,KAAK,CAAC;QAClB,OAAO,IAAI,CAAC;IACd,CAAC;CACF;AA9DC;IADC,QAAQ,EAAE;;+DACc;AAEzB;IADC,SAAS,CAAC,CAAC,CAAC;;yDACgB;AAE7B;IADC,QAAQ,EAAE;;gEACW;AAEtB;IADC,QAAQ,EAAE;;oEACe;AAE1B;IADC,GAAG,CAAC,CAAC,CAAC;;kEACiB;AAExB;IADC,QAAQ,EAAE;;wDACG"}
@@ -1,2 +1,4 @@
1
1
  export * from "./FabricEnrollmentService";
2
+ export * from "./RegistrationRequestBuilder";
3
+ export * from "./FabricIdentityService";
2
4
  export * from "./constants";
@@ -1,3 +1,5 @@
1
1
  export * from "./FabricEnrollmentService.js";
2
+ export * from "./RegistrationRequestBuilder.js";
3
+ export * from "./FabricIdentityService.js";
2
4
  export * from "./constants.js";
3
5
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/client/services/index.ts"],"names":[],"mappings":"AAAA,6CAA0C;AAC1C,+BAA4B"}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/client/services/index.ts"],"names":[],"mappings":"AAAA,6CAA0C;AAC1C,gDAA6C;AAC7C,2CAAwC;AACxC,+BAA4B"}
@@ -67,20 +67,4 @@ export declare class FabricContractSequence extends Sequence {
67
67
  * @return A promise that resolves to the new sequence value after incrementing
68
68
  */
69
69
  protected increment(count: number | undefined, ctx: Context<any>): Promise<string | number | bigint>;
70
- /**
71
- * @description Gets the next value in the sequence
72
- * @summary Retrieves the current value of the sequence and increments it by the
73
- * configured increment amount. This is the main method used to get a new sequential value.
74
- * @return A promise that resolves to the next value in the sequence
75
- */
76
- next(...argz: MaybeContextualArg<any>): Promise<number | string | bigint>;
77
- /**
78
- * @description Generates a range of sequential values
79
- * @summary Retrieves a specified number of sequential values from the sequence.
80
- * This is useful when you need to allocate multiple IDs at once.
81
- * The method increments the sequence by the total amount needed and returns all values in the range.
82
- * @param {number} count - The number of sequential values to generate
83
- * @return A promise that resolves to an array of sequential values
84
- */
85
- range(count: number, ...argz: MaybeContextualArg<any>): Promise<(number | string | bigint)[]>;
86
70
  }
@@ -1,5 +1,5 @@
1
1
  import { ConflictError, InternalError, NotFoundError, OperationKeys, } from "@decaf-ts/db-decorators";
2
- import { Context, Sequence, SequenceModel, Serial, UnsupportedError, UUID, } from "@decaf-ts/core";
2
+ import { Context, Sequence, SequenceModel, Serial, UUID, } from "@decaf-ts/core";
3
3
  /**
4
4
  * @description Abstract base class for sequence generation
5
5
  * @summary Provides a framework for generating sequential values (like primary keys) in the persistence layer.
@@ -73,16 +73,15 @@ export class FabricContractSequence extends Sequence {
73
73
  if (e instanceof NotFoundError) {
74
74
  let cachedCurrent;
75
75
  try {
76
+ log.debug(`Trying to resolve current sequence ${name} value from context`);
76
77
  cachedCurrent = ctx.get(name);
77
- log.info(`Retrieved cached current value for sequence ${name}: ${cachedCurrent}`);
78
+ log.debug(`Retrieved cached current value for sequence ${name}: ${cachedCurrent}`);
78
79
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
79
80
  }
80
81
  catch (e) {
82
+ log.info(`No cached value for sequence ${name} in context`);
81
83
  cachedCurrent = startWith;
82
84
  }
83
- log.debug(`Sequence.current missing ${name}, returning startWith=${cachedCurrent}`);
84
- if (typeof cachedCurrent === "undefined")
85
- throw new InternalError("Starting value is not defined for a non existing sequence");
86
85
  try {
87
86
  return this.parse(cachedCurrent);
88
87
  }
@@ -171,49 +170,5 @@ export class FabricContractSequence extends Sequence {
171
170
  return seq.current;
172
171
  }, name);
173
172
  }
174
- /**
175
- * @description Gets the next value in the sequence
176
- * @summary Retrieves the current value of the sequence and increments it by the
177
- * configured increment amount. This is the main method used to get a new sequential value.
178
- * @return A promise that resolves to the next value in the sequence
179
- */
180
- async next(...argz) {
181
- const contextArgs = await Context.args(OperationKeys.UPDATE, SequenceModel, argz, this.adapter);
182
- const { context } = contextArgs;
183
- return this.increment(undefined, context);
184
- }
185
- /**
186
- * @description Generates a range of sequential values
187
- * @summary Retrieves a specified number of sequential values from the sequence.
188
- * This is useful when you need to allocate multiple IDs at once.
189
- * The method increments the sequence by the total amount needed and returns all values in the range.
190
- * @param {number} count - The number of sequential values to generate
191
- * @return A promise that resolves to an array of sequential values
192
- */
193
- async range(count, ...argz) {
194
- const contextArgs = await Context.args(OperationKeys.UPDATE, SequenceModel, argz, this.adapter);
195
- const { context, args } = contextArgs;
196
- const log = context.logger.for(this.range);
197
- if (this.options.type === "uuid" || this.options.type === "serial")
198
- throw new UnsupportedError(// TODO just generate valid uuids/serials
199
- `type ${this.options.type} is currently not suppported for this adapter`);
200
- const typeName = typeof this.options.type === "function" &&
201
- this.options.type?.name
202
- ? this.options.type.name
203
- : this.options.type;
204
- log.info(`Obtaining sequence range for ${typeName}`);
205
- const current = (await this.current(...args));
206
- log.info(`current value is ${current}`);
207
- const incrementBy = this.parse(this.options.incrementBy);
208
- const next = await this.increment(this.parse(count) * incrementBy, context);
209
- const range = [];
210
- for (let i = 1; i <= count; i++) {
211
- range.push(current + incrementBy * this.parse(i));
212
- }
213
- log.info(`Calculated range: ${range.join(", ")}`);
214
- if (range[range.length - 1] !== next && typeName !== "String")
215
- throw new InternalError("Miscalculation of range");
216
- return range;
217
- }
218
173
  }
219
174
  //# sourceMappingURL=FabricContractSequence.js.map