@wwchen/stack 0.6.2 → 0.6.4

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 (78) hide show
  1. package/blocks/env.example +1 -2
  2. package/dist/auth/better-auth/index.d.ts +6 -17
  3. package/dist/auth/better-auth/index.js +11 -33
  4. package/dist/auth/better-auth/tables.js +5 -14
  5. package/dist/auth/better-auth/users.d.ts +2 -7
  6. package/dist/auth/better-auth/users.js +3 -9
  7. package/dist/auth/index.d.ts +6 -17
  8. package/dist/auth/index.js +5 -19
  9. package/dist/auth/proxy.d.ts +1 -3
  10. package/dist/auth/proxy.js +6 -19
  11. package/dist/auth/safe-next.d.ts +2 -8
  12. package/dist/auth/safe-next.js +2 -8
  13. package/dist/auth/types.d.ts +1 -2
  14. package/dist/auth/types.js +1 -2
  15. package/dist/cli/context.d.ts +1 -3
  16. package/dist/cli/index.js +1 -2
  17. package/dist/cli/neon.d.ts +11 -44
  18. package/dist/cli/neon.js +15 -56
  19. package/dist/cli/sync-blocks.d.ts +1 -3
  20. package/dist/cli/sync-blocks.js +2 -6
  21. package/dist/cli/vercel-build.js +5 -16
  22. package/dist/configs/vitest.js +3 -7
  23. package/dist/connections/index.d.ts +2 -8
  24. package/dist/connections/index.js +2 -8
  25. package/dist/connections/providers.d.ts +1 -3
  26. package/dist/connections/table.d.ts +1 -2
  27. package/dist/connections/table.js +1 -2
  28. package/dist/db/explaining-pool.d.ts +1 -6
  29. package/dist/db/explaining-pool.js +3 -10
  30. package/dist/db/index.d.ts +1 -3
  31. package/dist/db/index.js +5 -13
  32. package/dist/db/migration-status.d.ts +1 -4
  33. package/dist/db/migration-status.js +1 -4
  34. package/dist/db/ssl.d.ts +1 -5
  35. package/dist/db/ssl.js +1 -5
  36. package/dist/db/target.d.ts +2 -9
  37. package/dist/db/target.js +2 -9
  38. package/dist/db/testing/index.d.ts +3 -7
  39. package/dist/db/testing/index.js +3 -7
  40. package/dist/db/testing/isolate.js +1 -2
  41. package/dist/db/testing/pglite.d.ts +2 -6
  42. package/dist/db/testing/pglite.js +2 -6
  43. package/dist/env/define-env.d.ts +3 -9
  44. package/dist/env/define-env.js +6 -16
  45. package/dist/env/load-env-file.d.ts +4 -9
  46. package/dist/env/load-env-file.js +5 -11
  47. package/dist/env/stack-env.d.ts +1 -3
  48. package/dist/env/stack-env.js +3 -7
  49. package/dist/env/testing.d.ts +1 -3
  50. package/dist/env/testing.js +2 -5
  51. package/dist/http/client-ip.d.ts +2 -8
  52. package/dist/http/client-ip.js +3 -10
  53. package/dist/http/guards.d.ts +3 -10
  54. package/dist/http/guards.js +4 -12
  55. package/dist/http/rate-limit.d.ts +4 -10
  56. package/dist/http/rate-limit.js +7 -19
  57. package/dist/jobs/index.d.ts +2 -9
  58. package/dist/jobs/index.js +2 -9
  59. package/dist/mail/index.d.ts +2 -9
  60. package/dist/mail/index.js +2 -7
  61. package/dist/next/api.d.ts +6 -17
  62. package/dist/next/api.js +6 -15
  63. package/dist/next/config.js +10 -32
  64. package/dist/next/cron.d.ts +2 -6
  65. package/dist/next/cron.js +3 -8
  66. package/dist/next/health.d.ts +3 -8
  67. package/dist/next/health.js +3 -8
  68. package/dist/testing/next.d.ts +1 -4
  69. package/dist/testing/next.js +2 -7
  70. package/dist/ui/app.css +5 -16
  71. package/dist/ui/globals.css +6 -20
  72. package/dist/ui/icons.d.ts +1 -3
  73. package/dist/ui/icons.js +3 -10
  74. package/dist/ui/index.d.ts +4 -12
  75. package/dist/ui/index.js +4 -12
  76. package/dist/ui/theme.d.ts +3 -9
  77. package/dist/ui/theme.js +3 -9
  78. package/package.json +3 -3
@@ -1,5 +1,4 @@
1
- # Names only: copy to .env and fill in. Never put a real value in this file.
2
- # A blank value counts as unset. NODE_ENV is set by tooling, never here.
1
+ # Names only: copy to .env and fill in. Never put a real value in this file. A blank value counts as unset. NODE_ENV is set by tooling, never here.
3
2
 
4
3
  # Public URL of this deployment (default http://localhost:3000; on Vercel, derived from its domain when unset)
5
4
  APP_URL=
@@ -4,22 +4,13 @@ import type { Mailer } from "../../mail/index.ts";
4
4
  import type { AuthProvider } from "../types.ts";
5
5
  import type { AuthTables } from "./tables.ts";
6
6
  /**
7
- * The self-hosted provider: Better Auth running in the app, over the app's own database. Users,
8
- * sessions, linked accounts and magic-link tokens live in the four tables of `./tables.ts`; who may
9
- * sign in is managed by `./users.ts`. This module only configures Better Auth and adapts it to
10
- * `AuthProvider`.
7
+ * The self-hosted provider: Better Auth running in the app, over the app's own database. Users, sessions, linked accounts and magic-link tokens live in the four tables of `./tables.ts`; who may sign in is managed by `./users.ts`. This module only configures Better Auth and adapts it to `AuthProvider`.
11
8
  *
12
9
  * Invite-only throughout: no sign-in path creates a user. Off unless the app opts in —
13
- * - `emailAndPassword`: passwords, for an app that keeps them. Sign-up is forced off, and
14
- * the HTTP password routes stay unserved (`createAuth`'s handler answers 404 for sign-in/email,
15
- * change-password and verify-password): the app calls `provider.instance.api.signInEmail /
16
- * setPassword / changePassword / verifyPassword` from its own server action, behind a budget of
17
- * its own.
10
+ * - `emailAndPassword`: passwords, for an app that keeps them. Sign-up is forced off, and the HTTP password routes stay unserved (`createAuth`'s handler answers 404 for sign-in/email, change-password and verify-password): the app calls `provider.instance.api.signInEmail / setPassword / changePassword / verifyPassword` from its own server action, behind a budget of its own.
18
11
  * Deliberately absent —
19
- * - the generic OAuth plugin: it registers its providers as first-class social sign-in providers,
20
- * reachable through /sign-in/social and /sign-in/oauth2, outside the Google settings below;
21
- * - Better Auth's `admin()` plugin: it serves /api/auth/admin/* (impersonate a user, set a role,
22
- * remove or create a user) that would bypass the last-admin rule. `users.ts` is the admin API;
12
+ * - the generic OAuth plugin: it registers its providers as first-class social sign-in providers, reachable through /sign-in/social and /sign-in/oauth2, outside the Google settings below;
13
+ * - Better Auth's `admin()` plugin: it serves /api/auth/admin/* (impersonate a user, set a role, remove or create a user) that would bypass the last-admin rule. `users.ts` is the admin API;
23
14
  * - `session.cookieCache`: a session cached in a cookie would outlive the user's removal.
24
15
  */
25
16
  export type BetterAuthProviderOptions = {
@@ -40,8 +31,7 @@ export type BetterAuthProviderOptions = {
40
31
  /** How long a sign-in link works. Defaults to 15 minutes. */
41
32
  magicLinkTtlSeconds?: number;
42
33
  /**
43
- * Passwords, for an app that keeps one: enables Better Auth's email and password with sign-up
44
- * forced off. Reached only in-process, through `instance.api`; never over HTTP. Omit for none.
34
+ * Passwords, for an app that keeps one: enables Better Auth's email and password with sign-up forced off. Reached only in-process, through `instance.api`; never over HTTP. Omit for none.
45
35
  */
46
36
  emailAndPassword?: {
47
37
  minPasswordLength?: number;
@@ -51,8 +41,7 @@ export type BetterAuthProviderOptions = {
51
41
  /** The Better Auth instance behind the provider, for in-process calls (`instance.api.*`). */
52
42
  export type BetterAuthInstance = ReturnType<typeof createInstance>;
53
43
  /**
54
- * The provider, plus the Better Auth instance behind it. `instance` is not part of `AuthProvider`:
55
- * it is for an app's own server actions (a password sign-in), which keep their own budget.
44
+ * The provider, plus the Better Auth instance behind it. `instance` is not part of `AuthProvider`: it is for an app's own server actions (a password sign-in), which keep their own budget.
56
45
  */
57
46
  export type BetterAuthProvider = AuthProvider & {
58
47
  readonly instance: BetterAuthInstance;
@@ -110,8 +110,7 @@ function createInstance(opts) {
110
110
  google: {
111
111
  clientId: opts.google.clientId,
112
112
  clientSecret: opts.google.clientSecret,
113
- // Google never creates a user: an email nobody added is refused with
114
- // `signup_disabled`.
113
+ // Google never creates a user: an email nobody added is refused with `signup_disabled`.
115
114
  disableImplicitSignUp: true,
116
115
  disableSignUp: true,
117
116
  },
@@ -119,30 +118,18 @@ function createInstance(opts) {
119
118
  }
120
119
  : {}),
121
120
  account: {
122
- // The first Google sign-in for an added email attaches a Google `account` row to that user —
123
- // only when Google reports the email verified. Google is deliberately NOT a trusted
124
- // provider: trusting it would skip that check and let an unverified Google address claim
125
- // an added user. Refused, it lands on `/sign-in?error=account_not_linked`. Linking also
126
- // requires the Google email to equal the user's (`allowDifferentEmails` stays off).
121
+ // The first Google sign-in for an added email attaches a Google `account` row to that user — only when Google reports the email verified. Google is deliberately NOT a trusted provider: trusting it would skip that check and let an unverified Google address claim an added user. Refused, it lands on `/sign-in?error=account_not_linked`. Linking also requires the Google email to equal the user's (`allowDifferentEmails` stays off).
127
122
  accountLinking: { enabled: true },
128
- // Google signs people in; the app never calls Google for them, so its tokens are not kept
129
- // (see `databaseHooks.account`). Nothing to refresh on sign-in either.
123
+ // Google signs people in; the app never calls Google for them, so its tokens are not kept (see `databaseHooks.account`). Nothing to refresh on sign-in either.
130
124
  updateAccountOnSignIn: false,
131
125
  },
132
126
  user: {
133
127
  modelName: userModel,
134
- // `role` is a column Better Auth reads and returns but never takes from a caller
135
- // (`input: false`): only ./users.ts sets it.
128
+ // `role` is a column Better Auth reads and returns but never takes from a caller (`input: false`): only ./users.ts sets it.
136
129
  additionalFields: {
137
130
  role: { type: "string", required: false, input: false, defaultValue: "user" },
138
131
  },
139
- // The backstop: no OAuth sign-in ever creates a user. In 1.7.6 the id-token path of
140
- // /sign-in/social honoured a caller's `requestSignUp: true` over `disableImplicitSignUp`,
141
- // and read only `provider.disableSignUp` (a property Google's provider never sets) —
142
- // Google's setting lives in `provider.options.disableSignUp` — so without this, anyone
143
- // could POST their own Google id token and get a user. 1.7.7 fixed that by also reading
144
- // `provider.options?.disableSignUp`; `requestSignUp` still overrides `disableImplicitSignUp`
145
- // by design. Kept as defence in depth: it runs inside createUser, whatever route got there.
132
+ // The backstop: no OAuth sign-in ever creates a user. In 1.7.6 the id-token path of /sign-in/social honoured a caller's `requestSignUp: true` over `disableImplicitSignUp`, and read only `provider.disableSignUp` (a property Google's provider never sets) — Google's setting lives in `provider.options.disableSignUp` — so without this, anyone could POST their own Google id token and get a user. 1.7.7 fixed that by also reading `provider.options?.disableSignUp`; `requestSignUp` still overrides `disableImplicitSignUp` by design. Kept as defence in depth: it runs inside createUser, whatever route got there.
146
133
  validateUserInfo: async ({ source }) => source.method === "oauth" && source.action === "create-user"
147
134
  ? { error: "signup_disabled", errorDescription: "signup disabled" }
148
135
  : undefined,
@@ -153,22 +140,18 @@ function createInstance(opts) {
153
140
  updateAge: DAY, // refreshed on use once older than a day
154
141
  },
155
142
  databaseHooks: {
156
- // Better Auth stores no third-party API token (security rule 7): a provider's access,
157
- // refresh and id tokens are dropped before every account write.
143
+ // Better Auth stores no third-party API token (security rule 7): a provider's access, refresh and id tokens are dropped before every account write.
158
144
  account: {
159
145
  create: { before: async (row) => ({ data: withoutTokens(row) }) },
160
146
  update: { before: async (row) => ({ data: withoutTokens(row) }) },
161
147
  },
162
148
  },
163
149
  advanced: {
164
- // `appUser.id` is a uuid column, and app tables' foreign keys point at it. Generated here for
165
- // all four tables: Better Auth's `"uuid"` setting leaves it to a database default, which the
166
- // text ids of `session`, `account` and `verification` do not have.
150
+ // `appUser.id` is a uuid column, and app tables' foreign keys point at it. Generated here for all four tables: Better Auth's `"uuid"` setting leaves it to a database default, which the text ids of `session`, `account` and `verification` do not have.
167
151
  database: { generateId: () => randomUUID() },
168
152
  defaultCookieAttributes: {
169
153
  httpOnly: true,
170
- // A magic link is a top-level navigation from a mail client; `strict` would drop the
171
- // session on that first request.
154
+ // A magic link is a top-level navigation from a mail client; `strict` would drop the session on that first request.
172
155
  sameSite: "lax",
173
156
  path: "/",
174
157
  secure: opts.baseURL.startsWith("https://"),
@@ -180,13 +163,10 @@ function createInstance(opts) {
180
163
  expiresIn: ttlSeconds, // and single use
181
164
  // There is no public sign-up: a user row is added out of band (./users.ts).
182
165
  disableSignUp: true,
183
- // The token is stored hashed, so a copy of the database (every dev branch is one) holds
184
- // no link that works.
166
+ // The token is stored hashed, so a copy of the database (every dev branch is one) holds no link that works.
185
167
  storeToken: "hashed",
186
168
  sendMagicLink: async ({ email, url }, ctx) => {
187
- // The plugin calls this for EVERY address and then answers 200 either way, so the
188
- // enumeration guard lives here: an unknown address is sent nothing and looks identical
189
- // to a known one. Resolved through Better Auth's own adapter, not a query in this layer.
169
+ // The plugin calls this for EVERY address and then answers 200 either way, so the enumeration guard lives here: an unknown address is sent nothing and looks identical to a known one. Resolved through Better Auth's own adapter, not a query in this layer.
190
170
  const existing = await ctx?.context.internalAdapter.findUserByEmail(normaliseEmail(email));
191
171
  if (!existing?.user)
192
172
  return;
@@ -217,9 +197,7 @@ function withoutTokens(row) {
217
197
  return copy;
218
198
  }
219
199
  /**
220
- * Runs a Better Auth call. A refusal says nothing about the address (every 4xx and 5xx is
221
- * `unavailable`). The log line carries the status and message, never the address the caller typed
222
- * (the mailer redacts addresses from a Resend refusal).
200
+ * Runs a Better Auth call. A refusal says nothing about the address (every 4xx and 5xx is `unavailable`). The log line carries the status and message, never the address the caller typed (the mailer redacts addresses from a Resend refusal).
223
201
  */
224
202
  async function attempt(what, call) {
225
203
  try {
@@ -1,23 +1,16 @@
1
1
  import { sql } from "drizzle-orm";
2
2
  import { boolean, check, pgTable, text, timestamp, uuid } from "drizzle-orm/pg-core";
3
3
  /**
4
- * Self-hosted Better Auth's four tables, as Drizzle definitions the app re-exports from its own
5
- * schema so drizzle-kit generates them into the app's one migration history. The package never
6
- * migrates anything itself.
4
+ * Self-hosted Better Auth's four tables, as Drizzle definitions the app re-exports from its own schema so drizzle-kit generates them into the app's one migration history. The package never migrates anything itself.
7
5
  *
8
- * **One user table.** Better Auth's user model *is* the app's user table (`app_user`, or the name
9
- * the app passes, such as `user`): there is no second identity table to keep in sync, so removing
10
- * a person cannot leave a sign-in-able account behind. App tables reference `appUser.id`, a uuid.
11
- * `role` is declared to Better Auth as an additional field it never takes from a caller, and is set
12
- * only by `users.ts`.
6
+ * **One user table.** Better Auth's user model *is* the app's user table (`app_user`, or the name the app passes, such as `user`): there is no second identity table to keep in sync, so removing a person cannot leave a sign-in-able account behind. App tables reference `appUser.id`, a uuid. `role` is declared to Better Auth as an additional field it never takes from a caller, and is set only by `users.ts`.
13
7
  *
14
8
  * Better Auth owns exactly these columns: no app column is ever added to them.
15
9
  */
16
10
  const createdAt = () => timestamp("created_at", { withTimezone: true }).notNull().defaultNow();
17
11
  const updatedAt = () => timestamp("updated_at", { withTimezone: true }).notNull().defaultNow();
18
12
  export function authTables(opts = {}) {
19
- // The name stays a literal type ("app_user", or the one the app passes, such as "user"): Drizzle keys a joined select's
20
- // result by table name, so a plain `string` would merge every joined table's columns into one.
13
+ // The name stays a literal type ("app_user", or the one the app passes, such as "user"): Drizzle keys a joined select's result by table name, so a plain `string` would merge every joined table's columns into one.
21
14
  const userTable = (opts.userTable ?? "app_user");
22
15
  const appUser = pgTable(userTable, {
23
16
  id: uuid("id").primaryKey().defaultRandom(),
@@ -29,8 +22,7 @@ export function authTables(opts = {}) {
29
22
  updatedAt: updatedAt(),
30
23
  role: text("role").notNull().default("user"),
31
24
  }, (t) => [
32
- // Every user has an email, trimmed and lower-cased, so the unique constraint is also
33
- // case-insensitive. `users.add` normalises; this refuses any other path that does not.
25
+ // Every user has an email, trimmed and lower-cased, so the unique constraint is also case-insensitive. `users.add` normalises; this refuses any other path that does not.
34
26
  check(`${userTable}_email_normalised`, sql `${t.email} = lower(btrim(${t.email}))`),
35
27
  ]);
36
28
  const session = pgTable("session", {
@@ -52,8 +44,7 @@ export function authTables(opts = {}) {
52
44
  userId: uuid("user_id")
53
45
  .notNull()
54
46
  .references(() => appUser.id, { onDelete: "cascade" }),
55
- // Better Auth's columns for a provider's tokens. The provider never fills them: Google is used
56
- // to sign in, not to call Google (index.ts strips them before every write).
47
+ // Better Auth's columns for a provider's tokens. The provider never fills them: Google is used to sign in, not to call Google (index.ts strips them before every write).
57
48
  accessToken: text("access_token"),
58
49
  refreshToken: text("refresh_token"),
59
50
  idToken: text("id_token"),
@@ -2,14 +2,9 @@ import type { NodePgDatabase } from "drizzle-orm/node-postgres";
2
2
  import type { AuthProvider } from "../types.ts";
3
3
  import type { AuthTables } from "./tables.ts";
4
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.
5
+ * Who gets in. Sign-in never creates a user, so a person exists because an admin added their email here (from a dashboard, or `stack user:create`); they then sign in with a magic link or Google like anyone else. Removing a person deletes their user row, sessions and accounts in one transaction, so a cookie they still hold stops working on their next request.
9
6
  *
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.
7
+ * The app always has an admin once it has one: any change that would leave none is refused inside the transaction that holds a lock on the admin rows, so two concurrent demotions cannot both succeed.
13
8
  */
14
9
  export declare class DuplicateUserError extends Error {
15
10
  constructor(email: string);
@@ -2,14 +2,9 @@ import { randomUUID } from "node:crypto";
2
2
  import { asc, eq } from "drizzle-orm";
3
3
  import { z } from "zod";
4
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.
5
+ * Who gets in. Sign-in never creates a user, so a person exists because an admin added their email here (from a dashboard, or `stack user:create`); they then sign in with a magic link or Google like anyone else. Removing a person deletes their user row, sessions and accounts in one transaction, so a cookie they still hold stops working on their next request.
9
6
  *
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.
7
+ * The app always has an admin once it has one: any change that would leave none is refused inside the transaction that holds a lock on the admin rows, so two concurrent demotions cannot both succeed.
13
8
  */
14
9
  export class DuplicateUserError extends Error {
15
10
  constructor(email) {
@@ -98,8 +93,7 @@ export function createUsers(db, tables) {
98
93
  await lockTarget(tx, userId);
99
94
  if (admins.includes(userId) && admins.length <= 1)
100
95
  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.
96
+ // The foreign keys cascade these too; deleting them by name keeps the guarantee — no session or linked account outlives the person — independent of the app's constraints.
103
97
  await tx.delete(session).where(eq(session.userId, userId));
104
98
  await tx.delete(account).where(eq(account.userId, userId));
105
99
  await tx.delete(appUser).where(eq(appUser.id, userId));
@@ -1,20 +1,13 @@
1
1
  import type { AuthProvider, AuthResult, Session } from "./types.ts";
2
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.
3
+ * The app's one auth object: `export const auth = createAuth({ provider })` in `src/lib/auth.ts`, and every session read, sign-in and sign-out goes through it. Which provider runs sign-in is invisible past this point.
6
4
  *
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()`.
5
+ * The sign-in functions are plain async functions that read the request through `next/headers`; the app's thin `actions.ts` marks them `"use server"` (the package ships no server-action module). They must run as server actions: that is where Next lets a cookie be set, and the provider sets its cookies there — Better Auth's `nextCookies()` writes each `Set-Cookie` of an in-process call (Google's signed state cookie, sign-out's cleared session) into `cookies()`.
12
6
  */
13
7
  export type CreateAuthOptions = {
14
8
  provider: AuthProvider;
15
9
  /**
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.
10
+ * Sign-in requests allowed per client address per hour (default 10). Spent by every magic-link request and Google start, whatever the address typed. `Infinity` turns the limit off.
18
11
  */
19
12
  rateLimitPerHour?: number;
20
13
  /** Proxies in front of the app that append to `X-Forwarded-For` (default 0, as on Vercel). */
@@ -24,19 +17,15 @@ export type StackAuth = {
24
17
  /** The session, or null. Reads `headers` when given (route handlers), else the request's. */
25
18
  getSession(headers?: Headers): Promise<Session | null>;
26
19
  /**
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.
20
+ * The session, or a redirect to `/sign-in?next=<nextPath>`. A server layout cannot see the request path in Next 16, so the caller supplies it; the proxy redirects with the real one.
29
21
  */
30
22
  requireSession(nextPath?: string): Promise<Session>;
31
23
  /**
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.
24
+ * An admin's session, or the not-found page: a signed-in user who is not an admin gets the same 404 a missing page does, so admin pages do not announce themselves. Pages only — `notFound()` throws, so API routes check `session.user.role` and answer the envelope instead.
35
25
  */
36
26
  requireAdmin(): Promise<Session>;
37
27
  /**
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.
28
+ * Sends a sign-in link. `{ ok: true }` for every address, known or not (the provider sends nothing to an address nobody added). `rate_limited` once this caller's budget is spent.
40
29
  */
41
30
  requestMagicLink(input: {
42
31
  email: string;
@@ -3,25 +3,15 @@ import { rateLimit } from "../http/rate-limit.js";
3
3
  import { safeNext } from "./safe-next.js";
4
4
  const SIGN_IN_PATH = "/sign-in";
5
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.
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.
10
7
  */
11
8
  const navigation = () => import("next/navigation");
12
9
  /**
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.
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.
16
11
  */
17
12
  const SIGN_IN_BUDGET_PATH = "/api/auth/sign-in/magic-link";
18
13
  /**
19
- * Better Auth's password routes. Passwords are off unless an app opts in with
20
- * `betterAuthProvider({ emailAndPassword })`; 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).
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).
25
15
  */
26
16
  const NOT_SERVED = new Set([
27
17
  "/api/auth/sign-in/email",
@@ -59,8 +49,7 @@ export function createAuth(opts) {
59
49
  return (await navigation()).notFound();
60
50
  return current;
61
51
  },
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.
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.
64
53
  async requestMagicLink(input) {
65
54
  const next = safeNext(input.next);
66
55
  if (await budgetSpent())
@@ -96,10 +85,7 @@ export function createAuth(opts) {
96
85
  };
97
86
  }
98
87
  /**
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.
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.
103
89
  */
104
90
  function routePath(req) {
105
91
  const raw = new URL(req.url).pathname;
@@ -1,8 +1,6 @@
1
1
  import { type NextRequest, NextResponse } from "next/server.js";
2
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.
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.
6
4
  */
7
5
  export declare const proxyMatcher: string[];
8
6
  export type SessionProxyOptions = {
@@ -1,32 +1,19 @@
1
1
  import { NextResponse } from "next/server.js";
2
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.
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.
7
4
  *
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.
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.
12
6
  */
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.
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.
15
8
  const SESSION_COOKIES = ["better-auth.session_token", "__Secure-better-auth.session_token"];
16
9
  /**
17
- * Paths the proxy never redirects, matching what `proxyMatcher` leaves out — so the proxy is right
18
- * even when an app widens its matcher.
10
+ * Paths the proxy never redirects, matching what `proxyMatcher` leaves out — so the proxy is right even when an app widens its matcher.
19
11
  *
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.
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.
24
13
  */
25
14
  const EXCLUDED = /^\/(?:api(?:\/|$)|sign-in(?:\/|$)|_next\/|favicon\.ico$|.*\.(?:svg|png|jpg|jpeg|gif|webp|ico|txt|xml|webmanifest)$)/;
26
15
  /**
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.
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.
30
17
  */
31
18
  export const proxyMatcher = [
32
19
  "/((?!api(?:/|$)|sign-in(?:/|$)|_next/|favicon\\.ico$|.*\\.(?:svg|png|jpg|jpeg|gif|webp|ico|txt|xml|webmanifest)$).*)",
@@ -1,17 +1,11 @@
1
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.
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.
5
3
  *
6
4
  * Kept: a string starting with a single `/`. Refused, as well as anything that is not a string:
7
5
  * - `//host` and `/\host`: browsers read both as protocol-relative URLs to another host;
8
6
  * - any backslash: the URL parser turns it into `/`;
9
7
  * - control characters: the URL parser strips tabs and newlines, so `/\t/host` becomes `//host`;
10
8
  * - `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.
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.
16
10
  */
17
11
  export declare function safeNext(raw: unknown, fallback?: string): string;
@@ -1,18 +1,12 @@
1
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.
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.
5
3
  *
6
4
  * Kept: a string starting with a single `/`. Refused, as well as anything that is not a string:
7
5
  * - `//host` and `/\host`: browsers read both as protocol-relative URLs to another host;
8
6
  * - any backslash: the URL parser turns it into `/`;
9
7
  * - control characters: the URL parser strips tabs and newlines, so `/\t/host` becomes `//host`;
10
8
  * - `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.
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.
16
10
  */
17
11
  export function safeNext(raw, fallback = "/") {
18
12
  if (typeof raw !== "string")
@@ -1,6 +1,5 @@
1
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.
2
+ * The provider-agnostic auth types. An app only ever sees these: whichever provider runs sign-in, a session's user is an `app_user` row, and a sign-in answers with a short, normalised code.
4
3
  */
5
4
  /** The two roles. Granted by an admin, never assumed: a user with no admin role reads as `user`. */
6
5
  export type Role = "admin" | "user";
@@ -1,5 +1,4 @@
1
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.
2
+ * The provider-agnostic auth types. An app only ever sees these: whichever provider runs sign-in, a session's user is an `app_user` row, and a sign-in answers with a short, normalised code.
4
3
  */
5
4
  export {};
@@ -19,9 +19,7 @@ export type LocalDatabase = {
19
19
  stop(): Promise<void>;
20
20
  };
21
21
  /**
22
- * Everything the CLI touches outside its own process, so a test can replace it. Only the entry
23
- * point reads `process.env`: it passes it in as `env`, and nothing below reads it directly.
24
- * `exec` runs a program with an argument array, never a shell string.
22
+ * Everything the CLI touches outside its own process, so a test can replace it. Only the entry point reads `process.env`: it passes it in as `env`, and nothing below reads it directly. `exec` runs a program with an argument array, never a shell string.
25
23
  */
26
24
  export type CliDeps = {
27
25
  env: Env;
package/dist/cli/index.js CHANGED
@@ -100,8 +100,7 @@ export function exec(command, args, options = {}) {
100
100
  });
101
101
  }
102
102
  /**
103
- * Whether Node is running this file as its program, through any symlink (node_modules/.bin).
104
- * Not `import.meta.main`: that needs Node 24.2, and the package accepts any 24.x.
103
+ * Whether Node is running this file as its program, through any symlink (node_modules/.bin). Not `import.meta.main`: that needs Node 24.2, and the package accepts any 24.x.
105
104
  */
106
105
  function isEntryPoint() {
107
106
  const program = process.argv[1];
@@ -11,10 +11,7 @@ export type Branch = {
11
11
  export declare const SEED_NEXT = "seed-next";
12
12
  export declare function projectId(env: Env): string;
13
13
  /**
14
- * Refuses a dev branch name that is not a dev branch: production (whatever this project calls its
15
- * default branch, and the name `production` itself), the shared `seed` and `preview`, and `seed-next`
16
- * (the seed being built, which may briefly hold production's data). One check
17
- * for every command that uses your dev branch: with-neon, dev-setup and user:create.
14
+ * Refuses a dev branch name that is not a dev branch: production (whatever this project calls its default branch, and the name `production` itself), the shared `seed` and `preview`, and `seed-next` (the seed being built, which may briefly hold production's data). One check for every command that uses your dev branch: with-neon, dev-setup and user:create.
18
15
  */
19
16
  export declare function assertDevBranchName(name: string, production: Branch): void;
20
17
  /** `dev/<os user>` unless NEON_DEV_BRANCH names another. */
@@ -23,25 +20,19 @@ export declare function findBranch(cli: Cli, name: string): Promise<Branch | und
23
20
  /** Production: the project's default branch (Neon's `default` flag), not a branch name. */
24
21
  export declare function defaultBranch(branches: Branch[]): Branch;
25
22
  /**
26
- * What `.env` used to carry for local work: `branch`'s URLs, and the host of production (the
27
- * default branch; `production` when the caller already has it, else listed).
23
+ * What `.env` used to carry for local work: `branch`'s URLs, and the host of production (the default branch; `production` when the caller already has it, else listed).
28
24
  */
29
25
  export declare function branchEnv(cli: Cli, branch: string, production?: Branch): Promise<Record<string, string>>;
30
26
  /** The migrations, run against whatever database `env` names, through the direct endpoint. */
31
27
  export declare function migrate(cli: Cli, env: Env): Promise<number>;
32
28
  /**
33
- * `stack with-neon <command> [args]` — runs a local command against your Neon dev branch with no
34
- * `.env`: the connection strings and production's host come from the Neon CLI on every run.
29
+ * `stack with-neon <command> [args]` — runs a local command against your Neon dev branch with no `.env`: the connection strings and production's host come from the Neon CLI on every run.
35
30
  *
36
- * Steps aside, and runs the command untouched, when something else already says where the database
37
- * is: DATABASE_URL in the environment (Vercel, an e2e run, a local Postgres), ENV_FILE
38
- * (a deliberate production command). A `.env` never decides: what this sets wins over it, in Next
39
- * and in `loadEnvFile` alike.
31
+ * Steps aside, and runs the command untouched, when something else already says where the database is: DATABASE_URL in the environment (Vercel, an e2e run, a local Postgres), ENV_FILE (a deliberate production command). A `.env` never decides: what this sets wins over it, in Next and in `loadEnvFile` alike.
40
32
  */
41
33
  export declare function withNeon(cli: Cli, [command, ...args]: string[]): Promise<number>;
42
34
  /**
43
- * Your dev branch's `branchEnv`, as `with-neon` hands it to a command; nothing (`{}`) when
44
- * DATABASE_URL or ENV_FILE already says where the database is. Refuses the default branch.
35
+ * Your dev branch's `branchEnv`, as `with-neon` hands it to a command; nothing (`{}`) when DATABASE_URL or ENV_FILE already says where the database is. Refuses the default branch.
45
36
  */
46
37
  export declare function devBranchEnv(cli: Cli): Promise<Record<string, string>>;
47
38
  /**
@@ -49,47 +40,23 @@ export declare function devBranchEnv(cli: Cli): Promise<Record<string, string>>;
49
40
  */
50
41
  export declare function previewBranchEnv(cli: Cli): Promise<Record<string, string>>;
51
42
  /**
52
- * `stack dev-setup` — once per developer: makes your Neon dev branch from `seed` (never from
53
- * production) if it does not exist yet (`dev/<os user>`, or NEON_DEV_BRANCH) and migrates it. Safe
54
- * to re-run. Sign-in needs nothing on the branch: Better Auth runs in the app, with a development
55
- * BETTER_AUTH_SECRET and magic links written to the sink file. There is no `.env` to write:
56
- * `stack with-neon` reads the branch from the Neon CLI on every command.
43
+ * `stack dev-setup` — once per developer: makes your Neon dev branch from `seed` (never from production) if it does not exist yet (`dev/<os user>`, or NEON_DEV_BRANCH) and migrates it. Safe to re-run. Sign-in needs nothing on the branch: Better Auth runs in the app, with a development BETTER_AUTH_SECRET and magic links written to the sink file. There is no `.env` to write: `stack with-neon` reads the branch from the Neon CLI on every command.
57
44
  */
58
45
  export declare function devSetup(cli: Cli): Promise<number>;
59
46
  /**
60
- * Schemas Neon's own services install, which hold functions and settings rather than anyone's rows:
61
- * `auth` is the pg_session_jwt extension the Data API installs (Neon: "do not install this extension
62
- * manually"), `pgrst` is the Data API's PostgREST configuration. Left in place so the branch keeps
63
- * working like any other. Neon Auth's `neon_auth` is *not* here: it holds users.
47
+ * Schemas Neon's own services install, which hold functions and settings rather than anyone's rows: `auth` is the pg_session_jwt extension the Data API installs (Neon: "do not install this extension manually"), `pgrst` is the Data API's PostgREST configuration. Left in place so the branch keeps working like any other. Neon Auth's `neon_auth` is *not* here: it holds users.
64
48
  */
65
49
  export declare const NEON_SCHEMAS: readonly string[];
66
50
  /**
67
- * Empties a database down to an empty `public`: drops every schema but Postgres's own
68
- * (`pg_catalog`, `pg_toast*`, `information_schema`, any `pg_*`) and Neon's service schemas, with
69
- * everything in them — tables, rows, drizzle's journal, Neon Auth's users. Then the migrations
70
- * run from nothing, as on a new database. A schema-only branch needs this as much as a full copy:
71
- * it keeps drizzle's journal *table* but not its rows, so migrate would re-run 0000 into tables
72
- * that already exist. Large objects belong to the database rather than to a schema, so no drop
73
- * removes them: every one is unlinked too.
51
+ * Empties a database down to an empty `public`: drops every schema but Postgres's own (`pg_catalog`, `pg_toast*`, `information_schema`, any `pg_*`) and Neon's service schemas, with everything in them — tables, rows, drizzle's journal, Neon Auth's users. Then the migrations run from nothing, as on a new database. A schema-only branch needs this as much as a full copy: it keeps drizzle's journal *table* but not its rows, so migrate would re-run 0000 into tables that already exist. Large objects belong to the database rather than to a schema, so no drop removes them: every one is unlinked too.
74
52
  *
75
- * Neon's schemas are kept by name, so first it checks they hold what Neon puts there: functions and
76
- * settings, no rows. A table, partitioned table, materialized view, sequence or foreign table in
77
- * one (an app's own `auth.accounts`, say) would carry production's rows into the seed, so it
78
- * refuses before dropping anything.
53
+ * Neon's schemas are kept by name, so first it checks they hold what Neon puts there: functions and settings, no rows. A table, partitioned table, materialized view, sequence or foreign table in one (an app's own `auth.accounts`, say) would carry production's rows into the seed, so it refuses before dropping anything.
79
54
  */
80
55
  export declare function emptyDatabase(sql: (statement: string) => Promise<Record<string, unknown>[]>): Promise<string[]>;
81
56
  /**
82
- * `stack neon seed` — (re)creates the `seed` branch: exactly the app's migrations plus its seed
83
- * rows, and none of production's data. Cuts it from production (the project's default branch) as
84
- * Neon's `--schema-only` branch (a normal branch where that is unsupported), empties it of every
85
- * non-system schema either way (`emptyDatabase`), migrates it from nothing and runs the app's
86
- * `db/seed.ts`: `export default async function seed(db)`.
57
+ * `stack neon seed` — (re)creates the `seed` branch: exactly the app's migrations plus its seed rows, and none of production's data. Cuts it from production (the project's default branch) as Neon's `--schema-only` branch (a normal branch where that is unsupported), empties it of every non-system schema either way (`emptyDatabase`), migrates it from nothing and runs the app's `db/seed.ts`: `export default async function seed(db)`.
87
58
  *
88
- * The new seed is built as `seed-next` and takes the name `seed` only once it is clean, so a
89
- * failure part-way never leaves a branch holding production's data under the name every dev and
90
- * preview branch is cut from; `seed-next` is deleted on any failure. Neon will not delete a branch
91
- * that has children, so a seed with dev/preview branches on it is refused up front: remove them
92
- * yourself (this never deletes them).
59
+ * The new seed is built as `seed-next` and takes the name `seed` only once it is clean, so a failure part-way never leaves a branch holding production's data under the name every dev and preview branch is cut from; `seed-next` is deleted on any failure. Neon will not delete a branch that has children, so a seed with dev/preview branches on it is refused up front: remove them yourself (this never deletes them).
93
60
  */
94
61
  export declare function neonSeed(cli: Cli): Promise<number>;
95
62
  /**