@happyvertical/smrt-users 0.57.41 → 0.57.43

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (30) hide show
  1. package/AGENTS.md +1 -0
  2. package/agents/family-invitations.md +62 -0
  3. package/dist/chunks/{PasswordCredentialService-bedKxkaa.js → PasswordCredentialService-DHJNKEeJ.js} +53 -7
  4. package/dist/chunks/PasswordCredentialService-DHJNKEeJ.js.map +1 -0
  5. package/dist/chunks/{TerminalAuthService-DU1uUFVC.js → TerminalAuthService-B1SqTDum.js} +3 -3
  6. package/dist/chunks/TerminalAuthService-B1SqTDum.js.map +1 -0
  7. package/dist/collections/UserCollection.d.ts +7 -0
  8. package/dist/collections/UserCollection.d.ts.map +1 -1
  9. package/dist/index.d.ts +1 -1
  10. package/dist/index.d.ts.map +1 -1
  11. package/dist/index.js +197 -17
  12. package/dist/index.js.map +1 -1
  13. package/dist/manifest.json +20 -1
  14. package/dist/operator.js +1 -1
  15. package/dist/services/LoginAttemptLimiter.d.ts +2 -0
  16. package/dist/services/LoginAttemptLimiter.d.ts.map +1 -1
  17. package/dist/services/MailboxAuthenticationService.d.ts +40 -1
  18. package/dist/services/MailboxAuthenticationService.d.ts.map +1 -1
  19. package/dist/services/TenantInvitationService.d.ts +17 -3
  20. package/dist/services/TenantInvitationService.d.ts.map +1 -1
  21. package/dist/services/index.d.ts +1 -1
  22. package/dist/services/index.d.ts.map +1 -1
  23. package/dist/smrt-knowledge.json +29 -6
  24. package/dist/sveltekit/index.d.ts +8 -3
  25. package/dist/sveltekit/index.d.ts.map +1 -1
  26. package/dist/sveltekit.js +2 -2
  27. package/dist/sveltekit.js.map +1 -1
  28. package/package.json +10 -10
  29. package/dist/chunks/PasswordCredentialService-bedKxkaa.js.map +0 -1
  30. package/dist/chunks/TerminalAuthService-DU1uUFVC.js.map +0 -1
package/AGENTS.md CHANGED
@@ -16,6 +16,7 @@ are not prerequisites for unrelated user-package work.
16
16
  | `src/services/DeviceCredentialService.ts` | per-person PIN layered on a device session (#3276), verifier seam for other credential kinds | this file, "Security boundaries" |
17
17
  | `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" |
18
18
  | `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" |
19
+ | `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) |
19
20
  | `src/retention.ts` | expired session/token/CLI-auth reaping and retention sweep wiring | [agents/retention.md](agents/retention.md) |
20
21
 
21
22
  ## Models and authority
@@ -0,0 +1,62 @@
1
+ ## Family invitations and preserved Person identity
2
+
3
+ Trusted hosts may use `prepare({tenantId,email,roleId})` instead of `roleSlug`
4
+ to select an exact destination-owned role (or genuine global system role). Both
5
+ selectors together, foreign-tenant roles and missing roles fail closed. The
6
+ legacy `roleSlug` path remains system-only. `existingProfilePolicy:'owned-person'`
7
+ is an explicit service option allowing an existing ACTIVE canonical User's
8
+ already-owned tenant Person; exact normalized email, Person discriminator, unique
9
+ ownership and active source-family membership/tenant are required. It never
10
+ rebinds profiles or credentials. New pending identities stay canonical global;
11
+ OIDC owner authorization still requires canonical global Person. Returning
12
+ `MailboxAuthenticationService` retains its existing global-only contract.
13
+
14
+ `UserCollection.requireOwnedPersonForTenant(userId,tenantId)` is a bounded
15
+ read for the exact current tenant actor, with active destination membership; it
16
+ validates the same preserved owned Person. System/bypass/different actors fail.
17
+ Consumers must use their transaction executor and treat returned profile data as
18
+ private identity data, never a cross-family directory.
19
+
20
+ Each `issue` rotates a random generation in canonical membership context memory
21
+ (`smrt/tenant-invitation`, `generation`) and signs it into grant bindings, so a
22
+ resend invalidates every earlier grant and its mailbox proofs. `revoke` affects
23
+ only pending membership, rotates generation and marks it inactive. `prepare`
24
+ may reprepare only service-revoked inactive membership with the same role;
25
+ manual inactive memberships stay refused. Malformed generation fails closed.
26
+ Never edit/forget this framework-owned state. Legacy grants without generation
27
+ remain valid until a rotation, expiry or consumption. Host scope/relationship
28
+ writes must follow acceptance on the same caller executor: a failure rolls back
29
+ nonces, activation, generation and host writes. Mint the canonical magic-link
30
+ session only after committed mailbox identity proof; the grant alone cannot mint.
31
+
32
+ ### Retained send budgets with embedded caller transactions
33
+
34
+ Before opening a caller transaction, use exported
35
+ `reserveMailboxAuthenticationRequest({limiter,scope,sourceKey})`. Scope is
36
+ `{purpose:'returning',email}` or `{purpose:'invitation',tenantId,email}`. Pass
37
+ its opaque `MailboxRequestReservation` as `reservation` to the corresponding
38
+ request method, with the same limiter instance configured on the service and
39
+ the same trusted source key. The capability is a frozen empty object branded
40
+ only in a private WeakMap: copying/serializing/forging/reusing it does not carry
41
+ authority. Claim is synchronous and consumes even mismatched attempts before
42
+ any await. It has no release/refund method; budget is settled with
43
+ `retainOnSuccess` before the host transaction, so transport/caller rollback
44
+ cannot refund it. Reserve outside all caller transactions; SDK versions without
45
+ root transaction introspection cannot prove that the host followed this rule.
46
+
47
+ SQLite/DuckDB requests without a pre-reservation fail before writes or delivery.
48
+ PostgreSQL retains its independently supplied root-limiter implicit request path
49
+ and its legacy subject keys; do not claim those counters are pooled with the new
50
+ capability keys. Each host should consistently use its selected request path.
51
+ Each capability expires at the earlier of thirty seconds or the earliest actual
52
+ reserved key window end; allowed `LoginAttemptLease.budgetExpiresAt` reports that
53
+ Unix-millisecond deadline. Request rechecks expiry after awaited identity work,
54
+ before proof generation and before delivery. Never retain capabilities for later
55
+ work or carry one across processes. Capability subject budgets use purpose-separated immutable
56
+ `['returning',normalizedEmail]` and `['invitation',tenantId,normalizedEmail]`
57
+ tuples, so malformed returning email cannot collide with invitation scope and preparing/reissuing membership
58
+ or grant generations does not reset the send budget. Source budget namespace is
59
+ shared across both purposes. Returning malformed/unknown email intentionally
60
+ consumes normal source budget and returns no proof: a host's unknown invitation
61
+ preflight may reserve `{purpose:'returning',email:''}`, discard the capability
62
+ and return its uniform failure response without a service/proof call.
@@ -1,7 +1,7 @@
1
1
  import { a as MembershipStatus, c as TenantPermissionEffect, l as TenantStatus, n as DEFAULT_ROLES, o as OverrideEffect, r as DEFAULT_ROLE_SLUGS, s as SessionStatus, u as UserStatus } from "./types-DFqeph0R.js";
2
2
  import { IN_LIST_CHUNK_SIZE, ObjectRegistry, SmrtCollection, SmrtObject, bumpChangeFeed, chunkArray, crossPackageRef, field, findManifestEntryByQualifiedName, foreignKey, inheritedCollectionSurface, isEmbeddedDatabase, isPostgresDatabase, resolveOperationPermissionAlias, smrt, withEmbeddedWriteTransaction } from "@happyvertical/smrt-core";
3
3
  import { getCurrentTenant, runTenantHierarchyReadScope, withSystemContext } from "@happyvertical/smrt-tenancy";
4
- import { AmbiguousOidcIdentityError, OidcIdentity, OidcIdentityCollection, normalizeIdentityEmail } from "@happyvertical/smrt-profiles";
4
+ import { AmbiguousOidcIdentityError, CanonicalPersonProfileError, OidcIdentity, OidcIdentityCollection, ProfileCollection, normalizeIdentityEmail } from "@happyvertical/smrt-profiles";
5
5
  import { createHash, randomBytes, randomUUID, scrypt, timingSafeEqual } from "node:crypto";
6
6
  import { getPackageConfig } from "@happyvertical/smrt-config";
7
7
  import { createLogger } from "@happyvertical/logger";
@@ -3898,6 +3898,34 @@ async function backfillUserEmailKeys(db) {
3898
3898
  }
3899
3899
  //#endregion
3900
3900
  //#region src/collections/UserCollection.ts
3901
+ async function requireExistingOwnedPerson(db, userId) {
3902
+ return withSystemContext(async () => {
3903
+ const unavailable = () => new CanonicalPersonProfileError("email_mismatch", "Owned Person identity is unavailable");
3904
+ if (isPostgresDatabase(db)) await db.query("SELECT id FROM users WHERE id = ? FOR UPDATE", userId);
3905
+ const users = await UserCollection.create({ db });
3906
+ const user = await users.get({ id: userId }, { cache: false });
3907
+ if (!user || user.status !== UserStatus.ACTIVE || !user.profileId || !user.email) throw unavailable();
3908
+ if ((await users.findCanonicalByEmail(user.email))?.id !== userId) throw unavailable();
3909
+ const owners = await users.list({
3910
+ where: { profileId: user.profileId },
3911
+ limit: 2
3912
+ });
3913
+ if (owners.length !== 1 || owners[0].id !== userId) throw unavailable();
3914
+ if (isPostgresDatabase(db)) await db.query("SELECT id FROM profiles WHERE id = ? FOR UPDATE", user.profileId);
3915
+ const profiles = await ProfileCollection.create({ db });
3916
+ const profile = await profiles.get({ id: user.profileId }, { cache: false });
3917
+ if (!await db.get("profiles", {
3918
+ id: user.profileId,
3919
+ _meta_type: "@happyvertical/smrt-profiles:Person"
3920
+ }) || !profile || await profile.getTypeSlug() !== "person" || normalizeIdentityEmail(profile.email ?? "") !== normalizeIdentityEmail(user.email)) throw unavailable();
3921
+ if (profile.tenantId == null) return profiles.requireCanonicalGlobalPerson(user.profileId, user.email);
3922
+ if (isPostgresDatabase(db)) await db.query("SELECT id FROM memberships WHERE user_id = ? AND tenant_id = ? FOR UPDATE", userId, profile.tenantId);
3923
+ const membership = await (await MembershipCollection.create({ db })).findByUserAndTenant(userId, profile.tenantId);
3924
+ const tenant = await (await TenantCollection.create({ db })).get({ id: profile.tenantId }, { cache: false });
3925
+ if (!membership || membership.status !== MembershipStatus.ACTIVE || tenant?.status !== TenantStatus.ACTIVE) throw unavailable();
3926
+ return profile;
3927
+ });
3928
+ }
3901
3929
  var OidcProvisioningError = class extends Error {
3902
3930
  constructor(code, message, options) {
3903
3931
  super(message, options);
@@ -3910,6 +3938,23 @@ var UserCollection = class UserCollection extends SmrtCollection {
3910
3938
  static _itemClass = User;
3911
3939
  userEmailKeysReadyPromise = null;
3912
3940
  /**
3941
+ * Read only the current active tenant actor's exact owned Person, including a
3942
+ * preserved Person in another family. No identity or membership is created.
3943
+ */
3944
+ async requireOwnedPersonForTenant(userId, tenantId) {
3945
+ const context = getCurrentTenant();
3946
+ if (!userId || !tenantId || context?.userId !== userId || context.tenantId !== tenantId || context.superAdminBypass) throw new Error("Owned Person identity is unavailable");
3947
+ const db = this.options.db;
3948
+ if (isPostgresDatabase(db)) {
3949
+ await db.query("SELECT id FROM users WHERE id = ? FOR UPDATE", userId);
3950
+ await db.query("SELECT id FROM memberships WHERE user_id = ? AND tenant_id = ? FOR UPDATE", userId, tenantId);
3951
+ }
3952
+ const membership = await (await MembershipCollection.create({ db })).findByUserAndTenant(userId, tenantId);
3953
+ const tenant = await (await TenantCollection.create({ db })).get({ id: tenantId }, { cache: false });
3954
+ if (!membership?.isActive() || tenant?.status !== TenantStatus.ACTIVE) throw new Error("Owned Person identity is unavailable");
3955
+ return requireExistingOwnedPerson(db, userId);
3956
+ }
3957
+ /**
3913
3958
  * Find user by email address
3914
3959
  */
3915
3960
  async findByEmail(email) {
@@ -4048,8 +4093,8 @@ var UserCollection = class UserCollection extends SmrtCollection {
4048
4093
  return db;
4049
4094
  }
4050
4095
  async provisionOidcIdentity(claims, provider, options, db) {
4051
- const { ProfileCollection } = await import("@happyvertical/smrt-profiles");
4052
- const profileCollection = await ProfileCollection.create({ db });
4096
+ const { ProfileCollection: ProfileCollection2 } = await import("@happyvertical/smrt-profiles");
4097
+ const profileCollection = await ProfileCollection2.create({ db });
4053
4098
  const identityCollection = await OidcIdentityCollection.create({ db });
4054
4099
  const existingIdentity = await this.findUniqueOidcIdentity(identityCollection, claims);
4055
4100
  const createResolverContext = () => ({
@@ -4186,9 +4231,9 @@ var UserCollection = class UserCollection extends SmrtCollection {
4186
4231
  const identityId = requireId(result.oidcIdentity.id, "OIDC identity");
4187
4232
  const userId = requireId(result.user.id, "OIDC User");
4188
4233
  return withSystemContext(async () => {
4189
- const { ProfileCollection } = await import("@happyvertical/smrt-profiles");
4234
+ const { ProfileCollection: ProfileCollection2 } = await import("@happyvertical/smrt-profiles");
4190
4235
  const users = await UserCollection.create({ db: rootDb });
4191
- const profiles = await ProfileCollection.create({ db: rootDb });
4236
+ const profiles = await ProfileCollection2.create({ db: rootDb });
4192
4237
  const identities = await OidcIdentityCollection.create({ db: rootDb });
4193
4238
  const user = await users.get({ id: userId });
4194
4239
  const profile = await profiles.get({ id: profileId });
@@ -4535,6 +4580,7 @@ var LoginAttemptLimiter = class LoginAttemptLimiter {
4535
4580
  };
4536
4581
  return {
4537
4582
  allowed: true,
4583
+ budgetExpiresAt: Math.min(...reserved.map((key) => Date.parse(key.windowStartedAt) + this.budgetFor(key.scope).windowMs)),
4538
4584
  subjectKeyHash: subjectHash,
4539
4585
  sourceKeyHash: sourceHash,
4540
4586
  fail: async (metadata) => {
@@ -6132,6 +6178,6 @@ var PasswordCredentialService = class PasswordCredentialService {
6132
6178
  }
6133
6179
  };
6134
6180
  //#endregion
6135
- export { deriveOperationPermissionCollectionName as $, InvalidCredentialsError as A, Session as At, TenantPermissionOverrideCollection as B, DEFAULT_LOGIN_ATTEMPT_WINDOW_SECONDS as C, SessionCollection as Ct, DEFAULT_LOGIN_MAX_ATTEMPTS as D, normalizeUsername as Dt, DEFAULT_LOGIN_LOCKOUT_MAX_SECONDS as E, normalizeEmail as Et, OidcProvisioningError as F, __exportAll as Ft, TenantHierarchyError as G, TenantCollection as H, UserCollection as I, planTenantHierarchy as J, applyTenantHierarchyUpdates as K, USER_EMAIL_KEY_BACKFILL_NAME as L, LoginRateLimitError as M, Role as Mt, hashSecret as N, Permission as Nt, DEFAULT_SOURCE_LOCKOUT_AUDIT_SECONDS as O, DEFAULT_SESSION_TTL as Ot, verifySecretHash as P, Membership as Pt, PermissionCatalogService as Q, UserEmailKeyBackfillError as R, normalizeAncestorReadPolicy as S, UsersLoginAttempt as St, DEFAULT_LOGIN_LOCKOUT_FACTOR as T, isValidEmail as Tt, Tenant as U, TenantPermissionOverride as V, MAX_TENANT_HIERARCHY_DEPTH as W, DEFAULT_ROLE_PERMISSION_PATTERNS as X, recordTenantHierarchyChanges as Y, RolePermissionCollection 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, deriveOperationPermissionSlug 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, generateSessionId as jt, DurableLoginAuditSink as k, SESSION_DATA_KEYS 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, registerPermissionDefinitions as nt, PASSWORD_LOGIN_KIND as o, RoleCollection as ot, PasswordPolicyError as p, GroupRoleCollection as pt, assertTenantTableName 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, normalizeOperationPermissionAction as tt, PasswordCredentialError as u, MembershipOverrideCollection as ut, ANCESTOR_READ_ACTION as v, Group as vt, DEFAULT_LOGIN_LOCKOUT_BASE_SECONDS as w, User as wt, isAncestorReadableSlug as x, UsersLoginAttemptCollection as xt, DEFAULT_ANCESTOR_READ_MAX_DEPTH as y, UsersLoginAuditEventCollection as yt, backfillUserEmailKeys as z };
6181
+ export { PermissionCatalogService as $, InvalidCredentialsError as A, SESSION_DATA_KEYS as At, backfillUserEmailKeys as B, DEFAULT_LOGIN_ATTEMPT_WINDOW_SECONDS as C, UsersLoginAttempt as Ct, DEFAULT_LOGIN_MAX_ATTEMPTS as D, normalizeEmail as Dt, DEFAULT_LOGIN_LOCKOUT_MAX_SECONDS as E, isValidEmail as Et, OidcProvisioningError as F, Membership as Ft, MAX_TENANT_HIERARCHY_DEPTH as G, TenantPermissionOverride as H, UserCollection as I, __exportAll as It, assertTenantTableName as J, TenantHierarchyError as K, requireExistingOwnedPerson as L, LoginRateLimitError as M, generateSessionId as Mt, hashSecret as N, Role as Nt, DEFAULT_SOURCE_LOCKOUT_AUDIT_SECONDS as O, normalizeUsername as Ot, verifySecretHash as P, Permission as Pt, RolePermissionCollection as Q, USER_EMAIL_KEY_BACKFILL_NAME as R, normalizeAncestorReadPolicy as S, UsersLoginAttemptCollection as St, DEFAULT_LOGIN_LOCKOUT_FACTOR as T, User 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 _, GroupMember as _t, DEFAULT_PASSWORD_RECOVERY_MAX_AGE_SECONDS as a, withoutListBounds as at, getConfiguredAncestorReadPolicy as b, UsersLoginAuditEventCollection as bt, PASSWORD_PERMISSION_DEFINITIONS as c, PermissionCollection as ct, PasswordCredentialForbiddenError as d, MembershipOverrideCollection as dt, deriveOperationPermissionCollectionName as et, PasswordCredentialService as f, MembershipOverride as ft, SessionService as g, GroupMemberCollection as gt, outOfBandProofSessionData as h, GroupRole as ht, DEFAULT_PASSWORD_MIN_LENGTH as i, syncPermissionCatalog as it, LoginAttemptLimiter as j, Session as jt, DurableLoginAuditSink as k, DEFAULT_SESSION_TTL as kt, PASSWORD_RECOVERY_MAX_AGE_CEILING_SECONDS as l, UsersPasswordCredentialCollection as lt, ensurePasswordPermissionsRegistered as m, GroupRoleCollection as mt, DEFAULT_PASSWORD_MANAGE_PERMISSION as n, normalizeOperationPermissionAction as nt, PASSWORD_LOGIN_KIND as o, RolePermission as ot, PasswordPolicyError as p, MembershipCollection as pt, applyTenantHierarchyUpdates as q, DEFAULT_PASSWORD_MAX_LENGTH as r, registerPermissionDefinitions as rt, PASSWORD_MAX_LENGTH_CEILING as s, RoleCollection as st, DEFAULT_PASSWORD_DENYLIST as t, deriveOperationPermissionSlug as tt, PasswordCredentialError as u, UsersPasswordCredential as ut, ANCESTOR_READ_ACTION as v, GroupCollection as vt, DEFAULT_LOGIN_LOCKOUT_BASE_SECONDS as w, SessionCollection as wt, isAncestorReadableSlug as x, UsersLoginAuditEvent as xt, DEFAULT_ANCESTOR_READ_MAX_DEPTH as y, Group as yt, UserEmailKeyBackfillError as z };
6136
6182
 
6137
- //# sourceMappingURL=PasswordCredentialService-bedKxkaa.js.map
6183
+ //# sourceMappingURL=PasswordCredentialService-DHJNKEeJ.js.map