@voltro/plugin-auth-social 0.85.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/apple.js ADDED
@@ -0,0 +1,64 @@
1
+ import { SocialConfigError as e } from "./errors.js";
2
+ import { createPrivateKey as t, sign as n } from "node:crypto";
3
+ //#region src/apple.ts
4
+ var r = 15777e3, i = 900, a = "https://appleid.apple.com", o = (e) => (typeof e == "string" ? Buffer.from(e, "utf8") : e).toString("base64url"), s = /* @__PURE__ */ new Map(), c = (n) => {
5
+ let r = s.get(n);
6
+ if (r) return r;
7
+ let i;
8
+ try {
9
+ i = t({ key: n });
10
+ } catch (t) {
11
+ throw new e(`apple: could not parse the .p8 private key — ${t.message}`);
12
+ }
13
+ if (i.asymmetricKeyType !== "ec") throw new e(`apple: the .p8 key must be an EC (P-256) key, got '${String(i.asymmetricKeyType)}'`);
14
+ let a = i.asymmetricKeyDetails?.namedCurve;
15
+ if (a !== void 0 && a !== "prime256v1") throw new e(`apple: ES256 requires the P-256 curve (prime256v1), got '${a}'`);
16
+ return s.set(n, i), i;
17
+ }, l = /* @__PURE__ */ new Map(), u = () => {
18
+ s.clear(), l.clear();
19
+ }, d = (t, i, s = Date.now) => {
20
+ if (!t) throw new e("apple: `clientId` (Services ID) is required");
21
+ if (!i.teamId) throw new e("apple: `teamId` is required");
22
+ if (!i.keyId) throw new e("apple: `keyId` is required");
23
+ if (!i.privateKey) throw new e("apple: `privateKey` (.p8 contents) is required");
24
+ let u = i.ttlSeconds ?? 900;
25
+ if (!Number.isFinite(u) || u <= 0) throw new e("apple: `ttlSeconds` must be a positive number");
26
+ if (u > 15777e3) throw new e(`apple: \`ttlSeconds\` may not exceed ${r} (six months, Apple's cap) — got ${u}`);
27
+ let d = s(), f = `${i.teamId}\u0000${i.keyId}\u0000${t}\u0000${u}`, p = l.get(f);
28
+ if (p && p.expiresAtMs - d > 6e4) return p.secret;
29
+ let m = Math.floor(d / 1e3), h = m + u, g = `${o(JSON.stringify({
30
+ alg: "ES256",
31
+ kid: i.keyId,
32
+ typ: "JWT"
33
+ }))}.${o(JSON.stringify({
34
+ iss: i.teamId,
35
+ iat: m,
36
+ exp: h,
37
+ aud: a,
38
+ sub: t
39
+ }))}`, _ = `${g}.${n("sha256", Buffer.from(g, "ascii"), {
40
+ key: c(i.privateKey),
41
+ dsaEncoding: "ieee-p1363"
42
+ }).toString("base64url")}`;
43
+ return l.set(f, {
44
+ secret: _,
45
+ expiresAtMs: h * 1e3
46
+ }), _;
47
+ }, f = (e) => {
48
+ if (!e) return null;
49
+ let t;
50
+ try {
51
+ t = JSON.parse(e);
52
+ } catch {
53
+ return null;
54
+ }
55
+ if (typeof t != "object" || !t) return null;
56
+ let n = t, r = typeof n.name == "object" && n.name !== null ? n.name : {}, i = (e) => typeof e == "string" && e.length > 0 ? e : null, a = {
57
+ firstName: i(r.firstName),
58
+ lastName: i(r.lastName),
59
+ email: i(n.email)
60
+ };
61
+ return a.firstName === null && a.lastName === null && a.email === null ? null : a;
62
+ }, p = (e) => e !== null && e.toLowerCase().endsWith("@privaterelay.appleid.com");
63
+ //#endregion
64
+ export { i as APPLE_CLIENT_SECRET_DEFAULT_TTL_S, r as APPLE_CLIENT_SECRET_MAX_TTL_S, u as _resetAppleSecretCache, d as appleClientSecret, p as isApplePrivateRelayEmail, f as parseAppleUserPayload };
@@ -0,0 +1,129 @@
1
+ import { SocialAuthError as e, SocialConfigError as t, SocialExchangeError as n, SocialIdTokenError as r, SocialStateMismatchError as i } from "./errors.js";
2
+ import { socialProvider as a } from "./providers.js";
3
+ import { appleClientSecret as o, isApplePrivateRelayEmail as s, parseAppleUserPayload as c } from "./apple.js";
4
+ import { fetchGithubIdentity as l } from "./github.js";
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";
9
+ //#region src/callback.ts
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 ?? (() => {
18
+ throw new t("apple: `appleKey` (teamId + keyId + .p8) is required");
19
+ })(), _.now ?? Date.now) : _.clientSecret ?? (() => {
20
+ throw new t(`${v.id}: \`clientSecret\` is required`);
21
+ })(), b = _.fetchImpl ?? fetch, x = new URLSearchParams({
22
+ grant_type: "authorization_code",
23
+ client_id: _.clientId,
24
+ client_secret: y,
25
+ code: _.code,
26
+ redirect_uri: _.redirectUri,
27
+ code_verifier: _.codeVerifier
28
+ });
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`);
44
+ }
45
+ if (!S.ok) throw new n("exchange_failed", `${v.id}: token exchange failed (${S.status})`);
46
+ let C;
47
+ try {
48
+ let e = await S.json();
49
+ if (typeof e != "object" || !e || Array.isArray(e)) throw Error();
50
+ C = e;
51
+ } catch {
52
+ throw new n("malformed_token_response", `${v.id}: token endpoint returned a body that is not JSON`);
53
+ }
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
+ })();
68
+ return {
69
+ provider: v.id,
70
+ providerAccountId: r.accountId,
71
+ email: r.email,
72
+ emailVerified: r.emailVerified,
73
+ emailIsPrivateRelay: !1,
74
+ name: r.name ?? r.login,
75
+ firstName: null,
76
+ lastName: null,
77
+ avatarUrl: r.avatarUrl,
78
+ nameIsFirstAuthorizationOnly: !1,
79
+ raw: { ...r }
80
+ };
81
+ }
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;
85
+ try {
86
+ w = await m(C.id_token, v.jwksUrl, {
87
+ issuer: v.issuer,
88
+ audience: _.clientId
89
+ });
90
+ } catch (e) {
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`);
92
+ }
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(" ");
100
+ return {
101
+ provider: "apple",
102
+ providerAccountId: E,
103
+ email: D ?? e?.email ?? null,
104
+ emailVerified: O,
105
+ emailIsPrivateRelay: t,
106
+ name: i.length > 0 ? i : null,
107
+ firstName: n,
108
+ lastName: r,
109
+ avatarUrl: null,
110
+ nameIsFirstAuthorizationOnly: e !== null,
111
+ raw: w
112
+ };
113
+ }
114
+ return {
115
+ provider: v.id,
116
+ providerAccountId: E,
117
+ email: D,
118
+ emailVerified: O,
119
+ emailIsPrivateRelay: !1,
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),
124
+ nameIsFirstAuthorizationOnly: !1,
125
+ raw: w
126
+ };
127
+ };
128
+ //#endregion
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 ADDED
@@ -0,0 +1,34 @@
1
+ //#region src/errors.ts
2
+ var e = class extends Error {
3
+ status;
4
+ code;
5
+ constructor(e, t, n) {
6
+ super(n), this.status = e, this.code = t, this.name = "SocialAuthError";
7
+ }
8
+ }, t = class extends e {
9
+ constructor(e) {
10
+ super(400, "state_mismatch", e), this.name = "SocialStateMismatchError";
11
+ }
12
+ }, n = class extends e {
13
+ constructor(e, t, n = 502) {
14
+ super(n, e, t), this.name = "SocialExchangeError";
15
+ }
16
+ }, r = class extends e {
17
+ constructor(e, t) {
18
+ super(401, e, t), this.name = "SocialIdTokenError";
19
+ }
20
+ }, i = class extends e {
21
+ constructor(e) {
22
+ super(401, "ticket_rejected", e), this.name = "PlatformTicketError";
23
+ }
24
+ }, a = class extends e {
25
+ constructor(e) {
26
+ super(500, "config", e), this.name = "SocialConfigError";
27
+ }
28
+ }, o = class extends e {
29
+ constructor(e, t, n = 409) {
30
+ super(n, e, t), this.name = "SocialAccountLinkError";
31
+ }
32
+ };
33
+ //#endregion
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 ADDED
@@ -0,0 +1,37 @@
1
+ import { SocialExchangeError as e } from "./errors.js";
2
+ //#region src/github.ts
3
+ var t = (e) => ({
4
+ authorization: `Bearer ${e}`,
5
+ accept: "application/vnd.github+json",
6
+ "x-github-api-version": "2022-11-28",
7
+ "user-agent": "voltro-plugin-auth-social"
8
+ }), n = async (n, r) => {
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
+ let o = await a.json();
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`, {
17
+ headers: t(n),
18
+ redirect: "error"
19
+ });
20
+ if (l.ok) {
21
+ let e = await l.json();
22
+ if (Array.isArray(e)) {
23
+ let t = e.find((e) => e.primary === !0 && typeof e.email == "string");
24
+ t?.email && (s = t.email, c = t.verified === !0);
25
+ }
26
+ }
27
+ return {
28
+ accountId: String(o.id),
29
+ login: o.login,
30
+ name: typeof o.name == "string" && o.name.length > 0 ? o.name : null,
31
+ avatarUrl: typeof o.avatar_url == "string" && o.avatar_url.length > 0 ? o.avatar_url : null,
32
+ email: s,
33
+ emailVerified: c
34
+ };
35
+ };
36
+ //#endregion
37
+ export { n as fetchGithubIdentity };
@@ -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 };
@@ -0,0 +1,124 @@
1
+ import { Data as e, Effect as t } from "effect";
2
+ import { and as n, boolean as r, classifyConstraintViolation as i, eq as a, extractDbCause as o, generateId as s, id as c, table as l, text as u, timestamp as d } from "@voltro/database";
3
+ //#region src/identityStore.ts
4
+ var f = "_voltro_oauth_identities", p = l(f, {
5
+ id: c({ prefix: "oauthid" }),
6
+ userId: u(),
7
+ provider: u(),
8
+ providerAccountId: u(),
9
+ email: u().nullable(),
10
+ emailVerified: r().default(!1),
11
+ createdAt: d().default("now"),
12
+ lastLoginAt: d().nullable()
13
+ }).unique("byOauthProviderAccount", ["provider", "providerAccountId"]).index(["userId"]), m = [p], h = class extends e.TaggedError("SocialIdentityConflict") {}, g = (e) => typeof e == "object" && !!e && e._tag === "ConstraintViolation" && e.kind === "unique" || i(o(e), "insert")?.kind === "unique", _ = () => s({
14
+ kind: "typeid",
15
+ prefix: "oauthid"
16
+ }, "oauthid"), v = (e = []) => {
17
+ let n = [...e];
18
+ return {
19
+ findByProviderAccount: (e, r) => t.sync(() => n.find((t) => t.provider === e && t.providerAccountId === r) ?? null),
20
+ listForUser: (e) => t.sync(() => n.filter((t) => t.userId === e)),
21
+ insert: (e) => n.some((t) => t.provider === e.provider && t.providerAccountId === e.providerAccountId) ? t.fail(new h({ provider: e.provider })) : t.sync(() => {
22
+ let t = {
23
+ ...e,
24
+ id: _(),
25
+ createdAt: /* @__PURE__ */ new Date(),
26
+ lastLoginAt: null
27
+ };
28
+ return n.push(t), t;
29
+ }),
30
+ touch: (e, r) => t.sync(() => {
31
+ let t = n.findIndex((t) => t.id === e);
32
+ t >= 0 && (n[t] = {
33
+ ...n[t],
34
+ lastLoginAt: r
35
+ });
36
+ }),
37
+ remove: (e, r) => t.sync(() => {
38
+ let t = n.findIndex((t) => t.userId === e && t.provider === r);
39
+ return t < 0 ? !1 : (n.splice(t, 1), !0);
40
+ })
41
+ };
42
+ }, y = (e) => {
43
+ if (e instanceof Date) return e;
44
+ if (typeof e == "string" || typeof e == "number") {
45
+ let t = new Date(e);
46
+ return Number.isNaN(t.getTime()) ? null : t;
47
+ }
48
+ return null;
49
+ }, b = (e) => ({
50
+ id: String(e.id ?? ""),
51
+ userId: String(e.userId ?? ""),
52
+ provider: String(e.provider ?? ""),
53
+ providerAccountId: String(e.providerAccountId ?? ""),
54
+ email: typeof e.email == "string" && e.email.length > 0 ? e.email : null,
55
+ emailVerified: e.emailVerified === !0 || e.emailVerified === 1,
56
+ createdAt: y(e.createdAt) ?? /* @__PURE__ */ new Date(0),
57
+ lastLoginAt: y(e.lastLoginAt)
58
+ }), x = (e) => ({
59
+ findByProviderAccount: (r, i) => t.promise(async () => {
60
+ let t = (await e.query({
61
+ table: f,
62
+ predicate: n(a("provider", r), a("providerAccountId", i)),
63
+ limit: 1,
64
+ take: 1,
65
+ skip: void 0,
66
+ projection: void 0,
67
+ order: []
68
+ }))[0];
69
+ return t ? b(t) : null;
70
+ }),
71
+ listForUser: (n) => t.promise(async () => (await e.query({
72
+ table: f,
73
+ predicate: a("userId", n),
74
+ order: [{
75
+ column: "createdAt",
76
+ direction: "asc"
77
+ }],
78
+ take: void 0,
79
+ skip: void 0,
80
+ projection: void 0
81
+ })).map(b)),
82
+ insert: (n) => t.tryPromise({
83
+ try: async () => {
84
+ let t = {
85
+ id: _(),
86
+ userId: n.userId,
87
+ provider: n.provider,
88
+ providerAccountId: n.providerAccountId,
89
+ email: n.email,
90
+ emailVerified: n.emailVerified,
91
+ createdAt: /* @__PURE__ */ new Date(),
92
+ lastLoginAt: null
93
+ };
94
+ if (!("insertIgnoreWithOutcome" in e) || e.insertIgnoreWithOutcome === void 0) return b(await e.insert(f, t));
95
+ let r = await e.insertIgnoreWithOutcome(f, t, { conflictColumns: ["provider", "providerAccountId"] });
96
+ if (r.outcome === "ignored") throw new h({ provider: n.provider });
97
+ return b(r.row);
98
+ },
99
+ catch: (e) => e
100
+ }).pipe(t.catch((e) => e instanceof h || g(e) ? t.fail(new h({ provider: n.provider })) : t.die(e))),
101
+ touch: (n, r) => t.promise(async () => {
102
+ await e.update(f, n, { lastLoginAt: r });
103
+ }),
104
+ remove: (r, i) => t.promise(async () => {
105
+ let t = (await e.query({
106
+ table: f,
107
+ predicate: n(a("userId", r), a("provider", i)),
108
+ limit: 1,
109
+ take: 1,
110
+ skip: void 0,
111
+ projection: void 0,
112
+ order: []
113
+ }))[0];
114
+ return t ? e.delete(f, String(t.id ?? "")) : !1;
115
+ })
116
+ }), S = (e, n, r) => t.gen(function* () {
117
+ let i = yield* e.findByProviderAccount(r.provider, r.providerAccountId);
118
+ return i ? i.userId === n ? i : yield* t.fail(/* @__PURE__ */ Error(`linkSocialIdentity: this ${r.provider} account is already linked to another user`)) : yield* e.insert({
119
+ ...r,
120
+ userId: n
121
+ });
122
+ });
123
+ //#endregion
124
+ export { f as SOCIAL_IDENTITY_TABLE, h as SocialIdentityConflict, x as dataStoreSocialIdentityStore, S as linkSocialIdentity, v as memorySocialIdentityStore, m as socialAuthTables, p as socialIdentitiesTable };