@soroi/auth 0.0.0-stage → 0.1.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/AGENTS.md +154 -0
- package/LICENSE +21 -0
- package/README.md +26 -2
- package/dist/account.d.ts +52 -0
- package/dist/account.js +177 -0
- package/dist/adapters/next.d.ts +6 -0
- package/dist/adapters/next.js +35 -0
- package/dist/adapters/tanstack.d.ts +12 -0
- package/dist/adapters/tanstack.js +40 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +76 -0
- package/dist/core.d.ts +122 -0
- package/dist/core.js +351 -0
- package/dist/crypto.d.ts +12 -0
- package/dist/crypto.js +69 -0
- package/dist/db.d.ts +29 -0
- package/dist/db.js +55 -0
- package/dist/email.d.ts +9 -0
- package/dist/email.js +64 -0
- package/dist/errors.d.ts +24 -0
- package/dist/errors.js +88 -0
- package/dist/index.d.ts +202 -0
- package/dist/index.js +255 -0
- package/dist/methods.d.ts +16 -0
- package/dist/methods.js +21 -0
- package/dist/migrations.d.ts +5 -0
- package/dist/migrations.js +147 -0
- package/dist/modules/oauth-server.d.ts +110 -0
- package/dist/modules/oauth-server.js +568 -0
- package/dist/modules/tokens.d.ts +31 -0
- package/dist/modules/tokens.js +107 -0
- package/dist/modules/two-factor.d.ts +41 -0
- package/dist/modules/two-factor.js +169 -0
- package/dist/modules/workspaces.d.ts +138 -0
- package/dist/modules/workspaces.js +295 -0
- package/dist/oauth/flow.d.ts +5 -0
- package/dist/oauth/flow.js +161 -0
- package/dist/oauth/providers.d.ts +29 -0
- package/dist/oauth/providers.js +124 -0
- package/dist/password-hash.d.ts +8 -0
- package/dist/password-hash.js +68 -0
- package/dist/password.d.ts +49 -0
- package/dist/password.js +181 -0
- package/dist/routes.d.ts +5 -0
- package/dist/routes.js +77 -0
- package/dist/sessions.d.ts +51 -0
- package/dist/sessions.js +184 -0
- package/dist/testing.d.ts +15 -0
- package/dist/testing.js +32 -0
- package/dist/types.d.ts +184 -0
- package/dist/types.js +1 -0
- package/package.json +75 -4
package/AGENTS.md
ADDED
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
# @soroi/auth — notes for coding agents
|
|
2
|
+
|
|
3
|
+
Server-only, framework-agnostic auth. No UI, no client SDK, no runtime dependencies. Full docs: https://auth.kaarel.dev/llms-full.txt
|
|
4
|
+
|
|
5
|
+
## Rules
|
|
6
|
+
|
|
7
|
+
- Call the package only from server code: server functions, server actions, route handlers, server loaders. Never import `~/auth` or `@soroi/auth` into browser code. Pages import `AuthError` and `messages` from `@soroi/auth/errors` (no server code).
|
|
8
|
+
- Everything that changes something must run in a POST request (TanStack `createServerFn({ method: "POST" })`, a Next.js server action, a POST route). The package refuses changes over GET (`forbidden_origin`).
|
|
9
|
+
- Follow the app's own file layout. The config can live in any server-only module (`src/auth.ts`, `lib/auth.ts`, …); page paths go in `pages`; `basePath` (default `/auth`) is where the routes mount.
|
|
10
|
+
- Handle `reauth_required`: sensitive changes (e-mail change, first password, unlink, delete, provider link, `tokens.create`, `twoFactor.setup`) need a sign-in in the last 15 minutes. Ask for the password and call `auth.account.reauthenticate({ password })` (or `{ code }` when two-factor is on) or pass `password` to the call; users without a password sign in again.
|
|
11
|
+
- `pages.signIn` must handle `?verified=1` ("E-mail confirmed, sign in") and `?verified=reset` ("E-mail confirmed, choose a password", linked to the reset form): a verification link opened in another browser only verifies, and drops the password that was set before.
|
|
12
|
+
- Show `email_unavailable` and hide sign-up and reset when no e-mail is set up (`email: false`).
|
|
13
|
+
- MCP clients sign in through `createOAuthServer` (docs: MCP sign-in). Do not write OAuth server code by hand.
|
|
14
|
+
- The app owns every page: login, sign-up, forgot password, reset password, two-factor code, settings, invite. The package never renders HTML.
|
|
15
|
+
- Functions that change something return `{ ok: true, ... } | { ok: false, error: AuthError }`. Show `error` in the app's own words. Do not show raw codes to users.
|
|
16
|
+
- Read functions (`user`, `session`, `sessions.list`, `workspaces.members`, …) return data and throw `AuthException` (`code: "not_signed_in"`) without a session.
|
|
17
|
+
- Redirect flows (Google, GitHub, e-mail links) send errors to `pages.error` as `?error=<code>`. The page that `pages.error` points to must read `error` from the query string.
|
|
18
|
+
- Use `result.redirectTo` after `password.signIn` and `twoFactor.verify`. It is safe: a path on this site, or a full URL on one of `trustedOrigins`. Open full URLs with a page load (`window.location.assign`), not the router.
|
|
19
|
+
- Do not add better-auth, lucia, next-auth, arctic, oslo, jose, bcrypt or a client auth SDK. Do not write session or cookie code by hand.
|
|
20
|
+
- Do not loosen security: keep `rateLimit` on outside tests, keep `verifyEmail` on unless the user asks, never set `trustedOrigins` to origins the app does not control, never put `devLogin` in production config.
|
|
21
|
+
- Run `bunx --bun soroi-auth doctor` after setup and report the redirect URIs it prints.
|
|
22
|
+
- Do not name a file `src/server.ts` in TanStack Start; that name is its server entry.
|
|
23
|
+
|
|
24
|
+
## Setup
|
|
25
|
+
|
|
26
|
+
```ts
|
|
27
|
+
// a server-only module, e.g. src/auth.ts or lib/auth.ts
|
|
28
|
+
import { createAuth, google, github, password, allowlist, resend, pg } from "@soroi/auth";
|
|
29
|
+
|
|
30
|
+
export const auth = createAuth({
|
|
31
|
+
url: process.env.BASE_URL!, // public URL; https in production
|
|
32
|
+
secret: process.env.AUTH_SECRET!, // ≥32 chars: `bunx soroi-auth secret`
|
|
33
|
+
db: process.env.DATABASE_URL!, // Bun. Node: pg(pool) | postgresJs(sql)
|
|
34
|
+
framework: tanstackStart(), // or nextjs(), or leave out and use auth.withRequest(request)
|
|
35
|
+
appName: "Acme",
|
|
36
|
+
methods: [password(), google(process.env.GOOGLE_CLIENT_ID, process.env.GOOGLE_CLIENT_SECRET)],
|
|
37
|
+
access: "open", // "closed" | allowlist("a@x.dev, @team.dev") | (email) => boolean
|
|
38
|
+
email: { from: "Acme <no-reply@acme.dev>", send: resend(process.env.RESEND_API_KEY) },
|
|
39
|
+
pages: {
|
|
40
|
+
signIn: "/login", afterSignIn: "/app", afterSignOut: "/", error: "/login", verified: "/app",
|
|
41
|
+
resetPassword: "/reset-password", twoFactor: "/login/two-factor", acceptInvite: "/invite",
|
|
42
|
+
},
|
|
43
|
+
// optional modules:
|
|
44
|
+
twoFactor: true,
|
|
45
|
+
workspaces: { roles: ["owner", "admin", "member"] },
|
|
46
|
+
tokens: { prefix: "acme" },
|
|
47
|
+
onUserCreated: async (user, tx) => { /* same transaction as the user insert */ },
|
|
48
|
+
});
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
Connect the framework. Mount the routes on `<basePath>/*` and call the API from POST handlers:
|
|
52
|
+
|
|
53
|
+
| Framework | Adapter | Mount `/auth/*` | Changes run in | Guard |
|
|
54
|
+
| --- | --- | --- | --- | --- |
|
|
55
|
+
| TanStack Start | `tanstackStart()` from `@soroi/auth/tanstack` | `createFileRoute("/auth/$")({ server: { handlers: auth.routes } })` (1.131: `createServerFileRoute("/auth/$").methods(auth.routes)`) | `createServerFn({ method: "POST" })` | `beforeLoad` → server fn → `auth.user()` |
|
|
56
|
+
| Next.js 15+ | `nextjs()` from `@soroi/auth/next` | `app/auth/[...auth]/route.ts`: `export const GET = auth.handler; export const POST = auth.handler;` | server actions | server component: `await auth.requireUser({ next: "/page" })` |
|
|
57
|
+
| Hono | none | `app.all("/auth/*", (c) => auth.handler(c.req.raw))` | POST route: `const api = auth.withRequest(c.req.raw)`; return `api.headers` | middleware: `auth.withRequest(c.req.raw).user()` |
|
|
58
|
+
| Any (web Request) | none | send `/auth/*` to `auth.handler(request)` | POST handler with `auth.withRequest(request)`; copy `api.headers` (Set-Cookie) to the response | `auth.withRequest(request).user()` |
|
|
59
|
+
|
|
60
|
+
Sessions last 365 days (`session.days`, at most 400) and renew once a day when used. Reads renew too, so copy `api.headers` to the response after every `withRequest` call, reads included. Inside a TanStack Start request: `sendCookies(api.headers)` from `@soroi/auth/tanstack`.
|
|
61
|
+
|
|
62
|
+
Next.js server components only read (`user`, `session`, `requireUser`); they cannot set cookies.
|
|
63
|
+
|
|
64
|
+
Routes it serves (all redirect, none render):
|
|
65
|
+
|
|
66
|
+
| Route | Use |
|
|
67
|
+
| --- | --- |
|
|
68
|
+
| `GET /auth/google?next=/x`, `GET /auth/github?next=/x` | Login button links |
|
|
69
|
+
| `GET /auth/google?link=1&next=/settings` | Link a provider to the signed-in user |
|
|
70
|
+
| `GET /auth/{google,github}/callback` | Register this as the redirect URI |
|
|
71
|
+
| `GET /auth/verify?token=` | Sign-up and e-mail change links |
|
|
72
|
+
| `POST /auth/sign-out` | `<form method="post" action="/auth/sign-out">` |
|
|
73
|
+
| `GET /auth/dev?next=/x` | Dev login (`devLogin`), local hosts only |
|
|
74
|
+
|
|
75
|
+
## API
|
|
76
|
+
|
|
77
|
+
```ts
|
|
78
|
+
auth.user(): Promise<User | null>
|
|
79
|
+
auth.session(): Promise<{ user, session, scopes? } | null>
|
|
80
|
+
auth.requireUser({ next? }): Promise<User> // redirects to pages.signIn?next= (adapter) or throws not_signed_in
|
|
81
|
+
auth.signOut()
|
|
82
|
+
|
|
83
|
+
auth.password.signUp({ email, password, name? }) // → { ok, next: "verify_email" | "signed_in" }
|
|
84
|
+
auth.password.signIn({ email, password, next? }) // → { ok, next: "signed_in" | "two_factor", redirectTo }
|
|
85
|
+
auth.password.requestReset({ email }) // always { ok: true }
|
|
86
|
+
auth.password.reset({ token, password }) // token from pages.resetPassword?token=
|
|
87
|
+
auth.password.resendVerification({ email }) // always { ok: true }
|
|
88
|
+
|
|
89
|
+
auth.account.reauthenticate({ password }) // opens a 15-minute window for sensitive changes
|
|
90
|
+
auth.account.changePassword({ current?, next })
|
|
91
|
+
auth.account.changeEmail({ email, password? }) // link must be opened while signed in as this user
|
|
92
|
+
auth.account.linked() // { hasPassword, accounts }
|
|
93
|
+
auth.account.unlink({ provider, password? })
|
|
94
|
+
auth.account.delete({ password? })
|
|
95
|
+
|
|
96
|
+
auth.sessions.list() // each has current: boolean
|
|
97
|
+
auth.sessions.revoke({ id })
|
|
98
|
+
auth.sessions.revokeOthers()
|
|
99
|
+
|
|
100
|
+
auth.twoFactor.status() // { enabled, recoveryCodesLeft }
|
|
101
|
+
auth.twoFactor.setup({ password? }) // { secret, uri } → draw uri as a QR code
|
|
102
|
+
auth.twoFactor.enable({ code }) // { recoveryCodes } → show once
|
|
103
|
+
auth.twoFactor.verify({ code }) // sign-in step on pages.twoFactor → { redirectTo }
|
|
104
|
+
auth.twoFactor.disable({ code })
|
|
105
|
+
auth.twoFactor.regenerateRecoveryCodes({ code })
|
|
106
|
+
|
|
107
|
+
auth.workspaces.current() / list()
|
|
108
|
+
auth.workspaces.requireMember({ role?, workspaceId? }) // { user, session, workspace, role }; throws forbidden
|
|
109
|
+
auth.workspaces.create({ name }) / switch({ workspaceId }) / rename({ name }) / delete()
|
|
110
|
+
auth.workspaces.members() / setRole({ userId, role }) / removeMember({ userId }) / leave() / transferOwnership({ userId })
|
|
111
|
+
auth.workspaces.invite({ email, role }) / invites() / revokeInvite({ email })
|
|
112
|
+
auth.workspaces.inviteInfo({ token }) // works signed out
|
|
113
|
+
auth.workspaces.acceptInvite({ token }) // signed-in user's verified e-mail must match
|
|
114
|
+
|
|
115
|
+
auth.tokens.create({ name, scopes?, expiresInDays?, workspaceId?, password? }) // { token } → show once
|
|
116
|
+
auth.tokens.list() / revoke({ id })
|
|
117
|
+
// Bearer tokens: auth.session() returns { session: { method: "token" }, scopes }.
|
|
118
|
+
// Tokens only read through the package (user, session, workspace reads in their own workspace).
|
|
119
|
+
// The package does not check scopes: check session().scopes in your API routes.
|
|
120
|
+
|
|
121
|
+
auth.handler(request) / auth.routes / auth.withRequest(request) // + .headers with Set-Cookie, also after reads
|
|
122
|
+
sendCookies(api.headers) // @soroi/auth/tanstack: adds them to the current response
|
|
123
|
+
auth.users.create({ email, password?, name?, emailVerified? }) / get(id) / byEmail(email) / setPassword(id, pw) / delete(id)
|
|
124
|
+
auth.migrate() / auth.doctor() / auth.settled() // settled: wait for background e-mails (tests)
|
|
125
|
+
```
|
|
126
|
+
|
|
127
|
+
Workspace functions act on the session's active workspace unless `workspaceId` is given.
|
|
128
|
+
|
|
129
|
+
## Error codes (`AuthError`)
|
|
130
|
+
|
|
131
|
+
`invalid_input invalid_email weak_password password_too_long invalid_credentials email_not_verified email_taken signup_closed access_denied rate_limited forbidden_origin not_signed_in reauth_required invalid_token link_expired oauth_failed oauth_denied oauth_email_unverified account_linked_elsewhere last_sign_in_method method_disabled invalid_code two_factor_not_enabled two_factor_already_enabled challenge_expired not_found forbidden already_member invite_email_mismatch owner_cannot_leave transfer_ownership_first`
|
|
132
|
+
|
|
133
|
+
English defaults: `import { messages } from "@soroi/auth/errors"; messages.en[code]`. A thrown `AuthException` that crosses a server function boundary arrives as a plain `Error` whose `message` is the code. For full coverage type the app's map as `Record<AuthError, string>`.
|
|
134
|
+
|
|
135
|
+
## Patterns (TanStack Start example)
|
|
136
|
+
|
|
137
|
+
```ts
|
|
138
|
+
export const signIn = createServerFn({ method: "POST" })
|
|
139
|
+
.validator((d: { email: string; password: string; next?: string }) => d)
|
|
140
|
+
.handler(({ data }) => auth.password.signIn(data));
|
|
141
|
+
|
|
142
|
+
export const currentUser = createServerFn().handler(() => auth.user());
|
|
143
|
+
|
|
144
|
+
// route guard
|
|
145
|
+
beforeLoad: async ({ location }) => {
|
|
146
|
+
const user = await currentUser();
|
|
147
|
+
if (!user) throw redirect({ to: "/login", search: { next: location.href } });
|
|
148
|
+
return { user };
|
|
149
|
+
},
|
|
150
|
+
```
|
|
151
|
+
|
|
152
|
+
App tables reference `auth.users(id)` / `auth.workspaces(id)` (uuid) with `on delete cascade`.
|
|
153
|
+
|
|
154
|
+
Tests: `import { signInAs } from "@soroi/auth/testing"; const { request } = await signInAs(auth, "a@b.dev");`
|
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Kaarel
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,27 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @soroi/auth
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Framework-agnostic, server-only auth for TypeScript apps. No UI, no client SDK, no runtime dependencies.
|
|
4
|
+
|
|
5
|
+
- Cookie sessions, Google, GitHub, e-mail and password, verification and reset e-mails
|
|
6
|
+
- Optional modules: two-factor (TOTP), workspaces with roles and invites, API tokens, MCP sign-in (OAuth server)
|
|
7
|
+
- Your app keeps its own pages. Functions return `{ ok, error }` with typed error codes.
|
|
8
|
+
- Any framework with a web `Request`; adapters for TanStack Start and Next.js
|
|
9
|
+
- Bun 1.2+ or Node 24.7+, PostgreSQL 13+
|
|
10
|
+
|
|
11
|
+
```ts
|
|
12
|
+
import { createAuth, google, password } from "@soroi/auth";
|
|
13
|
+
|
|
14
|
+
export const auth = createAuth({
|
|
15
|
+
url: process.env.BASE_URL!,
|
|
16
|
+
secret: process.env.AUTH_SECRET!,
|
|
17
|
+
db: process.env.DATABASE_URL!,
|
|
18
|
+
methods: [password(), google(process.env.GOOGLE_CLIENT_ID, process.env.GOOGLE_CLIENT_SECRET)],
|
|
19
|
+
});
|
|
20
|
+
|
|
21
|
+
// any framework: Hono, Bun.serve, SvelteKit, … (TanStack Start and Next.js adapters drop the withRequest)
|
|
22
|
+
const api = auth.withRequest(request);
|
|
23
|
+
const result = await api.password.signIn({ email, password }); // set api.headers on the response, also after reads
|
|
24
|
+
if (!result.ok) showError(result.error); // "invalid_credentials" | "email_not_verified" | …
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
Docs: https://auth.kaarel.dev · For coding agents: [AGENTS.md](./AGENTS.md) and https://auth.kaarel.dev/llms-full.txt
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import { type Core, type RequestContext } from "./core.js";
|
|
2
|
+
import type { OAuthProviderId } from "./types.js";
|
|
3
|
+
/**
|
|
4
|
+
* Renews the recent sign-in window. Users with two-factor on give a code, others their password.
|
|
5
|
+
* Users with neither sign in again instead.
|
|
6
|
+
*/
|
|
7
|
+
export declare function reauthenticate(core: Core, ctx: RequestContext, input: {
|
|
8
|
+
password?: string;
|
|
9
|
+
code?: string;
|
|
10
|
+
}): Promise<{
|
|
11
|
+
ok: true;
|
|
12
|
+
}>;
|
|
13
|
+
/**
|
|
14
|
+
* With a password, `current` must be right. Without one (Google only), the user sets a first password,
|
|
15
|
+
* which needs a recent sign-in. Other sessions and pending e-mail changes end.
|
|
16
|
+
*/
|
|
17
|
+
export declare function changePassword(core: Core, ctx: RequestContext, input: {
|
|
18
|
+
current?: string;
|
|
19
|
+
next: string;
|
|
20
|
+
}): Promise<{
|
|
21
|
+
ok: true;
|
|
22
|
+
}>;
|
|
23
|
+
/** Sends a link to the new address. The e-mail changes when that link is opened while signed in as this user. */
|
|
24
|
+
export declare function changeEmail(core: Core, ctx: RequestContext, input: {
|
|
25
|
+
email: string;
|
|
26
|
+
password?: string;
|
|
27
|
+
}): Promise<{
|
|
28
|
+
ok: true;
|
|
29
|
+
}>;
|
|
30
|
+
/** Handles `/auth/verify?token=` for sign-up and e-mail change links. Returns where to redirect. */
|
|
31
|
+
export declare function verifyEmailLink(core: Core, ctx: RequestContext, token: string): Promise<string>;
|
|
32
|
+
export declare function linkedAccounts(core: Core, ctx: RequestContext): Promise<{
|
|
33
|
+
hasPassword: boolean;
|
|
34
|
+
accounts: {
|
|
35
|
+
provider: OAuthProviderId;
|
|
36
|
+
email: string | null;
|
|
37
|
+
createdAt: Date;
|
|
38
|
+
}[];
|
|
39
|
+
}>;
|
|
40
|
+
/** Refuses to remove the last way to sign in. */
|
|
41
|
+
export declare function unlink(core: Core, ctx: RequestContext, input: {
|
|
42
|
+
provider: OAuthProviderId;
|
|
43
|
+
password?: string;
|
|
44
|
+
}): Promise<{
|
|
45
|
+
ok: true;
|
|
46
|
+
}>;
|
|
47
|
+
/** Deletes the user and everything that cascades from it. Workspaces they own alone go too. */
|
|
48
|
+
export declare function deleteAccount(core: Core, ctx: RequestContext, input?: {
|
|
49
|
+
password?: string;
|
|
50
|
+
}): Promise<{
|
|
51
|
+
ok: true;
|
|
52
|
+
}>;
|
package/dist/account.js
ADDED
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
import { assertSameOrigin, consumeEmailToken, issueEmailToken, limit, link, peekEmailToken, requireEmail, signInLink, } from "./core.js";
|
|
2
|
+
import { safeEqual } from "./crypto.js";
|
|
3
|
+
import { AuthException } from "./errors.js";
|
|
4
|
+
import { hashPassword, verifyPassword } from "./password-hash.js";
|
|
5
|
+
import { browserHash, checkEmail, checkPassword, verifyLink } from "./password.js";
|
|
6
|
+
import * as twoFactor from "./modules/two-factor.js";
|
|
7
|
+
import { deleteUserSessions, finishSignIn, getUser, readSession, renewRecent, requireRecent, requireSession, revokeAccess, signOut, twoFactorEnabled, } from "./sessions.js";
|
|
8
|
+
const CHANGE_EMAIL_SECONDS = 24 * 3600;
|
|
9
|
+
/**
|
|
10
|
+
* Renews the recent sign-in window. Users with two-factor on give a code, others their password.
|
|
11
|
+
* Users with neither sign in again instead.
|
|
12
|
+
*/
|
|
13
|
+
export async function reauthenticate(core, ctx, input) {
|
|
14
|
+
assertSameOrigin(core, ctx);
|
|
15
|
+
const current = await requireSession(core, ctx, { browser: true });
|
|
16
|
+
if (await twoFactorEnabled(core, current.user.id)) {
|
|
17
|
+
await twoFactor.confirm(core, current.user.id, input?.code);
|
|
18
|
+
await renewRecent(core, current);
|
|
19
|
+
return { ok: true };
|
|
20
|
+
}
|
|
21
|
+
if (!current.user.hasPassword)
|
|
22
|
+
throw new AuthException("reauth_required");
|
|
23
|
+
if (typeof input?.password !== "string")
|
|
24
|
+
throw new AuthException("invalid_credentials");
|
|
25
|
+
await requireRecent(core, current, input.password);
|
|
26
|
+
return { ok: true };
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* With a password, `current` must be right. Without one (Google only), the user sets a first password,
|
|
30
|
+
* which needs a recent sign-in. Other sessions and pending e-mail changes end.
|
|
31
|
+
*/
|
|
32
|
+
export async function changePassword(core, ctx, input) {
|
|
33
|
+
assertSameOrigin(core, ctx);
|
|
34
|
+
const current = await requireSession(core, ctx, { browser: true });
|
|
35
|
+
const { user, session } = current;
|
|
36
|
+
const next = checkPassword(core, input?.next);
|
|
37
|
+
const stored = await getUser(core, core.db, "id", user.id);
|
|
38
|
+
if (stored?.passwordHash) {
|
|
39
|
+
await limit(core, `confirm-password:${user.id}`, 10, 900);
|
|
40
|
+
if (typeof input?.current !== "string" || !(await verifyPassword(stored.passwordHash, input.current))) {
|
|
41
|
+
throw new AuthException("invalid_credentials");
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
else {
|
|
45
|
+
await requireRecent(core, current);
|
|
46
|
+
}
|
|
47
|
+
await core.db.transaction(async (tx) => {
|
|
48
|
+
await tx.query(`update ${core.s}.users set password_hash = $2, updated_at = now() where id = $1::uuid`, [
|
|
49
|
+
user.id,
|
|
50
|
+
await hashPassword(next),
|
|
51
|
+
]);
|
|
52
|
+
await deleteUserSessions(core, tx, user.id, session.id);
|
|
53
|
+
await tx.query(`delete from ${core.s}.email_tokens where user_id = $1::uuid and kind = 'change_email'`, [user.id]);
|
|
54
|
+
});
|
|
55
|
+
core.background(() => core.sendEmail("passwordChanged", user.email, { appName: core.appName, email: user.email, name: user.name }));
|
|
56
|
+
return { ok: true };
|
|
57
|
+
}
|
|
58
|
+
/** Sends a link to the new address. The e-mail changes when that link is opened while signed in as this user. */
|
|
59
|
+
export async function changeEmail(core, ctx, input) {
|
|
60
|
+
assertSameOrigin(core, ctx);
|
|
61
|
+
const current = await requireSession(core, ctx, { browser: true });
|
|
62
|
+
const { user } = current;
|
|
63
|
+
requireEmail(core);
|
|
64
|
+
const email = checkEmail(input?.email);
|
|
65
|
+
if (email === user.email)
|
|
66
|
+
return { ok: true };
|
|
67
|
+
await requireRecent(core, current, input?.password);
|
|
68
|
+
await limit(core, `change-email:${user.id}`, 5, 3600);
|
|
69
|
+
if (await getUser(core, core.db, "email", email))
|
|
70
|
+
throw new AuthException("email_taken");
|
|
71
|
+
const token = await issueEmailToken(core, core.db, "change_email", user.id, email, CHANGE_EMAIL_SECONDS);
|
|
72
|
+
core.background(() => core.sendEmail("changeEmail", email, { appName: core.appName, url: verifyLink(core, token), email, name: user.name }));
|
|
73
|
+
return { ok: true };
|
|
74
|
+
}
|
|
75
|
+
/** Handles `/auth/verify?token=` for sign-up and e-mail change links. Returns where to redirect. */
|
|
76
|
+
export async function verifyEmailLink(core, ctx, token) {
|
|
77
|
+
const peeked = await peekEmailToken(core, token);
|
|
78
|
+
if (peeked?.kind === "change_email") {
|
|
79
|
+
// Only the account owner, signed in, can move the account to the new address.
|
|
80
|
+
// A stranger who opens the link cannot complete the change.
|
|
81
|
+
const current = await readSession(core, ctx);
|
|
82
|
+
if (!current || current.user.id !== peeked.userId || current.session.method === "token") {
|
|
83
|
+
return signInLink(core, { next: `${ctx.url.pathname}${ctx.url.search}` });
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
const pending = ctx.cookie(core.cookies.pending);
|
|
87
|
+
const result = await core.db.transaction(async (tx) => {
|
|
88
|
+
const consumed = await consumeEmailToken(core, tx, ["verify_email", "change_email"], token);
|
|
89
|
+
if (typeof consumed === "string")
|
|
90
|
+
return consumed;
|
|
91
|
+
if (consumed.kind === "change_email") {
|
|
92
|
+
const [taken] = await tx.query(`select 1 from ${core.s}.users where email = $1 and id <> $2::uuid`, [
|
|
93
|
+
consumed.email,
|
|
94
|
+
consumed.userId,
|
|
95
|
+
]);
|
|
96
|
+
if (taken)
|
|
97
|
+
return "email_taken";
|
|
98
|
+
const [old] = await tx.query(`select email, name from ${core.s}.users where id = $1::uuid`, [consumed.userId]);
|
|
99
|
+
await tx.query(`update ${core.s}.users set email = $2, email_verified_at = now(), updated_at = now() where id = $1::uuid`, [consumed.userId, consumed.email]);
|
|
100
|
+
return { ...consumed, oldEmail: old?.email ?? null, name: old?.name ?? null, sameBrowser: false, passwordDropped: false };
|
|
101
|
+
}
|
|
102
|
+
const [user] = await tx.query(`select email_verified_at is not null as verified from ${core.s}.users where id = $1::uuid and email = $2 for update`, [consumed.userId, consumed.email]);
|
|
103
|
+
if (!user)
|
|
104
|
+
return "invalid_token";
|
|
105
|
+
const sameBrowser = !!pending && !!consumed.browser && safeEqual(browserHash(core, pending), consumed.browser);
|
|
106
|
+
await tx.query(`update ${core.s}.users set email_verified_at = coalesce(email_verified_at, now()), updated_at = now() where id = $1::uuid`, [consumed.userId]);
|
|
107
|
+
// Whoever signed up is not the one who opened the link, so the password they set may not be the owner's.
|
|
108
|
+
if (!user.verified && !sameBrowser) {
|
|
109
|
+
await tx.query(`update ${core.s}.users set password_hash = null where id = $1::uuid`, [consumed.userId]);
|
|
110
|
+
await revokeAccess(core, tx, consumed.userId);
|
|
111
|
+
}
|
|
112
|
+
return { ...consumed, oldEmail: null, name: null, sameBrowser, passwordDropped: !user.verified && !sameBrowser };
|
|
113
|
+
});
|
|
114
|
+
if (typeof result === "string")
|
|
115
|
+
return link(core, core.pages.error, { error: result });
|
|
116
|
+
if (result.kind === "change_email") {
|
|
117
|
+
if (result.oldEmail) {
|
|
118
|
+
const oldEmail = result.oldEmail;
|
|
119
|
+
core.background(() => core.sendEmail("emailChanged", oldEmail, {
|
|
120
|
+
appName: core.appName,
|
|
121
|
+
url: core.origin,
|
|
122
|
+
email: oldEmail,
|
|
123
|
+
name: result.name,
|
|
124
|
+
newEmail: result.email,
|
|
125
|
+
}));
|
|
126
|
+
}
|
|
127
|
+
return core.pages.verified;
|
|
128
|
+
}
|
|
129
|
+
// The link signs in only the browser that signed up. Opened anywhere else it only verifies the e-mail,
|
|
130
|
+
// so a link someone forwards or plants does not sign the opener into that account.
|
|
131
|
+
if (!result.sameBrowser) {
|
|
132
|
+
return link(core, core.pages.signIn, { verified: result.passwordDropped ? "reset" : "1" });
|
|
133
|
+
}
|
|
134
|
+
ctx.clearCookie(core.cookies.pending);
|
|
135
|
+
const step = await finishSignIn(core, ctx, result.userId, "email_link", core.pages.verified);
|
|
136
|
+
return step.redirectTo;
|
|
137
|
+
}
|
|
138
|
+
export async function linkedAccounts(core, ctx) {
|
|
139
|
+
const { user } = await requireSession(core, ctx, { browser: true });
|
|
140
|
+
const rows = await core.db.query(`select provider, email, created_at from ${core.s}.accounts where user_id = $1::uuid order by created_at`, [user.id]);
|
|
141
|
+
return {
|
|
142
|
+
hasPassword: user.hasPassword,
|
|
143
|
+
accounts: rows.map((row) => ({ provider: row.provider, email: row.email, createdAt: new Date(row.created_at) })),
|
|
144
|
+
};
|
|
145
|
+
}
|
|
146
|
+
/** Refuses to remove the last way to sign in. */
|
|
147
|
+
export async function unlink(core, ctx, input) {
|
|
148
|
+
assertSameOrigin(core, ctx);
|
|
149
|
+
const current = await requireSession(core, ctx, { browser: true });
|
|
150
|
+
await requireRecent(core, current, input?.password);
|
|
151
|
+
const linked = await linkedAccounts(core, ctx);
|
|
152
|
+
const others = linked.accounts.filter((account) => account.provider !== input?.provider).length;
|
|
153
|
+
if (!current.user.hasPassword && others === 0)
|
|
154
|
+
throw new AuthException("last_sign_in_method");
|
|
155
|
+
await core.db.query(`delete from ${core.s}.accounts where user_id = $1::uuid and provider = $2`, [current.user.id, input?.provider]);
|
|
156
|
+
return { ok: true };
|
|
157
|
+
}
|
|
158
|
+
/** Deletes the user and everything that cascades from it. Workspaces they own alone go too. */
|
|
159
|
+
export async function deleteAccount(core, ctx, input = {}) {
|
|
160
|
+
assertSameOrigin(core, ctx);
|
|
161
|
+
const current = await requireSession(core, ctx, { browser: true });
|
|
162
|
+
const { user } = current;
|
|
163
|
+
await requireRecent(core, current, input?.password);
|
|
164
|
+
await core.db.transaction(async (tx) => {
|
|
165
|
+
const [shared] = await tx.query(`select 1 from ${core.s}.members m
|
|
166
|
+
where m.user_id = $1::uuid and m.role = $2
|
|
167
|
+
and exists (select 1 from ${core.s}.members o where o.workspace_id = m.workspace_id and o.user_id <> m.user_id)`, [user.id, core.roles[0]]);
|
|
168
|
+
if (shared)
|
|
169
|
+
throw new AuthException("transfer_ownership_first");
|
|
170
|
+
await tx.query(`delete from ${core.s}.workspaces w where exists (
|
|
171
|
+
select 1 from ${core.s}.members m where m.workspace_id = w.id and m.user_id = $1::uuid and m.role = $2)`, [user.id, core.roles[0]]);
|
|
172
|
+
await revokeAccess(core, tx, user.id);
|
|
173
|
+
await tx.query(`delete from ${core.s}.users where id = $1::uuid`, [user.id]);
|
|
174
|
+
});
|
|
175
|
+
await signOut(core, ctx);
|
|
176
|
+
return { ok: true };
|
|
177
|
+
}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import type { FrameworkAdapter } from "../types.js";
|
|
2
|
+
/**
|
|
3
|
+
* Next.js App Router adapter (Next 15+). Works in server actions, route handlers and server components.
|
|
4
|
+
* Server components cannot set cookies, so sign-in and other changes belong in server actions.
|
|
5
|
+
*/
|
|
6
|
+
export declare function nextjs(): FrameworkAdapter;
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import { cookies, headers } from "next/headers";
|
|
2
|
+
import { redirect } from "next/navigation";
|
|
3
|
+
const requests = new WeakMap();
|
|
4
|
+
/**
|
|
5
|
+
* Next.js App Router adapter (Next 15+). Works in server actions, route handlers and server components.
|
|
6
|
+
* Server components cannot set cookies, so sign-in and other changes belong in server actions.
|
|
7
|
+
*/
|
|
8
|
+
export function nextjs() {
|
|
9
|
+
return {
|
|
10
|
+
async getRequest() {
|
|
11
|
+
const incoming = await headers();
|
|
12
|
+
// One Request per incoming request, so the session is read once and cookie changes stay visible.
|
|
13
|
+
let request = requests.get(incoming);
|
|
14
|
+
if (!request) {
|
|
15
|
+
const host = incoming.get("x-forwarded-host") ?? incoming.get("host") ?? "localhost";
|
|
16
|
+
const protocol = incoming.get("x-forwarded-proto") ?? (/^(localhost|127\.0\.0\.1)(:|$)/.test(host) ? "http" : "https");
|
|
17
|
+
// Server actions are POST requests with a `next-action` header. Everything else here renders a page.
|
|
18
|
+
request = new Request(`${protocol}://${host}/`, { method: incoming.has("next-action") ? "POST" : "GET", headers: new Headers(incoming) });
|
|
19
|
+
requests.set(incoming, request);
|
|
20
|
+
}
|
|
21
|
+
return request;
|
|
22
|
+
},
|
|
23
|
+
async setCookie(name, value, options) {
|
|
24
|
+
try {
|
|
25
|
+
(await cookies()).set(name, value, { ...options });
|
|
26
|
+
return true;
|
|
27
|
+
}
|
|
28
|
+
catch {
|
|
29
|
+
// A server component render cannot set cookies. Reads still work; the refresh waits for the next action.
|
|
30
|
+
return false;
|
|
31
|
+
}
|
|
32
|
+
},
|
|
33
|
+
redirect: (to) => redirect(to),
|
|
34
|
+
};
|
|
35
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import type { FrameworkAdapter } from "../types.js";
|
|
2
|
+
/**
|
|
3
|
+
* TanStack Start adapter. Works with 1.131+ (`getWebRequest`) and 1.160+ (`getRequest`).
|
|
4
|
+
* Call auth functions only on the server: in server functions, server routes and `beforeLoad` via a server function.
|
|
5
|
+
*/
|
|
6
|
+
export declare function tanstackStart(): FrameworkAdapter;
|
|
7
|
+
/**
|
|
8
|
+
* Sends the cookies of `auth.withRequest(...)` with the current TanStack Start response.
|
|
9
|
+
* Call it after every `withRequest` read inside a request, or a renewed session never reaches the browser.
|
|
10
|
+
* Returns false outside a request (a script, a test, a WebSocket message).
|
|
11
|
+
*/
|
|
12
|
+
export declare function sendCookies(headers: Headers): boolean;
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import { redirect } from "@tanstack/react-router";
|
|
2
|
+
import * as server from "@tanstack/react-start/server";
|
|
3
|
+
/**
|
|
4
|
+
* TanStack Start adapter. Works with 1.131+ (`getWebRequest`) and 1.160+ (`getRequest`).
|
|
5
|
+
* Call auth functions only on the server: in server functions, server routes and `beforeLoad` via a server function.
|
|
6
|
+
*/
|
|
7
|
+
export function tanstackStart() {
|
|
8
|
+
const module = server;
|
|
9
|
+
const getRequest = module.getRequest ?? module.getWebRequest;
|
|
10
|
+
if (!getRequest)
|
|
11
|
+
throw new Error("@soroi/auth: this TanStack Start version has no getRequest or getWebRequest.");
|
|
12
|
+
return {
|
|
13
|
+
getRequest: () => getRequest(),
|
|
14
|
+
setCookie: (name, value, options) => module.setCookie(name, value, { ...options }),
|
|
15
|
+
redirect: (to) => {
|
|
16
|
+
throw redirect({ href: to });
|
|
17
|
+
},
|
|
18
|
+
getIP: () => module.getRequestIP?.() ?? null,
|
|
19
|
+
};
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* Sends the cookies of `auth.withRequest(...)` with the current TanStack Start response.
|
|
23
|
+
* Call it after every `withRequest` read inside a request, or a renewed session never reaches the browser.
|
|
24
|
+
* Returns false outside a request (a script, a test, a WebSocket message).
|
|
25
|
+
*/
|
|
26
|
+
export function sendCookies(headers) {
|
|
27
|
+
const cookies = headers.getSetCookie();
|
|
28
|
+
if (!cookies.length)
|
|
29
|
+
return true;
|
|
30
|
+
let response;
|
|
31
|
+
try {
|
|
32
|
+
response = server.getResponseHeaders();
|
|
33
|
+
}
|
|
34
|
+
catch {
|
|
35
|
+
return false;
|
|
36
|
+
}
|
|
37
|
+
for (const cookie of cookies)
|
|
38
|
+
response.append("set-cookie", cookie);
|
|
39
|
+
return true;
|
|
40
|
+
}
|
package/dist/cli.d.ts
ADDED
package/dist/cli.js
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
3
|
+
import { resolve } from "node:path";
|
|
4
|
+
import { pathToFileURL } from "node:url";
|
|
5
|
+
import { CORE } from "./index.js";
|
|
6
|
+
const CANDIDATES = [
|
|
7
|
+
"src/auth.ts",
|
|
8
|
+
"src/lib/auth.ts",
|
|
9
|
+
"src/server/auth.ts",
|
|
10
|
+
"lib/auth.ts",
|
|
11
|
+
"server/auth.ts",
|
|
12
|
+
"app/auth.ts",
|
|
13
|
+
"auth.ts",
|
|
14
|
+
"src/auth.js",
|
|
15
|
+
"lib/auth.js",
|
|
16
|
+
];
|
|
17
|
+
const usage = `Usage: soroi-auth <doctor|migrate|secret> [path to the file that exports auth]
|
|
18
|
+
|
|
19
|
+
doctor Checks the config and prints the redirect URIs to register.
|
|
20
|
+
migrate Applies pending migrations (for migrate: "manual").
|
|
21
|
+
secret Prints a new random AUTH_SECRET.
|
|
22
|
+
|
|
23
|
+
Without a path it looks in: ${CANDIDATES.join(", ")}.
|
|
24
|
+
Run it with Bun: bunx --bun soroi-auth doctor`;
|
|
25
|
+
async function loadAuth(file) {
|
|
26
|
+
const module = (await import(pathToFileURL(resolve(file)).href));
|
|
27
|
+
const found = Object.values(module).find((value) => !!value && typeof value === "object" && CORE in value);
|
|
28
|
+
if (!found)
|
|
29
|
+
throw new Error(`${file} exports no object made by createAuth().`);
|
|
30
|
+
return found;
|
|
31
|
+
}
|
|
32
|
+
/** `bunx` and `npx` do not load the app's .env for package binaries. Values already set win. */
|
|
33
|
+
function loadDotEnv(path = ".env") {
|
|
34
|
+
let text;
|
|
35
|
+
try {
|
|
36
|
+
text = readFileSync(resolve(path), "utf8");
|
|
37
|
+
}
|
|
38
|
+
catch {
|
|
39
|
+
return;
|
|
40
|
+
}
|
|
41
|
+
for (const line of text.split(/\r?\n/)) {
|
|
42
|
+
const match = /^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*?)\s*$/.exec(line);
|
|
43
|
+
if (!match || process.env[match[1]] !== undefined)
|
|
44
|
+
continue;
|
|
45
|
+
let value = match[2];
|
|
46
|
+
if ((value.startsWith('"') && value.endsWith('"')) || (value.startsWith("'") && value.endsWith("'")))
|
|
47
|
+
value = value.slice(1, -1);
|
|
48
|
+
else
|
|
49
|
+
value = value.replace(/\s+#.*$/, "");
|
|
50
|
+
process.env[match[1]] = value;
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
loadDotEnv();
|
|
54
|
+
const [command, given] = process.argv.slice(2);
|
|
55
|
+
const file = given ?? CANDIDATES.find((candidate) => existsSync(resolve(candidate))) ?? "src/auth.ts";
|
|
56
|
+
if (command === "secret") {
|
|
57
|
+
const { randomBytes } = await import("node:crypto");
|
|
58
|
+
console.log(randomBytes(32).toString("base64url"));
|
|
59
|
+
}
|
|
60
|
+
else if (command === "doctor") {
|
|
61
|
+
const auth = await loadAuth(file);
|
|
62
|
+
const checks = await auth.doctor();
|
|
63
|
+
for (const check of checks)
|
|
64
|
+
console.log(`${{ ok: "✓", warn: "!", error: "✗" }[check.level]} ${check.message}`);
|
|
65
|
+
process.exit(checks.some((check) => check.level === "error") ? 1 : 0);
|
|
66
|
+
}
|
|
67
|
+
else if (command === "migrate") {
|
|
68
|
+
const auth = await loadAuth(file);
|
|
69
|
+
const applied = await auth.migrate();
|
|
70
|
+
console.log(applied.length ? `Applied migrations: ${applied.join(", ")}` : "No pending migrations.");
|
|
71
|
+
process.exit(0);
|
|
72
|
+
}
|
|
73
|
+
else {
|
|
74
|
+
console.log(usage);
|
|
75
|
+
process.exit(command ? 1 : 0);
|
|
76
|
+
}
|