@somewhere-cloud/cli 0.38.155 → 0.38.156

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (142) hide show
  1. package/CHANGELOG.md +4 -1
  2. package/dist/commands/docs.js +1 -1
  3. package/dist/lib/bundle.js +276 -188
  4. package/dist/lib/bundle.js.map +3 -3
  5. package/npm-shrinkwrap.json +2 -2
  6. package/package.json +2 -3
  7. package/dist/docs/adopt.md +0 -39
  8. package/dist/docs/analytics.md +0 -161
  9. package/dist/docs/api-reference.md +0 -339
  10. package/dist/docs/api-surface.md +0 -2067
  11. package/dist/docs/app-mcp.md +0 -162
  12. package/dist/docs/architecture-patterns.md +0 -334
  13. package/dist/docs/auth-client.md +0 -531
  14. package/dist/docs/billing.md +0 -76
  15. package/dist/docs/browser.md +0 -639
  16. package/dist/docs/calendar.md +0 -298
  17. package/dist/docs/changes.md +0 -323
  18. package/dist/docs/cli.md +0 -407
  19. package/dist/docs/common-mistakes.md +0 -199
  20. package/dist/docs/connect-agent.md +0 -72
  21. package/dist/docs/cors.md +0 -114
  22. package/dist/docs/cron.md +0 -167
  23. package/dist/docs/database-engine.md +0 -167
  24. package/dist/docs/declared-data.md +0 -1656
  25. package/dist/docs/declared-files.md +0 -475
  26. package/dist/docs/deploy-intelligence.md +0 -188
  27. package/dist/docs/deploy.md +0 -733
  28. package/dist/docs/design-system.md +0 -273
  29. package/dist/docs/dev-environments.md +0 -496
  30. package/dist/docs/domain-ownership.md +0 -31
  31. package/dist/docs/domains.md +0 -370
  32. package/dist/docs/feedback.md +0 -88
  33. package/dist/docs/file-tools.md +0 -116
  34. package/dist/docs/functions.md +0 -489
  35. package/dist/docs/getting-started.md +0 -238
  36. package/dist/docs/github.md +0 -95
  37. package/dist/docs/google-calendar.md +0 -212
  38. package/dist/docs/groups.md +0 -836
  39. package/dist/docs/guarantees.md +0 -58
  40. package/dist/docs/handled-for-you.md +0 -224
  41. package/dist/docs/inspect.md +0 -171
  42. package/dist/docs/limits.md +0 -68
  43. package/dist/docs/live-data.md +0 -197
  44. package/dist/docs/live.md +0 -92
  45. package/dist/docs/local-dev.md +0 -30
  46. package/dist/docs/migration-supabase.md +0 -58
  47. package/dist/docs/payments.md +0 -1102
  48. package/dist/docs/portability.md +0 -194
  49. package/dist/docs/postgres.md +0 -301
  50. package/dist/docs/pricing-comparison.md +0 -42
  51. package/dist/docs/pricing.md +0 -39
  52. package/dist/docs/project-groups.md +0 -107
  53. package/dist/docs/projects.md +0 -380
  54. package/dist/docs/recipe-ai-agent.md +0 -112
  55. package/dist/docs/recipe-ai-features.md +0 -227
  56. package/dist/docs/recipe-ai-receipts.md +0 -783
  57. package/dist/docs/recipe-background-jobs.md +0 -369
  58. package/dist/docs/recipe-booking.md +0 -348
  59. package/dist/docs/recipe-csv-import.md +0 -390
  60. package/dist/docs/recipe-ecommerce.md +0 -127
  61. package/dist/docs/recipe-email.md +0 -282
  62. package/dist/docs/recipe-escalation.md +0 -133
  63. package/dist/docs/recipe-file-uploads.md +0 -159
  64. package/dist/docs/recipe-import-app.md +0 -110
  65. package/dist/docs/recipe-login.md +0 -457
  66. package/dist/docs/recipe-multi-chat.md +0 -198
  67. package/dist/docs/recipe-paid-api.md +0 -161
  68. package/dist/docs/recipe-pdfs.md +0 -205
  69. package/dist/docs/recipe-push-notifications.md +0 -107
  70. package/dist/docs/recipe-seo.md +0 -200
  71. package/dist/docs/recipe-signed-in-app.md +0 -330
  72. package/dist/docs/render.md +0 -99
  73. package/dist/docs/rooms.md +0 -554
  74. package/dist/docs/sdk.md +0 -287
  75. package/dist/docs/sdks.md +0 -24
  76. package/dist/docs/search.md +0 -199
  77. package/dist/docs/security-model.md +0 -168
  78. package/dist/docs/setup.md +0 -212
  79. package/dist/docs/smoke.md +0 -102
  80. package/dist/docs/speed.md +0 -298
  81. package/dist/docs/sql-compatibility.md +0 -96
  82. package/dist/docs/sw.agent.md +0 -248
  83. package/dist/docs/sw.ai.md +0 -1291
  84. package/dist/docs/sw.auth.md +0 -1811
  85. package/dist/docs/sw.billing.md +0 -171
  86. package/dist/docs/sw.db.md +0 -2128
  87. package/dist/docs/sw.email.md +0 -661
  88. package/dist/docs/sw.endpoint.md +0 -187
  89. package/dist/docs/sw.env.md +0 -303
  90. package/dist/docs/sw.fetch.md +0 -115
  91. package/dist/docs/sw.fs.md +0 -424
  92. package/dist/docs/sw.groups.md +0 -836
  93. package/dist/docs/sw.image.md +0 -69
  94. package/dist/docs/sw.jobs.md +0 -520
  95. package/dist/docs/sw.logs.md +0 -61
  96. package/dist/docs/sw.mail.md +0 -106
  97. package/dist/docs/sw.notifications.md +0 -78
  98. package/dist/docs/sw.push.md +0 -161
  99. package/dist/docs/sw.rateLimit.md +0 -67
  100. package/dist/docs/sw.web.md +0 -128
  101. package/dist/docs/tasks.md +0 -269
  102. package/dist/docs/test.md +0 -220
  103. package/dist/docs/tool-reference-account.md +0 -7
  104. package/dist/docs/tool-reference-ai.md +0 -121
  105. package/dist/docs/tool-reference-analytics.md +0 -37
  106. package/dist/docs/tool-reference-api.md +0 -19
  107. package/dist/docs/tool-reference-artifacts.md +0 -35
  108. package/dist/docs/tool-reference-auth.md +0 -163
  109. package/dist/docs/tool-reference-browser.md +0 -114
  110. package/dist/docs/tool-reference-code.md +0 -26
  111. package/dist/docs/tool-reference-connect.md +0 -21
  112. package/dist/docs/tool-reference-cron.md +0 -48
  113. package/dist/docs/tool-reference-db.md +0 -282
  114. package/dist/docs/tool-reference-domains.md +0 -107
  115. package/dist/docs/tool-reference-email.md +0 -55
  116. package/dist/docs/tool-reference-env.md +0 -19
  117. package/dist/docs/tool-reference-feedback.md +0 -56
  118. package/dist/docs/tool-reference-fs.md +0 -265
  119. package/dist/docs/tool-reference-github.md +0 -57
  120. package/dist/docs/tool-reference-groups.md +0 -85
  121. package/dist/docs/tool-reference-help.md +0 -29
  122. package/dist/docs/tool-reference-jobs.md +0 -39
  123. package/dist/docs/tool-reference-live.md +0 -48
  124. package/dist/docs/tool-reference-logs.md +0 -16
  125. package/dist/docs/tool-reference-payments.md +0 -44
  126. package/dist/docs/tool-reference-project.md +0 -706
  127. package/dist/docs/tool-reference-push.md +0 -78
  128. package/dist/docs/tool-reference-rate-limit.md +0 -18
  129. package/dist/docs/tool-reference-search.md +0 -68
  130. package/dist/docs/tool-reference-security.md +0 -42
  131. package/dist/docs/tool-reference-smoke.md +0 -17
  132. package/dist/docs/tool-reference-stock-photos.md +0 -20
  133. package/dist/docs/tool-reference-tasks.md +0 -73
  134. package/dist/docs/tool-reference-telegram.md +0 -32
  135. package/dist/docs/tool-reference-usage.md +0 -9
  136. package/dist/docs/tool-reference-web.md +0 -71
  137. package/dist/docs/tool-reference-webhooks.md +0 -9
  138. package/dist/docs/troubleshooting.md +0 -411
  139. package/dist/docs/typed-functions.md +0 -94
  140. package/dist/docs/verify-before-deploy.md +0 -67
  141. package/dist/docs/vs-supabase.md +0 -75
  142. package/dist/docs/vs-vercel.md +0 -103
@@ -1,110 +0,0 @@
1
- # Recipe — Bring an existing app
2
-
3
- A Vite + React app deploys as it is. The platform compiles raw source on
4
- every deploy, so it needs no build step and no layout change. What you move by hand is whatever ran on another backend: server
5
- routes become functions in `api/`, and Supabase data, users and files move
6
- with the steps below.
7
-
8
- ## From a GitHub repository
9
-
10
- ```bash
11
- somewhere git connect owner/name --project <project> --branch main
12
- ```
13
-
14
- This connects the repository to the project, opens GitHub once if the GitHub
15
- App is not yet installed, deploys the branch's current commit, waits for it
16
- and prints the live URL. Every later push to that branch deploys the same
17
- way. Inside a folder already linked with `somewhere init`, `--project` is not
18
- needed. For a monorepo, add `--root <app folder>`. The MCP tools for the same
19
- flow (`github_app_install`, `github_installations`, `github_connect`) are in
20
- `github`.
21
-
22
- ## From a folder on disk
23
-
24
- Ask before destructive or paid actions unless the user already authorized them.
25
-
26
- ```bash
27
- cd my-app
28
- somewhere init --name my-app # link this folder to a new project and keep its source
29
- somewhere deploy-check # compiles exactly what deploy would publish, publishes nothing
30
- somewhere deploy
31
- ```
32
-
33
- `somewhere init` adds `.somewhere.json` to link the folder.
34
- To update an app already live on Somewhere, start with `somewhere pull <app>`
35
- in a fresh folder, then apply your changes to that source. The CLI never uploads `node_modules`, `.git`, `.env`, `dist`
36
- or `.next`. Deploy from the project root; the platform builds `src/`, so
37
- `dist/` is not needed.
38
-
39
- ## From a zip
40
-
41
- Unzip it, then deploy the folder as above. The zip itself is not a deploy
42
- input.
43
-
44
- ## What has to change in the code
45
-
46
- | You have | Do this |
47
- |---|---|
48
- | Vite + React (any folder layout under a root `index.html`) | Nothing. Deploy it. |
49
- | Plain HTML, CSS and JS | Nothing. A root `index.html` is enough; `package.json` is optional. |
50
- | Create React App (`public/index.html`) | Move `index.html` to the root, remove `%PUBLIC_URL%` from it, rename `src/index.js` to `src/index.jsx` (a page script compiles only as `.jsx` or `.tsx`; a `.js` one is served as-is), and add `<script type="module" src="/src/index.jsx"></script>`. Other `.js` files with JSX compile as they are. |
51
- | Express, Fastify or Koa routes | Rewrite each route as a function file in `api/` that returns a `Response` (below). A server file is not run. |
52
- | Next.js | Pages become a Vite React app with a router; API routes become functions in `api/`. Server-side rendering does not run here. |
53
- | Environment variables | `somewhere env set NAME value` (`--stdin` for a secret); functions read `sw.env.NAME`. A `VITE_` value the page reads needs `--public` (`sw.env`). |
54
-
55
- A function is one file per route. `api/users/[id].ts` serves
56
- `/api/users/:id`:
57
-
58
- ```ts
59
- // api/users/[id].ts — what an Express `app.get('/api/users/:id', …)` becomes
60
- export async function GET(request: Request, sw: SomewhereRuntimeContext): Promise<Response> {
61
- const user = await sw.auth.fromRequest(request);
62
- if (!user) return Response.json({ error: 'Sign in.' }, { status: 401 });
63
- const id = new URL(request.url).pathname.split('/').pop();
64
- return Response.json({ id, viewer: user.id });
65
- }
66
- ```
67
-
68
- Export `GET`, `POST` and the other methods by name, or one default function
69
- that handles every method; a method with no handler answers 405. Database,
70
- auth, files, email and AI are `sw.*` calls inside the function, not HTTP
71
- clients you configure. Contract: `functions`.
72
-
73
- ## From Supabase, or a Lovable app on Supabase
74
-
75
- A Lovable export is a Vite + React app on Supabase, so the frontend deploys
76
- unchanged and the backend moves in four steps (`migration-supabase` has each
77
- in full):
78
-
79
- 1. Declare your tables and who may read and write them in `db/schema.ts`,
80
- then replace `supabase.from(...)` calls with the generated `somewhere:data`
81
- client (`declared-data`).
82
- 2. Switch sign-in to the starter's cookie session (`recipe-login`). Remove the
83
- Supabase keys from browser code.
84
- 3. Users create their accounts again with the same email address (importing
85
- users with their passwords is not available). New accounts get new
86
- IDs; remap ownership columns by email before loading rows.
87
- 4. Copy files with their visibility (`declared-files`), and move each table's
88
- rows. To keep the data in PostgreSQL instead, attach it (`postgres`).
89
-
90
- Edge Functions become functions in `api/` as in the table above.
91
-
92
- ## From another builder's code export
93
-
94
- Put pages and components under `src/` with a root `index.html` and a router,
95
- and move each server endpoint into `api/` as a named `GET` or `POST` export
96
- that returns a `Response`. A Floot export maps file by file:
97
- `endpoints/<route>/<name>_GET.ts` becomes the `GET` export of
98
- `api/<route>/<name>.ts`, and its `.schema.ts` input check moves into that
99
- function.
100
-
101
- ## Check it
102
-
103
- ```bash
104
- somewhere typecheck && somewhere deploy-check && somewhere deploy
105
- somewhere verify --project <project> --flow flow.json
106
- ```
107
-
108
- `deploy-check` reports compile and function errors before anything is
109
- published. After the deploy, sign in with two accounts and a signed-out
110
- visitor and confirm each sees only what it should (`verify-before-deploy`).
@@ -1,457 +0,0 @@
1
- # Recipe — Sign-in: the starter, your data, then providers
2
-
3
- Users sign up and in with the starter's email-and-password page, your
4
- functions know who is calling, and each user sees only their own rows. Add
5
- Google, GitHub or Discord, sign-in links or a second factor only when the app
6
- needs them.
7
-
8
- ## 1. What the starter already does
9
-
10
- `somewhere init` writes sign-in end to end:
11
-
12
- | File | What it does |
13
- |---|---|
14
- | `api/auth/[...path].ts` | One line, `export { somewhereAuth as default } from '@somewhere-cloud/sdk/server'`, serving `/api/auth/signup`, `login`, `logout`, `me`, `magic-link`, `magic-link/verify`, `verify-email`, `request-email-verification` and the Google/GitHub/Discord sign-in routes. |
15
- | `src/services/auth.ts` | Creates and shares one browser client with `createSomewhereAuth()`. |
16
- | `src/auth/hooks.ts`, `src/pages/SignInPage.tsx`, `src/ui/AuthCard.tsx` | The sign-in and sign-up form, the signed-in check and sign-out. |
17
- | `src/auth/useEmailVerification.ts`, `src/ui/VerifyEmail.tsx` | The "Verify your email" panel a password account sees until it enters the emailed code. |
18
-
19
- Signing in sets the session as HttpOnly `__Host-` cookies, so page
20
- JavaScript, including an injected script, can't read the session token or
21
- send it elsewhere. A script running in the page can still make requests that
22
- carry the cookie, so keep untrusted HTML out of your pages. Password
23
- sign-in already limits attempts per IP address and per email, with progressive
24
- lockout: `sw.auth` → `automatic-password-sign-in-protection`.
25
-
26
- ## 2. Your endpoint and the signed-in user
27
-
28
- Ask before destructive or paid actions unless the user already authorized them.
29
-
30
- Run `somewhere init --name my-app --features private-data`. The starter's
31
- `db/schema.ts` declares a `notes` table owned by each user.
32
-
33
- ```ts
34
- // db/schema.ts
35
- import { id, owner, schema, table, text } from 'somewhere/db';
36
-
37
- export default schema({
38
- notes: table(
39
- { id: id(), title: text(), body: text({ default: '' }) },
40
- {
41
- scope: owner(),
42
- client: { read: ['id', 'title', 'body'], create: ['title', 'body'], update: ['title', 'body'], delete: true, identity: 'authenticated' },
43
- },
44
- ),
45
- });
46
- ```
47
-
48
- A function reads the caller from the request and answers with their data:
49
-
50
- ```ts
51
- // api/summary.ts — GET: the signed-in user's own summary
52
- export default sw.endpoint({
53
- auth: 'required',
54
- handler: async ({ user }, sw) => {
55
- // notes is owner(): the count covers only the caller's rows.
56
- const { data: notes } = await sw.db.count('notes');
57
- return { email: user.email, notes };
58
- },
59
- });
60
- ```
61
-
62
- The page calls it through the same client, which carries the session:
63
-
64
- ```ts
65
- // src/services/summary.ts
66
- import { auth } from './auth';
67
-
68
- export interface Summary { email: string | null; notes: number }
69
-
70
- export async function loadSummary(): Promise<Summary | null> {
71
- const response = await auth.fetch('/api/summary');
72
- if (response.status === 401) return null; // signed out
73
- if (!response.ok) throw new Error(`Summary failed (${response.status})`);
74
- return (await response.json()) as Summary;
75
- }
76
- ```
77
-
78
- `auth: 'required'` verifies the session before calling the handler and returns
79
- 401 for a signed-out request. Owner scopes, shared rows and server authority:
80
- `declared-data`.
81
-
82
- ## 3. Check it with two users
83
-
84
- Deploy, then confirm a signed-out request is refused:
85
-
86
- ```bash
87
- somewhere deploy
88
- # Set PROJECT to your app's subdomain.
89
- curl -i "https://${PROJECT}.somewhere.site/api/summary" # 401 {"error":"Sign in."}
90
- ```
91
-
92
- Then run two people in their own browsers: `browser` →
93
- `several-users-in-one-run` has the exact flow for this starter. Alice signs up
94
- and adds a note, Bob signs up and sees none of hers. Sign up with
95
- `<name>@<project>.test.somewhere.site` addresses, and read their sign-in email
96
- with `somewhere email test-inbox <address>`.
97
-
98
- ## 4. Google, GitHub or Discord
99
-
100
- The platform provides these sign-in clients. They work without app-specific
101
- OAuth credentials or a Google Cloud project.
102
-
103
- ```tsx
104
- // src/ui/GoogleButton.tsx — place it beside the form in src/ui/AuthCard.tsx
105
- import { useState } from 'react';
106
- import { auth, authErrorMessage } from '../services/auth';
107
-
108
- export function GoogleButton() {
109
- const [pending, setPending] = useState(false);
110
- const [error, setError] = useState<string | null>(null);
111
- async function start() {
112
- setPending(true);
113
- setError(null);
114
- try {
115
- const url = await auth.googleSignInUrl({ redirectUri: `${window.location.origin}/auth/callback` });
116
- window.location.assign(url);
117
- } catch (reason: unknown) {
118
- setError(authErrorMessage(reason));
119
- setPending(false);
120
- }
121
- }
122
- return (
123
- <>
124
- <button type="button" className="button button--quiet" onClick={() => void start()} disabled={pending}>
125
- {pending ? 'Opening Google…' : 'Continue with Google'}
126
- </button>
127
- {error ? <p className="error" role="alert">{error}</p> : null}
128
- </>
129
- );
130
- }
131
- ```
132
-
133
- ```tsx
134
- // src/pages/AuthCallbackPage.tsx — the page at /auth/callback
135
- import { useState } from 'react';
136
- import { AuthCallback } from '@somewhere-cloud/sdk/react';
137
-
138
- export function AuthCallbackPage() {
139
- const [failed, setFailed] = useState(false);
140
- return (
141
- <main className="loading">
142
- {/* Shows "Signing you in…", then the error; on success it opens / */}
143
- <p role={failed ? 'alert' : 'status'}><AuthCallback provider="google" onError={() => setFailed(true)} /></p>
144
- {failed ? <a href="/">Back to sign-in</a> : null}
145
- </main>
146
- );
147
- }
148
- ```
149
-
150
- The person isn't signed in yet when they land on `/auth/callback` or
151
- `/auth/magic`, so these pages go in front of the starter's sign-in gate, not
152
- inside the signed-in routes. This is the starter's `src/App.tsx` with both
153
- pages added in front of the gate; `MagicLinkPage` is in step 5:
154
-
155
- ```tsx
156
- // src/App.tsx
157
- import type { User } from '../types/auth';
158
- import { useAuthState } from './auth/hooks';
159
- import { APP_NAME } from './config';
160
- import { AuthCallbackPage } from './pages/AuthCallbackPage';
161
- import { HomePage } from './pages/HomePage';
162
- import { MagicLinkPage } from './pages/MagicLinkPage';
163
- import { NotFoundPage } from './pages/NotFoundPage';
164
- import { SignInPage } from './pages/SignInPage';
165
- import { linkTo, ROUTES, usePathname } from './routes';
166
- import { AppShell } from './ui/AppShell';
167
- import { SessionUnavailable } from './ui/feedback';
168
-
169
- export function App() {
170
- const pathname = usePathname();
171
- const session = useAuthState();
172
-
173
- // Sign-in returns run before the gate: the session doesn't exist until they finish.
174
- if (pathname === '/auth/callback') return <AuthCallbackPage />;
175
- if (pathname === '/auth/magic') return <MagicLinkPage />;
176
-
177
- // Before the server has answered, the app's frame shows at once, with no
178
- // account and no full-page loading screen; the page fills in on the answer.
179
- if (session.status === 'loading' || session.status === 'signing-out') {
180
- return (
181
- <AppShell appName={APP_NAME} homeLink={linkTo(ROUTES.home)} busy>
182
- {session.status === 'signing-out' ? <p role="status">Signing out…</p> : null}
183
- </AppShell>
184
- );
185
- }
186
- if (session.status === 'signed-out') return <SignInPage />;
187
- if (session.status === 'unavailable') {
188
- return <SessionUnavailable keepsWork={false} checkStatus={session.checkStatus} retrying={session.retrying} onRetry={session.retry} />;
189
- }
190
- const suspended = session.status === 'suspended';
191
- return (
192
- <>
193
- {suspended ? <SessionUnavailable keepsWork checkStatus={session.checkStatus} retrying={session.retrying} onRetry={session.retry} /> : null}
194
- <div hidden={suspended} inert={suspended}>
195
- <PrivateRoutes key={session.user.id} user={session.user} />
196
- </div>
197
- </>
198
- );
199
- }
200
-
201
- function PrivateRoutes({ user }: { user: User }) {
202
- const pathname = usePathname();
203
- switch (pathname) {
204
- case ROUTES.home:
205
- return <HomePage user={user} />;
206
- default:
207
- return <NotFoundPage user={user} />;
208
- }
209
- }
210
- ```
211
-
212
- The provider returns with a one-time `?code=`; `AuthCallback` exchanges it for
213
- the cookie session and opens `/`, so no session token ever appears in a URL. GitHub and Discord are the same
214
- with `githubSignInUrl` / `discordSignInUrl` and `provider="github"` or
215
- `"discord"`. The redirect must be on your project's address or a domain
216
- attached to it: `sw.auth` → `social-oauth`.
217
-
218
- ## 5. Sign-in links
219
-
220
- ```ts
221
- // src/services/sign-in-link.ts — call from a form on the sign-in page
222
- import { auth } from './auth';
223
-
224
- export function sendSignInLink(email: string): Promise<void> {
225
- return auth.sendMagicLink({ email });
226
- }
227
- ```
228
-
229
- ```tsx
230
- // src/pages/MagicLinkPage.tsx — /auth/magic, the page the emailed link opens
231
- import { useEffect, useRef, useState } from 'react';
232
- import { auth, authErrorMessage } from '../services/auth';
233
-
234
- export function MagicLinkPage() {
235
- const [error, setError] = useState<string | null>(null);
236
- const started = useRef(false);
237
- useEffect(() => {
238
- if (started.current) return; // the token works once; never verify it twice
239
- started.current = true;
240
- const token = new URLSearchParams(window.location.search).get('token');
241
- if (!token) {
242
- setError('This sign-in link is incomplete. Request a new one.');
243
- return;
244
- }
245
- auth.verifyMagicLink({ token })
246
- .then(() => window.location.replace('/'))
247
- .catch((reason: unknown) => setError(authErrorMessage(reason)));
248
- }, []);
249
- return (
250
- <main className="loading">
251
- <p role={error ? 'alert' : 'status'}>{error ?? 'Signing you in…'}</p>
252
- {error ? <a href="/">Back to sign-in</a> : null}
253
- </main>
254
- );
255
- }
256
- ```
257
-
258
- The email links to `/auth/magic?token=…` on your app, which `src/App.tsx`
259
- above sends to this page.
260
- The link works once; a completed sign-in uses the same cookie session. Details and expiry: `sw.auth` →
261
- `magic-links-passwordless-sign-in`.
262
-
263
- Sign-in links, verification codes and invitations come from the platform's
264
- auth sender and reach any address. Your own `sw.email.send` mail reaches only
265
- this project's users and its owner unless you add a sender domain, so invite
266
- new people with `sw.auth.invite` (`sw.auth` → `invitations`). Verifying
267
- the address of a password account: `sw.auth` → `with-a-cookie-session`.
268
-
269
- ## 6. A second factor
270
-
271
- Email sign-in codes: the app owner sets the policy (`PUT /v1/auth/mfa/policy`,
272
- `optional` or `required`), and then a password sign-in answers
273
- `{ mfa_required: true, mfa_token }` with no session until the user enters the code
274
- from their email (`sw.auth.mfa.challengeWithCookie({ mfa_token, code })`). The
275
- full contract, turning codes off and the 72-hour recovery: `sw.auth` →
276
- `email-sign-in-codes`. Authenticator-app codes are not available.
277
-
278
- ## 7. Sign out
279
-
280
- The starter's sign-out button already calls `auth.signOut()`. Private pages
281
- close as soon as sign-out starts. Two answers are shown, never hidden:
282
-
283
- - **Sign-out not confirmed.** The server failed to confirm revocation, so the
284
- session may still be active. The starter shows "We couldn't confirm sign-out with
285
- the server" with **Sign out again**.
286
- - **Session can't be checked.** A sign-in check failed without an answer. The
287
- starter shows "We can't confirm your sign-in" with **Try again**. Until the
288
- server answers, the user is neither signed in nor signed out; a user it had
289
- already confirmed keeps their unsaved work.
290
-
291
- To sign out from another place, use `useSignOut()` from `src/auth/hooks.ts`
292
- (`sw.auth` → `logout`).
293
-
294
- ## 7. Team invites
295
-
296
- A team app on built-in groups: someone creates a team and becomes its owner,
297
- invites people by email, and the members share the team's tasks. The platform
298
- keeps the team, its members, their roles and the invitations; you declare
299
- which rows belong to a team and add your own rules about rows.
300
-
301
- ### Team tables
302
-
303
- ```ts
304
- // db/schema.ts
305
- import { boolean, group, id, schema, table, text } from 'somewhere/db';
306
-
307
- export default schema({
308
- tasks: table(
309
- {
310
- id: id(),
311
- team_id: text(),
312
- title: text(),
313
- done: boolean({ default: false }),
314
- created_by: text(),
315
- },
316
- {
317
- scope: group({ column: 'team_id' }),
318
- // Members read and edit from the browser; api/tasks.ts creates and deletes.
319
- client: { read: ['id', 'team_id', 'title', 'done', 'created_by'], create: null, update: ['title', 'done'], delete: false },
320
- },
321
- ),
322
- });
323
- ```
324
-
325
- There is no teams table and no membership table: a team is a built-in group,
326
- and `team_id` holds its id.
327
-
328
- ### Create a team
329
-
330
- ```ts
331
- // api/teams.ts — POST { name } creates a team owned by the caller; GET lists the caller's teams
332
- export default async function teams(req: Request, sw: SomewhereRuntimeContext): Promise<Response> {
333
- if (req.method !== 'POST' && req.method !== 'GET') {
334
- return new Response(null, { status: 405, headers: { Allow: 'GET, POST' } });
335
- }
336
- if (!(await sw.auth.fromRequest(req))) return Response.json({ error: 'Sign in first.' }, { status: 401 });
337
- if (req.method === 'GET') {
338
- // Also finishes any accepted invitation not yet confirmed, and reports it.
339
- const listed = await sw.groups.list(req);
340
- if (listed.error) return Response.json({ error: listed.error.message }, { status: listed.error.status });
341
- return Response.json({ teams: listed.data.items, invitations: listed.data.invitations });
342
- }
343
- const body = (await req.json().catch(() => null)) as { name?: unknown } | null;
344
- const name = typeof body?.name === 'string' ? body.name.trim() : '';
345
- if (!name) return Response.json({ error: 'Name the team.' }, { status: 400 });
346
- const created = await sw.groups.create(req, { name });
347
- if (created.error) return Response.json({ error: created.error.message }, { status: created.error.status });
348
- return Response.json({ team_id: created.data.id }, { status: 201 });
349
- }
350
- ```
351
-
352
- ### Invite, then join
353
-
354
- ```ts
355
- // api/invites.ts — POST { team_id, email }: an owner or admin invites a member
356
- export default async function invite(req: Request, sw: SomewhereRuntimeContext): Promise<Response> {
357
- if (req.method !== 'POST') return new Response(null, { status: 405, headers: { Allow: 'POST' } });
358
- if (!(await sw.auth.fromRequest(req))) return Response.json({ error: 'Sign in first.' }, { status: 401 });
359
- const body = (await req.json().catch(() => null)) as { team_id?: unknown; email?: unknown } | null;
360
- if (typeof body?.team_id !== 'string' || typeof body.email !== 'string') {
361
- return Response.json({ error: 'Send team_id and email.' }, { status: 400 });
362
- }
363
- const invited = await sw.groups.invite(req, body.team_id, { email: body.email, role: 'member', redirect_uri: '/join' });
364
- // ROLE_NOT_GRANTABLE: the caller's role can't invite members; no email was sent.
365
- if (invited.error) return Response.json({ error: invited.error.message, code: invited.error.code }, { status: invited.error.status });
366
- return Response.json({ id: invited.data.invite.id, delivery: invited.data.delivery });
367
- }
368
- ```
369
-
370
- The email links to your app's `/auth/magic` page. Following it signs the
371
- invitee in as the invited address and opens `/join?invite_id=<id>`. The sign-in
372
- result reports the membership in `group_invitation`: `completed` means they are
373
- a member with the invited role; `pending` means it is not confirmed yet;
374
- `refused` carries a `code`, for example `INVITATION_REVOKED` or
375
- `INVITATION_AUTHORITY_LOST` when the inviter can no longer grant the role. Your
376
- `/join` page loads `GET /api/teams`: listing the user's teams also completes
377
- pending invitations, a few at a time, and reports each one in `invitations`.
378
- Your app never adds the member itself.
379
-
380
- The emailed link is a one-time sign-in for the invited address. Whoever opens
381
- it is signed in as that address, and that address becomes the member, so treat
382
- the link like a password: it must not be forwarded. The membership always
383
- belongs to the invited address, never to another account the person opening it
384
- was already signed in as. An invitation expires at its `expires_at`
385
- (`expires_in` sets how long it lasts). To withdraw one earlier, call
386
- `sw.groups.revokeInvitation(req, inviteId)` from a function, with the `id`
387
- that `api/invites.ts` returned; the group's own rules decide who may.
388
- Re-inviting is how a removed member comes back.
389
-
390
- ### Who created a task comes from the session
391
-
392
- `created_by` is an ordinary column. If the browser could write it, any
393
- member could create a task in someone else's name, so tasks are created and
394
- deleted here. To let the creator or a team owner delete, declare it instead
395
- of writing it: `sw.db` → `owner-or-member-and-parent-access` ("creator or
396
- team owner can delete") does it with `anyOf(owner(), group(...))` and built-in
397
- groups. For a roster your app manages without email verification, see
398
- `somewhere docs declared-data --section teams-without-email-verification`.
399
-
400
- ```ts
401
- // api/tasks.ts — POST { team_id, title } adds a task; DELETE { id } removes your own
402
- export default async function tasks(req: Request, sw: SomewhereRuntimeContext): Promise<Response> {
403
- if (req.method !== 'POST' && req.method !== 'DELETE') {
404
- return new Response(null, { status: 405, headers: { Allow: 'POST, DELETE' } });
405
- }
406
- const user = await sw.auth.requireUser(req);
407
- const body = (await req.json().catch(() => null)) as { id?: unknown; team_id?: unknown; title?: unknown } | null;
408
- if (req.method === 'DELETE') {
409
- if (typeof body?.id !== 'string' || body.id === '') {
410
- return Response.json({ error: 'Send the task id.' }, { status: 400 });
411
- }
412
- // group() limits this to the caller's teams; "only the creator" is this app's rule.
413
- const { changes } = await sw.db.remove('tasks', { where: { id: body.id, created_by: user.id } });
414
- return changes === 1 ? Response.json({ deleted: true }) : Response.json({ error: 'Only its creator can delete a task.' }, { status: 404 });
415
- }
416
- if (typeof body?.team_id !== 'string' || typeof body.title !== 'string') {
417
- return Response.json({ error: 'Send team_id and title.' }, { status: 400 });
418
- }
419
- // group() checks the caller belongs to team_id: 403 POLICY_AUTHORITY_REQUIRED otherwise.
420
- const { data: [task] } = await sw.db.insert('tasks', { team_id: body.team_id, title: body.title, created_by: user.id });
421
- return Response.json({ task });
422
- }
423
- ```
424
-
425
- The body cannot choose the creator: the function never reads one. The
426
- browser keeps the generated client for `data.tasks.list`, `get` and
427
- `update`.
428
-
429
- ### Which rule lives where
430
-
431
- - **The platform:** who belongs to a team and with which role, who may invite
432
- or change roles, and who may read or change a task (current members of its
433
- team), on every path: the generated client, `/__sw/data`,
434
- `sw.db.from`/`insert`/`update`/`remove` and `sw.db.tx`.
435
- - **Your functions:** rules about rows (only the creator deletes). A rule about
436
- another person's membership, such as "the payer must be in the team", is a
437
- read with `sw.groups.members` in your function before the write.
438
- - **Work with no user** (a webhook, a cron): `sw.db.server.*`, after your
439
- function has authorized it.
440
-
441
- ### Check the team flow
442
-
443
- - Invite `bob@<project>.test.somewhere.site`, then
444
- `somewhere email test-inbox bob@<project>.test.somewhere.site` prints the
445
- one invite email and its link.
446
- - Open the link in a browser: Bob is signed in, lands on `/join`, and
447
- `GET /api/teams` lists the team.
448
- - As a non-member, call `/__sw/data` directly for `tasks`: `list` → `[]`,
449
- `get` → `null`, `update` → 404 (`declared-data` →
450
- `calling-the-data-endpoint-directly`).
451
- - The same check works in a preview with preview users: the invite is captured
452
- (`somewhere preview mail`), and Bob signs up with the invited address and
453
- verifies it instead of opening a sign-in link.
454
-
455
- An app that already keeps its own membership table with `member()` keeps
456
- working; moving it to built-in groups is an explicit mapping
457
- (`sw.groups` → `apps-with-their-own-membership-table`).