@wwchen/stack 0.0.0-stage → 0.2.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 (101) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +79 -2
  3. package/blocks/AGENTS.md +77 -0
  4. package/blocks/CLAUDE.md +113 -0
  5. package/blocks/env.example +34 -0
  6. package/blocks/gitignore +18 -0
  7. package/configs/biome.json +45 -0
  8. package/configs/tsconfig.next.json +22 -0
  9. package/dist/auth/better-auth/index.d.ts +316 -0
  10. package/dist/auth/better-auth/index.js +237 -0
  11. package/dist/auth/better-auth/tables.d.ts +628 -0
  12. package/dist/auth/better-auth/tables.js +74 -0
  13. package/dist/auth/better-auth/users.d.ts +27 -0
  14. package/dist/auth/better-auth/users.js +128 -0
  15. package/dist/auth/index.d.ts +58 -0
  16. package/dist/auth/index.js +120 -0
  17. package/dist/auth/proxy.d.ts +14 -0
  18. package/dist/auth/proxy.js +50 -0
  19. package/dist/auth/safe-next.d.ts +17 -0
  20. package/dist/auth/safe-next.js +36 -0
  21. package/dist/auth/types.d.ts +47 -0
  22. package/dist/auth/types.js +5 -0
  23. package/dist/cli/context.d.ts +38 -0
  24. package/dist/cli/context.js +43 -0
  25. package/dist/cli/index.d.ts +4 -0
  26. package/dist/cli/index.js +95 -0
  27. package/dist/cli/neon.d.ts +97 -0
  28. package/dist/cli/neon.js +334 -0
  29. package/dist/cli/sync-blocks.d.ts +16 -0
  30. package/dist/cli/sync-blocks.js +97 -0
  31. package/dist/cli/user-create.d.ts +2 -0
  32. package/dist/cli/user-create.js +35 -0
  33. package/dist/cli/vercel-build.d.ts +4 -0
  34. package/dist/cli/vercel-build.js +72 -0
  35. package/dist/configs/vitest.d.ts +4 -0
  36. package/dist/configs/vitest.js +50 -0
  37. package/dist/connections/crypto.d.ts +8 -0
  38. package/dist/connections/crypto.js +50 -0
  39. package/dist/connections/index.d.ts +63 -0
  40. package/dist/connections/index.js +212 -0
  41. package/dist/connections/providers.d.ts +30 -0
  42. package/dist/connections/providers.js +47 -0
  43. package/dist/connections/table.d.ts +156 -0
  44. package/dist/connections/table.js +29 -0
  45. package/dist/db/explaining-pool.d.ts +16 -0
  46. package/dist/db/explaining-pool.js +62 -0
  47. package/dist/db/index.d.ts +21 -0
  48. package/dist/db/index.js +36 -0
  49. package/dist/db/migration-status.d.ts +8 -0
  50. package/dist/db/migration-status.js +41 -0
  51. package/dist/db/target.d.ts +26 -0
  52. package/dist/db/target.js +72 -0
  53. package/dist/db/testing/index.d.ts +27 -0
  54. package/dist/db/testing/index.js +71 -0
  55. package/dist/db/testing/isolate.d.ts +1 -0
  56. package/dist/db/testing/isolate.js +4 -0
  57. package/dist/db/testing/pglite.d.ts +21 -0
  58. package/dist/db/testing/pglite.js +71 -0
  59. package/dist/env/define-env.d.ts +37 -0
  60. package/dist/env/define-env.js +134 -0
  61. package/dist/env/index.d.ts +3 -0
  62. package/dist/env/index.js +3 -0
  63. package/dist/env/load-env-file.d.ts +15 -0
  64. package/dist/env/load-env-file.js +52 -0
  65. package/dist/env/stack-env.d.ts +40 -0
  66. package/dist/env/stack-env.js +60 -0
  67. package/dist/env/testing.d.ts +8 -0
  68. package/dist/env/testing.js +16 -0
  69. package/dist/http/client-ip.d.ts +12 -0
  70. package/dist/http/client-ip.js +28 -0
  71. package/dist/http/guards.d.ts +17 -0
  72. package/dist/http/guards.js +57 -0
  73. package/dist/http/rate-limit.d.ts +34 -0
  74. package/dist/http/rate-limit.js +79 -0
  75. package/dist/index.d.ts +1 -0
  76. package/dist/index.js +1 -0
  77. package/dist/jobs/index.d.ts +37 -0
  78. package/dist/jobs/index.js +51 -0
  79. package/dist/mail/index.d.ts +45 -0
  80. package/dist/mail/index.js +97 -0
  81. package/dist/next/api.d.ts +71 -0
  82. package/dist/next/api.js +118 -0
  83. package/dist/next/config.d.ts +8 -0
  84. package/dist/next/config.js +104 -0
  85. package/dist/next/cron.d.ts +14 -0
  86. package/dist/next/cron.js +40 -0
  87. package/dist/next/health.d.ts +19 -0
  88. package/dist/next/health.js +36 -0
  89. package/dist/next/index.d.ts +5 -0
  90. package/dist/next/index.js +4 -0
  91. package/dist/testing/next.d.ts +14 -0
  92. package/dist/testing/next.js +39 -0
  93. package/dist/ui/app.css +56 -0
  94. package/dist/ui/globals.css +152 -0
  95. package/dist/ui/icons.d.ts +17 -0
  96. package/dist/ui/icons.js +104 -0
  97. package/dist/ui/index.d.ts +33 -0
  98. package/dist/ui/index.js +41 -0
  99. package/dist/ui/theme.d.ts +18 -0
  100. package/dist/ui/theme.js +24 -0
  101. package/package.json +134 -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
+ }
@@ -0,0 +1 @@
1
+ export {};
package/dist/index.js ADDED
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,37 @@
1
+ /**
2
+ * Helpers for scheduled jobs that work for many people (ifttt syncs everyone's check-ins).
3
+ *
4
+ * **Alert on new failures only.** An uptime monitor that calls the job alerts when it answers 500.
5
+ * If every failure answered 500, one person whose sync is broken would hold the monitor down for
6
+ * good, and the next person to break would raise no alert. So a failure counts as *new* for its
7
+ * first `ALERT_FOR_HOURS` (24h) and the job answers 500 only while someone's failure is new
8
+ * (`cronRoute` does that when the job returns `alerting: true`). The person stays marked failing in
9
+ * the app until fixed; the monitor recovers and is free to alert on the next streak.
10
+ */
11
+ export declare const ALERT_FOR_HOURS = 24;
12
+ type Timestamp = string | Date;
13
+ export type RunOutcome = {
14
+ ok: boolean;
15
+ startedAt: Timestamp;
16
+ /** When the failure streak this run belongs to began; carried from run to run. */
17
+ failingSince?: Timestamp | null;
18
+ };
19
+ /**
20
+ * When `run`'s failure streak began: the previous run's streak start when that one failed too,
21
+ * otherwise `run` itself. Null for a successful run. `previous` is the person's last real (not
22
+ * dry-run) run before this one.
23
+ */
24
+ export declare function failingSince(run: {
25
+ ok: boolean;
26
+ startedAt: Timestamp;
27
+ }, previous: RunOutcome | null | undefined): string | null;
28
+ /** A failed run whose streak began less than `alertForHours` ago. */
29
+ export declare function isNewFailure(run: RunOutcome, now?: number, alertForHours?: number): boolean;
30
+ /**
31
+ * `fn` over `items`, at most `limit` at a time, results in input order. A job that works for many
32
+ * people shares one external quota (ifttt: one Google service account) and one function timeout,
33
+ * so it neither runs them one by one nor all at once. A rejection rejects the whole call: `fn`
34
+ * catches its own per-person failures.
35
+ */
36
+ export declare function mapLimit<T, R>(items: readonly T[], limit: number, fn: (item: T, index: number) => Promise<R>): Promise<R[]>;
37
+ export {};
@@ -0,0 +1,51 @@
1
+ /**
2
+ * Helpers for scheduled jobs that work for many people (ifttt syncs everyone's check-ins).
3
+ *
4
+ * **Alert on new failures only.** An uptime monitor that calls the job alerts when it answers 500.
5
+ * If every failure answered 500, one person whose sync is broken would hold the monitor down for
6
+ * good, and the next person to break would raise no alert. So a failure counts as *new* for its
7
+ * first `ALERT_FOR_HOURS` (24h) and the job answers 500 only while someone's failure is new
8
+ * (`cronRoute` does that when the job returns `alerting: true`). The person stays marked failing in
9
+ * the app until fixed; the monitor recovers and is free to alert on the next streak.
10
+ */
11
+ export const ALERT_FOR_HOURS = 24;
12
+ const ms = (t) => (typeof t === "string" ? Date.parse(t) : t.getTime());
13
+ const iso = (t) => (typeof t === "string" ? t : t.toISOString());
14
+ /**
15
+ * When `run`'s failure streak began: the previous run's streak start when that one failed too,
16
+ * otherwise `run` itself. Null for a successful run. `previous` is the person's last real (not
17
+ * dry-run) run before this one.
18
+ */
19
+ export function failingSince(run, previous) {
20
+ if (run.ok)
21
+ return null;
22
+ if (previous && !previous.ok)
23
+ return iso(previous.failingSince ?? previous.startedAt);
24
+ return iso(run.startedAt);
25
+ }
26
+ /** A failed run whose streak began less than `alertForHours` ago. */
27
+ export function isNewFailure(run, now = Date.now(), alertForHours = ALERT_FOR_HOURS) {
28
+ if (run.ok)
29
+ return false;
30
+ return now - ms(run.failingSince ?? run.startedAt) < alertForHours * 3_600_000;
31
+ }
32
+ /**
33
+ * `fn` over `items`, at most `limit` at a time, results in input order. A job that works for many
34
+ * people shares one external quota (ifttt: one Google service account) and one function timeout,
35
+ * so it neither runs them one by one nor all at once. A rejection rejects the whole call: `fn`
36
+ * catches its own per-person failures.
37
+ */
38
+ export async function mapLimit(items, limit, fn) {
39
+ if (!Number.isInteger(limit) || limit < 1)
40
+ throw new Error("mapLimit: limit must be at least 1");
41
+ const results = new Array(items.length);
42
+ let next = 0;
43
+ const worker = async () => {
44
+ while (next < items.length) {
45
+ const i = next++;
46
+ results[i] = await fn(items[i], i);
47
+ }
48
+ };
49
+ await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));
50
+ return results;
51
+ }
@@ -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>;
@@ -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,14 @@
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
+ * A job that returns `alerting: true` answers 500 with the same counts, so an uptime monitor calling
8
+ * it alerts: a multi-person job sets it while someone's failure is new (`@wwchen/stack/jobs`).
9
+ *
10
+ * `export const GET = cronRoute(tick, { secret: env.CRON_SECRET })`.
11
+ */
12
+ export declare function cronRoute(fn: (req: Request) => Promise<unknown>, opts: {
13
+ secret: string | undefined;
14
+ }): (req: Request) => Promise<Response>;