@cclabsnz/sf-core 0.12.0 → 0.13.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 CHANGED
@@ -10,6 +10,42 @@ CycloneDX SBOM for the build.
10
10
 
11
11
  ## [Unreleased]
12
12
 
13
+ ## [0.13.0] — 2026-11-27
14
+
15
+ ### Added
16
+
17
+ - **`@cclabsnz/sf-core/storage`: an S3-compatible `ObjectStore`.** `createS3ObjectStore` connects to
18
+ AWS S3, Cloudflare R2 or MinIO with whole-object `get`, `put`, create-only `putIfAbsent`
19
+ (`If-None-Match: *`) and paged `list`. `resolveS3Endpoint`, `parseS3Uri`, `BucketMissingError`
20
+ and `StorageAccessDeniedError` come with it, and credential values are redacted from every
21
+ error it raises. `@aws-sdk/client-s3` is an optional peer, loaded only when a store is created.
22
+ `@cclabsnz/sf-core/storage/testing` exports `MemoryObjectStore` for tests.
23
+ `s3Host(bucket, endpoint)` names the host the client actually contacts (`<bucket>.s3.<region>.amazonaws.com`
24
+ for AWS, or path-style `s3.<region>.amazonaws.com` for bucket names that are not one DNS label;
25
+ the endpoint's host for a custom endpoint), so tools can list network destinations truthfully.
26
+ Redaction covers credential values set in the environment (`AWS_ACCESS_KEY_ID`,
27
+ `AWS_SECRET_ACCESS_KEY`, `AWS_SESSION_TOKEN`) only.
28
+ - **Chunked, streaming encryption: version 2 of the `SFEB` format.** `createEncryptStream` and
29
+ `createDecryptStream` are Node `Transform`s that encrypt and decrypt a file of any size while
30
+ holding at most one chunk (64 KiB by default) in memory. Each chunk is sealed with AES-256-GCM
31
+ under the STREAM construction, so reordered, repeated, dropped or appended chunks, and a file
32
+ cut at a chunk boundary, all fail with `DecryptionError`. The header carries the scrypt
33
+ parameters and chunk size, both bounded before any key is derived. A stream refuses a version 1
34
+ input over 64 MiB rather than buffering it whole.
35
+ - `ENCRYPTED_PREFIX`, the 4-byte `SFEB` prefix shared by every format version.
36
+
37
+ ### Changed
38
+
39
+ - `decryptWithPassphrase` and `createDecryptStream` read both versions; version 1 files are
40
+ unchanged and still readable. `isEncryptedBuffer` now also recognises version 2, and an
41
+ unknown version fails as "Unsupported SFEB format version N" instead of "not in recognized SFEB
42
+ encrypted format".
43
+ - **A header's scrypt settings are bounded together, not only one by one**, for both versions:
44
+ at most 256 MiB of memory (128·N·r) and four times the default's work (N·r·p). Settings that
45
+ passed each per-field limit could still demand about 12 s of blocking work or more than 1 GiB
46
+ per file. A key-derivation failure is now a `DecryptionError`, never a `RangeError`. Files
47
+ written with the defaults are unaffected.
48
+
13
49
  ## [0.12.0] — 2026-10-23
14
50
 
15
51
  ### Breaking
@@ -309,7 +345,8 @@ hourly capture path that dependants build on.
309
345
 
310
346
  Initial internal releases: API clients, org context, findings model and report rendering.
311
347
 
312
- [Unreleased]: https://github.com/cclabsnz/sf-core/compare/v0.4.0...HEAD
348
+ [Unreleased]: https://github.com/cclabsnz/sf-core/compare/v0.13.0...HEAD
349
+ [0.13.0]: https://github.com/cclabsnz/sf-core/releases/tag/v0.13.0
313
350
  [0.4.0]: https://github.com/cclabsnz/sf-core/releases/tag/v0.4.0
314
351
  [0.3.0]: https://github.com/cclabsnz/sf-core/releases/tag/v0.3.0
315
352
  [0.2.0]: https://github.com/cclabsnz/sf-core/releases/tag/v0.2.0
package/README.md CHANGED
@@ -21,6 +21,7 @@ contracts behind [`@cclabsnz/sf-audit`](https://www.npmjs.com/package/@cclabsnz/
21
21
 
22
22
  | Area | What it provides |
23
23
  | --- | --- |
24
+ | **Storage** | `ObjectStore`, an S3-compatible connection (AWS S3, Cloudflare R2, MinIO) from `@cclabsnz/sf-core/storage`, with `MemoryObjectStore` in `@cclabsnz/sf-core/storage/testing`. `@aws-sdk/client-s3` is an optional peer, loaded only when a store is created |
24
25
  | **API clients** | `SoqlClient`, `ToolingClient`, `RestClient`, `MetadataClient`: read-only wrappers over a `@salesforce/core` `Connection`, or, via `@cclabsnz/sf-core/fetch`, over plain `fetch` with a JWT bearer login (no `@salesforce/core`; `MetadataClient` is Connection-only) |
25
26
  | **Platform behaviour** | `FlowRepository`, `ApexRepository`, `isSalesforceId`, `describeSalesforceError`, `mapWithConcurrency` |
26
27
  | **Event capture** | `EventBaselineStore`, `RTE_CATALOG`, `pullEventLogs`, `pullRealtimeEvents`, `CaptureManifest`: bounded, resumable EventLogFile and Real-Time Event pulls |
@@ -129,8 +130,8 @@ Both are enforced as tests, not asserted in prose. Run them yourself with `pnpm
129
130
  appear in source. The one exception is the OAuth token `POST` in the fetch login, which
130
131
  writes no org data and is confined to one file by a test. Every org request is a SOQL query, a REST **GET**, or a Metadata read.
131
132
  - **Local-first.** No third-party HTTP client, telemetry endpoint, LLM call, websocket, or
132
- remote asset in a generated report. The only network destination is the org the operator
133
- authenticated against.
133
+ remote asset in a generated report. The only network destinations are the org the operator
134
+ authenticated against, or an object-storage endpoint the caller passes explicitly.
134
135
 
135
136
  ## Versioning
136
137
 
@@ -1,3 +1,4 @@
1
+ import { Transform } from 'node:stream';
1
2
  /**
2
3
  * Passphrase encryption for files that hold org data at rest (incident bundles).
3
4
  *
@@ -8,13 +9,41 @@
8
9
  * AES-256-GCM with a key from scrypt. The scrypt parameters travel in the header so they can be
9
10
  * raised later without stranding existing files, and the whole header is authenticated as GCM
10
11
  * additional data, so altering any byte of it fails decryption.
12
+ *
13
+ * Format, version 2 (chunked, for files too large to hold in memory):
14
+ *
15
+ * 'SFEB' | version (1) | log2(N) (1) | r (1) | p (1) | log2(chunk) (1) | salt (16) | nonce prefix (7)
16
+ * then one segment per chunk: ciphertext (chunk bytes, the last one 0..chunk) | tag (16)
17
+ *
18
+ * The STREAM construction (Hoang, Reyhanitabar, Rogaway, Vizár 2015), as age and Tink use it: each
19
+ * chunk is sealed on its own with nonce = prefix | chunk index (4, big-endian) | last-chunk flag (1),
20
+ * and the header is every chunk's additional data. Reordered, repeated, dropped or appended chunks,
21
+ * and a file cut at a chunk boundary, all fail authentication. A reader may emit the chunks before
22
+ * a failure, each of which authenticated, so a consumer must treat a stream error as fatal.
11
23
  */
24
+ export declare const ENCRYPTED_PREFIX: Buffer<ArrayBuffer>;
12
25
  export declare const ENCRYPTED_MAGIC: Buffer<ArrayBuffer>;
13
26
  export declare class DecryptionError extends Error {
14
27
  constructor(message?: string);
15
28
  }
16
- /** Whether `buf` starts with this format's header. Says nothing about whether it will decrypt. */
29
+ /** Whether `buf` starts with a header of a known version. Says nothing about whether it will decrypt. */
17
30
  export declare function isEncryptedBuffer(buf: Buffer): boolean;
18
31
  export declare function encryptWithPassphrase(plaintext: Buffer | string, passphrase: string): Buffer;
19
32
  export declare function decryptWithPassphrase(encrypted: Buffer, passphrase: string): Buffer;
33
+ export type EncryptStreamOptions = {
34
+ /** Plaintext bytes per chunk: a power of two from 1 KiB to 16 MiB. Defaults to 64 KiB. */
35
+ chunkSize?: number;
36
+ };
37
+ /**
38
+ * A Transform that writes version 2 of the format. It holds at most one chunk of plaintext, so a
39
+ * file of any size is encrypted without ever being held whole in memory.
40
+ */
41
+ export declare function createEncryptStream(passphrase: string, options?: EncryptStreamOptions): Transform;
42
+ /**
43
+ * A Transform that reads either version. Version 2 is decrypted chunk by chunk and only
44
+ * authenticated plaintext is emitted; version 1 is a single sealed blob, so it is buffered whole.
45
+ * Any failure is a DecryptionError, and the chunks emitted before it must not be trusted as a whole
46
+ * file: treat a stream error as fatal.
47
+ */
48
+ export declare function createDecryptStream(passphrase: string): Transform;
20
49
  //# sourceMappingURL=bundleCrypto.d.ts.map
@@ -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 this format's header. Says nothing about whether it will decrypt. */
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
- return buf.length >= MIN_LEN && buf.subarray(0, ENCRYPTED_MAGIC.length).equals(ENCRYPTED_MAGIC);
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 (!isEncryptedBuffer(encrypted)) {
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 [log2N, r, p] = [encrypted[o++], encrypted[o++], encrypted[o++]];
76
- const within = (v, [lo, hi]) => v >= lo && v <= hi;
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
@@ -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,2 @@
1
+ export {};
2
+ //# sourceMappingURL=ObjectStore.js.map
@@ -0,0 +1,12 @@
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
+ }
9
+ /** S3Client settings. Path-style and WHEN_REQUIRED checksums keep R2 and other S3-compatible services happy. */
10
+ export declare function s3ClientConfig(ep: S3Endpoint): Record<string, unknown>;
11
+ export declare function createS3ObjectStore(bucket: string, ep: S3Endpoint, opts?: S3ObjectStoreOptions): Promise<ObjectStore>;
12
+ //# sourceMappingURL=S3ObjectStoreImpl.d.ts.map
@@ -0,0 +1,122 @@
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) {
4
+ return {
5
+ region: ep.region,
6
+ endpoint: ep.endpoint,
7
+ forcePathStyle: ep.custom,
8
+ requestChecksumCalculation: 'WHEN_REQUIRED',
9
+ responseChecksumValidation: 'WHEN_REQUIRED',
10
+ };
11
+ }
12
+ const SECRET_ENV = ['AWS_SECRET_ACCESS_KEY', 'AWS_SESSION_TOKEN', 'AWS_ACCESS_KEY_ID'];
13
+ /**
14
+ * Replace any credential value found in the environment with [redacted].
15
+ *
16
+ * Scope: only the values of AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY and AWS_SESSION_TOKEN as set in
17
+ * process.env (values shorter than 4 characters are left alone). Credentials the SDK resolves from
18
+ * other sources (shared ini files, SSO, process, web-identity or instance-metadata providers) are not
19
+ * known here and are not redacted; neither is anything else in the message.
20
+ */
21
+ function redact(text) {
22
+ let out = text;
23
+ for (const name of SECRET_ENV) {
24
+ const v = process.env[name];
25
+ if (v && v.length >= 4)
26
+ out = out.split(v).join('[redacted]');
27
+ }
28
+ return out;
29
+ }
30
+ function statusOf(e) {
31
+ return e.$metadata?.httpStatusCode;
32
+ }
33
+ function isNotFound(e) {
34
+ return e.name === 'NoSuchKey' || e.name === 'NotFound' || statusOf(e) === 404;
35
+ }
36
+ function isPreconditionFailed(e) {
37
+ return e.name === 'PreconditionFailed' || statusOf(e) === 412;
38
+ }
39
+ function toStorageError(err, bucket) {
40
+ const e = (err ?? {});
41
+ const message = redact(e.message ?? String(err));
42
+ if (e.name === 'NoSuchBucket')
43
+ return new BucketMissingError(bucket);
44
+ if (e.name === 'AccessDenied' || statusOf(e) === 403) {
45
+ return new StorageAccessDeniedError(bucket, `Access denied to bucket "${bucket}": ${message}`);
46
+ }
47
+ const out = new Error(message);
48
+ if (e.name)
49
+ out.name = e.name;
50
+ const status = statusOf(e);
51
+ if (typeof status === 'number')
52
+ out.status = status;
53
+ return out;
54
+ }
55
+ export async function createS3ObjectStore(bucket, ep, opts = {}) {
56
+ // One dynamic import serves both the client constructor and the Command classes, so the SDK
57
+ // (an optional peer) is only loaded when a store is actually created.
58
+ let sdk;
59
+ try {
60
+ sdk = await import('@aws-sdk/client-s3');
61
+ }
62
+ catch (err) {
63
+ if (err.code === 'ERR_MODULE_NOT_FOUND') {
64
+ throw new Error('Install @aws-sdk/client-s3 (an optional peer dependency of @cclabsnz/sf-core) to use S3 storage.');
65
+ }
66
+ throw err;
67
+ }
68
+ const client = opts.client ?? new sdk.S3Client(s3ClientConfig(ep));
69
+ const send = (cmd) => client.send(cmd);
70
+ return {
71
+ async get(key) {
72
+ try {
73
+ const res = (await send(new sdk.GetObjectCommand({ Bucket: bucket, Key: key })));
74
+ return res.Body ? Buffer.from(await res.Body.transformToByteArray()) : Buffer.alloc(0);
75
+ }
76
+ catch (err) {
77
+ if (isNotFound(err) && err.name !== 'NoSuchBucket')
78
+ return null;
79
+ throw toStorageError(err, bucket);
80
+ }
81
+ },
82
+ async put(key, bytes, contentType) {
83
+ try {
84
+ await send(new sdk.PutObjectCommand({ Bucket: bucket, Key: key, Body: bytes, ContentType: contentType }));
85
+ }
86
+ catch (err) {
87
+ throw toStorageError(err, bucket);
88
+ }
89
+ },
90
+ async putIfAbsent(key, bytes, contentType) {
91
+ try {
92
+ await send(new sdk.PutObjectCommand({ Bucket: bucket, Key: key, Body: bytes, ContentType: contentType, IfNoneMatch: '*' }));
93
+ return true;
94
+ }
95
+ catch (err) {
96
+ if (isPreconditionFailed(err))
97
+ return false;
98
+ throw toStorageError(err, bucket);
99
+ }
100
+ },
101
+ async list({ prefix, delimiter, maxKeys, token }) {
102
+ try {
103
+ const res = (await send(new sdk.ListObjectsV2Command({
104
+ Bucket: bucket,
105
+ Prefix: prefix,
106
+ ...(delimiter !== undefined && { Delimiter: delimiter }),
107
+ ...(maxKeys !== undefined && { MaxKeys: maxKeys }),
108
+ ...(token !== undefined && { ContinuationToken: token }),
109
+ })));
110
+ return {
111
+ keys: (res.Contents ?? []).map((o) => ({ key: o.Key ?? '', size: o.Size ?? 0 })),
112
+ prefixes: (res.CommonPrefixes ?? []).map((p) => p.Prefix ?? ''),
113
+ next: res.NextContinuationToken,
114
+ };
115
+ }
116
+ catch (err) {
117
+ throw toStorageError(err, bucket);
118
+ }
119
+ },
120
+ };
121
+ }
122
+ //# 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
@@ -0,0 +1,63 @@
1
+ export function isS3Uri(s) {
2
+ return s.startsWith('s3://');
3
+ }
4
+ export function parseS3Uri(uri) {
5
+ if (!isS3Uri(uri))
6
+ throw new Error(`Not an s3:// URI: ${uri}`);
7
+ const rest = uri.slice('s3://'.length);
8
+ const slash = rest.indexOf('/');
9
+ const bucket = slash === -1 ? rest : rest.slice(0, slash);
10
+ if (!bucket)
11
+ throw new Error(`s3:// URI has no bucket: ${uri}`);
12
+ // Split and drop empty segments rather than trim with a /^\/+|\/+$/ regex: that backtracks
13
+ // quadratically on a long run of '/', and a prefix is caller input.
14
+ const prefix = slash === -1 ? '' : rest.slice(slash + 1).split('/').filter(Boolean).join('/');
15
+ return { bucket, prefix };
16
+ }
17
+ const LOOPBACK = new Set(['localhost', '127.0.0.1', '[::1]', '::1']);
18
+ /**
19
+ * Resolve the endpoint from the standard AWS environment variables.
20
+ * `AWS_ENDPOINT_URL_S3` beats `AWS_ENDPOINT_URL`; `AWS_REGION` beats `AWS_DEFAULT_REGION`.
21
+ * A custom endpoint defaults the region to `auto` (Cloudflare R2); with none, a region is required.
22
+ */
23
+ export function resolveS3Endpoint(env) {
24
+ const region = env.AWS_REGION || env.AWS_DEFAULT_REGION || undefined;
25
+ const custom = env.AWS_ENDPOINT_URL_S3 || env.AWS_ENDPOINT_URL || undefined;
26
+ if (!custom) {
27
+ if (!region) {
28
+ throw new Error('Set AWS_REGION (for AWS S3) or AWS_ENDPOINT_URL_S3 (for R2 or another S3-compatible service).');
29
+ }
30
+ if (!/^[a-z0-9-]+$/.test(region))
31
+ throw new Error('AWS_REGION is not a valid region name.');
32
+ return { endpoint: `https://s3.${region}.amazonaws.com`, region, custom: false };
33
+ }
34
+ let url;
35
+ try {
36
+ url = new URL(custom);
37
+ }
38
+ catch {
39
+ throw new Error('The S3 endpoint (AWS_ENDPOINT_URL_S3 or AWS_ENDPOINT_URL) is not a valid URL.');
40
+ }
41
+ if (url.username || url.password)
42
+ throw new Error('The S3 endpoint must not contain credentials.');
43
+ if (url.protocol !== 'https:' && !(url.protocol === 'http:' && LOOPBACK.has(url.hostname))) {
44
+ throw new Error('The S3 endpoint (AWS_ENDPOINT_URL_S3 or AWS_ENDPOINT_URL) must use https; http is allowed only for localhost.');
45
+ }
46
+ return { endpoint: custom, region: region ?? 'auto', custom: true };
47
+ }
48
+ /**
49
+ * The host the S3 client actually contacts for `bucket`, for naming network destinations truthfully.
50
+ * A custom endpoint (R2, MinIO...) is used path-style, so the host is the endpoint's own host.
51
+ * AWS S3 is used virtual-hosted style, so the bucket is part of the host:
52
+ * `<bucket>.s3.<region>.amazonaws.com`. The SDK falls back to path style, and so to
53
+ * `s3.<region>.amazonaws.com`, for a bucket name that cannot be a single DNS label over https
54
+ * (one with a dot, upper case or an underscore), and this mirrors that rule.
55
+ */
56
+ export function s3Host(bucket, ep) {
57
+ if (ep.custom)
58
+ return new URL(ep.endpoint).host;
59
+ return VIRTUAL_HOSTABLE.test(bucket) ? `${bucket}.s3.${ep.region}.amazonaws.com` : `s3.${ep.region}.amazonaws.com`;
60
+ }
61
+ /** The AWS SDK's isVirtualHostableS3Bucket without sub-domains: 3-63 lower-case letters, digits and inner hyphens. */
62
+ const VIRTUAL_HOSTABLE = /^[a-z0-9][a-z0-9-]{1,61}[a-z0-9]$/;
63
+ //# sourceMappingURL=s3Location.js.map
@@ -0,0 +1,32 @@
1
+ import type { ObjectStore } from '../ObjectStore.js';
2
+ /** In-memory ObjectStore for tests. Keys list in lexical order; the token is the last key returned. */
3
+ export declare class MemoryObjectStore implements ObjectStore {
4
+ readonly objects: Map<string, Buffer<ArrayBufferLike>>;
5
+ /** Return an Error to make the next put/putIfAbsent of that key fail with it. */
6
+ failNextPut?: (key: string) => Error | undefined;
7
+ private readonly pageSize;
8
+ private readonly bucketExists;
9
+ constructor(opts?: {
10
+ pageSize?: number;
11
+ bucketExists?: boolean;
12
+ });
13
+ private check;
14
+ private maybeFail;
15
+ get(key: string): Promise<Buffer | null>;
16
+ put(key: string, bytes: Buffer, _contentType: string): Promise<void>;
17
+ putIfAbsent(key: string, bytes: Buffer, _contentType: string): Promise<boolean>;
18
+ list(args: {
19
+ prefix: string;
20
+ delimiter?: string;
21
+ maxKeys?: number;
22
+ token?: string;
23
+ }): Promise<{
24
+ keys: Array<{
25
+ key: string;
26
+ size: number;
27
+ }>;
28
+ prefixes: string[];
29
+ next?: string;
30
+ }>;
31
+ }
32
+ //# sourceMappingURL=MemoryObjectStore.d.ts.map
@@ -0,0 +1,79 @@
1
+ import { BucketMissingError } from '../errors.js';
2
+ /** In-memory ObjectStore for tests. Keys list in lexical order; the token is the last key returned. */
3
+ export class MemoryObjectStore {
4
+ objects = new Map();
5
+ /** Return an Error to make the next put/putIfAbsent of that key fail with it. */
6
+ failNextPut;
7
+ pageSize;
8
+ bucketExists;
9
+ constructor(opts = {}) {
10
+ this.pageSize = opts.pageSize ?? 1000;
11
+ this.bucketExists = opts.bucketExists ?? true;
12
+ }
13
+ check() {
14
+ if (!this.bucketExists)
15
+ throw new BucketMissingError('memory');
16
+ }
17
+ maybeFail(key) {
18
+ const err = this.failNextPut?.(key);
19
+ if (err) {
20
+ this.failNextPut = undefined;
21
+ throw err;
22
+ }
23
+ }
24
+ async get(key) {
25
+ this.check();
26
+ const b = this.objects.get(key);
27
+ return b ? Buffer.from(b) : null;
28
+ }
29
+ async put(key, bytes, _contentType) {
30
+ this.check();
31
+ this.maybeFail(key);
32
+ this.objects.set(key, Buffer.from(bytes));
33
+ }
34
+ async putIfAbsent(key, bytes, _contentType) {
35
+ this.check();
36
+ this.maybeFail(key);
37
+ // No await between the check and the set, so concurrent callers cannot both win.
38
+ if (this.objects.has(key))
39
+ return false;
40
+ this.objects.set(key, Buffer.from(bytes));
41
+ return true;
42
+ }
43
+ async list(args) {
44
+ this.check();
45
+ const limit = Math.min(args.maxKeys ?? this.pageSize, this.pageSize);
46
+ const keys = [];
47
+ const prefixes = [];
48
+ let count = 0;
49
+ let last;
50
+ let more = false;
51
+ for (const key of [...this.objects.keys()].filter((k) => k.startsWith(args.prefix)).sort()) {
52
+ if (args.token !== undefined && key <= args.token)
53
+ continue;
54
+ let common;
55
+ if (args.delimiter) {
56
+ const i = key.indexOf(args.delimiter, args.prefix.length);
57
+ if (i !== -1)
58
+ common = key.slice(0, i + args.delimiter.length);
59
+ }
60
+ // Further keys under an already-listed common prefix add nothing to the page.
61
+ if (common !== undefined && prefixes.includes(common)) {
62
+ continue;
63
+ }
64
+ if (count >= limit) {
65
+ more = true;
66
+ break;
67
+ }
68
+ if (common !== undefined)
69
+ prefixes.push(common);
70
+ else
71
+ keys.push({ key, size: this.objects.get(key).length });
72
+ count++;
73
+ // A token ending on a common prefix must skip the rest of that prefix on the next page.
74
+ last = common !== undefined ? common + '\uffff' : key;
75
+ }
76
+ return { keys, prefixes, next: more ? last : undefined };
77
+ }
78
+ }
79
+ //# sourceMappingURL=MemoryObjectStore.js.map
@@ -0,0 +1,2 @@
1
+ export * from './storage/index.js';
2
+ //# sourceMappingURL=storage.d.ts.map
package/lib/storage.js ADDED
@@ -0,0 +1,4 @@
1
+ // The ./storage entry point: an S3-compatible ObjectStore. @aws-sdk/client-s3 is an optional peer,
2
+ // loaded only when createS3ObjectStore runs.
3
+ export * from './storage/index.js';
4
+ //# sourceMappingURL=storage.js.map
@@ -0,0 +1,2 @@
1
+ export { MemoryObjectStore } from './storage/testing/MemoryObjectStore.js';
2
+ //# sourceMappingURL=storageTesting.d.ts.map
@@ -0,0 +1,3 @@
1
+ // The ./storage/testing entry point: an in-memory ObjectStore for tests.
2
+ export { MemoryObjectStore } from './storage/testing/MemoryObjectStore.js';
3
+ //# sourceMappingURL=storageTesting.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cclabsnz/sf-core",
3
- "version": "0.12.0",
3
+ "version": "0.13.0",
4
4
  "description": "Shared platform layer for CloudCounsel Salesforce sf plugins — API clients, org context, event log pull, report shell, and versioned IR schemas.",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",
@@ -15,6 +15,14 @@
15
15
  "types": "./lib/fetch.d.ts",
16
16
  "default": "./lib/fetch.js"
17
17
  },
18
+ "./storage": {
19
+ "types": "./lib/storage.d.ts",
20
+ "default": "./lib/storage.js"
21
+ },
22
+ "./storage/testing": {
23
+ "types": "./lib/storageTesting.d.ts",
24
+ "default": "./lib/storageTesting.js"
25
+ },
18
26
  "./testing": {
19
27
  "types": "./lib/testing/invariants.d.ts",
20
28
  "default": "./lib/testing/invariants.js"
@@ -31,6 +39,7 @@
31
39
  "prepare": "git config core.hooksPath .githooks 2>/dev/null || true"
32
40
  },
33
41
  "devDependencies": {
42
+ "@aws-sdk/client-s3": "3.1168.0",
34
43
  "@jest/globals": "^29.7.0",
35
44
  "@jsforce/jsforce-node": "3.10.19",
36
45
  "@salesforce/core": "^9",
@@ -85,11 +94,15 @@
85
94
  }
86
95
  },
87
96
  "peerDependencies": {
88
- "@salesforce/core": "^8 || ^9"
97
+ "@salesforce/core": "^8 || ^9",
98
+ "@aws-sdk/client-s3": ">=3.1168.0 <4"
89
99
  },
90
100
  "peerDependenciesMeta": {
91
101
  "@salesforce/core": {
92
102
  "optional": true
103
+ },
104
+ "@aws-sdk/client-s3": {
105
+ "optional": true
93
106
  }
94
107
  },
95
108
  "dependencies": {