@somewhere-cloud/cli 0.38.153 → 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.
Files changed (147) hide show
  1. package/CHANGELOG.md +11 -0
  2. package/dist/docs/adopt.md +39 -0
  3. package/dist/docs/analytics.md +161 -0
  4. package/dist/docs/api-reference.md +339 -0
  5. package/dist/docs/api-surface.md +2067 -0
  6. package/dist/docs/app-mcp.md +162 -0
  7. package/dist/docs/architecture-patterns.md +334 -0
  8. package/dist/docs/auth-client.md +531 -0
  9. package/dist/docs/billing.md +76 -0
  10. package/dist/docs/browser.md +639 -0
  11. package/dist/docs/calendar.md +298 -0
  12. package/dist/docs/changes.md +323 -0
  13. package/dist/docs/cli.md +407 -0
  14. package/dist/docs/common-mistakes.md +199 -0
  15. package/dist/docs/connect-agent.md +72 -0
  16. package/dist/docs/cors.md +114 -0
  17. package/dist/docs/cron.md +167 -0
  18. package/dist/docs/database-engine.md +167 -0
  19. package/dist/docs/declared-data.md +1656 -0
  20. package/dist/docs/declared-files.md +475 -0
  21. package/dist/docs/deploy-intelligence.md +188 -0
  22. package/dist/docs/deploy.md +733 -0
  23. package/dist/docs/design-system.md +273 -0
  24. package/dist/docs/dev-environments.md +496 -0
  25. package/dist/docs/domain-ownership.md +31 -0
  26. package/dist/docs/domains.md +370 -0
  27. package/dist/docs/feedback.md +88 -0
  28. package/dist/docs/file-tools.md +116 -0
  29. package/dist/docs/functions.md +489 -0
  30. package/dist/docs/getting-started.md +238 -0
  31. package/dist/docs/github.md +95 -0
  32. package/dist/docs/google-calendar.md +212 -0
  33. package/dist/docs/groups.md +836 -0
  34. package/dist/docs/guarantees.md +58 -0
  35. package/dist/docs/handled-for-you.md +224 -0
  36. package/dist/docs/inspect.md +171 -0
  37. package/dist/docs/limits.md +68 -0
  38. package/dist/docs/live-data.md +197 -0
  39. package/dist/docs/live.md +92 -0
  40. package/dist/docs/local-dev.md +30 -0
  41. package/dist/docs/migration-supabase.md +58 -0
  42. package/dist/docs/payments.md +1102 -0
  43. package/dist/docs/portability.md +194 -0
  44. package/dist/docs/postgres.md +301 -0
  45. package/dist/docs/pricing-comparison.md +42 -0
  46. package/dist/docs/pricing.md +39 -0
  47. package/dist/docs/project-groups.md +107 -0
  48. package/dist/docs/projects.md +380 -0
  49. package/dist/docs/recipe-ai-agent.md +112 -0
  50. package/dist/docs/recipe-ai-features.md +227 -0
  51. package/dist/docs/recipe-ai-receipts.md +783 -0
  52. package/dist/docs/recipe-background-jobs.md +369 -0
  53. package/dist/docs/recipe-booking.md +348 -0
  54. package/dist/docs/recipe-csv-import.md +390 -0
  55. package/dist/docs/recipe-ecommerce.md +127 -0
  56. package/dist/docs/recipe-email.md +282 -0
  57. package/dist/docs/recipe-escalation.md +133 -0
  58. package/dist/docs/recipe-file-uploads.md +159 -0
  59. package/dist/docs/recipe-import-app.md +110 -0
  60. package/dist/docs/recipe-login.md +457 -0
  61. package/dist/docs/recipe-multi-chat.md +198 -0
  62. package/dist/docs/recipe-paid-api.md +161 -0
  63. package/dist/docs/recipe-pdfs.md +205 -0
  64. package/dist/docs/recipe-push-notifications.md +107 -0
  65. package/dist/docs/recipe-seo.md +200 -0
  66. package/dist/docs/recipe-signed-in-app.md +330 -0
  67. package/dist/docs/render.md +99 -0
  68. package/dist/docs/rooms.md +554 -0
  69. package/dist/docs/sdk.md +287 -0
  70. package/dist/docs/sdks.md +24 -0
  71. package/dist/docs/search.md +199 -0
  72. package/dist/docs/security-model.md +168 -0
  73. package/dist/docs/setup.md +212 -0
  74. package/dist/docs/smoke.md +102 -0
  75. package/dist/docs/speed.md +298 -0
  76. package/dist/docs/sql-compatibility.md +96 -0
  77. package/dist/docs/sw.agent.md +248 -0
  78. package/dist/docs/sw.ai.md +1291 -0
  79. package/dist/docs/sw.auth.md +1811 -0
  80. package/dist/docs/sw.billing.md +171 -0
  81. package/dist/docs/sw.db.md +2128 -0
  82. package/dist/docs/sw.email.md +661 -0
  83. package/dist/docs/sw.endpoint.md +187 -0
  84. package/dist/docs/sw.env.md +303 -0
  85. package/dist/docs/sw.fetch.md +115 -0
  86. package/dist/docs/sw.fs.md +424 -0
  87. package/dist/docs/sw.groups.md +836 -0
  88. package/dist/docs/sw.image.md +69 -0
  89. package/dist/docs/sw.jobs.md +520 -0
  90. package/dist/docs/sw.logs.md +61 -0
  91. package/dist/docs/sw.mail.md +106 -0
  92. package/dist/docs/sw.notifications.md +78 -0
  93. package/dist/docs/sw.push.md +161 -0
  94. package/dist/docs/sw.rateLimit.md +67 -0
  95. package/dist/docs/sw.web.md +128 -0
  96. package/dist/docs/tasks.md +269 -0
  97. package/dist/docs/test.md +220 -0
  98. package/dist/docs/tool-reference-account.md +7 -0
  99. package/dist/docs/tool-reference-ai.md +121 -0
  100. package/dist/docs/tool-reference-analytics.md +37 -0
  101. package/dist/docs/tool-reference-api.md +19 -0
  102. package/dist/docs/tool-reference-artifacts.md +35 -0
  103. package/dist/docs/tool-reference-auth.md +163 -0
  104. package/dist/docs/tool-reference-browser.md +114 -0
  105. package/dist/docs/tool-reference-code.md +26 -0
  106. package/dist/docs/tool-reference-connect.md +21 -0
  107. package/dist/docs/tool-reference-cron.md +48 -0
  108. package/dist/docs/tool-reference-db.md +282 -0
  109. package/dist/docs/tool-reference-domains.md +107 -0
  110. package/dist/docs/tool-reference-email.md +55 -0
  111. package/dist/docs/tool-reference-env.md +19 -0
  112. package/dist/docs/tool-reference-feedback.md +56 -0
  113. package/dist/docs/tool-reference-fs.md +265 -0
  114. package/dist/docs/tool-reference-github.md +57 -0
  115. package/dist/docs/tool-reference-groups.md +85 -0
  116. package/dist/docs/tool-reference-help.md +29 -0
  117. package/dist/docs/tool-reference-jobs.md +39 -0
  118. package/dist/docs/tool-reference-live.md +48 -0
  119. package/dist/docs/tool-reference-logs.md +16 -0
  120. package/dist/docs/tool-reference-payments.md +44 -0
  121. package/dist/docs/tool-reference-project.md +706 -0
  122. package/dist/docs/tool-reference-push.md +78 -0
  123. package/dist/docs/tool-reference-rate-limit.md +18 -0
  124. package/dist/docs/tool-reference-search.md +68 -0
  125. package/dist/docs/tool-reference-security.md +42 -0
  126. package/dist/docs/tool-reference-smoke.md +17 -0
  127. package/dist/docs/tool-reference-stock-photos.md +20 -0
  128. package/dist/docs/tool-reference-tasks.md +73 -0
  129. package/dist/docs/tool-reference-telegram.md +32 -0
  130. package/dist/docs/tool-reference-usage.md +9 -0
  131. package/dist/docs/tool-reference-web.md +71 -0
  132. package/dist/docs/tool-reference-webhooks.md +9 -0
  133. package/dist/docs/troubleshooting.md +411 -0
  134. package/dist/docs/typed-functions.md +94 -0
  135. package/dist/docs/verify-before-deploy.md +67 -0
  136. package/dist/docs/vs-supabase.md +75 -0
  137. package/dist/docs/vs-vercel.md +103 -0
  138. package/dist/lib/bundle.js +303 -221
  139. package/dist/lib/bundle.js.map +3 -3
  140. package/dist/types/lib/test-session.d.ts +8 -0
  141. package/npm-shrinkwrap.json +2 -2
  142. package/package.json +3 -2
  143. package/runtime/DECLARED-DATA-VENDOR.json +5 -5
  144. package/runtime/PLATFORM-SOURCE.json +1 -1
  145. package/runtime/SOURCE-LINT-VENDOR.json +2 -2
  146. package/runtime/declared-data.cjs +37 -19
  147. package/runtime/source-lint.cjs +1 -1
@@ -0,0 +1,531 @@
1
+ # Auth on the client — the correct session code
2
+
3
+ The platform owns the hard part server-side: social OAuth clients, JWT
4
+ validation (`sw.auth.fromRequest`), and session refresh. The happy path puts
5
+ ZERO token/session machinery in the browser: **httpOnly cookie sessions**. No tokens in JS,
6
+ nothing in localStorage, nothing for XSS to steal — and expected failures
7
+ (wrong password, duplicate email, weak password) come back as structured 4xx
8
+ with the real message, never an opaque 500.
9
+
10
+ The whole contract is: **browser → cookie session; non-browser/script/native
11
+ client → bearer token**. Packages are optional adapters to that contract.
12
+ Direct bearer-backed database/file access from a browser is compatibility mode,
13
+ not another recommended path.
14
+
15
+ Read first: the default sign-in path the starter ships is `sw.auth` → `auth-sign-in-is-already-part-of-your-app`. This topic covers browser customization.
16
+
17
+ ## 1. The backend — one line
18
+
19
+ `login` / `signup` are developer-key-gated (the browser can't call them), so
20
+ one server route mediates them and sets the session cookies. The SDK ships that
21
+ route; `somewhere init` writes it:
22
+
23
+ ```ts
24
+ // api/auth/[...path].ts
25
+ export { somewhereAuth as default } from '@somewhere-cloud/sdk/server';
26
+ ```
27
+
28
+ It serves `POST /signup`, `/login`, `/logout`, `/magic-link`,
29
+ `/magic-link/verify`, `GET /me`, and the Google/GitHub/Discord
30
+ `GET /<provider>-url` + `POST /<provider>` code exchange, and `POST /mfa/challenge`,
31
+ the email sign-in code step: in the page, `auth.completeMfa({ code })` finishes a
32
+ sign-in that rejected with code `MFA_REQUIRED` (`sw.auth` → `email-sign-in-codes`).
33
+ A custom server-side OAuth `/callback` redirect uses section 3.
34
+
35
+ ## 2. The page — the SDK client
36
+
37
+ ```ts
38
+ import { createSomewhereAuth, type User } from '@somewhere-cloud/sdk/auth'; // 0.14.1+
39
+
40
+ export const auth = createSomewhereAuth(); // talks to /api/auth, cookie mode
41
+
42
+ // Failures surface as AuthError with the real message ("Wrong email or password.").
43
+ export function signUp(email: string, password: string): Promise<User> {
44
+ return auth.signUp({ email, password });
45
+ }
46
+
47
+ export function signIn(email: string, password: string): Promise<User> {
48
+ return auth.signIn({ email, password });
49
+ }
50
+
51
+ export function currentUser(): Promise<User | null> {
52
+ return auth.getUser(); // probes /api/auth/me; null when signed out
53
+ }
54
+
55
+ export function signOut(): Promise<void> {
56
+ return auth.signOut();
57
+ }
58
+ ```
59
+
60
+ When you use the client directly, call `auth.getUser()` at startup to resolve
61
+ the current session on SDK versions that need an initial check. Reading
62
+ `getState()` alone only reads the cached snapshot.
63
+
64
+ `createSomewhereAuth` holds no tokens in cookie mode: `getSession()` is
65
+ `null`, `getCachedUser()` paints instantly, and a network blip never
66
+ reads as a logout (only a definitive 401 does).
67
+
68
+ Await `signOut()` in the click handler before navigating or reloading. While it
69
+ is pending, keep the current screen or show a disabled signing-out state.
70
+ Do not use the appearance of a signed-out form as proof that the server session
71
+ has ended. After awaiting, check `auth.getState().signOutUnconfirmed`; show a retry
72
+ message when true. `signOut()` can settle without confirming server logout.
73
+
74
+ Awaiting the call orders navigation after it; it does not establish that a
75
+ concurrent session read cannot race with logout. Verify sign-out followed by
76
+ immediate reload on the SDK version deployed in your app.
77
+
78
+ The starter provides the sign-out UI. The client pairs with the handler in
79
+ section 1: it treats a sign-in as a cookie session only when the handler
80
+ answers `cookie_session: true`, which the packaged handler does. Calls to
81
+ your own `api/*` functions just send `credentials: 'include'`.
82
+
83
+ Password sign-in already includes automatic per-IP and per-email attempt
84
+ limits and an account lockout. The SDK route above uses those same controls;
85
+ an extra `sw.rateLimit` wrapper is optional. Exact limits and retry behavior:
86
+ `somewhere docs sw.auth --section automatic-password-sign-in-protection`.
87
+
88
+ ## React auth state
89
+
90
+ Read `docs({ topic: 'auth-client', section: 'react-auth-state' })` for the SDK's
91
+ React state contract. Extend the starter's existing provider and auth client.
92
+ `SomewhereAuthProvider` from `@somewhere-cloud/sdk/react` accepts `client={auth}`
93
+ for a shared `createSomewhereAuth()` instance. Inside it, `useAuthState()`
94
+ returns `status`, `user`, `signingOut` and `signOutUnconfirmed`.
95
+ The React hook exposes `useAuthState().recheck()`. To refresh from the
96
+ client on all supported SDK versions, call `auth.getUser()`.
97
+
98
+ Gate private UI on `status === 'authenticated'`. Render pending UI for
99
+ `checking`, a retry for `indeterminate`, and sign-in for `signed-out`.
100
+ While `signingOut` is true, disable repeat sign-out and navigation. Check
101
+ `signOutUnconfirmed` after the call and offer a retry when true. These are UI
102
+ state controls; server routes still authorize each request.
103
+
104
+ Outside React, `auth.getState()` reads the snapshot and
105
+ `auth.onChange(listener)` subscribes to changes and returns an unsubscribe
106
+ function. Use the subscription to render from the confirmed state. Browser
107
+ clients that publish `data-sw-auth` start checking the session when created
108
+ and reuse that check if you call `auth.getUser()` while it is in flight.
109
+ `getCachedUser()` is presentation data. Keep authorization in your server routes.
110
+
111
+ ### Wait for auth in a browser test
112
+
113
+ When the browser SDK publishes `data-sw-auth` on `<html>`, wait for its value.
114
+ `checking` means the client is resolving the session, `indeterminate` means
115
+ the check failed, and `signed-in` or `signed-out` means it has confirmed
116
+ the state. The first confirmed state also fires `sw-auth-ready` on
117
+ `document.documentElement`. Wait for a confirmed state, then assert on the
118
+ specific page content you need.
119
+
120
+ In Playwright, including specs run by `somewhere test`, use
121
+ `await page.locator('html[data-sw-auth="signed-in"], html[data-sw-auth="signed-out"]').waitFor({ state: 'attached' })`.
122
+ To inspect a confirmed page with the CLI, use
123
+ `somewhere browser --wait 'html[data-sw-auth="signed-in"], html[data-sw-auth="signed-out"]'`.
124
+
125
+ ## 3. Without the SDK — one backend file (paste exactly this)
126
+
127
+ The same route written by hand. Pair it with plain `fetch` (section 5) or
128
+ `createClient(...).auth` (section 4), not `createSomewhereAuth`. Writing it
129
+ from a shell, quote the path: `cat > 'api/auth/[...path].js'`.
130
+
131
+ ```js
132
+ // api/auth/[...path].js
133
+ export default async function (req, sw) {
134
+ const url = new URL(req.url);
135
+ const sub = url.pathname.replace(/.*\/auth/, '') || '/';
136
+ /**
137
+ * @param {unknown} d
138
+ * @param {number} [s]
139
+ */
140
+ const json = (d, s) => Response.json(d, { status: s || 200 });
141
+ const body = async () => { try { return await req.json(); } catch (e) { return {}; } };
142
+ // Returns { user } after staging cookies. An account with email sign-in codes gets
143
+ // { mfa_required, mfa_token } and no session; /mfa completes it with the emailed code.
144
+ if (req.method === 'POST' && sub === '/login') { const b = await body(); return json(await sw.auth.loginWithCookie(req, b.email, b.password)); }
145
+ if (req.method === 'POST' && sub === '/mfa') {
146
+ const b = await body();
147
+ if (b.resend) return json(await sw.auth.mfa.resend({ mfa_token: b.mfa_token }));
148
+ return json(await sw.auth.mfa.challengeWithCookie({ mfa_token: b.mfa_token, code: b.code }));
149
+ }
150
+ if (req.method === 'POST' && sub === '/signup') { const b = await body(); return json(await sw.auth.signupWithCookie(req, b)); }
151
+ if (req.method === 'POST' && sub === '/magic-link') {
152
+ const b = await body();
153
+ return json(await sw.auth.signInWithOtp({ email: b.email, redirect_uri: b.redirect_uri }));
154
+ }
155
+ if (req.method === 'POST' && sub === '/magic-link/verify') {
156
+ // Resolves the issued session itself: { user, access_token, refresh_token, ... }.
157
+ const issued = await sw.auth.verifyOtp(await body());
158
+ // A copied account whose second factor is not available here gets a ticket and no session. An account with
159
+ // email sign-in codes is refused (403): it signs in with its password and a code.
160
+ if (issued.mfa_required) return json({ error: 'SIGN_IN_INCOMPLETE' }, 409);
161
+ sw.auth.setSessionCookies(issued.access_token, issued.refresh_token);
162
+ return json({ user: issued.user, cookie_session: true });
163
+ }
164
+ if (req.method === 'GET' && sub === '/callback') return sw.auth.googleCallbackWithCookie(req, '/'); // completed sign-in: 302
165
+ if (req.method === 'POST' && sub === '/logout') return json(await sw.auth.logoutWithCookie(req));
166
+ if (req.method === 'GET' && sub === '/me') return json({ user: await sw.auth.fromRequest(req) });
167
+ return json({ error: 'NOT_FOUND' }, 404);
168
+ }
169
+ ```
170
+
171
+ No try/catch needed: expected auth failures surface automatically as
172
+ structured 4xx — `{ error: 'INVALID_CREDENTIALS', message: 'Wrong email or
173
+ password.' }` and friends — so your UI can show `body.message` directly.
174
+ Real bugs still return opaque 500s. (The cookie helpers also accept an
175
+ options object: `loginWithCookie(req, { email, password })` works too, and
176
+ `signupWithCookie` additionally accepts `{ email, password, display_name?,
177
+ locale?, timezone?, turnstile_token? }` — or pass those fields as the fourth
178
+ argument after positional email/password, or call it with just that object
179
+ and no `req` at all.)
180
+
181
+ ## Response shapes — one contract
182
+
183
+ Every auth success that carries a user wraps it: `{ "user": { ... } }`.
184
+ Success is never a bare user object and never `null` — if the platform
185
+ ever failed to produce a user on sign-in, the helper throws
186
+ `AUTH_RESPONSE_MALFORMED` instead of returning an ambiguous 200. Errors are
187
+ structured `{ error, message }` responses. The platform returns
188
+ `503 AUTH_SIGN_IN_UNAVAILABLE` when a database it needed was briefly
189
+ unreachable. No credentials were returned and no sign-in write was retried.
190
+ With `retry: false`, a session or a failed-attempt count may already have
191
+ been recorded. With `retry: true`, nothing was recorded. Either way, show
192
+ the message and let the person try again; it is not a wrong password.
193
+
194
+ The SDK handler can also return `501 COOKIE_SESSION_UNAVAILABLE` if its
195
+ runtime cannot attach the required session cookies. It refuses the sign-in
196
+ response instead of exposing tokens in a browser response; inspect the
197
+ runtime capability error rather than treating it as a password failure.
198
+
199
+ - `POST /api/auth/login` and `/signup` →
200
+ `{ "user": { "id", "email", "role", "display_name" } }` — the compact
201
+ session identity. The session rides on httpOnly `Set-Cookie` headers; the
202
+ cookie helpers put no token material in the body.
203
+ - `GET /api/auth/me` → `{ "user": { ... } }` — the signed-in user. The
204
+ zero-dependency handler (section 3) returns the verified session identity; the
205
+ SDK `somewhereAuth` handler returns the full stored profile
206
+ (`email_verified`, `created_at`, `last_login_at`, `metadata`,
207
+ `locale`, `timezone`, …; no billing fields) — a superset of
208
+ the sign-in shape. Read `data.user` either way.
209
+ - `POST /api/auth/logout` → `{ "ok": true }` after confirmed sign-out
210
+ or local cleanup when no session cookie was sent. A non-2xx response means
211
+ sign-out failed; the session may still be active.
212
+ - Explicit token mode (`sw.auth.login` / `signup` called
213
+ server-side) additionally carries `access_token`, `refresh_token`,
214
+ `session_token`, and `expires_in` alongside `user`.
215
+ The starter's SDK browser flow uses cookies; its default sign-in response
216
+ body contains no session tokens. Explicit token mode is for clients that
217
+ manage their own session, as described below.
218
+
219
+ ## 4. The root SDK client — createClient
220
+
221
+ ```ts
222
+ import { createClient, type User } from '@somewhere-cloud/sdk' // 0.14.1+
223
+
224
+ // Same origin, no credential: posts to your /api/auth routes (section 1 or 3),
225
+ // and the session is httpOnly cookies.
226
+ const client = createClient(window.location.origin, undefined, { fetch: window.fetch.bind(window) })
227
+
228
+ // Each call returns { data, error }; these throw the SDK's own error
229
+ // (error.message is the real cause, e.g. "Wrong email or password.").
230
+ export async function signIn(email: string, password: string): Promise<User | null> {
231
+ const { data, error } = await client.auth.signIn({ email, password })
232
+ if (error) throw error
233
+ return data ? data.user : null
234
+ }
235
+
236
+ export async function signUp(email: string, password: string): Promise<User | null> {
237
+ const { data, error } = await client.auth.signUp({ email, password })
238
+ if (error) throw error
239
+ return data ? data.user : null
240
+ }
241
+
242
+ export async function sendMagicLink(email: string): Promise<void> {
243
+ const { error } = await client.auth.sendMagicLink({ email })
244
+ if (error) throw error
245
+ }
246
+
247
+ export async function verifyMagicLink(token: string): Promise<User | null> {
248
+ const { data, error } = await client.auth.verifyMagicLink({ token })
249
+ if (error) throw error
250
+ return data ? data.user : null
251
+ }
252
+
253
+ export async function currentUser(): Promise<User | null> {
254
+ const { data, error } = await client.auth.getUser() // probes /api/auth/me
255
+ if (error) throw error
256
+ return data ? data.user : null
257
+ }
258
+
259
+ export async function signOut(): Promise<void> {
260
+ const { error } = await client.auth.signOut()
261
+ if (error) throw error
262
+ }
263
+
264
+ // Google — zero token-handoff code: the platform redirects back through
265
+ // your /callback route, which sets the cookies and 302s home.
266
+ export async function signInWithGoogle(): Promise<void> {
267
+ const { data, error } = await client.auth.signInWithOAuth({ provider: 'google' })
268
+ if (error) throw error
269
+ if (!data) throw new Error('signInWithOAuth returned neither a sign-in URL nor an error')
270
+ window.location.href = data.url
271
+ }
272
+ ```
273
+
274
+ In cookie mode the SDK holds no tokens: `getSession()` returns
275
+ `{ cookie_session: true, user }`, a network blip never reads as a logout
276
+ (only a definitive 401 does), and `functions.invoke` rides the cookie
277
+ automatically.
278
+
279
+ The browser constructor needs no bearer or developer key. Do not ship an
280
+ `smt_` key or invent a placeholder browser credential. Cookie sign-in does
281
+ not credential the SDK's direct `from()`, storage, or channel calls.
282
+ Use the generated `somewhere:data` client for declared browser database
283
+ operations. File access and business logic go through same-origin functions.
284
+
285
+ ## 5. Without the SDK — plain fetch
286
+
287
+ If you cannot use the SDK, nothing to install — the cookie does the work:
288
+
289
+ ```js
290
+ // Sign in (sign up is the same against /api/auth/signup):
291
+ const res = await fetch('/api/auth/login', {
292
+ method: 'POST', headers: { 'Content-Type': 'application/json' },
293
+ body: JSON.stringify({ email, password }), credentials: 'include',
294
+ });
295
+ if (!res.ok) showMessage((await res.json()).message); // "Wrong email or password."
296
+
297
+ // Who is signed in? (any page load)
298
+ const me = await (await fetch('/api/auth/me', { credentials: 'include' })).json();
299
+
300
+ // Every authed request — just include credentials:
301
+ const r = await fetch('/api/whatever', { credentials: 'include' });
302
+
303
+ // Sign out: show an unconfirmed outcome instead of assuming success.
304
+ try {
305
+ const out = await fetch('/api/auth/logout', { method: 'POST', credentials: 'include' });
306
+ if (!out.ok) showMessage("We couldn't confirm sign-out; the session may still be active.");
307
+ } catch {
308
+ showMessage("We couldn't reach the server to confirm sign-out.");
309
+ }
310
+ ```
311
+
312
+ ## 6. React — one hook (plain fetch)
313
+
314
+ ```jsx
315
+ import { useState, useEffect } from 'react';
316
+ export function useUser() {
317
+ const [user, setUser] = useState(null);
318
+ useEffect(() => {
319
+ let on = true;
320
+ fetch('/api/auth/me', { credentials: 'include' })
321
+ .then((r) => r.json()).then((d) => { if (on) setUser(d.user || null); })
322
+ .catch(() => {}); // network blip — never treat as logged out
323
+ return () => { on = false; };
324
+ }, []);
325
+ return user;
326
+ }
327
+ ```
328
+
329
+ ## Package status: one SDK, one version
330
+
331
+ Install `@somewhere-cloud/sdk`. Its tree-shakeable `/auth`, `/react`, and
332
+ `/server` subpaths contain the framework-agnostic cookie client, React
333
+ hooks/gates, OAuth callback UI, billing components, and the handler for the
334
+ same `/api/auth` contract above. The contract matrix verifies every
335
+ SDK-exported client method against that handler, including
336
+ `sendMagicLink` / `verifyMagicLink` delegation to
337
+ `sw.auth.signInWithOtp` / `sw.auth.verifyOtp`.
338
+
339
+ Header mode is only for non-browser integrations.
340
+
341
+ The cookies are HttpOnly + Secure (invisible to JS — XSS can't steal them),
342
+ SameSite=Lax, Path=/, 30-day lifetime. `sw.auth.fromRequest` auto-refreshes
343
+ the session on every call and re-issues the cookie, so users stay logged in
344
+ across browser restarts and you never write a line of refresh logic.
345
+
346
+ A cookie-session write (POST/PUT/PATCH/DELETE) must carry a normal browser
347
+ `Origin` header — a plain `fetch()` from a page already sends one, so
348
+ there's nothing to add. A write with no `Origin` at all (not a real
349
+ browser request) gets a 400 `ORIGIN_REQUIRED`. Reads and Bearer-token
350
+ requests are unaffected — don't hand-write CORS headers to work around
351
+ this.
352
+
353
+ A non-browser caller (a script, an agent, a server-side caller) doing a
354
+ cookie-authenticated write has two supported paths: send the `Origin`
355
+ header yourself naming your app's own origin, or stop sending the session
356
+ cookie and pass the user's token in an `Authorization: Bearer <token>`
357
+ header instead. For custom functions using `sw.auth.fromRequest`, the
358
+ bearer path is not origin-checked and fits non-browser callers. The generated
359
+ data endpoint `/__sw/data` has a separate rule: every call, including
360
+ Bearer-authenticated list/get reads, requires `Origin` set to the app's
361
+ own origin. There is no CSRF-token alternative.
362
+
363
+ ## Advanced — manual token mode (native apps / non-browser clients)
364
+
365
+ Browser apps use the cookie sessions above. This section is for a script, CLI
366
+ or native app, where there is no browser cookie jar. The example holds one
367
+ session in one process's memory. Await each request before starting the next
368
+ so token rotations stay in order. The three session rules are below.
369
+
370
+ ### The session client — `src/session.ts`
371
+
372
+ ```ts
373
+ // src/session.ts — for a script, CLI or native app; tokens live in this process's memory
374
+ type Session = { accessToken: string; refreshToken: string }
375
+ type User = { id: string; email: string }
376
+
377
+ const APP = 'https://my-app.somewhere.site' // your app's fixed URL, never one taken from input
378
+ const ORIGIN = new URL(APP).origin
379
+ let session: Session | null = null
380
+
381
+ // Tokens and credentials go only to APP: anything resolving elsewhere is refused before a request.
382
+ function appUrl(path: string): URL {
383
+ const url = new URL(path, APP)
384
+ if (url.origin !== ORIGIN || url.username || url.password) {
385
+ throw new Error(`Refusing to send the session outside ${ORIGIN}`)
386
+ }
387
+ return url
388
+ }
389
+
390
+ function field(data: unknown, key: string): unknown {
391
+ return typeof data === 'object' && data !== null ? Reflect.get(data, key) : undefined
392
+ }
393
+ function readUser(data: unknown): User | null {
394
+ const id = field(data, 'id')
395
+ const email = field(data, 'email')
396
+ return typeof id === 'string' && typeof email === 'string' ? { id, email } : null
397
+ }
398
+ function failure(data: unknown, fallback: string): Error {
399
+ const message = field(data, 'message')
400
+ const code = field(data, 'error')
401
+ return new Error(typeof message === 'string' ? message : typeof code === 'string' ? code : fallback)
402
+ }
403
+
404
+ async function exchange(path: '/login' | '/signup', email: string, password: string): Promise<User | null> {
405
+ const res = await fetch(appUrl('/api/auth-token' + path), {
406
+ method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ email, password }),
407
+ redirect: 'error', // the password never follows a redirect
408
+ })
409
+ const data: unknown = await res.json().catch(() => null)
410
+ if (!res.ok) throw failure(data, 'Sign-in failed')
411
+ const access = field(data, 'token') ?? field(data, 'access_token')
412
+ const refresh = field(data, 'refresh_token')
413
+ if (typeof access !== 'string' || !access || typeof refresh !== 'string' || !refresh) {
414
+ throw failure(data, 'Sign-in needs another step') // no token pair in this answer
415
+ }
416
+ session = { accessToken: access, refreshToken: refresh } // both tokens as one value
417
+ return readUser(field(data, 'user'))
418
+ }
419
+ export const signIn = (email: string, password: string) => exchange('/login', email, password)
420
+ export const signUp = (email: string, password: string) => exchange('/signup', email, password)
421
+ export function getSession(): Session | null { return session }
422
+
423
+ // Use this for every request to your backend that needs the user.
424
+ export async function authFetch(path: string, init: RequestInit = {}): Promise<Response> {
425
+ const url = appUrl(path) // a foreign or credentialed URL throws here, before any request
426
+ const headers = new Headers(init.headers)
427
+ if (session) {
428
+ headers.set('Authorization', `Bearer ${session.accessToken}`)
429
+ headers.set('X-Refresh-Token', session.refreshToken) // lets the server refresh an expired token
430
+ }
431
+ // The tokens never follow a redirect. A network error rejects here; the session stays.
432
+ const res = await fetch(url, { ...init, headers, redirect: 'error' })
433
+ const access = res.headers.get('X-New-Access-Token')
434
+ const refresh = res.headers.get('X-New-Refresh-Token')
435
+ if (access && refresh) session = { accessToken: access, refreshToken: refresh } // rotate both or neither
436
+ if (res.status === 401) session = null // the server already tried to refresh: the session is over
437
+ return res
438
+ }
439
+
440
+ export async function getUser(): Promise<User | null> {
441
+ if (!session) return null
442
+ const res = await authFetch('/api/auth-token/me')
443
+ if (res.status === 401) return null
444
+ if (!res.ok) throw new Error(`Could not load the user (${res.status})`) // a 5xx keeps the session
445
+ return readUser(field(await res.json(), 'user'))
446
+ }
447
+
448
+ // Revoke on the server with the refresh token first; forget the pair only after it answers.
449
+ export async function signOut(): Promise<void> {
450
+ if (!session) return
451
+ const res = await fetch(appUrl('/api/auth-token/logout'), {
452
+ method: 'POST', headers: { 'Content-Type': 'application/json' },
453
+ body: JSON.stringify({ refresh_token: session.refreshToken }),
454
+ redirect: 'error',
455
+ })
456
+ const data: unknown = await res.json().catch(() => null)
457
+ const revoked = res.ok && field(data, 'logged_out') === true
458
+ const absent = res.status === 404 && field(data, 'error') === 'SESSION_NOT_FOUND' // nothing left to revoke
459
+ if (!revoked && !absent) throw failure(data, 'Sign-out failed') // a network error rejects first; retry later
460
+ session = null
461
+ }
462
+ ```
463
+
464
+ Set `APP` to your deployed app's URL: its subdomain or your custom domain. The
465
+ pair lives in this process's memory, so a script signs in again on its next
466
+ run. A native app that should stay signed in across launches keeps the pair in
467
+ the operating system's secure store (Keychain, Android Keystore or Windows
468
+ Credential Manager), saved as one value and updated after every rotation.
469
+ Google and other OAuth sign-ins are browser redirects: use them through the
470
+ cookie flow above (section 4) or `sw.auth`.
471
+
472
+ ### The backend — one function that wires it to `sw.auth`
473
+
474
+ A thin server function mediates the developer-key-gated calls and returns
475
+ the token pair to the client (this is the manual-mode sibling of the cookie
476
+ handler above, mounted at a different path so the examples are not pasted over
477
+ each other):
478
+
479
+ ```js
480
+ // api/auth-token/[...path].js
481
+ export default async function (req, sw) {
482
+ const url = new URL(req.url);
483
+ const parts = url.pathname.split('/auth-token');
484
+ const sub = parts.length > 1 ? (parts[parts.length - 1] || '/') : '/';
485
+ /**
486
+ * @param {unknown} d
487
+ * @param {number} [s]
488
+ */
489
+ const json = function (d, s) { return Response.json(d, { status: s || 200 }); };
490
+ const body = async function () { try { return await req.json(); } catch (e) { return {}; } };
491
+ try {
492
+ if (req.method === 'POST' && sub === '/login') return json(await sw.auth.login(await body()));
493
+ if (req.method === 'POST' && sub === '/signup') return json(await sw.auth.signup(await body()));
494
+ if (req.method === 'POST' && sub === '/logout') {
495
+ const b = await body();
496
+ if (typeof b.refresh_token !== 'string' || !b.refresh_token) {
497
+ return json({ error: 'VALIDATION_ERROR', message: 'refresh_token is required.' }, 400);
498
+ }
499
+ try {
500
+ // Revokes the session this refresh token belongs to, with every token of that session.
501
+ return json(await sw.auth.logout({ refresh_token: b.refresh_token })); // { logged_out: true }
502
+ } catch (e) {
503
+ if (typeof e === 'object' && e !== null && 'code' in e && e.code === 'SESSION_NOT_FOUND') {
504
+ return json({ error: 'SESSION_NOT_FOUND', message: 'No live session matched this refresh token; nothing was signed out.' }, 404);
505
+ }
506
+ throw e;
507
+ }
508
+ }
509
+ if (req.method === 'GET' && sub === '/me') return json({ user: await sw.auth.fromRequest(req) });
510
+ return json({ error: 'NOT_FOUND' }, 404);
511
+ } catch (e) { return json({ error: 'AUTH_ERROR', message: e instanceof Error ? e.message : String(e) }, 400); }
512
+ }
513
+ ```
514
+
515
+ ### The three rules
516
+
517
+ - **Keep the pair as one value** — in memory, and in any secure store you add.
518
+ Saving the access token without the refresh token (or the reverse) leaves a
519
+ pair the server refuses, and the user is signed out.
520
+ - **A network error leaves the session in place** — `fetch` rejects before the
521
+ session changes, so the same tokens are there for the retry.
522
+ - **Rotate only when both `X-New-*` headers are present** — a partial header set
523
+ means no rotation happened.
524
+
525
+
526
+ ## The package does not create another path
527
+
528
+ The SDK is the default: a one-line backend route plus `createSomewhereAuth`.
529
+ It is an adapter to the same `/api/auth` cookie contract that the pasted
530
+ file plus plain `fetch` implements without a package. Use the SDK for API shape or UI helpers, never to introduce
531
+ browser-held credentials.
@@ -0,0 +1,76 @@
1
+ # Plans & Pricing
2
+
3
+ (Building YOUR OWN app's plans + feature-gating for your users? That's a
4
+ different thing — see `docs({ topic: 'sw.billing' })`. This topic is what
5
+ somewhere.cloud charges you.)
6
+
7
+ Pricing is DB-driven (the tier_plans table) and served live at
8
+ /v1/pricing — always fetch that for the current numbers rather than
9
+ hardcoding them. Every tier includes unlimited projects and deploys.
10
+ Bandwidth is included on every plan. We do not meter it or bill for it. Fair use applies: this covers normal traffic to your app's pages, functions and files. Custom domains are free on every tier.
11
+
12
+ Payments: charges settle to your connected account, minus Stripe's standard
13
+ processing fee and a 0.5% platform fee (each checkout response includes
14
+ `fee_percent` so you can account for it). Managed AI uses the same all-in
15
+ catalog rates on every tier. Every plan includes a managed-AI allowance that
16
+ renews each month on Free and each billing period on paid plans. Included/default calls never spend prepaid
17
+ balance automatically; explicit paid-model selection on Free uses prepaid
18
+ only, while eligible paid-plan calls use the allowance first and then prepaid.
19
+ Published request and model limits still apply.
20
+
21
+ ## Balance and included AI
22
+ `GET /v1/billing/balance` keeps the prepaid balance fields at the top level
23
+ and reports the plan inclusion separately as `included_ai`:
24
+
25
+ ```text
26
+ included_ai: {
27
+ scope: "account"
28
+ period_start: number | null
29
+ period_end: number | null
30
+ allowance_microdollars, spent_microdollars, reserved_microdollars,
31
+ available_microdollars: number
32
+ allowance_dollars, spent_dollars, reserved_dollars, available_dollars: number
33
+ }
34
+ ```
35
+
36
+ Period values are Unix epoch milliseconds, or null. `spent` is settled use;
37
+ `reserved` is outstanding included-allowance holds and must not be counted as
38
+ spent. Included `available` is clamped at zero. It is distinct from the
39
+ top-level prepaid `balance`, `pending` and `available` values.
40
+
41
+ ## The tiers
42
+ Five tiers — Free, Builder, Pro, Scale, Enterprise. Fetch /v1/pricing for the
43
+ live prices and per-tier caps (files, database, email, realtime publishes,
44
+ upload size, uptime-check frequency). They differ along two axes:
45
+
46
+ - **Core platform plus plan capabilities.** Every tier includes functions,
47
+ database, auth, outbound email, AI, payments, files, live updates, one-shot
48
+ jobs, customer cron schedules, builds, and deploys. Higher tiers raise caps
49
+ and shorten the minimum schedule interval; Builder and higher add recurring
50
+ smoke checks. See /v1/pricing for the current
51
+ numbers and capability flags.
52
+ - **Service level.** Free uses its included AI allowance and request limits.
53
+ Every plan can request a review. Paid plans get a longer report. Eligible paid
54
+ plans also review when a preview is promoted. Pro adds office hours.
55
+ Scale adds priority support. Enterprise adds custom limits, contracts, SLA, and
56
+ invoicing.
57
+
58
+ ## The "unlimited" caveat
59
+ Advertised "unlimited" (e.g. database rows / auth users on higher tiers)
60
+ means a high SAFETY cap, never literally uncapped — to protect shared
61
+ infrastructure. Row/user counts are metered with warnings before any cap;
62
+ the platform never silently blacks out a live app at a limit.
63
+
64
+ ## Check your plan / upgrade
65
+ Your plan covers your account. See it under [Plan and billing](https://somewhere.cloud/app/account/billing).
66
+ Upgrade there, or create a platform subscription checkout directly:
67
+
68
+ ```bash
69
+ curl -X POST https://api.somewhere.cloud/v1/billing/checkout \
70
+ -H "Authorization: Bearer $SOMEWHERE_API_KEY" \
71
+ -H "Content-Type: application/json" \
72
+ -d '{"plan":"builder"}'
73
+ ```
74
+
75
+ The JSON body has exactly one field, `plan`, whose value is `builder`,
76
+ `pro`, or `scale`. This platform upgrade does not take a Stripe Price ID.