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
56 changes: 38 additions & 18 deletions packages/app/src/features/auth/consent.tsx
Original file line number Diff line number Diff line change
@@ -1,27 +1,36 @@
import { Button, Input, Label, Page } from "../../shared/ui";
import { useState } from "react";
import { Button, Input, Label, Page, Select } from "../../shared/ui";
import { useEffect, useState } from "react";
import { useQuery, useMutation } from "@tanstack/react-query";
import { api } from "factorize-api-client";
import { messageOf } from "./session";

type ConnectionTarget = { kind: "installation" | "legacy"; id: string };
const targetKey = (target?: ConnectionTarget) => target ? target.kind + ":" + target.id : "new";
const targetKey = (target?: ConnectionTarget | null) => target ? target.kind + ":" + target.id : "new";

export function ConsentScreen() {
const authorizationQuery = location.search.slice(1);
const [target, setTarget] = useState<ConnectionTarget>();
const [target, setTarget] = useState<ConnectionTarget | null>();
const [selection, setSelection] = useState<{ request: string; scopes: string[] }>();
const preview = useQuery({
queryKey: ["consent", authorizationQuery, targetKey(target)],
queryFn: async ({ signal }) => {
const { data, error } = await api.POST("/api/v1/oauth/consent/preview", { signal, body: { authorizationQuery, target } });
const { data, error } = await api.POST("/api/v1/oauth/consent/preview", { signal, body: { authorizationQuery, target: target ?? undefined } });
if (!data || error) throw new Error(messageOf(error));
return data;
},
staleTime: Infinity,
retry: false,
});
const data = preview.data;
// A callback handoff can reconnect, but never guess between several installs.
// null is the user's explicit choice to create a separate connection.
const targets = new URLSearchParams(authorizationQuery).has("connection") ? data?.targets ?? [] : [];
const reconnectSelected = targets.length > 0 && target !== null;
const needsTarget = reconnectSelected && !target;
const defaultTarget = needsTarget && targets.length === 1 ? targets[0] : undefined;
useEffect(() => {
if (defaultTarget) setTarget({ kind: defaultTarget.kind, id: defaultTarget.id });
}, [defaultTarget]);
const scopes = data && selection?.request === data.request ? selection.scopes : (data?.selectedScopes ?? []);
const stepUp = data?.scopes.filter(scope => data.newScopes?.includes(scope)) ?? [];
const saved = data?.savedOutsideRequestedScopes ?? [];
Expand All @@ -39,7 +48,7 @@ export function ConsentScreen() {
location.assign(result.redirectTo);
},
});
const changeTarget = (next?: ConnectionTarget) => {
const changeTarget = (next: ConnectionTarget | null | undefined) => {
setSelection(undefined);
decision.reset();
setTarget(next);
Expand All @@ -53,22 +62,33 @@ export function ConsentScreen() {
<h1 className="text-3xl font-semibold">{data?.reconnect ? "Reconnect" : "Authorize"} {data?.clientName ?? "a client"}</h1>
{preview.isFetching && <p role="status">Validating authorization request…</p>}
{preview.error && <p role="alert">{preview.error.message}</p>}
{preview.isError && target && <Button disabled={preview.isFetching} onClick={() => changeTarget()}>Choose another connection</Button>}
{data && !preview.isError && !preview.isFetching && <>
{!!data.targets?.length && <fieldset className="mb-4" disabled={decision.isPending || decision.isSuccess}>
{preview.isError && target && <Button disabled={preview.isFetching} onClick={() => changeTarget(null)}>Choose another connection</Button>}
{data && !defaultTarget && !preview.isError && !preview.isFetching && <>
{targets.length > 0 && <fieldset className="mb-4" disabled={decision.isPending || decision.isSuccess}>
<legend>Which connection should receive the new authorization?</legend>
<Label className="block">
<Input type="radio" name="oauth-connection-target" checked={!target} onChange={() => changeTarget()} />
<Input type="radio" name="oauth-connection-mode" checked={reconnectSelected} onChange={() => changeTarget(undefined)} />
Reconnect
</Label>
<Label className="block">
<Input type="radio" name="oauth-connection-mode" checked={!reconnectSelected} onChange={() => changeTarget(null)} />
Create a separate connection
</Label>
{data.targets.map(choice => <Label className="block" key={targetKey(choice)}>
<Input type="radio" name="oauth-connection-target" checked={targetKey(target) === targetKey(choice)}
onChange={() => changeTarget({ kind: choice.kind, id: choice.id })} />
Reconnect {choice.name} ({new Date(choice.createdAt).toLocaleString()})
</Label>)}
{reconnectSelected && <Label className="block">
Connection to reconnect
<Select value={target ? targetKey(target) : ""} onChange={event => {
const choice = targets.find(choice => targetKey(choice) === event.target.value);
if (choice) changeTarget({ kind: choice.kind, id: choice.id });
}}>
<option value="" disabled>Choose a connection</option>
{targets.map(choice => <option key={targetKey(choice)} value={targetKey(choice)}>
{choice.name} ({new Date(choice.createdAt).toLocaleString()})
</option>)}
</Select>
</Label>}
<p className="text-sm">Only connections with this exact compatible client and callback are listed. Reconnect only the installation you started from. A successful reconnect replaces its credential and keeps its subscriptions. When in doubt, create a separate connection.</p>
</fieldset>}
<p>{data.reconnect ? "Review your saved choices and select the permissions to grant to the new token. Existing tokens won’t gain permissions." : "Select the workspace permissions to grant to this client."} Write does not imply read. Trigger writes can cause future schedule or webhook processing.</p>
{!needsTarget && <><p>{data.reconnect ? "Review your saved choices and select the permissions to grant to the new token. Existing tokens won’t gain permissions." : "Select the workspace permissions to grant to this client."} Write does not imply read. Trigger writes can cause future schedule or webhook processing.</p>
{!!data.unavailableSavedScopes?.length && <p role="status">These saved permissions are not available in this request and will not be in the new token: {data.unavailableSavedScopes.join(", ")}. Your saved choices are unchanged. Check whether the integration is still connected and available.</p>}
<fieldset disabled={decision.isPending || decision.isSuccess || decision.isError}>
<legend>Permissions</legend>
Expand All @@ -92,8 +112,8 @@ export function ConsentScreen() {
})}
</div>)}
</fieldset>
<p>Request expires {data.expiresAt}.</p>
<Button variant="primary" disabled={decision.isPending || decision.isSuccess || decision.isError} onClick={() => decision.mutate("allow")}>Allow</Button>
<p>Request expires {data.expiresAt}.</p></>}
<Button variant="primary" disabled={needsTarget || decision.isPending || decision.isSuccess || decision.isError} onClick={() => decision.mutate("allow")}>Allow</Button>
<Button disabled={decision.isPending || decision.isSuccess || decision.isError} onClick={() => decision.mutate("deny")}>Deny</Button>
</>}
{decision.error && <p role="alert">{decision.error.message}</p>}
Expand Down
43 changes: 40 additions & 3 deletions packages/app/test/functional/protocol.spec.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,7 @@ test("reconnect separates granted, requested, blocked and optional permissions w
});


test("explicitly chooses the existing compatible connection rather than inferring it", async () => {
test("defaults to the only compatible reconnect on a callback handoff and waits for approval", async () => {
const { context, page } = await setup();
try {
const requests = [];
Expand All @@ -148,9 +148,14 @@ test("explicitly chooses the existing compatible connection rather than inferrin
return route.fulfill({json:{redirectTo:origin+"/completed?code=issued"}});
});
await page.goto(origin+"/authorize?client_id=client&connection=fixture");
await page.getByRole("radio", {name:"Create a separate connection"}).waitFor();
await page.getByRole("heading", {name:"Reconnect External CLI"}).waitFor();
assert.equal(await page.getByRole("radio", {name:"Reconnect",exact:true}).isChecked(), true);
assert.equal(await page.getByLabel("Connection to reconnect").inputValue(), "installation:existing-1");
assert.equal(approval, undefined);
await page.getByRole("radio", {name:"Create a separate connection"}).check();
await page.getByRole("heading", {name:"Authorize External CLI"}).waitFor();
assert.equal(await page.getByRole("radio", {name:"Create a separate connection"}).isChecked(), true);
await page.getByRole("radio", {name:/Reconnect Laptop client/}).check();
await page.getByRole("radio", {name:"Reconnect",exact:true}).check();
await page.getByRole("heading", {name:"Reconnect External CLI"}).waitFor();
await page.getByRole("heading", {name:"Additional permissions you saved for this connection"}).waitFor();
assert.equal(await page.getByLabel("triggers:write").isChecked(), true);
Expand All @@ -162,3 +167,35 @@ test("explicitly chooses the existing compatible connection rather than inferrin
assert.deepEqual(approval, {request:"reconnect-request",signature:"signed",decision:"allow",scopes:["team:read"]});
} finally { await context.close(); }
});


test("leaves a new request alone and requires a target when reconnect offers multiple installations", async () => {
const { context, page } = await setup();
try {
const requests = [];
await page.route("**/api/v1/oauth/consent/preview", route => {
const body = route.request().postDataJSON();
requests.push(body);
const one = {kind:"installation", id:"existing-1", name:"Laptop", createdAt:"2026-10-09T12:00:00Z"};
const targets = body.authorizationQuery.includes("connection=") ? [one,{...one,id:"existing-2",name:"Desktop"}] : [one];
return route.fulfill({json:{clientName:"External CLI", reconnect:!!body.target, targets, scopes:[], selectedScopes:[],
request:"signed-request", signature:"signature", expiresAt:"2026-10-09T12:00:00Z"}});
});
await page.goto(origin+"/authorize?client_id=client");
await page.getByRole("button", {name:"Allow",exact:true}).waitFor();
assert.equal(await page.getByRole("radio", {name:"Reconnect",exact:true}).count(), 0);
assert.equal(await page.getByRole("button", {name:"Allow",exact:true}).isEnabled(), true);
await page.goto(origin+"/authorize?client_id=client&connection=fixture");
const reconnect = page.getByRole("radio", {name:"Reconnect",exact:true});
await reconnect.waitFor();
assert.equal(await reconnect.isChecked(), true);
assert.equal(await page.getByLabel("Connection to reconnect").inputValue(), "");
assert.equal(await page.getByRole("button", {name:"Allow",exact:true}).isEnabled(), false);
assert.equal(requests.length, 2);
assert.ok(requests.every(request => request.target === undefined));
await page.getByLabel("Connection to reconnect").selectOption("installation:existing-2");
await page.getByRole("heading", {name:"Reconnect External CLI"}).waitFor();
assert.deepEqual(requests[2].target, {kind:"installation", id:"existing-2"});
assert.equal(await page.getByRole("button", {name:"Allow",exact:true}).isEnabled(), true);
} finally { await context.close(); }
});
Loading