wao 0.21.2 → 0.22.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.
package/cjs/signer.js ADDED
@@ -0,0 +1,1016 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.createRequest = createRequest;
7
+ exports.send = send;
8
+ exports.verify = verify;
9
+ var _base64url = _interopRequireDefault(require("base64url"));
10
+ var _crypto = _interopRequireDefault(require("crypto"));
11
+ var _httpMessageSignatures = require("http-message-signatures");
12
+ var _structuredHeaders = require("structured-headers");
13
+ var _excluded = ["path", "method"];
14
+ function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; }
15
+ function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var s = Object.getOwnPropertySymbols(e); for (r = 0; r < s.length; r++) o = s[r], t.includes(o) || {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
16
+ function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (e.includes(n)) continue; t[n] = r[n]; } return t; }
17
+ function _regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ _regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == _typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator["return"] && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, "catch": function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; }
18
+ function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
19
+ function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
20
+ function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }
21
+ function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; }
22
+ function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
23
+ function _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest(); }
24
+ 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."); }
25
+ 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; } }
26
+ function _arrayWithHoles(r) { if (Array.isArray(r)) return r; }
27
+ 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); }
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); }
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); }); }; }
30
+ function _toConsumableArray(r) { return _arrayWithoutHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableSpread(); }
31
+ function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
32
+ function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }
33
+ function _iterableToArray(r) { if ("undefined" != typeof Symbol && null != r[Symbol.iterator] || null != r["@@iterator"]) return Array.from(r); }
34
+ function _arrayWithoutHoles(r) { if (Array.isArray(r)) return _arrayLikeToArray(r); }
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
+ var verifyMessage = _httpMessageSignatures.httpbis.verifyMessage;
37
+ var augmentHeaders = _httpMessageSignatures.httpbis.augmentHeaders,
38
+ createSignatureBase = _httpMessageSignatures.httpbis.createSignatureBase,
39
+ createSigningParameters = _httpMessageSignatures.httpbis.createSigningParameters,
40
+ formatSignatureBase = _httpMessageSignatures.httpbis.formatSignatureBase;
41
+
42
+ /**
43
+ * Convert value to Buffer
44
+ */
45
+ var toView = function toView(value) {
46
+ if (ArrayBuffer.isView(value)) {
47
+ return Buffer.from(value.buffer, value.byteOffset, value.byteLength);
48
+ } else if (typeof value === "string") {
49
+ return _base64url["default"].toBuffer(value);
50
+ }
51
+ throw new Error("Value must be Uint8Array, ArrayBuffer, or base64url-encoded string");
52
+ };
53
+
54
+ /**
55
+ * Generate HTTP signature name from address
56
+ */
57
+ var httpSigName = function httpSigName(address) {
58
+ var decoded = _base64url["default"].toBuffer(address);
59
+ var hexString = _toConsumableArray(decoded.subarray(1, 9)).map(function (_byte) {
60
+ return _byte.toString(16).padStart(2, "0");
61
+ }).join("");
62
+ return "http-sig-".concat(hexString);
63
+ };
64
+
65
+ /**
66
+ * Join URL parts
67
+ */
68
+ var joinUrl = function joinUrl(_ref) {
69
+ var url = _ref.url,
70
+ path = _ref.path;
71
+ // If path is already a full URL, return it as-is
72
+ if (path.startsWith("http://") || path.startsWith("https://")) {
73
+ return path;
74
+ }
75
+
76
+ // Otherwise, join the base URL with the path
77
+ return url.endsWith("/") ? url.slice(0, -1) + path : url + path;
78
+ };
79
+
80
+ /**
81
+ * HyperBEAM Encoding Logic
82
+ */
83
+ var MAX_HEADER_LENGTH = 4096;
84
+ function hasNewline(_x) {
85
+ return _hasNewline.apply(this, arguments);
86
+ }
87
+ function _hasNewline() {
88
+ _hasNewline = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee3(value) {
89
+ return _regeneratorRuntime().wrap(function _callee3$(_context3) {
90
+ while (1) switch (_context3.prev = _context3.next) {
91
+ case 0:
92
+ if (!(typeof value === "string")) {
93
+ _context3.next = 2;
94
+ break;
95
+ }
96
+ return _context3.abrupt("return", value.includes("\n"));
97
+ case 2:
98
+ if (!(value instanceof Blob)) {
99
+ _context3.next = 7;
100
+ break;
101
+ }
102
+ _context3.next = 5;
103
+ return value.text();
104
+ case 5:
105
+ value = _context3.sent;
106
+ return _context3.abrupt("return", value.includes("\n"));
107
+ case 7:
108
+ if (!isBytes(value)) {
109
+ _context3.next = 9;
110
+ break;
111
+ }
112
+ return _context3.abrupt("return", Buffer.from(value).includes("\n"));
113
+ case 9:
114
+ return _context3.abrupt("return", false);
115
+ case 10:
116
+ case "end":
117
+ return _context3.stop();
118
+ }
119
+ }, _callee3);
120
+ }));
121
+ return _hasNewline.apply(this, arguments);
122
+ }
123
+ function sha256(_x2) {
124
+ return _sha.apply(this, arguments);
125
+ }
126
+ function _sha() {
127
+ _sha = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee4(data) {
128
+ return _regeneratorRuntime().wrap(function _callee4$(_context4) {
129
+ while (1) switch (_context4.prev = _context4.next) {
130
+ case 0:
131
+ return _context4.abrupt("return", _crypto["default"].subtle.digest("SHA-256", data));
132
+ case 1:
133
+ case "end":
134
+ return _context4.stop();
135
+ }
136
+ }, _callee4);
137
+ }));
138
+ return _sha.apply(this, arguments);
139
+ }
140
+ function isBytes(value) {
141
+ return value instanceof ArrayBuffer || ArrayBuffer.isView(value);
142
+ }
143
+ function isPojo(value) {
144
+ return !isBytes(value) && !Array.isArray(value) && !(value instanceof Blob) && _typeof(value) === "object" && value !== null;
145
+ }
146
+ function hbEncodeValue(value) {
147
+ if (isBytes(value)) {
148
+ if (value.byteLength === 0) return hbEncodeValue("");
149
+ return [undefined, value];
150
+ }
151
+ if (typeof value === "string") {
152
+ if (value.length === 0) return [undefined, "empty-binary"];
153
+ return [undefined, value];
154
+ }
155
+ if (Array.isArray(value)) {
156
+ if (value.length === 0) return ["empty-list", undefined];
157
+ // For structured fields, just join the string values
158
+ var encoded = value.map(function (v) {
159
+ if (typeof v === "string") {
160
+ // Escape quotes and backslashes
161
+ var escaped = v.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
162
+ return "\"".concat(escaped, "\"");
163
+ }
164
+ return "\"".concat(String(v), "\"");
165
+ }).join(", ");
166
+ return ["list", encoded];
167
+ }
168
+ if (typeof value === "number") {
169
+ if (!Number.isInteger(value)) return ["float", "".concat(value)];
170
+ return ["integer", String(value)];
171
+ }
172
+ if (_typeof(value) === "symbol") {
173
+ return ["atom", value.description];
174
+ }
175
+ throw new Error("Cannot encode value: ".concat(value.toString()));
176
+ }
177
+ function hbEncodeLift(obj) {
178
+ var parent = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : "";
179
+ var top = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
180
+ var _Object$entries$reduc = Object.entries(_objectSpread({}, obj)).reduce(function (acc, _ref2) {
181
+ var _ref3 = _slicedToArray(_ref2, 2),
182
+ key = _ref3[0],
183
+ value = _ref3[1];
184
+ // For nested paths, preserve casing. For top-level, also preserve casing
185
+ var storageKey = parent ? "".concat(parent, "/").concat(key) : key;
186
+
187
+ // skip nullish values
188
+ if (value == null) return acc;
189
+
190
+ // list of objects
191
+ if (Array.isArray(value) && value.some(isPojo)) {
192
+ value = value.reduce(function (indexedObj, v, idx) {
193
+ return Object.assign(indexedObj, _defineProperty({}, idx, v));
194
+ }, {});
195
+ }
196
+
197
+ // first/second lift object
198
+ if (isPojo(value)) {
199
+ hbEncodeLift(value, storageKey, top);
200
+ return acc;
201
+ }
202
+
203
+ // leaf encode value
204
+ var _hbEncodeValue = hbEncodeValue(value),
205
+ _hbEncodeValue2 = _slicedToArray(_hbEncodeValue, 2),
206
+ type = _hbEncodeValue2[0],
207
+ encoded = _hbEncodeValue2[1];
208
+ if (encoded !== undefined) {
209
+ if (Buffer.from(String(encoded)).byteLength > MAX_HEADER_LENGTH) {
210
+ top[storageKey] = String(encoded);
211
+ } else {
212
+ // Preserve the original key casing
213
+ var httpKey = key;
214
+ if (type === "integer" && typeof value === "number") {
215
+ acc[0][httpKey] = String(value);
216
+ } else {
217
+ acc[0][httpKey] = encoded;
218
+ }
219
+ }
220
+ }
221
+ if (type) {
222
+ // Store type with lowercase key for ao-types dictionary
223
+ acc[1][key.toLowerCase()] = type;
224
+ }
225
+ return acc;
226
+ }, [{}, {}]),
227
+ _Object$entries$reduc2 = _slicedToArray(_Object$entries$reduc, 2),
228
+ flattened = _Object$entries$reduc2[0],
229
+ types = _Object$entries$reduc2[1];
230
+ if (Object.keys(flattened).length === 0) return top;
231
+ if (Object.keys(types).length > 0) {
232
+ // Format as structured fields dictionary
233
+ var aoTypeItems = Object.entries(types).map(function (_ref4) {
234
+ var _ref5 = _slicedToArray(_ref4, 2),
235
+ key = _ref5[0],
236
+ value = _ref5[1];
237
+ var safeKey = key.toLowerCase().replace(/[^a-z0-9_-]/g, function (c) {
238
+ return "%" + c.charCodeAt(0).toString(16).padStart(2, "0");
239
+ });
240
+ return "".concat(safeKey, "=\"").concat(value, "\"");
241
+ });
242
+ aoTypeItems.sort();
243
+ var aoTypes = aoTypeItems.join(", ");
244
+ if (Buffer.from(aoTypes).byteLength > MAX_HEADER_LENGTH) {
245
+ var flatK = parent ? "".concat(parent, "/ao-types") : "ao-types";
246
+ top[flatK] = aoTypes;
247
+ } else {
248
+ flattened["ao-types"] = aoTypes;
249
+ }
250
+ }
251
+ if (parent) {
252
+ top[parent] = flattened;
253
+ } else {
254
+ Object.assign(top, flattened);
255
+ }
256
+ return top;
257
+ }
258
+ function encodePart(name, _ref6) {
259
+ var headers = _ref6.headers,
260
+ body = _ref6.body;
261
+ var parts = Object.entries(Object.fromEntries(headers)).reduce(function (acc, _ref7) {
262
+ var _ref8 = _slicedToArray(_ref7, 2),
263
+ name = _ref8[0],
264
+ value = _ref8[1];
265
+ acc.push("".concat(name, ": "), value, "\r\n");
266
+ return acc;
267
+ }, ["content-disposition: form-data;name=\"".concat(name, "\"\r\n")]);
268
+ if (body) parts.push("\r\n", body);
269
+ return new Blob(parts);
270
+ }
271
+ function encode() {
272
+ return _encode.apply(this, arguments);
273
+ }
274
+ /**
275
+ * Create HTTP signer wrapper
276
+ */
277
+ function _encode() {
278
+ _encode = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee6() {
279
+ var obj,
280
+ originalObj,
281
+ flattened,
282
+ bodyKeys,
283
+ headerKeys,
284
+ headers,
285
+ body,
286
+ bodyKey,
287
+ bodyParts,
288
+ base,
289
+ hash,
290
+ boundary,
291
+ blobParts,
292
+ finalContent,
293
+ contentDigest,
294
+ base64,
295
+ _args6 = arguments;
296
+ return _regeneratorRuntime().wrap(function _callee6$(_context6) {
297
+ while (1) switch (_context6.prev = _context6.next) {
298
+ case 0:
299
+ obj = _args6.length > 0 && _args6[0] !== undefined ? _args6[0] : {};
300
+ if (!(Object.keys(obj).length === 0)) {
301
+ _context6.next = 3;
302
+ break;
303
+ }
304
+ return _context6.abrupt("return");
305
+ case 3:
306
+ // Keep reference to original object for data field
307
+ originalObj = obj;
308
+ flattened = hbEncodeLift(obj);
309
+ bodyKeys = [];
310
+ headerKeys = []; // Process all flattened keys
311
+ _context6.next = 9;
312
+ return Promise.all(Object.keys(flattened).map(/*#__PURE__*/function () {
313
+ var _ref13 = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee5(key) {
314
+ var value, subPart, valueStr;
315
+ return _regeneratorRuntime().wrap(function _callee5$(_context5) {
316
+ while (1) switch (_context5.prev = _context5.next) {
317
+ case 0:
318
+ value = flattened[key];
319
+ if (!isPojo(value)) {
320
+ _context5.next = 10;
321
+ break;
322
+ }
323
+ _context5.next = 4;
324
+ return encode(value);
325
+ case 4:
326
+ subPart = _context5.sent;
327
+ if (subPart) {
328
+ _context5.next = 7;
329
+ break;
330
+ }
331
+ return _context5.abrupt("return");
332
+ case 7:
333
+ bodyKeys.push(key);
334
+ flattened[key] = encodePart(key, subPart);
335
+ return _context5.abrupt("return");
336
+ case 10:
337
+ // Check if this should be a body field
338
+ valueStr = String(value);
339
+ _context5.next = 13;
340
+ return hasNewline(valueStr);
341
+ case 13:
342
+ _context5.t1 = _context5.sent;
343
+ if (_context5.t1) {
344
+ _context5.next = 16;
345
+ break;
346
+ }
347
+ _context5.t1 = key.includes("/");
348
+ case 16:
349
+ _context5.t0 = _context5.t1;
350
+ if (_context5.t0) {
351
+ _context5.next = 19;
352
+ break;
353
+ }
354
+ _context5.t0 = Buffer.from(valueStr).byteLength > MAX_HEADER_LENGTH;
355
+ case 19:
356
+ if (!_context5.t0) {
357
+ _context5.next = 23;
358
+ break;
359
+ }
360
+ bodyKeys.push(key);
361
+ flattened[key] = new Blob(["content-disposition: form-data;name=\"".concat(key, "\"\r\n\r\n"), value]);
362
+ return _context5.abrupt("return");
363
+ case 23:
364
+ // It's a header
365
+ headerKeys.push(key);
366
+ case 24:
367
+ case "end":
368
+ return _context5.stop();
369
+ }
370
+ }, _callee5);
371
+ }));
372
+ return function (_x9) {
373
+ return _ref13.apply(this, arguments);
374
+ };
375
+ }()));
376
+ case 9:
377
+ // Build headers object with all header keys
378
+ headers = {};
379
+ headerKeys.forEach(function (key) {
380
+ headers[key] = flattened[key];
381
+ });
382
+
383
+ // Special handling for data and body fields
384
+ if ("data" in originalObj && !bodyKeys.includes("data")) {
385
+ bodyKeys.push("data");
386
+ delete headers["data"]; // Remove from headers if it was there
387
+ }
388
+ if ("body" in originalObj && !bodyKeys.includes("body")) {
389
+ bodyKeys.push("body");
390
+ delete headers["body"]; // Remove from headers if it was there
391
+ }
392
+ body = undefined;
393
+ if (!(bodyKeys.length > 0)) {
394
+ _context6.next = 47;
395
+ break;
396
+ }
397
+ if (!(bodyKeys.length === 1)) {
398
+ _context6.next = 21;
399
+ break;
400
+ }
401
+ // If there is only one element, promote it to be the full body
402
+ bodyKey = bodyKeys[0];
403
+ body = new Blob([originalObj[bodyKey] || flattened[bodyKey]]);
404
+ headers["inline-body-key"] = bodyKey;
405
+ _context6.next = 37;
406
+ break;
407
+ case 21:
408
+ _context6.next = 23;
409
+ return Promise.all(bodyKeys.map(function (name) {
410
+ if (flattened[name] instanceof Blob) {
411
+ return flattened[name].arrayBuffer();
412
+ }
413
+ // For raw values, create a blob
414
+ return new Blob([originalObj[name] || ""]).arrayBuffer();
415
+ }));
416
+ case 23:
417
+ bodyParts = _context6.sent;
418
+ base = new Blob(bodyParts.flatMap(function (p, i, arr) {
419
+ return i < arr.length - 1 ? [p, "\r\n"] : [p];
420
+ }));
421
+ _context6.t0 = sha256;
422
+ _context6.next = 28;
423
+ return base.arrayBuffer();
424
+ case 28:
425
+ _context6.t1 = _context6.sent;
426
+ _context6.next = 31;
427
+ return (0, _context6.t0)(_context6.t1);
428
+ case 31:
429
+ hash = _context6.sent;
430
+ boundary = _base64url["default"].encode(Buffer.from(hash));
431
+ blobParts = bodyParts.flatMap(function (p) {
432
+ return ["--".concat(boundary, "\r\n"), p, "\r\n"];
433
+ });
434
+ blobParts.push("--".concat(boundary, "--"));
435
+ headers["content-type"] = "multipart/form-data; boundary=\"".concat(boundary, "\"");
436
+ body = new Blob(blobParts);
437
+ case 37:
438
+ if (!body) {
439
+ _context6.next = 47;
440
+ break;
441
+ }
442
+ _context6.next = 40;
443
+ return body.arrayBuffer();
444
+ case 40:
445
+ finalContent = _context6.sent;
446
+ _context6.next = 43;
447
+ return sha256(finalContent);
448
+ case 43:
449
+ contentDigest = _context6.sent;
450
+ base64 = _base64url["default"].toBase64(_base64url["default"].encode(contentDigest)); // Use lowercase to match what's in the other headers
451
+ headers["content-digest"] = "sha-256=:".concat(base64, ":");
452
+ headers["content-length"] = String(finalContent.byteLength);
453
+ case 47:
454
+ return _context6.abrupt("return", {
455
+ headers: headers,
456
+ body: body
457
+ });
458
+ case 48:
459
+ case "end":
460
+ return _context6.stop();
461
+ }
462
+ }, _callee6);
463
+ }));
464
+ return _encode.apply(this, arguments);
465
+ }
466
+ var toHttpSigner = function toHttpSigner(signer) {
467
+ var params = ["alg", "keyid"].sort();
468
+ return /*#__PURE__*/function () {
469
+ var _ref10 = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee(_ref9) {
470
+ var request, fields, signatureBase, signatureInput, createCalled, create, result, signatureBuffer, signedHeaders, finalHeaders, _i, _Object$entries, _Object$entries$_i, key, value;
471
+ return _regeneratorRuntime().wrap(function _callee$(_context) {
472
+ while (1) switch (_context.prev = _context.next) {
473
+ case 0:
474
+ request = _ref9.request, fields = _ref9.fields;
475
+ createCalled = false;
476
+ create = function create(injected) {
477
+ createCalled = true;
478
+ var publicKey = injected.publicKey,
479
+ _injected$alg = injected.alg,
480
+ alg = _injected$alg === void 0 ? "rsa-pss-sha512" : _injected$alg;
481
+ var publicKeyBuffer = toView(publicKey);
482
+ var signingParameters = createSigningParameters({
483
+ params: params,
484
+ paramValues: {
485
+ keyid: _base64url["default"].encode(publicKeyBuffer),
486
+ alg: alg
487
+ }
488
+ });
489
+ var signatureBaseArray = createSignatureBase({
490
+ fields: fields
491
+ }, request);
492
+ signatureInput = (0, _structuredHeaders.serializeList)([[signatureBaseArray.map(function (_ref11) {
493
+ var _ref12 = _slicedToArray(_ref11, 1),
494
+ item = _ref12[0];
495
+ return (0, _structuredHeaders.parseItem)(item);
496
+ }), signingParameters]]);
497
+ signatureBaseArray.push(['"@signature-params"', [signatureInput]]);
498
+ signatureBase = formatSignatureBase(signatureBaseArray);
499
+ return new TextEncoder().encode(signatureBase);
500
+ };
501
+ _context.next = 5;
502
+ return signer(create, "httpsig");
503
+ case 5:
504
+ result = _context.sent;
505
+ if (createCalled) {
506
+ _context.next = 8;
507
+ break;
508
+ }
509
+ throw new Error("create() must be invoked in order to construct the data to sign");
510
+ case 8:
511
+ if (!(!result.signature || !result.address)) {
512
+ _context.next = 10;
513
+ break;
514
+ }
515
+ throw new Error("Signer must return signature and address");
516
+ case 10:
517
+ signatureBuffer = toView(result.signature);
518
+ signedHeaders = augmentHeaders(request.headers, signatureBuffer, signatureInput, httpSigName(result.address)); // Only lowercase the signature headers
519
+ finalHeaders = {};
520
+ for (_i = 0, _Object$entries = Object.entries(signedHeaders); _i < _Object$entries.length; _i++) {
521
+ _Object$entries$_i = _slicedToArray(_Object$entries[_i], 2), key = _Object$entries$_i[0], value = _Object$entries$_i[1];
522
+ if (key === "Signature" || key === "Signature-Input") {
523
+ finalHeaders[key.toLowerCase()] = value;
524
+ } else {
525
+ finalHeaders[key] = value;
526
+ }
527
+ }
528
+ return _context.abrupt("return", _objectSpread(_objectSpread({}, request), {}, {
529
+ headers: finalHeaders
530
+ }));
531
+ case 15:
532
+ case "end":
533
+ return _context.stop();
534
+ }
535
+ }, _callee);
536
+ }));
537
+ return function (_x3) {
538
+ return _ref10.apply(this, arguments);
539
+ };
540
+ }();
541
+ };
542
+
543
+ /**
544
+ * Create the main request function that creates signed messages locally
545
+ *
546
+ * @param {Object} config - Configuration object
547
+ * @param {Function} config.signer - Signer function
548
+ * @param {string} [config.HB_URL='http://relay.ao-hb.xyz'] - Base URL
549
+ * @returns {Function} Request function that takes tags and returns signed message
550
+ */
551
+ function createRequest(config) {
552
+ var signer = config.signer,
553
+ _config$url = config.url,
554
+ url = _config$url === void 0 ? "http://localhost:10001" : _config$url;
555
+ if (!signer) {
556
+ throw new Error("Signer is required for mainnet mode");
557
+ }
558
+ return /*#__PURE__*/function () {
559
+ var _request = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee2(fields) {
560
+ 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;
561
+ return _regeneratorRuntime().wrap(function _callee2$(_context2) {
562
+ while (1) switch (_context2.prev = _context2.next) {
563
+ case 0:
564
+ _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
565
+ aoFields = _objectSpread({}, restFields); // Use the HyperBEAM encode function
566
+ _context2.next = 4;
567
+ return encode(aoFields);
568
+ case 4:
569
+ encoded = _context2.sent;
570
+ // If no encoding needed, create minimal structure
571
+ headersObj = encoded ? encoded.headers : {};
572
+ body = encoded ? encoded.body : undefined;
573
+ _url = joinUrl({
574
+ url: url,
575
+ path: path
576
+ }); // Add Content-Length if body exists
577
+ if (body && !headersObj["content-length"]) {
578
+ bodySize = body.size || body.byteLength || 0;
579
+ if (bodySize > 0) {
580
+ headersObj["content-length"] = String(bodySize);
581
+ }
582
+ }
583
+
584
+ // Create lowercase headers for signing
585
+ lowercaseHeaders = {};
586
+ for (_i2 = 0, _Object$entries2 = Object.entries(headersObj); _i2 < _Object$entries2.length; _i2++) {
587
+ _Object$entries2$_i = _slicedToArray(_Object$entries2[_i2], 2), key = _Object$entries2$_i[0], value = _Object$entries2$_i[1];
588
+ lowercaseHeaders[key.toLowerCase()] = value;
589
+ }
590
+
591
+ // Get all header keys for signing (lowercase)
592
+ signingFields = Object.keys(lowercaseHeaders); // Sign the request with lowercase headers
593
+ _context2.next = 14;
594
+ return toHttpSigner(signer)({
595
+ request: {
596
+ url: _url,
597
+ method: method,
598
+ headers: lowercaseHeaders
599
+ },
600
+ fields: signingFields
601
+ });
602
+ case 14:
603
+ signedRequest = _context2.sent;
604
+ // Build final headers: use original casing for all headers except signature headers
605
+ finalHeaders = {}; // First, add all original headers with their original casing
606
+ for (_i3 = 0, _Object$entries3 = Object.entries(headersObj); _i3 < _Object$entries3.length; _i3++) {
607
+ _Object$entries3$_i = _slicedToArray(_Object$entries3[_i3], 2), _key = _Object$entries3$_i[0], _value = _Object$entries3$_i[1];
608
+ finalHeaders[_key] = _value;
609
+ }
610
+
611
+ // Then add the signature headers (which should be lowercase)
612
+ finalHeaders["signature"] = signedRequest.headers["signature"];
613
+ finalHeaders["signature-input"] = signedRequest.headers["signature-input"];
614
+
615
+ // Return the signed message
616
+ result = {
617
+ url: _url,
618
+ method: method,
619
+ headers: finalHeaders
620
+ }; // Only add body if it exists
621
+ if (body) {
622
+ result.body = body;
623
+ }
624
+ return _context2.abrupt("return", result);
625
+ case 22:
626
+ case "end":
627
+ return _context2.stop();
628
+ }
629
+ }, _callee2);
630
+ }));
631
+ function request(_x4) {
632
+ return _request.apply(this, arguments);
633
+ }
634
+ return request;
635
+ }();
636
+ }
637
+ /**
638
+ * Utility function to extract the message ID from a signed message
639
+ * Based on the original code's hash calculation
640
+ */
641
+ function getMessageId(_x5) {
642
+ return _getMessageId.apply(this, arguments);
643
+ }
644
+ function _getMessageId() {
645
+ _getMessageId = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee7(signedMessage) {
646
+ var signatureHeader, match, signature, encoder, data, hashBuffer, hashArray, hashBase64;
647
+ return _regeneratorRuntime().wrap(function _callee7$(_context7) {
648
+ while (1) switch (_context7.prev = _context7.next) {
649
+ case 0:
650
+ // Extract signature from the Signature header
651
+ signatureHeader = signedMessage.headers.Signature || signedMessage.headers.signature;
652
+ match = signatureHeader.match(/Signature:\s*'http-sig-[^:]+:([^']+)'/);
653
+ signature = match ? match[1] : null;
654
+ if (signature) {
655
+ _context7.next = 5;
656
+ break;
657
+ }
658
+ throw new Error("Could not extract signature from headers");
659
+ case 5:
660
+ // Hash the signature to get message ID
661
+ encoder = new TextEncoder();
662
+ data = encoder.encode(signature);
663
+ _context7.next = 9;
664
+ return _crypto["default"].subtle.digest("SHA-256", data);
665
+ case 9:
666
+ hashBuffer = _context7.sent;
667
+ hashArray = Array.from(new Uint8Array(hashBuffer));
668
+ hashBase64 = btoa(String.fromCharCode.apply(String, hashArray));
669
+ return _context7.abrupt("return", hashBase64);
670
+ case 13:
671
+ case "end":
672
+ return _context7.stop();
673
+ }
674
+ }, _callee7);
675
+ }));
676
+ return _getMessageId.apply(this, arguments);
677
+ }
678
+ function send(_x6) {
679
+ return _send.apply(this, arguments);
680
+ }
681
+ /**
682
+ * Convert JWK modulus (n) to PEM format public key
683
+ * @param {Buffer} nBuffer - The modulus buffer
684
+ * @returns {string} PEM formatted public key
685
+ */
686
+ function _send() {
687
+ _send = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee8(signedMsg) {
688
+ var fetchImpl,
689
+ fetchOptions,
690
+ response,
691
+ _args8 = arguments;
692
+ return _regeneratorRuntime().wrap(function _callee8$(_context8) {
693
+ while (1) switch (_context8.prev = _context8.next) {
694
+ case 0:
695
+ fetchImpl = _args8.length > 1 && _args8[1] !== undefined ? _args8[1] : fetch;
696
+ fetchOptions = {
697
+ method: signedMsg.method,
698
+ headers: signedMsg.headers,
699
+ redirect: "follow"
700
+ }; // Only add body if it exists and method supports it
701
+ if (signedMsg.body !== undefined && signedMsg.method !== "GET" && signedMsg.method !== "HEAD") {
702
+ fetchOptions.body = signedMsg.body;
703
+ }
704
+ _context8.next = 5;
705
+ return fetchImpl(signedMsg.url, fetchOptions);
706
+ case 5:
707
+ response = _context8.sent;
708
+ if (!(response.status >= 400)) {
709
+ _context8.next = 14;
710
+ break;
711
+ }
712
+ _context8.t0 = Error;
713
+ _context8.t1 = "".concat(response.status, ": ");
714
+ _context8.next = 11;
715
+ return response.text();
716
+ case 11:
717
+ _context8.t2 = _context8.sent;
718
+ _context8.t3 = _context8.t1.concat.call(_context8.t1, _context8.t2);
719
+ throw new _context8.t0(_context8.t3);
720
+ case 14:
721
+ _context8.t4 = response.headers;
722
+ _context8.next = 17;
723
+ return response.text();
724
+ case 17:
725
+ _context8.t5 = _context8.sent;
726
+ _context8.t6 = response.status;
727
+ return _context8.abrupt("return", {
728
+ headers: _context8.t4,
729
+ body: _context8.t5,
730
+ status: _context8.t6
731
+ });
732
+ case 20:
733
+ case "end":
734
+ return _context8.stop();
735
+ }
736
+ }, _callee8);
737
+ }));
738
+ return _send.apply(this, arguments);
739
+ }
740
+ function jwkModulusToPem(nBuffer) {
741
+ // RSA public key with standard exponent
742
+ var rsaPublicKey = _crypto["default"].createPublicKey({
743
+ key: {
744
+ kty: "RSA",
745
+ n: _base64url["default"].encode(nBuffer),
746
+ e: "AQAB" // Standard exponent 65537
747
+ },
748
+ format: "jwk"
749
+ });
750
+ return rsaPublicKey["export"]({
751
+ type: "spki",
752
+ format: "pem"
753
+ });
754
+ }
755
+
756
+ /**
757
+ * Extract signature name from headers
758
+ * @param {Object} headers - Request headers
759
+ * @returns {string|null} Signature name or null
760
+ */
761
+ function extractSignatureName(headers) {
762
+ var signatureHeader = headers["signature"] || headers["Signature"];
763
+ if (!signatureHeader) return null;
764
+
765
+ // Extract signature name (e.g., "http-sig-xxxxxxxx")
766
+ // Handle both "name:" and "name=" formats
767
+ var match = signatureHeader.match(/^([^:=]+)[:=]/);
768
+ return match ? match[1] : null;
769
+ }
770
+
771
+ /**
772
+ * Extract public key from signature-input header
773
+ * @param {Object} headers - Request headers
774
+ * @param {string} [signatureName] - Optional signature name to look for
775
+ * @returns {Buffer|null} Public key buffer or null
776
+ */
777
+ function extractPublicKeyFromHeaders(headers, signatureName) {
778
+ var signatureInput = headers["signature-input"] || headers["Signature-Input"];
779
+ if (!signatureInput) return null;
780
+
781
+ // If we have a signature name, look for its specific keyid
782
+ var keyidMatch;
783
+ if (signatureName) {
784
+ // The signature-input format is: signatureName=(...);alg="...";keyid="..."
785
+ // We need to match after the signature name
786
+ var signatureSection = signatureInput.substring(signatureInput.indexOf(signatureName));
787
+ keyidMatch = signatureSection.match(/keyid="([^"]+)"/);
788
+ } else {
789
+ // General keyid match
790
+ keyidMatch = signatureInput.match(/keyid="([^"]+)"/);
791
+ }
792
+ if (!keyidMatch) return null;
793
+ try {
794
+ return _base64url["default"].toBuffer(keyidMatch[1]);
795
+ } catch (error) {
796
+ return null;
797
+ }
798
+ }
799
+
800
+ /**
801
+ * Verify an HTTP signed message using http-message-signatures
802
+ *
803
+ * @param {Object} signedMessage - The signed message to verify
804
+ * @param {string} signedMessage.url - Request URL
805
+ * @param {string} signedMessage.method - HTTP method
806
+ * @param {Object} signedMessage.headers - Headers including signature
807
+ * @param {string} [signedMessage.body] - Request body
808
+ * @param {string|Buffer} [publicKey] - Optional public key (if not provided, extracts from keyid)
809
+ * @returns {Object} Verification result
810
+ */
811
+ function verify(_x7, _x8) {
812
+ return _verify.apply(this, arguments);
813
+ }
814
+ /**
815
+ * Extract public key from a signed message
816
+ *
817
+ * @param {Object} signedMessage - The signed message
818
+ * @returns {Buffer|null} The public key buffer or null
819
+ */
820
+ function _verify() {
821
+ _verify = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee13(signedMessage, publicKey) {
822
+ var url, method, headers, body, keyLookup, pem, _signatureName, extractedKey, _pem, _request2, signatureName, extractedPublicKey, signatureInputHeader, algMatch, algorithm, verified, verificationError, verificationResult;
823
+ return _regeneratorRuntime().wrap(function _callee13$(_context13) {
824
+ while (1) switch (_context13.prev = _context13.next) {
825
+ case 0:
826
+ _context13.prev = 0;
827
+ url = signedMessage.url, method = signedMessage.method, headers = signedMessage.headers, body = signedMessage.body; // Determine which public key to use
828
+ if (!publicKey) {
829
+ _context13.next = 7;
830
+ break;
831
+ }
832
+ // Use provided public key
833
+ pem = typeof publicKey === "string" ? publicKey : jwkModulusToPem(publicKey);
834
+ keyLookup = /*#__PURE__*/function () {
835
+ var _ref14 = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee10(keyId) {
836
+ return _regeneratorRuntime().wrap(function _callee10$(_context10) {
837
+ while (1) switch (_context10.prev = _context10.next) {
838
+ case 0:
839
+ return _context10.abrupt("return", {
840
+ id: keyId,
841
+ algs: ["rsa-pss-sha512", "rsa-pss-sha256", "rsa-v1_5-sha256"],
842
+ verify: function () {
843
+ var _verify2 = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee9(data, signature, parameters) {
844
+ var verifier;
845
+ return _regeneratorRuntime().wrap(function _callee9$(_context9) {
846
+ while (1) switch (_context9.prev = _context9.next) {
847
+ case 0:
848
+ verifier = _crypto["default"].createVerify("RSA-SHA".concat(parameters.alg.includes("512") ? "512" : "256"));
849
+ verifier.update(data);
850
+ if (!parameters.alg.startsWith("rsa-pss")) {
851
+ _context9.next = 6;
852
+ break;
853
+ }
854
+ return _context9.abrupt("return", verifier.verify({
855
+ key: pem,
856
+ padding: _crypto["default"].constants.RSA_PKCS1_PSS_PADDING,
857
+ saltLength: _crypto["default"].constants.RSA_PSS_SALTLEN_DIGEST
858
+ }, signature));
859
+ case 6:
860
+ return _context9.abrupt("return", verifier.verify(pem, signature));
861
+ case 7:
862
+ case "end":
863
+ return _context9.stop();
864
+ }
865
+ }, _callee9);
866
+ }));
867
+ function verify(_x11, _x12, _x13) {
868
+ return _verify2.apply(this, arguments);
869
+ }
870
+ return verify;
871
+ }()
872
+ });
873
+ case 1:
874
+ case "end":
875
+ return _context10.stop();
876
+ }
877
+ }, _callee10);
878
+ }));
879
+ return function keyLookup(_x10) {
880
+ return _ref14.apply(this, arguments);
881
+ };
882
+ }();
883
+ _context13.next = 13;
884
+ break;
885
+ case 7:
886
+ // Extract public key from keyid
887
+ _signatureName = extractSignatureName(headers);
888
+ extractedKey = extractPublicKeyFromHeaders(headers, _signatureName);
889
+ if (extractedKey) {
890
+ _context13.next = 11;
891
+ break;
892
+ }
893
+ return _context13.abrupt("return", {
894
+ valid: false,
895
+ error: "No public key provided and none found in signature"
896
+ });
897
+ case 11:
898
+ _pem = jwkModulusToPem(extractedKey);
899
+ keyLookup = /*#__PURE__*/function () {
900
+ var _ref15 = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee12(keyId) {
901
+ return _regeneratorRuntime().wrap(function _callee12$(_context12) {
902
+ while (1) switch (_context12.prev = _context12.next) {
903
+ case 0:
904
+ return _context12.abrupt("return", {
905
+ id: keyId,
906
+ algs: ["rsa-pss-sha512", "rsa-pss-sha256", "rsa-v1_5-sha256"],
907
+ verify: function () {
908
+ var _verify3 = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee11(data, signature, parameters) {
909
+ var verifier, _verified;
910
+ return _regeneratorRuntime().wrap(function _callee11$(_context11) {
911
+ while (1) switch (_context11.prev = _context11.next) {
912
+ case 0:
913
+ _context11.prev = 0;
914
+ verifier = _crypto["default"].createVerify("RSA-SHA".concat(parameters.alg.includes("512") ? "512" : "256"));
915
+ verifier.update(data);
916
+ if (parameters.alg.startsWith("rsa-pss")) {
917
+ _verified = verifier.verify({
918
+ key: _pem,
919
+ padding: _crypto["default"].constants.RSA_PKCS1_PSS_PADDING,
920
+ saltLength: _crypto["default"].constants.RSA_PSS_SALTLEN_DIGEST
921
+ }, signature);
922
+ } else {
923
+ _verified = verifier.verify(_pem, signature);
924
+ }
925
+ return _context11.abrupt("return", _verified);
926
+ case 7:
927
+ _context11.prev = 7;
928
+ _context11.t0 = _context11["catch"](0);
929
+ console.error("Verification error:", _context11.t0);
930
+ return _context11.abrupt("return", false);
931
+ case 11:
932
+ case "end":
933
+ return _context11.stop();
934
+ }
935
+ }, _callee11, null, [[0, 7]]);
936
+ }));
937
+ function verify(_x15, _x16, _x17) {
938
+ return _verify3.apply(this, arguments);
939
+ }
940
+ return verify;
941
+ }()
942
+ });
943
+ case 1:
944
+ case "end":
945
+ return _context12.stop();
946
+ }
947
+ }, _callee12);
948
+ }));
949
+ return function keyLookup(_x14) {
950
+ return _ref15.apply(this, arguments);
951
+ };
952
+ }();
953
+ case 13:
954
+ // Create request object for verification
955
+ _request2 = {
956
+ method: method,
957
+ url: url,
958
+ headers: _objectSpread({}, headers)
959
+ }; // Extract additional info from headers
960
+ signatureName = extractSignatureName(headers);
961
+ extractedPublicKey = extractPublicKeyFromHeaders(headers, signatureName); // Extract algorithm from signature-input
962
+ signatureInputHeader = headers["signature-input"] || headers["Signature-Input"];
963
+ algMatch = signatureInputHeader === null || signatureInputHeader === void 0 ? void 0 : signatureInputHeader.match(/alg="([^"]+)"/);
964
+ algorithm = algMatch ? algMatch[1] : undefined; // Verify using the library
965
+ verified = false;
966
+ verificationError = null;
967
+ _context13.prev = 21;
968
+ _context13.next = 24;
969
+ return verifyMessage({
970
+ keyLookup: keyLookup,
971
+ requiredFields: [] // Don't require specific fields
972
+ }, _request2);
973
+ case 24:
974
+ verificationResult = _context13.sent;
975
+ // If we get here without throwing, verification succeeded
976
+ verified = true;
977
+ _context13.next = 32;
978
+ break;
979
+ case 28:
980
+ _context13.prev = 28;
981
+ _context13.t0 = _context13["catch"](21);
982
+ // Verification failed
983
+ verificationError = _context13.t0.message;
984
+ verified = false;
985
+ case 32:
986
+ return _context13.abrupt("return", _objectSpread({
987
+ valid: true,
988
+ // The signature format is valid
989
+ verified: verified,
990
+ // Whether the cryptographic verification passed
991
+ signatureName: signatureName,
992
+ keyId: extractedPublicKey ? _base64url["default"].encode(extractedPublicKey) : undefined,
993
+ algorithm: algorithm,
994
+ publicKeyFromHeader: extractedPublicKey
995
+ }, verificationError && {
996
+ error: verificationError
997
+ }));
998
+ case 35:
999
+ _context13.prev = 35;
1000
+ _context13.t1 = _context13["catch"](0);
1001
+ return _context13.abrupt("return", {
1002
+ valid: false,
1003
+ error: _context13.t1.message
1004
+ });
1005
+ case 38:
1006
+ case "end":
1007
+ return _context13.stop();
1008
+ }
1009
+ }, _callee13, null, [[0, 35], [21, 28]]);
1010
+ }));
1011
+ return _verify.apply(this, arguments);
1012
+ }
1013
+ function extractPublicKeyFromMessage(signedMessage) {
1014
+ var signatureName = extractSignatureName(signedMessage.headers);
1015
+ return extractPublicKeyFromHeaders(signedMessage.headers, signatureName);
1016
+ }