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