@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.
Files changed (38) hide show
  1. package/CHANGELOG.md +58 -1
  2. package/README.md +3 -2
  3. package/lib/cloudflare/CloudflareClient.d.ts +53 -0
  4. package/lib/cloudflare/CloudflareClient.js +10 -0
  5. package/lib/cloudflare/FetchCloudflareClient.d.ts +6 -0
  6. package/lib/cloudflare/FetchCloudflareClient.js +152 -0
  7. package/lib/cloudflare/errors.d.ts +16 -0
  8. package/lib/cloudflare/errors.js +25 -0
  9. package/lib/cloudflare/index.d.ts +5 -0
  10. package/lib/cloudflare/index.js +4 -0
  11. package/lib/cloudflare/testing/MemoryCloudflareClient.d.ts +43 -0
  12. package/lib/cloudflare/testing/MemoryCloudflareClient.js +77 -0
  13. package/lib/cloudflare.d.ts +2 -0
  14. package/lib/cloudflare.js +4 -0
  15. package/lib/cloudflareTesting.d.ts +3 -0
  16. package/lib/cloudflareTesting.js +3 -0
  17. package/lib/crypto/bundleCrypto.d.ts +30 -1
  18. package/lib/crypto/bundleCrypto.js +269 -9
  19. package/lib/graph/validate.js +1 -1
  20. package/lib/index.d.ts +1 -1
  21. package/lib/index.js +1 -1
  22. package/lib/storage/ObjectStore.d.ts +26 -0
  23. package/lib/storage/ObjectStore.js +2 -0
  24. package/lib/storage/S3ObjectStoreImpl.d.ts +20 -0
  25. package/lib/storage/S3ObjectStoreImpl.js +132 -0
  26. package/lib/storage/errors.d.ts +11 -0
  27. package/lib/storage/errors.js +19 -0
  28. package/lib/storage/index.d.ts +7 -0
  29. package/lib/storage/index.js +4 -0
  30. package/lib/storage/s3Location.d.ts +29 -0
  31. package/lib/storage/s3Location.js +63 -0
  32. package/lib/storage/testing/MemoryObjectStore.d.ts +32 -0
  33. package/lib/storage/testing/MemoryObjectStore.js +79 -0
  34. package/lib/storage.d.ts +2 -0
  35. package/lib/storage.js +4 -0
  36. package/lib/storageTesting.d.ts +2 -0
  37. package/lib/storageTesting.js +3 -0
  38. package/package.json +23 -2
package/CHANGELOG.md CHANGED
@@ -10,6 +10,62 @@ CycloneDX SBOM for the build.
10
10
 
11
11
  ## [Unreleased]
12
12
 
13
+ ## [0.14.0] — 2026-11-29
14
+
15
+ ### Added
16
+
17
+ - **`@cclabsnz/sf-core/cloudflare`: a Cloudflare client for guided R2 setup.** `createCloudflareClient(token)`
18
+ verifies an account-owned API token, lists accounts, checks that R2 is enabled, gets or creates a
19
+ bucket (EU and other jurisdictions included), merges object lock rules without dropping existing
20
+ ones, and creates and deletes a bucket-scoped API token. Permission groups are looked up by name,
21
+ and the S3 key pair is derived from the new token (`deriveR2Credentials`). `r2Endpoint(accountId, jurisdiction)`
22
+ gives the S3 endpoint. Failures raise `CloudflareApiError` (`status`, `code`, and `missingPermission`
23
+ when Cloudflare names one) or `R2NotEnabledError`; the token never appears in an error.
24
+ `@cclabsnz/sf-core/cloudflare/testing` exports `MemoryCloudflareClient` for tests.
25
+ - **`createS3ObjectStore` accepts explicit `credentials`** (`{ accessKeyId, secretAccessKey }`), for a
26
+ bucket-scoped R2 key. They are redacted from errors like the environment credentials.
27
+
28
+ ### Changed
29
+
30
+ - `putIfAbsent` returns `false` when R2 answers 409 `ObjectLockedByBucketPolicy`, as it does for 412.
31
+ A lock rule only covers objects that already exist, so this means "already exists".
32
+
33
+ ## [0.13.0] — 2026-11-27
34
+
35
+ ### Added
36
+
37
+ - **`@cclabsnz/sf-core/storage`: an S3-compatible `ObjectStore`.** `createS3ObjectStore` connects to
38
+ AWS S3, Cloudflare R2 or MinIO with whole-object `get`, `put`, create-only `putIfAbsent`
39
+ (`If-None-Match: *`) and paged `list`. `resolveS3Endpoint`, `parseS3Uri`, `BucketMissingError`
40
+ and `StorageAccessDeniedError` come with it, and credential values are redacted from every
41
+ error it raises. `@aws-sdk/client-s3` is an optional peer, loaded only when a store is created.
42
+ `@cclabsnz/sf-core/storage/testing` exports `MemoryObjectStore` for tests.
43
+ `s3Host(bucket, endpoint)` names the host the client actually contacts (`<bucket>.s3.<region>.amazonaws.com`
44
+ for AWS, or path-style `s3.<region>.amazonaws.com` for bucket names that are not one DNS label;
45
+ the endpoint's host for a custom endpoint), so tools can list network destinations truthfully.
46
+ Redaction covers credential values set in the environment (`AWS_ACCESS_KEY_ID`,
47
+ `AWS_SECRET_ACCESS_KEY`, `AWS_SESSION_TOKEN`) only.
48
+ - **Chunked, streaming encryption: version 2 of the `SFEB` format.** `createEncryptStream` and
49
+ `createDecryptStream` are Node `Transform`s that encrypt and decrypt a file of any size while
50
+ holding at most one chunk (64 KiB by default) in memory. Each chunk is sealed with AES-256-GCM
51
+ under the STREAM construction, so reordered, repeated, dropped or appended chunks, and a file
52
+ cut at a chunk boundary, all fail with `DecryptionError`. The header carries the scrypt
53
+ parameters and chunk size, both bounded before any key is derived. A stream refuses a version 1
54
+ input over 64 MiB rather than buffering it whole.
55
+ - `ENCRYPTED_PREFIX`, the 4-byte `SFEB` prefix shared by every format version.
56
+
57
+ ### Changed
58
+
59
+ - `decryptWithPassphrase` and `createDecryptStream` read both versions; version 1 files are
60
+ unchanged and still readable. `isEncryptedBuffer` now also recognises version 2, and an
61
+ unknown version fails as "Unsupported SFEB format version N" instead of "not in recognized SFEB
62
+ encrypted format".
63
+ - **A header's scrypt settings are bounded together, not only one by one**, for both versions:
64
+ at most 256 MiB of memory (128·N·r) and four times the default's work (N·r·p). Settings that
65
+ passed each per-field limit could still demand about 12 s of blocking work or more than 1 GiB
66
+ per file. A key-derivation failure is now a `DecryptionError`, never a `RangeError`. Files
67
+ written with the defaults are unaffected.
68
+
13
69
  ## [0.12.0] — 2026-10-23
14
70
 
15
71
  ### Breaking
@@ -309,7 +365,8 @@ hourly capture path that dependants build on.
309
365
 
310
366
  Initial internal releases: API clients, org context, findings model and report rendering.
311
367
 
312
- [Unreleased]: https://github.com/cclabsnz/sf-core/compare/v0.4.0...HEAD
368
+ [Unreleased]: https://github.com/cclabsnz/sf-core/compare/v0.13.0...HEAD
369
+ [0.13.0]: https://github.com/cclabsnz/sf-core/releases/tag/v0.13.0
313
370
  [0.4.0]: https://github.com/cclabsnz/sf-core/releases/tag/v0.4.0
314
371
  [0.3.0]: https://github.com/cclabsnz/sf-core/releases/tag/v0.3.0
315
372
  [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
 
@@ -0,0 +1,53 @@
1
+ /** S3 credentials for an R2 bucket. */
2
+ export interface R2Credentials {
3
+ accessKeyId: string;
4
+ secretAccessKey: string;
5
+ }
6
+ export interface CloudflareAccount {
7
+ id: string;
8
+ name: string;
9
+ }
10
+ /** A freshly created API token. `value` is shown by Cloudflare once; `r2` is the S3 key pair derived from it. */
11
+ export interface CreatedToken {
12
+ id: string;
13
+ value: string;
14
+ r2: R2Credentials;
15
+ }
16
+ export type R2Jurisdiction = 'default' | 'eu' | 'fedramp' | 'us';
17
+ /** Keep objects under `prefix` for `retentionDays` days after they are written. */
18
+ export interface LockRule {
19
+ id: string;
20
+ prefix: string;
21
+ retentionDays: number;
22
+ }
23
+ export interface BucketTokenArgs {
24
+ name: string;
25
+ bucket: string;
26
+ jurisdiction: R2Jurisdiction;
27
+ access: 'read-write' | 'read';
28
+ }
29
+ /** The Cloudflare calls the guided R2 setup needs. Built from a user-pasted bootstrap token. */
30
+ export interface CloudflareClient {
31
+ /** Verify the (account-owned) token. Account tokens can only be verified under their account. */
32
+ verifyToken(accountId: string): Promise<{
33
+ tokenId: string;
34
+ status: string;
35
+ }>;
36
+ listAccounts(): Promise<CloudflareAccount[]>;
37
+ /** False when R2 has not been enabled on the account (Cloudflare error 10042). */
38
+ r2Enabled(accountId: string): Promise<boolean>;
39
+ getBucket(accountId: string, name: string, j: R2Jurisdiction): Promise<{
40
+ name: string;
41
+ } | null>;
42
+ /** Idempotent: a bucket that already exists and is owned by the account is not an error. */
43
+ createBucket(accountId: string, name: string, j: R2Jurisdiction): Promise<void>;
44
+ /** Merges with the bucket's existing rules (same id replaces); never drops the others. */
45
+ putLockRules(accountId: string, bucket: string, j: R2Jurisdiction, rules: LockRule[]): Promise<void>;
46
+ createBucketToken(accountId: string, args: BucketTokenArgs): Promise<CreatedToken>;
47
+ deleteToken(accountId: string, tokenId: string): Promise<void>;
48
+ }
49
+ /** S3 endpoint for an account: `https://<id>.r2.cloudflarestorage.com`, with the jurisdiction as a subdomain (`.eu.`). */
50
+ export declare function r2Endpoint(accountId: string, j: R2Jurisdiction): string;
51
+ /** R2 S3 credentials from an API token: the access key is the token id, the secret is the hex SHA-256 of its value. */
52
+ export declare function deriveR2Credentials(id: string, value: string): R2Credentials;
53
+ //# sourceMappingURL=CloudflareClient.d.ts.map
@@ -0,0 +1,10 @@
1
+ import { createHash } from 'node:crypto';
2
+ /** S3 endpoint for an account: `https://<id>.r2.cloudflarestorage.com`, with the jurisdiction as a subdomain (`.eu.`). */
3
+ export function r2Endpoint(accountId, j) {
4
+ return j === 'default' ? `https://${accountId}.r2.cloudflarestorage.com` : `https://${accountId}.${j}.r2.cloudflarestorage.com`;
5
+ }
6
+ /** R2 S3 credentials from an API token: the access key is the token id, the secret is the hex SHA-256 of its value. */
7
+ export function deriveR2Credentials(id, value) {
8
+ return { accessKeyId: id, secretAccessKey: createHash('sha256').update(value).digest('hex') };
9
+ }
10
+ //# sourceMappingURL=CloudflareClient.js.map
@@ -0,0 +1,6 @@
1
+ import type { CloudflareClient } from './CloudflareClient.js';
2
+ /** A Cloudflare client for the given API token. `opts.fetch` is for tests. */
3
+ export declare function createCloudflareClient(token: string, opts?: {
4
+ fetch?: typeof fetch;
5
+ }): CloudflareClient;
6
+ //# sourceMappingURL=FetchCloudflareClient.d.ts.map
@@ -0,0 +1,152 @@
1
+ import { deriveR2Credentials } from './CloudflareClient.js';
2
+ import { CloudflareApiError, R2NotEnabledError } from './errors.js';
3
+ const BASE_URL = 'https://api.cloudflare.com/client/v4';
4
+ const R2_NOT_ENABLED = 10042;
5
+ const BUCKET_NOT_FOUND = 10006;
6
+ const BUCKET_ALREADY_OWNED = 10004;
7
+ const READ_GROUP = 'Workers R2 Storage Bucket Item Read';
8
+ const WRITE_GROUP = 'Workers R2 Storage Bucket Item Write';
9
+ /** Only a permission the message actually names; nothing is guessed. */
10
+ const PERMISSION_NAME = /\b(Account API Tokens|Workers R2 Storage(?: Bucket Item| Metadata)?)\s+(Read|Write|Edit)\b/;
11
+ class FetchCloudflareClient {
12
+ token;
13
+ doFetch;
14
+ constructor(token, doFetch) {
15
+ this.token = token;
16
+ this.doFetch = doFetch;
17
+ }
18
+ scrub(text) {
19
+ return this.token ? text.split(this.token).join('[redacted]') : text;
20
+ }
21
+ /** One API call. Returns `result`; throws CloudflareApiError or R2NotEnabledError with the token scrubbed out. */
22
+ async call(method, path, opts = {}) {
23
+ const headers = { Authorization: `Bearer ${this.token}`, ...opts.headers };
24
+ if (opts.body !== undefined)
25
+ headers['Content-Type'] = 'application/json';
26
+ let res;
27
+ try {
28
+ res = await this.doFetch(`${BASE_URL}${path}`, {
29
+ method,
30
+ headers,
31
+ ...(opts.body !== undefined && { body: JSON.stringify(opts.body) }),
32
+ });
33
+ }
34
+ catch (err) {
35
+ // No `cause`: the original error can carry request details, including the Authorization header.
36
+ throw new CloudflareApiError(this.scrub(`Cloudflare request failed: ${err?.message ?? String(err)}`), 0);
37
+ }
38
+ let env = {};
39
+ try {
40
+ env = JSON.parse(await res.text());
41
+ }
42
+ catch {
43
+ // Not JSON (a proxy error page, say); fall through to the status check.
44
+ }
45
+ if (res.ok && env.success !== false)
46
+ return env.result;
47
+ const first = env.errors?.[0];
48
+ const code = typeof first?.code === 'number' ? first.code : undefined;
49
+ const message = this.scrub(first?.message ?? `HTTP ${res.status}`);
50
+ if (code === R2_NOT_ENABLED)
51
+ throw new R2NotEnabledError();
52
+ throw new CloudflareApiError(`Cloudflare API ${method} ${path} failed (HTTP ${res.status}${code === undefined ? '' : `, code ${code}`}): ${message}`, res.status, code, PERMISSION_NAME.exec(message)?.[0]);
53
+ }
54
+ static jurisdictionHeader(j) {
55
+ return j === 'default' ? {} : { 'cf-r2-jurisdiction': j };
56
+ }
57
+ static bucketPath(accountId, bucket) {
58
+ return `/accounts/${accountId}/r2/buckets/${encodeURIComponent(bucket)}`;
59
+ }
60
+ async verifyToken(accountId) {
61
+ const r = (await this.call('GET', `/accounts/${accountId}/tokens/verify`));
62
+ return { tokenId: r.id, status: r.status };
63
+ }
64
+ async listAccounts() {
65
+ const r = (await this.call('GET', '/accounts'));
66
+ return r.map((a) => ({ id: a.id, name: a.name }));
67
+ }
68
+ async r2Enabled(accountId) {
69
+ try {
70
+ await this.call('GET', `/accounts/${accountId}/r2/buckets`);
71
+ return true;
72
+ }
73
+ catch (err) {
74
+ if (err instanceof R2NotEnabledError)
75
+ return false;
76
+ throw err;
77
+ }
78
+ }
79
+ async getBucket(accountId, name, j) {
80
+ try {
81
+ const r = (await this.call('GET', FetchCloudflareClient.bucketPath(accountId, name), {
82
+ headers: FetchCloudflareClient.jurisdictionHeader(j),
83
+ }));
84
+ return { name: r.name };
85
+ }
86
+ catch (err) {
87
+ if (err instanceof CloudflareApiError && err.code === BUCKET_NOT_FOUND)
88
+ return null;
89
+ throw err;
90
+ }
91
+ }
92
+ async createBucket(accountId, name, j) {
93
+ try {
94
+ await this.call('POST', `/accounts/${accountId}/r2/buckets`, {
95
+ body: { name },
96
+ headers: FetchCloudflareClient.jurisdictionHeader(j),
97
+ });
98
+ }
99
+ catch (err) {
100
+ if (err instanceof CloudflareApiError && err.status === 409 && err.code === BUCKET_ALREADY_OWNED)
101
+ return;
102
+ throw err;
103
+ }
104
+ }
105
+ async putLockRules(accountId, bucket, j, rules) {
106
+ const path = `${FetchCloudflareClient.bucketPath(accountId, bucket)}/lock`;
107
+ const headers = FetchCloudflareClient.jurisdictionHeader(j);
108
+ const current = (await this.call('GET', path, { headers }));
109
+ const incoming = new Map(rules.map((r) => [
110
+ r.id,
111
+ { id: r.id, enabled: true, prefix: r.prefix, condition: { type: 'Age', maxAgeSeconds: r.retentionDays * 86400 } },
112
+ ]));
113
+ // PUT replaces the whole set. Existing rules go back as returned; an incoming rule with the same id takes its place.
114
+ const merged = (current?.rules ?? []).map((e) => (e.id !== undefined && incoming.has(e.id) ? incoming.get(e.id) : e));
115
+ const existingIds = new Set((current?.rules ?? []).map((e) => e.id));
116
+ for (const [id, rule] of incoming)
117
+ if (!existingIds.has(id))
118
+ merged.push(rule);
119
+ await this.call('PUT', path, { body: { rules: merged }, headers });
120
+ }
121
+ async createBucketToken(accountId, args) {
122
+ const groups = (await this.call('GET', `/accounts/${accountId}/tokens/permission_groups`));
123
+ const idOf = (name) => {
124
+ const g = groups.find((x) => x.name === name);
125
+ if (!g)
126
+ throw new CloudflareApiError(`Cloudflare has no permission group named "${name}".`, 0);
127
+ return g.id;
128
+ };
129
+ const ids = args.access === 'read-write' ? [idOf(WRITE_GROUP), idOf(READ_GROUP)] : [idOf(READ_GROUP)];
130
+ const r = (await this.call('POST', `/accounts/${accountId}/tokens`, {
131
+ body: {
132
+ name: args.name,
133
+ policies: [
134
+ {
135
+ effect: 'allow',
136
+ resources: { [`com.cloudflare.edge.r2.bucket.${accountId}_${args.jurisdiction}_${args.bucket}`]: '*' },
137
+ permission_groups: ids.map((id) => ({ id })),
138
+ },
139
+ ],
140
+ },
141
+ }));
142
+ return { id: r.id, value: r.value, r2: deriveR2Credentials(r.id, r.value) };
143
+ }
144
+ async deleteToken(accountId, tokenId) {
145
+ await this.call('DELETE', `/accounts/${accountId}/tokens/${encodeURIComponent(tokenId)}`);
146
+ }
147
+ }
148
+ /** A Cloudflare client for the given API token. `opts.fetch` is for tests. */
149
+ export function createCloudflareClient(token, opts = {}) {
150
+ return new FetchCloudflareClient(token, opts.fetch ?? fetch);
151
+ }
152
+ //# sourceMappingURL=FetchCloudflareClient.js.map
@@ -0,0 +1,16 @@
1
+ /**
2
+ * A Cloudflare API call failed. `status` is the HTTP status (0 when the request never got a response),
3
+ * `code` the first Cloudflare error code. `missingPermission` is set only when Cloudflare's own message
4
+ * names a permission. The message never contains the API token.
5
+ */
6
+ export declare class CloudflareApiError extends Error {
7
+ readonly status: number;
8
+ readonly code?: number;
9
+ readonly missingPermission?: string;
10
+ constructor(message: string, status: number, code?: number, missingPermission?: string);
11
+ }
12
+ /** R2 is not enabled on the account (Cloudflare error 10042). Enable it in the dashboard first. */
13
+ export declare class R2NotEnabledError extends Error {
14
+ constructor(message?: string);
15
+ }
16
+ //# sourceMappingURL=errors.d.ts.map
@@ -0,0 +1,25 @@
1
+ /**
2
+ * A Cloudflare API call failed. `status` is the HTTP status (0 when the request never got a response),
3
+ * `code` the first Cloudflare error code. `missingPermission` is set only when Cloudflare's own message
4
+ * names a permission. The message never contains the API token.
5
+ */
6
+ export class CloudflareApiError extends Error {
7
+ status;
8
+ code;
9
+ missingPermission;
10
+ constructor(message, status, code, missingPermission) {
11
+ super(message);
12
+ this.name = 'CloudflareApiError';
13
+ this.status = status;
14
+ this.code = code;
15
+ this.missingPermission = missingPermission;
16
+ }
17
+ }
18
+ /** R2 is not enabled on the account (Cloudflare error 10042). Enable it in the dashboard first. */
19
+ export class R2NotEnabledError extends Error {
20
+ constructor(message = 'R2 is not enabled on this Cloudflare account. Enable it in the Cloudflare dashboard.') {
21
+ super(message);
22
+ this.name = 'R2NotEnabledError';
23
+ }
24
+ }
25
+ //# sourceMappingURL=errors.js.map
@@ -0,0 +1,5 @@
1
+ export type { BucketTokenArgs, CloudflareAccount, CloudflareClient, CreatedToken, LockRule, R2Credentials, R2Jurisdiction, } from './CloudflareClient.js';
2
+ export { deriveR2Credentials, r2Endpoint } from './CloudflareClient.js';
3
+ export { CloudflareApiError, R2NotEnabledError } from './errors.js';
4
+ export { createCloudflareClient } from './FetchCloudflareClient.js';
5
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,4 @@
1
+ export { deriveR2Credentials, r2Endpoint } from './CloudflareClient.js';
2
+ export { CloudflareApiError, R2NotEnabledError } from './errors.js';
3
+ export { createCloudflareClient } from './FetchCloudflareClient.js';
4
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,43 @@
1
+ import type { BucketTokenArgs, CloudflareAccount, CloudflareClient, CreatedToken, LockRule, R2Jurisdiction } from '../CloudflareClient.js';
2
+ export interface MemoryCloudflareOptions {
3
+ accounts?: CloudflareAccount[];
4
+ /** An array is consumed one value per r2Enabled call; the last value sticks. */
5
+ r2On?: boolean | boolean[];
6
+ /** Make the first N createBucketToken calls fail. */
7
+ failCreateTokenTimes?: number;
8
+ }
9
+ interface StoredRule {
10
+ id: string;
11
+ prefix: string;
12
+ retentionDays: number;
13
+ }
14
+ /** In-memory CloudflareClient for tests. `calls` has one readable entry per method call. */
15
+ export declare class MemoryCloudflareClient implements CloudflareClient {
16
+ readonly calls: string[];
17
+ accounts: CloudflareAccount[];
18
+ r2On: boolean | boolean[];
19
+ failCreateTokenTimes?: number;
20
+ readonly tokens: Map<string, CreatedToken>;
21
+ private readonly buckets;
22
+ private readonly rules;
23
+ private r2Calls;
24
+ private tokenSeq;
25
+ constructor(opts?: MemoryCloudflareOptions);
26
+ /** The lock rules held for a bucket. */
27
+ lockRules(bucket: string, j: R2Jurisdiction): readonly StoredRule[];
28
+ verifyToken(accountId: string): Promise<{
29
+ tokenId: string;
30
+ status: string;
31
+ }>;
32
+ listAccounts(): Promise<CloudflareAccount[]>;
33
+ r2Enabled(accountId: string): Promise<boolean>;
34
+ getBucket(_accountId: string, name: string, j: R2Jurisdiction): Promise<{
35
+ name: string;
36
+ } | null>;
37
+ createBucket(_accountId: string, name: string, j: R2Jurisdiction): Promise<void>;
38
+ putLockRules(_accountId: string, bucket: string, j: R2Jurisdiction, rules: LockRule[]): Promise<void>;
39
+ createBucketToken(_accountId: string, args: BucketTokenArgs): Promise<CreatedToken>;
40
+ deleteToken(_accountId: string, tokenId: string): Promise<void>;
41
+ }
42
+ export {};
43
+ //# sourceMappingURL=MemoryCloudflareClient.d.ts.map
@@ -0,0 +1,77 @@
1
+ import { deriveR2Credentials } from '../CloudflareClient.js';
2
+ import { CloudflareApiError } from '../errors.js';
3
+ /** In-memory CloudflareClient for tests. `calls` has one readable entry per method call. */
4
+ export class MemoryCloudflareClient {
5
+ calls = [];
6
+ accounts;
7
+ r2On;
8
+ failCreateTokenTimes;
9
+ tokens = new Map();
10
+ buckets = new Set();
11
+ rules = new Map();
12
+ r2Calls = 0;
13
+ tokenSeq = 0;
14
+ constructor(opts = {}) {
15
+ this.accounts = opts.accounts ?? [{ id: '0123456789abcdef0123456789abcdef', name: 'Test account' }];
16
+ this.r2On = opts.r2On ?? true;
17
+ this.failCreateTokenTimes = opts.failCreateTokenTimes;
18
+ }
19
+ /** The lock rules held for a bucket. */
20
+ lockRules(bucket, j) {
21
+ return this.rules.get(`${j}:${bucket}`) ?? [];
22
+ }
23
+ async verifyToken(accountId) {
24
+ this.calls.push(`verifyToken:${accountId}`);
25
+ return { tokenId: 'memory-bootstrap-token', status: 'active' };
26
+ }
27
+ async listAccounts() {
28
+ this.calls.push('listAccounts');
29
+ return this.accounts.map((a) => ({ ...a }));
30
+ }
31
+ async r2Enabled(accountId) {
32
+ this.calls.push(`r2Enabled:${accountId}`);
33
+ if (!Array.isArray(this.r2On))
34
+ return this.r2On;
35
+ const i = Math.min(this.r2Calls++, this.r2On.length - 1);
36
+ return this.r2On[i] ?? true;
37
+ }
38
+ async getBucket(_accountId, name, j) {
39
+ this.calls.push(`getBucket:${name}:${j}`);
40
+ return this.buckets.has(`${j}:${name}`) ? { name } : null;
41
+ }
42
+ async createBucket(_accountId, name, j) {
43
+ this.calls.push(`createBucket:${name}:${j}`);
44
+ this.buckets.add(`${j}:${name}`);
45
+ }
46
+ async putLockRules(_accountId, bucket, j, rules) {
47
+ this.calls.push(`putLockRules:${bucket}:${j}`);
48
+ const key = `${j}:${bucket}`;
49
+ const merged = [...(this.rules.get(key) ?? [])];
50
+ for (const r of rules) {
51
+ const at = merged.findIndex((m) => m.id === r.id);
52
+ if (at === -1)
53
+ merged.push({ ...r });
54
+ else
55
+ merged[at] = { ...r };
56
+ }
57
+ this.rules.set(key, merged);
58
+ }
59
+ async createBucketToken(_accountId, args) {
60
+ this.calls.push(`createBucketToken:${args.bucket}:${args.jurisdiction}:${args.access}`);
61
+ if (this.failCreateTokenTimes && this.failCreateTokenTimes > 0) {
62
+ this.failCreateTokenTimes -= 1;
63
+ throw new CloudflareApiError('Simulated token creation failure', 500);
64
+ }
65
+ this.tokenSeq += 1;
66
+ const id = `memory-token-id-${this.tokenSeq}`;
67
+ const value = `memory-token-value-${this.tokenSeq}`;
68
+ const token = { id, value, r2: deriveR2Credentials(id, value) };
69
+ this.tokens.set(id, token);
70
+ return token;
71
+ }
72
+ async deleteToken(_accountId, tokenId) {
73
+ this.calls.push(`deleteToken:${tokenId}`);
74
+ this.tokens.delete(tokenId);
75
+ }
76
+ }
77
+ //# sourceMappingURL=MemoryCloudflareClient.js.map
@@ -0,0 +1,2 @@
1
+ export * from './cloudflare/index.js';
2
+ //# sourceMappingURL=cloudflare.d.ts.map
@@ -0,0 +1,4 @@
1
+ // The ./cloudflare entry point: a small Cloudflare API client for guided R2 setup (bucket, lock rules,
2
+ // bucket-scoped token). Talks only to the Cloudflare API, with a token the caller passes in.
3
+ export * from './cloudflare/index.js';
4
+ //# sourceMappingURL=cloudflare.js.map
@@ -0,0 +1,3 @@
1
+ export { MemoryCloudflareClient } from './cloudflare/testing/MemoryCloudflareClient.js';
2
+ export type { MemoryCloudflareOptions } from './cloudflare/testing/MemoryCloudflareClient.js';
3
+ //# sourceMappingURL=cloudflareTesting.d.ts.map
@@ -0,0 +1,3 @@
1
+ // The ./cloudflare/testing entry point: an in-memory CloudflareClient for tests.
2
+ export { MemoryCloudflareClient } from './cloudflare/testing/MemoryCloudflareClient.js';
3
+ //# sourceMappingURL=cloudflareTesting.js.map
@@ -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