-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathtdf.ts
More file actions
1514 lines (1370 loc) · 47.8 KB
/
Copy pathtdf.ts
File metadata and controls
1514 lines (1370 loc) · 47.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import {
KasPublicKeyAlgorithm,
KasPublicKeyInfo,
OriginAllowList,
fetchKasPubKey as fetchKasPubKeyV2,
fetchWrappedKey,
publicKeyAlgorithmToJwa,
} from '../../src/access.js';
import { create, toJsonString } from '@bufbuild/protobuf';
import {
KeyAccessSchema,
UnsignedRewrapRequestSchema,
UnsignedRewrapRequest_WithPolicyRequestSchema,
UnsignedRewrapRequest_WithPolicySchema,
UnsignedRewrapRequest_WithKeyAccessObjectSchema,
} from '../../src/platform/kas/kas_pb.js';
import { type AuthProvider, reqSignature } from '../../src/auth/auth.js';
import { type AuthConfig } from '../../src/auth/interceptors.js';
import { handleRpcRewrapErrorString } from '../../src/access/access-rpc.js';
import { allPool, anyPool } from '../../src/concurrency.js';
import { base64, hex } from '../../src/encodings/index.js';
import {
ConfigurationError,
DecryptError,
InvalidFileError,
IntegrityError,
NetworkError,
UnsafeUrlError,
UnsupportedFeatureError as UnsupportedError,
} from '../../src/errors.js';
import { type Chunker } from '../../src/seekable.js';
import { tdfSpecVersion } from '../../src/version.js';
import { AssertionConfig, AssertionKey, AssertionVerificationKeys } from './assertions.js';
import * as assertions from './assertions.js';
import { Binary } from './binary.js';
import { AesGcmCipher } from './ciphers/aes-gcm-cipher.js';
import { SymmetricCipher } from './ciphers/symmetric-cipher-base.js';
import { DecryptParams } from './client/builders.js';
import { DecoratedReadableStream } from './client/DecoratedReadableStream.js';
import {
type CryptoService,
type DecryptResult,
type KeyPair,
type SymmetricKey,
} from './crypto/declarations.js';
import { Algorithms } from './ciphers/index.js';
import {
ECWrapped,
KeyAccessType,
KeyInfo,
Manifest,
Policy,
SplitKey,
Wrapped,
KeyAccess,
KeyAccessObject,
SplitType,
} from './models/index.js';
import { unsigned } from './utils/buffer-crc32.js';
import { ZipReader, ZipWriter, concatUint8, buffToString } from './utils/index.js';
import { CentralDirectory } from './utils/zip-reader.js';
import { getZtdfSalt } from './crypto/salt.js';
import { Payload } from './models/payload.js';
import {
getRequiredObligationFQNs,
upgradeRewrapResponseV1,
getPlatformUrlFromKasEndpoint,
} from '../../src/utils.js';
// TODO: input validation on manifest JSON
const DEFAULT_SEGMENT_SIZE = 1024 * 1024;
const HEX_SEMVER_VERSION = '4.2.2';
const LEGACY_SEGMENTS_PER_DOWNLOAD = 500;
const LEGACY_MAX_CONCURRENT_SEGMENT_BATCHES = 3;
const DEFAULT_BOUND_SEGMENT_BATCH_SIZE = LEGACY_SEGMENTS_PER_DOWNLOAD;
const DEFAULT_BOUND_MAX_CONCURRENT_SEGMENT_BATCHES = LEGACY_MAX_CONCURRENT_SEGMENT_BATCHES;
/**
* Configuration for TDF3
*/
export type EncryptionOptions = {
/**
* Defaults to `split`, the currently only implmented key wrap algorithm.
*/
type?: SplitType;
// Defaults to AES-256-GCM for the encryption.
cipher?: string;
};
type KeyMiddleware = DecryptParams['keyMiddleware'];
export type Metadata = unknown;
export type BuildKeyAccess = {
type: KeyAccessType;
alg?: KasPublicKeyAlgorithm;
url?: string;
kid?: string;
publicKey: string;
metadata?: Metadata;
sid?: string;
cryptoService: CryptoService;
};
type Segment = {
hash: string;
segmentSize?: number;
encryptedSegmentSize?: number;
};
type EntryInfo = {
filename: string;
offset?: number;
crcCounter?: number;
fileByteCount?: number;
};
type Mailbox<T> = Promise<T> & {
set: (value: T) => void;
reject: (error: Error) => void;
};
function mailbox<T>(): Mailbox<T> {
let set: (value: T) => void;
let reject: (error: Error) => void;
const promise = new Promise<T>((resolve, rejectFn) => {
set = resolve;
reject = rejectFn;
}) as Mailbox<T>;
promise.set = set!;
promise.reject = reject!;
return promise;
}
type Chunk = {
hash: string;
plainSegmentSize?: number;
encryptedOffset: number;
encryptedSegmentSize?: number;
decryptedChunk: Mailbox<DecryptResult>;
};
export type IntegrityAlgorithm = 'GMAC' | 'HS256';
export type EncryptConfiguration = {
allowList?: OriginAllowList;
cryptoService: CryptoService;
dpopKeys: KeyPair;
encryptionInformation: SplitKey;
segmentSizeDefault: number;
integrityAlgorithm: IntegrityAlgorithm;
segmentIntegrityAlgorithm: IntegrityAlgorithm;
contentStream: ReadableStream<Uint8Array>;
mimeType?: string;
policy: Policy;
/** Auth configuration: AuthProvider or { interceptors }. */
auth?: AuthConfig;
byteLimit: number;
progressHandler?: (bytesProcessed: number) => void;
keyForEncryption: KeyInfo;
keyForManifest: KeyInfo;
assertionConfigs?: AssertionConfig[];
systemMetadataAssertion?: boolean;
tdfSpecVersion?: string;
};
export type DecryptConfiguration = {
fulfillableObligations: string[];
allowedKases?: string[];
allowList?: OriginAllowList;
/** Auth configuration: AuthProvider or { interceptors }. */
auth?: AuthConfig;
cryptoService: CryptoService;
dpopKeys: KeyPair;
chunker: Chunker;
keyMiddleware: KeyMiddleware;
progressHandler?: (bytesProcessed: number) => void;
fileStreamServiceWorker?: string;
assertionVerificationKeys?: AssertionVerificationKeys;
noVerifyAssertions?: boolean;
concurrencyLimit?: number;
segmentBatchSize?: number;
maxConcurrentSegmentBatches?: number;
wrappingKeyAlgorithm?: KasPublicKeyAlgorithm;
};
export type UpsertConfiguration = {
allowedKases?: string[];
allowList?: OriginAllowList;
authProvider: AuthProvider;
privateKey: CryptoKey;
unsavedManifest: Manifest;
// if true skips the key access type check when syncing
ignoreType?: boolean;
};
export type RewrapRequest = {
signedRequestToken: string;
};
export type KasPublicKeyFormat = 'pkcs8' | 'jwks';
/**
* If we have KAS url but not public key we can fetch it from KAS, fetching
* the value from `${kas}/kas_public_key`.
*/
export async function fetchKasPublicKey(
kas: string,
algorithm?: KasPublicKeyAlgorithm,
kid?: string
): Promise<KasPublicKeyInfo> {
if (kid) {
// Some specific thing for fetching a key by kid?
// Currently this is just "using" `kid` so TypeScript doesn't complain and
// we can use the type for our cache parameters.
// So this empty `if` is actually doing something.
}
return fetchKasPubKeyV2(kas, algorithm);
}
export async function extractPemFromKeyString(
keyString: string,
alg: KasPublicKeyAlgorithm,
cryptoService: CryptoService
): Promise<string> {
// Convert KAS algorithm to JWA algorithm if provided
const jwaAlgorithm = publicKeyAlgorithmToJwa(alg);
// extractPublicKeyPem handles both X.509 certificates and raw PEM keys
return cryptoService.extractPublicKeyPem(keyString, jwaAlgorithm);
}
/**
* Build a key access object and add it to the list. Can specify either
* a (url, publicKey) pair (legacy, deprecated) or an attribute URL (future).
* If all are missing then it attempts to use the default attribute. If that
* is missing it throws an error.
* @param {Object} options
* @param {String} options.type - enum representing how the object key is treated
* @param {String} options.url - directly set the KAS URL
* @param {String} options.publicKey - directly set the (KAS) public key
* @param {String?} options.kid - Key identifier of KAS public key
* @param {String? Object?} options.metadata - Metadata. Appears to be dead code.
* @return {KeyAccess}- the key access object loaded
*/
export async function buildKeyAccess({
type,
url,
publicKey,
kid,
metadata,
sid = '',
alg = 'rsa:2048',
cryptoService,
}: BuildKeyAccess): Promise<KeyAccess> {
// if url and pulicKey are specified load the key access object with them
if (!url && !publicKey) {
throw new ConfigurationError('TDF.buildKeyAccess: No source for kasUrl or pubKey');
} else if (!url) {
throw new ConfigurationError('TDF.buildKeyAccess: No kasUrl');
} else if (!publicKey) {
throw new ConfigurationError('TDF.buildKeyAccess: No kas public key');
}
let pubKey: string;
try {
pubKey = await extractPemFromKeyString(publicKey, alg, cryptoService);
} catch (e) {
throw new ConfigurationError(
`TDF.buildKeyAccess: Invalid public key [${publicKey}], caused by [${e}]`,
e
);
}
switch (type) {
case 'wrapped':
return new Wrapped(url, kid, pubKey, metadata, cryptoService, sid);
case 'ec-wrapped':
return new ECWrapped(url, kid, pubKey, metadata, cryptoService, sid);
default:
throw new ConfigurationError(`buildKeyAccess: Key access type [${type}] is unsupported`);
}
}
export function validatePolicyObject(policy: Policy): void {
const missingFields: string[] = [];
if (!policy.uuid) missingFields.push('uuid');
if (!policy.body) missingFields.push('body', 'body.dissem');
if (policy.body && !policy.body.dissem) missingFields.push('body.dissem');
if (missingFields.length) {
throw new ConfigurationError(
`The given policy object requires the following properties: ${missingFields}`
);
}
}
async function _generateManifest(
keyInfo: KeyInfo,
encryptionInformation: SplitKey,
policy: Policy,
mimeType?: string,
targetSpecVersion?: string
): Promise<Manifest> {
// (maybe) Fields are quoted to avoid renaming
const payload: Payload = {
type: 'reference',
url: '0.payload',
protocol: 'zip',
isEncrypted: true,
...(mimeType && { mimeType }),
};
const encryptionInformationStr = await encryptionInformation.write(policy, keyInfo);
const assertions: assertions.Assertion[] = [];
const partial = {
payload,
// generate the manifest first, then insert integrity information into it
encryptionInformation: encryptionInformationStr,
assertions: assertions,
};
const schemaVersion = targetSpecVersion || tdfSpecVersion;
if (schemaVersion === '4.2.2') {
return partial;
}
return {
...partial,
schemaVersion,
};
}
async function getSignature(
unwrappedKey: SymmetricKey,
content: Uint8Array,
algorithmType: IntegrityAlgorithm,
cryptoService: CryptoService
): Promise<Uint8Array> {
switch (algorithmType.toUpperCase()) {
case 'GMAC':
// use the auth tag baked into the encrypted payload
return content.slice(-16);
case 'HS256': {
// Use CryptoService for HMAC-SHA256 signing
return cryptoService.hmac(content, unwrappedKey);
}
default:
throw new ConfigurationError(`Unsupported signature alg [${algorithmType}]`);
}
}
async function getSignatureVersion422(
unwrappedKey: SymmetricKey,
payloadBinary: Binary,
algorithmType: IntegrityAlgorithm,
cryptoService: CryptoService
): Promise<string> {
switch (algorithmType.toUpperCase()) {
case 'GMAC':
// use the auth tag baked into the encrypted payload
return buffToString(Uint8Array.from(payloadBinary.asByteArray()).slice(-16), 'hex');
case 'HS256': {
const content = buffToString(new Uint8Array(payloadBinary.asArrayBuffer()), 'utf-8');
const sig = await cryptoService.hmac(new TextEncoder().encode(content), unwrappedKey);
return hex.encodeArrayBuffer(sig.buffer);
}
default:
throw new ConfigurationError(`Unsupported signature alg [${algorithmType}]`);
}
}
function isTargetSpecLegacyTDF(targetSpecVersion?: string): boolean {
return targetSpecVersion === HEX_SEMVER_VERSION;
}
export async function writeStream(cfg: EncryptConfiguration): Promise<DecoratedReadableStream> {
if (!cfg.auth) {
throw new ConfigurationError('No authorization middleware defined');
}
if (!cfg.contentStream) {
throw new ConfigurationError('No input stream defined');
}
// eslint-disable-next-line @typescript-eslint/no-this-alias
const segmentInfos: Segment[] = [];
cfg.byteLimit ??= Number.MAX_SAFE_INTEGER;
const entryInfos: EntryInfo[] = [
{
filename: '0.payload',
},
{
filename: '0.manifest.json',
},
];
let currentBuffer = new Uint8Array();
let totalByteCount = 0;
let bytesProcessed = 0;
let crcCounter = 0;
let fileByteCount = 0;
let aggregateHash422 = '';
const segmentHashList: Uint8Array[] = [];
const zipWriter = new ZipWriter();
const manifest = await _generateManifest(
cfg.keyForManifest,
cfg.encryptionInformation,
cfg.policy,
cfg.mimeType,
cfg.tdfSpecVersion
);
if (!manifest) {
// Set in encrypt; should never be reached.
throw new ConfigurationError('internal: please use "loadTDFStream" first to load a manifest.');
}
// determine default segment size by writing empty buffer
const { segmentSizeDefault } = cfg;
const encryptedBlargh = await cfg.encryptionInformation.encrypt(
Binary.fromArrayBuffer(new ArrayBuffer(segmentSizeDefault)),
cfg.keyForEncryption.unwrappedKey
);
const payloadBuffer = new Uint8Array(encryptedBlargh.payload.asByteArray());
const encryptedSegmentSizeDefault = payloadBuffer.length;
// start writing the content
entryInfos[0].filename = '0.payload';
entryInfos[0].offset = totalByteCount;
const sourceReader = cfg.contentStream.getReader();
/*
TODO: Code duplication should be addressed
- RCA operations require that the write stream has already finished executing it's .on('end') handler before being returned,
thus both handlers are wrapped in a encompassing promise when we have an RCA source. We should investigate
if this causes O(n) promises to be loaded into memory.
- LFS operations can have the write stream returned immediately after both .on('end') and .on('data') handlers
have been defined, thus not requiring the handlers to be wrapped in a promise.
*/
const underlingSource = {
start: (controller: ReadableStreamDefaultController) => {
controller.enqueue(getHeader(entryInfos[0].filename));
_countChunk(getHeader(entryInfos[0].filename));
crcCounter = 0;
fileByteCount = 0;
},
pull: async (controller: ReadableStreamDefaultController) => {
let isDone;
while (currentBuffer.length < segmentSizeDefault && !isDone) {
const { value, done } = await sourceReader.read();
isDone = done;
if (value) {
currentBuffer = concatUint8([currentBuffer, value]);
}
}
while (
currentBuffer.length >= segmentSizeDefault &&
!!controller.desiredSize &&
controller.desiredSize > 0
) {
const segment = currentBuffer.slice(0, segmentSizeDefault);
const encryptedSegment = await _encryptAndCountSegment(segment);
controller.enqueue(encryptedSegment);
currentBuffer = currentBuffer.slice(segmentSizeDefault);
}
const isFinalChunkLeft = isDone && currentBuffer.length;
if (isFinalChunkLeft) {
const encryptedSegment = await _encryptAndCountSegment(currentBuffer);
controller.enqueue(encryptedSegment);
currentBuffer = new Uint8Array();
}
if (isDone && currentBuffer.length === 0) {
entryInfos[0].crcCounter = crcCounter;
entryInfos[0].fileByteCount = fileByteCount;
const payloadDataDescriptor = zipWriter.writeDataDescriptor(crcCounter, fileByteCount);
controller.enqueue(payloadDataDescriptor);
_countChunk(payloadDataDescriptor);
// prepare the manifest
entryInfos[1].filename = '0.manifest.json';
entryInfos[1].offset = totalByteCount;
controller.enqueue(getHeader(entryInfos[1].filename));
_countChunk(getHeader(entryInfos[1].filename));
crcCounter = 0;
fileByteCount = 0;
let aggregateHash: string | Uint8Array;
if (isTargetSpecLegacyTDF(cfg.tdfSpecVersion)) {
aggregateHash = aggregateHash422;
const payloadSigStr = await getSignatureVersion422(
cfg.keyForEncryption.unwrappedKey,
Binary.fromString(aggregateHash),
cfg.integrityAlgorithm,
cfg.cryptoService
);
manifest.encryptionInformation.integrityInformation.rootSignature.sig =
base64.encode(payloadSigStr);
} else {
// hash the concat of all hashes
aggregateHash = await concatenateUint8Array(segmentHashList);
const payloadSig = await getSignature(
cfg.keyForEncryption.unwrappedKey,
aggregateHash,
cfg.integrityAlgorithm,
cfg.cryptoService
);
const rootSig = base64.encodeArrayBuffer(payloadSig);
manifest.encryptionInformation.integrityInformation.rootSignature.sig = rootSig;
}
manifest.encryptionInformation.integrityInformation.rootSignature.alg =
cfg.integrityAlgorithm;
manifest.encryptionInformation.integrityInformation.segmentSizeDefault = segmentSizeDefault;
manifest.encryptionInformation.integrityInformation.encryptedSegmentSizeDefault =
encryptedSegmentSizeDefault;
manifest.encryptionInformation.integrityInformation.segmentHashAlg =
cfg.segmentIntegrityAlgorithm;
manifest.encryptionInformation.integrityInformation.segments = segmentInfos;
manifest.encryptionInformation.method.isStreamable = true;
const signedAssertions: assertions.Assertion[] = [];
if (cfg.systemMetadataAssertion) {
const systemMetadataConfigBase = assertions.getSystemMetadataAssertionConfig();
const signingKeyForSystemMetadata: AssertionKey = {
alg: 'HS256', // Default algorithm, can be configured if needed
key: cfg.keyForEncryption.unwrappedKey,
};
signedAssertions.push(
await assertions.CreateAssertion(
aggregateHash,
{
...systemMetadataConfigBase, // Spread the properties from the base config
signingKey: signingKeyForSystemMetadata, // Add the signing key
},
cfg.cryptoService,
cfg.tdfSpecVersion // Pass the TDF spec version
)
);
}
if (cfg.assertionConfigs && cfg.assertionConfigs.length > 0) {
await Promise.all(
cfg.assertionConfigs.map(async (assertionConfig) => {
// Create assertion using the assertionConfig values
const signingKey: AssertionKey = assertionConfig.signingKey ?? {
alg: 'HS256',
key: cfg.keyForEncryption.unwrappedKey,
};
const assertion = await assertions.CreateAssertion(
aggregateHash,
{
...assertionConfig,
signingKey,
},
cfg.cryptoService,
cfg.tdfSpecVersion
);
// Add signed assertion to the signedAssertions array
signedAssertions.push(assertion);
})
);
}
manifest.assertions = signedAssertions;
// write the manifest
const manifestBuffer = new TextEncoder().encode(JSON.stringify(manifest));
controller.enqueue(manifestBuffer);
_countChunk(manifestBuffer);
entryInfos[1].crcCounter = crcCounter;
entryInfos[1].fileByteCount = fileByteCount;
const manifestDataDescriptor = zipWriter.writeDataDescriptor(crcCounter, fileByteCount);
controller.enqueue(manifestDataDescriptor);
_countChunk(manifestDataDescriptor);
// write the central directory out
const centralDirectoryByteCount = totalByteCount;
for (let i = 0; i < entryInfos.length; i++) {
const entryInfo = entryInfos[i];
const result = zipWriter.writeCentralDirectoryRecord(
entryInfo.fileByteCount || 0,
entryInfo.filename,
entryInfo.offset || 0,
entryInfo.crcCounter || 0,
2175008768
);
controller.enqueue(result);
_countChunk(result);
}
const endOfCentralDirectoryByteCount = totalByteCount - centralDirectoryByteCount;
const finalChunk = zipWriter.writeEndOfCentralDirectoryRecord(
entryInfos.length,
endOfCentralDirectoryByteCount,
centralDirectoryByteCount
);
controller.enqueue(finalChunk);
_countChunk(finalChunk);
controller.close();
}
},
};
const plaintextStream = new DecoratedReadableStream(underlingSource);
plaintextStream.manifest = manifest;
return plaintextStream;
// nested helper fn's
function getHeader(filename: string) {
return zipWriter.getLocalFileHeader(filename, 0, 0, 0);
}
function _countChunk(chunk: string | Uint8Array) {
if (typeof chunk === 'string') {
chunk = new TextEncoder().encode(chunk);
}
totalByteCount += chunk.length;
if (totalByteCount > cfg.byteLimit) {
throw new ConfigurationError(`Safe byte limit (${cfg.byteLimit}) exceeded`);
}
//new Uint8Array(chunk.buffer, chunk.byteOffset, chunk.byteLength);
crcCounter = unsigned(chunk, crcCounter);
fileByteCount += chunk.length;
}
async function _encryptAndCountSegment(chunk: Uint8Array) {
bytesProcessed += chunk.length;
cfg.progressHandler?.(bytesProcessed);
// Don't pass in an IV here. The encrypt function will generate one for you, ensuring that each segment has a unique IV.
const encryptedResult = await cfg.encryptionInformation.encrypt(
Binary.fromArrayBuffer(chunk.buffer),
cfg.keyForEncryption.unwrappedKey
);
const payloadBuffer = new Uint8Array(encryptedResult.payload.asByteArray());
let hash: string;
if (isTargetSpecLegacyTDF(cfg.tdfSpecVersion)) {
const payloadSigStr = await getSignatureVersion422(
cfg.keyForEncryption.unwrappedKey,
encryptedResult.payload,
cfg.segmentIntegrityAlgorithm,
cfg.cryptoService
);
// combined string of all hashes for root signature
aggregateHash422 += payloadSigStr;
hash = base64.encode(payloadSigStr);
} else {
const payloadSig = await getSignature(
cfg.keyForEncryption.unwrappedKey,
new Uint8Array(encryptedResult.payload.asArrayBuffer()),
cfg.segmentIntegrityAlgorithm,
cfg.cryptoService
);
segmentHashList.push(new Uint8Array(payloadSig));
hash = base64.encodeArrayBuffer(payloadSig);
}
segmentInfos.push({
hash,
segmentSize: chunk.length === segmentSizeDefault ? undefined : chunk.length,
encryptedSegmentSize:
payloadBuffer.length === encryptedSegmentSizeDefault ? undefined : payloadBuffer.length,
});
const result = new Uint8Array(encryptedResult.payload.asByteArray());
_countChunk(result);
return result;
}
}
export type InspectedTDFOverview = {
manifest: Manifest;
zipReader: ZipReader;
centralDirectory: CentralDirectory[];
};
// load the TDF as a stream in memory, for further use in reading and key syncing
export async function loadTDFStream(chunker: Chunker): Promise<InspectedTDFOverview> {
const zipReader = new ZipReader(chunker);
const centralDirectory = await zipReader.getCentralDirectory();
const manifest = await zipReader.getManifest(centralDirectory, '0.manifest.json');
return { manifest, zipReader, centralDirectory };
}
export function splitLookupTableFactory(
keyAccess: KeyAccessObject[],
allowedKases: OriginAllowList
): Record<string, Record<string, KeyAccessObject[]>> {
const allowed = (k: KeyAccessObject) => allowedKases.allows(k.url);
const splitIds = new Set(keyAccess.map(({ sid }) => sid ?? ''));
const accessibleSplits = new Set(keyAccess.filter(allowed).map(({ sid }) => sid ?? ''));
if (splitIds.size > accessibleSplits.size) {
const disallowedKases = new Set(keyAccess.filter((k) => !allowed(k)).map(({ url }) => url));
throw new UnsafeUrlError(
`Unreconstructable key - disallowed KASes include: ${JSON.stringify([
...disallowedKases,
])} from splitIds ${JSON.stringify([...splitIds])}`,
...disallowedKases
);
}
const splitPotentials: Record<string, Record<string, KeyAccessObject[]>> = Object.fromEntries(
[...splitIds].map((s) => [s, {}])
);
for (const kao of keyAccess) {
if (!allowed(kao)) {
continue;
}
const disjunction = splitPotentials[kao.sid ?? ''];
const existing = disjunction[kao.url];
if (existing) {
const isDuplicate = existing.some(
(e) => e.kid === kao.kid && e.wrappedKey === kao.wrappedKey
);
if (isDuplicate) {
continue;
}
existing.push(kao);
} else {
disjunction[kao.url] = [kao];
}
}
return splitPotentials;
}
type RewrapResponseData = {
key: Uint8Array;
metadata: Record<string, unknown>;
requiredObligations: string[];
};
async function unwrapKey({
manifest,
allowedKases,
auth,
dpopKeys,
concurrencyLimit,
cryptoService,
wrappingKeyAlgorithm,
fulfillableObligations,
}: {
manifest: Manifest;
allowedKases: OriginAllowList;
/** Auth configuration: AuthProvider or { interceptors }. */
auth?: AuthConfig;
concurrencyLimit?: number;
dpopKeys: KeyPair;
cryptoService: CryptoService;
wrappingKeyAlgorithm?: KasPublicKeyAlgorithm;
fulfillableObligations: string[];
}) {
if (!auth) {
throw new ConfigurationError('rewrap requires auth; must be configured in client constructor');
}
const resolvedAuth: AuthConfig = auth;
const { keyAccess } = manifest.encryptionInformation;
const splitPotentials = splitLookupTableFactory(keyAccess, allowedKases);
async function tryKasRewrap(keySplitInfo: KeyAccessObject): Promise<RewrapResponseData> {
const url = `${keySplitInfo.url}/v2/rewrap`;
let ephemeralEncryptionKeys: KeyPair;
if (wrappingKeyAlgorithm === 'ec:secp256r1') {
// Generate EC key pair via CryptoService (returns opaque keys)
ephemeralEncryptionKeys = await cryptoService.generateECKeyPair('P-256');
} else if (wrappingKeyAlgorithm === 'rsa:2048' || !wrappingKeyAlgorithm) {
// generateKeyPair() returns opaque keys
ephemeralEncryptionKeys = await cryptoService.generateKeyPair();
} else {
throw new ConfigurationError(`Unsupported wrapping key algorithm [${wrappingKeyAlgorithm}]`);
}
// Export public key to PEM for protobuf request
const clientPublicKey = await cryptoService.exportPublicKeyPem(
ephemeralEncryptionKeys.publicKey
);
// Convert keySplitInfo to protobuf KeyAccess
const keyAccessProto = create(KeyAccessSchema, {
...(keySplitInfo.type && { keyType: keySplitInfo.type }),
...(keySplitInfo.url && { kasUrl: keySplitInfo.url }),
...(keySplitInfo.protocol && { protocol: keySplitInfo.protocol }),
...(keySplitInfo.wrappedKey && {
wrappedKey: new Uint8Array(base64.decodeArrayBuffer(keySplitInfo.wrappedKey)),
}),
...(keySplitInfo.policyBinding && { policyBinding: keySplitInfo.policyBinding }),
...(keySplitInfo.kid && { kid: keySplitInfo.kid }),
...(keySplitInfo.sid && { splitId: keySplitInfo.sid }),
...(keySplitInfo.encryptedMetadata && { encryptedMetadata: keySplitInfo.encryptedMetadata }),
...(keySplitInfo.ephemeralPublicKey && {
ephemeralPublicKey: keySplitInfo.ephemeralPublicKey,
}),
});
// Create the protobuf request
const unsignedRequest = create(UnsignedRewrapRequestSchema, {
clientPublicKey,
requests: [
create(UnsignedRewrapRequest_WithPolicyRequestSchema, {
keyAccessObjects: [
create(UnsignedRewrapRequest_WithKeyAccessObjectSchema, {
keyAccessObjectId: 'kao-0',
keyAccessObject: keyAccessProto,
}),
],
...(manifest.encryptionInformation.policy && {
policy: create(UnsignedRewrapRequest_WithPolicySchema, {
id: 'policy',
body: manifest.encryptionInformation.policy,
}),
}),
}),
],
// include deprecated fields for backward compatibility
algorithm: 'RS256',
keyAccess: keyAccessProto,
policy: manifest.encryptionInformation.policy,
});
const requestBodyStr = toJsonString(UnsignedRewrapRequestSchema, unsignedRequest);
const jwtPayload = { requestBody: requestBodyStr };
const signedRequestToken = await reqSignature(jwtPayload, dpopKeys.privateKey, cryptoService);
const rewrapResp = await fetchWrappedKey(
url,
signedRequestToken,
resolvedAuth,
fulfillableObligations
);
// Upgrade V1 response to V2 format if needed
upgradeRewrapResponseV1(rewrapResp);
const { sessionPublicKey } = rewrapResp;
const requiredObligations = getRequiredObligationFQNs(rewrapResp);
// Assume only one response and one result for now (V1 style)
const result = rewrapResp.responses?.[0]?.results?.[0];
if (!result) {
// This should not happen - KAS should always return at least one response and one result
// or the upgradeRewrapResponseV1 should have created them
throw new DecryptError('KAS rewrap response missing expected response or result');
}
const metadata = result.metadata;
// Handle the different cases of result.result
switch (result.result.case) {
case 'kasWrappedKey': {
const entityWrappedKey = result.result.value;
if (wrappingKeyAlgorithm === 'ec:secp256r1') {
// Import KAS session public key from PEM
const sessionPublicKeyOpaque = await cryptoService.importPublicKey(sessionPublicKey, {
usage: 'derive',
});
// Derive decryption key using ECDH + HKDF via CryptoService (returns SymmetricKey)
const derivedKey = await cryptoService.deriveKeyFromECDH(
ephemeralEncryptionKeys.privateKey,
sessionPublicKeyOpaque,
{
hash: 'SHA-256',
salt: await getZtdfSalt(cryptoService),
}
);
const wrappedKeyAndNonce = entityWrappedKey;
const iv = wrappedKeyAndNonce.slice(0, 12);
const wrappedKey = wrappedKeyAndNonce.slice(12);
// Decrypt using CryptoService with opaque symmetric key
const decryptResult = await cryptoService.decrypt(
Binary.fromArrayBuffer(wrappedKey.buffer),
derivedKey, // SymmetricKey (opaque)
Binary.fromArrayBuffer(iv.buffer),
Algorithms.AES_256_GCM
);
return {
key: new Uint8Array(decryptResult.payload.asArrayBuffer()),
metadata,
requiredObligations,
};
}
const key = Binary.fromArrayBuffer(entityWrappedKey);
const decryptedKeyBinary = await cryptoService.decryptWithPrivateKey(
key,
ephemeralEncryptionKeys.privateKey
);
return {
key: new Uint8Array(decryptedKeyBinary.asByteArray()),
metadata,
requiredObligations,
};
}
case 'error': {
handleRpcRewrapErrorString(
result.result.value,
getPlatformUrlFromKasEndpoint(url),
requiredObligations
);
}
default: {
throw new DecryptError('KAS rewrap response missing wrapped key');
}
}
}
let poolSize = 1;
if (concurrencyLimit !== undefined && concurrencyLimit > 1) {
poolSize = concurrencyLimit;
}
const splitPromises: Record<string, () => Promise<RewrapResponseData>> = {};
for (const splitId of Object.keys(splitPotentials)) {
const potentials = splitPotentials[splitId];
if (!potentials || !Object.keys(potentials).length) {
throw new UnsafeUrlError(
`Unreconstructable key - no valid KAS found for split ${JSON.stringify(splitId)}`,
''
);
}
const anyPromises: Record<string, () => Promise<RewrapResponseData>> = {};
for (const [kas, kaoList] of Object.entries(potentials)) {
kaoList.forEach((keySplitInfo, idx) => {
const key = kaoList.length === 1 ? kas : `${kas}#${idx}`;
anyPromises[key] = async () => {
try {
return await tryKasRewrap(keySplitInfo);
} catch (e) {
throw handleRewrapError(e as Error);
}
};
});
}
splitPromises[splitId] = () => anyPool(poolSize, anyPromises);
}
try {
const rewrapResponseData = await allPool(poolSize, splitPromises);
const splitKeys = [];
const requiredObligations = new Set<string>();
for (const resp of rewrapResponseData) {
// Import each split key as opaque SymmetricKey
const splitKeyOpaque = await cryptoService.importSymmetricKey(resp.key);
splitKeys.push(splitKeyOpaque);
for (const requiredObligation of resp.requiredObligations) {
requiredObligations.add(requiredObligation.toLowerCase());
}
}
// Merge symmetric keys via CryptoService
const reconstructedKey = await cryptoService.mergeSymmetricKeys(splitKeys);
return {
reconstructedKey, // SymmetricKey (opaque)
metadata: rewrapResponseData[0].metadata, // Use metadata from first split
requiredObligations: [...requiredObligations],
};
} catch (e) {
if (e instanceof AggregateError) {
const errors = e.errors;
if (errors.length === 1) {
throw errors[0];
}
}
throw e;
}
}
function handleRewrapError(error: Error) {
if (error.name === 'InvalidAccessError' || error.name === 'OperationError') {
return new DecryptError('unable to unwrap key from kas', error);
}
return error;
}
async function decryptChunk(
encryptedChunk: Uint8Array,
reconstructedKey: SymmetricKey,
hash: string,
cipher: SymmetricCipher,
segmentIntegrityAlgorithm: IntegrityAlgorithm,
specVersion: string,