Skip to content

armgit / qm

Public Imported from GitHub
0

Multiplayer agent harness for work.

Add opt-in trusted sign-in switching and provider memory (#1232)

Regan Bell862649540677
diff --git a/docs/images/trusted-signin.png b/docs/images/trusted-signin.png
new file mode 100644
index 000000000..7bd0d1071
Binary files /dev/null and b/docs/images/trusted-signin.png differ
diff --git a/plugins/auth/README.md b/plugins/auth/README.md
index 32b5f2513..fbf5c1dba 100644
--- a/plugins/auth/README.md
+++ b/plugins/auth/README.md
@@ -136,3 +136,9 @@ the authenticated email principal. The signed core endpoint
from that user's portal identity or an authorized administrator. These operations
prevent future silent reauthentication; already-issued stateless portal sessions
remain valid until their normal expiry.
+
+When hosted by a portal with trusted OIDC and an explicit provider label configured,
+the embedded broker receives
+its trusted provider label and shows an alternate sign-in link throughout the
+email flow. The link starts a fresh trusted login through the portal, without
+submitting an email or linking the two identities. Standalone brokers omit it.
diff --git a/plugins/auth/src/index.ts b/plugins/auth/src/index.ts
index 839e02acd..0aefcce6d 100644
--- a/plugins/auth/src/index.ts
+++ b/plugins/auth/src/index.ts
@@ -23,7 +23,9 @@ export function bootChecks(): void {
throw new Error(`auth broker refusing to start: ${problems.length} misconfiguration(s)`);
}
-export async function startServer(options: { port?: number; host?: string } = {}): Promise<import("node:http").Server> {
+export async function startServer(
+ options: { port?: number; host?: string; trustedSignInLabel?: string } = {},
+): Promise<import("node:http").Server> {
bootChecks();
const signingKey = await loadSigningKey(CFG.signingJwk!);
const mailer = mailerFor(CFG);
@@ -39,6 +41,7 @@ export async function startServer(options: { port?: number; host?: string } = {}
});
const handle = createAuthHandler({
cfg: CFG,
+ trustedSignInLabel: options.trustedSignInLabel,
signingKey,
signer: new TokenSigner(CFG.tokenSecret, CFG.issuer),
sessions: coreRememberedSessions(CFG.coreApiUrl, CFG.coreSigningSecret),
diff --git a/plugins/auth/src/pages.ts b/plugins/auth/src/pages.ts
index 47fec76b4..3f86f2cb4 100644
--- a/plugins/auth/src/pages.ts
+++ b/plugins/auth/src/pages.ts
@@ -67,6 +67,9 @@ const STYLE = `<style>
text-decoration:none; font:inherit; font-weight:600; border-radius:var(--radius-md); cursor:pointer;
background:var(--text); color:var(--bg); border:1px solid var(--text); }
.btn:hover{ opacity:.9; }
+ .alternative{ background:var(--surface); color:var(--text); border-color:var(--border); }
+ .divider{ display:flex; align-items:center; gap:16px; margin:24px 0; color:var(--muted); font-size:11px; font-weight:600; letter-spacing:.08em; }
+ .divider::before,.divider::after{ content:""; flex:1; height:1px; background:var(--border); }
.help{ color:var(--muted); font-size:12.5px; margin:20px 0 0; }
.who{ display:block; margin:0 auto 22px; font-size:13px; color:var(--text); background:var(--secondary);
border:1px solid var(--border); border-radius:var(--radius-md); padding:11px 14px; word-break:break-word; }
@@ -80,6 +83,7 @@ const LOCK_ICON = `<svg viewBox="0 0 24 24"><rect x="5" y="11" width="14" height
function page(o: {
title: string;
brandName: string;
+ trustedSignInLabel?: string;
icon: string;
warn?: boolean;
heading: string;
@@ -104,6 +108,7 @@ ${STYLE}
<p class="msg">${escapeHtml(o.msg)}</p>
${o.body ?? ""}
<p class="help">${escapeHtml(o.help)}</p>
+ ${o.trustedSignInLabel ? `<div class="divider">OR</div><a class="btn alternative" href="/auth/trusted/login">Sign in with ${escapeHtml(o.trustedSignInLabel)}</a>` : ""}
</section>
</main>
</body>
@@ -112,6 +117,7 @@ ${STYLE}
export function emailFormPage(o: {
brandName: string;
+ trustedSignInLabel?: string;
action: string;
requestToken: string;
email?: string;
@@ -120,6 +126,7 @@ export function emailFormPage(o: {
return page({
title: "Sign in",
brandName: o.brandName,
+ trustedSignInLabel: o.trustedSignInLabel,
icon: MAIL_ICON,
heading: `Sign in to ${o.brandName}`,
msg: "Enter your work email and we'll send you a one-time sign-in link.",
@@ -134,10 +141,16 @@ export function emailFormPage(o: {
});
}
-export function linkSentPage(o: { brandName: string; email: string; ttlMinutes: number }): string {
+export function linkSentPage(o: {
+ brandName: string;
+ trustedSignInLabel?: string;
+ email: string;
+ ttlMinutes: number;
+}): string {
return page({
title: "Check your email",
brandName: o.brandName,
+ trustedSignInLabel: o.trustedSignInLabel,
icon: SENT_ICON,
heading: "Check your email",
msg: `If that address can sign in, a one-time link is on its way. Open it in this browser. It works once and expires in ${o.ttlMinutes} minutes.`,
@@ -146,10 +159,11 @@ export function linkSentPage(o: { brandName: string; email: string; ttlMinutes:
});
}
-export function confirmSignInPage(o: { brandName: string; action: string }): string {
+export function confirmSignInPage(o: { brandName: string; trustedSignInLabel?: string; action: string }): string {
return page({
title: "Finish signing in",
brandName: o.brandName,
+ trustedSignInLabel: o.trustedSignInLabel,
icon: LOCK_ICON,
heading: `Finish signing in to ${o.brandName}`,
msg: "Confirm below to complete sign-in. Your link is spent the moment you confirm, so do it in the browser you want to be signed in to.",
@@ -166,6 +180,7 @@ export function confirmSignInPage(o: { brandName: string; action: string }): str
export function problemPage(o: {
brandName: string;
+ trustedSignInLabel?: string;
heading: string;
msg: string;
detail?: string;
@@ -177,6 +192,7 @@ export function problemPage(o: {
return page({
title: "Sign-in problem",
brandName: o.brandName,
+ trustedSignInLabel: o.trustedSignInLabel,
icon: ALERT_ICON,
warn: true,
heading: o.heading,
diff --git a/plugins/auth/src/server.ts b/plugins/auth/src/server.ts
index b0c8c6cc5..6e18b0312 100644
--- a/plugins/auth/src/server.ts
+++ b/plugins/auth/src/server.ts
@@ -24,6 +24,7 @@ export interface AuthDeps {
sessions?: RememberedSessions;
mailer: Mailer | null;
brandName?: () => string;
+ trustedSignInLabel?: string;
emailAllowed?: (email: string) => Promise<boolean>;
now?: () => number;
onBackgroundTask?: (task: Promise<void>) => void;
@@ -138,7 +139,17 @@ export function createAuthHandler(deps: AuthDeps): (req: IncomingMessage, res: S
};
const problem = (res: ServerResponse, status: number, heading: string, msg: string, detail?: string): void =>
- sendHtml(res, status, problemPage({ brandName: brandName(), heading, msg, ...(detail ? { detail } : {}) }));
+ sendHtml(
+ res,
+ status,
+ problemPage({
+ brandName: brandName(),
+ trustedSignInLabel: deps.trustedSignInLabel,
+ heading,
+ msg,
+ ...(detail ? { detail } : {}),
+ }),
+ );
const emailUnavailable = (res: ServerResponse): void =>
problem(
@@ -162,6 +173,7 @@ export function createAuthHandler(deps: AuthDeps): (req: IncomingMessage, res: S
400,
problemPage({
brandName: brandName(),
+ trustedSignInLabel: deps.trustedSignInLabel,
heading: "This sign-in link no longer works",
msg: "Sign-in links work once and expire quickly. Request a fresh one and open it right away.",
...(signInUrl ? { retryUrl: signInUrl } : {}),
@@ -259,7 +271,12 @@ export function createAuthHandler(deps: AuthDeps): (req: IncomingMessage, res: S
return sendHtml(
res,
200,
- emailFormPage({ brandName: brandName(), action: formAction, requestToken: sealed.token }),
+ emailFormPage({
+ brandName: brandName(),
+ trustedSignInLabel: deps.trustedSignInLabel,
+ action: formAction,
+ requestToken: sealed.token,
+ }),
);
}
@@ -327,6 +344,7 @@ export function createAuthHandler(deps: AuthDeps): (req: IncomingMessage, res: S
400,
emailFormPage({
brandName: brandName(),
+ trustedSignInLabel: deps.trustedSignInLabel,
action: formAction,
requestToken: sealed.token,
problem: "That doesn't look like an email address.",
@@ -334,7 +352,16 @@ export function createAuthHandler(deps: AuthDeps): (req: IncomingMessage, res: S
);
}
const ip = clientIpOf(req);
- sendHtml(res, 200, linkSentPage({ brandName: brandName(), email, ttlMinutes: linkTtlMinutes }));
+ sendHtml(
+ res,
+ 200,
+ linkSentPage({
+ brandName: brandName(),
+ trustedSignInLabel: deps.trustedSignInLabel,
+ email,
+ ttlMinutes: linkTtlMinutes,
+ }),
+ );
background(() => sendLink(request, email, ip, mailer));
}
@@ -342,7 +369,11 @@ export function createAuthHandler(deps: AuthDeps): (req: IncomingMessage, res: S
return sendHtml(
res,
200,
- confirmSignInPage({ brandName: brandName(), action: `${cfg.publicPath}/verify` }),
+ confirmSignInPage({
+ brandName: brandName(),
+ trustedSignInLabel: deps.trustedSignInLabel,
+ action: `${cfg.publicPath}/verify`,
+ }),
CONFIRM_PAGE_CSP,
);
}
diff --git a/plugins/auth/test/flow.test.ts b/plugins/auth/test/flow.test.ts
index 33ace44c7..5160a7f3a 100644
--- a/plugins/auth/test/flow.test.ts
+++ b/plugins/auth/test/flow.test.ts
@@ -749,3 +749,34 @@ test("a remembered browser loses access when email eligibility is withdrawn", as
});
assert.equal(new URL(response.headers.get("location")!).searchParams.get("error"), "login_required");
});
+
+test("trusted sign-in is available throughout the email flow only when configured", async () => {
+ for (const trustedSignInLabel of [undefined, "Company SSO"]) {
+ const h = await startHarness({ trustedSignInLabel });
+ try {
+ const page = await fetch(`${h.base}/authorize?${authorizeQuery()}`);
+ const html = await page.text();
+ assert.equal(html.includes('href="/auth/trusted/login"'), Boolean(trustedSignInLabel));
+ if (trustedSignInLabel) assert.match(html, /Sign in with Company SSO/);
+ const request = hiddenRequestToken(html);
+ for (const email of ["invalid", "[email protected]"]) {
+ const response = await fetch(`${h.base}/authorize`, form({ request, email }));
+ assert.equal((await response.text()).includes('href="/auth/trusted/login"'), Boolean(trustedSignInLabel));
+ }
+ } finally {
+ await h.settle();
+ await h.close();
+ }
+ }
+});
+
+test("trusted sign-in remains available when email is unavailable", async () => {
+ const h = await startHarness({ trustedSignInLabel: "Company SSO", env: { RESEND_API_KEY: undefined } });
+ try {
+ const response = await fetch(`${h.base}/authorize?${authorizeQuery()}`);
+ assert.equal(response.status, 503);
+ assert.match(await response.text(), /href="\/auth\/trusted\/login"/);
+ } finally {
+ await h.close();
+ }
+});
diff --git a/plugins/auth/test/helpers.ts b/plugins/auth/test/helpers.ts
index 28fc1a2b7..9b9af431d 100644
--- a/plugins/auth/test/helpers.ts
+++ b/plugins/auth/test/helpers.ts
@@ -98,6 +98,7 @@ export async function startHarness(
env?: Record<string, string | undefined>;
claims?: ClaimStore & { calls: string[][] };
brandName?: () => string;
+ trustedSignInLabel?: string;
emailAllowed?: (email: string) => Promise<boolean>;
sessions?: RememberedSessions;
} = {},
@@ -130,6 +131,7 @@ export async function startHarness(
const pending: Array<Promise<void>> = [];
const handle = createAuthHandler({
cfg,
+ trustedSignInLabel: options.trustedSignInLabel,
signingKey: await loadSigningKey(cfg.signingJwk!),
signer: new TokenSigner(cfg.tokenSecret, cfg.issuer),
claims,
diff --git a/plugins/portal/README.md b/plugins/portal/README.md
index 7e0f998eb..b10b9236b 100644
--- a/plugins/portal/README.md
+++ b/plugins/portal/README.md
@@ -71,6 +71,17 @@ grants but does not remove existing ones. Company login and Slack integration re
existing configuration. Deployment CLI secret wiring, account linking, and live
qualification are pending; this is not a released deployment feature.
+When `PORTAL_TRUSTED_OIDC_LABEL` is explicitly set, successful trusted sign-in
+makes the portal remember the configured issuer in a
+host-only, HttpOnly browser preference for one year. Ordinary
+`/auth/login` requests then return to the trusted route, including after logout
+or session expiry. Session renewal and logout also remember existing trusted
+sessions. A successful primary or operator sign-in clears the preference. The
+preference only selects a provider; it grants no identity or administrator access.
+A new browser or cleared cookies still uses the primary provider by default.
+Use `/auth/login?provider=primary` to explicitly select the primary provider; the
+trusted sign-in error page offers this alternative.
+
## Operator admin login without email
Run `qm admin-login` with the deployment's configuration and secrets to generate
@@ -258,3 +269,11 @@ npm test
See **`deploy/README.md` → Portal** for the public bring-up (IPs + cert, DNS, the Slack OIDC
app, and secrets) and `deploy/portal/fly.toml`.
+
+With embedded auth, trusted OIDC, and `PORTAL_TRUSTED_OIDC_LABEL` explicitly set,
+all email sign-in pages offer a link
+to the trusted provider, including the email-unavailable and link-sent pages.
+The label is the provider display name. Without it, the email page and primary
+login routing retain their existing behavior. Switching keeps the destination
+from the signed email login transaction.
+The link is available without a remembered browser preference.
diff --git a/plugins/portal/src/index.ts b/plugins/portal/src/index.ts
index ff441b95d..9b062744d 100644
--- a/plugins/portal/src/index.ts
+++ b/plugins/portal/src/index.ts
@@ -1,4 +1,5 @@
import { provisionTrustedAdmin } from "./trusted-admin.ts";
+import { createHash } from "node:crypto";
import { createServer, type IncomingMessage, type ServerResponse } from "node:http";
import { pathToFileURL } from "node:url";
import { ADMIN_LOGIN_SCRIPT, ADMIN_LOGIN_SCRIPT_HASH, openAdminLogin } from "./admin-login.ts";
@@ -207,6 +208,7 @@ const sessionKey = deriveKey(SESSION_SECRET ?? DEV_SECRET, "portal.session.v1");
const tmpKey = deriveKey(SESSION_SECRET ?? DEV_SECRET, "portal.tmp.v1");
const impersonateKey = deriveKey(SESSION_SECRET ?? DEV_SECRET, "portal.impersonate.v1");
const trustedOidc = trustedEntryConfig(process.env, PUBLIC_URL);
+const trustedSignInLabel = trustedOidc ? process.env.PORTAL_TRUSTED_OIDC_LABEL?.trim() || undefined : undefined;
const trustedAdminEnabled = process.env.PORTAL_TRUSTED_OIDC_ADMIN === "1";
if (
trustedAdminEnabled &&
@@ -522,7 +524,7 @@ export function signInErrorHtml(
warn: true,
extra: `<p class="reason"><strong>Details</strong>${escapeHtml(detail)}</p>`,
actions: `<a class="btn primary" href="${retryPath}">Try signing in again</a>
- <a class="btn ghost" href="/">Back to start</a>`,
+ ${retryPath === "/auth/trusted/login" && trustedSignInLabel ? '<a class="btn ghost" href="/auth/login?provider=primary">Use another sign-in method</a>' : '<a class="btn ghost" href="/">Back to start</a>'}`,
help: "Still stuck? Check that your account has access, then contact your admin.",
});
}
@@ -786,14 +788,31 @@ function isDeploymentLayerPassthrough(method: string, pathname: string): boolean
return (method === "GET" || method === "PUT") && pathname === "/v1/deployment-layer";
}
-function sessionCookieSet(value: string): string[] {
+function loginProviderCookie(sub: string): string[] {
+ if (!trustedOidc || !trustedSignInLabel) return [];
+ const issuerHash = createHash("sha256").update(trustedOidc.issuer).digest("hex");
+ return [
+ sub.startsWith(`oidc:${issuerHash}:`)
+ ? setCookie("portal_login_provider", issuerHash, {
+ path: "/",
+ maxAge: 365 * 24 * 60 * 60,
+ secure: SECURE_COOKIES,
+ })
+ : clearCookie("portal_login_provider", "/", SECURE_COOKIES),
+ ];
+}
+
+function sessionCookieSet(value: string, sub: string): string[] {
const set = setCookie("portal_session", value, {
path: "/",
maxAge: SESSION_TTL_S,
secure: SECURE_COOKIES,
...(COOKIE_DOMAIN ? { domain: COOKIE_DOMAIN } : {}),
});
- return COOKIE_DOMAIN ? [set, clearCookie("portal_session", "/", SECURE_COOKIES)] : [set];
+ return [
+ ...(COOKIE_DOMAIN ? [set, clearCookie("portal_session", "/", SECURE_COOKIES)] : [set]),
+ ...loginProviderCookie(sub),
+ ];
}
function setSession(res: ServerResponse, headers: string[]): void {
@@ -865,7 +884,7 @@ async function mintPlaygroundSession(req: IncomingMessage, res: ServerResponse):
iat: now,
exp: now + SESSION_TTL_S,
};
- setSession(res, sessionCookieSet(seal(session, sessionKey)));
+ setSession(res, sessionCookieSet(seal(session, sessionKey), session.sub));
return session;
}
@@ -887,7 +906,7 @@ function renewSessionCookie(req: IncomingMessage, res: ServerResponse): void {
iat: now,
exp: Math.min(now + SESSION_TTL_S, authenticatedAt + SESSION_MAX_TTL_S),
};
- setSession(res, sessionCookieSet(seal(renewed, sessionKey)));
+ setSession(res, sessionCookieSet(seal(renewed, sessionKey), renewed.sub));
}
const server = createServer((req, res) => {
@@ -955,7 +974,9 @@ async function handle(req: IncomingMessage, res: ServerResponse): Promise<void>
return json(res, 503, { error: "revocation_failed" });
}
}
+ const signedOutSession = currentSession(req);
setSession(res, [
+ ...(signedOutSession ? loginProviderCookie(signedOutSession.sub) : []),
clearCookie("portal_session", "/", SECURE_COOKIES, COOKIE_DOMAIN),
...(COOKIE_DOMAIN ? [clearCookie("portal_session", "/", SECURE_COOKIES)] : []),
clearCookie("portal_oidc_tmp", "/auth", SECURE_COOKIES),
@@ -1291,7 +1312,11 @@ async function trustedAuth(req: IncomingMessage, res: ServerResponse, url: URL):
const cookieName = "portal_trusted_tmp";
const path = "/auth/trusted";
if (url.pathname === `${path}/login`) {
- const login = trustedEntry.start(sanitizeReturnTo(url.searchParams.get("returnTo"), PUBLIC_URL, APPS_DOMAIN));
+ const returnTo =
+ url.searchParams.get("returnTo") ??
+ openTmp(readCookie(req.headers.cookie, "portal_oidc_tmp"), tmpKey, Date.now())?.returnTo ??
+ null;
+ const login = trustedEntry.start(sanitizeReturnTo(returnTo, PUBLIC_URL, APPS_DOMAIN));
setSession(res, [setCookie(cookieName, login.cookie, { path, maxAge: login.ttl, secure: SECURE_COOKIES })]);
res.writeHead(302, { location: login.location, "cache-control": "no-store" });
return void res.end();
@@ -1340,7 +1365,7 @@ function setAuthenticatedSession(res: ServerResponse, sub: string, name = ""): v
...(name ? { name } : {}),
};
setSession(res, [
- ...sessionCookieSet(seal(session, sessionKey)),
+ ...sessionCookieSet(seal(session, sessionKey), session.sub),
clearCookie("portal_trusted_tmp", "/auth/trusted", SECURE_COOKIES),
clearCookie("portal_oidc_tmp", "/auth", SECURE_COOKIES),
clearCookie("portal_impersonate", "/", SECURE_COOKIES),
@@ -1348,11 +1373,25 @@ function setAuthenticatedSession(res: ServerResponse, sub: string, name = ""): v
}
function authLogin(req: IncomingMessage, res: ServerResponse, url: URL): void {
+ if (
+ trustedOidc &&
+ trustedSignInLabel &&
+ url.searchParams.get("provider") !== "primary" &&
+ readCookie(req.headers.cookie, "portal_login_provider") ===
+ createHash("sha256").update(trustedOidc.issuer).digest("hex")
+ ) {
+ const returnTo = sanitizeReturnTo(url.searchParams.get("returnTo"), PUBLIC_URL, APPS_DOMAIN);
+ res.writeHead(302, {
+ location: `/auth/trusted/login?returnTo=${encodeURIComponent(returnTo)}`,
+ "cache-control": "no-store",
+ });
+ return void res.end();
+ }
const returnTo = sanitizeReturnTo(url.searchParams.get("returnTo"), PUBLIC_URL, APPS_DOMAIN);
const localSession = localDevSession(req, Date.now(), true);
if (localSession) {
setSession(res, [
- ...sessionCookieSet(seal(localSession, sessionKey)),
+ ...sessionCookieSet(seal(localSession, sessionKey), localSession.sub),
clearCookie("portal_oidc_tmp", "/auth", SECURE_COOKIES),
...(AUTH_BROKER_UPSTREAM ? [clearCookie("qm_idp_session", AUTH_BROKER_PREFIX, true)] : []),
clearCookie(LOCAL_LOGOUT_COOKIE, "/", SECURE_COOKIES),
@@ -1576,7 +1615,11 @@ export async function startServer(): Promise<void> {
throw new Error("Embedded auth requires the loopback broker upstream");
}
const auth = await import("../../auth/src/index.ts");
- const broker = await auth.startServer({ port: 8099, host: "127.0.0.1" });
+ const broker = await auth.startServer({
+ port: 8099,
+ host: "127.0.0.1",
+ ...(trustedSignInLabel ? { trustedSignInLabel } : {}),
+ });
server.once("close", () => broker.close());
server.once("error", () => broker.close());
}
diff --git a/plugins/portal/test/trusted-entry-default-routes.test.ts b/plugins/portal/test/trusted-entry-default-routes.test.ts
new file mode 100644
index 000000000..0124ddeb0
--- /dev/null
+++ b/plugins/portal/test/trusted-entry-default-routes.test.ts
@@ -0,0 +1,2 @@
+process.env.TRUSTED_LOGIN_LABEL_TEST = "0";
+await import("./trusted-entry-routes.test.ts");
diff --git a/plugins/portal/test/trusted-entry-routes.test.ts b/plugins/portal/test/trusted-entry-routes.test.ts
index b57899449..aec7c7333 100644
--- a/plugins/portal/test/trusted-entry-routes.test.ts
+++ b/plugins/portal/test/trusted-entry-routes.test.ts
@@ -6,6 +6,7 @@ import { createHash } from "node:crypto";
import { exportJWK, generateKeyPair, SignJWT, compactVerify } from "jose";
import { deriveKey, openSession } from "../src/session.ts";
+const preferenceEnabled = process.env.TRUSTED_LOGIN_LABEL_TEST !== "0";
const adminEnabled = process.env.TRUSTED_ADMIN_ROUTE_TEST === "1";
const claims = new Set<string>();
let claimAvailable = true;
@@ -88,6 +89,7 @@ Object.assign(process.env, {
CORE_SIGNING_SECRET: "test-core-secret",
PORTAL_IDENTITY_SECRET: identitySecret,
PORTAL_TRUSTED_OIDC_ADMIN: adminEnabled ? "1" : "0",
+ PORTAL_TRUSTED_OIDC_LABEL: preferenceEnabled ? "Company SSO" : "",
WEB_UI_UPSTREAM: issuer,
ADMIN_UPSTREAM: issuer,
OIDC_AUTH_ENDPOINT: "https://primary.example.test/authorize",
@@ -160,7 +162,9 @@ test("durable claim service failure cannot issue a session", async () => {
try {
const response = await fetch(login.callback, { redirect: "manual", headers: { cookie: login.cookie } });
assert.equal(response.status, 400);
- assert.match(await response.text(), /href="\/auth\/trusted\/login"/);
+ const html = await response.text();
+ assert.match(html, /href="\/auth\/trusted\/login"/);
+ assert.equal(html.includes('href="/auth/login?provider=primary"'), preferenceEnabled);
assert.ok(!response.headers.getSetCookie().some((cookie) => cookie.startsWith("portal_session=")));
} finally {
claimAvailable = true;
@@ -178,3 +182,79 @@ test("admin provisioning failure cannot issue a session", { skip: !adminEnabled
adminAvailable = true;
}
});
+
+test(
+ "trusted sign-in preference survives logout and preserves the requested destination",
+ { skip: !preferenceEnabled },
+ async () => {
+ const login = await start();
+ const callback = await fetch(login.callback, { redirect: "manual", headers: { cookie: login.cookie } });
+ const cookies = callback.headers.getSetCookie();
+ const preference = cookies.find((cookie) => cookie.startsWith("portal_login_provider="))!;
+ assert.ok(preference.includes("HttpOnly"));
+ assert.ok(preference.includes("SameSite=Lax"));
+ const session = cookies.find((cookie) => cookie.startsWith("portal_session="))!.split(";")[0]!;
+ const logout = await fetch(`${base}/auth/logout`, {
+ method: "POST",
+ headers: { origin: process.env.PORTAL_PUBLIC_URL!, cookie: session },
+ });
+ assert.equal(logout.status, 200);
+ assert.ok(logout.headers.getSetCookie().includes(preference));
+ const response = await fetch(`${base}/auth/login?returnTo=%2Fadmin%2F`, {
+ redirect: "manual",
+ headers: { cookie: preference.split(";")[0]! },
+ });
+ assert.equal(response.headers.get("location"), "/auth/trusted/login?returnTo=%2Fadmin%2F");
+ assert.ok(!response.headers.getSetCookie().some((cookie) => cookie.startsWith("portal_session=")));
+ const external = await fetch(`${base}/auth/login?returnTo=https://evil.example`, {
+ redirect: "manual",
+ headers: { cookie: preference.split(";")[0]! },
+ });
+ assert.equal(external.headers.get("location"), "/auth/trusted/login?returnTo=%2F");
+ const primary = await fetch(`${base}/auth/login?provider=primary`, {
+ redirect: "manual",
+ headers: { cookie: preference.split(";")[0]! },
+ });
+ assert.equal(new URL(primary.headers.get("location")!).origin, "https://primary.example.test");
+ },
+);
+
+test("unknown provider preferences retain primary sign-in", async () => {
+ const response = await fetch(`${base}/auth/login`, {
+ redirect: "manual",
+ headers: { cookie: "portal_login_provider=unknown" },
+ });
+ assert.equal(new URL(response.headers.get("location")!).origin, "https://primary.example.test");
+});
+
+test("switching from email retains its signed return destination", async () => {
+ const email = await fetch(`${base}/auth/login?provider=primary&returnTo=%2Fadmin%2F`, { redirect: "manual" });
+ const cookie = email.headers.getSetCookie()[0]!.split(";")[0]!;
+ const trusted = await fetch(`${base}/auth/trusted/login`, { redirect: "manual", headers: { cookie } });
+ const url = new URL(trusted.headers.get("location")!);
+ const code = `switch-${Math.random()}`;
+ codes.set(code, { nonce: url.searchParams.get("nonce")!, challenge: url.searchParams.get("code_challenge")! });
+ const response = await fetch(`${base}/auth/trusted/callback?code=${code}&state=${url.searchParams.get("state")}`, {
+ redirect: "manual",
+ headers: { cookie: trusted.headers.getSetCookie()[0]!.split(";")[0]! },
+ });
+ assert.equal(response.status, 302);
+ assert.equal(response.headers.get("location"), "/admin/");
+});
+
+test(
+ "without an opt-in label trusted sessions do not change primary login routing",
+ { skip: preferenceEnabled },
+ async () => {
+ const login = await start();
+ const callback = await fetch(login.callback, { redirect: "manual", headers: { cookie: login.cookie } });
+ assert.equal(callback.status, 302);
+ assert.ok(!callback.headers.getSetCookie().some((cookie) => cookie.startsWith("portal_login_provider=")));
+ const preference = createHash("sha256").update(issuer).digest("hex");
+ const primary = await fetch(`${base}/auth/login`, {
+ redirect: "manual",
+ headers: { cookie: `portal_login_provider=${preference}` },
+ });
+ assert.equal(new URL(primary.headers.get("location")!).origin, "https://primary.example.test");
+ },
+);