@virtru/dsp-sdk 0.5.0 → 0.6.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 (130) hide show
  1. package/CHANGELOG.md +8 -1
  2. package/README.md +81 -3
  3. package/dist/src/fips.d.ts +7 -0
  4. package/dist/src/fips.js +12 -0
  5. package/dist/src/lib/dsp.d.ts +17 -1
  6. package/dist/src/lib/dsp.js +28 -5
  7. package/package.json +23 -2
  8. package/.prettierrc +0 -3
  9. package/.rush/temp/chunked-rush-logs/dsp-sdk._phase_build.chunks.jsonl +0 -12
  10. package/.rush/temp/chunked-rush-logs/dsp-sdk._phase_test.chunks.jsonl +0 -383
  11. package/.rush/temp/package-deps__phase_build.json +0 -76
  12. package/.rush/temp/shrinkwrap-deps.json +0 -1262
  13. package/CHANGELOG.json +0 -299
  14. package/buf.gen.yaml +0 -17
  15. package/buf.yaml +0 -4
  16. package/config/jest.config.json +0 -6
  17. package/config/rig.json +0 -8
  18. package/dist/tests/dsp-client.test.d.ts +0 -1
  19. package/dist/tests/dsp-client.test.js +0 -73
  20. package/dist/tests/dsp.test.d.ts +0 -1
  21. package/dist/tests/dsp.test.js +0 -92
  22. package/dist/tests/fips-crypto.unit.test.d.ts +0 -1
  23. package/dist/tests/fips-crypto.unit.test.js +0 -258
  24. package/dist/tests/mocks/create-export-artifacts.d.ts +0 -2
  25. package/dist/tests/mocks/create-export-artifacts.js +0 -13
  26. package/dist/tests/mocks/tagging-pdp-tag.d.ts +0 -2
  27. package/dist/tests/mocks/tagging-pdp-tag.js +0 -11
  28. package/dist/tests/mocks/well-known-configuration.d.ts +0 -2
  29. package/dist/tests/mocks/well-known-configuration.js +0 -12
  30. package/dist/tests/setup-msw.d.ts +0 -9
  31. package/dist/tests/setup-msw.js +0 -30
  32. package/dist/tests/setup-unit.d.ts +0 -7
  33. package/dist/tests/setup-unit.js +0 -70
  34. package/eslint.config.mjs +0 -28
  35. package/lib-commonjs/src/gen/buf/validate/validate_pb.js +0 -487
  36. package/lib-commonjs/src/gen/config/v1/config_pb.js +0 -142
  37. package/lib-commonjs/src/gen/config/v1/kas_config_pb.js +0 -72
  38. package/lib-commonjs/src/gen/config/v1/meta_pb.js +0 -36
  39. package/lib-commonjs/src/gen/config/v1/outlook_config_pb.js +0 -67
  40. package/lib-commonjs/src/gen/config/v1/secureviewer_config_pb.js +0 -67
  41. package/lib-commonjs/src/gen/config/v1/tagging_pb.js +0 -246
  42. package/lib-commonjs/src/gen/google/api/annotations_pb.js +0 -33
  43. package/lib-commonjs/src/gen/google/api/http_pb.js +0 -44
  44. package/lib-commonjs/src/gen/policyimportexport/v1/policy_import_export_pb.js +0 -93
  45. package/lib-commonjs/src/gen/shared/v1/shared_pb.js +0 -95
  46. package/lib-commonjs/src/gen/tagging/pdp/v2/tagging_pb.js +0 -277
  47. package/lib-commonjs/src/gen/version/v1/version_pb.js +0 -40
  48. package/lib-commonjs/src/gen/virtru/common/common_pb.js +0 -76
  49. package/lib-commonjs/src/gen/virtru/policy/certificates/v1/certificates_pb.js +0 -77
  50. package/lib-commonjs/src/gen/virtru/policy/objects_pb.js +0 -143
  51. package/lib-commonjs/src/index.js +0 -48
  52. package/lib-commonjs/src/lib/client.js +0 -66
  53. package/lib-commonjs/src/lib/consts.js +0 -10
  54. package/lib-commonjs/src/lib/dsp.js +0 -49
  55. package/lib-commonjs/src/lib/fips-crypto/asymmetric.js +0 -126
  56. package/lib-commonjs/src/lib/fips-crypto/key-format.js +0 -243
  57. package/lib-commonjs/src/lib/fips-crypto/keys.js +0 -134
  58. package/lib-commonjs/src/lib/fips-crypto/primitives.js +0 -112
  59. package/lib-commonjs/src/lib/fips-crypto/symmetric.js +0 -162
  60. package/lib-commonjs/src/lib/fips-crypto-service.js +0 -57
  61. package/lib-commonjs/src/lib/utils.js +0 -401
  62. package/lib-commonjs/tests/dsp-client.test.js +0 -75
  63. package/lib-commonjs/tests/dsp.test.js +0 -94
  64. package/lib-commonjs/tests/fips-crypto.unit.test.js +0 -260
  65. package/lib-commonjs/tests/mocks/create-export-artifacts.js +0 -17
  66. package/lib-commonjs/tests/mocks/tagging-pdp-tag.js +0 -15
  67. package/lib-commonjs/tests/mocks/well-known-configuration.js +0 -16
  68. package/lib-commonjs/tests/setup-msw.js +0 -33
  69. package/lib-commonjs/tests/setup-unit.js +0 -72
  70. package/public/virtru.wasm +0 -0
  71. package/src/gen/buf/validate/validate_pb.ts +0 -4879
  72. package/src/gen/config/formatters/testdata/v1/test_pb.ts +0 -287
  73. package/src/gen/config/v1/config_connect.ts +0 -111
  74. package/src/gen/config/v1/config_pb.ts +0 -439
  75. package/src/gen/config/v1/kas_config_pb.ts +0 -183
  76. package/src/gen/config/v1/meta_pb.ts +0 -72
  77. package/src/gen/config/v1/outlook_config_pb.ts +0 -242
  78. package/src/gen/config/v1/secureviewer_config_pb.ts +0 -161
  79. package/src/gen/config/v1/tagging_pb.ts +0 -456
  80. package/src/gen/google/api/annotations_pb.ts +0 -43
  81. package/src/gen/google/api/http_pb.ts +0 -486
  82. package/src/gen/helloworld/v1/helloworld_connect.ts +0 -49
  83. package/src/gen/helloworld/v1/helloworld_pb.ts +0 -104
  84. package/src/gen/kas/nanotdf/v1/nanotdf_rewrap_connect.ts +0 -39
  85. package/src/gen/kas/nanotdf/v1/nanotdf_rewrap_pb.ts +0 -207
  86. package/src/gen/policyimportexport/v1/policy_import_export_connect.ts +0 -56
  87. package/src/gen/policyimportexport/v1/policy_import_export_pb.ts +0 -332
  88. package/src/gen/shared/v1/shared_connect.ts +0 -61
  89. package/src/gen/shared/v1/shared_pb.ts +0 -240
  90. package/src/gen/shared/v2/shared_connect.ts +0 -39
  91. package/src/gen/shared/v2/shared_pb.ts +0 -122
  92. package/src/gen/tagging/pdp/v2/externalprocessors/processor_connect.ts +0 -156
  93. package/src/gen/tagging/pdp/v2/externalprocessors/processor_pb.ts +0 -709
  94. package/src/gen/tagging/pdp/v2/stanag/stanag_pb.ts +0 -953
  95. package/src/gen/tagging/pdp/v2/tagging_connect.ts +0 -73
  96. package/src/gen/tagging/pdp/v2/tagging_pb.ts +0 -1064
  97. package/src/gen/version/v1/version_connect.ts +0 -31
  98. package/src/gen/version/v1/version_pb.ts +0 -143
  99. package/src/gen/virtru/common/common_pb.ts +0 -201
  100. package/src/gen/virtru/policy/certificates/v1/certificates_connect.ts +0 -44
  101. package/src/gen/virtru/policy/certificates/v1/certificates_pb.ts +0 -305
  102. package/src/gen/virtru/policy/objects_pb.ts +0 -253
  103. package/src/gen/web-admin/v1/config_connect.ts +0 -52
  104. package/src/gen/web-admin/v1/config_pb.ts +0 -173
  105. package/src/index.ts +0 -62
  106. package/src/lib/client.ts +0 -90
  107. package/src/lib/consts.ts +0 -8
  108. package/src/lib/dsp.ts +0 -65
  109. package/src/lib/fips-crypto/asymmetric.ts +0 -162
  110. package/src/lib/fips-crypto/key-format.ts +0 -287
  111. package/src/lib/fips-crypto/keys.ts +0 -190
  112. package/src/lib/fips-crypto/primitives.ts +0 -197
  113. package/src/lib/fips-crypto/symmetric.ts +0 -213
  114. package/src/lib/fips-crypto-service.ts +0 -58
  115. package/src/lib/utils.test.ts +0 -415
  116. package/src/lib/utils.ts +0 -525
  117. package/src/vite-env.d.ts +0 -7
  118. package/temp/build/lint/_eslint-5eVG3S6w.json +0 -38
  119. package/temp/test/jest/haste-map-b055a9550e6d9f9b43d8ad29b1607278-49d19aee56a0732eca9c014a51272338-8710993d07b75a801b0956e67ffc46fa +0 -0
  120. package/tests/dsp-client.test.ts +0 -95
  121. package/tests/dsp.test.ts +0 -119
  122. package/tests/fips-crypto.unit.test.ts +0 -412
  123. package/tests/mocks/create-export-artifacts.ts +0 -16
  124. package/tests/mocks/tagging-pdp-tag.ts +0 -13
  125. package/tests/mocks/well-known-configuration.ts +0 -15
  126. package/tests/setup-msw.ts +0 -35
  127. package/tests/setup-unit.ts +0 -108
  128. package/tsconfig.json +0 -32
  129. package/update-protos.sh +0 -63
  130. package/vitest.config.ts +0 -48
package/src/lib/utils.ts DELETED
@@ -1,525 +0,0 @@
1
- /*
2
- * Copyright (c) Virtru Corporation. All rights reserved.
3
- *
4
- * Your use of this file is governed by the Virtu Terms of Service <https://www.virtru.com/terms-of-service/>.
5
- */
6
-
7
- import type { AuthProvider } from '@opentdf/sdk';
8
- import {
9
- AuthProviders,
10
- OpenTDF,
11
- PermissionDeniedError,
12
- type Source,
13
- } from '@opentdf/sdk';
14
- import { type CryptoService, WebCryptoService } from '@opentdf/sdk/singlecontainer';
15
- import { PlatformClient } from '@opentdf/sdk/platform';
16
- import { ActiveStateEnum } from '@opentdf/sdk/platform/common/common_pb.js';
17
- import type { Certificate } from '../gen/virtru/policy/objects_pb';
18
- import type { Interceptor as Inter } from '@connectrpc/connect';
19
- import * as asn1js from 'asn1js';
20
- import * as pkijs from 'pkijs';
21
- import { MAX_CERT_BYTES, MAX_CERTS } from './consts';
22
- import { DSPClient } from './client';
23
-
24
- export type Interceptor = Inter;
25
-
26
- export type ObligationFeatureMap = {
27
- fully_qualified_names: string[];
28
- };
29
-
30
- export type SupportedObligations = {
31
- watermark?: ObligationFeatureMap;
32
- prevent_download?: ObligationFeatureMap;
33
- };
34
-
35
- export type GetUserEntitlementsResponse = {
36
- entitlements: {
37
- entityId: string;
38
- attributeValueFqns: string[];
39
- }[];
40
- };
41
-
42
- /**
43
- * Creates an interceptor that adds authentication headers to outgoing requests.
44
- *
45
- * This function uses the provided `AuthProvider` to generate authentication credentials
46
- * for each request. The `AuthProvider` is expected to implement a `withCreds` method
47
- * that returns an object containing authentication headers. These headers are then
48
- * added to the request before it is sent to the server.
49
- *
50
- * @param authProvider - An instance of `AuthProvider` used to generate authentication credentials.
51
- * @returns An `Interceptor` function that modifies requests to include authentication headers.
52
- */
53
-
54
- export function createAuthInterceptor(authProvider: AuthProvider, _cryptoService?: CryptoService): Interceptor {
55
- return (next) => async (req) => {
56
- const url = new URL(req.url);
57
- const pathOnly = url.pathname;
58
- // Signs only the path of the url in the request
59
- const token = await authProvider.withCreds({
60
- url: pathOnly,
61
- method: 'POST',
62
- headers: {
63
- 'Content-Type': 'application/json',
64
- },
65
- });
66
-
67
- Object.entries(token.headers).forEach(([key, value]) => {
68
- req.header.set(key, value);
69
- });
70
-
71
- return await next(req);
72
- };
73
- }
74
-
75
- /** Creates a new instance of an OIDC Auth Provider consumed by the TDF Clients */
76
- export async function createAuthProvider(options: {
77
- oidc: {
78
- clientId: string;
79
- tokenEndpoint: string;
80
- userInfoEndpoint: string;
81
- };
82
- refreshToken: string;
83
- cryptoService?: CryptoService;
84
- }): Promise<AuthProviders.OIDCRefreshTokenProvider> {
85
- const { oidc, refreshToken } = options;
86
-
87
- return await AuthProviders.refreshAuthProvider({
88
- clientId: oidc.clientId,
89
- exchange: 'refresh',
90
- refreshToken: refreshToken,
91
- // TODO(DSPX-1559): Clean up these URLs.
92
- oidcOrigin: 'https://only-required-for-back-compat.invalid',
93
- oidcTokenEndpoint: oidc.tokenEndpoint,
94
- oidcUserInfoEndpoint: oidc.userInfoEndpoint,
95
- });
96
- }
97
-
98
- export async function createOpenTDFClient(options: {
99
- oidc: {
100
- clientId: string;
101
- tokenEndpoint: string;
102
- userInfoEndpoint: string;
103
- };
104
- platformEndpoint: string;
105
- refreshToken: string;
106
- obligations: string[];
107
- cryptoService?: CryptoService;
108
- }) {
109
- const { platformEndpoint, obligations, ...authProviderOptions } = options;
110
- return new OpenTDF({
111
- authProvider: await createAuthProvider(authProviderOptions),
112
- platformUrl: platformEndpoint,
113
- policyEndpoint: platformEndpoint,
114
- defaultCreateOptions: {
115
- defaultKASEndpoint: `${platformEndpoint}/kas`,
116
- },
117
- defaultReadOptions: {
118
- fulfillableObligationFQNs: obligations,
119
- // NOTE(DSP-249): Disabling assertion verification until all generated assertions are supported.
120
- noVerify: true,
121
- },
122
- disableDPoP: true,
123
- cryptoService: options.cryptoService,
124
- });
125
- }
126
-
127
- export const getObligations = async (
128
- ciphertext: ArrayBuffer,
129
- options: {
130
- oidc: {
131
- clientId: string;
132
- tokenEndpoint: string;
133
- userInfoEndpoint: string;
134
- };
135
- platformEndpoint: string;
136
- refreshToken: string;
137
- obligations: string[];
138
- cryptoService?: CryptoService;
139
- }
140
- ): Promise<string[]> => {
141
- const client = await createOpenTDFClient(options);
142
- const source: Source = {
143
- type: 'buffer',
144
- location: new Uint8Array(ciphertext),
145
- };
146
- const tdfReader = client.open({ source });
147
- let obligations: string[] = [];
148
- try {
149
- obligations = (await tdfReader.obligations()).fqns;
150
- } catch (error) {
151
- if (error instanceof PermissionDeniedError) {
152
- obligations = error.requiredObligations || [];
153
- }
154
- // Swallow other errors and return empty obligations.
155
- }
156
- return obligations;
157
- };
158
-
159
- export async function getUserEntitlements(options: {
160
- oidc: {
161
- clientId: string;
162
- tokenEndpoint: string;
163
- userInfoEndpoint: string;
164
- };
165
- platformEndpoint: string;
166
- refreshToken: string;
167
- cryptoService?: CryptoService;
168
- }) {
169
- const authProvider = await createAuthProvider({
170
- oidc: options.oidc,
171
- refreshToken: options.refreshToken,
172
- cryptoService: options.cryptoService,
173
- });
174
- const accessToken = await authProvider.oidcAuth.get();
175
- const userEntitlementsResponse = await fetch(
176
- `${options.platformEndpoint}/shared/entitlements`,
177
- {
178
- body: JSON.stringify({}),
179
- headers: {
180
- Authorization: `Bearer ${accessToken}`,
181
- 'Content-Type': 'application/json',
182
- },
183
- method: 'POST',
184
- }
185
- );
186
-
187
- return (await userEntitlementsResponse.json()) as GetUserEntitlementsResponse;
188
- }
189
-
190
- export const flattenObligations = (
191
- obligations: SupportedObligations
192
- ): string[] =>
193
- Object.values(obligations).flatMap(
194
- (feature: ObligationFeatureMap) => feature?.fully_qualified_names || []
195
- );
196
-
197
- /**
198
- * Helper function to retrieve certificates for a specific namespace with pagination handling.
199
- *
200
- * This function automatically handles pagination to retrieve all certificates for a namespace,
201
- * making multiple requests if necessary.
202
- *
203
- * @param dspClient - The DSP client instance.
204
- * @param namespaceId - The namespace UUID.
205
- * @returns A promise that resolves to an array of certificates for the namespace.
206
- * @throws If there is an error retrieving the certificates from the CertificateService.
207
- */
208
- async function getCertificatesForNamespace(
209
- dspClient: DSPClient,
210
- namespaceId: string
211
- ): Promise<Certificate[]> {
212
- const certificates: Certificate[] = [];
213
- let offset = 0;
214
- const limit = 100;
215
-
216
- while (true) {
217
- const response =
218
- await dspClient.v1.certificateService.listCertificatesByNamespace({
219
- namespaceId,
220
- pagination: { limit, offset },
221
- });
222
-
223
- if (response.certificates?.length > 0) {
224
- certificates.push(...response.certificates);
225
- }
226
-
227
- // Check for more pages
228
- if (response.pagination?.nextOffset && response.pagination.nextOffset > 0) {
229
- offset = response.pagination.nextOffset;
230
- } else {
231
- break;
232
- }
233
- }
234
-
235
- return certificates;
236
- }
237
-
238
- /**
239
- * Retrieves all trusted certificates from active namespaces in the platform.
240
- *
241
- * This function uses the new CertificateService API to retrieve certificates from all active
242
- * namespaces. It automatically handles pagination to ensure all certificates are retrieved.
243
- *
244
- * The function performs the following steps:
245
- * 1. Creates an authenticated auth provider with DPoP signing keys
246
- * 2. Lists all active namespaces using the PlatformClient
247
- * 3. For each namespace, retrieves all associated certificates using the CertificateService
248
- * 4. Aggregates and returns all certificates from all namespaces
249
- *
250
- * @param options - The options object containing the platform endpoint, OIDC configuration, and refresh token.
251
- * @param options.oidc - The OIDC configuration object.
252
- * @param options.oidc.clientId - The OIDC client ID.
253
- * @param options.oidc.tokenEndpoint - The OIDC token endpoint URL.
254
- * @param options.oidc.userInfoEndpoint - The OIDC user info endpoint URL.
255
- * @param options.platformEndpoint - The base URL of the platform.
256
- * @param options.refreshToken - The refresh token for authentication.
257
- * @returns A promise that resolves to an array of trusted certificates from all active namespaces.
258
- * @throws If there is an error retrieving namespaces or certificates.
259
- *
260
- * @example
261
- * ```typescript
262
- * const certificates = await getTrustedCertificates({
263
- * oidc: {
264
- * clientId: 'my-client-id',
265
- * tokenEndpoint: 'https://auth.example.com/token',
266
- * userInfoEndpoint: 'https://auth.example.com/userinfo',
267
- * },
268
- * platformEndpoint: 'https://platform.example.com',
269
- * refreshToken: 'my-refresh-token',
270
- * });
271
- * ```
272
- */
273
- export async function getTrustedCertificates(options: {
274
- oidc: {
275
- clientId: string;
276
- tokenEndpoint: string;
277
- userInfoEndpoint: string;
278
- };
279
- platformEndpoint: string;
280
- refreshToken: string;
281
- cryptoService?: CryptoService;
282
- }): Promise<Certificate[]> {
283
- const cs = options.cryptoService ?? WebCryptoService;
284
-
285
- const authProvider = await createAuthProvider({
286
- oidc: options.oidc,
287
- refreshToken: options.refreshToken,
288
- cryptoService: options.cryptoService,
289
- });
290
- await authProvider.updateClientPublicKey(await cs.generateSigningKeyPair());
291
-
292
- // Create both clients
293
- const platform = new PlatformClient({
294
- authProvider,
295
- platformUrl: options.platformEndpoint,
296
- });
297
-
298
- const dspClient = new DSPClient({
299
- platformUrl: options.platformEndpoint,
300
- authProvider,
301
- });
302
-
303
- const certificates: Certificate[] = [];
304
-
305
- try {
306
- // Get active namespaces (still using namespace API)
307
- const namespaces = await platform.v1.namespace.listNamespaces({
308
- state: ActiveStateEnum.ACTIVE,
309
- });
310
-
311
- // Get certificates using new CertificateService API
312
- for (const namespace of namespaces.namespaces) {
313
- const namespaceCerts = await getCertificatesForNamespace(
314
- dspClient,
315
- namespace.id
316
- );
317
- certificates.push(...namespaceCerts);
318
- }
319
- } catch (error) {
320
- throw error;
321
- }
322
-
323
- return certificates;
324
- }
325
-
326
- /**
327
- * Helper to get a string representation of a pkijs Name.
328
- */
329
- function getNameStringSafe(
330
- name: pkijs.RelativeDistinguishedNames | undefined
331
- ): string {
332
- if (!name) return '';
333
- try {
334
- // pkijs Name to string can be derived from typesAndValues
335
- const parts = (name.typesAndValues || []).map((tv: any) => {
336
- const type = tv?.type ?? 'unknownType';
337
- // tv.value is an ASN.1 value; best-effort toString fallback
338
- let value: string;
339
- try {
340
- const block = tv?.value?.valueBlock;
341
- const v = block?.value;
342
- value = typeof v === 'string' ? v : String(tv?.value);
343
- } catch {
344
- value = '<?>';
345
- }
346
- return `${type}=${value}`;
347
- });
348
- return parts.join(', ');
349
- } catch {
350
- return '';
351
- }
352
- }
353
-
354
- export type JWSValidationResult = {
355
- valid: boolean;
356
- validationResult: Record<string, string[]>;
357
- };
358
-
359
- function base64ToArrayBuffer(b64: string): ArrayBuffer {
360
- const normalized = b64.replace(/\s+/g, '');
361
- // Basic sanity check; allow trailing '=' padding
362
- if (!/^[-A-Za-z0-9+/]*=*$/.test(normalized)) {
363
- throw new Error('Invalid base64 characters');
364
- }
365
- // Optional size guard (approx: 3/4 of base64 length is bytes)
366
- const approxBytes = Math.floor((normalized.length * 3) / 4);
367
- if (approxBytes === 0) {
368
- throw new Error('Empty base64 data');
369
- }
370
- if (approxBytes > MAX_CERT_BYTES) {
371
- throw new Error(
372
- `Certificate exceeds maximum allowed size of ${MAX_CERT_BYTES} bytes`
373
- );
374
- }
375
- const binaryString = atob(normalized);
376
- const bytes = new Uint8Array(binaryString.length);
377
- for (let i = 0; i < binaryString.length; i++) {
378
- bytes[i] = binaryString.charCodeAt(i);
379
- }
380
- return bytes.buffer; // bytes is freshly allocated; buffer is tightly packed
381
- }
382
-
383
- function pemToArrayBuffer(pem: string): ArrayBuffer {
384
- const base64Der = pem
385
- .replace(/-----BEGIN CERTIFICATE-----/g, '')
386
- .replace(/-----END CERTIFICATE-----/g, '')
387
- .replace(/\r?\n|\r|\s/g, '');
388
- return base64ToArrayBuffer(base64Der);
389
- }
390
-
391
- /**
392
- * Validate that a certificate chain from JWS x5c header chains to a trusted root.
393
- *
394
- * This function is designed to be portable and can be moved to another repository.
395
- * It validates that the certificate chain presented in a JWS x5c header builds a
396
- * valid chain to one of the provided trusted root certificates.
397
- *
398
- * Expectations and behavior:
399
- * - `x5c` must be ordered leaf-first and contain base64-encoded DER certs.
400
- * - `trustedRootCertificates` should contain PEM-encoded root certificates.
401
- * - Performs basic input size checks and safe base64 decoding.
402
- * - Uses PKI.js `CertificateChainValidationEngine` for comprehensive path validation
403
- * (validity dates, signatures, policies when present, etc.).
404
- * - Returns detailed error messages including the leaf subject/issuer and parsing warnings.
405
- *
406
- * @param x5c - Array of base64-encoded DER certificates from JWS header (leaf first)
407
- * @param trustedRootCertificates - Array of Certificate objects containing trusted roots in PEM format
408
- * @returns Object with validation result and warnings
409
- * @throws {Error} if validation fails
410
- *
411
- * @example
412
- * ```typescript
413
- * try {
414
- * const result = await validateJWSCertificateChain(
415
- * jwsHeader.x5c,
416
- * namespaceCertificates
417
- * );
418
- * console.log('Chain validates to trusted root', result.validationResult.warnings);
419
- * } catch (error) {
420
- * console.error('Validation failed:', error.message);
421
- * }
422
- * ```
423
- */
424
- export async function validateJWSCertificateChain(
425
- x5c: string[],
426
- trustedRootCertificates: Certificate[],
427
- _cryptoService?: CryptoService
428
- ): Promise<JWSValidationResult> {
429
- const warnings: string[] = [];
430
-
431
- try {
432
- // Validate inputs
433
- if (!Array.isArray(x5c) || x5c.length === 0) {
434
- throw new Error('No certificates provided in x5c array');
435
- }
436
- if (x5c.length > MAX_CERTS) {
437
- throw new Error(`Too many certificates in x5c (max ${MAX_CERTS})`);
438
- }
439
- if (
440
- !Array.isArray(trustedRootCertificates) ||
441
- trustedRootCertificates.length === 0
442
- ) {
443
- throw new Error('No trusted root certificates provided');
444
- }
445
-
446
- // Parse chain certs (base64 DER)
447
- const chainCertificates: pkijs.Certificate[] = [];
448
- for (let i = 0; i < x5c.length; i++) {
449
- const certBase64 = x5c[i];
450
- try {
451
- const certBuffer = base64ToArrayBuffer(certBase64);
452
- const asn1 = asn1js.fromBER(certBuffer);
453
- if (asn1.offset === -1) {
454
- throw new Error(`Invalid DER encoding for certificate at x5c[${i}]`);
455
- }
456
- chainCertificates.push(new pkijs.Certificate({ schema: asn1.result }));
457
- } catch (err) {
458
- const msg = err instanceof Error ? err.message : 'Unknown error';
459
- throw new Error(`Failed to parse certificate at x5c[${i}]: ${msg}`);
460
- }
461
- }
462
-
463
- // Parse trusted roots (PEM)
464
- const trustedCerts: pkijs.Certificate[] = [];
465
- for (let i = 0; i < trustedRootCertificates.length; i++) {
466
- const rootCert = trustedRootCertificates[i];
467
- try {
468
- const pem = (rootCert as any).pem as string | undefined;
469
- if (!pem || pem.trim().length === 0) {
470
- warnings.push(`Trusted root at index ${i} has no PEM data; skipping`);
471
- continue;
472
- }
473
- const certBuffer = pemToArrayBuffer(pem);
474
- const asn1 = asn1js.fromBER(certBuffer);
475
- if (asn1.offset === -1) {
476
- warnings.push(`Trusted root at index ${i} has invalid DER; skipping`);
477
- continue;
478
- }
479
- trustedCerts.push(new pkijs.Certificate({ schema: asn1.result }));
480
- } catch (err) {
481
- const msg = err instanceof Error ? err.message : 'Unknown error';
482
- warnings.push(`Failed to parse trusted root at index ${i}: ${msg}`);
483
- }
484
- }
485
-
486
- if (trustedCerts.length === 0) {
487
- throw new Error('No valid trusted root certificates could be parsed');
488
- }
489
-
490
- // Build and verify certificate chain using PKI.js
491
- const chainEngine = new pkijs.CertificateChainValidationEngine({
492
- trustedCerts,
493
- certs: chainCertificates,
494
- checkDate: new Date(),
495
- });
496
-
497
- const verificationResult = await chainEngine.verify();
498
- if (!verificationResult.result) {
499
- // Compose detailed message
500
- const leaf = chainCertificates[0];
501
- const leafSubject = getNameStringSafe(leaf.subject);
502
- const leafIssuer = getNameStringSafe(leaf.issuer);
503
- const baseMsg =
504
- verificationResult.resultMessage ||
505
- 'Certificate chain validation failed';
506
- throw new Error(
507
- `${baseMsg} (leaf subject='${leafSubject}', issuer='${leafIssuer}')`
508
- );
509
- }
510
-
511
- return {
512
- valid: true,
513
- validationResult: {
514
- warnings,
515
- errors: [],
516
- },
517
- };
518
- } catch (error) {
519
- const msg = error instanceof Error ? error.message : 'Unknown error';
520
- const warnSuffix = warnings.length
521
- ? `; warnings: ${warnings.join(' | ')}`
522
- : '';
523
- throw new Error(`Validation error: ${msg}${warnSuffix}`);
524
- }
525
- }
package/src/vite-env.d.ts DELETED
@@ -1,7 +0,0 @@
1
- /*
2
- * Copyright (c) Virtru Corporation. All rights reserved.
3
- *
4
- * Your use of this file is governed by the Virtu Terms of Service <https://www.virtru.com/terms-of-service/>.
5
- */
6
-
7
- /// <reference types="vite/client" />
@@ -1,38 +0,0 @@
1
- {
2
- "cacheVersion": "9.39.3_v22.20.0",
3
- "fileVersions": [
4
- [
5
- "tests/mocks/tagging-pdp-tag.ts",
6
- "0TIytF72WOsx6WUt4FS95Kjjc8M=_KBnhlqHDJygGymeSAMhfjnUj064="
7
- ],
8
- [
9
- "tests/mocks/create-export-artifacts.ts",
10
- "lwszirUbVVEn8blGPnAheNMD1M0=_KBnhlqHDJygGymeSAMhfjnUj064="
11
- ],
12
- [
13
- "tests/dsp-client.test.ts",
14
- "6V91AliuHKY80qNjP5pei3a5GDs=_KBnhlqHDJygGymeSAMhfjnUj064="
15
- ],
16
- [
17
- "tests/mocks/well-known-configuration.ts",
18
- "NPWElstpsX6yX0j72aHwIW+jC6o=_KBnhlqHDJygGymeSAMhfjnUj064="
19
- ],
20
- [
21
- "tests/dsp.test.ts",
22
- "72K1himJItp7yd9dkZNa7RwUmQo=_KBnhlqHDJygGymeSAMhfjnUj064="
23
- ],
24
- [
25
- "tests/fips-crypto.unit.test.ts",
26
- "eStngPGfsHlKIOfJ2k1WkUpqFX0=_KBnhlqHDJygGymeSAMhfjnUj064="
27
- ],
28
- [
29
- "tests/setup-msw.ts",
30
- "Sz1wiT3itCcl8Bpq5hnfs4hPjuo=_KBnhlqHDJygGymeSAMhfjnUj064="
31
- ],
32
- [
33
- "tests/setup-unit.ts",
34
- "Hb3n5KLyWlQyrMYmNx9grgPHBCU=_KBnhlqHDJygGymeSAMhfjnUj064="
35
- ]
36
- ],
37
- "filesHash": "flOfsEjcUy5GStpiBEHpfg"
38
- }
@@ -1,95 +0,0 @@
1
- /*
2
- * Copyright (c) Virtru Corporation. All rights reserved.
3
- *
4
- * Your use of this file is governed by the Virtu Terms of Service <https://www.virtru.com/terms-of-service/>.
5
- */
6
-
7
- import { expect, test, vi, beforeEach } from 'vitest';
8
- import { DSPClient } from '../src/index';
9
- import { mockTaggingPDPResponse } from './mocks/tagging-pdp-tag';
10
- import { mockCreateExportArtifactsResponse } from './mocks/create-export-artifacts';
11
-
12
- const platformUrl = 'https://dsp.example.com';
13
-
14
- // Mock fetch globally
15
- const mockFetch = vi.fn();
16
- global.fetch = mockFetch;
17
-
18
- beforeEach(() => {
19
- mockFetch.mockReset();
20
-
21
- // Setup default mock responses
22
- mockFetch.mockImplementation(async (url: string) => {
23
- if (url.includes('/tagging.pdp.v2.TaggingPDPService/Tag')) {
24
- return {
25
- ok: true,
26
- status: 200,
27
- json: async () => mockTaggingPDPResponse(),
28
- headers: new Headers({
29
- 'Content-Type': 'application/json',
30
- }),
31
- };
32
- }
33
-
34
- if (
35
- url.includes(
36
- '/policyimportexport.v1.PolicyArtifactService/CreateExportArtifacts'
37
- )
38
- ) {
39
- return {
40
- ok: true,
41
- status: 200,
42
- json: async () => mockCreateExportArtifactsResponse(),
43
- headers: new Headers({
44
- 'Content-Type': 'application/json',
45
- }),
46
- };
47
- }
48
-
49
- return {
50
- ok: false,
51
- status: 404,
52
- json: async () => ({}),
53
- headers: new Headers(),
54
- };
55
- });
56
- });
57
-
58
- test('should create a new DSPClient instance with platformUrl', async () => {
59
- const client = new DSPClient({ platformUrl });
60
- expect(client).toBeInstanceOf(DSPClient);
61
- });
62
-
63
- test('should throw an error if platformUrl is not provided', async () => {
64
- expect(() => new DSPClient({} as never)).toThrowError(
65
- 'platformUrl is required for DSP client'
66
- );
67
- });
68
-
69
- test('should perform RPC calls using the taggingPDPService', async () => {
70
- const client = new DSPClient({ platformUrl });
71
- expect(client).toBeInstanceOf(DSPClient);
72
- const result = await client.v2.taggingPDPService.tag({});
73
- expect(result.$typeName).toBe('tagging.pdp.v2.TaggingPDPResponse');
74
- });
75
-
76
- test('should perform RPC calls using the policyArtifactService', async () => {
77
- const client = new DSPClient({ platformUrl });
78
- expect(client).toBeInstanceOf(DSPClient);
79
- const result = await client.v1.policyArtifactService.createExportArtifacts(
80
- {}
81
- );
82
- expect(result.$typeName).toBe(
83
- 'policyimportexport.v1.CreateExportArtifactsResponse'
84
- );
85
- });
86
-
87
- test('should use provided interceptors when making RPC calls', async () => {
88
- const mockInterceptor = vi.fn((next) => next);
89
- const client = new DSPClient({
90
- platformUrl,
91
- interceptors: [mockInterceptor],
92
- });
93
- await client.v2.taggingPDPService.tag({});
94
- expect(mockInterceptor).toHaveBeenCalled();
95
- });