@blamejs/core 0.7.18 → 0.7.19

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (167) hide show
  1. package/CHANGELOG.md +425 -423
  2. package/README.md +150 -150
  3. package/bin/blamejs.js +0 -0
  4. package/index.js +310 -308
  5. package/lib/api-key.js +660 -660
  6. package/lib/api-snapshot.js +338 -338
  7. package/lib/app-shutdown.js +385 -385
  8. package/lib/app.js +365 -365
  9. package/lib/archive.js +250 -250
  10. package/lib/atomic-file.js +544 -544
  11. package/lib/audit-chain.js +177 -177
  12. package/lib/audit-sign.js +344 -344
  13. package/lib/audit-tools.js +677 -677
  14. package/lib/audit.js +766 -766
  15. package/lib/auth/jwt-external.js +365 -0
  16. package/lib/auth/jwt.js +337 -311
  17. package/lib/auth/lockout.js +436 -436
  18. package/lib/auth/oauth.js +721 -721
  19. package/lib/auth/passkey.js +181 -181
  20. package/lib/auth/password.js +628 -594
  21. package/lib/backup/bundle.js +217 -217
  22. package/lib/backup/crypto.js +176 -176
  23. package/lib/backup/index.js +515 -515
  24. package/lib/backup/manifest.js +282 -282
  25. package/lib/break-glass.js +1338 -1338
  26. package/lib/bundler.js +441 -441
  27. package/lib/cache-redis.js +256 -256
  28. package/lib/cache.js +1206 -1206
  29. package/lib/canonical-json.js +115 -115
  30. package/lib/chain-writer.js +234 -234
  31. package/lib/cli-helpers.js +206 -206
  32. package/lib/cli.js +2334 -2334
  33. package/lib/cluster-provider-db.js +317 -317
  34. package/lib/cluster-storage.js +226 -226
  35. package/lib/cluster.js +703 -703
  36. package/lib/config-drift.js +301 -301
  37. package/lib/consent.js +222 -222
  38. package/lib/constants.js +191 -191
  39. package/lib/cookies.js +315 -315
  40. package/lib/credential-hash.js +322 -322
  41. package/lib/crypto.js +266 -266
  42. package/lib/csv.js +275 -275
  43. package/lib/db-declare-row-policy.js +267 -267
  44. package/lib/db-declare-view.js +420 -420
  45. package/lib/db-query.js +406 -406
  46. package/lib/db-schema.js +319 -319
  47. package/lib/db.js +1288 -1288
  48. package/lib/deprecate.js +222 -222
  49. package/lib/dev.js +335 -335
  50. package/lib/dual-control.js +473 -473
  51. package/lib/error-page.js +420 -420
  52. package/lib/external-db-migrate.js +441 -441
  53. package/lib/external-db.js +1061 -1061
  54. package/lib/file-type.js +273 -273
  55. package/lib/forms.js +422 -422
  56. package/lib/framework-error.js +293 -293
  57. package/lib/framework-schema.js +717 -717
  58. package/lib/handlers.js +350 -350
  59. package/lib/http-client-cookie-jar.js +508 -508
  60. package/lib/http-client.js +1195 -1195
  61. package/lib/i18n.js +878 -878
  62. package/lib/jobs.js +185 -185
  63. package/lib/log-stream-cloudwatch.js +369 -369
  64. package/lib/log-stream-local.js +146 -146
  65. package/lib/log-stream-otlp-grpc.js +410 -410
  66. package/lib/log-stream-otlp.js +286 -286
  67. package/lib/log-stream-syslog.js +302 -302
  68. package/lib/log-stream-webhook.js +199 -199
  69. package/lib/log-stream.js +330 -330
  70. package/lib/log.js +500 -500
  71. package/lib/mail-bounce.js +528 -528
  72. package/lib/mail-dkim.js +369 -369
  73. package/lib/mail.js +981 -981
  74. package/lib/metrics.js +683 -683
  75. package/lib/middleware/api-encrypt.js +936 -936
  76. package/lib/middleware/attach-user.js +157 -157
  77. package/lib/middleware/bearer-auth.js +152 -0
  78. package/lib/middleware/body-parser.js +1170 -1170
  79. package/lib/middleware/bot-guard.js +178 -178
  80. package/lib/middleware/compression.js +452 -452
  81. package/lib/middleware/cors.js +314 -314
  82. package/lib/middleware/csp-nonce.js +348 -348
  83. package/lib/middleware/csrf-protect.js +316 -316
  84. package/lib/middleware/db-role-for.js +264 -264
  85. package/lib/middleware/health.js +392 -392
  86. package/lib/middleware/index.js +82 -79
  87. package/lib/middleware/rate-limit.js +358 -358
  88. package/lib/middleware/request-id.js +61 -61
  89. package/lib/middleware/request-log.js +168 -168
  90. package/lib/middleware/require-auth.js +104 -104
  91. package/lib/middleware/security-headers.js +116 -116
  92. package/lib/middleware/sse.js +166 -166
  93. package/lib/migrations.js +383 -383
  94. package/lib/mtls-ca.js +518 -518
  95. package/lib/mtls-engine-default.js +481 -481
  96. package/lib/network-dns.js +632 -632
  97. package/lib/network-heartbeat.js +290 -290
  98. package/lib/network-nts.js +574 -574
  99. package/lib/network-proxy.js +265 -265
  100. package/lib/network-tls.js +328 -328
  101. package/lib/network.js +233 -233
  102. package/lib/notify.js +612 -612
  103. package/lib/ntp-check.js +229 -229
  104. package/lib/numeric-bounds.js +111 -111
  105. package/lib/object-store/azure-blob-bucket-ops.js +349 -349
  106. package/lib/object-store/azure-blob.js +488 -488
  107. package/lib/object-store/gcs-bucket-ops.js +351 -351
  108. package/lib/object-store/gcs.js +519 -519
  109. package/lib/object-store/http-put.js +153 -153
  110. package/lib/object-store/index.js +197 -197
  111. package/lib/object-store/sigv4-bucket-ops.js +1092 -1092
  112. package/lib/object-store/sigv4.js +903 -903
  113. package/lib/observability.js +151 -151
  114. package/lib/otel-export.js +269 -269
  115. package/lib/pagination.js +464 -464
  116. package/lib/parsers/index.js +80 -80
  117. package/lib/parsers/safe-env.js +642 -642
  118. package/lib/parsers/safe-ini.js +292 -292
  119. package/lib/parsers/safe-toml.js +784 -784
  120. package/lib/parsers/safe-xml.js +390 -390
  121. package/lib/parsers/safe-yaml.js +1015 -1015
  122. package/lib/permissions.js +708 -708
  123. package/lib/pqc-agent.js +87 -87
  124. package/lib/pqc-gate.js +279 -279
  125. package/lib/protobuf-encoder.js +190 -190
  126. package/lib/protocol-dispatcher.js +161 -161
  127. package/lib/pubsub-redis.js +167 -167
  128. package/lib/pubsub.js +429 -429
  129. package/lib/queue-local.js +476 -476
  130. package/lib/queue-redis.js +745 -745
  131. package/lib/queue-sqs.js +319 -319
  132. package/lib/queue.js +695 -695
  133. package/lib/redis-client.js +519 -519
  134. package/lib/request-helpers.js +340 -340
  135. package/lib/restore-bundle.js +237 -237
  136. package/lib/restore-rollback.js +259 -259
  137. package/lib/restore.js +409 -409
  138. package/lib/retry.js +376 -376
  139. package/lib/router.js +748 -748
  140. package/lib/safe-async.js +735 -735
  141. package/lib/safe-buffer.js +237 -237
  142. package/lib/safe-json.js +541 -541
  143. package/lib/safe-schema.js +1266 -1266
  144. package/lib/safe-url.js +159 -159
  145. package/lib/scheduler.js +706 -706
  146. package/lib/security-assert.js +373 -373
  147. package/lib/seeders.js +618 -618
  148. package/lib/session.js +535 -478
  149. package/lib/slug.js +269 -269
  150. package/lib/ssrf-guard.js +401 -401
  151. package/lib/storage.js +471 -471
  152. package/lib/subject.js +281 -281
  153. package/lib/template.js +791 -791
  154. package/lib/testing.js +798 -798
  155. package/lib/time.js +310 -310
  156. package/lib/totp.js +302 -302
  157. package/lib/tracing.js +494 -494
  158. package/lib/uuid.js +132 -132
  159. package/lib/validate-opts.js +340 -340
  160. package/lib/vault/index.js +308 -308
  161. package/lib/vault/rotate.js +784 -784
  162. package/lib/vault/wrap.js +296 -296
  163. package/lib/vendor/noble-ciphers.cjs +9 -9
  164. package/lib/webhook.js +595 -595
  165. package/lib/websocket.js +1048 -1048
  166. package/package.json +77 -77
  167. package/sbom.cyclonedx.json +7 -7
@@ -1,519 +1,519 @@
1
- "use strict";
2
- /**
3
- * Google Cloud Storage (GCS) protocol adapter — native JSON API.
4
- *
5
- * Auth: service-account JSON (RSA-SHA256 signed JWT exchanged for an
6
- * OAuth2 access token; tokens cached until ~5 min before expiry).
7
- *
8
- * Endpoint: https://storage.googleapis.com (override via config.endpoint
9
- * for emulators / private endpoints).
10
- *
11
- * Config:
12
- * {
13
- * bucket: 'my-bucket' // required
14
- * serviceAccount: { client_email, private_key, ... } // OR
15
- * serviceAccountFile: '/path/to/sa.json' // OR
16
- * scope: 'https://www.googleapis.com/auth/devstorage.read_write'
17
- * endpoint: 'https://storage.googleapis.com'
18
- * timeoutMs: C.TIME.seconds(30)
19
- * }
20
- *
21
- * Reference:
22
- * https://cloud.google.com/storage/docs/json_api/v1
23
- * https://developers.google.com/identity/protocols/oauth2/service-account
24
- */
25
- var fs = require("fs");
26
- var nodeCrypto = require("crypto");
27
- var { Readable } = require("stream");
28
- var safeJson = require("../safe-json");
29
- var C = require("../constants");
30
- var nb = require("../numeric-bounds");
31
- var requestHelpers = require("../request-helpers");
32
- var { ObjectStoreError } = require("../framework-error");
33
- var safeUrl = require("../safe-url");
34
- var sharedRequest = require("./http-request");
35
- var authHeader = require("../auth-header");
36
- var sigv4 = require("./sigv4");
37
-
38
- // Internal URL builder — endpoint + path string from validated config.
39
- // Routes through safeUrl.parse so the protocol allowlist + length cap
40
- // apply uniformly. Cap is generous since presigned URLs can carry many
41
- // query params.
42
- function _internalUrl(input, allowedProtocols) {
43
- return safeUrl.parse(input, {
44
- allowedProtocols: allowedProtocols || safeUrl.ALLOW_HTTP_TLS,
45
- errorClass: ObjectStoreError,
46
- maxUrlLength: C.BYTES.kib(32),
47
- });
48
- }
49
-
50
- // V4 query-string presigning. GCS uses the same canonical-request
51
- // shape as AWS SigV4, differing only in:
52
- // - algorithm: GOOG4-RSA-SHA256 (RSA service-account signing)
53
- // - service: storage
54
- // - region: auto (single global region for V4 presigning)
55
- // - credential scope: {date}/{region}/storage/goog4_request
56
- // - param prefix: X-Goog-* instead of X-Amz-*
57
- // - credential value: client_email instead of accessKeyId
58
- var GCS_V4_ALGORITHM = "GOOG4-RSA-SHA256";
59
- var GCS_V4_SERVICE = "storage";
60
- var GCS_V4_REGION = "auto";
61
-
62
- // Same expiry bounds as SigV4 — V4 presigning shares the spec's 7-day cap.
63
- var PRESIGN_DEFAULT_EXPIRES_SECONDS = C.TIME.minutes(15) / C.TIME.seconds(1);
64
- var PRESIGN_MAX_EXPIRES_SECONDS = C.TIME.days(7) / C.TIME.seconds(1);
65
- var PRESIGN_MIN_EXPIRES_SECONDS = 1;
66
-
67
- var SERVICE_ACCOUNT_SCHEMA = {
68
- type: "object",
69
- required: ["client_email", "private_key"],
70
- properties: {
71
- client_email: { type: "string" },
72
- private_key: { type: "string" },
73
- token_uri: { type: "string" },
74
- project_id: { type: "string" },
75
- },
76
- };
77
-
78
- var DEFAULT_ENDPOINT = "https://storage.googleapis.com";
79
- var TOKEN_ENDPOINT = "https://oauth2.googleapis.com/token";
80
- var DEFAULT_SCOPE = "https://www.googleapis.com/auth/devstorage.read_write";
81
- var TOKEN_REFRESH_BUFFER = C.TIME.minutes(5); // refresh 5 min before expiry
82
-
83
- var _err = ObjectStoreError.factory;
84
-
85
- // ---- Generic HTTP helper (separate from sigv4's; no signing here) ----
86
-
87
- var _httpRequest = sharedRequest;
88
-
89
- // ---- JWT signing for service-account auth ----
90
-
91
- function _base64UrlEncode(buf) {
92
- return Buffer.from(buf).toString("base64")
93
- .replace(/=+$/g, "")
94
- .replace(/\+/g, "-")
95
- .replace(/\//g, "_");
96
- }
97
-
98
- function _signJwt(serviceAccount, scope, audience) {
99
- var nowSec = Math.floor(Date.now() / C.TIME.seconds(1));
100
- var header = { alg: "RS256", typ: "JWT" };
101
- var claim = {
102
- iss: serviceAccount.client_email,
103
- scope: scope,
104
- aud: audience || TOKEN_ENDPOINT,
105
- iat: nowSec,
106
- exp: nowSec + (C.TIME.hours(1) / C.TIME.seconds(1)),
107
- };
108
- var headerB64 = _base64UrlEncode(JSON.stringify(header));
109
- var claimB64 = _base64UrlEncode(JSON.stringify(claim));
110
- var signingInput = headerB64 + "." + claimB64;
111
-
112
- var signer = nodeCrypto.createSign("RSA-SHA256");
113
- signer.update(signingInput);
114
- signer.end();
115
- var signature = signer.sign(serviceAccount.private_key);
116
- return signingInput + "." + _base64UrlEncode(signature);
117
- }
118
-
119
- // ---- Public adapter factory ----
120
-
121
- function create(config) {
122
- if (!config) throw new Error("gcs protocol requires config");
123
- if (!config.bucket) throw new Error("gcs: bucket is required");
124
-
125
- var serviceAccount = config.serviceAccount;
126
- if (!serviceAccount && config.serviceAccountFile) {
127
- try {
128
- serviceAccount = safeJson.parse(fs.readFileSync(config.serviceAccountFile), { schema: SERVICE_ACCOUNT_SCHEMA });
129
- } catch (e) {
130
- throw new Error("gcs: failed to read serviceAccountFile '" + config.serviceAccountFile + "': " + e.message);
131
- }
132
- } else if (serviceAccount && (!serviceAccount.client_email || !serviceAccount.private_key)) {
133
- throw new Error("gcs: serviceAccount with { client_email, private_key } is required (or serviceAccountFile pointing to one)");
134
- }
135
- if (!serviceAccount) {
136
- throw new Error("gcs: serviceAccount with { client_email, private_key } is required (or serviceAccountFile pointing to one)");
137
- }
138
-
139
- var endpoint = config.endpoint || DEFAULT_ENDPOINT;
140
- if (endpoint.endsWith("/")) endpoint = endpoint.slice(0, -1);
141
- var tokenEndpoint = config.tokenEndpoint || TOKEN_ENDPOINT;
142
- var bucket = config.bucket;
143
- var scope = config.scope || DEFAULT_SCOPE;
144
- var timeoutMs = config.timeoutMs;
145
- // HTTPS-only by default — google APIs are always HTTPS. Operators with
146
- // an emulator / private fake-GCS endpoint opt in via config.allowedProtocols.
147
- var allowedProtocols = config.allowedProtocols || safeUrl.ALLOW_HTTP_TLS;
148
- var allowInternal = config.allowInternal != null ? config.allowInternal : null;
149
- safeUrl.parse(endpoint, { allowedProtocols: allowedProtocols, errorClass: ObjectStoreError });
150
- safeUrl.parse(tokenEndpoint, { allowedProtocols: allowedProtocols, errorClass: ObjectStoreError });
151
- var reqOpts = { timeoutMs: timeoutMs, allowedProtocols: allowedProtocols };
152
- if (allowInternal !== null) reqOpts.allowInternal = allowInternal;
153
-
154
- // ---- Token cache ----
155
- var cachedToken = null; // { accessToken, expiresAt }
156
-
157
- async function _ensureToken() {
158
- if (cachedToken && Date.now() < cachedToken.expiresAt - TOKEN_REFRESH_BUFFER) {
159
- return cachedToken.accessToken;
160
- }
161
- var assertion = _signJwt(serviceAccount, scope, tokenEndpoint);
162
- var bodyStr = "grant_type=" + encodeURIComponent("urn:ietf:params:oauth:grant-type:jwt-bearer") +
163
- "&assertion=" + encodeURIComponent(assertion);
164
- var bodyBuf = Buffer.from(bodyStr, "utf8");
165
- var res = await _httpRequest(
166
- "POST",
167
- _internalUrl(tokenEndpoint, allowedProtocols),
168
- {
169
- "Content-Type": "application/x-www-form-urlencoded",
170
- "Content-Length": String(bodyBuf.length),
171
- },
172
- bodyBuf,
173
- reqOpts
174
- );
175
- var tokenResp = safeJson.parse(res.body);
176
- if (!tokenResp.access_token) {
177
- throw _err("AUTH_FAILED", "GCS token endpoint returned no access_token: " + res.body.toString("utf8"), true);
178
- }
179
- var expiresInMs = C.TIME.seconds(tokenResp.expires_in || 3600);
180
- cachedToken = {
181
- accessToken: tokenResp.access_token,
182
- expiresAt: Date.now() + expiresInMs,
183
- };
184
- return cachedToken.accessToken;
185
- }
186
-
187
- function _objectUrl(key, params) {
188
- var u = _internalUrl(endpoint + "/storage/v1/b/" + encodeURIComponent(bucket) +
189
- "/o/" + encodeURIComponent(key), allowedProtocols);
190
- if (params) {
191
- Object.keys(params).forEach(function (k) { u.searchParams.set(k, params[k]); });
192
- }
193
- return u;
194
- }
195
-
196
- function _uploadUrl(key) {
197
- var u = _internalUrl(endpoint + "/upload/storage/v1/b/" + encodeURIComponent(bucket) + "/o", allowedProtocols);
198
- u.searchParams.set("uploadType", "media");
199
- u.searchParams.set("name", key);
200
- return u;
201
- }
202
-
203
- function _listUrl(prefix, opts) {
204
- var u = _internalUrl(endpoint + "/storage/v1/b/" + encodeURIComponent(bucket) + "/o", allowedProtocols);
205
- if (prefix) u.searchParams.set("prefix", prefix);
206
- if (opts && opts.maxResults) u.searchParams.set("maxResults", String(opts.maxResults));
207
- if (opts && opts.pageToken) u.searchParams.set("pageToken", opts.pageToken);
208
- return u;
209
- }
210
-
211
- // ---- Operations ----
212
-
213
- async function put(key, body, opts) {
214
- var token = await _ensureToken();
215
- var url = _uploadUrl(key);
216
- var buf = Buffer.isBuffer(body) ? body : Buffer.from(typeof body === "string" ? body : "", "utf8");
217
- var contentType = (opts && opts.contentType) || "application/octet-stream";
218
- var res = await _httpRequest("POST", url, Object.assign(
219
- authHeader.bearer(token),
220
- { "Content-Type": contentType,
221
- "Content-Length": String(buf.length) }
222
- ), buf, reqOpts);
223
- var meta = safeJson.parse(res.body);
224
- return { size: parseInt(meta.size || buf.length, 10), etag: meta.etag };
225
- }
226
-
227
- // get(key, opts?) — opts forwarded to GCS as conditional / range
228
- // headers (Range, If-None-Match, If-Match, If-Modified-Since,
229
- // If-Unmodified-Since). Returns the body buffer for backwards compat;
230
- // operators wanting full status + response headers call getResponse().
231
- async function get(key, opts) {
232
- var r = await getResponse(key, opts);
233
- return r.body;
234
- }
235
-
236
- function getStream(key, opts) {
237
- return Readable.from(get(key, opts));
238
- }
239
-
240
- async function getResponse(key, opts) {
241
- opts = opts || {};
242
- var token = await _ensureToken();
243
- var url = _objectUrl(key, { alt: "media" });
244
- var headers = authHeader.bearer(token);
245
- if (opts.range) {
246
- headers["Range"] = "bytes=" + opts.range.start + "-" + opts.range.end;
247
- }
248
- if (opts.ifNoneMatch) headers["If-None-Match"] = opts.ifNoneMatch;
249
- if (opts.ifMatch) headers["If-Match"] = opts.ifMatch;
250
- if (opts.ifModifiedSince) headers["If-Modified-Since"] = opts.ifModifiedSince;
251
- if (opts.ifUnmodifiedSince) headers["If-Unmodified-Since"] = opts.ifUnmodifiedSince;
252
- try {
253
- var res = await _httpRequest("GET", url, headers, null, reqOpts);
254
- return {
255
- statusCode: res.statusCode,
256
- body: res.body,
257
- etag: res.headers && res.headers.etag,
258
- lastModified: res.headers && res.headers["last-modified"]
259
- ? Date.parse(res.headers["last-modified"]) : null,
260
- contentRange: res.headers && res.headers["content-range"] || null,
261
- size: res.headers && res.headers["content-length"]
262
- ? parseInt(res.headers["content-length"], 10) : null,
263
- contentType: res.headers && res.headers["content-type"] || null,
264
- };
265
- } catch (err) {
266
- if (err && err.statusCode === requestHelpers.HTTP_STATUS.NOT_MODIFIED) {
267
- return {
268
- statusCode: requestHelpers.HTTP_STATUS.NOT_MODIFIED,
269
- body: null, etag: null, lastModified: null,
270
- };
271
- }
272
- throw err;
273
- }
274
- }
275
-
276
- async function head(key) {
277
- var token = await _ensureToken();
278
- var url = _objectUrl(key);
279
- var res = await _httpRequest("GET", url, authHeader.bearer(token), null, reqOpts);
280
- var meta = safeJson.parse(res.body);
281
- return {
282
- size: parseInt(meta.size, 10),
283
- etag: meta.etag,
284
- lastModified: meta.updated ? Date.parse(meta.updated) : null,
285
- };
286
- }
287
-
288
- async function deleteKey(key) {
289
- var token = await _ensureToken();
290
- var url = _objectUrl(key);
291
- try {
292
- await _httpRequest("DELETE", url, authHeader.bearer(token), null, reqOpts);
293
- return true;
294
- } catch (e) {
295
- if (e.statusCode === 404) return false;
296
- throw e;
297
- }
298
- }
299
-
300
- async function list(prefix, opts) {
301
- opts = opts || {};
302
- var token = await _ensureToken();
303
- var url = _listUrl(prefix, { maxResults: opts.maxResults, pageToken: opts.continuationToken });
304
- var res = await _httpRequest("GET", url, authHeader.bearer(token), null, reqOpts);
305
- var listResp = safeJson.parse(res.body);
306
- var items = (listResp.items || []).map(function (item) {
307
- return {
308
- key: item.name,
309
- size: parseInt(item.size, 10),
310
- lastModified: item.updated ? Date.parse(item.updated) : null,
311
- };
312
- });
313
- return {
314
- items: items,
315
- truncated: !!listResp.nextPageToken,
316
- continuationToken: listResp.nextPageToken || null,
317
- };
318
- }
319
-
320
- function _v4Presign(method, opts) {
321
- opts = opts || {};
322
- if (!opts.key || typeof opts.key !== "string") {
323
- throw _err("INVALID_KEY", "presigned URL: key is required", true);
324
- }
325
- if (opts.key.indexOf("\0") !== -1) {
326
- throw _err("INVALID_KEY", "null byte in key", true);
327
- }
328
- var expiresIn = opts.expiresIn != null ? opts.expiresIn : PRESIGN_DEFAULT_EXPIRES_SECONDS;
329
- if (typeof expiresIn !== "number" ||
330
- expiresIn < PRESIGN_MIN_EXPIRES_SECONDS ||
331
- expiresIn > PRESIGN_MAX_EXPIRES_SECONDS) {
332
- throw _err("INVALID_EXPIRES",
333
- "presigned URL: expiresIn must be a number of seconds between " +
334
- PRESIGN_MIN_EXPIRES_SECONDS + " and " + PRESIGN_MAX_EXPIRES_SECONDS +
335
- " (7 days, V4 hard cap)", true);
336
- }
337
-
338
- // V4 presigned URLs target the XML API path-style endpoint
339
- // (storage.googleapis.com/{bucket}/{key}), not the JSON API used
340
- // for the in-process put/get methods. The XML endpoint is what
341
- // honors the V4 signature.
342
- var encodedKey = opts.key.split("/")
343
- .map(function (s) { return sigv4.awsUriEncode(s, true); })
344
- .join("/");
345
- var url = _internalUrl(endpoint + "/" + encodeURIComponent(bucket) + "/" + encodedKey, allowedProtocols);
346
-
347
- var date = opts.date || new Date();
348
- // Reuse SigV4's date formatters — the wire format is identical.
349
- var amzDate = sigv4.formatAmzDate(date);
350
- var dateStamp = sigv4.formatDateStamp(date);
351
- var credentialScope = dateStamp + "/" + GCS_V4_REGION + "/" +
352
- GCS_V4_SERVICE + "/goog4_request";
353
-
354
- var headers = { host: url.host };
355
- if (opts.contentType) headers["content-type"] = opts.contentType;
356
- // GCS V4 SignedHeaders: lowercase, semicolon-joined, AWS-spec order.
357
- var signedHeaderKeys = [];
358
- for (var hk in headers) signedHeaderKeys.push(hk);
359
- signedHeaderKeys.sort();
360
- var signedHeadersStr = signedHeaderKeys.join(";");
361
-
362
- url.searchParams.set("X-Goog-Algorithm", GCS_V4_ALGORITHM);
363
- url.searchParams.set("X-Goog-Credential", serviceAccount.client_email + "/" + credentialScope);
364
- url.searchParams.set("X-Goog-Date", amzDate);
365
- url.searchParams.set("X-Goog-Expires", String(expiresIn));
366
- url.searchParams.set("X-Goog-SignedHeaders", signedHeadersStr);
367
-
368
- // Build the canonical request — identical shape to SigV4. The
369
- // sigv4 export gives us the formatter so this stays in lockstep
370
- // with the AWS implementation.
371
- var canon = sigv4.canonicalRequest(method, url, headers, "UNSIGNED-PAYLOAD");
372
- var stringToSign = [
373
- GCS_V4_ALGORITHM,
374
- amzDate,
375
- credentialScope,
376
- sigv4.sha256Hex(canon),
377
- ].join("\n");
378
-
379
- // GCS V4 signs the stringToSign with the service-account's RSA
380
- // private key (RSA-SHA256). Hex-encoded signature goes back into
381
- // the URL.
382
- var signer = nodeCrypto.createSign("RSA-SHA256");
383
- signer.update(stringToSign);
384
- signer.end();
385
- var signature = signer.sign(serviceAccount.private_key).toString("hex");
386
-
387
- url.searchParams.set("X-Goog-Signature", signature);
388
-
389
- var clientHeaders = {};
390
- if (opts.contentType) clientHeaders["Content-Type"] = opts.contentType;
391
-
392
- return {
393
- url: url.toString(),
394
- method: method,
395
- headers: clientHeaders,
396
- expiresAt: date.getTime() + C.TIME.seconds(expiresIn),
397
- };
398
- }
399
-
400
- function presignedUploadUrl(opts) { return _v4Presign("PUT", opts); }
401
- function presignedDownloadUrl(opts) { return _v4Presign("GET", opts); }
402
-
403
- // GCS V4 POST policy presigning. Same shape as SigV4 POST policy
404
- // (operator-uploaded multipart/form-data with policy + signature
405
- // fields), but signed with the service account's RSA private key
406
- // instead of an HMAC chain. The content-length-range condition is
407
- // server-side enforced by GCS — clients sending bodies outside the
408
- // declared range get a 403 from the bucket itself.
409
- function presignedUploadPolicy(opts) {
410
- opts = opts || {};
411
- if (!opts.key || typeof opts.key !== "string") {
412
- throw _err("INVALID_KEY", "presignedUploadPolicy: key is required", true);
413
- }
414
- if (opts.key.indexOf("\0") !== -1) {
415
- throw _err("INVALID_KEY", "null byte in key", true);
416
- }
417
- if (typeof opts.maxBytes !== "number" || !Number.isFinite(opts.maxBytes) ||
418
- opts.maxBytes <= 0) {
419
- throw _err("INVALID_MAX_BYTES",
420
- "presignedUploadPolicy: maxBytes (positive number of bytes) is required — " +
421
- "POST-form policy enforces body size via the content-length-range condition; " +
422
- "use presignedUploadUrl if size enforcement is not needed", true);
423
- }
424
- if (opts.minBytes !== undefined && !nb.isNonNegativeFiniteInt(opts.minBytes)) {
425
- throw _err("INVALID_MIN_BYTES",
426
- "presignedUploadPolicy: minBytes must be a non-negative finite integer; got " +
427
- nb.shape(opts.minBytes), true);
428
- }
429
- var minBytes = opts.minBytes !== undefined ? opts.minBytes : 0;
430
- var expiresIn = opts.expiresIn != null ? opts.expiresIn : PRESIGN_DEFAULT_EXPIRES_SECONDS;
431
- if (typeof expiresIn !== "number" ||
432
- expiresIn < PRESIGN_MIN_EXPIRES_SECONDS ||
433
- expiresIn > PRESIGN_MAX_EXPIRES_SECONDS) {
434
- throw _err("INVALID_EXPIRES",
435
- "presignedUploadPolicy: expiresIn must be a number of seconds between " +
436
- PRESIGN_MIN_EXPIRES_SECONDS + " and " + PRESIGN_MAX_EXPIRES_SECONDS +
437
- " (7 days, V4 hard cap)", true);
438
- }
439
-
440
- var date = opts.date || new Date();
441
- var amzDate = sigv4.formatAmzDate(date);
442
- var dateStamp = sigv4.formatDateStamp(date);
443
- var credentialScope = dateStamp + "/" + GCS_V4_REGION + "/" +
444
- GCS_V4_SERVICE + "/goog4_request";
445
- var credential = serviceAccount.client_email + "/" + credentialScope;
446
- var expirationIso = new Date(date.getTime() + C.TIME.seconds(expiresIn)).toISOString();
447
-
448
- var conditions = [
449
- { "bucket": bucket },
450
- { "key": opts.key },
451
- { "x-goog-algorithm": GCS_V4_ALGORITHM },
452
- { "x-goog-credential": credential },
453
- { "x-goog-date": amzDate },
454
- ["content-length-range", minBytes, opts.maxBytes],
455
- ];
456
- if (opts.contentType) {
457
- conditions.push({ "content-type": opts.contentType });
458
- }
459
-
460
- var policy = { expiration: expirationIso, conditions: conditions };
461
- var policyJson = JSON.stringify(policy);
462
- var policyB64 = Buffer.from(policyJson, "utf8").toString("base64");
463
-
464
- // GCS V4: signature is hex(RSA-SHA256(privateKey, policyB64)).
465
- var signer = nodeCrypto.createSign("RSA-SHA256");
466
- signer.update(policyB64);
467
- signer.end();
468
- var signature = signer.sign(serviceAccount.private_key).toString("hex");
469
-
470
- var fields = {
471
- "key": opts.key,
472
- "x-goog-algorithm": GCS_V4_ALGORITHM,
473
- "x-goog-credential": credential,
474
- "x-goog-date": amzDate,
475
- "policy": policyB64,
476
- "x-goog-signature": signature,
477
- };
478
- if (opts.contentType) fields["content-type"] = opts.contentType;
479
-
480
- var url = _internalUrl(endpoint + "/" + encodeURIComponent(bucket) + "/", allowedProtocols);
481
-
482
- return {
483
- url: url.toString(),
484
- method: "POST",
485
- fields: fields,
486
- expiresAt: date.getTime() + C.TIME.seconds(expiresIn),
487
- maxBytes: opts.maxBytes,
488
- enforcement: "content-length-range",
489
- };
490
- }
491
-
492
- return {
493
- protocol: "gcs",
494
- endpoint: endpoint,
495
- bucket: bucket,
496
- put: put,
497
- get: get,
498
- getStream: getStream,
499
- getResponse: getResponse,
500
- head: head,
501
- delete: deleteKey,
502
- list: list,
503
- presignedUploadUrl: presignedUploadUrl,
504
- presignedDownloadUrl: presignedDownloadUrl,
505
- presignedUploadPolicy: presignedUploadPolicy,
506
- // Internal accessors for tests
507
- _ensureToken: _ensureToken,
508
- _signJwt: function () { return _signJwt(serviceAccount, scope, TOKEN_ENDPOINT); },
509
- };
510
- }
511
-
512
- module.exports = {
513
- create: create,
514
- _signJwt: _signJwt,
515
- _base64UrlEncode: _base64UrlEncode,
516
- DEFAULT_ENDPOINT: DEFAULT_ENDPOINT,
517
- TOKEN_ENDPOINT: TOKEN_ENDPOINT,
518
- DEFAULT_SCOPE: DEFAULT_SCOPE,
519
- };
1
+ "use strict";
2
+ /**
3
+ * Google Cloud Storage (GCS) protocol adapter — native JSON API.
4
+ *
5
+ * Auth: service-account JSON (RSA-SHA256 signed JWT exchanged for an
6
+ * OAuth2 access token; tokens cached until ~5 min before expiry).
7
+ *
8
+ * Endpoint: https://storage.googleapis.com (override via config.endpoint
9
+ * for emulators / private endpoints).
10
+ *
11
+ * Config:
12
+ * {
13
+ * bucket: 'my-bucket' // required
14
+ * serviceAccount: { client_email, private_key, ... } // OR
15
+ * serviceAccountFile: '/path/to/sa.json' // OR
16
+ * scope: 'https://www.googleapis.com/auth/devstorage.read_write'
17
+ * endpoint: 'https://storage.googleapis.com'
18
+ * timeoutMs: C.TIME.seconds(30)
19
+ * }
20
+ *
21
+ * Reference:
22
+ * https://cloud.google.com/storage/docs/json_api/v1
23
+ * https://developers.google.com/identity/protocols/oauth2/service-account
24
+ */
25
+ var fs = require("fs");
26
+ var nodeCrypto = require("crypto");
27
+ var { Readable } = require("stream");
28
+ var safeJson = require("../safe-json");
29
+ var C = require("../constants");
30
+ var nb = require("../numeric-bounds");
31
+ var requestHelpers = require("../request-helpers");
32
+ var { ObjectStoreError } = require("../framework-error");
33
+ var safeUrl = require("../safe-url");
34
+ var sharedRequest = require("./http-request");
35
+ var authHeader = require("../auth-header");
36
+ var sigv4 = require("./sigv4");
37
+
38
+ // Internal URL builder — endpoint + path string from validated config.
39
+ // Routes through safeUrl.parse so the protocol allowlist + length cap
40
+ // apply uniformly. Cap is generous since presigned URLs can carry many
41
+ // query params.
42
+ function _internalUrl(input, allowedProtocols) {
43
+ return safeUrl.parse(input, {
44
+ allowedProtocols: allowedProtocols || safeUrl.ALLOW_HTTP_TLS,
45
+ errorClass: ObjectStoreError,
46
+ maxUrlLength: C.BYTES.kib(32),
47
+ });
48
+ }
49
+
50
+ // V4 query-string presigning. GCS uses the same canonical-request
51
+ // shape as AWS SigV4, differing only in:
52
+ // - algorithm: GOOG4-RSA-SHA256 (RSA service-account signing)
53
+ // - service: storage
54
+ // - region: auto (single global region for V4 presigning)
55
+ // - credential scope: {date}/{region}/storage/goog4_request
56
+ // - param prefix: X-Goog-* instead of X-Amz-*
57
+ // - credential value: client_email instead of accessKeyId
58
+ var GCS_V4_ALGORITHM = "GOOG4-RSA-SHA256";
59
+ var GCS_V4_SERVICE = "storage";
60
+ var GCS_V4_REGION = "auto";
61
+
62
+ // Same expiry bounds as SigV4 — V4 presigning shares the spec's 7-day cap.
63
+ var PRESIGN_DEFAULT_EXPIRES_SECONDS = C.TIME.minutes(15) / C.TIME.seconds(1);
64
+ var PRESIGN_MAX_EXPIRES_SECONDS = C.TIME.days(7) / C.TIME.seconds(1);
65
+ var PRESIGN_MIN_EXPIRES_SECONDS = 1;
66
+
67
+ var SERVICE_ACCOUNT_SCHEMA = {
68
+ type: "object",
69
+ required: ["client_email", "private_key"],
70
+ properties: {
71
+ client_email: { type: "string" },
72
+ private_key: { type: "string" },
73
+ token_uri: { type: "string" },
74
+ project_id: { type: "string" },
75
+ },
76
+ };
77
+
78
+ var DEFAULT_ENDPOINT = "https://storage.googleapis.com";
79
+ var TOKEN_ENDPOINT = "https://oauth2.googleapis.com/token";
80
+ var DEFAULT_SCOPE = "https://www.googleapis.com/auth/devstorage.read_write";
81
+ var TOKEN_REFRESH_BUFFER = C.TIME.minutes(5); // refresh 5 min before expiry
82
+
83
+ var _err = ObjectStoreError.factory;
84
+
85
+ // ---- Generic HTTP helper (separate from sigv4's; no signing here) ----
86
+
87
+ var _httpRequest = sharedRequest;
88
+
89
+ // ---- JWT signing for service-account auth ----
90
+
91
+ function _base64UrlEncode(buf) {
92
+ return Buffer.from(buf).toString("base64")
93
+ .replace(/=+$/g, "")
94
+ .replace(/\+/g, "-")
95
+ .replace(/\//g, "_");
96
+ }
97
+
98
+ function _signJwt(serviceAccount, scope, audience) {
99
+ var nowSec = Math.floor(Date.now() / C.TIME.seconds(1));
100
+ var header = { alg: "RS256", typ: "JWT" };
101
+ var claim = {
102
+ iss: serviceAccount.client_email,
103
+ scope: scope,
104
+ aud: audience || TOKEN_ENDPOINT,
105
+ iat: nowSec,
106
+ exp: nowSec + (C.TIME.hours(1) / C.TIME.seconds(1)),
107
+ };
108
+ var headerB64 = _base64UrlEncode(JSON.stringify(header));
109
+ var claimB64 = _base64UrlEncode(JSON.stringify(claim));
110
+ var signingInput = headerB64 + "." + claimB64;
111
+
112
+ var signer = nodeCrypto.createSign("RSA-SHA256");
113
+ signer.update(signingInput);
114
+ signer.end();
115
+ var signature = signer.sign(serviceAccount.private_key);
116
+ return signingInput + "." + _base64UrlEncode(signature);
117
+ }
118
+
119
+ // ---- Public adapter factory ----
120
+
121
+ function create(config) {
122
+ if (!config) throw new Error("gcs protocol requires config");
123
+ if (!config.bucket) throw new Error("gcs: bucket is required");
124
+
125
+ var serviceAccount = config.serviceAccount;
126
+ if (!serviceAccount && config.serviceAccountFile) {
127
+ try {
128
+ serviceAccount = safeJson.parse(fs.readFileSync(config.serviceAccountFile), { schema: SERVICE_ACCOUNT_SCHEMA });
129
+ } catch (e) {
130
+ throw new Error("gcs: failed to read serviceAccountFile '" + config.serviceAccountFile + "': " + e.message);
131
+ }
132
+ } else if (serviceAccount && (!serviceAccount.client_email || !serviceAccount.private_key)) {
133
+ throw new Error("gcs: serviceAccount with { client_email, private_key } is required (or serviceAccountFile pointing to one)");
134
+ }
135
+ if (!serviceAccount) {
136
+ throw new Error("gcs: serviceAccount with { client_email, private_key } is required (or serviceAccountFile pointing to one)");
137
+ }
138
+
139
+ var endpoint = config.endpoint || DEFAULT_ENDPOINT;
140
+ if (endpoint.endsWith("/")) endpoint = endpoint.slice(0, -1);
141
+ var tokenEndpoint = config.tokenEndpoint || TOKEN_ENDPOINT;
142
+ var bucket = config.bucket;
143
+ var scope = config.scope || DEFAULT_SCOPE;
144
+ var timeoutMs = config.timeoutMs;
145
+ // HTTPS-only by default — google APIs are always HTTPS. Operators with
146
+ // an emulator / private fake-GCS endpoint opt in via config.allowedProtocols.
147
+ var allowedProtocols = config.allowedProtocols || safeUrl.ALLOW_HTTP_TLS;
148
+ var allowInternal = config.allowInternal != null ? config.allowInternal : null;
149
+ safeUrl.parse(endpoint, { allowedProtocols: allowedProtocols, errorClass: ObjectStoreError });
150
+ safeUrl.parse(tokenEndpoint, { allowedProtocols: allowedProtocols, errorClass: ObjectStoreError });
151
+ var reqOpts = { timeoutMs: timeoutMs, allowedProtocols: allowedProtocols };
152
+ if (allowInternal !== null) reqOpts.allowInternal = allowInternal;
153
+
154
+ // ---- Token cache ----
155
+ var cachedToken = null; // { accessToken, expiresAt }
156
+
157
+ async function _ensureToken() {
158
+ if (cachedToken && Date.now() < cachedToken.expiresAt - TOKEN_REFRESH_BUFFER) {
159
+ return cachedToken.accessToken;
160
+ }
161
+ var assertion = _signJwt(serviceAccount, scope, tokenEndpoint);
162
+ var bodyStr = "grant_type=" + encodeURIComponent("urn:ietf:params:oauth:grant-type:jwt-bearer") +
163
+ "&assertion=" + encodeURIComponent(assertion);
164
+ var bodyBuf = Buffer.from(bodyStr, "utf8");
165
+ var res = await _httpRequest(
166
+ "POST",
167
+ _internalUrl(tokenEndpoint, allowedProtocols),
168
+ {
169
+ "Content-Type": "application/x-www-form-urlencoded",
170
+ "Content-Length": String(bodyBuf.length),
171
+ },
172
+ bodyBuf,
173
+ reqOpts
174
+ );
175
+ var tokenResp = safeJson.parse(res.body);
176
+ if (!tokenResp.access_token) {
177
+ throw _err("AUTH_FAILED", "GCS token endpoint returned no access_token: " + res.body.toString("utf8"), true);
178
+ }
179
+ var expiresInMs = C.TIME.seconds(tokenResp.expires_in || 3600);
180
+ cachedToken = {
181
+ accessToken: tokenResp.access_token,
182
+ expiresAt: Date.now() + expiresInMs,
183
+ };
184
+ return cachedToken.accessToken;
185
+ }
186
+
187
+ function _objectUrl(key, params) {
188
+ var u = _internalUrl(endpoint + "/storage/v1/b/" + encodeURIComponent(bucket) +
189
+ "/o/" + encodeURIComponent(key), allowedProtocols);
190
+ if (params) {
191
+ Object.keys(params).forEach(function (k) { u.searchParams.set(k, params[k]); });
192
+ }
193
+ return u;
194
+ }
195
+
196
+ function _uploadUrl(key) {
197
+ var u = _internalUrl(endpoint + "/upload/storage/v1/b/" + encodeURIComponent(bucket) + "/o", allowedProtocols);
198
+ u.searchParams.set("uploadType", "media");
199
+ u.searchParams.set("name", key);
200
+ return u;
201
+ }
202
+
203
+ function _listUrl(prefix, opts) {
204
+ var u = _internalUrl(endpoint + "/storage/v1/b/" + encodeURIComponent(bucket) + "/o", allowedProtocols);
205
+ if (prefix) u.searchParams.set("prefix", prefix);
206
+ if (opts && opts.maxResults) u.searchParams.set("maxResults", String(opts.maxResults));
207
+ if (opts && opts.pageToken) u.searchParams.set("pageToken", opts.pageToken);
208
+ return u;
209
+ }
210
+
211
+ // ---- Operations ----
212
+
213
+ async function put(key, body, opts) {
214
+ var token = await _ensureToken();
215
+ var url = _uploadUrl(key);
216
+ var buf = Buffer.isBuffer(body) ? body : Buffer.from(typeof body === "string" ? body : "", "utf8");
217
+ var contentType = (opts && opts.contentType) || "application/octet-stream";
218
+ var res = await _httpRequest("POST", url, Object.assign(
219
+ authHeader.bearer(token),
220
+ { "Content-Type": contentType,
221
+ "Content-Length": String(buf.length) }
222
+ ), buf, reqOpts);
223
+ var meta = safeJson.parse(res.body);
224
+ return { size: parseInt(meta.size || buf.length, 10), etag: meta.etag };
225
+ }
226
+
227
+ // get(key, opts?) — opts forwarded to GCS as conditional / range
228
+ // headers (Range, If-None-Match, If-Match, If-Modified-Since,
229
+ // If-Unmodified-Since). Returns the body buffer for backwards compat;
230
+ // operators wanting full status + response headers call getResponse().
231
+ async function get(key, opts) {
232
+ var r = await getResponse(key, opts);
233
+ return r.body;
234
+ }
235
+
236
+ function getStream(key, opts) {
237
+ return Readable.from(get(key, opts));
238
+ }
239
+
240
+ async function getResponse(key, opts) {
241
+ opts = opts || {};
242
+ var token = await _ensureToken();
243
+ var url = _objectUrl(key, { alt: "media" });
244
+ var headers = authHeader.bearer(token);
245
+ if (opts.range) {
246
+ headers["Range"] = "bytes=" + opts.range.start + "-" + opts.range.end;
247
+ }
248
+ if (opts.ifNoneMatch) headers["If-None-Match"] = opts.ifNoneMatch;
249
+ if (opts.ifMatch) headers["If-Match"] = opts.ifMatch;
250
+ if (opts.ifModifiedSince) headers["If-Modified-Since"] = opts.ifModifiedSince;
251
+ if (opts.ifUnmodifiedSince) headers["If-Unmodified-Since"] = opts.ifUnmodifiedSince;
252
+ try {
253
+ var res = await _httpRequest("GET", url, headers, null, reqOpts);
254
+ return {
255
+ statusCode: res.statusCode,
256
+ body: res.body,
257
+ etag: res.headers && res.headers.etag,
258
+ lastModified: res.headers && res.headers["last-modified"]
259
+ ? Date.parse(res.headers["last-modified"]) : null,
260
+ contentRange: res.headers && res.headers["content-range"] || null,
261
+ size: res.headers && res.headers["content-length"]
262
+ ? parseInt(res.headers["content-length"], 10) : null,
263
+ contentType: res.headers && res.headers["content-type"] || null,
264
+ };
265
+ } catch (err) {
266
+ if (err && err.statusCode === requestHelpers.HTTP_STATUS.NOT_MODIFIED) {
267
+ return {
268
+ statusCode: requestHelpers.HTTP_STATUS.NOT_MODIFIED,
269
+ body: null, etag: null, lastModified: null,
270
+ };
271
+ }
272
+ throw err;
273
+ }
274
+ }
275
+
276
+ async function head(key) {
277
+ var token = await _ensureToken();
278
+ var url = _objectUrl(key);
279
+ var res = await _httpRequest("GET", url, authHeader.bearer(token), null, reqOpts);
280
+ var meta = safeJson.parse(res.body);
281
+ return {
282
+ size: parseInt(meta.size, 10),
283
+ etag: meta.etag,
284
+ lastModified: meta.updated ? Date.parse(meta.updated) : null,
285
+ };
286
+ }
287
+
288
+ async function deleteKey(key) {
289
+ var token = await _ensureToken();
290
+ var url = _objectUrl(key);
291
+ try {
292
+ await _httpRequest("DELETE", url, authHeader.bearer(token), null, reqOpts);
293
+ return true;
294
+ } catch (e) {
295
+ if (e.statusCode === 404) return false;
296
+ throw e;
297
+ }
298
+ }
299
+
300
+ async function list(prefix, opts) {
301
+ opts = opts || {};
302
+ var token = await _ensureToken();
303
+ var url = _listUrl(prefix, { maxResults: opts.maxResults, pageToken: opts.continuationToken });
304
+ var res = await _httpRequest("GET", url, authHeader.bearer(token), null, reqOpts);
305
+ var listResp = safeJson.parse(res.body);
306
+ var items = (listResp.items || []).map(function (item) {
307
+ return {
308
+ key: item.name,
309
+ size: parseInt(item.size, 10),
310
+ lastModified: item.updated ? Date.parse(item.updated) : null,
311
+ };
312
+ });
313
+ return {
314
+ items: items,
315
+ truncated: !!listResp.nextPageToken,
316
+ continuationToken: listResp.nextPageToken || null,
317
+ };
318
+ }
319
+
320
+ function _v4Presign(method, opts) {
321
+ opts = opts || {};
322
+ if (!opts.key || typeof opts.key !== "string") {
323
+ throw _err("INVALID_KEY", "presigned URL: key is required", true);
324
+ }
325
+ if (opts.key.indexOf("\0") !== -1) {
326
+ throw _err("INVALID_KEY", "null byte in key", true);
327
+ }
328
+ var expiresIn = opts.expiresIn != null ? opts.expiresIn : PRESIGN_DEFAULT_EXPIRES_SECONDS;
329
+ if (typeof expiresIn !== "number" ||
330
+ expiresIn < PRESIGN_MIN_EXPIRES_SECONDS ||
331
+ expiresIn > PRESIGN_MAX_EXPIRES_SECONDS) {
332
+ throw _err("INVALID_EXPIRES",
333
+ "presigned URL: expiresIn must be a number of seconds between " +
334
+ PRESIGN_MIN_EXPIRES_SECONDS + " and " + PRESIGN_MAX_EXPIRES_SECONDS +
335
+ " (7 days, V4 hard cap)", true);
336
+ }
337
+
338
+ // V4 presigned URLs target the XML API path-style endpoint
339
+ // (storage.googleapis.com/{bucket}/{key}), not the JSON API used
340
+ // for the in-process put/get methods. The XML endpoint is what
341
+ // honors the V4 signature.
342
+ var encodedKey = opts.key.split("/")
343
+ .map(function (s) { return sigv4.awsUriEncode(s, true); })
344
+ .join("/");
345
+ var url = _internalUrl(endpoint + "/" + encodeURIComponent(bucket) + "/" + encodedKey, allowedProtocols);
346
+
347
+ var date = opts.date || new Date();
348
+ // Reuse SigV4's date formatters — the wire format is identical.
349
+ var amzDate = sigv4.formatAmzDate(date);
350
+ var dateStamp = sigv4.formatDateStamp(date);
351
+ var credentialScope = dateStamp + "/" + GCS_V4_REGION + "/" +
352
+ GCS_V4_SERVICE + "/goog4_request";
353
+
354
+ var headers = { host: url.host };
355
+ if (opts.contentType) headers["content-type"] = opts.contentType;
356
+ // GCS V4 SignedHeaders: lowercase, semicolon-joined, AWS-spec order.
357
+ var signedHeaderKeys = [];
358
+ for (var hk in headers) signedHeaderKeys.push(hk);
359
+ signedHeaderKeys.sort();
360
+ var signedHeadersStr = signedHeaderKeys.join(";");
361
+
362
+ url.searchParams.set("X-Goog-Algorithm", GCS_V4_ALGORITHM);
363
+ url.searchParams.set("X-Goog-Credential", serviceAccount.client_email + "/" + credentialScope);
364
+ url.searchParams.set("X-Goog-Date", amzDate);
365
+ url.searchParams.set("X-Goog-Expires", String(expiresIn));
366
+ url.searchParams.set("X-Goog-SignedHeaders", signedHeadersStr);
367
+
368
+ // Build the canonical request — identical shape to SigV4. The
369
+ // sigv4 export gives us the formatter so this stays in lockstep
370
+ // with the AWS implementation.
371
+ var canon = sigv4.canonicalRequest(method, url, headers, "UNSIGNED-PAYLOAD");
372
+ var stringToSign = [
373
+ GCS_V4_ALGORITHM,
374
+ amzDate,
375
+ credentialScope,
376
+ sigv4.sha256Hex(canon),
377
+ ].join("\n");
378
+
379
+ // GCS V4 signs the stringToSign with the service-account's RSA
380
+ // private key (RSA-SHA256). Hex-encoded signature goes back into
381
+ // the URL.
382
+ var signer = nodeCrypto.createSign("RSA-SHA256");
383
+ signer.update(stringToSign);
384
+ signer.end();
385
+ var signature = signer.sign(serviceAccount.private_key).toString("hex");
386
+
387
+ url.searchParams.set("X-Goog-Signature", signature);
388
+
389
+ var clientHeaders = {};
390
+ if (opts.contentType) clientHeaders["Content-Type"] = opts.contentType;
391
+
392
+ return {
393
+ url: url.toString(),
394
+ method: method,
395
+ headers: clientHeaders,
396
+ expiresAt: date.getTime() + C.TIME.seconds(expiresIn),
397
+ };
398
+ }
399
+
400
+ function presignedUploadUrl(opts) { return _v4Presign("PUT", opts); }
401
+ function presignedDownloadUrl(opts) { return _v4Presign("GET", opts); }
402
+
403
+ // GCS V4 POST policy presigning. Same shape as SigV4 POST policy
404
+ // (operator-uploaded multipart/form-data with policy + signature
405
+ // fields), but signed with the service account's RSA private key
406
+ // instead of an HMAC chain. The content-length-range condition is
407
+ // server-side enforced by GCS — clients sending bodies outside the
408
+ // declared range get a 403 from the bucket itself.
409
+ function presignedUploadPolicy(opts) {
410
+ opts = opts || {};
411
+ if (!opts.key || typeof opts.key !== "string") {
412
+ throw _err("INVALID_KEY", "presignedUploadPolicy: key is required", true);
413
+ }
414
+ if (opts.key.indexOf("\0") !== -1) {
415
+ throw _err("INVALID_KEY", "null byte in key", true);
416
+ }
417
+ if (typeof opts.maxBytes !== "number" || !Number.isFinite(opts.maxBytes) ||
418
+ opts.maxBytes <= 0) {
419
+ throw _err("INVALID_MAX_BYTES",
420
+ "presignedUploadPolicy: maxBytes (positive number of bytes) is required — " +
421
+ "POST-form policy enforces body size via the content-length-range condition; " +
422
+ "use presignedUploadUrl if size enforcement is not needed", true);
423
+ }
424
+ if (opts.minBytes !== undefined && !nb.isNonNegativeFiniteInt(opts.minBytes)) {
425
+ throw _err("INVALID_MIN_BYTES",
426
+ "presignedUploadPolicy: minBytes must be a non-negative finite integer; got " +
427
+ nb.shape(opts.minBytes), true);
428
+ }
429
+ var minBytes = opts.minBytes !== undefined ? opts.minBytes : 0;
430
+ var expiresIn = opts.expiresIn != null ? opts.expiresIn : PRESIGN_DEFAULT_EXPIRES_SECONDS;
431
+ if (typeof expiresIn !== "number" ||
432
+ expiresIn < PRESIGN_MIN_EXPIRES_SECONDS ||
433
+ expiresIn > PRESIGN_MAX_EXPIRES_SECONDS) {
434
+ throw _err("INVALID_EXPIRES",
435
+ "presignedUploadPolicy: expiresIn must be a number of seconds between " +
436
+ PRESIGN_MIN_EXPIRES_SECONDS + " and " + PRESIGN_MAX_EXPIRES_SECONDS +
437
+ " (7 days, V4 hard cap)", true);
438
+ }
439
+
440
+ var date = opts.date || new Date();
441
+ var amzDate = sigv4.formatAmzDate(date);
442
+ var dateStamp = sigv4.formatDateStamp(date);
443
+ var credentialScope = dateStamp + "/" + GCS_V4_REGION + "/" +
444
+ GCS_V4_SERVICE + "/goog4_request";
445
+ var credential = serviceAccount.client_email + "/" + credentialScope;
446
+ var expirationIso = new Date(date.getTime() + C.TIME.seconds(expiresIn)).toISOString();
447
+
448
+ var conditions = [
449
+ { "bucket": bucket },
450
+ { "key": opts.key },
451
+ { "x-goog-algorithm": GCS_V4_ALGORITHM },
452
+ { "x-goog-credential": credential },
453
+ { "x-goog-date": amzDate },
454
+ ["content-length-range", minBytes, opts.maxBytes],
455
+ ];
456
+ if (opts.contentType) {
457
+ conditions.push({ "content-type": opts.contentType });
458
+ }
459
+
460
+ var policy = { expiration: expirationIso, conditions: conditions };
461
+ var policyJson = JSON.stringify(policy);
462
+ var policyB64 = Buffer.from(policyJson, "utf8").toString("base64");
463
+
464
+ // GCS V4: signature is hex(RSA-SHA256(privateKey, policyB64)).
465
+ var signer = nodeCrypto.createSign("RSA-SHA256");
466
+ signer.update(policyB64);
467
+ signer.end();
468
+ var signature = signer.sign(serviceAccount.private_key).toString("hex");
469
+
470
+ var fields = {
471
+ "key": opts.key,
472
+ "x-goog-algorithm": GCS_V4_ALGORITHM,
473
+ "x-goog-credential": credential,
474
+ "x-goog-date": amzDate,
475
+ "policy": policyB64,
476
+ "x-goog-signature": signature,
477
+ };
478
+ if (opts.contentType) fields["content-type"] = opts.contentType;
479
+
480
+ var url = _internalUrl(endpoint + "/" + encodeURIComponent(bucket) + "/", allowedProtocols);
481
+
482
+ return {
483
+ url: url.toString(),
484
+ method: "POST",
485
+ fields: fields,
486
+ expiresAt: date.getTime() + C.TIME.seconds(expiresIn),
487
+ maxBytes: opts.maxBytes,
488
+ enforcement: "content-length-range",
489
+ };
490
+ }
491
+
492
+ return {
493
+ protocol: "gcs",
494
+ endpoint: endpoint,
495
+ bucket: bucket,
496
+ put: put,
497
+ get: get,
498
+ getStream: getStream,
499
+ getResponse: getResponse,
500
+ head: head,
501
+ delete: deleteKey,
502
+ list: list,
503
+ presignedUploadUrl: presignedUploadUrl,
504
+ presignedDownloadUrl: presignedDownloadUrl,
505
+ presignedUploadPolicy: presignedUploadPolicy,
506
+ // Internal accessors for tests
507
+ _ensureToken: _ensureToken,
508
+ _signJwt: function () { return _signJwt(serviceAccount, scope, TOKEN_ENDPOINT); },
509
+ };
510
+ }
511
+
512
+ module.exports = {
513
+ create: create,
514
+ _signJwt: _signJwt,
515
+ _base64UrlEncode: _base64UrlEncode,
516
+ DEFAULT_ENDPOINT: DEFAULT_ENDPOINT,
517
+ TOKEN_ENDPOINT: TOKEN_ENDPOINT,
518
+ DEFAULT_SCOPE: DEFAULT_SCOPE,
519
+ };