@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,316 @@
1
+ import type { NodePgDatabase } from "drizzle-orm/node-postgres";
2
+ import { z } from "zod";
3
+ import type { Mailer } from "../../mail/index.ts";
4
+ import type { AuthProvider } from "../types.ts";
5
+ import type { AuthTables } from "./tables.ts";
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`.
11
+ *
12
+ * Invite-only throughout: no sign-in path creates a user. Off unless the app opts in —
13
+ * - `emailAndPassword`: passwords, for an app that keeps one (cc does). 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.
18
+ * 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;
23
+ * - `session.cookieCache`: a session cached in a cookie would outlive the user's removal.
24
+ */
25
+ export type BetterAuthProviderOptions = {
26
+ db: NodePgDatabase<any>;
27
+ tables: AuthTables;
28
+ /** The app's public origin, e.g. `https://app.example.com`. Cookies are `Secure` when https. */
29
+ baseURL: string;
30
+ /** Better Auth's signing secret (32+ random characters). */
31
+ secret: string;
32
+ mailer: Mailer;
33
+ /** Sign in with Google, for users already added. Omit to offer magic links only. */
34
+ google?: {
35
+ clientId: string;
36
+ clientSecret: string;
37
+ };
38
+ /** Better Auth's per-caller limits on /api/auth/*. On unless turned off. */
39
+ rateLimit?: boolean;
40
+ /** How long a sign-in link works. Defaults to 15 minutes. */
41
+ magicLinkTtlSeconds?: number;
42
+ /**
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.
45
+ */
46
+ emailAndPassword?: {
47
+ minPasswordLength?: number;
48
+ maxPasswordLength?: number;
49
+ };
50
+ };
51
+ /** The Better Auth instance behind the provider, for in-process calls (`instance.api.*`). */
52
+ export type BetterAuthInstance = ReturnType<typeof createInstance>;
53
+ /**
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.
56
+ */
57
+ export type BetterAuthProvider = AuthProvider & {
58
+ readonly instance: BetterAuthInstance;
59
+ };
60
+ export declare function betterAuthProvider(opts: BetterAuthProviderOptions): BetterAuthProvider;
61
+ declare function createInstance(opts: BetterAuthProviderOptions): import("better-auth").Auth<{
62
+ account: {
63
+ accountLinking: {
64
+ enabled: true;
65
+ };
66
+ updateAccountOnSignIn: false;
67
+ };
68
+ user: {
69
+ modelName: string;
70
+ additionalFields: {
71
+ role: {
72
+ type: "string";
73
+ required: false;
74
+ input: false;
75
+ defaultValue: string;
76
+ };
77
+ };
78
+ validateUserInfo: ({ source }: {
79
+ user: Partial<import("better-auth").User> & Record<string, unknown>;
80
+ source: import("better-auth").ValidateUserInfoSource;
81
+ }) => Promise<{
82
+ error: string;
83
+ errorDescription: string;
84
+ } | undefined>;
85
+ };
86
+ session: {
87
+ expiresIn: number;
88
+ updateAge: number;
89
+ };
90
+ databaseHooks: {
91
+ account: {
92
+ create: {
93
+ before: (row: {
94
+ id: string;
95
+ createdAt: Date;
96
+ updatedAt: Date;
97
+ providerId: string;
98
+ accountId: string;
99
+ userId: string;
100
+ accessToken?: string | null | undefined;
101
+ refreshToken?: string | null | undefined;
102
+ idToken?: string | null | undefined;
103
+ accessTokenExpiresAt?: Date | null | undefined;
104
+ refreshTokenExpiresAt?: Date | null | undefined;
105
+ scope?: string | null | undefined;
106
+ password?: string | null | undefined;
107
+ }) => Promise<{
108
+ data: {
109
+ id: string;
110
+ createdAt: Date;
111
+ updatedAt: Date;
112
+ providerId: string;
113
+ accountId: string;
114
+ userId: string;
115
+ accessToken?: string | null | undefined;
116
+ refreshToken?: string | null | undefined;
117
+ idToken?: string | null | undefined;
118
+ accessTokenExpiresAt?: Date | null | undefined;
119
+ refreshTokenExpiresAt?: Date | null | undefined;
120
+ scope?: string | null | undefined;
121
+ password?: string | null | undefined;
122
+ };
123
+ }>;
124
+ };
125
+ update: {
126
+ before: (row: Partial<{
127
+ id: string;
128
+ createdAt: Date;
129
+ updatedAt: Date;
130
+ providerId: string;
131
+ accountId: string;
132
+ userId: string;
133
+ accessToken?: string | null | undefined;
134
+ refreshToken?: string | null | undefined;
135
+ idToken?: string | null | undefined;
136
+ accessTokenExpiresAt?: Date | null | undefined;
137
+ refreshTokenExpiresAt?: Date | null | undefined;
138
+ scope?: string | null | undefined;
139
+ password?: string | null | undefined;
140
+ }> & Record<string, unknown>) => Promise<{
141
+ data: Partial<{
142
+ id: string;
143
+ createdAt: Date;
144
+ updatedAt: Date;
145
+ providerId: string;
146
+ accountId: string;
147
+ userId: string;
148
+ accessToken?: string | null | undefined;
149
+ refreshToken?: string | null | undefined;
150
+ idToken?: string | null | undefined;
151
+ accessTokenExpiresAt?: Date | null | undefined;
152
+ refreshTokenExpiresAt?: Date | null | undefined;
153
+ scope?: string | null | undefined;
154
+ password?: string | null | undefined;
155
+ }> & Record<string, unknown>;
156
+ }>;
157
+ };
158
+ };
159
+ };
160
+ advanced: {
161
+ database: {
162
+ generateId: () => `${string}-${string}-${string}-${string}-${string}`;
163
+ };
164
+ defaultCookieAttributes: {
165
+ httpOnly: true;
166
+ sameSite: "lax";
167
+ path: string;
168
+ secure: boolean;
169
+ };
170
+ };
171
+ rateLimit: {
172
+ enabled: boolean;
173
+ };
174
+ plugins: [{
175
+ id: "magic-link";
176
+ version: string;
177
+ endpoints: {
178
+ signInMagicLink: import("better-auth").StrictEndpoint<"/sign-in/magic-link", {
179
+ method: "POST";
180
+ requireHeaders: true;
181
+ use: import("better-auth").Middleware<import("better-auth").MiddlewareOptions, (inputContext: import("better-auth").MiddlewareInputContext<import("better-auth").MiddlewareOptions>) => Promise<void>>[];
182
+ body: z.ZodObject<{
183
+ email: z.ZodEmail;
184
+ name: z.ZodOptional<z.ZodString>;
185
+ callbackURL: z.ZodOptional<z.ZodString>;
186
+ newUserCallbackURL: z.ZodOptional<z.ZodString>;
187
+ errorCallbackURL: z.ZodOptional<z.ZodString>;
188
+ metadata: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodAny>>;
189
+ }, z.core.$strip>;
190
+ metadata: {
191
+ openapi: {
192
+ operationId: string;
193
+ description: string;
194
+ responses: {
195
+ 200: {
196
+ description: string;
197
+ content: {
198
+ "application/json": {
199
+ schema: {
200
+ type: "object";
201
+ properties: {
202
+ status: {
203
+ type: string;
204
+ };
205
+ };
206
+ };
207
+ };
208
+ };
209
+ };
210
+ };
211
+ };
212
+ };
213
+ }, {
214
+ status: boolean;
215
+ }>;
216
+ magicLinkVerify: import("better-auth").StrictEndpoint<"/magic-link/verify", {
217
+ method: "GET";
218
+ query: z.ZodObject<{
219
+ token: z.ZodString;
220
+ callbackURL: z.ZodOptional<z.ZodString>;
221
+ errorCallbackURL: z.ZodOptional<z.ZodString>;
222
+ newUserCallbackURL: z.ZodOptional<z.ZodString>;
223
+ }, z.core.$strip>;
224
+ use: import("better-auth").Middleware<import("better-auth").MiddlewareOptions, (inputContext: import("better-auth").MiddlewareInputContext<import("better-auth").MiddlewareOptions>) => Promise<void>>[];
225
+ requireHeaders: true;
226
+ metadata: {
227
+ openapi: {
228
+ operationId: string;
229
+ description: string;
230
+ responses: {
231
+ 200: {
232
+ description: string;
233
+ content: {
234
+ "application/json": {
235
+ schema: {
236
+ type: "object";
237
+ properties: {
238
+ session: {
239
+ $ref: string;
240
+ };
241
+ user: {
242
+ $ref: string;
243
+ };
244
+ };
245
+ };
246
+ };
247
+ };
248
+ };
249
+ };
250
+ };
251
+ };
252
+ }, {
253
+ token: string;
254
+ user: {
255
+ id: string;
256
+ createdAt: Date;
257
+ updatedAt: Date;
258
+ email: string;
259
+ emailVerified: boolean;
260
+ name: string;
261
+ image?: string | null | undefined;
262
+ };
263
+ session: {
264
+ id: string;
265
+ createdAt: Date;
266
+ updatedAt: Date;
267
+ userId: string;
268
+ expiresAt: Date;
269
+ token: string;
270
+ ipAddress?: string | null | undefined;
271
+ userAgent?: string | null | undefined;
272
+ };
273
+ }>;
274
+ };
275
+ rateLimit: {
276
+ pathMatcher(path: string): boolean;
277
+ window: number;
278
+ max: number;
279
+ }[];
280
+ options: import("better-auth/plugins/magic-link").MagicLinkOptions;
281
+ }, {
282
+ id: "next-cookies";
283
+ version: string;
284
+ hooks: {
285
+ before: {
286
+ matcher(ctx: import("better-auth").HookEndpointContext): boolean;
287
+ handler: import("better-auth").Middleware<import("better-auth").MiddlewareOptions, (inputContext: import("better-auth").MiddlewareInputContext<import("better-auth").MiddlewareOptions>) => Promise<void>>;
288
+ }[];
289
+ after: {
290
+ matcher(ctx: import("better-auth").HookEndpointContext): true;
291
+ handler: import("better-auth").Middleware<import("better-auth").MiddlewareOptions, (inputContext: import("better-auth").MiddlewareInputContext<import("better-auth").MiddlewareOptions>) => Promise<void>>;
292
+ }[];
293
+ };
294
+ }];
295
+ socialProviders?: {
296
+ google: {
297
+ clientId: string;
298
+ clientSecret: string;
299
+ disableImplicitSignUp: true;
300
+ disableSignUp: true;
301
+ };
302
+ } | undefined;
303
+ baseURL: string;
304
+ secret: string;
305
+ database: (options: import("better-auth").BetterAuthOptions) => import("better-auth").DBAdapter<import("better-auth").BetterAuthOptions>;
306
+ emailAndPassword: {
307
+ maxPasswordLength?: number | undefined;
308
+ minPasswordLength?: number | undefined;
309
+ enabled: true;
310
+ disableSignUp: true;
311
+ } | {
312
+ enabled: false;
313
+ };
314
+ }>;
315
+ export { type AuthTables, authTables } from "./tables.ts";
316
+ export { DuplicateUserError, LastAdminError, UserNotFoundError } from "./users.ts";
@@ -0,0 +1,237 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { betterAuth } from "better-auth";
3
+ import { drizzleAdapter } from "better-auth/adapters/drizzle";
4
+ import { APIError } from "better-auth/api";
5
+ import { nextCookies } from "better-auth/next-js";
6
+ import { magicLink } from "better-auth/plugins/magic-link";
7
+ import { getTableName } from "drizzle-orm";
8
+ import { z } from "zod";
9
+ import { createUsers, normaliseEmail } from "./users.js";
10
+ const DAY = 60 * 60 * 24;
11
+ /** Where a refused link or Google sign-in lands, keeping where the person was going. */
12
+ const signInErrorURL = (next) => `/sign-in?next=${encodeURIComponent(next)}`;
13
+ export function betterAuthProvider(opts) {
14
+ const auth = createInstance(opts);
15
+ return {
16
+ instance: auth,
17
+ handler: (req) => auth.handler(req),
18
+ async getSession(headers) {
19
+ const current = await auth.api.getSession({ headers });
20
+ if (!current)
21
+ return null;
22
+ const { user } = current;
23
+ return {
24
+ user: {
25
+ id: user.id,
26
+ email: user.email,
27
+ name: user.name ?? null,
28
+ // Being admin is granted, never assumed.
29
+ role: user.role === "admin" ? "admin" : "user",
30
+ createdAt: user.createdAt,
31
+ },
32
+ expiresAt: current.session.expiresAt,
33
+ };
34
+ },
35
+ signIn: {
36
+ async magicLink(rawEmail, next) {
37
+ const email = normaliseEmail(rawEmail);
38
+ if (!z.email().safeParse(email).success)
39
+ return { ok: false, code: "invalid_email" };
40
+ return attempt("magic-link request", () => auth.api.signInMagicLink({
41
+ body: {
42
+ email,
43
+ callbackURL: next,
44
+ // A second open of a consumed link lands here, with `?error=`.
45
+ errorCallbackURL: signInErrorURL(next),
46
+ },
47
+ headers: new Headers(),
48
+ }));
49
+ },
50
+ async oauth(providerId, next) {
51
+ if (providerId !== "google" || !opts.google)
52
+ return { ok: false, code: "unavailable" };
53
+ let url;
54
+ const result = await attempt("google sign-in", async () => {
55
+ // Sets the signed state cookie that binds the flow to this browser (via nextCookies).
56
+ ({ url } = await auth.api.signInSocial({
57
+ body: {
58
+ provider: "google",
59
+ callbackURL: next,
60
+ errorCallbackURL: signInErrorURL(next),
61
+ disableRedirect: true,
62
+ },
63
+ }));
64
+ });
65
+ if (!result.ok)
66
+ return result;
67
+ return url ? { ok: true, redirect: url } : { ok: false, code: "unavailable" };
68
+ },
69
+ },
70
+ async signOut(headers) {
71
+ await auth.api.signOut({ headers });
72
+ },
73
+ users: createUsers(opts.db, opts.tables),
74
+ };
75
+ }
76
+ function createInstance(opts) {
77
+ const { db, tables, mailer } = opts;
78
+ const userModel = getTableName(tables.appUser);
79
+ const ttlSeconds = opts.magicLinkTtlSeconds ?? 60 * 15;
80
+ const ttlMinutes = Math.round(ttlSeconds / 60);
81
+ return betterAuth({
82
+ baseURL: opts.baseURL,
83
+ secret: opts.secret,
84
+ database: drizzleAdapter(db, {
85
+ provider: "pg",
86
+ // Better Auth owns exactly these four. No app column is ever added to them.
87
+ schema: {
88
+ [userModel]: tables.appUser,
89
+ session: tables.session,
90
+ account: tables.account,
91
+ verification: tables.verification,
92
+ },
93
+ }),
94
+ // Off unless asked for. On, it never signs anyone up: a password belongs to an added user.
95
+ emailAndPassword: opts.emailAndPassword
96
+ ? {
97
+ enabled: true,
98
+ disableSignUp: true,
99
+ ...(opts.emailAndPassword.minPasswordLength !== undefined
100
+ ? { minPasswordLength: opts.emailAndPassword.minPasswordLength }
101
+ : {}),
102
+ ...(opts.emailAndPassword.maxPasswordLength !== undefined
103
+ ? { maxPasswordLength: opts.emailAndPassword.maxPasswordLength }
104
+ : {}),
105
+ }
106
+ : { enabled: false },
107
+ ...(opts.google
108
+ ? {
109
+ socialProviders: {
110
+ google: {
111
+ clientId: opts.google.clientId,
112
+ clientSecret: opts.google.clientSecret,
113
+ // Google never creates a user: an email nobody added is refused with
114
+ // `signup_disabled`.
115
+ disableImplicitSignUp: true,
116
+ disableSignUp: true,
117
+ },
118
+ },
119
+ }
120
+ : {}),
121
+ 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).
127
+ 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.
130
+ updateAccountOnSignIn: false,
131
+ },
132
+ user: {
133
+ 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.
136
+ additionalFields: {
137
+ role: { type: "string", required: false, input: false, defaultValue: "user" },
138
+ },
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.
146
+ validateUserInfo: async ({ source }) => source.method === "oauth" && source.action === "create-user"
147
+ ? { error: "signup_disabled", errorDescription: "signup disabled" }
148
+ : undefined,
149
+ },
150
+ session: {
151
+ // Database sessions: every request reads the row, so deleting it signs the person out.
152
+ expiresIn: 30 * DAY,
153
+ updateAge: DAY, // refreshed on use once older than a day
154
+ },
155
+ 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.
158
+ account: {
159
+ create: { before: async (row) => ({ data: withoutTokens(row) }) },
160
+ update: { before: async (row) => ({ data: withoutTokens(row) }) },
161
+ },
162
+ },
163
+ 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.
167
+ database: { generateId: () => randomUUID() },
168
+ defaultCookieAttributes: {
169
+ 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.
172
+ sameSite: "lax",
173
+ path: "/",
174
+ secure: opts.baseURL.startsWith("https://"),
175
+ },
176
+ },
177
+ rateLimit: { enabled: opts.rateLimit ?? true },
178
+ plugins: [
179
+ magicLink({
180
+ expiresIn: ttlSeconds, // and single use
181
+ // There is no public sign-up: a user row is added out of band (./users.ts).
182
+ 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.
185
+ storeToken: "hashed",
186
+ 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.
190
+ const existing = await ctx?.context.internalAdapter.findUserByEmail(normaliseEmail(email));
191
+ if (!existing?.user)
192
+ return;
193
+ await mailer.send({
194
+ to: existing.user.email,
195
+ subject: "Your sign-in link",
196
+ text: `Sign in: ${url}\n\nThe link works once and expires in ${ttlMinutes} minutes.`,
197
+ });
198
+ },
199
+ }),
200
+ // Last: lets a server action that signs someone in or out set Better Auth's cookies.
201
+ nextCookies(),
202
+ ],
203
+ });
204
+ }
205
+ const TOKEN_COLUMNS = [
206
+ "accessToken",
207
+ "refreshToken",
208
+ "idToken",
209
+ "accessTokenExpiresAt",
210
+ "refreshTokenExpiresAt",
211
+ ];
212
+ function withoutTokens(row) {
213
+ const copy = { ...row };
214
+ for (const column of TOKEN_COLUMNS)
215
+ if (column in copy)
216
+ copy[column] = null;
217
+ return copy;
218
+ }
219
+ /**
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).
223
+ */
224
+ async function attempt(what, call) {
225
+ try {
226
+ await call();
227
+ return { ok: true };
228
+ }
229
+ catch (error) {
230
+ const status = error instanceof APIError ? error.statusCode : 500;
231
+ const message = error instanceof Error ? error.message : String(error);
232
+ console.error(`[auth] ${what} failed`, { status, message });
233
+ return { ok: false, code: "unavailable" };
234
+ }
235
+ }
236
+ export { authTables } from "./tables.js";
237
+ export { DuplicateUserError, LastAdminError, UserNotFoundError } from "./users.js";