@happyvertical/smrt-users 0.60.15 → 0.60.17

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 (50) hide show
  1. package/AGENTS.md +27 -0
  2. package/README.md +66 -0
  3. package/dist/chunks/{PasswordCredentialService-AL5GT_UL.js → PasswordCredentialService-D_evcc-I.js} +143 -5
  4. package/dist/chunks/PasswordCredentialService-D_evcc-I.js.map +1 -0
  5. package/dist/chunks/{TerminalAuthService-CgePPat5.js → TerminalAuthService-lE2aS7C_.js} +132 -8
  6. package/dist/chunks/TerminalAuthService-lE2aS7C_.js.map +1 -0
  7. package/dist/collections/SessionCollection.d.ts +30 -0
  8. package/dist/collections/SessionCollection.d.ts.map +1 -1
  9. package/dist/index.d.ts +3 -2
  10. package/dist/index.d.ts.map +1 -1
  11. package/dist/index.js +110 -11
  12. package/dist/index.js.map +1 -1
  13. package/dist/manifest.json +89 -1
  14. package/dist/models/Session.d.ts +45 -0
  15. package/dist/models/Session.d.ts.map +1 -1
  16. package/dist/models/index.d.ts +1 -1
  17. package/dist/models/index.d.ts.map +1 -1
  18. package/dist/operator.js +1 -1
  19. package/dist/services/MagicLinkService.d.ts +55 -0
  20. package/dist/services/MagicLinkService.d.ts.map +1 -1
  21. package/dist/services/OidcLoginService.d.ts +63 -0
  22. package/dist/services/OidcLoginService.d.ts.map +1 -1
  23. package/dist/services/PasswordCredentialService.d.ts +23 -0
  24. package/dist/services/PasswordCredentialService.d.ts.map +1 -1
  25. package/dist/services/SessionService.d.ts +8 -0
  26. package/dist/services/SessionService.d.ts.map +1 -1
  27. package/dist/services/index.d.ts +3 -3
  28. package/dist/services/index.d.ts.map +1 -1
  29. package/dist/smrt-knowledge.json +82 -5
  30. package/dist/smrt-knowledge.okf.md +3 -2
  31. package/dist/step-up.d.ts +57 -0
  32. package/dist/step-up.d.ts.map +1 -0
  33. package/dist/step-up.js +36 -0
  34. package/dist/step-up.js.map +1 -0
  35. package/dist/svelte/components/AccountSecurityPanel.svelte +55 -2
  36. package/dist/svelte/components/InviteUserModal.svelte +36 -33
  37. package/dist/svelte/components/MagicLinkForm.svelte +36 -2
  38. package/dist/svelte/components/OidcProviderButtons.svelte +25 -2
  39. package/dist/svelte/components/PasskeySignInButton.svelte +15 -2
  40. package/dist/svelte/components/SignInForm.svelte +30 -2
  41. package/dist/svelte/components/SignUpForm.svelte +30 -2
  42. package/dist/svelte/components/UserAvatar.svelte +29 -23
  43. package/dist/svelte/components/UserCard.svelte +68 -68
  44. package/dist/svelte/components/UserForm.svelte +19 -19
  45. package/dist/svelte/components/UserList.svelte +22 -17
  46. package/dist/svelte/components/UserMenu.svelte +90 -89
  47. package/dist/sveltekit.js +2 -2
  48. package/package.json +16 -12
  49. package/dist/chunks/PasswordCredentialService-AL5GT_UL.js.map +0 -1
  50. package/dist/chunks/TerminalAuthService-CgePPat5.js.map +0 -1
@@ -3,13 +3,13 @@
3
3
  "sensitiveFieldsExcluded": true,
4
4
  "generatedAt": "1970-01-01T00:00:00.000Z",
5
5
  "packageName": "@happyvertical/smrt-users",
6
- "packageVersion": "0.60.15",
6
+ "packageVersion": "0.60.17",
7
7
  "sourceManifestPath": "dist/manifest.json",
8
8
  "agentDocPath": "AGENTS.md",
9
9
  "sourceHashes": {
10
- "manifest": "f926ed4e03d57689d4beaf473de855616ce30ad5d1cc4d52618369e4e52ce171",
11
- "packageJson": "2a94346445c4cb03e72ada3a248990417bddc3386d10acd43b9cc252ed36d309",
12
- "agents": "97dc7344ebd89a89e596ebf6979bfbf05d98314463878f0ec41d37331d7cbedb",
10
+ "manifest": "bdd8c6f949a807218bf92072d48252cb612c1a14fa7c6c5d651e1f4ce763f312",
11
+ "packageJson": "d19643d4bee9f08676a4a4700198078cae0e0bd86c7c2a296bf90e4a7644e995",
12
+ "agents": "30b71cb25de701433b9b10de8968eaafb6f30e4dd933dc1328feac416c439d70",
13
13
  "moduleDoc:agents/permissions.md": "08a83623a45ef11b2d8596fff2c88cbfbb10bb71188e12e796037b61278bbe56",
14
14
  "moduleDoc:agents/oidc-provisioning.md": "b73f3fdaf61136720132a614c7e14237b7bd35f7bf5d43eabb29f565485803b9",
15
15
  "moduleDoc:agents/mobile-auth.md": "25e85e83f43e3a46383a92fa809f3a003b4545c3026e78dbe1bccbbc35161e18",
@@ -25,6 +25,7 @@
25
25
  "./operator",
26
26
  "./permission-registry",
27
27
  "./playground",
28
+ "./step-up",
28
29
  "./svelte",
29
30
  "./sveltekit"
30
31
  ],
@@ -2323,12 +2324,15 @@
2323
2324
  "findChildren",
2324
2325
  "findValidSession",
2325
2326
  "getSessionData",
2327
+ "markReauthenticated",
2328
+ "recordStepUpIntent",
2326
2329
  "revokeChildren",
2327
2330
  "revokeSession",
2328
2331
  "revokeUserSessions",
2329
2332
  "revokeUserSessionsByAuthMethod",
2330
2333
  "setSessionData",
2331
2334
  "setSessionTenant",
2335
+ "takeStepUpIntent",
2332
2336
  "touch"
2333
2337
  ],
2334
2338
  "methodSignatures": [
@@ -2397,6 +2401,25 @@
2397
2401
  ],
2398
2402
  "returns": "Promise<T | undefined>"
2399
2403
  },
2404
+ {
2405
+ "name": "markReauthenticated",
2406
+ "async": true,
2407
+ "params": [
2408
+ "sessionId: string",
2409
+ "options?: object"
2410
+ ],
2411
+ "returns": "Promise<Date | null>"
2412
+ },
2413
+ {
2414
+ "name": "recordStepUpIntent",
2415
+ "async": true,
2416
+ "params": [
2417
+ "sessionId: string",
2418
+ "intent: Record<string, unknown>",
2419
+ "options?: object"
2420
+ ],
2421
+ "returns": "Promise<boolean>"
2422
+ },
2400
2423
  {
2401
2424
  "name": "revokeChildren",
2402
2425
  "async": true,
@@ -2452,6 +2475,15 @@
2452
2475
  ],
2453
2476
  "returns": "Promise<boolean>"
2454
2477
  },
2478
+ {
2479
+ "name": "takeStepUpIntent",
2480
+ "async": true,
2481
+ "params": [
2482
+ "sessionId: string",
2483
+ "options?: object"
2484
+ ],
2485
+ "returns": "Promise<Record<string, unknown> | null>"
2486
+ },
2455
2487
  {
2456
2488
  "name": "touch",
2457
2489
  "async": true,
@@ -2521,6 +2553,20 @@
2521
2553
  "reason": "not listed in api.include",
2522
2554
  "objectName": "@happyvertical/smrt-users:SessionCollection"
2523
2555
  },
2556
+ {
2557
+ "kind": "api",
2558
+ "operation": "markReauthenticated",
2559
+ "code": "not-included",
2560
+ "reason": "not listed in api.include",
2561
+ "objectName": "@happyvertical/smrt-users:SessionCollection"
2562
+ },
2563
+ {
2564
+ "kind": "api",
2565
+ "operation": "recordStepUpIntent",
2566
+ "code": "not-included",
2567
+ "reason": "not listed in api.include",
2568
+ "objectName": "@happyvertical/smrt-users:SessionCollection"
2569
+ },
2524
2570
  {
2525
2571
  "kind": "api",
2526
2572
  "operation": "revokeChildren",
@@ -2563,6 +2609,13 @@
2563
2609
  "reason": "not listed in api.include",
2564
2610
  "objectName": "@happyvertical/smrt-users:SessionCollection"
2565
2611
  },
2612
+ {
2613
+ "kind": "api",
2614
+ "operation": "takeStepUpIntent",
2615
+ "code": "not-included",
2616
+ "reason": "not listed in api.include",
2617
+ "objectName": "@happyvertical/smrt-users:SessionCollection"
2618
+ },
2566
2619
  {
2567
2620
  "kind": "api",
2568
2621
  "operation": "touch",
@@ -6675,9 +6728,11 @@
6675
6728
  "getData",
6676
6729
  "getIdleSeconds",
6677
6730
  "getPermissionCeiling",
6731
+ "getReauthenticatedAt",
6678
6732
  "isExpired",
6679
6733
  "isLayered",
6680
6734
  "isRevoked",
6735
+ "isStepUpEligible",
6681
6736
  "isValid",
6682
6737
  "recordActivity",
6683
6738
  "removeData",
@@ -6717,6 +6772,10 @@
6717
6772
  "name": "getPermissionCeiling",
6718
6773
  "returns": "string[] | null"
6719
6774
  },
6775
+ {
6776
+ "name": "getReauthenticatedAt",
6777
+ "returns": "Date | null"
6778
+ },
6720
6779
  {
6721
6780
  "name": "isExpired",
6722
6781
  "returns": "boolean"
@@ -6729,6 +6788,10 @@
6729
6788
  "name": "isRevoked",
6730
6789
  "returns": "boolean"
6731
6790
  },
6791
+ {
6792
+ "name": "isStepUpEligible",
6793
+ "returns": "boolean"
6794
+ },
6732
6795
  {
6733
6796
  "name": "isValid",
6734
6797
  "returns": "boolean"
@@ -6839,6 +6902,13 @@
6839
6902
  "reason": "not listed in api.include",
6840
6903
  "objectName": "@happyvertical/smrt-users:Session"
6841
6904
  },
6905
+ {
6906
+ "kind": "api",
6907
+ "operation": "getReauthenticatedAt",
6908
+ "code": "not-included",
6909
+ "reason": "not listed in api.include",
6910
+ "objectName": "@happyvertical/smrt-users:Session"
6911
+ },
6842
6912
  {
6843
6913
  "kind": "api",
6844
6914
  "operation": "isExpired",
@@ -6860,6 +6930,13 @@
6860
6930
  "reason": "not listed in api.include",
6861
6931
  "objectName": "@happyvertical/smrt-users:Session"
6862
6932
  },
6933
+ {
6934
+ "kind": "api",
6935
+ "operation": "isStepUpEligible",
6936
+ "code": "not-included",
6937
+ "reason": "not listed in api.include",
6938
+ "objectName": "@happyvertical/smrt-users:Session"
6939
+ },
6863
6940
  {
6864
6941
  "kind": "api",
6865
6942
  "operation": "isValid",
@@ -8242,7 +8319,7 @@
8242
8319
  "polymorphicAssociations": 0,
8243
8320
  "uuidColumns": 162
8244
8321
  },
8245
- "agentDoc": "# @happyvertical/smrt-users\n\nMulti-tenant identity, RBAC, hierarchical tenants, sessions, and SvelteKit auth.\n\n## Modules\n\nRead only the module relevant to the change; protocol and provisioning details\nare not prerequisites for unrelated user-package work.\n\n| Module | Scope | Module doc |\n|---|---|---|\n| `src/permission-registry.ts` | portable permission metadata registration; same root/service singleton, no authority grants | [agents/permissions.md](agents/permissions.md#portable-metadata-registry-4765) |\n| `src/services/PermissionResolver.ts` | permission precedence, inherited memberships, guards, RLS, role seeding | [agents/permissions.md](agents/permissions.md) |\n| `src/services/OidcLoginService.ts`, collections and OIDC handlers | identity reconciliation, transaction boundaries, migration readiness | [agents/oidc-provisioning.md](agents/oidc-provisioning.md) |\n| `src/services/MobileAuthService.ts` | mobile handshake, bearer sessions, bootstrap extension boundary | [agents/mobile-auth.md](agents/mobile-auth.md) |\n| `src/services/TerminalAuthService.ts`, `src/services/LoginAttemptLimiter.ts`, `src/collections/LoginAttemptCollection.ts` | terminal approval concurrency, shared login budget and lockout (#3273), retry-safe database fixtures | [agents/terminal-auth-testing.md](agents/terminal-auth-testing.md) |\n| `src/services/DeviceCredentialService.ts` | per-person PIN layered on a device session (#3276), verifier seam for other credential kinds | this file, \"Security boundaries\" |\n| `src/services/PasswordCredentialService.ts`, `src/sveltekit/password-handlers.ts` | email + password sign-in and password lifecycle (#3274); shared scrypt in `credential-hash.ts` | this file, \"Security boundaries\"; README \"Password sign-in\" |\n| `src/services/PasskeyCredentialService.ts`, `src/sveltekit/passkey-handlers.ts`, `src/svelte/passkey.ts` | passkey (WebAuthn) sign-in and passkey lifecycle (#3275); library does all verification | this file, \"Security boundaries\"; README \"Passkey sign-in\" |\n| `src/services/TenantInvitationService.ts`, `src/services/MailboxAuthenticationService.ts` | exact-role invitations, preserved identity, one-use generations and embedded transaction send budgets | [agents/family-invitations.md](agents/family-invitations.md) |\n| `src/retention.ts` | expired session/token/CLI-auth reaping and retention sweep wiring | [agents/retention.md](agents/retention.md) |\n\n## Models and authority\n\n- Users are global; tenant access comes through Membership (unique user/tenant).\n User email is normalized and globally unique through readonly nullable\n `emailKey`. `profileId` is a unique cross-package reference: at most one User\n owns each non-null Profile.\n- Tenant uses STI and a materialized hierarchy, maximum depth 10.\n `hierarchyPath`/`hierarchyLevel` are derived from `parentTenantId` by\n `Tenant.save()` on every save (any caller-supplied value is recomputed) and\n descendants are re-materialized when they change; never hand-maintain them.\n Legacy rows are backfilled with `smrt db:materialize-tenant-hierarchy`\n (`materializeTenantHierarchy()`). Tests that need a corrupt path must write it\n with raw SQL (#3036).\n- Role with `tenantId = null` is available to all tenants; `isSystem` prevents\n deletion. `inheritsToDescendants` is opt-in. Seed owner/admin/member/viewer\n through `RoleCollection.seedSystemRoles()` at application initialization.\n- Group roles apply only in their own tenant. Use `getGroupIdsForTenant()`,\n never cross-tenant `getGroupIds()`, for authorization.\n- Upward visibility is opt-in and read-only: `permissions.ancestorRead`\n ({ roles, collections, maxDepth? }) lets a DESCENDANT membership contribute\n declared `<collection>.read` at an ancestor, only when no membership resolved\n there, intersected with BOTH the role's own catalog grants and the\n principal's effective permissions in that descendant, and only for SYSTEM\n roles (a tenant-scoped role sharing a declared slug is ignored). Off by default, never\n write, never lateral, and never row visibility — sibling rows stay scoped by\n tenancy/RLS. Read the permissions module before changing it.\n- Membership DENY always wins. Direct inactive membership blocks inherited\n authority; a direct active membership pins resolution instead of unioning it\n with ancestors. Read the permissions module before changing these rules.\n- AccessRequest has no generated API/MCP/CLI operations; access it through\n `AccessRequestService`. Its JSON field is `requestContext`, not reserved\n slug-scoping `context`.\n\n## Security boundaries\n\n- Generated REST/MCP operations on identity/RBAC models are list/get only.\n Route authentication does not authorize authority mutations, and these models\n are not tenant-scoped. Use permission-gated services or explicitly checked\n consumer handlers. Generated CLI is list/get or closed (`cli: false` for\n credential/grant models) because agents shell out to it; a `cli` without\n `include` is full CRUD (#3742). Their catalog slugs stay full via\n `USERS_AUTHORITY_CATALOG_MODELS`. Preserve the registry assertions in\n `security-audit-1400.test.ts` and `issue-3742-cli-surface-lockdown.test.ts`.\n- Resource guards take the resource tenant, not the session tenant. Omit a\n session membership when targeting a different tenant; mismatches fail closed.\n `loadSessionContext().tenantAuthorization` must be checked by required-tenant\n consumers: null membership can represent inherited authority.\n- Sessions use secure UUIDs; TTL is seconds (default seven days). Access marks\n expired sessions EXPIRED. Magic-link tokens are single use.\n- `Session.authMethod` is server-set at mint time and never read from the\n client; every mint site in this package sets it. A session with\n `parentSessionId` is valid only while its parent validates\n (`loadSessionContext` enforces this; there is no FK cascade by design), may\n not switch to a tenant other than the parent's, and is revoked with its\n parent by `destroySession`.\n- Credential sign-ins reserve through `LoginAttemptLimiter` BEFORE credential\n work and key the subject on the submitted identifier, never a resolved user,\n so unknown and wrong take the same path. Reservations are fail-closed: keep\n them on failure, release on success or abort, never skip the reserve.\n Limiter writes are raw SQL and bypass the change feed; the audit sink is the\n observability seam, and it must never throw into the sign-in path.\n Subject and source budgets are sized independently (#3531); `source: false`\n ignores the source key, so a reservation then needs a subject (fail closed).\n The `source-locked` audit entry never carries a subject or caller metadata.\n- `DeviceCredentialService` accepts a person credential only from a\n first-class session whose `authMethod` is a device-enrollment method\n (`terminal` by default) and that the host's `assertEnrolledDevice` confirms.\n A layered or PIN session can never administer PINs regardless of\n permissions. PIN hashes carry a per-row salt and the configured pepper;\n treat an unset pepper as a production misconfiguration.\n- A person session carries the PERSON's authority (resolved from their own\n membership on every load), never the device account's. `Session.data` keys\n in `SESSION_DATA_KEYS` are server-set controls enforced by the model:\n `permissionCeiling` only ever intersects (malformed fails closed to none)\n and suppresses `superAdminBypass`/`systemContext`; `absoluteExpiresAt`\n bounds `extend()` and `isValid()`; `idleSeconds` overrides the resolving\n service's TTL policy. Never write them from client input. The ceiling is a\n sign-in snapshot; `singleOccupant` revokes other children only AFTER a\n successful mint. A `mustReset` sign-in mints with an empty ceiling and\n `setPin` ends that session; do not grant it authority another way.\n- `UsersPasswordCredential` is one row per person, sensitive, with no\n generated surface; `PasswordCredentialService` and its handlers are its only\n session-authorized read/write paths. The separate Node `./operator` entrypoint\n provisions new PostgreSQL owners from trusted database custody, atomically;\n never mount it in a browser/REST/MCP handler. Exact retries verify existing\n credentials without writes; partial/conflicting identities fail closed.\n See README \"Trusted deployment owner provisioning\".\n Sign-in normalizes the email like `emailKey`, reserves\n before work, always runs one scrypt verify (dummy hash when absent), never\n creates a user, and maps every non-rate-limit refusal to one\n `PasswordCredentialError`. It re-checks the credential after the mint (a\n rehash that keeps row and version is confirmed by re-verifying); the\n parameter-upgrade write is a guarded UPDATE that must never replace a\n rotated password, and verification against a weaker stored hash is padded\n to the policy's scrypt cost. Self-service writes are guarded on the proven\n credential (first set insert-only); session sweeps run before and after\n each write. Self-service needs the current password except for a first\n set; `users.password.manage` follows the PIN's single-tenant target\n rule and never resets the actor's own. Layered sessions never manage\n passwords; a `mustChange` sign-in mints an empty ceiling.\n `replaceForgottenPassword` (#3905, opt-in `recovery`) is the only\n self-service write without the current password: it decides on the stored\n session row (owner, first-class, no ceiling, listed non-password/pin\n `authMethod`, fresh `outOfBandProofAt` stamp) and ends every session,\n its own included. Never set that stamp from client input.\n- `UsersPasskeyCredential` (many per person) and `UsersPasskeyChallenge` (consumed\n challenge ledger) are sensitive with no generated surface;\n `PasskeyCredentialService` and its handlers are the only paths. Verification is\n `@simplewebauthn/server`, loaded on first use (its `reflect-metadata` polyfill is process-wide) and external in the build; never hand-roll COSE/CBOR. Sign-in reserves on\n the submitted credential id before any work, requires user verification, checks\n user handle and a strictly advancing counter (`reason: 'counter'`), mints, then\n re-checks with a guarded counter UPDATE; a ceremony is an HMAC-signed\n `ceremonyId` consumed into the unique ledger (replay = refuse; set\n `challengeSecret` for multi-process). Unique arbiters are\n `INSERT … ON CONFLICT DO NOTHING`, never a caught constraint error. Register and\n self-remove need a session authenticated within `freshSessionSeconds`, decided\n on the stored row (`Session.getAuthenticatedAt()`: server-set\n `data.authenticatedAt`, which tenant-switch rotation carries forward, else\n `created_at`; malformed fails closed; `setSessionData` refuses the key),\n first-class, no ceiling, and its STORED `authMethod` in `freshAuthMethods` (default password/passkey/oidc/magic-link; never `terminal`, whose approval mints a fresh session for any holder of a stale one, nor `pin`); self list/rename also refuse a ceiling; `users.passkey.manage` follows the PIN's\n single-tenant rule, and `removeAllPasskeys` is admin-only, never self. Sessions\n end before and after every removal; `SESSION_DATA_KEYS.passkeyCredentialId` is\n server-set (`setSessionData` refuses it). State-changing handlers require\n `application/json` (415). Challenge rows are reaped only 10 minutes past expiry\n (clock skew).\n- A layered session whose tenant differs from its parent's never loads (null\n is allowed: narrower). Limiter rows carry `retain_until`; retention must\n not fall back to a process-wide horizon.\n- `Session.parentSessionId` is the parent's bearer: sensitive, never a\n `list()` filter (raw-SQL id reads, which also keep revocation sweeps free of\n caller list bounds), never serialized to clients. `users.pin.manage` reaches\n only people whose every active membership is in the actor's tenant (the PIN\n is global per person). A sign-in re-checks the verified\n credential generation AFTER the mint (`stillValid`); keep that ordering.\n Operation guards deny outside a session's ceiling; `loadPersonSession`\n re-checks device enrollment.\n- Tenant switching verifies active membership before writing and rotates the\n session ID for non-null targets, revoking the old session. Persist the returned\n `SwitchTenantResult.sessionId`; `switchSessionTenant()` updates the cookie and\n preserves its security settings. Failed switches mutate nothing; null clears\n do not rotate, and layered sessions never rotate (a replacement would escape\n the revocation sweeps they depend on). Layers do not nest. `SessionCollection.setSessionTenant()` is unguarded and must\n never receive an untrusted tenant ID.\n- OIDC provisioning is atomic and fail-closed. Preserve exact issuer/subject\n identifiers, claim-source email verification, unique global Person ownership,\n and transaction-bound reconciliation. Read the OIDC module and canonical\n scenario matrix before changing any provisioning path.\n\n## Entry points and validation\n\n`src/sveltekit/` owns `createSessionHandler`, `createSessionCookie`,\n`destroySessionCookie`, and `switchSessionTenant`. Use README integration examples\nrather than copying application setup into these instructions.\n\nFrom the repository root:\n\n```bash\npnpm --filter @happyvertical/smrt-users test\npnpm --filter @happyvertical/smrt-users typecheck\npnpm --filter @happyvertical/smrt-users test:postgres\n```\n\nStart with the relevant test file via `test -- src/__tests__/<file>.test.ts`.\nRun `test:postgres` for RLS, principal context, OIDC, or terminal-auth database\nchanges. `typecheck` includes Svelte accessibility checks; plain `tsc` is\ninsufficient. Follow root knowledge freshness checks before shipping.\n\n## Pending invitations\n\n`TenantInvitationService.create({ db: tx, transaction: 'caller' }).prepare({\ntenantId, email, roleSlug })` is a trusted host integration seam. The caller\nmust authorize the destination tenant and system role, serialize its invitation\nscope, and own the entire transaction. It prepares only pending User and\nMembership records, with a canonical global Person and email reservation;\nit never proves email ownership, activates access, sends email, or mints login\ncredentials. Existing canonical User/Profile links remain unchanged; unowned\nsame-email Profiles require explicit reconciliation. Pending retries reuse rows,\nactive memberships remain active with their existing role, and inactive or\nconflicting memberships fail closed. Caller failures must roll back the whole\ntransaction; retry identity uniqueness conflicts only after rollback. Run the\nprofile/user email-key backfills before using this service.\n\n`issue({ membershipId })` requires the host to authorize that exact destination\nand returns a signed single-use `{ membershipId, token, expiresAt }`; secure\ndelivery is the host’s responsibility (no email is sent). Configure `secret` and\noptional `tokenExpiry` (1–604800 seconds, default one day) at service creation.\n`accept({ membershipId, token, sessionId, expectedUserId? })` consumes the tenant\ngrant only after validating an independently authenticated, active exact User's\nstored first-class OIDC, magic-link, password or passkey session. Layered,\npermission-ceiling, terminal and unknown sessions fail closed. It activates only\nthe Membership; reuse/switch that session through canonical session APIs.\nNever mint global identity sessions from an operator-copyable invitation.\n\nFor a new pending User, wire `authorizeOidcOwner(context, { membershipId, token })`\nonly into the canonical protocol-verified OIDC `authorizeProfileOwner` callback.\nIt requires the exact caller transaction, strict `email_verified: true` and the\nexact canonical invitee email, consumes the grant and activates pending User\nand Membership atomically before returning `{ profile, user, tenantId, membershipId }`.\nArbitrary claims must never reach this trusted callback seam. The canonical\nbinder still verifies ownership and issuer/subject authority before commit.\nThe signed scope fixes user, profile, tenant, membership and role; expiration,\nreplay, changed bindings, inactive membership and suspended users fail closed.\nNonce consumption and activation roll back together. `TenantInvitationError`\nis an expected 400/403 refusal;\n`MagicLinkError` represents invalid, expired or replayed proof. Database failures\nremain distinct. Treat tokens as secrets, prefer URL fragments and POST bodies,\nand never log or persist a copy outside the canonical token ledger.\n\n\n## Independent emailed mailbox authentication\n\n`MailboxAuthenticationService.create({db:tx,transaction:'caller',secret,loginLimiter})`\nrequests and verifies returning-client login without creating identities/sessions.\n`request({email,sourceKey,deliver})` returns only `{requested:true}` for known,\nunknown, malformed, pending, inactive or unauthorized accounts. The trusted server\n`deliver({email,token,expiresAt})` callback sends only to the eligible canonical\nactive User's email; never expose a proof in HTTP responses/operator UI/logs,\nincluding development. Ten-minute one-use proofs bind immutable User/Profile ids.\n`authenticate({token,expectedUserId?,sessionId?})` rechecks canonical identity and\nactive tenant membership before consuming proof; returns only verified\n`{userId,profileId,tenantId}` for the host's canonical magic-link session mint.\nExisting signed-in identity must match; supplied sessions cannot have a parent,\npermission ceiling, terminal/PIN/unknown method, or inactive principal.\n\nFor pending invitation onboarding, `requestMailboxAuthentication({membershipId,\ntoken:projectGrant,sourceKey,deliver})` inspects but never consumes the signed\nproject grant, then delivers a DIFFERENT mailbox proof to the fixed invitee.\nOnly `{expiresAt}` is returned. `authenticateMailbox({membershipId,\ninvitationToken:projectGrant,token:mailedProof,expectedUserId?,sessionId?})` claims\nBOTH proof nonces and activates pending canonical User/exact Membership in the\nsame caller transaction. Mailbox proof issuer binds all invitation ids, role and\nSHA256 of the exact grant. A copied operator-visible grant cannot authenticate\nidentity. Repeated email requests do not burn the grant; only the first completed\nauthentication can claim it. Existing active-session/OIDC paths remain supported.\n\nAll refusals/caller failures must roll back the whole caller transaction. Mail\ntransport must reject on failure. Delivery is an external effect before commit:\na successfully delivered but rolled-back proof is unusable; retry may send another\nmail. No session/authentication is valid without committed proof claims. The host\nmust set a bounded transport timeout and never return transport payloads/secrets.\nNo generic outbox/provider is required; compose the existing SDK email transport.\n\nBoth mail request operations REQUIRE a root-executor canonical\n`LoginAttemptLimiter` passed as `loginLimiter`; missing limiters fail before\nnonce/budget writes or delivery. Completion-only operations may omit it. Supply\nthe limiter independently from the caller transaction so\ncaller rollbacks cannot release send budgets (SQLite single-connection fixtures\ncannot prove that production-pool separation). `sourceKey` is a trusted server\nclient-address key, never request-controlled forwarded headers; limiter hashes\nand peppers it, never stores raw addresses/email. Each request retains its budget\nthrough window expiry via `retainOnSuccess`, regardless of account eligibility.\nHandle `LoginRateLimitError` with the same generic request response plus retry\npolicy. Returning request has a 250ms response floor; delivery latency remains\ntransport-dependent, so do not claim constant timing. Malformed/expired/replayed\nproofs raise `MagicLinkError`; invitation binding/status refusals also use\n`TenantInvitationError`. Database/transport faults remain distinguishable server\nfailures. Never swallow an error and commit a partially consumed transaction.\n\n`MagicLinkService.inspect()` validates signed live nonce without claiming it;\nit is preparation, never authentication. `verify()` remains the atomic claim.\nOptional generated signed `subject` binds immutable identity; legacy callers\nwithout a subject retain their existing result shape.\n\nFocused matrix: `mailbox-authentication.test.ts` runs in memory SQLite by default;\n`TEST_DB_ADAPTER=postgres` plus an explicit isolated `DATABASE_URL` creates a unique\nschema per scenario and also exercises concurrent invitation/login proof claims.\nIt is registered in `test:postgres`; no shared local service fallback is used.\n",
8322
+ "agentDoc": "# @happyvertical/smrt-users\n\nMulti-tenant identity, RBAC, hierarchical tenants, sessions, and SvelteKit auth.\n\n## Modules\n\nRead only the module relevant to the change; protocol and provisioning details\nare not prerequisites for unrelated user-package work.\n\n| Module | Scope | Module doc |\n|---|---|---|\n| `src/permission-registry.ts` | portable permission metadata registration; same root/service singleton, no authority grants | [agents/permissions.md](agents/permissions.md#portable-metadata-registry-4765) |\n| `src/services/PermissionResolver.ts` | permission precedence, inherited memberships, guards, RLS, role seeding | [agents/permissions.md](agents/permissions.md) |\n| `src/services/OidcLoginService.ts`, collections and OIDC handlers | identity reconciliation, transaction boundaries, migration readiness | [agents/oidc-provisioning.md](agents/oidc-provisioning.md) |\n| `src/services/MobileAuthService.ts` | mobile handshake, bearer sessions, bootstrap extension boundary | [agents/mobile-auth.md](agents/mobile-auth.md) |\n| `src/services/TerminalAuthService.ts`, `src/services/LoginAttemptLimiter.ts`, `src/collections/LoginAttemptCollection.ts` | terminal approval concurrency, shared login budget and lockout (#3273), retry-safe database fixtures | [agents/terminal-auth-testing.md](agents/terminal-auth-testing.md) |\n| `src/services/DeviceCredentialService.ts` | per-person PIN layered on a device session (#3276), verifier seam for other credential kinds | this file, \"Security boundaries\" |\n| `src/services/PasswordCredentialService.ts`, `src/sveltekit/password-handlers.ts` | email + password sign-in and password lifecycle (#3274); shared scrypt in `credential-hash.ts` | this file, \"Security boundaries\"; README \"Password sign-in\" |\n| `src/services/PasskeyCredentialService.ts`, `src/sveltekit/passkey-handlers.ts`, `src/svelte/passkey.ts` | passkey (WebAuthn) sign-in and passkey lifecycle (#3275); library does all verification | this file, \"Security boundaries\"; README \"Passkey sign-in\" |\n| `src/services/TenantInvitationService.ts`, `src/services/MailboxAuthenticationService.ts` | exact-role invitations, preserved identity, one-use generations and embedded transaction send budgets | [agents/family-invitations.md](agents/family-invitations.md) |\n| `src/retention.ts` | expired session/token/CLI-auth reaping and retention sweep wiring | [agents/retention.md](agents/retention.md) |\n\n## Models and authority\n\n- Users are global; tenant access comes through Membership (unique user/tenant).\n User email is normalized and globally unique through readonly nullable\n `emailKey`. `profileId` is a unique cross-package reference: at most one User\n owns each non-null Profile.\n- Tenant uses STI and a materialized hierarchy, maximum depth 10.\n `hierarchyPath`/`hierarchyLevel` are derived from `parentTenantId` by\n `Tenant.save()` on every save (any caller-supplied value is recomputed) and\n descendants are re-materialized when they change; never hand-maintain them.\n Legacy rows are backfilled with `smrt db:materialize-tenant-hierarchy`\n (`materializeTenantHierarchy()`). Tests that need a corrupt path must write it\n with raw SQL (#3036).\n- Role with `tenantId = null` is available to all tenants; `isSystem` prevents\n deletion. `inheritsToDescendants` is opt-in. Seed owner/admin/member/viewer\n through `RoleCollection.seedSystemRoles()` at application initialization.\n- Group roles apply only in their own tenant. Use `getGroupIdsForTenant()`,\n never cross-tenant `getGroupIds()`, for authorization.\n- Upward visibility is opt-in and read-only: `permissions.ancestorRead`\n ({ roles, collections, maxDepth? }) lets a DESCENDANT membership contribute\n declared `<collection>.read` at an ancestor, only when no membership resolved\n there, intersected with BOTH the role's own catalog grants and the\n principal's effective permissions in that descendant, and only for SYSTEM\n roles (a tenant-scoped role sharing a declared slug is ignored). Off by default, never\n write, never lateral, and never row visibility — sibling rows stay scoped by\n tenancy/RLS. Read the permissions module before changing it.\n- Membership DENY always wins. Direct inactive membership blocks inherited\n authority; a direct active membership pins resolution instead of unioning it\n with ancestors. Read the permissions module before changing these rules.\n- AccessRequest has no generated API/MCP/CLI operations; access it through\n `AccessRequestService`. Its JSON field is `requestContext`, not reserved\n slug-scoping `context`.\n\n## Security boundaries\n\n- Generated REST/MCP operations on identity/RBAC models are list/get only.\n Route authentication does not authorize authority mutations, and these models\n are not tenant-scoped. Use permission-gated services or explicitly checked\n consumer handlers. Generated CLI is list/get or closed (`cli: false` for\n credential/grant models) because agents shell out to it; a `cli` without\n `include` is full CRUD (#3742). Their catalog slugs stay full via\n `USERS_AUTHORITY_CATALOG_MODELS`. Preserve the registry assertions in\n `security-audit-1400.test.ts` and `issue-3742-cli-surface-lockdown.test.ts`.\n- Resource guards take the resource tenant, not the session tenant. Omit a\n session membership when targeting a different tenant; mismatches fail closed.\n `loadSessionContext().tenantAuthorization` must be checked by required-tenant\n consumers: null membership can represent inherited authority.\n- Sessions use secure UUIDs; TTL is seconds (default seven days). Access marks\n expired sessions EXPIRED. Magic-link tokens are single use.\n- `Session.authMethod` is server-set at mint time and never read from the\n client; every mint site in this package sets it. A session with\n `parentSessionId` is valid only while its parent validates\n (`loadSessionContext` enforces this; there is no FK cascade by design), may\n not switch to a tenant other than the parent's, and is revoked with its\n parent by `destroySession`.\n- Credential sign-ins reserve through `LoginAttemptLimiter` BEFORE credential\n work and key the subject on the submitted identifier, never a resolved user,\n so unknown and wrong take the same path. Reservations are fail-closed: keep\n them on failure, release on success or abort, never skip the reserve.\n Limiter writes are raw SQL and bypass the change feed; the audit sink is the\n observability seam, and it must never throw into the sign-in path.\n Subject and source budgets are sized independently (#3531); `source: false`\n ignores the source key, so a reservation then needs a subject (fail closed).\n The `source-locked` audit entry never carries a subject or caller metadata.\n- `DeviceCredentialService` accepts a person credential only from a\n first-class session whose `authMethod` is a device-enrollment method\n (`terminal` by default) and that the host's `assertEnrolledDevice` confirms.\n A layered or PIN session can never administer PINs regardless of\n permissions. PIN hashes carry a per-row salt and the configured pepper;\n treat an unset pepper as a production misconfiguration.\n- A person session carries the PERSON's authority (resolved from their own\n membership on every load), never the device account's. `Session.data` keys\n in `SESSION_DATA_KEYS` are server-set controls enforced by the model:\n `permissionCeiling` only ever intersects (malformed fails closed to none)\n and suppresses `superAdminBypass`/`systemContext`; `absoluteExpiresAt`\n bounds `extend()` and `isValid()`; `idleSeconds` overrides the resolving\n service's TTL policy. Never write them from client input. The ceiling is a\n sign-in snapshot; `singleOccupant` revokes other children only AFTER a\n successful mint. A `mustReset` sign-in mints with an empty ceiling and\n `setPin` ends that session; do not grant it authority another way.\n- `UsersPasswordCredential` is one row per person, sensitive, with no\n generated surface; `PasswordCredentialService` and its handlers are its only\n session-authorized read/write paths. The separate Node `./operator` entrypoint\n provisions new PostgreSQL owners from trusted database custody, atomically;\n never mount it in a browser/REST/MCP handler. Exact retries verify existing\n credentials without writes; partial/conflicting identities fail closed.\n See README \"Trusted deployment owner provisioning\".\n Sign-in normalizes the email like `emailKey`, reserves\n before work, always runs one scrypt verify (dummy hash when absent), never\n creates a user, and maps every non-rate-limit refusal to one\n `PasswordCredentialError`. It re-checks the credential after the mint (a\n rehash that keeps row and version is confirmed by re-verifying); the\n parameter-upgrade write is a guarded UPDATE that must never replace a\n rotated password, and verification against a weaker stored hash is padded\n to the policy's scrypt cost. Self-service writes are guarded on the proven\n credential (first set insert-only); session sweeps run before and after\n each write. Self-service needs the current password except for a first\n set; `users.password.manage` follows the PIN's single-tenant target\n rule and never resets the actor's own. Layered sessions never manage\n passwords; a `mustChange` sign-in mints an empty ceiling.\n `replaceForgottenPassword` (#3905, opt-in `recovery`) is the only\n self-service write without the current password: it decides on the stored\n session row (owner, first-class, no ceiling, listed non-password/pin\n `authMethod`, fresh `outOfBandProofAt` stamp) and ends every session,\n its own included. Never set that stamp from client input.\n- `UsersPasskeyCredential` (many per person) and `UsersPasskeyChallenge` (consumed\n challenge ledger) are sensitive with no generated surface;\n `PasskeyCredentialService` and its handlers are the only paths. Verification is\n `@simplewebauthn/server`, loaded on first use (its `reflect-metadata` polyfill is process-wide) and external in the build; never hand-roll COSE/CBOR. Sign-in reserves on\n the submitted credential id before any work, requires user verification, checks\n user handle and a strictly advancing counter (`reason: 'counter'`), mints, then\n re-checks with a guarded counter UPDATE; a ceremony is an HMAC-signed\n `ceremonyId` consumed into the unique ledger (replay = refuse; set\n `challengeSecret` for multi-process). Unique arbiters are\n `INSERT … ON CONFLICT DO NOTHING`, never a caught constraint error. Register and\n self-remove need a session authenticated within `freshSessionSeconds`, decided\n on the stored row (`Session.getAuthenticatedAt()`: server-set\n `data.authenticatedAt`, which tenant-switch rotation carries forward, else\n `created_at`; malformed fails closed; `setSessionData` refuses the key),\n first-class, no ceiling, and its STORED `authMethod` in `freshAuthMethods` (default password/passkey/oidc/magic-link; never `terminal`, whose approval mints a fresh session for any holder of a stale one, nor `pin`); self list/rename also refuse a ceiling; `users.passkey.manage` follows the PIN's\n single-tenant rule, and `removeAllPasskeys` is admin-only, never self. Sessions\n end before and after every removal; `SESSION_DATA_KEYS.passkeyCredentialId` is\n server-set (`setSessionData` refuses it). State-changing handlers require\n `application/json` (415). Challenge rows are reaped only 10 minutes past expiry\n (clock skew).\n- Step-up (#4841, `src/step-up.ts`, subpath `./step-up`): `requireRecentAuthentication`\n decides on `SessionContext.reauthenticatedAt`, derived from the stored row:\n `data.reauthenticatedAt` (server-set through `SessionCollection.markReauthenticated`\n only after a deliberate fresh authentication; `setSessionData` refuses it;\n extend/activity never move it) or the sign-in time of a password or passkey\n session only (`STEP_UP_SIGN_IN_AUTH_METHODS` = `password`, `passkey`; an OIDC\n or magic-link SIGN-IN, `terminal`, `pin`, `mobile` never count: an unlocked\n stolen device can complete them without the person). Rule: an EXISTING\n session never counts as fresh by itself; a DELIBERATE fresh authentication\n with any supported method does, so an OIDC-only or magic-link-only owner can\n still step up. Methods, all stamping the EXISTING session (never minting one),\n all refusing layered/PIN/ceilinged sessions (`Session.isStepUpEligible`):\n `PasswordCredentialService.stepUp` (limiter-guarded password check);\n `OidcLoginService.beginStepUp`/`completeStepUp` (authorization request with\n `prompt=login` + `max_age=0`; the transaction is stored on the session as\n `data.oidcStepUpIntent`, taken at the callback so it is single use; the ID\n token must verify as at sign-in AND carry `auth_time` inside the window, not\n before the intent started, not future; its issuer+subject must be an existing\n `OidcIdentity` of the session user's own profile; a provider that omits\n `auth_time` or ignores `prompt`/`max_age` is refused);\n `MagicLinkService.requestStepUp`/`consumeStepUp` (token claim `purpose:\n step_up` + session digest + user id, TTL <= 300 s, single use; `verify` and\n `inspect` refuse it so it cannot sign in; `consumeStepUp` refuses a link\n without that purpose). Every step-up refusal is one `StepUpRequiredError`\n (`step_up_required`) that does not say which check failed. A passkey owner\n re-authenticates with a fresh passkey sign-in. Keep the entry free of\n side-effect imports.\n- A layered session whose tenant differs from its parent's never loads (null\n is allowed: narrower). Limiter rows carry `retain_until`; retention must\n not fall back to a process-wide horizon.\n- `Session.parentSessionId` is the parent's bearer: sensitive, never a\n `list()` filter (raw-SQL id reads, which also keep revocation sweeps free of\n caller list bounds), never serialized to clients. `users.pin.manage` reaches\n only people whose every active membership is in the actor's tenant (the PIN\n is global per person). A sign-in re-checks the verified\n credential generation AFTER the mint (`stillValid`); keep that ordering.\n Operation guards deny outside a session's ceiling; `loadPersonSession`\n re-checks device enrollment.\n- Tenant switching verifies active membership before writing and rotates the\n session ID for non-null targets, revoking the old session. Persist the returned\n `SwitchTenantResult.sessionId`; `switchSessionTenant()` updates the cookie and\n preserves its security settings. Failed switches mutate nothing; null clears\n do not rotate, and layered sessions never rotate (a replacement would escape\n the revocation sweeps they depend on). Layers do not nest. `SessionCollection.setSessionTenant()` is unguarded and must\n never receive an untrusted tenant ID.\n- OIDC provisioning is atomic and fail-closed. Preserve exact issuer/subject\n identifiers, claim-source email verification, unique global Person ownership,\n and transaction-bound reconciliation. Read the OIDC module and canonical\n scenario matrix before changing any provisioning path.\n\n## Entry points and validation\n\n`src/sveltekit/` owns `createSessionHandler`, `createSessionCookie`,\n`destroySessionCookie`, and `switchSessionTenant`. Use README integration examples\nrather than copying application setup into these instructions.\n\nFrom the repository root:\n\n```bash\npnpm --filter @happyvertical/smrt-users test\npnpm --filter @happyvertical/smrt-users typecheck\npnpm --filter @happyvertical/smrt-users test:postgres\n```\n\nStart with the relevant test file via `test -- src/__tests__/<file>.test.ts`.\nRun `test:postgres` for RLS, principal context, OIDC, or terminal-auth database\nchanges. `typecheck` includes Svelte accessibility checks; plain `tsc` is\ninsufficient. Follow root knowledge freshness checks before shipping.\n\n## Pending invitations\n\n`TenantInvitationService.create({ db: tx, transaction: 'caller' }).prepare({\ntenantId, email, roleSlug })` is a trusted host integration seam. The caller\nmust authorize the destination tenant and system role, serialize its invitation\nscope, and own the entire transaction. It prepares only pending User and\nMembership records, with a canonical global Person and email reservation;\nit never proves email ownership, activates access, sends email, or mints login\ncredentials. Existing canonical User/Profile links remain unchanged; unowned\nsame-email Profiles require explicit reconciliation. Pending retries reuse rows,\nactive memberships remain active with their existing role, and inactive or\nconflicting memberships fail closed. Caller failures must roll back the whole\ntransaction; retry identity uniqueness conflicts only after rollback. Run the\nprofile/user email-key backfills before using this service.\n\n`issue({ membershipId })` requires the host to authorize that exact destination\nand returns a signed single-use `{ membershipId, token, expiresAt }`; secure\ndelivery is the host’s responsibility (no email is sent). Configure `secret` and\noptional `tokenExpiry` (1–604800 seconds, default one day) at service creation.\n`accept({ membershipId, token, sessionId, expectedUserId? })` consumes the tenant\ngrant only after validating an independently authenticated, active exact User's\nstored first-class OIDC, magic-link, password or passkey session. Layered,\npermission-ceiling, terminal and unknown sessions fail closed. It activates only\nthe Membership; reuse/switch that session through canonical session APIs.\nNever mint global identity sessions from an operator-copyable invitation.\n\nFor a new pending User, wire `authorizeOidcOwner(context, { membershipId, token })`\nonly into the canonical protocol-verified OIDC `authorizeProfileOwner` callback.\nIt requires the exact caller transaction, strict `email_verified: true` and the\nexact canonical invitee email, consumes the grant and activates pending User\nand Membership atomically before returning `{ profile, user, tenantId, membershipId }`.\nArbitrary claims must never reach this trusted callback seam. The canonical\nbinder still verifies ownership and issuer/subject authority before commit.\nThe signed scope fixes user, profile, tenant, membership and role; expiration,\nreplay, changed bindings, inactive membership and suspended users fail closed.\nNonce consumption and activation roll back together. `TenantInvitationError`\nis an expected 400/403 refusal;\n`MagicLinkError` represents invalid, expired or replayed proof. Database failures\nremain distinct. Treat tokens as secrets, prefer URL fragments and POST bodies,\nand never log or persist a copy outside the canonical token ledger.\n\n\n## Independent emailed mailbox authentication\n\n`MailboxAuthenticationService.create({db:tx,transaction:'caller',secret,loginLimiter})`\nrequests and verifies returning-client login without creating identities/sessions.\n`request({email,sourceKey,deliver})` returns only `{requested:true}` for known,\nunknown, malformed, pending, inactive or unauthorized accounts. The trusted server\n`deliver({email,token,expiresAt})` callback sends only to the eligible canonical\nactive User's email; never expose a proof in HTTP responses/operator UI/logs,\nincluding development. Ten-minute one-use proofs bind immutable User/Profile ids.\n`authenticate({token,expectedUserId?,sessionId?})` rechecks canonical identity and\nactive tenant membership before consuming proof; returns only verified\n`{userId,profileId,tenantId}` for the host's canonical magic-link session mint.\nExisting signed-in identity must match; supplied sessions cannot have a parent,\npermission ceiling, terminal/PIN/unknown method, or inactive principal.\n\nFor pending invitation onboarding, `requestMailboxAuthentication({membershipId,\ntoken:projectGrant,sourceKey,deliver})` inspects but never consumes the signed\nproject grant, then delivers a DIFFERENT mailbox proof to the fixed invitee.\nOnly `{expiresAt}` is returned. `authenticateMailbox({membershipId,\ninvitationToken:projectGrant,token:mailedProof,expectedUserId?,sessionId?})` claims\nBOTH proof nonces and activates pending canonical User/exact Membership in the\nsame caller transaction. Mailbox proof issuer binds all invitation ids, role and\nSHA256 of the exact grant. A copied operator-visible grant cannot authenticate\nidentity. Repeated email requests do not burn the grant; only the first completed\nauthentication can claim it. Existing active-session/OIDC paths remain supported.\n\nAll refusals/caller failures must roll back the whole caller transaction. Mail\ntransport must reject on failure. Delivery is an external effect before commit:\na successfully delivered but rolled-back proof is unusable; retry may send another\nmail. No session/authentication is valid without committed proof claims. The host\nmust set a bounded transport timeout and never return transport payloads/secrets.\nNo generic outbox/provider is required; compose the existing SDK email transport.\n\nBoth mail request operations REQUIRE a root-executor canonical\n`LoginAttemptLimiter` passed as `loginLimiter`; missing limiters fail before\nnonce/budget writes or delivery. Completion-only operations may omit it. Supply\nthe limiter independently from the caller transaction so\ncaller rollbacks cannot release send budgets (SQLite single-connection fixtures\ncannot prove that production-pool separation). `sourceKey` is a trusted server\nclient-address key, never request-controlled forwarded headers; limiter hashes\nand peppers it, never stores raw addresses/email. Each request retains its budget\nthrough window expiry via `retainOnSuccess`, regardless of account eligibility.\nHandle `LoginRateLimitError` with the same generic request response plus retry\npolicy. Returning request has a 250ms response floor; delivery latency remains\ntransport-dependent, so do not claim constant timing. Malformed/expired/replayed\nproofs raise `MagicLinkError`; invitation binding/status refusals also use\n`TenantInvitationError`. Database/transport faults remain distinguishable server\nfailures. Never swallow an error and commit a partially consumed transaction.\n\n`MagicLinkService.inspect()` validates signed live nonce without claiming it;\nit is preparation, never authentication. `verify()` remains the atomic claim.\nOptional generated signed `subject` binds immutable identity; legacy callers\nwithout a subject retain their existing result shape.\n\nFocused matrix: `mailbox-authentication.test.ts` runs in memory SQLite by default;\n`TEST_DB_ADAPTER=postgres` plus an explicit isolated `DATABASE_URL` creates a unique\nschema per scenario and also exercises concurrent invitation/login proof claims.\nIt is registered in `test:postgres`; no shared local service fallback is used.\n",
8246
8323
  "moduleDocs": [
8247
8324
  {
8248
8325
  "path": "agents/permissions.md",
@@ -5,10 +5,10 @@ description: "Multi-tenant user management for the SMRT framework - users, tenan
5
5
  status: "stable"
6
6
  generated:
7
7
  by: "smrt/scripts/generate-knowledge-okf.ts"
8
- at: "2026-11-08T08:24:43Z"
8
+ at: "2026-11-09T18:41:34Z"
9
9
  audience: "internal"
10
10
  evidence_level: "source-inspected"
11
- source_revision: "sha256:bf54a1549afc9fe3bcef1d6852ebc175c8adac9ad17ef90f5910050a7111ed9c"
11
+ source_revision: "sha256:85c5ed7ca0925f6bc5251da5c5d77a57cf9e9f4fe725d1ad38fc236ef9ca5ab0"
12
12
  sources:
13
13
  - id: "manifest"
14
14
  resource: "https://github.com/happyvertical/smrt/blob/main/packages/users/package.json"
@@ -80,6 +80,7 @@ sources:
80
80
  - `./operator`
81
81
  - `./permission-registry`
82
82
  - `./playground`
83
+ - `./step-up`
83
84
  - `./svelte`
84
85
  - `./sveltekit`
85
86
 
@@ -0,0 +1,57 @@
1
+ /**
2
+ * Step-up (recent authentication) check (#4841).
3
+ *
4
+ * A session proves who signed in at some point; a sensitive action (replacing
5
+ * a vault account, for instance) needs proof the person is at the keyboard
6
+ * NOW. The proof is server-side session state: the sign-in time of an
7
+ * interactive session, or the stamp `PasswordCredentialService.stepUp` writes
8
+ * after a fresh password check. This module only decides; it never writes.
9
+ *
10
+ * @packageDocumentation
11
+ */
12
+ import type { SessionContext } from './services/SessionService.js';
13
+ /** The slice of a session context the step-up and owner checks read. */
14
+ export type StepUpSession = Pick<SessionContext, 'sessionId' | 'user' | 'reauthenticatedAt' | 'membership' | 'tenantId' | 'authMethod' | 'parent' | 'permissionCeiling' | 'tenantAuthorization'>;
15
+ /** Stable machine code carried by {@link StepUpRequiredError}. */
16
+ export declare const STEP_UP_REQUIRED_CODE = "step_up_required";
17
+ /** Default age (5 minutes) a step-up may have when an action runs. */
18
+ export declare const DEFAULT_STEP_UP_MAX_AGE_SECONDS = 300;
19
+ /** Largest accepted `maxAgeSeconds` (1 hour). */
20
+ export declare const STEP_UP_MAX_AGE_CEILING_SECONDS: number;
21
+ /**
22
+ * The session has no sufficiently recent authentication. One message and one
23
+ * code for every reason (missing, stale, malformed, wrong session or user), so
24
+ * a caller learns only that it must re-authenticate.
25
+ */
26
+ export declare class StepUpRequiredError extends Error {
27
+ readonly code = "step_up_required";
28
+ constructor(message?: string);
29
+ }
30
+ export interface RequireRecentAuthenticationOptions {
31
+ /** Longest acceptable age in seconds. Default 300; capped at one hour. */
32
+ maxAgeSeconds?: number;
33
+ /** Clock, injectable for tests. Default `() => new Date()`. */
34
+ now?: () => Date;
35
+ /** The session the caller authenticated; a different session is refused. */
36
+ expectedSessionId?: string;
37
+ /** The user the action is for; a different user's session is refused. */
38
+ expectedUserId?: string;
39
+ }
40
+ /**
41
+ * Throw {@link StepUpRequiredError} unless `session` (a context from
42
+ * `SessionService.loadSessionContext`) was authenticated within
43
+ * `maxAgeSeconds`. Fails closed: a missing, malformed, future-dated or stale
44
+ * timestamp, a session or user other than the expected ones, or an invalid
45
+ * `maxAgeSeconds` all refuse.
46
+ */
47
+ export declare function requireRecentAuthentication(session: Pick<StepUpSession, 'sessionId' | 'user' | 'reauthenticatedAt'>, options?: RequireRecentAuthenticationOptions): void;
48
+ /**
49
+ * Whether `session` is a first-class session of the OWNER of its tenant: a
50
+ * direct, active membership in the system `owner` role (not an inherited or
51
+ * ancestor one), with no device or layered channel (`terminal`, `pin`, a
52
+ * parent session) and no permission ceiling. A member, a device-only session
53
+ * and a missing session are all false. Hosts with a custom owner role decide
54
+ * for themselves and pass their own check where this one is injected.
55
+ */
56
+ export declare function isTenantOwnerSession(session: StepUpSession | null | undefined): boolean;
57
+ //# sourceMappingURL=step-up.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"step-up.d.ts","sourceRoot":"","sources":["../src/step-up.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAEH,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;AAGnE,wEAAwE;AACxE,MAAM,MAAM,aAAa,GAAG,IAAI,CAC9B,cAAc,EACZ,WAAW,GACX,MAAM,GACN,mBAAmB,GACnB,YAAY,GACZ,UAAU,GACV,YAAY,GACZ,QAAQ,GACR,mBAAmB,GACnB,qBAAqB,CACxB,CAAC;AAOF,kEAAkE;AAClE,eAAO,MAAM,qBAAqB,qBAAqB,CAAC;AAExD,sEAAsE;AACtE,eAAO,MAAM,+BAA+B,MAAM,CAAC;AAEnD,iDAAiD;AACjD,eAAO,MAAM,+BAA+B,QAAU,CAAC;AAKvD;;;;GAIG;AACH,qBAAa,mBAAoB,SAAQ,KAAK;IAC5C,QAAQ,CAAC,IAAI,sBAAyB;gBAE1B,OAAO,SAAuC;CAI3D;AAED,MAAM,WAAW,kCAAkC;IACjD,0EAA0E;IAC1E,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,+DAA+D;IAC/D,GAAG,CAAC,EAAE,MAAM,IAAI,CAAC;IACjB,4EAA4E;IAC5E,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAC3B,yEAAyE;IACzE,cAAc,CAAC,EAAE,MAAM,CAAC;CACzB;AAED;;;;;;GAMG;AACH,wBAAgB,2BAA2B,CACzC,OAAO,EAAE,IAAI,CAAC,aAAa,EAAE,WAAW,GAAG,MAAM,GAAG,mBAAmB,CAAC,EACxE,OAAO,GAAE,kCAAuC,GAC/C,IAAI,CA8BN;AAED;;;;;;;GAOG;AACH,wBAAgB,oBAAoB,CAClC,OAAO,EAAE,aAAa,GAAG,IAAI,GAAG,SAAS,GACxC,OAAO,CAkBT"}
@@ -0,0 +1,36 @@
1
+ import { n as DEFAULT_ROLES } from "./chunks/types-DqUZxluX.js";
2
+ //#region src/step-up.ts
3
+ var OWNER_ROLE_ID = DEFAULT_ROLES[0].id;
4
+ var DEVICE_AUTH_METHODS = /* @__PURE__ */ new Set(["terminal", "pin"]);
5
+ var STEP_UP_REQUIRED_CODE = "step_up_required";
6
+ var DEFAULT_STEP_UP_MAX_AGE_SECONDS = 300;
7
+ var STEP_UP_MAX_AGE_CEILING_SECONDS = 3600;
8
+ var StepUpRequiredError = class extends Error {
9
+ code = STEP_UP_REQUIRED_CODE;
10
+ constructor(message = "Recent authentication is required.") {
11
+ super(message);
12
+ this.name = "StepUpRequiredError";
13
+ }
14
+ };
15
+ function requireRecentAuthentication(session, options = {}) {
16
+ const maxAge = options.maxAgeSeconds ?? 300;
17
+ if (!Number.isFinite(maxAge) || maxAge <= 0 || maxAge > 3600) throw new StepUpRequiredError();
18
+ if (options.expectedSessionId !== void 0 && session.sessionId !== options.expectedSessionId) throw new StepUpRequiredError();
19
+ if (options.expectedUserId !== void 0 && session.user?.id !== options.expectedUserId) throw new StepUpRequiredError();
20
+ const at = session.reauthenticatedAt;
21
+ if (!(at instanceof Date) || Number.isNaN(at.getTime())) throw new StepUpRequiredError();
22
+ const age = (options.now ?? (() => /* @__PURE__ */ new Date()))().getTime() - at.getTime();
23
+ if (age < -3e4 || age > maxAge * 1e3) throw new StepUpRequiredError();
24
+ }
25
+ function isTenantOwnerSession(session) {
26
+ if (!session?.user?.id || !session.tenantId) return false;
27
+ const membership = session.membership;
28
+ if (!membership || membership.roleId !== OWNER_ROLE_ID || membership.tenantId !== session.tenantId || membership.userId !== session.user.id || typeof membership.isActive === "function" && !membership.isActive()) return false;
29
+ if (session.tenantAuthorization?.inheritedFromTenantId) return false;
30
+ if (session.parent || session.permissionCeiling) return false;
31
+ return !(typeof session.authMethod === "string" && DEVICE_AUTH_METHODS.has(session.authMethod));
32
+ }
33
+ //#endregion
34
+ export { DEFAULT_STEP_UP_MAX_AGE_SECONDS, STEP_UP_MAX_AGE_CEILING_SECONDS, STEP_UP_REQUIRED_CODE, StepUpRequiredError, isTenantOwnerSession, requireRecentAuthentication };
35
+
36
+ //# sourceMappingURL=step-up.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"step-up.js","names":[],"sources":["../src/step-up.ts"],"sourcesContent":["/**\n * Step-up (recent authentication) check (#4841).\n *\n * A session proves who signed in at some point; a sensitive action (replacing\n * a vault account, for instance) needs proof the person is at the keyboard\n * NOW. The proof is server-side session state: the sign-in time of an\n * interactive session, or the stamp `PasswordCredentialService.stepUp` writes\n * after a fresh password check. This module only decides; it never writes.\n *\n * @packageDocumentation\n */\n\nimport type { SessionContext } from './services/SessionService.js';\nimport { DEFAULT_ROLES } from './types/index.js';\n\n/** The slice of a session context the step-up and owner checks read. */\nexport type StepUpSession = Pick<\n SessionContext,\n | 'sessionId'\n | 'user'\n | 'reauthenticatedAt'\n | 'membership'\n | 'tenantId'\n | 'authMethod'\n | 'parent'\n | 'permissionCeiling'\n | 'tenantAuthorization'\n>;\n\nconst OWNER_ROLE_ID: string = DEFAULT_ROLES[0].id;\n\n/** Session channels that are a device, never the person at the keyboard. */\nconst DEVICE_AUTH_METHODS: ReadonlySet<string> = new Set(['terminal', 'pin']);\n\n/** Stable machine code carried by {@link StepUpRequiredError}. */\nexport const STEP_UP_REQUIRED_CODE = 'step_up_required';\n\n/** Default age (5 minutes) a step-up may have when an action runs. */\nexport const DEFAULT_STEP_UP_MAX_AGE_SECONDS = 300;\n\n/** Largest accepted `maxAgeSeconds` (1 hour). */\nexport const STEP_UP_MAX_AGE_CEILING_SECONDS = 60 * 60;\n\n/** Clock skew tolerated before a future stamp is treated as forged. */\nconst FUTURE_SKEW_MS = 30_000;\n\n/**\n * The session has no sufficiently recent authentication. One message and one\n * code for every reason (missing, stale, malformed, wrong session or user), so\n * a caller learns only that it must re-authenticate.\n */\nexport class StepUpRequiredError extends Error {\n readonly code = STEP_UP_REQUIRED_CODE;\n\n constructor(message = 'Recent authentication is required.') {\n super(message);\n this.name = 'StepUpRequiredError';\n }\n}\n\nexport interface RequireRecentAuthenticationOptions {\n /** Longest acceptable age in seconds. Default 300; capped at one hour. */\n maxAgeSeconds?: number;\n /** Clock, injectable for tests. Default `() => new Date()`. */\n now?: () => Date;\n /** The session the caller authenticated; a different session is refused. */\n expectedSessionId?: string;\n /** The user the action is for; a different user's session is refused. */\n expectedUserId?: string;\n}\n\n/**\n * Throw {@link StepUpRequiredError} unless `session` (a context from\n * `SessionService.loadSessionContext`) was authenticated within\n * `maxAgeSeconds`. Fails closed: a missing, malformed, future-dated or stale\n * timestamp, a session or user other than the expected ones, or an invalid\n * `maxAgeSeconds` all refuse.\n */\nexport function requireRecentAuthentication(\n session: Pick<StepUpSession, 'sessionId' | 'user' | 'reauthenticatedAt'>,\n options: RequireRecentAuthenticationOptions = {},\n): void {\n const maxAge = options.maxAgeSeconds ?? DEFAULT_STEP_UP_MAX_AGE_SECONDS;\n if (\n !Number.isFinite(maxAge) ||\n maxAge <= 0 ||\n maxAge > STEP_UP_MAX_AGE_CEILING_SECONDS\n ) {\n throw new StepUpRequiredError();\n }\n if (\n options.expectedSessionId !== undefined &&\n session.sessionId !== options.expectedSessionId\n ) {\n throw new StepUpRequiredError();\n }\n if (\n options.expectedUserId !== undefined &&\n session.user?.id !== options.expectedUserId\n ) {\n throw new StepUpRequiredError();\n }\n const at = session.reauthenticatedAt;\n if (!(at instanceof Date) || Number.isNaN(at.getTime())) {\n throw new StepUpRequiredError();\n }\n const nowMs = (options.now ?? (() => new Date()))().getTime();\n const age = nowMs - at.getTime();\n if (age < -FUTURE_SKEW_MS || age > maxAge * 1000) {\n throw new StepUpRequiredError();\n }\n}\n\n/**\n * Whether `session` is a first-class session of the OWNER of its tenant: a\n * direct, active membership in the system `owner` role (not an inherited or\n * ancestor one), with no device or layered channel (`terminal`, `pin`, a\n * parent session) and no permission ceiling. A member, a device-only session\n * and a missing session are all false. Hosts with a custom owner role decide\n * for themselves and pass their own check where this one is injected.\n */\nexport function isTenantOwnerSession(\n session: StepUpSession | null | undefined,\n): boolean {\n if (!session?.user?.id || !session.tenantId) return false;\n const membership = session.membership;\n if (\n !membership ||\n membership.roleId !== OWNER_ROLE_ID ||\n membership.tenantId !== session.tenantId ||\n membership.userId !== session.user.id ||\n (typeof membership.isActive === 'function' && !membership.isActive())\n ) {\n return false;\n }\n if (session.tenantAuthorization?.inheritedFromTenantId) return false;\n if (session.parent || session.permissionCeiling) return false;\n return !(\n typeof session.authMethod === 'string' &&\n DEVICE_AUTH_METHODS.has(session.authMethod)\n );\n}\n"],"mappings":";;AA6BA,IAAM,gBAAwB,cAAc,EAAC,CAAE;AAG/C,IAAM,sCAA2C,IAAI,IAAI,CAAC,YAAY,KAAK,CAAC;AAGrE,IAAM,wBAAwB;AAG9B,IAAM,kCAAkC;AAGxC,IAAM,kCAAkC;AAUxC,IAAM,sBAAN,cAAkC,MAAM;CACpC,OAAO;CAEhB,YAAY,UAAU,sCAAsC;EAC1D,MAAM,OAAO;EACb,KAAK,OAAO;CACd;AACF;AAoBO,SAAS,4BACd,SACA,UAA8C,CAAC,GACzC;CACN,MAAM,SAAS,QAAQ,iBAAA;CACvB,IACE,CAAC,OAAO,SAAS,MAAM,KACvB,UAAU,KACV,SAAA,MAEA,MAAM,IAAI,oBAAoB;CAEhC,IACE,QAAQ,sBAAsB,KAAA,KAC9B,QAAQ,cAAc,QAAQ,mBAE9B,MAAM,IAAI,oBAAoB;CAEhC,IACE,QAAQ,mBAAmB,KAAA,KAC3B,QAAQ,MAAM,OAAO,QAAQ,gBAE7B,MAAM,IAAI,oBAAoB;CAEhC,MAAM,KAAK,QAAQ;CACnB,IAAI,EAAE,cAAc,SAAS,OAAO,MAAM,GAAG,QAAQ,CAAC,GACpD,MAAM,IAAI,oBAAoB;CAGhC,MAAM,OADS,QAAQ,8BAAc,IAAI,KAAK,GAAA,CAAI,CAAA,CAAE,QACxC,IAAQ,GAAG,QAAQ;CAC/B,IAAI,MAAM,QAAmB,MAAM,SAAS,KAC1C,MAAM,IAAI,oBAAoB;AAElC;AAUO,SAAS,qBACd,SACS;CACT,IAAI,CAAC,SAAS,MAAM,MAAM,CAAC,QAAQ,UAAU,OAAO;CACpD,MAAM,aAAa,QAAQ;CAC3B,IACE,CAAC,cACD,WAAW,WAAW,iBACtB,WAAW,aAAa,QAAQ,YAChC,WAAW,WAAW,QAAQ,KAAK,MAClC,OAAO,WAAW,aAAa,cAAc,CAAC,WAAW,SAAS,GAEnE,OAAO;CAET,IAAI,QAAQ,qBAAqB,uBAAuB,OAAO;CAC/D,IAAI,QAAQ,UAAU,QAAQ,mBAAmB,OAAO;CACxD,OAAO,EACL,OAAO,QAAQ,eAAe,YAC9B,oBAAoB,IAAI,QAAQ,UAAU;AAE9C"}
@@ -38,10 +38,63 @@ async function revoke(kind: 'session' | 'api-key', id: string) {
38
38
  }
39
39
  }
40
40
  </script>
41
- <section class="security" aria-labelledby="account-security-title" data-smrt-component="AccountSecurityPanel"><h2 id="account-security-title">{t('users.auth.account_security')}</h2>{#if error}<p role="alert">{t(error)}</p>{/if}<h3>{t('users.auth.signed_in_sessions')}</h3>{#if sessions.length}<ul>{#each sessions as session (session.id)}<li><div><strong>{session.label}</strong>{#if session.current}<span>{t('users.auth.current_session')}</span>{/if}{#if session.lastActiveAt}<small>{t('users.auth.last_active',{value:session.lastActiveAt})}</small>{/if}</div><Button variant="secondary" size="sm" onclick={()=>revoke('session',session.id)} disabled={session.current||!adapter.revokeSession} loading={pending===`session:${session.id}`}>{t('users.auth.sign_out')}</Button></li>{/each}</ul>{:else}<p>{t('users.auth.no_active_sessions')}</p>{/if}<h3>{t('users.auth.api_keys')}</h3>{#if apiKeys.length}<ul>{#each apiKeys as key (key.id)}<li><div><strong>{key.label}</strong>{#if key.lastUsedAt}<small>{t('users.auth.last_used',{value:key.lastUsedAt})}</small>{/if}</div><Button variant="secondary" size="sm" onclick={()=>revoke('api-key',key.id)} disabled={!adapter.revokeApiKey} loading={pending===`api-key:${key.id}`}>{t('users.auth.revoke')}</Button></li>{/each}</ul>{:else}<p>{t('users.auth.no_api_keys')}</p>{/if}</section>
41
+ <section class="smrt-account-security-panel__root" aria-labelledby="account-security-title" data-smrt-component="AccountSecurityPanel"><h2 id="account-security-title">{t('users.auth.account_security')}</h2>{#if error}<p role="alert">{t(error)}</p>{/if}<h3>{t('users.auth.signed_in_sessions')}</h3>{#if sessions.length}<ul>{#each sessions as session (session.id)}<li><div><strong>{session.label}</strong>{#if session.current}<span>{t('users.auth.current_session')}</span>{/if}{#if session.lastActiveAt}<small>{t('users.auth.last_active',{value:session.lastActiveAt})}</small>{/if}</div><Button variant="secondary" size="sm" onclick={()=>revoke('session',session.id)} disabled={session.current||!adapter.revokeSession} loading={pending===`session:${session.id}`}>{t('users.auth.sign_out')}</Button></li>{/each}</ul>{:else}<p>{t('users.auth.no_active_sessions')}</p>{/if}<h3>{t('users.auth.api_keys')}</h3>{#if apiKeys.length}<ul>{#each apiKeys as key (key.id)}<li><div><strong>{key.label}</strong>{#if key.lastUsedAt}<small>{t('users.auth.last_used',{value:key.lastUsedAt})}</small>{/if}</div><Button variant="secondary" size="sm" onclick={()=>revoke('api-key',key.id)} disabled={!adapter.revokeApiKey} loading={pending===`api-key:${key.id}`}>{t('users.auth.revoke')}</Button></li>{/each}</ul>{:else}<p>{t('users.auth.no_api_keys')}</p>{/if}</section>
42
42
  <style>
43
43
  @layer smrt.reset, smrt.structure, smrt.theme;
44
+ @layer smrt.structure {
45
+ .smrt-account-security-panel__root {
46
+ display:grid;
47
+ gap:var(--smrt-spacing-sm,.5rem);
48
+ }
49
+ h2,h3,p {
50
+ margin:0;
51
+ }
52
+ h3 {
53
+ margin-top:var(--smrt-spacing-sm,.5rem);
54
+ }
55
+ ul {
56
+ list-style:none;
57
+ padding:0;
58
+ margin:0;
59
+ display:grid;
60
+ gap:var(--smrt-spacing-sm,.5rem);
61
+ }
62
+ li {
63
+ display:flex;
64
+ justify-content:space-between;
65
+ align-items:center;
66
+ gap:var(--smrt-spacing-md,1rem);
67
+ padding:var(--smrt-spacing-sm,.5rem);
68
+ }
69
+ li div {
70
+ display:grid;
71
+ gap:var(--smrt-spacing-2,.25rem);
72
+ }
73
+ }
74
+
44
75
  @layer smrt.theme {
45
- .security{display:grid;gap:var(--smrt-spacing-sm,.5rem);color:var(--smrt-color-on-surface)}h2,h3,p{margin:0}h2{font:var(--smrt-typography-title-large-font)}h3{margin-top:var(--smrt-spacing-sm,.5rem);font:var(--smrt-typography-title-small-font)}p[role=alert]{color:var(--smrt-color-error)}ul{list-style:none;padding:0;margin:0;display:grid;gap:var(--smrt-spacing-sm,.5rem)}li{display:flex;justify-content:space-between;align-items:center;gap:var(--smrt-spacing-md,1rem);padding:var(--smrt-spacing-sm,.5rem);background:var(--smrt-color-surface-container-low);border-radius:var(--smrt-radius-sm,.25rem)}li div{display:grid;gap:var(--smrt-spacing-2,.25rem)}small,span{color:var(--smrt-color-on-surface-variant)}span{font:var(--smrt-typography-label-small-font)}
76
+ .smrt-account-security-panel__root {
77
+ color:var(--smrt-color-on-surface);
78
+ }
79
+ h2 {
80
+ font:var(--smrt-typography-title-large-font);
81
+ }
82
+ h3 {
83
+ font:var(--smrt-typography-title-small-font);
84
+ }
85
+ p[role=alert] {
86
+ color:var(--smrt-color-error);
87
+ }
88
+ li {
89
+ background:var(--smrt-color-surface-container-low);
90
+ border-radius:var(--smrt-radius-sm,.25rem);
91
+ }
92
+ small,span {
93
+ color:var(--smrt-color-on-surface-variant);
94
+ }
95
+ span {
96
+ font:var(--smrt-typography-label-small-font);
97
+ }
46
98
  }
99
+
47
100
  </style>
@@ -91,13 +91,13 @@ function handleClose() {
91
91
  closeOnBackdrop={!loading}
92
92
  closeOnEscape={!loading}
93
93
  >
94
- <div class="invite-form-shell">
94
+ <div class="smrt-invite-user-modal__root" data-smrt-part="body">
95
95
  <Form id={formId} class="invite-form" onsubmit={handleSubmit}>
96
96
  {#if error}
97
- <div class="error">{error}</div>
97
+ <div class="smrt-invite-user-modal__error" data-smrt-part="error">{error}</div>
98
98
  {/if}
99
99
 
100
- <div class="field">
100
+ <div class="smrt-invite-user-modal__field" data-smrt-part="field">
101
101
  <label for="invite-email">{t(M['users.invite_user_modal.email_address'])}</label>
102
102
  <Input
103
103
  id="invite-email"
@@ -109,7 +109,7 @@ function handleClose() {
109
109
  />
110
110
  </div>
111
111
 
112
- <div class="field">
112
+ <div class="smrt-invite-user-modal__field" data-smrt-part="field">
113
113
  <label for="invite-role">Role</label>
114
114
  <RoleSelector
115
115
  {roles}
@@ -120,14 +120,14 @@ function handleClose() {
120
120
  />
121
121
  </div>
122
122
 
123
- <div class="checkbox-field">
123
+ <div class="smrt-invite-user-modal__checkbox-field" data-smrt-part="control">
124
124
  <!-- raw-primitive-allow: native checkbox; no Provider-free checkbox primitive (Toggle is a switch with different semantics, CheckboxInput requires a Provider) -->
125
125
  <input id="send-email" type="checkbox" bind:checked={sendEmail} disabled={loading} />
126
126
  <label for="send-email">{t(M['users.invite_user_modal.send_invitation_email'])}</label>
127
127
  </div>
128
128
 
129
129
  {#if !sendEmail}
130
- <div class="hint">
130
+ <div class="smrt-invite-user-modal__hint" data-smrt-part="description">
131
131
  {t(M['users.invite_user_modal.pending_hint'])}
132
132
  </div>
133
133
  {/if}
@@ -150,58 +150,61 @@ function handleClose() {
150
150
 
151
151
  <style>
152
152
  @layer smrt.reset, smrt.structure, smrt.theme;
153
- @layer smrt.theme {
153
+ @layer smrt.structure {
154
154
  /* The dialog chrome (backdrop, surface, header, footer bar, close button) is
155
- supplied by the smrt-ui Modal. Only the form-content + footer-button styles
156
- live here. */
157
- .invite-form-shell :global(.invite-form) {
155
+ supplied by the smrt-ui Modal. Only the form-content + footer-button styles
156
+ live here. */
157
+ .smrt-invite-user-modal__root :global(.invite-form) {
158
158
  display: flex;
159
159
  flex-direction: column;
160
160
  gap: var(--smrt-spacing-md, 1rem);
161
161
  }
162
-
163
- .error {
162
+ .smrt-invite-user-modal__error {
164
163
  padding: var(--smrt-spacing-sm, 0.75rem);
165
- background: var(--smrt-color-error-container);
166
- border: 1px solid var(--smrt-color-error);
167
- border-radius: var(--smrt-radius-medium, 0.5rem);
168
- color: var(--smrt-color-on-error-container);
169
- font: var(--smrt-typography-body-medium-font, 0.875rem / 1.25 sans-serif);
170
164
  }
171
-
172
- .field {
165
+ .smrt-invite-user-modal__field {
173
166
  display: flex;
174
167
  flex-direction: column;
175
168
  gap: 0.375rem;
176
169
  }
177
-
178
- label {
179
- font: var(--smrt-typography-body-medium-font, 500 0.875rem / 1.25 sans-serif);
180
- color: var(--smrt-color-on-surface-variant);
181
- }
182
-
183
- .checkbox-field {
170
+ .smrt-invite-user-modal__checkbox-field {
184
171
  display: flex;
185
172
  align-items: center;
186
173
  gap: var(--smrt-spacing-sm, 0.5rem);
187
174
  }
188
-
189
- .checkbox-field input {
175
+ .smrt-invite-user-modal__checkbox-field input {
190
176
  width: 1rem;
191
177
  height: 1rem;
192
- accent-color: var(--smrt-color-primary);
193
178
  }
179
+ .smrt-invite-user-modal__hint {
180
+ padding: var(--smrt-spacing-sm, 0.5rem);
181
+ }
182
+ }
194
183
 
195
- .checkbox-field label {
184
+ @layer smrt.theme {
185
+ .smrt-invite-user-modal__error {
186
+ background: var(--smrt-color-error-container);
187
+ border: 1px solid var(--smrt-color-error);
188
+ border-radius: var(--smrt-radius-medium, 0.5rem);
189
+ color: var(--smrt-color-on-error-container);
190
+ font: var(--smrt-typography-body-medium-font, 0.875rem / 1.25 sans-serif);
191
+ }
192
+ label {
193
+ font: var(--smrt-typography-body-medium-font, 500 0.875rem / 1.25 sans-serif);
194
+ color: var(--smrt-color-on-surface-variant);
195
+ }
196
+ .smrt-invite-user-modal__checkbox-field input {
197
+ accent-color: var(--smrt-color-primary);
198
+ }
199
+ .smrt-invite-user-modal__checkbox-field label {
196
200
  font-weight: var(--smrt-typography-weight-normal, 400);
197
201
  }
198
-
199
- .hint {
202
+ .smrt-invite-user-modal__hint {
200
203
  font: var(--smrt-typography-body-small-font, 0.75rem / 1.25 sans-serif);
201
204
  color: var(--smrt-color-on-surface-variant);
202
- padding: var(--smrt-spacing-sm, 0.5rem);
203
205
  background: var(--smrt-color-surface-container-low);
204
206
  border-radius: var(--smrt-radius-small, 0.25rem);
205
207
  }
206
208
  }
209
+
207
210
  </style>