@connextar/house 0.23.1 → 0.24.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (186) hide show
  1. package/README.md +55 -13
  2. package/dist/analytics/browser.d.ts +1 -0
  3. package/dist/analytics/browser.d.ts.map +1 -1
  4. package/dist/analytics/browser.js +22 -5
  5. package/dist/analytics/browser.js.map +1 -1
  6. package/dist/analytics/config.d.ts +5 -0
  7. package/dist/analytics/config.d.ts.map +1 -1
  8. package/dist/analytics/config.js +4 -1
  9. package/dist/analytics/config.js.map +1 -1
  10. package/dist/analytics/posthog-extensions.d.ts +19 -0
  11. package/dist/analytics/posthog-extensions.d.ts.map +1 -0
  12. package/dist/analytics/posthog-extensions.js +19 -0
  13. package/dist/analytics/posthog-extensions.js.map +1 -0
  14. package/dist/analytics/react.d.ts.map +1 -1
  15. package/dist/analytics/react.js +4 -2
  16. package/dist/analytics/react.js.map +1 -1
  17. package/dist/analytics/redact.d.ts.map +1 -1
  18. package/dist/analytics/redact.js +6 -1
  19. package/dist/analytics/redact.js.map +1 -1
  20. package/dist/house.css +19 -0
  21. package/package.json +17 -3
  22. package/src/account/data-contract.ts +112 -0
  23. package/src/account/index.ts +11 -0
  24. package/src/admin/access.ts +267 -0
  25. package/src/admin/audit.ts +238 -0
  26. package/src/admin/bootstrap.ts +220 -0
  27. package/src/admin/client-index.ts +19 -0
  28. package/src/admin/client.tsx +187 -0
  29. package/src/admin/index.ts +91 -0
  30. package/src/admin/proof.ts +155 -0
  31. package/src/admin/second-factor-index.ts +16 -0
  32. package/src/admin/second-factor.ts +403 -0
  33. package/src/admin/testing-index.ts +13 -0
  34. package/src/admin/testing.ts +299 -0
  35. package/src/admin/view-as.ts +511 -0
  36. package/src/ai/config-index.ts +40 -0
  37. package/src/ai/config.ts +176 -0
  38. package/src/ai/images.ts +18 -0
  39. package/src/ai/index.ts +21 -0
  40. package/src/ai/pricing.ts +107 -0
  41. package/src/ai/provider.ts +403 -0
  42. package/src/analytics/browser.ts +400 -0
  43. package/src/analytics/client-index.ts +12 -0
  44. package/src/analytics/config.ts +89 -0
  45. package/src/analytics/index.ts +17 -0
  46. package/src/analytics/ingest.ts +81 -0
  47. package/src/analytics/posthog-extensions.ts +19 -0
  48. package/src/analytics/react-index.ts +16 -0
  49. package/src/analytics/react.tsx +241 -0
  50. package/src/analytics/redact.ts +146 -0
  51. package/src/analytics/server-index.ts +17 -0
  52. package/src/analytics/server.ts +277 -0
  53. package/src/auth/index.ts +30 -0
  54. package/src/auth/second-factor-index.ts +16 -0
  55. package/src/auth/second-factor-next.ts +136 -0
  56. package/src/auth/second-factor-routes.ts +40 -0
  57. package/src/auth/second-factor.ts +226 -0
  58. package/src/auth/step-up-client-index.ts +13 -0
  59. package/src/auth/step-up-client.ts +23 -0
  60. package/src/auth/step-up-index.ts +19 -0
  61. package/src/auth/step-up-routes.ts +99 -0
  62. package/src/auth/step-up.ts +432 -0
  63. package/src/auth/two-factor-policy.ts +112 -0
  64. package/src/changelog/changelog.tsx +367 -0
  65. package/src/changelog/index.ts +12 -0
  66. package/src/editor/block-handle.tsx +312 -0
  67. package/src/editor/blocks.ts +169 -0
  68. package/src/editor/bubble-toolbar.tsx +208 -0
  69. package/src/editor/collapsible.ts +159 -0
  70. package/src/editor/content-index.ts +1 -0
  71. package/src/editor/content.tsx +343 -0
  72. package/src/editor/editor.tsx +333 -0
  73. package/src/editor/emoji-index.ts +1 -0
  74. package/src/editor/emoji-picker.tsx +114 -0
  75. package/src/editor/emoji.ts +436 -0
  76. package/src/editor/index.ts +6 -0
  77. package/src/editor/sections.ts +83 -0
  78. package/src/editor/suggestion-popup.tsx +136 -0
  79. package/src/editor/suggestions.ts +309 -0
  80. package/src/editor/ui.tsx +171 -0
  81. package/src/errors/error-shell.tsx +72 -0
  82. package/src/errors/global-error-shell.tsx +116 -0
  83. package/src/errors/index.ts +2 -0
  84. package/src/grid/columns.ts +48 -0
  85. package/src/grid/compare.ts +35 -0
  86. package/src/grid/hidden-columns.ts +95 -0
  87. package/src/grid/index.ts +27 -0
  88. package/src/grid/use-grid.ts +282 -0
  89. package/src/grid/views.ts +70 -0
  90. package/src/guides/guide-article.tsx +92 -0
  91. package/src/guides/guide-figure-zoom.tsx +533 -0
  92. package/src/guides/guide-figure.tsx +68 -0
  93. package/src/guides/guide-toc.tsx +133 -0
  94. package/src/guides/guides-landing.tsx +57 -0
  95. package/src/guides/guides-search.tsx +160 -0
  96. package/src/guides/guides-shell.tsx +60 -0
  97. package/src/guides/guides-sidebar.tsx +93 -0
  98. package/src/guides/index.ts +28 -0
  99. package/src/guides/library.ts +165 -0
  100. package/src/health/health.ts +115 -0
  101. package/src/health/index.ts +11 -0
  102. package/src/internal/cx.ts +4 -0
  103. package/src/internal/next-link.ts +23 -0
  104. package/src/jobs/counts.ts +151 -0
  105. package/src/jobs/cron-auth.ts +60 -0
  106. package/src/jobs/health.ts +315 -0
  107. package/src/jobs/idle.ts +86 -0
  108. package/src/jobs/index.ts +120 -0
  109. package/src/jobs/job-health-list.tsx +316 -0
  110. package/src/jobs/next-index.ts +4 -0
  111. package/src/jobs/next.ts +65 -0
  112. package/src/jobs/prisma-index.ts +12 -0
  113. package/src/jobs/prisma.ts +170 -0
  114. package/src/jobs/prune.ts +79 -0
  115. package/src/jobs/react-index.ts +35 -0
  116. package/src/jobs/registry.ts +189 -0
  117. package/src/jobs/scheduler.ts +437 -0
  118. package/src/jobs/store.ts +212 -0
  119. package/src/jobs/windows.ts +157 -0
  120. package/src/maintenance/core.ts +270 -0
  121. package/src/maintenance/gate.ts +171 -0
  122. package/src/maintenance/index.ts +40 -0
  123. package/src/maintenance/page.ts +76 -0
  124. package/src/maintenance/proxy.ts +88 -0
  125. package/src/maintenance/react-index.ts +7 -0
  126. package/src/maintenance/react.tsx +190 -0
  127. package/src/maintenance/route.ts +82 -0
  128. package/src/maintenance/unavailable.ts +61 -0
  129. package/src/markdown/figure.tsx +132 -0
  130. package/src/markdown/figures.ts +237 -0
  131. package/src/markdown/guide.tsx +536 -0
  132. package/src/markdown/index.ts +53 -0
  133. package/src/markdown/table-view.tsx +74 -0
  134. package/src/markdown/table.ts +90 -0
  135. package/src/password/common.ts +58 -0
  136. package/src/password/estimate-index.ts +18 -0
  137. package/src/password/estimate.ts +715 -0
  138. package/src/password/index.ts +40 -0
  139. package/src/password/password-input.tsx +116 -0
  140. package/src/password/password-strength.tsx +157 -0
  141. package/src/password/reveal.ts +151 -0
  142. package/src/rate-limit/better-auth.ts +94 -0
  143. package/src/rate-limit/index.ts +32 -0
  144. package/src/rate-limit/keys.ts +110 -0
  145. package/src/rate-limit/limiter.ts +276 -0
  146. package/src/rate-limit/prisma-index.ts +12 -0
  147. package/src/rate-limit/prisma.ts +157 -0
  148. package/src/rate-limit/store.ts +47 -0
  149. package/src/release/changelog.ts +364 -0
  150. package/src/release/index.ts +32 -0
  151. package/src/release/version.ts +64 -0
  152. package/src/setup-guide/bits.tsx +420 -0
  153. package/src/setup-guide/card.tsx +358 -0
  154. package/src/setup-guide/class-names.ts +144 -0
  155. package/src/setup-guide/context.tsx +239 -0
  156. package/src/setup-guide/guide.ts +271 -0
  157. package/src/setup-guide/index.ts +76 -0
  158. package/src/setup-guide/launcher.tsx +207 -0
  159. package/src/setup-guide/strip.tsx +127 -0
  160. package/src/styles/house.css +403 -0
  161. package/src/trail/index.ts +12 -0
  162. package/src/trail/rules.ts +84 -0
  163. package/src/trail/trail.tsx +367 -0
  164. package/src/ux/errors.ts +32 -0
  165. package/src/ux/feedback.tsx +41 -0
  166. package/src/ux/index.ts +44 -0
  167. package/src/ux/navigation-index.ts +16 -0
  168. package/src/ux/navigation-progress.tsx +270 -0
  169. package/src/ux/optimistic.ts +415 -0
  170. package/src/ux/use-action.ts +155 -0
  171. package/src/ux/use-optimistic-list.ts +227 -0
  172. package/src/ux/use-optimistic-value.ts +136 -0
  173. package/src/web-search/index.ts +13 -0
  174. package/src/web-search/providers.ts +177 -0
  175. package/src/web-search/types.ts +98 -0
  176. package/src/whats-new/body.tsx +190 -0
  177. package/src/whats-new/index.ts +43 -0
  178. package/src/whats-new/seen.ts +40 -0
  179. package/src/whats-new/select.ts +230 -0
  180. package/src/whats-new/use-whats-new.ts +109 -0
  181. package/src/wizard/index.ts +61 -0
  182. package/src/wizard/invalid.ts +152 -0
  183. package/src/wizard/react-hook-form-index.ts +11 -0
  184. package/src/wizard/rhf-adapter.ts +67 -0
  185. package/src/wizard/rules.ts +137 -0
  186. package/src/wizard/wizard.tsx +442 -0
@@ -0,0 +1,110 @@
1
+ import { createHash, createHmac } from "node:crypto";
2
+
3
+ /**
4
+ * What goes into a key: the caller's address, bucketed; a private value, made unreadable; and the whole, made to fit.
5
+ */
6
+
7
+ /** The `key` column most apps have: `VARCHAR(200)`. */
8
+ export const DEFAULT_MAX_KEY_LENGTH = 200;
9
+
10
+ /**
11
+ * The key as it is stored. One that fits is stored as it is. A longer one becomes its surface (up to the first `:`,
12
+ * at most 40 characters), `#`, and the SHA-256 of the whole key — still its own window, and never wider than 105
13
+ * characters. Every app but Quickie stored the long key as it came, which a `VARCHAR(200)` refused, and the limiter
14
+ * then failed open: a long enough key switched the limit off (Quickie security round 7). The format is Quickie's, so
15
+ * its rows keep counting.
16
+ */
17
+ export function storedKey(key: string, maxLength: number = DEFAULT_MAX_KEY_LENGTH): string {
18
+ if (key.length <= maxLength) return key;
19
+ const prefix = key.slice(0, Math.min(key.indexOf(":") + 1 || 40, 40));
20
+ return `${prefix}#${createHash("sha256").update(key).digest("hex")}`;
21
+ }
22
+
23
+ /**
24
+ * A key for something private — an email address, a calendar token, a path that names somebody — that still counts
25
+ * per value: `prefix:` and 40 hex characters of an HMAC-SHA256 over the parts, keyed by the app's secret. The table
26
+ * then holds no address, and nobody who reads it can test a guess without the secret. Quickie's format, so its rows
27
+ * keep counting.
28
+ */
29
+ export function privateKey(secret: string, prefix: string, ...parts: string[]): string {
30
+ if (typeof secret !== "string" || secret.length < 32) {
31
+ throw new Error("[rate-limit] privateKey needs a secret of at least 32 characters.");
32
+ }
33
+ return `${prefix}:${createHmac("sha256", secret).update(parts.join("\u0000")).digest("hex").slice(0, 40)}`;
34
+ }
35
+
36
+ const IPV4 = /^\d{1,3}(\.\d{1,3}){3}$/;
37
+
38
+ /**
39
+ * The bucket an address counts in. IPv4 is itself; IPv4-mapped IPv6 (`::ffff:203.0.113.7`) is the IPv4 address;
40
+ * other IPv6 is its /64 — one household or one phone gets a whole /64, so counting per address would let a single
41
+ * caller rotate through 2^64 of them. A zone (`%eth0`) is dropped; anything unreadable is kept as it came, cut to 64
42
+ * characters, so it still counts as something. AltEd's mapping and Quickie's zones, together.
43
+ */
44
+ export function ipBucket(address: string): string {
45
+ const ip = address.trim();
46
+ if (!ip.includes(":")) return ip.slice(0, 64) || "unknown";
47
+ const head = ip
48
+ .split("%")[0]!
49
+ .toLowerCase()
50
+ .replace(/^\[|\]$/g, "");
51
+ const mapped = /^(?:0{0,4}:){0,5}:?ffff:(\d{1,3}(?:\.\d{1,3}){3})$/i.exec(head);
52
+ if (mapped && IPV4.test(mapped[1]!)) return mapped[1]!;
53
+ const halves = head.split("::");
54
+ if (halves.length > 2) return ip.slice(0, 64);
55
+ const left = halves[0] ? halves[0].split(":") : [];
56
+ let right = halves.length > 1 && halves[1] ? halves[1].split(":") : [];
57
+ // An embedded IPv4 tail counts as two groups.
58
+ if (right.length && IPV4.test(right.at(-1)!)) right = [...right.slice(0, -1), "0", "0"];
59
+ const groups =
60
+ halves.length > 1
61
+ ? [...left, ...Array<string>(Math.max(0, 8 - left.length - right.length)).fill("0"), ...right]
62
+ : left;
63
+ if (groups.length !== 8 || !groups.every((group) => /^[0-9a-f]{1,4}$/.test(group))) return ip.slice(0, 64);
64
+ return `${groups
65
+ .slice(0, 4)
66
+ .map((group) => group.replace(/^0+(?=.)/, ""))
67
+ .join(":")}::/64`;
68
+ }
69
+
70
+ export interface CallerIpOptions {
71
+ /**
72
+ * Headers to read, first that is present wins. Default: `x-vercel-forwarded-for` (set by Vercel, which a client
73
+ * cannot), `x-real-ip`, then `x-forwarded-for`.
74
+ */
75
+ headers?: readonly string[];
76
+ /**
77
+ * Which entry of a comma-separated list to take. Default `"rightmost"`: the one the last proxy added, which a client
78
+ * cannot forge by sending its own `X-Forwarded-For`. Behind several proxies of the app's own, say how many with
79
+ * `{ trustedProxies: n }`, and the entry that many from the right is taken.
80
+ */
81
+ forwarded?: "rightmost" | "leftmost" | { trustedProxies: number };
82
+ }
83
+
84
+ const DEFAULT_IP_HEADERS = ["x-vercel-forwarded-for", "x-real-ip", "x-forwarded-for"] as const;
85
+
86
+ /** The caller's address bucket from a request or its headers: `ipBucket` of the first trusted header, or `unknown`. */
87
+ export function callerIp(source: Request | Pick<Headers, "get">, options: CallerIpOptions = {}): string {
88
+ const headers =
89
+ "headers" in source && typeof (source as Request).headers?.get === "function"
90
+ ? (source as Request).headers
91
+ : (source as Pick<Headers, "get">);
92
+ for (const name of options.headers ?? DEFAULT_IP_HEADERS) {
93
+ const value = headers.get(name);
94
+ if (!value) continue;
95
+ const entries = value
96
+ .split(",")
97
+ .map((entry) => entry.trim())
98
+ .filter(Boolean);
99
+ if (!entries.length) continue;
100
+ const forwarded = options.forwarded ?? "rightmost";
101
+ const pick =
102
+ forwarded === "leftmost"
103
+ ? entries[0]
104
+ : forwarded === "rightmost"
105
+ ? entries.at(-1)
106
+ : entries[Math.max(0, entries.length - Math.max(1, Math.floor(forwarded.trustedProxies)))];
107
+ if (pick) return ipBucket(pick);
108
+ }
109
+ return "unknown";
110
+ }
@@ -0,0 +1,276 @@
1
+ import { DEFAULT_MAX_KEY_LENGTH, privateKey, storedKey } from "./keys.js";
2
+ import type { RateLimitStore } from "./store.js";
3
+
4
+ /**
5
+ * A fixed-window limiter over the app's own table — the one every app with a `rate_limit` table wrote, eleven times.
6
+ *
7
+ * Each copy had one thing the others lacked, and the union is here: AltEd's per-rule `failClosed`, variable cost and
8
+ * "everyone" ceilings; Quickie's long keys hashed rather than refused, private keys made unreadable, a `usage` that
9
+ * reads without spending, and IPv6 counted per /64; PharmaLine's read that fails closed. All but PharmaLine failed open
10
+ * on every database error, including the long-key one that turned a limit off.
11
+ *
12
+ * Windows are fixed and aligned to the epoch — `windowAt` is `now` rounded down to `windowMs` — so a daily rule's day
13
+ * is the UTC day, every app's rows keep counting, and two instances agree on a window without talking.
14
+ */
15
+
16
+ export interface RateLimitRule {
17
+ /** Most uses in one window. */
18
+ limit: number;
19
+ windowMs: number;
20
+ /**
21
+ * When the count cannot be read or written: refuse (`true`) or allow (default). Fail closed where a use spends
22
+ * money or reaches someone — a paid model call, an email to a stranger, a code check — and open where a refusal
23
+ * would only stop somebody reading their own page while the database is down.
24
+ */
25
+ failClosed?: boolean;
26
+ /**
27
+ * A ceiling over every caller together, checked after the caller's own: "300 class requests a day across the whole
28
+ * site, 5 each". Its own key, a limit, and a window (the rule's, unless given).
29
+ */
30
+ everyone?: { key: string; limit: number; windowMs?: number };
31
+ }
32
+
33
+ export interface RateLimitResult {
34
+ allowed: boolean;
35
+ /** Uses left in the window that decided — the caller's, or everyone's when that ceiling refused. */
36
+ remaining: number;
37
+ limit: number;
38
+ /** When the deciding window ends. */
39
+ resetAt: Date;
40
+ /** Seconds until then, at least 1. */
41
+ retryAfter: number;
42
+ /** Which limit refused: the caller's own, or the ceiling over everyone. Absent when allowed. */
43
+ refusedBy?: "caller" | "everyone";
44
+ /** The count could not be read or written, and the rule's `failClosed` decided. */
45
+ failed?: true;
46
+ }
47
+
48
+ export interface RateLimitUsage {
49
+ /** Spent in the current window, at most `limit`. */
50
+ used: number;
51
+ limit: number;
52
+ remaining: number;
53
+ resetAt: Date;
54
+ /** The ceiling over everyone, when the rule has one. */
55
+ everyone?: { used: number; limit: number; remaining: number; resetAt: Date };
56
+ /** The count could not be read: `used` is the whole limit under `failClosed`, nothing otherwise. */
57
+ failed?: true;
58
+ }
59
+
60
+ export interface RateLimiterLogger {
61
+ error(message: string, ...detail: unknown[]): void;
62
+ }
63
+
64
+ export interface AutoPruneOptions {
65
+ /** The chance, from 0 to 1, that an allowed `consume` prunes afterwards. FB Web's 0.01. */
66
+ chance: number;
67
+ olderThanMs?: number;
68
+ batch?: number;
69
+ /** Run the prune after the response: Next's `after`. Default: started and not awaited, errors logged. */
70
+ schedule?: (task: () => Promise<void>) => void;
71
+ }
72
+
73
+ export interface RateLimiterOptions {
74
+ store: RateLimitStore;
75
+ /** For `privateKey`. At least 32 characters; the app's `BETTER_AUTH_SECRET` serves. */
76
+ secret?: string;
77
+ /** The `key` column's width. Default 200; longer keys are stored hashed (`storedKey`). */
78
+ maxKeyLength?: number;
79
+ /** For apps with no job to prune from (KRP, MAS, FB Web, Tracker C): prune now and then, as windows are spent. */
80
+ autoPrune?: AutoPruneOptions;
81
+ logger?: RateLimiterLogger;
82
+ /** For tests. */
83
+ now?: () => number;
84
+ /** For tests of `autoPrune`. */
85
+ random?: () => number;
86
+ }
87
+
88
+ export interface PruneOptions {
89
+ /** Windows that started longer ago than this go. Default seven days — longer than any rule's window. */
90
+ olderThanMs?: number;
91
+ /** At most this many a call. Default 1,000. */
92
+ batch?: number;
93
+ }
94
+
95
+ export interface RateLimiter {
96
+ /** Spend `amount` (default 1) of the key's window and say whether it was allowed. Never throws for the store. */
97
+ consume(key: string, rule: RateLimitRule, amount?: number): Promise<RateLimitResult>;
98
+ /** How much of the window is spent, without spending any — for a page that shows a budget. */
99
+ usage(key: string, rule: RateLimitRule): Promise<RateLimitUsage>;
100
+ /** `prefix:` and an HMAC of the parts, keyed by `secret` — for an email address or a token in a key. */
101
+ privateKey(prefix: string, ...parts: string[]): string;
102
+ /** Delete old windows, at most a batch a call. For the app's housekeeping job. */
103
+ prune(options?: PruneOptions): Promise<number>;
104
+ }
105
+
106
+ export const DEFAULT_RATE_LIMIT_RETENTION_MS = 7 * 24 * 60 * 60 * 1000;
107
+ export const DEFAULT_RATE_LIMIT_PRUNE_BATCH = 1000;
108
+
109
+ /** Checks a rule table where it is declared, so a typo is found when the module loads rather than in a refusal. */
110
+ export function defineRateLimits<T extends Record<string, RateLimitRule>>(rules: T): T {
111
+ const problems = Object.entries(rules).flatMap(([name, rule]) => ruleProblems(rule).map((p) => `${name}: ${p}`));
112
+ if (problems.length) throw new Error(`[rate-limit] ${problems.join("; ")}`);
113
+ return rules;
114
+ }
115
+
116
+ function ruleProblems(rule: RateLimitRule): string[] {
117
+ const problems: string[] = [];
118
+ if (!Number.isInteger(rule?.limit) || rule.limit < 1) problems.push("limit must be a whole number, at least 1");
119
+ if (!Number.isFinite(rule?.windowMs) || rule.windowMs < 1000) problems.push("windowMs must be at least 1000");
120
+ if (rule?.everyone) {
121
+ const e = rule.everyone;
122
+ if (!e.key) problems.push("everyone needs a key");
123
+ if (!Number.isInteger(e.limit) || e.limit < 1) problems.push("everyone.limit must be a whole number, at least 1");
124
+ if (e.windowMs !== undefined && (!Number.isFinite(e.windowMs) || e.windowMs < 1000)) {
125
+ problems.push("everyone.windowMs must be at least 1000");
126
+ }
127
+ }
128
+ return problems;
129
+ }
130
+
131
+ export function createRateLimiter(options: RateLimiterOptions): RateLimiter {
132
+ const { store } = options;
133
+ const now = options.now ?? Date.now;
134
+ const random = options.random ?? Math.random;
135
+ const logger = options.logger ?? console;
136
+ const maxKeyLength = options.maxKeyLength ?? DEFAULT_MAX_KEY_LENGTH;
137
+ if (!Number.isInteger(maxKeyLength) || maxKeyLength < 110) {
138
+ throw new Error("[rate-limit] maxKeyLength must be at least 110, the length of a hashed key.");
139
+ }
140
+
141
+ const windowOf = (windowMs: number, at: number) => {
142
+ const windowAt = new Date(Math.floor(at / windowMs) * windowMs);
143
+ const resetAt = new Date(windowAt.getTime() + windowMs);
144
+ return { windowAt, resetAt, retryAfter: Math.max(1, Math.ceil((resetAt.getTime() - at) / 1000)) };
145
+ };
146
+
147
+ async function spend(
148
+ key: string,
149
+ rule: { limit: number; windowMs: number; failClosed?: boolean },
150
+ amount: number,
151
+ at: number,
152
+ ): Promise<RateLimitResult> {
153
+ const { windowAt, resetAt, retryAfter } = windowOf(rule.windowMs, at);
154
+ const stored = storedKey(key, maxKeyLength);
155
+ try {
156
+ const count = await store.increment(stored, windowAt, amount);
157
+ const allowed = count <= rule.limit;
158
+ return {
159
+ allowed,
160
+ remaining: Math.max(0, rule.limit - count),
161
+ limit: rule.limit,
162
+ resetAt,
163
+ retryAfter,
164
+ ...(allowed ? {} : { refusedBy: "caller" as const }),
165
+ };
166
+ } catch (error) {
167
+ logger.error(`[rate-limit] failing ${rule.failClosed ? "closed" : "open"} for ${stored}`, error);
168
+ return {
169
+ allowed: !rule.failClosed,
170
+ remaining: rule.failClosed ? 0 : rule.limit,
171
+ limit: rule.limit,
172
+ resetAt,
173
+ retryAfter,
174
+ failed: true,
175
+ ...(rule.failClosed ? { refusedBy: "caller" as const } : {}),
176
+ };
177
+ }
178
+ }
179
+
180
+ async function read(key: string, rule: { limit: number; windowMs: number; failClosed?: boolean }, at: number) {
181
+ const { windowAt, resetAt } = windowOf(rule.windowMs, at);
182
+ try {
183
+ const count = await store.read(storedKey(key, maxKeyLength), windowAt);
184
+ const used = Math.min(count, rule.limit);
185
+ return { used, limit: rule.limit, remaining: rule.limit - used, resetAt };
186
+ } catch (error) {
187
+ logger.error(`[rate-limit] could not read ${storedKey(key, maxKeyLength)}`, error);
188
+ const used = rule.failClosed ? rule.limit : 0;
189
+ return { used, limit: rule.limit, remaining: rule.limit - used, resetAt, failed: true as const };
190
+ }
191
+ }
192
+
193
+ function maybePrune() {
194
+ const auto = options.autoPrune;
195
+ if (!auto || !(random() < auto.chance)) return;
196
+ const task = async () => {
197
+ try {
198
+ await prune({ olderThanMs: auto.olderThanMs, batch: auto.batch });
199
+ } catch (error) {
200
+ logger.error("[rate-limit] pruning old windows failed", error);
201
+ }
202
+ };
203
+ if (auto.schedule) auto.schedule(task);
204
+ else void task();
205
+ }
206
+
207
+ async function prune(pruneOptions: PruneOptions = {}) {
208
+ const olderThanMs = pruneOptions.olderThanMs ?? DEFAULT_RATE_LIMIT_RETENTION_MS;
209
+ const batch = pruneOptions.batch ?? DEFAULT_RATE_LIMIT_PRUNE_BATCH;
210
+ if (!Number.isFinite(olderThanMs) || olderThanMs < 60 * 60 * 1000) {
211
+ throw new Error("[rate-limit] prune's olderThanMs must be at least an hour.");
212
+ }
213
+ if (!Number.isInteger(batch) || batch < 1) throw new Error("[rate-limit] prune's batch must be at least 1.");
214
+ return store.prune(new Date(now() - olderThanMs), batch);
215
+ }
216
+
217
+ return {
218
+ async consume(key, rule, amount = 1) {
219
+ const problems = ruleProblems(rule);
220
+ if (problems.length) throw new Error(`[rate-limit] ${problems.join("; ")}`);
221
+ if (!Number.isInteger(amount) || amount < 1)
222
+ throw new Error("[rate-limit] amount must be a whole number, at least 1.");
223
+ const at = now();
224
+ const own = await spend(key, rule, amount, at);
225
+ if (!own.allowed || !rule.everyone) {
226
+ if (own.allowed && !own.failed) maybePrune();
227
+ return own;
228
+ }
229
+ const everyone = await spend(
230
+ rule.everyone.key,
231
+ { limit: rule.everyone.limit, windowMs: rule.everyone.windowMs ?? rule.windowMs, failClosed: rule.failClosed },
232
+ amount,
233
+ at,
234
+ );
235
+ if (!everyone.allowed) return { ...everyone, refusedBy: "everyone" };
236
+ if (!own.failed && !everyone.failed) maybePrune();
237
+ return everyone.failed && !own.failed ? { ...own, failed: true } : own;
238
+ },
239
+
240
+ async usage(key, rule) {
241
+ const problems = ruleProblems(rule);
242
+ if (problems.length) throw new Error(`[rate-limit] ${problems.join("; ")}`);
243
+ const at = now();
244
+ const own = await read(key, rule, at);
245
+ if (!rule.everyone) return own;
246
+ const everyone = await read(
247
+ rule.everyone.key,
248
+ { limit: rule.everyone.limit, windowMs: rule.everyone.windowMs ?? rule.windowMs, failClosed: rule.failClosed },
249
+ at,
250
+ );
251
+ const { failed: everyoneFailed, ...ceiling } = everyone;
252
+ return { ...own, everyone: ceiling, ...(everyoneFailed ? { failed: true as const } : {}) };
253
+ },
254
+
255
+ privateKey(prefix, ...parts) {
256
+ if (!options.secret) throw new Error("[rate-limit] privateKey needs the limiter's `secret`.");
257
+ return privateKey(options.secret, prefix, ...parts);
258
+ },
259
+
260
+ prune,
261
+ };
262
+ }
263
+
264
+ /**
265
+ * The standard headers for a limited response: `x-ratelimit-limit`, `-remaining` and `-reset` (epoch seconds), and
266
+ * `retry-after` (seconds) when refused.
267
+ */
268
+ export function rateLimitHeaders(result: RateLimitResult): Record<string, string> {
269
+ const headers: Record<string, string> = {
270
+ "x-ratelimit-limit": String(result.limit),
271
+ "x-ratelimit-remaining": String(result.remaining),
272
+ "x-ratelimit-reset": String(Math.floor(result.resetAt.getTime() / 1000)),
273
+ };
274
+ if (!result.allowed) headers["retry-after"] = String(result.retryAfter);
275
+ return headers;
276
+ }
@@ -0,0 +1,12 @@
1
+ /**
2
+ * `@connextar/house/rate-limit/prisma` — the store over the `RateLimit` model every app has. Imports nothing: the
3
+ * Prisma client is passed in.
4
+ */
5
+ export {
6
+ incrementSql,
7
+ prismaRateLimitStore,
8
+ type PrismaRateLimitStoreOptions,
9
+ type RateLimitCalls,
10
+ type RateLimitDelegate,
11
+ type RateLimitSql,
12
+ } from "./prisma.js";
@@ -0,0 +1,157 @@
1
+ import type { RateLimitStore } from "./store.js";
2
+
3
+ /**
4
+ * The `RateLimitStore` over the `RateLimit` model every app already has — so adopting the limiter needs no migration.
5
+ *
6
+ * The shape is one everywhere: `key`, `windowAt` (`window_at`), `count`, a string `id` with no database default, unique
7
+ * on `(key, windowAt)` under Prisma's name `key_windowAt`. The exceptions are configuration: AltEd's `key` is `TEXT`
8
+ * where the rest are `VARCHAR(200)` (the limiter hashes long keys either way); PharmaLine, Tracker C and the Stripe
9
+ * gateway carry a nullable `last_request` for Better Auth's old get/set rows, left NULL here; Canisters' table is
10
+ * `"RateLimit"` with a `"windowAt"` column; MAS keeps the model in MongoDB, where there is no SQL.
11
+ *
12
+ * **On Postgres, pass `sql`** (the Prisma client) and the count is one statement:
13
+ * `INSERT … ON CONFLICT ("key", "window_at") DO UPDATE SET "count" = "count" + n RETURNING "count"`. Atomic, and it never
14
+ * raises. Every app's own copy used `upsert` and, when two requests raced to create the same window, caught the unique
15
+ * violation and retried with `update` — the job claims' P2002 lesson again: Postgres logs each of those as an error.
16
+ * **Without `sql`** (MongoDB) it is the apps' upsert and retry.
17
+ *
18
+ * Typed structurally, so the package imports no Prisma: `runs: prisma.rateLimit`, `sql: prisma`.
19
+ */
20
+
21
+ /** The calls the store makes on `prisma.rateLimit`, exactly — what a test's stand-in implements. */
22
+ export interface RateLimitCalls {
23
+ upsert(args: {
24
+ where: Record<string, { key: string; windowAt: Date }>;
25
+ create: { key: string; windowAt: Date; count: number };
26
+ update: { count: { increment: number } };
27
+ select: { count: true };
28
+ }): Promise<{ count: number }>;
29
+ update(args: {
30
+ where: Record<string, { key: string; windowAt: Date }>;
31
+ data: { count: { increment: number } };
32
+ select: { count: true };
33
+ }): Promise<{ count: number }>;
34
+ findUnique(args: {
35
+ where: Record<string, { key: string; windowAt: Date }>;
36
+ select: { count: true };
37
+ }): Promise<{ count: number } | null>;
38
+ findMany(args: {
39
+ where: { windowAt: { lt: Date } };
40
+ select: { id: true };
41
+ orderBy: { windowAt: "asc" };
42
+ take: number;
43
+ }): Promise<{ id: string }[]>;
44
+ deleteMany(args: { where: { id: { in: string[] } } }): Promise<{ count: number }>;
45
+ }
46
+
47
+ /**
48
+ * `prisma.rateLimit`, as the option accepts it. Prisma's methods are generic over their arguments
49
+ * (`<T extends RateLimitUpsertArgs>(args: SelectSubset<T, …>)`), which no fixed argument type matches, on Prisma 6 or
50
+ * 7; a method that takes `never` accepts every one of them. The store calls it as `RateLimitCalls`.
51
+ */
52
+ export type RateLimitDelegate = { [K in keyof RateLimitCalls]: (args: never) => PromiseLike<unknown> };
53
+
54
+ export interface RateLimitSql {
55
+ $queryRawUnsafe<T = unknown>(query: string, ...values: unknown[]): Promise<T>;
56
+ }
57
+
58
+ export interface PrismaRateLimitStoreOptions {
59
+ /** `prisma.rateLimit`. */
60
+ model: RateLimitDelegate;
61
+ /** `prisma`, on Postgres: the count becomes one `INSERT … ON CONFLICT`. Leave it out on MongoDB. */
62
+ sql?: RateLimitSql;
63
+ /** The table and columns in the database, for `sql`. Default `rate_limit` with `id`, `key`, `window_at`, `count`. */
64
+ table?: string;
65
+ columns?: Partial<Record<"id" | "key" | "windowAt" | "count", string>>;
66
+ /** Prisma's name for the `(key, windowAt)` unique. Default `key_windowAt`. */
67
+ uniqueName?: string;
68
+ /** For the new row's `id`. Default a random UUID — the column is text; Prisma's cuid is not needed to read it. */
69
+ newId?: () => string;
70
+ }
71
+
72
+ const IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_]{0,62}$/;
73
+
74
+ function quoted(name: string): string {
75
+ if (!IDENTIFIER.test(name)) throw new Error(`[rate-limit] "${name}" is not a plain SQL identifier.`);
76
+ return `"${name}"`;
77
+ }
78
+
79
+ /**
80
+ * The statement, for a table that is not the reference one. The window goes in as an ISO string and is turned into a
81
+ * UTC timestamp in SQL, as Prisma stores `DateTime` — so a database session in another time zone cannot shift it.
82
+ */
83
+ export function incrementSql(table = "rate_limit", columns: PrismaRateLimitStoreOptions["columns"] = {}): string {
84
+ const t = quoted(table);
85
+ const id = quoted(columns.id ?? "id");
86
+ const key = quoted(columns.key ?? "key");
87
+ const windowAt = quoted(columns.windowAt ?? "window_at");
88
+ const count = quoted(columns.count ?? "count");
89
+ return `INSERT INTO ${t} (${id}, ${key}, ${windowAt}, ${count})
90
+ VALUES ($1, $2, ($3::timestamptz AT TIME ZONE 'UTC'), $4)
91
+ ON CONFLICT (${key}, ${windowAt}) DO UPDATE SET ${count} = ${t}.${count} + EXCLUDED.${count}
92
+ RETURNING ${count} AS "count"`;
93
+ }
94
+
95
+ export function prismaRateLimitStore(options: PrismaRateLimitStoreOptions): RateLimitStore {
96
+ const model = options.model as unknown as RateLimitCalls;
97
+ const { sql } = options;
98
+ const unique = options.uniqueName ?? "key_windowAt";
99
+ const newId = options.newId ?? (() => globalThis.crypto.randomUUID());
100
+ const statement = sql ? incrementSql(options.table, options.columns) : null;
101
+ const where = (key: string, windowAt: Date) => ({ [unique]: { key, windowAt } });
102
+
103
+ return {
104
+ async increment(key, windowAt, amount) {
105
+ if (sql && statement) {
106
+ const rows = await sql.$queryRawUnsafe<{ count: number | bigint }[]>(
107
+ statement,
108
+ newId(),
109
+ key,
110
+ windowAt.toISOString(),
111
+ amount,
112
+ );
113
+ const count = rows[0]?.count;
114
+ if (count === undefined) throw new Error("[rate-limit] the count was not returned.");
115
+ return Number(count);
116
+ }
117
+ try {
118
+ const row = await model.upsert({
119
+ where: where(key, windowAt),
120
+ create: { key, windowAt, count: amount },
121
+ update: { count: { increment: amount } },
122
+ select: { count: true },
123
+ });
124
+ return row.count;
125
+ } catch (error) {
126
+ // Two first requests in one window race to create it; the loser's retry lands on the update.
127
+ try {
128
+ const row = await model.update({
129
+ where: where(key, windowAt),
130
+ data: { count: { increment: amount } },
131
+ select: { count: true },
132
+ });
133
+ return row.count;
134
+ } catch {
135
+ throw error;
136
+ }
137
+ }
138
+ },
139
+
140
+ async read(key, windowAt) {
141
+ const row = await model.findUnique({ where: where(key, windowAt), select: { count: true } });
142
+ return row?.count ?? 0;
143
+ },
144
+
145
+ async prune(before, limit) {
146
+ const rows = await model.findMany({
147
+ where: { windowAt: { lt: before } },
148
+ select: { id: true },
149
+ orderBy: { windowAt: "asc" },
150
+ take: limit,
151
+ });
152
+ if (!rows.length) return 0;
153
+ const { count } = await model.deleteMany({ where: { id: { in: rows.map((row) => row.id) } } });
154
+ return count;
155
+ },
156
+ };
157
+ }
@@ -0,0 +1,47 @@
1
+ /**
2
+ * Where windows are counted — the app's table, behind this interface, as `jobs` keeps its ledger.
3
+ *
4
+ * The package owns no schema. Ten apps already have a `rate_limit` table of one shape (`key`, `window_at`, `count`,
5
+ * unique on the first two) and MAS keeps the same model in MongoDB; `@connextar/house/rate-limit/prisma` is the
6
+ * adapter for all of them, so adopting the limiter needs no migration.
7
+ */
8
+ export interface RateLimitStore {
9
+ /**
10
+ * Add `amount` to the window `(key, windowAt)`, creating it at `amount`, and resolve with its count afterwards —
11
+ * in one atomic step, so two requests at once can never both read the count before either adds to it.
12
+ */
13
+ increment(key: string, windowAt: Date, amount: number): Promise<number>;
14
+ /** The window's count, or 0 when there is none. Never writes. */
15
+ read(key: string, windowAt: Date): Promise<number>;
16
+ /** Delete at most `limit` windows that started before `before`, oldest first, and resolve with how many went. */
17
+ prune(before: Date, limit: number): Promise<number>;
18
+ }
19
+
20
+ /** The whole contract in memory — for tests, the app's included. */
21
+ export function memoryRateLimitStore(): RateLimitStore & {
22
+ windows: Map<string, { key: string; windowAt: Date; count: number }>;
23
+ } {
24
+ const windows = new Map<string, { key: string; windowAt: Date; count: number }>();
25
+ const id = (key: string, windowAt: Date) => `${windowAt.getTime()}\u0000${key}`;
26
+ return {
27
+ windows,
28
+ async increment(key, windowAt, amount) {
29
+ const at = id(key, windowAt);
30
+ const row = windows.get(at) ?? { key, windowAt, count: 0 };
31
+ row.count += amount;
32
+ windows.set(at, row);
33
+ return row.count;
34
+ },
35
+ async read(key, windowAt) {
36
+ return windows.get(id(key, windowAt))?.count ?? 0;
37
+ },
38
+ async prune(before, limit) {
39
+ const doomed = [...windows.entries()]
40
+ .filter(([, row]) => row.windowAt.getTime() < before.getTime())
41
+ .sort(([, a], [, b]) => a.windowAt.getTime() - b.windowAt.getTime())
42
+ .slice(0, limit);
43
+ for (const [at] of doomed) windows.delete(at);
44
+ return doomed.length;
45
+ },
46
+ };
47
+ }