@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.
Files changed (91) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +47 -2
  3. package/blocks/AGENTS.md +77 -0
  4. package/blocks/CLAUDE.md +113 -0
  5. package/blocks/env.example +32 -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/db/explaining-pool.d.ts +16 -0
  38. package/dist/db/explaining-pool.js +62 -0
  39. package/dist/db/index.d.ts +21 -0
  40. package/dist/db/index.js +36 -0
  41. package/dist/db/migration-status.d.ts +8 -0
  42. package/dist/db/migration-status.js +41 -0
  43. package/dist/db/target.d.ts +26 -0
  44. package/dist/db/target.js +72 -0
  45. package/dist/db/testing/index.d.ts +27 -0
  46. package/dist/db/testing/index.js +71 -0
  47. package/dist/db/testing/isolate.d.ts +1 -0
  48. package/dist/db/testing/isolate.js +4 -0
  49. package/dist/db/testing/pglite.d.ts +21 -0
  50. package/dist/db/testing/pglite.js +71 -0
  51. package/dist/env/define-env.d.ts +37 -0
  52. package/dist/env/define-env.js +134 -0
  53. package/dist/env/index.d.ts +3 -0
  54. package/dist/env/index.js +3 -0
  55. package/dist/env/load-env-file.d.ts +15 -0
  56. package/dist/env/load-env-file.js +52 -0
  57. package/dist/env/stack-env.d.ts +39 -0
  58. package/dist/env/stack-env.js +52 -0
  59. package/dist/env/testing.d.ts +8 -0
  60. package/dist/env/testing.js +16 -0
  61. package/dist/http/client-ip.d.ts +12 -0
  62. package/dist/http/client-ip.js +28 -0
  63. package/dist/http/guards.d.ts +17 -0
  64. package/dist/http/guards.js +57 -0
  65. package/dist/http/rate-limit.d.ts +34 -0
  66. package/dist/http/rate-limit.js +79 -0
  67. package/dist/index.d.ts +1 -0
  68. package/dist/index.js +1 -0
  69. package/dist/mail/index.d.ts +45 -0
  70. package/dist/mail/index.js +97 -0
  71. package/dist/next/api.d.ts +71 -0
  72. package/dist/next/api.js +118 -0
  73. package/dist/next/config.d.ts +8 -0
  74. package/dist/next/config.js +104 -0
  75. package/dist/next/cron.d.ts +11 -0
  76. package/dist/next/cron.js +33 -0
  77. package/dist/next/health.d.ts +19 -0
  78. package/dist/next/health.js +36 -0
  79. package/dist/next/index.d.ts +5 -0
  80. package/dist/next/index.js +4 -0
  81. package/dist/testing/next.d.ts +14 -0
  82. package/dist/testing/next.js +39 -0
  83. package/dist/ui/app.css +56 -0
  84. package/dist/ui/globals.css +152 -0
  85. package/dist/ui/icons.d.ts +17 -0
  86. package/dist/ui/icons.js +104 -0
  87. package/dist/ui/index.d.ts +33 -0
  88. package/dist/ui/index.js +41 -0
  89. package/dist/ui/theme.d.ts +18 -0
  90. package/dist/ui/theme.js +24 -0
  91. package/package.json +126 -4
@@ -0,0 +1,71 @@
1
+ import { createServer } from "node:net";
2
+ /**
3
+ * PGlite served over the Postgres wire protocol, so the app's `pg` pool talks to it like any other
4
+ * Postgres. Used by the test helper and a template's dev server.
5
+ *
6
+ * `1` because pglite-socket serialises every connection onto PGlite's single session: with more,
7
+ * one connection's open transaction blocks the others and there is no per-connection isolation.
8
+ * At the limit a second connection is refused outright, so a pool pointed at this server must use
9
+ * `max: PGLITE_MAX_CONNECTIONS` and nothing may open another pool against it.
10
+ */
11
+ export const PGLITE_MAX_CONNECTIONS = 1;
12
+ async function freePort(host) {
13
+ return new Promise((resolve, reject) => {
14
+ const probe = createServer();
15
+ probe.once("error", reject);
16
+ probe.listen(0, host, () => {
17
+ const address = probe.address();
18
+ if (address === null || typeof address === "string") {
19
+ probe.close();
20
+ reject(new Error("could not find a free port"));
21
+ return;
22
+ }
23
+ probe.close(() => resolve(address.port));
24
+ });
25
+ });
26
+ }
27
+ /**
28
+ * PGlite and pglite-socket are optional peers, loaded only here, on the PGlite path: a
29
+ * Postgres-only setup (`TEST_DATABASE_URL`) need not install them.
30
+ */
31
+ async function loadPglite() {
32
+ try {
33
+ const [{ PGlite }, { PGLiteSocketServer }] = await Promise.all([
34
+ import("@electric-sql/pglite"),
35
+ import("@electric-sql/pglite-socket"),
36
+ ]);
37
+ return { PGlite, PGLiteSocketServer };
38
+ }
39
+ catch (error) {
40
+ throw new Error("PGlite could not be loaded: install @electric-sql/pglite and @electric-sql/pglite-socket " +
41
+ "as devDependencies, or set TEST_DATABASE_URL to a Postgres server for the tests to use.", { cause: error });
42
+ }
43
+ }
44
+ /** In-memory when `dataDir` is absent. `port` 0 (or absent) picks a free one. */
45
+ export async function startPgliteServer(options = {}) {
46
+ const { PGlite, PGLiteSocketServer } = await loadPglite();
47
+ const host = options.host ?? "127.0.0.1";
48
+ const port = options.port ? options.port : await freePort(host);
49
+ const db = await PGlite.create(options.dataDir);
50
+ const server = new PGLiteSocketServer({
51
+ db,
52
+ host,
53
+ port,
54
+ maxConnections: PGLITE_MAX_CONNECTIONS,
55
+ });
56
+ try {
57
+ await server.start();
58
+ }
59
+ catch (error) {
60
+ await db.close();
61
+ throw error;
62
+ }
63
+ return {
64
+ url: `postgres://postgres@${host}:${port}/postgres`,
65
+ port,
66
+ stop: async () => {
67
+ await server.stop();
68
+ await db.close();
69
+ },
70
+ };
71
+ }
@@ -0,0 +1,37 @@
1
+ import { z } from "zod";
2
+ export type EnvSource = Record<string, string | undefined>;
3
+ export interface EnvProblem {
4
+ variable: string;
5
+ problem: string;
6
+ }
7
+ /**
8
+ * Thrown by `defineEnv` with every problem found, not just the first. The message names each bad
9
+ * variable and says what is wrong with it; it never contains a variable's value, because values
10
+ * can be secrets.
11
+ */
12
+ export declare class ConfigError extends Error {
13
+ readonly problems: EnvProblem[];
14
+ constructor(problems: EnvProblem[]);
15
+ }
16
+ export interface EnvSpec<S extends z.ZodRawShape> {
17
+ schema: S;
18
+ /** Required (non-blank, no default) when NODE_ENV is production. */
19
+ productionRequired?: readonly (keyof S & string)[];
20
+ /** Named all-or-none groups: either every member is set or none is. */
21
+ groups?: Readonly<Record<string, readonly (keyof S & string)[]>>;
22
+ }
23
+ /**
24
+ * Validates `source` (default `process.env`, the only place the package reads it) against `schema`.
25
+ *
26
+ * - Blank values are absent; `<NAME>_FILE` is read when `<NAME>` is unset (both set is an error).
27
+ * - Production requirements are checked against the resolved value before defaults apply, so a
28
+ * development default can never satisfy one.
29
+ * - During a Next build (`NEXT_PHASE=phase-production-build`) or with `SKIP_ENV_VALIDATION=1`, a
30
+ * build is not a boot: production requirements, groups and a missing `DATABASE_URL` are not
31
+ * enforced (a placeholder stands in), but defaults still apply. With `NODE_ENV=production`,
32
+ * `SKIP_ENV_VALIDATION` is ignored outside the build phase.
33
+ * - When the schema has `APP_URL`, it is derived from VERCEL_BRANCH_URL / VERCEL_URL on a Vercel
34
+ * preview, so apps that extend the stack schema get it for free.
35
+ * - Throws one `ConfigError` listing every problem.
36
+ */
37
+ export declare function defineEnv<S extends z.ZodRawShape>(spec: EnvSpec<S>, rawSource?: EnvSource): z.infer<z.ZodObject<S>>;
@@ -0,0 +1,134 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { z } from "zod";
3
+ /**
4
+ * Thrown by `defineEnv` with every problem found, not just the first. The message names each bad
5
+ * variable and says what is wrong with it; it never contains a variable's value, because values
6
+ * can be secrets.
7
+ */
8
+ export class ConfigError extends Error {
9
+ problems;
10
+ constructor(problems) {
11
+ super(`Invalid environment configuration: ${problems
12
+ .map(({ variable, problem }) => `${variable} ${problem}`)
13
+ .join("; ")}`);
14
+ this.name = "ConfigError";
15
+ this.problems = problems;
16
+ }
17
+ }
18
+ /** Stands in for a connection string during a build, which never opens a connection. */
19
+ const BUILD_PLACEHOLDER_DATABASE_URL = "postgres://unused:unused@127.0.0.1:1/unused";
20
+ const TRAILING_NEWLINES = /[\r\n]+$/;
21
+ const isBlank = (value) => value === undefined || value.trim() === "";
22
+ /**
23
+ * Resolves one variable: the plain name, else the contents of `<NAME>_FILE`. Blank counts as
24
+ * absent, because `KEY=` in a `.env` file means "not set". Both set is a mistake.
25
+ */
26
+ function resolve(name, source, problems) {
27
+ const direct = isBlank(source[name]) ? undefined : source[name];
28
+ const fileVariable = `${name}_FILE`;
29
+ const file = source[fileVariable];
30
+ if (isBlank(file))
31
+ return direct;
32
+ if (direct !== undefined) {
33
+ problems.push({ variable: name, problem: `and ${fileVariable} are both set; set one` });
34
+ return undefined;
35
+ }
36
+ let contents;
37
+ try {
38
+ contents = readFileSync(file, "utf8");
39
+ }
40
+ catch {
41
+ problems.push({ variable: fileVariable, problem: "names a file that cannot be read" });
42
+ return undefined;
43
+ }
44
+ const value = contents.replace(TRAILING_NEWLINES, "");
45
+ if (isBlank(value)) {
46
+ problems.push({ variable: fileVariable, problem: "names an empty file" });
47
+ return undefined;
48
+ }
49
+ return value;
50
+ }
51
+ /**
52
+ * On a Vercel preview the platform's own hostnames are the only addresses the app has, so APP_URL
53
+ * may be derived from them. Deliberately not a schema default: the derived value is placed in the
54
+ * source, so it satisfies the production requirement on a preview and nowhere else.
55
+ *
56
+ * The branch alias comes first, the deployment URL only without one. Deployment Protection's
57
+ * Vercel sign-in is per hostname, so a magic link pointing at the other hostname makes the owner
58
+ * sign in to Vercel again first.
59
+ */
60
+ function withPreviewAppUrl(source) {
61
+ if (source.VERCEL_ENV !== "preview" ||
62
+ !isBlank(source.APP_URL) ||
63
+ !isBlank(source.APP_URL_FILE)) {
64
+ return source;
65
+ }
66
+ const host = (source.VERCEL_BRANCH_URL ?? "").trim() || (source.VERCEL_URL ?? "").trim();
67
+ return host === "" ? source : { ...source, APP_URL: `https://${host}` };
68
+ }
69
+ /**
70
+ * Validates `source` (default `process.env`, the only place the package reads it) against `schema`.
71
+ *
72
+ * - Blank values are absent; `<NAME>_FILE` is read when `<NAME>` is unset (both set is an error).
73
+ * - Production requirements are checked against the resolved value before defaults apply, so a
74
+ * development default can never satisfy one.
75
+ * - During a Next build (`NEXT_PHASE=phase-production-build`) or with `SKIP_ENV_VALIDATION=1`, a
76
+ * build is not a boot: production requirements, groups and a missing `DATABASE_URL` are not
77
+ * enforced (a placeholder stands in), but defaults still apply. With `NODE_ENV=production`,
78
+ * `SKIP_ENV_VALIDATION` is ignored outside the build phase.
79
+ * - When the schema has `APP_URL`, it is derived from VERCEL_BRANCH_URL / VERCEL_URL on a Vercel
80
+ * preview, so apps that extend the stack schema get it for free.
81
+ * - Throws one `ConfigError` listing every problem.
82
+ */
83
+ export function defineEnv(spec, rawSource = process.env) {
84
+ const source = "APP_URL" in spec.schema ? withPreviewAppUrl(rawSource) : rawSource;
85
+ const problems = [];
86
+ const resolved = {};
87
+ for (const name of Object.keys(spec.schema)) {
88
+ resolved[name] = resolve(name, source, problems);
89
+ }
90
+ // SKIP_ENV_VALIDATION is for builds and tooling. A production server that inherited it would
91
+ // boot on development defaults (a public BETTER_AUTH_SECRET), so production honours it only in
92
+ // the build phase.
93
+ const building = source.NEXT_PHASE === "phase-production-build";
94
+ const skipValidation = building || (source.SKIP_ENV_VALIDATION === "1" && source.NODE_ENV !== "production");
95
+ if (skipValidation && "DATABASE_URL" in spec.schema) {
96
+ resolved.DATABASE_URL ??= BUILD_PLACEHOLDER_DATABASE_URL;
97
+ }
98
+ const parsed = z.object(spec.schema).safeParse(resolved);
99
+ // One problem per variable: a bad `_FILE` also leaves its plain name unset, and a missing
100
+ // production secret may also fail the schema.
101
+ const reported = new Set(problems.flatMap((p) => [p.variable, p.variable.replace(/_FILE$/, "")]));
102
+ if (!parsed.success) {
103
+ for (const issue of parsed.error.issues) {
104
+ const variable = String(issue.path[0] ?? "(root)");
105
+ if (reported.has(variable))
106
+ continue;
107
+ reported.add(variable);
108
+ problems.push({ variable, problem: issue.message });
109
+ }
110
+ }
111
+ if (!skipValidation) {
112
+ for (const [group, members] of Object.entries(spec.groups ?? {})) {
113
+ const present = members.filter((name) => resolved[name] !== undefined);
114
+ if (present.length === 0 || present.length === members.length)
115
+ continue;
116
+ for (const name of members.filter((member) => resolved[member] === undefined)) {
117
+ problems.push({
118
+ variable: name,
119
+ problem: `must be set together with ${present.join(", ")} (group ${group}: all or none)`,
120
+ });
121
+ }
122
+ }
123
+ if (resolved.NODE_ENV === "production") {
124
+ for (const name of spec.productionRequired ?? []) {
125
+ if (resolved[name] === undefined && !reported.has(name)) {
126
+ problems.push({ variable: name, problem: "is required when NODE_ENV is production" });
127
+ }
128
+ }
129
+ }
130
+ }
131
+ if (problems.length > 0 || !parsed.success)
132
+ throw new ConfigError(problems);
133
+ return parsed.data;
134
+ }
@@ -0,0 +1,3 @@
1
+ export { ConfigError, defineEnv, type EnvProblem, type EnvSource, type EnvSpec, } from "./define-env.ts";
2
+ export { loadEnvFile } from "./load-env-file.ts";
3
+ export { isProductionEnv, type StackEnv, stackEnv, stackEnvSchema, stackGroups, stackProductionRequired, } from "./stack-env.ts";
@@ -0,0 +1,3 @@
1
+ export { ConfigError, defineEnv, } from "./define-env.js";
2
+ export { loadEnvFile } from "./load-env-file.js";
3
+ export { isProductionEnv, stackEnv, stackEnvSchema, stackGroups, stackProductionRequired, } from "./stack-env.js";
@@ -0,0 +1,15 @@
1
+ /**
2
+ * Zero-dependency `.env` loader for every entry point Next.js does not boot (drizzle config,
3
+ * test setup, scripts). Rules:
4
+ *
5
+ * - never overrides a variable that is already set: real process env always wins, which is what
6
+ * makes this safe on Vercel and in CI;
7
+ * - never throws when the file is absent, since production supplies real env vars. A file named
8
+ * with `ENV_FILE` is different: the command asked for that file, so a missing one throws rather
9
+ * than surfacing later as some unrelated variable being unset;
10
+ * - no interpolation, no `export` keyword handling. Keep `.env` boring.
11
+ *
12
+ * With no `path`, the file is `target.ENV_FILE` if set, else `.env`. A `path` passed explicitly
13
+ * that does not exist is skipped silently; only `ENV_FILE` is treated as an explicit request.
14
+ */
15
+ export declare function loadEnvFile(path?: string, target?: Record<string, string | undefined>): void;
@@ -0,0 +1,52 @@
1
+ import { readFileSync } from "node:fs";
2
+ /**
3
+ * Zero-dependency `.env` loader for every entry point Next.js does not boot (drizzle config,
4
+ * test setup, scripts). Rules:
5
+ *
6
+ * - never overrides a variable that is already set: real process env always wins, which is what
7
+ * makes this safe on Vercel and in CI;
8
+ * - never throws when the file is absent, since production supplies real env vars. A file named
9
+ * with `ENV_FILE` is different: the command asked for that file, so a missing one throws rather
10
+ * than surfacing later as some unrelated variable being unset;
11
+ * - no interpolation, no `export` keyword handling. Keep `.env` boring.
12
+ *
13
+ * With no `path`, the file is `target.ENV_FILE` if set, else `.env`. A `path` passed explicitly
14
+ * that does not exist is skipped silently; only `ENV_FILE` is treated as an explicit request.
15
+ */
16
+ export function loadEnvFile(path, target = process.env) {
17
+ const envFile = target.ENV_FILE?.trim() ? target.ENV_FILE : undefined;
18
+ const named = path === undefined ? envFile : undefined;
19
+ const file = path ?? named ?? ".env";
20
+ let contents;
21
+ try {
22
+ // Runtime only, from the working directory: not a file for the bundler to trace.
23
+ contents = readFileSync(/* turbopackIgnore: true */ file, "utf8");
24
+ }
25
+ catch (error) {
26
+ // Only "not there" is expected (production and CI have no .env); EACCES, EISDIR and the like
27
+ // are real problems and must not look like an absent file.
28
+ if (error.code !== "ENOENT")
29
+ throw error;
30
+ if (named !== undefined) {
31
+ throw new Error(`ENV_FILE=${file}: no such file. Create it, or unset ENV_FILE.`);
32
+ }
33
+ return;
34
+ }
35
+ for (const rawLine of contents.split("\n")) {
36
+ const line = rawLine.trim();
37
+ if (line.length === 0 || line.startsWith("#"))
38
+ continue;
39
+ const eq = line.indexOf("=");
40
+ if (eq <= 0)
41
+ continue;
42
+ const key = line.slice(0, eq).trim();
43
+ let value = line.slice(eq + 1).trim();
44
+ if (value.length >= 2 &&
45
+ ((value.startsWith('"') && value.endsWith('"')) ||
46
+ (value.startsWith("'") && value.endsWith("'")))) {
47
+ value = value.slice(1, -1);
48
+ }
49
+ if (target[key] === undefined)
50
+ target[key] = value;
51
+ }
52
+ }
@@ -0,0 +1,39 @@
1
+ import { z } from "zod";
2
+ import { type EnvSource } from "./define-env.ts";
3
+ /**
4
+ * The variables every stack app shares. Apps extend it:
5
+ * `defineEnv({ schema: { ...stackEnvSchema, MY_VAR: z.string() }, ... })`.
6
+ * Blank values are treated as absent by `defineEnv`, so no field needs its own preprocessing.
7
+ */
8
+ export declare const stackEnvSchema: {
9
+ NODE_ENV: z.ZodDefault<z.ZodEnum<{
10
+ production: "production";
11
+ development: "development";
12
+ test: "test";
13
+ }>>;
14
+ APP_URL: z.ZodDefault<z.ZodString>;
15
+ DATABASE_URL: z.ZodString;
16
+ DATABASE_URL_UNPOOLED: z.ZodOptional<z.ZodString>;
17
+ PRODUCTION_DATABASE_HOST: z.ZodOptional<z.ZodString>;
18
+ BETTER_AUTH_SECRET: z.ZodDefault<z.ZodString>;
19
+ RESEND_API_KEY: z.ZodOptional<z.ZodString>;
20
+ EMAIL_FROM: z.ZodDefault<z.ZodString>;
21
+ MAGIC_LINK_SINK_PATH: z.ZodDefault<z.ZodString>;
22
+ CRON_SECRET: z.ZodOptional<z.ZodString>;
23
+ HEALTH_TOKEN: z.ZodOptional<z.ZodString>;
24
+ GOOGLE_CLIENT_ID: z.ZodOptional<z.ZodString>;
25
+ GOOGLE_CLIENT_SECRET: z.ZodOptional<z.ZodString>;
26
+ TRUSTED_PROXY_HOPS: z.ZodDefault<z.ZodCoercedNumber<unknown>>;
27
+ AUTH_RATE_LIMIT_PER_HOUR: z.ZodDefault<z.ZodCoercedNumber<unknown>>;
28
+ LOG_LEVEL: z.ZodDefault<z.ZodString>;
29
+ };
30
+ /** Required (raw, non-blank) when NODE_ENV is production. Spread it to extend. */
31
+ export declare const stackProductionRequired: readonly ["APP_URL", "DATABASE_URL", "BETTER_AUTH_SECRET", "RESEND_API_KEY", "EMAIL_FROM"];
32
+ /** All-or-none groups. Spread it to extend. */
33
+ export declare const stackGroups: {
34
+ readonly google: readonly ["GOOGLE_CLIENT_ID", "GOOGLE_CLIENT_SECRET"];
35
+ };
36
+ export type StackEnv = z.infer<z.ZodObject<typeof stackEnvSchema>>;
37
+ export declare function stackEnv(source?: EnvSource): StackEnv;
38
+ /** Whether this is a production run. For the build-time config, which loads before any env schema. */
39
+ export declare function isProductionEnv(source?: EnvSource): boolean;
@@ -0,0 +1,52 @@
1
+ import { z } from "zod";
2
+ import { defineEnv } from "./define-env.js";
3
+ const count = (fallback) => z.coerce.number().int().positive().default(fallback);
4
+ /**
5
+ * The variables every stack app shares. Apps extend it:
6
+ * `defineEnv({ schema: { ...stackEnvSchema, MY_VAR: z.string() }, ... })`.
7
+ * Blank values are treated as absent by `defineEnv`, so no field needs its own preprocessing.
8
+ */
9
+ export const stackEnvSchema = {
10
+ // Set by tooling, never by `.env`: next dev/build set it, Vitest sets `test`, Vercel's runtime
11
+ // sets `production`.
12
+ NODE_ENV: z.enum(["development", "test", "production"]).default("development"),
13
+ APP_URL: z.string().default("http://localhost:3000"),
14
+ DATABASE_URL: z.string().min(1),
15
+ DATABASE_URL_UNPOOLED: z.string().optional(),
16
+ // Production's database host, so local tooling can refuse it.
17
+ PRODUCTION_DATABASE_HOST: z.string().optional(),
18
+ // Signs session cookies and tokens. Better Auth warns on fewer than 32 characters.
19
+ BETTER_AUTH_SECRET: z.string().min(32).default("dev-only-better-auth-secret-change-me"),
20
+ // Sign-in mail. Production sends through Resend; elsewhere the link goes to the sink file.
21
+ RESEND_API_KEY: z.string().optional(),
22
+ EMAIL_FROM: z.string().default("App <no-reply@example.invalid>"),
23
+ MAGIC_LINK_SINK_PATH: z.string().default(".magic-links.log"),
24
+ CRON_SECRET: z.string().optional(),
25
+ HEALTH_TOKEN: z.string().optional(),
26
+ // Sign in with Google. Both or neither (group `google`).
27
+ GOOGLE_CLIENT_ID: z.string().optional(),
28
+ GOOGLE_CLIENT_SECRET: z.string().optional(),
29
+ // 0 on Vercel, which terminates the proxy chain itself.
30
+ TRUSTED_PROXY_HOPS: z.coerce.number().int().nonnegative().default(0),
31
+ AUTH_RATE_LIMIT_PER_HOUR: count(10),
32
+ LOG_LEVEL: z.string().default("info"),
33
+ };
34
+ /** Required (raw, non-blank) when NODE_ENV is production. Spread it to extend. */
35
+ export const stackProductionRequired = [
36
+ "APP_URL",
37
+ "DATABASE_URL",
38
+ "BETTER_AUTH_SECRET",
39
+ "RESEND_API_KEY",
40
+ "EMAIL_FROM",
41
+ ];
42
+ /** All-or-none groups. Spread it to extend. */
43
+ export const stackGroups = {
44
+ google: ["GOOGLE_CLIENT_ID", "GOOGLE_CLIENT_SECRET"],
45
+ };
46
+ export function stackEnv(source = process.env) {
47
+ return defineEnv({ schema: stackEnvSchema, productionRequired: stackProductionRequired, groups: stackGroups }, source);
48
+ }
49
+ /** Whether this is a production run. For the build-time config, which loads before any env schema. */
50
+ export function isProductionEnv(source = process.env) {
51
+ return source.NODE_ENV === "production";
52
+ }
@@ -0,0 +1,8 @@
1
+ /** `TEST_DATABASE_URL`: a real Postgres server for test databases (a CI job's service); else PGlite. */
2
+ export declare function testDatabaseUrl(source?: Record<string, string | undefined>): string | undefined;
3
+ /**
4
+ * Points DATABASE_URL at a closed port before anything loads `.env`: an env loader never overrides
5
+ * a variable that is already set, so `.env`, which may name a real, remote database, cannot reach a
6
+ * test. A test that needs a database starts its own.
7
+ */
8
+ export declare function isolateTestEnv(target?: Record<string, string | undefined>): void;
@@ -0,0 +1,16 @@
1
+ // The environment the test helpers (`@wwchen/stack/db/testing`) read and write, kept here so that
2
+ // src/env/ stays the one place in the package that touches `process.env`.
3
+ /** `TEST_DATABASE_URL`: a real Postgres server for test databases (a CI job's service); else PGlite. */
4
+ export function testDatabaseUrl(source = process.env) {
5
+ const url = source.TEST_DATABASE_URL?.trim();
6
+ return url ? url : undefined;
7
+ }
8
+ /**
9
+ * Points DATABASE_URL at a closed port before anything loads `.env`: an env loader never overrides
10
+ * a variable that is already set, so `.env`, which may name a real, remote database, cannot reach a
11
+ * test. A test that needs a database starts its own.
12
+ */
13
+ export function isolateTestEnv(target = process.env) {
14
+ target.DATABASE_URL = "postgres://unused:unused@127.0.0.1:1/unused";
15
+ target.DATABASE_URL_UNPOOLED = "";
16
+ }
@@ -0,0 +1,12 @@
1
+ /**
2
+ * Who the caller is, read from standard forwarded headers in this one place. No vendor-specific
3
+ * header (Cloudflare's, Vercel's) is read: the proxy in front of the app is infrastructure, and
4
+ * `X-Forwarded-For` already carries the value.
5
+ *
6
+ * The client is the first entry a trusted proxy did not add: with `hops` trusted proxies in front,
7
+ * the Nth-from-last entry in `X-Forwarded-For`. Trusting the *first* entry instead is the classic
8
+ * spoof — a caller can send any `X-Forwarded-For` they like, and only the entries the proxies
9
+ * themselves appended can be believed. Hence counting from the right. Vercel terminates the chain
10
+ * itself, so `hops` is 0 there.
11
+ */
12
+ export declare function clientIp(headers: Headers, hops: number): string | null;
@@ -0,0 +1,28 @@
1
+ /**
2
+ * Who the caller is, read from standard forwarded headers in this one place. No vendor-specific
3
+ * header (Cloudflare's, Vercel's) is read: the proxy in front of the app is infrastructure, and
4
+ * `X-Forwarded-For` already carries the value.
5
+ *
6
+ * The client is the first entry a trusted proxy did not add: with `hops` trusted proxies in front,
7
+ * the Nth-from-last entry in `X-Forwarded-For`. Trusting the *first* entry instead is the classic
8
+ * spoof — a caller can send any `X-Forwarded-For` they like, and only the entries the proxies
9
+ * themselves appended can be believed. Hence counting from the right. Vercel terminates the chain
10
+ * itself, so `hops` is 0 there.
11
+ */
12
+ export function clientIp(headers, hops) {
13
+ const forwarded = headers.get("x-forwarded-for");
14
+ if (forwarded !== null) {
15
+ const entries = forwarded
16
+ .split(",")
17
+ .map((entry) => entry.trim())
18
+ .filter((entry) => entry.length > 0);
19
+ if (entries.length > 0) {
20
+ // Clamped: a request that arrived with fewer hops than configured is not a reason to return
21
+ // nothing, and the left-most entry is the best remaining guess.
22
+ const index = Math.max(entries.length - 1 - hops, 0);
23
+ return entries[index];
24
+ }
25
+ }
26
+ // Standard, non-vendor fallback only.
27
+ return headers.get("x-real-ip") ?? null;
28
+ }
@@ -0,0 +1,17 @@
1
+ /** A method that can change state: everything but GET, HEAD and OPTIONS. */
2
+ export declare function isMutation(request: Request): boolean;
3
+ /** `application/json`, with or without parameters (`; charset=utf-8`). */
4
+ export declare function isJsonRequest(request: Request): boolean;
5
+ /**
6
+ * Whether a mutation came from this app's own pages. Browsers attach `Origin` to every cross-origin
7
+ * and every non-GET request, so it is compared with the host the request was addressed to (the
8
+ * host, not the scheme: a proxy that ends TLS makes the scheme the app sees untrue). Without
9
+ * `Origin`, `Sec-Fetch-Site` decides. A request with neither is not from a browser page, and a
10
+ * session cookie must not ride on it, so it is refused.
11
+ */
12
+ export declare function isSameOrigin(request: Request): boolean;
13
+ /**
14
+ * Whether `Authorization` is `Bearer <secret>`. An unset or empty secret matches nothing, so
15
+ * `Bearer undefined` is never accepted. The comparison is constant-time.
16
+ */
17
+ export declare function bearerMatches(request: Request, secret: string | undefined): boolean;
@@ -0,0 +1,57 @@
1
+ import { timingSafeEqual } from "node:crypto";
2
+ /**
3
+ * Request guards shared by the API wrapper, the cron route and the health route. Pure functions of
4
+ * a `Request`: none reads the environment or the database.
5
+ */
6
+ const SAFE_METHODS = new Set(["GET", "HEAD", "OPTIONS"]);
7
+ /** A method that can change state: everything but GET, HEAD and OPTIONS. */
8
+ export function isMutation(request) {
9
+ return !SAFE_METHODS.has(request.method.toUpperCase());
10
+ }
11
+ /** `application/json`, with or without parameters (`; charset=utf-8`). */
12
+ export function isJsonRequest(request) {
13
+ const type = request.headers.get("content-type")?.split(";")[0]?.trim().toLowerCase();
14
+ return type === "application/json";
15
+ }
16
+ function hostOf(origin) {
17
+ if (origin === null)
18
+ return null;
19
+ try {
20
+ return new URL(origin).host;
21
+ }
22
+ catch {
23
+ return null; // `Origin: null` (sandboxed frames, redirects across origins) and garbage
24
+ }
25
+ }
26
+ /** The host the caller addressed: behind a proxy that is `X-Forwarded-Host`, not the internal one. */
27
+ function servedHost(request) {
28
+ const forwarded = request.headers.get("x-forwarded-host")?.split(",")[0]?.trim();
29
+ return forwarded || request.headers.get("host") || new URL(request.url).host;
30
+ }
31
+ /**
32
+ * Whether a mutation came from this app's own pages. Browsers attach `Origin` to every cross-origin
33
+ * and every non-GET request, so it is compared with the host the request was addressed to (the
34
+ * host, not the scheme: a proxy that ends TLS makes the scheme the app sees untrue). Without
35
+ * `Origin`, `Sec-Fetch-Site` decides. A request with neither is not from a browser page, and a
36
+ * session cookie must not ride on it, so it is refused.
37
+ */
38
+ export function isSameOrigin(request) {
39
+ const origin = request.headers.get("origin");
40
+ if (origin !== null)
41
+ return hostOf(origin) === servedHost(request);
42
+ return request.headers.get("sec-fetch-site") === "same-origin";
43
+ }
44
+ /**
45
+ * Whether `Authorization` is `Bearer <secret>`. An unset or empty secret matches nothing, so
46
+ * `Bearer undefined` is never accepted. The comparison is constant-time.
47
+ */
48
+ export function bearerMatches(request, secret) {
49
+ if (!secret)
50
+ return false;
51
+ const presented = Buffer.from(request.headers.get("authorization") ?? "");
52
+ const expected = Buffer.from(`Bearer ${secret}`);
53
+ // `timingSafeEqual` throws on unequal lengths, so compare those first.
54
+ if (presented.length !== expected.length)
55
+ return false;
56
+ return timingSafeEqual(presented, expected);
57
+ }
@@ -0,0 +1,34 @@
1
+ /**
2
+ * Past this many buckets, a new one first sweeps out every expired bucket. A caller can invent
3
+ * paths (every `/api/auth/<anything>` is counted), so the store must not only grow; a live bucket
4
+ * is never swept, so sweeping cannot hand anyone a fresh budget.
5
+ */
6
+ export declare const RATE_LIMIT_SWEEP_AT = 10000;
7
+ /**
8
+ * A sweep walks the whole store, and past the cap with every bucket live it frees nothing, so the
9
+ * next request would walk it again: at most one sweep per interval keeps that off every request.
10
+ */
11
+ export declare const RATE_LIMIT_SWEEP_INTERVAL_MS: number;
12
+ export declare function rateLimitStoreSize(): number;
13
+ /** Test-only reset, so one case's bucket cannot decide the next one's outcome. */
14
+ export declare function resetRateLimits(): void;
15
+ export type RateLimitInput = {
16
+ /** What is being limited, e.g. `/api/auth/sign-in/magic-link`. Each path has its own budget. */
17
+ path: string;
18
+ /** The request's headers, for the client address. */
19
+ headers: Headers;
20
+ /** Requests allowed per caller per path per hour. `Infinity` never limits. */
21
+ limit: number;
22
+ /** Proxies in front of the app that append to `X-Forwarded-For`. */
23
+ trustedProxyHops: number;
24
+ now?: number;
25
+ };
26
+ /**
27
+ * Answers a **429 with `Retry-After`** when this caller has used up `limit` on `path` within the
28
+ * hour, and null — meaning "carry on" — every other time.
29
+ *
30
+ * Returning a Response rather than throwing keeps the decision at the edge: the caller writes
31
+ * `const limited = rateLimit(...); if (limited) return limited;`. The body is the
32
+ * `{ error: { code, message } }` envelope every API error uses.
33
+ */
34
+ export declare function rateLimit(input: RateLimitInput): Response | null;