@virtru/dsp-sdk 0.4.1 → 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 (123) hide show
  1. package/CHANGELOG.md +15 -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/dist/src/lib/fips-crypto/asymmetric.d.ts +35 -0
  8. package/dist/src/lib/fips-crypto/asymmetric.js +116 -0
  9. package/dist/src/lib/fips-crypto/key-format.d.ts +51 -0
  10. package/dist/src/lib/fips-crypto/key-format.js +233 -0
  11. package/dist/src/lib/fips-crypto/keys.d.ts +26 -0
  12. package/dist/src/lib/fips-crypto/keys.js +123 -0
  13. package/dist/src/lib/fips-crypto/primitives.d.ts +41 -0
  14. package/dist/src/lib/fips-crypto/primitives.js +105 -0
  15. package/dist/src/lib/fips-crypto/symmetric.d.ts +61 -0
  16. package/dist/src/lib/fips-crypto/symmetric.js +152 -0
  17. package/dist/src/lib/fips-crypto-service.d.ts +5 -0
  18. package/dist/src/lib/fips-crypto-service.js +44 -0
  19. package/dist/src/lib/utils.d.ts +8 -2
  20. package/dist/src/lib/utils.js +8 -9
  21. package/package.json +31 -5
  22. package/.prettierrc +0 -3
  23. package/.rush/temp/chunked-rush-logs/dsp-sdk._phase_build.chunks.jsonl +0 -12
  24. package/.rush/temp/chunked-rush-logs/dsp-sdk._phase_test.chunks.jsonl +0 -43
  25. package/.rush/temp/package-deps__phase_build.json +0 -68
  26. package/.rush/temp/shrinkwrap-deps.json +0 -1257
  27. package/CHANGELOG.json +0 -278
  28. package/buf.gen.yaml +0 -17
  29. package/buf.yaml +0 -4
  30. package/config/jest.config.json +0 -6
  31. package/config/rig.json +0 -8
  32. package/dist/tests/dsp-client.test.d.ts +0 -1
  33. package/dist/tests/dsp-client.test.js +0 -73
  34. package/dist/tests/dsp.test.d.ts +0 -1
  35. package/dist/tests/dsp.test.js +0 -92
  36. package/dist/tests/mocks/create-export-artifacts.d.ts +0 -2
  37. package/dist/tests/mocks/create-export-artifacts.js +0 -13
  38. package/dist/tests/mocks/tagging-pdp-tag.d.ts +0 -2
  39. package/dist/tests/mocks/tagging-pdp-tag.js +0 -11
  40. package/dist/tests/mocks/well-known-configuration.d.ts +0 -2
  41. package/dist/tests/mocks/well-known-configuration.js +0 -12
  42. package/dist/tests/setup-msw.d.ts +0 -9
  43. package/dist/tests/setup-msw.js +0 -30
  44. package/eslint.config.mjs +0 -28
  45. package/lib-commonjs/src/gen/buf/validate/validate_pb.js +0 -487
  46. package/lib-commonjs/src/gen/config/v1/config_pb.js +0 -142
  47. package/lib-commonjs/src/gen/config/v1/kas_config_pb.js +0 -72
  48. package/lib-commonjs/src/gen/config/v1/meta_pb.js +0 -36
  49. package/lib-commonjs/src/gen/config/v1/outlook_config_pb.js +0 -67
  50. package/lib-commonjs/src/gen/config/v1/secureviewer_config_pb.js +0 -67
  51. package/lib-commonjs/src/gen/config/v1/tagging_pb.js +0 -246
  52. package/lib-commonjs/src/gen/google/api/annotations_pb.js +0 -33
  53. package/lib-commonjs/src/gen/google/api/http_pb.js +0 -44
  54. package/lib-commonjs/src/gen/policyimportexport/v1/policy_import_export_pb.js +0 -93
  55. package/lib-commonjs/src/gen/shared/v1/shared_pb.js +0 -95
  56. package/lib-commonjs/src/gen/tagging/pdp/v2/tagging_pb.js +0 -277
  57. package/lib-commonjs/src/gen/version/v1/version_pb.js +0 -40
  58. package/lib-commonjs/src/gen/virtru/common/common_pb.js +0 -76
  59. package/lib-commonjs/src/gen/virtru/policy/certificates/v1/certificates_pb.js +0 -77
  60. package/lib-commonjs/src/gen/virtru/policy/objects_pb.js +0 -143
  61. package/lib-commonjs/src/index.js +0 -48
  62. package/lib-commonjs/src/lib/client.js +0 -66
  63. package/lib-commonjs/src/lib/consts.js +0 -10
  64. package/lib-commonjs/src/lib/dsp.js +0 -49
  65. package/lib-commonjs/src/lib/utils.js +0 -402
  66. package/lib-commonjs/tests/dsp-client.test.js +0 -75
  67. package/lib-commonjs/tests/dsp.test.js +0 -94
  68. package/lib-commonjs/tests/mocks/create-export-artifacts.js +0 -17
  69. package/lib-commonjs/tests/mocks/tagging-pdp-tag.js +0 -15
  70. package/lib-commonjs/tests/mocks/well-known-configuration.js +0 -16
  71. package/lib-commonjs/tests/setup-msw.js +0 -33
  72. package/src/gen/buf/validate/validate_pb.ts +0 -4879
  73. package/src/gen/config/formatters/testdata/v1/test_pb.ts +0 -287
  74. package/src/gen/config/v1/config_connect.ts +0 -111
  75. package/src/gen/config/v1/config_pb.ts +0 -439
  76. package/src/gen/config/v1/kas_config_pb.ts +0 -183
  77. package/src/gen/config/v1/meta_pb.ts +0 -72
  78. package/src/gen/config/v1/outlook_config_pb.ts +0 -242
  79. package/src/gen/config/v1/secureviewer_config_pb.ts +0 -161
  80. package/src/gen/config/v1/tagging_pb.ts +0 -456
  81. package/src/gen/google/api/annotations_pb.ts +0 -43
  82. package/src/gen/google/api/http_pb.ts +0 -486
  83. package/src/gen/helloworld/v1/helloworld_connect.ts +0 -49
  84. package/src/gen/helloworld/v1/helloworld_pb.ts +0 -104
  85. package/src/gen/kas/nanotdf/v1/nanotdf_rewrap_connect.ts +0 -39
  86. package/src/gen/kas/nanotdf/v1/nanotdf_rewrap_pb.ts +0 -207
  87. package/src/gen/policyimportexport/v1/policy_import_export_connect.ts +0 -56
  88. package/src/gen/policyimportexport/v1/policy_import_export_pb.ts +0 -332
  89. package/src/gen/shared/v1/shared_connect.ts +0 -61
  90. package/src/gen/shared/v1/shared_pb.ts +0 -240
  91. package/src/gen/shared/v2/shared_connect.ts +0 -39
  92. package/src/gen/shared/v2/shared_pb.ts +0 -122
  93. package/src/gen/tagging/pdp/v2/externalprocessors/processor_connect.ts +0 -156
  94. package/src/gen/tagging/pdp/v2/externalprocessors/processor_pb.ts +0 -709
  95. package/src/gen/tagging/pdp/v2/stanag/stanag_pb.ts +0 -953
  96. package/src/gen/tagging/pdp/v2/tagging_connect.ts +0 -73
  97. package/src/gen/tagging/pdp/v2/tagging_pb.ts +0 -1064
  98. package/src/gen/version/v1/version_connect.ts +0 -31
  99. package/src/gen/version/v1/version_pb.ts +0 -143
  100. package/src/gen/virtru/common/common_pb.ts +0 -201
  101. package/src/gen/virtru/policy/certificates/v1/certificates_connect.ts +0 -44
  102. package/src/gen/virtru/policy/certificates/v1/certificates_pb.ts +0 -305
  103. package/src/gen/virtru/policy/objects_pb.ts +0 -253
  104. package/src/gen/web-admin/v1/config_connect.ts +0 -52
  105. package/src/gen/web-admin/v1/config_pb.ts +0 -173
  106. package/src/index.ts +0 -62
  107. package/src/lib/client.ts +0 -90
  108. package/src/lib/consts.ts +0 -8
  109. package/src/lib/dsp.ts +0 -65
  110. package/src/lib/utils.test.ts +0 -412
  111. package/src/lib/utils.ts +0 -524
  112. package/src/vite-env.d.ts +0 -7
  113. package/temp/build/lint/_eslint-5eVG3S6w.json +0 -30
  114. package/temp/test/jest/haste-map-b055a9550e6d9f9b43d8ad29b1607278-49d19aee56a0732eca9c014a51272338-8710993d07b75a801b0956e67ffc46fa +0 -0
  115. package/tests/dsp-client.test.ts +0 -95
  116. package/tests/dsp.test.ts +0 -119
  117. package/tests/mocks/create-export-artifacts.ts +0 -16
  118. package/tests/mocks/tagging-pdp-tag.ts +0 -13
  119. package/tests/mocks/well-known-configuration.ts +0 -15
  120. package/tests/setup-msw.ts +0 -35
  121. package/tsconfig.json +0 -32
  122. package/update-protos.sh +0 -63
  123. package/vitest.config.ts +0 -32
package/src/lib/utils.ts DELETED
@@ -1,524 +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 { PlatformClient } from '@opentdf/sdk/platform';
15
- import { ActiveStateEnum } from '@opentdf/sdk/platform/common/common_pb.js';
16
- import type { Certificate } from '../gen/virtru/policy/objects_pb';
17
- import type { Interceptor as Inter } from '@connectrpc/connect';
18
- import * as asn1js from 'asn1js';
19
- import * as pkijs from 'pkijs';
20
- import { MAX_CERT_BYTES, MAX_CERTS } from './consts';
21
- import { DSPClient } from './client';
22
-
23
- export type Interceptor = Inter;
24
-
25
- export type ObligationFeatureMap = {
26
- fully_qualified_names: string[];
27
- };
28
-
29
- export type SupportedObligations = {
30
- watermark?: ObligationFeatureMap;
31
- prevent_download?: ObligationFeatureMap;
32
- };
33
-
34
- export type GetUserEntitlementsResponse = {
35
- entitlements: {
36
- entityId: string;
37
- attributeValueFqns: string[];
38
- }[];
39
- };
40
-
41
- /**
42
- * Creates an interceptor that adds authentication headers to outgoing requests.
43
- *
44
- * This function uses the provided `AuthProvider` to generate authentication credentials
45
- * for each request. The `AuthProvider` is expected to implement a `withCreds` method
46
- * that returns an object containing authentication headers. These headers are then
47
- * added to the request before it is sent to the server.
48
- *
49
- * @param authProvider - An instance of `AuthProvider` used to generate authentication credentials.
50
- * @returns An `Interceptor` function that modifies requests to include authentication headers.
51
- */
52
-
53
- export function createAuthInterceptor(authProvider: AuthProvider): Interceptor {
54
- return (next) => async (req) => {
55
- const url = new URL(req.url);
56
- const pathOnly = url.pathname;
57
- // Signs only the path of the url in the request
58
- const token = await authProvider.withCreds({
59
- url: pathOnly,
60
- method: 'POST',
61
- headers: {
62
- 'Content-Type': 'application/json',
63
- },
64
- });
65
-
66
- Object.entries(token.headers).forEach(([key, value]) => {
67
- req.header.set(key, value);
68
- });
69
-
70
- return await next(req);
71
- };
72
- }
73
-
74
- /** Creates a new instance of an OIDC Auth Provider consumed by the TDF Clients */
75
- export async function createAuthProvider(options: {
76
- oidc: {
77
- clientId: string;
78
- tokenEndpoint: string;
79
- userInfoEndpoint: string;
80
- };
81
- refreshToken: string;
82
- }): Promise<AuthProviders.OIDCRefreshTokenProvider> {
83
- const { oidc, refreshToken } = options;
84
-
85
- return await AuthProviders.refreshAuthProvider({
86
- clientId: oidc.clientId,
87
- exchange: 'refresh',
88
- refreshToken: refreshToken,
89
- // TODO(DSPX-1559): Clean up these URLs.
90
- oidcOrigin: 'https://only-required-for-back-compat.invalid',
91
- oidcTokenEndpoint: oidc.tokenEndpoint,
92
- oidcUserInfoEndpoint: oidc.userInfoEndpoint,
93
- });
94
- }
95
-
96
- export async function createOpenTDFClient(options: {
97
- oidc: {
98
- clientId: string;
99
- tokenEndpoint: string;
100
- userInfoEndpoint: string;
101
- };
102
- platformEndpoint: string;
103
- refreshToken: string;
104
- obligations: string[];
105
- }) {
106
- const { platformEndpoint, obligations, ...authProviderOptions } = options;
107
- return new OpenTDF({
108
- authProvider: await createAuthProvider(authProviderOptions),
109
- platformUrl: platformEndpoint,
110
- policyEndpoint: platformEndpoint,
111
- defaultCreateOptions: {
112
- defaultKASEndpoint: `${platformEndpoint}/kas`,
113
- },
114
- defaultReadOptions: {
115
- fulfillableObligationFQNs: obligations,
116
- // NOTE(DSP-249): Disabling assertion verification until all generated assertions are supported.
117
- noVerify: true,
118
- },
119
- disableDPoP: true,
120
- });
121
- }
122
-
123
- export const getObligations = async (
124
- ciphertext: ArrayBuffer,
125
- options: {
126
- oidc: {
127
- clientId: string;
128
- tokenEndpoint: string;
129
- userInfoEndpoint: string;
130
- };
131
- platformEndpoint: string;
132
- refreshToken: string;
133
- obligations: string[];
134
- }
135
- ): Promise<string[]> => {
136
- const client = await createOpenTDFClient(options);
137
- const source: Source = {
138
- type: 'buffer',
139
- location: new Uint8Array(ciphertext),
140
- };
141
- const tdfReader = client.open({ source });
142
- let obligations: string[] = [];
143
- try {
144
- obligations = (await tdfReader.obligations()).fqns;
145
- } catch (error) {
146
- if (error instanceof PermissionDeniedError) {
147
- obligations = error.requiredObligations || [];
148
- }
149
- // Swallow other errors and return empty obligations.
150
- }
151
- return obligations;
152
- };
153
-
154
- export async function getUserEntitlements(options: {
155
- oidc: {
156
- clientId: string;
157
- tokenEndpoint: string;
158
- userInfoEndpoint: string;
159
- };
160
- platformEndpoint: string;
161
- refreshToken: string;
162
- }) {
163
- const authProvider = await createAuthProvider({
164
- oidc: options.oidc,
165
- refreshToken: options.refreshToken,
166
- });
167
- const accessToken = await authProvider.oidcAuth.get();
168
- const userEntitlementsResponse = await fetch(
169
- `${options.platformEndpoint}/shared/entitlements`,
170
- {
171
- body: JSON.stringify({}),
172
- headers: {
173
- Authorization: `Bearer ${accessToken}`,
174
- 'Content-Type': 'application/json',
175
- },
176
- method: 'POST',
177
- }
178
- );
179
-
180
- return (await userEntitlementsResponse.json()) as GetUserEntitlementsResponse;
181
- }
182
-
183
- export const flattenObligations = (
184
- obligations: SupportedObligations
185
- ): string[] =>
186
- Object.values(obligations).flatMap(
187
- (feature: ObligationFeatureMap) => feature?.fully_qualified_names || []
188
- );
189
-
190
- /**
191
- * Helper function to retrieve certificates for a specific namespace with pagination handling.
192
- *
193
- * This function automatically handles pagination to retrieve all certificates for a namespace,
194
- * making multiple requests if necessary.
195
- *
196
- * @param dspClient - The DSP client instance.
197
- * @param namespaceId - The namespace UUID.
198
- * @returns A promise that resolves to an array of certificates for the namespace.
199
- * @throws If there is an error retrieving the certificates from the CertificateService.
200
- */
201
- async function getCertificatesForNamespace(
202
- dspClient: DSPClient,
203
- namespaceId: string
204
- ): Promise<Certificate[]> {
205
- const certificates: Certificate[] = [];
206
- let offset = 0;
207
- const limit = 100;
208
-
209
- while (true) {
210
- const response =
211
- await dspClient.v1.certificateService.listCertificatesByNamespace({
212
- namespaceId,
213
- pagination: { limit, offset },
214
- });
215
-
216
- if (response.certificates?.length > 0) {
217
- certificates.push(...response.certificates);
218
- }
219
-
220
- // Check for more pages
221
- if (response.pagination?.nextOffset && response.pagination.nextOffset > 0) {
222
- offset = response.pagination.nextOffset;
223
- } else {
224
- break;
225
- }
226
- }
227
-
228
- return certificates;
229
- }
230
-
231
- /**
232
- * Retrieves all trusted certificates from active namespaces in the platform.
233
- *
234
- * This function uses the new CertificateService API to retrieve certificates from all active
235
- * namespaces. It automatically handles pagination to ensure all certificates are retrieved.
236
- *
237
- * The function performs the following steps:
238
- * 1. Creates an authenticated auth provider with DPoP signing keys
239
- * 2. Lists all active namespaces using the PlatformClient
240
- * 3. For each namespace, retrieves all associated certificates using the CertificateService
241
- * 4. Aggregates and returns all certificates from all namespaces
242
- *
243
- * @param options - The options object containing the platform endpoint, OIDC configuration, and refresh token.
244
- * @param options.oidc - The OIDC configuration object.
245
- * @param options.oidc.clientId - The OIDC client ID.
246
- * @param options.oidc.tokenEndpoint - The OIDC token endpoint URL.
247
- * @param options.oidc.userInfoEndpoint - The OIDC user info endpoint URL.
248
- * @param options.platformEndpoint - The base URL of the platform.
249
- * @param options.refreshToken - The refresh token for authentication.
250
- * @returns A promise that resolves to an array of trusted certificates from all active namespaces.
251
- * @throws If there is an error retrieving namespaces or certificates.
252
- *
253
- * @example
254
- * ```typescript
255
- * const certificates = await getTrustedCertificates({
256
- * oidc: {
257
- * clientId: 'my-client-id',
258
- * tokenEndpoint: 'https://auth.example.com/token',
259
- * userInfoEndpoint: 'https://auth.example.com/userinfo',
260
- * },
261
- * platformEndpoint: 'https://platform.example.com',
262
- * refreshToken: 'my-refresh-token',
263
- * });
264
- * ```
265
- */
266
- export async function getTrustedCertificates(options: {
267
- oidc: {
268
- clientId: string;
269
- tokenEndpoint: string;
270
- userInfoEndpoint: string;
271
- };
272
- platformEndpoint: string;
273
- refreshToken: string;
274
- }): Promise<Certificate[]> {
275
- function generateSigningKeyPair() {
276
- return crypto.subtle.generateKey(
277
- {
278
- name: 'ECDSA',
279
- namedCurve: 'P-256',
280
- },
281
- true,
282
- ['sign', 'verify']
283
- );
284
- }
285
-
286
- const authProvider = await createAuthProvider({
287
- oidc: options.oidc,
288
- refreshToken: options.refreshToken,
289
- });
290
- await authProvider.updateClientPublicKey(await 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
- ): Promise<JWSValidationResult> {
428
- const warnings: string[] = [];
429
-
430
- try {
431
- // Validate inputs
432
- if (!Array.isArray(x5c) || x5c.length === 0) {
433
- throw new Error('No certificates provided in x5c array');
434
- }
435
- if (x5c.length > MAX_CERTS) {
436
- throw new Error(`Too many certificates in x5c (max ${MAX_CERTS})`);
437
- }
438
- if (
439
- !Array.isArray(trustedRootCertificates) ||
440
- trustedRootCertificates.length === 0
441
- ) {
442
- throw new Error('No trusted root certificates provided');
443
- }
444
-
445
- // Parse chain certs (base64 DER)
446
- const chainCertificates: pkijs.Certificate[] = [];
447
- for (let i = 0; i < x5c.length; i++) {
448
- const certBase64 = x5c[i];
449
- try {
450
- const certBuffer = base64ToArrayBuffer(certBase64);
451
- const asn1 = asn1js.fromBER(certBuffer);
452
- if (asn1.offset === -1) {
453
- throw new Error(`Invalid DER encoding for certificate at x5c[${i}]`);
454
- }
455
- chainCertificates.push(new pkijs.Certificate({ schema: asn1.result }));
456
- } catch (err) {
457
- const msg = err instanceof Error ? err.message : 'Unknown error';
458
- throw new Error(`Failed to parse certificate at x5c[${i}]: ${msg}`);
459
- }
460
- }
461
-
462
- // Parse trusted roots (PEM)
463
- const trustedCerts: pkijs.Certificate[] = [];
464
- for (let i = 0; i < trustedRootCertificates.length; i++) {
465
- const rootCert = trustedRootCertificates[i];
466
- try {
467
- const pem = (rootCert as any).pem as string | undefined;
468
- if (!pem || pem.trim().length === 0) {
469
- warnings.push(`Trusted root at index ${i} has no PEM data; skipping`);
470
- continue;
471
- }
472
- const certBuffer = pemToArrayBuffer(pem);
473
- const asn1 = asn1js.fromBER(certBuffer);
474
- if (asn1.offset === -1) {
475
- warnings.push(`Trusted root at index ${i} has invalid DER; skipping`);
476
- continue;
477
- }
478
- trustedCerts.push(new pkijs.Certificate({ schema: asn1.result }));
479
- } catch (err) {
480
- const msg = err instanceof Error ? err.message : 'Unknown error';
481
- warnings.push(`Failed to parse trusted root at index ${i}: ${msg}`);
482
- }
483
- }
484
-
485
- if (trustedCerts.length === 0) {
486
- throw new Error('No valid trusted root certificates could be parsed');
487
- }
488
-
489
- // Build and verify certificate chain using PKI.js
490
- const chainEngine = new pkijs.CertificateChainValidationEngine({
491
- trustedCerts,
492
- certs: chainCertificates,
493
- checkDate: new Date(),
494
- });
495
-
496
- const verificationResult = await chainEngine.verify();
497
- if (!verificationResult.result) {
498
- // Compose detailed message
499
- const leaf = chainCertificates[0];
500
- const leafSubject = getNameStringSafe(leaf.subject);
501
- const leafIssuer = getNameStringSafe(leaf.issuer);
502
- const baseMsg =
503
- verificationResult.resultMessage ||
504
- 'Certificate chain validation failed';
505
- throw new Error(
506
- `${baseMsg} (leaf subject='${leafSubject}', issuer='${leafIssuer}')`
507
- );
508
- }
509
-
510
- return {
511
- valid: true,
512
- validationResult: {
513
- warnings,
514
- errors: [],
515
- },
516
- };
517
- } catch (error) {
518
- const msg = error instanceof Error ? error.message : 'Unknown error';
519
- const warnSuffix = warnings.length
520
- ? `; warnings: ${warnings.join(' | ')}`
521
- : '';
522
- throw new Error(`Validation error: ${msg}${warnSuffix}`);
523
- }
524
- }
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,30 +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/setup-msw.ts",
26
- "Sz1wiT3itCcl8Bpq5hnfs4hPjuo=_KBnhlqHDJygGymeSAMhfjnUj064="
27
- ]
28
- ],
29
- "filesHash": "ZUDFQlGnS2ya5rvcK6ruZA"
30
- }
@@ -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
- });