@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
package/dist/docs/sdk.md
ADDED
|
@@ -0,0 +1,287 @@
|
|
|
1
|
+
# @somewhere-cloud/sdk — optional adapter, one auth path
|
|
2
|
+
|
|
3
|
+
There is one auth map:
|
|
4
|
+
|
|
5
|
+
- **Browser app:** httpOnly cookie sessions. The browser holds no access token,
|
|
6
|
+
refresh token, or developer key. Declared data and file collections use the
|
|
7
|
+
generated `somewhere:data` and `somewhere:files` clients; sign-in and custom
|
|
8
|
+
logic go through same-origin `api/*` functions that call `sw.auth`,
|
|
9
|
+
`sw.db`, and `sw.fs`.
|
|
10
|
+
- **Non-browser client:** bearer token mode, because a script/CLI/native client
|
|
11
|
+
has no browser cookie boundary.
|
|
12
|
+
|
|
13
|
+
This is the one JS/TS package. Its root client plus tree-shakeable
|
|
14
|
+
`@somewhere-cloud/sdk/auth`, `@somewhere-cloud/sdk/react`, and
|
|
15
|
+
`@somewhere-cloud/sdk/server` entry points adapt that contract without
|
|
16
|
+
defining a second transport.
|
|
17
|
+
|
|
18
|
+
```bash
|
|
19
|
+
npm i @somewhere-cloud/sdk
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
## createClient
|
|
23
|
+
|
|
24
|
+
```ts
|
|
25
|
+
import { createClient } from '@somewhere-cloud/sdk'
|
|
26
|
+
|
|
27
|
+
// Browser: same origin, no credential. auth.* and functions.invoke() ride httpOnly cookies.
|
|
28
|
+
// window is read only when browser code calls this.
|
|
29
|
+
export function createBrowserClient() {
|
|
30
|
+
return createClient(window.location.origin, undefined, { fetch: window.fetch.bind(window) })
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
// Script, CLI or trusted server: use the app URL, project ID and your credential.
|
|
34
|
+
export function createScriptClient(projectUrl: string, projectId: string, credential: string) {
|
|
35
|
+
return createClient(projectUrl, credential, { projectId })
|
|
36
|
+
}
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
- The first argument is your project URL, https://<project>.somewhere.site; in
|
|
40
|
+
the browser that is the page's own origin. The SDK uses it for
|
|
41
|
+
`functions.invoke`. For project resources such as files, pass the project ID
|
|
42
|
+
explicitly as `{ projectId }` for `*.somewhere.site` and custom domains.
|
|
43
|
+
- The second argument is optional in a browser. In non-browser/header mode it
|
|
44
|
+
is an app-user bearer token or a developer `smt_` key restricted to a
|
|
45
|
+
deployed function or trusted server process. Do not invent a placeholder
|
|
46
|
+
credential.
|
|
47
|
+
- `new Somewhere({ key, projectId })` remains the explicit compatibility
|
|
48
|
+
constructor for existing bearer-based integrations.
|
|
49
|
+
|
|
50
|
+
## Database — declared client and server functions
|
|
51
|
+
|
|
52
|
+
For ordinary browser reads and writes, declare client grants in `db/schema.ts`
|
|
53
|
+
and import the generated `data` client from `somewhere:data`. See
|
|
54
|
+
`docs({ topic: 'declared-data' })` for its named, typed operations.
|
|
55
|
+
The SDK's generic database interface is not this generated client: direct
|
|
56
|
+
app-user SQL/database API access is refused (`BROWSER_DB_ACCESS_REMOVED`).
|
|
57
|
+
For custom logic, call an `api/` function that uses `sw.db`.
|
|
58
|
+
|
|
59
|
+
```ts
|
|
60
|
+
// db/schema.ts
|
|
61
|
+
import { id, owner, schema, table, text, timestamp } from 'somewhere/db';
|
|
62
|
+
|
|
63
|
+
export default schema({
|
|
64
|
+
notes: table(
|
|
65
|
+
{ id: id(), title: text(), created_at: timestamp({ default: 'now' }) },
|
|
66
|
+
{ scope: owner() },
|
|
67
|
+
),
|
|
68
|
+
});
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
```ts
|
|
72
|
+
// api/notes.ts — the signed-in caller's notes; owner() scopes the read to them.
|
|
73
|
+
export default async function notes(req: Request, sw: SomewhereRuntimeContext): Promise<Response> {
|
|
74
|
+
const user = await sw.auth.fromRequest(req);
|
|
75
|
+
if (!user) return Response.json({ error: 'Sign in first.' }, { status: 401 });
|
|
76
|
+
const { data } = await sw.db.from('notes', { order: [['created_at', 'desc']], limit: 50 });
|
|
77
|
+
return Response.json({ notes: data });
|
|
78
|
+
}
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
The browser calls that function on its own origin; the session cookie identifies the caller:
|
|
82
|
+
|
|
83
|
+
```ts
|
|
84
|
+
// src/notes.ts
|
|
85
|
+
import { createClient } from '@somewhere-cloud/sdk';
|
|
86
|
+
|
|
87
|
+
type Note = { id: string; title: string; created_at: string };
|
|
88
|
+
|
|
89
|
+
export async function listMyNotes(): Promise<Note[]> {
|
|
90
|
+
const client = createClient(window.location.origin, undefined, { fetch: window.fetch.bind(window) });
|
|
91
|
+
const { data, error } = await client.functions.invoke<{ notes: Note[] }>('notes', { method: 'GET' });
|
|
92
|
+
if (error) throw error;
|
|
93
|
+
if (!data) throw new Error('notes returned no body');
|
|
94
|
+
return data.notes;
|
|
95
|
+
}
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
On managed projects, ordinary `sw.db.query` / `sw.db.batch` calls are
|
|
99
|
+
refused with `MANAGED_RAW_SQL_REQUIRES_SERVER_AUTHORITY`. Use the structured
|
|
100
|
+
calls for declared access. When a read truly requires raw SQL, authorize the
|
|
101
|
+
caller first and use `sw.db.server.query` or `sw.db.server.batch`; those
|
|
102
|
+
calls run exactly as written and do not apply declared row permissions. Raw
|
|
103
|
+
writes remain refused in managed mode. SQL-mode projects retain ordinary raw
|
|
104
|
+
SQL behavior.
|
|
105
|
+
|
|
106
|
+
### Structured queries — the platform composes and scopes
|
|
107
|
+
|
|
108
|
+
For platform-proven per-user scoping, use the structured builder. You describe
|
|
109
|
+
the query; the platform renders the SQL (identifiers validated, every value
|
|
110
|
+
bound) and scopes it automatically to the request's signed-in user. It never
|
|
111
|
+
parses a string it did not write. The operations (`from`, `count`, `insert`,
|
|
112
|
+
`update`, `remove`) are documented in
|
|
113
|
+
`sw.db` → `per-user-scoping-the-structured-builder-not-raw-sql` and
|
|
114
|
+
`builder-verbs-and-where-shapes`. In brief:
|
|
115
|
+
|
|
116
|
+
`where`: `{ col: value }` (=), `{ col: { gt|gte|lt|lte|ne|like: v } }`,
|
|
117
|
+
`{ col: { in: [...] } }` (empty array matches nothing), `{ col: null }`
|
|
118
|
+
(IS NULL), `{ col: { not: null } }` (IS NOT NULL), a per-column array of
|
|
119
|
+
conditions ANDed (`{ created_at: [{ gte: a }, { lte: b }] }`). A shallow
|
|
120
|
+
`$or` group accepts 2-8 single-column leaf branches, for example
|
|
121
|
+
`{ $or: [{ status: 'draft' }, { status: 'published' }] }`; the whole group
|
|
122
|
+
remains inside the platform's owner/member scope. Nested OR, relation-filter OR,
|
|
123
|
+
and named-live OR are refused. Every structured table needs an
|
|
124
|
+
explicit declared intent (scoped / shared / server-only). Scoping is automatic
|
|
125
|
+
and mandatory: on a declared user-owned table every structured query is scoped
|
|
126
|
+
to the request's verified user. Each request checks the credential; a valid
|
|
127
|
+
check may be reused for up to 60 seconds, so a revoked app session or a ban is
|
|
128
|
+
refused within 60 seconds. Without a
|
|
129
|
+
signed-in user, the operation throws `AUTH_REQUIRED` before reading data.
|
|
130
|
+
A `shared()` table also needs a signed-in user (`AUTH_REQUIRED`, 401):
|
|
131
|
+
reads return every row and writes are attributed to that user.
|
|
132
|
+
`serverOnly()` tables and `sw.db.server.*` calls run unscoped, under the
|
|
133
|
+
authority of your function. The platform owns the ownership column and refuses to let
|
|
134
|
+
insert/update set or reassign it (`OWNER_COLUMN_NOT_ASSIGNABLE`). A table
|
|
135
|
+
with NO declared intent cannot be structured-queried at all — it fails the
|
|
136
|
+
deploy and throws `TABLE_INTENT_REQUIRED` (403) at runtime; declare it or,
|
|
137
|
+
for an intentional raw read, authorize the caller and use
|
|
138
|
+
`sw.db.server.query`. Cross-user raw reads and reads from undeclared tables
|
|
139
|
+
use that explicit server-authority path. A third scope argument
|
|
140
|
+
throws `SCOPE_ARGUMENT_REMOVED`. Responses match
|
|
141
|
+
`sw.db.query` (`{ data, error, count, last_row_id, changes }`; `count()`
|
|
142
|
+
returns exactly `{ data, error }`); mutations `RETURNING *`. The
|
|
143
|
+
`last_row_id` result field is always
|
|
144
|
+
null; read an inserted ID from its returned row in `data`.
|
|
145
|
+
|
|
146
|
+
The release records the DECLARED shape, never a reconstruction from
|
|
147
|
+
reading code: each deploy pins the project's table intents (scoped/shared,
|
|
148
|
+
owner column) and a schema snapshot captured from the live database
|
|
149
|
+
(`SCHEMA_CAPTURE_FAILED` if the snapshot cannot be taken). Explicit
|
|
150
|
+
`sw.db.server.query`/`batch` reads run as written and are never analyzed —
|
|
151
|
+
the deliberate server-authority escape hatch. `POST /v1/db/migrate` is the same
|
|
152
|
+
trust class: a production target takes a named restore point BEFORE any
|
|
153
|
+
statement runs (a recorded marker: restoring a database in place is not
|
|
154
|
+
available, so it is not an undo), then runs your SQL atomically, exactly as written. A preview
|
|
155
|
+
target runs against the disposable clone and takes no production restore
|
|
156
|
+
point. It does NOT analyze the SQL and cannot warn about or refuse what a
|
|
157
|
+
statement drops or breaks. If a production restore point cannot be taken,
|
|
158
|
+
nothing applies (`RESTORE_POINT_FAILED`, retryable). A managed
|
|
159
|
+
`db/schema.ts` instead runs through the schema planner on production deploy;
|
|
160
|
+
its table access intents are declared
|
|
161
|
+
by the file. `GET
|
|
162
|
+
/v1/db/access-map` (developer key) returns the release's data-access map
|
|
163
|
+
at per-table granularity: declared intents with ownership scope, the schema
|
|
164
|
+
snapshot, and a plain note that explicit server-authority SQL is not analyzed.
|
|
165
|
+
|
|
166
|
+
## Auth — sw.auth
|
|
167
|
+
|
|
168
|
+
Browser sign-in starts here: the backend route is one line and the page uses
|
|
169
|
+
`createSomewhereAuth` (`somewhere init` writes both).
|
|
170
|
+
|
|
171
|
+
```ts
|
|
172
|
+
// api/auth/[...path].ts
|
|
173
|
+
export { somewhereAuth as default } from '@somewhere-cloud/sdk/server'
|
|
174
|
+
```
|
|
175
|
+
|
|
176
|
+
```ts
|
|
177
|
+
// src/auth.ts — page code
|
|
178
|
+
import { createSomewhereAuth } from '@somewhere-cloud/sdk/auth'
|
|
179
|
+
|
|
180
|
+
export const auth = createSomewhereAuth()
|
|
181
|
+
|
|
182
|
+
// Call from your sign-up form; throws AuthError with the message on failure.
|
|
183
|
+
export async function signUp(email: string, password: string) {
|
|
184
|
+
return auth.signUp({ email, password }) // or auth.signIn({ email, password })
|
|
185
|
+
}
|
|
186
|
+
export async function signOut() {
|
|
187
|
+
await auth.signOut();
|
|
188
|
+
if (auth.getState().signOutUnconfirmed) {
|
|
189
|
+
throw new Error('Sign-out could not be confirmed. Please try again.');
|
|
190
|
+
}
|
|
191
|
+
// Only navigate or reload after confirmed logout.
|
|
192
|
+
}
|
|
193
|
+
```
|
|
194
|
+
|
|
195
|
+
The root client carries the same methods with `{ data, error }` results:
|
|
196
|
+
|
|
197
|
+
```js
|
|
198
|
+
await client.auth.signUp({ email, password })
|
|
199
|
+
await client.auth.signIn({ email, password }) // preferred name
|
|
200
|
+
await client.auth.signInWithPassword({ email, password })
|
|
201
|
+
await client.auth.sendMagicLink({ email })
|
|
202
|
+
await client.auth.verifyMagicLink({ token })
|
|
203
|
+
const { data: oauth, error: oauthError } = await client.auth.signInWithOAuth({ provider: 'google' })
|
|
204
|
+
if (oauthError) throw oauthError
|
|
205
|
+
if (!oauth) throw new Error('Sign-in URL unavailable')
|
|
206
|
+
window.location.href = oauth.url
|
|
207
|
+
const { data: me, error: userError } = await client.auth.getUser()
|
|
208
|
+
if (userError) throw userError
|
|
209
|
+
const user = me?.user ?? null
|
|
210
|
+
client.auth.onAuthStateChange((event, session) => { /* SIGNED_IN / SIGNED_OUT / ... */ })
|
|
211
|
+
await client.auth.signOut()
|
|
212
|
+
```
|
|
213
|
+
|
|
214
|
+
In a browser these auth methods run in **cookie mode** by default
|
|
215
|
+
(0.14.1): the SDK posts to your app's own auth routes
|
|
216
|
+
(`/api/auth/*` — the one-line packaged route above, see
|
|
217
|
+
`docs({ topic: 'auth-client' })`) and the session is set as httpOnly cookies.
|
|
218
|
+
No tokens land in JS or localStorage; `error.message` carries the real cause
|
|
219
|
+
("Wrong email or password."). `getSession()` returns
|
|
220
|
+
`{ cookie_session: true, user }`.
|
|
221
|
+
|
|
222
|
+
Scope boundary: `functions.invoke()` also rides that cookie. Direct
|
|
223
|
+
`from()`, storage, and channel calls go to the platform API. Bearer-based
|
|
224
|
+
browser calls still work and warn before any future enforcement; cookie sign-in deliberately does not credential those surfaces.
|
|
225
|
+
Node/CLI keep header mode (tokens in SDK memory); pass
|
|
226
|
+
`{ authMode: 'header' }` only when the client is meant to hold tokens.
|
|
227
|
+
|
|
228
|
+
Name/result alignment for new code:
|
|
229
|
+
|
|
230
|
+
| Intent | Preferred method | Compatibility alias | Result |
|
|
231
|
+
| --- | --- | --- | --- |
|
|
232
|
+
| Password sign-in | `signIn` | `signInWithPassword` | `{ data: { user, session }, error }` |
|
|
233
|
+
| Send passwordless link | `sendMagicLink` | — | `{ data, error }` |
|
|
234
|
+
| Complete passwordless link | `verifyMagicLink` | — | `{ data: { user, session }, error }` |
|
|
235
|
+
| Complete password reset | `verifyPasswordReset` | `verifyOtp` (same call) | `{ data, error }` |
|
|
236
|
+
|
|
237
|
+
No compatibility alias is removed here. A future removal or result-shape break
|
|
238
|
+
requires a major version.
|
|
239
|
+
|
|
240
|
+
## Storage — client.storage.from(bucket)
|
|
241
|
+
|
|
242
|
+
For browser uploads and downloads, declare a file collection in
|
|
243
|
+
`db/schema.ts` and use the generated `somewhere:files` client
|
|
244
|
+
(`docs({ topic: 'declared-files' })`). `client.storage` is a compatibility
|
|
245
|
+
API over `/v1/fs`, which accepts only a developer key or a project runtime
|
|
246
|
+
key: an app-user session token is refused, and a developer key is refused
|
|
247
|
+
from a browser. Use it from server code only.
|
|
248
|
+
|
|
249
|
+
```js
|
|
250
|
+
await client.storage.from('avatars').upload('me.png', file)
|
|
251
|
+
client.storage.from('avatars').getPublicUrl('me.png') // { data: { publicUrl } }
|
|
252
|
+
await client.storage.from('avatars').download('me.png')
|
|
253
|
+
await client.storage.from('avatars').remove(['me.png'])
|
|
254
|
+
```
|
|
255
|
+
|
|
256
|
+
To mint a signed download URL while the file exists, send
|
|
257
|
+
`POST /v1/fs/<project_id>/sign` with your developer key and the JSON body
|
|
258
|
+
`{ "path": "/avatars/me.png", "expires_in": 3600 }`.
|
|
259
|
+
|
|
260
|
+
## Live updates — not client.channel
|
|
261
|
+
|
|
262
|
+
The adapter has no realtime channel. Supabase-style `channel()`, broadcast and
|
|
263
|
+
presence are not available, and the channel transport refuses app-user and
|
|
264
|
+
visitor sessions. The live path a browser can use is a declared live view:
|
|
265
|
+
the function returns rows plus a subscription URL, and `watchLive` re-reads
|
|
266
|
+
through your function on every invalidation.
|
|
267
|
+
|
|
268
|
+
```js
|
|
269
|
+
import { watchLive } from '/__sw/rooms/client.js'
|
|
270
|
+
|
|
271
|
+
watchLive(
|
|
272
|
+
() => fetch('/api/open-notes', { credentials: 'include' }).then(r => r.json()),
|
|
273
|
+
(rows) => render(rows),
|
|
274
|
+
)
|
|
275
|
+
```
|
|
276
|
+
|
|
277
|
+
Declare the list server-side with `sw.rooms.live(name, sw.db.from(...))` →
|
|
278
|
+
docs({ topic: 'rooms' }), "Live lists".
|
|
279
|
+
|
|
280
|
+
## Functions — client.functions.invoke
|
|
281
|
+
|
|
282
|
+
```js
|
|
283
|
+
const { data, error } = await client.functions.invoke('checkout', { body: { plan: 'pro' } })
|
|
284
|
+
```
|
|
285
|
+
|
|
286
|
+
Other languages → docs({ topic: 'sdks' }). Porting an existing app → the
|
|
287
|
+
migration guide via docs({ topic: 'migration-supabase' }).
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
# Client SDK — JavaScript and TypeScript
|
|
2
|
+
|
|
3
|
+
Use the JavaScript/TypeScript SDK for browser sign-in, typed function calls
|
|
4
|
+
and developer automation. The default starter already includes its auth
|
|
5
|
+
client and server route. Extend those working files when building an app.
|
|
6
|
+
|
|
7
|
+
| Package | Install | Version |
|
|
8
|
+
|---|---|---|
|
|
9
|
+
| @somewhere-cloud/sdk | npm i @somewhere-cloud/sdk | 0.14.1 |
|
|
10
|
+
|
|
11
|
+
Choose the entry for the code you're writing:
|
|
12
|
+
|
|
13
|
+
- **Browser sign-in:** `@somewhere-cloud/sdk/auth` manages same-origin cookie
|
|
14
|
+
sessions. → `auth-client`
|
|
15
|
+
- **App data and files:** declare access in `db/schema.ts`, then use
|
|
16
|
+
`somewhere:data` and `somewhere:files` in pages. Functions receive `sw`.
|
|
17
|
+
→ `declared-data`, `declared-files`, `functions`
|
|
18
|
+
- **Calls to your functions:** use the generated typed function client.
|
|
19
|
+
→ `typed-functions`
|
|
20
|
+
- **Developer scripts:** use the SDK with a developer key kept on the server,
|
|
21
|
+
or use `somewhere call <tool> '<json>'` from the CLI. → `sdk`, `cli`
|
|
22
|
+
|
|
23
|
+
See `sdk` for exports and result shapes, and `api-surface` for the HTTP
|
|
24
|
+
contract. Keep developer keys out of browser code.
|
|
@@ -0,0 +1,199 @@
|
|
|
1
|
+
# Search — managed document search and named indexes
|
|
2
|
+
|
|
3
|
+
> Named-index writes also have a reported name-length failure: creation can
|
|
4
|
+
> succeed while upsert returns `UPSTREAM_ERROR`. Successful creation alone
|
|
5
|
+
> does not verify an index. The exact supported length is under investigation.
|
|
6
|
+
|
|
7
|
+
Managed search makes each user's own documents searchable by meaning. The
|
|
8
|
+
platform extracts the text, splits it into passages, indexes them, and keeps
|
|
9
|
+
them current. Rewriting a file replaces its passages, and deleting it removes
|
|
10
|
+
them.
|
|
11
|
+
|
|
12
|
+
## Managed file search — point it at a file (inside functions)
|
|
13
|
+
|
|
14
|
+
Declare per-user search once in `db/schema.ts`, next to your tables and file
|
|
15
|
+
collections:
|
|
16
|
+
|
|
17
|
+
```ts
|
|
18
|
+
// db/schema.ts
|
|
19
|
+
import { owner, schema } from 'somewhere/db';
|
|
20
|
+
|
|
21
|
+
export default schema({}, { search: owner() });
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
Without this declaration, `sw.search.add` and string-form
|
|
25
|
+
`sw.search.query` are refused with `SEARCH_NOT_DECLARED` (409).
|
|
26
|
+
|
|
27
|
+
From a signed-in request:
|
|
28
|
+
|
|
29
|
+
```js
|
|
30
|
+
await sw.search.add('/documents/<file id>/report.pdf')
|
|
31
|
+
const { results } = await sw.search.query('How do I rotate the signing key?')
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
`add(path)` publishes one file owned by the signed-in user and returns `searchable: "shortly"`; a newly added document becomes searchable shortly after the add returns, which can take a few minutes on a new index. It refuses a file the user doesn't own. String `query`
|
|
35
|
+
searches only what that user added. Ownership comes from the session and is
|
|
36
|
+
never an argument. Each result carries `content`, `score` and a `source`
|
|
37
|
+
naming the file and the passage's location in it. Without a verified user,
|
|
38
|
+
`sw.search.add` and string-form `sw.search.query` throw `AUTH_REQUIRED`
|
|
39
|
+
(401). For server work without a signed-in user, use a named index and authorize
|
|
40
|
+
access in your function.
|
|
41
|
+
|
|
42
|
+
`sw.search.remove({ index, ids })` removes items from a named index. It does
|
|
43
|
+
not accept a file path and is not the inverse of managed `add(path)`. Deleting
|
|
44
|
+
a managed file removes its passages; do not delete a file merely to un-index it.
|
|
45
|
+
|
|
46
|
+
In a function, `sw.search.remove` takes any number of ids. More than 1000
|
|
47
|
+
are removed in sequential batches of 1000, and success returns
|
|
48
|
+
`{ index, removed, item_count, batches }`. The `removed` count is the number
|
|
49
|
+
of items deleted. An already-absent ID contributes zero. The first batch that
|
|
50
|
+
fails stops the rest. If any earlier batches completed, the error is
|
|
51
|
+
`SEARCH_REMOVE_PARTIAL`. Its `partial` gives the confirmed deletion count
|
|
52
|
+
(`removed`), the IDs confirmed absent after their batch (`removed_ids`),
|
|
53
|
+
the IDs in an unconfirmed batch (`unconfirmed_ids`), and the remaining IDs
|
|
54
|
+
(`not_removed_ids`). Check which
|
|
55
|
+
unconfirmed ids still exist before removing them again, and delete the record
|
|
56
|
+
or file the items describe only after the removal has succeeded.
|
|
57
|
+
|
|
58
|
+
Direct `POST /v1/search/remove` and the MCP `search_delete` accept at most
|
|
59
|
+
1000 ids per request; a longer list is refused with 400 `VALIDATION_ERROR`
|
|
60
|
+
before anything is removed. A `SEARCH_REMOVE_UNCONFIRMED` answer means that
|
|
61
|
+
request's outcome is unknown. One `upsert` call accepts up to 100 items.
|
|
62
|
+
|
|
63
|
+
The object forms `sw.search.upsert({ index, items })` and
|
|
64
|
+
`sw.search.query({ index, query })` work on named indexes for content you
|
|
65
|
+
compose yourself. A named index is shared across the project: your function
|
|
66
|
+
decides which items each caller may see.
|
|
67
|
+
|
|
68
|
+
## File search — sw.fs.dev.search (developer run_code only)
|
|
69
|
+
|
|
70
|
+
Full-text search across the project's text files. Used by code agents
|
|
71
|
+
to grep code, search docs, find TODOs.
|
|
72
|
+
|
|
73
|
+
Available in developer run_code. File search, glob and diff are unavailable
|
|
74
|
+
in deployed functions, including the server file view. As a `run_code` input:
|
|
75
|
+
|
|
76
|
+
```json
|
|
77
|
+
{
|
|
78
|
+
"project_id": "my-app",
|
|
79
|
+
"code": "export default async function (sw) { return await sw.fs.dev.search({ path: '/src/', query: 'TODO', limit: 50 }) }"
|
|
80
|
+
}
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
The full contract is in `file-tools` → `search-glob-and-diff`. Per-project full-text index,
|
|
84
|
+
kept in sync automatically on every fs write/delete/move/replace.
|
|
85
|
+
|
|
86
|
+
## Semantic search — named indexes
|
|
87
|
+
|
|
88
|
+
Vector search for product features (FAQ search, semantic
|
|
89
|
+
recommendations, RAG retrieval). Embeddings are 768-dim
|
|
90
|
+
(cosine distance). Each project can hold many named indexes.
|
|
91
|
+
|
|
92
|
+
Manage indexes over MCP with `search_index_create`, `search_index_list`,
|
|
93
|
+
`search_upsert`, `search_query` and `search_delete`. Inside a deployed
|
|
94
|
+
function, use `sw.search` — the platform handles the connection and project
|
|
95
|
+
scope. See "From inside a function" below.
|
|
96
|
+
|
|
97
|
+
## search_index_create({ project_id, name })
|
|
98
|
+
Idempotent — returns the existing index if name already exists.
|
|
99
|
+
Returns { name, project_id, dimensions, distance_metric, created_at }.
|
|
100
|
+
|
|
101
|
+
## search_index_list({ project_id })
|
|
102
|
+
Lists every index on the project: [{ name, item_count, created_at }].
|
|
103
|
+
|
|
104
|
+
## search_delete({ project_id, index, ids? })
|
|
105
|
+
Delete from a search index. Pass ids (a JSON array of item id
|
|
106
|
+
strings) to remove specific items, up to 1000 per call (more is refused
|
|
107
|
+
before anything is removed); omit ids to drop the entire
|
|
108
|
+
index AND all items in it (irreversible).
|
|
109
|
+
|
|
110
|
+
## search_upsert({ project_id, index, items })
|
|
111
|
+
Insert or replace items. items is a JSON array of:
|
|
112
|
+
{ id, content, metadata? }
|
|
113
|
+
|
|
114
|
+
search_upsert({
|
|
115
|
+
project_id: "my-app",
|
|
116
|
+
index: "faqs",
|
|
117
|
+
items: [
|
|
118
|
+
{ id: "faq-1", content: "How do I reset my password?", metadata: { category: "account" } },
|
|
119
|
+
{ id: "faq-2", content: "Where can I see my billing history?", metadata: { category: "billing" } }
|
|
120
|
+
]
|
|
121
|
+
})
|
|
122
|
+
|
|
123
|
+
content is embedded server-side — you never compute embeddings
|
|
124
|
+
yourself. metadata is returned alongside results but NOT searched.
|
|
125
|
+
Max 100 items per call.
|
|
126
|
+
|
|
127
|
+
## search_query({ project_id, index, query, limit? })
|
|
128
|
+
Returns top N matches by cosine similarity:
|
|
129
|
+
{ results: [{ id, score, content, metadata }] }
|
|
130
|
+
|
|
131
|
+
search_query({
|
|
132
|
+
project_id: "my-app",
|
|
133
|
+
index: "faqs",
|
|
134
|
+
query: "I forgot my login",
|
|
135
|
+
limit: 5
|
|
136
|
+
})
|
|
137
|
+
|
|
138
|
+
Score is 0–1. Higher is closer. Limit defaults to 10, max 100.
|
|
139
|
+
|
|
140
|
+
## From inside a function — sw.search.*
|
|
141
|
+
|
|
142
|
+
Same surface, same args, no API key. Use sw.search inside a deployed
|
|
143
|
+
function — the platform binding handles auth and project scope.
|
|
144
|
+
|
|
145
|
+
```ts
|
|
146
|
+
// api/_lib/faq-index.ts — server helpers over the project-wide 'faqs' index.
|
|
147
|
+
// A named index is shared across the project, so the calling handler has
|
|
148
|
+
// already decided who may change it and which results each caller may see.
|
|
149
|
+
|
|
150
|
+
// Index management
|
|
151
|
+
export async function setUpFaqIndex(sw: SomewhereRuntimeContext): Promise<string[]> {
|
|
152
|
+
await sw.search.createIndex('faqs')
|
|
153
|
+
const { indexes } = await sw.search.listIndexes()
|
|
154
|
+
return indexes.map((index) => index.name)
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
export async function dropFaqIndex(sw: SomewhereRuntimeContext): Promise<void> {
|
|
158
|
+
await sw.search.deleteIndex('faqs')
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
// Upsert
|
|
162
|
+
export async function saveFaq(sw: SomewhereRuntimeContext, id: string, content: string, category: string): Promise<number> {
|
|
163
|
+
const r = await sw.search.upsert({
|
|
164
|
+
index: 'faqs',
|
|
165
|
+
items: [{ id, content, metadata: { category } }],
|
|
166
|
+
})
|
|
167
|
+
return r.upserted
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
// Query
|
|
171
|
+
export async function findFaqs(sw: SomewhereRuntimeContext, question: string): Promise<{ id: string; score: number; content: string }[]> {
|
|
172
|
+
const { results } = await sw.search.query({ index: 'faqs', query: question, limit: 5 })
|
|
173
|
+
return results.map(({ id, score, content }) => ({ id, score, content }))
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
// Remove specific items
|
|
177
|
+
export async function removeFaq(sw: SomewhereRuntimeContext, id: string): Promise<number> {
|
|
178
|
+
const r = await sw.search.remove({ index: 'faqs', ids: [id] })
|
|
179
|
+
return r.removed
|
|
180
|
+
}
|
|
181
|
+
```
|
|
182
|
+
|
|
183
|
+
For example, `saveFaq(sw, 'faq-1', 'How do I reset my password?', 'account')`
|
|
184
|
+
then `findFaqs(sw, 'I forgot my login')`. Pass a single string to
|
|
185
|
+
`removeFaq(sw, 'faq-1')`. The write helpers return the count for that
|
|
186
|
+
operation. Removing an already-absent FAQ returns zero. `item_count` is the
|
|
187
|
+
number of items in the index after the write.
|
|
188
|
+
|
|
189
|
+
## When to use which
|
|
190
|
+
- Searching files (code, markdown, configs in your project) from developer run_code → sw.fs.dev.search
|
|
191
|
+
- Semantic / "find similar meaning" over your app's content → sw.search.* (or search_index_* MCP)
|
|
192
|
+
- Searching log bodies or analytics → use sw.logs / sw.analytics.query
|
|
193
|
+
|
|
194
|
+
## What NOT to do
|
|
195
|
+
- Don't put PII in metadata if you don't have to — it's stored with
|
|
196
|
+
the embeddings.
|
|
197
|
+
- Don't reindex a whole catalog on every write; batch upserts of 100.
|
|
198
|
+
- Don't expect exact-match — semantic search ranks by meaning, not
|
|
199
|
+
keyword overlap.
|
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
# Security model — who can read/write what
|
|
2
|
+
|
|
3
|
+
The platform runs sign-in, sessions and the data boundary; your functions
|
|
4
|
+
decide what each signed-in user may do.
|
|
5
|
+
|
|
6
|
+
Handled for you: sessions travel in HttpOnly cookies, `sw.auth.fromRequest(req)`
|
|
7
|
+
returns the verified user, and browser sessions reach data only through your
|
|
8
|
+
functions and the generated data client, never through raw SQL. On a declared
|
|
9
|
+
`owner()` table, `sw.db.from`, `insert`, `update` and `remove` are scoped to
|
|
10
|
+
that user automatically. Secrets stay on the server in `sw.env`.
|
|
11
|
+
|
|
12
|
+
Yours to decide: which user may take which action. Check it in the function
|
|
13
|
+
before the work runs — `await sw.auth.requireUser(req, { role: 'admin' })`
|
|
14
|
+
answers 401 to a signed-out caller and 403 to anyone who isn't an admin. A raw
|
|
15
|
+
read through `sw.db.server.query` runs exactly as written, so authorize the
|
|
16
|
+
caller first and take the user from the session, never from the request body.
|
|
17
|
+
|
|
18
|
+
Next: `security-model` → `your-part-the-seven-app-security-rules` has a block
|
|
19
|
+
to paste into your project instructions; `sw.auth`, `sw.db` and `cors` cover
|
|
20
|
+
each boundary in depth.
|
|
21
|
+
|
|
22
|
+
## Three actor classes
|
|
23
|
+
|
|
24
|
+
1. **End users** of your app — sign up via `sw.auth`. Get a JWT in
|
|
25
|
+
cookies or `Authorization: Bearer …`. Identified by
|
|
26
|
+
`sw.auth.fromRequest(req)`. Cannot run raw SQL from the browser.
|
|
27
|
+
2. **Your server functions** — code you deploy under `api/*`. Run with
|
|
28
|
+
project-level credentials. Can hit any `sw.*` method and read env
|
|
29
|
+
vars. On managed projects (the default), ordinary raw SQL is refused:
|
|
30
|
+
raw reads go through `sw.db.server.query` / `sw.db.server.batch`
|
|
31
|
+
after your code authorizes the caller, and raw writes are refused.
|
|
32
|
+
SQL-mode projects can run raw SQL.
|
|
33
|
+
3. **You (the developer)** — somewhere.cloud account, smt_ API key.
|
|
34
|
+
Can deploy, change settings, query the database, and access logs.
|
|
35
|
+
|
|
36
|
+
## Data access via the CLI, MCP server & API
|
|
37
|
+
|
|
38
|
+
The somewhere MCP server and `somewhere` CLI are clients for your own control plane. They let an agent or developer manage YOUR account — create projects, deploy code, run database queries, manage files, secrets, and domains.
|
|
39
|
+
|
|
40
|
+
- Authentication: OAuth 2.0 (MCP) or interactive browser login (`somewhere auth login`, CLI). The session token is stored locally in `~/.somewhere/config.json` and sent only to the Somewhere API and MCP hosts over HTTPS. We never request, read, or store third-party passwords. A revocable `smt_` API key is offered for CI; it is the only long-lived credential.
|
|
41
|
+
- Scope: the token acts as your developer identity — it can perform any action your account can (read/write your projects' source, databases, stored files, environment variables/secrets, deploys, billing config) and ONLY for resources your account owns, never another user's. During `somewhere deploy` the CLI reads the project source in the working directory to upload it and reads nothing outside that directory.
|
|
42
|
+
- What it does not do: it does not read arbitrary files on your machine, harvest environment variables, touch other applications' credentials, or contact any host other than the Somewhere API. Secret VALUES are write-only through these tools — they cannot be read back.
|
|
43
|
+
- Disconnect a connected agent on the [Agents page](https://somewhere.cloud/app/agents). Revoke a developer key with `DELETE /v1/keys/<id>`.
|
|
44
|
+
|
|
45
|
+
## Per-user data access
|
|
46
|
+
|
|
47
|
+
For data scoped to an end-user (notes, orders, messages, etc.), declare the
|
|
48
|
+
table with `scope: owner()` in `db/schema.ts` and use the structured
|
|
49
|
+
builder — it scopes to the request's verified user automatically, with no user
|
|
50
|
+
argument:
|
|
51
|
+
|
|
52
|
+
```js
|
|
53
|
+
// auto-scoped to the signed-in user
|
|
54
|
+
const mine = await sw.db.from('notes');
|
|
55
|
+
await sw.db.insert('notes', { body }); // owner column set by the platform
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
On managed projects, ordinary `sw.db.query` / `sw.db.batch` are refused.
|
|
59
|
+
For an intentional raw read, authorize the caller first and use
|
|
60
|
+
`sw.db.server.query` / `sw.db.server.batch`; those calls are never scoped or
|
|
61
|
+
rewritten for you.
|
|
62
|
+
|
|
63
|
+
## Can raw SQL bypass scoping?
|
|
64
|
+
|
|
65
|
+
- **From browser code:** no. App-user database access is structured table
|
|
66
|
+
access; raw SQL endpoints refuse app-user credentials.
|
|
67
|
+
- **From your own server code:** only deliberately. A trusted server function
|
|
68
|
+
must authorize the caller and select `sw.db.server.query` or
|
|
69
|
+
`sw.db.server.batch` for an intentional raw read. Options on ordinary raw
|
|
70
|
+
calls do not grant server authority in managed mode.
|
|
71
|
+
- **Via the MCP `db_query` tool:** yes — but only with your developer
|
|
72
|
+
key (smt_), never with an end-user JWT.
|
|
73
|
+
|
|
74
|
+
## Deploy-time + on-demand review
|
|
75
|
+
|
|
76
|
+
- **Every deploy** runs a pattern scanner that catches the obvious shapes
|
|
77
|
+
(auth bypass, raw SQL, payment metadata spoof, env leakage, eval,
|
|
78
|
+
RCE). Its hits surface as `warnings[]` in the deploy response and do not
|
|
79
|
+
block the deploy.
|
|
80
|
+
- **Deterministic refusals.** A deploy is refused, and nothing is
|
|
81
|
+
published, for a recognized secret key in source (`SECRET_IN_SOURCE`),
|
|
82
|
+
for browser code reading a `VITE_`/`REACT_APP_` variable whose value is a
|
|
83
|
+
secret key (`BROWSER_ENV_SECRET`), and for an uploaded private credential
|
|
84
|
+
file such as `.env`, `.pem`/`.key` or a service-account key
|
|
85
|
+
(`DEPLOY_PATH_REJECTED`).
|
|
86
|
+
- **On-demand** (`security_review` MCP tool) runs
|
|
87
|
+
an LLM over the deployed code and returns a Markdown report with
|
|
88
|
+
WHAT/WHERE/IMPACT/FIX per finding. Every plan runs the same reviewer;
|
|
89
|
+
plans that include the deep review (`tier_unlocks_deep_review: true`)
|
|
90
|
+
allow a longer report. Per-run cost is at /v1/pricing.
|
|
91
|
+
|
|
92
|
+
## Server-side secrets
|
|
93
|
+
|
|
94
|
+
- `sw.env.SECRET_NAME` — server-side. Reading it inside a handler is
|
|
95
|
+
fine. Returning it in a response (`Response.json(sw.env)`) is a leak;
|
|
96
|
+
the security review flags this shape.
|
|
97
|
+
- `VITE_*` / `REACT_APP_*` names remain server-only until you explicitly
|
|
98
|
+
mark them public. A public value with one of those names is visible in
|
|
99
|
+
the browser to every visitor. Use this for an API
|
|
100
|
+
base URL or a publishable key, never a service secret.
|
|
101
|
+
- Service keys: set via `somewhere env set KEY --stdin` or the dashboard.
|
|
102
|
+
Stored encrypted; read with `sw.env.KEY` in a server function.
|
|
103
|
+
Do not return the value to the browser.
|
|
104
|
+
|
|
105
|
+
## Admin paths
|
|
106
|
+
|
|
107
|
+
- `sw.auth.admin` (privileged auth ops — delete user, list all users)
|
|
108
|
+
is not callable inside deployed functions — any call throws
|
|
109
|
+
`AUTH_ADMIN_REMOVED_FROM_RUNTIME`. Use the developer-key surface
|
|
110
|
+
instead (auth_user_update, auth_user_delete, auth_users_list) from your
|
|
111
|
+
own tooling. A developer cannot sign in as an app user (410
|
|
112
|
+
`IMPERSONATION_RETIRED`).
|
|
113
|
+
- `sw.db.migrate` is removed from deployed functions; run schema changes with
|
|
114
|
+
developer credentials through `db_migrate`, the CLI, or dashboard.
|
|
115
|
+
- `sw.keys.*` / `sw.deploy.*` are developer-key only.
|
|
116
|
+
|
|
117
|
+
## Runtime function key scope
|
|
118
|
+
|
|
119
|
+
Your deployed functions share one server credential
|
|
120
|
+
(`PROJECT_API_KEY`) that lives inside the `sw.*` helpers and is never
|
|
121
|
+
exposed to your code. On deploy it is scoped to exactly the
|
|
122
|
+
surfaces your functions use: a function that only calls `sw.db` and
|
|
123
|
+
`sw.payments` gets a key that can reach the database and payments
|
|
124
|
+
areas and nothing else — a call to an unused area is refused. This is
|
|
125
|
+
derived from your code automatically (no config), and every `sw.*`
|
|
126
|
+
surface keeps working unchanged. If you reach the platform only through the
|
|
127
|
+
documented `sw.*` methods (the normal case), there is nothing to do.
|
|
128
|
+
|
|
129
|
+
## Auth token lifecycle
|
|
130
|
+
|
|
131
|
+
- Access tokens: 1 minute. Auto-refreshed inline — if expired and the
|
|
132
|
+
refresh is valid, the response includes `X-New-Access-Token` +
|
|
133
|
+
`X-New-Refresh-Token` headers (CORS exposes them).
|
|
134
|
+
- Refresh tokens rotate on every refresh; store the replacement pair. A
|
|
135
|
+
just-rotated token is briefly accepted so concurrent refreshes don't sign
|
|
136
|
+
the user out. A replay after that window revokes every session and refresh
|
|
137
|
+
token the user has in the project. Lifetimes and current windows:
|
|
138
|
+
`docs({ topic: 'sw.auth', section: 'token-types' })`.
|
|
139
|
+
- Revoke a session: `auth_revoke_session` (MCP) or
|
|
140
|
+
`DELETE /v1/auth/sessions/:id` with a developer key.
|
|
141
|
+
|
|
142
|
+
## Your part — the seven app-security rules
|
|
143
|
+
|
|
144
|
+
The platform owns the boundaries above. Which of your users may do what —
|
|
145
|
+
application-level authorization — is yours. These seven rules are the whole of
|
|
146
|
+
it; on somewhere most are the floor, not homework. Paste the block into the
|
|
147
|
+
project's CLAUDE.md (or equivalent) so every session starts with it:
|
|
148
|
+
|
|
149
|
+
```md
|
|
150
|
+
# Security rules (the browser is untrusted)
|
|
151
|
+
1. NEVER trust the client for identity: the user is who the SERVER says (verified session), never a user_id from a body, query param, or localStorage.
|
|
152
|
+
2. SCOPE EVERY QUERY to the signed-in user, server-side; default deny. Declare each table user-owned / shared / server-only (unsure = user-owned). Use sw.db.from / insert / update / remove for user-owned tables; any raw SQL carries its own WHERE user_id = ?.
|
|
153
|
+
3. THE BROWSER MAY NEVER WRITE PRIVILEGE FIELDS (role, is_admin, permissions, plan, balance, credits): server-set only; whitelist client-writable columns.
|
|
154
|
+
4. NO SECRETS IN CLIENT CODE: keys and tokens live in server env only and are read with sw.env inside a function; public keys are fine; if a secret reaches the page, rotate it.
|
|
155
|
+
5. AUTHORIZE ON THE SERVER, not in the UI: a hidden button is not a control; re-check the caller on every endpoint.
|
|
156
|
+
6. LOCK DOWN CORS: same-origin by default, explicit allowed origins only; never reflect an arbitrary Origin with credentials.
|
|
157
|
+
7. PARAMETERIZE EVERYTHING: no concatenated SQL; validate every input; treat every client field as hostile.
|
|
158
|
+
Server code stays free to do anything intended. These rules constrain the untrusted browser and the end-user credential only.
|
|
159
|
+
```
|
|
160
|
+
|
|
161
|
+
The block is written for any coding agent, on any stack. Here, the platform
|
|
162
|
+
verifies the session and scopes structured queries on user-owned tables to that
|
|
163
|
+
user (rules 1 and 2). In a handler that uses `sw.db.server.*` or raw SQL, take
|
|
164
|
+
the user from `sw.auth.requireUser(req)`, never from a request field. The
|
|
165
|
+
deploy review flags the most common slips on 3, 4 and 5 — the block keeps you
|
|
166
|
+
honest about the rest.
|
|
167
|
+
|
|
168
|
+
Related: `sw.auth`, `sw.db`, `common-mistakes`.
|