@sd-jwt/core 0.20.1 → 0.21.0-alpha-20260916100413

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 (68) hide show
  1. package/LICENSE +2 -2
  2. package/README.md +82 -80
  3. package/dist/index.cjs +1526 -0
  4. package/dist/index.cjs.map +1 -0
  5. package/dist/index.d.cts +696 -0
  6. package/dist/index.d.mts +537 -527
  7. package/dist/index.mjs +1422 -1998
  8. package/dist/index.mjs.map +1 -0
  9. package/package.json +29 -49
  10. package/CHANGELOG.md +0 -39
  11. package/dist/index.d.ts +0 -686
  12. package/dist/index.js +0 -2100
  13. package/src/decode/decode.ts +0 -407
  14. package/src/decode/index.ts +0 -1
  15. package/src/decoy.ts +0 -15
  16. package/src/flattenJSON.ts +0 -99
  17. package/src/generalJSON.ts +0 -157
  18. package/src/index.ts +0 -1000
  19. package/src/jwt.ts +0 -286
  20. package/src/kbjwt.ts +0 -101
  21. package/src/present/index.ts +0 -1
  22. package/src/present/present.ts +0 -216
  23. package/src/sdjwt.ts +0 -384
  24. package/src/test/decode/decode.spec.ts +0 -197
  25. package/src/test/decoy.spec.ts +0 -30
  26. package/src/test/flattenJSON.spec.ts +0 -122
  27. package/src/test/generalJSON.spec.ts +0 -198
  28. package/src/test/index.spec.ts +0 -986
  29. package/src/test/jwt.spec.ts +0 -301
  30. package/src/test/kbjwt.spec.ts +0 -555
  31. package/src/test/pass.spec.ts +0 -7
  32. package/src/test/present/present.spec.ts +0 -305
  33. package/src/test/sdjwt.spec.ts +0 -384
  34. package/src/test/types/type.spec.ts +0 -88
  35. package/src/test/utils/base64url.spec.ts +0 -33
  36. package/src/test/utils/disclosure.spec.ts +0 -170
  37. package/src/test/utils/error.spec.ts +0 -15
  38. package/src/types/index.ts +0 -2
  39. package/src/types/type.ts +0 -270
  40. package/src/types/verification-error.ts +0 -55
  41. package/src/utils/base64url.ts +0 -6
  42. package/src/utils/disclosure.ts +0 -121
  43. package/src/utils/error.ts +0 -25
  44. package/src/utils/index.ts +0 -3
  45. package/src/utils/strict-json.ts +0 -17
  46. package/test/app-e2e.spec.ts +0 -292
  47. package/test/array_data_types.json +0 -31
  48. package/test/array_full_sd.json +0 -21
  49. package/test/array_in_sd.json +0 -13
  50. package/test/array_nested_in_plain.json +0 -29
  51. package/test/array_none_disclosed.json +0 -17
  52. package/test/array_of_nulls.json +0 -15
  53. package/test/array_of_objects.json +0 -65
  54. package/test/array_of_scalars.json +0 -19
  55. package/test/array_recursive_sd.json +0 -35
  56. package/test/array_recursive_sd_some_disclosed.json +0 -63
  57. package/test/complex.json +0 -43
  58. package/test/header_mod.json +0 -48
  59. package/test/json_serialization.json +0 -48
  60. package/test/key_binding.json +0 -48
  61. package/test/no_sd.json +0 -36
  62. package/test/object_data_types.json +0 -62
  63. package/test/recursions.json +0 -117
  64. package/test/rfc9901-audit-fixes.spec.ts +0 -252
  65. package/test/rfc9901-validation.spec.ts +0 -150
  66. package/test/tsconfig.json +0 -4
  67. package/tsconfig.json +0 -7
  68. package/vitest.config.mts +0 -4
package/src/index.ts DELETED
@@ -1,1000 +0,0 @@
1
- import { getSDAlgAndPayload } from './decode';
2
- import { FlattenJSON } from './flattenJSON';
3
- import { GeneralJSON } from './generalJSON';
4
- import { Jwt, type VerifierOptions, validateJwtPayload } from './jwt';
5
- import { KBJwt } from './kbjwt';
6
- import { pack, SDJwt } from './sdjwt';
7
- import {
8
- DEFAULT_SECURE_HASH_ALGORITHMS,
9
- type DisclosureFrame,
10
- type Hasher,
11
- IANA_HASH_ALGORITHMS,
12
- KB_JWT_TYP,
13
- type KBOptions,
14
- type PresentationFrame,
15
- type SafeVerifyResult,
16
- SD_DECOY,
17
- SD_DIGEST,
18
- SD_LIST_KEY,
19
- type SDJWTCompact,
20
- type SDJWTConfig,
21
- type Signer,
22
- type VerificationError,
23
- type VerificationErrorCode,
24
- } from './types';
25
- import {
26
- base64urlEncode,
27
- ensureError,
28
- SDJWTException,
29
- uint8ArrayToBase64Url,
30
- } from './utils';
31
- import { decodeBase64urlJsonStrict } from './utils/strict-json';
32
-
33
- export * from './decode';
34
- export * from './decoy';
35
- export * from './flattenJSON';
36
- export * from './generalJSON';
37
- export * from './jwt';
38
- export * from './kbjwt';
39
- export * from './present';
40
- export * from './sdjwt';
41
- // Re-export all types, utils, decode, and present functionality
42
- export * from './types';
43
- export * from './utils';
44
-
45
- export type SdJwtPayload = Record<string, unknown>;
46
-
47
- /**
48
- * Internal utility function to validate that a payload does not contain reserved field names.
49
- */
50
- function validateReservedFieldsInternal(
51
- payload: Record<string, unknown>,
52
- ): void {
53
- const reservedFields = new Set([SD_DIGEST, '_sd_alg', SD_DECOY, SD_LIST_KEY]);
54
-
55
- const visit = (node: unknown) => {
56
- if (!node || typeof node !== 'object') {
57
- return;
58
- }
59
-
60
- for (const [key, value] of Object.entries(
61
- node as Record<string, unknown>,
62
- )) {
63
- if (reservedFields.has(key)) {
64
- throw new SDJWTException(`Reserved field name "${key}" is not allowed`);
65
- }
66
- visit(value);
67
- }
68
- };
69
-
70
- visit(payload);
71
- }
72
-
73
- export class SDJwtInstance<ExtendedPayload extends SdJwtPayload, T = unknown> {
74
- //header type
75
- protected type?: string;
76
-
77
- public static readonly DEFAULT_hashAlg = 'sha-256';
78
-
79
- protected userConfig: SDJWTConfig<T> = {};
80
-
81
- constructor(userConfig?: SDJWTConfig<T>) {
82
- if (userConfig) {
83
- if (
84
- userConfig.hashAlg &&
85
- !IANA_HASH_ALGORITHMS.includes(userConfig.hashAlg)
86
- ) {
87
- throw new SDJWTException(
88
- `Invalid hash algorithm: ${userConfig.hashAlg}`,
89
- );
90
- }
91
- const allowedDisclosureHashAlgorithms =
92
- userConfig.allowedDisclosureHashAlgorithms ??
93
- DEFAULT_SECURE_HASH_ALGORITHMS;
94
- if (
95
- userConfig.hashAlg &&
96
- !allowedDisclosureHashAlgorithms.includes(userConfig.hashAlg)
97
- ) {
98
- throw new SDJWTException(
99
- `Disallowed hash algorithm: ${userConfig.hashAlg}`,
100
- );
101
- }
102
- this.userConfig = userConfig;
103
- }
104
- }
105
-
106
- private async createKBJwt(
107
- options: KBOptions,
108
- sdHash: string,
109
- ): Promise<KBJwt> {
110
- if (!this.userConfig.kbSigner) {
111
- throw new SDJWTException('Key Binding Signer not found');
112
- }
113
- if (!this.userConfig.kbSignAlg) {
114
- throw new SDJWTException('Key Binding sign algorithm not specified');
115
- }
116
-
117
- const { payload } = options;
118
- const kbJwt = new KBJwt({
119
- header: {
120
- typ: KB_JWT_TYP,
121
- alg: this.userConfig.kbSignAlg,
122
- },
123
- payload: { ...payload, sd_hash: sdHash },
124
- });
125
-
126
- await kbJwt.sign(this.userConfig.kbSigner);
127
- return kbJwt;
128
- }
129
-
130
- private async SignJwt(jwt: Jwt) {
131
- if (!this.userConfig.signer) {
132
- throw new SDJWTException('Signer not found');
133
- }
134
- await jwt.sign(this.userConfig.signer);
135
- return jwt;
136
- }
137
-
138
- private async VerifyJwt(jwt: Jwt, options?: T & VerifierOptions) {
139
- if (!this.userConfig.verifier) {
140
- throw new SDJWTException('Verifier not found');
141
- }
142
- return jwt.verify<T>(this.userConfig.verifier, options);
143
- }
144
-
145
- public async issue<Payload extends ExtendedPayload>(
146
- payload: Payload,
147
- disclosureFrame?: DisclosureFrame<Payload>,
148
- options?: {
149
- header?: object; // This is for customizing the header of the jwt
150
- },
151
- ): Promise<SDJWTCompact> {
152
- if (!this.userConfig.hasher) {
153
- throw new SDJWTException('Hasher not found');
154
- }
155
-
156
- if (!this.userConfig.saltGenerator) {
157
- throw new SDJWTException('SaltGenerator not found');
158
- }
159
-
160
- if (!this.userConfig.signAlg) {
161
- throw new SDJWTException('sign alogrithm not specified');
162
- }
163
- if (this.userConfig.signAlg === 'none') {
164
- throw new SDJWTException('sign algorithm "none" is not allowed');
165
- }
166
-
167
- this.validateReservedFields<Payload>(payload);
168
- this.validateDisclosureFrame<Payload>(disclosureFrame);
169
-
170
- const hasher = this.userConfig.hasher;
171
- const hashAlg = this.userConfig.hashAlg ?? SDJwtInstance.DEFAULT_hashAlg;
172
- const allowedDisclosureHashAlgorithms =
173
- this.userConfig.allowedDisclosureHashAlgorithms ??
174
- DEFAULT_SECURE_HASH_ALGORITHMS;
175
- if (!allowedDisclosureHashAlgorithms.includes(hashAlg)) {
176
- throw new SDJWTException(`Disallowed hash algorithm: ${hashAlg}`);
177
- }
178
-
179
- const { packedClaims, disclosures } = await pack(
180
- payload,
181
- disclosureFrame,
182
- { hasher, alg: hashAlg },
183
- this.userConfig.saltGenerator,
184
- );
185
- const alg = this.userConfig.signAlg;
186
- const OptionHeader = options?.header ?? {};
187
- const CustomHeader = this.userConfig.omitTyp
188
- ? OptionHeader
189
- : { typ: this.type, ...OptionHeader };
190
- const header = { ...CustomHeader, alg };
191
- const jwt = new Jwt({
192
- header,
193
- payload: {
194
- ...packedClaims,
195
- _sd_alg: disclosureFrame ? hashAlg : undefined,
196
- },
197
- });
198
- await this.SignJwt(jwt);
199
-
200
- const sdJwt = new SDJwt({
201
- jwt,
202
- disclosures,
203
- });
204
-
205
- return sdJwt.encodeSDJwt();
206
- }
207
-
208
- /**
209
- * Validates if the payload contains any reserved claim names. If so it will throw an error.
210
- * @param payload
211
- * @returns
212
- */
213
- protected validateReservedFields<T extends ExtendedPayload>(payload: T) {
214
- validateReservedFieldsInternal(payload as Record<string, unknown>);
215
- }
216
-
217
- protected validateDisclosureFrame<T extends ExtendedPayload>(
218
- _disclosureFrame?: DisclosureFrame<T>,
219
- ) {
220
- return;
221
- }
222
-
223
- public async present<T extends Record<string, unknown>>(
224
- encodedSDJwt: string,
225
- presentationFrame?: PresentationFrame<T>,
226
- options?: {
227
- kb?: KBOptions;
228
- },
229
- ): Promise<SDJWTCompact> {
230
- if (!this.userConfig.hasher) {
231
- throw new SDJWTException('Hasher not found');
232
- }
233
- const hasher = this.userConfig.hasher;
234
-
235
- const sdjwt = await SDJwt.fromEncode(encodedSDJwt, hasher);
236
- if (sdjwt.kbJwt) {
237
- throw new SDJWTException('Holder cannot present an SD-JWT with KB-JWT');
238
- }
239
-
240
- if (!sdjwt.jwt?.payload) throw new SDJWTException('Payload not found');
241
- const presentSdJwtWithoutKb = await sdjwt.present(
242
- presentationFrame,
243
- hasher,
244
- );
245
-
246
- if (!options?.kb) {
247
- return presentSdJwtWithoutKb;
248
- }
249
-
250
- const sdHashStr = await this.calculateSDHash(
251
- presentSdJwtWithoutKb,
252
- sdjwt,
253
- hasher,
254
- );
255
-
256
- sdjwt.kbJwt = await this.createKBJwt(options.kb, sdHashStr);
257
- return sdjwt.present(presentationFrame, hasher);
258
- }
259
-
260
- // This function is for verifying the SD JWT
261
- // If requiredClaimKeys is provided, it will check if the required claim keys are presentation in the SD JWT
262
- // If requireKeyBindings is true, it will check if the key binding JWT is presentation and verify it
263
- public async verify(encodedSDJwt: string, options?: T & VerifierOptions) {
264
- if (!this.userConfig.hasher) {
265
- throw new SDJWTException('Hasher not found');
266
- }
267
- const hasher = this.userConfig.hasher;
268
-
269
- const sdjwt = await SDJwt.fromEncode(encodedSDJwt, hasher);
270
- if (!sdjwt.jwt?.payload) {
271
- throw new SDJWTException('Invalid SD JWT');
272
- }
273
- const { payload, header } = await this.validate(encodedSDJwt, options);
274
-
275
- if (options?.requiredClaimKeys) {
276
- const keys = await sdjwt.keys(hasher);
277
- const missingKeys = options.requiredClaimKeys.filter(
278
- (k) => !keys.includes(k),
279
- );
280
- if (missingKeys.length > 0) {
281
- throw new SDJWTException(
282
- `Missing required claim keys: ${missingKeys.join(', ')}`,
283
- );
284
- }
285
- }
286
-
287
- if (!options?.keyBindingNonce) {
288
- return { payload, header };
289
- }
290
-
291
- if (!sdjwt.kbJwt) {
292
- throw new SDJWTException('Key Binding JWT not exist');
293
- }
294
- if (!this.userConfig.kbVerifier) {
295
- throw new SDJWTException('Key Binding Verifier not found');
296
- }
297
- const kb = await sdjwt.kbJwt.verifyKB({
298
- verifier: this.userConfig.kbVerifier,
299
- payload,
300
- nonce: options.keyBindingNonce,
301
- options,
302
- });
303
- if (!kb) {
304
- throw new Error('signature is not valid');
305
- }
306
-
307
- const sdHashfromKb = kb.payload.sd_hash;
308
- const sdjwtWithoutKb = new SDJwt({
309
- jwt: sdjwt.jwt,
310
- disclosures: sdjwt.disclosures,
311
- });
312
-
313
- const presentSdJwtWithoutKb = sdjwtWithoutKb.encodeSDJwt();
314
- const sdHashStr = await this.calculateSDHash(
315
- presentSdJwtWithoutKb,
316
- sdjwt,
317
- hasher,
318
- );
319
-
320
- if (sdHashStr !== sdHashfromKb) {
321
- throw new SDJWTException('Invalid sd_hash in Key Binding JWT');
322
- }
323
-
324
- return { payload, header, kb };
325
- }
326
-
327
- /**
328
- * Safe verification that collects all errors instead of failing fast.
329
- * Returns a result object with either the verified data or an array of all errors.
330
- *
331
- * @param encodedSDJwt - The encoded SD-JWT to verify
332
- * @param options - Verification options
333
- * @returns A SafeVerifyResult containing either success data or collected errors
334
- */
335
- public async safeVerify(
336
- encodedSDJwt: string,
337
- options?: T & VerifierOptions,
338
- ): Promise<
339
- SafeVerifyResult<{
340
- payload: ExtendedPayload;
341
- header: Record<string, unknown> | undefined;
342
- kb?: {
343
- payload: Record<string, unknown>;
344
- header: Record<string, unknown>;
345
- };
346
- }>
347
- > {
348
- const errors: VerificationError[] = [];
349
-
350
- // Helper to add errors
351
- const addError = (
352
- code: VerificationErrorCode,
353
- message: string,
354
- details?: unknown,
355
- ) => {
356
- errors.push({ code, message, details });
357
- };
358
-
359
- // Helper to convert exception to error code
360
- const exceptionToCode = (error: Error): VerificationErrorCode => {
361
- const message = error.message.toLowerCase();
362
- if (message.includes('hasher not found')) return 'HASHER_NOT_FOUND';
363
- if (message.includes('verifier not found')) return 'VERIFIER_NOT_FOUND';
364
- if (message.includes('invalid sd jwt') || message.includes('invalid jwt'))
365
- return 'INVALID_SD_JWT';
366
- if (message.includes('not yet valid')) return 'JWT_NOT_YET_VALID';
367
- if (message.includes('expired')) return 'JWT_EXPIRED';
368
- if (message.includes('signature')) return 'INVALID_JWT_SIGNATURE';
369
- if (message.includes('missing required claim'))
370
- return 'MISSING_REQUIRED_CLAIMS';
371
- if (message.includes('key binding jwt not exist'))
372
- return 'KEY_BINDING_JWT_MISSING';
373
- if (message.includes('key binding verifier not found'))
374
- return 'KEY_BINDING_VERIFIER_NOT_FOUND';
375
- if (message.includes('sd_hash')) return 'KEY_BINDING_SD_HASH_INVALID';
376
- return 'UNKNOWN_ERROR';
377
- };
378
-
379
- // Check basic configuration first
380
- if (!this.userConfig.hasher) {
381
- addError('HASHER_NOT_FOUND', 'Hasher not found');
382
- }
383
- if (!this.userConfig.verifier) {
384
- addError('VERIFIER_NOT_FOUND', 'Verifier not found');
385
- }
386
-
387
- // If basic config is missing, return early
388
- if (errors.length > 0) {
389
- return { success: false, errors };
390
- }
391
-
392
- if (!this.userConfig.hasher) {
393
- throw new SDJWTException('Hasher not found');
394
- }
395
-
396
- // hasher and verifier are guaranteed to be defined here
397
- const hasher = this.userConfig.hasher;
398
-
399
- // Try to decode and validate the SD-JWT
400
- let sdjwt: SDJwt | undefined;
401
- let payload: ExtendedPayload | undefined;
402
- let header: Record<string, unknown> | undefined;
403
-
404
- try {
405
- sdjwt = await SDJwt.fromEncode(encodedSDJwt, hasher);
406
- if (!sdjwt.jwt?.payload) {
407
- addError('INVALID_SD_JWT', 'Invalid SD JWT: missing JWT or payload');
408
- }
409
- } catch (e) {
410
- const error = ensureError(e);
411
- addError(
412
- 'INVALID_SD_JWT',
413
- `Failed to decode SD-JWT: ${error.message}`,
414
- error,
415
- );
416
- }
417
-
418
- // Validate signature and claims
419
- if (sdjwt?.jwt) {
420
- try {
421
- const result = await this.VerifyJwt(sdjwt.jwt, {
422
- ...options,
423
- skipJwtClaimValidation: true,
424
- } as T & VerifierOptions);
425
- header = result.header;
426
- const claims = await sdjwt.getClaims(hasher);
427
- payload = claims as ExtendedPayload;
428
- validateJwtPayload(payload, options);
429
- } catch (e) {
430
- const error = ensureError(e);
431
- const code = exceptionToCode(error);
432
- addError(code, error.message, error);
433
- }
434
- }
435
-
436
- // Check required claim keys
437
- if (sdjwt && options?.requiredClaimKeys) {
438
- try {
439
- const keys = await sdjwt.keys(hasher);
440
- const missingKeys = options.requiredClaimKeys.filter(
441
- (k) => !keys.includes(k),
442
- );
443
- if (missingKeys.length > 0) {
444
- addError(
445
- 'MISSING_REQUIRED_CLAIMS',
446
- `Missing required claim keys: ${missingKeys.join(', ')}`,
447
- { missingKeys },
448
- );
449
- }
450
- } catch (e) {
451
- const error = ensureError(e);
452
- addError(
453
- 'UNKNOWN_ERROR',
454
- `Failed to check required claims: ${error.message}`,
455
- error,
456
- );
457
- }
458
- }
459
-
460
- // Verify key binding if requested
461
- let kb:
462
- | { payload: Record<string, unknown>; header: Record<string, unknown> }
463
- | undefined;
464
- if (options?.keyBindingNonce && sdjwt) {
465
- if (!sdjwt.kbJwt) {
466
- addError('KEY_BINDING_JWT_MISSING', 'Key Binding JWT not exist');
467
- } else if (!this.userConfig.kbVerifier) {
468
- addError(
469
- 'KEY_BINDING_VERIFIER_NOT_FOUND',
470
- 'Key Binding Verifier not found',
471
- );
472
- } else if (payload) {
473
- try {
474
- const kbResult = await sdjwt.kbJwt.verifyKB({
475
- verifier: this.userConfig.kbVerifier,
476
- payload,
477
- nonce: options.keyBindingNonce,
478
- options,
479
- });
480
- if (!kbResult) {
481
- addError(
482
- 'KEY_BINDING_SIGNATURE_INVALID',
483
- 'Key binding signature is not valid',
484
- );
485
- } else {
486
- kb = kbResult;
487
-
488
- // Verify sd_hash
489
- const sdjwtWithoutKb = new SDJwt({
490
- jwt: sdjwt.jwt,
491
- disclosures: sdjwt.disclosures,
492
- });
493
- const presentSdJwtWithoutKb = sdjwtWithoutKb.encodeSDJwt();
494
- const sdHashStr = await this.calculateSDHash(
495
- presentSdJwtWithoutKb,
496
- sdjwt,
497
- hasher,
498
- );
499
-
500
- if (sdHashStr !== kbResult.payload.sd_hash) {
501
- addError(
502
- 'KEY_BINDING_SD_HASH_INVALID',
503
- 'Invalid sd_hash in Key Binding JWT',
504
- {
505
- expected: sdHashStr,
506
- received: kbResult.payload.sd_hash,
507
- },
508
- );
509
- }
510
- }
511
- } catch (e) {
512
- const error = ensureError(e);
513
- addError(
514
- 'KEY_BINDING_SIGNATURE_INVALID',
515
- `Key binding verification failed: ${error.message}`,
516
- error,
517
- );
518
- }
519
- }
520
- }
521
-
522
- // Return result
523
- if (errors.length > 0) {
524
- return { success: false, errors };
525
- }
526
-
527
- return {
528
- success: true,
529
- data: {
530
- payload: payload as ExtendedPayload,
531
- header,
532
- kb,
533
- },
534
- };
535
- }
536
-
537
- private async calculateSDHash(
538
- presentSdJwtWithoutKb: string,
539
- sdjwt: SDJwt,
540
- hasher: Hasher,
541
- ) {
542
- if (!sdjwt.jwt?.payload) {
543
- throw new SDJWTException('Invalid SD JWT');
544
- }
545
- const { _sd_alg } = getSDAlgAndPayload(sdjwt.jwt.payload);
546
- const sdHash = await hasher(presentSdJwtWithoutKb, _sd_alg);
547
- const sdHashStr = uint8ArrayToBase64Url(sdHash);
548
- return sdHashStr;
549
- }
550
-
551
- /**
552
- * This function is for validating the SD JWT
553
- * Checking signature, if provided the iat and exp when provided and return its the claims
554
- * @param encodedSDJwt
555
- * @param options
556
- * @returns
557
- */
558
- public async validate(encodedSDJwt: string, options?: T & VerifierOptions) {
559
- if (!this.userConfig.hasher) {
560
- throw new SDJWTException('Hasher not found');
561
- }
562
- const hasher = this.userConfig.hasher;
563
-
564
- const sdjwt = await SDJwt.fromEncode(encodedSDJwt, hasher);
565
- if (!sdjwt.jwt) {
566
- throw new SDJWTException('Invalid SD JWT');
567
- }
568
-
569
- const verifiedPayloads = await this.VerifyJwt(sdjwt.jwt, {
570
- ...options,
571
- skipJwtClaimValidation: true,
572
- } as T & VerifierOptions);
573
- const claims = await sdjwt.getClaims<ExtendedPayload>(hasher);
574
- // Validate that unpacked claims do not contain reserved field names
575
- validateReservedFieldsInternal(claims);
576
- validateJwtPayload(claims, options);
577
- return { payload: claims, header: verifiedPayloads.header };
578
- }
579
-
580
- public config(newConfig: SDJWTConfig) {
581
- this.userConfig = { ...this.userConfig, ...newConfig };
582
- }
583
-
584
- public encode(sdJwt: SDJwt): SDJWTCompact {
585
- return sdJwt.encodeSDJwt();
586
- }
587
-
588
- public decode(endcodedSDJwt: SDJWTCompact) {
589
- if (!this.userConfig.hasher) {
590
- throw new SDJWTException('Hasher not found');
591
- }
592
- return SDJwt.fromEncode(endcodedSDJwt, this.userConfig.hasher);
593
- }
594
-
595
- public async keys(endcodedSDJwt: SDJWTCompact) {
596
- if (!this.userConfig.hasher) {
597
- throw new SDJWTException('Hasher not found');
598
- }
599
- const sdjwt = await SDJwt.fromEncode(endcodedSDJwt, this.userConfig.hasher);
600
- return sdjwt.keys(this.userConfig.hasher);
601
- }
602
-
603
- public async presentableKeys(endcodedSDJwt: SDJWTCompact) {
604
- if (!this.userConfig.hasher) {
605
- throw new SDJWTException('Hasher not found');
606
- }
607
- const sdjwt = await SDJwt.fromEncode(endcodedSDJwt, this.userConfig.hasher);
608
- return sdjwt.presentableKeys(this.userConfig.hasher);
609
- }
610
-
611
- public async getClaims(endcodedSDJwt: SDJWTCompact) {
612
- if (!this.userConfig.hasher) {
613
- throw new SDJWTException('Hasher not found');
614
- }
615
- const sdjwt = await SDJwt.fromEncode(endcodedSDJwt, this.userConfig.hasher);
616
- return sdjwt.getClaims(this.userConfig.hasher);
617
- }
618
-
619
- public toFlattenJSON(endcodedSDJwt: SDJWTCompact) {
620
- return FlattenJSON.fromEncode(endcodedSDJwt);
621
- }
622
-
623
- public toGeneralJSON(endcodedSDJwt: SDJWTCompact) {
624
- return GeneralJSON.fromEncode(endcodedSDJwt);
625
- }
626
- }
627
-
628
- export class SDJwtGeneralJSONInstance<ExtendedPayload extends SdJwtPayload> {
629
- //header type
630
- protected type?: string;
631
-
632
- public static readonly DEFAULT_hashAlg = 'sha-256';
633
-
634
- protected userConfig: SDJWTConfig = {};
635
-
636
- constructor(userConfig?: SDJWTConfig) {
637
- if (userConfig) {
638
- if (
639
- userConfig.hashAlg &&
640
- !IANA_HASH_ALGORITHMS.includes(userConfig.hashAlg)
641
- ) {
642
- throw new SDJWTException(
643
- `Invalid hash algorithm: ${userConfig.hashAlg}`,
644
- );
645
- }
646
- const allowedDisclosureHashAlgorithms =
647
- userConfig.allowedDisclosureHashAlgorithms ??
648
- DEFAULT_SECURE_HASH_ALGORITHMS;
649
- if (
650
- userConfig.hashAlg &&
651
- !allowedDisclosureHashAlgorithms.includes(userConfig.hashAlg)
652
- ) {
653
- throw new SDJWTException(
654
- `Disallowed hash algorithm: ${userConfig.hashAlg}`,
655
- );
656
- }
657
- this.userConfig = userConfig;
658
- }
659
- }
660
-
661
- private async createKBJwt(
662
- options: KBOptions,
663
- sdHash: string,
664
- ): Promise<KBJwt> {
665
- if (!this.userConfig.kbSigner) {
666
- throw new SDJWTException('Key Binding Signer not found');
667
- }
668
- if (!this.userConfig.kbSignAlg) {
669
- throw new SDJWTException('Key Binding sign algorithm not specified');
670
- }
671
-
672
- const { payload } = options;
673
- const kbJwt = new KBJwt({
674
- header: {
675
- typ: KB_JWT_TYP,
676
- alg: this.userConfig.kbSignAlg,
677
- },
678
- payload: { ...payload, sd_hash: sdHash },
679
- });
680
-
681
- await kbJwt.sign(this.userConfig.kbSigner);
682
- return kbJwt;
683
- }
684
-
685
- private encodeObj(obj: Record<string, unknown>): string {
686
- return base64urlEncode(JSON.stringify(obj));
687
- }
688
-
689
- public async issue<Payload extends ExtendedPayload>(
690
- payload: Payload,
691
- disclosureFrame: DisclosureFrame<Payload> | undefined,
692
- options: {
693
- sigs: Array<{
694
- signer: Signer;
695
- alg: string;
696
- kid: string;
697
- header?: Record<string, unknown>;
698
- }>; // multiple signers for the credential
699
- },
700
- ): Promise<GeneralJSON> {
701
- if (!this.userConfig.hasher) {
702
- throw new SDJWTException('Hasher not found');
703
- }
704
-
705
- if (!this.userConfig.saltGenerator) {
706
- throw new SDJWTException('SaltGenerator not found');
707
- }
708
-
709
- this.validateReservedFields<Payload>(payload);
710
- this.validateDisclosureFrame<Payload>(disclosureFrame);
711
-
712
- const hasher = this.userConfig.hasher;
713
- const hashAlg = this.userConfig.hashAlg ?? SDJwtInstance.DEFAULT_hashAlg;
714
-
715
- const { packedClaims, disclosures } = await pack(
716
- payload,
717
- disclosureFrame,
718
- { hasher, alg: hashAlg },
719
- this.userConfig.saltGenerator,
720
- );
721
-
722
- const encodedSDJwtPayload = this.encodeObj({
723
- ...packedClaims,
724
- _sd_alg: disclosureFrame ? hashAlg : undefined,
725
- });
726
-
727
- const encodedDisclosures = disclosures.map((disclosure) =>
728
- disclosure.encode(),
729
- );
730
-
731
- const signatures = await Promise.all(
732
- options.sigs.map(async (s) => {
733
- const { signer, alg, kid, header } = s;
734
- const protectedHeader = { typ: this.type, alg, kid, ...header };
735
- const encodedProtectedHeader = this.encodeObj(protectedHeader);
736
- const signature = await signer(
737
- `${encodedProtectedHeader}.${encodedSDJwtPayload}`,
738
- );
739
-
740
- return {
741
- protected: encodedProtectedHeader,
742
- signature,
743
- };
744
- }),
745
- );
746
-
747
- const generalJson = new GeneralJSON({
748
- payload: encodedSDJwtPayload,
749
- disclosures: encodedDisclosures,
750
- signatures,
751
- });
752
-
753
- return generalJson;
754
- }
755
-
756
- /**
757
- * Validates if the payload contains any reserved claim names. If so it will throw an error.
758
- * @param payload
759
- * @returns
760
- */
761
- protected validateReservedFields<T extends ExtendedPayload>(payload: T) {
762
- validateReservedFieldsInternal(payload as Record<string, unknown>);
763
- }
764
-
765
- protected validateDisclosureFrame<T extends ExtendedPayload>(
766
- _disclosureFrame?: DisclosureFrame<T>,
767
- ) {
768
- return;
769
- }
770
-
771
- public async present<T extends Record<string, unknown>>(
772
- generalJSON: GeneralJSON,
773
- presentationFrame?: PresentationFrame<T>,
774
- options?: {
775
- kb?: KBOptions;
776
- },
777
- ): Promise<GeneralJSON> {
778
- if (!this.userConfig.hasher) {
779
- throw new SDJWTException('Hasher not found');
780
- }
781
- const hasher = this.userConfig.hasher;
782
- const encodedSDJwt = generalJSON.toEncoded(0);
783
- const sdjwt = await SDJwt.fromEncode(encodedSDJwt, hasher);
784
- if (sdjwt.kbJwt) {
785
- throw new SDJWTException('Holder cannot present an SD-JWT with KB-JWT');
786
- }
787
-
788
- if (!sdjwt.jwt?.payload) throw new SDJWTException('Payload not found');
789
- const disclosures = await sdjwt.getPresentDisclosures(
790
- presentationFrame,
791
- hasher,
792
- );
793
- const encodedDisclosures = disclosures.map((d) => d.encode());
794
- const presentedGeneralJSON = new GeneralJSON({
795
- payload: generalJSON.payload,
796
- disclosures: encodedDisclosures,
797
- signatures: generalJSON.signatures,
798
- });
799
-
800
- if (!options?.kb) {
801
- return presentedGeneralJSON;
802
- }
803
-
804
- const presentSdJwtWithoutKb = await sdjwt.present(
805
- presentationFrame,
806
- hasher,
807
- );
808
-
809
- const sdHashStr = await this.calculateSDHash(
810
- presentSdJwtWithoutKb,
811
- sdjwt,
812
- hasher,
813
- );
814
-
815
- const kbJwt = await this.createKBJwt(options.kb, sdHashStr);
816
- const encodedKbJwt = kbJwt.encodeJwt();
817
- presentedGeneralJSON.kb_jwt = encodedKbJwt;
818
- return presentedGeneralJSON;
819
- }
820
-
821
- // This function is for verifying the SD JWT
822
- // If requiredClaimKeys is provided, it will check if the required claim keys are presentation in the SD JWT
823
- // If requireKeyBindings is true, it will check if the key binding JWT is presentation and verify it
824
- public async verify(generalJSON: GeneralJSON, options?: VerifierOptions) {
825
- if (!this.userConfig.hasher) {
826
- throw new SDJWTException('Hasher not found');
827
- }
828
- const hasher = this.userConfig.hasher;
829
-
830
- const { payload, headers } = await this.validate(generalJSON, options);
831
-
832
- const encodedSDJwt = generalJSON.toEncoded(0);
833
- const sdjwt = await SDJwt.fromEncode(encodedSDJwt, hasher);
834
- if (!sdjwt.jwt?.payload) {
835
- throw new SDJWTException('Invalid SD JWT');
836
- }
837
-
838
- if (options?.requiredClaimKeys) {
839
- const keys = await sdjwt.keys(hasher);
840
- const missingKeys = options?.requiredClaimKeys.filter(
841
- (k) => !keys.includes(k),
842
- );
843
- if (missingKeys.length > 0) {
844
- throw new SDJWTException(
845
- `Missing required claim keys: ${missingKeys.join(', ')}`,
846
- );
847
- }
848
- }
849
-
850
- if (!options?.keyBindingNonce) {
851
- return { payload, headers };
852
- }
853
-
854
- if (!sdjwt.kbJwt) {
855
- throw new SDJWTException('Key Binding JWT not exist');
856
- }
857
- if (!this.userConfig.kbVerifier) {
858
- throw new SDJWTException('Key Binding Verifier not found');
859
- }
860
- const kb = await sdjwt.kbJwt.verifyKB({
861
- verifier: this.userConfig.kbVerifier,
862
- payload,
863
- nonce: options.keyBindingNonce,
864
- options,
865
- });
866
- if (!kb) {
867
- throw new Error('signature is not valid');
868
- }
869
- const sdHashfromKb = kb.payload.sd_hash;
870
- const sdjwtWithoutKb = new SDJwt({
871
- jwt: sdjwt.jwt,
872
- disclosures: sdjwt.disclosures,
873
- });
874
-
875
- const presentSdJwtWithoutKb = sdjwtWithoutKb.encodeSDJwt();
876
- const sdHashStr = await this.calculateSDHash(
877
- presentSdJwtWithoutKb,
878
- sdjwt,
879
- hasher,
880
- );
881
-
882
- if (sdHashStr !== sdHashfromKb) {
883
- throw new SDJWTException('Invalid sd_hash in Key Binding JWT');
884
- }
885
-
886
- return { payload, headers, kb };
887
- }
888
-
889
- private async calculateSDHash(
890
- presentSdJwtWithoutKb: string,
891
- sdjwt: SDJwt,
892
- hasher: Hasher,
893
- ) {
894
- if (!sdjwt.jwt?.payload) {
895
- throw new SDJWTException('Invalid SD JWT');
896
- }
897
- const { _sd_alg } = getSDAlgAndPayload(sdjwt.jwt.payload);
898
- const sdHash = await hasher(presentSdJwtWithoutKb, _sd_alg);
899
- const sdHashStr = uint8ArrayToBase64Url(sdHash);
900
- return sdHashStr;
901
- }
902
-
903
- // This function is for validating the SD JWT
904
- // Just checking signature and return its the claims
905
- public async validate(generalJSON: GeneralJSON, options?: VerifierOptions) {
906
- if (!this.userConfig.hasher) {
907
- throw new SDJWTException('Hasher not found');
908
- }
909
- if (!this.userConfig.verifier) {
910
- throw new SDJWTException('Verifier not found');
911
- }
912
- const hasher = this.userConfig.hasher;
913
- const verifier = this.userConfig.verifier;
914
-
915
- const { payload, signatures } = generalJSON;
916
-
917
- const results = await Promise.all(
918
- signatures.map(async (s) => {
919
- const { protected: encodedHeader, signature } = s;
920
- const verified = await verifier(
921
- `${encodedHeader}.${payload}`,
922
- signature,
923
- { ...options, skipJwtClaimValidation: true },
924
- );
925
- const header = decodeBase64urlJsonStrict<Record<string, unknown>>(
926
- encodedHeader,
927
- 'Invalid JWT',
928
- );
929
- if (typeof header.alg !== 'string' || header.alg === 'none') {
930
- throw new SDJWTException('Verify Error: alg "none" is not allowed');
931
- }
932
- if (
933
- options?.allowedIssuerAlgorithms &&
934
- !options.allowedIssuerAlgorithms.includes(header.alg)
935
- ) {
936
- throw new SDJWTException(
937
- `Verify Error: Disallowed alg ${header.alg}`,
938
- );
939
- }
940
- return { verified, header };
941
- }),
942
- );
943
-
944
- const verified = results.every((r) => r.verified);
945
- if (!verified) {
946
- throw new SDJWTException('Signature is not valid');
947
- }
948
-
949
- const encodedSDJwt = generalJSON.toEncoded(0);
950
- const sdjwt = await SDJwt.fromEncode(encodedSDJwt, hasher);
951
- if (!sdjwt.jwt) {
952
- throw new SDJWTException('Invalid SD JWT');
953
- }
954
-
955
- const claims = await sdjwt.getClaims<ExtendedPayload>(hasher);
956
- // Validate that unpacked claims do not contain reserved field names
957
- validateReservedFieldsInternal(claims);
958
- validateJwtPayload(claims, options);
959
- return { payload: claims, headers: results.map((r) => r.header) };
960
- }
961
-
962
- public config(newConfig: SDJWTConfig) {
963
- this.userConfig = { ...this.userConfig, ...newConfig };
964
- }
965
-
966
- public encode(sdJwt: GeneralJSON, index: number): SDJWTCompact {
967
- return sdJwt.toEncoded(index);
968
- }
969
-
970
- public decode(endcodedSDJwt: SDJWTCompact) {
971
- return GeneralJSON.fromEncode(endcodedSDJwt);
972
- }
973
-
974
- public async keys(generalSdjwt: GeneralJSON) {
975
- if (!this.userConfig.hasher) {
976
- throw new SDJWTException('Hasher not found');
977
- }
978
- const endcodedSDJwt = generalSdjwt.toEncoded(0);
979
- const sdjwt = await SDJwt.fromEncode(endcodedSDJwt, this.userConfig.hasher);
980
- return sdjwt.keys(this.userConfig.hasher);
981
- }
982
-
983
- public async presentableKeys(generalSdjwt: GeneralJSON) {
984
- if (!this.userConfig.hasher) {
985
- throw new SDJWTException('Hasher not found');
986
- }
987
- const endcodedSDJwt = generalSdjwt.toEncoded(0);
988
- const sdjwt = await SDJwt.fromEncode(endcodedSDJwt, this.userConfig.hasher);
989
- return sdjwt.presentableKeys(this.userConfig.hasher);
990
- }
991
-
992
- public async getClaims(generalSdjwt: GeneralJSON) {
993
- if (!this.userConfig.hasher) {
994
- throw new SDJWTException('Hasher not found');
995
- }
996
- const endcodedSDJwt = generalSdjwt.toEncoded(0);
997
- const sdjwt = await SDJwt.fromEncode(endcodedSDJwt, this.userConfig.hasher);
998
- return sdjwt.getClaims(this.userConfig.hasher);
999
- }
1000
- }