wao 0.23.5 → 0.24.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.
@@ -1,19 +1,17 @@
1
1
  "use strict";
2
2
 
3
+ 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); }
3
4
  Object.defineProperty(exports, "__esModule", {
4
5
  value: true
5
6
  });
6
- exports.createRequest = createRequest;
7
7
  exports.send = send;
8
+ exports.toHttpSigner = void 0;
8
9
  exports.verify = verify;
9
10
  var _base64url = _interopRequireDefault(require("base64url"));
10
11
  var _crypto = _interopRequireDefault(require("crypto"));
11
12
  var _httpMessageSignatures = require("http-message-signatures");
12
13
  var _structuredHeaders = require("structured-headers");
13
- var _excluded = ["path", "method"];
14
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
15
  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
16
  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
17
  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; }
@@ -24,715 +22,25 @@ function _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLim
24
22
  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
23
  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
24
  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
25
  function _toConsumableArray(r) { return _arrayWithoutHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableSpread(); }
31
26
  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
27
  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
28
  function _iterableToArray(r) { if ("undefined" != typeof Symbol && null != r[Symbol.iterator] || null != r["@@iterator"]) return Array.from(r); }
34
29
  function _arrayWithoutHoles(r) { if (Array.isArray(r)) return _arrayLikeToArray(r); }
35
30
  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;
31
+ 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); }
32
+ 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); }); }; }
37
33
  var augmentHeaders = _httpMessageSignatures.httpbis.augmentHeaders,
38
34
  createSignatureBase = _httpMessageSignatures.httpbis.createSignatureBase,
39
35
  createSigningParameters = _httpMessageSignatures.httpbis.createSigningParameters,
40
36
  formatSignatureBase = _httpMessageSignatures.httpbis.formatSignatureBase;
37
+ var verifyMessage = _httpMessageSignatures.httpbis.verifyMessage;
41
38
 
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
-
559
- /**
560
- * Create a signed message with tags (no network request)
561
- *
562
- * @param {Object} fields - Request fields (tags)
563
- * @param {string} [fields.path='/relay/process'] - Path to append to base URL
564
- * @param {string} [fields.method='POST'] - HTTP method
565
- * @returns {Promise<Object>} Signed message object
566
- */
567
- return /*#__PURE__*/function () {
568
- var _request = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee2(fields) {
569
- var _fields$path, path, _fields$method, method, restFields, aoFields, encoded, headersObj, body, _url, bodySize, signingFields, signedRequest, result;
570
- return _regeneratorRuntime().wrap(function _callee2$(_context2) {
571
- while (1) switch (_context2.prev = _context2.next) {
572
- case 0:
573
- _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
574
- aoFields = _objectSpread({}, restFields); // Use the HyperBEAM encode function
575
- _context2.next = 4;
576
- return encode(aoFields);
577
- case 4:
578
- encoded = _context2.sent;
579
- // If no encoding needed, create minimal structure
580
- headersObj = encoded ? encoded.headers : {};
581
- body = encoded ? encoded.body : undefined;
582
- _url = joinUrl({
583
- url: url,
584
- path: path
585
- }); // Add Content-Length if body exists
586
- if (body && !headersObj["content-length"]) {
587
- bodySize = body.size || body.byteLength || 0;
588
- if (bodySize > 0) {
589
- headersObj["content-length"] = String(bodySize);
590
- }
591
- }
592
-
593
- // Get all header keys for signing (might be empty)
594
- // Convert to lowercase for HTTP signature spec compliance
595
- signingFields = Object.keys(headersObj).map(function (key) {
596
- return key.toLowerCase();
597
- }); // Sign the request (even with no fields)
598
- _context2.next = 12;
599
- return toHttpSigner(signer)({
600
- request: {
601
- url: url,
602
- method: method,
603
- headers: headersObj
604
- },
605
- fields: signingFields
606
- });
607
- case 12:
608
- signedRequest = _context2.sent;
609
- // Return the signed message
610
- result = {
611
- url: _url,
612
- method: method,
613
- headers: signedRequest.headers
614
- }; // Only add body if it exists
615
- if (body) {
616
- result.body = body;
617
- }
618
- return _context2.abrupt("return", result);
619
- case 16:
620
- case "end":
621
- return _context2.stop();
622
- }
623
- }, _callee2);
624
- }));
625
- function request(_x4) {
626
- return _request.apply(this, arguments);
627
- }
628
- return request;
629
- }();
630
- }
631
-
632
- /**
633
- * Utility function to extract the message ID from a signed message
634
- * Based on the original code's hash calculation
635
- */
636
- function getMessageId(_x5) {
637
- return _getMessageId.apply(this, arguments);
638
- }
639
- function _getMessageId() {
640
- _getMessageId = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee7(signedMessage) {
641
- var signatureHeader, match, signature, encoder, data, hashBuffer, hashArray, hashBase64;
642
- return _regeneratorRuntime().wrap(function _callee7$(_context7) {
643
- while (1) switch (_context7.prev = _context7.next) {
644
- case 0:
645
- // Extract signature from the Signature header
646
- signatureHeader = signedMessage.headers.Signature || signedMessage.headers.signature;
647
- match = signatureHeader.match(/Signature:\s*'http-sig-[^:]+:([^']+)'/);
648
- signature = match ? match[1] : null;
649
- if (signature) {
650
- _context7.next = 5;
651
- break;
652
- }
653
- throw new Error("Could not extract signature from headers");
654
- case 5:
655
- // Hash the signature to get message ID
656
- encoder = new TextEncoder();
657
- data = encoder.encode(signature);
658
- _context7.next = 9;
659
- return _crypto["default"].subtle.digest("SHA-256", data);
660
- case 9:
661
- hashBuffer = _context7.sent;
662
- hashArray = Array.from(new Uint8Array(hashBuffer));
663
- hashBase64 = btoa(String.fromCharCode.apply(String, hashArray));
664
- return _context7.abrupt("return", hashBase64);
665
- case 13:
666
- case "end":
667
- return _context7.stop();
668
- }
669
- }, _callee7);
670
- }));
671
- return _getMessageId.apply(this, arguments);
672
- }
673
- function send(_x6) {
674
- return _send.apply(this, arguments);
675
- }
676
39
  /**
677
40
  * Convert JWK modulus (n) to PEM format public key
678
41
  * @param {Buffer} nBuffer - The modulus buffer
679
42
  * @returns {string} PEM formatted public key
680
43
  */
681
- function _send() {
682
- _send = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee8(signedMsg) {
683
- var fetchImpl,
684
- fetchOptions,
685
- response,
686
- _args8 = arguments;
687
- return _regeneratorRuntime().wrap(function _callee8$(_context8) {
688
- while (1) switch (_context8.prev = _context8.next) {
689
- case 0:
690
- fetchImpl = _args8.length > 1 && _args8[1] !== undefined ? _args8[1] : fetch;
691
- console.log("signed....", signedMsg);
692
- fetchOptions = {
693
- method: signedMsg.method,
694
- headers: signedMsg.headers,
695
- redirect: "follow"
696
- }; // Only add body if it exists and method supports it
697
- if (signedMsg.body !== undefined && signedMsg.method !== "GET" && signedMsg.method !== "HEAD") {
698
- fetchOptions.body = signedMsg.body;
699
- }
700
- _context8.next = 6;
701
- return fetchImpl(signedMsg.url, fetchOptions);
702
- case 6:
703
- response = _context8.sent;
704
- if (!(response.status >= 400)) {
705
- _context8.next = 15;
706
- break;
707
- }
708
- _context8.t0 = Error;
709
- _context8.t1 = "".concat(response.status, ": ");
710
- _context8.next = 12;
711
- return response.text();
712
- case 12:
713
- _context8.t2 = _context8.sent;
714
- _context8.t3 = _context8.t1.concat.call(_context8.t1, _context8.t2);
715
- throw new _context8.t0(_context8.t3);
716
- case 15:
717
- _context8.t4 = response.headers;
718
- _context8.next = 18;
719
- return response.text();
720
- case 18:
721
- _context8.t5 = _context8.sent;
722
- _context8.t6 = response.status;
723
- return _context8.abrupt("return", {
724
- headers: _context8.t4,
725
- body: _context8.t5,
726
- status: _context8.t6
727
- });
728
- case 21:
729
- case "end":
730
- return _context8.stop();
731
- }
732
- }, _callee8);
733
- }));
734
- return _send.apply(this, arguments);
735
- }
736
44
  function jwkModulusToPem(nBuffer) {
737
45
  // RSA public key with standard exponent
738
46
  var rsaPublicKey = _crypto["default"].createPublicKey({
@@ -764,35 +72,6 @@ function extractSignatureName(headers) {
764
72
  return match ? match[1] : null;
765
73
  }
766
74
 
767
- /**
768
- * Extract public key from signature-input header
769
- * @param {Object} headers - Request headers
770
- * @param {string} [signatureName] - Optional signature name to look for
771
- * @returns {Buffer|null} Public key buffer or null
772
- */
773
- function extractPublicKeyFromHeaders(headers, signatureName) {
774
- var signatureInput = headers["signature-input"] || headers["Signature-Input"];
775
- if (!signatureInput) return null;
776
-
777
- // If we have a signature name, look for its specific keyid
778
- var keyidMatch;
779
- if (signatureName) {
780
- // The signature-input format is: signatureName=(...);alg="...";keyid="..."
781
- // We need to match after the signature name
782
- var signatureSection = signatureInput.substring(signatureInput.indexOf(signatureName));
783
- keyidMatch = signatureSection.match(/keyid="([^"]+)"/);
784
- } else {
785
- // General keyid match
786
- keyidMatch = signatureInput.match(/keyid="([^"]+)"/);
787
- }
788
- if (!keyidMatch) return null;
789
- try {
790
- return _base64url["default"].toBuffer(keyidMatch[1]);
791
- } catch (error) {
792
- return null;
793
- }
794
- }
795
-
796
75
  /**
797
76
  * Verify an HTTP signed message using http-message-signatures
798
77
  *
@@ -804,63 +83,63 @@ function extractPublicKeyFromHeaders(headers, signatureName) {
804
83
  * @param {string|Buffer} [publicKey] - Optional public key (if not provided, extracts from keyid)
805
84
  * @returns {Object} Verification result
806
85
  */
807
- function verify(_x7, _x8) {
86
+ function verify(_x, _x2) {
808
87
  return _verify.apply(this, arguments);
809
88
  }
810
89
  /**
811
- * Extract public key from a signed message
812
- *
813
- * @param {Object} signedMessage - The signed message
814
- * @returns {Buffer|null} The public key buffer or null
90
+ * Extract public key from signature-input header
91
+ * @param {Object} headers - Request headers
92
+ * @param {string} [signatureName] - Optional signature name to look for
93
+ * @returns {Buffer|null} Public key buffer or null
815
94
  */
816
95
  function _verify() {
817
- _verify = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee13(signedMessage, publicKey) {
818
- var url, method, headers, body, keyLookup, pem, _signatureName, extractedKey, _pem, _request2, signatureName, extractedPublicKey, signatureInputHeader, algMatch, algorithm, verified, verificationError, verificationResult;
819
- return _regeneratorRuntime().wrap(function _callee13$(_context13) {
820
- while (1) switch (_context13.prev = _context13.next) {
96
+ _verify = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee6(signedMessage, publicKey) {
97
+ var url, method, headers, body, keyLookup, pem, _signatureName, extractedKey, _pem, _request, signatureName, extractedPublicKey, signatureInputHeader, algMatch, algorithm, verified, verificationError, verificationResult;
98
+ return _regeneratorRuntime().wrap(function _callee6$(_context6) {
99
+ while (1) switch (_context6.prev = _context6.next) {
821
100
  case 0:
822
- _context13.prev = 0;
101
+ _context6.prev = 0;
823
102
  url = signedMessage.url, method = signedMessage.method, headers = signedMessage.headers, body = signedMessage.body; // Determine which public key to use
824
103
  if (!publicKey) {
825
- _context13.next = 7;
104
+ _context6.next = 7;
826
105
  break;
827
106
  }
828
107
  // Use provided public key
829
108
  pem = typeof publicKey === "string" ? publicKey : jwkModulusToPem(publicKey);
830
109
  keyLookup = /*#__PURE__*/function () {
831
- var _ref14 = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee10(keyId) {
832
- return _regeneratorRuntime().wrap(function _callee10$(_context10) {
833
- while (1) switch (_context10.prev = _context10.next) {
110
+ var _ref5 = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee3(keyId) {
111
+ return _regeneratorRuntime().wrap(function _callee3$(_context3) {
112
+ while (1) switch (_context3.prev = _context3.next) {
834
113
  case 0:
835
- return _context10.abrupt("return", {
114
+ return _context3.abrupt("return", {
836
115
  id: keyId,
837
116
  algs: ["rsa-pss-sha512", "rsa-pss-sha256", "rsa-v1_5-sha256"],
838
117
  verify: function () {
839
- var _verify2 = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee9(data, signature, parameters) {
118
+ var _verify2 = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee2(data, signature, parameters) {
840
119
  var verifier;
841
- return _regeneratorRuntime().wrap(function _callee9$(_context9) {
842
- while (1) switch (_context9.prev = _context9.next) {
120
+ return _regeneratorRuntime().wrap(function _callee2$(_context2) {
121
+ while (1) switch (_context2.prev = _context2.next) {
843
122
  case 0:
844
123
  verifier = _crypto["default"].createVerify("RSA-SHA".concat(parameters.alg.includes("512") ? "512" : "256"));
845
124
  verifier.update(data);
846
125
  if (!parameters.alg.startsWith("rsa-pss")) {
847
- _context9.next = 6;
126
+ _context2.next = 6;
848
127
  break;
849
128
  }
850
- return _context9.abrupt("return", verifier.verify({
129
+ return _context2.abrupt("return", verifier.verify({
851
130
  key: pem,
852
131
  padding: _crypto["default"].constants.RSA_PKCS1_PSS_PADDING,
853
132
  saltLength: _crypto["default"].constants.RSA_PSS_SALTLEN_DIGEST
854
133
  }, signature));
855
134
  case 6:
856
- return _context9.abrupt("return", verifier.verify(pem, signature));
135
+ return _context2.abrupt("return", verifier.verify(pem, signature));
857
136
  case 7:
858
137
  case "end":
859
- return _context9.stop();
138
+ return _context2.stop();
860
139
  }
861
- }, _callee9);
140
+ }, _callee2);
862
141
  }));
863
- function verify(_x11, _x12, _x13) {
142
+ function verify(_x6, _x7, _x8) {
864
143
  return _verify2.apply(this, arguments);
865
144
  }
866
145
  return verify;
@@ -868,45 +147,45 @@ function _verify() {
868
147
  });
869
148
  case 1:
870
149
  case "end":
871
- return _context10.stop();
150
+ return _context3.stop();
872
151
  }
873
- }, _callee10);
152
+ }, _callee3);
874
153
  }));
875
- return function keyLookup(_x10) {
876
- return _ref14.apply(this, arguments);
154
+ return function keyLookup(_x5) {
155
+ return _ref5.apply(this, arguments);
877
156
  };
878
157
  }();
879
- _context13.next = 13;
158
+ _context6.next = 13;
880
159
  break;
881
160
  case 7:
882
161
  // Extract public key from keyid
883
162
  _signatureName = extractSignatureName(headers);
884
163
  extractedKey = extractPublicKeyFromHeaders(headers, _signatureName);
885
164
  if (extractedKey) {
886
- _context13.next = 11;
165
+ _context6.next = 11;
887
166
  break;
888
167
  }
889
- return _context13.abrupt("return", {
168
+ return _context6.abrupt("return", {
890
169
  valid: false,
891
170
  error: "No public key provided and none found in signature"
892
171
  });
893
172
  case 11:
894
173
  _pem = jwkModulusToPem(extractedKey);
895
174
  keyLookup = /*#__PURE__*/function () {
896
- var _ref15 = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee12(keyId) {
897
- return _regeneratorRuntime().wrap(function _callee12$(_context12) {
898
- while (1) switch (_context12.prev = _context12.next) {
175
+ var _ref6 = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee5(keyId) {
176
+ return _regeneratorRuntime().wrap(function _callee5$(_context5) {
177
+ while (1) switch (_context5.prev = _context5.next) {
899
178
  case 0:
900
- return _context12.abrupt("return", {
179
+ return _context5.abrupt("return", {
901
180
  id: keyId,
902
181
  algs: ["rsa-pss-sha512", "rsa-pss-sha256", "rsa-v1_5-sha256"],
903
182
  verify: function () {
904
- var _verify3 = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee11(data, signature, parameters) {
183
+ var _verify3 = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee4(data, signature, parameters) {
905
184
  var verifier, _verified;
906
- return _regeneratorRuntime().wrap(function _callee11$(_context11) {
907
- while (1) switch (_context11.prev = _context11.next) {
185
+ return _regeneratorRuntime().wrap(function _callee4$(_context4) {
186
+ while (1) switch (_context4.prev = _context4.next) {
908
187
  case 0:
909
- _context11.prev = 0;
188
+ _context4.prev = 0;
910
189
  verifier = _crypto["default"].createVerify("RSA-SHA".concat(parameters.alg.includes("512") ? "512" : "256"));
911
190
  verifier.update(data);
912
191
  if (parameters.alg.startsWith("rsa-pss")) {
@@ -918,19 +197,19 @@ function _verify() {
918
197
  } else {
919
198
  _verified = verifier.verify(_pem, signature);
920
199
  }
921
- return _context11.abrupt("return", _verified);
200
+ return _context4.abrupt("return", _verified);
922
201
  case 7:
923
- _context11.prev = 7;
924
- _context11.t0 = _context11["catch"](0);
925
- console.error("Verification error:", _context11.t0);
926
- return _context11.abrupt("return", false);
202
+ _context4.prev = 7;
203
+ _context4.t0 = _context4["catch"](0);
204
+ console.error("Verification error:", _context4.t0);
205
+ return _context4.abrupt("return", false);
927
206
  case 11:
928
207
  case "end":
929
- return _context11.stop();
208
+ return _context4.stop();
930
209
  }
931
- }, _callee11, null, [[0, 7]]);
210
+ }, _callee4, null, [[0, 7]]);
932
211
  }));
933
- function verify(_x15, _x16, _x17) {
212
+ function verify(_x10, _x11, _x12) {
934
213
  return _verify3.apply(this, arguments);
935
214
  }
936
215
  return verify;
@@ -938,17 +217,17 @@ function _verify() {
938
217
  });
939
218
  case 1:
940
219
  case "end":
941
- return _context12.stop();
220
+ return _context5.stop();
942
221
  }
943
- }, _callee12);
222
+ }, _callee5);
944
223
  }));
945
- return function keyLookup(_x14) {
946
- return _ref15.apply(this, arguments);
224
+ return function keyLookup(_x9) {
225
+ return _ref6.apply(this, arguments);
947
226
  };
948
227
  }();
949
228
  case 13:
950
229
  // Create request object for verification
951
- _request2 = {
230
+ _request = {
952
231
  method: method,
953
232
  url: url,
954
233
  headers: _objectSpread({}, headers)
@@ -960,26 +239,26 @@ function _verify() {
960
239
  algorithm = algMatch ? algMatch[1] : undefined; // Verify using the library
961
240
  verified = false;
962
241
  verificationError = null;
963
- _context13.prev = 21;
964
- _context13.next = 24;
242
+ _context6.prev = 21;
243
+ _context6.next = 24;
965
244
  return verifyMessage({
966
245
  keyLookup: keyLookup,
967
246
  requiredFields: [] // Don't require specific fields
968
- }, _request2);
247
+ }, _request);
969
248
  case 24:
970
- verificationResult = _context13.sent;
249
+ verificationResult = _context6.sent;
971
250
  // If we get here without throwing, verification succeeded
972
251
  verified = true;
973
- _context13.next = 32;
252
+ _context6.next = 32;
974
253
  break;
975
254
  case 28:
976
- _context13.prev = 28;
977
- _context13.t0 = _context13["catch"](21);
255
+ _context6.prev = 28;
256
+ _context6.t0 = _context6["catch"](21);
978
257
  // Verification failed
979
- verificationError = _context13.t0.message;
258
+ verificationError = _context6.t0.message;
980
259
  verified = false;
981
260
  case 32:
982
- return _context13.abrupt("return", _objectSpread({
261
+ return _context6.abrupt("return", _objectSpread({
983
262
  valid: true,
984
263
  // The signature format is valid
985
264
  verified: verified,
@@ -992,21 +271,209 @@ function _verify() {
992
271
  error: verificationError
993
272
  }));
994
273
  case 35:
995
- _context13.prev = 35;
996
- _context13.t1 = _context13["catch"](0);
997
- return _context13.abrupt("return", {
274
+ _context6.prev = 35;
275
+ _context6.t1 = _context6["catch"](0);
276
+ return _context6.abrupt("return", {
998
277
  valid: false,
999
- error: _context13.t1.message
278
+ error: _context6.t1.message
1000
279
  });
1001
280
  case 38:
1002
281
  case "end":
1003
- return _context13.stop();
282
+ return _context6.stop();
1004
283
  }
1005
- }, _callee13, null, [[0, 35], [21, 28]]);
284
+ }, _callee6, null, [[0, 35], [21, 28]]);
1006
285
  }));
1007
286
  return _verify.apply(this, arguments);
1008
287
  }
288
+ function extractPublicKeyFromHeaders(headers, signatureName) {
289
+ var signatureInput = headers["signature-input"] || headers["Signature-Input"];
290
+ if (!signatureInput) return null;
291
+
292
+ // If we have a signature name, look for its specific keyid
293
+ var keyidMatch;
294
+ if (signatureName) {
295
+ // The signature-input format is: signatureName=(...);alg="...";keyid="..."
296
+ // We need to match after the signature name
297
+ var signatureSection = signatureInput.substring(signatureInput.indexOf(signatureName));
298
+ keyidMatch = signatureSection.match(/keyid="([^"]+)"/);
299
+ } else {
300
+ // General keyid match
301
+ keyidMatch = signatureInput.match(/keyid="([^"]+)"/);
302
+ }
303
+ if (!keyidMatch) return null;
304
+ try {
305
+ return _base64url["default"].toBuffer(keyidMatch[1]);
306
+ } catch (error) {
307
+ return null;
308
+ }
309
+ }
310
+
311
+ /**
312
+ * Extract public key from a signed message
313
+ *
314
+ * @param {Object} signedMessage - The signed message
315
+ * @returns {Buffer|null} The public key buffer or null
316
+ */
1009
317
  function extractPublicKeyFromMessage(signedMessage) {
1010
318
  var signatureName = extractSignatureName(signedMessage.headers);
1011
319
  return extractPublicKeyFromHeaders(signedMessage.headers, signatureName);
1012
- }
320
+ }
321
+ function send(_x3) {
322
+ return _send.apply(this, arguments);
323
+ }
324
+ /**
325
+ * Convert value to Buffer
326
+ */
327
+ function _send() {
328
+ _send = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee7(signedMsg) {
329
+ var fetchImpl,
330
+ fetchOptions,
331
+ response,
332
+ _args7 = arguments;
333
+ return _regeneratorRuntime().wrap(function _callee7$(_context7) {
334
+ while (1) switch (_context7.prev = _context7.next) {
335
+ case 0:
336
+ fetchImpl = _args7.length > 1 && _args7[1] !== undefined ? _args7[1] : fetch;
337
+ fetchOptions = {
338
+ method: signedMsg.method,
339
+ headers: signedMsg.headers,
340
+ redirect: "follow"
341
+ }; // Only add body if it exists and method supports it
342
+ if (signedMsg.body !== undefined && signedMsg.method !== "GET" && signedMsg.method !== "HEAD") {
343
+ fetchOptions.body = signedMsg.body;
344
+ }
345
+ _context7.next = 5;
346
+ return fetchImpl(signedMsg.url, fetchOptions);
347
+ case 5:
348
+ response = _context7.sent;
349
+ if (!(response.status >= 400)) {
350
+ _context7.next = 14;
351
+ break;
352
+ }
353
+ _context7.t0 = Error;
354
+ _context7.t1 = "".concat(response.status, ": ");
355
+ _context7.next = 11;
356
+ return response.text();
357
+ case 11:
358
+ _context7.t2 = _context7.sent;
359
+ _context7.t3 = _context7.t1.concat.call(_context7.t1, _context7.t2);
360
+ throw new _context7.t0(_context7.t3);
361
+ case 14:
362
+ _context7.t4 = response.headers;
363
+ _context7.next = 17;
364
+ return response.text();
365
+ case 17:
366
+ _context7.t5 = _context7.sent;
367
+ _context7.t6 = response.status;
368
+ return _context7.abrupt("return", {
369
+ headers: _context7.t4,
370
+ body: _context7.t5,
371
+ status: _context7.t6
372
+ });
373
+ case 20:
374
+ case "end":
375
+ return _context7.stop();
376
+ }
377
+ }, _callee7);
378
+ }));
379
+ return _send.apply(this, arguments);
380
+ }
381
+ var toView = function toView(value) {
382
+ if (ArrayBuffer.isView(value)) {
383
+ return Buffer.from(value.buffer, value.byteOffset, value.byteLength);
384
+ } else if (typeof value === "string") {
385
+ return _base64url["default"].toBuffer(value);
386
+ }
387
+ throw new Error("Value must be Uint8Array, ArrayBuffer, or base64url-encoded string");
388
+ };
389
+
390
+ /**
391
+ * Generate HTTP signature name from address
392
+ */
393
+ var httpSigName = function httpSigName(address) {
394
+ var decoded = _base64url["default"].toBuffer(address);
395
+ var hexString = _toConsumableArray(decoded.subarray(1, 9)).map(function (_byte) {
396
+ return _byte.toString(16).padStart(2, "0");
397
+ }).join("");
398
+ return "http-sig-".concat(hexString);
399
+ };
400
+
401
+ /**
402
+ * Create HTTP signer wrapper
403
+ */
404
+ var toHttpSigner = exports.toHttpSigner = function toHttpSigner(signer) {
405
+ var params = ["alg", "keyid"].sort();
406
+ return /*#__PURE__*/function () {
407
+ var _ref2 = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee(_ref) {
408
+ var request, fields, signatureBase, signatureInput, createCalled, create, result, signatureBuffer, signedHeaders, finalHeaders, _i, _Object$entries, _Object$entries$_i, key, value;
409
+ return _regeneratorRuntime().wrap(function _callee$(_context) {
410
+ while (1) switch (_context.prev = _context.next) {
411
+ case 0:
412
+ request = _ref.request, fields = _ref.fields;
413
+ createCalled = false;
414
+ create = function create(injected) {
415
+ createCalled = true;
416
+ var publicKey = injected.publicKey,
417
+ _injected$alg = injected.alg,
418
+ alg = _injected$alg === void 0 ? "rsa-pss-sha512" : _injected$alg;
419
+ var publicKeyBuffer = toView(publicKey);
420
+ var signingParameters = createSigningParameters({
421
+ params: params,
422
+ paramValues: {
423
+ keyid: _base64url["default"].encode(publicKeyBuffer),
424
+ alg: alg
425
+ }
426
+ });
427
+ var signatureBaseArray = createSignatureBase({
428
+ fields: fields
429
+ }, request);
430
+ signatureInput = (0, _structuredHeaders.serializeList)([[signatureBaseArray.map(function (_ref3) {
431
+ var _ref4 = _slicedToArray(_ref3, 1),
432
+ item = _ref4[0];
433
+ return (0, _structuredHeaders.parseItem)(item);
434
+ }), signingParameters]]);
435
+ signatureBaseArray.push(['"@signature-params"', [signatureInput]]);
436
+ signatureBase = formatSignatureBase(signatureBaseArray);
437
+ return new TextEncoder().encode(signatureBase);
438
+ };
439
+ _context.next = 5;
440
+ return signer(create, "httpsig");
441
+ case 5:
442
+ result = _context.sent;
443
+ if (createCalled) {
444
+ _context.next = 8;
445
+ break;
446
+ }
447
+ throw new Error("create() must be invoked in order to construct the data to sign");
448
+ case 8:
449
+ if (!(!result.signature || !result.address)) {
450
+ _context.next = 10;
451
+ break;
452
+ }
453
+ throw new Error("Signer must return signature and address");
454
+ case 10:
455
+ signatureBuffer = toView(result.signature);
456
+ signedHeaders = augmentHeaders(request.headers, signatureBuffer, signatureInput, httpSigName(result.address)); // Only lowercase the signature headers
457
+ finalHeaders = {};
458
+ for (_i = 0, _Object$entries = Object.entries(signedHeaders); _i < _Object$entries.length; _i++) {
459
+ _Object$entries$_i = _slicedToArray(_Object$entries[_i], 2), key = _Object$entries$_i[0], value = _Object$entries$_i[1];
460
+ if (key === "Signature" || key === "Signature-Input") {
461
+ finalHeaders[key.toLowerCase()] = value;
462
+ } else {
463
+ finalHeaders[key] = value;
464
+ }
465
+ }
466
+ return _context.abrupt("return", _objectSpread(_objectSpread({}, request), {}, {
467
+ headers: finalHeaders
468
+ }));
469
+ case 15:
470
+ case "end":
471
+ return _context.stop();
472
+ }
473
+ }, _callee);
474
+ }));
475
+ return function (_x4) {
476
+ return _ref2.apply(this, arguments);
477
+ };
478
+ }();
479
+ };