wao 0.24.2 → 0.25.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/cjs/signer.js CHANGED
@@ -4,9 +4,8 @@ Object.defineProperty(exports, "__esModule", {
4
4
  value: true
5
5
  });
6
6
  exports.createRequest = createRequest;
7
- exports.extractPublicKeyFromHeaders = extractPublicKeyFromHeaders;
7
+ exports.hbEncodeValue = hbEncodeValue;
8
8
  exports.send = send;
9
- exports.verify = verify;
10
9
  var _base64url = _interopRequireDefault(require("base64url"));
11
10
  var _crypto = _interopRequireDefault(require("crypto"));
12
11
  var _httpMessageSignatures = require("http-message-signatures");
@@ -26,7 +25,6 @@ function _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLim
26
25
  function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
27
26
  function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t["return"] && (u = t["return"](), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
28
27
  function _arrayWithHoles(r) { if (Array.isArray(r)) return r; }
29
- function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
30
28
  function asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); }
31
29
  function _asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; }
32
30
  function _toConsumableArray(r) { return _arrayWithoutHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableSpread(); }
@@ -35,27 +33,63 @@ function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r)
35
33
  function _iterableToArray(r) { if ("undefined" != typeof Symbol && null != r[Symbol.iterator] || null != r["@@iterator"]) return Array.from(r); }
36
34
  function _arrayWithoutHoles(r) { if (Array.isArray(r)) return _arrayLikeToArray(r); }
37
35
  function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }
36
+ function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
38
37
  var verifyMessage = _httpMessageSignatures.httpbis.verifyMessage;
39
38
  var augmentHeaders = _httpMessageSignatures.httpbis.augmentHeaders,
40
39
  createSignatureBase = _httpMessageSignatures.httpbis.createSignatureBase,
41
40
  createSigningParameters = _httpMessageSignatures.httpbis.createSigningParameters,
42
41
  formatSignatureBase = _httpMessageSignatures.httpbis.formatSignatureBase;
43
-
44
- /**
45
- * Convert value to Buffer
46
- */
42
+ function hbEncodeValue(value) {
43
+ if (isBytes(value)) {
44
+ if (value.byteLength === 0) return hbEncodeValue("");
45
+ return [undefined, value];
46
+ }
47
+ if (typeof value === "string") {
48
+ if (value.length === 0) return ["empty-binary", undefined];
49
+ return [undefined, value];
50
+ }
51
+ if (Array.isArray(value)) {
52
+ if (value.length === 0) return ["empty-list", undefined];
53
+ if (value.some(isPojo)) {
54
+ throw new Error("Array with objects should have been lifted: ".concat(JSON.stringify(value)));
55
+ }
56
+ var encoded = value.map(function (v) {
57
+ if (typeof v === "string") {
58
+ if (v === "") return "\"(ao-type-empty-binary) \"";
59
+ var escaped = v.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
60
+ return "\"".concat(escaped, "\"");
61
+ } else if (typeof v === "number") return String(v);else if (typeof v === "boolean") return v ? "?1" : "?0";else if (_typeof(v) === "symbol") {
62
+ var desc = v.description || "symbol";
63
+ var _escaped = desc.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
64
+ return "\"(ao-type-atom) ".concat(_escaped, "\"");
65
+ } else if (v === null) return "\"(ao-type-atom) null\"";else if (v === undefined) return "\"(ao-type-atom) undefined\"";else if (Array.isArray(v) && v.length === 0) {
66
+ return "\"(ao-type-empty-list) \"";
67
+ }
68
+ return "\"".concat(String(v), "\"");
69
+ }).join(", ");
70
+ return ["list", encoded];
71
+ }
72
+ if (typeof value === "number") {
73
+ if (!Number.isInteger(value)) return ["float", "".concat(value)];
74
+ return ["integer", String(value)];
75
+ }
76
+ if (typeof value === "boolean") {
77
+ return ["atom", "\"".concat(value ? "true" : "false", "\"")];
78
+ }
79
+ if (_typeof(value) === "symbol") {
80
+ var desc = value.description || "symbol";
81
+ return ["atom", "\"".concat(desc, "\"")];
82
+ }
83
+ if (value === null) return ["atom", "\"null\""];
84
+ if (value === undefined) return ["atom", "\"undefined\""];
85
+ throw new Error("Cannot encode value: ".concat(String(value)));
86
+ }
47
87
  var toView = function toView(value) {
48
88
  if (ArrayBuffer.isView(value)) {
49
89
  return Buffer.from(value.buffer, value.byteOffset, value.byteLength);
50
- } else if (typeof value === "string") {
51
- return _base64url["default"].toBuffer(value);
52
- }
90
+ } else if (typeof value === "string") return _base64url["default"].toBuffer(value);
53
91
  throw new Error("Value must be Uint8Array, ArrayBuffer, or base64url-encoded string");
54
92
  };
55
-
56
- /**
57
- * Generate HTTP signature name from address
58
- */
59
93
  var httpSigName = function httpSigName(address) {
60
94
  var decoded = _base64url["default"].toBuffer(address);
61
95
  var hexString = _toConsumableArray(decoded.subarray(1, 9)).map(function (_byte) {
@@ -63,26 +97,23 @@ var httpSigName = function httpSigName(address) {
63
97
  }).join("");
64
98
  return "http-sig-".concat(hexString);
65
99
  };
66
-
67
- /**
68
- * Join URL parts
69
- */
70
100
  var joinUrl = function joinUrl(_ref) {
71
101
  var url = _ref.url,
72
102
  path = _ref.path;
73
- // If path is already a full URL, return it as-is
74
103
  if (path.startsWith("http://") || path.startsWith("https://")) {
75
104
  return path;
76
105
  }
77
-
78
- // Otherwise, join the base URL with the path
79
106
  return url.endsWith("/") ? url.slice(0, -1) + path : url + path;
80
107
  };
81
-
82
- /**
83
- * HyperBEAM Encoding Logic
84
- */
85
108
  var MAX_HEADER_LENGTH = 4096;
109
+ function encode_body_keys(bodyKeys) {
110
+ if (!bodyKeys || bodyKeys.length === 0) return "";
111
+ var items = bodyKeys.map(function (key) {
112
+ return "\"".concat(key, "\"");
113
+ });
114
+ var result = items.join(", ");
115
+ return result;
116
+ }
86
117
  function hasNewline(_x) {
87
118
  return _hasNewline.apply(this, arguments);
88
119
  }
@@ -145,43 +176,6 @@ function isBytes(value) {
145
176
  function isPojo(value) {
146
177
  return !isBytes(value) && !Array.isArray(value) && !(value instanceof Blob) && _typeof(value) === "object" && value !== null;
147
178
  }
148
- function hbEncodeValue(value) {
149
- if (isBytes(value)) {
150
- if (value.byteLength === 0) return hbEncodeValue("");
151
- return [undefined, value];
152
- }
153
- if (typeof value === "string") {
154
- if (value.length === 0) return [undefined, "empty-binary"];
155
- return [undefined, value];
156
- }
157
- if (Array.isArray(value)) {
158
- if (value.length === 0) return ["empty-list", undefined];
159
- // For structured fields, just join the string values
160
- var encoded = value.map(function (v) {
161
- if (typeof v === "string") {
162
- // Escape quotes and backslashes
163
- var escaped = v.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
164
- return "\"".concat(escaped, "\"");
165
- } else if (typeof v === "number") {
166
- // Numbers should be encoded as bare items, not strings
167
- return String(v);
168
- } else if (typeof v === "boolean") {
169
- // Booleans as structured field tokens
170
- return v ? "?1" : "?0";
171
- }
172
- return "\"".concat(String(v), "\"");
173
- }).join(", ");
174
- return ["list", encoded];
175
- }
176
- if (typeof value === "number") {
177
- if (!Number.isInteger(value)) return ["float", "".concat(value)];
178
- return ["integer", String(value)];
179
- }
180
- if (_typeof(value) === "symbol") {
181
- return ["atom", value.description];
182
- }
183
- throw new Error("Cannot encode value: ".concat(value.toString()));
184
- }
185
179
  function hbEncodeLift(obj) {
186
180
  var parent = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : "";
187
181
  var top = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
@@ -189,122 +183,159 @@ function hbEncodeLift(obj) {
189
183
  var _ref3 = _slicedToArray(_ref2, 2),
190
184
  key = _ref3[0],
191
185
  value = _ref3[1];
192
- // For nested paths, preserve casing. For top-level, also preserve casing
193
186
  var storageKey = parent ? "".concat(parent, "/").concat(key) : key;
194
-
195
- // skip nullish values
196
- if (value == null) return acc;
197
-
198
- // list of objects
199
- if (Array.isArray(value) && value.some(isPojo)) {
200
- value = value.reduce(function (indexedObj, v, idx) {
201
- return Object.assign(indexedObj, _defineProperty({}, idx, v));
202
- }, {});
187
+ if (value == null) {
188
+ var _hbEncodeValue = hbEncodeValue(value),
189
+ _hbEncodeValue2 = _slicedToArray(_hbEncodeValue, 2),
190
+ _type = _hbEncodeValue2[0],
191
+ _encoded = _hbEncodeValue2[1];
192
+ if (_encoded !== undefined) acc[0][key] = _encoded;
193
+ if (_type) acc[1][key.toLowerCase()] = _type;
194
+ return acc;
195
+ }
196
+ if (Array.isArray(value)) {
197
+ var hasObjects = value.some(isPojo);
198
+ var hasBinary = value.some(isBytes);
199
+ if (hasObjects || hasBinary) {
200
+ var indexedObj = value.reduce(function (obj, v, idx) {
201
+ return Object.assign(obj, _defineProperty({}, idx, v));
202
+ }, {});
203
+ acc[1][key.toLowerCase()] = "list";
204
+ hbEncodeLift(indexedObj, storageKey, top);
205
+ return acc;
206
+ } else {
207
+ var _hbEncodeValue3 = hbEncodeValue(value),
208
+ _hbEncodeValue4 = _slicedToArray(_hbEncodeValue3, 2),
209
+ _type2 = _hbEncodeValue4[0],
210
+ _encoded2 = _hbEncodeValue4[1];
211
+ if (_type2) acc[1][key.toLowerCase()] = _type2;
212
+ if (_encoded2 !== undefined) acc[0][key] = _encoded2;
213
+ return acc;
214
+ }
203
215
  }
204
-
205
- // Store the original value for reference
206
216
  var originalValue = value;
207
-
208
- // first/second lift object - handle nested objects
209
217
  if (isPojo(value)) {
210
- // Check if this object has any nested objects or arrays with objects
218
+ if (Object.keys(value).length === 0) {
219
+ acc[1][key.toLowerCase()] = "empty-message";
220
+ return acc;
221
+ }
211
222
  var hasComplexValues = Object.values(value).some(function (v) {
212
223
  return isPojo(v) || Array.isArray(v) && v.some(function (item) {
213
224
  return isPojo(item);
214
225
  });
215
226
  });
216
227
  if (!hasComplexValues) {
217
- // Simple flat object - can be encoded as structured field dictionary
218
228
  var items = [];
229
+ var hasAnyNonEmptyValues = Object.values(value).some(function (v) {
230
+ return !(v === null || v === undefined || v === "" || Array.isArray(v) && v.length === 0 || isPojo(v) && Object.keys(v).length === 0);
231
+ });
219
232
  Object.entries(value).forEach(function (_ref4) {
220
233
  var _ref5 = _slicedToArray(_ref4, 2),
221
234
  k = _ref5[0],
222
235
  v = _ref5[1];
223
236
  var subKey = k.toLowerCase();
224
- if (typeof v === "string") {
225
- var escaped = v.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
226
- items.push("".concat(subKey, "=\"").concat(escaped, "\""));
237
+ if (v === null) {
238
+ items.push("".concat(subKey, "=\"null\""));
239
+ acc[1]["".concat(key.toLowerCase(), "%2f").concat(subKey)] = "atom";
240
+ } else if (v === undefined) {
241
+ items.push("".concat(subKey, "=\"undefined\""));
242
+ acc[1]["".concat(key.toLowerCase(), "%2f").concat(subKey)] = "atom";
243
+ } else if (typeof v === "string") {
244
+ if (v === "") {
245
+ acc[1]["".concat(key.toLowerCase(), "%2f").concat(subKey)] = "empty-binary";
246
+ } else {
247
+ var escaped = v.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
248
+ items.push("".concat(subKey, "=\"").concat(escaped, "\""));
249
+ }
227
250
  } else if (typeof v === "number") {
228
251
  items.push("".concat(subKey, "=").concat(v));
229
252
  if (Number.isInteger(v)) {
230
- // Use URL-encoded forward slash separator
231
253
  acc[1]["".concat(key.toLowerCase(), "%2f").concat(subKey)] = "integer";
232
254
  } else {
233
255
  acc[1]["".concat(key.toLowerCase(), "%2f").concat(subKey)] = "float";
234
256
  }
235
257
  } else if (typeof v === "boolean") {
236
258
  items.push("".concat(subKey, "=").concat(v ? "?1" : "?0"));
259
+ acc[1]["".concat(key.toLowerCase(), "%2f").concat(subKey)] = "boolean";
260
+ } else if (_typeof(v) === "symbol") {
261
+ var desc = v.description || "symbol";
262
+ var _escaped2 = desc.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
263
+ items.push("".concat(subKey, "=\"").concat(_escaped2, "\""));
264
+ acc[1]["".concat(key.toLowerCase(), "%2f").concat(subKey)] = "atom";
237
265
  } else if (Array.isArray(v) && !v.some(function (item) {
238
266
  return isPojo(item);
239
267
  })) {
240
- // Simple array (no objects) - encode as structured field inner list
241
- var listItems = v.map(function (item) {
242
- if (typeof item === "string") {
243
- return "\"".concat(item.replace(/\\/g, "\\\\").replace(/"/g, '\\"'), "\"");
244
- } else if (typeof item === "number") {
245
- return String(item);
246
- } else if (typeof item === "boolean") {
247
- return item ? "?1" : "?0";
248
- } else {
249
- return "\"".concat(String(item), "\"");
250
- }
251
- });
252
- items.push("".concat(subKey, "=(").concat(listItems.join(" "), ")"));
268
+ if (v.length === 0) {
269
+ items.push("".concat(subKey, "=()"));
270
+ acc[1]["".concat(key.toLowerCase(), "%2f").concat(subKey)] = "empty-list";
271
+ } else {
272
+ var listItems = v.map(function (item) {
273
+ if (typeof item === "string") {
274
+ return "\"".concat(item.replace(/\\/g, "\\\\").replace(/"/g, '\\"'), "\"");
275
+ } else if (typeof item === "number") {
276
+ return String(item);
277
+ } else if (typeof item === "boolean") {
278
+ return item ? "?1" : "?0";
279
+ } else if (_typeof(item) === "symbol") {
280
+ var _desc = item.description || "symbol";
281
+ return "\"".concat(_desc.replace(/\\/g, "\\\\").replace(/"/g, '\\"'), "\"");
282
+ } else if (item === null) {
283
+ return "\"null\"";
284
+ } else if (item === undefined) {
285
+ return "\"undefined\"";
286
+ } else {
287
+ return "\"".concat(String(item), "\"");
288
+ }
289
+ });
290
+ items.push("".concat(subKey, "=(").concat(listItems.join(" "), ")"));
291
+ }
292
+ } else if (isPojo(v) && Object.keys(v).length === 0) {
293
+ items.push("".concat(subKey));
294
+ acc[1]["".concat(key.toLowerCase(), "%2f").concat(subKey)] = "empty-message";
253
295
  }
254
296
  });
255
297
  var encodedValue = items.join(", ");
256
- acc[0][key] = encodedValue;
257
- acc[1][key.toLowerCase()] = "map";
258
- } else {
259
- // Has nested objects - needs multipart encoding
260
- hbEncodeLift(value, storageKey, top);
261
- // Add the original object to flattened so it can be processed
262
- acc[0][key] = value;
263
- }
298
+ var hasOnlyEmptyValues = Object.entries(value).every(function (_ref6) {
299
+ var _ref7 = _slicedToArray(_ref6, 2),
300
+ k = _ref7[0],
301
+ v = _ref7[1];
302
+ return v === null || v === undefined || v === "" || Array.isArray(v) && v.length === 0 || isPojo(v) && Object.keys(v).length === 0;
303
+ });
304
+ if (!hasAnyNonEmptyValues) {
305
+ acc[1][key.toLowerCase()] = "map";
306
+ } else if (encodedValue === "") {
307
+ acc[1][key.toLowerCase()] = "empty-message";
308
+ } else {
309
+ acc[0][key] = encodedValue;
310
+ acc[1][key.toLowerCase()] = "map";
311
+ }
312
+ } else hbEncodeLift(value, storageKey, top);
264
313
  return acc;
265
314
  }
266
-
267
- // leaf encode value
268
- var _hbEncodeValue = hbEncodeValue(value),
269
- _hbEncodeValue2 = _slicedToArray(_hbEncodeValue, 2),
270
- type = _hbEncodeValue2[0],
271
- encoded = _hbEncodeValue2[1];
315
+ var _hbEncodeValue5 = hbEncodeValue(value),
316
+ _hbEncodeValue6 = _slicedToArray(_hbEncodeValue5, 2),
317
+ type = _hbEncodeValue6[0],
318
+ encoded = _hbEncodeValue6[1];
272
319
  if (encoded !== undefined) {
273
- // For binary data, check the byte length directly without converting to string
274
- var byteLength = isBytes(encoded) ? encoded.byteLength : Buffer.from(String(encoded)).byteLength;
275
- if (byteLength > MAX_HEADER_LENGTH) {
276
- // Store large values, but preserve binary data as-is
277
- top[storageKey] = isBytes(encoded) ? encoded : String(encoded);
278
- } else {
279
- // Preserve the original key casing
280
- var httpKey = key;
281
- if (type === "integer" && typeof value === "number") {
282
- acc[0][httpKey] = String(value);
283
- } else {
284
- acc[0][httpKey] = encoded;
285
- }
320
+ if (isBytes(encoded)) top[storageKey] = encoded;else {
321
+ acc[0][key] = encoded;
322
+ if (type) acc[1][key.toLowerCase()] = type;
286
323
  }
287
- }
288
- if (type) {
289
- // Store type with lowercase key for ao-types dictionary
290
- acc[1][key.toLowerCase()] = type;
291
- }
324
+ } else if (type) acc[1][key.toLowerCase()] = type;
292
325
  return acc;
293
326
  }, [{}, {}]),
294
327
  _Object$entries$reduc2 = _slicedToArray(_Object$entries$reduc, 2),
295
328
  flattened = _Object$entries$reduc2[0],
296
329
  types = _Object$entries$reduc2[1];
297
- if (Object.keys(flattened).length === 0) return top;
330
+ if (Object.keys(flattened).length === 0 && Object.keys(types).length === 0) return top;
298
331
  if (Object.keys(types).length > 0) {
299
- // Format as structured fields dictionary
300
- var aoTypeItems = Object.entries(types).map(function (_ref6) {
301
- var _ref7 = _slicedToArray(_ref6, 2),
302
- key = _ref7[0],
303
- value = _ref7[1];
304
- // The Erlang side expects keys with %2f for forward slashes
332
+ var aoTypeItems = Object.entries(types).map(function (_ref8) {
333
+ var _ref9 = _slicedToArray(_ref8, 2),
334
+ key = _ref9[0],
335
+ value = _ref9[1];
305
336
  var safeKey = key.toLowerCase().replace(/[^a-z0-9_\-.*\/]/g, function (c) {
306
337
  return "%" + c.charCodeAt(0).toString(16).padStart(2, "0");
307
- }).replace(/\//g, "%2f"); // Replace forward slashes AFTER other encoding
338
+ }).replace(/\//g, "%2f");
308
339
  return "".concat(safeKey, "=\"").concat(value, "\"");
309
340
  });
310
341
  aoTypeItems.sort();
@@ -312,27 +343,20 @@ function hbEncodeLift(obj) {
312
343
  if (Buffer.from(aoTypes).byteLength > MAX_HEADER_LENGTH) {
313
344
  var flatK = parent ? "".concat(parent, "/ao-types") : "ao-types";
314
345
  top[flatK] = aoTypes;
315
- } else {
316
- flattened["ao-types"] = aoTypes;
317
- }
318
- }
319
- if (parent) {
320
- top[parent] = flattened;
321
- } else {
322
- Object.assign(top, flattened);
346
+ } else flattened["ao-types"] = aoTypes;
323
347
  }
348
+ if (parent) top[parent] = flattened;else Object.assign(top, flattened);
324
349
  return top;
325
350
  }
326
- function encodePart(name, _ref8) {
327
- var _ref8$headers = _ref8.headers,
328
- headers = _ref8$headers === void 0 ? {} : _ref8$headers,
329
- body = _ref8.body;
330
- // Convert headers to a plain object if it's a Headers instance
351
+ function encodePart(name, _ref10) {
352
+ var _ref10$headers = _ref10.headers,
353
+ headers = _ref10$headers === void 0 ? {} : _ref10$headers,
354
+ body = _ref10.body;
331
355
  var headerEntries = headers instanceof Headers ? Array.from(headers.entries()) : Object.entries(headers || {});
332
- var parts = headerEntries.reduce(function (acc, _ref9) {
333
- var _ref10 = _slicedToArray(_ref9, 2),
334
- name = _ref10[0],
335
- value = _ref10[1];
356
+ var parts = headerEntries.reduce(function (acc, _ref11) {
357
+ var _ref12 = _slicedToArray(_ref11, 2),
358
+ name = _ref12[0],
359
+ value = _ref12[1];
336
360
  acc.push("".concat(name, ": "), value, "\r\n");
337
361
  return acc;
338
362
  }, ["content-disposition: form-data;name=\"".concat(name, "\"\r\n")]);
@@ -342,9 +366,6 @@ function encodePart(name, _ref8) {
342
366
  function encode() {
343
367
  return _encode.apply(this, arguments);
344
368
  }
345
- /**
346
- * Create HTTP signer wrapper
347
- */
348
369
  function _encode() {
349
370
  _encode = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee7() {
350
371
  var obj,
@@ -358,6 +379,11 @@ function _encode() {
358
379
  bodyKey,
359
380
  originalValue,
360
381
  flattenedValue,
382
+ hasSymbols,
383
+ _hbEncodeValue7,
384
+ _hbEncodeValue8,
385
+ type,
386
+ encoded,
361
387
  bodyParts,
362
388
  allPartsBuffer,
363
389
  hash,
@@ -383,15 +409,14 @@ function _encode() {
383
409
  body: undefined
384
410
  });
385
411
  case 3:
386
- // Keep reference to original object for data field
387
412
  originalObj = obj;
388
413
  flattened = hbEncodeLift(obj);
389
414
  bodyKeys = [];
390
- headerKeys = []; // Process all flattened keys
415
+ headerKeys = [];
391
416
  _context7.next = 9;
392
417
  return Promise.all(Object.keys(flattened).map(/*#__PURE__*/function () {
393
- var _ref15 = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee5(key) {
394
- var value, subPart, valueStr;
418
+ var _ref17 = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee5(key) {
419
+ var value, subPart, uint8Array, valueStr;
395
420
  return _regeneratorRuntime().wrap(function _callee5$(_context5) {
396
421
  while (1) switch (_context5.prev = _context5.next) {
397
422
  case 0:
@@ -415,107 +440,107 @@ function _encode() {
415
440
  return _context5.abrupt("return");
416
441
  case 10:
417
442
  if (!isBytes(value)) {
418
- _context5.next = 14;
443
+ _context5.next = 15;
419
444
  break;
420
445
  }
421
- // Binary data should always go to body
422
446
  bodyKeys.push(key);
423
- flattened[key] = new Blob(["content-disposition: form-data;name=\"".concat(key, "\"\r\n\r\n"), new Uint8Array(value.buffer || value)]);
447
+ uint8Array = value instanceof Uint8Array ? value : value instanceof ArrayBuffer ? new Uint8Array(value) : Buffer.isBuffer(value) ? new Uint8Array(value.buffer, value.byteOffset, value.length) : new Uint8Array(value.buffer, value.byteOffset, value.byteLength);
448
+ flattened[key] = new Blob(["content-disposition: form-data;name=\"".concat(key, "\"\r\n\r\n"), uint8Array]);
424
449
  return _context5.abrupt("return");
425
- case 14:
450
+ case 15:
426
451
  valueStr = String(value);
427
- _context5.next = 17;
452
+ _context5.next = 18;
428
453
  return hasNewline(valueStr);
429
- case 17:
454
+ case 18:
430
455
  _context5.t2 = _context5.sent;
431
456
  if (_context5.t2) {
432
- _context5.next = 20;
457
+ _context5.next = 21;
433
458
  break;
434
459
  }
435
460
  _context5.t2 = key.includes("/");
436
- case 20:
461
+ case 21:
437
462
  _context5.t1 = _context5.t2;
438
463
  if (_context5.t1) {
439
- _context5.next = 23;
464
+ _context5.next = 24;
440
465
  break;
441
466
  }
442
467
  _context5.t1 = Buffer.from(valueStr).byteLength > MAX_HEADER_LENGTH;
443
- case 23:
468
+ case 24:
444
469
  _context5.t0 = _context5.t1;
445
470
  if (_context5.t0) {
446
- _context5.next = 26;
471
+ _context5.next = 27;
447
472
  break;
448
473
  }
449
474
  _context5.t0 = isPojo(value) && valueStr === "[object Object]";
450
- case 26:
475
+ case 27:
451
476
  if (!_context5.t0) {
452
- _context5.next = 30;
477
+ _context5.next = 31;
453
478
  break;
454
479
  }
455
480
  bodyKeys.push(key);
456
481
  flattened[key] = new Blob(["content-disposition: form-data;name=\"".concat(key, "\"\r\n\r\n"), value]);
457
482
  return _context5.abrupt("return");
458
- case 30:
459
- // It's a header
460
- headerKeys.push(key);
461
483
  case 31:
484
+ headerKeys.push(key);
485
+ case 32:
462
486
  case "end":
463
487
  return _context5.stop();
464
488
  }
465
489
  }, _callee5);
466
490
  }));
467
- return function (_x9) {
468
- return _ref15.apply(this, arguments);
491
+ return function (_x6) {
492
+ return _ref17.apply(this, arguments);
469
493
  };
470
494
  }()));
471
495
  case 9:
472
- // Build headers object with all header keys
473
496
  headers = {};
474
497
  headerKeys.forEach(function (key) {
475
498
  headers[key] = flattened[key];
476
499
  });
477
-
478
- // Special handling for data and body fields
479
500
  if ("data" in originalObj && !bodyKeys.includes("data")) {
480
501
  bodyKeys.push("data");
481
- delete headers["data"]; // Remove from headers if it was there
502
+ delete headers["data"];
482
503
  }
483
504
  if ("body" in originalObj && !bodyKeys.includes("body")) {
484
505
  bodyKeys.push("body");
485
- delete headers["body"]; // Remove from headers if it was there
506
+ delete headers["body"];
507
+ }
508
+ if (bodyKeys.length > 0) {
509
+ headers["body-keys"] = encode_body_keys(bodyKeys);
486
510
  }
487
511
  body = undefined;
488
512
  promoteToBody = true;
489
513
  if (!(bodyKeys.length > 0)) {
490
- _context7.next = 44;
514
+ _context7.next = 45;
491
515
  break;
492
516
  }
493
517
  if (bodyKeys.length === 1) {
494
- // If there is only one element, promote it to be the full body
495
518
  bodyKey = bodyKeys[0];
496
519
  originalValue = originalObj[bodyKey];
497
- flattenedValue = flattened[bodyKey]; // Only promote if it's not a complex object
520
+ flattenedValue = flattened[bodyKey];
498
521
  if (!isPojo(originalValue) || isPojo(originalValue) && typeof flattenedValue === "string") {
499
- // For objects that were encoded as structured fields, use the encoded value
500
522
  if ((bodyKey === "body" || bodyKey === "data") && isPojo(originalValue) && typeof flattenedValue === "string") {
501
523
  body = new Blob([flattenedValue]);
502
- } else {
503
- body = new Blob([originalValue || flattenedValue]);
504
- }
524
+ } else if (Array.isArray(originalValue)) {
525
+ hasSymbols = originalValue.some(function (item) {
526
+ return _typeof(item) === "symbol";
527
+ });
528
+ if (hasSymbols) {
529
+ _hbEncodeValue7 = hbEncodeValue(originalValue), _hbEncodeValue8 = _slicedToArray(_hbEncodeValue7, 2), type = _hbEncodeValue8[0], encoded = _hbEncodeValue8[1];
530
+ body = new Blob([encoded || originalValue.toString()]);
531
+ } else body = new Blob([originalValue.toString()]);
532
+ } else body = new Blob([originalValue || flattenedValue]);
505
533
  headers["inline-body-key"] = bodyKey;
506
- } else {
507
- // Complex object - don't promote, create multipart
508
- promoteToBody = false;
509
- }
534
+ } else promoteToBody = false;
510
535
  }
511
536
  if (!(!promoteToBody || bodyKeys.length > 1)) {
512
- _context7.next = 34;
537
+ _context7.next = 35;
513
538
  break;
514
539
  }
515
- _context7.next = 20;
540
+ _context7.next = 21;
516
541
  return Promise.all(bodyKeys.map(/*#__PURE__*/function () {
517
- var _ref16 = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee6(name) {
518
- var value, _partBlob, partBlob;
542
+ var _ref18 = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee6(name) {
543
+ var value, _partBlob, valueToEncode, _hasSymbols, _hbEncodeValue9, _hbEncodeValue10, _type3, _encoded3, partBlob, uint8Array;
519
544
  return _regeneratorRuntime().wrap(function _callee6$(_context6) {
520
545
  while (1) switch (_context6.prev = _context6.next) {
521
546
  case 0:
@@ -525,8 +550,7 @@ function _encode() {
525
550
  }
526
551
  return _context6.abrupt("return", flattened[name]);
527
552
  case 2:
528
- // For raw values, we need to create a proper multipart part
529
- value = originalObj[name] || flattened[name] || ""; // Special case: if this is a structured field encoded value, use the flattened value
553
+ value = originalObj[name] || flattened[name] || "";
530
554
  if (!(name === "body" && isPojo(originalObj[name]) && typeof flattened[name] === "string")) {
531
555
  _context6.next = 6;
532
556
  break;
@@ -534,29 +558,44 @@ function _encode() {
534
558
  _partBlob = new Blob(["content-disposition: form-data;name=\"".concat(name, "\"\r\n\r\n"), flattened[name]]);
535
559
  return _context6.abrupt("return", _partBlob);
536
560
  case 6:
537
- partBlob = new Blob(["content-disposition: form-data;name=\"".concat(name, "\"\r\n\r\n"), value]);
561
+ valueToEncode = value;
562
+ if (Array.isArray(value)) {
563
+ _hasSymbols = value.some(function (item) {
564
+ return _typeof(item) === "symbol";
565
+ });
566
+ if (_hasSymbols) {
567
+ _hbEncodeValue9 = hbEncodeValue(value), _hbEncodeValue10 = _slicedToArray(_hbEncodeValue9, 2), _type3 = _hbEncodeValue10[0], _encoded3 = _hbEncodeValue10[1];
568
+ valueToEncode = _encoded3 || value.toString();
569
+ }
570
+ } else if (isBytes(value)) valueToEncode = value;
571
+ if (isBytes(valueToEncode)) {
572
+ uint8Array = valueToEncode instanceof Uint8Array ? valueToEncode : valueToEncode instanceof ArrayBuffer ? new Uint8Array(valueToEncode) : Buffer.isBuffer(valueToEncode) ? new Uint8Array(valueToEncode.buffer, valueToEncode.byteOffset, valueToEncode.length) : new Uint8Array(valueToEncode.buffer, valueToEncode.byteOffset, valueToEncode.byteLength);
573
+ partBlob = new Blob(["content-disposition: form-data;name=\"".concat(name, "\"\r\n\r\n"), uint8Array]);
574
+ } else {
575
+ partBlob = new Blob(["content-disposition: form-data;name=\"".concat(name, "\"\r\n\r\n"), valueToEncode]);
576
+ }
538
577
  return _context6.abrupt("return", partBlob);
539
- case 8:
578
+ case 10:
540
579
  case "end":
541
580
  return _context6.stop();
542
581
  }
543
582
  }, _callee6);
544
583
  }));
545
- return function (_x10) {
546
- return _ref16.apply(this, arguments);
584
+ return function (_x7) {
585
+ return _ref18.apply(this, arguments);
547
586
  };
548
587
  }()));
549
- case 20:
588
+ case 21:
550
589
  bodyParts = _context7.sent;
551
- _context7.next = 23;
590
+ _context7.next = 24;
552
591
  return new Blob(bodyParts).arrayBuffer();
553
- case 23:
592
+ case 24:
554
593
  allPartsBuffer = _context7.sent;
555
- _context7.next = 26;
594
+ _context7.next = 27;
556
595
  return sha256(allPartsBuffer);
557
- case 26:
596
+ case 27:
558
597
  hash = _context7.sent;
559
- boundary = _base64url["default"].encode(Buffer.from(hash)); // Build the multipart body with proper boundaries
598
+ boundary = _base64url["default"].encode(Buffer.from(hash));
560
599
  finalParts = [];
561
600
  _iterator = _createForOfIteratorHelper(bodyParts);
562
601
  try {
@@ -574,28 +613,28 @@ function _encode() {
574
613
  finalParts.push("--".concat(boundary, "--"));
575
614
  headers["content-type"] = "multipart/form-data; boundary=\"".concat(boundary, "\"");
576
615
  body = new Blob(finalParts);
577
- case 34:
616
+ case 35:
578
617
  if (!body) {
579
- _context7.next = 44;
618
+ _context7.next = 45;
580
619
  break;
581
620
  }
582
- _context7.next = 37;
621
+ _context7.next = 38;
583
622
  return body.arrayBuffer();
584
- case 37:
623
+ case 38:
585
624
  finalContent = _context7.sent;
586
- _context7.next = 40;
625
+ _context7.next = 41;
587
626
  return sha256(finalContent);
588
- case 40:
627
+ case 41:
589
628
  contentDigest = _context7.sent;
590
- base64 = _base64url["default"].toBase64(_base64url["default"].encode(contentDigest)); // Use lowercase to match what's in the other headers
629
+ base64 = _base64url["default"].toBase64(_base64url["default"].encode(contentDigest));
591
630
  headers["content-digest"] = "sha-256=:".concat(base64, ":");
592
631
  headers["content-length"] = String(finalContent.byteLength);
593
- case 44:
632
+ case 45:
594
633
  return _context7.abrupt("return", {
595
634
  headers: headers,
596
635
  body: body
597
636
  });
598
- case 45:
637
+ case 46:
599
638
  case "end":
600
639
  return _context7.stop();
601
640
  }
@@ -606,12 +645,12 @@ function _encode() {
606
645
  var toHttpSigner = function toHttpSigner(signer) {
607
646
  var params = ["alg", "keyid"].sort();
608
647
  return /*#__PURE__*/function () {
609
- var _ref12 = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee(_ref11) {
648
+ var _ref14 = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee(_ref13) {
610
649
  var request, fields, signatureBase, signatureInput, createCalled, create, result, signatureBuffer, signedHeaders, finalHeaders, _i, _Object$entries, _Object$entries$_i, key, value;
611
650
  return _regeneratorRuntime().wrap(function _callee$(_context) {
612
651
  while (1) switch (_context.prev = _context.next) {
613
652
  case 0:
614
- request = _ref11.request, fields = _ref11.fields;
653
+ request = _ref13.request, fields = _ref13.fields;
615
654
  createCalled = false;
616
655
  create = function create(injected) {
617
656
  createCalled = true;
@@ -629,9 +668,9 @@ var toHttpSigner = function toHttpSigner(signer) {
629
668
  var signatureBaseArray = createSignatureBase({
630
669
  fields: fields
631
670
  }, request);
632
- signatureInput = (0, _structuredHeaders.serializeList)([[signatureBaseArray.map(function (_ref13) {
633
- var _ref14 = _slicedToArray(_ref13, 1),
634
- item = _ref14[0];
671
+ signatureInput = (0, _structuredHeaders.serializeList)([[signatureBaseArray.map(function (_ref15) {
672
+ var _ref16 = _slicedToArray(_ref15, 1),
673
+ item = _ref16[0];
635
674
  return (0, _structuredHeaders.parseItem)(item);
636
675
  }), signingParameters]]);
637
676
  signatureBaseArray.push(['"@signature-params"', [signatureInput]]);
@@ -655,15 +694,13 @@ var toHttpSigner = function toHttpSigner(signer) {
655
694
  throw new Error("Signer must return signature and address");
656
695
  case 10:
657
696
  signatureBuffer = toView(result.signature);
658
- signedHeaders = augmentHeaders(request.headers, signatureBuffer, signatureInput, httpSigName(result.address)); // Only lowercase the signature headers
697
+ signedHeaders = augmentHeaders(request.headers, signatureBuffer, signatureInput, httpSigName(result.address));
659
698
  finalHeaders = {};
660
699
  for (_i = 0, _Object$entries = Object.entries(signedHeaders); _i < _Object$entries.length; _i++) {
661
700
  _Object$entries$_i = _slicedToArray(_Object$entries[_i], 2), key = _Object$entries$_i[0], value = _Object$entries$_i[1];
662
701
  if (key === "Signature" || key === "Signature-Input") {
663
702
  finalHeaders[key.toLowerCase()] = value;
664
- } else {
665
- finalHeaders[key] = value;
666
- }
703
+ } else finalHeaders[key] = value;
667
704
  }
668
705
  return _context.abrupt("return", _objectSpread(_objectSpread({}, request), {}, {
669
706
  headers: finalHeaders
@@ -675,19 +712,10 @@ var toHttpSigner = function toHttpSigner(signer) {
675
712
  }, _callee);
676
713
  }));
677
714
  return function (_x3) {
678
- return _ref12.apply(this, arguments);
715
+ return _ref14.apply(this, arguments);
679
716
  };
680
717
  }();
681
718
  };
682
-
683
- /**
684
- * Create the main request function that creates signed messages locally
685
- *
686
- * @param {Object} config - Configuration object
687
- * @param {Function} config.signer - Signer function
688
- * @param {string} [config.HB_URL='http://relay.ao-hb.xyz'] - Base URL
689
- * @returns {Function} Request function that takes tags and returns signed message
690
- */
691
719
  function createRequest(config) {
692
720
  var signer = config.signer,
693
721
  _config$url = config.url,
@@ -697,46 +725,48 @@ function createRequest(config) {
697
725
  }
698
726
  return /*#__PURE__*/function () {
699
727
  var _request = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee2(fields) {
700
- var _fields$path, path, _fields$method, method, restFields, aoFields, encoded, headersObj, body, _url, bodySize, lowercaseHeaders, _i2, _Object$entries2, _Object$entries2$_i, key, value, signingFields, signedRequest, finalHeaders, _i3, _Object$entries3, _Object$entries3$_i, _key, _value, result;
728
+ var _fields$path, path, _fields$method, method, restFields, aoFields, rootKeys, binaryKeys, encoded, headersObj, body, _url, bodySize, lowercaseHeaders, _i2, _Object$entries2, _Object$entries2$_i, key, value, signingFields, signedRequest, finalHeaders, _i3, _Object$entries3, _Object$entries3$_i, _key, _value, result;
701
729
  return _regeneratorRuntime().wrap(function _callee2$(_context2) {
702
730
  while (1) switch (_context2.prev = _context2.next) {
703
731
  case 0:
704
- _fields$path = fields.path, path = _fields$path === void 0 ? "/relay/process" : _fields$path, _fields$method = fields.method, method = _fields$method === void 0 ? "POST" : _fields$method, restFields = _objectWithoutProperties(fields, _excluded); // Add default AO fields
705
- aoFields = _objectSpread({}, restFields); // Use the HyperBEAM encode function
706
- _context2.next = 4;
732
+ _fields$path = fields.path, path = _fields$path === void 0 ? "/relay/process" : _fields$path, _fields$method = fields.method, method = _fields$method === void 0 ? "POST" : _fields$method, restFields = _objectWithoutProperties(fields, _excluded);
733
+ aoFields = _objectSpread({}, restFields);
734
+ rootKeys = Object.keys(aoFields);
735
+ binaryKeys = rootKeys.filter(function (key) {
736
+ return isBytes(aoFields[key]);
737
+ });
738
+ if (binaryKeys.length > 1 && !aoFields.body && !aoFields.data) {
739
+ aoFields.body = "1984";
740
+ }
741
+ _context2.next = 7;
707
742
  return encode(aoFields);
708
- case 4:
743
+ case 7:
709
744
  encoded = _context2.sent;
710
- // If no encoding needed, create minimal structure
711
745
  headersObj = encoded ? encoded.headers : {};
712
746
  body = encoded ? encoded.body : undefined;
713
747
  _url = joinUrl({
714
748
  url: url,
715
749
  path: path
716
- }); // Add Content-Length if body exists
750
+ });
717
751
  if (body && !headersObj["content-length"]) {
718
752
  bodySize = body.size || body.byteLength || 0;
719
753
  if (bodySize > 0) {
720
754
  headersObj["content-length"] = String(bodySize);
721
755
  }
722
756
  }
723
-
724
- // Create lowercase headers for signing
725
757
  lowercaseHeaders = {};
726
758
  for (_i2 = 0, _Object$entries2 = Object.entries(headersObj); _i2 < _Object$entries2.length; _i2++) {
727
759
  _Object$entries2$_i = _slicedToArray(_Object$entries2[_i2], 2), key = _Object$entries2$_i[0], value = _Object$entries2$_i[1];
728
760
  lowercaseHeaders[key.toLowerCase()] = value;
729
761
  }
730
-
731
- // Get all header keys for signing (lowercase)
732
- signingFields = Object.keys(lowercaseHeaders); // If there are no fields to sign, add at least the content-length
762
+ signingFields = Object.keys(lowercaseHeaders).filter(function (key) {
763
+ return key !== "body-keys";
764
+ });
733
765
  if (signingFields.length === 0 && !body) {
734
766
  lowercaseHeaders["content-length"] = "0";
735
767
  signingFields.push("content-length");
736
768
  }
737
-
738
- // Sign the request with lowercase headers
739
- _context2.next = 15;
769
+ _context2.next = 18;
740
770
  return toHttpSigner(signer)({
741
771
  request: {
742
772
  url: _url,
@@ -745,30 +775,26 @@ function createRequest(config) {
745
775
  },
746
776
  fields: signingFields
747
777
  });
748
- case 15:
778
+ case 18:
749
779
  signedRequest = _context2.sent;
750
- // Build final headers: use original casing for all headers except signature headers
751
- finalHeaders = {}; // First, add all original headers with their original casing
780
+ finalHeaders = {};
752
781
  for (_i3 = 0, _Object$entries3 = Object.entries(headersObj); _i3 < _Object$entries3.length; _i3++) {
753
782
  _Object$entries3$_i = _slicedToArray(_Object$entries3[_i3], 2), _key = _Object$entries3$_i[0], _value = _Object$entries3$_i[1];
754
783
  finalHeaders[_key] = _value;
755
784
  }
756
-
757
- // Then add the signature headers (which should be lowercase)
758
785
  finalHeaders["signature"] = signedRequest.headers["signature"];
759
786
  finalHeaders["signature-input"] = signedRequest.headers["signature-input"];
760
-
761
- // Return the signed message
787
+ if (headersObj["body-keys"]) {
788
+ finalHeaders["body-keys"] = headersObj["body-keys"];
789
+ }
762
790
  result = {
763
791
  url: _url,
764
792
  method: method,
765
793
  headers: finalHeaders
766
- }; // Only add body if it exists
767
- if (body) {
768
- result.body = body;
769
- }
794
+ };
795
+ if (body) result.body = body;
770
796
  return _context2.abrupt("return", result);
771
- case 23:
797
+ case 27:
772
798
  case "end":
773
799
  return _context2.stop();
774
800
  }
@@ -780,393 +806,69 @@ function createRequest(config) {
780
806
  return request;
781
807
  }();
782
808
  }
783
- /**
784
- * Utility function to extract the message ID from a signed message
785
- * Based on the original code's hash calculation
786
- */
787
- function getMessageId(_x5) {
788
- return _getMessageId.apply(this, arguments);
789
- }
790
- function _getMessageId() {
791
- _getMessageId = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee8(signedMessage) {
792
- var signatureHeader, match, signature, encoder, data, hashBuffer, hashArray, hashBase64;
793
- return _regeneratorRuntime().wrap(function _callee8$(_context8) {
794
- while (1) switch (_context8.prev = _context8.next) {
795
- case 0:
796
- // Extract signature from the Signature header
797
- signatureHeader = signedMessage.headers.Signature || signedMessage.headers.signature;
798
- match = signatureHeader.match(/Signature:\s*'http-sig-[^:]+:([^']+)'/);
799
- signature = match ? match[1] : null;
800
- if (signature) {
801
- _context8.next = 5;
802
- break;
803
- }
804
- throw new Error("Could not extract signature from headers");
805
- case 5:
806
- // Hash the signature to get message ID
807
- encoder = new TextEncoder();
808
- data = encoder.encode(signature);
809
- _context8.next = 9;
810
- return _crypto["default"].subtle.digest("SHA-256", data);
811
- case 9:
812
- hashBuffer = _context8.sent;
813
- hashArray = Array.from(new Uint8Array(hashBuffer));
814
- hashBase64 = btoa(String.fromCharCode.apply(String, hashArray));
815
- return _context8.abrupt("return", hashBase64);
816
- case 13:
817
- case "end":
818
- return _context8.stop();
819
- }
820
- }, _callee8);
821
- }));
822
- return _getMessageId.apply(this, arguments);
823
- }
824
- function send(_x6) {
809
+ function send(_x5) {
825
810
  return _send.apply(this, arguments);
826
811
  }
827
- /**
828
- * Convert JWK modulus (n) to PEM format public key
829
- * @param {Buffer} nBuffer - The modulus buffer
830
- * @returns {string} PEM formatted public key
831
- */
832
812
  function _send() {
833
- _send = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee9(signedMsg) {
813
+ _send = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee8(signedMsg) {
834
814
  var fetchImpl,
835
815
  fetchOptions,
836
816
  response,
837
817
  headers,
838
- _args9 = arguments;
839
- return _regeneratorRuntime().wrap(function _callee9$(_context9) {
840
- while (1) switch (_context9.prev = _context9.next) {
818
+ _args8 = arguments;
819
+ return _regeneratorRuntime().wrap(function _callee8$(_context8) {
820
+ while (1) switch (_context8.prev = _context8.next) {
841
821
  case 0:
842
- fetchImpl = _args9.length > 1 && _args9[1] !== undefined ? _args9[1] : fetch;
822
+ fetchImpl = _args8.length > 1 && _args8[1] !== undefined ? _args8[1] : fetch;
843
823
  fetchOptions = {
844
824
  method: signedMsg.method,
845
825
  headers: signedMsg.headers,
846
826
  redirect: "follow"
847
- }; // Only add body if it exists and method supports it
827
+ };
848
828
  if (signedMsg.body !== undefined && signedMsg.method !== "GET" && signedMsg.method !== "HEAD") {
849
829
  fetchOptions.body = signedMsg.body;
850
830
  }
851
- _context9.next = 5;
831
+ _context8.next = 5;
852
832
  return fetchImpl(signedMsg.url, fetchOptions);
853
833
  case 5:
854
- response = _context9.sent;
834
+ response = _context8.sent;
855
835
  if (!(response.status >= 400)) {
856
- _context9.next = 14;
836
+ _context8.next = 14;
857
837
  break;
858
838
  }
859
- _context9.t0 = Error;
860
- _context9.t1 = "".concat(response.status, ": ");
861
- _context9.next = 11;
839
+ _context8.t0 = Error;
840
+ _context8.t1 = "".concat(response.status, ": ");
841
+ _context8.next = 11;
862
842
  return response.text();
863
843
  case 11:
864
- _context9.t2 = _context9.sent;
865
- _context9.t3 = _context9.t1.concat.call(_context9.t1, _context9.t2);
866
- throw new _context9.t0(_context9.t3);
844
+ _context8.t2 = _context8.sent;
845
+ _context8.t3 = _context8.t1.concat.call(_context8.t1, _context8.t2);
846
+ throw new _context8.t0(_context8.t3);
867
847
  case 14:
868
- // Convert Headers object to plain object
869
848
  headers = {};
870
849
  if (response.headers && typeof response.headers.forEach === "function") {
871
850
  response.headers.forEach(function (v, k) {
872
851
  return headers[k] = v;
873
852
  });
874
853
  } else headers = response.headers;
875
- _context9.t4 = response;
876
- _context9.t5 = headers;
877
- _context9.next = 20;
854
+ _context8.t4 = response;
855
+ _context8.t5 = headers;
856
+ _context8.next = 20;
878
857
  return response.text();
879
858
  case 20:
880
- _context9.t6 = _context9.sent;
881
- _context9.t7 = response.status;
882
- return _context9.abrupt("return", {
883
- response: _context9.t4,
884
- headers: _context9.t5,
885
- body: _context9.t6,
886
- status: _context9.t7
859
+ _context8.t6 = _context8.sent;
860
+ _context8.t7 = response.status;
861
+ return _context8.abrupt("return", {
862
+ response: _context8.t4,
863
+ headers: _context8.t5,
864
+ body: _context8.t6,
865
+ status: _context8.t7
887
866
  });
888
867
  case 23:
889
868
  case "end":
890
- return _context9.stop();
869
+ return _context8.stop();
891
870
  }
892
- }, _callee9);
871
+ }, _callee8);
893
872
  }));
894
873
  return _send.apply(this, arguments);
895
- }
896
- function jwkModulusToPem(nBuffer) {
897
- // RSA public key with standard exponent
898
- var rsaPublicKey = _crypto["default"].createPublicKey({
899
- key: {
900
- kty: "RSA",
901
- n: _base64url["default"].encode(nBuffer),
902
- e: "AQAB" // Standard exponent 65537
903
- },
904
- format: "jwk"
905
- });
906
- return rsaPublicKey["export"]({
907
- type: "spki",
908
- format: "pem"
909
- });
910
- }
911
-
912
- /**
913
- * Extract signature name from headers
914
- * @param {Object} headers - Request headers
915
- * @returns {string|null} Signature name or null
916
- */
917
- function extractSignatureName(headers) {
918
- var signatureHeader = headers["signature"] || headers["Signature"];
919
- if (!signatureHeader) return null;
920
-
921
- // Extract signature name (e.g., "http-sig-xxxxxxxx")
922
- // Handle both "name:" and "name=" formats
923
- var match = signatureHeader.match(/^([^:=]+)[:=]/);
924
- return match ? match[1] : null;
925
- }
926
-
927
- /**
928
- * Extract public key from signature-input header
929
- * @param {Object} headers - Request headers
930
- * @param {string} [signatureName] - Optional signature name to look for
931
- * @returns {Buffer|null} Public key buffer or null
932
- */
933
- function extractPublicKeyFromHeaders(headers, signatureName) {
934
- var signatureInput = headers["signature-input"] || headers["Signature-Input"];
935
- if (!signatureInput) return null;
936
-
937
- // If we have a signature name, look for its specific keyid
938
- var keyidMatch;
939
- if (signatureName) {
940
- // The signature-input format is: signatureName=(...);alg="...";keyid="..."
941
- // We need to match after the signature name
942
- var signatureSection = signatureInput.substring(signatureInput.indexOf(signatureName));
943
- keyidMatch = signatureSection.match(/keyid="([^"]+)"/);
944
- } else {
945
- // General keyid match
946
- keyidMatch = signatureInput.match(/keyid="([^"]+)"/);
947
- }
948
- if (!keyidMatch) return null;
949
- try {
950
- return _base64url["default"].toBuffer(keyidMatch[1]);
951
- } catch (error) {
952
- return null;
953
- }
954
- }
955
-
956
- /**
957
- * Verify an HTTP signed message using http-message-signatures
958
- *
959
- * @param {Object} signedMessage - The signed message to verify
960
- * @param {string} signedMessage.url - Request URL
961
- * @param {string} signedMessage.method - HTTP method
962
- * @param {Object} signedMessage.headers - Headers including signature
963
- * @param {string} [signedMessage.body] - Request body
964
- * @param {string|Buffer} [publicKey] - Optional public key (if not provided, extracts from keyid)
965
- * @returns {Object} Verification result
966
- */
967
- function verify(_x7, _x8) {
968
- return _verify.apply(this, arguments);
969
- }
970
- /**
971
- * Extract public key from a signed message
972
- *
973
- * @param {Object} signedMessage - The signed message
974
- * @returns {Buffer|null} The public key buffer or null
975
- */
976
- function _verify() {
977
- _verify = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee14(signedMessage, publicKey) {
978
- var url, method, headers, body, keyLookup, pem, _signatureName, extractedKey, _pem, _request2, signatureName, extractedPublicKey, signatureInputHeader, algMatch, algorithm, verified, verificationError, verificationResult;
979
- return _regeneratorRuntime().wrap(function _callee14$(_context14) {
980
- while (1) switch (_context14.prev = _context14.next) {
981
- case 0:
982
- _context14.prev = 0;
983
- url = signedMessage.url, method = signedMessage.method, headers = signedMessage.headers, body = signedMessage.body; // Determine which public key to use
984
- if (!publicKey) {
985
- _context14.next = 7;
986
- break;
987
- }
988
- // Use provided public key
989
- pem = typeof publicKey === "string" ? publicKey : jwkModulusToPem(publicKey);
990
- keyLookup = /*#__PURE__*/function () {
991
- var _ref17 = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee11(keyId) {
992
- return _regeneratorRuntime().wrap(function _callee11$(_context11) {
993
- while (1) switch (_context11.prev = _context11.next) {
994
- case 0:
995
- return _context11.abrupt("return", {
996
- id: keyId,
997
- algs: ["rsa-pss-sha512", "rsa-pss-sha256", "rsa-v1_5-sha256"],
998
- verify: function () {
999
- var _verify2 = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee10(data, signature, parameters) {
1000
- var verifier;
1001
- return _regeneratorRuntime().wrap(function _callee10$(_context10) {
1002
- while (1) switch (_context10.prev = _context10.next) {
1003
- case 0:
1004
- verifier = _crypto["default"].createVerify("RSA-SHA".concat(parameters.alg.includes("512") ? "512" : "256"));
1005
- verifier.update(data);
1006
- if (!parameters.alg.startsWith("rsa-pss")) {
1007
- _context10.next = 6;
1008
- break;
1009
- }
1010
- return _context10.abrupt("return", verifier.verify({
1011
- key: pem,
1012
- padding: _crypto["default"].constants.RSA_PKCS1_PSS_PADDING,
1013
- saltLength: _crypto["default"].constants.RSA_PSS_SALTLEN_DIGEST
1014
- }, signature));
1015
- case 6:
1016
- return _context10.abrupt("return", verifier.verify(pem, signature));
1017
- case 7:
1018
- case "end":
1019
- return _context10.stop();
1020
- }
1021
- }, _callee10);
1022
- }));
1023
- function verify(_x12, _x13, _x14) {
1024
- return _verify2.apply(this, arguments);
1025
- }
1026
- return verify;
1027
- }()
1028
- });
1029
- case 1:
1030
- case "end":
1031
- return _context11.stop();
1032
- }
1033
- }, _callee11);
1034
- }));
1035
- return function keyLookup(_x11) {
1036
- return _ref17.apply(this, arguments);
1037
- };
1038
- }();
1039
- _context14.next = 13;
1040
- break;
1041
- case 7:
1042
- // Extract public key from keyid
1043
- _signatureName = extractSignatureName(headers);
1044
- extractedKey = extractPublicKeyFromHeaders(headers, _signatureName);
1045
- if (extractedKey) {
1046
- _context14.next = 11;
1047
- break;
1048
- }
1049
- return _context14.abrupt("return", {
1050
- valid: false,
1051
- error: "No public key provided and none found in signature"
1052
- });
1053
- case 11:
1054
- _pem = jwkModulusToPem(extractedKey);
1055
- keyLookup = /*#__PURE__*/function () {
1056
- var _ref18 = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee13(keyId) {
1057
- return _regeneratorRuntime().wrap(function _callee13$(_context13) {
1058
- while (1) switch (_context13.prev = _context13.next) {
1059
- case 0:
1060
- return _context13.abrupt("return", {
1061
- id: keyId,
1062
- algs: ["rsa-pss-sha512", "rsa-pss-sha256", "rsa-v1_5-sha256"],
1063
- verify: function () {
1064
- var _verify3 = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee12(data, signature, parameters) {
1065
- var verifier, _verified;
1066
- return _regeneratorRuntime().wrap(function _callee12$(_context12) {
1067
- while (1) switch (_context12.prev = _context12.next) {
1068
- case 0:
1069
- _context12.prev = 0;
1070
- verifier = _crypto["default"].createVerify("RSA-SHA".concat(parameters.alg.includes("512") ? "512" : "256"));
1071
- verifier.update(data);
1072
- if (parameters.alg.startsWith("rsa-pss")) {
1073
- _verified = verifier.verify({
1074
- key: _pem,
1075
- padding: _crypto["default"].constants.RSA_PKCS1_PSS_PADDING,
1076
- saltLength: _crypto["default"].constants.RSA_PSS_SALTLEN_DIGEST
1077
- }, signature);
1078
- } else {
1079
- _verified = verifier.verify(_pem, signature);
1080
- }
1081
- return _context12.abrupt("return", _verified);
1082
- case 7:
1083
- _context12.prev = 7;
1084
- _context12.t0 = _context12["catch"](0);
1085
- console.error("Verification error:", _context12.t0);
1086
- return _context12.abrupt("return", false);
1087
- case 11:
1088
- case "end":
1089
- return _context12.stop();
1090
- }
1091
- }, _callee12, null, [[0, 7]]);
1092
- }));
1093
- function verify(_x16, _x17, _x18) {
1094
- return _verify3.apply(this, arguments);
1095
- }
1096
- return verify;
1097
- }()
1098
- });
1099
- case 1:
1100
- case "end":
1101
- return _context13.stop();
1102
- }
1103
- }, _callee13);
1104
- }));
1105
- return function keyLookup(_x15) {
1106
- return _ref18.apply(this, arguments);
1107
- };
1108
- }();
1109
- case 13:
1110
- // Create request object for verification
1111
- _request2 = {
1112
- method: method,
1113
- url: url,
1114
- headers: _objectSpread({}, headers)
1115
- }; // Extract additional info from headers
1116
- signatureName = extractSignatureName(headers);
1117
- extractedPublicKey = extractPublicKeyFromHeaders(headers, signatureName); // Extract algorithm from signature-input
1118
- signatureInputHeader = headers["signature-input"] || headers["Signature-Input"];
1119
- algMatch = signatureInputHeader === null || signatureInputHeader === void 0 ? void 0 : signatureInputHeader.match(/alg="([^"]+)"/);
1120
- algorithm = algMatch ? algMatch[1] : undefined; // Verify using the library
1121
- verified = false;
1122
- verificationError = null;
1123
- _context14.prev = 21;
1124
- _context14.next = 24;
1125
- return verifyMessage({
1126
- keyLookup: keyLookup,
1127
- requiredFields: [] // Don't require specific fields
1128
- }, _request2);
1129
- case 24:
1130
- verificationResult = _context14.sent;
1131
- // If we get here without throwing, verification succeeded
1132
- verified = true;
1133
- _context14.next = 32;
1134
- break;
1135
- case 28:
1136
- _context14.prev = 28;
1137
- _context14.t0 = _context14["catch"](21);
1138
- // Verification failed
1139
- verificationError = _context14.t0.message;
1140
- verified = false;
1141
- case 32:
1142
- return _context14.abrupt("return", _objectSpread({
1143
- valid: true,
1144
- // The signature format is valid
1145
- verified: verified,
1146
- // Whether the cryptographic verification passed
1147
- signatureName: signatureName,
1148
- keyId: extractedPublicKey ? _base64url["default"].encode(extractedPublicKey) : undefined,
1149
- algorithm: algorithm,
1150
- publicKeyFromHeader: extractedPublicKey
1151
- }, verificationError && {
1152
- error: verificationError
1153
- }));
1154
- case 35:
1155
- _context14.prev = 35;
1156
- _context14.t1 = _context14["catch"](0);
1157
- return _context14.abrupt("return", {
1158
- valid: false,
1159
- error: _context14.t1.message
1160
- });
1161
- case 38:
1162
- case "end":
1163
- return _context14.stop();
1164
- }
1165
- }, _callee14, null, [[0, 35], [21, 28]]);
1166
- }));
1167
- return _verify.apply(this, arguments);
1168
- }
1169
- function extractPublicKeyFromMessage(signedMessage) {
1170
- var signatureName = extractSignatureName(signedMessage.headers);
1171
- return extractPublicKeyFromHeaders(signedMessage.headers, signatureName);
1172
874
  }