@wwchen/stack 0.6.4 → 0.7.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +9 -8
- package/dist/auth/better-auth/index.d.ts +2 -305
- package/dist/auth/better-auth/index.js +2 -215
- package/dist/auth/index.d.ts +2 -47
- package/dist/auth/index.js +2 -106
- package/dist/auth/proxy.d.ts +2 -12
- package/dist/auth/proxy.js +2 -37
- package/dist/cli/context.d.ts +5 -0
- package/dist/cli/context.js +3 -0
- package/dist/cli/db.d.ts +3 -0
- package/dist/cli/db.js +26 -0
- package/dist/cli/index.js +13 -1
- package/dist/cli/migrate-suite.d.ts +2 -0
- package/dist/cli/migrate-suite.js +787 -0
- package/dist/connections/index.js +1 -1
- package/dist/connections/table.d.ts +1 -1
- package/dist/db/schema-changes.d.ts +13 -0
- package/dist/db/schema-changes.js +99 -0
- package/dist/mail/index.d.ts +4 -38
- package/dist/mail/index.js +4 -92
- package/dist/next/api.d.ts +1 -2
- package/package.json +15 -9
- package/dist/auth/better-auth/tables.d.ts +0 -628
- package/dist/auth/better-auth/tables.js +0 -67
- package/dist/auth/better-auth/users.d.ts +0 -22
- package/dist/auth/better-auth/users.js +0 -122
- package/dist/auth/safe-next.d.ts +0 -11
- package/dist/auth/safe-next.js +0 -30
- package/dist/auth/types.d.ts +0 -46
- package/dist/auth/types.js +0 -4
- package/dist/http/client-ip.d.ts +0 -6
- package/dist/http/client-ip.js +0 -21
- package/dist/http/rate-limit.d.ts +0 -28
- package/dist/http/rate-limit.js +0 -67
|
@@ -1,22 +0,0 @@
|
|
|
1
|
-
import type { NodePgDatabase } from "drizzle-orm/node-postgres";
|
|
2
|
-
import type { AuthProvider } from "../types.ts";
|
|
3
|
-
import type { AuthTables } from "./tables.ts";
|
|
4
|
-
/**
|
|
5
|
-
* Who gets in. Sign-in never creates a user, so a person exists because an admin added their email here (from a dashboard, or `stack user:create`); they then sign in with a magic link or Google like anyone else. Removing a person deletes their user row, sessions and accounts in one transaction, so a cookie they still hold stops working on their next request.
|
|
6
|
-
*
|
|
7
|
-
* The app always has an admin once it has one: any change that would leave none is refused inside the transaction that holds a lock on the admin rows, so two concurrent demotions cannot both succeed.
|
|
8
|
-
*/
|
|
9
|
-
export declare class DuplicateUserError extends Error {
|
|
10
|
-
constructor(email: string);
|
|
11
|
-
}
|
|
12
|
-
export declare class LastAdminError extends Error {
|
|
13
|
-
constructor();
|
|
14
|
-
}
|
|
15
|
-
export declare class UserNotFoundError extends Error {
|
|
16
|
-
constructor();
|
|
17
|
-
}
|
|
18
|
-
/** Trimmed and lower-cased: the one form an email is stored and looked up in. */
|
|
19
|
-
export declare function normaliseEmail(email: string): string;
|
|
20
|
-
type Database = NodePgDatabase<any>;
|
|
21
|
-
export declare function createUsers(db: Database, tables: AuthTables): AuthProvider["users"];
|
|
22
|
-
export {};
|
|
@@ -1,122 +0,0 @@
|
|
|
1
|
-
import { randomUUID } from "node:crypto";
|
|
2
|
-
import { asc, eq } from "drizzle-orm";
|
|
3
|
-
import { z } from "zod";
|
|
4
|
-
/**
|
|
5
|
-
* Who gets in. Sign-in never creates a user, so a person exists because an admin added their email here (from a dashboard, or `stack user:create`); they then sign in with a magic link or Google like anyone else. Removing a person deletes their user row, sessions and accounts in one transaction, so a cookie they still hold stops working on their next request.
|
|
6
|
-
*
|
|
7
|
-
* The app always has an admin once it has one: any change that would leave none is refused inside the transaction that holds a lock on the admin rows, so two concurrent demotions cannot both succeed.
|
|
8
|
-
*/
|
|
9
|
-
export class DuplicateUserError extends Error {
|
|
10
|
-
constructor(email) {
|
|
11
|
-
super(`A user with the email ${email} already exists`);
|
|
12
|
-
this.name = "DuplicateUserError";
|
|
13
|
-
}
|
|
14
|
-
}
|
|
15
|
-
export class LastAdminError extends Error {
|
|
16
|
-
constructor() {
|
|
17
|
-
super("There must be at least one admin");
|
|
18
|
-
this.name = "LastAdminError";
|
|
19
|
-
}
|
|
20
|
-
}
|
|
21
|
-
export class UserNotFoundError extends Error {
|
|
22
|
-
constructor() {
|
|
23
|
-
super("User not found");
|
|
24
|
-
this.name = "UserNotFoundError";
|
|
25
|
-
}
|
|
26
|
-
}
|
|
27
|
-
/** Trimmed and lower-cased: the one form an email is stored and looked up in. */
|
|
28
|
-
export function normaliseEmail(email) {
|
|
29
|
-
return email.trim().toLowerCase();
|
|
30
|
-
}
|
|
31
|
-
const emailSchema = z.email();
|
|
32
|
-
const uuidSchema = z.uuid();
|
|
33
|
-
const toRole = (role) => (role === "admin" ? "admin" : "user");
|
|
34
|
-
export function createUsers(db, tables) {
|
|
35
|
-
const { appUser, session, account } = tables;
|
|
36
|
-
const columns = {
|
|
37
|
-
id: appUser.id,
|
|
38
|
-
email: appUser.email,
|
|
39
|
-
name: appUser.name,
|
|
40
|
-
role: appUser.role,
|
|
41
|
-
createdAt: appUser.createdAt,
|
|
42
|
-
};
|
|
43
|
-
const toAppUser = (row) => ({
|
|
44
|
-
...row,
|
|
45
|
-
role: toRole(row.role),
|
|
46
|
-
});
|
|
47
|
-
/** Locks every admin row for the rest of the transaction and returns their ids. */
|
|
48
|
-
async function lockAdmins(tx) {
|
|
49
|
-
const admins = await tx
|
|
50
|
-
.select({ id: appUser.id })
|
|
51
|
-
.from(appUser)
|
|
52
|
-
.where(eq(appUser.role, "admin"))
|
|
53
|
-
.for("update");
|
|
54
|
-
return admins.map((row) => row.id);
|
|
55
|
-
}
|
|
56
|
-
/** The target row, locked; `UserNotFoundError` when there is none (or the id is not a uuid). */
|
|
57
|
-
async function lockTarget(tx, userId) {
|
|
58
|
-
if (!uuidSchema.safeParse(userId).success)
|
|
59
|
-
throw new UserNotFoundError();
|
|
60
|
-
const [target] = await tx
|
|
61
|
-
.select({ id: appUser.id })
|
|
62
|
-
.from(appUser)
|
|
63
|
-
.where(eq(appUser.id, userId))
|
|
64
|
-
.for("update");
|
|
65
|
-
if (!target)
|
|
66
|
-
throw new UserNotFoundError();
|
|
67
|
-
}
|
|
68
|
-
return {
|
|
69
|
-
async add(rawEmail, role = "user") {
|
|
70
|
-
const email = normaliseEmail(rawEmail);
|
|
71
|
-
if (!emailSchema.safeParse(email).success) {
|
|
72
|
-
throw new Error(`"${rawEmail}" is not a valid email address`);
|
|
73
|
-
}
|
|
74
|
-
const [inserted] = await db
|
|
75
|
-
.insert(appUser)
|
|
76
|
-
.values({
|
|
77
|
-
id: randomUUID(),
|
|
78
|
-
name: email.split("@")[0],
|
|
79
|
-
email,
|
|
80
|
-
// The admin vouches for the address by adding it; signing in proves it on first use.
|
|
81
|
-
emailVerified: true,
|
|
82
|
-
role,
|
|
83
|
-
})
|
|
84
|
-
.onConflictDoNothing({ target: appUser.email })
|
|
85
|
-
.returning(columns);
|
|
86
|
-
if (!inserted)
|
|
87
|
-
throw new DuplicateUserError(email);
|
|
88
|
-
return toAppUser(inserted);
|
|
89
|
-
},
|
|
90
|
-
async remove(userId) {
|
|
91
|
-
await db.transaction(async (tx) => {
|
|
92
|
-
const admins = await lockAdmins(tx);
|
|
93
|
-
await lockTarget(tx, userId);
|
|
94
|
-
if (admins.includes(userId) && admins.length <= 1)
|
|
95
|
-
throw new LastAdminError();
|
|
96
|
-
// The foreign keys cascade these too; deleting them by name keeps the guarantee — no session or linked account outlives the person — independent of the app's constraints.
|
|
97
|
-
await tx.delete(session).where(eq(session.userId, userId));
|
|
98
|
-
await tx.delete(account).where(eq(account.userId, userId));
|
|
99
|
-
await tx.delete(appUser).where(eq(appUser.id, userId));
|
|
100
|
-
});
|
|
101
|
-
},
|
|
102
|
-
async setRole(userId, role) {
|
|
103
|
-
await db.transaction(async (tx) => {
|
|
104
|
-
const admins = await lockAdmins(tx);
|
|
105
|
-
await lockTarget(tx, userId);
|
|
106
|
-
const isAdmin = admins.includes(userId);
|
|
107
|
-
if ((role === "admin") === isAdmin)
|
|
108
|
-
return;
|
|
109
|
-
if (isAdmin && admins.length <= 1)
|
|
110
|
-
throw new LastAdminError();
|
|
111
|
-
await tx.update(appUser).set({ role, updatedAt: new Date() }).where(eq(appUser.id, userId));
|
|
112
|
-
});
|
|
113
|
-
},
|
|
114
|
-
async list() {
|
|
115
|
-
const rows = await db
|
|
116
|
-
.select(columns)
|
|
117
|
-
.from(appUser)
|
|
118
|
-
.orderBy(asc(appUser.createdAt), asc(appUser.email));
|
|
119
|
-
return rows.map(toAppUser);
|
|
120
|
-
},
|
|
121
|
-
};
|
|
122
|
-
}
|
package/dist/auth/safe-next.d.ts
DELETED
|
@@ -1,11 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Where to send someone after signing in, from a `?next=` they could have been handed by anyone. Only a path on this site is kept; anything else becomes `fallback`, so a sign-in link can never be turned into a redirect to another origin.
|
|
3
|
-
*
|
|
4
|
-
* Kept: a string starting with a single `/`. Refused, as well as anything that is not a string:
|
|
5
|
-
* - `//host` and `/\host`: browsers read both as protocol-relative URLs to another host;
|
|
6
|
-
* - any backslash: the URL parser turns it into `/`;
|
|
7
|
-
* - control characters: the URL parser strips tabs and newlines, so `/\t/host` becomes `//host`;
|
|
8
|
-
* - `https:`, `javascript:` and every other scheme: they do not start with `/`.
|
|
9
|
-
* Then the path is resolved as a browser would, which removes dot segments (`.`, `..`, `%2e`): it must stay on the origin it is resolved against, and its resolved path must not itself start with `//` — `/..//host` and `/%2e//host` resolve to `//host`, which a router that writes the path back would follow off-site. What is returned is that resolved path, query and fragment, so a caller only ever passes on what was checked.
|
|
10
|
-
*/
|
|
11
|
-
export declare function safeNext(raw: unknown, fallback?: string): string;
|
package/dist/auth/safe-next.js
DELETED
|
@@ -1,30 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Where to send someone after signing in, from a `?next=` they could have been handed by anyone. Only a path on this site is kept; anything else becomes `fallback`, so a sign-in link can never be turned into a redirect to another origin.
|
|
3
|
-
*
|
|
4
|
-
* Kept: a string starting with a single `/`. Refused, as well as anything that is not a string:
|
|
5
|
-
* - `//host` and `/\host`: browsers read both as protocol-relative URLs to another host;
|
|
6
|
-
* - any backslash: the URL parser turns it into `/`;
|
|
7
|
-
* - control characters: the URL parser strips tabs and newlines, so `/\t/host` becomes `//host`;
|
|
8
|
-
* - `https:`, `javascript:` and every other scheme: they do not start with `/`.
|
|
9
|
-
* Then the path is resolved as a browser would, which removes dot segments (`.`, `..`, `%2e`): it must stay on the origin it is resolved against, and its resolved path must not itself start with `//` — `/..//host` and `/%2e//host` resolve to `//host`, which a router that writes the path back would follow off-site. What is returned is that resolved path, query and fragment, so a caller only ever passes on what was checked.
|
|
10
|
-
*/
|
|
11
|
-
export function safeNext(raw, fallback = "/") {
|
|
12
|
-
if (typeof raw !== "string")
|
|
13
|
-
return fallback;
|
|
14
|
-
if (!raw.startsWith("/") || raw.startsWith("//"))
|
|
15
|
-
return fallback;
|
|
16
|
-
// biome-ignore lint/suspicious/noControlCharactersInRegex: refusing control characters is the point.
|
|
17
|
-
if (/[\\\u0000-\u001f\u007f]/.test(raw))
|
|
18
|
-
return fallback;
|
|
19
|
-
const base = "http://same-site.invalid";
|
|
20
|
-
let url;
|
|
21
|
-
try {
|
|
22
|
-
url = new URL(raw, base);
|
|
23
|
-
}
|
|
24
|
-
catch {
|
|
25
|
-
return fallback;
|
|
26
|
-
}
|
|
27
|
-
if (url.origin !== base || url.pathname.startsWith("//"))
|
|
28
|
-
return fallback;
|
|
29
|
-
return `${url.pathname}${url.search}${url.hash}`;
|
|
30
|
-
}
|
package/dist/auth/types.d.ts
DELETED
|
@@ -1,46 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* The provider-agnostic auth types. An app only ever sees these: whichever provider runs sign-in, a session's user is an `app_user` row, and a sign-in answers with a short, normalised code.
|
|
3
|
-
*/
|
|
4
|
-
/** The two roles. Granted by an admin, never assumed: a user with no admin role reads as `user`. */
|
|
5
|
-
export type Role = "admin" | "user";
|
|
6
|
-
export type AppUser = {
|
|
7
|
-
id: string;
|
|
8
|
-
email: string;
|
|
9
|
-
name: string | null;
|
|
10
|
-
role: Role;
|
|
11
|
-
createdAt: Date;
|
|
12
|
-
};
|
|
13
|
-
export type Session = {
|
|
14
|
-
user: AppUser;
|
|
15
|
-
expiresAt: Date;
|
|
16
|
-
};
|
|
17
|
-
export type AuthErrorCode = "invalid_email" | "rate_limited" | "unavailable";
|
|
18
|
-
export type AuthResult = {
|
|
19
|
-
ok: true;
|
|
20
|
-
redirect?: string;
|
|
21
|
-
} | {
|
|
22
|
-
ok: false;
|
|
23
|
-
code: AuthErrorCode;
|
|
24
|
-
};
|
|
25
|
-
export interface AuthProvider {
|
|
26
|
-
/** Serves the provider's routes: `app/api/auth/[...all]/route.ts`. */
|
|
27
|
-
handler(req: Request): Promise<Response>;
|
|
28
|
-
/** The session the request's cookies carry, or null. `Session.user` is an `app_user` row. */
|
|
29
|
-
getSession(headers: Headers): Promise<Session | null>;
|
|
30
|
-
signIn: {
|
|
31
|
-
/** Sends a sign-in link to an added user; answers the same for an address nobody added. */
|
|
32
|
-
magicLink(email: string, next: string): Promise<AuthResult>;
|
|
33
|
-
/** Starts an OAuth sign-in; `redirect` is the provider's URL. Never creates a user. */
|
|
34
|
-
oauth(providerId: string, next: string): Promise<AuthResult>;
|
|
35
|
-
};
|
|
36
|
-
signOut(headers: Headers): Promise<void>;
|
|
37
|
-
/** For adapters that need a verifier step in the proxy. */
|
|
38
|
-
proxy?(req: Request): Promise<Response | null>;
|
|
39
|
-
/** Invite-only user management: sign-in never creates a user, an admin adds them here. */
|
|
40
|
-
users: {
|
|
41
|
-
add(email: string, role?: Role): Promise<AppUser>;
|
|
42
|
-
remove(userId: string): Promise<void>;
|
|
43
|
-
setRole(userId: string, role: Role): Promise<void>;
|
|
44
|
-
list(): Promise<AppUser[]>;
|
|
45
|
-
};
|
|
46
|
-
}
|
package/dist/auth/types.js
DELETED
package/dist/http/client-ip.d.ts
DELETED
|
@@ -1,6 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Who the caller is, read from standard forwarded headers in this one place. No vendor-specific header (Cloudflare's, Vercel's) is read: the proxy in front of the app is infrastructure, and `X-Forwarded-For` already carries the value.
|
|
3
|
-
*
|
|
4
|
-
* The client is the first entry a trusted proxy did not add: with `hops` trusted proxies in front, the Nth-from-last entry in `X-Forwarded-For`. Trusting the *first* entry instead is the classic spoof — a caller can send any `X-Forwarded-For` they like, and only the entries the proxies themselves appended can be believed. Hence counting from the right. Vercel terminates the chain itself, so `hops` is 0 there.
|
|
5
|
-
*/
|
|
6
|
-
export declare function clientIp(headers: Headers, hops: number): string | null;
|
package/dist/http/client-ip.js
DELETED
|
@@ -1,21 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Who the caller is, read from standard forwarded headers in this one place. No vendor-specific header (Cloudflare's, Vercel's) is read: the proxy in front of the app is infrastructure, and `X-Forwarded-For` already carries the value.
|
|
3
|
-
*
|
|
4
|
-
* The client is the first entry a trusted proxy did not add: with `hops` trusted proxies in front, the Nth-from-last entry in `X-Forwarded-For`. Trusting the *first* entry instead is the classic spoof — a caller can send any `X-Forwarded-For` they like, and only the entries the proxies themselves appended can be believed. Hence counting from the right. Vercel terminates the chain itself, so `hops` is 0 there.
|
|
5
|
-
*/
|
|
6
|
-
export function clientIp(headers, hops) {
|
|
7
|
-
const forwarded = headers.get("x-forwarded-for");
|
|
8
|
-
if (forwarded !== null) {
|
|
9
|
-
const entries = forwarded
|
|
10
|
-
.split(",")
|
|
11
|
-
.map((entry) => entry.trim())
|
|
12
|
-
.filter((entry) => entry.length > 0);
|
|
13
|
-
if (entries.length > 0) {
|
|
14
|
-
// Clamped: a request that arrived with fewer hops than configured is not a reason to return nothing, and the left-most entry is the best remaining guess.
|
|
15
|
-
const index = Math.max(entries.length - 1 - hops, 0);
|
|
16
|
-
return entries[index];
|
|
17
|
-
}
|
|
18
|
-
}
|
|
19
|
-
// Standard, non-vendor fallback only.
|
|
20
|
-
return headers.get("x-real-ip") ?? null;
|
|
21
|
-
}
|
|
@@ -1,28 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Past this many buckets, a new one first sweeps out every expired bucket. A caller can invent paths (every `/api/auth/<anything>` is counted), so the store must not only grow; a live bucket is never swept, so sweeping cannot hand anyone a fresh budget.
|
|
3
|
-
*/
|
|
4
|
-
export declare const RATE_LIMIT_SWEEP_AT = 10000;
|
|
5
|
-
/**
|
|
6
|
-
* A sweep walks the whole store, and past the cap with every bucket live it frees nothing, so the next request would walk it again: at most one sweep per interval keeps that off every request.
|
|
7
|
-
*/
|
|
8
|
-
export declare const RATE_LIMIT_SWEEP_INTERVAL_MS: number;
|
|
9
|
-
export declare function rateLimitStoreSize(): number;
|
|
10
|
-
/** Test-only reset, so one case's bucket cannot decide the next one's outcome. */
|
|
11
|
-
export declare function resetRateLimits(): void;
|
|
12
|
-
export type RateLimitInput = {
|
|
13
|
-
/** What is being limited, e.g. `/api/auth/sign-in/magic-link`. Each path has its own budget. */
|
|
14
|
-
path: string;
|
|
15
|
-
/** The request's headers, for the client address. */
|
|
16
|
-
headers: Headers;
|
|
17
|
-
/** Requests allowed per caller per path per hour. `Infinity` never limits. */
|
|
18
|
-
limit: number;
|
|
19
|
-
/** Proxies in front of the app that append to `X-Forwarded-For`. */
|
|
20
|
-
trustedProxyHops: number;
|
|
21
|
-
now?: number;
|
|
22
|
-
};
|
|
23
|
-
/**
|
|
24
|
-
* Answers a **429 with `Retry-After`** when this caller has used up `limit` on `path` within the hour, and null — meaning "carry on" — every other time.
|
|
25
|
-
*
|
|
26
|
-
* Returning a Response rather than throwing keeps the decision at the edge: the caller writes `const limited = rateLimit(...); if (limited) return limited;`. The body is the `{ error: { code, message } }` envelope every API error uses.
|
|
27
|
-
*/
|
|
28
|
-
export declare function rateLimit(input: RateLimitInput): Response | null;
|
package/dist/http/rate-limit.js
DELETED
|
@@ -1,67 +0,0 @@
|
|
|
1
|
-
import { clientIp } from "./client-ip.js";
|
|
2
|
-
/**
|
|
3
|
-
* How often a caller may knock: a fixed hourly budget per client address per path.
|
|
4
|
-
*
|
|
5
|
-
* This is the stack's own limiter, independent of Better Auth's internal one, because sign-in runs in-process from server actions that no route limit sees. The app sets the budget; an infinite budget turns the limiter off and allocates nothing (development and tests then need no store).
|
|
6
|
-
*/
|
|
7
|
-
const WINDOW_MS = 60 * 60 * 1000;
|
|
8
|
-
/**
|
|
9
|
-
* Created lazily, so a process that never limits never allocates it.
|
|
10
|
-
*
|
|
11
|
-
* An in-process counter is correct for exactly **one** app instance: each serverless instance counts separately. That is tolerable for invite-only sign-in; scaling out for real means moving this to a shared store.
|
|
12
|
-
*/
|
|
13
|
-
let buckets = null;
|
|
14
|
-
/**
|
|
15
|
-
* Past this many buckets, a new one first sweeps out every expired bucket. A caller can invent paths (every `/api/auth/<anything>` is counted), so the store must not only grow; a live bucket is never swept, so sweeping cannot hand anyone a fresh budget.
|
|
16
|
-
*/
|
|
17
|
-
export const RATE_LIMIT_SWEEP_AT = 10_000;
|
|
18
|
-
/**
|
|
19
|
-
* A sweep walks the whole store, and past the cap with every bucket live it frees nothing, so the next request would walk it again: at most one sweep per interval keeps that off every request.
|
|
20
|
-
*/
|
|
21
|
-
export const RATE_LIMIT_SWEEP_INTERVAL_MS = 60 * 1000;
|
|
22
|
-
let lastSweep = Number.NEGATIVE_INFINITY;
|
|
23
|
-
function sweepExpired(store, now) {
|
|
24
|
-
if (now - lastSweep < RATE_LIMIT_SWEEP_INTERVAL_MS)
|
|
25
|
-
return;
|
|
26
|
-
lastSweep = now;
|
|
27
|
-
for (const [key, bucket] of store)
|
|
28
|
-
if (now >= bucket.resetAt)
|
|
29
|
-
store.delete(key);
|
|
30
|
-
}
|
|
31
|
-
export function rateLimitStoreSize() {
|
|
32
|
-
return buckets?.size ?? 0;
|
|
33
|
-
}
|
|
34
|
-
/** Test-only reset, so one case's bucket cannot decide the next one's outcome. */
|
|
35
|
-
export function resetRateLimits() {
|
|
36
|
-
buckets = null;
|
|
37
|
-
lastSweep = Number.NEGATIVE_INFINITY;
|
|
38
|
-
}
|
|
39
|
-
/**
|
|
40
|
-
* Answers a **429 with `Retry-After`** when this caller has used up `limit` on `path` within the hour, and null — meaning "carry on" — every other time.
|
|
41
|
-
*
|
|
42
|
-
* Returning a Response rather than throwing keeps the decision at the edge: the caller writes `const limited = rateLimit(...); if (limited) return limited;`. The body is the `{ error: { code, message } }` envelope every API error uses.
|
|
43
|
-
*/
|
|
44
|
-
export function rateLimit(input) {
|
|
45
|
-
if (!Number.isFinite(input.limit))
|
|
46
|
-
return null;
|
|
47
|
-
const caller = clientIp(input.headers, input.trustedProxyHops) ?? "unknown";
|
|
48
|
-
const now = input.now ?? Date.now();
|
|
49
|
-
buckets ??= new Map();
|
|
50
|
-
/**
|
|
51
|
-
* **One bucket per caller PER PATH, not per caller for the whole auth surface.** Following a magic link is a GET under the same prefix as asking for one; a shared bucket would let requesting ten links and clicking them lock the caller out for an hour.
|
|
52
|
-
*/
|
|
53
|
-
const key = `${caller}:${input.path}`;
|
|
54
|
-
const bucket = buckets.get(key);
|
|
55
|
-
if (bucket === undefined || now >= bucket.resetAt) {
|
|
56
|
-
if (bucket === undefined && buckets.size >= RATE_LIMIT_SWEEP_AT)
|
|
57
|
-
sweepExpired(buckets, now);
|
|
58
|
-
buckets.set(key, { count: 1, resetAt: now + WINDOW_MS });
|
|
59
|
-
return null;
|
|
60
|
-
}
|
|
61
|
-
if (bucket.count < input.limit) {
|
|
62
|
-
bucket.count += 1;
|
|
63
|
-
return null;
|
|
64
|
-
}
|
|
65
|
-
const retryAfterSeconds = Math.max(Math.ceil((bucket.resetAt - now) / 1000), 1);
|
|
66
|
-
return Response.json({ error: { code: "rate_limited", message: "Too many sign-in attempts. Try again later." } }, { status: 429, headers: { "retry-after": String(retryAfterSeconds) } });
|
|
67
|
-
}
|