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
3 changes: 3 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,9 @@ restyle:

- The five states, and the wording that sends people back to the chat app. A
person on this page came from Slack or Teams and needs to be told to go back
- No Connect button until the preview has named the chat account, including
when the preview fails. That name is the only check a person can make against
a link somebody else sent them
- The `noindex,nofollow` and `no-referrer` meta tags. The URL carries a token
- Sign-in starting on arrival rather than behind a second click

Expand Down
25 changes: 18 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,8 @@ makes it run as each of your customers instead.
as `?token=`, and the app they came from as `?platform=`
3. Your page signs the visitor in the way your product already does
4. Your backend asks `POST /api/v1/customer-links/preview` who the token names,
and your page shows it next to who they are signed in as
and your page shows it next to who they are signed in as. Only then does it
offer Connect
5. Your backend `POST`s the token and your own identifier for that user to
`POST /api/v1/customer-links`, with your Agenta API key
6. Agenta stores the link. It is durable — only the token was short-lived — and
Expand Down Expand Up @@ -50,11 +51,20 @@ https://app.example.com/connect

## What can go wrong

| Status | What happened | What to tell them |
| --------------------- | -------------------------------------- | ---------------------------- |
| `400 invalid_request` | Expired, tampered with, or not a token | Ask the agent for a new link |
| `409 link_token_used` | The link was already redeemed | Ask for a new one if needed |
| `502` | Agenta could not be reached | Try again |
| Agenta answers | What happened | What to tell them |
| --------------------- | ------------------------------------------------ | ---------------------------- |
| `400 invalid_request` | Expired, tampered with, or not a token | Ask the agent for a new link |
| `409 link_token_used` | The link was already redeemed | Ask for a new one if needed |
| `401` to `404` | Your API key or plan, or an agent it doesn't own | Try again later |
| No answer, or a `5xx` | Agenta could not be reached | Try again |

Your endpoints answer `502` for the last two rows. Neither is the person's
link, so neither may read as an expired one: they would only ask the agent for
a new link that fails the same way.

Only redeeming says a link was used. The preview reads the token, not whether
it has been redeemed, so a spent link still names its account until it
expires.

## Two things to keep

Expand All @@ -69,7 +79,8 @@ which the attacker's messages run as them. Every request in that sequence is
first-party, correctly signed, and impossible to tell from the real thing at the
server. The only place it can be caught is on the page, by a person reading
"Connect your account (you@corp.com) to Slack (@attacker in Some Other Corp)".
That is what `preview` is for.
That is what `preview` is for, and why the page offers no Connect button until
it has answered, or when it could not.

**Take a JSON body, not a form post.** An HTML form can only send urlencoded,
multipart, or plain text bodies, so a server that requires `application/json`
Expand Down
94 changes: 66 additions & 28 deletions src/connect-page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@
* The page the Connect button opens.
*
* It reads `?token=`, makes sure the visitor is signed in to your product, asks
* your server who the token names, and posts the token back to your own
* `/connect`. Everything it renders is one of five states, because those
* your server who the token names, and only then offers to post the token back to
* your own `/connect`. Everything it renders is one of five states, because those
* are the only five things that can happen and each one needs a person to be
* told something different.
*
Expand All @@ -21,8 +21,9 @@ import type { LinkDescription } from "./connect.js";
/**
* Where the visitor is.
*
* `ready` is the only state with a button. The other four are terminal, and the
* three that are not `failed` all end the same way: go back to the chat app.
* `ready` offers the button once the preview has named the account, and `failed`
* offers it again if Connect itself failed; a preview that failed has nothing to
* retry against. The other three all end the same way: go back to the chat app.
*/
export type ConnectStatus = "ready" | "connected" | "invalid" | "used" | "failed";

Expand All @@ -37,9 +38,22 @@ const APP_NAMES: Record<LinkDescription["surface"], string> = {
copilot: "Copilot",
};

/** What to call the chat app before the description has said which one it is. */
/** What to call the chat app when nothing has said which one it is. */
const ANY_APP = "Slack, Teams, or Copilot";

/**
* What to call the chat app the visitor came from.
* @param surface The preview's `surface`, or Agenta's `?platform=` before the preview has answered.
* @returns "Slack", "Teams", or "Copilot", or all three when it is not one of them.
*/
export function appName(surface: string | undefined): string {
// Compared one by one rather than looked up, so "?platform=constructor"
// names all three apps, not a function from the object's prototype.
return surface === "slack" || surface === "teams" || surface === "copilot"
? APP_NAMES[surface]
: ANY_APP;
}

/**
* What to say in each terminal state.
* @param status Where the visitor ended up.
Expand Down Expand Up @@ -74,24 +88,29 @@ export function statusContent(status: ConnectStatus, platform: string): StatusCo
* Show this next to who the visitor is signed in as. Someone who was sent a
* link they did not ask for is reading the only line on the page that can tell
* them so.
* @param description What your server got back from Agenta, if anything.
* @returns A phrase such as "Slack (@alice in Acme Corp)".
* @param description What your server got back from Agenta.
* @returns A phrase such as "Slack (@alice in Acme Corp)" or "Teams (Alice Smith)".
*/
export function identityLabel(description: LinkDescription | undefined): string {
if (!description) return ANY_APP;
const inside = [
description.platformUserName && `@${description.platformUserName}`,
description.workspaceName && `in ${description.workspaceName}`,
]
.filter(Boolean)
.join(" ");
const app = APP_NAMES[description.surface];
export function identityLabel(description: LinkDescription): string {
const { surface, platformUserName, workspaceName } = description;
// As each app shows a person: Slack as "@" and their display name, Teams and
// Copilot as the name alone.
const who =
platformUserName && (surface === "slack" ? `@${platformUserName}` : platformUserName);
const inside = [who, workspaceName && `in ${workspaceName}`].filter(Boolean).join(" ");
const app = APP_NAMES[surface];
return inside ? `${app} (${inside})` : app;
}

export interface ConnectPageProps {
/** The `?token=` query parameter, however your router hands it over. */
token: string;
/**
* The `?platform=` query parameter Agenta sends alongside the token. Only names
* the app in messages shown before the preview has answered: anyone can edit a
* URL, so who is being connected comes from the preview alone.
*/
platform?: string;
/** Whether your own session is loading. */
loading: boolean;
/** Whether the visitor is signed in to your product. */
Expand All @@ -105,6 +124,7 @@ export interface ConnectPageProps {
/** Links the signed-in visitor's account to the chat identity that sent them here. */
export function ConnectPage({
token,
platform,
loading,
isAuthenticated,
signIn,
Expand Down Expand Up @@ -137,13 +157,15 @@ export function ConnectPage({
if (status !== "ready" || !token || loading || isAuthenticated) return;
if (signInStarted.current) return;
signInStarted.current = true;
signIn(`/connect?${new URLSearchParams({ token }).toString()}`).catch(() =>
setStatus("failed"),
);
}, [isAuthenticated, loading, signIn, status, token]);
// Back to this same link, `platform` included, so the messages that come
// before the preview still name the app.
const returnTo = new URLSearchParams({ token });
if (platform) returnTo.set("platform", platform);
signIn(`/connect?${returnTo.toString()}`).catch(() => setStatus("failed"));
}, [isAuthenticated, loading, platform, signIn, status, token]);

// Asked for before the button is offered, so nobody clicks Connect without
// having been told what they are connecting.
// The button is not offered until this answers, so nobody clicks Connect
// without having been told what they are connecting.
useEffect(() => {
if (!token || !isAuthenticated) return;
let live = true;
Expand All @@ -157,9 +179,11 @@ export function ConnectPage({
if (!live) return;
if (response.ok) setDescription((await response.json()) as LinkDescription);
else if (response.status === 400) setStatus("invalid");
else setStatus("failed");
} catch {
// Leaves the button offered against the generic noun. A dead
// token is caught again on redeem, where it costs nothing.
// Not a reason to offer the button anyway: without the account's
// name there is nothing for the visitor to check.
if (live) setStatus("failed");
}
})();
return () => {
Expand Down Expand Up @@ -191,8 +215,8 @@ export function ConnectPage({
}
};

const target = identityLabel(description);
const content = statusContent(status, description ? APP_NAMES[description.surface] : ANY_APP);
const app = appName(description?.surface ?? platform);
const content = statusContent(status, app);
if (content) {
return (
<main>
Expand All @@ -208,7 +232,7 @@ export function ConnectPage({
return (
<main>
<h1>This link has expired</h1>
<p>Return to {ANY_APP} and ask the agent for a new link</p>
<p>Return to {app} and ask the agent for a new link</p>
</main>
);
}
Expand All @@ -226,11 +250,25 @@ export function ConnectPage({
);
}

if (!description) {
return (
<main>
<h1>Connect your account</h1>
{status === "failed" ? (
<p>We could not check this connection. Please try again.</p>
) : (
<p>Checking this connection…</p>
)}
</main>
);
}

return (
<main>
<h1>Connect your account</h1>
<p>
Connect your account{accountName ? ` (${accountName})` : ""} to {target}
Connect your account{accountName ? ` (${accountName})` : ""} to{" "}
{identityLabel(description)}
</p>
{status === "failed" && <p>We could not connect the account. Please try again.</p>}
<button type="button" onClick={() => void connect()} disabled={submitting}>
Expand Down
58 changes: 46 additions & 12 deletions src/connect.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,18 @@ export type ConnectFailure = "invalid" | "used" | "unreachable";

export type ConnectResult = { connected: true } | { connected: false; reason: ConnectFailure };

/**
* Why there is nothing to show for a link token.
*
* No `used`: the preview reads the token, not whether it has been redeemed, so a
* spent link still previews until it expires. Only redeeming it says so.
*/
export type PreviewFailure = "invalid" | "unreachable";

export type PreviewResult =
| { described: true; description: LinkDescription }
| { described: false; reason: PreviewFailure };

/**
* Who a link token names, for the page to show before anyone clicks Connect.
*
Expand Down Expand Up @@ -86,6 +98,11 @@ export async function redeemLinkToken(
return { connected: false, reason: "unreachable" };
}

const SURFACES: ReadonlySet<string> = new Set(["slack", "teams", "copilot"]);

const optionalName = (value: unknown): string | undefined =>
typeof value === "string" ? value : undefined;

/**
* Asks Agenta who a link token names, without redeeming it.
*
Expand All @@ -95,9 +112,9 @@ export async function redeemLinkToken(
* and indistinguishable from the real thing. Naming the chat account the link
* would bind to is the one part of the flow the victim can recognise as wrong.
* @param linkToken The `?token=` the Connect button carried into the browser.
* @returns Who the token names, or null when it is expired, spent, or not yours.
* @returns Who the token names, or why there is nothing to show.
*/
export async function previewLinkToken(linkToken: string): Promise<LinkDescription | null> {
export async function previewLinkToken(linkToken: string): Promise<PreviewResult> {
let response: Response;
try {
response = await fetch(`${env("AGENTA_API_URL")}/customer-links/preview`, {
Expand All @@ -109,16 +126,33 @@ export async function previewLinkToken(linkToken: string): Promise<LinkDescripti
body: JSON.stringify({ linkToken }),
});
} catch {
return null;
return { described: false, reason: "unreachable" };
}
if (!response.ok) return null;

const body = (await response.json()) as LinkDescription;
// Only a 400 is about the link: expired, tampered with, or simply wrong. A 401
// is your API key, and a 403 or 404 an agent that key does not own or that no
// longer exists. None of those is the person's fault, and calling the link
// expired would only send them for a new one that fails the same way.
if (response.status === 400) return { described: false, reason: "invalid" };
if (!response.ok) return { described: false, reason: "unreachable" };

let body: Record<string, unknown>;
try {
body = (await response.json()) as Record<string, unknown>;
} catch {
return { described: false, reason: "unreachable" };
}
if (typeof body.agentName !== "string" || !SURFACES.has(body.surface as string)) {
return { described: false, reason: "unreachable" };
}
return {
agentName: body.agentName,
surface: body.surface,
workspaceName: body.workspaceName,
platformUserName: body.platformUserName,
described: true,
description: {
agentName: body.agentName,
surface: body.surface as LinkDescription["surface"],
workspaceName: optionalName(body.workspaceName),
platformUserName: optionalName(body.platformUserName),
},
};
}

Expand Down Expand Up @@ -187,8 +221,8 @@ export function handlePreviewRequest(
const linkToken = body.token?.trim();
if (!linkToken) return json({ error: "A connection token is required" }, 400);

const description = await previewLinkToken(linkToken);
if (!description) return json({ error: MESSAGE_BY_REASON.invalid }, 400);
return json(description, 200);
const result = await previewLinkToken(linkToken);
if (result.described) return json(result.description, 200);
return json({ error: MESSAGE_BY_REASON[result.reason] }, STATUS_BY_REASON[result.reason]);
};
}
45 changes: 45 additions & 0 deletions tests/connect-page.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
// SPDX-FileCopyrightText: 2026-present Agenta <hello@buildagenta.com>
//
// SPDX-License-Identifier: Apache-2.0

import { describe, expect, test } from "bun:test";
import { appName, identityLabel } from "../src/connect-page.js";

describe("identityLabel", () => {
test("names a Slack account as Slack shows it", () => {
expect(
identityLabel({
agentName: "Bookings",
surface: "slack",
workspaceName: "Acme Corp",
platformUserName: "Alice Smith",
}),
).toBe("Slack (@Alice Smith in Acme Corp)");
});

test.each([
["teams", "Teams"],
["copilot", "Copilot"],
] as const)("names a %s account without an @", (surface, app) => {
expect(
identityLabel({ agentName: "Bookings", surface, platformUserName: "Alice Smith" }),
).toBe(`${app} (Alice Smith)`);
});

test("falls back to the app alone when the platform names nobody", () => {
expect(identityLabel({ agentName: "Bookings", surface: "teams" })).toBe("Teams");
});
});

describe("appName", () => {
test("names the app Agenta said the visitor came from", () => {
expect(appName("copilot")).toBe("Copilot");
});

test.each([undefined, "", "irc", "constructor", "toString"])(
"names all three apps for %p",
(surface) => {
expect(appName(surface)).toBe("Slack, Teams, or Copilot");
},
);
});
Loading
Loading