@quatronic/sdk 0.10.0 → 0.10.1-test.b120025

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 +6 -0
  2. package/dist/chunk-7XIDABOQ.js +83 -0
  3. package/dist/chunk-7XIDABOQ.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-YXIYI7R2.js +23 -0
  11. package/dist/chunk-YXIYI7R2.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-B_u-vpkw.d.ts +111 -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 +8 -0
  19. package/dist/expo/auth/index.js +177 -0
  20. package/dist/expo/auth/index.js.map +1 -0
  21. package/dist/expo/config/index.d.ts +16 -0
  22. package/dist/expo/config/index.js +17 -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 +39 -0
  28. package/dist/expo/query/index.js +92 -0
  29. package/dist/expo/query/index.js.map +1 -0
  30. package/dist/expo/sentry/index.d.ts +29 -0
  31. package/dist/expo/sentry/index.js +93 -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 +57 -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 +504 -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/sentry/client.js +3 -3
  42. package/dist/next/sentry/client.js.map +1 -1
  43. package/dist/next/sentry/index.js +1 -1
  44. package/dist/next/sentry/register.js +3 -3
  45. package/dist/node/sentry/index.js +1 -1
  46. package/dist/node/sentry/register.js +2 -2
  47. package/package.json +75 -2
  48. package/skills/catalog.json +3 -0
  49. package/skills/qore-add-api-route/SKILL.md +1 -1
  50. package/skills/qore-add-connection/SKILL.next.md +3 -1
  51. package/skills/qore-add-connection/SKILL.node.md +3 -1
  52. package/skills/qore-add-env-key/SKILL.md +174 -9
  53. package/skills/qore-add-feature/SKILL.md +1 -1
  54. package/skills/qore-add-integration/SKILL.next.md +4 -2
  55. package/skills/qore-add-integration/SKILL.node.md +6 -6
  56. package/skills/qore-add-page/SKILL.md +1 -1
  57. package/skills/qore-author-skill/SKILL.md +1 -1
  58. package/skills/qore-debug-issue/SKILL.md +10 -0
  59. package/skills/qore-mobile-add-screen/SKILL.md +64 -0
  60. package/skills/qore-mobile-call-server/SKILL.md +74 -0
  61. package/skills/qore-mobile-run-on-device/SKILL.md +41 -0
  62. package/skills/qore-observability/SKILL.md +17 -0
  63. package/skills/qore-secure-io/SKILL.md +15 -0
  64. package/skills/qore-ship-checklist/SKILL.md +10 -0
  65. package/skills/qore-translate-strings/SKILL.md +10 -0
  66. package/skills/qore-use-addons/SKILL.md +2 -0
  67. package/skills/qore-use-database/SKILL.md +2 -0
  68. package/skills/qore-use-design-system/SKILL.md +1 -1
  69. package/skills/qore-use-mail-domain/SKILL.next.md +1 -1
  70. package/skills/qore-use-mail-domain/SKILL.node.md +2 -2
  71. package/skills/qore-use-permissions/SKILL.md +10 -0
  72. package/dist/chunk-IFESUTF2.js.map +0 -1
  73. package/dist/chunk-TPBRMW5N.js.map +0 -1
  74. /package/dist/{chunk-YFZB5EW6.js.map → chunk-P5GBQVO7.js.map} +0 -0
  75. /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,170 @@ 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
+ 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
+
836
1113
  // src/next/auth/createAuthRouteHandlers.ts
837
1114
  var AUTH_TIME_SKEW_SEC = 5;
838
1115
  var DEFAULT_IDENTITY_MISMATCH_PATH = "/login?reason=identity_mismatch";
@@ -840,7 +1117,8 @@ var LOGGED_OUT_PATH = "/api/auth/logged-out";
840
1117
  var CLEAR_SITE_DATA = '"cookies"';
841
1118
  function segment(req) {
842
1119
  const parts = req.nextUrl.pathname.split("/").filter(Boolean);
843
- return parts[parts.length - 1] ?? "";
1120
+ const last = parts[parts.length - 1] ?? "";
1121
+ return parts[parts.length - 2] === "mobile" ? `mobile/${last}` : last;
844
1122
  }
845
1123
  function noStore(res) {
846
1124
  res.headers.set("Cache-Control", "no-store");
@@ -868,7 +1146,9 @@ async function createAuthRouteHandlers(opts) {
868
1146
  realm: opts.realm,
869
1147
  audience: opts.clientId
870
1148
  });
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 };
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 });
872
1152
  async function GET(req) {
873
1153
  switch (segment(req)) {
874
1154
  case "login":
@@ -876,7 +1156,11 @@ async function createAuthRouteHandlers(opts) {
876
1156
  case "me":
877
1157
  return handleMe(req, ctx);
878
1158
  case "callback":
879
- return handleCallback(req, ctx);
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();
880
1164
  case "logout":
881
1165
  return handleLogoutRedirect(req, ctx);
882
1166
  case "logged-out":
@@ -884,7 +1168,7 @@ async function createAuthRouteHandlers(opts) {
884
1168
  case "identity-mismatch":
885
1169
  return handleIdentityMismatch(req, ctx);
886
1170
  default:
887
- return NextResponse.json({ error: "not_found" }, { status: 404 });
1171
+ return NextResponse2.json({ error: "not_found" }, { status: 404 });
888
1172
  }
889
1173
  }
890
1174
  async function POST(req) {
@@ -897,8 +1181,12 @@ async function createAuthRouteHandlers(opts) {
897
1181
  return handleBackchannelLogout(req, ctx);
898
1182
  case "confirm-identity":
899
1183
  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();
900
1188
  default:
901
- return NextResponse.json({ error: "not_found" }, { status: 404 });
1189
+ return NextResponse2.json({ error: "not_found" }, { status: 404 });
902
1190
  }
903
1191
  }
904
1192
  return { GET, POST };
@@ -993,7 +1281,7 @@ async function handleLogin(req, ctx) {
993
1281
  authorizePrompt === "id_token_hint" ? { idTokenHint } : { prompt: "select_account" }
994
1282
  )
995
1283
  });
996
- const res = NextResponse.redirect(url, 302);
1284
+ const res = NextResponse2.redirect(url, 302);
997
1285
  res.headers.append("Set-Cookie", appendBoundState(req.headers.get("cookie"), state));
998
1286
  res.headers.append("Set-Cookie", ctx.handoff.clear());
999
1287
  return res;
@@ -1002,17 +1290,28 @@ async function handleLogin(req, ctx) {
1002
1290
  }
1003
1291
  async function handleMe(req, ctx) {
1004
1292
  try {
1005
- return noStore(await handleMeInner(req, ctx));
1293
+ const res = noStore(await handleMeInner(req, ctx));
1294
+ if (ctx.mobile) res.headers.set("Vary", "Cookie, Authorization");
1295
+ return res;
1006
1296
  } catch (err) {
1007
1297
  getLogger().error({ err }, "auth /me failed unexpectedly");
1008
- return noStore(NextResponse.json({ error: "internal" }, { status: 500 }));
1298
+ return noStore(NextResponse2.json({ error: "internal" }, { status: 500 }));
1009
1299
  }
1010
1300
  }
1011
1301
  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 });
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";
1014
1311
  const existing = await ctx.refreshStore.getSession(id);
1015
- if (!existing) return NextResponse.json({ error: "unauthenticated" }, { status: 401 });
1312
+ if (!existing || !kindMatches(source.via, existing)) {
1313
+ return NextResponse2.json({ error: "unauthenticated" }, { status: 401 });
1314
+ }
1016
1315
  let session;
1017
1316
  try {
1018
1317
  session = await refreshWithinSkew(
@@ -1022,7 +1321,8 @@ async function handleMeInner(req, ctx) {
1022
1321
  skewSec: 30,
1023
1322
  orgAlias: ctx.orgAlias,
1024
1323
  idleTimeoutSec: ctx.idleTimeoutSec,
1025
- absoluteMaxSec: ctx.absoluteMaxSec
1324
+ absoluteMaxSec: ctx.absoluteMaxSec,
1325
+ mobile: ctx.mobile
1026
1326
  },
1027
1327
  id,
1028
1328
  existing
@@ -1030,17 +1330,27 @@ async function handleMeInner(req, ctx) {
1030
1330
  } catch (err) {
1031
1331
  if (!(err instanceof AuthError)) throw err;
1032
1332
  if (err.reason === "refresh_unavailable") {
1033
- return NextResponse.json({ error: "refresh_unavailable" }, { status: 503 });
1333
+ return NextResponse2.json({ error: "refresh_unavailable" }, { status: 503 });
1034
1334
  }
1035
- const res = NextResponse.json({ error: "session_expired" }, { status: 401 });
1036
- res.headers.set("Set-Cookie", ctx.cookies.clear());
1335
+ const res = NextResponse2.json({ error: "session_expired" }, { status: 401 });
1336
+ if (!bearer) res.headers.set("Set-Cookie", ctx.cookies.clear());
1037
1337
  return res;
1038
1338
  }
1039
1339
  const claims = decodeJwt3(session.accessToken);
1040
1340
  if (ctx.requireAppRole && rolesForClient(claims, ctx.clientId).length === 0) {
1041
- return NextResponse.json({ error: "no_app_access" }, { status: 403 });
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
+ });
1042
1352
  }
1043
- return NextResponse.json({
1353
+ return NextResponse2.json({
1044
1354
  user: { id: session.userSub, email: session.userEmail },
1045
1355
  organization: { id: session.organizationId, alias: session.organizationAlias },
1046
1356
  permissions: resolveMePermissions(ctx.permissions, session.accessToken, ctx.clientId)
@@ -1052,12 +1362,12 @@ async function handleRefresh(req, ctx) {
1052
1362
  const id = await ctx.cookies.read(req.headers.get("cookie"));
1053
1363
  if (!id) {
1054
1364
  auth.set("qore.auth.event", "refresh_skipped");
1055
- return NextResponse.json({ error: "unauthenticated" }, { status: 401 });
1365
+ return NextResponse2.json({ error: "unauthenticated" }, { status: 401 });
1056
1366
  }
1057
1367
  const session = await ctx.refreshStore.getSession(id);
1058
1368
  if (!session) {
1059
1369
  auth.set("qore.auth.event", "refresh_skipped");
1060
- return NextResponse.json({ error: "unauthenticated" }, { status: 401 });
1370
+ return NextResponse2.json({ error: "unauthenticated" }, { status: 401 });
1061
1371
  }
1062
1372
  try {
1063
1373
  await refreshWithinSkew(
@@ -1077,15 +1387,15 @@ async function handleRefresh(req, ctx) {
1077
1387
  auth.set("qore.auth.event", "refresh_failed");
1078
1388
  if (err.reason === "refresh_unavailable") {
1079
1389
  auth.fail("refresh_unavailable");
1080
- return NextResponse.json({ error: "refresh_unavailable" }, { status: 503 });
1390
+ return NextResponse2.json({ error: "refresh_unavailable" }, { status: 503 });
1081
1391
  }
1082
1392
  auth.fail("session_expired");
1083
- const res = NextResponse.json({ error: "session_expired" }, { status: 401 });
1393
+ const res = NextResponse2.json({ error: "session_expired" }, { status: 401 });
1084
1394
  res.headers.set("Set-Cookie", ctx.cookies.clear());
1085
1395
  return res;
1086
1396
  }
1087
1397
  auth.set("qore.auth.event", "session_refreshed");
1088
- return new NextResponse(null, { status: 204 });
1398
+ return new NextResponse2(null, { status: 204 });
1089
1399
  });
1090
1400
  }
1091
1401
  async function handleLogout(req, ctx) {
@@ -1113,7 +1423,7 @@ async function handleLogout(req, ctx) {
1113
1423
  );
1114
1424
  }
1115
1425
  }
1116
- const res = new NextResponse(null, { status: 204 });
1426
+ const res = new NextResponse2(null, { status: 204 });
1117
1427
  res.headers.set("Set-Cookie", ctx.cookies.clear());
1118
1428
  return res;
1119
1429
  });
@@ -1154,7 +1464,7 @@ async function handleLogoutRedirect(req, ctx) {
1154
1464
  postLogoutRedirectUri: landing.toString(),
1155
1465
  idTokenHint
1156
1466
  });
1157
- const res = NextResponse.redirect(endSessionUrl, 302);
1467
+ const res = NextResponse2.redirect(endSessionUrl, 302);
1158
1468
  res.headers.set("Set-Cookie", ctx.cookies.clear());
1159
1469
  return res;
1160
1470
  });
@@ -1163,7 +1473,7 @@ async function handleLoggedOut(req, ctx) {
1163
1473
  const target = safeRedirect(req.nextUrl.searchParams.get("redirect"));
1164
1474
  const attr = target.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/"/g, "&quot;");
1165
1475
  const literal = JSON.stringify(target).replace(/</g, "\\u003c");
1166
- const res = new NextResponse(
1476
+ const res = new NextResponse2(
1167
1477
  `<!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
1478
  { status: 200, headers: { "Content-Type": "text/html; charset=utf-8" } }
1169
1479
  );
@@ -1178,44 +1488,43 @@ async function handleBackchannelLogout(req, ctx) {
1178
1488
  { "qore.auth.event": "logout", "qore.auth.method": "backchannel" },
1179
1489
  async (auth) => {
1180
1490
  const log = getLogger();
1181
- const form = await req.formData();
1182
- const logoutToken = form.get("logout_token");
1183
- if (typeof logoutToken !== "string") {
1491
+ const logoutToken = new URLSearchParams(await req.text()).get("logout_token");
1492
+ if (!logoutToken) {
1184
1493
  auth.fail("missing_logout_token");
1185
- return new NextResponse("missing logout_token", { status: 400 });
1494
+ return new NextResponse2("missing logout_token", { status: 400 });
1186
1495
  }
1187
1496
  let claims;
1188
1497
  try {
1189
1498
  claims = await ctx.jwks.verify(logoutToken);
1190
1499
  } catch {
1191
1500
  auth.fail("invalid_logout_token");
1192
- return new NextResponse("invalid logout_token", { status: 400 });
1501
+ return new NextResponse2("invalid logout_token", { status: 400 });
1193
1502
  }
1194
1503
  if (!claims.events || !(BACKCHANNEL_EVENT in claims.events)) {
1195
1504
  auth.fail("invalid_events");
1196
- return new NextResponse("invalid logout_token events", { status: 400 });
1505
+ return new NextResponse2("invalid logout_token events", { status: 400 });
1197
1506
  }
1198
1507
  if (!claims.sub) {
1199
1508
  auth.fail("missing_sub");
1200
- return new NextResponse("missing sub", { status: 400 });
1509
+ return new NextResponse2("missing sub", { status: 400 });
1201
1510
  }
1202
1511
  await ctx.refreshStore.revokeByUser(claims.sub);
1203
1512
  log.info({ event: "auth.logout", method: "backchannel", user_sub: claims.sub }, "auth logout");
1204
- return new NextResponse("ok", { status: 200 });
1513
+ return new NextResponse2("ok", { status: 200 });
1205
1514
  }
1206
1515
  );
1207
1516
  }
1208
1517
  async function handleIdentityMismatch(req, ctx) {
1209
1518
  const handoff = await ctx.handoff.read(req.headers.get("cookie"));
1210
1519
  if (!handoff) {
1211
- return noStore(NextResponse.json({ error: "no_pending_identity" }, { status: 404 }));
1520
+ return noStore(NextResponse2.json({ error: "no_pending_identity" }, { status: 404 }));
1212
1521
  }
1213
1522
  const pending = await ctx.refreshStore.getPendingSession(handoff.sessionId);
1214
1523
  if (!pending) {
1215
- return noStore(NextResponse.json({ error: "no_pending_identity" }, { status: 404 }));
1524
+ return noStore(NextResponse2.json({ error: "no_pending_identity" }, { status: 404 }));
1216
1525
  }
1217
1526
  return noStore(
1218
- NextResponse.json({
1527
+ NextResponse2.json({
1219
1528
  expected: { email: handoff.expectedEmail },
1220
1529
  actual: { email: pending.userEmail }
1221
1530
  })
@@ -1230,12 +1539,12 @@ async function handleConfirmIdentity(req, ctx) {
1230
1539
  const handoff = await ctx.handoff.read(req.headers.get("cookie"));
1231
1540
  if (!handoff) {
1232
1541
  auth.fail("no_pending_identity");
1233
- return NextResponse.json({ error: "no_pending_identity" }, { status: 409 });
1542
+ return NextResponse2.json({ error: "no_pending_identity" }, { status: 409 });
1234
1543
  }
1235
1544
  const pending = await ctx.refreshStore.getPendingSession(handoff.sessionId);
1236
1545
  if (!pending) {
1237
1546
  auth.fail("no_pending_identity");
1238
- const res2 = NextResponse.json({ error: "no_pending_identity" }, { status: 409 });
1547
+ const res2 = NextResponse2.json({ error: "no_pending_identity" }, { status: 409 });
1239
1548
  res2.headers.append("Set-Cookie", ctx.handoff.clear());
1240
1549
  return res2;
1241
1550
  }
@@ -1253,14 +1562,14 @@ async function handleConfirmIdentity(req, ctx) {
1253
1562
  "auth identity confirm failed"
1254
1563
  );
1255
1564
  auth.fail("no_app_access");
1256
- const denied = NextResponse.json({ error: "no_app_access" }, { status: 403 });
1565
+ const denied = NextResponse2.json({ error: "no_app_access" }, { status: 403 });
1257
1566
  denied.headers.append("Set-Cookie", ctx.handoff.clear());
1258
1567
  return denied;
1259
1568
  }
1260
1569
  }
1261
1570
  if (!await ctx.refreshStore.confirmSession(handoff.sessionId)) {
1262
1571
  auth.fail("no_pending_identity");
1263
- const res2 = NextResponse.json({ error: "no_pending_identity" }, { status: 409 });
1572
+ const res2 = NextResponse2.json({ error: "no_pending_identity" }, { status: 409 });
1264
1573
  res2.headers.append("Set-Cookie", ctx.handoff.clear());
1265
1574
  return res2;
1266
1575
  }
@@ -1273,7 +1582,7 @@ async function handleConfirmIdentity(req, ctx) {
1273
1582
  },
1274
1583
  "auth identity confirmed"
1275
1584
  );
1276
- const res = new NextResponse(null, { status: 204 });
1585
+ const res = new NextResponse2(null, { status: 204 });
1277
1586
  res.headers.append(
1278
1587
  "Set-Cookie",
1279
1588
  await ctx.cookies.issue(handoff.sessionId, {
@@ -1290,14 +1599,48 @@ function resolveMePermissions(map, accessToken, clientId) {
1290
1599
  const roles = extractRoles(decodeJwtPayload(accessToken), clientId);
1291
1600
  return permissionsForRoles(map, roles);
1292
1601
  }
1293
- async function handleCallback(req, ctx) {
1294
- return runAuthSpan("Complete login", {}, async (auth) => {
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) => {
1295
1634
  const log = getLogger();
1635
+ const fail = (reason) => {
1636
+ auth.fail(reason);
1637
+ if (mobile) mobile.reason = reason;
1638
+ };
1296
1639
  const code = req.nextUrl.searchParams.get("code");
1297
1640
  const state = req.nextUrl.searchParams.get("state");
1298
1641
  const consume = async (res) => {
1299
1642
  if (state) {
1300
- await ctx.db.delete(loginState).where(eq2(loginState.state, state));
1643
+ await ctx.db.delete(loginState).where(eq3(loginState.state, state));
1301
1644
  res.headers.append("Set-Cookie", removeBoundState(req.headers.get("cookie"), state));
1302
1645
  }
1303
1646
  return res;
@@ -1307,8 +1650,8 @@ async function handleCallback(req, ctx) {
1307
1650
  if (readBoundStates(req.headers.get("cookie")).includes(state)) return null;
1308
1651
  log.warn({ event: "auth.login.failed", reason: "state_not_bound" }, "auth login failed");
1309
1652
  auth.set("qore.auth.event", "login_failed");
1310
- auth.fail("state_not_bound");
1311
- return new NextResponse("state_not_bound", { status: 400 });
1653
+ fail("state_not_bound");
1654
+ return new NextResponse2("state_not_bound", { status: 400 });
1312
1655
  };
1313
1656
  const oidcError = req.nextUrl.searchParams.get("error");
1314
1657
  if (oidcError) {
@@ -1320,7 +1663,7 @@ async function handleCallback(req, ctx) {
1320
1663
  "auth login failed"
1321
1664
  );
1322
1665
  auth.set("qore.auth.event", "login_failed");
1323
- auth.fail(oidcError);
1666
+ fail(oidcError);
1324
1667
  const restartable = oidcError === "authentication_expired" || oidcError === "login_required";
1325
1668
  const queryRetried = req.nextUrl.searchParams.get("retried") === "1";
1326
1669
  let alreadyRetried = queryRetried;
@@ -1328,48 +1671,57 @@ async function handleCallback(req, ctx) {
1328
1671
  if (!state) {
1329
1672
  alreadyRetried = true;
1330
1673
  } else {
1331
- const [row2] = await ctx.db.select().from(loginState).where(eq2(loginState.state, state)).limit(1);
1674
+ const [row2] = await ctx.db.select().from(loginState).where(eq3(loginState.state, state)).limit(1);
1332
1675
  if (!row2 || row2.retried) alreadyRetried = true;
1333
1676
  retryRow = row2;
1334
1677
  }
1335
1678
  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
+ }
1336
1688
  const restart = new URL("/api/auth/login", ctx.publicOrigin);
1337
1689
  restart.searchParams.set("prompt", "login");
1338
1690
  restart.searchParams.set("retried", "1");
1339
1691
  if (retryRow?.redirectPath) restart.searchParams.set("redirect", retryRow.redirectPath);
1340
1692
  if (retryRow?.expectedEmail) restart.searchParams.set("login_hint", retryRow.expectedEmail);
1341
- return await consume(NextResponse.redirect(restart, 302));
1693
+ return await consume(NextResponse2.redirect(restart, 302));
1342
1694
  }
1343
- return await consume(new NextResponse(`login failed: ${oidcError}`, { status: 400 }));
1695
+ return await consume(new NextResponse2(`login failed: ${oidcError}`, { status: 400 }));
1344
1696
  }
1345
1697
  const bindingFailure = checkBinding();
1346
1698
  if (bindingFailure) return bindingFailure;
1347
1699
  if (!code || !state) {
1348
1700
  log.warn({ event: "auth.login.failed", reason: "missing_params" }, "auth login failed");
1349
1701
  auth.set("qore.auth.event", "login_failed");
1350
- auth.fail("missing_params");
1351
- return await consume(new NextResponse("missing code or state", { status: 400 }));
1702
+ fail("missing_params");
1703
+ return await consume(new NextResponse2("missing code or state", { status: 400 }));
1352
1704
  }
1353
- const [row] = await ctx.db.select().from(loginState).where(eq2(loginState.state, state)).limit(1);
1705
+ const [row] = await ctx.db.select().from(loginState).where(eq3(loginState.state, state)).limit(1);
1354
1706
  if (!row) {
1355
1707
  log.warn({ event: "auth.login.failed", reason: "invalid_state" }, "auth login failed");
1356
1708
  auth.set("qore.auth.event", "login_failed");
1357
- auth.fail("invalid_state");
1358
- return await consume(new NextResponse("invalid state", { status: 400 }));
1709
+ fail("invalid_state");
1710
+ return await consume(new NextResponse2("invalid state", { status: 400 }));
1359
1711
  }
1360
1712
  if (row.expiresAt < /* @__PURE__ */ new Date()) {
1361
1713
  log.warn({ event: "auth.login.failed", reason: "expired_state" }, "auth login failed");
1362
1714
  auth.set("qore.auth.event", "login_failed");
1363
- auth.fail("expired_state");
1364
- return await consume(new NextResponse("expired state", { status: 400 }));
1715
+ fail("expired_state");
1716
+ return await consume(new NextResponse2("expired state", { status: 400 }));
1365
1717
  }
1366
- const previousSessionId = await ctx.cookies.read(req.headers.get("cookie"));
1718
+ const previousSessionId = mobile ? null : await ctx.cookies.read(req.headers.get("cookie"));
1367
1719
  const iss = req.nextUrl.searchParams.get("iss");
1368
1720
  if (iss && iss !== ctx.kcClient.issuer) {
1369
1721
  log.warn({ event: "auth.login.failed", reason: "iss_mismatch", iss }, "auth login failed");
1370
1722
  auth.set("qore.auth.event", "login_failed");
1371
- auth.fail("iss_mismatch");
1372
- return await consume(new NextResponse("iss_mismatch", { status: 400 }));
1723
+ fail("iss_mismatch");
1724
+ return await consume(new NextResponse2("iss_mismatch", { status: 400 }));
1373
1725
  }
1374
1726
  try {
1375
1727
  const tokens = await ctx.kcClient.exchangeCode({ code, codeVerifier: row.codeVerifier });
@@ -1381,8 +1733,8 @@ async function handleCallback(req, ctx) {
1381
1733
  "auth login failed"
1382
1734
  );
1383
1735
  auth.set("qore.auth.event", "login_failed");
1384
- auth.fail("nonce_mismatch");
1385
- return await consume(new NextResponse("nonce_mismatch", { status: 400 }));
1736
+ fail("nonce_mismatch");
1737
+ return await consume(new NextResponse2("nonce_mismatch", { status: 400 }));
1386
1738
  }
1387
1739
  }
1388
1740
  const claims = decodeJwt3(tokens.accessToken);
@@ -1396,8 +1748,8 @@ async function handleCallback(req, ctx) {
1396
1748
  "auth login failed"
1397
1749
  );
1398
1750
  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 }));
1751
+ fail("stale_auth_time");
1752
+ return await consume(new NextResponse2("re-authentication was not performed", { status: 400 }));
1401
1753
  }
1402
1754
  }
1403
1755
  const expectedSub = row.expectedSub;
@@ -1432,12 +1784,12 @@ async function handleCallback(req, ctx) {
1432
1784
  "auth login identity mismatch"
1433
1785
  );
1434
1786
  auth.set("qore.auth.event", "login_identity_mismatch");
1435
- auth.fail("identity_mismatch");
1787
+ fail("identity_mismatch");
1436
1788
  const target = new URL(
1437
1789
  ctx.identityMismatchPath ?? DEFAULT_IDENTITY_MISMATCH_PATH,
1438
1790
  ctx.publicOrigin
1439
1791
  );
1440
- const res2 = NextResponse.redirect(target, 302);
1792
+ const res2 = NextResponse2.redirect(target, 302);
1441
1793
  res2.headers.append("Set-Cookie", ctx.cookies.clear());
1442
1794
  res2.headers.append(
1443
1795
  "Set-Cookie",
@@ -1456,12 +1808,52 @@ async function handleCallback(req, ctx) {
1456
1808
  "auth login failed"
1457
1809
  );
1458
1810
  auth.set("qore.auth.event", "login_failed");
1459
- auth.fail("no_app_access");
1811
+ fail("no_app_access");
1460
1812
  if (previousSessionId) await ctx.refreshStore.revokeSession(previousSessionId);
1461
- const denied = NextResponse.redirect(new URL("/no-access", ctx.publicOrigin), 302);
1813
+ const denied = NextResponse2.redirect(new URL("/no-access", ctx.publicOrigin), 302);
1462
1814
  denied.headers.set("Set-Cookie", ctx.cookies.clear());
1463
1815
  return await consume(denied);
1464
1816
  }
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
+ }
1465
1857
  if (previousSessionId) await ctx.refreshStore.revokeSession(previousSessionId);
1466
1858
  const org = parseOrganizationClaim(claims.organization);
1467
1859
  const refreshExpiresAt = new Date(Date.now() + tokens.refreshExpiresIn * 1e3);
@@ -1488,14 +1880,14 @@ async function handleCallback(req, ctx) {
1488
1880
  );
1489
1881
  auth.set("qore.auth.event", "login_succeeded");
1490
1882
  if (org.alias) auth.set("qore.auth.org_alias", org.alias);
1491
- const res = NextResponse.redirect(new URL(row.redirectPath, ctx.publicOrigin), 302);
1883
+ const res = NextResponse2.redirect(new URL(row.redirectPath, ctx.publicOrigin), 302);
1492
1884
  res.headers.set("Set-Cookie", await ctx.cookies.issue(sessionId, { expiresAt: refreshExpiresAt }));
1493
1885
  return await consume(res);
1494
1886
  } catch (err) {
1495
1887
  log.error({ event: "auth.login.failed", reason: "token_exchange", err }, "auth login failed");
1496
1888
  auth.set("qore.auth.event", "login_failed");
1497
- auth.fail("token_exchange");
1498
- await ctx.db.delete(loginState).where(eq2(loginState.state, state));
1889
+ fail("token_exchange");
1890
+ await ctx.db.delete(loginState).where(eq3(loginState.state, state));
1499
1891
  throw err;
1500
1892
  }
1501
1893
  });
@@ -1524,20 +1916,28 @@ async function requireAuthFor(opts) {
1524
1916
  clientId,
1525
1917
  orgAlias: opts.orgAlias,
1526
1918
  idleTimeoutSec: opts.sessionIdleTimeoutSec ?? DEFAULT_SESSION_IDLE_TIMEOUT_SEC,
1527
- absoluteMaxSec: opts.sessionAbsoluteMaxSec ?? DEFAULT_SESSION_ABSOLUTE_MAX_SEC
1919
+ absoluteMaxSec: opts.sessionAbsoluteMaxSec ?? DEFAULT_SESSION_ABSOLUTE_MAX_SEC,
1920
+ mobile: resolveMobileAuth(opts.mobile)
1528
1921
  });
1529
1922
  }
1530
1923
 
1531
1924
  // src/next/auth/getAccessToken.ts
1532
- import { cookies as cookies2 } from "next/headers";
1925
+ import { cookies as cookies2, headers as headers2 } from "next/headers";
1533
1926
  async function resolveAccessToken(opts) {
1534
1927
  const skewSec = opts.refreshSkewSec ?? 30;
1535
1928
  const jar = await cookies2();
1536
1929
  const raw = jar.get(COOKIE_NAME)?.value;
1537
- const id = await opts.cookies.read(raw ? `${COOKIE_NAME}=${raw}` : null);
1538
- if (!id) return null;
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;
1539
1939
  let session = await opts.refreshStore.getSession(id);
1540
- if (!session) return null;
1940
+ if (!session || !kindMatches(source.via, session)) return null;
1541
1941
  session = await refreshWithinSkew(
1542
1942
  {
1543
1943
  refreshStore: opts.refreshStore,
@@ -1545,7 +1945,8 @@ async function resolveAccessToken(opts) {
1545
1945
  skewSec,
1546
1946
  orgAlias: opts.orgAlias,
1547
1947
  idleTimeoutSec: opts.idleTimeoutSec,
1548
- absoluteMaxSec: opts.absoluteMaxSec
1948
+ absoluteMaxSec: opts.absoluteMaxSec,
1949
+ mobile: opts.mobile
1549
1950
  },
1550
1951
  id,
1551
1952
  session
@@ -1577,7 +1978,8 @@ function depsCacheKey(opts) {
1577
1978
  requireAppRole: opts.requireAppRole,
1578
1979
  permissions: opts.permissions,
1579
1980
  sessionIdleTimeoutSec: opts.sessionIdleTimeoutSec,
1580
- sessionAbsoluteMaxSec: opts.sessionAbsoluteMaxSec
1981
+ sessionAbsoluteMaxSec: opts.sessionAbsoluteMaxSec,
1982
+ mobile: opts.mobile
1581
1983
  });
1582
1984
  }
1583
1985
  async function buildDepsUncached(opts) {
@@ -1600,7 +2002,8 @@ async function buildDepsUncached(opts) {
1600
2002
  kcClient,
1601
2003
  orgAlias: opts.orgAlias,
1602
2004
  idleTimeoutSec: opts.sessionIdleTimeoutSec ?? DEFAULT_SESSION_IDLE_TIMEOUT_SEC,
1603
- absoluteMaxSec: opts.sessionAbsoluteMaxSec ?? DEFAULT_SESSION_ABSOLUTE_MAX_SEC
2005
+ absoluteMaxSec: opts.sessionAbsoluteMaxSec ?? DEFAULT_SESSION_ABSOLUTE_MAX_SEC,
2006
+ mobile: resolveMobileAuth(opts.mobile)
1604
2007
  };
1605
2008
  }
1606
2009
  async function buildDeps(opts) {
@@ -1624,7 +2027,7 @@ async function requireAccessTokenFor(opts) {
1624
2027
  }
1625
2028
 
1626
2029
  // src/next/auth/permissionGuards.ts
1627
- import { NextResponse as NextResponse2 } from "next/server";
2030
+ import { NextResponse as NextResponse3 } from "next/server";
1628
2031
  function makeGuards(map, getPermissions, requireUser = async () => {
1629
2032
  throw new AuthError("unauthenticated");
1630
2033
  }) {
@@ -1635,7 +2038,7 @@ function makeGuards(map, getPermissions, requireUser = async () => {
1635
2038
  return user;
1636
2039
  };
1637
2040
  const withPermission = (permission, handler) => async (...args) => {
1638
- if (!await can(permission)) return new NextResponse2(null, { status: 403 });
2041
+ if (!await can(permission)) return new NextResponse3(null, { status: 403 });
1639
2042
  return handler(...args);
1640
2043
  };
1641
2044
  return { can, requirePermission, withPermission };
@@ -1656,7 +2059,7 @@ function createPermissionGuards(map, getOpts) {
1656
2059
  }
1657
2060
 
1658
2061
  // src/next/auth/withConnectionToken.ts
1659
- import { timingSafeEqual } from "crypto";
2062
+ import { timingSafeEqual as timingSafeEqual2 } from "crypto";
1660
2063
  function expectedTokens() {
1661
2064
  return Object.entries(process.env).filter(([k, v]) => /^CONN_.+_TOKEN$/.test(k) && !!v).map(([, v]) => v);
1662
2065
  }
@@ -1664,7 +2067,7 @@ function safeEqual(a, b) {
1664
2067
  const ab = Buffer.from(a);
1665
2068
  const bb = Buffer.from(b);
1666
2069
  if (ab.length !== bb.length) return false;
1667
- return timingSafeEqual(ab, bb);
2070
+ return timingSafeEqual2(ab, bb);
1668
2071
  }
1669
2072
  function withConnectionToken(handler) {
1670
2073
  return async (req) => {