@proteinjs/user-server 1.22.0 → 1.22.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (133) hide show
  1. package/CHANGELOG.md +24 -0
  2. package/dist/generated/index.js +1 -1
  3. package/dist/generated/index.js.map +1 -1
  4. package/dist/index.d.ts +3 -0
  5. package/dist/index.d.ts.map +1 -1
  6. package/dist/index.js +10 -2
  7. package/dist/index.js.map +1 -1
  8. package/dist/src/authentication/PasswordHasher.d.ts +9 -0
  9. package/dist/src/authentication/PasswordHasher.d.ts.map +1 -1
  10. package/dist/src/authentication/PasswordHasher.js +25 -0
  11. package/dist/src/authentication/PasswordHasher.js.map +1 -1
  12. package/dist/src/authentication/PasswordResetToken.d.ts +43 -12
  13. package/dist/src/authentication/PasswordResetToken.d.ts.map +1 -1
  14. package/dist/src/authentication/PasswordResetToken.js +86 -21
  15. package/dist/src/authentication/PasswordResetToken.js.map +1 -1
  16. package/dist/src/authentication/authenticate.d.ts +15 -0
  17. package/dist/src/authentication/authenticate.d.ts.map +1 -1
  18. package/dist/src/authentication/authenticate.js +55 -20
  19. package/dist/src/authentication/authenticate.js.map +1 -1
  20. package/dist/src/routes/devLogin.d.ts +1 -1
  21. package/dist/src/routes/devLogin.js +1 -1
  22. package/dist/src/routes/executePasswordReset.d.ts +6 -1
  23. package/dist/src/routes/executePasswordReset.d.ts.map +1 -1
  24. package/dist/src/routes/executePasswordReset.js +16 -7
  25. package/dist/src/routes/executePasswordReset.js.map +1 -1
  26. package/dist/src/routes/initiatePasswordReset.d.ts +10 -2
  27. package/dist/src/routes/initiatePasswordReset.d.ts.map +1 -1
  28. package/dist/src/routes/initiatePasswordReset.js +55 -34
  29. package/dist/src/routes/initiatePasswordReset.js.map +1 -1
  30. package/dist/src/routes/login.d.ts +8 -0
  31. package/dist/src/routes/login.d.ts.map +1 -1
  32. package/dist/src/routes/login.js +63 -22
  33. package/dist/src/routes/login.js.map +1 -1
  34. package/dist/src/throttle/ClientAddress.d.ts +35 -0
  35. package/dist/src/throttle/ClientAddress.d.ts.map +1 -0
  36. package/dist/src/throttle/ClientAddress.js +48 -0
  37. package/dist/src/throttle/ClientAddress.js.map +1 -0
  38. package/dist/src/throttle/PasswordResetThrottle.d.ts +39 -0
  39. package/dist/src/throttle/PasswordResetThrottle.d.ts.map +1 -0
  40. package/dist/src/throttle/PasswordResetThrottle.js +59 -0
  41. package/dist/src/throttle/PasswordResetThrottle.js.map +1 -0
  42. package/dist/src/throttle/RequestDigests.d.ts +42 -0
  43. package/dist/src/throttle/RequestDigests.d.ts.map +1 -0
  44. package/dist/src/throttle/RequestDigests.js +96 -0
  45. package/dist/src/throttle/RequestDigests.js.map +1 -0
  46. package/dist/src/throttle/SignInThrottle.d.ts +67 -0
  47. package/dist/src/throttle/SignInThrottle.d.ts.map +1 -0
  48. package/dist/src/throttle/SignInThrottle.js +91 -0
  49. package/dist/src/throttle/SignInThrottle.js.map +1 -0
  50. package/dist/src/throttle/SlidingWindow.d.ts +51 -0
  51. package/dist/src/throttle/SlidingWindow.d.ts.map +1 -0
  52. package/dist/src/throttle/SlidingWindow.js +85 -0
  53. package/dist/src/throttle/SlidingWindow.js.map +1 -0
  54. package/dist/test/ClientAddress.test.d.ts +2 -0
  55. package/dist/test/ClientAddress.test.d.ts.map +1 -0
  56. package/dist/test/ClientAddress.test.js +51 -0
  57. package/dist/test/ClientAddress.test.js.map +1 -0
  58. package/dist/test/DbTraffic.d.ts +29 -0
  59. package/dist/test/DbTraffic.d.ts.map +1 -0
  60. package/dist/test/DbTraffic.js +106 -0
  61. package/dist/test/DbTraffic.js.map +1 -0
  62. package/dist/test/DevLoginBootstrapAdmin.test.js +3 -4
  63. package/dist/test/DevLoginBootstrapAdmin.test.js.map +1 -1
  64. package/dist/test/DevLoginStaleCookieFirstHit.test.js +1 -1
  65. package/dist/test/DevLoginStaleCookieFirstHit.test.js.map +1 -1
  66. package/dist/test/ExecutePasswordReset.test.js +513 -124
  67. package/dist/test/ExecutePasswordReset.test.js.map +1 -1
  68. package/dist/test/InitiatePasswordReset.test.d.ts +2 -0
  69. package/dist/test/InitiatePasswordReset.test.d.ts.map +1 -0
  70. package/dist/test/InitiatePasswordReset.test.js +783 -0
  71. package/dist/test/InitiatePasswordReset.test.js.map +1 -0
  72. package/dist/test/LogCapture.d.ts +22 -0
  73. package/dist/test/LogCapture.d.ts.map +1 -0
  74. package/dist/test/LogCapture.js +127 -0
  75. package/dist/test/LogCapture.js.map +1 -0
  76. package/dist/test/LoginThrottle.integration.test.d.ts +2 -0
  77. package/dist/test/LoginThrottle.integration.test.d.ts.map +1 -0
  78. package/dist/test/LoginThrottle.integration.test.js +616 -0
  79. package/dist/test/LoginThrottle.integration.test.js.map +1 -0
  80. package/dist/test/MalformedResetTokens.d.ts +11 -0
  81. package/dist/test/MalformedResetTokens.d.ts.map +1 -0
  82. package/dist/test/MalformedResetTokens.js +35 -0
  83. package/dist/test/MalformedResetTokens.js.map +1 -0
  84. package/dist/test/RequestDigests.test.d.ts +2 -0
  85. package/dist/test/RequestDigests.test.d.ts.map +1 -0
  86. package/dist/test/RequestDigests.test.js +73 -0
  87. package/dist/test/RequestDigests.test.js.map +1 -0
  88. package/dist/test/SlidingWindow.test.d.ts +2 -0
  89. package/dist/test/SlidingWindow.test.d.ts.map +1 -0
  90. package/dist/test/SlidingWindow.test.js +72 -0
  91. package/dist/test/SlidingWindow.test.js.map +1 -0
  92. package/dist/test/ValidateResetToken.test.js +156 -33
  93. package/dist/test/ValidateResetToken.test.js.map +1 -1
  94. package/dist/test/emulatorLock.test.d.ts +2 -0
  95. package/dist/test/emulatorLock.test.d.ts.map +1 -0
  96. package/dist/test/emulatorLock.test.js +32 -0
  97. package/dist/test/emulatorLock.test.js.map +1 -0
  98. package/dist/test/emulatorLockName.test.d.ts +2 -0
  99. package/dist/test/emulatorLockName.test.d.ts.map +1 -0
  100. package/dist/test/emulatorLockName.test.js +36 -0
  101. package/dist/test/emulatorLockName.test.js.map +1 -0
  102. package/generated/index.ts +1 -1
  103. package/index.ts +6 -1
  104. package/jest.config.js +2 -2
  105. package/package.json +3 -3
  106. package/src/authentication/PasswordHasher.ts +18 -1
  107. package/src/authentication/PasswordResetToken.ts +74 -20
  108. package/src/authentication/authenticate.ts +36 -9
  109. package/src/routes/devLogin.ts +1 -1
  110. package/src/routes/executePasswordReset.ts +10 -2
  111. package/src/routes/initiatePasswordReset.ts +46 -25
  112. package/src/routes/login.ts +39 -8
  113. package/src/throttle/ClientAddress.ts +47 -0
  114. package/src/throttle/PasswordResetThrottle.ts +62 -0
  115. package/src/throttle/RequestDigests.ts +97 -0
  116. package/src/throttle/SignInThrottle.ts +98 -0
  117. package/src/throttle/SlidingWindow.ts +90 -0
  118. package/test/ClientAddress.test.ts +54 -0
  119. package/test/DbTraffic.ts +43 -0
  120. package/test/DevLoginBootstrapAdmin.test.ts +3 -4
  121. package/test/DevLoginStaleCookieFirstHit.test.ts +1 -1
  122. package/test/ExecutePasswordReset.test.ts +308 -70
  123. package/test/InitiatePasswordReset.test.ts +456 -0
  124. package/test/LogCapture.ts +54 -0
  125. package/test/LoginThrottle.integration.test.ts +339 -0
  126. package/test/MalformedResetTokens.ts +27 -0
  127. package/test/RequestDigests.test.ts +81 -0
  128. package/test/SlidingWindow.test.ts +85 -0
  129. package/test/ValidateResetToken.test.ts +108 -24
  130. package/test/emulatorLock.js +5 -6
  131. package/test/emulatorLock.test.ts +32 -0
  132. package/test/emulatorLockName.test.ts +33 -0
  133. package/test/setup.js +2 -0
@@ -0,0 +1,96 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.RequestDigests = void 0;
4
+ var crypto_1 = require("crypto");
5
+ /**
6
+ * The two keyed digests the throttled doors key their windows on and write on their log lines,
7
+ * in place of what they stand for:
8
+ * - `account(email)` — the ACCOUNT DIGEST: a keyed hash of the trimmed, lowercased address.
9
+ * One address gives one digest however it was typed, on every replica and across restarts, so
10
+ * an operator can say "one account" across lines without the address.
11
+ * - `coarseIp(address)` — the COARSE IP HASH: a keyed hash of the client address at the grain
12
+ * one device holds (an IPv4 address; an IPv6 /64, inside which a device rotates freely), so
13
+ * an operator can say "one device" and a throttle cannot be dodged by rotating inside a /64.
14
+ *
15
+ * Keyed with HMAC-SHA256 under a key DERIVED from the session secret — the one secret every
16
+ * replica already shares, the same keying the invite-request door's IP hash uses; derived per
17
+ * purpose, never used raw, so neither digest weakens the session's own use of it, and the two
18
+ * digests never collide in meaning. Truncated to 64 bits: enough to tell accounts and devices
19
+ * apart, useless to anyone without the key — never the address, never a plain hash a list of
20
+ * addresses could reverse.
21
+ *
22
+ * The key is the deployment's `SESSION_SECRET` unless the constructor is given one (the tests).
23
+ * Without either the digests refuse to run: a server with no `SESSION_SECRET` has no sessions
24
+ * either (the session middleware refuses to start), so nothing ever runs unkeyed — never a plain
25
+ * hash a list of addresses could reverse, never a per-process key that quietly stops matching
26
+ * across replicas.
27
+ */
28
+ var RequestDigests = /** @class */ (function () {
29
+ function RequestDigests(options) {
30
+ this.options = options;
31
+ }
32
+ /** The account digest of an address, however it was typed. */
33
+ RequestDigests.prototype.account = function (email) {
34
+ return this.digest('account-digest', email.trim().toLowerCase());
35
+ };
36
+ /** The coarse IP hash of a client address (see `ClientAddress`). */
37
+ RequestDigests.prototype.coarseIp = function (address) {
38
+ return this.digest('coarse-ip', this.coarsen(address.trim().toLowerCase()));
39
+ };
40
+ RequestDigests.prototype.digest = function (purpose, value) {
41
+ return (0, crypto_1.createHmac)('sha256', "".concat(purpose, ":").concat(this.secret()))
42
+ .update(value)
43
+ .digest('hex')
44
+ .slice(0, RequestDigests.DIGEST_HEX_LENGTH);
45
+ };
46
+ RequestDigests.prototype.secret = function () {
47
+ var _a, _b;
48
+ var configured = (_b = (_a = this.options) === null || _a === void 0 ? void 0 : _a.secret) !== null && _b !== void 0 ? _b : process.env.SESSION_SECRET;
49
+ if (!configured) {
50
+ throw new Error('SESSION_SECRET is not set: the account digest and the coarse IP hash need the key every replica shares');
51
+ }
52
+ return configured;
53
+ };
54
+ /** An IPv4 address as itself (an IPv4-mapped IPv6 address as its IPv4); an IPv6 address as its /64. */
55
+ RequestDigests.prototype.coarsen = function (address) {
56
+ var mapped = /^::ffff:(\d{1,3}(?:\.\d{1,3}){3})$/.exec(address);
57
+ if (mapped) {
58
+ return mapped[1];
59
+ }
60
+ if (!address.includes(':')) {
61
+ return address;
62
+ }
63
+ var groups = this.ipv6Groups(address.split('%')[0]);
64
+ return groups ? "".concat(groups.slice(0, 4).join(':'), "::/64") : address;
65
+ };
66
+ /** The first four groups (the /64) of an IPv6 address, each without leading zeros; undefined when it does not parse. */
67
+ RequestDigests.prototype.ipv6Groups = function (address) {
68
+ var halves = address.split('::');
69
+ if (halves.length > 2) {
70
+ return undefined;
71
+ }
72
+ var parts = function (half) { return (half ? half.split(':') : []); };
73
+ var head = parts(halves[0]);
74
+ var tail = parts(halves[1]);
75
+ // A trailing dotted IPv4 part stands for two groups.
76
+ var groupsIn = function (list) { return list.reduce(function (count, part) { return count + (part.includes('.') ? 2 : 1); }, 0); };
77
+ var missing = 8 - groupsIn(head) - groupsIn(tail);
78
+ if (missing < 0 || (halves.length === 1 && missing !== 0)) {
79
+ return undefined;
80
+ }
81
+ var zeros = [];
82
+ for (var i = 0; i < missing; i++) {
83
+ zeros.push('0');
84
+ }
85
+ var groups = head.concat(zeros, tail).slice(0, 4);
86
+ if (groups.some(function (group) { return !/^[0-9a-f]{1,4}$/.test(group); })) {
87
+ return undefined;
88
+ }
89
+ return groups.map(function (group) { return parseInt(group, 16).toString(16); });
90
+ };
91
+ /** Hex characters kept from the HMAC: 64 bits. */
92
+ RequestDigests.DIGEST_HEX_LENGTH = 16;
93
+ return RequestDigests;
94
+ }());
95
+ exports.RequestDigests = RequestDigests;
96
+ //# sourceMappingURL=RequestDigests.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"RequestDigests.js","sourceRoot":"","sources":["../../../src/throttle/RequestDigests.ts"],"names":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C;QACpD,IAAI,OAAO,GAAG,CAAC,IAAI,CAAC,MAAM,CAAC,MAAM,KAAK,CAAC,IAAI,OAAO,KAAK,CAAC,CAAC,EAAE;YACzD,OAAO,SAAS,CAAC;SAClB;QACD,IAAM,KAAK,GAAa,EAAE,CAAC;QAC3B,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,OAAO,EAAE,CAAC,EAAE,EAAE;YAChC,KAAK,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;SACjB;QACD,IAAM,MAAM,GAAG,IAAI,CAAC,MAAM,CAAC,KAAK,EAAE,IAAI,CAAC,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC;QACpD,IAAI,MAAM,CAAC,IAAI,CAAC,UAAC,KAAK,IAAK,OAAA,CAAC,iBAAiB,CAAC,IAAI,CAAC,KAAK,CAAC,EAA9B,CAA8B,CAAC,EAAE;YAC1D,OAAO,SAAS,CAAC;SAClB;QACD,OAAO,MAAM,CAAC,GAAG,CAAC,UAAC,KAAK,IAAK,OAAA,QAAQ,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC,QAAQ,CAAC,EAAE,CAAC,EAAhC,CAAgC,CAAC,CAAC;IACjE,CAAC;IArED,kDAAkD;IAC1B,gCAAiB,GAAG,EAAE,CAAC;IAqEjD,qBAAC;CAAA,AAvED,IAuEC;AAvEY,wCAAc"}
@@ -0,0 +1,67 @@
1
+ /** Which window refused a try: the client's (its coarse IP hash) or the account's (its digest). */
2
+ export type ThrottleWindow = 'client' | 'account';
3
+ /**
4
+ * The sign-in door's two windows (`POST /user/login`), keyed by digests (`RequestDigests`),
5
+ * never by an address:
6
+ * - per CLIENT: every try that is not a success counts — wrong passwords, blank ones too, the
7
+ * client made them — so one device cannot sweep many accounts; a successful sign-in never
8
+ * counts (it is forgiven the moment it succeeds), so the people behind one shared address
9
+ * signing in do not spend the window on each other;
10
+ * - per ACCOUNT: every try that carries a password counts (a blank submission judges no
11
+ * password, so it never counts), so guesses spread over many devices still stop; a success
12
+ * clears the account's count. A try is counted as it ARRIVES, before it is judged: tries in
13
+ * flight at the same moment cannot all pass the window together.
14
+ *
15
+ * A throttled try is told `ANSWER` whichever window refused it and whether or not the address
16
+ * has an account, in the same time a refused password takes (the door runs the same password
17
+ * check and discards its verdict).
18
+ *
19
+ * The windows are in process memory (`SlidingWindow`): per replica. A deployment of three
20
+ * replicas behind a load balancer (up to ten under load) keeps three sets of windows, so its
21
+ * effective ceiling is ~3× the numbers below (up to ~10×). Friction, not the wall — a shared
22
+ * store is a separate step.
23
+ */
24
+ export declare class SignInThrottle {
25
+ /** What a throttled try is told — in plain words, the same for every address, known or not. */
26
+ static readonly ANSWER = "Too many attempts. Try again in a few minutes.";
27
+ /**
28
+ * Per client: 50 tries that are not successes in 10 minutes (the founder's number, 2026-09-23).
29
+ * Successes never count, so an office or a school behind one address signing in at nine o'clock
30
+ * never spends this window on itself — only its mistypes do, and fifty wrong or blank tries in
31
+ * ten minutes is beyond any human population behind one address; a guessing script from one
32
+ * device is held to ~300 tries an hour per replica.
33
+ */
34
+ private static readonly CLIENT_LIMIT;
35
+ private static readonly CLIENT_WINDOW_MS;
36
+ /**
37
+ * Per account: 10 tries in 15 minutes (a success clears them, so only wrong ones ever add up).
38
+ * Someone who has forgotten a password tries a handful and asks for a reset link; ten wrong in
39
+ * a quarter of an hour is guessing, and counting per account holds however many devices the
40
+ * guesses come from. "A few minutes" in the answer is honest: the oldest try leaves the window
41
+ * within 15.
42
+ */
43
+ private static readonly ACCOUNT_LIMIT;
44
+ private static readonly ACCOUNT_WINDOW_MS;
45
+ private readonly clients;
46
+ private readonly accounts;
47
+ constructor(options?: {
48
+ now?: () => number;
49
+ });
50
+ /**
51
+ * Count this try against the client and against the account, and answer which window refuses
52
+ * it, if any. `account` is the digest of the address tried, given only when a password came
53
+ * with it (a blank submission judges no password, so it never counts toward an account). The
54
+ * count is taken here, before the try is judged, so tries in flight at once cannot all pass
55
+ * the window; a success clears it (`recordSuccess`).
56
+ */
57
+ admit(client: string, account?: string): ThrottleWindow | undefined;
58
+ /**
59
+ * The account proved itself: its window opens again. When it was a sign-in try from `client`
60
+ * (rather than a reset link redeemed), that try is forgiven — a success never counts against
61
+ * the device.
62
+ */
63
+ recordSuccess(account: string, client?: string): void;
64
+ }
65
+ /** The process-wide windows the sign-in door shares — they must span requests. */
66
+ export declare const signInThrottle: SignInThrottle;
67
+ //# sourceMappingURL=SignInThrottle.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"SignInThrottle.d.ts","sourceRoot":"","sources":["../../../src/throttle/SignInThrottle.ts"],"names":[],"mappings":"AAEA,mGAAmG;AACnG,MAAM,MAAM,cAAc,GAAG,QAAQ,GAAG,SAAS,CAAC;AAElD;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,qBAAa,cAAc;IACzB,+FAA+F;IAC/F,MAAM,CAAC,QAAQ,CAAC,MAAM,oDAAoD;IAE1E;;;;;;OAMG;IACH,OAAO,CAAC,MAAM,CAAC,QAAQ,CAAC,YAAY,CAAM;IAC1C,OAAO,CAAC,MAAM,CAAC,QAAQ,CAAC,gBAAgB,CAAkB;IAE1D;;;;;;OAMG;IACH,OAAO,CAAC,MAAM,CAAC,QAAQ,CAAC,aAAa,CAAM;IAC3C,OAAO,CAAC,MAAM,CAAC,QAAQ,CAAC,iBAAiB,CAAkB;IAE3D,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAgB;IACxC,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAgB;gBAE7B,OAAO,CAAC,EAAE;QAAE,GAAG,CAAC,EAAE,MAAM,MAAM,CAAA;KAAE;IAa5C;;;;;;OAMG;IACH,KAAK,CAAC,MAAM,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,MAAM,GAAG,cAAc,GAAG,SAAS;IAUnE;;;;OAIG;IACH,aAAa,CAAC,OAAO,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,MAAM,GAAG,IAAI;CAMtD;AAED,kFAAkF;AAClF,eAAO,MAAM,cAAc,gBAAuB,CAAC"}
@@ -0,0 +1,91 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.signInThrottle = exports.SignInThrottle = void 0;
4
+ var SlidingWindow_1 = require("./SlidingWindow");
5
+ /**
6
+ * The sign-in door's two windows (`POST /user/login`), keyed by digests (`RequestDigests`),
7
+ * never by an address:
8
+ * - per CLIENT: every try that is not a success counts — wrong passwords, blank ones too, the
9
+ * client made them — so one device cannot sweep many accounts; a successful sign-in never
10
+ * counts (it is forgiven the moment it succeeds), so the people behind one shared address
11
+ * signing in do not spend the window on each other;
12
+ * - per ACCOUNT: every try that carries a password counts (a blank submission judges no
13
+ * password, so it never counts), so guesses spread over many devices still stop; a success
14
+ * clears the account's count. A try is counted as it ARRIVES, before it is judged: tries in
15
+ * flight at the same moment cannot all pass the window together.
16
+ *
17
+ * A throttled try is told `ANSWER` whichever window refused it and whether or not the address
18
+ * has an account, in the same time a refused password takes (the door runs the same password
19
+ * check and discards its verdict).
20
+ *
21
+ * The windows are in process memory (`SlidingWindow`): per replica. A deployment of three
22
+ * replicas behind a load balancer (up to ten under load) keeps three sets of windows, so its
23
+ * effective ceiling is ~3× the numbers below (up to ~10×). Friction, not the wall — a shared
24
+ * store is a separate step.
25
+ */
26
+ var SignInThrottle = /** @class */ (function () {
27
+ function SignInThrottle(options) {
28
+ this.clients = new SlidingWindow_1.SlidingWindow({
29
+ windowMs: SignInThrottle.CLIENT_WINDOW_MS,
30
+ limit: SignInThrottle.CLIENT_LIMIT,
31
+ now: options === null || options === void 0 ? void 0 : options.now,
32
+ });
33
+ this.accounts = new SlidingWindow_1.SlidingWindow({
34
+ windowMs: SignInThrottle.ACCOUNT_WINDOW_MS,
35
+ limit: SignInThrottle.ACCOUNT_LIMIT,
36
+ now: options === null || options === void 0 ? void 0 : options.now,
37
+ });
38
+ }
39
+ /**
40
+ * Count this try against the client and against the account, and answer which window refuses
41
+ * it, if any. `account` is the digest of the address tried, given only when a password came
42
+ * with it (a blank submission judges no password, so it never counts toward an account). The
43
+ * count is taken here, before the try is judged, so tries in flight at once cannot all pass
44
+ * the window; a success clears it (`recordSuccess`).
45
+ */
46
+ SignInThrottle.prototype.admit = function (client, account) {
47
+ if (this.clients.hit(client)) {
48
+ return 'client';
49
+ }
50
+ if (account !== undefined && this.accounts.hit(account)) {
51
+ return 'account';
52
+ }
53
+ return undefined;
54
+ };
55
+ /**
56
+ * The account proved itself: its window opens again. When it was a sign-in try from `client`
57
+ * (rather than a reset link redeemed), that try is forgiven — a success never counts against
58
+ * the device.
59
+ */
60
+ SignInThrottle.prototype.recordSuccess = function (account, client) {
61
+ this.accounts.clear(account);
62
+ if (client !== undefined) {
63
+ this.clients.forgive(client);
64
+ }
65
+ };
66
+ /** What a throttled try is told — in plain words, the same for every address, known or not. */
67
+ SignInThrottle.ANSWER = 'Too many attempts. Try again in a few minutes.';
68
+ /**
69
+ * Per client: 50 tries that are not successes in 10 minutes (the founder's number, 2026-09-23).
70
+ * Successes never count, so an office or a school behind one address signing in at nine o'clock
71
+ * never spends this window on itself — only its mistypes do, and fifty wrong or blank tries in
72
+ * ten minutes is beyond any human population behind one address; a guessing script from one
73
+ * device is held to ~300 tries an hour per replica.
74
+ */
75
+ SignInThrottle.CLIENT_LIMIT = 50;
76
+ SignInThrottle.CLIENT_WINDOW_MS = 10 * 60 * 1000;
77
+ /**
78
+ * Per account: 10 tries in 15 minutes (a success clears them, so only wrong ones ever add up).
79
+ * Someone who has forgotten a password tries a handful and asks for a reset link; ten wrong in
80
+ * a quarter of an hour is guessing, and counting per account holds however many devices the
81
+ * guesses come from. "A few minutes" in the answer is honest: the oldest try leaves the window
82
+ * within 15.
83
+ */
84
+ SignInThrottle.ACCOUNT_LIMIT = 10;
85
+ SignInThrottle.ACCOUNT_WINDOW_MS = 15 * 60 * 1000;
86
+ return SignInThrottle;
87
+ }());
88
+ exports.SignInThrottle = SignInThrottle;
89
+ /** The process-wide windows the sign-in door shares — they must span requests. */
90
+ exports.signInThrottle = new SignInThrottle();
91
+ //# sourceMappingURL=SignInThrottle.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"SignInThrottle.js","sourceRoot":"","sources":["../../../src/throttle/SignInThrottle.ts"],"names":[],"mappings":";;;AAAA,iDAAgD;AAKhD;;;;;;;;;;;;;;;;;;;;GAoBG;AACH;IA2BE,wBAAY,OAAgC;QAC1C,IAAI,CAAC,OAAO,GAAG,IAAI,6BAAa,CAAC;YAC/B,QAAQ,EAAE,cAAc,CAAC,gBAAgB;YACzC,KAAK,EAAE,cAAc,CAAC,YAAY;YAClC,GAAG,EAAE,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,GAAG;SAClB,CAAC,CAAC;QACH,IAAI,CAAC,QAAQ,GAAG,IAAI,6BAAa,CAAC;YAChC,QAAQ,EAAE,cAAc,CAAC,iBAAiB;YAC1C,KAAK,EAAE,cAAc,CAAC,aAAa;YACnC,GAAG,EAAE,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,GAAG;SAClB,CAAC,CAAC;IACL,CAAC;IAED;;;;;;OAMG;IACH,8BAAK,GAAL,UAAM,MAAc,EAAE,OAAgB;QACpC,IAAI,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC,EAAE;YAC5B,OAAO,QAAQ,CAAC;SACjB;QACD,IAAI,OAAO,KAAK,SAAS,IAAI,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,OAAO,CAAC,EAAE;YACvD,OAAO,SAAS,CAAC;SAClB;QACD,OAAO,SAAS,CAAC;IACnB,CAAC;IAED;;;;OAIG;IACH,sCAAa,GAAb,UAAc,OAAe,EAAE,MAAe;QAC5C,IAAI,CAAC,QAAQ,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;QAC7B,IAAI,MAAM,KAAK,SAAS,EAAE;YACxB,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;SAC9B;IACH,CAAC;IAlED,+FAA+F;IAC/E,qBAAM,GAAG,gDAAgD,CAAC;IAE1E;;;;;;OAMG;IACqB,2BAAY,GAAG,EAAE,CAAC;IAClB,+BAAgB,GAAG,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC;IAE1D;;;;;;OAMG;IACqB,4BAAa,GAAG,EAAE,CAAC;IACnB,gCAAiB,GAAG,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC;IA8C7D,qBAAC;CAAA,AApED,IAoEC;AApEY,wCAAc;AAsE3B,kFAAkF;AACrE,QAAA,cAAc,GAAG,IAAI,cAAc,EAAE,CAAC"}
@@ -0,0 +1,51 @@
1
+ /**
2
+ * A per-key sliding window: how many attempts a key made in the last `windowMs`, against a
3
+ * `limit`. The one window every throttled door shares — the sign-in and password-reset doors in
4
+ * this package, and any consumer door throttling per client (lifted from the invite-request
5
+ * door's per-IP throttle, which it replaces).
6
+ *
7
+ * Held in process memory only, which is what makes it cheap and what bounds it:
8
+ * - PER PROCESS. Each replica keeps its own windows, so behind a load balancer spreading a
9
+ * client over N replicas the effective ceiling is ~N× the limit; a restart forgets them.
10
+ * A throttle built on this is friction, not the wall. A shared store is a separate step.
11
+ * - BOUNDED. At most `maxKeys` keys are tracked; at the bound the oldest-touched key is
12
+ * forgotten first, so a flood of fresh keys degrades the friction before it grows memory.
13
+ *
14
+ * Keys are whatever the caller passes — callers pass digests (see `RequestDigests`), never raw
15
+ * addresses, so nothing identifying is held here either.
16
+ */
17
+ export declare class SlidingWindow {
18
+ private static readonly DEFAULT_MAX_KEYS;
19
+ private readonly windowMs;
20
+ private readonly limit;
21
+ private readonly maxKeys;
22
+ private readonly now;
23
+ /** key → the counted attempt times inside the window (pruned on touch), in touch order. */
24
+ private readonly attempts;
25
+ constructor(options: {
26
+ windowMs: number;
27
+ limit: number;
28
+ maxKeys?: number;
29
+ now?: () => number;
30
+ });
31
+ /**
32
+ * Record an attempt for `key` and answer whether it was over the window — `true` means refuse.
33
+ * A refused attempt is not counted, so a key drains one window after its last counted attempt.
34
+ */
35
+ hit(key: string): boolean;
36
+ /** Whether `key` has used up its window, without counting anything. */
37
+ isOver(key: string): boolean;
38
+ /** Count an attempt for `key` without answering (for doors that judge the attempt first). */
39
+ record(key: string): void;
40
+ /** Forget `key`'s attempts. */
41
+ clear(key: string): void;
42
+ /**
43
+ * Uncount `key`'s latest attempt (for doors that count a try as it arrives and learn afterwards
44
+ * that it should never have counted — a sign-in that succeeded).
45
+ */
46
+ forgive(key: string): void;
47
+ private inWindow;
48
+ /** Store `key`'s attempts as the most recently touched, evicting the oldest-touched key at the bound. */
49
+ private touch;
50
+ }
51
+ //# sourceMappingURL=SlidingWindow.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"SlidingWindow.d.ts","sourceRoot":"","sources":["../../../src/throttle/SlidingWindow.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AACH,qBAAa,aAAa;IACxB,OAAO,CAAC,MAAM,CAAC,QAAQ,CAAC,gBAAgB,CAAU;IAElD,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAS;IAClC,OAAO,CAAC,QAAQ,CAAC,KAAK,CAAS;IAC/B,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAS;IACjC,OAAO,CAAC,QAAQ,CAAC,GAAG,CAAe;IACnC,2FAA2F;IAC3F,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAA+B;gBAE5C,OAAO,EAAE;QAAE,QAAQ,EAAE,MAAM,CAAC;QAAC,KAAK,EAAE,MAAM,CAAC;QAAC,OAAO,CAAC,EAAE,MAAM,CAAC;QAAC,GAAG,CAAC,EAAE,MAAM,MAAM,CAAA;KAAE;IAO9F;;;OAGG;IACH,GAAG,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO;IASzB,uEAAuE;IACvE,MAAM,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO;IAI5B,6FAA6F;IAC7F,MAAM,CAAC,GAAG,EAAE,MAAM,GAAG,IAAI;IAMzB,+BAA+B;IAC/B,KAAK,CAAC,GAAG,EAAE,MAAM,GAAG,IAAI;IAIxB;;;OAGG;IACH,OAAO,CAAC,GAAG,EAAE,MAAM,GAAG,IAAI;IAM1B,OAAO,CAAC,QAAQ;IAKhB,yGAAyG;IACzG,OAAO,CAAC,KAAK;CAUd"}
@@ -0,0 +1,85 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.SlidingWindow = void 0;
4
+ /**
5
+ * A per-key sliding window: how many attempts a key made in the last `windowMs`, against a
6
+ * `limit`. The one window every throttled door shares — the sign-in and password-reset doors in
7
+ * this package, and any consumer door throttling per client (lifted from the invite-request
8
+ * door's per-IP throttle, which it replaces).
9
+ *
10
+ * Held in process memory only, which is what makes it cheap and what bounds it:
11
+ * - PER PROCESS. Each replica keeps its own windows, so behind a load balancer spreading a
12
+ * client over N replicas the effective ceiling is ~N× the limit; a restart forgets them.
13
+ * A throttle built on this is friction, not the wall. A shared store is a separate step.
14
+ * - BOUNDED. At most `maxKeys` keys are tracked; at the bound the oldest-touched key is
15
+ * forgotten first, so a flood of fresh keys degrades the friction before it grows memory.
16
+ *
17
+ * Keys are whatever the caller passes — callers pass digests (see `RequestDigests`), never raw
18
+ * addresses, so nothing identifying is held here either.
19
+ */
20
+ var SlidingWindow = /** @class */ (function () {
21
+ function SlidingWindow(options) {
22
+ var _a, _b;
23
+ /** key → the counted attempt times inside the window (pruned on touch), in touch order. */
24
+ this.attempts = new Map();
25
+ this.windowMs = options.windowMs;
26
+ this.limit = options.limit;
27
+ this.maxKeys = (_a = options.maxKeys) !== null && _a !== void 0 ? _a : SlidingWindow.DEFAULT_MAX_KEYS;
28
+ this.now = (_b = options.now) !== null && _b !== void 0 ? _b : Date.now;
29
+ }
30
+ /**
31
+ * Record an attempt for `key` and answer whether it was over the window — `true` means refuse.
32
+ * A refused attempt is not counted, so a key drains one window after its last counted attempt.
33
+ */
34
+ SlidingWindow.prototype.hit = function (key) {
35
+ if (this.isOver(key)) {
36
+ this.touch(key, this.inWindow(key));
37
+ return true;
38
+ }
39
+ this.record(key);
40
+ return false;
41
+ };
42
+ /** Whether `key` has used up its window, without counting anything. */
43
+ SlidingWindow.prototype.isOver = function (key) {
44
+ return this.inWindow(key).length >= this.limit;
45
+ };
46
+ /** Count an attempt for `key` without answering (for doors that judge the attempt first). */
47
+ SlidingWindow.prototype.record = function (key) {
48
+ var attempts = this.inWindow(key);
49
+ attempts.push(this.now());
50
+ this.touch(key, attempts);
51
+ };
52
+ /** Forget `key`'s attempts. */
53
+ SlidingWindow.prototype.clear = function (key) {
54
+ this.attempts.delete(key);
55
+ };
56
+ /**
57
+ * Uncount `key`'s latest attempt (for doors that count a try as it arrives and learn afterwards
58
+ * that it should never have counted — a sign-in that succeeded).
59
+ */
60
+ SlidingWindow.prototype.forgive = function (key) {
61
+ var attempts = this.inWindow(key);
62
+ attempts.pop();
63
+ this.touch(key, attempts);
64
+ };
65
+ SlidingWindow.prototype.inWindow = function (key) {
66
+ var _a;
67
+ var cutoff = this.now() - this.windowMs;
68
+ return ((_a = this.attempts.get(key)) !== null && _a !== void 0 ? _a : []).filter(function (time) { return time > cutoff; });
69
+ };
70
+ /** Store `key`'s attempts as the most recently touched, evicting the oldest-touched key at the bound. */
71
+ SlidingWindow.prototype.touch = function (key, attempts) {
72
+ if (!this.attempts.has(key) && this.attempts.size >= this.maxKeys) {
73
+ var oldest = this.attempts.keys().next().value;
74
+ if (oldest !== undefined) {
75
+ this.attempts.delete(oldest);
76
+ }
77
+ }
78
+ this.attempts.delete(key);
79
+ this.attempts.set(key, attempts);
80
+ };
81
+ SlidingWindow.DEFAULT_MAX_KEYS = 10000;
82
+ return SlidingWindow;
83
+ }());
84
+ exports.SlidingWindow = SlidingWindow;
85
+ //# sourceMappingURL=SlidingWindow.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"SlidingWindow.js","sourceRoot":"","sources":["../../../src/throttle/SlidingWindow.ts"],"names":[],"mappings":";;;AAAA;;;;;;;;;;;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0,0 +1 @@
1
+ {"version":3,"file":"ClientAddress.test.d.ts","sourceRoot":"","sources":["../../test/ClientAddress.test.ts"],"names":[],"mappings":""}
@@ -0,0 +1,51 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ var ClientAddress_1 = require("../src/throttle/ClientAddress");
4
+ /**
5
+ * Which address a throttle keys on. Behind Google's external Application Load Balancer the
6
+ * header ends `<client-ip>,<load-balancer-ip>` — the balancer appends both, and anything before
7
+ * them is whatever the client itself sent. So the client is the SECOND entry from the right:
8
+ * never the last (the balancer's own address, the same for every visitor — a throttle keyed on
9
+ * it is one bucket for the whole world) and never the first (client-supplied, rotatable at will).
10
+ */
11
+ describe('ClientAddress', function () {
12
+ var behindTheBalancer = function (forwardedFor, socketAddress) {
13
+ var _a, _b;
14
+ if (socketAddress === void 0) { socketAddress = '35.191.0.10'; }
15
+ return ({
16
+ app: { get: function (setting) { return (setting === 'trust proxy' ? 1 : undefined); } },
17
+ headers: forwardedFor === undefined ? {} : { 'x-forwarded-for': forwardedFor },
18
+ socket: { remoteAddress: socketAddress },
19
+ // What express's own `request.ip` resolves to under `trust proxy 1`: the header's last entry.
20
+ ip: (_b = (_a = forwardedFor === null || forwardedFor === void 0 ? void 0 : forwardedFor.split(',').pop()) === null || _a === void 0 ? void 0 : _a.trim()) !== null && _b !== void 0 ? _b : socketAddress,
21
+ });
22
+ };
23
+ it("reads the client the balancer appended, not the balancer's own address", function () {
24
+ var request = behindTheBalancer('198.51.100.23, 34.120.1.1');
25
+ expect(new ClientAddress_1.ClientAddress().of(request)).toBe('198.51.100.23');
26
+ expect(request.ip).toBe('34.120.1.1');
27
+ });
28
+ it('ignores whatever the client put in the header itself', function () {
29
+ var spoofed = behindTheBalancer('203.0.113.99, 10.0.0.1, 198.51.100.23, 34.120.1.1');
30
+ expect(new ClientAddress_1.ClientAddress().of(spoofed)).toBe('198.51.100.23');
31
+ });
32
+ it('reads IPv6 clients the same way', function () {
33
+ expect(new ClientAddress_1.ClientAddress().of(behindTheBalancer('2001:db8:1:2:3:4:5:6,34.120.1.1'))).toBe('2001:db8:1:2:3:4:5:6');
34
+ });
35
+ it('a request that did not come through the balancer (no appended pair) keys on its own connection', function () {
36
+ expect(new ClientAddress_1.ClientAddress().of(behindTheBalancer(undefined, '10.8.0.7'))).toBe('10.8.0.7');
37
+ expect(new ClientAddress_1.ClientAddress().of(behindTheBalancer('10.8.0.9', '10.8.0.7'))).toBe('10.8.0.7');
38
+ });
39
+ it('with no proxy trusted (development) the connection is the client, and a forwarded header is ignored', function () {
40
+ var direct = {
41
+ app: { get: function () { return false; } },
42
+ headers: { 'x-forwarded-for': '203.0.113.99, 198.51.100.23' },
43
+ socket: { remoteAddress: '::1' },
44
+ };
45
+ expect(new ClientAddress_1.ClientAddress().of(direct)).toBe('::1');
46
+ });
47
+ it('a request with no connection details at all reads as the empty address', function () {
48
+ expect(new ClientAddress_1.ClientAddress().of({})).toBe('');
49
+ });
50
+ });
51
+ //# sourceMappingURL=ClientAddress.test.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ClientAddress.test.js","sourceRoot":"","sources":["../../test/ClientAddress.test.ts"],"names":[],"mappings":";;AAAA,+DAA8D;AAE9D;;;;;;GAMG;AACH,QAAQ,CAAC,eAAe,EAAE;IACxB,IAAM,iBAAiB,GAAG,UAAC,YAAgC,EAAE,aAA6B;;QAA7B,8BAAA,EAAA,6BAA6B;QAAK,OAAA,CAAC;YAC9F,GAAG,EAAE,EAAE,GAAG,EAAE,UAAC,OAAe,IAAK,OAAA,CAAC,OAAO,KAAK,aAAa,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC,EAA3C,CAA2C,EAAE;YAC9E,OAAO,EAAE,YAAY,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,iBAAiB,EAAE,YAAY,EAAE;YAC9E,MAAM,EAAE,EAAE,aAAa,EAAE,aAAa,EAAE;YACxC,8FA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AAC,CAAC;IAEH,EAAE,CAAC,qGAAqG,EAAE;QACxG,IAAM,MAAM,GAAG;YACb,GAAG,EAAE,EAAE,GAAG,EAAE,cAAM,OAAA,KAAK,EAAL,CAAK,EAAE;YACzB,OAAO,EAAE,EAAE,iBAAiB,EAAE,6BAA6B,EAAE;YAC7D,MAAM,EAAE,EAAE,aAAa,EAAE,KAAK,EAAE;SACjC,CAAC;QAEF,MAAM,CAAC,IAAI,6BAAa,EAAE,CAAC,EAAE,CAAC,MAAM,CAAC,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;IACrD,CAAC,CAAC,CAAC;IAEH,EAAE,CAAC,wEAAwE,EAAE;QAC3E,MAAM,CAAC,IAAI,6BAAa,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;IAC9C,CAAC,CAAC,CAAC;AACL,CAAC,CAAC,CAAC"}
@@ -0,0 +1,29 @@
1
+ import { DbDriver } from '@proteinjs/db';
2
+ /**
3
+ * What reached the database while a run executed — the outcome a "refused before any lookup"
4
+ * claim rests on. A response code cannot prove it: a value that is wrongly let through still
5
+ * matches no row and still answers 400, so the proof is that nothing was built and nothing ran.
6
+ * - `lookups`: the filter of every read built through the package's `Db` — every `query`, which
7
+ * is also what a `get` is (the first row of one);
8
+ * - `writes`: how many writes were built through it (`insert`, `update`, `delete`);
9
+ * - `statements`: how many statements the driver ran, whoever built them.
10
+ */
11
+ export declare class DbTraffic {
12
+ readonly lookups: unknown[];
13
+ readonly writes: number;
14
+ readonly statements: number;
15
+ private constructor();
16
+ /** The traffic of a run that never touched the database: `expect(traffic).toEqual(DbTraffic.NONE)`. */
17
+ static readonly NONE: {
18
+ lookups: never[];
19
+ writes: number;
20
+ statements: number;
21
+ };
22
+ /** Runs `run` and answers what it resolved to beside the database traffic it caused. */
23
+ static during<T>(driver: DbDriver, run: () => Promise<T>): Promise<{
24
+ result: T;
25
+ traffic: DbTraffic;
26
+ }>;
27
+ private static callCount;
28
+ }
29
+ //# sourceMappingURL=DbTraffic.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"DbTraffic.d.ts","sourceRoot":"","sources":["../../test/DbTraffic.ts"],"names":[],"mappings":"AAAA,OAAO,EAAM,QAAQ,EAAE,MAAM,eAAe,CAAC;AAE7C;;;;;;;;GAQG;AACH,qBAAa,SAAS;IAElB,QAAQ,CAAC,OAAO,EAAE,OAAO,EAAE;IAC3B,QAAQ,CAAC,MAAM,EAAE,MAAM;IACvB,QAAQ,CAAC,UAAU,EAAE,MAAM;IAH7B,OAAO;IAMP,uGAAuG;IACvG,MAAM,CAAC,QAAQ,CAAC,IAAI;;;;MAA6C;IAEjE,wFAAwF;WAC3E,MAAM,CAAC,CAAC,EAAE,MAAM,EAAE,QAAQ,EAAE,GAAG,EAAE,MAAM,OAAO,CAAC,CAAC,CAAC,GAAG,OAAO,CAAC;QAAE,MAAM,EAAE,CAAC,CAAC;QAAC,OAAO,EAAE,SAAS,CAAA;KAAE,CAAC;IAiB3G,OAAO,CAAC,MAAM,CAAC,SAAS;CAGzB"}
@@ -0,0 +1,106 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __generator = (this && this.__generator) || function (thisArg, body) {
12
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
13
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
14
+ function verb(n) { return function (v) { return step([n, v]); }; }
15
+ function step(op) {
16
+ if (f) throw new TypeError("Generator is already executing.");
17
+ while (g && (g = 0, op[0] && (_ = 0)), _) try {
18
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
19
+ if (y = 0, t) op = [op[0] & 2, t.value];
20
+ switch (op[0]) {
21
+ case 0: case 1: t = op; break;
22
+ case 4: _.label++; return { value: op[1], done: false };
23
+ case 5: _.label++; y = op[1]; op = [0]; continue;
24
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
25
+ default:
26
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
27
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
28
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
29
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
30
+ if (t[2]) _.ops.pop();
31
+ _.trys.pop(); continue;
32
+ }
33
+ op = body.call(thisArg, _);
34
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
35
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
36
+ }
37
+ };
38
+ var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
39
+ if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
40
+ if (ar || !(i in from)) {
41
+ if (!ar) ar = Array.prototype.slice.call(from, 0, i);
42
+ ar[i] = from[i];
43
+ }
44
+ }
45
+ return to.concat(ar || Array.prototype.slice.call(from));
46
+ };
47
+ Object.defineProperty(exports, "__esModule", { value: true });
48
+ exports.DbTraffic = void 0;
49
+ var db_1 = require("@proteinjs/db");
50
+ /**
51
+ * What reached the database while a run executed — the outcome a "refused before any lookup"
52
+ * claim rests on. A response code cannot prove it: a value that is wrongly let through still
53
+ * matches no row and still answers 400, so the proof is that nothing was built and nothing ran.
54
+ * - `lookups`: the filter of every read built through the package's `Db` — every `query`, which
55
+ * is also what a `get` is (the first row of one);
56
+ * - `writes`: how many writes were built through it (`insert`, `update`, `delete`);
57
+ * - `statements`: how many statements the driver ran, whoever built them.
58
+ */
59
+ var DbTraffic = /** @class */ (function () {
60
+ function DbTraffic(lookups, writes, statements) {
61
+ this.lookups = lookups;
62
+ this.writes = writes;
63
+ this.statements = statements;
64
+ }
65
+ /** Runs `run` and answers what it resolved to beside the database traffic it caused. */
66
+ DbTraffic.during = function (driver, run) {
67
+ return __awaiter(this, void 0, void 0, function () {
68
+ var reads, writes, statements, result, lookups;
69
+ return __generator(this, function (_a) {
70
+ switch (_a.label) {
71
+ case 0:
72
+ reads = jest.spyOn(db_1.Db.prototype, 'query');
73
+ writes = [
74
+ jest.spyOn(db_1.Db.prototype, 'insert'),
75
+ jest.spyOn(db_1.Db.prototype, 'update'),
76
+ jest.spyOn(db_1.Db.prototype, 'delete'),
77
+ ];
78
+ statements = [jest.spyOn(driver, 'runQuery'), jest.spyOn(driver, 'runDml')];
79
+ _a.label = 1;
80
+ case 1:
81
+ _a.trys.push([1, , 3, 4]);
82
+ return [4 /*yield*/, run()];
83
+ case 2:
84
+ result = _a.sent();
85
+ lookups = reads.mock.calls.map(function (_a) {
86
+ var _table = _a[0], filter = _a[1];
87
+ return filter;
88
+ });
89
+ return [2 /*return*/, { result: result, traffic: new DbTraffic(lookups, DbTraffic.callCount(writes), DbTraffic.callCount(statements)) }];
90
+ case 3:
91
+ __spreadArray(__spreadArray([reads], writes, true), statements, true).forEach(function (spy) { return spy.mockRestore(); });
92
+ return [7 /*endfinally*/];
93
+ case 4: return [2 /*return*/];
94
+ }
95
+ });
96
+ });
97
+ };
98
+ DbTraffic.callCount = function (spies) {
99
+ return spies.reduce(function (count, spy) { return count + spy.mock.calls.length; }, 0);
100
+ };
101
+ /** The traffic of a run that never touched the database: `expect(traffic).toEqual(DbTraffic.NONE)`. */
102
+ DbTraffic.NONE = { lookups: [], writes: 0, statements: 0 };
103
+ return DbTraffic;
104
+ }());
105
+ exports.DbTraffic = DbTraffic;
106
+ //# sourceMappingURL=DbTraffic.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"DbTraffic.js","sourceRoot":"","sources":["../../test/DbTraffic.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,oCAA6C;AAE7C;;;;;;;;GAQG;AACH;IACE,mBACW,OAAkB,EAClB,MAAc,EACd,UAAkB;QAFlB,YAAO,GAAP,OAAO,CAAW;QAClB,WAAM,GAAN,MAAM,CAAQ;QACd,eAAU,GAAV,UAAU,CAAQ;IAC1B,CAAC;IAKJ,wFAAwF;IAC3E,gBAAM,GAAnB,UAAuB,MAAgB,EAAE,GAAqB;;;;;;wBACtD,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,OAAE,CAAC,SAAS,EAAE,OAAO,CAAC,CAAC;wBAC1C,MAAM,GAAG;4BACb,IAAI,CAAC,KAAK,CAAC,OAAE,CAAC,SAAS,EAAE,QAAQ,CAAC;4BAClC,IAAI,CAAC,KAAK,CAAC,OAAE,CAAC,SAAS,EAAE,QAAQ,CAAC;4BAClC,IAAI,CAAC,KAAK,CAAC,OAAE,CAAC,SAAS,EAAE,QAAQ,CAAC;yBACnC,CAAC;wBACI,UAAU,GAAG,CAAC,IAAI,CAAC,KAAK,CAAC,MAAM,EAAE,UAAU,CAAC,EAAE,IAAI,CAAC,KAAK,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAC,CAAC;;;;wBAEjE,qBAAM,GAAG,EAAE,EAAA;;wBAApB,MAAM,GAAG,SAAW;wBACpB,OAAO,GAAG,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,UAAC,EAAgB;gCAAf,MAAM,QAAA,EAAE,MAAM,Q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