# טיוטה: זהות ואבטחה במובייל

> טיוטת PR #69 — לא מוזגה. מקור: docs/mobile-identity-security.md · 34bdd4e · 2026-11-21.
> בגרסה הציבורית הושמטו מזהים תפעוליים ופרטי חשבון אישיים. קובץ המקור נשמר במאגר.

Reviewed **2026-11-21** against PR65 head `1d077f23c482b40fb91c6d7cdc725c19e9cebec4`, installed `@clerk/expo` 4.15.1, and the LinkNodes Energy production Clerk configuration. This document separates the requested product package, implementation work, and external activation requirements. It is not a production certification or a statement that an enterprise customer's identity provider is connected.

## Scope and existing authority

The authorized additions are Apple sign-in, device biometric sign-in/reverification, and Enterprise SSO/MFA foundations. Existing email/password and Google login, navigation, map, vehicle assets, tenant roles, and data residency remain unchanged by this design.

- Clerk application: `app_3LnOGGQ5iSA2KlooyXeTeuAHVoB` (LinkNodes Energy).
- Production instance: `ins_3LnYsreDptgUwIzLTcBbn0C2CbM`; development: `ins_3LnOGD8pvDUWRSdpldufQF6d7o6`.
- iOS bundle identifier: `com.linknodesenergy.app`; application scheme: `linknodes`.
- Authoritative Supabase project remains `dxeijkkmueuhvynvsgch` in Singapore. This change does not migrate or cut over the database.
- PostgreSQL active membership and RLS remain the authorization authority. Clerk organization membership alone never grants access to a LinkNodes tenant.

Source evidence: `lib/client-api/server.ts`, `lib/platform/server.ts`, `lib/client-api/account-rules.ts`, `lib/platform/plans.ts`, `lib/platform/types.ts`, `apps/mobile/lib/supabase.ts`, `apps/mobile/app.json`.

## Product package and activation status

| Capability                                                          | Personal / Family                  | Business                                                        | Enterprise                                                       | Activation boundary                                                                                                                          |
| ------------------------------------------------------------------- | ---------------------------------- | --------------------------------------------------------------- | ---------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------- |
| Email/password and Google                                           | Existing                           | Existing                                                        | Existing, subject to a customer's eventual SSO policy            | Preserve working flows and existing accounts.                                                                                                |
| Sign in with Apple                                                  | Requested                          | Requested                                                       | Available unless the customer's identity policy requires its IdP | Native registration, Apple capability, provider configuration and a new iOS build are required. Hosted/web Apple has additional credentials. |
| Face ID / Touch ID                                                  | Optional device credential         | Optional sign-in and step-up for sensitive details/actions      | Device convenience subject to organization policy                | Enroll a device-bound Clerk credential after authenticated sign-in; real native build and supported hardware required.                       |
| Authenticator app and backup codes                                  | Optional account protection        | Optional account protection                                     | Foundation for an eventual mandatory tenant policy               | Provider methods, enrollment, second-factor completion and recovery must all work. Enabling methods does not make MFA mandatory.             |
| SAML / OIDC SSO                                                     | Not a personal-account requirement | No new mandatory SSO policy                                     | Customer-specific connection                                     | Verify Clerk entitlement, organization/domain ownership, IdP configuration and successful pilot login before enforcement.                    |
| Roles and tenant isolation                                          | Existing owner account rules       | Existing `owner`, `admin`, `fleet_manager`, `finance`, `driver` | Same database authority                                          | Authentication additions must not expand membership, resource access or role permissions.                                                    |
| SCIM lifecycle, enterprise audit export and enforced session policy | No claim                           | No claim                                                        | Separate follow-up work                                          | SSO alone does not provide provisioning/deprovisioning, audit retention, SIEM export or a complete enterprise security program.              |

Do not market an enabled button, a plan name, or a local biometric prompt as mandatory server-enforced enterprise authentication.

## Live configuration snapshot before activation

Read through Clerk's configuration/schema, native applications and redirect tools; no credentials or personal user records were read.

```json
{
  "auth_biometric": {
    "enrollment_prompt_after_sign_in": false,
    "enrollment_prompt_after_sign_up": false,
    "used_for_sign_in": false
  },
  "auth_multi_factor": {
    "authenticator_app": { "enabled": false },
    "backup_code": { "enabled": false },
    "required_for_sign_in": false,
    "required_for_sign_up": false
  },
  "connection_oauth_apple": {
    "enabled": false,
    "authenticatable": true,
    "bundle_id": "",
    "client_id": "",
    "client_secret": "",
    "key_id": "",
    "team_id": "",
    "block_email_subaddresses": false
  }
}
```

Native API is already enabled. There is no registered production iOS application; the Android registration is `com.linknodesenergy.app`. Google is enabled. Preserve the existing custom session claim `{"role":"authenticated"}` used by Supabase.

Allowlisted redirects at inspection:

- `clerk://com.linknodesenergy.app.callback`
- `linknodes://oauth-callback`
- `exp://u.expo.dev/[expo-project-id-redacted]/--/hosted-auth-callback`

Existing enterprise connections and the application's Clerk subscription entitlement were **not verified** by the available tool surface. An organization membership limit is not evidence of a particular subscription. No enterprise connection, customer domain, or IdP MFA policy is claimed as configured.

The narrow provider activation is biometric sign-in plus optional authenticator/backup-code methods. Keep both global `required_for_sign_in` and `required_for_sign_up` false. Those switches affect the entire Clerk instance and introduce pending MFA-enrollment tasks for existing users; they are not per-Enterprise-plan policies. Review the provider's dry-run result before applying any configuration change, and record the observed post-change state in release evidence.

## Apple activation requirements

Native Apple authentication requires the exact App ID Prefix and bundle ID from the Apple Developer identifier, an enabled Apple connection, `expo-apple-authentication` and `expo-crypto`, the Apple authentication plugin/capability, and a new native build. The previous Apple enrollment reference is not proof of the Team ID or App ID Prefix. Confirm the actual identifier; do not substitute the enrollment reference.

Hosted/browser Apple additionally needs production Apple Services ID and key/client-secret configuration. Configure Apple's email relay sources for users selecting Hide My Email. Store credentials only in provider-managed secrets; do not put them in the repository, Expo public environment, logs or documentation. Test account creation and repeat sign-in on a real iPhone, including a hidden email address and cancellation.

Source: [Clerk native Apple authentication](https://clerk.com/docs/expo/guides/configure/auth-strategies/sign-in-with-apple).

## Face ID semantics and native build

Use `useBiometricCredentials` from `@clerk/expo/biometrics` with the `@clerk/expo-biometrics` native module. The device creates a private key, Clerk stores its public key, and biometric approval signs a one-time challenge. Enrollment must follow a valid authenticated session. Use `biometry_current_set` for credentials intended for reverification; changed biometric enrollment invalidates the device credential.

`signIn()` creates a real Clerk session; `reverify()` refreshes the current session token. Treat only `status === "complete"` as a completed reverification and check the returned effective level. A `needs_second_factor` result requires another verification method. Availability for sign-in alone does not prove reverification compatibility.

Expo Go cannot supply this native module. A JavaScript update cannot add it to an installed binary. This implementation sets `ios.infoPlist.NSFaceIDUsageDescription` explicitly: the installed Clerk 4.15.1 config plugin does not apply the `faceIDPermission` option described by the current guide. Expo introspection must confirm the generated Info.plist and Apple entitlement. Ship a new runtime/build and retain ordinary login and recovery when hardware, enrollment, the local key or provider configuration is unavailable. Physical-device testing is required; iOS Simulator cannot validate real biometric key enrollment. Do not store passwords or biometric samples.

Sources: [Clerk biometric flow](https://clerk.com/docs/expo/guides/development/custom-flows/authentication/biometric-sign-in), [biometric hook API](https://clerk.com/docs/reference/expo/native-hooks/use-biometric-credentials).

## Smallest safe per-tenant enforcement design

This original activation design is now implemented in the separate Development source release described in [identity-development-release.md](/draft-identity-development). The new migrations remain unapplied to hosted databases, and mandatory SSO still requires a supported session-bound provider assertion before activation.

1. **Explicit server policy.** Key an initially empty, server-owned policy registry by verified tenant ID. Include policy version, protected operations, required factor level, freshness window, expected Clerk organization and allowed enterprise connection. Derive tenant/role from existing database membership, never a plan value, organization ID or security flag supplied by a client. Do not automatically enforce policy merely because a tenant selects Enterprise.
2. **Keep verified authentication context.** Extend both `clientIdentity()` and `platformIdentity()` to retain server-verified `sessionId`, `has`, and factor age alongside the existing user-token-backed database client. Check active tenant membership first, then apply the policy immediately before protected reads/writes. The Development release now retains verified session context; the database policy enforces factor freshness across API and direct database paths.
3. **Use Clerk's server verification contract with an enrollment check.** Installed types support `has({ reverification: { level: "multi_factor", afterMinutes: 10 } })`, or `first_factor`/`second_factor` for other policies. However, the installed authorization helper deliberately falls back to first-factor freshness when the second-factor age is `-1`, even for `multi_factor` / `strict_mfa`. Mandatory first-plus-second-factor policy must separately require both verified ages to be finite, nonnegative and within the window, or accept a separately validated provider-supported equivalent for passkeys/IdP MFA. The helper alone does not require enrollment. Return `reverificationErrorResponse(policy)` from `@clerk/nextjs/server` when freshness is unmet, and direct unenrolled users to enrollment rather than looping the same challenge. The client obtains a refreshed token and retries. Missing, invalid, stale or incomplete assurance must deny the protected action; a client message claiming Face ID succeeded is insufficient.
4. **Establish SSO session evidence.** Verify the customer's connection/domain, bind it to the tenant's server-owned organization mapping, and test a fresh SP-initiated session. A verified email domain, linked SSO account or active organization is insufficient proof of the method used for this session. Current standard session claims do not establish the customer's IdP MFA policy. Before enforcing SSO at application APIs, define and verify a provider-supported, server-side session-evidence contract; fail closed when required evidence is missing. Never invent an `amr` or connection claim.
5. **Cover direct database paths.** A Next route guard alone does not protect authenticated PostgREST/RPC/storage access allowed by existing grants/RLS. Before announcing mandatory protection for sensitive Business or Enterprise data, enforce equivalent verified assurance at those boundaries or route the protected operations exclusively through an authorized server path. Keep RLS and tenant checks. The reviewed Development migrations implement this boundary with opt-in policy and lifecycle checks in the canonical tenant-role helper; hosted activation remains a separate gate.
6. **Pilot before enforcement.** Confirm enrollment and recovery for affected admins, test revoked sessions, expired assurance, cross-tenant attempts, direct API/RPC calls, staff offboarding and IdP outage. Keep an explicitly authorized, narrowly scoped recovery process with audit records. Activate one customer policy only after this evidence exists. Do not silently weaken a failed policy or disable MFA globally to recover one tenant.

Clerk documents signed factor verification age and backend reverification checks. Such freshness checks protect a time window; they do not by themselves bind one approval to one payment or other transaction. Transaction-specific approval needs a separately persisted, single-use correlation and must not be inferred from Face ID alone.

Sources: [server reverification](https://clerk.com/docs/guides/secure/reverification), [session claims](https://clerk.com/docs/guides/sessions/session-tokens). Installed evidence: `@clerk/shared`'s `sessionVerification.d.ts`, `authorization-errors.d.ts` and `authorization.js` (`checkReverificationAuthorization`); `@clerk/nextjs/server` exports the response helper.

## Enterprise connection prerequisites

Production self-serve SSO requires the relevant Clerk Pro/Business entitlement, Organizations, per-organization enablement and the `org:sys_entconns:manage` permission. A customer admin must control DNS and its IdP. SAML uses metadata/signing certificates; OIDC needs issuer/discovery, redirect registration and client credentials. Enable the admin UI only for the verified tenant/organization mapping and existing authorized roles. DNS possession must not automatically add a LinkNodes tenant membership.

Clerk delegates MFA to the IdP for ordinary SSO sign-in; its global required-MFA setting does not prove the IdP challenged the user. Confirm the customer's IdP MFA/conditional-access policy independently. SSO bypass creates a normal session and needs deliberate recovery authorization, strong verification and audit handling. SCIM and directory lifecycle are separate configuration and implementation work.

Sources: [self-serve SSO](https://clerk.com/docs/guides/configure/auth-strategies/enterprise-connections/self-serve-sso), [SSO bypass and MFA](https://clerk.com/docs/guides/configure/auth-strategies/enterprise-connections/sso-bypass).

## Validation and stop conditions

- Preserve existing email/password, Google, personal accounts, tenant switching, roles and the Supabase token claim.
- Native QA: Apple success/cancel/hidden email; biometric enroll/sign-in/reverify/cancel/revoke; app background/return; missing or changed device enrollment; required second factor; backup-code recovery; old installed runtime; Expo Go fallback.
- Enterprise QA: configured and unknown domains; pending session tasks; mapped and unrelated organizations; stale/missing assurance; role denials; replay/retry behavior; direct backend/database paths; offboarding and recovery.
- If Apple registration or provider credentials, signing access, production entitlements, a customer IdP, or a test device are unavailable, describe that exact blocker. Source readiness is not evidence of activation or a completed device login.
- Roll back a failed client release to its prior compatible runtime/update. Do not remove existing credentials, globally change MFA requirements, bypass DB authorization or migrate the database as an identity rollback.

## Implemented client release

The native source now adds Apple sign-in, an Enterprise work-email SSO entry, returning device-key biometric sign-in, server-offered TOTP/backup/SMS/email challenges, an account security screen, TOTP enrollment and recovery-code management, and a scoped opt-in device gate. Pending Clerk session tasks cannot open the application tabs. Required MFA setup stays on its dedicated route through recovery-code acknowledgement, even if Clerk activates the session during setup.

The optional app gate covers inactive content, invalidates its unlock lease on actual backgrounding or user/session/workspace replacement, and checks Clerk before returning protected content. Native iOS app-switcher blur covers active and pending sessions independently of that opt-in, including MFA setup/recovery outside the tabs. Sensitive Business profile and management actions request reverification when the user enabled the device policy. A sufficiently fresh Clerk verification may complete without another system scan; the UI states this. These client checks do not replace the server-side Enterprise policy described above.

`EXPO_PUBLIC_APPLE_SIGN_IN_ENABLED` and `EXPO_PUBLIC_MFA_ENABLED` default to false until the corresponding provider configuration is verified. A real pending `setup-mfa` task can still complete enrollment. Biometric enrollment uses Clerk's actual availability response rather than a local feature flag. Disabled methods never become a successful login or a local protected-account badge.

The app/runtime version is **0.2.0**, separating the new native dependencies from the existing **0.1.0** iPhone preview. The prior published update remains the rollback baseline: group `6caa4298-715c-439b-a966-46a5ae0bede4`, source `1d077f23c482b40fb91c6d7cdc725c19e9cebec4`. Do not deliver the new native functionality to that older runtime through an OTA-only update.

Validation includes real component-handler tests with mocked external boundaries, native TypeScript, dependency compatibility, Expo config introspection, and platform JavaScript exports. These checks do not establish physical Face ID, Apple login, a customer IdP login, a signed iPhone installation, or server-enforced mandatory tenant MFA. The identity test command is wired into the existing mobile CI job without removing its existing checks.

**Activation status, updated 2026-11-21:** Production entitlement dry runs still require the planned paid upgrade; no production method, billing plan or global MFA requirement was changed. Following explicit user approval, EAS CLI authentication was restored for **only `[account-redacted]`, Developer role**, and the intended Expo project was verified. iOS credential inspection found no signing credentials and no iOS build history; no native build or OTA update was published. Clerk **Development** now has biometric sign-in, authenticator/backup codes and Organizations enabled, with optional organization selection and global required-MFA disabled. The isolated `development-preview` profile enables the existing MFA screen. See [the Development activation record](/draft-identity-development) for server assurance, lifecycle code, tests and exact remaining gates. Apple native registration still needs the verified App ID Prefix for `com.linknodesenergy.app`; the enrollment reference cannot substitute for it. Customer SSO and hosted tenant-policy enforcement remain unactivated.

### Observed provider entitlement blocker

During the 2026-11-21 release work, a targeted Clerk dry run enabling biometric sign-in failed with `unsupported_subscription_plan_features`. A separate dry run enabling only authenticator-app MFA and backup codes failed with the same error. Neither patch was applied, and no subscription was upgraded. These methods therefore remain unavailable in the current production instance until its entitlement is resolved and activation is verified.

The mobile MFA enrollment panel uses `EXPO_PUBLIC_MFA_ENABLED=true` only after verified provider activation; its default is unavailable, without presenting a broken enrollment button or a subscription-upgrade prompt to end users. An actual Clerk `setup-mfa` pending-session task still permits the required enrollment UI. The flag controls presentation and rollout availability, never authorization. Existing email/password and Google sign-in remain available.
