@happyvertical/smrt-users 0.57.21 → 0.57.23

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 (33) hide show
  1. package/AGENTS.md +101 -0
  2. package/README.md +53 -1
  3. package/dist/chunks/{PasswordCredentialService-DezdsV_v.js → PasswordCredentialService-DA2Y6H2X.js} +8 -2
  4. package/dist/chunks/PasswordCredentialService-DA2Y6H2X.js.map +1 -0
  5. package/dist/chunks/{TerminalAuthService-D7SIRyUk.js → TerminalAuthService-VRpBNnsC.js} +3 -3
  6. package/dist/chunks/TerminalAuthService-VRpBNnsC.js.map +1 -0
  7. package/dist/collections/MagicLinkTokenCollection.d.ts +2 -0
  8. package/dist/collections/MagicLinkTokenCollection.d.ts.map +1 -1
  9. package/dist/collections/UserCollection.d.ts +2 -0
  10. package/dist/collections/UserCollection.d.ts.map +1 -1
  11. package/dist/index.d.ts +2 -0
  12. package/dist/index.d.ts.map +1 -1
  13. package/dist/index.js +590 -64
  14. package/dist/index.js.map +1 -1
  15. package/dist/manifest.json +34 -1
  16. package/dist/member-register/service.d.ts +18 -2
  17. package/dist/member-register/service.d.ts.map +1 -1
  18. package/dist/operator.js +1 -1
  19. package/dist/services/LoginAttemptLimiter.d.ts +2 -0
  20. package/dist/services/LoginAttemptLimiter.d.ts.map +1 -1
  21. package/dist/services/MagicLinkService.d.ts +11 -1
  22. package/dist/services/MagicLinkService.d.ts.map +1 -1
  23. package/dist/services/MailboxAuthenticationService.d.ts +61 -0
  24. package/dist/services/MailboxAuthenticationService.d.ts.map +1 -0
  25. package/dist/services/TenantInvitationService.d.ts +120 -0
  26. package/dist/services/TenantInvitationService.d.ts.map +1 -0
  27. package/dist/services/index.d.ts +2 -0
  28. package/dist/services/index.d.ts.map +1 -1
  29. package/dist/smrt-knowledge.json +38 -5
  30. package/dist/sveltekit.js +2 -2
  31. package/package.json +10 -10
  32. package/dist/chunks/PasswordCredentialService-DezdsV_v.js.map +0 -1
  33. package/dist/chunks/TerminalAuthService-D7SIRyUk.js.map +0 -1
package/dist/index.js CHANGED
@@ -1,11 +1,11 @@
1
- import { $ as PermissionCatalogService, A as InvalidCredentialsError, At as Session, 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 withoutListBounds, G as MAX_TENANT_HIERARCHY_DEPTH, H as TenantPermissionOverride, I as OidcProvisioningError, J as assertTenantTableName, K as TenantHierarchyError, L as UserCollection, M as LoginRateLimitError, Mt as Role, Nt as Permission, O as DEFAULT_SOURCE_LOCKOUT_AUDIT_SECONDS, Ot as DEFAULT_SESSION_TTL, Pt as Membership, 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 syncPermissionCatalog, j as LoginAttemptLimiter, jt as generateSessionId, 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 registerPermissionDefinitions, 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-DezdsV_v.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-D7SIRyUk.js";
1
+ import { $ as PermissionCatalogService, A as InvalidCredentialsError, At as Session, 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 withoutListBounds, G as MAX_TENANT_HIERARCHY_DEPTH, H as TenantPermissionOverride, I as OidcProvisioningError, J as assertTenantTableName, K as TenantHierarchyError, L as UserCollection, M as LoginRateLimitError, Mt as Role, Nt as Permission, O as DEFAULT_SOURCE_LOCKOUT_AUDIT_SECONDS, Ot as DEFAULT_SESSION_TTL, Pt as Membership, 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 syncPermissionCatalog, j as LoginAttemptLimiter, jt as generateSessionId, 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 registerPermissionDefinitions, 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-DA2Y6H2X.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-VRpBNnsC.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-DFqeph0R.js";
4
- import { ObjectRegistry, SmrtCollection, SmrtObject, SmrtRecipe, bumpChangeFeed, crossPackageRef, ensureChangeFeedTable, field, findManifestEntryByQualifiedName, foreignKey, isEmbeddedDatabase, isUniqueViolationError, registerRetentionTask, smrt, unregisterRetentionTask, withEmbeddedWriteTransaction } from "@happyvertical/smrt-core";
4
+ import { ObjectRegistry, SmrtCollection, SmrtObject, SmrtRecipe, bumpChangeFeed, crossPackageRef, ensureChangeFeedTable, field, findManifestEntryByQualifiedName, foreignKey, isEmbeddedDatabase, isPostgresDatabase, isUniqueViolationError, registerRetentionTask, smrt, unregisterRetentionTask, withEmbeddedWriteTransaction } from "@happyvertical/smrt-core";
5
5
  import { TenantScoped, getTenantId, tenantId, withSystemContext, withTenant, withTenantGlobalRead } from "@happyvertical/smrt-tenancy";
6
- import { PROFILE_EMAIL_KEY_BACKFILL_NAME, Person, ProfileCollection, ProfileTypeCollection, normalizeIdentityEmail } from "@happyvertical/smrt-profiles";
6
+ import { CanonicalPersonProfileError, PROFILE_EMAIL_KEY_BACKFILL_NAME, Person, ProfileCollection, ProfileTypeCollection, normalizeIdentityEmail } from "@happyvertical/smrt-profiles";
7
7
  import { createHash, randomUUID } from "node:crypto";
8
- import { setTimeout } from "node:timers/promises";
8
+ import { setTimeout as setTimeout$1 } from "node:timers/promises";
9
9
  import { createLogger } from "@happyvertical/logger";
10
10
  import { BackfillTracker } from "@happyvertical/smrt-core/migrations";
11
11
  import { getDatabase } from "@happyvertical/sql";
@@ -353,6 +353,22 @@ var MemberRegisterError = class extends Error {
353
353
  }
354
354
  code;
355
355
  };
356
+ function normalizeEligibilityPolicy(policy) {
357
+ if (!policy || typeof policy !== "object" || [
358
+ policy.memberClassKeys,
359
+ policy.statuses,
360
+ policy.requireAuthoritativeKinds
361
+ ].some((values) => values !== void 0 && !Array.isArray(values))) throw new MemberRegisterError("MEMBER_REGISTER_INVALID", "Eligibility policy values must be arrays.");
362
+ const memberClassKeys = policy.memberClassKeys === void 0 ? null : [...policy.memberClassKeys];
363
+ const statuses = [...policy.statuses ?? ["active"]];
364
+ const requiredAuthoritativeKinds = [...policy.requireAuthoritativeKinds ?? []];
365
+ if (memberClassKeys?.some((key) => typeof key !== "string" || !key.trim()) || statuses.some((status) => !MEMBER_STATUSES.includes(status)) || requiredAuthoritativeKinds.some((kind) => !REFERENCE_KINDS.includes(kind))) throw new MemberRegisterError("MEMBER_REGISTER_INVALID", "Unknown or malformed eligibility policy.");
366
+ return {
367
+ ...memberClassKeys === null ? {} : { memberClassKeys },
368
+ statuses,
369
+ requireAuthoritativeKinds: requiredAuthoritativeKinds
370
+ };
371
+ }
356
372
  var MemberRegisterService = class MemberRegisterService {
357
373
  constructor(db, actor, transactionBound) {
358
374
  this.db = db;
@@ -364,9 +380,14 @@ var MemberRegisterService = class MemberRegisterService {
364
380
  actor;
365
381
  transactionBound;
366
382
  static transactionToken = /* @__PURE__ */ Symbol("member-register-transaction");
367
- transaction(operation) {
383
+ /** Atomically accept a host command and its evidence on the same executor.
384
+ * The callback service and executor must not escape the callback.
385
+ */
386
+ withTransaction(operation) {
387
+ if (this.transactionBound === MemberRegisterService.transactionToken) return this.scope(() => operation(this, this.db));
368
388
  if (!this.db.transaction) throw new MemberRegisterError("MEMBER_REGISTER_INVALID", "Member register writes require transaction support.");
369
- return this.db.transaction((db) => operation(new MemberRegisterService(db, this.actor, MemberRegisterService.transactionToken)));
389
+ const transaction = this.db.transaction.bind(this.db);
390
+ return this.scope(() => transaction((db) => operation(new MemberRegisterService(db, this.actor, MemberRegisterService.transactionToken), db)));
370
391
  }
371
392
  scope(run) {
372
393
  const active = getTenantId();
@@ -397,7 +418,7 @@ var MemberRegisterService = class MemberRegisterService {
397
418
  }
398
419
  async enroll(input) {
399
420
  if (this.transactionBound !== MemberRegisterService.transactionToken) {
400
- const member = await this.transaction((service) => service.enroll(input));
421
+ const member = await this.withTransaction((service) => service.enroll(input));
401
422
  return this.scope(() => this.member(member.id));
402
423
  }
403
424
  return this.scope(async () => {
@@ -441,7 +462,7 @@ var MemberRegisterService = class MemberRegisterService {
441
462
  }
442
463
  async setStatus(memberId, input) {
443
464
  if (this.transactionBound !== MemberRegisterService.transactionToken) {
444
- const member = await this.transaction((service) => service.setStatus(memberId, input));
465
+ const member = await this.withTransaction((service) => service.setStatus(memberId, input));
445
466
  return this.scope(() => this.member(member.id));
446
467
  }
447
468
  return this.scope(async () => {
@@ -531,63 +552,105 @@ var MemberRegisterService = class MemberRegisterService {
531
552
  });
532
553
  });
533
554
  }
555
+ /** Read one member without snapshots, register enumeration or a transaction. */
556
+ async eligibilityFor(identity, recordDate, policy = {}) {
557
+ return this.scope(async () => {
558
+ const capturedPolicy = normalizeEligibilityPolicy(policy);
559
+ if (!identity || identity.memberId !== void 0 === (identity.userId !== void 0)) throw new MemberRegisterError("MEMBER_REGISTER_INVALID", "Supply exactly one memberId or userId.");
560
+ const members = await LegalMemberCollection.create({ db: this.db });
561
+ let member;
562
+ if (identity.memberId !== void 0) member = await this.member(identity.memberId);
563
+ else {
564
+ const matches = await members.list({
565
+ where: {
566
+ tenantId: this.actor.tenantId,
567
+ userId: text(identity.userId, "userId")
568
+ },
569
+ limit: 2
570
+ });
571
+ if (matches.length !== 1) throw new MemberRegisterError("MEMBER_REGISTER_NOT_FOUND", "Member identity not uniquely found in this tenant.");
572
+ member = matches[0];
573
+ }
574
+ return this.evaluateMember(member, recordDate, capturedPolicy);
575
+ });
576
+ }
577
+ /** Explicit immutable evidence write; call inside withTransaction for accepted commands. */
578
+ async captureEligibility(identity, recordDate, policy = {}) {
579
+ return this.withTransaction(async (service) => {
580
+ const row = await service.eligibilityFor(identity, recordDate, policy);
581
+ const snapshots = await MemberEligibilitySnapshotCollection.create({ db: service.db });
582
+ return service.scope(() => snapshots.create({
583
+ tenantId: service.actor.tenantId,
584
+ memberId: row.memberId,
585
+ recordDate: row.recordDate,
586
+ eligible: row.eligible,
587
+ reason: row.reason,
588
+ evidence: row.evidence
589
+ }));
590
+ });
591
+ }
592
+ async evaluateMember(member, recordDate, policy) {
593
+ const on = date(recordDate, "recordDate");
594
+ const memberClassKeys = policy.memberClassKeys ?? null;
595
+ const statuses = policy.statuses ?? ["active"];
596
+ const requiredAuthoritativeKinds = policy.requireAuthoritativeKinds ?? [];
597
+ const classes = await MemberClassCollection.create({ db: this.db });
598
+ const histories = await LegalMemberStatusHistoryCollection.create({ db: this.db });
599
+ const refs = await LegalMemberReferenceCollection.create({ db: this.db });
600
+ const klass = await classes.get({
601
+ id: member.memberClassId,
602
+ tenantId: this.actor.tenantId
603
+ });
604
+ const status = (await histories.list({ where: {
605
+ tenantId: this.actor.tenantId,
606
+ memberId: member.id
607
+ } })).filter((entry) => entry.effectiveOn <= on).sort(compareHistory).at(-1)?.status;
608
+ const allRefs = await refs.list({ where: {
609
+ tenantId: this.actor.tenantId,
610
+ memberId: member.id
611
+ } });
612
+ const revoked = new Set(allRefs.filter((reference) => reference.revokesId && reference.effectiveFrom <= on).map((reference) => reference.revokesId));
613
+ const memberRefs = allRefs.filter((reference) => !reference.revokesId && !revoked.has(reference.id) && reference.effectiveFrom <= on && (reference.effectiveTo === null || reference.effectiveTo >= on));
614
+ const missing = requiredAuthoritativeKinds.filter((kind) => !memberRefs.some((reference) => reference.kind === kind && reference.authoritative));
615
+ const classOK = memberClassKeys === null || !!klass && memberClassKeys.includes(klass.key);
616
+ const statusOK = !!status && statuses.includes(status);
617
+ const eligible = member.joinedOn <= on && classOK && statusOK && missing.length === 0;
618
+ const reason = missing.length ? `authoritative evidence unavailable: ${missing.join(", ")}` : !classOK ? "member class excluded by policy" : !statusOK ? `status ${status ?? "unrecorded"} excluded by policy` : member.joinedOn > on ? "joined after record date" : "eligible";
619
+ const evidence = {
620
+ status,
621
+ memberClassKeys,
622
+ statuses,
623
+ requiredAuthoritativeKinds,
624
+ missingAuthoritativeKinds: missing,
625
+ referenceCount: memberRefs.length
626
+ };
627
+ return {
628
+ memberId: member.id,
629
+ displayName: member.displayName,
630
+ memberClassKey: klass?.key ?? "",
631
+ recordDate: on,
632
+ eligible,
633
+ reason,
634
+ evidence
635
+ };
636
+ }
534
637
  async asOf(recordDate, policy = {}) {
535
- if (this.transactionBound !== MemberRegisterService.transactionToken) return this.transaction((service) => service.asOf(recordDate, policy));
638
+ if (this.transactionBound !== MemberRegisterService.transactionToken) return this.withTransaction((service) => service.asOf(recordDate, policy));
536
639
  return this.scope(async () => {
537
640
  const on = date(recordDate, "recordDate");
538
- const memberClassKeys = policy.memberClassKeys === void 0 ? null : [...policy.memberClassKeys];
539
- const statuses = [...policy.statuses ?? ["active"]];
540
- const requiredAuthoritativeKinds = [...policy.requireAuthoritativeKinds ?? []];
641
+ const capturedPolicy = normalizeEligibilityPolicy(policy);
541
642
  const members = await LegalMemberCollection.create({ db: this.db });
542
- const classes = await MemberClassCollection.create({ db: this.db });
543
- const histories = await LegalMemberStatusHistoryCollection.create({ db: this.db });
544
- const refs = await LegalMemberReferenceCollection.create({ db: this.db });
545
643
  const snapshots = await MemberEligibilitySnapshotCollection.create({ db: this.db });
546
644
  const rows = [];
547
645
  for (const member of await members.list({ where: { tenantId: this.actor.tenantId } })) {
548
- const klass = await classes.get({
549
- id: member.memberClassId,
550
- tenantId: this.actor.tenantId
551
- });
552
- const status = (await histories.list({ where: {
553
- tenantId: this.actor.tenantId,
554
- memberId: member.id
555
- } })).filter((entry) => entry.effectiveOn <= on).sort(compareHistory).at(-1)?.status;
556
- const allRefs = await refs.list({ where: {
557
- tenantId: this.actor.tenantId,
558
- memberId: member.id
559
- } });
560
- const revoked = new Set(allRefs.filter((reference) => reference.revokesId && reference.effectiveFrom <= on).map((reference) => reference.revokesId));
561
- const memberRefs = allRefs.filter((reference) => !reference.revokesId && !revoked.has(reference.id) && reference.effectiveFrom <= on && (reference.effectiveTo === null || reference.effectiveTo >= on));
562
- const missing = requiredAuthoritativeKinds.filter((kind) => !memberRefs.some((reference) => reference.kind === kind && reference.authoritative));
563
- const classOK = memberClassKeys === null || !!klass && memberClassKeys.includes(klass.key);
564
- const statusOK = !!status && statuses.includes(status);
565
- const eligible = member.joinedOn <= on && classOK && statusOK && missing.length === 0;
566
- const reason = missing.length ? `authoritative evidence unavailable: ${missing.join(", ")}` : !classOK ? "member class excluded by policy" : !statusOK ? `status ${status ?? "unrecorded"} excluded by policy` : member.joinedOn > on ? "joined after record date" : "eligible";
567
- const evidence = {
568
- status,
569
- memberClassKeys,
570
- statuses,
571
- requiredAuthoritativeKinds,
572
- missingAuthoritativeKinds: missing,
573
- referenceCount: memberRefs.length
574
- };
575
- const row = {
576
- memberId: member.id,
577
- displayName: member.displayName,
578
- memberClassKey: klass?.key ?? "",
579
- recordDate: on,
580
- eligible,
581
- reason,
582
- evidence
583
- };
646
+ const row = await this.evaluateMember(member, on, capturedPolicy);
584
647
  await snapshots.create({
585
648
  tenantId: this.actor.tenantId,
586
649
  memberId: row.memberId,
587
650
  recordDate: on,
588
- eligible,
589
- reason,
590
- evidence
651
+ eligible: row.eligible,
652
+ reason: row.reason,
653
+ evidence: row.evidence
591
654
  });
592
655
  rows.push(row);
593
656
  }
@@ -852,6 +915,11 @@ var UsersMagicLinkTokenCollection = class extends SmrtCollection {
852
915
  async findByNonce(nonce) {
853
916
  return this.findOne({ where: { nonce } });
854
917
  }
918
+ /** Check a signed token's live nonce without claiming it; never authorizes login. */
919
+ async isAvailable(nonce, email) {
920
+ const { rows } = await this.db.query(`SELECT nonce FROM ${this.tableName} WHERE nonce = ? AND email = ? AND used = ? AND expires_at > ? LIMIT 1`, nonce, email, false, (/* @__PURE__ */ new Date()).toISOString());
921
+ return rows.length === 1;
922
+ }
855
923
  /**
856
924
  * Atomically mark a token as used (single-use enforcement).
857
925
  *
@@ -1233,7 +1301,7 @@ async function withOAuthTransaction(db, action) {
1233
1301
  current = failure.cause;
1234
1302
  }
1235
1303
  if (attempt >= 6 || !retryable || invalidated) throw error;
1236
- await setTimeout(5 * 2 ** attempt);
1304
+ await setTimeout$1(5 * 2 ** attempt);
1237
1305
  }
1238
1306
  }
1239
1307
  //#endregion
@@ -2635,8 +2703,8 @@ var MagicLinkService = class MagicLinkService {
2635
2703
  * Stores a nonce in the database for replay protection.
2636
2704
  * The caller is responsible for emailing the token to the user.
2637
2705
  */
2638
- async generate(email) {
2639
- const { SignJWT } = await import("./chunks/TerminalAuthService-D7SIRyUk.js").then((n) => n.G);
2706
+ async generate(email, options = {}) {
2707
+ const { SignJWT } = await import("./chunks/TerminalAuthService-VRpBNnsC.js").then((n) => n.G);
2640
2708
  const key = await this.getSigningKey();
2641
2709
  const nonce = crypto.randomUUID();
2642
2710
  const normalizedEmail = normalizeEmail(email);
@@ -2651,7 +2719,8 @@ var MagicLinkService = class MagicLinkService {
2651
2719
  return {
2652
2720
  token: await new SignJWT({
2653
2721
  email: normalizedEmail,
2654
- nonce
2722
+ nonce,
2723
+ ...options.subject !== void 0 ? { sub: options.subject } : {}
2655
2724
  }).setProtectedHeader({ alg: "HS256" }).setIssuedAt().setExpirationTime(`${this.tokenExpiry}s`).setIssuer(this.issuer).sign(key),
2656
2725
  expiresAt
2657
2726
  };
@@ -2665,7 +2734,21 @@ var MagicLinkService = class MagicLinkService {
2665
2734
  * @throws {MagicLinkError} If the token is invalid, expired, or already used
2666
2735
  */
2667
2736
  async verify(token) {
2668
- const { jwtVerify, errors } = await import("./chunks/TerminalAuthService-D7SIRyUk.js").then((n) => n.G);
2737
+ const proof = await this.verifySignature(token);
2738
+ if (!await this.tokenCollection.markUsed(proof.nonce)) throw new MagicLinkError("Token has already been used or has expired");
2739
+ return proof;
2740
+ }
2741
+ /**
2742
+ * Validate a signed live nonce without consuming it. This is preparation only,
2743
+ * never authentication: a final verify() must atomically claim the token.
2744
+ */
2745
+ async inspect(token) {
2746
+ const proof = await this.verifySignature(token);
2747
+ if (!await this.tokenCollection.isAvailable(proof.nonce, proof.email)) throw new MagicLinkError("Token has already been used or has expired");
2748
+ return proof;
2749
+ }
2750
+ async verifySignature(token) {
2751
+ const { jwtVerify, errors } = await import("./chunks/TerminalAuthService-VRpBNnsC.js").then((n) => n.G);
2669
2752
  const key = await this.getSigningKey();
2670
2753
  let payload;
2671
2754
  try {
@@ -2677,10 +2760,10 @@ var MagicLinkService = class MagicLinkService {
2677
2760
  const email = payload.email;
2678
2761
  const nonce = payload.nonce;
2679
2762
  if (typeof email !== "string" || typeof nonce !== "string") throw new MagicLinkError("Invalid token payload");
2680
- if (!await this.tokenCollection.markUsed(nonce)) throw new MagicLinkError("Token has already been used or has expired");
2681
2763
  return {
2682
2764
  email: normalizeEmail(email),
2683
- nonce
2765
+ nonce,
2766
+ ...typeof payload.sub === "string" ? { subject: payload.sub } : {}
2684
2767
  };
2685
2768
  }
2686
2769
  /**
@@ -2699,6 +2782,154 @@ var MagicLinkService = class MagicLinkService {
2699
2782
  }
2700
2783
  };
2701
2784
  //#endregion
2785
+ //#region src/services/MailboxAuthenticationService.ts
2786
+ async function reserveMailboxRequest(input) {
2787
+ if (!input.limiter) throw new Error("Mailbox authentication requests require an independently supplied root-executor login limiter");
2788
+ if (!input.sourceKey?.trim()) throw new Error("Mailbox authentication source key is required");
2789
+ const lease = await input.limiter.reserve({
2790
+ kind: "mailbox-request",
2791
+ subject: `mailbox:${input.subject}`,
2792
+ source: `mailbox:${input.sourceKey}`,
2793
+ retainOnSuccess: true
2794
+ });
2795
+ if (!lease.allowed) throw new LoginRateLimitError(lease);
2796
+ await lease.succeed();
2797
+ }
2798
+ async function assertMailboxSessionCompatibility(options, input) {
2799
+ if (input.expectedUserId !== void 0 && input.expectedUserId !== input.userId) throw new MagicLinkError("Sign-in identity does not match");
2800
+ if (input.sessionId !== void 0) {
2801
+ const session = await (await SessionCollection.create(options)).findValidSession(input.sessionId);
2802
+ const context = session ? await (await SessionService.create(options)).loadSessionContext(input.sessionId) : null;
2803
+ if (!session || !context || session.userId !== input.userId || context.user.id !== input.userId || session.parentSessionId || session.getPermissionCeiling() !== null || ![
2804
+ "oidc",
2805
+ "magic-link",
2806
+ "password",
2807
+ "passkey"
2808
+ ].includes(session.authMethod ?? "")) throw new MagicLinkError("Independent first-class sign-in is required");
2809
+ }
2810
+ }
2811
+ var MailboxAuthenticationService = class MailboxAuthenticationService {
2812
+ constructor(options, auth) {
2813
+ this.options = options;
2814
+ this.auth = auth;
2815
+ }
2816
+ options;
2817
+ auth;
2818
+ static async create(options) {
2819
+ if (!options.db || options.transaction !== "caller" || !options.secret) throw new Error("Mailbox authentication requires a signing secret and caller-owned transaction");
2820
+ return new MailboxAuthenticationService({
2821
+ db: options.db,
2822
+ _reuseInitializedDb: true,
2823
+ _deferRuntimeInitialization: true
2824
+ }, {
2825
+ secret: options.secret,
2826
+ loginLimiter: options.loginLimiter
2827
+ });
2828
+ }
2829
+ async request(input) {
2830
+ if (typeof input.deliver !== "function") throw new Error("Mailbox authentication delivery is required");
2831
+ const started = performance.now();
2832
+ try {
2833
+ await reserveMailboxRequest({
2834
+ subject: normalizeEmail(input.email),
2835
+ sourceKey: input.sourceKey,
2836
+ limiter: this.auth.loginLimiter
2837
+ });
2838
+ return await withSystemContext(async () => {
2839
+ const identity = isValidEmail(input.email) ? await this.eligible(input.email) : null;
2840
+ if (identity) {
2841
+ const proof = await (await this.links()).generate(identity.user.email, { subject: identity.binding });
2842
+ await input.deliver({
2843
+ email: normalizeIdentityEmail(identity.user.email),
2844
+ ...proof
2845
+ });
2846
+ }
2847
+ return { requested: true };
2848
+ });
2849
+ } finally {
2850
+ await new Promise((resolve) => setTimeout(resolve, Math.max(0, 250 - (performance.now() - started))));
2851
+ }
2852
+ }
2853
+ async authenticate(input) {
2854
+ return await withSystemContext(async () => {
2855
+ const proof = await (await this.links()).inspect(input.token);
2856
+ const identity = await this.eligible(proof.email, true);
2857
+ if (!identity || proof.subject !== identity.binding || input.expectedUserId !== void 0 && input.expectedUserId !== identity.user.id) throw new MagicLinkError("Sign-in link is unavailable");
2858
+ await assertMailboxSessionCompatibility(this.options, {
2859
+ userId: identity.user.id,
2860
+ expectedUserId: input.expectedUserId,
2861
+ sessionId: input.sessionId
2862
+ });
2863
+ await (await this.links()).verify(input.token);
2864
+ identity.user.recordLogin();
2865
+ await identity.user.save();
2866
+ return {
2867
+ userId: identity.user.id,
2868
+ profileId: identity.user.profileId,
2869
+ tenantId: identity.tenantId
2870
+ };
2871
+ });
2872
+ }
2873
+ async links() {
2874
+ return await MagicLinkService.create({
2875
+ ...this.options,
2876
+ secret: this.auth.secret,
2877
+ tokenExpiry: 600,
2878
+ issuer: "smrt:mailbox-auth:v1"
2879
+ });
2880
+ }
2881
+ async eligible(email, lock = false) {
2882
+ const users = await UserCollection.create(this.options);
2883
+ let user = await users.findCanonicalByEmail(normalizeIdentityEmail(email));
2884
+ if (!user?.id || user.status !== UserStatus.ACTIVE) return null;
2885
+ const db = this.options.db;
2886
+ if (lock && isPostgresDatabase(db)) {
2887
+ await db.query("SELECT id FROM users WHERE id = ? FOR UPDATE", user.id);
2888
+ user = await users.get({ id: user.id }, { cache: false });
2889
+ if (!user?.id || user.status !== UserStatus.ACTIVE || normalizeIdentityEmail(user.email) !== normalizeIdentityEmail(email)) return null;
2890
+ }
2891
+ const profiles = await ProfileCollection.create(this.options);
2892
+ try {
2893
+ await profiles.requireCanonicalGlobalPerson(user.profileId, user.email);
2894
+ } catch (error) {
2895
+ if (error instanceof CanonicalPersonProfileError) return null;
2896
+ throw error;
2897
+ }
2898
+ const memberships = await MembershipCollection.create(this.options);
2899
+ const tenants = await TenantCollection.create(this.options);
2900
+ const pageSize = 100;
2901
+ let afterId;
2902
+ for (;;) {
2903
+ const active = await memberships.list({
2904
+ where: {
2905
+ userId: user.id,
2906
+ status: MembershipStatus.ACTIVE,
2907
+ ...afterId ? { "id >": afterId } : {}
2908
+ },
2909
+ orderBy: "id ASC",
2910
+ limit: pageSize
2911
+ });
2912
+ for (let membership of active) {
2913
+ if (lock && isPostgresDatabase(db)) {
2914
+ await db.query("SELECT id FROM memberships WHERE id = ? FOR UPDATE", membership.id);
2915
+ const current = await memberships.get({ id: membership.id }, { cache: false });
2916
+ if (!current || current.userId !== user.id || current.status !== MembershipStatus.ACTIVE) continue;
2917
+ membership = current;
2918
+ }
2919
+ if (!membership.tenantId) continue;
2920
+ if ((await tenants.get({ id: membership.tenantId }, { cache: false }))?.status === TenantStatus.ACTIVE) return {
2921
+ user,
2922
+ tenantId: membership.tenantId,
2923
+ binding: JSON.stringify([user.id, user.profileId])
2924
+ };
2925
+ }
2926
+ const lastId = active.at(-1)?.id;
2927
+ if (active.length < pageSize || !lastId) return null;
2928
+ afterId = lastId;
2929
+ }
2930
+ }
2931
+ };
2932
+ //#endregion
2702
2933
  //#region src/services/OAuthAuthorizationStorage.ts
2703
2934
  var SMRT_OAUTH_GRANT_CLAIM = "smrt_grant_id";
2704
2935
  function authorizationId(grant) {
@@ -2767,7 +2998,7 @@ var SmrtOAuthAuthorizationStorage = class SmrtOAuthAuthorizationStorage {
2767
2998
  });
2768
2999
  await this.recovering;
2769
3000
  }
2770
- await setTimeout(5 * 2 ** attempt);
3001
+ await setTimeout$1(5 * 2 ** attempt);
2771
3002
  }
2772
3003
  }
2773
3004
  }
@@ -3497,6 +3728,301 @@ async function hasActiveAncestors(collection, grant) {
3497
3728
  return true;
3498
3729
  }
3499
3730
  //#endregion
3731
+ //#region src/services/TenantInvitationService.ts
3732
+ var TenantInvitationError = class extends Error {
3733
+ status;
3734
+ constructor(message, status = 400) {
3735
+ super(message);
3736
+ this.name = "TenantInvitationError";
3737
+ this.status = status;
3738
+ }
3739
+ };
3740
+ var TenantInvitationService = class TenantInvitationService {
3741
+ constructor(options, signing) {
3742
+ this.options = options;
3743
+ this.signing = signing;
3744
+ }
3745
+ options;
3746
+ signing;
3747
+ /** Bind an already-initialized transaction executor; never nest transactions. */
3748
+ static async create(options) {
3749
+ if (!options.db || options.transaction !== "caller") throw new Error("Tenant invitation requires a caller-owned transaction");
3750
+ return new TenantInvitationService({
3751
+ db: options.db,
3752
+ _reuseInitializedDb: true,
3753
+ _deferRuntimeInitialization: true
3754
+ }, {
3755
+ secret: options.secret,
3756
+ tokenExpiry: options.tokenExpiry,
3757
+ loginLimiter: options.loginLimiter
3758
+ });
3759
+ }
3760
+ /** Host-authorized issue/reissue; never sends or logs the bearer token. */
3761
+ async issue(input) {
3762
+ return await withSystemContext(async () => {
3763
+ const records = await this.invitationRecords(input.membershipId);
3764
+ const result = await (await this.magicLinks(records.binding)).generate(records.user.email);
3765
+ return {
3766
+ membershipId: input.membershipId,
3767
+ ...result
3768
+ };
3769
+ });
3770
+ }
3771
+ /**
3772
+ * Request independent mailbox authentication, delivering only to the canonical
3773
+ * invitee. The trusted server callback must send auth mail, never expose the
3774
+ * proof to a requester/operator, and reject on transport failure. No grant is
3775
+ * consumed here, so failed delivery/retries do not burn invitation access.
3776
+ * Delivery precedes caller commit: a rolled-back challenge cannot authenticate.
3777
+ */
3778
+ async requestMailboxAuthentication(input) {
3779
+ if (typeof input.deliver !== "function") throw new TenantInvitationError("Mailbox authentication delivery is required");
3780
+ await reserveMailboxRequest({
3781
+ subject: `invitation:${input.membershipId}`,
3782
+ sourceKey: input.sourceKey,
3783
+ limiter: this.signing.loginLimiter
3784
+ });
3785
+ return await withSystemContext(async () => {
3786
+ const records = await this.invitationRecords(input.membershipId);
3787
+ if ((await (await this.magicLinks(records.binding)).inspect(input.token)).email !== normalizeIdentityEmail(records.user.email)) throw new TenantInvitationError("Invitation identity does not match", 403);
3788
+ const proof = await (await this.mailboxLinks(records.binding, input.token)).generate(records.user.email);
3789
+ await input.deliver({
3790
+ email: normalizeIdentityEmail(records.user.email),
3791
+ ...proof
3792
+ });
3793
+ return { expiresAt: proof.expiresAt };
3794
+ });
3795
+ }
3796
+ /**
3797
+ * Authenticate ONLY independent proof delivered to the canonical mailbox plus
3798
+ * the exact project grant. Claim both nonces and activate atomically in the
3799
+ * caller transaction. The host may then establish a magic-link session from
3800
+ * committed returned IDs; a copied project grant alone never proves identity.
3801
+ */
3802
+ async authenticateMailbox(input) {
3803
+ return await withSystemContext(async () => {
3804
+ const records = await this.invitationRecords(input.membershipId);
3805
+ if (input.expectedUserId !== void 0 && input.expectedUserId !== records.user.id) throw new TenantInvitationError("Invitation does not belong to the signed-in user", 403);
3806
+ await assertMailboxSessionCompatibility(this.options, {
3807
+ userId: requiredId(records.user.id),
3808
+ expectedUserId: input.expectedUserId,
3809
+ sessionId: input.sessionId
3810
+ });
3811
+ if ((await (await this.mailboxLinks(records.binding, input.invitationToken)).verify(input.token)).email !== normalizeIdentityEmail(records.user.email)) throw new TenantInvitationError("Mailbox authentication identity does not match", 403);
3812
+ await this.verifyProof(records.binding, records.user.email, input.invitationToken);
3813
+ if (records.user.status === UserStatus.PENDING) records.user.status = UserStatus.ACTIVE;
3814
+ records.user.recordLogin();
3815
+ await records.user.save();
3816
+ await this.activateMembership(records.membership);
3817
+ return {
3818
+ userId: requiredId(records.user.id),
3819
+ profileId: records.profileId,
3820
+ membershipId: requiredId(records.membership.id),
3821
+ tenantId: requiredId(records.membership.tenantId),
3822
+ status: "active"
3823
+ };
3824
+ });
3825
+ }
3826
+ async mailboxLinks(binding, grant) {
3827
+ if (!this.signing.secret) throw new Error("Invitation signing secret is required");
3828
+ return await MagicLinkService.create({
3829
+ ...this.options,
3830
+ secret: this.signing.secret,
3831
+ tokenExpiry: 600,
3832
+ issuer: `smrt:tenant-mailbox:v1:${binding}:${createHash("sha256").update(grant).digest("hex")}`
3833
+ });
3834
+ }
3835
+ /** Accept a tenant grant using an independently authenticated first-class session. */
3836
+ async accept(input) {
3837
+ return await withSystemContext(async () => {
3838
+ const records = await this.invitationRecords(input.membershipId);
3839
+ const sessions = await SessionCollection.create(this.options);
3840
+ const session = input.sessionId ? await sessions.findValidSession(input.sessionId) : null;
3841
+ const context = session ? await (await SessionService.create(this.options)).loadSessionContext(input.sessionId) : null;
3842
+ if (!session || !context || records.user.status !== UserStatus.ACTIVE || context.user.id !== records.user.id || session.userId !== records.user.id || session.parentSessionId || session.getPermissionCeiling() !== null || ![
3843
+ "oidc",
3844
+ "magic-link",
3845
+ "password",
3846
+ "passkey"
3847
+ ].includes(session.authMethod ?? "") || input.expectedUserId !== void 0 && input.expectedUserId !== records.user.id) throw new TenantInvitationError("Independent invitation identity authentication is required", 403);
3848
+ await this.verifyProof(records.binding, records.user.email, input.token);
3849
+ await this.activateMembership(records.membership);
3850
+ return {
3851
+ userId: requiredId(records.user.id),
3852
+ profileId: records.profileId,
3853
+ membershipId: requiredId(records.membership.id),
3854
+ tenantId: requiredId(records.membership.tenantId),
3855
+ status: "active"
3856
+ };
3857
+ });
3858
+ }
3859
+ /**
3860
+ * Authorize a pre-provisioned owner ONLY inside the canonical protocol-verified
3861
+ * OIDC callback. A tenant grant alone never proves global identity. The host
3862
+ * must not expose this trusted callback seam to arbitrary claims.
3863
+ */
3864
+ async authorizeOidcOwner(context, input) {
3865
+ if (context.db !== this.options.db || context.claims.email_verified !== true) throw new TenantInvitationError("Verified OIDC invitation identity is required", 403);
3866
+ return await withSystemContext(async () => {
3867
+ const records = await this.invitationRecords(input.membershipId);
3868
+ if (!context.claims.email || normalizeIdentityEmail(context.claims.email) !== normalizeIdentityEmail(records.user.email)) throw new TenantInvitationError("Verified OIDC invitation identity does not match", 403);
3869
+ await this.verifyProof(records.binding, records.user.email, input.token);
3870
+ if (records.user.status === UserStatus.PENDING) {
3871
+ records.user.status = UserStatus.ACTIVE;
3872
+ await records.user.save();
3873
+ }
3874
+ await this.activateMembership(records.membership);
3875
+ return {
3876
+ profile: records.profile,
3877
+ user: records.user,
3878
+ tenantId: requiredId(records.membership.tenantId),
3879
+ membershipId: requiredId(records.membership.id)
3880
+ };
3881
+ });
3882
+ }
3883
+ async activateMembership(membership) {
3884
+ if (membership.status === MembershipStatus.PENDING) {
3885
+ membership.status = MembershipStatus.ACTIVE;
3886
+ await membership.save();
3887
+ }
3888
+ }
3889
+ async verifyProof(binding, email, token) {
3890
+ if ((await (await this.magicLinks(binding)).verify(token)).email !== normalizeIdentityEmail(email)) throw new TenantInvitationError("Invitation identity does not match", 403);
3891
+ }
3892
+ async magicLinks(binding) {
3893
+ if (!this.signing.secret) throw new Error("Invitation signing secret is required");
3894
+ const tokenExpiry = this.signing.tokenExpiry ?? 86400;
3895
+ if (!Number.isSafeInteger(tokenExpiry) || tokenExpiry < 1 || tokenExpiry > 604800) throw new Error("Invitation token expiry must be 1–604800 seconds");
3896
+ return await MagicLinkService.create({
3897
+ ...this.options,
3898
+ secret: this.signing.secret,
3899
+ tokenExpiry,
3900
+ issuer: `smrt:tenant-invitation:v1:${binding}`
3901
+ });
3902
+ }
3903
+ /** Lock existing authority before verifying it; never authorize by email match. */
3904
+ async invitationRecords(membershipId) {
3905
+ if (typeof membershipId !== "string" || !/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu.test(membershipId)) throw new TenantInvitationError("Invitation is unavailable", 403);
3906
+ const memberships = await MembershipCollection.create(this.options);
3907
+ let membership = await memberships.get({ id: membershipId }, { cache: false });
3908
+ if (!membership?.userId || !membership.tenantId || !membership.roleId) throw new TenantInvitationError("Invitation is unavailable");
3909
+ const userId = membership.userId;
3910
+ const db = this.options.db;
3911
+ if (isPostgresDatabase(db)) {
3912
+ await db.query("SELECT id FROM users WHERE id = ? FOR UPDATE", userId);
3913
+ await db.query("SELECT id FROM memberships WHERE id = ? FOR UPDATE", membershipId);
3914
+ }
3915
+ membership = await memberships.get({ id: membershipId }, { cache: false });
3916
+ if (!membership || membership.userId !== userId || !membership.tenantId || !membership.roleId || membership.status !== MembershipStatus.PENDING && membership.status !== MembershipStatus.ACTIVE) throw new TenantInvitationError("Invitation is unavailable");
3917
+ const users = await UserCollection.create(this.options);
3918
+ const user = await users.get({ id: userId }, { cache: false });
3919
+ if (!user || user.status !== UserStatus.PENDING && user.status !== UserStatus.ACTIVE) throw new TenantInvitationError("Invitation is unavailable");
3920
+ const tenant = await (await TenantCollection.create(this.options)).get({ id: membership.tenantId }, { cache: false });
3921
+ if (!tenant || tenant.status !== TenantStatus.ACTIVE) throw new TenantInvitationError("Invitation is unavailable");
3922
+ const profiles = await ProfileCollection.create(this.options);
3923
+ let profile;
3924
+ try {
3925
+ profile = await profiles.requireCanonicalGlobalPerson(user.profileId, user.email);
3926
+ } catch (error) {
3927
+ if (error instanceof CanonicalPersonProfileError) throw new TenantInvitationError("Invitation identity is unavailable", 403);
3928
+ throw error;
3929
+ }
3930
+ if ((await users.findCanonicalByEmail(user.email))?.id !== user.id) throw new TenantInvitationError("Invitation identity ownership is inconsistent");
3931
+ const profileId = requiredId(profile.id);
3932
+ const binding = createHash("sha256").update(JSON.stringify([
3933
+ membership.id,
3934
+ user.id,
3935
+ profileId,
3936
+ membership.tenantId,
3937
+ membership.roleId
3938
+ ])).digest("hex");
3939
+ return {
3940
+ user,
3941
+ membership,
3942
+ profile,
3943
+ profileId,
3944
+ binding
3945
+ };
3946
+ }
3947
+ /** Prepare or replay a pending membership, preserving all existing authority. */
3948
+ async prepare(input) {
3949
+ if (!input.tenantId?.trim() || !input.roleSlug?.trim() || !isValidEmail(input.email)) throw new TenantInvitationError("Invalid tenant invitation input");
3950
+ const email = normalizeIdentityEmail(input.email);
3951
+ return await withSystemContext(async () => {
3952
+ const tenant = await (await TenantCollection.create(this.options)).get({ id: input.tenantId }, { cache: false });
3953
+ if (!tenant || tenant.status !== TenantStatus.ACTIVE) throw new TenantInvitationError("Invitation tenant is unavailable");
3954
+ const role = await (await RoleCollection.create(this.options)).findSystemRoleBySlug(input.roleSlug);
3955
+ if (!role?.id) throw new TenantInvitationError("Invitation system role is unavailable");
3956
+ const users = await UserCollection.create(this.options);
3957
+ const profiles = await ProfileCollection.create(this.options);
3958
+ let user = await users.findCanonicalByEmail(email);
3959
+ let profileId;
3960
+ if (user) {
3961
+ if (user.status !== UserStatus.ACTIVE && user.status !== UserStatus.PENDING) throw new TenantInvitationError("Invitation user is unavailable");
3962
+ profileId = requiredId((await profiles.requireCanonicalGlobalPerson(user.profileId, email)).id);
3963
+ const owners = await users.list({
3964
+ where: { profileId },
3965
+ limit: 2
3966
+ });
3967
+ if (owners.length !== 1 || owners[0].id !== user.id) throw new TenantInvitationError("Invitation identity ownership is inconsistent");
3968
+ } else {
3969
+ if (await profiles.findUniqueGlobalPersonByEmail(email)) throw new TenantInvitationError("Invitation email requires explicit identity reconciliation");
3970
+ const personType = await (await ProfileTypeCollection.create(this.options)).getOrCreateGlobalBySlug("person", {
3971
+ name: "Person",
3972
+ description: "Individual person profile"
3973
+ });
3974
+ const person = new Person({
3975
+ ...this.options,
3976
+ tenantId: null,
3977
+ typeId: requiredId(personType.id),
3978
+ slug: `invitation-${randomUUID()}`,
3979
+ name: email,
3980
+ email
3981
+ });
3982
+ await person.initialize();
3983
+ await person.save();
3984
+ profileId = requiredId(person.id);
3985
+ await profiles.reserveCanonicalIdentityEmail(profileId, email);
3986
+ user = await users.create({
3987
+ email,
3988
+ profileId,
3989
+ status: UserStatus.PENDING
3990
+ });
3991
+ }
3992
+ const userId = requiredId(user.id);
3993
+ const memberships = await MembershipCollection.create(this.options);
3994
+ const matches = await memberships.list({
3995
+ where: {
3996
+ userId,
3997
+ tenantId: input.tenantId
3998
+ },
3999
+ limit: 2
4000
+ });
4001
+ if (matches.length > 1) throw new TenantInvitationError("Invitation membership is ambiguous");
4002
+ let membership = matches[0];
4003
+ if (membership) {
4004
+ if (membership.status !== MembershipStatus.ACTIVE && membership.status !== MembershipStatus.PENDING) throw new TenantInvitationError("Invitation membership is unavailable");
4005
+ if (membership.status === MembershipStatus.PENDING && membership.roleId !== role.id) throw new TenantInvitationError("Pending invitation role conflicts with existing invitation");
4006
+ } else membership = await memberships.create({
4007
+ userId,
4008
+ tenantId: input.tenantId,
4009
+ roleId: role.id,
4010
+ status: MembershipStatus.PENDING
4011
+ });
4012
+ return {
4013
+ userId,
4014
+ profileId,
4015
+ membershipId: requiredId(membership.id),
4016
+ status: membership.status
4017
+ };
4018
+ });
4019
+ }
4020
+ };
4021
+ function requiredId(id) {
4022
+ if (typeof id !== "string" || !id) throw new TenantInvitationError("Invitation record has no id");
4023
+ return id;
4024
+ }
4025
+ //#endregion
3500
4026
  //#region src/services/TenantService.ts
3501
4027
  var TenantService = class TenantService {
3502
4028
  options;
@@ -3661,6 +4187,6 @@ var TenantService = class TenantService {
3661
4187
  //#region src/index.ts
3662
4188
  registerUserRetentionTasks();
3663
4189
  //#endregion
3664
- export { ACCESS_REQUEST_CAPABILITIES, ANCESTOR_READ_ACTION, AccessRequest, AccessRequestCollection, AccessRequestError, AccessRequestService, AccessRequestStatus, CLI_AUTH_RETENTION_TASK, UsersCliAuthRequest as CliAuthRequest, UsersCliAuthRequest, UsersCliAuthRequestCollection as CliAuthRequestCollection, UsersCliAuthRequestCollection, DEFAULT_ANCESTOR_READ_MAX_DEPTH, DEFAULT_CLI_AUTH_POLL_INTERVAL_SECONDS, DEFAULT_CLI_AUTH_REQUEST_TTL_SECONDS, DEFAULT_CLI_SESSION_TTL_SECONDS, DEFAULT_DEVICE_PERSON_IDLE_SECONDS, DEFAULT_LOGIN_ATTEMPT_WINDOW_SECONDS, DEFAULT_LOGIN_AUDIT_RETENTION_DAYS, DEFAULT_LOGIN_LOCKOUT_BASE_SECONDS, DEFAULT_LOGIN_LOCKOUT_FACTOR, DEFAULT_LOGIN_LOCKOUT_MAX_SECONDS, DEFAULT_LOGIN_MAX_ATTEMPTS, DEFAULT_MAX_PASSKEYS_PER_USER, DEFAULT_PASSKEY_CHALLENGE_TTL_SECONDS, DEFAULT_PASSKEY_FRESH_AUTH_METHODS, DEFAULT_PASSKEY_FRESH_SESSION_SECONDS, DEFAULT_PASSKEY_MANAGE_PERMISSION, DEFAULT_PASSKEY_NAME, DEFAULT_PASSWORD_DENYLIST, DEFAULT_PASSWORD_MANAGE_PERMISSION, DEFAULT_PASSWORD_MAX_LENGTH, DEFAULT_PASSWORD_MIN_LENGTH, DEFAULT_PASSWORD_RECOVERY_MAX_AGE_SECONDS, DEFAULT_PIN_MANAGE_PERMISSION, DEFAULT_ROLES, DEFAULT_ROLE_PERMISSION_PATTERNS, DEFAULT_ROLE_SLUGS, DEFAULT_SESSION_TTL, DEFAULT_SOURCE_LOCKOUT_AUDIT_SECONDS, DEFAULT_TENANT_POLICY, DEFAULT_TOKEN_EXPIRY_SECONDS, DeviceCredentialError, DeviceCredentialForbiddenError, DeviceCredentialPolicyError, DeviceCredentialService, DurableLoginAuditSink, Group, GroupCollection, GroupMember, GroupMemberCollection, GroupRole, GroupRoleCollection, InvalidCredentialsError, LEGACY_USER_PROFILE_BACKFILL_NAME, LOGIN_ATTEMPTS_RETENTION_TASK, LOGIN_AUDIT_RETENTION_TASK, LegacyUserProfileBackfillError, LegalMember, LegalMemberCollection, LegalMemberReference, LegalMemberReferenceCollection, LegalMemberStatusHistory, LegalMemberStatusHistoryCollection, LoginAttemptLimiter, LoginRateLimitError, MAGIC_LINK_RETENTION_TASK, MAX_RESOURCE_GRANT_DELEGATION_DEPTH, MAX_TENANT_HIERARCHY_DEPTH, MagicLinkError, MagicLinkService, UsersMagicLinkToken as MagicLinkToken, UsersMagicLinkToken, UsersMagicLinkTokenCollection as MagicLinkTokenCollection, UsersMagicLinkTokenCollection, MemberClass, MemberClassCollection, MemberEligibilitySnapshot, MemberEligibilitySnapshotCollection, MemberOfficerAppointment, MemberOfficerAppointmentCollection, MemberRegisterError, MemberRegisterService, Membership, MembershipCollection, MembershipOverride, MembershipOverrideCollection, MembershipStatus, MobileAuthError, MobileAuthService, OAUTH_CREDENTIALS_RETENTION_TASK, OidcLoginError, OidcLoginService, OidcProvisioningError, OperationPermissionError, OverrideEffect, PASSKEY_CHALLENGES_RETENTION_TASK, PASSKEY_CHALLENGE_TTL_CEILING_SECONDS, PASSKEY_FRESH_SESSION_CEILING_SECONDS, PASSKEY_FRESH_SESSION_FLOOR_SECONDS, PASSKEY_LOGIN_KIND, PASSKEY_MAX_PER_USER_CEILING, PASSKEY_NAME_MAX_LENGTH, PASSKEY_PERMISSION_DEFINITIONS, PASSKEY_SESSION_DATA_KEY, PASSWORD_LOGIN_KIND, PASSWORD_MAX_LENGTH_CEILING, PASSWORD_PERMISSION_DEFINITIONS, PASSWORD_RECOVERY_MAX_AGE_CEILING_SECONDS, PIN_LOGIN_KIND, PIN_PERMISSION_DEFINITIONS, PasskeyCredentialError, PasskeyCredentialForbiddenError, PasskeyCredentialService, PasskeyReauthenticationRequiredError, PasskeyRegistrationError, PasswordCredentialError, PasswordCredentialForbiddenError, PasswordCredentialService, PasswordPolicyError, Permission, PermissionCatalogService, PermissionCollection, PermissionResolver, PinVerifier, ResourceGrant, ResourceGrantCollection, ResourceGrantService, Role, RoleCollection, RolePermission, RolePermissionCollection, SESSIONS_RETENTION_TASK, SESSION_DATA_KEYS, SMRT_OAUTH_GRANT_CLAIM, Session, SessionCollection, SessionService, SessionStatus, SmrtOAuthAuthorizationService, SmrtOAuthAuthorizationStorage, TERMINAL_APPROVE_LOGIN_KIND, Tenant, TenantCollection, TenantHierarchyError, TenantHierarchyMaterializationError, TenantIntegration, TenantIntegrationCollection, TenantPermissionEffect, TenantPermissionOverride, TenantPermissionOverrideCollection, TenantService, TenantStatus, TerminalAuthError, TerminalAuthRateLimitError, TerminalAuthService, USER_RETENTION_TASKS, User, UserCollection, UserEmailKeyBackfillError, UserStatus, UsersCliAuthApproveLimit, UsersCliAuthApproveLimitCollection, UsersLoginAttempt, UsersLoginAttemptCollection, UsersLoginAuditEvent, UsersLoginAuditEventCollection, UsersOAuthAccessTokenRevocation, UsersOAuthAccessTokenRevocationCollection, UsersOAuthAuthorization, UsersOAuthAuthorizationCode, UsersOAuthAuthorizationCodeCollection, UsersOAuthAuthorizationCollection, UsersOAuthClient, UsersOAuthClientCollection, UsersOAuthRefreshFamily, UsersOAuthRefreshFamilyCollection, UsersOAuthRefreshGrant, UsersOAuthRefreshGrantCollection, UsersPasskeyChallenge, UsersPasskeyChallengeCollection, UsersPasskeyCredential, UsersPasskeyCredentialCollection, UsersPasswordCredential, UsersPasswordCredentialCollection, UsersPinCredential, UsersPinCredentialCollection, UsersRolesAndPermissionsRecipe, UsersSignInRecipe, applyPostgresPermissionPolicies, assertOperationPermission, backfillLegacyUserProfiles, backfillUserEmailKeys, checkOperationPermission, checkReadiness, checkResourceOperationPermission, decodeOidcTransaction, deduplicateAuthorityPairs, deduplicateRolePermissions, deriveOperationPermissionCollectionName, deriveOperationPermissionSlug, encodeOidcTransaction, ensurePasskeyPermissionsRegistered, ensurePasswordPermissionsRegistered, ensurePinPermissionsRegistered, generatePostgresPermissionSql, generateSessionId, getConfiguredAncestorReadPolicy, getCurrentSessionPermissionContext, getRequestScopedDatabase, getUsersOidcConfig, hasOperationPermission, isAncestorReadableSlug, materializeTenantHierarchy, normalizeAncestorReadPolicy, normalizeOperationPermissionAction, outOfBandProofSessionData, planTenantHierarchy, readMobileBearerToken, registerPermissionDefinitions, registerUserRetentionTasks, resolveOidcProviderConfig, syncPermissionCatalog, unregisterUserRetentionTasks, validateMobileRedirectUri, withPrincipalPermissionContext, withSessionPermissionContext };
4190
+ export { ACCESS_REQUEST_CAPABILITIES, ANCESTOR_READ_ACTION, AccessRequest, AccessRequestCollection, AccessRequestError, AccessRequestService, AccessRequestStatus, CLI_AUTH_RETENTION_TASK, UsersCliAuthRequest as CliAuthRequest, UsersCliAuthRequest, UsersCliAuthRequestCollection as CliAuthRequestCollection, UsersCliAuthRequestCollection, DEFAULT_ANCESTOR_READ_MAX_DEPTH, DEFAULT_CLI_AUTH_POLL_INTERVAL_SECONDS, DEFAULT_CLI_AUTH_REQUEST_TTL_SECONDS, DEFAULT_CLI_SESSION_TTL_SECONDS, DEFAULT_DEVICE_PERSON_IDLE_SECONDS, DEFAULT_LOGIN_ATTEMPT_WINDOW_SECONDS, DEFAULT_LOGIN_AUDIT_RETENTION_DAYS, DEFAULT_LOGIN_LOCKOUT_BASE_SECONDS, DEFAULT_LOGIN_LOCKOUT_FACTOR, DEFAULT_LOGIN_LOCKOUT_MAX_SECONDS, DEFAULT_LOGIN_MAX_ATTEMPTS, DEFAULT_MAX_PASSKEYS_PER_USER, DEFAULT_PASSKEY_CHALLENGE_TTL_SECONDS, DEFAULT_PASSKEY_FRESH_AUTH_METHODS, DEFAULT_PASSKEY_FRESH_SESSION_SECONDS, DEFAULT_PASSKEY_MANAGE_PERMISSION, DEFAULT_PASSKEY_NAME, DEFAULT_PASSWORD_DENYLIST, DEFAULT_PASSWORD_MANAGE_PERMISSION, DEFAULT_PASSWORD_MAX_LENGTH, DEFAULT_PASSWORD_MIN_LENGTH, DEFAULT_PASSWORD_RECOVERY_MAX_AGE_SECONDS, DEFAULT_PIN_MANAGE_PERMISSION, DEFAULT_ROLES, DEFAULT_ROLE_PERMISSION_PATTERNS, DEFAULT_ROLE_SLUGS, DEFAULT_SESSION_TTL, DEFAULT_SOURCE_LOCKOUT_AUDIT_SECONDS, DEFAULT_TENANT_POLICY, DEFAULT_TOKEN_EXPIRY_SECONDS, DeviceCredentialError, DeviceCredentialForbiddenError, DeviceCredentialPolicyError, DeviceCredentialService, DurableLoginAuditSink, Group, GroupCollection, GroupMember, GroupMemberCollection, GroupRole, GroupRoleCollection, InvalidCredentialsError, LEGACY_USER_PROFILE_BACKFILL_NAME, LOGIN_ATTEMPTS_RETENTION_TASK, LOGIN_AUDIT_RETENTION_TASK, LegacyUserProfileBackfillError, LegalMember, LegalMemberCollection, LegalMemberReference, LegalMemberReferenceCollection, LegalMemberStatusHistory, LegalMemberStatusHistoryCollection, LoginAttemptLimiter, LoginRateLimitError, MAGIC_LINK_RETENTION_TASK, MAX_RESOURCE_GRANT_DELEGATION_DEPTH, MAX_TENANT_HIERARCHY_DEPTH, MagicLinkError, MagicLinkService, UsersMagicLinkToken as MagicLinkToken, UsersMagicLinkToken, UsersMagicLinkTokenCollection as MagicLinkTokenCollection, UsersMagicLinkTokenCollection, MailboxAuthenticationService, MemberClass, MemberClassCollection, MemberEligibilitySnapshot, MemberEligibilitySnapshotCollection, MemberOfficerAppointment, MemberOfficerAppointmentCollection, MemberRegisterError, MemberRegisterService, Membership, MembershipCollection, MembershipOverride, MembershipOverrideCollection, MembershipStatus, MobileAuthError, MobileAuthService, OAUTH_CREDENTIALS_RETENTION_TASK, OidcLoginError, OidcLoginService, OidcProvisioningError, OperationPermissionError, OverrideEffect, PASSKEY_CHALLENGES_RETENTION_TASK, PASSKEY_CHALLENGE_TTL_CEILING_SECONDS, PASSKEY_FRESH_SESSION_CEILING_SECONDS, PASSKEY_FRESH_SESSION_FLOOR_SECONDS, PASSKEY_LOGIN_KIND, PASSKEY_MAX_PER_USER_CEILING, PASSKEY_NAME_MAX_LENGTH, PASSKEY_PERMISSION_DEFINITIONS, PASSKEY_SESSION_DATA_KEY, PASSWORD_LOGIN_KIND, PASSWORD_MAX_LENGTH_CEILING, PASSWORD_PERMISSION_DEFINITIONS, PASSWORD_RECOVERY_MAX_AGE_CEILING_SECONDS, PIN_LOGIN_KIND, PIN_PERMISSION_DEFINITIONS, PasskeyCredentialError, PasskeyCredentialForbiddenError, PasskeyCredentialService, PasskeyReauthenticationRequiredError, PasskeyRegistrationError, PasswordCredentialError, PasswordCredentialForbiddenError, PasswordCredentialService, PasswordPolicyError, Permission, PermissionCatalogService, PermissionCollection, PermissionResolver, PinVerifier, ResourceGrant, ResourceGrantCollection, ResourceGrantService, Role, RoleCollection, RolePermission, RolePermissionCollection, SESSIONS_RETENTION_TASK, SESSION_DATA_KEYS, SMRT_OAUTH_GRANT_CLAIM, Session, SessionCollection, SessionService, SessionStatus, SmrtOAuthAuthorizationService, SmrtOAuthAuthorizationStorage, TERMINAL_APPROVE_LOGIN_KIND, Tenant, TenantCollection, TenantHierarchyError, TenantHierarchyMaterializationError, TenantIntegration, TenantIntegrationCollection, TenantInvitationError, TenantInvitationService, TenantPermissionEffect, TenantPermissionOverride, TenantPermissionOverrideCollection, TenantService, TenantStatus, TerminalAuthError, TerminalAuthRateLimitError, TerminalAuthService, USER_RETENTION_TASKS, User, UserCollection, UserEmailKeyBackfillError, UserStatus, UsersCliAuthApproveLimit, UsersCliAuthApproveLimitCollection, UsersLoginAttempt, UsersLoginAttemptCollection, UsersLoginAuditEvent, UsersLoginAuditEventCollection, UsersOAuthAccessTokenRevocation, UsersOAuthAccessTokenRevocationCollection, UsersOAuthAuthorization, UsersOAuthAuthorizationCode, UsersOAuthAuthorizationCodeCollection, UsersOAuthAuthorizationCollection, UsersOAuthClient, UsersOAuthClientCollection, UsersOAuthRefreshFamily, UsersOAuthRefreshFamilyCollection, UsersOAuthRefreshGrant, UsersOAuthRefreshGrantCollection, UsersPasskeyChallenge, UsersPasskeyChallengeCollection, UsersPasskeyCredential, UsersPasskeyCredentialCollection, UsersPasswordCredential, UsersPasswordCredentialCollection, UsersPinCredential, UsersPinCredentialCollection, UsersRolesAndPermissionsRecipe, UsersSignInRecipe, applyPostgresPermissionPolicies, assertOperationPermission, backfillLegacyUserProfiles, backfillUserEmailKeys, checkOperationPermission, checkReadiness, checkResourceOperationPermission, decodeOidcTransaction, deduplicateAuthorityPairs, deduplicateRolePermissions, deriveOperationPermissionCollectionName, deriveOperationPermissionSlug, encodeOidcTransaction, ensurePasskeyPermissionsRegistered, ensurePasswordPermissionsRegistered, ensurePinPermissionsRegistered, generatePostgresPermissionSql, generateSessionId, getConfiguredAncestorReadPolicy, getCurrentSessionPermissionContext, getRequestScopedDatabase, getUsersOidcConfig, hasOperationPermission, isAncestorReadableSlug, materializeTenantHierarchy, normalizeAncestorReadPolicy, normalizeOperationPermissionAction, outOfBandProofSessionData, planTenantHierarchy, readMobileBearerToken, registerPermissionDefinitions, registerUserRetentionTasks, resolveOidcProviderConfig, syncPermissionCatalog, unregisterUserRetentionTasks, validateMobileRedirectUri, withPrincipalPermissionContext, withSessionPermissionContext };
3665
4191
 
3666
4192
  //# sourceMappingURL=index.js.map