@wwchen/stack 0.6.3 → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +9 -8
- package/blocks/env.example +1 -2
- package/dist/auth/better-auth/index.d.ts +2 -316
- package/dist/auth/better-auth/index.js +2 -237
- package/dist/auth/index.d.ts +2 -58
- package/dist/auth/index.js +2 -120
- package/dist/auth/proxy.d.ts +2 -14
- package/dist/auth/proxy.js +2 -50
- package/dist/cli/context.d.ts +6 -3
- package/dist/cli/context.js +3 -0
- package/dist/cli/db.d.ts +3 -0
- package/dist/cli/db.js +26 -0
- package/dist/cli/index.js +14 -3
- package/dist/cli/migrate-suite.d.ts +2 -0
- package/dist/cli/migrate-suite.js +787 -0
- package/dist/cli/neon.d.ts +11 -44
- package/dist/cli/neon.js +15 -56
- package/dist/cli/sync-blocks.d.ts +1 -3
- package/dist/cli/sync-blocks.js +2 -6
- package/dist/cli/vercel-build.js +5 -16
- package/dist/configs/vitest.js +3 -7
- package/dist/connections/index.d.ts +2 -8
- package/dist/connections/index.js +3 -9
- package/dist/connections/providers.d.ts +1 -3
- package/dist/connections/table.d.ts +2 -3
- package/dist/connections/table.js +1 -2
- package/dist/db/explaining-pool.d.ts +1 -6
- package/dist/db/explaining-pool.js +3 -10
- package/dist/db/index.d.ts +1 -3
- package/dist/db/index.js +5 -13
- package/dist/db/migration-status.d.ts +1 -4
- package/dist/db/migration-status.js +1 -4
- package/dist/db/schema-changes.d.ts +13 -0
- package/dist/db/schema-changes.js +99 -0
- package/dist/db/ssl.d.ts +1 -5
- package/dist/db/ssl.js +1 -5
- package/dist/db/target.d.ts +2 -9
- package/dist/db/target.js +2 -9
- package/dist/db/testing/index.d.ts +3 -7
- package/dist/db/testing/index.js +3 -7
- package/dist/db/testing/isolate.js +1 -2
- package/dist/db/testing/pglite.d.ts +2 -6
- package/dist/db/testing/pglite.js +2 -6
- package/dist/env/define-env.d.ts +3 -9
- package/dist/env/define-env.js +6 -16
- package/dist/env/load-env-file.d.ts +4 -9
- package/dist/env/load-env-file.js +5 -11
- package/dist/env/stack-env.d.ts +1 -3
- package/dist/env/stack-env.js +3 -7
- package/dist/env/testing.d.ts +1 -3
- package/dist/env/testing.js +2 -5
- package/dist/http/guards.d.ts +3 -10
- package/dist/http/guards.js +4 -12
- package/dist/jobs/index.d.ts +2 -9
- package/dist/jobs/index.js +2 -9
- package/dist/mail/index.d.ts +4 -45
- package/dist/mail/index.js +4 -97
- package/dist/next/api.d.ts +7 -19
- package/dist/next/api.js +6 -15
- package/dist/next/config.js +10 -32
- package/dist/next/cron.d.ts +2 -6
- package/dist/next/cron.js +3 -8
- package/dist/next/health.d.ts +3 -8
- package/dist/next/health.js +3 -8
- package/dist/testing/next.d.ts +1 -4
- package/dist/testing/next.js +2 -7
- package/dist/ui/app.css +5 -16
- package/dist/ui/globals.css +6 -20
- package/dist/ui/icons.d.ts +1 -3
- package/dist/ui/icons.js +3 -10
- package/dist/ui/index.d.ts +4 -12
- package/dist/ui/index.js +4 -12
- package/dist/ui/theme.d.ts +3 -9
- package/dist/ui/theme.js +3 -9
- package/package.json +15 -9
- package/dist/auth/better-auth/tables.d.ts +0 -628
- package/dist/auth/better-auth/tables.js +0 -76
- package/dist/auth/better-auth/users.d.ts +0 -27
- package/dist/auth/better-auth/users.js +0 -128
- package/dist/auth/safe-next.d.ts +0 -17
- package/dist/auth/safe-next.js +0 -36
- package/dist/auth/types.d.ts +0 -47
- package/dist/auth/types.js +0 -5
- package/dist/http/client-ip.d.ts +0 -12
- package/dist/http/client-ip.js +0 -28
- package/dist/http/rate-limit.d.ts +0 -34
- package/dist/http/rate-limit.js +0 -79
package/README.md
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
# @wwchen/stack
|
|
2
2
|
|
|
3
|
-
Shared building blocks for Next.js 16 apps on Neon, Better Auth, Resend and lew-ds. Apps are normally created from the Copier template in [wwchen/bootstrap-stack](https://github.com/wwchen/bootstrap-stack), which wires everything below; this README is the package's reference.
|
|
3
|
+
Shared building blocks for Next.js 16 apps on Neon, Better Auth, Resend and lew-ds. Sign-in is [`@wwchen/stack-auth`](../auth) and mail is [`@wwchen/stack-notify`](../notify), released with this package under the same version. Apps are normally created from the Copier template in [wwchen/bootstrap-stack](https://github.com/wwchen/bootstrap-stack), which wires everything below; this README is the package's reference.
|
|
4
4
|
|
|
5
|
-
Requires Node 24. The peer dependencies are exact pins: `next`, `react`, `react-dom`, `drizzle-orm`, `@lew-ds/lds`, `@lew-ds/lds-react`, `@lew-ds/open-icons
|
|
5
|
+
Requires Node 24. The peer dependencies are exact pins: `next`, `react`, `react-dom`, `drizzle-orm`, `@lew-ds/lds`, `@lew-ds/lds-react`, `@lew-ds/open-icons`; `typescript` takes patch releases (`~`), and `stack migrate-suite` parses the app's imports with it. `@electric-sql/pglite` and `@electric-sql/pglite-socket` are optional peers for tests and local development, and `storybook` and `@storybook/nextjs-vite` for an app's Storybook.
|
|
6
6
|
|
|
7
7
|
## Entry points
|
|
8
8
|
|
|
@@ -11,10 +11,10 @@ Requires Node 24. The peer dependencies are exact pins: `next`, `react`, `react-
|
|
|
11
11
|
| `@wwchen/stack/env` | `stackEnvSchema` and `stackEnv()`: the shared variables, validated; production requires `APP_URL` (derived on Vercel when unset), `DATABASE_URL`, `BETTER_AUTH_SECRET`, `RESEND_API_KEY`, `EMAIL_FROM`. `SKIP_ENV_VALIDATION=1` skips it in builds (never at production runtime). |
|
|
12
12
|
| `@wwchen/stack/db` | the pooled client, `migrationStatus`, the dev-database guard that refuses production |
|
|
13
13
|
| `@wwchen/stack/db/testing`, `/db/testing/isolate` | test databases: PGlite by default, a real Postgres when `TEST_DATABASE_URL` is set |
|
|
14
|
-
| `@wwchen/stack/mail` |
|
|
15
|
-
| `@wwchen/stack/auth` |
|
|
16
|
-
| `@wwchen/stack/auth/better-auth` |
|
|
17
|
-
| `@wwchen/stack/auth/proxy` |
|
|
14
|
+
| `@wwchen/stack/mail` | deprecated: re-exports [`@wwchen/stack-notify`](../notify); import that instead |
|
|
15
|
+
| `@wwchen/stack/auth` | deprecated: re-exports [`@wwchen/stack-auth`](../auth); import that instead |
|
|
16
|
+
| `@wwchen/stack/auth/better-auth` | deprecated: re-exports `@wwchen/stack-auth/better-auth`; import that instead |
|
|
17
|
+
| `@wwchen/stack/auth/proxy` | deprecated: re-exports `@wwchen/stack-auth/proxy`; import that instead |
|
|
18
18
|
| `@wwchen/stack/next` | `withStack(appConfig)` for `next.config.ts`, `apiHandler` and `readJson`, `cronRoute` (answers 500 when the job returns `alerting: true`) and `healthRoute` |
|
|
19
19
|
| `@wwchen/stack/connections` | connected accounts (not sign-in): `connectionTable`, `createConnections` (start and callback route handlers, `token`, `list`, `connected`, `disconnect`), the `ConnectionProvider` type each app implements for its own services, AES-256-GCM token encryption under `TOKEN_ENCRYPTION_KEY` |
|
|
20
20
|
| `@wwchen/stack/jobs` | multi-person scheduled jobs: `failingSince` and `isNewFailure` (alert on a failure's first 24 hours only), `mapLimit` |
|
|
@@ -23,7 +23,7 @@ Requires Node 24. The peer dependencies are exact pins: `next`, `react`, `react-
|
|
|
23
23
|
| `@wwchen/stack/configs/tsconfig.next.json`, `/configs/biome.json`, `/configs/vitest` | shared tool configs, consumed with `extends` or an import |
|
|
24
24
|
| `@wwchen/stack/testing/next` | tests only: `inServerAction` runs a function in a real Next server-action scope, `thrownBy` reads a `redirect()`/`notFound()` |
|
|
25
25
|
|
|
26
|
-
Sign-in never creates users: every user is added first (`stack user:create`), has an email, and the email is unique, trimmed and lower-cased.
|
|
26
|
+
The deprecated paths still work in this release; a later release removes them. They are deprecated in this documentation only: each re-exports its package with `export *`, which does not carry `@deprecated` to the names, so an editor does not strike them through. `stack migrate-suite` moves an app's imports off them. Sign-in never creates users: every user is added first (`stack user:create`), has an email, and the email is unique, trimmed and lower-cased.
|
|
27
27
|
|
|
28
28
|
### Connected accounts
|
|
29
29
|
|
|
@@ -62,9 +62,10 @@ The callback lands on `next` with `?connection=<provider>&result=<code>`, where
|
|
|
62
62
|
| `stack user:create <email> [--admin] [--preview]` | adds a user through the app's `src/lib/auth.ts`; `--preview` adds your own email to the shared `preview` branch so you can sign in on a preview (`docs/runbook.md`, "Signing in on a preview") |
|
|
63
63
|
| `stack user:role <email> <admin\|user> [--preview]` | changes a user's role through the app's `src/lib/auth.ts`; never leaves the app without an admin |
|
|
64
64
|
| `stack sync-blocks [--check]` | refreshes the stack blocks in `AGENTS.md`, `CLAUDE.md`, `.gitignore`, `.env.example` |
|
|
65
|
+
| `stack migrate-suite [--expect <version>]` | moves the app onto `@wwchen/stack-auth` and `@wwchen/stack-notify`: adds them to `package.json` and the suite's packages to `pnpm-workspace.yaml`'s `minimumReleaseAgeExclude` (where the app has that list, or sets `minimumReleaseAge`), rewrites import and export specifiers of the old paths (and `vi.mock`-style module names), sorts the imports it touched with the app's Biome, and adds `rateLimit` to `src/db/schema.ts` and `src/lib/auth.ts` when they have the template's shape (otherwise prints the lines to write, and exits non-zero when the auth provider gets `authTables()`'s `rate_limit` table that the schema does not export, since sign-in would answer `unavailable`); changes nothing on an app already moved. `--expect` refuses unless the installed stack is that version |
|
|
65
66
|
|
|
66
67
|
`NEON_PROJECT_ID` comes from the environment; nothing in the package names a project or domain.
|
|
67
68
|
|
|
68
69
|
## Versioning
|
|
69
70
|
|
|
70
|
-
The package, the Copier template and the shared CI workflow share one version, tagged `vX.Y.Z`. Releases are published to npm with provenance.
|
|
71
|
+
The package, `@wwchen/stack-auth`, `@wwchen/stack-notify`, the Copier template and the shared CI workflow share one version, tagged `vX.Y.Z`. Releases are published to npm with provenance.
|
package/blocks/env.example
CHANGED
|
@@ -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=
|
|
@@ -1,316 +1,2 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
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 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.
|
|
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, normaliseEmail, UserNotFoundError } from "./users.ts";
|
|
1
|
+
/** @deprecated Import from `@wwchen/stack-auth/better-auth`. */
|
|
2
|
+
export * from "@wwchen/stack-auth/better-auth";
|
|
@@ -1,237 +1,2 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
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, normaliseEmail, UserNotFoundError } from "./users.js";
|
|
1
|
+
/** @deprecated Import from `@wwchen/stack-auth/better-auth`. */
|
|
2
|
+
export * from "@wwchen/stack-auth/better-auth";
|