# Client Architecture & API Integration

How every Substratal Hub client (macOS, Windows, iOS, Android, Linux, Web) talks to the Platform API (`openapi.yaml` 1.0.0-draft.33, API docs v1.9.2). These rules are identical everywhere; each `PLATFORM-SPEC.md` names the native libraries that implement them.

Spec references: [Conventions](https://compositecode.github.io/substratalapps.com/api-reference/conventions/) (especially [Versioning](https://compositecode.github.io/substratalapps.com/api-reference/conventions/#versioning)), [Auth](https://compositecode.github.io/substratalapps.com/api-reference/auth/), [Access Control](https://compositecode.github.io/substratalapps.com/access-control/), [Push Notifications](https://compositecode.github.io/substratalapps.com/api-reference/notifications/), [Billing](https://compositecode.github.io/substratalapps.com/api-reference/billing/), [Non-Functional Requirements](https://compositecode.github.io/substratalapps.com/non-functional-requirements/).

## 1. Layers

```
┌───────────────────────────────────────────────────────────────┐
│ UI (native views)  — screens from SCREEN-SPECS                │
├───────────────────────────────────────────────────────────────┤
│ Presentation state (view models / stores): screen state       │
│   machines idle → loading → loaded/empty/error; Capabilities  │
├───────────────────────────────────────────────────────────────┤
│ Domain services: Session · Directory · Access · Roles · Orgs  │
│   · Apps · Settings · Developer · Billing · Audit ·           │
│   Notifications (inbox, badge) · Push (device registration,   │
│   incoming push handling)                                     │
├───────────────────────────────────────────────────────────────┤
│ API client: auth, retries, idempotency, ETags, pagination,    │
│   error decoding, rate limits                                 │
├───────────────────────────────────────────────────────────────┤
│ Local store: secure credentials · response cache · device id  │
│   · preferences                                               │
└───────────────────────────────────────────────────────────────┘
```

**Generate the API client from `openapi.yaml`** for each platform: Swift (`swift-openapi-generator`), C# (Kiota or NSwag), Kotlin (`openapi-generator` + OkHttp/Ktor), Rust/Python for Linux (`openapi-generator`), TypeScript for Web (`openapi-typescript` + `openapi-fetch`). Screens never call HTTP directly. Generate from `openapi.yaml` 1.0.0-draft.9 or later: its server URL has no `/v1`, and every versioned operation declares the `Substratal-Version` header (the shared `ApiVersion` parameter). Set that header once, in the API client layer, rather than passing it per call (§4.1).

## 2. The Hub is a first-party Application

To receive push notifications the Hub must own devices, and a Device belongs to an Application. So the Hub is registered in the catalog as **`app_hub`** (slug `hub`):

| Field | Value | Why |
|---|---|---|
| `access_tier` | `free` | Every User gets a platform-managed `free` Entitlement at signup, which device registration requires (`allow()` must pass). |
| `receives_platform_notifications` | `true` | Security and account alerts push to Hub devices. |
| `visibility` | `internal` | Not shown as a launchable tile; APP-01 hides it. |
| Push credentials | APNs (topic `com.substratalapps.hub`, the shared iOS/macOS bundle id), FCM (Android, `com.substratalapps.hub`), Web Push (VAPID) | Configured once by staff in APL-07. |

The Hub still authenticates with **platform sessions** (it never mints app tokens for itself). If an admin disables someone's `app_hub` access, registration returns `403 entitlement_required`; the Hub then runs in inbox-only mode (no push) and says so in NTF-03.

## 3. Session lifecycle

| Token | Where it lives | Lifetime | Notes |
|---|---|---|---|
| Platform access token (JWT RS256) | Memory only | 15 min | `Authorization: Bearer` on every call |
| Platform refresh token (opaque, rotating) | OS secure store (Keychain, Credential Locker/DPAPI, Keystore, libsecret); Web: HttpOnly cookie via BFF | per spec | Persist the rotated token atomically before using the new access token |
| App token (per-app JWT) | Never stored | 5 min | Minted at launch only (APP-03) |
| MFA token | Memory | `expires_in` (~300 s) | Discard on success or expiry |
| Push device id (`dvc_…`) | Local preferences (not secret) | until deleted | Used to PATCH token rotations and to DELETE on "turn off" |

Rules:
1. **Single-flight refresh.** On `401 unauthenticated`, pause the queue, call `POST /auth/token/refresh` once, replay. Never refresh in parallel — reuse of a rotated token revokes the session and raises a `security.session_reuse_detected` alert.
2. **Proactive refresh** 60 s before expiry while in the foreground.
3. `401` on refresh or `session_revoked` → wipe credentials, show GLB-03 "Session ended", return to AUTH-01 keeping the destination.
4. **Sign out** = `POST /auth/logout`, then wipe secure store, cache, inbox cache and stored device id. The server deactivates this session's push devices (`session_revoked`); signing in again re-registers.
5. One account per device profile in v1. `test_mode` sessions (developer builds only) are stored separately with a persistent TEST indicator.

### 3.1 Web: the backend-for-frontend (BFF)

Browsers have no OS secure store, so the web Hub keeps the refresh token in a same-origin backend at `https://hub.substratalapps.com` (one Lambda behind CloudFront that also serves the Ops gateway, `/ops-api/*`). Everything else goes from the SPA **straight to the API** (CORS allows `https://hub.substratalapps.com` for every method with a User token; API Keys are refused from a browser with `400 api_key_in_browser`).

| Step | Call | Notes |
|---|---|---|
| Sign in / MFA | `POST /auth/login`, `POST /auth/mfa/verify` from the SPA, directly to the API | so the API sees the person's real IP for its per-IP limits and the Sessions list |
| Hand over the refresh token | `POST /bff/session` | sets `__Host-sub_rt` (`HttpOnly; Secure; SameSite=Strict; Path=/`); the SPA forgets the refresh token and keeps only the 15-minute access token, in memory |
| Refresh | `POST /bff/session/refresh` with `X-Substratal-CSRF` | the BFF calls `POST /auth/token/refresh` (with `Substratal-Version: 1`), rotates the cookie and returns the new access token. Single-flight **across tabs** with the Web Locks API (`navigator.locks`) |
| Sign out | `POST /bff/session/logout` | the BFF calls `POST /auth/logout`, clears the cookie and sends `Clear-Site-Data: "cache", "storage"` |

**Trusted client IP.** Refreshes and logouts reach the API from the BFF, so without help the API counts them against the BFF's IP and shows that IP in Sessions (ACC-04) and SEC-01. A first-party backend can forward the person's IP and user agent in signed headers: `X-Substratal-Client-IP`, `X-Substratal-Client-UA`, `X-Substratal-BFF-Timestamp` and `X-Substratal-BFF-Signature` (HMAC with a first-party secret held only by the BFF). With a valid signature the API uses them for per-IP rate limits, session records and the security log; anything else is ignored. They aren't in `openapi.yaml`, and native apps never send them. The web BFF should sign every call it makes for a person (OPEN-QUESTIONS #28).

## 4. Request conventions

| Concern | Client behavior |
|---|---|
| Base URL | `https://api.substratalapps.com` — the host root, with **no version in the path** (configurable: prod / staging / local devserver). Paths are the same in every API version. |
| API version | `Substratal-Version: 1` on every request. Required; see §4.1. |
| IDs | Opaque prefixed strings (`usr_ app_ org_ ent_ role_ key_ evt_ sbs_ dvc_ pcr_ ntf_ ndl_ tnt_ whk_ dlv_ ses_ sct_`; request ids are `req_…`). Only the prefix is ever interpreted (palette routing). `me` for `{id}` with a user token. |
| Idempotency | Generate a UUID v4 **when a create form opens**; send `Idempotency-Key` on submit and every retry. **Required** on personal and org entitlement grants and both Checkout endpoints; send it on every create POST, including `POST …/notifications`. Handle `idempotency_key_reused` (409) and `idempotency_key_in_flight` (409 → retry after 1 s). |
| Concurrency | Keep `ETag` from single-resource GETs and writes; send `If-Match` on PATCH/DELETE of Entitlements, Roles, Settings, AppSettings, Profile, Organizations, Users, Organization subscription coverage. On `409 version_conflict`: refetch, then **Reload** or **Re-apply**. |
| Pagination | Cursor: `limit` (50 desktop / 25 compact) + `cursor`; stop when `page.has_more` is false. Infinite scroll on touch; virtualized lists + "Load more" on desktop. Keep loaded pages on back-navigation. A cursor is bound to the filters and `sort` it was issued under (`400 invalid_cursor` otherwise): start over when either changes. |
| Counts | Send `include=total` on the **first page** of a list that shows a count (USR-01, ACX-05, APL-01, ORG-01/03, AUD-01, WHK-01/03, KEY-01, ROL-01, RPT-01, GLB-02 badges). The response adds `page.total` and `page.total_capped`; the count follows the list's filters and visibility and stops at 10,000 (`total: 10000, total_capped: true` → show "10,000+"). Don't send it on later pages: every page reports the same total, and cursors ignore `include`. Any other `include` value is `422`. |
| Filtering | List endpoints exclude terminal states (revoked entitlements, inactive devices, archived notifications, **retired Applications**) unless `status=…` / `review_status=…` or `include_inactive=true` is passed. Sorting is server-side only where the API offers `sort` (`GET /applications`: `created_at` / `-created_at`); elsewhere sort within the loaded page. |
| Errors | Decode `{error:{code,message,details}}`; map `code` → COPY-AND-STATES; `details.fields[].field` → form fields. Raw `message` only inside a "Details" disclosure with the request id. `400 api_version_required` / `unsupported_api_version` → §4.1. `405 method_not_allowed` is a client bug (wrong method for a path that exists): log it with `details.allowed` and show the generic error. |
| Rate limits | Ordinary sessions and API Keys: one bucket of 100 req/min. **Staff sessions** (a platform Role with at least one permission): `GET` at 600/min, everything else at 100/min. Endpoints with their own limits (`POST /users`, `POST /entitlements`, sends: 600/min per key, 60 notifications per recipient per app per hour, 10 device tests per device per hour) keep them. `RateLimit-Limit/Remaining/Reset` describe the bucket the request counted against; slow bulk work when `RateLimit-Remaining` < 20. On `429` honor `Retry-After` and show a countdown; back off background polling ×2 up to 5 min. |
| 501 | `not_implemented` → turn the feature's flag off for the session, log once, never show an error. |
| 503 | Reads auto-retry after `Retry-After`; writes never auto-retry (GLB-03 banner). `billing_unavailable` is a 503 on billing endpoints. |
| Timeouts | 10 s connect / 30 s read; reads retry twice with jitter; writes retry only with an Idempotency-Key. |
| Headers | `Substratal-Version: 1`; `User-Agent: Substratal-{platform}/{version} ({os})` (the API shows it in Sessions); `Accept-Language` from the active locale. |

### 4.1 API versioning

The API version is a **request header, not part of the URL**. Every endpoint lives at the host root (`POST https://api.substratalapps.com/users`), and the request names the version it was written against:

```
GET https://api.substratalapps.com/users/me
Authorization: Bearer eyJ…
Substratal-Version: 1
```

Because the version isn't in the path, a resource's URL never changes between versions. Routes, deep links, cache keys, `ETag` handling and stored URLs stay the same when the Hub moves to a new version; only the header value and the shapes that version defines change.

| Rule | Client behavior |
|---|---|
| One version per build | Each Hub build is written against exactly one API version, a **compile-time constant** (`1` today; whole numbers only). Never read it from remote config and never negotiate: there's no default version, so the server never moves a client to a new one. Moving to a new version is a code change, released as an app update. |
| Send it everywhere | The API client layer (middleware / interceptor / `DelegatingHandler` / `openapi-fetch` middleware) adds `Substratal-Version` to **every** request, including the auth calls (sign-in, MFA, refresh, logout) and requests a generated client builds by hand. Requests without it fail with `400 api_version_required` before authentication runs. |
| Exempt endpoints | `GET /health` (the GLB-03 connectivity probe), `POST /auth/oauth/token` (called by launched Applications, never the Hub), `/.well-known/*`, and SCIM under `/scim/v2` don't need the header. Sending it to them is harmless, so the shared middleware doesn't special-case them. |
| Check the echo | Every response to a versioned request echoes `Substratal-Version`. If it differs from what was sent, log it (no PII) — it means a proxy or a misconfigured environment. Don't change behavior on it. |
| `400 api_version_required` | Always a client bug (a request bypassed the middleware). Log `screen_id` + path, show the generic error, never "Update required". |
| `400 unsupported_api_version` | The server no longer serves this build's version (it passed its `Sunset` date) or the environment is wrong. `details.supported` lists the versions served. Stop all API traffic and show GLB-03 **Update required**. Re-check on foreground with one request. |
| `Deprecation` / `Sunset` headers | When a response carries `Deprecation` (RFC 9745), this build's version is deprecated; `Sunset` (RFC 8594) is the date it stops working (at least 6 months after deprecation). Record both, show GLB-03 **Update available** once per day with the sunset date, and send `api_version_deprecated{version}` telemetry. Mobile/desktop link to the store or updater; the Web app reloads to pick up the new build. |
| Additive changes | New optional fields, endpoints and enum values ship **within** a version, with no header change. Decoders must ignore unknown fields and map unknown enum values to an "other / unknown" case — never crash or drop the record. |
| Persistent caches | Tag persistent caches (§7) with the API version that wrote them; on launch, discard any cache written under a different version. |
| CORS (Web) | `https://hub.substratalapps.com` may call every endpoint with the person's User token. The API exposes `ETag`, `X-Request-Id`, `RateLimit-*`, `Retry-After`, `Audit-Hot-Window-Start`, `Substratal-Version`, `Deprecation` and `Sunset`, so the PWA behaves exactly like the native apps. API Keys are never used from the browser (`400 api_key_in_browser`). |
| Webhook payload version | A webhook subscription's `api_version` (a date such as `2026-10-05`, edited in WHK-02) fixes the shape of the payloads that subscription receives. It is **separate** from `Substratal-Version`; the Hub never derives one from the other, and labels it "Payload version" in the UI. |
| MCP | MCP clients don't send the header; the MCP server calls the API with the version its tools describe. Nothing for the Hub to do. |

**Paths in this spec** (`API-SCREEN-MAP.csv`, screen tables, flows) are written without a version prefix, exactly as in `openapi.yaml`. Older revisions of this package used `/v1/…`; those paths now return `404 not_found`, with no redirect.

### 4.2 Step-up and staff two-step verification

- **Staff must use two-step verification** (enforced from 2026-11-05 in production). `User.mfa_enrollment_required` is true for a staff User without TOTP. Until they enroll, their session can only read itself, enroll TOTP, change the password, sign out and read `GET /platform/settings`; everything else is `403 mfa_enrollment_required` → GLB-03 **Two-step required** → ACC-05. Capabilities treats admin permissions as unusable while it's true.
- **Step-up.** Operations marked `x-substratal-step-up` in `openapi.yaml` (deleting, suspending or erasing a User; assigning or removing a platform Role; creating a platform-scoped API Key; setting a key's rate limit; `PATCH /platform/settings`) need a second factor proved in the last 10 minutes. The access token's `mfa_verified_at` claim (Unix seconds) says when; if it's older than 600 s, show GLB-03 **Confirm it's you** *before* the call. If a call still returns `403 reauthentication_required`, show it then and retry once. `POST /auth/reauthenticate {code | recovery_code}` returns a new access token: replace the one in memory (web: in the SPA; the BFF's refresh keeps `mfa_verified_at`). Users without TOTP and API Keys are never asked.
- **Read-only maintenance.** When operators freeze writes, every non-`GET` returns `503 service_unavailable` with `details.reason: "read_only"` and `Retry-After: 300`; sign-in, refresh and app tokens keep working. Show the GLB-03 banner and disable write actions; superadmins are exempt.

### 4.3 Image uploads (avatars and Application icons)

The API hosts images at `https://assets.substratalapps.com`; the bytes never pass through the API.

1. Pick, crop square, and re-encode on the device (PNG, JPEG or WebP; avatar ≤ 2 MB, icon ≤ 1 MB and square; ≤ 2048 × 2048). Check size and type before uploading.
2. `POST /users/{id}/avatar/uploads` or `POST /applications/{id}/icon/uploads` with `{content_type, content_length}` → `ImageUpload {id, url, fields, content_type, max_bytes, expires_at}` (valid 5 minutes; 10 starts per caller per hour).
3. `POST` `multipart/form-data` to `url` with every entry of `fields`, then the file as the last field, named `file`. No `Authorization` or `Substratal-Version` header on this request: it goes to storage, not the API.
4. `POST …/uploads/{uploadId}/complete` → the updated Profile or Application with the new content-addressed URL. `422 invalid_image` (`details.reason`) or `404 upload_not_found` (expired or used) → start again from step 2.
5. Remove with `DELETE /users/{id}/avatar` / `DELETE /applications/{id}/icon`.

Web: allow the upload `url`'s host in `connect-src`, and `https://assets.substratalapps.com` in `img-src`.

### 4.4 Passkeys

Passkeys (WebAuthn) are a second factor next to TOTP, accepted at sign-in (AUTH-02), for step-up (GLB-03) and for staff two-step. RP ID `substratalapps.com`, RP name "Substratal"; user verification is always required; up to 10 per User.

| Ceremony | Calls |
|---|---|
| Register (ACC-04/05) | `POST /users/me/mfa/passkeys/registration-options` → `publicKey` creation options → platform create → `POST /users/me/mfa/passkeys {credential, name}`. A first MFA method needs a password sign-in in the last 10 minutes (`403 recent_sign_in_required`); a second needs step-up |
| Sign in (AUTH-02) | `MfaChallenge.methods` includes `passkey` → `POST /auth/mfa/passkey-options {mfa_token}` → platform get → `POST /auth/mfa/verify {mfa_token, passkey}` |
| Step-up (GLB-03) | `POST /auth/reauthenticate/passkey-options` → platform get → `POST /auth/reauthenticate {passkey}` |
| Manage (ACC-04) | `GET /users/me/mfa/passkeys`; `PATCH …/{passkeyId}` to rename; `DELETE …/{passkeyId}` (step-up) |

| Platform | API | Status |
|---|---|---|
| Web | `navigator.credentials.create/get` with `PublicKeyCredential.parseCreationOptionsFromJSON` / `parseRequestOptionsFromJSON` | **Supported**: `https://hub.substratalapps.com` is an allowed origin |
| iOS / macOS | `ASAuthorizationPlatformPublicKeyCredentialProvider(relyingPartyIdentifier: "substratalapps.com")`; Associated Domains `webcredentials:substratalapps.com` | Behind the `passkeys` flag until the API accepts native origins (OPEN-QUESTIONS #32) |
| Android | Credential Manager (`androidx.credentials`, `CreatePublicKeyCredentialRequest`); Digital Asset Links on `substratalapps.com` | Behind the flag; the signed origin is `android:apk-key-hash:…` (#32) |
| Windows | Windows Hello WebAuthn API (`webauthn.dll`) | Behind the flag (#32) |
| Linux | No platform passkey API | TOTP only; the passkey rows are hidden |

Errors: `passkey_invalid` (400 at registration, 401 at sign-in and step-up), `passkey_not_registered`, `passkey_already_registered`, `passkey_limit_reached` (409), `passkey_not_found` (404), `recent_sign_in_required` (403). Cancelling the OS prompt is not an error: fall back to the code field. Recovery codes come with the first MFA method, TOTP or passkey.

### 4.5 Bulk operations

`POST /users/bulk-invite`, `POST /users/bulk-suspend` and `POST /entitlements/bulk-update` act on up to **25** items per call. Send one `Idempotency-Key` per batch (required) and reuse it on a network retry. The response is `200` with one `{id | email, status, error?}` result per item, in request order: show per-row results, and retry only the failed rows, in a new batch with a new key. Each item follows its single call's rules, rate limit and audit; `bulk-suspend` is a step-up operation for the whole batch. Larger selections are split into batches of 25, run one at a time. Actions without a bulk endpoint (Resend invitation, inbox Mark unread / Archive) still run one request per row, at most 4 in parallel.

## 5. Capabilities (permission gating)

Computed on sign-in and on every foreground refresh:

```
GET /users/me                      → status, mfa_enabled, email_verified, plan, plan_sources
GET /users/me/roles                → platform role ids (+ implicit)
GET /roles?scope=platform          → role → permission keys (cache 1 h; 403 = no admin permissions)
GET /applications?owned=true       → owned apps → app-owner rights
GET /tenants                       → owned Tenant(s)
GET /organizations                 → memberships + my_role (org_admin → subscription rights)
```

Exposes `canListUsers`, `canManageUsers`, `canManageEntitlements`, `canManageRoles`, `canViewAudit`, `canManageApplications`, `canManageApiKeys`, `canManageWebhooks`, `canManageTenants`, `canManageBilling`, `canSendNotifications`, `canViewOperations` (`operations.view`), `canManageOperations` (`operations.manage`), `isStaff` (any platform permission: selects the 600/min read bucket), `ownsApps[]` (also grants that app's roles in ROL-01/02, push credentials, webhooks and deliveries), `ownsTenants[]`, `adminOfOrgs[]`, `plan`, `planSources[]`. Seeded platform roles include `superadmin` (everything, including both operations permissions) and `operator` (`operations.view` + `audit.view`). Navigation and every action read only from `Capabilities`; a `403` triggers a background refresh. The server is always the authority.

## 6. Push notifications and the inbox

### 6.1 What the Hub receives

| Kind | In the Hub inbox (NTF-01) | Pushed to Hub devices |
|---|---|---|
| Platform alerts (`security.*`, `account.*`) | yes | yes — `app_hub` opts in |
| Notifications sent by `app_hub` itself | yes | yes |
| Notifications from other Applications | yes (the User sees everything addressed to them) | no — they push to that app's own installs |

### 6.2 Provider per platform

The API supports **APNs, FCM and Web Push** only.

| Hub app | Provider | Notes |
|---|---|---|
| iOS / iPadOS | `apns` | `environment: sandbox` for development builds, `production` for TestFlight/App Store |
| macOS | `apns` | Same bundle id as iOS, `com.substratalapps.hub` (Universal Purchase), so the single `app_hub` APNs credential's `topic` covers both — see OPEN-QUESTIONS #3 |
| Android | `fcm` | Firebase project for `app_hub` |
| Web (PWA) | `web_push` | VAPID public key from `app_hub`'s credential, shipped in the web build config (it's public); iOS/iPadOS Safari only when installed to the Home Screen |
| Windows | none | No WNS in the API. Poll `unread-count` + new items and raise **local** app notifications; taskbar badge. See OPEN-QUESTIONS #2 |
| Linux | none | No push service on Linux desktops. Poll and raise local `GNotification`s |

### 6.3 Device lifecycle (iOS, macOS, Android, Web)

1. **Ask at the right moment** (NTF-04): after sign-in on mobile at the first meaningful moment, or when the person turns notifications on — never before sign-in.
2. On OS permission granted: obtain the token/subscription → `POST /users/me/devices {application_id: "app_hub", provider, token | subscription, environment, name, app_version}` → store the returned `dvc_` id.
3. **Re-register on launch at most once a day** (keeps `stale` deactivation at bay, re-attaches to the current session after sign-in).
4. **Token rotation** (APNs device token change, FCM `onNewToken`, `pushsubscriptionchange`) → `PATCH /users/me/devices/{deviceId}` with the new token.
5. **Turn off on this device** → `DELETE /users/me/devices/{deviceId}` and stop re-registering until turned on again. The global preference is `Settings.notifications.push` (SET-01); per app via AppSettings override (SET-02).
6. **Sign out**: the server deactivates the session's devices; the client also forgets the device id.
7. OS permission revoked → nothing to call; the provider reports the token invalid on next send and the server deactivates it. Settings shows "Blocked — Open system settings".
8. Max 20 active devices per User per app: older ones become `inactive (limit)` — nothing for the client to do.

### 6.4 Handling an incoming push

- Read the `substratal` block: `notification_id`, `application_id`, `source`, `category`, `action_url`.
- **Foreground:** show an in-app banner/toast (don't duplicate a system banner), refresh `unread-count`, prepend to the inbox if visible.
- **Tap:** `PATCH /users/me/notifications/{id} {state: read}`, then route: Hub route in `action_url` → navigate; other URL → open externally; none → NTF-02.
- **Action buttons** by category (COPY-AND-STATES "Push notification text"): e.g. `account.organization_invitation` → **Accept** calls `POST /organizations/{id}/members/me/accept` from the notification action (requires unlock/auth on mobile).
- Pushes are prompts, not truth: always refetch from the API. No ordering guarantee; `collapse_key` already collapses on device.
- Content is visible on lock screens — the Hub shows only what the API sent; it never adds details to a notification.

### 6.5 Badges and unread counts

`GET /users/me/notifications/unread-count` on launch, on foreground, after any push, after marking read, and every 60 s while visible (Windows/Linux also in the background while running). Badge = total `unread_count` (app icon, Dock, taskbar, PWA badge, Inbox nav item). Per-app counts drive the Inbox app filter.

### 6.6 Notification channels / categories

- iOS/macOS: register `UNNotificationCategory` per category with actions; `security.*` uses interruption level time-sensitive (requires the Time Sensitive capability).
- Android: channels **Security alerts** (high importance), **Account & invitations** (default), **App updates** (default); map by category prefix.
- Web/Windows/Linux: actions via the Notifications API / app notification buttons where supported.

## 7. Caching & offline

| Data | Cache | Freshness |
|---|---|---|
| Capabilities, own User/Profile/Settings, plan | persistent | launch + foreground |
| Applications catalog | persistent | 1 h, or pull-to-refresh |
| Own entitlements | persistent | launch, foreground, 60 s while APP-01 visible |
| Inbox (first page) | persistent, encrypted | launch, foreground, on push; 90-day retention mirrors the API |
| Subscription | memory | on BIL screens; poll after checkout |
| Prices (`GET /billing/prices`) | memory | per visit to BIL screens or the upsell sheet |
| Admin lists (users, access, audit, other people's notifications) | memory only | per visit |
| Secrets, app tokens, push credential key material | never | — |

Persistent caches carry the API version they were written under and are dropped when it changes (§4.1).

Offline: Home and Inbox render read-only from cache; launch disabled (needs a fresh app token). Writes require connectivity — no offline write queue (access changes must be immediate). Clear everything on sign-out.

## 8. Launching apps (APP-03)

- **Embedded (MVP):** `POST /auth/app-tokens {application_id, organization_id?}` → hand the 5-min token to the app per its integration contract.
- **Hosted / PKCE (Phase 3):** generate verifier/challenge (S256) on device, `POST /auth/oauth/authorization-codes`, open `redirect_uri?code&state` with the platform auth-session browser; validate `state`. The hosted sign-in page itself ships with the Web Hub.

## 9. Billing hand-off

- Checkout (the payment page) and the billing portal are hosted by the payment processor (Stripe) and opened in the system browser (or auth-session browser on mobile). `success_url` / `cancel_url` / `return_url` are `https://hub.substratalapps.com/billing/return?…` (or `/orgs/{id}/subscription?…`), which Universal/App Links route back to the native app.
- Returning to `success_url` doesn't mean coverage started: poll `GET …/subscription` every 2 s for up to 30 s until `plan = standard`, then refresh Capabilities and entitlements (new standard apps appear on Home).
- Checkout bodies take an optional `interval` (`month` | `year`, default `month`) chosen in the Monthly / Yearly picker. Prices come from `GET /billing/prices` (`PlanPrice {plan, interval, unit_amount, currency}`); `unit_amount` is in cents per user per interval, on both `PlanPrice` and `Subscription`. Never show the payment processor's name to users: say "payment page", "billing portal" or "payment processor".
- In-app purchase rules for iOS/Android are an open policy question (OPEN-QUESTIONS #10); upgrade buttons are flag-gated per store.

## 10. Feature flags

Read from the API: `GET /platform/settings` → `client_flags` (a signed-in caller gets its own mode's flags; operators change them in CFG-02, and changes reach every API server within 30 s). Fetch on launch and on foreground, cache the last value, and fall back to the build's defaults when the call fails. A flag missing from `client_flags` uses the build's default. Also folded into `Capabilities`:
`sso`, `passkeys`, `organizations`, `org_grants`, `app_profiles`, `app_settings`, `app_roles`, `webhooks`, **`notifications`** (inbox, devices, NTF-*), **`push`** (device registration per platform), **`push_credentials`** (APL-07), **`send_notifications`** (NTF-06), **`billing`** (BIL-01..03), `billing_upgrade_ios`, `billing_upgrade_android`, `tier_changes`, `hosted_launch`, `scim`, `app_registration_self_service`, `audit_export`, **`operations`** (web console: OPS-*, SEC-01, CFG-*), **`reports`** (RPT-01).

A `404`/`501` from a gated endpoint turns its flag off for the session. (`scim` gates the SCIM section of ORG-08.)

The same call gives `signup_open` (AUTH-03) and `announcement` (GLB-03 banner), with no sign-in needed.

## 11. Security checklist

- TLS only; OS trust store (no pinning).
- SCIM tokens (ORG-08) are secrets: shown once, held only in memory, never cached or logged.
- Secrets (API key secrets, webhook secrets, recovery codes, push key files being uploaded) exist only in memory; KEY-03 window protected from capture where the OS allows.
- Push key material (`.p8`, FCM JSON) is read from the picked file and sent once; never cached, logged or written to temp files.
- Clipboard marked sensitive and auto-cleared after 60 s.
- No tokens, emails, IDs, notification titles/bodies or device tokens in analytics or crash reports.
- Admin screens hidden in app-switcher snapshots; auto-lock after 15 min idle.
- Deep links and `action_url`s are untrusted input: validate before routing; emailed tokens are exchanged at once and stripped from history.

## 12. Telemetry (privacy-preserving)

Shared event names: `app_launch`, `sign_in_success`, `sign_in_mfa_required`, `sign_in_failed{code}`, `screen_view{screen_id}`, `app_tile_launch`, `access_toggle{direction,managed}`, `grant_created{source}`, `role_assigned`, `key_created{mode,intended_use}`, `secret_copied`, `palette_used{result_type}`, `push_permission{result}`, `device_registered{provider}`, `push_opened{category_prefix}`, `inbox_mark_all_read`, `checkout_started{subscriber_type}`, `checkout_completed{subscriber_type}`, `error_shown{code,screen_id}`, `api_version_deprecated{version}`, `api_version_unsupported{version}`. No PII; per-install hashed ids; opt-out in SET-01.

## 13. Themes

- **Inputs:** `Settings.theme` (light / dark / system) plus `app_hub` settings `light_theme` and `dark_theme`. Ids and defaults are in THEMES.md.
- **Launch:** apply the cached choice before first paint (web: the inline head script; native: read it from preferences before the first window), then reconcile with `GET /users/me/settings` and `GET /users/me/apps/app_hub/settings`.
- **Live changes:** follow OS light/dark changes while in *Match system*. When a choice changes on another device, apply it on the next settings refresh: launch, foreground, or `settings.updated` in the inbox stream if available.
- **Fallback:** an unknown id uses the default for its mode, and the error is never surfaced to the user. Platform high-contrast modes bypass the theme.

## 14. Help

Help is online, in the **Substratal Hub help center** at `https://specs.substratalapps.com/help/`. It's one site for every app, so a screen's help address is the same on all six platforms. Apps don't bundle or cache help content.

- **Base URL:** a build setting, defaulting to `https://specs.substratalapps.com/help/`, so a staging build can point at a preview.
- **Per screen:** every screen's Help action (the **?** button, or **Help** in the macOS menu bar) opens `screens/<screen-id-lowercase>.html`, for example `screens/usr-01.html`. Screen IDs come from SCREEN-SPECS.md. Console screens (domain C) are linked from the web app only.
- **Other pages:** `index.html` (help home), `guides/<slug>.html`, `tutorials/<slug>.html`, `faq.html`, `search.html`, and the API reference at `api/v<Substratal-Version>/index.html`, using the same version the app sends in the `Substratal-Version` header (§4.1). `search-index.json` is served with `Access-Control-Allow-Origin: *` for in-app help search.
- **Where it opens:** web, in a new tab. iOS / iPadOS, in `SFSafariViewController`. Android, in Custom Tabs. macOS, Windows and Linux, in the default browser.
- **Offline:** help needs a connection. The app doesn't show a stale copy.

The full list of URLs, and how an app reports which screens it has built, is in the help center's developer guide [Linking to help from an app](https://specs.substratalapps.com/help/developers/linking-to-help.html).
