@digilogiclabs/platform-core 1.18.0 → 1.19.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/auth.d.mts CHANGED
@@ -666,4 +666,215 @@ declare function createSecureHandlerFactory<TSession extends SecureSession = Sec
666
666
  }) => Promise<Response>;
667
667
  };
668
668
 
669
- export { type FederatedLogoutConfig, type LazyRateLimitStoreOptions, RateLimitOptions, type RateLimitResult, RateLimitRule, RateLimitStore, type RedisRateLimitClient, type RedisRateLimitStoreOptions, type SecureAuditConfig, type SecureAuthMethod, type SecureHandlerFactoryConfig, type SecureLogger, type SecureRateLimitResult, type SecureRouteConfig, type SecureRouteContext, type SecureRouteHandler, type SecureSession, type SecureTimedAudit, addRateLimitHeaders, buildFederatedLogoutHandler, createLazyRateLimitStore, createRedisRateLimitStore, createSecureHandlerFactory, enforceRateLimit, errorResponse, extractBearerToken, getClientIp, isValidBearerToken, rateLimitResponse, safeValidate, verifyCronAuth, zodErrorResponse };
669
+ /**
670
+ * createEnsureUser — drift-proof choke point for resolving a Keycloak session
671
+ * to a local `users.id` in apps that mirror Keycloak users into their own
672
+ * `users` table.
673
+ *
674
+ * **Why this exists:** Keycloak-mirrored apps that match only by `keycloak_id`
675
+ * silently accumulate duplicate rows whenever the Keycloak `sub` rotates
676
+ * (admin reset, realm migration, sub-claim format change, logout-saga
677
+ * resign-in storms). Each duplicate strands `creator_id` / favorites /
678
+ * preferences / analytics behind an orphan row keyed on a stale sub. Same
679
+ * email, different rows, invisible data.
680
+ *
681
+ * **The 3-layer pattern this factory enforces:**
682
+ *
683
+ * 1. **Hot path** — match by `keycloak_id` (one indexed read). If the cached
684
+ * email or displayName differs from the current Keycloak claims, fire
685
+ * `onClaimRefresh` so the local mirror stays aligned with Keycloak truth.
686
+ * A missing claim never erases an existing value (don't-erase-on-missing).
687
+ *
688
+ * 2. **Claim-on-login by email** — if no `keycloak_id` row exists but a row
689
+ * exists for the same (lower-cased) email, re-anchor that row to the
690
+ * current sub via `rebindKeycloakId`. The email is trusted because
691
+ * Keycloak only forwards verified addresses into the OIDC session. This
692
+ * is the rule that prevents new drift from being created.
693
+ *
694
+ * 3. **Insert** — brand-new user. Optional `onNewUser` hook for
695
+ * schema-specific backfills (e.g. linking pre-registration anonymous
696
+ * donations by email). `onNewUser` errors are swallowed; the user row
697
+ * is already created, so failure to backfill must not block sign-in.
698
+ *
699
+ * **Choke-point invariant:** every authenticated path that needs a `users.id`
700
+ * MUST go through the function this factory returns. Use it in BOTH read and
701
+ * write paths so every authenticated GET becomes a self-healing touchpoint —
702
+ * stale `keycloak_id` sessions are re-anchored on the FIRST authenticated
703
+ * request, not "first POST that mutates state." Read-side `if (!user) return
704
+ * empty` early-returns silently mask drift behind 200 OK responses with
705
+ * empty payloads.
706
+ *
707
+ * **Pair with a DB-level guard:**
708
+ * ```sql
709
+ * CREATE UNIQUE INDEX <prefix>_users_lower_email_uniq
710
+ * ON <schema>.users (lower(email))
711
+ * WHERE email IS NOT NULL;
712
+ * ```
713
+ * Apply ONLY after merging existing duplicates — pre-existing dups block
714
+ * index creation. See `memory/user-identity-choke-point.md` for the merge
715
+ * playbook + cross-app port reference.
716
+ *
717
+ * **Edge-runtime safe:** this module imports nothing — apps wire their own
718
+ * Drizzle/pg queries via the four required callbacks. No transitive
719
+ * dependency on `pg`, `stripe`, or any Node-only SDK.
720
+ *
721
+ * @example
722
+ * ```ts
723
+ * // app/src/lib/db/ensure-user.ts
724
+ * import { createEnsureUser } from '@digilogiclabs/platform-core/auth';
725
+ * import { db } from './drizzle';
726
+ * import { users, donations } from './schema';
727
+ * import { and, eq, isNull, sql } from 'drizzle-orm';
728
+ *
729
+ * export const ensureUser = createEnsureUser({
730
+ * async findByKeycloakId(keycloakId) {
731
+ * const [row] = await db.select({
732
+ * id: users.id,
733
+ * email: users.email,
734
+ * displayName: users.displayName,
735
+ * }).from(users).where(eq(users.keycloakId, keycloakId)).limit(1);
736
+ * return row ?? null;
737
+ * },
738
+ * async findByEmailLower(emailLower) {
739
+ * const [row] = await db.select({
740
+ * id: users.id,
741
+ * email: users.email,
742
+ * displayName: users.displayName,
743
+ * }).from(users)
744
+ * .where(sql`lower(${users.email}) = ${emailLower}`)
745
+ * .limit(1);
746
+ * return row ?? null;
747
+ * },
748
+ * async rebindKeycloakId(userId, keycloakId, name) {
749
+ * await db.update(users)
750
+ * .set({ keycloakId, ...(name ? { displayName: name } : {}), updatedAt: new Date() })
751
+ * .where(eq(users.id, userId));
752
+ * },
753
+ * async insertNewUser({ keycloakId, email, name }) {
754
+ * const [row] = await db.insert(users).values({
755
+ * keycloakId,
756
+ * email: email ?? undefined,
757
+ * displayName: name ?? undefined,
758
+ * }).returning({ id: users.id });
759
+ * return { id: row!.id };
760
+ * },
761
+ * async onClaimRefresh(userId, next) {
762
+ * await db.update(users)
763
+ * .set({
764
+ * ...(next.email !== undefined ? { email: next.email } : {}),
765
+ * ...(next.displayName !== undefined ? { displayName: next.displayName } : {}),
766
+ * updatedAt: new Date(),
767
+ * })
768
+ * .where(eq(users.id, userId));
769
+ * },
770
+ * async onNewUser(userId, email) {
771
+ * if (!email) return;
772
+ * await db.update(donations)
773
+ * .set({ userId })
774
+ * .where(and(sql`lower(${donations.email}) = ${email.toLowerCase()}`, isNull(donations.userId)));
775
+ * },
776
+ * });
777
+ * ```
778
+ */
779
+ /**
780
+ * Minimal row shape returned by lookup callbacks. `email` and `displayName`
781
+ * are optional so apps that don't track those columns can omit them — they
782
+ * only feed the `onClaimRefresh` drift-detection path.
783
+ */
784
+ interface EnsureUserRow {
785
+ id: string;
786
+ email?: string | null;
787
+ displayName?: string | null;
788
+ }
789
+ /**
790
+ * Claims surfaced to `onClaimRefresh`. Only fields the factory actually
791
+ * detected as changed are populated; unchanged fields are `undefined` so
792
+ * the callback can do a sparse UPDATE without overwriting other columns.
793
+ */
794
+ interface EnsureUserClaimDelta {
795
+ /**
796
+ * The current Keycloak `email` claim, if it differs from the cached value.
797
+ * `null` means Keycloak explicitly cleared the email; `undefined` means
798
+ * the email was unchanged or not provided in this call.
799
+ */
800
+ email?: string | null;
801
+ /**
802
+ * The current Keycloak `name` claim, if it differs from the cached value.
803
+ * Only present when the caller supplied a non-empty name AND it differs
804
+ * from the cached `displayName` — a missing claim never erases the
805
+ * existing name.
806
+ */
807
+ displayName?: string;
808
+ }
809
+ interface EnsureUserConfig {
810
+ /**
811
+ * Lookup by `keycloak_id`. Should return the row with at least `id`, and
812
+ * preferably `email` and `displayName` so the factory can detect claim
813
+ * drift and call `onClaimRefresh`.
814
+ */
815
+ findByKeycloakId(keycloakId: string): Promise<EnsureUserRow | null>;
816
+ /**
817
+ * Lookup by lower-cased email. The factory passes the email already
818
+ * lower-cased, so the callback can match with a simple
819
+ * `lower(users.email) = $1` predicate. Only invoked when the caller
820
+ * supplied a non-empty email.
821
+ */
822
+ findByEmailLower(emailLowerCase: string): Promise<EnsureUserRow | null>;
823
+ /**
824
+ * Re-anchor a stale row's `keycloak_id` to the current sub. Used when
825
+ * step 2 (claim-on-login) finds a row by email whose sub no longer
826
+ * matches. Implementations should ALSO refresh `displayName` when `name`
827
+ * is non-empty (don't-erase-on-missing-claim) and bump `updatedAt`.
828
+ */
829
+ rebindKeycloakId(userId: string, keycloakId: string, name: string | null | undefined): Promise<void>;
830
+ /**
831
+ * Insert a brand-new user row. Must return `{ id }` of the new row.
832
+ * Implementations should treat null/undefined `email` / `name` as
833
+ * absent fields, not empty strings.
834
+ */
835
+ insertNewUser(input: {
836
+ keycloakId: string;
837
+ email: string | null | undefined;
838
+ name: string | null | undefined;
839
+ }): Promise<{
840
+ id: string;
841
+ }>;
842
+ /**
843
+ * Optional. Called from the hot path (step 1) when the cached email or
844
+ * displayName differs from the current Keycloak claims. Apps that wire
845
+ * this get a self-correcting local mirror — every authenticated request
846
+ * brings the cached profile back into sync with Keycloak truth.
847
+ *
848
+ * **Don't-erase-on-missing-claim:** a missing claim is never reported as
849
+ * a change. `email: null` means Keycloak explicitly cleared the email;
850
+ * `email: undefined` means it wasn't supplied. Callbacks should use
851
+ * `if (next.email !== undefined)` to distinguish.
852
+ *
853
+ * Errors thrown from this callback propagate to the caller — the user
854
+ * is already authenticated and the row exists, so a failed refresh is
855
+ * worth surfacing rather than swallowing.
856
+ */
857
+ onClaimRefresh?(userId: string, delta: EnsureUserClaimDelta): Promise<void>;
858
+ /**
859
+ * Optional. Called from step 3 (insert) after a brand-new row is
860
+ * created. Used for app-specific backfills like linking pre-registration
861
+ * anonymous donations by email. Receives the new user's id and the
862
+ * email that was supplied at signup.
863
+ *
864
+ * Errors thrown from this callback are swallowed — the user row is
865
+ * already created, so a failed backfill must not block sign-in. If you
866
+ * need observability, log inside the callback.
867
+ */
868
+ onNewUser?(userId: string, email: string | null | undefined): Promise<void>;
869
+ }
870
+ /** Function returned by `createEnsureUser`. */
871
+ type EnsureUserFn = (keycloakId: string, email?: string | null, name?: string | null) => Promise<string>;
872
+ /**
873
+ * Build the canonical `ensureUser(keycloakId, email?, name?)` helper for an
874
+ * app that mirrors Keycloak users into its own `users` table.
875
+ *
876
+ * See file-level JSDoc for the full pattern, invariants, and example wiring.
877
+ */
878
+ declare function createEnsureUser(config: EnsureUserConfig): EnsureUserFn;
879
+
880
+ export { type EnsureUserClaimDelta, type EnsureUserConfig, type EnsureUserFn, type EnsureUserRow, type FederatedLogoutConfig, type LazyRateLimitStoreOptions, RateLimitOptions, type RateLimitResult, RateLimitRule, RateLimitStore, type RedisRateLimitClient, type RedisRateLimitStoreOptions, type SecureAuditConfig, type SecureAuthMethod, type SecureHandlerFactoryConfig, type SecureLogger, type SecureRateLimitResult, type SecureRouteConfig, type SecureRouteContext, type SecureRouteHandler, type SecureSession, type SecureTimedAudit, addRateLimitHeaders, buildFederatedLogoutHandler, createEnsureUser, createLazyRateLimitStore, createRedisRateLimitStore, createSecureHandlerFactory, enforceRateLimit, errorResponse, extractBearerToken, getClientIp, isValidBearerToken, rateLimitResponse, safeValidate, verifyCronAuth, zodErrorResponse };
package/dist/auth.d.ts CHANGED
@@ -666,4 +666,215 @@ declare function createSecureHandlerFactory<TSession extends SecureSession = Sec
666
666
  }) => Promise<Response>;
667
667
  };
668
668
 
669
- export { type FederatedLogoutConfig, type LazyRateLimitStoreOptions, RateLimitOptions, type RateLimitResult, RateLimitRule, RateLimitStore, type RedisRateLimitClient, type RedisRateLimitStoreOptions, type SecureAuditConfig, type SecureAuthMethod, type SecureHandlerFactoryConfig, type SecureLogger, type SecureRateLimitResult, type SecureRouteConfig, type SecureRouteContext, type SecureRouteHandler, type SecureSession, type SecureTimedAudit, addRateLimitHeaders, buildFederatedLogoutHandler, createLazyRateLimitStore, createRedisRateLimitStore, createSecureHandlerFactory, enforceRateLimit, errorResponse, extractBearerToken, getClientIp, isValidBearerToken, rateLimitResponse, safeValidate, verifyCronAuth, zodErrorResponse };
669
+ /**
670
+ * createEnsureUser — drift-proof choke point for resolving a Keycloak session
671
+ * to a local `users.id` in apps that mirror Keycloak users into their own
672
+ * `users` table.
673
+ *
674
+ * **Why this exists:** Keycloak-mirrored apps that match only by `keycloak_id`
675
+ * silently accumulate duplicate rows whenever the Keycloak `sub` rotates
676
+ * (admin reset, realm migration, sub-claim format change, logout-saga
677
+ * resign-in storms). Each duplicate strands `creator_id` / favorites /
678
+ * preferences / analytics behind an orphan row keyed on a stale sub. Same
679
+ * email, different rows, invisible data.
680
+ *
681
+ * **The 3-layer pattern this factory enforces:**
682
+ *
683
+ * 1. **Hot path** — match by `keycloak_id` (one indexed read). If the cached
684
+ * email or displayName differs from the current Keycloak claims, fire
685
+ * `onClaimRefresh` so the local mirror stays aligned with Keycloak truth.
686
+ * A missing claim never erases an existing value (don't-erase-on-missing).
687
+ *
688
+ * 2. **Claim-on-login by email** — if no `keycloak_id` row exists but a row
689
+ * exists for the same (lower-cased) email, re-anchor that row to the
690
+ * current sub via `rebindKeycloakId`. The email is trusted because
691
+ * Keycloak only forwards verified addresses into the OIDC session. This
692
+ * is the rule that prevents new drift from being created.
693
+ *
694
+ * 3. **Insert** — brand-new user. Optional `onNewUser` hook for
695
+ * schema-specific backfills (e.g. linking pre-registration anonymous
696
+ * donations by email). `onNewUser` errors are swallowed; the user row
697
+ * is already created, so failure to backfill must not block sign-in.
698
+ *
699
+ * **Choke-point invariant:** every authenticated path that needs a `users.id`
700
+ * MUST go through the function this factory returns. Use it in BOTH read and
701
+ * write paths so every authenticated GET becomes a self-healing touchpoint —
702
+ * stale `keycloak_id` sessions are re-anchored on the FIRST authenticated
703
+ * request, not "first POST that mutates state." Read-side `if (!user) return
704
+ * empty` early-returns silently mask drift behind 200 OK responses with
705
+ * empty payloads.
706
+ *
707
+ * **Pair with a DB-level guard:**
708
+ * ```sql
709
+ * CREATE UNIQUE INDEX <prefix>_users_lower_email_uniq
710
+ * ON <schema>.users (lower(email))
711
+ * WHERE email IS NOT NULL;
712
+ * ```
713
+ * Apply ONLY after merging existing duplicates — pre-existing dups block
714
+ * index creation. See `memory/user-identity-choke-point.md` for the merge
715
+ * playbook + cross-app port reference.
716
+ *
717
+ * **Edge-runtime safe:** this module imports nothing — apps wire their own
718
+ * Drizzle/pg queries via the four required callbacks. No transitive
719
+ * dependency on `pg`, `stripe`, or any Node-only SDK.
720
+ *
721
+ * @example
722
+ * ```ts
723
+ * // app/src/lib/db/ensure-user.ts
724
+ * import { createEnsureUser } from '@digilogiclabs/platform-core/auth';
725
+ * import { db } from './drizzle';
726
+ * import { users, donations } from './schema';
727
+ * import { and, eq, isNull, sql } from 'drizzle-orm';
728
+ *
729
+ * export const ensureUser = createEnsureUser({
730
+ * async findByKeycloakId(keycloakId) {
731
+ * const [row] = await db.select({
732
+ * id: users.id,
733
+ * email: users.email,
734
+ * displayName: users.displayName,
735
+ * }).from(users).where(eq(users.keycloakId, keycloakId)).limit(1);
736
+ * return row ?? null;
737
+ * },
738
+ * async findByEmailLower(emailLower) {
739
+ * const [row] = await db.select({
740
+ * id: users.id,
741
+ * email: users.email,
742
+ * displayName: users.displayName,
743
+ * }).from(users)
744
+ * .where(sql`lower(${users.email}) = ${emailLower}`)
745
+ * .limit(1);
746
+ * return row ?? null;
747
+ * },
748
+ * async rebindKeycloakId(userId, keycloakId, name) {
749
+ * await db.update(users)
750
+ * .set({ keycloakId, ...(name ? { displayName: name } : {}), updatedAt: new Date() })
751
+ * .where(eq(users.id, userId));
752
+ * },
753
+ * async insertNewUser({ keycloakId, email, name }) {
754
+ * const [row] = await db.insert(users).values({
755
+ * keycloakId,
756
+ * email: email ?? undefined,
757
+ * displayName: name ?? undefined,
758
+ * }).returning({ id: users.id });
759
+ * return { id: row!.id };
760
+ * },
761
+ * async onClaimRefresh(userId, next) {
762
+ * await db.update(users)
763
+ * .set({
764
+ * ...(next.email !== undefined ? { email: next.email } : {}),
765
+ * ...(next.displayName !== undefined ? { displayName: next.displayName } : {}),
766
+ * updatedAt: new Date(),
767
+ * })
768
+ * .where(eq(users.id, userId));
769
+ * },
770
+ * async onNewUser(userId, email) {
771
+ * if (!email) return;
772
+ * await db.update(donations)
773
+ * .set({ userId })
774
+ * .where(and(sql`lower(${donations.email}) = ${email.toLowerCase()}`, isNull(donations.userId)));
775
+ * },
776
+ * });
777
+ * ```
778
+ */
779
+ /**
780
+ * Minimal row shape returned by lookup callbacks. `email` and `displayName`
781
+ * are optional so apps that don't track those columns can omit them — they
782
+ * only feed the `onClaimRefresh` drift-detection path.
783
+ */
784
+ interface EnsureUserRow {
785
+ id: string;
786
+ email?: string | null;
787
+ displayName?: string | null;
788
+ }
789
+ /**
790
+ * Claims surfaced to `onClaimRefresh`. Only fields the factory actually
791
+ * detected as changed are populated; unchanged fields are `undefined` so
792
+ * the callback can do a sparse UPDATE without overwriting other columns.
793
+ */
794
+ interface EnsureUserClaimDelta {
795
+ /**
796
+ * The current Keycloak `email` claim, if it differs from the cached value.
797
+ * `null` means Keycloak explicitly cleared the email; `undefined` means
798
+ * the email was unchanged or not provided in this call.
799
+ */
800
+ email?: string | null;
801
+ /**
802
+ * The current Keycloak `name` claim, if it differs from the cached value.
803
+ * Only present when the caller supplied a non-empty name AND it differs
804
+ * from the cached `displayName` — a missing claim never erases the
805
+ * existing name.
806
+ */
807
+ displayName?: string;
808
+ }
809
+ interface EnsureUserConfig {
810
+ /**
811
+ * Lookup by `keycloak_id`. Should return the row with at least `id`, and
812
+ * preferably `email` and `displayName` so the factory can detect claim
813
+ * drift and call `onClaimRefresh`.
814
+ */
815
+ findByKeycloakId(keycloakId: string): Promise<EnsureUserRow | null>;
816
+ /**
817
+ * Lookup by lower-cased email. The factory passes the email already
818
+ * lower-cased, so the callback can match with a simple
819
+ * `lower(users.email) = $1` predicate. Only invoked when the caller
820
+ * supplied a non-empty email.
821
+ */
822
+ findByEmailLower(emailLowerCase: string): Promise<EnsureUserRow | null>;
823
+ /**
824
+ * Re-anchor a stale row's `keycloak_id` to the current sub. Used when
825
+ * step 2 (claim-on-login) finds a row by email whose sub no longer
826
+ * matches. Implementations should ALSO refresh `displayName` when `name`
827
+ * is non-empty (don't-erase-on-missing-claim) and bump `updatedAt`.
828
+ */
829
+ rebindKeycloakId(userId: string, keycloakId: string, name: string | null | undefined): Promise<void>;
830
+ /**
831
+ * Insert a brand-new user row. Must return `{ id }` of the new row.
832
+ * Implementations should treat null/undefined `email` / `name` as
833
+ * absent fields, not empty strings.
834
+ */
835
+ insertNewUser(input: {
836
+ keycloakId: string;
837
+ email: string | null | undefined;
838
+ name: string | null | undefined;
839
+ }): Promise<{
840
+ id: string;
841
+ }>;
842
+ /**
843
+ * Optional. Called from the hot path (step 1) when the cached email or
844
+ * displayName differs from the current Keycloak claims. Apps that wire
845
+ * this get a self-correcting local mirror — every authenticated request
846
+ * brings the cached profile back into sync with Keycloak truth.
847
+ *
848
+ * **Don't-erase-on-missing-claim:** a missing claim is never reported as
849
+ * a change. `email: null` means Keycloak explicitly cleared the email;
850
+ * `email: undefined` means it wasn't supplied. Callbacks should use
851
+ * `if (next.email !== undefined)` to distinguish.
852
+ *
853
+ * Errors thrown from this callback propagate to the caller — the user
854
+ * is already authenticated and the row exists, so a failed refresh is
855
+ * worth surfacing rather than swallowing.
856
+ */
857
+ onClaimRefresh?(userId: string, delta: EnsureUserClaimDelta): Promise<void>;
858
+ /**
859
+ * Optional. Called from step 3 (insert) after a brand-new row is
860
+ * created. Used for app-specific backfills like linking pre-registration
861
+ * anonymous donations by email. Receives the new user's id and the
862
+ * email that was supplied at signup.
863
+ *
864
+ * Errors thrown from this callback are swallowed — the user row is
865
+ * already created, so a failed backfill must not block sign-in. If you
866
+ * need observability, log inside the callback.
867
+ */
868
+ onNewUser?(userId: string, email: string | null | undefined): Promise<void>;
869
+ }
870
+ /** Function returned by `createEnsureUser`. */
871
+ type EnsureUserFn = (keycloakId: string, email?: string | null, name?: string | null) => Promise<string>;
872
+ /**
873
+ * Build the canonical `ensureUser(keycloakId, email?, name?)` helper for an
874
+ * app that mirrors Keycloak users into its own `users` table.
875
+ *
876
+ * See file-level JSDoc for the full pattern, invariants, and example wiring.
877
+ */
878
+ declare function createEnsureUser(config: EnsureUserConfig): EnsureUserFn;
879
+
880
+ export { type EnsureUserClaimDelta, type EnsureUserConfig, type EnsureUserFn, type EnsureUserRow, type FederatedLogoutConfig, type LazyRateLimitStoreOptions, RateLimitOptions, type RateLimitResult, RateLimitRule, RateLimitStore, type RedisRateLimitClient, type RedisRateLimitStoreOptions, type SecureAuditConfig, type SecureAuthMethod, type SecureHandlerFactoryConfig, type SecureLogger, type SecureRateLimitResult, type SecureRouteConfig, type SecureRouteContext, type SecureRouteHandler, type SecureSession, type SecureTimedAudit, addRateLimitHeaders, buildFederatedLogoutHandler, createEnsureUser, createLazyRateLimitStore, createRedisRateLimitStore, createSecureHandlerFactory, enforceRateLimit, errorResponse, extractBearerToken, getClientIp, isValidBearerToken, rateLimitResponse, safeValidate, verifyCronAuth, zodErrorResponse };
package/dist/auth.js CHANGED
@@ -59,6 +59,7 @@ __export(auth_exports, {
59
59
  createAuditActor: () => createAuditActor,
60
60
  createAuditLogger: () => createAuditLogger,
61
61
  createBetaClient: () => createBetaClient,
62
+ createEnsureUser: () => createEnsureUser,
62
63
  createFeatureFlags: () => createFeatureFlags,
63
64
  createLazyRateLimitStore: () => createLazyRateLimitStore,
64
65
  createMemoryRateLimitStore: () => createMemoryRateLimitStore,
@@ -1863,6 +1864,83 @@ function createSecureHandlerFactory(factoryConfig) {
1863
1864
  };
1864
1865
  }
1865
1866
 
1867
+ // src/auth/ensure-user.ts
1868
+ function createEnsureUser(config) {
1869
+ return async function ensureUser(keycloakId, email, name) {
1870
+ if (!keycloakId) {
1871
+ throw new Error(
1872
+ "createEnsureUser: keycloakId is required (got empty string / null / undefined)"
1873
+ );
1874
+ }
1875
+ const normalizedEmail = normalizeEmail(email);
1876
+ const normalizedName = normalizeName(name);
1877
+ const byKeycloak = await config.findByKeycloakId(keycloakId);
1878
+ if (byKeycloak) {
1879
+ if (config.onClaimRefresh) {
1880
+ const delta = computeClaimDelta(
1881
+ byKeycloak,
1882
+ normalizedEmail,
1883
+ normalizedName
1884
+ );
1885
+ if (delta) {
1886
+ await config.onClaimRefresh(byKeycloak.id, delta);
1887
+ }
1888
+ }
1889
+ return byKeycloak.id;
1890
+ }
1891
+ if (normalizedEmail) {
1892
+ const byEmail = await config.findByEmailLower(
1893
+ normalizedEmail.toLowerCase()
1894
+ );
1895
+ if (byEmail) {
1896
+ await config.rebindKeycloakId(byEmail.id, keycloakId, normalizedName);
1897
+ return byEmail.id;
1898
+ }
1899
+ }
1900
+ const inserted = await config.insertNewUser({
1901
+ keycloakId,
1902
+ email: normalizedEmail,
1903
+ name: normalizedName
1904
+ });
1905
+ if (config.onNewUser) {
1906
+ try {
1907
+ await config.onNewUser(inserted.id, normalizedEmail);
1908
+ } catch {
1909
+ }
1910
+ }
1911
+ return inserted.id;
1912
+ };
1913
+ }
1914
+ function normalizeEmail(email) {
1915
+ if (email === void 0 || email === null) return null;
1916
+ const trimmed = email.trim();
1917
+ return trimmed === "" ? null : trimmed;
1918
+ }
1919
+ function normalizeName(name) {
1920
+ if (name === void 0 || name === null) return void 0;
1921
+ const trimmed = name.trim();
1922
+ return trimmed === "" ? void 0 : trimmed;
1923
+ }
1924
+ function computeClaimDelta(current, newEmail, newName) {
1925
+ const delta = {};
1926
+ let changed = false;
1927
+ if (current.email !== void 0) {
1928
+ const currentLower = current.email == null ? null : current.email.toLowerCase();
1929
+ const newLower = newEmail == null ? null : newEmail.toLowerCase();
1930
+ if (currentLower !== newLower) {
1931
+ delta.email = newEmail;
1932
+ changed = true;
1933
+ }
1934
+ }
1935
+ if (newName !== void 0 && current.displayName !== void 0) {
1936
+ if (current.displayName !== newName) {
1937
+ delta.displayName = newName;
1938
+ changed = true;
1939
+ }
1940
+ }
1941
+ return changed ? delta : null;
1942
+ }
1943
+
1866
1944
  // src/env.ts
1867
1945
  function getRequiredEnv(key) {
1868
1946
  const value = process.env[key];
@@ -1994,6 +2072,7 @@ function getEnvSummary(keys) {
1994
2072
  createAuditActor,
1995
2073
  createAuditLogger,
1996
2074
  createBetaClient,
2075
+ createEnsureUser,
1997
2076
  createFeatureFlags,
1998
2077
  createLazyRateLimitStore,
1999
2078
  createMemoryRateLimitStore,