gdc-common-utils-ts 1.0.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.
Files changed (100) hide show
  1. package/PUBLISHING.md +33 -0
  2. package/__tests__/AesManager.test.ts +53 -0
  3. package/__tests__/CryptographyService.test.ts +194 -0
  4. package/__tests__/bundle.test.ts +29 -0
  5. package/__tests__/content.test.ts +72 -0
  6. package/__tests__/crypto-encode-decode.test.ts +52 -0
  7. package/__tests__/crypto-hmac.test.ts +21 -0
  8. package/__tests__/did-generateServiceId.errors.test.ts +8 -0
  9. package/__tests__/did-generateServiceId.test.ts +18 -0
  10. package/__tests__/models-clinical-sections.test.ts +32 -0
  11. package/__tests__/models-multibase58.test.ts +33 -0
  12. package/__tests__/multibase58.errors.test.ts +7 -0
  13. package/__tests__/multibase58.test.ts +28 -0
  14. package/__tests__/multibasehash.test.ts +25 -0
  15. package/__tests__/utils-actor.test.ts +22 -0
  16. package/__tests__/utils-base-convert.test.ts +57 -0
  17. package/__tests__/utils-baseN.test.ts +40 -0
  18. package/__tests__/utils-did-extra.test.ts +33 -0
  19. package/__tests__/utils-format-converter.test.ts +87 -0
  20. package/__tests__/utils-jwt.test.ts +57 -0
  21. package/__tests__/utils-manager-error.test.ts +11 -0
  22. package/__tests__/utils-normalize.test.ts +15 -0
  23. package/__tests__/utils-object-convert.test.ts +38 -0
  24. package/__tests__/utils-string-convert.test.ts +20 -0
  25. package/__tests__/utils-string-utils.test.ts +25 -0
  26. package/__tests__/utils-url.test.ts +21 -0
  27. package/babel.config.cjs +5 -0
  28. package/jest.config.ts +46 -0
  29. package/package.json +36 -0
  30. package/src/AesManager.ts +82 -0
  31. package/src/CryptographyService.ts +461 -0
  32. package/src/JweManager.ts.txt +365 -0
  33. package/src/KmsService.txt +493 -0
  34. package/src/constants/Schemas.ts +61 -0
  35. package/src/constants/index.ts +1 -0
  36. package/src/constants/schemaorg.ts +193 -0
  37. package/src/cryptoDecode.ts +104 -0
  38. package/src/cryptoEncode.ts +36 -0
  39. package/src/cryptography.abstract.ts +29 -0
  40. package/src/hmac.ts +15 -0
  41. package/src/index.ts +3 -0
  42. package/src/interfaces/Cryptography.types.ts +131 -0
  43. package/src/interfaces/ICryptoHelper.ts +33 -0
  44. package/src/interfaces/ICryptography.ts +177 -0
  45. package/src/interfaces/IWallet.ts +62 -0
  46. package/src/interfaces/MlDsa.ts +25 -0
  47. package/src/interfaces/MlKem.ts +18 -0
  48. package/src/models/aes.ts +93 -0
  49. package/src/models/auth.ts +38 -0
  50. package/src/models/bundle.ts +152 -0
  51. package/src/models/bundle.txt +93 -0
  52. package/src/models/clinical-sections.en.ts +82 -0
  53. package/src/models/clinical-sections.ts +64 -0
  54. package/src/models/comm.ts +63 -0
  55. package/src/models/confidential-job.ts +100 -0
  56. package/src/models/confidential-message.ts +137 -0
  57. package/src/models/confidential-storage.ts +170 -0
  58. package/src/models/consent-rule.ts +141 -0
  59. package/src/models/crypto.ts +43 -0
  60. package/src/models/device-license.ts +161 -0
  61. package/src/models/did.ts +81 -0
  62. package/src/models/index.ts +31 -0
  63. package/src/models/indexing.ts +20 -0
  64. package/src/models/issue.ts +85 -0
  65. package/src/models/jsonapi.ts +19 -0
  66. package/src/models/jwe.ts +132 -0
  67. package/src/models/jwk.ts +50 -0
  68. package/src/models/jws.ts +42 -0
  69. package/src/models/jwt.ts +15 -0
  70. package/src/models/multibase58.ts +46 -0
  71. package/src/models/oidc4ida.common.model.ts +39 -0
  72. package/src/models/oidc4ida.document.model.ts +61 -0
  73. package/src/models/oidc4ida.electronicRecord.model.ts +86 -0
  74. package/src/models/oidc4ida.evidence.model.ts +69 -0
  75. package/src/models/openid-device.ts +146 -0
  76. package/src/models/operation-outcome.ts +34 -0
  77. package/src/models/params.ts +142 -0
  78. package/src/models/resource-document.ts +21 -0
  79. package/src/models/response.ts +5 -0
  80. package/src/models/urlPath.ts +76 -0
  81. package/src/models/verifiable-credential.ts +52 -0
  82. package/src/types/noble-hashes.d.ts +4 -0
  83. package/src/utils/actor.ts +52 -0
  84. package/src/utils/base-convert.ts +77 -0
  85. package/src/utils/baseN.ts +203 -0
  86. package/src/utils/bundle.ts +30 -0
  87. package/src/utils/content.ts +66 -0
  88. package/src/utils/did.ts +155 -0
  89. package/src/utils/format-converter.ts +119 -0
  90. package/src/utils/index.ts +13 -0
  91. package/src/utils/jwt.ts +165 -0
  92. package/src/utils/manager-error.ts +27 -0
  93. package/src/utils/multibase58.ts +46 -0
  94. package/src/utils/multibasehash.ts +28 -0
  95. package/src/utils/normalize.ts +43 -0
  96. package/src/utils/object-convert.ts +57 -0
  97. package/src/utils/string-convert.ts +71 -0
  98. package/src/utils/string-utils.ts +70 -0
  99. package/src/utils/url.ts +46 -0
  100. package/tsconfig.json +13 -0
@@ -0,0 +1,193 @@
1
+ // Copyright 2025 Antifraud Services Inc. under the Apache License, Version 2.0.
2
+ // File: src/models/schemaorg.ts
3
+
4
+ import { ParameterData } from "../models/params";
5
+
6
+ export enum ClaimsServiceSchemaorg {
7
+ category = "org.schema.Service.category",
8
+ identifier = "org.schema.Service.identifier",
9
+ serviceType = "org.schema.Service.serviceType",
10
+ termsOfService = "org.schema.Service.termsOfService",
11
+ }
12
+
13
+ /**
14
+ * Defines the canonical claim names for the 'org.schema' context,
15
+ * based on Schema.org vocabulary.
16
+ */
17
+ export enum ClaimsOrganizationSchemaorg {
18
+ /** ISO 3166-1 alpha-2 (two-letter country code). The jurisdiction could be the country or the region (county, province or state) */
19
+ addressCountry = "org.schema.Organization.address.addressCountry",
20
+ /** ISO 3166-2 code for administrative divisions. The jurisdiction could be the country or the region (county, province or state) */
21
+ addressRegion = "org.schema.Organization.address.addressRegion",
22
+ addressLocality = "org.schema.Organization.address.addressLocality",
23
+ postalCode = "org.schema.Organization.address.postalCode",
24
+ streetAddress = "org.schema.Organization.address.streetAddress",
25
+ /** `TAX` ID or `EI` (Employer ID): @see http://terminology.hl7.org/CodeSystem/v2-0203 */
26
+ identifierType = "org.schema.Organization.identifier.additionalType",
27
+ identifierValue = "org.schema.Organization.identifier.value",
28
+ /** Legal registered name */
29
+ legalName = "org.schema.Organization.legalName",
30
+ /** Commercial name */
31
+ name = "org.schema.Organization.name",
32
+ /** short url-friendly name (0-9,a-z) */
33
+ alternateName = "org.schema.Organization.alternateName",
34
+ /** External URL for the service */
35
+ url = "org.schema.Organization.url",
36
+ /** The identifier is a URN generated using the legal ID (TAX or EI) */
37
+ identifier = "org.schema.Organization.identifier",
38
+ /** DUNS (free) or LEI could be provided */
39
+ duns = "org.schema.Organization.duns",
40
+ /** Public contact email */
41
+ email = "org.schema.Organization.email",
42
+ /** Public contact phone */
43
+ telephone = "org.schema.Organization.telephone",
44
+ numberOfEmployees = "org.schema.Organization.numberOfEmployees.value" // to purchase licenses for device profile's activation
45
+ }
46
+
47
+ export enum ClaimsOfferSchemaorg {
48
+ acceptedPaymentMethod = "org.schema.Offer.acceptedPaymentMethod",
49
+ category = "org.schema.Offer.category",
50
+ checkoutPageURLTemplate = "org.schema.Offer.checkoutPageURLTemplate",
51
+ eligibleCustomerType = "org.schema.Offer.eligibleCustomerType",
52
+ eligibleQuantityValue = "org.schema.Offer.eligibleQuantity.value",
53
+ identifier = "org.schema.Offer.identifier",
54
+ itemOfferedName = "org.schema.Offer.itemOffered.name",
55
+ itemOfferedSku = "org.schema.Offer.itemOffered.sku",
56
+ offeredBy = "org.schema.Offer.offeredBy",
57
+ price = "org.schema.Offer.price",
58
+ priceCurrency = "org.schema.Offer.priceCurrency",
59
+ serialNumber = "org.schema.Offer.serialNumber",
60
+ }
61
+
62
+ /** For Employees (and Employee Role, but no PII) and customers / related persons.
63
+ * - `givenName`: The given name of the person.
64
+ * - `familyName`: The primary family name or surname of the person.
65
+ * - `alternateName`: The second surname or mother's family name, used for facilitating searches
66
+ * and catering to cultures with multiple surnames.
67
+ * - `name`: The transliterated full name of the person, useful for standardized naming
68
+ * conventions and international contexts.
69
+ */
70
+ export enum ClaimsPersonSchemaorg {
71
+ /** Second surname or mother's maiden name */
72
+ additionalName = "org.schema.Person.additionalName",
73
+ /** Short friendly name */
74
+ alternateName = "org.schema.Person.alternateName",
75
+ birthDate = "org.schema.Person.birthDate",
76
+ email = "org.schema.Person.email",
77
+ familyName = "org.schema.Person.familyName",
78
+ gender = "org.schema.Person.gender",
79
+ givenName = "org.schema.Person.givenName",
80
+ hasOccupation = "org.schema.Person.hasOccupation",
81
+ identifier = "org.schema.Person.identifier", // the URN (composed by the provider)
82
+ identifierType = "org.schema.Person.identifier.additionalType", // retrieved from a form
83
+ identifierValue = "org.schema.Person.identifier.value", // retrieved from a form
84
+ /** ICAO transliteration of official given name (including middlenames), family name and addtional surname */
85
+ name = "org.schema.Person.name",
86
+ memberOf = "org.schema.Person.memberOf", // for employees
87
+ telephone = "org.schema.Person.telephone",
88
+ worksFor = "org.schema.Person.worksFor", // for employees
89
+ /*
90
+ gender = 'org.schema.Person.gender',
91
+ birthDate = 'org.schema.Person.birthdate', // Date: Date of birth.
92
+ birthPlace = 'org.schema.Person.birthplace', // Place: The place where the person was born.
93
+ nationality = 'org.schema.Person.nationality', // Country: Nationality of the person.
94
+ height = 'org.schema.Person.height',
95
+ // Properties from Thing
96
+ additionalType = 'org.schema.Person.additionaltype', // e.g.: 'Employee'
97
+ */
98
+ }
99
+
100
+ /**
101
+ * Defines the flat claim structure for a schema.org/Action.
102
+ * This is used for requests where an entity (agent) performs an action,
103
+ * often with a human controller (participant) initiating it.
104
+ */
105
+ export enum ClaimsActionSchemaorg {
106
+ // The primary agent performing the action (e.g., the Tenant Organization)
107
+ agentIdentifier = 'org.schema.Action.agent.identifier',
108
+ agentLegalName = 'org.schema.Action.agent.legalName',
109
+ // ... other flattened properties of the agent ...
110
+
111
+ // A co-agent participating in the action (e.g., the Human Controller T)
112
+ participantIdentifier = 'org.schema.Action.participant.identifier',
113
+
114
+ // The service provider or target of the action (e.g., the Fabric Network)
115
+ providerIdentifier = 'org.schema.Action.provider.identifier',
116
+ providerName = 'org.schema.Action.provider.name',
117
+
118
+ // The time the action was initiated
119
+ startTime = 'org.schema.Action.startTime',
120
+ }
121
+
122
+ export const ICAOReverseDns = 'int.icao';
123
+ export enum ICAOIdentityParams {
124
+ HairColor = 'int.icao.mrtd.hair-color',
125
+ }
126
+
127
+ export const indexedPersonAttributeList: string[] = [
128
+ ClaimsPersonSchemaorg.givenName,
129
+ ClaimsPersonSchemaorg.familyName,
130
+ ClaimsPersonSchemaorg.additionalName,
131
+ ClaimsPersonSchemaorg.email,
132
+ ClaimsPersonSchemaorg.telephone,
133
+ ClaimsPersonSchemaorg.birthDate,
134
+ ClaimsPersonSchemaorg.identifierType,
135
+ ClaimsPersonSchemaorg.identifierValue,
136
+ // ClaimsPersonSchemaorg.additionalType,
137
+ ];
138
+
139
+ export const fullPersonParamsSchemaorg: ParameterData[] = [
140
+ {
141
+ name: ClaimsPersonSchemaorg.additionalName,
142
+ type: 'string',
143
+ value: undefined,
144
+ unique: true,
145
+ },
146
+ {
147
+ name: ClaimsPersonSchemaorg.familyName,
148
+ type: 'string',
149
+ value: undefined,
150
+ unique: true,
151
+ },
152
+ { name: ClaimsPersonSchemaorg.email, type: 'string', value: undefined },
153
+ {
154
+ name: ClaimsPersonSchemaorg.givenName,
155
+ type: 'string',
156
+ value: undefined,
157
+ },
158
+ {
159
+ name: ClaimsPersonSchemaorg.telephone,
160
+ type: 'string',
161
+ value: undefined,
162
+ },
163
+ {
164
+ name: ClaimsPersonSchemaorg.gender,
165
+ type: 'string',
166
+ value: undefined,
167
+ unique: true,
168
+ },
169
+ {
170
+ name: ClaimsPersonSchemaorg.identifierType,
171
+ type: 'string',
172
+ value: undefined,
173
+ },
174
+ {
175
+ name: ClaimsPersonSchemaorg.identifierValue,
176
+ type: 'string',
177
+ value: undefined,
178
+ },
179
+ {
180
+ name: ClaimsPersonSchemaorg.birthDate,
181
+ type: 'string',
182
+ value: undefined,
183
+ unique: true,
184
+ },
185
+ /*
186
+ {
187
+ name: ClaimsPersonSchemaorg.additionalType,
188
+ type: 'string',
189
+ value: undefined,
190
+ },
191
+ */
192
+ ];
193
+
@@ -0,0 +1,104 @@
1
+ // Copyright 2025 Antifraud Services Inc. under the Apache License, Version 2.0.
2
+ // File: crypto-ts/cryptoEncode.ts
3
+
4
+ // Function to encode a payload into a JWT with the header "alg=none"
5
+ // senderTenant signs and encrypts to recipient(s)
6
+ export function encodeJWT(senderKeysSet: any[], payload: any, recipientsEncKey: any[], header: any): string {
7
+ try {
8
+ // 1. Convert the header to JSON and then Base64Url encode it
9
+ const encodedHeader = base64UrlEncode(JSON.stringify(header));
10
+
11
+ // 2. Convert the payload to JSON and then Base64Url encode it
12
+ const encodedPayload = base64UrlEncode(JSON.stringify(payload));
13
+
14
+ // 3. No signature for `alg=none`, so we just return the concatenation of header and payload
15
+ // Format: `header.payload.` (no signature part)
16
+ const jwt = `${encodedHeader}.${encodedPayload}.`;
17
+
18
+ return jwt;
19
+ } catch (error) {
20
+ console.error('Error encoding JWT:', error);
21
+ return '';
22
+ }
23
+ }
24
+
25
+ // Helper function to Base64Url encode a string (works for header and payload)
26
+ function base64UrlEncode(str: string): string {
27
+ // Convert the string to a Base64 string (using standard Base64 encoding first)
28
+ const base64 = Buffer.from(str).toString('base64');
29
+
30
+ // Replace '+' with '-', '/' with '_', and remove the padding '='
31
+ return base64
32
+ .replace(/\+/g, '-') // Replace '+' with '-'
33
+ .replace(/\//g, '_') // Replace '/' with '_'
34
+ .replace(/=+$/, ''); // Remove any '=' padding at the end
35
+ }
36
+
37
+ // src/managers/cryptoDecode.ts
38
+
39
+ // TODO: decode, verify, encode, sign, encrypt, decrypt, all of them must be in the wallet
40
+ // Note: each tenant can have their own wallet.
41
+ // Function to decode JWT and handle Base64Url using native JavaScript functions
42
+ export function decodePayloadRequest(targetTenant: string, requestJAR: string | undefined, authorizationHeader: string | undefined): any {
43
+ try {
44
+ let authToken: string | undefined;
45
+ // TODO: auth token could be protected in the request: payload.body.meta.http.header.bearer.source
46
+ // TODO: this function will decode the bearer (auth) token and set it here: payload.body.meta.http.header.bearer.decoded
47
+ // TODO: first of all the request must be decrypted in case of JWE, then the nested JWT is decoded
48
+ // If not in the JAR, look for auth token in the Authorization header (Bearer token)
49
+ if (authorizationHeader) {
50
+ authToken = authorizationHeader.replace('Bearer ', '').trim();
51
+ }
52
+
53
+ // If the token is not found, return an error
54
+ if (!authToken) {
55
+ throw new Error('No JWT found in request or Authorization header');
56
+ }
57
+
58
+ // Decode the JWT (Base64Url format as per the JOSE specification)
59
+ const [header, payload, signature] = authToken.split('.');
60
+
61
+ if (!payload) {
62
+ throw new Error('JWT payload is missing');
63
+ }
64
+ const decodedPayload = decodeBase64Url(payload);
65
+
66
+ // Return the decoded payload that contains the body and data
67
+ return decodedPayload;
68
+ } catch (error) {
69
+ console.error('Error decoding JWT payload:', error);
70
+ return null;
71
+ }
72
+ }
73
+
74
+ export function decodeBase64Url(base64Url: string): string {
75
+ try {
76
+ // Convert Base64Url to Base64 by replacing '-' with '+' and '_' with '/'
77
+ let base64 = base64Url
78
+ .replace(/-/g, '+') // Replace '-' with '+'
79
+ .replace(/_/g, '/'); // Replace '_' with '/'
80
+
81
+ // Ensure that Base64 has the correct size (padding)
82
+ const padding = base64.length % 4;
83
+ if (padding) {
84
+ base64 += '='.repeat(4 - padding); // Add the necessary padding
85
+ }
86
+
87
+ // Decode the Base64 string using Buffer (for Node.js)
88
+ const decodedString = Buffer.from(base64, 'base64').toString('utf-8');
89
+
90
+ // Check if decoding results in a valid JSON string
91
+ try {
92
+ JSON.parse(decodedString); // Ensure it's valid JSON
93
+ } catch (e) {
94
+ console.error('Invalid Base64Url string:', e);
95
+ return ''; // Return empty string for invalid JSON payload
96
+ }
97
+
98
+ return decodedString;
99
+ } catch (error) {
100
+ console.error('Error decoding Base64Url string:', error);
101
+ return ''; // Return empty string if there's an error during decoding
102
+ }
103
+ }
104
+
@@ -0,0 +1,36 @@
1
+ // Copyright 2025 Antifraud Services Inc. under the Apache License, Version 2.0.
2
+ // File: crypto-ts/cryptoEncode.ts
3
+
4
+ // Function to encode a payload into a JWT with the header "alg=none"
5
+ // senderTenant signs and encrypts to recipient(s)
6
+ export function encodeJWT(senderKeysSet: any[], payload: any, recipientsEncKey: any[], header: any): string {
7
+ try {
8
+ // 1. Convert the header to JSON and then Base64Url encode it
9
+ const encodedHeader = base64UrlEncode(JSON.stringify(header));
10
+
11
+ // 2. Convert the payload to JSON and then Base64Url encode it
12
+ const encodedPayload = base64UrlEncode(JSON.stringify(payload));
13
+
14
+ // 3. No signature for `alg=none`, so we just return the concatenation of header and payload
15
+ // Format: `header.payload.` (no signature part)
16
+ const jwt = `${encodedHeader}.${encodedPayload}.`;
17
+
18
+ return jwt;
19
+ } catch (error) {
20
+ console.error('Error encoding JWT:', error);
21
+ return '';
22
+ }
23
+ }
24
+
25
+ // Helper function to Base64Url encode a string (works for header and payload)
26
+ function base64UrlEncode(str: string): string {
27
+ // Convert the string to a Base64 string (using standard Base64 encoding first)
28
+ const base64 = Buffer.from(str).toString('base64');
29
+
30
+ // Replace '+' with '-', '/' with '_', and remove the padding '='
31
+ return base64
32
+ .replace(/\+/g, '-') // Replace '+' with '-'
33
+ .replace(/\//g, '_') // Replace '/' with '_'
34
+ .replace(/=+$/, ''); // Remove any '=' padding at the end
35
+ }
36
+
@@ -0,0 +1,29 @@
1
+ // Copyright 2025 Antifraud Services Inc. under the Apache License, Version 2.0.
2
+ // File: crypto-ts/cryptography.abstract.ts
3
+
4
+ export abstract class CryptographyManagerAbstract {
5
+ protected publicJWK = {};
6
+ protected privateKeyBytes!: Uint8Array;
7
+
8
+ constructor() {
9
+ }
10
+
11
+ /** Initializes public and private keys. */
12
+ protected abstract newKeys(seedBytes?: Uint8Array): Promise<void>;
13
+
14
+ /** Sets the public and private keys to be used. */
15
+ protected setKeys(publicJWK: any, privateKeyBytes: Uint8Array): void {
16
+ this.publicJWK = publicJWK;
17
+ this.privateKeyBytes = privateKeyBytes;
18
+ }
19
+
20
+ /** Returns the public JWK */
21
+ public getPublicJWK(): any {
22
+ return this.publicJWK;
23
+ }
24
+
25
+ /** Returns the public Key ID ('kid') or empty string */
26
+ public getKeyID(): string {
27
+ return this.getPublicJWK().kid ? this.getPublicJWK().kid : '';
28
+ }
29
+ }
package/src/hmac.ts ADDED
@@ -0,0 +1,15 @@
1
+ // Copyright 2025 Antifraud Services Inc. under the Apache License, Version 2.0.
2
+ // File: crypto-ts/hmac.ts
3
+
4
+ // Use explicit .js subpaths to satisfy package exports in Metro/Node ESM.
5
+ import { hmac } from '@noble/hashes/hmac.js';
6
+ import { sha3_256 } from '@noble/hashes/sha3.js';
7
+ import { Content } from './utils/content';
8
+
9
+ export async function computeHmacSha256(plaintext: string, hmacKeyBytes: Uint8Array): Promise<Uint8Array> {
10
+ return await hmac(sha3_256, hmacKeyBytes, Content.stringToBytesUTF8(plaintext));
11
+ }
12
+
13
+ export async function computeHmacSha256Base64Url(plaintext: string, hmacKeyBytes: Uint8Array): Promise<string> {
14
+ return Content.bytesToRawBase64UrlSafe(await computeHmacSha256(plaintext, hmacKeyBytes));
15
+ }
package/src/index.ts ADDED
@@ -0,0 +1,3 @@
1
+ export * from './AesManager';
2
+ export * from './CryptographyService';
3
+ export * from './hmac';
@@ -0,0 +1,131 @@
1
+ // Copyright 2025 Antifraud Services Inc. under the Apache License, Version 2.0.
2
+ // File: crypto-ts/interfaces/Cryptography.types.ts
3
+
4
+ /**
5
+ * JWK shapes and RFC 7638 thumbprints for ML-KEM and ML-DSA.
6
+ *
7
+ * References (normative)
8
+ * @see https://www.rfc-editor.org/rfc/rfc7638 // JWK Thumbprint
9
+ * @see https://www.rfc-editor.org/rfc/rfc7517 // JWK
10
+ * @see https://www.rfc-editor.org/rfc/rfc7515#appendix-C // base64url (no padding)
11
+ * @see https://www.rfc-editor.org/rfc/rfc8037 // OKP key type
12
+ * @see https://www.rfc-editor.org/rfc/rfc9278 // JWK Thumbprint URI
13
+ *
14
+ * Post-quantum mappings
15
+ * @see https://datatracker.ietf.org/doc/draft-ietf-jose-pqc-kem/ // JOSE PQ KEM
16
+ * @see https://datatracker.ietf.org/doc/draft-ietf-cose-dilithium/ // ML-DSA for JOSE/COSE (datatracker)
17
+ * @see https://cose-wg.github.io/draft-ietf-cose-dilithium/draft-ietf-cose-dilithium.html // ML-DSA (GitHub pages)
18
+ *
19
+ * NIST algorithm specs
20
+ * @see https://csrc.nist.gov/pubs/fips/203/final // FIPS 203 ML-KEM (landing)
21
+ * @see https://nvlpubs.nist.gov/nistpubs/fips/nist.fips.203.pdf // FIPS 203 PDF
22
+ * @see https://csrc.nist.gov/pubs/fips/204/final // FIPS 204 ML-DSA (landing)
23
+ * @see https://nvlpubs.nist.gov/nistpubs/fips/nist.fips.204.pdf // FIPS 204 PDF
24
+ */
25
+
26
+ export type CurveMlKem512 = "ML-KEM-512";
27
+ export type CurveMlKem768 = "ML-KEM-768";
28
+ export type CurveMlKem1024 = "ML-KEM-1024";
29
+
30
+ export type MlkemCurve = CurveMlKem512 | CurveMlKem768 | CurveMlKem1024;
31
+
32
+ export type AlgMlDsa2 = "ML-DSA-44";
33
+ export type AlgMlDsa3 = "ML-DSA-65";
34
+ export type AlgMlDsa5 ="ML-DSA-87";
35
+
36
+ export type MldsaAlg = AlgMlDsa2 | AlgMlDsa3 | AlgMlDsa5;
37
+
38
+ // Base JWKs used for RFC 7638 thumbprint calculation
39
+ export type MlkemBaseJwk = { kty: "OKP"; crv: MlkemCurve; x: string };
40
+ export type MldsaBaseJwk = { kty: "AKP"; alg: MldsaAlg; pub: string };
41
+ export type EcBaseJwk = { kty: "EC"; crv: string; x: string; y: string };
42
+ export type BaseJwk = MlkemBaseJwk | MldsaBaseJwk | EcBaseJwk;
43
+
44
+ export interface MlkemPublicJwk extends MlkemBaseJwk {
45
+ kid?: string; // filled from thumbprint
46
+ };
47
+
48
+ export interface MldsaPublicJwk extends MldsaBaseJwk {
49
+ kid?: string; // filled from thumbprint
50
+ };
51
+
52
+ /**
53
+ * Represents a public key for classic cryptography algorithms like Elliptic Curve.
54
+ */
55
+ export interface ClassicPublicJwk {
56
+ kty: "EC";
57
+ crv: string; // e.g., "P-256"
58
+ x: string;
59
+ y: string;
60
+ kid?: string;
61
+ alg?: string;
62
+ use?: string;
63
+ };
64
+
65
+ /**
66
+ * Represents a public key in JWK format, suitable for public documents like DIDs.
67
+ * This is a union of all supported public key types, both Post-Quantum and classic.
68
+ */
69
+ export type PublicJwk = MlkemPublicJwk | MldsaPublicJwk | ClassicPublicJwk;
70
+
71
+ export interface MlkemPrivateJwk extends MlkemPublicJwk{
72
+ // Private material (extended seed) must never be published:
73
+ dBytes: Uint8Array;
74
+ };
75
+
76
+ export interface MldsaPrivateJwk extends MldsaPublicJwk{
77
+ // Private material (extended seed) must never be published:
78
+ privBytes: Uint8Array;
79
+ };
80
+
81
+ export interface RecipientInfo {
82
+ tenantId: string;
83
+ header?: Record<string, any>;
84
+ }
85
+
86
+ export interface SignerInfo {
87
+ tenantId: string;
88
+ protectedHeader: Record<string, any>;
89
+ unprotectedHeader?: Record<string, any>;
90
+ }
91
+
92
+ export interface ProtectRequest {
93
+ stream: Uint8Array;
94
+ recipients: RecipientInfo[];
95
+ protectedHeader?: Record<string, any>; // is it meta.jws.protected?
96
+ unprotectedHeader?: Record<string, any>; // is it meta.jws.unprotected?
97
+ aad?: Uint8Array;// src/adapters/queue.ts
98
+ input: Record<string, any>;
99
+ meta?: {
100
+ jws?: { protected?: Record<string, any>; unprotected?: Record<string, any>;}; // protected and unprotected headers
101
+ jwe?: { header?: Record<string, any>; }; // public unencypted header from the JWE
102
+ bearer?: { jwt: { header?: Record<string, any>; payload?: Record<string, any>; } }
103
+ };
104
+ }
105
+
106
+ export interface JWEData {
107
+ protected?: string;
108
+ unprotected?: Record<string, any>;
109
+ recipients: Array<{
110
+ header?: Record<string, any>;
111
+ encrypted_key?: string;
112
+ }>;
113
+ aad?: string;
114
+ iv: string;
115
+ ciphertext: string;
116
+ tag: string;
117
+ }
118
+
119
+ export interface SignRequest {
120
+ payload: Uint8Array;
121
+ signers: SignerInfo[];
122
+ }
123
+
124
+ export interface JwsObject {
125
+ payload: string;
126
+ signatures: Array<{
127
+ protected: string;
128
+ unprotected?: Record<string, any>;
129
+ signature: string;
130
+ }>;
131
+ }
@@ -0,0 +1,33 @@
1
+ // Copyright 2025 Antifraud Services Inc. under the Apache License, Version 2.0.
2
+ // File: crypto-ts/interfaces/ICryptoHelper.ts
3
+
4
+ /**
5
+ * @interface ICryptoHelper
6
+ * Defines the contract for platform-specific cryptographic primitives.
7
+ * This is the "port" in a hexagonal architecture, allowing the agnostic
8
+ * core (CryptographyService) to be "plugged into" any runtime environment
9
+ * (like Expo, Node, or Web) without depending on its implementation details.
10
+ */
11
+ export interface ICryptoHelper {
12
+ /**
13
+ * Generates a specified number of cryptographically secure random bytes.
14
+ * @param byteCount The number of bytes to generate.
15
+ * @returns A Promise that resolves to a Uint8Array with the random bytes.
16
+ */
17
+ getRandomBytes(byteCount: number): Promise<Uint8Array>;
18
+
19
+ /**
20
+ * Computes the cryptographic digest of a string using a specified algorithm.
21
+ * The implementation is responsible for validating the algorithm string.
22
+ * @param data The string to hash.
23
+ * @param algorithm The hash algorithm to use (e.g., 'SHA-256', 'SHA-512').
24
+ * @returns A Promise that resolves to the digest as a hex string.
25
+ */
26
+ digestString(data: string, algorithm: any): Promise<string>;
27
+
28
+ /**
29
+ * Generates a platform-specific, cryptographically secure UUID v4.
30
+ * @returns A string representation of the UUID.
31
+ */
32
+ randomUUID(): string;
33
+ }