@wwchen/stack 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (101) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +79 -2
  3. package/blocks/AGENTS.md +77 -0
  4. package/blocks/CLAUDE.md +113 -0
  5. package/blocks/env.example +34 -0
  6. package/blocks/gitignore +18 -0
  7. package/configs/biome.json +45 -0
  8. package/configs/tsconfig.next.json +22 -0
  9. package/dist/auth/better-auth/index.d.ts +316 -0
  10. package/dist/auth/better-auth/index.js +237 -0
  11. package/dist/auth/better-auth/tables.d.ts +628 -0
  12. package/dist/auth/better-auth/tables.js +74 -0
  13. package/dist/auth/better-auth/users.d.ts +27 -0
  14. package/dist/auth/better-auth/users.js +128 -0
  15. package/dist/auth/index.d.ts +58 -0
  16. package/dist/auth/index.js +120 -0
  17. package/dist/auth/proxy.d.ts +14 -0
  18. package/dist/auth/proxy.js +50 -0
  19. package/dist/auth/safe-next.d.ts +17 -0
  20. package/dist/auth/safe-next.js +36 -0
  21. package/dist/auth/types.d.ts +47 -0
  22. package/dist/auth/types.js +5 -0
  23. package/dist/cli/context.d.ts +38 -0
  24. package/dist/cli/context.js +43 -0
  25. package/dist/cli/index.d.ts +4 -0
  26. package/dist/cli/index.js +95 -0
  27. package/dist/cli/neon.d.ts +97 -0
  28. package/dist/cli/neon.js +334 -0
  29. package/dist/cli/sync-blocks.d.ts +16 -0
  30. package/dist/cli/sync-blocks.js +97 -0
  31. package/dist/cli/user-create.d.ts +2 -0
  32. package/dist/cli/user-create.js +35 -0
  33. package/dist/cli/vercel-build.d.ts +4 -0
  34. package/dist/cli/vercel-build.js +72 -0
  35. package/dist/configs/vitest.d.ts +4 -0
  36. package/dist/configs/vitest.js +50 -0
  37. package/dist/connections/crypto.d.ts +8 -0
  38. package/dist/connections/crypto.js +50 -0
  39. package/dist/connections/index.d.ts +63 -0
  40. package/dist/connections/index.js +212 -0
  41. package/dist/connections/providers.d.ts +30 -0
  42. package/dist/connections/providers.js +47 -0
  43. package/dist/connections/table.d.ts +156 -0
  44. package/dist/connections/table.js +29 -0
  45. package/dist/db/explaining-pool.d.ts +16 -0
  46. package/dist/db/explaining-pool.js +62 -0
  47. package/dist/db/index.d.ts +21 -0
  48. package/dist/db/index.js +36 -0
  49. package/dist/db/migration-status.d.ts +8 -0
  50. package/dist/db/migration-status.js +41 -0
  51. package/dist/db/target.d.ts +26 -0
  52. package/dist/db/target.js +72 -0
  53. package/dist/db/testing/index.d.ts +27 -0
  54. package/dist/db/testing/index.js +71 -0
  55. package/dist/db/testing/isolate.d.ts +1 -0
  56. package/dist/db/testing/isolate.js +4 -0
  57. package/dist/db/testing/pglite.d.ts +21 -0
  58. package/dist/db/testing/pglite.js +71 -0
  59. package/dist/env/define-env.d.ts +37 -0
  60. package/dist/env/define-env.js +134 -0
  61. package/dist/env/index.d.ts +3 -0
  62. package/dist/env/index.js +3 -0
  63. package/dist/env/load-env-file.d.ts +15 -0
  64. package/dist/env/load-env-file.js +52 -0
  65. package/dist/env/stack-env.d.ts +40 -0
  66. package/dist/env/stack-env.js +60 -0
  67. package/dist/env/testing.d.ts +8 -0
  68. package/dist/env/testing.js +16 -0
  69. package/dist/http/client-ip.d.ts +12 -0
  70. package/dist/http/client-ip.js +28 -0
  71. package/dist/http/guards.d.ts +17 -0
  72. package/dist/http/guards.js +57 -0
  73. package/dist/http/rate-limit.d.ts +34 -0
  74. package/dist/http/rate-limit.js +79 -0
  75. package/dist/index.d.ts +1 -0
  76. package/dist/index.js +1 -0
  77. package/dist/jobs/index.d.ts +37 -0
  78. package/dist/jobs/index.js +51 -0
  79. package/dist/mail/index.d.ts +45 -0
  80. package/dist/mail/index.js +97 -0
  81. package/dist/next/api.d.ts +71 -0
  82. package/dist/next/api.js +118 -0
  83. package/dist/next/config.d.ts +8 -0
  84. package/dist/next/config.js +104 -0
  85. package/dist/next/cron.d.ts +14 -0
  86. package/dist/next/cron.js +40 -0
  87. package/dist/next/health.d.ts +19 -0
  88. package/dist/next/health.js +36 -0
  89. package/dist/next/index.d.ts +5 -0
  90. package/dist/next/index.js +4 -0
  91. package/dist/testing/next.d.ts +14 -0
  92. package/dist/testing/next.js +39 -0
  93. package/dist/ui/app.css +56 -0
  94. package/dist/ui/globals.css +152 -0
  95. package/dist/ui/icons.d.ts +17 -0
  96. package/dist/ui/icons.js +104 -0
  97. package/dist/ui/index.d.ts +33 -0
  98. package/dist/ui/index.js +41 -0
  99. package/dist/ui/theme.d.ts +18 -0
  100. package/dist/ui/theme.js +24 -0
  101. package/package.json +134 -4
@@ -0,0 +1,27 @@
1
+ import type { NodePgDatabase } from "drizzle-orm/node-postgres";
2
+ import type { AuthProvider } from "../types.ts";
3
+ import type { AuthTables } from "./tables.ts";
4
+ /**
5
+ * Who gets in. Sign-in never creates a user, so a person exists because an admin added their email
6
+ * here (from a dashboard, or `stack user:create`); they then sign in with a magic link or Google
7
+ * like anyone else. Removing a person deletes their user row, sessions and accounts in one
8
+ * transaction, so a cookie they still hold stops working on their next request.
9
+ *
10
+ * The app always has an admin once it has one: any change that would leave none is refused inside
11
+ * the transaction that holds a lock on the admin rows, so two concurrent demotions cannot both
12
+ * succeed.
13
+ */
14
+ export declare class DuplicateUserError extends Error {
15
+ constructor(email: string);
16
+ }
17
+ export declare class LastAdminError extends Error {
18
+ constructor();
19
+ }
20
+ export declare class UserNotFoundError extends Error {
21
+ constructor();
22
+ }
23
+ /** Trimmed and lower-cased: the one form an email is stored and looked up in. */
24
+ export declare function normaliseEmail(email: string): string;
25
+ type Database = NodePgDatabase<any>;
26
+ export declare function createUsers(db: Database, tables: AuthTables): AuthProvider["users"];
27
+ export {};
@@ -0,0 +1,128 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { asc, eq } from "drizzle-orm";
3
+ import { z } from "zod";
4
+ /**
5
+ * Who gets in. Sign-in never creates a user, so a person exists because an admin added their email
6
+ * here (from a dashboard, or `stack user:create`); they then sign in with a magic link or Google
7
+ * like anyone else. Removing a person deletes their user row, sessions and accounts in one
8
+ * transaction, so a cookie they still hold stops working on their next request.
9
+ *
10
+ * The app always has an admin once it has one: any change that would leave none is refused inside
11
+ * the transaction that holds a lock on the admin rows, so two concurrent demotions cannot both
12
+ * succeed.
13
+ */
14
+ export class DuplicateUserError extends Error {
15
+ constructor(email) {
16
+ super(`A user with the email ${email} already exists`);
17
+ this.name = "DuplicateUserError";
18
+ }
19
+ }
20
+ export class LastAdminError extends Error {
21
+ constructor() {
22
+ super("There must be at least one admin");
23
+ this.name = "LastAdminError";
24
+ }
25
+ }
26
+ export class UserNotFoundError extends Error {
27
+ constructor() {
28
+ super("User not found");
29
+ this.name = "UserNotFoundError";
30
+ }
31
+ }
32
+ /** Trimmed and lower-cased: the one form an email is stored and looked up in. */
33
+ export function normaliseEmail(email) {
34
+ return email.trim().toLowerCase();
35
+ }
36
+ const emailSchema = z.email();
37
+ const uuidSchema = z.uuid();
38
+ const toRole = (role) => (role === "admin" ? "admin" : "user");
39
+ export function createUsers(db, tables) {
40
+ const { appUser, session, account } = tables;
41
+ const columns = {
42
+ id: appUser.id,
43
+ email: appUser.email,
44
+ name: appUser.name,
45
+ role: appUser.role,
46
+ createdAt: appUser.createdAt,
47
+ };
48
+ const toAppUser = (row) => ({
49
+ ...row,
50
+ role: toRole(row.role),
51
+ });
52
+ /** Locks every admin row for the rest of the transaction and returns their ids. */
53
+ async function lockAdmins(tx) {
54
+ const admins = await tx
55
+ .select({ id: appUser.id })
56
+ .from(appUser)
57
+ .where(eq(appUser.role, "admin"))
58
+ .for("update");
59
+ return admins.map((row) => row.id);
60
+ }
61
+ /** The target row, locked; `UserNotFoundError` when there is none (or the id is not a uuid). */
62
+ async function lockTarget(tx, userId) {
63
+ if (!uuidSchema.safeParse(userId).success)
64
+ throw new UserNotFoundError();
65
+ const [target] = await tx
66
+ .select({ id: appUser.id })
67
+ .from(appUser)
68
+ .where(eq(appUser.id, userId))
69
+ .for("update");
70
+ if (!target)
71
+ throw new UserNotFoundError();
72
+ }
73
+ return {
74
+ async add(rawEmail, role = "user") {
75
+ const email = normaliseEmail(rawEmail);
76
+ if (!emailSchema.safeParse(email).success) {
77
+ throw new Error(`"${rawEmail}" is not a valid email address`);
78
+ }
79
+ const [inserted] = await db
80
+ .insert(appUser)
81
+ .values({
82
+ id: randomUUID(),
83
+ name: email.split("@")[0],
84
+ email,
85
+ // The admin vouches for the address by adding it; signing in proves it on first use.
86
+ emailVerified: true,
87
+ role,
88
+ })
89
+ .onConflictDoNothing({ target: appUser.email })
90
+ .returning(columns);
91
+ if (!inserted)
92
+ throw new DuplicateUserError(email);
93
+ return toAppUser(inserted);
94
+ },
95
+ async remove(userId) {
96
+ await db.transaction(async (tx) => {
97
+ const admins = await lockAdmins(tx);
98
+ await lockTarget(tx, userId);
99
+ if (admins.includes(userId) && admins.length <= 1)
100
+ throw new LastAdminError();
101
+ // The foreign keys cascade these too; deleting them by name keeps the guarantee — no
102
+ // session or linked account outlives the person — independent of the app's constraints.
103
+ await tx.delete(session).where(eq(session.userId, userId));
104
+ await tx.delete(account).where(eq(account.userId, userId));
105
+ await tx.delete(appUser).where(eq(appUser.id, userId));
106
+ });
107
+ },
108
+ async setRole(userId, role) {
109
+ await db.transaction(async (tx) => {
110
+ const admins = await lockAdmins(tx);
111
+ await lockTarget(tx, userId);
112
+ const isAdmin = admins.includes(userId);
113
+ if ((role === "admin") === isAdmin)
114
+ return;
115
+ if (isAdmin && admins.length <= 1)
116
+ throw new LastAdminError();
117
+ await tx.update(appUser).set({ role, updatedAt: new Date() }).where(eq(appUser.id, userId));
118
+ });
119
+ },
120
+ async list() {
121
+ const rows = await db
122
+ .select(columns)
123
+ .from(appUser)
124
+ .orderBy(asc(appUser.createdAt), asc(appUser.email));
125
+ return rows.map(toAppUser);
126
+ },
127
+ };
128
+ }
@@ -0,0 +1,58 @@
1
+ import type { AuthProvider, AuthResult, Session } from "./types.ts";
2
+ /**
3
+ * The app's one auth object: `export const auth = createAuth({ provider })` in `src/lib/auth.ts`,
4
+ * and every session read, sign-in and sign-out goes through it. Which provider runs sign-in is
5
+ * invisible past this point.
6
+ *
7
+ * The sign-in functions are plain async functions that read the request through `next/headers`;
8
+ * the app's thin `actions.ts` marks them `"use server"` (the package ships no server-action module).
9
+ * They must run as server actions: that is where Next lets a cookie be set, and the provider sets
10
+ * its cookies there — Better Auth's `nextCookies()` writes each `Set-Cookie` of an in-process call
11
+ * (Google's signed state cookie, sign-out's cleared session) into `cookies()`.
12
+ */
13
+ export type CreateAuthOptions = {
14
+ provider: AuthProvider;
15
+ /**
16
+ * Sign-in requests allowed per client address per hour (default 10). Spent by every magic-link
17
+ * request and Google start, whatever the address typed. `Infinity` turns the limit off.
18
+ */
19
+ rateLimitPerHour?: number;
20
+ /** Proxies in front of the app that append to `X-Forwarded-For` (default 0, as on Vercel). */
21
+ trustedProxyHops?: number;
22
+ };
23
+ export type StackAuth = {
24
+ /** The session, or null. Reads `headers` when given (route handlers), else the request's. */
25
+ getSession(headers?: Headers): Promise<Session | null>;
26
+ /**
27
+ * The session, or a redirect to `/sign-in?next=<nextPath>`. A server layout cannot see the
28
+ * request path in Next 16, so the caller supplies it; the proxy redirects with the real one.
29
+ */
30
+ requireSession(nextPath?: string): Promise<Session>;
31
+ /**
32
+ * An admin's session, or the not-found page: a signed-in user who is not an admin gets the same
33
+ * 404 a missing page does, so admin pages do not announce themselves. Pages only — `notFound()`
34
+ * throws, so API routes check `session.user.role` and answer the envelope instead.
35
+ */
36
+ requireAdmin(): Promise<Session>;
37
+ /**
38
+ * Sends a sign-in link. `{ ok: true }` for every address, known or not (the provider sends
39
+ * nothing to an address nobody added). `rate_limited` once this caller's budget is spent.
40
+ */
41
+ requestMagicLink(input: {
42
+ email: string;
43
+ next?: string;
44
+ }): Promise<AuthResult>;
45
+ /** Starts Google sign-in; `redirect` is Google's URL, for the action to `redirect()` to. */
46
+ startGoogleSignIn(next?: string): Promise<AuthResult>;
47
+ /** Ends the session and clears its cookie. A failure is logged and swallowed. */
48
+ signOut(): Promise<void>;
49
+ /** For `app/api/auth/[...all]/route.ts`: `export const GET = auth.handler, POST = auth.handler`. */
50
+ handler(req: Request): Promise<Response>;
51
+ /** Invite-only user management. */
52
+ users: AuthProvider["users"];
53
+ };
54
+ export declare function createAuth(opts: CreateAuthOptions): StackAuth;
55
+ export { clientIp } from "../http/client-ip.ts";
56
+ export { type RateLimitInput, rateLimit } from "../http/rate-limit.ts";
57
+ export { safeNext } from "./safe-next.ts";
58
+ export type { AppUser, AuthErrorCode, AuthProvider, AuthResult, Role, Session, } from "./types.ts";
@@ -0,0 +1,120 @@
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
7
+ * its own versions only for the bare `next/navigation`; `next/navigation.js` is the client module,
8
+ * which cannot load in a route handler. Plain Node (the `stack` CLI importing the app's auth) cannot
9
+ * resolve the bare name, and never calls this.
10
+ */
11
+ const navigation = () => import("next/navigation");
12
+ /**
13
+ * The bucket the sign-in functions spend, under the path of the route that does the same thing, so
14
+ * a raw POST to that route and the server action share one budget: neither is a way around the
15
+ * other.
16
+ */
17
+ const SIGN_IN_BUDGET_PATH = "/api/auth/sign-in/magic-link";
18
+ /**
19
+ * Better Auth's password routes. Passwords are off unless an app opts in with
20
+ * `betterAuthProvider({ emailAndPassword })` (as cc needs); it then calls
21
+ * `provider.instance.api.signInEmail / changePassword / verifyPassword` in-process from its own
22
+ * server action, with a budget of its own. Served here too, each would be a second door with its
23
+ * own budget, multiplying the guesses an attacker gets. Answered 404 whether or not the option is
24
+ * on (off, Better Auth refuses them anyway).
25
+ */
26
+ const NOT_SERVED = new Set([
27
+ "/api/auth/sign-in/email",
28
+ "/api/auth/change-password",
29
+ "/api/auth/verify-password",
30
+ ]);
31
+ export function createAuth(opts) {
32
+ const { provider } = opts;
33
+ const budget = {
34
+ limit: opts.rateLimitPerHour ?? 10,
35
+ trustedProxyHops: opts.trustedProxyHops ?? 0,
36
+ };
37
+ /** Spends one sign-in request from this caller's budget; true when there was none left. */
38
+ async function budgetSpent() {
39
+ const headers = await requestHeaders();
40
+ return rateLimit({ path: SIGN_IN_BUDGET_PATH, headers, ...budget }) !== null;
41
+ }
42
+ async function getSession(headers) {
43
+ return provider.getSession(headers ?? (await requestHeaders()));
44
+ }
45
+ async function requireSession(nextPath = "/") {
46
+ const current = await getSession();
47
+ if (!current) {
48
+ const { redirect } = await navigation();
49
+ return redirect(`${SIGN_IN_PATH}?next=${encodeURIComponent(safeNext(nextPath))}`);
50
+ }
51
+ return current;
52
+ }
53
+ return {
54
+ getSession,
55
+ requireSession,
56
+ async requireAdmin() {
57
+ const current = await requireSession();
58
+ if (current.user.role !== "admin")
59
+ return (await navigation()).notFound();
60
+ return current;
61
+ },
62
+ // The provider passes `next` through as given, so it is made safe here, before any provider
63
+ // sees it. The budget is spent by every request, known address or not, so it says nothing.
64
+ async requestMagicLink(input) {
65
+ const next = safeNext(input.next);
66
+ if (await budgetSpent())
67
+ return { ok: false, code: "rate_limited" };
68
+ return provider.signIn.magicLink(input.email, next);
69
+ },
70
+ async startGoogleSignIn(next) {
71
+ const target = safeNext(next);
72
+ if (await budgetSpent())
73
+ return { ok: false, code: "rate_limited" };
74
+ return provider.signIn.oauth("google", target);
75
+ },
76
+ async signOut() {
77
+ const headers = await requestHeaders();
78
+ try {
79
+ await provider.signOut(headers);
80
+ }
81
+ catch (error) {
82
+ // The caller is sent to sign-in either way, and a session that survived still expires.
83
+ const message = error instanceof Error ? error.message : String(error);
84
+ console.error("[auth] sign-out failed", { message });
85
+ }
86
+ },
87
+ async handler(req) {
88
+ const path = routePath(req);
89
+ if (NOT_SERVED.has(path) || [...NOT_SERVED].some((route) => path.startsWith(`${route}/`))) {
90
+ return Response.json({ error: { code: "not_found", message: "Not found." } }, { status: 404 });
91
+ }
92
+ // Every route, per path: asking for links is limited apart from following them.
93
+ return rateLimit({ path, headers: req.headers, ...budget }) ?? provider.handler(req);
94
+ },
95
+ users: provider.users,
96
+ };
97
+ }
98
+ /**
99
+ * The request's path in one canonical spelling: percent-decoded, lower-cased, without repeated or
100
+ * trailing slashes. Better Auth routes none of the other spellings, so this is a backstop: if
101
+ * a router ever does, `/api/auth/sign-in/%65mail/` is still a path that is not served, and a
102
+ * spelling of the sign-in path is not a fresh budget.
103
+ */
104
+ function routePath(req) {
105
+ const raw = new URL(req.url).pathname;
106
+ let decoded = raw;
107
+ try {
108
+ decoded = decodeURIComponent(raw);
109
+ }
110
+ catch {
111
+ // Malformed escapes: compare the raw path.
112
+ }
113
+ return decoded
114
+ .toLowerCase()
115
+ .replace(/\/{2,}/g, "/")
116
+ .replace(/(.)\/$/, "$1");
117
+ }
118
+ export { clientIp } from "../http/client-ip.js";
119
+ export { rateLimit } from "../http/rate-limit.js";
120
+ export { safeNext } from "./safe-next.js";
@@ -0,0 +1,14 @@
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
4
+ * matcher statically at build time, so the app's `src/proxy.ts` writes this value out literally
5
+ * rather than importing it; this export is what a test compares that literal against.
6
+ */
7
+ export declare const proxyMatcher: string[];
8
+ export type SessionProxyOptions = {
9
+ /** Where an anonymous request is sent. Defaults to `/sign-in`. */
10
+ signInPath?: string;
11
+ /** Paths anyone may see. Each covers itself and everything under it; `/` covers only `/`. */
12
+ publicPaths?: string[];
13
+ };
14
+ export declare function sessionProxy(opts?: SessionProxyOptions): (req: NextRequest) => NextResponse;
@@ -0,0 +1,50 @@
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
4
+ * middleware), and the only place the request path is knowable: a Next 16 server layout receives no
5
+ * pathname, so `/sign-in?next=<path>` cannot be built there. Running before routing also means an
6
+ * anonymous request is redirected rather than answered with a 404 by a page it cannot see yet.
7
+ *
8
+ * This checks only for the PRESENCE of a session cookie: a proxy has no database. It is a
9
+ * convenience — the real enforcement is `requireSession()` in the `(app)` layout, and every API
10
+ * route guards itself. Its own module, `@wwchen/stack/auth/proxy`, so the proxy bundle never pulls
11
+ * in the database or the auth provider.
12
+ */
13
+ // Better Auth names its cookie `<prefix>.session_token`, and prefixes it `__Secure-` when the
14
+ // cookie is secure — which it is whenever the app's URL is https.
15
+ const SESSION_COOKIES = ["better-auth.session_token", "__Secure-better-auth.session_token"];
16
+ /**
17
+ * Paths the proxy never redirects, matching what `proxyMatcher` leaves out — so the proxy is right
18
+ * even when an app widens its matcher.
19
+ *
20
+ * `/api/**` is excluded for a reason, not for tidiness: an unauthenticated API call must answer 401
21
+ * with the `{ error: { code, message } }` envelope from its own route; a redirect would hand the
22
+ * caller a 307 to an HTML page. Sign-in must stay out too, or an anonymous visitor redirects to it
23
+ * forever.
24
+ */
25
+ const EXCLUDED = /^\/(?:api(?:\/|$)|sign-in(?:\/|$)|_next\/|favicon\.ico$|.*\.(?:svg|png|jpg|jpeg|gif|webp|ico|txt|xml|webmanifest)$)/;
26
+ /**
27
+ * For the app's `export const config = { matcher: [...] }`: page routes only. Next reads the
28
+ * matcher statically at build time, so the app's `src/proxy.ts` writes this value out literally
29
+ * rather than importing it; this export is what a test compares that literal against.
30
+ */
31
+ export const proxyMatcher = [
32
+ "/((?!api(?:/|$)|sign-in(?:/|$)|_next/|favicon\\.ico$|.*\\.(?:svg|png|jpg|jpeg|gif|webp|ico|txt|xml|webmanifest)$).*)",
33
+ ];
34
+ export function sessionProxy(opts = {}) {
35
+ const signInPath = opts.signInPath ?? "/sign-in";
36
+ const open = [signInPath, ...(opts.publicPaths ?? [])];
37
+ const isOpen = (pathname) => EXCLUDED.test(pathname) ||
38
+ open.some((path) => pathname === path || (path !== "/" && pathname.startsWith(`${path}/`)));
39
+ return (req) => {
40
+ const { pathname, search } = req.nextUrl;
41
+ const signedIn = SESSION_COOKIES.some((name) => req.cookies.has(name));
42
+ if (signedIn || isOpen(pathname))
43
+ return NextResponse.next();
44
+ const target = req.nextUrl.clone();
45
+ target.pathname = signInPath;
46
+ target.search = "";
47
+ target.searchParams.set("next", `${pathname}${search}`);
48
+ return NextResponse.redirect(target);
49
+ };
50
+ }
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Where to send someone after signing in, from a `?next=` they could have been handed by anyone.
3
+ * Only a path on this site is kept; anything else becomes `fallback`, so a sign-in link can never
4
+ * be turned into a redirect to another origin.
5
+ *
6
+ * Kept: a string starting with a single `/`. Refused, as well as anything that is not a string:
7
+ * - `//host` and `/\host`: browsers read both as protocol-relative URLs to another host;
8
+ * - any backslash: the URL parser turns it into `/`;
9
+ * - control characters: the URL parser strips tabs and newlines, so `/\t/host` becomes `//host`;
10
+ * - `https:`, `javascript:` and every other scheme: they do not start with `/`.
11
+ * Then the path is resolved as a browser would, which removes dot segments (`.`, `..`, `%2e`): it
12
+ * must stay on the origin it is resolved against, and its resolved path must not itself start with
13
+ * `//` — `/..//host` and `/%2e//host` resolve to `//host`, which a router that writes the path back
14
+ * would follow off-site. What is returned is that resolved path, query and fragment, so a caller
15
+ * only ever passes on what was checked.
16
+ */
17
+ export declare function safeNext(raw: unknown, fallback?: string): string;
@@ -0,0 +1,36 @@
1
+ /**
2
+ * Where to send someone after signing in, from a `?next=` they could have been handed by anyone.
3
+ * Only a path on this site is kept; anything else becomes `fallback`, so a sign-in link can never
4
+ * be turned into a redirect to another origin.
5
+ *
6
+ * Kept: a string starting with a single `/`. Refused, as well as anything that is not a string:
7
+ * - `//host` and `/\host`: browsers read both as protocol-relative URLs to another host;
8
+ * - any backslash: the URL parser turns it into `/`;
9
+ * - control characters: the URL parser strips tabs and newlines, so `/\t/host` becomes `//host`;
10
+ * - `https:`, `javascript:` and every other scheme: they do not start with `/`.
11
+ * Then the path is resolved as a browser would, which removes dot segments (`.`, `..`, `%2e`): it
12
+ * must stay on the origin it is resolved against, and its resolved path must not itself start with
13
+ * `//` — `/..//host` and `/%2e//host` resolve to `//host`, which a router that writes the path back
14
+ * would follow off-site. What is returned is that resolved path, query and fragment, so a caller
15
+ * only ever passes on what was checked.
16
+ */
17
+ export function safeNext(raw, fallback = "/") {
18
+ if (typeof raw !== "string")
19
+ return fallback;
20
+ if (!raw.startsWith("/") || raw.startsWith("//"))
21
+ return fallback;
22
+ // biome-ignore lint/suspicious/noControlCharactersInRegex: refusing control characters is the point.
23
+ if (/[\\\u0000-\u001f\u007f]/.test(raw))
24
+ return fallback;
25
+ const base = "http://same-site.invalid";
26
+ let url;
27
+ try {
28
+ url = new URL(raw, base);
29
+ }
30
+ catch {
31
+ return fallback;
32
+ }
33
+ if (url.origin !== base || url.pathname.startsWith("//"))
34
+ return fallback;
35
+ return `${url.pathname}${url.search}${url.hash}`;
36
+ }
@@ -0,0 +1,47 @@
1
+ /**
2
+ * The provider-agnostic auth types. An app only ever sees these: whichever provider runs sign-in,
3
+ * a session's user is an `app_user` row, and a sign-in answers with a short, normalised code.
4
+ */
5
+ /** The two roles. Granted by an admin, never assumed: a user with no admin role reads as `user`. */
6
+ export type Role = "admin" | "user";
7
+ export type AppUser = {
8
+ id: string;
9
+ email: string;
10
+ name: string | null;
11
+ role: Role;
12
+ createdAt: Date;
13
+ };
14
+ export type Session = {
15
+ user: AppUser;
16
+ expiresAt: Date;
17
+ };
18
+ export type AuthErrorCode = "invalid_email" | "rate_limited" | "unavailable";
19
+ export type AuthResult = {
20
+ ok: true;
21
+ redirect?: string;
22
+ } | {
23
+ ok: false;
24
+ code: AuthErrorCode;
25
+ };
26
+ export interface AuthProvider {
27
+ /** Serves the provider's routes: `app/api/auth/[...all]/route.ts`. */
28
+ handler(req: Request): Promise<Response>;
29
+ /** The session the request's cookies carry, or null. `Session.user` is an `app_user` row. */
30
+ getSession(headers: Headers): Promise<Session | null>;
31
+ signIn: {
32
+ /** Sends a sign-in link to an added user; answers the same for an address nobody added. */
33
+ magicLink(email: string, next: string): Promise<AuthResult>;
34
+ /** Starts an OAuth sign-in; `redirect` is the provider's URL. Never creates a user. */
35
+ oauth(providerId: string, next: string): Promise<AuthResult>;
36
+ };
37
+ signOut(headers: Headers): Promise<void>;
38
+ /** For adapters that need a verifier step in the proxy. */
39
+ proxy?(req: Request): Promise<Response | null>;
40
+ /** Invite-only user management: sign-in never creates a user, an admin adds them here. */
41
+ users: {
42
+ add(email: string, role?: Role): Promise<AppUser>;
43
+ remove(userId: string): Promise<void>;
44
+ setRole(userId: string, role: Role): Promise<void>;
45
+ list(): Promise<AppUser[]>;
46
+ };
47
+ }
@@ -0,0 +1,5 @@
1
+ /**
2
+ * The provider-agnostic auth types. An app only ever sees these: whichever provider runs sign-in,
3
+ * a session's user is an `app_user` row, and a sign-in answers with a short, normalised code.
4
+ */
5
+ export {};
@@ -0,0 +1,38 @@
1
+ export type Env = Record<string, string | undefined>;
2
+ export type ExecResult = {
3
+ stdout: string;
4
+ code: number;
5
+ };
6
+ export type ExecOptions = {
7
+ /** The child's environment; defaults to the CLI's own. */
8
+ env?: Env;
9
+ /** Hand the child this terminal (a dev server, a build) instead of capturing its stdout. */
10
+ inherit?: boolean;
11
+ };
12
+ /**
13
+ * Everything the CLI touches outside its own process, so a test can replace it. Only the entry
14
+ * point reads `process.env`: it passes it in as `env`, and nothing below reads it directly.
15
+ * `exec` runs a program with an argument array, never a shell string.
16
+ */
17
+ export type CliDeps = {
18
+ env: Env;
19
+ exec(command: string, args: string[], options?: ExecOptions): Promise<ExecResult>;
20
+ cwd: string;
21
+ /** The OS user, for the default `dev/<user>` branch name. */
22
+ username?: string;
23
+ log?(message: string): void;
24
+ error?(message: string): void;
25
+ /** Imports the app's own TypeScript (`src/lib/auth.ts`, `db/seed.ts`) with Node's type stripping. */
26
+ importModule?(specifier: string): Promise<Record<string, unknown>>;
27
+ /** Runs one SQL statement against a database, for emptying the new `seed` branch. */
28
+ sql?(url: string, statement: string): Promise<Record<string, unknown>[]>;
29
+ };
30
+ export type Cli = Required<CliDeps>;
31
+ export declare function resolveDeps(deps: CliDeps): Cli;
32
+ /** Loads the app's `.env` (or the file `ENV_FILE` names) into `env`; real variables always win. */
33
+ export declare function loadAppEnv(cli: Cli): void;
34
+ /** Imports a file of the app by path relative to its root. */
35
+ export declare function importApp(cli: Cli, path: string): Promise<Record<string, unknown>>;
36
+ /** A failure the CLI reports as one line and a non-zero exit, with no stack trace. */
37
+ export declare class CliError extends Error {
38
+ }
@@ -0,0 +1,43 @@
1
+ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExtension) || function (path, preserveJsx) {
2
+ if (typeof path === "string" && /^\.\.?\//.test(path)) {
3
+ return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
4
+ return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
5
+ });
6
+ }
7
+ return path;
8
+ };
9
+ import { userInfo } from "node:os";
10
+ import { join } from "node:path";
11
+ import { pathToFileURL } from "node:url";
12
+ import pg from "pg";
13
+ import { loadEnvFile } from "../env/index.js";
14
+ export function resolveDeps(deps) {
15
+ return {
16
+ log: (message) => console.log(message),
17
+ error: (message) => console.error(message),
18
+ username: userInfo().username,
19
+ importModule: (specifier) => import(__rewriteRelativeImportExtension(specifier)),
20
+ sql: async (url, statement) => {
21
+ const client = new pg.Client({ connectionString: url });
22
+ await client.connect();
23
+ try {
24
+ return (await client.query(statement)).rows;
25
+ }
26
+ finally {
27
+ await client.end();
28
+ }
29
+ },
30
+ ...deps,
31
+ };
32
+ }
33
+ /** Loads the app's `.env` (or the file `ENV_FILE` names) into `env`; real variables always win. */
34
+ export function loadAppEnv(cli) {
35
+ loadEnvFile(cli.env.ENV_FILE?.trim() ? undefined : join(cli.cwd, ".env"), cli.env);
36
+ }
37
+ /** Imports a file of the app by path relative to its root. */
38
+ export function importApp(cli, path) {
39
+ return cli.importModule(pathToFileURL(join(cli.cwd, path)).href);
40
+ }
41
+ /** A failure the CLI reports as one line and a non-zero exit, with no stack trace. */
42
+ export class CliError extends Error {
43
+ }
@@ -0,0 +1,4 @@
1
+ #!/usr/bin/env node
2
+ import { type CliDeps } from "./context.ts";
3
+ /** The testable entry: every outside effect arrives through `deps`; the exit code comes back. */
4
+ export declare function runCli(argv: string[], deps: CliDeps): Promise<number>;