From 0a35237741c01fdfc72d17e3e9e57e522d7fffcf Mon Sep 17 00:00:00 2001 From: bonbud-macryg Date: Mon, 15 Jul 2024 15:49:51 +0100 Subject: [PATCH 01/46] Draft /pro/notification --- pkg/arvo/neo/cod/std/src/pro/notification.hoon | 1 + 1 file changed, 1 insertion(+) create mode 100644 pkg/arvo/neo/cod/std/src/pro/notification.hoon diff --git a/pkg/arvo/neo/cod/std/src/pro/notification.hoon b/pkg/arvo/neo/cod/std/src/pro/notification.hoon new file mode 100644 index 0000000000..1a5df643ec --- /dev/null +++ b/pkg/arvo/neo/cod/std/src/pro/notification.hoon @@ -0,0 +1 @@ +,[read=flag =time =pith =cord] From e6b0d3ffe42196d0925f477907dc51c7d3cd22bc Mon Sep 17 00:00:00 2001 From: bonbud-macryg Date: Mon, 15 Jul 2024 16:07:48 +0100 Subject: [PATCH 02/46] Draft /imp/notifications --- .../neo/cod/std/src/imp/notification.hoon | 1 + .../neo/cod/std/src/imp/notifications.hoon | 40 +++++++++++++++++++ 2 files changed, 41 insertions(+) create mode 100644 pkg/arvo/neo/cod/std/src/imp/notification.hoon create mode 100644 pkg/arvo/neo/cod/std/src/imp/notifications.hoon diff --git a/pkg/arvo/neo/cod/std/src/imp/notification.hoon b/pkg/arvo/neo/cod/std/src/imp/notification.hoon new file mode 100644 index 0000000000..54bcf30465 --- /dev/null +++ b/pkg/arvo/neo/cod/std/src/imp/notification.hoon @@ -0,0 +1 @@ +~ diff --git a/pkg/arvo/neo/cod/std/src/imp/notifications.hoon b/pkg/arvo/neo/cod/std/src/imp/notifications.hoon new file mode 100644 index 0000000000..47c148ef15 --- /dev/null +++ b/pkg/arvo/neo/cod/std/src/imp/notifications.hoon @@ -0,0 +1,40 @@ +/@ notification +^- kook:neo +|% +++ state + *state:neo +:: +++ poke + ^- (set stud:neo) + (sy %notification ~) +:: +++ kids + ^- kids:neo + %- some + :- %y + %- ~(gas by *lads:neo) + :~ :- [[%.n %da] %.n] + [[%pro %notification] ~] + == +:: +++ deps + *deps:neo +:: +++ form + ^- form:neo + |_ [=bowl:neo =aeon:neo =stud:neo state-vase=vase] + ++ init + |= old=(unit pail:neo) + ^- (quip card:neo pail:neo) + [~ *state:neo] + :: + ++ poke + |= [=stud:neo vaz=vase] + ^- (quip card:neo pail:neo) + ?> =(stud %notification) + =/ new !<(notification vaz) + :_ *state:neo + :~ [#/[time.new] [%make %notification `[%notification !>(new)] ~]] + == + -- +-- From 6d3fad486d0958eaa0cd2bfe3bc594742a6d1e92 Mon Sep 17 00:00:00 2001 From: bonbud-macryg Date: Tue, 16 Jul 2024 14:43:10 +0100 Subject: [PATCH 03/46] Draft imp/notification --- .../neo/cod/std/src/imp/notification.hoon | 32 ++++++++++++++++++- .../neo/cod/std/src/imp/notifications.hoon | 22 ++++++++++--- pkg/arvo/neo/cod/std/src/pro/flag.hoon | 1 + .../neo/cod/std/src/pro/notification.hoon | 2 +- 4 files changed, 50 insertions(+), 7 deletions(-) create mode 100644 pkg/arvo/neo/cod/std/src/pro/flag.hoon diff --git a/pkg/arvo/neo/cod/std/src/imp/notification.hoon b/pkg/arvo/neo/cod/std/src/imp/notification.hoon index 54bcf30465..103ec76ae8 100644 --- a/pkg/arvo/neo/cod/std/src/imp/notification.hoon +++ b/pkg/arvo/neo/cod/std/src/imp/notification.hoon @@ -1 +1,31 @@ -~ +/@ flag +/@ notification +^- kook:neo +|% +++ state + ^- curb:neo + [%pro %notification] +++ poke + ^- (set stud:neo) + (sy %flag ~) +++ kids + *kids:neo +++ deps + *deps:neo +++ form + ^- form:neo + |_ [=bowl:neo =aeon:neo =stud:neo state-vase=vase] + +* state !<(notification state-vase) + ++ init + |= old=(unit pail:neo) + ^- (quip card:neo pail:neo) + ?< =(~ old) + [~ u.old] + ++ poke + |= [=stud:neo vaz=vase] + ^- (quip card:neo pail:neo) + ?> =(stud %flag) + ?> =(our.bowl ship.src.bowl) + [~ [%notification [!<(flag vaz) time.state pith.state cord.state]]] + -- +-- diff --git a/pkg/arvo/neo/cod/std/src/imp/notifications.hoon b/pkg/arvo/neo/cod/std/src/imp/notifications.hoon index 47c148ef15..55cb38385a 100644 --- a/pkg/arvo/neo/cod/std/src/imp/notifications.hoon +++ b/pkg/arvo/neo/cod/std/src/imp/notifications.hoon @@ -2,7 +2,8 @@ ^- kook:neo |% ++ state - *state:neo + ^- curb:neo + [%pro %sig] :: ++ poke ^- (set stud:neo) @@ -26,15 +27,26 @@ ++ init |= old=(unit pail:neo) ^- (quip card:neo pail:neo) - [~ *state:neo] + [~ [%sig !>(~)]] :: ++ poke + :: XX mute and block |= [=stud:neo vaz=vase] ^- (quip card:neo pail:neo) ?> =(stud %notification) - =/ new !<(notification vaz) - :_ *state:neo - :~ [#/[time.new] [%make %notification `[%notification !>(new)] ~]] + =/ not !<(notification vaz) + ?< =('' cord.not) + ?< (gth time.not now.bowl) + ?> =(pith.not pith.src.bowl) + :_ [%sig !>(~)] + ?. flag.not + =. flag.not %.y + :~ :- #/[here.bowl]/[da/now.bowl] + [%make %notification `[%notification !>(not)] ~] + == + :~ :- #/[here.bowl]/[da/now.bowl] + [%make %notification `[%notification !>(not)] ~] + :: XX send push notification == -- -- diff --git a/pkg/arvo/neo/cod/std/src/pro/flag.hoon b/pkg/arvo/neo/cod/std/src/pro/flag.hoon new file mode 100644 index 0000000000..0d42f2278a --- /dev/null +++ b/pkg/arvo/neo/cod/std/src/pro/flag.hoon @@ -0,0 +1 @@ +,? diff --git a/pkg/arvo/neo/cod/std/src/pro/notification.hoon b/pkg/arvo/neo/cod/std/src/pro/notification.hoon index 1a5df643ec..332651eab8 100644 --- a/pkg/arvo/neo/cod/std/src/pro/notification.hoon +++ b/pkg/arvo/neo/cod/std/src/pro/notification.hoon @@ -1 +1 @@ -,[read=flag =time =pith =cord] +,[=flag =time =pith =cord] From dacf599ac0e179e440e4a8dbf070473b4aacb360 Mon Sep 17 00:00:00 2001 From: bonbud-macryg Date: Thu, 18 Jul 2024 15:39:58 +0100 Subject: [PATCH 04/46] Draft notifications config and controller --- .../neo/cod/std/src/imp/notifications.hoon | 70 +++++++++++++++---- .../cod/std/src/pro/notifications-config.hoon | 5 ++ .../std/src/pro/notifications-controller.hoon | 2 + 3 files changed, 63 insertions(+), 14 deletions(-) create mode 100644 pkg/arvo/neo/cod/std/src/pro/notifications-config.hoon create mode 100644 pkg/arvo/neo/cod/std/src/pro/notifications-controller.hoon diff --git a/pkg/arvo/neo/cod/std/src/imp/notifications.hoon b/pkg/arvo/neo/cod/std/src/imp/notifications.hoon index 55cb38385a..c5a9fc2598 100644 --- a/pkg/arvo/neo/cod/std/src/imp/notifications.hoon +++ b/pkg/arvo/neo/cod/std/src/imp/notifications.hoon @@ -1,9 +1,11 @@ /@ notification +/@ notifications-config +/@ notifications-controller ^- kook:neo |% ++ state ^- curb:neo - [%pro %sig] + [%pro %notifications-controller] :: ++ poke ^- (set stud:neo) @@ -16,6 +18,8 @@ %- ~(gas by *lads:neo) :~ :- [[%.n %da] %.n] [[%pro %notification] ~] + :- [[%.n %tas] %.n] + [[%pro %notifications-config] ~] == :: ++ deps @@ -24,29 +28,67 @@ ++ form ^- form:neo |_ [=bowl:neo =aeon:neo =stud:neo state-vase=vase] + +* state !<(notifications-controller state-vase) ++ init |= old=(unit pail:neo) ^- (quip card:neo pail:neo) - [~ [%sig !>(~)]] + ?^ old + [~ u.old] + :_ [%notifications-controller !>(|=(notification /default)] + :~ :- #/[here.bowl]/default + :* %make + %notifications-config + `[%notifications-config !>(*notifications-config)] + ~ + == + == :: ++ poke - :: XX mute and block |= [=stud:neo vaz=vase] ^- (quip card:neo pail:neo) - ?> =(stud %notification) - =/ not !<(notification vaz) - ?< =('' cord.not) - ?< (gth time.not now.bowl) - ?> =(pith.not pith.src.bowl) - :_ [%sig !>(~)] - ?. flag.not - =. flag.not %.y + ?+ stud + [~ [%notifications-controller !>(state)]] + %notifications-controller + :: XX need to check vaz? + [~ [%notifications-controller vaz]] + :: + %notification + =/ not !<(notification vaz) + ?< =('' cord.not) + ?< (gth time.not now.bowl) + ?> =(pith.not pith.src.bowl) + =/ config + !< notifications-config + q.pail:(need (~(get by ~(tar of:neo kids.bowl)) (state not))) + :_ [%notifications-controller !>(state)] + :: + :: XX algo has to be more sophisticated than this; + :: has to say "is whole pith.not contained in a kill.config path?" + :: probably check if first iota in pith.not is first iota of a + :: kill.config pith, if yes check second iota, etc. + :: this is to handle killing/muting entire subtrees + ?: (~(has in kill.config) pith.not) + ~ + ?: (~(has in mute.config) pith.not) + =. flag.not %.y + :~ :- #/[here.bowl]/[da/now.bowl] + [%make %notification `[%notification !>(not)]] + == + ?: (~(has in buzz.config) pith.not) + =. flag.not %.y + :~ :- #/[here.bowl]/[da/now.bowl] + [%make %notification `[%notification !>(not)]] + :: XX send push notification + == + ?. flag.not + =. flag.not %.y + :~ :- #/[here.bowl]/[da/now.bowl] + [%make %notification `[%notification !>(not)] ~] + == :~ :- #/[here.bowl]/[da/now.bowl] [%make %notification `[%notification !>(not)] ~] + :: XX send push notification == - :~ :- #/[here.bowl]/[da/now.bowl] - [%make %notification `[%notification !>(not)] ~] - :: XX send push notification == -- -- diff --git a/pkg/arvo/neo/cod/std/src/pro/notifications-config.hoon b/pkg/arvo/neo/cod/std/src/pro/notifications-config.hoon new file mode 100644 index 0000000000..cdb91b09c5 --- /dev/null +++ b/pkg/arvo/neo/cod/std/src/pro/notifications-config.hoon @@ -0,0 +1,5 @@ +^: +$: buzz=(set pith) + mute=(set pith) + kill=(set pith) +== \ No newline at end of file diff --git a/pkg/arvo/neo/cod/std/src/pro/notifications-controller.hoon b/pkg/arvo/neo/cod/std/src/pro/notifications-controller.hoon new file mode 100644 index 0000000000..aa47902156 --- /dev/null +++ b/pkg/arvo/neo/cod/std/src/pro/notifications-controller.hoon @@ -0,0 +1,2 @@ +/@ notification +,$-(notification pith) \ No newline at end of file From eacd5e408166f8ee485c94458caf8fd66ffc9cb9 Mon Sep 17 00:00:00 2001 From: bonbud-macryg Date: Thu, 18 Jul 2024 20:36:00 +0100 Subject: [PATCH 05/46] Draft notifications-config imp --- .../cod/std/src/imp/notifications-config.hoon | 29 +++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 pkg/arvo/neo/cod/std/src/imp/notifications-config.hoon diff --git a/pkg/arvo/neo/cod/std/src/imp/notifications-config.hoon b/pkg/arvo/neo/cod/std/src/imp/notifications-config.hoon new file mode 100644 index 0000000000..0efc9fb20f --- /dev/null +++ b/pkg/arvo/neo/cod/std/src/imp/notifications-config.hoon @@ -0,0 +1,29 @@ +/@ notifications-config +^- kook:neo +|% +++ state + [%pro %notifications] +++ poke + (sy %notifications-config ~) +++ kids + *kids:neo +++ deps + *deps:neo +++ form + ^- form:neo + |_ [=bowl:neo =aeon:neo =stud:neo state-vase=vase] + +* state !<(notifications-config state-vase) + ++ init + |= old=(unit pail:neo) + ^- (quip card:neo pail:neo) + ?^ old + [~ (need old)] + [~ [%notifications-config !>(*state)]] + ++ poke + |= [=stud:neo vaz=vase] + ^- (quip card:neo pail:neo) + ?> =(%notifications-config stud) + =/ new-config !<(notifications-config vaz) + [~ [%notifications-config !>(new-config)]] + -- +-- \ No newline at end of file From ae2c95c6aaca409cc7dffbd07994fa5b5d4ac1b1 Mon Sep 17 00:00:00 2001 From: bonbud-macryg Date: Mon, 22 Jul 2024 11:34:58 +0100 Subject: [PATCH 06/46] Get compiling --- pkg/arvo/neo/cod/std/src/imp/notification.hoon | 8 +++++--- .../neo/cod/std/src/imp/notifications.hoon | 18 ++++++++++-------- 2 files changed, 15 insertions(+), 11 deletions(-) diff --git a/pkg/arvo/neo/cod/std/src/imp/notification.hoon b/pkg/arvo/neo/cod/std/src/imp/notification.hoon index 103ec76ae8..259cedb003 100644 --- a/pkg/arvo/neo/cod/std/src/imp/notification.hoon +++ b/pkg/arvo/neo/cod/std/src/imp/notification.hoon @@ -19,13 +19,15 @@ ++ init |= old=(unit pail:neo) ^- (quip card:neo pail:neo) - ?< =(~ old) - [~ u.old] + ?^ old + [~ u.old] + ~| "notification: no notification provided" + !! ++ poke |= [=stud:neo vaz=vase] ^- (quip card:neo pail:neo) ?> =(stud %flag) ?> =(our.bowl ship.src.bowl) - [~ [%notification [!<(flag vaz) time.state pith.state cord.state]]] + [~ [%notification !>([!<(flag vaz) time.state pith.state cord.state])]] -- -- diff --git a/pkg/arvo/neo/cod/std/src/imp/notifications.hoon b/pkg/arvo/neo/cod/std/src/imp/notifications.hoon index c5a9fc2598..fcf4db5c86 100644 --- a/pkg/arvo/neo/cod/std/src/imp/notifications.hoon +++ b/pkg/arvo/neo/cod/std/src/imp/notifications.hoon @@ -34,8 +34,8 @@ ^- (quip card:neo pail:neo) ?^ old [~ u.old] - :_ [%notifications-controller !>(|=(notification /default)] - :~ :- #/[here.bowl]/default + :_ [%notifications-controller !>(|=(notification /default))] + :~ :- (welp here.bowl ~[%default]) :* %make %notifications-config `[%notifications-config !>(*notifications-config)] @@ -67,25 +67,27 @@ :: probably check if first iota in pith.not is first iota of a :: kill.config pith, if yes check second iota, etc. :: this is to handle killing/muting entire subtrees + :: + :: ?: (~(has in kill.config) pith.not) ~ ?: (~(has in mute.config) pith.not) =. flag.not %.y - :~ :- #/[here.bowl]/[da/now.bowl] - [%make %notification `[%notification !>(not)]] + :~ :- (welp here.bowl ~[[da/now.bowl]]) + [%make %notification `[%notification !>(not)] ~] == ?: (~(has in buzz.config) pith.not) =. flag.not %.y - :~ :- #/[here.bowl]/[da/now.bowl] - [%make %notification `[%notification !>(not)]] + :~ :- (welp here.bowl ~[[da/now.bowl]]) + [%make %notification `[%notification !>(not)] ~] :: XX send push notification == ?. flag.not =. flag.not %.y - :~ :- #/[here.bowl]/[da/now.bowl] + :~ :- (welp here.bowl ~[[da/now.bowl]]) [%make %notification `[%notification !>(not)] ~] == - :~ :- #/[here.bowl]/[da/now.bowl] + :~ :- (welp here.bowl ~[[da/now.bowl]]) [%make %notification `[%notification !>(not)] ~] :: XX send push notification == From 70adbfde7098aa0e3b7fe5ea65fbf62709fd7833 Mon Sep 17 00:00:00 2001 From: bonbud-macryg Date: Mon, 22 Jul 2024 11:36:46 +0100 Subject: [PATCH 07/46] Error on unspecified stud --- pkg/arvo/neo/cod/std/src/imp/notifications.hoon | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pkg/arvo/neo/cod/std/src/imp/notifications.hoon b/pkg/arvo/neo/cod/std/src/imp/notifications.hoon index fcf4db5c86..8660b57db2 100644 --- a/pkg/arvo/neo/cod/std/src/imp/notifications.hoon +++ b/pkg/arvo/neo/cod/std/src/imp/notifications.hoon @@ -47,7 +47,7 @@ |= [=stud:neo vaz=vase] ^- (quip card:neo pail:neo) ?+ stud - [~ [%notifications-controller !>(state)]] + !! %notifications-controller :: XX need to check vaz? [~ [%notifications-controller vaz]] From 4704fdc3c290def850dad403d6b6bdb5eac9745b Mon Sep 17 00:00:00 2001 From: bonbud-macryg Date: Mon, 22 Jul 2024 12:36:52 +0100 Subject: [PATCH 08/46] Check if config contains src pith --- .../neo/cod/std/src/imp/notifications.hoon | 20 ++++++++++++++++--- 1 file changed, 17 insertions(+), 3 deletions(-) diff --git a/pkg/arvo/neo/cod/std/src/imp/notifications.hoon b/pkg/arvo/neo/cod/std/src/imp/notifications.hoon index 8660b57db2..f9b220ad30 100644 --- a/pkg/arvo/neo/cod/std/src/imp/notifications.hoon +++ b/pkg/arvo/neo/cod/std/src/imp/notifications.hoon @@ -2,6 +2,20 @@ /@ notifications-config /@ notifications-controller ^- kook:neo +=> +:: +:: helper core +|% +++ has-pith-in-any + |= [piths=(set pith) query=pith] + ^- ? + %- ~(any in piths) + |= =pith + ^- ? + =(query (scag (lent query) pith)) +-- +:: +:: main core |% ++ state ^- curb:neo @@ -69,14 +83,14 @@ :: this is to handle killing/muting entire subtrees :: :: - ?: (~(has in kill.config) pith.not) + ?: (has-pith-in-any kill.config pith.not) ~ - ?: (~(has in mute.config) pith.not) + ?: (has-pith-in-any mute.config pith.not) =. flag.not %.y :~ :- (welp here.bowl ~[[da/now.bowl]]) [%make %notification `[%notification !>(not)] ~] == - ?: (~(has in buzz.config) pith.not) + ?: (has-pith-in-any buzz.config pith.not) =. flag.not %.y :~ :- (welp here.bowl ~[[da/now.bowl]]) [%make %notification `[%notification !>(not)] ~] From 31909f5a673fe0919384e97aaa313903b6a029f3 Mon Sep 17 00:00:00 2001 From: bonbud-macryg Date: Tue, 23 Jul 2024 11:05:32 +0100 Subject: [PATCH 09/46] Add packaged web-push library --- pkg/arvo/neo/cod/std/src/fil/web-push.js | 9535 ++++++++++++++++++++++ 1 file changed, 9535 insertions(+) create mode 100644 pkg/arvo/neo/cod/std/src/fil/web-push.js diff --git a/pkg/arvo/neo/cod/std/src/fil/web-push.js b/pkg/arvo/neo/cod/std/src/fil/web-push.js new file mode 100644 index 0000000000..5fcc98e70e --- /dev/null +++ b/pkg/arvo/neo/cod/std/src/fil/web-push.js @@ -0,0 +1,9535 @@ +/******/ (() => { // webpackBootstrap +/******/ var __webpack_modules__ = ({ + +/***/ 8073: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + +"use strict"; + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.req = exports.json = exports.toBuffer = void 0; +const http = __importStar(__nccwpck_require__(3685)); +const https = __importStar(__nccwpck_require__(5687)); +async function toBuffer(stream) { + let length = 0; + const chunks = []; + for await (const chunk of stream) { + length += chunk.length; + chunks.push(chunk); + } + return Buffer.concat(chunks, length); +} +exports.toBuffer = toBuffer; +// eslint-disable-next-line @typescript-eslint/no-explicit-any +async function json(stream) { + const buf = await toBuffer(stream); + const str = buf.toString('utf8'); + try { + return JSON.parse(str); + } + catch (_err) { + const err = _err; + err.message += ` (input: ${str})`; + throw err; + } +} +exports.json = json; +function req(url, opts = {}) { + const href = typeof url === 'string' ? url : url.href; + const req = (href.startsWith('https:') ? https : http).request(url, opts); + const promise = new Promise((resolve, reject) => { + req + .once('response', resolve) + .once('error', reject) + .end(); + }); + req.then = promise.then.bind(promise); + return req; +} +exports.req = req; +//# sourceMappingURL=helpers.js.map + +/***/ }), + +/***/ 7111: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + +"use strict"; + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __exportStar = (this && this.__exportStar) || function(m, exports) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.Agent = void 0; +const net = __importStar(__nccwpck_require__(1808)); +const http = __importStar(__nccwpck_require__(3685)); +const https_1 = __nccwpck_require__(5687); +__exportStar(__nccwpck_require__(8073), exports); +const INTERNAL = Symbol('AgentBaseInternalState'); +class Agent extends http.Agent { + constructor(opts) { + super(opts); + this[INTERNAL] = {}; + } + /** + * Determine whether this is an `http` or `https` request. + */ + isSecureEndpoint(options) { + if (options) { + // First check the `secureEndpoint` property explicitly, since this + // means that a parent `Agent` is "passing through" to this instance. + // eslint-disable-next-line @typescript-eslint/no-explicit-any + if (typeof options.secureEndpoint === 'boolean') { + return options.secureEndpoint; + } + // If no explicit `secure` endpoint, check if `protocol` property is + // set. This will usually be the case since using a full string URL + // or `URL` instance should be the most common usage. + if (typeof options.protocol === 'string') { + return options.protocol === 'https:'; + } + } + // Finally, if no `protocol` property was set, then fall back to + // checking the stack trace of the current call stack, and try to + // detect the "https" module. + const { stack } = new Error(); + if (typeof stack !== 'string') + return false; + return stack + .split('\n') + .some((l) => l.indexOf('(https.js:') !== -1 || + l.indexOf('node:https:') !== -1); + } + // In order to support async signatures in `connect()` and Node's native + // connection pooling in `http.Agent`, the array of sockets for each origin + // has to be updated synchronously. This is so the length of the array is + // accurate when `addRequest()` is next called. We achieve this by creating a + // fake socket and adding it to `sockets[origin]` and incrementing + // `totalSocketCount`. + incrementSockets(name) { + // If `maxSockets` and `maxTotalSockets` are both Infinity then there is no + // need to create a fake socket because Node.js native connection pooling + // will never be invoked. + if (this.maxSockets === Infinity && this.maxTotalSockets === Infinity) { + return null; + } + // All instances of `sockets` are expected TypeScript errors. The + // alternative is to add it as a private property of this class but that + // will break TypeScript subclassing. + if (!this.sockets[name]) { + // @ts-expect-error `sockets` is readonly in `@types/node` + this.sockets[name] = []; + } + const fakeSocket = new net.Socket({ writable: false }); + this.sockets[name].push(fakeSocket); + // @ts-expect-error `totalSocketCount` isn't defined in `@types/node` + this.totalSocketCount++; + return fakeSocket; + } + decrementSockets(name, socket) { + if (!this.sockets[name] || socket === null) { + return; + } + const sockets = this.sockets[name]; + const index = sockets.indexOf(socket); + if (index !== -1) { + sockets.splice(index, 1); + // @ts-expect-error `totalSocketCount` isn't defined in `@types/node` + this.totalSocketCount--; + if (sockets.length === 0) { + // @ts-expect-error `sockets` is readonly in `@types/node` + delete this.sockets[name]; + } + } + } + // In order to properly update the socket pool, we need to call `getName()` on + // the core `https.Agent` if it is a secureEndpoint. + getName(options) { + const secureEndpoint = typeof options.secureEndpoint === 'boolean' + ? options.secureEndpoint + : this.isSecureEndpoint(options); + if (secureEndpoint) { + // @ts-expect-error `getName()` isn't defined in `@types/node` + return https_1.Agent.prototype.getName.call(this, options); + } + // @ts-expect-error `getName()` isn't defined in `@types/node` + return super.getName(options); + } + createSocket(req, options, cb) { + const connectOpts = { + ...options, + secureEndpoint: this.isSecureEndpoint(options), + }; + const name = this.getName(connectOpts); + const fakeSocket = this.incrementSockets(name); + Promise.resolve() + .then(() => this.connect(req, connectOpts)) + .then((socket) => { + this.decrementSockets(name, fakeSocket); + if (socket instanceof http.Agent) { + // @ts-expect-error `addRequest()` isn't defined in `@types/node` + return socket.addRequest(req, connectOpts); + } + this[INTERNAL].currentSocket = socket; + // @ts-expect-error `createSocket()` isn't defined in `@types/node` + super.createSocket(req, options, cb); + }, (err) => { + this.decrementSockets(name, fakeSocket); + cb(err); + }); + } + createConnection() { + const socket = this[INTERNAL].currentSocket; + this[INTERNAL].currentSocket = undefined; + if (!socket) { + throw new Error('No socket was returned in the `connect()` function'); + } + return socket; + } + get defaultPort() { + return (this[INTERNAL].defaultPort ?? + (this.protocol === 'https:' ? 443 : 80)); + } + set defaultPort(v) { + if (this[INTERNAL]) { + this[INTERNAL].defaultPort = v; + } + } + get protocol() { + return (this[INTERNAL].protocol ?? + (this.isSecureEndpoint() ? 'https:' : 'http:')); + } + set protocol(v) { + if (this[INTERNAL]) { + this[INTERNAL].protocol = v; + } + } +} +exports.Agent = Agent; +//# sourceMappingURL=index.js.map + +/***/ }), + +/***/ 731: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + + +const asn1 = exports; + +asn1.bignum = __nccwpck_require__(5071); + +asn1.define = (__nccwpck_require__(9819).define); +asn1.base = __nccwpck_require__(7784); +asn1.constants = __nccwpck_require__(7723); +asn1.decoders = __nccwpck_require__(9921); +asn1.encoders = __nccwpck_require__(3650); + + +/***/ }), + +/***/ 9819: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + + +const encoders = __nccwpck_require__(3650); +const decoders = __nccwpck_require__(9921); +const inherits = __nccwpck_require__(9581); + +const api = exports; + +api.define = function define(name, body) { + return new Entity(name, body); +}; + +function Entity(name, body) { + this.name = name; + this.body = body; + + this.decoders = {}; + this.encoders = {}; +} + +Entity.prototype._createNamed = function createNamed(Base) { + const name = this.name; + + function Generated(entity) { + this._initNamed(entity, name); + } + inherits(Generated, Base); + Generated.prototype._initNamed = function _initNamed(entity, name) { + Base.call(this, entity, name); + }; + + return new Generated(this); +}; + +Entity.prototype._getDecoder = function _getDecoder(enc) { + enc = enc || 'der'; + // Lazily create decoder + if (!this.decoders.hasOwnProperty(enc)) + this.decoders[enc] = this._createNamed(decoders[enc]); + return this.decoders[enc]; +}; + +Entity.prototype.decode = function decode(data, enc, options) { + return this._getDecoder(enc).decode(data, options); +}; + +Entity.prototype._getEncoder = function _getEncoder(enc) { + enc = enc || 'der'; + // Lazily create encoder + if (!this.encoders.hasOwnProperty(enc)) + this.encoders[enc] = this._createNamed(encoders[enc]); + return this.encoders[enc]; +}; + +Entity.prototype.encode = function encode(data, enc, /* internal */ reporter) { + return this._getEncoder(enc).encode(data, reporter); +}; + + +/***/ }), + +/***/ 754: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + + +const inherits = __nccwpck_require__(9581); +const Reporter = (__nccwpck_require__(8154)/* .Reporter */ .b); +const Buffer = (__nccwpck_require__(5827).Buffer); + +function DecoderBuffer(base, options) { + Reporter.call(this, options); + if (!Buffer.isBuffer(base)) { + this.error('Input not Buffer'); + return; + } + + this.base = base; + this.offset = 0; + this.length = base.length; +} +inherits(DecoderBuffer, Reporter); +exports.C = DecoderBuffer; + +DecoderBuffer.isDecoderBuffer = function isDecoderBuffer(data) { + if (data instanceof DecoderBuffer) { + return true; + } + + // Or accept compatible API + const isCompatible = typeof data === 'object' && + Buffer.isBuffer(data.base) && + data.constructor.name === 'DecoderBuffer' && + typeof data.offset === 'number' && + typeof data.length === 'number' && + typeof data.save === 'function' && + typeof data.restore === 'function' && + typeof data.isEmpty === 'function' && + typeof data.readUInt8 === 'function' && + typeof data.skip === 'function' && + typeof data.raw === 'function'; + + return isCompatible; +}; + +DecoderBuffer.prototype.save = function save() { + return { offset: this.offset, reporter: Reporter.prototype.save.call(this) }; +}; + +DecoderBuffer.prototype.restore = function restore(save) { + // Return skipped data + const res = new DecoderBuffer(this.base); + res.offset = save.offset; + res.length = this.offset; + + this.offset = save.offset; + Reporter.prototype.restore.call(this, save.reporter); + + return res; +}; + +DecoderBuffer.prototype.isEmpty = function isEmpty() { + return this.offset === this.length; +}; + +DecoderBuffer.prototype.readUInt8 = function readUInt8(fail) { + if (this.offset + 1 <= this.length) + return this.base.readUInt8(this.offset++, true); + else + return this.error(fail || 'DecoderBuffer overrun'); +}; + +DecoderBuffer.prototype.skip = function skip(bytes, fail) { + if (!(this.offset + bytes <= this.length)) + return this.error(fail || 'DecoderBuffer overrun'); + + const res = new DecoderBuffer(this.base); + + // Share reporter state + res._reporterState = this._reporterState; + + res.offset = this.offset; + res.length = this.offset + bytes; + this.offset += bytes; + return res; +}; + +DecoderBuffer.prototype.raw = function raw(save) { + return this.base.slice(save ? save.offset : this.offset, this.length); +}; + +function EncoderBuffer(value, reporter) { + if (Array.isArray(value)) { + this.length = 0; + this.value = value.map(function(item) { + if (!EncoderBuffer.isEncoderBuffer(item)) + item = new EncoderBuffer(item, reporter); + this.length += item.length; + return item; + }, this); + } else if (typeof value === 'number') { + if (!(0 <= value && value <= 0xff)) + return reporter.error('non-byte EncoderBuffer value'); + this.value = value; + this.length = 1; + } else if (typeof value === 'string') { + this.value = value; + this.length = Buffer.byteLength(value); + } else if (Buffer.isBuffer(value)) { + this.value = value; + this.length = value.length; + } else { + return reporter.error('Unsupported type: ' + typeof value); + } +} +exports.R = EncoderBuffer; + +EncoderBuffer.isEncoderBuffer = function isEncoderBuffer(data) { + if (data instanceof EncoderBuffer) { + return true; + } + + // Or accept compatible API + const isCompatible = typeof data === 'object' && + data.constructor.name === 'EncoderBuffer' && + typeof data.length === 'number' && + typeof data.join === 'function'; + + return isCompatible; +}; + +EncoderBuffer.prototype.join = function join(out, offset) { + if (!out) + out = Buffer.alloc(this.length); + if (!offset) + offset = 0; + + if (this.length === 0) + return out; + + if (Array.isArray(this.value)) { + this.value.forEach(function(item) { + item.join(out, offset); + offset += item.length; + }); + } else { + if (typeof this.value === 'number') + out[offset] = this.value; + else if (typeof this.value === 'string') + out.write(this.value, offset); + else if (Buffer.isBuffer(this.value)) + this.value.copy(out, offset); + offset += this.length; + } + + return out; +}; + + +/***/ }), + +/***/ 7784: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + + +const base = exports; + +base.Reporter = (__nccwpck_require__(8154)/* .Reporter */ .b); +base.DecoderBuffer = (__nccwpck_require__(754)/* .DecoderBuffer */ .C); +base.EncoderBuffer = (__nccwpck_require__(754)/* .EncoderBuffer */ .R); +base.Node = __nccwpck_require__(5956); + + +/***/ }), + +/***/ 5956: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +const Reporter = (__nccwpck_require__(8154)/* .Reporter */ .b); +const EncoderBuffer = (__nccwpck_require__(754)/* .EncoderBuffer */ .R); +const DecoderBuffer = (__nccwpck_require__(754)/* .DecoderBuffer */ .C); +const assert = __nccwpck_require__(2104); + +// Supported tags +const tags = [ + 'seq', 'seqof', 'set', 'setof', 'objid', 'bool', + 'gentime', 'utctime', 'null_', 'enum', 'int', 'objDesc', + 'bitstr', 'bmpstr', 'charstr', 'genstr', 'graphstr', 'ia5str', 'iso646str', + 'numstr', 'octstr', 'printstr', 't61str', 'unistr', 'utf8str', 'videostr' +]; + +// Public methods list +const methods = [ + 'key', 'obj', 'use', 'optional', 'explicit', 'implicit', 'def', 'choice', + 'any', 'contains' +].concat(tags); + +// Overrided methods list +const overrided = [ + '_peekTag', '_decodeTag', '_use', + '_decodeStr', '_decodeObjid', '_decodeTime', + '_decodeNull', '_decodeInt', '_decodeBool', '_decodeList', + + '_encodeComposite', '_encodeStr', '_encodeObjid', '_encodeTime', + '_encodeNull', '_encodeInt', '_encodeBool' +]; + +function Node(enc, parent, name) { + const state = {}; + this._baseState = state; + + state.name = name; + state.enc = enc; + + state.parent = parent || null; + state.children = null; + + // State + state.tag = null; + state.args = null; + state.reverseArgs = null; + state.choice = null; + state.optional = false; + state.any = false; + state.obj = false; + state.use = null; + state.useDecoder = null; + state.key = null; + state['default'] = null; + state.explicit = null; + state.implicit = null; + state.contains = null; + + // Should create new instance on each method + if (!state.parent) { + state.children = []; + this._wrap(); + } +} +module.exports = Node; + +const stateProps = [ + 'enc', 'parent', 'children', 'tag', 'args', 'reverseArgs', 'choice', + 'optional', 'any', 'obj', 'use', 'alteredUse', 'key', 'default', 'explicit', + 'implicit', 'contains' +]; + +Node.prototype.clone = function clone() { + const state = this._baseState; + const cstate = {}; + stateProps.forEach(function(prop) { + cstate[prop] = state[prop]; + }); + const res = new this.constructor(cstate.parent); + res._baseState = cstate; + return res; +}; + +Node.prototype._wrap = function wrap() { + const state = this._baseState; + methods.forEach(function(method) { + this[method] = function _wrappedMethod() { + const clone = new this.constructor(this); + state.children.push(clone); + return clone[method].apply(clone, arguments); + }; + }, this); +}; + +Node.prototype._init = function init(body) { + const state = this._baseState; + + assert(state.parent === null); + body.call(this); + + // Filter children + state.children = state.children.filter(function(child) { + return child._baseState.parent === this; + }, this); + assert.equal(state.children.length, 1, 'Root node can have only one child'); +}; + +Node.prototype._useArgs = function useArgs(args) { + const state = this._baseState; + + // Filter children and args + const children = args.filter(function(arg) { + return arg instanceof this.constructor; + }, this); + args = args.filter(function(arg) { + return !(arg instanceof this.constructor); + }, this); + + if (children.length !== 0) { + assert(state.children === null); + state.children = children; + + // Replace parent to maintain backward link + children.forEach(function(child) { + child._baseState.parent = this; + }, this); + } + if (args.length !== 0) { + assert(state.args === null); + state.args = args; + state.reverseArgs = args.map(function(arg) { + if (typeof arg !== 'object' || arg.constructor !== Object) + return arg; + + const res = {}; + Object.keys(arg).forEach(function(key) { + if (key == (key | 0)) + key |= 0; + const value = arg[key]; + res[value] = key; + }); + return res; + }); + } +}; + +// +// Overrided methods +// + +overrided.forEach(function(method) { + Node.prototype[method] = function _overrided() { + const state = this._baseState; + throw new Error(method + ' not implemented for encoding: ' + state.enc); + }; +}); + +// +// Public methods +// + +tags.forEach(function(tag) { + Node.prototype[tag] = function _tagMethod() { + const state = this._baseState; + const args = Array.prototype.slice.call(arguments); + + assert(state.tag === null); + state.tag = tag; + + this._useArgs(args); + + return this; + }; +}); + +Node.prototype.use = function use(item) { + assert(item); + const state = this._baseState; + + assert(state.use === null); + state.use = item; + + return this; +}; + +Node.prototype.optional = function optional() { + const state = this._baseState; + + state.optional = true; + + return this; +}; + +Node.prototype.def = function def(val) { + const state = this._baseState; + + assert(state['default'] === null); + state['default'] = val; + state.optional = true; + + return this; +}; + +Node.prototype.explicit = function explicit(num) { + const state = this._baseState; + + assert(state.explicit === null && state.implicit === null); + state.explicit = num; + + return this; +}; + +Node.prototype.implicit = function implicit(num) { + const state = this._baseState; + + assert(state.explicit === null && state.implicit === null); + state.implicit = num; + + return this; +}; + +Node.prototype.obj = function obj() { + const state = this._baseState; + const args = Array.prototype.slice.call(arguments); + + state.obj = true; + + if (args.length !== 0) + this._useArgs(args); + + return this; +}; + +Node.prototype.key = function key(newKey) { + const state = this._baseState; + + assert(state.key === null); + state.key = newKey; + + return this; +}; + +Node.prototype.any = function any() { + const state = this._baseState; + + state.any = true; + + return this; +}; + +Node.prototype.choice = function choice(obj) { + const state = this._baseState; + + assert(state.choice === null); + state.choice = obj; + this._useArgs(Object.keys(obj).map(function(key) { + return obj[key]; + })); + + return this; +}; + +Node.prototype.contains = function contains(item) { + const state = this._baseState; + + assert(state.use === null); + state.contains = item; + + return this; +}; + +// +// Decoding +// + +Node.prototype._decode = function decode(input, options) { + const state = this._baseState; + + // Decode root node + if (state.parent === null) + return input.wrapResult(state.children[0]._decode(input, options)); + + let result = state['default']; + let present = true; + + let prevKey = null; + if (state.key !== null) + prevKey = input.enterKey(state.key); + + // Check if tag is there + if (state.optional) { + let tag = null; + if (state.explicit !== null) + tag = state.explicit; + else if (state.implicit !== null) + tag = state.implicit; + else if (state.tag !== null) + tag = state.tag; + + if (tag === null && !state.any) { + // Trial and Error + const save = input.save(); + try { + if (state.choice === null) + this._decodeGeneric(state.tag, input, options); + else + this._decodeChoice(input, options); + present = true; + } catch (e) { + present = false; + } + input.restore(save); + } else { + present = this._peekTag(input, tag, state.any); + + if (input.isError(present)) + return present; + } + } + + // Push object on stack + let prevObj; + if (state.obj && present) + prevObj = input.enterObject(); + + if (present) { + // Unwrap explicit values + if (state.explicit !== null) { + const explicit = this._decodeTag(input, state.explicit); + if (input.isError(explicit)) + return explicit; + input = explicit; + } + + const start = input.offset; + + // Unwrap implicit and normal values + if (state.use === null && state.choice === null) { + let save; + if (state.any) + save = input.save(); + const body = this._decodeTag( + input, + state.implicit !== null ? state.implicit : state.tag, + state.any + ); + if (input.isError(body)) + return body; + + if (state.any) + result = input.raw(save); + else + input = body; + } + + if (options && options.track && state.tag !== null) + options.track(input.path(), start, input.length, 'tagged'); + + if (options && options.track && state.tag !== null) + options.track(input.path(), input.offset, input.length, 'content'); + + // Select proper method for tag + if (state.any) { + // no-op + } else if (state.choice === null) { + result = this._decodeGeneric(state.tag, input, options); + } else { + result = this._decodeChoice(input, options); + } + + if (input.isError(result)) + return result; + + // Decode children + if (!state.any && state.choice === null && state.children !== null) { + state.children.forEach(function decodeChildren(child) { + // NOTE: We are ignoring errors here, to let parser continue with other + // parts of encoded data + child._decode(input, options); + }); + } + + // Decode contained/encoded by schema, only in bit or octet strings + if (state.contains && (state.tag === 'octstr' || state.tag === 'bitstr')) { + const data = new DecoderBuffer(result); + result = this._getUse(state.contains, input._reporterState.obj) + ._decode(data, options); + } + } + + // Pop object + if (state.obj && present) + result = input.leaveObject(prevObj); + + // Set key + if (state.key !== null && (result !== null || present === true)) + input.leaveKey(prevKey, state.key, result); + else if (prevKey !== null) + input.exitKey(prevKey); + + return result; +}; + +Node.prototype._decodeGeneric = function decodeGeneric(tag, input, options) { + const state = this._baseState; + + if (tag === 'seq' || tag === 'set') + return null; + if (tag === 'seqof' || tag === 'setof') + return this._decodeList(input, tag, state.args[0], options); + else if (/str$/.test(tag)) + return this._decodeStr(input, tag, options); + else if (tag === 'objid' && state.args) + return this._decodeObjid(input, state.args[0], state.args[1], options); + else if (tag === 'objid') + return this._decodeObjid(input, null, null, options); + else if (tag === 'gentime' || tag === 'utctime') + return this._decodeTime(input, tag, options); + else if (tag === 'null_') + return this._decodeNull(input, options); + else if (tag === 'bool') + return this._decodeBool(input, options); + else if (tag === 'objDesc') + return this._decodeStr(input, tag, options); + else if (tag === 'int' || tag === 'enum') + return this._decodeInt(input, state.args && state.args[0], options); + + if (state.use !== null) { + return this._getUse(state.use, input._reporterState.obj) + ._decode(input, options); + } else { + return input.error('unknown tag: ' + tag); + } +}; + +Node.prototype._getUse = function _getUse(entity, obj) { + + const state = this._baseState; + // Create altered use decoder if implicit is set + state.useDecoder = this._use(entity, obj); + assert(state.useDecoder._baseState.parent === null); + state.useDecoder = state.useDecoder._baseState.children[0]; + if (state.implicit !== state.useDecoder._baseState.implicit) { + state.useDecoder = state.useDecoder.clone(); + state.useDecoder._baseState.implicit = state.implicit; + } + return state.useDecoder; +}; + +Node.prototype._decodeChoice = function decodeChoice(input, options) { + const state = this._baseState; + let result = null; + let match = false; + + Object.keys(state.choice).some(function(key) { + const save = input.save(); + const node = state.choice[key]; + try { + const value = node._decode(input, options); + if (input.isError(value)) + return false; + + result = { type: key, value: value }; + match = true; + } catch (e) { + input.restore(save); + return false; + } + return true; + }, this); + + if (!match) + return input.error('Choice not matched'); + + return result; +}; + +// +// Encoding +// + +Node.prototype._createEncoderBuffer = function createEncoderBuffer(data) { + return new EncoderBuffer(data, this.reporter); +}; + +Node.prototype._encode = function encode(data, reporter, parent) { + const state = this._baseState; + if (state['default'] !== null && state['default'] === data) + return; + + const result = this._encodeValue(data, reporter, parent); + if (result === undefined) + return; + + if (this._skipDefault(result, reporter, parent)) + return; + + return result; +}; + +Node.prototype._encodeValue = function encode(data, reporter, parent) { + const state = this._baseState; + + // Decode root node + if (state.parent === null) + return state.children[0]._encode(data, reporter || new Reporter()); + + let result = null; + + // Set reporter to share it with a child class + this.reporter = reporter; + + // Check if data is there + if (state.optional && data === undefined) { + if (state['default'] !== null) + data = state['default']; + else + return; + } + + // Encode children first + let content = null; + let primitive = false; + if (state.any) { + // Anything that was given is translated to buffer + result = this._createEncoderBuffer(data); + } else if (state.choice) { + result = this._encodeChoice(data, reporter); + } else if (state.contains) { + content = this._getUse(state.contains, parent)._encode(data, reporter); + primitive = true; + } else if (state.children) { + content = state.children.map(function(child) { + if (child._baseState.tag === 'null_') + return child._encode(null, reporter, data); + + if (child._baseState.key === null) + return reporter.error('Child should have a key'); + const prevKey = reporter.enterKey(child._baseState.key); + + if (typeof data !== 'object') + return reporter.error('Child expected, but input is not object'); + + const res = child._encode(data[child._baseState.key], reporter, data); + reporter.leaveKey(prevKey); + + return res; + }, this).filter(function(child) { + return child; + }); + content = this._createEncoderBuffer(content); + } else { + if (state.tag === 'seqof' || state.tag === 'setof') { + // TODO(indutny): this should be thrown on DSL level + if (!(state.args && state.args.length === 1)) + return reporter.error('Too many args for : ' + state.tag); + + if (!Array.isArray(data)) + return reporter.error('seqof/setof, but data is not Array'); + + const child = this.clone(); + child._baseState.implicit = null; + content = this._createEncoderBuffer(data.map(function(item) { + const state = this._baseState; + + return this._getUse(state.args[0], data)._encode(item, reporter); + }, child)); + } else if (state.use !== null) { + result = this._getUse(state.use, parent)._encode(data, reporter); + } else { + content = this._encodePrimitive(state.tag, data); + primitive = true; + } + } + + // Encode data itself + if (!state.any && state.choice === null) { + const tag = state.implicit !== null ? state.implicit : state.tag; + const cls = state.implicit === null ? 'universal' : 'context'; + + if (tag === null) { + if (state.use === null) + reporter.error('Tag could be omitted only for .use()'); + } else { + if (state.use === null) + result = this._encodeComposite(tag, primitive, cls, content); + } + } + + // Wrap in explicit + if (state.explicit !== null) + result = this._encodeComposite(state.explicit, false, 'context', result); + + return result; +}; + +Node.prototype._encodeChoice = function encodeChoice(data, reporter) { + const state = this._baseState; + + const node = state.choice[data.type]; + if (!node) { + assert( + false, + data.type + ' not found in ' + + JSON.stringify(Object.keys(state.choice))); + } + return node._encode(data.value, reporter); +}; + +Node.prototype._encodePrimitive = function encodePrimitive(tag, data) { + const state = this._baseState; + + if (/str$/.test(tag)) + return this._encodeStr(data, tag); + else if (tag === 'objid' && state.args) + return this._encodeObjid(data, state.reverseArgs[0], state.args[1]); + else if (tag === 'objid') + return this._encodeObjid(data, null, null); + else if (tag === 'gentime' || tag === 'utctime') + return this._encodeTime(data, tag); + else if (tag === 'null_') + return this._encodeNull(); + else if (tag === 'int' || tag === 'enum') + return this._encodeInt(data, state.args && state.reverseArgs[0]); + else if (tag === 'bool') + return this._encodeBool(data); + else if (tag === 'objDesc') + return this._encodeStr(data, tag); + else + throw new Error('Unsupported tag: ' + tag); +}; + +Node.prototype._isNumstr = function isNumstr(str) { + return /^[0-9 ]*$/.test(str); +}; + +Node.prototype._isPrintstr = function isPrintstr(str) { + return /^[A-Za-z0-9 '()+,-./:=?]*$/.test(str); +}; + + +/***/ }), + +/***/ 8154: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + + +const inherits = __nccwpck_require__(9581); + +function Reporter(options) { + this._reporterState = { + obj: null, + path: [], + options: options || {}, + errors: [] + }; +} +exports.b = Reporter; + +Reporter.prototype.isError = function isError(obj) { + return obj instanceof ReporterError; +}; + +Reporter.prototype.save = function save() { + const state = this._reporterState; + + return { obj: state.obj, pathLen: state.path.length }; +}; + +Reporter.prototype.restore = function restore(data) { + const state = this._reporterState; + + state.obj = data.obj; + state.path = state.path.slice(0, data.pathLen); +}; + +Reporter.prototype.enterKey = function enterKey(key) { + return this._reporterState.path.push(key); +}; + +Reporter.prototype.exitKey = function exitKey(index) { + const state = this._reporterState; + + state.path = state.path.slice(0, index - 1); +}; + +Reporter.prototype.leaveKey = function leaveKey(index, key, value) { + const state = this._reporterState; + + this.exitKey(index); + if (state.obj !== null) + state.obj[key] = value; +}; + +Reporter.prototype.path = function path() { + return this._reporterState.path.join('/'); +}; + +Reporter.prototype.enterObject = function enterObject() { + const state = this._reporterState; + + const prev = state.obj; + state.obj = {}; + return prev; +}; + +Reporter.prototype.leaveObject = function leaveObject(prev) { + const state = this._reporterState; + + const now = state.obj; + state.obj = prev; + return now; +}; + +Reporter.prototype.error = function error(msg) { + let err; + const state = this._reporterState; + + const inherited = msg instanceof ReporterError; + if (inherited) { + err = msg; + } else { + err = new ReporterError(state.path.map(function(elem) { + return '[' + JSON.stringify(elem) + ']'; + }).join(''), msg.message || msg, msg.stack); + } + + if (!state.options.partial) + throw err; + + if (!inherited) + state.errors.push(err); + + return err; +}; + +Reporter.prototype.wrapResult = function wrapResult(result) { + const state = this._reporterState; + if (!state.options.partial) + return result; + + return { + result: this.isError(result) ? null : result, + errors: state.errors + }; +}; + +function ReporterError(path, msg) { + this.path = path; + this.rethrow(msg); +} +inherits(ReporterError, Error); + +ReporterError.prototype.rethrow = function rethrow(msg) { + this.message = msg + ' at: ' + (this.path || '(shallow)'); + if (Error.captureStackTrace) + Error.captureStackTrace(this, ReporterError); + + if (!this.stack) { + try { + // IE only adds stack when thrown + throw new Error(this.message); + } catch (e) { + this.stack = e.stack; + } + } + return this; +}; + + +/***/ }), + +/***/ 9115: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + + +// Helper +function reverse(map) { + const res = {}; + + Object.keys(map).forEach(function(key) { + // Convert key to integer if it is stringified + if ((key | 0) == key) + key = key | 0; + + const value = map[key]; + res[value] = key; + }); + + return res; +} + +exports.tagClass = { + 0: 'universal', + 1: 'application', + 2: 'context', + 3: 'private' +}; +exports.tagClassByName = reverse(exports.tagClass); + +exports.tag = { + 0x00: 'end', + 0x01: 'bool', + 0x02: 'int', + 0x03: 'bitstr', + 0x04: 'octstr', + 0x05: 'null_', + 0x06: 'objid', + 0x07: 'objDesc', + 0x08: 'external', + 0x09: 'real', + 0x0a: 'enum', + 0x0b: 'embed', + 0x0c: 'utf8str', + 0x0d: 'relativeOid', + 0x10: 'seq', + 0x11: 'set', + 0x12: 'numstr', + 0x13: 'printstr', + 0x14: 't61str', + 0x15: 'videostr', + 0x16: 'ia5str', + 0x17: 'utctime', + 0x18: 'gentime', + 0x19: 'graphstr', + 0x1a: 'iso646str', + 0x1b: 'genstr', + 0x1c: 'unistr', + 0x1d: 'charstr', + 0x1e: 'bmpstr' +}; +exports.tagByName = reverse(exports.tag); + + +/***/ }), + +/***/ 7723: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + + +const constants = exports; + +// Helper +constants._reverse = function reverse(map) { + const res = {}; + + Object.keys(map).forEach(function(key) { + // Convert key to integer if it is stringified + if ((key | 0) == key) + key = key | 0; + + const value = map[key]; + res[value] = key; + }); + + return res; +}; + +constants.der = __nccwpck_require__(9115); + + +/***/ }), + +/***/ 126: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +const inherits = __nccwpck_require__(9581); + +const bignum = __nccwpck_require__(5071); +const DecoderBuffer = (__nccwpck_require__(754)/* .DecoderBuffer */ .C); +const Node = __nccwpck_require__(5956); + +// Import DER constants +const der = __nccwpck_require__(9115); + +function DERDecoder(entity) { + this.enc = 'der'; + this.name = entity.name; + this.entity = entity; + + // Construct base tree + this.tree = new DERNode(); + this.tree._init(entity.body); +} +module.exports = DERDecoder; + +DERDecoder.prototype.decode = function decode(data, options) { + if (!DecoderBuffer.isDecoderBuffer(data)) { + data = new DecoderBuffer(data, options); + } + + return this.tree._decode(data, options); +}; + +// Tree methods + +function DERNode(parent) { + Node.call(this, 'der', parent); +} +inherits(DERNode, Node); + +DERNode.prototype._peekTag = function peekTag(buffer, tag, any) { + if (buffer.isEmpty()) + return false; + + const state = buffer.save(); + const decodedTag = derDecodeTag(buffer, 'Failed to peek tag: "' + tag + '"'); + if (buffer.isError(decodedTag)) + return decodedTag; + + buffer.restore(state); + + return decodedTag.tag === tag || decodedTag.tagStr === tag || + (decodedTag.tagStr + 'of') === tag || any; +}; + +DERNode.prototype._decodeTag = function decodeTag(buffer, tag, any) { + const decodedTag = derDecodeTag(buffer, + 'Failed to decode tag of "' + tag + '"'); + if (buffer.isError(decodedTag)) + return decodedTag; + + let len = derDecodeLen(buffer, + decodedTag.primitive, + 'Failed to get length of "' + tag + '"'); + + // Failure + if (buffer.isError(len)) + return len; + + if (!any && + decodedTag.tag !== tag && + decodedTag.tagStr !== tag && + decodedTag.tagStr + 'of' !== tag) { + return buffer.error('Failed to match tag: "' + tag + '"'); + } + + if (decodedTag.primitive || len !== null) + return buffer.skip(len, 'Failed to match body of: "' + tag + '"'); + + // Indefinite length... find END tag + const state = buffer.save(); + const res = this._skipUntilEnd( + buffer, + 'Failed to skip indefinite length body: "' + this.tag + '"'); + if (buffer.isError(res)) + return res; + + len = buffer.offset - state.offset; + buffer.restore(state); + return buffer.skip(len, 'Failed to match body of: "' + tag + '"'); +}; + +DERNode.prototype._skipUntilEnd = function skipUntilEnd(buffer, fail) { + for (;;) { + const tag = derDecodeTag(buffer, fail); + if (buffer.isError(tag)) + return tag; + const len = derDecodeLen(buffer, tag.primitive, fail); + if (buffer.isError(len)) + return len; + + let res; + if (tag.primitive || len !== null) + res = buffer.skip(len); + else + res = this._skipUntilEnd(buffer, fail); + + // Failure + if (buffer.isError(res)) + return res; + + if (tag.tagStr === 'end') + break; + } +}; + +DERNode.prototype._decodeList = function decodeList(buffer, tag, decoder, + options) { + const result = []; + while (!buffer.isEmpty()) { + const possibleEnd = this._peekTag(buffer, 'end'); + if (buffer.isError(possibleEnd)) + return possibleEnd; + + const res = decoder.decode(buffer, 'der', options); + if (buffer.isError(res) && possibleEnd) + break; + result.push(res); + } + return result; +}; + +DERNode.prototype._decodeStr = function decodeStr(buffer, tag) { + if (tag === 'bitstr') { + const unused = buffer.readUInt8(); + if (buffer.isError(unused)) + return unused; + return { unused: unused, data: buffer.raw() }; + } else if (tag === 'bmpstr') { + const raw = buffer.raw(); + if (raw.length % 2 === 1) + return buffer.error('Decoding of string type: bmpstr length mismatch'); + + let str = ''; + for (let i = 0; i < raw.length / 2; i++) { + str += String.fromCharCode(raw.readUInt16BE(i * 2)); + } + return str; + } else if (tag === 'numstr') { + const numstr = buffer.raw().toString('ascii'); + if (!this._isNumstr(numstr)) { + return buffer.error('Decoding of string type: ' + + 'numstr unsupported characters'); + } + return numstr; + } else if (tag === 'octstr') { + return buffer.raw(); + } else if (tag === 'objDesc') { + return buffer.raw(); + } else if (tag === 'printstr') { + const printstr = buffer.raw().toString('ascii'); + if (!this._isPrintstr(printstr)) { + return buffer.error('Decoding of string type: ' + + 'printstr unsupported characters'); + } + return printstr; + } else if (/str$/.test(tag)) { + return buffer.raw().toString(); + } else { + return buffer.error('Decoding of string type: ' + tag + ' unsupported'); + } +}; + +DERNode.prototype._decodeObjid = function decodeObjid(buffer, values, relative) { + let result; + const identifiers = []; + let ident = 0; + let subident = 0; + while (!buffer.isEmpty()) { + subident = buffer.readUInt8(); + ident <<= 7; + ident |= subident & 0x7f; + if ((subident & 0x80) === 0) { + identifiers.push(ident); + ident = 0; + } + } + if (subident & 0x80) + identifiers.push(ident); + + const first = (identifiers[0] / 40) | 0; + const second = identifiers[0] % 40; + + if (relative) + result = identifiers; + else + result = [first, second].concat(identifiers.slice(1)); + + if (values) { + let tmp = values[result.join(' ')]; + if (tmp === undefined) + tmp = values[result.join('.')]; + if (tmp !== undefined) + result = tmp; + } + + return result; +}; + +DERNode.prototype._decodeTime = function decodeTime(buffer, tag) { + const str = buffer.raw().toString(); + + let year; + let mon; + let day; + let hour; + let min; + let sec; + if (tag === 'gentime') { + year = str.slice(0, 4) | 0; + mon = str.slice(4, 6) | 0; + day = str.slice(6, 8) | 0; + hour = str.slice(8, 10) | 0; + min = str.slice(10, 12) | 0; + sec = str.slice(12, 14) | 0; + } else if (tag === 'utctime') { + year = str.slice(0, 2) | 0; + mon = str.slice(2, 4) | 0; + day = str.slice(4, 6) | 0; + hour = str.slice(6, 8) | 0; + min = str.slice(8, 10) | 0; + sec = str.slice(10, 12) | 0; + if (year < 70) + year = 2000 + year; + else + year = 1900 + year; + } else { + return buffer.error('Decoding ' + tag + ' time is not supported yet'); + } + + return Date.UTC(year, mon - 1, day, hour, min, sec, 0); +}; + +DERNode.prototype._decodeNull = function decodeNull() { + return null; +}; + +DERNode.prototype._decodeBool = function decodeBool(buffer) { + const res = buffer.readUInt8(); + if (buffer.isError(res)) + return res; + else + return res !== 0; +}; + +DERNode.prototype._decodeInt = function decodeInt(buffer, values) { + // Bigint, return as it is (assume big endian) + const raw = buffer.raw(); + let res = new bignum(raw); + + if (values) + res = values[res.toString(10)] || res; + + return res; +}; + +DERNode.prototype._use = function use(entity, obj) { + if (typeof entity === 'function') + entity = entity(obj); + return entity._getDecoder('der').tree; +}; + +// Utility methods + +function derDecodeTag(buf, fail) { + let tag = buf.readUInt8(fail); + if (buf.isError(tag)) + return tag; + + const cls = der.tagClass[tag >> 6]; + const primitive = (tag & 0x20) === 0; + + // Multi-octet tag - load + if ((tag & 0x1f) === 0x1f) { + let oct = tag; + tag = 0; + while ((oct & 0x80) === 0x80) { + oct = buf.readUInt8(fail); + if (buf.isError(oct)) + return oct; + + tag <<= 7; + tag |= oct & 0x7f; + } + } else { + tag &= 0x1f; + } + const tagStr = der.tag[tag]; + + return { + cls: cls, + primitive: primitive, + tag: tag, + tagStr: tagStr + }; +} + +function derDecodeLen(buf, primitive, fail) { + let len = buf.readUInt8(fail); + if (buf.isError(len)) + return len; + + // Indefinite form + if (!primitive && len === 0x80) + return null; + + // Definite form + if ((len & 0x80) === 0) { + // Short form + return len; + } + + // Long form + const num = len & 0x7f; + if (num > 4) + return buf.error('length octect is too long'); + + len = 0; + for (let i = 0; i < num; i++) { + len <<= 8; + const j = buf.readUInt8(fail); + if (buf.isError(j)) + return j; + len |= j; + } + + return len; +} + + +/***/ }), + +/***/ 9921: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + + +const decoders = exports; + +decoders.der = __nccwpck_require__(126); +decoders.pem = __nccwpck_require__(3274); + + +/***/ }), + +/***/ 3274: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +const inherits = __nccwpck_require__(9581); +const Buffer = (__nccwpck_require__(5827).Buffer); + +const DERDecoder = __nccwpck_require__(126); + +function PEMDecoder(entity) { + DERDecoder.call(this, entity); + this.enc = 'pem'; +} +inherits(PEMDecoder, DERDecoder); +module.exports = PEMDecoder; + +PEMDecoder.prototype.decode = function decode(data, options) { + const lines = data.toString().split(/[\r\n]+/g); + + const label = options.label.toUpperCase(); + + const re = /^-----(BEGIN|END) ([^-]+)-----$/; + let start = -1; + let end = -1; + for (let i = 0; i < lines.length; i++) { + const match = lines[i].match(re); + if (match === null) + continue; + + if (match[2] !== label) + continue; + + if (start === -1) { + if (match[1] !== 'BEGIN') + break; + start = i; + } else { + if (match[1] !== 'END') + break; + end = i; + break; + } + } + if (start === -1 || end === -1) + throw new Error('PEM section not found for: ' + label); + + const base64 = lines.slice(start + 1, end).join(''); + // Remove excessive symbols + base64.replace(/[^a-z0-9+/=]+/gi, ''); + + const input = Buffer.from(base64, 'base64'); + return DERDecoder.prototype.decode.call(this, input, options); +}; + + +/***/ }), + +/***/ 1446: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +const inherits = __nccwpck_require__(9581); +const Buffer = (__nccwpck_require__(5827).Buffer); +const Node = __nccwpck_require__(5956); + +// Import DER constants +const der = __nccwpck_require__(9115); + +function DEREncoder(entity) { + this.enc = 'der'; + this.name = entity.name; + this.entity = entity; + + // Construct base tree + this.tree = new DERNode(); + this.tree._init(entity.body); +} +module.exports = DEREncoder; + +DEREncoder.prototype.encode = function encode(data, reporter) { + return this.tree._encode(data, reporter).join(); +}; + +// Tree methods + +function DERNode(parent) { + Node.call(this, 'der', parent); +} +inherits(DERNode, Node); + +DERNode.prototype._encodeComposite = function encodeComposite(tag, + primitive, + cls, + content) { + const encodedTag = encodeTag(tag, primitive, cls, this.reporter); + + // Short form + if (content.length < 0x80) { + const header = Buffer.alloc(2); + header[0] = encodedTag; + header[1] = content.length; + return this._createEncoderBuffer([ header, content ]); + } + + // Long form + // Count octets required to store length + let lenOctets = 1; + for (let i = content.length; i >= 0x100; i >>= 8) + lenOctets++; + + const header = Buffer.alloc(1 + 1 + lenOctets); + header[0] = encodedTag; + header[1] = 0x80 | lenOctets; + + for (let i = 1 + lenOctets, j = content.length; j > 0; i--, j >>= 8) + header[i] = j & 0xff; + + return this._createEncoderBuffer([ header, content ]); +}; + +DERNode.prototype._encodeStr = function encodeStr(str, tag) { + if (tag === 'bitstr') { + return this._createEncoderBuffer([ str.unused | 0, str.data ]); + } else if (tag === 'bmpstr') { + const buf = Buffer.alloc(str.length * 2); + for (let i = 0; i < str.length; i++) { + buf.writeUInt16BE(str.charCodeAt(i), i * 2); + } + return this._createEncoderBuffer(buf); + } else if (tag === 'numstr') { + if (!this._isNumstr(str)) { + return this.reporter.error('Encoding of string type: numstr supports ' + + 'only digits and space'); + } + return this._createEncoderBuffer(str); + } else if (tag === 'printstr') { + if (!this._isPrintstr(str)) { + return this.reporter.error('Encoding of string type: printstr supports ' + + 'only latin upper and lower case letters, ' + + 'digits, space, apostrophe, left and rigth ' + + 'parenthesis, plus sign, comma, hyphen, ' + + 'dot, slash, colon, equal sign, ' + + 'question mark'); + } + return this._createEncoderBuffer(str); + } else if (/str$/.test(tag)) { + return this._createEncoderBuffer(str); + } else if (tag === 'objDesc') { + return this._createEncoderBuffer(str); + } else { + return this.reporter.error('Encoding of string type: ' + tag + + ' unsupported'); + } +}; + +DERNode.prototype._encodeObjid = function encodeObjid(id, values, relative) { + if (typeof id === 'string') { + if (!values) + return this.reporter.error('string objid given, but no values map found'); + if (!values.hasOwnProperty(id)) + return this.reporter.error('objid not found in values map'); + id = values[id].split(/[\s.]+/g); + for (let i = 0; i < id.length; i++) + id[i] |= 0; + } else if (Array.isArray(id)) { + id = id.slice(); + for (let i = 0; i < id.length; i++) + id[i] |= 0; + } + + if (!Array.isArray(id)) { + return this.reporter.error('objid() should be either array or string, ' + + 'got: ' + JSON.stringify(id)); + } + + if (!relative) { + if (id[1] >= 40) + return this.reporter.error('Second objid identifier OOB'); + id.splice(0, 2, id[0] * 40 + id[1]); + } + + // Count number of octets + let size = 0; + for (let i = 0; i < id.length; i++) { + let ident = id[i]; + for (size++; ident >= 0x80; ident >>= 7) + size++; + } + + const objid = Buffer.alloc(size); + let offset = objid.length - 1; + for (let i = id.length - 1; i >= 0; i--) { + let ident = id[i]; + objid[offset--] = ident & 0x7f; + while ((ident >>= 7) > 0) + objid[offset--] = 0x80 | (ident & 0x7f); + } + + return this._createEncoderBuffer(objid); +}; + +function two(num) { + if (num < 10) + return '0' + num; + else + return num; +} + +DERNode.prototype._encodeTime = function encodeTime(time, tag) { + let str; + const date = new Date(time); + + if (tag === 'gentime') { + str = [ + two(date.getUTCFullYear()), + two(date.getUTCMonth() + 1), + two(date.getUTCDate()), + two(date.getUTCHours()), + two(date.getUTCMinutes()), + two(date.getUTCSeconds()), + 'Z' + ].join(''); + } else if (tag === 'utctime') { + str = [ + two(date.getUTCFullYear() % 100), + two(date.getUTCMonth() + 1), + two(date.getUTCDate()), + two(date.getUTCHours()), + two(date.getUTCMinutes()), + two(date.getUTCSeconds()), + 'Z' + ].join(''); + } else { + this.reporter.error('Encoding ' + tag + ' time is not supported yet'); + } + + return this._encodeStr(str, 'octstr'); +}; + +DERNode.prototype._encodeNull = function encodeNull() { + return this._createEncoderBuffer(''); +}; + +DERNode.prototype._encodeInt = function encodeInt(num, values) { + if (typeof num === 'string') { + if (!values) + return this.reporter.error('String int or enum given, but no values map'); + if (!values.hasOwnProperty(num)) { + return this.reporter.error('Values map doesn\'t contain: ' + + JSON.stringify(num)); + } + num = values[num]; + } + + // Bignum, assume big endian + if (typeof num !== 'number' && !Buffer.isBuffer(num)) { + const numArray = num.toArray(); + if (!num.sign && numArray[0] & 0x80) { + numArray.unshift(0); + } + num = Buffer.from(numArray); + } + + if (Buffer.isBuffer(num)) { + let size = num.length; + if (num.length === 0) + size++; + + const out = Buffer.alloc(size); + num.copy(out); + if (num.length === 0) + out[0] = 0; + return this._createEncoderBuffer(out); + } + + if (num < 0x80) + return this._createEncoderBuffer(num); + + if (num < 0x100) + return this._createEncoderBuffer([0, num]); + + let size = 1; + for (let i = num; i >= 0x100; i >>= 8) + size++; + + const out = new Array(size); + for (let i = out.length - 1; i >= 0; i--) { + out[i] = num & 0xff; + num >>= 8; + } + if(out[0] & 0x80) { + out.unshift(0); + } + + return this._createEncoderBuffer(Buffer.from(out)); +}; + +DERNode.prototype._encodeBool = function encodeBool(value) { + return this._createEncoderBuffer(value ? 0xff : 0); +}; + +DERNode.prototype._use = function use(entity, obj) { + if (typeof entity === 'function') + entity = entity(obj); + return entity._getEncoder('der').tree; +}; + +DERNode.prototype._skipDefault = function skipDefault(dataBuffer, reporter, parent) { + const state = this._baseState; + let i; + if (state['default'] === null) + return false; + + const data = dataBuffer.join(); + if (state.defaultBuffer === undefined) + state.defaultBuffer = this._encodeValue(state['default'], reporter, parent).join(); + + if (data.length !== state.defaultBuffer.length) + return false; + + for (i=0; i < data.length; i++) + if (data[i] !== state.defaultBuffer[i]) + return false; + + return true; +}; + +// Utility methods + +function encodeTag(tag, primitive, cls, reporter) { + let res; + + if (tag === 'seqof') + tag = 'seq'; + else if (tag === 'setof') + tag = 'set'; + + if (der.tagByName.hasOwnProperty(tag)) + res = der.tagByName[tag]; + else if (typeof tag === 'number' && (tag | 0) === tag) + res = tag; + else + return reporter.error('Unknown tag: ' + tag); + + if (res >= 0x1f) + return reporter.error('Multi-octet tag encoding unsupported'); + + if (!primitive) + res |= 0x20; + + res |= (der.tagClassByName[cls || 'universal'] << 6); + + return res; +} + + +/***/ }), + +/***/ 3650: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + + +const encoders = exports; + +encoders.der = __nccwpck_require__(1446); +encoders.pem = __nccwpck_require__(1447); + + +/***/ }), + +/***/ 1447: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +const inherits = __nccwpck_require__(9581); + +const DEREncoder = __nccwpck_require__(1446); + +function PEMEncoder(entity) { + DEREncoder.call(this, entity); + this.enc = 'pem'; +} +inherits(PEMEncoder, DEREncoder); +module.exports = PEMEncoder; + +PEMEncoder.prototype.encode = function encode(data, options) { + const buf = DEREncoder.prototype.encode.call(this, data); + + const p = buf.toString('base64'); + const out = [ '-----BEGIN ' + options.label + '-----' ]; + for (let i = 0; i < p.length; i += 64) + out.push(p.slice(i, i + 64)); + out.push('-----END ' + options.label + '-----'); + return out.join('\n'); +}; + + +/***/ }), + +/***/ 5071: +/***/ (function(module, __unused_webpack_exports, __nccwpck_require__) { + +/* module decorator */ module = __nccwpck_require__.nmd(module); +(function (module, exports) { + 'use strict'; + + // Utils + function assert (val, msg) { + if (!val) throw new Error(msg || 'Assertion failed'); + } + + // Could use `inherits` module, but don't want to move from single file + // architecture yet. + function inherits (ctor, superCtor) { + ctor.super_ = superCtor; + var TempCtor = function () {}; + TempCtor.prototype = superCtor.prototype; + ctor.prototype = new TempCtor(); + ctor.prototype.constructor = ctor; + } + + // BN + + function BN (number, base, endian) { + if (BN.isBN(number)) { + return number; + } + + this.negative = 0; + this.words = null; + this.length = 0; + + // Reduction context + this.red = null; + + if (number !== null) { + if (base === 'le' || base === 'be') { + endian = base; + base = 10; + } + + this._init(number || 0, base || 10, endian || 'be'); + } + } + if (typeof module === 'object') { + module.exports = BN; + } else { + exports.BN = BN; + } + + BN.BN = BN; + BN.wordSize = 26; + + var Buffer; + try { + if (typeof window !== 'undefined' && typeof window.Buffer !== 'undefined') { + Buffer = window.Buffer; + } else { + Buffer = (__nccwpck_require__(4300).Buffer); + } + } catch (e) { + } + + BN.isBN = function isBN (num) { + if (num instanceof BN) { + return true; + } + + return num !== null && typeof num === 'object' && + num.constructor.wordSize === BN.wordSize && Array.isArray(num.words); + }; + + BN.max = function max (left, right) { + if (left.cmp(right) > 0) return left; + return right; + }; + + BN.min = function min (left, right) { + if (left.cmp(right) < 0) return left; + return right; + }; + + BN.prototype._init = function init (number, base, endian) { + if (typeof number === 'number') { + return this._initNumber(number, base, endian); + } + + if (typeof number === 'object') { + return this._initArray(number, base, endian); + } + + if (base === 'hex') { + base = 16; + } + assert(base === (base | 0) && base >= 2 && base <= 36); + + number = number.toString().replace(/\s+/g, ''); + var start = 0; + if (number[0] === '-') { + start++; + this.negative = 1; + } + + if (start < number.length) { + if (base === 16) { + this._parseHex(number, start, endian); + } else { + this._parseBase(number, base, start); + if (endian === 'le') { + this._initArray(this.toArray(), base, endian); + } + } + } + }; + + BN.prototype._initNumber = function _initNumber (number, base, endian) { + if (number < 0) { + this.negative = 1; + number = -number; + } + if (number < 0x4000000) { + this.words = [ number & 0x3ffffff ]; + this.length = 1; + } else if (number < 0x10000000000000) { + this.words = [ + number & 0x3ffffff, + (number / 0x4000000) & 0x3ffffff + ]; + this.length = 2; + } else { + assert(number < 0x20000000000000); // 2 ^ 53 (unsafe) + this.words = [ + number & 0x3ffffff, + (number / 0x4000000) & 0x3ffffff, + 1 + ]; + this.length = 3; + } + + if (endian !== 'le') return; + + // Reverse the bytes + this._initArray(this.toArray(), base, endian); + }; + + BN.prototype._initArray = function _initArray (number, base, endian) { + // Perhaps a Uint8Array + assert(typeof number.length === 'number'); + if (number.length <= 0) { + this.words = [ 0 ]; + this.length = 1; + return this; + } + + this.length = Math.ceil(number.length / 3); + this.words = new Array(this.length); + for (var i = 0; i < this.length; i++) { + this.words[i] = 0; + } + + var j, w; + var off = 0; + if (endian === 'be') { + for (i = number.length - 1, j = 0; i >= 0; i -= 3) { + w = number[i] | (number[i - 1] << 8) | (number[i - 2] << 16); + this.words[j] |= (w << off) & 0x3ffffff; + this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff; + off += 24; + if (off >= 26) { + off -= 26; + j++; + } + } + } else if (endian === 'le') { + for (i = 0, j = 0; i < number.length; i += 3) { + w = number[i] | (number[i + 1] << 8) | (number[i + 2] << 16); + this.words[j] |= (w << off) & 0x3ffffff; + this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff; + off += 24; + if (off >= 26) { + off -= 26; + j++; + } + } + } + return this.strip(); + }; + + function parseHex4Bits (string, index) { + var c = string.charCodeAt(index); + // 'A' - 'F' + if (c >= 65 && c <= 70) { + return c - 55; + // 'a' - 'f' + } else if (c >= 97 && c <= 102) { + return c - 87; + // '0' - '9' + } else { + return (c - 48) & 0xf; + } + } + + function parseHexByte (string, lowerBound, index) { + var r = parseHex4Bits(string, index); + if (index - 1 >= lowerBound) { + r |= parseHex4Bits(string, index - 1) << 4; + } + return r; + } + + BN.prototype._parseHex = function _parseHex (number, start, endian) { + // Create possibly bigger array to ensure that it fits the number + this.length = Math.ceil((number.length - start) / 6); + this.words = new Array(this.length); + for (var i = 0; i < this.length; i++) { + this.words[i] = 0; + } + + // 24-bits chunks + var off = 0; + var j = 0; + + var w; + if (endian === 'be') { + for (i = number.length - 1; i >= start; i -= 2) { + w = parseHexByte(number, start, i) << off; + this.words[j] |= w & 0x3ffffff; + if (off >= 18) { + off -= 18; + j += 1; + this.words[j] |= w >>> 26; + } else { + off += 8; + } + } + } else { + var parseLength = number.length - start; + for (i = parseLength % 2 === 0 ? start + 1 : start; i < number.length; i += 2) { + w = parseHexByte(number, start, i) << off; + this.words[j] |= w & 0x3ffffff; + if (off >= 18) { + off -= 18; + j += 1; + this.words[j] |= w >>> 26; + } else { + off += 8; + } + } + } + + this.strip(); + }; + + function parseBase (str, start, end, mul) { + var r = 0; + var len = Math.min(str.length, end); + for (var i = start; i < len; i++) { + var c = str.charCodeAt(i) - 48; + + r *= mul; + + // 'a' + if (c >= 49) { + r += c - 49 + 0xa; + + // 'A' + } else if (c >= 17) { + r += c - 17 + 0xa; + + // '0' - '9' + } else { + r += c; + } + } + return r; + } + + BN.prototype._parseBase = function _parseBase (number, base, start) { + // Initialize as zero + this.words = [ 0 ]; + this.length = 1; + + // Find length of limb in base + for (var limbLen = 0, limbPow = 1; limbPow <= 0x3ffffff; limbPow *= base) { + limbLen++; + } + limbLen--; + limbPow = (limbPow / base) | 0; + + var total = number.length - start; + var mod = total % limbLen; + var end = Math.min(total, total - mod) + start; + + var word = 0; + for (var i = start; i < end; i += limbLen) { + word = parseBase(number, i, i + limbLen, base); + + this.imuln(limbPow); + if (this.words[0] + word < 0x4000000) { + this.words[0] += word; + } else { + this._iaddn(word); + } + } + + if (mod !== 0) { + var pow = 1; + word = parseBase(number, i, number.length, base); + + for (i = 0; i < mod; i++) { + pow *= base; + } + + this.imuln(pow); + if (this.words[0] + word < 0x4000000) { + this.words[0] += word; + } else { + this._iaddn(word); + } + } + + this.strip(); + }; + + BN.prototype.copy = function copy (dest) { + dest.words = new Array(this.length); + for (var i = 0; i < this.length; i++) { + dest.words[i] = this.words[i]; + } + dest.length = this.length; + dest.negative = this.negative; + dest.red = this.red; + }; + + BN.prototype.clone = function clone () { + var r = new BN(null); + this.copy(r); + return r; + }; + + BN.prototype._expand = function _expand (size) { + while (this.length < size) { + this.words[this.length++] = 0; + } + return this; + }; + + // Remove leading `0` from `this` + BN.prototype.strip = function strip () { + while (this.length > 1 && this.words[this.length - 1] === 0) { + this.length--; + } + return this._normSign(); + }; + + BN.prototype._normSign = function _normSign () { + // -0 = 0 + if (this.length === 1 && this.words[0] === 0) { + this.negative = 0; + } + return this; + }; + + BN.prototype.inspect = function inspect () { + return (this.red ? ''; + }; + + /* + + var zeros = []; + var groupSizes = []; + var groupBases = []; + + var s = ''; + var i = -1; + while (++i < BN.wordSize) { + zeros[i] = s; + s += '0'; + } + groupSizes[0] = 0; + groupSizes[1] = 0; + groupBases[0] = 0; + groupBases[1] = 0; + var base = 2 - 1; + while (++base < 36 + 1) { + var groupSize = 0; + var groupBase = 1; + while (groupBase < (1 << BN.wordSize) / base) { + groupBase *= base; + groupSize += 1; + } + groupSizes[base] = groupSize; + groupBases[base] = groupBase; + } + + */ + + var zeros = [ + '', + '0', + '00', + '000', + '0000', + '00000', + '000000', + '0000000', + '00000000', + '000000000', + '0000000000', + '00000000000', + '000000000000', + '0000000000000', + '00000000000000', + '000000000000000', + '0000000000000000', + '00000000000000000', + '000000000000000000', + '0000000000000000000', + '00000000000000000000', + '000000000000000000000', + '0000000000000000000000', + '00000000000000000000000', + '000000000000000000000000', + '0000000000000000000000000' + ]; + + var groupSizes = [ + 0, 0, + 25, 16, 12, 11, 10, 9, 8, + 8, 7, 7, 7, 7, 6, 6, + 6, 6, 6, 6, 6, 5, 5, + 5, 5, 5, 5, 5, 5, 5, + 5, 5, 5, 5, 5, 5, 5 + ]; + + var groupBases = [ + 0, 0, + 33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216, + 43046721, 10000000, 19487171, 35831808, 62748517, 7529536, 11390625, + 16777216, 24137569, 34012224, 47045881, 64000000, 4084101, 5153632, + 6436343, 7962624, 9765625, 11881376, 14348907, 17210368, 20511149, + 24300000, 28629151, 33554432, 39135393, 45435424, 52521875, 60466176 + ]; + + BN.prototype.toString = function toString (base, padding) { + base = base || 10; + padding = padding | 0 || 1; + + var out; + if (base === 16 || base === 'hex') { + out = ''; + var off = 0; + var carry = 0; + for (var i = 0; i < this.length; i++) { + var w = this.words[i]; + var word = (((w << off) | carry) & 0xffffff).toString(16); + carry = (w >>> (24 - off)) & 0xffffff; + if (carry !== 0 || i !== this.length - 1) { + out = zeros[6 - word.length] + word + out; + } else { + out = word + out; + } + off += 2; + if (off >= 26) { + off -= 26; + i--; + } + } + if (carry !== 0) { + out = carry.toString(16) + out; + } + while (out.length % padding !== 0) { + out = '0' + out; + } + if (this.negative !== 0) { + out = '-' + out; + } + return out; + } + + if (base === (base | 0) && base >= 2 && base <= 36) { + // var groupSize = Math.floor(BN.wordSize * Math.LN2 / Math.log(base)); + var groupSize = groupSizes[base]; + // var groupBase = Math.pow(base, groupSize); + var groupBase = groupBases[base]; + out = ''; + var c = this.clone(); + c.negative = 0; + while (!c.isZero()) { + var r = c.modn(groupBase).toString(base); + c = c.idivn(groupBase); + + if (!c.isZero()) { + out = zeros[groupSize - r.length] + r + out; + } else { + out = r + out; + } + } + if (this.isZero()) { + out = '0' + out; + } + while (out.length % padding !== 0) { + out = '0' + out; + } + if (this.negative !== 0) { + out = '-' + out; + } + return out; + } + + assert(false, 'Base should be between 2 and 36'); + }; + + BN.prototype.toNumber = function toNumber () { + var ret = this.words[0]; + if (this.length === 2) { + ret += this.words[1] * 0x4000000; + } else if (this.length === 3 && this.words[2] === 0x01) { + // NOTE: at this stage it is known that the top bit is set + ret += 0x10000000000000 + (this.words[1] * 0x4000000); + } else if (this.length > 2) { + assert(false, 'Number can only safely store up to 53 bits'); + } + return (this.negative !== 0) ? -ret : ret; + }; + + BN.prototype.toJSON = function toJSON () { + return this.toString(16); + }; + + BN.prototype.toBuffer = function toBuffer (endian, length) { + assert(typeof Buffer !== 'undefined'); + return this.toArrayLike(Buffer, endian, length); + }; + + BN.prototype.toArray = function toArray (endian, length) { + return this.toArrayLike(Array, endian, length); + }; + + BN.prototype.toArrayLike = function toArrayLike (ArrayType, endian, length) { + var byteLength = this.byteLength(); + var reqLength = length || Math.max(1, byteLength); + assert(byteLength <= reqLength, 'byte array longer than desired length'); + assert(reqLength > 0, 'Requested array length <= 0'); + + this.strip(); + var littleEndian = endian === 'le'; + var res = new ArrayType(reqLength); + + var b, i; + var q = this.clone(); + if (!littleEndian) { + // Assume big-endian + for (i = 0; i < reqLength - byteLength; i++) { + res[i] = 0; + } + + for (i = 0; !q.isZero(); i++) { + b = q.andln(0xff); + q.iushrn(8); + + res[reqLength - i - 1] = b; + } + } else { + for (i = 0; !q.isZero(); i++) { + b = q.andln(0xff); + q.iushrn(8); + + res[i] = b; + } + + for (; i < reqLength; i++) { + res[i] = 0; + } + } + + return res; + }; + + if (Math.clz32) { + BN.prototype._countBits = function _countBits (w) { + return 32 - Math.clz32(w); + }; + } else { + BN.prototype._countBits = function _countBits (w) { + var t = w; + var r = 0; + if (t >= 0x1000) { + r += 13; + t >>>= 13; + } + if (t >= 0x40) { + r += 7; + t >>>= 7; + } + if (t >= 0x8) { + r += 4; + t >>>= 4; + } + if (t >= 0x02) { + r += 2; + t >>>= 2; + } + return r + t; + }; + } + + BN.prototype._zeroBits = function _zeroBits (w) { + // Short-cut + if (w === 0) return 26; + + var t = w; + var r = 0; + if ((t & 0x1fff) === 0) { + r += 13; + t >>>= 13; + } + if ((t & 0x7f) === 0) { + r += 7; + t >>>= 7; + } + if ((t & 0xf) === 0) { + r += 4; + t >>>= 4; + } + if ((t & 0x3) === 0) { + r += 2; + t >>>= 2; + } + if ((t & 0x1) === 0) { + r++; + } + return r; + }; + + // Return number of used bits in a BN + BN.prototype.bitLength = function bitLength () { + var w = this.words[this.length - 1]; + var hi = this._countBits(w); + return (this.length - 1) * 26 + hi; + }; + + function toBitArray (num) { + var w = new Array(num.bitLength()); + + for (var bit = 0; bit < w.length; bit++) { + var off = (bit / 26) | 0; + var wbit = bit % 26; + + w[bit] = (num.words[off] & (1 << wbit)) >>> wbit; + } + + return w; + } + + // Number of trailing zero bits + BN.prototype.zeroBits = function zeroBits () { + if (this.isZero()) return 0; + + var r = 0; + for (var i = 0; i < this.length; i++) { + var b = this._zeroBits(this.words[i]); + r += b; + if (b !== 26) break; + } + return r; + }; + + BN.prototype.byteLength = function byteLength () { + return Math.ceil(this.bitLength() / 8); + }; + + BN.prototype.toTwos = function toTwos (width) { + if (this.negative !== 0) { + return this.abs().inotn(width).iaddn(1); + } + return this.clone(); + }; + + BN.prototype.fromTwos = function fromTwos (width) { + if (this.testn(width - 1)) { + return this.notn(width).iaddn(1).ineg(); + } + return this.clone(); + }; + + BN.prototype.isNeg = function isNeg () { + return this.negative !== 0; + }; + + // Return negative clone of `this` + BN.prototype.neg = function neg () { + return this.clone().ineg(); + }; + + BN.prototype.ineg = function ineg () { + if (!this.isZero()) { + this.negative ^= 1; + } + + return this; + }; + + // Or `num` with `this` in-place + BN.prototype.iuor = function iuor (num) { + while (this.length < num.length) { + this.words[this.length++] = 0; + } + + for (var i = 0; i < num.length; i++) { + this.words[i] = this.words[i] | num.words[i]; + } + + return this.strip(); + }; + + BN.prototype.ior = function ior (num) { + assert((this.negative | num.negative) === 0); + return this.iuor(num); + }; + + // Or `num` with `this` + BN.prototype.or = function or (num) { + if (this.length > num.length) return this.clone().ior(num); + return num.clone().ior(this); + }; + + BN.prototype.uor = function uor (num) { + if (this.length > num.length) return this.clone().iuor(num); + return num.clone().iuor(this); + }; + + // And `num` with `this` in-place + BN.prototype.iuand = function iuand (num) { + // b = min-length(num, this) + var b; + if (this.length > num.length) { + b = num; + } else { + b = this; + } + + for (var i = 0; i < b.length; i++) { + this.words[i] = this.words[i] & num.words[i]; + } + + this.length = b.length; + + return this.strip(); + }; + + BN.prototype.iand = function iand (num) { + assert((this.negative | num.negative) === 0); + return this.iuand(num); + }; + + // And `num` with `this` + BN.prototype.and = function and (num) { + if (this.length > num.length) return this.clone().iand(num); + return num.clone().iand(this); + }; + + BN.prototype.uand = function uand (num) { + if (this.length > num.length) return this.clone().iuand(num); + return num.clone().iuand(this); + }; + + // Xor `num` with `this` in-place + BN.prototype.iuxor = function iuxor (num) { + // a.length > b.length + var a; + var b; + if (this.length > num.length) { + a = this; + b = num; + } else { + a = num; + b = this; + } + + for (var i = 0; i < b.length; i++) { + this.words[i] = a.words[i] ^ b.words[i]; + } + + if (this !== a) { + for (; i < a.length; i++) { + this.words[i] = a.words[i]; + } + } + + this.length = a.length; + + return this.strip(); + }; + + BN.prototype.ixor = function ixor (num) { + assert((this.negative | num.negative) === 0); + return this.iuxor(num); + }; + + // Xor `num` with `this` + BN.prototype.xor = function xor (num) { + if (this.length > num.length) return this.clone().ixor(num); + return num.clone().ixor(this); + }; + + BN.prototype.uxor = function uxor (num) { + if (this.length > num.length) return this.clone().iuxor(num); + return num.clone().iuxor(this); + }; + + // Not ``this`` with ``width`` bitwidth + BN.prototype.inotn = function inotn (width) { + assert(typeof width === 'number' && width >= 0); + + var bytesNeeded = Math.ceil(width / 26) | 0; + var bitsLeft = width % 26; + + // Extend the buffer with leading zeroes + this._expand(bytesNeeded); + + if (bitsLeft > 0) { + bytesNeeded--; + } + + // Handle complete words + for (var i = 0; i < bytesNeeded; i++) { + this.words[i] = ~this.words[i] & 0x3ffffff; + } + + // Handle the residue + if (bitsLeft > 0) { + this.words[i] = ~this.words[i] & (0x3ffffff >> (26 - bitsLeft)); + } + + // And remove leading zeroes + return this.strip(); + }; + + BN.prototype.notn = function notn (width) { + return this.clone().inotn(width); + }; + + // Set `bit` of `this` + BN.prototype.setn = function setn (bit, val) { + assert(typeof bit === 'number' && bit >= 0); + + var off = (bit / 26) | 0; + var wbit = bit % 26; + + this._expand(off + 1); + + if (val) { + this.words[off] = this.words[off] | (1 << wbit); + } else { + this.words[off] = this.words[off] & ~(1 << wbit); + } + + return this.strip(); + }; + + // Add `num` to `this` in-place + BN.prototype.iadd = function iadd (num) { + var r; + + // negative + positive + if (this.negative !== 0 && num.negative === 0) { + this.negative = 0; + r = this.isub(num); + this.negative ^= 1; + return this._normSign(); + + // positive + negative + } else if (this.negative === 0 && num.negative !== 0) { + num.negative = 0; + r = this.isub(num); + num.negative = 1; + return r._normSign(); + } + + // a.length > b.length + var a, b; + if (this.length > num.length) { + a = this; + b = num; + } else { + a = num; + b = this; + } + + var carry = 0; + for (var i = 0; i < b.length; i++) { + r = (a.words[i] | 0) + (b.words[i] | 0) + carry; + this.words[i] = r & 0x3ffffff; + carry = r >>> 26; + } + for (; carry !== 0 && i < a.length; i++) { + r = (a.words[i] | 0) + carry; + this.words[i] = r & 0x3ffffff; + carry = r >>> 26; + } + + this.length = a.length; + if (carry !== 0) { + this.words[this.length] = carry; + this.length++; + // Copy the rest of the words + } else if (a !== this) { + for (; i < a.length; i++) { + this.words[i] = a.words[i]; + } + } + + return this; + }; + + // Add `num` to `this` + BN.prototype.add = function add (num) { + var res; + if (num.negative !== 0 && this.negative === 0) { + num.negative = 0; + res = this.sub(num); + num.negative ^= 1; + return res; + } else if (num.negative === 0 && this.negative !== 0) { + this.negative = 0; + res = num.sub(this); + this.negative = 1; + return res; + } + + if (this.length > num.length) return this.clone().iadd(num); + + return num.clone().iadd(this); + }; + + // Subtract `num` from `this` in-place + BN.prototype.isub = function isub (num) { + // this - (-num) = this + num + if (num.negative !== 0) { + num.negative = 0; + var r = this.iadd(num); + num.negative = 1; + return r._normSign(); + + // -this - num = -(this + num) + } else if (this.negative !== 0) { + this.negative = 0; + this.iadd(num); + this.negative = 1; + return this._normSign(); + } + + // At this point both numbers are positive + var cmp = this.cmp(num); + + // Optimization - zeroify + if (cmp === 0) { + this.negative = 0; + this.length = 1; + this.words[0] = 0; + return this; + } + + // a > b + var a, b; + if (cmp > 0) { + a = this; + b = num; + } else { + a = num; + b = this; + } + + var carry = 0; + for (var i = 0; i < b.length; i++) { + r = (a.words[i] | 0) - (b.words[i] | 0) + carry; + carry = r >> 26; + this.words[i] = r & 0x3ffffff; + } + for (; carry !== 0 && i < a.length; i++) { + r = (a.words[i] | 0) + carry; + carry = r >> 26; + this.words[i] = r & 0x3ffffff; + } + + // Copy rest of the words + if (carry === 0 && i < a.length && a !== this) { + for (; i < a.length; i++) { + this.words[i] = a.words[i]; + } + } + + this.length = Math.max(this.length, i); + + if (a !== this) { + this.negative = 1; + } + + return this.strip(); + }; + + // Subtract `num` from `this` + BN.prototype.sub = function sub (num) { + return this.clone().isub(num); + }; + + function smallMulTo (self, num, out) { + out.negative = num.negative ^ self.negative; + var len = (self.length + num.length) | 0; + out.length = len; + len = (len - 1) | 0; + + // Peel one iteration (compiler can't do it, because of code complexity) + var a = self.words[0] | 0; + var b = num.words[0] | 0; + var r = a * b; + + var lo = r & 0x3ffffff; + var carry = (r / 0x4000000) | 0; + out.words[0] = lo; + + for (var k = 1; k < len; k++) { + // Sum all words with the same `i + j = k` and accumulate `ncarry`, + // note that ncarry could be >= 0x3ffffff + var ncarry = carry >>> 26; + var rword = carry & 0x3ffffff; + var maxJ = Math.min(k, num.length - 1); + for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) { + var i = (k - j) | 0; + a = self.words[i] | 0; + b = num.words[j] | 0; + r = a * b + rword; + ncarry += (r / 0x4000000) | 0; + rword = r & 0x3ffffff; + } + out.words[k] = rword | 0; + carry = ncarry | 0; + } + if (carry !== 0) { + out.words[k] = carry | 0; + } else { + out.length--; + } + + return out.strip(); + } + + // TODO(indutny): it may be reasonable to omit it for users who don't need + // to work with 256-bit numbers, otherwise it gives 20% improvement for 256-bit + // multiplication (like elliptic secp256k1). + var comb10MulTo = function comb10MulTo (self, num, out) { + var a = self.words; + var b = num.words; + var o = out.words; + var c = 0; + var lo; + var mid; + var hi; + var a0 = a[0] | 0; + var al0 = a0 & 0x1fff; + var ah0 = a0 >>> 13; + var a1 = a[1] | 0; + var al1 = a1 & 0x1fff; + var ah1 = a1 >>> 13; + var a2 = a[2] | 0; + var al2 = a2 & 0x1fff; + var ah2 = a2 >>> 13; + var a3 = a[3] | 0; + var al3 = a3 & 0x1fff; + var ah3 = a3 >>> 13; + var a4 = a[4] | 0; + var al4 = a4 & 0x1fff; + var ah4 = a4 >>> 13; + var a5 = a[5] | 0; + var al5 = a5 & 0x1fff; + var ah5 = a5 >>> 13; + var a6 = a[6] | 0; + var al6 = a6 & 0x1fff; + var ah6 = a6 >>> 13; + var a7 = a[7] | 0; + var al7 = a7 & 0x1fff; + var ah7 = a7 >>> 13; + var a8 = a[8] | 0; + var al8 = a8 & 0x1fff; + var ah8 = a8 >>> 13; + var a9 = a[9] | 0; + var al9 = a9 & 0x1fff; + var ah9 = a9 >>> 13; + var b0 = b[0] | 0; + var bl0 = b0 & 0x1fff; + var bh0 = b0 >>> 13; + var b1 = b[1] | 0; + var bl1 = b1 & 0x1fff; + var bh1 = b1 >>> 13; + var b2 = b[2] | 0; + var bl2 = b2 & 0x1fff; + var bh2 = b2 >>> 13; + var b3 = b[3] | 0; + var bl3 = b3 & 0x1fff; + var bh3 = b3 >>> 13; + var b4 = b[4] | 0; + var bl4 = b4 & 0x1fff; + var bh4 = b4 >>> 13; + var b5 = b[5] | 0; + var bl5 = b5 & 0x1fff; + var bh5 = b5 >>> 13; + var b6 = b[6] | 0; + var bl6 = b6 & 0x1fff; + var bh6 = b6 >>> 13; + var b7 = b[7] | 0; + var bl7 = b7 & 0x1fff; + var bh7 = b7 >>> 13; + var b8 = b[8] | 0; + var bl8 = b8 & 0x1fff; + var bh8 = b8 >>> 13; + var b9 = b[9] | 0; + var bl9 = b9 & 0x1fff; + var bh9 = b9 >>> 13; + + out.negative = self.negative ^ num.negative; + out.length = 19; + /* k = 0 */ + lo = Math.imul(al0, bl0); + mid = Math.imul(al0, bh0); + mid = (mid + Math.imul(ah0, bl0)) | 0; + hi = Math.imul(ah0, bh0); + var w0 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w0 >>> 26)) | 0; + w0 &= 0x3ffffff; + /* k = 1 */ + lo = Math.imul(al1, bl0); + mid = Math.imul(al1, bh0); + mid = (mid + Math.imul(ah1, bl0)) | 0; + hi = Math.imul(ah1, bh0); + lo = (lo + Math.imul(al0, bl1)) | 0; + mid = (mid + Math.imul(al0, bh1)) | 0; + mid = (mid + Math.imul(ah0, bl1)) | 0; + hi = (hi + Math.imul(ah0, bh1)) | 0; + var w1 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w1 >>> 26)) | 0; + w1 &= 0x3ffffff; + /* k = 2 */ + lo = Math.imul(al2, bl0); + mid = Math.imul(al2, bh0); + mid = (mid + Math.imul(ah2, bl0)) | 0; + hi = Math.imul(ah2, bh0); + lo = (lo + Math.imul(al1, bl1)) | 0; + mid = (mid + Math.imul(al1, bh1)) | 0; + mid = (mid + Math.imul(ah1, bl1)) | 0; + hi = (hi + Math.imul(ah1, bh1)) | 0; + lo = (lo + Math.imul(al0, bl2)) | 0; + mid = (mid + Math.imul(al0, bh2)) | 0; + mid = (mid + Math.imul(ah0, bl2)) | 0; + hi = (hi + Math.imul(ah0, bh2)) | 0; + var w2 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w2 >>> 26)) | 0; + w2 &= 0x3ffffff; + /* k = 3 */ + lo = Math.imul(al3, bl0); + mid = Math.imul(al3, bh0); + mid = (mid + Math.imul(ah3, bl0)) | 0; + hi = Math.imul(ah3, bh0); + lo = (lo + Math.imul(al2, bl1)) | 0; + mid = (mid + Math.imul(al2, bh1)) | 0; + mid = (mid + Math.imul(ah2, bl1)) | 0; + hi = (hi + Math.imul(ah2, bh1)) | 0; + lo = (lo + Math.imul(al1, bl2)) | 0; + mid = (mid + Math.imul(al1, bh2)) | 0; + mid = (mid + Math.imul(ah1, bl2)) | 0; + hi = (hi + Math.imul(ah1, bh2)) | 0; + lo = (lo + Math.imul(al0, bl3)) | 0; + mid = (mid + Math.imul(al0, bh3)) | 0; + mid = (mid + Math.imul(ah0, bl3)) | 0; + hi = (hi + Math.imul(ah0, bh3)) | 0; + var w3 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w3 >>> 26)) | 0; + w3 &= 0x3ffffff; + /* k = 4 */ + lo = Math.imul(al4, bl0); + mid = Math.imul(al4, bh0); + mid = (mid + Math.imul(ah4, bl0)) | 0; + hi = Math.imul(ah4, bh0); + lo = (lo + Math.imul(al3, bl1)) | 0; + mid = (mid + Math.imul(al3, bh1)) | 0; + mid = (mid + Math.imul(ah3, bl1)) | 0; + hi = (hi + Math.imul(ah3, bh1)) | 0; + lo = (lo + Math.imul(al2, bl2)) | 0; + mid = (mid + Math.imul(al2, bh2)) | 0; + mid = (mid + Math.imul(ah2, bl2)) | 0; + hi = (hi + Math.imul(ah2, bh2)) | 0; + lo = (lo + Math.imul(al1, bl3)) | 0; + mid = (mid + Math.imul(al1, bh3)) | 0; + mid = (mid + Math.imul(ah1, bl3)) | 0; + hi = (hi + Math.imul(ah1, bh3)) | 0; + lo = (lo + Math.imul(al0, bl4)) | 0; + mid = (mid + Math.imul(al0, bh4)) | 0; + mid = (mid + Math.imul(ah0, bl4)) | 0; + hi = (hi + Math.imul(ah0, bh4)) | 0; + var w4 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w4 >>> 26)) | 0; + w4 &= 0x3ffffff; + /* k = 5 */ + lo = Math.imul(al5, bl0); + mid = Math.imul(al5, bh0); + mid = (mid + Math.imul(ah5, bl0)) | 0; + hi = Math.imul(ah5, bh0); + lo = (lo + Math.imul(al4, bl1)) | 0; + mid = (mid + Math.imul(al4, bh1)) | 0; + mid = (mid + Math.imul(ah4, bl1)) | 0; + hi = (hi + Math.imul(ah4, bh1)) | 0; + lo = (lo + Math.imul(al3, bl2)) | 0; + mid = (mid + Math.imul(al3, bh2)) | 0; + mid = (mid + Math.imul(ah3, bl2)) | 0; + hi = (hi + Math.imul(ah3, bh2)) | 0; + lo = (lo + Math.imul(al2, bl3)) | 0; + mid = (mid + Math.imul(al2, bh3)) | 0; + mid = (mid + Math.imul(ah2, bl3)) | 0; + hi = (hi + Math.imul(ah2, bh3)) | 0; + lo = (lo + Math.imul(al1, bl4)) | 0; + mid = (mid + Math.imul(al1, bh4)) | 0; + mid = (mid + Math.imul(ah1, bl4)) | 0; + hi = (hi + Math.imul(ah1, bh4)) | 0; + lo = (lo + Math.imul(al0, bl5)) | 0; + mid = (mid + Math.imul(al0, bh5)) | 0; + mid = (mid + Math.imul(ah0, bl5)) | 0; + hi = (hi + Math.imul(ah0, bh5)) | 0; + var w5 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w5 >>> 26)) | 0; + w5 &= 0x3ffffff; + /* k = 6 */ + lo = Math.imul(al6, bl0); + mid = Math.imul(al6, bh0); + mid = (mid + Math.imul(ah6, bl0)) | 0; + hi = Math.imul(ah6, bh0); + lo = (lo + Math.imul(al5, bl1)) | 0; + mid = (mid + Math.imul(al5, bh1)) | 0; + mid = (mid + Math.imul(ah5, bl1)) | 0; + hi = (hi + Math.imul(ah5, bh1)) | 0; + lo = (lo + Math.imul(al4, bl2)) | 0; + mid = (mid + Math.imul(al4, bh2)) | 0; + mid = (mid + Math.imul(ah4, bl2)) | 0; + hi = (hi + Math.imul(ah4, bh2)) | 0; + lo = (lo + Math.imul(al3, bl3)) | 0; + mid = (mid + Math.imul(al3, bh3)) | 0; + mid = (mid + Math.imul(ah3, bl3)) | 0; + hi = (hi + Math.imul(ah3, bh3)) | 0; + lo = (lo + Math.imul(al2, bl4)) | 0; + mid = (mid + Math.imul(al2, bh4)) | 0; + mid = (mid + Math.imul(ah2, bl4)) | 0; + hi = (hi + Math.imul(ah2, bh4)) | 0; + lo = (lo + Math.imul(al1, bl5)) | 0; + mid = (mid + Math.imul(al1, bh5)) | 0; + mid = (mid + Math.imul(ah1, bl5)) | 0; + hi = (hi + Math.imul(ah1, bh5)) | 0; + lo = (lo + Math.imul(al0, bl6)) | 0; + mid = (mid + Math.imul(al0, bh6)) | 0; + mid = (mid + Math.imul(ah0, bl6)) | 0; + hi = (hi + Math.imul(ah0, bh6)) | 0; + var w6 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w6 >>> 26)) | 0; + w6 &= 0x3ffffff; + /* k = 7 */ + lo = Math.imul(al7, bl0); + mid = Math.imul(al7, bh0); + mid = (mid + Math.imul(ah7, bl0)) | 0; + hi = Math.imul(ah7, bh0); + lo = (lo + Math.imul(al6, bl1)) | 0; + mid = (mid + Math.imul(al6, bh1)) | 0; + mid = (mid + Math.imul(ah6, bl1)) | 0; + hi = (hi + Math.imul(ah6, bh1)) | 0; + lo = (lo + Math.imul(al5, bl2)) | 0; + mid = (mid + Math.imul(al5, bh2)) | 0; + mid = (mid + Math.imul(ah5, bl2)) | 0; + hi = (hi + Math.imul(ah5, bh2)) | 0; + lo = (lo + Math.imul(al4, bl3)) | 0; + mid = (mid + Math.imul(al4, bh3)) | 0; + mid = (mid + Math.imul(ah4, bl3)) | 0; + hi = (hi + Math.imul(ah4, bh3)) | 0; + lo = (lo + Math.imul(al3, bl4)) | 0; + mid = (mid + Math.imul(al3, bh4)) | 0; + mid = (mid + Math.imul(ah3, bl4)) | 0; + hi = (hi + Math.imul(ah3, bh4)) | 0; + lo = (lo + Math.imul(al2, bl5)) | 0; + mid = (mid + Math.imul(al2, bh5)) | 0; + mid = (mid + Math.imul(ah2, bl5)) | 0; + hi = (hi + Math.imul(ah2, bh5)) | 0; + lo = (lo + Math.imul(al1, bl6)) | 0; + mid = (mid + Math.imul(al1, bh6)) | 0; + mid = (mid + Math.imul(ah1, bl6)) | 0; + hi = (hi + Math.imul(ah1, bh6)) | 0; + lo = (lo + Math.imul(al0, bl7)) | 0; + mid = (mid + Math.imul(al0, bh7)) | 0; + mid = (mid + Math.imul(ah0, bl7)) | 0; + hi = (hi + Math.imul(ah0, bh7)) | 0; + var w7 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w7 >>> 26)) | 0; + w7 &= 0x3ffffff; + /* k = 8 */ + lo = Math.imul(al8, bl0); + mid = Math.imul(al8, bh0); + mid = (mid + Math.imul(ah8, bl0)) | 0; + hi = Math.imul(ah8, bh0); + lo = (lo + Math.imul(al7, bl1)) | 0; + mid = (mid + Math.imul(al7, bh1)) | 0; + mid = (mid + Math.imul(ah7, bl1)) | 0; + hi = (hi + Math.imul(ah7, bh1)) | 0; + lo = (lo + Math.imul(al6, bl2)) | 0; + mid = (mid + Math.imul(al6, bh2)) | 0; + mid = (mid + Math.imul(ah6, bl2)) | 0; + hi = (hi + Math.imul(ah6, bh2)) | 0; + lo = (lo + Math.imul(al5, bl3)) | 0; + mid = (mid + Math.imul(al5, bh3)) | 0; + mid = (mid + Math.imul(ah5, bl3)) | 0; + hi = (hi + Math.imul(ah5, bh3)) | 0; + lo = (lo + Math.imul(al4, bl4)) | 0; + mid = (mid + Math.imul(al4, bh4)) | 0; + mid = (mid + Math.imul(ah4, bl4)) | 0; + hi = (hi + Math.imul(ah4, bh4)) | 0; + lo = (lo + Math.imul(al3, bl5)) | 0; + mid = (mid + Math.imul(al3, bh5)) | 0; + mid = (mid + Math.imul(ah3, bl5)) | 0; + hi = (hi + Math.imul(ah3, bh5)) | 0; + lo = (lo + Math.imul(al2, bl6)) | 0; + mid = (mid + Math.imul(al2, bh6)) | 0; + mid = (mid + Math.imul(ah2, bl6)) | 0; + hi = (hi + Math.imul(ah2, bh6)) | 0; + lo = (lo + Math.imul(al1, bl7)) | 0; + mid = (mid + Math.imul(al1, bh7)) | 0; + mid = (mid + Math.imul(ah1, bl7)) | 0; + hi = (hi + Math.imul(ah1, bh7)) | 0; + lo = (lo + Math.imul(al0, bl8)) | 0; + mid = (mid + Math.imul(al0, bh8)) | 0; + mid = (mid + Math.imul(ah0, bl8)) | 0; + hi = (hi + Math.imul(ah0, bh8)) | 0; + var w8 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w8 >>> 26)) | 0; + w8 &= 0x3ffffff; + /* k = 9 */ + lo = Math.imul(al9, bl0); + mid = Math.imul(al9, bh0); + mid = (mid + Math.imul(ah9, bl0)) | 0; + hi = Math.imul(ah9, bh0); + lo = (lo + Math.imul(al8, bl1)) | 0; + mid = (mid + Math.imul(al8, bh1)) | 0; + mid = (mid + Math.imul(ah8, bl1)) | 0; + hi = (hi + Math.imul(ah8, bh1)) | 0; + lo = (lo + Math.imul(al7, bl2)) | 0; + mid = (mid + Math.imul(al7, bh2)) | 0; + mid = (mid + Math.imul(ah7, bl2)) | 0; + hi = (hi + Math.imul(ah7, bh2)) | 0; + lo = (lo + Math.imul(al6, bl3)) | 0; + mid = (mid + Math.imul(al6, bh3)) | 0; + mid = (mid + Math.imul(ah6, bl3)) | 0; + hi = (hi + Math.imul(ah6, bh3)) | 0; + lo = (lo + Math.imul(al5, bl4)) | 0; + mid = (mid + Math.imul(al5, bh4)) | 0; + mid = (mid + Math.imul(ah5, bl4)) | 0; + hi = (hi + Math.imul(ah5, bh4)) | 0; + lo = (lo + Math.imul(al4, bl5)) | 0; + mid = (mid + Math.imul(al4, bh5)) | 0; + mid = (mid + Math.imul(ah4, bl5)) | 0; + hi = (hi + Math.imul(ah4, bh5)) | 0; + lo = (lo + Math.imul(al3, bl6)) | 0; + mid = (mid + Math.imul(al3, bh6)) | 0; + mid = (mid + Math.imul(ah3, bl6)) | 0; + hi = (hi + Math.imul(ah3, bh6)) | 0; + lo = (lo + Math.imul(al2, bl7)) | 0; + mid = (mid + Math.imul(al2, bh7)) | 0; + mid = (mid + Math.imul(ah2, bl7)) | 0; + hi = (hi + Math.imul(ah2, bh7)) | 0; + lo = (lo + Math.imul(al1, bl8)) | 0; + mid = (mid + Math.imul(al1, bh8)) | 0; + mid = (mid + Math.imul(ah1, bl8)) | 0; + hi = (hi + Math.imul(ah1, bh8)) | 0; + lo = (lo + Math.imul(al0, bl9)) | 0; + mid = (mid + Math.imul(al0, bh9)) | 0; + mid = (mid + Math.imul(ah0, bl9)) | 0; + hi = (hi + Math.imul(ah0, bh9)) | 0; + var w9 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w9 >>> 26)) | 0; + w9 &= 0x3ffffff; + /* k = 10 */ + lo = Math.imul(al9, bl1); + mid = Math.imul(al9, bh1); + mid = (mid + Math.imul(ah9, bl1)) | 0; + hi = Math.imul(ah9, bh1); + lo = (lo + Math.imul(al8, bl2)) | 0; + mid = (mid + Math.imul(al8, bh2)) | 0; + mid = (mid + Math.imul(ah8, bl2)) | 0; + hi = (hi + Math.imul(ah8, bh2)) | 0; + lo = (lo + Math.imul(al7, bl3)) | 0; + mid = (mid + Math.imul(al7, bh3)) | 0; + mid = (mid + Math.imul(ah7, bl3)) | 0; + hi = (hi + Math.imul(ah7, bh3)) | 0; + lo = (lo + Math.imul(al6, bl4)) | 0; + mid = (mid + Math.imul(al6, bh4)) | 0; + mid = (mid + Math.imul(ah6, bl4)) | 0; + hi = (hi + Math.imul(ah6, bh4)) | 0; + lo = (lo + Math.imul(al5, bl5)) | 0; + mid = (mid + Math.imul(al5, bh5)) | 0; + mid = (mid + Math.imul(ah5, bl5)) | 0; + hi = (hi + Math.imul(ah5, bh5)) | 0; + lo = (lo + Math.imul(al4, bl6)) | 0; + mid = (mid + Math.imul(al4, bh6)) | 0; + mid = (mid + Math.imul(ah4, bl6)) | 0; + hi = (hi + Math.imul(ah4, bh6)) | 0; + lo = (lo + Math.imul(al3, bl7)) | 0; + mid = (mid + Math.imul(al3, bh7)) | 0; + mid = (mid + Math.imul(ah3, bl7)) | 0; + hi = (hi + Math.imul(ah3, bh7)) | 0; + lo = (lo + Math.imul(al2, bl8)) | 0; + mid = (mid + Math.imul(al2, bh8)) | 0; + mid = (mid + Math.imul(ah2, bl8)) | 0; + hi = (hi + Math.imul(ah2, bh8)) | 0; + lo = (lo + Math.imul(al1, bl9)) | 0; + mid = (mid + Math.imul(al1, bh9)) | 0; + mid = (mid + Math.imul(ah1, bl9)) | 0; + hi = (hi + Math.imul(ah1, bh9)) | 0; + var w10 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w10 >>> 26)) | 0; + w10 &= 0x3ffffff; + /* k = 11 */ + lo = Math.imul(al9, bl2); + mid = Math.imul(al9, bh2); + mid = (mid + Math.imul(ah9, bl2)) | 0; + hi = Math.imul(ah9, bh2); + lo = (lo + Math.imul(al8, bl3)) | 0; + mid = (mid + Math.imul(al8, bh3)) | 0; + mid = (mid + Math.imul(ah8, bl3)) | 0; + hi = (hi + Math.imul(ah8, bh3)) | 0; + lo = (lo + Math.imul(al7, bl4)) | 0; + mid = (mid + Math.imul(al7, bh4)) | 0; + mid = (mid + Math.imul(ah7, bl4)) | 0; + hi = (hi + Math.imul(ah7, bh4)) | 0; + lo = (lo + Math.imul(al6, bl5)) | 0; + mid = (mid + Math.imul(al6, bh5)) | 0; + mid = (mid + Math.imul(ah6, bl5)) | 0; + hi = (hi + Math.imul(ah6, bh5)) | 0; + lo = (lo + Math.imul(al5, bl6)) | 0; + mid = (mid + Math.imul(al5, bh6)) | 0; + mid = (mid + Math.imul(ah5, bl6)) | 0; + hi = (hi + Math.imul(ah5, bh6)) | 0; + lo = (lo + Math.imul(al4, bl7)) | 0; + mid = (mid + Math.imul(al4, bh7)) | 0; + mid = (mid + Math.imul(ah4, bl7)) | 0; + hi = (hi + Math.imul(ah4, bh7)) | 0; + lo = (lo + Math.imul(al3, bl8)) | 0; + mid = (mid + Math.imul(al3, bh8)) | 0; + mid = (mid + Math.imul(ah3, bl8)) | 0; + hi = (hi + Math.imul(ah3, bh8)) | 0; + lo = (lo + Math.imul(al2, bl9)) | 0; + mid = (mid + Math.imul(al2, bh9)) | 0; + mid = (mid + Math.imul(ah2, bl9)) | 0; + hi = (hi + Math.imul(ah2, bh9)) | 0; + var w11 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w11 >>> 26)) | 0; + w11 &= 0x3ffffff; + /* k = 12 */ + lo = Math.imul(al9, bl3); + mid = Math.imul(al9, bh3); + mid = (mid + Math.imul(ah9, bl3)) | 0; + hi = Math.imul(ah9, bh3); + lo = (lo + Math.imul(al8, bl4)) | 0; + mid = (mid + Math.imul(al8, bh4)) | 0; + mid = (mid + Math.imul(ah8, bl4)) | 0; + hi = (hi + Math.imul(ah8, bh4)) | 0; + lo = (lo + Math.imul(al7, bl5)) | 0; + mid = (mid + Math.imul(al7, bh5)) | 0; + mid = (mid + Math.imul(ah7, bl5)) | 0; + hi = (hi + Math.imul(ah7, bh5)) | 0; + lo = (lo + Math.imul(al6, bl6)) | 0; + mid = (mid + Math.imul(al6, bh6)) | 0; + mid = (mid + Math.imul(ah6, bl6)) | 0; + hi = (hi + Math.imul(ah6, bh6)) | 0; + lo = (lo + Math.imul(al5, bl7)) | 0; + mid = (mid + Math.imul(al5, bh7)) | 0; + mid = (mid + Math.imul(ah5, bl7)) | 0; + hi = (hi + Math.imul(ah5, bh7)) | 0; + lo = (lo + Math.imul(al4, bl8)) | 0; + mid = (mid + Math.imul(al4, bh8)) | 0; + mid = (mid + Math.imul(ah4, bl8)) | 0; + hi = (hi + Math.imul(ah4, bh8)) | 0; + lo = (lo + Math.imul(al3, bl9)) | 0; + mid = (mid + Math.imul(al3, bh9)) | 0; + mid = (mid + Math.imul(ah3, bl9)) | 0; + hi = (hi + Math.imul(ah3, bh9)) | 0; + var w12 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w12 >>> 26)) | 0; + w12 &= 0x3ffffff; + /* k = 13 */ + lo = Math.imul(al9, bl4); + mid = Math.imul(al9, bh4); + mid = (mid + Math.imul(ah9, bl4)) | 0; + hi = Math.imul(ah9, bh4); + lo = (lo + Math.imul(al8, bl5)) | 0; + mid = (mid + Math.imul(al8, bh5)) | 0; + mid = (mid + Math.imul(ah8, bl5)) | 0; + hi = (hi + Math.imul(ah8, bh5)) | 0; + lo = (lo + Math.imul(al7, bl6)) | 0; + mid = (mid + Math.imul(al7, bh6)) | 0; + mid = (mid + Math.imul(ah7, bl6)) | 0; + hi = (hi + Math.imul(ah7, bh6)) | 0; + lo = (lo + Math.imul(al6, bl7)) | 0; + mid = (mid + Math.imul(al6, bh7)) | 0; + mid = (mid + Math.imul(ah6, bl7)) | 0; + hi = (hi + Math.imul(ah6, bh7)) | 0; + lo = (lo + Math.imul(al5, bl8)) | 0; + mid = (mid + Math.imul(al5, bh8)) | 0; + mid = (mid + Math.imul(ah5, bl8)) | 0; + hi = (hi + Math.imul(ah5, bh8)) | 0; + lo = (lo + Math.imul(al4, bl9)) | 0; + mid = (mid + Math.imul(al4, bh9)) | 0; + mid = (mid + Math.imul(ah4, bl9)) | 0; + hi = (hi + Math.imul(ah4, bh9)) | 0; + var w13 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w13 >>> 26)) | 0; + w13 &= 0x3ffffff; + /* k = 14 */ + lo = Math.imul(al9, bl5); + mid = Math.imul(al9, bh5); + mid = (mid + Math.imul(ah9, bl5)) | 0; + hi = Math.imul(ah9, bh5); + lo = (lo + Math.imul(al8, bl6)) | 0; + mid = (mid + Math.imul(al8, bh6)) | 0; + mid = (mid + Math.imul(ah8, bl6)) | 0; + hi = (hi + Math.imul(ah8, bh6)) | 0; + lo = (lo + Math.imul(al7, bl7)) | 0; + mid = (mid + Math.imul(al7, bh7)) | 0; + mid = (mid + Math.imul(ah7, bl7)) | 0; + hi = (hi + Math.imul(ah7, bh7)) | 0; + lo = (lo + Math.imul(al6, bl8)) | 0; + mid = (mid + Math.imul(al6, bh8)) | 0; + mid = (mid + Math.imul(ah6, bl8)) | 0; + hi = (hi + Math.imul(ah6, bh8)) | 0; + lo = (lo + Math.imul(al5, bl9)) | 0; + mid = (mid + Math.imul(al5, bh9)) | 0; + mid = (mid + Math.imul(ah5, bl9)) | 0; + hi = (hi + Math.imul(ah5, bh9)) | 0; + var w14 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w14 >>> 26)) | 0; + w14 &= 0x3ffffff; + /* k = 15 */ + lo = Math.imul(al9, bl6); + mid = Math.imul(al9, bh6); + mid = (mid + Math.imul(ah9, bl6)) | 0; + hi = Math.imul(ah9, bh6); + lo = (lo + Math.imul(al8, bl7)) | 0; + mid = (mid + Math.imul(al8, bh7)) | 0; + mid = (mid + Math.imul(ah8, bl7)) | 0; + hi = (hi + Math.imul(ah8, bh7)) | 0; + lo = (lo + Math.imul(al7, bl8)) | 0; + mid = (mid + Math.imul(al7, bh8)) | 0; + mid = (mid + Math.imul(ah7, bl8)) | 0; + hi = (hi + Math.imul(ah7, bh8)) | 0; + lo = (lo + Math.imul(al6, bl9)) | 0; + mid = (mid + Math.imul(al6, bh9)) | 0; + mid = (mid + Math.imul(ah6, bl9)) | 0; + hi = (hi + Math.imul(ah6, bh9)) | 0; + var w15 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w15 >>> 26)) | 0; + w15 &= 0x3ffffff; + /* k = 16 */ + lo = Math.imul(al9, bl7); + mid = Math.imul(al9, bh7); + mid = (mid + Math.imul(ah9, bl7)) | 0; + hi = Math.imul(ah9, bh7); + lo = (lo + Math.imul(al8, bl8)) | 0; + mid = (mid + Math.imul(al8, bh8)) | 0; + mid = (mid + Math.imul(ah8, bl8)) | 0; + hi = (hi + Math.imul(ah8, bh8)) | 0; + lo = (lo + Math.imul(al7, bl9)) | 0; + mid = (mid + Math.imul(al7, bh9)) | 0; + mid = (mid + Math.imul(ah7, bl9)) | 0; + hi = (hi + Math.imul(ah7, bh9)) | 0; + var w16 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w16 >>> 26)) | 0; + w16 &= 0x3ffffff; + /* k = 17 */ + lo = Math.imul(al9, bl8); + mid = Math.imul(al9, bh8); + mid = (mid + Math.imul(ah9, bl8)) | 0; + hi = Math.imul(ah9, bh8); + lo = (lo + Math.imul(al8, bl9)) | 0; + mid = (mid + Math.imul(al8, bh9)) | 0; + mid = (mid + Math.imul(ah8, bl9)) | 0; + hi = (hi + Math.imul(ah8, bh9)) | 0; + var w17 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w17 >>> 26)) | 0; + w17 &= 0x3ffffff; + /* k = 18 */ + lo = Math.imul(al9, bl9); + mid = Math.imul(al9, bh9); + mid = (mid + Math.imul(ah9, bl9)) | 0; + hi = Math.imul(ah9, bh9); + var w18 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w18 >>> 26)) | 0; + w18 &= 0x3ffffff; + o[0] = w0; + o[1] = w1; + o[2] = w2; + o[3] = w3; + o[4] = w4; + o[5] = w5; + o[6] = w6; + o[7] = w7; + o[8] = w8; + o[9] = w9; + o[10] = w10; + o[11] = w11; + o[12] = w12; + o[13] = w13; + o[14] = w14; + o[15] = w15; + o[16] = w16; + o[17] = w17; + o[18] = w18; + if (c !== 0) { + o[19] = c; + out.length++; + } + return out; + }; + + // Polyfill comb + if (!Math.imul) { + comb10MulTo = smallMulTo; + } + + function bigMulTo (self, num, out) { + out.negative = num.negative ^ self.negative; + out.length = self.length + num.length; + + var carry = 0; + var hncarry = 0; + for (var k = 0; k < out.length - 1; k++) { + // Sum all words with the same `i + j = k` and accumulate `ncarry`, + // note that ncarry could be >= 0x3ffffff + var ncarry = hncarry; + hncarry = 0; + var rword = carry & 0x3ffffff; + var maxJ = Math.min(k, num.length - 1); + for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) { + var i = k - j; + var a = self.words[i] | 0; + var b = num.words[j] | 0; + var r = a * b; + + var lo = r & 0x3ffffff; + ncarry = (ncarry + ((r / 0x4000000) | 0)) | 0; + lo = (lo + rword) | 0; + rword = lo & 0x3ffffff; + ncarry = (ncarry + (lo >>> 26)) | 0; + + hncarry += ncarry >>> 26; + ncarry &= 0x3ffffff; + } + out.words[k] = rword; + carry = ncarry; + ncarry = hncarry; + } + if (carry !== 0) { + out.words[k] = carry; + } else { + out.length--; + } + + return out.strip(); + } + + function jumboMulTo (self, num, out) { + var fftm = new FFTM(); + return fftm.mulp(self, num, out); + } + + BN.prototype.mulTo = function mulTo (num, out) { + var res; + var len = this.length + num.length; + if (this.length === 10 && num.length === 10) { + res = comb10MulTo(this, num, out); + } else if (len < 63) { + res = smallMulTo(this, num, out); + } else if (len < 1024) { + res = bigMulTo(this, num, out); + } else { + res = jumboMulTo(this, num, out); + } + + return res; + }; + + // Cooley-Tukey algorithm for FFT + // slightly revisited to rely on looping instead of recursion + + function FFTM (x, y) { + this.x = x; + this.y = y; + } + + FFTM.prototype.makeRBT = function makeRBT (N) { + var t = new Array(N); + var l = BN.prototype._countBits(N) - 1; + for (var i = 0; i < N; i++) { + t[i] = this.revBin(i, l, N); + } + + return t; + }; + + // Returns binary-reversed representation of `x` + FFTM.prototype.revBin = function revBin (x, l, N) { + if (x === 0 || x === N - 1) return x; + + var rb = 0; + for (var i = 0; i < l; i++) { + rb |= (x & 1) << (l - i - 1); + x >>= 1; + } + + return rb; + }; + + // Performs "tweedling" phase, therefore 'emulating' + // behaviour of the recursive algorithm + FFTM.prototype.permute = function permute (rbt, rws, iws, rtws, itws, N) { + for (var i = 0; i < N; i++) { + rtws[i] = rws[rbt[i]]; + itws[i] = iws[rbt[i]]; + } + }; + + FFTM.prototype.transform = function transform (rws, iws, rtws, itws, N, rbt) { + this.permute(rbt, rws, iws, rtws, itws, N); + + for (var s = 1; s < N; s <<= 1) { + var l = s << 1; + + var rtwdf = Math.cos(2 * Math.PI / l); + var itwdf = Math.sin(2 * Math.PI / l); + + for (var p = 0; p < N; p += l) { + var rtwdf_ = rtwdf; + var itwdf_ = itwdf; + + for (var j = 0; j < s; j++) { + var re = rtws[p + j]; + var ie = itws[p + j]; + + var ro = rtws[p + j + s]; + var io = itws[p + j + s]; + + var rx = rtwdf_ * ro - itwdf_ * io; + + io = rtwdf_ * io + itwdf_ * ro; + ro = rx; + + rtws[p + j] = re + ro; + itws[p + j] = ie + io; + + rtws[p + j + s] = re - ro; + itws[p + j + s] = ie - io; + + /* jshint maxdepth : false */ + if (j !== l) { + rx = rtwdf * rtwdf_ - itwdf * itwdf_; + + itwdf_ = rtwdf * itwdf_ + itwdf * rtwdf_; + rtwdf_ = rx; + } + } + } + } + }; + + FFTM.prototype.guessLen13b = function guessLen13b (n, m) { + var N = Math.max(m, n) | 1; + var odd = N & 1; + var i = 0; + for (N = N / 2 | 0; N; N = N >>> 1) { + i++; + } + + return 1 << i + 1 + odd; + }; + + FFTM.prototype.conjugate = function conjugate (rws, iws, N) { + if (N <= 1) return; + + for (var i = 0; i < N / 2; i++) { + var t = rws[i]; + + rws[i] = rws[N - i - 1]; + rws[N - i - 1] = t; + + t = iws[i]; + + iws[i] = -iws[N - i - 1]; + iws[N - i - 1] = -t; + } + }; + + FFTM.prototype.normalize13b = function normalize13b (ws, N) { + var carry = 0; + for (var i = 0; i < N / 2; i++) { + var w = Math.round(ws[2 * i + 1] / N) * 0x2000 + + Math.round(ws[2 * i] / N) + + carry; + + ws[i] = w & 0x3ffffff; + + if (w < 0x4000000) { + carry = 0; + } else { + carry = w / 0x4000000 | 0; + } + } + + return ws; + }; + + FFTM.prototype.convert13b = function convert13b (ws, len, rws, N) { + var carry = 0; + for (var i = 0; i < len; i++) { + carry = carry + (ws[i] | 0); + + rws[2 * i] = carry & 0x1fff; carry = carry >>> 13; + rws[2 * i + 1] = carry & 0x1fff; carry = carry >>> 13; + } + + // Pad with zeroes + for (i = 2 * len; i < N; ++i) { + rws[i] = 0; + } + + assert(carry === 0); + assert((carry & ~0x1fff) === 0); + }; + + FFTM.prototype.stub = function stub (N) { + var ph = new Array(N); + for (var i = 0; i < N; i++) { + ph[i] = 0; + } + + return ph; + }; + + FFTM.prototype.mulp = function mulp (x, y, out) { + var N = 2 * this.guessLen13b(x.length, y.length); + + var rbt = this.makeRBT(N); + + var _ = this.stub(N); + + var rws = new Array(N); + var rwst = new Array(N); + var iwst = new Array(N); + + var nrws = new Array(N); + var nrwst = new Array(N); + var niwst = new Array(N); + + var rmws = out.words; + rmws.length = N; + + this.convert13b(x.words, x.length, rws, N); + this.convert13b(y.words, y.length, nrws, N); + + this.transform(rws, _, rwst, iwst, N, rbt); + this.transform(nrws, _, nrwst, niwst, N, rbt); + + for (var i = 0; i < N; i++) { + var rx = rwst[i] * nrwst[i] - iwst[i] * niwst[i]; + iwst[i] = rwst[i] * niwst[i] + iwst[i] * nrwst[i]; + rwst[i] = rx; + } + + this.conjugate(rwst, iwst, N); + this.transform(rwst, iwst, rmws, _, N, rbt); + this.conjugate(rmws, _, N); + this.normalize13b(rmws, N); + + out.negative = x.negative ^ y.negative; + out.length = x.length + y.length; + return out.strip(); + }; + + // Multiply `this` by `num` + BN.prototype.mul = function mul (num) { + var out = new BN(null); + out.words = new Array(this.length + num.length); + return this.mulTo(num, out); + }; + + // Multiply employing FFT + BN.prototype.mulf = function mulf (num) { + var out = new BN(null); + out.words = new Array(this.length + num.length); + return jumboMulTo(this, num, out); + }; + + // In-place Multiplication + BN.prototype.imul = function imul (num) { + return this.clone().mulTo(num, this); + }; + + BN.prototype.imuln = function imuln (num) { + assert(typeof num === 'number'); + assert(num < 0x4000000); + + // Carry + var carry = 0; + for (var i = 0; i < this.length; i++) { + var w = (this.words[i] | 0) * num; + var lo = (w & 0x3ffffff) + (carry & 0x3ffffff); + carry >>= 26; + carry += (w / 0x4000000) | 0; + // NOTE: lo is 27bit maximum + carry += lo >>> 26; + this.words[i] = lo & 0x3ffffff; + } + + if (carry !== 0) { + this.words[i] = carry; + this.length++; + } + + return this; + }; + + BN.prototype.muln = function muln (num) { + return this.clone().imuln(num); + }; + + // `this` * `this` + BN.prototype.sqr = function sqr () { + return this.mul(this); + }; + + // `this` * `this` in-place + BN.prototype.isqr = function isqr () { + return this.imul(this.clone()); + }; + + // Math.pow(`this`, `num`) + BN.prototype.pow = function pow (num) { + var w = toBitArray(num); + if (w.length === 0) return new BN(1); + + // Skip leading zeroes + var res = this; + for (var i = 0; i < w.length; i++, res = res.sqr()) { + if (w[i] !== 0) break; + } + + if (++i < w.length) { + for (var q = res.sqr(); i < w.length; i++, q = q.sqr()) { + if (w[i] === 0) continue; + + res = res.mul(q); + } + } + + return res; + }; + + // Shift-left in-place + BN.prototype.iushln = function iushln (bits) { + assert(typeof bits === 'number' && bits >= 0); + var r = bits % 26; + var s = (bits - r) / 26; + var carryMask = (0x3ffffff >>> (26 - r)) << (26 - r); + var i; + + if (r !== 0) { + var carry = 0; + + for (i = 0; i < this.length; i++) { + var newCarry = this.words[i] & carryMask; + var c = ((this.words[i] | 0) - newCarry) << r; + this.words[i] = c | carry; + carry = newCarry >>> (26 - r); + } + + if (carry) { + this.words[i] = carry; + this.length++; + } + } + + if (s !== 0) { + for (i = this.length - 1; i >= 0; i--) { + this.words[i + s] = this.words[i]; + } + + for (i = 0; i < s; i++) { + this.words[i] = 0; + } + + this.length += s; + } + + return this.strip(); + }; + + BN.prototype.ishln = function ishln (bits) { + // TODO(indutny): implement me + assert(this.negative === 0); + return this.iushln(bits); + }; + + // Shift-right in-place + // NOTE: `hint` is a lowest bit before trailing zeroes + // NOTE: if `extended` is present - it will be filled with destroyed bits + BN.prototype.iushrn = function iushrn (bits, hint, extended) { + assert(typeof bits === 'number' && bits >= 0); + var h; + if (hint) { + h = (hint - (hint % 26)) / 26; + } else { + h = 0; + } + + var r = bits % 26; + var s = Math.min((bits - r) / 26, this.length); + var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r); + var maskedWords = extended; + + h -= s; + h = Math.max(0, h); + + // Extended mode, copy masked part + if (maskedWords) { + for (var i = 0; i < s; i++) { + maskedWords.words[i] = this.words[i]; + } + maskedWords.length = s; + } + + if (s === 0) { + // No-op, we should not move anything at all + } else if (this.length > s) { + this.length -= s; + for (i = 0; i < this.length; i++) { + this.words[i] = this.words[i + s]; + } + } else { + this.words[0] = 0; + this.length = 1; + } + + var carry = 0; + for (i = this.length - 1; i >= 0 && (carry !== 0 || i >= h); i--) { + var word = this.words[i] | 0; + this.words[i] = (carry << (26 - r)) | (word >>> r); + carry = word & mask; + } + + // Push carried bits as a mask + if (maskedWords && carry !== 0) { + maskedWords.words[maskedWords.length++] = carry; + } + + if (this.length === 0) { + this.words[0] = 0; + this.length = 1; + } + + return this.strip(); + }; + + BN.prototype.ishrn = function ishrn (bits, hint, extended) { + // TODO(indutny): implement me + assert(this.negative === 0); + return this.iushrn(bits, hint, extended); + }; + + // Shift-left + BN.prototype.shln = function shln (bits) { + return this.clone().ishln(bits); + }; + + BN.prototype.ushln = function ushln (bits) { + return this.clone().iushln(bits); + }; + + // Shift-right + BN.prototype.shrn = function shrn (bits) { + return this.clone().ishrn(bits); + }; + + BN.prototype.ushrn = function ushrn (bits) { + return this.clone().iushrn(bits); + }; + + // Test if n bit is set + BN.prototype.testn = function testn (bit) { + assert(typeof bit === 'number' && bit >= 0); + var r = bit % 26; + var s = (bit - r) / 26; + var q = 1 << r; + + // Fast case: bit is much higher than all existing words + if (this.length <= s) return false; + + // Check bit and return + var w = this.words[s]; + + return !!(w & q); + }; + + // Return only lowers bits of number (in-place) + BN.prototype.imaskn = function imaskn (bits) { + assert(typeof bits === 'number' && bits >= 0); + var r = bits % 26; + var s = (bits - r) / 26; + + assert(this.negative === 0, 'imaskn works only with positive numbers'); + + if (this.length <= s) { + return this; + } + + if (r !== 0) { + s++; + } + this.length = Math.min(s, this.length); + + if (r !== 0) { + var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r); + this.words[this.length - 1] &= mask; + } + + return this.strip(); + }; + + // Return only lowers bits of number + BN.prototype.maskn = function maskn (bits) { + return this.clone().imaskn(bits); + }; + + // Add plain number `num` to `this` + BN.prototype.iaddn = function iaddn (num) { + assert(typeof num === 'number'); + assert(num < 0x4000000); + if (num < 0) return this.isubn(-num); + + // Possible sign change + if (this.negative !== 0) { + if (this.length === 1 && (this.words[0] | 0) < num) { + this.words[0] = num - (this.words[0] | 0); + this.negative = 0; + return this; + } + + this.negative = 0; + this.isubn(num); + this.negative = 1; + return this; + } + + // Add without checks + return this._iaddn(num); + }; + + BN.prototype._iaddn = function _iaddn (num) { + this.words[0] += num; + + // Carry + for (var i = 0; i < this.length && this.words[i] >= 0x4000000; i++) { + this.words[i] -= 0x4000000; + if (i === this.length - 1) { + this.words[i + 1] = 1; + } else { + this.words[i + 1]++; + } + } + this.length = Math.max(this.length, i + 1); + + return this; + }; + + // Subtract plain number `num` from `this` + BN.prototype.isubn = function isubn (num) { + assert(typeof num === 'number'); + assert(num < 0x4000000); + if (num < 0) return this.iaddn(-num); + + if (this.negative !== 0) { + this.negative = 0; + this.iaddn(num); + this.negative = 1; + return this; + } + + this.words[0] -= num; + + if (this.length === 1 && this.words[0] < 0) { + this.words[0] = -this.words[0]; + this.negative = 1; + } else { + // Carry + for (var i = 0; i < this.length && this.words[i] < 0; i++) { + this.words[i] += 0x4000000; + this.words[i + 1] -= 1; + } + } + + return this.strip(); + }; + + BN.prototype.addn = function addn (num) { + return this.clone().iaddn(num); + }; + + BN.prototype.subn = function subn (num) { + return this.clone().isubn(num); + }; + + BN.prototype.iabs = function iabs () { + this.negative = 0; + + return this; + }; + + BN.prototype.abs = function abs () { + return this.clone().iabs(); + }; + + BN.prototype._ishlnsubmul = function _ishlnsubmul (num, mul, shift) { + var len = num.length + shift; + var i; + + this._expand(len); + + var w; + var carry = 0; + for (i = 0; i < num.length; i++) { + w = (this.words[i + shift] | 0) + carry; + var right = (num.words[i] | 0) * mul; + w -= right & 0x3ffffff; + carry = (w >> 26) - ((right / 0x4000000) | 0); + this.words[i + shift] = w & 0x3ffffff; + } + for (; i < this.length - shift; i++) { + w = (this.words[i + shift] | 0) + carry; + carry = w >> 26; + this.words[i + shift] = w & 0x3ffffff; + } + + if (carry === 0) return this.strip(); + + // Subtraction overflow + assert(carry === -1); + carry = 0; + for (i = 0; i < this.length; i++) { + w = -(this.words[i] | 0) + carry; + carry = w >> 26; + this.words[i] = w & 0x3ffffff; + } + this.negative = 1; + + return this.strip(); + }; + + BN.prototype._wordDiv = function _wordDiv (num, mode) { + var shift = this.length - num.length; + + var a = this.clone(); + var b = num; + + // Normalize + var bhi = b.words[b.length - 1] | 0; + var bhiBits = this._countBits(bhi); + shift = 26 - bhiBits; + if (shift !== 0) { + b = b.ushln(shift); + a.iushln(shift); + bhi = b.words[b.length - 1] | 0; + } + + // Initialize quotient + var m = a.length - b.length; + var q; + + if (mode !== 'mod') { + q = new BN(null); + q.length = m + 1; + q.words = new Array(q.length); + for (var i = 0; i < q.length; i++) { + q.words[i] = 0; + } + } + + var diff = a.clone()._ishlnsubmul(b, 1, m); + if (diff.negative === 0) { + a = diff; + if (q) { + q.words[m] = 1; + } + } + + for (var j = m - 1; j >= 0; j--) { + var qj = (a.words[b.length + j] | 0) * 0x4000000 + + (a.words[b.length + j - 1] | 0); + + // NOTE: (qj / bhi) is (0x3ffffff * 0x4000000 + 0x3ffffff) / 0x2000000 max + // (0x7ffffff) + qj = Math.min((qj / bhi) | 0, 0x3ffffff); + + a._ishlnsubmul(b, qj, j); + while (a.negative !== 0) { + qj--; + a.negative = 0; + a._ishlnsubmul(b, 1, j); + if (!a.isZero()) { + a.negative ^= 1; + } + } + if (q) { + q.words[j] = qj; + } + } + if (q) { + q.strip(); + } + a.strip(); + + // Denormalize + if (mode !== 'div' && shift !== 0) { + a.iushrn(shift); + } + + return { + div: q || null, + mod: a + }; + }; + + // NOTE: 1) `mode` can be set to `mod` to request mod only, + // to `div` to request div only, or be absent to + // request both div & mod + // 2) `positive` is true if unsigned mod is requested + BN.prototype.divmod = function divmod (num, mode, positive) { + assert(!num.isZero()); + + if (this.isZero()) { + return { + div: new BN(0), + mod: new BN(0) + }; + } + + var div, mod, res; + if (this.negative !== 0 && num.negative === 0) { + res = this.neg().divmod(num, mode); + + if (mode !== 'mod') { + div = res.div.neg(); + } + + if (mode !== 'div') { + mod = res.mod.neg(); + if (positive && mod.negative !== 0) { + mod.iadd(num); + } + } + + return { + div: div, + mod: mod + }; + } + + if (this.negative === 0 && num.negative !== 0) { + res = this.divmod(num.neg(), mode); + + if (mode !== 'mod') { + div = res.div.neg(); + } + + return { + div: div, + mod: res.mod + }; + } + + if ((this.negative & num.negative) !== 0) { + res = this.neg().divmod(num.neg(), mode); + + if (mode !== 'div') { + mod = res.mod.neg(); + if (positive && mod.negative !== 0) { + mod.isub(num); + } + } + + return { + div: res.div, + mod: mod + }; + } + + // Both numbers are positive at this point + + // Strip both numbers to approximate shift value + if (num.length > this.length || this.cmp(num) < 0) { + return { + div: new BN(0), + mod: this + }; + } + + // Very short reduction + if (num.length === 1) { + if (mode === 'div') { + return { + div: this.divn(num.words[0]), + mod: null + }; + } + + if (mode === 'mod') { + return { + div: null, + mod: new BN(this.modn(num.words[0])) + }; + } + + return { + div: this.divn(num.words[0]), + mod: new BN(this.modn(num.words[0])) + }; + } + + return this._wordDiv(num, mode); + }; + + // Find `this` / `num` + BN.prototype.div = function div (num) { + return this.divmod(num, 'div', false).div; + }; + + // Find `this` % `num` + BN.prototype.mod = function mod (num) { + return this.divmod(num, 'mod', false).mod; + }; + + BN.prototype.umod = function umod (num) { + return this.divmod(num, 'mod', true).mod; + }; + + // Find Round(`this` / `num`) + BN.prototype.divRound = function divRound (num) { + var dm = this.divmod(num); + + // Fast case - exact division + if (dm.mod.isZero()) return dm.div; + + var mod = dm.div.negative !== 0 ? dm.mod.isub(num) : dm.mod; + + var half = num.ushrn(1); + var r2 = num.andln(1); + var cmp = mod.cmp(half); + + // Round down + if (cmp < 0 || r2 === 1 && cmp === 0) return dm.div; + + // Round up + return dm.div.negative !== 0 ? dm.div.isubn(1) : dm.div.iaddn(1); + }; + + BN.prototype.modn = function modn (num) { + assert(num <= 0x3ffffff); + var p = (1 << 26) % num; + + var acc = 0; + for (var i = this.length - 1; i >= 0; i--) { + acc = (p * acc + (this.words[i] | 0)) % num; + } + + return acc; + }; + + // In-place division by number + BN.prototype.idivn = function idivn (num) { + assert(num <= 0x3ffffff); + + var carry = 0; + for (var i = this.length - 1; i >= 0; i--) { + var w = (this.words[i] | 0) + carry * 0x4000000; + this.words[i] = (w / num) | 0; + carry = w % num; + } + + return this.strip(); + }; + + BN.prototype.divn = function divn (num) { + return this.clone().idivn(num); + }; + + BN.prototype.egcd = function egcd (p) { + assert(p.negative === 0); + assert(!p.isZero()); + + var x = this; + var y = p.clone(); + + if (x.negative !== 0) { + x = x.umod(p); + } else { + x = x.clone(); + } + + // A * x + B * y = x + var A = new BN(1); + var B = new BN(0); + + // C * x + D * y = y + var C = new BN(0); + var D = new BN(1); + + var g = 0; + + while (x.isEven() && y.isEven()) { + x.iushrn(1); + y.iushrn(1); + ++g; + } + + var yp = y.clone(); + var xp = x.clone(); + + while (!x.isZero()) { + for (var i = 0, im = 1; (x.words[0] & im) === 0 && i < 26; ++i, im <<= 1); + if (i > 0) { + x.iushrn(i); + while (i-- > 0) { + if (A.isOdd() || B.isOdd()) { + A.iadd(yp); + B.isub(xp); + } + + A.iushrn(1); + B.iushrn(1); + } + } + + for (var j = 0, jm = 1; (y.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1); + if (j > 0) { + y.iushrn(j); + while (j-- > 0) { + if (C.isOdd() || D.isOdd()) { + C.iadd(yp); + D.isub(xp); + } + + C.iushrn(1); + D.iushrn(1); + } + } + + if (x.cmp(y) >= 0) { + x.isub(y); + A.isub(C); + B.isub(D); + } else { + y.isub(x); + C.isub(A); + D.isub(B); + } + } + + return { + a: C, + b: D, + gcd: y.iushln(g) + }; + }; + + // This is reduced incarnation of the binary EEA + // above, designated to invert members of the + // _prime_ fields F(p) at a maximal speed + BN.prototype._invmp = function _invmp (p) { + assert(p.negative === 0); + assert(!p.isZero()); + + var a = this; + var b = p.clone(); + + if (a.negative !== 0) { + a = a.umod(p); + } else { + a = a.clone(); + } + + var x1 = new BN(1); + var x2 = new BN(0); + + var delta = b.clone(); + + while (a.cmpn(1) > 0 && b.cmpn(1) > 0) { + for (var i = 0, im = 1; (a.words[0] & im) === 0 && i < 26; ++i, im <<= 1); + if (i > 0) { + a.iushrn(i); + while (i-- > 0) { + if (x1.isOdd()) { + x1.iadd(delta); + } + + x1.iushrn(1); + } + } + + for (var j = 0, jm = 1; (b.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1); + if (j > 0) { + b.iushrn(j); + while (j-- > 0) { + if (x2.isOdd()) { + x2.iadd(delta); + } + + x2.iushrn(1); + } + } + + if (a.cmp(b) >= 0) { + a.isub(b); + x1.isub(x2); + } else { + b.isub(a); + x2.isub(x1); + } + } + + var res; + if (a.cmpn(1) === 0) { + res = x1; + } else { + res = x2; + } + + if (res.cmpn(0) < 0) { + res.iadd(p); + } + + return res; + }; + + BN.prototype.gcd = function gcd (num) { + if (this.isZero()) return num.abs(); + if (num.isZero()) return this.abs(); + + var a = this.clone(); + var b = num.clone(); + a.negative = 0; + b.negative = 0; + + // Remove common factor of two + for (var shift = 0; a.isEven() && b.isEven(); shift++) { + a.iushrn(1); + b.iushrn(1); + } + + do { + while (a.isEven()) { + a.iushrn(1); + } + while (b.isEven()) { + b.iushrn(1); + } + + var r = a.cmp(b); + if (r < 0) { + // Swap `a` and `b` to make `a` always bigger than `b` + var t = a; + a = b; + b = t; + } else if (r === 0 || b.cmpn(1) === 0) { + break; + } + + a.isub(b); + } while (true); + + return b.iushln(shift); + }; + + // Invert number in the field F(num) + BN.prototype.invm = function invm (num) { + return this.egcd(num).a.umod(num); + }; + + BN.prototype.isEven = function isEven () { + return (this.words[0] & 1) === 0; + }; + + BN.prototype.isOdd = function isOdd () { + return (this.words[0] & 1) === 1; + }; + + // And first word and num + BN.prototype.andln = function andln (num) { + return this.words[0] & num; + }; + + // Increment at the bit position in-line + BN.prototype.bincn = function bincn (bit) { + assert(typeof bit === 'number'); + var r = bit % 26; + var s = (bit - r) / 26; + var q = 1 << r; + + // Fast case: bit is much higher than all existing words + if (this.length <= s) { + this._expand(s + 1); + this.words[s] |= q; + return this; + } + + // Add bit and propagate, if needed + var carry = q; + for (var i = s; carry !== 0 && i < this.length; i++) { + var w = this.words[i] | 0; + w += carry; + carry = w >>> 26; + w &= 0x3ffffff; + this.words[i] = w; + } + if (carry !== 0) { + this.words[i] = carry; + this.length++; + } + return this; + }; + + BN.prototype.isZero = function isZero () { + return this.length === 1 && this.words[0] === 0; + }; + + BN.prototype.cmpn = function cmpn (num) { + var negative = num < 0; + + if (this.negative !== 0 && !negative) return -1; + if (this.negative === 0 && negative) return 1; + + this.strip(); + + var res; + if (this.length > 1) { + res = 1; + } else { + if (negative) { + num = -num; + } + + assert(num <= 0x3ffffff, 'Number is too big'); + + var w = this.words[0] | 0; + res = w === num ? 0 : w < num ? -1 : 1; + } + if (this.negative !== 0) return -res | 0; + return res; + }; + + // Compare two numbers and return: + // 1 - if `this` > `num` + // 0 - if `this` == `num` + // -1 - if `this` < `num` + BN.prototype.cmp = function cmp (num) { + if (this.negative !== 0 && num.negative === 0) return -1; + if (this.negative === 0 && num.negative !== 0) return 1; + + var res = this.ucmp(num); + if (this.negative !== 0) return -res | 0; + return res; + }; + + // Unsigned comparison + BN.prototype.ucmp = function ucmp (num) { + // At this point both numbers have the same sign + if (this.length > num.length) return 1; + if (this.length < num.length) return -1; + + var res = 0; + for (var i = this.length - 1; i >= 0; i--) { + var a = this.words[i] | 0; + var b = num.words[i] | 0; + + if (a === b) continue; + if (a < b) { + res = -1; + } else if (a > b) { + res = 1; + } + break; + } + return res; + }; + + BN.prototype.gtn = function gtn (num) { + return this.cmpn(num) === 1; + }; + + BN.prototype.gt = function gt (num) { + return this.cmp(num) === 1; + }; + + BN.prototype.gten = function gten (num) { + return this.cmpn(num) >= 0; + }; + + BN.prototype.gte = function gte (num) { + return this.cmp(num) >= 0; + }; + + BN.prototype.ltn = function ltn (num) { + return this.cmpn(num) === -1; + }; + + BN.prototype.lt = function lt (num) { + return this.cmp(num) === -1; + }; + + BN.prototype.lten = function lten (num) { + return this.cmpn(num) <= 0; + }; + + BN.prototype.lte = function lte (num) { + return this.cmp(num) <= 0; + }; + + BN.prototype.eqn = function eqn (num) { + return this.cmpn(num) === 0; + }; + + BN.prototype.eq = function eq (num) { + return this.cmp(num) === 0; + }; + + // + // A reduce context, could be using montgomery or something better, depending + // on the `m` itself. + // + BN.red = function red (num) { + return new Red(num); + }; + + BN.prototype.toRed = function toRed (ctx) { + assert(!this.red, 'Already a number in reduction context'); + assert(this.negative === 0, 'red works only with positives'); + return ctx.convertTo(this)._forceRed(ctx); + }; + + BN.prototype.fromRed = function fromRed () { + assert(this.red, 'fromRed works only with numbers in reduction context'); + return this.red.convertFrom(this); + }; + + BN.prototype._forceRed = function _forceRed (ctx) { + this.red = ctx; + return this; + }; + + BN.prototype.forceRed = function forceRed (ctx) { + assert(!this.red, 'Already a number in reduction context'); + return this._forceRed(ctx); + }; + + BN.prototype.redAdd = function redAdd (num) { + assert(this.red, 'redAdd works only with red numbers'); + return this.red.add(this, num); + }; + + BN.prototype.redIAdd = function redIAdd (num) { + assert(this.red, 'redIAdd works only with red numbers'); + return this.red.iadd(this, num); + }; + + BN.prototype.redSub = function redSub (num) { + assert(this.red, 'redSub works only with red numbers'); + return this.red.sub(this, num); + }; + + BN.prototype.redISub = function redISub (num) { + assert(this.red, 'redISub works only with red numbers'); + return this.red.isub(this, num); + }; + + BN.prototype.redShl = function redShl (num) { + assert(this.red, 'redShl works only with red numbers'); + return this.red.shl(this, num); + }; + + BN.prototype.redMul = function redMul (num) { + assert(this.red, 'redMul works only with red numbers'); + this.red._verify2(this, num); + return this.red.mul(this, num); + }; + + BN.prototype.redIMul = function redIMul (num) { + assert(this.red, 'redMul works only with red numbers'); + this.red._verify2(this, num); + return this.red.imul(this, num); + }; + + BN.prototype.redSqr = function redSqr () { + assert(this.red, 'redSqr works only with red numbers'); + this.red._verify1(this); + return this.red.sqr(this); + }; + + BN.prototype.redISqr = function redISqr () { + assert(this.red, 'redISqr works only with red numbers'); + this.red._verify1(this); + return this.red.isqr(this); + }; + + // Square root over p + BN.prototype.redSqrt = function redSqrt () { + assert(this.red, 'redSqrt works only with red numbers'); + this.red._verify1(this); + return this.red.sqrt(this); + }; + + BN.prototype.redInvm = function redInvm () { + assert(this.red, 'redInvm works only with red numbers'); + this.red._verify1(this); + return this.red.invm(this); + }; + + // Return negative clone of `this` % `red modulo` + BN.prototype.redNeg = function redNeg () { + assert(this.red, 'redNeg works only with red numbers'); + this.red._verify1(this); + return this.red.neg(this); + }; + + BN.prototype.redPow = function redPow (num) { + assert(this.red && !num.red, 'redPow(normalNum)'); + this.red._verify1(this); + return this.red.pow(this, num); + }; + + // Prime numbers with efficient reduction + var primes = { + k256: null, + p224: null, + p192: null, + p25519: null + }; + + // Pseudo-Mersenne prime + function MPrime (name, p) { + // P = 2 ^ N - K + this.name = name; + this.p = new BN(p, 16); + this.n = this.p.bitLength(); + this.k = new BN(1).iushln(this.n).isub(this.p); + + this.tmp = this._tmp(); + } + + MPrime.prototype._tmp = function _tmp () { + var tmp = new BN(null); + tmp.words = new Array(Math.ceil(this.n / 13)); + return tmp; + }; + + MPrime.prototype.ireduce = function ireduce (num) { + // Assumes that `num` is less than `P^2` + // num = HI * (2 ^ N - K) + HI * K + LO = HI * K + LO (mod P) + var r = num; + var rlen; + + do { + this.split(r, this.tmp); + r = this.imulK(r); + r = r.iadd(this.tmp); + rlen = r.bitLength(); + } while (rlen > this.n); + + var cmp = rlen < this.n ? -1 : r.ucmp(this.p); + if (cmp === 0) { + r.words[0] = 0; + r.length = 1; + } else if (cmp > 0) { + r.isub(this.p); + } else { + if (r.strip !== undefined) { + // r is BN v4 instance + r.strip(); + } else { + // r is BN v5 instance + r._strip(); + } + } + + return r; + }; + + MPrime.prototype.split = function split (input, out) { + input.iushrn(this.n, 0, out); + }; + + MPrime.prototype.imulK = function imulK (num) { + return num.imul(this.k); + }; + + function K256 () { + MPrime.call( + this, + 'k256', + 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f'); + } + inherits(K256, MPrime); + + K256.prototype.split = function split (input, output) { + // 256 = 9 * 26 + 22 + var mask = 0x3fffff; + + var outLen = Math.min(input.length, 9); + for (var i = 0; i < outLen; i++) { + output.words[i] = input.words[i]; + } + output.length = outLen; + + if (input.length <= 9) { + input.words[0] = 0; + input.length = 1; + return; + } + + // Shift by 9 limbs + var prev = input.words[9]; + output.words[output.length++] = prev & mask; + + for (i = 10; i < input.length; i++) { + var next = input.words[i] | 0; + input.words[i - 10] = ((next & mask) << 4) | (prev >>> 22); + prev = next; + } + prev >>>= 22; + input.words[i - 10] = prev; + if (prev === 0 && input.length > 10) { + input.length -= 10; + } else { + input.length -= 9; + } + }; + + K256.prototype.imulK = function imulK (num) { + // K = 0x1000003d1 = [ 0x40, 0x3d1 ] + num.words[num.length] = 0; + num.words[num.length + 1] = 0; + num.length += 2; + + // bounded at: 0x40 * 0x3ffffff + 0x3d0 = 0x100000390 + var lo = 0; + for (var i = 0; i < num.length; i++) { + var w = num.words[i] | 0; + lo += w * 0x3d1; + num.words[i] = lo & 0x3ffffff; + lo = w * 0x40 + ((lo / 0x4000000) | 0); + } + + // Fast length reduction + if (num.words[num.length - 1] === 0) { + num.length--; + if (num.words[num.length - 1] === 0) { + num.length--; + } + } + return num; + }; + + function P224 () { + MPrime.call( + this, + 'p224', + 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001'); + } + inherits(P224, MPrime); + + function P192 () { + MPrime.call( + this, + 'p192', + 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff'); + } + inherits(P192, MPrime); + + function P25519 () { + // 2 ^ 255 - 19 + MPrime.call( + this, + '25519', + '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed'); + } + inherits(P25519, MPrime); + + P25519.prototype.imulK = function imulK (num) { + // K = 0x13 + var carry = 0; + for (var i = 0; i < num.length; i++) { + var hi = (num.words[i] | 0) * 0x13 + carry; + var lo = hi & 0x3ffffff; + hi >>>= 26; + + num.words[i] = lo; + carry = hi; + } + if (carry !== 0) { + num.words[num.length++] = carry; + } + return num; + }; + + // Exported mostly for testing purposes, use plain name instead + BN._prime = function prime (name) { + // Cached version of prime + if (primes[name]) return primes[name]; + + var prime; + if (name === 'k256') { + prime = new K256(); + } else if (name === 'p224') { + prime = new P224(); + } else if (name === 'p192') { + prime = new P192(); + } else if (name === 'p25519') { + prime = new P25519(); + } else { + throw new Error('Unknown prime ' + name); + } + primes[name] = prime; + + return prime; + }; + + // + // Base reduction engine + // + function Red (m) { + if (typeof m === 'string') { + var prime = BN._prime(m); + this.m = prime.p; + this.prime = prime; + } else { + assert(m.gtn(1), 'modulus must be greater than 1'); + this.m = m; + this.prime = null; + } + } + + Red.prototype._verify1 = function _verify1 (a) { + assert(a.negative === 0, 'red works only with positives'); + assert(a.red, 'red works only with red numbers'); + }; + + Red.prototype._verify2 = function _verify2 (a, b) { + assert((a.negative | b.negative) === 0, 'red works only with positives'); + assert(a.red && a.red === b.red, + 'red works only with red numbers'); + }; + + Red.prototype.imod = function imod (a) { + if (this.prime) return this.prime.ireduce(a)._forceRed(this); + return a.umod(this.m)._forceRed(this); + }; + + Red.prototype.neg = function neg (a) { + if (a.isZero()) { + return a.clone(); + } + + return this.m.sub(a)._forceRed(this); + }; + + Red.prototype.add = function add (a, b) { + this._verify2(a, b); + + var res = a.add(b); + if (res.cmp(this.m) >= 0) { + res.isub(this.m); + } + return res._forceRed(this); + }; + + Red.prototype.iadd = function iadd (a, b) { + this._verify2(a, b); + + var res = a.iadd(b); + if (res.cmp(this.m) >= 0) { + res.isub(this.m); + } + return res; + }; + + Red.prototype.sub = function sub (a, b) { + this._verify2(a, b); + + var res = a.sub(b); + if (res.cmpn(0) < 0) { + res.iadd(this.m); + } + return res._forceRed(this); + }; + + Red.prototype.isub = function isub (a, b) { + this._verify2(a, b); + + var res = a.isub(b); + if (res.cmpn(0) < 0) { + res.iadd(this.m); + } + return res; + }; + + Red.prototype.shl = function shl (a, num) { + this._verify1(a); + return this.imod(a.ushln(num)); + }; + + Red.prototype.imul = function imul (a, b) { + this._verify2(a, b); + return this.imod(a.imul(b)); + }; + + Red.prototype.mul = function mul (a, b) { + this._verify2(a, b); + return this.imod(a.mul(b)); + }; + + Red.prototype.isqr = function isqr (a) { + return this.imul(a, a.clone()); + }; + + Red.prototype.sqr = function sqr (a) { + return this.mul(a, a); + }; + + Red.prototype.sqrt = function sqrt (a) { + if (a.isZero()) return a.clone(); + + var mod3 = this.m.andln(3); + assert(mod3 % 2 === 1); + + // Fast case + if (mod3 === 3) { + var pow = this.m.add(new BN(1)).iushrn(2); + return this.pow(a, pow); + } + + // Tonelli-Shanks algorithm (Totally unoptimized and slow) + // + // Find Q and S, that Q * 2 ^ S = (P - 1) + var q = this.m.subn(1); + var s = 0; + while (!q.isZero() && q.andln(1) === 0) { + s++; + q.iushrn(1); + } + assert(!q.isZero()); + + var one = new BN(1).toRed(this); + var nOne = one.redNeg(); + + // Find quadratic non-residue + // NOTE: Max is such because of generalized Riemann hypothesis. + var lpow = this.m.subn(1).iushrn(1); + var z = this.m.bitLength(); + z = new BN(2 * z * z).toRed(this); + + while (this.pow(z, lpow).cmp(nOne) !== 0) { + z.redIAdd(nOne); + } + + var c = this.pow(z, q); + var r = this.pow(a, q.addn(1).iushrn(1)); + var t = this.pow(a, q); + var m = s; + while (t.cmp(one) !== 0) { + var tmp = t; + for (var i = 0; tmp.cmp(one) !== 0; i++) { + tmp = tmp.redSqr(); + } + assert(i < m); + var b = this.pow(c, new BN(1).iushln(m - i - 1)); + + r = r.redMul(b); + c = b.redSqr(); + t = t.redMul(c); + m = i; + } + + return r; + }; + + Red.prototype.invm = function invm (a) { + var inv = a._invmp(this.m); + if (inv.negative !== 0) { + inv.negative = 0; + return this.imod(inv).redNeg(); + } else { + return this.imod(inv); + } + }; + + Red.prototype.pow = function pow (a, num) { + if (num.isZero()) return new BN(1).toRed(this); + if (num.cmpn(1) === 0) return a.clone(); + + var windowSize = 4; + var wnd = new Array(1 << windowSize); + wnd[0] = new BN(1).toRed(this); + wnd[1] = a; + for (var i = 2; i < wnd.length; i++) { + wnd[i] = this.mul(wnd[i - 1], a); + } + + var res = wnd[0]; + var current = 0; + var currentLen = 0; + var start = num.bitLength() % 26; + if (start === 0) { + start = 26; + } + + for (i = num.length - 1; i >= 0; i--) { + var word = num.words[i]; + for (var j = start - 1; j >= 0; j--) { + var bit = (word >> j) & 1; + if (res !== wnd[0]) { + res = this.sqr(res); + } + + if (bit === 0 && current === 0) { + currentLen = 0; + continue; + } + + current <<= 1; + current |= bit; + currentLen++; + if (currentLen !== windowSize && (i !== 0 || j !== 0)) continue; + + res = this.mul(res, wnd[current]); + currentLen = 0; + current = 0; + } + start = 26; + } + + return res; + }; + + Red.prototype.convertTo = function convertTo (num) { + var r = num.umod(this.m); + + return r === num ? r.clone() : r; + }; + + Red.prototype.convertFrom = function convertFrom (num) { + var res = num.clone(); + res.red = null; + return res; + }; + + // + // Montgomery method engine + // + + BN.mont = function mont (num) { + return new Mont(num); + }; + + function Mont (m) { + Red.call(this, m); + + this.shift = this.m.bitLength(); + if (this.shift % 26 !== 0) { + this.shift += 26 - (this.shift % 26); + } + + this.r = new BN(1).iushln(this.shift); + this.r2 = this.imod(this.r.sqr()); + this.rinv = this.r._invmp(this.m); + + this.minv = this.rinv.mul(this.r).isubn(1).div(this.m); + this.minv = this.minv.umod(this.r); + this.minv = this.r.sub(this.minv); + } + inherits(Mont, Red); + + Mont.prototype.convertTo = function convertTo (num) { + return this.imod(num.ushln(this.shift)); + }; + + Mont.prototype.convertFrom = function convertFrom (num) { + var r = this.imod(num.mul(this.rinv)); + r.red = null; + return r; + }; + + Mont.prototype.imul = function imul (a, b) { + if (a.isZero() || b.isZero()) { + a.words[0] = 0; + a.length = 1; + return a; + } + + var t = a.imul(b); + var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m); + var u = t.isub(c).iushrn(this.shift); + var res = u; + + if (u.cmp(this.m) >= 0) { + res = u.isub(this.m); + } else if (u.cmpn(0) < 0) { + res = u.iadd(this.m); + } + + return res._forceRed(this); + }; + + Mont.prototype.mul = function mul (a, b) { + if (a.isZero() || b.isZero()) return new BN(0)._forceRed(this); + + var t = a.mul(b); + var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m); + var u = t.isub(c).iushrn(this.shift); + var res = u; + if (u.cmp(this.m) >= 0) { + res = u.isub(this.m); + } else if (u.cmpn(0) < 0) { + res = u.iadd(this.m); + } + + return res._forceRed(this); + }; + + Mont.prototype.invm = function invm (a) { + // (AR)^-1 * R^2 = (A^-1 * R^-1) * R^2 = A^-1 * R + var res = this.imod(a._invmp(this.m).mul(this.r2)); + return res._forceRed(this); + }; +})( false || module, this); + + +/***/ }), + +/***/ 7457: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; +/*jshint node:true */ + +var Buffer = (__nccwpck_require__(4300).Buffer); // browserify +var SlowBuffer = (__nccwpck_require__(4300).SlowBuffer); + +module.exports = bufferEq; + +function bufferEq(a, b) { + + // shortcutting on type is necessary for correctness + if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { + return false; + } + + // buffer sizes should be well-known information, so despite this + // shortcutting, it doesn't leak any information about the *contents* of the + // buffers. + if (a.length !== b.length) { + return false; + } + + var c = 0; + for (var i = 0; i < a.length; i++) { + /*jshint bitwise:false */ + c |= a[i] ^ b[i]; // XOR + } + return c === 0; +} + +bufferEq.install = function() { + Buffer.prototype.equal = SlowBuffer.prototype.equal = function equal(that) { + return bufferEq(this, that); + }; +}; + +var origBufEqual = Buffer.prototype.equal; +var origSlowBufEqual = SlowBuffer.prototype.equal; +bufferEq.restore = function() { + Buffer.prototype.equal = origBufEqual; + SlowBuffer.prototype.equal = origSlowBufEqual; +}; + + +/***/ }), + +/***/ 3756: +/***/ ((module, exports, __nccwpck_require__) => { + +/* eslint-env browser */ + +/** + * This is the web browser implementation of `debug()`. + */ + +exports.formatArgs = formatArgs; +exports.save = save; +exports.load = load; +exports.useColors = useColors; +exports.storage = localstorage(); +exports.destroy = (() => { + let warned = false; + + return () => { + if (!warned) { + warned = true; + console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); + } + }; +})(); + +/** + * Colors. + */ + +exports.colors = [ + '#0000CC', + '#0000FF', + '#0033CC', + '#0033FF', + '#0066CC', + '#0066FF', + '#0099CC', + '#0099FF', + '#00CC00', + '#00CC33', + '#00CC66', + '#00CC99', + '#00CCCC', + '#00CCFF', + '#3300CC', + '#3300FF', + '#3333CC', + '#3333FF', + '#3366CC', + '#3366FF', + '#3399CC', + '#3399FF', + '#33CC00', + '#33CC33', + '#33CC66', + '#33CC99', + '#33CCCC', + '#33CCFF', + '#6600CC', + '#6600FF', + '#6633CC', + '#6633FF', + '#66CC00', + '#66CC33', + '#9900CC', + '#9900FF', + '#9933CC', + '#9933FF', + '#99CC00', + '#99CC33', + '#CC0000', + '#CC0033', + '#CC0066', + '#CC0099', + '#CC00CC', + '#CC00FF', + '#CC3300', + '#CC3333', + '#CC3366', + '#CC3399', + '#CC33CC', + '#CC33FF', + '#CC6600', + '#CC6633', + '#CC9900', + '#CC9933', + '#CCCC00', + '#CCCC33', + '#FF0000', + '#FF0033', + '#FF0066', + '#FF0099', + '#FF00CC', + '#FF00FF', + '#FF3300', + '#FF3333', + '#FF3366', + '#FF3399', + '#FF33CC', + '#FF33FF', + '#FF6600', + '#FF6633', + '#FF9900', + '#FF9933', + '#FFCC00', + '#FFCC33' +]; + +/** + * Currently only WebKit-based Web Inspectors, Firefox >= v31, + * and the Firebug extension (any Firefox version) are known + * to support "%c" CSS customizations. + * + * TODO: add a `localStorage` variable to explicitly enable/disable colors + */ + +// eslint-disable-next-line complexity +function useColors() { + // NB: In an Electron preload script, document will be defined but not fully + // initialized. Since we know we're in Chrome, we'll just detect this case + // explicitly + if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) { + return true; + } + + // Internet Explorer and Edge do not support colors. + if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) { + return false; + } + + // Is webkit? http://stackoverflow.com/a/16459606/376773 + // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 + return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) || + // Is firebug? http://stackoverflow.com/a/398120/376773 + (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) || + // Is firefox >= v31? + // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages + (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) || + // Double check webkit in userAgent just in case we are in a worker + (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)); +} + +/** + * Colorize log arguments if enabled. + * + * @api public + */ + +function formatArgs(args) { + args[0] = (this.useColors ? '%c' : '') + + this.namespace + + (this.useColors ? ' %c' : ' ') + + args[0] + + (this.useColors ? '%c ' : ' ') + + '+' + module.exports.humanize(this.diff); + + if (!this.useColors) { + return; + } + + const c = 'color: ' + this.color; + args.splice(1, 0, c, 'color: inherit'); + + // The final "%c" is somewhat tricky, because there could be other + // arguments passed either before or after the %c, so we need to + // figure out the correct index to insert the CSS into + let index = 0; + let lastC = 0; + args[0].replace(/%[a-zA-Z%]/g, match => { + if (match === '%%') { + return; + } + index++; + if (match === '%c') { + // We only are interested in the *last* %c + // (the user may have provided their own) + lastC = index; + } + }); + + args.splice(lastC, 0, c); +} + +/** + * Invokes `console.debug()` when available. + * No-op when `console.debug` is not a "function". + * If `console.debug` is not available, falls back + * to `console.log`. + * + * @api public + */ +exports.log = console.debug || console.log || (() => {}); + +/** + * Save `namespaces`. + * + * @param {String} namespaces + * @api private + */ +function save(namespaces) { + try { + if (namespaces) { + exports.storage.setItem('debug', namespaces); + } else { + exports.storage.removeItem('debug'); + } + } catch (error) { + // Swallow + // XXX (@Qix-) should we be logging these? + } +} + +/** + * Load `namespaces`. + * + * @return {String} returns the previously persisted debug modes + * @api private + */ +function load() { + let r; + try { + r = exports.storage.getItem('debug'); + } catch (error) { + // Swallow + // XXX (@Qix-) should we be logging these? + } + + // If debug isn't set in LS, and we're in Electron, try to load $DEBUG + if (!r && typeof process !== 'undefined' && 'env' in process) { + r = process.env.DEBUG; + } + + return r; +} + +/** + * Localstorage attempts to return the localstorage. + * + * This is necessary because safari throws + * when a user disables cookies/localstorage + * and you attempt to access it. + * + * @return {LocalStorage} + * @api private + */ + +function localstorage() { + try { + // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context + // The Browser also has localStorage in the global context. + return localStorage; + } catch (error) { + // Swallow + // XXX (@Qix-) should we be logging these? + } +} + +module.exports = __nccwpck_require__(8994)(exports); + +const {formatters} = module.exports; + +/** + * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. + */ + +formatters.j = function (v) { + try { + return JSON.stringify(v); + } catch (error) { + return '[UnexpectedJSONParseError]: ' + error.message; + } +}; + + +/***/ }), + +/***/ 8994: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + +/** + * This is the common logic for both the Node.js and web browser + * implementations of `debug()`. + */ + +function setup(env) { + createDebug.debug = createDebug; + createDebug.default = createDebug; + createDebug.coerce = coerce; + createDebug.disable = disable; + createDebug.enable = enable; + createDebug.enabled = enabled; + createDebug.humanize = __nccwpck_require__(3730); + createDebug.destroy = destroy; + + Object.keys(env).forEach(key => { + createDebug[key] = env[key]; + }); + + /** + * The currently active debug mode names, and names to skip. + */ + + createDebug.names = []; + createDebug.skips = []; + + /** + * Map of special "%n" handling functions, for the debug "format" argument. + * + * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". + */ + createDebug.formatters = {}; + + /** + * Selects a color for a debug namespace + * @param {String} namespace The namespace string for the debug instance to be colored + * @return {Number|String} An ANSI color code for the given namespace + * @api private + */ + function selectColor(namespace) { + let hash = 0; + + for (let i = 0; i < namespace.length; i++) { + hash = ((hash << 5) - hash) + namespace.charCodeAt(i); + hash |= 0; // Convert to 32bit integer + } + + return createDebug.colors[Math.abs(hash) % createDebug.colors.length]; + } + createDebug.selectColor = selectColor; + + /** + * Create a debugger with the given `namespace`. + * + * @param {String} namespace + * @return {Function} + * @api public + */ + function createDebug(namespace) { + let prevTime; + let enableOverride = null; + let namespacesCache; + let enabledCache; + + function debug(...args) { + // Disabled? + if (!debug.enabled) { + return; + } + + const self = debug; + + // Set `diff` timestamp + const curr = Number(new Date()); + const ms = curr - (prevTime || curr); + self.diff = ms; + self.prev = prevTime; + self.curr = curr; + prevTime = curr; + + args[0] = createDebug.coerce(args[0]); + + if (typeof args[0] !== 'string') { + // Anything else let's inspect with %O + args.unshift('%O'); + } + + // Apply any `formatters` transformations + let index = 0; + args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => { + // If we encounter an escaped % then don't increase the array index + if (match === '%%') { + return '%'; + } + index++; + const formatter = createDebug.formatters[format]; + if (typeof formatter === 'function') { + const val = args[index]; + match = formatter.call(self, val); + + // Now we need to remove `args[index]` since it's inlined in the `format` + args.splice(index, 1); + index--; + } + return match; + }); + + // Apply env-specific formatting (colors, etc.) + createDebug.formatArgs.call(self, args); + + const logFn = self.log || createDebug.log; + logFn.apply(self, args); + } + + debug.namespace = namespace; + debug.useColors = createDebug.useColors(); + debug.color = createDebug.selectColor(namespace); + debug.extend = extend; + debug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release. + + Object.defineProperty(debug, 'enabled', { + enumerable: true, + configurable: false, + get: () => { + if (enableOverride !== null) { + return enableOverride; + } + if (namespacesCache !== createDebug.namespaces) { + namespacesCache = createDebug.namespaces; + enabledCache = createDebug.enabled(namespace); + } + + return enabledCache; + }, + set: v => { + enableOverride = v; + } + }); + + // Env-specific initialization logic for debug instances + if (typeof createDebug.init === 'function') { + createDebug.init(debug); + } + + return debug; + } + + function extend(namespace, delimiter) { + const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace); + newDebug.log = this.log; + return newDebug; + } + + /** + * Enables a debug mode by namespaces. This can include modes + * separated by a colon and wildcards. + * + * @param {String} namespaces + * @api public + */ + function enable(namespaces) { + createDebug.save(namespaces); + createDebug.namespaces = namespaces; + + createDebug.names = []; + createDebug.skips = []; + + let i; + const split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); + const len = split.length; + + for (i = 0; i < len; i++) { + if (!split[i]) { + // ignore empty strings + continue; + } + + namespaces = split[i].replace(/\*/g, '.*?'); + + if (namespaces[0] === '-') { + createDebug.skips.push(new RegExp('^' + namespaces.slice(1) + '$')); + } else { + createDebug.names.push(new RegExp('^' + namespaces + '$')); + } + } + } + + /** + * Disable debug output. + * + * @return {String} namespaces + * @api public + */ + function disable() { + const namespaces = [ + ...createDebug.names.map(toNamespace), + ...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace) + ].join(','); + createDebug.enable(''); + return namespaces; + } + + /** + * Returns true if the given mode name is enabled, false otherwise. + * + * @param {String} name + * @return {Boolean} + * @api public + */ + function enabled(name) { + if (name[name.length - 1] === '*') { + return true; + } + + let i; + let len; + + for (i = 0, len = createDebug.skips.length; i < len; i++) { + if (createDebug.skips[i].test(name)) { + return false; + } + } + + for (i = 0, len = createDebug.names.length; i < len; i++) { + if (createDebug.names[i].test(name)) { + return true; + } + } + + return false; + } + + /** + * Convert regexp to namespace + * + * @param {RegExp} regxep + * @return {String} namespace + * @api private + */ + function toNamespace(regexp) { + return regexp.toString() + .substring(2, regexp.toString().length - 2) + .replace(/\.\*\?$/, '*'); + } + + /** + * Coerce `val`. + * + * @param {Mixed} val + * @return {Mixed} + * @api private + */ + function coerce(val) { + if (val instanceof Error) { + return val.stack || val.message; + } + return val; + } + + /** + * XXX DO NOT USE. This is a temporary stub function. + * XXX It WILL be removed in the next major release. + */ + function destroy() { + console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); + } + + createDebug.enable(createDebug.load()); + + return createDebug; +} + +module.exports = setup; + + +/***/ }), + +/***/ 5062: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +/** + * Detect Electron renderer / nwjs process, which is node, but we should + * treat as a browser. + */ + +if (typeof process === 'undefined' || process.type === 'renderer' || process.browser === true || process.__nwjs) { + module.exports = __nccwpck_require__(3756); +} else { + module.exports = __nccwpck_require__(5404); +} + + +/***/ }), + +/***/ 5404: +/***/ ((module, exports, __nccwpck_require__) => { + +/** + * Module dependencies. + */ + +const tty = __nccwpck_require__(6224); +const util = __nccwpck_require__(3837); + +/** + * This is the Node.js implementation of `debug()`. + */ + +exports.init = init; +exports.log = log; +exports.formatArgs = formatArgs; +exports.save = save; +exports.load = load; +exports.useColors = useColors; +exports.destroy = util.deprecate( + () => {}, + 'Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.' +); + +/** + * Colors. + */ + +exports.colors = [6, 2, 3, 4, 5, 1]; + +try { + // Optional dependency (as in, doesn't need to be installed, NOT like optionalDependencies in package.json) + // eslint-disable-next-line import/no-extraneous-dependencies + const supportsColor = __nccwpck_require__(4341); + + if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) { + exports.colors = [ + 20, + 21, + 26, + 27, + 32, + 33, + 38, + 39, + 40, + 41, + 42, + 43, + 44, + 45, + 56, + 57, + 62, + 63, + 68, + 69, + 74, + 75, + 76, + 77, + 78, + 79, + 80, + 81, + 92, + 93, + 98, + 99, + 112, + 113, + 128, + 129, + 134, + 135, + 148, + 149, + 160, + 161, + 162, + 163, + 164, + 165, + 166, + 167, + 168, + 169, + 170, + 171, + 172, + 173, + 178, + 179, + 184, + 185, + 196, + 197, + 198, + 199, + 200, + 201, + 202, + 203, + 204, + 205, + 206, + 207, + 208, + 209, + 214, + 215, + 220, + 221 + ]; + } +} catch (error) { + // Swallow - we only care if `supports-color` is available; it doesn't have to be. +} + +/** + * Build up the default `inspectOpts` object from the environment variables. + * + * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js + */ + +exports.inspectOpts = Object.keys(process.env).filter(key => { + return /^debug_/i.test(key); +}).reduce((obj, key) => { + // Camel-case + const prop = key + .substring(6) + .toLowerCase() + .replace(/_([a-z])/g, (_, k) => { + return k.toUpperCase(); + }); + + // Coerce string value into JS value + let val = process.env[key]; + if (/^(yes|on|true|enabled)$/i.test(val)) { + val = true; + } else if (/^(no|off|false|disabled)$/i.test(val)) { + val = false; + } else if (val === 'null') { + val = null; + } else { + val = Number(val); + } + + obj[prop] = val; + return obj; +}, {}); + +/** + * Is stdout a TTY? Colored output is enabled when `true`. + */ + +function useColors() { + return 'colors' in exports.inspectOpts ? + Boolean(exports.inspectOpts.colors) : + tty.isatty(process.stderr.fd); +} + +/** + * Adds ANSI color escape codes if enabled. + * + * @api public + */ + +function formatArgs(args) { + const {namespace: name, useColors} = this; + + if (useColors) { + const c = this.color; + const colorCode = '\u001B[3' + (c < 8 ? c : '8;5;' + c); + const prefix = ` ${colorCode};1m${name} \u001B[0m`; + + args[0] = prefix + args[0].split('\n').join('\n' + prefix); + args.push(colorCode + 'm+' + module.exports.humanize(this.diff) + '\u001B[0m'); + } else { + args[0] = getDate() + name + ' ' + args[0]; + } +} + +function getDate() { + if (exports.inspectOpts.hideDate) { + return ''; + } + return new Date().toISOString() + ' '; +} + +/** + * Invokes `util.formatWithOptions()` with the specified arguments and writes to stderr. + */ + +function log(...args) { + return process.stderr.write(util.formatWithOptions(exports.inspectOpts, ...args) + '\n'); +} + +/** + * Save `namespaces`. + * + * @param {String} namespaces + * @api private + */ +function save(namespaces) { + if (namespaces) { + process.env.DEBUG = namespaces; + } else { + // If you set a process.env field to null or undefined, it gets cast to the + // string 'null' or 'undefined'. Just delete instead. + delete process.env.DEBUG; + } +} + +/** + * Load `namespaces`. + * + * @return {String} returns the previously persisted debug modes + * @api private + */ + +function load() { + return process.env.DEBUG; +} + +/** + * Init logic for `debug` instances. + * + * Create a new `inspectOpts` object in case `useColors` is set + * differently for a particular `debug` instance. + */ + +function init(debug) { + debug.inspectOpts = {}; + + const keys = Object.keys(exports.inspectOpts); + for (let i = 0; i < keys.length; i++) { + debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]]; + } +} + +module.exports = __nccwpck_require__(8994)(exports); + +const {formatters} = module.exports; + +/** + * Map %o to `util.inspect()`, all on a single line. + */ + +formatters.o = function (v) { + this.inspectOpts.colors = this.useColors; + return util.inspect(v, this.inspectOpts) + .split('\n') + .map(str => str.trim()) + .join(' '); +}; + +/** + * Map %O to `util.inspect()`, allowing multiple lines if needed. + */ + +formatters.O = function (v) { + this.inspectOpts.colors = this.useColors; + return util.inspect(v, this.inspectOpts); +}; + + +/***/ }), + +/***/ 9877: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +var Buffer = (__nccwpck_require__(3925).Buffer); + +var getParamBytesForAlg = __nccwpck_require__(380); + +var MAX_OCTET = 0x80, + CLASS_UNIVERSAL = 0, + PRIMITIVE_BIT = 0x20, + TAG_SEQ = 0x10, + TAG_INT = 0x02, + ENCODED_TAG_SEQ = (TAG_SEQ | PRIMITIVE_BIT) | (CLASS_UNIVERSAL << 6), + ENCODED_TAG_INT = TAG_INT | (CLASS_UNIVERSAL << 6); + +function base64Url(base64) { + return base64 + .replace(/=/g, '') + .replace(/\+/g, '-') + .replace(/\//g, '_'); +} + +function signatureAsBuffer(signature) { + if (Buffer.isBuffer(signature)) { + return signature; + } else if ('string' === typeof signature) { + return Buffer.from(signature, 'base64'); + } + + throw new TypeError('ECDSA signature must be a Base64 string or a Buffer'); +} + +function derToJose(signature, alg) { + signature = signatureAsBuffer(signature); + var paramBytes = getParamBytesForAlg(alg); + + // the DER encoded param should at most be the param size, plus a padding + // zero, since due to being a signed integer + var maxEncodedParamLength = paramBytes + 1; + + var inputLength = signature.length; + + var offset = 0; + if (signature[offset++] !== ENCODED_TAG_SEQ) { + throw new Error('Could not find expected "seq"'); + } + + var seqLength = signature[offset++]; + if (seqLength === (MAX_OCTET | 1)) { + seqLength = signature[offset++]; + } + + if (inputLength - offset < seqLength) { + throw new Error('"seq" specified length of "' + seqLength + '", only "' + (inputLength - offset) + '" remaining'); + } + + if (signature[offset++] !== ENCODED_TAG_INT) { + throw new Error('Could not find expected "int" for "r"'); + } + + var rLength = signature[offset++]; + + if (inputLength - offset - 2 < rLength) { + throw new Error('"r" specified length of "' + rLength + '", only "' + (inputLength - offset - 2) + '" available'); + } + + if (maxEncodedParamLength < rLength) { + throw new Error('"r" specified length of "' + rLength + '", max of "' + maxEncodedParamLength + '" is acceptable'); + } + + var rOffset = offset; + offset += rLength; + + if (signature[offset++] !== ENCODED_TAG_INT) { + throw new Error('Could not find expected "int" for "s"'); + } + + var sLength = signature[offset++]; + + if (inputLength - offset !== sLength) { + throw new Error('"s" specified length of "' + sLength + '", expected "' + (inputLength - offset) + '"'); + } + + if (maxEncodedParamLength < sLength) { + throw new Error('"s" specified length of "' + sLength + '", max of "' + maxEncodedParamLength + '" is acceptable'); + } + + var sOffset = offset; + offset += sLength; + + if (offset !== inputLength) { + throw new Error('Expected to consume entire buffer, but "' + (inputLength - offset) + '" bytes remain'); + } + + var rPadding = paramBytes - rLength, + sPadding = paramBytes - sLength; + + var dst = Buffer.allocUnsafe(rPadding + rLength + sPadding + sLength); + + for (offset = 0; offset < rPadding; ++offset) { + dst[offset] = 0; + } + signature.copy(dst, offset, rOffset + Math.max(-rPadding, 0), rOffset + rLength); + + offset = paramBytes; + + for (var o = offset; offset < o + sPadding; ++offset) { + dst[offset] = 0; + } + signature.copy(dst, offset, sOffset + Math.max(-sPadding, 0), sOffset + sLength); + + dst = dst.toString('base64'); + dst = base64Url(dst); + + return dst; +} + +function countPadding(buf, start, stop) { + var padding = 0; + while (start + padding < stop && buf[start + padding] === 0) { + ++padding; + } + + var needsSign = buf[start + padding] >= MAX_OCTET; + if (needsSign) { + --padding; + } + + return padding; +} + +function joseToDer(signature, alg) { + signature = signatureAsBuffer(signature); + var paramBytes = getParamBytesForAlg(alg); + + var signatureBytes = signature.length; + if (signatureBytes !== paramBytes * 2) { + throw new TypeError('"' + alg + '" signatures must be "' + paramBytes * 2 + '" bytes, saw "' + signatureBytes + '"'); + } + + var rPadding = countPadding(signature, 0, paramBytes); + var sPadding = countPadding(signature, paramBytes, signature.length); + var rLength = paramBytes - rPadding; + var sLength = paramBytes - sPadding; + + var rsBytes = 1 + 1 + rLength + 1 + 1 + sLength; + + var shortLength = rsBytes < MAX_OCTET; + + var dst = Buffer.allocUnsafe((shortLength ? 2 : 3) + rsBytes); + + var offset = 0; + dst[offset++] = ENCODED_TAG_SEQ; + if (shortLength) { + // Bit 8 has value "0" + // bits 7-1 give the length. + dst[offset++] = rsBytes; + } else { + // Bit 8 of first octet has value "1" + // bits 7-1 give the number of additional length octets. + dst[offset++] = MAX_OCTET | 1; + // length, base 256 + dst[offset++] = rsBytes & 0xff; + } + dst[offset++] = ENCODED_TAG_INT; + dst[offset++] = rLength; + if (rPadding < 0) { + dst[offset++] = 0; + offset += signature.copy(dst, offset, 0, paramBytes); + } else { + offset += signature.copy(dst, offset, rPadding, paramBytes); + } + dst[offset++] = ENCODED_TAG_INT; + dst[offset++] = sLength; + if (sPadding < 0) { + dst[offset++] = 0; + signature.copy(dst, offset, paramBytes); + } else { + signature.copy(dst, offset, paramBytes + sPadding); + } + + return dst; +} + +module.exports = { + derToJose: derToJose, + joseToDer: joseToDer +}; + + +/***/ }), + +/***/ 380: +/***/ ((module) => { + +"use strict"; + + +function getParamSize(keySize) { + var result = ((keySize / 8) | 0) + (keySize % 8 === 0 ? 0 : 1); + return result; +} + +var paramBytesForAlg = { + ES256: getParamSize(256), + ES384: getParamSize(384), + ES512: getParamSize(521) +}; + +function getParamBytesForAlg(alg) { + var paramBytes = paramBytesForAlg[alg]; + if (paramBytes) { + return paramBytes; + } + + throw new Error('Unknown algorithm "' + alg + '"'); +} + +module.exports = getParamBytesForAlg; + + +/***/ }), + +/***/ 5094: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + +/* + * Encrypted content coding + * + * === Note about versions === + * + * This code supports multiple versions of the draft. This is selected using + * the |version| parameter. + * + * aes128gcm: The most recent version, the salt, record size and key identifier + * are included in a header that is part of the encrypted content coding. + * + * aesgcm: The version that is widely deployed with WebPush (as of 2016-11). + * This version is selected by default, unless you specify a |padSize| of 1. + */ + +var crypto = __nccwpck_require__(6113); + +var AES_GCM = 'aes-128-gcm'; +var PAD_SIZE = { 'aes128gcm': 1, 'aesgcm': 2 }; +var TAG_LENGTH = 16; +var KEY_LENGTH = 16; +var NONCE_LENGTH = 12; +var SHA_256_LENGTH = 32; +var MODE_ENCRYPT = 'encrypt'; +var MODE_DECRYPT = 'decrypt'; + +var keylog; +if (process.env.ECE_KEYLOG === '1') { + keylog = function(m, k) { + console.warn(m + ' [' + k.length + ']: ' + k.toString('base64url')); + return k; + }; +} else { + keylog = function(m, k) { return k; }; +} + +/* Optionally base64 decode something. */ +function decode(b) { + if (typeof b === 'string') { + return Buffer.from(b, 'base64url'); + } + return b; +} + +function HMAC_hash(key, input) { + var hmac = crypto.createHmac('sha256', key); + hmac.update(input); + return hmac.digest(); +} + +/* HKDF as defined in RFC5869, using SHA-256 */ +function HKDF_extract(salt, ikm) { + keylog('salt', salt); + keylog('ikm', ikm); + return keylog('extract', HMAC_hash(salt, ikm)); +} + +function HKDF_expand(prk, info, l) { + keylog('prk', prk); + keylog('info', info); + var output = Buffer.alloc(0); + var T = Buffer.alloc(0); + info = Buffer.from(info, 'ascii'); + var counter = 0; + var cbuf = Buffer.alloc(1); + while (output.length < l) { + cbuf.writeUIntBE(++counter, 0, 1); + T = HMAC_hash(prk, Buffer.concat([T, info, cbuf])); + output = Buffer.concat([output, T]); + } + + return keylog('expand', output.slice(0, l)); +} + +function HKDF(salt, ikm, info, len) { + return HKDF_expand(HKDF_extract(salt, ikm), info, len); +} + +function info(base, context) { + var result = Buffer.concat([ + Buffer.from('Content-Encoding: ' + base + '\0', 'ascii'), + context + ]); + keylog('info ' + base, result); + return result; +} + +function lengthPrefix(buffer) { + var b = Buffer.concat([Buffer.alloc(2), buffer]); + b.writeUIntBE(buffer.length, 0, 2); + return b; +} + +function extractDH(header, mode) { + var key = header.privateKey; + var senderPubKey, receiverPubKey; + if (mode === MODE_ENCRYPT) { + senderPubKey = key.getPublicKey(); + receiverPubKey = header.dh; + } else if (mode === MODE_DECRYPT) { + senderPubKey = header.dh; + receiverPubKey = key.getPublicKey(); + } else { + throw new Error('Unknown mode only ' + MODE_ENCRYPT + + ' and ' + MODE_DECRYPT + ' supported'); + } + return { + secret: key.computeSecret(header.dh), + context: Buffer.concat([ + Buffer.from(header.keylabel, 'ascii'), + Buffer.from([0]), + lengthPrefix(receiverPubKey), // user agent + lengthPrefix(senderPubKey) // application server + ]) + }; +} + +function extractSecretAndContext(header, mode) { + var result = { secret: null, context: Buffer.alloc(0) }; + if (header.key) { + result.secret = header.key; + if (result.secret.length !== KEY_LENGTH) { + throw new Error('An explicit key must be ' + KEY_LENGTH + ' bytes'); + } + } else if (header.dh) { // receiver/decrypt + result = extractDH(header, mode); + } else if (typeof header.keyid !== undefined) { + result.secret = header.keymap[header.keyid]; + } + if (!result.secret) { + throw new Error('Unable to determine key'); + } + keylog('secret', result.secret); + keylog('context', result.context); + if (header.authSecret) { + result.secret = HKDF(header.authSecret, result.secret, + info('auth', Buffer.alloc(0)), SHA_256_LENGTH); + keylog('authsecret', result.secret); + } + return result; +} + +function webpushSecret(header, mode) { + if (!header.authSecret) { + throw new Error('No authentication secret for webpush'); + } + keylog('authsecret', header.authSecret); + + var remotePubKey, senderPubKey, receiverPubKey; + if (mode === MODE_ENCRYPT) { + senderPubKey = header.privateKey.getPublicKey(); + remotePubKey = receiverPubKey = header.dh; + } else if (mode === MODE_DECRYPT) { + remotePubKey = senderPubKey = header.keyid; + receiverPubKey = header.privateKey.getPublicKey(); + } else { + throw new Error('Unknown mode only ' + MODE_ENCRYPT + + ' and ' + MODE_DECRYPT + ' supported'); + } + keylog('remote pubkey', remotePubKey); + keylog('sender pubkey', senderPubKey); + keylog('receiver pubkey', receiverPubKey); + return keylog('secret dh', + HKDF(header.authSecret, + header.privateKey.computeSecret(remotePubKey), + Buffer.concat([ + Buffer.from('WebPush: info\0'), + receiverPubKey, + senderPubKey + ]), + SHA_256_LENGTH)); +} + +function extractSecret(header, mode, keyLookupCallback) { + if (keyLookupCallback) { + if (!isFunction(keyLookupCallback)) { + throw new Error('Callback is not a function') + } + } + + if (header.key) { + if (header.key.length !== KEY_LENGTH) { + throw new Error('An explicit key must be ' + KEY_LENGTH + ' bytes'); + } + return keylog('secret key', header.key); + } + + if (!header.privateKey) { + // Lookup based on keyid + if (!keyLookupCallback) { + var key = header.keymap && header.keymap[header.keyid]; + } else { + var key = keyLookupCallback(header.keyid) + } + if (!key) { + throw new Error('No saved key (keyid: "' + header.keyid + '")'); + } + return key; + } + + return webpushSecret(header, mode); +} + +function deriveKeyAndNonce(header, mode, lookupKeyCallback) { + if (!header.salt) { + throw new Error('must include a salt parameter for ' + header.version); + } + var keyInfo; + var nonceInfo; + var secret; + if (header.version === 'aesgcm') { + // old + var s = extractSecretAndContext(header, mode, lookupKeyCallback); + keyInfo = info('aesgcm', s.context); + nonceInfo = info('nonce', s.context); + secret = s.secret; + } else if (header.version === 'aes128gcm') { + // latest + keyInfo = Buffer.from('Content-Encoding: aes128gcm\0'); + nonceInfo = Buffer.from('Content-Encoding: nonce\0'); + secret = extractSecret(header, mode, lookupKeyCallback); + } else { + throw new Error('Unable to set context for mode ' + header.version); + } + var prk = HKDF_extract(header.salt, secret); + var result = { + key: HKDF_expand(prk, keyInfo, KEY_LENGTH), + nonce: HKDF_expand(prk, nonceInfo, NONCE_LENGTH) + }; + keylog('key', result.key); + keylog('nonce base', result.nonce); + return result; +} + +/* Parse command-line arguments. */ +function parseParams(params) { + var header = {}; + + header.version = params.version || 'aes128gcm'; + header.rs = parseInt(params.rs, 10); + if (isNaN(header.rs)) { + header.rs = 4096; + } + var overhead = PAD_SIZE[header.version]; + if (header.version === 'aes128gcm') { + overhead += TAG_LENGTH; + } + if (header.rs <= overhead) { + throw new Error('The rs parameter has to be greater than ' + overhead); + } + + if (params.salt) { + header.salt = decode(params.salt); + if (header.salt.length !== KEY_LENGTH) { + throw new Error('The salt parameter must be ' + KEY_LENGTH + ' bytes'); + } + } + header.keyid = params.keyid; + if (params.key) { + header.key = decode(params.key); + } else { + header.privateKey = params.privateKey; + if (!header.privateKey) { + header.keymap = params.keymap; + } + if (header.version !== 'aes128gcm') { + header.keylabel = params.keylabel || 'P-256'; + } + if (params.dh) { + header.dh = decode(params.dh); + } + } + if (params.authSecret) { + header.authSecret = decode(params.authSecret); + } + return header; +} + +function generateNonce(base, counter) { + var nonce = Buffer.from(base); + var m = nonce.readUIntBE(nonce.length - 6, 6); + var x = ((m ^ counter) & 0xffffff) + + ((((m / 0x1000000) ^ (counter / 0x1000000)) & 0xffffff) * 0x1000000); + nonce.writeUIntBE(x, nonce.length - 6, 6); + keylog('nonce' + counter, nonce); + return nonce; +} + +/* Used when decrypting aes128gcm to populate the header values. Modifies the + * header values in place and returns the size of the header. */ +function readHeader(buffer, header) { + var idsz = buffer.readUIntBE(20, 1); + header.salt = buffer.slice(0, KEY_LENGTH); + header.rs = buffer.readUIntBE(KEY_LENGTH, 4); + header.keyid = buffer.slice(21, 21 + idsz); + return 21 + idsz; +} + +function unpadLegacy(data, version) { + var padSize = PAD_SIZE[version]; + var pad = data.readUIntBE(0, padSize); + if (pad + padSize > data.length) { + throw new Error('padding exceeds block size'); + } + keylog('padding', data.slice(0, padSize + pad)); + var padCheck = Buffer.alloc(pad); + padCheck.fill(0); + if (padCheck.compare(data.slice(padSize, padSize + pad)) !== 0) { + throw new Error('invalid padding'); + } + return data.slice(padSize + pad); +} + +function unpad(data, last) { + var i = data.length - 1; + while(i >= 0) { + if (data[i]) { + if (last) { + if (data[i] !== 2) { + throw new Error('last record needs to start padding with a 2'); + } + } else { + if (data[i] !== 1) { + throw new Error('last record needs to start padding with a 2'); + } + } + return data.slice(0, i); + } + --i; + } + throw new Error('all zero plaintext'); +} + +function decryptRecord(key, counter, buffer, header, last) { + keylog('decrypt', buffer); + var nonce = generateNonce(key.nonce, counter); + var gcm = crypto.createDecipheriv(AES_GCM, key.key, nonce); + gcm.setAuthTag(buffer.slice(buffer.length - TAG_LENGTH)); + var data = gcm.update(buffer.slice(0, buffer.length - TAG_LENGTH)); + data = Buffer.concat([data, gcm.final()]); + keylog('decrypted', data); + if (header.version !== 'aes128gcm') { + return unpadLegacy(data, header.version); + } + return unpad(data, last); +} + +/** + * Decrypt some bytes. This uses the parameters to determine the key and block + * size, which are described in the draft. Binary values are base64url encoded. + * + * |params.version| contains the version of encoding to use: aes128gcm is the latest, + * but aesgcm is also accepted (though the latter might + * disappear in a future release). If omitted, assume aes128gcm. + * + * If |params.key| is specified, that value is used as the key. + * + * If the version is aes128gcm, the keyid is extracted from the header and used + * as the ECDH public key of the sender. For version aesgcm , + * |params.dh| needs to be provided with the public key of the sender. + * + * The |params.privateKey| includes the private key of the receiver. + */ +function decrypt(buffer, params, keyLookupCallback) { + var header = parseParams(params); + if (header.version === 'aes128gcm') { + var headerLength = readHeader(buffer, header); + buffer = buffer.slice(headerLength); + } + var key = deriveKeyAndNonce(header, MODE_DECRYPT, keyLookupCallback); + var start = 0; + var result = Buffer.alloc(0); + + var chunkSize = header.rs; + if (header.version !== 'aes128gcm') { + chunkSize += TAG_LENGTH; + } + + for (var i = 0; start < buffer.length; ++i) { + var end = start + chunkSize; + if (header.version !== 'aes128gcm' && end === buffer.length) { + throw new Error('Truncated payload'); + } + end = Math.min(end, buffer.length); + if (end - start <= TAG_LENGTH) { + throw new Error('Invalid block: too small at ' + i); + } + var block = decryptRecord(key, i, buffer.slice(start, end), + header, end >= buffer.length); + result = Buffer.concat([result, block]); + start = end; + } + return result; +} + +function encryptRecord(key, counter, buffer, pad, header, last) { + keylog('encrypt', buffer); + pad = pad || 0; + var nonce = generateNonce(key.nonce, counter); + var gcm = crypto.createCipheriv(AES_GCM, key.key, nonce); + + var ciphertext = []; + var padSize = PAD_SIZE[header.version]; + var padding = Buffer.alloc(pad + padSize); + padding.fill(0); + + if (header.version !== 'aes128gcm') { + padding.writeUIntBE(pad, 0, padSize); + keylog('padding', padding); + ciphertext.push(gcm.update(padding)); + ciphertext.push(gcm.update(buffer)); + + if (!last && padding.length + buffer.length < header.rs) { + throw new Error('Unable to pad to record size'); + } + } else { + ciphertext.push(gcm.update(buffer)); + padding.writeUIntBE(last ? 2 : 1, 0, 1); + keylog('padding', padding); + ciphertext.push(gcm.update(padding)); + } + + gcm.final(); + var tag = gcm.getAuthTag(); + if (tag.length !== TAG_LENGTH) { + throw new Error('invalid tag generated'); + } + ciphertext.push(tag); + return keylog('encrypted', Buffer.concat(ciphertext)); +} + +function writeHeader(header) { + var ints = Buffer.alloc(5); + var keyid = Buffer.from(header.keyid || []); + if (keyid.length > 255) { + throw new Error('keyid is too large'); + } + ints.writeUIntBE(header.rs, 0, 4); + ints.writeUIntBE(keyid.length, 4, 1); + return Buffer.concat([header.salt, ints, keyid]); +} + +/** + * Encrypt some bytes. This uses the parameters to determine the key and block + * size, which are described in the draft. + * + * |params.version| contains the version of encoding to use: aes128gcm is the latest, + * but aesgcm is also accepted (though the latter two might + * disappear in a future release). If omitted, assume aes128gcm. + * + * If |params.key| is specified, that value is used as the key. + * + * For Diffie-Hellman (WebPush), |params.dh| includes the public key of the + * receiver. |params.privateKey| is used to establish a shared secret. Key + * pairs can be created using |crypto.createECDH()|. + */ +function encrypt(buffer, params, keyLookupCallback) { + if (!Buffer.isBuffer(buffer)) { + throw new Error('buffer argument must be a Buffer'); + } + var header = parseParams(params); + if (!header.salt) { + header.salt = crypto.randomBytes(KEY_LENGTH); + } + + var result; + if (header.version === 'aes128gcm') { + // Save the DH public key in the header unless keyid is set. + if (header.privateKey && !header.keyid) { + header.keyid = header.privateKey.getPublicKey(); + } + result = writeHeader(header); + } else { + // No header on other versions + result = Buffer.alloc(0); + } + + var key = deriveKeyAndNonce(header, MODE_ENCRYPT, keyLookupCallback); + var start = 0; + var padSize = PAD_SIZE[header.version]; + var overhead = padSize; + if (header.version === 'aes128gcm') { + overhead += TAG_LENGTH; + } + var pad = isNaN(parseInt(params.pad, 10)) ? 0 : parseInt(params.pad, 10); + + var counter = 0; + var last = false; + while (!last) { + // Pad so that at least one data byte is in a block. + var recordPad = Math.min(header.rs - overhead - 1, pad); + if (header.version !== 'aes128gcm') { + recordPad = Math.min((1 << (padSize * 8)) - 1, recordPad); + } + if (pad > 0 && recordPad === 0) { + ++recordPad; // Deal with perverse case of rs=overhead+1 with padding. + } + pad -= recordPad; + + var end = start + header.rs - overhead - recordPad; + if (header.version !== 'aes128gcm') { + // The > here ensures that we write out a padding-only block at the end + // of a buffer. + last = end > buffer.length; + } else { + last = end >= buffer.length; + } + last = last && pad <= 0; + var block = encryptRecord(key, counter, buffer.slice(start, end), + recordPad, header, last); + result = Buffer.concat([result, block]); + + start = end; + ++counter; + } + return result; +} + + +function isFunction(object) { + return typeof(object) === 'function'; + } + +module.exports = { + decrypt: decrypt, + encrypt: encrypt +}; + + +/***/ }), + +/***/ 9521: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + +"use strict"; + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.HttpsProxyAgent = void 0; +const net = __importStar(__nccwpck_require__(1808)); +const tls = __importStar(__nccwpck_require__(4404)); +const assert_1 = __importDefault(__nccwpck_require__(9491)); +const debug_1 = __importDefault(__nccwpck_require__(5062)); +const agent_base_1 = __nccwpck_require__(7111); +const url_1 = __nccwpck_require__(7310); +const parse_proxy_response_1 = __nccwpck_require__(4325); +const debug = (0, debug_1.default)('https-proxy-agent'); +/** + * The `HttpsProxyAgent` implements an HTTP Agent subclass that connects to + * the specified "HTTP(s) proxy server" in order to proxy HTTPS requests. + * + * Outgoing HTTP requests are first tunneled through the proxy server using the + * `CONNECT` HTTP request method to establish a connection to the proxy server, + * and then the proxy server connects to the destination target and issues the + * HTTP request from the proxy server. + * + * `https:` requests have their socket connection upgraded to TLS once + * the connection to the proxy server has been established. + */ +class HttpsProxyAgent extends agent_base_1.Agent { + constructor(proxy, opts) { + super(opts); + this.options = { path: undefined }; + this.proxy = typeof proxy === 'string' ? new url_1.URL(proxy) : proxy; + this.proxyHeaders = opts?.headers ?? {}; + debug('Creating new HttpsProxyAgent instance: %o', this.proxy.href); + // Trim off the brackets from IPv6 addresses + const host = (this.proxy.hostname || this.proxy.host).replace(/^\[|\]$/g, ''); + const port = this.proxy.port + ? parseInt(this.proxy.port, 10) + : this.proxy.protocol === 'https:' + ? 443 + : 80; + this.connectOpts = { + // Attempt to negotiate http/1.1 for proxy servers that support http/2 + ALPNProtocols: ['http/1.1'], + ...(opts ? omit(opts, 'headers') : null), + host, + port, + }; + } + /** + * Called when the node-core HTTP client library is creating a + * new HTTP request. + */ + async connect(req, opts) { + const { proxy } = this; + if (!opts.host) { + throw new TypeError('No "host" provided'); + } + // Create a socket connection to the proxy server. + let socket; + if (proxy.protocol === 'https:') { + debug('Creating `tls.Socket`: %o', this.connectOpts); + const servername = this.connectOpts.servername || this.connectOpts.host; + socket = tls.connect({ + ...this.connectOpts, + servername, + }); + } + else { + debug('Creating `net.Socket`: %o', this.connectOpts); + socket = net.connect(this.connectOpts); + } + const headers = typeof this.proxyHeaders === 'function' + ? this.proxyHeaders() + : { ...this.proxyHeaders }; + const host = net.isIPv6(opts.host) ? `[${opts.host}]` : opts.host; + let payload = `CONNECT ${host}:${opts.port} HTTP/1.1\r\n`; + // Inject the `Proxy-Authorization` header if necessary. + if (proxy.username || proxy.password) { + const auth = `${decodeURIComponent(proxy.username)}:${decodeURIComponent(proxy.password)}`; + headers['Proxy-Authorization'] = `Basic ${Buffer.from(auth).toString('base64')}`; + } + headers.Host = `${host}:${opts.port}`; + if (!headers['Proxy-Connection']) { + headers['Proxy-Connection'] = this.keepAlive + ? 'Keep-Alive' + : 'close'; + } + for (const name of Object.keys(headers)) { + payload += `${name}: ${headers[name]}\r\n`; + } + const proxyResponsePromise = (0, parse_proxy_response_1.parseProxyResponse)(socket); + socket.write(`${payload}\r\n`); + const { connect, buffered } = await proxyResponsePromise; + req.emit('proxyConnect', connect); + this.emit('proxyConnect', connect, req); + if (connect.statusCode === 200) { + req.once('socket', resume); + if (opts.secureEndpoint) { + // The proxy is connecting to a TLS server, so upgrade + // this socket connection to a TLS connection. + debug('Upgrading socket connection to TLS'); + const servername = opts.servername || opts.host; + return tls.connect({ + ...omit(opts, 'host', 'path', 'port'), + socket, + servername, + }); + } + return socket; + } + // Some other status code that's not 200... need to re-play the HTTP + // header "data" events onto the socket once the HTTP machinery is + // attached so that the node core `http` can parse and handle the + // error status code. + // Close the original socket, and a new "fake" socket is returned + // instead, so that the proxy doesn't get the HTTP request + // written to it (which may contain `Authorization` headers or other + // sensitive data). + // + // See: https://hackerone.com/reports/541502 + socket.destroy(); + const fakeSocket = new net.Socket({ writable: false }); + fakeSocket.readable = true; + // Need to wait for the "socket" event to re-play the "data" events. + req.once('socket', (s) => { + debug('Replaying proxy buffer for failed request'); + (0, assert_1.default)(s.listenerCount('data') > 0); + // Replay the "buffered" Buffer onto the fake `socket`, since at + // this point the HTTP module machinery has been hooked up for + // the user. + s.push(buffered); + s.push(null); + }); + return fakeSocket; + } +} +HttpsProxyAgent.protocols = ['http', 'https']; +exports.HttpsProxyAgent = HttpsProxyAgent; +function resume(socket) { + socket.resume(); +} +function omit(obj, ...keys) { + const ret = {}; + let key; + for (key in obj) { + if (!keys.includes(key)) { + ret[key] = obj[key]; + } + } + return ret; +} +//# sourceMappingURL=index.js.map + +/***/ }), + +/***/ 4325: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + +"use strict"; + +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.parseProxyResponse = void 0; +const debug_1 = __importDefault(__nccwpck_require__(5062)); +const debug = (0, debug_1.default)('https-proxy-agent:parse-proxy-response'); +function parseProxyResponse(socket) { + return new Promise((resolve, reject) => { + // we need to buffer any HTTP traffic that happens with the proxy before we get + // the CONNECT response, so that if the response is anything other than an "200" + // response code, then we can re-play the "data" events on the socket once the + // HTTP parser is hooked up... + let buffersLength = 0; + const buffers = []; + function read() { + const b = socket.read(); + if (b) + ondata(b); + else + socket.once('readable', read); + } + function cleanup() { + socket.removeListener('end', onend); + socket.removeListener('error', onerror); + socket.removeListener('readable', read); + } + function onend() { + cleanup(); + debug('onend'); + reject(new Error('Proxy connection ended before receiving CONNECT response')); + } + function onerror(err) { + cleanup(); + debug('onerror %o', err); + reject(err); + } + function ondata(b) { + buffers.push(b); + buffersLength += b.length; + const buffered = Buffer.concat(buffers, buffersLength); + const endOfHeaders = buffered.indexOf('\r\n\r\n'); + if (endOfHeaders === -1) { + // keep buffering + debug('have not received end of HTTP headers yet...'); + read(); + return; + } + const headerParts = buffered + .slice(0, endOfHeaders) + .toString('ascii') + .split('\r\n'); + const firstLine = headerParts.shift(); + if (!firstLine) { + socket.destroy(); + return reject(new Error('No header received from proxy CONNECT response')); + } + const firstLineParts = firstLine.split(' '); + const statusCode = +firstLineParts[1]; + const statusText = firstLineParts.slice(2).join(' '); + const headers = {}; + for (const header of headerParts) { + if (!header) + continue; + const firstColon = header.indexOf(':'); + if (firstColon === -1) { + socket.destroy(); + return reject(new Error(`Invalid header from proxy CONNECT response: "${header}"`)); + } + const key = header.slice(0, firstColon).toLowerCase(); + const value = header.slice(firstColon + 1).trimStart(); + const current = headers[key]; + if (typeof current === 'string') { + headers[key] = [current, value]; + } + else if (Array.isArray(current)) { + current.push(value); + } + else { + headers[key] = value; + } + } + debug('got proxy server response: %o %o', firstLine, headers); + cleanup(); + resolve({ + connect: { + statusCode, + statusText, + headers, + }, + buffered, + }); + } + socket.on('error', onerror); + socket.on('end', onend); + read(); + }); +} +exports.parseProxyResponse = parseProxyResponse; +//# sourceMappingURL=parse-proxy-response.js.map + +/***/ }), + +/***/ 9581: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +try { + var util = __nccwpck_require__(3837); + /* istanbul ignore next */ + if (typeof util.inherits !== 'function') throw ''; + module.exports = util.inherits; +} catch (e) { + /* istanbul ignore next */ + module.exports = __nccwpck_require__(4345); +} + + +/***/ }), + +/***/ 4345: +/***/ ((module) => { + +if (typeof Object.create === 'function') { + // implementation from standard node.js 'util' module + module.exports = function inherits(ctor, superCtor) { + if (superCtor) { + ctor.super_ = superCtor + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } + }) + } + }; +} else { + // old school shim for old browsers + module.exports = function inherits(ctor, superCtor) { + if (superCtor) { + ctor.super_ = superCtor + var TempCtor = function () {} + TempCtor.prototype = superCtor.prototype + ctor.prototype = new TempCtor() + ctor.prototype.constructor = ctor + } + } +} + + +/***/ }), + +/***/ 3069: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +var bufferEqual = __nccwpck_require__(7457); +var Buffer = (__nccwpck_require__(3925).Buffer); +var crypto = __nccwpck_require__(6113); +var formatEcdsa = __nccwpck_require__(9877); +var util = __nccwpck_require__(3837); + +var MSG_INVALID_ALGORITHM = '"%s" is not a valid algorithm.\n Supported algorithms are:\n "HS256", "HS384", "HS512", "RS256", "RS384", "RS512", "PS256", "PS384", "PS512", "ES256", "ES384", "ES512" and "none".' +var MSG_INVALID_SECRET = 'secret must be a string or buffer'; +var MSG_INVALID_VERIFIER_KEY = 'key must be a string or a buffer'; +var MSG_INVALID_SIGNER_KEY = 'key must be a string, a buffer or an object'; + +var supportsKeyObjects = typeof crypto.createPublicKey === 'function'; +if (supportsKeyObjects) { + MSG_INVALID_VERIFIER_KEY += ' or a KeyObject'; + MSG_INVALID_SECRET += 'or a KeyObject'; +} + +function checkIsPublicKey(key) { + if (Buffer.isBuffer(key)) { + return; + } + + if (typeof key === 'string') { + return; + } + + if (!supportsKeyObjects) { + throw typeError(MSG_INVALID_VERIFIER_KEY); + } + + if (typeof key !== 'object') { + throw typeError(MSG_INVALID_VERIFIER_KEY); + } + + if (typeof key.type !== 'string') { + throw typeError(MSG_INVALID_VERIFIER_KEY); + } + + if (typeof key.asymmetricKeyType !== 'string') { + throw typeError(MSG_INVALID_VERIFIER_KEY); + } + + if (typeof key.export !== 'function') { + throw typeError(MSG_INVALID_VERIFIER_KEY); + } +}; + +function checkIsPrivateKey(key) { + if (Buffer.isBuffer(key)) { + return; + } + + if (typeof key === 'string') { + return; + } + + if (typeof key === 'object') { + return; + } + + throw typeError(MSG_INVALID_SIGNER_KEY); +}; + +function checkIsSecretKey(key) { + if (Buffer.isBuffer(key)) { + return; + } + + if (typeof key === 'string') { + return key; + } + + if (!supportsKeyObjects) { + throw typeError(MSG_INVALID_SECRET); + } + + if (typeof key !== 'object') { + throw typeError(MSG_INVALID_SECRET); + } + + if (key.type !== 'secret') { + throw typeError(MSG_INVALID_SECRET); + } + + if (typeof key.export !== 'function') { + throw typeError(MSG_INVALID_SECRET); + } +} + +function fromBase64(base64) { + return base64 + .replace(/=/g, '') + .replace(/\+/g, '-') + .replace(/\//g, '_'); +} + +function toBase64(base64url) { + base64url = base64url.toString(); + + var padding = 4 - base64url.length % 4; + if (padding !== 4) { + for (var i = 0; i < padding; ++i) { + base64url += '='; + } + } + + return base64url + .replace(/\-/g, '+') + .replace(/_/g, '/'); +} + +function typeError(template) { + var args = [].slice.call(arguments, 1); + var errMsg = util.format.bind(util, template).apply(null, args); + return new TypeError(errMsg); +} + +function bufferOrString(obj) { + return Buffer.isBuffer(obj) || typeof obj === 'string'; +} + +function normalizeInput(thing) { + if (!bufferOrString(thing)) + thing = JSON.stringify(thing); + return thing; +} + +function createHmacSigner(bits) { + return function sign(thing, secret) { + checkIsSecretKey(secret); + thing = normalizeInput(thing); + var hmac = crypto.createHmac('sha' + bits, secret); + var sig = (hmac.update(thing), hmac.digest('base64')) + return fromBase64(sig); + } +} + +function createHmacVerifier(bits) { + return function verify(thing, signature, secret) { + var computedSig = createHmacSigner(bits)(thing, secret); + return bufferEqual(Buffer.from(signature), Buffer.from(computedSig)); + } +} + +function createKeySigner(bits) { + return function sign(thing, privateKey) { + checkIsPrivateKey(privateKey); + thing = normalizeInput(thing); + // Even though we are specifying "RSA" here, this works with ECDSA + // keys as well. + var signer = crypto.createSign('RSA-SHA' + bits); + var sig = (signer.update(thing), signer.sign(privateKey, 'base64')); + return fromBase64(sig); + } +} + +function createKeyVerifier(bits) { + return function verify(thing, signature, publicKey) { + checkIsPublicKey(publicKey); + thing = normalizeInput(thing); + signature = toBase64(signature); + var verifier = crypto.createVerify('RSA-SHA' + bits); + verifier.update(thing); + return verifier.verify(publicKey, signature, 'base64'); + } +} + +function createPSSKeySigner(bits) { + return function sign(thing, privateKey) { + checkIsPrivateKey(privateKey); + thing = normalizeInput(thing); + var signer = crypto.createSign('RSA-SHA' + bits); + var sig = (signer.update(thing), signer.sign({ + key: privateKey, + padding: crypto.constants.RSA_PKCS1_PSS_PADDING, + saltLength: crypto.constants.RSA_PSS_SALTLEN_DIGEST + }, 'base64')); + return fromBase64(sig); + } +} + +function createPSSKeyVerifier(bits) { + return function verify(thing, signature, publicKey) { + checkIsPublicKey(publicKey); + thing = normalizeInput(thing); + signature = toBase64(signature); + var verifier = crypto.createVerify('RSA-SHA' + bits); + verifier.update(thing); + return verifier.verify({ + key: publicKey, + padding: crypto.constants.RSA_PKCS1_PSS_PADDING, + saltLength: crypto.constants.RSA_PSS_SALTLEN_DIGEST + }, signature, 'base64'); + } +} + +function createECDSASigner(bits) { + var inner = createKeySigner(bits); + return function sign() { + var signature = inner.apply(null, arguments); + signature = formatEcdsa.derToJose(signature, 'ES' + bits); + return signature; + }; +} + +function createECDSAVerifer(bits) { + var inner = createKeyVerifier(bits); + return function verify(thing, signature, publicKey) { + signature = formatEcdsa.joseToDer(signature, 'ES' + bits).toString('base64'); + var result = inner(thing, signature, publicKey); + return result; + }; +} + +function createNoneSigner() { + return function sign() { + return ''; + } +} + +function createNoneVerifier() { + return function verify(thing, signature) { + return signature === ''; + } +} + +module.exports = function jwa(algorithm) { + var signerFactories = { + hs: createHmacSigner, + rs: createKeySigner, + ps: createPSSKeySigner, + es: createECDSASigner, + none: createNoneSigner, + } + var verifierFactories = { + hs: createHmacVerifier, + rs: createKeyVerifier, + ps: createPSSKeyVerifier, + es: createECDSAVerifer, + none: createNoneVerifier, + } + var match = algorithm.match(/^(RS|PS|ES|HS)(256|384|512)$|^(none)$/); + if (!match) + throw typeError(MSG_INVALID_ALGORITHM, algorithm); + var algo = (match[1] || match[3]).toLowerCase(); + var bits = match[2]; + + return { + sign: signerFactories[algo](bits), + verify: verifierFactories[algo](bits), + } +}; + + +/***/ }), + +/***/ 7507: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +/*global exports*/ +var SignStream = __nccwpck_require__(3642); +var VerifyStream = __nccwpck_require__(6099); + +var ALGORITHMS = [ + 'HS256', 'HS384', 'HS512', + 'RS256', 'RS384', 'RS512', + 'PS256', 'PS384', 'PS512', + 'ES256', 'ES384', 'ES512' +]; + +exports.ALGORITHMS = ALGORITHMS; +exports.sign = SignStream.sign; +exports.verify = VerifyStream.verify; +exports.decode = VerifyStream.decode; +exports.isValid = VerifyStream.isValid; +exports.createSign = function createSign(opts) { + return new SignStream(opts); +}; +exports.createVerify = function createVerify(opts) { + return new VerifyStream(opts); +}; + + +/***/ }), + +/***/ 8621: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +/*global module, process*/ +var Buffer = (__nccwpck_require__(3925).Buffer); +var Stream = __nccwpck_require__(2781); +var util = __nccwpck_require__(3837); + +function DataStream(data) { + this.buffer = null; + this.writable = true; + this.readable = true; + + // No input + if (!data) { + this.buffer = Buffer.alloc(0); + return this; + } + + // Stream + if (typeof data.pipe === 'function') { + this.buffer = Buffer.alloc(0); + data.pipe(this); + return this; + } + + // Buffer or String + // or Object (assumedly a passworded key) + if (data.length || typeof data === 'object') { + this.buffer = data; + this.writable = false; + process.nextTick(function () { + this.emit('end', data); + this.readable = false; + this.emit('close'); + }.bind(this)); + return this; + } + + throw new TypeError('Unexpected data type ('+ typeof data + ')'); +} +util.inherits(DataStream, Stream); + +DataStream.prototype.write = function write(data) { + this.buffer = Buffer.concat([this.buffer, Buffer.from(data)]); + this.emit('data', data); +}; + +DataStream.prototype.end = function end(data) { + if (data) + this.write(data); + this.emit('end', data); + this.emit('close'); + this.writable = false; + this.readable = false; +}; + +module.exports = DataStream; + + +/***/ }), + +/***/ 3642: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +/*global module*/ +var Buffer = (__nccwpck_require__(3925).Buffer); +var DataStream = __nccwpck_require__(8621); +var jwa = __nccwpck_require__(3069); +var Stream = __nccwpck_require__(2781); +var toString = __nccwpck_require__(5591); +var util = __nccwpck_require__(3837); + +function base64url(string, encoding) { + return Buffer + .from(string, encoding) + .toString('base64') + .replace(/=/g, '') + .replace(/\+/g, '-') + .replace(/\//g, '_'); +} + +function jwsSecuredInput(header, payload, encoding) { + encoding = encoding || 'utf8'; + var encodedHeader = base64url(toString(header), 'binary'); + var encodedPayload = base64url(toString(payload), encoding); + return util.format('%s.%s', encodedHeader, encodedPayload); +} + +function jwsSign(opts) { + var header = opts.header; + var payload = opts.payload; + var secretOrKey = opts.secret || opts.privateKey; + var encoding = opts.encoding; + var algo = jwa(header.alg); + var securedInput = jwsSecuredInput(header, payload, encoding); + var signature = algo.sign(securedInput, secretOrKey); + return util.format('%s.%s', securedInput, signature); +} + +function SignStream(opts) { + var secret = opts.secret||opts.privateKey||opts.key; + var secretStream = new DataStream(secret); + this.readable = true; + this.header = opts.header; + this.encoding = opts.encoding; + this.secret = this.privateKey = this.key = secretStream; + this.payload = new DataStream(opts.payload); + this.secret.once('close', function () { + if (!this.payload.writable && this.readable) + this.sign(); + }.bind(this)); + + this.payload.once('close', function () { + if (!this.secret.writable && this.readable) + this.sign(); + }.bind(this)); +} +util.inherits(SignStream, Stream); + +SignStream.prototype.sign = function sign() { + try { + var signature = jwsSign({ + header: this.header, + payload: this.payload.buffer, + secret: this.secret.buffer, + encoding: this.encoding + }); + this.emit('done', signature); + this.emit('data', signature); + this.emit('end'); + this.readable = false; + return signature; + } catch (e) { + this.readable = false; + this.emit('error', e); + this.emit('close'); + } +}; + +SignStream.sign = jwsSign; + +module.exports = SignStream; + + +/***/ }), + +/***/ 5591: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +/*global module*/ +var Buffer = (__nccwpck_require__(4300).Buffer); + +module.exports = function toString(obj) { + if (typeof obj === 'string') + return obj; + if (typeof obj === 'number' || Buffer.isBuffer(obj)) + return obj.toString(); + return JSON.stringify(obj); +}; + + +/***/ }), + +/***/ 6099: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +/*global module*/ +var Buffer = (__nccwpck_require__(3925).Buffer); +var DataStream = __nccwpck_require__(8621); +var jwa = __nccwpck_require__(3069); +var Stream = __nccwpck_require__(2781); +var toString = __nccwpck_require__(5591); +var util = __nccwpck_require__(3837); +var JWS_REGEX = /^[a-zA-Z0-9\-_]+?\.[a-zA-Z0-9\-_]+?\.([a-zA-Z0-9\-_]+)?$/; + +function isObject(thing) { + return Object.prototype.toString.call(thing) === '[object Object]'; +} + +function safeJsonParse(thing) { + if (isObject(thing)) + return thing; + try { return JSON.parse(thing); } + catch (e) { return undefined; } +} + +function headerFromJWS(jwsSig) { + var encodedHeader = jwsSig.split('.', 1)[0]; + return safeJsonParse(Buffer.from(encodedHeader, 'base64').toString('binary')); +} + +function securedInputFromJWS(jwsSig) { + return jwsSig.split('.', 2).join('.'); +} + +function signatureFromJWS(jwsSig) { + return jwsSig.split('.')[2]; +} + +function payloadFromJWS(jwsSig, encoding) { + encoding = encoding || 'utf8'; + var payload = jwsSig.split('.')[1]; + return Buffer.from(payload, 'base64').toString(encoding); +} + +function isValidJws(string) { + return JWS_REGEX.test(string) && !!headerFromJWS(string); +} + +function jwsVerify(jwsSig, algorithm, secretOrKey) { + if (!algorithm) { + var err = new Error("Missing algorithm parameter for jws.verify"); + err.code = "MISSING_ALGORITHM"; + throw err; + } + jwsSig = toString(jwsSig); + var signature = signatureFromJWS(jwsSig); + var securedInput = securedInputFromJWS(jwsSig); + var algo = jwa(algorithm); + return algo.verify(securedInput, signature, secretOrKey); +} + +function jwsDecode(jwsSig, opts) { + opts = opts || {}; + jwsSig = toString(jwsSig); + + if (!isValidJws(jwsSig)) + return null; + + var header = headerFromJWS(jwsSig); + + if (!header) + return null; + + var payload = payloadFromJWS(jwsSig); + if (header.typ === 'JWT' || opts.json) + payload = JSON.parse(payload, opts.encoding); + + return { + header: header, + payload: payload, + signature: signatureFromJWS(jwsSig) + }; +} + +function VerifyStream(opts) { + opts = opts || {}; + var secretOrKey = opts.secret||opts.publicKey||opts.key; + var secretStream = new DataStream(secretOrKey); + this.readable = true; + this.algorithm = opts.algorithm; + this.encoding = opts.encoding; + this.secret = this.publicKey = this.key = secretStream; + this.signature = new DataStream(opts.signature); + this.secret.once('close', function () { + if (!this.signature.writable && this.readable) + this.verify(); + }.bind(this)); + + this.signature.once('close', function () { + if (!this.secret.writable && this.readable) + this.verify(); + }.bind(this)); +} +util.inherits(VerifyStream, Stream); +VerifyStream.prototype.verify = function verify() { + try { + var valid = jwsVerify(this.signature.buffer, this.algorithm, this.key.buffer); + var obj = jwsDecode(this.signature.buffer, this.encoding); + this.emit('done', valid, obj); + this.emit('data', valid); + this.emit('end'); + this.readable = false; + return valid; + } catch (e) { + this.readable = false; + this.emit('error', e); + this.emit('close'); + } +}; + +VerifyStream.decode = jwsDecode; +VerifyStream.isValid = isValidJws; +VerifyStream.verify = jwsVerify; + +module.exports = VerifyStream; + + +/***/ }), + +/***/ 2104: +/***/ ((module) => { + +module.exports = assert; + +function assert(val, msg) { + if (!val) + throw new Error(msg || 'Assertion failed'); +} + +assert.equal = function assertEqual(l, r, msg) { + if (l != r) + throw new Error(msg || ('Assertion failed: ' + l + ' != ' + r)); +}; + + +/***/ }), + +/***/ 3730: +/***/ ((module) => { + +/** + * Helpers. + */ + +var s = 1000; +var m = s * 60; +var h = m * 60; +var d = h * 24; +var w = d * 7; +var y = d * 365.25; + +/** + * Parse or format the given `val`. + * + * Options: + * + * - `long` verbose formatting [false] + * + * @param {String|Number} val + * @param {Object} [options] + * @throws {Error} throw an error if val is not a non-empty string or a number + * @return {String|Number} + * @api public + */ + +module.exports = function(val, options) { + options = options || {}; + var type = typeof val; + if (type === 'string' && val.length > 0) { + return parse(val); + } else if (type === 'number' && isFinite(val)) { + return options.long ? fmtLong(val) : fmtShort(val); + } + throw new Error( + 'val is not a non-empty string or a valid number. val=' + + JSON.stringify(val) + ); +}; + +/** + * Parse the given `str` and return milliseconds. + * + * @param {String} str + * @return {Number} + * @api private + */ + +function parse(str) { + str = String(str); + if (str.length > 100) { + return; + } + var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec( + str + ); + if (!match) { + return; + } + var n = parseFloat(match[1]); + var type = (match[2] || 'ms').toLowerCase(); + switch (type) { + case 'years': + case 'year': + case 'yrs': + case 'yr': + case 'y': + return n * y; + case 'weeks': + case 'week': + case 'w': + return n * w; + case 'days': + case 'day': + case 'd': + return n * d; + case 'hours': + case 'hour': + case 'hrs': + case 'hr': + case 'h': + return n * h; + case 'minutes': + case 'minute': + case 'mins': + case 'min': + case 'm': + return n * m; + case 'seconds': + case 'second': + case 'secs': + case 'sec': + case 's': + return n * s; + case 'milliseconds': + case 'millisecond': + case 'msecs': + case 'msec': + case 'ms': + return n; + default: + return undefined; + } +} + +/** + * Short format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ + +function fmtShort(ms) { + var msAbs = Math.abs(ms); + if (msAbs >= d) { + return Math.round(ms / d) + 'd'; + } + if (msAbs >= h) { + return Math.round(ms / h) + 'h'; + } + if (msAbs >= m) { + return Math.round(ms / m) + 'm'; + } + if (msAbs >= s) { + return Math.round(ms / s) + 's'; + } + return ms + 'ms'; +} + +/** + * Long format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ + +function fmtLong(ms) { + var msAbs = Math.abs(ms); + if (msAbs >= d) { + return plural(ms, msAbs, d, 'day'); + } + if (msAbs >= h) { + return plural(ms, msAbs, h, 'hour'); + } + if (msAbs >= m) { + return plural(ms, msAbs, m, 'minute'); + } + if (msAbs >= s) { + return plural(ms, msAbs, s, 'second'); + } + return ms + ' ms'; +} + +/** + * Pluralization helper. + */ + +function plural(ms, msAbs, n, name) { + var isPlural = msAbs >= n * 1.5; + return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : ''); +} + + +/***/ }), + +/***/ 3925: +/***/ ((module, exports, __nccwpck_require__) => { + +/*! safe-buffer. MIT License. Feross Aboukhadijeh */ +/* eslint-disable node/no-deprecated-api */ +var buffer = __nccwpck_require__(4300) +var Buffer = buffer.Buffer + +// alternative to using Object.keys for old browsers +function copyProps (src, dst) { + for (var key in src) { + dst[key] = src[key] + } +} +if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) { + module.exports = buffer +} else { + // Copy properties from require('buffer') + copyProps(buffer, exports) + exports.Buffer = SafeBuffer +} + +function SafeBuffer (arg, encodingOrOffset, length) { + return Buffer(arg, encodingOrOffset, length) +} + +SafeBuffer.prototype = Object.create(Buffer.prototype) + +// Copy static methods from Buffer +copyProps(Buffer, SafeBuffer) + +SafeBuffer.from = function (arg, encodingOrOffset, length) { + if (typeof arg === 'number') { + throw new TypeError('Argument must not be a number') + } + return Buffer(arg, encodingOrOffset, length) +} + +SafeBuffer.alloc = function (size, fill, encoding) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + var buf = Buffer(size) + if (fill !== undefined) { + if (typeof encoding === 'string') { + buf.fill(fill, encoding) + } else { + buf.fill(fill) + } + } else { + buf.fill(0) + } + return buf +} + +SafeBuffer.allocUnsafe = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + return Buffer(size) +} + +SafeBuffer.allocUnsafeSlow = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + return buffer.SlowBuffer(size) +} + + +/***/ }), + +/***/ 5827: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; +/* eslint-disable node/no-deprecated-api */ + + + +var buffer = __nccwpck_require__(4300) +var Buffer = buffer.Buffer + +var safer = {} + +var key + +for (key in buffer) { + if (!buffer.hasOwnProperty(key)) continue + if (key === 'SlowBuffer' || key === 'Buffer') continue + safer[key] = buffer[key] +} + +var Safer = safer.Buffer = {} +for (key in Buffer) { + if (!Buffer.hasOwnProperty(key)) continue + if (key === 'allocUnsafe' || key === 'allocUnsafeSlow') continue + Safer[key] = Buffer[key] +} + +safer.Buffer.prototype = Buffer.prototype + +if (!Safer.from || Safer.from === Uint8Array.from) { + Safer.from = function (value, encodingOrOffset, length) { + if (typeof value === 'number') { + throw new TypeError('The "value" argument must not be of type number. Received type ' + typeof value) + } + if (value && typeof value.length === 'undefined') { + throw new TypeError('The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type ' + typeof value) + } + return Buffer(value, encodingOrOffset, length) + } +} + +if (!Safer.alloc) { + Safer.alloc = function (size, fill, encoding) { + if (typeof size !== 'number') { + throw new TypeError('The "size" argument must be of type number. Received type ' + typeof size) + } + if (size < 0 || size >= 2 * (1 << 30)) { + throw new RangeError('The value "' + size + '" is invalid for option "size"') + } + var buf = Buffer(size) + if (!fill || fill.length === 0) { + buf.fill(0) + } else if (typeof encoding === 'string') { + buf.fill(fill, encoding) + } else { + buf.fill(fill) + } + return buf + } +} + +if (!safer.kStringMaxLength) { + try { + safer.kStringMaxLength = process.binding('buffer').kStringMaxLength + } catch (e) { + // we can't determine kStringMaxLength in environments where process.binding + // is unsupported, so let's not set it + } +} + +if (!safer.constants) { + safer.constants = { + MAX_LENGTH: safer.kMaxLength + } + if (safer.kStringMaxLength) { + safer.constants.MAX_STRING_LENGTH = safer.kStringMaxLength + } +} + +module.exports = safer + + +/***/ }), + +/***/ 1216: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +const crypto = __nccwpck_require__(6113); +const ece = __nccwpck_require__(5094); + +const encrypt = function(userPublicKey, userAuth, payload, contentEncoding) { + if (!userPublicKey) { + throw new Error('No user public key provided for encryption.'); + } + + if (typeof userPublicKey !== 'string') { + throw new Error('The subscription p256dh value must be a string.'); + } + + if (Buffer.from(userPublicKey, 'base64url').length !== 65) { + throw new Error('The subscription p256dh value should be 65 bytes long.'); + } + + if (!userAuth) { + throw new Error('No user auth provided for encryption.'); + } + + if (typeof userAuth !== 'string') { + throw new Error('The subscription auth key must be a string.'); + } + + if (Buffer.from(userAuth, 'base64url').length < 16) { + throw new Error('The subscription auth key should be at least 16 ' + + 'bytes long'); + } + + if (typeof payload !== 'string' && !Buffer.isBuffer(payload)) { + throw new Error('Payload must be either a string or a Node Buffer.'); + } + + if (typeof payload === 'string' || payload instanceof String) { + payload = Buffer.from(payload); + } + + const localCurve = crypto.createECDH('prime256v1'); + const localPublicKey = localCurve.generateKeys(); + + const salt = crypto.randomBytes(16).toString('base64url'); + + const cipherText = ece.encrypt(payload, { + version: contentEncoding, + dh: userPublicKey, + privateKey: localCurve, + salt: salt, + authSecret: userAuth + }); + + return { + localPublicKey: localPublicKey, + salt: salt, + cipherText: cipherText + }; +}; + +module.exports = { + encrypt: encrypt +}; + + +/***/ }), + +/***/ 760: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +const vapidHelper = __nccwpck_require__(2519); +const encryptionHelper = __nccwpck_require__(1216); +const WebPushLib = __nccwpck_require__(8733); +const WebPushError = __nccwpck_require__(5708); +const WebPushConstants = __nccwpck_require__(7933); + +const webPush = new WebPushLib(); + +module.exports = { + WebPushError: WebPushError, + supportedContentEncodings: WebPushConstants.supportedContentEncodings, + encrypt: encryptionHelper.encrypt, + getVapidHeaders: vapidHelper.getVapidHeaders, + generateVAPIDKeys: vapidHelper.generateVAPIDKeys, + setGCMAPIKey: webPush.setGCMAPIKey, + setVapidDetails: webPush.setVapidDetails, + generateRequestDetails: webPush.generateRequestDetails, + sendNotification: webPush.sendNotification.bind(webPush) +}; + + +/***/ }), + +/***/ 4933: +/***/ ((module) => { + +"use strict"; + + +/** + * @param {string} base64 + * @returns {boolean} + */ +function validate(base64) { + return /^[A-Za-z0-9\-_]+$/.test(base64); +} + +module.exports = { + validate: validate +}; + + +/***/ }), + +/***/ 2519: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +const crypto = __nccwpck_require__(6113); +const asn1 = __nccwpck_require__(731); +const jws = __nccwpck_require__(7507); +const { URL } = __nccwpck_require__(7310); + +const WebPushConstants = __nccwpck_require__(7933); +const urlBase64Helper = __nccwpck_require__(4933); + +/** + * DEFAULT_EXPIRATION is set to seconds in 12 hours + */ +const DEFAULT_EXPIRATION_SECONDS = 12 * 60 * 60; + +// Maximum expiration is 24 hours according. (See VAPID spec) +const MAX_EXPIRATION_SECONDS = 24 * 60 * 60; + +const ECPrivateKeyASN = asn1.define('ECPrivateKey', function() { + this.seq().obj( + this.key('version').int(), + this.key('privateKey').octstr(), + this.key('parameters').explicit(0).objid() + .optional(), + this.key('publicKey').explicit(1).bitstr() + .optional() + ); +}); + +function toPEM(key) { + return ECPrivateKeyASN.encode({ + version: 1, + privateKey: key, + parameters: [1, 2, 840, 10045, 3, 1, 7] // prime256v1 + }, 'pem', { + label: 'EC PRIVATE KEY' + }); +} + +function generateVAPIDKeys() { + const curve = crypto.createECDH('prime256v1'); + curve.generateKeys(); + + let publicKeyBuffer = curve.getPublicKey(); + let privateKeyBuffer = curve.getPrivateKey(); + + // Occassionally the keys will not be padded to the correct lengh resulting + // in errors, hence this padding. + // See https://github.com/web-push-libs/web-push/issues/295 for history. + if (privateKeyBuffer.length < 32) { + const padding = Buffer.alloc(32 - privateKeyBuffer.length); + padding.fill(0); + privateKeyBuffer = Buffer.concat([padding, privateKeyBuffer]); + } + + if (publicKeyBuffer.length < 65) { + const padding = Buffer.alloc(65 - publicKeyBuffer.length); + padding.fill(0); + publicKeyBuffer = Buffer.concat([padding, publicKeyBuffer]); + } + + return { + publicKey: publicKeyBuffer.toString('base64url'), + privateKey: privateKeyBuffer.toString('base64url') + }; +} + +function validateSubject(subject) { + if (!subject) { + throw new Error('No subject set in vapidDetails.subject.'); + } + + if (typeof subject !== 'string' || subject.length === 0) { + throw new Error('The subject value must be a string containing an https: URL or ' + + 'mailto: address. ' + subject); + } + + let subjectParseResult = null; + try { + subjectParseResult = new URL(subject); + } catch (err) { + throw new Error('Vapid subject is not a valid URL. ' + subject); + } + if (!['https:', 'mailto:'].includes(subjectParseResult.protocol)) { + throw new Error('Vapid subject is not an https: or mailto: URL. ' + subject); + } + if (subjectParseResult.hostname === 'localhost') { + console.warn('Vapid subject points to a localhost web URI, which is unsupported by ' + + 'Apple\'s push notification server and will result in a BadJwtToken error when ' + + 'sending notifications.'); + } +} + +function validatePublicKey(publicKey) { + if (!publicKey) { + throw new Error('No key set vapidDetails.publicKey'); + } + + if (typeof publicKey !== 'string') { + throw new Error('Vapid public key is must be a URL safe Base 64 ' + + 'encoded string.'); + } + + if (!urlBase64Helper.validate(publicKey)) { + throw new Error('Vapid public key must be a URL safe Base 64 (without "=")'); + } + + publicKey = Buffer.from(publicKey, 'base64url'); + + if (publicKey.length !== 65) { + throw new Error('Vapid public key should be 65 bytes long when decoded.'); + } +} + +function validatePrivateKey(privateKey) { + if (!privateKey) { + throw new Error('No key set in vapidDetails.privateKey'); + } + + if (typeof privateKey !== 'string') { + throw new Error('Vapid private key must be a URL safe Base 64 ' + + 'encoded string.'); + } + + if (!urlBase64Helper.validate(privateKey)) { + throw new Error('Vapid private key must be a URL safe Base 64 (without "=")'); + } + + privateKey = Buffer.from(privateKey, 'base64url'); + + if (privateKey.length !== 32) { + throw new Error('Vapid private key should be 32 bytes long when decoded.'); + } +} + +/** + * Given the number of seconds calculates + * the expiration in the future by adding the passed `numSeconds` + * with the current seconds from Unix Epoch + * + * @param {Number} numSeconds Number of seconds to be added + * @return {Number} Future expiration in seconds + */ +function getFutureExpirationTimestamp(numSeconds) { + const futureExp = new Date(); + futureExp.setSeconds(futureExp.getSeconds() + numSeconds); + return Math.floor(futureExp.getTime() / 1000); +} + +/** + * Validates the Expiration Header based on the VAPID Spec + * Throws error of type `Error` if the expiration is not validated + * + * @param {Number} expiration Expiration seconds from Epoch to be validated + */ +function validateExpiration(expiration) { + if (!Number.isInteger(expiration)) { + throw new Error('`expiration` value must be a number'); + } + + if (expiration < 0) { + throw new Error('`expiration` must be a positive integer'); + } + + // Roughly checks the time of expiration, since the max expiration can be ahead + // of the time than at the moment the expiration was generated + const maxExpirationTimestamp = getFutureExpirationTimestamp(MAX_EXPIRATION_SECONDS); + + if (expiration >= maxExpirationTimestamp) { + throw new Error('`expiration` value is greater than maximum of 24 hours'); + } +} + +/** + * This method takes the required VAPID parameters and returns the required + * header to be added to a Web Push Protocol Request. + * @param {string} audience This must be the origin of the push service. + * @param {string} subject This should be a URL or a 'mailto:' email + * address. + * @param {string} publicKey The VAPID public key. + * @param {string} privateKey The VAPID private key. + * @param {string} contentEncoding The contentEncoding type. + * @param {integer} [expiration] The expiration of the VAPID JWT. + * @return {Object} Returns an Object with the Authorization and + * 'Crypto-Key' values to be used as headers. + */ +function getVapidHeaders(audience, subject, publicKey, privateKey, contentEncoding, expiration) { + if (!audience) { + throw new Error('No audience could be generated for VAPID.'); + } + + if (typeof audience !== 'string' || audience.length === 0) { + throw new Error('The audience value must be a string containing the ' + + 'origin of a push service. ' + audience); + } + + try { + new URL(audience); // eslint-disable-line no-new + } catch (err) { + throw new Error('VAPID audience is not a url. ' + audience); + } + + validateSubject(subject); + validatePublicKey(publicKey); + validatePrivateKey(privateKey); + + privateKey = Buffer.from(privateKey, 'base64url'); + + if (expiration) { + validateExpiration(expiration); + } else { + expiration = getFutureExpirationTimestamp(DEFAULT_EXPIRATION_SECONDS); + } + + const header = { + typ: 'JWT', + alg: 'ES256' + }; + + const jwtPayload = { + aud: audience, + exp: expiration, + sub: subject + }; + + const jwt = jws.sign({ + header: header, + payload: jwtPayload, + privateKey: toPEM(privateKey) + }); + + if (contentEncoding === WebPushConstants.supportedContentEncodings.AES_128_GCM) { + return { + Authorization: 'vapid t=' + jwt + ', k=' + publicKey + }; + } + if (contentEncoding === WebPushConstants.supportedContentEncodings.AES_GCM) { + return { + Authorization: 'WebPush ' + jwt, + 'Crypto-Key': 'p256ecdsa=' + publicKey + }; + } + + throw new Error('Unsupported encoding type specified.'); +} + +module.exports = { + generateVAPIDKeys: generateVAPIDKeys, + getFutureExpirationTimestamp: getFutureExpirationTimestamp, + getVapidHeaders: getVapidHeaders, + validateSubject: validateSubject, + validatePublicKey: validatePublicKey, + validatePrivateKey: validatePrivateKey, + validateExpiration: validateExpiration +}; + + +/***/ }), + +/***/ 7933: +/***/ ((module) => { + +"use strict"; + + +const WebPushConstants = {}; + +WebPushConstants.supportedContentEncodings = { + AES_GCM: 'aesgcm', + AES_128_GCM: 'aes128gcm' +}; + +WebPushConstants.supportedUrgency = { + VERY_LOW: 'very-low', + LOW: 'low', + NORMAL: 'normal', + HIGH: 'high' +}; + +module.exports = WebPushConstants; + + +/***/ }), + +/***/ 5708: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +function WebPushError(message, statusCode, headers, body, endpoint) { + Error.captureStackTrace(this, this.constructor); + + this.name = this.constructor.name; + this.message = message; + this.statusCode = statusCode; + this.headers = headers; + this.body = body; + this.endpoint = endpoint; +} + +(__nccwpck_require__(3837).inherits)(WebPushError, Error); + +module.exports = WebPushError; + + +/***/ }), + +/***/ 8733: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +const url = __nccwpck_require__(7310); +const https = __nccwpck_require__(5687); + +const WebPushError = __nccwpck_require__(5708); +const vapidHelper = __nccwpck_require__(2519); +const encryptionHelper = __nccwpck_require__(1216); +const webPushConstants = __nccwpck_require__(7933); +const urlBase64Helper = __nccwpck_require__(4933); + +// Default TTL is four weeks. +const DEFAULT_TTL = 2419200; + +let gcmAPIKey = ''; +let vapidDetails; + +function WebPushLib() { + +} + +/** + * When sending messages to a GCM endpoint you need to set the GCM API key + * by either calling setGMAPIKey() or passing in the API key as an option + * to sendNotification(). + * @param {string} apiKey The API key to send with the GCM request. + */ +WebPushLib.prototype.setGCMAPIKey = function(apiKey) { + if (apiKey === null) { + gcmAPIKey = null; + return; + } + + if (typeof apiKey === 'undefined' + || typeof apiKey !== 'string' + || apiKey.length === 0) { + throw new Error('The GCM API Key should be a non-empty string or null.'); + } + + gcmAPIKey = apiKey; +}; + +/** + * When making requests where you want to define VAPID details, call this + * method before sendNotification() or pass in the details and options to + * sendNotification. + * @param {string} subject This must be either a URL or a 'mailto:' + * address. For example: 'https://my-site.com/contact' or + * 'mailto: contact@my-site.com' + * @param {string} publicKey The public VAPID key, a URL safe, base64 encoded string + * @param {string} privateKey The private VAPID key, a URL safe, base64 encoded string. + */ +WebPushLib.prototype.setVapidDetails = function(subject, publicKey, privateKey) { + if (arguments.length === 1 && arguments[0] === null) { + vapidDetails = null; + return; + } + + vapidHelper.validateSubject(subject); + vapidHelper.validatePublicKey(publicKey); + vapidHelper.validatePrivateKey(privateKey); + + vapidDetails = { + subject: subject, + publicKey: publicKey, + privateKey: privateKey + }; + }; + + /** + * To get the details of a request to trigger a push message, without sending + * a push notification call this method. + * + * This method will throw an error if there is an issue with the input. + * @param {PushSubscription} subscription The PushSubscription you wish to + * send the notification to. + * @param {string|Buffer} [payload] The payload you wish to send to the + * the user. + * @param {Object} [options] Options for the GCM API key and + * vapid keys can be passed in if they are unique for each notification you + * wish to send. + * @return {Object} This method returns an Object which + * contains 'endpoint', 'method', 'headers' and 'payload'. + */ +WebPushLib.prototype.generateRequestDetails = function(subscription, payload, options) { + if (!subscription || !subscription.endpoint) { + throw new Error('You must pass in a subscription with at least ' + + 'an endpoint.'); + } + + if (typeof subscription.endpoint !== 'string' + || subscription.endpoint.length === 0) { + throw new Error('The subscription endpoint must be a string with ' + + 'a valid URL.'); + } + + if (payload) { + // Validate the subscription keys + if (typeof subscription !== 'object' || !subscription.keys + || !subscription.keys.p256dh + || !subscription.keys.auth) { + throw new Error('To send a message with a payload, the ' + + 'subscription must have \'auth\' and \'p256dh\' keys.'); + } + } + + let currentGCMAPIKey = gcmAPIKey; + let currentVapidDetails = vapidDetails; + let timeToLive = DEFAULT_TTL; + let extraHeaders = {}; + let contentEncoding = webPushConstants.supportedContentEncodings.AES_128_GCM; + let urgency = webPushConstants.supportedUrgency.NORMAL; + let topic; + let proxy; + let agent; + let timeout; + + if (options) { + const validOptionKeys = [ + 'headers', + 'gcmAPIKey', + 'vapidDetails', + 'TTL', + 'contentEncoding', + 'urgency', + 'topic', + 'proxy', + 'agent', + 'timeout' + ]; + const optionKeys = Object.keys(options); + for (let i = 0; i < optionKeys.length; i += 1) { + const optionKey = optionKeys[i]; + if (!validOptionKeys.includes(optionKey)) { + throw new Error('\'' + optionKey + '\' is an invalid option. ' + + 'The valid options are [\'' + validOptionKeys.join('\', \'') + + '\'].'); + } + } + + if (options.headers) { + extraHeaders = options.headers; + let duplicates = Object.keys(extraHeaders) + .filter(function (header) { + return typeof options[header] !== 'undefined'; + }); + + if (duplicates.length > 0) { + throw new Error('Duplicated headers defined [' + + duplicates.join(',') + ']. Please either define the header in the' + + 'top level options OR in the \'headers\' key.'); + } + } + + if (options.gcmAPIKey) { + currentGCMAPIKey = options.gcmAPIKey; + } + + // Falsy values are allowed here so one can skip Vapid `else if` below and use FCM + if (options.vapidDetails !== undefined) { + currentVapidDetails = options.vapidDetails; + } + + if (options.TTL !== undefined) { + timeToLive = Number(options.TTL); + if (timeToLive < 0) { + throw new Error('TTL should be a number and should be at least 0'); + } + } + + if (options.contentEncoding) { + if ((options.contentEncoding === webPushConstants.supportedContentEncodings.AES_128_GCM + || options.contentEncoding === webPushConstants.supportedContentEncodings.AES_GCM)) { + contentEncoding = options.contentEncoding; + } else { + throw new Error('Unsupported content encoding specified.'); + } + } + + if (options.urgency) { + if ((options.urgency === webPushConstants.supportedUrgency.VERY_LOW + || options.urgency === webPushConstants.supportedUrgency.LOW + || options.urgency === webPushConstants.supportedUrgency.NORMAL + || options.urgency === webPushConstants.supportedUrgency.HIGH)) { + urgency = options.urgency; + } else { + throw new Error('Unsupported urgency specified.'); + } + } + + if (options.topic) { + if (!urlBase64Helper.validate(options.topic)) { + throw new Error('Unsupported characters set use the URL or filename-safe Base64 characters set'); + } + if (options.topic.length > 32) { + throw new Error('use maximum of 32 characters from the URL or filename-safe Base64 characters set'); + } + topic = options.topic; + } + + if (options.proxy) { + if (typeof options.proxy === 'string' + || typeof options.proxy.host === 'string') { + proxy = options.proxy; + } else { + console.warn('Attempt to use proxy option, but invalid type it should be a string or proxy options object.'); + } + } + + if (options.agent) { + if (options.agent instanceof https.Agent) { + if (proxy) { + console.warn('Agent option will be ignored because proxy option is defined.'); + } + + agent = options.agent; + } else { + console.warn('Wrong type for the agent option, it should be an instance of https.Agent.'); + } + } + + if (typeof options.timeout === 'number') { + timeout = options.timeout; + } + } + + if (typeof timeToLive === 'undefined') { + timeToLive = DEFAULT_TTL; + } + + const requestDetails = { + method: 'POST', + headers: { + TTL: timeToLive + } + }; + Object.keys(extraHeaders).forEach(function (header) { + requestDetails.headers[header] = extraHeaders[header]; + }); + let requestPayload = null; + + if (payload) { + const encrypted = encryptionHelper + .encrypt(subscription.keys.p256dh, subscription.keys.auth, payload, contentEncoding); + + requestDetails.headers['Content-Length'] = encrypted.cipherText.length; + requestDetails.headers['Content-Type'] = 'application/octet-stream'; + + if (contentEncoding === webPushConstants.supportedContentEncodings.AES_128_GCM) { + requestDetails.headers['Content-Encoding'] = webPushConstants.supportedContentEncodings.AES_128_GCM; + } else if (contentEncoding === webPushConstants.supportedContentEncodings.AES_GCM) { + requestDetails.headers['Content-Encoding'] = webPushConstants.supportedContentEncodings.AES_GCM; + requestDetails.headers.Encryption = 'salt=' + encrypted.salt; + requestDetails.headers['Crypto-Key'] = 'dh=' + encrypted.localPublicKey.toString('base64url'); + } + + requestPayload = encrypted.cipherText; + } else { + requestDetails.headers['Content-Length'] = 0; + } + + const isGCM = subscription.endpoint.startsWith('https://android.googleapis.com/gcm/send'); + const isFCM = subscription.endpoint.startsWith('https://fcm.googleapis.com/fcm/send'); + // VAPID isn't supported by GCM hence the if, else if. + if (isGCM) { + if (!currentGCMAPIKey) { + console.warn('Attempt to send push notification to GCM endpoint, ' + + 'but no GCM key is defined. Please use setGCMApiKey() or add ' + + '\'gcmAPIKey\' as an option.'); + } else { + requestDetails.headers.Authorization = 'key=' + currentGCMAPIKey; + } + } else if (currentVapidDetails) { + const parsedUrl = url.parse(subscription.endpoint); + const audience = parsedUrl.protocol + '//' + + parsedUrl.host; + + const vapidHeaders = vapidHelper.getVapidHeaders( + audience, + currentVapidDetails.subject, + currentVapidDetails.publicKey, + currentVapidDetails.privateKey, + contentEncoding + ); + + requestDetails.headers.Authorization = vapidHeaders.Authorization; + + if (contentEncoding === webPushConstants.supportedContentEncodings.AES_GCM) { + if (requestDetails.headers['Crypto-Key']) { + requestDetails.headers['Crypto-Key'] += ';' + + vapidHeaders['Crypto-Key']; + } else { + requestDetails.headers['Crypto-Key'] = vapidHeaders['Crypto-Key']; + } + } + } else if (isFCM && currentGCMAPIKey) { + requestDetails.headers.Authorization = 'key=' + currentGCMAPIKey; + } + + requestDetails.headers.Urgency = urgency; + + if (topic) { + requestDetails.headers.Topic = topic; + } + + requestDetails.body = requestPayload; + requestDetails.endpoint = subscription.endpoint; + + if (proxy) { + requestDetails.proxy = proxy; + } + + if (agent) { + requestDetails.agent = agent; + } + + if (timeout) { + requestDetails.timeout = timeout; + } + + return requestDetails; + }; + +/** + * To send a push notification call this method with a subscription, optional + * payload and any options. + * @param {PushSubscription} subscription The PushSubscription you wish to + * send the notification to. + * @param {string|Buffer} [payload] The payload you wish to send to the + * the user. + * @param {Object} [options] Options for the GCM API key and + * vapid keys can be passed in if they are unique for each notification you + * wish to send. + * @return {Promise} This method returns a Promise which + * resolves if the sending of the notification was successful, otherwise it + * rejects. + */ +WebPushLib.prototype.sendNotification = function(subscription, payload, options) { + let requestDetails; + try { + requestDetails = this.generateRequestDetails(subscription, payload, options); + } catch (err) { + return Promise.reject(err); + } + + return new Promise(function(resolve, reject) { + const httpsOptions = {}; + const urlParts = url.parse(requestDetails.endpoint); + httpsOptions.hostname = urlParts.hostname; + httpsOptions.port = urlParts.port; + httpsOptions.path = urlParts.path; + + httpsOptions.headers = requestDetails.headers; + httpsOptions.method = requestDetails.method; + + if (requestDetails.timeout) { + httpsOptions.timeout = requestDetails.timeout; + } + + if (requestDetails.agent) { + httpsOptions.agent = requestDetails.agent; + } + + if (requestDetails.proxy) { + const { HttpsProxyAgent } = __nccwpck_require__(9521); // eslint-disable-line global-require + httpsOptions.agent = new HttpsProxyAgent(requestDetails.proxy); + } + + const pushRequest = https.request(httpsOptions, function(pushResponse) { + let responseText = ''; + + pushResponse.on('data', function(chunk) { + responseText += chunk; + }); + + pushResponse.on('end', function() { + if (pushResponse.statusCode < 200 || pushResponse.statusCode > 299) { + reject(new WebPushError( + 'Received unexpected response code', + pushResponse.statusCode, + pushResponse.headers, + responseText, + requestDetails.endpoint + )); + } else { + resolve({ + statusCode: pushResponse.statusCode, + body: responseText, + headers: pushResponse.headers + }); + } + }); + }); + + if (requestDetails.timeout) { + pushRequest.on('timeout', function() { + pushRequest.destroy(new Error('Socket timeout')); + }); + } + + pushRequest.on('error', function(e) { + reject(e); + }); + + if (requestDetails.body) { + pushRequest.write(requestDetails.body); + } + + pushRequest.end(); + }); + }; + +module.exports = WebPushLib; + + +/***/ }), + +/***/ 4341: +/***/ ((module) => { + +module.exports = eval("require")("supports-color"); + + +/***/ }), + +/***/ 9491: +/***/ ((module) => { + +"use strict"; +module.exports = require("assert"); + +/***/ }), + +/***/ 4300: +/***/ ((module) => { + +"use strict"; +module.exports = require("buffer"); + +/***/ }), + +/***/ 6113: +/***/ ((module) => { + +"use strict"; +module.exports = require("crypto"); + +/***/ }), + +/***/ 3685: +/***/ ((module) => { + +"use strict"; +module.exports = require("http"); + +/***/ }), + +/***/ 5687: +/***/ ((module) => { + +"use strict"; +module.exports = require("https"); + +/***/ }), + +/***/ 1808: +/***/ ((module) => { + +"use strict"; +module.exports = require("net"); + +/***/ }), + +/***/ 2781: +/***/ ((module) => { + +"use strict"; +module.exports = require("stream"); + +/***/ }), + +/***/ 4404: +/***/ ((module) => { + +"use strict"; +module.exports = require("tls"); + +/***/ }), + +/***/ 6224: +/***/ ((module) => { + +"use strict"; +module.exports = require("tty"); + +/***/ }), + +/***/ 7310: +/***/ ((module) => { + +"use strict"; +module.exports = require("url"); + +/***/ }), + +/***/ 3837: +/***/ ((module) => { + +"use strict"; +module.exports = require("util"); + +/***/ }) + +/******/ }); +/************************************************************************/ +/******/ // The module cache +/******/ var __webpack_module_cache__ = {}; +/******/ +/******/ // The require function +/******/ function __nccwpck_require__(moduleId) { +/******/ // Check if module is in cache +/******/ var cachedModule = __webpack_module_cache__[moduleId]; +/******/ if (cachedModule !== undefined) { +/******/ return cachedModule.exports; +/******/ } +/******/ // Create a new module (and put it into the cache) +/******/ var module = __webpack_module_cache__[moduleId] = { +/******/ id: moduleId, +/******/ loaded: false, +/******/ exports: {} +/******/ }; +/******/ +/******/ // Execute the module function +/******/ var threw = true; +/******/ try { +/******/ __webpack_modules__[moduleId].call(module.exports, module, module.exports, __nccwpck_require__); +/******/ threw = false; +/******/ } finally { +/******/ if(threw) delete __webpack_module_cache__[moduleId]; +/******/ } +/******/ +/******/ // Flag the module as loaded +/******/ module.loaded = true; +/******/ +/******/ // Return the exports of the module +/******/ return module.exports; +/******/ } +/******/ +/************************************************************************/ +/******/ /* webpack/runtime/node module decorator */ +/******/ (() => { +/******/ __nccwpck_require__.nmd = (module) => { +/******/ module.paths = []; +/******/ if (!module.children) module.children = []; +/******/ return module; +/******/ }; +/******/ })(); +/******/ +/******/ /* webpack/runtime/compat */ +/******/ +/******/ if (typeof __nccwpck_require__ !== 'undefined') __nccwpck_require__.ab = __dirname + "/"; +/******/ +/************************************************************************/ +/******/ +/******/ // startup +/******/ // Load entry module and return exports +/******/ // This entry module is referenced by other modules so it can't be inlined +/******/ var __webpack_exports__ = __nccwpck_require__(760); +/******/ module.exports = __webpack_exports__; +/******/ +/******/ })() +; \ No newline at end of file From 09fa673c2dfb5fb33f9b0b342efdc36e818f6719 Mon Sep 17 00:00:00 2001 From: bonbud-macryg Date: Tue, 23 Jul 2024 11:08:55 +0100 Subject: [PATCH 10/46] Add notification template --- pkg/arvo/neo/cod/std/src/fil/push-sw.js | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 pkg/arvo/neo/cod/std/src/fil/push-sw.js diff --git a/pkg/arvo/neo/cod/std/src/fil/push-sw.js b/pkg/arvo/neo/cod/std/src/fil/push-sw.js new file mode 100644 index 0000000000..2bd3dabe36 --- /dev/null +++ b/pkg/arvo/neo/cod/std/src/fil/push-sw.js @@ -0,0 +1,14 @@ +self.addEventListener('push', function(e) { + var options = { + body: 'This notification was generated from a push!', + icon: 'https://ewr1.vultrobjects.com/urbit/hastuc-dibtux/2024.4.30..2.37.9..bae1.47ae.147a.e147-IMG_5592.jpeg', + vibrate: [100, 50, 100], + data: { + dateOfArrival: Date.now(), + primaryKey: '2' + } + }; + e.waitUntil( + self.registration.showNotification('Hello world!', options) + ); +}); \ No newline at end of file From e280a34edc2f02fabb31286af12d605e9cd47e79 Mon Sep 17 00:00:00 2001 From: bonbud-macryg Date: Tue, 23 Jul 2024 16:32:49 +0100 Subject: [PATCH 11/46] Draft frontend code --- pkg/arvo/neo/cod/std/src/con/sky-htmx.hoon | 202 ++++++++++++++++++ .../neo/cod/std/src/imp/notifications.hoon | 13 +- 2 files changed, 206 insertions(+), 9 deletions(-) create mode 100644 pkg/arvo/neo/cod/std/src/con/sky-htmx.hoon diff --git a/pkg/arvo/neo/cod/std/src/con/sky-htmx.hoon b/pkg/arvo/neo/cod/std/src/con/sky-htmx.hoon new file mode 100644 index 0000000000..5500732187 --- /dev/null +++ b/pkg/arvo/neo/cod/std/src/con/sky-htmx.hoon @@ -0,0 +1,202 @@ +/@ sky +/@ sky-settings +/- sky-server +/* s-k-y +/* feather-settings +/* wi-nd +/* hawk-icon +:- [%sky %$ %htmx] +|= =sky +|= =bowl:neo +^- manx +|^ + =; m + %- lift + ?: menu.sky m + m(a.g [[%closed ""] a.g.m]) + ^- manx + ;s-k-y + =our (scow %p our.bowl) + =windows-open "{}" + ; + == +:: +++ map-to-css-tape + |= m=(map @t @t) + ^- tape + %- zing + %+ turn ~(tap by m) + |= [key=@t val=@t] + """ + --{(trip key)}: {(trip val)}; + """ +++ icon-url + ^~ + %- trip + %^ cat + 3 + 'data:image/png;base64,' + %- ~(en base64:mimes:html & |) + (as-octs:mimes:html hawk-icon) +++ favicon + ^~ + =; m m(a.g [[%href icon-url] a.g.m]) + ^- manx + ;link + =rel "icon" + =type "image/png" + ; + == +++ manifest-url + ^~ + %- trip + %^ cat + 3 + 'data:application/json;utf-8,' + %- en:json:html + %- pairs:enjs:format + :~ + ['name' s+'sky'] + ['description' s+'an urbit namespace viewer'] + ['start_url' s+'http://localhost/neo/sky'] :: XX + ['display' s+'standalone'] + ['background_color' s+'black'] + ['theme_color' s+'black'] + :+ 'icons' %a + :~ + %- pairs:enjs:format + :~ + ['src' s+(crip icon-url)] + ['sizes' s+'196x196'] + ['type' s+'image/png'] + == + == + == +++ manifest + ^~ + =; m m(a.g [[%href manifest-url] a.g.m]) + ^- manx + ;link + =rel "manifest" + ; + == +:: +++ lift + |= in=manx + ^- manx + ;html + ;head + ;meta(charset "UTF-8"); + ;title: s k y + ;* standard-head-tags.sky-server + ;meta + =name "htmx-config" + =content (trip '{"ignoreTitle":"true"}') + ; + == + ;script + ;+ ;/ %- trip + ''' + document.addEventListener('feather-changed', (e) => { + e.detail.forEach(r => { + document.documentElement.style + .setProperty('--'+r.variable, `${r.value}${r.unit||''}`); + }) + let windows = document.querySelectorAll('wi-nd'); + windows.forEach(w => { + $(w).poke('set-feather-values', e.detail) + }) + let rules = document.querySelector('s-k-y').currentFeatherRules; + localStorage.setItem('feather-settings', JSON.stringify(rules)); + }); + let rules = JSON.parse(localStorage.getItem('feather-settings') || '[]'); + rules.forEach(r => { + document.documentElement.style + .setProperty('--'+r.variable, `${r.value}${r.unit||''}`); + }) + window.addEventListener('resize', () => { + $('s-k-y').attr('open', null); + }); + window.addEventListener('message', function(event) { + if (event.data?.messagetype == 'sky-poll-response') { + let wid = event.data.wid; + let here = event.data.here; + let prefix = event.data.prefix; + let wind = document.querySelector(`[wid='${wid}']`); + if (wind) { + $(wind).poke('iframe-moved', {here, prefix}) + } + } + else if (event.data?.messagetype == 'iframe-wants-feather') { + let rules = document.querySelector('s-k-y').currentFeatherRules; + let wid = event.data.wid; + let wind = document.querySelector(`[wid='${wid}']`); + if (wind) { + $(wind).poke('set-feather-values', rules) + } + } + }); + ''' + == +<<<<<<< HEAD + ;script: {(trip s-k-y)} + ;script: {(trip feather-settings)} + ;script: {(trip wi-nd)} +======= + ;script: {(trip a-i-r)} + ;script: {(trip date-now)} + :: + :: set up push notifications for this browser + ;script + ;+ ;/ %- trip + ''' + const push = require('../fil/web-push.js') + + addEventListener('load', async () => { + let sw = await navigator.serviceWorker.register('../fil/push-sw.js') + console.log(sw) + subscribeToNotifications() + }); + + async function subscribeToNotifications() { + let sw = await navigator.serviceWorker.ready + const vapidKeys = push.generateVAPIDKeys() + let pushSubscriptionDetails = await sw.pushManager.subscribe({ + userVisibleOnly: true, + applicationServerKey: `${vapidKeys.publicKey}` + }); + + sendSubscriptionToServer(pushSubscriptionDetails) + + // console.log(JSON.stringify(pushSubscriptionDetails)) + } + + function sendSubscriptionToServer(pushSubscriptionDetails) { + document.getElementById('push-subscription-details').value = + JSON.stringify(pushSubscriptionDetails) + document.getElementById('subscription-form').submit() + } + ''' + == +>>>>>>> 13d77f915b (Draft frontend code) + ;+ favicon + ;+ manifest + == + ;body + =hx-ext "dom-enc,response-targets,morph" + =hx-swap "outerHTML" + =hx-boost "true" + =hx-history "false" + =hx-replace-url "/neo/sky" + =our (scow %p our.bowl) + ;+ in +<<<<<<< HEAD +======= + ;+ eye + ;+ menu-btn-style + ;+ theme-style + ;+ notifications-subscription +>>>>>>> 13d77f915b (Draft frontend code) + == + == +-- diff --git a/pkg/arvo/neo/cod/std/src/imp/notifications.hoon b/pkg/arvo/neo/cod/std/src/imp/notifications.hoon index f9b220ad30..4a6d09746f 100644 --- a/pkg/arvo/neo/cod/std/src/imp/notifications.hoon +++ b/pkg/arvo/neo/cod/std/src/imp/notifications.hoon @@ -1,3 +1,4 @@ +/@ txt /@ notification /@ notifications-config /@ notifications-controller @@ -23,7 +24,7 @@ :: ++ poke ^- (set stud:neo) - (sy %notification ~) + (sy %txt %notification ~) :: ++ kids ^- kids:neo @@ -34,6 +35,8 @@ [[%pro %notification] ~] :- [[%.n %tas] %.n] [[%pro %notifications-config] ~] + :- [[%.n %t] %.n] + [[%pro %txt] ~] == :: ++ deps @@ -75,14 +78,6 @@ !< notifications-config q.pail:(need (~(get by ~(tar of:neo kids.bowl)) (state not))) :_ [%notifications-controller !>(state)] - :: - :: XX algo has to be more sophisticated than this; - :: has to say "is whole pith.not contained in a kill.config path?" - :: probably check if first iota in pith.not is first iota of a - :: kill.config pith, if yes check second iota, etc. - :: this is to handle killing/muting entire subtrees - :: - :: ?: (has-pith-in-any kill.config pith.not) ~ ?: (has-pith-in-any mute.config pith.not) From 574f63a188e2477946247cab4b90662ad74cc472 Mon Sep 17 00:00:00 2001 From: bonbud-macryg Date: Tue, 23 Jul 2024 19:58:21 +0100 Subject: [PATCH 12/46] make txt, todos --- .../neo/cod/std/src/imp/notifications.hoon | 19 +++++++++++++++++-- 1 file changed, 17 insertions(+), 2 deletions(-) diff --git a/pkg/arvo/neo/cod/std/src/imp/notifications.hoon b/pkg/arvo/neo/cod/std/src/imp/notifications.hoon index 4a6d09746f..a8dbfd1cc6 100644 --- a/pkg/arvo/neo/cod/std/src/imp/notifications.hoon +++ b/pkg/arvo/neo/cod/std/src/imp/notifications.hoon @@ -68,6 +68,21 @@ %notifications-controller :: XX need to check vaz? [~ [%notifications-controller vaz]] + :: + %txt + :_ [%notifications-controller !>(state)] + =/ auth (de:json:html !<(txt vaz)) + ?~ auth + ~ + :: XX parse JSON + :: need endpoint + expirationTime at minimum + :: XX maybe store endpoint details as $json + :: would need a /pro/json.hoon + :: XX handle expirationTime with behn + :: XX placeholder path + :~ :- (welp here.bowl ~[%foo]) + [%make %txt `[%txt !>('')] ~] + == :: %notification =/ not !<(notification vaz) @@ -89,7 +104,7 @@ =. flag.not %.y :~ :- (welp here.bowl ~[[da/now.bowl]]) [%make %notification `[%notification !>(not)] ~] - :: XX send push notification + :: XX send push notifications to subscribers == ?. flag.not =. flag.not %.y @@ -98,7 +113,7 @@ == :~ :- (welp here.bowl ~[[da/now.bowl]]) [%make %notification `[%notification !>(not)] ~] - :: XX send push notification + :: XX send push notifications to subscribers == == -- From dfc350e241b65976e619f76152c00463c17451a4 Mon Sep 17 00:00:00 2001 From: bonbud-macryg Date: Mon, 29 Jul 2024 11:33:45 +0100 Subject: [PATCH 13/46] Remove unnecessary ketcol --- pkg/arvo/neo/cod/std/src/pro/notifications-config.hoon | 1 - 1 file changed, 1 deletion(-) diff --git a/pkg/arvo/neo/cod/std/src/pro/notifications-config.hoon b/pkg/arvo/neo/cod/std/src/pro/notifications-config.hoon index cdb91b09c5..6ddcec2bf5 100644 --- a/pkg/arvo/neo/cod/std/src/pro/notifications-config.hoon +++ b/pkg/arvo/neo/cod/std/src/pro/notifications-config.hoon @@ -1,4 +1,3 @@ -^: $: buzz=(set pith) mute=(set pith) kill=(set pith) From ccbb5796cf0b515458c610f6e6b37517f681b958 Mon Sep 17 00:00:00 2001 From: bonbud-macryg Date: Mon, 29 Jul 2024 11:36:23 +0100 Subject: [PATCH 14/46] Fix notifications-config state --- pkg/arvo/neo/cod/std/src/imp/notifications-config.hoon | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pkg/arvo/neo/cod/std/src/imp/notifications-config.hoon b/pkg/arvo/neo/cod/std/src/imp/notifications-config.hoon index 0efc9fb20f..2d9098b8b8 100644 --- a/pkg/arvo/neo/cod/std/src/imp/notifications-config.hoon +++ b/pkg/arvo/neo/cod/std/src/imp/notifications-config.hoon @@ -2,7 +2,7 @@ ^- kook:neo |% ++ state - [%pro %notifications] + [%pro %notifications-config] ++ poke (sy %notifications-config ~) ++ kids From 8cccfa77c739607229ade80d61239e32df458a39 Mon Sep 17 00:00:00 2001 From: bonbud-macryg Date: Mon, 29 Jul 2024 11:45:21 +0100 Subject: [PATCH 15/46] Remove unnecessary tisfas --- pkg/arvo/neo/cod/std/src/imp/notifications-config.hoon | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/pkg/arvo/neo/cod/std/src/imp/notifications-config.hoon b/pkg/arvo/neo/cod/std/src/imp/notifications-config.hoon index 2d9098b8b8..d3694e3bd6 100644 --- a/pkg/arvo/neo/cod/std/src/imp/notifications-config.hoon +++ b/pkg/arvo/neo/cod/std/src/imp/notifications-config.hoon @@ -23,7 +23,6 @@ |= [=stud:neo vaz=vase] ^- (quip card:neo pail:neo) ?> =(%notifications-config stud) - =/ new-config !<(notifications-config vaz) - [~ [%notifications-config !>(new-config)]] + [~ [%notifications-config vaz]] -- -- \ No newline at end of file From 8ab95a63bff0c860c867abedce5f37f5819446e3 Mon Sep 17 00:00:00 2001 From: bonbud-macryg Date: Mon, 29 Jul 2024 11:49:12 +0100 Subject: [PATCH 16/46] Remove unnecessary com --- pkg/arvo/neo/cod/std/src/imp/notifications.hoon | 8 ++++---- .../neo/cod/std/src/pro/notifications-controller.hoon | 2 +- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/pkg/arvo/neo/cod/std/src/imp/notifications.hoon b/pkg/arvo/neo/cod/std/src/imp/notifications.hoon index a8dbfd1cc6..85af94a3b7 100644 --- a/pkg/arvo/neo/cod/std/src/imp/notifications.hoon +++ b/pkg/arvo/neo/cod/std/src/imp/notifications.hoon @@ -7,7 +7,7 @@ :: :: helper core |% -++ has-pith-in-any +++ has-pith-in |= [piths=(set pith) query=pith] ^- ? %- ~(any in piths) @@ -93,14 +93,14 @@ !< notifications-config q.pail:(need (~(get by ~(tar of:neo kids.bowl)) (state not))) :_ [%notifications-controller !>(state)] - ?: (has-pith-in-any kill.config pith.not) + ?: (has-pith-in kill.config pith.not) ~ - ?: (has-pith-in-any mute.config pith.not) + ?: (has-pith-in mute.config pith.not) =. flag.not %.y :~ :- (welp here.bowl ~[[da/now.bowl]]) [%make %notification `[%notification !>(not)] ~] == - ?: (has-pith-in-any buzz.config pith.not) + ?: (has-pith-in buzz.config pith.not) =. flag.not %.y :~ :- (welp here.bowl ~[[da/now.bowl]]) [%make %notification `[%notification !>(not)] ~] diff --git a/pkg/arvo/neo/cod/std/src/pro/notifications-controller.hoon b/pkg/arvo/neo/cod/std/src/pro/notifications-controller.hoon index aa47902156..04be12a293 100644 --- a/pkg/arvo/neo/cod/std/src/pro/notifications-controller.hoon +++ b/pkg/arvo/neo/cod/std/src/pro/notifications-controller.hoon @@ -1,2 +1,2 @@ /@ notification -,$-(notification pith) \ No newline at end of file +$-(notification pith) \ No newline at end of file From e1e592d29a3bb23f968c7e846923bfcb49d1bb14 Mon Sep 17 00:00:00 2001 From: bonbud-macryg Date: Mon, 29 Jul 2024 13:12:35 +0100 Subject: [PATCH 17/46] Fix notifications-config init --- pkg/arvo/neo/cod/std/src/imp/notifications-config.hoon | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pkg/arvo/neo/cod/std/src/imp/notifications-config.hoon b/pkg/arvo/neo/cod/std/src/imp/notifications-config.hoon index d3694e3bd6..01b4b6bf98 100644 --- a/pkg/arvo/neo/cod/std/src/imp/notifications-config.hoon +++ b/pkg/arvo/neo/cod/std/src/imp/notifications-config.hoon @@ -18,7 +18,7 @@ ^- (quip card:neo pail:neo) ?^ old [~ (need old)] - [~ [%notifications-config !>(*state)]] + [~ [%notifications-config !>(~)]] ++ poke |= [=stud:neo vaz=vase] ^- (quip card:neo pail:neo) From ea63317e8506cfbaf0a7c969a944a94519782e63 Mon Sep 17 00:00:00 2001 From: bonbud-macryg Date: Mon, 29 Jul 2024 14:05:14 +0100 Subject: [PATCH 18/46] Parse and store json from push service --- .../neo/cod/std/src/imp/notifications.hoon | 29 +++++++++---------- pkg/arvo/neo/cod/std/src/pro/json.hoon | 2 +- 2 files changed, 15 insertions(+), 16 deletions(-) diff --git a/pkg/arvo/neo/cod/std/src/imp/notifications.hoon b/pkg/arvo/neo/cod/std/src/imp/notifications.hoon index 85af94a3b7..c1d4d8c64a 100644 --- a/pkg/arvo/neo/cod/std/src/imp/notifications.hoon +++ b/pkg/arvo/neo/cod/std/src/imp/notifications.hoon @@ -1,4 +1,4 @@ -/@ txt +/@ json /@ notification /@ notifications-config /@ notifications-controller @@ -24,7 +24,7 @@ :: ++ poke ^- (set stud:neo) - (sy %txt %notification ~) + (sy %json %notification ~) :: ++ kids ^- kids:neo @@ -36,7 +36,7 @@ :- [[%.n %tas] %.n] [[%pro %notifications-config] ~] :- [[%.n %t] %.n] - [[%pro %txt] ~] + [[%pro %json] ~] == :: ++ deps @@ -66,22 +66,21 @@ ?+ stud !! %notifications-controller - :: XX need to check vaz? [~ [%notifications-controller vaz]] :: - %txt + %json :_ [%notifications-controller !>(state)] - =/ auth (de:json:html !<(txt vaz)) - ?~ auth + =/ cred !<(json vaz) + ?~ cred ~ - :: XX parse JSON - :: need endpoint + expirationTime at minimum - :: XX maybe store endpoint details as $json - :: would need a /pro/json.hoon - :: XX handle expirationTime with behn - :: XX placeholder path - :~ :- (welp here.bowl ~[%foo]) - [%make %txt `[%txt !>('')] ~] + :: XX parse expirationTime + =/ endpoint + %. cred + (ot ~[endpoint+so]):dejs:format + :: XX handle expirationTime with behn? + :: remove this endpoint when the timer fires + :~ :- (welp here.bowl ~[t/endpoint]) + [%make %json `[%json !>(cred)] ~] == :: %notification diff --git a/pkg/arvo/neo/cod/std/src/pro/json.hoon b/pkg/arvo/neo/cod/std/src/pro/json.hoon index 3c840093b7..977ecbe28a 100644 --- a/pkg/arvo/neo/cod/std/src/pro/json.hoon +++ b/pkg/arvo/neo/cod/std/src/pro/json.hoon @@ -1 +1 @@ -json +,json From 5b533ed7947d16fe314ebfb7ad67ae724fd2d493 Mon Sep 17 00:00:00 2001 From: bonbud-macryg Date: Mon, 29 Jul 2024 16:09:55 +0100 Subject: [PATCH 19/46] Clean up piths --- pkg/arvo/neo/cod/std/src/imp/notifications.hoon | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/pkg/arvo/neo/cod/std/src/imp/notifications.hoon b/pkg/arvo/neo/cod/std/src/imp/notifications.hoon index c1d4d8c64a..b0416387c1 100644 --- a/pkg/arvo/neo/cod/std/src/imp/notifications.hoon +++ b/pkg/arvo/neo/cod/std/src/imp/notifications.hoon @@ -31,11 +31,11 @@ %- some :- %y %- ~(gas by *lads:neo) - :~ :- [[%.n %da] %.n] + :~ :- [[%.y %notification] [%.n %da] %.n] [[%pro %notification] ~] - :- [[%.n %tas] %.n] + :- [[%.y %config] [%.n %tas] %.n] [[%pro %notifications-config] ~] - :- [[%.n %t] %.n] + :- [[%.y %endpoints] [%.n %t] %.n] [[%pro %json] ~] == :: @@ -51,8 +51,8 @@ ^- (quip card:neo pail:neo) ?^ old [~ u.old] - :_ [%notifications-controller !>(|=(notification /default))] - :~ :- (welp here.bowl ~[%default]) + :_ [%notifications-controller !>(|=(notification #/config/default))] + :~ :- (welp here.bowl ~[%config %default]) :* %make %notifications-config `[%notifications-config !>(*notifications-config)] @@ -79,7 +79,7 @@ (ot ~[endpoint+so]):dejs:format :: XX handle expirationTime with behn? :: remove this endpoint when the timer fires - :~ :- (welp here.bowl ~[t/endpoint]) + :~ :- (welp here.bowl ~[%endpoint t/endpoint]) [%make %json `[%json !>(cred)] ~] == :: From a8f5b947b3f020fba11243013d9cfa44eeaf72f9 Mon Sep 17 00:00:00 2001 From: bonbud-macryg Date: Mon, 29 Jul 2024 16:28:42 +0100 Subject: [PATCH 20/46] Add notifications to imp/home --- pkg/arvo/neo/cod/std/src/imp/home.hoon | 1 + 1 file changed, 1 insertion(+) diff --git a/pkg/arvo/neo/cod/std/src/imp/home.hoon b/pkg/arvo/neo/cod/std/src/imp/home.hoon index 7e582e45b1..3a6834eae7 100644 --- a/pkg/arvo/neo/cod/std/src/imp/home.hoon +++ b/pkg/arvo/neo/cod/std/src/imp/home.hoon @@ -36,6 +36,7 @@ [#/[p/our.bowl]/home/files %make %folder ~ ~] [#/[p/our.bowl]/home/planner %make %planner ~ ~] [#/[p/our.bowl]/home/messenger %make %messenger ~ ~] + [#/[p/our.bowl]/home/notifications %make %notifications ~ ~] [#/[p/our.bowl]/home/landscape %make %iframe `iframe/!>('/apps/landscape') ~] :: [#/[p/our.bowl]/home/docs %make %folder `folder/!>([%introduction %tutorials %guides ~]) ~] From 58642e3ee5eb5ccd5697b86d3242e63fb5e3ed10 Mon Sep 17 00:00:00 2001 From: bonbud-macryg Date: Tue, 30 Jul 2024 11:06:40 +0100 Subject: [PATCH 21/46] Dummy notifications from messenger --- pkg/arvo/neo/cod/std/src/imp/message-sub.hoon | 4 ++++ pkg/arvo/neo/cod/std/src/imp/notifications.hoon | 4 +++- 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/pkg/arvo/neo/cod/std/src/imp/message-sub.hoon b/pkg/arvo/neo/cod/std/src/imp/message-sub.hoon index 94d64fd960..f940f2c73a 100644 --- a/pkg/arvo/neo/cod/std/src/imp/message-sub.hoon +++ b/pkg/arvo/neo/cod/std/src/imp/message-sub.hoon @@ -34,6 +34,10 @@ :_ state =+ !<([=term =leaf:neo] vax) :: only get new kids + %+ welp + :~ :- #/[p/our.bowl]/home/notifications + [%poke [%notification !>([%.y now.bowl here.bowl 'foobar new notif'])]] + == %+ murn ~(tap of:neo q:(~(got by deps.bowl) %pub)) |= [=pith:neo =idea:neo] ^- (unit card:neo) diff --git a/pkg/arvo/neo/cod/std/src/imp/notifications.hoon b/pkg/arvo/neo/cod/std/src/imp/notifications.hoon index b0416387c1..530f3348c8 100644 --- a/pkg/arvo/neo/cod/std/src/imp/notifications.hoon +++ b/pkg/arvo/neo/cod/std/src/imp/notifications.hoon @@ -87,7 +87,9 @@ =/ not !<(notification vaz) ?< =('' cord.not) ?< (gth time.not now.bowl) - ?> =(pith.not pith.src.bowl) + :: ~& >> pith.not + :: ~& >> pith.src.bowl + :: ?> =(pith.not pith.src.bowl) =/ config !< notifications-config q.pail:(need (~(get by ~(tar of:neo kids.bowl)) (state not))) From b826a58538e473af5542bc0dd553fa9a055361ee Mon Sep 17 00:00:00 2001 From: bonbud-macryg Date: Tue, 30 Jul 2024 11:18:40 +0100 Subject: [PATCH 22/46] Fix pith.not check, add ship.src.bowl check --- pkg/arvo/neo/cod/std/src/imp/notifications.hoon | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/pkg/arvo/neo/cod/std/src/imp/notifications.hoon b/pkg/arvo/neo/cod/std/src/imp/notifications.hoon index 530f3348c8..a64332e95e 100644 --- a/pkg/arvo/neo/cod/std/src/imp/notifications.hoon +++ b/pkg/arvo/neo/cod/std/src/imp/notifications.hoon @@ -63,6 +63,7 @@ ++ poke |= [=stud:neo vaz=vase] ^- (quip card:neo pail:neo) + ?> =(ship.src.bowl our.bowl) ?+ stud !! %notifications-controller @@ -87,9 +88,7 @@ =/ not !<(notification vaz) ?< =('' cord.not) ?< (gth time.not now.bowl) - :: ~& >> pith.not - :: ~& >> pith.src.bowl - :: ?> =(pith.not pith.src.bowl) + ?> =(pith.src.bowl (tail pith.not)) =/ config !< notifications-config q.pail:(need (~(get by ~(tar of:neo kids.bowl)) (state not))) From 53908971e5a23af2ffc096ae566ba4cf87cb2a3c Mon Sep 17 00:00:00 2001 From: bonbud-macryg Date: Tue, 30 Jul 2024 11:51:54 +0100 Subject: [PATCH 23/46] Remove notif from message-sub --- pkg/arvo/neo/cod/std/src/imp/message-sub.hoon | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/pkg/arvo/neo/cod/std/src/imp/message-sub.hoon b/pkg/arvo/neo/cod/std/src/imp/message-sub.hoon index f940f2c73a..18165df172 100644 --- a/pkg/arvo/neo/cod/std/src/imp/message-sub.hoon +++ b/pkg/arvo/neo/cod/std/src/imp/message-sub.hoon @@ -33,11 +33,8 @@ ?> =(%rely stud) :_ state =+ !<([=term =leaf:neo] vax) + :: :: only get new kids - %+ welp - :~ :- #/[p/our.bowl]/home/notifications - [%poke [%notification !>([%.y now.bowl here.bowl 'foobar new notif'])]] - == %+ murn ~(tap of:neo q:(~(got by deps.bowl) %pub)) |= [=pith:neo =idea:neo] ^- (unit card:neo) From 67d267654a4d328db4ef3d2be7367783fecab7f2 Mon Sep 17 00:00:00 2001 From: bonbud-macryg Date: Tue, 30 Jul 2024 15:36:49 +0100 Subject: [PATCH 24/46] Fill notifications with message text --- pkg/arvo/neo/cod/std/src/imp/message.hoon | 30 ++++++++++++++++++++++- 1 file changed, 29 insertions(+), 1 deletion(-) diff --git a/pkg/arvo/neo/cod/std/src/imp/message.hoon b/pkg/arvo/neo/cod/std/src/imp/message.hoon index 4977bc62c0..a57cb6c401 100644 --- a/pkg/arvo/neo/cod/std/src/imp/message.hoon +++ b/pkg/arvo/neo/cod/std/src/imp/message.hoon @@ -1 +1,29 @@ -~ \ No newline at end of file +/@ message +^- kook:neo +|% +++ state [%pro %message] +++ poke (sy %sig ~) +++ kids *kids:neo +++ deps *deps:neo +++ form + ^- form:neo + |_ [=bowl:neo =aeon:neo =stud:neo state-vase=vase] + +* state !<(message state-vase) + ++ init + |= old=(unit pail:neo) + ^- (quip card:neo pail:neo) + ?~ old + ~| "No message contents for {}" + !! + =/ new-message + !<(message q:(need old)) + :_ [%message !>(new-message)] + :~ :- #/[p/our.bowl]/home/notifications + [%poke [%notification !>([%.y now.bowl here.bowl contents.new-message])]] + == + ++ poke + |= [=stud:neo vaz=vase] + ^- (quip card:neo pail:neo) + [~ [%message !>(state)]] + -- +-- \ No newline at end of file From 1cf1e7fbdb2f6a518e4657b043aeeff5f13cf936 Mon Sep 17 00:00:00 2001 From: bonbud-macryg Date: Tue, 30 Jul 2024 15:39:51 +0100 Subject: [PATCH 25/46] Don't notify us about our own messages --- pkg/arvo/neo/cod/std/src/imp/message.hoon | 2 ++ 1 file changed, 2 insertions(+) diff --git a/pkg/arvo/neo/cod/std/src/imp/message.hoon b/pkg/arvo/neo/cod/std/src/imp/message.hoon index a57cb6c401..2e4e8c361a 100644 --- a/pkg/arvo/neo/cod/std/src/imp/message.hoon +++ b/pkg/arvo/neo/cod/std/src/imp/message.hoon @@ -18,6 +18,8 @@ =/ new-message !<(message q:(need old)) :_ [%message !>(new-message)] + ?: =(our.bowl from.new-message) + ~ :~ :- #/[p/our.bowl]/home/notifications [%poke [%notification !>([%.y now.bowl here.bowl contents.new-message])]] == From 13d7d6a35d0ae64cdc45cbb1bd2afb979a67217c Mon Sep 17 00:00:00 2001 From: bonbud-macryg Date: Wed, 31 Jul 2024 09:58:50 +0100 Subject: [PATCH 26/46] Add destination pith to pro/notification --- pkg/arvo/neo/cod/std/src/imp/notifications.hoon | 8 ++++---- pkg/arvo/neo/cod/std/src/pro/notification.hoon | 2 +- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/pkg/arvo/neo/cod/std/src/imp/notifications.hoon b/pkg/arvo/neo/cod/std/src/imp/notifications.hoon index a64332e95e..80d852af6d 100644 --- a/pkg/arvo/neo/cod/std/src/imp/notifications.hoon +++ b/pkg/arvo/neo/cod/std/src/imp/notifications.hoon @@ -88,19 +88,19 @@ =/ not !<(notification vaz) ?< =('' cord.not) ?< (gth time.not now.bowl) - ?> =(pith.src.bowl (tail pith.not)) + ?> =(pith.src.bowl (tail src.not)) =/ config !< notifications-config q.pail:(need (~(get by ~(tar of:neo kids.bowl)) (state not))) :_ [%notifications-controller !>(state)] - ?: (has-pith-in kill.config pith.not) + ?: (has-pith-in kill.config src.not) ~ - ?: (has-pith-in mute.config pith.not) + ?: (has-pith-in mute.config src.not) =. flag.not %.y :~ :- (welp here.bowl ~[[da/now.bowl]]) [%make %notification `[%notification !>(not)] ~] == - ?: (has-pith-in buzz.config pith.not) + ?: (has-pith-in buzz.config src.not) =. flag.not %.y :~ :- (welp here.bowl ~[[da/now.bowl]]) [%make %notification `[%notification !>(not)] ~] diff --git a/pkg/arvo/neo/cod/std/src/pro/notification.hoon b/pkg/arvo/neo/cod/std/src/pro/notification.hoon index 332651eab8..b0a4cce80c 100644 --- a/pkg/arvo/neo/cod/std/src/pro/notification.hoon +++ b/pkg/arvo/neo/cod/std/src/pro/notification.hoon @@ -1 +1 @@ -,[=flag =time =pith =cord] +,[=flag =time src=pith dst=pith =cord] From c1a2235b051b97d3727b955399f1c7a3990e697c Mon Sep 17 00:00:00 2001 From: bonbud-macryg Date: Wed, 31 Jul 2024 11:51:53 +0100 Subject: [PATCH 27/46] Implement notification dst --- pkg/arvo/neo/cod/std/src/imp/message.hoon | 2 +- pkg/arvo/neo/cod/std/src/imp/notification.hoon | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/pkg/arvo/neo/cod/std/src/imp/message.hoon b/pkg/arvo/neo/cod/std/src/imp/message.hoon index 2e4e8c361a..e097be6ea2 100644 --- a/pkg/arvo/neo/cod/std/src/imp/message.hoon +++ b/pkg/arvo/neo/cod/std/src/imp/message.hoon @@ -21,7 +21,7 @@ ?: =(our.bowl from.new-message) ~ :~ :- #/[p/our.bowl]/home/notifications - [%poke [%notification !>([%.y now.bowl here.bowl contents.new-message])]] + [%poke [%notification !>([%.y now.bowl here.bowl here.bowl contents.new-message])]] == ++ poke |= [=stud:neo vaz=vase] diff --git a/pkg/arvo/neo/cod/std/src/imp/notification.hoon b/pkg/arvo/neo/cod/std/src/imp/notification.hoon index 259cedb003..74342ed218 100644 --- a/pkg/arvo/neo/cod/std/src/imp/notification.hoon +++ b/pkg/arvo/neo/cod/std/src/imp/notification.hoon @@ -28,6 +28,6 @@ ^- (quip card:neo pail:neo) ?> =(stud %flag) ?> =(our.bowl ship.src.bowl) - [~ [%notification !>([!<(flag vaz) time.state pith.state cord.state])]] + [~ [%notification !>([!<(flag vaz) time.state src.state dst.state cord.state])]] -- -- From 068d06ce5da3276e0a0124f38c23888abdcb673c Mon Sep 17 00:00:00 2001 From: bonbud-macryg Date: Thu, 1 Aug 2024 13:54:54 +0100 Subject: [PATCH 28/46] Add comment about json --- pkg/arvo/neo/cod/std/src/imp/notifications.hoon | 1 + 1 file changed, 1 insertion(+) diff --git a/pkg/arvo/neo/cod/std/src/imp/notifications.hoon b/pkg/arvo/neo/cod/std/src/imp/notifications.hoon index 80d852af6d..0c42b4cdce 100644 --- a/pkg/arvo/neo/cod/std/src/imp/notifications.hoon +++ b/pkg/arvo/neo/cod/std/src/imp/notifications.hoon @@ -69,6 +69,7 @@ %notifications-controller [~ [%notifications-controller vaz]] :: + :: XX should sanity-check json %json :_ [%notifications-controller !>(state)] =/ cred !<(json vaz) From e72d53bd3975588bd44301deeaedaf398be475b5 Mon Sep 17 00:00:00 2001 From: bonbud-macryg Date: Thu, 1 Aug 2024 13:57:38 +0100 Subject: [PATCH 29/46] Remove push notification stuff from sky-htmx --- pkg/arvo/neo/cod/std/src/con/sky-htmx.hoon | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/pkg/arvo/neo/cod/std/src/con/sky-htmx.hoon b/pkg/arvo/neo/cod/std/src/con/sky-htmx.hoon index 5500732187..fa2d038c3a 100644 --- a/pkg/arvo/neo/cod/std/src/con/sky-htmx.hoon +++ b/pkg/arvo/neo/cod/std/src/con/sky-htmx.hoon @@ -145,6 +145,7 @@ ======= ;script: {(trip a-i-r)} ;script: {(trip date-now)} +<<<<<<< HEAD :: :: set up push notifications for this browser ;script @@ -179,6 +180,8 @@ ''' == >>>>>>> 13d77f915b (Draft frontend code) +======= +>>>>>>> a9b223316b (Remove push notification stuff from sky-htmx) ;+ favicon ;+ manifest == @@ -195,8 +198,11 @@ ;+ eye ;+ menu-btn-style ;+ theme-style +<<<<<<< HEAD ;+ notifications-subscription >>>>>>> 13d77f915b (Draft frontend code) +======= +>>>>>>> a9b223316b (Remove push notification stuff from sky-htmx) == == -- From 07e3676a65c0c5a7dcb7e3eb42dac500edba06cc Mon Sep 17 00:00:00 2001 From: bonbud-macryg Date: Thu, 1 Aug 2024 14:00:02 +0100 Subject: [PATCH 30/46] Remove push JS files from backend --- pkg/arvo/neo/cod/std/src/fil/push-sw.js | 14 - pkg/arvo/neo/cod/std/src/fil/web-push.js | 9535 ---------------------- 2 files changed, 9549 deletions(-) delete mode 100644 pkg/arvo/neo/cod/std/src/fil/push-sw.js delete mode 100644 pkg/arvo/neo/cod/std/src/fil/web-push.js diff --git a/pkg/arvo/neo/cod/std/src/fil/push-sw.js b/pkg/arvo/neo/cod/std/src/fil/push-sw.js deleted file mode 100644 index 2bd3dabe36..0000000000 --- a/pkg/arvo/neo/cod/std/src/fil/push-sw.js +++ /dev/null @@ -1,14 +0,0 @@ -self.addEventListener('push', function(e) { - var options = { - body: 'This notification was generated from a push!', - icon: 'https://ewr1.vultrobjects.com/urbit/hastuc-dibtux/2024.4.30..2.37.9..bae1.47ae.147a.e147-IMG_5592.jpeg', - vibrate: [100, 50, 100], - data: { - dateOfArrival: Date.now(), - primaryKey: '2' - } - }; - e.waitUntil( - self.registration.showNotification('Hello world!', options) - ); -}); \ No newline at end of file diff --git a/pkg/arvo/neo/cod/std/src/fil/web-push.js b/pkg/arvo/neo/cod/std/src/fil/web-push.js deleted file mode 100644 index 5fcc98e70e..0000000000 --- a/pkg/arvo/neo/cod/std/src/fil/web-push.js +++ /dev/null @@ -1,9535 +0,0 @@ -/******/ (() => { // webpackBootstrap -/******/ var __webpack_modules__ = ({ - -/***/ 8073: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - -"use strict"; - -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.req = exports.json = exports.toBuffer = void 0; -const http = __importStar(__nccwpck_require__(3685)); -const https = __importStar(__nccwpck_require__(5687)); -async function toBuffer(stream) { - let length = 0; - const chunks = []; - for await (const chunk of stream) { - length += chunk.length; - chunks.push(chunk); - } - return Buffer.concat(chunks, length); -} -exports.toBuffer = toBuffer; -// eslint-disable-next-line @typescript-eslint/no-explicit-any -async function json(stream) { - const buf = await toBuffer(stream); - const str = buf.toString('utf8'); - try { - return JSON.parse(str); - } - catch (_err) { - const err = _err; - err.message += ` (input: ${str})`; - throw err; - } -} -exports.json = json; -function req(url, opts = {}) { - const href = typeof url === 'string' ? url : url.href; - const req = (href.startsWith('https:') ? https : http).request(url, opts); - const promise = new Promise((resolve, reject) => { - req - .once('response', resolve) - .once('error', reject) - .end(); - }); - req.then = promise.then.bind(promise); - return req; -} -exports.req = req; -//# sourceMappingURL=helpers.js.map - -/***/ }), - -/***/ 7111: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - -"use strict"; - -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -var __exportStar = (this && this.__exportStar) || function(m, exports) { - for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.Agent = void 0; -const net = __importStar(__nccwpck_require__(1808)); -const http = __importStar(__nccwpck_require__(3685)); -const https_1 = __nccwpck_require__(5687); -__exportStar(__nccwpck_require__(8073), exports); -const INTERNAL = Symbol('AgentBaseInternalState'); -class Agent extends http.Agent { - constructor(opts) { - super(opts); - this[INTERNAL] = {}; - } - /** - * Determine whether this is an `http` or `https` request. - */ - isSecureEndpoint(options) { - if (options) { - // First check the `secureEndpoint` property explicitly, since this - // means that a parent `Agent` is "passing through" to this instance. - // eslint-disable-next-line @typescript-eslint/no-explicit-any - if (typeof options.secureEndpoint === 'boolean') { - return options.secureEndpoint; - } - // If no explicit `secure` endpoint, check if `protocol` property is - // set. This will usually be the case since using a full string URL - // or `URL` instance should be the most common usage. - if (typeof options.protocol === 'string') { - return options.protocol === 'https:'; - } - } - // Finally, if no `protocol` property was set, then fall back to - // checking the stack trace of the current call stack, and try to - // detect the "https" module. - const { stack } = new Error(); - if (typeof stack !== 'string') - return false; - return stack - .split('\n') - .some((l) => l.indexOf('(https.js:') !== -1 || - l.indexOf('node:https:') !== -1); - } - // In order to support async signatures in `connect()` and Node's native - // connection pooling in `http.Agent`, the array of sockets for each origin - // has to be updated synchronously. This is so the length of the array is - // accurate when `addRequest()` is next called. We achieve this by creating a - // fake socket and adding it to `sockets[origin]` and incrementing - // `totalSocketCount`. - incrementSockets(name) { - // If `maxSockets` and `maxTotalSockets` are both Infinity then there is no - // need to create a fake socket because Node.js native connection pooling - // will never be invoked. - if (this.maxSockets === Infinity && this.maxTotalSockets === Infinity) { - return null; - } - // All instances of `sockets` are expected TypeScript errors. The - // alternative is to add it as a private property of this class but that - // will break TypeScript subclassing. - if (!this.sockets[name]) { - // @ts-expect-error `sockets` is readonly in `@types/node` - this.sockets[name] = []; - } - const fakeSocket = new net.Socket({ writable: false }); - this.sockets[name].push(fakeSocket); - // @ts-expect-error `totalSocketCount` isn't defined in `@types/node` - this.totalSocketCount++; - return fakeSocket; - } - decrementSockets(name, socket) { - if (!this.sockets[name] || socket === null) { - return; - } - const sockets = this.sockets[name]; - const index = sockets.indexOf(socket); - if (index !== -1) { - sockets.splice(index, 1); - // @ts-expect-error `totalSocketCount` isn't defined in `@types/node` - this.totalSocketCount--; - if (sockets.length === 0) { - // @ts-expect-error `sockets` is readonly in `@types/node` - delete this.sockets[name]; - } - } - } - // In order to properly update the socket pool, we need to call `getName()` on - // the core `https.Agent` if it is a secureEndpoint. - getName(options) { - const secureEndpoint = typeof options.secureEndpoint === 'boolean' - ? options.secureEndpoint - : this.isSecureEndpoint(options); - if (secureEndpoint) { - // @ts-expect-error `getName()` isn't defined in `@types/node` - return https_1.Agent.prototype.getName.call(this, options); - } - // @ts-expect-error `getName()` isn't defined in `@types/node` - return super.getName(options); - } - createSocket(req, options, cb) { - const connectOpts = { - ...options, - secureEndpoint: this.isSecureEndpoint(options), - }; - const name = this.getName(connectOpts); - const fakeSocket = this.incrementSockets(name); - Promise.resolve() - .then(() => this.connect(req, connectOpts)) - .then((socket) => { - this.decrementSockets(name, fakeSocket); - if (socket instanceof http.Agent) { - // @ts-expect-error `addRequest()` isn't defined in `@types/node` - return socket.addRequest(req, connectOpts); - } - this[INTERNAL].currentSocket = socket; - // @ts-expect-error `createSocket()` isn't defined in `@types/node` - super.createSocket(req, options, cb); - }, (err) => { - this.decrementSockets(name, fakeSocket); - cb(err); - }); - } - createConnection() { - const socket = this[INTERNAL].currentSocket; - this[INTERNAL].currentSocket = undefined; - if (!socket) { - throw new Error('No socket was returned in the `connect()` function'); - } - return socket; - } - get defaultPort() { - return (this[INTERNAL].defaultPort ?? - (this.protocol === 'https:' ? 443 : 80)); - } - set defaultPort(v) { - if (this[INTERNAL]) { - this[INTERNAL].defaultPort = v; - } - } - get protocol() { - return (this[INTERNAL].protocol ?? - (this.isSecureEndpoint() ? 'https:' : 'http:')); - } - set protocol(v) { - if (this[INTERNAL]) { - this[INTERNAL].protocol = v; - } - } -} -exports.Agent = Agent; -//# sourceMappingURL=index.js.map - -/***/ }), - -/***/ 731: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - - -const asn1 = exports; - -asn1.bignum = __nccwpck_require__(5071); - -asn1.define = (__nccwpck_require__(9819).define); -asn1.base = __nccwpck_require__(7784); -asn1.constants = __nccwpck_require__(7723); -asn1.decoders = __nccwpck_require__(9921); -asn1.encoders = __nccwpck_require__(3650); - - -/***/ }), - -/***/ 9819: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - - -const encoders = __nccwpck_require__(3650); -const decoders = __nccwpck_require__(9921); -const inherits = __nccwpck_require__(9581); - -const api = exports; - -api.define = function define(name, body) { - return new Entity(name, body); -}; - -function Entity(name, body) { - this.name = name; - this.body = body; - - this.decoders = {}; - this.encoders = {}; -} - -Entity.prototype._createNamed = function createNamed(Base) { - const name = this.name; - - function Generated(entity) { - this._initNamed(entity, name); - } - inherits(Generated, Base); - Generated.prototype._initNamed = function _initNamed(entity, name) { - Base.call(this, entity, name); - }; - - return new Generated(this); -}; - -Entity.prototype._getDecoder = function _getDecoder(enc) { - enc = enc || 'der'; - // Lazily create decoder - if (!this.decoders.hasOwnProperty(enc)) - this.decoders[enc] = this._createNamed(decoders[enc]); - return this.decoders[enc]; -}; - -Entity.prototype.decode = function decode(data, enc, options) { - return this._getDecoder(enc).decode(data, options); -}; - -Entity.prototype._getEncoder = function _getEncoder(enc) { - enc = enc || 'der'; - // Lazily create encoder - if (!this.encoders.hasOwnProperty(enc)) - this.encoders[enc] = this._createNamed(encoders[enc]); - return this.encoders[enc]; -}; - -Entity.prototype.encode = function encode(data, enc, /* internal */ reporter) { - return this._getEncoder(enc).encode(data, reporter); -}; - - -/***/ }), - -/***/ 754: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - - -const inherits = __nccwpck_require__(9581); -const Reporter = (__nccwpck_require__(8154)/* .Reporter */ .b); -const Buffer = (__nccwpck_require__(5827).Buffer); - -function DecoderBuffer(base, options) { - Reporter.call(this, options); - if (!Buffer.isBuffer(base)) { - this.error('Input not Buffer'); - return; - } - - this.base = base; - this.offset = 0; - this.length = base.length; -} -inherits(DecoderBuffer, Reporter); -exports.C = DecoderBuffer; - -DecoderBuffer.isDecoderBuffer = function isDecoderBuffer(data) { - if (data instanceof DecoderBuffer) { - return true; - } - - // Or accept compatible API - const isCompatible = typeof data === 'object' && - Buffer.isBuffer(data.base) && - data.constructor.name === 'DecoderBuffer' && - typeof data.offset === 'number' && - typeof data.length === 'number' && - typeof data.save === 'function' && - typeof data.restore === 'function' && - typeof data.isEmpty === 'function' && - typeof data.readUInt8 === 'function' && - typeof data.skip === 'function' && - typeof data.raw === 'function'; - - return isCompatible; -}; - -DecoderBuffer.prototype.save = function save() { - return { offset: this.offset, reporter: Reporter.prototype.save.call(this) }; -}; - -DecoderBuffer.prototype.restore = function restore(save) { - // Return skipped data - const res = new DecoderBuffer(this.base); - res.offset = save.offset; - res.length = this.offset; - - this.offset = save.offset; - Reporter.prototype.restore.call(this, save.reporter); - - return res; -}; - -DecoderBuffer.prototype.isEmpty = function isEmpty() { - return this.offset === this.length; -}; - -DecoderBuffer.prototype.readUInt8 = function readUInt8(fail) { - if (this.offset + 1 <= this.length) - return this.base.readUInt8(this.offset++, true); - else - return this.error(fail || 'DecoderBuffer overrun'); -}; - -DecoderBuffer.prototype.skip = function skip(bytes, fail) { - if (!(this.offset + bytes <= this.length)) - return this.error(fail || 'DecoderBuffer overrun'); - - const res = new DecoderBuffer(this.base); - - // Share reporter state - res._reporterState = this._reporterState; - - res.offset = this.offset; - res.length = this.offset + bytes; - this.offset += bytes; - return res; -}; - -DecoderBuffer.prototype.raw = function raw(save) { - return this.base.slice(save ? save.offset : this.offset, this.length); -}; - -function EncoderBuffer(value, reporter) { - if (Array.isArray(value)) { - this.length = 0; - this.value = value.map(function(item) { - if (!EncoderBuffer.isEncoderBuffer(item)) - item = new EncoderBuffer(item, reporter); - this.length += item.length; - return item; - }, this); - } else if (typeof value === 'number') { - if (!(0 <= value && value <= 0xff)) - return reporter.error('non-byte EncoderBuffer value'); - this.value = value; - this.length = 1; - } else if (typeof value === 'string') { - this.value = value; - this.length = Buffer.byteLength(value); - } else if (Buffer.isBuffer(value)) { - this.value = value; - this.length = value.length; - } else { - return reporter.error('Unsupported type: ' + typeof value); - } -} -exports.R = EncoderBuffer; - -EncoderBuffer.isEncoderBuffer = function isEncoderBuffer(data) { - if (data instanceof EncoderBuffer) { - return true; - } - - // Or accept compatible API - const isCompatible = typeof data === 'object' && - data.constructor.name === 'EncoderBuffer' && - typeof data.length === 'number' && - typeof data.join === 'function'; - - return isCompatible; -}; - -EncoderBuffer.prototype.join = function join(out, offset) { - if (!out) - out = Buffer.alloc(this.length); - if (!offset) - offset = 0; - - if (this.length === 0) - return out; - - if (Array.isArray(this.value)) { - this.value.forEach(function(item) { - item.join(out, offset); - offset += item.length; - }); - } else { - if (typeof this.value === 'number') - out[offset] = this.value; - else if (typeof this.value === 'string') - out.write(this.value, offset); - else if (Buffer.isBuffer(this.value)) - this.value.copy(out, offset); - offset += this.length; - } - - return out; -}; - - -/***/ }), - -/***/ 7784: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - - -const base = exports; - -base.Reporter = (__nccwpck_require__(8154)/* .Reporter */ .b); -base.DecoderBuffer = (__nccwpck_require__(754)/* .DecoderBuffer */ .C); -base.EncoderBuffer = (__nccwpck_require__(754)/* .EncoderBuffer */ .R); -base.Node = __nccwpck_require__(5956); - - -/***/ }), - -/***/ 5956: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -const Reporter = (__nccwpck_require__(8154)/* .Reporter */ .b); -const EncoderBuffer = (__nccwpck_require__(754)/* .EncoderBuffer */ .R); -const DecoderBuffer = (__nccwpck_require__(754)/* .DecoderBuffer */ .C); -const assert = __nccwpck_require__(2104); - -// Supported tags -const tags = [ - 'seq', 'seqof', 'set', 'setof', 'objid', 'bool', - 'gentime', 'utctime', 'null_', 'enum', 'int', 'objDesc', - 'bitstr', 'bmpstr', 'charstr', 'genstr', 'graphstr', 'ia5str', 'iso646str', - 'numstr', 'octstr', 'printstr', 't61str', 'unistr', 'utf8str', 'videostr' -]; - -// Public methods list -const methods = [ - 'key', 'obj', 'use', 'optional', 'explicit', 'implicit', 'def', 'choice', - 'any', 'contains' -].concat(tags); - -// Overrided methods list -const overrided = [ - '_peekTag', '_decodeTag', '_use', - '_decodeStr', '_decodeObjid', '_decodeTime', - '_decodeNull', '_decodeInt', '_decodeBool', '_decodeList', - - '_encodeComposite', '_encodeStr', '_encodeObjid', '_encodeTime', - '_encodeNull', '_encodeInt', '_encodeBool' -]; - -function Node(enc, parent, name) { - const state = {}; - this._baseState = state; - - state.name = name; - state.enc = enc; - - state.parent = parent || null; - state.children = null; - - // State - state.tag = null; - state.args = null; - state.reverseArgs = null; - state.choice = null; - state.optional = false; - state.any = false; - state.obj = false; - state.use = null; - state.useDecoder = null; - state.key = null; - state['default'] = null; - state.explicit = null; - state.implicit = null; - state.contains = null; - - // Should create new instance on each method - if (!state.parent) { - state.children = []; - this._wrap(); - } -} -module.exports = Node; - -const stateProps = [ - 'enc', 'parent', 'children', 'tag', 'args', 'reverseArgs', 'choice', - 'optional', 'any', 'obj', 'use', 'alteredUse', 'key', 'default', 'explicit', - 'implicit', 'contains' -]; - -Node.prototype.clone = function clone() { - const state = this._baseState; - const cstate = {}; - stateProps.forEach(function(prop) { - cstate[prop] = state[prop]; - }); - const res = new this.constructor(cstate.parent); - res._baseState = cstate; - return res; -}; - -Node.prototype._wrap = function wrap() { - const state = this._baseState; - methods.forEach(function(method) { - this[method] = function _wrappedMethod() { - const clone = new this.constructor(this); - state.children.push(clone); - return clone[method].apply(clone, arguments); - }; - }, this); -}; - -Node.prototype._init = function init(body) { - const state = this._baseState; - - assert(state.parent === null); - body.call(this); - - // Filter children - state.children = state.children.filter(function(child) { - return child._baseState.parent === this; - }, this); - assert.equal(state.children.length, 1, 'Root node can have only one child'); -}; - -Node.prototype._useArgs = function useArgs(args) { - const state = this._baseState; - - // Filter children and args - const children = args.filter(function(arg) { - return arg instanceof this.constructor; - }, this); - args = args.filter(function(arg) { - return !(arg instanceof this.constructor); - }, this); - - if (children.length !== 0) { - assert(state.children === null); - state.children = children; - - // Replace parent to maintain backward link - children.forEach(function(child) { - child._baseState.parent = this; - }, this); - } - if (args.length !== 0) { - assert(state.args === null); - state.args = args; - state.reverseArgs = args.map(function(arg) { - if (typeof arg !== 'object' || arg.constructor !== Object) - return arg; - - const res = {}; - Object.keys(arg).forEach(function(key) { - if (key == (key | 0)) - key |= 0; - const value = arg[key]; - res[value] = key; - }); - return res; - }); - } -}; - -// -// Overrided methods -// - -overrided.forEach(function(method) { - Node.prototype[method] = function _overrided() { - const state = this._baseState; - throw new Error(method + ' not implemented for encoding: ' + state.enc); - }; -}); - -// -// Public methods -// - -tags.forEach(function(tag) { - Node.prototype[tag] = function _tagMethod() { - const state = this._baseState; - const args = Array.prototype.slice.call(arguments); - - assert(state.tag === null); - state.tag = tag; - - this._useArgs(args); - - return this; - }; -}); - -Node.prototype.use = function use(item) { - assert(item); - const state = this._baseState; - - assert(state.use === null); - state.use = item; - - return this; -}; - -Node.prototype.optional = function optional() { - const state = this._baseState; - - state.optional = true; - - return this; -}; - -Node.prototype.def = function def(val) { - const state = this._baseState; - - assert(state['default'] === null); - state['default'] = val; - state.optional = true; - - return this; -}; - -Node.prototype.explicit = function explicit(num) { - const state = this._baseState; - - assert(state.explicit === null && state.implicit === null); - state.explicit = num; - - return this; -}; - -Node.prototype.implicit = function implicit(num) { - const state = this._baseState; - - assert(state.explicit === null && state.implicit === null); - state.implicit = num; - - return this; -}; - -Node.prototype.obj = function obj() { - const state = this._baseState; - const args = Array.prototype.slice.call(arguments); - - state.obj = true; - - if (args.length !== 0) - this._useArgs(args); - - return this; -}; - -Node.prototype.key = function key(newKey) { - const state = this._baseState; - - assert(state.key === null); - state.key = newKey; - - return this; -}; - -Node.prototype.any = function any() { - const state = this._baseState; - - state.any = true; - - return this; -}; - -Node.prototype.choice = function choice(obj) { - const state = this._baseState; - - assert(state.choice === null); - state.choice = obj; - this._useArgs(Object.keys(obj).map(function(key) { - return obj[key]; - })); - - return this; -}; - -Node.prototype.contains = function contains(item) { - const state = this._baseState; - - assert(state.use === null); - state.contains = item; - - return this; -}; - -// -// Decoding -// - -Node.prototype._decode = function decode(input, options) { - const state = this._baseState; - - // Decode root node - if (state.parent === null) - return input.wrapResult(state.children[0]._decode(input, options)); - - let result = state['default']; - let present = true; - - let prevKey = null; - if (state.key !== null) - prevKey = input.enterKey(state.key); - - // Check if tag is there - if (state.optional) { - let tag = null; - if (state.explicit !== null) - tag = state.explicit; - else if (state.implicit !== null) - tag = state.implicit; - else if (state.tag !== null) - tag = state.tag; - - if (tag === null && !state.any) { - // Trial and Error - const save = input.save(); - try { - if (state.choice === null) - this._decodeGeneric(state.tag, input, options); - else - this._decodeChoice(input, options); - present = true; - } catch (e) { - present = false; - } - input.restore(save); - } else { - present = this._peekTag(input, tag, state.any); - - if (input.isError(present)) - return present; - } - } - - // Push object on stack - let prevObj; - if (state.obj && present) - prevObj = input.enterObject(); - - if (present) { - // Unwrap explicit values - if (state.explicit !== null) { - const explicit = this._decodeTag(input, state.explicit); - if (input.isError(explicit)) - return explicit; - input = explicit; - } - - const start = input.offset; - - // Unwrap implicit and normal values - if (state.use === null && state.choice === null) { - let save; - if (state.any) - save = input.save(); - const body = this._decodeTag( - input, - state.implicit !== null ? state.implicit : state.tag, - state.any - ); - if (input.isError(body)) - return body; - - if (state.any) - result = input.raw(save); - else - input = body; - } - - if (options && options.track && state.tag !== null) - options.track(input.path(), start, input.length, 'tagged'); - - if (options && options.track && state.tag !== null) - options.track(input.path(), input.offset, input.length, 'content'); - - // Select proper method for tag - if (state.any) { - // no-op - } else if (state.choice === null) { - result = this._decodeGeneric(state.tag, input, options); - } else { - result = this._decodeChoice(input, options); - } - - if (input.isError(result)) - return result; - - // Decode children - if (!state.any && state.choice === null && state.children !== null) { - state.children.forEach(function decodeChildren(child) { - // NOTE: We are ignoring errors here, to let parser continue with other - // parts of encoded data - child._decode(input, options); - }); - } - - // Decode contained/encoded by schema, only in bit or octet strings - if (state.contains && (state.tag === 'octstr' || state.tag === 'bitstr')) { - const data = new DecoderBuffer(result); - result = this._getUse(state.contains, input._reporterState.obj) - ._decode(data, options); - } - } - - // Pop object - if (state.obj && present) - result = input.leaveObject(prevObj); - - // Set key - if (state.key !== null && (result !== null || present === true)) - input.leaveKey(prevKey, state.key, result); - else if (prevKey !== null) - input.exitKey(prevKey); - - return result; -}; - -Node.prototype._decodeGeneric = function decodeGeneric(tag, input, options) { - const state = this._baseState; - - if (tag === 'seq' || tag === 'set') - return null; - if (tag === 'seqof' || tag === 'setof') - return this._decodeList(input, tag, state.args[0], options); - else if (/str$/.test(tag)) - return this._decodeStr(input, tag, options); - else if (tag === 'objid' && state.args) - return this._decodeObjid(input, state.args[0], state.args[1], options); - else if (tag === 'objid') - return this._decodeObjid(input, null, null, options); - else if (tag === 'gentime' || tag === 'utctime') - return this._decodeTime(input, tag, options); - else if (tag === 'null_') - return this._decodeNull(input, options); - else if (tag === 'bool') - return this._decodeBool(input, options); - else if (tag === 'objDesc') - return this._decodeStr(input, tag, options); - else if (tag === 'int' || tag === 'enum') - return this._decodeInt(input, state.args && state.args[0], options); - - if (state.use !== null) { - return this._getUse(state.use, input._reporterState.obj) - ._decode(input, options); - } else { - return input.error('unknown tag: ' + tag); - } -}; - -Node.prototype._getUse = function _getUse(entity, obj) { - - const state = this._baseState; - // Create altered use decoder if implicit is set - state.useDecoder = this._use(entity, obj); - assert(state.useDecoder._baseState.parent === null); - state.useDecoder = state.useDecoder._baseState.children[0]; - if (state.implicit !== state.useDecoder._baseState.implicit) { - state.useDecoder = state.useDecoder.clone(); - state.useDecoder._baseState.implicit = state.implicit; - } - return state.useDecoder; -}; - -Node.prototype._decodeChoice = function decodeChoice(input, options) { - const state = this._baseState; - let result = null; - let match = false; - - Object.keys(state.choice).some(function(key) { - const save = input.save(); - const node = state.choice[key]; - try { - const value = node._decode(input, options); - if (input.isError(value)) - return false; - - result = { type: key, value: value }; - match = true; - } catch (e) { - input.restore(save); - return false; - } - return true; - }, this); - - if (!match) - return input.error('Choice not matched'); - - return result; -}; - -// -// Encoding -// - -Node.prototype._createEncoderBuffer = function createEncoderBuffer(data) { - return new EncoderBuffer(data, this.reporter); -}; - -Node.prototype._encode = function encode(data, reporter, parent) { - const state = this._baseState; - if (state['default'] !== null && state['default'] === data) - return; - - const result = this._encodeValue(data, reporter, parent); - if (result === undefined) - return; - - if (this._skipDefault(result, reporter, parent)) - return; - - return result; -}; - -Node.prototype._encodeValue = function encode(data, reporter, parent) { - const state = this._baseState; - - // Decode root node - if (state.parent === null) - return state.children[0]._encode(data, reporter || new Reporter()); - - let result = null; - - // Set reporter to share it with a child class - this.reporter = reporter; - - // Check if data is there - if (state.optional && data === undefined) { - if (state['default'] !== null) - data = state['default']; - else - return; - } - - // Encode children first - let content = null; - let primitive = false; - if (state.any) { - // Anything that was given is translated to buffer - result = this._createEncoderBuffer(data); - } else if (state.choice) { - result = this._encodeChoice(data, reporter); - } else if (state.contains) { - content = this._getUse(state.contains, parent)._encode(data, reporter); - primitive = true; - } else if (state.children) { - content = state.children.map(function(child) { - if (child._baseState.tag === 'null_') - return child._encode(null, reporter, data); - - if (child._baseState.key === null) - return reporter.error('Child should have a key'); - const prevKey = reporter.enterKey(child._baseState.key); - - if (typeof data !== 'object') - return reporter.error('Child expected, but input is not object'); - - const res = child._encode(data[child._baseState.key], reporter, data); - reporter.leaveKey(prevKey); - - return res; - }, this).filter(function(child) { - return child; - }); - content = this._createEncoderBuffer(content); - } else { - if (state.tag === 'seqof' || state.tag === 'setof') { - // TODO(indutny): this should be thrown on DSL level - if (!(state.args && state.args.length === 1)) - return reporter.error('Too many args for : ' + state.tag); - - if (!Array.isArray(data)) - return reporter.error('seqof/setof, but data is not Array'); - - const child = this.clone(); - child._baseState.implicit = null; - content = this._createEncoderBuffer(data.map(function(item) { - const state = this._baseState; - - return this._getUse(state.args[0], data)._encode(item, reporter); - }, child)); - } else if (state.use !== null) { - result = this._getUse(state.use, parent)._encode(data, reporter); - } else { - content = this._encodePrimitive(state.tag, data); - primitive = true; - } - } - - // Encode data itself - if (!state.any && state.choice === null) { - const tag = state.implicit !== null ? state.implicit : state.tag; - const cls = state.implicit === null ? 'universal' : 'context'; - - if (tag === null) { - if (state.use === null) - reporter.error('Tag could be omitted only for .use()'); - } else { - if (state.use === null) - result = this._encodeComposite(tag, primitive, cls, content); - } - } - - // Wrap in explicit - if (state.explicit !== null) - result = this._encodeComposite(state.explicit, false, 'context', result); - - return result; -}; - -Node.prototype._encodeChoice = function encodeChoice(data, reporter) { - const state = this._baseState; - - const node = state.choice[data.type]; - if (!node) { - assert( - false, - data.type + ' not found in ' + - JSON.stringify(Object.keys(state.choice))); - } - return node._encode(data.value, reporter); -}; - -Node.prototype._encodePrimitive = function encodePrimitive(tag, data) { - const state = this._baseState; - - if (/str$/.test(tag)) - return this._encodeStr(data, tag); - else if (tag === 'objid' && state.args) - return this._encodeObjid(data, state.reverseArgs[0], state.args[1]); - else if (tag === 'objid') - return this._encodeObjid(data, null, null); - else if (tag === 'gentime' || tag === 'utctime') - return this._encodeTime(data, tag); - else if (tag === 'null_') - return this._encodeNull(); - else if (tag === 'int' || tag === 'enum') - return this._encodeInt(data, state.args && state.reverseArgs[0]); - else if (tag === 'bool') - return this._encodeBool(data); - else if (tag === 'objDesc') - return this._encodeStr(data, tag); - else - throw new Error('Unsupported tag: ' + tag); -}; - -Node.prototype._isNumstr = function isNumstr(str) { - return /^[0-9 ]*$/.test(str); -}; - -Node.prototype._isPrintstr = function isPrintstr(str) { - return /^[A-Za-z0-9 '()+,-./:=?]*$/.test(str); -}; - - -/***/ }), - -/***/ 8154: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - - -const inherits = __nccwpck_require__(9581); - -function Reporter(options) { - this._reporterState = { - obj: null, - path: [], - options: options || {}, - errors: [] - }; -} -exports.b = Reporter; - -Reporter.prototype.isError = function isError(obj) { - return obj instanceof ReporterError; -}; - -Reporter.prototype.save = function save() { - const state = this._reporterState; - - return { obj: state.obj, pathLen: state.path.length }; -}; - -Reporter.prototype.restore = function restore(data) { - const state = this._reporterState; - - state.obj = data.obj; - state.path = state.path.slice(0, data.pathLen); -}; - -Reporter.prototype.enterKey = function enterKey(key) { - return this._reporterState.path.push(key); -}; - -Reporter.prototype.exitKey = function exitKey(index) { - const state = this._reporterState; - - state.path = state.path.slice(0, index - 1); -}; - -Reporter.prototype.leaveKey = function leaveKey(index, key, value) { - const state = this._reporterState; - - this.exitKey(index); - if (state.obj !== null) - state.obj[key] = value; -}; - -Reporter.prototype.path = function path() { - return this._reporterState.path.join('/'); -}; - -Reporter.prototype.enterObject = function enterObject() { - const state = this._reporterState; - - const prev = state.obj; - state.obj = {}; - return prev; -}; - -Reporter.prototype.leaveObject = function leaveObject(prev) { - const state = this._reporterState; - - const now = state.obj; - state.obj = prev; - return now; -}; - -Reporter.prototype.error = function error(msg) { - let err; - const state = this._reporterState; - - const inherited = msg instanceof ReporterError; - if (inherited) { - err = msg; - } else { - err = new ReporterError(state.path.map(function(elem) { - return '[' + JSON.stringify(elem) + ']'; - }).join(''), msg.message || msg, msg.stack); - } - - if (!state.options.partial) - throw err; - - if (!inherited) - state.errors.push(err); - - return err; -}; - -Reporter.prototype.wrapResult = function wrapResult(result) { - const state = this._reporterState; - if (!state.options.partial) - return result; - - return { - result: this.isError(result) ? null : result, - errors: state.errors - }; -}; - -function ReporterError(path, msg) { - this.path = path; - this.rethrow(msg); -} -inherits(ReporterError, Error); - -ReporterError.prototype.rethrow = function rethrow(msg) { - this.message = msg + ' at: ' + (this.path || '(shallow)'); - if (Error.captureStackTrace) - Error.captureStackTrace(this, ReporterError); - - if (!this.stack) { - try { - // IE only adds stack when thrown - throw new Error(this.message); - } catch (e) { - this.stack = e.stack; - } - } - return this; -}; - - -/***/ }), - -/***/ 9115: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - - -// Helper -function reverse(map) { - const res = {}; - - Object.keys(map).forEach(function(key) { - // Convert key to integer if it is stringified - if ((key | 0) == key) - key = key | 0; - - const value = map[key]; - res[value] = key; - }); - - return res; -} - -exports.tagClass = { - 0: 'universal', - 1: 'application', - 2: 'context', - 3: 'private' -}; -exports.tagClassByName = reverse(exports.tagClass); - -exports.tag = { - 0x00: 'end', - 0x01: 'bool', - 0x02: 'int', - 0x03: 'bitstr', - 0x04: 'octstr', - 0x05: 'null_', - 0x06: 'objid', - 0x07: 'objDesc', - 0x08: 'external', - 0x09: 'real', - 0x0a: 'enum', - 0x0b: 'embed', - 0x0c: 'utf8str', - 0x0d: 'relativeOid', - 0x10: 'seq', - 0x11: 'set', - 0x12: 'numstr', - 0x13: 'printstr', - 0x14: 't61str', - 0x15: 'videostr', - 0x16: 'ia5str', - 0x17: 'utctime', - 0x18: 'gentime', - 0x19: 'graphstr', - 0x1a: 'iso646str', - 0x1b: 'genstr', - 0x1c: 'unistr', - 0x1d: 'charstr', - 0x1e: 'bmpstr' -}; -exports.tagByName = reverse(exports.tag); - - -/***/ }), - -/***/ 7723: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - - -const constants = exports; - -// Helper -constants._reverse = function reverse(map) { - const res = {}; - - Object.keys(map).forEach(function(key) { - // Convert key to integer if it is stringified - if ((key | 0) == key) - key = key | 0; - - const value = map[key]; - res[value] = key; - }); - - return res; -}; - -constants.der = __nccwpck_require__(9115); - - -/***/ }), - -/***/ 126: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -const inherits = __nccwpck_require__(9581); - -const bignum = __nccwpck_require__(5071); -const DecoderBuffer = (__nccwpck_require__(754)/* .DecoderBuffer */ .C); -const Node = __nccwpck_require__(5956); - -// Import DER constants -const der = __nccwpck_require__(9115); - -function DERDecoder(entity) { - this.enc = 'der'; - this.name = entity.name; - this.entity = entity; - - // Construct base tree - this.tree = new DERNode(); - this.tree._init(entity.body); -} -module.exports = DERDecoder; - -DERDecoder.prototype.decode = function decode(data, options) { - if (!DecoderBuffer.isDecoderBuffer(data)) { - data = new DecoderBuffer(data, options); - } - - return this.tree._decode(data, options); -}; - -// Tree methods - -function DERNode(parent) { - Node.call(this, 'der', parent); -} -inherits(DERNode, Node); - -DERNode.prototype._peekTag = function peekTag(buffer, tag, any) { - if (buffer.isEmpty()) - return false; - - const state = buffer.save(); - const decodedTag = derDecodeTag(buffer, 'Failed to peek tag: "' + tag + '"'); - if (buffer.isError(decodedTag)) - return decodedTag; - - buffer.restore(state); - - return decodedTag.tag === tag || decodedTag.tagStr === tag || - (decodedTag.tagStr + 'of') === tag || any; -}; - -DERNode.prototype._decodeTag = function decodeTag(buffer, tag, any) { - const decodedTag = derDecodeTag(buffer, - 'Failed to decode tag of "' + tag + '"'); - if (buffer.isError(decodedTag)) - return decodedTag; - - let len = derDecodeLen(buffer, - decodedTag.primitive, - 'Failed to get length of "' + tag + '"'); - - // Failure - if (buffer.isError(len)) - return len; - - if (!any && - decodedTag.tag !== tag && - decodedTag.tagStr !== tag && - decodedTag.tagStr + 'of' !== tag) { - return buffer.error('Failed to match tag: "' + tag + '"'); - } - - if (decodedTag.primitive || len !== null) - return buffer.skip(len, 'Failed to match body of: "' + tag + '"'); - - // Indefinite length... find END tag - const state = buffer.save(); - const res = this._skipUntilEnd( - buffer, - 'Failed to skip indefinite length body: "' + this.tag + '"'); - if (buffer.isError(res)) - return res; - - len = buffer.offset - state.offset; - buffer.restore(state); - return buffer.skip(len, 'Failed to match body of: "' + tag + '"'); -}; - -DERNode.prototype._skipUntilEnd = function skipUntilEnd(buffer, fail) { - for (;;) { - const tag = derDecodeTag(buffer, fail); - if (buffer.isError(tag)) - return tag; - const len = derDecodeLen(buffer, tag.primitive, fail); - if (buffer.isError(len)) - return len; - - let res; - if (tag.primitive || len !== null) - res = buffer.skip(len); - else - res = this._skipUntilEnd(buffer, fail); - - // Failure - if (buffer.isError(res)) - return res; - - if (tag.tagStr === 'end') - break; - } -}; - -DERNode.prototype._decodeList = function decodeList(buffer, tag, decoder, - options) { - const result = []; - while (!buffer.isEmpty()) { - const possibleEnd = this._peekTag(buffer, 'end'); - if (buffer.isError(possibleEnd)) - return possibleEnd; - - const res = decoder.decode(buffer, 'der', options); - if (buffer.isError(res) && possibleEnd) - break; - result.push(res); - } - return result; -}; - -DERNode.prototype._decodeStr = function decodeStr(buffer, tag) { - if (tag === 'bitstr') { - const unused = buffer.readUInt8(); - if (buffer.isError(unused)) - return unused; - return { unused: unused, data: buffer.raw() }; - } else if (tag === 'bmpstr') { - const raw = buffer.raw(); - if (raw.length % 2 === 1) - return buffer.error('Decoding of string type: bmpstr length mismatch'); - - let str = ''; - for (let i = 0; i < raw.length / 2; i++) { - str += String.fromCharCode(raw.readUInt16BE(i * 2)); - } - return str; - } else if (tag === 'numstr') { - const numstr = buffer.raw().toString('ascii'); - if (!this._isNumstr(numstr)) { - return buffer.error('Decoding of string type: ' + - 'numstr unsupported characters'); - } - return numstr; - } else if (tag === 'octstr') { - return buffer.raw(); - } else if (tag === 'objDesc') { - return buffer.raw(); - } else if (tag === 'printstr') { - const printstr = buffer.raw().toString('ascii'); - if (!this._isPrintstr(printstr)) { - return buffer.error('Decoding of string type: ' + - 'printstr unsupported characters'); - } - return printstr; - } else if (/str$/.test(tag)) { - return buffer.raw().toString(); - } else { - return buffer.error('Decoding of string type: ' + tag + ' unsupported'); - } -}; - -DERNode.prototype._decodeObjid = function decodeObjid(buffer, values, relative) { - let result; - const identifiers = []; - let ident = 0; - let subident = 0; - while (!buffer.isEmpty()) { - subident = buffer.readUInt8(); - ident <<= 7; - ident |= subident & 0x7f; - if ((subident & 0x80) === 0) { - identifiers.push(ident); - ident = 0; - } - } - if (subident & 0x80) - identifiers.push(ident); - - const first = (identifiers[0] / 40) | 0; - const second = identifiers[0] % 40; - - if (relative) - result = identifiers; - else - result = [first, second].concat(identifiers.slice(1)); - - if (values) { - let tmp = values[result.join(' ')]; - if (tmp === undefined) - tmp = values[result.join('.')]; - if (tmp !== undefined) - result = tmp; - } - - return result; -}; - -DERNode.prototype._decodeTime = function decodeTime(buffer, tag) { - const str = buffer.raw().toString(); - - let year; - let mon; - let day; - let hour; - let min; - let sec; - if (tag === 'gentime') { - year = str.slice(0, 4) | 0; - mon = str.slice(4, 6) | 0; - day = str.slice(6, 8) | 0; - hour = str.slice(8, 10) | 0; - min = str.slice(10, 12) | 0; - sec = str.slice(12, 14) | 0; - } else if (tag === 'utctime') { - year = str.slice(0, 2) | 0; - mon = str.slice(2, 4) | 0; - day = str.slice(4, 6) | 0; - hour = str.slice(6, 8) | 0; - min = str.slice(8, 10) | 0; - sec = str.slice(10, 12) | 0; - if (year < 70) - year = 2000 + year; - else - year = 1900 + year; - } else { - return buffer.error('Decoding ' + tag + ' time is not supported yet'); - } - - return Date.UTC(year, mon - 1, day, hour, min, sec, 0); -}; - -DERNode.prototype._decodeNull = function decodeNull() { - return null; -}; - -DERNode.prototype._decodeBool = function decodeBool(buffer) { - const res = buffer.readUInt8(); - if (buffer.isError(res)) - return res; - else - return res !== 0; -}; - -DERNode.prototype._decodeInt = function decodeInt(buffer, values) { - // Bigint, return as it is (assume big endian) - const raw = buffer.raw(); - let res = new bignum(raw); - - if (values) - res = values[res.toString(10)] || res; - - return res; -}; - -DERNode.prototype._use = function use(entity, obj) { - if (typeof entity === 'function') - entity = entity(obj); - return entity._getDecoder('der').tree; -}; - -// Utility methods - -function derDecodeTag(buf, fail) { - let tag = buf.readUInt8(fail); - if (buf.isError(tag)) - return tag; - - const cls = der.tagClass[tag >> 6]; - const primitive = (tag & 0x20) === 0; - - // Multi-octet tag - load - if ((tag & 0x1f) === 0x1f) { - let oct = tag; - tag = 0; - while ((oct & 0x80) === 0x80) { - oct = buf.readUInt8(fail); - if (buf.isError(oct)) - return oct; - - tag <<= 7; - tag |= oct & 0x7f; - } - } else { - tag &= 0x1f; - } - const tagStr = der.tag[tag]; - - return { - cls: cls, - primitive: primitive, - tag: tag, - tagStr: tagStr - }; -} - -function derDecodeLen(buf, primitive, fail) { - let len = buf.readUInt8(fail); - if (buf.isError(len)) - return len; - - // Indefinite form - if (!primitive && len === 0x80) - return null; - - // Definite form - if ((len & 0x80) === 0) { - // Short form - return len; - } - - // Long form - const num = len & 0x7f; - if (num > 4) - return buf.error('length octect is too long'); - - len = 0; - for (let i = 0; i < num; i++) { - len <<= 8; - const j = buf.readUInt8(fail); - if (buf.isError(j)) - return j; - len |= j; - } - - return len; -} - - -/***/ }), - -/***/ 9921: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - - -const decoders = exports; - -decoders.der = __nccwpck_require__(126); -decoders.pem = __nccwpck_require__(3274); - - -/***/ }), - -/***/ 3274: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -const inherits = __nccwpck_require__(9581); -const Buffer = (__nccwpck_require__(5827).Buffer); - -const DERDecoder = __nccwpck_require__(126); - -function PEMDecoder(entity) { - DERDecoder.call(this, entity); - this.enc = 'pem'; -} -inherits(PEMDecoder, DERDecoder); -module.exports = PEMDecoder; - -PEMDecoder.prototype.decode = function decode(data, options) { - const lines = data.toString().split(/[\r\n]+/g); - - const label = options.label.toUpperCase(); - - const re = /^-----(BEGIN|END) ([^-]+)-----$/; - let start = -1; - let end = -1; - for (let i = 0; i < lines.length; i++) { - const match = lines[i].match(re); - if (match === null) - continue; - - if (match[2] !== label) - continue; - - if (start === -1) { - if (match[1] !== 'BEGIN') - break; - start = i; - } else { - if (match[1] !== 'END') - break; - end = i; - break; - } - } - if (start === -1 || end === -1) - throw new Error('PEM section not found for: ' + label); - - const base64 = lines.slice(start + 1, end).join(''); - // Remove excessive symbols - base64.replace(/[^a-z0-9+/=]+/gi, ''); - - const input = Buffer.from(base64, 'base64'); - return DERDecoder.prototype.decode.call(this, input, options); -}; - - -/***/ }), - -/***/ 1446: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -const inherits = __nccwpck_require__(9581); -const Buffer = (__nccwpck_require__(5827).Buffer); -const Node = __nccwpck_require__(5956); - -// Import DER constants -const der = __nccwpck_require__(9115); - -function DEREncoder(entity) { - this.enc = 'der'; - this.name = entity.name; - this.entity = entity; - - // Construct base tree - this.tree = new DERNode(); - this.tree._init(entity.body); -} -module.exports = DEREncoder; - -DEREncoder.prototype.encode = function encode(data, reporter) { - return this.tree._encode(data, reporter).join(); -}; - -// Tree methods - -function DERNode(parent) { - Node.call(this, 'der', parent); -} -inherits(DERNode, Node); - -DERNode.prototype._encodeComposite = function encodeComposite(tag, - primitive, - cls, - content) { - const encodedTag = encodeTag(tag, primitive, cls, this.reporter); - - // Short form - if (content.length < 0x80) { - const header = Buffer.alloc(2); - header[0] = encodedTag; - header[1] = content.length; - return this._createEncoderBuffer([ header, content ]); - } - - // Long form - // Count octets required to store length - let lenOctets = 1; - for (let i = content.length; i >= 0x100; i >>= 8) - lenOctets++; - - const header = Buffer.alloc(1 + 1 + lenOctets); - header[0] = encodedTag; - header[1] = 0x80 | lenOctets; - - for (let i = 1 + lenOctets, j = content.length; j > 0; i--, j >>= 8) - header[i] = j & 0xff; - - return this._createEncoderBuffer([ header, content ]); -}; - -DERNode.prototype._encodeStr = function encodeStr(str, tag) { - if (tag === 'bitstr') { - return this._createEncoderBuffer([ str.unused | 0, str.data ]); - } else if (tag === 'bmpstr') { - const buf = Buffer.alloc(str.length * 2); - for (let i = 0; i < str.length; i++) { - buf.writeUInt16BE(str.charCodeAt(i), i * 2); - } - return this._createEncoderBuffer(buf); - } else if (tag === 'numstr') { - if (!this._isNumstr(str)) { - return this.reporter.error('Encoding of string type: numstr supports ' + - 'only digits and space'); - } - return this._createEncoderBuffer(str); - } else if (tag === 'printstr') { - if (!this._isPrintstr(str)) { - return this.reporter.error('Encoding of string type: printstr supports ' + - 'only latin upper and lower case letters, ' + - 'digits, space, apostrophe, left and rigth ' + - 'parenthesis, plus sign, comma, hyphen, ' + - 'dot, slash, colon, equal sign, ' + - 'question mark'); - } - return this._createEncoderBuffer(str); - } else if (/str$/.test(tag)) { - return this._createEncoderBuffer(str); - } else if (tag === 'objDesc') { - return this._createEncoderBuffer(str); - } else { - return this.reporter.error('Encoding of string type: ' + tag + - ' unsupported'); - } -}; - -DERNode.prototype._encodeObjid = function encodeObjid(id, values, relative) { - if (typeof id === 'string') { - if (!values) - return this.reporter.error('string objid given, but no values map found'); - if (!values.hasOwnProperty(id)) - return this.reporter.error('objid not found in values map'); - id = values[id].split(/[\s.]+/g); - for (let i = 0; i < id.length; i++) - id[i] |= 0; - } else if (Array.isArray(id)) { - id = id.slice(); - for (let i = 0; i < id.length; i++) - id[i] |= 0; - } - - if (!Array.isArray(id)) { - return this.reporter.error('objid() should be either array or string, ' + - 'got: ' + JSON.stringify(id)); - } - - if (!relative) { - if (id[1] >= 40) - return this.reporter.error('Second objid identifier OOB'); - id.splice(0, 2, id[0] * 40 + id[1]); - } - - // Count number of octets - let size = 0; - for (let i = 0; i < id.length; i++) { - let ident = id[i]; - for (size++; ident >= 0x80; ident >>= 7) - size++; - } - - const objid = Buffer.alloc(size); - let offset = objid.length - 1; - for (let i = id.length - 1; i >= 0; i--) { - let ident = id[i]; - objid[offset--] = ident & 0x7f; - while ((ident >>= 7) > 0) - objid[offset--] = 0x80 | (ident & 0x7f); - } - - return this._createEncoderBuffer(objid); -}; - -function two(num) { - if (num < 10) - return '0' + num; - else - return num; -} - -DERNode.prototype._encodeTime = function encodeTime(time, tag) { - let str; - const date = new Date(time); - - if (tag === 'gentime') { - str = [ - two(date.getUTCFullYear()), - two(date.getUTCMonth() + 1), - two(date.getUTCDate()), - two(date.getUTCHours()), - two(date.getUTCMinutes()), - two(date.getUTCSeconds()), - 'Z' - ].join(''); - } else if (tag === 'utctime') { - str = [ - two(date.getUTCFullYear() % 100), - two(date.getUTCMonth() + 1), - two(date.getUTCDate()), - two(date.getUTCHours()), - two(date.getUTCMinutes()), - two(date.getUTCSeconds()), - 'Z' - ].join(''); - } else { - this.reporter.error('Encoding ' + tag + ' time is not supported yet'); - } - - return this._encodeStr(str, 'octstr'); -}; - -DERNode.prototype._encodeNull = function encodeNull() { - return this._createEncoderBuffer(''); -}; - -DERNode.prototype._encodeInt = function encodeInt(num, values) { - if (typeof num === 'string') { - if (!values) - return this.reporter.error('String int or enum given, but no values map'); - if (!values.hasOwnProperty(num)) { - return this.reporter.error('Values map doesn\'t contain: ' + - JSON.stringify(num)); - } - num = values[num]; - } - - // Bignum, assume big endian - if (typeof num !== 'number' && !Buffer.isBuffer(num)) { - const numArray = num.toArray(); - if (!num.sign && numArray[0] & 0x80) { - numArray.unshift(0); - } - num = Buffer.from(numArray); - } - - if (Buffer.isBuffer(num)) { - let size = num.length; - if (num.length === 0) - size++; - - const out = Buffer.alloc(size); - num.copy(out); - if (num.length === 0) - out[0] = 0; - return this._createEncoderBuffer(out); - } - - if (num < 0x80) - return this._createEncoderBuffer(num); - - if (num < 0x100) - return this._createEncoderBuffer([0, num]); - - let size = 1; - for (let i = num; i >= 0x100; i >>= 8) - size++; - - const out = new Array(size); - for (let i = out.length - 1; i >= 0; i--) { - out[i] = num & 0xff; - num >>= 8; - } - if(out[0] & 0x80) { - out.unshift(0); - } - - return this._createEncoderBuffer(Buffer.from(out)); -}; - -DERNode.prototype._encodeBool = function encodeBool(value) { - return this._createEncoderBuffer(value ? 0xff : 0); -}; - -DERNode.prototype._use = function use(entity, obj) { - if (typeof entity === 'function') - entity = entity(obj); - return entity._getEncoder('der').tree; -}; - -DERNode.prototype._skipDefault = function skipDefault(dataBuffer, reporter, parent) { - const state = this._baseState; - let i; - if (state['default'] === null) - return false; - - const data = dataBuffer.join(); - if (state.defaultBuffer === undefined) - state.defaultBuffer = this._encodeValue(state['default'], reporter, parent).join(); - - if (data.length !== state.defaultBuffer.length) - return false; - - for (i=0; i < data.length; i++) - if (data[i] !== state.defaultBuffer[i]) - return false; - - return true; -}; - -// Utility methods - -function encodeTag(tag, primitive, cls, reporter) { - let res; - - if (tag === 'seqof') - tag = 'seq'; - else if (tag === 'setof') - tag = 'set'; - - if (der.tagByName.hasOwnProperty(tag)) - res = der.tagByName[tag]; - else if (typeof tag === 'number' && (tag | 0) === tag) - res = tag; - else - return reporter.error('Unknown tag: ' + tag); - - if (res >= 0x1f) - return reporter.error('Multi-octet tag encoding unsupported'); - - if (!primitive) - res |= 0x20; - - res |= (der.tagClassByName[cls || 'universal'] << 6); - - return res; -} - - -/***/ }), - -/***/ 3650: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - - -const encoders = exports; - -encoders.der = __nccwpck_require__(1446); -encoders.pem = __nccwpck_require__(1447); - - -/***/ }), - -/***/ 1447: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -const inherits = __nccwpck_require__(9581); - -const DEREncoder = __nccwpck_require__(1446); - -function PEMEncoder(entity) { - DEREncoder.call(this, entity); - this.enc = 'pem'; -} -inherits(PEMEncoder, DEREncoder); -module.exports = PEMEncoder; - -PEMEncoder.prototype.encode = function encode(data, options) { - const buf = DEREncoder.prototype.encode.call(this, data); - - const p = buf.toString('base64'); - const out = [ '-----BEGIN ' + options.label + '-----' ]; - for (let i = 0; i < p.length; i += 64) - out.push(p.slice(i, i + 64)); - out.push('-----END ' + options.label + '-----'); - return out.join('\n'); -}; - - -/***/ }), - -/***/ 5071: -/***/ (function(module, __unused_webpack_exports, __nccwpck_require__) { - -/* module decorator */ module = __nccwpck_require__.nmd(module); -(function (module, exports) { - 'use strict'; - - // Utils - function assert (val, msg) { - if (!val) throw new Error(msg || 'Assertion failed'); - } - - // Could use `inherits` module, but don't want to move from single file - // architecture yet. - function inherits (ctor, superCtor) { - ctor.super_ = superCtor; - var TempCtor = function () {}; - TempCtor.prototype = superCtor.prototype; - ctor.prototype = new TempCtor(); - ctor.prototype.constructor = ctor; - } - - // BN - - function BN (number, base, endian) { - if (BN.isBN(number)) { - return number; - } - - this.negative = 0; - this.words = null; - this.length = 0; - - // Reduction context - this.red = null; - - if (number !== null) { - if (base === 'le' || base === 'be') { - endian = base; - base = 10; - } - - this._init(number || 0, base || 10, endian || 'be'); - } - } - if (typeof module === 'object') { - module.exports = BN; - } else { - exports.BN = BN; - } - - BN.BN = BN; - BN.wordSize = 26; - - var Buffer; - try { - if (typeof window !== 'undefined' && typeof window.Buffer !== 'undefined') { - Buffer = window.Buffer; - } else { - Buffer = (__nccwpck_require__(4300).Buffer); - } - } catch (e) { - } - - BN.isBN = function isBN (num) { - if (num instanceof BN) { - return true; - } - - return num !== null && typeof num === 'object' && - num.constructor.wordSize === BN.wordSize && Array.isArray(num.words); - }; - - BN.max = function max (left, right) { - if (left.cmp(right) > 0) return left; - return right; - }; - - BN.min = function min (left, right) { - if (left.cmp(right) < 0) return left; - return right; - }; - - BN.prototype._init = function init (number, base, endian) { - if (typeof number === 'number') { - return this._initNumber(number, base, endian); - } - - if (typeof number === 'object') { - return this._initArray(number, base, endian); - } - - if (base === 'hex') { - base = 16; - } - assert(base === (base | 0) && base >= 2 && base <= 36); - - number = number.toString().replace(/\s+/g, ''); - var start = 0; - if (number[0] === '-') { - start++; - this.negative = 1; - } - - if (start < number.length) { - if (base === 16) { - this._parseHex(number, start, endian); - } else { - this._parseBase(number, base, start); - if (endian === 'le') { - this._initArray(this.toArray(), base, endian); - } - } - } - }; - - BN.prototype._initNumber = function _initNumber (number, base, endian) { - if (number < 0) { - this.negative = 1; - number = -number; - } - if (number < 0x4000000) { - this.words = [ number & 0x3ffffff ]; - this.length = 1; - } else if (number < 0x10000000000000) { - this.words = [ - number & 0x3ffffff, - (number / 0x4000000) & 0x3ffffff - ]; - this.length = 2; - } else { - assert(number < 0x20000000000000); // 2 ^ 53 (unsafe) - this.words = [ - number & 0x3ffffff, - (number / 0x4000000) & 0x3ffffff, - 1 - ]; - this.length = 3; - } - - if (endian !== 'le') return; - - // Reverse the bytes - this._initArray(this.toArray(), base, endian); - }; - - BN.prototype._initArray = function _initArray (number, base, endian) { - // Perhaps a Uint8Array - assert(typeof number.length === 'number'); - if (number.length <= 0) { - this.words = [ 0 ]; - this.length = 1; - return this; - } - - this.length = Math.ceil(number.length / 3); - this.words = new Array(this.length); - for (var i = 0; i < this.length; i++) { - this.words[i] = 0; - } - - var j, w; - var off = 0; - if (endian === 'be') { - for (i = number.length - 1, j = 0; i >= 0; i -= 3) { - w = number[i] | (number[i - 1] << 8) | (number[i - 2] << 16); - this.words[j] |= (w << off) & 0x3ffffff; - this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff; - off += 24; - if (off >= 26) { - off -= 26; - j++; - } - } - } else if (endian === 'le') { - for (i = 0, j = 0; i < number.length; i += 3) { - w = number[i] | (number[i + 1] << 8) | (number[i + 2] << 16); - this.words[j] |= (w << off) & 0x3ffffff; - this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff; - off += 24; - if (off >= 26) { - off -= 26; - j++; - } - } - } - return this.strip(); - }; - - function parseHex4Bits (string, index) { - var c = string.charCodeAt(index); - // 'A' - 'F' - if (c >= 65 && c <= 70) { - return c - 55; - // 'a' - 'f' - } else if (c >= 97 && c <= 102) { - return c - 87; - // '0' - '9' - } else { - return (c - 48) & 0xf; - } - } - - function parseHexByte (string, lowerBound, index) { - var r = parseHex4Bits(string, index); - if (index - 1 >= lowerBound) { - r |= parseHex4Bits(string, index - 1) << 4; - } - return r; - } - - BN.prototype._parseHex = function _parseHex (number, start, endian) { - // Create possibly bigger array to ensure that it fits the number - this.length = Math.ceil((number.length - start) / 6); - this.words = new Array(this.length); - for (var i = 0; i < this.length; i++) { - this.words[i] = 0; - } - - // 24-bits chunks - var off = 0; - var j = 0; - - var w; - if (endian === 'be') { - for (i = number.length - 1; i >= start; i -= 2) { - w = parseHexByte(number, start, i) << off; - this.words[j] |= w & 0x3ffffff; - if (off >= 18) { - off -= 18; - j += 1; - this.words[j] |= w >>> 26; - } else { - off += 8; - } - } - } else { - var parseLength = number.length - start; - for (i = parseLength % 2 === 0 ? start + 1 : start; i < number.length; i += 2) { - w = parseHexByte(number, start, i) << off; - this.words[j] |= w & 0x3ffffff; - if (off >= 18) { - off -= 18; - j += 1; - this.words[j] |= w >>> 26; - } else { - off += 8; - } - } - } - - this.strip(); - }; - - function parseBase (str, start, end, mul) { - var r = 0; - var len = Math.min(str.length, end); - for (var i = start; i < len; i++) { - var c = str.charCodeAt(i) - 48; - - r *= mul; - - // 'a' - if (c >= 49) { - r += c - 49 + 0xa; - - // 'A' - } else if (c >= 17) { - r += c - 17 + 0xa; - - // '0' - '9' - } else { - r += c; - } - } - return r; - } - - BN.prototype._parseBase = function _parseBase (number, base, start) { - // Initialize as zero - this.words = [ 0 ]; - this.length = 1; - - // Find length of limb in base - for (var limbLen = 0, limbPow = 1; limbPow <= 0x3ffffff; limbPow *= base) { - limbLen++; - } - limbLen--; - limbPow = (limbPow / base) | 0; - - var total = number.length - start; - var mod = total % limbLen; - var end = Math.min(total, total - mod) + start; - - var word = 0; - for (var i = start; i < end; i += limbLen) { - word = parseBase(number, i, i + limbLen, base); - - this.imuln(limbPow); - if (this.words[0] + word < 0x4000000) { - this.words[0] += word; - } else { - this._iaddn(word); - } - } - - if (mod !== 0) { - var pow = 1; - word = parseBase(number, i, number.length, base); - - for (i = 0; i < mod; i++) { - pow *= base; - } - - this.imuln(pow); - if (this.words[0] + word < 0x4000000) { - this.words[0] += word; - } else { - this._iaddn(word); - } - } - - this.strip(); - }; - - BN.prototype.copy = function copy (dest) { - dest.words = new Array(this.length); - for (var i = 0; i < this.length; i++) { - dest.words[i] = this.words[i]; - } - dest.length = this.length; - dest.negative = this.negative; - dest.red = this.red; - }; - - BN.prototype.clone = function clone () { - var r = new BN(null); - this.copy(r); - return r; - }; - - BN.prototype._expand = function _expand (size) { - while (this.length < size) { - this.words[this.length++] = 0; - } - return this; - }; - - // Remove leading `0` from `this` - BN.prototype.strip = function strip () { - while (this.length > 1 && this.words[this.length - 1] === 0) { - this.length--; - } - return this._normSign(); - }; - - BN.prototype._normSign = function _normSign () { - // -0 = 0 - if (this.length === 1 && this.words[0] === 0) { - this.negative = 0; - } - return this; - }; - - BN.prototype.inspect = function inspect () { - return (this.red ? ''; - }; - - /* - - var zeros = []; - var groupSizes = []; - var groupBases = []; - - var s = ''; - var i = -1; - while (++i < BN.wordSize) { - zeros[i] = s; - s += '0'; - } - groupSizes[0] = 0; - groupSizes[1] = 0; - groupBases[0] = 0; - groupBases[1] = 0; - var base = 2 - 1; - while (++base < 36 + 1) { - var groupSize = 0; - var groupBase = 1; - while (groupBase < (1 << BN.wordSize) / base) { - groupBase *= base; - groupSize += 1; - } - groupSizes[base] = groupSize; - groupBases[base] = groupBase; - } - - */ - - var zeros = [ - '', - '0', - '00', - '000', - '0000', - '00000', - '000000', - '0000000', - '00000000', - '000000000', - '0000000000', - '00000000000', - '000000000000', - '0000000000000', - '00000000000000', - '000000000000000', - '0000000000000000', - '00000000000000000', - '000000000000000000', - '0000000000000000000', - '00000000000000000000', - '000000000000000000000', - '0000000000000000000000', - '00000000000000000000000', - '000000000000000000000000', - '0000000000000000000000000' - ]; - - var groupSizes = [ - 0, 0, - 25, 16, 12, 11, 10, 9, 8, - 8, 7, 7, 7, 7, 6, 6, - 6, 6, 6, 6, 6, 5, 5, - 5, 5, 5, 5, 5, 5, 5, - 5, 5, 5, 5, 5, 5, 5 - ]; - - var groupBases = [ - 0, 0, - 33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216, - 43046721, 10000000, 19487171, 35831808, 62748517, 7529536, 11390625, - 16777216, 24137569, 34012224, 47045881, 64000000, 4084101, 5153632, - 6436343, 7962624, 9765625, 11881376, 14348907, 17210368, 20511149, - 24300000, 28629151, 33554432, 39135393, 45435424, 52521875, 60466176 - ]; - - BN.prototype.toString = function toString (base, padding) { - base = base || 10; - padding = padding | 0 || 1; - - var out; - if (base === 16 || base === 'hex') { - out = ''; - var off = 0; - var carry = 0; - for (var i = 0; i < this.length; i++) { - var w = this.words[i]; - var word = (((w << off) | carry) & 0xffffff).toString(16); - carry = (w >>> (24 - off)) & 0xffffff; - if (carry !== 0 || i !== this.length - 1) { - out = zeros[6 - word.length] + word + out; - } else { - out = word + out; - } - off += 2; - if (off >= 26) { - off -= 26; - i--; - } - } - if (carry !== 0) { - out = carry.toString(16) + out; - } - while (out.length % padding !== 0) { - out = '0' + out; - } - if (this.negative !== 0) { - out = '-' + out; - } - return out; - } - - if (base === (base | 0) && base >= 2 && base <= 36) { - // var groupSize = Math.floor(BN.wordSize * Math.LN2 / Math.log(base)); - var groupSize = groupSizes[base]; - // var groupBase = Math.pow(base, groupSize); - var groupBase = groupBases[base]; - out = ''; - var c = this.clone(); - c.negative = 0; - while (!c.isZero()) { - var r = c.modn(groupBase).toString(base); - c = c.idivn(groupBase); - - if (!c.isZero()) { - out = zeros[groupSize - r.length] + r + out; - } else { - out = r + out; - } - } - if (this.isZero()) { - out = '0' + out; - } - while (out.length % padding !== 0) { - out = '0' + out; - } - if (this.negative !== 0) { - out = '-' + out; - } - return out; - } - - assert(false, 'Base should be between 2 and 36'); - }; - - BN.prototype.toNumber = function toNumber () { - var ret = this.words[0]; - if (this.length === 2) { - ret += this.words[1] * 0x4000000; - } else if (this.length === 3 && this.words[2] === 0x01) { - // NOTE: at this stage it is known that the top bit is set - ret += 0x10000000000000 + (this.words[1] * 0x4000000); - } else if (this.length > 2) { - assert(false, 'Number can only safely store up to 53 bits'); - } - return (this.negative !== 0) ? -ret : ret; - }; - - BN.prototype.toJSON = function toJSON () { - return this.toString(16); - }; - - BN.prototype.toBuffer = function toBuffer (endian, length) { - assert(typeof Buffer !== 'undefined'); - return this.toArrayLike(Buffer, endian, length); - }; - - BN.prototype.toArray = function toArray (endian, length) { - return this.toArrayLike(Array, endian, length); - }; - - BN.prototype.toArrayLike = function toArrayLike (ArrayType, endian, length) { - var byteLength = this.byteLength(); - var reqLength = length || Math.max(1, byteLength); - assert(byteLength <= reqLength, 'byte array longer than desired length'); - assert(reqLength > 0, 'Requested array length <= 0'); - - this.strip(); - var littleEndian = endian === 'le'; - var res = new ArrayType(reqLength); - - var b, i; - var q = this.clone(); - if (!littleEndian) { - // Assume big-endian - for (i = 0; i < reqLength - byteLength; i++) { - res[i] = 0; - } - - for (i = 0; !q.isZero(); i++) { - b = q.andln(0xff); - q.iushrn(8); - - res[reqLength - i - 1] = b; - } - } else { - for (i = 0; !q.isZero(); i++) { - b = q.andln(0xff); - q.iushrn(8); - - res[i] = b; - } - - for (; i < reqLength; i++) { - res[i] = 0; - } - } - - return res; - }; - - if (Math.clz32) { - BN.prototype._countBits = function _countBits (w) { - return 32 - Math.clz32(w); - }; - } else { - BN.prototype._countBits = function _countBits (w) { - var t = w; - var r = 0; - if (t >= 0x1000) { - r += 13; - t >>>= 13; - } - if (t >= 0x40) { - r += 7; - t >>>= 7; - } - if (t >= 0x8) { - r += 4; - t >>>= 4; - } - if (t >= 0x02) { - r += 2; - t >>>= 2; - } - return r + t; - }; - } - - BN.prototype._zeroBits = function _zeroBits (w) { - // Short-cut - if (w === 0) return 26; - - var t = w; - var r = 0; - if ((t & 0x1fff) === 0) { - r += 13; - t >>>= 13; - } - if ((t & 0x7f) === 0) { - r += 7; - t >>>= 7; - } - if ((t & 0xf) === 0) { - r += 4; - t >>>= 4; - } - if ((t & 0x3) === 0) { - r += 2; - t >>>= 2; - } - if ((t & 0x1) === 0) { - r++; - } - return r; - }; - - // Return number of used bits in a BN - BN.prototype.bitLength = function bitLength () { - var w = this.words[this.length - 1]; - var hi = this._countBits(w); - return (this.length - 1) * 26 + hi; - }; - - function toBitArray (num) { - var w = new Array(num.bitLength()); - - for (var bit = 0; bit < w.length; bit++) { - var off = (bit / 26) | 0; - var wbit = bit % 26; - - w[bit] = (num.words[off] & (1 << wbit)) >>> wbit; - } - - return w; - } - - // Number of trailing zero bits - BN.prototype.zeroBits = function zeroBits () { - if (this.isZero()) return 0; - - var r = 0; - for (var i = 0; i < this.length; i++) { - var b = this._zeroBits(this.words[i]); - r += b; - if (b !== 26) break; - } - return r; - }; - - BN.prototype.byteLength = function byteLength () { - return Math.ceil(this.bitLength() / 8); - }; - - BN.prototype.toTwos = function toTwos (width) { - if (this.negative !== 0) { - return this.abs().inotn(width).iaddn(1); - } - return this.clone(); - }; - - BN.prototype.fromTwos = function fromTwos (width) { - if (this.testn(width - 1)) { - return this.notn(width).iaddn(1).ineg(); - } - return this.clone(); - }; - - BN.prototype.isNeg = function isNeg () { - return this.negative !== 0; - }; - - // Return negative clone of `this` - BN.prototype.neg = function neg () { - return this.clone().ineg(); - }; - - BN.prototype.ineg = function ineg () { - if (!this.isZero()) { - this.negative ^= 1; - } - - return this; - }; - - // Or `num` with `this` in-place - BN.prototype.iuor = function iuor (num) { - while (this.length < num.length) { - this.words[this.length++] = 0; - } - - for (var i = 0; i < num.length; i++) { - this.words[i] = this.words[i] | num.words[i]; - } - - return this.strip(); - }; - - BN.prototype.ior = function ior (num) { - assert((this.negative | num.negative) === 0); - return this.iuor(num); - }; - - // Or `num` with `this` - BN.prototype.or = function or (num) { - if (this.length > num.length) return this.clone().ior(num); - return num.clone().ior(this); - }; - - BN.prototype.uor = function uor (num) { - if (this.length > num.length) return this.clone().iuor(num); - return num.clone().iuor(this); - }; - - // And `num` with `this` in-place - BN.prototype.iuand = function iuand (num) { - // b = min-length(num, this) - var b; - if (this.length > num.length) { - b = num; - } else { - b = this; - } - - for (var i = 0; i < b.length; i++) { - this.words[i] = this.words[i] & num.words[i]; - } - - this.length = b.length; - - return this.strip(); - }; - - BN.prototype.iand = function iand (num) { - assert((this.negative | num.negative) === 0); - return this.iuand(num); - }; - - // And `num` with `this` - BN.prototype.and = function and (num) { - if (this.length > num.length) return this.clone().iand(num); - return num.clone().iand(this); - }; - - BN.prototype.uand = function uand (num) { - if (this.length > num.length) return this.clone().iuand(num); - return num.clone().iuand(this); - }; - - // Xor `num` with `this` in-place - BN.prototype.iuxor = function iuxor (num) { - // a.length > b.length - var a; - var b; - if (this.length > num.length) { - a = this; - b = num; - } else { - a = num; - b = this; - } - - for (var i = 0; i < b.length; i++) { - this.words[i] = a.words[i] ^ b.words[i]; - } - - if (this !== a) { - for (; i < a.length; i++) { - this.words[i] = a.words[i]; - } - } - - this.length = a.length; - - return this.strip(); - }; - - BN.prototype.ixor = function ixor (num) { - assert((this.negative | num.negative) === 0); - return this.iuxor(num); - }; - - // Xor `num` with `this` - BN.prototype.xor = function xor (num) { - if (this.length > num.length) return this.clone().ixor(num); - return num.clone().ixor(this); - }; - - BN.prototype.uxor = function uxor (num) { - if (this.length > num.length) return this.clone().iuxor(num); - return num.clone().iuxor(this); - }; - - // Not ``this`` with ``width`` bitwidth - BN.prototype.inotn = function inotn (width) { - assert(typeof width === 'number' && width >= 0); - - var bytesNeeded = Math.ceil(width / 26) | 0; - var bitsLeft = width % 26; - - // Extend the buffer with leading zeroes - this._expand(bytesNeeded); - - if (bitsLeft > 0) { - bytesNeeded--; - } - - // Handle complete words - for (var i = 0; i < bytesNeeded; i++) { - this.words[i] = ~this.words[i] & 0x3ffffff; - } - - // Handle the residue - if (bitsLeft > 0) { - this.words[i] = ~this.words[i] & (0x3ffffff >> (26 - bitsLeft)); - } - - // And remove leading zeroes - return this.strip(); - }; - - BN.prototype.notn = function notn (width) { - return this.clone().inotn(width); - }; - - // Set `bit` of `this` - BN.prototype.setn = function setn (bit, val) { - assert(typeof bit === 'number' && bit >= 0); - - var off = (bit / 26) | 0; - var wbit = bit % 26; - - this._expand(off + 1); - - if (val) { - this.words[off] = this.words[off] | (1 << wbit); - } else { - this.words[off] = this.words[off] & ~(1 << wbit); - } - - return this.strip(); - }; - - // Add `num` to `this` in-place - BN.prototype.iadd = function iadd (num) { - var r; - - // negative + positive - if (this.negative !== 0 && num.negative === 0) { - this.negative = 0; - r = this.isub(num); - this.negative ^= 1; - return this._normSign(); - - // positive + negative - } else if (this.negative === 0 && num.negative !== 0) { - num.negative = 0; - r = this.isub(num); - num.negative = 1; - return r._normSign(); - } - - // a.length > b.length - var a, b; - if (this.length > num.length) { - a = this; - b = num; - } else { - a = num; - b = this; - } - - var carry = 0; - for (var i = 0; i < b.length; i++) { - r = (a.words[i] | 0) + (b.words[i] | 0) + carry; - this.words[i] = r & 0x3ffffff; - carry = r >>> 26; - } - for (; carry !== 0 && i < a.length; i++) { - r = (a.words[i] | 0) + carry; - this.words[i] = r & 0x3ffffff; - carry = r >>> 26; - } - - this.length = a.length; - if (carry !== 0) { - this.words[this.length] = carry; - this.length++; - // Copy the rest of the words - } else if (a !== this) { - for (; i < a.length; i++) { - this.words[i] = a.words[i]; - } - } - - return this; - }; - - // Add `num` to `this` - BN.prototype.add = function add (num) { - var res; - if (num.negative !== 0 && this.negative === 0) { - num.negative = 0; - res = this.sub(num); - num.negative ^= 1; - return res; - } else if (num.negative === 0 && this.negative !== 0) { - this.negative = 0; - res = num.sub(this); - this.negative = 1; - return res; - } - - if (this.length > num.length) return this.clone().iadd(num); - - return num.clone().iadd(this); - }; - - // Subtract `num` from `this` in-place - BN.prototype.isub = function isub (num) { - // this - (-num) = this + num - if (num.negative !== 0) { - num.negative = 0; - var r = this.iadd(num); - num.negative = 1; - return r._normSign(); - - // -this - num = -(this + num) - } else if (this.negative !== 0) { - this.negative = 0; - this.iadd(num); - this.negative = 1; - return this._normSign(); - } - - // At this point both numbers are positive - var cmp = this.cmp(num); - - // Optimization - zeroify - if (cmp === 0) { - this.negative = 0; - this.length = 1; - this.words[0] = 0; - return this; - } - - // a > b - var a, b; - if (cmp > 0) { - a = this; - b = num; - } else { - a = num; - b = this; - } - - var carry = 0; - for (var i = 0; i < b.length; i++) { - r = (a.words[i] | 0) - (b.words[i] | 0) + carry; - carry = r >> 26; - this.words[i] = r & 0x3ffffff; - } - for (; carry !== 0 && i < a.length; i++) { - r = (a.words[i] | 0) + carry; - carry = r >> 26; - this.words[i] = r & 0x3ffffff; - } - - // Copy rest of the words - if (carry === 0 && i < a.length && a !== this) { - for (; i < a.length; i++) { - this.words[i] = a.words[i]; - } - } - - this.length = Math.max(this.length, i); - - if (a !== this) { - this.negative = 1; - } - - return this.strip(); - }; - - // Subtract `num` from `this` - BN.prototype.sub = function sub (num) { - return this.clone().isub(num); - }; - - function smallMulTo (self, num, out) { - out.negative = num.negative ^ self.negative; - var len = (self.length + num.length) | 0; - out.length = len; - len = (len - 1) | 0; - - // Peel one iteration (compiler can't do it, because of code complexity) - var a = self.words[0] | 0; - var b = num.words[0] | 0; - var r = a * b; - - var lo = r & 0x3ffffff; - var carry = (r / 0x4000000) | 0; - out.words[0] = lo; - - for (var k = 1; k < len; k++) { - // Sum all words with the same `i + j = k` and accumulate `ncarry`, - // note that ncarry could be >= 0x3ffffff - var ncarry = carry >>> 26; - var rword = carry & 0x3ffffff; - var maxJ = Math.min(k, num.length - 1); - for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) { - var i = (k - j) | 0; - a = self.words[i] | 0; - b = num.words[j] | 0; - r = a * b + rword; - ncarry += (r / 0x4000000) | 0; - rword = r & 0x3ffffff; - } - out.words[k] = rword | 0; - carry = ncarry | 0; - } - if (carry !== 0) { - out.words[k] = carry | 0; - } else { - out.length--; - } - - return out.strip(); - } - - // TODO(indutny): it may be reasonable to omit it for users who don't need - // to work with 256-bit numbers, otherwise it gives 20% improvement for 256-bit - // multiplication (like elliptic secp256k1). - var comb10MulTo = function comb10MulTo (self, num, out) { - var a = self.words; - var b = num.words; - var o = out.words; - var c = 0; - var lo; - var mid; - var hi; - var a0 = a[0] | 0; - var al0 = a0 & 0x1fff; - var ah0 = a0 >>> 13; - var a1 = a[1] | 0; - var al1 = a1 & 0x1fff; - var ah1 = a1 >>> 13; - var a2 = a[2] | 0; - var al2 = a2 & 0x1fff; - var ah2 = a2 >>> 13; - var a3 = a[3] | 0; - var al3 = a3 & 0x1fff; - var ah3 = a3 >>> 13; - var a4 = a[4] | 0; - var al4 = a4 & 0x1fff; - var ah4 = a4 >>> 13; - var a5 = a[5] | 0; - var al5 = a5 & 0x1fff; - var ah5 = a5 >>> 13; - var a6 = a[6] | 0; - var al6 = a6 & 0x1fff; - var ah6 = a6 >>> 13; - var a7 = a[7] | 0; - var al7 = a7 & 0x1fff; - var ah7 = a7 >>> 13; - var a8 = a[8] | 0; - var al8 = a8 & 0x1fff; - var ah8 = a8 >>> 13; - var a9 = a[9] | 0; - var al9 = a9 & 0x1fff; - var ah9 = a9 >>> 13; - var b0 = b[0] | 0; - var bl0 = b0 & 0x1fff; - var bh0 = b0 >>> 13; - var b1 = b[1] | 0; - var bl1 = b1 & 0x1fff; - var bh1 = b1 >>> 13; - var b2 = b[2] | 0; - var bl2 = b2 & 0x1fff; - var bh2 = b2 >>> 13; - var b3 = b[3] | 0; - var bl3 = b3 & 0x1fff; - var bh3 = b3 >>> 13; - var b4 = b[4] | 0; - var bl4 = b4 & 0x1fff; - var bh4 = b4 >>> 13; - var b5 = b[5] | 0; - var bl5 = b5 & 0x1fff; - var bh5 = b5 >>> 13; - var b6 = b[6] | 0; - var bl6 = b6 & 0x1fff; - var bh6 = b6 >>> 13; - var b7 = b[7] | 0; - var bl7 = b7 & 0x1fff; - var bh7 = b7 >>> 13; - var b8 = b[8] | 0; - var bl8 = b8 & 0x1fff; - var bh8 = b8 >>> 13; - var b9 = b[9] | 0; - var bl9 = b9 & 0x1fff; - var bh9 = b9 >>> 13; - - out.negative = self.negative ^ num.negative; - out.length = 19; - /* k = 0 */ - lo = Math.imul(al0, bl0); - mid = Math.imul(al0, bh0); - mid = (mid + Math.imul(ah0, bl0)) | 0; - hi = Math.imul(ah0, bh0); - var w0 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w0 >>> 26)) | 0; - w0 &= 0x3ffffff; - /* k = 1 */ - lo = Math.imul(al1, bl0); - mid = Math.imul(al1, bh0); - mid = (mid + Math.imul(ah1, bl0)) | 0; - hi = Math.imul(ah1, bh0); - lo = (lo + Math.imul(al0, bl1)) | 0; - mid = (mid + Math.imul(al0, bh1)) | 0; - mid = (mid + Math.imul(ah0, bl1)) | 0; - hi = (hi + Math.imul(ah0, bh1)) | 0; - var w1 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w1 >>> 26)) | 0; - w1 &= 0x3ffffff; - /* k = 2 */ - lo = Math.imul(al2, bl0); - mid = Math.imul(al2, bh0); - mid = (mid + Math.imul(ah2, bl0)) | 0; - hi = Math.imul(ah2, bh0); - lo = (lo + Math.imul(al1, bl1)) | 0; - mid = (mid + Math.imul(al1, bh1)) | 0; - mid = (mid + Math.imul(ah1, bl1)) | 0; - hi = (hi + Math.imul(ah1, bh1)) | 0; - lo = (lo + Math.imul(al0, bl2)) | 0; - mid = (mid + Math.imul(al0, bh2)) | 0; - mid = (mid + Math.imul(ah0, bl2)) | 0; - hi = (hi + Math.imul(ah0, bh2)) | 0; - var w2 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w2 >>> 26)) | 0; - w2 &= 0x3ffffff; - /* k = 3 */ - lo = Math.imul(al3, bl0); - mid = Math.imul(al3, bh0); - mid = (mid + Math.imul(ah3, bl0)) | 0; - hi = Math.imul(ah3, bh0); - lo = (lo + Math.imul(al2, bl1)) | 0; - mid = (mid + Math.imul(al2, bh1)) | 0; - mid = (mid + Math.imul(ah2, bl1)) | 0; - hi = (hi + Math.imul(ah2, bh1)) | 0; - lo = (lo + Math.imul(al1, bl2)) | 0; - mid = (mid + Math.imul(al1, bh2)) | 0; - mid = (mid + Math.imul(ah1, bl2)) | 0; - hi = (hi + Math.imul(ah1, bh2)) | 0; - lo = (lo + Math.imul(al0, bl3)) | 0; - mid = (mid + Math.imul(al0, bh3)) | 0; - mid = (mid + Math.imul(ah0, bl3)) | 0; - hi = (hi + Math.imul(ah0, bh3)) | 0; - var w3 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w3 >>> 26)) | 0; - w3 &= 0x3ffffff; - /* k = 4 */ - lo = Math.imul(al4, bl0); - mid = Math.imul(al4, bh0); - mid = (mid + Math.imul(ah4, bl0)) | 0; - hi = Math.imul(ah4, bh0); - lo = (lo + Math.imul(al3, bl1)) | 0; - mid = (mid + Math.imul(al3, bh1)) | 0; - mid = (mid + Math.imul(ah3, bl1)) | 0; - hi = (hi + Math.imul(ah3, bh1)) | 0; - lo = (lo + Math.imul(al2, bl2)) | 0; - mid = (mid + Math.imul(al2, bh2)) | 0; - mid = (mid + Math.imul(ah2, bl2)) | 0; - hi = (hi + Math.imul(ah2, bh2)) | 0; - lo = (lo + Math.imul(al1, bl3)) | 0; - mid = (mid + Math.imul(al1, bh3)) | 0; - mid = (mid + Math.imul(ah1, bl3)) | 0; - hi = (hi + Math.imul(ah1, bh3)) | 0; - lo = (lo + Math.imul(al0, bl4)) | 0; - mid = (mid + Math.imul(al0, bh4)) | 0; - mid = (mid + Math.imul(ah0, bl4)) | 0; - hi = (hi + Math.imul(ah0, bh4)) | 0; - var w4 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w4 >>> 26)) | 0; - w4 &= 0x3ffffff; - /* k = 5 */ - lo = Math.imul(al5, bl0); - mid = Math.imul(al5, bh0); - mid = (mid + Math.imul(ah5, bl0)) | 0; - hi = Math.imul(ah5, bh0); - lo = (lo + Math.imul(al4, bl1)) | 0; - mid = (mid + Math.imul(al4, bh1)) | 0; - mid = (mid + Math.imul(ah4, bl1)) | 0; - hi = (hi + Math.imul(ah4, bh1)) | 0; - lo = (lo + Math.imul(al3, bl2)) | 0; - mid = (mid + Math.imul(al3, bh2)) | 0; - mid = (mid + Math.imul(ah3, bl2)) | 0; - hi = (hi + Math.imul(ah3, bh2)) | 0; - lo = (lo + Math.imul(al2, bl3)) | 0; - mid = (mid + Math.imul(al2, bh3)) | 0; - mid = (mid + Math.imul(ah2, bl3)) | 0; - hi = (hi + Math.imul(ah2, bh3)) | 0; - lo = (lo + Math.imul(al1, bl4)) | 0; - mid = (mid + Math.imul(al1, bh4)) | 0; - mid = (mid + Math.imul(ah1, bl4)) | 0; - hi = (hi + Math.imul(ah1, bh4)) | 0; - lo = (lo + Math.imul(al0, bl5)) | 0; - mid = (mid + Math.imul(al0, bh5)) | 0; - mid = (mid + Math.imul(ah0, bl5)) | 0; - hi = (hi + Math.imul(ah0, bh5)) | 0; - var w5 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w5 >>> 26)) | 0; - w5 &= 0x3ffffff; - /* k = 6 */ - lo = Math.imul(al6, bl0); - mid = Math.imul(al6, bh0); - mid = (mid + Math.imul(ah6, bl0)) | 0; - hi = Math.imul(ah6, bh0); - lo = (lo + Math.imul(al5, bl1)) | 0; - mid = (mid + Math.imul(al5, bh1)) | 0; - mid = (mid + Math.imul(ah5, bl1)) | 0; - hi = (hi + Math.imul(ah5, bh1)) | 0; - lo = (lo + Math.imul(al4, bl2)) | 0; - mid = (mid + Math.imul(al4, bh2)) | 0; - mid = (mid + Math.imul(ah4, bl2)) | 0; - hi = (hi + Math.imul(ah4, bh2)) | 0; - lo = (lo + Math.imul(al3, bl3)) | 0; - mid = (mid + Math.imul(al3, bh3)) | 0; - mid = (mid + Math.imul(ah3, bl3)) | 0; - hi = (hi + Math.imul(ah3, bh3)) | 0; - lo = (lo + Math.imul(al2, bl4)) | 0; - mid = (mid + Math.imul(al2, bh4)) | 0; - mid = (mid + Math.imul(ah2, bl4)) | 0; - hi = (hi + Math.imul(ah2, bh4)) | 0; - lo = (lo + Math.imul(al1, bl5)) | 0; - mid = (mid + Math.imul(al1, bh5)) | 0; - mid = (mid + Math.imul(ah1, bl5)) | 0; - hi = (hi + Math.imul(ah1, bh5)) | 0; - lo = (lo + Math.imul(al0, bl6)) | 0; - mid = (mid + Math.imul(al0, bh6)) | 0; - mid = (mid + Math.imul(ah0, bl6)) | 0; - hi = (hi + Math.imul(ah0, bh6)) | 0; - var w6 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w6 >>> 26)) | 0; - w6 &= 0x3ffffff; - /* k = 7 */ - lo = Math.imul(al7, bl0); - mid = Math.imul(al7, bh0); - mid = (mid + Math.imul(ah7, bl0)) | 0; - hi = Math.imul(ah7, bh0); - lo = (lo + Math.imul(al6, bl1)) | 0; - mid = (mid + Math.imul(al6, bh1)) | 0; - mid = (mid + Math.imul(ah6, bl1)) | 0; - hi = (hi + Math.imul(ah6, bh1)) | 0; - lo = (lo + Math.imul(al5, bl2)) | 0; - mid = (mid + Math.imul(al5, bh2)) | 0; - mid = (mid + Math.imul(ah5, bl2)) | 0; - hi = (hi + Math.imul(ah5, bh2)) | 0; - lo = (lo + Math.imul(al4, bl3)) | 0; - mid = (mid + Math.imul(al4, bh3)) | 0; - mid = (mid + Math.imul(ah4, bl3)) | 0; - hi = (hi + Math.imul(ah4, bh3)) | 0; - lo = (lo + Math.imul(al3, bl4)) | 0; - mid = (mid + Math.imul(al3, bh4)) | 0; - mid = (mid + Math.imul(ah3, bl4)) | 0; - hi = (hi + Math.imul(ah3, bh4)) | 0; - lo = (lo + Math.imul(al2, bl5)) | 0; - mid = (mid + Math.imul(al2, bh5)) | 0; - mid = (mid + Math.imul(ah2, bl5)) | 0; - hi = (hi + Math.imul(ah2, bh5)) | 0; - lo = (lo + Math.imul(al1, bl6)) | 0; - mid = (mid + Math.imul(al1, bh6)) | 0; - mid = (mid + Math.imul(ah1, bl6)) | 0; - hi = (hi + Math.imul(ah1, bh6)) | 0; - lo = (lo + Math.imul(al0, bl7)) | 0; - mid = (mid + Math.imul(al0, bh7)) | 0; - mid = (mid + Math.imul(ah0, bl7)) | 0; - hi = (hi + Math.imul(ah0, bh7)) | 0; - var w7 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w7 >>> 26)) | 0; - w7 &= 0x3ffffff; - /* k = 8 */ - lo = Math.imul(al8, bl0); - mid = Math.imul(al8, bh0); - mid = (mid + Math.imul(ah8, bl0)) | 0; - hi = Math.imul(ah8, bh0); - lo = (lo + Math.imul(al7, bl1)) | 0; - mid = (mid + Math.imul(al7, bh1)) | 0; - mid = (mid + Math.imul(ah7, bl1)) | 0; - hi = (hi + Math.imul(ah7, bh1)) | 0; - lo = (lo + Math.imul(al6, bl2)) | 0; - mid = (mid + Math.imul(al6, bh2)) | 0; - mid = (mid + Math.imul(ah6, bl2)) | 0; - hi = (hi + Math.imul(ah6, bh2)) | 0; - lo = (lo + Math.imul(al5, bl3)) | 0; - mid = (mid + Math.imul(al5, bh3)) | 0; - mid = (mid + Math.imul(ah5, bl3)) | 0; - hi = (hi + Math.imul(ah5, bh3)) | 0; - lo = (lo + Math.imul(al4, bl4)) | 0; - mid = (mid + Math.imul(al4, bh4)) | 0; - mid = (mid + Math.imul(ah4, bl4)) | 0; - hi = (hi + Math.imul(ah4, bh4)) | 0; - lo = (lo + Math.imul(al3, bl5)) | 0; - mid = (mid + Math.imul(al3, bh5)) | 0; - mid = (mid + Math.imul(ah3, bl5)) | 0; - hi = (hi + Math.imul(ah3, bh5)) | 0; - lo = (lo + Math.imul(al2, bl6)) | 0; - mid = (mid + Math.imul(al2, bh6)) | 0; - mid = (mid + Math.imul(ah2, bl6)) | 0; - hi = (hi + Math.imul(ah2, bh6)) | 0; - lo = (lo + Math.imul(al1, bl7)) | 0; - mid = (mid + Math.imul(al1, bh7)) | 0; - mid = (mid + Math.imul(ah1, bl7)) | 0; - hi = (hi + Math.imul(ah1, bh7)) | 0; - lo = (lo + Math.imul(al0, bl8)) | 0; - mid = (mid + Math.imul(al0, bh8)) | 0; - mid = (mid + Math.imul(ah0, bl8)) | 0; - hi = (hi + Math.imul(ah0, bh8)) | 0; - var w8 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w8 >>> 26)) | 0; - w8 &= 0x3ffffff; - /* k = 9 */ - lo = Math.imul(al9, bl0); - mid = Math.imul(al9, bh0); - mid = (mid + Math.imul(ah9, bl0)) | 0; - hi = Math.imul(ah9, bh0); - lo = (lo + Math.imul(al8, bl1)) | 0; - mid = (mid + Math.imul(al8, bh1)) | 0; - mid = (mid + Math.imul(ah8, bl1)) | 0; - hi = (hi + Math.imul(ah8, bh1)) | 0; - lo = (lo + Math.imul(al7, bl2)) | 0; - mid = (mid + Math.imul(al7, bh2)) | 0; - mid = (mid + Math.imul(ah7, bl2)) | 0; - hi = (hi + Math.imul(ah7, bh2)) | 0; - lo = (lo + Math.imul(al6, bl3)) | 0; - mid = (mid + Math.imul(al6, bh3)) | 0; - mid = (mid + Math.imul(ah6, bl3)) | 0; - hi = (hi + Math.imul(ah6, bh3)) | 0; - lo = (lo + Math.imul(al5, bl4)) | 0; - mid = (mid + Math.imul(al5, bh4)) | 0; - mid = (mid + Math.imul(ah5, bl4)) | 0; - hi = (hi + Math.imul(ah5, bh4)) | 0; - lo = (lo + Math.imul(al4, bl5)) | 0; - mid = (mid + Math.imul(al4, bh5)) | 0; - mid = (mid + Math.imul(ah4, bl5)) | 0; - hi = (hi + Math.imul(ah4, bh5)) | 0; - lo = (lo + Math.imul(al3, bl6)) | 0; - mid = (mid + Math.imul(al3, bh6)) | 0; - mid = (mid + Math.imul(ah3, bl6)) | 0; - hi = (hi + Math.imul(ah3, bh6)) | 0; - lo = (lo + Math.imul(al2, bl7)) | 0; - mid = (mid + Math.imul(al2, bh7)) | 0; - mid = (mid + Math.imul(ah2, bl7)) | 0; - hi = (hi + Math.imul(ah2, bh7)) | 0; - lo = (lo + Math.imul(al1, bl8)) | 0; - mid = (mid + Math.imul(al1, bh8)) | 0; - mid = (mid + Math.imul(ah1, bl8)) | 0; - hi = (hi + Math.imul(ah1, bh8)) | 0; - lo = (lo + Math.imul(al0, bl9)) | 0; - mid = (mid + Math.imul(al0, bh9)) | 0; - mid = (mid + Math.imul(ah0, bl9)) | 0; - hi = (hi + Math.imul(ah0, bh9)) | 0; - var w9 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w9 >>> 26)) | 0; - w9 &= 0x3ffffff; - /* k = 10 */ - lo = Math.imul(al9, bl1); - mid = Math.imul(al9, bh1); - mid = (mid + Math.imul(ah9, bl1)) | 0; - hi = Math.imul(ah9, bh1); - lo = (lo + Math.imul(al8, bl2)) | 0; - mid = (mid + Math.imul(al8, bh2)) | 0; - mid = (mid + Math.imul(ah8, bl2)) | 0; - hi = (hi + Math.imul(ah8, bh2)) | 0; - lo = (lo + Math.imul(al7, bl3)) | 0; - mid = (mid + Math.imul(al7, bh3)) | 0; - mid = (mid + Math.imul(ah7, bl3)) | 0; - hi = (hi + Math.imul(ah7, bh3)) | 0; - lo = (lo + Math.imul(al6, bl4)) | 0; - mid = (mid + Math.imul(al6, bh4)) | 0; - mid = (mid + Math.imul(ah6, bl4)) | 0; - hi = (hi + Math.imul(ah6, bh4)) | 0; - lo = (lo + Math.imul(al5, bl5)) | 0; - mid = (mid + Math.imul(al5, bh5)) | 0; - mid = (mid + Math.imul(ah5, bl5)) | 0; - hi = (hi + Math.imul(ah5, bh5)) | 0; - lo = (lo + Math.imul(al4, bl6)) | 0; - mid = (mid + Math.imul(al4, bh6)) | 0; - mid = (mid + Math.imul(ah4, bl6)) | 0; - hi = (hi + Math.imul(ah4, bh6)) | 0; - lo = (lo + Math.imul(al3, bl7)) | 0; - mid = (mid + Math.imul(al3, bh7)) | 0; - mid = (mid + Math.imul(ah3, bl7)) | 0; - hi = (hi + Math.imul(ah3, bh7)) | 0; - lo = (lo + Math.imul(al2, bl8)) | 0; - mid = (mid + Math.imul(al2, bh8)) | 0; - mid = (mid + Math.imul(ah2, bl8)) | 0; - hi = (hi + Math.imul(ah2, bh8)) | 0; - lo = (lo + Math.imul(al1, bl9)) | 0; - mid = (mid + Math.imul(al1, bh9)) | 0; - mid = (mid + Math.imul(ah1, bl9)) | 0; - hi = (hi + Math.imul(ah1, bh9)) | 0; - var w10 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w10 >>> 26)) | 0; - w10 &= 0x3ffffff; - /* k = 11 */ - lo = Math.imul(al9, bl2); - mid = Math.imul(al9, bh2); - mid = (mid + Math.imul(ah9, bl2)) | 0; - hi = Math.imul(ah9, bh2); - lo = (lo + Math.imul(al8, bl3)) | 0; - mid = (mid + Math.imul(al8, bh3)) | 0; - mid = (mid + Math.imul(ah8, bl3)) | 0; - hi = (hi + Math.imul(ah8, bh3)) | 0; - lo = (lo + Math.imul(al7, bl4)) | 0; - mid = (mid + Math.imul(al7, bh4)) | 0; - mid = (mid + Math.imul(ah7, bl4)) | 0; - hi = (hi + Math.imul(ah7, bh4)) | 0; - lo = (lo + Math.imul(al6, bl5)) | 0; - mid = (mid + Math.imul(al6, bh5)) | 0; - mid = (mid + Math.imul(ah6, bl5)) | 0; - hi = (hi + Math.imul(ah6, bh5)) | 0; - lo = (lo + Math.imul(al5, bl6)) | 0; - mid = (mid + Math.imul(al5, bh6)) | 0; - mid = (mid + Math.imul(ah5, bl6)) | 0; - hi = (hi + Math.imul(ah5, bh6)) | 0; - lo = (lo + Math.imul(al4, bl7)) | 0; - mid = (mid + Math.imul(al4, bh7)) | 0; - mid = (mid + Math.imul(ah4, bl7)) | 0; - hi = (hi + Math.imul(ah4, bh7)) | 0; - lo = (lo + Math.imul(al3, bl8)) | 0; - mid = (mid + Math.imul(al3, bh8)) | 0; - mid = (mid + Math.imul(ah3, bl8)) | 0; - hi = (hi + Math.imul(ah3, bh8)) | 0; - lo = (lo + Math.imul(al2, bl9)) | 0; - mid = (mid + Math.imul(al2, bh9)) | 0; - mid = (mid + Math.imul(ah2, bl9)) | 0; - hi = (hi + Math.imul(ah2, bh9)) | 0; - var w11 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w11 >>> 26)) | 0; - w11 &= 0x3ffffff; - /* k = 12 */ - lo = Math.imul(al9, bl3); - mid = Math.imul(al9, bh3); - mid = (mid + Math.imul(ah9, bl3)) | 0; - hi = Math.imul(ah9, bh3); - lo = (lo + Math.imul(al8, bl4)) | 0; - mid = (mid + Math.imul(al8, bh4)) | 0; - mid = (mid + Math.imul(ah8, bl4)) | 0; - hi = (hi + Math.imul(ah8, bh4)) | 0; - lo = (lo + Math.imul(al7, bl5)) | 0; - mid = (mid + Math.imul(al7, bh5)) | 0; - mid = (mid + Math.imul(ah7, bl5)) | 0; - hi = (hi + Math.imul(ah7, bh5)) | 0; - lo = (lo + Math.imul(al6, bl6)) | 0; - mid = (mid + Math.imul(al6, bh6)) | 0; - mid = (mid + Math.imul(ah6, bl6)) | 0; - hi = (hi + Math.imul(ah6, bh6)) | 0; - lo = (lo + Math.imul(al5, bl7)) | 0; - mid = (mid + Math.imul(al5, bh7)) | 0; - mid = (mid + Math.imul(ah5, bl7)) | 0; - hi = (hi + Math.imul(ah5, bh7)) | 0; - lo = (lo + Math.imul(al4, bl8)) | 0; - mid = (mid + Math.imul(al4, bh8)) | 0; - mid = (mid + Math.imul(ah4, bl8)) | 0; - hi = (hi + Math.imul(ah4, bh8)) | 0; - lo = (lo + Math.imul(al3, bl9)) | 0; - mid = (mid + Math.imul(al3, bh9)) | 0; - mid = (mid + Math.imul(ah3, bl9)) | 0; - hi = (hi + Math.imul(ah3, bh9)) | 0; - var w12 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w12 >>> 26)) | 0; - w12 &= 0x3ffffff; - /* k = 13 */ - lo = Math.imul(al9, bl4); - mid = Math.imul(al9, bh4); - mid = (mid + Math.imul(ah9, bl4)) | 0; - hi = Math.imul(ah9, bh4); - lo = (lo + Math.imul(al8, bl5)) | 0; - mid = (mid + Math.imul(al8, bh5)) | 0; - mid = (mid + Math.imul(ah8, bl5)) | 0; - hi = (hi + Math.imul(ah8, bh5)) | 0; - lo = (lo + Math.imul(al7, bl6)) | 0; - mid = (mid + Math.imul(al7, bh6)) | 0; - mid = (mid + Math.imul(ah7, bl6)) | 0; - hi = (hi + Math.imul(ah7, bh6)) | 0; - lo = (lo + Math.imul(al6, bl7)) | 0; - mid = (mid + Math.imul(al6, bh7)) | 0; - mid = (mid + Math.imul(ah6, bl7)) | 0; - hi = (hi + Math.imul(ah6, bh7)) | 0; - lo = (lo + Math.imul(al5, bl8)) | 0; - mid = (mid + Math.imul(al5, bh8)) | 0; - mid = (mid + Math.imul(ah5, bl8)) | 0; - hi = (hi + Math.imul(ah5, bh8)) | 0; - lo = (lo + Math.imul(al4, bl9)) | 0; - mid = (mid + Math.imul(al4, bh9)) | 0; - mid = (mid + Math.imul(ah4, bl9)) | 0; - hi = (hi + Math.imul(ah4, bh9)) | 0; - var w13 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w13 >>> 26)) | 0; - w13 &= 0x3ffffff; - /* k = 14 */ - lo = Math.imul(al9, bl5); - mid = Math.imul(al9, bh5); - mid = (mid + Math.imul(ah9, bl5)) | 0; - hi = Math.imul(ah9, bh5); - lo = (lo + Math.imul(al8, bl6)) | 0; - mid = (mid + Math.imul(al8, bh6)) | 0; - mid = (mid + Math.imul(ah8, bl6)) | 0; - hi = (hi + Math.imul(ah8, bh6)) | 0; - lo = (lo + Math.imul(al7, bl7)) | 0; - mid = (mid + Math.imul(al7, bh7)) | 0; - mid = (mid + Math.imul(ah7, bl7)) | 0; - hi = (hi + Math.imul(ah7, bh7)) | 0; - lo = (lo + Math.imul(al6, bl8)) | 0; - mid = (mid + Math.imul(al6, bh8)) | 0; - mid = (mid + Math.imul(ah6, bl8)) | 0; - hi = (hi + Math.imul(ah6, bh8)) | 0; - lo = (lo + Math.imul(al5, bl9)) | 0; - mid = (mid + Math.imul(al5, bh9)) | 0; - mid = (mid + Math.imul(ah5, bl9)) | 0; - hi = (hi + Math.imul(ah5, bh9)) | 0; - var w14 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w14 >>> 26)) | 0; - w14 &= 0x3ffffff; - /* k = 15 */ - lo = Math.imul(al9, bl6); - mid = Math.imul(al9, bh6); - mid = (mid + Math.imul(ah9, bl6)) | 0; - hi = Math.imul(ah9, bh6); - lo = (lo + Math.imul(al8, bl7)) | 0; - mid = (mid + Math.imul(al8, bh7)) | 0; - mid = (mid + Math.imul(ah8, bl7)) | 0; - hi = (hi + Math.imul(ah8, bh7)) | 0; - lo = (lo + Math.imul(al7, bl8)) | 0; - mid = (mid + Math.imul(al7, bh8)) | 0; - mid = (mid + Math.imul(ah7, bl8)) | 0; - hi = (hi + Math.imul(ah7, bh8)) | 0; - lo = (lo + Math.imul(al6, bl9)) | 0; - mid = (mid + Math.imul(al6, bh9)) | 0; - mid = (mid + Math.imul(ah6, bl9)) | 0; - hi = (hi + Math.imul(ah6, bh9)) | 0; - var w15 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w15 >>> 26)) | 0; - w15 &= 0x3ffffff; - /* k = 16 */ - lo = Math.imul(al9, bl7); - mid = Math.imul(al9, bh7); - mid = (mid + Math.imul(ah9, bl7)) | 0; - hi = Math.imul(ah9, bh7); - lo = (lo + Math.imul(al8, bl8)) | 0; - mid = (mid + Math.imul(al8, bh8)) | 0; - mid = (mid + Math.imul(ah8, bl8)) | 0; - hi = (hi + Math.imul(ah8, bh8)) | 0; - lo = (lo + Math.imul(al7, bl9)) | 0; - mid = (mid + Math.imul(al7, bh9)) | 0; - mid = (mid + Math.imul(ah7, bl9)) | 0; - hi = (hi + Math.imul(ah7, bh9)) | 0; - var w16 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w16 >>> 26)) | 0; - w16 &= 0x3ffffff; - /* k = 17 */ - lo = Math.imul(al9, bl8); - mid = Math.imul(al9, bh8); - mid = (mid + Math.imul(ah9, bl8)) | 0; - hi = Math.imul(ah9, bh8); - lo = (lo + Math.imul(al8, bl9)) | 0; - mid = (mid + Math.imul(al8, bh9)) | 0; - mid = (mid + Math.imul(ah8, bl9)) | 0; - hi = (hi + Math.imul(ah8, bh9)) | 0; - var w17 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w17 >>> 26)) | 0; - w17 &= 0x3ffffff; - /* k = 18 */ - lo = Math.imul(al9, bl9); - mid = Math.imul(al9, bh9); - mid = (mid + Math.imul(ah9, bl9)) | 0; - hi = Math.imul(ah9, bh9); - var w18 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w18 >>> 26)) | 0; - w18 &= 0x3ffffff; - o[0] = w0; - o[1] = w1; - o[2] = w2; - o[3] = w3; - o[4] = w4; - o[5] = w5; - o[6] = w6; - o[7] = w7; - o[8] = w8; - o[9] = w9; - o[10] = w10; - o[11] = w11; - o[12] = w12; - o[13] = w13; - o[14] = w14; - o[15] = w15; - o[16] = w16; - o[17] = w17; - o[18] = w18; - if (c !== 0) { - o[19] = c; - out.length++; - } - return out; - }; - - // Polyfill comb - if (!Math.imul) { - comb10MulTo = smallMulTo; - } - - function bigMulTo (self, num, out) { - out.negative = num.negative ^ self.negative; - out.length = self.length + num.length; - - var carry = 0; - var hncarry = 0; - for (var k = 0; k < out.length - 1; k++) { - // Sum all words with the same `i + j = k` and accumulate `ncarry`, - // note that ncarry could be >= 0x3ffffff - var ncarry = hncarry; - hncarry = 0; - var rword = carry & 0x3ffffff; - var maxJ = Math.min(k, num.length - 1); - for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) { - var i = k - j; - var a = self.words[i] | 0; - var b = num.words[j] | 0; - var r = a * b; - - var lo = r & 0x3ffffff; - ncarry = (ncarry + ((r / 0x4000000) | 0)) | 0; - lo = (lo + rword) | 0; - rword = lo & 0x3ffffff; - ncarry = (ncarry + (lo >>> 26)) | 0; - - hncarry += ncarry >>> 26; - ncarry &= 0x3ffffff; - } - out.words[k] = rword; - carry = ncarry; - ncarry = hncarry; - } - if (carry !== 0) { - out.words[k] = carry; - } else { - out.length--; - } - - return out.strip(); - } - - function jumboMulTo (self, num, out) { - var fftm = new FFTM(); - return fftm.mulp(self, num, out); - } - - BN.prototype.mulTo = function mulTo (num, out) { - var res; - var len = this.length + num.length; - if (this.length === 10 && num.length === 10) { - res = comb10MulTo(this, num, out); - } else if (len < 63) { - res = smallMulTo(this, num, out); - } else if (len < 1024) { - res = bigMulTo(this, num, out); - } else { - res = jumboMulTo(this, num, out); - } - - return res; - }; - - // Cooley-Tukey algorithm for FFT - // slightly revisited to rely on looping instead of recursion - - function FFTM (x, y) { - this.x = x; - this.y = y; - } - - FFTM.prototype.makeRBT = function makeRBT (N) { - var t = new Array(N); - var l = BN.prototype._countBits(N) - 1; - for (var i = 0; i < N; i++) { - t[i] = this.revBin(i, l, N); - } - - return t; - }; - - // Returns binary-reversed representation of `x` - FFTM.prototype.revBin = function revBin (x, l, N) { - if (x === 0 || x === N - 1) return x; - - var rb = 0; - for (var i = 0; i < l; i++) { - rb |= (x & 1) << (l - i - 1); - x >>= 1; - } - - return rb; - }; - - // Performs "tweedling" phase, therefore 'emulating' - // behaviour of the recursive algorithm - FFTM.prototype.permute = function permute (rbt, rws, iws, rtws, itws, N) { - for (var i = 0; i < N; i++) { - rtws[i] = rws[rbt[i]]; - itws[i] = iws[rbt[i]]; - } - }; - - FFTM.prototype.transform = function transform (rws, iws, rtws, itws, N, rbt) { - this.permute(rbt, rws, iws, rtws, itws, N); - - for (var s = 1; s < N; s <<= 1) { - var l = s << 1; - - var rtwdf = Math.cos(2 * Math.PI / l); - var itwdf = Math.sin(2 * Math.PI / l); - - for (var p = 0; p < N; p += l) { - var rtwdf_ = rtwdf; - var itwdf_ = itwdf; - - for (var j = 0; j < s; j++) { - var re = rtws[p + j]; - var ie = itws[p + j]; - - var ro = rtws[p + j + s]; - var io = itws[p + j + s]; - - var rx = rtwdf_ * ro - itwdf_ * io; - - io = rtwdf_ * io + itwdf_ * ro; - ro = rx; - - rtws[p + j] = re + ro; - itws[p + j] = ie + io; - - rtws[p + j + s] = re - ro; - itws[p + j + s] = ie - io; - - /* jshint maxdepth : false */ - if (j !== l) { - rx = rtwdf * rtwdf_ - itwdf * itwdf_; - - itwdf_ = rtwdf * itwdf_ + itwdf * rtwdf_; - rtwdf_ = rx; - } - } - } - } - }; - - FFTM.prototype.guessLen13b = function guessLen13b (n, m) { - var N = Math.max(m, n) | 1; - var odd = N & 1; - var i = 0; - for (N = N / 2 | 0; N; N = N >>> 1) { - i++; - } - - return 1 << i + 1 + odd; - }; - - FFTM.prototype.conjugate = function conjugate (rws, iws, N) { - if (N <= 1) return; - - for (var i = 0; i < N / 2; i++) { - var t = rws[i]; - - rws[i] = rws[N - i - 1]; - rws[N - i - 1] = t; - - t = iws[i]; - - iws[i] = -iws[N - i - 1]; - iws[N - i - 1] = -t; - } - }; - - FFTM.prototype.normalize13b = function normalize13b (ws, N) { - var carry = 0; - for (var i = 0; i < N / 2; i++) { - var w = Math.round(ws[2 * i + 1] / N) * 0x2000 + - Math.round(ws[2 * i] / N) + - carry; - - ws[i] = w & 0x3ffffff; - - if (w < 0x4000000) { - carry = 0; - } else { - carry = w / 0x4000000 | 0; - } - } - - return ws; - }; - - FFTM.prototype.convert13b = function convert13b (ws, len, rws, N) { - var carry = 0; - for (var i = 0; i < len; i++) { - carry = carry + (ws[i] | 0); - - rws[2 * i] = carry & 0x1fff; carry = carry >>> 13; - rws[2 * i + 1] = carry & 0x1fff; carry = carry >>> 13; - } - - // Pad with zeroes - for (i = 2 * len; i < N; ++i) { - rws[i] = 0; - } - - assert(carry === 0); - assert((carry & ~0x1fff) === 0); - }; - - FFTM.prototype.stub = function stub (N) { - var ph = new Array(N); - for (var i = 0; i < N; i++) { - ph[i] = 0; - } - - return ph; - }; - - FFTM.prototype.mulp = function mulp (x, y, out) { - var N = 2 * this.guessLen13b(x.length, y.length); - - var rbt = this.makeRBT(N); - - var _ = this.stub(N); - - var rws = new Array(N); - var rwst = new Array(N); - var iwst = new Array(N); - - var nrws = new Array(N); - var nrwst = new Array(N); - var niwst = new Array(N); - - var rmws = out.words; - rmws.length = N; - - this.convert13b(x.words, x.length, rws, N); - this.convert13b(y.words, y.length, nrws, N); - - this.transform(rws, _, rwst, iwst, N, rbt); - this.transform(nrws, _, nrwst, niwst, N, rbt); - - for (var i = 0; i < N; i++) { - var rx = rwst[i] * nrwst[i] - iwst[i] * niwst[i]; - iwst[i] = rwst[i] * niwst[i] + iwst[i] * nrwst[i]; - rwst[i] = rx; - } - - this.conjugate(rwst, iwst, N); - this.transform(rwst, iwst, rmws, _, N, rbt); - this.conjugate(rmws, _, N); - this.normalize13b(rmws, N); - - out.negative = x.negative ^ y.negative; - out.length = x.length + y.length; - return out.strip(); - }; - - // Multiply `this` by `num` - BN.prototype.mul = function mul (num) { - var out = new BN(null); - out.words = new Array(this.length + num.length); - return this.mulTo(num, out); - }; - - // Multiply employing FFT - BN.prototype.mulf = function mulf (num) { - var out = new BN(null); - out.words = new Array(this.length + num.length); - return jumboMulTo(this, num, out); - }; - - // In-place Multiplication - BN.prototype.imul = function imul (num) { - return this.clone().mulTo(num, this); - }; - - BN.prototype.imuln = function imuln (num) { - assert(typeof num === 'number'); - assert(num < 0x4000000); - - // Carry - var carry = 0; - for (var i = 0; i < this.length; i++) { - var w = (this.words[i] | 0) * num; - var lo = (w & 0x3ffffff) + (carry & 0x3ffffff); - carry >>= 26; - carry += (w / 0x4000000) | 0; - // NOTE: lo is 27bit maximum - carry += lo >>> 26; - this.words[i] = lo & 0x3ffffff; - } - - if (carry !== 0) { - this.words[i] = carry; - this.length++; - } - - return this; - }; - - BN.prototype.muln = function muln (num) { - return this.clone().imuln(num); - }; - - // `this` * `this` - BN.prototype.sqr = function sqr () { - return this.mul(this); - }; - - // `this` * `this` in-place - BN.prototype.isqr = function isqr () { - return this.imul(this.clone()); - }; - - // Math.pow(`this`, `num`) - BN.prototype.pow = function pow (num) { - var w = toBitArray(num); - if (w.length === 0) return new BN(1); - - // Skip leading zeroes - var res = this; - for (var i = 0; i < w.length; i++, res = res.sqr()) { - if (w[i] !== 0) break; - } - - if (++i < w.length) { - for (var q = res.sqr(); i < w.length; i++, q = q.sqr()) { - if (w[i] === 0) continue; - - res = res.mul(q); - } - } - - return res; - }; - - // Shift-left in-place - BN.prototype.iushln = function iushln (bits) { - assert(typeof bits === 'number' && bits >= 0); - var r = bits % 26; - var s = (bits - r) / 26; - var carryMask = (0x3ffffff >>> (26 - r)) << (26 - r); - var i; - - if (r !== 0) { - var carry = 0; - - for (i = 0; i < this.length; i++) { - var newCarry = this.words[i] & carryMask; - var c = ((this.words[i] | 0) - newCarry) << r; - this.words[i] = c | carry; - carry = newCarry >>> (26 - r); - } - - if (carry) { - this.words[i] = carry; - this.length++; - } - } - - if (s !== 0) { - for (i = this.length - 1; i >= 0; i--) { - this.words[i + s] = this.words[i]; - } - - for (i = 0; i < s; i++) { - this.words[i] = 0; - } - - this.length += s; - } - - return this.strip(); - }; - - BN.prototype.ishln = function ishln (bits) { - // TODO(indutny): implement me - assert(this.negative === 0); - return this.iushln(bits); - }; - - // Shift-right in-place - // NOTE: `hint` is a lowest bit before trailing zeroes - // NOTE: if `extended` is present - it will be filled with destroyed bits - BN.prototype.iushrn = function iushrn (bits, hint, extended) { - assert(typeof bits === 'number' && bits >= 0); - var h; - if (hint) { - h = (hint - (hint % 26)) / 26; - } else { - h = 0; - } - - var r = bits % 26; - var s = Math.min((bits - r) / 26, this.length); - var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r); - var maskedWords = extended; - - h -= s; - h = Math.max(0, h); - - // Extended mode, copy masked part - if (maskedWords) { - for (var i = 0; i < s; i++) { - maskedWords.words[i] = this.words[i]; - } - maskedWords.length = s; - } - - if (s === 0) { - // No-op, we should not move anything at all - } else if (this.length > s) { - this.length -= s; - for (i = 0; i < this.length; i++) { - this.words[i] = this.words[i + s]; - } - } else { - this.words[0] = 0; - this.length = 1; - } - - var carry = 0; - for (i = this.length - 1; i >= 0 && (carry !== 0 || i >= h); i--) { - var word = this.words[i] | 0; - this.words[i] = (carry << (26 - r)) | (word >>> r); - carry = word & mask; - } - - // Push carried bits as a mask - if (maskedWords && carry !== 0) { - maskedWords.words[maskedWords.length++] = carry; - } - - if (this.length === 0) { - this.words[0] = 0; - this.length = 1; - } - - return this.strip(); - }; - - BN.prototype.ishrn = function ishrn (bits, hint, extended) { - // TODO(indutny): implement me - assert(this.negative === 0); - return this.iushrn(bits, hint, extended); - }; - - // Shift-left - BN.prototype.shln = function shln (bits) { - return this.clone().ishln(bits); - }; - - BN.prototype.ushln = function ushln (bits) { - return this.clone().iushln(bits); - }; - - // Shift-right - BN.prototype.shrn = function shrn (bits) { - return this.clone().ishrn(bits); - }; - - BN.prototype.ushrn = function ushrn (bits) { - return this.clone().iushrn(bits); - }; - - // Test if n bit is set - BN.prototype.testn = function testn (bit) { - assert(typeof bit === 'number' && bit >= 0); - var r = bit % 26; - var s = (bit - r) / 26; - var q = 1 << r; - - // Fast case: bit is much higher than all existing words - if (this.length <= s) return false; - - // Check bit and return - var w = this.words[s]; - - return !!(w & q); - }; - - // Return only lowers bits of number (in-place) - BN.prototype.imaskn = function imaskn (bits) { - assert(typeof bits === 'number' && bits >= 0); - var r = bits % 26; - var s = (bits - r) / 26; - - assert(this.negative === 0, 'imaskn works only with positive numbers'); - - if (this.length <= s) { - return this; - } - - if (r !== 0) { - s++; - } - this.length = Math.min(s, this.length); - - if (r !== 0) { - var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r); - this.words[this.length - 1] &= mask; - } - - return this.strip(); - }; - - // Return only lowers bits of number - BN.prototype.maskn = function maskn (bits) { - return this.clone().imaskn(bits); - }; - - // Add plain number `num` to `this` - BN.prototype.iaddn = function iaddn (num) { - assert(typeof num === 'number'); - assert(num < 0x4000000); - if (num < 0) return this.isubn(-num); - - // Possible sign change - if (this.negative !== 0) { - if (this.length === 1 && (this.words[0] | 0) < num) { - this.words[0] = num - (this.words[0] | 0); - this.negative = 0; - return this; - } - - this.negative = 0; - this.isubn(num); - this.negative = 1; - return this; - } - - // Add without checks - return this._iaddn(num); - }; - - BN.prototype._iaddn = function _iaddn (num) { - this.words[0] += num; - - // Carry - for (var i = 0; i < this.length && this.words[i] >= 0x4000000; i++) { - this.words[i] -= 0x4000000; - if (i === this.length - 1) { - this.words[i + 1] = 1; - } else { - this.words[i + 1]++; - } - } - this.length = Math.max(this.length, i + 1); - - return this; - }; - - // Subtract plain number `num` from `this` - BN.prototype.isubn = function isubn (num) { - assert(typeof num === 'number'); - assert(num < 0x4000000); - if (num < 0) return this.iaddn(-num); - - if (this.negative !== 0) { - this.negative = 0; - this.iaddn(num); - this.negative = 1; - return this; - } - - this.words[0] -= num; - - if (this.length === 1 && this.words[0] < 0) { - this.words[0] = -this.words[0]; - this.negative = 1; - } else { - // Carry - for (var i = 0; i < this.length && this.words[i] < 0; i++) { - this.words[i] += 0x4000000; - this.words[i + 1] -= 1; - } - } - - return this.strip(); - }; - - BN.prototype.addn = function addn (num) { - return this.clone().iaddn(num); - }; - - BN.prototype.subn = function subn (num) { - return this.clone().isubn(num); - }; - - BN.prototype.iabs = function iabs () { - this.negative = 0; - - return this; - }; - - BN.prototype.abs = function abs () { - return this.clone().iabs(); - }; - - BN.prototype._ishlnsubmul = function _ishlnsubmul (num, mul, shift) { - var len = num.length + shift; - var i; - - this._expand(len); - - var w; - var carry = 0; - for (i = 0; i < num.length; i++) { - w = (this.words[i + shift] | 0) + carry; - var right = (num.words[i] | 0) * mul; - w -= right & 0x3ffffff; - carry = (w >> 26) - ((right / 0x4000000) | 0); - this.words[i + shift] = w & 0x3ffffff; - } - for (; i < this.length - shift; i++) { - w = (this.words[i + shift] | 0) + carry; - carry = w >> 26; - this.words[i + shift] = w & 0x3ffffff; - } - - if (carry === 0) return this.strip(); - - // Subtraction overflow - assert(carry === -1); - carry = 0; - for (i = 0; i < this.length; i++) { - w = -(this.words[i] | 0) + carry; - carry = w >> 26; - this.words[i] = w & 0x3ffffff; - } - this.negative = 1; - - return this.strip(); - }; - - BN.prototype._wordDiv = function _wordDiv (num, mode) { - var shift = this.length - num.length; - - var a = this.clone(); - var b = num; - - // Normalize - var bhi = b.words[b.length - 1] | 0; - var bhiBits = this._countBits(bhi); - shift = 26 - bhiBits; - if (shift !== 0) { - b = b.ushln(shift); - a.iushln(shift); - bhi = b.words[b.length - 1] | 0; - } - - // Initialize quotient - var m = a.length - b.length; - var q; - - if (mode !== 'mod') { - q = new BN(null); - q.length = m + 1; - q.words = new Array(q.length); - for (var i = 0; i < q.length; i++) { - q.words[i] = 0; - } - } - - var diff = a.clone()._ishlnsubmul(b, 1, m); - if (diff.negative === 0) { - a = diff; - if (q) { - q.words[m] = 1; - } - } - - for (var j = m - 1; j >= 0; j--) { - var qj = (a.words[b.length + j] | 0) * 0x4000000 + - (a.words[b.length + j - 1] | 0); - - // NOTE: (qj / bhi) is (0x3ffffff * 0x4000000 + 0x3ffffff) / 0x2000000 max - // (0x7ffffff) - qj = Math.min((qj / bhi) | 0, 0x3ffffff); - - a._ishlnsubmul(b, qj, j); - while (a.negative !== 0) { - qj--; - a.negative = 0; - a._ishlnsubmul(b, 1, j); - if (!a.isZero()) { - a.negative ^= 1; - } - } - if (q) { - q.words[j] = qj; - } - } - if (q) { - q.strip(); - } - a.strip(); - - // Denormalize - if (mode !== 'div' && shift !== 0) { - a.iushrn(shift); - } - - return { - div: q || null, - mod: a - }; - }; - - // NOTE: 1) `mode` can be set to `mod` to request mod only, - // to `div` to request div only, or be absent to - // request both div & mod - // 2) `positive` is true if unsigned mod is requested - BN.prototype.divmod = function divmod (num, mode, positive) { - assert(!num.isZero()); - - if (this.isZero()) { - return { - div: new BN(0), - mod: new BN(0) - }; - } - - var div, mod, res; - if (this.negative !== 0 && num.negative === 0) { - res = this.neg().divmod(num, mode); - - if (mode !== 'mod') { - div = res.div.neg(); - } - - if (mode !== 'div') { - mod = res.mod.neg(); - if (positive && mod.negative !== 0) { - mod.iadd(num); - } - } - - return { - div: div, - mod: mod - }; - } - - if (this.negative === 0 && num.negative !== 0) { - res = this.divmod(num.neg(), mode); - - if (mode !== 'mod') { - div = res.div.neg(); - } - - return { - div: div, - mod: res.mod - }; - } - - if ((this.negative & num.negative) !== 0) { - res = this.neg().divmod(num.neg(), mode); - - if (mode !== 'div') { - mod = res.mod.neg(); - if (positive && mod.negative !== 0) { - mod.isub(num); - } - } - - return { - div: res.div, - mod: mod - }; - } - - // Both numbers are positive at this point - - // Strip both numbers to approximate shift value - if (num.length > this.length || this.cmp(num) < 0) { - return { - div: new BN(0), - mod: this - }; - } - - // Very short reduction - if (num.length === 1) { - if (mode === 'div') { - return { - div: this.divn(num.words[0]), - mod: null - }; - } - - if (mode === 'mod') { - return { - div: null, - mod: new BN(this.modn(num.words[0])) - }; - } - - return { - div: this.divn(num.words[0]), - mod: new BN(this.modn(num.words[0])) - }; - } - - return this._wordDiv(num, mode); - }; - - // Find `this` / `num` - BN.prototype.div = function div (num) { - return this.divmod(num, 'div', false).div; - }; - - // Find `this` % `num` - BN.prototype.mod = function mod (num) { - return this.divmod(num, 'mod', false).mod; - }; - - BN.prototype.umod = function umod (num) { - return this.divmod(num, 'mod', true).mod; - }; - - // Find Round(`this` / `num`) - BN.prototype.divRound = function divRound (num) { - var dm = this.divmod(num); - - // Fast case - exact division - if (dm.mod.isZero()) return dm.div; - - var mod = dm.div.negative !== 0 ? dm.mod.isub(num) : dm.mod; - - var half = num.ushrn(1); - var r2 = num.andln(1); - var cmp = mod.cmp(half); - - // Round down - if (cmp < 0 || r2 === 1 && cmp === 0) return dm.div; - - // Round up - return dm.div.negative !== 0 ? dm.div.isubn(1) : dm.div.iaddn(1); - }; - - BN.prototype.modn = function modn (num) { - assert(num <= 0x3ffffff); - var p = (1 << 26) % num; - - var acc = 0; - for (var i = this.length - 1; i >= 0; i--) { - acc = (p * acc + (this.words[i] | 0)) % num; - } - - return acc; - }; - - // In-place division by number - BN.prototype.idivn = function idivn (num) { - assert(num <= 0x3ffffff); - - var carry = 0; - for (var i = this.length - 1; i >= 0; i--) { - var w = (this.words[i] | 0) + carry * 0x4000000; - this.words[i] = (w / num) | 0; - carry = w % num; - } - - return this.strip(); - }; - - BN.prototype.divn = function divn (num) { - return this.clone().idivn(num); - }; - - BN.prototype.egcd = function egcd (p) { - assert(p.negative === 0); - assert(!p.isZero()); - - var x = this; - var y = p.clone(); - - if (x.negative !== 0) { - x = x.umod(p); - } else { - x = x.clone(); - } - - // A * x + B * y = x - var A = new BN(1); - var B = new BN(0); - - // C * x + D * y = y - var C = new BN(0); - var D = new BN(1); - - var g = 0; - - while (x.isEven() && y.isEven()) { - x.iushrn(1); - y.iushrn(1); - ++g; - } - - var yp = y.clone(); - var xp = x.clone(); - - while (!x.isZero()) { - for (var i = 0, im = 1; (x.words[0] & im) === 0 && i < 26; ++i, im <<= 1); - if (i > 0) { - x.iushrn(i); - while (i-- > 0) { - if (A.isOdd() || B.isOdd()) { - A.iadd(yp); - B.isub(xp); - } - - A.iushrn(1); - B.iushrn(1); - } - } - - for (var j = 0, jm = 1; (y.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1); - if (j > 0) { - y.iushrn(j); - while (j-- > 0) { - if (C.isOdd() || D.isOdd()) { - C.iadd(yp); - D.isub(xp); - } - - C.iushrn(1); - D.iushrn(1); - } - } - - if (x.cmp(y) >= 0) { - x.isub(y); - A.isub(C); - B.isub(D); - } else { - y.isub(x); - C.isub(A); - D.isub(B); - } - } - - return { - a: C, - b: D, - gcd: y.iushln(g) - }; - }; - - // This is reduced incarnation of the binary EEA - // above, designated to invert members of the - // _prime_ fields F(p) at a maximal speed - BN.prototype._invmp = function _invmp (p) { - assert(p.negative === 0); - assert(!p.isZero()); - - var a = this; - var b = p.clone(); - - if (a.negative !== 0) { - a = a.umod(p); - } else { - a = a.clone(); - } - - var x1 = new BN(1); - var x2 = new BN(0); - - var delta = b.clone(); - - while (a.cmpn(1) > 0 && b.cmpn(1) > 0) { - for (var i = 0, im = 1; (a.words[0] & im) === 0 && i < 26; ++i, im <<= 1); - if (i > 0) { - a.iushrn(i); - while (i-- > 0) { - if (x1.isOdd()) { - x1.iadd(delta); - } - - x1.iushrn(1); - } - } - - for (var j = 0, jm = 1; (b.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1); - if (j > 0) { - b.iushrn(j); - while (j-- > 0) { - if (x2.isOdd()) { - x2.iadd(delta); - } - - x2.iushrn(1); - } - } - - if (a.cmp(b) >= 0) { - a.isub(b); - x1.isub(x2); - } else { - b.isub(a); - x2.isub(x1); - } - } - - var res; - if (a.cmpn(1) === 0) { - res = x1; - } else { - res = x2; - } - - if (res.cmpn(0) < 0) { - res.iadd(p); - } - - return res; - }; - - BN.prototype.gcd = function gcd (num) { - if (this.isZero()) return num.abs(); - if (num.isZero()) return this.abs(); - - var a = this.clone(); - var b = num.clone(); - a.negative = 0; - b.negative = 0; - - // Remove common factor of two - for (var shift = 0; a.isEven() && b.isEven(); shift++) { - a.iushrn(1); - b.iushrn(1); - } - - do { - while (a.isEven()) { - a.iushrn(1); - } - while (b.isEven()) { - b.iushrn(1); - } - - var r = a.cmp(b); - if (r < 0) { - // Swap `a` and `b` to make `a` always bigger than `b` - var t = a; - a = b; - b = t; - } else if (r === 0 || b.cmpn(1) === 0) { - break; - } - - a.isub(b); - } while (true); - - return b.iushln(shift); - }; - - // Invert number in the field F(num) - BN.prototype.invm = function invm (num) { - return this.egcd(num).a.umod(num); - }; - - BN.prototype.isEven = function isEven () { - return (this.words[0] & 1) === 0; - }; - - BN.prototype.isOdd = function isOdd () { - return (this.words[0] & 1) === 1; - }; - - // And first word and num - BN.prototype.andln = function andln (num) { - return this.words[0] & num; - }; - - // Increment at the bit position in-line - BN.prototype.bincn = function bincn (bit) { - assert(typeof bit === 'number'); - var r = bit % 26; - var s = (bit - r) / 26; - var q = 1 << r; - - // Fast case: bit is much higher than all existing words - if (this.length <= s) { - this._expand(s + 1); - this.words[s] |= q; - return this; - } - - // Add bit and propagate, if needed - var carry = q; - for (var i = s; carry !== 0 && i < this.length; i++) { - var w = this.words[i] | 0; - w += carry; - carry = w >>> 26; - w &= 0x3ffffff; - this.words[i] = w; - } - if (carry !== 0) { - this.words[i] = carry; - this.length++; - } - return this; - }; - - BN.prototype.isZero = function isZero () { - return this.length === 1 && this.words[0] === 0; - }; - - BN.prototype.cmpn = function cmpn (num) { - var negative = num < 0; - - if (this.negative !== 0 && !negative) return -1; - if (this.negative === 0 && negative) return 1; - - this.strip(); - - var res; - if (this.length > 1) { - res = 1; - } else { - if (negative) { - num = -num; - } - - assert(num <= 0x3ffffff, 'Number is too big'); - - var w = this.words[0] | 0; - res = w === num ? 0 : w < num ? -1 : 1; - } - if (this.negative !== 0) return -res | 0; - return res; - }; - - // Compare two numbers and return: - // 1 - if `this` > `num` - // 0 - if `this` == `num` - // -1 - if `this` < `num` - BN.prototype.cmp = function cmp (num) { - if (this.negative !== 0 && num.negative === 0) return -1; - if (this.negative === 0 && num.negative !== 0) return 1; - - var res = this.ucmp(num); - if (this.negative !== 0) return -res | 0; - return res; - }; - - // Unsigned comparison - BN.prototype.ucmp = function ucmp (num) { - // At this point both numbers have the same sign - if (this.length > num.length) return 1; - if (this.length < num.length) return -1; - - var res = 0; - for (var i = this.length - 1; i >= 0; i--) { - var a = this.words[i] | 0; - var b = num.words[i] | 0; - - if (a === b) continue; - if (a < b) { - res = -1; - } else if (a > b) { - res = 1; - } - break; - } - return res; - }; - - BN.prototype.gtn = function gtn (num) { - return this.cmpn(num) === 1; - }; - - BN.prototype.gt = function gt (num) { - return this.cmp(num) === 1; - }; - - BN.prototype.gten = function gten (num) { - return this.cmpn(num) >= 0; - }; - - BN.prototype.gte = function gte (num) { - return this.cmp(num) >= 0; - }; - - BN.prototype.ltn = function ltn (num) { - return this.cmpn(num) === -1; - }; - - BN.prototype.lt = function lt (num) { - return this.cmp(num) === -1; - }; - - BN.prototype.lten = function lten (num) { - return this.cmpn(num) <= 0; - }; - - BN.prototype.lte = function lte (num) { - return this.cmp(num) <= 0; - }; - - BN.prototype.eqn = function eqn (num) { - return this.cmpn(num) === 0; - }; - - BN.prototype.eq = function eq (num) { - return this.cmp(num) === 0; - }; - - // - // A reduce context, could be using montgomery or something better, depending - // on the `m` itself. - // - BN.red = function red (num) { - return new Red(num); - }; - - BN.prototype.toRed = function toRed (ctx) { - assert(!this.red, 'Already a number in reduction context'); - assert(this.negative === 0, 'red works only with positives'); - return ctx.convertTo(this)._forceRed(ctx); - }; - - BN.prototype.fromRed = function fromRed () { - assert(this.red, 'fromRed works only with numbers in reduction context'); - return this.red.convertFrom(this); - }; - - BN.prototype._forceRed = function _forceRed (ctx) { - this.red = ctx; - return this; - }; - - BN.prototype.forceRed = function forceRed (ctx) { - assert(!this.red, 'Already a number in reduction context'); - return this._forceRed(ctx); - }; - - BN.prototype.redAdd = function redAdd (num) { - assert(this.red, 'redAdd works only with red numbers'); - return this.red.add(this, num); - }; - - BN.prototype.redIAdd = function redIAdd (num) { - assert(this.red, 'redIAdd works only with red numbers'); - return this.red.iadd(this, num); - }; - - BN.prototype.redSub = function redSub (num) { - assert(this.red, 'redSub works only with red numbers'); - return this.red.sub(this, num); - }; - - BN.prototype.redISub = function redISub (num) { - assert(this.red, 'redISub works only with red numbers'); - return this.red.isub(this, num); - }; - - BN.prototype.redShl = function redShl (num) { - assert(this.red, 'redShl works only with red numbers'); - return this.red.shl(this, num); - }; - - BN.prototype.redMul = function redMul (num) { - assert(this.red, 'redMul works only with red numbers'); - this.red._verify2(this, num); - return this.red.mul(this, num); - }; - - BN.prototype.redIMul = function redIMul (num) { - assert(this.red, 'redMul works only with red numbers'); - this.red._verify2(this, num); - return this.red.imul(this, num); - }; - - BN.prototype.redSqr = function redSqr () { - assert(this.red, 'redSqr works only with red numbers'); - this.red._verify1(this); - return this.red.sqr(this); - }; - - BN.prototype.redISqr = function redISqr () { - assert(this.red, 'redISqr works only with red numbers'); - this.red._verify1(this); - return this.red.isqr(this); - }; - - // Square root over p - BN.prototype.redSqrt = function redSqrt () { - assert(this.red, 'redSqrt works only with red numbers'); - this.red._verify1(this); - return this.red.sqrt(this); - }; - - BN.prototype.redInvm = function redInvm () { - assert(this.red, 'redInvm works only with red numbers'); - this.red._verify1(this); - return this.red.invm(this); - }; - - // Return negative clone of `this` % `red modulo` - BN.prototype.redNeg = function redNeg () { - assert(this.red, 'redNeg works only with red numbers'); - this.red._verify1(this); - return this.red.neg(this); - }; - - BN.prototype.redPow = function redPow (num) { - assert(this.red && !num.red, 'redPow(normalNum)'); - this.red._verify1(this); - return this.red.pow(this, num); - }; - - // Prime numbers with efficient reduction - var primes = { - k256: null, - p224: null, - p192: null, - p25519: null - }; - - // Pseudo-Mersenne prime - function MPrime (name, p) { - // P = 2 ^ N - K - this.name = name; - this.p = new BN(p, 16); - this.n = this.p.bitLength(); - this.k = new BN(1).iushln(this.n).isub(this.p); - - this.tmp = this._tmp(); - } - - MPrime.prototype._tmp = function _tmp () { - var tmp = new BN(null); - tmp.words = new Array(Math.ceil(this.n / 13)); - return tmp; - }; - - MPrime.prototype.ireduce = function ireduce (num) { - // Assumes that `num` is less than `P^2` - // num = HI * (2 ^ N - K) + HI * K + LO = HI * K + LO (mod P) - var r = num; - var rlen; - - do { - this.split(r, this.tmp); - r = this.imulK(r); - r = r.iadd(this.tmp); - rlen = r.bitLength(); - } while (rlen > this.n); - - var cmp = rlen < this.n ? -1 : r.ucmp(this.p); - if (cmp === 0) { - r.words[0] = 0; - r.length = 1; - } else if (cmp > 0) { - r.isub(this.p); - } else { - if (r.strip !== undefined) { - // r is BN v4 instance - r.strip(); - } else { - // r is BN v5 instance - r._strip(); - } - } - - return r; - }; - - MPrime.prototype.split = function split (input, out) { - input.iushrn(this.n, 0, out); - }; - - MPrime.prototype.imulK = function imulK (num) { - return num.imul(this.k); - }; - - function K256 () { - MPrime.call( - this, - 'k256', - 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f'); - } - inherits(K256, MPrime); - - K256.prototype.split = function split (input, output) { - // 256 = 9 * 26 + 22 - var mask = 0x3fffff; - - var outLen = Math.min(input.length, 9); - for (var i = 0; i < outLen; i++) { - output.words[i] = input.words[i]; - } - output.length = outLen; - - if (input.length <= 9) { - input.words[0] = 0; - input.length = 1; - return; - } - - // Shift by 9 limbs - var prev = input.words[9]; - output.words[output.length++] = prev & mask; - - for (i = 10; i < input.length; i++) { - var next = input.words[i] | 0; - input.words[i - 10] = ((next & mask) << 4) | (prev >>> 22); - prev = next; - } - prev >>>= 22; - input.words[i - 10] = prev; - if (prev === 0 && input.length > 10) { - input.length -= 10; - } else { - input.length -= 9; - } - }; - - K256.prototype.imulK = function imulK (num) { - // K = 0x1000003d1 = [ 0x40, 0x3d1 ] - num.words[num.length] = 0; - num.words[num.length + 1] = 0; - num.length += 2; - - // bounded at: 0x40 * 0x3ffffff + 0x3d0 = 0x100000390 - var lo = 0; - for (var i = 0; i < num.length; i++) { - var w = num.words[i] | 0; - lo += w * 0x3d1; - num.words[i] = lo & 0x3ffffff; - lo = w * 0x40 + ((lo / 0x4000000) | 0); - } - - // Fast length reduction - if (num.words[num.length - 1] === 0) { - num.length--; - if (num.words[num.length - 1] === 0) { - num.length--; - } - } - return num; - }; - - function P224 () { - MPrime.call( - this, - 'p224', - 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001'); - } - inherits(P224, MPrime); - - function P192 () { - MPrime.call( - this, - 'p192', - 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff'); - } - inherits(P192, MPrime); - - function P25519 () { - // 2 ^ 255 - 19 - MPrime.call( - this, - '25519', - '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed'); - } - inherits(P25519, MPrime); - - P25519.prototype.imulK = function imulK (num) { - // K = 0x13 - var carry = 0; - for (var i = 0; i < num.length; i++) { - var hi = (num.words[i] | 0) * 0x13 + carry; - var lo = hi & 0x3ffffff; - hi >>>= 26; - - num.words[i] = lo; - carry = hi; - } - if (carry !== 0) { - num.words[num.length++] = carry; - } - return num; - }; - - // Exported mostly for testing purposes, use plain name instead - BN._prime = function prime (name) { - // Cached version of prime - if (primes[name]) return primes[name]; - - var prime; - if (name === 'k256') { - prime = new K256(); - } else if (name === 'p224') { - prime = new P224(); - } else if (name === 'p192') { - prime = new P192(); - } else if (name === 'p25519') { - prime = new P25519(); - } else { - throw new Error('Unknown prime ' + name); - } - primes[name] = prime; - - return prime; - }; - - // - // Base reduction engine - // - function Red (m) { - if (typeof m === 'string') { - var prime = BN._prime(m); - this.m = prime.p; - this.prime = prime; - } else { - assert(m.gtn(1), 'modulus must be greater than 1'); - this.m = m; - this.prime = null; - } - } - - Red.prototype._verify1 = function _verify1 (a) { - assert(a.negative === 0, 'red works only with positives'); - assert(a.red, 'red works only with red numbers'); - }; - - Red.prototype._verify2 = function _verify2 (a, b) { - assert((a.negative | b.negative) === 0, 'red works only with positives'); - assert(a.red && a.red === b.red, - 'red works only with red numbers'); - }; - - Red.prototype.imod = function imod (a) { - if (this.prime) return this.prime.ireduce(a)._forceRed(this); - return a.umod(this.m)._forceRed(this); - }; - - Red.prototype.neg = function neg (a) { - if (a.isZero()) { - return a.clone(); - } - - return this.m.sub(a)._forceRed(this); - }; - - Red.prototype.add = function add (a, b) { - this._verify2(a, b); - - var res = a.add(b); - if (res.cmp(this.m) >= 0) { - res.isub(this.m); - } - return res._forceRed(this); - }; - - Red.prototype.iadd = function iadd (a, b) { - this._verify2(a, b); - - var res = a.iadd(b); - if (res.cmp(this.m) >= 0) { - res.isub(this.m); - } - return res; - }; - - Red.prototype.sub = function sub (a, b) { - this._verify2(a, b); - - var res = a.sub(b); - if (res.cmpn(0) < 0) { - res.iadd(this.m); - } - return res._forceRed(this); - }; - - Red.prototype.isub = function isub (a, b) { - this._verify2(a, b); - - var res = a.isub(b); - if (res.cmpn(0) < 0) { - res.iadd(this.m); - } - return res; - }; - - Red.prototype.shl = function shl (a, num) { - this._verify1(a); - return this.imod(a.ushln(num)); - }; - - Red.prototype.imul = function imul (a, b) { - this._verify2(a, b); - return this.imod(a.imul(b)); - }; - - Red.prototype.mul = function mul (a, b) { - this._verify2(a, b); - return this.imod(a.mul(b)); - }; - - Red.prototype.isqr = function isqr (a) { - return this.imul(a, a.clone()); - }; - - Red.prototype.sqr = function sqr (a) { - return this.mul(a, a); - }; - - Red.prototype.sqrt = function sqrt (a) { - if (a.isZero()) return a.clone(); - - var mod3 = this.m.andln(3); - assert(mod3 % 2 === 1); - - // Fast case - if (mod3 === 3) { - var pow = this.m.add(new BN(1)).iushrn(2); - return this.pow(a, pow); - } - - // Tonelli-Shanks algorithm (Totally unoptimized and slow) - // - // Find Q and S, that Q * 2 ^ S = (P - 1) - var q = this.m.subn(1); - var s = 0; - while (!q.isZero() && q.andln(1) === 0) { - s++; - q.iushrn(1); - } - assert(!q.isZero()); - - var one = new BN(1).toRed(this); - var nOne = one.redNeg(); - - // Find quadratic non-residue - // NOTE: Max is such because of generalized Riemann hypothesis. - var lpow = this.m.subn(1).iushrn(1); - var z = this.m.bitLength(); - z = new BN(2 * z * z).toRed(this); - - while (this.pow(z, lpow).cmp(nOne) !== 0) { - z.redIAdd(nOne); - } - - var c = this.pow(z, q); - var r = this.pow(a, q.addn(1).iushrn(1)); - var t = this.pow(a, q); - var m = s; - while (t.cmp(one) !== 0) { - var tmp = t; - for (var i = 0; tmp.cmp(one) !== 0; i++) { - tmp = tmp.redSqr(); - } - assert(i < m); - var b = this.pow(c, new BN(1).iushln(m - i - 1)); - - r = r.redMul(b); - c = b.redSqr(); - t = t.redMul(c); - m = i; - } - - return r; - }; - - Red.prototype.invm = function invm (a) { - var inv = a._invmp(this.m); - if (inv.negative !== 0) { - inv.negative = 0; - return this.imod(inv).redNeg(); - } else { - return this.imod(inv); - } - }; - - Red.prototype.pow = function pow (a, num) { - if (num.isZero()) return new BN(1).toRed(this); - if (num.cmpn(1) === 0) return a.clone(); - - var windowSize = 4; - var wnd = new Array(1 << windowSize); - wnd[0] = new BN(1).toRed(this); - wnd[1] = a; - for (var i = 2; i < wnd.length; i++) { - wnd[i] = this.mul(wnd[i - 1], a); - } - - var res = wnd[0]; - var current = 0; - var currentLen = 0; - var start = num.bitLength() % 26; - if (start === 0) { - start = 26; - } - - for (i = num.length - 1; i >= 0; i--) { - var word = num.words[i]; - for (var j = start - 1; j >= 0; j--) { - var bit = (word >> j) & 1; - if (res !== wnd[0]) { - res = this.sqr(res); - } - - if (bit === 0 && current === 0) { - currentLen = 0; - continue; - } - - current <<= 1; - current |= bit; - currentLen++; - if (currentLen !== windowSize && (i !== 0 || j !== 0)) continue; - - res = this.mul(res, wnd[current]); - currentLen = 0; - current = 0; - } - start = 26; - } - - return res; - }; - - Red.prototype.convertTo = function convertTo (num) { - var r = num.umod(this.m); - - return r === num ? r.clone() : r; - }; - - Red.prototype.convertFrom = function convertFrom (num) { - var res = num.clone(); - res.red = null; - return res; - }; - - // - // Montgomery method engine - // - - BN.mont = function mont (num) { - return new Mont(num); - }; - - function Mont (m) { - Red.call(this, m); - - this.shift = this.m.bitLength(); - if (this.shift % 26 !== 0) { - this.shift += 26 - (this.shift % 26); - } - - this.r = new BN(1).iushln(this.shift); - this.r2 = this.imod(this.r.sqr()); - this.rinv = this.r._invmp(this.m); - - this.minv = this.rinv.mul(this.r).isubn(1).div(this.m); - this.minv = this.minv.umod(this.r); - this.minv = this.r.sub(this.minv); - } - inherits(Mont, Red); - - Mont.prototype.convertTo = function convertTo (num) { - return this.imod(num.ushln(this.shift)); - }; - - Mont.prototype.convertFrom = function convertFrom (num) { - var r = this.imod(num.mul(this.rinv)); - r.red = null; - return r; - }; - - Mont.prototype.imul = function imul (a, b) { - if (a.isZero() || b.isZero()) { - a.words[0] = 0; - a.length = 1; - return a; - } - - var t = a.imul(b); - var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m); - var u = t.isub(c).iushrn(this.shift); - var res = u; - - if (u.cmp(this.m) >= 0) { - res = u.isub(this.m); - } else if (u.cmpn(0) < 0) { - res = u.iadd(this.m); - } - - return res._forceRed(this); - }; - - Mont.prototype.mul = function mul (a, b) { - if (a.isZero() || b.isZero()) return new BN(0)._forceRed(this); - - var t = a.mul(b); - var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m); - var u = t.isub(c).iushrn(this.shift); - var res = u; - if (u.cmp(this.m) >= 0) { - res = u.isub(this.m); - } else if (u.cmpn(0) < 0) { - res = u.iadd(this.m); - } - - return res._forceRed(this); - }; - - Mont.prototype.invm = function invm (a) { - // (AR)^-1 * R^2 = (A^-1 * R^-1) * R^2 = A^-1 * R - var res = this.imod(a._invmp(this.m).mul(this.r2)); - return res._forceRed(this); - }; -})( false || module, this); - - -/***/ }), - -/***/ 7457: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; -/*jshint node:true */ - -var Buffer = (__nccwpck_require__(4300).Buffer); // browserify -var SlowBuffer = (__nccwpck_require__(4300).SlowBuffer); - -module.exports = bufferEq; - -function bufferEq(a, b) { - - // shortcutting on type is necessary for correctness - if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { - return false; - } - - // buffer sizes should be well-known information, so despite this - // shortcutting, it doesn't leak any information about the *contents* of the - // buffers. - if (a.length !== b.length) { - return false; - } - - var c = 0; - for (var i = 0; i < a.length; i++) { - /*jshint bitwise:false */ - c |= a[i] ^ b[i]; // XOR - } - return c === 0; -} - -bufferEq.install = function() { - Buffer.prototype.equal = SlowBuffer.prototype.equal = function equal(that) { - return bufferEq(this, that); - }; -}; - -var origBufEqual = Buffer.prototype.equal; -var origSlowBufEqual = SlowBuffer.prototype.equal; -bufferEq.restore = function() { - Buffer.prototype.equal = origBufEqual; - SlowBuffer.prototype.equal = origSlowBufEqual; -}; - - -/***/ }), - -/***/ 3756: -/***/ ((module, exports, __nccwpck_require__) => { - -/* eslint-env browser */ - -/** - * This is the web browser implementation of `debug()`. - */ - -exports.formatArgs = formatArgs; -exports.save = save; -exports.load = load; -exports.useColors = useColors; -exports.storage = localstorage(); -exports.destroy = (() => { - let warned = false; - - return () => { - if (!warned) { - warned = true; - console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); - } - }; -})(); - -/** - * Colors. - */ - -exports.colors = [ - '#0000CC', - '#0000FF', - '#0033CC', - '#0033FF', - '#0066CC', - '#0066FF', - '#0099CC', - '#0099FF', - '#00CC00', - '#00CC33', - '#00CC66', - '#00CC99', - '#00CCCC', - '#00CCFF', - '#3300CC', - '#3300FF', - '#3333CC', - '#3333FF', - '#3366CC', - '#3366FF', - '#3399CC', - '#3399FF', - '#33CC00', - '#33CC33', - '#33CC66', - '#33CC99', - '#33CCCC', - '#33CCFF', - '#6600CC', - '#6600FF', - '#6633CC', - '#6633FF', - '#66CC00', - '#66CC33', - '#9900CC', - '#9900FF', - '#9933CC', - '#9933FF', - '#99CC00', - '#99CC33', - '#CC0000', - '#CC0033', - '#CC0066', - '#CC0099', - '#CC00CC', - '#CC00FF', - '#CC3300', - '#CC3333', - '#CC3366', - '#CC3399', - '#CC33CC', - '#CC33FF', - '#CC6600', - '#CC6633', - '#CC9900', - '#CC9933', - '#CCCC00', - '#CCCC33', - '#FF0000', - '#FF0033', - '#FF0066', - '#FF0099', - '#FF00CC', - '#FF00FF', - '#FF3300', - '#FF3333', - '#FF3366', - '#FF3399', - '#FF33CC', - '#FF33FF', - '#FF6600', - '#FF6633', - '#FF9900', - '#FF9933', - '#FFCC00', - '#FFCC33' -]; - -/** - * Currently only WebKit-based Web Inspectors, Firefox >= v31, - * and the Firebug extension (any Firefox version) are known - * to support "%c" CSS customizations. - * - * TODO: add a `localStorage` variable to explicitly enable/disable colors - */ - -// eslint-disable-next-line complexity -function useColors() { - // NB: In an Electron preload script, document will be defined but not fully - // initialized. Since we know we're in Chrome, we'll just detect this case - // explicitly - if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) { - return true; - } - - // Internet Explorer and Edge do not support colors. - if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) { - return false; - } - - // Is webkit? http://stackoverflow.com/a/16459606/376773 - // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 - return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) || - // Is firebug? http://stackoverflow.com/a/398120/376773 - (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) || - // Is firefox >= v31? - // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages - (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) || - // Double check webkit in userAgent just in case we are in a worker - (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)); -} - -/** - * Colorize log arguments if enabled. - * - * @api public - */ - -function formatArgs(args) { - args[0] = (this.useColors ? '%c' : '') + - this.namespace + - (this.useColors ? ' %c' : ' ') + - args[0] + - (this.useColors ? '%c ' : ' ') + - '+' + module.exports.humanize(this.diff); - - if (!this.useColors) { - return; - } - - const c = 'color: ' + this.color; - args.splice(1, 0, c, 'color: inherit'); - - // The final "%c" is somewhat tricky, because there could be other - // arguments passed either before or after the %c, so we need to - // figure out the correct index to insert the CSS into - let index = 0; - let lastC = 0; - args[0].replace(/%[a-zA-Z%]/g, match => { - if (match === '%%') { - return; - } - index++; - if (match === '%c') { - // We only are interested in the *last* %c - // (the user may have provided their own) - lastC = index; - } - }); - - args.splice(lastC, 0, c); -} - -/** - * Invokes `console.debug()` when available. - * No-op when `console.debug` is not a "function". - * If `console.debug` is not available, falls back - * to `console.log`. - * - * @api public - */ -exports.log = console.debug || console.log || (() => {}); - -/** - * Save `namespaces`. - * - * @param {String} namespaces - * @api private - */ -function save(namespaces) { - try { - if (namespaces) { - exports.storage.setItem('debug', namespaces); - } else { - exports.storage.removeItem('debug'); - } - } catch (error) { - // Swallow - // XXX (@Qix-) should we be logging these? - } -} - -/** - * Load `namespaces`. - * - * @return {String} returns the previously persisted debug modes - * @api private - */ -function load() { - let r; - try { - r = exports.storage.getItem('debug'); - } catch (error) { - // Swallow - // XXX (@Qix-) should we be logging these? - } - - // If debug isn't set in LS, and we're in Electron, try to load $DEBUG - if (!r && typeof process !== 'undefined' && 'env' in process) { - r = process.env.DEBUG; - } - - return r; -} - -/** - * Localstorage attempts to return the localstorage. - * - * This is necessary because safari throws - * when a user disables cookies/localstorage - * and you attempt to access it. - * - * @return {LocalStorage} - * @api private - */ - -function localstorage() { - try { - // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context - // The Browser also has localStorage in the global context. - return localStorage; - } catch (error) { - // Swallow - // XXX (@Qix-) should we be logging these? - } -} - -module.exports = __nccwpck_require__(8994)(exports); - -const {formatters} = module.exports; - -/** - * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. - */ - -formatters.j = function (v) { - try { - return JSON.stringify(v); - } catch (error) { - return '[UnexpectedJSONParseError]: ' + error.message; - } -}; - - -/***/ }), - -/***/ 8994: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - -/** - * This is the common logic for both the Node.js and web browser - * implementations of `debug()`. - */ - -function setup(env) { - createDebug.debug = createDebug; - createDebug.default = createDebug; - createDebug.coerce = coerce; - createDebug.disable = disable; - createDebug.enable = enable; - createDebug.enabled = enabled; - createDebug.humanize = __nccwpck_require__(3730); - createDebug.destroy = destroy; - - Object.keys(env).forEach(key => { - createDebug[key] = env[key]; - }); - - /** - * The currently active debug mode names, and names to skip. - */ - - createDebug.names = []; - createDebug.skips = []; - - /** - * Map of special "%n" handling functions, for the debug "format" argument. - * - * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". - */ - createDebug.formatters = {}; - - /** - * Selects a color for a debug namespace - * @param {String} namespace The namespace string for the debug instance to be colored - * @return {Number|String} An ANSI color code for the given namespace - * @api private - */ - function selectColor(namespace) { - let hash = 0; - - for (let i = 0; i < namespace.length; i++) { - hash = ((hash << 5) - hash) + namespace.charCodeAt(i); - hash |= 0; // Convert to 32bit integer - } - - return createDebug.colors[Math.abs(hash) % createDebug.colors.length]; - } - createDebug.selectColor = selectColor; - - /** - * Create a debugger with the given `namespace`. - * - * @param {String} namespace - * @return {Function} - * @api public - */ - function createDebug(namespace) { - let prevTime; - let enableOverride = null; - let namespacesCache; - let enabledCache; - - function debug(...args) { - // Disabled? - if (!debug.enabled) { - return; - } - - const self = debug; - - // Set `diff` timestamp - const curr = Number(new Date()); - const ms = curr - (prevTime || curr); - self.diff = ms; - self.prev = prevTime; - self.curr = curr; - prevTime = curr; - - args[0] = createDebug.coerce(args[0]); - - if (typeof args[0] !== 'string') { - // Anything else let's inspect with %O - args.unshift('%O'); - } - - // Apply any `formatters` transformations - let index = 0; - args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => { - // If we encounter an escaped % then don't increase the array index - if (match === '%%') { - return '%'; - } - index++; - const formatter = createDebug.formatters[format]; - if (typeof formatter === 'function') { - const val = args[index]; - match = formatter.call(self, val); - - // Now we need to remove `args[index]` since it's inlined in the `format` - args.splice(index, 1); - index--; - } - return match; - }); - - // Apply env-specific formatting (colors, etc.) - createDebug.formatArgs.call(self, args); - - const logFn = self.log || createDebug.log; - logFn.apply(self, args); - } - - debug.namespace = namespace; - debug.useColors = createDebug.useColors(); - debug.color = createDebug.selectColor(namespace); - debug.extend = extend; - debug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release. - - Object.defineProperty(debug, 'enabled', { - enumerable: true, - configurable: false, - get: () => { - if (enableOverride !== null) { - return enableOverride; - } - if (namespacesCache !== createDebug.namespaces) { - namespacesCache = createDebug.namespaces; - enabledCache = createDebug.enabled(namespace); - } - - return enabledCache; - }, - set: v => { - enableOverride = v; - } - }); - - // Env-specific initialization logic for debug instances - if (typeof createDebug.init === 'function') { - createDebug.init(debug); - } - - return debug; - } - - function extend(namespace, delimiter) { - const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace); - newDebug.log = this.log; - return newDebug; - } - - /** - * Enables a debug mode by namespaces. This can include modes - * separated by a colon and wildcards. - * - * @param {String} namespaces - * @api public - */ - function enable(namespaces) { - createDebug.save(namespaces); - createDebug.namespaces = namespaces; - - createDebug.names = []; - createDebug.skips = []; - - let i; - const split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); - const len = split.length; - - for (i = 0; i < len; i++) { - if (!split[i]) { - // ignore empty strings - continue; - } - - namespaces = split[i].replace(/\*/g, '.*?'); - - if (namespaces[0] === '-') { - createDebug.skips.push(new RegExp('^' + namespaces.slice(1) + '$')); - } else { - createDebug.names.push(new RegExp('^' + namespaces + '$')); - } - } - } - - /** - * Disable debug output. - * - * @return {String} namespaces - * @api public - */ - function disable() { - const namespaces = [ - ...createDebug.names.map(toNamespace), - ...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace) - ].join(','); - createDebug.enable(''); - return namespaces; - } - - /** - * Returns true if the given mode name is enabled, false otherwise. - * - * @param {String} name - * @return {Boolean} - * @api public - */ - function enabled(name) { - if (name[name.length - 1] === '*') { - return true; - } - - let i; - let len; - - for (i = 0, len = createDebug.skips.length; i < len; i++) { - if (createDebug.skips[i].test(name)) { - return false; - } - } - - for (i = 0, len = createDebug.names.length; i < len; i++) { - if (createDebug.names[i].test(name)) { - return true; - } - } - - return false; - } - - /** - * Convert regexp to namespace - * - * @param {RegExp} regxep - * @return {String} namespace - * @api private - */ - function toNamespace(regexp) { - return regexp.toString() - .substring(2, regexp.toString().length - 2) - .replace(/\.\*\?$/, '*'); - } - - /** - * Coerce `val`. - * - * @param {Mixed} val - * @return {Mixed} - * @api private - */ - function coerce(val) { - if (val instanceof Error) { - return val.stack || val.message; - } - return val; - } - - /** - * XXX DO NOT USE. This is a temporary stub function. - * XXX It WILL be removed in the next major release. - */ - function destroy() { - console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); - } - - createDebug.enable(createDebug.load()); - - return createDebug; -} - -module.exports = setup; - - -/***/ }), - -/***/ 5062: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -/** - * Detect Electron renderer / nwjs process, which is node, but we should - * treat as a browser. - */ - -if (typeof process === 'undefined' || process.type === 'renderer' || process.browser === true || process.__nwjs) { - module.exports = __nccwpck_require__(3756); -} else { - module.exports = __nccwpck_require__(5404); -} - - -/***/ }), - -/***/ 5404: -/***/ ((module, exports, __nccwpck_require__) => { - -/** - * Module dependencies. - */ - -const tty = __nccwpck_require__(6224); -const util = __nccwpck_require__(3837); - -/** - * This is the Node.js implementation of `debug()`. - */ - -exports.init = init; -exports.log = log; -exports.formatArgs = formatArgs; -exports.save = save; -exports.load = load; -exports.useColors = useColors; -exports.destroy = util.deprecate( - () => {}, - 'Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.' -); - -/** - * Colors. - */ - -exports.colors = [6, 2, 3, 4, 5, 1]; - -try { - // Optional dependency (as in, doesn't need to be installed, NOT like optionalDependencies in package.json) - // eslint-disable-next-line import/no-extraneous-dependencies - const supportsColor = __nccwpck_require__(4341); - - if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) { - exports.colors = [ - 20, - 21, - 26, - 27, - 32, - 33, - 38, - 39, - 40, - 41, - 42, - 43, - 44, - 45, - 56, - 57, - 62, - 63, - 68, - 69, - 74, - 75, - 76, - 77, - 78, - 79, - 80, - 81, - 92, - 93, - 98, - 99, - 112, - 113, - 128, - 129, - 134, - 135, - 148, - 149, - 160, - 161, - 162, - 163, - 164, - 165, - 166, - 167, - 168, - 169, - 170, - 171, - 172, - 173, - 178, - 179, - 184, - 185, - 196, - 197, - 198, - 199, - 200, - 201, - 202, - 203, - 204, - 205, - 206, - 207, - 208, - 209, - 214, - 215, - 220, - 221 - ]; - } -} catch (error) { - // Swallow - we only care if `supports-color` is available; it doesn't have to be. -} - -/** - * Build up the default `inspectOpts` object from the environment variables. - * - * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js - */ - -exports.inspectOpts = Object.keys(process.env).filter(key => { - return /^debug_/i.test(key); -}).reduce((obj, key) => { - // Camel-case - const prop = key - .substring(6) - .toLowerCase() - .replace(/_([a-z])/g, (_, k) => { - return k.toUpperCase(); - }); - - // Coerce string value into JS value - let val = process.env[key]; - if (/^(yes|on|true|enabled)$/i.test(val)) { - val = true; - } else if (/^(no|off|false|disabled)$/i.test(val)) { - val = false; - } else if (val === 'null') { - val = null; - } else { - val = Number(val); - } - - obj[prop] = val; - return obj; -}, {}); - -/** - * Is stdout a TTY? Colored output is enabled when `true`. - */ - -function useColors() { - return 'colors' in exports.inspectOpts ? - Boolean(exports.inspectOpts.colors) : - tty.isatty(process.stderr.fd); -} - -/** - * Adds ANSI color escape codes if enabled. - * - * @api public - */ - -function formatArgs(args) { - const {namespace: name, useColors} = this; - - if (useColors) { - const c = this.color; - const colorCode = '\u001B[3' + (c < 8 ? c : '8;5;' + c); - const prefix = ` ${colorCode};1m${name} \u001B[0m`; - - args[0] = prefix + args[0].split('\n').join('\n' + prefix); - args.push(colorCode + 'm+' + module.exports.humanize(this.diff) + '\u001B[0m'); - } else { - args[0] = getDate() + name + ' ' + args[0]; - } -} - -function getDate() { - if (exports.inspectOpts.hideDate) { - return ''; - } - return new Date().toISOString() + ' '; -} - -/** - * Invokes `util.formatWithOptions()` with the specified arguments and writes to stderr. - */ - -function log(...args) { - return process.stderr.write(util.formatWithOptions(exports.inspectOpts, ...args) + '\n'); -} - -/** - * Save `namespaces`. - * - * @param {String} namespaces - * @api private - */ -function save(namespaces) { - if (namespaces) { - process.env.DEBUG = namespaces; - } else { - // If you set a process.env field to null or undefined, it gets cast to the - // string 'null' or 'undefined'. Just delete instead. - delete process.env.DEBUG; - } -} - -/** - * Load `namespaces`. - * - * @return {String} returns the previously persisted debug modes - * @api private - */ - -function load() { - return process.env.DEBUG; -} - -/** - * Init logic for `debug` instances. - * - * Create a new `inspectOpts` object in case `useColors` is set - * differently for a particular `debug` instance. - */ - -function init(debug) { - debug.inspectOpts = {}; - - const keys = Object.keys(exports.inspectOpts); - for (let i = 0; i < keys.length; i++) { - debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]]; - } -} - -module.exports = __nccwpck_require__(8994)(exports); - -const {formatters} = module.exports; - -/** - * Map %o to `util.inspect()`, all on a single line. - */ - -formatters.o = function (v) { - this.inspectOpts.colors = this.useColors; - return util.inspect(v, this.inspectOpts) - .split('\n') - .map(str => str.trim()) - .join(' '); -}; - -/** - * Map %O to `util.inspect()`, allowing multiple lines if needed. - */ - -formatters.O = function (v) { - this.inspectOpts.colors = this.useColors; - return util.inspect(v, this.inspectOpts); -}; - - -/***/ }), - -/***/ 9877: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -var Buffer = (__nccwpck_require__(3925).Buffer); - -var getParamBytesForAlg = __nccwpck_require__(380); - -var MAX_OCTET = 0x80, - CLASS_UNIVERSAL = 0, - PRIMITIVE_BIT = 0x20, - TAG_SEQ = 0x10, - TAG_INT = 0x02, - ENCODED_TAG_SEQ = (TAG_SEQ | PRIMITIVE_BIT) | (CLASS_UNIVERSAL << 6), - ENCODED_TAG_INT = TAG_INT | (CLASS_UNIVERSAL << 6); - -function base64Url(base64) { - return base64 - .replace(/=/g, '') - .replace(/\+/g, '-') - .replace(/\//g, '_'); -} - -function signatureAsBuffer(signature) { - if (Buffer.isBuffer(signature)) { - return signature; - } else if ('string' === typeof signature) { - return Buffer.from(signature, 'base64'); - } - - throw new TypeError('ECDSA signature must be a Base64 string or a Buffer'); -} - -function derToJose(signature, alg) { - signature = signatureAsBuffer(signature); - var paramBytes = getParamBytesForAlg(alg); - - // the DER encoded param should at most be the param size, plus a padding - // zero, since due to being a signed integer - var maxEncodedParamLength = paramBytes + 1; - - var inputLength = signature.length; - - var offset = 0; - if (signature[offset++] !== ENCODED_TAG_SEQ) { - throw new Error('Could not find expected "seq"'); - } - - var seqLength = signature[offset++]; - if (seqLength === (MAX_OCTET | 1)) { - seqLength = signature[offset++]; - } - - if (inputLength - offset < seqLength) { - throw new Error('"seq" specified length of "' + seqLength + '", only "' + (inputLength - offset) + '" remaining'); - } - - if (signature[offset++] !== ENCODED_TAG_INT) { - throw new Error('Could not find expected "int" for "r"'); - } - - var rLength = signature[offset++]; - - if (inputLength - offset - 2 < rLength) { - throw new Error('"r" specified length of "' + rLength + '", only "' + (inputLength - offset - 2) + '" available'); - } - - if (maxEncodedParamLength < rLength) { - throw new Error('"r" specified length of "' + rLength + '", max of "' + maxEncodedParamLength + '" is acceptable'); - } - - var rOffset = offset; - offset += rLength; - - if (signature[offset++] !== ENCODED_TAG_INT) { - throw new Error('Could not find expected "int" for "s"'); - } - - var sLength = signature[offset++]; - - if (inputLength - offset !== sLength) { - throw new Error('"s" specified length of "' + sLength + '", expected "' + (inputLength - offset) + '"'); - } - - if (maxEncodedParamLength < sLength) { - throw new Error('"s" specified length of "' + sLength + '", max of "' + maxEncodedParamLength + '" is acceptable'); - } - - var sOffset = offset; - offset += sLength; - - if (offset !== inputLength) { - throw new Error('Expected to consume entire buffer, but "' + (inputLength - offset) + '" bytes remain'); - } - - var rPadding = paramBytes - rLength, - sPadding = paramBytes - sLength; - - var dst = Buffer.allocUnsafe(rPadding + rLength + sPadding + sLength); - - for (offset = 0; offset < rPadding; ++offset) { - dst[offset] = 0; - } - signature.copy(dst, offset, rOffset + Math.max(-rPadding, 0), rOffset + rLength); - - offset = paramBytes; - - for (var o = offset; offset < o + sPadding; ++offset) { - dst[offset] = 0; - } - signature.copy(dst, offset, sOffset + Math.max(-sPadding, 0), sOffset + sLength); - - dst = dst.toString('base64'); - dst = base64Url(dst); - - return dst; -} - -function countPadding(buf, start, stop) { - var padding = 0; - while (start + padding < stop && buf[start + padding] === 0) { - ++padding; - } - - var needsSign = buf[start + padding] >= MAX_OCTET; - if (needsSign) { - --padding; - } - - return padding; -} - -function joseToDer(signature, alg) { - signature = signatureAsBuffer(signature); - var paramBytes = getParamBytesForAlg(alg); - - var signatureBytes = signature.length; - if (signatureBytes !== paramBytes * 2) { - throw new TypeError('"' + alg + '" signatures must be "' + paramBytes * 2 + '" bytes, saw "' + signatureBytes + '"'); - } - - var rPadding = countPadding(signature, 0, paramBytes); - var sPadding = countPadding(signature, paramBytes, signature.length); - var rLength = paramBytes - rPadding; - var sLength = paramBytes - sPadding; - - var rsBytes = 1 + 1 + rLength + 1 + 1 + sLength; - - var shortLength = rsBytes < MAX_OCTET; - - var dst = Buffer.allocUnsafe((shortLength ? 2 : 3) + rsBytes); - - var offset = 0; - dst[offset++] = ENCODED_TAG_SEQ; - if (shortLength) { - // Bit 8 has value "0" - // bits 7-1 give the length. - dst[offset++] = rsBytes; - } else { - // Bit 8 of first octet has value "1" - // bits 7-1 give the number of additional length octets. - dst[offset++] = MAX_OCTET | 1; - // length, base 256 - dst[offset++] = rsBytes & 0xff; - } - dst[offset++] = ENCODED_TAG_INT; - dst[offset++] = rLength; - if (rPadding < 0) { - dst[offset++] = 0; - offset += signature.copy(dst, offset, 0, paramBytes); - } else { - offset += signature.copy(dst, offset, rPadding, paramBytes); - } - dst[offset++] = ENCODED_TAG_INT; - dst[offset++] = sLength; - if (sPadding < 0) { - dst[offset++] = 0; - signature.copy(dst, offset, paramBytes); - } else { - signature.copy(dst, offset, paramBytes + sPadding); - } - - return dst; -} - -module.exports = { - derToJose: derToJose, - joseToDer: joseToDer -}; - - -/***/ }), - -/***/ 380: -/***/ ((module) => { - -"use strict"; - - -function getParamSize(keySize) { - var result = ((keySize / 8) | 0) + (keySize % 8 === 0 ? 0 : 1); - return result; -} - -var paramBytesForAlg = { - ES256: getParamSize(256), - ES384: getParamSize(384), - ES512: getParamSize(521) -}; - -function getParamBytesForAlg(alg) { - var paramBytes = paramBytesForAlg[alg]; - if (paramBytes) { - return paramBytes; - } - - throw new Error('Unknown algorithm "' + alg + '"'); -} - -module.exports = getParamBytesForAlg; - - -/***/ }), - -/***/ 5094: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - -/* - * Encrypted content coding - * - * === Note about versions === - * - * This code supports multiple versions of the draft. This is selected using - * the |version| parameter. - * - * aes128gcm: The most recent version, the salt, record size and key identifier - * are included in a header that is part of the encrypted content coding. - * - * aesgcm: The version that is widely deployed with WebPush (as of 2016-11). - * This version is selected by default, unless you specify a |padSize| of 1. - */ - -var crypto = __nccwpck_require__(6113); - -var AES_GCM = 'aes-128-gcm'; -var PAD_SIZE = { 'aes128gcm': 1, 'aesgcm': 2 }; -var TAG_LENGTH = 16; -var KEY_LENGTH = 16; -var NONCE_LENGTH = 12; -var SHA_256_LENGTH = 32; -var MODE_ENCRYPT = 'encrypt'; -var MODE_DECRYPT = 'decrypt'; - -var keylog; -if (process.env.ECE_KEYLOG === '1') { - keylog = function(m, k) { - console.warn(m + ' [' + k.length + ']: ' + k.toString('base64url')); - return k; - }; -} else { - keylog = function(m, k) { return k; }; -} - -/* Optionally base64 decode something. */ -function decode(b) { - if (typeof b === 'string') { - return Buffer.from(b, 'base64url'); - } - return b; -} - -function HMAC_hash(key, input) { - var hmac = crypto.createHmac('sha256', key); - hmac.update(input); - return hmac.digest(); -} - -/* HKDF as defined in RFC5869, using SHA-256 */ -function HKDF_extract(salt, ikm) { - keylog('salt', salt); - keylog('ikm', ikm); - return keylog('extract', HMAC_hash(salt, ikm)); -} - -function HKDF_expand(prk, info, l) { - keylog('prk', prk); - keylog('info', info); - var output = Buffer.alloc(0); - var T = Buffer.alloc(0); - info = Buffer.from(info, 'ascii'); - var counter = 0; - var cbuf = Buffer.alloc(1); - while (output.length < l) { - cbuf.writeUIntBE(++counter, 0, 1); - T = HMAC_hash(prk, Buffer.concat([T, info, cbuf])); - output = Buffer.concat([output, T]); - } - - return keylog('expand', output.slice(0, l)); -} - -function HKDF(salt, ikm, info, len) { - return HKDF_expand(HKDF_extract(salt, ikm), info, len); -} - -function info(base, context) { - var result = Buffer.concat([ - Buffer.from('Content-Encoding: ' + base + '\0', 'ascii'), - context - ]); - keylog('info ' + base, result); - return result; -} - -function lengthPrefix(buffer) { - var b = Buffer.concat([Buffer.alloc(2), buffer]); - b.writeUIntBE(buffer.length, 0, 2); - return b; -} - -function extractDH(header, mode) { - var key = header.privateKey; - var senderPubKey, receiverPubKey; - if (mode === MODE_ENCRYPT) { - senderPubKey = key.getPublicKey(); - receiverPubKey = header.dh; - } else if (mode === MODE_DECRYPT) { - senderPubKey = header.dh; - receiverPubKey = key.getPublicKey(); - } else { - throw new Error('Unknown mode only ' + MODE_ENCRYPT + - ' and ' + MODE_DECRYPT + ' supported'); - } - return { - secret: key.computeSecret(header.dh), - context: Buffer.concat([ - Buffer.from(header.keylabel, 'ascii'), - Buffer.from([0]), - lengthPrefix(receiverPubKey), // user agent - lengthPrefix(senderPubKey) // application server - ]) - }; -} - -function extractSecretAndContext(header, mode) { - var result = { secret: null, context: Buffer.alloc(0) }; - if (header.key) { - result.secret = header.key; - if (result.secret.length !== KEY_LENGTH) { - throw new Error('An explicit key must be ' + KEY_LENGTH + ' bytes'); - } - } else if (header.dh) { // receiver/decrypt - result = extractDH(header, mode); - } else if (typeof header.keyid !== undefined) { - result.secret = header.keymap[header.keyid]; - } - if (!result.secret) { - throw new Error('Unable to determine key'); - } - keylog('secret', result.secret); - keylog('context', result.context); - if (header.authSecret) { - result.secret = HKDF(header.authSecret, result.secret, - info('auth', Buffer.alloc(0)), SHA_256_LENGTH); - keylog('authsecret', result.secret); - } - return result; -} - -function webpushSecret(header, mode) { - if (!header.authSecret) { - throw new Error('No authentication secret for webpush'); - } - keylog('authsecret', header.authSecret); - - var remotePubKey, senderPubKey, receiverPubKey; - if (mode === MODE_ENCRYPT) { - senderPubKey = header.privateKey.getPublicKey(); - remotePubKey = receiverPubKey = header.dh; - } else if (mode === MODE_DECRYPT) { - remotePubKey = senderPubKey = header.keyid; - receiverPubKey = header.privateKey.getPublicKey(); - } else { - throw new Error('Unknown mode only ' + MODE_ENCRYPT + - ' and ' + MODE_DECRYPT + ' supported'); - } - keylog('remote pubkey', remotePubKey); - keylog('sender pubkey', senderPubKey); - keylog('receiver pubkey', receiverPubKey); - return keylog('secret dh', - HKDF(header.authSecret, - header.privateKey.computeSecret(remotePubKey), - Buffer.concat([ - Buffer.from('WebPush: info\0'), - receiverPubKey, - senderPubKey - ]), - SHA_256_LENGTH)); -} - -function extractSecret(header, mode, keyLookupCallback) { - if (keyLookupCallback) { - if (!isFunction(keyLookupCallback)) { - throw new Error('Callback is not a function') - } - } - - if (header.key) { - if (header.key.length !== KEY_LENGTH) { - throw new Error('An explicit key must be ' + KEY_LENGTH + ' bytes'); - } - return keylog('secret key', header.key); - } - - if (!header.privateKey) { - // Lookup based on keyid - if (!keyLookupCallback) { - var key = header.keymap && header.keymap[header.keyid]; - } else { - var key = keyLookupCallback(header.keyid) - } - if (!key) { - throw new Error('No saved key (keyid: "' + header.keyid + '")'); - } - return key; - } - - return webpushSecret(header, mode); -} - -function deriveKeyAndNonce(header, mode, lookupKeyCallback) { - if (!header.salt) { - throw new Error('must include a salt parameter for ' + header.version); - } - var keyInfo; - var nonceInfo; - var secret; - if (header.version === 'aesgcm') { - // old - var s = extractSecretAndContext(header, mode, lookupKeyCallback); - keyInfo = info('aesgcm', s.context); - nonceInfo = info('nonce', s.context); - secret = s.secret; - } else if (header.version === 'aes128gcm') { - // latest - keyInfo = Buffer.from('Content-Encoding: aes128gcm\0'); - nonceInfo = Buffer.from('Content-Encoding: nonce\0'); - secret = extractSecret(header, mode, lookupKeyCallback); - } else { - throw new Error('Unable to set context for mode ' + header.version); - } - var prk = HKDF_extract(header.salt, secret); - var result = { - key: HKDF_expand(prk, keyInfo, KEY_LENGTH), - nonce: HKDF_expand(prk, nonceInfo, NONCE_LENGTH) - }; - keylog('key', result.key); - keylog('nonce base', result.nonce); - return result; -} - -/* Parse command-line arguments. */ -function parseParams(params) { - var header = {}; - - header.version = params.version || 'aes128gcm'; - header.rs = parseInt(params.rs, 10); - if (isNaN(header.rs)) { - header.rs = 4096; - } - var overhead = PAD_SIZE[header.version]; - if (header.version === 'aes128gcm') { - overhead += TAG_LENGTH; - } - if (header.rs <= overhead) { - throw new Error('The rs parameter has to be greater than ' + overhead); - } - - if (params.salt) { - header.salt = decode(params.salt); - if (header.salt.length !== KEY_LENGTH) { - throw new Error('The salt parameter must be ' + KEY_LENGTH + ' bytes'); - } - } - header.keyid = params.keyid; - if (params.key) { - header.key = decode(params.key); - } else { - header.privateKey = params.privateKey; - if (!header.privateKey) { - header.keymap = params.keymap; - } - if (header.version !== 'aes128gcm') { - header.keylabel = params.keylabel || 'P-256'; - } - if (params.dh) { - header.dh = decode(params.dh); - } - } - if (params.authSecret) { - header.authSecret = decode(params.authSecret); - } - return header; -} - -function generateNonce(base, counter) { - var nonce = Buffer.from(base); - var m = nonce.readUIntBE(nonce.length - 6, 6); - var x = ((m ^ counter) & 0xffffff) + - ((((m / 0x1000000) ^ (counter / 0x1000000)) & 0xffffff) * 0x1000000); - nonce.writeUIntBE(x, nonce.length - 6, 6); - keylog('nonce' + counter, nonce); - return nonce; -} - -/* Used when decrypting aes128gcm to populate the header values. Modifies the - * header values in place and returns the size of the header. */ -function readHeader(buffer, header) { - var idsz = buffer.readUIntBE(20, 1); - header.salt = buffer.slice(0, KEY_LENGTH); - header.rs = buffer.readUIntBE(KEY_LENGTH, 4); - header.keyid = buffer.slice(21, 21 + idsz); - return 21 + idsz; -} - -function unpadLegacy(data, version) { - var padSize = PAD_SIZE[version]; - var pad = data.readUIntBE(0, padSize); - if (pad + padSize > data.length) { - throw new Error('padding exceeds block size'); - } - keylog('padding', data.slice(0, padSize + pad)); - var padCheck = Buffer.alloc(pad); - padCheck.fill(0); - if (padCheck.compare(data.slice(padSize, padSize + pad)) !== 0) { - throw new Error('invalid padding'); - } - return data.slice(padSize + pad); -} - -function unpad(data, last) { - var i = data.length - 1; - while(i >= 0) { - if (data[i]) { - if (last) { - if (data[i] !== 2) { - throw new Error('last record needs to start padding with a 2'); - } - } else { - if (data[i] !== 1) { - throw new Error('last record needs to start padding with a 2'); - } - } - return data.slice(0, i); - } - --i; - } - throw new Error('all zero plaintext'); -} - -function decryptRecord(key, counter, buffer, header, last) { - keylog('decrypt', buffer); - var nonce = generateNonce(key.nonce, counter); - var gcm = crypto.createDecipheriv(AES_GCM, key.key, nonce); - gcm.setAuthTag(buffer.slice(buffer.length - TAG_LENGTH)); - var data = gcm.update(buffer.slice(0, buffer.length - TAG_LENGTH)); - data = Buffer.concat([data, gcm.final()]); - keylog('decrypted', data); - if (header.version !== 'aes128gcm') { - return unpadLegacy(data, header.version); - } - return unpad(data, last); -} - -/** - * Decrypt some bytes. This uses the parameters to determine the key and block - * size, which are described in the draft. Binary values are base64url encoded. - * - * |params.version| contains the version of encoding to use: aes128gcm is the latest, - * but aesgcm is also accepted (though the latter might - * disappear in a future release). If omitted, assume aes128gcm. - * - * If |params.key| is specified, that value is used as the key. - * - * If the version is aes128gcm, the keyid is extracted from the header and used - * as the ECDH public key of the sender. For version aesgcm , - * |params.dh| needs to be provided with the public key of the sender. - * - * The |params.privateKey| includes the private key of the receiver. - */ -function decrypt(buffer, params, keyLookupCallback) { - var header = parseParams(params); - if (header.version === 'aes128gcm') { - var headerLength = readHeader(buffer, header); - buffer = buffer.slice(headerLength); - } - var key = deriveKeyAndNonce(header, MODE_DECRYPT, keyLookupCallback); - var start = 0; - var result = Buffer.alloc(0); - - var chunkSize = header.rs; - if (header.version !== 'aes128gcm') { - chunkSize += TAG_LENGTH; - } - - for (var i = 0; start < buffer.length; ++i) { - var end = start + chunkSize; - if (header.version !== 'aes128gcm' && end === buffer.length) { - throw new Error('Truncated payload'); - } - end = Math.min(end, buffer.length); - if (end - start <= TAG_LENGTH) { - throw new Error('Invalid block: too small at ' + i); - } - var block = decryptRecord(key, i, buffer.slice(start, end), - header, end >= buffer.length); - result = Buffer.concat([result, block]); - start = end; - } - return result; -} - -function encryptRecord(key, counter, buffer, pad, header, last) { - keylog('encrypt', buffer); - pad = pad || 0; - var nonce = generateNonce(key.nonce, counter); - var gcm = crypto.createCipheriv(AES_GCM, key.key, nonce); - - var ciphertext = []; - var padSize = PAD_SIZE[header.version]; - var padding = Buffer.alloc(pad + padSize); - padding.fill(0); - - if (header.version !== 'aes128gcm') { - padding.writeUIntBE(pad, 0, padSize); - keylog('padding', padding); - ciphertext.push(gcm.update(padding)); - ciphertext.push(gcm.update(buffer)); - - if (!last && padding.length + buffer.length < header.rs) { - throw new Error('Unable to pad to record size'); - } - } else { - ciphertext.push(gcm.update(buffer)); - padding.writeUIntBE(last ? 2 : 1, 0, 1); - keylog('padding', padding); - ciphertext.push(gcm.update(padding)); - } - - gcm.final(); - var tag = gcm.getAuthTag(); - if (tag.length !== TAG_LENGTH) { - throw new Error('invalid tag generated'); - } - ciphertext.push(tag); - return keylog('encrypted', Buffer.concat(ciphertext)); -} - -function writeHeader(header) { - var ints = Buffer.alloc(5); - var keyid = Buffer.from(header.keyid || []); - if (keyid.length > 255) { - throw new Error('keyid is too large'); - } - ints.writeUIntBE(header.rs, 0, 4); - ints.writeUIntBE(keyid.length, 4, 1); - return Buffer.concat([header.salt, ints, keyid]); -} - -/** - * Encrypt some bytes. This uses the parameters to determine the key and block - * size, which are described in the draft. - * - * |params.version| contains the version of encoding to use: aes128gcm is the latest, - * but aesgcm is also accepted (though the latter two might - * disappear in a future release). If omitted, assume aes128gcm. - * - * If |params.key| is specified, that value is used as the key. - * - * For Diffie-Hellman (WebPush), |params.dh| includes the public key of the - * receiver. |params.privateKey| is used to establish a shared secret. Key - * pairs can be created using |crypto.createECDH()|. - */ -function encrypt(buffer, params, keyLookupCallback) { - if (!Buffer.isBuffer(buffer)) { - throw new Error('buffer argument must be a Buffer'); - } - var header = parseParams(params); - if (!header.salt) { - header.salt = crypto.randomBytes(KEY_LENGTH); - } - - var result; - if (header.version === 'aes128gcm') { - // Save the DH public key in the header unless keyid is set. - if (header.privateKey && !header.keyid) { - header.keyid = header.privateKey.getPublicKey(); - } - result = writeHeader(header); - } else { - // No header on other versions - result = Buffer.alloc(0); - } - - var key = deriveKeyAndNonce(header, MODE_ENCRYPT, keyLookupCallback); - var start = 0; - var padSize = PAD_SIZE[header.version]; - var overhead = padSize; - if (header.version === 'aes128gcm') { - overhead += TAG_LENGTH; - } - var pad = isNaN(parseInt(params.pad, 10)) ? 0 : parseInt(params.pad, 10); - - var counter = 0; - var last = false; - while (!last) { - // Pad so that at least one data byte is in a block. - var recordPad = Math.min(header.rs - overhead - 1, pad); - if (header.version !== 'aes128gcm') { - recordPad = Math.min((1 << (padSize * 8)) - 1, recordPad); - } - if (pad > 0 && recordPad === 0) { - ++recordPad; // Deal with perverse case of rs=overhead+1 with padding. - } - pad -= recordPad; - - var end = start + header.rs - overhead - recordPad; - if (header.version !== 'aes128gcm') { - // The > here ensures that we write out a padding-only block at the end - // of a buffer. - last = end > buffer.length; - } else { - last = end >= buffer.length; - } - last = last && pad <= 0; - var block = encryptRecord(key, counter, buffer.slice(start, end), - recordPad, header, last); - result = Buffer.concat([result, block]); - - start = end; - ++counter; - } - return result; -} - - -function isFunction(object) { - return typeof(object) === 'function'; - } - -module.exports = { - decrypt: decrypt, - encrypt: encrypt -}; - - -/***/ }), - -/***/ 9521: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - -"use strict"; - -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.HttpsProxyAgent = void 0; -const net = __importStar(__nccwpck_require__(1808)); -const tls = __importStar(__nccwpck_require__(4404)); -const assert_1 = __importDefault(__nccwpck_require__(9491)); -const debug_1 = __importDefault(__nccwpck_require__(5062)); -const agent_base_1 = __nccwpck_require__(7111); -const url_1 = __nccwpck_require__(7310); -const parse_proxy_response_1 = __nccwpck_require__(4325); -const debug = (0, debug_1.default)('https-proxy-agent'); -/** - * The `HttpsProxyAgent` implements an HTTP Agent subclass that connects to - * the specified "HTTP(s) proxy server" in order to proxy HTTPS requests. - * - * Outgoing HTTP requests are first tunneled through the proxy server using the - * `CONNECT` HTTP request method to establish a connection to the proxy server, - * and then the proxy server connects to the destination target and issues the - * HTTP request from the proxy server. - * - * `https:` requests have their socket connection upgraded to TLS once - * the connection to the proxy server has been established. - */ -class HttpsProxyAgent extends agent_base_1.Agent { - constructor(proxy, opts) { - super(opts); - this.options = { path: undefined }; - this.proxy = typeof proxy === 'string' ? new url_1.URL(proxy) : proxy; - this.proxyHeaders = opts?.headers ?? {}; - debug('Creating new HttpsProxyAgent instance: %o', this.proxy.href); - // Trim off the brackets from IPv6 addresses - const host = (this.proxy.hostname || this.proxy.host).replace(/^\[|\]$/g, ''); - const port = this.proxy.port - ? parseInt(this.proxy.port, 10) - : this.proxy.protocol === 'https:' - ? 443 - : 80; - this.connectOpts = { - // Attempt to negotiate http/1.1 for proxy servers that support http/2 - ALPNProtocols: ['http/1.1'], - ...(opts ? omit(opts, 'headers') : null), - host, - port, - }; - } - /** - * Called when the node-core HTTP client library is creating a - * new HTTP request. - */ - async connect(req, opts) { - const { proxy } = this; - if (!opts.host) { - throw new TypeError('No "host" provided'); - } - // Create a socket connection to the proxy server. - let socket; - if (proxy.protocol === 'https:') { - debug('Creating `tls.Socket`: %o', this.connectOpts); - const servername = this.connectOpts.servername || this.connectOpts.host; - socket = tls.connect({ - ...this.connectOpts, - servername, - }); - } - else { - debug('Creating `net.Socket`: %o', this.connectOpts); - socket = net.connect(this.connectOpts); - } - const headers = typeof this.proxyHeaders === 'function' - ? this.proxyHeaders() - : { ...this.proxyHeaders }; - const host = net.isIPv6(opts.host) ? `[${opts.host}]` : opts.host; - let payload = `CONNECT ${host}:${opts.port} HTTP/1.1\r\n`; - // Inject the `Proxy-Authorization` header if necessary. - if (proxy.username || proxy.password) { - const auth = `${decodeURIComponent(proxy.username)}:${decodeURIComponent(proxy.password)}`; - headers['Proxy-Authorization'] = `Basic ${Buffer.from(auth).toString('base64')}`; - } - headers.Host = `${host}:${opts.port}`; - if (!headers['Proxy-Connection']) { - headers['Proxy-Connection'] = this.keepAlive - ? 'Keep-Alive' - : 'close'; - } - for (const name of Object.keys(headers)) { - payload += `${name}: ${headers[name]}\r\n`; - } - const proxyResponsePromise = (0, parse_proxy_response_1.parseProxyResponse)(socket); - socket.write(`${payload}\r\n`); - const { connect, buffered } = await proxyResponsePromise; - req.emit('proxyConnect', connect); - this.emit('proxyConnect', connect, req); - if (connect.statusCode === 200) { - req.once('socket', resume); - if (opts.secureEndpoint) { - // The proxy is connecting to a TLS server, so upgrade - // this socket connection to a TLS connection. - debug('Upgrading socket connection to TLS'); - const servername = opts.servername || opts.host; - return tls.connect({ - ...omit(opts, 'host', 'path', 'port'), - socket, - servername, - }); - } - return socket; - } - // Some other status code that's not 200... need to re-play the HTTP - // header "data" events onto the socket once the HTTP machinery is - // attached so that the node core `http` can parse and handle the - // error status code. - // Close the original socket, and a new "fake" socket is returned - // instead, so that the proxy doesn't get the HTTP request - // written to it (which may contain `Authorization` headers or other - // sensitive data). - // - // See: https://hackerone.com/reports/541502 - socket.destroy(); - const fakeSocket = new net.Socket({ writable: false }); - fakeSocket.readable = true; - // Need to wait for the "socket" event to re-play the "data" events. - req.once('socket', (s) => { - debug('Replaying proxy buffer for failed request'); - (0, assert_1.default)(s.listenerCount('data') > 0); - // Replay the "buffered" Buffer onto the fake `socket`, since at - // this point the HTTP module machinery has been hooked up for - // the user. - s.push(buffered); - s.push(null); - }); - return fakeSocket; - } -} -HttpsProxyAgent.protocols = ['http', 'https']; -exports.HttpsProxyAgent = HttpsProxyAgent; -function resume(socket) { - socket.resume(); -} -function omit(obj, ...keys) { - const ret = {}; - let key; - for (key in obj) { - if (!keys.includes(key)) { - ret[key] = obj[key]; - } - } - return ret; -} -//# sourceMappingURL=index.js.map - -/***/ }), - -/***/ 4325: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - -"use strict"; - -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.parseProxyResponse = void 0; -const debug_1 = __importDefault(__nccwpck_require__(5062)); -const debug = (0, debug_1.default)('https-proxy-agent:parse-proxy-response'); -function parseProxyResponse(socket) { - return new Promise((resolve, reject) => { - // we need to buffer any HTTP traffic that happens with the proxy before we get - // the CONNECT response, so that if the response is anything other than an "200" - // response code, then we can re-play the "data" events on the socket once the - // HTTP parser is hooked up... - let buffersLength = 0; - const buffers = []; - function read() { - const b = socket.read(); - if (b) - ondata(b); - else - socket.once('readable', read); - } - function cleanup() { - socket.removeListener('end', onend); - socket.removeListener('error', onerror); - socket.removeListener('readable', read); - } - function onend() { - cleanup(); - debug('onend'); - reject(new Error('Proxy connection ended before receiving CONNECT response')); - } - function onerror(err) { - cleanup(); - debug('onerror %o', err); - reject(err); - } - function ondata(b) { - buffers.push(b); - buffersLength += b.length; - const buffered = Buffer.concat(buffers, buffersLength); - const endOfHeaders = buffered.indexOf('\r\n\r\n'); - if (endOfHeaders === -1) { - // keep buffering - debug('have not received end of HTTP headers yet...'); - read(); - return; - } - const headerParts = buffered - .slice(0, endOfHeaders) - .toString('ascii') - .split('\r\n'); - const firstLine = headerParts.shift(); - if (!firstLine) { - socket.destroy(); - return reject(new Error('No header received from proxy CONNECT response')); - } - const firstLineParts = firstLine.split(' '); - const statusCode = +firstLineParts[1]; - const statusText = firstLineParts.slice(2).join(' '); - const headers = {}; - for (const header of headerParts) { - if (!header) - continue; - const firstColon = header.indexOf(':'); - if (firstColon === -1) { - socket.destroy(); - return reject(new Error(`Invalid header from proxy CONNECT response: "${header}"`)); - } - const key = header.slice(0, firstColon).toLowerCase(); - const value = header.slice(firstColon + 1).trimStart(); - const current = headers[key]; - if (typeof current === 'string') { - headers[key] = [current, value]; - } - else if (Array.isArray(current)) { - current.push(value); - } - else { - headers[key] = value; - } - } - debug('got proxy server response: %o %o', firstLine, headers); - cleanup(); - resolve({ - connect: { - statusCode, - statusText, - headers, - }, - buffered, - }); - } - socket.on('error', onerror); - socket.on('end', onend); - read(); - }); -} -exports.parseProxyResponse = parseProxyResponse; -//# sourceMappingURL=parse-proxy-response.js.map - -/***/ }), - -/***/ 9581: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -try { - var util = __nccwpck_require__(3837); - /* istanbul ignore next */ - if (typeof util.inherits !== 'function') throw ''; - module.exports = util.inherits; -} catch (e) { - /* istanbul ignore next */ - module.exports = __nccwpck_require__(4345); -} - - -/***/ }), - -/***/ 4345: -/***/ ((module) => { - -if (typeof Object.create === 'function') { - // implementation from standard node.js 'util' module - module.exports = function inherits(ctor, superCtor) { - if (superCtor) { - ctor.super_ = superCtor - ctor.prototype = Object.create(superCtor.prototype, { - constructor: { - value: ctor, - enumerable: false, - writable: true, - configurable: true - } - }) - } - }; -} else { - // old school shim for old browsers - module.exports = function inherits(ctor, superCtor) { - if (superCtor) { - ctor.super_ = superCtor - var TempCtor = function () {} - TempCtor.prototype = superCtor.prototype - ctor.prototype = new TempCtor() - ctor.prototype.constructor = ctor - } - } -} - - -/***/ }), - -/***/ 3069: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var bufferEqual = __nccwpck_require__(7457); -var Buffer = (__nccwpck_require__(3925).Buffer); -var crypto = __nccwpck_require__(6113); -var formatEcdsa = __nccwpck_require__(9877); -var util = __nccwpck_require__(3837); - -var MSG_INVALID_ALGORITHM = '"%s" is not a valid algorithm.\n Supported algorithms are:\n "HS256", "HS384", "HS512", "RS256", "RS384", "RS512", "PS256", "PS384", "PS512", "ES256", "ES384", "ES512" and "none".' -var MSG_INVALID_SECRET = 'secret must be a string or buffer'; -var MSG_INVALID_VERIFIER_KEY = 'key must be a string or a buffer'; -var MSG_INVALID_SIGNER_KEY = 'key must be a string, a buffer or an object'; - -var supportsKeyObjects = typeof crypto.createPublicKey === 'function'; -if (supportsKeyObjects) { - MSG_INVALID_VERIFIER_KEY += ' or a KeyObject'; - MSG_INVALID_SECRET += 'or a KeyObject'; -} - -function checkIsPublicKey(key) { - if (Buffer.isBuffer(key)) { - return; - } - - if (typeof key === 'string') { - return; - } - - if (!supportsKeyObjects) { - throw typeError(MSG_INVALID_VERIFIER_KEY); - } - - if (typeof key !== 'object') { - throw typeError(MSG_INVALID_VERIFIER_KEY); - } - - if (typeof key.type !== 'string') { - throw typeError(MSG_INVALID_VERIFIER_KEY); - } - - if (typeof key.asymmetricKeyType !== 'string') { - throw typeError(MSG_INVALID_VERIFIER_KEY); - } - - if (typeof key.export !== 'function') { - throw typeError(MSG_INVALID_VERIFIER_KEY); - } -}; - -function checkIsPrivateKey(key) { - if (Buffer.isBuffer(key)) { - return; - } - - if (typeof key === 'string') { - return; - } - - if (typeof key === 'object') { - return; - } - - throw typeError(MSG_INVALID_SIGNER_KEY); -}; - -function checkIsSecretKey(key) { - if (Buffer.isBuffer(key)) { - return; - } - - if (typeof key === 'string') { - return key; - } - - if (!supportsKeyObjects) { - throw typeError(MSG_INVALID_SECRET); - } - - if (typeof key !== 'object') { - throw typeError(MSG_INVALID_SECRET); - } - - if (key.type !== 'secret') { - throw typeError(MSG_INVALID_SECRET); - } - - if (typeof key.export !== 'function') { - throw typeError(MSG_INVALID_SECRET); - } -} - -function fromBase64(base64) { - return base64 - .replace(/=/g, '') - .replace(/\+/g, '-') - .replace(/\//g, '_'); -} - -function toBase64(base64url) { - base64url = base64url.toString(); - - var padding = 4 - base64url.length % 4; - if (padding !== 4) { - for (var i = 0; i < padding; ++i) { - base64url += '='; - } - } - - return base64url - .replace(/\-/g, '+') - .replace(/_/g, '/'); -} - -function typeError(template) { - var args = [].slice.call(arguments, 1); - var errMsg = util.format.bind(util, template).apply(null, args); - return new TypeError(errMsg); -} - -function bufferOrString(obj) { - return Buffer.isBuffer(obj) || typeof obj === 'string'; -} - -function normalizeInput(thing) { - if (!bufferOrString(thing)) - thing = JSON.stringify(thing); - return thing; -} - -function createHmacSigner(bits) { - return function sign(thing, secret) { - checkIsSecretKey(secret); - thing = normalizeInput(thing); - var hmac = crypto.createHmac('sha' + bits, secret); - var sig = (hmac.update(thing), hmac.digest('base64')) - return fromBase64(sig); - } -} - -function createHmacVerifier(bits) { - return function verify(thing, signature, secret) { - var computedSig = createHmacSigner(bits)(thing, secret); - return bufferEqual(Buffer.from(signature), Buffer.from(computedSig)); - } -} - -function createKeySigner(bits) { - return function sign(thing, privateKey) { - checkIsPrivateKey(privateKey); - thing = normalizeInput(thing); - // Even though we are specifying "RSA" here, this works with ECDSA - // keys as well. - var signer = crypto.createSign('RSA-SHA' + bits); - var sig = (signer.update(thing), signer.sign(privateKey, 'base64')); - return fromBase64(sig); - } -} - -function createKeyVerifier(bits) { - return function verify(thing, signature, publicKey) { - checkIsPublicKey(publicKey); - thing = normalizeInput(thing); - signature = toBase64(signature); - var verifier = crypto.createVerify('RSA-SHA' + bits); - verifier.update(thing); - return verifier.verify(publicKey, signature, 'base64'); - } -} - -function createPSSKeySigner(bits) { - return function sign(thing, privateKey) { - checkIsPrivateKey(privateKey); - thing = normalizeInput(thing); - var signer = crypto.createSign('RSA-SHA' + bits); - var sig = (signer.update(thing), signer.sign({ - key: privateKey, - padding: crypto.constants.RSA_PKCS1_PSS_PADDING, - saltLength: crypto.constants.RSA_PSS_SALTLEN_DIGEST - }, 'base64')); - return fromBase64(sig); - } -} - -function createPSSKeyVerifier(bits) { - return function verify(thing, signature, publicKey) { - checkIsPublicKey(publicKey); - thing = normalizeInput(thing); - signature = toBase64(signature); - var verifier = crypto.createVerify('RSA-SHA' + bits); - verifier.update(thing); - return verifier.verify({ - key: publicKey, - padding: crypto.constants.RSA_PKCS1_PSS_PADDING, - saltLength: crypto.constants.RSA_PSS_SALTLEN_DIGEST - }, signature, 'base64'); - } -} - -function createECDSASigner(bits) { - var inner = createKeySigner(bits); - return function sign() { - var signature = inner.apply(null, arguments); - signature = formatEcdsa.derToJose(signature, 'ES' + bits); - return signature; - }; -} - -function createECDSAVerifer(bits) { - var inner = createKeyVerifier(bits); - return function verify(thing, signature, publicKey) { - signature = formatEcdsa.joseToDer(signature, 'ES' + bits).toString('base64'); - var result = inner(thing, signature, publicKey); - return result; - }; -} - -function createNoneSigner() { - return function sign() { - return ''; - } -} - -function createNoneVerifier() { - return function verify(thing, signature) { - return signature === ''; - } -} - -module.exports = function jwa(algorithm) { - var signerFactories = { - hs: createHmacSigner, - rs: createKeySigner, - ps: createPSSKeySigner, - es: createECDSASigner, - none: createNoneSigner, - } - var verifierFactories = { - hs: createHmacVerifier, - rs: createKeyVerifier, - ps: createPSSKeyVerifier, - es: createECDSAVerifer, - none: createNoneVerifier, - } - var match = algorithm.match(/^(RS|PS|ES|HS)(256|384|512)$|^(none)$/); - if (!match) - throw typeError(MSG_INVALID_ALGORITHM, algorithm); - var algo = (match[1] || match[3]).toLowerCase(); - var bits = match[2]; - - return { - sign: signerFactories[algo](bits), - verify: verifierFactories[algo](bits), - } -}; - - -/***/ }), - -/***/ 7507: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -/*global exports*/ -var SignStream = __nccwpck_require__(3642); -var VerifyStream = __nccwpck_require__(6099); - -var ALGORITHMS = [ - 'HS256', 'HS384', 'HS512', - 'RS256', 'RS384', 'RS512', - 'PS256', 'PS384', 'PS512', - 'ES256', 'ES384', 'ES512' -]; - -exports.ALGORITHMS = ALGORITHMS; -exports.sign = SignStream.sign; -exports.verify = VerifyStream.verify; -exports.decode = VerifyStream.decode; -exports.isValid = VerifyStream.isValid; -exports.createSign = function createSign(opts) { - return new SignStream(opts); -}; -exports.createVerify = function createVerify(opts) { - return new VerifyStream(opts); -}; - - -/***/ }), - -/***/ 8621: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -/*global module, process*/ -var Buffer = (__nccwpck_require__(3925).Buffer); -var Stream = __nccwpck_require__(2781); -var util = __nccwpck_require__(3837); - -function DataStream(data) { - this.buffer = null; - this.writable = true; - this.readable = true; - - // No input - if (!data) { - this.buffer = Buffer.alloc(0); - return this; - } - - // Stream - if (typeof data.pipe === 'function') { - this.buffer = Buffer.alloc(0); - data.pipe(this); - return this; - } - - // Buffer or String - // or Object (assumedly a passworded key) - if (data.length || typeof data === 'object') { - this.buffer = data; - this.writable = false; - process.nextTick(function () { - this.emit('end', data); - this.readable = false; - this.emit('close'); - }.bind(this)); - return this; - } - - throw new TypeError('Unexpected data type ('+ typeof data + ')'); -} -util.inherits(DataStream, Stream); - -DataStream.prototype.write = function write(data) { - this.buffer = Buffer.concat([this.buffer, Buffer.from(data)]); - this.emit('data', data); -}; - -DataStream.prototype.end = function end(data) { - if (data) - this.write(data); - this.emit('end', data); - this.emit('close'); - this.writable = false; - this.readable = false; -}; - -module.exports = DataStream; - - -/***/ }), - -/***/ 3642: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -/*global module*/ -var Buffer = (__nccwpck_require__(3925).Buffer); -var DataStream = __nccwpck_require__(8621); -var jwa = __nccwpck_require__(3069); -var Stream = __nccwpck_require__(2781); -var toString = __nccwpck_require__(5591); -var util = __nccwpck_require__(3837); - -function base64url(string, encoding) { - return Buffer - .from(string, encoding) - .toString('base64') - .replace(/=/g, '') - .replace(/\+/g, '-') - .replace(/\//g, '_'); -} - -function jwsSecuredInput(header, payload, encoding) { - encoding = encoding || 'utf8'; - var encodedHeader = base64url(toString(header), 'binary'); - var encodedPayload = base64url(toString(payload), encoding); - return util.format('%s.%s', encodedHeader, encodedPayload); -} - -function jwsSign(opts) { - var header = opts.header; - var payload = opts.payload; - var secretOrKey = opts.secret || opts.privateKey; - var encoding = opts.encoding; - var algo = jwa(header.alg); - var securedInput = jwsSecuredInput(header, payload, encoding); - var signature = algo.sign(securedInput, secretOrKey); - return util.format('%s.%s', securedInput, signature); -} - -function SignStream(opts) { - var secret = opts.secret||opts.privateKey||opts.key; - var secretStream = new DataStream(secret); - this.readable = true; - this.header = opts.header; - this.encoding = opts.encoding; - this.secret = this.privateKey = this.key = secretStream; - this.payload = new DataStream(opts.payload); - this.secret.once('close', function () { - if (!this.payload.writable && this.readable) - this.sign(); - }.bind(this)); - - this.payload.once('close', function () { - if (!this.secret.writable && this.readable) - this.sign(); - }.bind(this)); -} -util.inherits(SignStream, Stream); - -SignStream.prototype.sign = function sign() { - try { - var signature = jwsSign({ - header: this.header, - payload: this.payload.buffer, - secret: this.secret.buffer, - encoding: this.encoding - }); - this.emit('done', signature); - this.emit('data', signature); - this.emit('end'); - this.readable = false; - return signature; - } catch (e) { - this.readable = false; - this.emit('error', e); - this.emit('close'); - } -}; - -SignStream.sign = jwsSign; - -module.exports = SignStream; - - -/***/ }), - -/***/ 5591: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -/*global module*/ -var Buffer = (__nccwpck_require__(4300).Buffer); - -module.exports = function toString(obj) { - if (typeof obj === 'string') - return obj; - if (typeof obj === 'number' || Buffer.isBuffer(obj)) - return obj.toString(); - return JSON.stringify(obj); -}; - - -/***/ }), - -/***/ 6099: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -/*global module*/ -var Buffer = (__nccwpck_require__(3925).Buffer); -var DataStream = __nccwpck_require__(8621); -var jwa = __nccwpck_require__(3069); -var Stream = __nccwpck_require__(2781); -var toString = __nccwpck_require__(5591); -var util = __nccwpck_require__(3837); -var JWS_REGEX = /^[a-zA-Z0-9\-_]+?\.[a-zA-Z0-9\-_]+?\.([a-zA-Z0-9\-_]+)?$/; - -function isObject(thing) { - return Object.prototype.toString.call(thing) === '[object Object]'; -} - -function safeJsonParse(thing) { - if (isObject(thing)) - return thing; - try { return JSON.parse(thing); } - catch (e) { return undefined; } -} - -function headerFromJWS(jwsSig) { - var encodedHeader = jwsSig.split('.', 1)[0]; - return safeJsonParse(Buffer.from(encodedHeader, 'base64').toString('binary')); -} - -function securedInputFromJWS(jwsSig) { - return jwsSig.split('.', 2).join('.'); -} - -function signatureFromJWS(jwsSig) { - return jwsSig.split('.')[2]; -} - -function payloadFromJWS(jwsSig, encoding) { - encoding = encoding || 'utf8'; - var payload = jwsSig.split('.')[1]; - return Buffer.from(payload, 'base64').toString(encoding); -} - -function isValidJws(string) { - return JWS_REGEX.test(string) && !!headerFromJWS(string); -} - -function jwsVerify(jwsSig, algorithm, secretOrKey) { - if (!algorithm) { - var err = new Error("Missing algorithm parameter for jws.verify"); - err.code = "MISSING_ALGORITHM"; - throw err; - } - jwsSig = toString(jwsSig); - var signature = signatureFromJWS(jwsSig); - var securedInput = securedInputFromJWS(jwsSig); - var algo = jwa(algorithm); - return algo.verify(securedInput, signature, secretOrKey); -} - -function jwsDecode(jwsSig, opts) { - opts = opts || {}; - jwsSig = toString(jwsSig); - - if (!isValidJws(jwsSig)) - return null; - - var header = headerFromJWS(jwsSig); - - if (!header) - return null; - - var payload = payloadFromJWS(jwsSig); - if (header.typ === 'JWT' || opts.json) - payload = JSON.parse(payload, opts.encoding); - - return { - header: header, - payload: payload, - signature: signatureFromJWS(jwsSig) - }; -} - -function VerifyStream(opts) { - opts = opts || {}; - var secretOrKey = opts.secret||opts.publicKey||opts.key; - var secretStream = new DataStream(secretOrKey); - this.readable = true; - this.algorithm = opts.algorithm; - this.encoding = opts.encoding; - this.secret = this.publicKey = this.key = secretStream; - this.signature = new DataStream(opts.signature); - this.secret.once('close', function () { - if (!this.signature.writable && this.readable) - this.verify(); - }.bind(this)); - - this.signature.once('close', function () { - if (!this.secret.writable && this.readable) - this.verify(); - }.bind(this)); -} -util.inherits(VerifyStream, Stream); -VerifyStream.prototype.verify = function verify() { - try { - var valid = jwsVerify(this.signature.buffer, this.algorithm, this.key.buffer); - var obj = jwsDecode(this.signature.buffer, this.encoding); - this.emit('done', valid, obj); - this.emit('data', valid); - this.emit('end'); - this.readable = false; - return valid; - } catch (e) { - this.readable = false; - this.emit('error', e); - this.emit('close'); - } -}; - -VerifyStream.decode = jwsDecode; -VerifyStream.isValid = isValidJws; -VerifyStream.verify = jwsVerify; - -module.exports = VerifyStream; - - -/***/ }), - -/***/ 2104: -/***/ ((module) => { - -module.exports = assert; - -function assert(val, msg) { - if (!val) - throw new Error(msg || 'Assertion failed'); -} - -assert.equal = function assertEqual(l, r, msg) { - if (l != r) - throw new Error(msg || ('Assertion failed: ' + l + ' != ' + r)); -}; - - -/***/ }), - -/***/ 3730: -/***/ ((module) => { - -/** - * Helpers. - */ - -var s = 1000; -var m = s * 60; -var h = m * 60; -var d = h * 24; -var w = d * 7; -var y = d * 365.25; - -/** - * Parse or format the given `val`. - * - * Options: - * - * - `long` verbose formatting [false] - * - * @param {String|Number} val - * @param {Object} [options] - * @throws {Error} throw an error if val is not a non-empty string or a number - * @return {String|Number} - * @api public - */ - -module.exports = function(val, options) { - options = options || {}; - var type = typeof val; - if (type === 'string' && val.length > 0) { - return parse(val); - } else if (type === 'number' && isFinite(val)) { - return options.long ? fmtLong(val) : fmtShort(val); - } - throw new Error( - 'val is not a non-empty string or a valid number. val=' + - JSON.stringify(val) - ); -}; - -/** - * Parse the given `str` and return milliseconds. - * - * @param {String} str - * @return {Number} - * @api private - */ - -function parse(str) { - str = String(str); - if (str.length > 100) { - return; - } - var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec( - str - ); - if (!match) { - return; - } - var n = parseFloat(match[1]); - var type = (match[2] || 'ms').toLowerCase(); - switch (type) { - case 'years': - case 'year': - case 'yrs': - case 'yr': - case 'y': - return n * y; - case 'weeks': - case 'week': - case 'w': - return n * w; - case 'days': - case 'day': - case 'd': - return n * d; - case 'hours': - case 'hour': - case 'hrs': - case 'hr': - case 'h': - return n * h; - case 'minutes': - case 'minute': - case 'mins': - case 'min': - case 'm': - return n * m; - case 'seconds': - case 'second': - case 'secs': - case 'sec': - case 's': - return n * s; - case 'milliseconds': - case 'millisecond': - case 'msecs': - case 'msec': - case 'ms': - return n; - default: - return undefined; - } -} - -/** - * Short format for `ms`. - * - * @param {Number} ms - * @return {String} - * @api private - */ - -function fmtShort(ms) { - var msAbs = Math.abs(ms); - if (msAbs >= d) { - return Math.round(ms / d) + 'd'; - } - if (msAbs >= h) { - return Math.round(ms / h) + 'h'; - } - if (msAbs >= m) { - return Math.round(ms / m) + 'm'; - } - if (msAbs >= s) { - return Math.round(ms / s) + 's'; - } - return ms + 'ms'; -} - -/** - * Long format for `ms`. - * - * @param {Number} ms - * @return {String} - * @api private - */ - -function fmtLong(ms) { - var msAbs = Math.abs(ms); - if (msAbs >= d) { - return plural(ms, msAbs, d, 'day'); - } - if (msAbs >= h) { - return plural(ms, msAbs, h, 'hour'); - } - if (msAbs >= m) { - return plural(ms, msAbs, m, 'minute'); - } - if (msAbs >= s) { - return plural(ms, msAbs, s, 'second'); - } - return ms + ' ms'; -} - -/** - * Pluralization helper. - */ - -function plural(ms, msAbs, n, name) { - var isPlural = msAbs >= n * 1.5; - return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : ''); -} - - -/***/ }), - -/***/ 3925: -/***/ ((module, exports, __nccwpck_require__) => { - -/*! safe-buffer. MIT License. Feross Aboukhadijeh */ -/* eslint-disable node/no-deprecated-api */ -var buffer = __nccwpck_require__(4300) -var Buffer = buffer.Buffer - -// alternative to using Object.keys for old browsers -function copyProps (src, dst) { - for (var key in src) { - dst[key] = src[key] - } -} -if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) { - module.exports = buffer -} else { - // Copy properties from require('buffer') - copyProps(buffer, exports) - exports.Buffer = SafeBuffer -} - -function SafeBuffer (arg, encodingOrOffset, length) { - return Buffer(arg, encodingOrOffset, length) -} - -SafeBuffer.prototype = Object.create(Buffer.prototype) - -// Copy static methods from Buffer -copyProps(Buffer, SafeBuffer) - -SafeBuffer.from = function (arg, encodingOrOffset, length) { - if (typeof arg === 'number') { - throw new TypeError('Argument must not be a number') - } - return Buffer(arg, encodingOrOffset, length) -} - -SafeBuffer.alloc = function (size, fill, encoding) { - if (typeof size !== 'number') { - throw new TypeError('Argument must be a number') - } - var buf = Buffer(size) - if (fill !== undefined) { - if (typeof encoding === 'string') { - buf.fill(fill, encoding) - } else { - buf.fill(fill) - } - } else { - buf.fill(0) - } - return buf -} - -SafeBuffer.allocUnsafe = function (size) { - if (typeof size !== 'number') { - throw new TypeError('Argument must be a number') - } - return Buffer(size) -} - -SafeBuffer.allocUnsafeSlow = function (size) { - if (typeof size !== 'number') { - throw new TypeError('Argument must be a number') - } - return buffer.SlowBuffer(size) -} - - -/***/ }), - -/***/ 5827: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; -/* eslint-disable node/no-deprecated-api */ - - - -var buffer = __nccwpck_require__(4300) -var Buffer = buffer.Buffer - -var safer = {} - -var key - -for (key in buffer) { - if (!buffer.hasOwnProperty(key)) continue - if (key === 'SlowBuffer' || key === 'Buffer') continue - safer[key] = buffer[key] -} - -var Safer = safer.Buffer = {} -for (key in Buffer) { - if (!Buffer.hasOwnProperty(key)) continue - if (key === 'allocUnsafe' || key === 'allocUnsafeSlow') continue - Safer[key] = Buffer[key] -} - -safer.Buffer.prototype = Buffer.prototype - -if (!Safer.from || Safer.from === Uint8Array.from) { - Safer.from = function (value, encodingOrOffset, length) { - if (typeof value === 'number') { - throw new TypeError('The "value" argument must not be of type number. Received type ' + typeof value) - } - if (value && typeof value.length === 'undefined') { - throw new TypeError('The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type ' + typeof value) - } - return Buffer(value, encodingOrOffset, length) - } -} - -if (!Safer.alloc) { - Safer.alloc = function (size, fill, encoding) { - if (typeof size !== 'number') { - throw new TypeError('The "size" argument must be of type number. Received type ' + typeof size) - } - if (size < 0 || size >= 2 * (1 << 30)) { - throw new RangeError('The value "' + size + '" is invalid for option "size"') - } - var buf = Buffer(size) - if (!fill || fill.length === 0) { - buf.fill(0) - } else if (typeof encoding === 'string') { - buf.fill(fill, encoding) - } else { - buf.fill(fill) - } - return buf - } -} - -if (!safer.kStringMaxLength) { - try { - safer.kStringMaxLength = process.binding('buffer').kStringMaxLength - } catch (e) { - // we can't determine kStringMaxLength in environments where process.binding - // is unsupported, so let's not set it - } -} - -if (!safer.constants) { - safer.constants = { - MAX_LENGTH: safer.kMaxLength - } - if (safer.kStringMaxLength) { - safer.constants.MAX_STRING_LENGTH = safer.kStringMaxLength - } -} - -module.exports = safer - - -/***/ }), - -/***/ 1216: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -const crypto = __nccwpck_require__(6113); -const ece = __nccwpck_require__(5094); - -const encrypt = function(userPublicKey, userAuth, payload, contentEncoding) { - if (!userPublicKey) { - throw new Error('No user public key provided for encryption.'); - } - - if (typeof userPublicKey !== 'string') { - throw new Error('The subscription p256dh value must be a string.'); - } - - if (Buffer.from(userPublicKey, 'base64url').length !== 65) { - throw new Error('The subscription p256dh value should be 65 bytes long.'); - } - - if (!userAuth) { - throw new Error('No user auth provided for encryption.'); - } - - if (typeof userAuth !== 'string') { - throw new Error('The subscription auth key must be a string.'); - } - - if (Buffer.from(userAuth, 'base64url').length < 16) { - throw new Error('The subscription auth key should be at least 16 ' - + 'bytes long'); - } - - if (typeof payload !== 'string' && !Buffer.isBuffer(payload)) { - throw new Error('Payload must be either a string or a Node Buffer.'); - } - - if (typeof payload === 'string' || payload instanceof String) { - payload = Buffer.from(payload); - } - - const localCurve = crypto.createECDH('prime256v1'); - const localPublicKey = localCurve.generateKeys(); - - const salt = crypto.randomBytes(16).toString('base64url'); - - const cipherText = ece.encrypt(payload, { - version: contentEncoding, - dh: userPublicKey, - privateKey: localCurve, - salt: salt, - authSecret: userAuth - }); - - return { - localPublicKey: localPublicKey, - salt: salt, - cipherText: cipherText - }; -}; - -module.exports = { - encrypt: encrypt -}; - - -/***/ }), - -/***/ 760: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -const vapidHelper = __nccwpck_require__(2519); -const encryptionHelper = __nccwpck_require__(1216); -const WebPushLib = __nccwpck_require__(8733); -const WebPushError = __nccwpck_require__(5708); -const WebPushConstants = __nccwpck_require__(7933); - -const webPush = new WebPushLib(); - -module.exports = { - WebPushError: WebPushError, - supportedContentEncodings: WebPushConstants.supportedContentEncodings, - encrypt: encryptionHelper.encrypt, - getVapidHeaders: vapidHelper.getVapidHeaders, - generateVAPIDKeys: vapidHelper.generateVAPIDKeys, - setGCMAPIKey: webPush.setGCMAPIKey, - setVapidDetails: webPush.setVapidDetails, - generateRequestDetails: webPush.generateRequestDetails, - sendNotification: webPush.sendNotification.bind(webPush) -}; - - -/***/ }), - -/***/ 4933: -/***/ ((module) => { - -"use strict"; - - -/** - * @param {string} base64 - * @returns {boolean} - */ -function validate(base64) { - return /^[A-Za-z0-9\-_]+$/.test(base64); -} - -module.exports = { - validate: validate -}; - - -/***/ }), - -/***/ 2519: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -const crypto = __nccwpck_require__(6113); -const asn1 = __nccwpck_require__(731); -const jws = __nccwpck_require__(7507); -const { URL } = __nccwpck_require__(7310); - -const WebPushConstants = __nccwpck_require__(7933); -const urlBase64Helper = __nccwpck_require__(4933); - -/** - * DEFAULT_EXPIRATION is set to seconds in 12 hours - */ -const DEFAULT_EXPIRATION_SECONDS = 12 * 60 * 60; - -// Maximum expiration is 24 hours according. (See VAPID spec) -const MAX_EXPIRATION_SECONDS = 24 * 60 * 60; - -const ECPrivateKeyASN = asn1.define('ECPrivateKey', function() { - this.seq().obj( - this.key('version').int(), - this.key('privateKey').octstr(), - this.key('parameters').explicit(0).objid() - .optional(), - this.key('publicKey').explicit(1).bitstr() - .optional() - ); -}); - -function toPEM(key) { - return ECPrivateKeyASN.encode({ - version: 1, - privateKey: key, - parameters: [1, 2, 840, 10045, 3, 1, 7] // prime256v1 - }, 'pem', { - label: 'EC PRIVATE KEY' - }); -} - -function generateVAPIDKeys() { - const curve = crypto.createECDH('prime256v1'); - curve.generateKeys(); - - let publicKeyBuffer = curve.getPublicKey(); - let privateKeyBuffer = curve.getPrivateKey(); - - // Occassionally the keys will not be padded to the correct lengh resulting - // in errors, hence this padding. - // See https://github.com/web-push-libs/web-push/issues/295 for history. - if (privateKeyBuffer.length < 32) { - const padding = Buffer.alloc(32 - privateKeyBuffer.length); - padding.fill(0); - privateKeyBuffer = Buffer.concat([padding, privateKeyBuffer]); - } - - if (publicKeyBuffer.length < 65) { - const padding = Buffer.alloc(65 - publicKeyBuffer.length); - padding.fill(0); - publicKeyBuffer = Buffer.concat([padding, publicKeyBuffer]); - } - - return { - publicKey: publicKeyBuffer.toString('base64url'), - privateKey: privateKeyBuffer.toString('base64url') - }; -} - -function validateSubject(subject) { - if (!subject) { - throw new Error('No subject set in vapidDetails.subject.'); - } - - if (typeof subject !== 'string' || subject.length === 0) { - throw new Error('The subject value must be a string containing an https: URL or ' - + 'mailto: address. ' + subject); - } - - let subjectParseResult = null; - try { - subjectParseResult = new URL(subject); - } catch (err) { - throw new Error('Vapid subject is not a valid URL. ' + subject); - } - if (!['https:', 'mailto:'].includes(subjectParseResult.protocol)) { - throw new Error('Vapid subject is not an https: or mailto: URL. ' + subject); - } - if (subjectParseResult.hostname === 'localhost') { - console.warn('Vapid subject points to a localhost web URI, which is unsupported by ' - + 'Apple\'s push notification server and will result in a BadJwtToken error when ' - + 'sending notifications.'); - } -} - -function validatePublicKey(publicKey) { - if (!publicKey) { - throw new Error('No key set vapidDetails.publicKey'); - } - - if (typeof publicKey !== 'string') { - throw new Error('Vapid public key is must be a URL safe Base 64 ' - + 'encoded string.'); - } - - if (!urlBase64Helper.validate(publicKey)) { - throw new Error('Vapid public key must be a URL safe Base 64 (without "=")'); - } - - publicKey = Buffer.from(publicKey, 'base64url'); - - if (publicKey.length !== 65) { - throw new Error('Vapid public key should be 65 bytes long when decoded.'); - } -} - -function validatePrivateKey(privateKey) { - if (!privateKey) { - throw new Error('No key set in vapidDetails.privateKey'); - } - - if (typeof privateKey !== 'string') { - throw new Error('Vapid private key must be a URL safe Base 64 ' - + 'encoded string.'); - } - - if (!urlBase64Helper.validate(privateKey)) { - throw new Error('Vapid private key must be a URL safe Base 64 (without "=")'); - } - - privateKey = Buffer.from(privateKey, 'base64url'); - - if (privateKey.length !== 32) { - throw new Error('Vapid private key should be 32 bytes long when decoded.'); - } -} - -/** - * Given the number of seconds calculates - * the expiration in the future by adding the passed `numSeconds` - * with the current seconds from Unix Epoch - * - * @param {Number} numSeconds Number of seconds to be added - * @return {Number} Future expiration in seconds - */ -function getFutureExpirationTimestamp(numSeconds) { - const futureExp = new Date(); - futureExp.setSeconds(futureExp.getSeconds() + numSeconds); - return Math.floor(futureExp.getTime() / 1000); -} - -/** - * Validates the Expiration Header based on the VAPID Spec - * Throws error of type `Error` if the expiration is not validated - * - * @param {Number} expiration Expiration seconds from Epoch to be validated - */ -function validateExpiration(expiration) { - if (!Number.isInteger(expiration)) { - throw new Error('`expiration` value must be a number'); - } - - if (expiration < 0) { - throw new Error('`expiration` must be a positive integer'); - } - - // Roughly checks the time of expiration, since the max expiration can be ahead - // of the time than at the moment the expiration was generated - const maxExpirationTimestamp = getFutureExpirationTimestamp(MAX_EXPIRATION_SECONDS); - - if (expiration >= maxExpirationTimestamp) { - throw new Error('`expiration` value is greater than maximum of 24 hours'); - } -} - -/** - * This method takes the required VAPID parameters and returns the required - * header to be added to a Web Push Protocol Request. - * @param {string} audience This must be the origin of the push service. - * @param {string} subject This should be a URL or a 'mailto:' email - * address. - * @param {string} publicKey The VAPID public key. - * @param {string} privateKey The VAPID private key. - * @param {string} contentEncoding The contentEncoding type. - * @param {integer} [expiration] The expiration of the VAPID JWT. - * @return {Object} Returns an Object with the Authorization and - * 'Crypto-Key' values to be used as headers. - */ -function getVapidHeaders(audience, subject, publicKey, privateKey, contentEncoding, expiration) { - if (!audience) { - throw new Error('No audience could be generated for VAPID.'); - } - - if (typeof audience !== 'string' || audience.length === 0) { - throw new Error('The audience value must be a string containing the ' - + 'origin of a push service. ' + audience); - } - - try { - new URL(audience); // eslint-disable-line no-new - } catch (err) { - throw new Error('VAPID audience is not a url. ' + audience); - } - - validateSubject(subject); - validatePublicKey(publicKey); - validatePrivateKey(privateKey); - - privateKey = Buffer.from(privateKey, 'base64url'); - - if (expiration) { - validateExpiration(expiration); - } else { - expiration = getFutureExpirationTimestamp(DEFAULT_EXPIRATION_SECONDS); - } - - const header = { - typ: 'JWT', - alg: 'ES256' - }; - - const jwtPayload = { - aud: audience, - exp: expiration, - sub: subject - }; - - const jwt = jws.sign({ - header: header, - payload: jwtPayload, - privateKey: toPEM(privateKey) - }); - - if (contentEncoding === WebPushConstants.supportedContentEncodings.AES_128_GCM) { - return { - Authorization: 'vapid t=' + jwt + ', k=' + publicKey - }; - } - if (contentEncoding === WebPushConstants.supportedContentEncodings.AES_GCM) { - return { - Authorization: 'WebPush ' + jwt, - 'Crypto-Key': 'p256ecdsa=' + publicKey - }; - } - - throw new Error('Unsupported encoding type specified.'); -} - -module.exports = { - generateVAPIDKeys: generateVAPIDKeys, - getFutureExpirationTimestamp: getFutureExpirationTimestamp, - getVapidHeaders: getVapidHeaders, - validateSubject: validateSubject, - validatePublicKey: validatePublicKey, - validatePrivateKey: validatePrivateKey, - validateExpiration: validateExpiration -}; - - -/***/ }), - -/***/ 7933: -/***/ ((module) => { - -"use strict"; - - -const WebPushConstants = {}; - -WebPushConstants.supportedContentEncodings = { - AES_GCM: 'aesgcm', - AES_128_GCM: 'aes128gcm' -}; - -WebPushConstants.supportedUrgency = { - VERY_LOW: 'very-low', - LOW: 'low', - NORMAL: 'normal', - HIGH: 'high' -}; - -module.exports = WebPushConstants; - - -/***/ }), - -/***/ 5708: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -function WebPushError(message, statusCode, headers, body, endpoint) { - Error.captureStackTrace(this, this.constructor); - - this.name = this.constructor.name; - this.message = message; - this.statusCode = statusCode; - this.headers = headers; - this.body = body; - this.endpoint = endpoint; -} - -(__nccwpck_require__(3837).inherits)(WebPushError, Error); - -module.exports = WebPushError; - - -/***/ }), - -/***/ 8733: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -const url = __nccwpck_require__(7310); -const https = __nccwpck_require__(5687); - -const WebPushError = __nccwpck_require__(5708); -const vapidHelper = __nccwpck_require__(2519); -const encryptionHelper = __nccwpck_require__(1216); -const webPushConstants = __nccwpck_require__(7933); -const urlBase64Helper = __nccwpck_require__(4933); - -// Default TTL is four weeks. -const DEFAULT_TTL = 2419200; - -let gcmAPIKey = ''; -let vapidDetails; - -function WebPushLib() { - -} - -/** - * When sending messages to a GCM endpoint you need to set the GCM API key - * by either calling setGMAPIKey() or passing in the API key as an option - * to sendNotification(). - * @param {string} apiKey The API key to send with the GCM request. - */ -WebPushLib.prototype.setGCMAPIKey = function(apiKey) { - if (apiKey === null) { - gcmAPIKey = null; - return; - } - - if (typeof apiKey === 'undefined' - || typeof apiKey !== 'string' - || apiKey.length === 0) { - throw new Error('The GCM API Key should be a non-empty string or null.'); - } - - gcmAPIKey = apiKey; -}; - -/** - * When making requests where you want to define VAPID details, call this - * method before sendNotification() or pass in the details and options to - * sendNotification. - * @param {string} subject This must be either a URL or a 'mailto:' - * address. For example: 'https://my-site.com/contact' or - * 'mailto: contact@my-site.com' - * @param {string} publicKey The public VAPID key, a URL safe, base64 encoded string - * @param {string} privateKey The private VAPID key, a URL safe, base64 encoded string. - */ -WebPushLib.prototype.setVapidDetails = function(subject, publicKey, privateKey) { - if (arguments.length === 1 && arguments[0] === null) { - vapidDetails = null; - return; - } - - vapidHelper.validateSubject(subject); - vapidHelper.validatePublicKey(publicKey); - vapidHelper.validatePrivateKey(privateKey); - - vapidDetails = { - subject: subject, - publicKey: publicKey, - privateKey: privateKey - }; - }; - - /** - * To get the details of a request to trigger a push message, without sending - * a push notification call this method. - * - * This method will throw an error if there is an issue with the input. - * @param {PushSubscription} subscription The PushSubscription you wish to - * send the notification to. - * @param {string|Buffer} [payload] The payload you wish to send to the - * the user. - * @param {Object} [options] Options for the GCM API key and - * vapid keys can be passed in if they are unique for each notification you - * wish to send. - * @return {Object} This method returns an Object which - * contains 'endpoint', 'method', 'headers' and 'payload'. - */ -WebPushLib.prototype.generateRequestDetails = function(subscription, payload, options) { - if (!subscription || !subscription.endpoint) { - throw new Error('You must pass in a subscription with at least ' - + 'an endpoint.'); - } - - if (typeof subscription.endpoint !== 'string' - || subscription.endpoint.length === 0) { - throw new Error('The subscription endpoint must be a string with ' - + 'a valid URL.'); - } - - if (payload) { - // Validate the subscription keys - if (typeof subscription !== 'object' || !subscription.keys - || !subscription.keys.p256dh - || !subscription.keys.auth) { - throw new Error('To send a message with a payload, the ' - + 'subscription must have \'auth\' and \'p256dh\' keys.'); - } - } - - let currentGCMAPIKey = gcmAPIKey; - let currentVapidDetails = vapidDetails; - let timeToLive = DEFAULT_TTL; - let extraHeaders = {}; - let contentEncoding = webPushConstants.supportedContentEncodings.AES_128_GCM; - let urgency = webPushConstants.supportedUrgency.NORMAL; - let topic; - let proxy; - let agent; - let timeout; - - if (options) { - const validOptionKeys = [ - 'headers', - 'gcmAPIKey', - 'vapidDetails', - 'TTL', - 'contentEncoding', - 'urgency', - 'topic', - 'proxy', - 'agent', - 'timeout' - ]; - const optionKeys = Object.keys(options); - for (let i = 0; i < optionKeys.length; i += 1) { - const optionKey = optionKeys[i]; - if (!validOptionKeys.includes(optionKey)) { - throw new Error('\'' + optionKey + '\' is an invalid option. ' - + 'The valid options are [\'' + validOptionKeys.join('\', \'') - + '\'].'); - } - } - - if (options.headers) { - extraHeaders = options.headers; - let duplicates = Object.keys(extraHeaders) - .filter(function (header) { - return typeof options[header] !== 'undefined'; - }); - - if (duplicates.length > 0) { - throw new Error('Duplicated headers defined [' - + duplicates.join(',') + ']. Please either define the header in the' - + 'top level options OR in the \'headers\' key.'); - } - } - - if (options.gcmAPIKey) { - currentGCMAPIKey = options.gcmAPIKey; - } - - // Falsy values are allowed here so one can skip Vapid `else if` below and use FCM - if (options.vapidDetails !== undefined) { - currentVapidDetails = options.vapidDetails; - } - - if (options.TTL !== undefined) { - timeToLive = Number(options.TTL); - if (timeToLive < 0) { - throw new Error('TTL should be a number and should be at least 0'); - } - } - - if (options.contentEncoding) { - if ((options.contentEncoding === webPushConstants.supportedContentEncodings.AES_128_GCM - || options.contentEncoding === webPushConstants.supportedContentEncodings.AES_GCM)) { - contentEncoding = options.contentEncoding; - } else { - throw new Error('Unsupported content encoding specified.'); - } - } - - if (options.urgency) { - if ((options.urgency === webPushConstants.supportedUrgency.VERY_LOW - || options.urgency === webPushConstants.supportedUrgency.LOW - || options.urgency === webPushConstants.supportedUrgency.NORMAL - || options.urgency === webPushConstants.supportedUrgency.HIGH)) { - urgency = options.urgency; - } else { - throw new Error('Unsupported urgency specified.'); - } - } - - if (options.topic) { - if (!urlBase64Helper.validate(options.topic)) { - throw new Error('Unsupported characters set use the URL or filename-safe Base64 characters set'); - } - if (options.topic.length > 32) { - throw new Error('use maximum of 32 characters from the URL or filename-safe Base64 characters set'); - } - topic = options.topic; - } - - if (options.proxy) { - if (typeof options.proxy === 'string' - || typeof options.proxy.host === 'string') { - proxy = options.proxy; - } else { - console.warn('Attempt to use proxy option, but invalid type it should be a string or proxy options object.'); - } - } - - if (options.agent) { - if (options.agent instanceof https.Agent) { - if (proxy) { - console.warn('Agent option will be ignored because proxy option is defined.'); - } - - agent = options.agent; - } else { - console.warn('Wrong type for the agent option, it should be an instance of https.Agent.'); - } - } - - if (typeof options.timeout === 'number') { - timeout = options.timeout; - } - } - - if (typeof timeToLive === 'undefined') { - timeToLive = DEFAULT_TTL; - } - - const requestDetails = { - method: 'POST', - headers: { - TTL: timeToLive - } - }; - Object.keys(extraHeaders).forEach(function (header) { - requestDetails.headers[header] = extraHeaders[header]; - }); - let requestPayload = null; - - if (payload) { - const encrypted = encryptionHelper - .encrypt(subscription.keys.p256dh, subscription.keys.auth, payload, contentEncoding); - - requestDetails.headers['Content-Length'] = encrypted.cipherText.length; - requestDetails.headers['Content-Type'] = 'application/octet-stream'; - - if (contentEncoding === webPushConstants.supportedContentEncodings.AES_128_GCM) { - requestDetails.headers['Content-Encoding'] = webPushConstants.supportedContentEncodings.AES_128_GCM; - } else if (contentEncoding === webPushConstants.supportedContentEncodings.AES_GCM) { - requestDetails.headers['Content-Encoding'] = webPushConstants.supportedContentEncodings.AES_GCM; - requestDetails.headers.Encryption = 'salt=' + encrypted.salt; - requestDetails.headers['Crypto-Key'] = 'dh=' + encrypted.localPublicKey.toString('base64url'); - } - - requestPayload = encrypted.cipherText; - } else { - requestDetails.headers['Content-Length'] = 0; - } - - const isGCM = subscription.endpoint.startsWith('https://android.googleapis.com/gcm/send'); - const isFCM = subscription.endpoint.startsWith('https://fcm.googleapis.com/fcm/send'); - // VAPID isn't supported by GCM hence the if, else if. - if (isGCM) { - if (!currentGCMAPIKey) { - console.warn('Attempt to send push notification to GCM endpoint, ' - + 'but no GCM key is defined. Please use setGCMApiKey() or add ' - + '\'gcmAPIKey\' as an option.'); - } else { - requestDetails.headers.Authorization = 'key=' + currentGCMAPIKey; - } - } else if (currentVapidDetails) { - const parsedUrl = url.parse(subscription.endpoint); - const audience = parsedUrl.protocol + '//' - + parsedUrl.host; - - const vapidHeaders = vapidHelper.getVapidHeaders( - audience, - currentVapidDetails.subject, - currentVapidDetails.publicKey, - currentVapidDetails.privateKey, - contentEncoding - ); - - requestDetails.headers.Authorization = vapidHeaders.Authorization; - - if (contentEncoding === webPushConstants.supportedContentEncodings.AES_GCM) { - if (requestDetails.headers['Crypto-Key']) { - requestDetails.headers['Crypto-Key'] += ';' - + vapidHeaders['Crypto-Key']; - } else { - requestDetails.headers['Crypto-Key'] = vapidHeaders['Crypto-Key']; - } - } - } else if (isFCM && currentGCMAPIKey) { - requestDetails.headers.Authorization = 'key=' + currentGCMAPIKey; - } - - requestDetails.headers.Urgency = urgency; - - if (topic) { - requestDetails.headers.Topic = topic; - } - - requestDetails.body = requestPayload; - requestDetails.endpoint = subscription.endpoint; - - if (proxy) { - requestDetails.proxy = proxy; - } - - if (agent) { - requestDetails.agent = agent; - } - - if (timeout) { - requestDetails.timeout = timeout; - } - - return requestDetails; - }; - -/** - * To send a push notification call this method with a subscription, optional - * payload and any options. - * @param {PushSubscription} subscription The PushSubscription you wish to - * send the notification to. - * @param {string|Buffer} [payload] The payload you wish to send to the - * the user. - * @param {Object} [options] Options for the GCM API key and - * vapid keys can be passed in if they are unique for each notification you - * wish to send. - * @return {Promise} This method returns a Promise which - * resolves if the sending of the notification was successful, otherwise it - * rejects. - */ -WebPushLib.prototype.sendNotification = function(subscription, payload, options) { - let requestDetails; - try { - requestDetails = this.generateRequestDetails(subscription, payload, options); - } catch (err) { - return Promise.reject(err); - } - - return new Promise(function(resolve, reject) { - const httpsOptions = {}; - const urlParts = url.parse(requestDetails.endpoint); - httpsOptions.hostname = urlParts.hostname; - httpsOptions.port = urlParts.port; - httpsOptions.path = urlParts.path; - - httpsOptions.headers = requestDetails.headers; - httpsOptions.method = requestDetails.method; - - if (requestDetails.timeout) { - httpsOptions.timeout = requestDetails.timeout; - } - - if (requestDetails.agent) { - httpsOptions.agent = requestDetails.agent; - } - - if (requestDetails.proxy) { - const { HttpsProxyAgent } = __nccwpck_require__(9521); // eslint-disable-line global-require - httpsOptions.agent = new HttpsProxyAgent(requestDetails.proxy); - } - - const pushRequest = https.request(httpsOptions, function(pushResponse) { - let responseText = ''; - - pushResponse.on('data', function(chunk) { - responseText += chunk; - }); - - pushResponse.on('end', function() { - if (pushResponse.statusCode < 200 || pushResponse.statusCode > 299) { - reject(new WebPushError( - 'Received unexpected response code', - pushResponse.statusCode, - pushResponse.headers, - responseText, - requestDetails.endpoint - )); - } else { - resolve({ - statusCode: pushResponse.statusCode, - body: responseText, - headers: pushResponse.headers - }); - } - }); - }); - - if (requestDetails.timeout) { - pushRequest.on('timeout', function() { - pushRequest.destroy(new Error('Socket timeout')); - }); - } - - pushRequest.on('error', function(e) { - reject(e); - }); - - if (requestDetails.body) { - pushRequest.write(requestDetails.body); - } - - pushRequest.end(); - }); - }; - -module.exports = WebPushLib; - - -/***/ }), - -/***/ 4341: -/***/ ((module) => { - -module.exports = eval("require")("supports-color"); - - -/***/ }), - -/***/ 9491: -/***/ ((module) => { - -"use strict"; -module.exports = require("assert"); - -/***/ }), - -/***/ 4300: -/***/ ((module) => { - -"use strict"; -module.exports = require("buffer"); - -/***/ }), - -/***/ 6113: -/***/ ((module) => { - -"use strict"; -module.exports = require("crypto"); - -/***/ }), - -/***/ 3685: -/***/ ((module) => { - -"use strict"; -module.exports = require("http"); - -/***/ }), - -/***/ 5687: -/***/ ((module) => { - -"use strict"; -module.exports = require("https"); - -/***/ }), - -/***/ 1808: -/***/ ((module) => { - -"use strict"; -module.exports = require("net"); - -/***/ }), - -/***/ 2781: -/***/ ((module) => { - -"use strict"; -module.exports = require("stream"); - -/***/ }), - -/***/ 4404: -/***/ ((module) => { - -"use strict"; -module.exports = require("tls"); - -/***/ }), - -/***/ 6224: -/***/ ((module) => { - -"use strict"; -module.exports = require("tty"); - -/***/ }), - -/***/ 7310: -/***/ ((module) => { - -"use strict"; -module.exports = require("url"); - -/***/ }), - -/***/ 3837: -/***/ ((module) => { - -"use strict"; -module.exports = require("util"); - -/***/ }) - -/******/ }); -/************************************************************************/ -/******/ // The module cache -/******/ var __webpack_module_cache__ = {}; -/******/ -/******/ // The require function -/******/ function __nccwpck_require__(moduleId) { -/******/ // Check if module is in cache -/******/ var cachedModule = __webpack_module_cache__[moduleId]; -/******/ if (cachedModule !== undefined) { -/******/ return cachedModule.exports; -/******/ } -/******/ // Create a new module (and put it into the cache) -/******/ var module = __webpack_module_cache__[moduleId] = { -/******/ id: moduleId, -/******/ loaded: false, -/******/ exports: {} -/******/ }; -/******/ -/******/ // Execute the module function -/******/ var threw = true; -/******/ try { -/******/ __webpack_modules__[moduleId].call(module.exports, module, module.exports, __nccwpck_require__); -/******/ threw = false; -/******/ } finally { -/******/ if(threw) delete __webpack_module_cache__[moduleId]; -/******/ } -/******/ -/******/ // Flag the module as loaded -/******/ module.loaded = true; -/******/ -/******/ // Return the exports of the module -/******/ return module.exports; -/******/ } -/******/ -/************************************************************************/ -/******/ /* webpack/runtime/node module decorator */ -/******/ (() => { -/******/ __nccwpck_require__.nmd = (module) => { -/******/ module.paths = []; -/******/ if (!module.children) module.children = []; -/******/ return module; -/******/ }; -/******/ })(); -/******/ -/******/ /* webpack/runtime/compat */ -/******/ -/******/ if (typeof __nccwpck_require__ !== 'undefined') __nccwpck_require__.ab = __dirname + "/"; -/******/ -/************************************************************************/ -/******/ -/******/ // startup -/******/ // Load entry module and return exports -/******/ // This entry module is referenced by other modules so it can't be inlined -/******/ var __webpack_exports__ = __nccwpck_require__(760); -/******/ module.exports = __webpack_exports__; -/******/ -/******/ })() -; \ No newline at end of file From f56137326345ef48cfb32b602647655edf9e65cc Mon Sep 17 00:00:00 2001 From: bonbud-macryg Date: Thu, 1 Aug 2024 14:04:13 +0100 Subject: [PATCH 31/46] Remove push notifications stuff from Hoon --- .../neo/cod/std/src/imp/notifications.hoon | 21 +------------------ 1 file changed, 1 insertion(+), 20 deletions(-) diff --git a/pkg/arvo/neo/cod/std/src/imp/notifications.hoon b/pkg/arvo/neo/cod/std/src/imp/notifications.hoon index 0c42b4cdce..6fdd935b1f 100644 --- a/pkg/arvo/neo/cod/std/src/imp/notifications.hoon +++ b/pkg/arvo/neo/cod/std/src/imp/notifications.hoon @@ -1,4 +1,3 @@ -/@ json /@ notification /@ notifications-config /@ notifications-controller @@ -24,7 +23,7 @@ :: ++ poke ^- (set stud:neo) - (sy %json %notification ~) + (sy %notification ~) :: ++ kids ^- kids:neo @@ -35,8 +34,6 @@ [[%pro %notification] ~] :- [[%.y %config] [%.n %tas] %.n] [[%pro %notifications-config] ~] - :- [[%.y %endpoints] [%.n %t] %.n] - [[%pro %json] ~] == :: ++ deps @@ -68,22 +65,6 @@ !! %notifications-controller [~ [%notifications-controller vaz]] - :: - :: XX should sanity-check json - %json - :_ [%notifications-controller !>(state)] - =/ cred !<(json vaz) - ?~ cred - ~ - :: XX parse expirationTime - =/ endpoint - %. cred - (ot ~[endpoint+so]):dejs:format - :: XX handle expirationTime with behn? - :: remove this endpoint when the timer fires - :~ :- (welp here.bowl ~[%endpoint t/endpoint]) - [%make %json `[%json !>(cred)] ~] - == :: %notification =/ not !<(notification vaz) From 3dfcf3f54bae0ef0d0f44fb9908359cdbf3f7e40 Mon Sep 17 00:00:00 2001 From: bonbud-macryg Date: Fri, 2 Aug 2024 10:38:55 +0100 Subject: [PATCH 32/46] Remove notifications-config imp and pro --- .../cod/std/src/imp/notifications-config.hoon | 28 ----------- .../neo/cod/std/src/imp/notifications.hoon | 48 +++++++++---------- .../cod/std/src/pro/notifications-config.hoon | 4 -- 3 files changed, 24 insertions(+), 56 deletions(-) delete mode 100644 pkg/arvo/neo/cod/std/src/imp/notifications-config.hoon delete mode 100644 pkg/arvo/neo/cod/std/src/pro/notifications-config.hoon diff --git a/pkg/arvo/neo/cod/std/src/imp/notifications-config.hoon b/pkg/arvo/neo/cod/std/src/imp/notifications-config.hoon deleted file mode 100644 index 01b4b6bf98..0000000000 --- a/pkg/arvo/neo/cod/std/src/imp/notifications-config.hoon +++ /dev/null @@ -1,28 +0,0 @@ -/@ notifications-config -^- kook:neo -|% -++ state - [%pro %notifications-config] -++ poke - (sy %notifications-config ~) -++ kids - *kids:neo -++ deps - *deps:neo -++ form - ^- form:neo - |_ [=bowl:neo =aeon:neo =stud:neo state-vase=vase] - +* state !<(notifications-config state-vase) - ++ init - |= old=(unit pail:neo) - ^- (quip card:neo pail:neo) - ?^ old - [~ (need old)] - [~ [%notifications-config !>(~)]] - ++ poke - |= [=stud:neo vaz=vase] - ^- (quip card:neo pail:neo) - ?> =(%notifications-config stud) - [~ [%notifications-config vaz]] - -- --- \ No newline at end of file diff --git a/pkg/arvo/neo/cod/std/src/imp/notifications.hoon b/pkg/arvo/neo/cod/std/src/imp/notifications.hoon index 6fdd935b1f..5915a75a3f 100644 --- a/pkg/arvo/neo/cod/std/src/imp/notifications.hoon +++ b/pkg/arvo/neo/cod/std/src/imp/notifications.hoon @@ -1,5 +1,4 @@ /@ notification -/@ notifications-config /@ notifications-controller ^- kook:neo => @@ -32,8 +31,12 @@ %- ~(gas by *lads:neo) :~ :- [[%.y %notification] [%.n %da] %.n] [[%pro %notification] ~] - :- [[%.y %config] [%.n %tas] %.n] - [[%pro %notifications-config] ~] + :- [[%.y %config] [%.n %tas] [%.y %buzz] %.y] + [[%pro %sig] ~] + :- [[%.y %config] [%.n %tas] [%.y %mute] %.y] + [[%pro %sig] ~] + :- [[%.y %config] [%.n %tas] [%.y %kill] %.y] + [[%pro %sig] ~] == :: ++ deps @@ -50,11 +53,7 @@ [~ u.old] :_ [%notifications-controller !>(|=(notification #/config/default))] :~ :- (welp here.bowl ~[%config %default]) - :* %make - %notifications-config - `[%notifications-config !>(*notifications-config)] - ~ - == + [%make %sig `[%sig !>(~)] ~] == :: ++ poke @@ -71,23 +70,24 @@ ?< =('' cord.not) ?< (gth time.not now.bowl) ?> =(pith.src.bowl (tail src.not)) - =/ config - !< notifications-config - q.pail:(need (~(get by ~(tar of:neo kids.bowl)) (state not))) + :: =/ config + :: !< notifications-config + :: q.pail:(need (~(get by ~(tar of:neo kids.bowl)) (state not))) + :: :_ [%notifications-controller !>(state)] + :: ?: (has-pith-in kill.config src.not) + :: ~ + :: ?: (has-pith-in mute.config src.not) + :: =. flag.not %.y + :: :~ :- (welp here.bowl ~[[da/now.bowl]]) + :: [%make %notification `[%notification !>(not)] ~] + :: == + :: ?: (has-pith-in buzz.config src.not) + :: =. flag.not %.y + :: :~ :- (welp here.bowl ~[[da/now.bowl]]) + :: [%make %notification `[%notification !>(not)] ~] + :: :: XX send push notifications to subscribers + :: == :_ [%notifications-controller !>(state)] - ?: (has-pith-in kill.config src.not) - ~ - ?: (has-pith-in mute.config src.not) - =. flag.not %.y - :~ :- (welp here.bowl ~[[da/now.bowl]]) - [%make %notification `[%notification !>(not)] ~] - == - ?: (has-pith-in buzz.config src.not) - =. flag.not %.y - :~ :- (welp here.bowl ~[[da/now.bowl]]) - [%make %notification `[%notification !>(not)] ~] - :: XX send push notifications to subscribers - == ?. flag.not =. flag.not %.y :~ :- (welp here.bowl ~[[da/now.bowl]]) diff --git a/pkg/arvo/neo/cod/std/src/pro/notifications-config.hoon b/pkg/arvo/neo/cod/std/src/pro/notifications-config.hoon deleted file mode 100644 index 6ddcec2bf5..0000000000 --- a/pkg/arvo/neo/cod/std/src/pro/notifications-config.hoon +++ /dev/null @@ -1,4 +0,0 @@ -$: buzz=(set pith) - mute=(set pith) - kill=(set pith) -== \ No newline at end of file From e24d7c11b86a7a0baca0d4e14296e57d19779c1b Mon Sep 17 00:00:00 2001 From: bonbud-macryg Date: Fri, 2 Aug 2024 11:56:09 +0100 Subject: [PATCH 33/46] New imp/notifications-config --- .../cod/std/src/imp/notifications-config.hoon | 31 +++++++++++++++++++ .../neo/cod/std/src/imp/notifications.hoon | 11 +++---- 2 files changed, 36 insertions(+), 6 deletions(-) create mode 100644 pkg/arvo/neo/cod/std/src/imp/notifications-config.hoon diff --git a/pkg/arvo/neo/cod/std/src/imp/notifications-config.hoon b/pkg/arvo/neo/cod/std/src/imp/notifications-config.hoon new file mode 100644 index 0000000000..d1aac89ef2 --- /dev/null +++ b/pkg/arvo/neo/cod/std/src/imp/notifications-config.hoon @@ -0,0 +1,31 @@ +^- kook:neo +|% +++ state [%pro %sig] +++ poke (sy %sig ~) +++ kids + ^- kids:neo + %- some + :- %y + %- ~(gas by *lads:neo) + :~ :- [[%.y %buzz] [%.n %tas] %.y] + [[%pro %sig] ~] + :- [[%.y %mute] [%.n %tas] %.y] + [[%pro %sig] ~] + :- [[%.y %kill] [%.n %tas] %.y] + [[%pro %sig] ~] + == +++ deps + *deps:neo +++ form + ^- form:neo + |_ [=bowl:neo =aeon:neo =stud:neo state-vase=vase] + ++ init + |= old=(unit pail:neo) + ^- (quip card:neo pail:neo) + [~ [%sig !>(~)]] + ++ poke + |= [=stud:neo vaz=vase] + ^- (quip card:neo pail:neo) + [~ [%sig !>(~)]] + -- +-- \ No newline at end of file diff --git a/pkg/arvo/neo/cod/std/src/imp/notifications.hoon b/pkg/arvo/neo/cod/std/src/imp/notifications.hoon index 5915a75a3f..f2b6f45966 100644 --- a/pkg/arvo/neo/cod/std/src/imp/notifications.hoon +++ b/pkg/arvo/neo/cod/std/src/imp/notifications.hoon @@ -1,4 +1,5 @@ /@ notification +/@ notifications-config /@ notifications-controller ^- kook:neo => @@ -31,12 +32,8 @@ %- ~(gas by *lads:neo) :~ :- [[%.y %notification] [%.n %da] %.n] [[%pro %notification] ~] - :- [[%.y %config] [%.n %tas] [%.y %buzz] %.y] - [[%pro %sig] ~] - :- [[%.y %config] [%.n %tas] [%.y %mute] %.y] - [[%pro %sig] ~] - :- [[%.y %config] [%.n %tas] [%.y %kill] %.y] - [[%pro %sig] ~] + :- [[%.y %config] [%.n %tas] %.n] + [[%pro %notifications-config] ~] == :: ++ deps @@ -70,6 +67,8 @@ ?< =('' cord.not) ?< (gth time.not now.bowl) ?> =(pith.src.bowl (tail src.not)) + ~& >> ~(tar of:neo kids.bowl) + ~& >> (~(get by ~(tar of:neo kids.bowl)) (state not)) :: =/ config :: !< notifications-config :: q.pail:(need (~(get by ~(tar of:neo kids.bowl)) (state not))) From 6a2378a3c717b58f247ebcd1946a6a34adb1b518 Mon Sep 17 00:00:00 2001 From: bonbud-macryg Date: Fri, 2 Aug 2024 13:24:10 +0100 Subject: [PATCH 34/46] Make notifications-config on init --- pkg/arvo/neo/cod/std/src/imp/notifications.hoon | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/pkg/arvo/neo/cod/std/src/imp/notifications.hoon b/pkg/arvo/neo/cod/std/src/imp/notifications.hoon index f2b6f45966..4291375f9d 100644 --- a/pkg/arvo/neo/cod/std/src/imp/notifications.hoon +++ b/pkg/arvo/neo/cod/std/src/imp/notifications.hoon @@ -50,7 +50,7 @@ [~ u.old] :_ [%notifications-controller !>(|=(notification #/config/default))] :~ :- (welp here.bowl ~[%config %default]) - [%make %sig `[%sig !>(~)] ~] + [%make %notifications-config `[%sig !>(~)] ~] == :: ++ poke @@ -67,8 +67,10 @@ ?< =('' cord.not) ?< (gth time.not now.bowl) ?> =(pith.src.bowl (tail src.not)) + ~& >> (state not) ~& >> ~(tar of:neo kids.bowl) ~& >> (~(get by ~(tar of:neo kids.bowl)) (state not)) + ~& >> (~(kids of:neo kids.bowl) #/config/default) :: =/ config :: !< notifications-config :: q.pail:(need (~(get by ~(tar of:neo kids.bowl)) (state not))) From 6708f144a2a3dcb696f5cf31cc3fd10b4975e6d6 Mon Sep 17 00:00:00 2001 From: bonbud-macryg Date: Fri, 2 Aug 2024 14:40:39 +0100 Subject: [PATCH 35/46] Add todo about checking piths --- pkg/arvo/neo/cod/std/src/imp/notifications.hoon | 2 ++ 1 file changed, 2 insertions(+) diff --git a/pkg/arvo/neo/cod/std/src/imp/notifications.hoon b/pkg/arvo/neo/cod/std/src/imp/notifications.hoon index 4291375f9d..3b0c8ff88f 100644 --- a/pkg/arvo/neo/cod/std/src/imp/notifications.hoon +++ b/pkg/arvo/neo/cod/std/src/imp/notifications.hoon @@ -66,6 +66,8 @@ =/ not !<(notification vaz) ?< =('' cord.not) ?< (gth time.not now.bowl) + :: XX should cut head off path more intelligently + :: "if head is our.bowl, remove head" ?> =(pith.src.bowl (tail src.not)) ~& >> (state not) ~& >> ~(tar of:neo kids.bowl) From ef0b56da0c1d02bc1c7425de2ab0547ede2d4898 Mon Sep 17 00:00:00 2001 From: bonbud-macryg Date: Fri, 2 Aug 2024 14:41:43 +0100 Subject: [PATCH 36/46] Remove outdated import --- pkg/arvo/neo/cod/std/src/imp/notifications.hoon | 1 - 1 file changed, 1 deletion(-) diff --git a/pkg/arvo/neo/cod/std/src/imp/notifications.hoon b/pkg/arvo/neo/cod/std/src/imp/notifications.hoon index 3b0c8ff88f..2da3ef42d3 100644 --- a/pkg/arvo/neo/cod/std/src/imp/notifications.hoon +++ b/pkg/arvo/neo/cod/std/src/imp/notifications.hoon @@ -1,5 +1,4 @@ /@ notification -/@ notifications-config /@ notifications-controller ^- kook:neo => From 09cae70385ee1cf2a7e7cc0ec86db6be37a77f5e Mon Sep 17 00:00:00 2001 From: bonbud-macryg Date: Tue, 23 Jul 2024 16:32:49 +0100 Subject: [PATCH 37/46] Draft frontend code --- pkg/arvo/neo/cod/std/src/con/sky-htmx.hoon | 42 +++++++++++++++++++ .../neo/cod/std/src/imp/notifications.hoon | 21 +++++++++- 2 files changed, 62 insertions(+), 1 deletion(-) diff --git a/pkg/arvo/neo/cod/std/src/con/sky-htmx.hoon b/pkg/arvo/neo/cod/std/src/con/sky-htmx.hoon index fa2d038c3a..2e9d3e0853 100644 --- a/pkg/arvo/neo/cod/std/src/con/sky-htmx.hoon +++ b/pkg/arvo/neo/cod/std/src/con/sky-htmx.hoon @@ -179,9 +179,47 @@ } ''' == +<<<<<<< HEAD >>>>>>> 13d77f915b (Draft frontend code) ======= >>>>>>> a9b223316b (Remove push notification stuff from sky-htmx) +======= + ;script: {(trip a-i-r)} + ;script: {(trip date-now)} + :: + :: set up push notifications for this browser + ;script + ;+ ;/ %- trip + ''' + const push = require('../fil/web-push.js') + + addEventListener('load', async () => { + let sw = await navigator.serviceWorker.register('../fil/push-sw.js') + console.log(sw) + subscribeToNotifications() + }); + + async function subscribeToNotifications() { + let sw = await navigator.serviceWorker.ready + const vapidKeys = push.generateVAPIDKeys() + let pushSubscriptionDetails = await sw.pushManager.subscribe({ + userVisibleOnly: true, + applicationServerKey: `${vapidKeys.publicKey}` + }); + + sendSubscriptionToServer(pushSubscriptionDetails) + + // console.log(JSON.stringify(pushSubscriptionDetails)) + } + + function sendSubscriptionToServer(pushSubscriptionDetails) { + document.getElementById('push-subscription-details').value = + JSON.stringify(pushSubscriptionDetails) + document.getElementById('subscription-form').submit() + } + ''' + == +>>>>>>> 13d77f915b (Draft frontend code) ;+ favicon ;+ manifest == @@ -198,11 +236,15 @@ ;+ eye ;+ menu-btn-style ;+ theme-style +<<<<<<< HEAD <<<<<<< HEAD ;+ notifications-subscription >>>>>>> 13d77f915b (Draft frontend code) ======= >>>>>>> a9b223316b (Remove push notification stuff from sky-htmx) +======= + ;+ notifications-subscription +>>>>>>> 13d77f915b (Draft frontend code) == == -- diff --git a/pkg/arvo/neo/cod/std/src/imp/notifications.hoon b/pkg/arvo/neo/cod/std/src/imp/notifications.hoon index 2da3ef42d3..561bc01504 100644 --- a/pkg/arvo/neo/cod/std/src/imp/notifications.hoon +++ b/pkg/arvo/neo/cod/std/src/imp/notifications.hoon @@ -1,3 +1,4 @@ +/@ txt /@ notification /@ notifications-controller ^- kook:neo @@ -22,7 +23,7 @@ :: ++ poke ^- (set stud:neo) - (sy %notification ~) + (sy %txt %notification ~) :: ++ kids ^- kids:neo @@ -33,6 +34,8 @@ [[%pro %notification] ~] :- [[%.y %config] [%.n %tas] %.n] [[%pro %notifications-config] ~] + :- [[%.n %t] %.n] + [[%pro %txt] ~] == :: ++ deps @@ -90,6 +93,22 @@ :: :: XX send push notifications to subscribers :: == :_ [%notifications-controller !>(state)] +<<<<<<< HEAD +======= + ?: (has-pith-in-any kill.config pith.not) + ~ + ?: (has-pith-in-any mute.config pith.not) + =. flag.not %.y + :~ :- (welp here.bowl ~[[da/now.bowl]]) + [%make %notification `[%notification !>(not)] ~] + == + ?: (has-pith-in-any buzz.config pith.not) + =. flag.not %.y + :~ :- (welp here.bowl ~[[da/now.bowl]]) + [%make %notification `[%notification !>(not)] ~] + :: XX send push notification + == +>>>>>>> 13d77f915b (Draft frontend code) ?. flag.not =. flag.not %.y :~ :- (welp here.bowl ~[[da/now.bowl]]) From f3e4d29c15d256ac0df54d9e2d88f12e6051d4ba Mon Sep 17 00:00:00 2001 From: bonbud-macryg Date: Thu, 1 Aug 2024 13:57:38 +0100 Subject: [PATCH 38/46] Remove push notification stuff from sky-htmx --- pkg/arvo/neo/cod/std/src/con/sky-htmx.hoon | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/pkg/arvo/neo/cod/std/src/con/sky-htmx.hoon b/pkg/arvo/neo/cod/std/src/con/sky-htmx.hoon index 2e9d3e0853..dff2649663 100644 --- a/pkg/arvo/neo/cod/std/src/con/sky-htmx.hoon +++ b/pkg/arvo/neo/cod/std/src/con/sky-htmx.hoon @@ -186,6 +186,7 @@ ======= ;script: {(trip a-i-r)} ;script: {(trip date-now)} +<<<<<<< HEAD :: :: set up push notifications for this browser ;script @@ -220,6 +221,8 @@ ''' == >>>>>>> 13d77f915b (Draft frontend code) +======= +>>>>>>> a9b223316b (Remove push notification stuff from sky-htmx) ;+ favicon ;+ manifest == @@ -237,6 +240,7 @@ ;+ menu-btn-style ;+ theme-style <<<<<<< HEAD +<<<<<<< HEAD <<<<<<< HEAD ;+ notifications-subscription >>>>>>> 13d77f915b (Draft frontend code) @@ -245,6 +249,8 @@ ======= ;+ notifications-subscription >>>>>>> 13d77f915b (Draft frontend code) +======= +>>>>>>> a9b223316b (Remove push notification stuff from sky-htmx) == == -- From 861dfadc4d3a8b3d16aebbcca4c9a5c5495cf5fa Mon Sep 17 00:00:00 2001 From: bonbud-macryg Date: Fri, 2 Aug 2024 16:02:21 +0100 Subject: [PATCH 39/46] Fix git conflicts --- pkg/arvo/neo/cod/std/src/con/sky-htmx.hoon | 99 ------------------- .../neo/cod/std/src/imp/notifications.hoon | 16 --- 2 files changed, 115 deletions(-) diff --git a/pkg/arvo/neo/cod/std/src/con/sky-htmx.hoon b/pkg/arvo/neo/cod/std/src/con/sky-htmx.hoon index dff2649663..950846cfcf 100644 --- a/pkg/arvo/neo/cod/std/src/con/sky-htmx.hoon +++ b/pkg/arvo/neo/cod/std/src/con/sky-htmx.hoon @@ -138,91 +138,9 @@ }); ''' == -<<<<<<< HEAD ;script: {(trip s-k-y)} ;script: {(trip feather-settings)} ;script: {(trip wi-nd)} -======= - ;script: {(trip a-i-r)} - ;script: {(trip date-now)} -<<<<<<< HEAD - :: - :: set up push notifications for this browser - ;script - ;+ ;/ %- trip - ''' - const push = require('../fil/web-push.js') - - addEventListener('load', async () => { - let sw = await navigator.serviceWorker.register('../fil/push-sw.js') - console.log(sw) - subscribeToNotifications() - }); - - async function subscribeToNotifications() { - let sw = await navigator.serviceWorker.ready - const vapidKeys = push.generateVAPIDKeys() - let pushSubscriptionDetails = await sw.pushManager.subscribe({ - userVisibleOnly: true, - applicationServerKey: `${vapidKeys.publicKey}` - }); - - sendSubscriptionToServer(pushSubscriptionDetails) - - // console.log(JSON.stringify(pushSubscriptionDetails)) - } - - function sendSubscriptionToServer(pushSubscriptionDetails) { - document.getElementById('push-subscription-details').value = - JSON.stringify(pushSubscriptionDetails) - document.getElementById('subscription-form').submit() - } - ''' - == -<<<<<<< HEAD ->>>>>>> 13d77f915b (Draft frontend code) -======= ->>>>>>> a9b223316b (Remove push notification stuff from sky-htmx) -======= - ;script: {(trip a-i-r)} - ;script: {(trip date-now)} -<<<<<<< HEAD - :: - :: set up push notifications for this browser - ;script - ;+ ;/ %- trip - ''' - const push = require('../fil/web-push.js') - - addEventListener('load', async () => { - let sw = await navigator.serviceWorker.register('../fil/push-sw.js') - console.log(sw) - subscribeToNotifications() - }); - - async function subscribeToNotifications() { - let sw = await navigator.serviceWorker.ready - const vapidKeys = push.generateVAPIDKeys() - let pushSubscriptionDetails = await sw.pushManager.subscribe({ - userVisibleOnly: true, - applicationServerKey: `${vapidKeys.publicKey}` - }); - - sendSubscriptionToServer(pushSubscriptionDetails) - - // console.log(JSON.stringify(pushSubscriptionDetails)) - } - - function sendSubscriptionToServer(pushSubscriptionDetails) { - document.getElementById('push-subscription-details').value = - JSON.stringify(pushSubscriptionDetails) - document.getElementById('subscription-form').submit() - } - ''' - == ->>>>>>> 13d77f915b (Draft frontend code) -======= ->>>>>>> a9b223316b (Remove push notification stuff from sky-htmx) ;+ favicon ;+ manifest == @@ -234,23 +152,6 @@ =hx-replace-url "/neo/sky" =our (scow %p our.bowl) ;+ in -<<<<<<< HEAD -======= - ;+ eye - ;+ menu-btn-style - ;+ theme-style -<<<<<<< HEAD -<<<<<<< HEAD -<<<<<<< HEAD - ;+ notifications-subscription ->>>>>>> 13d77f915b (Draft frontend code) -======= ->>>>>>> a9b223316b (Remove push notification stuff from sky-htmx) -======= - ;+ notifications-subscription ->>>>>>> 13d77f915b (Draft frontend code) -======= ->>>>>>> a9b223316b (Remove push notification stuff from sky-htmx) == == -- diff --git a/pkg/arvo/neo/cod/std/src/imp/notifications.hoon b/pkg/arvo/neo/cod/std/src/imp/notifications.hoon index 561bc01504..2ce92db22c 100644 --- a/pkg/arvo/neo/cod/std/src/imp/notifications.hoon +++ b/pkg/arvo/neo/cod/std/src/imp/notifications.hoon @@ -93,22 +93,6 @@ :: :: XX send push notifications to subscribers :: == :_ [%notifications-controller !>(state)] -<<<<<<< HEAD -======= - ?: (has-pith-in-any kill.config pith.not) - ~ - ?: (has-pith-in-any mute.config pith.not) - =. flag.not %.y - :~ :- (welp here.bowl ~[[da/now.bowl]]) - [%make %notification `[%notification !>(not)] ~] - == - ?: (has-pith-in-any buzz.config pith.not) - =. flag.not %.y - :~ :- (welp here.bowl ~[[da/now.bowl]]) - [%make %notification `[%notification !>(not)] ~] - :: XX send push notification - == ->>>>>>> 13d77f915b (Draft frontend code) ?. flag.not =. flag.not %.y :~ :- (welp here.bowl ~[[da/now.bowl]]) From 65a4413ef5f7c959614eae8c54b3a3fed5086c59 Mon Sep 17 00:00:00 2001 From: bonbud-macryg Date: Fri, 2 Aug 2024 16:38:46 +0100 Subject: [PATCH 40/46] Remove leftovers from git conflict --- pkg/arvo/neo/cod/std/src/imp/notifications.hoon | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/pkg/arvo/neo/cod/std/src/imp/notifications.hoon b/pkg/arvo/neo/cod/std/src/imp/notifications.hoon index 2ce92db22c..fcce86f79c 100644 --- a/pkg/arvo/neo/cod/std/src/imp/notifications.hoon +++ b/pkg/arvo/neo/cod/std/src/imp/notifications.hoon @@ -1,4 +1,3 @@ -/@ txt /@ notification /@ notifications-controller ^- kook:neo @@ -33,9 +32,7 @@ :~ :- [[%.y %notification] [%.n %da] %.n] [[%pro %notification] ~] :- [[%.y %config] [%.n %tas] %.n] - [[%pro %notifications-config] ~] - :- [[%.n %t] %.n] - [[%pro %txt] ~] + [[%pro %sig] ~] == :: ++ deps From b65cc4cdb02b44e571107d694ddaf8772a8b30b5 Mon Sep 17 00:00:00 2001 From: bonbud-macryg Date: Fri, 9 Aug 2024 16:22:50 +0100 Subject: [PATCH 41/46] Remove con/sky-htmx --- pkg/arvo/neo/cod/std/src/con/sky-htmx.hoon | 157 --------------------- 1 file changed, 157 deletions(-) delete mode 100644 pkg/arvo/neo/cod/std/src/con/sky-htmx.hoon diff --git a/pkg/arvo/neo/cod/std/src/con/sky-htmx.hoon b/pkg/arvo/neo/cod/std/src/con/sky-htmx.hoon deleted file mode 100644 index 950846cfcf..0000000000 --- a/pkg/arvo/neo/cod/std/src/con/sky-htmx.hoon +++ /dev/null @@ -1,157 +0,0 @@ -/@ sky -/@ sky-settings -/- sky-server -/* s-k-y -/* feather-settings -/* wi-nd -/* hawk-icon -:- [%sky %$ %htmx] -|= =sky -|= =bowl:neo -^- manx -|^ - =; m - %- lift - ?: menu.sky m - m(a.g [[%closed ""] a.g.m]) - ^- manx - ;s-k-y - =our (scow %p our.bowl) - =windows-open "{}" - ; - == -:: -++ map-to-css-tape - |= m=(map @t @t) - ^- tape - %- zing - %+ turn ~(tap by m) - |= [key=@t val=@t] - """ - --{(trip key)}: {(trip val)}; - """ -++ icon-url - ^~ - %- trip - %^ cat - 3 - 'data:image/png;base64,' - %- ~(en base64:mimes:html & |) - (as-octs:mimes:html hawk-icon) -++ favicon - ^~ - =; m m(a.g [[%href icon-url] a.g.m]) - ^- manx - ;link - =rel "icon" - =type "image/png" - ; - == -++ manifest-url - ^~ - %- trip - %^ cat - 3 - 'data:application/json;utf-8,' - %- en:json:html - %- pairs:enjs:format - :~ - ['name' s+'sky'] - ['description' s+'an urbit namespace viewer'] - ['start_url' s+'http://localhost/neo/sky'] :: XX - ['display' s+'standalone'] - ['background_color' s+'black'] - ['theme_color' s+'black'] - :+ 'icons' %a - :~ - %- pairs:enjs:format - :~ - ['src' s+(crip icon-url)] - ['sizes' s+'196x196'] - ['type' s+'image/png'] - == - == - == -++ manifest - ^~ - =; m m(a.g [[%href manifest-url] a.g.m]) - ^- manx - ;link - =rel "manifest" - ; - == -:: -++ lift - |= in=manx - ^- manx - ;html - ;head - ;meta(charset "UTF-8"); - ;title: s k y - ;* standard-head-tags.sky-server - ;meta - =name "htmx-config" - =content (trip '{"ignoreTitle":"true"}') - ; - == - ;script - ;+ ;/ %- trip - ''' - document.addEventListener('feather-changed', (e) => { - e.detail.forEach(r => { - document.documentElement.style - .setProperty('--'+r.variable, `${r.value}${r.unit||''}`); - }) - let windows = document.querySelectorAll('wi-nd'); - windows.forEach(w => { - $(w).poke('set-feather-values', e.detail) - }) - let rules = document.querySelector('s-k-y').currentFeatherRules; - localStorage.setItem('feather-settings', JSON.stringify(rules)); - }); - let rules = JSON.parse(localStorage.getItem('feather-settings') || '[]'); - rules.forEach(r => { - document.documentElement.style - .setProperty('--'+r.variable, `${r.value}${r.unit||''}`); - }) - window.addEventListener('resize', () => { - $('s-k-y').attr('open', null); - }); - window.addEventListener('message', function(event) { - if (event.data?.messagetype == 'sky-poll-response') { - let wid = event.data.wid; - let here = event.data.here; - let prefix = event.data.prefix; - let wind = document.querySelector(`[wid='${wid}']`); - if (wind) { - $(wind).poke('iframe-moved', {here, prefix}) - } - } - else if (event.data?.messagetype == 'iframe-wants-feather') { - let rules = document.querySelector('s-k-y').currentFeatherRules; - let wid = event.data.wid; - let wind = document.querySelector(`[wid='${wid}']`); - if (wind) { - $(wind).poke('set-feather-values', rules) - } - } - }); - ''' - == - ;script: {(trip s-k-y)} - ;script: {(trip feather-settings)} - ;script: {(trip wi-nd)} - ;+ favicon - ;+ manifest - == - ;body - =hx-ext "dom-enc,response-targets,morph" - =hx-swap "outerHTML" - =hx-boost "true" - =hx-history "false" - =hx-replace-url "/neo/sky" - =our (scow %p our.bowl) - ;+ in - == - == --- From bf5dbeb67c607e2f7cdd11225fe8374c04d638bf Mon Sep 17 00:00:00 2001 From: bonbud-macryg Date: Wed, 14 Aug 2024 12:15:36 +0100 Subject: [PATCH 42/46] Stub notification UI --- pkg/arvo/neo/cod/std/src/imp/mast-sky-ui.hoon | 78 +++++++++++++++++-- 1 file changed, 73 insertions(+), 5 deletions(-) diff --git a/pkg/arvo/neo/cod/std/src/imp/mast-sky-ui.hoon b/pkg/arvo/neo/cod/std/src/imp/mast-sky-ui.hoon index f59b8973e0..7097edb631 100644 --- a/pkg/arvo/neo/cod/std/src/imp/mast-sky-ui.hoon +++ b/pkg/arvo/neo/cod/std/src/imp/mast-sky-ui.hoon @@ -1,6 +1,7 @@ /@ ui-event /@ txt /@ order +/@ notification /- serv=sky-server ^- kook:neo =< @@ -335,11 +336,78 @@ == == ++ notifications - ;div.fc.g2(slot "notifications") - ;div.p3.br1.bd1: first - ;div.p3.br1.bd1: second - ;div.p3.br1.bd1: third - == + :: ;div.fc.g2(slot "notifications") + :: ;div.p3.br1.bd1: first + :: ;div.p3.br1.bd1: second + :: ;div.p3.br1.bd1: third + :: == + (nots-to-manx nots) + :: + ++ flagged-not + :* flag=%.y + time=~2000.1.1 + src=#/[p/~bud]/home/messages/dms/[p/~fun] + dst=#/[p/~bud]/home/messages/dms/[p/~fun] + cord='Unread notification.' + == + :: + ++ unflagged-not + :* flag=%.n + time=~1969.12.31 + src=#/[p/~bud]/home/messages/dms/[p/~fun] + dst=#/[p/~bud]/home/messages/dms/[p/~fun] + cord='Read notification.' + == + :: + ++ nots + :~ flagged-not + flagged-not + unflagged-not + == + :: + ++ not-to-manx + |= not=notification + ^- manx + ;div.bd1.br2.p0.tl.ma.mt1 + ;div.fr.g1.p0.wf + ;div.p0(style "width: 30%") + ;img@"https://ewr1.vultrobjects.com/urbit/hastuc-dibtux/2024.4.30..2.37.9..bae1.47ae.147a.e147-IMG_5592.jpeg"(style "margin: 0px; object-fit: cover; border-radius: 6px;"); + == + ;div.p1(style "width: 70%") + ;div.fr.jb + ;div.s-1 + =title "{<(format-src src.not)>}" + ; ship/desk + == + ;div.s-1 + ; {} + == + == + ; {(trip cord.not)} + == + == + == + :: + ++ nots-to-manx + |= nots=(list notification) + ^- manx + ;div(slot "notifications") + ;* + %+ turn + nots + |= not=notification + ^- manx + (not-to-manx not) + == + ++ format-src + |= =pith + ^- path + ?. =(%p (head (head pith))) + (pout pith) + (pout (tail pith)) + :: + :: XX format time.not + :: ++ lift |= in=manx ^- manx From 362ece9bd4c70c455e5a2c8e58e543ce6188f546 Mon Sep 17 00:00:00 2001 From: bonbud-macryg Date: Thu, 15 Aug 2024 15:46:25 +0100 Subject: [PATCH 43/46] Comment out notifications in messenger --- pkg/arvo/neo/cod/std/src/imp/message.hoon | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/pkg/arvo/neo/cod/std/src/imp/message.hoon b/pkg/arvo/neo/cod/std/src/imp/message.hoon index e097be6ea2..da032a9b67 100644 --- a/pkg/arvo/neo/cod/std/src/imp/message.hoon +++ b/pkg/arvo/neo/cod/std/src/imp/message.hoon @@ -18,11 +18,12 @@ =/ new-message !<(message q:(need old)) :_ [%message !>(new-message)] - ?: =(our.bowl from.new-message) - ~ - :~ :- #/[p/our.bowl]/home/notifications - [%poke [%notification !>([%.y now.bowl here.bowl here.bowl contents.new-message])]] - == + ~ + :: ?: =(our.bowl from.new-message) + :: ~ + :: :~ :- #/[p/our.bowl]/notifications + :: [%poke [%notification !>([%.y now.bowl here.bowl here.bowl contents.new-message])]] + :: == ++ poke |= [=stud:neo vaz=vase] ^- (quip card:neo pail:neo) From 9717e8d0493c702e53849ed80032a60293c006de Mon Sep 17 00:00:00 2001 From: bonbud-macryg Date: Mon, 19 Aug 2024 14:54:19 +0100 Subject: [PATCH 44/46] Build dependency on /notifications in sky --- pkg/arvo/app/neo.hoon | 4 +++- pkg/arvo/neo/cod/std/src/imp/sky.hoon | 14 +++++++++++++- 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/pkg/arvo/app/neo.hoon b/pkg/arvo/app/neo.hoon index 0629d5f5da..83bb0ac87e 100644 --- a/pkg/arvo/app/neo.hoon +++ b/pkg/arvo/app/neo.hoon @@ -1560,7 +1560,9 @@ =. run (emit (do-card #/[p/our.bowl] %make %root ~ ~)) =. run - (emit (do-card #/[p/our.bowl]/sky %make %sky ~ ~)) + (emit (do-card #/[p/our.bowl]/notifications %make %notifications ~ ~)) + =. run + (emit (do-card #/[p/our.bowl]/sky %make %sky ~ (~(gas by *crew:neo) not/#/[p/our.bowl]/notifications ~))) =. run (emit (do-card #/[p/our.bowl]/srv/hawk %make %hawk-eyre ~ ~)) =. run diff --git a/pkg/arvo/neo/cod/std/src/imp/sky.hoon b/pkg/arvo/neo/cod/std/src/imp/sky.hoon index 7737aca0d8..6f6cd39472 100644 --- a/pkg/arvo/neo/cod/std/src/imp/sky.hoon +++ b/pkg/arvo/neo/cod/std/src/imp/sky.hoon @@ -1,3 +1,6 @@ +/@ flag +/@ notification +/@ notifications-controller /- serv=sky-server /* feather /* s-k-y @@ -10,7 +13,16 @@ ++ kids :+ ~ %z schema.serv -++ deps *deps:neo +++ deps + %- ~(gas by *deps:neo) + :~ :- %not + :+ req=| [pro/%notifications-controller (sy %notification %notifications-controller ~)] + :+ ~ %z + %- ~(gas by *lads:neo) + :~ :- [&/%notification |/%da |] + [pro/%notification (sy %flag ~)] + == + == ++ form ^- form:neo |_ [=bowl:neo =aeon:neo =pail:neo] From 696873146597da4beb64c3f2c1f8cb0e15981e61 Mon Sep 17 00:00:00 2001 From: bonbud-macryg Date: Mon, 19 Aug 2024 14:55:48 +0100 Subject: [PATCH 45/46] Remove %txt poke from notifications --- pkg/arvo/neo/cod/std/src/imp/notifications.hoon | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pkg/arvo/neo/cod/std/src/imp/notifications.hoon b/pkg/arvo/neo/cod/std/src/imp/notifications.hoon index fcce86f79c..3d64819258 100644 --- a/pkg/arvo/neo/cod/std/src/imp/notifications.hoon +++ b/pkg/arvo/neo/cod/std/src/imp/notifications.hoon @@ -22,7 +22,7 @@ :: ++ poke ^- (set stud:neo) - (sy %txt %notification ~) + (sy %notification ~) :: ++ kids ^- kids:neo From d89a453a327aa6032a2492a8adb330cceda14f33 Mon Sep 17 00:00:00 2001 From: bonbud-macryg Date: Thu, 22 Aug 2024 18:34:04 +0100 Subject: [PATCH 46/46] wip: rely on /notifications --- pkg/arvo/neo/cod/std/src/imp/notifications.hoon | 2 +- pkg/arvo/neo/cod/std/src/imp/sky.hoon | 17 ++++++++++++++++- pkg/arvo/neo/cod/std/src/lib/sky-server.hoon | 3 +++ 3 files changed, 20 insertions(+), 2 deletions(-) diff --git a/pkg/arvo/neo/cod/std/src/imp/notifications.hoon b/pkg/arvo/neo/cod/std/src/imp/notifications.hoon index 3d64819258..7d3be3238b 100644 --- a/pkg/arvo/neo/cod/std/src/imp/notifications.hoon +++ b/pkg/arvo/neo/cod/std/src/imp/notifications.hoon @@ -27,7 +27,7 @@ ++ kids ^- kids:neo %- some - :- %y + :- %z %- ~(gas by *lads:neo) :~ :- [[%.y %notification] [%.n %da] %.n] [[%pro %notification] ~] diff --git a/pkg/arvo/neo/cod/std/src/imp/sky.hoon b/pkg/arvo/neo/cod/std/src/imp/sky.hoon index 6f6cd39472..035932e0b9 100644 --- a/pkg/arvo/neo/cod/std/src/imp/sky.hoon +++ b/pkg/arvo/neo/cod/std/src/imp/sky.hoon @@ -9,7 +9,7 @@ =< |% ++ state pro/%sig -++ poke (sy %gift %bind-static-assets ~) +++ poke (sy %gift %rely %bind-static-assets ~) ++ kids :+ ~ %z schema.serv @@ -32,6 +32,21 @@ ?+ stud ~|(bad-stud/stud !!) %gift [~ sig/!>(~)] + :: + %rely + :_ sig/!>(~) + %+ murn + ~(tap by ~(tar of:neo q:(~(got by deps.bowl) %not))) + |= [=pith:neo =idea:neo] + ^- (unit card:neo) + ?. =(%notification p.pail.idea) + ~ + =/ not !<(notification q.pail.idea) + ~& >> not + ~ + :: %- some + :: :- (welp here.bowl #/notification/[da/time.not]) + :: [%make %notification `pail.idea ~] :: %bind-static-assets :_ sig/!>(~) diff --git a/pkg/arvo/neo/cod/std/src/lib/sky-server.hoon b/pkg/arvo/neo/cod/std/src/lib/sky-server.hoon index 86246bf18d..79a4e1344c 100644 --- a/pkg/arvo/neo/cod/std/src/lib/sky-server.hoon +++ b/pkg/arvo/neo/cod/std/src/lib/sky-server.hoon @@ -35,6 +35,9 @@ :: /strategy/~zod/... = (list pith) :- [&/%strategy &] [pro/%order (sy %order ~)] :: + :: /notification/~2024.8.19..14.47.48..9228 = notification + :- [&/%notification |/%da |] [pro/%notification (sy %flag ~)] + :: == :: :: backend