@happyvertical/smrt-users 0.62.0 → 0.62.1

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,5 +1,5 @@
1
1
  import { $ as PermissionCatalogService, A as InvalidCredentialsError, At as STEP_UP_SIGN_IN_AUTH_METHODS, B as backfillUserEmailKeys, C as DEFAULT_LOGIN_ATTEMPT_WINDOW_SECONDS, Ct as SessionCollection, D as DEFAULT_LOGIN_MAX_ATTEMPTS, E as DEFAULT_LOGIN_LOCKOUT_MAX_SECONDS, Et as normalizeEmail, F as OidcProvisioningError, Ft as Membership, G as MAX_TENANT_HIERARCHY_DEPTH, H as TenantPermissionOverride, I as UserCollection, J as assertTenantTableName, K as TenantHierarchyError, L as requireExistingOwnedPerson, M as LoginRateLimitError, Mt as generateSessionId, Nt as Role, O as DEFAULT_SOURCE_LOCKOUT_AUDIT_SECONDS, Ot as DEFAULT_SESSION_TTL, Pt as Permission, Q as RolePermissionCollection, S as normalizeAncestorReadPolicy, St as UsersLoginAttempt, T as DEFAULT_LOGIN_LOCKOUT_FACTOR, Tt as isValidEmail, U as TenantCollection, V as TenantPermissionOverrideCollection, W as Tenant, X as recordTenantHierarchyChanges, Y as planTenantHierarchy, Z as DEFAULT_ROLE_PERMISSION_PATTERNS, _ as PermissionResolver, _t as GroupCollection, a as DEFAULT_PASSWORD_RECOVERY_MAX_AGE_SECONDS, at as RolePermission, b as getConfiguredAncestorReadPolicy, bt as UsersLoginAuditEvent, c as PASSWORD_PERMISSION_DEFINITIONS, ct as UsersPasswordCredentialCollection, d as PasswordCredentialForbiddenError, dt as MembershipOverride, et as deriveOperationPermissionCollectionName, f as PasswordCredentialService, ft as MembershipCollection, g as SessionService, gt as GroupMember, h as outOfBandProofSessionData, ht as GroupMemberCollection, i as DEFAULT_PASSWORD_MIN_LENGTH, it as withoutListBounds, j as LoginAttemptLimiter, jt as Session, k as DurableLoginAuditSink, kt as SESSION_DATA_KEYS, l as PASSWORD_RECOVERY_MAX_AGE_CEILING_SECONDS, lt as UsersPasswordCredential, m as ensurePasswordPermissionsRegistered, mt as GroupRole, n as DEFAULT_PASSWORD_MANAGE_PERMISSION, nt as normalizeOperationPermissionAction, o as PASSWORD_LOGIN_KIND, ot as RoleCollection, p as PasswordPolicyError, pt as GroupRoleCollection, q as applyTenantHierarchyUpdates, r as DEFAULT_PASSWORD_MAX_LENGTH, rt as syncPermissionCatalog, s as PASSWORD_MAX_LENGTH_CEILING, st as PermissionCollection, t as DEFAULT_PASSWORD_DENYLIST, tt as deriveOperationPermissionSlug, u as PasswordCredentialError, ut as MembershipOverrideCollection, v as ANCESTOR_READ_ACTION, vt as Group, w as DEFAULT_LOGIN_LOCKOUT_BASE_SECONDS, wt as User, x as isAncestorReadableSlug, xt as UsersLoginAttemptCollection, y as DEFAULT_ANCESTOR_READ_MAX_DEPTH, yt as UsersLoginAuditEventCollection, z as UserEmailKeyBackfillError } from "./chunks/PasswordCredentialService-BfYi-lfi.js";
2
- import { $ as PIN_PERMISSION_DEFINITIONS, A as hasOperationPermission, B as OidcLoginService, C as PasskeyCredentialService, D as OperationPermissionError, E as ensurePasskeyPermissionsRegistered, F as MobileAuthError, H as encodeOidcTransaction, I as MobileAuthService, J as DeviceCredentialError, K as DEFAULT_DEVICE_PERSON_IDLE_SECONDS, L as readMobileBearerToken, M as getRequestScopedDatabase, N as withPrincipalPermissionContext, O as assertOperationPermission, P as withSessionPermissionContext, Q as PIN_LOGIN_KIND, R as validateMobileRedirectUri, S as PasskeyCredentialForbiddenError, T as PasskeyRegistrationError, U as getUsersOidcConfig, V as decodeOidcTransaction, W as resolveOidcProviderConfig, X as DeviceCredentialPolicyError, Y as DeviceCredentialForbiddenError, Z as DeviceCredentialService, _ as PASSKEY_MAX_PER_USER_CEILING, a as TerminalAuthError, at as UsersPasskeyCredential, b as PASSKEY_SESSION_DATA_KEY, c as DEFAULT_MAX_PASSKEYS_PER_USER, ct as UsersPasskeyChallenge, d as DEFAULT_PASSKEY_FRESH_SESSION_SECONDS, et as PinVerifier, f as DEFAULT_PASSKEY_MANAGE_PERMISSION, g as PASSKEY_LOGIN_KIND, h as PASSKEY_FRESH_SESSION_FLOOR_SECONDS, i as TERMINAL_APPROVE_LOGIN_KIND, it as UsersPasskeyCredentialCollection, j as getCurrentSessionPermissionContext, k as checkOperationPermission, l as DEFAULT_PASSKEY_CHALLENGE_TTL_SECONDS, lt as UsersCliAuthRequestCollection, m as PASSKEY_FRESH_SESSION_CEILING_SECONDS, n as DEFAULT_CLI_AUTH_REQUEST_TTL_SECONDS, nt as UsersPinCredentialCollection, o as TerminalAuthRateLimitError, ot as UsersPasskeyChallengeCollection, p as DEFAULT_PASSKEY_NAME, q as DEFAULT_PIN_MANAGE_PERMISSION, r as DEFAULT_CLI_SESSION_TTL_SECONDS, rt as UsersPinCredential, s as TerminalAuthService, st as PASSKEY_CHALLENGE_TTL_CEILING_SECONDS, t as DEFAULT_CLI_AUTH_POLL_INTERVAL_SECONDS, tt as ensurePinPermissionsRegistered, u as DEFAULT_PASSKEY_FRESH_AUTH_METHODS, ut as UsersCliAuthRequest, v as PASSKEY_NAME_MAX_LENGTH, w as PasskeyReauthenticationRequiredError, x as PasskeyCredentialError, y as PASSKEY_PERMISSION_DEFINITIONS, z as OidcLoginError } from "./chunks/TerminalAuthService-1OIS6Bnv.js";
2
+ import { $ as PIN_PERMISSION_DEFINITIONS, A as hasOperationPermission, B as OidcLoginService, C as PasskeyCredentialService, D as OperationPermissionError, E as ensurePasskeyPermissionsRegistered, F as MobileAuthError, H as encodeOidcTransaction, I as MobileAuthService, J as DeviceCredentialError, K as DEFAULT_DEVICE_PERSON_IDLE_SECONDS, L as readMobileBearerToken, M as getRequestScopedDatabase, N as withPrincipalPermissionContext, O as assertOperationPermission, P as withSessionPermissionContext, Q as PIN_LOGIN_KIND, R as validateMobileRedirectUri, S as PasskeyCredentialForbiddenError, T as PasskeyRegistrationError, U as getUsersOidcConfig, V as decodeOidcTransaction, W as resolveOidcProviderConfig, X as DeviceCredentialPolicyError, Y as DeviceCredentialForbiddenError, Z as DeviceCredentialService, _ as PASSKEY_MAX_PER_USER_CEILING, a as TerminalAuthError, at as UsersPasskeyCredential, b as PASSKEY_SESSION_DATA_KEY, c as DEFAULT_MAX_PASSKEYS_PER_USER, ct as UsersPasskeyChallenge, d as DEFAULT_PASSKEY_FRESH_SESSION_SECONDS, et as PinVerifier, f as DEFAULT_PASSKEY_MANAGE_PERMISSION, g as PASSKEY_LOGIN_KIND, h as PASSKEY_FRESH_SESSION_FLOOR_SECONDS, i as TERMINAL_APPROVE_LOGIN_KIND, it as UsersPasskeyCredentialCollection, j as getCurrentSessionPermissionContext, k as checkOperationPermission, l as DEFAULT_PASSKEY_CHALLENGE_TTL_SECONDS, lt as UsersCliAuthRequestCollection, m as PASSKEY_FRESH_SESSION_CEILING_SECONDS, n as DEFAULT_CLI_AUTH_REQUEST_TTL_SECONDS, nt as UsersPinCredentialCollection, o as TerminalAuthRateLimitError, ot as UsersPasskeyChallengeCollection, p as DEFAULT_PASSKEY_NAME, q as DEFAULT_PIN_MANAGE_PERMISSION, r as DEFAULT_CLI_SESSION_TTL_SECONDS, rt as UsersPinCredential, s as TerminalAuthService, st as PASSKEY_CHALLENGE_TTL_CEILING_SECONDS, t as DEFAULT_CLI_AUTH_POLL_INTERVAL_SECONDS, tt as ensurePinPermissionsRegistered, u as DEFAULT_PASSKEY_FRESH_AUTH_METHODS, ut as UsersCliAuthRequest, v as PASSKEY_NAME_MAX_LENGTH, w as PasskeyReauthenticationRequiredError, x as PasskeyCredentialError, y as PASSKEY_PERMISSION_DEFINITIONS, z as OidcLoginError } from "./chunks/TerminalAuthService-3pzEWpFp.js";
3
3
  import { a as MembershipStatus, c as TenantPermissionEffect, i as DEFAULT_TENANT_POLICY, l as TenantStatus, n as DEFAULT_ROLES, o as OverrideEffect, r as DEFAULT_ROLE_SLUGS, s as SessionStatus, t as AccessRequestStatus, u as UserStatus } from "./chunks/types-DqUZxluX.js";
4
4
  import { t as registerPermissionDefinitions } from "./chunks/permission-registry-PhcdZvKe.js";
5
5
  import { DEFAULT_STEP_UP_MAX_AGE_SECONDS, STEP_UP_MAX_AGE_CEILING_SECONDS, STEP_UP_REQUIRED_CODE, StepUpRequiredError, isTenantOwnerSession, requireRecentAuthentication } from "./step-up.js";
@@ -2749,7 +2749,7 @@ var MagicLinkService = class MagicLinkService {
2749
2749
  return this.issue(email, this.tokenExpiry, { ...options.subject !== void 0 ? { sub: options.subject } : {} });
2750
2750
  }
2751
2751
  async issue(email, expirySeconds, claims) {
2752
- const { SignJWT } = await import("./chunks/TerminalAuthService-1OIS6Bnv.js").then((n) => n.G);
2752
+ const { SignJWT } = await import("./chunks/TerminalAuthService-3pzEWpFp.js").then((n) => n.G);
2753
2753
  const key = await this.getSigningKey();
2754
2754
  const nonce = crypto.randomUUID();
2755
2755
  const normalizedEmail = normalizeEmail(email);
@@ -2866,7 +2866,7 @@ var MagicLinkService = class MagicLinkService {
2866
2866
  };
2867
2867
  }
2868
2868
  async verifySignature(token) {
2869
- const { jwtVerify, errors } = await import("./chunks/TerminalAuthService-1OIS6Bnv.js").then((n) => n.G);
2869
+ const { jwtVerify, errors } = await import("./chunks/TerminalAuthService-3pzEWpFp.js").then((n) => n.G);
2870
2870
  const key = await this.getSigningKey();
2871
2871
  let payload;
2872
2872
  try {
@@ -2,7 +2,7 @@
2
2
  "version": "1.0.0",
3
3
  "timestamp": 0,
4
4
  "packageName": "@happyvertical/smrt-users",
5
- "packageVersion": "0.62.0",
5
+ "packageVersion": "0.62.1",
6
6
  "objects": {
7
7
  "@happyvertical/smrt-users:AccessRequestCollection": {
8
8
  "name": "accessrequestcollection",
@@ -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.62.0",
6
+ "packageVersion": "0.62.1",
7
7
  "sourceManifestPath": "dist/manifest.json",
8
8
  "agentDocPath": "AGENTS.md",
9
9
  "sourceHashes": {
10
- "manifest": "7776e60617dbc5dc36a33ea0ee313f1c2899ac6bbed67b30f5b2cf8bcb8fe750",
11
- "packageJson": "4abdf861537a4de1265b7196ac90b3e096847ccc17622e76fad3b3994d3feb20",
12
- "agents": "30b71cb25de701433b9b10de8968eaafb6f30e4dd933dc1328feac416c439d70",
10
+ "manifest": "fbeef8aecd4a2437b6e6e097b7438f7c7cc36f086d7555f6ea21977bd117b4a8",
11
+ "packageJson": "00122a0031d2131b42d8dab204d2bc806a70028a6a185e8664ed3a743bf6ab65",
12
+ "agents": "1a330a7858da6215d1e717eac5dd1f1dc3c3a8b6f133acdc23ae8c2090f15020",
13
13
  "moduleDoc:agents/permissions.md": "58e001789afc770ba904c1d971ada63b634684a04f69657514ce466422a90dee",
14
14
  "moduleDoc:agents/oidc-provisioning.md": "8408153424b22c6648f062151e261fe4b72271d5c0812b55e6d09a558a4386fd",
15
15
  "moduleDoc:agents/mobile-auth.md": "25e85e83f43e3a46383a92fa809f3a003b4545c3026e78dbe1bccbbc35161e18",
@@ -8335,7 +8335,7 @@
8335
8335
  "polymorphicAssociations": 0,
8336
8336
  "uuidColumns": 162
8337
8337
  },
8338
- "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",
8338
+ "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. The typecheck configs read workspace package sources, while\n`tsconfig.svelte.json` is used to package Svelte declarations. Follow root\nknowledge 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",
8339
8339
  "moduleDocs": [
8340
8340
  {
8341
8341
  "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-16T03:15:28Z"
8
+ at: "2026-11-16T19:29:11Z"
9
9
  audience: "internal"
10
10
  evidence_level: "source-inspected"
11
- source_revision: "sha256:f250b4c81d7371e8a933ea7b8114a4e68895ef70d0d71aff37339cd48ef1c723"
11
+ source_revision: "sha256:8548fce6f7038cd3733d9f8d4a33c9c0a3b1c1c603070683c9f16aeb4d81991d"
12
12
  sources:
13
13
  - id: "manifest"
14
14
  resource: "https://github.com/happyvertical/smrt/blob/main/packages/users/package.json"
package/dist/sveltekit.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { M as LoginRateLimitError, d as PasswordCredentialForbiddenError, f as PasswordCredentialService, g as SessionService, p as PasswordPolicyError, u as PasswordCredentialError } from "./chunks/PasswordCredentialService-BfYi-lfi.js";
2
- import { B as OidcLoginService, C as PasskeyCredentialService, D as OperationPermissionError, F as MobileAuthError, H as encodeOidcTransaction, I as MobileAuthService, J as DeviceCredentialError, L as readMobileBearerToken, P as withSessionPermissionContext, R as validateMobileRedirectUri, S as PasskeyCredentialForbiddenError, T as PasskeyRegistrationError, U as getUsersOidcConfig, V as decodeOidcTransaction, W as resolveOidcProviderConfig, X as DeviceCredentialPolicyError, Y as DeviceCredentialForbiddenError, Z as DeviceCredentialService, a as TerminalAuthError, o as TerminalAuthRateLimitError, s as TerminalAuthService, w as PasskeyReauthenticationRequiredError, x as PasskeyCredentialError, z as OidcLoginError } from "./chunks/TerminalAuthService-1OIS6Bnv.js";
2
+ import { B as OidcLoginService, C as PasskeyCredentialService, D as OperationPermissionError, F as MobileAuthError, H as encodeOidcTransaction, I as MobileAuthService, J as DeviceCredentialError, L as readMobileBearerToken, P as withSessionPermissionContext, R as validateMobileRedirectUri, S as PasskeyCredentialForbiddenError, T as PasskeyRegistrationError, U as getUsersOidcConfig, V as decodeOidcTransaction, W as resolveOidcProviderConfig, X as DeviceCredentialPolicyError, Y as DeviceCredentialForbiddenError, Z as DeviceCredentialService, a as TerminalAuthError, o as TerminalAuthRateLimitError, s as TerminalAuthService, w as PasskeyReauthenticationRequiredError, x as PasskeyCredentialError, z as OidcLoginError } from "./chunks/TerminalAuthService-3pzEWpFp.js";
3
3
  import { DiscoveryArtifactValidationError, SMRT_APP_RESULT_CONTRACT, SMRT_APP_RESULT_SCHEMA, SMRT_APP_RESULT_VERSION, SMRT_DISCOVERY_CONFORMANCE_ARTIFACT_SCHEMA, SMRT_DISCOVERY_CONFORMANCE_SCHEMA, SMRT_DISCOVERY_CONFORMANCE_VERSION, SMRT_MCP_RESULT_METADATA_KEY, canonicalizeDiscoveryArtifact, createDiscoveryConformanceArtifact, deriveCommandRequirements, validateDiscoveryConformanceArtifact } from "./app-contract.js";
4
4
  import { ObjectRegistry, createClassNamePredicate, resolveCustomActionMetadata, resolveEffectiveActionMetadata } from "@happyvertical/smrt-core";
5
5
  import { createLogger } from "@happyvertical/logger";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@happyvertical/smrt-users",
3
- "version": "0.62.0",
3
+ "version": "0.62.1",
4
4
  "smrtJsdoc": "strict",
5
5
  "description": "Multi-tenant user management for the SMRT framework - users, tenants, roles, permissions, groups",
6
6
  "type": "module",
@@ -61,20 +61,20 @@
61
61
  "dependencies": {
62
62
  "@happyvertical/auth": "^0.113.0",
63
63
  "@happyvertical/logger": "^0.113.0",
64
- "@happyvertical/smrt-config": "0.62.0",
65
- "@happyvertical/smrt-core": "0.62.0",
66
- "@happyvertical/smrt-mobile-contract": "0.62.0",
67
- "@happyvertical/smrt-profiles": "0.62.0",
68
- "@happyvertical/smrt-tenancy": "0.62.0",
69
- "@happyvertical/smrt-types": "0.62.0",
70
- "@happyvertical/smrt-ui": "0.62.0",
64
+ "@happyvertical/smrt-config": "0.62.1",
65
+ "@happyvertical/smrt-core": "0.62.1",
66
+ "@happyvertical/smrt-mobile-contract": "0.62.1",
67
+ "@happyvertical/smrt-profiles": "0.62.1",
68
+ "@happyvertical/smrt-tenancy": "0.62.1",
69
+ "@happyvertical/smrt-types": "0.62.1",
70
+ "@happyvertical/smrt-ui": "0.62.1",
71
71
  "@happyvertical/sql": "^0.113.0",
72
72
  "@simplewebauthn/browser": "^14.0.0",
73
73
  "@simplewebauthn/server": "^14.0.3",
74
74
  "jose": "^6.2.12"
75
75
  },
76
76
  "devDependencies": {
77
- "@happyvertical/smrt-vitest": "0.62.0",
77
+ "@happyvertical/smrt-vitest": "0.62.1",
78
78
  "@sveltejs/package": "^2.5.8",
79
79
  "@sveltejs/vite-plugin-svelte": "^7.3.0",
80
80
  "@types/node": "24.13.6",
@@ -112,8 +112,8 @@
112
112
  "dev": "npm run build:watch",
113
113
  "test": "vitest run",
114
114
  "test:postgres": "node ../../scripts/run-with-ci-postgres.mjs -- pnpm exec vitest run src/__tests__/operator-provisioning-postgres.test.ts src/__tests__/member-register-postgres.test.ts src/__tests__/member-eligibility-read.test.ts src/__tests__/permission-action-alias-postgres.test.ts src/__tests__/permission-postgres-rls.test.ts src/__tests__/principal-permission-context-postgres.test.ts src/__tests__/oidc-provisioning-postgres.test.ts src/__tests__/legacy-user-profile-backfill-postgres.test.ts src/__tests__/terminal-auth-postgres.test.ts src/__tests__/device-credential-postgres.test.ts src/__tests__/password-credential-postgres.test.ts src/__tests__/passkey-credential-postgres.test.ts src/__tests__/username-identity.test.ts src/__tests__/resource-grant-postgres.test.ts src/__tests__/issue-3036-hierarchy-resolution-postgres.test.ts src/__tests__/issue-3047-permission-resolution-cost-postgres.test.ts src/__tests__/issue-3048-authorization-list-bounds-postgres.test.ts src/__tests__/issue-3329-concurrent-seeding-postgres.test.ts src/__tests__/issue-3329-grant-dedup.test.ts src/__tests__/issue-3375-authority-pair-dedup.test.ts src/__tests__/issue-3375-authority-pair-identity.test.ts src/__tests__/oauth-authorization.test.ts src/__tests__/mailbox-authentication.test.ts src/__tests__/family-invitation.test.ts src/__tests__/mailbox-request-reservation.test.ts src/__tests__/mailbox-enrollment.test.ts",
115
- "typecheck": "tsc --noEmit && node ../../scripts/svelte-check-a11y.mjs --tsconfig ./tsconfig.svelte.json",
116
- "check": "pnpm exec svelte-check --tsconfig ./tsconfig.svelte.json",
115
+ "typecheck": "tsc -p tsconfig.typecheck.json && node ../../scripts/svelte-check-a11y.mjs --config ../../scripts/svelte.config.typecheck.mjs --tsconfig ./tsconfig.svelte-typecheck.json",
116
+ "check": "node ../../scripts/svelte-check-workspace.mjs --config ../../scripts/svelte.config.typecheck.mjs --tsconfig ./tsconfig.svelte-typecheck.json",
117
117
  "verify:pack": "node ../../scripts/verify-package-types-exports.js ."
118
118
  }
119
119
  }