wao 0.31.2 → 0.32.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,497 @@
1
+ "use strict";
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); }
4
+ Object.defineProperty(exports, "__esModule", {
5
+ value: true
6
+ });
7
+ exports.augmentHeaders = augmentHeaders;
8
+ exports.createSignatureBase = createSignatureBase;
9
+ exports.createSigningParameters = createSigningParameters;
10
+ exports.deriveComponent = deriveComponent;
11
+ exports.extractHeader = extractHeader;
12
+ exports.formatSignatureBase = formatSignatureBase;
13
+ exports.signMessage = signMessage;
14
+ exports.verifyMessage = verifyMessage;
15
+ var _structuredHeaders = require("structured-headers");
16
+ var _structuredHeader = require("./structured-header.js");
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 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); }
19
+ 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); }); }; }
20
+ 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; }
21
+ 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; }
22
+ 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; }
23
+ function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; }
24
+ 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); }
25
+ function _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest(); }
26
+ function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
27
+ 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; } }
28
+ 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; }
29
+ 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; } }
30
+ function _arrayWithHoles(r) { if (Array.isArray(r)) return r; }
31
+ // Default params if not provided
32
+ var defaultParams = ["created", "keyid", "alg", "expires"];
33
+
34
+ // Helper to check if message is a request
35
+ var isRequest = function isRequest(message) {
36
+ return message.method !== undefined;
37
+ };
38
+
39
+ /**
40
+ * Components can be derived from requests or responses (which can also be bound to their request).
41
+ * The signature is essentially (component, params, signingSubject, supplementaryData)
42
+ *
43
+ * MODIFIED: This implementation matches Erlang behavior where @ components are treated as field lookups
44
+ */
45
+ function deriveComponent(component, params, message, req) {
46
+ // MODIFIED: Match Erlang behavior - all @ components become field lookups
47
+ // The Erlang strips @ and calls extract_field for ALL derived components
48
+
49
+ // Remove @ prefix to match Erlang behavior
50
+ var fieldName = component.startsWith("@") ? component.slice(1) : component;
51
+
52
+ // For all @ components, do a field lookup instead of deriving
53
+ // This matches the Erlang identifier_to_component behavior
54
+ if (component.startsWith("@")) {
55
+ try {
56
+ if (params.has("req") && req) {
57
+ return extractHeader(fieldName, params, req, undefined);
58
+ }
59
+ return extractHeader(fieldName, params, message, req);
60
+ } catch (e) {
61
+ // If field not found, return empty or throw based on component type
62
+ throw new Error("No field \"".concat(fieldName, "\" found for component \"").concat(component, "\""));
63
+ }
64
+ }
65
+
66
+ // This code path should not be reached for @ components anymore
67
+ // but keeping it for non-@ components
68
+ throw new Error("Unsupported component \"".concat(component, "\""));
69
+ }
70
+ function extractHeader(header, params, messageOrHeaders, req) {
71
+ var headers = messageOrHeaders.headers || messageOrHeaders;
72
+ var context = params.has("req") ? req === null || req === void 0 ? void 0 : req.headers : headers;
73
+ if (!context) {
74
+ throw new Error("Missing request in request-response bound component");
75
+ }
76
+ var headerTuple = Object.entries(context).find(function (_ref) {
77
+ var _ref2 = _slicedToArray(_ref, 1),
78
+ name = _ref2[0];
79
+ return name.toLowerCase() === header;
80
+ });
81
+ if (!headerTuple) {
82
+ throw new Error("No header \"".concat(header, "\" found in headers"));
83
+ }
84
+ var values = Array.isArray(headerTuple[1]) ? headerTuple[1] : [headerTuple[1]];
85
+ if (params.has("bs") && (params.has("sf") || params.has("key"))) {
86
+ throw new Error("Cannot have both `bs` and (implicit) `sf` parameters");
87
+ }
88
+ if (params.has("sf") || params.has("key")) {
89
+ // strict encoding of field
90
+ var value = values.join(", ");
91
+ var parsed = (0, _structuredHeader.parseHeader)(value);
92
+ if (params.has("key") && !(parsed instanceof _structuredHeader.Dictionary)) {
93
+ throw new Error("Unable to parse header as dictionary");
94
+ }
95
+ if (params.has("key")) {
96
+ var key = params.get("key").toString();
97
+ if (!parsed.has(key)) {
98
+ throw new Error("Unable to find key \"".concat(key, "\" in structured field"));
99
+ }
100
+ return [parsed.get(key)];
101
+ }
102
+ return [parsed.toString()];
103
+ }
104
+ if (params.has("bs")) {
105
+ return [values.map(function (val) {
106
+ var encoded = Buffer.from(val.trim().replace(/\n\s*/gm, " "));
107
+ return ":".concat(encoded.toString("base64"), ":");
108
+ }).join(", ")];
109
+ }
110
+ // raw encoding
111
+ return [values.map(function (val) {
112
+ return val.trim().replace(/\n\s*/gm, " ");
113
+ }).join(", ")];
114
+ }
115
+ function normaliseParams(params) {
116
+ var map = new Map();
117
+ params.forEach(function (value, key) {
118
+ if (value instanceof _structuredHeaders.ByteSequence) {
119
+ map.set(key, value.toBase64());
120
+ } else if (value instanceof _structuredHeaders.Token) {
121
+ map.set(key, value.toString());
122
+ } else {
123
+ map.set(key, value);
124
+ }
125
+ });
126
+ return map;
127
+ }
128
+ function createSignatureBase(config, res, req) {
129
+ return config.fields.reduce(function (base, fieldName) {
130
+ var _parseItem = (0, _structuredHeaders.parseItem)((0, _structuredHeader.quoteString)(fieldName)),
131
+ _parseItem2 = _slicedToArray(_parseItem, 2),
132
+ field = _parseItem2[0],
133
+ params = _parseItem2[1];
134
+ var fieldParams = normaliseParams(params);
135
+ var lcFieldName = field.toLowerCase();
136
+ if (lcFieldName !== "@signature-params") {
137
+ var value = null;
138
+ if (config.componentParser) {
139
+ var _config$componentPars;
140
+ value = (_config$componentPars = config.componentParser(lcFieldName, fieldParams, res, req)) !== null && _config$componentPars !== void 0 ? _config$componentPars : null;
141
+ }
142
+ if (value === null) {
143
+ value = field.startsWith("@") ? deriveComponent(lcFieldName, fieldParams, res, req) : extractHeader(lcFieldName, fieldParams, res, req);
144
+ }
145
+ base.push([(0, _structuredHeaders.serializeItem)([field, params]), value]);
146
+ }
147
+ return base;
148
+ }, []);
149
+ }
150
+ function formatSignatureBase(base) {
151
+ return base.map(function (_ref3) {
152
+ var _ref4 = _slicedToArray(_ref3, 2),
153
+ key = _ref4[0],
154
+ value = _ref4[1];
155
+ var quotedKey = (0, _structuredHeaders.serializeItem)((0, _structuredHeaders.parseItem)((0, _structuredHeader.quoteString)(key)));
156
+
157
+ // MODIFIED: Special handling to match Erlang behavior
158
+ // If the key is "@path", format it as "path" (without @) in the signature base
159
+ var formattedKey = quotedKey;
160
+ if (quotedKey === '"@path"') {
161
+ formattedKey = '"path"';
162
+ }
163
+ return value.map(function (val) {
164
+ return "".concat(formattedKey, ": ").concat(val);
165
+ }).join("\n");
166
+ }).join("\n");
167
+ }
168
+ function createSigningParameters(config) {
169
+ var _config$params;
170
+ var now = new Date();
171
+ return ((_config$params = config.params) !== null && _config$params !== void 0 ? _config$params : defaultParams).reduce(function (params, paramName) {
172
+ var _config$paramValues, _config$paramValues3, _config$paramValues4, _config$paramValues9, _config$paramValues10;
173
+ var value = "";
174
+ switch (paramName.toLowerCase()) {
175
+ case "created":
176
+ // created is optional but recommended. If created is supplied but is null, that's an explicit
177
+ // instruction to *not* include the created parameter
178
+ if (((_config$paramValues = config.paramValues) === null || _config$paramValues === void 0 ? void 0 : _config$paramValues.created) !== null) {
179
+ var _config$paramValues$c, _config$paramValues2;
180
+ var created = (_config$paramValues$c = (_config$paramValues2 = config.paramValues) === null || _config$paramValues2 === void 0 ? void 0 : _config$paramValues2.created) !== null && _config$paramValues$c !== void 0 ? _config$paramValues$c : now;
181
+ value = Math.floor(created.getTime() / 1000);
182
+ }
183
+ break;
184
+ case "expires":
185
+ // attempt to obtain an explicit expires time, otherwise create one that is 300 seconds after
186
+ // creation. Don't add an expires time if there is no created time
187
+ if ((_config$paramValues3 = config.paramValues) !== null && _config$paramValues3 !== void 0 && _config$paramValues3.expires || ((_config$paramValues4 = config.paramValues) === null || _config$paramValues4 === void 0 ? void 0 : _config$paramValues4.created) !== null) {
188
+ var _config$paramValues$e, _config$paramValues5, _config$paramValues$c2, _config$paramValues6;
189
+ var expires = (_config$paramValues$e = (_config$paramValues5 = config.paramValues) === null || _config$paramValues5 === void 0 ? void 0 : _config$paramValues5.expires) !== null && _config$paramValues$e !== void 0 ? _config$paramValues$e : new Date(((_config$paramValues$c2 = (_config$paramValues6 = config.paramValues) === null || _config$paramValues6 === void 0 ? void 0 : _config$paramValues6.created) !== null && _config$paramValues$c2 !== void 0 ? _config$paramValues$c2 : now).getTime() + 300000);
190
+ value = Math.floor(expires.getTime() / 1000);
191
+ }
192
+ break;
193
+ case "keyid":
194
+ {
195
+ var _ref5, _config$paramValues$k, _config$paramValues7;
196
+ // attempt to obtain the keyid omit if missing
197
+ var kid = (_ref5 = (_config$paramValues$k = (_config$paramValues7 = config.paramValues) === null || _config$paramValues7 === void 0 ? void 0 : _config$paramValues7.keyid) !== null && _config$paramValues$k !== void 0 ? _config$paramValues$k : config.key.id) !== null && _ref5 !== void 0 ? _ref5 : null;
198
+ if (kid) {
199
+ value = kid.toString();
200
+ }
201
+ break;
202
+ }
203
+ case "alg":
204
+ {
205
+ var _ref6, _config$paramValues$a, _config$paramValues8;
206
+ // if there is no alg, but it's listed as a required parameter, we should probably
207
+ // throw an error - the problem is that if it's in the default set of params, do we
208
+ // really want to throw if there's no keyid?
209
+ var alg = (_ref6 = (_config$paramValues$a = (_config$paramValues8 = config.paramValues) === null || _config$paramValues8 === void 0 ? void 0 : _config$paramValues8.alg) !== null && _config$paramValues$a !== void 0 ? _config$paramValues$a : config.key.alg) !== null && _ref6 !== void 0 ? _ref6 : null;
210
+ if (alg) {
211
+ value = alg.toString();
212
+ }
213
+ break;
214
+ }
215
+ default:
216
+ if (((_config$paramValues9 = config.paramValues) === null || _config$paramValues9 === void 0 ? void 0 : _config$paramValues9[paramName]) instanceof Date) {
217
+ value = Math.floor(config.paramValues[paramName].getTime() / 1000);
218
+ } else if ((_config$paramValues10 = config.paramValues) !== null && _config$paramValues10 !== void 0 && _config$paramValues10[paramName]) {
219
+ value = config.paramValues[paramName];
220
+ }
221
+ }
222
+ if (value) {
223
+ params.set(paramName, value);
224
+ }
225
+ return params;
226
+ }, new Map());
227
+ }
228
+ function augmentHeaders(headers, signature, signatureInput, name) {
229
+ var signatureHeaderName = "Signature";
230
+ var signatureInputHeaderName = "Signature-Input";
231
+ var signatureHeader = new Map();
232
+ var inputHeader = new Map();
233
+ // check to see if there are already signature/signature-input headers
234
+ // if there are we want to store the current (case-sensitive) name of the header
235
+ // and we want to parse out the current values so we can append our new signature
236
+ for (var header in headers) {
237
+ switch (header.toLowerCase()) {
238
+ case "signature":
239
+ {
240
+ signatureHeaderName = header;
241
+ signatureHeader = (0, _structuredHeaders.parseDictionary)(Array.isArray(headers[header]) ? headers[header].join(", ") : headers[header]);
242
+ break;
243
+ }
244
+ case "signature-input":
245
+ signatureInputHeaderName = header;
246
+ inputHeader = (0, _structuredHeaders.parseDictionary)(Array.isArray(headers[header]) ? headers[header].join(", ") : headers[header]);
247
+ break;
248
+ }
249
+ }
250
+ // find a unique signature name for the header. Check if any existing headers already use
251
+ // the name we intend to use, if there are, add incrementing numbers to the signature name
252
+ // until we have a unique name to use
253
+ var signatureName = name !== null && name !== void 0 ? name : "sig";
254
+ if (signatureHeader.has(signatureName) || inputHeader.has(signatureName)) {
255
+ var count = 0;
256
+ while (signatureHeader.has("".concat(signatureName).concat(count)) || inputHeader.has("".concat(signatureName).concat(count))) {
257
+ count++;
258
+ }
259
+ signatureName += count.toString();
260
+ }
261
+ // append our signature and signature-inputs to the headers and return
262
+ signatureHeader.set(signatureName, [new _structuredHeaders.ByteSequence(signature.toString("base64")), new Map()]);
263
+ inputHeader.set(signatureName, (0, _structuredHeaders.parseList)(signatureInput)[0]);
264
+ return _objectSpread(_objectSpread({}, headers), {}, _defineProperty(_defineProperty({}, signatureHeaderName, (0, _structuredHeaders.serializeDictionary)(signatureHeader)), signatureInputHeaderName, (0, _structuredHeaders.serializeDictionary)(inputHeader)));
265
+ }
266
+ function signMessage(_x, _x2, _x3) {
267
+ return _signMessage.apply(this, arguments);
268
+ }
269
+ function _signMessage() {
270
+ _signMessage = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee(config, message, req) {
271
+ var _config$fields;
272
+ var signingParameters, signatureBase, signatureInput, base, signature;
273
+ return _regeneratorRuntime().wrap(function _callee$(_context) {
274
+ while (1) switch (_context.prev = _context.next) {
275
+ case 0:
276
+ signingParameters = createSigningParameters(config);
277
+ signatureBase = createSignatureBase({
278
+ fields: (_config$fields = config.fields) !== null && _config$fields !== void 0 ? _config$fields : [],
279
+ componentParser: config.componentParser
280
+ }, message, req);
281
+ signatureInput = (0, _structuredHeaders.serializeList)([[signatureBase.map(function (_ref7) {
282
+ var _ref8 = _slicedToArray(_ref7, 1),
283
+ item = _ref8[0];
284
+ return (0, _structuredHeaders.parseItem)(item);
285
+ }), signingParameters]]);
286
+ signatureBase.push(['"@signature-params"', [signatureInput]]);
287
+ base = formatSignatureBase(signatureBase); // call sign
288
+ _context.next = 7;
289
+ return config.key.sign(Buffer.from(base));
290
+ case 7:
291
+ signature = _context.sent;
292
+ return _context.abrupt("return", _objectSpread(_objectSpread({}, message), {}, {
293
+ headers: augmentHeaders(_objectSpread({}, message.headers), signature, signatureInput, config.name)
294
+ }));
295
+ case 9:
296
+ case "end":
297
+ return _context.stop();
298
+ }
299
+ }, _callee);
300
+ }));
301
+ return _signMessage.apply(this, arguments);
302
+ }
303
+ function verifyMessage(_x4, _x5, _x6) {
304
+ return _verifyMessage.apply(this, arguments);
305
+ }
306
+ function _verifyMessage() {
307
+ _verifyMessage = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee3(config, message, req) {
308
+ var _config$tolerance, _config$notAfter, _config$maxAge, _config$requiredParam, _config$requiredField;
309
+ var _Object$entries$reduc, signatures, signatureInputs, now, tolerance, notAfter, maxAge, requiredParams, requiredFields;
310
+ return _regeneratorRuntime().wrap(function _callee3$(_context3) {
311
+ while (1) switch (_context3.prev = _context3.next) {
312
+ case 0:
313
+ _Object$entries$reduc = Object.entries(message.headers).reduce(function (accum, _ref9) {
314
+ var _ref10 = _slicedToArray(_ref9, 2),
315
+ name = _ref10[0],
316
+ value = _ref10[1];
317
+ switch (name.toLowerCase()) {
318
+ case "signature":
319
+ return Object.assign(accum, {
320
+ signatures: (0, _structuredHeaders.parseDictionary)(Array.isArray(value) ? value.join(", ") : value)
321
+ });
322
+ case "signature-input":
323
+ return Object.assign(accum, {
324
+ signatureInputs: (0, _structuredHeaders.parseDictionary)(Array.isArray(value) ? value.join(", ") : value)
325
+ });
326
+ default:
327
+ return accum;
328
+ }
329
+ }, {}), signatures = _Object$entries$reduc.signatures, signatureInputs = _Object$entries$reduc.signatureInputs; // no signatures means an indeterminate result
330
+ if (!(!(signatures !== null && signatures !== void 0 && signatures.size) && !(signatureInputs !== null && signatureInputs !== void 0 && signatureInputs.size))) {
331
+ _context3.next = 3;
332
+ break;
333
+ }
334
+ return _context3.abrupt("return", null);
335
+ case 3:
336
+ if (!(!(signatures !== null && signatures !== void 0 && signatures.size) || !(signatureInputs !== null && signatureInputs !== void 0 && signatureInputs.size))) {
337
+ _context3.next = 5;
338
+ break;
339
+ }
340
+ throw new Error("Incomplete signature headers");
341
+ case 5:
342
+ now = Math.floor(Date.now() / 1000);
343
+ tolerance = (_config$tolerance = config.tolerance) !== null && _config$tolerance !== void 0 ? _config$tolerance : 0;
344
+ notAfter = config.notAfter instanceof Date ? Math.floor(config.notAfter.getTime() / 1000) : (_config$notAfter = config.notAfter) !== null && _config$notAfter !== void 0 ? _config$notAfter : now;
345
+ maxAge = (_config$maxAge = config.maxAge) !== null && _config$maxAge !== void 0 ? _config$maxAge : null;
346
+ requiredParams = (_config$requiredParam = config.requiredParams) !== null && _config$requiredParam !== void 0 ? _config$requiredParam : [];
347
+ requiredFields = (_config$requiredField = config.requiredFields) !== null && _config$requiredField !== void 0 ? _config$requiredField : [];
348
+ return _context3.abrupt("return", Array.from(signatureInputs.entries()).reduce(/*#__PURE__*/function () {
349
+ var _ref12 = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee2(prev, _ref11) {
350
+ var _key$algs;
351
+ var _ref13, name, input, signatureParams, _yield$Promise$all, _yield$Promise$all2, result, key, hasRequiredParams, hasRequiredFields, created, expires, fields, signingBase, base, signature;
352
+ return _regeneratorRuntime().wrap(function _callee2$(_context2) {
353
+ while (1) switch (_context2.prev = _context2.next) {
354
+ case 0:
355
+ _ref13 = _slicedToArray(_ref11, 2), name = _ref13[0], input = _ref13[1];
356
+ signatureParams = Array.from(input[1].entries()).reduce(function (params, _ref14) {
357
+ var _ref15 = _slicedToArray(_ref14, 2),
358
+ key = _ref15[0],
359
+ value = _ref15[1];
360
+ if (value instanceof _structuredHeaders.ByteSequence) {
361
+ Object.assign(params, _defineProperty({}, key, value.toBase64()));
362
+ } else if (value instanceof _structuredHeaders.Token) {
363
+ Object.assign(params, _defineProperty({}, key, value.toString()));
364
+ } else if (key === "created" || key === "expired") {
365
+ Object.assign(params, _defineProperty({}, key, new Date(value * 1000)));
366
+ } else {
367
+ Object.assign(params, _defineProperty({}, key, value));
368
+ }
369
+ return params;
370
+ }, {});
371
+ _context2.next = 4;
372
+ return Promise.all([prev["catch"](function (e) {
373
+ return e;
374
+ }), config.keyLookup(signatureParams)]);
375
+ case 4:
376
+ _yield$Promise$all = _context2.sent;
377
+ _yield$Promise$all2 = _slicedToArray(_yield$Promise$all, 2);
378
+ result = _yield$Promise$all2[0];
379
+ key = _yield$Promise$all2[1];
380
+ if (!(config.all && !key)) {
381
+ _context2.next = 10;
382
+ break;
383
+ }
384
+ throw new Error("Unknown key");
385
+ case 10:
386
+ if (key) {
387
+ _context2.next = 14;
388
+ break;
389
+ }
390
+ if (!(result instanceof Error)) {
391
+ _context2.next = 13;
392
+ break;
393
+ }
394
+ throw result;
395
+ case 13:
396
+ return _context2.abrupt("return", result);
397
+ case 14:
398
+ if (!(input[1].has("alg") && ((_key$algs = key.algs) === null || _key$algs === void 0 ? void 0 : _key$algs.includes(input[1].get("alg"))) === false)) {
399
+ _context2.next = 16;
400
+ break;
401
+ }
402
+ throw new Error("Unsupported key algorithm");
403
+ case 16:
404
+ if ((0, _structuredHeaders.isInnerList)(input)) {
405
+ _context2.next = 18;
406
+ break;
407
+ }
408
+ throw new Error("Malformed signature input");
409
+ case 18:
410
+ hasRequiredParams = requiredParams.every(function (param) {
411
+ return input[1].has(param);
412
+ });
413
+ if (hasRequiredParams) {
414
+ _context2.next = 21;
415
+ break;
416
+ }
417
+ throw new Error("Missing required signature parameters");
418
+ case 21:
419
+ // this could be tricky, what if we say "@method" but there is "@method;req"
420
+ hasRequiredFields = requiredFields.every(function (field) {
421
+ return input[0].some(function (_ref16) {
422
+ var _ref17 = _slicedToArray(_ref16, 1),
423
+ fieldName = _ref17[0];
424
+ return fieldName === field;
425
+ });
426
+ });
427
+ if (hasRequiredFields) {
428
+ _context2.next = 24;
429
+ break;
430
+ }
431
+ throw new Error("Missing required signed fields");
432
+ case 24:
433
+ if (!input[1].has("created")) {
434
+ _context2.next = 28;
435
+ break;
436
+ }
437
+ created = input[1].get("created") - tolerance; // maxAge overrides expires.
438
+ // signature is older than maxAge
439
+ if (!(maxAge && now - created > maxAge || created > notAfter)) {
440
+ _context2.next = 28;
441
+ break;
442
+ }
443
+ throw new Error("Signature is too old");
444
+ case 28:
445
+ if (!input[1].has("expires")) {
446
+ _context2.next = 32;
447
+ break;
448
+ }
449
+ expires = input[1].get("expires") + tolerance; // expired signature
450
+ if (!(now > expires)) {
451
+ _context2.next = 32;
452
+ break;
453
+ }
454
+ throw new Error("Signature has expired");
455
+ case 32:
456
+ // now look to verify the signature! Build the expected "signing base" and verify it!
457
+ fields = input[0].map(function (item) {
458
+ return (0, _structuredHeaders.serializeItem)(item);
459
+ });
460
+ signingBase = createSignatureBase({
461
+ fields: fields,
462
+ componentParser: config.componentParser
463
+ }, message, req);
464
+ signingBase.push(['"@signature-params"', [(0, _structuredHeaders.serializeList)([input])]]);
465
+ base = formatSignatureBase(signingBase);
466
+ signature = signatures.get(name);
467
+ if (signature) {
468
+ _context2.next = 39;
469
+ break;
470
+ }
471
+ throw new Error("No corresponding signature for input");
472
+ case 39:
473
+ if ((0, _structuredHeaders.isByteSequence)(signature[0])) {
474
+ _context2.next = 41;
475
+ break;
476
+ }
477
+ throw new Error("Malformed signature");
478
+ case 41:
479
+ return _context2.abrupt("return", key.verify(Buffer.from(base), Buffer.from(signature[0].toBase64(), "base64"), signatureParams));
480
+ case 42:
481
+ case "end":
482
+ return _context2.stop();
483
+ }
484
+ }, _callee2);
485
+ }));
486
+ return function (_x7, _x8) {
487
+ return _ref12.apply(this, arguments);
488
+ };
489
+ }(), Promise.resolve(null)));
490
+ case 12:
491
+ case "end":
492
+ return _context3.stop();
493
+ }
494
+ }, _callee3);
495
+ }));
496
+ return _verifyMessage.apply(this, arguments);
497
+ }
@@ -0,0 +1,26 @@
1
+ "use strict";
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); }
4
+ Object.defineProperty(exports, "__esModule", {
5
+ value: true
6
+ });
7
+ var _exportNames = {
8
+ httpbis: true
9
+ };
10
+ exports.httpbis = exports["default"] = void 0;
11
+ var httpbis = _interopRequireWildcard(require("./httpbis.js"));
12
+ exports.httpbis = httpbis;
13
+ exports["default"] = httpbis;
14
+ Object.keys(httpbis).forEach(function (key) {
15
+ if (key === "default" || key === "__esModule") return;
16
+ if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return;
17
+ if (key in exports && exports[key] === httpbis[key]) return;
18
+ Object.defineProperty(exports, key, {
19
+ enumerable: true,
20
+ get: function get() {
21
+ return httpbis[key];
22
+ }
23
+ });
24
+ });
25
+ function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(e) { return e ? t : r; })(e); }
26
+ function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != _typeof(e) && "function" != typeof e) return { "default": e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && {}.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n["default"] = e, t && t.set(e, n), n; }