@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
@@ -1,402 +0,0 @@
1
- "use strict";
2
- /*
3
- * Copyright (c) Virtru Corporation. All rights reserved.
4
- *
5
- * Your use of this file is governed by the Virtu Terms of Service <https://www.virtru.com/terms-of-service/>.
6
- */
7
- Object.defineProperty(exports, "__esModule", { value: true });
8
- exports.flattenObligations = exports.getObligations = void 0;
9
- exports.createAuthInterceptor = createAuthInterceptor;
10
- exports.createAuthProvider = createAuthProvider;
11
- exports.createOpenTDFClient = createOpenTDFClient;
12
- exports.getUserEntitlements = getUserEntitlements;
13
- exports.getTrustedCertificates = getTrustedCertificates;
14
- exports.validateJWSCertificateChain = validateJWSCertificateChain;
15
- const sdk_1 = require("@opentdf/sdk");
16
- const platform_1 = require("@opentdf/sdk/platform");
17
- const common_pb_js_1 = require("@opentdf/sdk/platform/common/common_pb.js");
18
- const asn1js = require("asn1js");
19
- const pkijs = require("pkijs");
20
- const consts_1 = require("./consts");
21
- const client_1 = require("./client");
22
- /**
23
- * Creates an interceptor that adds authentication headers to outgoing requests.
24
- *
25
- * This function uses the provided `AuthProvider` to generate authentication credentials
26
- * for each request. The `AuthProvider` is expected to implement a `withCreds` method
27
- * that returns an object containing authentication headers. These headers are then
28
- * added to the request before it is sent to the server.
29
- *
30
- * @param authProvider - An instance of `AuthProvider` used to generate authentication credentials.
31
- * @returns An `Interceptor` function that modifies requests to include authentication headers.
32
- */
33
- function createAuthInterceptor(authProvider) {
34
- return (next) => async (req) => {
35
- const url = new URL(req.url);
36
- const pathOnly = url.pathname;
37
- // Signs only the path of the url in the request
38
- const token = await authProvider.withCreds({
39
- url: pathOnly,
40
- method: 'POST',
41
- headers: {
42
- 'Content-Type': 'application/json',
43
- },
44
- });
45
- Object.entries(token.headers).forEach(([key, value]) => {
46
- req.header.set(key, value);
47
- });
48
- return await next(req);
49
- };
50
- }
51
- /** Creates a new instance of an OIDC Auth Provider consumed by the TDF Clients */
52
- async function createAuthProvider(options) {
53
- const { oidc, refreshToken } = options;
54
- return await sdk_1.AuthProviders.refreshAuthProvider({
55
- clientId: oidc.clientId,
56
- exchange: 'refresh',
57
- refreshToken: refreshToken,
58
- // TODO(DSPX-1559): Clean up these URLs.
59
- oidcOrigin: 'https://only-required-for-back-compat.invalid',
60
- oidcTokenEndpoint: oidc.tokenEndpoint,
61
- oidcUserInfoEndpoint: oidc.userInfoEndpoint,
62
- });
63
- }
64
- async function createOpenTDFClient(options) {
65
- const { platformEndpoint, obligations, ...authProviderOptions } = options;
66
- return new sdk_1.OpenTDF({
67
- authProvider: await createAuthProvider(authProviderOptions),
68
- platformUrl: platformEndpoint,
69
- policyEndpoint: platformEndpoint,
70
- defaultCreateOptions: {
71
- defaultKASEndpoint: `${platformEndpoint}/kas`,
72
- },
73
- defaultReadOptions: {
74
- fulfillableObligationFQNs: obligations,
75
- // NOTE(DSP-249): Disabling assertion verification until all generated assertions are supported.
76
- noVerify: true,
77
- },
78
- disableDPoP: true,
79
- });
80
- }
81
- const getObligations = async (ciphertext, options) => {
82
- const client = await createOpenTDFClient(options);
83
- const source = {
84
- type: 'buffer',
85
- location: new Uint8Array(ciphertext),
86
- };
87
- const tdfReader = client.open({ source });
88
- let obligations = [];
89
- try {
90
- obligations = (await tdfReader.obligations()).fqns;
91
- }
92
- catch (error) {
93
- if (error instanceof sdk_1.PermissionDeniedError) {
94
- obligations = error.requiredObligations || [];
95
- }
96
- // Swallow other errors and return empty obligations.
97
- }
98
- return obligations;
99
- };
100
- exports.getObligations = getObligations;
101
- async function getUserEntitlements(options) {
102
- const authProvider = await createAuthProvider({
103
- oidc: options.oidc,
104
- refreshToken: options.refreshToken,
105
- });
106
- const accessToken = await authProvider.oidcAuth.get();
107
- const userEntitlementsResponse = await fetch(`${options.platformEndpoint}/shared/entitlements`, {
108
- body: JSON.stringify({}),
109
- headers: {
110
- Authorization: `Bearer ${accessToken}`,
111
- 'Content-Type': 'application/json',
112
- },
113
- method: 'POST',
114
- });
115
- return (await userEntitlementsResponse.json());
116
- }
117
- const flattenObligations = (obligations) => Object.values(obligations).flatMap((feature) => feature?.fully_qualified_names || []);
118
- exports.flattenObligations = flattenObligations;
119
- /**
120
- * Helper function to retrieve certificates for a specific namespace with pagination handling.
121
- *
122
- * This function automatically handles pagination to retrieve all certificates for a namespace,
123
- * making multiple requests if necessary.
124
- *
125
- * @param dspClient - The DSP client instance.
126
- * @param namespaceId - The namespace UUID.
127
- * @returns A promise that resolves to an array of certificates for the namespace.
128
- * @throws If there is an error retrieving the certificates from the CertificateService.
129
- */
130
- async function getCertificatesForNamespace(dspClient, namespaceId) {
131
- const certificates = [];
132
- let offset = 0;
133
- const limit = 100;
134
- while (true) {
135
- const response = await dspClient.v1.certificateService.listCertificatesByNamespace({
136
- namespaceId,
137
- pagination: { limit, offset },
138
- });
139
- if (response.certificates?.length > 0) {
140
- certificates.push(...response.certificates);
141
- }
142
- // Check for more pages
143
- if (response.pagination?.nextOffset && response.pagination.nextOffset > 0) {
144
- offset = response.pagination.nextOffset;
145
- }
146
- else {
147
- break;
148
- }
149
- }
150
- return certificates;
151
- }
152
- /**
153
- * Retrieves all trusted certificates from active namespaces in the platform.
154
- *
155
- * This function uses the new CertificateService API to retrieve certificates from all active
156
- * namespaces. It automatically handles pagination to ensure all certificates are retrieved.
157
- *
158
- * The function performs the following steps:
159
- * 1. Creates an authenticated auth provider with DPoP signing keys
160
- * 2. Lists all active namespaces using the PlatformClient
161
- * 3. For each namespace, retrieves all associated certificates using the CertificateService
162
- * 4. Aggregates and returns all certificates from all namespaces
163
- *
164
- * @param options - The options object containing the platform endpoint, OIDC configuration, and refresh token.
165
- * @param options.oidc - The OIDC configuration object.
166
- * @param options.oidc.clientId - The OIDC client ID.
167
- * @param options.oidc.tokenEndpoint - The OIDC token endpoint URL.
168
- * @param options.oidc.userInfoEndpoint - The OIDC user info endpoint URL.
169
- * @param options.platformEndpoint - The base URL of the platform.
170
- * @param options.refreshToken - The refresh token for authentication.
171
- * @returns A promise that resolves to an array of trusted certificates from all active namespaces.
172
- * @throws If there is an error retrieving namespaces or certificates.
173
- *
174
- * @example
175
- * ```typescript
176
- * const certificates = await getTrustedCertificates({
177
- * oidc: {
178
- * clientId: 'my-client-id',
179
- * tokenEndpoint: 'https://auth.example.com/token',
180
- * userInfoEndpoint: 'https://auth.example.com/userinfo',
181
- * },
182
- * platformEndpoint: 'https://platform.example.com',
183
- * refreshToken: 'my-refresh-token',
184
- * });
185
- * ```
186
- */
187
- async function getTrustedCertificates(options) {
188
- function generateSigningKeyPair() {
189
- return crypto.subtle.generateKey({
190
- name: 'ECDSA',
191
- namedCurve: 'P-256',
192
- }, true, ['sign', 'verify']);
193
- }
194
- const authProvider = await createAuthProvider({
195
- oidc: options.oidc,
196
- refreshToken: options.refreshToken,
197
- });
198
- await authProvider.updateClientPublicKey(await generateSigningKeyPair());
199
- // Create both clients
200
- const platform = new platform_1.PlatformClient({
201
- authProvider,
202
- platformUrl: options.platformEndpoint,
203
- });
204
- const dspClient = new client_1.DSPClient({
205
- platformUrl: options.platformEndpoint,
206
- authProvider,
207
- });
208
- const certificates = [];
209
- try {
210
- // Get active namespaces (still using namespace API)
211
- const namespaces = await platform.v1.namespace.listNamespaces({
212
- state: common_pb_js_1.ActiveStateEnum.ACTIVE,
213
- });
214
- // Get certificates using new CertificateService API
215
- for (const namespace of namespaces.namespaces) {
216
- const namespaceCerts = await getCertificatesForNamespace(dspClient, namespace.id);
217
- certificates.push(...namespaceCerts);
218
- }
219
- }
220
- catch (error) {
221
- throw error;
222
- }
223
- return certificates;
224
- }
225
- /**
226
- * Helper to get a string representation of a pkijs Name.
227
- */
228
- function getNameStringSafe(name) {
229
- if (!name)
230
- return '';
231
- try {
232
- // pkijs Name to string can be derived from typesAndValues
233
- const parts = (name.typesAndValues || []).map((tv) => {
234
- const type = tv?.type ?? 'unknownType';
235
- // tv.value is an ASN.1 value; best-effort toString fallback
236
- let value;
237
- try {
238
- const block = tv?.value?.valueBlock;
239
- const v = block?.value;
240
- value = typeof v === 'string' ? v : String(tv?.value);
241
- }
242
- catch {
243
- value = '<?>';
244
- }
245
- return `${type}=${value}`;
246
- });
247
- return parts.join(', ');
248
- }
249
- catch {
250
- return '';
251
- }
252
- }
253
- function base64ToArrayBuffer(b64) {
254
- const normalized = b64.replace(/\s+/g, '');
255
- // Basic sanity check; allow trailing '=' padding
256
- if (!/^[-A-Za-z0-9+/]*=*$/.test(normalized)) {
257
- throw new Error('Invalid base64 characters');
258
- }
259
- // Optional size guard (approx: 3/4 of base64 length is bytes)
260
- const approxBytes = Math.floor((normalized.length * 3) / 4);
261
- if (approxBytes === 0) {
262
- throw new Error('Empty base64 data');
263
- }
264
- if (approxBytes > consts_1.MAX_CERT_BYTES) {
265
- throw new Error(`Certificate exceeds maximum allowed size of ${consts_1.MAX_CERT_BYTES} bytes`);
266
- }
267
- const binaryString = atob(normalized);
268
- const bytes = new Uint8Array(binaryString.length);
269
- for (let i = 0; i < binaryString.length; i++) {
270
- bytes[i] = binaryString.charCodeAt(i);
271
- }
272
- return bytes.buffer; // bytes is freshly allocated; buffer is tightly packed
273
- }
274
- function pemToArrayBuffer(pem) {
275
- const base64Der = pem
276
- .replace(/-----BEGIN CERTIFICATE-----/g, '')
277
- .replace(/-----END CERTIFICATE-----/g, '')
278
- .replace(/\r?\n|\r|\s/g, '');
279
- return base64ToArrayBuffer(base64Der);
280
- }
281
- /**
282
- * Validate that a certificate chain from JWS x5c header chains to a trusted root.
283
- *
284
- * This function is designed to be portable and can be moved to another repository.
285
- * It validates that the certificate chain presented in a JWS x5c header builds a
286
- * valid chain to one of the provided trusted root certificates.
287
- *
288
- * Expectations and behavior:
289
- * - `x5c` must be ordered leaf-first and contain base64-encoded DER certs.
290
- * - `trustedRootCertificates` should contain PEM-encoded root certificates.
291
- * - Performs basic input size checks and safe base64 decoding.
292
- * - Uses PKI.js `CertificateChainValidationEngine` for comprehensive path validation
293
- * (validity dates, signatures, policies when present, etc.).
294
- * - Returns detailed error messages including the leaf subject/issuer and parsing warnings.
295
- *
296
- * @param x5c - Array of base64-encoded DER certificates from JWS header (leaf first)
297
- * @param trustedRootCertificates - Array of Certificate objects containing trusted roots in PEM format
298
- * @returns Object with validation result and warnings
299
- * @throws {Error} if validation fails
300
- *
301
- * @example
302
- * ```typescript
303
- * try {
304
- * const result = await validateJWSCertificateChain(
305
- * jwsHeader.x5c,
306
- * namespaceCertificates
307
- * );
308
- * console.log('Chain validates to trusted root', result.validationResult.warnings);
309
- * } catch (error) {
310
- * console.error('Validation failed:', error.message);
311
- * }
312
- * ```
313
- */
314
- async function validateJWSCertificateChain(x5c, trustedRootCertificates) {
315
- const warnings = [];
316
- try {
317
- // Validate inputs
318
- if (!Array.isArray(x5c) || x5c.length === 0) {
319
- throw new Error('No certificates provided in x5c array');
320
- }
321
- if (x5c.length > consts_1.MAX_CERTS) {
322
- throw new Error(`Too many certificates in x5c (max ${consts_1.MAX_CERTS})`);
323
- }
324
- if (!Array.isArray(trustedRootCertificates) ||
325
- trustedRootCertificates.length === 0) {
326
- throw new Error('No trusted root certificates provided');
327
- }
328
- // Parse chain certs (base64 DER)
329
- const chainCertificates = [];
330
- for (let i = 0; i < x5c.length; i++) {
331
- const certBase64 = x5c[i];
332
- try {
333
- const certBuffer = base64ToArrayBuffer(certBase64);
334
- const asn1 = asn1js.fromBER(certBuffer);
335
- if (asn1.offset === -1) {
336
- throw new Error(`Invalid DER encoding for certificate at x5c[${i}]`);
337
- }
338
- chainCertificates.push(new pkijs.Certificate({ schema: asn1.result }));
339
- }
340
- catch (err) {
341
- const msg = err instanceof Error ? err.message : 'Unknown error';
342
- throw new Error(`Failed to parse certificate at x5c[${i}]: ${msg}`);
343
- }
344
- }
345
- // Parse trusted roots (PEM)
346
- const trustedCerts = [];
347
- for (let i = 0; i < trustedRootCertificates.length; i++) {
348
- const rootCert = trustedRootCertificates[i];
349
- try {
350
- const pem = rootCert.pem;
351
- if (!pem || pem.trim().length === 0) {
352
- warnings.push(`Trusted root at index ${i} has no PEM data; skipping`);
353
- continue;
354
- }
355
- const certBuffer = pemToArrayBuffer(pem);
356
- const asn1 = asn1js.fromBER(certBuffer);
357
- if (asn1.offset === -1) {
358
- warnings.push(`Trusted root at index ${i} has invalid DER; skipping`);
359
- continue;
360
- }
361
- trustedCerts.push(new pkijs.Certificate({ schema: asn1.result }));
362
- }
363
- catch (err) {
364
- const msg = err instanceof Error ? err.message : 'Unknown error';
365
- warnings.push(`Failed to parse trusted root at index ${i}: ${msg}`);
366
- }
367
- }
368
- if (trustedCerts.length === 0) {
369
- throw new Error('No valid trusted root certificates could be parsed');
370
- }
371
- // Build and verify certificate chain using PKI.js
372
- const chainEngine = new pkijs.CertificateChainValidationEngine({
373
- trustedCerts,
374
- certs: chainCertificates,
375
- checkDate: new Date(),
376
- });
377
- const verificationResult = await chainEngine.verify();
378
- if (!verificationResult.result) {
379
- // Compose detailed message
380
- const leaf = chainCertificates[0];
381
- const leafSubject = getNameStringSafe(leaf.subject);
382
- const leafIssuer = getNameStringSafe(leaf.issuer);
383
- const baseMsg = verificationResult.resultMessage ||
384
- 'Certificate chain validation failed';
385
- throw new Error(`${baseMsg} (leaf subject='${leafSubject}', issuer='${leafIssuer}')`);
386
- }
387
- return {
388
- valid: true,
389
- validationResult: {
390
- warnings,
391
- errors: [],
392
- },
393
- };
394
- }
395
- catch (error) {
396
- const msg = error instanceof Error ? error.message : 'Unknown error';
397
- const warnSuffix = warnings.length
398
- ? `; warnings: ${warnings.join(' | ')}`
399
- : '';
400
- throw new Error(`Validation error: ${msg}${warnSuffix}`);
401
- }
402
- }
@@ -1,75 +0,0 @@
1
- "use strict";
2
- /*
3
- * Copyright (c) Virtru Corporation. All rights reserved.
4
- *
5
- * Your use of this file is governed by the Virtu Terms of Service <https://www.virtru.com/terms-of-service/>.
6
- */
7
- Object.defineProperty(exports, "__esModule", { value: true });
8
- const vitest_1 = require("vitest");
9
- const index_1 = require("../src/index");
10
- const tagging_pdp_tag_1 = require("./mocks/tagging-pdp-tag");
11
- const create_export_artifacts_1 = require("./mocks/create-export-artifacts");
12
- const platformUrl = 'https://dsp.example.com';
13
- // Mock fetch globally
14
- const mockFetch = vitest_1.vi.fn();
15
- global.fetch = mockFetch;
16
- (0, vitest_1.beforeEach)(() => {
17
- mockFetch.mockReset();
18
- // Setup default mock responses
19
- mockFetch.mockImplementation(async (url) => {
20
- if (url.includes('/tagging.pdp.v2.TaggingPDPService/Tag')) {
21
- return {
22
- ok: true,
23
- status: 200,
24
- json: async () => (0, tagging_pdp_tag_1.mockTaggingPDPResponse)(),
25
- headers: new Headers({
26
- 'Content-Type': 'application/json',
27
- }),
28
- };
29
- }
30
- if (url.includes('/policyimportexport.v1.PolicyArtifactService/CreateExportArtifacts')) {
31
- return {
32
- ok: true,
33
- status: 200,
34
- json: async () => (0, create_export_artifacts_1.mockCreateExportArtifactsResponse)(),
35
- headers: new Headers({
36
- 'Content-Type': 'application/json',
37
- }),
38
- };
39
- }
40
- return {
41
- ok: false,
42
- status: 404,
43
- json: async () => ({}),
44
- headers: new Headers(),
45
- };
46
- });
47
- });
48
- (0, vitest_1.test)('should create a new DSPClient instance with platformUrl', async () => {
49
- const client = new index_1.DSPClient({ platformUrl });
50
- (0, vitest_1.expect)(client).toBeInstanceOf(index_1.DSPClient);
51
- });
52
- (0, vitest_1.test)('should throw an error if platformUrl is not provided', async () => {
53
- (0, vitest_1.expect)(() => new index_1.DSPClient({})).toThrowError('platformUrl is required for DSP client');
54
- });
55
- (0, vitest_1.test)('should perform RPC calls using the taggingPDPService', async () => {
56
- const client = new index_1.DSPClient({ platformUrl });
57
- (0, vitest_1.expect)(client).toBeInstanceOf(index_1.DSPClient);
58
- const result = await client.v2.taggingPDPService.tag({});
59
- (0, vitest_1.expect)(result.$typeName).toBe('tagging.pdp.v2.TaggingPDPResponse');
60
- });
61
- (0, vitest_1.test)('should perform RPC calls using the policyArtifactService', async () => {
62
- const client = new index_1.DSPClient({ platformUrl });
63
- (0, vitest_1.expect)(client).toBeInstanceOf(index_1.DSPClient);
64
- const result = await client.v1.policyArtifactService.createExportArtifacts({});
65
- (0, vitest_1.expect)(result.$typeName).toBe('policyimportexport.v1.CreateExportArtifactsResponse');
66
- });
67
- (0, vitest_1.test)('should use provided interceptors when making RPC calls', async () => {
68
- const mockInterceptor = vitest_1.vi.fn((next) => next);
69
- const client = new index_1.DSPClient({
70
- platformUrl,
71
- interceptors: [mockInterceptor],
72
- });
73
- await client.v2.taggingPDPService.tag({});
74
- (0, vitest_1.expect)(mockInterceptor).toHaveBeenCalled();
75
- });
@@ -1,94 +0,0 @@
1
- "use strict";
2
- /*
3
- * Copyright (c) Virtru Corporation. All rights reserved.
4
- *
5
- * Your use of this file is governed by the Virtu Terms of Service <https://www.virtru.com/terms-of-service/>.
6
- */
7
- Object.defineProperty(exports, "__esModule", { value: true });
8
- const vitest_1 = require("vitest");
9
- const src_1 = require("../src");
10
- const tagging_pdp_tag_1 = require("./mocks/tagging-pdp-tag");
11
- const sdk_1 = require("@opentdf/sdk");
12
- const well_known_configuration_1 = require("./mocks/well-known-configuration");
13
- const platformUrl = 'https://dsp.example.com';
14
- // Mock fetch globally
15
- const mockFetch = vitest_1.vi.fn();
16
- global.fetch = mockFetch;
17
- const authProvider = {
18
- updateClientPublicKey: async () => { },
19
- withCreds: async (req) => (0, sdk_1.withHeaders)(req, {
20
- Authorization: 'Bearer dummy auth token for testing purposes',
21
- }),
22
- };
23
- (0, vitest_1.beforeEach)(() => {
24
- mockFetch.mockReset();
25
- // Setup default mock responses
26
- mockFetch.mockImplementation(async (url) => {
27
- if (url.includes('/tagging.pdp.v2.TaggingPDPService/Tag')) {
28
- return {
29
- ok: true,
30
- status: 200,
31
- json: async () => (0, tagging_pdp_tag_1.mockTaggingPDPResponse)(),
32
- headers: new Headers({
33
- 'Content-Type': 'application/json',
34
- }),
35
- };
36
- }
37
- if (url.includes('/wellknownconfiguration.WellKnownService/GetWellKnownConfiguration')) {
38
- return {
39
- ok: true,
40
- status: 200,
41
- json: async () => (0, well_known_configuration_1.mockWellKnownConfiguration)(),
42
- headers: new Headers({
43
- 'Content-Type': 'application/json',
44
- }),
45
- };
46
- }
47
- return {
48
- ok: false,
49
- status: 404,
50
- json: async () => ({}),
51
- headers: new Headers(),
52
- };
53
- });
54
- });
55
- (0, vitest_1.test)('should create a new DSP instance with platformUrl', () => {
56
- const dsp = new src_1.DSP({ platformUrl, authProvider });
57
- (0, vitest_1.expect)(dsp).toBeInstanceOf(src_1.DSP);
58
- });
59
- (0, vitest_1.test)('should throw an error if platformUrl is not provided', () => {
60
- (0, vitest_1.expect)(() => new src_1.DSP({ authProvider })).toThrowError('platformUrl is required for DSP client');
61
- });
62
- (0, vitest_1.test)('should create a new DSP instance with platformUrl and authProvider', () => {
63
- const dsp = new src_1.DSP({ platformUrl, authProvider });
64
- (0, vitest_1.expect)(dsp).toBeInstanceOf(src_1.DSP);
65
- });
66
- (0, vitest_1.test)('should perform RPC calls using the DSP client service', async () => {
67
- const dsp = new src_1.DSP({ platformUrl, authProvider });
68
- const result = await dsp.services.v2.taggingPDPService.tag({});
69
- (0, vitest_1.expect)(result.$typeName).toBe('tagging.pdp.v2.TaggingPDPResponse');
70
- });
71
- (0, vitest_1.test)('should perform RPC calls via internal PlatformClient service', async () => {
72
- const dsp = new src_1.DSP({ platformUrl, authProvider });
73
- const result = await dsp.services.v1.wellknown.getWellKnownConfiguration({});
74
- (0, vitest_1.expect)(result.$typeName).toBe('wellknownconfiguration.GetWellKnownConfigurationResponse');
75
- });
76
- (0, vitest_1.test)('should use provided interceptors when making RPC calls', async () => {
77
- const mockInterceptor = vitest_1.vi.fn((next) => next);
78
- const dsp = new src_1.DSP({
79
- platformUrl,
80
- authProvider,
81
- interceptors: [mockInterceptor],
82
- });
83
- await dsp.services.v2.taggingPDPService.tag({});
84
- (0, vitest_1.expect)(mockInterceptor).toHaveBeenCalled();
85
- });
86
- (0, vitest_1.test)('should expose expected service structure', () => {
87
- const dsp = new src_1.DSP({ platformUrl, authProvider });
88
- (0, vitest_1.expect)(dsp.services).toHaveProperty('v1');
89
- (0, vitest_1.expect)(dsp.services.v2).toHaveProperty('taggingPDPService');
90
- (0, vitest_1.expect)(dsp.services.v1).toHaveProperty('wellknown');
91
- });
92
- (0, vitest_1.test)('should throw if authProvider is missing', () => {
93
- (0, vitest_1.expect)(() => new src_1.DSP({ platformUrl })).toThrowError('Client ID or custom AuthProvider must be defined');
94
- });
@@ -1,17 +0,0 @@
1
- "use strict";
2
- /*
3
- * Copyright (c) Virtru Corporation. All rights reserved.
4
- *
5
- * Your use of this file is governed by the Virtu Terms of Service <https://www.virtru.com/terms-of-service/>.
6
- */
7
- Object.defineProperty(exports, "__esModule", { value: true });
8
- exports.mockCreateExportArtifactsResponse = void 0;
9
- const policy_import_export_pb_1 = require("@src/gen/policyimportexport/v1/policy_import_export_pb");
10
- const mockCreateExportArtifactsResponse = () => ({
11
- $typeName: 'policyimportexport.v1.CreateExportArtifactsResponse',
12
- artifact: {
13
- case: undefined,
14
- value: undefined,
15
- },
16
- });
17
- exports.mockCreateExportArtifactsResponse = mockCreateExportArtifactsResponse;
@@ -1,15 +0,0 @@
1
- "use strict";
2
- /*
3
- * Copyright (c) Virtru Corporation. All rights reserved.
4
- *
5
- * Your use of this file is governed by the Virtu Terms of Service <https://www.virtru.com/terms-of-service/>.
6
- */
7
- Object.defineProperty(exports, "__esModule", { value: true });
8
- exports.mockTaggingPDPResponse = void 0;
9
- const tagging_pb_1 = require("@src/gen/tagging/pdp/v2/tagging_pb");
10
- const mockTaggingPDPResponse = () => ({
11
- $typeName: 'tagging.pdp.v2.TaggingPDPResponse',
12
- events: [],
13
- tags: [],
14
- });
15
- exports.mockTaggingPDPResponse = mockTaggingPDPResponse;
@@ -1,16 +0,0 @@
1
- "use strict";
2
- /*
3
- * Copyright (c) Virtru Corporation. All rights reserved.
4
- *
5
- * Your use of this file is governed by the Virtu Terms of Service <https://www.virtru.com/terms-of-service/>.
6
- */
7
- Object.defineProperty(exports, "__esModule", { value: true });
8
- exports.mockWellKnownConfiguration = void 0;
9
- const wellknown_configuration_pb_js_1 = require("@opentdf/sdk/platform/wellknownconfiguration/wellknown_configuration_pb.js");
10
- const mockWellKnownConfiguration = () => ({
11
- $typeName: 'wellknownconfiguration.GetWellKnownConfigurationResponse',
12
- configuration: {
13
- wellKnown: {},
14
- },
15
- });
16
- exports.mockWellKnownConfiguration = mockWellKnownConfiguration;
@@ -1,33 +0,0 @@
1
- "use strict";
2
- /*
3
- * Copyright (c) Virtru Corporation. All rights reserved.
4
- *
5
- * Your use of this file is governed by the Virtu Terms of Service <https://www.virtru.com/terms-of-service/>.
6
- */
7
- Object.defineProperty(exports, "__esModule", { value: true });
8
- exports.setupMSW = setupMSW;
9
- const browser_1 = require("msw/browser");
10
- const vitest_1 = require("vitest");
11
- const msw_1 = require("msw");
12
- let worker;
13
- /**
14
- * Sets up the MSW (Mock Service Worker) for testing.
15
- *
16
- * @param handlers - An array of HTTP handlers to be used with MSW.
17
- * @returns The MSW worker instance.
18
- */
19
- function setupMSW(handlers) {
20
- if (!worker) {
21
- worker = (0, browser_1.setupWorker)(...handlers);
22
- (0, vitest_1.beforeAll)(async () => {
23
- await worker.start();
24
- });
25
- (0, vitest_1.afterEach)(() => worker.resetHandlers());
26
- (0, vitest_1.afterAll)(() => worker.stop());
27
- }
28
- else {
29
- // If worker already exists, just update handlers
30
- worker.resetHandlers(...handlers);
31
- }
32
- return worker;
33
- }