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