@quatronic/sdk 0.9.0-test.ce03797 → 0.9.1-rc.3

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.
Files changed (75) hide show
  1. package/README.md +0 -6
  2. package/dist/{chunk-VQKYPW5V.js → chunk-IFESUTF2.js} +3 -7
  3. package/dist/chunk-IFESUTF2.js.map +1 -0
  4. package/dist/{chunk-WOFBDOMY.js → chunk-POZI4OKJ.js} +2 -2
  5. package/dist/{chunk-YCKDMG4B.js → chunk-TPBRMW5N.js} +1 -30
  6. package/dist/chunk-TPBRMW5N.js.map +1 -0
  7. package/dist/{chunk-P5GBQVO7.js → chunk-YFZB5EW6.js} +2 -2
  8. package/dist/cli/skills-postinstall.js +6 -13
  9. package/dist/cli/skills.js +5 -11
  10. package/dist/eslint/index.d.ts +1 -11
  11. package/dist/eslint/index.js +4 -123
  12. package/dist/eslint/index.js.map +1 -1
  13. package/dist/next/auth/index.d.ts +0 -50
  14. package/dist/next/auth/index.js +101 -504
  15. package/dist/next/auth/index.js.map +1 -1
  16. package/dist/next/boot/index.js +3 -3
  17. package/dist/next/db/index.js +1 -1
  18. package/dist/next/sentry/client.js +3 -3
  19. package/dist/next/sentry/client.js.map +1 -1
  20. package/dist/next/sentry/index.js +1 -1
  21. package/dist/next/sentry/register.js +3 -3
  22. package/dist/node/sentry/index.js +1 -1
  23. package/dist/node/sentry/register.js +2 -2
  24. package/package.json +2 -75
  25. package/skills/catalog.json +0 -3
  26. package/skills/qore-add-api-route/SKILL.md +1 -1
  27. package/skills/qore-add-connection/SKILL.next.md +1 -3
  28. package/skills/qore-add-connection/SKILL.node.md +1 -3
  29. package/skills/qore-add-env-key/SKILL.md +9 -174
  30. package/skills/qore-add-feature/SKILL.md +1 -1
  31. package/skills/qore-add-integration/SKILL.next.md +2 -4
  32. package/skills/qore-add-integration/SKILL.node.md +6 -6
  33. package/skills/qore-add-page/SKILL.md +1 -1
  34. package/skills/qore-author-skill/SKILL.md +1 -1
  35. package/skills/qore-debug-issue/SKILL.md +0 -10
  36. package/skills/qore-observability/SKILL.md +0 -17
  37. package/skills/qore-secure-io/SKILL.md +0 -15
  38. package/skills/qore-ship-checklist/SKILL.md +0 -10
  39. package/skills/qore-translate-strings/SKILL.md +0 -10
  40. package/skills/qore-use-addons/SKILL.md +0 -2
  41. package/skills/qore-use-database/SKILL.md +0 -2
  42. package/skills/qore-use-design-system/SKILL.md +1 -1
  43. package/skills/qore-use-mail-domain/SKILL.next.md +1 -1
  44. package/skills/qore-use-mail-domain/SKILL.node.md +2 -2
  45. package/skills/qore-use-permissions/SKILL.md +0 -10
  46. package/dist/chunk-7XIDABOQ.js +0 -83
  47. package/dist/chunk-7XIDABOQ.js.map +0 -1
  48. package/dist/chunk-VQKYPW5V.js.map +0 -1
  49. package/dist/chunk-YCKDMG4B.js.map +0 -1
  50. package/dist/chunk-YXIYI7R2.js +0 -23
  51. package/dist/chunk-YXIYI7R2.js.map +0 -1
  52. package/dist/context-B_u-vpkw.d.ts +0 -111
  53. package/dist/expo/auth/index.d.ts +0 -8
  54. package/dist/expo/auth/index.js +0 -177
  55. package/dist/expo/auth/index.js.map +0 -1
  56. package/dist/expo/config/index.d.ts +0 -16
  57. package/dist/expo/config/index.js +0 -17
  58. package/dist/expo/config/index.js.map +0 -1
  59. package/dist/expo/log/index.d.ts +0 -9
  60. package/dist/expo/log/index.js +0 -16
  61. package/dist/expo/log/index.js.map +0 -1
  62. package/dist/expo/query/index.d.ts +0 -15
  63. package/dist/expo/query/index.js +0 -52
  64. package/dist/expo/query/index.js.map +0 -1
  65. package/dist/expo/sentry/index.d.ts +0 -29
  66. package/dist/expo/sentry/index.js +0 -93
  67. package/dist/expo/sentry/index.js.map +0 -1
  68. package/dist/expo/testing/index.d.ts +0 -32
  69. package/dist/expo/testing/index.js +0 -57
  70. package/dist/expo/testing/index.js.map +0 -1
  71. package/skills/qore-mobile-add-screen/SKILL.md +0 -58
  72. package/skills/qore-mobile-call-server/SKILL.md +0 -74
  73. package/skills/qore-mobile-run-on-device/SKILL.md +0 -41
  74. /package/dist/{chunk-WOFBDOMY.js.map → chunk-POZI4OKJ.js.map} +0 -0
  75. /package/dist/{chunk-P5GBQVO7.js.map → chunk-YFZB5EW6.js.map} +0 -0
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  runAuthMigrations
3
- } from "../../chunk-YCKDMG4B.js";
3
+ } from "../../chunk-TPBRMW5N.js";
4
4
  import "../../chunk-4MBB2UQW.js";
5
5
  import {
6
6
  getLogger,
@@ -8,8 +8,8 @@ import {
8
8
  } from "../../chunk-MET4SIMB.js";
9
9
 
10
10
  // src/next/auth/createAuthRouteHandlers.ts
11
- import { NextResponse as NextResponse2 } from "next/server";
12
- import { eq as eq3 } from "drizzle-orm";
11
+ import { NextResponse } from "next/server";
12
+ import { eq as eq2 } from "drizzle-orm";
13
13
  import { decodeJwt as decodeJwt3 } from "jose";
14
14
 
15
15
  // src/auth-core/crypto.ts
@@ -119,8 +119,7 @@ function sessionCookie(opts) {
119
119
  }
120
120
  return null;
121
121
  }
122
- const token = sign;
123
- return { issue, clear, read, token };
122
+ return { issue, clear, read };
124
123
  }
125
124
 
126
125
  // src/auth-core/kcClient.ts
@@ -153,7 +152,7 @@ function createKcClient(cfg) {
153
152
  response_type: "code",
154
153
  client_id: cfg.clientId,
155
154
  redirect_uri: redirectUri,
156
- scope: [scope(), ...args.extraScopes ?? []].join(" "),
155
+ scope: scope(),
157
156
  state: args.state,
158
157
  code_challenge: args.codeChallenge,
159
158
  code_challenge_method: "S256"
@@ -164,7 +163,6 @@ function createKcClient(cfg) {
164
163
  if (args.prompt) params.set("prompt", args.prompt);
165
164
  if (args.maxAge !== void 0) params.set("max_age", String(args.maxAge));
166
165
  if (args.idTokenHint) params.set("id_token_hint", args.idTokenHint);
167
- if (args.uiLocales) params.set("ui_locales", args.uiLocales);
168
166
  return `${authorizeUrl}?${params.toString().replace(/\+/g, "%20")}`;
169
167
  }
170
168
  function buildEndSessionUrl(args) {
@@ -294,10 +292,7 @@ var sessions = authSchema.table(
294
292
  createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
295
293
  updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
296
294
  revokedAt: timestamp("revoked_at", { withTimezone: true }),
297
- pendingIdentityConfirm: boolean("pending_identity_confirm").notNull().default(false),
298
- // "web" (cookie) or "mobile" (bearer token held by the phone). Decides the
299
- // lifetime bounds and whether an Authorization header may present it.
300
- kind: varchar("kind", { length: 16 }).notNull().default("web")
295
+ pendingIdentityConfirm: boolean("pending_identity_confirm").notNull().default(false)
301
296
  },
302
297
  (t) => ({
303
298
  userSubIdx: index("ix_auth_sessions_user_sub").on(t.userSub)
@@ -321,26 +316,8 @@ var loginState = authSchema.table("login_state", {
321
316
  // being replaced and/or the address the user typed. The callback compares
322
317
  // Keycloak's answer against these instead of adopting whatever comes back.
323
318
  expectedSub: varchar("expected_sub", { length: 64 }),
324
- expectedEmail: varchar("expected_email", { length: 320 }),
325
- // Set only on a mobile login: the app's PKCE challenge (base64url SHA-256 of
326
- // its verifier), where to send the handoff code, and the language for
327
- // Keycloak's pages. A row with `mobileRedirect` is a mobile login.
328
- mobileChallenge: varchar("mobile_challenge", { length: 64 }),
329
- mobileRedirect: text("mobile_redirect"),
330
- uiLocales: varchar("ui_locales", { length: 16 })
319
+ expectedEmail: varchar("expected_email", { length: 320 })
331
320
  });
332
- var mobileHandoffCodes = authSchema.table(
333
- "mobile_handoff_codes",
334
- {
335
- codeHash: varchar("code_hash", { length: 64 }).primaryKey(),
336
- sessionId: uuid("session_id").notNull(),
337
- challenge: varchar("challenge", { length: 64 }).notNull(),
338
- expiresAt: timestamp("expires_at", { withTimezone: true }).notNull()
339
- },
340
- (t) => ({
341
- expiresIdx: index("ix_auth_mobile_handoff_expires").on(t.expiresAt)
342
- })
343
- );
344
321
 
345
322
  // src/auth-core/refreshStore.ts
346
323
  var SESSION_CACHE_TTL_MS = 5e3;
@@ -361,8 +338,7 @@ function createRefreshStore(opts) {
361
338
  refreshCt: ciphertext,
362
339
  refreshIv: iv,
363
340
  refreshExpiresAt: input.refreshExpiresAt,
364
- pendingIdentityConfirm: input.pendingIdentityConfirm ?? false,
365
- kind: input.kind ?? "web"
341
+ pendingIdentityConfirm: input.pendingIdentityConfirm ?? false
366
342
  }).returning({ id: sessions.id });
367
343
  return row.id;
368
344
  }
@@ -380,8 +356,7 @@ function createRefreshStore(opts) {
380
356
  refreshToken,
381
357
  refreshExpiresAt: row.refreshExpiresAt,
382
358
  createdAt: row.createdAt,
383
- updatedAt: row.updatedAt,
384
- kind: row.kind === "mobile" ? "mobile" : "web"
359
+ updatedAt: row.updatedAt
385
360
  };
386
361
  }
387
362
  async function getSession(id) {
@@ -575,58 +550,6 @@ async function createIdentityHandoff(opts) {
575
550
  return { issue, read, clear };
576
551
  }
577
552
 
578
- // src/auth-core/mobile.ts
579
- import { createHash, randomBytes, timingSafeEqual } from "crypto";
580
- var MOBILE_HANDOFF_TTL_SEC = 60;
581
- var CHALLENGE_RE = /^[A-Za-z0-9_-]{43}$/;
582
- var VERIFIER_RE = /^[A-Za-z0-9_-]{43,128}$/;
583
- var BEARER_RE = /^Bearer ([A-Za-z0-9_-]+\.[A-Za-z0-9_-]+)$/;
584
- var CODE_RE = /^[A-Za-z0-9_-]{43}$/;
585
- function sha256b64url(value) {
586
- return createHash("sha256").update(value).digest("base64url");
587
- }
588
- function newHandoffCode() {
589
- return randomBytes(32).toString("base64url");
590
- }
591
- function isHandoffCode(value) {
592
- return typeof value === "string" && CODE_RE.test(value);
593
- }
594
- function verifierMatches(verifier, challenge) {
595
- if (!VERIFIER_RE.test(verifier) || !CHALLENGE_RE.test(challenge)) return false;
596
- const a = Buffer.from(sha256b64url(verifier));
597
- const b = Buffer.from(challenge);
598
- return a.length === b.length && timingSafeEqual(a, b);
599
- }
600
- function bearerToken(header) {
601
- if (!header) return null;
602
- return BEARER_RE.exec(header)?.[1] ?? null;
603
- }
604
- function isAllowedMobileRedirect(raw, opts) {
605
- let url;
606
- try {
607
- url = new URL(raw);
608
- } catch {
609
- return false;
610
- }
611
- if (url.search || url.hash || raw.includes("?") || raw.includes("#")) return false;
612
- const scheme = url.protocol.slice(0, -1);
613
- if (opts.schemes.includes(scheme)) {
614
- return url.host === "auth" && url.pathname === "/return" && !url.username && !url.password;
615
- }
616
- if (opts.allowExpoGo && (scheme === "exp" || scheme === "exps")) {
617
- return url.pathname === "/--/auth/return" && !url.username && !url.password;
618
- }
619
- return false;
620
- }
621
- function withQuery(redirect, key, value) {
622
- return `${redirect}?${key}=${encodeURIComponent(value)}`;
623
- }
624
- var MOBILE_LOCALES = ["en", "nl"];
625
- function safeLocale(raw) {
626
- const tag = (raw ?? "").trim().toLowerCase().split(/[-_]/)[0];
627
- return MOBILE_LOCALES.includes(tag ?? "") ? tag : "en";
628
- }
629
-
630
553
  // src/auth-core/organizationClaim.ts
631
554
  function parseOrganizationClaim(raw) {
632
555
  if (!raw) return {};
@@ -740,7 +663,7 @@ function removeBoundState(cookieHeader, state) {
740
663
  import { decodeJwt as decodeJwt2 } from "jose";
741
664
 
742
665
  // src/next/auth/requireAuth.ts
743
- import { cookies, headers } from "next/headers";
666
+ import { cookies } from "next/headers";
744
667
  import { decodeJwt } from "jose";
745
668
 
746
669
  // src/next/auth/appAccess.ts
@@ -748,21 +671,6 @@ function rolesForClient(claims, clientId) {
748
671
  return claims.resource_access?.[clientId]?.roles ?? [];
749
672
  }
750
673
 
751
- // src/next/auth/sessionSource.ts
752
- async function sessionIdFrom(c, cookieHeader, authorization, mobileEnabled) {
753
- const fromCookie = await c.read(cookieHeader);
754
- if (fromCookie) return { id: fromCookie, via: "cookie" };
755
- if (!mobileEnabled) return null;
756
- const token = bearerToken(authorization);
757
- if (!token) return null;
758
- const fromBearer = await c.read(`${COOKIE_NAME}=${token}`);
759
- return fromBearer ? { id: fromBearer, via: "bearer" } : null;
760
- }
761
- function kindMatches(via, session) {
762
- const mobile = session.kind === "mobile";
763
- return via === "bearer" ? mobile : !mobile;
764
- }
765
-
766
674
  // src/next/auth/requireAuth.ts
767
675
  var AuthError = class extends Error {
768
676
  constructor(reason) {
@@ -777,17 +685,10 @@ function requireAuth(opts) {
777
685
  return async () => {
778
686
  const jar = await cookies();
779
687
  const raw = jar.get(COOKIE_NAME)?.value;
780
- const authorization = opts.mobile ? (await headers()).get("authorization") : null;
781
- const source = await sessionIdFrom(
782
- opts.cookies,
783
- raw ? `${COOKIE_NAME}=${raw}` : null,
784
- authorization,
785
- Boolean(opts.mobile)
786
- );
787
- if (!source) throw new AuthError("unauthenticated");
788
- const id = source.id;
688
+ const id = await opts.cookies.read(raw ? `${COOKIE_NAME}=${raw}` : null);
689
+ if (!id) throw new AuthError("unauthenticated");
789
690
  let session = await opts.refreshStore.getSession(id);
790
- if (!session || !kindMatches(source.via, session)) throw new AuthError("unauthenticated");
691
+ if (!session) throw new AuthError("unauthenticated");
791
692
  session = await refreshWithinSkew(
792
693
  {
793
694
  refreshStore: opts.refreshStore,
@@ -795,8 +696,7 @@ function requireAuth(opts) {
795
696
  skewSec,
796
697
  orgAlias: opts.orgAlias,
797
698
  idleTimeoutSec: opts.idleTimeoutSec,
798
- absoluteMaxSec: opts.absoluteMaxSec,
799
- mobile: opts.mobile
699
+ absoluteMaxSec: opts.absoluteMaxSec
800
700
  },
801
701
  id,
802
702
  session
@@ -821,9 +721,8 @@ function isDefinitiveRefreshFailure(err) {
821
721
  return err instanceof KcTokenError && err.status === 400 && err.oauthError === "invalid_grant";
822
722
  }
823
723
  async function refreshWithinSkew(opts, id, session) {
824
- const bounds = session.kind === "mobile" && opts.mobile ? opts.mobile : opts;
825
- const idleSec = bounds.idleTimeoutSec;
826
- const absoluteSec = bounds.absoluteMaxSec;
724
+ const idleSec = opts.idleTimeoutSec;
725
+ const absoluteSec = opts.absoluteMaxSec;
827
726
  const tooIdle = idleSec !== void 0 && Date.now() - session.updatedAt.getTime() > idleSec * 1e3;
828
727
  const tooOld = absoluteSec !== void 0 && Date.now() - session.createdAt.getTime() > absoluteSec * 1e3;
829
728
  if (tooIdle || tooOld) {
@@ -876,8 +775,8 @@ var KC_DEFAULT_ROLES = /* @__PURE__ */ new Set(["offline_access", "uma_authoriza
876
775
  function decodeJwtPayload(token) {
877
776
  const segment2 = token.split(".")[1];
878
777
  if (!segment2) throw new Error("Malformed JWT: missing payload segment");
879
- const json2 = Buffer.from(segment2, "base64url").toString("utf8");
880
- return JSON.parse(json2);
778
+ const json = Buffer.from(segment2, "base64url").toString("utf8");
779
+ return JSON.parse(json);
881
780
  }
882
781
  function extractRoles(payload, clientId) {
883
782
  const realm = payload.realm_access?.roles ?? [];
@@ -901,20 +800,8 @@ function permissionsForRoles(map, roles) {
901
800
  }
902
801
 
903
802
  // src/next/auth/types.ts
904
- function resolveMobileAuth(m) {
905
- if (!m) return void 0;
906
- return {
907
- schemes: m.schemes,
908
- allowExpoGo: m.allowExpoGo ?? false,
909
- offlineAccess: m.offlineAccess ?? false,
910
- idleTimeoutSec: m.sessionIdleTimeoutSec ?? DEFAULT_MOBILE_IDLE_TIMEOUT_SEC,
911
- absoluteMaxSec: m.sessionAbsoluteMaxSec ?? DEFAULT_MOBILE_ABSOLUTE_MAX_SEC
912
- };
913
- }
914
803
  var DEFAULT_SESSION_IDLE_TIMEOUT_SEC = 28800;
915
804
  var DEFAULT_SESSION_ABSOLUTE_MAX_SEC = 43200;
916
- var DEFAULT_MOBILE_IDLE_TIMEOUT_SEC = 30 * 86400;
917
- var DEFAULT_MOBILE_ABSOLUTE_MAX_SEC = 90 * 86400;
918
805
 
919
806
  // src/next/auth/authSpan.ts
920
807
  import { SpanStatusCode, trace } from "@opentelemetry/api";
@@ -946,170 +833,6 @@ function runAuthSpan(label, attributes3, fn) {
946
833
  });
947
834
  }
948
835
 
949
- // src/next/auth/mobileHandlers.ts
950
- import { NextResponse } from "next/server";
951
- import { eq as eq2, lt } from "drizzle-orm";
952
- var LOGIN_TTL_MS = 10 * 6e4;
953
- function json(body, status) {
954
- const res = NextResponse.json(body, { status });
955
- res.headers.set("Cache-Control", "no-store");
956
- return res;
957
- }
958
- async function handleMobileLogin(req, ctx) {
959
- return runAuthSpan(
960
- "Log in",
961
- { "qore.auth.event": "login_started", "qore.auth.surface": "mobile" },
962
- async (auth) => {
963
- const params = req.nextUrl.searchParams;
964
- const challenge = params.get("challenge");
965
- const redirect = params.get("redirect");
966
- if (!challenge || !CHALLENGE_RE.test(challenge)) {
967
- auth.fail("invalid_challenge");
968
- return json({ error: "invalid_challenge" }, 400);
969
- }
970
- if (!redirect || !isAllowedMobileRedirect(redirect, ctx.mobile)) {
971
- auth.fail("invalid_redirect");
972
- return json({ error: "invalid_redirect" }, 400);
973
- }
974
- const locale = safeLocale(params.get("locale"));
975
- const retried = params.get("retried") === "1";
976
- const state = randomB64Url(32);
977
- const codeVerifier = randomB64Url(48);
978
- const codeChallenge = await sha256B64Url(codeVerifier);
979
- const nonce = randomB64Url(32);
980
- await ctx.db.insert(loginState).values({
981
- state,
982
- codeVerifier,
983
- redirectPath: "/",
984
- expiresAt: new Date(Date.now() + LOGIN_TTL_MS),
985
- forcedReauth: retried,
986
- nonce,
987
- retried,
988
- expectedSub: null,
989
- expectedEmail: null,
990
- mobileChallenge: challenge,
991
- mobileRedirect: redirect,
992
- uiLocales: locale
993
- });
994
- getLogger().info(
995
- { event: "auth.login.started", surface: "mobile", state, forced_reauth: retried, locale },
996
- "auth login started"
997
- );
998
- const url = ctx.kcClient.buildAuthorizeUrl({
999
- state,
1000
- codeChallenge,
1001
- nonce,
1002
- ...retried ? { prompt: "login", maxAge: 0 } : { prompt: "select_account" },
1003
- extraScopes: ctx.mobile.offlineAccess ? ["offline_access"] : [],
1004
- uiLocales: locale
1005
- });
1006
- const res = NextResponse.redirect(url, 302);
1007
- res.headers.set("Cache-Control", "no-store");
1008
- res.headers.append("Set-Cookie", appendBoundState(req.headers.get("cookie"), state));
1009
- return res;
1010
- }
1011
- );
1012
- }
1013
- async function handleMobileRedeem(req, ctx) {
1014
- return runAuthSpan("Redeem mobile login", { "qore.auth.surface": "mobile" }, async (auth) => {
1015
- const log = getLogger();
1016
- let body;
1017
- try {
1018
- body = await req.json();
1019
- } catch {
1020
- auth.fail("invalid_request");
1021
- return json({ error: "invalid_request" }, 400);
1022
- }
1023
- const code = body?.code;
1024
- const verifier = body?.verifier;
1025
- if (!isHandoffCode(code) || typeof verifier !== "string" || !VERIFIER_RE.test(verifier)) {
1026
- auth.fail("invalid_request");
1027
- return json({ error: "invalid_request" }, 400);
1028
- }
1029
- const [rec] = await ctx.db.delete(mobileHandoffCodes).where(eq2(mobileHandoffCodes.codeHash, sha256b64url(code))).returning();
1030
- if (!rec) {
1031
- log.warn({ event: "auth.mobile.redeem_failed", reason: "unknown_code" }, "mobile redeem failed");
1032
- auth.fail("unknown_code");
1033
- return json({ error: "invalid_grant" }, 400);
1034
- }
1035
- const expired = rec.expiresAt.getTime() <= Date.now();
1036
- if (expired || !verifierMatches(verifier, rec.challenge)) {
1037
- await ctx.refreshStore.revokeSession(rec.sessionId);
1038
- const reason = expired ? "expired_code" : "verifier_mismatch";
1039
- log.warn({ event: "auth.mobile.redeem_failed", reason }, "mobile redeem failed");
1040
- auth.fail(reason);
1041
- return json({ error: "invalid_grant" }, 400);
1042
- }
1043
- const session = await ctx.refreshStore.getSession(rec.sessionId);
1044
- if (!session || session.kind !== "mobile") {
1045
- auth.fail("session_gone");
1046
- return json({ error: "invalid_grant" }, 400);
1047
- }
1048
- const token = await ctx.cookies.token(rec.sessionId);
1049
- const expiresAt = new Date(session.createdAt.getTime() + ctx.mobile.absoluteMaxSec * 1e3);
1050
- log.info({ event: "auth.mobile.redeemed", user_sub: session.userSub }, "mobile login redeemed");
1051
- auth.set("qore.auth.event", "mobile_redeemed");
1052
- return json({ token, expiresAt: expiresAt.toISOString() }, 200);
1053
- });
1054
- }
1055
- async function handleMobileLogout(req, ctx) {
1056
- return runAuthSpan(
1057
- "Log out",
1058
- { "qore.auth.event": "logout", "qore.auth.surface": "mobile" },
1059
- async () => {
1060
- const token = bearerToken(req.headers.get("authorization"));
1061
- const id = token ? await ctx.cookies.read(`${COOKIE_NAME}=${token}`) : null;
1062
- if (id) {
1063
- const session = await ctx.refreshStore.getSession(id);
1064
- if (session && session.kind === "mobile") {
1065
- try {
1066
- await ctx.kcClient.logout(session.refreshToken);
1067
- } catch {
1068
- }
1069
- await ctx.refreshStore.revokeSession(id);
1070
- getLogger().info(
1071
- { event: "auth.logout", method: "mobile", user_sub: session.userSub },
1072
- "auth logout"
1073
- );
1074
- }
1075
- }
1076
- const res = new NextResponse(null, { status: 204 });
1077
- res.headers.set("Cache-Control", "no-store");
1078
- return res;
1079
- }
1080
- );
1081
- }
1082
- function handleMobileResetPassword(req, ctx) {
1083
- const base = ctx.keycloakUrl.replace(/\/+$/, "");
1084
- const url = new URL(
1085
- `${base}/realms/${encodeURIComponent(ctx.realm)}/login-actions/reset-credentials`
1086
- );
1087
- url.searchParams.set("client_id", ctx.clientId);
1088
- url.searchParams.set("kc_locale", safeLocale(req.nextUrl.searchParams.get("locale")));
1089
- const res = NextResponse.redirect(url, 302);
1090
- res.headers.set("Cache-Control", "no-store");
1091
- return res;
1092
- }
1093
- function mobileLoginError(reason) {
1094
- switch (reason) {
1095
- case "access_denied":
1096
- return "cancelled";
1097
- case "expired_state":
1098
- case "authentication_expired":
1099
- case "login_required":
1100
- return "expired";
1101
- case "no_app_access":
1102
- return "no_app_access";
1103
- case "identity_mismatch":
1104
- return "identity_mismatch";
1105
- default:
1106
- return "failed";
1107
- }
1108
- }
1109
- async function pruneExpiredHandoffs(db) {
1110
- await db.delete(mobileHandoffCodes).where(lt(mobileHandoffCodes.expiresAt, /* @__PURE__ */ new Date()));
1111
- }
1112
-
1113
836
  // src/next/auth/createAuthRouteHandlers.ts
1114
837
  var AUTH_TIME_SKEW_SEC = 5;
1115
838
  var DEFAULT_IDENTITY_MISMATCH_PATH = "/login?reason=identity_mismatch";
@@ -1117,8 +840,7 @@ var LOGGED_OUT_PATH = "/api/auth/logged-out";
1117
840
  var CLEAR_SITE_DATA = '"cookies"';
1118
841
  function segment(req) {
1119
842
  const parts = req.nextUrl.pathname.split("/").filter(Boolean);
1120
- const last = parts[parts.length - 1] ?? "";
1121
- return parts[parts.length - 2] === "mobile" ? `mobile/${last}` : last;
843
+ return parts[parts.length - 1] ?? "";
1122
844
  }
1123
845
  function noStore(res) {
1124
846
  res.headers.set("Cache-Control", "no-store");
@@ -1146,9 +868,7 @@ async function createAuthRouteHandlers(opts) {
1146
868
  realm: opts.realm,
1147
869
  audience: opts.clientId
1148
870
  });
1149
- const ctx = { cookies: cookies3, refreshStore, handoff, kcClient, jwks, db: opts.db, publicOrigin: opts.publicOrigin, clientId: opts.clientId, requireAppRole: opts.requireAppRole !== false, orgAlias: opts.orgAlias, permissions: opts.permissions, identityMismatchPath: opts.identityMismatchPath, idleTimeoutSec: opts.sessionIdleTimeoutSec ?? DEFAULT_SESSION_IDLE_TIMEOUT_SEC, absoluteMaxSec: opts.sessionAbsoluteMaxSec ?? DEFAULT_SESSION_ABSOLUTE_MAX_SEC, mobile: resolveMobileAuth(opts.mobile), keycloakUrl: opts.keycloakUrl, realm: opts.realm };
1150
- const mobileCtx = ctx.mobile ? { ...ctx, mobile: ctx.mobile } : null;
1151
- const notFound = () => NextResponse2.json({ error: "not_found" }, { status: 404 });
871
+ const ctx = { cookies: cookies3, refreshStore, handoff, kcClient, jwks, db: opts.db, publicOrigin: opts.publicOrigin, clientId: opts.clientId, requireAppRole: opts.requireAppRole !== false, orgAlias: opts.orgAlias, permissions: opts.permissions, identityMismatchPath: opts.identityMismatchPath, idleTimeoutSec: opts.sessionIdleTimeoutSec ?? DEFAULT_SESSION_IDLE_TIMEOUT_SEC, absoluteMaxSec: opts.sessionAbsoluteMaxSec ?? DEFAULT_SESSION_ABSOLUTE_MAX_SEC };
1152
872
  async function GET(req) {
1153
873
  switch (segment(req)) {
1154
874
  case "login":
@@ -1156,11 +876,7 @@ async function createAuthRouteHandlers(opts) {
1156
876
  case "me":
1157
877
  return handleMe(req, ctx);
1158
878
  case "callback":
1159
- return mobileCtx ? handleCallbackMobileAware(req, ctx) : handleCallback(req, ctx);
1160
- case "mobile/login":
1161
- return mobileCtx ? handleMobileLogin(req, mobileCtx) : notFound();
1162
- case "mobile/reset-password":
1163
- return mobileCtx ? handleMobileResetPassword(req, mobileCtx) : notFound();
879
+ return handleCallback(req, ctx);
1164
880
  case "logout":
1165
881
  return handleLogoutRedirect(req, ctx);
1166
882
  case "logged-out":
@@ -1168,7 +884,7 @@ async function createAuthRouteHandlers(opts) {
1168
884
  case "identity-mismatch":
1169
885
  return handleIdentityMismatch(req, ctx);
1170
886
  default:
1171
- return NextResponse2.json({ error: "not_found" }, { status: 404 });
887
+ return NextResponse.json({ error: "not_found" }, { status: 404 });
1172
888
  }
1173
889
  }
1174
890
  async function POST(req) {
@@ -1181,12 +897,8 @@ async function createAuthRouteHandlers(opts) {
1181
897
  return handleBackchannelLogout(req, ctx);
1182
898
  case "confirm-identity":
1183
899
  return handleConfirmIdentity(req, ctx);
1184
- case "mobile/redeem":
1185
- return mobileCtx ? handleMobileRedeem(req, mobileCtx) : notFound();
1186
- case "mobile/logout":
1187
- return mobileCtx ? handleMobileLogout(req, mobileCtx) : notFound();
1188
900
  default:
1189
- return NextResponse2.json({ error: "not_found" }, { status: 404 });
901
+ return NextResponse.json({ error: "not_found" }, { status: 404 });
1190
902
  }
1191
903
  }
1192
904
  return { GET, POST };
@@ -1281,7 +993,7 @@ async function handleLogin(req, ctx) {
1281
993
  authorizePrompt === "id_token_hint" ? { idTokenHint } : { prompt: "select_account" }
1282
994
  )
1283
995
  });
1284
- const res = NextResponse2.redirect(url, 302);
996
+ const res = NextResponse.redirect(url, 302);
1285
997
  res.headers.append("Set-Cookie", appendBoundState(req.headers.get("cookie"), state));
1286
998
  res.headers.append("Set-Cookie", ctx.handoff.clear());
1287
999
  return res;
@@ -1290,28 +1002,17 @@ async function handleLogin(req, ctx) {
1290
1002
  }
1291
1003
  async function handleMe(req, ctx) {
1292
1004
  try {
1293
- const res = noStore(await handleMeInner(req, ctx));
1294
- if (ctx.mobile) res.headers.set("Vary", "Cookie, Authorization");
1295
- return res;
1005
+ return noStore(await handleMeInner(req, ctx));
1296
1006
  } catch (err) {
1297
1007
  getLogger().error({ err }, "auth /me failed unexpectedly");
1298
- return noStore(NextResponse2.json({ error: "internal" }, { status: 500 }));
1008
+ return noStore(NextResponse.json({ error: "internal" }, { status: 500 }));
1299
1009
  }
1300
1010
  }
1301
1011
  async function handleMeInner(req, ctx) {
1302
- const source = await sessionIdFrom(
1303
- ctx.cookies,
1304
- req.headers.get("cookie"),
1305
- req.headers.get("authorization"),
1306
- Boolean(ctx.mobile)
1307
- );
1308
- if (!source) return NextResponse2.json({ error: "unauthenticated" }, { status: 401 });
1309
- const id = source.id;
1310
- const bearer = source.via === "bearer";
1012
+ const id = await ctx.cookies.read(req.headers.get("cookie"));
1013
+ if (!id) return NextResponse.json({ error: "unauthenticated" }, { status: 401 });
1311
1014
  const existing = await ctx.refreshStore.getSession(id);
1312
- if (!existing || !kindMatches(source.via, existing)) {
1313
- return NextResponse2.json({ error: "unauthenticated" }, { status: 401 });
1314
- }
1015
+ if (!existing) return NextResponse.json({ error: "unauthenticated" }, { status: 401 });
1315
1016
  let session;
1316
1017
  try {
1317
1018
  session = await refreshWithinSkew(
@@ -1321,8 +1022,7 @@ async function handleMeInner(req, ctx) {
1321
1022
  skewSec: 30,
1322
1023
  orgAlias: ctx.orgAlias,
1323
1024
  idleTimeoutSec: ctx.idleTimeoutSec,
1324
- absoluteMaxSec: ctx.absoluteMaxSec,
1325
- mobile: ctx.mobile
1025
+ absoluteMaxSec: ctx.absoluteMaxSec
1326
1026
  },
1327
1027
  id,
1328
1028
  existing
@@ -1330,27 +1030,17 @@ async function handleMeInner(req, ctx) {
1330
1030
  } catch (err) {
1331
1031
  if (!(err instanceof AuthError)) throw err;
1332
1032
  if (err.reason === "refresh_unavailable") {
1333
- return NextResponse2.json({ error: "refresh_unavailable" }, { status: 503 });
1033
+ return NextResponse.json({ error: "refresh_unavailable" }, { status: 503 });
1334
1034
  }
1335
- const res = NextResponse2.json({ error: "session_expired" }, { status: 401 });
1336
- if (!bearer) res.headers.set("Set-Cookie", ctx.cookies.clear());
1035
+ const res = NextResponse.json({ error: "session_expired" }, { status: 401 });
1036
+ res.headers.set("Set-Cookie", ctx.cookies.clear());
1337
1037
  return res;
1338
1038
  }
1339
1039
  const claims = decodeJwt3(session.accessToken);
1340
1040
  if (ctx.requireAppRole && rolesForClient(claims, ctx.clientId).length === 0) {
1341
- return NextResponse2.json({ error: "no_app_access" }, { status: 403 });
1342
- }
1343
- if (bearer) {
1344
- return NextResponse2.json({
1345
- sub: session.userSub,
1346
- email: session.userEmail,
1347
- name: typeof claims.name === "string" ? claims.name : null,
1348
- organizationAlias: session.organizationAlias,
1349
- roles: rolesForClient(claims, ctx.clientId),
1350
- permissions: resolveMePermissions(ctx.permissions, session.accessToken, ctx.clientId)
1351
- });
1041
+ return NextResponse.json({ error: "no_app_access" }, { status: 403 });
1352
1042
  }
1353
- return NextResponse2.json({
1043
+ return NextResponse.json({
1354
1044
  user: { id: session.userSub, email: session.userEmail },
1355
1045
  organization: { id: session.organizationId, alias: session.organizationAlias },
1356
1046
  permissions: resolveMePermissions(ctx.permissions, session.accessToken, ctx.clientId)
@@ -1362,12 +1052,12 @@ async function handleRefresh(req, ctx) {
1362
1052
  const id = await ctx.cookies.read(req.headers.get("cookie"));
1363
1053
  if (!id) {
1364
1054
  auth.set("qore.auth.event", "refresh_skipped");
1365
- return NextResponse2.json({ error: "unauthenticated" }, { status: 401 });
1055
+ return NextResponse.json({ error: "unauthenticated" }, { status: 401 });
1366
1056
  }
1367
1057
  const session = await ctx.refreshStore.getSession(id);
1368
1058
  if (!session) {
1369
1059
  auth.set("qore.auth.event", "refresh_skipped");
1370
- return NextResponse2.json({ error: "unauthenticated" }, { status: 401 });
1060
+ return NextResponse.json({ error: "unauthenticated" }, { status: 401 });
1371
1061
  }
1372
1062
  try {
1373
1063
  await refreshWithinSkew(
@@ -1387,15 +1077,15 @@ async function handleRefresh(req, ctx) {
1387
1077
  auth.set("qore.auth.event", "refresh_failed");
1388
1078
  if (err.reason === "refresh_unavailable") {
1389
1079
  auth.fail("refresh_unavailable");
1390
- return NextResponse2.json({ error: "refresh_unavailable" }, { status: 503 });
1080
+ return NextResponse.json({ error: "refresh_unavailable" }, { status: 503 });
1391
1081
  }
1392
1082
  auth.fail("session_expired");
1393
- const res = NextResponse2.json({ error: "session_expired" }, { status: 401 });
1083
+ const res = NextResponse.json({ error: "session_expired" }, { status: 401 });
1394
1084
  res.headers.set("Set-Cookie", ctx.cookies.clear());
1395
1085
  return res;
1396
1086
  }
1397
1087
  auth.set("qore.auth.event", "session_refreshed");
1398
- return new NextResponse2(null, { status: 204 });
1088
+ return new NextResponse(null, { status: 204 });
1399
1089
  });
1400
1090
  }
1401
1091
  async function handleLogout(req, ctx) {
@@ -1423,7 +1113,7 @@ async function handleLogout(req, ctx) {
1423
1113
  );
1424
1114
  }
1425
1115
  }
1426
- const res = new NextResponse2(null, { status: 204 });
1116
+ const res = new NextResponse(null, { status: 204 });
1427
1117
  res.headers.set("Set-Cookie", ctx.cookies.clear());
1428
1118
  return res;
1429
1119
  });
@@ -1464,7 +1154,7 @@ async function handleLogoutRedirect(req, ctx) {
1464
1154
  postLogoutRedirectUri: landing.toString(),
1465
1155
  idTokenHint
1466
1156
  });
1467
- const res = NextResponse2.redirect(endSessionUrl, 302);
1157
+ const res = NextResponse.redirect(endSessionUrl, 302);
1468
1158
  res.headers.set("Set-Cookie", ctx.cookies.clear());
1469
1159
  return res;
1470
1160
  });
@@ -1473,7 +1163,7 @@ async function handleLoggedOut(req, ctx) {
1473
1163
  const target = safeRedirect(req.nextUrl.searchParams.get("redirect"));
1474
1164
  const attr = target.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/"/g, "&quot;");
1475
1165
  const literal = JSON.stringify(target).replace(/</g, "\\u003c");
1476
- const res = new NextResponse2(
1166
+ const res = new NextResponse(
1477
1167
  `<!doctype html><html><head><meta charset="utf-8"><meta http-equiv="refresh" content="0;url=${attr}"><title>Signing out\u2026</title></head><body><p>Signing out\u2026 <a href="${attr}">Continue</a></p><script>location.replace(${literal})</script></body></html>`,
1478
1168
  { status: 200, headers: { "Content-Type": "text/html; charset=utf-8" } }
1479
1169
  );
@@ -1488,43 +1178,44 @@ async function handleBackchannelLogout(req, ctx) {
1488
1178
  { "qore.auth.event": "logout", "qore.auth.method": "backchannel" },
1489
1179
  async (auth) => {
1490
1180
  const log = getLogger();
1491
- const logoutToken = new URLSearchParams(await req.text()).get("logout_token");
1492
- if (!logoutToken) {
1181
+ const form = await req.formData();
1182
+ const logoutToken = form.get("logout_token");
1183
+ if (typeof logoutToken !== "string") {
1493
1184
  auth.fail("missing_logout_token");
1494
- return new NextResponse2("missing logout_token", { status: 400 });
1185
+ return new NextResponse("missing logout_token", { status: 400 });
1495
1186
  }
1496
1187
  let claims;
1497
1188
  try {
1498
1189
  claims = await ctx.jwks.verify(logoutToken);
1499
1190
  } catch {
1500
1191
  auth.fail("invalid_logout_token");
1501
- return new NextResponse2("invalid logout_token", { status: 400 });
1192
+ return new NextResponse("invalid logout_token", { status: 400 });
1502
1193
  }
1503
1194
  if (!claims.events || !(BACKCHANNEL_EVENT in claims.events)) {
1504
1195
  auth.fail("invalid_events");
1505
- return new NextResponse2("invalid logout_token events", { status: 400 });
1196
+ return new NextResponse("invalid logout_token events", { status: 400 });
1506
1197
  }
1507
1198
  if (!claims.sub) {
1508
1199
  auth.fail("missing_sub");
1509
- return new NextResponse2("missing sub", { status: 400 });
1200
+ return new NextResponse("missing sub", { status: 400 });
1510
1201
  }
1511
1202
  await ctx.refreshStore.revokeByUser(claims.sub);
1512
1203
  log.info({ event: "auth.logout", method: "backchannel", user_sub: claims.sub }, "auth logout");
1513
- return new NextResponse2("ok", { status: 200 });
1204
+ return new NextResponse("ok", { status: 200 });
1514
1205
  }
1515
1206
  );
1516
1207
  }
1517
1208
  async function handleIdentityMismatch(req, ctx) {
1518
1209
  const handoff = await ctx.handoff.read(req.headers.get("cookie"));
1519
1210
  if (!handoff) {
1520
- return noStore(NextResponse2.json({ error: "no_pending_identity" }, { status: 404 }));
1211
+ return noStore(NextResponse.json({ error: "no_pending_identity" }, { status: 404 }));
1521
1212
  }
1522
1213
  const pending = await ctx.refreshStore.getPendingSession(handoff.sessionId);
1523
1214
  if (!pending) {
1524
- return noStore(NextResponse2.json({ error: "no_pending_identity" }, { status: 404 }));
1215
+ return noStore(NextResponse.json({ error: "no_pending_identity" }, { status: 404 }));
1525
1216
  }
1526
1217
  return noStore(
1527
- NextResponse2.json({
1218
+ NextResponse.json({
1528
1219
  expected: { email: handoff.expectedEmail },
1529
1220
  actual: { email: pending.userEmail }
1530
1221
  })
@@ -1539,12 +1230,12 @@ async function handleConfirmIdentity(req, ctx) {
1539
1230
  const handoff = await ctx.handoff.read(req.headers.get("cookie"));
1540
1231
  if (!handoff) {
1541
1232
  auth.fail("no_pending_identity");
1542
- return NextResponse2.json({ error: "no_pending_identity" }, { status: 409 });
1233
+ return NextResponse.json({ error: "no_pending_identity" }, { status: 409 });
1543
1234
  }
1544
1235
  const pending = await ctx.refreshStore.getPendingSession(handoff.sessionId);
1545
1236
  if (!pending) {
1546
1237
  auth.fail("no_pending_identity");
1547
- const res2 = NextResponse2.json({ error: "no_pending_identity" }, { status: 409 });
1238
+ const res2 = NextResponse.json({ error: "no_pending_identity" }, { status: 409 });
1548
1239
  res2.headers.append("Set-Cookie", ctx.handoff.clear());
1549
1240
  return res2;
1550
1241
  }
@@ -1562,14 +1253,14 @@ async function handleConfirmIdentity(req, ctx) {
1562
1253
  "auth identity confirm failed"
1563
1254
  );
1564
1255
  auth.fail("no_app_access");
1565
- const denied = NextResponse2.json({ error: "no_app_access" }, { status: 403 });
1256
+ const denied = NextResponse.json({ error: "no_app_access" }, { status: 403 });
1566
1257
  denied.headers.append("Set-Cookie", ctx.handoff.clear());
1567
1258
  return denied;
1568
1259
  }
1569
1260
  }
1570
1261
  if (!await ctx.refreshStore.confirmSession(handoff.sessionId)) {
1571
1262
  auth.fail("no_pending_identity");
1572
- const res2 = NextResponse2.json({ error: "no_pending_identity" }, { status: 409 });
1263
+ const res2 = NextResponse.json({ error: "no_pending_identity" }, { status: 409 });
1573
1264
  res2.headers.append("Set-Cookie", ctx.handoff.clear());
1574
1265
  return res2;
1575
1266
  }
@@ -1582,7 +1273,7 @@ async function handleConfirmIdentity(req, ctx) {
1582
1273
  },
1583
1274
  "auth identity confirmed"
1584
1275
  );
1585
- const res = new NextResponse2(null, { status: 204 });
1276
+ const res = new NextResponse(null, { status: 204 });
1586
1277
  res.headers.append(
1587
1278
  "Set-Cookie",
1588
1279
  await ctx.cookies.issue(handoff.sessionId, {
@@ -1599,48 +1290,14 @@ function resolveMePermissions(map, accessToken, clientId) {
1599
1290
  const roles = extractRoles(decodeJwtPayload(accessToken), clientId);
1600
1291
  return permissionsForRoles(map, roles);
1601
1292
  }
1602
- async function handleCallbackMobileAware(req, ctx) {
1603
- const state = req.nextUrl.searchParams.get("state");
1604
- const [row] = state ? await ctx.db.select().from(loginState).where(eq3(loginState.state, state)).limit(1) : [];
1605
- if (!row?.mobileRedirect || !row.mobileChallenge) return handleCallback(req, ctx);
1606
- const mobile = {
1607
- row: { ...row, mobileRedirect: row.mobileRedirect, mobileChallenge: row.mobileChallenge }
1608
- };
1609
- let res = null;
1610
- try {
1611
- res = await handleCallback(req, ctx, mobile);
1612
- } catch (err) {
1613
- if (mobile.reason !== "token_exchange") {
1614
- getLogger().error(
1615
- { event: "auth.login.failed", surface: "mobile", reason: "internal", err },
1616
- "auth login failed"
1617
- );
1618
- }
1619
- mobile.reason ??= "internal";
1620
- }
1621
- if (res && (mobile.restarted || mobile.reason === void 0)) return res;
1622
- const back = NextResponse2.redirect(
1623
- withQuery(mobile.row.mobileRedirect, "error", mobileLoginError(mobile.reason)),
1624
- 302
1625
- );
1626
- back.headers.set("Cache-Control", "no-store");
1627
- for (const c of res?.headers.getSetCookie() ?? []) {
1628
- if (c.startsWith(`${LOGIN_COOKIE_NAME}=`)) back.headers.append("Set-Cookie", c);
1629
- }
1630
- return back;
1631
- }
1632
- async function handleCallback(req, ctx, mobile) {
1633
- return runAuthSpan("Complete login", mobile ? { "qore.auth.surface": "mobile" } : {}, async (auth) => {
1293
+ async function handleCallback(req, ctx) {
1294
+ return runAuthSpan("Complete login", {}, async (auth) => {
1634
1295
  const log = getLogger();
1635
- const fail = (reason) => {
1636
- auth.fail(reason);
1637
- if (mobile) mobile.reason = reason;
1638
- };
1639
1296
  const code = req.nextUrl.searchParams.get("code");
1640
1297
  const state = req.nextUrl.searchParams.get("state");
1641
1298
  const consume = async (res) => {
1642
1299
  if (state) {
1643
- await ctx.db.delete(loginState).where(eq3(loginState.state, state));
1300
+ await ctx.db.delete(loginState).where(eq2(loginState.state, state));
1644
1301
  res.headers.append("Set-Cookie", removeBoundState(req.headers.get("cookie"), state));
1645
1302
  }
1646
1303
  return res;
@@ -1650,8 +1307,8 @@ async function handleCallback(req, ctx, mobile) {
1650
1307
  if (readBoundStates(req.headers.get("cookie")).includes(state)) return null;
1651
1308
  log.warn({ event: "auth.login.failed", reason: "state_not_bound" }, "auth login failed");
1652
1309
  auth.set("qore.auth.event", "login_failed");
1653
- fail("state_not_bound");
1654
- return new NextResponse2("state_not_bound", { status: 400 });
1310
+ auth.fail("state_not_bound");
1311
+ return new NextResponse("state_not_bound", { status: 400 });
1655
1312
  };
1656
1313
  const oidcError = req.nextUrl.searchParams.get("error");
1657
1314
  if (oidcError) {
@@ -1663,7 +1320,7 @@ async function handleCallback(req, ctx, mobile) {
1663
1320
  "auth login failed"
1664
1321
  );
1665
1322
  auth.set("qore.auth.event", "login_failed");
1666
- fail(oidcError);
1323
+ auth.fail(oidcError);
1667
1324
  const restartable = oidcError === "authentication_expired" || oidcError === "login_required";
1668
1325
  const queryRetried = req.nextUrl.searchParams.get("retried") === "1";
1669
1326
  let alreadyRetried = queryRetried;
@@ -1671,57 +1328,48 @@ async function handleCallback(req, ctx, mobile) {
1671
1328
  if (!state) {
1672
1329
  alreadyRetried = true;
1673
1330
  } else {
1674
- const [row2] = await ctx.db.select().from(loginState).where(eq3(loginState.state, state)).limit(1);
1331
+ const [row2] = await ctx.db.select().from(loginState).where(eq2(loginState.state, state)).limit(1);
1675
1332
  if (!row2 || row2.retried) alreadyRetried = true;
1676
1333
  retryRow = row2;
1677
1334
  }
1678
1335
  if (restartable && !alreadyRetried) {
1679
- if (mobile) {
1680
- const restart2 = new URL("/api/auth/mobile/login", ctx.publicOrigin);
1681
- restart2.searchParams.set("challenge", mobile.row.mobileChallenge);
1682
- restart2.searchParams.set("redirect", mobile.row.mobileRedirect);
1683
- if (mobile.row.uiLocales) restart2.searchParams.set("locale", mobile.row.uiLocales);
1684
- restart2.searchParams.set("retried", "1");
1685
- mobile.restarted = true;
1686
- return await consume(NextResponse2.redirect(restart2, 302));
1687
- }
1688
1336
  const restart = new URL("/api/auth/login", ctx.publicOrigin);
1689
1337
  restart.searchParams.set("prompt", "login");
1690
1338
  restart.searchParams.set("retried", "1");
1691
1339
  if (retryRow?.redirectPath) restart.searchParams.set("redirect", retryRow.redirectPath);
1692
1340
  if (retryRow?.expectedEmail) restart.searchParams.set("login_hint", retryRow.expectedEmail);
1693
- return await consume(NextResponse2.redirect(restart, 302));
1341
+ return await consume(NextResponse.redirect(restart, 302));
1694
1342
  }
1695
- return await consume(new NextResponse2(`login failed: ${oidcError}`, { status: 400 }));
1343
+ return await consume(new NextResponse(`login failed: ${oidcError}`, { status: 400 }));
1696
1344
  }
1697
1345
  const bindingFailure = checkBinding();
1698
1346
  if (bindingFailure) return bindingFailure;
1699
1347
  if (!code || !state) {
1700
1348
  log.warn({ event: "auth.login.failed", reason: "missing_params" }, "auth login failed");
1701
1349
  auth.set("qore.auth.event", "login_failed");
1702
- fail("missing_params");
1703
- return await consume(new NextResponse2("missing code or state", { status: 400 }));
1350
+ auth.fail("missing_params");
1351
+ return await consume(new NextResponse("missing code or state", { status: 400 }));
1704
1352
  }
1705
- const [row] = await ctx.db.select().from(loginState).where(eq3(loginState.state, state)).limit(1);
1353
+ const [row] = await ctx.db.select().from(loginState).where(eq2(loginState.state, state)).limit(1);
1706
1354
  if (!row) {
1707
1355
  log.warn({ event: "auth.login.failed", reason: "invalid_state" }, "auth login failed");
1708
1356
  auth.set("qore.auth.event", "login_failed");
1709
- fail("invalid_state");
1710
- return await consume(new NextResponse2("invalid state", { status: 400 }));
1357
+ auth.fail("invalid_state");
1358
+ return await consume(new NextResponse("invalid state", { status: 400 }));
1711
1359
  }
1712
1360
  if (row.expiresAt < /* @__PURE__ */ new Date()) {
1713
1361
  log.warn({ event: "auth.login.failed", reason: "expired_state" }, "auth login failed");
1714
1362
  auth.set("qore.auth.event", "login_failed");
1715
- fail("expired_state");
1716
- return await consume(new NextResponse2("expired state", { status: 400 }));
1363
+ auth.fail("expired_state");
1364
+ return await consume(new NextResponse("expired state", { status: 400 }));
1717
1365
  }
1718
- const previousSessionId = mobile ? null : await ctx.cookies.read(req.headers.get("cookie"));
1366
+ const previousSessionId = await ctx.cookies.read(req.headers.get("cookie"));
1719
1367
  const iss = req.nextUrl.searchParams.get("iss");
1720
1368
  if (iss && iss !== ctx.kcClient.issuer) {
1721
1369
  log.warn({ event: "auth.login.failed", reason: "iss_mismatch", iss }, "auth login failed");
1722
1370
  auth.set("qore.auth.event", "login_failed");
1723
- fail("iss_mismatch");
1724
- return await consume(new NextResponse2("iss_mismatch", { status: 400 }));
1371
+ auth.fail("iss_mismatch");
1372
+ return await consume(new NextResponse("iss_mismatch", { status: 400 }));
1725
1373
  }
1726
1374
  try {
1727
1375
  const tokens = await ctx.kcClient.exchangeCode({ code, codeVerifier: row.codeVerifier });
@@ -1733,8 +1381,8 @@ async function handleCallback(req, ctx, mobile) {
1733
1381
  "auth login failed"
1734
1382
  );
1735
1383
  auth.set("qore.auth.event", "login_failed");
1736
- fail("nonce_mismatch");
1737
- return await consume(new NextResponse2("nonce_mismatch", { status: 400 }));
1384
+ auth.fail("nonce_mismatch");
1385
+ return await consume(new NextResponse("nonce_mismatch", { status: 400 }));
1738
1386
  }
1739
1387
  }
1740
1388
  const claims = decodeJwt3(tokens.accessToken);
@@ -1748,8 +1396,8 @@ async function handleCallback(req, ctx, mobile) {
1748
1396
  "auth login failed"
1749
1397
  );
1750
1398
  auth.set("qore.auth.event", "login_failed");
1751
- fail("stale_auth_time");
1752
- return await consume(new NextResponse2("re-authentication was not performed", { status: 400 }));
1399
+ auth.fail("stale_auth_time");
1400
+ return await consume(new NextResponse("re-authentication was not performed", { status: 400 }));
1753
1401
  }
1754
1402
  }
1755
1403
  const expectedSub = row.expectedSub;
@@ -1784,12 +1432,12 @@ async function handleCallback(req, ctx, mobile) {
1784
1432
  "auth login identity mismatch"
1785
1433
  );
1786
1434
  auth.set("qore.auth.event", "login_identity_mismatch");
1787
- fail("identity_mismatch");
1435
+ auth.fail("identity_mismatch");
1788
1436
  const target = new URL(
1789
1437
  ctx.identityMismatchPath ?? DEFAULT_IDENTITY_MISMATCH_PATH,
1790
1438
  ctx.publicOrigin
1791
1439
  );
1792
- const res2 = NextResponse2.redirect(target, 302);
1440
+ const res2 = NextResponse.redirect(target, 302);
1793
1441
  res2.headers.append("Set-Cookie", ctx.cookies.clear());
1794
1442
  res2.headers.append(
1795
1443
  "Set-Cookie",
@@ -1808,52 +1456,12 @@ async function handleCallback(req, ctx, mobile) {
1808
1456
  "auth login failed"
1809
1457
  );
1810
1458
  auth.set("qore.auth.event", "login_failed");
1811
- fail("no_app_access");
1459
+ auth.fail("no_app_access");
1812
1460
  if (previousSessionId) await ctx.refreshStore.revokeSession(previousSessionId);
1813
- const denied = NextResponse2.redirect(new URL("/no-access", ctx.publicOrigin), 302);
1461
+ const denied = NextResponse.redirect(new URL("/no-access", ctx.publicOrigin), 302);
1814
1462
  denied.headers.set("Set-Cookie", ctx.cookies.clear());
1815
1463
  return await consume(denied);
1816
1464
  }
1817
- if (mobile) {
1818
- const org2 = parseOrganizationClaim(claims.organization);
1819
- const sessionId2 = await ctx.refreshStore.createSession({
1820
- userSub: claims.sub,
1821
- userEmail: claims.email,
1822
- organizationId: org2.id,
1823
- organizationAlias: org2.alias,
1824
- accessToken: tokens.accessToken,
1825
- accessExpiresAt: new Date(Date.now() + tokens.expiresIn * 1e3),
1826
- idToken: tokens.idToken,
1827
- refreshToken: tokens.refreshToken,
1828
- refreshExpiresAt: new Date(Date.now() + tokens.refreshExpiresIn * 1e3),
1829
- kind: "mobile"
1830
- });
1831
- await pruneExpiredHandoffs(ctx.db);
1832
- const handoffCode = newHandoffCode();
1833
- await ctx.db.insert(mobileHandoffCodes).values({
1834
- codeHash: sha256b64url(handoffCode),
1835
- sessionId: sessionId2,
1836
- challenge: mobile.row.mobileChallenge,
1837
- expiresAt: new Date(Date.now() + MOBILE_HANDOFF_TTL_SEC * 1e3)
1838
- });
1839
- log.info(
1840
- {
1841
- event: "auth.login.succeeded",
1842
- surface: "mobile",
1843
- user_sub: claims.sub,
1844
- user_email: claims.email,
1845
- org_id: org2.id,
1846
- org_alias: org2.alias
1847
- },
1848
- "auth login succeeded"
1849
- );
1850
- auth.set("qore.auth.event", "login_succeeded");
1851
- if (org2.alias) auth.set("qore.auth.org_alias", org2.alias);
1852
- const res2 = NextResponse2.redirect(withQuery(mobile.row.mobileRedirect, "code", handoffCode), 302);
1853
- res2.headers.set("Cache-Control", "no-store");
1854
- res2.headers.set("Referrer-Policy", "no-referrer");
1855
- return await consume(res2);
1856
- }
1857
1465
  if (previousSessionId) await ctx.refreshStore.revokeSession(previousSessionId);
1858
1466
  const org = parseOrganizationClaim(claims.organization);
1859
1467
  const refreshExpiresAt = new Date(Date.now() + tokens.refreshExpiresIn * 1e3);
@@ -1880,14 +1488,14 @@ async function handleCallback(req, ctx, mobile) {
1880
1488
  );
1881
1489
  auth.set("qore.auth.event", "login_succeeded");
1882
1490
  if (org.alias) auth.set("qore.auth.org_alias", org.alias);
1883
- const res = NextResponse2.redirect(new URL(row.redirectPath, ctx.publicOrigin), 302);
1491
+ const res = NextResponse.redirect(new URL(row.redirectPath, ctx.publicOrigin), 302);
1884
1492
  res.headers.set("Set-Cookie", await ctx.cookies.issue(sessionId, { expiresAt: refreshExpiresAt }));
1885
1493
  return await consume(res);
1886
1494
  } catch (err) {
1887
1495
  log.error({ event: "auth.login.failed", reason: "token_exchange", err }, "auth login failed");
1888
1496
  auth.set("qore.auth.event", "login_failed");
1889
- fail("token_exchange");
1890
- await ctx.db.delete(loginState).where(eq3(loginState.state, state));
1497
+ auth.fail("token_exchange");
1498
+ await ctx.db.delete(loginState).where(eq2(loginState.state, state));
1891
1499
  throw err;
1892
1500
  }
1893
1501
  });
@@ -1916,28 +1524,20 @@ async function requireAuthFor(opts) {
1916
1524
  clientId,
1917
1525
  orgAlias: opts.orgAlias,
1918
1526
  idleTimeoutSec: opts.sessionIdleTimeoutSec ?? DEFAULT_SESSION_IDLE_TIMEOUT_SEC,
1919
- absoluteMaxSec: opts.sessionAbsoluteMaxSec ?? DEFAULT_SESSION_ABSOLUTE_MAX_SEC,
1920
- mobile: resolveMobileAuth(opts.mobile)
1527
+ absoluteMaxSec: opts.sessionAbsoluteMaxSec ?? DEFAULT_SESSION_ABSOLUTE_MAX_SEC
1921
1528
  });
1922
1529
  }
1923
1530
 
1924
1531
  // src/next/auth/getAccessToken.ts
1925
- import { cookies as cookies2, headers as headers2 } from "next/headers";
1532
+ import { cookies as cookies2 } from "next/headers";
1926
1533
  async function resolveAccessToken(opts) {
1927
1534
  const skewSec = opts.refreshSkewSec ?? 30;
1928
1535
  const jar = await cookies2();
1929
1536
  const raw = jar.get(COOKIE_NAME)?.value;
1930
- const authorization = opts.mobile ? (await headers2()).get("authorization") : null;
1931
- const source = await sessionIdFrom(
1932
- opts.cookies,
1933
- raw ? `${COOKIE_NAME}=${raw}` : null,
1934
- authorization,
1935
- Boolean(opts.mobile)
1936
- );
1937
- if (!source) return null;
1938
- const id = source.id;
1537
+ const id = await opts.cookies.read(raw ? `${COOKIE_NAME}=${raw}` : null);
1538
+ if (!id) return null;
1939
1539
  let session = await opts.refreshStore.getSession(id);
1940
- if (!session || !kindMatches(source.via, session)) return null;
1540
+ if (!session) return null;
1941
1541
  session = await refreshWithinSkew(
1942
1542
  {
1943
1543
  refreshStore: opts.refreshStore,
@@ -1945,8 +1545,7 @@ async function resolveAccessToken(opts) {
1945
1545
  skewSec,
1946
1546
  orgAlias: opts.orgAlias,
1947
1547
  idleTimeoutSec: opts.idleTimeoutSec,
1948
- absoluteMaxSec: opts.absoluteMaxSec,
1949
- mobile: opts.mobile
1548
+ absoluteMaxSec: opts.absoluteMaxSec
1950
1549
  },
1951
1550
  id,
1952
1551
  session
@@ -1978,8 +1577,7 @@ function depsCacheKey(opts) {
1978
1577
  requireAppRole: opts.requireAppRole,
1979
1578
  permissions: opts.permissions,
1980
1579
  sessionIdleTimeoutSec: opts.sessionIdleTimeoutSec,
1981
- sessionAbsoluteMaxSec: opts.sessionAbsoluteMaxSec,
1982
- mobile: opts.mobile
1580
+ sessionAbsoluteMaxSec: opts.sessionAbsoluteMaxSec
1983
1581
  });
1984
1582
  }
1985
1583
  async function buildDepsUncached(opts) {
@@ -2002,8 +1600,7 @@ async function buildDepsUncached(opts) {
2002
1600
  kcClient,
2003
1601
  orgAlias: opts.orgAlias,
2004
1602
  idleTimeoutSec: opts.sessionIdleTimeoutSec ?? DEFAULT_SESSION_IDLE_TIMEOUT_SEC,
2005
- absoluteMaxSec: opts.sessionAbsoluteMaxSec ?? DEFAULT_SESSION_ABSOLUTE_MAX_SEC,
2006
- mobile: resolveMobileAuth(opts.mobile)
1603
+ absoluteMaxSec: opts.sessionAbsoluteMaxSec ?? DEFAULT_SESSION_ABSOLUTE_MAX_SEC
2007
1604
  };
2008
1605
  }
2009
1606
  async function buildDeps(opts) {
@@ -2027,7 +1624,7 @@ async function requireAccessTokenFor(opts) {
2027
1624
  }
2028
1625
 
2029
1626
  // src/next/auth/permissionGuards.ts
2030
- import { NextResponse as NextResponse3 } from "next/server";
1627
+ import { NextResponse as NextResponse2 } from "next/server";
2031
1628
  function makeGuards(map, getPermissions, requireUser = async () => {
2032
1629
  throw new AuthError("unauthenticated");
2033
1630
  }) {
@@ -2038,7 +1635,7 @@ function makeGuards(map, getPermissions, requireUser = async () => {
2038
1635
  return user;
2039
1636
  };
2040
1637
  const withPermission = (permission, handler) => async (...args) => {
2041
- if (!await can(permission)) return new NextResponse3(null, { status: 403 });
1638
+ if (!await can(permission)) return new NextResponse2(null, { status: 403 });
2042
1639
  return handler(...args);
2043
1640
  };
2044
1641
  return { can, requirePermission, withPermission };
@@ -2059,7 +1656,7 @@ function createPermissionGuards(map, getOpts) {
2059
1656
  }
2060
1657
 
2061
1658
  // src/next/auth/withConnectionToken.ts
2062
- import { timingSafeEqual as timingSafeEqual2 } from "crypto";
1659
+ import { timingSafeEqual } from "crypto";
2063
1660
  function expectedTokens() {
2064
1661
  return Object.entries(process.env).filter(([k, v]) => /^CONN_.+_TOKEN$/.test(k) && !!v).map(([, v]) => v);
2065
1662
  }
@@ -2067,7 +1664,7 @@ function safeEqual(a, b) {
2067
1664
  const ab = Buffer.from(a);
2068
1665
  const bb = Buffer.from(b);
2069
1666
  if (ab.length !== bb.length) return false;
2070
- return timingSafeEqual2(ab, bb);
1667
+ return timingSafeEqual(ab, bb);
2071
1668
  }
2072
1669
  function withConnectionToken(handler) {
2073
1670
  return async (req) => {