Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 25 additions & 6 deletions worker/src/routes/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,27 @@ export function requireRaftConfig(c: Context<{ Bindings: Env }>) {
};
}

/**
* Start Login with Raft at Raft's standard authorization endpoint. Raft owns
* where it sends the browser next (its own login/consent pages) and validates
* redirect_uri against the client's registered callbacks; Raft Desktop's
* built-in browser only takes over this standard request, never Raft's own
* setup page.
*/
export function raftAuthorizeUrl(
config: { clientId: string; raftApiOrigin: string },
redirectUri: string,
state?: string,
): string {
const url = new URL("/api/oauth/authorize", config.raftApiOrigin);
url.searchParams.set("response_type", "code");
url.searchParams.set("client_id", config.clientId);
url.searchParams.set("redirect_uri", redirectUri);
url.searchParams.set("scope", "openid profile");
if (state) url.searchParams.set("state", state);
return url.toString();
}

function normalizeReturnPath(raw: string | undefined): string {
if (!raw || !raw.startsWith("/") || raw.startsWith("//")) return "/";
if (raw.startsWith("/api/") || raw.startsWith("/login/")) return "/";
Expand Down Expand Up @@ -377,6 +398,7 @@ export async function exchangeRaftCode(
clientId: string,
clientSecret: string,
code: string,
redirectUri?: string,
): Promise<RaftTokenResponse> {
const response = await fetch(`${apiOrigin}/api/oauth/token`, {
method: "POST",
Expand All @@ -387,6 +409,7 @@ export async function exchangeRaftCode(
body: JSON.stringify({
grant_type: "authorization_code",
code,
...(redirectUri ? { redirect_uri: redirectUri } : {}),
}),
});

Expand Down Expand Up @@ -601,6 +624,7 @@ async function finalizeRaftLogin(
config.clientId,
config.clientSecret,
code,
callbackUrl(c),
);
const userinfo = await fetchRaftUserinfo(
config.raftApiOrigin,
Expand Down Expand Up @@ -740,12 +764,7 @@ export async function handleAuthLogin(c: Context<{ Bindings: Env }>) {
maxAge: BROWSER_LOGIN_STATE_TTL_MS / 1000,
});

const setup = new URL("/login-with-raft/setup", config.raftOrigin);
setup.searchParams.set("client_id", config.clientId);
setup.searchParams.set("return_to", callbackUrl(c));
setup.searchParams.set("scope", "openid profile");
setup.searchParams.set("state", state);
const setupUrl = setup.toString();
const setupUrl = raftAuthorizeUrl(config, callbackUrl(c), state);
const accept = c.req.header("accept") || "";
if (accept.includes("text/html")) {
c.header("cache-control", "no-store");
Expand Down
13 changes: 7 additions & 6 deletions worker/src/routes/installer_auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,15 @@ import {
exchangeRaftCode,
fetchRaftUserinfo,
isUserAllowed,
raftAuthorizeUrl,
requireRaftConfig,
upsertRaftAccount,
} from "./auth";

function installerCallbackUrl(c: Context<{ Bindings: Env }>): string {
return `${businessOrigin(c.env, () => requestOrigin(c))}/login/raft/installer/callback`;
}

const LOGIN_COOKIE = "hands_installer_login";
const LOGIN_REQUEST_TTL_MS = 10 * 60 * 1000;
const LOGIN_CODE_TTL_MS = 2 * 60 * 1000;
Expand Down Expand Up @@ -73,12 +78,8 @@ export async function handleInstallerLogin(c: Context<{ Bindings: Env }>) {
maxAge: LOGIN_REQUEST_TTL_MS / 1000,
});

const setup = new URL("/login-with-raft/setup", config.raftOrigin);
setup.searchParams.set("client_id", config.clientId);
setup.searchParams.set("return_to", `${businessOrigin(c.env, () => requestOrigin(c))}/login/raft/installer/callback`);
setup.searchParams.set("scope", "openid profile");
noStore(c);
return c.redirect(setup.toString(), 302);
return c.redirect(raftAuthorizeUrl(config, installerCallbackUrl(c)), 302);
}

export async function handleInstallerRaftCallback(c: Context<{ Bindings: Env }>) {
Expand All @@ -99,7 +100,7 @@ export async function handleInstallerRaftCallback(c: Context<{ Bindings: Env }>)

try {
const token = await exchangeRaftCode(
config.raftApiOrigin, config.clientId, config.clientSecret, raftCode,
config.raftApiOrigin, config.clientId, config.clientSecret, raftCode, installerCallbackUrl(c),
);
const userinfo = await fetchRaftUserinfo(config.raftApiOrigin, token.access_token);
if (userinfo.type !== "human" || !isUserAllowed(c.env, userinfo)) {
Expand Down
19 changes: 13 additions & 6 deletions worker/test/routes.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2611,7 +2611,7 @@ describe("auth origin handling", () => {
expect(parts[2]).toMatch(/^[A-Za-z0-9_-]+$/);
});

it("redirects Login with Raft through the current Raft setup route", async () => {
it("starts Login with Raft at Raft's standard authorization endpoint", async () => {
const env = makeMockEnv();
env.RAFT_CLIENT_ID = "test-client";
const app = new Hono<{ Bindings: MockEnv }>();
Expand All @@ -2625,10 +2625,11 @@ describe("auth origin handling", () => {

expect(res.status).toBe(302);
const location = new URL(res.headers.get("location") ?? "");
expect(location.origin).toBe("https://raft.example");
expect(location.pathname).toBe("/login-with-raft/setup");
expect(location.origin + location.pathname).toBe(`${env.RAFT_API_ORIGIN}/api/oauth/authorize`);
expect(location.searchParams.get("response_type")).toBe("code");
expect(location.searchParams.get("scope")).toBe("openid profile");
expect(location.searchParams.get("client_id")).toBe("test-client");
expect(location.searchParams.get("return_to")).toBe(
expect(location.searchParams.get("redirect_uri")).toBe(
"https://business.example/login/raft/callback",
);
expect(location.searchParams.get("state")).toMatch(/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/);
Expand All @@ -2648,7 +2649,7 @@ describe("auth origin handling", () => {

expect(res.status).toBe(302);
const location = new URL(res.headers.get("location") ?? "");
expect(location.searchParams.get("return_to")).toBe(
expect(location.searchParams.get("redirect_uri")).toBe(
"https://business.example/login/raft/callback",
);
expect(location.searchParams.get("state")).toMatch(/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/);
Expand All @@ -2675,7 +2676,7 @@ describe("auth origin handling", () => {
);

const location = new URL(res.headers.get("location") ?? "");
expect(location.searchParams.get("return_to")).toBe(
expect(location.searchParams.get("redirect_uri")).toBe(
"http://localhost:8787/login/raft/callback",
);
expect(location.searchParams.get("state")).toMatch(/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/);
Expand Down Expand Up @@ -2768,6 +2769,12 @@ describe("auth origin handling", () => {
expect(new URL(secondCallback.headers.get("location") ?? "").pathname).toBe("/apps/second");
expect(new URL(firstCallback.headers.get("location") ?? "").pathname).toBe("/apps/first");
expect(globalThis.fetch).toHaveBeenCalledTimes(4);
// The token exchange names the same registered callback as the authorize request.
const tokenCall = (globalThis.fetch as any).mock.calls.find(([url]: [string]) => String(url).endsWith("/api/oauth/token"));
expect(JSON.parse(tokenCall[1].body)).toMatchObject({
grant_type: "authorization_code",
redirect_uri: "https://business.example/login/raft/callback",
});
} finally {
globalThis.fetch = originalFetch;
}
Expand Down
Loading