@quatronic/sdk 0.9.0-rc.2 → 0.9.0-test.ab218af

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 (75) hide show
  1. package/README.md +6 -0
  2. package/dist/chunk-7XIDABOQ.js +83 -0
  3. package/dist/chunk-7XIDABOQ.js.map +1 -0
  4. package/dist/{chunk-YFZB5EW6.js → chunk-P5GBQVO7.js} +2 -2
  5. package/dist/{chunk-IFESUTF2.js → chunk-VQKYPW5V.js} +7 -3
  6. package/dist/chunk-VQKYPW5V.js.map +1 -0
  7. package/dist/{chunk-POZI4OKJ.js → chunk-WOFBDOMY.js} +2 -2
  8. package/dist/{chunk-TPBRMW5N.js → chunk-YCKDMG4B.js} +30 -1
  9. package/dist/chunk-YCKDMG4B.js.map +1 -0
  10. package/dist/chunk-YXIYI7R2.js +23 -0
  11. package/dist/chunk-YXIYI7R2.js.map +1 -0
  12. package/dist/cli/skills-postinstall.js +13 -6
  13. package/dist/cli/skills.js +11 -5
  14. package/dist/context-B_u-vpkw.d.ts +111 -0
  15. package/dist/eslint/index.d.ts +11 -1
  16. package/dist/eslint/index.js +123 -4
  17. package/dist/eslint/index.js.map +1 -1
  18. package/dist/expo/auth/index.d.ts +8 -0
  19. package/dist/expo/auth/index.js +177 -0
  20. package/dist/expo/auth/index.js.map +1 -0
  21. package/dist/expo/config/index.d.ts +16 -0
  22. package/dist/expo/config/index.js +17 -0
  23. package/dist/expo/config/index.js.map +1 -0
  24. package/dist/expo/log/index.d.ts +9 -0
  25. package/dist/expo/log/index.js +16 -0
  26. package/dist/expo/log/index.js.map +1 -0
  27. package/dist/expo/query/index.d.ts +15 -0
  28. package/dist/expo/query/index.js +52 -0
  29. package/dist/expo/query/index.js.map +1 -0
  30. package/dist/expo/sentry/index.d.ts +29 -0
  31. package/dist/expo/sentry/index.js +93 -0
  32. package/dist/expo/sentry/index.js.map +1 -0
  33. package/dist/expo/testing/index.d.ts +32 -0
  34. package/dist/expo/testing/index.js +57 -0
  35. package/dist/expo/testing/index.js.map +1 -0
  36. package/dist/next/auth/index.d.ts +50 -0
  37. package/dist/next/auth/index.js +504 -101
  38. package/dist/next/auth/index.js.map +1 -1
  39. package/dist/next/boot/index.js +3 -3
  40. package/dist/next/db/index.js +1 -1
  41. package/dist/next/sentry/client.js +3 -3
  42. package/dist/next/sentry/client.js.map +1 -1
  43. package/dist/next/sentry/index.js +1 -1
  44. package/dist/next/sentry/register.js +3 -3
  45. package/dist/node/sentry/index.js +1 -1
  46. package/dist/node/sentry/register.js +2 -2
  47. package/package.json +75 -2
  48. package/skills/catalog.json +3 -0
  49. package/skills/qore-add-api-route/SKILL.md +1 -1
  50. package/skills/qore-add-connection/SKILL.next.md +3 -1
  51. package/skills/qore-add-connection/SKILL.node.md +3 -1
  52. package/skills/qore-add-env-key/SKILL.md +174 -9
  53. package/skills/qore-add-feature/SKILL.md +1 -1
  54. package/skills/qore-add-integration/SKILL.next.md +4 -2
  55. package/skills/qore-add-integration/SKILL.node.md +6 -6
  56. package/skills/qore-add-page/SKILL.md +1 -1
  57. package/skills/qore-author-skill/SKILL.md +1 -1
  58. package/skills/qore-debug-issue/SKILL.md +10 -0
  59. package/skills/qore-mobile-add-screen/SKILL.md +58 -0
  60. package/skills/qore-mobile-call-server/SKILL.md +74 -0
  61. package/skills/qore-mobile-run-on-device/SKILL.md +41 -0
  62. package/skills/qore-observability/SKILL.md +17 -0
  63. package/skills/qore-secure-io/SKILL.md +15 -0
  64. package/skills/qore-ship-checklist/SKILL.md +10 -0
  65. package/skills/qore-translate-strings/SKILL.md +10 -0
  66. package/skills/qore-use-addons/SKILL.md +2 -0
  67. package/skills/qore-use-database/SKILL.md +2 -0
  68. package/skills/qore-use-design-system/SKILL.md +1 -1
  69. package/skills/qore-use-mail-domain/SKILL.next.md +1 -1
  70. package/skills/qore-use-mail-domain/SKILL.node.md +2 -2
  71. package/skills/qore-use-permissions/SKILL.md +10 -0
  72. package/dist/chunk-IFESUTF2.js.map +0 -1
  73. package/dist/chunk-TPBRMW5N.js.map +0 -1
  74. /package/dist/{chunk-YFZB5EW6.js.map → chunk-P5GBQVO7.js.map} +0 -0
  75. /package/dist/{chunk-POZI4OKJ.js.map → chunk-WOFBDOMY.js.map} +0 -0
@@ -0,0 +1,58 @@
1
+ ---
2
+ name: qore-mobile-add-screen
3
+ description: Add a screen to this module's phone app (mobile/, Expo Router) — a route file, a tab if it needs one, en+nl strings, loading/error states, a permission check and a component test. Use for any new screen or tab in mobile/; for a web page in src/app use qore-add-page instead.
4
+ allowed-tools: Bash(pnpm:*), Edit, Read
5
+ ---
6
+
7
+ # Add a screen to the phone app
8
+
9
+ `mobile/` is the Expo app; it is its own pnpm project (`cd mobile` before any `pnpm`
10
+ command) and imports only `@quatronic/sdk/expo/*` — never `next/*`, `node/*` or anything
11
+ from the module's `src/`. `pnpm lint` in `mobile/` enforces that. Read `mobile/CLAUDE.md`
12
+ first; for Expo APIs read the versioned docs it points to.
13
+
14
+ 1. **Route file.** Expo Router maps files to screens:
15
+ - a tab: `mobile/src/app/(tabs)/<name>.tsx`, plus a `<Tabs.Screen name="<name>" …>` in
16
+ `mobile/src/app/(tabs)/_layout.tsx` with a `title` from `tr(...)` and a
17
+ `lucide-react-native` icon re-exported from `@/components/ui`;
18
+ - a pushed screen (detail, settings): `mobile/src/app/<name>.tsx`, reached with
19
+ `router.push("/<name>")` or `<Link href="/<name>">`.
20
+
21
+ Default-export a component that renders `<Screen>` from `@/components/ui`. Everything
22
+ under `(tabs)` is already signed-in only; the root layout handles the gate.
23
+
24
+ 2. **Strings.** Every visible string is a key in **both**
25
+ `mobile/src/i18n/messages/en.json` and `nl.json`, read with `const t = useT()` from
26
+ `@/i18n`. The parity test (`pnpm test`) fails when one catalog lacks a key. Tab titles
27
+ live under `tabs.*`.
28
+
29
+ 3. **Data.** A screen that loads something uses a query hook over `apiFetch` — see
30
+ /qore-mobile-call-server. Render the three states with `LoadingState` and
31
+ `ErrorState` (`@/components/ui`); pass `onRetry={() => query.refetch()}`.
32
+
33
+ 4. **Permissions.** Hide what the user cannot use with `useCan("<permission>")` or
34
+ `<Can permission="<permission>">` from `@/lib/auth`. That only hides it: the server
35
+ route must check the same permission with `requireAuthFor`, because anyone can call it.
36
+
37
+ 5. **Style.** NativeWind classes with the theme's semantic tokens (`bg-card`,
38
+ `text-muted-foreground`, `border-border`) from `mobile/src/global.css`; navigation
39
+ options take colour values, read them from `useTokens()` (`@/styles/theme`). Tap
40
+ targets at least 44 pt, and give a `Pressable` an `accessibilityRole` and
41
+ `accessibilityLabel`.
42
+
43
+ 6. **Test.** `mobile/src/app/__tests__/<name>.test.tsx`, rendered inside
44
+ `TestProviders` from `@quatronic/sdk/expo/testing`:
45
+ ```tsx
46
+ import { render, screen } from "@testing-library/react-native"
47
+ import { mockApiFetch, TestProviders, testUser } from "@quatronic/sdk/expo/testing"
48
+
49
+ const auth = mockApiFetch({ "/api/orders": [{ id: "o1", total: 12 }] })
50
+ const me = testUser({ permissions: ["orders.read"] })
51
+ render(<TestProviders auth={auth} status={{ state: "signedIn", me }}><OrdersScreen /></TestProviders>)
52
+ expect(await screen.findByText("o1")).toBeTruthy()
53
+ ```
54
+
55
+ 7. `cd mobile && pnpm typecheck && pnpm lint && pnpm test`.
56
+
57
+ Navigation is traced already: every screen, tab switches included, becomes a transaction
58
+ in the Monitoring tab's Traces with tag `app=mobile`. Do not add your own.
@@ -0,0 +1,74 @@
1
+ ---
2
+ name: qore-mobile-call-server
3
+ description: Let the phone app (mobile/) read or change data — a route on this module's own Next server plus a TanStack Query hook over apiFetch on the phone. Use whenever a mobile screen needs data, a backend call or an external API.
4
+ allowed-tools: Bash(pnpm:*), Edit, Read
5
+ ---
6
+
7
+ # Call the server from the phone app
8
+
9
+ The phone talks to **one** host: this module's own Next server (`EXPO_PUBLIC_SERVER_URL`).
10
+ Everything else — the database, another module, a third-party API, any secret — sits
11
+ behind a route on that server. `apiFetch` refuses any other host, and
12
+ `qdc/no-raw-fetch` refuses `fetch` in `mobile/src`.
13
+
14
+ ## 1. The server route (`src/`, the web half)
15
+
16
+ Add it as for any route (/qore-add-api-route): `src/app/api/<area>/route.ts`, guarded with
17
+ `requireAuth()` or `requireAuthFor("<permission>")` from `@/lib/auth`. Nothing mobile-specific:
18
+ the SDK accepts the phone's `Authorization: Bearer` session where a browser sends a cookie,
19
+ so the same route serves both, and `getAccessToken()` / `callBackend` work unchanged for
20
+ the downstream call. Return JSON with a stable shape and errors as `{ error: "<code>" }`.
21
+
22
+ **Additive only.** Installed phones run old builds for months; a store update is not a
23
+ deploy. Never rename or remove a field, a route or an error code the phone reads, and
24
+ never make an optional request field required. Add a new field or a `/v2` route instead.
25
+ The request header `x-qore-app-version` says which build called, in logs and traces.
26
+
27
+ ## 2. The query hook (`mobile/`, the phone half)
28
+
29
+ Put the hook next to its screen's feature, `mobile/src/features/<area>/use<Thing>.ts`:
30
+
31
+ ```ts
32
+ import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"
33
+ import { useAuth } from "@/lib/auth"
34
+
35
+ export type Order = { id: string; total: number }
36
+
37
+ export function useOrders() {
38
+ const { auth } = useAuth()
39
+ return useQuery({ queryKey: ["orders"], queryFn: () => auth.apiFetch<Order[]>("/api/orders") })
40
+ }
41
+
42
+ export function useCreateOrder() {
43
+ const { auth } = useAuth()
44
+ const qc = useQueryClient()
45
+ return useMutation({
46
+ mutationFn: (body: { total: number }) =>
47
+ auth.apiFetch<Order>("/api/orders", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) }),
48
+ onSuccess: () => qc.invalidateQueries({ queryKey: ["orders"] }),
49
+ })
50
+ }
51
+ ```
52
+
53
+ Take `auth` from `useAuth()`, not a module import, so a test's `mockApiFetch` reaches it.
54
+ Type the response by hand next to the hook; there is no shared types folder yet.
55
+
56
+ ## 3. Errors
57
+
58
+ The shared query client (`@/lib/query`) already does the rest — do not repeat it per hook:
59
+
60
+ | Error | Meaning | Handled by |
61
+ |---|---|---|
62
+ | `Unauthenticated` | session gone; token already cleared | query client → login screen with "session ended" |
63
+ | `ApiError` 4xx | the server refused (`err.code` is its `error`) | your screen: show `ErrorState`, no retry |
64
+ | `ApiError` 5xx, network | server or connection trouble | retried twice, then your `ErrorState` with `onRetry` |
65
+
66
+ Offline, queries pause and resume when the connection returns; the offline banner says so.
67
+
68
+ ## 4. Check
69
+
70
+ - Server: `pnpm test` at the module root for the route.
71
+ - Phone: a component test with `mockApiFetch({ "/api/orders": [...] })` (see
72
+ /qore-mobile-add-screen), then `cd mobile && pnpm typecheck && pnpm lint && pnpm test`.
73
+ - On a device: /qore-mobile-run-on-device. The call shows up in Traces as a span under
74
+ the screen's transaction, continuing into the server's.
@@ -0,0 +1,41 @@
1
+ ---
2
+ name: qore-mobile-run-on-device
3
+ description: Run the phone app (mobile/) on a real phone with Expo Go against the module's staging server, sign in, and find the phone's errors, logs and traces in the portal. Use when asked to try, test or debug the mobile app on a device.
4
+ allowed-tools: Bash(pnpm:*), Bash(npx expo:*), Read
5
+ ---
6
+
7
+ # Run the phone app on a device
8
+
9
+ 1. **Configure.** `mobile/.env` holds three public values, never a secret:
10
+ - `EXPO_PUBLIC_SERVER_URL` — the module's **staging** origin, `https://…`, no path;
11
+ - `EXPO_PUBLIC_SENTRY_DSN` — the module's Sentry DSN (public by design; empty turns
12
+ Sentry off);
13
+ - `EXPO_PUBLIC_QORE_ENV` — `staging`.
14
+
15
+ The portal shows the server URL and the DSN on the module's page. A wrong value is not a crash: the
16
+ app opens on a "misconfigured" screen naming the key.
17
+
18
+ 2. **Start.** `cd mobile && pnpm install && npx expo start`. Scan the QR code with the
19
+ camera (iOS) or the Expo Go app (Android). Phone and computer on the same network; on a
20
+ network that blocks that, `npx expo start --tunnel`.
21
+
22
+ 3. **Sign in.** Login opens the server's Keycloak page in an in-app browser and comes back
23
+ to the app. In Expo Go the return address is `exp://…`, which the staging server accepts
24
+ and production refuses — a real build uses the app's own scheme. A login that fails
25
+ returns with a reason on the login screen (no access to this app, expired, cancelled).
26
+
27
+ 4. **Look.** In the portal, the module's **Monitoring** tab, environment staging:
28
+ - pick **Phone** in the toolbar to see only the phone's errors, logs and traces
29
+ (each also carries `app=mobile`);
30
+ - Traces has one transaction per screen, tab switches included, with each `apiFetch`
31
+ call as a span that continues into the server's trace;
32
+ - Replays: Expo Go does not record them; a development or store build does, masked.
33
+
34
+ Phone logs come only from `log` (`@/lib/log`); `console.*` stays on the device.
35
+
36
+ 5. **Reload** with `r` in the terminal, or shake the phone for the dev menu. A change to
37
+ `app.config.ts`, a plugin or a native package needs a restart of `npx expo start`, and
38
+ one that Expo Go does not include needs a development build — ask before setting one up.
39
+
40
+ Do not hand-edit `mobile/ios` or `mobile/android`; they are generated. Add a native package
41
+ with `npx expo install <package>`, which picks the version matching the Expo SDK.
@@ -87,3 +87,20 @@ If this repo has `console.*` under `src/` or no `eslint.config.mjs`: replace eac
87
87
  and `typescript-eslint` dev dependencies from a freshly generated backend. That config uses
88
88
  `configs.observability`, so bump `@quatronic/sdk` to a version that exports it first. Then run `pnpm lint`.
89
89
  {{/if}}
90
+
91
+ {{#if mobile}}
92
+ ## The phone app (`mobile/`)
93
+
94
+ The same Sentry project, tagged `app=mobile`; filter on it to tell the phone from the server.
95
+ `@quatronic/sdk/expo/sentry` owns the setup (`qoreSentryInit`, `useNavigationTelemetry` and
96
+ `wrap` in `mobile/src/app/_layout.tsx` via `@/lib/telemetry`) — no `Sentry.init` there either.
97
+
98
+ - **Logs:** `log.info("orders.loaded", { count })` from `@/lib/log` only. It reaches Sentry
99
+ Logs and, in development, the Metro terminal. `no-console` is an error in `mobile/src`.
100
+ - **Traces:** each screen is a transaction, tab switches included; each `apiFetch` is a span
101
+ whose trace continues on the server. Don't add navigation spans by hand.
102
+ - **Errors:** a thrown render error is caught by the root `wrap`. Capture by hand only an
103
+ error you swallow on purpose, with `Sentry.captureException` from `@sentry/react-native`.
104
+ - **Replay** is on and masks all text, images and vectors; don't unmask.
105
+ - **No personal data**, as on the server: the user is their Keycloak id, set on sign-in.
106
+ {{/if}}
@@ -172,3 +172,18 @@ Notes that are easy to get wrong:
172
172
 
173
173
  Run the full local check loop — `pnpm lint && pnpm typecheck && pnpm test:run &&
174
174
  pnpm build` — then `/qore-ship-checklist` before a PR.
175
+
176
+ {{#if mobile}}
177
+ ## The phone app (`mobile/`)
178
+
179
+ Everything in the phone app is public: its bundle can be unpacked. So:
180
+
181
+ - **No secrets in `EXPO_PUBLIC_*`** (`qdc/no-secret-public-env`). The only public values are
182
+ the server origin, the Sentry DSN and the environment name. Other `process.env` names are
183
+ undefined on the phone (`qdc/no-private-env`).
184
+ - **One host.** Requests go through `apiFetch` to the module's own server
185
+ (`qdc/no-raw-fetch`); the server holds the credentials and calls everything else.
186
+ - **The session token** lives in the device's secure store, owned by
187
+ `@quatronic/sdk/expo/auth`. Never read, log or pass it on.
188
+ - **Validate on the server** whatever the phone sends, exactly as for a browser.
189
+ {{/if}}
@@ -78,3 +78,13 @@ Walk the new code against `/qore-observability`:
78
78
  Small, focused commits on a feature branch. Open a PR (never push to
79
79
  `main`/`production` directly) so the change is reviewable, traceable, and
80
80
  revertable.
81
+
82
+ {{#if mobile}}
83
+ ## The phone app (`mobile/`)
84
+
85
+ - [ ] `cd mobile && pnpm typecheck && pnpm lint && pnpm test` is green.
86
+ - [ ] Every server route the phone reads changed additively only — no renamed or removed
87
+ field, route or error code (old builds keep calling it).
88
+ - [ ] New strings are in both `mobile/src/i18n/messages/*.json`.
89
+ - [ ] Tried on a device against staging (/qore-mobile-run-on-device).
90
+ {{/if}}
@@ -34,3 +34,13 @@ user-facing copy — every visible string is a key in `messages/nl.json` and
34
34
  - `pnpm typecheck` — typed messages (`global.d.ts`) catch mistyped keys.
35
35
 
36
36
  Both run as part of /qore-ship-checklist.
37
+
38
+ {{#if mobile}}
39
+ ## The phone app (`mobile/`)
40
+
41
+ Its own catalogs: `mobile/src/i18n/messages/en.json` and `nl.json`, read with
42
+ `const t = useT()` from `@/i18n` (not next-intl). Same rule — every visible string a key in
43
+ both — and `cd mobile && pnpm test` runs the parity check. The phone follows the device
44
+ language and passes it to the login page; a key the server returns (an `error` code) is
45
+ translated on the phone, never shown raw.
46
+ {{/if}}
@@ -49,6 +49,8 @@ Add the keys for the addons you use to the server schema in
49
49
  `DATABASE_URL` is already declared when this app was generated with a database.
50
50
  Add the others only for the addons you actually provisioned.
51
51
 
52
+ How to declare, mark and check a key: `/qore-add-env-key`.
53
+
52
54
  ## 2. Postgres — use the existing client
53
55
 
54
56
  {{#if db}}The database client already reads `DATABASE_URL` for you. Don't build a new
@@ -15,6 +15,8 @@ skill is the whole contract.
15
15
  `src/config/env.ts` requires `DATABASE_URL` (`z.string().min(1)`), so the service
16
16
  refuses to boot without it.
17
17
 
18
+ How to declare, mark and check a key: `/qore-add-env-key`.
19
+
18
20
  | Where | How it arrives |
19
21
  |-------|----------------|
20
22
  | **Local** | `pnpm bootstrap` (or `qore env pull`) fetches it from the portal into `.env`. It points at the docker-compose database below on this module's own port: `postgresql://postgres:postgres@localhost:<DB_PORT>/app`, with `DB_PORT` written alongside it |
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: qore-use-design-system
3
- description: Use this app's house component kit and design tokens. Use whenever building or restyling UI — pages, forms, tables, dialogs — so the app stays visually consistent.
3
+ description: Use the web app's (src/) house component kit and design tokens. Use whenever building or restyling UI — pages, forms, tables, dialogs — so the app stays visually consistent.{{#if mobile}} Not for the phone app in mobile/ (use the qore-mobile-* skills).{{/if}}
4
4
  ---
5
5
 
6
6
  # Use the design system
@@ -18,7 +18,7 @@ environments:
18
18
  | `MAIL_FROM` | the full from-header, e.g. `Acme Support <support@acme.nl>` |
19
19
 
20
20
  > These are system-managed: they never appear in `.env.example`, never show up
21
- > in this module's Secrets tab, and you cannot set them yourself. Until a
21
+ > in this module's Variables tab, and you cannot set them yourself. Until a
22
22
  > domain is linked they're simply absent.
23
23
 
24
24
  ## Hard rule: never present in `local` or preview
@@ -17,8 +17,8 @@ environments:
17
17
  | `MAIL_SENDING_DOMAIN` | the domain, e.g. `acme.nl` — informational only, already baked into `MAIL_FROM` |
18
18
  | `MAIL_FROM` | the full from-header, e.g. `Acme Support <support@acme.nl>` |
19
19
 
20
- > These are system-managed: they never appear in `.env.example`, never show up
21
- > in this module's Secrets tab, and you cannot set them yourself. Until a
20
+ > These are system-managed: they never show up
21
+ > in this module's Variables tab, and you cannot set them yourself. Until a
22
22
  > domain is linked they're simply absent.
23
23
 
24
24
  ## Hard rule: never present in `local` or preview
@@ -114,3 +114,13 @@ Run `pnpm lint && pnpm typecheck && pnpm test:run && pnpm build`, then
114
114
 
115
115
  > `hasRole` from `@/lib/roles` still exists for cases that genuinely key off a
116
116
  > raw role, but prefer permissions.
117
+
118
+ {{#if mobile}}
119
+ ## The phone app (`mobile/`)
120
+
121
+ The phone reads the signed-in user's permissions from `/api/auth/me` and offers
122
+ `useCan("<permission>")` and `<Can permission="…" fallback={…}>` from `@/lib/auth`. They
123
+ **only hide**: an installed app can be taken apart, so every server route the phone calls
124
+ checks the same permission with `requireAuthFor`. A role change reaches the phone on its next
125
+ `/api/auth/me`, at app start or after sign-in.
126
+ {{/if}}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/sentry-core/scrub.ts"],"sourcesContent":["export const REDACTED = \"●●●\"\n\n// Bounded and anchored (`(?<![...])` + `{1,64}` local part, no `.` in the\n// domain-char class) so it cannot backtrack catastrophically on long runs of\n// email-charset bytes — see the fix-round-1 report for the O(n²) it replaced.\nconst EMAIL = /(?<![A-Z0-9._%+-])[A-Z0-9._%+-]{1,64}@[A-Z0-9-]+(?:\\.[A-Z0-9-]+)*\\.[A-Z]{2,}/gi\nconst URL_USERINFO = /\\b([a-z][a-z0-9+.-]{0,31}:\\/\\/)[^/\\s:@]+(?::[^/\\s@]*)?@/gi\nconst JWT = /eyJ[\\w-]+\\.[\\w-]+\\.[\\w-]+/g\nconst AUTH_SCHEME = /\\b(Bearer|Basic)\\s+\\S+/gi\nconst PARAMS_TAIL = /\\bparams:\\s.*$/s\nexport const SECRET_PARAMS: ReadonlySet<string> = new Set([\"token\", \"code\", \"state\", \"password\", \"secret\", \"key\", \"session\", \"access_token\", \"refresh_token\", \"id_token\"])\nconst SECRET_HEADERS = new Set([\n \"authorization\",\n \"cookie\",\n \"set-cookie\",\n \"x-qdc-connection-token\",\n \"x-forwarded-for\",\n \"x-real-ip\",\n \"forwarded\",\n \"user-agent\",\n])\nconst DROP_LOG_ATTRS = new Set([\"ip\", \"ip_address\", \"user_agent\", \"email\", \"user_email\", \"server.address\"])\nconst REDACT_KEYS = new Set([\"db.connection_string\", \"db.user\"])\nconst REDACT_PREFIXES = [\"net.peer.\", \"net.sock.\", \"net.host.\", \"network.peer.\", \"network.local.\"]\nconst DROP_SPAN_KEYS = new Set([\"user_agent.original\", \"http.user_agent\", \"client.address\", \"http.client_ip\"])\nconst DROP_SPAN_PREFIXES = [\"http.request.header.\", \"http.response.header.\"]\nconst URL_SPAN_KEYS = new Set([\"url.full\", \"http.url\", \"url\", \"http.target\", \"url.query\", \"http.query\"])\n\nconst SECRETS = Symbol.for(\"@quatronic/sdk.sentry-secret-values\")\ntype SecretHolder = { [SECRETS]?: { values: Set<string>; longestFirst: string[] } }\nconst secretHolder = globalThis as SecretHolder\n\n// On globalThis because a Next app can bundle this module twice: the copy\n// serverEnv() registers into is not necessarily the one beforeSend reads.\nfunction secretState(): NonNullable<SecretHolder[typeof SECRETS]> {\n return (secretHolder[SECRETS] ??= { values: new Set(), longestFirst: [] })\n}\n\nexport function registerSecretValues(values: Iterable<unknown>): void {\n const state = secretState()\n for (const v of values) if (typeof v === \"string\" && v.length >= 8) state.values.add(v)\n state.longestFirst = [...state.values].sort((a, b) => b.length - a.length)\n}\n\nfunction maskSecretValues(s: string): string {\n return secretState().longestFirst.reduce((acc, v) => acc.replaceAll(v, REDACTED), s)\n}\n\nexport function redactText(s: string): string {\n return maskSecretValues(s)\n .replace(URL_USERINFO, `$1${REDACTED}@`)\n .replace(PARAMS_TAIL, \"params: [redacted]\")\n .replace(AUTH_SCHEME, \"$1 [redacted]\")\n .replace(JWT, \"[jwt]\")\n .replace(EMAIL, \"[email]\")\n}\n\nfunction redactQuery(query: string): string {\n return query\n .split(\"&\")\n .map((pair) => {\n const [k, v] = pair.split(\"=\", 2)\n return v !== undefined && SECRET_PARAMS.has(k!.toLowerCase()) ? `${k}=[redacted]` : pair\n })\n .join(\"&\")\n}\n\nfunction redactUrl(url: string): string {\n const i = url.indexOf(\"?\")\n return i < 0 ? url : url.slice(0, i + 1) + redactQuery(url.slice(i + 1))\n}\n\n// For values that are either a URL/path or a bare query string (no `?`).\nfunction redactUrlOrQuery(v: string): string {\n return v.includes(\"?\") ? redactUrl(v) : redactQuery(v)\n}\n\ntype Dict = Record<string, unknown>\n\nexport interface SentryEventLike {\n server_name?: string\n user?: Dict\n request?: { url?: string; query_string?: unknown; cookies?: unknown; headers?: Record<string, string>; data?: unknown }\n message?: string\n exception?: { values?: Array<{ type?: string; value?: string }> }\n breadcrumbs?: Array<{ message?: string; data?: Dict }>\n contexts?: { nextjs?: Dict } & Dict\n}\n\nexport function scrubEvent<E extends SentryEventLike>(e: E): E {\n delete e.server_name\n if (e.user) e.user = e.user.id ? { id: e.user.id } : {}\n if (e.request) {\n delete e.request.cookies\n delete e.request.data\n if (e.request.url) e.request.url = redactUrl(e.request.url)\n if (typeof e.request.query_string === \"string\") e.request.query_string = redactQuery(e.request.query_string)\n if (e.request.headers) {\n e.request.headers = Object.fromEntries(\n Object.entries(e.request.headers).filter(([k]) => !SECRET_HEADERS.has(k.toLowerCase())),\n )\n }\n }\n const nextjs = e.contexts?.nextjs\n if (typeof nextjs?.request_path === \"string\") nextjs.request_path = redactUrl(nextjs.request_path)\n if (e.message) e.message = redactText(e.message)\n for (const v of e.exception?.values ?? []) if (v.value) v.value = redactText(v.value)\n for (const b of e.breadcrumbs ?? []) {\n if (b.message) b.message = redactText(b.message)\n const d = b.data\n if (!d) continue\n for (const k of [\"url\", \"from\", \"to\"]) if (typeof d[k] === \"string\") d[k] = redactUrl(d[k])\n if (typeof d[\"http.query\"] === \"string\") d[\"http.query\"] = redactUrlOrQuery(d[\"http.query\"])\n if (Array.isArray(d.arguments)) d.arguments = d.arguments.map((a) => (typeof a === \"string\" ? redactText(a) : a))\n }\n return e\n}\n\nexport interface SentryLogLike {\n message: string\n attributes?: Dict\n}\n\nexport function scrubLog<L extends SentryLogLike>(l: L): L {\n l.message = redactText(l.message)\n if (l.attributes) {\n const out: Dict = {}\n for (const [k, v] of Object.entries(l.attributes)) {\n if (DROP_LOG_ATTRS.has(k)) continue\n out[k] = typeof v === \"string\" ? redactText(v) : v\n }\n l.attributes = out\n }\n return l\n}\n\nexport interface SentrySpanLike {\n description?: string\n data?: Dict\n}\n\nexport function scrubSpan<S extends SentrySpanLike>(s: S): S {\n // Browser page-metric spans are described by the full page URL.\n if (typeof s.description === \"string\") s.description = redactUrl(s.description)\n for (const [k, v] of Object.entries(s.data ?? {})) {\n if (DROP_SPAN_KEYS.has(k) || DROP_SPAN_PREFIXES.some((p) => k.startsWith(p))) delete s.data![k]\n else if (REDACT_KEYS.has(k) || REDACT_PREFIXES.some((p) => k.startsWith(p))) s.data![k] = REDACTED\n else if (typeof v === \"string\" && URL_SPAN_KEYS.has(k)) s.data![k] = redactUrlOrQuery(v)\n }\n return s\n}\n"],"mappings":";AAAO,IAAM,WAAW;AAKxB,IAAM,QAAQ;AACd,IAAM,eAAe;AACrB,IAAM,MAAM;AACZ,IAAM,cAAc;AACpB,IAAM,cAAc;AACb,IAAM,gBAAqC,oBAAI,IAAI,CAAC,SAAS,QAAQ,SAAS,YAAY,UAAU,OAAO,WAAW,gBAAgB,iBAAiB,UAAU,CAAC;AACzK,IAAM,iBAAiB,oBAAI,IAAI;AAAA,EAC7B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,CAAC;AACD,IAAM,iBAAiB,oBAAI,IAAI,CAAC,MAAM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MAAM,EAAE,WAAW,CAAC,CAAC,EAAG,GAAE,KAAM,CAAC,IAAI;AAAA,aACjF,OAAO,MAAM,YAAY,cAAc,IAAI,CAAC,EAAG,GAAE,KAAM,CAAC,IAAI,iBAAiB,CAAC;AAAA,EACzF;AACA,SAAO;AACT;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/db-core/migration-db.ts","../src/auth-core/migrate.ts"],"sourcesContent":["import { Pool } from \"pg\"\nimport { drizzle, type NodePgDatabase } from \"drizzle-orm/node-postgres\"\nimport { sql } from \"drizzle-orm\"\nimport { resolvePostgresConfig } from \"./postgres-config\"\n\nexport interface MigrationDb {\n readonly db: NodePgDatabase\n readonly close: () => Promise<void>\n}\n\n// Migrations get their own short-lived pool, separate from the app's\n// long-lived runtime pool — it exists only for the duration of the boot-time\n// migration call and is torn down immediately after.\nexport function createMigrationDb(databaseUrl: string): MigrationDb {\n const pool = new Pool(resolvePostgresConfig(databaseUrl))\n return { db: drizzle(pool), close: () => pool.end() }\n}\n\n// The addon's regular/admin credentials are both delivered as full DSNs\n// (POSTGRES_URI / POSTGRES_URI_ADMIN — see the templates SecretGroup\n// addonDependencies mapping), not as separate username/password fields, so\n// callers that need the runtime role's name for a GRANT statement parse it\n// out of the runtime connection string instead of reading it separately.\nexport function parseRoleFromUrl(databaseUrl: string): string {\n return decodeURIComponent(new URL(databaseUrl).username)\n}\n\n// `current_user` is compared as the server reports it, so the comparison holds\n// for a role whose name needed quoting in the DSN.\nasync function isCurrentUser(db: NodePgDatabase, role: string): Promise<boolean> {\n const result = await db.execute<{ current_user: string }>(\n sql.raw(`SELECT current_user AS \"current_user\"`),\n )\n return result.rows[0]?.current_user === role\n}\n\n// Safe to call on every boot, whether or not the migrator and runtime roles\n// are the same (the fallback case for environments that haven't opted into a\n// separate migration role yet — see MIGRATION_DATABASE_URL fallback in\n// portal-api/portal-web). ALTER DEFAULT PRIVILEGES only binds objects created\n// after it runs, so this also explicitly grants on ALL TABLES to cover\n// whatever this same run just created.\n//\n// The fallback case is skipped outright rather than issued anyway: granting a\n// role privileges to itself is either redundant (it owns the objects, so it\n// already holds everything) or impossible (it does not, so GRANT raises `must\n// be owner of table …` / `permission denied for schema …`). Issuing it made\n// that second case a boot-time failure on an environment where there was\n// nothing whatsoever to grant.\nexport async function grantRuntimeDefaultPrivileges(\n db: NodePgDatabase,\n schema: string,\n runtimeRole: string,\n): Promise<void> {\n if (await isCurrentUser(db, runtimeRole)) {\n return\n }\n await db.execute(\n sql.raw(`GRANT USAGE ON SCHEMA \"${schema}\" TO \"${runtimeRole}\"`),\n )\n await db.execute(\n sql.raw(\n `ALTER DEFAULT PRIVILEGES IN SCHEMA \"${schema}\" GRANT SELECT, INSERT, UPDATE, DELETE ON TABLES TO \"${runtimeRole}\"`,\n ),\n )\n await db.execute(\n sql.raw(\n `GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA \"${schema}\" TO \"${runtimeRole}\"`,\n ),\n )\n}\n","import { sql } from \"drizzle-orm\"\nimport type { NodePgDatabase } from \"drizzle-orm/node-postgres\"\nimport { grantRuntimeDefaultPrivileges } from \"../db-core/migration-db\"\n\n// Migrations are inlined as string constants rather than read from .sql files\n// at runtime. A runtime `readFile` does not survive bundlers that only trace\n// JS — notably Next.js standalone output, where the .sql is omitted and the\n// read ENOENTs, crashing the instrumentation hook and 500-ing the whole app.\n// Inlining keeps the SQL in the bundled JS so it works in every consumer.\n\n// Split out of what used to be a single MIGRATION_0001_INIT on purpose, and\n// the reason generalises to every statement below it: **Postgres checks the\n// connecting role's privileges before it evaluates `IF NOT EXISTS`.** So an\n// already-applied statement is not a no-op for a role that lacks the right —\n// it is an error:\n//\n// - `CREATE SCHEMA IF NOT EXISTS auth` needs CREATE on the *database* →\n// `permission denied for database <db>` (SQLSTATE 42501)\n// - `CREATE INDEX IF NOT EXISTS` and `ALTER TABLE ... ADD COLUMN IF NOT\n// EXISTS` need *ownership* of the table → `must be owner of table\n// sessions` (also 42501)\n//\n// That is the normal shape of a least-privileged runtime role against an\n// already-provisioned database, and because migrations run in order one such\n// error aborts every statement after it. It has now bitten staging twice: the\n// first time `login_state.forced_reauth` never landed and every\n// `/api/auth/login` 500'd; the second time `0001_init:tables` failed on its\n// `CREATE INDEX` with `must be owner of table sessions`, again blocking every\n// later ALTER even though there was nothing at all to do.\n//\n// So each migration below carries an `isApplied` catalog probe and the runner\n// skips it when its effect is already present. Catalog lookups need nothing\n// beyond CONNECT, so a role with only DML inside an up-to-date `auth` schema\n// gets through cleanly, while a migration that genuinely still has work to do\n// is attempted and — if the role cannot do it — fails loudly, by name.\nconst MIGRATION_0001_SCHEMA = `\nCREATE SCHEMA IF NOT EXISTS auth;\n`\n\nconst MIGRATION_0001_TABLES = `\nCREATE TABLE IF NOT EXISTS auth.sessions (\n id uuid PRIMARY KEY DEFAULT gen_random_uuid(),\n user_sub varchar(64) NOT NULL,\n user_email varchar(320),\n organization_id varchar(64),\n organization_alias varchar(255),\n access_token text NOT NULL,\n access_expires_at timestamptz NOT NULL,\n refresh_ct bytea NOT NULL,\n refresh_iv bytea NOT NULL,\n refresh_expires_at timestamptz NOT NULL,\n created_at timestamptz NOT NULL DEFAULT now(),\n updated_at timestamptz NOT NULL DEFAULT now(),\n revoked_at timestamptz\n);\n\nCREATE INDEX IF NOT EXISTS ix_auth_sessions_user_sub\n ON auth.sessions(user_sub) WHERE revoked_at IS NULL;\n\nCREATE TABLE IF NOT EXISTS auth.login_state (\n state varchar(128) PRIMARY KEY,\n code_verifier varchar(255) NOT NULL,\n redirect_path text NOT NULL DEFAULT '/',\n created_at timestamptz NOT NULL DEFAULT now(),\n expires_at timestamptz NOT NULL\n);\n\nCREATE INDEX IF NOT EXISTS ix_auth_login_state_expires\n ON auth.login_state(expires_at);\n`\n\n// The KC ID token, so RP-initiated logout can pass it as `id_token_hint` —\n// without it, Keycloak's end-session endpoint falls back to showing a logout\n// confirmation page. Nullable: existing sessions predate this column until\n// their next login or token refresh backfills it.\nconst MIGRATION_0002_ID_TOKEN = `\nALTER TABLE auth.sessions ADD COLUMN IF NOT EXISTS id_token text;\n`\n\n// Records that this login asked Keycloak to re-authenticate (prompt=login +\n// max_age=0). The callback needs it to know whether the ID token's auth_time\n// MUST prove a fresh authentication (OIDC 3.1.2.1) — without the flag it cannot\n// tell a forced login from an ordinary SSO continuation.\nconst MIGRATION_0003_FORCED_REAUTH = `\nALTER TABLE auth.login_state ADD COLUMN IF NOT EXISTS forced_reauth boolean NOT NULL DEFAULT false;\n`\n\n// OIDC 3.1.3.7 (11): the nonce sent on the authorization request must be\n// checked against the ID token's claim. Nullable because rows written by an\n// older build have none; the callback treats a null nonce on the row as\n// \"nothing to check\" so an in-flight login survives the deploy.\nconst MIGRATION_0004_NONCE = `\nALTER TABLE auth.login_state ADD COLUMN IF NOT EXISTS nonce varchar(128);\n`\n\n// Bounds the one-and-only restart the callback grants on Keycloak's explicit\n// \"start over\" signals (authentication_expired / login_required). The\n// callback URL is Keycloak's fixed redirect_uri, so Keycloak never echoes our\n// own query parameters back to it — a guard read off the callback's query\n// string can never fire in production. The restarted login (our own request\n// to /api/auth/login?retried=1) stamps this column on the NEW row instead, so\n// the second callback can see it on the row rather than in a URL Keycloak\n// controls. NOT NULL DEFAULT false: every row, old or new, starts un-retried.\nconst MIGRATION_0005_RETRIED = `\nALTER TABLE auth.login_state ADD COLUMN IF NOT EXISTS retried boolean NOT NULL DEFAULT false;\n`\n\n// A session created for an identity that did not match what the login expected\n// exists, holds real tokens, and grants nothing until a human confirms it.\n//\n// DELIBERATELY `DEFAULT false` rather than a nullable column with a backfill:\n// these migrations re-run on every app start, so an `UPDATE ... WHERE\n// pending_identity_confirm IS NULL` would confirm every row still awaiting a\n// human on the next deploy — silently adopting exactly the identity this\n// mechanism exists to stop. A default means pre-existing rows are already\n// confirmed, which is correct: they were issued under the old rules.\nconst MIGRATION_0006_PENDING_CONFIRM = `\nALTER TABLE auth.sessions\n ADD COLUMN IF NOT EXISTS pending_identity_confirm boolean NOT NULL DEFAULT false;\n`\n\n// Who this login was supposed to end up as: the subject of the session being\n// replaced, and/or the address the user typed. The callback compares Keycloak's\n// answer against these instead of adopting whatever comes back. Nullable: a\n// clean first login on a fresh browser expects nobody in particular.\nconst MIGRATION_0007_EXPECTED_IDENTITY = `\nALTER TABLE auth.login_state ADD COLUMN IF NOT EXISTS expected_sub varchar(64);\nALTER TABLE auth.login_state ADD COLUMN IF NOT EXISTS expected_email varchar(320);\n`\n\ninterface Migration {\n // Named so a failure can say *which* statement broke — see the catch below.\n readonly name: string\n readonly sql: string\n // \"Is this migration's effect already present?\" Answered from the catalogs\n // only, so it never needs a privilege the migration itself would need. A\n // partially-applied migration must answer `false` (the SQL is written to be\n // idempotent, so re-running the applied half is harmless).\n readonly isApplied: (db: NodePgDatabase) => Promise<boolean>\n // A migration may only add to the schema: a prod rollback keeps the\n // database, and the previous release must still work on it\n // (scripts/migration-lint.mjs refuses anything else). `true` marks the rare\n // migration that removes or tightens something on purpose; ship it only once\n // no prod still runs a version that reads the old shape.\n readonly contract?: boolean\n}\n\n// All probes funnel through here: one boolean expression, evaluated by the\n// server. Every one of them reads `pg_catalog` directly rather than going\n// through `to_regclass`/`to_regnamespace` or `information_schema`, both of\n// which are privilege-sensitive in ways that defeat the purpose: `to_regclass`\n// resolves the name and so raises `permission denied for schema auth` for a\n// role without USAGE, and `information_schema.columns` silently hides columns\n// the role holds no privilege on — reporting an applied migration as missing\n// and sending us straight into the ALTER we were trying to avoid. The catalogs\n// themselves are world-readable.\nasync function probe(db: NodePgDatabase, expression: string): Promise<boolean> {\n const result = await db.execute<{ applied: boolean }>(\n sql.raw(`SELECT (${expression}) AS \"applied\"`),\n )\n return result.rows[0]?.applied === true\n}\n\nconst schemaExists = (schema: string) => (db: NodePgDatabase) =>\n probe(db, `EXISTS (SELECT 1 FROM pg_namespace WHERE nspname = '${schema}')`)\n\n// Tables and indexes alike — both live in `pg_class`.\nconst relationsExist =\n (...relations: readonly (readonly [schema: string, name: string])[]) =>\n (db: NodePgDatabase) => {\n const tuples = relations.map(([schema, name]) => `('${schema}','${name}')`).join(\", \")\n return probe(\n db,\n `(SELECT count(*) FROM pg_class c\n JOIN pg_namespace n ON n.oid = c.relnamespace\n WHERE (n.nspname, c.relname) IN (${tuples})) = ${relations.length}`,\n )\n }\n\nconst columnsExist =\n (...columns: readonly (readonly [schema: string, table: string, column: string])[]) =>\n (db: NodePgDatabase) => {\n const tuples = columns\n .map(([schema, table, column]) => `('${schema}','${table}','${column}')`)\n .join(\", \")\n return probe(\n db,\n `(SELECT count(*) FROM pg_attribute a\n JOIN pg_class c ON c.oid = a.attrelid\n JOIN pg_namespace n ON n.oid = c.relnamespace\n WHERE a.attnum > 0 AND NOT a.attisdropped\n AND (n.nspname, c.relname, a.attname) IN (${tuples})) = ${columns.length}`,\n )\n }\n\nconst MIGRATIONS: readonly Migration[] = [\n {\n name: \"0001_init:schema\",\n sql: MIGRATION_0001_SCHEMA,\n isApplied: schemaExists(\"auth\"),\n },\n {\n name: \"0001_init:tables\",\n sql: MIGRATION_0001_TABLES,\n isApplied: relationsExist(\n [\"auth\", \"sessions\"],\n [\"auth\", \"ix_auth_sessions_user_sub\"],\n [\"auth\", \"login_state\"],\n [\"auth\", \"ix_auth_login_state_expires\"],\n ),\n },\n {\n name: \"0002_id_token\",\n sql: MIGRATION_0002_ID_TOKEN,\n isApplied: columnsExist([\"auth\", \"sessions\", \"id_token\"]),\n },\n {\n name: \"0003_forced_reauth\",\n sql: MIGRATION_0003_FORCED_REAUTH,\n isApplied: columnsExist([\"auth\", \"login_state\", \"forced_reauth\"]),\n },\n {\n name: \"0004_nonce\",\n sql: MIGRATION_0004_NONCE,\n isApplied: columnsExist([\"auth\", \"login_state\", \"nonce\"]),\n },\n {\n name: \"0005_retried\",\n sql: MIGRATION_0005_RETRIED,\n isApplied: columnsExist([\"auth\", \"login_state\", \"retried\"]),\n },\n {\n name: \"0006_pending_confirm\",\n sql: MIGRATION_0006_PENDING_CONFIRM,\n isApplied: columnsExist([\"auth\", \"sessions\", \"pending_identity_confirm\"]),\n },\n {\n name: \"0007_expected_identity\",\n sql: MIGRATION_0007_EXPECTED_IDENTITY,\n isApplied: columnsExist(\n [\"auth\", \"login_state\", \"expected_sub\"],\n [\"auth\", \"login_state\", \"expected_email\"],\n ),\n },\n]\n\nexport interface RunAuthMigrationsOptions {\n // When provided, grants this role SELECT/INSERT/UPDATE/DELETE on every\n // table in the `auth` schema — both ones this call just created and ones a\n // future boot's migrations will create. Omit for a single-role setup (the\n // fallback state of an environment that hasn't opted into a separate\n // migration role yet); passing it is what makes it safe for `db` to\n // connect as an admin/owner role while the app itself never does.\n readonly runtimeRole?: string\n}\n\nexport async function runAuthMigrations(\n db: NodePgDatabase,\n opts: RunAuthMigrationsOptions = {},\n): Promise<void> {\n for (const migration of MIGRATIONS) {\n try {\n if (await migration.isApplied(db)) {\n // Already there — do not issue the statement at all. See the comment\n // above MIGRATION_0001_SCHEMA for why relying on `IF NOT EXISTS` to make\n // it a no-op is not safe under every role.\n continue\n }\n await db.execute(sql.raw(migration.sql))\n } catch (err) {\n // Re-thrown, not swallowed: the caller decides what to do with a failed\n // migration. Naming the statement is what turns a bare \"permission\n // denied for database x\" into something you can actually act on; the\n // `cause` keeps the original Postgres error (code, detail, etc.) intact.\n const message = err instanceof Error ? err.message : String(err)\n throw new Error(`auth migration \"${migration.name}\" failed: ${message}`, { cause: err })\n }\n }\n\n if (opts.runtimeRole) {\n await grantRuntimeDefaultPrivileges(db, \"auth\", opts.runtimeRole)\n }\n}\n"],"mappings":";;;;;AAAA,SAAS,YAAY;AACrB,SAAS,eAAoC;AAC7C,SAAS,WAAW;AAWb,SAAS,kBAAkB,aAAkC;AAClE,QAAM,OAAO,IAAI,KAAK,sBAAsB,WAAW,CAAC;AACxD,SAAO,EAAE,IAAI,QAAQ,IAAI,GAAG,OAAO,MAAM,KAAK,IAAI,EAAE;AACtD;AAOO,SAAS,iBAAiB,aAA6B;AAC5D,SAAO,mBAAmB,IA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