@happyvertical/smrt-users 0.38.23 → 0.38.24

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import { $ as MembershipOverride, A as TenantPermissionOverride, B as RolePermissionCollection, C as decodeOidcTransaction, E as resolveOidcProviderConfig, F as SessionCollection, G as registerPermissionDefinitions, H as deriveOperationPermissionCollectionName, I as DEFAULT_SESSION_TTL, J as RoleCollection, K as syncPermissionCatalog, L as Session, M as TenantHierarchyError, N as MAX_TENANT_HIERARCHY_DEPTH, O as UserCollection, P as Tenant, Q as MembershipOverrideCollection, R as generateSessionId, S as OidcLoginService, St as UserStatus, T as getUsersOidcConfig, U as deriveOperationPermissionSlug, V as PermissionCatalogService, W as normalizeOperationPermissionAction, X as PermissionCollection, Y as Role, Z as Permission, _ as readMobileBearerToken, _t as MembershipStatus, a as TerminalAuthRateLimitError, at as GroupMember, b as PermissionResolver, bt as TenantPermissionEffect, c as assertOperationPermission, ct as UsersCliAuthRequestCollection, d as getCurrentSessionPermissionContext, dt as isValidEmail, et as MembershipCollection, f as getRequestScopedDatabase, ft as normalizeEmail, g as MobileAuthService, gt as DEFAULT_TENANT_POLICY, h as MobileAuthError, ht as DEFAULT_ROLE_SLUGS, i as TerminalAuthError, it as GroupMemberCollection, j as TenantCollection, k as TenantPermissionOverrideCollection, l as checkOperationPermission, lt as UsersCliAuthRequest, m as withSessionPermissionContext, mt as DEFAULT_ROLES, n as DEFAULT_CLI_AUTH_REQUEST_TTL_SECONDS, nt as GroupRoleCollection, o as TerminalAuthService, ot as GroupCollection, p as withPrincipalPermissionContext, pt as AccessRequestStatus, q as RolePermission, r as DEFAULT_CLI_SESSION_TTL_SECONDS, rt as GroupRole, s as OperationPermissionError, st as Group, t as DEFAULT_CLI_AUTH_POLL_INTERVAL_SECONDS, tt as Membership, u as hasOperationPermission, ut as User, v as validateMobileRedirectUri, vt as OverrideEffect, w as encodeOidcTransaction, x as OidcLoginError, xt as TenantStatus, y as SessionService, yt as SessionStatus, z as DEFAULT_ROLE_PERMISSION_PATTERNS } from "./chunks/TerminalAuthService-BjKbfFLR.js";
1
+ import { $ as MembershipOverride, A as TenantPermissionOverride, B as RolePermissionCollection, C as decodeOidcTransaction, E as resolveOidcProviderConfig, F as SessionCollection, G as registerPermissionDefinitions, H as deriveOperationPermissionCollectionName, I as DEFAULT_SESSION_TTL, J as RoleCollection, K as syncPermissionCatalog, L as Session, M as TenantHierarchyError, N as MAX_TENANT_HIERARCHY_DEPTH, O as UserCollection, P as Tenant, Q as MembershipOverrideCollection, R as generateSessionId, S as OidcLoginService, St as UserStatus, T as getUsersOidcConfig, U as deriveOperationPermissionSlug, V as PermissionCatalogService, W as normalizeOperationPermissionAction, X as PermissionCollection, Y as Role, Z as Permission, _ as readMobileBearerToken, _t as MembershipStatus, a as TerminalAuthRateLimitError, at as GroupMember, b as PermissionResolver, bt as TenantPermissionEffect, c as assertOperationPermission, ct as UsersCliAuthRequestCollection, d as getCurrentSessionPermissionContext, dt as isValidEmail, et as MembershipCollection, f as getRequestScopedDatabase, ft as normalizeEmail, g as MobileAuthService, gt as DEFAULT_TENANT_POLICY, h as MobileAuthError, ht as DEFAULT_ROLE_SLUGS, i as TerminalAuthError, it as GroupMemberCollection, j as TenantCollection, k as TenantPermissionOverrideCollection, l as checkOperationPermission, lt as UsersCliAuthRequest, m as withSessionPermissionContext, mt as DEFAULT_ROLES, n as DEFAULT_CLI_AUTH_REQUEST_TTL_SECONDS, nt as GroupRoleCollection, o as TerminalAuthService, ot as GroupCollection, p as withPrincipalPermissionContext, pt as AccessRequestStatus, q as RolePermission, r as DEFAULT_CLI_SESSION_TTL_SECONDS, rt as GroupRole, s as OperationPermissionError, st as Group, t as DEFAULT_CLI_AUTH_POLL_INTERVAL_SECONDS, tt as Membership, u as hasOperationPermission, ut as User, v as validateMobileRedirectUri, vt as OverrideEffect, w as encodeOidcTransaction, x as OidcLoginError, xt as TenantStatus, y as SessionService, yt as SessionStatus, z as DEFAULT_ROLE_PERMISSION_PATTERNS } from "./chunks/TerminalAuthService-9VB3eLYO.js";
2
2
  import { ObjectRegistry, SmrtCollection, SmrtObject, field, findManifestEntryByQualifiedName, smrt } from "@happyvertical/smrt-core";
3
3
  import { TenantScoped, tenantId } from "@happyvertical/smrt-tenancy";
4
4
  import { createLogger } from "@happyvertical/logger";
@@ -918,7 +918,7 @@ var MagicLinkService = class MagicLinkService {
918
918
  * The caller is responsible for emailing the token to the user.
919
919
  */
920
920
  async generate(email) {
921
- const { SignJWT } = await import("./chunks/TerminalAuthService-BjKbfFLR.js").then((n) => n.D);
921
+ const { SignJWT } = await import("./chunks/TerminalAuthService-9VB3eLYO.js").then((n) => n.D);
922
922
  const key = await this.getSigningKey();
923
923
  const nonce = crypto.randomUUID();
924
924
  const normalizedEmail = normalizeEmail(email);
@@ -947,7 +947,7 @@ var MagicLinkService = class MagicLinkService {
947
947
  * @throws {MagicLinkError} If the token is invalid, expired, or already used
948
948
  */
949
949
  async verify(token) {
950
- const { jwtVerify, errors } = await import("./chunks/TerminalAuthService-BjKbfFLR.js").then((n) => n.D);
950
+ const { jwtVerify, errors } = await import("./chunks/TerminalAuthService-9VB3eLYO.js").then((n) => n.D);
951
951
  const key = await this.getSigningKey();
952
952
  let payload;
953
953
  try {
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "version": "1.0.0",
3
- "timestamp": 1783633854404,
3
+ "timestamp": 1783637875164,
4
4
  "packageName": "@happyvertical/smrt-users",
5
- "packageVersion": "0.38.23",
5
+ "packageVersion": "0.38.24",
6
6
  "objects": {
7
7
  "@happyvertical/smrt-users:AccessRequestCollection": {
8
8
  "name": "accessrequestcollection",
@@ -1,14 +1,14 @@
1
1
  {
2
2
  "schemaVersion": 1,
3
- "generatedAt": "2026-07-09T21:50:54.792Z",
3
+ "generatedAt": "2026-07-09T22:57:55.578Z",
4
4
  "packageName": "@happyvertical/smrt-users",
5
- "packageVersion": "0.38.23",
5
+ "packageVersion": "0.38.24",
6
6
  "sourceManifestPath": "dist/manifest.json",
7
7
  "agentDocPath": "AGENTS.md",
8
8
  "sourceHashes": {
9
- "manifest": "d53d170bed634dd4e54e8a05001a7b22862902899ebdc73071d198e8e92d8b3f",
10
- "packageJson": "b0109a666663486ac55fcd28f6ec76f7b1973c000949a66237563178c4d0f1da",
11
- "agents": "994858a35636fc7a37372fe17b093d4a689e45466314f50dfd22ef09ba0a32af"
9
+ "manifest": "1efbeb5b434a70523500ae98873bd4d78a03031fa172b9202a6d90d5f044dffc",
10
+ "packageJson": "3f1b253d65cd4dca740a64773b0ca800ce71e24f4a5c29d9455f839c23646d92",
11
+ "agents": "529723694a1981f5aa1b39abe47007678a864c28d8e20ffc8f0d200da57c3226"
12
12
  },
13
13
  "exports": [
14
14
  ".",
@@ -3072,5 +3072,5 @@
3072
3072
  "polymorphicAssociations": 0,
3073
3073
  "uuidColumns": 52
3074
3074
  },
3075
- "agentDoc": "# @happyvertical/smrt-users\n\nMulti-tenant user management with RBAC, hierarchical tenants, session handling, and SvelteKit integration.\n\n## Models (14)\n\n| Model | Key Pattern |\n|-------|-------------|\n| User | Auth identity. `profileId` is plain string (not FK) to smrt-profiles. Email auto-lowercased. |\n| AccessRequest | \"Request access / waitlist\" record captured before a `User` exists. CLOSED generated surface (`api`/`mcp`/`cli` = `[]`) — all access via `AccessRequestService`. Email normalized + indexed; JSON `requestContext` (NOT `context` — reserved for slug scoping). |\n| Tenant | **STI** + hierarchical parent-child. `hierarchyPath` (materialized path), `hierarchyLevel`. Max depth 10. |\n| Session | Server-side. Secure UUID. TTL in **seconds** (not ms). Status auto-updates to EXPIRED on access. |\n| MagicLinkToken | Single-use email login token. Backed by `MagicLinkService`. |\n| Role | `tenantId = null` → system role (available to all tenants). `isSystem: true` blocks deletion. `inheritsToDescendants: true` (default false) opts the role's membership authority into descendant tenants. |\n| Permission | Slug format: `resource.action`. Parsed by PermissionResolver. |\n| Membership | User + Tenant + Role junction. UNIQUE(userId, tenantId). |\n| Group | Team within a tenant. Multiple roles via GroupRole. |\n| GroupMember, GroupRole, RolePermission | Join tables. |\n| MembershipOverride | Per-user permission grant/deny. **DENY always wins.** |\n| TenantPermissionOverride | Tenant-level cascade overrides. Effect: INHERIT/GRANT/DENY. |\n\n## Permission Resolution — Precedence (broad → specific, most-specific wins)\n\n`PermissionResolver.resolvePermissions` builds the effective set in this order;\neach later layer overrides earlier ones:\n\n1. **Tenant-inherited** — walk ancestors, apply each `TenantPermissionOverride`\n down the cascade (GRANT adds, DENY removes within the hierarchy)\n2. **Membership role** — base permissions from the user's role in the tenant\n3. **Group roles** — permissions from all groups the user belongs to **in that tenant**\n4. **Tenant-level DENY** *(removes; overrides role/group grants, tenant-wide)* — a\n `TenantPermissionOverride` with effect `DENY` is a HARD, tenant-wide block: it\n subtracts the DENY'd slug even if a role or group granted it (steps 2–3). It\n sits just **above** the per-user membership overrides and **below** role/group.\n5. **Membership GRANT override** *(re-adds; most specific)* — a per-user GRANT can\n re-add a slug a tenant DENY'd in step 4, because it is more specific.\n6. **Membership DENY override** *(absolute; always wins)* — a per-user DENY removes\n the slug last and is never overridden.\n\nSo a permission a role grants but the tenant DENYs is **removed**, unless that\nexact user also has a membership-GRANT override for it. A membership-DENY always\nwins. Tenant-DENY of an inherited/cascade grant still blocks it (unchanged).\nThe hard block reflects the tenant cascade's **net** resolution, not an\nunconditional union of every DENY in the chain — so a more-specific tenant GRANT\n(e.g. a child sub-tenant re-granting a permission its parent DENYs) still wins.\n\n### Membership selection — hierarchical inheritance (opt-in, #1866)\n\nWhich membership feeds step 2 above:\n\n1. **A direct membership row in the target tenant always pins resolution to\n itself** — active rows resolve normally; an inactive (pending/suspended)\n row resolves to the **empty set**. A direct row therefore *attenuates*\n rather than unions: \"viewer here, despite being network admin\" gives\n viewer, and a suspension in the child is effective even for users holding\n inheritable authority on an ancestor.\n2. **No direct row** → the resolver walks the tenant's ancestors (nearest\n first, from `hierarchyPath`) and resolves through the **nearest ACTIVE\n ancestor membership whose role has `inheritsToDescendants: true`**.\n Unflagged or inactive ancestor memberships are skipped (they neither confer\n nor block); there is **no union across the chain** — the nearest flagged\n membership alone is used. To attenuate a specific descendant, create a\n direct membership there or use a tenant-level DENY.\n3. **No qualifying ancestor** → empty set (byte-identical to the\n pre-inheritance resolver; with no role flagged, nothing changes).\n\nAll later layers run unchanged against the **target** tenant: the tenant\ncascade and tenant-DENY hard block come from the target tenant (a child can\ncarve authority out of an inherited role), group roles stay exact-tenant (only\ntarget-tenant groups contribute; ancestor groups never flow down), and\nmembership GRANT/DENY overrides travel with the ancestor membership used.\n`PermissionResolutionResult.inheritedFromTenantId` reports the ancestor tenant\nwhen inheritance was used (`null` for direct resolution).\n\nSafety: resolution is bounded by `MAX_TENANT_HIERARCHY_DEPTH`; malformed\n`hierarchyPath` values fail closed to the empty set — too deep,\nself-referential, duplicate ancestors, or inconsistent with the actual\n`parentTenantId` chain (the path is verified link-by-link against the loaded\nancestor rows before it is trusted as an authorization source). Tenant `status` is not consulted (parity with direct\nresolution). Caching: a long-lived `(user, tenant)` permission cache must also\ninvalidate on ancestor-membership changes and on `Role.inheritsToDescendants`\nflips — request-scoped caches (the common pattern) are unaffected.\n\nFlag roles at seed time with\n`seedSystemRoles({ inheritsToDescendants: ['owner', 'admin'] })` (additive:\nlisted slugs are flagged, omitted slugs are never unflagged; unknown slugs\nthrow). The default seed leaves every role exact-tenant.\n\n## Operation Permission Guards\n\n- Use `assertOperationPermission()` for hand-written mutations in SvelteKit form\n actions, custom endpoints, CLI scripts, and jobs. It derives the same\n `<collection>.<action>` slugs as `PermissionCatalogService` (`list`/`get` →\n `read`), requires the slug to exist in the catalog, then resolves permissions\n through `PermissionResolver`.\n- `assertOperationPermission()` throws fail-closed by default. Use\n `{ onDeny: 'return' }`, `checkOperationPermission()`, or\n `hasOperationPermission()` when a structured/boolean result is needed.\n- **Resource-tenant calling convention**: for resource-anchored authorization,\n pass the **resource's** tenant id — `tenantId: resourceTenantId` — not the\n session's current tenant. With `Role.inheritsToDescendants` flagged, a\n root-tenant admin then passes for any descendant resource with no app-side\n authority logic (and no membership fan-out), while per-child delegation and\n DENY precedence keep working. Do NOT pass a session-scoped `membership`\n alongside a different resource `tenantId` — a membership/tenant mismatch\n fails closed by design; omit `membership` and let the resolver look it up.\n- System context and super-admin bypass context are honored for parity with\n Postgres RLS. Pass `{ allowSuperAdminBypass: false }` on money-class or\n separation-of-duties operations that must require an explicit permission grant.\n- **Postgres RLS and membership inheritance**: RLS policies check the\n session-injected `smrt.permissions` list (resolved app-side by\n `PermissionResolver`), so a session whose `smrt.tenant_id` IS the child\n tenant gets inherited authority in RLS automatically. But RLS row filtering\n stays bound to the session's tenant setting — a root-tenant session acting\n on child-tenant rows is authorized by the app-level guard (resource-tenant\n convention above), not by RLS. This is a documented divergence, mirroring\n how #1829 handled bypass parity.\n- Seed role mappings with `RolePermissionCollection.seedRolePermissions()` or\n `RoleCollection.seedSystemRoles({ seedPermissions: true })`. The default\n matrix maps owner/admin to all catalog permissions, member to read/create for\n ordinary app resources, and viewer to read-only. Member create grants\n intentionally exclude users/RBAC authority and security resources (`users`,\n `tenants`, `roles`, `permissions`, memberships, groups, sessions, magic-link\n tokens, and related join/override tables). Re-seeding is additive and\n idempotent; pruning stale mappings requires `{ prune: true }`.\n\n**Critical**: `getGroupIdsForTenant(userId, tenantId)` (joins with groups table to scope by tenant). Never use `getGroupIds()` — it's cross-tenant.\n\n## Hierarchical Tenants\n\n- `TenantCollection.createChild()` auto-calculates hierarchy fields, enforces depth limit\n- `moveToParent()` updates tenant + ALL descendants' paths/levels\n- `cascadePermissions` (parent pushes down) + `inheritPermissions` (child accepts) — both must be true\n- `getTree(rootId?)` returns nested structure for UI\n- Two independent downward flows: the `TenantPermissionOverride` **cascade**\n (tenant-level permission config, flags above) and **membership-role\n inheritance** (`Role.inheritsToDescendants`, per-role opt-in — see\n \"Membership selection\" above). The cascade flags do not gate membership\n inheritance.\n\n## SvelteKit Integration\n\n```typescript\n// hooks.server.ts\nexport const handle = createSessionHandler({ db, ttl: 604800, skipPaths: ['/api/public'] });\n// Populates event.locals: { user, membership, permissions: string[], tenantId, sessionId }\n\n// +page.server.ts\nawait createSessionCookie(event, userId, tenantId, { db });\nawait destroySessionCookie(event, { db });\nawait switchSessionTenant(event, tenantId, { db });\n```\n\n## Mobile `/api/mobile` Handlers (ADR 0001 Phase 3.5, #1748)\n\n`createMobileAuthHandlers(options)` (from `/sveltekit`) returns the mountable\nserver side of the KMP mobile contract: `authStart` (`POST auth/start`,\nserver-brokered PKCE via `OidcLoginService`), `authComplete`\n(`POST auth/complete`, code + echoed `state`/`codeVerifier` → bearer\nsession), `session.GET`/`session.DELETE` (bootstrap/logout), and\n`guard`/`withSession` — the bearer middleware for app-owned mobile routes.\nCore logic lives in `MobileAuthService` (framework-agnostic; exported from\nthe package root).\n\n- **Bearer = session id** (same convention as `TerminalAuthService`); 401\n bodies are `{ error, code }` and drive the mobile client's re-auth flow.\n- **Stateless handshake**: the OAuth `state` is an HMAC-signed token\n (secret: `stateSecret` ?? provider `clientSecret`) carrying\n nonce/provider/createdAt — full ID-token nonce verification with no\n server-side pending state. The `codeVerifier` never enters a URL: it is\n client-held per the frozen contract.\n- **Wire DTOs** come from `@happyvertical/smrt-mobile-contract`\n (`MobileAuthStartRequest` etc.) — one owning package for the Kotlin,\n Swift, and TypeScript shapes (compile-checked descriptors + parity test).\n- **Tenant options** honor `Role.inheritsToDescendants` (#1867): direct\n ACTIVE memberships plus descendants of flagged memberships (nearest\n flagged ancestor labels the option; any direct row pins; inactive direct\n rows exclude). Session binding defaults to the first DIRECT tenant —\n override with `resolveTenantId`.\n- **Hooks**: `resolveUser` (invite-gating; default provisions via\n `getOrCreateFromOidc`), `resolveTenantId`, `buildExtras` (bootstrap\n `extras`; model JSON must use `toPublicJSON({ permissions })` — #1822).\n `buildExtras` is the only app-domain bootstrap extension point. Never emit\n app fields such as `dashboard` at the response top level: they are outside\n `MobileSessionBootstrap` and the Kotlin decoder ignores them.\n- **Guard** wraps `withSessionPermissionContext`, so\n `assertOperationPermission`, tenancy context, and Postgres RLS all see the\n bearer caller; `OperationPermissionError` maps to 403 with a\n machine-readable `reason`.\n- **Uploads**: `resolveMobileUploadDedupKey` + the documented contract in\n `docs/content/architecture/mobile-upload-contract.md` (`clientCaptureId`\n field, `Idempotency-Key` header fallback); domain ingestion stays\n app-side. Framework-model writes ride `sync/apply`, not this path.\n- Configure `redirectUris` in production — RFC 8252 scheme rules always\n apply, but the allow list is the defense against redirecting authorization\n responses to attacker-controlled URIs.\n\n## Security (S5 #1400)\n\n- **Generated REST/MCP surface is READ-ONLY for every RBAC/identity model.**\n User, Tenant, Group, Membership, MembershipOverride, Role, Permission,\n RolePermission, GroupRole, GroupMember, and TenantPermissionOverride generate\n `list`/`get` only — `create`/`update`/`delete` are intentionally NOT\n generated. The merged `requireRouteAuth` gate (#1540) enforces *authentication*,\n not *authorization*, and these models are not `@TenantScoped`, so an\n auto-generated mutating route would let any authenticated user self-grant a\n role/permission, flip a tenant's cascade flags, or change another user's auth\n identity. Mutate them through the permission-gated services (`TenantService`,\n collection helpers) or consumer-owned, permission-checked handlers. A\n structural regression test (`security-audit-1400.test.ts`) enumerates the\n registry to assert no authority model exposes a mutating op. (`cli` stays\n enabled — local-operator surface, outside the network/agent threat model.)\n- **`switchTenant` is fail-closed AND rotates the session id.**\n `SessionService.switchTenant` / `switchSessionTenant` verify the session's user\n has an ACTIVE membership in the target tenant before any write (the tenant id\n is the isolation key for every `@TenantScoped` query). A non-member/unknown-\n session switch returns `{ switched: false, sessionId: null, ... }` and mutates\n nothing. On a successful switch into a NON-null tenant the session id is\n ROTATED: a fresh `Session` (new secure id, fresh TTL, same user, new tenant,\n device context carried over) is minted and the old session is REVOKED — so a\n captured pre-switch id immediately stops validating, shrinking the blast radius\n of a leaked id across a tenant boundary. `switchTenant` returns a\n `SwitchTenantResult` (`{ switched, sessionId, session, rotated }`); callers MUST\n persist the returned `sessionId`. `switchSessionTenant` does this for you by\n re-setting the session cookie (preserving httpOnly/secure/sameSite) to the new\n id. A `null` clear stays in place (no rotation, no cookie change). The\n low-level `SessionCollection.setSessionTenant` is the UNGUARDED primitive (used\n for the null-clear path) — never call it with an untrusted tenant id.\n- **OIDC `email_verified` is enforced.** `UserCollection.getOrCreateFromOidc`\n refuses to provision a user when the IdP explicitly returns\n `email_verified: false` (opt out with `{ allowUnverifiedEmail: true }`). An\n absent claim makes no assertion and is not enforced.\n\n## Gotchas\n\n- **seedSystemRoles() required**: call `RoleCollection.seedSystemRoles()` at app init (creates owner/admin/member/viewer)\n- **PermissionResolver casts `as any`**: collections have protected constructors — known framework limitation\n- **Session TTL in seconds**: `DEFAULT_SESSION_TTL = 7 * 24 * 60 * 60` (not milliseconds)\n- **Users are cross-tenant**: one user, many tenants via Membership. Email globally unique.\n- **Batch permission queries**: resolver fetches all permission IDs in one query, then maps to slugs (avoids N+1)\n"
3075
+ "agentDoc": "# @happyvertical/smrt-users\n\nMulti-tenant user management with RBAC, hierarchical tenants, session handling, and SvelteKit integration.\n\n## Models (14)\n\n| Model | Key Pattern |\n|-------|-------------|\n| User | Auth identity. `profileId` is plain string (not FK) to smrt-profiles. Email auto-lowercased. |\n| AccessRequest | \"Request access / waitlist\" record captured before a `User` exists. CLOSED generated surface (`api`/`mcp`/`cli` = `[]`) — all access via `AccessRequestService`. Email normalized + indexed; JSON `requestContext` (NOT `context` — reserved for slug scoping). |\n| Tenant | **STI** + hierarchical parent-child. `hierarchyPath` (materialized path), `hierarchyLevel`. Max depth 10. |\n| Session | Server-side. Secure UUID. TTL in **seconds** (not ms). Status auto-updates to EXPIRED on access. |\n| MagicLinkToken | Single-use email login token. Backed by `MagicLinkService`. |\n| Role | `tenantId = null` → system role (available to all tenants). `isSystem: true` blocks deletion. `inheritsToDescendants: true` (default false) opts the role's membership authority into descendant tenants. |\n| Permission | Slug format: `resource.action`. Parsed by PermissionResolver. |\n| Membership | User + Tenant + Role junction. UNIQUE(userId, tenantId). |\n| Group | Team within a tenant. Multiple roles via GroupRole. |\n| GroupMember, GroupRole, RolePermission | Join tables. |\n| MembershipOverride | Per-user permission grant/deny. **DENY always wins.** |\n| TenantPermissionOverride | Tenant-level cascade overrides. Effect: INHERIT/GRANT/DENY. |\n\n## Permission Resolution — Precedence (broad → specific, most-specific wins)\n\n`PermissionResolver.resolvePermissions` builds the effective set in this order;\neach later layer overrides earlier ones:\n\n1. **Tenant-inherited** — walk ancestors, apply each `TenantPermissionOverride`\n down the cascade (GRANT adds, DENY removes within the hierarchy)\n2. **Membership role** — base permissions from the user's role in the tenant\n3. **Group roles** — permissions from all groups the user belongs to **in that tenant**\n4. **Tenant-level DENY** *(removes; overrides role/group grants, tenant-wide)* — a\n `TenantPermissionOverride` with effect `DENY` is a HARD, tenant-wide block: it\n subtracts the DENY'd slug even if a role or group granted it (steps 2–3). It\n sits just **above** the per-user membership overrides and **below** role/group.\n5. **Membership GRANT override** *(re-adds; most specific)* — a per-user GRANT can\n re-add a slug a tenant DENY'd in step 4, because it is more specific.\n6. **Membership DENY override** *(absolute; always wins)* — a per-user DENY removes\n the slug last and is never overridden.\n\nSo a permission a role grants but the tenant DENYs is **removed**, unless that\nexact user also has a membership-GRANT override for it. A membership-DENY always\nwins. Tenant-DENY of an inherited/cascade grant still blocks it (unchanged).\nThe hard block reflects the tenant cascade's **net** resolution, not an\nunconditional union of every DENY in the chain — so a more-specific tenant GRANT\n(e.g. a child sub-tenant re-granting a permission its parent DENYs) still wins.\n\n### Membership selection — hierarchical inheritance (opt-in, #1866)\n\nWhich membership feeds step 2 above:\n\n1. **A direct membership row in the target tenant always pins resolution to\n itself** — active rows resolve normally; an inactive (pending/suspended)\n row resolves to the **empty set**. A direct row therefore *attenuates*\n rather than unions: \"viewer here, despite being network admin\" gives\n viewer, and a suspension in the child is effective even for users holding\n inheritable authority on an ancestor.\n2. **No direct row** → the resolver walks the tenant's ancestors (nearest\n first, from `hierarchyPath`) and resolves through the **nearest ACTIVE\n ancestor membership whose role has `inheritsToDescendants: true`**.\n Unflagged or inactive ancestor memberships are skipped (they neither confer\n nor block); there is **no union across the chain** — the nearest flagged\n membership alone is used. To attenuate a specific descendant, create a\n direct membership there or use a tenant-level DENY.\n3. **No qualifying ancestor** → empty set (byte-identical to the\n pre-inheritance resolver; with no role flagged, nothing changes).\n\nAll later layers run unchanged against the **target** tenant: the tenant\ncascade and tenant-DENY hard block come from the target tenant (a child can\ncarve authority out of an inherited role), group roles stay exact-tenant (only\ntarget-tenant groups contribute; ancestor groups never flow down), and\nmembership GRANT/DENY overrides travel with the ancestor membership used.\n`PermissionResolutionResult.inheritedFromTenantId` reports the ancestor tenant\nwhen inheritance was used (`null` for direct resolution).\n\nSafety: resolution is bounded by `MAX_TENANT_HIERARCHY_DEPTH`; malformed\n`hierarchyPath` values fail closed to the empty set — too deep,\nself-referential, duplicate ancestors, or inconsistent with the actual\n`parentTenantId` chain (the path is verified link-by-link against the loaded\nancestor rows before it is trusted as an authorization source). Tenant `status` is not consulted (parity with direct\nresolution). Caching: a long-lived `(user, tenant)` permission cache must also\ninvalidate on ancestor-membership changes and on `Role.inheritsToDescendants`\nflips — request-scoped caches (the common pattern) are unaffected.\n\nFlag roles at seed time with\n`seedSystemRoles({ inheritsToDescendants: ['owner', 'admin'] })` (additive:\nlisted slugs are flagged, omitted slugs are never unflagged; unknown slugs\nthrow). The default seed leaves every role exact-tenant.\n\n## Operation Permission Guards\n\nSMRT derives a fine-grained, per-`<collection>.<action>` permission catalog **from the\nmanifest** (`PermissionCatalogService`, including custom `@smrt` actions — not just CRUD)\nand enforces it two ways: app-side via `assertOperationPermission()` / `PermissionResolver`,\nand at the database via generated **Postgres RLS** policies\n(`generatePostgresPermissionSql()` / `applyPostgresPermissionPolicies()`) that read the\nsession-injected `smrt.permissions` / `smrt.tenant_id` (set by `withSessionPermissionContext`\nvia `set_config`). Because the RLS teeth are at the data layer, enforcement is door-agnostic\n— REST, MCP, and in-process callers are all bounded once the principal's context is set.\nSetup: README → *Manifest-derived permission catalog* and *Postgres RLS enforcement*.\n\n- Use `assertOperationPermission()` for hand-written mutations in SvelteKit form\n actions, custom endpoints, CLI scripts, and jobs. It derives the same\n `<collection>.<action>` slugs as `PermissionCatalogService` (`list`/`get` →\n `read`), requires the slug to exist in the catalog, then resolves permissions\n through `PermissionResolver`.\n- `assertOperationPermission()` throws fail-closed by default. Use\n `{ onDeny: 'return' }`, `checkOperationPermission()`, or\n `hasOperationPermission()` when a structured/boolean result is needed.\n- **Resource-tenant calling convention**: for resource-anchored authorization,\n pass the **resource's** tenant id — `tenantId: resourceTenantId` — not the\n session's current tenant. With `Role.inheritsToDescendants` flagged, a\n root-tenant admin then passes for any descendant resource with no app-side\n authority logic (and no membership fan-out), while per-child delegation and\n DENY precedence keep working. Do NOT pass a session-scoped `membership`\n alongside a different resource `tenantId` — a membership/tenant mismatch\n fails closed by design; omit `membership` and let the resolver look it up.\n- System context and super-admin bypass context are honored for parity with\n Postgres RLS. Pass `{ allowSuperAdminBypass: false }` on money-class or\n separation-of-duties operations that must require an explicit permission grant.\n- **Postgres RLS and membership inheritance**: RLS policies check the\n session-injected `smrt.permissions` list (resolved app-side by\n `PermissionResolver`), so a session whose `smrt.tenant_id` IS the child\n tenant gets inherited authority in RLS automatically. But RLS row filtering\n stays bound to the session's tenant setting — a root-tenant session acting\n on child-tenant rows is authorized by the app-level guard (resource-tenant\n convention above), not by RLS. This is a documented divergence, mirroring\n how #1829 handled bypass parity.\n- Seed role mappings with `RolePermissionCollection.seedRolePermissions()` or\n `RoleCollection.seedSystemRoles({ seedPermissions: true })`. The default\n matrix maps owner/admin to all catalog permissions, member to read/create for\n ordinary app resources, and viewer to read-only. Member create grants\n intentionally exclude users/RBAC authority and security resources (`users`,\n `tenants`, `roles`, `permissions`, memberships, groups, sessions, magic-link\n tokens, and related join/override tables). Re-seeding is additive and\n idempotent; pruning stale mappings requires `{ prune: true }`.\n\n**Critical**: `getGroupIdsForTenant(userId, tenantId)` (joins with groups table to scope by tenant). Never use `getGroupIds()` — it's cross-tenant.\n\n## Hierarchical Tenants\n\n- `TenantCollection.createChild()` auto-calculates hierarchy fields, enforces depth limit\n- `moveToParent()` updates tenant + ALL descendants' paths/levels\n- `cascadePermissions` (parent pushes down) + `inheritPermissions` (child accepts) — both must be true\n- `getTree(rootId?)` returns nested structure for UI\n- Two independent downward flows: the `TenantPermissionOverride` **cascade**\n (tenant-level permission config, flags above) and **membership-role\n inheritance** (`Role.inheritsToDescendants`, per-role opt-in — see\n \"Membership selection\" above). The cascade flags do not gate membership\n inheritance.\n\n## SvelteKit Integration\n\n```typescript\n// hooks.server.ts\nexport const handle = createSessionHandler({ db, ttl: 604800, skipPaths: ['/api/public'] });\n// Populates event.locals: { user, membership, permissions: string[], tenantId, sessionId }\n\n// +page.server.ts\nawait createSessionCookie(event, userId, tenantId, { db });\nawait destroySessionCookie(event, { db });\nawait switchSessionTenant(event, tenantId, { db });\n```\n\n## Mobile `/api/mobile` Handlers (ADR 0001 Phase 3.5, #1748)\n\n`createMobileAuthHandlers(options)` (from `/sveltekit`) returns the mountable\nserver side of the KMP mobile contract: `authStart` (`POST auth/start`,\nserver-brokered PKCE via `OidcLoginService`), `authComplete`\n(`POST auth/complete`, code + echoed `state`/`codeVerifier` → bearer\nsession), `session.GET`/`session.DELETE` (bootstrap/logout), and\n`guard`/`withSession` — the bearer middleware for app-owned mobile routes.\nCore logic lives in `MobileAuthService` (framework-agnostic; exported from\nthe package root).\n\n- **Bearer = session id** (same convention as `TerminalAuthService`); 401\n bodies are `{ error, code }` and drive the mobile client's re-auth flow.\n- **Stateless handshake**: the OAuth `state` is an HMAC-signed token\n (secret: `stateSecret` ?? provider `clientSecret`) carrying\n nonce/provider/createdAt — full ID-token nonce verification with no\n server-side pending state. The `codeVerifier` never enters a URL: it is\n client-held per the frozen contract.\n- **Wire DTOs** come from `@happyvertical/smrt-mobile-contract`\n (`MobileAuthStartRequest` etc.) — one owning package for the Kotlin,\n Swift, and TypeScript shapes (compile-checked descriptors + parity test).\n- **Tenant options** honor `Role.inheritsToDescendants` (#1867): direct\n ACTIVE memberships plus descendants of flagged memberships (nearest\n flagged ancestor labels the option; any direct row pins; inactive direct\n rows exclude). Session binding defaults to the first DIRECT tenant —\n override with `resolveTenantId`.\n- **Hooks**: `resolveUser` (invite-gating; default provisions via\n `getOrCreateFromOidc`), `resolveTenantId`, `buildExtras` (bootstrap\n `extras`; model JSON must use `toPublicJSON({ permissions })` — #1822).\n `buildExtras` is the only app-domain bootstrap extension point. Never emit\n app fields such as `dashboard` at the response top level: they are outside\n `MobileSessionBootstrap` and the Kotlin decoder ignores them.\n- **Guard** wraps `withSessionPermissionContext`, so\n `assertOperationPermission`, tenancy context, and Postgres RLS all see the\n bearer caller; `OperationPermissionError` maps to 403 with a\n machine-readable `reason`.\n- **Uploads**: `resolveMobileUploadDedupKey` + the documented contract in\n `docs/content/architecture/mobile-upload-contract.md` (`clientCaptureId`\n field, `Idempotency-Key` header fallback); domain ingestion stays\n app-side. Framework-model writes ride `sync/apply`, not this path.\n- Configure `redirectUris` in production — RFC 8252 scheme rules always\n apply, but the allow list is the defense against redirecting authorization\n responses to attacker-controlled URIs.\n\n## Security (S5 #1400)\n\n- **Generated REST/MCP surface is READ-ONLY for every RBAC/identity model.**\n User, Tenant, Group, Membership, MembershipOverride, Role, Permission,\n RolePermission, GroupRole, GroupMember, and TenantPermissionOverride generate\n `list`/`get` only — `create`/`update`/`delete` are intentionally NOT\n generated. The merged `requireRouteAuth` gate (#1540) enforces *authentication*,\n not *authorization*, and these models are not `@TenantScoped`, so an\n auto-generated mutating route would let any authenticated user self-grant a\n role/permission, flip a tenant's cascade flags, or change another user's auth\n identity. Mutate them through the permission-gated services (`TenantService`,\n collection helpers) or consumer-owned, permission-checked handlers. A\n structural regression test (`security-audit-1400.test.ts`) enumerates the\n registry to assert no authority model exposes a mutating op. (`cli` stays\n enabled — local-operator surface, outside the network/agent threat model.)\n- **`switchTenant` is fail-closed AND rotates the session id.**\n `SessionService.switchTenant` / `switchSessionTenant` verify the session's user\n has an ACTIVE membership in the target tenant before any write (the tenant id\n is the isolation key for every `@TenantScoped` query). A non-member/unknown-\n session switch returns `{ switched: false, sessionId: null, ... }` and mutates\n nothing. On a successful switch into a NON-null tenant the session id is\n ROTATED: a fresh `Session` (new secure id, fresh TTL, same user, new tenant,\n device context carried over) is minted and the old session is REVOKED — so a\n captured pre-switch id immediately stops validating, shrinking the blast radius\n of a leaked id across a tenant boundary. `switchTenant` returns a\n `SwitchTenantResult` (`{ switched, sessionId, session, rotated }`); callers MUST\n persist the returned `sessionId`. `switchSessionTenant` does this for you by\n re-setting the session cookie (preserving httpOnly/secure/sameSite) to the new\n id. A `null` clear stays in place (no rotation, no cookie change). The\n low-level `SessionCollection.setSessionTenant` is the UNGUARDED primitive (used\n for the null-clear path) — never call it with an untrusted tenant id.\n- **OIDC `email_verified` is enforced.** `UserCollection.getOrCreateFromOidc`\n refuses to provision a user when the IdP explicitly returns\n `email_verified: false` (opt out with `{ allowUnverifiedEmail: true }`). An\n absent claim makes no assertion and is not enforced.\n\n## Gotchas\n\n- **seedSystemRoles() required**: call `RoleCollection.seedSystemRoles()` at app init (creates owner/admin/member/viewer)\n- **PermissionResolver casts `as any`**: collections have protected constructors — known framework limitation\n- **Session TTL in seconds**: `DEFAULT_SESSION_TTL = 7 * 24 * 60 * 60` (not milliseconds)\n- **Users are cross-tenant**: one user, many tenants via Membership. Email globally unique.\n- **Batch permission queries**: resolver fetches all permission IDs in one query, then maps to slugs (avoids N+1)\n"
3076
3076
  }
package/dist/sveltekit.js CHANGED
@@ -1,4 +1,4 @@
1
- import { C as decodeOidcTransaction, E as resolveOidcProviderConfig, S as OidcLoginService, T as getUsersOidcConfig, _ as readMobileBearerToken, a as TerminalAuthRateLimitError, g as MobileAuthService, h as MobileAuthError, i as TerminalAuthError, m as withSessionPermissionContext, o as TerminalAuthService, s as OperationPermissionError, v as validateMobileRedirectUri, w as encodeOidcTransaction, x as OidcLoginError, y as SessionService } from "./chunks/TerminalAuthService-BjKbfFLR.js";
1
+ import { C as decodeOidcTransaction, E as resolveOidcProviderConfig, S as OidcLoginService, T as getUsersOidcConfig, _ as readMobileBearerToken, a as TerminalAuthRateLimitError, g as MobileAuthService, h as MobileAuthError, i as TerminalAuthError, m as withSessionPermissionContext, o as TerminalAuthService, s as OperationPermissionError, v as validateMobileRedirectUri, w as encodeOidcTransaction, x as OidcLoginError, y as SessionService } from "./chunks/TerminalAuthService-9VB3eLYO.js";
2
2
  import { ObjectRegistry } from "@happyvertical/smrt-core";
3
3
  import { createLogger } from "@happyvertical/logger";
4
4
  import { classnameToTablename } from "@happyvertical/smrt-core/utils";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@happyvertical/smrt-users",
3
- "version": "0.38.23",
3
+ "version": "0.38.24",
4
4
  "description": "Multi-tenant user management for the SMRT framework - users, tenants, roles, permissions, groups",
5
5
  "type": "module",
6
6
  "smrtRawPrimitives": "strict",
@@ -41,18 +41,18 @@
41
41
  }
42
42
  },
43
43
  "dependencies": {
44
- "@happyvertical/logger": "^0.77.0",
44
+ "@happyvertical/logger": "^0.78.0",
45
45
  "jose": "^6.2.3",
46
- "@happyvertical/smrt-config": "0.38.23",
47
- "@happyvertical/smrt-mobile-contract": "0.38.23",
48
- "@happyvertical/smrt-core": "0.38.23",
49
- "@happyvertical/smrt-profiles": "0.38.23",
50
- "@happyvertical/smrt-tenancy": "0.38.23",
51
- "@happyvertical/smrt-types": "0.38.23",
52
- "@happyvertical/smrt-ui": "0.38.23"
46
+ "@happyvertical/smrt-config": "0.38.24",
47
+ "@happyvertical/smrt-mobile-contract": "0.38.24",
48
+ "@happyvertical/smrt-core": "0.38.24",
49
+ "@happyvertical/smrt-profiles": "0.38.24",
50
+ "@happyvertical/smrt-tenancy": "0.38.24",
51
+ "@happyvertical/smrt-types": "0.38.24",
52
+ "@happyvertical/smrt-ui": "0.38.24"
53
53
  },
54
54
  "devDependencies": {
55
- "@happyvertical/sql": "^0.77.0",
55
+ "@happyvertical/sql": "^0.78.0",
56
56
  "@sveltejs/package": "^2.5.8",
57
57
  "@sveltejs/vite-plugin-svelte": "^7.1.2",
58
58
  "@types/node": "24.13.2",
@@ -62,7 +62,7 @@
62
62
  "typescript": "^5.9.3",
63
63
  "vite": "^8.1.3",
64
64
  "vitest": "^4.1.9",
65
- "@happyvertical/smrt-vitest": "0.38.23"
65
+ "@happyvertical/smrt-vitest": "0.38.24"
66
66
  },
67
67
  "keywords": [
68
68
  "smrt",