@wwchen/stack 0.2.1 → 0.3.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 +11 -22
- package/blocks/AGENTS.md +18 -30
- package/blocks/CLAUDE.md +29 -59
- package/blocks/gitignore +1 -0
- package/dist/auth/better-auth/index.d.ts +1 -1
- package/dist/auth/better-auth/tables.js +2 -2
- package/dist/auth/index.js +1 -1
- package/dist/cli/context.d.ts +15 -0
- package/dist/cli/context.js +3 -0
- package/dist/cli/dev.d.ts +4 -0
- package/dist/cli/dev.js +70 -0
- package/dist/cli/doctor.d.ts +40 -0
- package/dist/cli/doctor.js +166 -0
- package/dist/cli/index.d.ts +8 -1
- package/dist/cli/index.js +36 -12
- package/dist/cli/neon.d.ts +16 -5
- package/dist/cli/neon.js +81 -13
- package/dist/cli/run.d.ts +2 -0
- package/dist/cli/run.js +29 -0
- package/dist/cli/user-create.d.ts +4 -0
- package/dist/cli/user-create.js +51 -14
- package/dist/configs/vitest.js +1 -3
- package/dist/connections/crypto.js +1 -4
- package/dist/connections/index.d.ts +1 -3
- package/dist/connections/index.js +1 -3
- package/dist/connections/table.d.ts +1 -3
- package/dist/connections/table.js +1 -3
- package/dist/db/testing/pglite.d.ts +4 -1
- package/dist/db/testing/pglite.js +19 -7
- package/dist/jobs/index.d.ts +2 -5
- package/dist/jobs/index.js +2 -5
- package/package.json +1 -1
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
// `stack doctor` — a read-only audit of the linked Vercel project's hosting setup: the framework preset, and the environment variables the stack depends on. Prints its findings, errors first, and exits non-zero when any is an error. Changes nothing.
|
|
2
|
+
//
|
|
3
|
+
// It reads metadata only — each variable's name, type, targets, id, git branch, and the integration fields (`configurationId`, `comment`) — through the Vercel REST API (`vercel api`), without `decrypt`. A value is dropped the moment the response is parsed, and never printed: whether Preview's DATABASE_URL is production's database can only be told from its value, so that one is left to `stack vercel-build`, which refuses it at build time.
|
|
4
|
+
import { readFileSync } from "node:fs";
|
|
5
|
+
import { join } from "node:path";
|
|
6
|
+
import { CliError } from "./context.js";
|
|
7
|
+
/** What the Neon Vercel integration writes on every variable it creates. */
|
|
8
|
+
export const NEON_INTEGRATION_COMMENT = "The Neon Postgres integration sets this environment variable automatically";
|
|
9
|
+
/** Secrets a preview must hold its own value of, never production's (runbook §3). */
|
|
10
|
+
export const PREVIEW_OWN_SECRETS = [
|
|
11
|
+
"BETTER_AUTH_SECRET",
|
|
12
|
+
"TOKEN_ENCRYPTION_KEY",
|
|
13
|
+
"CRON_SECRET",
|
|
14
|
+
"RESEND_API_KEY",
|
|
15
|
+
"GOOGLE_CLIENT_SECRET",
|
|
16
|
+
];
|
|
17
|
+
const RANK = { error: 0, warning: 1, info: 2 };
|
|
18
|
+
const str = (value) => typeof value === "string" && value !== "" ? value : undefined;
|
|
19
|
+
/** The metadata of one API variable; its value (and anything else) is not copied. */
|
|
20
|
+
export function envVarMeta(raw) {
|
|
21
|
+
const r = (raw ?? {});
|
|
22
|
+
const target = Array.isArray(r.target) ? r.target : r.target === undefined ? [] : [r.target];
|
|
23
|
+
return {
|
|
24
|
+
id: String(r.id ?? ""),
|
|
25
|
+
key: String(r.key ?? ""),
|
|
26
|
+
type: String(r.type ?? ""),
|
|
27
|
+
target: target.filter((t) => typeof t === "string"),
|
|
28
|
+
gitBranch: str(r.gitBranch),
|
|
29
|
+
configurationId: str(r.configurationId),
|
|
30
|
+
comment: str(r.comment),
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
/** Variables named `key` that apply to every deployment of `target`: no single git branch. */
|
|
34
|
+
const covering = (h, key, target) => h.envs.filter((v) => v.key === key && v.target.includes(target) && !v.gitBranch);
|
|
35
|
+
const fromNeonIntegration = (v) => (v.configurationId !== undefined && v.gitBranch !== undefined) ||
|
|
36
|
+
(v.comment?.includes(NEON_INTEGRATION_COMMENT) === true && v.target.includes("preview"));
|
|
37
|
+
/** Every check, on metadata alone. Sorted: errors, then warnings, then notes. */
|
|
38
|
+
export function audit(h) {
|
|
39
|
+
const findings = [];
|
|
40
|
+
const add = (severity, message) => findings.push({ severity, message });
|
|
41
|
+
const preset = h.framework ?? "Other";
|
|
42
|
+
if (h.vercelJsonFramework !== undefined && h.vercelJsonFramework !== "nextjs") {
|
|
43
|
+
add("error", `vercel.json sets "framework": ${JSON.stringify(h.vercelJsonFramework)}, which overrides the project's preset; set it to "nextjs".`);
|
|
44
|
+
}
|
|
45
|
+
else if (h.framework !== "nextjs") {
|
|
46
|
+
if (h.vercelJsonFramework === "nextjs") {
|
|
47
|
+
add("info", `The project's framework preset is ${preset}, but vercel.json's "framework": "nextjs" overrides it.`);
|
|
48
|
+
}
|
|
49
|
+
else {
|
|
50
|
+
add("error", `The project's framework preset is ${preset}, not Next.js, and vercel.json sets no framework: ` +
|
|
51
|
+
'Vercel will not serve the app as Next.js. Add "framework": "nextjs" to vercel.json ' +
|
|
52
|
+
"(or set the preset in Project Settings, Build and Deployment).");
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
const integration = h.envs.filter(fromNeonIntegration);
|
|
56
|
+
if (integration.length > 0) {
|
|
57
|
+
const names = [
|
|
58
|
+
...new Set(integration.map((v) => (v.gitBranch ? `${v.key} (${v.gitBranch})` : v.key))),
|
|
59
|
+
];
|
|
60
|
+
add("error", `The Neon Vercel integration is creating per-preview database variables: ${names.join(", ")}. ` +
|
|
61
|
+
"It cuts each preview's branch from production, copying production's data into previews. " +
|
|
62
|
+
"Turn off its preview branching (Vercel, Integrations, Neon), remove these variables, and " +
|
|
63
|
+
"point Preview at the shared `preview` branch: `stack neon reset-preview --set-vercel`.");
|
|
64
|
+
}
|
|
65
|
+
for (const key of PREVIEW_OWN_SECRETS) {
|
|
66
|
+
const shared = h.envs.filter((v) => v.key === key && v.target.includes("production") && v.target.includes("preview"));
|
|
67
|
+
if (shared.length > 0) {
|
|
68
|
+
add("warning", `${key} is one variable for Production and Preview: give Preview its own value, so a ` +
|
|
69
|
+
"preview can never use production's.");
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
for (const target of ["production", "preview", "development"]) {
|
|
73
|
+
if (covering(h, "PRODUCTION_DATABASE_HOST", target).length === 0) {
|
|
74
|
+
add(target === "development" ? "warning" : "error", `PRODUCTION_DATABASE_HOST is not set for ${target}: set production's direct host (not a ` +
|
|
75
|
+
"secret) in every environment, so builds and local tooling can refuse production." +
|
|
76
|
+
(target === "preview" ? " `stack vercel-build` refuses a preview build without it." : ""));
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
if (covering(h, "DATABASE_URL_UNPOOLED", "production").length === 0) {
|
|
80
|
+
add("warning", "DATABASE_URL_UNPOOLED is not set for Production, so migrations run through the pooler. " +
|
|
81
|
+
"Set it to production's direct (non -pooler) URL.");
|
|
82
|
+
}
|
|
83
|
+
if (covering(h, "DATABASE_URL", "preview").length === 0) {
|
|
84
|
+
add("error", "Preview has no DATABASE_URL, so every preview build fails. Run `stack neon reset-preview " +
|
|
85
|
+
"--set-vercel` to point Preview at the shared `preview` branch.");
|
|
86
|
+
}
|
|
87
|
+
else {
|
|
88
|
+
add("info", "Whether Preview's DATABASE_URL is production's database can only be told from its value, " +
|
|
89
|
+
"which doctor never reads; `stack vercel-build` refuses that at build time.");
|
|
90
|
+
}
|
|
91
|
+
if (h.truncated) {
|
|
92
|
+
add("info", "The project has more variables than one API page; only the first was checked.");
|
|
93
|
+
}
|
|
94
|
+
return findings.sort((a, b) => RANK[a.severity] - RANK[b.severity]);
|
|
95
|
+
}
|
|
96
|
+
/** Runs `vercel api <path>`; a failure names the endpoint and exit code, never the response. */
|
|
97
|
+
async function vercelApi(cli, path) {
|
|
98
|
+
const { stdout, code } = await cli.exec("vercel", ["api", path, "--raw"]);
|
|
99
|
+
if (code !== 0) {
|
|
100
|
+
throw new CliError(`vercel api ${path.split("?")[0]} failed (exit ${code}). Is the Vercel CLI signed in (\`vercel login\`)?`);
|
|
101
|
+
}
|
|
102
|
+
try {
|
|
103
|
+
return JSON.parse(stdout);
|
|
104
|
+
}
|
|
105
|
+
catch {
|
|
106
|
+
throw new CliError(`vercel api ${path.split("?")[0]} did not answer with JSON.`);
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
/** A JSON file's object, or undefined when there is no such file. */
|
|
110
|
+
function readJsonFile(path) {
|
|
111
|
+
let text;
|
|
112
|
+
try {
|
|
113
|
+
text = readFileSync(path, "utf8");
|
|
114
|
+
}
|
|
115
|
+
catch (error) {
|
|
116
|
+
if (error.code === "ENOENT")
|
|
117
|
+
return undefined;
|
|
118
|
+
throw error;
|
|
119
|
+
}
|
|
120
|
+
try {
|
|
121
|
+
return JSON.parse(text);
|
|
122
|
+
}
|
|
123
|
+
catch {
|
|
124
|
+
throw new CliError(`${path} is not valid JSON.`);
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
/**
|
|
128
|
+
* The linked project (`.vercel/project.json`, written by `vercel link`), its preset and its variables' metadata from the Vercel API, and the app's `vercel.json`.
|
|
129
|
+
*/
|
|
130
|
+
export async function readHosting(cli) {
|
|
131
|
+
const link = readJsonFile(join(cli.cwd, ".vercel", "project.json"));
|
|
132
|
+
if (!link) {
|
|
133
|
+
throw new CliError("this directory is not linked to a Vercel project: run `vercel link`.");
|
|
134
|
+
}
|
|
135
|
+
const projectId = str(link.projectId);
|
|
136
|
+
if (!projectId)
|
|
137
|
+
throw new CliError(".vercel/project.json has no projectId: run `vercel link`.");
|
|
138
|
+
const orgId = str(link.orgId);
|
|
139
|
+
const query = orgId?.startsWith("team_") ? `?teamId=${encodeURIComponent(orgId)}` : "";
|
|
140
|
+
const id = encodeURIComponent(projectId);
|
|
141
|
+
const project = await vercelApi(cli, `/v9/projects/${id}${query}`);
|
|
142
|
+
const listed = await vercelApi(cli, `/v10/projects/${id}/env${query}`);
|
|
143
|
+
const rawEnvs = Array.isArray(listed.envs) ? listed.envs : [];
|
|
144
|
+
const next = listed.pagination?.next;
|
|
145
|
+
const vercelJson = readJsonFile(join(cli.cwd, "vercel.json")) ?? {};
|
|
146
|
+
return {
|
|
147
|
+
project: str(project.name) ?? projectId,
|
|
148
|
+
framework: str(project.framework) ?? null,
|
|
149
|
+
vercelJsonFramework: "framework" in vercelJson ? (vercelJson.framework ?? null) : undefined,
|
|
150
|
+
envs: rawEnvs.map(envVarMeta),
|
|
151
|
+
truncated: next !== undefined && next !== null,
|
|
152
|
+
};
|
|
153
|
+
}
|
|
154
|
+
export async function doctor(cli) {
|
|
155
|
+
const hosting = await readHosting(cli);
|
|
156
|
+
const findings = audit(hosting);
|
|
157
|
+
cli.log(`[doctor] ${hosting.project}: ${hosting.envs.length} environment variables checked`);
|
|
158
|
+
for (const { severity, message } of findings)
|
|
159
|
+
cli.log(`${severity.padEnd(7)} ${message}`);
|
|
160
|
+
const count = (s) => findings.filter((f) => f.severity === s).length;
|
|
161
|
+
const errors = count("error");
|
|
162
|
+
const warnings = count("warning");
|
|
163
|
+
cli.log(`[doctor] ${errors} error${errors === 1 ? "" : "s"}, ${warnings} warning${warnings === 1 ? "" : "s"}` +
|
|
164
|
+
(errors > 0 ? ": fix the errors before the next deploy." : "."));
|
|
165
|
+
return errors > 0 ? 1 : 0;
|
|
166
|
+
}
|
package/dist/cli/index.d.ts
CHANGED
|
@@ -1,4 +1,11 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import { type CliDeps } from "./context.ts";
|
|
2
|
+
import { type CliDeps, type ExecOptions } from "./context.ts";
|
|
3
3
|
/** The testable entry: every outside effect arrives through `deps`; the exit code comes back. */
|
|
4
4
|
export declare function runCli(argv: string[], deps: CliDeps): Promise<number>;
|
|
5
|
+
/**
|
|
6
|
+
* Runs a program with an argument array (never a shell), forwarding signals to an inherited child. `input` is written to the child's stdin whole, then closed.
|
|
7
|
+
*/
|
|
8
|
+
export declare function exec(command: string, args: string[], options?: ExecOptions): Promise<{
|
|
9
|
+
stdout: string;
|
|
10
|
+
code: number;
|
|
11
|
+
}>;
|
package/dist/cli/index.js
CHANGED
|
@@ -3,18 +3,26 @@ import { spawn } from "node:child_process";
|
|
|
3
3
|
import { realpathSync } from "node:fs";
|
|
4
4
|
import { fileURLToPath } from "node:url";
|
|
5
5
|
import { CliError, resolveDeps } from "./context.js";
|
|
6
|
+
import { dev } from "./dev.js";
|
|
7
|
+
import { doctor } from "./doctor.js";
|
|
6
8
|
import { devSetup, neonSeed, resetPreview, withNeon } from "./neon.js";
|
|
9
|
+
import { runScript } from "./run.js";
|
|
7
10
|
import { syncBlocksCommand } from "./sync-blocks.js";
|
|
8
|
-
import { userCreate } from "./user-create.js";
|
|
11
|
+
import { userCreate, userRole } from "./user-create.js";
|
|
9
12
|
import { vercelBuild } from "./vercel-build.js";
|
|
10
13
|
const USAGE = `usage: stack <command>
|
|
11
|
-
with-neon <command> [args]
|
|
12
|
-
dev
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
14
|
+
with-neon <command> [args] run a command against your Neon dev branch
|
|
15
|
+
dev [--pglite] [next dev args] next dev on your dev branch; --pglite: on PGlite in .local-db/, no Neon
|
|
16
|
+
dev-setup create your dev branch from seed and migrate it
|
|
17
|
+
run <script> [args] run an app script with Node, with the app's database and .env
|
|
18
|
+
neon seed (re)create the seed branch and load the app's seed data
|
|
19
|
+
neon reset-preview [--set-vercel] (re)create the shared preview branch from seed;
|
|
20
|
+
--set-vercel writes its URLs into Vercel's Preview variables
|
|
21
|
+
vercel-build Vercel's build command: migrate, then next build
|
|
22
|
+
doctor audit the linked Vercel project's setup (read-only)
|
|
23
|
+
user:create <email> [--admin] add a user through the app's auth
|
|
24
|
+
user:role <email> <admin|user> change a user's role through the app's auth
|
|
25
|
+
sync-blocks [--check] refresh the stack-owned blocks in AGENTS.md, CLAUDE.md, .gitignore, .env.example`;
|
|
18
26
|
/** The testable entry: every outside effect arrives through `deps`; the exit code comes back. */
|
|
19
27
|
export async function runCli(argv, deps) {
|
|
20
28
|
const cli = resolveDeps(deps);
|
|
@@ -23,18 +31,26 @@ export async function runCli(argv, deps) {
|
|
|
23
31
|
switch (command) {
|
|
24
32
|
case "with-neon":
|
|
25
33
|
return await withNeon(cli, args);
|
|
34
|
+
case "dev":
|
|
35
|
+
return await dev(cli, args);
|
|
26
36
|
case "dev-setup":
|
|
27
37
|
return await devSetup(cli);
|
|
38
|
+
case "run":
|
|
39
|
+
return await runScript(cli, args);
|
|
28
40
|
case "neon":
|
|
29
41
|
if (args[0] === "seed")
|
|
30
42
|
return await neonSeed(cli);
|
|
31
43
|
if (args[0] === "reset-preview")
|
|
32
|
-
return await resetPreview(cli);
|
|
44
|
+
return await resetPreview(cli, args.slice(1));
|
|
33
45
|
break;
|
|
34
46
|
case "vercel-build":
|
|
35
47
|
return await vercelBuild(cli);
|
|
48
|
+
case "doctor":
|
|
49
|
+
return await doctor(cli);
|
|
36
50
|
case "user:create":
|
|
37
51
|
return await userCreate(cli, args);
|
|
52
|
+
case "user:role":
|
|
53
|
+
return await userRole(cli, args);
|
|
38
54
|
case "sync-blocks":
|
|
39
55
|
return await syncBlocksCommand(cli, args);
|
|
40
56
|
}
|
|
@@ -50,13 +66,21 @@ export async function runCli(argv, deps) {
|
|
|
50
66
|
cli.error(USAGE);
|
|
51
67
|
return 2;
|
|
52
68
|
}
|
|
53
|
-
/**
|
|
54
|
-
|
|
69
|
+
/**
|
|
70
|
+
* Runs a program with an argument array (never a shell), forwarding signals to an inherited child. `input` is written to the child's stdin whole, then closed.
|
|
71
|
+
*/
|
|
72
|
+
export function exec(command, args, options = {}) {
|
|
55
73
|
return new Promise((resolve, reject) => {
|
|
74
|
+
const stdin = options.input === undefined ? "ignore" : "pipe";
|
|
56
75
|
const child = spawn(command, args, {
|
|
57
76
|
env: options.env,
|
|
58
|
-
stdio: options.inherit ? "inherit" : [
|
|
77
|
+
stdio: options.inherit ? "inherit" : [stdin, "pipe", "inherit"],
|
|
59
78
|
});
|
|
79
|
+
if (options.input !== undefined && child.stdin) {
|
|
80
|
+
// A child that exits without reading reports EPIPE here; its exit code says what happened.
|
|
81
|
+
child.stdin.on("error", () => { });
|
|
82
|
+
child.stdin.end(options.input);
|
|
83
|
+
}
|
|
60
84
|
let stdout = "";
|
|
61
85
|
child.stdout?.on("data", (chunk) => {
|
|
62
86
|
stdout += chunk;
|
package/dist/cli/neon.d.ts
CHANGED
|
@@ -89,9 +89,20 @@ export declare function emptyDatabase(sql: (statement: string) => Promise<Record
|
|
|
89
89
|
*/
|
|
90
90
|
export declare function neonSeed(cli: Cli): Promise<number>;
|
|
91
91
|
/**
|
|
92
|
-
*
|
|
93
|
-
* its pooled URL. A build cannot change the DATABASE_URL a preview deployment uses at runtime, so
|
|
94
|
-
* previews share this branch: set the URL printed here once as a Preview-scoped Vercel variable.
|
|
95
|
-
* `stack vercel-build` migrates it on each preview build; run this again to start it clean.
|
|
92
|
+
* Runs the app's `db/seed.ts` (`export default async function seed(db)`) on the app's own `db` (`src/lib/db.ts`), wherever `cli.env` points it, then closes that client's pool: on PGlite it holds the one connection the server allows.
|
|
96
93
|
*/
|
|
97
|
-
export declare function
|
|
94
|
+
export declare function runAppSeed(cli: Cli): Promise<void>;
|
|
95
|
+
/** The Preview variables `--set-vercel` writes, and which of the branch's URLs each holds. */
|
|
96
|
+
export declare const PREVIEW_VARIABLES: readonly [{
|
|
97
|
+
readonly name: "DATABASE_URL";
|
|
98
|
+
readonly pooled: true;
|
|
99
|
+
}, {
|
|
100
|
+
readonly name: "DATABASE_URL_UNPOOLED";
|
|
101
|
+
readonly pooled: false;
|
|
102
|
+
}];
|
|
103
|
+
/**
|
|
104
|
+
* `stack neon reset-preview [--set-vercel]` — (re)creates the one shared `preview` branch from `seed`. A build cannot change the DATABASE_URL a preview deployment uses at runtime, so previews share this branch, and `stack vercel-build` migrates it on each preview build; run this again to start it clean.
|
|
105
|
+
*
|
|
106
|
+
* Without `--set-vercel` it prints the pooled URL, to set by hand as Preview's DATABASE_URL. With it, it writes the pooled URL as DATABASE_URL and the direct one as DATABASE_URL_UNPOOLED into the linked Vercel project, Preview only, as sensitive variables replacing any there, and prints neither. Each value is read from the Neon CLI in full before `vercel env add` starts, then handed over on its stdin: never in its arguments, where `ps` would show it, and never piped from a command still running, which `vercel env add` would read as empty.
|
|
107
|
+
*/
|
|
108
|
+
export declare function resetPreview(cli: Cli, args?: string[]): Promise<number>;
|
package/dist/cli/neon.js
CHANGED
|
@@ -11,6 +11,7 @@
|
|
|
11
11
|
// branch, whatever it is named (Neon calls a new project's `main`): `defaultBranch`.
|
|
12
12
|
import { endpointOf } from "../db/index.js";
|
|
13
13
|
import { CliError, importApp, loadAppEnv } from "./context.js";
|
|
14
|
+
import { readHosting } from "./doctor.js";
|
|
14
15
|
export const SEED = "seed";
|
|
15
16
|
export const PREVIEW = "preview";
|
|
16
17
|
/** Where the new seed is built; it takes the name `seed` only once it is clean. */
|
|
@@ -275,12 +276,7 @@ export async function neonSeed(cli) {
|
|
|
275
276
|
await deleteOrWarn(cli, next);
|
|
276
277
|
return status;
|
|
277
278
|
}
|
|
278
|
-
|
|
279
|
-
const seedFn = (await importApp(cli, "db/seed.ts")).default;
|
|
280
|
-
if (!db || typeof seedFn !== "function") {
|
|
281
|
-
throw new CliError("src/lib/db.ts must export `db` and db/seed.ts a default `seed(db)` function.");
|
|
282
|
-
}
|
|
283
|
-
await seedFn(db);
|
|
279
|
+
await runAppSeed(cli);
|
|
284
280
|
}
|
|
285
281
|
catch (error) {
|
|
286
282
|
await deleteOrWarn(cli, next);
|
|
@@ -304,6 +300,24 @@ export async function neonSeed(cli) {
|
|
|
304
300
|
cli.log(`[seed] ${SEED} is ready`);
|
|
305
301
|
return 0;
|
|
306
302
|
}
|
|
303
|
+
/**
|
|
304
|
+
* Runs the app's `db/seed.ts` (`export default async function seed(db)`) on the app's own `db` (`src/lib/db.ts`), wherever `cli.env` points it, then closes that client's pool: on PGlite it holds the one connection the server allows.
|
|
305
|
+
*/
|
|
306
|
+
export async function runAppSeed(cli) {
|
|
307
|
+
const { db } = await importApp(cli, "src/lib/db.ts");
|
|
308
|
+
const seedFn = (await importApp(cli, "db/seed.ts")).default;
|
|
309
|
+
if (!db || typeof seedFn !== "function") {
|
|
310
|
+
throw new CliError("src/lib/db.ts must export `db` and db/seed.ts a default `seed(db)` function.");
|
|
311
|
+
}
|
|
312
|
+
try {
|
|
313
|
+
await seedFn(db);
|
|
314
|
+
}
|
|
315
|
+
finally {
|
|
316
|
+
const client = db.$client;
|
|
317
|
+
if (typeof client?.end === "function")
|
|
318
|
+
await client.end();
|
|
319
|
+
}
|
|
320
|
+
}
|
|
307
321
|
/**
|
|
308
322
|
* Deletes a half-built `seed-next`; the failure being reported comes first, so this only warns. But
|
|
309
323
|
* loudly: until it is emptied, a full-copy `seed-next` holds production's data.
|
|
@@ -316,19 +330,73 @@ async function deleteOrWarn(cli, branch) {
|
|
|
316
330
|
}
|
|
317
331
|
}
|
|
318
332
|
/**
|
|
319
|
-
*
|
|
320
|
-
* its pooled URL. A build cannot change the DATABASE_URL a preview deployment uses at runtime, so
|
|
321
|
-
* previews share this branch: set the URL printed here once as a Preview-scoped Vercel variable.
|
|
322
|
-
* `stack vercel-build` migrates it on each preview build; run this again to start it clean.
|
|
333
|
+
* Refuses `--set-vercel` when a variable it would replace is one Vercel variable for Preview and another environment. Reads metadata only (`stack doctor`'s reader), never a value.
|
|
323
334
|
*/
|
|
324
|
-
|
|
335
|
+
async function refuseSharedPreviewVariables(cli) {
|
|
336
|
+
const { envs } = await readHosting(cli);
|
|
337
|
+
for (const { name } of PREVIEW_VARIABLES) {
|
|
338
|
+
for (const v of envs) {
|
|
339
|
+
if (v.key !== name || !v.target.includes("preview"))
|
|
340
|
+
continue;
|
|
341
|
+
const others = v.target.filter((t) => t !== "preview");
|
|
342
|
+
if (others.length > 0) {
|
|
343
|
+
throw new CliError(`${name} is one Vercel variable for Preview and ${others.join(", ")}; --set-vercel would change it there too. In Vercel, take Preview off it (Settings, Environment Variables), then run this again. Nothing was changed.`);
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
}
|
|
347
|
+
}
|
|
348
|
+
/** The Preview variables `--set-vercel` writes, and which of the branch's URLs each holds. */
|
|
349
|
+
export const PREVIEW_VARIABLES = [
|
|
350
|
+
{ name: "DATABASE_URL", pooled: true },
|
|
351
|
+
{ name: "DATABASE_URL_UNPOOLED", pooled: false },
|
|
352
|
+
];
|
|
353
|
+
/**
|
|
354
|
+
* `stack neon reset-preview [--set-vercel]` — (re)creates the one shared `preview` branch from `seed`. A build cannot change the DATABASE_URL a preview deployment uses at runtime, so previews share this branch, and `stack vercel-build` migrates it on each preview build; run this again to start it clean.
|
|
355
|
+
*
|
|
356
|
+
* Without `--set-vercel` it prints the pooled URL, to set by hand as Preview's DATABASE_URL. With it, it writes the pooled URL as DATABASE_URL and the direct one as DATABASE_URL_UNPOOLED into the linked Vercel project, Preview only, as sensitive variables replacing any there, and prints neither. Each value is read from the Neon CLI in full before `vercel env add` starts, then handed over on its stdin: never in its arguments, where `ps` would show it, and never piped from a command still running, which `vercel env add` would read as empty.
|
|
357
|
+
*/
|
|
358
|
+
export async function resetPreview(cli, args = []) {
|
|
359
|
+
const setVercel = args.includes("--set-vercel");
|
|
360
|
+
// Before anything changes: `vercel env add --environment preview --force` on a variable that Production (or Development) shares with Preview could rewrite it for them too, pointing production at the preview branch. Only a Preview-only variable may be replaced.
|
|
361
|
+
if (setVercel)
|
|
362
|
+
await refuseSharedPreviewVariables(cli);
|
|
325
363
|
if (!(await findBranch(cli, SEED))) {
|
|
326
364
|
throw new CliError(`no \`${SEED}\` branch to cut ${PREVIEW} from; run \`stack neon seed\` first.`);
|
|
327
365
|
}
|
|
328
366
|
const preview = await recreate(cli, PREVIEW, SEED);
|
|
329
367
|
if (!preview)
|
|
330
368
|
throw new CliError(`could not create ${PREVIEW} from ${SEED}.`);
|
|
331
|
-
|
|
332
|
-
|
|
369
|
+
if (!setVercel) {
|
|
370
|
+
cli.error(`[preview] created ${PREVIEW} from ${SEED}; set this as Preview DATABASE_URL on Vercel:`);
|
|
371
|
+
cli.log(await neonOk(cli, ["connection-string", preview.id, "--pooled"]));
|
|
372
|
+
return 0;
|
|
373
|
+
}
|
|
374
|
+
cli.error(`[preview] created ${PREVIEW} from ${SEED}`);
|
|
375
|
+
const production = defaultBranch(await listBranches(cli));
|
|
376
|
+
const productionUrl = await neonOk(cli, ["connection-string", production.id]);
|
|
377
|
+
const values = [];
|
|
378
|
+
for (const { name, pooled } of PREVIEW_VARIABLES) {
|
|
379
|
+
const value = await neonOk(cli, [
|
|
380
|
+
"connection-string",
|
|
381
|
+
preview.id,
|
|
382
|
+
...(pooled ? ["--pooled"] : []),
|
|
383
|
+
]);
|
|
384
|
+
if (!value)
|
|
385
|
+
throw new CliError(`neon connection-string returned nothing for ${PREVIEW}.`);
|
|
386
|
+
// The same backstop `vercel-build` applies: Preview must never be handed production.
|
|
387
|
+
if (endpointOf(value) === endpointOf(productionUrl)) {
|
|
388
|
+
throw new CliError(`${PREVIEW}'s ${pooled ? "pooled" : "direct"} URL resolves to production's endpoint; refusing to set it on Vercel.`);
|
|
389
|
+
}
|
|
390
|
+
values.push({ name, value });
|
|
391
|
+
}
|
|
392
|
+
for (const { name, value } of values) {
|
|
393
|
+
const { code } = await cli.exec("vercel", ["env", "add", name, "--environment", "preview", "--sensitive", "--force", "--yes"], { input: value });
|
|
394
|
+
if (code !== 0) {
|
|
395
|
+
throw new CliError(`vercel env add ${name} failed (exit ${code}). Is the Vercel CLI signed in (\`vercel login\`) ` +
|
|
396
|
+
"and this directory linked (`vercel link`)? Re-run with --set-vercel once it is.");
|
|
397
|
+
}
|
|
398
|
+
cli.error(`[preview] set ${name} on Vercel (Preview, sensitive)`);
|
|
399
|
+
}
|
|
400
|
+
cli.log(`[preview] Vercel's Preview DATABASE_URL and DATABASE_URL_UNPOOLED now point at ${PREVIEW}; redeploy a preview to use them.`);
|
|
333
401
|
return 0;
|
|
334
402
|
}
|
package/dist/cli/run.js
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
// `stack run <script> [args...]` — runs one of the app's own scripts (`scripts/backfill.ts`, say) with this Node, type stripping and all, and the environment every other command gives the app: your Neon dev branch unless DATABASE_URL or ENV_FILE says otherwise, then the app's `.env` (or the file ENV_FILE names) for whatever is still unset. ENV_FILE is also the deliberate production opt-in, exactly as for `user:create`. The arguments and the exit code pass through.
|
|
2
|
+
import { resolve } from "node:path";
|
|
3
|
+
import { assertDevDatabase } from "../db/index.js";
|
|
4
|
+
import { loadAppEnv } from "./context.js";
|
|
5
|
+
import { devBranchEnv } from "./neon.js";
|
|
6
|
+
export async function runScript(cli, [script, ...args]) {
|
|
7
|
+
if (!script) {
|
|
8
|
+
cli.error("usage: stack run <script> [args...]");
|
|
9
|
+
return 2;
|
|
10
|
+
}
|
|
11
|
+
Object.assign(cli.env, await devBranchEnv(cli));
|
|
12
|
+
loadAppEnv(cli);
|
|
13
|
+
// The same refusal the app's own db.ts makes, applied before the script starts: production only with ENV_FILE.
|
|
14
|
+
for (const url of [cli.env.DATABASE_URL, cli.env.DATABASE_URL_UNPOOLED]) {
|
|
15
|
+
if (!url?.trim())
|
|
16
|
+
continue;
|
|
17
|
+
assertDevDatabase(url, {
|
|
18
|
+
nodeEnv: cli.env.NODE_ENV,
|
|
19
|
+
allowRemote: cli.env.ALLOW_REMOTE_DATABASE,
|
|
20
|
+
envFile: cli.env.ENV_FILE,
|
|
21
|
+
productionHost: cli.env.PRODUCTION_DATABASE_HOST,
|
|
22
|
+
});
|
|
23
|
+
}
|
|
24
|
+
const { code } = await cli.exec(cli.execPath, [resolve(cli.cwd, script), ...args], {
|
|
25
|
+
env: cli.env,
|
|
26
|
+
inherit: true,
|
|
27
|
+
});
|
|
28
|
+
return code;
|
|
29
|
+
}
|
|
@@ -1,2 +1,6 @@
|
|
|
1
1
|
import { type Cli } from "./context.ts";
|
|
2
2
|
export declare function userCreate(cli: Cli, args: string[]): Promise<number>;
|
|
3
|
+
/**
|
|
4
|
+
* `stack user:role <email> <admin|user>`. The email is matched as it is stored (trimmed, lower-cased). The rule that the app always keeps an admin is `setRole`'s, enforced in its own transaction: its refusal is reported as is, and nothing changes.
|
|
5
|
+
*/
|
|
6
|
+
export declare function userRole(cli: Cli, args: string[]): Promise<number>;
|
package/dist/cli/user-create.js
CHANGED
|
@@ -1,12 +1,16 @@
|
|
|
1
|
-
// `stack user:create <email> [--admin]` — adds a real user to sign in as, through the app's own
|
|
2
|
-
// auth (`src/lib/auth.ts`, imported from the working directory with Node's type stripping, so it
|
|
3
|
-
// must use relative `.ts` imports). Sign-in never creates users; this is how the first admin
|
|
4
|
-
// exists. A duplicate email is an error, not a silent no-op.
|
|
5
|
-
//
|
|
6
|
-
// Where: like `stack with-neon`, your Neon dev branch unless DATABASE_URL or ENV_FILE says
|
|
7
|
-
// otherwise. Production is a deliberate `ENV_FILE=<production env file>` (docs/runbook.md).
|
|
8
1
|
import { CliError, importApp, loadAppEnv } from "./context.js";
|
|
9
2
|
import { devBranchEnv } from "./neon.js";
|
|
3
|
+
/**
|
|
4
|
+
* The app's `auth.users`, with the database every command here uses: the dev branch's connection (when nothing else names a database) wins over `.env`, which fills in only what is still unset. The app's modules read process.env, so this sets it before importing them.
|
|
5
|
+
*/
|
|
6
|
+
async function appUsers(cli) {
|
|
7
|
+
Object.assign(cli.env, await devBranchEnv(cli));
|
|
8
|
+
loadAppEnv(cli);
|
|
9
|
+
const auth = (await importApp(cli, "src/lib/auth.ts")).auth;
|
|
10
|
+
if (!auth?.users)
|
|
11
|
+
throw new CliError("src/lib/auth.ts must export `auth` (a StackAuth).");
|
|
12
|
+
return auth.users;
|
|
13
|
+
}
|
|
10
14
|
export async function userCreate(cli, args) {
|
|
11
15
|
const admin = args.includes("--admin");
|
|
12
16
|
const [email] = args.filter((arg) => arg !== "--admin");
|
|
@@ -14,15 +18,11 @@ export async function userCreate(cli, args) {
|
|
|
14
18
|
cli.error("usage: stack user:create <email> [--admin]");
|
|
15
19
|
return 2;
|
|
16
20
|
}
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
Object.assign(cli.env, await devBranchEnv(cli));
|
|
20
|
-
loadAppEnv(cli);
|
|
21
|
-
const auth = (await importApp(cli, "src/lib/auth.ts")).auth;
|
|
22
|
-
if (!auth?.users)
|
|
21
|
+
const users = await appUsers(cli);
|
|
22
|
+
if (!users.add)
|
|
23
23
|
throw new CliError("src/lib/auth.ts must export `auth` (a StackAuth).");
|
|
24
24
|
try {
|
|
25
|
-
const user = await
|
|
25
|
+
const user = await users.add(email, admin ? "admin" : "user");
|
|
26
26
|
cli.log(`created ${user.email}${admin ? " as an admin" : ""}. They sign in with a magic link or Google.`);
|
|
27
27
|
return 0;
|
|
28
28
|
}
|
|
@@ -33,3 +33,40 @@ export async function userCreate(cli, args) {
|
|
|
33
33
|
throw error;
|
|
34
34
|
}
|
|
35
35
|
}
|
|
36
|
+
const ROLES = ["admin", "user"];
|
|
37
|
+
const isRole = (value) => ROLES.includes(value);
|
|
38
|
+
/**
|
|
39
|
+
* `stack user:role <email> <admin|user>`. The email is matched as it is stored (trimmed, lower-cased). The rule that the app always keeps an admin is `setRole`'s, enforced in its own transaction: its refusal is reported as is, and nothing changes.
|
|
40
|
+
*/
|
|
41
|
+
export async function userRole(cli, args) {
|
|
42
|
+
const [email, role, ...rest] = args;
|
|
43
|
+
if (!email || !isRole(role) || rest.length > 0) {
|
|
44
|
+
cli.error("usage: stack user:role <email> <admin|user>");
|
|
45
|
+
return 2;
|
|
46
|
+
}
|
|
47
|
+
const users = await appUsers(cli);
|
|
48
|
+
if (!users.list || !users.setRole) {
|
|
49
|
+
throw new CliError("src/lib/auth.ts must export `auth` (a StackAuth).");
|
|
50
|
+
}
|
|
51
|
+
const wanted = email.trim().toLowerCase();
|
|
52
|
+
const user = (await users.list()).find((u) => u.email === wanted);
|
|
53
|
+
if (!user) {
|
|
54
|
+
throw new CliError(`no user with the email ${wanted}; add them with \`stack user:create\`. Nothing changed.`);
|
|
55
|
+
}
|
|
56
|
+
const as = role === "admin" ? "an admin" : "a user";
|
|
57
|
+
if (user.role === role) {
|
|
58
|
+
cli.log(`${user.email} is already ${as}. Nothing changed.`);
|
|
59
|
+
return 0;
|
|
60
|
+
}
|
|
61
|
+
try {
|
|
62
|
+
await users.setRole(user.id, role);
|
|
63
|
+
}
|
|
64
|
+
catch (error) {
|
|
65
|
+
if (error instanceof Error && error.name === "LastAdminError") {
|
|
66
|
+
throw new CliError(`${error.message}: ${user.email} is the only admin. Make someone else an admin first. Nothing changed.`);
|
|
67
|
+
}
|
|
68
|
+
throw error;
|
|
69
|
+
}
|
|
70
|
+
cli.log(`${user.email} is now ${as}.`);
|
|
71
|
+
return 0;
|
|
72
|
+
}
|
package/dist/configs/vitest.js
CHANGED
|
@@ -1,8 +1,6 @@
|
|
|
1
1
|
import { resolve as resolvePath } from "node:path";
|
|
2
2
|
const toArray = (value) => value === undefined ? [] : Array.isArray(value) ? value : [value];
|
|
3
|
-
// Vitest settings shared by every app,
|
|
4
|
-
// `overrides` is merged, not substituted: an app's `setupFiles`, `include`, `exclude` and `env`
|
|
5
|
-
// are added to the preset's, and any other key the app sets wins.
|
|
3
|
+
// Vitest settings shared by every app. `overrides` is merged, not substituted: an app's `setupFiles`, `include`, `exclude` and `env` are added to the preset's, and any other key the app sets wins.
|
|
6
4
|
export function stackVitestConfig(overrides = {}, options = {}) {
|
|
7
5
|
const { test: appTest = {}, resolve: appResolve, ...appRest } = overrides;
|
|
8
6
|
const { root = process.cwd() } = options;
|
|
@@ -1,9 +1,6 @@
|
|
|
1
1
|
import { createCipheriv, createDecipheriv, randomBytes } from "node:crypto";
|
|
2
2
|
/**
|
|
3
|
-
* Connected-account tokens are encrypted at rest with AES-256-GCM under `TOKEN_ENCRYPTION_KEY`
|
|
4
|
-
* (32 bytes, base64: `openssl rand -base64 32`), so a database leak alone exposes nobody's account.
|
|
5
|
-
* The format is ifttt's — `v1:<iv>:<tag>:<ciphertext>`, base64url parts — so tokens it stored move
|
|
6
|
-
* across unchanged. Changing the key makes every stored token unreadable: everyone reconnects.
|
|
3
|
+
* Connected-account tokens are encrypted at rest with AES-256-GCM under `TOKEN_ENCRYPTION_KEY` (32 bytes, base64: `openssl rand -base64 32`), so a database leak alone exposes nobody's account. The format is fixed — `v1:<iv>:<tag>:<ciphertext>`, base64url parts — so a token stored by any version decrypts in every later one. Changing the key makes every stored token unreadable: everyone reconnects.
|
|
7
4
|
*/
|
|
8
5
|
const VERSION = "v1";
|
|
9
6
|
export class TokenKeyError extends Error {
|
|
@@ -2,9 +2,7 @@ import type { NodePgDatabase } from "drizzle-orm/node-postgres";
|
|
|
2
2
|
import type { ConnectionProvider } from "./providers.ts";
|
|
3
3
|
import type { ConnectionTable } from "./table.ts";
|
|
4
4
|
/**
|
|
5
|
-
* Connected accounts: a signed-in person connects an account at another service
|
|
6
|
-
* Foursquare) so the app can work on their behalf. This is deliberately not sign-in — a connection
|
|
7
|
-
* never signs anyone in and never creates a user (see the design's "Everyone signs in by email").
|
|
5
|
+
* Connected accounts: a signed-in person connects an account at another service so the app can work on their behalf. This is deliberately not sign-in — a connection never signs anyone in and never creates a user; people sign in by email.
|
|
8
6
|
*
|
|
9
7
|
* The flow, as two route handlers the app mounts:
|
|
10
8
|
* - `start(userId, provider, next)` (GET `/api/connections/<provider>/start`): sets a one-off
|
|
@@ -3,9 +3,7 @@ import { and, asc, eq } from "drizzle-orm";
|
|
|
3
3
|
import { safeNext } from "../auth/safe-next.js";
|
|
4
4
|
import { decryptToken, encryptToken, parseEncryptionKey } from "./crypto.js";
|
|
5
5
|
/**
|
|
6
|
-
* Connected accounts: a signed-in person connects an account at another service
|
|
7
|
-
* Foursquare) so the app can work on their behalf. This is deliberately not sign-in — a connection
|
|
8
|
-
* never signs anyone in and never creates a user (see the design's "Everyone signs in by email").
|
|
6
|
+
* Connected accounts: a signed-in person connects an account at another service so the app can work on their behalf. This is deliberately not sign-in — a connection never signs anyone in and never creates a user; people sign in by email.
|
|
9
7
|
*
|
|
10
8
|
* The flow, as two route handlers the app mounts:
|
|
11
9
|
* - `start(userId, provider, next)` (GET `/api/connections/<provider>/start`): sets a one-off
|
|
@@ -1,8 +1,6 @@
|
|
|
1
1
|
import type { AuthTables } from "../auth/better-auth/tables.ts";
|
|
2
2
|
/**
|
|
3
|
-
* The `connection` table: an account at another service that a signed-in person connected so the
|
|
4
|
-
* app can work on their behalf (ifttt's Foursquare). The app re-exports it from its schema next to
|
|
5
|
-
* the auth tables, so drizzle-kit generates it into the app's own migrations.
|
|
3
|
+
* The `connection` table: an account at another service that a signed-in person connected so the app can work on their behalf. The app re-exports it from its schema next to the auth tables, so drizzle-kit generates it into the app's own migrations.
|
|
6
4
|
*
|
|
7
5
|
* - One connection per person per provider (reconnecting replaces the token).
|
|
8
6
|
* - One person per provider account (`subject`): an account already connected to someone else is
|
|
@@ -1,8 +1,6 @@
|
|
|
1
1
|
import { pgTable, text, timestamp, unique, uuid } from "drizzle-orm/pg-core";
|
|
2
2
|
/**
|
|
3
|
-
* The `connection` table: an account at another service that a signed-in person connected so the
|
|
4
|
-
* app can work on their behalf (ifttt's Foursquare). The app re-exports it from its schema next to
|
|
5
|
-
* the auth tables, so drizzle-kit generates it into the app's own migrations.
|
|
3
|
+
* The `connection` table: an account at another service that a signed-in person connected so the app can work on their behalf. The app re-exports it from its schema next to the auth tables, so drizzle-kit generates it into the app's own migrations.
|
|
6
4
|
*
|
|
7
5
|
* - One connection per person per provider (reconnecting replaces the token).
|
|
8
6
|
* - One person per provider account (`subject`): an account already connected to someone else is
|
|
@@ -13,9 +13,12 @@ export type PgliteServer = {
|
|
|
13
13
|
port: number;
|
|
14
14
|
stop(): Promise<void>;
|
|
15
15
|
};
|
|
16
|
-
/**
|
|
16
|
+
/**
|
|
17
|
+
* In-memory when `dataDir` is absent. `port` 0 (or absent) picks a free one. `resolveFrom` loads PGlite from that directory's dependencies (an app's root) rather than this package's.
|
|
18
|
+
*/
|
|
17
19
|
export declare function startPgliteServer(options?: {
|
|
18
20
|
dataDir?: string;
|
|
19
21
|
host?: string;
|
|
20
22
|
port?: number;
|
|
23
|
+
resolveFrom?: string;
|
|
21
24
|
}): Promise<PgliteServer>;
|