@cclabsnz/sf-core 0.12.0 → 0.14.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.
- package/CHANGELOG.md +58 -1
- package/README.md +3 -2
- package/lib/cloudflare/CloudflareClient.d.ts +53 -0
- package/lib/cloudflare/CloudflareClient.js +10 -0
- package/lib/cloudflare/FetchCloudflareClient.d.ts +6 -0
- package/lib/cloudflare/FetchCloudflareClient.js +152 -0
- package/lib/cloudflare/errors.d.ts +16 -0
- package/lib/cloudflare/errors.js +25 -0
- package/lib/cloudflare/index.d.ts +5 -0
- package/lib/cloudflare/index.js +4 -0
- package/lib/cloudflare/testing/MemoryCloudflareClient.d.ts +43 -0
- package/lib/cloudflare/testing/MemoryCloudflareClient.js +77 -0
- package/lib/cloudflare.d.ts +2 -0
- package/lib/cloudflare.js +4 -0
- package/lib/cloudflareTesting.d.ts +3 -0
- package/lib/cloudflareTesting.js +3 -0
- package/lib/crypto/bundleCrypto.d.ts +30 -1
- package/lib/crypto/bundleCrypto.js +269 -9
- package/lib/graph/validate.js +1 -1
- package/lib/index.d.ts +1 -1
- package/lib/index.js +1 -1
- package/lib/storage/ObjectStore.d.ts +26 -0
- package/lib/storage/ObjectStore.js +2 -0
- package/lib/storage/S3ObjectStoreImpl.d.ts +20 -0
- package/lib/storage/S3ObjectStoreImpl.js +132 -0
- package/lib/storage/errors.d.ts +11 -0
- package/lib/storage/errors.js +19 -0
- package/lib/storage/index.d.ts +7 -0
- package/lib/storage/index.js +4 -0
- package/lib/storage/s3Location.d.ts +29 -0
- package/lib/storage/s3Location.js +63 -0
- package/lib/storage/testing/MemoryObjectStore.d.ts +32 -0
- package/lib/storage/testing/MemoryObjectStore.js +79 -0
- package/lib/storage.d.ts +2 -0
- package/lib/storage.js +4 -0
- package/lib/storageTesting.d.ts +2 -0
- package/lib/storageTesting.js +3 -0
- package/package.json +23 -2
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { createCipheriv, createDecipheriv, randomBytes, scryptSync } from 'node:crypto';
|
|
2
|
+
import { Transform } from 'node:stream';
|
|
2
3
|
/**
|
|
3
4
|
* Passphrase encryption for files that hold org data at rest (incident bundles).
|
|
4
5
|
*
|
|
@@ -9,27 +10,72 @@ import { createCipheriv, createDecipheriv, randomBytes, scryptSync } from 'node:
|
|
|
9
10
|
* AES-256-GCM with a key from scrypt. The scrypt parameters travel in the header so they can be
|
|
10
11
|
* raised later without stranding existing files, and the whole header is authenticated as GCM
|
|
11
12
|
* additional data, so altering any byte of it fails decryption.
|
|
13
|
+
*
|
|
14
|
+
* Format, version 2 (chunked, for files too large to hold in memory):
|
|
15
|
+
*
|
|
16
|
+
* 'SFEB' | version (1) | log2(N) (1) | r (1) | p (1) | log2(chunk) (1) | salt (16) | nonce prefix (7)
|
|
17
|
+
* then one segment per chunk: ciphertext (chunk bytes, the last one 0..chunk) | tag (16)
|
|
18
|
+
*
|
|
19
|
+
* The STREAM construction (Hoang, Reyhanitabar, Rogaway, Vizár 2015), as age and Tink use it: each
|
|
20
|
+
* chunk is sealed on its own with nonce = prefix | chunk index (4, big-endian) | last-chunk flag (1),
|
|
21
|
+
* and the header is every chunk's additional data. Reordered, repeated, dropped or appended chunks,
|
|
22
|
+
* and a file cut at a chunk boundary, all fail authentication. A reader may emit the chunks before
|
|
23
|
+
* a failure, each of which authenticated, so a consumer must treat a stream error as fatal.
|
|
12
24
|
*/
|
|
25
|
+
export const ENCRYPTED_PREFIX = Buffer.from('SFEB', 'ascii');
|
|
13
26
|
export const ENCRYPTED_MAGIC = Buffer.from('SFEB\x01', 'ascii'); // 'SFEB' + format version 1
|
|
14
27
|
/** OWASP's scrypt option N=2^15, r=8, p=3: about 32 MiB and ~0.1-0.2 s per derivation. */
|
|
15
28
|
const DEFAULT_KDF = { log2N: 15, r: 8, p: 3 };
|
|
16
29
|
/** Bounds accepted when reading a header, so a crafted file cannot demand unbounded memory or time. */
|
|
17
30
|
const KDF_LIMITS = { log2N: [14, 20], r: [1, 16], p: [1, 16] };
|
|
18
31
|
const MAX_KDF_MEMORY = 1024 * 1024 * 1024;
|
|
32
|
+
/**
|
|
33
|
+
* Each field in range can still combine into seconds of blocking work or a gigabyte, per file. A
|
|
34
|
+
* header must also keep scrypt's memory (128·N·r) to 256 MiB and its work (N·r·p) to four times the
|
|
35
|
+
* default's.
|
|
36
|
+
*/
|
|
37
|
+
const MAX_HEADER_KDF_MEMORY = 256 * 1024 * 1024;
|
|
38
|
+
const MAX_HEADER_KDF_COST = 4 * 2 ** DEFAULT_KDF.log2N * DEFAULT_KDF.r * DEFAULT_KDF.p;
|
|
19
39
|
const SALT_LEN = 16;
|
|
20
40
|
const IV_LEN = 12;
|
|
21
41
|
const TAG_LEN = 16;
|
|
22
42
|
const HEADER_LEN = ENCRYPTED_MAGIC.length + 3 + SALT_LEN + IV_LEN; // authenticated as AAD
|
|
23
43
|
const MIN_LEN = HEADER_LEN + TAG_LEN;
|
|
44
|
+
const NONCE_PREFIX_LEN = 7;
|
|
45
|
+
const V2_HEADER_LEN = ENCRYPTED_PREFIX.length + 1 + 3 + 1 + SALT_LEN + NONCE_PREFIX_LEN;
|
|
46
|
+
const V2_MIN_LEN = V2_HEADER_LEN + TAG_LEN; // an empty file still has one (empty, last) chunk
|
|
47
|
+
/** 1 KiB to 16 MiB: the upper bound caps what a crafted header can make a reader buffer. */
|
|
48
|
+
const CHUNK_LOG2_LIMITS = [10, 24];
|
|
49
|
+
const DEFAULT_CHUNK_LOG2 = 16; // 64 KiB
|
|
50
|
+
const MAX_CHUNKS = 2 ** 32; // the chunk index is a 4-byte field
|
|
51
|
+
/** A version 1 file is sealed whole in memory, so a stream refuses one larger than this. */
|
|
52
|
+
const MAX_V1_STREAM_BYTES = 64 * 1024 * 1024;
|
|
24
53
|
export class DecryptionError extends Error {
|
|
25
54
|
constructor(message = 'Failed to decrypt data: invalid passphrase or corrupted payload') {
|
|
26
55
|
super(message);
|
|
27
56
|
this.name = 'DecryptionError';
|
|
28
57
|
}
|
|
29
58
|
}
|
|
30
|
-
/** Whether `buf` starts with
|
|
59
|
+
/** Whether `buf` starts with a header of a known version. Says nothing about whether it will decrypt. */
|
|
31
60
|
export function isEncryptedBuffer(buf) {
|
|
32
|
-
|
|
61
|
+
if (!hasPrefix(buf))
|
|
62
|
+
return false;
|
|
63
|
+
const version = buf[ENCRYPTED_PREFIX.length];
|
|
64
|
+
return (version === 1 && buf.length >= MIN_LEN) || (version === 2 && buf.length >= V2_MIN_LEN);
|
|
65
|
+
}
|
|
66
|
+
function hasPrefix(buf) {
|
|
67
|
+
return buf.length > ENCRYPTED_PREFIX.length && buf.subarray(0, ENCRYPTED_PREFIX.length).equals(ENCRYPTED_PREFIX);
|
|
68
|
+
}
|
|
69
|
+
const within = (v, [lo, hi]) => v >= lo && v <= hi;
|
|
70
|
+
/** Reads log2(N), r, p at `o` and refuses values that would demand unbounded memory or time. */
|
|
71
|
+
function readKdf(buf, o) {
|
|
72
|
+
const [log2N, r, p] = [buf[o], buf[o + 1], buf[o + 2]];
|
|
73
|
+
const N = 2 ** log2N;
|
|
74
|
+
if (!within(log2N, KDF_LIMITS.log2N) || !within(r, KDF_LIMITS.r) || !within(p, KDF_LIMITS.p) ||
|
|
75
|
+
128 * N * r > MAX_HEADER_KDF_MEMORY || N * r * p > MAX_HEADER_KDF_COST) {
|
|
76
|
+
throw new DecryptionError('Encrypted header carries key-derivation parameters outside the accepted range');
|
|
77
|
+
}
|
|
78
|
+
return { log2N, r, p };
|
|
33
79
|
}
|
|
34
80
|
// One passphrase decrypts every file of a bundle, each with its own salt, and readers revisit
|
|
35
81
|
// files. Caching derived keys keeps that from re-running scrypt. Entries are keyed by salt and
|
|
@@ -68,15 +114,16 @@ export function encryptWithPassphrase(plaintext, passphrase) {
|
|
|
68
114
|
}
|
|
69
115
|
export function decryptWithPassphrase(encrypted, passphrase) {
|
|
70
116
|
requirePassphrase(passphrase);
|
|
71
|
-
if (!
|
|
117
|
+
if (!hasPrefix(encrypted))
|
|
72
118
|
throw new DecryptionError('Buffer is not in recognized SFEB encrypted format');
|
|
73
|
-
|
|
119
|
+
checkVersion(encrypted[ENCRYPTED_PREFIX.length]);
|
|
120
|
+
if (!isEncryptedBuffer(encrypted))
|
|
121
|
+
throw new DecryptionError('Encrypted data is truncated');
|
|
122
|
+
if (encrypted[ENCRYPTED_PREFIX.length] === 2)
|
|
123
|
+
return decryptV2(encrypted, passphrase);
|
|
74
124
|
let o = ENCRYPTED_MAGIC.length;
|
|
75
|
-
const
|
|
76
|
-
|
|
77
|
-
if (!within(log2N, KDF_LIMITS.log2N) || !within(r, KDF_LIMITS.r) || !within(p, KDF_LIMITS.p)) {
|
|
78
|
-
throw new DecryptionError('Encrypted header carries key-derivation parameters outside the accepted range');
|
|
79
|
-
}
|
|
125
|
+
const { log2N, r, p } = readKdf(encrypted, o);
|
|
126
|
+
o += 3;
|
|
80
127
|
const salt = encrypted.subarray(o, (o += SALT_LEN));
|
|
81
128
|
const iv = encrypted.subarray(o, (o += IV_LEN));
|
|
82
129
|
const header = encrypted.subarray(0, HEADER_LEN);
|
|
@@ -93,4 +140,217 @@ export function decryptWithPassphrase(encrypted, passphrase) {
|
|
|
93
140
|
throw new DecryptionError();
|
|
94
141
|
}
|
|
95
142
|
}
|
|
143
|
+
function checkVersion(version) {
|
|
144
|
+
if (version !== 1 && version !== 2)
|
|
145
|
+
throw new DecryptionError(`Unsupported SFEB format version ${version}`);
|
|
146
|
+
}
|
|
147
|
+
/** Parses and checks a version 2 header, then derives its key. Limits are checked before scrypt runs. */
|
|
148
|
+
function openV2Header(header, passphrase) {
|
|
149
|
+
let o = ENCRYPTED_PREFIX.length + 1;
|
|
150
|
+
const { log2N, r, p } = readKdf(header, o);
|
|
151
|
+
o += 3;
|
|
152
|
+
const chunkLog2 = header[o++];
|
|
153
|
+
if (!within(chunkLog2, CHUNK_LOG2_LIMITS)) {
|
|
154
|
+
throw new DecryptionError('Encrypted header carries a chunk size outside the accepted range');
|
|
155
|
+
}
|
|
156
|
+
const salt = header.subarray(o, (o += SALT_LEN));
|
|
157
|
+
const noncePrefix = header.subarray(o, (o += NONCE_PREFIX_LEN));
|
|
158
|
+
let key;
|
|
159
|
+
try {
|
|
160
|
+
key = deriveKey(passphrase, salt, log2N, r, p);
|
|
161
|
+
}
|
|
162
|
+
catch {
|
|
163
|
+
throw new DecryptionError('Encrypted header carries key-derivation parameters outside the accepted range');
|
|
164
|
+
}
|
|
165
|
+
return { header, key, noncePrefix, chunkSize: 2 ** chunkLog2 };
|
|
166
|
+
}
|
|
167
|
+
function chunkNonce(prefix, index, last) {
|
|
168
|
+
if (index >= MAX_CHUNKS)
|
|
169
|
+
throw new RangeError('Too many chunks for one encrypted file');
|
|
170
|
+
const nonce = Buffer.alloc(IV_LEN);
|
|
171
|
+
prefix.copy(nonce);
|
|
172
|
+
nonce.writeUInt32BE(index, NONCE_PREFIX_LEN);
|
|
173
|
+
nonce[IV_LEN - 1] = last ? 1 : 0;
|
|
174
|
+
return nonce;
|
|
175
|
+
}
|
|
176
|
+
function sealChunk(h, index, last, plain) {
|
|
177
|
+
const cipher = createCipheriv('aes-256-gcm', h.key, chunkNonce(h.noncePrefix, index, last), { authTagLength: TAG_LEN });
|
|
178
|
+
cipher.setAAD(h.header);
|
|
179
|
+
const ciphertext = Buffer.concat([cipher.update(plain), cipher.final()]);
|
|
180
|
+
return Buffer.concat([ciphertext, cipher.getAuthTag()]);
|
|
181
|
+
}
|
|
182
|
+
function openChunk(h, index, last, segment) {
|
|
183
|
+
if (segment.length < TAG_LEN)
|
|
184
|
+
throw new DecryptionError('Encrypted data is truncated');
|
|
185
|
+
try {
|
|
186
|
+
const decipher = createDecipheriv('aes-256-gcm', h.key, chunkNonce(h.noncePrefix, index, last), { authTagLength: TAG_LEN });
|
|
187
|
+
decipher.setAAD(h.header);
|
|
188
|
+
decipher.setAuthTag(segment.subarray(segment.length - TAG_LEN));
|
|
189
|
+
return Buffer.concat([decipher.update(segment.subarray(0, segment.length - TAG_LEN)), decipher.final()]);
|
|
190
|
+
}
|
|
191
|
+
catch {
|
|
192
|
+
throw new DecryptionError();
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
function decryptV2(encrypted, passphrase) {
|
|
196
|
+
const h = openV2Header(Buffer.from(encrypted.subarray(0, V2_HEADER_LEN)), passphrase);
|
|
197
|
+
const segment = h.chunkSize + TAG_LEN;
|
|
198
|
+
const out = [];
|
|
199
|
+
let o = V2_HEADER_LEN;
|
|
200
|
+
let index = 0;
|
|
201
|
+
for (; encrypted.length - o > segment; o += segment)
|
|
202
|
+
out.push(openChunk(h, index++, false, encrypted.subarray(o, o + segment)));
|
|
203
|
+
out.push(openChunk(h, index, true, encrypted.subarray(o)));
|
|
204
|
+
return Buffer.concat(out);
|
|
205
|
+
}
|
|
206
|
+
/** Pending bytes as a list of pieces, so many small writes are not re-copied on every write. */
|
|
207
|
+
class ByteQueue {
|
|
208
|
+
pieces = [];
|
|
209
|
+
length = 0;
|
|
210
|
+
push(b) {
|
|
211
|
+
if (b.length === 0)
|
|
212
|
+
return;
|
|
213
|
+
this.pieces.push(b);
|
|
214
|
+
this.length += b.length;
|
|
215
|
+
}
|
|
216
|
+
/** Removes and returns the first `n` bytes (n <= length), copying only when they span pieces. */
|
|
217
|
+
take(n) {
|
|
218
|
+
const parts = [];
|
|
219
|
+
let need = n;
|
|
220
|
+
while (need > 0) {
|
|
221
|
+
const head = this.pieces[0];
|
|
222
|
+
if (head.length <= need) {
|
|
223
|
+
parts.push(head);
|
|
224
|
+
this.pieces.shift();
|
|
225
|
+
need -= head.length;
|
|
226
|
+
}
|
|
227
|
+
else {
|
|
228
|
+
parts.push(head.subarray(0, need));
|
|
229
|
+
this.pieces[0] = head.subarray(need);
|
|
230
|
+
need = 0;
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
this.length -= n;
|
|
234
|
+
return parts.length === 1 ? parts[0] : Buffer.concat(parts, n);
|
|
235
|
+
}
|
|
236
|
+
/** The first `n` bytes without removing them. */
|
|
237
|
+
peek(n) {
|
|
238
|
+
const out = this.take(n);
|
|
239
|
+
this.pieces.unshift(out);
|
|
240
|
+
this.length += n;
|
|
241
|
+
return out;
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
/**
|
|
245
|
+
* A Transform that writes version 2 of the format. It holds at most one chunk of plaintext, so a
|
|
246
|
+
* file of any size is encrypted without ever being held whole in memory.
|
|
247
|
+
*/
|
|
248
|
+
export function createEncryptStream(passphrase, options = {}) {
|
|
249
|
+
requirePassphrase(passphrase);
|
|
250
|
+
const chunkSize = options.chunkSize ?? 2 ** DEFAULT_CHUNK_LOG2;
|
|
251
|
+
const chunkLog2 = Math.log2(chunkSize);
|
|
252
|
+
if (!Number.isInteger(chunkLog2) || !within(chunkLog2, CHUNK_LOG2_LIMITS)) {
|
|
253
|
+
throw new RangeError('chunkSize must be a power of two from 1 KiB to 16 MiB');
|
|
254
|
+
}
|
|
255
|
+
const { log2N, r, p } = DEFAULT_KDF;
|
|
256
|
+
const salt = randomBytes(SALT_LEN);
|
|
257
|
+
const header = Buffer.concat([ENCRYPTED_PREFIX, Buffer.from([2, log2N, r, p, chunkLog2]), salt, randomBytes(NONCE_PREFIX_LEN)]);
|
|
258
|
+
const h = openV2Header(header, passphrase);
|
|
259
|
+
const pending = new ByteQueue();
|
|
260
|
+
let index = 0;
|
|
261
|
+
let started = false;
|
|
262
|
+
// A copy: the pushed buffer belongs to the consumer, and `header` is every chunk's AAD.
|
|
263
|
+
const pushHeader = (t) => {
|
|
264
|
+
if (!started)
|
|
265
|
+
t.push(Buffer.from(header));
|
|
266
|
+
started = true;
|
|
267
|
+
};
|
|
268
|
+
return new Transform({
|
|
269
|
+
transform(chunk, _enc, done) {
|
|
270
|
+
try {
|
|
271
|
+
pushHeader(this);
|
|
272
|
+
pending.push(chunk);
|
|
273
|
+
// Hold back the last full chunk: only the end of input says which chunk is last.
|
|
274
|
+
while (pending.length > chunkSize)
|
|
275
|
+
this.push(sealChunk(h, index++, false, pending.take(chunkSize)));
|
|
276
|
+
done();
|
|
277
|
+
}
|
|
278
|
+
catch (err) {
|
|
279
|
+
done(err);
|
|
280
|
+
}
|
|
281
|
+
},
|
|
282
|
+
flush(done) {
|
|
283
|
+
try {
|
|
284
|
+
pushHeader(this);
|
|
285
|
+
this.push(sealChunk(h, index, true, pending.take(pending.length)));
|
|
286
|
+
done();
|
|
287
|
+
}
|
|
288
|
+
catch (err) {
|
|
289
|
+
done(err);
|
|
290
|
+
}
|
|
291
|
+
},
|
|
292
|
+
});
|
|
293
|
+
}
|
|
294
|
+
/**
|
|
295
|
+
* A Transform that reads either version. Version 2 is decrypted chunk by chunk and only
|
|
296
|
+
* authenticated plaintext is emitted; version 1 is a single sealed blob, so it is buffered whole.
|
|
297
|
+
* Any failure is a DecryptionError, and the chunks emitted before it must not be trusted as a whole
|
|
298
|
+
* file: treat a stream error as fatal.
|
|
299
|
+
*/
|
|
300
|
+
export function createDecryptStream(passphrase) {
|
|
301
|
+
requirePassphrase(passphrase);
|
|
302
|
+
const pending = new ByteQueue();
|
|
303
|
+
let version = 0;
|
|
304
|
+
let h;
|
|
305
|
+
let index = 0;
|
|
306
|
+
return new Transform({
|
|
307
|
+
transform(chunk, _enc, done) {
|
|
308
|
+
try {
|
|
309
|
+
pending.push(chunk);
|
|
310
|
+
if (version === 0 && pending.length > ENCRYPTED_PREFIX.length) {
|
|
311
|
+
const head = pending.peek(ENCRYPTED_PREFIX.length + 1);
|
|
312
|
+
if (!hasPrefix(head))
|
|
313
|
+
throw new DecryptionError('Buffer is not in recognized SFEB encrypted format');
|
|
314
|
+
version = head[ENCRYPTED_PREFIX.length];
|
|
315
|
+
checkVersion(version);
|
|
316
|
+
}
|
|
317
|
+
if (version === 1 && pending.length > MAX_V1_STREAM_BYTES) {
|
|
318
|
+
throw new DecryptionError('Version 1 encrypted data is too large to read as a stream');
|
|
319
|
+
}
|
|
320
|
+
if (version !== 2)
|
|
321
|
+
return done();
|
|
322
|
+
if (!h) {
|
|
323
|
+
if (pending.length < V2_HEADER_LEN)
|
|
324
|
+
return done();
|
|
325
|
+
h = openV2Header(Buffer.from(pending.take(V2_HEADER_LEN)), passphrase);
|
|
326
|
+
}
|
|
327
|
+
const segment = h.chunkSize + TAG_LEN;
|
|
328
|
+
while (pending.length > segment)
|
|
329
|
+
this.push(openChunk(h, index++, false, pending.take(segment)));
|
|
330
|
+
done();
|
|
331
|
+
}
|
|
332
|
+
catch (err) {
|
|
333
|
+
done(err);
|
|
334
|
+
}
|
|
335
|
+
},
|
|
336
|
+
flush(done) {
|
|
337
|
+
try {
|
|
338
|
+
if (version === 0)
|
|
339
|
+
throw new DecryptionError('Buffer is not in recognized SFEB encrypted format');
|
|
340
|
+
if (version === 1) {
|
|
341
|
+
this.push(decryptWithPassphrase(pending.take(pending.length), passphrase));
|
|
342
|
+
}
|
|
343
|
+
else {
|
|
344
|
+
if (!h)
|
|
345
|
+
throw new DecryptionError('Encrypted data is truncated');
|
|
346
|
+
this.push(openChunk(h, index, true, pending.take(pending.length)));
|
|
347
|
+
}
|
|
348
|
+
done();
|
|
349
|
+
}
|
|
350
|
+
catch (err) {
|
|
351
|
+
done(err);
|
|
352
|
+
}
|
|
353
|
+
},
|
|
354
|
+
});
|
|
355
|
+
}
|
|
96
356
|
//# sourceMappingURL=bundleCrypto.js.map
|
package/lib/graph/validate.js
CHANGED
|
@@ -20,7 +20,7 @@ import { codepointCompare } from '../lib/order.js';
|
|
|
20
20
|
// its rule code, the offending id and a fix, so an operator repairs a graph in one pass. Stopping
|
|
21
21
|
// at the first error would report one problem per run against documents that routinely carry
|
|
22
22
|
// thousands of nodes.
|
|
23
|
-
// nosemgrep: javascript.ajv.security.audit.ajv-allerrors-true
|
|
23
|
+
// nosemgrep: javascript.ajv.security.audit.ajv-allerrors-true.ajv-allerrors-true
|
|
24
24
|
const ajv = new Ajv({ allErrors: true, strict: false });
|
|
25
25
|
const validateShape = ajv.compile(GRAPH_SCHEMA);
|
|
26
26
|
/** Edge identity used in findings, so a reader can locate the offending edge in the file. */
|
package/lib/index.d.ts
CHANGED
|
@@ -24,7 +24,7 @@ export { DEFAULT_BRANDING, resolveBranding } from './report/branding.js';
|
|
|
24
24
|
export { fontFaceCss, firaFontFaceCss } from './report/fonts.js';
|
|
25
25
|
export { esc, STRICT_CSP_META, INTERACTIVE_CSP_META } from './renderers/html-utils.js';
|
|
26
26
|
export { secureFs, SECURE_DIR_MODE, SECURE_FILE_MODE } from './fs/secureFs.js';
|
|
27
|
-
export { ENCRYPTED_MAGIC, DecryptionError, isEncryptedBuffer, encryptWithPassphrase, decryptWithPassphrase, } from './crypto/bundleCrypto.js';
|
|
27
|
+
export { ENCRYPTED_MAGIC, ENCRYPTED_PREFIX, DecryptionError, isEncryptedBuffer, encryptWithPassphrase, decryptWithPassphrase, createEncryptStream, createDecryptStream, type EncryptStreamOptions, } from './crypto/bundleCrypto.js';
|
|
28
28
|
export type { RiskLevel } from './findings/RiskLevel.js';
|
|
29
29
|
export { RISK_LEVELS } from './findings/RiskLevel.js';
|
|
30
30
|
export * from './platform/index.js';
|
package/lib/index.js
CHANGED
|
@@ -18,7 +18,7 @@ export { esc, STRICT_CSP_META, INTERACTIVE_CSP_META } from './renderers/html-uti
|
|
|
18
18
|
// --- Filesystem security ---
|
|
19
19
|
export { secureFs, SECURE_DIR_MODE, SECURE_FILE_MODE } from './fs/secureFs.js';
|
|
20
20
|
// --- Encryption at rest ---
|
|
21
|
-
export { ENCRYPTED_MAGIC, DecryptionError, isEncryptedBuffer, encryptWithPassphrase, decryptWithPassphrase, } from './crypto/bundleCrypto.js';
|
|
21
|
+
export { ENCRYPTED_MAGIC, ENCRYPTED_PREFIX, DecryptionError, isEncryptedBuffer, encryptWithPassphrase, decryptWithPassphrase, createEncryptStream, createDecryptStream, } from './crypto/bundleCrypto.js';
|
|
22
22
|
export { RISK_LEVELS } from './findings/RiskLevel.js';
|
|
23
23
|
// --- Platform behaviour (API routing, Id validation, repositories) ---
|
|
24
24
|
export * from './platform/index.js';
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A minimal object-store connection: whole-object reads and writes by full key, one page of
|
|
3
|
+
* listing at a time. Prefixes are the caller's business; the store never adds one.
|
|
4
|
+
*/
|
|
5
|
+
export interface ObjectStore {
|
|
6
|
+
/** The object's bytes, or null when no such key exists. */
|
|
7
|
+
get(key: string): Promise<Buffer | null>;
|
|
8
|
+
put(key: string, bytes: Buffer, contentType: string): Promise<void>;
|
|
9
|
+
/** Create-only (If-None-Match: *). false when the key already exists (HTTP 412). */
|
|
10
|
+
putIfAbsent(key: string, bytes: Buffer, contentType: string): Promise<boolean>;
|
|
11
|
+
/** One page. `delimiter: '/'` fills `prefixes`. */
|
|
12
|
+
list(args: {
|
|
13
|
+
prefix: string;
|
|
14
|
+
delimiter?: string;
|
|
15
|
+
maxKeys?: number;
|
|
16
|
+
token?: string;
|
|
17
|
+
}): Promise<{
|
|
18
|
+
keys: Array<{
|
|
19
|
+
key: string;
|
|
20
|
+
size: number;
|
|
21
|
+
}>;
|
|
22
|
+
prefixes: string[];
|
|
23
|
+
next?: string;
|
|
24
|
+
}>;
|
|
25
|
+
}
|
|
26
|
+
//# sourceMappingURL=ObjectStore.d.ts.map
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import type { ObjectStore } from './ObjectStore.js';
|
|
2
|
+
import type { S3Endpoint } from './s3Location.js';
|
|
3
|
+
export interface S3ObjectStoreOptions {
|
|
4
|
+
/** Tests inject a fake; otherwise an S3Client is built from the endpoint. */
|
|
5
|
+
client?: {
|
|
6
|
+
send(cmd: unknown): Promise<unknown>;
|
|
7
|
+
};
|
|
8
|
+
/** Explicit credentials (for example a bucket-scoped R2 key). Without them the SDK's default chain applies. */
|
|
9
|
+
credentials?: {
|
|
10
|
+
accessKeyId: string;
|
|
11
|
+
secretAccessKey: string;
|
|
12
|
+
};
|
|
13
|
+
}
|
|
14
|
+
/** S3Client settings. Path-style and WHEN_REQUIRED checksums keep R2 and other S3-compatible services happy. */
|
|
15
|
+
export declare function s3ClientConfig(ep: S3Endpoint, credentials?: {
|
|
16
|
+
accessKeyId: string;
|
|
17
|
+
secretAccessKey: string;
|
|
18
|
+
}): Record<string, unknown>;
|
|
19
|
+
export declare function createS3ObjectStore(bucket: string, ep: S3Endpoint, opts?: S3ObjectStoreOptions): Promise<ObjectStore>;
|
|
20
|
+
//# sourceMappingURL=S3ObjectStoreImpl.d.ts.map
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
import { BucketMissingError, StorageAccessDeniedError } from './errors.js';
|
|
2
|
+
/** S3Client settings. Path-style and WHEN_REQUIRED checksums keep R2 and other S3-compatible services happy. */
|
|
3
|
+
export function s3ClientConfig(ep, credentials) {
|
|
4
|
+
return {
|
|
5
|
+
...(credentials && { credentials: { accessKeyId: credentials.accessKeyId, secretAccessKey: credentials.secretAccessKey } }),
|
|
6
|
+
region: ep.region,
|
|
7
|
+
endpoint: ep.endpoint,
|
|
8
|
+
forcePathStyle: ep.custom,
|
|
9
|
+
requestChecksumCalculation: 'WHEN_REQUIRED',
|
|
10
|
+
responseChecksumValidation: 'WHEN_REQUIRED',
|
|
11
|
+
};
|
|
12
|
+
}
|
|
13
|
+
const SECRET_ENV = ['AWS_SECRET_ACCESS_KEY', 'AWS_SESSION_TOKEN', 'AWS_ACCESS_KEY_ID'];
|
|
14
|
+
/**
|
|
15
|
+
* Replace any credential value found in the environment with [redacted].
|
|
16
|
+
*
|
|
17
|
+
* Explicitly passed credentials are redacted too. Scope otherwise: only the values of AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY and AWS_SESSION_TOKEN as set in
|
|
18
|
+
* process.env (values shorter than 4 characters are left alone). Credentials the SDK resolves from
|
|
19
|
+
* other sources (shared ini files, SSO, process, web-identity or instance-metadata providers) are not
|
|
20
|
+
* known here and are not redacted; neither is anything else in the message.
|
|
21
|
+
*/
|
|
22
|
+
function redact(text, extra = []) {
|
|
23
|
+
let out = text;
|
|
24
|
+
for (const v of extra)
|
|
25
|
+
if (v.length >= 4)
|
|
26
|
+
out = out.split(v).join('[redacted]');
|
|
27
|
+
for (const name of SECRET_ENV) {
|
|
28
|
+
const v = process.env[name];
|
|
29
|
+
if (v && v.length >= 4)
|
|
30
|
+
out = out.split(v).join('[redacted]');
|
|
31
|
+
}
|
|
32
|
+
return out;
|
|
33
|
+
}
|
|
34
|
+
function statusOf(e) {
|
|
35
|
+
return e.$metadata?.httpStatusCode;
|
|
36
|
+
}
|
|
37
|
+
function isNotFound(e) {
|
|
38
|
+
return e.name === 'NoSuchKey' || e.name === 'NotFound' || statusOf(e) === 404;
|
|
39
|
+
}
|
|
40
|
+
function isPreconditionFailed(e) {
|
|
41
|
+
return e.name === 'PreconditionFailed' || statusOf(e) === 412;
|
|
42
|
+
}
|
|
43
|
+
/** R2 answers a put-if-absent on an existing key under a lock rule with 409 ObjectLockedByBucketPolicy, not 412. */
|
|
44
|
+
function isObjectLocked(e) {
|
|
45
|
+
return [e.name, e.Code, e.code].includes('ObjectLockedByBucketPolicy');
|
|
46
|
+
}
|
|
47
|
+
function toStorageError(err, bucket, secrets = []) {
|
|
48
|
+
const e = (err ?? {});
|
|
49
|
+
const message = redact(e.message ?? String(err), secrets);
|
|
50
|
+
if (e.name === 'NoSuchBucket')
|
|
51
|
+
return new BucketMissingError(bucket);
|
|
52
|
+
if (e.name === 'AccessDenied' || statusOf(e) === 403) {
|
|
53
|
+
return new StorageAccessDeniedError(bucket, `Access denied to bucket "${bucket}": ${message}`);
|
|
54
|
+
}
|
|
55
|
+
const out = new Error(message);
|
|
56
|
+
if (e.name)
|
|
57
|
+
out.name = e.name;
|
|
58
|
+
const status = statusOf(e);
|
|
59
|
+
if (typeof status === 'number')
|
|
60
|
+
out.status = status;
|
|
61
|
+
return out;
|
|
62
|
+
}
|
|
63
|
+
export async function createS3ObjectStore(bucket, ep, opts = {}) {
|
|
64
|
+
// One dynamic import serves both the client constructor and the Command classes, so the SDK
|
|
65
|
+
// (an optional peer) is only loaded when a store is actually created.
|
|
66
|
+
let sdk;
|
|
67
|
+
try {
|
|
68
|
+
sdk = await import('@aws-sdk/client-s3');
|
|
69
|
+
}
|
|
70
|
+
catch (err) {
|
|
71
|
+
if (err.code === 'ERR_MODULE_NOT_FOUND') {
|
|
72
|
+
throw new Error('Install @aws-sdk/client-s3 (an optional peer dependency of @cclabsnz/sf-core) to use S3 storage.');
|
|
73
|
+
}
|
|
74
|
+
throw err;
|
|
75
|
+
}
|
|
76
|
+
const client = opts.client ?? new sdk.S3Client(s3ClientConfig(ep, opts.credentials));
|
|
77
|
+
const secrets = opts.credentials ? [opts.credentials.accessKeyId, opts.credentials.secretAccessKey] : [];
|
|
78
|
+
const send = (cmd) => client.send(cmd);
|
|
79
|
+
return {
|
|
80
|
+
async get(key) {
|
|
81
|
+
try {
|
|
82
|
+
const res = (await send(new sdk.GetObjectCommand({ Bucket: bucket, Key: key })));
|
|
83
|
+
return res.Body ? Buffer.from(await res.Body.transformToByteArray()) : Buffer.alloc(0);
|
|
84
|
+
}
|
|
85
|
+
catch (err) {
|
|
86
|
+
if (isNotFound(err) && err.name !== 'NoSuchBucket')
|
|
87
|
+
return null;
|
|
88
|
+
throw toStorageError(err, bucket, secrets);
|
|
89
|
+
}
|
|
90
|
+
},
|
|
91
|
+
async put(key, bytes, contentType) {
|
|
92
|
+
try {
|
|
93
|
+
await send(new sdk.PutObjectCommand({ Bucket: bucket, Key: key, Body: bytes, ContentType: contentType }));
|
|
94
|
+
}
|
|
95
|
+
catch (err) {
|
|
96
|
+
throw toStorageError(err, bucket, secrets);
|
|
97
|
+
}
|
|
98
|
+
},
|
|
99
|
+
async putIfAbsent(key, bytes, contentType) {
|
|
100
|
+
try {
|
|
101
|
+
await send(new sdk.PutObjectCommand({ Bucket: bucket, Key: key, Body: bytes, ContentType: contentType, IfNoneMatch: '*' }));
|
|
102
|
+
return true;
|
|
103
|
+
}
|
|
104
|
+
catch (err) {
|
|
105
|
+
// A lock rule only covers objects that already exist, so a locked-key 409 means "already exists".
|
|
106
|
+
if (isPreconditionFailed(err) || isObjectLocked(err))
|
|
107
|
+
return false;
|
|
108
|
+
throw toStorageError(err, bucket, secrets);
|
|
109
|
+
}
|
|
110
|
+
},
|
|
111
|
+
async list({ prefix, delimiter, maxKeys, token }) {
|
|
112
|
+
try {
|
|
113
|
+
const res = (await send(new sdk.ListObjectsV2Command({
|
|
114
|
+
Bucket: bucket,
|
|
115
|
+
Prefix: prefix,
|
|
116
|
+
...(delimiter !== undefined && { Delimiter: delimiter }),
|
|
117
|
+
...(maxKeys !== undefined && { MaxKeys: maxKeys }),
|
|
118
|
+
...(token !== undefined && { ContinuationToken: token }),
|
|
119
|
+
})));
|
|
120
|
+
return {
|
|
121
|
+
keys: (res.Contents ?? []).map((o) => ({ key: o.Key ?? '', size: o.Size ?? 0 })),
|
|
122
|
+
prefixes: (res.CommonPrefixes ?? []).map((p) => p.Prefix ?? ''),
|
|
123
|
+
next: res.NextContinuationToken,
|
|
124
|
+
};
|
|
125
|
+
}
|
|
126
|
+
catch (err) {
|
|
127
|
+
throw toStorageError(err, bucket, secrets);
|
|
128
|
+
}
|
|
129
|
+
},
|
|
130
|
+
};
|
|
131
|
+
}
|
|
132
|
+
//# sourceMappingURL=S3ObjectStoreImpl.js.map
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/** The bucket does not exist (S3 NoSuchBucket). */
|
|
2
|
+
export declare class BucketMissingError extends Error {
|
|
3
|
+
readonly bucket: string;
|
|
4
|
+
constructor(bucket: string, message?: string);
|
|
5
|
+
}
|
|
6
|
+
/** The credentials were rejected for the bucket (AccessDenied / HTTP 403). */
|
|
7
|
+
export declare class StorageAccessDeniedError extends Error {
|
|
8
|
+
readonly bucket: string;
|
|
9
|
+
constructor(bucket: string, message?: string);
|
|
10
|
+
}
|
|
11
|
+
//# sourceMappingURL=errors.d.ts.map
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/** The bucket does not exist (S3 NoSuchBucket). */
|
|
2
|
+
export class BucketMissingError extends Error {
|
|
3
|
+
bucket;
|
|
4
|
+
constructor(bucket, message) {
|
|
5
|
+
super(message ?? `Bucket "${bucket}" does not exist`);
|
|
6
|
+
this.name = 'BucketMissingError';
|
|
7
|
+
this.bucket = bucket;
|
|
8
|
+
}
|
|
9
|
+
}
|
|
10
|
+
/** The credentials were rejected for the bucket (AccessDenied / HTTP 403). */
|
|
11
|
+
export class StorageAccessDeniedError extends Error {
|
|
12
|
+
bucket;
|
|
13
|
+
constructor(bucket, message) {
|
|
14
|
+
super(message ?? `Access denied to bucket "${bucket}"`);
|
|
15
|
+
this.name = 'StorageAccessDeniedError';
|
|
16
|
+
this.bucket = bucket;
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
//# sourceMappingURL=errors.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
export type { ObjectStore } from './ObjectStore.js';
|
|
2
|
+
export { BucketMissingError, StorageAccessDeniedError } from './errors.js';
|
|
3
|
+
export { isS3Uri, parseS3Uri, resolveS3Endpoint, s3Host } from './s3Location.js';
|
|
4
|
+
export type { S3Endpoint, S3Location } from './s3Location.js';
|
|
5
|
+
export { createS3ObjectStore, s3ClientConfig } from './S3ObjectStoreImpl.js';
|
|
6
|
+
export type { S3ObjectStoreOptions } from './S3ObjectStoreImpl.js';
|
|
7
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
export { BucketMissingError, StorageAccessDeniedError } from './errors.js';
|
|
2
|
+
export { isS3Uri, parseS3Uri, resolveS3Endpoint, s3Host } from './s3Location.js';
|
|
3
|
+
export { createS3ObjectStore, s3ClientConfig } from './S3ObjectStoreImpl.js';
|
|
4
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
/** Where objects live: a bucket and a key prefix ('' or 'a/b', no leading or trailing '/'). */
|
|
2
|
+
export interface S3Location {
|
|
3
|
+
bucket: string;
|
|
4
|
+
prefix: string;
|
|
5
|
+
}
|
|
6
|
+
export declare function isS3Uri(s: string): boolean;
|
|
7
|
+
export declare function parseS3Uri(uri: string): S3Location;
|
|
8
|
+
export interface S3Endpoint {
|
|
9
|
+
endpoint: string;
|
|
10
|
+
region: string;
|
|
11
|
+
/** True when the endpoint came from the environment (R2, MinIO...) rather than the AWS region. */
|
|
12
|
+
custom: boolean;
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* Resolve the endpoint from the standard AWS environment variables.
|
|
16
|
+
* `AWS_ENDPOINT_URL_S3` beats `AWS_ENDPOINT_URL`; `AWS_REGION` beats `AWS_DEFAULT_REGION`.
|
|
17
|
+
* A custom endpoint defaults the region to `auto` (Cloudflare R2); with none, a region is required.
|
|
18
|
+
*/
|
|
19
|
+
export declare function resolveS3Endpoint(env: NodeJS.ProcessEnv): S3Endpoint;
|
|
20
|
+
/**
|
|
21
|
+
* The host the S3 client actually contacts for `bucket`, for naming network destinations truthfully.
|
|
22
|
+
* A custom endpoint (R2, MinIO...) is used path-style, so the host is the endpoint's own host.
|
|
23
|
+
* AWS S3 is used virtual-hosted style, so the bucket is part of the host:
|
|
24
|
+
* `<bucket>.s3.<region>.amazonaws.com`. The SDK falls back to path style, and so to
|
|
25
|
+
* `s3.<region>.amazonaws.com`, for a bucket name that cannot be a single DNS label over https
|
|
26
|
+
* (one with a dot, upper case or an underscore), and this mirrors that rule.
|
|
27
|
+
*/
|
|
28
|
+
export declare function s3Host(bucket: string, ep: S3Endpoint): string;
|
|
29
|
+
//# sourceMappingURL=s3Location.d.ts.map
|