@quatronic/sdk 0.10.0 → 0.10.1-test.97e91bf

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 (78) hide show
  1. package/README.md +6 -0
  2. package/dist/chunk-JM5LHJUJ.js +32 -0
  3. package/dist/chunk-JM5LHJUJ.js.map +1 -0
  4. package/dist/{chunk-YFZB5EW6.js → chunk-P5GBQVO7.js} +2 -2
  5. package/dist/{chunk-IFESUTF2.js → chunk-VQKYPW5V.js} +7 -3
  6. package/dist/chunk-VQKYPW5V.js.map +1 -0
  7. package/dist/{chunk-POZI4OKJ.js → chunk-WOFBDOMY.js} +2 -2
  8. package/dist/{chunk-TPBRMW5N.js → chunk-YCKDMG4B.js} +30 -1
  9. package/dist/chunk-YCKDMG4B.js.map +1 -0
  10. package/dist/chunk-YJZZURE4.js +83 -0
  11. package/dist/chunk-YJZZURE4.js.map +1 -0
  12. package/dist/cli/skills-postinstall.js +13 -6
  13. package/dist/cli/skills.js +11 -5
  14. package/dist/context-CWvUIBHJ.d.ts +196 -0
  15. package/dist/eslint/index.d.ts +11 -1
  16. package/dist/eslint/index.js +123 -4
  17. package/dist/eslint/index.js.map +1 -1
  18. package/dist/expo/auth/index.d.ts +14 -0
  19. package/dist/expo/auth/index.js +324 -0
  20. package/dist/expo/auth/index.js.map +1 -0
  21. package/dist/expo/config/index.d.ts +38 -0
  22. package/dist/expo/config/index.js +35 -0
  23. package/dist/expo/config/index.js.map +1 -0
  24. package/dist/expo/log/index.d.ts +9 -0
  25. package/dist/expo/log/index.js +16 -0
  26. package/dist/expo/log/index.js.map +1 -0
  27. package/dist/expo/query/index.d.ts +41 -0
  28. package/dist/expo/query/index.js +98 -0
  29. package/dist/expo/query/index.js.map +1 -0
  30. package/dist/expo/sentry/index.d.ts +33 -0
  31. package/dist/expo/sentry/index.js +100 -0
  32. package/dist/expo/sentry/index.js.map +1 -0
  33. package/dist/expo/testing/index.d.ts +32 -0
  34. package/dist/expo/testing/index.js +58 -0
  35. package/dist/expo/testing/index.js.map +1 -0
  36. package/dist/next/auth/index.d.ts +50 -0
  37. package/dist/next/auth/index.js +523 -101
  38. package/dist/next/auth/index.js.map +1 -1
  39. package/dist/next/boot/index.js +3 -3
  40. package/dist/next/db/index.js +1 -1
  41. package/dist/next/security/index.d.ts +24 -1
  42. package/dist/next/security/index.js +29 -0
  43. package/dist/next/security/index.js.map +1 -1
  44. package/dist/next/sentry/client.js +3 -3
  45. package/dist/next/sentry/client.js.map +1 -1
  46. package/dist/next/sentry/index.js +1 -1
  47. package/dist/next/sentry/register.js +3 -3
  48. package/dist/node/sentry/index.js +1 -1
  49. package/dist/node/sentry/register.js +2 -2
  50. package/package.json +75 -2
  51. package/skills/catalog.json +3 -0
  52. package/skills/qore-add-api-route/SKILL.md +1 -1
  53. package/skills/qore-add-connection/SKILL.next.md +3 -1
  54. package/skills/qore-add-connection/SKILL.node.md +3 -1
  55. package/skills/qore-add-env-key/SKILL.md +174 -9
  56. package/skills/qore-add-feature/SKILL.md +1 -1
  57. package/skills/qore-add-integration/SKILL.next.md +4 -2
  58. package/skills/qore-add-integration/SKILL.node.md +6 -6
  59. package/skills/qore-add-page/SKILL.md +1 -1
  60. package/skills/qore-author-skill/SKILL.md +1 -1
  61. package/skills/qore-debug-issue/SKILL.md +10 -0
  62. package/skills/qore-mobile-add-screen/SKILL.md +64 -0
  63. package/skills/qore-mobile-call-server/SKILL.md +75 -0
  64. package/skills/qore-mobile-run-on-device/SKILL.md +44 -0
  65. package/skills/qore-observability/SKILL.md +17 -0
  66. package/skills/qore-secure-io/SKILL.md +15 -0
  67. package/skills/qore-ship-checklist/SKILL.md +10 -0
  68. package/skills/qore-translate-strings/SKILL.md +10 -0
  69. package/skills/qore-use-addons/SKILL.md +2 -0
  70. package/skills/qore-use-database/SKILL.md +2 -0
  71. package/skills/qore-use-design-system/SKILL.md +1 -1
  72. package/skills/qore-use-mail-domain/SKILL.next.md +1 -1
  73. package/skills/qore-use-mail-domain/SKILL.node.md +2 -2
  74. package/skills/qore-use-permissions/SKILL.md +10 -0
  75. package/dist/chunk-IFESUTF2.js.map +0 -1
  76. package/dist/chunk-TPBRMW5N.js.map +0 -1
  77. /package/dist/{chunk-YFZB5EW6.js.map → chunk-P5GBQVO7.js.map} +0 -0
  78. /package/dist/{chunk-POZI4OKJ.js.map → chunk-WOFBDOMY.js.map} +0 -0
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  runAuthMigrations
3
- } from "../../chunk-TPBRMW5N.js";
3
+ } from "../../chunk-YCKDMG4B.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 } from "next/server";
12
- import { eq as eq2 } from "drizzle-orm";
11
+ import { NextResponse as NextResponse2 } from "next/server";
12
+ import { eq as eq3 } from "drizzle-orm";
13
13
  import { decodeJwt as decodeJwt3 } from "jose";
14
14
 
15
15
  // src/auth-core/crypto.ts
@@ -119,7 +119,8 @@ function sessionCookie(opts) {
119
119
  }
120
120
  return null;
121
121
  }
122
- return { issue, clear, read };
122
+ const token = sign;
123
+ return { issue, clear, read, token };
123
124
  }
124
125
 
125
126
  // src/auth-core/kcClient.ts
@@ -152,7 +153,7 @@ function createKcClient(cfg) {
152
153
  response_type: "code",
153
154
  client_id: cfg.clientId,
154
155
  redirect_uri: redirectUri,
155
- scope: scope(),
156
+ scope: [scope(), ...args.extraScopes ?? []].join(" "),
156
157
  state: args.state,
157
158
  code_challenge: args.codeChallenge,
158
159
  code_challenge_method: "S256"
@@ -163,6 +164,7 @@ function createKcClient(cfg) {
163
164
  if (args.prompt) params.set("prompt", args.prompt);
164
165
  if (args.maxAge !== void 0) params.set("max_age", String(args.maxAge));
165
166
  if (args.idTokenHint) params.set("id_token_hint", args.idTokenHint);
167
+ if (args.uiLocales) params.set("ui_locales", args.uiLocales);
166
168
  return `${authorizeUrl}?${params.toString().replace(/\+/g, "%20")}`;
167
169
  }
168
170
  function buildEndSessionUrl(args) {
@@ -292,7 +294,10 @@ var sessions = authSchema.table(
292
294
  createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
293
295
  updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
294
296
  revokedAt: timestamp("revoked_at", { withTimezone: true }),
295
- pendingIdentityConfirm: boolean("pending_identity_confirm").notNull().default(false)
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")
296
301
  },
297
302
  (t) => ({
298
303
  userSubIdx: index("ix_auth_sessions_user_sub").on(t.userSub)
@@ -316,8 +321,26 @@ var loginState = authSchema.table("login_state", {
316
321
  // being replaced and/or the address the user typed. The callback compares
317
322
  // Keycloak's answer against these instead of adopting whatever comes back.
318
323
  expectedSub: varchar("expected_sub", { length: 64 }),
319
- expectedEmail: varchar("expected_email", { length: 320 })
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 })
320
331
  });
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
+ );
321
344
 
322
345
  // src/auth-core/refreshStore.ts
323
346
  var SESSION_CACHE_TTL_MS = 5e3;
@@ -338,7 +361,8 @@ function createRefreshStore(opts) {
338
361
  refreshCt: ciphertext,
339
362
  refreshIv: iv,
340
363
  refreshExpiresAt: input.refreshExpiresAt,
341
- pendingIdentityConfirm: input.pendingIdentityConfirm ?? false
364
+ pendingIdentityConfirm: input.pendingIdentityConfirm ?? false,
365
+ kind: input.kind ?? "web"
342
366
  }).returning({ id: sessions.id });
343
367
  return row.id;
344
368
  }
@@ -356,7 +380,8 @@ function createRefreshStore(opts) {
356
380
  refreshToken,
357
381
  refreshExpiresAt: row.refreshExpiresAt,
358
382
  createdAt: row.createdAt,
359
- updatedAt: row.updatedAt
383
+ updatedAt: row.updatedAt,
384
+ kind: row.kind === "mobile" ? "mobile" : "web"
360
385
  };
361
386
  }
362
387
  async function getSession(id) {
@@ -550,6 +575,58 @@ async function createIdentityHandoff(opts) {
550
575
  return { issue, read, clear };
551
576
  }
552
577
 
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
+
553
630
  // src/auth-core/organizationClaim.ts
554
631
  function parseOrganizationClaim(raw) {
555
632
  if (!raw) return {};
@@ -663,7 +740,7 @@ function removeBoundState(cookieHeader, state) {
663
740
  import { decodeJwt as decodeJwt2 } from "jose";
664
741
 
665
742
  // src/next/auth/requireAuth.ts
666
- import { cookies } from "next/headers";
743
+ import { cookies, headers } from "next/headers";
667
744
  import { decodeJwt } from "jose";
668
745
 
669
746
  // src/next/auth/appAccess.ts
@@ -671,6 +748,21 @@ function rolesForClient(claims, clientId) {
671
748
  return claims.resource_access?.[clientId]?.roles ?? [];
672
749
  }
673
750
 
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
+
674
766
  // src/next/auth/requireAuth.ts
675
767
  var AuthError = class extends Error {
676
768
  constructor(reason) {
@@ -685,10 +777,17 @@ function requireAuth(opts) {
685
777
  return async () => {
686
778
  const jar = await cookies();
687
779
  const raw = jar.get(COOKIE_NAME)?.value;
688
- const id = await opts.cookies.read(raw ? `${COOKIE_NAME}=${raw}` : null);
689
- if (!id) throw new AuthError("unauthenticated");
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;
690
789
  let session = await opts.refreshStore.getSession(id);
691
- if (!session) throw new AuthError("unauthenticated");
790
+ if (!session || !kindMatches(source.via, session)) throw new AuthError("unauthenticated");
692
791
  session = await refreshWithinSkew(
693
792
  {
694
793
  refreshStore: opts.refreshStore,
@@ -696,7 +795,8 @@ function requireAuth(opts) {
696
795
  skewSec,
697
796
  orgAlias: opts.orgAlias,
698
797
  idleTimeoutSec: opts.idleTimeoutSec,
699
- absoluteMaxSec: opts.absoluteMaxSec
798
+ absoluteMaxSec: opts.absoluteMaxSec,
799
+ mobile: opts.mobile
700
800
  },
701
801
  id,
702
802
  session
@@ -721,8 +821,9 @@ function isDefinitiveRefreshFailure(err) {
721
821
  return err instanceof KcTokenError && err.status === 400 && err.oauthError === "invalid_grant";
722
822
  }
723
823
  async function refreshWithinSkew(opts, id, session) {
724
- const idleSec = opts.idleTimeoutSec;
725
- const absoluteSec = opts.absoluteMaxSec;
824
+ const bounds = session.kind === "mobile" && opts.mobile ? opts.mobile : opts;
825
+ const idleSec = bounds.idleTimeoutSec;
826
+ const absoluteSec = bounds.absoluteMaxSec;
726
827
  const tooIdle = idleSec !== void 0 && Date.now() - session.updatedAt.getTime() > idleSec * 1e3;
727
828
  const tooOld = absoluteSec !== void 0 && Date.now() - session.createdAt.getTime() > absoluteSec * 1e3;
728
829
  if (tooIdle || tooOld) {
@@ -775,8 +876,8 @@ var KC_DEFAULT_ROLES = /* @__PURE__ */ new Set(["offline_access", "uma_authoriza
775
876
  function decodeJwtPayload(token) {
776
877
  const segment2 = token.split(".")[1];
777
878
  if (!segment2) throw new Error("Malformed JWT: missing payload segment");
778
- const json = Buffer.from(segment2, "base64url").toString("utf8");
779
- return JSON.parse(json);
879
+ const json2 = Buffer.from(segment2, "base64url").toString("utf8");
880
+ return JSON.parse(json2);
780
881
  }
781
882
  function extractRoles(payload, clientId) {
782
883
  const realm = payload.realm_access?.roles ?? [];
@@ -800,8 +901,20 @@ function permissionsForRoles(map, roles) {
800
901
  }
801
902
 
802
903
  // 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
+ }
803
914
  var DEFAULT_SESSION_IDLE_TIMEOUT_SEC = 28800;
804
915
  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;
805
918
 
806
919
  // src/next/auth/authSpan.ts
807
920
  import { SpanStatusCode, trace } from "@opentelemetry/api";
@@ -833,6 +946,189 @@ function runAuthSpan(label, attributes3, fn) {
833
946
  });
834
947
  }
835
948
 
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
+ var HOPPED = "hopped";
959
+ function requestHost(req) {
960
+ const forwarded = req.headers.get("x-forwarded-host")?.split(",")[0]?.trim();
961
+ return (forwarded || req.headers.get("host") || req.nextUrl.host).toLowerCase();
962
+ }
963
+ function hopToPublicOrigin(req, publicOrigin) {
964
+ const params = req.nextUrl.searchParams;
965
+ if (params.get(HOPPED) === "1") return null;
966
+ const target = new URL("/api/auth/mobile/login", publicOrigin);
967
+ if (requestHost(req) === target.host.toLowerCase()) return null;
968
+ const query = new URLSearchParams(params);
969
+ query.set(HOPPED, "1");
970
+ target.search = query.toString();
971
+ const res = NextResponse.redirect(target, 302);
972
+ res.headers.set("Cache-Control", "no-store");
973
+ return res;
974
+ }
975
+ async function handleMobileLogin(req, ctx) {
976
+ return runAuthSpan(
977
+ "Log in",
978
+ { "qore.auth.event": "login_started", "qore.auth.surface": "mobile" },
979
+ async (auth) => {
980
+ const params = req.nextUrl.searchParams;
981
+ const challenge = params.get("challenge");
982
+ const redirect = params.get("redirect");
983
+ if (!challenge || !CHALLENGE_RE.test(challenge)) {
984
+ auth.fail("invalid_challenge");
985
+ return json({ error: "invalid_challenge" }, 400);
986
+ }
987
+ if (!redirect || !isAllowedMobileRedirect(redirect, ctx.mobile)) {
988
+ auth.fail("invalid_redirect");
989
+ return json({ error: "invalid_redirect" }, 400);
990
+ }
991
+ const hop = hopToPublicOrigin(req, ctx.publicOrigin);
992
+ if (hop) return hop;
993
+ const locale = safeLocale(params.get("locale"));
994
+ const retried = params.get("retried") === "1";
995
+ const state = randomB64Url(32);
996
+ const codeVerifier = randomB64Url(48);
997
+ const codeChallenge = await sha256B64Url(codeVerifier);
998
+ const nonce = randomB64Url(32);
999
+ await ctx.db.insert(loginState).values({
1000
+ state,
1001
+ codeVerifier,
1002
+ redirectPath: "/",
1003
+ expiresAt: new Date(Date.now() + LOGIN_TTL_MS),
1004
+ forcedReauth: retried,
1005
+ nonce,
1006
+ retried,
1007
+ expectedSub: null,
1008
+ expectedEmail: null,
1009
+ mobileChallenge: challenge,
1010
+ mobileRedirect: redirect,
1011
+ uiLocales: locale
1012
+ });
1013
+ getLogger().info(
1014
+ { event: "auth.login.started", surface: "mobile", state, forced_reauth: retried, locale },
1015
+ "auth login started"
1016
+ );
1017
+ const url = ctx.kcClient.buildAuthorizeUrl({
1018
+ state,
1019
+ codeChallenge,
1020
+ nonce,
1021
+ ...retried ? { prompt: "login", maxAge: 0 } : { prompt: "select_account" },
1022
+ extraScopes: ctx.mobile.offlineAccess ? ["offline_access"] : [],
1023
+ uiLocales: locale
1024
+ });
1025
+ const res = NextResponse.redirect(url, 302);
1026
+ res.headers.set("Cache-Control", "no-store");
1027
+ res.headers.append("Set-Cookie", appendBoundState(req.headers.get("cookie"), state));
1028
+ return res;
1029
+ }
1030
+ );
1031
+ }
1032
+ async function handleMobileRedeem(req, ctx) {
1033
+ return runAuthSpan("Redeem mobile login", { "qore.auth.surface": "mobile" }, async (auth) => {
1034
+ const log = getLogger();
1035
+ let body;
1036
+ try {
1037
+ body = await req.json();
1038
+ } catch {
1039
+ auth.fail("invalid_request");
1040
+ return json({ error: "invalid_request" }, 400);
1041
+ }
1042
+ const code = body?.code;
1043
+ const verifier = body?.verifier;
1044
+ if (!isHandoffCode(code) || typeof verifier !== "string" || !VERIFIER_RE.test(verifier)) {
1045
+ auth.fail("invalid_request");
1046
+ return json({ error: "invalid_request" }, 400);
1047
+ }
1048
+ const [rec] = await ctx.db.delete(mobileHandoffCodes).where(eq2(mobileHandoffCodes.codeHash, sha256b64url(code))).returning();
1049
+ if (!rec) {
1050
+ log.warn({ event: "auth.mobile.redeem_failed", reason: "unknown_code" }, "mobile redeem failed");
1051
+ auth.fail("unknown_code");
1052
+ return json({ error: "invalid_grant" }, 400);
1053
+ }
1054
+ const expired = rec.expiresAt.getTime() <= Date.now();
1055
+ if (expired || !verifierMatches(verifier, rec.challenge)) {
1056
+ await ctx.refreshStore.revokeSession(rec.sessionId);
1057
+ const reason = expired ? "expired_code" : "verifier_mismatch";
1058
+ log.warn({ event: "auth.mobile.redeem_failed", reason }, "mobile redeem failed");
1059
+ auth.fail(reason);
1060
+ return json({ error: "invalid_grant" }, 400);
1061
+ }
1062
+ const session = await ctx.refreshStore.getSession(rec.sessionId);
1063
+ if (!session || session.kind !== "mobile") {
1064
+ auth.fail("session_gone");
1065
+ return json({ error: "invalid_grant" }, 400);
1066
+ }
1067
+ const token = await ctx.cookies.token(rec.sessionId);
1068
+ const expiresAt = new Date(session.createdAt.getTime() + ctx.mobile.absoluteMaxSec * 1e3);
1069
+ log.info({ event: "auth.mobile.redeemed", user_sub: session.userSub }, "mobile login redeemed");
1070
+ auth.set("qore.auth.event", "mobile_redeemed");
1071
+ return json({ token, expiresAt: expiresAt.toISOString() }, 200);
1072
+ });
1073
+ }
1074
+ async function handleMobileLogout(req, ctx) {
1075
+ return runAuthSpan(
1076
+ "Log out",
1077
+ { "qore.auth.event": "logout", "qore.auth.surface": "mobile" },
1078
+ async () => {
1079
+ const token = bearerToken(req.headers.get("authorization"));
1080
+ const id = token ? await ctx.cookies.read(`${COOKIE_NAME}=${token}`) : null;
1081
+ if (id) {
1082
+ const session = await ctx.refreshStore.getSession(id);
1083
+ if (session && session.kind === "mobile") {
1084
+ try {
1085
+ await ctx.kcClient.logout(session.refreshToken);
1086
+ } catch {
1087
+ }
1088
+ await ctx.refreshStore.revokeSession(id);
1089
+ getLogger().info(
1090
+ { event: "auth.logout", method: "mobile", user_sub: session.userSub },
1091
+ "auth logout"
1092
+ );
1093
+ }
1094
+ }
1095
+ const res = new NextResponse(null, { status: 204 });
1096
+ res.headers.set("Cache-Control", "no-store");
1097
+ return res;
1098
+ }
1099
+ );
1100
+ }
1101
+ function handleMobileResetPassword(req, ctx) {
1102
+ const base = ctx.keycloakUrl.replace(/\/+$/, "");
1103
+ const url = new URL(
1104
+ `${base}/realms/${encodeURIComponent(ctx.realm)}/login-actions/reset-credentials`
1105
+ );
1106
+ url.searchParams.set("client_id", ctx.clientId);
1107
+ url.searchParams.set("kc_locale", safeLocale(req.nextUrl.searchParams.get("locale")));
1108
+ const res = NextResponse.redirect(url, 302);
1109
+ res.headers.set("Cache-Control", "no-store");
1110
+ return res;
1111
+ }
1112
+ function mobileLoginError(reason) {
1113
+ switch (reason) {
1114
+ case "access_denied":
1115
+ return "cancelled";
1116
+ case "expired_state":
1117
+ case "authentication_expired":
1118
+ case "login_required":
1119
+ return "expired";
1120
+ case "no_app_access":
1121
+ return "no_app_access";
1122
+ case "identity_mismatch":
1123
+ return "identity_mismatch";
1124
+ default:
1125
+ return "failed";
1126
+ }
1127
+ }
1128
+ async function pruneExpiredHandoffs(db) {
1129
+ await db.delete(mobileHandoffCodes).where(lt(mobileHandoffCodes.expiresAt, /* @__PURE__ */ new Date()));
1130
+ }
1131
+
836
1132
  // src/next/auth/createAuthRouteHandlers.ts
837
1133
  var AUTH_TIME_SKEW_SEC = 5;
838
1134
  var DEFAULT_IDENTITY_MISMATCH_PATH = "/login?reason=identity_mismatch";
@@ -840,7 +1136,8 @@ var LOGGED_OUT_PATH = "/api/auth/logged-out";
840
1136
  var CLEAR_SITE_DATA = '"cookies"';
841
1137
  function segment(req) {
842
1138
  const parts = req.nextUrl.pathname.split("/").filter(Boolean);
843
- return parts[parts.length - 1] ?? "";
1139
+ const last = parts[parts.length - 1] ?? "";
1140
+ return parts[parts.length - 2] === "mobile" ? `mobile/${last}` : last;
844
1141
  }
845
1142
  function noStore(res) {
846
1143
  res.headers.set("Cache-Control", "no-store");
@@ -868,7 +1165,9 @@ async function createAuthRouteHandlers(opts) {
868
1165
  realm: opts.realm,
869
1166
  audience: opts.clientId
870
1167
  });
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 };
1168
+ 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 };
1169
+ const mobileCtx = ctx.mobile ? { ...ctx, mobile: ctx.mobile } : null;
1170
+ const notFound = () => NextResponse2.json({ error: "not_found" }, { status: 404 });
872
1171
  async function GET(req) {
873
1172
  switch (segment(req)) {
874
1173
  case "login":
@@ -876,7 +1175,11 @@ async function createAuthRouteHandlers(opts) {
876
1175
  case "me":
877
1176
  return handleMe(req, ctx);
878
1177
  case "callback":
879
- return handleCallback(req, ctx);
1178
+ return mobileCtx ? handleCallbackMobileAware(req, ctx) : handleCallback(req, ctx);
1179
+ case "mobile/login":
1180
+ return mobileCtx ? handleMobileLogin(req, mobileCtx) : notFound();
1181
+ case "mobile/reset-password":
1182
+ return mobileCtx ? handleMobileResetPassword(req, mobileCtx) : notFound();
880
1183
  case "logout":
881
1184
  return handleLogoutRedirect(req, ctx);
882
1185
  case "logged-out":
@@ -884,7 +1187,7 @@ async function createAuthRouteHandlers(opts) {
884
1187
  case "identity-mismatch":
885
1188
  return handleIdentityMismatch(req, ctx);
886
1189
  default:
887
- return NextResponse.json({ error: "not_found" }, { status: 404 });
1190
+ return NextResponse2.json({ error: "not_found" }, { status: 404 });
888
1191
  }
889
1192
  }
890
1193
  async function POST(req) {
@@ -897,8 +1200,12 @@ async function createAuthRouteHandlers(opts) {
897
1200
  return handleBackchannelLogout(req, ctx);
898
1201
  case "confirm-identity":
899
1202
  return handleConfirmIdentity(req, ctx);
1203
+ case "mobile/redeem":
1204
+ return mobileCtx ? handleMobileRedeem(req, mobileCtx) : notFound();
1205
+ case "mobile/logout":
1206
+ return mobileCtx ? handleMobileLogout(req, mobileCtx) : notFound();
900
1207
  default:
901
- return NextResponse.json({ error: "not_found" }, { status: 404 });
1208
+ return NextResponse2.json({ error: "not_found" }, { status: 404 });
902
1209
  }
903
1210
  }
904
1211
  return { GET, POST };
@@ -993,7 +1300,7 @@ async function handleLogin(req, ctx) {
993
1300
  authorizePrompt === "id_token_hint" ? { idTokenHint } : { prompt: "select_account" }
994
1301
  )
995
1302
  });
996
- const res = NextResponse.redirect(url, 302);
1303
+ const res = NextResponse2.redirect(url, 302);
997
1304
  res.headers.append("Set-Cookie", appendBoundState(req.headers.get("cookie"), state));
998
1305
  res.headers.append("Set-Cookie", ctx.handoff.clear());
999
1306
  return res;
@@ -1002,17 +1309,28 @@ async function handleLogin(req, ctx) {
1002
1309
  }
1003
1310
  async function handleMe(req, ctx) {
1004
1311
  try {
1005
- return noStore(await handleMeInner(req, ctx));
1312
+ const res = noStore(await handleMeInner(req, ctx));
1313
+ if (ctx.mobile) res.headers.set("Vary", "Cookie, Authorization");
1314
+ return res;
1006
1315
  } catch (err) {
1007
1316
  getLogger().error({ err }, "auth /me failed unexpectedly");
1008
- return noStore(NextResponse.json({ error: "internal" }, { status: 500 }));
1317
+ return noStore(NextResponse2.json({ error: "internal" }, { status: 500 }));
1009
1318
  }
1010
1319
  }
1011
1320
  async function handleMeInner(req, ctx) {
1012
- const id = await ctx.cookies.read(req.headers.get("cookie"));
1013
- if (!id) return NextResponse.json({ error: "unauthenticated" }, { status: 401 });
1321
+ const source = await sessionIdFrom(
1322
+ ctx.cookies,
1323
+ req.headers.get("cookie"),
1324
+ req.headers.get("authorization"),
1325
+ Boolean(ctx.mobile)
1326
+ );
1327
+ if (!source) return NextResponse2.json({ error: "unauthenticated" }, { status: 401 });
1328
+ const id = source.id;
1329
+ const bearer = source.via === "bearer";
1014
1330
  const existing = await ctx.refreshStore.getSession(id);
1015
- if (!existing) return NextResponse.json({ error: "unauthenticated" }, { status: 401 });
1331
+ if (!existing || !kindMatches(source.via, existing)) {
1332
+ return NextResponse2.json({ error: "unauthenticated" }, { status: 401 });
1333
+ }
1016
1334
  let session;
1017
1335
  try {
1018
1336
  session = await refreshWithinSkew(
@@ -1022,7 +1340,8 @@ async function handleMeInner(req, ctx) {
1022
1340
  skewSec: 30,
1023
1341
  orgAlias: ctx.orgAlias,
1024
1342
  idleTimeoutSec: ctx.idleTimeoutSec,
1025
- absoluteMaxSec: ctx.absoluteMaxSec
1343
+ absoluteMaxSec: ctx.absoluteMaxSec,
1344
+ mobile: ctx.mobile
1026
1345
  },
1027
1346
  id,
1028
1347
  existing
@@ -1030,17 +1349,27 @@ async function handleMeInner(req, ctx) {
1030
1349
  } catch (err) {
1031
1350
  if (!(err instanceof AuthError)) throw err;
1032
1351
  if (err.reason === "refresh_unavailable") {
1033
- return NextResponse.json({ error: "refresh_unavailable" }, { status: 503 });
1352
+ return NextResponse2.json({ error: "refresh_unavailable" }, { status: 503 });
1034
1353
  }
1035
- const res = NextResponse.json({ error: "session_expired" }, { status: 401 });
1036
- res.headers.set("Set-Cookie", ctx.cookies.clear());
1354
+ const res = NextResponse2.json({ error: "session_expired" }, { status: 401 });
1355
+ if (!bearer) res.headers.set("Set-Cookie", ctx.cookies.clear());
1037
1356
  return res;
1038
1357
  }
1039
1358
  const claims = decodeJwt3(session.accessToken);
1040
1359
  if (ctx.requireAppRole && rolesForClient(claims, ctx.clientId).length === 0) {
1041
- return NextResponse.json({ error: "no_app_access" }, { status: 403 });
1360
+ return NextResponse2.json({ error: "no_app_access" }, { status: 403 });
1361
+ }
1362
+ if (bearer) {
1363
+ return NextResponse2.json({
1364
+ sub: session.userSub,
1365
+ email: session.userEmail,
1366
+ name: typeof claims.name === "string" ? claims.name : null,
1367
+ organizationAlias: session.organizationAlias,
1368
+ roles: rolesForClient(claims, ctx.clientId),
1369
+ permissions: resolveMePermissions(ctx.permissions, session.accessToken, ctx.clientId)
1370
+ });
1042
1371
  }
1043
- return NextResponse.json({
1372
+ return NextResponse2.json({
1044
1373
  user: { id: session.userSub, email: session.userEmail },
1045
1374
  organization: { id: session.organizationId, alias: session.organizationAlias },
1046
1375
  permissions: resolveMePermissions(ctx.permissions, session.accessToken, ctx.clientId)
@@ -1052,12 +1381,12 @@ async function handleRefresh(req, ctx) {
1052
1381
  const id = await ctx.cookies.read(req.headers.get("cookie"));
1053
1382
  if (!id) {
1054
1383
  auth.set("qore.auth.event", "refresh_skipped");
1055
- return NextResponse.json({ error: "unauthenticated" }, { status: 401 });
1384
+ return NextResponse2.json({ error: "unauthenticated" }, { status: 401 });
1056
1385
  }
1057
1386
  const session = await ctx.refreshStore.getSession(id);
1058
1387
  if (!session) {
1059
1388
  auth.set("qore.auth.event", "refresh_skipped");
1060
- return NextResponse.json({ error: "unauthenticated" }, { status: 401 });
1389
+ return NextResponse2.json({ error: "unauthenticated" }, { status: 401 });
1061
1390
  }
1062
1391
  try {
1063
1392
  await refreshWithinSkew(
@@ -1077,15 +1406,15 @@ async function handleRefresh(req, ctx) {
1077
1406
  auth.set("qore.auth.event", "refresh_failed");
1078
1407
  if (err.reason === "refresh_unavailable") {
1079
1408
  auth.fail("refresh_unavailable");
1080
- return NextResponse.json({ error: "refresh_unavailable" }, { status: 503 });
1409
+ return NextResponse2.json({ error: "refresh_unavailable" }, { status: 503 });
1081
1410
  }
1082
1411
  auth.fail("session_expired");
1083
- const res = NextResponse.json({ error: "session_expired" }, { status: 401 });
1412
+ const res = NextResponse2.json({ error: "session_expired" }, { status: 401 });
1084
1413
  res.headers.set("Set-Cookie", ctx.cookies.clear());
1085
1414
  return res;
1086
1415
  }
1087
1416
  auth.set("qore.auth.event", "session_refreshed");
1088
- return new NextResponse(null, { status: 204 });
1417
+ return new NextResponse2(null, { status: 204 });
1089
1418
  });
1090
1419
  }
1091
1420
  async function handleLogout(req, ctx) {
@@ -1113,7 +1442,7 @@ async function handleLogout(req, ctx) {
1113
1442
  );
1114
1443
  }
1115
1444
  }
1116
- const res = new NextResponse(null, { status: 204 });
1445
+ const res = new NextResponse2(null, { status: 204 });
1117
1446
  res.headers.set("Set-Cookie", ctx.cookies.clear());
1118
1447
  return res;
1119
1448
  });
@@ -1154,7 +1483,7 @@ async function handleLogoutRedirect(req, ctx) {
1154
1483
  postLogoutRedirectUri: landing.toString(),
1155
1484
  idTokenHint
1156
1485
  });
1157
- const res = NextResponse.redirect(endSessionUrl, 302);
1486
+ const res = NextResponse2.redirect(endSessionUrl, 302);
1158
1487
  res.headers.set("Set-Cookie", ctx.cookies.clear());
1159
1488
  return res;
1160
1489
  });
@@ -1163,7 +1492,7 @@ async function handleLoggedOut(req, ctx) {
1163
1492
  const target = safeRedirect(req.nextUrl.searchParams.get("redirect"));
1164
1493
  const attr = target.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/"/g, "&quot;");
1165
1494
  const literal = JSON.stringify(target).replace(/</g, "\\u003c");
1166
- const res = new NextResponse(
1495
+ const res = new NextResponse2(
1167
1496
  `<!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>`,
1168
1497
  { status: 200, headers: { "Content-Type": "text/html; charset=utf-8" } }
1169
1498
  );
@@ -1178,44 +1507,43 @@ async function handleBackchannelLogout(req, ctx) {
1178
1507
  { "qore.auth.event": "logout", "qore.auth.method": "backchannel" },
1179
1508
  async (auth) => {
1180
1509
  const log = getLogger();
1181
- const form = await req.formData();
1182
- const logoutToken = form.get("logout_token");
1183
- if (typeof logoutToken !== "string") {
1510
+ const logoutToken = new URLSearchParams(await req.text()).get("logout_token");
1511
+ if (!logoutToken) {
1184
1512
  auth.fail("missing_logout_token");
1185
- return new NextResponse("missing logout_token", { status: 400 });
1513
+ return new NextResponse2("missing logout_token", { status: 400 });
1186
1514
  }
1187
1515
  let claims;
1188
1516
  try {
1189
1517
  claims = await ctx.jwks.verify(logoutToken);
1190
1518
  } catch {
1191
1519
  auth.fail("invalid_logout_token");
1192
- return new NextResponse("invalid logout_token", { status: 400 });
1520
+ return new NextResponse2("invalid logout_token", { status: 400 });
1193
1521
  }
1194
1522
  if (!claims.events || !(BACKCHANNEL_EVENT in claims.events)) {
1195
1523
  auth.fail("invalid_events");
1196
- return new NextResponse("invalid logout_token events", { status: 400 });
1524
+ return new NextResponse2("invalid logout_token events", { status: 400 });
1197
1525
  }
1198
1526
  if (!claims.sub) {
1199
1527
  auth.fail("missing_sub");
1200
- return new NextResponse("missing sub", { status: 400 });
1528
+ return new NextResponse2("missing sub", { status: 400 });
1201
1529
  }
1202
1530
  await ctx.refreshStore.revokeByUser(claims.sub);
1203
1531
  log.info({ event: "auth.logout", method: "backchannel", user_sub: claims.sub }, "auth logout");
1204
- return new NextResponse("ok", { status: 200 });
1532
+ return new NextResponse2("ok", { status: 200 });
1205
1533
  }
1206
1534
  );
1207
1535
  }
1208
1536
  async function handleIdentityMismatch(req, ctx) {
1209
1537
  const handoff = await ctx.handoff.read(req.headers.get("cookie"));
1210
1538
  if (!handoff) {
1211
- return noStore(NextResponse.json({ error: "no_pending_identity" }, { status: 404 }));
1539
+ return noStore(NextResponse2.json({ error: "no_pending_identity" }, { status: 404 }));
1212
1540
  }
1213
1541
  const pending = await ctx.refreshStore.getPendingSession(handoff.sessionId);
1214
1542
  if (!pending) {
1215
- return noStore(NextResponse.json({ error: "no_pending_identity" }, { status: 404 }));
1543
+ return noStore(NextResponse2.json({ error: "no_pending_identity" }, { status: 404 }));
1216
1544
  }
1217
1545
  return noStore(
1218
- NextResponse.json({
1546
+ NextResponse2.json({
1219
1547
  expected: { email: handoff.expectedEmail },
1220
1548
  actual: { email: pending.userEmail }
1221
1549
  })
@@ -1230,12 +1558,12 @@ async function handleConfirmIdentity(req, ctx) {
1230
1558
  const handoff = await ctx.handoff.read(req.headers.get("cookie"));
1231
1559
  if (!handoff) {
1232
1560
  auth.fail("no_pending_identity");
1233
- return NextResponse.json({ error: "no_pending_identity" }, { status: 409 });
1561
+ return NextResponse2.json({ error: "no_pending_identity" }, { status: 409 });
1234
1562
  }
1235
1563
  const pending = await ctx.refreshStore.getPendingSession(handoff.sessionId);
1236
1564
  if (!pending) {
1237
1565
  auth.fail("no_pending_identity");
1238
- const res2 = NextResponse.json({ error: "no_pending_identity" }, { status: 409 });
1566
+ const res2 = NextResponse2.json({ error: "no_pending_identity" }, { status: 409 });
1239
1567
  res2.headers.append("Set-Cookie", ctx.handoff.clear());
1240
1568
  return res2;
1241
1569
  }
@@ -1253,14 +1581,14 @@ async function handleConfirmIdentity(req, ctx) {
1253
1581
  "auth identity confirm failed"
1254
1582
  );
1255
1583
  auth.fail("no_app_access");
1256
- const denied = NextResponse.json({ error: "no_app_access" }, { status: 403 });
1584
+ const denied = NextResponse2.json({ error: "no_app_access" }, { status: 403 });
1257
1585
  denied.headers.append("Set-Cookie", ctx.handoff.clear());
1258
1586
  return denied;
1259
1587
  }
1260
1588
  }
1261
1589
  if (!await ctx.refreshStore.confirmSession(handoff.sessionId)) {
1262
1590
  auth.fail("no_pending_identity");
1263
- const res2 = NextResponse.json({ error: "no_pending_identity" }, { status: 409 });
1591
+ const res2 = NextResponse2.json({ error: "no_pending_identity" }, { status: 409 });
1264
1592
  res2.headers.append("Set-Cookie", ctx.handoff.clear());
1265
1593
  return res2;
1266
1594
  }
@@ -1273,7 +1601,7 @@ async function handleConfirmIdentity(req, ctx) {
1273
1601
  },
1274
1602
  "auth identity confirmed"
1275
1603
  );
1276
- const res = new NextResponse(null, { status: 204 });
1604
+ const res = new NextResponse2(null, { status: 204 });
1277
1605
  res.headers.append(
1278
1606
  "Set-Cookie",
1279
1607
  await ctx.cookies.issue(handoff.sessionId, {
@@ -1290,14 +1618,48 @@ function resolveMePermissions(map, accessToken, clientId) {
1290
1618
  const roles = extractRoles(decodeJwtPayload(accessToken), clientId);
1291
1619
  return permissionsForRoles(map, roles);
1292
1620
  }
1293
- async function handleCallback(req, ctx) {
1294
- return runAuthSpan("Complete login", {}, async (auth) => {
1621
+ async function handleCallbackMobileAware(req, ctx) {
1622
+ const state = req.nextUrl.searchParams.get("state");
1623
+ const [row] = state ? await ctx.db.select().from(loginState).where(eq3(loginState.state, state)).limit(1) : [];
1624
+ if (!row?.mobileRedirect || !row.mobileChallenge) return handleCallback(req, ctx);
1625
+ const mobile = {
1626
+ row: { ...row, mobileRedirect: row.mobileRedirect, mobileChallenge: row.mobileChallenge }
1627
+ };
1628
+ let res = null;
1629
+ try {
1630
+ res = await handleCallback(req, ctx, mobile);
1631
+ } catch (err) {
1632
+ if (mobile.reason !== "token_exchange") {
1633
+ getLogger().error(
1634
+ { event: "auth.login.failed", surface: "mobile", reason: "internal", err },
1635
+ "auth login failed"
1636
+ );
1637
+ }
1638
+ mobile.reason ??= "internal";
1639
+ }
1640
+ if (res && (mobile.restarted || mobile.reason === void 0)) return res;
1641
+ const back = NextResponse2.redirect(
1642
+ withQuery(mobile.row.mobileRedirect, "error", mobileLoginError(mobile.reason)),
1643
+ 302
1644
+ );
1645
+ back.headers.set("Cache-Control", "no-store");
1646
+ for (const c of res?.headers.getSetCookie() ?? []) {
1647
+ if (c.startsWith(`${LOGIN_COOKIE_NAME}=`)) back.headers.append("Set-Cookie", c);
1648
+ }
1649
+ return back;
1650
+ }
1651
+ async function handleCallback(req, ctx, mobile) {
1652
+ return runAuthSpan("Complete login", mobile ? { "qore.auth.surface": "mobile" } : {}, async (auth) => {
1295
1653
  const log = getLogger();
1654
+ const fail = (reason) => {
1655
+ auth.fail(reason);
1656
+ if (mobile) mobile.reason = reason;
1657
+ };
1296
1658
  const code = req.nextUrl.searchParams.get("code");
1297
1659
  const state = req.nextUrl.searchParams.get("state");
1298
1660
  const consume = async (res) => {
1299
1661
  if (state) {
1300
- await ctx.db.delete(loginState).where(eq2(loginState.state, state));
1662
+ await ctx.db.delete(loginState).where(eq3(loginState.state, state));
1301
1663
  res.headers.append("Set-Cookie", removeBoundState(req.headers.get("cookie"), state));
1302
1664
  }
1303
1665
  return res;
@@ -1307,8 +1669,8 @@ async function handleCallback(req, ctx) {
1307
1669
  if (readBoundStates(req.headers.get("cookie")).includes(state)) return null;
1308
1670
  log.warn({ event: "auth.login.failed", reason: "state_not_bound" }, "auth login failed");
1309
1671
  auth.set("qore.auth.event", "login_failed");
1310
- auth.fail("state_not_bound");
1311
- return new NextResponse("state_not_bound", { status: 400 });
1672
+ fail("state_not_bound");
1673
+ return new NextResponse2("state_not_bound", { status: 400 });
1312
1674
  };
1313
1675
  const oidcError = req.nextUrl.searchParams.get("error");
1314
1676
  if (oidcError) {
@@ -1320,7 +1682,7 @@ async function handleCallback(req, ctx) {
1320
1682
  "auth login failed"
1321
1683
  );
1322
1684
  auth.set("qore.auth.event", "login_failed");
1323
- auth.fail(oidcError);
1685
+ fail(oidcError);
1324
1686
  const restartable = oidcError === "authentication_expired" || oidcError === "login_required";
1325
1687
  const queryRetried = req.nextUrl.searchParams.get("retried") === "1";
1326
1688
  let alreadyRetried = queryRetried;
@@ -1328,48 +1690,57 @@ async function handleCallback(req, ctx) {
1328
1690
  if (!state) {
1329
1691
  alreadyRetried = true;
1330
1692
  } else {
1331
- const [row2] = await ctx.db.select().from(loginState).where(eq2(loginState.state, state)).limit(1);
1693
+ const [row2] = await ctx.db.select().from(loginState).where(eq3(loginState.state, state)).limit(1);
1332
1694
  if (!row2 || row2.retried) alreadyRetried = true;
1333
1695
  retryRow = row2;
1334
1696
  }
1335
1697
  if (restartable && !alreadyRetried) {
1698
+ if (mobile) {
1699
+ const restart2 = new URL("/api/auth/mobile/login", ctx.publicOrigin);
1700
+ restart2.searchParams.set("challenge", mobile.row.mobileChallenge);
1701
+ restart2.searchParams.set("redirect", mobile.row.mobileRedirect);
1702
+ if (mobile.row.uiLocales) restart2.searchParams.set("locale", mobile.row.uiLocales);
1703
+ restart2.searchParams.set("retried", "1");
1704
+ mobile.restarted = true;
1705
+ return await consume(NextResponse2.redirect(restart2, 302));
1706
+ }
1336
1707
  const restart = new URL("/api/auth/login", ctx.publicOrigin);
1337
1708
  restart.searchParams.set("prompt", "login");
1338
1709
  restart.searchParams.set("retried", "1");
1339
1710
  if (retryRow?.redirectPath) restart.searchParams.set("redirect", retryRow.redirectPath);
1340
1711
  if (retryRow?.expectedEmail) restart.searchParams.set("login_hint", retryRow.expectedEmail);
1341
- return await consume(NextResponse.redirect(restart, 302));
1712
+ return await consume(NextResponse2.redirect(restart, 302));
1342
1713
  }
1343
- return await consume(new NextResponse(`login failed: ${oidcError}`, { status: 400 }));
1714
+ return await consume(new NextResponse2(`login failed: ${oidcError}`, { status: 400 }));
1344
1715
  }
1345
1716
  const bindingFailure = checkBinding();
1346
1717
  if (bindingFailure) return bindingFailure;
1347
1718
  if (!code || !state) {
1348
1719
  log.warn({ event: "auth.login.failed", reason: "missing_params" }, "auth login failed");
1349
1720
  auth.set("qore.auth.event", "login_failed");
1350
- auth.fail("missing_params");
1351
- return await consume(new NextResponse("missing code or state", { status: 400 }));
1721
+ fail("missing_params");
1722
+ return await consume(new NextResponse2("missing code or state", { status: 400 }));
1352
1723
  }
1353
- const [row] = await ctx.db.select().from(loginState).where(eq2(loginState.state, state)).limit(1);
1724
+ const [row] = await ctx.db.select().from(loginState).where(eq3(loginState.state, state)).limit(1);
1354
1725
  if (!row) {
1355
1726
  log.warn({ event: "auth.login.failed", reason: "invalid_state" }, "auth login failed");
1356
1727
  auth.set("qore.auth.event", "login_failed");
1357
- auth.fail("invalid_state");
1358
- return await consume(new NextResponse("invalid state", { status: 400 }));
1728
+ fail("invalid_state");
1729
+ return await consume(new NextResponse2("invalid state", { status: 400 }));
1359
1730
  }
1360
1731
  if (row.expiresAt < /* @__PURE__ */ new Date()) {
1361
1732
  log.warn({ event: "auth.login.failed", reason: "expired_state" }, "auth login failed");
1362
1733
  auth.set("qore.auth.event", "login_failed");
1363
- auth.fail("expired_state");
1364
- return await consume(new NextResponse("expired state", { status: 400 }));
1734
+ fail("expired_state");
1735
+ return await consume(new NextResponse2("expired state", { status: 400 }));
1365
1736
  }
1366
- const previousSessionId = await ctx.cookies.read(req.headers.get("cookie"));
1737
+ const previousSessionId = mobile ? null : await ctx.cookies.read(req.headers.get("cookie"));
1367
1738
  const iss = req.nextUrl.searchParams.get("iss");
1368
1739
  if (iss && iss !== ctx.kcClient.issuer) {
1369
1740
  log.warn({ event: "auth.login.failed", reason: "iss_mismatch", iss }, "auth login failed");
1370
1741
  auth.set("qore.auth.event", "login_failed");
1371
- auth.fail("iss_mismatch");
1372
- return await consume(new NextResponse("iss_mismatch", { status: 400 }));
1742
+ fail("iss_mismatch");
1743
+ return await consume(new NextResponse2("iss_mismatch", { status: 400 }));
1373
1744
  }
1374
1745
  try {
1375
1746
  const tokens = await ctx.kcClient.exchangeCode({ code, codeVerifier: row.codeVerifier });
@@ -1381,8 +1752,8 @@ async function handleCallback(req, ctx) {
1381
1752
  "auth login failed"
1382
1753
  );
1383
1754
  auth.set("qore.auth.event", "login_failed");
1384
- auth.fail("nonce_mismatch");
1385
- return await consume(new NextResponse("nonce_mismatch", { status: 400 }));
1755
+ fail("nonce_mismatch");
1756
+ return await consume(new NextResponse2("nonce_mismatch", { status: 400 }));
1386
1757
  }
1387
1758
  }
1388
1759
  const claims = decodeJwt3(tokens.accessToken);
@@ -1396,8 +1767,8 @@ async function handleCallback(req, ctx) {
1396
1767
  "auth login failed"
1397
1768
  );
1398
1769
  auth.set("qore.auth.event", "login_failed");
1399
- auth.fail("stale_auth_time");
1400
- return await consume(new NextResponse("re-authentication was not performed", { status: 400 }));
1770
+ fail("stale_auth_time");
1771
+ return await consume(new NextResponse2("re-authentication was not performed", { status: 400 }));
1401
1772
  }
1402
1773
  }
1403
1774
  const expectedSub = row.expectedSub;
@@ -1432,12 +1803,12 @@ async function handleCallback(req, ctx) {
1432
1803
  "auth login identity mismatch"
1433
1804
  );
1434
1805
  auth.set("qore.auth.event", "login_identity_mismatch");
1435
- auth.fail("identity_mismatch");
1806
+ fail("identity_mismatch");
1436
1807
  const target = new URL(
1437
1808
  ctx.identityMismatchPath ?? DEFAULT_IDENTITY_MISMATCH_PATH,
1438
1809
  ctx.publicOrigin
1439
1810
  );
1440
- const res2 = NextResponse.redirect(target, 302);
1811
+ const res2 = NextResponse2.redirect(target, 302);
1441
1812
  res2.headers.append("Set-Cookie", ctx.cookies.clear());
1442
1813
  res2.headers.append(
1443
1814
  "Set-Cookie",
@@ -1456,12 +1827,52 @@ async function handleCallback(req, ctx) {
1456
1827
  "auth login failed"
1457
1828
  );
1458
1829
  auth.set("qore.auth.event", "login_failed");
1459
- auth.fail("no_app_access");
1830
+ fail("no_app_access");
1460
1831
  if (previousSessionId) await ctx.refreshStore.revokeSession(previousSessionId);
1461
- const denied = NextResponse.redirect(new URL("/no-access", ctx.publicOrigin), 302);
1832
+ const denied = NextResponse2.redirect(new URL("/no-access", ctx.publicOrigin), 302);
1462
1833
  denied.headers.set("Set-Cookie", ctx.cookies.clear());
1463
1834
  return await consume(denied);
1464
1835
  }
1836
+ if (mobile) {
1837
+ const org2 = parseOrganizationClaim(claims.organization);
1838
+ const sessionId2 = await ctx.refreshStore.createSession({
1839
+ userSub: claims.sub,
1840
+ userEmail: claims.email,
1841
+ organizationId: org2.id,
1842
+ organizationAlias: org2.alias,
1843
+ accessToken: tokens.accessToken,
1844
+ accessExpiresAt: new Date(Date.now() + tokens.expiresIn * 1e3),
1845
+ idToken: tokens.idToken,
1846
+ refreshToken: tokens.refreshToken,
1847
+ refreshExpiresAt: new Date(Date.now() + tokens.refreshExpiresIn * 1e3),
1848
+ kind: "mobile"
1849
+ });
1850
+ await pruneExpiredHandoffs(ctx.db);
1851
+ const handoffCode = newHandoffCode();
1852
+ await ctx.db.insert(mobileHandoffCodes).values({
1853
+ codeHash: sha256b64url(handoffCode),
1854
+ sessionId: sessionId2,
1855
+ challenge: mobile.row.mobileChallenge,
1856
+ expiresAt: new Date(Date.now() + MOBILE_HANDOFF_TTL_SEC * 1e3)
1857
+ });
1858
+ log.info(
1859
+ {
1860
+ event: "auth.login.succeeded",
1861
+ surface: "mobile",
1862
+ user_sub: claims.sub,
1863
+ user_email: claims.email,
1864
+ org_id: org2.id,
1865
+ org_alias: org2.alias
1866
+ },
1867
+ "auth login succeeded"
1868
+ );
1869
+ auth.set("qore.auth.event", "login_succeeded");
1870
+ if (org2.alias) auth.set("qore.auth.org_alias", org2.alias);
1871
+ const res2 = NextResponse2.redirect(withQuery(mobile.row.mobileRedirect, "code", handoffCode), 302);
1872
+ res2.headers.set("Cache-Control", "no-store");
1873
+ res2.headers.set("Referrer-Policy", "no-referrer");
1874
+ return await consume(res2);
1875
+ }
1465
1876
  if (previousSessionId) await ctx.refreshStore.revokeSession(previousSessionId);
1466
1877
  const org = parseOrganizationClaim(claims.organization);
1467
1878
  const refreshExpiresAt = new Date(Date.now() + tokens.refreshExpiresIn * 1e3);
@@ -1488,14 +1899,14 @@ async function handleCallback(req, ctx) {
1488
1899
  );
1489
1900
  auth.set("qore.auth.event", "login_succeeded");
1490
1901
  if (org.alias) auth.set("qore.auth.org_alias", org.alias);
1491
- const res = NextResponse.redirect(new URL(row.redirectPath, ctx.publicOrigin), 302);
1902
+ const res = NextResponse2.redirect(new URL(row.redirectPath, ctx.publicOrigin), 302);
1492
1903
  res.headers.set("Set-Cookie", await ctx.cookies.issue(sessionId, { expiresAt: refreshExpiresAt }));
1493
1904
  return await consume(res);
1494
1905
  } catch (err) {
1495
1906
  log.error({ event: "auth.login.failed", reason: "token_exchange", err }, "auth login failed");
1496
1907
  auth.set("qore.auth.event", "login_failed");
1497
- auth.fail("token_exchange");
1498
- await ctx.db.delete(loginState).where(eq2(loginState.state, state));
1908
+ fail("token_exchange");
1909
+ await ctx.db.delete(loginState).where(eq3(loginState.state, state));
1499
1910
  throw err;
1500
1911
  }
1501
1912
  });
@@ -1524,20 +1935,28 @@ async function requireAuthFor(opts) {
1524
1935
  clientId,
1525
1936
  orgAlias: opts.orgAlias,
1526
1937
  idleTimeoutSec: opts.sessionIdleTimeoutSec ?? DEFAULT_SESSION_IDLE_TIMEOUT_SEC,
1527
- absoluteMaxSec: opts.sessionAbsoluteMaxSec ?? DEFAULT_SESSION_ABSOLUTE_MAX_SEC
1938
+ absoluteMaxSec: opts.sessionAbsoluteMaxSec ?? DEFAULT_SESSION_ABSOLUTE_MAX_SEC,
1939
+ mobile: resolveMobileAuth(opts.mobile)
1528
1940
  });
1529
1941
  }
1530
1942
 
1531
1943
  // src/next/auth/getAccessToken.ts
1532
- import { cookies as cookies2 } from "next/headers";
1944
+ import { cookies as cookies2, headers as headers2 } from "next/headers";
1533
1945
  async function resolveAccessToken(opts) {
1534
1946
  const skewSec = opts.refreshSkewSec ?? 30;
1535
1947
  const jar = await cookies2();
1536
1948
  const raw = jar.get(COOKIE_NAME)?.value;
1537
- const id = await opts.cookies.read(raw ? `${COOKIE_NAME}=${raw}` : null);
1538
- if (!id) return null;
1949
+ const authorization = opts.mobile ? (await headers2()).get("authorization") : null;
1950
+ const source = await sessionIdFrom(
1951
+ opts.cookies,
1952
+ raw ? `${COOKIE_NAME}=${raw}` : null,
1953
+ authorization,
1954
+ Boolean(opts.mobile)
1955
+ );
1956
+ if (!source) return null;
1957
+ const id = source.id;
1539
1958
  let session = await opts.refreshStore.getSession(id);
1540
- if (!session) return null;
1959
+ if (!session || !kindMatches(source.via, session)) return null;
1541
1960
  session = await refreshWithinSkew(
1542
1961
  {
1543
1962
  refreshStore: opts.refreshStore,
@@ -1545,7 +1964,8 @@ async function resolveAccessToken(opts) {
1545
1964
  skewSec,
1546
1965
  orgAlias: opts.orgAlias,
1547
1966
  idleTimeoutSec: opts.idleTimeoutSec,
1548
- absoluteMaxSec: opts.absoluteMaxSec
1967
+ absoluteMaxSec: opts.absoluteMaxSec,
1968
+ mobile: opts.mobile
1549
1969
  },
1550
1970
  id,
1551
1971
  session
@@ -1577,7 +1997,8 @@ function depsCacheKey(opts) {
1577
1997
  requireAppRole: opts.requireAppRole,
1578
1998
  permissions: opts.permissions,
1579
1999
  sessionIdleTimeoutSec: opts.sessionIdleTimeoutSec,
1580
- sessionAbsoluteMaxSec: opts.sessionAbsoluteMaxSec
2000
+ sessionAbsoluteMaxSec: opts.sessionAbsoluteMaxSec,
2001
+ mobile: opts.mobile
1581
2002
  });
1582
2003
  }
1583
2004
  async function buildDepsUncached(opts) {
@@ -1600,7 +2021,8 @@ async function buildDepsUncached(opts) {
1600
2021
  kcClient,
1601
2022
  orgAlias: opts.orgAlias,
1602
2023
  idleTimeoutSec: opts.sessionIdleTimeoutSec ?? DEFAULT_SESSION_IDLE_TIMEOUT_SEC,
1603
- absoluteMaxSec: opts.sessionAbsoluteMaxSec ?? DEFAULT_SESSION_ABSOLUTE_MAX_SEC
2024
+ absoluteMaxSec: opts.sessionAbsoluteMaxSec ?? DEFAULT_SESSION_ABSOLUTE_MAX_SEC,
2025
+ mobile: resolveMobileAuth(opts.mobile)
1604
2026
  };
1605
2027
  }
1606
2028
  async function buildDeps(opts) {
@@ -1624,7 +2046,7 @@ async function requireAccessTokenFor(opts) {
1624
2046
  }
1625
2047
 
1626
2048
  // src/next/auth/permissionGuards.ts
1627
- import { NextResponse as NextResponse2 } from "next/server";
2049
+ import { NextResponse as NextResponse3 } from "next/server";
1628
2050
  function makeGuards(map, getPermissions, requireUser = async () => {
1629
2051
  throw new AuthError("unauthenticated");
1630
2052
  }) {
@@ -1635,7 +2057,7 @@ function makeGuards(map, getPermissions, requireUser = async () => {
1635
2057
  return user;
1636
2058
  };
1637
2059
  const withPermission = (permission, handler) => async (...args) => {
1638
- if (!await can(permission)) return new NextResponse2(null, { status: 403 });
2060
+ if (!await can(permission)) return new NextResponse3(null, { status: 403 });
1639
2061
  return handler(...args);
1640
2062
  };
1641
2063
  return { can, requirePermission, withPermission };
@@ -1656,7 +2078,7 @@ function createPermissionGuards(map, getOpts) {
1656
2078
  }
1657
2079
 
1658
2080
  // src/next/auth/withConnectionToken.ts
1659
- import { timingSafeEqual } from "crypto";
2081
+ import { timingSafeEqual as timingSafeEqual2 } from "crypto";
1660
2082
  function expectedTokens() {
1661
2083
  return Object.entries(process.env).filter(([k, v]) => /^CONN_.+_TOKEN$/.test(k) && !!v).map(([, v]) => v);
1662
2084
  }
@@ -1664,7 +2086,7 @@ function safeEqual(a, b) {
1664
2086
  const ab = Buffer.from(a);
1665
2087
  const bb = Buffer.from(b);
1666
2088
  if (ab.length !== bb.length) return false;
1667
- return timingSafeEqual(ab, bb);
2089
+ return timingSafeEqual2(ab, bb);
1668
2090
  }
1669
2091
  function withConnectionToken(handler) {
1670
2092
  return async (req) => {