@somewhere-cloud/cli 0.38.154 → 0.38.155
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/CHANGELOG.md +7 -0
- package/dist/docs/adopt.md +39 -0
- package/dist/docs/analytics.md +161 -0
- package/dist/docs/api-reference.md +339 -0
- package/dist/docs/api-surface.md +2067 -0
- package/dist/docs/app-mcp.md +162 -0
- package/dist/docs/architecture-patterns.md +334 -0
- package/dist/docs/auth-client.md +531 -0
- package/dist/docs/billing.md +76 -0
- package/dist/docs/browser.md +639 -0
- package/dist/docs/calendar.md +298 -0
- package/dist/docs/changes.md +323 -0
- package/dist/docs/cli.md +407 -0
- package/dist/docs/common-mistakes.md +199 -0
- package/dist/docs/connect-agent.md +72 -0
- package/dist/docs/cors.md +114 -0
- package/dist/docs/cron.md +167 -0
- package/dist/docs/database-engine.md +167 -0
- package/dist/docs/declared-data.md +1656 -0
- package/dist/docs/declared-files.md +475 -0
- package/dist/docs/deploy-intelligence.md +188 -0
- package/dist/docs/deploy.md +733 -0
- package/dist/docs/design-system.md +273 -0
- package/dist/docs/dev-environments.md +496 -0
- package/dist/docs/domain-ownership.md +31 -0
- package/dist/docs/domains.md +370 -0
- package/dist/docs/feedback.md +88 -0
- package/dist/docs/file-tools.md +116 -0
- package/dist/docs/functions.md +489 -0
- package/dist/docs/getting-started.md +238 -0
- package/dist/docs/github.md +95 -0
- package/dist/docs/google-calendar.md +212 -0
- package/dist/docs/groups.md +836 -0
- package/dist/docs/guarantees.md +58 -0
- package/dist/docs/handled-for-you.md +224 -0
- package/dist/docs/inspect.md +171 -0
- package/dist/docs/limits.md +68 -0
- package/dist/docs/live-data.md +197 -0
- package/dist/docs/live.md +92 -0
- package/dist/docs/local-dev.md +30 -0
- package/dist/docs/migration-supabase.md +58 -0
- package/dist/docs/payments.md +1102 -0
- package/dist/docs/portability.md +194 -0
- package/dist/docs/postgres.md +301 -0
- package/dist/docs/pricing-comparison.md +42 -0
- package/dist/docs/pricing.md +39 -0
- package/dist/docs/project-groups.md +107 -0
- package/dist/docs/projects.md +380 -0
- package/dist/docs/recipe-ai-agent.md +112 -0
- package/dist/docs/recipe-ai-features.md +227 -0
- package/dist/docs/recipe-ai-receipts.md +783 -0
- package/dist/docs/recipe-background-jobs.md +369 -0
- package/dist/docs/recipe-booking.md +348 -0
- package/dist/docs/recipe-csv-import.md +390 -0
- package/dist/docs/recipe-ecommerce.md +127 -0
- package/dist/docs/recipe-email.md +282 -0
- package/dist/docs/recipe-escalation.md +133 -0
- package/dist/docs/recipe-file-uploads.md +159 -0
- package/dist/docs/recipe-import-app.md +110 -0
- package/dist/docs/recipe-login.md +457 -0
- package/dist/docs/recipe-multi-chat.md +198 -0
- package/dist/docs/recipe-paid-api.md +161 -0
- package/dist/docs/recipe-pdfs.md +205 -0
- package/dist/docs/recipe-push-notifications.md +107 -0
- package/dist/docs/recipe-seo.md +200 -0
- package/dist/docs/recipe-signed-in-app.md +330 -0
- package/dist/docs/render.md +99 -0
- package/dist/docs/rooms.md +554 -0
- package/dist/docs/sdk.md +287 -0
- package/dist/docs/sdks.md +24 -0
- package/dist/docs/search.md +199 -0
- package/dist/docs/security-model.md +168 -0
- package/dist/docs/setup.md +212 -0
- package/dist/docs/smoke.md +102 -0
- package/dist/docs/speed.md +298 -0
- package/dist/docs/sql-compatibility.md +96 -0
- package/dist/docs/sw.agent.md +248 -0
- package/dist/docs/sw.ai.md +1291 -0
- package/dist/docs/sw.auth.md +1811 -0
- package/dist/docs/sw.billing.md +171 -0
- package/dist/docs/sw.db.md +2128 -0
- package/dist/docs/sw.email.md +661 -0
- package/dist/docs/sw.endpoint.md +187 -0
- package/dist/docs/sw.env.md +303 -0
- package/dist/docs/sw.fetch.md +115 -0
- package/dist/docs/sw.fs.md +424 -0
- package/dist/docs/sw.groups.md +836 -0
- package/dist/docs/sw.image.md +69 -0
- package/dist/docs/sw.jobs.md +520 -0
- package/dist/docs/sw.logs.md +61 -0
- package/dist/docs/sw.mail.md +106 -0
- package/dist/docs/sw.notifications.md +78 -0
- package/dist/docs/sw.push.md +161 -0
- package/dist/docs/sw.rateLimit.md +67 -0
- package/dist/docs/sw.web.md +128 -0
- package/dist/docs/tasks.md +269 -0
- package/dist/docs/test.md +220 -0
- package/dist/docs/tool-reference-account.md +7 -0
- package/dist/docs/tool-reference-ai.md +121 -0
- package/dist/docs/tool-reference-analytics.md +37 -0
- package/dist/docs/tool-reference-api.md +19 -0
- package/dist/docs/tool-reference-artifacts.md +35 -0
- package/dist/docs/tool-reference-auth.md +163 -0
- package/dist/docs/tool-reference-browser.md +114 -0
- package/dist/docs/tool-reference-code.md +26 -0
- package/dist/docs/tool-reference-connect.md +21 -0
- package/dist/docs/tool-reference-cron.md +48 -0
- package/dist/docs/tool-reference-db.md +282 -0
- package/dist/docs/tool-reference-domains.md +107 -0
- package/dist/docs/tool-reference-email.md +55 -0
- package/dist/docs/tool-reference-env.md +19 -0
- package/dist/docs/tool-reference-feedback.md +56 -0
- package/dist/docs/tool-reference-fs.md +265 -0
- package/dist/docs/tool-reference-github.md +57 -0
- package/dist/docs/tool-reference-groups.md +85 -0
- package/dist/docs/tool-reference-help.md +29 -0
- package/dist/docs/tool-reference-jobs.md +39 -0
- package/dist/docs/tool-reference-live.md +48 -0
- package/dist/docs/tool-reference-logs.md +16 -0
- package/dist/docs/tool-reference-payments.md +44 -0
- package/dist/docs/tool-reference-project.md +706 -0
- package/dist/docs/tool-reference-push.md +78 -0
- package/dist/docs/tool-reference-rate-limit.md +18 -0
- package/dist/docs/tool-reference-search.md +68 -0
- package/dist/docs/tool-reference-security.md +42 -0
- package/dist/docs/tool-reference-smoke.md +17 -0
- package/dist/docs/tool-reference-stock-photos.md +20 -0
- package/dist/docs/tool-reference-tasks.md +73 -0
- package/dist/docs/tool-reference-telegram.md +32 -0
- package/dist/docs/tool-reference-usage.md +9 -0
- package/dist/docs/tool-reference-web.md +71 -0
- package/dist/docs/tool-reference-webhooks.md +9 -0
- package/dist/docs/troubleshooting.md +411 -0
- package/dist/docs/typed-functions.md +94 -0
- package/dist/docs/verify-before-deploy.md +67 -0
- package/dist/docs/vs-supabase.md +75 -0
- package/dist/docs/vs-vercel.md +103 -0
- package/dist/lib/bundle.js +303 -221
- package/dist/lib/bundle.js.map +3 -3
- package/dist/types/lib/test-session.d.ts +8 -0
- package/npm-shrinkwrap.json +2 -2
- package/package.json +3 -2
|
@@ -0,0 +1,1811 @@
|
|
|
1
|
+
# Auth — End-User Authentication
|
|
2
|
+
|
|
3
|
+
## Auth — sign-in is already part of your app
|
|
4
|
+
|
|
5
|
+
The starter includes sign-in, sign-out and sessions in HttpOnly cookies. Cookie-authenticated browser requests from unapproved origins are rejected before your function runs. Declared `owner()` tables automatically scope normal data operations to the signed-in user.
|
|
6
|
+
|
|
7
|
+
Password sign-in protection and magic links are built in. Keep the starter's auth route and React hooks, then build your app around the verified user from `sw.auth.fromRequest(request)`. No cookie parsing, header slicing or try/catch for expired tokens.
|
|
8
|
+
|
|
9
|
+
The starter's auth is three pieces. `api/auth/[...path].ts` is one line that re-exports the SDK's server route (`export { somewhereAuth as default } from '@somewhere-cloud/sdk/server'`). `src/services/auth.ts` holds the browser client. `src/auth/hooks.ts` holds the React state and actions. Don't write a second set of sign-in or sign-up functions next to them.
|
|
10
|
+
|
|
11
|
+
### Protect a function
|
|
12
|
+
|
|
13
|
+
Add this file to the starter:
|
|
14
|
+
|
|
15
|
+
```ts
|
|
16
|
+
// api/account.ts
|
|
17
|
+
export default async function account(
|
|
18
|
+
request: Request,
|
|
19
|
+
sw: SomewhereRuntimeContext,
|
|
20
|
+
): Promise<Response> {
|
|
21
|
+
const user = await sw.auth.fromRequest(request);
|
|
22
|
+
if (!user) {
|
|
23
|
+
return Response.json({ error: 'Sign in to view your account.' }, { status: 401 });
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
return Response.json({ id: user.id, email: user.email });
|
|
27
|
+
}
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
Deploy, sign in through the starter, then open `/api/account` in the same browser. You get back your account ID and email. Open that path in a signed-out browser and it returns 401.
|
|
31
|
+
|
|
32
|
+
Pair this with an `owner()` table and normal scoped queries return only this user's rows. See [Data](https://somewhere.cloud/docs/declared-data.txt) for the schema and query together.
|
|
33
|
+
|
|
34
|
+
`SomewhereRuntimeContext` comes from the platform's generated TypeScript declarations. You write this function in `api/`, and the starter's `api/auth/[...path].ts` keeps handling sign-in and sign-out.
|
|
35
|
+
|
|
36
|
+
From your UI, a same-origin request uses the browser's session cookie:
|
|
37
|
+
|
|
38
|
+
```ts
|
|
39
|
+
const response = await fetch('/api/account');
|
|
40
|
+
if (response.status === 401) {
|
|
41
|
+
// Show your existing sign-in screen.
|
|
42
|
+
} else if (!response.ok) {
|
|
43
|
+
throw new Error('Could not load your account.');
|
|
44
|
+
} else {
|
|
45
|
+
const account: unknown = await response.json();
|
|
46
|
+
console.log(account);
|
|
47
|
+
}
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
### Sign out
|
|
51
|
+
|
|
52
|
+
The starter's sign-out button is already wired. Use `useSignOut()` from
|
|
53
|
+
`src/auth/hooks.ts` anywhere else you need the same action; see
|
|
54
|
+
`sw.auth` → `logout` for the component and session contract.
|
|
55
|
+
|
|
56
|
+
### Keep identity and data together
|
|
57
|
+
|
|
58
|
+
Use the verified request identity with your declared tables. On an `owner()` table, normal scoped data operations select that user's rows. The Data guide shows the schema and the query together. A privileged server query runs with the authority your handler grants, so authorize its caller before using that path.
|
|
59
|
+
|
|
60
|
+
A signed-in account can have an unverified email address. If an action requires a confirmed address, check `user.email_verified` before performing it. For an administrative action, call `sw.auth.requireUser(request, { role: 'admin' })` before doing the work. It answers 401 for a signed-out caller and 403 for anyone who isn't an admin.
|
|
61
|
+
|
|
62
|
+
Browser writes go through the platform's origin checks. Keep ordinary app requests on the app's own origin, and use the CORS guide when you deliberately add another browser origin. Developer keys belong in developer tooling and server integrations, never in the app's browser code.
|
|
63
|
+
|
|
64
|
+
### Add more only when the app needs it
|
|
65
|
+
|
|
66
|
+
The starter is the default path. Use these existing sections for additional account features:
|
|
67
|
+
|
|
68
|
+
- Password reset: `sw.auth` → `password-reset`.
|
|
69
|
+
- Email verification: `sw.auth` → `email-verification`.
|
|
70
|
+
- Magic links: `sw.auth` → `magic-links`.
|
|
71
|
+
- Social sign-in: `sw.auth` → `social-sign-in`.
|
|
72
|
+
- Visitors who use the app before signing in: `sw.auth` → `visitors`.
|
|
73
|
+
- Browser customization: `auth-client`.
|
|
74
|
+
- Manual token clients: `sw.auth` → `token-refresh`.
|
|
75
|
+
- Sign-out contract: `sw.auth` → `logout`.
|
|
76
|
+
- Find other users by email or ID from server code, for example to add an existing user to a group: `sw.auth.server.listUsers({ emails })` or `listUsers({ ids })`, in `sw.auth` → `member-contacts`. Authorize the caller first. For one known address, use `listUsers({ emails: [email] })` instead of paging the directory.
|
|
77
|
+
|
|
78
|
+
For example, request one section with `docs({ topic: 'sw.auth', section: 'password-reset' })`, or run `somewhere docs sw.auth --section password-reset`. The complete section index stays available with the topic.
|
|
79
|
+
|
|
80
|
+
## Security model (the industry-standard checklist)
|
|
81
|
+
|
|
82
|
+
- **Tenant-scoped signing keys (per-project HKDF derivation).** Each
|
|
83
|
+
project's JWT signing key is derived from a master secret +
|
|
84
|
+
project ID via HKDF-SHA256. A leaked token in project A can't
|
|
85
|
+
forge anything in project B.
|
|
86
|
+
- **Session revocation within 60 seconds.** Signing out clears that
|
|
87
|
+
device's session at once and revokes the app session. Password changes,
|
|
88
|
+
password resets, role changes, bans and revoking all sessions also
|
|
89
|
+
invalidate the user's existing access tokens. The platform checks the
|
|
90
|
+
user's current authorization and session when it verifies a credential and
|
|
91
|
+
may reuse that answer for up to 60 seconds, so a revoked token copied
|
|
92
|
+
elsewhere, or held on another device, stops working within 60 seconds.
|
|
93
|
+
This answer describes identity and session authority only. It carries no
|
|
94
|
+
plan, billing status or entitlement fields. Read billing explicitly with
|
|
95
|
+
`await sw.billing.has(feature)` or `await sw.billing.entitlements()`
|
|
96
|
+
inside an authenticated function. These calls read current entitlements;
|
|
97
|
+
sign-in does not wait for a billing lookup. Payments and plan changes remain
|
|
98
|
+
transactional.
|
|
99
|
+
- **Atomic single-use tokens** for password reset and magic links.
|
|
100
|
+
Consumption uses `UPDATE … WHERE token = ? AND consumed_at IS NULL`
|
|
101
|
+
so two parallel uses can't both succeed. Refresh tokens rotate
|
|
102
|
+
instead (see Token types).
|
|
103
|
+
- **Email sign-in codes (multi-factor sign-in).** The app owner turns them on
|
|
104
|
+
for everyone or lets each user choose; a code sent to the account's email then
|
|
105
|
+
completes every password sign-in. See "Email sign-in codes" below.
|
|
106
|
+
- **Not available:** authenticator-app (TOTP) codes, passkeys, changing a
|
|
107
|
+
signed-in user's profile or email address, in-app user moderation,
|
|
108
|
+
anonymous-account migration and user import/export. See "Not available" below.
|
|
109
|
+
- **OAuth (Google, GitHub, Discord)** as first-class flows — the platform owns the
|
|
110
|
+
callback, sets the cookie, no `passport` boilerplate.
|
|
111
|
+
- **Header-based auto-refresh.** If the access token has expired and
|
|
112
|
+
a refresh token rides along, the platform mints a
|
|
113
|
+
new pair, runs the request under the refreshed identity, and
|
|
114
|
+
returns the new pair on `X-New-Access-Token` /
|
|
115
|
+
`X-New-Refresh-Token`. No 401-loop in your client code.
|
|
116
|
+
- **Built-in per-user scoping** — covered in the `sw.db` topic. The
|
|
117
|
+
structured builder (`sw.db.from/insert/update/remove`) auto-scopes a
|
|
118
|
+
declared owner table to the request's verified identity. In managed mode,
|
|
119
|
+
ordinary `sw.db.query` / `sw.db.batch` calls are refused; adding a
|
|
120
|
+
handwritten `WHERE user_id = ?` does not authorize them. An intentional
|
|
121
|
+
raw read requires `sw.db.server.query` / `sw.db.server.batch` after
|
|
122
|
+
your function authorizes its caller. Those explicit server calls run as
|
|
123
|
+
written, without automatic ownership filtering. See `sw.db` for the
|
|
124
|
+
managed-mode write limits and the separate SQL-mode contract.
|
|
125
|
+
- **Role-based access control (RBAC) — platform layers.** Platform
|
|
126
|
+
admin (`platform_users.is_admin`), project membership
|
|
127
|
+
(`project_collaborators`), API-key authority
|
|
128
|
+
(`developer | admin | cli_pair` via `api_key_authority`), and
|
|
129
|
+
subscription tier all gate what an actor can do. Your app's own
|
|
130
|
+
end-users have a platform-owned `user | admin` role. Enforce it
|
|
131
|
+
server-side with `sw.auth.requireUser(req, { role: 'admin' })`.
|
|
132
|
+
Signup always creates `user`; only owner tooling authenticated by a
|
|
133
|
+
developer key can grant `admin` through `auth_user_update`, so a
|
|
134
|
+
public signup or app-user profile request cannot self-promote.
|
|
135
|
+
|
|
136
|
+
Full reviewer-facing depth: <https://somewhere.cloud/docs/llms.txt>.
|
|
137
|
+
|
|
138
|
+
For agent-driven flows from your tools, the same surface is exposed as
|
|
139
|
+
MCP (auth_signup, auth_login, auth_me, auth_refresh, auth_users_list,
|
|
140
|
+
auth_user_delete, auth_user_update, auth_google_url) and as REST under
|
|
141
|
+
/v1/auth/*.
|
|
142
|
+
|
|
143
|
+
## Token types
|
|
144
|
+
|
|
145
|
+
Every signup/login returns three tokens:
|
|
146
|
+
token — short-lived JWT (1 minute). Used as Bearer on protected
|
|
147
|
+
endpoints. Sent by the browser on every API call.
|
|
148
|
+
refresh_token — 30 days. Rotates on every refresh (below).
|
|
149
|
+
session_token — opaque server-side session. Pass to logout to revoke.
|
|
150
|
+
|
|
151
|
+
Every refresh returns a replacement pair: store both tokens before the next
|
|
152
|
+
request. A just-rotated refresh token is still accepted for a short grace window, so
|
|
153
|
+
concurrent refreshes don't sign the user out: currently 30 seconds on
|
|
154
|
+
`POST /v1/auth/refresh` and 10 seconds on header and cookie auto-refresh.
|
|
155
|
+
Presenting it after its window is treated as reuse: every session and refresh
|
|
156
|
+
token that user has in this project is revoked, and their access tokens stop
|
|
157
|
+
working. Only `POST /v1/auth/refresh` also sends a `refresh_token_reuse` event
|
|
158
|
+
to your auth webhook; auto-refresh sends none. A refresh token issued under
|
|
159
|
+
strict single-use rotation has no window: any second use counts as reuse.
|
|
160
|
+
|
|
161
|
+
The smt_ developer key is for YOUR backend. App-user JWTs are for the
|
|
162
|
+
end user's browser. `sw.auth` holds the developer key for you — you
|
|
163
|
+
never type `smt_` inside a function.
|
|
164
|
+
|
|
165
|
+
## Scoped developer keys
|
|
166
|
+
|
|
167
|
+
Developer keys can be limited to specific API areas at mint time —
|
|
168
|
+
right for CI jobs and single-purpose automations that shouldn't hold
|
|
169
|
+
full account authority:
|
|
170
|
+
|
|
171
|
+
POST /v1/keys
|
|
172
|
+
{ "name": "ci-embeddings", "scopes": ["ai:complete", "db"] }
|
|
173
|
+
→ { id, key: "smt_…", prefix, name, scopes }
|
|
174
|
+
|
|
175
|
+
A scope is the `/v1/…` path with `:` separators — `"db"` covers
|
|
176
|
+
`/v1/db/*`, `"ai:complete"` covers `/v1/ai/complete`. Max 32
|
|
177
|
+
scopes per key. A scoped key calling outside its scopes gets 403
|
|
178
|
+
FORBIDDEN with a message naming the key's scopes and the blocked path.
|
|
179
|
+
Keys minted without `scopes` have full access. The same `scopes`
|
|
180
|
+
field works on `POST /v1/keys/cli-pair` for ephemeral 24h keys.
|
|
181
|
+
|
|
182
|
+
Turn on a second sign-in step under [Signing in](https://somewhere.cloud/app/account/security).
|
|
183
|
+
Then a new account credential (`POST /v1/keys`,
|
|
184
|
+
`POST /v1/keys/cli-pair`, `POST /v1/keys/:id/regenerate`, a CLI or
|
|
185
|
+
device sign-in) is made only from a browser session that passed the
|
|
186
|
+
step; from an existing key, connector or app token these answer 403
|
|
187
|
+
`SECOND_STEP_REQUIRED`. Existing keys keep working for their own calls,
|
|
188
|
+
and an existing CLI sign-in keeps refreshing.
|
|
189
|
+
|
|
190
|
+
## Sign up
|
|
191
|
+
|
|
192
|
+
const { user, token, refresh_token, session_token } = await sw.auth.signup({
|
|
193
|
+
email,
|
|
194
|
+
password,
|
|
195
|
+
display_name, // optional
|
|
196
|
+
locale, // optional, BCP-47 like "en-US"
|
|
197
|
+
timezone, // optional, IANA like "America/Los_Angeles"
|
|
198
|
+
});
|
|
199
|
+
|
|
200
|
+
REST: POST /v1/auth/signup · MCP: auth_signup
|
|
201
|
+
|
|
202
|
+
### What sign-up sends
|
|
203
|
+
|
|
204
|
+
A password sign-up (`sw.auth.signup`, `signupWithCookie`, the REST route or
|
|
205
|
+
`auth_signup`) sends two emails by default:
|
|
206
|
+
|
|
207
|
+
- a **welcome email** (template `welcome`);
|
|
208
|
+
- an **email verification code** (template `email_verification`).
|
|
209
|
+
|
|
210
|
+
Two project settings change this. Set them with `project_update` or
|
|
211
|
+
`PATCH /v1/projects/:id`; both are read back on the project:
|
|
212
|
+
|
|
213
|
+
- `auth_welcome_email: false` stops the welcome email. Nothing else changes.
|
|
214
|
+
- `auth_signup_verification: "on_request"` sends no code at sign-up. Your app
|
|
215
|
+
sends one when it wants with `sw.auth.resendVerification(token)`. The
|
|
216
|
+
default is `"at_signup"`.
|
|
217
|
+
|
|
218
|
+
Neither setting verifies anyone: an address becomes verified only when the
|
|
219
|
+
user enters a code you sent, follows a magic link, or signs in with a
|
|
220
|
+
provider that proves the address. Magic link, Google, GitHub and Discord
|
|
221
|
+
sign-ins send no welcome email.
|
|
222
|
+
|
|
223
|
+
To read these emails while testing, sign up with
|
|
224
|
+
`<name>@<subdomain>.test.somewhere.site`: both land in the project's test
|
|
225
|
+
inbox (`somewhere email test-inbox <address>`) and are never delivered. In
|
|
226
|
+
the live app a real address gets real mail. In a preview, sign-in mail is
|
|
227
|
+
captured and never sent, whatever the address (read it with
|
|
228
|
+
`somewhere preview mail`; see dev-environments).
|
|
229
|
+
|
|
230
|
+
## Log in
|
|
231
|
+
|
|
232
|
+
const { user, token, refresh_token, session_token } = await sw.auth.login({
|
|
233
|
+
email,
|
|
234
|
+
password,
|
|
235
|
+
});
|
|
236
|
+
|
|
237
|
+
REST: POST /v1/auth/login · MCP: auth_login
|
|
238
|
+
|
|
239
|
+
### Automatic password sign-in protection
|
|
240
|
+
|
|
241
|
+
Password sign-in is throttled automatically, including calls through
|
|
242
|
+
`sw.auth.login`, `loginWithCookie`, and the starter's sign-in route.
|
|
243
|
+
No `sw.rateLimit` recipe is needed to turn this protection on:
|
|
244
|
+
|
|
245
|
+
- **Per project and source address:** up to 600 sign-in attempts a minute.
|
|
246
|
+
- **Per project and account (email):** up to 30 sign-in attempts a minute.
|
|
247
|
+
Every attempt counts, whatever the password result.
|
|
248
|
+
- **Repeated wrong passwords:** 10 consecutive wrong passwords lock the account
|
|
249
|
+
for 15 minutes. The lock ends by itself, and a correct password resets the
|
|
250
|
+
count.
|
|
251
|
+
|
|
252
|
+
A refusal returns HTTP 429 with `RATE_LIMITED` and `retry_after_ms`. The
|
|
253
|
+
per-minute limits are approximate: they are counted close to where requests
|
|
254
|
+
arrive, so a burst can briefly pass slightly more than the number shown. The
|
|
255
|
+
address limit uses the address seen by the sign-in endpoint; requests through
|
|
256
|
+
an external proxy can share that address.
|
|
257
|
+
|
|
258
|
+
Additional `sw.rateLimit` rules are for your app's own actions or an
|
|
259
|
+
intentionally stricter policy. They are not required for built-in password
|
|
260
|
+
sign-in and do not replace authorization. See `sw.rateLimit` for examples.
|
|
261
|
+
|
|
262
|
+
## Get the user from a request — start here
|
|
263
|
+
|
|
264
|
+
Return the signed-in user from a protected function. For user-owned rows, see
|
|
265
|
+
`declared-data` and the complete notes example in `sdk`.
|
|
266
|
+
|
|
267
|
+
```typescript
|
|
268
|
+
export default async function (req: Request, sw: SomewhereRuntimeContext) {
|
|
269
|
+
const user = await sw.auth.fromRequest(req)
|
|
270
|
+
if (!user) return Response.json({ error: 'unauthorized' }, { status: 401 })
|
|
271
|
+
|
|
272
|
+
return Response.json({ id: user.id, email: user.email })
|
|
273
|
+
}
|
|
274
|
+
```
|
|
275
|
+
|
|
276
|
+
`fromRequest(req)` reads the `__Host-token` cookie, then
|
|
277
|
+
`Authorization: Bearer <jwt>`, validates it
|
|
278
|
+
(cached) and returns the user object itself — or `null` if no token, the
|
|
279
|
+
token is expired, or the token is invalid. A cookie write without `Origin`
|
|
280
|
+
throws `ORIGIN_REQUIRED`; a foreign `Origin` is refused with 403
|
|
281
|
+
`ORIGIN_NOT_ALLOWED` before your function runs. This
|
|
282
|
+
is the single call you should reach for from every protected function.
|
|
283
|
+
|
|
284
|
+
## The app's owner
|
|
285
|
+
|
|
286
|
+
`user.is_owner` is `true` when the signed-in user is the app's owner: the
|
|
287
|
+
email the app verified for them equals the email of the Somewhere account
|
|
288
|
+
that owns the project. Check it instead of writing the owner's email into
|
|
289
|
+
code.
|
|
290
|
+
|
|
291
|
+
```typescript
|
|
292
|
+
export default async function (req: Request, sw: SomewhereRuntimeContext) {
|
|
293
|
+
const user = await sw.auth.requireUser(req)
|
|
294
|
+
if (!user.is_owner) return Response.json({ error: 'owner only' }, { status: 403 })
|
|
295
|
+
return Response.json({ ok: true })
|
|
296
|
+
}
|
|
297
|
+
```
|
|
298
|
+
|
|
299
|
+
It is decided on every request; the owner's email is re-read at least once a
|
|
300
|
+
minute, so a project hand-over moves it to the new owner. Previews behave the
|
|
301
|
+
same way. In a preview, anyone working on the project can act as the app's owner. It is `false` when the user's email was typed and never verified
|
|
302
|
+
(an emailed code or link, or a provider that confirms the address, verifies
|
|
303
|
+
it), when they changed their email and have not verified the new one, when
|
|
304
|
+
the address differs other than by A-to-Z case (no plus-address or dot matching, and an address with non-ASCII characters never counts),
|
|
305
|
+
for editors and other collaborators, and when the owner's Somewhere account
|
|
306
|
+
email is not verified. If your app never verifies emails, nobody is the
|
|
307
|
+
owner. For rows, use `appOwner()` in `db/schema.ts` (see `declared-data` →
|
|
308
|
+
`rows-for-the-apps-owner`).
|
|
309
|
+
|
|
310
|
+
## Lower-level: validate a token you already pulled
|
|
311
|
+
|
|
312
|
+
const { user } = await sw.auth.me(jwt);
|
|
313
|
+
|
|
314
|
+
Use this only when you already extracted the JWT yourself (e.g. from a
|
|
315
|
+
non-standard header, a query param, a WebSocket subprotocol). For 99 %
|
|
316
|
+
of routes, prefer `fromRequest` — it does the extraction + validation
|
|
317
|
+
in one call.
|
|
318
|
+
|
|
319
|
+
`me` throws `AUTH_INVALID_CREDS` if the token is bad. Returns
|
|
320
|
+
`{ user: { id, email, email_verified, display_name, locale?, timezone?, ... } }`.
|
|
321
|
+
This is an identity/profile response. It does not contain `plan`,
|
|
322
|
+
`plan_status` or `entitlements`. Never infer free access from their absence.
|
|
323
|
+
Use `await sw.billing.has(feature)` inside the function that performs a paid
|
|
324
|
+
operation. For a plan label or feature list, read
|
|
325
|
+
`await sw.billing.entitlements()` from an authenticated function and send
|
|
326
|
+
only the needed observation to the browser. Keep loading or unavailable
|
|
327
|
+
billing separate from a confirmed free plan. Test purchases remain separate
|
|
328
|
+
from live access. See `payments` for checkout.
|
|
329
|
+
|
|
330
|
+
REST: GET /v1/auth/me with the user JWT in Authorization · MCP: auth_me
|
|
331
|
+
|
|
332
|
+
## Browser sessions — use httpOnly cookies, not tokens
|
|
333
|
+
|
|
334
|
+
Browser apps should hold NO tokens at all: the happy path is cookie
|
|
335
|
+
sessions — your backend calls `sw.auth.loginWithCookie` and the platform
|
|
336
|
+
sets the session as httpOnly cookies the browser owns. Zero client auth
|
|
337
|
+
code, nothing in localStorage, XSS can't steal what JS can't read, and
|
|
338
|
+
the session refreshes server-side automatically.
|
|
339
|
+
`docs({ topic: 'auth-client' })` has the exact code to paste.
|
|
340
|
+
|
|
341
|
+
The full cookie-session surface (all on the runtime):
|
|
342
|
+
|
|
343
|
+
| Call | Resolves to | Checked example |
|
|
344
|
+
|---|---|---|
|
|
345
|
+
| `loginWithCookie(req, email, password)` | `{ user }`; for an account with email sign-in codes, `{ mfa_required: true, mfa_token, methods: ['email'] }` and no session: `sw.auth.mfa.challengeWithCookie({ mfa_token, code })` completes it | — |
|
|
346
|
+
| `signupWithCookie(req, { email, password, display_name })` | `{ user }` | — |
|
|
347
|
+
| `googleCallbackWithCookie(req, redirectTo)` | a 302 to `redirectTo` (default `/`) after a completed sign-in; for an account with email sign-in codes (or under `required`), a 200 JSON `{ mfa_required: true, mfa_token }` and no cookies: `sw.auth.mfa.challengeWithCookie({ mfa_token, code })` completes it | `api/auth-callback.ts` ("Social OAuth") |
|
|
348
|
+
| `logoutWithCookie(req)` | `{ ok: true }` after server revocation; clears the account cookies | `api/sign-out.ts` ("Logout") |
|
|
349
|
+
| `setSessionCookies(access, refresh)`, `clearSessionCookies()` | stage or clear the cookies only | — |
|
|
350
|
+
|
|
351
|
+
A successful `loginWithCookie` or `signupWithCookie` resolves to a WRAPPER,
|
|
352
|
+
`{ user }`, never the bare user: read `user.email` from it (`id`, `email`,
|
|
353
|
+
`role`, `display_name`, null until set). `signupWithCookie` also accepts
|
|
354
|
+
`(req, email, password)`, `(req, email, password, { display_name })` and
|
|
355
|
+
`({ email, password, display_name })` with req omitted. The two lower-level
|
|
356
|
+
primitives are for backends that already hold a token pair (after
|
|
357
|
+
`verifyOtp`) and want THAT session as cookies; they do not perform the
|
|
358
|
+
visitor completion the helpers do.
|
|
359
|
+
|
|
360
|
+
On success, those sign-in helpers return `{ user }` and attach protected session cookies to the response. The bearer signup/login methods return tokens instead. Expected signup and login failures retain their structured status and message.
|
|
361
|
+
|
|
362
|
+
**An account with email sign-in codes finishes signing in with the code.** Its
|
|
363
|
+
password sign-in answers `{ mfa_required: true, mfa_token, methods: ['email'] }`
|
|
364
|
+
and issues no session; a 6-digit code goes to its email. Check `mfa_required`
|
|
365
|
+
before reading `user`, ask for the code, and pass it to
|
|
366
|
+
`sw.auth.mfa.challengeWithCookie({ mfa_token, code })`. Its Google, GitHub and
|
|
367
|
+
Discord sign-in answer the same code step (the provider is the first factor; a
|
|
368
|
+
first Google, GitHub or Discord sign-up under `required` gets the enrolling code
|
|
369
|
+
step and no session). Its sign-in link, invitation and MCP sign-in are refused
|
|
370
|
+
(403 `AUTH_MFA_METHOD_NOT_ALLOWED`), because the code is only checked after a
|
|
371
|
+
first factor that is not the inbox. See "Email sign-in codes".
|
|
372
|
+
|
|
373
|
+
**No session credentials are exposed to browser JAVASCRIPT.** The access and
|
|
374
|
+
refresh tokens travel to the browser as httpOnly cookies, which it stores and
|
|
375
|
+
sends but your page cannot read.
|
|
376
|
+
|
|
377
|
+
Cookie-authed requests are origin-checked server-side: a cross-origin
|
|
378
|
+
page can't ride the cookies into your API (blocked attempts log
|
|
379
|
+
loudly). `fromRequest` auto-refreshes expired cookie sessions and
|
|
380
|
+
re-issues the cookies, so users stay signed in across browser restarts.
|
|
381
|
+
|
|
382
|
+
The generated data endpoint `/__sw/data` has its own Origin requirement:
|
|
383
|
+
every call is a POST and must name the app's own Origin, including list/get
|
|
384
|
+
reads authenticated with an app-user Bearer token. Browsers send it
|
|
385
|
+
automatically; scripts must set the `Origin` header explicitly.
|
|
386
|
+
|
|
387
|
+
### Account changes with a cookie session
|
|
388
|
+
|
|
389
|
+
Use the request itself for account settings. The helper reads the session,
|
|
390
|
+
checks the Origin and keeps refreshed credentials in HttpOnly cookies.
|
|
391
|
+
Account changes accept POST, PUT, PATCH or DELETE; GET and HEAD return 405.
|
|
392
|
+
|
|
393
|
+
- Password: `updatePasswordWithCookie(req, { current_password, new_password })`.
|
|
394
|
+
- Delete the account: `deleteUserWithCookie(req)`.
|
|
395
|
+
|
|
396
|
+
Changing a signed-in user's profile or email address is not available
|
|
397
|
+
(see "Not available").
|
|
398
|
+
|
|
399
|
+
A successful password change or account deletion ends the account's sessions
|
|
400
|
+
and clears its cookies. A refused change keeps the session, including any
|
|
401
|
+
refreshed cookies; your app never needs the session token.
|
|
402
|
+
|
|
403
|
+
## Header-based auto-refresh (manual token mode)
|
|
404
|
+
|
|
405
|
+
For clients that DO hold tokens — native apps, CLIs and other
|
|
406
|
+
non-browser runtimes — tell the client to send both tokens on every
|
|
407
|
+
request:
|
|
408
|
+
|
|
409
|
+
Authorization: Bearer <access>
|
|
410
|
+
X-Refresh-Token: <refresh>
|
|
411
|
+
|
|
412
|
+
When the access token has expired the platform mints a fresh pair,
|
|
413
|
+
runs the request under the refreshed identity, and returns the new
|
|
414
|
+
pair on the response:
|
|
415
|
+
|
|
416
|
+
X-New-Access-Token: <new-access>
|
|
417
|
+
X-New-Refresh-Token: <new-refresh>
|
|
418
|
+
|
|
419
|
+
The client persists the new pair and moves on — no 401-handling loop.
|
|
420
|
+
Inside deployed functions `sw.auth.fromRequest(req)` does the same
|
|
421
|
+
dance automatically for a header session and the platform attaches the
|
|
422
|
+
X-New-* headers to your function's response. Cookie sessions receive only
|
|
423
|
+
HttpOnly cookies; these token headers are removed. Per-request opt-out: `X-No-Auto-Refresh: 1`.
|
|
424
|
+
|
|
425
|
+
Two flavors for guarded handlers:
|
|
426
|
+
|
|
427
|
+
```ts
|
|
428
|
+
// api/greeting.ts
|
|
429
|
+
export default async function (req: Request, sw: SomewhereRuntimeContext) {
|
|
430
|
+
// Returns the user OR null — use when the route works for anonymous
|
|
431
|
+
// visitors too (e.g. a feed that personalizes when signed in).
|
|
432
|
+
const user = await sw.auth.fromRequest(req);
|
|
433
|
+
return Response.json({ greeting: user ? 'Welcome back, ' + (user.display_name ?? user.email) : 'Welcome' });
|
|
434
|
+
}
|
|
435
|
+
```
|
|
436
|
+
|
|
437
|
+
```ts
|
|
438
|
+
// api/me.ts
|
|
439
|
+
export default async function (req: Request, sw: SomewhereRuntimeContext) {
|
|
440
|
+
// Throws 401 if not signed in — use when the route requires auth.
|
|
441
|
+
// The handler shim converts the thrown error into a 401 response.
|
|
442
|
+
const user = await sw.auth.requireUser(req);
|
|
443
|
+
return Response.json({ id: user.id, email: user.email, email_verified: user.email_verified });
|
|
444
|
+
}
|
|
445
|
+
```
|
|
446
|
+
|
|
447
|
+
```ts
|
|
448
|
+
// api/admin/whoami.ts
|
|
449
|
+
export default async function (req: Request, sw: SomewhereRuntimeContext) {
|
|
450
|
+
// Throws 403 unless the platform-owned app-user role is admin.
|
|
451
|
+
const admin = await sw.auth.requireUser(req, { role: 'admin' });
|
|
452
|
+
return Response.json({ admin: admin.id });
|
|
453
|
+
}
|
|
454
|
+
```
|
|
455
|
+
|
|
456
|
+
Enrichment (optional 2nd arg) — most apps follow up fromRequest with
|
|
457
|
+
a SELECT against their own SQL user table to pull app-specific fields.
|
|
458
|
+
Pass `enrichFrom` to perform that lookup in one database call. In an app with
|
|
459
|
+
separate databases, enrichment reads the production SQL database:
|
|
460
|
+
|
|
461
|
+
```ts
|
|
462
|
+
// api/me-enriched.ts
|
|
463
|
+
export default async function (req: Request, sw: SomewhereRuntimeContext) {
|
|
464
|
+
const me = await sw.auth.requireUser(req, {
|
|
465
|
+
enrichFrom: 'members', // your table
|
|
466
|
+
fields: ['display_color'], // optional, default *
|
|
467
|
+
on: 'id', // optional, default 'id' (matches user.id)
|
|
468
|
+
})
|
|
469
|
+
// me = { id, email, ...platform fields..., display_color }
|
|
470
|
+
return Response.json(me)
|
|
471
|
+
}
|
|
472
|
+
```
|
|
473
|
+
|
|
474
|
+
Platform fields always win on a name collision (id/email/etc), and a
|
|
475
|
+
missing table or column logs server-side without throwing — your
|
|
476
|
+
handler still gets the unenriched user back.
|
|
477
|
+
|
|
478
|
+
Use cookie sessions for browser apps, as the starter's sign-in does. The headers above are for non-browser token
|
|
479
|
+
clients — native apps, CLIs and servers — which persist each new pair as
|
|
480
|
+
described.
|
|
481
|
+
|
|
482
|
+
## Refresh expired token
|
|
483
|
+
|
|
484
|
+
const { access_token, refresh_token, expires_in } = await sw.auth.refresh({
|
|
485
|
+
refresh_token,
|
|
486
|
+
});
|
|
487
|
+
|
|
488
|
+
Store the new pair right away: the old refresh token is accepted again only
|
|
489
|
+
within the rotation window described under Token types.
|
|
490
|
+
Use cookie sessions for browser apps. In manual token mode, prefer the
|
|
491
|
+
header-based refresh flow above — explicit
|
|
492
|
+
`/v1/auth/refresh` is for non-browser SDKs or clients that want to
|
|
493
|
+
control rotation manually.
|
|
494
|
+
|
|
495
|
+
REST: POST /v1/auth/refresh
|
|
496
|
+
|
|
497
|
+
## Password reset flow
|
|
498
|
+
|
|
499
|
+
The reset email links to `/reset-password?token=…` on your app. That page
|
|
500
|
+
reads `token` from the URL and posts it with the new password.
|
|
501
|
+
|
|
502
|
+
```ts
|
|
503
|
+
// api/forgot-password.ts — the page posts { email }
|
|
504
|
+
export default async function (req: Request, sw: SomewhereRuntimeContext) {
|
|
505
|
+
if (req.method !== 'POST') return new Response('Use POST.', { status: 405, headers: { Allow: 'POST' } });
|
|
506
|
+
const input: unknown = await req.json().catch(() => null);
|
|
507
|
+
const email = typeof input === 'object' && input !== null && 'email' in input ? input.email : undefined;
|
|
508
|
+
if (typeof email !== 'string' || !email.trim()) return Response.json({ error: 'Email is required.' }, { status: 400 });
|
|
509
|
+
|
|
510
|
+
// Request a reset email; the reply does not reveal whether the account exists.
|
|
511
|
+
const { message } = await sw.auth.forgot({ email });
|
|
512
|
+
return Response.json({ message });
|
|
513
|
+
}
|
|
514
|
+
```
|
|
515
|
+
|
|
516
|
+
```ts
|
|
517
|
+
// api/reset-password.ts — the /reset-password page posts { token, new_password }
|
|
518
|
+
export default async function (req: Request, sw: SomewhereRuntimeContext) {
|
|
519
|
+
if (req.method !== 'POST') return new Response('Use POST.', { status: 405, headers: { Allow: 'POST' } });
|
|
520
|
+
const input: unknown = await req.json().catch(() => null);
|
|
521
|
+
const token = typeof input === 'object' && input !== null && 'token' in input ? input.token : undefined;
|
|
522
|
+
const newPassword = typeof input === 'object' && input !== null && 'new_password' in input ? input.new_password : undefined;
|
|
523
|
+
if (typeof token !== 'string' || typeof newPassword !== 'string') {
|
|
524
|
+
return Response.json({ error: 'The reset link token and a new password are required.' }, { status: 400 });
|
|
525
|
+
}
|
|
526
|
+
|
|
527
|
+
// Step 2 — user clicks the email link, your form posts the token + new pw.
|
|
528
|
+
const { message } = await sw.auth.reset({ token, new_password: newPassword });
|
|
529
|
+
return Response.json({ message });
|
|
530
|
+
}
|
|
531
|
+
```
|
|
532
|
+
|
|
533
|
+
A reset refuses common or too-short passwords and signs the user out on
|
|
534
|
+
every device within 60 seconds; an invalid, used or expired token is refused with
|
|
535
|
+
`AUTH_INVALID_CREDS`.
|
|
536
|
+
|
|
537
|
+
REST: POST /v1/auth/forgot, POST /v1/auth/reset
|
|
538
|
+
|
|
539
|
+
## Email verification
|
|
540
|
+
|
|
541
|
+
`sw.auth.signup` sends a 6-digit code to the user's email on success,
|
|
542
|
+
unless the project sets `auth_signup_verification: "on_request"` (see "What
|
|
543
|
+
sign-up sends"); then your app sends the first code with
|
|
544
|
+
`resendVerification`. The full surface, for
|
|
545
|
+
clients that hold tokens (a cookie-session app uses the handler under "With a
|
|
546
|
+
cookie session" below):
|
|
547
|
+
|
|
548
|
+
```ts
|
|
549
|
+
// api/_lib/email-verification-token.ts — token mode: `token` is the user's own access token
|
|
550
|
+
// Re-send a 6-digit code (15 min expiry).
|
|
551
|
+
export function requestCode(sw: SomewhereRuntimeContext, token: string) {
|
|
552
|
+
return sw.auth.requestEmailVerification(token);
|
|
553
|
+
}
|
|
554
|
+
|
|
555
|
+
// User types the code into your form; you verify it.
|
|
556
|
+
export function verifyCode(sw: SomewhereRuntimeContext, token: string, code: string) {
|
|
557
|
+
return sw.auth.verifyEmail(token, { code });
|
|
558
|
+
}
|
|
559
|
+
|
|
560
|
+
// Or — resend the email if it didn't arrive.
|
|
561
|
+
export function resendCode(sw: SomewhereRuntimeContext, token: string) {
|
|
562
|
+
return sw.auth.resendVerification(token);
|
|
563
|
+
}
|
|
564
|
+
```
|
|
565
|
+
|
|
566
|
+
Which code works: **the most recently requested one.** Requesting again does
|
|
567
|
+
not withdraw the previous code by itself; the newer code replaces it once the
|
|
568
|
+
newer send is accepted and installed, so an email that arrives late may carry
|
|
569
|
+
a code that no longer works. Do not assume any particular received code is
|
|
570
|
+
still valid. A new request never extends the expiry of an earlier code, and
|
|
571
|
+
the platform never re-sends on its own after an uncertain delivery — request
|
|
572
|
+
again. A request made from a signed-in session is bound to that session while
|
|
573
|
+
it is still pending: if that session is revoked or ends before the code has
|
|
574
|
+
been installed, that request never installs its code, and a current session
|
|
575
|
+
has to request a new one. A code that has already been installed is not
|
|
576
|
+
affected by a later session change and can be verified from any current
|
|
577
|
+
session of the same user.
|
|
578
|
+
|
|
579
|
+
### With a cookie session
|
|
580
|
+
|
|
581
|
+
In a cookie-session app the page never holds a token. The packaged route
|
|
582
|
+
`api/auth/[...path].ts` (`@somewhere-cloud/sdk` 0.11.6 and later) serves
|
|
583
|
+
`GET /api/auth/verify-email` (`{ email_verified }`),
|
|
584
|
+
`POST /api/auth/request-email-verification` and `POST /api/auth/verify-email`,
|
|
585
|
+
taking the account from the session cookie. The page uses the starter's client:
|
|
586
|
+
`await auth.requestEmailVerification()`, then
|
|
587
|
+
`await auth.verifyEmail({ code })`; `await auth.emailVerified()` says whether
|
|
588
|
+
to show the prompt. The starter's "Verify your email" panel does exactly this.
|
|
589
|
+
|
|
590
|
+
Without the SDK route, the same is one function:
|
|
591
|
+
|
|
592
|
+
```ts
|
|
593
|
+
// api/auth/verify-email.ts — POST {} emails a code; POST { code } verifies it
|
|
594
|
+
export default async function (req: Request, sw: SomewhereRuntimeContext): Promise<Response> {
|
|
595
|
+
if (req.method !== 'POST') return new Response(null, { status: 405, headers: { Allow: 'POST' } });
|
|
596
|
+
const { code } = (await req.json().catch(() => ({}))) as { code?: string };
|
|
597
|
+
return Response.json(code === undefined
|
|
598
|
+
? await sw.auth.requestEmailVerificationWithCookie(req)
|
|
599
|
+
: await sw.auth.verifyEmailWithCookie(req, { code }));
|
|
600
|
+
}
|
|
601
|
+
```
|
|
602
|
+
|
|
603
|
+
Either way: signed out → 401 `AUTH_REQUIRED`; a code that is not 6 digits → 400
|
|
604
|
+
`VALIDATION_ERROR` before any platform call; a code issued to another account
|
|
605
|
+
does not verify this one. `sw.auth.requireUser(req)` returns
|
|
606
|
+
`email_verified` for showing the prompt.
|
|
607
|
+
|
|
608
|
+
### Keeping your password
|
|
609
|
+
|
|
610
|
+
To keep the password created at sign-up, verify the email with the six-digit
|
|
611
|
+
code while signed in. The starter's "Verify your email" panel does this.
|
|
612
|
+
|
|
613
|
+
If an unverified address is first verified by a sign-in link, an invitation
|
|
614
|
+
link, or Google, GitHub or Discord with a verified email, the platform clears
|
|
615
|
+
earlier sign-in methods and other sessions. This prevents someone who
|
|
616
|
+
registered another person's address from retaining access. The email owner
|
|
617
|
+
stays signed in. To add a password afterwards, use the password reset flow
|
|
618
|
+
(`docs({ topic: 'sw.auth', section: 'password-reset' })`).
|
|
619
|
+
|
|
620
|
+
This clears the earlier password, other linked social sign-ins, other sessions, and pending
|
|
621
|
+
sign-in links, password resets, email changes and verification codes. The
|
|
622
|
+
social sign-in used to verify the address is kept. The account ID, data, role
|
|
623
|
+
and profile stay unchanged. For an already verified account, opening a link
|
|
624
|
+
preserves the existing sign-in methods.
|
|
625
|
+
Recovery immediately retires old sessions, passwords, second-step and refresh credentials; an already issued access token may still work until its original expiry, at most 60 seconds from issuance, and recovery never extends that expiry.
|
|
626
|
+
|
|
627
|
+
## Magic links (passwordless sign-in)
|
|
628
|
+
|
|
629
|
+
For users who don't want a password (or forgot it). `signInWithOtp`
|
|
630
|
+
emails a one-click link; `verifyOtp` exchanges the token for a session
|
|
631
|
+
the same shape as `login`.
|
|
632
|
+
|
|
633
|
+
Step 1: request the link. In the starter, `sendSignInLink` in
|
|
634
|
+
`src/services/sign-in-link.ts` (`recipe-login`) posts to the packaged
|
|
635
|
+
`/api/auth/magic-link` route; in a function of your own, call
|
|
636
|
+
`sw.auth.signInWithOtp({ email, redirect_uri? })`. It emails a 15-min
|
|
637
|
+
single-use sign-in link and creates a pending account for a new address.
|
|
638
|
+
An accepted request answers with the same message whether or not the address
|
|
639
|
+
already has an account, and a pending send answers `status: 'pending'`.
|
|
640
|
+
Repeated requests for one address can receive that same reply without
|
|
641
|
+
sending another email. Suppressed addresses, paused sending and failed sends return errors.
|
|
642
|
+
When delivery could not be confirmed, check the inbox before requesting another link. Auth emails are exempt from the plan's email quota;
|
|
643
|
+
abuse protections still apply.
|
|
644
|
+
|
|
645
|
+
Step 2: the link lands on your /auth/magic page. Use the current SDK/starter to redeem it, or the manual callback example below.
|
|
646
|
+
|
|
647
|
+
To have a visitor confirm something by email (a booking, an RSVP, an
|
|
648
|
+
order) rather than sign in, pass `purpose: 'confirm'`. The link, its expiry,
|
|
649
|
+
redemption and limits are the same; the email reads "Please confirm your
|
|
650
|
+
request with {project}" with a **Confirm** button instead of "Sign in". After
|
|
651
|
+
redemption the visitor is a verified user of your app, so `sw.email.send` can
|
|
652
|
+
email them the confirmation.
|
|
653
|
+
|
|
654
|
+
```js
|
|
655
|
+
await sw.auth.signInWithOtp({ email, redirect_uri: `${origin}/confirm?b=${bookingId}`, purpose: 'confirm' })
|
|
656
|
+
```
|
|
657
|
+
|
|
658
|
+
REST: POST /v1/auth/magic-link, POST /v1/auth/magic-link/verify
|
|
659
|
+
MCP: auth_send_magic_link, auth_verify_magic_link
|
|
660
|
+
|
|
661
|
+
On an account whose email is not verified yet, the first verification by a
|
|
662
|
+
sign-in link clears earlier sign-in methods (`docs({ topic: 'sw.auth', section: 'keeping-your-password' })`).
|
|
663
|
+
|
|
664
|
+
How the link works (contract, verified against the route): `sw.auth.signInWithOtp({ email, redirect_uri? })`
|
|
665
|
+
emails a single-use link, valid 15 minutes, that points at YOUR app:
|
|
666
|
+
`https://<your-subdomain>.somewhere.site/auth/magic?token=…` (plus
|
|
667
|
+
`&redirect_uri=…` when you passed one). Your app must serve that
|
|
668
|
+
`/auth/magic` page: it reads `token` from the query and POSTs it to your
|
|
669
|
+
server handler, which calls `sw.auth.verifyOtp` (REST
|
|
670
|
+
`POST /v1/auth/magic-link/verify`). A completed response returns the normal
|
|
671
|
+
login shape. An account with email sign-in codes is refused (403
|
|
672
|
+
`AUTH_MFA_METHOD_NOT_ALLOWED`), no session is issued and the link is not spent:
|
|
673
|
+
it signs in with its password and a code. Both include the
|
|
674
|
+
`redirect_uri` you originally passed, or null — there is no platform
|
|
675
|
+
default destination: with no `redirect_uri` the app decides where to go
|
|
676
|
+
after `/auth/magic`. `redirect_uri` is validated when the link is
|
|
677
|
+
requested: its origin must be the project's somewhere.site address, its
|
|
678
|
+
somewhere.cloud address, the project's owner-gated `-dev` host, a verified
|
|
679
|
+
custom domain attached to the project, or a localhost dev origin
|
|
680
|
+
(`http://localhost:5173`, `:5174`, `:3000`, `http://127.0.0.1:5173`);
|
|
681
|
+
anything else is refused with `VALIDATION_ERROR`. A first-time address has
|
|
682
|
+
its app user created as PENDING when the link is REQUESTED; signing in with a
|
|
683
|
+
magic link requires a successful redemption, which verifies the address and
|
|
684
|
+
signs the user in. Redemption consumes the exact issued identity and commits
|
|
685
|
+
proof and session together.
|
|
686
|
+
Mirrors are best effort and an already committed sign-in is not undone. A
|
|
687
|
+
link is bound to the email it was issued for; if the account's email changes
|
|
688
|
+
before redemption, the link is no longer valid. If redemption cannot determine
|
|
689
|
+
its outcome, the response is `AUTH_SIGN_IN_OUTCOME_UNKNOWN` (503,
|
|
690
|
+
`retry: false`): do not resubmit the same token, request a new link.
|
|
691
|
+
|
|
692
|
+
**Cookies are queued, not returned.** `sw.auth.setSessionCookies(token,
|
|
693
|
+
refresh_token)` returns `undefined`: it queues the `Set-Cookie` headers
|
|
694
|
+
and the platform attaches them to whatever Response your function returns.
|
|
695
|
+
Do not build cookie headers by hand and do not expect a value back. The
|
|
696
|
+
canonical access field on a sign-in result is `token` (the runtime also
|
|
697
|
+
tolerates `access_token` from older bundles); the refresh field is
|
|
698
|
+
`refresh_token`.
|
|
699
|
+
|
|
700
|
+
**Manual callback bridge.** The emailed link lands on
|
|
701
|
+
YOUR route `/auth/magic?token=…`, always on the project's somewhere.site
|
|
702
|
+
origin. That page posts the token once to your API function; the function
|
|
703
|
+
verifies and queues cookies only after a completed session. The advisor
|
|
704
|
+
renders the same manual example (`magic-link-browser`).
|
|
705
|
+
|
|
706
|
+
```ts
|
|
707
|
+
// api/auth/magic.ts
|
|
708
|
+
export default async function (req: Request, sw: SomewhereRuntimeContext) {
|
|
709
|
+
if (req.method !== 'POST') return new Response('method not allowed', { status: 405 });
|
|
710
|
+
const body = await req.json().catch(() => null);
|
|
711
|
+
if (!body || typeof body.token !== 'string' || !body.token) {
|
|
712
|
+
return new Response('request a new sign-in link', { status: 400 });
|
|
713
|
+
}
|
|
714
|
+
try {
|
|
715
|
+
const session = await sw.auth.verifyOtp({ token: body.token });
|
|
716
|
+
if (session.mfa_required) return Response.json({ mfa_required: true, mfa_token: session.mfa_token }, { headers: { 'Cache-Control': 'no-store' } });
|
|
717
|
+
sw.auth.setSessionCookies(session.token, session.refresh_token);
|
|
718
|
+
const destination = new URL(session.redirect_uri ?? '/', req.url);
|
|
719
|
+
// This example intentionally navigates only within the app.
|
|
720
|
+
const redirect = destination.origin === new URL(req.url).origin &&
|
|
721
|
+
destination.pathname !== '/auth/magic' ? destination.pathname + destination.search + destination.hash : '/';
|
|
722
|
+
return Response.json({ redirect });
|
|
723
|
+
} catch {
|
|
724
|
+
return new Response('request a new sign-in link', { status: 400 });
|
|
725
|
+
}
|
|
726
|
+
}
|
|
727
|
+
```
|
|
728
|
+
|
|
729
|
+
```ts
|
|
730
|
+
// src/auth/magic.ts
|
|
731
|
+
// Call only from the Continue button's click handler on /auth/magic, never on
|
|
732
|
+
// render or in an effect: a link preview or mail scanner that loads the page
|
|
733
|
+
// must not spend the one-time token. A second press finds no token.
|
|
734
|
+
export async function completeMagicLink() {
|
|
735
|
+
const token = new URLSearchParams(location.search).get('token');
|
|
736
|
+
history.replaceState(null, '', '/auth/magic');
|
|
737
|
+
if (!token) return 'Request a new sign-in link.';
|
|
738
|
+
try {
|
|
739
|
+
const response = await fetch('/api/auth/magic', {
|
|
740
|
+
method: 'POST', credentials: 'include',
|
|
741
|
+
headers: { 'content-type': 'application/json' }, body: JSON.stringify({ token }),
|
|
742
|
+
});
|
|
743
|
+
if (!response.ok) return 'Request a new sign-in link.';
|
|
744
|
+
const answer = await response.json();
|
|
745
|
+
if (answer.mfa_required) return 'Sign-in needs an authenticator or backup code. This page cannot complete that step.';
|
|
746
|
+
const { redirect } = answer;
|
|
747
|
+
const destination = new URL(redirect, location.origin);
|
|
748
|
+
location.assign(destination.origin === location.origin && destination.pathname !== '/auth/magic'
|
|
749
|
+
? destination.href : '/');
|
|
750
|
+
} catch {
|
|
751
|
+
return 'Request a new sign-in link.';
|
|
752
|
+
}
|
|
753
|
+
}
|
|
754
|
+
```
|
|
755
|
+
|
|
756
|
+
Contract and pitfalls the recipe encodes:
|
|
757
|
+
|
|
758
|
+
- **Response contract:** a completed sign-in answers `200` with
|
|
759
|
+
`{ redirect }` and session cookies. A non-2xx does not by itself say why: the link may
|
|
760
|
+
be invalid or expired, or the platform may have been unable to complete the
|
|
761
|
+
sign-in (`503 AUTH_SIGN_IN_OUTCOME_UNKNOWN`, or an ordinary provider or
|
|
762
|
+
database failure). Never send the same token again — it is single-use and
|
|
763
|
+
may already be consumed; the page makes one request and offers a new link.
|
|
764
|
+
- **The destination is never a body value.** Only the `redirect_uri` the
|
|
765
|
+
platform validated when the link was requested, or the site root — and only
|
|
766
|
+
within the app's own origin, never back to `/auth/magic`. A body-supplied
|
|
767
|
+
URL is an open redirect.
|
|
768
|
+
- **Same origin only, and custom domains land on the subdomain.** The link is
|
|
769
|
+
built on the somewhere.site origin even when your app also serves a custom
|
|
770
|
+
domain, and session cookies are host-scoped. A validated destination on the
|
|
771
|
+
custom domain would arrive without the session. Keep the destination on the
|
|
772
|
+
origin that verified the token.
|
|
773
|
+
- **Read the incoming token under a different name than the result's
|
|
774
|
+
`token`** — `const { token } = await sw.auth.verifyOtp({ token })` is a
|
|
775
|
+
temporal-dead-zone error. `setSessionCookies` returns nothing; the cookies
|
|
776
|
+
ride on the Response you return.
|
|
777
|
+
- **Testing consumes links.** Redeeming a link through the CLI or MCP
|
|
778
|
+
(`auth_verify_magic_link`) uses it up, so the browser flow can no longer be
|
|
779
|
+
proven with it. Prove the browser flow with the emailed link; use a
|
|
780
|
+
separately requested link for any API-only check.
|
|
781
|
+
|
|
782
|
+
The send
|
|
783
|
+
response text is the same whether or not the address already existed
|
|
784
|
+
(`If that email exists or can be created, a sign-in link has been sent.`);
|
|
785
|
+
delivery itself is asynchronous and its outcome is reported separately, so
|
|
786
|
+
this response does not tell you whether the mail was delivered.
|
|
787
|
+
|
|
788
|
+
## Invitations
|
|
789
|
+
|
|
790
|
+
`sw.auth.invite` invites someone by email, whether or not they already have
|
|
791
|
+
an account. It sends one invite email from the platform auth sender, and its
|
|
792
|
+
link signs the invitee in as the invited address:
|
|
793
|
+
|
|
794
|
+
```ts
|
|
795
|
+
// api/invite.ts — POST { email }: the signed-in caller invites a teammate
|
|
796
|
+
export default async function (req: Request, sw: SomewhereRuntimeContext): Promise<Response> {
|
|
797
|
+
const user = await sw.auth.requireUser(req);
|
|
798
|
+
const { email } = (await req.json()) as { email: string };
|
|
799
|
+
// data is stored with the invite on the server; it is not in the email or the link.
|
|
800
|
+
const { invite, delivery } = await sw.auth.invite({ email, redirect_uri: '/join', data: { invited_by: user.id } });
|
|
801
|
+
return Response.json({ id: invite.id, delivery });
|
|
802
|
+
}
|
|
803
|
+
```
|
|
804
|
+
|
|
805
|
+
The link opens your app's `/auth/magic` page, the same page sign-in links
|
|
806
|
+
use. Verifying its token (`sw.auth.verifyOtp`, or the starter's
|
|
807
|
+
`auth.verifyMagicLink`) accepts the invitation and signs the invitee in. The
|
|
808
|
+
verify result's `redirect_uri` is the invite's `redirect_uri` with
|
|
809
|
+
`invite_id=<id>` added, and it also carries `invite_id`. On that page, read
|
|
810
|
+
the invitation on the server:
|
|
811
|
+
|
|
812
|
+
```ts
|
|
813
|
+
// api/join.ts — POST ?invite_id=…: the invitee, now signed in, joins
|
|
814
|
+
export default async function (req: Request, sw: SomewhereRuntimeContext): Promise<Response> {
|
|
815
|
+
const id = new URL(req.url).searchParams.get('invite_id') ?? '';
|
|
816
|
+
// Only the account that accepted this invitation gets it back.
|
|
817
|
+
const invite = await sw.auth.getAcceptedInvite(req, id);
|
|
818
|
+
return Response.json({ invited_by: invite.data?.invited_by ?? null });
|
|
819
|
+
}
|
|
820
|
+
```
|
|
821
|
+
|
|
822
|
+
- **One use, bound to the address.** Accepting signs in the account for the
|
|
823
|
+
invited email, creating it if needed, and verifies that address. If that
|
|
824
|
+
address was not verified yet, this first verification clears the account's
|
|
825
|
+
earlier sign-in methods (`docs({ topic: 'sw.auth', section: 'keeping-your-password' })`). A token
|
|
826
|
+
that was used, revoked or expired is refused like any other invalid link
|
|
827
|
+
(`AUTH_INVALID_CREDS`, 401). `getAcceptedInvite` answers 403
|
|
828
|
+
`INVITE_NOT_ACCEPTED_BY_YOU` to every other signed-in account and for an
|
|
829
|
+
invitation that is not accepted, and 401 `AUTH_REQUIRED` when nobody is
|
|
830
|
+
signed in.
|
|
831
|
+
- **The link is single use; the accepted invitation is not consumed.**
|
|
832
|
+
`getAcceptedInvite` keeps returning an accepted invitation to its account,
|
|
833
|
+
and an accepted invitation cannot be revoked. To grant something once per
|
|
834
|
+
invitation, record `invite.id` in a `serverOnly()` table with a unique
|
|
835
|
+
column, in the same transaction as the grant, and keep that row when the
|
|
836
|
+
grant is later removed. To invite someone into a team or group with a role,
|
|
837
|
+
use `sw.groups.invite` instead: acceptance adds the member, and
|
|
838
|
+
`sw.groups.revokeInvitation` withdraws it (`sw.groups`).
|
|
839
|
+
- **Options.** `redirect_uri` is required: a path in your app such as
|
|
840
|
+
`'/join'`, or a URL that passes the sign-in-link rules above. `data` is
|
|
841
|
+
a JSON object of at most 4096 bytes. `expires_in`
|
|
842
|
+
accepts 900–2592000 seconds; the
|
|
843
|
+
default is 604800 seconds (7 days).
|
|
844
|
+
- **Manage.** `sw.auth.listInvites({ status?, email?, limit? })` (status is
|
|
845
|
+
`pending`, `accepted`, `revoked` or `expired`; newest first, at most
|
|
846
|
+
100), `sw.auth.getInvite(id)` (`null` when unknown) and
|
|
847
|
+
`sw.auth.revokeInvite(id)` (pending only; otherwise 409
|
|
848
|
+
`INVITE_NOT_PENDING`). An invite never exposes its token.
|
|
849
|
+
- **Delivery.** `delivery` is `'sent'` or `'pending'`. A send that
|
|
850
|
+
definitely failed withdraws the invitation and throws. A send whose outcome
|
|
851
|
+
is unknown throws `EMAIL_DELIVERY_UNKNOWN`; that invitation stays valid,
|
|
852
|
+
so list it before sending another. Repeated invitations to one address are
|
|
853
|
+
rate limited (429 `RATE_LIMITED`).
|
|
854
|
+
- **Email allowance.** Invitations, like other sign-in emails, are quota-exempt
|
|
855
|
+
on every plan. They do not use your plan’s email allowance. Repeated sends
|
|
856
|
+
to one address are rate limited; bounce and complaint suppression and
|
|
857
|
+
automatic project pauses protect email delivery.
|
|
858
|
+
- **Testing.** Invite `<name>@<project>.test.somewhere.site`; the test
|
|
859
|
+
inbox keeps the invite and prints its link as `magic_link`.
|
|
860
|
+
|
|
861
|
+
The email says who invites by the project's name, like every auth email. The
|
|
862
|
+
team recipe on built-in groups, with the creator of each row taken from the
|
|
863
|
+
session: `recipe-login` → `7-team-invites`.
|
|
864
|
+
|
|
865
|
+
REST: POST /v1/auth/invites, GET /v1/auth/invites, GET /v1/auth/invites/:id,
|
|
866
|
+
POST /v1/auth/invites/:id/revoke
|
|
867
|
+
|
|
868
|
+
## Email sign-in codes
|
|
869
|
+
|
|
870
|
+
After the password, the user enters a 6-digit code sent to their verified email.
|
|
871
|
+
Codes are valid for 5 minutes and work once. Email is the only second factor:
|
|
872
|
+
whoever controls the inbox can also reset the password, so it protects against a
|
|
873
|
+
leaked or guessed password, not against a lost inbox.
|
|
874
|
+
|
|
875
|
+
**The app owner sets the policy** with a developer key:
|
|
876
|
+
`GET /v1/auth/mfa/policy?project_id=` and `PUT /v1/auth/mfa/policy` with
|
|
877
|
+
`{ project_id, mode }`. Modes change in any order, and the answer states what
|
|
878
|
+
the new mode does:
|
|
879
|
+
|
|
880
|
+
| Mode | Users with codes on | Users without |
|
|
881
|
+
|---|---|---|
|
|
882
|
+
| `off` (default) | still asked for a code | password only; nobody can turn codes on |
|
|
883
|
+
| `optional` | asked for a code | password only; each user can turn codes on |
|
|
884
|
+
| `required` | asked for a code | the next password, Google, GitHub or Discord sign-in or sign-up sends a code, and that code turns codes on (and verifies the address) |
|
|
885
|
+
|
|
886
|
+
No mode erases a user's codes and no mode change ends a session. Under
|
|
887
|
+
`required`, sign-up answers 201 with the user and the code step, and no
|
|
888
|
+
session; a first Google, GitHub or Discord sign-up answers the code step the
|
|
889
|
+
same way (the account exists; no session before the code). Sign-in with a link
|
|
890
|
+
or MCP is refused (403 `AUTH_MFA_METHOD_NOT_ALLOWED`), managed test identities cannot sign in, and
|
|
891
|
+
old refresh tokens that belong to no session stop working (sign in again). An
|
|
892
|
+
app whose sign-in store predates codes answers 409 `AUTH_MFA_UNAVAILABLE` and
|
|
893
|
+
changes nothing.
|
|
894
|
+
|
|
895
|
+
**Signing in.** `loginWithCookie` (or `login`) answers
|
|
896
|
+
`{ mfa_required: true, mfa_token, methods: ['email'] }` and no session; under
|
|
897
|
+
`required` a user who is being enrolled also gets `enrolling: true`.
|
|
898
|
+
`sw.auth.mfa.challengeWithCookie({ mfa_token, code })` (or `challenge`)
|
|
899
|
+
completes it with the normal sign-in answer. `sw.auth.mfa.resend({ mfa_token })`
|
|
900
|
+
mails a new code. In the page, the SDK client's `auth.signIn` rejects with code
|
|
901
|
+
`MFA_REQUIRED` and the message "Enter the 6-digit code we emailed you to finish
|
|
902
|
+
signing in." (from `@somewhere-cloud/sdk` 0.14.1), `auth.completeMfa({ code })`
|
|
903
|
+
finishes the sign-in through the starter's `/api/auth` handler, and
|
|
904
|
+
`auth.resendMfaCode()` mails a new code. From 0.14.1 the page can also turn codes
|
|
905
|
+
on (`auth.enrollMfa()`, then `auth.verifyMfaEnrollment({ challenge_id, code })`)
|
|
906
|
+
and off (`auth.unenrollMfa({ password })`, then `({ challenge_id, code })`). Five wrong codes in an hour lock code sign-in for that account
|
|
907
|
+
(429 `AUTH_MFA_LOCKED`) until the hour rolls over.
|
|
908
|
+
|
|
909
|
+
**Turning codes on** (mode `optional` or `required`), signed in:
|
|
910
|
+
`sw.auth.mfa.enrollWithCookie(req)` mails a code and answers `{ challenge_id }`;
|
|
911
|
+
`sw.auth.mfa.verifyWithCookie(req, { challenge_id, code })` turns codes on.
|
|
912
|
+
|
|
913
|
+
**Turning codes off**, signed in, in two steps:
|
|
914
|
+
`sw.auth.mfa.unenrollWithCookie(req, { password })` checks the password and mails
|
|
915
|
+
a code; `sw.auth.mfa.unenrollWithCookie(req, { challenge_id, code })` turns codes
|
|
916
|
+
off. Under `required` this is refused (409 `AUTH_MFA_REQUIRED_BY_APP`).
|
|
917
|
+
|
|
918
|
+
**A user who cannot receive a code**, with no session:
|
|
919
|
+
`sw.auth.mfa.recover({ email, password })` starts a 72-hour wait (202
|
|
920
|
+
`{ removal_pending, removes_at }`). It starts only if the app can email the user
|
|
921
|
+
right now (otherwise 503 `AUTH_MFA_RECOVERY_NOTICE_UNSENT`). The email carries a
|
|
922
|
+
cancel link that works for the whole wait without signing in. The same call after
|
|
923
|
+
the wait turns codes off. A code sign-in, a password change or reset, an email
|
|
924
|
+
change, or the cancel link stops it.
|
|
925
|
+
|
|
926
|
+
**The app owner** can turn a user's codes off at once with
|
|
927
|
+
`DELETE /v1/auth/users/:id/mfa?project_id=`, or set the user's email address with
|
|
928
|
+
`PATCH /v1/auth/users/:id` `{ email }`, for a user who lost their inbox. The new
|
|
929
|
+
address is unverified, their codes are turned off, and mail sent to the old address
|
|
930
|
+
stops working.
|
|
931
|
+
|
|
932
|
+
**Limits.** At most one code a minute and 5 an hour per account. Code mail never
|
|
933
|
+
counts against the app's email allowance, and mail to a verified address is sent
|
|
934
|
+
even while the app's email is paused for bounces. Code mail to unverified addresses
|
|
935
|
+
(sign-ups under `required`) is limited to 200 an hour per app and 20 an hour
|
|
936
|
+
per network address (429 `AUTH_MFA_NEW_ACCOUNT_LIMITED`).
|
|
937
|
+
|
|
938
|
+
**Webhooks:** `mfa_factor_removed` (`via`: `self`, `recovery` or `owner`),
|
|
939
|
+
`mfa_recovery_started`, `mfa_user_email_changed` and `mfa_policy_changed`.
|
|
940
|
+
|
|
941
|
+
REST: `POST /v1/auth/mfa/challenge`, `/enroll`, `/verify`, `/unenroll`,
|
|
942
|
+
`/recovery`, `/recovery/cancel`; `GET|PUT /v1/auth/mfa/policy`;
|
|
943
|
+
`DELETE /v1/auth/users/:id/mfa`. MCP: `auth_mfa_enroll`, `auth_mfa_verify`,
|
|
944
|
+
`auth_mfa_challenge`, `auth_mfa_unenroll`.
|
|
945
|
+
|
|
946
|
+
## Not available
|
|
947
|
+
|
|
948
|
+
These account features are not available. Their calls answer 501
|
|
949
|
+
`AUTH_FEATURE_UNAVAILABLE` before anything runs, so they change nothing:
|
|
950
|
+
|
|
951
|
+
| Feature | Calls that answer 501 |
|
|
952
|
+
|---|---|
|
|
953
|
+
| Authenticator-app (TOTP) codes | `sw.auth.mfa.reauthenticate`, `verifyReauthentication`, `POST /v1/auth/mfa/activation/reauth*` |
|
|
954
|
+
| Passkeys | `/v1/auth/passkey/*` |
|
|
955
|
+
| Changing a signed-in user's profile or email address | `sw.auth.updateProfile`, `updateProfileWithCookie`, `verifyEmailChangeWithCookie`, `verifyEmailChangeCurrentWithCookie`, `PATCH /v1/auth/me`, `PATCH /v1/auth/users/me`, `POST /v1/auth/change-email/*` |
|
|
956
|
+
| In-app user moderation | `sw.auth.moderation`, `/v1/auth/admin/users` |
|
|
957
|
+
| Anonymous-account migration | `POST /v1/auth/migrate-anon` |
|
|
958
|
+
| User import and export | `POST /v1/auth/import`, `POST /v1/auth/export/request`, `POST /v1/auth/export/download` |
|
|
959
|
+
|
|
960
|
+
An account copied from an earlier platform with authenticator-app codes gets
|
|
961
|
+
`{ mfa_required: true, mfa_token }` and no session, and cannot complete it.
|
|
962
|
+
|
|
963
|
+
What works today: password sign-up and sign-in, email sign-in codes, sign-in
|
|
964
|
+
links, invitations, Google, GitHub and Discord sign-in, email verification,
|
|
965
|
+
password reset and password change, sign-out, account self-delete, and
|
|
966
|
+
developer user management with a developer key (list, edit, ban, delete,
|
|
967
|
+
sessions, and a user's sign-in codes and address).
|
|
968
|
+
|
|
969
|
+
## Update password (logged-in user)
|
|
970
|
+
|
|
971
|
+
```ts
|
|
972
|
+
// api/settings/password.ts — POST { current_password?, new_password }
|
|
973
|
+
export default async function (req: Request, sw: SomewhereRuntimeContext) {
|
|
974
|
+
if (req.method !== 'POST') return new Response('Use POST.', { status: 405, headers: { Allow: 'POST' } });
|
|
975
|
+
const input: unknown = await req.json().catch(() => null);
|
|
976
|
+
const newPassword = typeof input === 'object' && input !== null && 'new_password' in input ? input.new_password : undefined;
|
|
977
|
+
const currentPassword = typeof input === 'object' && input !== null && 'current_password' in input ? input.current_password : undefined;
|
|
978
|
+
if (typeof newPassword !== 'string' || (currentPassword !== undefined && typeof currentPassword !== 'string')) {
|
|
979
|
+
return Response.json({ error: 'new_password is required; current_password must be text.' }, { status: 400 });
|
|
980
|
+
}
|
|
981
|
+
const result = await sw.auth.updatePasswordWithCookie(req, { new_password: newPassword, current_password: currentPassword });
|
|
982
|
+
return Response.json(result);
|
|
983
|
+
}
|
|
984
|
+
```
|
|
985
|
+
|
|
986
|
+
Token-mode clients call `sw.auth.updatePassword(token, { current_password, new_password })`.
|
|
987
|
+
|
|
988
|
+
Wipes ALL active sessions and refresh tokens on success — the user has
|
|
989
|
+
to log in again everywhere.
|
|
990
|
+
|
|
991
|
+
**A bearer token alone cannot set the FIRST password.** An account that
|
|
992
|
+
has never had one — magic link, OAuth — is refused here with
|
|
993
|
+
`AUTH_PASSWORD_RESET_REQUIRED` (403). Send that user through the existing
|
|
994
|
+
`/v1/auth/forgot` and `/v1/auth/reset` pair instead, so the password is set
|
|
995
|
+
against a code delivered to their current address rather than against a
|
|
996
|
+
token someone may have stolen. On an account that already has a password,
|
|
997
|
+
`current_password` is required (`VALIDATION_ERROR` without it, `AUTH_INVALID_CREDS`
|
|
998
|
+
if it is wrong), and if the password changes underneath the call it answers
|
|
999
|
+
`AUTH_CREDENTIAL_CHANGED` (409) rather than overwriting the newer one.
|
|
1000
|
+
|
|
1001
|
+
## Change email (logged-in user)
|
|
1002
|
+
|
|
1003
|
+
Not available: see "Not available".
|
|
1004
|
+
|
|
1005
|
+
## Update profile (logged-in user)
|
|
1006
|
+
|
|
1007
|
+
Not available: see "Not available". A developer key can still edit a
|
|
1008
|
+
user (see "Admin / test-harness edit").
|
|
1009
|
+
|
|
1010
|
+
## Self-service account deletion
|
|
1011
|
+
|
|
1012
|
+
```ts
|
|
1013
|
+
// api/settings/delete-account.ts — POST deletes the signed-in user's own account
|
|
1014
|
+
export default async function (req: Request, sw: SomewhereRuntimeContext) {
|
|
1015
|
+
if (req.method !== 'POST') return new Response('Use POST.', { status: 405, headers: { Allow: 'POST' } });
|
|
1016
|
+
const result = await sw.auth.deleteUserWithCookie(req);
|
|
1017
|
+
return Response.json(result);
|
|
1018
|
+
}
|
|
1019
|
+
```
|
|
1020
|
+
|
|
1021
|
+
Token-mode clients call `sw.auth.deleteUser(token)`. Both forms end every
|
|
1022
|
+
session; the cookie form also clears the cookies.
|
|
1023
|
+
|
|
1024
|
+
The call removes the sign-in identity, sessions and refresh tokens, password reset
|
|
1025
|
+
and verification codes, pending email changes, magic links, MFA credentials,
|
|
1026
|
+
provider links, group memberships, app-role grants, plan selection,
|
|
1027
|
+
push devices, MCP grants and pending MCP consents. Grants the user gave other
|
|
1028
|
+
people stay with those people.
|
|
1029
|
+
|
|
1030
|
+
Passkey sign-in is not available. Account deletion also clears any
|
|
1031
|
+
passkey records left by older versions.
|
|
1032
|
+
|
|
1033
|
+
The answer keeps `deleted: true` and adds three lists: `removed` names the
|
|
1034
|
+
categories removed; `kept` names payment records (`accounts_and_disputes`),
|
|
1035
|
+
the group deletion marker (`prevents_stale_access`), and suppression of a
|
|
1036
|
+
complained email address (`prevents_unwanted_mail`). These are categories and
|
|
1037
|
+
reason codes, not a check that such records exist. `not_covered` names rows and
|
|
1038
|
+
files the person created, AI history, search, mail records, the sign-in mirror,
|
|
1039
|
+
logs and their archive, and backups. This call does not inspect those stores.
|
|
1040
|
+
Anything in `not_covered` is yours to delete. The author and bulk deletion
|
|
1041
|
+
routes return the same lists for each successfully deleted user.
|
|
1042
|
+
|
|
1043
|
+
### Delete the person's own data too, and give them a copy
|
|
1044
|
+
|
|
1045
|
+
Pass `{ erase: 'owned' }` to `deleteUserWithCookie(req, { erase: 'owned' })` or `deleteUser(token, { erase: 'owned' })`, or add `?erase=owned` to `DELETE /v1/auth/users/me`. The project owner can also use it on `DELETE /v1/auth/users/<id>?project_id=<project>` with their own developer key; editors cannot. The erase also removes:
|
|
1046
|
+
- rows in tables whose access rule is `owner()` and that hold the person's id;
|
|
1047
|
+
- files stored as theirs.
|
|
1048
|
+
|
|
1049
|
+
The person's own mailbox goes with every deletion. Mail in other people's mailboxes is theirs and is not touched. Rows in shared or policy tables are kept, because the app's own rules decide who keeps them.
|
|
1050
|
+
|
|
1051
|
+
Before anything is deleted, the platform checks the app's tables. If a table could reach another person's rows, the request is refused with `ERASE_UNSAFE`, the tables are named and nothing is deleted. Such a table is one that:
|
|
1052
|
+
- is referenced by another table's foreign key;
|
|
1053
|
+
- has the app's own triggers;
|
|
1054
|
+
- has no rowid;
|
|
1055
|
+
- is declared only in an older release.
|
|
1056
|
+
|
|
1057
|
+
Delete without `erase`, or change those tables, and try again. If an option other than `"owned"` is given, nothing is deleted.
|
|
1058
|
+
|
|
1059
|
+
The answer's `erasure` has an id, a state and counts. The erase finishes in the background about 15 minutes after the deletion. The owner reads the receipt with `GET /v1/auth/erasures/<id>?project_id=<project>`; it holds counts only.
|
|
1060
|
+
|
|
1061
|
+
A person's own copy of their data:
|
|
1062
|
+
- the signed-in person: `sw.auth.exportUser(token)` or `GET /v1/auth/users/me/export`;
|
|
1063
|
+
- the owner: `GET /v1/auth/users/<id>/export?project_id=<project>` with their own developer key.
|
|
1064
|
+
|
|
1065
|
+
The copy has:
|
|
1066
|
+
- their profile;
|
|
1067
|
+
- their rows in `owner()` tables, without columns the app marks sensitive;
|
|
1068
|
+
- their files by path;
|
|
1069
|
+
- their passkeys.
|
|
1070
|
+
|
|
1071
|
+
Shared and policy tables are named in `not_in_copy`, not copied. A copy over 5,000 rows in one table, or 10 MB in all, is refused with `EXPORT_TOO_LARGE`; nothing is truncated.
|
|
1072
|
+
|
|
1073
|
+
When someone asks the app to delete their data or send them a copy, these calls are the answer for what the platform can tell is theirs. Ask your human about anything the answer lists as not covered: raw SQL tables, shared tables, or another service.
|
|
1074
|
+
|
|
1075
|
+
A group always keeps an owner. If the account is the only owner of a group,
|
|
1076
|
+
the call is refused with a 409 `LAST_OWNER` error whose message names the
|
|
1077
|
+
group, and nothing is deleted. Make another member an owner
|
|
1078
|
+
(`sw.groups.setRole`), or delete the group, then delete the account again.
|
|
1079
|
+
|
|
1080
|
+
An already-admitted sign-in can be honoured for up to 60 seconds after deletion.
|
|
1081
|
+
An open live-room connection can last until its ticket expires (at most 5 minutes).
|
|
1082
|
+
|
|
1083
|
+
## Admin / test-harness deletion (developer key)
|
|
1084
|
+
|
|
1085
|
+
```text
|
|
1086
|
+
auth_user_delete({ project_id: "my-app", user_id: "6f1c2a9e-3b7d-4e2a-9c41-8d5e0f7a2b13" })
|
|
1087
|
+
```
|
|
1088
|
+
|
|
1089
|
+
REST: `DELETE /v1/auth/users/:id?project_id=...` with an `smt_` key.
|
|
1090
|
+
|
|
1091
|
+
For wiping throwaway test users from your own tooling, when you don't
|
|
1092
|
+
have the user's JWT. Same cascade and the same `LAST_OWNER` refusal as the
|
|
1093
|
+
self-service variant. The project must be one you own.
|
|
1094
|
+
|
|
1095
|
+
To delete several test users together, with the groups only they belong to:
|
|
1096
|
+
`POST /v1/auth/users/delete?project_id=...` with an `smt_` key and
|
|
1097
|
+
`{ "ids": [...], "delete_groups_only_they_belong_to": true }` (1 to 50 exact ids,
|
|
1098
|
+
never emails). A group whose every member is in `ids` is deleted with them. A user
|
|
1099
|
+
who is the only owner of a group with any member outside `ids` is kept, and the
|
|
1100
|
+
group is left alone. The answer gives each id's outcome (`deleted`, `not_found` or
|
|
1101
|
+
`kept` with the group named) and the groups deleted. `somewhere test` uses this
|
|
1102
|
+
for the accounts it signed up; in a preview it uses
|
|
1103
|
+
`POST /v1/preview-tools/signups/delete` with the preview's own credential.
|
|
1104
|
+
|
|
1105
|
+
## Admin / test-harness edit (developer key)
|
|
1106
|
+
|
|
1107
|
+
```text
|
|
1108
|
+
auth_user_update({
|
|
1109
|
+
project_id: "my-app",
|
|
1110
|
+
user_id: "6f1c2a9e-3b7d-4e2a-9c41-8d5e0f7a2b13",
|
|
1111
|
+
display_name: "Ada Lovelace",
|
|
1112
|
+
metadata: { team: "support" },
|
|
1113
|
+
role: "admin"
|
|
1114
|
+
})
|
|
1115
|
+
```
|
|
1116
|
+
|
|
1117
|
+
REST: `PATCH /v1/auth/users/:id?project_id=...` with an `smt_` key.
|
|
1118
|
+
|
|
1119
|
+
For admin tooling: edit `display_name`, `metadata`, and/or the
|
|
1120
|
+
platform-owned `user | admin` role on any end-user in a project you
|
|
1121
|
+
own. Signup always creates `user`; granting the first `admin` here is
|
|
1122
|
+
safe because this control-plane call requires the project owner's
|
|
1123
|
+
developer key and the app-user self-profile route does not accept
|
|
1124
|
+
`role`. Role changes are audited and invalidate existing access tokens. Email and
|
|
1125
|
+
password are intentionally NOT here — those have their own verification
|
|
1126
|
+
and reset flows. `metadata` is REPLACED, not merged; max 16 KB.
|
|
1127
|
+
|
|
1128
|
+
Also accepts `banned` and `banned_reason` — see "Ban / suspend" below.
|
|
1129
|
+
|
|
1130
|
+
## Server-assigned app roles (setRoles)
|
|
1131
|
+
|
|
1132
|
+
Who gets a role is your app's decision; the platform enforces what the role may do.
|
|
1133
|
+
Require mailbox verification when grant eligibility depends on an email
|
|
1134
|
+
domain. Anyone can sign up as `anyone@yourco.example` before verifying it.
|
|
1135
|
+
|
|
1136
|
+
**First choice: the verified email domain.** When staff are the people with an
|
|
1137
|
+
address at your domain, declare `appRoles: { staff: { emailDomain: 'yourco.example' } }`.
|
|
1138
|
+
The role holds as soon as the person verifies that address; there is no grant
|
|
1139
|
+
code to write or to fail (`sw.groups` → `app-wide-roles`).
|
|
1140
|
+
|
|
1141
|
+
**Second choice: an invitation your app issued, granted inside sign-up.** When
|
|
1142
|
+
staff must hold the role before any verification, grant it only from something
|
|
1143
|
+
the visitor cannot choose: an invitation code your app created for one address.
|
|
1144
|
+
The link is a bearer credential for that address. Nothing here verifies the
|
|
1145
|
+
mailbox, so deliver the link only to that person, over a channel you trust:
|
|
1146
|
+
whoever holds it can sign up as that address first. Declare the role
|
|
1147
|
+
`assignedBy: 'server'` and keep the invitations server-only. The invitation row
|
|
1148
|
+
is the record of who is owed the role: it is claimed once, by one account,
|
|
1149
|
+
then marked granted.
|
|
1150
|
+
|
|
1151
|
+
```ts
|
|
1152
|
+
// db/schema.ts
|
|
1153
|
+
import { appRole, id, schema, serverOnly, table, text } from 'somewhere/db';
|
|
1154
|
+
|
|
1155
|
+
export default schema({
|
|
1156
|
+
staff_invites: table({
|
|
1157
|
+
id: id(), email: text(), code: text(),
|
|
1158
|
+
claimed_by: text({ nullable: true }), // the account that redeemed it; set once
|
|
1159
|
+
granted_at: text({ nullable: true }), // set after the role is held; never grants again
|
|
1160
|
+
}, { scope: serverOnly(), unique: [['code']] }),
|
|
1161
|
+
staff_notes: table({ id: id(), body: text() }, {
|
|
1162
|
+
scope: appRole({ roles: { read: ['staff'], create: ['staff'] } }),
|
|
1163
|
+
client: { read: true, create: ['body'] },
|
|
1164
|
+
}),
|
|
1165
|
+
}, { appRoles: { staff: { assignedBy: 'server' } } });
|
|
1166
|
+
```
|
|
1167
|
+
|
|
1168
|
+
```ts
|
|
1169
|
+
// api/staff-invites.ts — POST { email }: an app admin issues an invitation link
|
|
1170
|
+
export default sw.endpoint({
|
|
1171
|
+
auth: 'required', body: { email: 'email' },
|
|
1172
|
+
handler: async ({ request, body }, sw) => {
|
|
1173
|
+
await sw.auth.requireUser(request, { role: 'admin' });
|
|
1174
|
+
const code = crypto.randomUUID();
|
|
1175
|
+
await sw.db.server.insert('staff_invites', { id: crypto.randomUUID(), email: body.email.toLowerCase(), code });
|
|
1176
|
+
return { link: new URL('/api/staff-invite?code=' + code, request.url).href };
|
|
1177
|
+
},
|
|
1178
|
+
});
|
|
1179
|
+
```
|
|
1180
|
+
|
|
1181
|
+
```ts
|
|
1182
|
+
// api/staff-invite.ts — GET: the invitation link keeps its code for the sign-up route
|
|
1183
|
+
export const GET = sw.endpoint({
|
|
1184
|
+
auth: 'none',
|
|
1185
|
+
handler: async ({ request }) => {
|
|
1186
|
+
const code = new URL(request.url).searchParams.get('code') ?? '';
|
|
1187
|
+
if (!/^[0-9a-f-]{36}$/.test(code)) return Response.json({ error: 'INVITE_INVALID' }, { status: 400 });
|
|
1188
|
+
return new Response(null, { status: 303, headers: {
|
|
1189
|
+
location: '/', 'set-cookie': `staff_invite=${code}; Path=/api/auth; HttpOnly; Secure; SameSite=Lax; Max-Age=604800`,
|
|
1190
|
+
} });
|
|
1191
|
+
},
|
|
1192
|
+
});
|
|
1193
|
+
```
|
|
1194
|
+
|
|
1195
|
+
```ts
|
|
1196
|
+
// api/auth/[...path].ts — the starter's auth route, plus: an invited person becomes staff
|
|
1197
|
+
import { somewhereAuth } from '@somewhere-cloud/sdk/server';
|
|
1198
|
+
export default async function (request: Request, sw: SomewhereRuntimeContext): Promise<Response> {
|
|
1199
|
+
const response = await somewhereAuth(request, sw);
|
|
1200
|
+
if (!response.ok || request.method !== 'POST' || !/\/auth\/(signup|login)$/.test(new URL(request.url).pathname)) return response;
|
|
1201
|
+
const { user } = await response.clone().json() as { user?: { id?: string; email?: string } };
|
|
1202
|
+
if (!user?.id || !user.email) return response; // an emailed sign-in code is still pending
|
|
1203
|
+
const code = /(?:^|;\s*)staff_invite=([0-9a-f-]{36})/.exec(request.headers.get('cookie') ?? '')?.[1];
|
|
1204
|
+
// 1. Claim: bind an unclaimed invitation for this address to this account. The
|
|
1205
|
+
// condition claimed_by: null makes it single use: of any two attempts, one changes it.
|
|
1206
|
+
if (code) {
|
|
1207
|
+
await sw.db.server.update('staff_invites', {
|
|
1208
|
+
where: { code, email: user.email.toLowerCase(), claimed_by: null }, set: { claimed_by: user.id },
|
|
1209
|
+
});
|
|
1210
|
+
}
|
|
1211
|
+
// 2. Grant what this account is owed: claimed now, or claimed by an earlier sign-in whose grant failed.
|
|
1212
|
+
const { data: [owed] } = await sw.db.server.from('staff_invites', { where: { claimed_by: user.id, granted_at: null }, limit: 1 });
|
|
1213
|
+
const inviteId = owed?.id;
|
|
1214
|
+
if (typeof inviteId !== 'string') return response;
|
|
1215
|
+
try {
|
|
1216
|
+
await sw.auth.server.setRoles(user.id, { add: ['staff'] }); // idempotent
|
|
1217
|
+
} catch {
|
|
1218
|
+
// Not granted. The invitation stays bound to this account; its next sign-in grants again.
|
|
1219
|
+
sw.auth.clearSessionCookies();
|
|
1220
|
+
return Response.json({ error: 'STAFF_SETUP_FAILED', message: 'Your account was created, but staff access could not be set up yet. Sign in again to finish.' }, { status: 503 });
|
|
1221
|
+
}
|
|
1222
|
+
// 3. Spend it. If this write fails, the person holds the role they were invited to;
|
|
1223
|
+
// their next sign-in finds the row still owed, grants again (a no-op) and spends it.
|
|
1224
|
+
await sw.db.server.update('staff_invites', { where: { id: inviteId, claimed_by: user.id, granted_at: null }, set: { granted_at: new Date().toISOString() } })
|
|
1225
|
+
.catch((error: unknown) => console.error('staff invite not marked granted; the next sign-in finishes it', String(error)));
|
|
1226
|
+
return response;
|
|
1227
|
+
}
|
|
1228
|
+
```
|
|
1229
|
+
|
|
1230
|
+
```ts
|
|
1231
|
+
// api/staff-revoke.ts — POST { userId }: an app admin removes staff. The invitation is
|
|
1232
|
+
// retired first, so no later sign-in can grant the role back.
|
|
1233
|
+
export default sw.endpoint({
|
|
1234
|
+
auth: 'required', body: { userId: 'string' },
|
|
1235
|
+
handler: async ({ request, body }, sw) => {
|
|
1236
|
+
await sw.auth.requireUser(request, { role: 'admin' });
|
|
1237
|
+
await sw.db.server.remove('staff_invites', { where: { claimed_by: body.userId } });
|
|
1238
|
+
await sw.auth.server.setRoles(body.userId, { remove: ['staff'] });
|
|
1239
|
+
return { ok: true };
|
|
1240
|
+
},
|
|
1241
|
+
});
|
|
1242
|
+
```
|
|
1243
|
+
|
|
1244
|
+
Every state is safe. Unclaimed, the invitation gives nothing. Claimed, it belongs
|
|
1245
|
+
to one account and to nobody else, even with the same link. A second account at
|
|
1246
|
+
that address, or a forwarded link, finds it claimed. Until it is marked granted,
|
|
1247
|
+
any sign-in of that account (with or without the link) finishes the grant, so a
|
|
1248
|
+
failed grant is recovered, never lost. Marked granted, it never grants again,
|
|
1249
|
+
and a revoked role stays revoked. A failed grant signs the person out with the
|
|
1250
|
+
message above and holds no role. The grant runs before the response is sent, so
|
|
1251
|
+
the new person's first request already holds the role; a separate setup request
|
|
1252
|
+
after sign-up would race it. A project that requires emailed sign-in codes
|
|
1253
|
+
finishes sign-up at the code step, which this route does not intercept; there,
|
|
1254
|
+
use the verified email domain above.
|
|
1255
|
+
|
|
1256
|
+
For a later promotion (an admin, a payment), call setRoles from a POST handler
|
|
1257
|
+
that first authorizes the caller, for example with
|
|
1258
|
+
`await sw.auth.requireUser(request, { role: 'admin' })`. Never from a GET:
|
|
1259
|
+
role changes mutate authentication state, so cookie-authenticated safe methods
|
|
1260
|
+
are refused.
|
|
1261
|
+
|
|
1262
|
+
`setRoles(userId, { add: ['staff'] })` adds; `{ remove: ['staff'] }` removes.
|
|
1263
|
+
These server methods run in deployed functions, not dev or run_code. In a preview they read and assign roles for that preview's own users in its copy of the data; the live app's users and roles are never reached.
|
|
1264
|
+
Full declared schema: `somewhere docs declared-data --section server-roles-and-membership-restrictions`.
|
|
1265
|
+
|
|
1266
|
+
## Check an app role from a page
|
|
1267
|
+
|
|
1268
|
+
For a page that shows owner controls, call a signed-in endpoint that uses
|
|
1269
|
+
`await sw.auth.requireUser(request, { appRoles: true })` and returns whether
|
|
1270
|
+
the caller's `appRoles` includes `owner`. The browser auth client's session
|
|
1271
|
+
contains the built-in auth role. Enforce the required app role again on any
|
|
1272
|
+
endpoint that reads private data or changes state. See
|
|
1273
|
+
`somewhere docs sw.groups --section app-wide-roles` for the server-side checks.
|
|
1274
|
+
|
|
1275
|
+
## App roles (developer key)
|
|
1276
|
+
|
|
1277
|
+
Roles your schema declares (`db/schema.ts` `appRoles`: staff, moderator, …)
|
|
1278
|
+
are granted here as well, so every `appRole()` rule on your tables applies to
|
|
1279
|
+
the person at once:
|
|
1280
|
+
|
|
1281
|
+
```text
|
|
1282
|
+
app_role_grant({ project_id: "my-app", email: "ann@example.com", role: "staff" })
|
|
1283
|
+
app_role_revoke({ project_id: "my-app", user_id: "6f1c2a9e-3b7d-4e2a-9c41-8d5e0f7a2b13", role: "staff" })
|
|
1284
|
+
app_role_list({ project_id: "my-app", role: "staff" })
|
|
1285
|
+
```
|
|
1286
|
+
|
|
1287
|
+
REST: `POST /v1/auth/app-roles/grant`, `POST /v1/auth/app-roles/revoke`,
|
|
1288
|
+
`GET /v1/auth/app-roles?project_id=…` with an `smt_` key · CLI:
|
|
1289
|
+
`somewhere auth roles grant|revoke|list`. Name the person by `user_id` or
|
|
1290
|
+
by the exact address they signed up with; the address need not be verified.
|
|
1291
|
+
An app role is different from the `user | admin` auth role above: you declare
|
|
1292
|
+
it and your `appRole()` rules read it; the `admin` auth role is the
|
|
1293
|
+
platform's. Who holds what, and the in-app grant path: `sw.groups` →
|
|
1294
|
+
`app-wide-roles`.
|
|
1295
|
+
|
|
1296
|
+
## Admin operations are NOT on the runtime
|
|
1297
|
+
|
|
1298
|
+
`sw.auth.admin.*` is not callable inside deployed functions — any
|
|
1299
|
+
call throws `AUTH_ADMIN_REMOVED_FROM_RUNTIME`. A public handler that
|
|
1300
|
+
accepted a user id from the request body would be an account-takeover
|
|
1301
|
+
primitive, so admin actions on app users run only from your own
|
|
1302
|
+
tooling with a developer `smt_` key (MCP tools or REST), never from
|
|
1303
|
+
a request handler. The sections below are that surface.
|
|
1304
|
+
|
|
1305
|
+
## Ban / suspend (developer key)
|
|
1306
|
+
|
|
1307
|
+
Block a user from signing in without deleting their data. Bans are
|
|
1308
|
+
reversible — the row stays put, sessions are wiped, future `login`
|
|
1309
|
+
returns AUTH_INVALID_CREDS (no enumeration), and any active JWT bounces
|
|
1310
|
+
with 403 AUTH_BANNED on `/me` so your SPA can log them out.
|
|
1311
|
+
|
|
1312
|
+
Ban, then unban (unbanning clears the reason and timestamp):
|
|
1313
|
+
|
|
1314
|
+
```text
|
|
1315
|
+
auth_user_update({ project_id: "my-app", user_id: "6f1c2a9e-3b7d-4e2a-9c41-8d5e0f7a2b13", banned: true, banned_reason: "spam" })
|
|
1316
|
+
auth_user_update({ project_id: "my-app", user_id: "6f1c2a9e-3b7d-4e2a-9c41-8d5e0f7a2b13", banned: false })
|
|
1317
|
+
```
|
|
1318
|
+
|
|
1319
|
+
The `banned_reason` is staff-only — never returned to the banned
|
|
1320
|
+
user. Banning a user invalidates every active session + refresh token.
|
|
1321
|
+
|
|
1322
|
+
REST: PATCH /v1/auth/users/:id?project_id=… with `banned` /
|
|
1323
|
+
`banned_reason` fields · MCP: auth_user_update
|
|
1324
|
+
|
|
1325
|
+
## Acting as an app user
|
|
1326
|
+
|
|
1327
|
+
The platform does not sign a developer in as one of an app's users.
|
|
1328
|
+
`POST /v1/auth/users/:id/impersonate` answers **410 IMPERSONATION_RETIRED**
|
|
1329
|
+
and issues no token. To test your app as a user, use a test identity;
|
|
1330
|
+
browser_test's `auth: { user_id }` accepts only a test identity of the
|
|
1331
|
+
project and answers 410 IMPERSONATION_RETIRED for anyone else.
|
|
1332
|
+
|
|
1333
|
+
## Test users and the after-deploy check
|
|
1334
|
+
|
|
1335
|
+
After every live deploy, Somewhere checks the new release as a stranger and as a
|
|
1336
|
+
signed-out visitor. It creates two test users in your app, has one of them create
|
|
1337
|
+
a row in each table the browser may both create in and delete from, tries to read,
|
|
1338
|
+
change and delete that row as the other test user and as a visitor, and calls each
|
|
1339
|
+
server function that takes an id in its path (such as `api/notes/[id].ts`) once with
|
|
1340
|
+
GET, using that test row's id. In the platform's browser it loads the home page and
|
|
1341
|
+
the pages it links to, signed out and as a test user, on a computer and a phone, and
|
|
1342
|
+
signs in once through your app's own form with an account it signs up through your
|
|
1343
|
+
app's sign-up route. It presses no other button. It then deletes that row, any row
|
|
1344
|
+
your app made for these users, the sign-in account and both test users, by id.
|
|
1345
|
+
It never changes or deletes anything it did not create; other people's rows are
|
|
1346
|
+
only read to learn whether a stranger can see them, and their contents are never
|
|
1347
|
+
stored. The result is one sentence on the deploy log: `GET /v1/deploy/log` field
|
|
1348
|
+
`access_check`, also linked from the deploy response's `checks`.
|
|
1349
|
+
|
|
1350
|
+
A test user's email ends in `.test.somewhere.site`, and `sw.auth` user objects for
|
|
1351
|
+
managed test users carry `test: true` (the sign-in account is an ordinary sign-up on
|
|
1352
|
+
that address). Test users are never admins, are not counted in your app's
|
|
1353
|
+
user totals, and their mail goes to the test inbox. If your code reacts to a new
|
|
1354
|
+
or first-seen user (notifying the owner, sending a welcome, posting to a channel),
|
|
1355
|
+
skip users whose email ends in `.test.somewhere.site`:
|
|
1356
|
+
|
|
1357
|
+
```ts
|
|
1358
|
+
const isTestUser = (user: { email?: string | null }) => /\.test\.somewhere\.site$/i.test(user.email ?? '');
|
|
1359
|
+
```
|
|
1360
|
+
|
|
1361
|
+
## Session management (developer key)
|
|
1362
|
+
|
|
1363
|
+
List + revoke a user's active sessions. Tokens themselves are never
|
|
1364
|
+
returned — only session IDs, creation timestamps, and expiries.
|
|
1365
|
+
|
|
1366
|
+
`auth_list_sessions` returns `[{ id, created_at, expires_at }, ...]`,
|
|
1367
|
+
non-expired only, max 100. Revoke one session to log that device out, or all
|
|
1368
|
+
of them to log every device out:
|
|
1369
|
+
|
|
1370
|
+
```text
|
|
1371
|
+
auth_list_sessions({ project_id: "my-app", user_id: "6f1c2a9e-3b7d-4e2a-9c41-8d5e0f7a2b13" })
|
|
1372
|
+
auth_revoke_session({ project_id: "my-app", session_id: "<id from auth_list_sessions>" })
|
|
1373
|
+
auth_revoke_all_sessions({ project_id: "my-app", user_id: "6f1c2a9e-3b7d-4e2a-9c41-8d5e0f7a2b13" })
|
|
1374
|
+
```
|
|
1375
|
+
|
|
1376
|
+
REST: GET /v1/auth/users/:id/sessions, DELETE /v1/auth/sessions/:id,
|
|
1377
|
+
DELETE /v1/auth/users/:id/sessions
|
|
1378
|
+
MCP: auth_list_sessions, auth_revoke_session, auth_revoke_all_sessions
|
|
1379
|
+
|
|
1380
|
+
## Lifecycle webhook (clean up your own tables on user delete)
|
|
1381
|
+
|
|
1382
|
+
Deleting a user removes their platform account and sessions. Your app must
|
|
1383
|
+
clean up its own references, such as posts, comments and avatar files.
|
|
1384
|
+
|
|
1385
|
+
Configure a project-scoped webhook to handle account events and clean up app data:
|
|
1386
|
+
|
|
1387
|
+
// one-time setup (developer key)
|
|
1388
|
+
const { secret } = await auth_webhook_set({
|
|
1389
|
+
project_id: 'default',
|
|
1390
|
+
url: 'https://yourapp.somewhere.site/api/lifecycle-webhook',
|
|
1391
|
+
});
|
|
1392
|
+
// store the returned secret in server env (never in the browser bundle):
|
|
1393
|
+
// somewhere env set AUTH_WEBHOOK_SECRET <secret>
|
|
1394
|
+
// a URL-only update keeps the secret but does not return it;
|
|
1395
|
+
// rotate_secret: true issues a new one (then set the new value).
|
|
1396
|
+
|
|
1397
|
+
The tables the handler writes, both `owner()` (the owner column is `user_id`):
|
|
1398
|
+
|
|
1399
|
+
```ts
|
|
1400
|
+
// db/schema.ts
|
|
1401
|
+
import { id, owner, schema, table, text, timestamp } from 'somewhere/db';
|
|
1402
|
+
|
|
1403
|
+
export default schema({
|
|
1404
|
+
profiles: table(
|
|
1405
|
+
{ id: id(), email: text({ unique: true }), display_name: text({ nullable: true }) },
|
|
1406
|
+
{ scope: owner() },
|
|
1407
|
+
),
|
|
1408
|
+
posts: table(
|
|
1409
|
+
{ id: id(), title: text(), body: text(), created_at: timestamp({ default: 'now' }) },
|
|
1410
|
+
{ scope: owner() },
|
|
1411
|
+
),
|
|
1412
|
+
});
|
|
1413
|
+
```
|
|
1414
|
+
|
|
1415
|
+
The handler verifies the signature over the exact raw bytes before any write:
|
|
1416
|
+
|
|
1417
|
+
```ts
|
|
1418
|
+
// api/lifecycle-webhook.ts
|
|
1419
|
+
export default async function lifecycleWebhook(req: Request, sw: SomewhereRuntimeContext): Promise<Response> {
|
|
1420
|
+
const secret = sw.env.AUTH_WEBHOOK_SECRET
|
|
1421
|
+
if (!secret) return new Response('webhook secret not configured', { status: 500 })
|
|
1422
|
+
const raw = await req.text() // verify these exact bytes, then parse
|
|
1423
|
+
const m = /^t=(\d+),v1=([0-9a-f]{64})$/.exec(req.headers.get('X-Somewhere-Signature') ?? '')
|
|
1424
|
+
if (!m || Math.abs(Date.now() - Number(m[1])) > 5 * 60 * 1000) return new Response('forbidden', { status: 403 })
|
|
1425
|
+
const sig = new Uint8Array(32)
|
|
1426
|
+
for (let i = 0; i < 32; i++) sig[i] = parseInt(m[2].slice(i * 2, i * 2 + 2), 16)
|
|
1427
|
+
const key = await crypto.subtle.importKey('raw', new TextEncoder().encode(secret),
|
|
1428
|
+
{ name: 'HMAC', hash: 'SHA-256' }, false, ['verify'])
|
|
1429
|
+
if (!(await crypto.subtle.verify('HMAC', key, sig, new TextEncoder().encode(`${m[1]}.${raw}`)))) {
|
|
1430
|
+
return new Response('forbidden', { status: 403 })
|
|
1431
|
+
}
|
|
1432
|
+
|
|
1433
|
+
let event: unknown
|
|
1434
|
+
try { event = JSON.parse(raw) } catch { return new Response('bad payload', { status: 400 }) }
|
|
1435
|
+
const body: object = typeof event === 'object' && event !== null ? event : {}
|
|
1436
|
+
const user: object = 'user' in body && typeof body.user === 'object' && body.user !== null ? body.user : {}
|
|
1437
|
+
const type = 'type' in body ? body.type : undefined
|
|
1438
|
+
const userId = 'id' in user ? user.id : undefined
|
|
1439
|
+
// A webhook has no signed-in user, so it writes with explicit server
|
|
1440
|
+
// authority and names the owner column (user_id) itself.
|
|
1441
|
+
if (type === 'auth.user.created') {
|
|
1442
|
+
const email = 'email' in user ? user.email : undefined
|
|
1443
|
+
if (typeof userId !== 'string' || typeof email !== 'string') return new Response('bad payload', { status: 400 })
|
|
1444
|
+
const displayName = 'display_name' in user && typeof user.display_name === 'string' ? user.display_name : null
|
|
1445
|
+
await sw.db.server.insert('profiles', { user_id: userId, email, display_name: displayName },
|
|
1446
|
+
{ onConflict: 'ignore' }) // a repeated delivery is a no-op: email is unique
|
|
1447
|
+
} else if (type === 'auth.user.deleted') {
|
|
1448
|
+
if (typeof userId !== 'string') return new Response('bad payload', { status: 400 })
|
|
1449
|
+
await sw.db.server.remove('posts', { where: { user_id: userId } })
|
|
1450
|
+
await sw.db.server.remove('profiles', { where: { user_id: userId } })
|
|
1451
|
+
}
|
|
1452
|
+
return Response.json({ ok: true }) // other events on this URL are acknowledged
|
|
1453
|
+
}
|
|
1454
|
+
```
|
|
1455
|
+
|
|
1456
|
+
Web Crypto verifies the HMAC over the signed timestamp and raw body before
|
|
1457
|
+
anything is parsed or written. This is the lifecycle webhook's own HMAC;
|
|
1458
|
+
`sw.jobs.verifyInvocation` is for job, queue and cron deliveries and does
|
|
1459
|
+
not apply here.
|
|
1460
|
+
|
|
1461
|
+
Fired events: `auth.user.created`, `auth.user.updated`, `auth.user.deleted`.
|
|
1462
|
+
The same URL also receives `refresh_token_reuse` and `payment.completed`;
|
|
1463
|
+
acknowledge any type you don't handle.
|
|
1464
|
+
- `created` fires on password signup, Google-created, and magic-link-created
|
|
1465
|
+
users. Body: `{ type, user: { id, email, display_name, project_id, created_at } }`.
|
|
1466
|
+
- `updated` fires when a user edits their profile (display_name / metadata).
|
|
1467
|
+
- `deleted` fires on account deletion.
|
|
1468
|
+
A failed delivery is retried up to four attempts in all, about 10 seconds, 1 minute and 5 minutes apart; every attempt of one event carries the same `X-Somewhere-Event-Id` header, so dedupe on it.
|
|
1469
|
+
|
|
1470
|
+
## Verify signatures and imported passwords
|
|
1471
|
+
|
|
1472
|
+
Use `sw.crypto` inside a function when an integration needs its own signature
|
|
1473
|
+
check or password-hash comparison. Normal app sign-in uses `sw.auth`; it already
|
|
1474
|
+
handles passwords and sessions.
|
|
1475
|
+
|
|
1476
|
+
| Call | Result |
|
|
1477
|
+
|---|---|
|
|
1478
|
+
| `await sw.crypto.hmacSha256Hex(message, secret)` | HMAC-SHA256 of the UTF-8 message, returned as lowercase hex. Keep the secret in `sw.env`. |
|
|
1479
|
+
| `sw.crypto.timingSafeEqual(a, b)` | A boolean string comparison that checks every character when the lengths match; different lengths return false. |
|
|
1480
|
+
| `await sw.crypto.bcrypt.verify(password, hash)` | A boolean password/hash match from the platform's bcrypt verifier. Request failures throw. |
|
|
1481
|
+
|
|
1482
|
+
For incoming webhooks, verify the sender's exact signing format against the raw
|
|
1483
|
+
request body before acting on it. See `webhooks` for the platform event format;
|
|
1484
|
+
auth lifecycle webhooks use the separate format above.
|
|
1485
|
+
|
|
1486
|
+
## Member contacts
|
|
1487
|
+
|
|
1488
|
+
Use `sw.auth.server.listUsers` in a deployed function to resolve member IDs
|
|
1489
|
+
into your app's contact details. Authorize the caller first: this is explicit
|
|
1490
|
+
server access to the app's users, so ordinary group membership alone does not
|
|
1491
|
+
grant access to emails. For example, this route lets a group's owner or admin
|
|
1492
|
+
read one page of member contacts:
|
|
1493
|
+
|
|
1494
|
+
```ts
|
|
1495
|
+
// api/groups/[id]/contacts.ts
|
|
1496
|
+
export default async function (req: Request, sw: SomewhereRuntimeContext) {
|
|
1497
|
+
await sw.auth.requireUser(req);
|
|
1498
|
+
const groupId = sw.params.id;
|
|
1499
|
+
const group = await sw.groups.get(req, groupId);
|
|
1500
|
+
if (group.error) return Response.json({ error: group.error.code }, { status: group.error.status });
|
|
1501
|
+
if (group.data.role !== 'owner' && group.data.role !== 'admin') {
|
|
1502
|
+
return new Response('Only a group owner or admin may read contacts.', { status: 403 });
|
|
1503
|
+
}
|
|
1504
|
+
const cursor = new URL(req.url).searchParams.get('cursor') ?? undefined;
|
|
1505
|
+
const page = await sw.groups.members(req, groupId, { cursor });
|
|
1506
|
+
if (page.error) return Response.json({ error: page.error.code }, { status: page.error.status });
|
|
1507
|
+
const contacts = await sw.auth.server.listUsers({ ids: page.data.items.map(member => member.user_id) });
|
|
1508
|
+
return Response.json({ users: contacts.users, next_cursor: page.data.next_cursor });
|
|
1509
|
+
}
|
|
1510
|
+
```
|
|
1511
|
+
|
|
1512
|
+
Continue with the returned cursor for the next roster page. Role, roster and
|
|
1513
|
+
contact reads are separate; recheck permission for each request. For a custom
|
|
1514
|
+
organiser role, make that permission explicit in your handler. Sending a message
|
|
1515
|
+
also needs your app's permission and recipient-consent rules.
|
|
1516
|
+
|
|
1517
|
+
`listUsers({ ids })` accepts up to 200 distinct user
|
|
1518
|
+
IDs. `listUsers({ emails })` looks users up by exact address, up to
|
|
1519
|
+
200 at a time: addresses are matched without regard to
|
|
1520
|
+
case or surrounding spaces, never by partial match, and an address with no
|
|
1521
|
+
account is simply absent from `users`. Check the caller before telling anyone
|
|
1522
|
+
whether an address has an account. To find one known address, call
|
|
1523
|
+
`listUsers({ emails: [email] })`: a single exact lookup. Don't page with
|
|
1524
|
+
`{ limit, cursor }` and filter for the address. Paging is for work that needs
|
|
1525
|
+
the whole directory, such as an admin user list or an export. Without IDs or emails,
|
|
1526
|
+
`listUsers({ limit, cursor })` pages through the app's users:
|
|
1527
|
+
default 50, maximum 200 per
|
|
1528
|
+
page. Use one mode at a time. Each user has `id`, `email`,
|
|
1529
|
+
`display_name`, `email_verified` and `created_at`; the result has
|
|
1530
|
+
`users` and `next_cursor`. The contact records carry no app roles. Declare
|
|
1531
|
+
`appRole()` or an endpoint role guard for staff authorization. If you need
|
|
1532
|
+
an app-managed list of staff for assignment, track it with your app's
|
|
1533
|
+
role-assignment workflow. Suspended, deleted and agent accounts are
|
|
1534
|
+
excluded. Missing IDs are omitted. Unverified addresses carry
|
|
1535
|
+
`email_verified: false`; filter them when the action requires verification.
|
|
1536
|
+
A failed directory read throws `AUTH_DIRECTORY_UNAVAILABLE` rather than
|
|
1537
|
+
returning an empty list. Look up live users from a deployed production
|
|
1538
|
+
function or an ordinary verified cron, job or queue handler. A current
|
|
1539
|
+
deployed preview looks up only its own users. Sign up in the preview or
|
|
1540
|
+
use `somewhere preview user-add` before testing there. Row-bound jobs,
|
|
1541
|
+
development and `run_code` refuse directory lookups.
|
|
1542
|
+
|
|
1543
|
+
## Listing users in scheduled work
|
|
1544
|
+
|
|
1545
|
+
Use `sw.auth.server.listUsers({ limit, cursor })` in an ordinary verified cron,
|
|
1546
|
+
job or queue handler when the work needs every app user. Verify the invocation
|
|
1547
|
+
before directory access. Process `users`, then pass `next_cursor` as `cursor`
|
|
1548
|
+
until it is null; an empty page is not the termination signal. This is the
|
|
1549
|
+
same directory contract and exclusions as `member-contacts` above. A separate
|
|
1550
|
+
`known_users` table is unnecessary for discovering signed-up users; store only
|
|
1551
|
+
app-specific preferences in your own tables. Check consent and address
|
|
1552
|
+
verification before any email side effect.
|
|
1553
|
+
|
|
1554
|
+
## Joining users from your app data — the `auth_users` table
|
|
1555
|
+
|
|
1556
|
+
For the current user's identity, use `sw.auth.requireUser(req)`. For other
|
|
1557
|
+
users' contact details, use the authorized server helper above. Keep app-specific
|
|
1558
|
+
profile fields in declared tables with your app's access rules.
|
|
1559
|
+
|
|
1560
|
+
The `auth_users` mirror can be absent or stale and is outside managed
|
|
1561
|
+
declarations. Raw SQL in a split project cannot read it. Use structured queries
|
|
1562
|
+
for app data and verified identity for authorization.
|
|
1563
|
+
|
|
1564
|
+
To stop firing webhooks for the project:
|
|
1565
|
+
|
|
1566
|
+
```text
|
|
1567
|
+
auth_webhook_delete({ project_id: "my-app" })
|
|
1568
|
+
```
|
|
1569
|
+
|
|
1570
|
+
## Logout
|
|
1571
|
+
|
|
1572
|
+
Sign-out is already wired. `SignedInLayout` passes the `useSignOut()` hook from `src/auth/hooks.ts` to the button in `AppShell`. To sign out from somewhere else in your UI, use the same hook:
|
|
1573
|
+
|
|
1574
|
+
```tsx
|
|
1575
|
+
// src/pages/SignOutButton.tsx
|
|
1576
|
+
import { useSignOut } from '../auth/hooks';
|
|
1577
|
+
|
|
1578
|
+
export function SignOutButton() {
|
|
1579
|
+
const signOut = useSignOut();
|
|
1580
|
+
return (
|
|
1581
|
+
<>
|
|
1582
|
+
<button type="button" className="button button--quiet" onClick={() => void signOut.signOut()} disabled={signOut.pending}>
|
|
1583
|
+
{signOut.pending ? 'Signing out…' : 'Sign out'}
|
|
1584
|
+
</button>
|
|
1585
|
+
{signOut.error ? <p className="error" role="alert">{signOut.error}</p> : null}
|
|
1586
|
+
</>
|
|
1587
|
+
);
|
|
1588
|
+
}
|
|
1589
|
+
```
|
|
1590
|
+
|
|
1591
|
+
The app clears private pages as soon as sign-out starts. If the server can't confirm the sign-out, the sign-in page says so and offers to try again.
|
|
1592
|
+
|
|
1593
|
+
Update `@somewhere-cloud/sdk` and your lockfile to 0.14.1 or later,
|
|
1594
|
+
then deploy your app to use the current sign-out handler and runtime.
|
|
1595
|
+
If account revocation fails, the account cookies stay and sign-out remains
|
|
1596
|
+
unconfirmed. A temporary failure can be retried; `SESSION_NOT_FOUND` or
|
|
1597
|
+
`LOGOUT_REFRESH_REQUIRED` needs a new sign-in. If only visitor sign-out
|
|
1598
|
+
fails, the account cookies clear and the HTTP response carries
|
|
1599
|
+
`VISITOR_SIGN_OUT_UNCONFIRMED`. The SDK client reports an unconfirmed
|
|
1600
|
+
sign-out; use the starter's status and recovery UI.
|
|
1601
|
+
|
|
1602
|
+
```ts
|
|
1603
|
+
// api/sign-out.ts — cookie sessions (browser default): revoke + clear the cookies
|
|
1604
|
+
export default async function (req: Request, sw: SomewhereRuntimeContext) {
|
|
1605
|
+
if (req.method !== 'POST') return new Response('Use POST.', { status: 405, headers: { Allow: 'POST' } });
|
|
1606
|
+
const result = await sw.auth.logoutWithCookie(req); // { ok: true }
|
|
1607
|
+
return Response.json(result);
|
|
1608
|
+
}
|
|
1609
|
+
```
|
|
1610
|
+
|
|
1611
|
+
```ts
|
|
1612
|
+
// api/token-sign-out.ts — token mode: pass the session_token and/or refresh_token
|
|
1613
|
+
export default async function (req: Request, sw: SomewhereRuntimeContext) {
|
|
1614
|
+
if (req.method !== 'POST') return new Response('Use POST.', { status: 405, headers: { Allow: 'POST' } });
|
|
1615
|
+
const input: unknown = await req.json().catch(() => null);
|
|
1616
|
+
const { session_token } = (input ?? {}) as { session_token?: unknown };
|
|
1617
|
+
if (typeof session_token !== 'string') return Response.json({ error: 'session_token is required.' }, { status: 400 });
|
|
1618
|
+
const result = await sw.auth.logout({ session_token }); // { logged_out: true }
|
|
1619
|
+
return Response.json(result);
|
|
1620
|
+
}
|
|
1621
|
+
```
|
|
1622
|
+
|
|
1623
|
+
Revokes that session and its refresh tokens. An access token bound to the
|
|
1624
|
+
revoked session is refused on its next verification. Other sessions stay
|
|
1625
|
+
signed in; use the session-management tools to end them too.
|
|
1626
|
+
|
|
1627
|
+
## Visitors (before sign-in)
|
|
1628
|
+
|
|
1629
|
+
Lots of apps let a visitor do something useful before signing up (fill a
|
|
1630
|
+
cart, send a message, save a draft). Declare it on the table instead of
|
|
1631
|
+
tracking it by hand:
|
|
1632
|
+
|
|
1633
|
+
```ts
|
|
1634
|
+
// db/schema.ts
|
|
1635
|
+
import { id, owner, schema, table, text } from 'somewhere/db';
|
|
1636
|
+
|
|
1637
|
+
export default schema({
|
|
1638
|
+
cart: table({ id: id(), sku: text() }, {
|
|
1639
|
+
scope: owner({ visitors: true }),
|
|
1640
|
+
client: { read: true, create: ['sku'], delete: true, identity: 'visitor' },
|
|
1641
|
+
}),
|
|
1642
|
+
});
|
|
1643
|
+
```
|
|
1644
|
+
|
|
1645
|
+
The platform gives each visitor a signed session cookie that lasts 30 days.
|
|
1646
|
+
Rows the visitor creates belong to that session. When the visitor signs in,
|
|
1647
|
+
the platform moves those rows to the account in one step, and that visitor
|
|
1648
|
+
session can never hand rows over again, so a later account can never take an earlier
|
|
1649
|
+
account's rows. A retry or a second tab is a no-op; logging out issues a fresh
|
|
1650
|
+
visitor session. If visitor rows conflict with rows the account already has,
|
|
1651
|
+
sign-in still completes and the account's existing data is unaffected; the visitor data stays stored under the visitor session the sign-in replaced and is not merged automatically — the browser cannot reach it again. No helper and no
|
|
1652
|
+
manual migration step is needed for the declared browser
|
|
1653
|
+
flow. Server code can still read the visitor with `sw.auth.anonSession(req)`
|
|
1654
|
+
(it resolves the signed visitor session); the old `sw.auth.migrateAnon`
|
|
1655
|
+
refuses with `MIGRATE_ANON_REMOVED` (400) because the hand-over is automatic on sign-in. Full contract: the
|
|
1656
|
+
`declared-data` topic.
|
|
1657
|
+
|
|
1658
|
+
## Social OAuth
|
|
1659
|
+
|
|
1660
|
+
**Somewhere manages the Google OAuth client for your app.** Call
|
|
1661
|
+
`await sw.auth.oauthStart('google', { redirect_uri })` with a return URL on
|
|
1662
|
+
your project's subdomain or a verified custom domain attached to your
|
|
1663
|
+
project. If the return URL is rejected, check the project subdomain or
|
|
1664
|
+
attach and verify the custom domain.
|
|
1665
|
+
|
|
1666
|
+
Google sign-in only identifies the person: it asks Google for their name and
|
|
1667
|
+
email, nothing else. To add events to a signed-in user's Google Calendar, use
|
|
1668
|
+
`sw.connect.googleCalendar` (`docs({ topic: 'google-calendar' })`). It runs on
|
|
1669
|
+
the platform's Google client too, so the same rule holds: do not create Google
|
|
1670
|
+
credentials or write your own Google OAuth flow.
|
|
1671
|
+
|
|
1672
|
+
GitHub and Discord use the same project-scoped flow:
|
|
1673
|
+
|
|
1674
|
+
- `oauthStart('github', { redirect_uri })` / `githubExchange({ code })` /
|
|
1675
|
+
`githubCallbackWithCookie(req, redirectTo)`. Identity-only scopes:
|
|
1676
|
+
`read:user user:email`.
|
|
1677
|
+
- `oauthStart('discord', { redirect_uri })` / `discordExchange({ code })` /
|
|
1678
|
+
`discordCallbackWithCookie(req, redirectTo)`. Identity-only scopes:
|
|
1679
|
+
`identify email`.
|
|
1680
|
+
|
|
1681
|
+
All three providers return to the customer app with the same one-time
|
|
1682
|
+
`?code=` shape and exchange into the same project-scoped session. When a
|
|
1683
|
+
provider's verified email is the first verification of an unverified
|
|
1684
|
+
account's address, earlier sign-in methods are cleared (`docs({ topic: 'sw.auth', section: 'keeping-your-password' })`).
|
|
1685
|
+
|
|
1686
|
+
**Sign-in is bound to the browser that starts it.** `oauthStart` sets an
|
|
1687
|
+
HttpOnly cookie for this attempt on your app's response and puts only its
|
|
1688
|
+
challenge in the URL; the code is redeemed only by your server handling a
|
|
1689
|
+
request from that same browser. A browser may hold 8 open attempts
|
|
1690
|
+
(`OAUTH_START_LIMIT` after that). The old `googleUrl` / `githubUrl` /
|
|
1691
|
+
`discordUrl` refuse with `OAUTH_START_REQUIRES_BINDING`, and a start without
|
|
1692
|
+
the challenge is refused with `OAUTH_BINDING_REQUIRED`.
|
|
1693
|
+
|
|
1694
|
+
```ts
|
|
1695
|
+
// api/auth-google.ts — start sign-in and send the user's browser to Google
|
|
1696
|
+
export default async function (req: Request, sw: SomewhereRuntimeContext) {
|
|
1697
|
+
// The callback below answers /api/auth-callback on this app's own host.
|
|
1698
|
+
const url = await sw.auth.oauthStart('google', { redirect_uri: new URL('/api/auth-callback', req.url).toString() });
|
|
1699
|
+
return Response.redirect(url, 302);
|
|
1700
|
+
}
|
|
1701
|
+
```
|
|
1702
|
+
|
|
1703
|
+
After the user approves, the platform handles the Google code
|
|
1704
|
+
exchange and then bounces them back to your `redirect_uri` with a
|
|
1705
|
+
short-lived authorization code and its public attempt id in the query string:
|
|
1706
|
+
|
|
1707
|
+
https://your-app.somewhere.site/api/auth-callback?code=...&attempt=...
|
|
1708
|
+
|
|
1709
|
+
The JWT is never put in the URL. To get the JWT, your callback
|
|
1710
|
+
function exchanges the code while handling that browser's request (the
|
|
1711
|
+
runtime presents the cookie of the attempt that `attempt` names):
|
|
1712
|
+
|
|
1713
|
+
const { token, user } = await sw.auth.googleExchange({ code, attempt });
|
|
1714
|
+
|
|
1715
|
+
Codes are single-use and expire after 60 seconds. A server that is not a
|
|
1716
|
+
`sw` function keeps its own verifier in an HttpOnly cookie, sends only
|
|
1717
|
+
`challenge` (base64url SHA-256 of the verifier) on the start URL, and posts
|
|
1718
|
+
`{ code, attempt, verifier }` to the exchange, where `attempt` is the callback's
|
|
1719
|
+
`?attempt=` (the first 16 characters of that challenge).
|
|
1720
|
+
|
|
1721
|
+
Typical callback function — one line with the cookie helper:
|
|
1722
|
+
|
|
1723
|
+
```ts
|
|
1724
|
+
// api/auth-callback.ts
|
|
1725
|
+
export default async function(req: Request, sw: SomewhereRuntimeContext) {
|
|
1726
|
+
// Reads ?code, exchanges it, sets the httpOnly session cookies,
|
|
1727
|
+
// and 302s home. Tokens never touch client JS.
|
|
1728
|
+
return sw.auth.googleCallbackWithCookie(req, '/');
|
|
1729
|
+
}
|
|
1730
|
+
```
|
|
1731
|
+
|
|
1732
|
+
Call `googleExchange` directly only when you manage tokens yourself
|
|
1733
|
+
(native apps / non-browser clients) — it returns the same
|
|
1734
|
+
`{ user, token, refresh_token, session_token }` shape as `login`.
|
|
1735
|
+
|
|
1736
|
+
REST uses `GET /v1/auth/{google|github|discord}` for the URL and
|
|
1737
|
+
`POST /v1/auth/{provider}/exchange` for the code. MCP currently exposes
|
|
1738
|
+
`auth_google_url`; deployed functions use the `sw.auth` helpers above.
|
|
1739
|
+
|
|
1740
|
+
## Common pattern: protected endpoint inside a deployed function
|
|
1741
|
+
|
|
1742
|
+
```ts
|
|
1743
|
+
// api/posts.ts — uses the posts table from the db/schema.ts above
|
|
1744
|
+
export default async function(req: Request, sw: SomewhereRuntimeContext) {
|
|
1745
|
+
const user = await sw.auth.fromRequest(req);
|
|
1746
|
+
if (!user) return Response.json({ error: 'Unauthorized' }, { status: 401 });
|
|
1747
|
+
|
|
1748
|
+
// posts is owner() in db/schema.ts: rows are already scoped to this user.
|
|
1749
|
+
const posts = await sw.db.from('posts', { order: [['created_at', 'desc']] });
|
|
1750
|
+
return Response.json(posts.data);
|
|
1751
|
+
}
|
|
1752
|
+
```
|
|
1753
|
+
|
|
1754
|
+
That's it. No cookie parsing, no header slicing, no try/catch on
|
|
1755
|
+
expired tokens — all of that lives inside `fromRequest`. If you find
|
|
1756
|
+
yourself writing `req.headers.get('cookie')` inside a function, you
|
|
1757
|
+
re-implemented something that already exists.
|
|
1758
|
+
|
|
1759
|
+
## Auth emails
|
|
1760
|
+
|
|
1761
|
+
Your app's password reset, email verification, sign-in link, invitation and
|
|
1762
|
+
welcome emails are sent automatically from `noreply@somewhere.cloud` unless
|
|
1763
|
+
the project has a verified sender domain. Every project gets working auth
|
|
1764
|
+
without email setup.
|
|
1765
|
+
|
|
1766
|
+
On the platform address, auth emails always use the platform's built-in
|
|
1767
|
+
templates, with your project's name in plain text (at most 40 characters,
|
|
1768
|
+
without link prefixes such as `https://` or `www.`). Set the subject and HTML
|
|
1769
|
+
for your app's auth emails with the email-templates API. Custom templates take
|
|
1770
|
+
effect once the project has a verified sending domain. Those emails then come from `noreply@<your domain>`. You can save app
|
|
1771
|
+
auth templates before that. The templates API's `custom_templates_apply`
|
|
1772
|
+
field reports whether app auth email can use them.
|
|
1773
|
+
|
|
1774
|
+
Somewhere's own lifecycle emails, such as the welcome email for a new
|
|
1775
|
+
Somewhere account, use saved lifecycle template overrides without requiring
|
|
1776
|
+
a verified project sending domain.
|
|
1777
|
+
|
|
1778
|
+
Auth emails reach any address, with a limit on the platform address: each
|
|
1779
|
+
project can send at most 30 auth emails per clock hour and 200 per UTC day to
|
|
1780
|
+
people who have not verified their address with the project (sign-in links,
|
|
1781
|
+
invitations, sign-up welcome and verification emails, password resets). Email to
|
|
1782
|
+
the project owner and to users who have verified their address is not counted;
|
|
1783
|
+
signing up alone does not verify an address. The same 30 per hour and 200 per
|
|
1784
|
+
day also apply per account: all the projects one account owns share them, counted
|
|
1785
|
+
the same way, so a second project is not a second allowance. Because the account
|
|
1786
|
+
budget is shared, unverified sign-ups on one of your apps (anyone can type any
|
|
1787
|
+
address into a sign-up form) count against all of them: once it is used up,
|
|
1788
|
+
sign-in links, invitations and verification emails to new, unverified addresses
|
|
1789
|
+
are refused on every project of the account until the window resets. The owner
|
|
1790
|
+
and users who have verified their address are not counted, so existing users'
|
|
1791
|
+
email sign-in codes keep arriving. A project that sends from its own verified
|
|
1792
|
+
domain is outside the shared budget.
|
|
1793
|
+
Past the limit the request is refused with `EMAIL_FIRST_CONTACT_LIMIT` (HTTP
|
|
1794
|
+
429), and its message names the limit that was reached and whether it is the
|
|
1795
|
+
project's or the account's. Requests that send in the background keep their
|
|
1796
|
+
usual answer: sign-up still succeeds without its verification email (a later
|
|
1797
|
+
code request answers 429), and a password reset still answers 200. The limit applies on every plan and
|
|
1798
|
+
does not apply once the project sends from its own verified domain.
|
|
1799
|
+
|
|
1800
|
+
A project owned by a guest account (connected without signing up, not yet
|
|
1801
|
+
claimed) can send 10 auth emails per UTC day to people other than its owner who
|
|
1802
|
+
have not verified their address, on any sender, and 10 per day across all of the
|
|
1803
|
+
guest account's projects together. Past that the request is refused with `EMAIL_GUEST_PROJECT_LIMIT` (HTTP
|
|
1804
|
+
429). The owner claims the account by verifying their email, which lifts the
|
|
1805
|
+
limit. Test inbox addresses are not counted.
|
|
1806
|
+
|
|
1807
|
+
Your app's own mail through sw.email.send
|
|
1808
|
+
uses the same zero-setup sender but reaches only this project's users and its
|
|
1809
|
+
owner; to bring in someone new, use `sw.auth.invite` (Invitations above).
|
|
1810
|
+
Add a verified sender domain to email anyone else, to use your own From
|
|
1811
|
+
address, or for marketing mail.
|