@voltro/plugin-auth-social 0.89.1 → 0.90.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/plugin.js CHANGED
@@ -3,18 +3,20 @@ import { isSocialProviderId as n, socialProvider as r } from "./providers.js";
3
3
  import { socialBeginLogin as i } from "./login.js";
4
4
  import { socialCompleteLogin as a } from "./callback.js";
5
5
  import { completeSocialSignIn as o } from "./signIn.js";
6
- import { dataStoreSocialIdentityStore as s, socialAuthTables as c } from "./identityStore.js";
7
- import { completeGuestSocialUpgrade as l } from "./guestUpgrade.js";
8
- import { decodeGuestUpgradeHandoff as u, encodeGuestUpgradeHandoff as d, guestIdentityOf as f } from "./guestHandoff.js";
9
- import { isNativeVerifier as p, nativeUpgradeRequestOf as m, openNativeUpgradeCode as h, sealNativeUpgradeCode as g, signNativeUpgradeTicket as ee, verifierMatches as te, verifyNativeUpgradeTicket as ne } from "./nativeGuestUpgrade.js";
10
- import { verifyPlatformTicket as _ } from "./platform.js";
11
- import { Effect as v, Result as y } from "effect";
12
- import { and as b, eq as x } from "@voltro/database";
13
- import { definePlugin as re } from "@voltro/protocol";
14
- import { SESSION_HEADER_NAME as S, buildSetCookie as C, readCookie as w } from "@voltro/protocol/session";
15
- import { CSRF_COOKIE_NAME as T, CSRF_HEADER_NAME as ie, configSessionSecrets as E, dataStoreGuestAuth as ae, dataStoreSessionRegistry as oe, issueCsrfToken as se, parseGuestCredential as D, readSessionFromHeaders as O, signAuthClaims as ce, verifyAuthClaims as k, verifyCsrf as le } from "@voltro/plugin-auth";
6
+ import { ACCOUNT_MERGE_TABLE as s, SOCIAL_IDENTITY_TABLE as c, dataStoreSocialIdentityStore as l, linkSocialIdentity as u, socialAuthTables as d } from "./identityStore.js";
7
+ import { completeGuestSocialUpgrade as f } from "./guestUpgrade.js";
8
+ import { completeGuestSocialMerge as p, guestMergeTarget as m } from "./accountMerge.js";
9
+ import { decodeGuestUpgradeHandoff as ee, encodeGuestUpgradeHandoff as h, guestIdentityOf as te } from "./guestHandoff.js";
10
+ import { isNativeVerifier as ne, nativeUpgradeRequestOf as re, openNativeUpgradeCode as ie, sealNativeUpgradeCode as ae, signNativeUpgradeTicket as oe, verifierMatches as se, verifyNativeUpgradeTicket as ce } from "./nativeGuestUpgrade.js";
11
+ import { steamBeginOpenId as le, steamCompleteOpenId as ue } from "./steam.js";
12
+ import { verifyPlatformTicket as de } from "./platform.js";
13
+ import { Effect as g, Result as _ } from "effect";
14
+ import { and as fe, eq as v } from "@voltro/database";
15
+ import { definePlugin as pe } from "@voltro/protocol";
16
+ import { SESSION_HEADER_NAME as me, buildSetCookie as y, readCookie as b } from "@voltro/protocol/session";
17
+ import { CSRF_COOKIE_NAME as x, CSRF_HEADER_NAME as he, configSessionSecrets as S, dataStoreGuestAuth as ge, dataStoreSessionRegistry as _e, deferredUserStore as ve, issueCsrfToken as ye, parseGuestCredential as be, readSessionFromHeaders as C, signAuthClaims as xe, verifyAuthClaims as w, verifyCsrf as Se } from "@voltro/plugin-auth";
16
18
  // src/plugin.ts
17
- var ue = "/auth/social", de = 600, fe = "voltro:oauth", A = {
19
+ var Ce = "/auth/social", we = 600, Te = "voltro:oauth", T = {
18
20
  google: [{
19
21
  name: "VOLTRO_GOOGLE_CLIENT_ID",
20
22
  secret: !1,
@@ -91,12 +93,12 @@ var ue = "/auth/social", de = 600, fe = "voltro:oauth", A = {
91
93
  secret: !0,
92
94
  description: "Epic Account Services OAuth client secret."
93
95
  }]
94
- }, j = (e, t) => ({
96
+ }, E = (e, t) => ({
95
97
  status: e,
96
98
  body: JSON.stringify(t),
97
99
  contentType: "application/json; charset=utf-8",
98
100
  headers: { "cache-control": "no-store" }
99
- }), M = (e, t) => e + (e.includes("?") ? "&" : "?") + new URLSearchParams(t).toString(), N = (e, t) => ({
101
+ }), Ee = (e, t) => e + (e.includes("?") ? "&" : "?") + new URLSearchParams(t).toString(), D = (e, t) => ({
100
102
  status: 302,
101
103
  body: "",
102
104
  contentType: "text/plain; charset=utf-8",
@@ -106,17 +108,19 @@ var ue = "/auth/social", de = 600, fe = "voltro:oauth", A = {
106
108
  location: e,
107
109
  ...t === void 0 ? {} : { "set-cookie": t }
108
110
  }
109
- }), pe = (e, t) => ce({ ...e }, t.current.secret, "social-login"), me = (e, t) => {
111
+ }), De = (e, t) => xe({ ...e }, t.current.secret, "social-login"), Oe = (e, t) => {
110
112
  if (!e) return null;
111
113
  try {
112
- let n = [t.current, t.previous].filter((e) => e !== void 0).map((t) => k(e, t.secret, "social-login")).find((e) => e !== null);
114
+ let n = [t.current, t.previous].filter((e) => e !== void 0).map((t) => w(e, t.secret, "social-login")).find((e) => e !== null);
113
115
  if (!n) return null;
114
116
  let r = n;
115
117
  if (typeof r.p != "string" || typeof r.s != "string" || typeof r.v != "string" || typeof r.n != "string" || typeof r.exp != "number" || typeof r.audience != "string" || typeof r.redirectUri != "string") return null;
116
- let i = r.guest === void 0 ? void 0 : f(r.guest);
118
+ let i = r.guest === void 0 ? void 0 : te(r.guest);
117
119
  if (i === null) return null;
118
- let a = r.native, o = a === void 0 ? void 0 : m(a, typeof a?.r == "string" ? [a.r] : []);
119
- return o === null || o !== void 0 && i === void 0 ? null : {
120
+ let a = r.native, o = a === void 0 ? void 0 : re(a, typeof a?.r == "string" ? [a.r] : []);
121
+ if (o === null || o !== void 0 && i === void 0) return null;
122
+ let s = r.link;
123
+ return s !== void 0 && (typeof s.u != "string" || typeof s.t != "string" || typeof s.sid != "string" || i !== void 0) ? null : {
120
124
  p: r.p,
121
125
  s: r.s,
122
126
  v: r.v,
@@ -125,37 +129,46 @@ var ue = "/auth/social", de = 600, fe = "voltro:oauth", A = {
125
129
  audience: r.audience,
126
130
  redirectUri: r.redirectUri,
127
131
  ...i === void 0 ? {} : { guest: i },
128
- ...o === void 0 ? {} : { native: o }
132
+ ...o === void 0 ? {} : { native: o },
133
+ ...s === void 0 ? {} : { link: {
134
+ u: s.u,
135
+ t: s.t,
136
+ sid: s.sid
137
+ } }
129
138
  };
130
139
  } catch {
131
140
  return null;
132
141
  }
133
- }, he = (e) => e.method === "POST" && (e.headers["content-type"] ?? "").includes("application/x-www-form-urlencoded") ? new URLSearchParams(Buffer.from(e.rawBody).toString("utf8")) : new URLSearchParams(e.query), P = (k) => {
134
- let P = k.prefix ?? ue, F = k.stateTtlSeconds ?? de, I = k.stateCookieName ?? fe, L = k.linkPolicy ?? "never", R = k.auth.cookieSecure ?? !0, z = k.providers ?? {}, ge = Object.keys(z);
135
- if (ge.find((e) => !n(e)) !== void 0) throw new t("socialAuthPlugin: unknown provider configuration");
136
- let B = ge.filter(n), V = /* @__PURE__ */ new Map();
142
+ }, ke = (e) => e.method === "POST" && (e.headers["content-type"] ?? "").includes("application/x-www-form-urlencoded") ? new URLSearchParams(Buffer.from(e.rawBody).toString("utf8")) : new URLSearchParams(e.query), O = (w) => {
143
+ let O = { current: typeof w.users == "function" ? void 0 : w.users }, k = {
144
+ ...w,
145
+ users: typeof w.users == "function" ? ve(() => O.current) : w.users
146
+ }, A = k.prefix ?? Ce, j = k.stateTtlSeconds ?? we, M = k.stateCookieName ?? Te, Ae = k.linkPolicy ?? "never", N = k.auth.cookieSecure ?? !0, je = k.providers ?? {}, Me = Object.keys(je);
147
+ if (Me.find((e) => !n(e)) !== void 0) throw new t("socialAuthPlugin: unknown provider configuration");
148
+ let P = Me.filter(n), F = k.steam, Ne = F === void 0 ? P : [...P, "steam"], I = (e) => e === "steam" ? F !== void 0 : e !== void 0 && n(e) && P.includes(e), L = /* @__PURE__ */ new Map();
137
149
  for (let e of k.platforms ?? []) {
138
- if (V.has(e.id)) throw new t(`socialAuthPlugin: platform ${e.id} is configured twice`);
139
- V.set(e.id, e);
150
+ if (L.has(e.id)) throw new t(`socialAuthPlugin: platform ${e.id} is configured twice`);
151
+ L.set(e.id, e);
140
152
  }
141
- if (B.length === 0 && V.size === 0) throw new t("socialAuthPlugin: `providers` and `platforms` are empty — enable at least one provider or platform");
142
- if (!Number.isSafeInteger(F) || F <= 0 || F > 3600) throw new t("socialAuthPlugin: stateTtlSeconds must be an integer from 1 to 3600");
143
- let H = (k.appBaseUrl ?? k.auth.appBaseUrl ?? "").replace(/\/+$/, ""), U = I + ":upgrade", W = k.guestUpgrade, G = JSON.stringify([
144
- H,
145
- P,
153
+ if (!Number.isSafeInteger(j) || j <= 0 || j > 3600) throw new t("socialAuthPlugin: stateTtlSeconds must be an integer from 1 to 3600");
154
+ let R = (k.appBaseUrl ?? k.auth.appBaseUrl ?? "").replace(/\/+$/, ""), z = M + ":upgrade", B = k.guestUpgrade, V = JSON.stringify([
155
+ R,
156
+ A,
146
157
  k.name ?? "",
147
158
  k.auth.defaultTenantId
148
159
  ]);
149
- if (W) {
150
- if (W.guest.tenantId !== k.auth.defaultTenantId || k.auth.ensureActor !== void 0 && W.configForTransaction === void 0) throw new t("Guest upgrade requires matching server tenants and transaction-bound actor hooks");
160
+ if (F !== void 0 && !/^https?:\/\//.test(R)) throw new t("socialAuthPlugin: steam needs an absolute app URL — set `appBaseUrl`");
161
+ let H = `${R}${A}/steam/callback`, U = F?.hotStore === void 0 ? void 0 : () => Promise.resolve(F.hotStore);
162
+ if (B) {
163
+ if (B.guest.tenantId !== k.auth.defaultTenantId || k.auth.ensureActor !== void 0 && B.configForTransaction === void 0) throw new t("Guest upgrade requires matching server tenants and transaction-bound actor hooks");
151
164
  if (k.identities !== void 0) throw new t("Guest upgrade requires transaction-bound SQL social identities");
152
165
  let e = !1;
153
166
  try {
154
- let t = new URL(H), n = new URL(W.confirmationRedirect, t);
155
- e = /^https?:$/.test(t.protocol) && n.origin === t.origin && !n.username && !n.password && !W.confirmationRedirect.startsWith("//") && !W.confirmationRedirect.includes("\\");
167
+ let t = new URL(R), n = new URL(B.confirmationRedirect, t);
168
+ e = /^https?:$/.test(t.protocol) && n.origin === t.origin && !n.username && !n.password && !B.confirmationRedirect.startsWith("//") && !B.confirmationRedirect.includes("\\");
156
169
  } catch {}
157
170
  if (!e) throw new t("Guest upgrade confirmation must be a same-origin application page");
158
- for (let e of W.native?.redirectUris ?? ["acme://valid"]) {
171
+ for (let e of B.native?.redirectUris ?? ["acme://valid"]) {
159
172
  let n = null;
160
173
  try {
161
174
  n = new URL(e);
@@ -166,22 +179,22 @@ var ue = "/auth/social", de = 600, fe = "voltro:oauth", A = {
166
179
  "localhost"
167
180
  ].includes(n.hostname)) throw new t("Native guest upgrade redirect URIs must be exact app URIs (custom scheme, https or loopback http)");
168
181
  }
169
- if (W.native && W.native.redirectUris.length === 0) throw new t("Native guest upgrade needs at least one redirect URI");
182
+ if (B.native && B.native.redirectUris.length === 0) throw new t("Native guest upgrade needs at least one redirect URI");
170
183
  }
171
- let K = (e) => {
172
- if (!W) throw new t("Guest upgrade is not configured");
173
- return W.service?.(e) ?? ae(e, W.guest);
174
- }, q = (e) => C(e, "", {
184
+ let W = (e) => {
185
+ if (!B) throw new t("Guest upgrade is not configured");
186
+ return B.service?.(e) ?? ge(e, B.guest);
187
+ }, G = (e) => y(e, "", {
175
188
  maxAgeSeconds: 0,
176
- path: P,
177
- secure: R,
189
+ path: A,
190
+ secure: N,
178
191
  httpOnly: !0,
179
192
  sameSite: "lax",
180
193
  ...k.auth.cookieDomain ? { domain: k.auth.cookieDomain } : {}
181
- }), J = (e) => {
182
- let n = z[e] ?? {}, r = process.env, i = n.clientId ?? r[A[e][0].name] ?? "";
183
- if (!i) throw new t(`socialAuthPlugin: ${e} has no client id — pass \`providers.${e}.clientId\` or set ${A[e][0].name}`);
184
- let a = n.redirectUri ?? `${H}${P}/${e}/callback`, o = !1;
194
+ }), K = (e) => {
195
+ let n = je[e] ?? {}, r = process.env, i = n.clientId ?? r[T[e][0].name] ?? "";
196
+ if (!i) throw new t(`socialAuthPlugin: ${e} has no client id — pass \`providers.${e}.clientId\` or set ${T[e][0].name}`);
197
+ let a = n.redirectUri ?? `${R}${A}/${e}/callback`, o = !1;
185
198
  try {
186
199
  let e = new URL(a);
187
200
  o = (e.protocol === "https:" || e.protocol === "http:") && e.username === "" && e.password === "" && e.hash === "";
@@ -206,31 +219,42 @@ var ue = "/auth/social", de = 600, fe = "voltro:oauth", A = {
206
219
  appleKey: e
207
220
  };
208
221
  }
209
- let c = n.clientSecret ?? r[A[e][1].name] ?? "";
210
- if (!c) throw new t(`socialAuthPlugin: ${e} has no client secret — pass \`providers.${e}.clientSecret\` or set ${A[e][1].name}`);
222
+ let c = n.clientSecret ?? r[T[e][1].name] ?? "";
223
+ if (!c) throw new t(`socialAuthPlugin: ${e} has no client secret — pass \`providers.${e}.clientSecret\` or set ${T[e][1].name}`);
211
224
  return {
212
225
  ...s,
213
226
  clientSecret: c
214
227
  };
215
- }, Y = k.identities ?? null, _e = (e) => {
216
- if (Y) return Y;
228
+ }, q = k.identities ?? null, J, Pe, Fe, Ie = () => {
229
+ if (q) return q;
230
+ if (!J) throw new t("socialAuthPlugin: privacy hooks need the app DataStore or an `identities` store");
231
+ return q = l(J), q;
232
+ }, Le = (e) => g.promise(async () => J === void 0 ? [] : (await J.query({
233
+ table: s,
234
+ predicate: v("targetId", e),
235
+ order: [],
236
+ take: void 0,
237
+ skip: void 0,
238
+ projection: void 0
239
+ })).filter((t) => t.targetId === e)), Y = (e) => {
240
+ if (q) return q;
217
241
  let n = e.store;
218
242
  if (!n) throw new t("socialAuthPlugin: no identity store — pass `identities`, or run on an app with a DataStore");
219
- return Y = s(n), Y;
220
- }, ve = (e) => {
221
- if (!e.startsWith(`${P}/`)) return null;
222
- let [t, ...r] = e.slice(P.length + 1).split("/");
223
- return !t || !n(t) || !B.includes(t) ? null : r.length === 0 ? {
243
+ return q = l(n), q;
244
+ }, Re = (e) => {
245
+ if (!e.startsWith(`${A}/`)) return null;
246
+ let [t, ...n] = e.slice(A.length + 1).split("/");
247
+ return I(t) ? n.length === 0 ? {
224
248
  id: t,
225
249
  isCallback: !1
226
- } : r.length === 1 && r[0] === "callback" ? {
250
+ } : n.length === 1 && n[0] === "callback" ? {
227
251
  id: t,
228
252
  isCallback: !0
229
- } : null;
253
+ } : null : null;
230
254
  }, X = (e, t, n) => {
231
- let r = [q(I), ...W ? [q(U)] : []];
255
+ let r = [G(M), ...B ? [G(z)] : []];
232
256
  if (!k.failureRedirect) return {
233
- ...j(e, {
257
+ ...E(e, {
234
258
  error: t,
235
259
  message: n
236
260
  }),
@@ -239,7 +263,7 @@ var ue = "/auth/social", de = 600, fe = "voltro:oauth", A = {
239
263
  "set-cookie": r
240
264
  }
241
265
  };
242
- let i = k.failureRedirect.includes("?") ? "&" : "?", a = N(`${k.failureRedirect}${i}social_error=${encodeURIComponent(t)}`);
266
+ let i = k.failureRedirect.includes("?") ? "&" : "?", a = D(`${k.failureRedirect}${i}social_error=${encodeURIComponent(t)}`);
243
267
  return {
244
268
  ...a,
245
269
  headers: {
@@ -247,61 +271,117 @@ var ue = "/auth/social", de = 600, fe = "voltro:oauth", A = {
247
271
  "set-cookie": r
248
272
  }
249
273
  };
250
- }, Z = (e, t, n, a) => {
251
- let o = J(t), s = r(t, o.endpoints), c = i({
274
+ }, Z = (e, t, n, a, o) => {
275
+ if (t === "steam") {
276
+ let e = le({
277
+ returnTo: H,
278
+ ...F?.realm === void 0 ? {} : { realm: F.realm }
279
+ }), t = y(M, De({
280
+ p: "steam",
281
+ s: e.state,
282
+ v: "",
283
+ n: "",
284
+ exp: Math.floor(Date.now() / 1e3) + j,
285
+ audience: V,
286
+ redirectUri: H,
287
+ ...n === void 0 ? {} : { guest: n },
288
+ ...o === void 0 || n !== void 0 ? {} : { link: o }
289
+ }, S(k.auth)), {
290
+ maxAgeSeconds: j,
291
+ httpOnly: !0,
292
+ sameSite: "lax",
293
+ secure: N,
294
+ ...k.auth.cookieDomain ? { domain: k.auth.cookieDomain } : {},
295
+ path: A
296
+ }), r = D(e.url, t);
297
+ return B ? {
298
+ ...r,
299
+ headers: {
300
+ ...r.headers,
301
+ "set-cookie": [t, G(z)]
302
+ }
303
+ } : r;
304
+ }
305
+ let s = K(t), c = r(t, s.endpoints), l = i({
252
306
  provider: t,
253
- clientId: o.clientId,
254
- redirectUri: o.redirectUri,
255
- ...o.scopes === void 0 ? {} : { scopes: o.scopes },
256
- endpoints: o.endpoints,
307
+ clientId: s.clientId,
308
+ redirectUri: s.redirectUri,
309
+ ...s.scopes === void 0 ? {} : { scopes: s.scopes },
310
+ endpoints: s.endpoints,
257
311
  ...new URLSearchParams(e.query).get("login_hint") ? { loginHint: new URLSearchParams(e.query).get("login_hint") } : {}
258
- }), l = C(I, pe({
312
+ }), u = y(M, De({
259
313
  p: t,
260
- s: c.state,
261
- v: c.codeVerifier,
262
- n: c.nonce,
263
- exp: Math.floor(Date.now() / 1e3) + F,
264
- audience: G,
265
- redirectUri: o.redirectUri,
314
+ s: l.state,
315
+ v: l.codeVerifier,
316
+ n: l.nonce,
317
+ exp: Math.floor(Date.now() / 1e3) + j,
318
+ audience: V,
319
+ redirectUri: s.redirectUri,
266
320
  ...n === void 0 ? {} : { guest: n },
267
- ...n !== void 0 && a !== void 0 ? { native: a } : {}
268
- }, E(k.auth)), {
269
- maxAgeSeconds: F,
321
+ ...n !== void 0 && a !== void 0 ? { native: a } : {},
322
+ ...o === void 0 || n !== void 0 ? {} : { link: o }
323
+ }, S(k.auth)), {
324
+ maxAgeSeconds: j,
270
325
  httpOnly: !0,
271
- sameSite: s.responseMode === "form_post" ? "none" : "lax",
272
- secure: s.responseMode === "form_post" || R,
326
+ sameSite: c.responseMode === "form_post" ? "none" : "lax",
327
+ secure: c.responseMode === "form_post" || N,
273
328
  ...k.auth.cookieDomain ? { domain: k.auth.cookieDomain } : {},
274
- path: P
275
- }), u = N(c.url, l);
276
- return W ? {
277
- ...u,
329
+ path: A
330
+ }), d = D(l.url, u);
331
+ return B ? {
332
+ ...d,
278
333
  headers: {
279
- ...u.headers,
280
- "set-cookie": [l, q(U)]
334
+ ...d.headers,
335
+ "set-cookie": [u, G(z)]
281
336
  }
282
- } : u;
283
- }, ye = async (e, t) => {
284
- let n = he(e), r = me(w(e.headers.cookie, I), E(k.auth)), i = J(t), s = r && r.p === t && r.audience === G && r.redirectUri === i.redirectUri ? r : null, c = W?.native && s?.guest && s.native ? s.native : null, l = (e) => {
285
- let t = N(e);
337
+ } : d;
338
+ }, ze = (e) => {
339
+ let t = new URL(H);
340
+ return t.searchParams.set("state", e), t.href;
341
+ }, Be = async (e, n) => {
342
+ if (!F || !U) throw new t("socialAuthPlugin: steam has no hot store for replay protection");
343
+ let r = new URL(A + "/steam/callback", R + "/");
344
+ r.search = new URLSearchParams(e.query).toString();
345
+ let i = await g.runPromise(g.result(ue({
346
+ callbackUrl: r.href,
347
+ expectedReturnTo: ze(n?.s ?? ""),
348
+ expectedState: n?.s ?? "",
349
+ hotStore: await U(),
350
+ namespace: "auth-social:steam:" + V,
351
+ ...F.multiNode === void 0 ? {} : { multiNode: F.multiNode },
352
+ ...F.timeoutMs === void 0 ? {} : { timeoutMs: F.timeoutMs },
353
+ ...F.fetchImpl === void 0 ? {} : { fetchImpl: F.fetchImpl },
354
+ ...F.verificationUrl === void 0 ? {} : { verificationUrl: F.verificationUrl }
355
+ })));
356
+ if (_.isFailure(i)) throw i.failure;
357
+ return i.success;
358
+ }, Ve = async (e, t) => {
359
+ let n = ke(e), r = Oe(b(e.headers.cookie, M), S(k.auth)), i = t === "steam" ? null : K(t), s = r && r.p === t && r.audience === V && r.redirectUri === (i === null ? H : i.redirectUri) ? r : null, c = B?.native && s?.guest && s.native ? s.native : null, l = (e) => {
360
+ let t = D(e);
286
361
  return {
287
362
  ...t,
288
363
  headers: {
289
364
  ...t.headers,
290
- "set-cookie": [q(I)]
365
+ "set-cookie": [G(M)]
291
366
  }
292
367
  };
293
- }, u = (e, t, n) => c ? l(M(c.r, {
368
+ }, d = (e, t, n) => c ? l(Ee(c.r, {
294
369
  error: t,
295
370
  state: c.ns
296
371
  })) : X(e, t, n);
297
- if (n.get("error")) return u(400, "exchange_failed", `${t} refused the authorization`);
372
+ if (n.get("error")) return d(400, "exchange_failed", `${t} refused the authorization`);
298
373
  if (s?.guest) {
299
- if (!W || !e.store || s.guest.tenantId !== W.guest.tenantId) return u(403, "credential_rejected", "Guest upgrade was refused.");
300
- let t = await v.runPromise(v.result(K(e.store).isLive(s.guest)));
301
- if (y.isFailure(t)) return u(503, "store_unavailable", "Guest upgrade storage is unavailable.");
302
- if (!t.success) return u(403, "credential_rejected", "Guest upgrade was refused.");
374
+ if (!B || !e.store || s.guest.tenantId !== B.guest.tenantId) return d(403, "credential_rejected", "Guest upgrade was refused.");
375
+ let t = await g.runPromise(g.result(W(e.store).isLive(s.guest)));
376
+ if (_.isFailure(t)) return d(503, "store_unavailable", "Guest upgrade storage is unavailable.");
377
+ if (!t.success) return d(403, "credential_rejected", "Guest upgrade was refused.");
303
378
  }
304
- let f = await a({
379
+ if (s?.link) {
380
+ let t = await Ke(e);
381
+ if (t === "unavailable") return d(503, "store_unavailable", "Account storage is unavailable.");
382
+ if (!t || t.id !== s.link.u || t.tenantId !== s.link.t || t.sessionId !== s.link.sid) return d(403, "credential_rejected", "Sign in again to connect this provider.");
383
+ }
384
+ let f = i === null ? await Be(e, s) : await a({
305
385
  provider: t,
306
386
  clientId: i.clientId,
307
387
  ...i.clientSecret === void 0 ? {} : { clientSecret: i.clientSecret },
@@ -315,55 +395,64 @@ var ue = "/auth/social", de = 600, fe = "voltro:oauth", A = {
315
395
  ...n.get("user") ? { appleUserPayload: n.get("user") } : {},
316
396
  endpoints: i.endpoints
317
397
  });
318
- if (s?.guest && W) {
319
- let e = Math.min(s.exp, Math.floor(Date.now() / 1e3) + F), t = d({
398
+ if (s?.guest && B) {
399
+ let e = Math.min(s.exp, Math.floor(Date.now() / 1e3) + j), t = h({
320
400
  guest: s.guest,
321
401
  profile: f,
322
402
  exp: e,
323
- audience: G
324
- }, E(k.auth));
403
+ audience: V
404
+ }, S(k.auth));
325
405
  if (c) {
326
- let n = g({
406
+ let n = ae({
327
407
  handoff: t,
328
408
  ch: c.ch,
329
409
  guestId: s.guest.id,
330
410
  exp: Math.min(e, Math.floor(Date.now() / 1e3) + 120)
331
- }, E(k.auth), G);
332
- return l(M(c.r, {
411
+ }, S(k.auth), V);
412
+ return l(Ee(c.r, {
333
413
  code: n,
334
414
  state: c.ns
335
415
  }));
336
416
  }
337
- let n = N(W.confirmationRedirect);
417
+ let n = D(B.confirmationRedirect);
338
418
  return {
339
419
  ...n,
340
420
  headers: {
341
421
  ...n.headers,
342
- "set-cookie": [q(I), C(U, t, {
422
+ "set-cookie": [G(M), y(z, t, {
343
423
  maxAgeSeconds: Math.max(0, e - Math.floor(Date.now() / 1e3)),
344
- path: P,
424
+ path: A,
345
425
  httpOnly: !0,
346
426
  sameSite: "lax",
347
- secure: R,
427
+ secure: N,
348
428
  ...k.auth.cookieDomain ? { domain: k.auth.cookieDomain } : {}
349
429
  })]
350
430
  }
351
431
  };
352
432
  }
353
- let p = await v.runPromise(o({
433
+ if (s?.link) {
434
+ let n = await g.runPromise(g.result(u(Y(e), s.link.u, {
435
+ provider: f.provider,
436
+ providerAccountId: f.providerAccountId,
437
+ email: f.email,
438
+ emailVerified: f.emailVerified
439
+ })));
440
+ return _.isFailure(n) ? d(409, "identity_in_use", "This provider account is already connected to another account.") : l(Ee(k.linkRedirect ?? k.successRedirect ?? k.auth.successRedirect ?? "/", { social_linked: t }));
441
+ }
442
+ let p = await g.runPromise(o({
354
443
  profile: f,
355
- identities: _e(e),
444
+ identities: Y(e),
356
445
  users: k.users,
357
446
  config: k.auth,
358
- policy: L,
447
+ policy: Ae,
359
448
  ipAddress: e.remoteAddr ?? null,
360
449
  userAgent: e.headers["user-agent"] ?? null
361
450
  }));
362
451
  if (p.kind === "refused") return X(p.status, p.code, p.message);
363
- let m = C(I, "", {
452
+ let m = y(M, "", {
364
453
  maxAgeSeconds: 0,
365
- path: P,
366
- secure: R
454
+ path: A,
455
+ secure: N
367
456
  });
368
457
  return {
369
458
  status: 302,
@@ -377,24 +466,24 @@ var ue = "/auth/social", de = 600, fe = "voltro:oauth", A = {
377
466
  }
378
467
  };
379
468
  }, Q = (e, t) => ({
380
- ...j(e, t),
469
+ ...E(e, t),
381
470
  headers: { "cache-control": "no-store" }
382
- }), be = async (e, t, r) => {
383
- let i = W?.native;
384
- if (!W || !i) return j(404, { error: "not_found" });
471
+ }), He = async (e, t, r) => {
472
+ let i = B?.native;
473
+ if (!B || !i) return E(404, { error: "not_found" });
385
474
  let a = async (t) => {
386
475
  if (!e.store) return Q(503, { error: "store_unavailable" });
387
- let n = await v.runPromise(v.result(K(e.store).isLive(t)));
388
- return y.isFailure(n) ? Q(503, { error: "store_unavailable" }) : n.success ? null : Q(403, { error: "credential_rejected" });
476
+ let n = await g.runPromise(g.result(W(e.store).isLive(t)));
477
+ return _.isFailure(n) ? Q(503, { error: "store_unavailable" }) : n.success ? null : Q(403, { error: "credential_rejected" });
389
478
  };
390
479
  if (t === "begin") {
391
- if (e.method !== "GET") return j(405, { error: "method_not_allowed" });
392
- let t = ne(new URLSearchParams(e.query).get("t"), r, G, i.redirectUris);
393
- return !t || !n(t.provider) || !B.includes(t.provider) || t.guest.tenantId !== W.guest.tenantId ? Q(403, { error: "upgrade_ticket_rejected" }) : await a(t.guest) ?? Z(e, t.provider, t.guest, t.native);
480
+ if (e.method !== "GET") return E(405, { error: "method_not_allowed" });
481
+ let t = ce(new URLSearchParams(e.query).get("t"), r, V, i.redirectUris);
482
+ return !t || !n(t.provider) || !P.includes(t.provider) || t.guest.tenantId !== B.guest.tenantId ? Q(403, { error: "upgrade_ticket_rejected" }) : await a(t.guest) ?? Z(e, t.provider, t.guest, t.native);
394
483
  }
395
- if (e.method !== "POST") return j(405, { error: "method_not_allowed" });
396
- if ((e.headers["content-type"] ?? "").split(";")[0]?.trim() !== "application/json") return j(415, { error: "json_required" });
397
- if (e.rawBody.byteLength > 8192) return j(413, { error: "body_too_large" });
484
+ if (e.method !== "POST") return E(405, { error: "method_not_allowed" });
485
+ if ((e.headers["content-type"] ?? "").split(";")[0]?.trim() !== "application/json") return E(415, { error: "json_required" });
486
+ if (e.rawBody.byteLength > 8192) return E(413, { error: "body_too_large" });
398
487
  let o;
399
488
  try {
400
489
  o = JSON.parse(new TextDecoder().decode(e.rawBody));
@@ -405,57 +494,57 @@ var ue = "/auth/social", de = 600, fe = "voltro:oauth", A = {
405
494
  let s = o;
406
495
  if (t.startsWith("start/")) {
407
496
  let o = t.slice(6);
408
- if (!n(o) || !B.includes(o)) return j(404, { error: "not_found" });
409
- let c = e.headers[S], l = typeof W.guest.secret == "function" ? W.guest.secret() : W.guest.secret, u = typeof c == "string" && c ? f(O({ [S]: c }, l)?.subject) : null;
410
- if (!u || u.tenantId !== W.guest.tenantId) return Q(403, { error: "credential_rejected" });
411
- let d = m({
497
+ if (!n(o) || !P.includes(o)) return E(404, { error: "not_found" });
498
+ let c = e.headers[me], l = typeof B.guest.secret == "function" ? B.guest.secret() : B.guest.secret, u = typeof c == "string" && c ? te(C({ [me]: c }, l)?.subject) : null;
499
+ if (!u || u.tenantId !== B.guest.tenantId) return Q(403, { error: "credential_rejected" });
500
+ let d = re({
412
501
  ch: s.codeChallenge,
413
502
  r: s.redirectUri,
414
503
  ns: s.state
415
504
  }, i.redirectUris);
416
505
  if (!d || Object.keys(s).some((e) => e !== "codeChallenge" && e !== "redirectUri" && e !== "state")) return Q(400, { error: "invalid_input" });
417
- let p = await a(u);
418
- if (p) return p;
419
- let h = ee({
506
+ let f = await a(u);
507
+ if (f) return f;
508
+ let p = oe({
420
509
  guest: u,
421
510
  provider: o,
422
511
  native: d,
423
- exp: Math.floor(Date.now() / 1e3) + F,
424
- audience: G
425
- }, r), g = new URL(P + "/upgrade/native/begin", J(o).redirectUri);
426
- return g.search = new URLSearchParams({ t: h }).toString(), Q(200, { authorizationUrl: g.toString() });
512
+ exp: Math.floor(Date.now() / 1e3) + j,
513
+ audience: V
514
+ }, r), m = new URL(A + "/upgrade/native/begin", K(o).redirectUri);
515
+ return m.search = new URLSearchParams({ t: p }).toString(), Q(200, { authorizationUrl: m.toString() });
427
516
  }
428
- if (t !== "complete") return j(404, { error: "not_found" });
429
- if (Object.keys(s).some((e) => e !== "code" && e !== "codeVerifier" && e !== "credential" && e !== "confirmed") || s.confirmed !== !0 || typeof s.credential != "string" || !p(s.codeVerifier)) return Q(400, { error: "invalid_input" });
430
- let c = h(s.code, r, G);
431
- if (!c || !te(s.codeVerifier, c.ch)) return Q(400, { error: "invalid_code" });
432
- let d = u(c.handoff, r, G), g = D(s.credential);
433
- if (!d || d.guest.id !== c.guestId || d.guest.tenantId !== W.guest.tenantId || !g || g.guestId !== d.guest.id || g.deviceId !== d.guest.metadata?.guestDeviceId) return Q(403, { error: "upgrade_handoff_rejected" });
434
- let _ = await a(d.guest);
435
- if (_) return _;
436
- let b = await v.runPromise(l({
437
- profile: d.profile,
517
+ if (t !== "complete") return E(404, { error: "not_found" });
518
+ if (Object.keys(s).some((e) => e !== "code" && e !== "codeVerifier" && e !== "credential" && e !== "confirmed") || s.confirmed !== !0 || typeof s.credential != "string" || !ne(s.codeVerifier)) return Q(400, { error: "invalid_input" });
519
+ let c = ie(s.code, r, V);
520
+ if (!c || !se(s.codeVerifier, c.ch)) return Q(400, { error: "invalid_code" });
521
+ let l = ee(c.handoff, r, V), u = be(s.credential);
522
+ if (!l || l.guest.id !== c.guestId || l.guest.tenantId !== B.guest.tenantId || !u || u.guestId !== l.guest.id || u.deviceId !== l.guest.metadata?.guestDeviceId) return Q(403, { error: "upgrade_handoff_rejected" });
523
+ let d = await a(l.guest);
524
+ if (d) return d;
525
+ let p = await g.runPromise(f({
526
+ profile: l.profile,
438
527
  credential: s.credential,
439
528
  store: e.store,
440
- guest: W.guest,
441
- service: K(e.store),
529
+ guest: B.guest,
530
+ service: W(e.store),
442
531
  users: k.users,
443
532
  config: k.auth,
444
- ...W.configForTransaction ? { configForTransaction: W.configForTransaction } : {},
533
+ ...B.configForTransaction ? { configForTransaction: B.configForTransaction } : {},
445
534
  ipAddress: e.remoteAddr ?? null,
446
535
  userAgent: e.headers["user-agent"] ?? null
447
536
  }));
448
- return b.kind === "refused" ? Q(b.status, {
449
- error: b.code,
450
- message: b.message
537
+ return p.kind === "refused" ? Q(p.status, {
538
+ error: p.code,
539
+ message: p.message
451
540
  }) : Q(200, {
452
541
  ok: !0,
453
542
  upgraded: !0,
454
- subject: b.subject,
455
- session: b.session.value,
456
- expiresAt: b.session.expiresAt
543
+ subject: p.subject,
544
+ session: p.session.value,
545
+ expiresAt: p.session.expiresAt
457
546
  });
458
- }, $ = /* @__PURE__ */ new Map(), xe = async (e, t) => {
547
+ }, $ = /* @__PURE__ */ new Map(), Ue = async (e, t) => {
459
548
  let n = ($.get(e) ?? Promise.resolve()).then(t, t), r = n.then(() => void 0, () => void 0);
460
549
  $.set(e, r);
461
550
  try {
@@ -463,12 +552,12 @@ var ue = "/auth/social", de = 600, fe = "voltro:oauth", A = {
463
552
  } finally {
464
553
  $.get(e) === r && $.delete(e);
465
554
  }
466
- }, Se = async (t) => {
467
- let [n, r, ...i] = t.path.slice((P + "/platform/").length).split("/"), a = n === void 0 ? void 0 : V.get(n);
468
- if (!a || i.length !== 0 || r !== "sign-in" && r !== "link" || r === "link" && !W) return j(404, { error: "not_found" });
469
- if (t.method !== "POST") return j(405, { error: "method_not_allowed" });
470
- if ((t.headers["content-type"] ?? "").split(";")[0]?.trim() !== "application/json") return j(415, { error: "json_required" });
471
- if (t.rawBody.byteLength > 16384) return j(413, { error: "body_too_large" });
555
+ }, We = async (t) => {
556
+ let [n, r, ...i] = t.path.slice((A + "/platform/").length).split("/"), a = n === void 0 ? void 0 : L.get(n);
557
+ if (!a || i.length !== 0 || r !== "sign-in" && r !== "link" || r === "link" && !B) return E(404, { error: "not_found" });
558
+ if (t.method !== "POST") return E(405, { error: "method_not_allowed" });
559
+ if ((t.headers["content-type"] ?? "").split(";")[0]?.trim() !== "application/json") return E(415, { error: "json_required" });
560
+ if (t.rawBody.byteLength > 16384) return E(413, { error: "body_too_large" });
472
561
  let s;
473
562
  try {
474
563
  s = JSON.parse(new TextDecoder().decode(t.rawBody));
@@ -476,12 +565,12 @@ var ue = "/auth/social", de = 600, fe = "voltro:oauth", A = {
476
565
  return Q(400, { error: "invalid_input" });
477
566
  }
478
567
  if (!s || typeof s != "object" || Array.isArray(s)) return Q(400, { error: "invalid_input" });
479
- let c = s, u = r === "link" ? ["ticket", "credential"] : ["ticket"];
480
- if (Object.keys(c).some((e) => !u.includes(e)) || typeof c.ticket != "string" || c.ticket.length === 0 || r === "link" && (typeof c.credential != "string" || !D(c.credential))) return Q(400, { error: "invalid_input" });
568
+ let c = s, l = r === "link" ? ["ticket", "credential"] : ["ticket"];
569
+ if (Object.keys(c).some((e) => !l.includes(e)) || typeof c.ticket != "string" || c.ticket.length === 0 || r === "link" && (typeof c.credential != "string" || !be(c.credential))) return Q(400, { error: "invalid_input" });
481
570
  if (!t.store && (r === "link" || !k.identities)) return Q(503, { error: "store_unavailable" });
482
- let d;
571
+ let u;
483
572
  try {
484
- d = await _(a, c.ticket);
573
+ u = await de(a, c.ticket);
485
574
  } catch (t) {
486
575
  if (t instanceof e) return Q(t.status, {
487
576
  error: t.code,
@@ -489,9 +578,9 @@ var ue = "/auth/social", de = 600, fe = "voltro:oauth", A = {
489
578
  });
490
579
  throw t;
491
580
  }
492
- let f = {
581
+ let d = {
493
582
  provider: a.id,
494
- providerAccountId: d.accountId,
583
+ providerAccountId: u.accountId,
495
584
  email: null,
496
585
  emailVerified: !1,
497
586
  emailIsPrivateRelay: !1,
@@ -504,22 +593,22 @@ var ue = "/auth/social", de = 600, fe = "voltro:oauth", A = {
504
593
  }, p = {
505
594
  ipAddress: t.remoteAddr ?? null,
506
595
  userAgent: t.headers["user-agent"] ?? null
507
- }, m = await xe(a.id + "\0" + d.accountId, () => r === "sign-in" ? v.runPromise(o({
508
- profile: f,
509
- identities: _e(t),
596
+ }, m = await Ue(a.id + "\0" + u.accountId, () => r === "sign-in" ? g.runPromise(o({
597
+ profile: d,
598
+ identities: Y(t),
510
599
  users: k.users,
511
600
  config: k.auth,
512
- policy: L,
601
+ policy: Ae,
513
602
  ...p
514
- })) : v.runPromise(l({
515
- profile: f,
603
+ })) : g.runPromise(f({
604
+ profile: d,
516
605
  credential: c.credential,
517
606
  store: t.store,
518
- guest: W.guest,
519
- service: K(t.store),
607
+ guest: B.guest,
608
+ service: W(t.store),
520
609
  users: k.users,
521
610
  config: k.auth,
522
- ...W.configForTransaction ? { configForTransaction: W.configForTransaction } : {},
611
+ ...B.configForTransaction ? { configForTransaction: B.configForTransaction } : {},
523
612
  ...p
524
613
  })));
525
614
  return m.kind === "refused" ? Q(m.status, {
@@ -532,38 +621,38 @@ var ue = "/auth/social", de = 600, fe = "voltro:oauth", A = {
532
621
  expiresAt: m.session.expiresAt,
533
622
  created: m.created
534
623
  });
535
- }, Ce = async (e) => {
536
- if (!W) return j(404, { error: "not_found" });
537
- let t = e.path.slice((P + "/upgrade/").length), r = E(k.auth);
538
- if (t.startsWith("native/")) return be(e, t.slice(7), r);
624
+ }, Ge = async (e) => {
625
+ if (!B) return E(404, { error: "not_found" });
626
+ let t = e.path.slice((A + "/upgrade/").length), n = S(k.auth);
627
+ if (t.startsWith("native/")) return He(e, t.slice(7), n);
539
628
  if (t === "csrf") {
540
- if (e.method !== "GET") return j(405, { error: "method_not_allowed" });
541
- let t = se(r.current.secret);
629
+ if (e.method !== "GET") return E(405, { error: "method_not_allowed" });
630
+ let t = ye(n.current.secret);
542
631
  return {
543
- ...j(200, { token: t }),
632
+ ...E(200, { token: t }),
544
633
  headers: {
545
634
  "cache-control": "no-store",
546
- "set-cookie": C(T, t, {
635
+ "set-cookie": y(x, t, {
547
636
  path: "/",
548
637
  httpOnly: !1,
549
- secure: R,
638
+ secure: N,
550
639
  sameSite: "lax",
551
- maxAgeSeconds: F,
640
+ maxAgeSeconds: j,
552
641
  ...k.auth.cookieDomain ? { domain: k.auth.cookieDomain } : {}
553
642
  })
554
643
  }
555
644
  };
556
645
  }
557
- let i = () => u(w(e.headers.cookie, U), r, G);
646
+ let r = () => ee(b(e.headers.cookie, z), n, V);
558
647
  if (t === "receipt") {
559
- if (e.method !== "GET") return j(405, { error: "method_not_allowed" });
560
- let t = O(e.headers, r)?.subject;
561
- if (!e.store || t?.type !== "user" || t.kind === "guest" || !/^guest_[A-Za-z0-9_-]+$/.test(t.id) || t.tenantId !== W.guest.tenantId || typeof t.metadata?.sessionId != "string") return j(403, { error: "credential_rejected" });
648
+ if (e.method !== "GET") return E(405, { error: "method_not_allowed" });
649
+ let t = C(e.headers, n)?.subject;
650
+ if (!e.store || t?.type !== "user" || t.kind === "guest" || !/^guest_[A-Za-z0-9_-]+$/.test(t.id) || t.tenantId !== B.guest.tenantId || typeof t.metadata?.sessionId != "string") return E(403, { error: "credential_rejected" });
562
651
  try {
563
- let n = await v.runPromise(oe(e.store).findSession(t.metadata.sessionId));
564
- if (!n || n.userId !== t.id || n.tenantId !== t.tenantId || !(n.expiresAt.getTime() > Date.now())) return j(403, { error: "credential_rejected" });
652
+ let n = await g.runPromise(_e(e.store).findSession(t.metadata.sessionId));
653
+ if (!n || n.userId !== t.id || n.tenantId !== t.tenantId || !(n.expiresAt.getTime() > Date.now())) return E(403, { error: "credential_rejected" });
565
654
  let r = {
566
- predicate: b(x("id", t.id), x("tenantId", t.tenantId)),
655
+ predicate: fe(v("id", t.id), v("tenantId", t.tenantId)),
567
656
  order: [],
568
657
  take: void 0,
569
658
  skip: void 0,
@@ -575,7 +664,7 @@ var ue = "/auth/social", de = 600, fe = "voltro:oauth", A = {
575
664
  table: "authGuests",
576
665
  ...r
577
666
  }))[0];
578
- return !i || i.id !== t.id || i.tenantId !== t.tenantId || a || i.deactivatedAt !== null && i.deactivatedAt !== void 0 ? j(403, { error: "credential_rejected" }) : j(200, {
667
+ return !i || i.id !== t.id || i.tenantId !== t.tenantId || a || i.deactivatedAt !== null && i.deactivatedAt !== void 0 ? E(403, { error: "credential_rejected" }) : E(200, {
579
668
  upgraded: !0,
580
669
  subject: {
581
670
  type: "user",
@@ -584,106 +673,236 @@ var ue = "/auth/social", de = 600, fe = "voltro:oauth", A = {
584
673
  }
585
674
  });
586
675
  } catch {
587
- return j(503, { error: "store_unavailable" });
676
+ return E(503, { error: "store_unavailable" });
588
677
  }
589
678
  }
590
679
  if (t === "pending") {
591
- if (e.method !== "GET") return j(405, { error: "method_not_allowed" });
592
- let t = i();
593
- if (!t || t.guest.tenantId !== W.guest.tenantId || !e.store) return j(403, { error: "upgrade_handoff_rejected" });
594
- let n = await v.runPromise(v.result(K(e.store).isLive(t.guest)));
595
- return y.isFailure(n) ? j(503, { error: "store_unavailable" }) : n.success ? j(200, {
680
+ if (e.method !== "GET") return E(405, { error: "method_not_allowed" });
681
+ let t = r();
682
+ if (!t || t.guest.tenantId !== B.guest.tenantId || !e.store) return E(403, { error: "upgrade_handoff_rejected" });
683
+ let n = await g.runPromise(g.result(W(e.store).isLive(t.guest)));
684
+ if (_.isFailure(n)) return E(503, { error: "store_unavailable" });
685
+ if (!n.success) return E(403, { error: "credential_rejected" });
686
+ let i = await g.runPromise(g.result(m(e.store, t.profile)));
687
+ return _.isFailure(i) ? E(503, { error: "store_unavailable" }) : E(200, {
596
688
  guestId: t.guest.id,
597
689
  provider: t.profile.provider,
598
690
  email: t.profile.email,
599
691
  emailVerified: t.profile.emailVerified,
600
- expiresAt: t.exp * 1e3
601
- }) : j(403, { error: "credential_rejected" });
692
+ expiresAt: t.exp * 1e3,
693
+ conflict: i.success.kind === "none" ? null : i.success.kind
694
+ });
602
695
  }
603
- let a = n(t) && B.includes(t);
604
- if (!a && t !== "complete") return j(404, { error: "not_found" });
605
- if (e.method !== "POST") return j(405, { error: "method_not_allowed" });
606
- if ((e.headers["content-type"] ?? "").split(";")[0]?.trim() !== "application/json") return j(415, { error: "json_required" });
607
- if (e.rawBody.byteLength > 1024) return j(413, { error: "body_too_large" });
608
- if (![r.current, r.previous].filter((e) => e !== void 0).some((t) => le(e.headers[ie], w(e.headers.cookie, T), t.secret))) return j(403, { error: "csrf_rejected" });
609
- let o;
696
+ let i = I(t);
697
+ if (!i && t !== "complete" && t !== "merge") return E(404, { error: "not_found" });
698
+ if (e.method !== "POST") return E(405, { error: "method_not_allowed" });
699
+ if ((e.headers["content-type"] ?? "").split(";")[0]?.trim() !== "application/json") return E(415, { error: "json_required" });
700
+ if (e.rawBody.byteLength > 1024) return E(413, { error: "body_too_large" });
701
+ if (![n.current, n.previous].filter((e) => e !== void 0).some((t) => Se(e.headers[he], b(e.headers.cookie, x), t.secret))) return E(403, { error: "csrf_rejected" });
702
+ let a;
610
703
  try {
611
- o = JSON.parse(new TextDecoder().decode(e.rawBody));
704
+ a = JSON.parse(new TextDecoder().decode(e.rawBody));
612
705
  } catch {
613
- return j(400, { error: "invalid_input" });
706
+ return E(400, { error: "invalid_input" });
614
707
  }
615
- if (!o || typeof o != "object" || Array.isArray(o)) return j(400, { error: "invalid_input" });
616
- let s = o;
617
- if (!e.store) return j(503, { error: "store_unavailable" });
618
- let c = K(e.store);
619
- if (a && n(t)) {
620
- if (Object.keys(s).length !== 0) return j(400, { error: "invalid_input" });
621
- let n = typeof W.guest.secret == "function" ? W.guest.secret() : W.guest.secret, r = f(O(e.headers, n)?.subject);
622
- if (!r || r.tenantId !== W.guest.tenantId) return j(403, { error: "credential_rejected" });
623
- let i = await v.runPromise(v.result(c.isLive(r)));
624
- if (y.isFailure(i)) return j(503, { error: "store_unavailable" });
625
- if (!i.success) return j(403, { error: "credential_rejected" });
708
+ if (!a || typeof a != "object" || Array.isArray(a)) return E(400, { error: "invalid_input" });
709
+ let o = a;
710
+ if (!e.store) return E(503, { error: "store_unavailable" });
711
+ let s = W(e.store);
712
+ if (i && I(t)) {
713
+ if (Object.keys(o).length !== 0) return E(400, { error: "invalid_input" });
714
+ let n = typeof B.guest.secret == "function" ? B.guest.secret() : B.guest.secret, r = te(C(e.headers, n)?.subject);
715
+ if (!r || r.tenantId !== B.guest.tenantId) return E(403, { error: "credential_rejected" });
716
+ let i = await g.runPromise(g.result(s.isLive(r)));
717
+ if (_.isFailure(i)) return E(503, { error: "store_unavailable" });
718
+ if (!i.success) return E(403, { error: "credential_rejected" });
626
719
  let a = Z(e, t, r);
627
720
  return {
628
- ...j(200, { authorizationUrl: a.headers?.location }),
721
+ ...E(200, { authorizationUrl: a.headers?.location }),
629
722
  headers: {
630
723
  "cache-control": "no-store",
631
724
  "set-cookie": a.headers?.["set-cookie"] ?? []
632
725
  }
633
726
  };
634
727
  }
635
- if (Object.keys(s).some((e) => e !== "credential" && e !== "confirmed") || typeof s.credential != "string" || s.confirmed !== !0) return j(400, { error: "invalid_input" });
636
- let d = i(), p = D(s.credential);
637
- if (!d || !p || d.guest.tenantId !== W.guest.tenantId || p.guestId !== d.guest.id || p.deviceId !== d.guest.metadata?.guestDeviceId) return j(403, { error: "upgrade_handoff_rejected" });
638
- let m = await v.runPromise(v.result(c.isLive(d.guest)));
639
- if (y.isFailure(m)) return j(503, { error: "store_unavailable" });
640
- if (!m.success) return j(403, { error: "credential_rejected" });
641
- let h = await v.runPromise(l({
642
- profile: d.profile,
643
- credential: s.credential,
728
+ let c = t === "merge";
729
+ if (Object.keys(o).some((e) => e !== "credential" && e !== "confirmed" && !(c && e === "requestId")) || typeof o.credential != "string" || o.confirmed !== !0 || c && typeof o.requestId != "string") return E(400, { error: "invalid_input" });
730
+ let l = r(), u = be(o.credential);
731
+ if (!l || !u || l.guest.tenantId !== B.guest.tenantId || u.guestId !== l.guest.id || u.deviceId !== l.guest.metadata?.guestDeviceId) return E(403, { error: "upgrade_handoff_rejected" });
732
+ if (c) {
733
+ let t = await g.runPromise(p({
734
+ profile: l.profile,
735
+ credential: o.credential,
736
+ guestId: l.guest.id,
737
+ requestId: o.requestId,
738
+ store: e.store,
739
+ guest: B.guest,
740
+ service: s,
741
+ users: k.users,
742
+ config: k.auth,
743
+ registry: Pe,
744
+ privacy: Fe,
745
+ ipAddress: e.remoteAddr ?? null,
746
+ userAgent: e.headers["user-agent"] ?? null
747
+ }));
748
+ return t.kind === "refused" ? E(t.status, {
749
+ error: t.code,
750
+ message: t.message
751
+ }) : {
752
+ ...E(200, {
753
+ merged: !0,
754
+ subject: t.subject,
755
+ replayed: t.merged.replayed
756
+ }),
757
+ headers: {
758
+ "cache-control": "no-store",
759
+ "set-cookie": [G(z), t.setCookie]
760
+ }
761
+ };
762
+ }
763
+ let d = await g.runPromise(g.result(s.isLive(l.guest)));
764
+ if (_.isFailure(d)) return E(503, { error: "store_unavailable" });
765
+ if (!d.success) return E(403, { error: "credential_rejected" });
766
+ let h = await g.runPromise(f({
767
+ profile: l.profile,
768
+ credential: o.credential,
644
769
  store: e.store,
645
- guest: W.guest,
646
- service: c,
770
+ guest: B.guest,
771
+ service: s,
647
772
  users: k.users,
648
773
  config: k.auth,
649
- ...W.configForTransaction ? { configForTransaction: W.configForTransaction } : {},
774
+ ...B.configForTransaction ? { configForTransaction: B.configForTransaction } : {},
650
775
  ipAddress: e.remoteAddr ?? null,
651
776
  userAgent: e.headers["user-agent"] ?? null
652
777
  }));
653
- return h.kind === "refused" ? j(h.status, {
778
+ return h.kind === "refused" ? E(h.status, {
654
779
  error: h.code,
655
780
  message: h.message
656
781
  }) : {
657
- ...j(200, {
782
+ ...E(200, {
658
783
  upgraded: !0,
659
784
  subject: h.subject
660
785
  }),
661
786
  headers: {
662
787
  "cache-control": "no-store",
663
- "set-cookie": [q(U), h.setCookie]
788
+ "set-cookie": [G(z), h.setCookie]
664
789
  }
665
790
  };
666
- }, we = {
791
+ }, Ke = async (e) => {
792
+ let t = C(e.headers, S(k.auth))?.subject;
793
+ if (!e.store || t?.type !== "user" || t.kind === "guest" || typeof t.tenantId != "string" || typeof t.metadata?.sessionId != "string") return null;
794
+ try {
795
+ let n = await g.runPromise(_e(e.store).findSession(t.metadata.sessionId));
796
+ if (!n || n.userId !== t.id || n.tenantId !== t.tenantId || !(n.expiresAt.getTime() > Date.now()) || n.rotatedAt !== null && n.rotatedAt !== void 0) return null;
797
+ let r = await g.runPromise(k.users.findById(t.id));
798
+ return !r || r.tenantId !== t.tenantId ? null : {
799
+ id: t.id,
800
+ tenantId: t.tenantId,
801
+ sessionId: t.metadata.sessionId
802
+ };
803
+ } catch {
804
+ return "unavailable";
805
+ }
806
+ }, qe = (e) => {
807
+ let t = S(k.auth);
808
+ return [t.current, t.previous].filter((e) => e !== void 0).some((t) => Se(e.headers[he], b(e.headers.cookie, x), t.secret));
809
+ }, Je = async (e) => {
810
+ let t = e.path.slice((A + "/links").length).replace(/^\//, "");
811
+ if (t === "csrf") {
812
+ if (e.method !== "GET") return E(405, { error: "method_not_allowed" });
813
+ let t = S(k.auth), n = ye(t.current.secret);
814
+ return {
815
+ ...E(200, { token: n }),
816
+ headers: {
817
+ "cache-control": "no-store",
818
+ "set-cookie": y(x, n, {
819
+ path: "/",
820
+ httpOnly: !1,
821
+ secure: N,
822
+ sameSite: "lax",
823
+ maxAgeSeconds: j,
824
+ ...k.auth.cookieDomain ? { domain: k.auth.cookieDomain } : {}
825
+ })
826
+ }
827
+ };
828
+ }
829
+ let n = await Ke(e);
830
+ if (n === "unavailable") return Q(503, { error: "store_unavailable" });
831
+ if (!n) return Q(401, { error: "credential_rejected" });
832
+ if (t === "") {
833
+ if (e.method !== "GET") return E(405, { error: "method_not_allowed" });
834
+ let t = await g.runPromise(Y(e).listForUser(n.id));
835
+ return Q(200, { links: t.filter((e) => e.userId === n.id).map((e) => ({
836
+ provider: e.provider,
837
+ connectedAt: e.createdAt.getTime(),
838
+ lastUsedAt: e.lastLoginAt?.getTime() ?? null
839
+ })) });
840
+ }
841
+ let [r, i, ...a] = t.split("/");
842
+ if (!I(r) || a.length > 0 || i !== void 0 && i !== "remove") return E(404, { error: "not_found" });
843
+ if (e.method !== "POST") return E(405, { error: "method_not_allowed" });
844
+ if (!qe(e)) return E(403, { error: "csrf_rejected" });
845
+ if (i === void 0) {
846
+ let t = Z(e, r, void 0, void 0, {
847
+ u: n.id,
848
+ t: n.tenantId,
849
+ sid: n.sessionId
850
+ }), i = t.headers?.location;
851
+ return t.status !== 302 || !i ? t : {
852
+ ...E(200, { authorizationUrl: i }),
853
+ headers: {
854
+ "cache-control": "no-store",
855
+ "set-cookie": t.headers["set-cookie"]
856
+ }
857
+ };
858
+ }
859
+ let o = await g.runPromise(k.users.findById(n.id)), s = typeof o?.passwordHash == "string" && o.passwordHash.length > 0;
860
+ if (k.identities === void 0) {
861
+ if (!e.store) return Q(503, { error: "store_unavailable" });
862
+ let t = await e.store.transactional(async (e) => {
863
+ let t = (await e.query({
864
+ table: c,
865
+ predicate: v("userId", n.id),
866
+ order: [],
867
+ take: 64,
868
+ skip: void 0,
869
+ projection: void 0,
870
+ lock: "update"
871
+ })).filter((e) => e.userId === n.id), i = t.find((e) => e.provider === r);
872
+ return i ? !s && t.length <= 1 ? "last_sign_in_method" : (await e.delete(c, String(i.id)), "removed") : "not_found";
873
+ });
874
+ return t === "removed" ? Q(200, { removed: r }) : Q(t === "not_found" ? 404 : 409, { error: t });
875
+ }
876
+ let l = await g.runPromise(Y(e).listForUser(n.id));
877
+ return l.some((e) => e.provider === r) ? !s && l.length <= 1 ? Q(409, { error: "last_sign_in_method" }) : (await g.runPromise(Y(e).remove(n.id, r)), Q(200, { removed: r })) : Q(404, { error: "not_found" });
878
+ }, Ye = {
667
879
  method: "*",
668
- path: P,
880
+ path: A,
669
881
  handle: async (t) => {
670
- if (t.path.startsWith(P + "/platform/")) return Se(t);
671
- if (t.path.startsWith(P + "/upgrade/")) try {
672
- return await Ce(t);
882
+ if (t.path === A + "/providers") return t.method === "GET" ? Q(200, { providers: [...Ne] }) : E(405, { error: "method_not_allowed" });
883
+ if (t.path === A + "/links" || t.path.startsWith(A + "/links/")) try {
884
+ return await Je(t);
885
+ } catch (t) {
886
+ if (t instanceof e) return X(t.status, t.code, t.message);
887
+ throw t;
888
+ }
889
+ if (t.path.startsWith(A + "/platform/")) return We(t);
890
+ if (t.path.startsWith(A + "/upgrade/")) try {
891
+ return await Ge(t);
673
892
  } catch (t) {
674
893
  if (t instanceof e) return X(t.status, t.code, t.message);
675
894
  throw t;
676
895
  }
677
- let n = ve(t.path);
678
- if (!n) return j(404, { error: "not_found" });
896
+ let n = Re(t.path);
897
+ if (!n) return E(404, { error: "not_found" });
679
898
  try {
680
- return n.isCallback ? t.method !== "GET" && t.method !== "POST" ? j(405, { error: "method_not_allowed" }) : await ye(t, n.id) : t.method === "GET" ? Z(t, n.id) : j(405, { error: "method_not_allowed" });
899
+ return n.isCallback ? t.method !== "GET" && t.method !== "POST" ? E(405, { error: "method_not_allowed" }) : await Ve(t, n.id) : t.method === "GET" ? Z(t, n.id) : E(405, { error: "method_not_allowed" });
681
900
  } catch (t) {
682
901
  if (t instanceof e) return X(t.status, t.code, t.message);
683
902
  throw t;
684
903
  }
685
904
  }
686
- }, Te = [
905
+ }, Xe = [
687
906
  "store:write",
688
907
  "network:outbound:oauth2.googleapis.com",
689
908
  "network:outbound:www.googleapis.com",
@@ -694,47 +913,97 @@ var ue = "/auth/social", de = 600, fe = "voltro:oauth", A = {
694
913
  "network:outbound:id.twitch.tv",
695
914
  "network:outbound:login.microsoftonline.com",
696
915
  "network:outbound:api.epicgames.dev",
697
- ...[...V.values()].flatMap((e) => e.permissions)
698
- ], Ee = (e, t) => {
699
- let n = z[e];
916
+ ...F === void 0 ? [] : ["network:outbound:steamcommunity.com"],
917
+ ...[...L.values()].flatMap((e) => e.permissions)
918
+ ], Ze = (e, t) => {
919
+ let n = je[e];
700
920
  return t === 0 ? n?.clientId !== void 0 : e === "apple" ? t === 1 ? n?.appleKey?.teamId !== void 0 : t === 2 ? n?.appleKey?.keyId !== void 0 : n?.appleKey?.privateKey !== void 0 : n?.clientSecret !== void 0;
701
- }, De = B.flatMap((e) => A[e].map((t, n) => ({
921
+ }, Qe = P.flatMap((e) => T[e].map((t, n) => ({
702
922
  name: t.name,
703
- required: !Ee(e, n),
923
+ required: !Ze(e, n),
704
924
  secret: t.secret,
705
925
  description: t.description
706
- }))), Oe = k.auth.secret === void 0 && k.auth.secrets === void 0 ? [{
926
+ }))), $e = k.auth.secret === void 0 && k.auth.secrets === void 0 ? [{
707
927
  name: "VOLTRO_SESSION_SECRET",
708
928
  required: !0,
709
929
  secret: !0,
710
930
  generate: "base64url",
711
931
  description: "Project key for signed login handoffs and ordinary sessions."
712
932
  }] : [];
713
- return re({
933
+ return pe({
714
934
  name: k.name ? `@voltro/plugin-auth-social#${k.name}` : "@voltro/plugin-auth-social",
715
935
  description: "Social login — Google / GitHub / Apple / Discord / Twitch / Microsoft / Epic, and game sign-in with Steam / EOS / console tickets. Mandatory S256 + state, JWKS-verified ID tokens, a deliberate account-linking policy, and sessions issued through @voltro/plugin-auth.",
716
- permissions: Te,
936
+ permissions: Xe,
717
937
  declaredEnv: [
718
- ...De,
719
- ...[...V.values()].flatMap((e) => e.declaredEnv),
720
- ...Oe
938
+ ...Qe,
939
+ ...[...L.values()].flatMap((e) => e.declaredEnv),
940
+ ...$e
721
941
  ],
722
- extendSchema: { tables: c },
723
- httpRoutes: [we],
724
- onActivate: (e) => v.sync(() => {
725
- for (let e of B) J(e);
726
- for (let e of V.values()) e.check();
727
- let n = E(k.auth);
728
- if (ce({ exp: Math.floor(Date.now() / 1e3) + F }, n.current.secret, "social-login"), n.previous && n.previous.secret.length < 32) throw new t("socialAuthPlugin: previous project signing key is too short");
942
+ extendSchema: { tables: d },
943
+ httpRoutes: [Ye],
944
+ subjectPrivacy: {
945
+ tables: [c, s],
946
+ kinds: ["user"]
947
+ },
948
+ subjectMerge: {
949
+ tables: [c, s],
950
+ kinds: ["guest"]
951
+ },
952
+ onMergeAccounts: (e) => g.promise(async () => {
953
+ let t = (t, n, r) => e.store.query({
954
+ table: t,
955
+ predicate: v(n, r),
956
+ order: [],
957
+ take: void 0,
958
+ skip: void 0,
959
+ projection: void 0,
960
+ lock: "update"
961
+ }), n = new Set((await t(c, "userId", e.targetId)).map((e) => String(e.provider)));
962
+ for (let r of await t(c, "userId", e.sourceId)) r.userId === e.sourceId && (n.has(String(r.provider)) ? await e.store.delete(c, String(r.id)) : (await e.store.update(c, String(r.id), { userId: e.targetId }), n.add(String(r.provider))));
963
+ }),
964
+ bindDataStore: (e, t) => {
965
+ if (J ??= e, F !== void 0 && U === void 0 && t?.hotStore !== void 0) {
966
+ let e = t.hotStore;
967
+ U = () => e();
968
+ }
969
+ Pe ??= t?.accountMergeRegistry, Fe ??= t?.privacyRegistry, typeof w.users == "function" && O.current === void 0 && (O.current = w.users(t?.sql === void 0 ? { store: e } : {
970
+ store: e,
971
+ sql: t.sql
972
+ }));
973
+ },
974
+ onExport: (e) => g.suspend(() => Ie().listForUser(e).pipe(g.flatMap((t) => g.map(Le(e), (n) => ({
975
+ connections: t.filter((t) => t.userId === e).map((e) => ({
976
+ provider: e.provider,
977
+ email: e.email,
978
+ emailVerified: e.emailVerified,
979
+ connectedAt: e.createdAt.toISOString(),
980
+ lastUsedAt: e.lastLoginAt?.toISOString() ?? null
981
+ })),
982
+ mergedGuests: n.map((e) => ({
983
+ guestId: String(e.sourceId),
984
+ mergedAt: new Date(e.mergedAt).toISOString()
985
+ }))
986
+ }))))),
987
+ onErase: (e) => g.suspend(() => {
988
+ let t = Ie();
989
+ return t.listForUser(e).pipe(g.flatMap((n) => g.forEach(n.filter((t) => t.userId === e), (n) => t.remove(e, n.provider), { discard: !0 })), g.andThen(g.flatMap(Le(e), (e) => g.promise(async () => {
990
+ for (let t of e) await J.delete(s, String(t.id));
991
+ }))));
992
+ }),
993
+ onActivate: (e) => g.sync(() => {
994
+ for (let e of P) K(e);
995
+ for (let e of L.values()) e.check();
996
+ let n = S(k.auth);
997
+ if (xe({ exp: Math.floor(Date.now() / 1e3) + j }, n.current.secret, "social-login"), n.previous && n.previous.secret.length < 32) throw new t("socialAuthPlugin: previous project signing key is too short");
729
998
  e.logger.info("social auth active", {
730
- prefix: P,
731
- providers: B.join(","),
732
- platforms: [...V.keys()].join(","),
733
- linkPolicy: L,
734
- stateTtlSeconds: F
999
+ prefix: A,
1000
+ providers: Ne.join(","),
1001
+ platforms: [...L.keys()].join(","),
1002
+ linkPolicy: Ae,
1003
+ stateTtlSeconds: j
735
1004
  });
736
1005
  }),
737
- onDeactivate: () => v.void
1006
+ onDeactivate: () => g.void
738
1007
  });
739
1008
  };
740
- export { P as socialAuthPlugin };
1009
+ export { O as socialAuthPlugin };