@wwchen/stack 0.0.0-stage → 0.1.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.
- package/LICENSE +21 -0
- package/README.md +47 -2
- package/blocks/AGENTS.md +77 -0
- package/blocks/CLAUDE.md +113 -0
- package/blocks/env.example +32 -0
- package/blocks/gitignore +18 -0
- package/configs/biome.json +45 -0
- package/configs/tsconfig.next.json +22 -0
- package/dist/auth/better-auth/index.d.ts +316 -0
- package/dist/auth/better-auth/index.js +237 -0
- package/dist/auth/better-auth/tables.d.ts +628 -0
- package/dist/auth/better-auth/tables.js +74 -0
- package/dist/auth/better-auth/users.d.ts +27 -0
- package/dist/auth/better-auth/users.js +128 -0
- package/dist/auth/index.d.ts +58 -0
- package/dist/auth/index.js +120 -0
- package/dist/auth/proxy.d.ts +14 -0
- package/dist/auth/proxy.js +50 -0
- package/dist/auth/safe-next.d.ts +17 -0
- package/dist/auth/safe-next.js +36 -0
- package/dist/auth/types.d.ts +47 -0
- package/dist/auth/types.js +5 -0
- package/dist/cli/context.d.ts +38 -0
- package/dist/cli/context.js +43 -0
- package/dist/cli/index.d.ts +4 -0
- package/dist/cli/index.js +95 -0
- package/dist/cli/neon.d.ts +97 -0
- package/dist/cli/neon.js +334 -0
- package/dist/cli/sync-blocks.d.ts +16 -0
- package/dist/cli/sync-blocks.js +97 -0
- package/dist/cli/user-create.d.ts +2 -0
- package/dist/cli/user-create.js +35 -0
- package/dist/cli/vercel-build.d.ts +4 -0
- package/dist/cli/vercel-build.js +72 -0
- package/dist/configs/vitest.d.ts +4 -0
- package/dist/configs/vitest.js +50 -0
- package/dist/db/explaining-pool.d.ts +16 -0
- package/dist/db/explaining-pool.js +62 -0
- package/dist/db/index.d.ts +21 -0
- package/dist/db/index.js +36 -0
- package/dist/db/migration-status.d.ts +8 -0
- package/dist/db/migration-status.js +41 -0
- package/dist/db/target.d.ts +26 -0
- package/dist/db/target.js +72 -0
- package/dist/db/testing/index.d.ts +27 -0
- package/dist/db/testing/index.js +71 -0
- package/dist/db/testing/isolate.d.ts +1 -0
- package/dist/db/testing/isolate.js +4 -0
- package/dist/db/testing/pglite.d.ts +21 -0
- package/dist/db/testing/pglite.js +71 -0
- package/dist/env/define-env.d.ts +37 -0
- package/dist/env/define-env.js +134 -0
- package/dist/env/index.d.ts +3 -0
- package/dist/env/index.js +3 -0
- package/dist/env/load-env-file.d.ts +15 -0
- package/dist/env/load-env-file.js +52 -0
- package/dist/env/stack-env.d.ts +39 -0
- package/dist/env/stack-env.js +52 -0
- package/dist/env/testing.d.ts +8 -0
- package/dist/env/testing.js +16 -0
- package/dist/http/client-ip.d.ts +12 -0
- package/dist/http/client-ip.js +28 -0
- package/dist/http/guards.d.ts +17 -0
- package/dist/http/guards.js +57 -0
- package/dist/http/rate-limit.d.ts +34 -0
- package/dist/http/rate-limit.js +79 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -0
- package/dist/mail/index.d.ts +45 -0
- package/dist/mail/index.js +97 -0
- package/dist/next/api.d.ts +71 -0
- package/dist/next/api.js +118 -0
- package/dist/next/config.d.ts +8 -0
- package/dist/next/config.js +104 -0
- package/dist/next/cron.d.ts +11 -0
- package/dist/next/cron.js +33 -0
- package/dist/next/health.d.ts +19 -0
- package/dist/next/health.js +36 -0
- package/dist/next/index.d.ts +5 -0
- package/dist/next/index.js +4 -0
- package/dist/testing/next.d.ts +14 -0
- package/dist/testing/next.js +39 -0
- package/dist/ui/app.css +56 -0
- package/dist/ui/globals.css +152 -0
- package/dist/ui/icons.d.ts +17 -0
- package/dist/ui/icons.js +104 -0
- package/dist/ui/index.d.ts +33 -0
- package/dist/ui/index.js +41 -0
- package/dist/ui/theme.d.ts +18 -0
- package/dist/ui/theme.js +24 -0
- package/package.json +126 -4
|
@@ -0,0 +1,79 @@
|
|
|
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
|
|
6
|
+
* in-process from server actions that no route limit sees. The app sets the budget; an infinite
|
|
7
|
+
* budget turns the limiter off and allocates nothing (development and tests then need no store).
|
|
8
|
+
*/
|
|
9
|
+
const WINDOW_MS = 60 * 60 * 1000;
|
|
10
|
+
/**
|
|
11
|
+
* Created lazily, so a process that never limits never allocates it.
|
|
12
|
+
*
|
|
13
|
+
* An in-process counter is correct for exactly **one** app instance: each serverless instance
|
|
14
|
+
* counts separately. That is tolerable for invite-only sign-in; scaling out for real means moving
|
|
15
|
+
* this to a shared store.
|
|
16
|
+
*/
|
|
17
|
+
let buckets = null;
|
|
18
|
+
/**
|
|
19
|
+
* Past this many buckets, a new one first sweeps out every expired bucket. A caller can invent
|
|
20
|
+
* paths (every `/api/auth/<anything>` is counted), so the store must not only grow; a live bucket
|
|
21
|
+
* is never swept, so sweeping cannot hand anyone a fresh budget.
|
|
22
|
+
*/
|
|
23
|
+
export const RATE_LIMIT_SWEEP_AT = 10_000;
|
|
24
|
+
/**
|
|
25
|
+
* A sweep walks the whole store, and past the cap with every bucket live it frees nothing, so the
|
|
26
|
+
* next request would walk it again: at most one sweep per interval keeps that off every request.
|
|
27
|
+
*/
|
|
28
|
+
export const RATE_LIMIT_SWEEP_INTERVAL_MS = 60 * 1000;
|
|
29
|
+
let lastSweep = Number.NEGATIVE_INFINITY;
|
|
30
|
+
function sweepExpired(store, now) {
|
|
31
|
+
if (now - lastSweep < RATE_LIMIT_SWEEP_INTERVAL_MS)
|
|
32
|
+
return;
|
|
33
|
+
lastSweep = now;
|
|
34
|
+
for (const [key, bucket] of store)
|
|
35
|
+
if (now >= bucket.resetAt)
|
|
36
|
+
store.delete(key);
|
|
37
|
+
}
|
|
38
|
+
export function rateLimitStoreSize() {
|
|
39
|
+
return buckets?.size ?? 0;
|
|
40
|
+
}
|
|
41
|
+
/** Test-only reset, so one case's bucket cannot decide the next one's outcome. */
|
|
42
|
+
export function resetRateLimits() {
|
|
43
|
+
buckets = null;
|
|
44
|
+
lastSweep = Number.NEGATIVE_INFINITY;
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* Answers a **429 with `Retry-After`** when this caller has used up `limit` on `path` within the
|
|
48
|
+
* hour, and null — meaning "carry on" — every other time.
|
|
49
|
+
*
|
|
50
|
+
* Returning a Response rather than throwing keeps the decision at the edge: the caller writes
|
|
51
|
+
* `const limited = rateLimit(...); if (limited) return limited;`. The body is the
|
|
52
|
+
* `{ error: { code, message } }` envelope every API error uses.
|
|
53
|
+
*/
|
|
54
|
+
export function rateLimit(input) {
|
|
55
|
+
if (!Number.isFinite(input.limit))
|
|
56
|
+
return null;
|
|
57
|
+
const caller = clientIp(input.headers, input.trustedProxyHops) ?? "unknown";
|
|
58
|
+
const now = input.now ?? Date.now();
|
|
59
|
+
buckets ??= new Map();
|
|
60
|
+
/**
|
|
61
|
+
* **One bucket per caller PER PATH, not per caller for the whole auth surface.** Following a
|
|
62
|
+
* magic link is a GET under the same prefix as asking for one; a shared bucket would let
|
|
63
|
+
* requesting ten links and clicking them lock the caller out for an hour.
|
|
64
|
+
*/
|
|
65
|
+
const key = `${caller}:${input.path}`;
|
|
66
|
+
const bucket = buckets.get(key);
|
|
67
|
+
if (bucket === undefined || now >= bucket.resetAt) {
|
|
68
|
+
if (bucket === undefined && buckets.size >= RATE_LIMIT_SWEEP_AT)
|
|
69
|
+
sweepExpired(buckets, now);
|
|
70
|
+
buckets.set(key, { count: 1, resetAt: now + WINDOW_MS });
|
|
71
|
+
return null;
|
|
72
|
+
}
|
|
73
|
+
if (bucket.count < input.limit) {
|
|
74
|
+
bucket.count += 1;
|
|
75
|
+
return null;
|
|
76
|
+
}
|
|
77
|
+
const retryAfterSeconds = Math.max(Math.ceil((bucket.resetAt - now) / 1000), 1);
|
|
78
|
+
return Response.json({ error: { code: "rate_limited", message: "Too many sign-in attempts. Try again later." } }, { status: 429, headers: { "retry-after": String(retryAfterSeconds) } });
|
|
79
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
package/dist/index.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The one way an app sends mail, and sign-in is the only mail it sends.
|
|
3
|
+
*
|
|
4
|
+
* Production posts to Resend's HTTP API with `fetch` — no SDK, one request. Everywhere else nothing
|
|
5
|
+
* is sent: the first URL in the text is appended, one per line, to the sink file, which is what
|
|
6
|
+
* lets development, the tests and e2e sign in with no mail account and no network. The sink never
|
|
7
|
+
* holds the body or the address.
|
|
8
|
+
*/
|
|
9
|
+
export type Mail = {
|
|
10
|
+
to: string;
|
|
11
|
+
subject: string;
|
|
12
|
+
text: string;
|
|
13
|
+
};
|
|
14
|
+
export type Mailer = {
|
|
15
|
+
send(m: Mail): Promise<void>;
|
|
16
|
+
};
|
|
17
|
+
export type MailerOptions = {
|
|
18
|
+
mode: "resend";
|
|
19
|
+
apiKey: string;
|
|
20
|
+
from: string;
|
|
21
|
+
fetch?: typeof fetch;
|
|
22
|
+
} | {
|
|
23
|
+
mode: "sink";
|
|
24
|
+
sinkPath: string;
|
|
25
|
+
};
|
|
26
|
+
export declare function createMailer(opts: MailerOptions): Mailer;
|
|
27
|
+
/**
|
|
28
|
+
* Production sends through Resend; every other environment uses the sink.
|
|
29
|
+
*
|
|
30
|
+
* A production run without `RESEND_API_KEY` or `EMAIL_FROM` gets a mailer that refuses every send,
|
|
31
|
+
* naming the missing variable, rather than a throw here: `next build` evaluates the app's mail
|
|
32
|
+
* module with `NODE_ENV=production` and no secrets (a build skips env validation), and must not
|
|
33
|
+
* fail on it. A booted production app never gets this far without them: the stack's env requires
|
|
34
|
+
* both in production.
|
|
35
|
+
*/
|
|
36
|
+
export declare function mailerFromEnv(env: {
|
|
37
|
+
NODE_ENV: string;
|
|
38
|
+
RESEND_API_KEY?: string | undefined;
|
|
39
|
+
EMAIL_FROM?: string | undefined;
|
|
40
|
+
MAGIC_LINK_SINK_PATH: string;
|
|
41
|
+
}): Mailer;
|
|
42
|
+
/** How many links the sink holds now; take it before the request that should add one. */
|
|
43
|
+
export declare function countSinkLines(sinkPath: string): number;
|
|
44
|
+
/** The first link after line `afterLine` (a count from `countSinkLines`), polling until `timeoutMs`. */
|
|
45
|
+
export declare function waitForMagicLink(sinkPath: string, afterLine: number, timeoutMs?: number): Promise<string>;
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
import { appendFileSync, existsSync, readFileSync } from "node:fs";
|
|
2
|
+
const RESEND_ENDPOINT = "https://api.resend.com/emails";
|
|
3
|
+
export function createMailer(opts) {
|
|
4
|
+
if (opts.mode === "sink") {
|
|
5
|
+
const { sinkPath } = opts;
|
|
6
|
+
return {
|
|
7
|
+
async send(m) {
|
|
8
|
+
const url = m.text.match(/https?:\/\/\S+/)?.[0];
|
|
9
|
+
if (url)
|
|
10
|
+
appendFileSync(sinkPath, `${url}\n`, "utf8");
|
|
11
|
+
},
|
|
12
|
+
};
|
|
13
|
+
}
|
|
14
|
+
const { apiKey, from } = opts;
|
|
15
|
+
const doFetch = opts.fetch ?? fetch;
|
|
16
|
+
return {
|
|
17
|
+
async send(m) {
|
|
18
|
+
const response = await doFetch(RESEND_ENDPOINT, {
|
|
19
|
+
method: "POST",
|
|
20
|
+
headers: {
|
|
21
|
+
authorization: `Bearer ${apiKey}`,
|
|
22
|
+
"content-type": "application/json",
|
|
23
|
+
},
|
|
24
|
+
body: JSON.stringify({ from, to: m.to, subject: m.subject, text: m.text }),
|
|
25
|
+
// A hung Resend must not hold the sign-in request open.
|
|
26
|
+
signal: AbortSignal.timeout(10_000),
|
|
27
|
+
});
|
|
28
|
+
if (!response.ok) {
|
|
29
|
+
throw new Error(`Resend refused the message: ${response.status}${await refusalReason(response)}`);
|
|
30
|
+
}
|
|
31
|
+
},
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* Production sends through Resend; every other environment uses the sink.
|
|
36
|
+
*
|
|
37
|
+
* A production run without `RESEND_API_KEY` or `EMAIL_FROM` gets a mailer that refuses every send,
|
|
38
|
+
* naming the missing variable, rather than a throw here: `next build` evaluates the app's mail
|
|
39
|
+
* module with `NODE_ENV=production` and no secrets (a build skips env validation), and must not
|
|
40
|
+
* fail on it. A booted production app never gets this far without them: the stack's env requires
|
|
41
|
+
* both in production.
|
|
42
|
+
*/
|
|
43
|
+
export function mailerFromEnv(env) {
|
|
44
|
+
if (env.NODE_ENV !== "production") {
|
|
45
|
+
return createMailer({ mode: "sink", sinkPath: env.MAGIC_LINK_SINK_PATH });
|
|
46
|
+
}
|
|
47
|
+
const { RESEND_API_KEY: apiKey, EMAIL_FROM: from } = env;
|
|
48
|
+
if (!apiKey || !from) {
|
|
49
|
+
const missing = apiKey ? "EMAIL_FROM" : "RESEND_API_KEY";
|
|
50
|
+
return {
|
|
51
|
+
async send() {
|
|
52
|
+
throw new Error(`${missing} is required in production`);
|
|
53
|
+
},
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
return createMailer({ mode: "resend", apiKey, from });
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* Resend's `{ name, message }` as " name: message", or "" for any other body. The caller logs it,
|
|
60
|
+
* and Resend's message can echo the recipient, so every email address in it is redacted.
|
|
61
|
+
*/
|
|
62
|
+
async function refusalReason(response) {
|
|
63
|
+
try {
|
|
64
|
+
const body = await response.json();
|
|
65
|
+
if (typeof body !== "object" || body === null)
|
|
66
|
+
return "";
|
|
67
|
+
const { name, message } = body;
|
|
68
|
+
if (typeof name !== "string" || typeof message !== "string")
|
|
69
|
+
return "";
|
|
70
|
+
const redacted = message.replace(/[^\s()<>@,;:"]+@[^\s()<>@,;:"]+/g, "[email]").slice(0, 300);
|
|
71
|
+
return ` ${name}: ${redacted}`;
|
|
72
|
+
}
|
|
73
|
+
catch {
|
|
74
|
+
return "";
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
function sinkLines(sinkPath) {
|
|
78
|
+
if (!existsSync(sinkPath))
|
|
79
|
+
return [];
|
|
80
|
+
return readFileSync(sinkPath, "utf8").split("\n").filter(Boolean);
|
|
81
|
+
}
|
|
82
|
+
/** How many links the sink holds now; take it before the request that should add one. */
|
|
83
|
+
export function countSinkLines(sinkPath) {
|
|
84
|
+
return sinkLines(sinkPath).length;
|
|
85
|
+
}
|
|
86
|
+
/** The first link after line `afterLine` (a count from `countSinkLines`), polling until `timeoutMs`. */
|
|
87
|
+
export async function waitForMagicLink(sinkPath, afterLine, timeoutMs = 10_000) {
|
|
88
|
+
const deadline = Date.now() + timeoutMs;
|
|
89
|
+
for (;;) {
|
|
90
|
+
const line = sinkLines(sinkPath)[afterLine];
|
|
91
|
+
if (line)
|
|
92
|
+
return line;
|
|
93
|
+
if (Date.now() >= deadline)
|
|
94
|
+
throw new Error(`No magic link reached ${sinkPath}`);
|
|
95
|
+
await new Promise((resolve) => setTimeout(resolve, 100));
|
|
96
|
+
}
|
|
97
|
+
}
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import type { StackAuth } from "../auth/index.ts";
|
|
2
|
+
import type { Session } from "../auth/types.ts";
|
|
3
|
+
/**
|
|
4
|
+
* The shell every API route runs in: session, admin check, the request guards, the handler, and
|
|
5
|
+
* the envelope for whatever it throws. Written once so route files cannot drift on it.
|
|
6
|
+
*
|
|
7
|
+
* Every failure answers `{ error: { code, message } }`. An `ApiError` is answered as it says; that
|
|
8
|
+
* is how `readJson` reports the request body (400 `invalid_json`, 422 `invalid_input`). Anything
|
|
9
|
+
* else is a bug, even a SyntaxError or a ZodError from the route's own code, and becomes a 500 with
|
|
10
|
+
* a fixed message: what was thrown is logged for the operator and never sent to the caller.
|
|
11
|
+
*
|
|
12
|
+
* `CRON_SECRET` and `HEALTH_TOKEN` are never read here. This wrapper accepts a session and nothing
|
|
13
|
+
* else, so neither secret opens an API route.
|
|
14
|
+
*/
|
|
15
|
+
/** An error a route throws on purpose: its message is written for the caller and is sent as is. */
|
|
16
|
+
export declare class ApiError extends Error {
|
|
17
|
+
readonly status: number;
|
|
18
|
+
readonly code: string;
|
|
19
|
+
/** Per-field problems with the request, sent as `details`: paths and messages, never values. */
|
|
20
|
+
readonly details?: {
|
|
21
|
+
path: string;
|
|
22
|
+
message: string;
|
|
23
|
+
}[] | undefined;
|
|
24
|
+
constructor(status: number, code: string, message: string,
|
|
25
|
+
/** Per-field problems with the request, sent as `details`: paths and messages, never values. */
|
|
26
|
+
details?: {
|
|
27
|
+
path: string;
|
|
28
|
+
message: string;
|
|
29
|
+
}[] | undefined);
|
|
30
|
+
}
|
|
31
|
+
/** The row does not exist (or the caller may not know that it does). */
|
|
32
|
+
export declare class NotFoundError extends ApiError {
|
|
33
|
+
constructor(message?: string);
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* A path id that is not a uuid: the same 404 a missing row gets, but told apart from one so a
|
|
37
|
+
* route that surfaces its own not-found message never surfaces this one.
|
|
38
|
+
*/
|
|
39
|
+
export declare class PathIdError extends NotFoundError {
|
|
40
|
+
constructor();
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* A path id, or a `PathIdError` for the wrapper to answer. Anything that is not a uuid cannot name
|
|
44
|
+
* a row, so it is the same 404 a missing row gets, answered before the query: Postgres would
|
|
45
|
+
* otherwise reject the cast and turn a typo'd URL into a 500.
|
|
46
|
+
*/
|
|
47
|
+
export declare function requirePathId(value: string): string;
|
|
48
|
+
export declare function apiError(status: number, code: string, message: string, details?: {
|
|
49
|
+
path: string;
|
|
50
|
+
message: string;
|
|
51
|
+
}[]): Response;
|
|
52
|
+
/** What parses a body: a zod schema, from whichever copy of zod the app has. */
|
|
53
|
+
export type BodySchema<T> = {
|
|
54
|
+
parse(input: unknown): T;
|
|
55
|
+
};
|
|
56
|
+
/**
|
|
57
|
+
* The request's JSON body, parsed by `schema` when one is given. A body that is not JSON throws a
|
|
58
|
+
* 400 `invalid_json`; one the schema rejects, a 422 `invalid_input` whose `details` list each
|
|
59
|
+
* issue's path and message (never the input's values). Both are `ApiError`s for `apiHandler` to
|
|
60
|
+
* answer. Anything else thrown, by the schema's own transforms for one, passes through as a bug.
|
|
61
|
+
*/
|
|
62
|
+
export declare function readJson(req: Request): Promise<unknown>;
|
|
63
|
+
export declare function readJson<T>(req: Request, schema: BodySchema<T>): Promise<T>;
|
|
64
|
+
export type ApiHandlerOptions = {
|
|
65
|
+
auth: StackAuth;
|
|
66
|
+
/** What a failure logs as: `"PUT /api/v1/things/:id"`. */
|
|
67
|
+
label: string;
|
|
68
|
+
/** Admin only: any other signed-in caller gets the 404 envelope, never a 403. */
|
|
69
|
+
admin?: boolean;
|
|
70
|
+
};
|
|
71
|
+
export declare function apiHandler<C = unknown>(opts: ApiHandlerOptions, fn: (req: Request, ctx: C, session: Session) => Promise<Response>): (req: Request, ctx: C) => Promise<Response>;
|
package/dist/next/api.js
ADDED
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import { isJsonRequest, isMutation, isSameOrigin } from "../http/guards.js";
|
|
3
|
+
/**
|
|
4
|
+
* The shell every API route runs in: session, admin check, the request guards, the handler, and
|
|
5
|
+
* the envelope for whatever it throws. Written once so route files cannot drift on it.
|
|
6
|
+
*
|
|
7
|
+
* Every failure answers `{ error: { code, message } }`. An `ApiError` is answered as it says; that
|
|
8
|
+
* is how `readJson` reports the request body (400 `invalid_json`, 422 `invalid_input`). Anything
|
|
9
|
+
* else is a bug, even a SyntaxError or a ZodError from the route's own code, and becomes a 500 with
|
|
10
|
+
* a fixed message: what was thrown is logged for the operator and never sent to the caller.
|
|
11
|
+
*
|
|
12
|
+
* `CRON_SECRET` and `HEALTH_TOKEN` are never read here. This wrapper accepts a session and nothing
|
|
13
|
+
* else, so neither secret opens an API route.
|
|
14
|
+
*/
|
|
15
|
+
/** An error a route throws on purpose: its message is written for the caller and is sent as is. */
|
|
16
|
+
export class ApiError extends Error {
|
|
17
|
+
status;
|
|
18
|
+
code;
|
|
19
|
+
details;
|
|
20
|
+
constructor(status, code, message,
|
|
21
|
+
/** Per-field problems with the request, sent as `details`: paths and messages, never values. */
|
|
22
|
+
details) {
|
|
23
|
+
super(message);
|
|
24
|
+
this.status = status;
|
|
25
|
+
this.code = code;
|
|
26
|
+
this.details = details;
|
|
27
|
+
this.name = "ApiError";
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
/** The row does not exist (or the caller may not know that it does). */
|
|
31
|
+
export class NotFoundError extends ApiError {
|
|
32
|
+
constructor(message = "Not found.") {
|
|
33
|
+
super(404, "not_found", message);
|
|
34
|
+
this.name = "NotFoundError";
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* A path id that is not a uuid: the same 404 a missing row gets, but told apart from one so a
|
|
39
|
+
* route that surfaces its own not-found message never surfaces this one.
|
|
40
|
+
*/
|
|
41
|
+
export class PathIdError extends NotFoundError {
|
|
42
|
+
constructor() {
|
|
43
|
+
super();
|
|
44
|
+
this.name = "PathIdError";
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* A path id, or a `PathIdError` for the wrapper to answer. Anything that is not a uuid cannot name
|
|
49
|
+
* a row, so it is the same 404 a missing row gets, answered before the query: Postgres would
|
|
50
|
+
* otherwise reject the cast and turn a typo'd URL into a 500.
|
|
51
|
+
*/
|
|
52
|
+
export function requirePathId(value) {
|
|
53
|
+
if (!z.uuid().safeParse(value).success)
|
|
54
|
+
throw new PathIdError();
|
|
55
|
+
return value;
|
|
56
|
+
}
|
|
57
|
+
export function apiError(status, code, message, details) {
|
|
58
|
+
return Response.json({ error: { code, message, ...(details ? { details } : {}) } }, { status });
|
|
59
|
+
}
|
|
60
|
+
/** A zod parse failure, by class or by shape: the app's zod may be another copy of the package. */
|
|
61
|
+
function zodIssues(error) {
|
|
62
|
+
if (error instanceof z.ZodError)
|
|
63
|
+
return error.issues;
|
|
64
|
+
const candidate = error;
|
|
65
|
+
return candidate?.name === "ZodError" && Array.isArray(candidate.issues)
|
|
66
|
+
? candidate.issues
|
|
67
|
+
: undefined;
|
|
68
|
+
}
|
|
69
|
+
export async function readJson(req, schema) {
|
|
70
|
+
let body;
|
|
71
|
+
try {
|
|
72
|
+
body = await req.json();
|
|
73
|
+
}
|
|
74
|
+
catch (error) {
|
|
75
|
+
if (error instanceof SyntaxError) {
|
|
76
|
+
throw new ApiError(400, "invalid_json", "Send a valid JSON body.");
|
|
77
|
+
}
|
|
78
|
+
throw error;
|
|
79
|
+
}
|
|
80
|
+
if (!schema)
|
|
81
|
+
return body;
|
|
82
|
+
try {
|
|
83
|
+
return schema.parse(body);
|
|
84
|
+
}
|
|
85
|
+
catch (error) {
|
|
86
|
+
const issues = zodIssues(error);
|
|
87
|
+
if (!issues)
|
|
88
|
+
throw error;
|
|
89
|
+
throw new ApiError(422, "invalid_input", "The request is not valid.", issues.map((issue) => ({ path: issue.path.join("."), message: issue.message })));
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
export function apiHandler(opts, fn) {
|
|
93
|
+
return async (req, ctx) => {
|
|
94
|
+
try {
|
|
95
|
+
const session = await opts.auth.getSession(req.headers);
|
|
96
|
+
if (!session)
|
|
97
|
+
return apiError(401, "unauthenticated", "Sign in to continue.");
|
|
98
|
+
if (opts.admin && session.user.role !== "admin") {
|
|
99
|
+
return apiError(404, "not_found", "Not found.");
|
|
100
|
+
}
|
|
101
|
+
if (isMutation(req)) {
|
|
102
|
+
if (!isJsonRequest(req)) {
|
|
103
|
+
return apiError(415, "unsupported_media_type", "Send application/json.");
|
|
104
|
+
}
|
|
105
|
+
if (!isSameOrigin(req))
|
|
106
|
+
return apiError(403, "cross_origin", "Cross-origin request refused.");
|
|
107
|
+
}
|
|
108
|
+
return await fn(req, ctx, session);
|
|
109
|
+
}
|
|
110
|
+
catch (error) {
|
|
111
|
+
if (error instanceof ApiError) {
|
|
112
|
+
return apiError(error.status, error.code, error.message, error.details);
|
|
113
|
+
}
|
|
114
|
+
console.error(`[api] ${opts.label} failed`, error);
|
|
115
|
+
return apiError(500, "internal_error", "Something went wrong.");
|
|
116
|
+
}
|
|
117
|
+
};
|
|
118
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import type { NextConfig } from "next";
|
|
2
|
+
export type WithStackOptions = {
|
|
3
|
+
/** Add the CSP. Defaults to `NODE_ENV === "production"`. */
|
|
4
|
+
isProduction?: boolean;
|
|
5
|
+
/** Extra `connect-src` origins (an API or analytics host the browser calls). */
|
|
6
|
+
cspConnectSrc?: string[];
|
|
7
|
+
};
|
|
8
|
+
export declare function withStack(appConfig?: NextConfig, opts?: WithStackOptions): NextConfig;
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
import { isProductionEnv } from "../env/index.js";
|
|
2
|
+
/**
|
|
3
|
+
* `next.config.ts`: `export default withStack({ ...the app's own config })`.
|
|
4
|
+
*
|
|
5
|
+
* Sentry (or any monitor) is initialised at runtime from `instrumentation.ts`, not through a
|
|
6
|
+
* build-time config wrapper, so there is nothing to compose here.
|
|
7
|
+
*/
|
|
8
|
+
const securityHeaders = [
|
|
9
|
+
{ key: "X-Content-Type-Options", value: "nosniff" },
|
|
10
|
+
{ key: "Referrer-Policy", value: "strict-origin-when-cross-origin" },
|
|
11
|
+
{ key: "X-Frame-Options", value: "DENY" },
|
|
12
|
+
{ key: "Permissions-Policy", value: "camera=(), microphone=(), geolocation=()" },
|
|
13
|
+
{ key: "Strict-Transport-Security", value: "max-age=31536000; includeSubDomains" },
|
|
14
|
+
];
|
|
15
|
+
/**
|
|
16
|
+
* **The Content-Security-Policy, production only.**
|
|
17
|
+
*
|
|
18
|
+
* Turbopack's dev server needs `'unsafe-eval'` and a websocket for HMR that a production policy
|
|
19
|
+
* must not carry, and a half-right CSP breaks the dev loop. So the header is added to production
|
|
20
|
+
* builds only, and a claim about it can only be checked against a production build
|
|
21
|
+
* (`pnpm build && pnpm start`): an e2e suite running against `pnpm dev` never sees it.
|
|
22
|
+
*
|
|
23
|
+
* `process.env.NODE_ENV` is read through `isProductionEnv` rather than an app's validated env
|
|
24
|
+
* because this file is Next's own config: the framework evaluates it before any application module
|
|
25
|
+
* loads, and importing validated config would make a build depend on a boot.
|
|
26
|
+
*/
|
|
27
|
+
function contentSecurityPolicy(connectSrc) {
|
|
28
|
+
return [
|
|
29
|
+
// Nothing loads from anywhere but this origin unless a directive below says so.
|
|
30
|
+
"default-src 'self'",
|
|
31
|
+
/**
|
|
32
|
+
* `'unsafe-inline'`, and the reason is structural rather than lazy: Next's App Router ships the
|
|
33
|
+
* flight payload and its hydration bootstrap as INLINE `<script>` tags, and a policy living in
|
|
34
|
+
* `next.config.ts` is a static header: it cannot carry the per-request nonce those tags would
|
|
35
|
+
* need. With `script-src 'self'` alone the page server-renders and the console fills with
|
|
36
|
+
* "Executing inline script violates...", which means no hydration and dead client components.
|
|
37
|
+
*
|
|
38
|
+
* A nonce-based policy is strictly better: generate one per request in `src/proxy.ts`, pass it
|
|
39
|
+
* on the request headers, and Next stamps its own scripts with it. That moves the CSP out of
|
|
40
|
+
* this file and puts per-request work in the one file that guards every page, so it is a
|
|
41
|
+
* decision for the app rather than a default here.
|
|
42
|
+
*
|
|
43
|
+
* What this still buys: no script from another origin can load, `eval` is refused (no
|
|
44
|
+
* `'unsafe-eval'`), and the directives below close framing, base-tag and form-action
|
|
45
|
+
* redirection. Strictly better than no CSP.
|
|
46
|
+
*/
|
|
47
|
+
"script-src 'self' 'unsafe-inline'",
|
|
48
|
+
/**
|
|
49
|
+
* `'unsafe-inline'` here is a correctness requirement, not a convenience. Under `style-src
|
|
50
|
+
* 'self'` a browser keeps a `style="..."` attribute and refuses to apply it, so any component
|
|
51
|
+
* that sets a width or transform inline renders as if the style were absent (a meter drawn at
|
|
52
|
+
* full width is a worse failure than a missing header).
|
|
53
|
+
*
|
|
54
|
+
* `style-src-attr 'unsafe-inline'` with a strict `style-src` would be tighter, and is
|
|
55
|
+
* deliberately not used: where a browser does not support `style-src-attr` it falls back to
|
|
56
|
+
* `style-src`, and the failure mode of guessing wrong is the one above.
|
|
57
|
+
*/
|
|
58
|
+
"style-src 'self' 'unsafe-inline'",
|
|
59
|
+
// `data:` is for the favicon and inline icons; remote images are an app decision.
|
|
60
|
+
"img-src 'self' data:",
|
|
61
|
+
// `next/font` downloads fonts AT BUILD TIME and serves them from /_next/static, so the running
|
|
62
|
+
// app never reaches a font CDN and this stays 'self'.
|
|
63
|
+
"font-src 'self'",
|
|
64
|
+
// Same-origin fetches only, plus whatever origins the app lists in `cspConnectSrc`.
|
|
65
|
+
["connect-src 'self'", ...connectSrc].join(" "),
|
|
66
|
+
"form-action 'self'",
|
|
67
|
+
// Belt to X-Frame-Options' braces, and the directive browsers actually honour now.
|
|
68
|
+
"frame-ancestors 'none'",
|
|
69
|
+
"base-uri 'none'",
|
|
70
|
+
"object-src 'none'",
|
|
71
|
+
// On Vercel every request is https; this closes the gap if one is not.
|
|
72
|
+
"upgrade-insecure-requests",
|
|
73
|
+
].join("; ");
|
|
74
|
+
}
|
|
75
|
+
export function withStack(appConfig = {}, opts = {}) {
|
|
76
|
+
const isProduction = opts.isProduction ?? isProductionEnv();
|
|
77
|
+
const stackHeaders = isProduction
|
|
78
|
+
? [
|
|
79
|
+
...securityHeaders,
|
|
80
|
+
{
|
|
81
|
+
key: "Content-Security-Policy",
|
|
82
|
+
value: contentSecurityPolicy(opts.cspConnectSrc ?? []),
|
|
83
|
+
},
|
|
84
|
+
]
|
|
85
|
+
: securityHeaders;
|
|
86
|
+
return {
|
|
87
|
+
reactStrictMode: true,
|
|
88
|
+
...appConfig,
|
|
89
|
+
poweredByHeader: false,
|
|
90
|
+
// The health route checks the migrations folder at runtime. Vercel bundles only traced files,
|
|
91
|
+
// so without this the read fails and migrations always report "unknown".
|
|
92
|
+
outputFileTracingIncludes: {
|
|
93
|
+
...appConfig.outputFileTracingIncludes,
|
|
94
|
+
"/api/health": ["./drizzle/**"],
|
|
95
|
+
},
|
|
96
|
+
// The stack's headers first, then the app's own.
|
|
97
|
+
async headers() {
|
|
98
|
+
return [
|
|
99
|
+
{ source: "/:path*", headers: stackHeaders },
|
|
100
|
+
...((await appConfig.headers?.()) ?? []),
|
|
101
|
+
];
|
|
102
|
+
},
|
|
103
|
+
};
|
|
104
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A scheduled job's route, called by Vercel Cron with `Authorization: Bearer $CRON_SECRET`.
|
|
3
|
+
* `CRON_SECRET` triggers scheduled jobs and nothing else: with none configured every request is
|
|
4
|
+
* refused (an empty bearer is not accepted), and the response is whatever `fn` returned, which
|
|
5
|
+
* must be counts. No row data, no ids, no messages.
|
|
6
|
+
*
|
|
7
|
+
* `export const GET = cronRoute(tick, { secret: env.CRON_SECRET })`.
|
|
8
|
+
*/
|
|
9
|
+
export declare function cronRoute(fn: (req: Request) => Promise<unknown>, opts: {
|
|
10
|
+
secret: string | undefined;
|
|
11
|
+
}): (req: Request) => Promise<Response>;
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { bearerMatches } from "../http/guards.js";
|
|
2
|
+
import { apiError } from "./api.js";
|
|
3
|
+
/**
|
|
4
|
+
* A scheduled job's route, called by Vercel Cron with `Authorization: Bearer $CRON_SECRET`.
|
|
5
|
+
* `CRON_SECRET` triggers scheduled jobs and nothing else: with none configured every request is
|
|
6
|
+
* refused (an empty bearer is not accepted), and the response is whatever `fn` returned, which
|
|
7
|
+
* must be counts. No row data, no ids, no messages.
|
|
8
|
+
*
|
|
9
|
+
* `export const GET = cronRoute(tick, { secret: env.CRON_SECRET })`.
|
|
10
|
+
*/
|
|
11
|
+
export function cronRoute(fn, opts) {
|
|
12
|
+
return async (req) => {
|
|
13
|
+
if (!bearerMatches(req, opts.secret)) {
|
|
14
|
+
// A refused call writes nothing anywhere, so without this line a missing or wrong secret
|
|
15
|
+
// looks exactly like a cron that never fired. Never logs what was presented.
|
|
16
|
+
console.warn(JSON.stringify({
|
|
17
|
+
level: "warn",
|
|
18
|
+
msg: "cron refused",
|
|
19
|
+
reason: opts.secret ? "bad secret" : "CRON_SECRET not set",
|
|
20
|
+
}));
|
|
21
|
+
return apiError(401, "unauthenticated", "Invalid cron credentials.");
|
|
22
|
+
}
|
|
23
|
+
try {
|
|
24
|
+
const counts = await fn(req);
|
|
25
|
+
return Response.json(counts ?? {}, { headers: { "cache-control": "no-store" } });
|
|
26
|
+
}
|
|
27
|
+
catch (error) {
|
|
28
|
+
// A short-lived function can be frozen before a logger drains, so this is the one line.
|
|
29
|
+
console.error("[cron] job failed", error);
|
|
30
|
+
return apiError(500, "internal_error", "Something went wrong.");
|
|
31
|
+
}
|
|
32
|
+
};
|
|
33
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import type { NodePgDatabase } from "drizzle-orm/node-postgres";
|
|
2
|
+
/**
|
|
3
|
+
* Liveness, deliberately not readiness. The status is ALWAYS 200 while the process can answer: a
|
|
4
|
+
* database blip must not make an uptime check report a healthy web process as down.
|
|
5
|
+
*
|
|
6
|
+
* Without the token the answer is `{ ok: true }` and the database is never touched, so an
|
|
7
|
+
* anonymous caller cannot make the app query it. With `Authorization: Bearer $HEALTH_TOKEN` it
|
|
8
|
+
* also reports `db` and `migrations`. `HEALTH_TOKEN` is its own secret, never `CRON_SECRET`.
|
|
9
|
+
*
|
|
10
|
+
* `export const GET = healthRoute({ db, token: env.HEALTH_TOKEN })`, with `dynamic =
|
|
11
|
+
* "force-dynamic"`. `withStack` traces `./drizzle/**` into this route so the migrations folder
|
|
12
|
+
* exists in a deployment.
|
|
13
|
+
*/
|
|
14
|
+
export declare function healthRoute(opts: {
|
|
15
|
+
db?: NodePgDatabase<any>;
|
|
16
|
+
/** Defaults to `drizzle/` under the working directory. */
|
|
17
|
+
migrationsFolder?: string;
|
|
18
|
+
token?: string;
|
|
19
|
+
}): (req: Request) => Promise<Response>;
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import path from "node:path";
|
|
2
|
+
import { sql } from "drizzle-orm";
|
|
3
|
+
import { migrationStatus } from "../db/migration-status.js";
|
|
4
|
+
import { bearerMatches } from "../http/guards.js";
|
|
5
|
+
/**
|
|
6
|
+
* Liveness, deliberately not readiness. The status is ALWAYS 200 while the process can answer: a
|
|
7
|
+
* database blip must not make an uptime check report a healthy web process as down.
|
|
8
|
+
*
|
|
9
|
+
* Without the token the answer is `{ ok: true }` and the database is never touched, so an
|
|
10
|
+
* anonymous caller cannot make the app query it. With `Authorization: Bearer $HEALTH_TOKEN` it
|
|
11
|
+
* also reports `db` and `migrations`. `HEALTH_TOKEN` is its own secret, never `CRON_SECRET`.
|
|
12
|
+
*
|
|
13
|
+
* `export const GET = healthRoute({ db, token: env.HEALTH_TOKEN })`, with `dynamic =
|
|
14
|
+
* "force-dynamic"`. `withStack` traces `./drizzle/**` into this route so the migrations folder
|
|
15
|
+
* exists in a deployment.
|
|
16
|
+
*/
|
|
17
|
+
export function healthRoute(opts) {
|
|
18
|
+
const migrationsFolder = opts.migrationsFolder ?? path.join(process.cwd(), "drizzle");
|
|
19
|
+
// No-store: a cached liveness answer is not a liveness answer.
|
|
20
|
+
const headers = { "cache-control": "no-store" };
|
|
21
|
+
return async (req) => {
|
|
22
|
+
if (!bearerMatches(req, opts.token))
|
|
23
|
+
return Response.json({ ok: true }, { headers });
|
|
24
|
+
const { db } = opts;
|
|
25
|
+
if (!db)
|
|
26
|
+
return Response.json({ ok: true, db: "unknown", migrations: "unknown" }, { headers });
|
|
27
|
+
try {
|
|
28
|
+
await db.execute(sql `select 1`);
|
|
29
|
+
}
|
|
30
|
+
catch {
|
|
31
|
+
return Response.json({ ok: true, db: "down", migrations: "unknown" }, { headers });
|
|
32
|
+
}
|
|
33
|
+
const migrations = await migrationStatus(db, migrationsFolder).catch(() => "unknown");
|
|
34
|
+
return Response.json({ ok: true, db: "up", migrations }, { headers });
|
|
35
|
+
};
|
|
36
|
+
}
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
export type { ApiHandlerOptions, BodySchema } from "./api.ts";
|
|
2
|
+
export { ApiError, apiError, apiHandler, NotFoundError, PathIdError, readJson, requirePathId, } from "./api.ts";
|
|
3
|
+
export { withStack } from "./config.ts";
|
|
4
|
+
export { cronRoute } from "./cron.ts";
|
|
5
|
+
export { healthRoute } from "./health.ts";
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Runs `fn` inside a real Next request scope in its server-action phase — what Next sets up around
|
|
3
|
+
* a `"use server"` function — so `headers()` reads `headers` and `cookies().set()` works. Returns
|
|
4
|
+
* the `Set-Cookie` lines the scope would send, which is how a test sees what Better Auth's
|
|
5
|
+
* `nextCookies()` wrote. Built from Next's own internals (next is pinned exactly).
|
|
6
|
+
*
|
|
7
|
+
* `redirect()` and `notFound()` throw as they do in Next; `thrownBy` reads where they pointed.
|
|
8
|
+
*/
|
|
9
|
+
export declare function inServerAction<T>(headers: HeadersInit, fn: () => Promise<T>): Promise<{
|
|
10
|
+
result: T;
|
|
11
|
+
setCookies: string[];
|
|
12
|
+
}>;
|
|
13
|
+
/** What a `redirect()` or `notFound()` thrown by `fn` means: `redirect:<url>` or `http:<status>`. */
|
|
14
|
+
export declare function thrownBy(fn: () => Promise<unknown>): Promise<string>;
|