@wwchen/stack 0.9.1 → 0.11.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/README.md +50 -23
- package/blocks/AGENTS.md +11 -31
- package/blocks/CLAUDE.md +10 -36
- package/blocks/env.example +1 -18
- package/blocks/gitignore +1 -8
- package/dist/cli/builtin.d.ts +7 -0
- package/dist/cli/builtin.js +42 -0
- package/dist/cli/check.d.ts +5 -0
- package/dist/cli/check.js +39 -0
- package/dist/cli/context.d.ts +4 -35
- package/dist/cli/context.js +1 -23
- package/dist/cli/discover.d.ts +15 -0
- package/dist/cli/discover.js +156 -0
- package/dist/cli/generate.d.ts +6 -0
- package/dist/cli/generate.js +94 -0
- package/dist/cli/host.d.ts +8 -0
- package/dist/cli/host.js +146 -0
- package/dist/cli/index.js +4 -71
- package/dist/cli/owned.d.ts +33 -0
- package/dist/cli/owned.js +151 -0
- package/dist/cli/sync.d.ts +19 -0
- package/dist/cli/sync.js +231 -0
- package/dist/configs/vitest.d.ts +3 -1
- package/dist/configs/vitest.js +8 -11
- package/dist/connections/env.d.ts +8 -0
- package/dist/connections/env.js +15 -0
- package/dist/connections/index.d.ts +1 -1
- package/dist/connections/index.js +1 -1
- package/dist/connections/table.d.ts +5 -3
- package/dist/connections/table.js +3 -3
- package/dist/env/core-env.d.ts +23 -0
- package/dist/env/core-env.js +24 -0
- package/dist/env/define-env.d.ts +22 -10
- package/dist/env/define-env.js +72 -17
- package/dist/env/index.d.ts +2 -2
- package/dist/env/index.js +1 -1
- package/dist/http/client-ip.d.ts +6 -0
- package/dist/http/client-ip.js +21 -0
- package/dist/http/index.d.ts +2 -0
- package/dist/http/index.js +2 -0
- package/dist/http/safe-next.d.ts +11 -0
- package/dist/http/safe-next.js +30 -0
- package/dist/index.d.ts +2 -1
- package/dist/index.js +1 -1
- package/dist/next/api.d.ts +9 -8
- package/dist/next/api.js +10 -8
- package/dist/next/config.d.ts +2 -0
- package/dist/next/config.js +10 -6
- package/dist/next/health.d.ts +5 -7
- package/dist/next/health.js +16 -17
- package/dist/stack/contracts.d.ts +202 -0
- package/dist/stack/contracts.js +66 -0
- package/dist/vercel/index.d.ts +28 -0
- package/dist/vercel/index.js +90 -0
- package/files/.claude/rules/stack-ui.md +24 -0
- package/files/next.config.ts +6 -0
- package/files/src/app/api/health/route.ts +9 -0
- package/package.json +16 -29
- package/dist/cli/db.d.ts +0 -4
- package/dist/cli/db.js +0 -43
- package/dist/cli/dev.d.ts +0 -4
- package/dist/cli/dev.js +0 -70
- package/dist/cli/doctor.d.ts +0 -40
- package/dist/cli/doctor.js +0 -166
- package/dist/cli/migrate-suite.d.ts +0 -2
- package/dist/cli/migrate-suite.js +0 -491
- package/dist/cli/neon.d.ts +0 -79
- package/dist/cli/neon.js +0 -384
- package/dist/cli/run.d.ts +0 -2
- package/dist/cli/run.js +0 -29
- package/dist/cli/sync-blocks.d.ts +0 -14
- package/dist/cli/sync-blocks.js +0 -93
- package/dist/cli/user-create.d.ts +0 -6
- package/dist/cli/user-create.js +0 -77
- package/dist/cli/vercel-build.d.ts +0 -4
- package/dist/cli/vercel-build.js +0 -61
- package/dist/db/explaining-pool.d.ts +0 -11
- package/dist/db/explaining-pool.js +0 -55
- package/dist/db/index.d.ts +0 -20
- package/dist/db/index.js +0 -31
- package/dist/db/migration-status.d.ts +0 -5
- package/dist/db/migration-status.js +0 -38
- package/dist/db/schema-changes.d.ts +0 -13
- package/dist/db/schema-changes.js +0 -99
- package/dist/db/ssl.d.ts +0 -4
- package/dist/db/ssl.js +0 -17
- package/dist/db/target.d.ts +0 -19
- package/dist/db/target.js +0 -65
- package/dist/db/testing/index.d.ts +0 -23
- package/dist/db/testing/index.js +0 -67
- package/dist/db/testing/isolate.d.ts +0 -1
- package/dist/db/testing/isolate.js +0 -3
- package/dist/db/testing/pglite.d.ts +0 -20
- package/dist/db/testing/pglite.js +0 -79
- package/dist/env/stack-env.d.ts +0 -37
- package/dist/env/stack-env.js +0 -54
- package/dist/env/testing.d.ts +0 -6
- package/dist/env/testing.js +0 -13
package/dist/env/define-env.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { readFileSync } from "node:fs";
|
|
2
2
|
import { z } from "zod";
|
|
3
|
+
import { NODE_ENVS, VERCEL_TARGET } from "../stack/contracts.js";
|
|
3
4
|
/**
|
|
4
5
|
* Thrown by `defineEnv` with every problem found, not just the first. The message names each bad variable and says what is wrong with it; it never contains a variable's value, because values can be secrets.
|
|
5
6
|
*/
|
|
@@ -13,8 +14,6 @@ export class ConfigError extends Error {
|
|
|
13
14
|
this.problems = problems;
|
|
14
15
|
}
|
|
15
16
|
}
|
|
16
|
-
/** Stands in for a connection string during a build, which never opens a connection. */
|
|
17
|
-
const BUILD_PLACEHOLDER_DATABASE_URL = "postgres://unused:unused@127.0.0.1:1/unused";
|
|
18
17
|
const TRAILING_NEWLINES = /[\r\n]+$/;
|
|
19
18
|
const isBlank = (value) => value === undefined || value.trim() === "";
|
|
20
19
|
/**
|
|
@@ -54,36 +53,92 @@ function resolve(name, source, problems) {
|
|
|
54
53
|
function withVercelAppUrl(source) {
|
|
55
54
|
if (!isBlank(source.APP_URL) || !isBlank(source.APP_URL_FILE))
|
|
56
55
|
return source;
|
|
57
|
-
const host = source.VERCEL_ENV ===
|
|
56
|
+
const host = source.VERCEL_ENV === VERCEL_TARGET.production
|
|
58
57
|
? (source.VERCEL_PROJECT_PRODUCTION_URL ?? "").trim()
|
|
59
|
-
: source.VERCEL_ENV ===
|
|
58
|
+
: source.VERCEL_ENV === VERCEL_TARGET.preview
|
|
60
59
|
? (source.VERCEL_BRANCH_URL ?? "").trim() || (source.VERCEL_URL ?? "").trim()
|
|
61
60
|
: "";
|
|
62
61
|
return host === "" ? source : { ...source, APP_URL: `https://${host}` };
|
|
63
62
|
}
|
|
64
63
|
/**
|
|
65
|
-
*
|
|
64
|
+
* Merges the fragments and the app's own schema into one. A fragment is named by its `name` (`coreEnv`). A package's variable is the package's, its default included: the app sets its value in the environment and never defines it again. A variable defined twice, or a requirement or group member that nothing defines, is a mistake in the app's code, not its environment, so it throws a plain `Error` naming each one.
|
|
65
|
+
*/
|
|
66
|
+
function merge(spec) {
|
|
67
|
+
const app = {
|
|
68
|
+
name: "the app's schema",
|
|
69
|
+
schema: spec.schema ?? {},
|
|
70
|
+
productionRequired: spec.productionRequired,
|
|
71
|
+
groups: spec.groups,
|
|
72
|
+
};
|
|
73
|
+
const sources = [
|
|
74
|
+
...(spec.fragments ?? []).map((fragment, i) => {
|
|
75
|
+
// A fragment from plain JavaScript may lack its name; its position names it then.
|
|
76
|
+
const label = fragment.name || `fragment ${i + 1}`;
|
|
77
|
+
return { label, whose: `${label}'s`, fragment };
|
|
78
|
+
}),
|
|
79
|
+
{ label: "the app's schema", whose: "the app's", fragment: app },
|
|
80
|
+
];
|
|
81
|
+
const mistakes = [];
|
|
82
|
+
const definedBy = new Map();
|
|
83
|
+
const merged = { shape: {}, productionRequired: [], groups: [], placeholders: {} };
|
|
84
|
+
for (const { label, fragment } of sources) {
|
|
85
|
+
for (const [name, type] of Object.entries(fragment.schema)) {
|
|
86
|
+
const first = definedBy.get(name);
|
|
87
|
+
if (first === undefined) {
|
|
88
|
+
definedBy.set(name, label);
|
|
89
|
+
merged.shape[name] = type;
|
|
90
|
+
}
|
|
91
|
+
else {
|
|
92
|
+
mistakes.push(fragment === app
|
|
93
|
+
? `${name} is defined by ${first}: remove it from the app's schema, and set its value in the environment`
|
|
94
|
+
: `${name} is defined twice: by ${first} and ${label}`);
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
merged.productionRequired.push(...(fragment.productionRequired ?? []));
|
|
98
|
+
merged.groups.push(...Object.entries(fragment.groups ?? {}));
|
|
99
|
+
Object.assign(merged.placeholders, fragment.buildPlaceholders);
|
|
100
|
+
}
|
|
101
|
+
for (const { whose, fragment } of sources) {
|
|
102
|
+
const named = [
|
|
103
|
+
...(fragment.productionRequired ?? []).map((name) => ({ name, by: "productionRequired" })),
|
|
104
|
+
...Object.entries(fragment.groups ?? {}).flatMap(([group, members]) => members.map((name) => ({ name, by: `group ${group}` }))),
|
|
105
|
+
];
|
|
106
|
+
for (const { name, by } of named) {
|
|
107
|
+
if (definedBy.has(name))
|
|
108
|
+
continue;
|
|
109
|
+
mistakes.push(`${name} is named by ${whose} ${by}, but no fragment or the app's schema defines it`);
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
if (mistakes.length > 0)
|
|
113
|
+
throw new Error(`defineEnv: ${mistakes.join("; ")}`);
|
|
114
|
+
return merged;
|
|
115
|
+
}
|
|
116
|
+
/**
|
|
117
|
+
* Validates `source` (default `process.env`, the only place the package reads it) against the fragments' schemas and the app's own `schema`, merged.
|
|
66
118
|
*
|
|
119
|
+
* - A variable defined by two fragments, or by a fragment and the app's schema, throws an `Error` naming both.
|
|
67
120
|
* - Blank values are absent; `<NAME>_FILE` is read when `<NAME>` is unset (both set is an error).
|
|
68
121
|
* - Production requirements are checked against the resolved value before defaults apply, so a development default can never satisfy one.
|
|
69
|
-
* - During a Next build (`NEXT_PHASE=phase-production-build`) or with `SKIP_ENV_VALIDATION=1`, a build is not a boot: production requirements
|
|
70
|
-
* - When the schema has `APP_URL` and it is unset, it is derived on Vercel: from VERCEL_PROJECT_PRODUCTION_URL in production, from VERCEL_BRANCH_URL / VERCEL_URL on a preview
|
|
122
|
+
* - During a Next build (`NEXT_PHASE=phase-production-build`) or with `SKIP_ENV_VALIDATION=1`, a build is not a boot: production requirements and groups are not enforced, and an unset variable with a fragment's build placeholder takes it, but defaults still apply. With `NODE_ENV=production`, `SKIP_ENV_VALIDATION` is ignored outside the build phase.
|
|
123
|
+
* - When the merged schema has `APP_URL` and it is unset, it is derived on Vercel: from VERCEL_PROJECT_PRODUCTION_URL in production, from VERCEL_BRANCH_URL / VERCEL_URL on a preview.
|
|
71
124
|
* - Throws one `ConfigError` listing every problem.
|
|
72
125
|
*/
|
|
73
126
|
export function defineEnv(spec, rawSource = process.env) {
|
|
74
|
-
const
|
|
127
|
+
const { shape, productionRequired, groups, placeholders } = merge(spec);
|
|
128
|
+
const source = "APP_URL" in shape ? withVercelAppUrl(rawSource) : rawSource;
|
|
75
129
|
const problems = [];
|
|
76
130
|
const resolved = {};
|
|
77
|
-
for (const name of Object.keys(
|
|
131
|
+
for (const name of Object.keys(shape)) {
|
|
78
132
|
resolved[name] = resolve(name, source, problems);
|
|
79
133
|
}
|
|
80
|
-
// SKIP_ENV_VALIDATION is for builds and tooling. A production server that inherited it would boot on development defaults (a public
|
|
134
|
+
// SKIP_ENV_VALIDATION is for builds and tooling. A production server that inherited it would boot on development defaults (a public development secret), so production honours it only in the build phase.
|
|
81
135
|
const building = source.NEXT_PHASE === "phase-production-build";
|
|
82
|
-
const skipValidation = building || (source.SKIP_ENV_VALIDATION === "1" && source.NODE_ENV !==
|
|
83
|
-
if (skipValidation
|
|
84
|
-
|
|
136
|
+
const skipValidation = building || (source.SKIP_ENV_VALIDATION === "1" && source.NODE_ENV !== NODE_ENVS.production);
|
|
137
|
+
if (skipValidation) {
|
|
138
|
+
for (const [name, placeholder] of Object.entries(placeholders))
|
|
139
|
+
resolved[name] ??= placeholder;
|
|
85
140
|
}
|
|
86
|
-
const parsed = z.object(
|
|
141
|
+
const parsed = z.object(shape).safeParse(resolved);
|
|
87
142
|
// One problem per variable: a bad `_FILE` also leaves its plain name unset, and a missing production secret may also fail the schema.
|
|
88
143
|
const reported = new Set(problems.flatMap((p) => [p.variable, p.variable.replace(/_FILE$/, "")]));
|
|
89
144
|
if (!parsed.success) {
|
|
@@ -96,7 +151,7 @@ export function defineEnv(spec, rawSource = process.env) {
|
|
|
96
151
|
}
|
|
97
152
|
}
|
|
98
153
|
if (!skipValidation) {
|
|
99
|
-
for (const [group, members] of
|
|
154
|
+
for (const [group, members] of groups) {
|
|
100
155
|
const present = members.filter((name) => resolved[name] !== undefined);
|
|
101
156
|
if (present.length === 0 || present.length === members.length)
|
|
102
157
|
continue;
|
|
@@ -107,8 +162,8 @@ export function defineEnv(spec, rawSource = process.env) {
|
|
|
107
162
|
});
|
|
108
163
|
}
|
|
109
164
|
}
|
|
110
|
-
if (resolved.NODE_ENV ===
|
|
111
|
-
for (const name of
|
|
165
|
+
if (resolved.NODE_ENV === NODE_ENVS.production) {
|
|
166
|
+
for (const name of productionRequired) {
|
|
112
167
|
if (resolved[name] === undefined && !reported.has(name)) {
|
|
113
168
|
problems.push({ variable: name, problem: "is required when NODE_ENV is production" });
|
|
114
169
|
}
|
package/dist/env/index.d.ts
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
export {
|
|
1
|
+
export { coreEnv, isProductionEnv } from "./core-env.ts";
|
|
2
|
+
export { ConfigError, defineEnv, type EnvProblem, type EnvSource, type EnvSpec, type MergedShape, } from "./define-env.ts";
|
|
2
3
|
export { loadEnvFile } from "./load-env-file.ts";
|
|
3
|
-
export { isProductionEnv, type StackEnv, stackEnv, stackEnvSchema, stackGroups, stackProductionRequired, } from "./stack-env.ts";
|
package/dist/env/index.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
+
export { coreEnv, isProductionEnv } from "./core-env.js";
|
|
1
2
|
export { ConfigError, defineEnv, } from "./define-env.js";
|
|
2
3
|
export { loadEnvFile } from "./load-env-file.js";
|
|
3
|
-
export { isProductionEnv, stackEnv, stackEnvSchema, stackGroups, stackProductionRequired, } from "./stack-env.js";
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Who the caller is, read from standard forwarded headers in this one place. No vendor-specific header (Cloudflare's, Vercel's) is read: the proxy in front of the app is infrastructure, and `X-Forwarded-For` already carries the value.
|
|
3
|
+
*
|
|
4
|
+
* The client is the first entry a trusted proxy did not add: with `hops` trusted proxies in front, the Nth-from-last entry in `X-Forwarded-For`. Trusting the *first* entry instead is the classic spoof — a caller can send any `X-Forwarded-For` they like, and only the entries the proxies themselves appended can be believed. Hence counting from the right. Vercel terminates the chain itself, so `hops` is 0 there.
|
|
5
|
+
*/
|
|
6
|
+
export declare function clientIp(headers: Headers, hops: number): string | null;
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Who the caller is, read from standard forwarded headers in this one place. No vendor-specific header (Cloudflare's, Vercel's) is read: the proxy in front of the app is infrastructure, and `X-Forwarded-For` already carries the value.
|
|
3
|
+
*
|
|
4
|
+
* The client is the first entry a trusted proxy did not add: with `hops` trusted proxies in front, the Nth-from-last entry in `X-Forwarded-For`. Trusting the *first* entry instead is the classic spoof — a caller can send any `X-Forwarded-For` they like, and only the entries the proxies themselves appended can be believed. Hence counting from the right. Vercel terminates the chain itself, so `hops` is 0 there.
|
|
5
|
+
*/
|
|
6
|
+
export function clientIp(headers, hops) {
|
|
7
|
+
const forwarded = headers.get("x-forwarded-for");
|
|
8
|
+
if (forwarded !== null) {
|
|
9
|
+
const entries = forwarded
|
|
10
|
+
.split(",")
|
|
11
|
+
.map((entry) => entry.trim())
|
|
12
|
+
.filter((entry) => entry.length > 0);
|
|
13
|
+
if (entries.length > 0) {
|
|
14
|
+
// Clamped: a request that arrived with fewer hops than configured is not a reason to return nothing, and the left-most entry is the best remaining guess.
|
|
15
|
+
const index = Math.max(entries.length - 1 - hops, 0);
|
|
16
|
+
return entries[index];
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
// Standard, non-vendor fallback only.
|
|
20
|
+
return headers.get("x-real-ip") ?? null;
|
|
21
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Where to send someone after signing in, from a `?next=` they could have been handed by anyone. Only a path on this site is kept; anything else becomes `fallback`, so a sign-in link can never be turned into a redirect to another origin.
|
|
3
|
+
*
|
|
4
|
+
* Kept: a string starting with a single `/`. Refused, as well as anything that is not a string:
|
|
5
|
+
* - `//host` and `/\host`: browsers read both as protocol-relative URLs to another host;
|
|
6
|
+
* - any backslash: the URL parser turns it into `/`;
|
|
7
|
+
* - control characters: the URL parser strips tabs and newlines, so `/\t/host` becomes `//host`;
|
|
8
|
+
* - `https:`, `javascript:` and every other scheme: they do not start with `/`.
|
|
9
|
+
* Then the path is resolved as a browser would, which removes dot segments (`.`, `..`, `%2e`): it must stay on the origin it is resolved against, and its resolved path must not itself start with `//` — `/..//host` and `/%2e//host` resolve to `//host`, which a router that writes the path back would follow off-site. What is returned is that resolved path, query and fragment, so a caller only ever passes on what was checked.
|
|
10
|
+
*/
|
|
11
|
+
export declare function safeNext(raw: unknown, fallback?: string): string;
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Where to send someone after signing in, from a `?next=` they could have been handed by anyone. Only a path on this site is kept; anything else becomes `fallback`, so a sign-in link can never be turned into a redirect to another origin.
|
|
3
|
+
*
|
|
4
|
+
* Kept: a string starting with a single `/`. Refused, as well as anything that is not a string:
|
|
5
|
+
* - `//host` and `/\host`: browsers read both as protocol-relative URLs to another host;
|
|
6
|
+
* - any backslash: the URL parser turns it into `/`;
|
|
7
|
+
* - control characters: the URL parser strips tabs and newlines, so `/\t/host` becomes `//host`;
|
|
8
|
+
* - `https:`, `javascript:` and every other scheme: they do not start with `/`.
|
|
9
|
+
* Then the path is resolved as a browser would, which removes dot segments (`.`, `..`, `%2e`): it must stay on the origin it is resolved against, and its resolved path must not itself start with `//` — `/..//host` and `/%2e//host` resolve to `//host`, which a router that writes the path back would follow off-site. What is returned is that resolved path, query and fragment, so a caller only ever passes on what was checked.
|
|
10
|
+
*/
|
|
11
|
+
export function safeNext(raw, fallback = "/") {
|
|
12
|
+
if (typeof raw !== "string")
|
|
13
|
+
return fallback;
|
|
14
|
+
if (!raw.startsWith("/") || raw.startsWith("//"))
|
|
15
|
+
return fallback;
|
|
16
|
+
// biome-ignore lint/suspicious/noControlCharactersInRegex: refusing control characters is the point.
|
|
17
|
+
if (/[\\\u0000-\u001f\u007f]/.test(raw))
|
|
18
|
+
return fallback;
|
|
19
|
+
const base = "http://same-site.invalid";
|
|
20
|
+
let url;
|
|
21
|
+
try {
|
|
22
|
+
url = new URL(raw, base);
|
|
23
|
+
}
|
|
24
|
+
catch {
|
|
25
|
+
return fallback;
|
|
26
|
+
}
|
|
27
|
+
if (url.origin !== base || url.pathname.startsWith("//"))
|
|
28
|
+
return fallback;
|
|
29
|
+
return `${url.pathname}${url.search}${url.hash}`;
|
|
30
|
+
}
|
package/dist/index.d.ts
CHANGED
|
@@ -1 +1,2 @@
|
|
|
1
|
-
export {};
|
|
1
|
+
export type { Block, BlockFile, BuildStep, Check, Command, CommandContext, DoctorCheck, DoctorFacts, Env, EnvFragment, EnvVarMeta, ExecOptions, ExecResult, Export, Finding, Gate, GateResult, HealthCheck, NodeEnv, OwnedFile, PackageSettings, Severity, StackConfig, StackFactory, StackPackage, VariableOf, VercelTarget, } from "./stack/contracts.ts";
|
|
2
|
+
export { BLOCK_FILES, BUILTIN_PACKAGE, CORE_PACKAGE, defineStack, FILES_RECORD, GENERATED, NODE_ENVS, packageBlocks, SEVERITY, STACK_CONFIG_FILE, starterFileChecks, VERCEL_TARGET, } from "./stack/contracts.ts";
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export {};
|
|
1
|
+
export { BLOCK_FILES, BUILTIN_PACKAGE, CORE_PACKAGE, defineStack, FILES_RECORD, GENERATED, NODE_ENVS, packageBlocks, SEVERITY, STACK_CONFIG_FILE, starterFileChecks, VERCEL_TARGET, } from "./stack/contracts.js";
|
package/dist/next/api.d.ts
CHANGED
|
@@ -1,10 +1,12 @@
|
|
|
1
|
-
import type {
|
|
1
|
+
import type { Gate } from "../stack/contracts.ts";
|
|
2
2
|
/**
|
|
3
|
-
* The shell every API route runs in:
|
|
3
|
+
* The shell every API route runs in: the gate, the request guards, the handler, and the envelope for whatever it throws. Written once so route files cannot drift on it.
|
|
4
|
+
*
|
|
5
|
+
* The gate decides who the caller is: its 401 is answered `unauthenticated`, its 404 `not_found` (never a 403, so a route the caller may not use does not announce itself), and its principal is handed to the handler. A gate that throws is a bug like any other.
|
|
4
6
|
*
|
|
5
7
|
* Every failure answers `{ error: { code, message } }`. An `ApiError` is answered as it says; that is how `readJson` reports the request body (400 `invalid_json`, 422 `invalid_input`). Anything else is a bug, even a SyntaxError or a ZodError from the route's own code, and becomes a 500 with a fixed message: what was thrown is logged for the operator and never sent to the caller.
|
|
6
8
|
*
|
|
7
|
-
* `CRON_SECRET` and `HEALTH_TOKEN` are never read here. This wrapper
|
|
9
|
+
* `CRON_SECRET` and `HEALTH_TOKEN` are never read here. This wrapper admits only what its gate admits, so neither secret opens an API route.
|
|
8
10
|
*/
|
|
9
11
|
/** An error a route throws on purpose: its message is written for the caller and is sent as is. */
|
|
10
12
|
export declare class ApiError extends Error {
|
|
@@ -49,11 +51,10 @@ export type BodySchema<T> = {
|
|
|
49
51
|
*/
|
|
50
52
|
export declare function readJson(req: Request): Promise<unknown>;
|
|
51
53
|
export declare function readJson<T>(req: Request, schema: BodySchema<T>): Promise<T>;
|
|
52
|
-
export type ApiHandlerOptions = {
|
|
53
|
-
auth: StackAuth;
|
|
54
|
+
export type ApiHandlerOptions<P> = {
|
|
54
55
|
/** What a failure logs as: `"PUT /api/v1/things/:id"`. */
|
|
55
56
|
label: string;
|
|
56
|
-
/**
|
|
57
|
-
|
|
57
|
+
/** Who may call the route; what it admits is the handler's `principal`. */
|
|
58
|
+
gate: Gate<P>;
|
|
58
59
|
};
|
|
59
|
-
export declare function apiHandler<C = unknown>(opts: ApiHandlerOptions
|
|
60
|
+
export declare function apiHandler<P, C = unknown>(opts: ApiHandlerOptions<P>, fn: (req: Request, ctx: C, principal: P) => Promise<Response>): (req: Request, ctx: C) => Promise<Response>;
|
package/dist/next/api.js
CHANGED
|
@@ -1,11 +1,13 @@
|
|
|
1
1
|
import { z } from "zod";
|
|
2
2
|
import { hasNoBody, isJsonRequest, isMutation, isSameOrigin } from "../http/guards.js";
|
|
3
3
|
/**
|
|
4
|
-
* The shell every API route runs in:
|
|
4
|
+
* The shell every API route runs in: the gate, the request guards, the handler, and the envelope for whatever it throws. Written once so route files cannot drift on it.
|
|
5
|
+
*
|
|
6
|
+
* The gate decides who the caller is: its 401 is answered `unauthenticated`, its 404 `not_found` (never a 403, so a route the caller may not use does not announce itself), and its principal is handed to the handler. A gate that throws is a bug like any other.
|
|
5
7
|
*
|
|
6
8
|
* Every failure answers `{ error: { code, message } }`. An `ApiError` is answered as it says; that is how `readJson` reports the request body (400 `invalid_json`, 422 `invalid_input`). Anything else is a bug, even a SyntaxError or a ZodError from the route's own code, and becomes a 500 with a fixed message: what was thrown is logged for the operator and never sent to the caller.
|
|
7
9
|
*
|
|
8
|
-
* `CRON_SECRET` and `HEALTH_TOKEN` are never read here. This wrapper
|
|
10
|
+
* `CRON_SECRET` and `HEALTH_TOKEN` are never read here. This wrapper admits only what its gate admits, so neither secret opens an API route.
|
|
9
11
|
*/
|
|
10
12
|
/** An error a route throws on purpose: its message is written for the caller and is sent as is. */
|
|
11
13
|
export class ApiError extends Error {
|
|
@@ -84,11 +86,11 @@ export async function readJson(req, schema) {
|
|
|
84
86
|
export function apiHandler(opts, fn) {
|
|
85
87
|
return async (req, ctx) => {
|
|
86
88
|
try {
|
|
87
|
-
const
|
|
88
|
-
if (!
|
|
89
|
-
return
|
|
90
|
-
|
|
91
|
-
|
|
89
|
+
const admitted = await opts.gate(req.headers);
|
|
90
|
+
if (!admitted.ok) {
|
|
91
|
+
return admitted.status === 401
|
|
92
|
+
? apiError(401, "unauthenticated", "Sign in to continue.")
|
|
93
|
+
: apiError(404, "not_found", "Not found.");
|
|
92
94
|
}
|
|
93
95
|
if (isMutation(req)) {
|
|
94
96
|
// JSON only, so a cross-site form post can't reach a handler; a request with no body at all (a plain `DELETE`) has nothing to be JSON, and a form always sends a Content-Type.
|
|
@@ -98,7 +100,7 @@ export function apiHandler(opts, fn) {
|
|
|
98
100
|
if (!isSameOrigin(req))
|
|
99
101
|
return apiError(403, "cross_origin", "Cross-origin request refused.");
|
|
100
102
|
}
|
|
101
|
-
return await fn(req, ctx,
|
|
103
|
+
return await fn(req, ctx, admitted.principal);
|
|
102
104
|
}
|
|
103
105
|
catch (error) {
|
|
104
106
|
if (error instanceof ApiError) {
|
package/dist/next/config.d.ts
CHANGED
|
@@ -4,5 +4,7 @@ export type WithStackOptions = {
|
|
|
4
4
|
isProduction?: boolean;
|
|
5
5
|
/** Extra `connect-src` origins (an API or analytics host the browser calls). */
|
|
6
6
|
cspConnectSrc?: string[];
|
|
7
|
+
/** Files a route reads at run time, by route, merged into `outputFileTracingIncludes`: Vercel bundles only traced files. The generated `src/stack/next.ts` holds the packages' share. */
|
|
8
|
+
tracing?: Record<string, string[]>;
|
|
7
9
|
};
|
|
8
10
|
export declare function withStack(appConfig?: NextConfig, opts?: WithStackOptions): NextConfig;
|
package/dist/next/config.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { isProductionEnv } from "../env/index.js";
|
|
2
2
|
/**
|
|
3
|
-
* `next.config.ts`: `export default withStack({ ...the app's own config })`.
|
|
3
|
+
* `next.config.ts`: `export default withStack({ ...the app's own config }, { tracing })`.
|
|
4
4
|
*
|
|
5
5
|
* Sentry (or any monitor) is initialised at runtime from `instrumentation.ts`, not through a build-time config wrapper, so there is nothing to compose here.
|
|
6
6
|
*/
|
|
@@ -51,6 +51,14 @@ function contentSecurityPolicy(connectSrc) {
|
|
|
51
51
|
"upgrade-insecure-requests",
|
|
52
52
|
].join("; ");
|
|
53
53
|
}
|
|
54
|
+
/** The app's tracing and the stack's, each route's globs joined without repeats. */
|
|
55
|
+
function mergeTracing(app = {}, stack = {}) {
|
|
56
|
+
const merged = { ...app };
|
|
57
|
+
for (const [route, globs] of Object.entries(stack)) {
|
|
58
|
+
merged[route] = [...new Set([...(merged[route] ?? []), ...globs])];
|
|
59
|
+
}
|
|
60
|
+
return merged;
|
|
61
|
+
}
|
|
54
62
|
export function withStack(appConfig = {}, opts = {}) {
|
|
55
63
|
const isProduction = opts.isProduction ?? isProductionEnv();
|
|
56
64
|
const stackHeaders = isProduction
|
|
@@ -66,11 +74,7 @@ export function withStack(appConfig = {}, opts = {}) {
|
|
|
66
74
|
reactStrictMode: true,
|
|
67
75
|
...appConfig,
|
|
68
76
|
poweredByHeader: false,
|
|
69
|
-
|
|
70
|
-
outputFileTracingIncludes: {
|
|
71
|
-
...appConfig.outputFileTracingIncludes,
|
|
72
|
-
"/api/health": ["./drizzle/**"],
|
|
73
|
-
},
|
|
77
|
+
outputFileTracingIncludes: mergeTracing(appConfig.outputFileTracingIncludes, opts.tracing),
|
|
74
78
|
// The stack's headers first, then the app's own.
|
|
75
79
|
async headers() {
|
|
76
80
|
return [
|
package/dist/next/health.d.ts
CHANGED
|
@@ -1,14 +1,12 @@
|
|
|
1
|
-
import type {
|
|
1
|
+
import type { HealthCheck } from "../stack/contracts.ts";
|
|
2
2
|
/**
|
|
3
|
-
* Liveness, deliberately not readiness. The status is ALWAYS 200 while the process can answer: a
|
|
3
|
+
* Liveness, deliberately not readiness. The status is ALWAYS 200 while the process can answer: a failing dependency must not make an uptime check report a healthy web process as down.
|
|
4
4
|
*
|
|
5
|
-
* Without the token the answer is `{ ok: true }` and
|
|
5
|
+
* Without the token the answer is `{ ok: true }` and no check runs, so an anonymous caller cannot make the app touch what the checks probe. With `Authorization: Bearer $HEALTH_TOKEN` each check runs in turn and its fields join the answer in order; a check that throws reports `{ [name]: "unknown" }`. `HEALTH_TOKEN` is its own secret, never `CRON_SECRET`.
|
|
6
6
|
*
|
|
7
|
-
* `export const GET = healthRoute({
|
|
7
|
+
* `export const GET = healthRoute({ token: env.HEALTH_TOKEN, checks: healthChecks(env) })`, with `dynamic = "force-dynamic"`.
|
|
8
8
|
*/
|
|
9
9
|
export declare function healthRoute(opts: {
|
|
10
|
-
db?: NodePgDatabase<any>;
|
|
11
|
-
/** Defaults to `drizzle/` under the working directory. */
|
|
12
|
-
migrationsFolder?: string;
|
|
13
10
|
token?: string;
|
|
11
|
+
checks?: HealthCheck[];
|
|
14
12
|
}): (req: Request) => Promise<Response>;
|
package/dist/next/health.js
CHANGED
|
@@ -1,31 +1,30 @@
|
|
|
1
|
-
import path from "node:path";
|
|
2
|
-
import { sql } from "drizzle-orm";
|
|
3
|
-
import { migrationStatus } from "../db/migration-status.js";
|
|
4
1
|
import { bearerMatches } from "../http/guards.js";
|
|
5
2
|
/**
|
|
6
|
-
* Liveness, deliberately not readiness. The status is ALWAYS 200 while the process can answer: a
|
|
3
|
+
* Liveness, deliberately not readiness. The status is ALWAYS 200 while the process can answer: a failing dependency must not make an uptime check report a healthy web process as down.
|
|
7
4
|
*
|
|
8
|
-
* Without the token the answer is `{ ok: true }` and
|
|
5
|
+
* Without the token the answer is `{ ok: true }` and no check runs, so an anonymous caller cannot make the app touch what the checks probe. With `Authorization: Bearer $HEALTH_TOKEN` each check runs in turn and its fields join the answer in order; a check that throws reports `{ [name]: "unknown" }`. `HEALTH_TOKEN` is its own secret, never `CRON_SECRET`.
|
|
9
6
|
*
|
|
10
|
-
* `export const GET = healthRoute({
|
|
7
|
+
* `export const GET = healthRoute({ token: env.HEALTH_TOKEN, checks: healthChecks(env) })`, with `dynamic = "force-dynamic"`.
|
|
11
8
|
*/
|
|
12
9
|
export function healthRoute(opts) {
|
|
13
|
-
const
|
|
10
|
+
const checks = opts.checks ?? [];
|
|
14
11
|
// No-store: a cached liveness answer is not a liveness answer.
|
|
15
12
|
const headers = { "cache-control": "no-store" };
|
|
16
13
|
return async (req) => {
|
|
17
14
|
if (!bearerMatches(req, opts.token))
|
|
18
15
|
return Response.json({ ok: true }, { headers });
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
16
|
+
let body = { ok: true };
|
|
17
|
+
for (const probe of checks) {
|
|
18
|
+
let fields;
|
|
19
|
+
try {
|
|
20
|
+
fields = await probe.check();
|
|
21
|
+
}
|
|
22
|
+
catch (error) {
|
|
23
|
+
console.error(`[health] ${probe.name} check failed`, error);
|
|
24
|
+
fields = { [probe.name]: "unknown" };
|
|
25
|
+
}
|
|
26
|
+
body = { ...body, ...fields };
|
|
24
27
|
}
|
|
25
|
-
|
|
26
|
-
return Response.json({ ok: true, db: "down", migrations: "unknown" }, { headers });
|
|
27
|
-
}
|
|
28
|
-
const migrations = await migrationStatus(db, migrationsFolder).catch(() => "unknown");
|
|
29
|
-
return Response.json({ ok: true, db: "up", migrations }, { headers });
|
|
28
|
+
return Response.json(body, { headers });
|
|
30
29
|
};
|
|
31
30
|
}
|