@happyvertical/smrt-users 0.63.0 → 0.64.0

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/README.md CHANGED
@@ -1818,7 +1818,8 @@ authority and effective dates, and no posting or balance is copied here.
1818
1818
  | `createSessionHandler` | SvelteKit handle hook that populates `event.locals`, and can also enter tenancy context and Postgres RLS request transactions |
1819
1819
  | `createSessionCookie` | Set session cookie after login |
1820
1820
  | `destroySessionCookie` | Clear session cookie on logout |
1821
- | `switchSessionTenant` | Change tenant context for current session |
1821
+ | `switchSessionTenant` | Change tenant context for current session; also records it as the user's last tenant |
1822
+ | `lastActiveTenantFor` | Tenant the user last switched into, or `null` unless they still hold an active membership in an active tenant (usable while tenantless) |
1822
1823
  | `beginOidcLogin`, `completeOidcLogin` | Low-level SvelteKit helpers for custom OIDC login routes |
1823
1824
  | `createOidcLoginHandler`, `createOidcCallbackHandler` | Ready-to-use SvelteKit route handlers for OIDC login and callback |
1824
1825
  | `getOidcClientRegistration` | Redirect URL and landing (login start) URL to register with the IdP for an OIDC client |
@@ -2057,3 +2058,29 @@ rows. Generated collection action writes still require the **item model's**
2057
2058
  collection permission (for example `items.submit`, even if the route is
2058
2059
  `/api/operations/submit`), and domain actions retain their tenant checks. See
2059
2060
  [collection action resources](../core/agents/generators.md#explicit-collection-action-resources).
2061
+
2062
+
2063
+ ## Resuming the last tenant (#5358)
2064
+
2065
+ A successful switch into a tenant (`switchSessionTenant()` or
2066
+ `SessionService.switchTenant()`) stamps `Membership.lastSelectedAt`, so the
2067
+ choice holds across devices and sign-ins. At sign-in, a person who belongs to
2068
+ several tenants can skip the workspace picker:
2069
+
2070
+ ```typescript
2071
+ import {
2072
+ lastActiveTenantFor,
2073
+ switchSessionTenant,
2074
+ } from '@happyvertical/smrt-users/sveltekit';
2075
+
2076
+ const last = await lastActiveTenantFor(userId, { db });
2077
+ if (last) await switchSessionTenant(event, last, { db }); // normal checks still run
2078
+ ```
2079
+
2080
+ `SessionService.lastActiveTenantFor(userId)` is the service form. It returns the
2081
+ most recently selected tenant id only while that membership is ACTIVE and the
2082
+ tenant is ACTIVE; otherwise `null` (an older tenant is never substituted).
2083
+ It grants nothing, works while the session is tenantless, and is per user.
2084
+ Clearing the session's tenant (`switchTenant(id, null)`) does not forget it.
2085
+ Opt-in: apps that never call it see no behaviour change. The new nullable
2086
+ `lastSelectedAt` column on `memberships` needs the usual `smrt db:migrate`.
@@ -41,12 +41,14 @@ var Membership = class extends SmrtObject {
41
41
  tenantId;
42
42
  roleId;
43
43
  status = MembershipStatus.ACTIVE;
44
+ lastSelectedAt = null;
44
45
  constructor(options = {}) {
45
46
  super(options);
46
47
  if (options.userId !== void 0) this.userId = options.userId;
47
48
  if (options.tenantId !== void 0) this.tenantId = options.tenantId;
48
49
  if (options.roleId !== void 0) this.roleId = options.roleId;
49
50
  if (options.status !== void 0) this.status = options.status;
51
+ if (options.lastSelectedAt != null) this.lastSelectedAt = options.lastSelectedAt instanceof Date ? options.lastSelectedAt : new Date(options.lastSelectedAt);
50
52
  }
51
53
  /**
52
54
  * Check if membership is active
@@ -78,6 +80,11 @@ __decorateClass$14([field({
78
80
  description: "Whether this membership is active, pending, or inactive.",
79
81
  type: "text"
80
82
  })], Membership.prototype, "status", 2);
83
+ __decorateClass$14([field({
84
+ description: "When this person last switched into this organization, used to resume it at sign-in.",
85
+ type: "datetime",
86
+ nullable: true
87
+ })], Membership.prototype, "lastSelectedAt", 2);
81
88
  Membership = __decorateClass$14([smrt({
82
89
  api: { include: ["list", "get"] },
83
90
  mcp: { include: ["list", "get"] },
@@ -5620,6 +5627,7 @@ var SessionService = class SessionService {
5620
5627
  sessionCollection;
5621
5628
  userCollection;
5622
5629
  membershipCollection;
5630
+ tenantCollection;
5623
5631
  permissionResolver;
5624
5632
  defaultTTL;
5625
5633
  autoExtend;
@@ -5635,6 +5643,7 @@ var SessionService = class SessionService {
5635
5643
  this.sessionCollection = await SessionCollection.create(this.options);
5636
5644
  this.userCollection = await UserCollection.create(this.options);
5637
5645
  this.membershipCollection = await MembershipCollection.create(this.options);
5646
+ this.tenantCollection = await TenantCollection.create(this.options);
5638
5647
  this.permissionResolver = await PermissionResolver.create(this.options);
5639
5648
  }
5640
5649
  /**
@@ -5820,13 +5829,15 @@ var SessionService = class SessionService {
5820
5829
  const parentSession = await this.sessionCollection.findValidSession(session.parentSessionId);
5821
5830
  if (!parentSession || parentSession.tenantId !== tenantId) return failClosed;
5822
5831
  }
5823
- if (!(await this.membershipCollection.findByUserAndTenant(session.userId, tenantId))?.isActive()) return failClosed;
5832
+ const membership = await this.membershipCollection.findByUserAndTenant(session.userId, tenantId);
5833
+ if (!membership?.isActive()) return failClosed;
5824
5834
  if (session.isLayered()) {
5825
5835
  if (session.tenantId !== tenantId) {
5826
5836
  if (!await this.sessionCollection.setSessionTenant(sessionId, tenantId)) return failClosed;
5827
5837
  }
5828
5838
  const current = await this.sessionCollection.findValidSession(sessionId);
5829
5839
  if (!current) return failClosed;
5840
+ await this.rememberTenant(membership);
5830
5841
  return {
5831
5842
  switched: true,
5832
5843
  sessionId,
@@ -5849,6 +5860,7 @@ var SessionService = class SessionService {
5849
5860
  authMethod: session.authMethod,
5850
5861
  parentSessionId: session.parentSessionId
5851
5862
  });
5863
+ await this.rememberTenant(membership);
5852
5864
  return {
5853
5865
  switched: true,
5854
5866
  sessionId: rotated.id,
@@ -5857,6 +5869,34 @@ var SessionService = class SessionService {
5857
5869
  };
5858
5870
  }
5859
5871
  /**
5872
+ * Record the tenant a user just switched into (#5358). Best effort: a failed
5873
+ * write must never fail or undo a switch that already succeeded.
5874
+ */
5875
+ async rememberTenant(membership) {
5876
+ try {
5877
+ membership.lastSelectedAt = /* @__PURE__ */ new Date();
5878
+ await membership.save();
5879
+ } catch {}
5880
+ }
5881
+ /**
5882
+ * The tenant `userId` last switched a session into, for an app's sign-in step
5883
+ * to resume (#5358). Usable while the session is still tenantless.
5884
+ *
5885
+ * Returns the tenant id only while the user still holds an ACTIVE membership
5886
+ * there AND the tenant is ACTIVE; a removed or suspended membership, an
5887
+ * inactive tenant, or no recorded switch returns `null` (the next most
5888
+ * recently selected valid tenant is NOT substituted). Grants nothing: the app
5889
+ * must still call `switchTenant()` / `switchSessionTenant()`, which runs the
5890
+ * normal membership checks. Clearing the tenant (`switchTenant(id, null)`)
5891
+ * does not forget it. The value is per user and never crosses users.
5892
+ */
5893
+ async lastActiveTenantFor(userId) {
5894
+ if (!userId) return null;
5895
+ const latest = (await this.membershipCollection.findByUser(userId)).filter((m) => m.lastSelectedAt).sort((a, b) => b.lastSelectedAt.getTime() - a.lastSelectedAt.getTime())[0];
5896
+ if (!latest?.isActive() || !latest.tenantId) return null;
5897
+ return (await this.tenantCollection.get({ id: latest.tenantId }))?.isActive() ? latest.tenantId : null;
5898
+ }
5899
+ /**
5860
5900
  * Get all active sessions for a user (for "manage sessions" UI)
5861
5901
  */
5862
5902
  async getUserSessions(userId) {
@@ -6525,4 +6565,4 @@ var PasswordCredentialService = class PasswordCredentialService {
6525
6565
  //#endregion
6526
6566
  export { PermissionCatalogService as $, InvalidCredentialsError as A, normalizeEmail as At, backfillUserEmailKeys as B, __exportAll as Bt, DEFAULT_LOGIN_ATTEMPT_WINDOW_SECONDS as C, SessionCollection as Ct, DEFAULT_LOGIN_MAX_ATTEMPTS as D, User as Dt, DEFAULT_LOGIN_LOCKOUT_MAX_SECONDS as E, ServicePrincipalError as Et, OidcProvisioningError as F, Session as Ft, MAX_TENANT_HIERARCHY_DEPTH as G, TenantPermissionOverride as H, UserCollection as I, generateSessionId as It, assertTenantTableName as J, TenantHierarchyError as K, requireExistingOwnedPerson as L, Role as Lt, LoginRateLimitError as M, DEFAULT_SESSION_TTL as Mt, hashSecret as N, SESSION_DATA_KEYS as Nt, DEFAULT_SOURCE_LOCKOUT_AUDIT_SECONDS as O, isServicePrincipalKind as Ot, verifySecretHash as P, STEP_UP_SIGN_IN_AUTH_METHODS as Pt, RolePermissionCollection as Q, USER_EMAIL_KEY_BACKFILL_NAME as R, Permission as Rt, normalizeAncestorReadPolicy as S, UsersLoginAttempt as St, DEFAULT_LOGIN_LOCKOUT_FACTOR as T, SERVICE_PRINCIPAL_KIND as Tt, TenantCollection as U, TenantPermissionOverrideCollection as V, Tenant as W, recordTenantHierarchyChanges as X, planTenantHierarchy as Y, DEFAULT_ROLE_PERMISSION_PATTERNS as Z, PermissionResolver as _, GroupCollection as _t, DEFAULT_PASSWORD_RECOVERY_MAX_AGE_SECONDS as a, RolePermission as at, getConfiguredAncestorReadPolicy as b, UsersLoginAuditEvent as bt, PASSWORD_PERMISSION_DEFINITIONS as c, UsersPasswordCredentialCollection as ct, PasswordCredentialForbiddenError as d, MembershipOverride as dt, deriveOperationPermissionCollectionName as et, PasswordCredentialService as f, MembershipCollection as ft, SessionService as g, GroupMember as gt, outOfBandProofSessionData as h, GroupMemberCollection as ht, DEFAULT_PASSWORD_MIN_LENGTH as i, withoutListBounds as it, LoginAttemptLimiter as j, normalizeUsername as jt, DurableLoginAuditSink as k, isValidEmail as kt, PASSWORD_RECOVERY_MAX_AGE_CEILING_SECONDS as l, UsersPasswordCredential as lt, ensurePasswordPermissionsRegistered as m, GroupRole as mt, DEFAULT_PASSWORD_MANAGE_PERMISSION as n, normalizeOperationPermissionAction as nt, PASSWORD_LOGIN_KIND as o, RoleCollection as ot, PasswordPolicyError as p, GroupRoleCollection as pt, applyTenantHierarchyUpdates as q, DEFAULT_PASSWORD_MAX_LENGTH as r, syncPermissionCatalog as rt, PASSWORD_MAX_LENGTH_CEILING as s, PermissionCollection as st, DEFAULT_PASSWORD_DENYLIST as t, deriveOperationPermissionSlug as tt, PasswordCredentialError as u, MembershipOverrideCollection as ut, ANCESTOR_READ_ACTION as v, Group as vt, DEFAULT_LOGIN_LOCKOUT_BASE_SECONDS as w, isSessionlessPrincipalUser as wt, isAncestorReadableSlug as x, UsersLoginAttemptCollection as xt, DEFAULT_ANCESTOR_READ_MAX_DEPTH as y, UsersLoginAuditEventCollection as yt, UserEmailKeyBackfillError as z, Membership as zt };
6527
6567
 
6528
- //# sourceMappingURL=PasswordCredentialService-DODrdCBc.js.map
6568
+ //# sourceMappingURL=PasswordCredentialService-Dec3bz4G.js.map