@blamejs/core 0.6.35 → 0.6.37
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 +2 -0
- package/README.md +1 -1
- package/lib/db-query.js +71 -40
- package/lib/object-store/azure-blob-bucket-ops.js +291 -0
- package/lib/object-store/gcs-bucket-ops.js +327 -0
- package/lib/object-store/index.js +65 -14
- package/package.json +1 -1
- package/sbom.cyclonedx.json +6 -6
package/CHANGELOG.md
CHANGED
|
@@ -8,6 +8,8 @@ upgrading across more than a few patches at a time.
|
|
|
8
8
|
|
|
9
9
|
## v0.6.x
|
|
10
10
|
|
|
11
|
+
- **0.6.37** (2026-05-02) — Azure + GCS bucket-ops parity. **`b.objectStore.bucketOps`** is now a protocol-dispatching factory: pass `{ protocol: 'sigv4' | 'azure-blob' | 'gcs', ... }` to get a service-scoped client for the matching cloud. Previously SigV4 only. **`lib/object-store/azure-blob-bucket-ops.js`** (new) — Azure Storage container lifecycle via Shared Key auth (reuses `azure-blob.js`'s `signRequest`): `create(name, {publicAccess?})` (PUT `/{container}?restype=container`), `delete(name)` (DELETE), `list({prefix?, maxResults?})` (GET `/?comp=list` with XML response parsed into `[{ name, lastModified, etag, leaseStatus, leaseState, publicAccess }]`), `setCorsRules(rules)` (PUT `/?restype=service&comp=properties` — Azure CORS is account-level, not per-container). `setLifecycle` is intentionally not implemented because Azure Storage lifecycle management policies live on Azure Resource Manager (`management.azure.com`) and require Azure AD bearer-token auth — a different scheme entirely; calling it throws `NOT_SUPPORTED` with operator guidance pointing at Terraform / Bicep / az CLI. **`lib/object-store/gcs-bucket-ops.js`** (new) — GCS bucket lifecycle via service-account JWT exchanged for an OAuth2 access token (reuses `gcs.js`'s `_signJwt`); admin-scoped (`devstorage.full_control`) so list-buckets + create + delete + lifecycle + CORS all succeed: `create(name, {location?, storageClass?, iamConfiguration?})` (POST `/storage/v1/b?project=`), `delete(name)`, `list({prefix?, maxResults?, pageToken?})`, `setLifecycle(name, rules)` (PATCH bucket with `lifecycle: { rule: [{ action, condition }] }`; rules support `Delete` / `SetStorageClass` / `AbortIncompleteMultipartUpload` actions), `setCorsRules(name, rules)` (PATCH bucket with `cors: [{ origin, method, responseHeader, maxAgeSeconds }]`). **Bucket-name validation** matches each cloud's spec: Azure containers (3-63 lowercase alphanumeric + hyphens, no consecutive hyphens, must start/end with alphanumeric); GCS buckets (3-63 lowercase + digits + hyphens + underscores + dots, no consecutive dots, no `goog` prefix). Bad names are rejected at the call site before the request leaves the process. **404 / 409 semantic mapping** — both modules treat 404 on delete as "already gone" (returns false), 409 on create as `BUCKET_ALREADY_OWNED`; everything else surfaces with the original HTTP status preserved on the thrown ObjectStoreError. **Tests**: 47 layer-0 mock-based assertions for Azure (surface, factory validation, container-name validation, create/delete/list wire shape including XML response parsing, CORS validation + wire shape, setLifecycle NOT_SUPPORTED guidance) + 50 layer-0 mock-based assertions for GCS (surface, factory validation including missing service-account / project, bucket-name validation, create/delete/list wire shape including JWT bearer auth, lifecycle validation + JSON body shape, CORS shape). HTTP mock servers record every request shape so signing, URL params, headers, and body-format are all asserted. **Wiki page** `examples/wiki/seeders/prod/pages/object-store.js` updated end-to-end with all three clouds' bucket-ops examples and the Azure-vs-Resource-Manager lifecycle gap documented. Smoke 6951 / wiki e2e 178 / per-primitive integration 16 files / wiki integration 32 / shellcheck clean / eslint clean.
|
|
12
|
+
- **0.6.36** (2026-05-02) — `b.db.from("schema.table")` cross-schema chain. **`b.db.from("audit.events")`** — the chainable Query builder now accepts a two-part `schema.table` identifier. Both halves validated separately as SQL identifiers (rejects three-part names, empty parts, identifiers with embedded quotes / SQL keywords); both halves wrapped in `"..."` when interpolated so the generated SQL is `SELECT * FROM "audit"."events" WHERE ...` etc. The bare `b.db.from("users")` form still works unchanged. Sealed-field registry lookup tries the qualified name (`audit.users`) first when schema is set, falls back to the bare table — operators registering `cryptoField.registerTable("audit.users", { sealedFields: ... })` get per-schema sealed columns; existing table-name-only registrations keep working. Use cases: cross-schema joins on Postgres external-db (`public.users` vs `audit.events` from one app), SQLite `ATTACH DATABASE` (per-classification audit / archive databases mounted on the side and queried through the same Query API). **Tests**: 14 layer-0 SQL-shape assertions against a fake DB (verify schema-qualified SELECT / INSERT / UPDATE / DELETE / count / sub-select-on-rowid all emit `"schema"."table"`; reject three-part / empty / invalid identifiers; bare table name preserved unqualified) + 7 layer-2 end-to-end assertions against a real `ATTACH DATABASE` schema (insert / select / count / update / delete round-trip via `b.db.from("audit.events")`). Smoke 6854 / wiki e2e 178 / per-primitive integration 16 files / wiki integration 32 / shellcheck clean / eslint clean.
|
|
11
13
|
- **0.6.35** (2026-05-02) — `cluster-provider-db` MySQL dialect. **`b.cluster.create({ provider: clusterProviderDb.create({ dialect: "mysql", ... }) })`** — operators on MySQL no longer have to supply their own provider; the framework's default DB-row leader-election provider now speaks all three of postgres / sqlite / mysql. The MySQL acquireLease shape uses `INSERT INTO _blamejs_leader (...) VALUES (...) ON DUPLICATE KEY UPDATE col = IF(expiresAt < ?, VALUES(col), col), ..., expiresAt = IF(expiresAt < ?, VALUES(expiresAt), expiresAt)` so a still-valid lease is preserved untouched and an expired one is overwritten — atomic at the row level — followed by a `SELECT FROM _blamejs_leader WHERE scope='leader'` to read who holds (MySQL has no `RETURNING`). The expiresAt assignment runs LAST so per-column IF() predicates evaluate against pre-update row state. Renew uses `UPDATE ... SET expiresAt=?, endpoint=? WHERE scope='leader' AND nodeId=? AND leaseId=?` followed by a check-SELECT to surface takeover races as `LEASE_LOST`. Schema generation: `BIGINT` int columns (was `INTEGER` for SQLite), `VARCHAR(64)` for primary-key text columns and `VARCHAR(255)` for body text (MySQL needs explicit lengths on PRIMARY KEY columns), `CHECK (scope = 'leader' / 'state')` constraint dropped on MySQL because some MariaDB / MySQL 5.x versions parse-then-silently-drop CHECK clauses (would surface as version drift); the constant-scope invariant is enforced by application code anyway. Placeholder style auto-flips to `?` for MySQL (Postgres / SQLite continue to use `$1..$N`). **Tests**: 16 layer-1 assertions exercising the MySQL dialect path against a fake mysql-shaped driver (`_makeFakeMysqlDriver` in `test/helpers/drivers.js`) that emulates `INSERT ... ON DUPLICATE KEY UPDATE` with the per-column `IF()` semantics; covers acquire-empty, blocked-while-held, renew-no-fencing-bump, takeover-with-fencing-bump, old-leader-renew-throws-LEASE_LOST, currentLeader, releaseLease — plus a SQL-shape audit (validates VARCHAR primary keys, ON DUPLICATE KEY syntax, ?-placeholders, IF() gating). 14 live integration assertions against the docker MySQL 8.4 container via a docker-exec-based external-db driver shim (no npm mysql client; the framework already requires operator-supplied driver wiring, the shim demonstrates one path) covering ensureSchema, acquireLease, blocked-second-node, currentLeader, renewLease, release, takeover-after-expiry, fencingToken bump, old-leader LEASE_LOST. Smoke 6833 / wiki e2e 178 / per-primitive integration 16 files / wiki integration 32 / shellcheck clean / eslint clean.
|
|
12
14
|
- **0.6.34** (2026-05-02) — distributed pub/sub primitive. **`b.pubsub`** — single API for cross-node fan-out across the framework, with three backends. `local` dispatches in-process to registered handlers (zero coordination overhead for single-node deploys); `cluster` polls a shared `_blamejs_pubsub_messages` table at `pollIntervalMs` (default 100ms) and dispatches new rows past `lastSeenId` from other nodes (publishedBy=self filter prevents loopback); `redis` opens a SUBSCRIBE-mode connection on `lib/redis-client.js` (now with new push-message demultiplexing — server-pushed `["message", channel, payload]` and `["pmessage", pattern, channel, payload]` arrays route through `setOnPushMessage` instead of consuming a pending request slot, while SUBSCRIBE / UNSUBSCRIBE acks still flow through the normal command pipeline). Per-instance nonce stamped on outgoing redis payloads so the SUBSCRIBE socket recognizes its own publishes and skips the loopback (without it every same-instance publish would fire local handlers twice). Operator API: `ps.subscribe(channel, handler) → token`, `ps.subscribePattern(pattern, handler) → token` (glob-style on local + cluster, native PSUBSCRIBE on redis), `ps.unsubscribe(token)`, `await ps.publish(channel, payload) → { local, remote }`, `await ps.close()`. `topicPrefix` opt scopes channel names so independent pubsub instances sharing a backend (cache invalidation + websocket channels + custom) don't collide. Handler errors are caught + logged via the framework's boot logger; they never abort dispatch to other handlers on the same channel. **`lib/websocket-channels.js`** — replaces the inline cluster-poll-and-fan-out logic with `b.pubsub` consumption. The hub now owns one pubsub instance per primitive; cross-node delivery is `pubsub.subscribe` per channel the hub joins, with the hub's `_localDispatch` as the handler. Per-channel pubsub subscription is refcounted by local conn count (subscribe on first conn, unsubscribe on last). The `_blamejs_ws_messages` table is renamed to `_blamejs_pubsub_messages` (column `channel` → `topic`) reflecting the generalization; pre-v1, no compat shim — operators upgrading wipe the previous table (which carried only ephemeral fan-out rows with default 60s retention). **`b.cache.create({ invalidationPubsub })`** — passing a `b.pubsub.create()` instance auto-publishes on every successful `del` / `clear` / `invalidateTag`, and subscribes for the same events so other cache instances on other nodes (or processes sharing the pubsub backend) react locally — primarily useful for the memory backend so stale per-node entries don't survive a global tag wipe. Re-entrancy guard prevents inbound invalidation events from re-publishing (no fan-out loops). Tests: 29 layer-0 assertions covering local + cluster behavior, topicPrefix isolation, pattern subscribe, handler error isolation, post-close error path, end-to-end cache invalidationPubsub fan-out via local pubsub. 10 live integration assertions against the docker redis container covering single-instance round-trip, PSUBSCRIBE pattern, cross-instance fan-out, and cache invalidation through redis PUB/SUB. Smoke 6817 / wiki e2e 178 / per-primitive integration 15 files / wiki integration 32 / shellcheck clean / eslint clean.
|
|
13
15
|
- **0.6.33** (2026-05-02) — log-stream sinks parity sweep. **`b.logStream` syslog sink (RFC 5424)** — first-class `protocol: "syslog"` for `b.logStream.init({ sinks: { ... } })`; new module `lib/log-stream-syslog.js`. URL-driven transport selection: `udp://host:514` / `tcp://host:514` / `tls://host:6514`. UDP is best-effort one-datagram-per-record; TCP / TLS use RFC 6587 octet-counting framing (`<length> <message>`) so collectors that prefer it over the older non-transparent newline framing parse cleanly. TLS is TLS 1.3 minimum; operators with private CAs pass `ca` (PEM string or array) for trust pinning, `servername` for SNI override (auto-suppressed on IP literals per the v0.6.28 redis-client convention). Outgoing records are formatted with PRI = `(facility << 3) | severity`, default facility `local0` (16), severity mapped from the framework's level field (debug=7 / info=6 / warn=4 / error=3); operators override via `facility`, `appName` (default `blamejs`), `procId` (default `process.pid`), `hostname` (default `os.hostname()`), `structuredData` (default `-`). Meta is JSON-encoded into the MSG body so the structured payload survives the wire as a single token. TCP / TLS reconnect with exponential backoff (default 250ms→30s); records buffer during the down window with `bufferLimit`-bounded oldest-drop semantics, replay on reconnect. `close()` waits up to 3s for an in-flight (re)connect to drain the buffer before tearing down — without this the slower TLS handshake raced fire-and-forget shutdown emits and silently dropped records. Operator-supplied `onDrop({reason, batch, error})` surfaces every drop class (`overflow` / `udp-send-error` / `write-error` / `sink-closed`). Removed `syslog` from `DEFERRED_PROTOCOLS`. **`b.logStream` cloudwatch sink: `autoCreate`** — pass `{ autoCreate: true }` to have the framework issue `CreateLogGroup` + `CreateLogStream` on first emit so operators provisioning collectors via env vars / runbooks don't need a separate aws-cli step. Idempotent: AWS's `ResourceAlreadyExistsException` is treated as success on both calls. Hard failures (5xx, AccessDenied, etc.) drop the batch with `onDrop` reason `autocreate-failed`. Default remains `autoCreate: false` so the AWS posture (operator pre-creates via aws / CDK / Terraform) stays the recommended path; `autoCreate` exists for ephemeral / dynamic-stream deployments where pre-provisioning is impractical. **Test suite**: 19 new framework-level cloudwatch assertions cover autoCreate fires both Create calls in order before PutLogEvents, ResourceAlreadyExists doesn't abort the post-create PutLogEvents, hard 5xx during CreateLogGroup drops the batch via `onDrop`, autoCreate=false skips Create calls entirely. Live syslog integration covers UDP / TCP wire delivery against the docker syslog-ng container (`/var/log/blamejs-test.log`) plus an in-process `tls.createServer` receiver that asserts the on-the-wire RFC 6587 octet-counting framing + RFC 5424 PRI / timestamp / structured-data slot the framework emits over TLS. **Test infrastructure fix**: `docker/init/generate-certs.sh` was overwriting an existing CA when re-run with `.complete` removed, invalidating every previously-issued leaf cert; now reuses an existing `(ca.crt, ca.key)` pair across `.complete`-only resets and only generates a fresh CA when neither file is present. Smoke 6790 / wiki e2e 178 / per-primitive integration 14 files (log-stream up from 16→18 checks, cloudwatch suite up from 39→58 assertions) / wiki integration 32 / shellcheck clean / eslint clean.
|
package/README.md
CHANGED
|
@@ -41,7 +41,7 @@ var b = require("@blamejs/core");
|
|
|
41
41
|
|
|
42
42
|
The framework bundles the surface a typical Node app reaches for. Every primitive listed is callable today; nothing is a stub.
|
|
43
43
|
|
|
44
|
-
- **Data layer** — SQLite with sealed-by-default columns (`b.db`), migrations, seeders, atomic-file writes; bring-your-own external Postgres / MySQL / etc. with pool tuning + role-aware connect + read-replica routing (`b.externalDb`); declarative role-narrowed views and Postgres row-level-security migrations (`b.db.declareView`, `b.db.declareRowPolicy`); S3 / R2 / B2 / GCS / Azure object store with multipart upload + SSE + bucket
|
|
44
|
+
- **Data layer** — SQLite with sealed-by-default columns (`b.db`), migrations, seeders, atomic-file writes; bring-your-own external Postgres / MySQL / etc. with pool tuning + role-aware connect + read-replica routing (`b.externalDb`); declarative role-narrowed views and Postgres row-level-security migrations (`b.db.declareView`, `b.db.declareRowPolicy`); S3 / R2 / B2 / GCS / Azure object store with multipart upload + SSE + bucket-ops (create / delete / list / lifecycle / CORS) across all three clouds (`b.storage`, `b.objectStore`); durable queue with priority + cron + flows on the local SQLite backend OR a shared Redis backend for multi-replica deploys (`b.queue`, `b.jobs`); cluster-shared cache (`b.cache`).
|
|
45
45
|
- **Identity & access** — passwords (Argon2id) + policy primitive (NIST 800-63B / PCI-DSS 4.0 / HIPAA-AAL2 profiles, HaveIBeenPwned k-anonymity breach check, length / context / dictionary / complexity rules, rotation + history) (`b.auth.password`); passkeys (WebAuthn), TOTP, JWT (PQ-default), OAuth, sessions with optional IP / UA fingerprint drift detection + anomaly scoring, brute-force lockout (`b.auth.*`, `b.session`); RBAC + optional per-role DB binding + role-spec `requireMfa` + per-route MFA freshness window + ABAC predicate registry (`b.permissions`); API keys with rotation (`b.apiKey`); break-glass column gates with second-factor + audit (`b.breakGlass`); two-person-rule approval workflow with m-of-n quorum + cooling-off lock + approver-role gate + cancellation (`b.dualControl`).
|
|
46
46
|
- **Crypto** — envelope-versioned PQC at rest (ML-KEM-1024 + P-384 hybrid, XChaCha20-Poly1305, SHAKE256), vault sealing, field-level crypto + cryptographic erasure (`b.cryptoField.eraseRow`), signed webhooks (SLH-DSA-SHAKE-256f), ECIES API encryption (`b.crypto`, `b.vault`, `b.webhook`); pure-JS mTLS CA that issues clientAuth / serverAuth / dual-EKU certs with SAN entries and auto-detects the highest-PQC signature algorithm the vendored x509 library accepts (today: ECDSA-P384-SHA384 bridge; self-upgrades to SLH-DSA / ML-DSA when the X.509 ecosystem catches up), PQC TLS gates inbound + outbound (`b.mtlsCa`, `b.pqcGate`, `b.pqcAgent`).
|
|
47
47
|
- **HTTP** — router with schema-validated routes + OpenAPI publication; full middleware stack (CSRF, CORS, rate-limit, security headers, CSP nonce, body parser, compression, SSE, request log, request-time DB role binding via `b.middleware.dbRoleFor`, in-process CIDR fence via `b.middleware.networkAllowlist`) wired by `createApp`; HTTP/1.1 + HTTP/2 outbound client with SSRF gate (cloud-metadata IPs hard-denied unconditionally; private / loopback / link-local overridable per call), scheme + userinfo + per-host (wildcard / per-method) destination allowlist, redirects, multipart, interceptors, progress, encrypted cookie jar (`b.httpClient`, `b.ssrfGuard`, `b.safeUrl`); operator-tunable network configurability — env-driven NTP / NTS (RFC 8915 authenticated time), IPv4-or-IPv6 NTP servers, DNS with IPv6 / DoH / DoT (private-CA trust pinning via `opts.ca`) / cache / lookup timeout, outbound HTTP proxy (`HTTP_PROXY` / `HTTPS_PROXY` / `NO_PROXY`), runtime DPI trust-store CA additions, application-level heartbeats, TCP socket defaults (`b.network`).
|
package/lib/db-query.js
CHANGED
|
@@ -39,31 +39,46 @@ class Query {
|
|
|
39
39
|
// (parameter placeholders only bind values, not names). Validate at
|
|
40
40
|
// construction so an attacker-controlled name with embedded `"` or
|
|
41
41
|
// SQL keywords can't break out of the wrapping quotes downstream.
|
|
42
|
-
// Cross-schema queries (e.g., Postgres `public.users`) need the
|
|
43
|
-
// schema-qualified API, not a dotted single-identifier — reject `.`
|
|
44
|
-
// here so the failure mode is explicit.
|
|
45
42
|
if (typeof tableName !== "string") {
|
|
46
43
|
throw new TypeError("Query: tableName must be a string, got " + typeof tableName);
|
|
47
44
|
}
|
|
45
|
+
// Cross-schema syntax: "schema.table". Two-part identifier only —
|
|
46
|
+
// three-part (catalog.schema.table) is rejected. Both parts must
|
|
47
|
+
// be valid SQL identifiers and contain no further dots.
|
|
48
|
+
var schema = null;
|
|
49
|
+
var table = tableName;
|
|
48
50
|
if (tableName.indexOf(".") !== -1) {
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
"
|
|
51
|
+
var parts = tableName.split(".");
|
|
52
|
+
if (parts.length !== 2 || parts[0].length === 0 || parts[1].length === 0) {
|
|
53
|
+
throw new Error("Query: schema-qualified tableName must be exactly " +
|
|
54
|
+
"'schema.table' (got '" + tableName + "'). Three-part identifiers " +
|
|
55
|
+
"(catalog.schema.table) and empty parts are not supported.");
|
|
56
|
+
}
|
|
57
|
+
schema = parts[0];
|
|
58
|
+
table = parts[1];
|
|
59
|
+
// Validate the schema identifier separately. allowReserved:true
|
|
60
|
+
// because we always wrap in `"..."`.
|
|
61
|
+
safeSql.validateIdentifier(schema, { allowReserved: true });
|
|
52
62
|
}
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
this.
|
|
60
|
-
this.
|
|
61
|
-
this.
|
|
62
|
-
this.
|
|
63
|
-
this.
|
|
64
|
-
this.
|
|
65
|
-
|
|
66
|
-
|
|
63
|
+
safeSql.validateIdentifier(table, { allowReserved: true });
|
|
64
|
+
|
|
65
|
+
this._db = database;
|
|
66
|
+
this._schema = schema;
|
|
67
|
+
this._table = table;
|
|
68
|
+
this._qualifiedKey = schema ? schema + "." + table : table;
|
|
69
|
+
this._where = [];
|
|
70
|
+
this._whereParams = [];
|
|
71
|
+
this._select = null;
|
|
72
|
+
this._orderBy = null;
|
|
73
|
+
this._limit = null;
|
|
74
|
+
this._offset = null;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
// Quoted SQL form: `"schema"."table"` if schema-qualified, else `"table"`.
|
|
78
|
+
_quotedTable() {
|
|
79
|
+
return this._schema
|
|
80
|
+
? '"' + this._schema + '"."' + this._table + '"'
|
|
81
|
+
: '"' + this._table + '"';
|
|
67
82
|
}
|
|
68
83
|
|
|
69
84
|
// ---- Chainable filters ----
|
|
@@ -89,10 +104,10 @@ class Query {
|
|
|
89
104
|
}
|
|
90
105
|
// Sealed-field translation: rewrite predicate to use derived hash if available
|
|
91
106
|
if (this._isSealedField(field)) {
|
|
92
|
-
var lookup = cryptoField.lookupHash(this.
|
|
107
|
+
var lookup = cryptoField.lookupHash(this._cryptoFieldKey(), field, value);
|
|
93
108
|
if (!lookup) {
|
|
94
109
|
throw new Error(
|
|
95
|
-
"cannot query sealed column '" + this.
|
|
110
|
+
"cannot query sealed column '" + this._cryptoFieldKey() + "." + field +
|
|
96
111
|
"' without a derived hash. Declare derivedHashes: { <name>: { from: '" + field + "' } } " +
|
|
97
112
|
"in the table's schema config."
|
|
98
113
|
);
|
|
@@ -107,10 +122,23 @@ class Query {
|
|
|
107
122
|
}
|
|
108
123
|
|
|
109
124
|
_isSealedField(field) {
|
|
110
|
-
var sealed = cryptoField.getSealedFields(this.
|
|
125
|
+
var sealed = cryptoField.getSealedFields(this._cryptoFieldKey());
|
|
111
126
|
return sealed.indexOf(field) !== -1;
|
|
112
127
|
}
|
|
113
128
|
|
|
129
|
+
// Sealed-field registry lookup key. Schema-qualified queries first
|
|
130
|
+
// try the qualified name (`audit.users`) so an operator can register
|
|
131
|
+
// per-schema sealed columns; falls back to the bare table when no
|
|
132
|
+
// qualified registration exists. The fall-back lets the existing
|
|
133
|
+
// table-name-only registrations keep working unchanged.
|
|
134
|
+
_cryptoFieldKey() {
|
|
135
|
+
if (!this._schema) return this._table;
|
|
136
|
+
if (cryptoField.getSealedFields(this._qualifiedKey).length > 0) {
|
|
137
|
+
return this._qualifiedKey;
|
|
138
|
+
}
|
|
139
|
+
return this._table;
|
|
140
|
+
}
|
|
141
|
+
|
|
114
142
|
// whereRaw — append a parenthesized raw SQL fragment with positional
|
|
115
143
|
// placeholders and the parameter values that fill them. Composes with
|
|
116
144
|
// .where() (AND-joined via the same `_where` array). The fragment
|
|
@@ -207,21 +235,22 @@ class Query {
|
|
|
207
235
|
// ---- Terminal methods (sync) ----
|
|
208
236
|
|
|
209
237
|
first() {
|
|
210
|
-
var sql = "SELECT " + this._projection() +
|
|
238
|
+
var sql = "SELECT " + this._projection() + " FROM " + this._quotedTable() +
|
|
211
239
|
this._whereClause() + this._orderLimitOffset() + " LIMIT 1";
|
|
212
240
|
var stmt = this._db.prepare(sql);
|
|
213
241
|
var row = stmt.get.apply(stmt, this._whereParams);
|
|
214
|
-
return row ? cryptoField.unsealRow(this.
|
|
242
|
+
return row ? cryptoField.unsealRow(this._cryptoFieldKey(), row) : null;
|
|
215
243
|
}
|
|
216
244
|
|
|
217
245
|
all() {
|
|
218
|
-
var sql = "SELECT " + this._projection() +
|
|
246
|
+
var sql = "SELECT " + this._projection() + " FROM " + this._quotedTable() +
|
|
219
247
|
this._whereClause() + this._orderLimitOffset();
|
|
220
248
|
var stmt = this._db.prepare(sql);
|
|
221
249
|
var rows = stmt.all.apply(stmt, this._whereParams);
|
|
222
250
|
var out = new Array(rows.length);
|
|
251
|
+
var key = this._cryptoFieldKey();
|
|
223
252
|
for (var i = 0; i < rows.length; i++) {
|
|
224
|
-
out[i] = cryptoField.unsealRow(
|
|
253
|
+
out[i] = cryptoField.unsealRow(key, rows[i]);
|
|
225
254
|
}
|
|
226
255
|
return out;
|
|
227
256
|
}
|
|
@@ -231,10 +260,10 @@ class Query {
|
|
|
231
260
|
// operator's pipeline. For large result sets (audit exports, backup
|
|
232
261
|
// table dumps) this avoids materializing the full rowset in memory.
|
|
233
262
|
stream() {
|
|
234
|
-
var sql = "SELECT " + this._projection() +
|
|
263
|
+
var sql = "SELECT " + this._projection() + " FROM " + this._quotedTable() +
|
|
235
264
|
this._whereClause() + this._orderLimitOffset();
|
|
236
265
|
var stmt = this._db.prepare(sql);
|
|
237
|
-
var
|
|
266
|
+
var key = this._cryptoFieldKey();
|
|
238
267
|
var iter;
|
|
239
268
|
try { iter = stmt.iterate.apply(stmt, this._whereParams); }
|
|
240
269
|
catch (e) {
|
|
@@ -248,7 +277,7 @@ class Query {
|
|
|
248
277
|
try {
|
|
249
278
|
var step = iter.next();
|
|
250
279
|
if (step.done) { this.push(null); return; }
|
|
251
|
-
this.push(cryptoField.unsealRow(
|
|
280
|
+
this.push(cryptoField.unsealRow(key, step.value));
|
|
252
281
|
} catch (e) {
|
|
253
282
|
this.destroy(e);
|
|
254
283
|
}
|
|
@@ -257,7 +286,7 @@ class Query {
|
|
|
257
286
|
}
|
|
258
287
|
|
|
259
288
|
count() {
|
|
260
|
-
var sql =
|
|
289
|
+
var sql = "SELECT COUNT(*) AS n FROM " + this._quotedTable() + this._whereClause();
|
|
261
290
|
var stmt = this._db.prepare(sql);
|
|
262
291
|
var row = stmt.get.apply(stmt, this._whereParams);
|
|
263
292
|
return row ? row.n : 0;
|
|
@@ -271,12 +300,12 @@ class Query {
|
|
|
271
300
|
if (withId._id === undefined || withId._id === null) {
|
|
272
301
|
withId._id = generateToken(16);
|
|
273
302
|
}
|
|
274
|
-
var sealed = cryptoField.sealRow(this.
|
|
303
|
+
var sealed = cryptoField.sealRow(this._cryptoFieldKey(), withId);
|
|
275
304
|
var cols = Object.keys(sealed);
|
|
276
305
|
var placeholders = cols.map(function () { return "?"; }).join(", ");
|
|
277
306
|
var quotedCols = cols.map(function (c) { return '"' + c + '"'; }).join(", ");
|
|
278
307
|
var values = cols.map(function (c) { return sealed[c]; });
|
|
279
|
-
var sql =
|
|
308
|
+
var sql = "INSERT INTO " + this._quotedTable() + " (" + quotedCols + ") VALUES (" + placeholders + ")";
|
|
280
309
|
var insertStmt = this._db.prepare(sql);
|
|
281
310
|
insertStmt.run.apply(insertStmt, values);
|
|
282
311
|
// Return the original row with _id filled in (plaintext, never sealed)
|
|
@@ -308,7 +337,7 @@ class Query {
|
|
|
308
337
|
if (this._where.length === 0) {
|
|
309
338
|
throw new Error("refusing unconditional update — call where(...) first");
|
|
310
339
|
}
|
|
311
|
-
var sealed = cryptoField.sealRow(this.
|
|
340
|
+
var sealed = cryptoField.sealRow(this._cryptoFieldKey(), changes);
|
|
312
341
|
var setKeys = Object.keys(sealed);
|
|
313
342
|
if (setKeys.length === 0) {
|
|
314
343
|
throw new Error("update changes object is empty");
|
|
@@ -322,11 +351,12 @@ class Query {
|
|
|
322
351
|
// SQLite supports LIMIT on UPDATE only when compiled with SQLITE_ENABLE_UPDATE_DELETE_LIMIT.
|
|
323
352
|
// node:sqlite ships without that flag — emulate single-row with a sub-select on rowid.
|
|
324
353
|
var sql;
|
|
354
|
+
var qt = this._quotedTable();
|
|
325
355
|
if (single) {
|
|
326
|
-
sql =
|
|
327
|
-
|
|
356
|
+
sql = "UPDATE " + qt + " SET " + setClause +
|
|
357
|
+
" WHERE rowid = (SELECT rowid FROM " + qt + " WHERE " + whereSql + " LIMIT 1)";
|
|
328
358
|
} else {
|
|
329
|
-
sql =
|
|
359
|
+
sql = "UPDATE " + qt + " SET " + setClause + " WHERE " + whereSql + limit;
|
|
330
360
|
}
|
|
331
361
|
var allParams = setValues.concat(this._whereParams);
|
|
332
362
|
var updStmt = this._db.prepare(sql);
|
|
@@ -348,11 +378,12 @@ class Query {
|
|
|
348
378
|
}
|
|
349
379
|
var whereSql = this._where.join(" AND ");
|
|
350
380
|
var sql;
|
|
381
|
+
var qt = this._quotedTable();
|
|
351
382
|
if (single) {
|
|
352
|
-
sql =
|
|
353
|
-
|
|
383
|
+
sql = "DELETE FROM " + qt +
|
|
384
|
+
" WHERE rowid = (SELECT rowid FROM " + qt + " WHERE " + whereSql + " LIMIT 1)";
|
|
354
385
|
} else {
|
|
355
|
-
sql =
|
|
386
|
+
sql = "DELETE FROM " + qt + " WHERE " + whereSql;
|
|
356
387
|
}
|
|
357
388
|
var delStmt = this._db.prepare(sql);
|
|
358
389
|
var info = delStmt.run.apply(delStmt, this._whereParams);
|
|
@@ -0,0 +1,291 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* azure-blob-bucket-ops — container-level operations for Azure Blob.
|
|
4
|
+
*
|
|
5
|
+
* Per-blob ops (put / get / list / delete) live in
|
|
6
|
+
* `lib/object-store/azure-blob.js` and are bound to a single container
|
|
7
|
+
* at create() time. Container lifecycle ops are at a different level —
|
|
8
|
+
* a service-scoped client that addresses arbitrary containers — so
|
|
9
|
+
* they get their own factory.
|
|
10
|
+
*
|
|
11
|
+
* create(name, opts?) async; PUT /{container}?restype=container
|
|
12
|
+
* delete(name) async; DELETE /{container}?restype=container
|
|
13
|
+
* list(opts?) async; GET /?comp=list
|
|
14
|
+
* -> [{ name, lastModified, etag,
|
|
15
|
+
* leaseStatus, leaseState, publicAccess }]
|
|
16
|
+
* setCorsRules(rules) async; PUT /?restype=service&comp=properties
|
|
17
|
+
* account-level CORS — Azure has no
|
|
18
|
+
* per-container CORS.
|
|
19
|
+
*
|
|
20
|
+
* Shared Key auth via `lib/object-store/azure-blob.js`'s `signRequest`
|
|
21
|
+
* helper. Not implemented here:
|
|
22
|
+
*
|
|
23
|
+
* setLifecycle(name, rules) — Azure Storage lifecycle management
|
|
24
|
+
* policies live on Azure Resource Manager
|
|
25
|
+
* (`management.azure.com`), not the Blob service endpoint. ARM
|
|
26
|
+
* requires an Azure AD bearer token (Service Principal flow), a
|
|
27
|
+
* different auth scheme entirely. Operators wiring lifecycle do
|
|
28
|
+
* so via Terraform / Bicep / az CLI; the framework documents the
|
|
29
|
+
* gap rather than half-implementing one auth path.
|
|
30
|
+
*/
|
|
31
|
+
var azureBlob = require("./azure-blob");
|
|
32
|
+
var httpClient = require("../http-client");
|
|
33
|
+
var safeUrl = require("../safe-url");
|
|
34
|
+
var { ObjectStoreError } = require("../framework-error");
|
|
35
|
+
|
|
36
|
+
var _err = ObjectStoreError.factory;
|
|
37
|
+
|
|
38
|
+
// Azure container names: 3-63 chars, lowercase alphanumeric + hyphens,
|
|
39
|
+
// no consecutive hyphens, must start and end with letter or digit.
|
|
40
|
+
var CONTAINER_NAME_RE = /^[a-z0-9](?:[a-z0-9]|-(?!-))*[a-z0-9]$/;
|
|
41
|
+
|
|
42
|
+
function _validateContainerName(name) {
|
|
43
|
+
if (typeof name !== "string" || name.length === 0) {
|
|
44
|
+
throw _err("BUCKET_INVALID_NAME",
|
|
45
|
+
"azure-blob bucketOps: container name must be a non-empty string", true);
|
|
46
|
+
}
|
|
47
|
+
if (name.length < 3 || name.length > 63) {
|
|
48
|
+
throw _err("BUCKET_INVALID_NAME",
|
|
49
|
+
"azure-blob bucketOps: container name must be 3-63 chars (got " +
|
|
50
|
+
name.length + ")", true);
|
|
51
|
+
}
|
|
52
|
+
if (!CONTAINER_NAME_RE.test(name)) {
|
|
53
|
+
throw _err("BUCKET_INVALID_NAME",
|
|
54
|
+
"azure-blob bucketOps: container name '" + name + "' is invalid; " +
|
|
55
|
+
"lowercase letters / digits / hyphens only, no consecutive hyphens, " +
|
|
56
|
+
"must start and end with letter or digit", true);
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function _validateCorsRule(rule, idx) {
|
|
61
|
+
function bad(msg) {
|
|
62
|
+
throw _err("INVALID_CORS_RULE",
|
|
63
|
+
"azure-blob bucketOps: setCorsRules: rule[" + idx + "]: " + msg, true);
|
|
64
|
+
}
|
|
65
|
+
if (!rule || typeof rule !== "object") bad("must be an object");
|
|
66
|
+
if (!Array.isArray(rule.allowedOrigins) || rule.allowedOrigins.length === 0) {
|
|
67
|
+
bad("allowedOrigins must be a non-empty array");
|
|
68
|
+
}
|
|
69
|
+
if (!Array.isArray(rule.allowedMethods) || rule.allowedMethods.length === 0) {
|
|
70
|
+
bad("allowedMethods must be a non-empty array");
|
|
71
|
+
}
|
|
72
|
+
for (var i = 0; i < rule.allowedMethods.length; i++) {
|
|
73
|
+
var m = rule.allowedMethods[i];
|
|
74
|
+
if (["GET", "PUT", "POST", "DELETE", "HEAD", "MERGE", "OPTIONS"].indexOf(m) === -1) {
|
|
75
|
+
bad("allowedMethods[" + i + "] = " + JSON.stringify(m) +
|
|
76
|
+
" (must be one of GET/PUT/POST/DELETE/HEAD/MERGE/OPTIONS)");
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
if (rule.allowedHeaders !== undefined && !Array.isArray(rule.allowedHeaders)) {
|
|
80
|
+
bad("allowedHeaders, if present, must be an array");
|
|
81
|
+
}
|
|
82
|
+
if (rule.exposedHeaders !== undefined && !Array.isArray(rule.exposedHeaders)) {
|
|
83
|
+
bad("exposedHeaders, if present, must be an array");
|
|
84
|
+
}
|
|
85
|
+
if (rule.maxAgeInSeconds !== undefined &&
|
|
86
|
+
(typeof rule.maxAgeInSeconds !== "number" || rule.maxAgeInSeconds < 0 ||
|
|
87
|
+
!Number.isFinite(rule.maxAgeInSeconds))) {
|
|
88
|
+
bad("maxAgeInSeconds, if present, must be a non-negative finite number");
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
function _xmlEscape(s) {
|
|
93
|
+
return String(s)
|
|
94
|
+
.replace(/&/g, "&")
|
|
95
|
+
.replace(/</g, "<")
|
|
96
|
+
.replace(/>/g, ">")
|
|
97
|
+
.replace(/"/g, """)
|
|
98
|
+
.replace(/'/g, "'");
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
function _buildCorsXml(rules) {
|
|
102
|
+
var inner = rules.map(function (rule) {
|
|
103
|
+
var parts = [
|
|
104
|
+
"<CorsRule>",
|
|
105
|
+
"<AllowedOrigins>" + _xmlEscape(rule.allowedOrigins.join(",")) + "</AllowedOrigins>",
|
|
106
|
+
"<AllowedMethods>" + rule.allowedMethods.join(",") + "</AllowedMethods>",
|
|
107
|
+
"<AllowedHeaders>" + _xmlEscape((rule.allowedHeaders || []).join(",")) + "</AllowedHeaders>",
|
|
108
|
+
"<ExposedHeaders>" + _xmlEscape((rule.exposedHeaders || []).join(",")) + "</ExposedHeaders>",
|
|
109
|
+
"<MaxAgeInSeconds>" +
|
|
110
|
+
(rule.maxAgeInSeconds == null ? 0 : Math.floor(rule.maxAgeInSeconds)) +
|
|
111
|
+
"</MaxAgeInSeconds>",
|
|
112
|
+
"</CorsRule>",
|
|
113
|
+
];
|
|
114
|
+
return parts.join("");
|
|
115
|
+
}).join("");
|
|
116
|
+
return '<?xml version="1.0" encoding="utf-8"?>' +
|
|
117
|
+
"<StorageServiceProperties><Cors>" + inner + "</Cors></StorageServiceProperties>";
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
// Tiny XML extractor — pulls every occurrence of <Tag>value</Tag>
|
|
121
|
+
// and returns an array of value strings. Sufficient for the limited
|
|
122
|
+
// shapes we read (Containers list, container metadata).
|
|
123
|
+
function _extractAll(xml, tag) {
|
|
124
|
+
var out = [];
|
|
125
|
+
var re = new RegExp("<" + tag + ">([\\s\\S]*?)</" + tag + ">", "g");
|
|
126
|
+
var m;
|
|
127
|
+
while ((m = re.exec(xml)) !== null) out.push(m[1]);
|
|
128
|
+
return out;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
function _extractBlocks(xml, tag) {
|
|
132
|
+
var open = "<" + tag + ">";
|
|
133
|
+
var close = "</" + tag + ">";
|
|
134
|
+
var blocks = [];
|
|
135
|
+
var i = 0;
|
|
136
|
+
while (true) {
|
|
137
|
+
var s = xml.indexOf(open, i);
|
|
138
|
+
if (s === -1) break;
|
|
139
|
+
var e = xml.indexOf(close, s + open.length);
|
|
140
|
+
if (e === -1) break;
|
|
141
|
+
blocks.push(xml.slice(s + open.length, e));
|
|
142
|
+
i = e + close.length;
|
|
143
|
+
}
|
|
144
|
+
return blocks;
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
function create(config) {
|
|
148
|
+
if (!config) throw _err("BAD_OPT", "azure-blob bucketOps: config required", true);
|
|
149
|
+
if (!config.accountName) throw _err("BAD_OPT", "azure-blob bucketOps: accountName required", true);
|
|
150
|
+
if (!config.accountKey) throw _err("BAD_OPT", "azure-blob bucketOps: accountKey required", true);
|
|
151
|
+
|
|
152
|
+
var endpoint = config.endpoint ||
|
|
153
|
+
("https://" + config.accountName + ".blob.core.windows.net");
|
|
154
|
+
if (endpoint.endsWith("/")) endpoint = endpoint.slice(0, -1);
|
|
155
|
+
var apiVersion = config.apiVersion || azureBlob.DEFAULT_API_VERSION;
|
|
156
|
+
var timeoutMs = config.timeoutMs;
|
|
157
|
+
var allowedProtocols = config.allowedProtocols || safeUrl.ALLOW_HTTP_TLS;
|
|
158
|
+
var allowInternal = config.allowInternal != null ? config.allowInternal : null;
|
|
159
|
+
|
|
160
|
+
function _sign(method, url, headers) {
|
|
161
|
+
return azureBlob.signRequest({
|
|
162
|
+
method: method,
|
|
163
|
+
url: url,
|
|
164
|
+
headers: headers || {},
|
|
165
|
+
accountName: config.accountName,
|
|
166
|
+
accountKey: config.accountKey,
|
|
167
|
+
apiVersion: apiVersion,
|
|
168
|
+
}).headers;
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
function _request(method, url, headers, body, expectStatus) {
|
|
172
|
+
var reqOpts = {
|
|
173
|
+
method: method,
|
|
174
|
+
url: url,
|
|
175
|
+
headers: headers,
|
|
176
|
+
body: body,
|
|
177
|
+
idleTimeoutMs: timeoutMs,
|
|
178
|
+
allowedProtocols: allowedProtocols,
|
|
179
|
+
errorClass: ObjectStoreError,
|
|
180
|
+
};
|
|
181
|
+
if (allowInternal !== null) reqOpts.allowInternal = allowInternal;
|
|
182
|
+
// http-client rejects on any 4xx/5xx by default. The bucket-ops API
|
|
183
|
+
// semantically accepts certain non-2xx codes (404 for "missing on
|
|
184
|
+
// delete", 409 for "container already exists"), so we catch those
|
|
185
|
+
// and surface them as the wrapped response object instead.
|
|
186
|
+
return httpClient.request(reqOpts).then(function (res) {
|
|
187
|
+
if (expectStatus && expectStatus.indexOf(res.statusCode) === -1) {
|
|
188
|
+
throw _err("UNEXPECTED_STATUS",
|
|
189
|
+
"azure-blob bucketOps: " + method + " " + url +
|
|
190
|
+
" returned HTTP " + res.statusCode, true);
|
|
191
|
+
}
|
|
192
|
+
return res;
|
|
193
|
+
}, function (e) {
|
|
194
|
+
var sc = e && e.statusCode;
|
|
195
|
+
if (sc && expectStatus && expectStatus.indexOf(sc) !== -1) {
|
|
196
|
+
return { statusCode: sc, headers: {}, body: Buffer.alloc(0) };
|
|
197
|
+
}
|
|
198
|
+
throw e;
|
|
199
|
+
});
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
async function createContainer(name, opts) {
|
|
203
|
+
_validateContainerName(name);
|
|
204
|
+
opts = opts || {};
|
|
205
|
+
var url = new URL(endpoint + "/" + name + "?restype=container");
|
|
206
|
+
var headers = { "Content-Length": "0" };
|
|
207
|
+
if (opts.publicAccess) {
|
|
208
|
+
if (opts.publicAccess !== "blob" && opts.publicAccess !== "container") {
|
|
209
|
+
throw _err("BAD_OPT",
|
|
210
|
+
"azure-blob bucketOps: createContainer: publicAccess must be " +
|
|
211
|
+
"'blob' or 'container' (got " + JSON.stringify(opts.publicAccess) + ")", true);
|
|
212
|
+
}
|
|
213
|
+
headers["x-ms-blob-public-access"] = opts.publicAccess;
|
|
214
|
+
}
|
|
215
|
+
var signed = _sign("PUT", url, headers);
|
|
216
|
+
var res = await _request("PUT", url, signed, null, [201, 409]);
|
|
217
|
+
if (res.statusCode === 409) {
|
|
218
|
+
throw _err("BUCKET_ALREADY_OWNED",
|
|
219
|
+
"azure-blob bucketOps: container '" + name +
|
|
220
|
+
"' already exists or was recently deleted", true);
|
|
221
|
+
}
|
|
222
|
+
return { name: name };
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
async function deleteContainer(name) {
|
|
226
|
+
_validateContainerName(name);
|
|
227
|
+
var url = new URL(endpoint + "/" + name + "?restype=container");
|
|
228
|
+
var signed = _sign("DELETE", url, {});
|
|
229
|
+
var res = await _request("DELETE", url, signed, null, [202, 404]);
|
|
230
|
+
return res.statusCode === 202;
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
async function listContainers(opts) {
|
|
234
|
+
opts = opts || {};
|
|
235
|
+
var url = new URL(endpoint + "/?comp=list");
|
|
236
|
+
if (opts.prefix) url.searchParams.set("prefix", opts.prefix);
|
|
237
|
+
if (opts.maxResults != null) url.searchParams.set("maxresults", String(opts.maxResults));
|
|
238
|
+
var signed = _sign("GET", url, {});
|
|
239
|
+
var res = await _request("GET", url, signed, null, [200]);
|
|
240
|
+
var xml = Buffer.isBuffer(res.body) ? res.body.toString("utf8") :
|
|
241
|
+
typeof res.body === "string" ? res.body :
|
|
242
|
+
"";
|
|
243
|
+
var blocks = _extractBlocks(xml, "Container");
|
|
244
|
+
return blocks.map(function (block) {
|
|
245
|
+
return {
|
|
246
|
+
name: (_extractAll(block, "Name")[0] || "").trim(),
|
|
247
|
+
lastModified: (_extractAll(block, "Last-Modified")[0] || null),
|
|
248
|
+
etag: (_extractAll(block, "Etag")[0] || null),
|
|
249
|
+
leaseStatus: (_extractAll(block, "LeaseStatus")[0] || null),
|
|
250
|
+
leaseState: (_extractAll(block, "LeaseState")[0] || null),
|
|
251
|
+
publicAccess: (_extractAll(block, "PublicAccess")[0] || null),
|
|
252
|
+
};
|
|
253
|
+
});
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
async function setCorsRules(rules) {
|
|
257
|
+
if (!Array.isArray(rules)) {
|
|
258
|
+
throw _err("INVALID_CORS_RULE",
|
|
259
|
+
"azure-blob bucketOps: setCorsRules: rules must be an array", true);
|
|
260
|
+
}
|
|
261
|
+
rules.forEach(_validateCorsRule);
|
|
262
|
+
var xml = _buildCorsXml(rules);
|
|
263
|
+
var bodyBuf = Buffer.from(xml, "utf8");
|
|
264
|
+
var url = new URL(endpoint + "/?restype=service&comp=properties");
|
|
265
|
+
var headers = {
|
|
266
|
+
"Content-Type": "application/xml",
|
|
267
|
+
"Content-Length": String(bodyBuf.length),
|
|
268
|
+
};
|
|
269
|
+
var signed = _sign("PUT", url, headers);
|
|
270
|
+
await _request("PUT", url, signed, bodyBuf, [202]);
|
|
271
|
+
return { rulesApplied: rules.length };
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
return {
|
|
275
|
+
protocol: "azure-blob",
|
|
276
|
+
create: createContainer,
|
|
277
|
+
delete: deleteContainer,
|
|
278
|
+
list: listContainers,
|
|
279
|
+
setCorsRules: setCorsRules,
|
|
280
|
+
setLifecycle: function () {
|
|
281
|
+
throw _err("NOT_SUPPORTED",
|
|
282
|
+
"azure-blob bucketOps: setLifecycle is not implemented because " +
|
|
283
|
+
"Azure Storage lifecycle management policies live on Azure Resource " +
|
|
284
|
+
"Manager (management.azure.com) and require Azure AD bearer token " +
|
|
285
|
+
"auth, not Shared Key. Configure lifecycle via Terraform / Bicep / " +
|
|
286
|
+
"az CLI.", true);
|
|
287
|
+
},
|
|
288
|
+
};
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
module.exports = { create: create };
|
|
@@ -0,0 +1,327 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* gcs-bucket-ops — bucket-level operations for Google Cloud Storage.
|
|
4
|
+
*
|
|
5
|
+
* Per-object ops (put / get / list / delete) live in
|
|
6
|
+
* `lib/object-store/gcs.js` and are bound to a single bucket at
|
|
7
|
+
* create() time. Bucket lifecycle ops are at a different level — a
|
|
8
|
+
* project-scoped client that addresses arbitrary buckets — so they
|
|
9
|
+
* get their own factory.
|
|
10
|
+
*
|
|
11
|
+
* create(name, opts?) async; POST /storage/v1/b?project={projectId}
|
|
12
|
+
* opts: location ('US' / 'EU' / region) +
|
|
13
|
+
* storageClass + iamConfiguration
|
|
14
|
+
* delete(name) async; DELETE /storage/v1/b/{name}
|
|
15
|
+
* list() async; GET /storage/v1/b?project={projectId}
|
|
16
|
+
* -> [{ name, location, storageClass,
|
|
17
|
+
* timeCreated, updated }]
|
|
18
|
+
* setLifecycle(name, rules) async; PATCH /storage/v1/b/{name}
|
|
19
|
+
* -> body { lifecycle: { rule: [...] } }
|
|
20
|
+
* setCorsRules(name, rules) async; PATCH /storage/v1/b/{name}
|
|
21
|
+
* -> body { cors: [...] }
|
|
22
|
+
*
|
|
23
|
+
* Auth: same service-account JSON / RSA-SHA256-signed JWT exchanged
|
|
24
|
+
* for an OAuth2 access token as `lib/object-store/gcs.js`.
|
|
25
|
+
*/
|
|
26
|
+
var fs = require("node:fs");
|
|
27
|
+
var gcs = require("./gcs");
|
|
28
|
+
var authHeader = require("../auth-header");
|
|
29
|
+
var httpClient = require("../http-client");
|
|
30
|
+
var safeJson = require("../safe-json");
|
|
31
|
+
var safeUrl = require("../safe-url");
|
|
32
|
+
var C = require("../constants");
|
|
33
|
+
var { ObjectStoreError } = require("../framework-error");
|
|
34
|
+
|
|
35
|
+
var _err = ObjectStoreError.factory;
|
|
36
|
+
|
|
37
|
+
// GCS bucket names: 3-63 chars, lowercase letters / digits / hyphens /
|
|
38
|
+
// underscores / dots; can't start or end with hyphen; can't contain '..'
|
|
39
|
+
// or 'goog' prefix; can't be IP address. Most violations the API will
|
|
40
|
+
// reject for us — we sanity-check the basics.
|
|
41
|
+
var BUCKET_NAME_RE = /^[a-z0-9][a-z0-9._-]{1,61}[a-z0-9]$/;
|
|
42
|
+
|
|
43
|
+
function _validateBucketName(name) {
|
|
44
|
+
if (typeof name !== "string" || name.length === 0) {
|
|
45
|
+
throw _err("BUCKET_INVALID_NAME",
|
|
46
|
+
"gcs bucketOps: bucket name must be a non-empty string", true);
|
|
47
|
+
}
|
|
48
|
+
if (name.length < 3 || name.length > 63) {
|
|
49
|
+
throw _err("BUCKET_INVALID_NAME",
|
|
50
|
+
"gcs bucketOps: bucket name must be 3-63 chars (got " + name.length + ")", true);
|
|
51
|
+
}
|
|
52
|
+
if (!BUCKET_NAME_RE.test(name)) {
|
|
53
|
+
throw _err("BUCKET_INVALID_NAME",
|
|
54
|
+
"gcs bucketOps: bucket name '" + name + "' is invalid; lowercase " +
|
|
55
|
+
"letters / digits / hyphens / underscores / dots only, must start " +
|
|
56
|
+
"and end with letter or digit", true);
|
|
57
|
+
}
|
|
58
|
+
if (name.indexOf("..") !== -1) {
|
|
59
|
+
throw _err("BUCKET_INVALID_NAME",
|
|
60
|
+
"gcs bucketOps: bucket name '" + name + "' contains '..'", true);
|
|
61
|
+
}
|
|
62
|
+
if (name.indexOf("goog") === 0) {
|
|
63
|
+
throw _err("BUCKET_INVALID_NAME",
|
|
64
|
+
"gcs bucketOps: bucket name '" + name + "' starts with 'goog' " +
|
|
65
|
+
"(reserved by Google)", true);
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
// GCS lifecycle rules: { action: { type: "Delete"|"SetStorageClass", storageClass? },
|
|
70
|
+
// condition: { age, createdBefore, ...} }
|
|
71
|
+
function _validateLifecycleRule(rule, idx) {
|
|
72
|
+
function bad(msg) {
|
|
73
|
+
throw _err("INVALID_LIFECYCLE",
|
|
74
|
+
"gcs bucketOps: setLifecycle: rule[" + idx + "]: " + msg, true);
|
|
75
|
+
}
|
|
76
|
+
if (!rule || typeof rule !== "object") bad("must be an object");
|
|
77
|
+
if (!rule.action || typeof rule.action !== "object") {
|
|
78
|
+
bad("action object is required");
|
|
79
|
+
}
|
|
80
|
+
if (!rule.action.type) bad("action.type is required");
|
|
81
|
+
if (rule.action.type !== "Delete" && rule.action.type !== "SetStorageClass" &&
|
|
82
|
+
rule.action.type !== "AbortIncompleteMultipartUpload") {
|
|
83
|
+
bad("action.type must be 'Delete' / 'SetStorageClass' / " +
|
|
84
|
+
"'AbortIncompleteMultipartUpload' (got " +
|
|
85
|
+
JSON.stringify(rule.action.type) + ")");
|
|
86
|
+
}
|
|
87
|
+
if (rule.action.type === "SetStorageClass" && !rule.action.storageClass) {
|
|
88
|
+
bad("action.storageClass required when action.type='SetStorageClass'");
|
|
89
|
+
}
|
|
90
|
+
if (!rule.condition || typeof rule.condition !== "object") {
|
|
91
|
+
bad("condition object is required");
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
function _validateCorsRule(rule, idx) {
|
|
96
|
+
function bad(msg) {
|
|
97
|
+
throw _err("INVALID_CORS_RULE",
|
|
98
|
+
"gcs bucketOps: setCorsRules: rule[" + idx + "]: " + msg, true);
|
|
99
|
+
}
|
|
100
|
+
if (!rule || typeof rule !== "object") bad("must be an object");
|
|
101
|
+
if (!Array.isArray(rule.origin) || rule.origin.length === 0) {
|
|
102
|
+
bad("origin must be a non-empty array");
|
|
103
|
+
}
|
|
104
|
+
if (rule.method !== undefined && !Array.isArray(rule.method)) {
|
|
105
|
+
bad("method, if present, must be an array");
|
|
106
|
+
}
|
|
107
|
+
if (rule.responseHeader !== undefined && !Array.isArray(rule.responseHeader)) {
|
|
108
|
+
bad("responseHeader, if present, must be an array");
|
|
109
|
+
}
|
|
110
|
+
if (rule.maxAgeSeconds !== undefined &&
|
|
111
|
+
(typeof rule.maxAgeSeconds !== "number" || rule.maxAgeSeconds < 0)) {
|
|
112
|
+
bad("maxAgeSeconds, if present, must be a non-negative number");
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
function create(config) {
|
|
117
|
+
if (!config) throw _err("BAD_OPT", "gcs bucketOps: config required", true);
|
|
118
|
+
|
|
119
|
+
var serviceAccount = config.serviceAccount;
|
|
120
|
+
if (!serviceAccount && config.serviceAccountFile) {
|
|
121
|
+
try {
|
|
122
|
+
serviceAccount = safeJson.parse(fs.readFileSync(config.serviceAccountFile));
|
|
123
|
+
} catch (e) {
|
|
124
|
+
throw _err("BAD_OPT", "gcs bucketOps: failed to read serviceAccountFile '" +
|
|
125
|
+
config.serviceAccountFile + "': " + ((e && e.message) || String(e)), true);
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
if (!serviceAccount || !serviceAccount.client_email || !serviceAccount.private_key) {
|
|
129
|
+
throw _err("BAD_OPT",
|
|
130
|
+
"gcs bucketOps: serviceAccount with { client_email, private_key } required " +
|
|
131
|
+
"(or serviceAccountFile pointing to one)", true);
|
|
132
|
+
}
|
|
133
|
+
var projectId = config.projectId || serviceAccount.project_id;
|
|
134
|
+
if (!projectId) {
|
|
135
|
+
throw _err("BAD_OPT",
|
|
136
|
+
"gcs bucketOps: projectId required (either config.projectId or " +
|
|
137
|
+
"serviceAccount.project_id)", true);
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
var endpoint = config.endpoint || gcs.DEFAULT_ENDPOINT;
|
|
141
|
+
if (endpoint.endsWith("/")) endpoint = endpoint.slice(0, -1);
|
|
142
|
+
var tokenEndpoint = config.tokenEndpoint || "https://oauth2.googleapis.com/token";
|
|
143
|
+
// Bucket-level admin needs the full-control scope — list-buckets +
|
|
144
|
+
// create + delete + lifecycle + CORS are all admin operations beyond
|
|
145
|
+
// the per-object read_write scope used by gcs.js's per-blob client.
|
|
146
|
+
var scope = config.scope || "https://www.googleapis.com/auth/devstorage.full_control";
|
|
147
|
+
var timeoutMs = config.timeoutMs;
|
|
148
|
+
var allowedProtocols = config.allowedProtocols || safeUrl.ALLOW_HTTP_TLS;
|
|
149
|
+
var allowInternal = config.allowInternal != null ? config.allowInternal : null;
|
|
150
|
+
|
|
151
|
+
// Token cache — same shape as gcs.js's per-blob client, scoped to
|
|
152
|
+
// this factory instance so a parallel per-blob client doesn't share
|
|
153
|
+
// the admin-scoped token (different scope).
|
|
154
|
+
var cachedToken = null;
|
|
155
|
+
var TOKEN_REFRESH_BUFFER = C.TIME.minutes(5);
|
|
156
|
+
|
|
157
|
+
function _request(method, url, headers, body, expectStatus) {
|
|
158
|
+
var reqOpts = {
|
|
159
|
+
method: method,
|
|
160
|
+
url: url,
|
|
161
|
+
headers: headers,
|
|
162
|
+
body: body,
|
|
163
|
+
idleTimeoutMs: timeoutMs,
|
|
164
|
+
allowedProtocols: allowedProtocols,
|
|
165
|
+
errorClass: ObjectStoreError,
|
|
166
|
+
};
|
|
167
|
+
if (allowInternal !== null) reqOpts.allowInternal = allowInternal;
|
|
168
|
+
return httpClient.request(reqOpts).then(function (res) {
|
|
169
|
+
if (expectStatus && expectStatus.indexOf(res.statusCode) === -1) {
|
|
170
|
+
var bodyText = res.body ?
|
|
171
|
+
(Buffer.isBuffer(res.body) ? res.body.toString("utf8") : String(res.body)) : "";
|
|
172
|
+
throw _err("UNEXPECTED_STATUS",
|
|
173
|
+
"gcs bucketOps: " + method + " " + url + " returned HTTP " +
|
|
174
|
+
res.statusCode + (bodyText ? " — " + bodyText.slice(0, 500) : ""), true);
|
|
175
|
+
}
|
|
176
|
+
return res;
|
|
177
|
+
}, function (e) {
|
|
178
|
+
// http-client rejects on 4xx/5xx; if the caller marked the
|
|
179
|
+
// status as semantically acceptable (404 on delete, 409 on
|
|
180
|
+
// create) surface it as a normal response.
|
|
181
|
+
var sc = e && e.statusCode;
|
|
182
|
+
if (sc && expectStatus && expectStatus.indexOf(sc) !== -1) {
|
|
183
|
+
return { statusCode: sc, headers: {}, body: Buffer.alloc(0) };
|
|
184
|
+
}
|
|
185
|
+
throw e;
|
|
186
|
+
});
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
async function _ensureToken() {
|
|
190
|
+
if (cachedToken && Date.now() < cachedToken.expiresAt - TOKEN_REFRESH_BUFFER) {
|
|
191
|
+
return cachedToken.accessToken;
|
|
192
|
+
}
|
|
193
|
+
var assertion = gcs._signJwt(serviceAccount, scope, tokenEndpoint);
|
|
194
|
+
var bodyStr = "grant_type=" + encodeURIComponent("urn:ietf:params:oauth:grant-type:jwt-bearer") +
|
|
195
|
+
"&assertion=" + encodeURIComponent(assertion);
|
|
196
|
+
var bodyBuf = Buffer.from(bodyStr, "utf8");
|
|
197
|
+
var res = await _request("POST", new URL(tokenEndpoint), {
|
|
198
|
+
"Content-Type": "application/x-www-form-urlencoded",
|
|
199
|
+
"Content-Length": String(bodyBuf.length),
|
|
200
|
+
}, bodyBuf, [200]);
|
|
201
|
+
var tokenResp = safeJson.parse(res.body);
|
|
202
|
+
if (!tokenResp.access_token) {
|
|
203
|
+
throw _err("AUTH_FAILED",
|
|
204
|
+
"gcs bucketOps: token endpoint returned no access_token: " +
|
|
205
|
+
(res.body ? res.body.toString("utf8") : ""), true);
|
|
206
|
+
}
|
|
207
|
+
var expiresInMs = C.TIME.seconds(tokenResp.expires_in || 3600);
|
|
208
|
+
cachedToken = {
|
|
209
|
+
accessToken: tokenResp.access_token,
|
|
210
|
+
expiresAt: Date.now() + expiresInMs,
|
|
211
|
+
};
|
|
212
|
+
return cachedToken.accessToken;
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
function _bucketBaseUrl() {
|
|
216
|
+
return endpoint + "/storage/v1/b";
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
async function createBucket(name, opts) {
|
|
220
|
+
_validateBucketName(name);
|
|
221
|
+
opts = opts || {};
|
|
222
|
+
var token = await _ensureToken();
|
|
223
|
+
var url = new URL(_bucketBaseUrl());
|
|
224
|
+
url.searchParams.set("project", projectId);
|
|
225
|
+
var bodyObj = { name: name };
|
|
226
|
+
if (opts.location) bodyObj.location = opts.location;
|
|
227
|
+
if (opts.storageClass) bodyObj.storageClass = opts.storageClass;
|
|
228
|
+
if (opts.iamConfiguration) bodyObj.iamConfiguration = opts.iamConfiguration;
|
|
229
|
+
var bodyBuf = Buffer.from(JSON.stringify(bodyObj), "utf8");
|
|
230
|
+
var headers = Object.assign(authHeader.bearer(token), {
|
|
231
|
+
"Content-Type": "application/json",
|
|
232
|
+
"Content-Length": String(bodyBuf.length),
|
|
233
|
+
});
|
|
234
|
+
var res = await _request("POST", url, headers, bodyBuf, [200, 409]);
|
|
235
|
+
if (res.statusCode === 409) {
|
|
236
|
+
throw _err("BUCKET_ALREADY_OWNED",
|
|
237
|
+
"gcs bucketOps: bucket '" + name + "' already exists", true);
|
|
238
|
+
}
|
|
239
|
+
var parsed = safeJson.parse(res.body);
|
|
240
|
+
return {
|
|
241
|
+
name: parsed.name,
|
|
242
|
+
location: parsed.location || null,
|
|
243
|
+
storageClass: parsed.storageClass || null,
|
|
244
|
+
};
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
async function deleteBucket(name) {
|
|
248
|
+
_validateBucketName(name);
|
|
249
|
+
var token = await _ensureToken();
|
|
250
|
+
var url = new URL(_bucketBaseUrl() + "/" + encodeURIComponent(name));
|
|
251
|
+
var headers = authHeader.bearer(token);
|
|
252
|
+
var res = await _request("DELETE", url, headers, null, [204, 404]);
|
|
253
|
+
return res.statusCode === 204;
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
async function listBuckets(opts) {
|
|
257
|
+
opts = opts || {};
|
|
258
|
+
var token = await _ensureToken();
|
|
259
|
+
var url = new URL(_bucketBaseUrl());
|
|
260
|
+
url.searchParams.set("project", projectId);
|
|
261
|
+
if (opts.prefix) url.searchParams.set("prefix", opts.prefix);
|
|
262
|
+
if (opts.maxResults) url.searchParams.set("maxResults", String(opts.maxResults));
|
|
263
|
+
if (opts.pageToken) url.searchParams.set("pageToken", opts.pageToken);
|
|
264
|
+
var headers = authHeader.bearer(token);
|
|
265
|
+
var res = await _request("GET", url, headers, null, [200]);
|
|
266
|
+
var parsed = safeJson.parse(res.body);
|
|
267
|
+
var items = Array.isArray(parsed.items) ? parsed.items : [];
|
|
268
|
+
return items.map(function (item) {
|
|
269
|
+
return {
|
|
270
|
+
name: item.name,
|
|
271
|
+
location: item.location || null,
|
|
272
|
+
storageClass: item.storageClass || null,
|
|
273
|
+
timeCreated: item.timeCreated || null,
|
|
274
|
+
updated: item.updated || null,
|
|
275
|
+
};
|
|
276
|
+
});
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
async function setLifecycle(name, rules) {
|
|
280
|
+
_validateBucketName(name);
|
|
281
|
+
if (!Array.isArray(rules)) {
|
|
282
|
+
throw _err("INVALID_LIFECYCLE",
|
|
283
|
+
"gcs bucketOps: setLifecycle: rules must be an array", true);
|
|
284
|
+
}
|
|
285
|
+
rules.forEach(_validateLifecycleRule);
|
|
286
|
+
var token = await _ensureToken();
|
|
287
|
+
var url = new URL(_bucketBaseUrl() + "/" + encodeURIComponent(name));
|
|
288
|
+
var bodyObj = { lifecycle: { rule: rules } };
|
|
289
|
+
var bodyBuf = Buffer.from(JSON.stringify(bodyObj), "utf8");
|
|
290
|
+
var headers = Object.assign(authHeader.bearer(token), {
|
|
291
|
+
"Content-Type": "application/json",
|
|
292
|
+
"Content-Length": String(bodyBuf.length),
|
|
293
|
+
});
|
|
294
|
+
await _request("PATCH", url, headers, bodyBuf, [200]);
|
|
295
|
+
return { rulesApplied: rules.length };
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
async function setCorsRules(name, rules) {
|
|
299
|
+
_validateBucketName(name);
|
|
300
|
+
if (!Array.isArray(rules)) {
|
|
301
|
+
throw _err("INVALID_CORS_RULE",
|
|
302
|
+
"gcs bucketOps: setCorsRules: rules must be an array", true);
|
|
303
|
+
}
|
|
304
|
+
rules.forEach(_validateCorsRule);
|
|
305
|
+
var token = await _ensureToken();
|
|
306
|
+
var url = new URL(_bucketBaseUrl() + "/" + encodeURIComponent(name));
|
|
307
|
+
var bodyObj = { cors: rules };
|
|
308
|
+
var bodyBuf = Buffer.from(JSON.stringify(bodyObj), "utf8");
|
|
309
|
+
var headers = Object.assign(authHeader.bearer(token), {
|
|
310
|
+
"Content-Type": "application/json",
|
|
311
|
+
"Content-Length": String(bodyBuf.length),
|
|
312
|
+
});
|
|
313
|
+
await _request("PATCH", url, headers, bodyBuf, [200]);
|
|
314
|
+
return { rulesApplied: rules.length };
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
return {
|
|
318
|
+
protocol: "gcs",
|
|
319
|
+
create: createBucket,
|
|
320
|
+
delete: deleteBucket,
|
|
321
|
+
list: listBuckets,
|
|
322
|
+
setLifecycle: setLifecycle,
|
|
323
|
+
setCorsRules: setCorsRules,
|
|
324
|
+
};
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
module.exports = { create: create };
|
|
@@ -27,15 +27,17 @@
|
|
|
27
27
|
* delete(key) → boolean (true if deleted, false if missing)
|
|
28
28
|
* list(prefix, opts?) → { items: [{ key, size, lastModified }], truncated }
|
|
29
29
|
*/
|
|
30
|
-
var localProto
|
|
31
|
-
var httpPutProto
|
|
32
|
-
var sigv4Proto
|
|
33
|
-
var sigv4BucketOps
|
|
34
|
-
var gcsProto
|
|
35
|
-
var
|
|
36
|
-
var
|
|
37
|
-
var
|
|
38
|
-
var
|
|
30
|
+
var localProto = require("./local");
|
|
31
|
+
var httpPutProto = require("./http-put");
|
|
32
|
+
var sigv4Proto = require("./sigv4");
|
|
33
|
+
var sigv4BucketOps = require("./sigv4-bucket-ops");
|
|
34
|
+
var gcsProto = require("./gcs");
|
|
35
|
+
var gcsBucketOps = require("./gcs-bucket-ops");
|
|
36
|
+
var azureBlobProto = require("./azure-blob");
|
|
37
|
+
var azureBlobBucketOps = require("./azure-blob-bucket-ops");
|
|
38
|
+
var retryHelper = require("./retry");
|
|
39
|
+
var protocolDispatcher = require("../protocol-dispatcher");
|
|
40
|
+
var { ObjectStoreError } = require("../framework-error");
|
|
39
41
|
|
|
40
42
|
// All currently advertised protocols are bundled. The dispatcher's
|
|
41
43
|
// `deferred` slot is the hook for adding deferred ones later.
|
|
@@ -134,13 +136,62 @@ function buildBackend(config) {
|
|
|
134
136
|
};
|
|
135
137
|
}
|
|
136
138
|
|
|
139
|
+
// ---- Bucket-level ops dispatcher ----
|
|
140
|
+
//
|
|
141
|
+
// Bucket lifecycle (create / delete / list) + lifecycle / CORS rules
|
|
142
|
+
// are service-scoped, not bucket-scoped — `b.objectStore.bucketOps`
|
|
143
|
+
// resolves a per-cloud factory by protocol. Each cloud's ops shape
|
|
144
|
+
// differs (S3 sigv4 vs Azure Shared Key vs GCS OAuth) so the
|
|
145
|
+
// per-protocol modules each own their own validation, signing, and
|
|
146
|
+
// REST-API translation; this dispatcher just routes.
|
|
147
|
+
//
|
|
148
|
+
// Operator entry point — unchanged from v0.6.x:
|
|
149
|
+
//
|
|
150
|
+
// var ops = b.objectStore.bucketOps.create({
|
|
151
|
+
// protocol: 'sigv4' | 'azure-blob' | 'gcs',
|
|
152
|
+
// // ... protocol-specific creds ...
|
|
153
|
+
// });
|
|
154
|
+
//
|
|
155
|
+
// Each returned ops object exposes (where supported per-cloud):
|
|
156
|
+
// ops.create(name, opts?)
|
|
157
|
+
// ops.delete(name)
|
|
158
|
+
// ops.list(opts?)
|
|
159
|
+
// ops.setLifecycle(name, rules)
|
|
160
|
+
// ops.setCorsRules(name, rules) // sigv4 + gcs accept (name, rules);
|
|
161
|
+
// // azure-blob accepts (rules) — its
|
|
162
|
+
// // CORS is account-level.
|
|
163
|
+
var BUCKET_OPS_BY_PROTOCOL = {
|
|
164
|
+
"sigv4": sigv4BucketOps,
|
|
165
|
+
"gcs": gcsBucketOps,
|
|
166
|
+
"azure-blob": azureBlobBucketOps,
|
|
167
|
+
};
|
|
168
|
+
function _bucketOpsCreate(config) {
|
|
169
|
+
if (!config) {
|
|
170
|
+
throw _err("BAD_OPT",
|
|
171
|
+
"objectStore.bucketOps.create: config required (must include " +
|
|
172
|
+
"{ protocol })", true);
|
|
173
|
+
}
|
|
174
|
+
var protoMod = BUCKET_OPS_BY_PROTOCOL[config.protocol];
|
|
175
|
+
if (!protoMod) {
|
|
176
|
+
throw _err("UNKNOWN_PROTOCOL",
|
|
177
|
+
"objectStore.bucketOps.create: unknown protocol '" + config.protocol +
|
|
178
|
+
"' (supported: " + Object.keys(BUCKET_OPS_BY_PROTOCOL).join(", ") +
|
|
179
|
+
")", true);
|
|
180
|
+
}
|
|
181
|
+
return protoMod.create(config);
|
|
182
|
+
}
|
|
183
|
+
|
|
137
184
|
module.exports = {
|
|
138
185
|
buildBackend: buildBackend,
|
|
139
186
|
PROTOCOLS: dispatcher.protocols,
|
|
140
187
|
DEFERRED_PROTOCOLS: dispatcher.deferred,
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
188
|
+
bucketOps: {
|
|
189
|
+
create: _bucketOpsCreate,
|
|
190
|
+
PROTOCOLS: Object.keys(BUCKET_OPS_BY_PROTOCOL),
|
|
191
|
+
// Per-protocol modules exposed for advanced operators wiring
|
|
192
|
+
// their own dispatch / testing harnesses against a specific cloud.
|
|
193
|
+
sigv4: sigv4BucketOps,
|
|
194
|
+
gcs: gcsBucketOps,
|
|
195
|
+
"azure-blob": azureBlobBucketOps,
|
|
196
|
+
},
|
|
146
197
|
};
|
package/package.json
CHANGED
package/sbom.cyclonedx.json
CHANGED
|
@@ -2,10 +2,10 @@
|
|
|
2
2
|
"$schema": "http://cyclonedx.org/schema/bom-1.5.schema.json",
|
|
3
3
|
"bomFormat": "CycloneDX",
|
|
4
4
|
"specVersion": "1.5",
|
|
5
|
-
"serialNumber": "urn:uuid:
|
|
5
|
+
"serialNumber": "urn:uuid:a13cf9c3-cc15-4fc1-bff7-03071923ae8d",
|
|
6
6
|
"version": 1,
|
|
7
7
|
"metadata": {
|
|
8
|
-
"timestamp": "2026-05-
|
|
8
|
+
"timestamp": "2026-05-02T21:50:09.461Z",
|
|
9
9
|
"lifecycles": [
|
|
10
10
|
{
|
|
11
11
|
"phase": "build"
|
|
@@ -19,14 +19,14 @@
|
|
|
19
19
|
}
|
|
20
20
|
],
|
|
21
21
|
"component": {
|
|
22
|
-
"bom-ref": "@blamejs/core@0.6.
|
|
22
|
+
"bom-ref": "@blamejs/core@0.6.37",
|
|
23
23
|
"type": "library",
|
|
24
24
|
"name": "blamejs",
|
|
25
|
-
"version": "0.6.
|
|
25
|
+
"version": "0.6.37",
|
|
26
26
|
"scope": "required",
|
|
27
27
|
"author": "blamejs contributors",
|
|
28
28
|
"description": "The Node framework that owns its stack.",
|
|
29
|
-
"purl": "pkg:npm/%40blamejs/core@0.6.
|
|
29
|
+
"purl": "pkg:npm/%40blamejs/core@0.6.37",
|
|
30
30
|
"properties": [],
|
|
31
31
|
"externalReferences": [
|
|
32
32
|
{
|
|
@@ -54,7 +54,7 @@
|
|
|
54
54
|
"components": [],
|
|
55
55
|
"dependencies": [
|
|
56
56
|
{
|
|
57
|
-
"ref": "@blamejs/core@0.6.
|
|
57
|
+
"ref": "@blamejs/core@0.6.37",
|
|
58
58
|
"dependsOn": []
|
|
59
59
|
}
|
|
60
60
|
]
|