@blamejs/core 0.6.36 → 0.6.58

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.
@@ -424,10 +424,50 @@ function algorithmEnvelope() {
424
424
  };
425
425
  }
426
426
 
427
+ // Generate a signed X.509 CRL (RFC 5280) covering every revoked
428
+ // serial number. The vendored peculiar/x509 library exposes
429
+ // X509CrlGenerator.create which builds the TBSCertList, populates
430
+ // the entries, and signs with the CA private key — same signature
431
+ // algorithm the CA itself was issued under (auto-detected via
432
+ // _selectAlgorithm + cached on first issuance).
433
+ async function generateCrl(opts) {
434
+ opts = opts || {};
435
+ if (!opts.caCertPem || !opts.caKeyPem) {
436
+ throw new MtlsEngineError("mtls-engine/missing-arg",
437
+ "generateCrl requires { caCertPem, caKeyPem, revocations, thisUpdate, nextUpdate }");
438
+ }
439
+ var revocations = Array.isArray(opts.revocations) ? opts.revocations : [];
440
+ var alg = await _selectAlgorithm();
441
+ CA_KEY_ALG = alg.keyAlg; CA_SIG_ALG = alg.sigAlg;
442
+
443
+ var caKey = await _importPemPrivateKey(opts.caKeyPem, CA_KEY_ALG, ["sign"]);
444
+ var caCert = _parseCertPem(opts.caCertPem);
445
+
446
+ // X509CrlEntry expects { serialNumber: hex, revocationDate, reason }.
447
+ var entries = revocations.map(function (r) {
448
+ return {
449
+ serialNumber: r.serialNumber,
450
+ revocationDate: new Date(r.revokedAt || Date.now()),
451
+ reason: (typeof r.reasonCode === "number") ? r.reasonCode : 0,
452
+ };
453
+ });
454
+
455
+ var crl = await x509.X509CrlGenerator.create({
456
+ issuer: caCert.subject,
457
+ thisUpdate: opts.thisUpdate || new Date(),
458
+ nextUpdate: opts.nextUpdate,
459
+ entries: entries,
460
+ signingAlgorithm: CA_SIG_ALG,
461
+ signingKey: caKey,
462
+ });
463
+ return crl.toString("pem");
464
+ }
465
+
427
466
  module.exports = {
428
467
  generateCa: generateCa,
429
468
  signClientCert: signClientCert,
430
469
  packageP12: packageP12,
470
+ generateCrl: generateCrl,
431
471
  algorithmEnvelope: algorithmEnvelope,
432
472
  MtlsEngineError: MtlsEngineError,
433
473
  };
@@ -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, "&amp;")
95
+ .replace(/</g, "&lt;")
96
+ .replace(/>/g, "&gt;")
97
+ .replace(/"/g, "&quot;")
98
+ .replace(/'/g, "&apos;");
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 };