@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,836 +0,0 @@
1
- # Groups
2
-
3
- Teams people join and roles people hand on. The platform already keeps teams,
4
- their owners, invitations, rosters, removal, leaving and the last-owner rule,
5
- and who may hand out an app role: an app writes no membership code. Complete,
6
- copyable, tested apps: `team-example` (a team with invitations, roster, removal
7
- and leaving) and `staff-example` (staff who make other people staff).
8
-
9
- - Scope a team's rows with `group({ column: 'team_id', roles })` on a non-null
10
- `text()` column; inside `anyOf(owner(), group())` list all four operations.
11
- - Call `sw.groups` from endpoints: the browser cannot call it directly.
12
- - Starting a team needs a signed-in user; joining one needs a verified email.
13
- - Staff who make other people staff: `appRoles: { staff: { grantableBy: ['staff'] } }`
14
- and `sw.groups.appRoles.grant(request, userId, 'staff')`.
15
-
16
- ## Team example
17
-
18
- An ordinary team runs on built-in groups: someone starts a team, invites people
19
- by email, members share its rows, owners remove people, and anyone may leave.
20
- The platform keeps the team, its owner, invitations, the roster, removal,
21
- leaving, and the rule that a team always keeps an owner. Your app declares which
22
- rows belong to a team and passes each group call through a small endpoint.
23
-
24
- - Creating a team needs only a signed-in user. Joining one needs a verified
25
- email: someone who signs up with a password joins once they enter the code
26
- emailed to them, or open the invitation link, which verifies the address.
27
- - The browser cannot call `sw.groups`: group methods run in deployed functions,
28
- so each one the page needs gets an endpoint, as below. A method returns
29
- `{ data, error }`; these endpoints pass a refusal to the browser unchanged.
30
- - The roster has user ids and roles, no emails. To show emails, look up exactly
31
- the returned ids in the endpoint with `sw.auth.server.listUsers({ ids })`.
32
- - Group calls are slower than data calls today, about a second each and three
33
- for an invitation, so the spec raises Playwright's 30-second test timeout.
34
-
35
- Copy these files into a project made with `somewhere init`. Run
36
- `somewhere deploy && somewhere test` so the specs run after a successful deploy.
37
-
38
- ```ts
39
- // db/schema.ts
40
- import { schema, table, id, text, timestamp, owner, group, anyOf } from 'somewhere/db';
41
-
42
- export default schema({
43
- // team_id holds a built-in group's id. Members read, create and update tasks;
44
- // the task's creator or a team owner deletes it, and a creator who leaves the
45
- // team loses access too. Inside anyOf() an operation left out of roles allows
46
- // no group role, so all four are listed.
47
- tasks: table({ id: id(), team_id: text(), title: text(), created_at: timestamp({ default: 'now' }) }, {
48
- scope: anyOf(
49
- owner(),
50
- group({ column: 'team_id', roles: {
51
- read: ['owner', 'admin', 'member'],
52
- create: ['owner', 'admin', 'member'],
53
- update: ['owner', 'admin', 'member'],
54
- delete: ['owner'],
55
- } }),
56
- ),
57
- indexes: [['team_id']],
58
- client: { read: ['id', 'team_id', 'title', 'created_at'], create: ['team_id', 'title'], update: ['title'], delete: true },
59
- }),
60
- });
61
- ```
62
-
63
- ```ts
64
- // api/_groups.ts
65
- // A sw.groups refusal, passed to the browser unchanged: { error: code, message } with its status.
66
- export const refusal = (e: { code: string; message: string; status: number }) =>
67
- Response.json({ error: e.code, message: e.message }, { status: e.status });
68
- ```
69
-
70
- ```ts
71
- // api/teams.ts
72
- import { refusal } from './_groups';
73
-
74
- // GET /api/teams?cursor= — the caller's teams, each with their role. Listing
75
- // also completes invitations addressed to the caller's verified email.
76
- export const GET = sw.endpoint({
77
- auth: 'required',
78
- handler: async ({ request }, sw) => {
79
- const cursor = new URL(request.url).searchParams.get('cursor') ?? undefined;
80
- const page = await sw.groups.list(request, { cursor, limit: 100 });
81
- if (page.error) return refusal(page.error);
82
- return { teams: page.data.items, next_cursor: page.data.next_cursor };
83
- },
84
- });
85
-
86
- // POST /api/teams { name } — start a team; the caller becomes its owner.
87
- export default sw.endpoint({
88
- auth: 'required',
89
- body: { name: 'string' },
90
- handler: async ({ request, body }, sw) => {
91
- const created = await sw.groups.create(request, { name: body.name });
92
- if (created.error) return refusal(created.error);
93
- return { id: created.data.id, name: created.data.name };
94
- },
95
- });
96
- ```
97
-
98
- ```ts
99
- // api/teams/[id].ts
100
- import { refusal } from '../_groups';
101
-
102
- // GET /api/teams/:id — the team, the caller's role and the first page of
103
- // members ({ user_id, role, created_at }; sw.groups.members pages the rest).
104
- // Anyone who is not a member gets 404 GROUP_NOT_FOUND.
105
- export const GET = sw.endpoint({
106
- auth: 'required',
107
- handler: async ({ request, params }, sw) => {
108
- const team = await sw.groups.get(request, params.id);
109
- if (team.error) return refusal(team.error);
110
- return team.data;
111
- },
112
- });
113
-
114
- // DELETE /api/teams/:id — owners only. Memberships and pending invitations end;
115
- // the team's tasks stay in the database, unreachable by anyone signed in.
116
- export const DELETE = sw.endpoint({
117
- auth: 'required',
118
- handler: async ({ request, params }, sw) => {
119
- const deleted = await sw.groups.delete(request, params.id);
120
- if (deleted.error) return refusal(deleted.error);
121
- return null;
122
- },
123
- });
124
- ```
125
-
126
- ```ts
127
- // api/teams/[id]/invitations.ts
128
- import { refusal } from '../../_groups';
129
-
130
- // POST /api/teams/:id/invitations { email } — invite someone as a member.
131
- // Only owners and admins may (a member gets 403 ROLE_NOT_GRANTABLE); a current
132
- // member's address gets 409 ALREADY_MEMBER. One email goes out; the person
133
- // joins once they sign in with that address verified. The app accepts nothing.
134
- export default sw.endpoint({
135
- auth: 'required',
136
- body: { email: 'string' },
137
- handler: async ({ request, params, body }, sw) => {
138
- const invited = await sw.groups.invite(request, params.id, { email: body.email, role: 'member', redirect_uri: '/' });
139
- if (invited.error) return refusal(invited.error);
140
- return { invite_id: invited.data.invite.id, delivery: invited.data.delivery };
141
- },
142
- });
143
-
144
- // GET /api/teams/:id/invitations — pending invitations the caller could withdraw
145
- // (sw.groups.revokeInvitation(request, inviteId)); a plain member gets an empty list.
146
- export const GET = sw.endpoint({
147
- auth: 'required',
148
- handler: async ({ request, params }, sw) => {
149
- const page = await sw.groups.invitations(request, params.id, { limit: 100 });
150
- if (page.error) return refusal(page.error);
151
- return { invitations: page.data.items };
152
- },
153
- });
154
- ```
155
-
156
- ```ts
157
- // api/teams/[id]/members/[userId].ts
158
- import { refusal } from '../../../_groups';
159
-
160
- // DELETE /api/teams/:id/members/:userId — an owner removes a member, or a
161
- // member removes themselves (leaves). A member removing someone else gets 403
162
- // GROUP_ROLE_FORBIDDEN; the last owner cannot leave or be removed (409 LAST_OWNER).
163
- export const DELETE = sw.endpoint({
164
- auth: 'required',
165
- handler: async ({ request, params, user }, sw) => {
166
- const done = params.userId === user.id
167
- ? await sw.groups.leave(request, params.id)
168
- : await sw.groups.remove(request, params.id, params.userId);
169
- if (done.error) return refusal(done.error);
170
- return null;
171
- },
172
- });
173
- ```
174
-
175
- ```ts
176
- // tests/team.spec.ts
177
- import { test, expect, expectRefused, data, type TestUser } from '@somewhere-cloud/cli/testing';
178
-
179
- // Each group call takes about a second, so a team with members needs more than 30 s.
180
- test.describe.configure({ timeout: 90_000 });
181
-
182
- // A test user who is still a team's only owner cannot be deleted: delete every team a test makes.
183
- const made: { owner: TestUser; id: string }[] = [];
184
- test.afterEach(async () => {
185
- for (const t of made.splice(0)) expect([204, 404]).toContain((await t.owner.request.delete(`/api/teams/${t.id}`)).status());
186
- });
187
-
188
- async function teamOf(owner: TestUser, ...members: TestUser[]): Promise<string> {
189
- const created = await owner.request.post('/api/teams', { data: { name: `Team ${crypto.randomUUID().slice(0, 8)}` } });
190
- expect(created.status()).toBe(200);
191
- const { id } = await created.json();
192
- made.push({ owner, id });
193
- for (const member of members) {
194
- expect((await owner.request.post(`/api/teams/${id}/invitations`, { data: { email: member.email } })).status()).toBe(200);
195
- // Test users are verified, so the member's next teams read completes the invitation.
196
- const { teams } = await (await member.request.get('/api/teams')).json();
197
- expect(teams).toContainEqual(expect.objectContaining({ id, role: 'member' }));
198
- }
199
- return id;
200
- }
201
-
202
- async function taskBy(user: TestUser, teamId: string) {
203
- const created = await data(user.request, 'tasks', { operation: 'create', values: { team_id: teamId, title: 'Ship it' } });
204
- expect(created.status()).toBe(200);
205
- return (await created.json()).data as { id: string };
206
- }
207
-
208
- test('members share tasks; the creator or an owner deletes; outsiders get nothing', async ({ newUser, anonymous }) => {
209
- const [owner, ann, ben, outsider] = await Promise.all([newUser(), newUser(), newUser(), newUser()]);
210
- const teamId = await teamOf(owner, ann, ben);
211
- const task = await taskBy(ann, teamId);
212
-
213
- const seen = await (await data(ben.request, 'tasks', { operation: 'list', where: { team_id: teamId } })).json();
214
- expect(seen.data.map((t: { id: string }) => t.id)).toEqual([task.id]);
215
- await expectRefused(outsider, 'tasks', { operation: 'get', id: task.id }, { allowed: ben });
216
- await expectRefused(outsider, 'tasks', { operation: 'create', values: { team_id: teamId, title: 'Sneaky' } });
217
- await expectRefused(outsider, `GET /api/teams/${teamId}`, undefined, { allowed: ben });
218
- await expectRefused(anonymous, 'tasks', { operation: 'list' });
219
-
220
- await expectRefused(ben, 'tasks', { operation: 'delete', id: task.id }, { allowed: owner });
221
- expect((await data(ann.request, 'tasks', { operation: 'delete', id: task.id })).status()).toBe(200);
222
- const second = await taskBy(ann, teamId);
223
- expect((await data(owner.request, 'tasks', { operation: 'delete', id: second.id })).status()).toBe(200);
224
- });
225
-
226
- test('only owners invite and remove; members leave; the last owner stays', async ({ newUser }) => {
227
- const [owner, ann, ben] = await Promise.all([newUser(), newUser(), newUser()]);
228
- const teamId = await teamOf(owner, ann, ben);
229
- const task = await taskBy(ann, teamId);
230
-
231
- await expectRefused(ann, `POST /api/teams/${teamId}/invitations`, { email: `x-${crypto.randomUUID().slice(0, 8)}@example.com` });
232
- await expectRefused(ann, `DELETE /api/teams/${teamId}/members/${ben.id}`);
233
- const again = await owner.request.post(`/api/teams/${teamId}/invitations`, { data: { email: ann.email } });
234
- expect([again.status(), (await again.json()).error]).toEqual([409, 'ALREADY_MEMBER']);
235
- const leave = await owner.request.delete(`/api/teams/${teamId}/members/${owner.id}`);
236
- expect([leave.status(), (await leave.json()).error]).toEqual([409, 'LAST_OWNER']);
237
-
238
- const team = await (await ben.request.get(`/api/teams/${teamId}`)).json();
239
- expect(team.members.map((m: { user_id: string; role: string }) => `${m.role}:${m.user_id}`).sort())
240
- .toEqual([`owner:${owner.id}`, `member:${ann.id}`, `member:${ben.id}`].sort());
241
-
242
- expect((await ben.request.delete(`/api/teams/${teamId}/members/${ben.id}`)).status()).toBe(204);
243
- expect((await owner.request.delete(`/api/teams/${teamId}/members/${ann.id}`)).status()).toBe(204);
244
- // Removed, Ann loses even the task she created.
245
- await expectRefused(ann, 'tasks', { operation: 'get', id: task.id }, { allowed: owner });
246
- await expectRefused(ben, `GET /api/teams/${teamId}`, undefined, { allowed: owner });
247
- });
248
- ```
249
-
250
- Not shown, same pattern: withdraw an invitation with
251
- `sw.groups.revokeInvitation(request, inviteId)`, page a large roster with
252
- `sw.groups.members(request, teamId, { cursor, limit })`, and change a role with
253
- `setRole`. "A comment's author or a team owner deletes it" on a `parent()`
254
- child stays an endpoint: `parent()` passes delete to the parent row's rule (the
255
- task's creator or a team owner), not to the comment's author.
256
-
257
- ## Staff example
258
-
259
- A role that people who hold it hand on, such as staff making other people
260
- staff, needs no grant logic: declare `grantableBy` and call
261
- `sw.groups.appRoles.grant`. The platform refuses a grant from anyone who does
262
- not hold the role (`APP_ROLE_FORBIDDEN`) and a grant to oneself
263
- (`SELF_PROMOTION`); the role applies from the person's next request, and
264
- granting it does not need a verified email. Grant the first staff member
265
- yourself with `somewhere auth roles grant <email> staff`; in tests,
266
- `newUser({ role: 'staff' })` does the same.
267
-
268
- ```ts
269
- // db/schema.ts
270
- import { schema, table, id, text, owner, anyOf, appRole } from 'somewhere/db';
271
-
272
- export default schema({
273
- // A customer reads and updates the tickets they opened; anyone holding
274
- // staff reads and updates every ticket.
275
- tickets: table({ id: id(), subject: text() }, {
276
- scope: anyOf(owner(), appRole({ roles: { read: ['staff'], update: ['staff'] } })),
277
- client: { read: ['id', 'subject'], create: ['subject'], update: ['subject'] },
278
- }),
279
- }, {
280
- // Only someone who already holds staff can hand it on, never to themselves.
281
- // The first staff member: somewhere auth roles grant <email> staff.
282
- appRoles: { staff: { grantableBy: ['staff'] } },
283
- });
284
- ```
285
-
286
- ```ts
287
- // api/staff.ts
288
- // POST /api/staff { email } — a staff member makes an existing account staff.
289
- // The platform refuses a grant from anyone who does not hold staff
290
- // (403 APP_ROLE_FORBIDDEN) and a grant to oneself (403 SELF_PROMOTION).
291
- // The staff check below runs first only so that the address lookup never
292
- // tells a customer which addresses have accounts.
293
- const fail = (e: { code: string; message: string; status: number }) =>
294
- Response.json({ error: e.code, message: e.message }, { status: e.status });
295
-
296
- export default sw.endpoint({
297
- auth: 'required',
298
- body: { email: 'string' },
299
- handler: async ({ request, body }, sw) => {
300
- const mine = await sw.groups.appRoles.list(request, undefined, { limit: 100 });
301
- if (mine.error) return fail(mine.error);
302
- if (!mine.data.items.some((grant) => grant.role === 'staff')) {
303
- return Response.json({ error: 'STAFF_ONLY', message: 'Only staff can do this.' }, { status: 403 });
304
- }
305
- const { users: [target] } = await sw.auth.server.listUsers({ emails: [body.email] });
306
- if (!target) return Response.json({ error: 'ACCOUNT_NOT_FOUND', message: 'No account uses that email.' }, { status: 404 });
307
- const granted = await sw.groups.appRoles.grant(request, target.id, 'staff');
308
- if (granted.error) return fail(granted.error);
309
- return { user_id: target.id };
310
- },
311
- });
312
- ```
313
-
314
- ```ts
315
- // tests/staff.spec.ts
316
- import { test, expect, expectRefused, data } from '@somewhere-cloud/cli/testing';
317
-
318
- test('staff read every ticket and hand the role on; customers cannot', async ({ newUser }) => {
319
- const [staff, alice, bob] = await Promise.all([newUser({ role: 'staff' }), newUser(), newUser()]);
320
- const created = await data(alice.request, 'tickets', { operation: 'create', values: { subject: 'Late order' } });
321
- expect(created.status()).toBe(200);
322
- const { id } = (await created.json()).data;
323
-
324
- // Bob is a customer: he cannot read Alice's ticket or make anyone staff.
325
- await expectRefused(bob, 'tickets', { operation: 'get', id }, { allowed: staff });
326
- await expectRefused(bob, 'POST /api/staff', { email: bob.email });
327
- await expectRefused(alice, 'POST /api/staff', { email: bob.email });
328
-
329
- // Staff hand the role to Bob; it applies from his next request.
330
- expect((await staff.request.post('/api/staff', { data: { email: bob.email } })).status()).toBe(200);
331
- const read = await data(bob.request, 'tickets', { operation: 'get', id });
332
- expect((await read.json()).data).toMatchObject({ id, subject: 'Late order' });
333
- expect((await data(bob.request, 'tickets', { operation: 'update', id, values: { subject: 'Late order (chased)' } })).status()).toBe(200);
334
- });
335
- ```
336
-
337
- `sw.groups.appRoles.revoke(request, userId, 'staff')` takes the role back; any
338
- current holder may revoke it. A column only staff may set is declared with
339
- `columns` (`docs({ topic: 'declared-data' })`), and a staff-only endpoint with
340
- `roles: ['staff']` (`docs({ topic: 'sw.endpoint' })`). For a page that shows
341
- staff controls, `await sw.auth.requireUser(request, { appRoles: true })` returns
342
- the caller's own role names, read fresh.
343
-
344
- ## Share data with a group
345
-
346
- Built-in groups let people share rows with the people they invite, each with a
347
- role. The platform keeps the groups, their members, roles and invitations. Your
348
- `db/schema.ts` says which rows belong to a group and which roles may read,
349
- create, update or delete them. A later deploy can change which roles may do
350
- which operation on an existing table (a team owner gains delete); the rest of
351
- the rule and the role declarations stay as deployed (`sw.db` → the managed
352
- database section). A new app needs no membership table of its own.
353
- For an organiser whose authority covers the whole app rather than one invited
354
- team, see `appRole()` below in `app-wide-roles`.
355
- For files shared by a group,
356
- use a file collection with `parent({ table, via })` pointing to a group-scoped
357
- row: `declared-files` → `files-that-follow-a-group-row`.
358
-
359
- ### Declare a group table
360
-
361
- ```ts
362
- // db/schema.ts
363
- import { group, id, integer, schema, table, text, timestamp } from 'somewhere/db';
364
-
365
- export default schema({
366
- expenses: table(
367
- {
368
- id: id(),
369
- group_id: text(),
370
- description: text(),
371
- amount_cents: integer(),
372
- created_at: timestamp({ default: 'now' }),
373
- },
374
- {
375
- scope: group({ roles: { update: ['owner', 'admin'], delete: ['owner', 'admin'] } }),
376
- client: {
377
- read: true,
378
- create: ['group_id', 'description', 'amount_cents'],
379
- update: ['description', 'amount_cents'],
380
- delete: true,
381
- },
382
- },
383
- ),
384
- });
385
- ```
386
-
387
- `group()` ties each row to one group through its `group_id` text column
388
- (`group({ column: 'trip_id' })` names a different one). Every member reads and
389
- adds expenses; only owners and admins edit or delete them. In a `group()` scope
390
- on its own, an operation you leave out of `roles` is open to every role in the
391
- group. Inside `anyOf()` or `allOf()` it is open to **no** group role (the
392
- `owner()` branch already covers the row's creator), so list all four operations
393
- there, as `team-example` does. `[]` closes an operation to everyone.
394
- `client.create` must include the group column, so every new row names
395
- its group, and the caller must hold a role that may create in that group.
396
-
397
- ### Create a group and invite people
398
-
399
- ```ts
400
- // api/groups/create.ts — start a group; the caller becomes its owner
401
- export default async function createGroup(
402
- request: Request,
403
- sw: SomewhereRuntimeContext,
404
- ): Promise<Response> {
405
- if (request.method !== 'POST') {
406
- return new Response('Use POST.', { status: 405, headers: { Allow: 'POST' } });
407
- }
408
- if (!(await sw.auth.fromRequest(request))) {
409
- return Response.json({ error: 'Sign in first.' }, { status: 401 });
410
- }
411
- const body = (await request.json().catch(() => null)) as { name?: unknown } | null;
412
- const name = typeof body?.name === 'string' ? body.name.trim() : '';
413
- if (!name) return Response.json({ error: 'Name the group.' }, { status: 400 });
414
-
415
- const created = await sw.groups.create(request, { name });
416
- if (created.error) {
417
- return Response.json({ error: created.error.message, code: created.error.code }, { status: created.error.status });
418
- }
419
- return Response.json({ id: created.data.id, role: created.data.role }, { status: 201 });
420
- }
421
- ```
422
-
423
- ```ts
424
- // api/groups/invite.ts — invite someone by email as a member
425
- export default async function inviteToGroup(
426
- request: Request,
427
- sw: SomewhereRuntimeContext,
428
- ): Promise<Response> {
429
- if (request.method !== 'POST') {
430
- return new Response('Use POST.', { status: 405, headers: { Allow: 'POST' } });
431
- }
432
- if (!(await sw.auth.fromRequest(request))) {
433
- return Response.json({ error: 'Sign in first.' }, { status: 401 });
434
- }
435
- const body = (await request.json().catch(() => null)) as { groupId?: unknown; email?: unknown } | null;
436
- if (typeof body?.groupId !== 'string' || typeof body.email !== 'string') {
437
- return Response.json({ error: 'Send groupId and email.' }, { status: 400 });
438
- }
439
-
440
- const invited = await sw.groups.invite(request, body.groupId, {
441
- email: body.email,
442
- role: 'member',
443
- redirect_uri: '/trips',
444
- });
445
- if (invited.error) {
446
- return Response.json({ error: invited.error.message, code: invited.error.code }, { status: invited.error.status });
447
- }
448
- return Response.json({ invite_id: invited.data.invite.id, delivery: invited.data.delivery }, { status: 201 });
449
- }
450
- ```
451
-
452
- The invitation is one email. Only a member whose role may grant `member` (an
453
- owner or admin) can send it; anyone else gets `ROLE_NOT_GRANTABLE` and no email
454
- goes out. An address whose verified account is already a member gets 409
455
- `ALREADY_MEMBER`, and no email goes out. The link opens your app's `/auth/magic` page, which redeems it
456
- with `sw.auth.verifyOtp`: the starter's sign-in pages include it, and an app
457
- without that page never completes the invitation
458
- (`docs({ topic: 'sw.auth', section: 'magic-links' })`). The invitee signs in
459
- there; a new address gets an account. If the invitee's existing account had not verified its email yet,
460
- this first verification clears its earlier sign-in methods
461
- (`docs({ topic: 'sw.auth', section: 'keeping-your-password' })`).
462
- In the normal case that sign-in also adds them with the invited role,
463
- and they land on `redirect_uri` with `?invite_id=` as a member. Your app
464
- makes no call to accept. The link is a one-time sign-in for the invited
465
- address: whoever opens it signs in as that address, so it must not be
466
- forwarded. The
467
- sign-in result reports `group_invitation.state`: `completed` (a member now),
468
- `pending` (not confirmed yet) or `refused` with a `code`, such as
469
- `INVITATION_REVOKED`, `INVITATION_AUTHORITY_LOST` or `ALREADY_MEMBER`.
470
-
471
- **Joining without the link.** An invitation completes for the account whose
472
- **verified** email is the invited address, however that is proved:
473
-
474
- - Someone already signed in with that address verified joins as soon as they
475
- are invited, with no sign-in.
476
- - Someone who signs up or signs in with that address joins when the address is
477
- verified: the sign-in or the code verification adds them at once. Typing the
478
- address at sign-up is not enough; until it is verified they are not a member.
479
- - `sw.groups.list` also claims live invitations to the caller's verified
480
- address and completes them, a few per call, reporting each outcome in
481
- `invitations`; one stays pending while the platform still can't confirm it.
482
-
483
- Test users (`newUser()`) have verified addresses, so a test invites them and
484
- their next groups read shows the team (`team-example`).
485
-
486
- To add someone who already uses your app, without an email, call
487
- `sw.groups.add(request, groupId, userId, role)`. The same grant rules as
488
- `invite` apply. Only an account whose email is verified can be added this
489
- way. Any other id, unverified, banned, unknown or from another project, gets
490
- `TARGET_INELIGIBLE` with the same message, so the call reveals nothing
491
- about which accounts exist; invite those people by email instead. To add
492
- someone by email address, look the address up in server code, after authorizing
493
- the caller, with `sw.auth.server.listUsers({ emails: [address] })`
494
- (`docs({ topic: 'sw.auth', section: 'member-contacts' })`), then pass
495
- `users[0].id` to `add`. Never show the person using the form whether the
496
- address matched. If it has no account, or `add` answers
497
- `TARGET_INELIGIBLE`, send an invitation with `sw.groups.invite` instead,
498
- and answer the same way in every case so the form doesn't reveal who has an
499
- account. Adding
500
- someone who is already a member answers `ALREADY_MEMBER` and never changes
501
- their role (use `setRole`).
502
-
503
- A complete handler for this form: **Add an existing user by email** below.
504
-
505
- Until someone is a member, the group's rows are invisible to them. Their
506
- reads find nothing, and a create in that group answers 403
507
- `POLICY_AUTHORITY_REQUIRED`.
508
-
509
- To withdraw an invitation before it's accepted, call
510
- `sw.groups.revokeInvitation(request, inviteId)` with `invite.id` from
511
- `invite`. Its link then can't add anyone. Only the member who sent it, or a
512
- member whose role may grant its role, can revoke it. A current member without
513
- that authority gets `GROUP_ROLE_FORBIDDEN`; a non-member gets
514
- `INVITATION_NOT_FOUND`. An accepted invitation returns `INVITATION_USED`,
515
- and revoking twice is harmless.
516
-
517
- ### Read a group's rows
518
-
519
- ```ts
520
- // api/groups/expenses.ts — one group's expenses, for a member of that group
521
- export default async function groupExpenses(
522
- request: Request,
523
- sw: SomewhereRuntimeContext,
524
- ): Promise<Response> {
525
- if (!(await sw.auth.fromRequest(request))) {
526
- return Response.json({ error: 'Sign in first.' }, { status: 401 });
527
- }
528
- const groupId = new URL(request.url).searchParams.get('group') ?? '';
529
- if (!groupId) return Response.json({ error: 'Pass ?group=<id>.' }, { status: 400 });
530
-
531
- // group() returns rows only from groups the caller belongs to right now.
532
- const { data } = await sw.db.from('expenses', {
533
- where: { group_id: groupId },
534
- order: [['created_at', 'desc']],
535
- limit: 50,
536
- });
537
- return Response.json(data);
538
- }
539
- ```
540
-
541
- The browser reaches the same rows through `somewhere:data` with the `client`
542
- grant above. `sw.groups.list(request)` returns the groups the caller belongs to,
543
- each with the caller's role.
544
-
545
- ### Who may do what
546
-
547
- - **The account is the signed-in user of the request.** Every call acts as the
548
- user signed in on the request your function is handling. No method takes a
549
- user to act as.
550
- - **Membership is checked now.** Each read and write checks the user's current
551
- role in the row's group. Removing a member or changing a role applies to their
552
- next request, and their open live lists for that group close. Under
553
- `anyOf(owner(), group(...))`, a removed member also loses the rows they
554
- created in that group.
555
- - **Roles.** Every group has `owner`, `admin` and `member`. Add your own with
556
- `schema({ ... }, { groups: { roles: ['editor'], adminGrantableRoles: ['editor'] } })`.
557
- An owner can grant any role. An admin can grant `member` and the roles in
558
- `adminGrantableRoles`. Owners and admins manage members and added roles; only
559
- owners change or remove owners and admins. Group methods refuse to remove,
560
- demote or let leave a group's last owner (`LAST_OWNER`). If a group's only
561
- owner can no longer use the app, the platform team can restore an owner.
562
- - **Refusals are results.** Group methods return
563
- `{ data: null, error: { code, message, status } }` for an expected refusal:
564
- `GROUP_NOT_FOUND` for a group the caller doesn't belong to, `ROLE_NOT_GRANTABLE`
565
- for a role they can't grant, `LAST_OWNER` for removing the last owner. A call
566
- with no signed-in user, or from a job or queue delivery, returns
567
- `error.code: 'AUTH_REQUIRED'`.
568
- - **Groups run in your deployed app and in a preview.** In a preview they act
569
- on the preview's own users and copy of the data, and invitations are captured
570
- mail (`dev-environments` → "Signing in to a preview"). A local run refuses
571
- group calls (`DRAFT_CONTEXT_INVALID`).
572
-
573
- ### Hand a group over or delete it
574
-
575
- To hand a group to someone else, an owner makes them an owner with
576
- `setRole(request, groupId, newOwnerId, 'owner')`; the new owner then demotes
577
- or removes the old one with `setRole` or `remove`. A demoted owner cannot
578
- promote themselves back (`SELF_PROMOTION`).
579
-
580
- Deleting the account of a group's only owner is refused with `LAST_OWNER`
581
- naming the group, so hand the group over or delete it first.
582
-
583
- `sw.groups.delete(request, groupId)` deletes a group. Only an owner can;
584
- admins and members get `GROUP_ROLE_FORBIDDEN`. It ends every membership,
585
- revokes the group's pending invitations and closes its live lists. Your app's
586
- rows that named the group stay in your database: no signed-in user can reach
587
- them any more, and `sw.db.server` still can, so delete or archive them from a
588
- server function if you need to.
589
-
590
- ### More on groups
591
-
592
- | Need | Where |
593
- |---|---|
594
- | A background job that acts on one row for its user | `sw.jobs` → `act-on-one-row-for-the-signed-in-user` |
595
- | Charging for one row | `payments` → `charge-for-one-row-live-only` |
596
- | Every other scope and the generated client | `declared-data` |
597
-
598
- ## Relationships that are not teams
599
-
600
- Built-in groups are for teams people join. For a relationship your app records
601
- itself, such as a booking's provider or a class's enrolled students, or for
602
- membership that must exist before an email is verified, declare your own
603
- membership table and use `member()` over it. This is the advanced case.
604
- `sw.groups.add` deliberately requires the target user's verified email.
605
- A signed-in session with `email_verified: false` is nevertheless an
606
- authenticated identity for `owner()` and `member()` data rules. See `sw.db` →
607
- `provider-or-booker-and-owner-or-staff-recipes` for a per-record example.
608
- This does not call `sw.groups.add` or bypass its verification requirement.
609
-
610
- The server must authorize each membership write. Resolve the target user from
611
- your trusted enrollment flow, not a body field alone, and keep that table
612
- `serverOnly()`. `group: 'id'` is supported when a membership row names the
613
- scoped row's primary key: `member_group` names that corresponding column in
614
- the membership table. Never make the membership table publicly writable.
615
-
616
- ## Add an existing user by email
617
-
618
- One form that adds someone who already has an account, or invites the address
619
- when there is none, with one exact lookup and the same answer either way:
620
-
621
- ```ts
622
- // api/groups/add-by-email.ts — add an existing user, or invite the address
623
- export default async function addByEmail(
624
- request: Request,
625
- sw: SomewhereRuntimeContext,
626
- ): Promise<Response> {
627
- if (request.method !== 'POST') {
628
- return new Response('Use POST.', { status: 405, headers: { Allow: 'POST' } });
629
- }
630
- if (!(await sw.auth.fromRequest(request))) {
631
- return Response.json({ error: 'Sign in first.' }, { status: 401 });
632
- }
633
- const body = (await request.json().catch(() => null)) as { groupId?: unknown; email?: unknown } | null;
634
- if (typeof body?.groupId !== 'string' || typeof body.email !== 'string'
635
- || body.email.length > 320 || !/^[^\s@]+@[^\s@]+$/.test(body.email)) {
636
- return Response.json({ error: 'Send groupId and an email address.' }, { status: 400 });
637
- }
638
- const group = await sw.groups.get(request, body.groupId);
639
- if (group.error) {
640
- return Response.json({ error: group.error.message, code: group.error.code }, { status: group.error.status });
641
- }
642
- if (group.data.role !== 'owner' && group.data.role !== 'admin') {
643
- return Response.json({ error: 'Only an owner or admin can add people.' }, { status: 403 });
644
- }
645
-
646
- // One exact lookup for this address; no need to page the user directory to find it.
647
- const { users: [existing] } = await sw.auth.server.listUsers({ emails: [body.email] });
648
- if (existing) {
649
- const added = await sw.groups.add(request, body.groupId, existing.id, 'member');
650
- if (!added.error || added.error.code === 'ALREADY_MEMBER') return Response.json({ ok: true });
651
- if (added.error.code !== 'TARGET_INELIGIBLE') {
652
- return Response.json({ error: added.error.message, code: added.error.code }, { status: added.error.status });
653
- }
654
- }
655
- const invited = await sw.groups.invite(request, body.groupId, {
656
- email: body.email,
657
- role: 'member',
658
- redirect_uri: '/trips',
659
- });
660
- if (invited.error) {
661
- return Response.json({ error: invited.error.message, code: invited.error.code }, { status: invited.error.status });
662
- }
663
- // The same answer whether or not the address had an account.
664
- return Response.json({ ok: true });
665
- }
666
- ```
667
-
668
- ## Methods
669
-
670
- Every method takes the request first and returns `{ data, error }`. Lists are
671
- pages: pass `next_cursor` back as `cursor`; `limit` is 1–100.
672
-
673
- | Call | Who may call it | `data` |
674
- |---|---|---|
675
- | `create(request, { name })` | any signed-in user (becomes `owner`) | the group with its first page of members |
676
- | `list(request, { cursor?, limit? })` | any signed-in user | `{ items, next_cursor, invitations }` |
677
- | `get(request, groupId)` | a member | the group, the caller's `role`, first `members` page (`{ user_id, role, created_at }`, no email), `members_next_cursor` |
678
- | `members(request, groupId, { cursor?, limit? })` | a member | `{ items, next_cursor }` |
679
- | `invite(request, groupId, { email, role, redirect_uri, expires_in? })` | a member who may grant `role`; a current member's address gets `ALREADY_MEMBER` | `{ invite, group, delivery }` |
680
- | `invitations(request, groupId, { cursor?, limit? })` | a member; lists only the pending invitations the caller could revoke (a plain member gets an empty page) | `{ items: [{ invite_id, email, role, invited_by, status, created_at, expires_at, email_state }], next_cursor }` |
681
- | `add(request, groupId, userId, role)` | a member who may grant `role`; the user must have a verified email | `{ user_id, role }` |
682
- | `setRole(request, groupId, userId, role)` | owner or admin, within the rules above | `{ user_id, role }` |
683
- | `remove(request, groupId, userId)` | owner or admin, within the rules above | `{ removed: true }` |
684
- | `leave(request, groupId)` | a member (the last owner can't leave) | `{ left: true }` |
685
- | `delete(request, groupId)` | an owner | `{ deleted: true }` |
686
- | `revokeInvitation(request, inviteId)` | the member who sent it, or a member who may grant its role | `{ revoked: true }` |
687
-
688
- `invite` answers `delivery: 'sent'` or `'pending'`; inviting an address that
689
- already has a pending invitation with the same role answers that invitation with
690
- `delivery: 'not_sent'` and sends nothing (another role: `INVITATION_PENDING`). A delivery that couldn't be
691
- confirmed returns `EMAIL_DELIVERY_UNKNOWN` with the invitation in `error.data`;
692
- check before inviting the same address again.
693
-
694
- ## App-wide roles
695
-
696
- Use emailDomain when staff are people at your domain: the role holds once
697
- the person verifies that address, with no grant code. Use grantableBy when people
698
- who hold the role hand it on (`staff-example`). Use assignedBy: 'server'
699
- when your app decides (an admin promotion, payment, or an invitation it issued).
700
- Require mailbox verification when grant eligibility depends on an email
701
- domain. Your app's code decides who gets the role;
702
- the platform enforces what it may do. An invitation is checked inside the app's
703
- sign-up route, before it answers; a later promotion runs in a POST handler that
704
- authorizes the caller first. Either calls
705
- `await sw.auth.server.setRoles(userId, { add: ['staff'] })`, never a GET/read handler;
706
- see `somewhere docs sw.auth --section server-assigned-app-roles-setroles`.
707
-
708
-
709
- Some roles belong to a person across the whole app, such as staff. Declare them
710
- in the schema options and grant table access with `appRole()` (imported from
711
- `'somewhere/db'` like the other helpers):
712
-
713
- ```ts
714
- schema(
715
- {
716
- refunds: table(
717
- { id: id(), reason: text() },
718
- { scope: appRole({ roles: { read: ['staff', 'auditor'], create: ['staff'], update: ['staff'], delete: [] } }) },
719
- ),
720
- },
721
- { appRoles: { staff: {}, auditor: { grantableBy: ['staff'] } } },
722
- );
723
- ```
724
-
725
- `sw.groups.appRoles.grant(request, userId, role)`, `revoke` and `list` manage
726
- them. An app admin, a user whose auth role is `admin`, can grant any app role.
727
- Holders of a role named in `grantableBy` can grant that role to someone else,
728
- never to themselves. A role with no `grantableBy` is granted only by an app
729
- admin.
730
-
731
- `sw.groups.appRoles.list(request)` returns the signed-in caller's own grants
732
- as `{ data: { items, next_cursor }, error }`. Each item is `{ user_id, role,
733
- granted_by, grant_source, created_at }`; `grant_source` is
734
- `'platform_admin'` for a grant made by an app admin, `'delegation'`
735
- for one made through `grantableBy`, and `'email_domain'` for a role held
736
- through the role's `emailDomain` (then `granted_by` is the domain). `list(request, userId)` reads another
737
- user's grants and only an app admin may call it; anyone else gets
738
- `APP_ROLE_FORBIDDEN`. A page holds 50 grants unless you pass `{ limit }`
739
- (1–100); pass a page's `next_cursor` as `{ cursor }` for the next one.
740
- To serve staff-only data from a function, declare the role on the endpoint;
741
- the platform reads the caller's roles fresh before the handler runs:
742
-
743
- ```ts
744
- // api/staff/report.ts — 403 APP_ROLE_REQUIRED unless the caller holds staff
745
- export const GET = sw.endpoint({
746
- auth: 'required',
747
- roles: ['staff'],
748
- handler: async ({ user }) => ({ staff: user.id, roles: user.appRoles }),
749
- });
750
- ```
751
-
752
- Row access does not need this check: an `appRole()` scope already limits
753
- reads and writes to holders of the role.
754
-
755
- **Staff by email domain.** To make everyone with a verified email at your
756
- company's domain staff, declare the domain on the role:
757
-
758
- ```ts
759
- schema(
760
- { refunds: table({ id: id(), reason: text() }, { scope: appRole({ roles: { read: ['staff'], update: ['staff'] } }) }) },
761
- { appRoles: { staff: { emailDomain: 'example.com' } } },
762
- );
763
- ```
764
-
765
- A signed-in user holds `staff` while their email is verified and its domain is
766
- exactly `example.com`: `ana@example.com` does, `ana@sub.example.com`,
767
- `ana@example.com.evil.io` and an unverified `ana@example.com` do not. The
768
- address is read with each request (a short-lived access token carries it for at
769
- most 60 seconds), so a changed, removed or unverified address loses the role
770
- within 60 seconds. Write the domain in lowercase, without `@`, a wildcard or a
771
- path. Grants of the same role keep working alongside it.
772
- `sw.groups.appRoles.list(request)` shows the role as
773
- `{ role: 'staff', grant_source: 'email_domain', granted_by: 'example.com', created_at: 0 }`.
774
- A role held by email domain cannot be listed in another role's
775
- `grantableBy`: delegation works from explicit grants. Changing the domain within `emailDomain` is an ordinary deploy. Adding or
776
- removing email-domain acquisition changes the role policy; revoke explicit grants
777
- first, then use a role-policy transition. It takes effect within a minute
778
- of that version going live, and the deploy report names who gains or loses the
779
- role. Rolling back or restoring to a version that gives a role to a domain the
780
- live version does not is refused; deploying that version's source again is
781
- accepted, and its report says who gains the role.
782
-
783
- The domain is the only source of that role: there is no per-user exception.
784
- `sw.groups.appRoles.revoke(request, userId, 'staff')` for someone who holds
785
- staff through their address answers
786
- `{ revoked: false, held_by: 'email_domain', domain: 'example.com', message }`
787
- (`revoked: true` with the same `held_by` when an explicit grant was removed
788
- but the address still holds the role). The role ends when the address changes
789
- to another domain or is removed, or when the user is banned. It applies the
790
- same way to `sw.db` from the browser, your functions, background jobs and
791
- your app's MCP tools. Agents are not excluded: an agent is its own app user
792
- and holds a role by email domain through its own account's verified address,
793
- like anyone else; the address of the person who claimed it does not pass to
794
- the agent. A write an app role does not allow is refused with
795
- `POLICY_AUTHORITY_REQUIRED`, whose message says the role can be an explicit
796
- grant or a verified address at the role's `emailDomain`.
797
-
798
- **The first staff member.** Ordinary users and delegated role holders cannot
799
- grant themselves a role. Grant it from your own tooling with your developer
800
- key, once the person has signed up in the app:
801
-
802
- ```text
803
- somewhere auth roles grant ann@example.com staff
804
- app_role_grant({ project_id: "my-app", email: "ann@example.com", role: "staff" })
805
- ```
806
-
807
- Name the person by the exact address they signed up with or by their app user
808
- id. The address does not have to be verified: you vouch for the person (a role
809
- given through `emailDomain` stays verified-only). The grant is the same record
810
- `sw.groups.appRoles` reads, so every declared `appRole()` rule applies to them
811
- at once, and an app admin can see or revoke it from inside the app.
812
- `somewhere auth roles revoke` / `app_role_revoke` takes a role back, whoever
813
- granted it; `somewhere auth roles list` / `app_role_list` shows who holds what.
814
- REST: `POST /v1/auth/app-roles/grant`, `/revoke` and `GET /v1/auth/app-roles`
815
- with an `smt_` key for a project you own or edit (a temporary project's key
816
- must be claimed first, as for editing an app user). Refused: an address nobody
817
- signed up with (`USER_NOT_FOUND`), a banned account (`TARGET_INELIGIBLE`), a
818
- role the live schema does not declare (`ROLE_UNKNOWN`), a project whose deployed
819
- schema declares no `appRoles` (`POLICY_UNAVAILABLE`).
820
-
821
- Both paths work. In-app, when the app itself manages staff: make a signed-up
822
- person an app admin with `auth_user_update({ project_id, user_id, role: 'admin' })`
823
- (`sw.auth`; a public signup always creates an ordinary `user`), and that
824
- admin, signed in, calls an endpoint of yours that runs
825
- `sw.groups.appRoles.grant(request, userId, 'staff')`. An app admin may grant any
826
- declared role to anyone, including themselves; the person receiving a role must
827
- not be banned (`TARGET_INELIGIBLE`). After that, holders of a role named in
828
- another role's `grantableBy` grant that role onward; they cannot grant it to
829
- themselves.
830
-
831
- ## Apps with their own membership table
832
-
833
- `member()` tables keep working as declared; `declared-data` documents them. To
834
- move such an app to built-in groups, map each of its groups, users and roles to
835
- a built-in group and role explicitly. Nothing converts automatically, and no
836
- role is inferred from a membership row.