@sssb/tools 0.2.0 → 0.3.0
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/bin/sssb.js +14 -0
- package/package.json +1 -1
- package/src/app-port.js +3 -3
- package/src/commands/add-app.js +344 -0
- package/src/commands/doctor-checks.js +136 -16
- package/src/commands/doctor-settings.js +583 -0
- package/src/commands/doctor.js +94 -15
- package/src/commands/pin.js +411 -0
- package/src/commands/remove-items.js +191 -0
- package/src/kit.d.ts +6 -0
- package/src/kit.js +11 -0
- package/src/ports.d.ts +1 -1
- package/src/ports.js +5 -4
- package/src/remove-items/code.patch +798 -0
- package/src/remove-items/database.patch +218 -0
- package/src/remove-items/exact-patch.js +122 -0
- package/src/tick/tick.js +12 -10
- package/src/vitest.d.ts +17 -0
- package/src/vitest.js +28 -1
|
@@ -0,0 +1,798 @@
|
|
|
1
|
+
diff --git a/messages/en.json b/messages/en.json
|
|
2
|
+
index 43e5945..15cd515 100644
|
|
3
|
+
--- a/messages/en.json
|
|
4
|
+
+++ b/messages/en.json
|
|
5
|
+
@@ -8,14 +8,5 @@
|
|
6
|
+
"dashboard": {
|
|
7
|
+
"title": "Dashboard",
|
|
8
|
+
"signedInAs": "Signed in as {name} ({role})."
|
|
9
|
+
- },
|
|
10
|
+
- "items": {
|
|
11
|
+
- "title": "Items",
|
|
12
|
+
- "hint": "Items belong to the team you're working in — and never leave your tenant.",
|
|
13
|
+
- "empty": "No items in this team yet.",
|
|
14
|
+
- "addLabel": "New item",
|
|
15
|
+
- "addButton": "Add item",
|
|
16
|
+
- "readOnlyHint": "You have read-only access to items in this team.",
|
|
17
|
+
- "loadMore": "Show older items"
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
diff --git a/messages/es.json b/messages/es.json
|
|
21
|
+
index 07b6b29..7a7ecf8 100644
|
|
22
|
+
--- a/messages/es.json
|
|
23
|
+
+++ b/messages/es.json
|
|
24
|
+
@@ -8,14 +8,5 @@
|
|
25
|
+
"dashboard": {
|
|
26
|
+
"title": "Panel",
|
|
27
|
+
"signedInAs": "Sesión iniciada como {name} ({role})."
|
|
28
|
+
- },
|
|
29
|
+
- "items": {
|
|
30
|
+
- "title": "Elementos",
|
|
31
|
+
- "hint": "Los elementos pertenecen al equipo en el que trabajas y nunca salen de tu organización.",
|
|
32
|
+
- "empty": "Aún no hay elementos en este equipo.",
|
|
33
|
+
- "addLabel": "Nuevo elemento",
|
|
34
|
+
- "addButton": "Añadir elemento",
|
|
35
|
+
- "readOnlyHint": "Tienes acceso de solo lectura a los elementos de este equipo.",
|
|
36
|
+
- "loadMore": "Ver elementos anteriores"
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
diff --git a/playwright.config.ts b/playwright.config.ts
|
|
40
|
+
index a4815c5..e5a31e1 100644
|
|
41
|
+
--- a/playwright.config.ts
|
|
42
|
+
+++ b/playwright.config.ts
|
|
43
|
+
@@ -20,15 +20,15 @@ const BASE_URL = originForApp(__dirname)
|
|
44
|
+
export default defineConfig({
|
|
45
|
+
testDir: './tests/e2e',
|
|
46
|
+
fullyParallel: true,
|
|
47
|
+
- // This app's whole suite is two short specs, so the first always starts against a cold dev server and pays a
|
|
48
|
+
- // full Next compile on every route it touches — sign-in, dashboard, the items route, the Simulator's. The default
|
|
49
|
+
+ // This app's whole suite is one short spec, so it always starts against a cold dev server and pays a
|
|
50
|
+
+ // full Next compile on every route it touches — sign-in, dashboard, the Simulator's. The default
|
|
51
|
+
// 30s is marginal for that (it timed out on the first run and passed on retry), and there is no
|
|
52
|
+
// warm-up pass to inherit, so the budget is raised rather than left to flake.
|
|
53
|
+
timeout: 60_000,
|
|
54
|
+
expect: { timeout: 15_000 },
|
|
55
|
+
forbidOnly: !!process.env['CI'],
|
|
56
|
+
retries: process.env['CI'] ? 2 : 1,
|
|
57
|
+
- // One worker, on CI too — this app's whole suite is two short specs, so parallelism buys little here,
|
|
58
|
+
+ // One worker, on CI too — this app's whole suite is one short spec, so parallelism buys little here,
|
|
59
|
+
// and more workers against one shared world (one `.data` behind one dev server) cost reliability rather than
|
|
60
|
+
// saving time.
|
|
61
|
+
workers: 1,
|
|
62
|
+
diff --git a/src/app-config/abilities.ts b/src/app-config/abilities.ts
|
|
63
|
+
index c69a9ec..851160c 100644
|
|
64
|
+
--- a/src/app-config/abilities.ts
|
|
65
|
+
+++ b/src/app-config/abilities.ts
|
|
66
|
+
@@ -2,12 +2,12 @@ import type { AbilityAction, AbilityActor, AbilitySubject, NonSessionAdministrat
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* The APP's authorization extension (the seam side of @sssb/kit/core/abilities.ts, ADR-0012). The framework
|
|
70
|
+
- * owns the base subjects and the deny-by-default switch; this app registers ONE subject and its rules.
|
|
71
|
+
- * PURE TypeScript, same as core.
|
|
72
|
+
+ * owns the base subjects and the deny-by-default switch; this app registers NO subject of its own yet, which
|
|
73
|
+
+ * is the empty registration. PURE TypeScript, same as core.
|
|
74
|
+
*/
|
|
75
|
+
|
|
76
|
+
-/** The subject types this app adds on top of the framework's BaseSubjectType. */
|
|
77
|
+
-export type AppSubjectType = 'Item'
|
|
78
|
+
+/** The subject types this app adds on top of the framework's BaseSubjectType. None yet: `'Project' | 'Invoice'`. */
|
|
79
|
+
+export type AppSubjectType = never
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* App-specific fields merged into the framework's AbilitySubject (`AbilitySubject = AppSubjectFields & { … }`).
|
|
83
|
+
@@ -45,27 +45,18 @@ export function anchorSubjectExtras(anchor: string): AppSubjectFields {
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* The app's per-subject rules, invoked by @sssb/kit/core/abilities.ts's `default:` case (deny by default).
|
|
87
|
+
- * `sameOrg` is injected by core so "the subject is org-scoped AND its org is the acting org" is
|
|
88
|
+
- * defined once.
|
|
89
|
+
- * - Item: read = sameOrg; create|update|delete = !restricted && sameOrg.
|
|
90
|
+
+ * This app registers no subject, so there is nothing to allow and every app subject is denied. To add one,
|
|
91
|
+
+ * switch on `subject.type` and end in `default: return false`; `sameOrg` is injected by core so "the subject is
|
|
92
|
+
+ * org-scoped AND its org is the acting org" is defined once.
|
|
93
|
+
*/
|
|
94
|
+
export function appAbilityRules(
|
|
95
|
+
actor: AbilityActor,
|
|
96
|
+
action: AbilityAction,
|
|
97
|
+
subject: AbilitySubject,
|
|
98
|
+
- { sameOrg }: { sameOrg: (subject: AbilitySubject) => boolean },
|
|
99
|
+
+ helpers: { sameOrg: (subject: AbilitySubject) => boolean },
|
|
100
|
+
): boolean {
|
|
101
|
+
- switch (subject.type) {
|
|
102
|
+
- case 'Item':
|
|
103
|
+
- if (action === 'read') return sameOrg(subject)
|
|
104
|
+
- if (action === 'create' || action === 'update' || action === 'delete') {
|
|
105
|
+
- return !actor.restricted && sameOrg(subject)
|
|
106
|
+
- }
|
|
107
|
+
- return false
|
|
108
|
+
- default:
|
|
109
|
+
- // Deny by default: an app subject added here without a rule is denied.
|
|
110
|
+
- return false
|
|
111
|
+
- }
|
|
112
|
+
+ void [actor, action, subject, helpers] // no app subject yet: nothing to allow
|
|
113
|
+
+ return false
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
diff --git a/src/app-config/db/rls-proofs.ts b/src/app-config/db/rls-proofs.ts
|
|
118
|
+
index 3f6db15..153b345 100644
|
|
119
|
+
--- a/src/app-config/db/rls-proofs.ts
|
|
120
|
+
+++ b/src/app-config/db/rls-proofs.ts
|
|
121
|
+
@@ -1,9 +1,6 @@
|
|
122
|
+
import { sql } from 'kysely'
|
|
123
|
+
-import { encodeKeysetCursor, parseKeysetCursor } from '@sssb/kit/core/keyset'
|
|
124
|
+
-import { parseDbKeysetCursor } from '@sssb/kit/db/keyset'
|
|
125
|
+
import type { RlsProofSuite } from '@sssb/kit/db/rls-proofs'
|
|
126
|
+
import { runWithTenant } from '@sssb/kit/db/with-tenant'
|
|
127
|
+
-import { listItems } from '@/domain/db/items'
|
|
128
|
+
|
|
129
|
+
/**
|
|
130
|
+
* The APP's tenant-isolation proofs (the seam side of @sssb/kit/db/rls-proofs.ts, ADR-0004 + ADR-0012) —
|
|
131
|
+
@@ -18,7 +15,6 @@ import { listItems } from '@/domain/db/items'
|
|
132
|
+
export const appRlsProofs: RlsProofSuite = async ({
|
|
133
|
+
db,
|
|
134
|
+
appDb,
|
|
135
|
+
- dbPort,
|
|
136
|
+
expect,
|
|
137
|
+
alphaTenantId,
|
|
138
|
+
demoTenantId,
|
|
139
|
+
@@ -82,105 +78,4 @@ export const appRlsProofs: RlsProofSuite = async ({
|
|
140
|
+
deleteRejected = /permission denied/.test(String(error))
|
|
141
|
+
}
|
|
142
|
+
expect(deleteRejected).toBe(true)
|
|
143
|
+
-
|
|
144
|
+
- // ---- the PAGED items list: neither boundary moves when a cursor is involved ----
|
|
145
|
+
- //
|
|
146
|
+
- // The tenant boundary is RLS's, and the framework half proves a cursor cannot cross it. This half proves
|
|
147
|
+
- // the one the app adds on top, the team (an app-level WHERE, not a policy), because that is the one a
|
|
148
|
+
- // hand-rolled pager loses: page one is built from the session, page two from the cursor, and the org
|
|
149
|
+
- // filter is on the first query only. There is no such second query here, and these assertions say so.
|
|
150
|
+
- //
|
|
151
|
+
- // Driven through the PRODUCTION function, `listItems`, the same call GET /api/items makes: a proof of a
|
|
152
|
+
- // copy of the read path proves nothing about the read path.
|
|
153
|
+
-
|
|
154
|
+
- const stamp = Date.now()
|
|
155
|
+
- const [pageOrgP] = await db
|
|
156
|
+
- .insertInto('organizations')
|
|
157
|
+
- .values({ tenant_id: alphaTenantId, slug: `page-p-${stamp}`, name: 'Page Org P' })
|
|
158
|
+
- .returning('id')
|
|
159
|
+
- .execute()
|
|
160
|
+
- const [pageOrgQ] = await db
|
|
161
|
+
- .insertInto('organizations')
|
|
162
|
+
- .values({ tenant_id: alphaTenantId, slug: `page-q-${stamp}`, name: 'Page Org Q' })
|
|
163
|
+
- .returning('id')
|
|
164
|
+
- .execute()
|
|
165
|
+
-
|
|
166
|
+
- // Six items for team P, three for team Q, three for the OTHER TENANT. Every row in a batch shares ONE
|
|
167
|
+
- // created_at, written at MICROSECOND precision: the two properties that break a hand-rolled pager (no
|
|
168
|
+
- // defined position inside a batch; a cursor truncated to a JS millisecond that excludes the batch it
|
|
169
|
+
- // points into).
|
|
170
|
+
- const batch = (tenantId: string, orgId: string, label: string, count: number, at: string) =>
|
|
171
|
+
- Array.from({ length: count }, (_, index) => ({
|
|
172
|
+
- tenant_id: tenantId,
|
|
173
|
+
- org_id: orgId,
|
|
174
|
+
- title: `${label}-${stamp}-${index}`,
|
|
175
|
+
- created_by_user_id: 'proof-user',
|
|
176
|
+
- created_at: at,
|
|
177
|
+
- }))
|
|
178
|
+
- await db
|
|
179
|
+
- .insertInto('items')
|
|
180
|
+
- .values([
|
|
181
|
+
- ...batch(alphaTenantId, pageOrgP!.id, 'KP', 6, '2020-03-04T05:06:07.123456Z'),
|
|
182
|
+
- ...batch(alphaTenantId, pageOrgQ!.id, 'KQ', 3, '2020-03-04T05:06:08.654321Z'),
|
|
183
|
+
- ...batch(demoTenantId, demoOrgId, 'KD', 3, '2020-03-04T05:06:09.987654Z'),
|
|
184
|
+
- ])
|
|
185
|
+
- .execute()
|
|
186
|
+
-
|
|
187
|
+
- /** Walk a team's list to the end through the real read path, and report everything it showed. */
|
|
188
|
+
- const walk = async (tenantId: string, orgId: string, limit: number) => {
|
|
189
|
+
- const seen: string[] = []
|
|
190
|
+
- let cursor: string | null = null
|
|
191
|
+
- for (let guard = 0; guard < 50; guard++) {
|
|
192
|
+
- const parsed = parseDbKeysetCursor(cursor)
|
|
193
|
+
- expect(parsed.kind === 'invalid').toBe(false)
|
|
194
|
+
- const page = await listItems(dbPort, tenantId, orgId, { after: parsed.position ?? null, limit })
|
|
195
|
+
- seen.push(...page.items.map((item) => item.title))
|
|
196
|
+
- if (page.nextCursor === null) return seen
|
|
197
|
+
- cursor = page.nextCursor
|
|
198
|
+
- }
|
|
199
|
+
- throw new Error('keyset proof: the items walk did not terminate')
|
|
200
|
+
- }
|
|
201
|
+
-
|
|
202
|
+
- // (a) a full walk at a page size that cuts through the batch shows team P's six, once each, and no
|
|
203
|
+
- // sight of team Q's or of the other tenant's.
|
|
204
|
+
- const walkedP = await walk(alphaTenantId, pageOrgP!.id, 2)
|
|
205
|
+
- expect(walkedP.length).toBe(6)
|
|
206
|
+
- expect(new Set(walkedP).size).toBe(6)
|
|
207
|
+
- expect(walkedP.every((title) => title.startsWith(`KP-${stamp}-`))).toBe(true)
|
|
208
|
+
-
|
|
209
|
+
- // (b) THE ATTACK on the team boundary: a cursor minted while paging team Q's list, handed to team P's.
|
|
210
|
+
- // The two teams share a tenant, so RLS is not what stops this; the org filter is, and it is re-applied
|
|
211
|
+
- // because the pager rebuilds the whole query on every page rather than resuming one.
|
|
212
|
+
- const teamQPage = await listItems(dbPort, alphaTenantId, pageOrgQ!.id, { after: null, limit: 1 })
|
|
213
|
+
- expect(teamQPage.nextCursor !== null).toBe(true)
|
|
214
|
+
- const crossTeam = await listItems(dbPort, alphaTenantId, pageOrgP!.id, {
|
|
215
|
+
- after: parseDbKeysetCursor(teamQPage.nextCursor).position ?? null,
|
|
216
|
+
- limit: 50,
|
|
217
|
+
- })
|
|
218
|
+
- expect(crossTeam.items.length).toBe(6)
|
|
219
|
+
- expect(crossTeam.items.every((item) => item.title.startsWith(`KP-${stamp}-`))).toBe(true)
|
|
220
|
+
-
|
|
221
|
+
- // (c) the same across TENANTS: a cursor minted in the other tenant, replayed against alpha's list. The
|
|
222
|
+
- // tenant comes from withTenant, which the pager opens from the caller's session, never from the cursor.
|
|
223
|
+
- const demoList = await listItems(dbPort, demoTenantId, demoOrgId, { after: null, limit: 1 })
|
|
224
|
+
- expect(demoList.nextCursor !== null).toBe(true)
|
|
225
|
+
- const crossTenant = await listItems(dbPort, alphaTenantId, pageOrgP!.id, {
|
|
226
|
+
- after: parseDbKeysetCursor(demoList.nextCursor).position ?? null,
|
|
227
|
+
- limit: 50,
|
|
228
|
+
- })
|
|
229
|
+
- expect(crossTenant.items.length).toBe(6)
|
|
230
|
+
- expect(crossTenant.items.every((item) => item.title.startsWith(`KP-${stamp}-`))).toBe(true)
|
|
231
|
+
-
|
|
232
|
+
- // (d) a cursor crafted to name a REAL item of the other team, at a timestamp that opens the predicate
|
|
233
|
+
- // as wide as it goes. Still exactly team P's six rows.
|
|
234
|
+
- const teamQFirst = teamQPage.items[0]
|
|
235
|
+
- expect(teamQFirst !== undefined).toBe(true)
|
|
236
|
+
- const crafted = await listItems(dbPort, alphaTenantId, pageOrgP!.id, {
|
|
237
|
+
- after:
|
|
238
|
+
- parseKeysetCursor(encodeKeysetCursor({ at: '2999-01-01T00:00:00.000000Z', id: teamQFirst!.id })).position ??
|
|
239
|
+
- null,
|
|
240
|
+
- limit: 50,
|
|
241
|
+
- })
|
|
242
|
+
- expect(crafted.items.length).toBe(6)
|
|
243
|
+
- expect(crafted.items.every((item) => item.title.startsWith(`KP-${stamp}-`))).toBe(true)
|
|
244
|
+
}
|
|
245
|
+
diff --git a/src/app-config/messages.ts b/src/app-config/messages.ts
|
|
246
|
+
index 117cbdc..6539ae5 100644
|
|
247
|
+
--- a/src/app-config/messages.ts
|
|
248
|
+
+++ b/src/app-config/messages.ts
|
|
249
|
+
@@ -7,7 +7,7 @@ import type { MessageTree } from '@sssb/kit/i18n/messages'
|
|
250
|
+
* (disjoint + exhaustive), enforced by the conformance suite's `i18n-partition` check (@sssb/kit/testing), which
|
|
251
|
+
* this app runs against these registrations from src/sssb.conformance.test.ts.
|
|
252
|
+
*/
|
|
253
|
+
-export const APP_NAMESPACES = ['welcome', 'dashboard', 'items'] as const
|
|
254
|
+
+export const APP_NAMESPACES = ['welcome', 'dashboard'] as const
|
|
255
|
+
|
|
256
|
+
/**
|
|
257
|
+
* The app's catalog for one locale. Framework code (the next-intl request config, the parity tests)
|
|
258
|
+
diff --git a/src/app/[locale]/(protected)/dashboard/dashboard-glue.tsx b/src/app/[locale]/(protected)/dashboard/dashboard-glue.tsx
|
|
259
|
+
index 5fdea5a..874f935 100644
|
|
260
|
+
--- a/src/app/[locale]/(protected)/dashboard/dashboard-glue.tsx
|
|
261
|
+
+++ b/src/app/[locale]/(protected)/dashboard/dashboard-glue.tsx
|
|
262
|
+
@@ -1,61 +1,7 @@
|
|
263
|
+
'use client'
|
|
264
|
+
|
|
265
|
+
-import { useEffect, useState } from 'react'
|
|
266
|
+
import { DashboardScreen, type DashboardUser } from '@/components/dashboard-screen'
|
|
267
|
+
-import { ItemsCard, type Item } from '@/components/items-card'
|
|
268
|
+
|
|
269
|
+
-/** One page of items; no cursor is the first page. Null when the request failed, so a flaky network is a page that does not grow, not an unhandled rejection. */
|
|
270
|
+
-async function fetchItemsPage(after: string | null): Promise<{ items: Item[]; nextCursor: string | null } | null> {
|
|
271
|
+
- try {
|
|
272
|
+
- const response = await fetch(after === null ? '/api/items' : `/api/items?cursor=${encodeURIComponent(after)}`)
|
|
273
|
+
- return response.ok ? ((await response.json()) as { items: Item[]; nextCursor: string | null }) : null
|
|
274
|
+
- } catch {
|
|
275
|
+
- return null
|
|
276
|
+
- }
|
|
277
|
+
-}
|
|
278
|
+
-
|
|
279
|
+
-export function DashboardGlue({ user, canCreateItem }: { user: DashboardUser; canCreateItem: boolean }) {
|
|
280
|
+
- const [items, setItems] = useState<Item[]>([])
|
|
281
|
+
- // The cursor for the NEXT page, or null at the end. The glue owns fetching; the card stays a plain list.
|
|
282
|
+
- const [cursor, setCursor] = useState<string | null>(null)
|
|
283
|
+
-
|
|
284
|
+
- useEffect(() => {
|
|
285
|
+
- // Sets state only once the response lands — the legitimate "sync with an external system"
|
|
286
|
+
- // case, so the react-hooks set-state-in-effect rule does not fire here.
|
|
287
|
+
- void fetchItemsPage(null).then((page) => {
|
|
288
|
+
- if (!page) return
|
|
289
|
+
- setItems(page.items)
|
|
290
|
+
- setCursor(page.nextCursor)
|
|
291
|
+
- })
|
|
292
|
+
- }, [])
|
|
293
|
+
-
|
|
294
|
+
- /** "Show older items" APPENDS the next page, so what the reader has scrolled past stays put. */
|
|
295
|
+
- async function loadMore() {
|
|
296
|
+
- const page = await fetchItemsPage(cursor)
|
|
297
|
+
- if (!page) return
|
|
298
|
+
- setItems((previous) => [...previous, ...page.items])
|
|
299
|
+
- setCursor(page.nextCursor)
|
|
300
|
+
- }
|
|
301
|
+
-
|
|
302
|
+
- return (
|
|
303
|
+
- <DashboardScreen user={user}>
|
|
304
|
+
- <ItemsCard
|
|
305
|
+
- items={items}
|
|
306
|
+
- canCreate={canCreateItem}
|
|
307
|
+
- hasMore={cursor !== null}
|
|
308
|
+
- onLoadMore={loadMore}
|
|
309
|
+
- onAdd={async (title) => {
|
|
310
|
+
- const response = await fetch('/api/items', {
|
|
311
|
+
- method: 'POST',
|
|
312
|
+
- headers: { 'content-type': 'application/json' },
|
|
313
|
+
- body: JSON.stringify({ title }),
|
|
314
|
+
- })
|
|
315
|
+
- if (response.ok) {
|
|
316
|
+
- const { item } = (await response.json()) as { item: Item }
|
|
317
|
+
- setItems((prev) => [item, ...prev])
|
|
318
|
+
- }
|
|
319
|
+
- }}
|
|
320
|
+
- />
|
|
321
|
+
- </DashboardScreen>
|
|
322
|
+
- )
|
|
323
|
+
+export function DashboardGlue({ user }: { user: DashboardUser }) {
|
|
324
|
+
+ return <DashboardScreen user={user} />
|
|
325
|
+
}
|
|
326
|
+
diff --git a/src/app/[locale]/(protected)/dashboard/page.tsx b/src/app/[locale]/(protected)/dashboard/page.tsx
|
|
327
|
+
index 1794523..9fba9eb 100644
|
|
328
|
+
--- a/src/app/[locale]/(protected)/dashboard/page.tsx
|
|
329
|
+
+++ b/src/app/[locale]/(protected)/dashboard/page.tsx
|
|
330
|
+
@@ -1,7 +1,6 @@
|
|
331
|
+
import { setRequestLocale } from 'next-intl/server'
|
|
332
|
+
import { redirect } from 'next/navigation'
|
|
333
|
+
import { auth } from '@sssb/kit/adapters/index'
|
|
334
|
+
-import { canInActiveOrg } from '@sssb/kit/authz/authorize'
|
|
335
|
+
import { DashboardGlue } from './dashboard-glue'
|
|
336
|
+
|
|
337
|
+
export default async function DashboardPage({ params }: { params: Promise<{ locale: string }> }) {
|
|
338
|
+
@@ -9,13 +8,7 @@ export default async function DashboardPage({ params }: { params: Promise<{ loca
|
|
339
|
+
setRequestLocale(locale)
|
|
340
|
+
const user = await auth.getCurrentUser()
|
|
341
|
+
if (!user) redirect(`/${locale}${auth.signInPath()}`)
|
|
342
|
+
-
|
|
343
|
+
- // Reflect the server-side authorization in the UI: restricted members get a read-only card. The
|
|
344
|
+
- // POST route re-checks with authorize(), so this is presentation, never enforcement.
|
|
345
|
+
- return (
|
|
346
|
+
- <DashboardGlue
|
|
347
|
+
- user={{ name: user.name, role: user.role }}
|
|
348
|
+
- canCreateItem={canInActiveOrg(user, 'create', 'Item')}
|
|
349
|
+
- />
|
|
350
|
+
- )
|
|
351
|
+
+ // Presentation, never enforcement: reflect what the user may do with `canInActiveOrg(user, action, subject)`
|
|
352
|
+
+ // from @sssb/kit/authz/authorize, and re-check with `authorize()` in every route that writes.
|
|
353
|
+
+ return <DashboardGlue user={{ name: user.name, role: user.role }} />
|
|
354
|
+
}
|
|
355
|
+
diff --git a/src/app/api/items/route.ts b/src/app/api/items/route.ts
|
|
356
|
+
deleted file mode 100644
|
|
357
|
+
index cb2d480..0000000
|
|
358
|
+
--- a/src/app/api/items/route.ts
|
|
359
|
+
+++ /dev/null
|
|
360
|
+
@@ -1,59 +0,0 @@
|
|
361
|
+
-import { auth, db } from '@sssb/kit/adapters/index'
|
|
362
|
+
-import { authorize } from '@sssb/kit/authz/authorize'
|
|
363
|
+
-import { clampKeysetLimit } from '@sssb/kit/core/keyset'
|
|
364
|
+
-import { parseDbKeysetCursor } from '@sssb/kit/db/keyset'
|
|
365
|
+
-import { orgIdForSlug } from '@sssb/kit/db/org-lookup'
|
|
366
|
+
-import { tenantIdForSlug } from '@sssb/kit/db/tenant-lookup'
|
|
367
|
+
-import { listItems } from '@/domain/db/items'
|
|
368
|
+
-import { withPortErrors } from '../respond'
|
|
369
|
+
-
|
|
370
|
+
-/**
|
|
371
|
+
- * The app's only product route. Items are tenant-scoped by RLS (the hostile-isolation boundary) AND
|
|
372
|
+
- * filtered to the active org (the team boundary — an app-level WHERE, since org membership is enforced
|
|
373
|
+
- * at the auth port; ADR-0004). Every query runs inside withTenant.
|
|
374
|
+
- *
|
|
375
|
+
- * GET lists ONE PAGE (`?cursor=<opaque>&limit=<n>`); both parameters are untrusted input. An unreadable
|
|
376
|
+
- * cursor is a 400, never a silent first page, and the page size is clamped on the server: the query
|
|
377
|
+
- * string may ask, it does not decide. A cursor carries no scope, since the tenant and the org are
|
|
378
|
+
- * resolved from the session on every page.
|
|
379
|
+
- */
|
|
380
|
+
-export async function GET(request: Request): Promise<Response> {
|
|
381
|
+
- return withPortErrors(async () => {
|
|
382
|
+
- const user = await auth.requireUser()
|
|
383
|
+
- const params = new URL(request.url).searchParams
|
|
384
|
+
- const cursor = parseDbKeysetCursor(params.get('cursor'))
|
|
385
|
+
- if (cursor.kind === 'invalid') return Response.json({ error: 'invalid-cursor' }, { status: 400 })
|
|
386
|
+
- const tenantId = await tenantIdForSlug(db, user.tenantSlug)
|
|
387
|
+
- if (!tenantId) return Response.json({ error: 'unknown tenant' }, { status: 404 })
|
|
388
|
+
- const orgId = await orgIdForSlug(db, tenantId, user.orgSlug)
|
|
389
|
+
- if (!orgId) return Response.json({ error: 'unknown org' }, { status: 404 })
|
|
390
|
+
- const { items, nextCursor } = await listItems(db, tenantId, orgId, {
|
|
391
|
+
- after: cursor.position ?? null,
|
|
392
|
+
- limit: clampKeysetLimit(params.get('limit')),
|
|
393
|
+
- })
|
|
394
|
+
- return Response.json({ items, nextCursor })
|
|
395
|
+
- })
|
|
396
|
+
-}
|
|
397
|
+
-
|
|
398
|
+
-export async function POST(request: Request): Promise<Response> {
|
|
399
|
+
- return withPortErrors(async () => {
|
|
400
|
+
- const user = await auth.requireUser()
|
|
401
|
+
- const { title } = (await request.json()) as { title: string }
|
|
402
|
+
- if (!title?.trim()) return Response.json({ error: 'empty item' }, { status: 400 })
|
|
403
|
+
- const tenantId = await tenantIdForSlug(db, user.tenantSlug)
|
|
404
|
+
- if (!tenantId) return Response.json({ error: 'unknown tenant' }, { status: 404 })
|
|
405
|
+
- const orgId = await orgIdForSlug(db, tenantId, user.orgSlug)
|
|
406
|
+
- if (!orgId) return Response.json({ error: 'unknown org' }, { status: 404 })
|
|
407
|
+
- // The authorization choke point: restricted members may read items but not author them.
|
|
408
|
+
- // Throws ForbiddenError → 403 via withPortErrors.
|
|
409
|
+
- authorize(user, orgId, 'create', { type: 'Item', orgId })
|
|
410
|
+
- const item = await db.withTenant(tenantId, (trx) =>
|
|
411
|
+
- trx
|
|
412
|
+
- .insertInto('items')
|
|
413
|
+
- .values({ tenant_id: tenantId, org_id: orgId, title: title.trim(), created_by_user_id: user.id })
|
|
414
|
+
- .returning(['id', 'title'])
|
|
415
|
+
- .executeTakeFirstOrThrow(),
|
|
416
|
+
- )
|
|
417
|
+
- return Response.json({ item })
|
|
418
|
+
- })
|
|
419
|
+
-}
|
|
420
|
+
diff --git a/src/components/dashboard-screen.tsx b/src/components/dashboard-screen.tsx
|
|
421
|
+
index 42b10b7..20ada9e 100644
|
|
422
|
+
--- a/src/components/dashboard-screen.tsx
|
|
423
|
+
+++ b/src/components/dashboard-screen.tsx
|
|
424
|
+
@@ -9,8 +9,8 @@ export interface DashboardUser {
|
|
425
|
+
role: string
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
-/** Signed-in landing screen. Router-agnostic (ADR-0006); the cards are slotted in as children. */
|
|
429
|
+
-export function DashboardScreen({ user, children }: { user: DashboardUser; children: ReactNode }) {
|
|
430
|
+
+/** Signed-in landing screen. Router-agnostic (ADR-0006); an app's cards are slotted in as children. */
|
|
431
|
+
+export function DashboardScreen({ user, children }: { user: DashboardUser; children?: ReactNode }) {
|
|
432
|
+
const t = useTranslations('dashboard')
|
|
433
|
+
return (
|
|
434
|
+
<Container component="main" size="sm" py="xl">
|
|
435
|
+
diff --git a/src/components/items-card.tsx b/src/components/items-card.tsx
|
|
436
|
+
deleted file mode 100644
|
|
437
|
+
index 9a501ae..0000000
|
|
438
|
+
--- a/src/components/items-card.tsx
|
|
439
|
+
+++ /dev/null
|
|
440
|
+
@@ -1,106 +0,0 @@
|
|
441
|
+
-'use client'
|
|
442
|
+
-
|
|
443
|
+
-import { Button, Card, Group, Stack, Text, TextInput, Title } from '@mantine/core'
|
|
444
|
+
-import { useTranslations } from 'next-intl'
|
|
445
|
+
-import { useState } from 'react'
|
|
446
|
+
-
|
|
447
|
+
-export interface Item {
|
|
448
|
+
- id: string
|
|
449
|
+
- title: string
|
|
450
|
+
-}
|
|
451
|
+
-
|
|
452
|
+
-/**
|
|
453
|
+
- * The app's ONE screen component: a list of the active team's items with an add box. Router-agnostic
|
|
454
|
+
- * (ADR-0006) so the Next route and the `file://` static twin render the same component; `canCreate`
|
|
455
|
+
- * comes from the same pure ability model on both sides.
|
|
456
|
+
- */
|
|
457
|
+
-export function ItemsCard({
|
|
458
|
+
- items,
|
|
459
|
+
- onAdd,
|
|
460
|
+
- canCreate = true,
|
|
461
|
+
- hasMore = false,
|
|
462
|
+
- onLoadMore,
|
|
463
|
+
-}: {
|
|
464
|
+
- items: Item[]
|
|
465
|
+
- onAdd: (title: string) => Promise<void>
|
|
466
|
+
- /** When false (restricted members), the add affordance is disabled and a read-only hint shows. */
|
|
467
|
+
- canCreate?: boolean
|
|
468
|
+
- /** True while the server has older items to show. The list is paged (`@sssb/kit/db/keyset`). */
|
|
469
|
+
- hasMore?: boolean
|
|
470
|
+
- /** Appends the next page to `items`; the card shows "load more" only when both this and `hasMore` are set. */
|
|
471
|
+
- onLoadMore?: () => Promise<void>
|
|
472
|
+
-}) {
|
|
473
|
+
- const t = useTranslations('items')
|
|
474
|
+
- const [draft, setDraft] = useState('')
|
|
475
|
+
- const [busy, setBusy] = useState(false)
|
|
476
|
+
- const [loadingMore, setLoadingMore] = useState(false)
|
|
477
|
+
-
|
|
478
|
+
- return (
|
|
479
|
+
- <Card withBorder padding="lg" radius="md" data-testid="items-card">
|
|
480
|
+
- <Stack gap="sm">
|
|
481
|
+
- <Title order={2} size="h3">
|
|
482
|
+
- {t('title')}
|
|
483
|
+
- </Title>
|
|
484
|
+
- <Text size="sm" c="gray.7">
|
|
485
|
+
- {t('hint')}
|
|
486
|
+
- </Text>
|
|
487
|
+
- {items.length === 0 ? (
|
|
488
|
+
- <Text c="gray.7" data-testid="items-empty">
|
|
489
|
+
- {t('empty')}
|
|
490
|
+
- </Text>
|
|
491
|
+
- ) : (
|
|
492
|
+
- <Stack gap={4} data-testid="items-list">
|
|
493
|
+
- {items.map((item) => (
|
|
494
|
+
- <Text key={item.id} data-testid="item-row">
|
|
495
|
+
- {item.title}
|
|
496
|
+
- </Text>
|
|
497
|
+
- ))}
|
|
498
|
+
- </Stack>
|
|
499
|
+
- )}
|
|
500
|
+
- {hasMore && onLoadMore ? (
|
|
501
|
+
- <Button
|
|
502
|
+
- size="compact-sm"
|
|
503
|
+
- variant="default"
|
|
504
|
+
- loading={loadingMore}
|
|
505
|
+
- data-testid="items-load-more"
|
|
506
|
+
- style={{ alignSelf: 'flex-start' }}
|
|
507
|
+
- onClick={() => {
|
|
508
|
+
- setLoadingMore(true)
|
|
509
|
+
- onLoadMore().finally(() => setLoadingMore(false))
|
|
510
|
+
- }}
|
|
511
|
+
- >
|
|
512
|
+
- {t('loadMore')}
|
|
513
|
+
- </Button>
|
|
514
|
+
- ) : null}
|
|
515
|
+
- <Group align="end" gap="sm">
|
|
516
|
+
- <TextInput
|
|
517
|
+
- label={t('addLabel')}
|
|
518
|
+
- flex={1}
|
|
519
|
+
- value={draft}
|
|
520
|
+
- disabled={!canCreate}
|
|
521
|
+
- data-testid="item-input"
|
|
522
|
+
- onChange={(event) => setDraft(event.currentTarget.value)}
|
|
523
|
+
- />
|
|
524
|
+
- <Button
|
|
525
|
+
- loading={busy}
|
|
526
|
+
- disabled={!canCreate || !draft.trim()}
|
|
527
|
+
- data-testid="item-add"
|
|
528
|
+
- onClick={() => {
|
|
529
|
+
- setBusy(true)
|
|
530
|
+
- onAdd(draft.trim())
|
|
531
|
+
- .then(() => setDraft(''))
|
|
532
|
+
- .finally(() => setBusy(false))
|
|
533
|
+
- }}
|
|
534
|
+
- >
|
|
535
|
+
- {t('addButton')}
|
|
536
|
+
- </Button>
|
|
537
|
+
- </Group>
|
|
538
|
+
- {!canCreate ? (
|
|
539
|
+
- <Text size="sm" c="gray.7" data-testid="items-readonly-hint">
|
|
540
|
+
- {t('readOnlyHint')}
|
|
541
|
+
- </Text>
|
|
542
|
+
- ) : null}
|
|
543
|
+
- </Stack>
|
|
544
|
+
- </Card>
|
|
545
|
+
- )
|
|
546
|
+
-}
|
|
547
|
+
diff --git a/src/demo-static/app.tsx b/src/demo-static/app.tsx
|
|
548
|
+
index 8d963b9..dca74e9 100644
|
|
549
|
+
--- a/src/demo-static/app.tsx
|
|
550
|
+
+++ b/src/demo-static/app.tsx
|
|
551
|
+
@@ -1,14 +1,9 @@
|
|
552
|
+
-import { useState } from 'react'
|
|
553
|
+
import { useTranslations } from 'next-intl'
|
|
554
|
+
-import { defineAbilitiesFor } from '@sssb/kit/core/abilities'
|
|
555
|
+
-import { isRestricted } from '@sssb/kit/core/roles'
|
|
556
|
+
import type { Locale } from '@sssb/kit/core/locale'
|
|
557
|
+
import { DemoShell } from '@sssb/kit/demo-static/shell'
|
|
558
|
+
import { useDemoWorld } from '@sssb/kit/demo-static/world'
|
|
559
|
+
import type { SeedPerson } from '@/seed'
|
|
560
|
+
-import { staffOrgSlug } from '@/app-config/abilities'
|
|
561
|
+
import { DashboardScreen } from '@/components/dashboard-screen'
|
|
562
|
+
-import { ItemsCard, type Item } from '@/components/items-card'
|
|
563
|
+
import { WelcomeScreen } from '@/components/welcome-screen'
|
|
564
|
+
|
|
565
|
+
/**
|
|
566
|
+
@@ -16,50 +11,19 @@ import { WelcomeScreen } from '@/components/welcome-screen'
|
|
567
|
+
* take the framework's simulated world (@sssb/kit/demo-static/world), add THIS app's own rows, hand the
|
|
568
|
+
* shell its screens, and get out of the way (ADR-0006, ADR-0012).
|
|
569
|
+
*
|
|
570
|
+
- * This is what the twin costs an app that owns ONE table: a row type, a piece of state, an ability
|
|
571
|
+
- * check and a card. Everything else on screen — routing, sign-in, the people, mail, jobs, schedules,
|
|
572
|
+
- * webhooks, notifications, agreements, audit and the whole Simulator panel — is the package's.
|
|
573
|
+
+ * This app has no rows of its own yet, so it adds none: everything on screen — routing, sign-in, the people,
|
|
574
|
+
+ * mail, jobs, schedules, webhooks, notifications, agreements, audit and the whole Simulator panel — is the
|
|
575
|
+
+ * package's. An app that owns a table adds, for each: a row type, a piece of state (reset through
|
|
576
|
+
+ * `useDemoWorld({ onReset })`), an ability check (`defineAbilitiesFor` from @sssb/kit/core/abilities, the
|
|
577
|
+
+ * pure model the real server runs) and a card in `renderDashboard`.
|
|
578
|
+
*/
|
|
579
|
+
|
|
580
|
+
-/** In-memory twin of an `items` row — tenant + org scoped, so the static dashboard shows only the
|
|
581
|
+
- * active team's items and gates create by the same pure ability model the real server runs. */
|
|
582
|
+
-interface DemoItem extends Item {
|
|
583
|
+
- tenantSlug: string
|
|
584
|
+
- orgSlug: string
|
|
585
|
+
-}
|
|
586
|
+
-
|
|
587
|
+
export function StaticDemoApp({ locale, onLocaleChange }: { locale: Locale; onLocaleChange: (l: Locale) => void }) {
|
|
588
|
+
const t = useTranslations('welcome')
|
|
589
|
+
- const [items, setItems] = useState<DemoItem[]>([])
|
|
590
|
+
- const world = useDemoWorld({ onReset: () => setItems([]) })
|
|
591
|
+
+ const world = useDemoWorld()
|
|
592
|
+
|
|
593
|
+
function renderDashboard(person: SeedPerson) {
|
|
594
|
+
- const { tenant, activeOrgSlug } = world
|
|
595
|
+
- // Same pure ability the real server runs — a restricted person gets a read-only card here too.
|
|
596
|
+
- const ability = defineAbilitiesFor({
|
|
597
|
+
- // The static shell's signed-in person IS a session, and only a stated session wields manage-all.
|
|
598
|
+
- credential: { kind: 'session', id: null },
|
|
599
|
+
- userId: person.id,
|
|
600
|
+
- role: world.roleInOrg(person, activeOrgSlug),
|
|
601
|
+
- restricted: isRestricted(person.restricted, world.roleInOrg(person, activeOrgSlug)),
|
|
602
|
+
- activeOrgId: activeOrgSlug,
|
|
603
|
+
- // Acting AS the operator org activates manage-all, exactly like abilityActorFromUser does
|
|
604
|
+
- // server-side — genuine parity, no degrade.
|
|
605
|
+
- manageAll: activeOrgSlug === staffOrgSlug,
|
|
606
|
+
- })
|
|
607
|
+
-
|
|
608
|
+
- return (
|
|
609
|
+
- <DashboardScreen user={{ name: world.name, role: world.roleInOrg(person, activeOrgSlug) }}>
|
|
610
|
+
- <ItemsCard
|
|
611
|
+
- items={items.filter((i) => i.tenantSlug === tenant.slug && i.orgSlug === activeOrgSlug)}
|
|
612
|
+
- canCreate={ability.can('create', { type: 'Item', orgId: activeOrgSlug })}
|
|
613
|
+
- onAdd={async (title) => {
|
|
614
|
+
- const id = crypto.randomUUID()
|
|
615
|
+
- setItems((prev) => [{ id, title, tenantSlug: tenant.slug, orgSlug: activeOrgSlug }, ...prev])
|
|
616
|
+
- }}
|
|
617
|
+
- />
|
|
618
|
+
- </DashboardScreen>
|
|
619
|
+
- )
|
|
620
|
+
+ return <DashboardScreen user={{ name: world.name, role: world.roleInOrg(person, world.activeOrgSlug) }} />
|
|
621
|
+
}
|
|
622
|
+
|
|
623
|
+
return (
|
|
624
|
+
diff --git a/src/domain/db/items.ts b/src/domain/db/items.ts
|
|
625
|
+
deleted file mode 100644
|
|
626
|
+
index 813980d..0000000
|
|
627
|
+
--- a/src/domain/db/items.ts
|
|
628
|
+
+++ /dev/null
|
|
629
|
+
@@ -1,37 +0,0 @@
|
|
630
|
+
-import type { KeysetPosition } from '@sssb/kit/core/keyset'
|
|
631
|
+
-import { keysetPage } from '@sssb/kit/db/keyset'
|
|
632
|
+
-import type { DbPort } from '@sssb/kit/ports/db'
|
|
633
|
+
-
|
|
634
|
+
-/** An item as its owning team sees it in the list. */
|
|
635
|
+
-interface ItemView {
|
|
636
|
+
- id: string
|
|
637
|
+
- title: string
|
|
638
|
+
-}
|
|
639
|
+
-
|
|
640
|
+
-/** One page of a team's items, plus the token that fetches the next one (null at the end). */
|
|
641
|
+
-export interface ItemPage {
|
|
642
|
+
- items: ItemView[]
|
|
643
|
+
- nextCursor: string | null
|
|
644
|
+
-}
|
|
645
|
+
-
|
|
646
|
+
-/**
|
|
647
|
+
- * Lists ONE PAGE of a team's items, newest first. Tenant-scoped by RLS AND filtered to the org: the same
|
|
648
|
+
- * two boundaries as every list (ADR-0004).
|
|
649
|
+
- *
|
|
650
|
+
- * A list that can grow pages through the framework primitive (`@sssb/kit/db/keyset`), never a hand-rolled
|
|
651
|
+
- * `LIMIT`/`OFFSET`. The callback is THE query, run once per page with the cursor added as one more
|
|
652
|
+
- * conjunct, so page 7 is scoped by construction: there is no second code path that could forget the org.
|
|
653
|
+
- * The order is fixed here (the primitive's default, `created_at` then `id`, newest first), never taken
|
|
654
|
+
- * from a request, because a cursor does not say which column it was minted under.
|
|
655
|
+
- */
|
|
656
|
+
-export async function listItems(
|
|
657
|
+
- db: DbPort,
|
|
658
|
+
- tenantId: string,
|
|
659
|
+
- orgId: string,
|
|
660
|
+
- page: { after: KeysetPosition | null; limit: number },
|
|
661
|
+
-): Promise<ItemPage> {
|
|
662
|
+
- const result = await keysetPage(db, { tenantId, after: page.after, limit: page.limit }, (trx) =>
|
|
663
|
+
- trx.selectFrom('items').select(['id', 'title']).where('org_id', '=', orgId),
|
|
664
|
+
- )
|
|
665
|
+
- return { items: result.rows.map(({ id, title }) => ({ id, title })), nextCursor: result.nextCursor }
|
|
666
|
+
-}
|
|
667
|
+
diff --git a/tests/demo-static/static-shell.spec.ts b/tests/demo-static/static-shell.spec.ts
|
|
668
|
+
index d859cdf..dad4e92 100644
|
|
669
|
+
--- a/tests/demo-static/static-shell.spec.ts
|
|
670
|
+
+++ b/tests/demo-static/static-shell.spec.ts
|
|
671
|
+
@@ -4,7 +4,7 @@ import { welcome } from '../catalog'
|
|
672
|
+
|
|
673
|
+
const indexUrl = `file://${path.resolve(__dirname, '../../dist-demo/index.html')}`
|
|
674
|
+
|
|
675
|
+
-test('the static shell signs in and lists an item, with the framework panel intact', async ({ page }) => {
|
|
676
|
+
+test('the static shell signs in, with the framework panel intact', async ({ page }) => {
|
|
677
|
+
await page.goto(indexUrl)
|
|
678
|
+
// Asserted against the catalog, not the product name — `pnpm create @sssb` renames the app, and this
|
|
679
|
+
// spec is the first thing that would have broken if it hard-coded the title.
|
|
680
|
+
@@ -14,10 +14,6 @@ test('the static shell signs in and lists an item, with the framework panel inta
|
|
681
|
+
await page.getByTestId('person-person-owner').click()
|
|
682
|
+
await expect(page.getByTestId('signed-in-as')).toContainText('Nadia Owner')
|
|
683
|
+
|
|
684
|
+
- await page.getByTestId('item-input').fill('write the first item')
|
|
685
|
+
- await page.getByTestId('item-add').click()
|
|
686
|
+
- await expect(page.getByTestId('items-list')).toContainText('write the first item')
|
|
687
|
+
-
|
|
688
|
+
// The whole Simulator panel comes from the package: an app that registers no tabs still gets the
|
|
689
|
+
// framework's, and switching people still works.
|
|
690
|
+
await page.getByTestId('simulator-pill').click()
|
|
691
|
+
diff --git a/tests/e2e/items.spec.ts b/tests/e2e/items.spec.ts
|
|
692
|
+
deleted file mode 100644
|
|
693
|
+
index 6c6e8cb..0000000
|
|
694
|
+
--- a/tests/e2e/items.spec.ts
|
|
695
|
+
+++ /dev/null
|
|
696
|
+
@@ -1,102 +0,0 @@
|
|
697
|
+
-import { expect, test, type Page } from '@playwright/test'
|
|
698
|
+
-
|
|
699
|
+
-/**
|
|
700
|
+
- * The claim this app exists to prove: an item written in one tenant is invisible from the other, through the
|
|
701
|
+
- * entire stack (UI → route → withTenant → RLS on pglite).
|
|
702
|
+
- *
|
|
703
|
+
- * Crossing tenants is done the way a real user would, not through the Simulator panel: sign out, sign in
|
|
704
|
+
- * as somebody whose home tenant differs.
|
|
705
|
+
- */
|
|
706
|
+
-
|
|
707
|
+
-async function signInAs(page: Page, personId: string) {
|
|
708
|
+
- await page.goto('/en/signin')
|
|
709
|
+
- await page.getByTestId(`person-${personId}`).click()
|
|
710
|
+
- await page.waitForURL('**/dashboard')
|
|
711
|
+
-}
|
|
712
|
+
-
|
|
713
|
+
-async function signOut(page: Page) {
|
|
714
|
+
- await page.getByTestId('user-menu').click()
|
|
715
|
+
- await page.getByTestId('menu-signout').click()
|
|
716
|
+
- await page.waitForURL(/\/en\/?$/)
|
|
717
|
+
-}
|
|
718
|
+
-
|
|
719
|
+
-/** Hydration-safe entry: right after a navigation, filling the controlled input can beat React
|
|
720
|
+
- * hydration, so the DOM has the text but state does not and the button stays disabled. */
|
|
721
|
+
-async function addItem(page: Page, title: string) {
|
|
722
|
+
- await expect(async () => {
|
|
723
|
+
- await page.getByTestId('item-input').fill(title)
|
|
724
|
+
- await expect(page.getByTestId('item-add')).toBeEnabled({ timeout: 1_000 })
|
|
725
|
+
- }).toPass()
|
|
726
|
+
- await page.getByTestId('item-add').click()
|
|
727
|
+
- await expect(page.getByTestId('items-list')).toContainText(title)
|
|
728
|
+
-}
|
|
729
|
+
-
|
|
730
|
+
-test('an item created in one tenant is invisible from the other', async ({ page }) => {
|
|
731
|
+
- const secret = `northwind-item-${Date.now()}`
|
|
732
|
+
-
|
|
733
|
+
- // Nadia's home tenant is northwind.
|
|
734
|
+
- await signInAs(page, 'person-owner')
|
|
735
|
+
- await expect(page.getByTestId('active-tenant')).toHaveText('Northwind')
|
|
736
|
+
- await addItem(page, secret)
|
|
737
|
+
-
|
|
738
|
+
- // Reload proves the row survived a round trip through Postgres rather than living in React state.
|
|
739
|
+
- await page.reload()
|
|
740
|
+
- await expect(page.getByTestId('items-list')).toContainText(secret)
|
|
741
|
+
-
|
|
742
|
+
- // Cross to the other tenant: Wes must not see it, and his own view starts empty.
|
|
743
|
+
- await signOut(page)
|
|
744
|
+
- await signInAs(page, 'person-other-tenant')
|
|
745
|
+
- await expect(page.getByTestId('active-tenant')).toHaveText('Westgate')
|
|
746
|
+
- await expect(page.getByTestId('items-card')).toBeVisible()
|
|
747
|
+
- await expect(page.getByTestId('items-card')).not.toContainText(secret)
|
|
748
|
+
-
|
|
749
|
+
- // ...and back again: Nadia's item is still there.
|
|
750
|
+
- await signOut(page)
|
|
751
|
+
- await signInAs(page, 'person-owner')
|
|
752
|
+
- await expect(page.getByTestId('items-list')).toContainText(secret)
|
|
753
|
+
-})
|
|
754
|
+
-
|
|
755
|
+
-test('the items list pages, and the endpoint refuses a cursor it cannot read', async ({ page }) => {
|
|
756
|
+
- await signInAs(page, 'person-owner')
|
|
757
|
+
- await expect(page.getByTestId('items-card')).toBeVisible()
|
|
758
|
+
-
|
|
759
|
+
- // The default page is 20, so 22 more items guarantee the list is longer than one page whatever else this
|
|
760
|
+
- // run has already written. Written through the route, the way the card's own add button does.
|
|
761
|
+
- const stamp = Date.now()
|
|
762
|
+
- for (let index = 0; index < 22; index++) {
|
|
763
|
+
- const response = await page.request.post('/api/items', { data: { title: `paged-${stamp}-${index}` } })
|
|
764
|
+
- expect(response.ok()).toBe(true)
|
|
765
|
+
- }
|
|
766
|
+
- await page.reload()
|
|
767
|
+
- const rows = page.getByTestId('item-row')
|
|
768
|
+
- await expect(rows).toHaveCount(20)
|
|
769
|
+
- await expect(page.getByTestId('items-load-more')).toBeVisible()
|
|
770
|
+
-
|
|
771
|
+
- // "Show older items" APPENDS: what is on screen stays, in the same order, and the button goes away at the
|
|
772
|
+
- // end of the list. Walked with a guard rather than one click, because this world keeps its rows between
|
|
773
|
+
- // runs and the list can be longer than two pages.
|
|
774
|
+
- let previous = await rows.allTextContents()
|
|
775
|
+
- for (let click = 0; click < 20; click++) {
|
|
776
|
+
- if (!(await page.getByTestId('items-load-more').isVisible())) break
|
|
777
|
+
- await page.getByTestId('items-load-more').click()
|
|
778
|
+
- await expect(rows).not.toHaveCount(previous.length)
|
|
779
|
+
- const current = await rows.allTextContents()
|
|
780
|
+
- expect(current.slice(0, previous.length)).toEqual(previous)
|
|
781
|
+
- previous = current
|
|
782
|
+
- }
|
|
783
|
+
- await expect(page.getByTestId('items-load-more')).toHaveCount(0)
|
|
784
|
+
- expect(previous.length).toBeGreaterThan(20)
|
|
785
|
+
- expect(new Set(previous).size).toBe(previous.length)
|
|
786
|
+
-
|
|
787
|
+
- // A malformed cursor is a 400, never a silent first page; the server also caps the page size itself.
|
|
788
|
+
- const bad = await page.request.get('/api/items?cursor=not-a-cursor')
|
|
789
|
+
- expect(bad.status()).toBe(400)
|
|
790
|
+
- expect(await bad.json()).toEqual({ error: 'invalid-cursor' })
|
|
791
|
+
- const single = await page.request.get('/api/items?limit=1')
|
|
792
|
+
- const onePage = (await single.json()) as { items: unknown[]; nextCursor: string | null }
|
|
793
|
+
- expect(onePage.items.length).toBe(1)
|
|
794
|
+
- expect(onePage.nextCursor).not.toBeNull()
|
|
795
|
+
- const greedy = await page.request.get('/api/items?limit=1000000')
|
|
796
|
+
- expect(greedy.status()).toBe(200)
|
|
797
|
+
- expect(((await greedy.json()) as { items: unknown[] }).items.length).toBeLessThanOrEqual(100)
|
|
798
|
+
-})
|