@cclabsnz/sf-core 0.13.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 CHANGED
@@ -10,6 +10,26 @@ 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
+
13
33
  ## [0.13.0] — 2026-11-27
14
34
 
15
35
  ### Added
@@ -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
@@ -5,8 +5,16 @@ export interface S3ObjectStoreOptions {
5
5
  client?: {
6
6
  send(cmd: unknown): Promise<unknown>;
7
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
+ };
8
13
  }
9
14
  /** 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>;
15
+ export declare function s3ClientConfig(ep: S3Endpoint, credentials?: {
16
+ accessKeyId: string;
17
+ secretAccessKey: string;
18
+ }): Record<string, unknown>;
11
19
  export declare function createS3ObjectStore(bucket: string, ep: S3Endpoint, opts?: S3ObjectStoreOptions): Promise<ObjectStore>;
12
20
  //# sourceMappingURL=S3ObjectStoreImpl.d.ts.map
@@ -1,7 +1,8 @@
1
1
  import { BucketMissingError, StorageAccessDeniedError } from './errors.js';
2
2
  /** S3Client settings. Path-style and WHEN_REQUIRED checksums keep R2 and other S3-compatible services happy. */
3
- export function s3ClientConfig(ep) {
3
+ export function s3ClientConfig(ep, credentials) {
4
4
  return {
5
+ ...(credentials && { credentials: { accessKeyId: credentials.accessKeyId, secretAccessKey: credentials.secretAccessKey } }),
5
6
  region: ep.region,
6
7
  endpoint: ep.endpoint,
7
8
  forcePathStyle: ep.custom,
@@ -13,13 +14,16 @@ const SECRET_ENV = ['AWS_SECRET_ACCESS_KEY', 'AWS_SESSION_TOKEN', 'AWS_ACCESS_KE
13
14
  /**
14
15
  * Replace any credential value found in the environment with [redacted].
15
16
  *
16
- * Scope: only the values of AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY and AWS_SESSION_TOKEN as set in
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
17
18
  * process.env (values shorter than 4 characters are left alone). Credentials the SDK resolves from
18
19
  * other sources (shared ini files, SSO, process, web-identity or instance-metadata providers) are not
19
20
  * known here and are not redacted; neither is anything else in the message.
20
21
  */
21
- function redact(text) {
22
+ function redact(text, extra = []) {
22
23
  let out = text;
24
+ for (const v of extra)
25
+ if (v.length >= 4)
26
+ out = out.split(v).join('[redacted]');
23
27
  for (const name of SECRET_ENV) {
24
28
  const v = process.env[name];
25
29
  if (v && v.length >= 4)
@@ -36,9 +40,13 @@ function isNotFound(e) {
36
40
  function isPreconditionFailed(e) {
37
41
  return e.name === 'PreconditionFailed' || statusOf(e) === 412;
38
42
  }
39
- function toStorageError(err, bucket) {
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 = []) {
40
48
  const e = (err ?? {});
41
- const message = redact(e.message ?? String(err));
49
+ const message = redact(e.message ?? String(err), secrets);
42
50
  if (e.name === 'NoSuchBucket')
43
51
  return new BucketMissingError(bucket);
44
52
  if (e.name === 'AccessDenied' || statusOf(e) === 403) {
@@ -65,7 +73,8 @@ export async function createS3ObjectStore(bucket, ep, opts = {}) {
65
73
  }
66
74
  throw err;
67
75
  }
68
- const client = opts.client ?? new sdk.S3Client(s3ClientConfig(ep));
76
+ const client = opts.client ?? new sdk.S3Client(s3ClientConfig(ep, opts.credentials));
77
+ const secrets = opts.credentials ? [opts.credentials.accessKeyId, opts.credentials.secretAccessKey] : [];
69
78
  const send = (cmd) => client.send(cmd);
70
79
  return {
71
80
  async get(key) {
@@ -76,7 +85,7 @@ export async function createS3ObjectStore(bucket, ep, opts = {}) {
76
85
  catch (err) {
77
86
  if (isNotFound(err) && err.name !== 'NoSuchBucket')
78
87
  return null;
79
- throw toStorageError(err, bucket);
88
+ throw toStorageError(err, bucket, secrets);
80
89
  }
81
90
  },
82
91
  async put(key, bytes, contentType) {
@@ -84,7 +93,7 @@ export async function createS3ObjectStore(bucket, ep, opts = {}) {
84
93
  await send(new sdk.PutObjectCommand({ Bucket: bucket, Key: key, Body: bytes, ContentType: contentType }));
85
94
  }
86
95
  catch (err) {
87
- throw toStorageError(err, bucket);
96
+ throw toStorageError(err, bucket, secrets);
88
97
  }
89
98
  },
90
99
  async putIfAbsent(key, bytes, contentType) {
@@ -93,9 +102,10 @@ export async function createS3ObjectStore(bucket, ep, opts = {}) {
93
102
  return true;
94
103
  }
95
104
  catch (err) {
96
- if (isPreconditionFailed(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))
97
107
  return false;
98
- throw toStorageError(err, bucket);
108
+ throw toStorageError(err, bucket, secrets);
99
109
  }
100
110
  },
101
111
  async list({ prefix, delimiter, maxKeys, token }) {
@@ -114,7 +124,7 @@ export async function createS3ObjectStore(bucket, ep, opts = {}) {
114
124
  };
115
125
  }
116
126
  catch (err) {
117
- throw toStorageError(err, bucket);
127
+ throw toStorageError(err, bucket, secrets);
118
128
  }
119
129
  },
120
130
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cclabsnz/sf-core",
3
- "version": "0.13.0",
3
+ "version": "0.14.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
+ "./cloudflare": {
19
+ "types": "./lib/cloudflare.d.ts",
20
+ "default": "./lib/cloudflare.js"
21
+ },
22
+ "./cloudflare/testing": {
23
+ "types": "./lib/cloudflareTesting.d.ts",
24
+ "default": "./lib/cloudflareTesting.js"
25
+ },
18
26
  "./storage": {
19
27
  "types": "./lib/storage.d.ts",
20
28
  "default": "./lib/storage.js"