@voltro/plugin-auth-social 0.86.0 → 0.87.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/callback.js CHANGED
@@ -2,112 +2,128 @@ import { SocialAuthError as e, SocialConfigError as t, SocialExchangeError as n,
2
2
  import { socialProvider as a } from "./providers.js";
3
3
  import { appleClientSecret as o, isApplePrivateRelayEmail as s, parseAppleUserPayload as c } from "./apple.js";
4
4
  import { fetchGithubIdentity as l } from "./github.js";
5
- import { timingSafeStringEqual as u } from "@voltro/protocol/session";
6
- import { JwtVerifyError as d, verifyJwt as f } from "@voltro/protocol/jwt";
5
+ import { fetchDiscordIdentity as u } from "./discord.js";
6
+ import { fetchEpicIdentity as d } from "./epic.js";
7
+ import { timingSafeStringEqual as f } from "@voltro/protocol/session";
8
+ import { JwtVerifyError as p, verifyJwt as m } from "@voltro/protocol/jwt";
7
9
  //#region src/callback.ts
8
- var p = (e) => e === !0 || e === "true", m = (e) => typeof e == "string" && e.length > 0 ? e : null, h = async (h) => {
9
- let g = a(h.provider, h.endpoints ?? {});
10
- if (!h.code) throw new e(400, "missing_code", "socialCompleteLogin: missing `code`");
11
- if (!h.expectedState) throw new i("socialCompleteLogin: no `expectedState` — the login was never started by this server, or the state cookie expired. Refusing to exchange the code.");
12
- if (!h.state || !u(h.state, h.expectedState)) throw new i("socialCompleteLogin: `state` does not match the value minted for this browser (possible login CSRF).");
13
- if (!h.codeVerifier) throw new e(400, "missing_verifier", "socialCompleteLogin: missing `codeVerifier` (PKCE)");
14
- if (g.kind === "oidc" && !h.expectedNonce) throw new t(`socialCompleteLogin: ${g.id} returns an ID token, so \`expectedNonce\` is required — without it a token captured from another login replays here.`);
15
- let _ = g.id === "apple" ? o(h.clientId, h.appleKey ?? (() => {
10
+ var h = (e) => e === !0 || e === "true", g = (e) => typeof e == "string" && e.length > 0 ? e : null, _ = async (_) => {
11
+ let v = a(_.provider, _.endpoints ?? {});
12
+ if (!_.code) throw new e(400, "missing_code", "socialCompleteLogin: missing `code`");
13
+ if (!_.expectedState) throw new i("socialCompleteLogin: no `expectedState` — the login was never started by this server, or the state cookie expired. Refusing to exchange the code.");
14
+ if (!_.state || !f(_.state, _.expectedState)) throw new i("socialCompleteLogin: `state` does not match the value minted for this browser (possible login CSRF).");
15
+ if (!_.codeVerifier) throw new e(400, "missing_verifier", "socialCompleteLogin: missing `codeVerifier` (PKCE)");
16
+ if (v.kind === "oidc" && !_.expectedNonce) throw new t(`socialCompleteLogin: ${v.id} returns an ID token, so \`expectedNonce\` is required — without it a token captured from another login replays here.`);
17
+ let y = v.id === "apple" ? o(_.clientId, _.appleKey ?? (() => {
16
18
  throw new t("apple: `appleKey` (teamId + keyId + .p8) is required");
17
- })(), h.now ?? Date.now) : h.clientSecret ?? (() => {
18
- throw new t(`${g.id}: \`clientSecret\` is required`);
19
- })(), v = h.fetchImpl ?? fetch, y = new URLSearchParams({
19
+ })(), _.now ?? Date.now) : _.clientSecret ?? (() => {
20
+ throw new t(`${v.id}: \`clientSecret\` is required`);
21
+ })(), b = _.fetchImpl ?? fetch, x = new URLSearchParams({
20
22
  grant_type: "authorization_code",
21
- client_id: h.clientId,
22
- client_secret: _,
23
- code: h.code,
24
- redirect_uri: h.redirectUri,
25
- code_verifier: h.codeVerifier
26
- }), b = await v(g.tokenUrl, {
27
- method: "POST",
28
- headers: {
29
- "content-type": "application/x-www-form-urlencoded",
30
- accept: "application/json"
31
- },
32
- body: y.toString()
23
+ client_id: _.clientId,
24
+ client_secret: y,
25
+ code: _.code,
26
+ redirect_uri: _.redirectUri,
27
+ code_verifier: _.codeVerifier
33
28
  });
34
- if (!b.ok) {
35
- let e = await b.text().catch(() => "");
36
- throw new n("exchange_failed", `${g.id}: token exchange failed (${b.status}): ${e.slice(0, 200)}`);
29
+ v.id === "epic" && (x.delete("client_id"), x.delete("client_secret"));
30
+ let S;
31
+ try {
32
+ S = await b(v.tokenUrl, {
33
+ method: "POST",
34
+ headers: {
35
+ "content-type": "application/x-www-form-urlencoded",
36
+ accept: "application/json",
37
+ ...v.id === "epic" ? { authorization: `Basic ${Buffer.from(`${encodeURIComponent(_.clientId)}:${encodeURIComponent(y)}`, "utf8").toString("base64")}` } : {}
38
+ },
39
+ body: x.toString(),
40
+ redirect: "error"
41
+ });
42
+ } catch {
43
+ throw new n("exchange_failed", `${v.id}: token exchange request failed`);
37
44
  }
38
- let x;
45
+ if (!S.ok) throw new n("exchange_failed", `${v.id}: token exchange failed (${S.status})`);
46
+ let C;
39
47
  try {
40
- x = await b.json();
48
+ let e = await S.json();
49
+ if (typeof e != "object" || !e || Array.isArray(e)) throw Error();
50
+ C = e;
41
51
  } catch {
42
- throw new n("malformed_token_response", `${g.id}: token endpoint returned a body that is not JSON`);
52
+ throw new n("malformed_token_response", `${v.id}: token endpoint returned a body that is not JSON`);
43
53
  }
44
- if (x.error) throw new n("exchange_failed", `${g.id}: token exchange refused: ${x.error}${x.error_description ? ` (${x.error_description})` : ""}`);
45
- if (g.kind === "oauth2") {
46
- if (!x.access_token) throw new n("malformed_token_response", `${g.id}: token response carries no access_token`);
47
- if (!g.apiBase) throw new t(`${g.id}: no apiBase configured`);
48
- let e = await l(x.access_token, {
49
- apiBase: g.apiBase,
50
- ...h.fetchImpl === void 0 ? {} : { fetchImpl: h.fetchImpl }
51
- });
54
+ if (C.error) throw new n("exchange_failed", `${v.id}: token exchange refused`);
55
+ if (v.kind === "oauth2") {
56
+ if (typeof C.access_token != "string" || !C.access_token) throw new n("malformed_token_response", `${v.id}: token response carries no access_token`);
57
+ if (!v.apiBase) throw new t(`${v.id}: no apiBase configured`);
58
+ let e = {
59
+ apiBase: v.apiBase,
60
+ ..._.fetchImpl === void 0 ? {} : { fetchImpl: _.fetchImpl }
61
+ }, r = v.id === "github" ? await l(C.access_token, e) : v.id === "discord" ? await u(C.access_token, e) : v.id === "epic" ? await d(C.access_token, {
62
+ ...e,
63
+ clientId: _.clientId,
64
+ ..._.now ? { now: _.now } : {}
65
+ }) : (() => {
66
+ throw new t(`${v.id}: no OAuth identity adapter`);
67
+ })();
52
68
  return {
53
- provider: g.id,
54
- providerAccountId: e.accountId,
55
- email: e.email,
56
- emailVerified: e.emailVerified,
69
+ provider: v.id,
70
+ providerAccountId: r.accountId,
71
+ email: r.email,
72
+ emailVerified: r.emailVerified,
57
73
  emailIsPrivateRelay: !1,
58
- name: e.name ?? e.login,
74
+ name: r.name ?? r.login,
59
75
  firstName: null,
60
76
  lastName: null,
61
- avatarUrl: e.avatarUrl,
77
+ avatarUrl: r.avatarUrl,
62
78
  nameIsFirstAuthorizationOnly: !1,
63
- raw: { ...e }
79
+ raw: { ...r }
64
80
  };
65
81
  }
66
- if (!x.id_token) throw new n("malformed_token_response", `${g.id}: token response carries no id_token`);
67
- if (!g.jwksUrl || !g.issuer) throw new t(`${g.id}: no JWKS/issuer configured`);
68
- let S;
82
+ if (typeof C.id_token != "string" || !C.id_token) throw new n("malformed_token_response", `${v.id}: token response carries no id_token`);
83
+ if (!v.jwksUrl || !v.issuer) throw new t(`${v.id}: no JWKS/issuer configured`);
84
+ let w;
69
85
  try {
70
- S = await f(x.id_token, g.jwksUrl, {
71
- issuer: g.issuer,
72
- audience: h.clientId
86
+ w = await m(C.id_token, v.jwksUrl, {
87
+ issuer: v.issuer,
88
+ audience: _.clientId
73
89
  });
74
90
  } catch (e) {
75
- throw e instanceof d ? new r("id_token_invalid", `${g.id}: id_token ${e.code}: ${e.message}`) : new r("id_token_invalid", `${g.id}: id_token verification failed: ${e.message}`);
91
+ throw e instanceof p ? new r("id_token_invalid", `${v.id}: id_token verification refused (${e.code})`) : new r("id_token_invalid", `${v.id}: id_token verification failed`);
76
92
  }
77
- let C = m(S.nonce);
78
- if (!C || !u(C, h.expectedNonce ?? "")) throw new r("nonce_mismatch", `${g.id}: id_token nonce does not match the value minted for this login (possible replay).`);
79
- let w = m(S.sub);
80
- if (!w) throw new r("id_token_invalid", `${g.id}: id_token has no sub claim`);
81
- let T = m(S.email), E = p(S.email_verified);
82
- if (g.id === "apple") {
83
- let e = c(h.appleUserPayload), t = p(S.is_private_email) || s(T), n = e?.firstName ?? null, r = e?.lastName ?? null, i = [n, r].filter((e) => e !== null).join(" ");
93
+ let T = g(w.nonce);
94
+ if (!T || !f(T, _.expectedNonce ?? "")) throw new r("nonce_mismatch", `${v.id}: id_token nonce does not match the value minted for this login (possible replay).`);
95
+ let E = g(w.sub);
96
+ if (!E) throw new r("id_token_invalid", `${v.id}: id_token has no sub claim`);
97
+ let D = g(w.email), O = D !== null && v.assertsEmailVerification && h(w.email_verified);
98
+ if (v.id === "apple") {
99
+ let e = c(_.appleUserPayload), t = h(w.is_private_email) || s(D), n = e?.firstName ?? null, r = e?.lastName ?? null, i = [n, r].filter((e) => e !== null).join(" ");
84
100
  return {
85
101
  provider: "apple",
86
- providerAccountId: w,
87
- email: T ?? e?.email ?? null,
88
- emailVerified: E,
102
+ providerAccountId: E,
103
+ email: D ?? e?.email ?? null,
104
+ emailVerified: O,
89
105
  emailIsPrivateRelay: t,
90
106
  name: i.length > 0 ? i : null,
91
107
  firstName: n,
92
108
  lastName: r,
93
109
  avatarUrl: null,
94
110
  nameIsFirstAuthorizationOnly: e !== null,
95
- raw: S
111
+ raw: w
96
112
  };
97
113
  }
98
114
  return {
99
- provider: g.id,
100
- providerAccountId: w,
101
- email: T,
102
- emailVerified: E,
115
+ provider: v.id,
116
+ providerAccountId: E,
117
+ email: D,
118
+ emailVerified: O,
103
119
  emailIsPrivateRelay: !1,
104
- name: m(S.name),
105
- firstName: m(S.given_name),
106
- lastName: m(S.family_name),
107
- avatarUrl: m(S.picture),
120
+ name: g(w.name) ?? (v.id === "twitch" ? g(w.preferred_username) : null),
121
+ firstName: g(w.given_name),
122
+ lastName: g(w.family_name),
123
+ avatarUrl: g(w.picture),
108
124
  nameIsFirstAuthorizationOnly: !1,
109
- raw: S
125
+ raw: w
110
126
  };
111
127
  };
112
128
  //#endregion
113
- export { h as socialCompleteLogin };
129
+ export { _ as socialCompleteLogin };
@@ -0,0 +1,38 @@
1
+ import { SocialExchangeError as e } from "./errors.js";
2
+ //#region src/discord.ts
3
+ var t = async (t, n) => {
4
+ if (!t) throw new e("malformed_token_response", "discord: missing access token");
5
+ let r;
6
+ try {
7
+ r = await (n.fetchImpl ?? fetch)(`${n.apiBase}/users/@me`, {
8
+ headers: {
9
+ authorization: `Bearer ${t}`,
10
+ accept: "application/json"
11
+ },
12
+ redirect: "error"
13
+ });
14
+ } catch {
15
+ throw new e("exchange_failed", "discord: identity request failed");
16
+ }
17
+ if (!r.ok) throw new e("exchange_failed", `discord: identity request refused (${r.status})`);
18
+ let i;
19
+ try {
20
+ i = await r.json();
21
+ } catch {
22
+ throw new e("malformed_token_response", "discord: identity response is not JSON");
23
+ }
24
+ if (typeof i != "object" || !i || Array.isArray(i)) throw new e("malformed_token_response", "discord: malformed identity response");
25
+ let a = i;
26
+ if (typeof a.id != "string" || !/^[0-9]{1,20}$/.test(a.id) || typeof a.username != "string" || a.username.length === 0) throw new e("malformed_token_response", "discord: identity response has no stable id/username");
27
+ let o = typeof a.email == "string" && a.email.length > 0 ? a.email : null;
28
+ return {
29
+ accountId: a.id,
30
+ login: a.username,
31
+ name: typeof a.global_name == "string" && a.global_name.length > 0 ? a.global_name : null,
32
+ avatarUrl: null,
33
+ email: o,
34
+ emailVerified: o !== null && a.verified === !0
35
+ };
36
+ };
37
+ //#endregion
38
+ export { t as fetchDiscordIdentity };
package/dist/epic.js ADDED
@@ -0,0 +1,39 @@
1
+ import { SocialExchangeError as e } from "./errors.js";
2
+ //#region src/epic.ts
3
+ var t = async (t, n) => {
4
+ if (!t || !n.clientId) throw new e("malformed_token_response", "epic: missing token/client binding");
5
+ let r;
6
+ try {
7
+ r = await (n.fetchImpl ?? fetch)(`${n.apiBase}/tokenInfo`, {
8
+ method: "POST",
9
+ headers: {
10
+ "content-type": "application/x-www-form-urlencoded",
11
+ accept: "application/json"
12
+ },
13
+ body: new URLSearchParams({ token: t }).toString(),
14
+ redirect: "error"
15
+ });
16
+ } catch {
17
+ throw new e("exchange_failed", "epic: token verification request failed");
18
+ }
19
+ if (!r.ok) throw new e("exchange_failed", `epic: token verification refused (${r.status})`);
20
+ let i;
21
+ try {
22
+ i = await r.json();
23
+ } catch {
24
+ throw new e("malformed_token_response", "epic: token verification response is not JSON");
25
+ }
26
+ if (typeof i != "object" || !i || Array.isArray(i)) throw new e("malformed_token_response", "epic: malformed token verification response");
27
+ let a = i, o = (n.now ?? Date.now)(), s = typeof a.expires_at == "string" ? Date.parse(a.expires_at) : NaN;
28
+ if (a.active !== !0 || a.client_id !== n.clientId || typeof a.account_id != "string" || !/^[a-f0-9]{32}$/.test(a.account_id) || typeof a.token_type != "string" || a.token_type.toLowerCase() !== "bearer" || !Number.isFinite(o) || !Number.isFinite(s) || s <= o) throw new e("exchange_failed", "epic: inactive, expired or unbound account token");
29
+ return {
30
+ accountId: a.account_id,
31
+ login: a.account_id,
32
+ name: null,
33
+ avatarUrl: null,
34
+ email: null,
35
+ emailVerified: !1
36
+ };
37
+ };
38
+ //#endregion
39
+ export { t as fetchEpicIdentity };
package/dist/errors.js CHANGED
@@ -19,12 +19,16 @@ var e = class extends Error {
19
19
  }
20
20
  }, i = class extends e {
21
21
  constructor(e) {
22
- super(500, "config", e), this.name = "SocialConfigError";
22
+ super(401, "ticket_rejected", e), this.name = "PlatformTicketError";
23
23
  }
24
24
  }, a = class extends e {
25
+ constructor(e) {
26
+ super(500, "config", e), this.name = "SocialConfigError";
27
+ }
28
+ }, o = class extends e {
25
29
  constructor(e, t, n = 409) {
26
30
  super(n, e, t), this.name = "SocialAccountLinkError";
27
31
  }
28
32
  };
29
33
  //#endregion
30
- export { a as SocialAccountLinkError, e as SocialAuthError, i as SocialConfigError, n as SocialExchangeError, r as SocialIdTokenError, t as SocialStateMismatchError };
34
+ export { i as PlatformTicketError, o as SocialAccountLinkError, e as SocialAuthError, a as SocialConfigError, n as SocialExchangeError, r as SocialIdTokenError, t as SocialStateMismatchError };
package/dist/github.js CHANGED
@@ -6,14 +6,17 @@ var t = (e) => ({
6
6
  "x-github-api-version": "2022-11-28",
7
7
  "user-agent": "voltro-plugin-auth-social"
8
8
  }), n = async (n, r) => {
9
- let i = r.fetchImpl ?? fetch, a = await i(`${r.apiBase}/user`, { headers: t(n) });
10
- if (!a.ok) {
11
- let t = await a.text().catch(() => "");
12
- throw new e("exchange_failed", `github: GET /user failed (${a.status}): ${t.slice(0, 200)}`);
13
- }
9
+ let i = r.fetchImpl ?? fetch, a = await i(`${r.apiBase}/user`, {
10
+ headers: t(n),
11
+ redirect: "error"
12
+ });
13
+ if (!a.ok) throw new e("exchange_failed", `github: GET /user failed (${a.status})`);
14
14
  let o = await a.json();
15
15
  if (o.id === void 0 || o.id === null || !o.login) throw new e("malformed_token_response", "github: GET /user response is missing id/login");
16
- let s = null, c = !1, l = await i(`${r.apiBase}/user/emails`, { headers: t(n) });
16
+ let s = null, c = !1, l = await i(`${r.apiBase}/user/emails`, {
17
+ headers: t(n),
18
+ redirect: "error"
19
+ });
17
20
  if (l.ok) {
18
21
  let e = await l.json();
19
22
  if (Array.isArray(e)) {
@@ -0,0 +1,61 @@
1
+ import { SocialConfigError as e } from "./errors.js";
2
+ import { isSocialProviderId as t } from "./providers.js";
3
+ import { signAuthClaims as n, verifyAuthClaims as r } from "@voltro/plugin-auth";
4
+ //#region src/guestHandoff.ts
5
+ var i = (t, r) => {
6
+ let i = t.profile, a = n({
7
+ exp: t.exp,
8
+ audience: t.audience,
9
+ guest: t.guest,
10
+ profile: {
11
+ provider: i.provider,
12
+ providerAccountId: i.providerAccountId,
13
+ email: i.email,
14
+ emailVerified: i.emailVerified,
15
+ emailIsPrivateRelay: i.emailIsPrivateRelay,
16
+ firstName: i.firstName,
17
+ lastName: i.lastName,
18
+ nameIsFirstAuthorizationOnly: i.nameIsFirstAuthorizationOnly
19
+ }
20
+ }, r.current.secret, "social-upgrade");
21
+ if (a.length > 3400) throw new e("Guest upgrade handoff exceeds its cookie budget");
22
+ return a;
23
+ }, a = (e) => typeof e == "object" && e && !Array.isArray(e) ? e : null, o = (e) => {
24
+ let t = a(e), n = a(t?.metadata);
25
+ return t?.type !== "user" || t.kind !== "guest" || typeof t.id != "string" || !/^guest_[A-Za-z0-9_-]+$/.test(t.id) || typeof t.tenantId != "string" || !t.tenantId.trim() || typeof n?.sessionId != "string" || !n.sessionId || typeof n.guestDeviceId != "string" || !/^gdev_[A-Za-z0-9_-]+$/.test(n.guestDeviceId) || typeof n.guestDeviceGeneration != "number" || !Number.isSafeInteger(n.guestDeviceGeneration) || n.guestDeviceGeneration < 0 ? null : {
26
+ type: "user",
27
+ kind: "guest",
28
+ id: t.id,
29
+ tenantId: t.tenantId,
30
+ metadata: {
31
+ sessionId: n.sessionId,
32
+ guestDeviceId: n.guestDeviceId,
33
+ guestDeviceGeneration: n.guestDeviceGeneration
34
+ }
35
+ };
36
+ }, s = (e, n, i) => {
37
+ if (!e || e.length > 3400) return null;
38
+ let s = [n.current, n.previous].filter((e) => e !== void 0).map((t) => r(e, t.secret, "social-upgrade")).find((e) => e !== null);
39
+ if (!s || s.audience !== i || typeof s.exp != "number") return null;
40
+ let c = o(s.guest), l = a(s.profile), u = (e) => e === null || typeof e == "string";
41
+ return !c || !l || typeof l.provider != "string" || !t(l.provider) || typeof l.providerAccountId != "string" || !l.providerAccountId || !u(l.email) || !u(l.firstName) || !u(l.lastName) || typeof l.emailVerified != "boolean" || typeof l.emailIsPrivateRelay != "boolean" || typeof l.nameIsFirstAuthorizationOnly != "boolean" ? null : {
42
+ guest: c,
43
+ exp: s.exp,
44
+ audience: i,
45
+ profile: {
46
+ provider: l.provider,
47
+ providerAccountId: l.providerAccountId,
48
+ email: l.email,
49
+ emailVerified: l.emailVerified,
50
+ emailIsPrivateRelay: l.emailIsPrivateRelay,
51
+ firstName: l.firstName,
52
+ lastName: l.lastName,
53
+ nameIsFirstAuthorizationOnly: l.nameIsFirstAuthorizationOnly,
54
+ name: null,
55
+ avatarUrl: null,
56
+ raw: {}
57
+ }
58
+ };
59
+ };
60
+ //#endregion
61
+ export { s as decodeGuestUpgradeHandoff, i as encodeGuestUpgradeHandoff, o as guestIdentityOf };
@@ -0,0 +1,97 @@
1
+ import { SOCIAL_IDENTITY_TABLE as e, dataStoreSocialIdentityStore as t } from "./identityStore.js";
2
+ import { Effect as n } from "effect";
3
+ import { and as r, eq as i } from "@voltro/database";
4
+ import { GuestAuthError as a, dataStoreGuestAuth as o, dataStoreSessionRegistry as s, issueUserSession as c, runSubjectGuards as l } from "@voltro/plugin-auth";
5
+ //#region src/guestUpgrade.ts
6
+ var u = (e, t, n) => ({
7
+ table: e,
8
+ predicate: i(t, n),
9
+ order: [],
10
+ take: void 0,
11
+ skip: void 0,
12
+ projection: void 0
13
+ }), d = (d) => {
14
+ if (d.config.defaultTenantId !== d.guest.tenantId || d.config.ensureActor !== void 0 && d.configForTransaction === void 0) return n.succeed({
15
+ kind: "refused",
16
+ status: 500,
17
+ code: "config",
18
+ message: "Guest upgrade requires a matching tenant and transaction-bound actor hooks."
19
+ });
20
+ let f = d.profile, p = f.email === null || f.email.length === 0 ? null : f.email;
21
+ return (d.service ?? o(d.store, d.guest)).upgrade(d.credential, async (o) => {
22
+ let m = o.store, h = t(m);
23
+ if (await n.runPromise(h.findByProviderAccount(f.provider, f.providerAccountId)) !== null || p !== null && (await m.query(u("users", "email", p))).length !== 0) throw new a({ code: "upgrade_conflict" });
24
+ let g = {
25
+ id: o.subjectId,
26
+ tenantId: o.tenantId,
27
+ email: p,
28
+ passwordHash: null,
29
+ createdAt: o.createdAt,
30
+ mfaSecret: null,
31
+ mfaEnrolledAt: null,
32
+ emailVerifiedAt: p !== null && f.emailVerified ? /* @__PURE__ */ new Date() : null
33
+ }, _ = d.configForTransaction?.(m) ?? d.config;
34
+ if (_.defaultTenantId !== o.tenantId || !(await n.runPromise(l(_.subjectGuards ?? [], g))).ok) throw new a({ code: "credential_rejected" });
35
+ if (await m.insert("users", {
36
+ ...g,
37
+ updatedAt: /* @__PURE__ */ new Date()
38
+ }), !await n.runPromise(h.insert({
39
+ userId: g.id,
40
+ provider: f.provider,
41
+ providerAccountId: f.providerAccountId,
42
+ email: p,
43
+ emailVerified: p !== null && f.emailVerified
44
+ }).pipe(n.as(!0), n.catchTag("SocialIdentityConflict", () => n.succeed(!1))))) throw new a({ code: "upgrade_conflict" });
45
+ let v = {
46
+ ...d.users,
47
+ ...s(m),
48
+ listMemberships: (e) => n.promise(async () => (await m.query({
49
+ ...u("memberships", "userId", e),
50
+ predicate: r(i("userId", e), i("tenantId", o.tenantId))
51
+ })).map((t) => {
52
+ if (t.userId !== e || t.tenantId !== o.tenantId || typeof t.role != "string") throw new a({ code: "store_unavailable" });
53
+ let n = t.joinedAt instanceof Date ? t.joinedAt : new Date(String(t.joinedAt));
54
+ if (!Number.isFinite(n.getTime())) throw new a({ code: "store_unavailable" });
55
+ return {
56
+ userId: e,
57
+ tenantId: o.tenantId,
58
+ role: t.role,
59
+ joinedAt: n
60
+ };
61
+ }))
62
+ }, y = await n.runPromise(c(g, v, _, {
63
+ clearLoginFailures: !1,
64
+ ipAddress: d.ipAddress ?? null,
65
+ userAgent: d.userAgent ?? null
66
+ })), b = y.subject.type === "user" ? y.subject.metadata?.sessionId : null;
67
+ if (typeof b != "string" || (await m.query(u("sessions", "id", b))).length !== 1) throw new a({ code: "store_unavailable" });
68
+ let x = (await m.query({
69
+ ...u(e, "provider", f.provider),
70
+ predicate: r(i("provider", f.provider), i("providerAccountId", f.providerAccountId))
71
+ }))[0];
72
+ if (!x || x.provider !== f.provider || x.providerAccountId !== f.providerAccountId || x.userId !== g.id) throw new a({ code: "upgrade_conflict" });
73
+ return {
74
+ kind: "ok",
75
+ userId: g.id,
76
+ subject: y.subject,
77
+ setCookie: y.setCookie,
78
+ session: {
79
+ value: y.value,
80
+ expiresAt: y.expiresAt
81
+ },
82
+ created: !0,
83
+ linked: !0,
84
+ oneTimeName: f.nameIsFirstAuthorizationOnly ? {
85
+ firstName: f.firstName,
86
+ lastName: f.lastName
87
+ } : null
88
+ };
89
+ }).pipe(n.catch((e) => n.succeed({
90
+ kind: "refused",
91
+ status: e.code === "upgrade_conflict" ? 409 : e.code === "credential_rejected" ? 403 : 503,
92
+ code: e.code === "upgrade_conflict" ? "account_merge_required" : e.code,
93
+ message: e.code === "upgrade_conflict" ? "The provider or email belongs to an existing account. Confirm both accounts before merging." : e.code === "credential_rejected" ? "Guest upgrade was refused." : "Guest upgrade storage is unavailable."
94
+ })));
95
+ };
96
+ //#endregion
97
+ export { d as completeGuestSocialUpgrade };