Accept a verification or recovery code pasted with whitespace around it
CI / full-gate (push) Failing after 16s
CI / full-gate (push) Failing after 16s
This commit is contained in:
@@ -100,9 +100,8 @@ test("collects oidc nodes as SSO providers (text logo = initial), keeping csrf a
|
||||
assert.deepEqual(view.buttons, [{ label: "Sign in", name: "method", value: "password" }]);
|
||||
});
|
||||
|
||||
test("the code field guards a pasted space: one-time-code autofill + numeric inputmode + digits-only pattern", () => {
|
||||
// Verification/recovery enter a numeric OTP. Kratos doesn't trim, so a stray pasted space makes it
|
||||
// reject the code as "invalid"; a digits-only pattern blocks that in the browser before submit.
|
||||
test("the code field takes a pasted code: one-time-code autofill + numeric inputmode + digits, whitespace around them allowed", () => {
|
||||
// The host trims the code before Kratos sees it (routes.ts), so only a stray non-digit is refused.
|
||||
const view = buildFlowView(
|
||||
flow([
|
||||
node({ name: "csrf_token", type: "hidden", value: "tok" }),
|
||||
@@ -113,18 +112,26 @@ test("the code field guards a pasted space: one-time-code autofill + numeric inp
|
||||
);
|
||||
assert.deepEqual(view.fields.find((f) => f.name === "code"), {
|
||||
autocomplete: "one-time-code", // Kratos sends none for the OTP node — enable OS/email autofill
|
||||
hint: "Digits only — no spaces.", // the pattern refusal alone reads as a bare "match the requested format"
|
||||
hint: "Digits only.", // the pattern refusal alone reads as a bare "match the requested format"
|
||||
icon: "i-shield",
|
||||
id: "field-code",
|
||||
inputmode: "numeric",
|
||||
label: "Verification code",
|
||||
name: "code",
|
||||
pattern: "[0-9]*",
|
||||
pattern: "\\s*[0-9]*\\s*",
|
||||
required: true,
|
||||
type: "text",
|
||||
});
|
||||
});
|
||||
|
||||
test("the code flows post to the host, which trims the code; every other flow posts to Kratos", () => {
|
||||
for (const type of ["recovery", "verification"] as const) assert.equal(buildFlowView(flow([]), type).action, `/${type}?flow=f1`);
|
||||
for (const type of ["login", "registration", "settings"] as const) {
|
||||
assert.equal(buildFlowView(flow([]), type).action, "http://127.0.0.1:4433/self-service/login?flow=f1");
|
||||
}
|
||||
assert.equal(buildFlowView({ ...flow([]), id: "a&b" }, "recovery").action, "/recovery?flow=a%26b");
|
||||
});
|
||||
|
||||
test("chrome varies per flow type: registration alt, recovery back link", () => {
|
||||
const reg = buildFlowView(flow([]), "registration");
|
||||
assert.equal(reg.title, "Create account");
|
||||
|
||||
+11
-8
@@ -1,8 +1,8 @@
|
||||
// Kratos flow → themed view model. Pure: turns a fetched self-service Flow
|
||||
// (src/auth/kratos-public.ts) into the data views/auth.ejs renders — hidden inputs (incl. the
|
||||
// CSRF token), themed fields, submit buttons, tone-mapped messages, and one SSO button per
|
||||
// configured `oidc` provider. The form posts straight back to `flow.ui.action`, so Kratos
|
||||
// owns its CSRF; we only render and map errors. No providers configured ⇒ no SSO buttons.
|
||||
// configured `oidc` provider. The form posts to `flow.ui.action`, except a CODE_FLOWS form, which
|
||||
// posts to the host first; Kratos owns the CSRF of both. No providers configured ⇒ no SSO buttons.
|
||||
|
||||
import { ENGLISH } from "../i18n/english.ts";
|
||||
import type { Translate } from "../i18n/translate.ts";
|
||||
@@ -17,7 +17,7 @@ export interface FlowField {
|
||||
inputmode?: string; // virtual-keyboard hint (e.g. "numeric" for the OTP code)
|
||||
label: string;
|
||||
name: string;
|
||||
pattern?: string; // client-side validity regex; blocks a pasted space before it reaches Kratos
|
||||
pattern?: string; // client-side validity regex
|
||||
required?: boolean;
|
||||
type: string;
|
||||
value?: string;
|
||||
@@ -69,6 +69,9 @@ export const AUTH_FLOWS: Record<string, FlowType> = {
|
||||
"/verification": "verification",
|
||||
};
|
||||
|
||||
// The flows that take an emailed one-time code, whose form posts to the host to have it trimmed.
|
||||
export const CODE_FLOWS: ReadonlySet<FlowType> = new Set(["recovery", "verification"]);
|
||||
|
||||
// Where each flow's card links; its words come from the catalog under `auth.<flow>.*`.
|
||||
const LINKS: Record<FlowType, { alt?: string; back?: boolean }> = {
|
||||
login: { alt: "/registration" },
|
||||
@@ -123,9 +126,9 @@ const ssoLogo = (value: string): string => (value.charAt(0) || "?").toUpperCase(
|
||||
|
||||
function toField(node: UiNode, name: string, type: string, t: Translate): FlowField {
|
||||
const value = str(node.attributes["value"]);
|
||||
// The recovery/verification one-time code: numeric, and Kratos doesn't trim it, so a stray pasted
|
||||
// space makes it reject the code as "invalid". A digits-only pattern + numeric keypad block that in
|
||||
// the browser; one-time-code enables OS/email autofill (Kratos sends no autocomplete for the node).
|
||||
// The recovery/verification one-time code: numeric, so a numeric keypad and a digits pattern, which
|
||||
// allows the whitespace a paste brings since the host trims it (routes.ts → codeFlowSubmit).
|
||||
// one-time-code enables OS/email autofill (Kratos sends no autocomplete for the node).
|
||||
const isCode = name === "code";
|
||||
const autocomplete = str(node.attributes["autocomplete"]) ?? (isCode ? "one-time-code" : undefined);
|
||||
const icon = iconFor(name, type);
|
||||
@@ -140,7 +143,7 @@ function toField(node: UiNode, name: string, type: string, t: Translate): FlowFi
|
||||
...(autocomplete ? { autocomplete } : {}),
|
||||
...(errorMsg ? { error: { text: kratosText(t, errorMsg.text, idKey(errorMsg.id)) } } : {}),
|
||||
...(icon ? { icon } : {}),
|
||||
...(isCode ? { hint: t("auth.field.code.hint"), inputmode: "numeric", pattern: "[0-9]*" } : {}),
|
||||
...(isCode ? { hint: t("auth.field.code.hint"), inputmode: "numeric", pattern: "\\s*[0-9]*\\s*" } : {}),
|
||||
...(node.attributes["required"] === true ? { required: true } : {}),
|
||||
...(value ? { value } : {}),
|
||||
};
|
||||
@@ -174,7 +177,7 @@ export function buildFlowView(flow: Flow, type: FlowType, t: Translate = ENGLISH
|
||||
}
|
||||
|
||||
return {
|
||||
action: flow.ui.action,
|
||||
action: CODE_FLOWS.has(type) ? `/${type}?flow=${encodeURIComponent(flow.id)}` : flow.ui.action,
|
||||
buttons,
|
||||
fields,
|
||||
hidden,
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
// Kratos public-API client: typed fetch wrappers over Ory Kratos' public endpoints.
|
||||
// Guards the request contracts (URLs, JSON-accept, cookie relay) and the result mapping
|
||||
// (200/401/4xx, validation-flow vs success, tokenized JWT). Live wiring is verified by the
|
||||
// (200/401/4xx, a submit's redirect, tokenized JWT). Live wiring is verified by the
|
||||
// flow pages; these catch contract drift with a mock fetch.
|
||||
import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
@@ -57,35 +57,27 @@ test("getFlow throws a KratosError carrying the status when the flow is gone (41
|
||||
);
|
||||
});
|
||||
|
||||
test("submitFlow POSTs urlencoded to the action and reports success + relays Set-Cookie", async () => {
|
||||
const { calls, fetchImpl } = recorder(() => res(200, { session: { active: true } }, ["plainpages_session=s; Path=/"]));
|
||||
test("submitFlow POSTs the form to the flow on Kratos' own base URL, as a browser would, and relays the redirect + Set-Cookie", async () => {
|
||||
const { calls, fetchImpl } = recorder(() => new Response(null, {
|
||||
headers: new Headers([["location", "http://app/settings?flow=s1"], ["set-cookie", "plainpages_session=s; Path=/"]]),
|
||||
status: 303,
|
||||
}));
|
||||
const out = await createKratosPublic({ baseUrl: BASE, fetchImpl })
|
||||
.submitFlow(`${BASE}/self-service/login?flow=f`, { body: "identifier=a&password=b", cookie: "csrf_token=abc" });
|
||||
assert.equal(out.ok, true);
|
||||
assert.equal(out.status, 200);
|
||||
assert.deepEqual(out.setCookie, ["plainpages_session=s; Path=/"]);
|
||||
.submitFlow("recovery", "f 1", { body: "code=123456&method=code", cookie: "csrf_token=abc" });
|
||||
assert.deepEqual(out, { location: "http://app/settings?flow=s1", setCookie: ["plainpages_session=s; Path=/"], status: 303 });
|
||||
assert.equal(calls[0]!.url, `${BASE}/self-service/recovery?flow=f+1`);
|
||||
assert.equal(calls[0]!.method, "POST");
|
||||
// Not JSON: Kratos then answers with the same 303s a browser posting to it directly would get.
|
||||
assert.equal(calls[0]!.headers.get("accept"), "text/html");
|
||||
assert.equal(calls[0]!.headers.get("content-type"), "application/x-www-form-urlencoded");
|
||||
assert.equal(calls[0]!.body, "identifier=a&password=b");
|
||||
assert.equal(calls[0]!.headers.get("cookie"), "csrf_token=abc");
|
||||
assert.equal(calls[0]!.body, "code=123456&method=code");
|
||||
});
|
||||
|
||||
test("submitFlow returns the re-rendered flow (no throw) on a 400 validation error", async () => {
|
||||
const flow = { id: "f", ui: { action: "x", messages: [{ id: 4000006, text: "invalid credentials", type: "error" }], method: "POST", nodes: [] } };
|
||||
const { fetchImpl } = recorder(() => res(400, flow));
|
||||
const out = await createKratosPublic({ baseUrl: BASE, fetchImpl }).submitFlow(`${BASE}/x`, { body: "x=1" });
|
||||
assert.equal(out.ok, false);
|
||||
assert.equal(out.status, 400);
|
||||
assert.deepEqual(out.body, flow);
|
||||
});
|
||||
|
||||
test("submitFlow surfaces the redirect target — Location header or a 422 redirect_browser_to body", async () => {
|
||||
const k = (handler: () => Response) => createKratosPublic({ baseUrl: BASE, fetchImpl: recorder(handler).fetchImpl });
|
||||
const viaHeader = await k(() => new Response(null, { headers: new Headers({ location: "http://app/" }), status: 303 }))
|
||||
.submitFlow(`${BASE}/x`, { body: "x=1" });
|
||||
assert.equal(viaHeader.location, "http://app/");
|
||||
const viaBody = await k(() => res(422, { redirect_browser_to: "http://app/login?flow=next" }))
|
||||
.submitFlow(`${BASE}/x`, { body: "x=1" });
|
||||
assert.equal(viaBody.location, "http://app/login?flow=next");
|
||||
test("submitFlow reports a 4xx without a redirect as a null location, and throws on a Kratos 5xx", async () => {
|
||||
const k = (status: number) => createKratosPublic({ baseUrl: BASE, fetchImpl: recorder(() => res(status, { error: "x" })).fetchImpl });
|
||||
assert.deepEqual(await k(400).submitFlow("verification", "f", { body: "x=1" }), { location: null, setCookie: [], status: 400 });
|
||||
await assert.rejects(k(502).submitFlow("verification", "f", { body: "x=1" }), (e: unknown) => e instanceof KratosError && e.status === 502);
|
||||
});
|
||||
|
||||
test("whoami returns the session on 200 (cookie forwarded) and null on 401", async () => {
|
||||
|
||||
+13
-27
@@ -51,9 +51,7 @@ export interface LogoutFlow {
|
||||
}
|
||||
|
||||
export interface FlowSubmission {
|
||||
body: unknown; // parsed JSON: the re-rendered flow on 400, the success payload on 200
|
||||
location: string | null; // redirect target (Location header, or a 422 redirect_browser_to)
|
||||
ok: boolean; // status === 200
|
||||
location: string | null; // where Kratos sends the browser next
|
||||
setCookie: string[];
|
||||
status: number;
|
||||
}
|
||||
@@ -74,23 +72,10 @@ export interface KratosPublic {
|
||||
createLogoutFlow(opts?: { cookie?: string }): Promise<LogoutFlow | null>; // null ⇒ no active session (401)
|
||||
getFlow(type: FlowType, id: string, opts?: { cookie?: string }): Promise<Flow>;
|
||||
initBrowserFlow(type: FlowType, opts?: { cookie?: string; returnTo?: string }): Promise<FlowInit>;
|
||||
submitFlow(action: string, opts: { body: string; contentType?: string; cookie?: string }): Promise<FlowSubmission>;
|
||||
submitFlow(type: FlowType, flowId: string, opts: { body: string; cookie?: string }): Promise<FlowSubmission>;
|
||||
whoami(opts?: { cookie?: string; tokenizeAs?: string }): Promise<Session | null>;
|
||||
}
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === "object" && value !== null && !Array.isArray(value);
|
||||
}
|
||||
|
||||
function parseBody(text: string): unknown {
|
||||
if (!text) return null;
|
||||
try {
|
||||
return JSON.parse(text);
|
||||
} catch {
|
||||
return text;
|
||||
}
|
||||
}
|
||||
|
||||
export function createKratosPublic(config: { baseUrl: string; fetchImpl?: typeof fetch }): KratosPublic {
|
||||
const base = config.baseUrl.replace(/\/+$/, "");
|
||||
const http = config.fetchImpl ?? fetch;
|
||||
@@ -129,16 +114,17 @@ export function createKratosPublic(config: { baseUrl: string; fetchImpl?: typeof
|
||||
return (await res.json()) as Flow;
|
||||
},
|
||||
|
||||
async submitFlow(action, opts) {
|
||||
const h = headers(opts.cookie);
|
||||
h["content-type"] = opts.contentType ?? "application/x-www-form-urlencoded";
|
||||
// Manual redirect so we can read a 303 Location instead of following it server-side.
|
||||
const res = await http(action, { body: opts.body, headers: h, method: "POST", redirect: "manual" });
|
||||
const body = parseBody(await res.text());
|
||||
const location =
|
||||
res.headers.get("location") ??
|
||||
(isRecord(body) && typeof body["redirect_browser_to"] === "string" ? body["redirect_browser_to"] : null);
|
||||
return { body, location, ok: res.status === 200, setCookie: res.headers.getSetCookie(), status: res.status };
|
||||
async submitFlow(type, flowId, opts) {
|
||||
const url = new URL(`${base}/self-service/${type}`);
|
||||
url.searchParams.set("flow", flowId);
|
||||
// Asked for HTML, Kratos answers with the redirects a browser posting to it directly gets, so
|
||||
// every success/error/expiry branch stays Kratos'. Its nosurf demands a Referer, which this
|
||||
// POST lacks, only on an https request: valid while KRATOS_PUBLIC_URL is in-cluster http.
|
||||
const h = { ...headers(opts.cookie), accept: "text/html", "content-type": "application/x-www-form-urlencoded" };
|
||||
const res = await http(url, { body: opts.body, headers: h, method: "POST", redirect: "manual" });
|
||||
if (res.status >= 500) throw new KratosError(`Kratos submit ${type} flow failed (${res.status})`, res.status, await res.text());
|
||||
await res.body?.cancel();
|
||||
return { location: res.headers.get("location"), setCookie: res.headers.getSetCookie(), status: res.status };
|
||||
},
|
||||
|
||||
async whoami(opts = {}) {
|
||||
|
||||
+27
-3
@@ -1,5 +1,5 @@
|
||||
// The built-in auth/OAuth2 endpoints as named handlers on the host's internal route table
|
||||
// (src/http/builtin-routes.ts): the themed Kratos self-service pages, the Hydra OAuth2
|
||||
// (src/http/builtin-routes.ts): the themed Kratos self-service pages and their code submits, the Hydra OAuth2
|
||||
// login/consent/logout challenges, login completion, the first-party logout, and Kratos'
|
||||
// flow-error sink. buildAuthRoutes registers only what the wired clients support — a missing
|
||||
// client means the path simply doesn't exist (404). `view` results render the core views.
|
||||
@@ -8,11 +8,11 @@ import type { BuiltinRoute, RequestCsrf } from "../http/builtin-routes.ts";
|
||||
import type { RequestContext } from "../http/context.ts";
|
||||
import { CSRF_FIELD } from "./csrf.ts";
|
||||
import { chosenLocale } from "../i18n/locale.ts";
|
||||
import { AUTH_FLOWS, buildFlowView } from "./flow-view.ts";
|
||||
import { AUTH_FLOWS, buildFlowView, CODE_FLOWS } from "./flow-view.ts";
|
||||
import { HydraError, type HydraAdmin } from "./hydra-admin.ts";
|
||||
import type { KetoClient } from "./keto-client.ts";
|
||||
import type { KratosAdmin } from "./kratos-admin.ts";
|
||||
import { type Flow, type FlowType, KratosError, type KratosPublic } from "./kratos-public.ts";
|
||||
import { type Flow, type FlowSubmission, type FlowType, KratosError, type KratosPublic } from "./kratos-public.ts";
|
||||
import { clearSessionCookie, completeLogin, sessionCookie } from "./login.ts";
|
||||
import type { MenuConfig } from "../ui/menu-config.ts";
|
||||
import { acceptConsent, rejectConsent, resolveConsentChallenge } from "./oauth-consent.ts";
|
||||
@@ -114,6 +114,29 @@ function flowPage(kratos: KratosPublic, flowType: FlowType, secureCookies: boole
|
||||
};
|
||||
}
|
||||
|
||||
// A code flow's POST (flow-view.ts → CODE_FLOWS): trim the pasted one-time code, which Kratos would
|
||||
// refuse with its surrounding whitespace, and relay the rest to Kratos and its redirect back. Kratos'
|
||||
// own csrf_token field guards the POST, so the host checks no token of its own.
|
||||
function codeFlowSubmit(kratos: KratosPublic, flowType: FlowType): BuiltinRoute["handler"] {
|
||||
return async (ctx: RequestContext): Promise<RouteResult> => {
|
||||
const pathname = ctx.url.pathname;
|
||||
const flowId = ctx.url.searchParams.get("flow");
|
||||
if (!flowId) return { redirect: pathname };
|
||||
const form = await readFormBody(ctx.req);
|
||||
const code = form.get("code");
|
||||
if (code !== null) form.set("code", code.trim());
|
||||
const cookie = ctx.req.headers.cookie;
|
||||
let submitted: FlowSubmission;
|
||||
try {
|
||||
submitted = await kratos.submitFlow(flowType, flowId, { body: form.toString(), ...(cookie ? { cookie } : {}) });
|
||||
} catch (err) {
|
||||
return flowFailure(err, ctx, flowType);
|
||||
}
|
||||
if (submitted.setCookie.length) ctx.res.appendHeader("set-cookie", submitted.setCookie);
|
||||
return { redirect: submitted.location ?? `${pathname}?flow=${encodeURIComponent(flowId)}` };
|
||||
};
|
||||
}
|
||||
|
||||
// OAuth2 login challenge: Hydra hands the browser here when another app logs in *through* us.
|
||||
// Resolve it via the Kratos session and accept; an unauthenticated user bounces to our themed
|
||||
// login and returns here once signed in. Provider-only.
|
||||
@@ -250,6 +273,7 @@ export function buildAuthRoutes({ hydra, keto, kratos, kratosAdmin, menu, secure
|
||||
if (kratos) {
|
||||
for (const [path, flowType] of Object.entries(AUTH_FLOWS)) {
|
||||
routes.push({ handler: flowPage(kratos, flowType, secureCookies), method: "GET", path, public: true });
|
||||
if (CODE_FLOWS.has(flowType)) routes.push({ handler: codeFlowSubmit(kratos, flowType), method: "POST", path, public: true });
|
||||
}
|
||||
routes.push({ handler: logout(kratos, secureCookies), method: "POST", path: "/logout", public: true });
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user