@jskit-ai/auth-provider-supabase-core 0.2.5 → 0.2.7

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.
@@ -4,37 +4,41 @@ import { once } from "node:events";
4
4
  import test from "node:test";
5
5
  import * as jose from "jose";
6
6
  import * as authProviderSupabase from "../src/server/lib/index.js";
7
- import { createAccountFlows } from "../src/server/lib/accountFlows.js";
8
- import { createPasswordSecurityFlows } from "../src/server/lib/passwordSecurityFlows.js";
7
+ import { createSupabaseAccountFlows } from "../src/server/lib/accountFlows.js";
8
+ import { resolveSupabaseConfig } from "../src/server/lib/config.js";
9
+ import { createSupabasePasswordFlows } from "../src/server/lib/passwordFlows.js";
10
+ import { PROVIDER_MODE_PROFILES } from "../src/server/lib/profileModes.js";
9
11
 
10
12
  test("auth.provider.supabase exports required symbols", () => {
11
- assert.equal(typeof authProviderSupabase.createService, "function");
13
+ assert.equal(typeof authProviderSupabase.createSupabaseAuthService, "function");
12
14
  });
13
15
 
14
- function createServiceFixture(overrides = {}) {
15
- return authProviderSupabase.createService({
16
- authProvider: {
17
- id: "supabase",
18
- supabaseUrl: "",
19
- supabasePublishableKey: ""
20
- },
21
- appPublicUrl: "http://localhost:5173",
22
- nodeEnv: "development",
23
- userProfileSyncService: {
24
- async findByIdentity() {
25
- return null;
26
- },
27
- async syncIdentityProfile(profile) {
28
- return {
29
- id: "1",
30
- email: String(profile?.email || "ada@example.com"),
31
- displayName: String(profile?.displayName || "Ada Example"),
32
- authProvider: String(profile?.authProvider || "supabase"),
33
- authProviderUserSid: String(profile?.authProviderUserSid || "supabase-user-1")
34
- };
35
- }
36
- },
37
- ...overrides
16
+ function supabaseConfig(env = {}) {
17
+ return resolveSupabaseConfig({
18
+ config: {},
19
+ env: { APP_PUBLIC_URL: "http://localhost:5173", NODE_ENV: "development", ...env }
20
+ });
21
+ }
22
+
23
+ const fixtureProjector = {
24
+ async findByIdentity() {
25
+ return null;
26
+ },
27
+ async syncIdentityProfile(profile) {
28
+ return {
29
+ id: "1",
30
+ email: String(profile?.email || "ada@example.com"),
31
+ displayName: String(profile?.displayName || "Ada Example"),
32
+ authProvider: String(profile?.authProvider || "supabase"),
33
+ authProviderUserSid: String(profile?.authProviderUserSid || "supabase-user-1")
34
+ };
35
+ }
36
+ };
37
+
38
+ function createServiceFixture({ env = {}, projector = fixtureProjector } = {}) {
39
+ return authProviderSupabase.createSupabaseAuthService({
40
+ config: supabaseConfig(env),
41
+ profiles: { ...PROVIDER_MODE_PROFILES, projector }
38
42
  });
39
43
  }
40
44
 
@@ -69,7 +73,7 @@ test("clearSessionCookies clears root and API path session cookie variants", ()
69
73
 
70
74
  test("clearSessionCookies preserves secure cookie clearing in production", () => {
71
75
  const authService = createServiceFixture({
72
- nodeEnv: "production"
76
+ env: { NODE_ENV: "production" }
73
77
  });
74
78
  const clearCalls = [];
75
79
  const reply = {
@@ -98,53 +102,55 @@ test("clearSessionCookies preserves secure cookie clearing in production", () =>
98
102
 
99
103
  test("supabase account flow updateDisplayName accepts the core command payload shape", async () => {
100
104
  let updatePayload = null;
101
- const flows = createAccountFlows({
102
- ensureConfigured() {},
103
- validationError(errors) {
104
- return new Error(JSON.stringify(errors));
105
- },
106
- getSupabaseClient() {
107
- return {
108
- auth: {
109
- async updateUser(payload) {
110
- updatePayload = payload;
111
- return {
112
- data: {
113
- user: {
114
- id: "supabase-user-1",
115
- email: "ada@example.com",
116
- user_metadata: {
117
- display_name: payload.data.display_name
118
- },
119
- app_metadata: {}
105
+ const flows = createSupabaseAccountFlows({
106
+ config: supabaseConfig(),
107
+ clients: {
108
+ ensureConfigured() {},
109
+ createSupabaseClient() {
110
+ return {
111
+ auth: {
112
+ async updateUser(payload) {
113
+ updatePayload = payload;
114
+ return {
115
+ data: {
116
+ user: {
117
+ id: "supabase-user-1",
118
+ email: "ada@example.com",
119
+ user_metadata: {
120
+ display_name: payload.data.display_name
121
+ },
122
+ app_metadata: {}
123
+ }
120
124
  }
121
- }
122
- };
125
+ };
126
+ }
123
127
  }
124
- }
125
- };
128
+ };
129
+ }
126
130
  },
127
- async setSessionFromRequestCookies() {
128
- return {
129
- data: {
130
- session: {
131
- access_token: "access"
131
+ sessions: {
132
+ async setSessionFromRequestCookies() {
133
+ return {
134
+ data: {
135
+ session: {
136
+ access_token: "access"
137
+ }
132
138
  }
133
- }
134
- };
139
+ };
140
+ }
135
141
  },
136
- async syncProfileFromSupabaseUser(user) {
137
- return {
138
- id: "profile-1",
139
- email: user.email,
140
- displayName: user.user_metadata.display_name,
141
- authProvider: "supabase",
142
- authProviderUserSid: user.id
143
- };
142
+ profileMirror: {
143
+ async syncProfileFromSupabaseUser(user) {
144
+ return {
145
+ id: "profile-1",
146
+ email: user.email,
147
+ displayName: user.user_metadata.display_name,
148
+ authProvider: "supabase",
149
+ authProviderUserSid: user.id
150
+ };
151
+ }
144
152
  },
145
- mapProfileUpdateError(error) {
146
- return error || new Error("profile update failed");
147
- }
153
+ securityStatus: {}
148
154
  });
149
155
 
150
156
  const result = await flows.updateDisplayName(
@@ -223,8 +229,8 @@ test("authentication without profile sync reads the existing profile", async (t)
223
229
  let existingProfile = profile;
224
230
  let syncCalls = 0;
225
231
  const authService = createServiceFixture({
226
- authProvider: { id: "supabase", supabaseUrl, supabasePublishableKey: "publishable-key" },
227
- userProfileSyncService: {
232
+ env: { AUTH_SUPABASE_URL: supabaseUrl, AUTH_SUPABASE_PUBLISHABLE_KEY: "publishable-key" },
233
+ projector: {
228
234
  async findByIdentity() {
229
235
  return existingProfile;
230
236
  },
@@ -260,7 +266,7 @@ test("a caller that cannot store a refreshed session is told to refresh instead
260
266
  await once(supabase, "listening");
261
267
  t.after(() => new Promise((resolve) => supabase.close(resolve)));
262
268
  const authService = createServiceFixture({
263
- authProvider: { id: "supabase", supabaseUrl: `http://127.0.0.1:${supabase.address().port}`, supabasePublishableKey: "publishable-key" }
269
+ env: { AUTH_SUPABASE_URL: `http://127.0.0.1:${supabase.address().port}`, AUTH_SUPABASE_PUBLISHABLE_KEY: "publishable-key" }
264
270
  });
265
271
  // The access cookie is gone once its token expires; the refresh cookie remains.
266
272
  const request = { cookies: { sb_refresh_token: "R1" } };
@@ -310,85 +316,93 @@ test("supabase password reset consumes the recovery session reader", async () =>
310
316
  let normalSessionReads = 0;
311
317
  let recoverySessionReads = 0;
312
318
  let signOutCalls = 0;
313
- const flows = createPasswordSecurityFlows({
314
- ensureConfigured() {},
315
- validationError(errors) {
316
- const error = new Error("Validation failed.");
317
- error.errors = errors;
318
- return error;
319
- },
320
- getSupabaseClient() {
321
- return {
322
- auth: {
323
- async updateUser(input) {
324
- assert.deepEqual(input, { password: "new password value" });
325
- return {
326
- data: {
327
- user: {
328
- id: "supabase-user-1",
329
- email: "reset@example.com"
330
- }
331
- },
332
- error: null
333
- };
334
- },
335
- async signOut(options) {
336
- signOutCalls += 1;
337
- assert.deepEqual(options, {
338
- scope: "local"
339
- });
340
- return {
341
- error: null
342
- };
319
+ const flows = createSupabasePasswordFlows({
320
+ config: supabaseConfig(),
321
+ clients: {
322
+ ensureConfigured() {},
323
+ createSupabaseClient() {
324
+ return {
325
+ auth: {
326
+ async updateUser(input) {
327
+ assert.deepEqual(input, { password: "new password value" });
328
+ return {
329
+ data: {
330
+ user: {
331
+ id: "supabase-user-1",
332
+ email: "reset@example.com"
333
+ }
334
+ },
335
+ error: null
336
+ };
337
+ },
338
+ async signOut(options) {
339
+ signOutCalls += 1;
340
+ assert.deepEqual(options, {
341
+ scope: "local"
342
+ });
343
+ return {
344
+ error: null
345
+ };
346
+ }
343
347
  }
344
- }
345
- };
346
- },
347
- async setSessionFromRequestCookies() {
348
- normalSessionReads += 1;
349
- throw new Error("normal session reader should not be used for reset.");
348
+ };
349
+ }
350
350
  },
351
- async setRecoverySessionFromRequestCookies(_request, { supabaseClient }) {
352
- recoverySessionReads += 1;
353
- assert.equal(typeof supabaseClient.auth.updateUser, "function");
354
- return {
355
- data: {
356
- user: {
357
- id: "supabase-user-1",
358
- email: "reset@example.com"
359
- },
360
- session: {
361
- access_token: "recovery-access",
362
- refresh_token: "recovery-refresh"
351
+ sessions: {
352
+ async setSessionFromRequestCookies() {
353
+ normalSessionReads += 1;
354
+ throw new Error("normal session reader should not be used for reset.");
355
+ },
356
+ async setRecoverySessionFromRequestCookies(_request, { supabaseClient }) {
357
+ recoverySessionReads += 1;
358
+ assert.equal(typeof supabaseClient.auth.updateUser, "function");
359
+ return {
360
+ data: {
361
+ user: {
362
+ id: "supabase-user-1",
363
+ email: "reset@example.com"
364
+ },
365
+ session: {
366
+ access_token: "recovery-access",
367
+ refresh_token: "recovery-refresh"
368
+ }
363
369
  }
364
- }
365
- };
366
- },
367
- async syncProfileFromSupabaseUser(user) {
368
- return {
369
- id: "1",
370
- email: user.email,
371
- displayName: "Reset Example",
372
- authProvider: "supabase",
373
- authProviderUserSid: user.id
374
- };
370
+ };
371
+ }
375
372
  },
376
- async resolvePasswordSignInPolicyForUserId(userId) {
377
- assert.equal(userId, "1");
378
- return {
379
- passwordSignInEnabled: true
380
- };
373
+ profileMirror: {
374
+ async syncProfileFromSupabaseUser(user) {
375
+ return {
376
+ id: "1",
377
+ email: user.email,
378
+ displayName: "Reset Example",
379
+ authProvider: "supabase",
380
+ authProviderUserSid: user.id
381
+ };
382
+ }
381
383
  },
382
- async setPasswordSetupRequiredForUserId(userId, required) {
383
- assert.equal(userId, "1");
384
- assert.equal(required, false);
384
+ securityStatus: {
385
+ async passwordSignInPolicyForUser(userId) {
386
+ assert.equal(userId, "1");
387
+ return {
388
+ passwordSignInEnabled: true
389
+ };
390
+ }
385
391
  },
386
- mapPasswordUpdateError(error) {
387
- return error instanceof Error ? error : new Error("Password update failed.");
392
+ profiles: {
393
+ userSettingsRepository: {
394
+ async updatePasswordSetupRequired(userId, required) {
395
+ assert.equal(userId, "1");
396
+ assert.equal(required, false);
397
+ }
398
+ }
388
399
  }
389
400
  });
390
401
 
391
402
  await flows.resetPassword(
403
+ {
404
+ password: "new password value"
405
+ },
392
406
  {
393
407
  cookies: {
394
408
  sb_access_token: "normal-access",
@@ -396,9 +410,6 @@ test("supabase password reset consumes the recovery session reader", async () =>
396
410
  sb_recovery_access_token: "recovery-access",
397
411
  sb_recovery_refresh_token: "recovery-refresh"
398
412
  }
399
- },
400
- {
401
- password: "new password value"
402
413
  }
403
414
  );
404
415
 
@@ -1,6 +1,5 @@
1
1
  import assert from "node:assert/strict";
2
2
  import test from "node:test";
3
- import { createValidationError } from "@jskit-ai/kernel/server/runtime/errors";
4
3
  import { catalogMessage, formatMessage, mergeCatalogs, messageKeyForCode } from "@jskit-ai/kernel/shared/i18n";
5
4
  import authCoreEnglish from "@jskit-ai/auth-core/locales/en.json" with { type: "json" };
6
5
  import supabaseEnglish from "../locales/en.json" with { type: "json" };
@@ -84,12 +83,11 @@ test("Supabase field errors carry codes whose English is the field message", asy
84
83
  });
85
84
 
86
85
  await assert.rejects(() => resolveDevAuthProfile({ email: "ghost@example.com" }, {
87
- userProfilesRepository: { findById: async () => null, findByEmail: async () => null },
88
- validationError: createValidationError
86
+ userProfilesRepository: { findById: async () => null, findByEmail: async () => null }
89
87
  }), (error) => assertCoded(error, "validation_failed").details.fieldErrorCodes.email.code === "auth.dev.userNotFound");
90
88
  });
91
89
 
92
- test("an invalid authenticated profile names its context through params", () => {
90
+ test("an invalid authenticated profile is an internal failure naming its context", () => {
93
91
  assert.throws(() => requireAuthenticatedProfile({}, { context: "authentication profile" }),
94
- (error) => Boolean(assertCoded(error, "auth.supabase.profile.invalid")));
92
+ (error) => error.message === "authentication profile is invalid." && error.code === undefined);
95
93
  });
@@ -1,6 +1,8 @@
1
1
  import assert from "node:assert/strict";
2
2
  import test from "node:test";
3
- import { createService } from "../src/server/lib/index.js";
3
+ import { resolveSupabaseConfig } from "../src/server/lib/config.js";
4
+ import { createSupabaseAuthService } from "../src/server/lib/index.js";
5
+ import { PROVIDER_MODE_PROFILES } from "../src/server/lib/profileModes.js";
4
6
 
5
7
  const DEV_AUTH_SECRET = "dev-bootstrap-secret";
6
8
 
@@ -77,22 +79,23 @@ function createDevAuthExchangeRequest(overrides = {}) {
77
79
  };
78
80
  }
79
81
 
80
- function createServiceFixture(overrides = {}) {
81
- return createService({
82
- authProvider: {
83
- id: "supabase",
84
- supabaseUrl: "",
85
- supabasePublishableKey: "",
86
- jwtAudience: "authenticated"
87
- },
88
- appPublicUrl: "http://localhost:5173",
89
- nodeEnv: "development",
90
- devAuthBypassEnabled: true,
91
- devAuthBypassSecret: DEV_AUTH_SECRET,
92
- userProfilesRepository: createUserProfilesRepository(),
93
- userProfileSyncService: createUserProfileSyncService(),
94
- profileProjectionEnabled: true,
95
- ...overrides
82
+ function createServiceFixture({ userProfilesRepository = createUserProfilesRepository() } = {}) {
83
+ return createSupabaseAuthService({
84
+ config: resolveSupabaseConfig({
85
+ config: { auth: { profileMode: "users" } },
86
+ env: {
87
+ APP_PUBLIC_URL: "http://localhost:5173",
88
+ NODE_ENV: "development",
89
+ AUTH_JWT_AUDIENCE: "authenticated",
90
+ AUTH_DEV_BYPASS_ENABLED: true,
91
+ AUTH_DEV_BYPASS_SECRET: DEV_AUTH_SECRET
92
+ }
93
+ }),
94
+ profiles: {
95
+ projector: createUserProfileSyncService(),
96
+ userProfilesRepository,
97
+ userSettingsRepository: PROVIDER_MODE_PROFILES.userSettingsRepository
98
+ }
96
99
  });
97
100
  }
98
101
 
@@ -100,9 +103,9 @@ test("dev auth bootstrap can issue and authenticate a local session without Supa
100
103
  const authService = createServiceFixture();
101
104
  const loginRequest = createDevAuthExchangeRequest();
102
105
 
103
- const loginResult = await authService.devLoginAs(loginRequest, {
106
+ const loginResult = await authService.devLoginAs({
104
107
  userId: "7"
105
- });
108
+ }, loginRequest);
106
109
 
107
110
  assert.equal(loginResult.actor.id, "7");
108
111
  assert.match(loginResult.session.access_token, /^jskit-dev\./);
@@ -125,9 +128,9 @@ test("dev auth bootstrap can issue and authenticate a local session without Supa
125
128
 
126
129
  test("dev auth bootstrap resolves security status without Supabase", async () => {
127
130
  const authService = createServiceFixture();
128
- const loginResult = await authService.devLoginAs(createDevAuthExchangeRequest(), {
131
+ const loginResult = await authService.devLoginAs({
129
132
  userId: "7"
130
- });
133
+ }, createDevAuthExchangeRequest());
131
134
 
132
135
  const securityStatus = await authService.getSecurityStatus(
133
136
  createLocalRequest({
@@ -167,9 +170,9 @@ test("dev auth security status rejects invalid dev sessions without recovery-lin
167
170
  test("dev auth bootstrap supports email lookup", async () => {
168
171
  const authService = createServiceFixture();
169
172
 
170
- const result = await authService.devLoginAs(createDevAuthExchangeRequest(), {
173
+ const result = await authService.devLoginAs({
171
174
  email: "ADA@EXAMPLE.COM"
172
- });
175
+ }, createDevAuthExchangeRequest());
173
176
 
174
177
  assert.equal(result.actor.id, "7");
175
178
  assert.equal(result.actor.email, "ada@example.com");
@@ -179,16 +182,16 @@ test("dev auth bootstrap rejects a missing or incorrect exchange secret", async
179
182
  const authService = createServiceFixture();
180
183
 
181
184
  await assert.rejects(
182
- () => authService.devLoginAs(createLocalRequest(), { userId: "7" }),
185
+ () => authService.devLoginAs({ userId: "7" }, createLocalRequest()),
183
186
  /not authorized/
184
187
  );
185
188
  await assert.rejects(
186
- () => authService.devLoginAs(createLocalRequest({
189
+ () => authService.devLoginAs({ userId: "7" }, createLocalRequest({
187
190
  headers: {
188
191
  host: "localhost:3000",
189
192
  "x-jskit-dev-auth-secret": "wrong-secret"
190
193
  }
191
- }), { userId: "7" }),
194
+ })),
192
195
  /not authorized/
193
196
  );
194
197
  });
@@ -209,9 +212,9 @@ test("dev auth bootstrap returns the canonical actor", async () => {
209
212
  userProfilesRepository: createUserProfilesRepository(rawProfile)
210
213
  });
211
214
 
212
- const loginResult = await authService.devLoginAs(createDevAuthExchangeRequest(), {
215
+ const loginResult = await authService.devLoginAs({
213
216
  userId: "7"
214
- });
217
+ }, createDevAuthExchangeRequest());
215
218
 
216
219
  assert.deepEqual(loginResult.actor, {
217
220
  id: "7",
@@ -228,19 +231,19 @@ test("dev auth bootstrap returns the canonical actor", async () => {
228
231
 
229
232
  test("dev auth bootstrap rejects non-local requests and clears leaked dev sessions", async () => {
230
233
  const authService = createServiceFixture();
231
- const issued = await authService.devLoginAs(createDevAuthExchangeRequest(), {
234
+ const issued = await authService.devLoginAs({
232
235
  userId: "7"
233
- });
236
+ }, createDevAuthExchangeRequest());
234
237
 
235
238
  await assert.rejects(
236
239
  () =>
237
240
  authService.devLoginAs(
241
+ { userId: "7" },
238
242
  createDevAuthExchangeRequest({
239
243
  ip: "203.0.113.10",
240
244
  hostname: "example.com",
241
245
  headers: { host: "example.com" }
242
- }),
243
- { userId: "7" }
246
+ })
244
247
  ),
245
248
  /localhost/
246
249
  );
@@ -265,6 +268,7 @@ test("dev auth bootstrap does not trust forwarded localhost headers", async () =
265
268
  await assert.rejects(
266
269
  () =>
267
270
  authService.devLoginAs(
271
+ { userId: "7" },
268
272
  createDevAuthExchangeRequest({
269
273
  ip: "203.0.113.10",
270
274
  socket: {
@@ -280,8 +284,7 @@ test("dev auth bootstrap does not trust forwarded localhost headers", async () =
280
284
  "x-forwarded-for": "127.0.0.1",
281
285
  "x-forwarded-host": "localhost"
282
286
  }
283
- }),
284
- { userId: "7" }
287
+ })
285
288
  ),
286
289
  /localhost/
287
290
  );
@@ -1,7 +1,7 @@
1
1
  import assert from "node:assert/strict";
2
2
  import test from "node:test";
3
- import { createService } from "../src/server/lib/index.js";
3
+ import { createSupabaseAuthService } from "../src/server/lib/index.js";
4
4
 
5
- test("auth provider supabase core validates required provider options", () => {
6
- assert.throws(() => createService({}), /authProvider is required/);
5
+ test("auth provider supabase core exports its auth service factory", () => {
6
+ assert.equal(typeof createSupabaseAuthService, "function");
7
7
  });
@@ -1,97 +0,0 @@
1
- import { normalizeLowerText, normalizeText } from "@jskit-ai/kernel/shared/support/normalize";
2
-
3
- const USER_PROFILE_EMAIL_CONFLICT_CODE = "USER_PROFILE_EMAIL_CONFLICT";
4
-
5
- function buildIdentityKey({ authProvider, authProviderUserSid } = {}) {
6
- return `${normalizeLowerText(authProvider)}:${normalizeText(authProviderUserSid)}`;
7
- }
8
-
9
- function normalizeIdentity(identityLike) {
10
- const source = identityLike && typeof identityLike === "object" ? identityLike : {};
11
- const authProvider = normalizeLowerText(source.authProvider || source.provider);
12
- const authProviderUserSid = normalizeText(source.authProviderUserSid || source.providerUserId);
13
- if (!authProvider || !authProviderUserSid) {
14
- throw new TypeError("Standalone profile sync requires authProvider and authProviderUserSid.");
15
- }
16
- return {
17
- authProvider,
18
- authProviderUserSid
19
- };
20
- }
21
-
22
- function normalizeProfile(profileLike) {
23
- const source = profileLike && typeof profileLike === "object" ? profileLike : {};
24
- const identity = normalizeIdentity(source);
25
- const email = normalizeLowerText(source.email);
26
- const displayName = normalizeText(source.displayName);
27
- if (!email || !displayName) {
28
- throw new TypeError("Standalone profile sync requires email and displayName.");
29
- }
30
- return {
31
- authProvider: identity.authProvider,
32
- authProviderUserSid: identity.authProviderUserSid,
33
- email,
34
- displayName
35
- };
36
- }
37
-
38
- function cloneProfile(profile) {
39
- return profile ? { ...profile } : null;
40
- }
41
-
42
- function createEmailConflictError() {
43
- const error = new Error("Email is already linked to a different profile.");
44
- error.code = USER_PROFILE_EMAIL_CONFLICT_CODE;
45
- return error;
46
- }
47
-
48
- function createStandaloneProfileSyncService() {
49
- const profilesByIdentityKey = new Map();
50
- const identityKeyByEmail = new Map();
51
- let nextId = 1n;
52
-
53
- async function findByIdentity(identityLike) {
54
- const identity = normalizeIdentity(identityLike);
55
- return cloneProfile(profilesByIdentityKey.get(buildIdentityKey(identity)) || null);
56
- }
57
-
58
- async function syncIdentityProfile(profileLike) {
59
- const normalizedProfile = normalizeProfile(profileLike);
60
- const identityKey = buildIdentityKey(normalizedProfile);
61
- const existing = profilesByIdentityKey.get(identityKey) || null;
62
-
63
- const existingOwnerIdentityKey = identityKeyByEmail.get(normalizedProfile.email);
64
- if (existingOwnerIdentityKey && existingOwnerIdentityKey !== identityKey) {
65
- throw createEmailConflictError();
66
- }
67
-
68
- const nextIdValue = existing?.id ? String(existing.id) : String(nextId);
69
- if (!existing?.id) {
70
- nextId += 1n;
71
- }
72
-
73
- const next = {
74
- id: nextIdValue,
75
- authProvider: normalizedProfile.authProvider,
76
- authProviderUserSid: normalizedProfile.authProviderUserSid,
77
- email: normalizedProfile.email,
78
- displayName: normalizedProfile.displayName
79
- };
80
-
81
- if (existing?.email && existing.email !== next.email) {
82
- identityKeyByEmail.delete(existing.email);
83
- }
84
-
85
- profilesByIdentityKey.set(identityKey, next);
86
- identityKeyByEmail.set(next.email, identityKey);
87
- return cloneProfile(next);
88
- }
89
-
90
- return Object.freeze({
91
- findByIdentity,
92
- syncIdentityProfile
93
- });
94
- }
95
-
96
- export { createStandaloneProfileSyncService };
97
- export { USER_PROFILE_EMAIL_CONFLICT_CODE };