@happyvertical/smrt-users 0.57.22 → 0.57.24

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
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-pHNqf5o3.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-Cs_59-Al.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
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";
@@ -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
  }
@@ -2641,7 +2704,7 @@ var MagicLinkService = class MagicLinkService {
2641
2704
  * The caller is responsible for emailing the token to the user.
2642
2705
  */
2643
2706
  async generate(email, options = {}) {
2644
- const { SignJWT } = await import("./chunks/TerminalAuthService-pHNqf5o3.js").then((n) => n.G);
2707
+ const { SignJWT } = await import("./chunks/TerminalAuthService-Cs_59-Al.js").then((n) => n.G);
2645
2708
  const key = await this.getSigningKey();
2646
2709
  const nonce = crypto.randomUUID();
2647
2710
  const normalizedEmail = normalizeEmail(email);
@@ -2685,7 +2748,7 @@ var MagicLinkService = class MagicLinkService {
2685
2748
  return proof;
2686
2749
  }
2687
2750
  async verifySignature(token) {
2688
- const { jwtVerify, errors } = await import("./chunks/TerminalAuthService-pHNqf5o3.js").then((n) => n.G);
2751
+ const { jwtVerify, errors } = await import("./chunks/TerminalAuthService-Cs_59-Al.js").then((n) => n.G);
2689
2752
  const key = await this.getSigningKey();
2690
2753
  let payload;
2691
2754
  try {