@crvouga/mockingbird-service-s3 3.7.0 → 3.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -382,7 +382,7 @@ var nameChar = nameStartChar + "\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040";
382
382
  var nameRegexp = "[" + nameStartChar + "][" + nameChar + "]*";
383
383
  var regexName = new RegExp("^" + nameRegexp + "$");
384
384
  function getAllMatches(string, regex) {
385
- const matches2 = [];
385
+ const matches3 = [];
386
386
  let match2 = regex.exec(string);
387
387
  while (match2) {
388
388
  const allmatches = [];
@@ -391,10 +391,10 @@ function getAllMatches(string, regex) {
391
391
  for (let index = 0; index < len; index++) {
392
392
  allmatches.push(match2[index]);
393
393
  }
394
- matches2.push(allmatches);
394
+ matches3.push(allmatches);
395
395
  match2 = regex.exec(string);
396
396
  }
397
- return matches2;
397
+ return matches3;
398
398
  }
399
399
  var isName = function(string) {
400
400
  const match2 = regexName.exec(string);
@@ -687,24 +687,24 @@ function scanAttributeTokens(attrStr) {
687
687
  return tokens;
688
688
  }
689
689
  function validateAttributeString(attrStr, options) {
690
- const matches2 = scanAttributeTokens(attrStr);
690
+ const matches3 = scanAttributeTokens(attrStr);
691
691
  const attrNames = {};
692
- for (let i = 0; i < matches2.length; i++) {
693
- if (matches2[i][1].length === 0) {
694
- return getErrorObject("InvalidAttr", "Attribute '" + matches2[i][2] + "' has no space in starting.", getPositionFromMatch(matches2[i]));
695
- } else if (matches2[i][3] !== void 0 && matches2[i][4] === void 0) {
696
- return getErrorObject("InvalidAttr", "Attribute '" + matches2[i][2] + "' is without value.", getPositionFromMatch(matches2[i]));
697
- } else if (matches2[i][3] === void 0 && !options.allowBooleanAttributes) {
698
- return getErrorObject("InvalidAttr", "boolean attribute '" + matches2[i][2] + "' is not allowed.", getPositionFromMatch(matches2[i]));
699
- }
700
- const attrName = matches2[i][2];
692
+ for (let i = 0; i < matches3.length; i++) {
693
+ if (matches3[i][1].length === 0) {
694
+ return getErrorObject("InvalidAttr", "Attribute '" + matches3[i][2] + "' has no space in starting.", getPositionFromMatch(matches3[i]));
695
+ } else if (matches3[i][3] !== void 0 && matches3[i][4] === void 0) {
696
+ return getErrorObject("InvalidAttr", "Attribute '" + matches3[i][2] + "' is without value.", getPositionFromMatch(matches3[i]));
697
+ } else if (matches3[i][3] === void 0 && !options.allowBooleanAttributes) {
698
+ return getErrorObject("InvalidAttr", "boolean attribute '" + matches3[i][2] + "' is not allowed.", getPositionFromMatch(matches3[i]));
699
+ }
700
+ const attrName = matches3[i][2];
701
701
  if (!validateAttrName(attrName)) {
702
- return getErrorObject("InvalidAttr", "Attribute '" + attrName + "' is an invalid name.", getPositionFromMatch(matches2[i]));
702
+ return getErrorObject("InvalidAttr", "Attribute '" + attrName + "' is an invalid name.", getPositionFromMatch(matches3[i]));
703
703
  }
704
704
  if (!Object.prototype.hasOwnProperty.call(attrNames, attrName)) {
705
705
  attrNames[attrName] = 1;
706
706
  } else {
707
- return getErrorObject("InvalidAttr", "Attribute '" + attrName + "' is repeated.", getPositionFromMatch(matches2[i]));
707
+ return getErrorObject("InvalidAttr", "Attribute '" + attrName + "' is repeated.", getPositionFromMatch(matches3[i]));
708
708
  }
709
709
  }
710
710
  return true;
@@ -3675,8 +3675,8 @@ function assertContext(context) {
3675
3675
  throw new TypeError("is-unsafe: context must not be an empty array");
3676
3676
  }
3677
3677
  if (Array.isArray(context[0])) {
3678
- for (const list of context) {
3679
- if (!Array.isArray(list) || list.length === 0) {
3678
+ for (const list2 of context) {
3679
+ if (!Array.isArray(list2) || list2.length === 0) {
3680
3680
  throw new TypeError(
3681
3681
  "is-unsafe: each context in the array must be a non-empty pattern array (PatternList)"
3682
3682
  );
@@ -3694,9 +3694,9 @@ function normalise(context) {
3694
3694
  if (Array.isArray(context[0])) return { lists: context, regex: null };
3695
3695
  return { lists: [context], regex: null };
3696
3696
  }
3697
- function matchList(value, list) {
3698
- const label = list.label ?? "CUSTOM";
3699
- for (const rule of list) {
3697
+ function matchList(value, list2) {
3698
+ const label = list2.label ?? "CUSTOM";
3699
+ for (const rule of list2) {
3700
3700
  if (rule.pattern.test(value)) {
3701
3701
  return { context: label, id: rule.id, description: rule.description, pattern: rule.pattern };
3702
3702
  }
@@ -3708,8 +3708,8 @@ function isUnsafe(value, context) {
3708
3708
  assertContext(context);
3709
3709
  const { lists, regex } = normalise(context);
3710
3710
  if (regex) return regex.test(value);
3711
- for (const list of lists) {
3712
- if (matchList(value, list) !== null) return true;
3711
+ for (const list2 of lists) {
3712
+ if (matchList(value, list2) !== null) return true;
3713
3713
  }
3714
3714
  return false;
3715
3715
  }
@@ -3843,15 +3843,15 @@ var attrsRegx = new RegExp(`([^\\s=]+)\\s*(=\\s*(['"])([\\s\\S]*?)\\3)?`, "gm");
3843
3843
  function buildAttributesMap(attrStr, jPath, tagName, force = false) {
3844
3844
  const options = this.options;
3845
3845
  if (force === true || options.ignoreAttributes !== true && typeof attrStr === "string") {
3846
- const matches2 = getAllMatches(attrStr, attrsRegx);
3847
- const len = matches2.length;
3846
+ const matches3 = getAllMatches(attrStr, attrsRegx);
3847
+ const len = matches3.length;
3848
3848
  const attrs = {};
3849
3849
  const processedVals = new Array(len);
3850
3850
  let hasRawAttrs = false;
3851
3851
  const rawAttrsForMatcher = {};
3852
3852
  for (let i = 0; i < len; i++) {
3853
- const attrName = this.resolveNameSpace(matches2[i][1]);
3854
- const oldVal = matches2[i][4];
3853
+ const attrName = this.resolveNameSpace(matches3[i][1]);
3854
+ const oldVal = matches3[i][4];
3855
3855
  if (attrName.length && oldVal !== void 0) {
3856
3856
  let val = oldVal;
3857
3857
  if (options.trimValues) val = val.trim();
@@ -3867,7 +3867,7 @@ function buildAttributesMap(attrStr, jPath, tagName, force = false) {
3867
3867
  const jPathStr = options.jPath ? jPath.toString() : this.readonlyMatcher;
3868
3868
  let hasAttrs = false;
3869
3869
  for (let i = 0; i < len; i++) {
3870
- const attrName = this.resolveNameSpace(matches2[i][1]);
3870
+ const attrName = this.resolveNameSpace(matches3[i][1]);
3871
3871
  if (this.ignoreAttributesFn(attrName, jPathStr)) continue;
3872
3872
  let aName = options.attributeNamePrefix + attrName;
3873
3873
  if (attrName.length) {
@@ -3875,7 +3875,7 @@ function buildAttributesMap(attrStr, jPath, tagName, force = false) {
3875
3875
  aName = options.transformAttributeName(aName);
3876
3876
  }
3877
3877
  aName = sanitizeName(aName, options);
3878
- if (matches2[i][4] !== void 0) {
3878
+ if (matches3[i][4] !== void 0) {
3879
3879
  const oldVal = processedVals[i];
3880
3880
  const newVal = options.attributeValueProcessor(attrName, oldVal, jPathStr);
3881
3881
  if (newVal === null || newVal === void 0) {
@@ -7111,10 +7111,10 @@ var createControlPlane = (context) => {
7111
7111
  return preset !== void 0 ? json(201, { preset, rules: added }) : json(201, added[0]);
7112
7112
  }),
7113
7113
  "PUT /faults": ({ body, namespace }) => guard(() => {
7114
- const list = isRecord2(body) ? body.faults : void 0;
7115
- if (!Array.isArray(list))
7114
+ const list2 = isRecord2(body) ? body.faults : void 0;
7115
+ if (!Array.isArray(list2))
7116
7116
  return adminError(400, 'expected {"faults": [...]}');
7117
- controls.apply(namespace, normalizeControls({ faults: list }));
7117
+ controls.apply(namespace, normalizeControls({ faults: list2 }));
7118
7118
  return json(200, { faults: faults.list(namespace) });
7119
7119
  }),
7120
7120
  "DELETE /faults": ({ url, namespace }) => {
@@ -7738,11 +7738,11 @@ var inferFields = (records) => {
7738
7738
  const objects = sample.filter((record) => isRecord3(record.value));
7739
7739
  if (objects.length === 0) {
7740
7740
  const kinds = new Set(sample.map((record) => kindOf(record.value)));
7741
- const list = [...kinds];
7741
+ const list2 = [...kinds];
7742
7742
  return [
7743
7743
  {
7744
7744
  name: "(value)",
7745
- kind: list.length === 1 ? list[0] : "unknown",
7745
+ kind: list2.length === 1 ? list2[0] : "unknown",
7746
7746
  optional: false
7747
7747
  }
7748
7748
  ];
@@ -8039,7 +8039,7 @@ var stateAdminRoutes = (routes) => {
8039
8039
  };
8040
8040
 
8041
8041
  // ../core/dist/version.js
8042
- var PACKAGE_VERSION = true ? "3.7.0" : UNRELEASED_VERSION;
8042
+ var PACKAGE_VERSION = true ? "3.8.0" : UNRELEASED_VERSION;
8043
8043
 
8044
8044
  // ../core/dist/signing.js
8045
8045
  var encoder = new TextEncoder();
@@ -8562,11 +8562,11 @@ var webhookAdminRoutes = (hub) => ({
8562
8562
  }))
8563
8563
  }),
8564
8564
  "PUT /webhook-endpoints": ({ body, namespace }) => {
8565
- const list = Array.isArray(body) ? body : isRecord4(body) ? body.endpoints : void 0;
8566
- if (!Array.isArray(list))
8565
+ const list2 = Array.isArray(body) ? body : isRecord4(body) ? body.endpoints : void 0;
8566
+ if (!Array.isArray(list2))
8567
8567
  return adminError3(400, "expected [{url, secret?, events?}]");
8568
8568
  const parsed = [];
8569
- for (const each of list) {
8569
+ for (const each of list2) {
8570
8570
  const endpoint = parseEndpoint(each);
8571
8571
  if (typeof endpoint === "string")
8572
8572
  return adminError3(400, endpoint);
@@ -9728,9 +9728,9 @@ var credentialRoutes = (registry) => ({
9728
9728
  }),
9729
9729
  "PUT /credentials": ({ body, namespace }) => {
9730
9730
  const pairs = [];
9731
- const list = Array.isArray(body) ? body : isRecord2(body) ? body.credentials : void 0;
9732
- if (Array.isArray(list)) {
9733
- for (const each of list) {
9731
+ const list2 = Array.isArray(body) ? body : isRecord2(body) ? body.credentials : void 0;
9732
+ if (Array.isArray(list2)) {
9733
+ for (const each of list2) {
9734
9734
  if (typeof each === "string")
9735
9735
  pairs.push([each, namespace]);
9736
9736
  else if (isRecord2(each) && typeof each.credential === "string") {
@@ -9741,8 +9741,8 @@ var credentialRoutes = (registry) => ({
9741
9741
  } else
9742
9742
  return adminFail(400, "each entry is a credential string or {credential, namespace}");
9743
9743
  }
9744
- } else if (isRecord2(list)) {
9745
- for (const [credential, target] of Object.entries(list)) {
9744
+ } else if (isRecord2(list2)) {
9745
+ for (const [credential, target] of Object.entries(list2)) {
9746
9746
  if (typeof target !== "string")
9747
9747
  return adminFail(400, `namespace for ${credential} must be a string`);
9748
9748
  pairs.push([credential, target]);
@@ -9769,12 +9769,253 @@ var credentialRoutes = (registry) => ({
9769
9769
  }
9770
9770
  });
9771
9771
 
9772
+ // src/checksums.ts
9773
+ var table = (polynomial) => Array.from({ length: 256 }, (_, index) => {
9774
+ let value = index;
9775
+ for (let bit = 0; bit < 8; bit++) value = value & 1 ? value >>> 1 ^ polynomial : value >>> 1;
9776
+ return value >>> 0;
9777
+ });
9778
+ var CRC32_TABLE = table(3988292384);
9779
+ var CRC32C_TABLE = table(2197175160);
9780
+ var crc32 = (bytes, lookup) => {
9781
+ let crc = 4294967295;
9782
+ for (const byte of bytes) crc = lookup[(crc ^ byte) & 255] ^ crc >>> 8;
9783
+ return (crc ^ 4294967295) >>> 0;
9784
+ };
9785
+ var POLYNOMIAL_64 = 0x9a6c9329ac4bc9b5n;
9786
+ var table64;
9787
+ var crc64nvme = (bytes) => {
9788
+ table64 ??= Array.from({ length: 256 }, (_, index) => {
9789
+ let value = BigInt(index);
9790
+ for (let bit = 0; bit < 8; bit++)
9791
+ value = value & 1n ? value >> 1n ^ POLYNOMIAL_64 : value >> 1n;
9792
+ return value;
9793
+ });
9794
+ let crc = 0xffffffffffffffffn;
9795
+ for (const byte of bytes)
9796
+ crc = table64[Number((crc ^ BigInt(byte)) & 0xffn)] ^ crc >> 8n;
9797
+ return crc ^ 0xffffffffffffffffn;
9798
+ };
9799
+ var base64 = (bytes) => btoa(String.fromCharCode(...bytes));
9800
+ var big = (value, width) => {
9801
+ const out = new Uint8Array(width);
9802
+ let rest = BigInt(value);
9803
+ for (let index = width - 1; index >= 0; index--) {
9804
+ out[index] = Number(rest & 0xffn);
9805
+ rest >>= 8n;
9806
+ }
9807
+ return out;
9808
+ };
9809
+ var subtle = async (algorithm, bytes) => new Uint8Array(await crypto.subtle.digest(algorithm, bytes));
9810
+ var CHECKSUM_ALGORITHMS = ["crc32", "crc32c", "crc64nvme", "sha1", "sha256"];
9811
+ var checksum = async (algorithm, bytes) => {
9812
+ switch (algorithm) {
9813
+ case "crc32":
9814
+ return base64(big(crc32(bytes, CRC32_TABLE), 4));
9815
+ case "crc32c":
9816
+ return base64(big(crc32(bytes, CRC32C_TABLE), 4));
9817
+ case "crc64nvme":
9818
+ return base64(big(crc64nvme(bytes), 8));
9819
+ case "sha1":
9820
+ return base64(await subtle("SHA-1", bytes));
9821
+ case "sha256":
9822
+ return base64(await subtle("SHA-256", bytes));
9823
+ }
9824
+ };
9825
+
9826
+ // src/chunked.ts
9827
+ var isAwsChunked = (headers) => (headers.get("x-amz-content-sha256") ?? "").startsWith("STREAMING-") || (headers.get("content-encoding") ?? "").split(",").some((coding) => coding.trim().toLowerCase() === "aws-chunked");
9828
+ var CR = 13;
9829
+ var LF = 10;
9830
+ var HEX_SIZE = /^[0-9a-fA-F]{1,15}$/;
9831
+ var decodeAwsChunked = (input) => {
9832
+ const line = (from) => {
9833
+ for (let index = from; index + 1 < input.length; index++)
9834
+ if (input[index] === CR && input[index + 1] === LF)
9835
+ return {
9836
+ text: new TextDecoder("latin1").decode(input.subarray(from, index)),
9837
+ next: index + 2
9838
+ };
9839
+ return void 0;
9840
+ };
9841
+ const chunks = [];
9842
+ let position = 0;
9843
+ for (; ; ) {
9844
+ const header = line(position);
9845
+ if (!header) return void 0;
9846
+ const size = header.text.split(";")[0];
9847
+ if (!HEX_SIZE.test(size)) return void 0;
9848
+ position = header.next;
9849
+ const length = Number.parseInt(size, 16);
9850
+ if (length === 0) break;
9851
+ if (position + length + 2 > input.length) return void 0;
9852
+ if (input[position + length] !== CR || input[position + length + 1] !== LF) return void 0;
9853
+ chunks.push(input.subarray(position, position + length));
9854
+ position += length + 2;
9855
+ }
9856
+ const trailers = {};
9857
+ for (; ; ) {
9858
+ const trailer = line(position);
9859
+ if (!trailer) return void 0;
9860
+ position = trailer.next;
9861
+ if (trailer.text === "") break;
9862
+ const colon = trailer.text.indexOf(":");
9863
+ if (colon < 1) return void 0;
9864
+ trailers[trailer.text.slice(0, colon).trim().toLowerCase()] = trailer.text.slice(colon + 1).trim();
9865
+ }
9866
+ const payload = new Uint8Array(chunks.reduce((total, chunk) => total + chunk.length, 0));
9867
+ let offset = 0;
9868
+ for (const chunk of chunks) {
9869
+ payload.set(chunk, offset);
9870
+ offset += chunk.length;
9871
+ }
9872
+ return { payload, trailers };
9873
+ };
9874
+
9875
+ // src/cors.ts
9876
+ var CORS_METHODS = ["GET", "PUT", "POST", "DELETE", "HEAD"];
9877
+ var PREFLIGHT_VARY = "Origin, Access-Control-Request-Headers, Access-Control-Request-Method";
9878
+ var list = (value) => (Array.isArray(value) ? value : value === void 0 || value === "" ? [] : [value]).map(String);
9879
+ var parseCors = (body) => {
9880
+ const root = awsParseXml(body).CORSConfiguration ?? {};
9881
+ const rules = Array.isArray(root.CORSRule) ? root.CORSRule : root.CORSRule ? [root.CORSRule] : [];
9882
+ return rules.map((rule) => ({
9883
+ origins: list(rule.AllowedOrigin),
9884
+ methods: list(rule.AllowedMethod),
9885
+ headers: list(rule.AllowedHeader),
9886
+ expose: list(rule.ExposeHeader),
9887
+ ...rule.MaxAgeSeconds !== void 0 ? { maxAge: String(rule.MaxAgeSeconds).trim() } : {}
9888
+ }));
9889
+ };
9890
+ var invalidCors = (rules) => {
9891
+ if (rules.length === 0 || rules.length > 100)
9892
+ return [
9893
+ "MalformedXML",
9894
+ "The XML you provided was not well-formed or did not validate against our published schema"
9895
+ ];
9896
+ for (const rule of rules) {
9897
+ if (rule.origins.length === 0 || rule.methods.length === 0)
9898
+ return [
9899
+ "MalformedXML",
9900
+ "The XML you provided was not well-formed or did not validate against our published schema"
9901
+ ];
9902
+ for (const method of rule.methods)
9903
+ if (!CORS_METHODS.includes(method))
9904
+ return [
9905
+ "InvalidRequest",
9906
+ `Found unsupported HTTP method in CORS config. Unsupported method is ${method}`
9907
+ ];
9908
+ for (const [name2, values] of [
9909
+ ["AllowedOrigin", rule.origins],
9910
+ ["AllowedHeader", rule.headers]
9911
+ ])
9912
+ for (const value of values)
9913
+ if (value.split("*").length > 2)
9914
+ return ["InvalidRequest", `${name2} "${value}" can not have more than one wildcard.`];
9915
+ if (rule.maxAge !== void 0 && !/^\d+$/.test(rule.maxAge))
9916
+ return [
9917
+ "MalformedXML",
9918
+ "The XML you provided was not well-formed or did not validate against our published schema"
9919
+ ];
9920
+ }
9921
+ return void 0;
9922
+ };
9923
+ var matches2 = (pattern, value) => {
9924
+ const star = pattern.indexOf("*");
9925
+ return star < 0 ? pattern === value : value.length >= pattern.length - 1 && value.startsWith(pattern.slice(0, star)) && value.endsWith(pattern.slice(star + 1));
9926
+ };
9927
+ var matchRule = (rules, origin, method, requested = []) => rules.find(
9928
+ (rule) => rule.origins.some((pattern) => matches2(pattern, origin)) && rule.methods.includes(method) && requested.every(
9929
+ (header) => rule.headers.some((pattern) => matches2(pattern.toLowerCase(), header))
9930
+ )
9931
+ );
9932
+ var corsHeaders = (rule, origin) => {
9933
+ const any = rule.origins.includes("*");
9934
+ return {
9935
+ "access-control-allow-origin": any ? "*" : origin,
9936
+ "access-control-allow-methods": rule.methods.join(", "),
9937
+ ...any ? {} : { "access-control-allow-credentials": "true" },
9938
+ ...rule.expose.length ? { "access-control-expose-headers": rule.expose.join(", ") } : {}
9939
+ };
9940
+ };
9941
+
9772
9942
  // src/generated/openapi.ts
9773
9943
  var document = JSON.parse(`{"openapi":"3.1.0","info":{"title":"Amazon S3 (Mockingbird subset)","version":"2006-03-01","description":"Path-style S3 REST contract used by AWS SDK v3."},"servers":[{"url":"https://s3.us-east-1.amazonaws.com"}],"paths":{"/{bucket}":{"parameters":[{"name":"bucket","in":"path","required":true,"schema":{"type":"string"}}],"put":{"operationId":"CreateBucket","x-mockingbird":{"supported":true,"parity":{"safe":false}},"responses":{"200":{"description":"Created"},"400":{"$ref":"#/components/responses/Error"},"403":{"$ref":"#/components/responses/Error"}}},"head":{"operationId":"HeadBucket","responses":{"200":{"description":"Exists"},"404":{"description":"Missing"}}},"get":{"operationId":"ListObjectsV2","responses":{"200":{"description":"XML listing","content":{"application/xml":{"schema":{"type":"string"}}}},"404":{"$ref":"#/components/responses/Error"}}},"post":{"operationId":"BucketPost","x-mockingbird":{"supported":true,"parity":{"safe":false}},"responses":{"200":{"description":"DeleteObjects result","content":{"application/xml":{"schema":{"type":"string"}}}},"404":{"$ref":"#/components/responses/Error"}}}},"/{bucket}/{key}":{"parameters":[{"name":"bucket","in":"path","required":true,"schema":{"type":"string"}},{"name":"key","in":"path","required":true,"schema":{"type":"string"}}],"put":{"operationId":"PutObject","x-mockingbird":{"supported":true,"parity":{"safe":false}},"requestBody":{"content":{"application/octet-stream":{"schema":{"type":"string","format":"binary"}}}},"responses":{"200":{"description":"Stored"},"400":{"$ref":"#/components/responses/Error"},"403":{"$ref":"#/components/responses/Error"},"404":{"$ref":"#/components/responses/Error"}}},"get":{"operationId":"GetObject","responses":{"200":{"description":"Object bytes","content":{"application/octet-stream":{"schema":{"type":"string","format":"binary"}}}},"206":{"description":"Range bytes"},"403":{"$ref":"#/components/responses/Error"},"404":{"$ref":"#/components/responses/Error"},"416":{"$ref":"#/components/responses/Error"}}},"head":{"operationId":"HeadObject","responses":{"200":{"description":"Object metadata"},"404":{"description":"Missing"}}},"delete":{"operationId":"DeleteObject","x-mockingbird":{"supported":true,"parity":{"safe":false}},"responses":{"204":{"description":"Deleted"},"403":{"$ref":"#/components/responses/Error"}}},"post":{"operationId":"MultipartPost","x-mockingbird":{"supported":true,"parity":{"enabled":false,"reason":"Multipart XML protocol."}},"responses":{"200":{"description":"Multipart response","content":{"application/xml":{"schema":{"type":"string"}}}},"404":{"$ref":"#/components/responses/Error"}}}}},"components":{"responses":{"Error":{"description":"Canonical S3 XML error.","content":{"application/xml":{"schema":{"type":"string"}}}}}}}`);
9774
9944
  var operationIds = ["ListObjectsV2", "CreateBucket", "BucketPost", "HeadBucket", "GetObject", "PutObject", "MultipartPost", "DeleteObject", "HeadObject"];
9775
9945
  var supportedOperationIds = ["ListObjectsV2", "CreateBucket", "BucketPost", "HeadBucket", "GetObject", "PutObject", "MultipartPost", "DeleteObject", "HeadObject"];
9776
9946
 
9947
+ // src/hosting.ts
9948
+ var DEFAULT_VIRTUAL_HOSTS = ["localhost"];
9949
+ var VIRTUAL_BUCKET_HEADER = "x-mockingbird-s3-virtual-bucket";
9950
+ var virtualBucket = (host, bases) => {
9951
+ if (host.startsWith("[")) return void 0;
9952
+ const name2 = host.replace(/:\d+$/, "").toLowerCase();
9953
+ const base = [...bases].map((value) => value.toLowerCase().replace(/^\.+|\.+$/g, "")).filter((value) => value && name2.endsWith(`.${value}`) && name2.length > value.length + 1).sort((a, b) => b.length - a.length)[0];
9954
+ return base ? name2.slice(0, name2.length - base.length - 1) : void 0;
9955
+ };
9956
+ var toPathStyle = (request, bases, keep) => {
9957
+ const url = new URL(request.url);
9958
+ const bucket = virtualBucket(url.host, bases);
9959
+ if (!bucket || request.headers.get(VIRTUAL_BUCKET_HEADER) === bucket) return request;
9960
+ if (keep && (url.pathname === keep || url.pathname.startsWith(`${keep}/`))) return request;
9961
+ url.pathname = url.pathname === "/" ? `/${bucket}` : `/${bucket}${url.pathname}`;
9962
+ const headers = new Headers(request.headers);
9963
+ headers.set(VIRTUAL_BUCKET_HEADER, bucket);
9964
+ const init = {
9965
+ method: request.method,
9966
+ headers,
9967
+ signal: request.signal
9968
+ };
9969
+ if (request.body) {
9970
+ init.body = request.body;
9971
+ init.duplex = "half";
9972
+ }
9973
+ return new Request(url, init);
9974
+ };
9975
+
9777
9976
  // src/state.ts
9977
+ var CHUNK = 32768;
9978
+ var encodeBytes = (bytes) => {
9979
+ const pieces = [];
9980
+ for (let offset = 0; offset < bytes.length; offset += CHUNK)
9981
+ pieces.push(String.fromCharCode(...bytes.subarray(offset, offset + CHUNK)));
9982
+ return btoa(pieces.join(""));
9983
+ };
9984
+ var decodeBytes = (stored) => {
9985
+ if (typeof stored !== "string") return Uint8Array.from(stored);
9986
+ const binary = atob(stored);
9987
+ const bytes = new Uint8Array(binary.length);
9988
+ for (let index = 0; index < binary.length; index++) bytes[index] = binary.charCodeAt(index);
9989
+ return bytes;
9990
+ };
9991
+ var BlobCollection = class {
9992
+ inner;
9993
+ constructor(sqlite, namespace, name2) {
9994
+ this.inner = new Collection(sqlite, namespace, name2);
9995
+ }
9996
+ decode(value) {
9997
+ return { ...value, bytes: decodeBytes(value.bytes) };
9998
+ }
9999
+ get(id) {
10000
+ const value = this.inner.get(id);
10001
+ return value && this.decode(value);
10002
+ }
10003
+ has(id) {
10004
+ return this.inner.has(id);
10005
+ }
10006
+ insert(id, value) {
10007
+ this.inner.insert(id, { ...value, bytes: encodeBytes(value.bytes) });
10008
+ }
10009
+ delete(id) {
10010
+ return this.inner.delete(id);
10011
+ }
10012
+ list(options = {}) {
10013
+ return this.inner.list({
10014
+ ...options.order ? { order: options.order } : {},
10015
+ ...options.where ? { where: options.where } : {}
10016
+ }).map((row) => ({ ...row, value: this.decode(row.value) }));
10017
+ }
10018
+ };
9778
10019
  var S3State = class {
9779
10020
  buckets;
9780
10021
  objects;
@@ -9785,11 +10026,11 @@ var S3State = class {
9785
10026
  ids;
9786
10027
  constructor(sqlite, namespace) {
9787
10028
  this.buckets = new Collection(sqlite, namespace, "s3_buckets");
9788
- this.objects = new Collection(sqlite, namespace, "s3_objects");
9789
- this.versions = new Collection(sqlite, namespace, "s3_versions");
10029
+ this.objects = new BlobCollection(sqlite, namespace, "s3_objects");
10030
+ this.versions = new BlobCollection(sqlite, namespace, "s3_versions");
9790
10031
  this.configurations = new Collection(sqlite, namespace, "s3_configurations");
9791
10032
  this.uploads = new Collection(sqlite, namespace, "s3_uploads");
9792
- this.parts = new Collection(sqlite, namespace, "s3_parts");
10033
+ this.parts = new BlobCollection(sqlite, namespace, "s3_parts");
9793
10034
  this.ids = new IdSequence(sqlite, namespace, "s3");
9794
10035
  }
9795
10036
  objectId(bucket, key) {
@@ -9920,6 +10161,7 @@ var createRuntime2 = (options = {}) => {
9920
10161
  ...options.buckets ? { buckets: options.buckets } : {},
9921
10162
  ...options.objects ? { objects: options.objects } : {},
9922
10163
  ...options.credentials ? { credentials: options.credentials } : {},
10164
+ ...options.virtualHosts ? { virtualHosts: options.virtualHosts } : {},
9923
10165
  onNotification: (event) => hub.publish({
9924
10166
  namespace,
9925
10167
  type: `s3:${event.eventName}`,
@@ -9943,11 +10185,18 @@ var createRuntime2 = (options = {}) => {
9943
10185
  }),
9944
10186
  admin
9945
10187
  });
9946
- return Object.assign(runtime, { webhooks: hub });
10188
+ const bases = options.virtualHosts ?? DEFAULT_VIRTUAL_HOSTS;
10189
+ const adminPrefix = (options.adminPrefix ?? "/__admin").replace(/\/+$/, "");
10190
+ const fetch2 = runtime.fetch.bind(runtime);
10191
+ return Object.assign(runtime, {
10192
+ webhooks: hub,
10193
+ fetch: (request) => fetch2(toPathStyle(request, bases, adminPrefix))
10194
+ });
9947
10195
  };
9948
10196
 
9949
10197
  // src/index.ts
9950
10198
  var S3_NAMESPACE = "s3";
10199
+ var S3_MAX_UPLOAD_BYTES = 5 * 1024 ** 3;
9951
10200
  var accessKeyCredential = sigV4AccessKeyId;
9952
10201
  var encoder2 = new TextEncoder();
9953
10202
  var xmlEscape = awsXmlEscape;
@@ -9970,6 +10219,16 @@ var hmac2 = async (key, value) => {
9970
10219
  );
9971
10220
  return new Uint8Array(await crypto.subtle.sign("HMAC", imported, encoder2.encode(value)));
9972
10221
  };
10222
+ var RESPONSE_OVERRIDES = [
10223
+ ["response-cache-control", "cache-control"],
10224
+ ["response-content-disposition", "content-disposition"],
10225
+ ["response-content-encoding", "content-encoding"],
10226
+ ["response-content-language", "content-language"],
10227
+ ["response-content-type", "content-type"],
10228
+ ["response-expires", "expires"]
10229
+ ];
10230
+ var CHECKSUM_HEADER = /^x-amz-checksum-(?!algorithm$|type$)/;
10231
+ var hexBytes = (value) => Uint8Array.from([...value.matchAll(/../g)].map((match2) => Number.parseInt(match2[0], 16)));
9973
10232
  var awsEncode = (value) => encodeURIComponent(value).replace(
9974
10233
  /[!'()*]/g,
9975
10234
  (char) => `%${char.charCodeAt(0).toString(16).toUpperCase()}`
@@ -10006,7 +10265,7 @@ var S3API = class {
10006
10265
  const object = {
10007
10266
  bucket: input.bucket,
10008
10267
  key: input.key,
10009
- bytes: [...bytes],
10268
+ bytes,
10010
10269
  etag: input.etag ?? await digest(bytes),
10011
10270
  lastModified: input.lastModified ?? this.now(),
10012
10271
  metadata: input.metadata,
@@ -10031,10 +10290,11 @@ var S3API = class {
10031
10290
  this.state.objects.insert(this.state.objectId(input.bucket, input.key), object);
10032
10291
  return object;
10033
10292
  }
10034
- error(code, message, status, resource) {
10293
+ error(code, message, status, resource, extra = {}) {
10035
10294
  const id = requestId(this.options.random);
10295
+ const fields = Object.entries(extra).map(([name2, value]) => `<${name2}>${xmlEscape(value)}</${name2}>`).join("");
10036
10296
  return xml(
10037
- `<Error><Code>${code}</Code><Message>${xmlEscape(message)}</Message><Resource>${xmlEscape(resource)}</Resource><RequestId>${id}</RequestId><HostId>mockingbird</HostId></Error>`,
10297
+ `<Error><Code>${code}</Code><Message>${xmlEscape(message)}</Message>${fields}<Resource>${xmlEscape(resource)}</Resource><RequestId>${id}</RequestId><HostId>mockingbird</HostId></Error>`,
10038
10298
  status,
10039
10299
  { "x-amz-request-id": id, "x-amz-id-2": "mockingbird" }
10040
10300
  );
@@ -10049,7 +10309,7 @@ var S3API = class {
10049
10309
  occurredAt: new Date(this.now()).toISOString()
10050
10310
  });
10051
10311
  }
10052
- async verifyPresign(request, url) {
10312
+ async verifyPresign(request, url, path) {
10053
10313
  if (!url.searchParams.has("X-Amz-Signature")) return;
10054
10314
  const algorithm = url.searchParams.get("X-Amz-Algorithm");
10055
10315
  const credential = url.searchParams.get("X-Amz-Credential") ?? "";
@@ -10059,15 +10319,10 @@ var S3API = class {
10059
10319
  const expires = Number(url.searchParams.get("X-Amz-Expires"));
10060
10320
  const parts = credential.split("/");
10061
10321
  if (algorithm !== "AWS4-HMAC-SHA256" || parts.length !== 5 || parts[3] !== "s3" || parts[4] !== "aws4_request")
10062
- return this.error(
10063
- "AuthorizationQueryParametersError",
10064
- "Invalid credential scope",
10065
- 400,
10066
- url.pathname
10067
- );
10322
+ return this.error("AuthorizationQueryParametersError", "Invalid credential scope", 400, path);
10068
10323
  const [accessKey, date, region] = parts;
10069
10324
  const secret = (this.options.credentials ?? { fixture: "fixture" })[accessKey];
10070
- if (!secret) return this.error("AccessDenied", "Invalid access key", 403, url.pathname);
10325
+ if (!secret) return this.error("AccessDenied", "Invalid access key", 403, path);
10071
10326
  const signedAt = /^\d{8}T\d{6}Z$/.test(stamp) ? Date.UTC(
10072
10327
  Number(stamp.slice(0, 4)),
10073
10328
  Number(stamp.slice(4, 6)) - 1,
@@ -10077,15 +10332,10 @@ var S3API = class {
10077
10332
  Number(stamp.slice(13, 15))
10078
10333
  ) : Number.NaN;
10079
10334
  if (!Number.isFinite(signedAt) || !Number.isFinite(expires) || expires < 1 || expires > 604800 || !Number.isInteger(expires) || signedAt > this.now() + 9e5 || this.now() > signedAt + expires * 1e3)
10080
- return this.error("AccessDenied", "Request has expired", 403, url.pathname);
10335
+ return this.error("AccessDenied", "Request has expired", 403, path);
10081
10336
  const names = signedHeaders.split(";").filter(Boolean);
10082
10337
  if (!names.includes("host"))
10083
- return this.error(
10084
- "SignatureDoesNotMatch",
10085
- "SignedHeaders must include host",
10086
- 403,
10087
- url.pathname
10088
- );
10338
+ return this.error("SignatureDoesNotMatch", "SignedHeaders must include host", 403, path);
10089
10339
  const canonicalHeaders = names.map(
10090
10340
  (name2) => `${name2}:${name2 === "host" ? url.host : (request.headers.get(name2) ?? "").trim().replace(/\s+/g, " ")}
10091
10341
  `
@@ -10093,7 +10343,7 @@ var S3API = class {
10093
10343
  const canonicalQuery = [...url.searchParams].filter(([name2]) => name2 !== "X-Amz-Signature").map(([name2, value]) => `${awsEncode(name2)}=${awsEncode(value)}`).sort().join("&");
10094
10344
  const canonical = [
10095
10345
  request.method,
10096
- url.pathname,
10346
+ path,
10097
10347
  canonicalQuery,
10098
10348
  canonicalHeaders,
10099
10349
  signedHeaders,
@@ -10110,7 +10360,7 @@ var S3API = class {
10110
10360
  "SignatureDoesNotMatch",
10111
10361
  "The request signature we calculated does not match the signature you provided",
10112
10362
  403,
10113
- url.pathname
10363
+ path
10114
10364
  );
10115
10365
  return void 0;
10116
10366
  }
@@ -10132,14 +10382,22 @@ var S3API = class {
10132
10382
  headers.set(`x-amz-meta-${name2}`, value);
10133
10383
  return headers;
10134
10384
  }
10135
- async fetch(request) {
10385
+ async fetch(input) {
10136
10386
  await this.ready;
10387
+ const bases = this.options.virtualHosts ?? DEFAULT_VIRTUAL_HOSTS;
10388
+ const request = toPathStyle(input, bases);
10137
10389
  const url = new URL(request.url);
10138
- const invalidPresign = await this.verifyPresign(request, url);
10139
- if (invalidPresign) return invalidPresign;
10140
10390
  const slash = url.pathname.indexOf("/", 1);
10141
10391
  const bucket = decodeURIComponent(url.pathname.slice(1, slash < 0 ? void 0 : slash));
10142
10392
  const key = slash < 0 ? "" : decodeURIComponent(url.pathname.slice(slash + 1));
10393
+ const signedPath = virtualBucket(url.host, bases) !== void 0 && request.headers.get(VIRTUAL_BUCKET_HEADER) === bucket ? url.pathname.slice(bucket.length + 1) || "/" : url.pathname;
10394
+ if (request.method === "OPTIONS" && bucket) return this.preflight(bucket, request, url);
10395
+ const response = await this.handle(request, url, bucket, key, signedPath);
10396
+ return this.withCors(bucket, request, response);
10397
+ }
10398
+ async handle(request, url, bucket, key, signedPath) {
10399
+ const invalidPresign = await this.verifyPresign(request, url, signedPath);
10400
+ if (invalidPresign) return invalidPresign;
10143
10401
  if (!bucket) {
10144
10402
  if (request.method === "GET")
10145
10403
  return xml(
@@ -10155,7 +10413,9 @@ var S3API = class {
10155
10413
  return new Response(null, { status: 200, headers: { location: `/${bucket}` } });
10156
10414
  }
10157
10415
  if (!exists)
10158
- return this.error("NoSuchBucket", "The specified bucket does not exist", 404, url.pathname);
10416
+ return this.error("NoSuchBucket", "The specified bucket does not exist", 404, url.pathname, {
10417
+ BucketName: bucket
10418
+ });
10159
10419
  if (request.method === "HEAD" && !key)
10160
10420
  return new Response(null, { status: 200, headers: { "x-amz-bucket-region": "us-east-1" } });
10161
10421
  const config = await this.bucketConfiguration(bucket, key, request, url);
@@ -10217,6 +10477,14 @@ var S3API = class {
10217
10477
  if (request.method === "PUT") return this.put(bucket, key, request);
10218
10478
  if (request.method === "DELETE")
10219
10479
  return this.removeObject(bucket, key, url.searchParams.get("versionId"));
10480
+ const overrides = RESPONSE_OVERRIDES.filter(([param]) => url.searchParams.has(param));
10481
+ if (overrides.length && !request.headers.has("authorization") && !url.searchParams.has("X-Amz-Signature"))
10482
+ return this.error(
10483
+ "InvalidRequest",
10484
+ "Request specific response headers cannot be used for anonymous GET requests.",
10485
+ 400,
10486
+ url.pathname
10487
+ );
10220
10488
  const object = url.searchParams.has("versionId") ? this.state.versions.get(
10221
10489
  this.versionKey(bucket, key, url.searchParams.get("versionId"))
10222
10490
  ) : this.state.object(bucket, key);
@@ -10236,10 +10504,52 @@ var S3API = class {
10236
10504
  const condition = this.conditions(object, request);
10237
10505
  if (condition) return condition;
10238
10506
  if (request.method === "HEAD")
10239
- return new Response(null, { status: 200, headers: this.objectHeaders(object) });
10240
- if (request.method === "GET") return this.get(object, request, url.pathname);
10507
+ return this.overridden(
10508
+ new Response(null, { status: 200, headers: this.objectHeaders(object) }),
10509
+ url,
10510
+ overrides
10511
+ );
10512
+ if (request.method === "GET")
10513
+ return this.overridden(this.get(object, request, url.pathname), url, overrides);
10241
10514
  return this.error("MethodNotAllowed", "The specified method is not allowed", 405, url.pathname);
10242
10515
  }
10516
+ /** `response-*` query parameters replace the stored headers on a 200 or 206. */
10517
+ overridden(response, url, overrides) {
10518
+ if (response.status === 200 || response.status === 206)
10519
+ for (const [param, header] of overrides) {
10520
+ const value = url.searchParams.get(param);
10521
+ if (value) response.headers.set(header, value);
10522
+ }
10523
+ return response;
10524
+ }
10525
+ /**
10526
+ * `x-amz-copy-source-if-*`, evaluated as the CopyObject reference describes: a true if-match
10527
+ * overrides a false if-unmodified-since, and a failed condition is always 412, never 304.
10528
+ */
10529
+ copyConditions(source, request) {
10530
+ const unquote = (value) => value.trim().replace(/^W\//, "").replace(/^"|"$/g, "");
10531
+ const etags = (header) => header === null ? void 0 : header.split(",").map(unquote);
10532
+ const have = unquote(source.etag);
10533
+ const hit = (list2) => list2?.includes("*") || list2?.includes(have);
10534
+ const modified = Math.floor(source.lastModified / 1e3) * 1e3;
10535
+ const date = (name2) => Date.parse(request.headers.get(name2) ?? "");
10536
+ const ifMatch = etags(request.headers.get("x-amz-copy-source-if-match"));
10537
+ const ifNoneMatch = etags(request.headers.get("x-amz-copy-source-if-none-match"));
10538
+ const since = date("x-amz-copy-source-if-modified-since");
10539
+ const until = date("x-amz-copy-source-if-unmodified-since");
10540
+ const failed = (name2) => this.error(
10541
+ "PreconditionFailed",
10542
+ "At least one of the pre-conditions you specified did not hold",
10543
+ 412,
10544
+ new URL(request.url).pathname,
10545
+ { Condition: name2 }
10546
+ );
10547
+ if (ifMatch && !hit(ifMatch)) return failed("x-amz-copy-source-If-Match");
10548
+ if (!ifMatch && modified > until) return failed("x-amz-copy-source-If-Unmodified-Since");
10549
+ if (ifNoneMatch && hit(ifNoneMatch)) return failed("x-amz-copy-source-If-None-Match");
10550
+ if (!ifNoneMatch && modified <= since) return failed("x-amz-copy-source-If-Modified-Since");
10551
+ return void 0;
10552
+ }
10243
10553
  async put(bucket, key, request) {
10244
10554
  const condition = this.conditions(this.state.object(bucket, key), request, true);
10245
10555
  if (condition) return condition;
@@ -10255,11 +10565,13 @@ var S3API = class {
10255
10565
  )
10256
10566
  ) : this.state.object(sourceBucket, sourceKey.join("/")) : void 0;
10257
10567
  if (!source) return this.error("NoSuchKey", "The specified key does not exist.", 404, copy2);
10568
+ const sourceCondition = this.copyConditions(source, request);
10569
+ if (sourceCondition) return sourceCondition;
10258
10570
  const stored = await this.putSeed({
10259
10571
  ...source,
10260
10572
  bucket,
10261
10573
  key,
10262
- body: new Uint8Array(source.bytes),
10574
+ body: source.bytes,
10263
10575
  metadata: request.headers.get("x-amz-metadata-directive") === "REPLACE" ? metadata(request.headers) : source.metadata,
10264
10576
  lastModified: this.now(),
10265
10577
  ...request.headers.get("x-amz-metadata-directive") === "REPLACE" ? {
@@ -10273,20 +10585,16 @@ var S3API = class {
10273
10585
  `<CopyObjectResult><LastModified>${new Date(stored.lastModified).toISOString()}</LastModified><ETag>${stored.etag}</ETag></CopyObjectResult>`
10274
10586
  );
10275
10587
  }
10276
- const bytes = new Uint8Array(await request.arrayBuffer());
10277
- const checksumError = this.validateChecksums(bytes, request);
10278
- if (checksumError) return checksumError;
10588
+ const received = await this.payload(request);
10589
+ if (received instanceof Response) return received;
10590
+ const { bytes, checksums } = received;
10279
10591
  const object = await this.putSeed({
10280
10592
  bucket,
10281
10593
  key,
10282
10594
  body: bytes,
10283
10595
  metadata: metadata(request.headers),
10284
10596
  tags: Object.fromEntries(new URLSearchParams(request.headers.get("x-amz-tagging") ?? "")),
10285
- checksums: Object.fromEntries(
10286
- [...request.headers].filter(
10287
- ([name2]) => name2.startsWith("x-amz-checksum-") && name2 !== "x-amz-checksum-algorithm"
10288
- )
10289
- ),
10597
+ checksums,
10290
10598
  storageClass: request.headers.get("x-amz-storage-class") ?? "STANDARD",
10291
10599
  ...request.headers.get("content-type") ? { contentType: request.headers.get("content-type") } : {},
10292
10600
  ...request.headers.get("cache-control") ? { cacheControl: request.headers.get("cache-control") } : {},
@@ -10382,14 +10690,14 @@ var S3API = class {
10382
10690
  400,
10383
10691
  url.pathname
10384
10692
  );
10385
- const bytes = new Uint8Array(await request.arrayBuffer());
10386
- const checksumError = this.validateChecksums(bytes, request);
10387
- if (checksumError) return checksumError;
10693
+ const received = await this.payload(request);
10694
+ if (received instanceof Response) return received;
10695
+ const { bytes } = received;
10388
10696
  const etag = await digest(bytes);
10389
10697
  this.state.parts.insert(`${id}:${partNumber}`, {
10390
10698
  uploadId: id,
10391
10699
  partNumber,
10392
- bytes: [...bytes],
10700
+ bytes,
10393
10701
  etag
10394
10702
  });
10395
10703
  return new Response(null, { status: 200, headers: { etag } });
@@ -10444,7 +10752,12 @@ var S3API = class {
10444
10752
  );
10445
10753
  const condition = this.conditions(this.state.object(bucket, key), request, true);
10446
10754
  if (condition) return condition;
10447
- const bytes = new Uint8Array(parts.flatMap((part) => part.bytes));
10755
+ const bytes = new Uint8Array(parts.reduce((total, part) => total + part.bytes.length, 0));
10756
+ let offset = 0;
10757
+ for (const part of parts) {
10758
+ bytes.set(part.bytes, offset);
10759
+ offset += part.bytes.length;
10760
+ }
10448
10761
  const hashes = Uint8Array.from(
10449
10762
  parts.flatMap(
10450
10763
  (part) => [...part.etag.replace(/"/g, "").matchAll(/../g)].map(
@@ -10475,7 +10788,7 @@ var S3API = class {
10475
10788
  let input;
10476
10789
  try {
10477
10790
  input = awsParseXml(await request.text()).Delete;
10478
- if (!input || !input.Object) throw new TypeError();
10791
+ if (!input?.Object) throw new TypeError();
10479
10792
  } catch {
10480
10793
  return this.error("MalformedXML", "Malformed XML", 400, `/${bucket}`);
10481
10794
  }
@@ -10527,7 +10840,7 @@ var S3API = class {
10527
10840
  const marker = {
10528
10841
  bucket,
10529
10842
  key,
10530
- bytes: [],
10843
+ bytes: new Uint8Array(),
10531
10844
  etag: "",
10532
10845
  lastModified: this.now(),
10533
10846
  metadata: {},
@@ -10546,16 +10859,16 @@ var S3API = class {
10546
10859
  return new Response(null, { status: 204, headers });
10547
10860
  }
10548
10861
  conditions(object, request, write = false) {
10549
- const matches2 = (header) => header !== null && (header === "*" || header.split(",").some((value) => value.trim() === object?.etag));
10862
+ const matches3 = (header) => header !== null && (header === "*" || header.split(",").some((value) => value.trim() === object?.etag));
10550
10863
  const exists = object && !object.deleteMarker;
10551
- if (request.headers.has("if-match") && (!exists || !matches2(request.headers.get("if-match"))))
10864
+ if (request.headers.has("if-match") && (!exists || !matches3(request.headers.get("if-match"))))
10552
10865
  return this.error(
10553
10866
  "PreconditionFailed",
10554
10867
  "At least one precondition failed",
10555
10868
  412,
10556
10869
  new URL(request.url).pathname
10557
10870
  );
10558
- if (exists && matches2(request.headers.get("if-none-match")))
10871
+ if (exists && matches3(request.headers.get("if-none-match")))
10559
10872
  return write ? this.error(
10560
10873
  "PreconditionFailed",
10561
10874
  "At least one precondition failed",
@@ -10578,23 +10891,69 @@ var S3API = class {
10578
10891
  }
10579
10892
  return void 0;
10580
10893
  }
10581
- validateChecksums(bytes, request) {
10582
- const md5 = request.headers.get("content-md5");
10583
- const actual = btoa(
10584
- String.fromCharCode(
10585
- ...Uint8Array.from(
10586
- [...awsMd5(bytes).matchAll(/../g)].map((match2) => Number.parseInt(match2[0], 16))
10587
- )
10588
- )
10894
+ /**
10895
+ * The object bytes of a PutObject or UploadPart: an `aws-chunked` stream is decoded (the framing
10896
+ * and trailers are not part of the object), the decoded length and every supplied checksum are
10897
+ * verified, and the checksums to keep come back as the `x-amz-checksum-*` headers they were.
10898
+ */
10899
+ async payload(request) {
10900
+ const path = new URL(request.url).pathname;
10901
+ const chunked = isAwsChunked(request.headers);
10902
+ const declared = Number(
10903
+ (chunked ? request.headers.get("x-amz-decoded-content-length") : null) ?? request.headers.get("content-length")
10589
10904
  );
10590
- if (md5 && md5 !== actual)
10905
+ if (declared > S3_MAX_UPLOAD_BYTES)
10906
+ return this.error(
10907
+ "EntityTooLarge",
10908
+ "Your proposed upload exceeds the maximum allowed size",
10909
+ 400,
10910
+ path,
10911
+ { ProposedSize: String(declared), MaxSizeAllowed: String(S3_MAX_UPLOAD_BYTES) }
10912
+ );
10913
+ let bytes = new Uint8Array(await request.arrayBuffer());
10914
+ const checksums = Object.fromEntries(
10915
+ [...request.headers].filter(([name2]) => CHECKSUM_HEADER.test(name2))
10916
+ );
10917
+ if (chunked) {
10918
+ const decoded = decodeAwsChunked(bytes);
10919
+ if (!decoded)
10920
+ return this.error(
10921
+ "IncompleteBody",
10922
+ "The aws-chunked request body is malformed or ends before its last chunk",
10923
+ 400,
10924
+ path
10925
+ );
10926
+ bytes = decoded.payload;
10927
+ const length = request.headers.get("x-amz-decoded-content-length");
10928
+ if (length !== null && Number(length) !== bytes.length)
10929
+ return this.error(
10930
+ "IncompleteBody",
10931
+ "You did not provide the number of bytes specified by the x-amz-decoded-content-length HTTP header",
10932
+ 400,
10933
+ path
10934
+ );
10935
+ for (const [name2, value] of Object.entries(decoded.trailers))
10936
+ if (CHECKSUM_HEADER.test(name2)) checksums[name2] = value;
10937
+ }
10938
+ const md5 = request.headers.get("content-md5");
10939
+ if (md5 && md5 !== btoa(String.fromCharCode(...hexBytes(awsMd5(bytes)))))
10591
10940
  return this.error(
10592
10941
  "BadDigest",
10593
10942
  "The Content-MD5 you specified did not match what we received",
10594
10943
  400,
10595
- new URL(request.url).pathname
10944
+ path
10596
10945
  );
10597
- return void 0;
10946
+ for (const [name2, expected] of Object.entries(checksums)) {
10947
+ const algorithm = name2.slice("x-amz-checksum-".length);
10948
+ if (CHECKSUM_ALGORITHMS.includes(algorithm) && await checksum(algorithm, bytes) !== expected)
10949
+ return this.error(
10950
+ "BadDigest",
10951
+ `The ${algorithm.toUpperCase()} you specified did not match the calculated checksum.`,
10952
+ 400,
10953
+ path
10954
+ );
10955
+ }
10956
+ return { bytes, checksums };
10598
10957
  }
10599
10958
  async bucketConfiguration(bucket, key, request, url) {
10600
10959
  if (key) return void 0;
@@ -10634,6 +10993,10 @@ var S3API = class {
10634
10993
  }
10635
10994
  if (kind === "versioning" && !/<Status>(Enabled|Suspended)<\/Status>/.test(body))
10636
10995
  return this.error("MalformedXML", "Invalid versioning status", 400, url.pathname);
10996
+ if (kind === "cors") {
10997
+ const invalid = invalidCors(parseCors(body));
10998
+ if (invalid) return this.error(invalid[0], invalid[1], 400, url.pathname);
10999
+ }
10637
11000
  this.state.configurations.insert(id, { body });
10638
11001
  return new Response(null, { status: 200 });
10639
11002
  }
@@ -10651,6 +11014,68 @@ var S3API = class {
10651
11014
  }
10652
11015
  return this.error("MethodNotAllowed", "Method not allowed", 405, url.pathname);
10653
11016
  }
11017
+ corsRules(bucket) {
11018
+ const stored = this.state.configurations.get(`${bucket}:cors`);
11019
+ return stored ? parseCors(stored.body) : void 0;
11020
+ }
11021
+ /**
11022
+ * The browser preflight (`OPTIONS` on a bucket or object URL). S3 refuses one it cannot match
11023
+ * with 403 AccessForbidden "CORSResponse: ..." and no `Access-Control-*` headers.
11024
+ */
11025
+ preflight(bucket, request, url) {
11026
+ if (!this.state.buckets.has(bucket))
11027
+ return this.error("NoSuchBucket", "The specified bucket does not exist", 404, url.pathname, {
11028
+ BucketName: bucket
11029
+ });
11030
+ const origin = request.headers.get("origin");
11031
+ if (!origin)
11032
+ return this.error(
11033
+ "BadRequest",
11034
+ "Insufficient information. Origin request header needed.",
11035
+ 400,
11036
+ url.pathname
11037
+ );
11038
+ const method = request.headers.get("access-control-request-method");
11039
+ if (!method || !CORS_METHODS.includes(method))
11040
+ return this.error(
11041
+ "BadRequest",
11042
+ `Invalid Access-Control-Request-Method: ${method}`,
11043
+ 400,
11044
+ url.pathname
11045
+ );
11046
+ const requested = (request.headers.get("access-control-request-headers") ?? "").split(",").map((name2) => name2.trim().toLowerCase()).filter(Boolean);
11047
+ const rules = this.corsRules(bucket);
11048
+ const refuse = (message) => this.error("AccessForbidden", `CORSResponse: ${message}`, 403, url.pathname, {
11049
+ Method: method,
11050
+ ResourceType: url.pathname.indexOf("/", 1) < 0 ? "BUCKET" : "OBJECT"
11051
+ });
11052
+ if (!rules) return refuse("CORS is not enabled for this bucket.");
11053
+ const rule = matchRule(rules, origin, method, requested);
11054
+ if (!rule)
11055
+ return refuse(
11056
+ "This CORS request is not allowed. This is usually because the evalution of Origin, request method / Access-Control-Request-Method or Access-Control-Request-Headers are not whitelisted by the resource's CORS spec."
11057
+ );
11058
+ return new Response(null, {
11059
+ status: 200,
11060
+ headers: {
11061
+ ...corsHeaders(rule, origin),
11062
+ ...requested.length ? { "access-control-allow-headers": requested.join(", ") } : {},
11063
+ ...rule.maxAge ? { "access-control-max-age": rule.maxAge } : {},
11064
+ vary: PREFLIGHT_VARY
11065
+ }
11066
+ });
11067
+ }
11068
+ /** A matching rule adds the `Access-Control-*` headers to an actual cross-origin response. */
11069
+ withCors(bucket, request, response) {
11070
+ const origin = request.headers.get("origin");
11071
+ if (!origin || !bucket || !this.state.buckets.has(bucket)) return response;
11072
+ const rule = matchRule(this.corsRules(bucket) ?? [], origin, request.method);
11073
+ if (!rule) return response;
11074
+ for (const [name2, value] of Object.entries(corsHeaders(rule, origin)))
11075
+ response.headers.set(name2, value);
11076
+ response.headers.append("vary", "Origin");
11077
+ return response;
11078
+ }
10654
11079
  async objectTagging(bucket, key, request, url) {
10655
11080
  const object = url.searchParams.has("versionId") ? this.state.versions.get(
10656
11081
  this.versionKey(bucket, key, url.searchParams.get("versionId"))
@@ -10668,10 +11093,10 @@ var S3API = class {
10668
11093
  try {
10669
11094
  const tagging = awsParseXml(await request.text()).Tagging;
10670
11095
  const value = tagging?.TagSet?.Tag;
10671
- const list = Array.isArray(value) ? value : value ? [value] : [];
10672
- if (list.length > 10 || list.some((tag) => typeof tag.Key !== "string" || typeof tag.Value !== "string") || new Set(list.map((tag) => tag.Key)).size !== list.length)
11096
+ const list2 = Array.isArray(value) ? value : value ? [value] : [];
11097
+ if (list2.length > 10 || list2.some((tag) => typeof tag.Key !== "string" || typeof tag.Value !== "string") || new Set(list2.map((tag) => tag.Key)).size !== list2.length)
10673
11098
  throw new TypeError();
10674
- tags = Object.fromEntries(list.map((tag) => [tag.Key, tag.Value]));
11099
+ tags = Object.fromEntries(list2.map((tag) => [tag.Key, tag.Value]));
10675
11100
  } catch {
10676
11101
  return this.error("MalformedXML", "Invalid tag set", 400, url.pathname);
10677
11102
  }
@@ -10737,7 +11162,8 @@ export {
10737
11162
  S3_PRESETS,
10738
11163
  createRuntime2 as createRuntime,
10739
11164
  S3_NAMESPACE,
11165
+ S3_MAX_UPLOAD_BYTES,
10740
11166
  accessKeyCredential,
10741
11167
  S3API
10742
11168
  };
10743
- //# sourceMappingURL=chunk-XFKAVTM2.js.map
11169
+ //# sourceMappingURL=chunk-NNRVXV6X.js.map