@sd-jwt/core 0.1.0 → 0.1.1-next.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (170) hide show
  1. package/CHANGELOG.md +17 -0
  2. package/LICENSE +201 -0
  3. package/README.md +106 -0
  4. package/dist/index.d.mts +659 -0
  5. package/dist/index.d.ts +659 -0
  6. package/dist/index.js +1906 -0
  7. package/dist/index.mjs +1846 -0
  8. package/package.json +59 -47
  9. package/src/decode/decode.ts +376 -0
  10. package/src/decode/index.ts +1 -0
  11. package/src/decoy.ts +15 -0
  12. package/src/flattenJSON.ts +99 -0
  13. package/src/generalJSON.ts +148 -0
  14. package/src/index.ts +945 -0
  15. package/src/jwt.ts +190 -0
  16. package/src/kbjwt.ts +81 -0
  17. package/src/present/index.ts +1 -0
  18. package/src/present/present.ts +210 -0
  19. package/src/sdjwt.ts +354 -0
  20. package/src/test/decode/decode.spec.ts +202 -0
  21. package/src/test/decoy.spec.ts +30 -0
  22. package/src/test/flattenJSON.spec.ts +122 -0
  23. package/src/test/generalJSON.spec.ts +198 -0
  24. package/src/test/index.spec.ts +974 -0
  25. package/src/test/jwt.spec.ts +301 -0
  26. package/src/test/kbjwt.spec.ts +565 -0
  27. package/src/test/pass.spec.ts +7 -0
  28. package/src/test/present/present.spec.ts +305 -0
  29. package/src/test/sdjwt.spec.ts +384 -0
  30. package/src/test/types/type.spec.ts +88 -0
  31. package/src/test/utils/base64url.spec.ts +33 -0
  32. package/src/test/utils/disclosure.spec.ts +170 -0
  33. package/src/test/utils/error.spec.ts +15 -0
  34. package/src/types/index.ts +2 -0
  35. package/src/types/type.ts +249 -0
  36. package/src/types/verification-error.ts +55 -0
  37. package/src/utils/base64url.ts +6 -0
  38. package/src/utils/disclosure.ts +101 -0
  39. package/src/utils/error.ts +25 -0
  40. package/src/utils/index.ts +3 -0
  41. package/src/utils/strict-json.ts +17 -0
  42. package/test/app-e2e.spec.ts +292 -0
  43. package/test/array_data_types.json +31 -0
  44. package/test/array_full_sd.json +21 -0
  45. package/test/array_in_sd.json +13 -0
  46. package/test/array_nested_in_plain.json +29 -0
  47. package/test/array_none_disclosed.json +17 -0
  48. package/test/array_of_nulls.json +15 -0
  49. package/test/array_of_objects.json +65 -0
  50. package/test/array_of_scalars.json +19 -0
  51. package/test/array_recursive_sd.json +35 -0
  52. package/test/array_recursive_sd_some_disclosed.json +63 -0
  53. package/test/complex.json +43 -0
  54. package/test/header_mod.json +48 -0
  55. package/test/json_serialization.json +48 -0
  56. package/test/key_binding.json +48 -0
  57. package/test/no_sd.json +36 -0
  58. package/test/object_data_types.json +62 -0
  59. package/test/recursions.json +117 -0
  60. package/test/rfc9901-validation.spec.ts +150 -0
  61. package/tsconfig.json +7 -0
  62. package/vitest.config.mts +4 -0
  63. package/build/base64url.d.ts +0 -28
  64. package/build/base64url.js +0 -40
  65. package/build/base64url.js.map +0 -1
  66. package/build/hasherAlgorithm.d.ts +0 -70
  67. package/build/hasherAlgorithm.js +0 -75
  68. package/build/hasherAlgorithm.js.map +0 -1
  69. package/build/index.d.ts +0 -11
  70. package/build/index.js +0 -20
  71. package/build/index.js.map +0 -1
  72. package/build/jwt/compact.d.ts +0 -6
  73. package/build/jwt/compact.js +0 -27
  74. package/build/jwt/compact.js.map +0 -1
  75. package/build/jwt/error.d.ts +0 -2
  76. package/build/jwt/error.js +0 -7
  77. package/build/jwt/error.js.map +0 -1
  78. package/build/jwt/index.d.ts +0 -3
  79. package/build/jwt/index.js +0 -20
  80. package/build/jwt/index.js.map +0 -1
  81. package/build/jwt/jwt.d.ts +0 -204
  82. package/build/jwt/jwt.js +0 -324
  83. package/build/jwt/jwt.js.map +0 -1
  84. package/build/keyBinding/index.d.ts +0 -1
  85. package/build/keyBinding/index.js +0 -18
  86. package/build/keyBinding/index.js.map +0 -1
  87. package/build/keyBinding/keyBinding.d.ts +0 -56
  88. package/build/keyBinding/keyBinding.js +0 -99
  89. package/build/keyBinding/keyBinding.js.map +0 -1
  90. package/build/sdJwt/compact.d.ts +0 -8
  91. package/build/sdJwt/compact.js +0 -39
  92. package/build/sdJwt/compact.js.map +0 -1
  93. package/build/sdJwt/decoys.d.ts +0 -2
  94. package/build/sdJwt/decoys.js +0 -35
  95. package/build/sdJwt/decoys.js.map +0 -1
  96. package/build/sdJwt/disclosureFrame.d.ts +0 -7
  97. package/build/sdJwt/disclosureFrame.js +0 -89
  98. package/build/sdJwt/disclosureFrame.js.map +0 -1
  99. package/build/sdJwt/disclosureMapping.d.ts +0 -44
  100. package/build/sdJwt/disclosureMapping.js +0 -289
  101. package/build/sdJwt/disclosureMapping.js.map +0 -1
  102. package/build/sdJwt/disclosures.d.ts +0 -14
  103. package/build/sdJwt/disclosures.js +0 -59
  104. package/build/sdJwt/disclosures.js.map +0 -1
  105. package/build/sdJwt/error.d.ts +0 -2
  106. package/build/sdJwt/error.js +0 -7
  107. package/build/sdJwt/error.js.map +0 -1
  108. package/build/sdJwt/index.d.ts +0 -7
  109. package/build/sdJwt/index.js +0 -24
  110. package/build/sdJwt/index.js.map +0 -1
  111. package/build/sdJwt/presentationFrame.d.ts +0 -4
  112. package/build/sdJwt/presentationFrame.js +0 -73
  113. package/build/sdJwt/presentationFrame.js.map +0 -1
  114. package/build/sdJwt/sdJwt.d.ts +0 -204
  115. package/build/sdJwt/sdJwt.js +0 -383
  116. package/build/sdJwt/sdJwt.js.map +0 -1
  117. package/build/sdJwt/swapClaim.d.ts +0 -3
  118. package/build/sdJwt/swapClaim.js +0 -90
  119. package/build/sdJwt/swapClaim.js.map +0 -1
  120. package/build/sdJwt/types.d.ts +0 -5
  121. package/build/sdJwt/types.js +0 -3
  122. package/build/sdJwt/types.js.map +0 -1
  123. package/build/sdJwtVc/error.d.ts +0 -2
  124. package/build/sdJwtVc/error.js +0 -7
  125. package/build/sdJwtVc/error.js.map +0 -1
  126. package/build/sdJwtVc/index.d.ts +0 -2
  127. package/build/sdJwtVc/index.js +0 -19
  128. package/build/sdJwtVc/index.js.map +0 -1
  129. package/build/sdJwtVc/sdJwtVc.d.ts +0 -47
  130. package/build/sdJwtVc/sdJwtVc.js +0 -125
  131. package/build/sdJwtVc/sdJwtVc.js.map +0 -1
  132. package/build/signatureAndEncryptionAlgorithm.d.ts +0 -105
  133. package/build/signatureAndEncryptionAlgorithm.js +0 -110
  134. package/build/signatureAndEncryptionAlgorithm.js.map +0 -1
  135. package/build/types/disclosure.d.ts +0 -5
  136. package/build/types/disclosure.js +0 -3
  137. package/build/types/disclosure.js.map +0 -1
  138. package/build/types/frame.d.ts +0 -5
  139. package/build/types/frame.js +0 -3
  140. package/build/types/frame.js.map +0 -1
  141. package/build/types/hasher.d.ts +0 -14
  142. package/build/types/hasher.js +0 -3
  143. package/build/types/hasher.js.map +0 -1
  144. package/build/types/index.d.ts +0 -6
  145. package/build/types/index.js +0 -23
  146. package/build/types/index.js.map +0 -1
  147. package/build/types/present.d.ts +0 -2
  148. package/build/types/present.js +0 -3
  149. package/build/types/present.js.map +0 -1
  150. package/build/types/saltGenerator.d.ts +0 -17
  151. package/build/types/saltGenerator.js +0 -3
  152. package/build/types/saltGenerator.js.map +0 -1
  153. package/build/types/signer.d.ts +0 -2
  154. package/build/types/signer.js +0 -3
  155. package/build/types/signer.js.map +0 -1
  156. package/build/types/utils.d.ts +0 -5
  157. package/build/types/utils.js +0 -3
  158. package/build/types/utils.js.map +0 -1
  159. package/build/types/verifier.d.ts +0 -14
  160. package/build/types/verifier.js +0 -3
  161. package/build/types/verifier.js.map +0 -1
  162. package/build/utils/index.d.ts +0 -2
  163. package/build/utils/index.js +0 -19
  164. package/build/utils/index.js.map +0 -1
  165. package/build/utils/traverse.d.ts +0 -8
  166. package/build/utils/traverse.js +0 -29
  167. package/build/utils/traverse.js.map +0 -1
  168. package/build/utils/utils.d.ts +0 -7
  169. package/build/utils/utils.js +0 -109
  170. package/build/utils/utils.js.map +0 -1
package/src/jwt.ts ADDED
@@ -0,0 +1,190 @@
1
+ import { decodeJwt } from './decode';
2
+ import type { Base64urlString, Signer, Verifier } from './types';
3
+ import { base64urlEncode, SDJWTException } from './utils';
4
+
5
+ export type JwtData<
6
+ Header extends Record<string, unknown>,
7
+ Payload extends Record<string, unknown>,
8
+ > = {
9
+ header?: Header;
10
+ payload?: Payload;
11
+ signature?: Base64urlString;
12
+ encoded?: string;
13
+ };
14
+
15
+ /**
16
+ * Options for the JWT verifier
17
+ */
18
+ export type VerifierOptions = {
19
+ /**
20
+ * current time in seconds since epoch
21
+ */
22
+ currentDate?: number;
23
+
24
+ /**
25
+ * allowed skew for the current time in seconds. Positive value that will lower the iat and nbf checks, and increase the exp check.
26
+ */
27
+ skewSeconds?: number;
28
+
29
+ /**
30
+ * required claim keys for the payload.
31
+ * If the payload does not contain these keys, the verification will fail.
32
+ */
33
+ requiredClaimKeys?: string[];
34
+
35
+ /**
36
+ * nonce used to verify the key binding jwt to prevent replay attacks.
37
+ */
38
+ keyBindingNonce?: string;
39
+
40
+ /**
41
+ * disable the verification of the status claim in the payload.
42
+ *
43
+ * @default false
44
+ */
45
+ disableStatusVerification?: boolean;
46
+
47
+ /**
48
+ * any other custom options
49
+ */
50
+ [key: string]: unknown;
51
+ };
52
+
53
+ // This class is used to create and verify JWT
54
+ // Contains header, payload, and signature
55
+ export class Jwt<
56
+ Header extends Record<string, unknown> = Record<string, unknown>,
57
+ Payload extends Record<string, unknown> = Record<string, unknown>,
58
+ > {
59
+ public header?: Header;
60
+ public payload?: Payload;
61
+ public signature?: Base64urlString;
62
+ private encoded?: string;
63
+
64
+ constructor(data?: JwtData<Header, Payload>) {
65
+ this.header = data?.header;
66
+ this.payload = data?.payload;
67
+ this.signature = data?.signature;
68
+ this.encoded = data?.encoded;
69
+ }
70
+
71
+ public static decodeJWT<
72
+ Header extends Record<string, unknown> = Record<string, unknown>,
73
+ Payload extends Record<string, unknown> = Record<string, unknown>,
74
+ >(
75
+ jwt: string,
76
+ ): { header: Header; payload: Payload; signature: Base64urlString } {
77
+ return decodeJwt(jwt);
78
+ }
79
+
80
+ public static fromEncode<
81
+ Header extends Record<string, unknown> = Record<string, unknown>,
82
+ Payload extends Record<string, unknown> = Record<string, unknown>,
83
+ >(encodedJwt: string): Jwt<Header, Payload> {
84
+ const { header, payload, signature } = Jwt.decodeJWT<Header, Payload>(
85
+ encodedJwt,
86
+ );
87
+
88
+ const jwt = new Jwt<Header, Payload>({
89
+ header,
90
+ payload,
91
+ signature,
92
+ encoded: encodedJwt,
93
+ });
94
+
95
+ return jwt;
96
+ }
97
+
98
+ public setHeader(header: Header): Jwt<Header, Payload> {
99
+ this.header = header;
100
+ this.encoded = undefined;
101
+ return this;
102
+ }
103
+
104
+ public setPayload(payload: Payload): Jwt<Header, Payload> {
105
+ this.payload = payload;
106
+ this.encoded = undefined;
107
+ return this;
108
+ }
109
+
110
+ protected getUnsignedToken() {
111
+ if (!this.header || !this.payload) {
112
+ throw new SDJWTException('Serialize Error: Invalid JWT');
113
+ }
114
+
115
+ if (this.encoded) {
116
+ const parts = this.encoded.split('.');
117
+ if (parts.length !== 3) {
118
+ throw new SDJWTException(`Invalid JWT format: ${this.encoded}`);
119
+ }
120
+ const unsignedToken = parts.slice(0, 2).join('.');
121
+ return unsignedToken;
122
+ }
123
+
124
+ const header = base64urlEncode(JSON.stringify(this.header));
125
+ const payload = base64urlEncode(JSON.stringify(this.payload));
126
+ return `${header}.${payload}`;
127
+ }
128
+
129
+ public async sign(signer: Signer) {
130
+ const data = this.getUnsignedToken();
131
+ this.signature = await signer(data);
132
+
133
+ return this.encodeJwt();
134
+ }
135
+
136
+ public encodeJwt(): string {
137
+ if (this.encoded) {
138
+ return this.encoded;
139
+ }
140
+
141
+ if (!this.header || !this.payload || !this.signature) {
142
+ throw new SDJWTException('Serialize Error: Invalid JWT');
143
+ }
144
+
145
+ const header = base64urlEncode(JSON.stringify(this.header));
146
+ const payload = base64urlEncode(JSON.stringify(this.payload));
147
+ const signature = this.signature;
148
+ const compact = `${header}.${payload}.${signature}`;
149
+ this.encoded = compact;
150
+
151
+ return compact;
152
+ }
153
+
154
+ /**
155
+ * Verify the JWT using the provided verifier function.
156
+ * It checks the signature and validates the iat, nbf, and exp claims if they are present.
157
+ * @param verifier
158
+ * @param options - Options for verification, such as current date and skew seconds
159
+ * @returns
160
+ */
161
+ public async verify<T>(verifier: Verifier<T>, options?: T & VerifierOptions) {
162
+ const skew = options?.skewSeconds ? options.skewSeconds : 0;
163
+ const currentDate = options?.currentDate ?? Math.floor(Date.now() / 1000);
164
+ const iat = this.payload?.iat;
165
+ const nbf = this.payload?.nbf;
166
+ const exp = this.payload?.exp;
167
+
168
+ if (typeof iat === 'number' && iat - skew > currentDate) {
169
+ throw new SDJWTException('Verify Error: JWT is not yet valid');
170
+ }
171
+
172
+ if (typeof nbf === 'number' && nbf - skew > currentDate) {
173
+ throw new SDJWTException('Verify Error: JWT is not yet valid');
174
+ }
175
+ if (typeof exp === 'number' && exp + skew < currentDate) {
176
+ throw new SDJWTException('Verify Error: JWT is expired');
177
+ }
178
+
179
+ if (!this.signature) {
180
+ throw new SDJWTException('Verify Error: no signature in JWT');
181
+ }
182
+ const data = this.getUnsignedToken();
183
+
184
+ const verified = await verifier(data, this.signature, options);
185
+ if (!verified) {
186
+ throw new SDJWTException('Verify Error: Invalid JWT Signature');
187
+ }
188
+ return { payload: this.payload, header: this.header };
189
+ }
190
+ }
package/src/kbjwt.ts ADDED
@@ -0,0 +1,81 @@
1
+ import { Jwt, type VerifierOptions } from './jwt';
2
+ import {
3
+ KB_JWT_TYP,
4
+ type KbVerifier,
5
+ type kbHeader,
6
+ type kbPayload,
7
+ } from './types';
8
+ import { SDJWTException } from './utils';
9
+
10
+ export class KBJwt<
11
+ Header extends kbHeader = kbHeader,
12
+ Payload extends kbPayload = kbPayload,
13
+ > extends Jwt<Header, Payload> {
14
+ // Checking the validity of the key binding jwt
15
+ // the type unknown is not good, but we don't know at this point how to get the public key of the signer, this is defined in the kbVerifier
16
+ public async verifyKB(values: {
17
+ verifier: KbVerifier;
18
+ payload: Record<string, unknown>;
19
+ nonce: string;
20
+ /**
21
+ * Options forwarded to the common JWT verification, e.g. currentDate and
22
+ * skewSeconds used to validate the iat, nbf and exp claims.
23
+ */
24
+ options?: VerifierOptions;
25
+ }) {
26
+ if (!this.header || !this.payload || !this.signature) {
27
+ throw new SDJWTException('Verify Error: Invalid JWT');
28
+ }
29
+
30
+ if (
31
+ !this.header.alg ||
32
+ this.header.alg === 'none' ||
33
+ !this.header.typ ||
34
+ this.header.typ !== KB_JWT_TYP ||
35
+ !this.payload.iat ||
36
+ !this.payload.aud ||
37
+ !this.payload.nonce ||
38
+ // this is for backward compatibility with version 06
39
+ !(
40
+ this.payload.sd_hash ||
41
+ ('_sd_hash' in this.payload && this.payload._sd_hash)
42
+ )
43
+ ) {
44
+ throw new SDJWTException('Invalid Key Binding Jwt');
45
+ }
46
+
47
+ if (this.payload.nonce !== values.nonce) {
48
+ throw new SDJWTException('Verify Error: Invalid Nonce');
49
+ }
50
+
51
+ // Delegate signature verification and common JWT claim validation
52
+ // (iat, nbf, exp) to the shared Jwt.verify implementation. The kbVerifier
53
+ // needs the kb+jwt payload (e.g. the holder's cnf key), so we wrap it to
54
+ // forward values.payload instead of the base verifier's options argument.
55
+ await this.verify(
56
+ (data, sig) => values.verifier(data, sig, values.payload),
57
+ values.options,
58
+ );
59
+
60
+ return { payload: this.payload, header: this.header };
61
+ }
62
+
63
+ // This function is for creating KBJwt object for verify properly
64
+ public static fromKBEncode<
65
+ Header extends kbHeader = kbHeader,
66
+ Payload extends kbPayload = kbPayload,
67
+ >(encodedJwt: string): KBJwt<Header, Payload> {
68
+ const { header, payload, signature } = Jwt.decodeJWT<Header, Payload>(
69
+ encodedJwt,
70
+ );
71
+
72
+ const jwt = new KBJwt<Header, Payload>({
73
+ header,
74
+ payload,
75
+ signature,
76
+ encoded: encodedJwt,
77
+ });
78
+
79
+ return jwt;
80
+ }
81
+ }
@@ -0,0 +1 @@
1
+ export * from './present';
@@ -0,0 +1,210 @@
1
+ import {
2
+ createHashMapping,
3
+ createHashMappingSync,
4
+ decodeSdJwt,
5
+ decodeSdJwtSync,
6
+ getSDAlgAndPayload,
7
+ splitSdJwt,
8
+ unpack,
9
+ unpackObj,
10
+ unpackSync,
11
+ } from '../decode';
12
+ import type { Extensible, HasherSync } from '../types';
13
+ import { type Hasher, type PresentationFrame, SD_SEPARATOR } from '../types';
14
+ import { Disclosure, SDJWTException } from '../utils';
15
+
16
+ // Presentable keys
17
+ // The presentable keys are the path of JSON object that are presentable in the SD JWT
18
+ // e.g. if the SD JWT has the following payload and set sd like this:
19
+ // {
20
+ // "foo": "bar", // sd
21
+ // "arr": [ // sd
22
+ // "1", // sd
23
+ // "2",
24
+ // {
25
+ // "a": "1" // sd
26
+ // }
27
+ // ],
28
+ // "test": {
29
+ // "zzz": "xxx" // sd
30
+ // }
31
+ // }
32
+ // The presentable keys are: ["arr", "arr.0", "arr.2.a", "foo", "test.zzz"]
33
+ export const presentableKeys = async (
34
+ rawPayload: Record<string, unknown>,
35
+ disclosures: Array<Disclosure>,
36
+ hasher: Hasher,
37
+ ): Promise<string[]> => {
38
+ const { disclosureKeymap } = await unpack(rawPayload, disclosures, hasher);
39
+ return Object.keys(disclosureKeymap).sort();
40
+ };
41
+
42
+ export const presentableKeysSync = (
43
+ rawPayload: Record<string, unknown>,
44
+ disclosures: Array<Disclosure>,
45
+ hasher: HasherSync,
46
+ ): string[] => {
47
+ const { disclosureKeymap } = unpackSync(rawPayload, disclosures, hasher);
48
+ return Object.keys(disclosureKeymap).sort();
49
+ };
50
+
51
+ export const present = async <T extends Record<string, unknown>>(
52
+ sdJwt: string,
53
+ presentFrame: PresentationFrame<T>,
54
+ hasher: Hasher,
55
+ ): Promise<string> => {
56
+ const { jwt, kbJwt } = splitSdJwt(sdJwt);
57
+ const {
58
+ jwt: { payload },
59
+ disclosures,
60
+ } = await decodeSdJwt(sdJwt, hasher);
61
+
62
+ const { _sd_alg: alg } = getSDAlgAndPayload(payload);
63
+ const hash = { alg, hasher };
64
+ const keys = transformPresentationFrame(presentFrame);
65
+
66
+ // hashmap: <digest> => <disclosure>
67
+ // to match the digest with the disclosure
68
+ const hashmap = await createHashMapping(disclosures, hash);
69
+ const { disclosureKeymap } = await unpack(payload, disclosures, hasher);
70
+ const presentedDisclosures = keys
71
+ .map((k) => hashmap[disclosureKeymap[k]])
72
+ .filter((d) => d !== undefined);
73
+
74
+ return [
75
+ jwt,
76
+ ...presentedDisclosures.map((d) => d.encode()),
77
+ kbJwt ?? '',
78
+ ].join(SD_SEPARATOR);
79
+ };
80
+
81
+ export const presentSync = <T extends Record<string, unknown>>(
82
+ sdJwt: string,
83
+ presentFrame: PresentationFrame<T>,
84
+ hasher: HasherSync,
85
+ ): string => {
86
+ const { jwt, kbJwt } = splitSdJwt(sdJwt);
87
+ const {
88
+ jwt: { payload },
89
+ disclosures,
90
+ } = decodeSdJwtSync(sdJwt, hasher);
91
+
92
+ const { _sd_alg: alg } = getSDAlgAndPayload(payload);
93
+ const hash = { alg, hasher };
94
+ const keys = transformPresentationFrame(presentFrame);
95
+
96
+ // hashmap: <digest> => <disclosure>
97
+ // to match the digest with the disclosure
98
+ const hashmap = createHashMappingSync(disclosures, hash);
99
+ const { disclosureKeymap } = unpackSync(payload, disclosures, hasher);
100
+
101
+ const presentedDisclosures = keys
102
+ .map((k) => hashmap[disclosureKeymap[k]])
103
+ .filter((d) => d !== undefined);
104
+
105
+ return [
106
+ jwt,
107
+ ...presentedDisclosures.map((d) => d.encode()),
108
+ kbJwt ?? '',
109
+ ].join(SD_SEPARATOR);
110
+ };
111
+
112
+ /**
113
+ * Transform the object keys into an array of strings. We are not sorting the array in any way.
114
+ * @param obj The object to transform
115
+ * @param prefix The prefix to add to the keys
116
+ * @returns
117
+ */
118
+ export const transformPresentationFrame = (
119
+ obj: PresentationFrame<Extensible>,
120
+ prefix = '',
121
+ ): string[] => {
122
+ return Object.entries(obj).reduce<string[]>((acc, [key, value]) => {
123
+ const newPrefix = prefix ? `${prefix}.${key}` : key;
124
+ if (typeof value === 'boolean') {
125
+ // only add it, when it's true
126
+ if (value) {
127
+ acc.push(newPrefix);
128
+ }
129
+ } else if (typeof value === 'object' && value !== null) {
130
+ acc.push(
131
+ newPrefix,
132
+ ...transformPresentationFrame(
133
+ value as PresentationFrame<Extensible>,
134
+ newPrefix,
135
+ ),
136
+ );
137
+ }
138
+ return acc;
139
+ }, []);
140
+ };
141
+
142
+ export type SerializedDisclosure = {
143
+ digest: string;
144
+ encoded: string;
145
+ salt: string;
146
+ key: string | undefined;
147
+ value: unknown;
148
+ };
149
+
150
+ export const createHashMappingForSerializedDisclosure = (
151
+ disclosures: SerializedDisclosure[],
152
+ ) => {
153
+ const map: Record<string, Disclosure> = {};
154
+ for (let i = 0; i < disclosures.length; i++) {
155
+ const disclosure = disclosures[i];
156
+ const { digest, encoded, key, salt, value } = disclosure;
157
+ // we made Disclosure to fit the interface of unpack
158
+ map[digest] = Disclosure.fromArray(
159
+ key ? [salt, key, value] : [salt, value],
160
+ { digest, encoded },
161
+ );
162
+ }
163
+ return map;
164
+ };
165
+
166
+ /**
167
+ * This function selects the serialized disclosures from the payload
168
+ * and array of serialized disclosure based on the presentation frame.
169
+ * If you want to know what is serialized disclosures, check type SerializedDisclosure.
170
+ * @param payload: Record<string, unknown>
171
+ * @param disclosures: SerializedDisclosure[]
172
+ * @param presentationFrame: PresentationFrame<T>
173
+ */
174
+ export const selectDisclosures = <T extends Record<string, unknown>>(
175
+ payload: Record<string, unknown>,
176
+ disclosures: SerializedDisclosure[],
177
+ presentationFrame: PresentationFrame<T>,
178
+ ) => {
179
+ if (disclosures.length === 0) {
180
+ return [];
181
+ }
182
+
183
+ const hashmap = createHashMappingForSerializedDisclosure(disclosures);
184
+ const { disclosureKeymap } = unpackObj(payload, hashmap);
185
+ const keys = transformPresentationFrame(presentationFrame);
186
+
187
+ const presentedDisclosures = keys
188
+ .map((k) => hashmap[disclosureKeymap[k]])
189
+ .filter((d) => d !== undefined);
190
+
191
+ const selectedDisclosures: SerializedDisclosure[] = presentedDisclosures.map(
192
+ (d) => {
193
+ const { salt, key, value, _digest } = d;
194
+ if (!_digest) {
195
+ throw new SDJWTException(
196
+ 'Implementation error: _digest is not defined',
197
+ );
198
+ }
199
+ return {
200
+ digest: _digest,
201
+ encoded: d.encode(),
202
+ salt,
203
+ key,
204
+ value,
205
+ };
206
+ },
207
+ );
208
+
209
+ return selectedDisclosures;
210
+ };