@wwchen/stack 0.6.4 → 0.7.1

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.
@@ -1,106 +1,2 @@
1
- import { headers as requestHeaders } from "next/headers.js";
2
- import { rateLimit } from "../http/rate-limit.js";
3
- import { safeNext } from "./safe-next.js";
4
- const SIGN_IN_PATH = "/sign-in";
5
- /**
6
- * `redirect` and `notFound`, imported on call by their bare name. Next's bundler gives server code its own versions only for the bare `next/navigation`; `next/navigation.js` is the client module, which cannot load in a route handler. Plain Node (the `stack` CLI importing the app's auth) cannot resolve the bare name, and never calls this.
7
- */
8
- const navigation = () => import("next/navigation");
9
- /**
10
- * The bucket the sign-in functions spend, under the path of the route that does the same thing, so a raw POST to that route and the server action share one budget: neither is a way around the other.
11
- */
12
- const SIGN_IN_BUDGET_PATH = "/api/auth/sign-in/magic-link";
13
- /**
14
- * Better Auth's password routes. Passwords are off unless an app opts in with `betterAuthProvider({ emailAndPassword })`; it then calls `provider.instance.api.signInEmail / changePassword / verifyPassword` in-process from its own server action, with a budget of its own. Served here too, each would be a second door with its own budget, multiplying the guesses an attacker gets. Answered 404 whether or not the option is on (off, Better Auth refuses them anyway).
15
- */
16
- const NOT_SERVED = new Set([
17
- "/api/auth/sign-in/email",
18
- "/api/auth/change-password",
19
- "/api/auth/verify-password",
20
- ]);
21
- export function createAuth(opts) {
22
- const { provider } = opts;
23
- const budget = {
24
- limit: opts.rateLimitPerHour ?? 10,
25
- trustedProxyHops: opts.trustedProxyHops ?? 0,
26
- };
27
- /** Spends one sign-in request from this caller's budget; true when there was none left. */
28
- async function budgetSpent() {
29
- const headers = await requestHeaders();
30
- return rateLimit({ path: SIGN_IN_BUDGET_PATH, headers, ...budget }) !== null;
31
- }
32
- async function getSession(headers) {
33
- return provider.getSession(headers ?? (await requestHeaders()));
34
- }
35
- async function requireSession(nextPath = "/") {
36
- const current = await getSession();
37
- if (!current) {
38
- const { redirect } = await navigation();
39
- return redirect(`${SIGN_IN_PATH}?next=${encodeURIComponent(safeNext(nextPath))}`);
40
- }
41
- return current;
42
- }
43
- return {
44
- getSession,
45
- requireSession,
46
- async requireAdmin() {
47
- const current = await requireSession();
48
- if (current.user.role !== "admin")
49
- return (await navigation()).notFound();
50
- return current;
51
- },
52
- // The provider passes `next` through as given, so it is made safe here, before any provider sees it. The budget is spent by every request, known address or not, so it says nothing.
53
- async requestMagicLink(input) {
54
- const next = safeNext(input.next);
55
- if (await budgetSpent())
56
- return { ok: false, code: "rate_limited" };
57
- return provider.signIn.magicLink(input.email, next);
58
- },
59
- async startGoogleSignIn(next) {
60
- const target = safeNext(next);
61
- if (await budgetSpent())
62
- return { ok: false, code: "rate_limited" };
63
- return provider.signIn.oauth("google", target);
64
- },
65
- async signOut() {
66
- const headers = await requestHeaders();
67
- try {
68
- await provider.signOut(headers);
69
- }
70
- catch (error) {
71
- // The caller is sent to sign-in either way, and a session that survived still expires.
72
- const message = error instanceof Error ? error.message : String(error);
73
- console.error("[auth] sign-out failed", { message });
74
- }
75
- },
76
- async handler(req) {
77
- const path = routePath(req);
78
- if (NOT_SERVED.has(path) || [...NOT_SERVED].some((route) => path.startsWith(`${route}/`))) {
79
- return Response.json({ error: { code: "not_found", message: "Not found." } }, { status: 404 });
80
- }
81
- // Every route, per path: asking for links is limited apart from following them.
82
- return rateLimit({ path, headers: req.headers, ...budget }) ?? provider.handler(req);
83
- },
84
- users: provider.users,
85
- };
86
- }
87
- /**
88
- * The request's path in one canonical spelling: percent-decoded, lower-cased, without repeated or trailing slashes. Better Auth routes none of the other spellings, so this is a backstop: if a router ever does, `/api/auth/sign-in/%65mail/` is still a path that is not served, and a spelling of the sign-in path is not a fresh budget.
89
- */
90
- function routePath(req) {
91
- const raw = new URL(req.url).pathname;
92
- let decoded = raw;
93
- try {
94
- decoded = decodeURIComponent(raw);
95
- }
96
- catch {
97
- // Malformed escapes: compare the raw path.
98
- }
99
- return decoded
100
- .toLowerCase()
101
- .replace(/\/{2,}/g, "/")
102
- .replace(/(.)\/$/, "$1");
103
- }
104
- export { clientIp } from "../http/client-ip.js";
105
- export { rateLimit } from "../http/rate-limit.js";
106
- export { safeNext } from "./safe-next.js";
1
+ /** @deprecated Import from `@wwchen/stack-auth`. */
2
+ export * from "@wwchen/stack-auth";
@@ -1,12 +1,2 @@
1
- import { type NextRequest, NextResponse } from "next/server.js";
2
- /**
3
- * For the app's `export const config = { matcher: [...] }`: page routes only. Next reads the matcher statically at build time, so the app's `src/proxy.ts` writes this value out literally rather than importing it; this export is what a test compares that literal against.
4
- */
5
- export declare const proxyMatcher: string[];
6
- export type SessionProxyOptions = {
7
- /** Where an anonymous request is sent. Defaults to `/sign-in`. */
8
- signInPath?: string;
9
- /** Paths anyone may see. Each covers itself and everything under it; `/` covers only `/`. */
10
- publicPaths?: string[];
11
- };
12
- export declare function sessionProxy(opts?: SessionProxyOptions): (req: NextRequest) => NextResponse;
1
+ /** @deprecated Import from `@wwchen/stack-auth/proxy`. */
2
+ export * from "@wwchen/stack-auth/proxy";
@@ -1,37 +1,2 @@
1
- import { NextResponse } from "next/server.js";
2
- /**
3
- * The redirect half of route protection, for the app's `src/proxy.ts` (Next 16's name for middleware), and the only place the request path is knowable: a Next 16 server layout receives no pathname, so `/sign-in?next=<path>` cannot be built there. Running before routing also means an anonymous request is redirected rather than answered with a 404 by a page it cannot see yet.
4
- *
5
- * This checks only for the PRESENCE of a session cookie: a proxy has no database. It is a convenience — the real enforcement is `requireSession()` in the `(app)` layout, and every API route guards itself. Its own module, `@wwchen/stack/auth/proxy`, so the proxy bundle never pulls in the database or the auth provider.
6
- */
7
- // Better Auth names its cookie `<prefix>.session_token`, and prefixes it `__Secure-` when the cookie is secure — which it is whenever the app's URL is https.
8
- const SESSION_COOKIES = ["better-auth.session_token", "__Secure-better-auth.session_token"];
9
- /**
10
- * Paths the proxy never redirects, matching what `proxyMatcher` leaves out — so the proxy is right even when an app widens its matcher.
11
- *
12
- * `/api/**` is excluded for a reason, not for tidiness: an unauthenticated API call must answer 401 with the `{ error: { code, message } }` envelope from its own route; a redirect would hand the caller a 307 to an HTML page. Sign-in must stay out too, or an anonymous visitor redirects to it forever.
13
- */
14
- const EXCLUDED = /^\/(?:api(?:\/|$)|sign-in(?:\/|$)|_next\/|favicon\.ico$|.*\.(?:svg|png|jpg|jpeg|gif|webp|ico|txt|xml|webmanifest)$)/;
15
- /**
16
- * For the app's `export const config = { matcher: [...] }`: page routes only. Next reads the matcher statically at build time, so the app's `src/proxy.ts` writes this value out literally rather than importing it; this export is what a test compares that literal against.
17
- */
18
- export const proxyMatcher = [
19
- "/((?!api(?:/|$)|sign-in(?:/|$)|_next/|favicon\\.ico$|.*\\.(?:svg|png|jpg|jpeg|gif|webp|ico|txt|xml|webmanifest)$).*)",
20
- ];
21
- export function sessionProxy(opts = {}) {
22
- const signInPath = opts.signInPath ?? "/sign-in";
23
- const open = [signInPath, ...(opts.publicPaths ?? [])];
24
- const isOpen = (pathname) => EXCLUDED.test(pathname) ||
25
- open.some((path) => pathname === path || (path !== "/" && pathname.startsWith(`${path}/`)));
26
- return (req) => {
27
- const { pathname, search } = req.nextUrl;
28
- const signedIn = SESSION_COOKIES.some((name) => req.cookies.has(name));
29
- if (signedIn || isOpen(pathname))
30
- return NextResponse.next();
31
- const target = req.nextUrl.clone();
32
- target.pathname = signInPath;
33
- target.search = "";
34
- target.searchParams.set("next", `${pathname}${search}`);
35
- return NextResponse.redirect(target);
36
- };
37
- }
1
+ /** @deprecated Import from `@wwchen/stack-auth/proxy`. */
2
+ export * from "@wwchen/stack-auth/proxy";
@@ -1,3 +1,8 @@
1
+ /** The stack's own package.json: the installed version, and the suite packages it depends on. It sits two levels above both `src/cli/` and `dist/cli/`. */
2
+ export declare const STACK_PACKAGE: {
3
+ version: string;
4
+ dependencies: Record<string, string>;
5
+ };
1
6
  export type Env = Record<string, string | undefined>;
2
7
  export type ExecResult = {
3
8
  stdout: string;
@@ -6,6 +6,7 @@ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExte
6
6
  }
7
7
  return path;
8
8
  };
9
+ import { readFileSync } from "node:fs";
9
10
  import { userInfo } from "node:os";
10
11
  import { join } from "node:path";
11
12
  import { pathToFileURL } from "node:url";
@@ -13,6 +14,8 @@ import pg from "pg";
13
14
  import { explicitSslMode } from "../db/ssl.js";
14
15
  import { startPgliteServer } from "../db/testing/pglite.js";
15
16
  import { loadEnvFile } from "../env/index.js";
17
+ /** The stack's own package.json: the installed version, and the suite packages it depends on. It sits two levels above both `src/cli/` and `dist/cli/`. */
18
+ export const STACK_PACKAGE = JSON.parse(readFileSync(new URL("../../package.json", import.meta.url), "utf8"));
16
19
  export function resolveDeps(deps) {
17
20
  return {
18
21
  log: (message) => console.log(message),
@@ -0,0 +1,3 @@
1
+ import { type Cli } from "./context.ts";
2
+ export declare function dbCheck(cli: Cli): Promise<number>;
3
+ export declare function dbUpgrade(cli: Cli): Promise<number>;
package/dist/cli/db.js ADDED
@@ -0,0 +1,26 @@
1
+ // `stack db:check` — fails when the app's `src/db/schema.ts` has changes `drizzle/` has no migration for: a package table that changed in an upgrade, or the app's own, never generated. App CI runs it.
2
+ //
3
+ // `stack db:upgrade` — after the stack is upgraded, generates the migration for its tables' changes (`stack_<version>`), so the app's one history carries them. Copier runs it after `pnpm install`.
4
+ //
5
+ // Both run in the app's root and import its schema with Node's type stripping, so it must use relative `.ts` imports.
6
+ import { join } from "node:path";
7
+ import { pendingStatements } from "../db/schema-changes.js";
8
+ import { importApp, STACK_PACKAGE } from "./context.js";
9
+ async function pending(cli) {
10
+ const schema = await importApp(cli, "src/db/schema.ts");
11
+ return pendingStatements(schema, join(cli.cwd, "drizzle"));
12
+ }
13
+ export async function dbCheck(cli) {
14
+ const statements = await pending(cli);
15
+ if (statements.length === 0)
16
+ return 0;
17
+ cli.error(`src/db/schema.ts has changes drizzle/ has no migration for:\n\n${statements.join("\n")}\n\nRun \`pnpm exec drizzle-kit generate\`, review the SQL and commit it.`);
18
+ return 1;
19
+ }
20
+ export async function dbUpgrade(cli) {
21
+ if ((await pending(cli)).length === 0)
22
+ return 0;
23
+ const name = `stack_${STACK_PACKAGE.version.replaceAll(".", "_")}`;
24
+ cli.log(`generating drizzle/ migration ${name} for the schema's changes`);
25
+ return (await cli.exec("pnpm", ["exec", "drizzle-kit", "generate", "--name", name], { inherit: true })).code;
26
+ }
package/dist/cli/index.js CHANGED
@@ -3,8 +3,10 @@ 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 { dbCheck, dbUpgrade } from "./db.js";
6
7
  import { dev } from "./dev.js";
7
8
  import { doctor } from "./doctor.js";
9
+ import { migrateSuite } from "./migrate-suite.js";
8
10
  import { devSetup, neonSeed, resetPreview, withNeon } from "./neon.js";
9
11
  import { runScript } from "./run.js";
10
12
  import { syncBlocksCommand } from "./sync-blocks.js";
@@ -23,7 +25,11 @@ const USAGE = `usage: stack <command>
23
25
  user:create <email> [--admin] add a user through the app's auth; --preview: on the shared
24
26
  preview branch (your own email only, to sign in on a preview)
25
27
  user:role <email> <admin|user> change a user's role through the app's auth; --preview as above
26
- sync-blocks [--check] refresh the stack-owned blocks in AGENTS.md, CLAUDE.md, .gitignore, .env.example`;
28
+ sync-blocks [--check] refresh the stack-owned blocks in AGENTS.md, CLAUDE.md, .gitignore, .env.example
29
+ db:check fail when src/db/schema.ts has changes drizzle/ has no migration for
30
+ db:upgrade generate drizzle/'s migration for the schema's changes, named stack_<version>
31
+ migrate-suite [--expect <version>] move the app onto the suite's packages (@wwchen/stack-auth, -notify);
32
+ --expect: refuse unless the installed stack is that version`;
27
33
  /** The testable entry: every outside effect arrives through `deps`; the exit code comes back. */
28
34
  export async function runCli(argv, deps) {
29
35
  const cli = resolveDeps(deps);
@@ -54,6 +60,12 @@ export async function runCli(argv, deps) {
54
60
  return await userRole(cli, args);
55
61
  case "sync-blocks":
56
62
  return await syncBlocksCommand(cli, args);
63
+ case "db:check":
64
+ return await dbCheck(cli);
65
+ case "db:upgrade":
66
+ return await dbUpgrade(cli);
67
+ case "migrate-suite":
68
+ return await migrateSuite(cli, args);
57
69
  }
58
70
  }
59
71
  catch (error) {
@@ -0,0 +1,2 @@
1
+ import { type Cli } from "./context.ts";
2
+ export declare function migrateSuite(cli: Cli, args: string[]): Promise<number>;