Skip to content

armgit / qm

Public Imported from GitHub
0

Multiplayer agent harness for work.

Link personal Slack accounts to existing web identities (#1442)

Regan Belle29acebd6c65
diff --git a/README.md b/README.md
index de7d118e2..4545390d0 100644
--- a/README.md
+++ b/README.md
@@ -241,6 +241,7 @@ upstream source history to merge.
- [`docs/getting-started.md`](./docs/getting-started.md) — first run, end to end
- [`cli/README.md`](./cli/README.md) — the `qm` CLI and the deployment directory contract
- [`docs/deploy-directory.md`](./docs/deploy-directory.md) — the deployment directory in full
+- [`docs/principal-links.md`](./docs/principal-links.md) — one person, several sign-ins: linking principals
- [`docs/porter.md`](./docs/porter.md) — running qm on Porter
- [`docs/superserve.md`](./docs/superserve.md) — using Superserve for agent sandboxes
- [`.env.example`](./.env.example) — every knob, documented in place
diff --git a/docs/principal-links.md b/docs/principal-links.md
new file mode 100644
index 000000000..38df15dfe
--- /dev/null
+++ b/docs/principal-links.md
@@ -0,0 +1,60 @@
+# Principal links
+
+A person can reach qm through several sign-ins: a Slack account, an email
+magic link, or a trusted OIDC provider. Each produces its own principal id
+(`[email protected]`, `U0JORDAN`, `oidc:<issuer-hash>:<subject>`). Without a
+link, qm treats them as different people: a credential dropped from Slack is
+owned by the email principal, and the same founder signed in through OIDC is
+told the link is for someone else.
+
+A **principal link** records that two principal ids are one person. One id is
+the **canonical principal**; the other is a **linked sign-in**. Every
+same-person check in core (`personKey`, `samePerson`) folds a linked sign-in to
+its canonical principal, so ownership of credentials, admin grants, sessions,
+approvals, and secret drops recorded under either id belongs to the person.
+New writes use the canonical id: the identity service classifies a linked
+sign-in as its canonical principal, the portal resolves the session subject
+before proxying, and the keychain stores credentials under the canonical owner.
+
+## Rules
+
+- **Administrative links keep the directory member canonical.** When the company runs Slack, the
+ Slack-verified directory principal is the person's canonical id and the
+ trusted OIDC subject is the linked sign-in. The admin API refuses a link
+ whose linked side is a directory member, by principal id or Slack id.
+- **A link never creates an admin.** A sign-in that holds an org admin grant
+ can only be linked to a canonical principal that is already an admin.
+- **Links are flat.** A canonical principal is never itself linked onward, and
+ a linked sign-in cannot become canonical for others.
+- **Evidence is required.** Every link records how the two identities were
+ verified as one person and which admin created it.
+- **Links are reversible.** Deleting a link restores two separate principals.
+ Records written while the link existed stay under the canonical id, so a
+ wrong link is an incident to reconcile, not just a row to delete.
+- **Deactivation follows the person.** Deactivating either id deactivates both.
+
+## Admin API
+
+Org admins manage links through the admin surface; the agent cannot.
+
+```
+GET /v1/admin/principal-links
+POST /v1/admin/principal-links { principalId, canonicalId, evidence }
+DELETE /v1/admin/principal-links/:principalId
+```
+
+Surfaces resolve a sign-in with a source-authenticated read:
+
+```
+GET /v1/principals/:id/canonical → { principalId, canonicalId }
+```
+
+The portal caches the answer for one minute and refuses to proxy (503) when
+core cannot answer, rather than acting as the unresolved subject. A deleted
+link therefore stays effective for at most a minute of cached sessions.
+
+Links live in the `principal_links` durable map of the company database.
+
+## Self-service Slack linking
+
+The dedicated Connect Slack flow preserves the signed-in web principal as canonical, keeping its existing connector ownership. Completion verifies a short-lived signed ticket, Composio account ownership, Slack user identity, and the installed company workspace before linking the directory member. Existing credentials or Composio accounts on the Slack principal require support instead of being silently stranded. Email similarity is not proof of identity.
diff --git a/plugins/admin/src/index.ts b/plugins/admin/src/index.ts
index 283eecb23..c95da8cac 100644
--- a/plugins/admin/src/index.ts
+++ b/plugins/admin/src/index.ts
@@ -298,6 +298,7 @@ async function coreWhoami(principal: string): Promise<{ isAdmin: boolean; role?:
const WRITES = new Map<string, string[]>([
["grants", ["POST", "DELETE"]],
+ ["principal-links", ["POST", "DELETE"]],
["external-users", ["POST", "DELETE"]],
["memory", ["PUT"]],
["crons", ["PUT"]],
@@ -335,6 +336,7 @@ const READS = [
"model-providers",
"model-registry",
"custom-providers",
+ "principal-links",
];
export async function handler(req: IncomingMessage, res: ServerResponse): Promise<void> {
diff --git a/plugins/chassis/src/portal-identity.ts b/plugins/chassis/src/portal-identity.ts
index ac43b52f4..f461a6a70 100644
--- a/plugins/chassis/src/portal-identity.ts
+++ b/plugins/chassis/src/portal-identity.ts
@@ -2,6 +2,7 @@ import { createHmac, timingSafeEqual } from "node:crypto";
export interface PortalIdentity {
p: string;
+ authenticatedAs?: string;
n?: string;
imp?: string;
exp: number;
@@ -30,6 +31,8 @@ export function verifyPortalIdentity(token: string, secret: string, nowMs: numbe
return null;
}
if (!claims || typeof claims.p !== "string" || !claims.p || typeof claims.exp !== "number") return null;
+ if (claims.authenticatedAs !== undefined && (typeof claims.authenticatedAs !== "string" || !claims.authenticatedAs))
+ return null;
if (nowMs > claims.exp) return null;
return claims;
}
diff --git a/plugins/portal/README.md b/plugins/portal/README.md
index b10b9236b..f08ffcba1 100644
--- a/plugins/portal/README.md
+++ b/plugins/portal/README.md
@@ -42,6 +42,10 @@ surfaces, and it does **not** import the core.
**exact first path segment**, strips the prefix, and proxies to the private upstream,
synthesizing the surface cookie for compatibility and attaching a short-lived signed portal
identity. Surfaces pass that identity to core, which verifies it before any user-scoped action.
+ Before proxying, the portal asks core for the session subject's canonical principal
+ (`GET /v1/principals/:id/canonical`, cached for a minute). A sign-in that an org admin has
+ linked to another identity therefore acts as that person's canonical principal; see
+ [`docs/principal-links.md`](../../docs/principal-links.md).
## Additional trusted entry (PoC)
@@ -277,3 +281,5 @@ 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.
+
+The proxy also signs the original authenticated subject as `authenticatedAs`. Core verifies that it still belongs to the canonical person, rejecting stale claims after unlinking. Trusted-entry failures offer retry of that provider without an alternate email sign-in link; invitation authentication remains unchanged.
diff --git a/plugins/portal/src/index.ts b/plugins/portal/src/index.ts
index 58e28d834..bd5bff708 100644
--- a/plugins/portal/src/index.ts
+++ b/plugins/portal/src/index.ts
@@ -296,6 +296,43 @@ async function isAdmin(sub: string): Promise<boolean> {
return (await adminProbe(sub)).isAdmin;
}
+const CANONICAL_TTL_MS = 60_000;
+const CANONICAL_TIMEOUT_MS = 4_000;
+const canonicalCache = new LRUCache<string, string>({ max: 10_000, ttl: CANONICAL_TTL_MS });
+
+async function canonicalPrincipal(sub: string): Promise<string | null> {
+ const hit = canonicalCache.get(sub);
+ if (hit !== undefined) return hit;
+ const path = withSourceAuthNonce(`/v1/principals/${encodeURIComponent(sub)}/canonical`, CORE_SIGNING_SECRET);
+ try {
+ const r = await fetch(`${CORE}${path}`, {
+ headers: signedHeaders(CORE_SIGNING_SECRET, "GET", path),
+ signal: AbortSignal.timeout(CANONICAL_TIMEOUT_MS),
+ });
+ if (!r.ok) {
+ console.warn(`[portal] canonical principal lookup returned HTTP ${r.status}`);
+ return null;
+ }
+ const body = (await r.json()) as { canonicalId?: unknown };
+ const canonical = typeof body.canonicalId === "string" && body.canonicalId ? body.canonicalId : sub;
+ canonicalCache.set(sub, canonical);
+ return canonical;
+ } catch (error) {
+ console.warn(`[portal] canonical principal lookup failed: ${errMessage(error)}`);
+ return null;
+ }
+}
+
+function identityUnavailable(req: IncomingMessage, res: ServerResponse): void {
+ if (wantsHtml(req))
+ return sendHtml(
+ res,
+ 503,
+ '<!doctype html><meta charset=utf-8><body style="font-family:system-ui;max-width:32rem;margin:4rem auto"><h2>Service unavailable</h2><p>Could not confirm your identity. Try again in a moment.</p></body>',
+ );
+ json(res, 503, { error: "identity_unavailable", message: "could not confirm your identity, try again in a moment" });
+}
+
const PAGE_CSP =
"default-src 'none'; style-src 'unsafe-inline'; form-action 'self'; base-uri 'none'; frame-ancestors 'none'";
@@ -525,8 +562,7 @@ export function signInErrorHtml(
icon: ALERT_ICON,
warn: true,
extra: `<p class="reason"><strong>Details</strong>${escapeHtml(detail)}</p>`,
- actions: `<a class="btn primary" href="${retryPath}">Try signing in again</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>'}`,
+ actions: `<a class="btn primary" href="${retryPath}">Try signing in again</a>`,
help: "Still stuck? Check that your account has access, then contact your admin.",
});
}
@@ -1017,6 +1053,12 @@ async function handle(req: IncomingMessage, res: ServerResponse): Promise<void>
let session = currentSession(req);
if (session) renewSessionCookie(req, res);
+ const authenticatedPrincipal = session?.sub;
+ if (session && !session.anon && (!pathname.startsWith("/auth/") || pathname.startsWith("/auth/impersonate"))) {
+ const canonical = await canonicalPrincipal(session.sub);
+ if (canonical === null) return identityUnavailable(req, res);
+ session = { ...session, sub: canonical };
+ }
if (pathname === "/auth/impersonate" && method === "POST") {
if (!session) return json(res, 401, { error: "sign in" });
@@ -1024,7 +1066,8 @@ async function handle(req: IncomingMessage, res: ServerResponse): Promise<void>
if (!(await isAdmin(session.sub))) return json(res, 403, { error: "forbidden", message: "admin access required" });
const target = (url.searchParams.get("target") ?? "").trim();
if (!target) return json(res, 400, { error: "bad_request", message: "target required" });
- if (target === session.sub) return json(res, 400, { error: "bad_request", message: "cannot impersonate yourself" });
+ if (target === session.sub || (await canonicalPrincipal(target)) === session.sub)
+ return json(res, 400, { error: "bad_request", message: "cannot impersonate yourself" });
const result = await coreImpersonate("start", session.sub, target);
if (!result.ok) {
const status = result.status === 403 || result.status === 400 ? result.status : 502;
@@ -1272,6 +1315,7 @@ async function handle(req: IncomingMessage, res: ServerResponse): Promise<void>
...(!impersonator && session.name ? { displayName: session.name } : {}),
...(impersonator ? { impersonator } : {}),
...(PORTAL_IDENTITY_SECRET ? { identitySecret: PORTAL_IDENTITY_SECRET } : {}),
+ authenticatedPrincipal,
});
}
diff --git a/plugins/portal/src/proxy.ts b/plugins/portal/src/proxy.ts
index 5229a7b83..823264b45 100644
--- a/plugins/portal/src/proxy.ts
+++ b/plugins/portal/src/proxy.ts
@@ -105,6 +105,7 @@ export interface SurfaceTarget {
displayName?: string;
impersonator?: string;
identitySecret?: string;
+ authenticatedPrincipal?: string;
nowMs?: number;
}
@@ -120,6 +121,7 @@ export function proxyToSurface(req: IncomingMessage, res: ServerResponse, t: Sur
base[PORTAL_IDENTITY_HEADER] = mintPortalIdentity(
{
p: t.principal,
+ ...(t.authenticatedPrincipal ? { authenticatedAs: t.authenticatedPrincipal } : {}),
...(t.displayName ? { n: t.displayName } : {}),
...(t.impersonator ? { imp: t.impersonator } : {}),
exp: now + IDENTITY_TTL_MS,
diff --git a/plugins/portal/test/router.test.ts b/plugins/portal/test/router.test.ts
index 67a153195..fff560f10 100644
--- a/plugins/portal/test/router.test.ts
+++ b/plugins/portal/test/router.test.ts
@@ -49,6 +49,18 @@ const upstream = createServer((req: IncomingMessage, res) => {
JSON.stringify({ status: "authorize", authorizeUrl: "https://accounts.google.test/o/oauth2?x=1" }),
);
}
+ if (req.url?.startsWith("/v1/principals/U-admin-alias/canonical")) {
+ res.writeHead(200, { "content-type": "application/json" });
+ return void res.end(JSON.stringify({ canonicalId: "U-admin" }));
+ }
+ if (req.url?.startsWith("/v1/principals/U-alias/canonical")) {
+ res.writeHead(200, { "content-type": "application/json" });
+ return void res.end(JSON.stringify({ principalId: "U-alias", canonicalId: "U1" }));
+ }
+ if (req.url?.startsWith("/v1/principals/U-unresolved/canonical")) {
+ res.writeHead(500, { "content-type": "application/json" });
+ return void res.end(JSON.stringify({ error: "boom" }));
+ }
if (req.url === "/api/whoami") {
whoamiProbes++;
const m = (req.headers.cookie ?? "").match(/admin=([^;]+)/);
@@ -167,6 +179,27 @@ test("valid session: upstream receives ONLY the synthesized cookie, prefix strip
assert.equal(body.headers["x-admin-actor"], undefined);
});
+test("a session whose subject core links to another principal is proxied as that canonical principal", async () => {
+ const r = await fetch(`${base}/api/x`, { headers: { cookie: sessionCookie("U-alias") } });
+ assert.equal(r.status, 200);
+ const body = (await r.json()) as { cookie: string };
+ assert.equal(body.cookie, "webuiuser=U1");
+ const unlinked = await fetch(`${base}/api/x`, { headers: { cookie: sessionCookie("U-solo") } });
+ assert.equal(((await unlinked.json()) as { cookie: string }).cookie, "webuiuser=U-solo");
+});
+
+test("when core cannot resolve the session subject the portal refuses to proxy instead of guessing", async () => {
+ const r = await fetch(`${base}/api/x`, { headers: { cookie: sessionCookie("U-unresolved") } });
+ assert.equal(r.status, 503);
+ assert.equal(((await r.json()) as { error: string }).error, "identity_unavailable");
+ const logout = await fetch(`${base}/auth/logout`, {
+ method: "POST",
+ headers: { cookie: sessionCookie("U-unresolved"), origin: PUBLIC },
+ redirect: "manual",
+ });
+ assert.notEqual(logout.status, 503, "auth routes still work without core");
+});
+
test("web-ui /app-edit drops x-frame-options so its own frame-ancestors CSP can allow the app origin", async () => {
const editPage = await fetch(`${base}/app-edit?slug=demo`, { headers: { cookie: sessionCookie("U1") } });
assert.equal(editPage.status, 200);
@@ -697,3 +730,18 @@ test("Loop ingress forwards signed events and Google identity without a portal s
assert.equal((await fetch(`${base}/v1/loop-ingress/gmail`)).status, 404);
assert.equal((await fetch(`${base}/v1/loop-ingress/gmail/extra`, { method: "POST" })).status, 404);
});
+
+test("linked administrator impersonation follows the target", async () => {
+ const start = await fetch(`${base}/auth/impersonate?target=alice@acme`, {
+ method: "POST",
+ headers: { cookie: sessionCookie("U-admin-alias"), origin: PUBLIC },
+ });
+ assert.equal(start.status, 200);
+ const imp = (start.headers.get("set-cookie") ?? "").match(/portal_impersonate=([^;]+)/);
+ assert.ok(imp);
+ const web = await fetch(`${base}/api/x`, {
+ headers: { cookie: `${sessionCookie("U-admin-alias")}; portal_impersonate=${imp[1]}` },
+ });
+ const body = (await web.json()) as { cookie: string };
+ assert.match(body.cookie, /webuiuser=alice%40acme/);
+});
diff --git a/plugins/portal/test/trusted-entry-routes.test.ts b/plugins/portal/test/trusted-entry-routes.test.ts
index aec7c7333..a905dadb6 100644
--- a/plugins/portal/test/trusted-entry-routes.test.ts
+++ b/plugins/portal/test/trusted-entry-routes.test.ts
@@ -164,7 +164,7 @@ test("durable claim service failure cannot issue a session", async () => {
assert.equal(response.status, 400);
const html = await response.text();
assert.match(html, /href="\/auth\/trusted\/login"/);
- assert.equal(html.includes('href="/auth/login?provider=primary"'), preferenceEnabled);
+ assert.equal(html.includes('href="/auth/login?provider=primary"'), false);
assert.ok(!response.headers.getSetCookie().some((cookie) => cookie.startsWith("portal_session=")));
} finally {
claimAvailable = true;
diff --git a/plugins/web-ui/README.md b/plugins/web-ui/README.md
index e625a3635..232443a38 100644
--- a/plugins/web-ui/README.md
+++ b/plugins/web-ui/README.md
@@ -270,7 +270,7 @@ Gmail, Google Calendar, Google Drive, and Google Sheets artwork comes from
Set `WEB_UI_WELCOME_COHORT=F26` on the web surface to show the cohort welcome in a new user's empty chat. It replaces the automatic first agent turn for that deployment; ordinary chat starts when the user sends a message. The greeting uses the signed-in display name. The welcome remains above the messages in the earliest personal web conversation, including when reopened. It is selected from persisted session creation times. The champagne and soft flutter sequence replays on refresh only before the first message and respects reduced motion.
-The picker reads Composio's live catalog in usage order, omits apps that need no authorization, and searches the complete paginated catalog. Known services use local logos; remaining catalog logos use Composio's logo host. Selecting an app submits to the authenticated web surface and opens the provider's authorization link directly. Consent remains on the provider page. The Slack action opens the existing administrator setup page.
+The picker reads Composio's live catalog in usage order, omits apps that need no authorization, and searches the complete paginated catalog. Known services use local logos; remaining catalog logos use Composio's logo host. Selecting an app submits to the authenticated web surface and opens the provider's authorization link directly. Consent remains on the provider page. Slack is excluded from this picker. A dedicated Connect Slack card in onboarding and Settings authorizes the signed-in person’s Slack tools through Composio and links their verified Slack workspace identity to their existing web account. Installing the company bot remains a separate administrator action.
The core bridge accepts a verified portal identity and uses either that person's own `COMPOSIO_API_KEY` keychain entry or an enabled org service credential granted to them. Secrets never enter the browser. The agent skill reads `/v1/composio/identity` to use the same organization/person identity as the picker. A company project key retains Composio's existing project-wide access boundary; the identity selects accounts and does not isolate them from other holders of that key.
@@ -365,3 +365,5 @@ access failures do not retry on company credentials. Messages using a different
account queue separately instead of steering an existing run; an explicit steer
across accounts is refused. Organizations that already require individual accounts
continue to require them.
+
+The standalone `::link-slack-account{}` directive offers personal Slack account linking in a web reply. It shows the account card or linked status, requires the company bot to be installed first, and does not include the app picker. `::add-to-slack{}` remains the company installation trigger.
diff --git a/plugins/web-ui/server/composio-return.ts b/plugins/web-ui/server/composio-return.ts
index f5c1f6b64..64da8d815 100644
--- a/plugins/web-ui/server/composio-return.ts
+++ b/plugins/web-ui/server/composio-return.ts
@@ -9,6 +9,7 @@ export function composioCallbackUrl(publicUrl: string, returnTo: unknown, state:
target.origin !== base.origin ||
!(
target.pathname === `${prefix}/` ||
+ target.pathname === `${prefix}/settings` ||
new RegExp(`^${prefix.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}/s/[a-zA-Z0-9_-]+$`).test(target.pathname)
)
)
diff --git a/plugins/web-ui/server/index.ts b/plugins/web-ui/server/index.ts
index 906e79c49..7f7f0b560 100644
--- a/plugins/web-ui/server/index.ts
+++ b/plugins/web-ui/server/index.ts
@@ -1196,6 +1196,32 @@ const apiRoutes: readonly WebRoute[] = [
},
},
+ { method: "GET", path: "/api/composio/slack", handle: (c) => relayCore(c.res, "GET", "/v1/composio/slack") },
+ {
+ method: "POST",
+ path: "/api/composio/slack/authorize",
+ handle: async (c) => {
+ const body = await readJson<{ returnTo?: unknown; state?: unknown }>(c.req, c.res, false);
+ if (!body) return;
+ const callback = composioCallbackUrl(PUBLIC_URL, body.returnTo, body.state);
+ if (!callback) return json(c.res, 400, { error: "invalid_return_url" });
+ const url = new URL(callback);
+ url.searchParams.delete("composioReturn");
+ url.searchParams.set("slackReturn", String(body.state));
+ c.res.setHeader("Cache-Control", "no-store");
+ return relayCore(c.res, "POST", "/v1/composio/slack/authorize", JSON.stringify({ callbackUrl: url.href }));
+ },
+ },
+ {
+ method: "POST",
+ path: "/api/composio/slack/complete",
+ handle: async (c) => {
+ const body = await readJson<{ ticket?: unknown }>(c.req, c.res, false);
+ if (!body) return;
+ c.res.setHeader("Cache-Control", "no-store");
+ return relayCore(c.res, "POST", "/v1/composio/slack/complete", JSON.stringify({ ticket: body.ticket }));
+ },
+ },
{
method: "GET",
path: "/api/composio/toolkits",
diff --git a/plugins/web-ui/src/chat.ts b/plugins/web-ui/src/chat.ts
index c7701917f..38a1ff853 100644
--- a/plugins/web-ui/src/chat.ts
+++ b/plugins/web-ui/src/chat.ts
@@ -1889,7 +1889,7 @@ export function createChatSurface(
.me=${appState.me}
.base=${withBase("")}
.adminBase=${ADMIN_BASE}
- .widget=${part.type === "slack" ? "slack" : "apps"}
+ .widget=${part.type === "setup" ? "apps" : part.type}
.returnKey=${`reply:${message.timestamp}:${chunkIndex}:${partIndex}`}
.setupOnly=${true}
.animateWelcome=${false}
diff --git a/plugins/web-ui/src/onboarding-slack.ts b/plugins/web-ui/src/onboarding-slack.ts
index e68a80648..64c72836d 100644
--- a/plugins/web-ui/src/onboarding-slack.ts
+++ b/plugins/web-ui/src/onboarding-slack.ts
@@ -1,3 +1,4 @@
+import "./slack-account.css";
import { LitElement, html, nothing } from "lit";
import { ArrowUpRight, Check } from "lucide";
import { icon, slackMark } from "./ui";
@@ -63,11 +64,14 @@ export class OnboardingSlack extends LitElement {
} catch {
if (this.isConnected) {
this.connected = false;
- this.error = "Could not check Slack connection. Try again.";
+ this.error = "Could not check the Slack installation. Try again.";
}
} finally {
clearTimeout(timeout);
this.request = undefined;
+ this.dispatchEvent(
+ new window.CustomEvent("slack-installation-status", { detail: { connected: this.connected } }),
+ );
if (this.isConnected && !this.connected && Date.now() < this.pollUntil)
this.timer = setTimeout(this.refreshVisible, 5000);
}
@@ -77,7 +81,7 @@ export class OnboardingSlack extends LitElement {
if (this.busy || this.installAvailable === undefined) return;
const popup = window.open("", "_blank");
if (!popup) {
- this.error = "Allow a new tab to connect Slack, then try again.";
+ this.error = "Allow a new tab to install QM, then try again.";
return;
}
popup.opener = null;
@@ -122,10 +126,7 @@ export class OnboardingSlack extends LitElement {
if (this.installAvailable === undefined) label = "Checking Slack…";
return html`${
this.connected
- ? html`<div class="welcome-slack" role="status">
- ${slackMark(24)}<span><strong>Connected to Slack</strong><small>QM is ready in your workspace.</small></span
- >${icon(Check, 16)}
- </div>`
+ ? html`<div class="slack-connected" role="status">${icon(Check, 14)} QM added to Slack</div>`
: html`<button
class="welcome-slack"
type="button"
diff --git a/plugins/web-ui/src/onboarding-welcome.css b/plugins/web-ui/src/onboarding-welcome.css
index c762125e4..99dde8e6b 100644
--- a/plugins/web-ui/src/onboarding-welcome.css
+++ b/plugins/web-ui/src/onboarding-welcome.css
@@ -74,44 +74,6 @@ qm-onboarding-welcome {
opacity: 0;
z-index: -1;
}
-.welcome-slack {
- width: 100%;
- text-align: left;
- font: inherit;
- cursor: pointer;
- display: flex;
- align-items: center;
- gap: 12px;
- max-width: 480px;
- padding: 16px 18px;
- border: 1px solid var(--border);
- border-radius: 14px;
- color: var(--foreground);
- text-decoration: none;
- margin-bottom: 16px;
- background: var(--background);
-}
-.welcome-slack > span {
- flex: 1;
-}
-.welcome-slack strong {
- display: block;
- font-size: 14px;
- font-weight: 600;
-}
-.welcome-slack small {
- display: block;
- font-size: 12px;
- color: var(--muted-foreground);
- margin-top: 4px;
-}
-.welcome-slack:hover {
- background: var(--secondary);
-}
-.welcome-slack:focus-visible {
- outline: 2px solid var(--foreground);
- outline-offset: 3px;
-}
.welcome-load {
padding: 16px;
border: 1px solid var(--border);
diff --git a/plugins/web-ui/src/onboarding-welcome.ts b/plugins/web-ui/src/onboarding-welcome.ts
index 45aa0c412..439eb5fd6 100644
--- a/plugins/web-ui/src/onboarding-welcome.ts
+++ b/plugins/web-ui/src/onboarding-welcome.ts
@@ -13,6 +13,7 @@ import { mountConnectionPicker, type ConnectionService } from "./connection-pick
import type { Me } from "./shell-state";
import "./onboarding-welcome.css";
import "./onboarding-slack";
+import "./slack-account";
import {
connectionPreviewEnabled,
previewParameters,
@@ -46,13 +47,15 @@ export class OnboardingWelcome extends LitElement {
connectionOutcome: { state: true },
connections: { state: true },
connectionError: { state: true },
+ workspaceConnected: { state: true },
+ workspaceError: { state: true },
};
declare me: Me | null;
declare onMoreIdeas: (() => void) | undefined;
declare ideasDisabled: boolean;
declare animateWelcome: boolean;
declare setupOnly: boolean;
- declare widget: "all" | "apps" | "slack";
+ declare widget: "all" | "apps" | "slack" | "slack-account";
declare returnKey: string;
declare base: string;
declare adminBase: string;
@@ -62,13 +65,17 @@ export class OnboardingWelcome extends LitElement {
declare authorizationError: string;
private connections: Array<{ id: string; toolkit: string }> = [];
private connectionError = "";
+ private workspaceConnected: boolean | null = null;
+ private workspaceError = false;
private realReturn: ConnectionAttempt | null = null;
private connectionsController?: AbortController;
private restoreScrollTop: number | null = null;
private returnError = "";
private returnAccount = "";
private refreshConnections = () => {
- if (!this.preview && this.widget !== "slack" && !document.hidden) void this.loadConnections();
+ if (!document.hidden) void this.refreshWorkspace();
+ if (!this.preview && !["slack", "slack-account"].includes(this.widget) && !document.hidden)
+ void this.loadConnections();
};
private preview = connectionPreviewEnabled();
private consent: PreviewAttempt | null = null;
@@ -101,10 +108,28 @@ export class OnboardingWelcome extends LitElement {
private previewUser(): string {
return `${this.me?.org}:${this.me?.user}`;
}
+ private async refreshWorkspace(): Promise<void> {
+ if (this.widget === "apps" || (this.widget !== "slack-account" && this.me?.permissions?.includes("admin"))) return;
+ try {
+ const response = await fetch(`${this.base}api/composio/slack`, {
+ cache: "no-store",
+ signal: AbortSignal.timeout(10000),
+ });
+ if (!response.ok) throw Error("Slack status unavailable");
+ this.workspaceConnected = (await response.json()).workspaceInstalled === true;
+ this.workspaceError = false;
+ } catch {
+ this.workspaceConnected = null;
+ this.workspaceError = true;
+ }
+ }
protected firstUpdated(): void {
+ void this.refreshWorkspace();
const params = previewParameters();
const returnUrl =
- !this.preview && this.widget !== "slack" ? takeConnectionReturn(this.previewUser(), this.returnKey) : null;
+ !this.preview && !["slack", "slack-account"].includes(this.widget)
+ ? takeConnectionReturn(this.previewUser(), this.returnKey)
+ : null;
const realParams = returnUrl?.url.searchParams;
const returning = !this.preview && isConnectionReturn();
if (realParams) {
@@ -122,10 +147,10 @@ export class OnboardingWelcome extends LitElement {
for (const key of ["composioReturn", "status", "error", "connectedAccountId"]) clean.searchParams.delete(key);
history.replaceState(history.state, "", clean);
}
- if (!this.preview && this.widget !== "slack") {
+ if (!this.preview) {
window.addEventListener("focus", this.refreshConnections);
document.addEventListener("visibilitychange", this.refreshConnections);
- void this.loadConnections();
+ if (!["slack", "slack-account"].includes(this.widget)) void this.loadConnections();
}
if (this.preview) {
const visible = new URL(location.href);
@@ -170,7 +195,7 @@ export class OnboardingWelcome extends LitElement {
) {
this.classList.add("welcome-rolling");
}
- if (this.widget !== "slack") void this.loadCatalog();
+ if (!["slack", "slack-account"].includes(this.widget)) void this.loadCatalog();
}
private drawPicker(): void {
const target = this.querySelector<HTMLElement>(".welcome-picker");
@@ -256,9 +281,9 @@ export class OnboardingWelcome extends LitElement {
});
const result = await response.json();
if (!response.ok)
- throw new Error(result.message ?? "Composio is not available. Ask your administrator to check its setup.");
+ throw new Error(result.message ?? "App connections are unavailable right now. Please try again.");
for (const item of result.items as Array<{ id: string; name: string; description: string }>) {
- if (!services.some((service) => service.id === item.id))
+ if (item.id !== "slack" && !services.some((service) => service.id === item.id))
services.push({ ...item, popularity: 100000 - services.length });
}
cursor = typeof result.nextCursor === "string" ? result.nextCursor : "";
@@ -426,24 +451,43 @@ export class OnboardingWelcome extends LitElement {
}`
}
${
- this.widget !== "apps" && this.me?.permissions?.includes("admin")
+ !["apps", "slack-account"].includes(this.widget) && this.me?.permissions?.includes("admin")
? html`<qm-onboarding-slack
class="welcome-beat"
style=${`--welcome-delay:${cohort ? 3050 : 900}ms`}
.adminBase=${this.adminBase}
+ @slack-installation-status=${(event: CustomEvent<{ connected: boolean }>) => {
+ this.workspaceConnected = event.detail.connected;
+ }}
></qm-onboarding-slack>`
: nothing
}
+ ${this.widget === "slack-account" && this.workspaceError ? html`<p role="status">Could not check Slack setup. <button class="btn" @click=${() => void this.refreshWorkspace()}>Try again</button></p>` : nothing}
+ ${this.widget === "slack-account" && this.workspaceConnected === false ? html`<p role="status">QM needs to be added to your company’s Slack workspace before you can link your account. Ask an administrator to finish setup.</p>` : nothing}
+ <div class="welcome-beat" style=${`--welcome-delay:${cohort ? 3250 : 1100}ms`}>
+ ${this.workspaceConnected && this.widget !== "apps" && (["slack", "slack-account"].includes(this.widget) || (!this.loading && !this.error)) ? html`<qm-slack-account .user=${this.previewUser()}></qm-slack-account>` : nothing}
+ </div>
${
- this.widget === "slack"
+ ["slack", "slack-account"].includes(this.widget)
? nothing
- : html`<div class="welcome-beat" style=${`--welcome-delay:${cohort ? 3300 : 1100}ms`}>
+ : html`<div class="welcome-beat" style=${`--welcome-delay:${cohort ? 3450 : 1300}ms`}>
${this.loading ? html`<div class="welcome-load" role="status">Loading your available apps…</div>` : nothing}
${
this.error
? html`<div class="welcome-load">
+ <strong>Connect your apps</strong>
<p role="status">${this.error}</p>
- <button type="button" class="btn" @click=${() => void this.loadCatalog()}>Try again</button>
+ <button
+ type="button"
+ class="btn"
+ @click=${() => {
+ void this.loadCatalog();
+ void this.loadConnections();
+ void this.refreshWorkspace();
+ }}
+ >
+ Try again
+ </button>
</div>`
: nothing
}
@@ -461,7 +505,7 @@ export class OnboardingWelcome extends LitElement {
</div>`
: nothing
}
- ${this.connectionError ? html`<div class="welcome-connection-status" role="status">${this.connectionError} <button class="btn" @click=${() => void this.loadConnections()}>Check again</button></div>` : nothing}
+ ${this.connectionError && !this.error && !this.loading ? html`<div class="welcome-connection-status" role="status">${this.connectionError} <button class="btn" @click=${() => void this.loadConnections()}>Check again</button></div>` : nothing}
${!this.preview && this.connectionOutcome === "failed" ? html`<button class="btn" @click=${() => void this.loadConnections()}>Check again</button>` : nothing}
<div class="welcome-picker" ?inert=${Boolean(this.authorizing)}></div>
${
diff --git a/plugins/web-ui/src/settings.ts b/plugins/web-ui/src/settings.ts
index 892836cf4..564003b50 100644
--- a/plugins/web-ui/src/settings.ts
+++ b/plugins/web-ui/src/settings.ts
@@ -1,3 +1,4 @@
+import "./slack-account";
import { openModelConnectManager, type StatusResponse } from "./model-connect";
import { api } from "./core-bridge";
import { html, nothing, render, type TemplateResult } from "lit";
@@ -401,6 +402,9 @@ function settingsPane(): TemplateResult {
<div class="settings-group">
${aiAccountsRow()} ${themeRow()} ${sidebarSurfaceRow()} ${can("admin") ? adminRow() : nothing} ${aboutRow()}
${accountRow()}
+ <div class="settings-row settings-slack-account">
+ <qm-slack-account .user=${`${appState.me?.org}:${appState.me?.user}`}></qm-slack-account>
+ </div>
</div>
`;
}
diff --git a/plugins/web-ui/src/setup-widget.ts b/plugins/web-ui/src/setup-widget.ts
index 94f0706a0..5aa59939d 100644
--- a/plugins/web-ui/src/setup-widget.ts
+++ b/plugins/web-ui/src/setup-widget.ts
@@ -1,12 +1,20 @@
import { marked } from "marked";
-export type SetupContent = { type: "text"; text: string } | { type: "setup" | "slack" };
+export type SetupContent = { type: "text"; text: string } | { type: "setup" | "slack" | "slack-account" };
export function setupContent(text: string): SetupContent[] {
const parts: SetupContent[] = [];
for (const token of marked.lexer(text)) {
- if (token.type === "paragraph" && ["::connect-apps{}", "::add-to-slack{}"].includes(token.raw.trim())) {
- parts.push({ type: token.raw.trim() === "::add-to-slack{}" ? "slack" : "setup" });
+ if (
+ token.type === "paragraph" &&
+ ["::connect-apps{}", "::add-to-slack{}", "::link-slack-account{}"].includes(token.raw.trim())
+ ) {
+ const type = {
+ "::connect-apps{}": "setup",
+ "::add-to-slack{}": "slack",
+ "::link-slack-account{}": "slack-account",
+ } as const;
+ parts.push({ type: type[token.raw.trim() as keyof typeof type] });
} else {
const last = parts.at(-1);
if (last?.type === "text") last.text += token.raw;
diff --git a/plugins/web-ui/src/shell.css b/plugins/web-ui/src/shell.css
index 1124778f2..e69ee84df 100644
--- a/plugins/web-ui/src/shell.css
+++ b/plugins/web-ui/src/shell.css
@@ -1082,6 +1082,13 @@ a.chat-row-open {
.settings-row:last-child {
border-bottom: 0;
}
+.settings-slack-account qm-slack-account {
+ width: 100%;
+}
+.settings-slack-account .slack-connected,
+.settings-slack-account .welcome-slack {
+ margin-bottom: 0;
+}
.settings-row-copy {
flex: 1 1 260px;
min-width: 0;
diff --git a/plugins/web-ui/src/shell.ts b/plugins/web-ui/src/shell.ts
index 59e2e0b9d..f938afd97 100644
--- a/plugins/web-ui/src/shell.ts
+++ b/plugins/web-ui/src/shell.ts
@@ -1,5 +1,6 @@
import { initializeBrowserErrors, stopBrowserErrors } from "./browser-errors";
import { initializeAnalytics, capturePageview, stopAnalytics } from "./product-analytics";
+import { captureSlackReturn } from "./slack-account";
import { captureConnectionReturn } from "./connection-return";
import { renderModelConnectGate } from "./model-connect";
import { html, nothing, render, type TemplateResult } from "lit";
@@ -997,6 +998,7 @@ export async function bootSafely(): Promise<void> {
export async function boot(): Promise<void> {
captureConnectionReturn(location.href);
+ captureSlackReturn(location.href);
const params = new URLSearchParams(location.search);
const {
view: wanted,
diff --git a/plugins/web-ui/src/slack-account.css b/plugins/web-ui/src/slack-account.css
new file mode 100644
index 000000000..a2456ef9a
--- /dev/null
+++ b/plugins/web-ui/src/slack-account.css
@@ -0,0 +1,100 @@
+qm-slack-account,
+qm-onboarding-slack {
+ display: block;
+}
+
+.welcome-slack {
+ width: 100%;
+ text-align: left;
+ font: inherit;
+ cursor: pointer;
+ display: flex;
+ align-items: center;
+ gap: 12px;
+ max-width: 480px;
+ padding: 16px 18px;
+ border: 1px solid var(--border);
+ border-radius: 14px;
+ color: var(--foreground);
+ text-decoration: none;
+ margin-bottom: 16px;
+ background: var(--background);
+}
+.welcome-slack > span {
+ flex: 1;
+}
+.welcome-slack strong {
+ display: block;
+ font-size: 14px;
+ font-weight: 600;
+}
+.welcome-slack small {
+ display: block;
+ font-size: 12px;
+ color: var(--muted-foreground);
+ margin-top: 4px;
+}
+.welcome-slack:hover {
+ background: var(--secondary);
+}
+.welcome-slack:focus-visible {
+ outline: 2px solid var(--foreground);
+ outline-offset: 3px;
+}
+
+.slack-connected {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ color: var(--muted-foreground);
+ font-size: 12px;
+ margin: 0 0 16px;
+}
+.slack-connected svg {
+ color: var(--success);
+ flex: none;
+}
+.slack-link-icon {
+ position: relative;
+ width: 44px;
+ height: 39px;
+ flex: none;
+}
+.slack-link-person,
+.slack-link-service {
+ position: absolute;
+ display: grid;
+ place-items: center;
+ width: 27px;
+ height: 27px;
+ border: 1px solid var(--border);
+ border-radius: 50%;
+ background: var(--background);
+}
+.slack-link-person {
+ top: 0;
+ left: 0;
+ background: var(--secondary);
+ color: var(--foreground);
+}
+.slack-link-service {
+ top: 10px;
+ right: 0;
+}
+.slack-link-chain {
+ position: absolute;
+ display: grid;
+ place-items: center;
+ bottom: 0;
+ left: 10px;
+ width: 19px;
+ height: 16px;
+ border-radius: 8px;
+ background: var(--background);
+ color: var(--muted-foreground);
+ transform: rotate(-35deg);
+}
+.slack-account-error {
+ font-size: 12px;
+ margin: 0 0 12px;
+}
diff --git a/plugins/web-ui/src/slack-account.ts b/plugins/web-ui/src/slack-account.ts
new file mode 100644
index 000000000..8f137b964
--- /dev/null
+++ b/plugins/web-ui/src/slack-account.ts
@@ -0,0 +1,170 @@
+import { LitElement, html, nothing } from "lit";
+import { ArrowUpRight, Check, Link2, UserRound } from "lucide";
+import { icon, slackMark } from "./ui";
+import "./slack-account.css";
+import { withBase } from "./core-bridge";
+
+interface SlackAttempt {
+ user: string;
+ state: string;
+ ticket: string;
+ expiresAt: number;
+}
+
+let returnUrl: URL | null = null;
+
+export function captureSlackReturn(url: string): void {
+ const parsed = new URL(url);
+ returnUrl = parsed.searchParams.has("slackReturn") ? parsed : null;
+}
+
+export class SlackAccount extends LitElement {
+ static properties = {
+ user: {},
+ busy: { state: true },
+ error: { state: true },
+ connected: { state: true },
+ label: { state: true },
+ };
+ user = "";
+ private busy = false;
+ private error = "";
+ private connected = false;
+ private label = "";
+ private attempt: SlackAttempt | null = null;
+
+ protected createRenderRoot(): HTMLElement {
+ return this;
+ }
+
+ protected firstUpdated(): void {
+ const url = returnUrl ?? new URL(location.href);
+ returnUrl = null;
+ const state = url.searchParams.get("slackReturn");
+ try {
+ const saved = JSON.parse(sessionStorage.getItem("qm-slack-account") ?? "null") as SlackAttempt | null;
+ if (saved?.user === this.user && saved.expiresAt > Date.now()) this.attempt = saved;
+ } catch {
+ this.attempt = null;
+ }
+ if (state) {
+ const cancelled = url.searchParams.has("error");
+ for (const key of ["slackReturn", "status", "error", "connectedAccountId"]) url.searchParams.delete(key);
+ history.replaceState(history.state, "", url);
+ if (!this.attempt || this.attempt.state !== state) {
+ this.error =
+ "This connection expired or was started in another QM account. Sign in to the account you want to connect and try again.";
+ return;
+ }
+ if (cancelled) {
+ this.clearAttempt();
+ this.error = "Slack authorization was cancelled. Your QM account has not been linked.";
+ return;
+ }
+ void this.complete();
+ } else void this.status();
+ }
+
+ private clearAttempt(): void {
+ this.attempt = null;
+ sessionStorage.removeItem("qm-slack-account");
+ }
+
+ private async status(): Promise<void> {
+ try {
+ const response = await fetch(withBase("/api/composio/slack"), {
+ cache: "no-store",
+ signal: AbortSignal.timeout(10_000),
+ });
+ if (!response.ok) return;
+ const result = await response.json();
+ this.connected = result.connected === true;
+ this.label = [result.user, result.workspace].filter(Boolean).join(" · ");
+ } catch {
+ return;
+ }
+ }
+
+ private async connect(): Promise<void> {
+ if (this.busy) return;
+ this.busy = true;
+ this.error = "";
+ try {
+ const state = crypto.randomUUID();
+ const response = await fetch(withBase("/api/composio/slack/authorize"), {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({ state, returnTo: `${location.pathname}${location.search}` }),
+ signal: AbortSignal.timeout(30_000),
+ });
+ const result = await response.json();
+ if (!response.ok) throw Error(result.message ?? "Could not start Slack authorization. Please try again.");
+ const url = new URL(result.url);
+ if (
+ url.protocol !== "https:" ||
+ !["connect.composio.dev", "app.composio.dev"].includes(url.hostname) ||
+ url.username ||
+ url.password ||
+ typeof result.ticket !== "string"
+ )
+ throw Error("Could not verify the Slack authorization link.");
+ this.attempt = { user: this.user, state, ticket: result.ticket, expiresAt: Date.now() + 20 * 60_000 };
+ sessionStorage.setItem("qm-slack-account", JSON.stringify(this.attempt));
+ location.assign(url.href);
+ } catch (error) {
+ this.error = error instanceof Error ? error.message : "Could not connect Slack.";
+ } finally {
+ this.busy = false;
+ }
+ }
+
+ private async complete(): Promise<void> {
+ if (this.busy || !this.attempt) return;
+ this.busy = true;
+ this.error = "";
+ try {
+ const response = await fetch(withBase("/api/composio/slack/complete"), {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({ ticket: this.attempt.ticket }),
+ signal: AbortSignal.timeout(45_000),
+ });
+ const result = await response.json();
+ if (!response.ok) throw Error(result.message ?? "Could not verify your Slack account. Try again.");
+ this.connected = true;
+ this.label = [result.user, result.workspace].filter(Boolean).join(" · ");
+ this.clearAttempt();
+ } catch (error) {
+ this.error = error instanceof Error ? error.message : "Could not verify your Slack account.";
+ } finally {
+ this.busy = false;
+ }
+ }
+
+ protected render() {
+ return html`<section class="slack-account" aria-label="Your Slack account">
+ ${
+ this.connected
+ ? html`<div class="slack-connected" role="status">
+ ${icon(Check, 14)}<span>Your Slack account is linked${this.label ? ` · ${this.label}` : ""}</span>
+ </div>`
+ : html`<button class="welcome-slack" type="button" ?disabled=${this.busy} @click=${() => void this.connect()}>
+ <div class="slack-link-icon" aria-hidden="true">
+ <span class="slack-link-person">${icon(UserRound, 17)}</span>
+ <span class="slack-link-service">${slackMark(18)}</span>
+ <span class="slack-link-chain">${icon(Link2, 13)}</span>
+ </div>
+ <span
+ ><strong>${this.busy ? "Linking Slack…" : "Link your Slack account"}</strong
+ ><small>Let QM search Slack and take action on your behalf.</small></span
+ >
+ ${icon(ArrowUpRight, 16)}
+ </button>`
+ }
+ ${this.error ? html`<p class="slack-account-error" role="alert">${this.error}</p>` : nothing}
+ ${this.attempt && !this.connected ? html`<button class="btn" type="button" ?disabled=${this.busy} @click=${() => void this.complete()}>Check connection</button>` : nothing}
+ </section>`;
+ }
+}
+
+if (!customElements.get("qm-slack-account")) customElements.define("qm-slack-account", SlackAccount);
diff --git a/plugins/web-ui/test/composio-return.test.ts b/plugins/web-ui/test/composio-return.test.ts
index ae345fc6f..ecb820890 100644
--- a/plugins/web-ui/test/composio-return.test.ts
+++ b/plugins/web-ui/test/composio-return.test.ts
@@ -13,6 +13,10 @@ test("callbacks stay on the configured public origin and preserve the conversati
composioCallbackUrl("https://qm.example/web-ui", "/web-ui/s/chat", state),
`https://qm.example/web-ui/s/chat?composioReturn=${state}`,
);
+ assert.equal(
+ composioCallbackUrl("https://qm.example/web-ui", "/web-ui/settings", state),
+ `https://qm.example/web-ui/settings?composioReturn=${state}`,
+ );
for (const path of [
"https://evil.example/",
"//evil.example/",
diff --git a/plugins/web-ui/test/deep-link-boot-fixture.ts b/plugins/web-ui/test/deep-link-boot-fixture.ts
index eda1553cb..d6da98fe1 100644
--- a/plugins/web-ui/test/deep-link-boot-fixture.ts
+++ b/plugins/web-ui/test/deep-link-boot-fixture.ts
@@ -26,6 +26,7 @@ interface HarnessOptions {
savedCanvas?: boolean;
welcome?: boolean;
connectionReturn?: boolean;
+ slackReturn?: "success" | "expired" | "cancelled" | "wrong-account";
returnWidget?: string;
}
@@ -54,6 +55,16 @@ export async function harness(opts: HarnessOptions): Promise<Harness> {
},
}),
);
+ if (opts.slackReturn)
+ dom.window.sessionStorage.setItem(
+ "qm-slack-account",
+ JSON.stringify({
+ user: opts.slackReturn === "wrong-account" ? "test:other" : "test:tester",
+ state: "qa-slack-nonce",
+ ticket: "signed-test-ticket",
+ expiresAt: Date.now() + (opts.slackReturn === "expired" ? -60000 : 60000),
+ }),
+ );
let connectedItems: unknown[] = opts.connectionReturn ? [{ id: "ca_test", toolkit: "gmail" }] : [];
let connectedStatus = 200;
if (opts.connectionReturn)
@@ -93,6 +104,9 @@ export async function harness(opts: HarnessOptions): Promise<Harness> {
permissions: [],
...(opts.welcome ? { welcomeCohort: "F26" } : {}),
});
+ if (path === "/api/composio/slack/complete")
+ return Response.json({ connected: true, user: "Alice", workspace: "Acme" });
+ if (path === "/api/composio/slack") return Response.json({ connected: false, workspaceInstalled: true });
if (path.startsWith("/api/composio/connections"))
return Response.json({ items: connectedItems, nextCursor: null }, { status: connectedStatus });
if (path.startsWith("/api/composio/toolkits"))
diff --git a/plugins/web-ui/test/onboarding-slack.test.ts b/plugins/web-ui/test/onboarding-slack.test.ts
index a8682eed6..b32cd3885 100644
--- a/plugins/web-ui/test/onboarding-slack.test.ts
+++ b/plugins/web-ui/test/onboarding-slack.test.ts
@@ -37,7 +37,7 @@ test("Slack onboarding launches directly and verifies connection on return", asy
releaseStatus();
await settle();
assert.match(element.textContent ?? "", /Add to Slack/);
- assert.doesNotMatch(element.textContent ?? "", /Connected to Slack/);
+ assert.doesNotMatch(element.textContent ?? "", /QM added to Slack/);
let submitted: HTMLFormElement | undefined;
const popupDocument = document.implementation.createHTMLDocument();
const createElement = popupDocument.createElement.bind(popupDocument);
@@ -67,12 +67,14 @@ test("Slack onboarding launches directly and verifies connection on return", asy
assert.equal(submitted?.method, "post");
assert.equal(submitted?.action, "https://slack-service.example/install/launch?ticket=test");
assert.equal(popup.opener, null);
- assert.doesNotMatch(element.textContent ?? "", /Connected to Slack/);
+ assert.doesNotMatch(element.textContent ?? "", /QM added to Slack/);
status = { configured: true, setup: { connected: true } };
window.dispatchEvent(new window.Event("focus"));
await settle();
- assert.match(element.textContent ?? "", /Connected to Slack/);
+ assert.match(element.textContent ?? "", /QM added to Slack/);
assert.equal(element.querySelector("button"), null);
+ assert.ok(element.querySelector(".slack-connected"));
+ assert.equal(element.querySelector(".welcome-slack"), null);
for (const next of [
{ configured: true, setup: { connected: false } },
{ configured: true, setupUnavailable: true },
@@ -80,12 +82,12 @@ test("Slack onboarding launches directly and verifies connection on return", asy
status = { ...next, installAvailable: true };
window.dispatchEvent(new window.Event("focus"));
await settle();
- assert.doesNotMatch(element.textContent ?? "", /Connected to Slack/);
+ assert.doesNotMatch(element.textContent ?? "", /QM added to Slack/);
}
statusCode = 503;
window.dispatchEvent(new window.Event("focus"));
await settle();
- assert.match(element.textContent ?? "", /Could not check Slack connection/);
+ assert.match(element.textContent ?? "", /Could not check the Slack installation/);
window.open = () => null;
element.querySelector<HTMLButtonElement>(".welcome-slack")!.click();
await settle();
diff --git a/plugins/web-ui/test/onboarding-unavailable.test.ts b/plugins/web-ui/test/onboarding-unavailable.test.ts
new file mode 100644
index 000000000..b97630174
--- /dev/null
+++ b/plugins/web-ui/test/onboarding-unavailable.test.ts
@@ -0,0 +1,36 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+import { harness } from "./deep-link-boot-fixture.ts";
+
+test("unavailable connections produce one setup message and recover together", async () => {
+ const h = await harness({ path: "/", welcome: true });
+ const previousFetch = globalThis.fetch;
+ let unavailable = true;
+ globalThis.fetch = async (input, init) => {
+ if (unavailable && String(input).includes("/api/composio/"))
+ return Response.json(
+ { message: "App connections aren’t available for your account yet. Ask your administrator to enable them." },
+ { status: 403 },
+ );
+ return previousFetch(input, init);
+ };
+ try {
+ h.releaseSessions();
+ await h.boot();
+ for (let i = 0; i < 100 && !h.mainText().includes("App connections aren’t available"); i++)
+ await new Promise((resolve) => setTimeout(resolve, 10));
+ assert.equal(h.mainText().split("App connections aren’t available").length - 1, 1);
+ assert.doesNotMatch(h.mainText(), /Could not check connected apps|Link your Slack account/);
+ unavailable = false;
+ const retry = [...document.querySelectorAll<HTMLButtonElement>(".welcome-load button")][0];
+ assert.ok(retry);
+ retry.click();
+ for (let i = 0; i < 100 && !h.mainText().includes("Link your Slack account"); i++)
+ await new Promise((resolve) => setTimeout(resolve, 10));
+ assert.match(h.mainText(), /Link your Slack account/);
+ assert.doesNotMatch(h.mainText(), /App connections aren’t available|Could not check connected apps/);
+ } finally {
+ globalThis.fetch = previousFetch;
+ await h.close();
+ }
+});
diff --git a/plugins/web-ui/test/setup-widget.test.ts b/plugins/web-ui/test/setup-widget.test.ts
index bf20cebd6..2f16bb680 100644
--- a/plugins/web-ui/test/setup-widget.test.ts
+++ b/plugins/web-ui/test/setup-widget.test.ts
@@ -33,3 +33,18 @@ test("Slack and apps render independently", () => {
[{ type: "slack" }, { type: "setup" }],
);
});
+
+test("personal Slack linking has its own standalone widget trigger", () => {
+ assert.deepEqual(setupContent("::link-slack-account{}"), [{ type: "slack-account" }]);
+ for (const text of [
+ "`::link-slack-account{}`",
+ "> ::link-slack-account{}",
+ "Use ::link-slack-account{} here",
+ "```text\n::link-slack-account{}\n```",
+ "::link-slack-account{",
+ ])
+ assert.equal(
+ setupContent(text).some((part) => part.type === "slack-account"),
+ false,
+ );
+});
diff --git a/plugins/web-ui/test/slack-account-widget.test.ts b/plugins/web-ui/test/slack-account-widget.test.ts
new file mode 100644
index 000000000..85b7c8429
--- /dev/null
+++ b/plugins/web-ui/test/slack-account-widget.test.ts
@@ -0,0 +1,38 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+import { harness } from "./deep-link-boot-fixture.ts";
+
+test("recalled personal Slack widget renders independently and respects installation", async () => {
+ const h = await harness({ path: "/", welcome: true });
+ const previousFetch = globalThis.fetch;
+ let installed = true;
+ globalThis.fetch = async (input, init) =>
+ String(input) === "/api/composio/slack"
+ ? Response.json({ workspaceInstalled: installed, connected: false })
+ : previousFetch(input, init);
+ try {
+ h.releaseSessions();
+ await h.boot();
+ const widget = Object.assign(document.createElement("qm-onboarding-welcome"), {
+ me: { org: "test", user: "tester", permissions: ["admin"] },
+ widget: "slack-account",
+ setupOnly: true,
+ animateWelcome: false,
+ });
+ document.body.append(widget);
+ for (let i = 0; i < 100 && !widget.querySelector("qm-slack-account"); i++)
+ await new Promise((resolve) => setTimeout(resolve, 10));
+ assert.ok(widget.querySelector("qm-slack-account"));
+ assert.equal(widget.querySelector("qm-onboarding-slack"), null);
+ assert.equal(widget.querySelector(".welcome-picker"), null);
+ installed = false;
+ window.dispatchEvent(new window.Event("focus"));
+ for (let i = 0; i < 100 && widget.querySelector("qm-slack-account"); i++)
+ await new Promise((resolve) => setTimeout(resolve, 10));
+ assert.match(widget.textContent ?? "", /needs to be added/);
+ assert.equal(widget.querySelector("qm-slack-account"), null);
+ } finally {
+ globalThis.fetch = previousFetch;
+ await h.close();
+ }
+});
diff --git a/plugins/web-ui/test/slack-authorize-return.test.ts b/plugins/web-ui/test/slack-authorize-return.test.ts
new file mode 100644
index 000000000..2255a962b
--- /dev/null
+++ b/plugins/web-ui/test/slack-authorize-return.test.ts
@@ -0,0 +1,33 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+import { harness } from "./deep-link-boot-fixture.ts";
+
+test("Slack authorization returns to the page where the account card was clicked", async () => {
+ const h = await harness({ path: "/settings" });
+ const previousFetch = globalThis.fetch;
+ const returns: string[] = [];
+ globalThis.fetch = async (input, init) => {
+ if (String(input) === "/api/composio/slack/authorize") {
+ returns.push(JSON.parse(String(init?.body)).returnTo);
+ return Response.json({ message: "Test authorization stopped" }, { status: 503 });
+ }
+ return previousFetch(input, init);
+ };
+ try {
+ h.releaseSessions();
+ await h.boot();
+ const card = document.querySelector("qm-slack-account")!;
+ for (const path of ["/settings", "/s/sess-deep?layout=single"]) {
+ history.replaceState(null, "", path);
+ (card.querySelector("button") as HTMLButtonElement).click();
+ await (card as HTMLElement & { updateComplete: Promise<boolean> }).updateComplete;
+ for (let i = 0; i < 100 && card.querySelector("button")?.disabled; i++)
+ await new Promise((resolve) => setTimeout(resolve, 5));
+ assert.equal(returns.at(-1), path);
+ }
+ assert.equal(returns.length, 2);
+ } finally {
+ globalThis.fetch = previousFetch;
+ await h.close();
+ }
+});
diff --git a/plugins/web-ui/test/slack-onboarding-sequence.test.ts b/plugins/web-ui/test/slack-onboarding-sequence.test.ts
new file mode 100644
index 000000000..eaa1fa940
--- /dev/null
+++ b/plugins/web-ui/test/slack-onboarding-sequence.test.ts
@@ -0,0 +1,40 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+import { harness } from "./deep-link-boot-fixture.ts";
+
+test("personal Slack linking appears beneath the confirmed company installation", async () => {
+ const h = await harness({ path: "/", welcome: true });
+ const previousFetch = globalThis.fetch;
+ let installed = false;
+ globalThis.fetch = async (input, init) => {
+ if (String(input) === "/me")
+ return Response.json({ user: "tester", org: "test", welcomeCohort: "F26", permissions: ["admin"] });
+ if (String(input) === "/admin/api/slack-installation")
+ return Response.json({ configured: installed, installAvailable: true, setup: { connected: installed } });
+ return previousFetch(input, init);
+ };
+ try {
+ h.releaseSessions();
+ await h.boot();
+ for (let i = 0; i < 100 && !h.mainText().includes("Add to Slack"); i++)
+ await new Promise((resolve) => setTimeout(resolve, 10));
+ assert.match(h.mainText(), /Add to Slack/);
+ assert.equal(document.querySelector("qm-slack-account"), null);
+ installed = true;
+ window.dispatchEvent(new window.Event("focus"));
+ for (let i = 0; i < 100 && !h.mainText().includes("Link your Slack account"); i++)
+ await new Promise((resolve) => setTimeout(resolve, 10));
+ assert.match(h.mainText(), /QM added to Slack/);
+ assert.match(h.mainText(), /Link your Slack account/);
+ assert.ok(h.mainText().indexOf("QM added to Slack") < h.mainText().indexOf("Link your Slack account"));
+ assert.equal(document.querySelector("qm-onboarding-slack button.welcome-slack"), null);
+ installed = false;
+ window.dispatchEvent(new window.Event("focus"));
+ for (let i = 0; i < 100 && document.querySelector("qm-slack-account"); i++)
+ await new Promise((resolve) => setTimeout(resolve, 10));
+ assert.equal(document.querySelector("qm-slack-account"), null);
+ } finally {
+ globalThis.fetch = previousFetch;
+ await h.close();
+ }
+});
diff --git a/plugins/web-ui/test/slack-return-cancelled.test.ts b/plugins/web-ui/test/slack-return-cancelled.test.ts
new file mode 100644
index 000000000..a8dcc41dc
--- /dev/null
+++ b/plugins/web-ui/test/slack-return-cancelled.test.ts
@@ -0,0 +1,3 @@
+import { slackReturnTest } from "./slack-return-fixture.ts";
+
+slackReturnTest("cancelled");
diff --git a/plugins/web-ui/test/slack-return-expired.test.ts b/plugins/web-ui/test/slack-return-expired.test.ts
new file mode 100644
index 000000000..276e80047
--- /dev/null
+++ b/plugins/web-ui/test/slack-return-expired.test.ts
@@ -0,0 +1,3 @@
+import { slackReturnTest } from "./slack-return-fixture.ts";
+
+slackReturnTest("expired");
diff --git a/plugins/web-ui/test/slack-return-fixture.ts b/plugins/web-ui/test/slack-return-fixture.ts
new file mode 100644
index 000000000..62457f6f0
--- /dev/null
+++ b/plugins/web-ui/test/slack-return-fixture.ts
@@ -0,0 +1,37 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+import { harness } from "./deep-link-boot-fixture.ts";
+
+export function slackReturnTest(outcome: "success" | "expired" | "cancelled" | "wrong-account", session = false) {
+ test(`Slack callback survives real router boot: ${outcome}`, async () => {
+ const h = await harness({
+ welcome: session,
+ path: `${session ? "/s/sess-deep?" : "/settings?"}slackReturn=qa-slack-nonce${outcome === "cancelled" ? "&error=access_denied" : ""}`,
+ slackReturn: outcome,
+ });
+ try {
+ h.releaseSessions();
+ await h.boot();
+ const expected = {
+ success: /Your Slack account is linked/,
+ cancelled: /authorization was cancelled/,
+ expired: /expired or was started in another/,
+ "wrong-account": /expired or was started in another/,
+ }[outcome];
+ for (let i = 0; i < 100 && !expected.test(h.mainText()); i++)
+ await new Promise((resolve) => setTimeout(resolve, 5));
+ assert.match(h.mainText(), expected);
+ if (session) {
+ assert.equal(location.pathname, "/s/sess-deep");
+ assert.equal(h.visibleConversation().state.sessionId, "sess-deep");
+ }
+ assert.equal(
+ h.requests.some((p) => p.includes("/api/composio/slack/complete")),
+ outcome === "success",
+ );
+ if (outcome === "success") assert.equal(sessionStorage.getItem("qm-slack-account"), null);
+ } finally {
+ await h.close();
+ }
+ });
+}
diff --git a/plugins/web-ui/test/slack-return-session.test.ts b/plugins/web-ui/test/slack-return-session.test.ts
new file mode 100644
index 000000000..b609092a4
--- /dev/null
+++ b/plugins/web-ui/test/slack-return-session.test.ts
@@ -0,0 +1,3 @@
+import { slackReturnTest } from "./slack-return-fixture.ts";
+
+slackReturnTest("success", true);
diff --git a/plugins/web-ui/test/slack-return-success.test.ts b/plugins/web-ui/test/slack-return-success.test.ts
new file mode 100644
index 000000000..ac127779e
--- /dev/null
+++ b/plugins/web-ui/test/slack-return-success.test.ts
@@ -0,0 +1,3 @@
+import { slackReturnTest } from "./slack-return-fixture.ts";
+
+slackReturnTest("success");
diff --git a/plugins/web-ui/test/slack-return-wrong-account.test.ts b/plugins/web-ui/test/slack-return-wrong-account.test.ts
new file mode 100644
index 000000000..8dad889a1
--- /dev/null
+++ b/plugins/web-ui/test/slack-return-wrong-account.test.ts
@@ -0,0 +1,3 @@
+import { slackReturnTest } from "./slack-return-fixture.ts";
+
+slackReturnTest("wrong-account");
diff --git a/skills-seed/composio/SKILL.md b/skills-seed/composio/SKILL.md
index ed9abb615..26387c602 100644
--- a/skills-seed/composio/SKILL.md
+++ b/skills-seed/composio/SKILL.md
@@ -55,3 +55,7 @@ Automatic file transfer is disabled. Upload/download only explicit authorized fi
If project-level callback identity verification is enabled, consent must return through that project's existing authenticated verifier. Do not redeem `session_uri` from the agent with a self-asserted user ID, disable verification, or fabricate callback success. This skill does not implement a verifier; ask the operator to resolve missing setup.
When no authorized Composio credential is available, use the existing direct app skill. A permission denial is not permission to switch accounts or bypass approval. Composio's personal Slack connection does not install the separate QM bot.
+
+For Slack authorization, offer `::link-slack-account{}` in web chat, signed into the existing web account. From Slack, direct them to **Link your Slack account** in QM web Settings (`/?view=settings`). This also links the Slack identity. Do not use a generic Composio consent link for Slack. Installing the company bot is a separate action.
+
+In web chat, offer personal Slack account linking with `::link-slack-account{}` as a standalone paragraph, outside code fences and quotations. Use it when someone wants Slack search, actions on their behalf, or access to their existing web connectors from Slack. This shows the personal linking card and its verified connection status, without the general app picker. Company bot installation must be completed first; use `::add-to-slack{}` for that separate administrator step. In Slack, send them to QM web Settings while signed into their existing web account; web widget directives do not render in Slack.
diff --git a/skills-seed/connect-apps/SKILL.md b/skills-seed/connect-apps/SKILL.md
index 9e4f86659..61912b38f 100644
--- a/skills-seed/connect-apps/SKILL.md
+++ b/skills-seed/connect-apps/SKILL.md
@@ -26,3 +26,9 @@ curl -sS -X POST "$AGENT_API_URL/v1/connectors/oauth/consent/mint" \
direct OAuth path or re-send old links; this does not establish that every access path is unavailable.
- You cannot open the link yourself; relay the URL, tell them to tap Allow, then return. After they
connect, the app's tools/skills work in your 1:1s with them.
+
+## Connect a personal Slack account
+
+When someone asks to connect Slack or use their existing web connectors from Slack, offer the personal Slack linking widget in web chat, or direct them to QM web Settings (`/?view=settings`) and **Link your Slack account** from Slack. They must sign in with their existing web account before connecting. This authorizes personal Slack access and links their verified Slack identity to that QM account. Workspace bot installation is separate. Do not create a generic Composio Slack link or infer identity from matching emails.
+
+In web chat, offer personal Slack account linking with `::link-slack-account{}` as a standalone paragraph, outside code fences and quotations. Use it when someone wants Slack search, actions on their behalf, or access to their existing web connectors from Slack. This shows the personal linking card and its verified connection status, without the general app picker. Company bot installation must be completed first; use `::add-to-slack{}` for that separate administrator step. In Slack, send them to QM web Settings while signed into their existing web account; web widget directives do not render in Slack.
diff --git a/src/admin/users.ts b/src/admin/users.ts
index dfa9b88c1..e87673fe8 100644
--- a/src/admin/users.ts
+++ b/src/admin/users.ts
@@ -1,6 +1,7 @@
import type { AdminGrant } from "./admin-grant-store.ts";
import { adminStatusFromGrants, type AdminStatus } from "./admin-service.ts";
import { forEachAttributedTurn, type AttributionInput } from "./attribution.ts";
+import { canonicalPerson } from "../directory/person.ts";
export interface AdminUserRow {
principalId: string;
@@ -26,18 +27,20 @@ export function computeUsers(input: UsersInput): AdminUserRow[] {
forEachAttributedTurn(input, {
onWindow(sessionId, w) {
- const set = sessionsByUser.get(w.principalId);
+ const principalId = canonicalPerson(w.principalId);
+ const set = sessionsByUser.get(principalId);
if (set) set.add(sessionId);
- else sessionsByUser.set(w.principalId, new Set([sessionId]));
- bumpLastSeen(w.principalId, w.validFrom);
+ else sessionsByUser.set(principalId, new Set([sessionId]));
+ bumpLastSeen(principalId, w.validFrom);
},
onTurn(w, turn) {
- turnsByUser.set(w.principalId, (turnsByUser.get(w.principalId) ?? 0) + turn.turns);
- bumpLastSeen(w.principalId, turn.lastAt);
+ const principalId = canonicalPerson(w.principalId);
+ turnsByUser.set(principalId, (turnsByUser.get(principalId) ?? 0) + turn.turns);
+ bumpLastSeen(principalId, turn.lastAt);
},
});
- const ids = new Set<string>([...sessionsByUser.keys(), ...grants.map((g) => g.principalId)]);
+ const ids = new Set<string>([...sessionsByUser.keys(), ...grants.map((g) => canonicalPerson(g.principalId))]);
return [...ids]
.map((principalId) => ({
principalId,
diff --git a/src/api/agent-api-catalog.ts b/src/api/agent-api-catalog.ts
index 72a1e5912..ccde78bfc 100644
--- a/src/api/agent-api-catalog.ts
+++ b/src/api/agent-api-catalog.ts
@@ -760,7 +760,7 @@ const FAMILIES: AgentApiFamily[] = [
match: (_m, p) => p.startsWith("/v1/admin/"),
when: (v) => v.isAdmin && livePersonCapability(v.claims),
guidance:
- "Admin plane: you act AS this org admin — live-authorized per call, audited under their name; confirm before any mutation (bodies/params in the admin skill). Enforced limits: content reads require a DM or effective Open sharing for the live admin (organization, personal, and conversation restrictions all apply); configuration mutations work anywhere; admin grant changes and impersonation are portal-only. Open admin reads can expose private data to the conversation; retrieve and report only what the request needs.",
+ "Admin plane: you act AS this org admin — live-authorized per call, audited under their name; confirm before any mutation (bodies/params in the admin skill). Enforced limits: content reads require a DM or effective Open sharing for the live admin (organization, personal, and conversation restrictions all apply); configuration mutations work anywhere; admin grant changes, impersonation, and identity links are portal-only. Open admin reads can expose private data to the conversation; retrieve and report only what the request needs.",
routes: [
{ method: "GET", path: "/v1/admin/whoami", summary: "this user's admin status" },
{
diff --git a/src/api/deps.ts b/src/api/deps.ts
index 1cd30b5e2..5c884d600 100644
--- a/src/api/deps.ts
+++ b/src/api/deps.ts
@@ -1,3 +1,4 @@
+import type { DurableMap } from "../persistence/durable-map.ts";
import type { BackgroundOwnershipStore } from "../runs/background-ownership.ts";
import type { LoopIngressService } from "../loops/ingress.ts";
import type { createSuggestedActivityService } from "../suggestions/activities.ts";
@@ -43,6 +44,7 @@ import type { EnvironmentStore } from "../environments/environment-store.ts";
import type { Scheduler } from "../cron/scheduler.ts";
import type { WebhookReceiver } from "../webhooks/webhook-receiver.ts";
import type { IdentityService } from "../identity/identity-service.ts";
+import type { PrincipalLinkService } from "../identity/principal-links.ts";
import type { DeviceFlowCutoverStore } from "../credentials/device-flow-cutover.ts";
import type { FeatureFlagStore } from "../feature-flags.ts";
import type {
@@ -72,7 +74,10 @@ import type { RateLimiter } from "../ratelimit/rate-limiter.ts";
import type { AdvisoryLock } from "../persistence/advisory-lock.ts";
import type { SlackInstallationStore, SlackSocketAppIdReader } from "../surfaces/slack-installation.ts";
+import type { SlackAccountLink } from "./routes/composio.ts";
+
export interface ServerDeps {
+ slackAccounts?: DurableMap<SlackAccountLink>;
composioFetch?: typeof fetch;
suggestedActivities?: ReturnType<typeof createSuggestedActivityService>;
production?: boolean;
@@ -180,6 +185,7 @@ export interface ServerDeps {
webhookReceiver?: WebhookReceiver;
loopIngress?: LoopIngressService;
identity?: IdentityService;
+ principalLinks?: PrincipalLinkService;
keychain?: Keychain;
serviceCreds?: ServiceCredentialStore;
deliveries?: DeliveryStore;
diff --git a/src/api/routes/admin.ts b/src/api/routes/admin.ts
index df4628b18..cfcc5eab1 100644
--- a/src/api/routes/admin.ts
+++ b/src/api/routes/admin.ts
@@ -48,6 +48,7 @@ import { deleteModelProvider, getModelProviders, putModelProvider } from "./admi
import { deleteCustomProvider, getCustomProviders, putCustomProvider } from "./admin/custom-providers.ts";
import { deleteMcpServer, getMcpServers, putMcpServer } from "./admin/mcp-servers.ts";
import { listSecurityFlags, releaseSecurityTaint } from "./admin/security.ts";
+import { createPrincipalLink, deletePrincipalLink, listPrincipalLinks } from "./admin/principal-links.ts";
const timed =
(handle: (ctx: ApiCtx) => void | Promise<void>) =>
@@ -148,6 +149,9 @@ const routes: ReadonlyArray<Route<ApiCtx>> = [
{ method: "GET", path: "/v1/admin/users/:principalId", auth: "either", handle: getUserDetail },
{ method: "PUT", path: "/v1/admin/users/:principalId/onboarding", auth: "either", handle: setUserOnboarding },
{ method: "POST", path: "/v1/admin/users/:principalId/reset", auth: "either", handle: resetUserToBrandNew },
+ { method: "GET", path: "/v1/admin/principal-links", auth: "either", handle: listPrincipalLinks },
+ { method: "POST", path: "/v1/admin/principal-links", auth: "either", handle: createPrincipalLink },
+ { method: "DELETE", path: "/v1/admin/principal-links/:principalId", auth: "either", handle: deletePrincipalLink },
{ method: "POST", path: "/v1/admin/grants", auth: "either", handle: createAdminGrant },
{ method: "DELETE", path: "/v1/admin/grants/:principalId", auth: "either", handle: revokeAdminGrant },
{ method: "POST", path: "/v1/admin/external-users", auth: "either", handle: inviteExternalUser },
diff --git a/src/api/routes/admin/principal-links.ts b/src/api/routes/admin/principal-links.ts
new file mode 100644
index 000000000..70a2273ce
--- /dev/null
+++ b/src/api/routes/admin/principal-links.ts
@@ -0,0 +1,77 @@
+import { PrincipalLinkError } from "../../../identity/principal-links.ts";
+import { adminStatusFromGrants } from "../../../admin/admin-service.ts";
+import { samePerson } from "../../../directory/person.ts";
+import { sendJson } from "../../http.ts";
+import { audit, authorizeAdmin, isObj, orgScope } from "../shared.ts";
+import { type ApiCtx } from "../route.ts";
+
+const DIRECTORY_MEMBER_IS_CANONICAL =
+ "that principal is a directory member; directory members stay canonical, so link the other identity to it instead";
+const ADMIN_SIGN_IN_NEEDS_ADMIN_CANONICAL =
+ "that sign-in holds an org admin grant; a link may not make another principal an admin, so grant the canonical principal first or revoke it";
+
+async function directoryMember(deps: ApiCtx["deps"], id: string): Promise<boolean> {
+ if (!deps.directory) return false;
+ const trimmed = id.trim();
+ return (await deps.directory.list()).some((m) => samePerson(m.principalId, trimmed) || m.slackId === trimmed);
+}
+
+export async function listPrincipalLinks(ctx: ApiCtx): Promise<void> {
+ const { res, deps } = ctx;
+ if (!deps.principalLinks) return sendJson(res, 404, { error: "not_found" });
+ const actor = await authorizeAdmin(ctx, orgScope(deps));
+ if (!actor) return;
+ return sendJson(res, 200, { links: await deps.principalLinks.list() });
+}
+
+export async function createPrincipalLink(ctx: ApiCtx): Promise<void> {
+ const { res, deps, body } = ctx;
+ if (!deps.principalLinks) return sendJson(res, 404, { error: "not_found" });
+ const actor = await authorizeAdmin(ctx, orgScope(deps));
+ if (!actor) return;
+ const b = isObj(body) ? body : {};
+ if (typeof b.principalId === "string" && (await directoryMember(deps, b.principalId)))
+ return sendJson(res, 400, { error: "link_failed", message: DIRECTORY_MEMBER_IS_CANONICAL });
+ if (typeof b.principalId === "string" && typeof b.canonicalId === "string" && deps.admin) {
+ const grants = await deps.admin.listGrants();
+ if (adminStatusFromGrants(grants, b.principalId).isAdmin && !adminStatusFromGrants(grants, b.canonicalId).isAdmin)
+ return sendJson(res, 400, { error: "link_failed", message: ADMIN_SIGN_IN_NEEDS_ADMIN_CANONICAL });
+ }
+ try {
+ const link = await deps.principalLinks.link({
+ principalId: b.principalId,
+ canonicalId: b.canonicalId,
+ evidence: b.evidence,
+ linkedBy: actor.id,
+ });
+ await deps.identity?.refresh(true);
+ audit(deps, {
+ principalId: actor.id,
+ action: "principal_link.create",
+ resource: `${link.principalId} -> ${link.canonicalId}`,
+ scopeLabel: orgScope(deps),
+ });
+ return sendJson(res, 200, { ok: true, link });
+ } catch (error) {
+ if (error instanceof PrincipalLinkError)
+ return sendJson(res, error.status, { error: "link_failed", message: error.message });
+ throw error;
+ }
+}
+
+export async function deletePrincipalLink(ctx: ApiCtx): Promise<void> {
+ const { res, deps, params } = ctx;
+ if (!deps.principalLinks) return sendJson(res, 404, { error: "not_found" });
+ const actor = await authorizeAdmin(ctx, orgScope(deps));
+ if (!actor) return;
+ const link = await deps.principalLinks.unlink(params.principalId!);
+ if (!link) return sendJson(res, 404, { error: "not_found" });
+ await deps.identity?.refresh(true);
+ audit(deps, {
+ principalId: actor.id,
+ action: "principal_link.delete",
+ resource: `${link.principalId} -> ${link.canonicalId}`,
+ scopeLabel: orgScope(deps),
+ });
+ return sendJson(res, 200, { ok: true, link });
+}
diff --git a/src/api/routes/composio.ts b/src/api/routes/composio.ts
index 835769d9e..c6909b882 100644
--- a/src/api/routes/composio.ts
+++ b/src/api/routes/composio.ts
@@ -1,3 +1,6 @@
+import { mintSignedPayload, verifySignedPayload } from "../../auth/signed-token.ts";
+import { canonicalPerson, samePerson } from "../../directory/person.ts";
+import { PrincipalLinkError } from "../../identity/principal-links.ts";
import { createHash } from "node:crypto";
import { scopeId } from "../../types.ts";
import { parseRef } from "../../acl/resource-ref.ts";
@@ -55,7 +58,7 @@ async function credential(ctx: ApiCtx): Promise<{ key: string; principal: string
if (records.length !== 1) {
sendJson(ctx.res, records.length ? 409 : 403, {
error: "composio_unavailable",
- message: "Composio is not available to this account. Ask your administrator to check its credential grant.",
+ message: "App connections aren’t available for your account yet. Ask your administrator to enable them.",
});
return null;
}
@@ -116,10 +119,12 @@ async function catalog(ctx: ApiCtx): Promise<void> {
}
}
-async function authorize(ctx: ApiCtx): Promise<void> {
+async function authorize(ctx: ApiCtx, linkSlack = false): Promise<void> {
const access = await credential(ctx);
if (!access) return;
- const toolkit = (ctx.body as { toolkit?: unknown } | null)?.toolkit;
+ const toolkit = linkSlack ? "slack" : (ctx.body as { toolkit?: unknown } | null)?.toolkit;
+ if (linkSlack && (!ctx.deps.signingSecret || !ctx.deps.principalLinks || ctx.actor?.imp))
+ return sendJson(ctx.res, 403, { error: "link_unavailable", message: "Sign in as yourself to connect Slack." });
if (typeof toolkit !== "string" || !/^[a-z0-9_-]{1,100}$/.test(toolkit))
return sendJson(ctx.res, 400, { error: "invalid_toolkit" });
const callbackUrl = (ctx.body as { callbackUrl?: unknown }).callbackUrl;
@@ -172,7 +177,23 @@ async function authorize(ctx: ApiCtx): Promise<void> {
resource: toolkit,
scopeLabel: scopeId("personal", access.principal),
});
- return sendJson(ctx.res, 200, { url: url.href, accountId: link.connected_account_id });
+ const ticket = linkSlack
+ ? await mintSignedPayload(
+ {
+ purpose: "slack-account-link",
+ principal: access.principal,
+ org: orgId(),
+ accountId: link.connected_account_id,
+ exp: Date.now() + 20 * 60_000,
+ },
+ ctx.deps.signingSecret!,
+ )
+ : undefined;
+ return sendJson(ctx.res, 200, {
+ url: url.href,
+ accountId: link.connected_account_id,
+ ...(ticket ? { ticket } : {}),
+ });
} catch {
return sendJson(ctx.res, 502, {
error: "composio_authorization_failed",
@@ -226,7 +247,212 @@ async function identity(ctx: ApiCtx): Promise<void> {
return sendJson(ctx.res, 200, { userId: composioUserId(orgId(), principal) });
}
+export interface SlackAccountLink {
+ principalId: string;
+ accountId: string;
+ memberId: string;
+ userId: string;
+ teamId: string;
+ user: string;
+ workspace: string;
+}
+
+async function slackStatus(ctx: ApiCtx): Promise<void> {
+ const access = await credential(ctx);
+ if (!access) return;
+ const installation = await ctx.deps.slackInstallation?.get();
+ const workspaceInstalled = Boolean(installation?.botToken || ctx.deps.slackEnvBotToken);
+ const record = await ctx.deps.slackAccounts?.get(access.principal);
+ ctx.res.setHeader("Cache-Control", "no-store");
+ if (!record || !samePerson(record.memberId, access.principal))
+ return sendJson(ctx.res, 200, { connected: false, workspaceInstalled });
+ try {
+ const account = await request(ctx, access.key, `/connected_accounts/${encodeURIComponent(record.accountId)}`);
+ const toolkit = account.toolkit as { slug?: string } | undefined;
+ const connected =
+ account.id === record.accountId &&
+ account.user_id === composioUserId(orgId(), access.principal) &&
+ toolkit?.slug === "slack" &&
+ account.status === "ACTIVE" &&
+ account.is_disabled !== true;
+ return sendJson(ctx.res, 200, { connected, workspaceInstalled, user: record.user, workspace: record.workspace });
+ } catch {
+ return sendJson(ctx.res, 502, { error: "status_unavailable" });
+ }
+}
+
+async function completeSlack(ctx: ApiCtx): Promise<void> {
+ const access = await credential(ctx);
+ if (!access) return;
+ const { deps, res } = ctx;
+ if (!deps.signingSecret || !deps.principalLinks || !deps.directory || !deps.slackAccounts || ctx.actor?.imp)
+ return sendJson(res, 403, { error: "link_unavailable", message: "Sign in as yourself to connect Slack." });
+ const ticket = (ctx.body as { ticket?: unknown } | null)?.ticket;
+ const proof =
+ typeof ticket === "string"
+ ? ((await verifySignedPayload(ticket, deps.signingSecret)) as Record<string, unknown> | null)
+ : null;
+ if (
+ !proof ||
+ proof.purpose !== "slack-account-link" ||
+ proof.org !== orgId() ||
+ proof.principal !== access.principal ||
+ typeof proof.exp !== "number" ||
+ proof.exp <= Date.now() ||
+ typeof proof.accountId !== "string" ||
+ !/^ca_[a-zA-Z0-9_-]+$/.test(proof.accountId)
+ )
+ return sendJson(res, 400, {
+ error: "invalid_link",
+ message:
+ "This connection expired or belongs to another QM account. Start again from the account you want to connect.",
+ });
+ try {
+ const account = await request(ctx, access.key, `/connected_accounts/${encodeURIComponent(proof.accountId)}`);
+ const toolkit = account.toolkit as { slug?: string } | undefined;
+ if (
+ account.id !== proof.accountId ||
+ account.user_id !== composioUserId(orgId(), access.principal) ||
+ toolkit?.slug !== "slack" ||
+ account.is_disabled === true
+ )
+ return sendJson(res, 403, {
+ error: "wrong_account",
+ message: "This Slack connection does not belong to your QM account.",
+ });
+ if (account.status !== "ACTIVE")
+ return sendJson(res, 409, {
+ error: "not_connected",
+ message: "Slack authorization has not completed. Try again after approving access.",
+ });
+ const result = await request(ctx, access.key, "/tools/execute/proxy", {
+ connected_account_id: proof.accountId,
+ endpoint: "https://slack.com/api/auth.test",
+ method: "GET",
+ });
+ const slack = result.data as
+ { ok?: boolean; user_id?: string; team_id?: string; bot_id?: string; user?: string; team?: string } | undefined;
+ if (
+ slack?.ok !== true ||
+ slack.bot_id ||
+ !/^[UW][A-Z0-9]+$/.test(slack.user_id ?? "") ||
+ !/^T[A-Z0-9]+$/.test(slack.team_id ?? "")
+ )
+ return sendJson(res, 400, {
+ error: "not_user",
+ message: "Connect your personal Slack account, not a bot account.",
+ });
+ const installation = await deps.slackInstallation?.get();
+ let teamId = installation?.teamId;
+ const botToken = installation?.botToken ?? deps.slackEnvBotToken;
+ if (!teamId && botToken) {
+ const response = await (deps.slackInstallationFetch ?? fetch)("https://slack.com/api/auth.test", {
+ method: "POST",
+ headers: { authorization: `Bearer ${botToken}` },
+ signal: AbortSignal.timeout(10_000),
+ redirect: "error",
+ });
+ const bot = (await response.json()) as { ok?: boolean; team_id?: string };
+ if (response.ok && bot.ok) teamId = bot.team_id;
+ }
+ if (!teamId)
+ return sendJson(res, 409, {
+ error: "workspace_unavailable",
+ message:
+ "Slack access is authorized. Ask an administrator to finish installing the company bot, then check the connection again.",
+ });
+ if (teamId !== slack.team_id)
+ return sendJson(res, 409, {
+ error: "wrong_workspace",
+ message: "Connect the Slack workspace where your company uses QM.",
+ });
+ const members = (await deps.directory.list()).filter(
+ (m) => m.slackId === slack.user_id || m.principalId === slack.user_id,
+ );
+ if (members.length !== 1 || members[0]!.type !== "internal")
+ return sendJson(res, 409, {
+ error: "member_unavailable",
+ message:
+ "QM could not find your company Slack membership. Message the bot and try again, or ask your administrator for help.",
+ });
+ const member = members[0]!;
+ await deps.identity?.refresh(true);
+ if (!(await activePrincipal(deps, member.principalId)) || !(await activePrincipal(deps, access.principal)))
+ return sendJson(res, 403, {
+ error: "inactive_account",
+ message: "An account is inactive. Ask your administrator for help.",
+ });
+ if (!samePerson(member.principalId, access.principal)) {
+ const existingCredentials = (await deps.keychain?.listByOwner(member.principalId)) ?? [];
+ const projectKeys = new Set([access.key]);
+ const companyCredentials = (await deps.serviceCreds?.listServiceCredentials(scopeId("org", orgId()))) ?? [];
+ for (const candidate of companyCredentials) {
+ if (candidate.envKey !== "COMPOSIO_API_KEY" || !candidate.hasSecret) continue;
+ const material = await deps.serviceCreds!.getServiceCredentialSecret(scopeId("org", orgId()), candidate.slug);
+ if (!material?.secret) throw Error("Could not inspect existing connections");
+ projectKeys.add(material.secret);
+ }
+ let hasPriorAccounts = false;
+ for (const projectKey of projectKeys) {
+ const priorAccounts = await request(
+ ctx,
+ projectKey,
+ `/connected_accounts?${new URLSearchParams({ user_ids: composioUserId(orgId(), member.principalId), limit: "1" })}`,
+ );
+ if (!Array.isArray(priorAccounts.items)) throw Error("Could not inspect existing connections");
+ hasPriorAccounts ||= priorAccounts.items.length > 0;
+ }
+ if (existingCredentials.length || hasPriorAccounts)
+ return sendJson(res, 409, {
+ error: "established_account",
+ message:
+ "Your Slack identity already has connected services. Ask your administrator to combine these accounts so those connections are preserved.",
+ });
+
+ if (canonicalPerson(member.principalId) !== member.principalId)
+ return sendJson(res, 409, {
+ error: "already_linked",
+ message: "This Slack identity is connected to another QM account. Ask your administrator for help.",
+ });
+ await deps.principalLinks.link({
+ principalId: member.principalId,
+ canonicalId: access.principal,
+ evidence: `Slack OAuth user ${slack.user_id} in workspace ${slack.team_id}, connection ${proof.accountId}`,
+ linkedBy: access.principal,
+ });
+ await deps.identity?.refresh(true);
+ audit(deps, {
+ principalId: access.principal,
+ action: "principal_link.create",
+ resource: `${member.principalId} -> ${access.principal}`,
+ scopeLabel: scopeId("org", orgId()),
+ });
+ }
+ await deps.slackAccounts.put(access.principal, {
+ principalId: access.principal,
+ accountId: proof.accountId,
+ memberId: member.principalId,
+ userId: slack.user_id!,
+ teamId: slack.team_id!,
+ user: slack.user ?? member.displayName,
+ workspace: slack.team ?? slack.team_id!,
+ });
+ return sendJson(res, 200, { connected: true, user: slack.user, workspace: slack.team });
+ } catch (error) {
+ return sendJson(res, error instanceof PrincipalLinkError ? 409 : 502, {
+ error: "slack_link_failed",
+ message:
+ error instanceof PrincipalLinkError
+ ? "These accounts need an administrator's help to connect. Your existing data has not been moved."
+ : "Could not verify the Slack connection. Please try again.",
+ });
+ }
+}
+
export const composioRoutes: ReadonlyArray<Route<ApiCtx>> = [
+ { method: "GET", path: "/v1/composio/slack", auth: "source", handle: slackStatus },
+ { method: "POST", path: "/v1/composio/slack/authorize", auth: "source", handle: (ctx) => authorize(ctx, true) },
+ { method: "POST", path: "/v1/composio/slack/complete", auth: "source", handle: completeSlack },
{ method: "GET", path: "/v1/composio/connections", auth: "source", handle: connections },
{ method: "GET", path: "/v1/composio/toolkits", auth: "source", handle: catalog },
{ method: "POST", path: "/v1/composio/authorize", auth: "source", handle: authorize },
diff --git a/src/api/routes/directory.ts b/src/api/routes/directory.ts
index c1586ab33..4cb87718e 100644
--- a/src/api/routes/directory.ts
+++ b/src/api/routes/directory.ts
@@ -1,5 +1,6 @@
import { isPrincipalType, PRINCIPAL_TYPES, type PrincipalType } from "../../types.ts";
import type { DirectoryMember } from "../../directory/directory-store.ts";
+import { canonicalPerson } from "../../directory/person.ts";
import { sendJson } from "../http.ts";
import { audit, isObj, orgScope } from "./shared.ts";
import { type ApiCtx, type Route } from "./route.ts";
@@ -26,6 +27,14 @@ async function reactivatePrincipal(ctx: ApiCtx): Promise<void> {
return sendJson(res, 200, { ok: true, principalId: id, active: true });
}
+async function canonicalPrincipal(ctx: ApiCtx): Promise<void> {
+ const { res, deps } = ctx;
+ const id = ctx.params.id!;
+ if (!id) return sendJson(res, 404, { error: "not_found" });
+ await deps.identity?.refresh(true);
+ return sendJson(res, 200, { principalId: id, canonicalId: canonicalPerson(id) });
+}
+
async function pushDirectory(ctx: ApiCtx): Promise<void> {
const { res, app, body } = ctx;
const b = body as {
@@ -156,6 +165,7 @@ async function channelMembership(ctx: ApiCtx): Promise<void> {
export const directoryRoutes: ReadonlyArray<Route<ApiCtx>> = [
{ method: "POST", path: "/v1/principals/:id/deactivate", auth: "source", handle: deactivatePrincipal },
{ method: "POST", path: "/v1/principals/:id/reactivate", auth: "source", handle: reactivatePrincipal },
+ { method: "GET", path: "/v1/principals/:id/canonical", auth: "source", handle: canonicalPrincipal },
{ method: "POST", path: "/v1/directory", auth: "source", handle: pushDirectory },
{ method: "GET", path: "/v1/directory/meta", auth: "source", handle: directoryMeta },
{
diff --git a/src/api/routes/shared.ts b/src/api/routes/shared.ts
index 5b154c1af..37cfec719 100644
--- a/src/api/routes/shared.ts
+++ b/src/api/routes/shared.ts
@@ -2,7 +2,7 @@ import { orgId as configOrgId, orgScope as configOrgScope } from "../../config.t
import type { Principal } from "../../types.ts";
import type { AuditEvent } from "../../audit/audit-log.ts";
import { adminStatusFromGrants } from "../../admin/admin-service.ts";
-import { samePerson } from "../../directory/person.ts";
+import { canonicalPerson, samePerson } from "../../directory/person.ts";
import { isTerminal, type Run } from "../../runs/run-store.ts";
import type { ServerDeps } from "../deps.ts";
import type { ApiCtx } from "./route.ts";
@@ -16,13 +16,18 @@ export function audit(deps: ServerDeps, e: Omit<AuditEvent, "at">): void {
deps.auditLog?.record({ at: Date.now(), ...e });
}
-export function adminActorFrom(ctx: Pick<ApiCtx, "req" | "deps" | "capability" | "actor">): Principal | null {
+function rawAdminActor(ctx: Pick<ApiCtx, "req" | "deps" | "capability" | "actor">): Principal | null {
if (ctx.capability) return { id: ctx.capability.actorId, type: "internal" };
if (ctx.actor)
return ctx.deps.admin?.resolveActor(`${ctx.actor.p}@${configOrgId()}`) ?? { id: ctx.actor.p, type: "internal" };
return ctx.deps.admin?.resolveActor(headerValue(ctx.req, "x-admin-actor")) ?? null;
}
+export function adminActorFrom(ctx: Pick<ApiCtx, "req" | "deps" | "capability" | "actor">): Principal | null {
+ const actor = rawAdminActor(ctx);
+ return actor ? { ...actor, id: canonicalPerson(actor.id) } : null;
+}
+
export async function authorizeAdmin(
ctx: Pick<ApiCtx, "req" | "res" | "deps" | "capability" | "actor">,
_scope: string,
diff --git a/src/api/server.ts b/src/api/server.ts
index 68b9616c6..238f4a935 100644
--- a/src/api/server.ts
+++ b/src/api/server.ts
@@ -36,6 +36,7 @@ import { apiRoutes, rawRoutes } from "./routes/index.ts";
import { proxyDeploymentSubdomain } from "./routes/deployments.ts";
import { CAPABILITY_HEADER } from "./contract.ts";
import { livePersonCapability } from "./artifact-share.ts";
+import { canonicalPerson, samePerson } from "../directory/person.ts";
const safeDecode = (s: string): string => {
try {
@@ -63,6 +64,9 @@ async function capabilityAdminDenied(
if (pathname.startsWith("/v1/admin/impersonate")) {
return "impersonating a user is portal-only — the agent cannot act as another person";
}
+ if (pathname.startsWith("/v1/admin/principal-links")) {
+ return "identity links are portal-only — the agent cannot decide which sign-ins belong to one person";
+ }
if (method === "GET" && isAdminContentRead(pathname) && parseScopeId(claims.scopeId).kind !== "personal") {
let target = "";
if (pathname.startsWith("/v1/admin/scopes/"))
@@ -297,9 +301,17 @@ async function gate(
const token = Array.isArray(rawToken) ? rawToken[0] : rawToken;
actor = token && psecret ? await verifyPortalIdentity(token, psecret, Date.now()) : null;
if (actor && deps.identity) {
- await deps.identity.refresh();
- if (deps.identity.classify(actor.p).type !== "internal") actor = null;
+ await deps.identity.refresh(Boolean(actor.authenticatedAs));
+ if (
+ deps.identity.classify(actor.p).type !== "internal" ||
+ (actor.authenticatedAs &&
+ (deps.identity.classify(actor.authenticatedAs).type !== "internal" ||
+ !samePerson(actor.authenticatedAs, actor.imp ?? actor.p)))
+ )
+ actor = null;
}
+ if (actor)
+ actor = { ...actor, p: canonicalPerson(actor.p), ...(actor.imp ? { imp: canonicalPerson(actor.imp) } : {}) };
if (!isPublicRoute && requirePortalIdentity) {
const webTurn =
method === "POST" &&
@@ -321,7 +333,9 @@ async function gate(
let asserted: unknown = null;
if (webTurn) asserted = (body as { actor?: { externalId?: unknown } }).actor?.externalId ?? null;
else if (field) asserted = assertedActor(field, url, body, req);
- if ((field && asserted !== actor.p) || (!field && asserted !== null && asserted !== actor.p)) {
+ const actorId = actor.p;
+ const matchesActor = (value: unknown): boolean => typeof value === "string" && samePerson(value, actorId);
+ if ((field && !matchesActor(asserted)) || (!field && asserted !== null && !matchesActor(asserted))) {
sendJson(res, 403, { error: "forbidden", message: "portal identity does not match the requested actor" });
return null;
}
diff --git a/src/auth/portal-identity.ts b/src/auth/portal-identity.ts
index 720675700..355d8e0ac 100644
--- a/src/auth/portal-identity.ts
+++ b/src/auth/portal-identity.ts
@@ -2,6 +2,7 @@ import { mintSignedPayload, verifySignedPayload } from "./signed-token.ts";
export interface PortalIdentity {
p: string;
+ authenticatedAs?: string;
n?: string;
imp?: string;
exp: number;
@@ -20,6 +21,8 @@ export async function verifyPortalIdentity(
): Promise<PortalIdentity | null> {
const claims = (await verifySignedPayload(token, secret)) as PortalIdentity | null;
if (!claims || typeof claims.p !== "string" || !claims.p || typeof claims.exp !== "number") return null;
+ if (claims.authenticatedAs !== undefined && (typeof claims.authenticatedAs !== "string" || !claims.authenticatedAs))
+ return null;
if (nowMs > claims.exp) return null;
return claims;
}
diff --git a/src/credentials/keychain.ts b/src/credentials/keychain.ts
index d9b6dcd26..4d56a4130 100644
--- a/src/credentials/keychain.ts
+++ b/src/credentials/keychain.ts
@@ -5,7 +5,7 @@ import { CAPABILITY_CURL_AUTH, keychainUseCommand } from "../api/contract.ts";
import type { DurableMap } from "../persistence/durable-map.ts";
import { encryptSecret, decryptSecret, type SecretKey } from "../connectors/connector-client-store.ts";
import { errMessage } from "../util/errors.ts";
-import { personKey, samePerson } from "../directory/person.ts";
+import { canonicalPerson, personIds, personKey, samePerson } from "../directory/person.ts";
import { cronIdOf } from "../sessions/session-store.ts";
import { hashId } from "../util/crypto.ts";
import { shq } from "../util/shell.ts";
@@ -471,7 +471,7 @@ function toMeta(rec: KeychainCredential): KeychainCredentialMeta {
}
function byOwners(ownerIds: string[]): { field: "ownerId"; anyOfFold: string[] } {
- return { field: "ownerId", anyOfFold: ownerIds.map((id) => personKey(id)) };
+ return { field: "ownerId", anyOfFold: ownerIds.flatMap((id) => personIds(id)) };
}
function bucketByOwner<C extends { ownerId: string }, T>(
@@ -846,12 +846,13 @@ export function createKeychain(deps: {
.map((f) => f.envKey)
.sort()
.join(",")}`;
- const id = credId(input.ownerId, service, slot);
+ const ownerId = canonicalPerson(input.ownerId);
+ const id = credId(ownerId, service, slot);
const buildRec = (prior?: KeychainCredential | null): KeychainCredential => {
const carriedCapturePaths = input.capturePaths ?? prior?.capturePaths;
return {
id,
- ownerId: input.ownerId,
+ ownerId,
orgId: configOrgId(),
service,
kind,
diff --git a/src/directory/person.ts b/src/directory/person.ts
index fcae6d822..63f40fa67 100644
--- a/src/directory/person.ts
+++ b/src/directory/person.ts
@@ -1,8 +1,38 @@
-export function personKey(id: string | null | undefined): string {
+export interface PrincipalLinkResolver {
+ canonical(key: string): string | undefined;
+ aliases(key: string): readonly string[];
+}
+
+let links: PrincipalLinkResolver | null = null;
+
+export function installPrincipalLinks(resolver: PrincipalLinkResolver | null): void {
+ links = resolver;
+}
+
+export function foldPrincipalId(id: string | null | undefined): string {
const s = (id ?? "").trim();
return s.includes("@") ? s.toLowerCase() : s;
}
+export function canonicalPerson(id: string): string {
+ const key = foldPrincipalId(id);
+ if (!key) return id;
+ return links?.canonical(key) ?? id;
+}
+
+export function personIds(id: string): string[] {
+ const key = foldPrincipalId(id);
+ if (!key) return [];
+ const canonical = links?.canonical(key) ?? id.trim();
+ return [canonical, ...(links?.aliases(foldPrincipalId(canonical)) ?? [])];
+}
+
+export function personKey(id: string | null | undefined): string {
+ const key = foldPrincipalId(id);
+ if (!key) return "";
+ return foldPrincipalId(links?.canonical(key) ?? key);
+}
+
export function samePerson(a: string | null | undefined, b: string | null | undefined): boolean {
const key = personKey(a);
return key !== "" && key === personKey(b);
diff --git a/src/directory/postgres-directory-store.ts b/src/directory/postgres-directory-store.ts
index 9cb0bd91d..347d9d467 100644
--- a/src/directory/postgres-directory-store.ts
+++ b/src/directory/postgres-directory-store.ts
@@ -2,7 +2,7 @@ import { orgId as configOrgId } from "../config.ts";
import { createHash } from "node:crypto";
import { createPgPool, type PoolClient, withPgTransaction } from "../persistence/pg-pool.ts";
import type { PrincipalType } from "../types.ts";
-import { personKey } from "./person.ts";
+import { foldPrincipalId } from "./person.ts";
import {
MAX_CANDIDATES,
groupParticipantsKey,
@@ -623,7 +623,7 @@ export function createPostgresDirectoryStore(connectionString: string): Director
},
async get(principalId) {
- const key = personKey(principalId);
+ const key = foldPrincipalId(principalId);
const rows = await q(
`SELECT ${MEMBER_COLS} FROM directory_members
WHERE org_id = $1 AND (principal_id = $2 OR ($3 AND lower(principal_id) = $4))
diff --git a/src/identity/identity-service.ts b/src/identity/identity-service.ts
index e445fc960..9633d96c1 100644
--- a/src/identity/identity-service.ts
+++ b/src/identity/identity-service.ts
@@ -1,6 +1,6 @@
import type { ActorAssertion, Principal } from "../types.ts";
import { createMemoryMap, type DurableMap } from "../persistence/durable-map.ts";
-import { personKey } from "../directory/person.ts";
+import { canonicalPerson, foldPrincipalId, personIds, personKey } from "../directory/person.ts";
import { externalMemberActive, type ExternalMember } from "./external-members.ts";
interface IdentityProvider {
@@ -48,21 +48,25 @@ export function createIdentityService(
isOverridden?: (externalId: string) => boolean;
directorySyncProtected?: readonly string[];
externalMembers?: DurableMap<ExternalMember>;
+ principalLinks?: { refresh(force?: boolean): Promise<void> };
} = {},
): IdentityService {
const store = backing ?? createMemoryMap<DeactivationRecord>();
const externalStore = opts.externalMembers ?? createMemoryMap<ExternalMember>();
const deactivated = new Map<string, DeactivationRecord>();
const externals = new Map<string, ExternalMember>();
- const directorySyncProtected = new Set((opts.directorySyncProtected ?? []).map(personKey).filter(Boolean));
+ const directorySyncProtected = opts.directorySyncProtected ?? [];
const REFRESH_TTL_MS = 10_000;
let refreshedAt = 0;
let refreshP: Promise<void> | null = null;
let hydrateP: Promise<void> | null = null;
- const keptByDirectorySync = (key: string): boolean => directorySyncProtected.has(key) || externals.has(key);
+ const keptByDirectorySync = (key: string): boolean =>
+ directorySyncProtected.some((id) => personKey(id) === key) || externals.has(key);
+ const storeKeys = (externalId: string): string[] => personIds(externalId).map(foldPrincipalId).filter(Boolean);
async function load(overwrite: boolean): Promise<void> {
+ await opts.principalLinks?.refresh(true);
const [deactivations, members] = await Promise.all([store.all(), externalStore.all()]);
if (overwrite) {
deactivated.clear();
@@ -70,7 +74,8 @@ export function createIdentityService(
}
for (const r of deactivations) {
const key = personKey(r.principalId);
- if (overwrite || !deactivated.has(key)) deactivated.set(key, r);
+ if (deactivated.get(key)?.source !== "manual" && (r.source === "manual" || overwrite || !deactivated.has(key)))
+ deactivated.set(key, r);
}
for (const m of members) {
const key = personKey(m.email);
@@ -79,7 +84,8 @@ export function createIdentityService(
}
function classify(externalId: string, isExternalGuest?: boolean): Principal {
- if (opts.isOverridden?.(externalId)) return { id: externalId, type: "internal" };
+ const id = canonicalPerson(externalId);
+ if (opts.isOverridden?.(externalId)) return { id, type: "internal" };
const key = personKey(externalId);
const record = deactivated.get(key);
const external = externals.get(key);
@@ -88,7 +94,7 @@ export function createIdentityService(
(record?.source === "directory-sync" && !keptByDirectorySync(key)) ||
(external !== undefined && !externalMemberActive(external));
const type: Principal["type"] = inactive || isExternalGuest ? "guest" : "internal";
- return { id: externalId, type };
+ return { id, type };
}
async function deactivate(externalId: string, source: DeactivationSource = "manual"): Promise<void> {
@@ -97,13 +103,12 @@ export function createIdentityService(
if (existing && (existing.source === "manual" || existing.source === source)) return;
const record: DeactivationRecord = { principalId: externalId, source, at: Date.now() };
deactivated.set(key, record);
- await store.put(key, record);
+ await store.put(foldPrincipalId(externalId), record);
}
async function reactivate(externalId: string): Promise<void> {
- const key = personKey(externalId);
- deactivated.delete(key);
- await store.delete(key);
+ deactivated.delete(personKey(externalId));
+ for (const key of storeKeys(externalId)) await store.delete(key);
}
async function refresh(force = false): Promise<void> {
@@ -146,14 +151,12 @@ export function createIdentityService(
return externals.get(personKey(principalId));
},
async putExternalMember(m: ExternalMember): Promise<void> {
- const key = personKey(m.email);
- externals.set(key, m);
- await externalStore.put(key, m);
+ externals.set(personKey(m.email), m);
+ await externalStore.put(foldPrincipalId(m.email), m);
},
async removeExternalMember(principalId: string): Promise<void> {
- const key = personKey(principalId);
- externals.delete(key);
- await externalStore.delete(key);
+ externals.delete(personKey(principalId));
+ for (const key of storeKeys(principalId)) await externalStore.delete(key);
},
hydrate(): Promise<void> {
if (!hydrateP) hydrateP = load(false);
diff --git a/src/identity/principal-links.ts b/src/identity/principal-links.ts
new file mode 100644
index 000000000..7af7b5713
--- /dev/null
+++ b/src/identity/principal-links.ts
@@ -0,0 +1,148 @@
+import { createMemoryAdvisoryLock, type AdvisoryLock } from "../persistence/advisory-lock.ts";
+import { createMemoryMap, type DurableMap } from "../persistence/durable-map.ts";
+import { foldPrincipalId, type PrincipalLinkResolver } from "../directory/person.ts";
+
+export interface PrincipalLink {
+ principalId: string;
+ canonicalId: string;
+ evidence: string;
+ linkedBy: string;
+ createdAt: number;
+}
+
+interface PrincipalLinkInput {
+ principalId: unknown;
+ canonicalId: unknown;
+ evidence: unknown;
+ linkedBy: string;
+}
+
+export class PrincipalLinkError extends Error {
+ readonly status: number;
+ constructor(status: number, message: string) {
+ super(message);
+ this.status = status;
+ }
+}
+
+export interface PrincipalLinkService extends PrincipalLinkResolver {
+ list(): Promise<PrincipalLink[]>;
+ link(input: PrincipalLinkInput): Promise<PrincipalLink>;
+ unlink(principalId: string): Promise<PrincipalLink | null>;
+ refresh(force?: boolean): Promise<void>;
+}
+
+const MAX_ID_LENGTH = 255;
+const MAX_EVIDENCE_LENGTH = 500;
+const REFRESH_TTL_MS = 10_000;
+
+function validId(value: unknown): value is string {
+ return typeof value === "string" && value.trim().length > 0 && value.trim().length <= MAX_ID_LENGTH;
+}
+
+export function createPrincipalLinkService(
+ backing?: DurableMap<PrincipalLink>,
+ lock: AdvisoryLock = createMemoryAdvisoryLock(),
+): PrincipalLinkService {
+ const store = backing ?? createMemoryMap<PrincipalLink>();
+ const byAlias = new Map<string, PrincipalLink>();
+ const byCanonical = new Map<string, PrincipalLink[]>();
+ let refreshedAt = 0;
+ let refreshP: Promise<void> | null = null;
+
+ function index(rows: PrincipalLink[]): void {
+ byAlias.clear();
+ byCanonical.clear();
+ for (const row of rows) {
+ byAlias.set(foldPrincipalId(row.principalId), row);
+ const key = foldPrincipalId(row.canonicalId);
+ const list = byCanonical.get(key) ?? [];
+ list.push(row);
+ byCanonical.set(key, list);
+ }
+ }
+
+ async function refresh(force = false): Promise<void> {
+ if (refreshP && !force) return refreshP;
+ while (refreshP) await refreshP;
+ if (!force && Date.now() - refreshedAt < REFRESH_TTL_MS) return Promise.resolve();
+ refreshP = store
+ .all()
+ .then(index)
+ .then(() => {
+ refreshedAt = Date.now();
+ })
+ .finally(() => {
+ refreshP = null;
+ });
+ return refreshP;
+ }
+
+ return {
+ canonical(key) {
+ return byAlias.get(key)?.canonicalId;
+ },
+ aliases(key) {
+ return (byCanonical.get(key) ?? []).map((row) => row.principalId);
+ },
+ refresh,
+ async list() {
+ await refresh(true);
+ return [...byAlias.values()].sort(
+ (a, b) => a.createdAt - b.createdAt || a.principalId.localeCompare(b.principalId),
+ );
+ },
+ async link(input) {
+ return lock.withLock("principal-links", async () => {
+ if (!validId(input.principalId) || !validId(input.canonicalId))
+ throw new PrincipalLinkError(
+ 400,
+ `principalId and canonicalId must be non-empty ids of at most ${MAX_ID_LENGTH} characters`,
+ );
+ const evidence = typeof input.evidence === "string" ? input.evidence.trim() : "";
+ if (!evidence || evidence.length > MAX_EVIDENCE_LENGTH)
+ throw new PrincipalLinkError(400, `evidence must say how the two identities were verified as one person`);
+ const principalId = input.principalId.trim();
+ const canonicalId = input.canonicalId.trim();
+ const aliasKey = foldPrincipalId(principalId);
+ const canonicalKey = foldPrincipalId(canonicalId);
+ if (aliasKey === canonicalKey) throw new PrincipalLinkError(400, "a principal cannot be linked to itself");
+ await refresh(true);
+ const existing = byAlias.get(aliasKey);
+ if (existing) {
+ if (foldPrincipalId(existing.canonicalId) === canonicalKey) return existing;
+ throw new PrincipalLinkError(409, `${principalId} is already linked to ${existing.canonicalId}`);
+ }
+ const canonicalIsAlias = byAlias.get(canonicalKey);
+ if (canonicalIsAlias)
+ throw new PrincipalLinkError(
+ 400,
+ `${canonicalId} is itself linked to ${canonicalIsAlias.canonicalId}; link to that principal instead`,
+ );
+ if (byCanonical.has(aliasKey))
+ throw new PrincipalLinkError(
+ 400,
+ `${principalId} is the canonical principal of other links; unlink those first`,
+ );
+ const stored = await store.putIfAbsent(aliasKey, {
+ principalId,
+ canonicalId,
+ evidence,
+ linkedBy: input.linkedBy,
+ createdAt: Date.now(),
+ });
+ await refresh(true);
+ if (foldPrincipalId(stored.canonicalId) !== canonicalKey)
+ throw new PrincipalLinkError(409, `${principalId} is already linked to ${stored.canonicalId}`);
+ return stored;
+ });
+ },
+ async unlink(principalId) {
+ return lock.withLock("principal-links", async () => {
+ const row = await store.take(foldPrincipalId(principalId));
+ await refresh(true);
+ return row;
+ });
+ },
+ };
+}
diff --git a/src/wiring.ts b/src/wiring.ts
index e4e3bfb58..605100c17 100644
--- a/src/wiring.ts
+++ b/src/wiring.ts
@@ -64,6 +64,13 @@ import {
type DeactivationRecord,
type IdentityService,
} from "./identity/identity-service.ts";
+import {
+ createPrincipalLinkService,
+ type PrincipalLink,
+ type PrincipalLinkService,
+} from "./identity/principal-links.ts";
+import type { SlackAccountLink } from "./api/routes/composio.ts";
+import { installPrincipalLinks } from "./directory/person.ts";
import type { ExternalMember } from "./identity/external-members.ts";
import { createResendMailer } from "./admin/invite-email.ts";
import {
@@ -501,6 +508,8 @@ export interface BuiltApp {
credentialUsage: CredentialUsageSink;
egressAudit: EgressAuditSink;
identity: IdentityService;
+ principalLinks: PrincipalLinkService;
+ slackAccounts: DurableMap<SlackAccountLink>;
keychain?: Keychain;
serviceCreds: ServiceCredentialStore;
deliveries: DeliveryStore;
@@ -623,18 +632,21 @@ export function buildApp(
};
},
};
+ const advisoryLock: AdvisoryLock = pgArtifactMap
+ ? createPostgresAdvisoryLock(pgArtifactMap.pool)
+ : createMemoryAdvisoryLock();
+ const principalLinks = createPrincipalLinkService(artifactMap<PrincipalLink>("principal_links"), advisoryLock);
+ installPrincipalLinks(principalLinks);
const identity = createIdentityService(artifactMap<DeactivationRecord>("deactivated_principals"), {
isOverridden: (id) => configStore.getInternalMemberOverrides().includes(id.trim().toLowerCase()),
directorySyncProtected: config.emailAuthPrincipals,
externalMembers: artifactMap<ExternalMember>("external_members"),
+ principalLinks,
});
void identity.hydrate();
const leaderLease: LeaderLease = pgArtifactMap
? createPostgresLeaderLease(pgArtifactMap.pool)
: createNoopLeaderLease();
- const advisoryLock: AdvisoryLock = pgArtifactMap
- ? createPostgresAdvisoryLock(pgArtifactMap.pool)
- : createMemoryAdvisoryLock();
const configStore = createMemoryConfigStore(config.orgId, {
connectorClients: artifactMap<StoredConnectorClient>("connector_clients"),
souls: artifactMap<PersistedSoul>("soul_configs"),
@@ -2636,6 +2648,8 @@ export function buildApp(
credentialUsage,
egressAudit,
identity,
+ principalLinks,
+ slackAccounts: artifactMap<SlackAccountLink>("slack_accounts"),
workspace,
memory,
...(keychain ? { keychain } : {}),
@@ -2769,6 +2783,8 @@ export function serverDeps(
webhookReceiver: built.webhookReceiver,
loopIngress: built.loopIngress,
identity: built.identity,
+ principalLinks: built.principalLinks,
+ slackAccounts: built.slackAccounts,
...(built.keychain ? { keychain: built.keychain } : {}),
serviceCreds: built.serviceCreds,
deliveries: built.deliveries,
diff --git a/test/composio-route.test.ts b/test/composio-route.test.ts
index 34882ac11..becc1d55c 100644
--- a/test/composio-route.test.ts
+++ b/test/composio-route.test.ts
@@ -237,3 +237,117 @@ test("connections require credential access and fail visibly on upstream errors"
assert.equal(r.status, 502);
assert.doesNotMatch(r.text, /private-key/);
});
+
+test("Slack connection links verified workspace identity to the web owner and persists status", async () => {
+ const f = fixture();
+ await f.own();
+ const { createPrincipalLinkService } = await import("../src/identity/principal-links.ts");
+ const { createDirectoryStore } = await import("../src/directory/directory-store.ts");
+ const { installPrincipalLinks, canonicalPerson } = await import("../src/directory/person.ts");
+ f.deps.principalLinks = createPrincipalLinkService();
+ installPrincipalLinks(f.deps.principalLinks);
+ f.deps.slackAccounts = createMemoryMap();
+ f.deps.signingSecret = "qa-slack-link-secret";
+ f.deps.directory = createDirectoryStore();
+ await f.deps.directory.replace([
+ { principalId: "[email protected]", slackId: "U123", displayName: "Alice", type: "internal" },
+ ]);
+ f.deps.slackEnvBotToken = "bot-test";
+ f.deps.slackInstallationFetch = (async () => Response.json({ ok: true, team_id: "T123" })) as typeof fetch;
+ try {
+ f.replies.push(
+ { session_id: "trs_test" },
+ { redirect_url: "https://connect.composio.dev/link/lk_test", connected_account_id: "ca_test" },
+ );
+ const started = await f.invoke("/v1/composio/slack/authorize", {});
+ assert.equal(started.status, 200);
+ const account = {
+ id: "ca_test",
+ user_id: composioUserId(orgId(), "alice"),
+ toolkit: { slug: "slack" },
+ status: "ACTIVE",
+ };
+ f.replies.push(account, { data: { ok: true, user_id: "U123", team_id: "T123", user: "alice", team: "Acme" } });
+ f.replies.push({ items: [] });
+ const linked = await f.invoke("/v1/composio/slack/complete", { ticket: started.data.ticket });
+ assert.equal(linked.status, 200);
+ assert.equal(canonicalPerson("[email protected]"), "alice");
+ assert.equal((await f.deps.slackAccounts.get("alice"))?.accountId, "ca_test");
+ f.replies.push(account);
+ assert.equal((await f.invoke("/v1/composio/slack")).data.connected, true);
+ f.replies.push({ ...account, status: "REVOKED" });
+ assert.equal((await f.invoke("/v1/composio/slack")).data.connected, false);
+ f.replies.push(account, { data: { ok: true, user_id: "U123", team_id: "T123", user: "alice", team: "Acme" } });
+ assert.equal((await f.invoke("/v1/composio/slack/complete", { ticket: started.data.ticket })).status, 200);
+ } finally {
+ installPrincipalLinks(null);
+ }
+});
+
+test("Slack link rejects changed browser accounts, wrong owner, bots, other workspaces and inactive connections", async () => {
+ const { createPrincipalLinkService } = await import("../src/identity/principal-links.ts");
+ const { createDirectoryStore } = await import("../src/directory/directory-store.ts");
+ const { mintSignedPayload } = await import("../src/auth/signed-token.ts");
+ for (const scenario of [
+ "expired",
+ "other-browser",
+ "wrong-owner",
+ "bot",
+ "wrong-workspace",
+ "pending",
+ "existing-connectors",
+ "existing-key",
+ "different-project",
+ ]) {
+ const f = fixture();
+ await f.own();
+ await f.own("bob");
+ f.deps.signingSecret = "slack-test";
+ f.deps.principalLinks = createPrincipalLinkService();
+ f.deps.slackAccounts = createMemoryMap();
+ f.deps.directory = createDirectoryStore();
+ await f.deps.directory.replace([
+ { principalId: "[email protected]", slackId: "U123", displayName: "Alice", type: "internal" },
+ ]);
+ f.deps.slackEnvBotToken = "bot-test";
+ f.deps.slackInstallationFetch = (async () => Response.json({ ok: true, team_id: "T123" })) as typeof fetch;
+ const ticket = await mintSignedPayload(
+ {
+ purpose: "slack-account-link",
+ principal: "alice",
+ org: orgId(),
+ accountId: "ca_test",
+ exp: Date.now() + (scenario === "expired" ? -1000 : 60000),
+ },
+ "slack-test",
+ );
+ f.replies.push(
+ {
+ id: "ca_test",
+ user_id: composioUserId(orgId(), scenario === "wrong-owner" ? "bob" : "alice"),
+ toolkit: { slug: "slack" },
+ status: scenario === "pending" ? "INITIATED" : "ACTIVE",
+ },
+ {
+ data: {
+ ok: true,
+ user_id: "U123",
+ team_id: scenario === "wrong-workspace" ? "T999" : "T123",
+ ...(scenario === "bot" ? { bot_id: "B123" } : {}),
+ },
+ },
+ );
+ if (scenario === "existing-key") await f.own("[email protected]");
+ if (scenario === "different-project") await f.shared();
+ f.replies.push({ items: scenario === "existing-connectors" ? [{ id: "ca_existing" }] : [] });
+ if (scenario === "different-project") f.replies.push({ items: [{ id: "ca_company_existing" }] });
+ const result = await f.invoke(
+ "/v1/composio/slack/complete",
+ { ticket },
+ scenario === "other-browser" ? "bob" : "alice",
+ );
+ assert.ok(result.status >= 400, `${scenario}: ${result.status}`);
+ assert.equal((await f.deps.principalLinks.list()).length, 0);
+ assert.equal((await f.deps.slackAccounts.all()).length, 0);
+ }
+});
diff --git a/test/principal-links.test.ts b/test/principal-links.test.ts
new file mode 100644
index 000000000..0127902a6
--- /dev/null
+++ b/test/principal-links.test.ts
@@ -0,0 +1,523 @@
+import "./support/auto-fake-sprites.ts";
+
+import { describe, it, before, after, afterEach } from "node:test";
+import assert from "node:assert/strict";
+import { mkdtempSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import type { AddressInfo } from "node:net";
+import type { Server } from "node:http";
+import { buildApp, type BuiltApp } from "../src/wiring.ts";
+import { createServer, createInsecureTestServer } from "../src/api/server.ts";
+import { createPrincipalLinkService, PrincipalLinkError, type PrincipalLink } from "../src/identity/principal-links.ts";
+import {
+ canonicalPerson,
+ installPrincipalLinks,
+ personIds,
+ personKey,
+ samePerson,
+ samePersonInDirectory,
+} from "../src/directory/person.ts";
+import { createDirectoryStore } from "../src/directory/directory-store.ts";
+import { createIdentityService } from "../src/identity/identity-service.ts";
+import { createMemoryMap } from "../src/persistence/durable-map.ts";
+import { createKeychain, type KeychainCredential } from "../src/credentials/keychain.ts";
+import { deriveConnectorKey } from "../src/connectors/connector-client-store.ts";
+import { adminStatusFromGrants } from "../src/admin/admin-service.ts";
+import { computeUsers } from "../src/admin/users.ts";
+import { mintCapabilityToken, CAPABILITY_TTL_MS } from "../src/auth/capability-token.ts";
+import { mintSignedPayload } from "../src/auth/signed-token.ts";
+import { signedRequestHeaders } from "../src/auth/source-auth-sign.ts";
+import { scopeId } from "../src/types.ts";
+import { testConfig } from "./support/test-config.ts";
+
+const EMAIL = "[email protected]";
+const SLACK = "U0JORDAN";
+const OIDC = "oidc:11f23f7cabe8a3778c0651be5112f1cd67387728be3d94afe6d758964c05d3c6:NDI3NjQ0";
+const EVIDENCE = "bookface email [email protected] matched the Slack-verified directory email";
+
+describe("principal link service: one person, several sign-ins", () => {
+ it("links a sign-in to a canonical principal and resolves both directions", async () => {
+ const links = createPrincipalLinkService();
+ const row = await links.link({ principalId: OIDC, canonicalId: EMAIL, evidence: EVIDENCE, linkedBy: "admin" });
+ assert.equal(row.canonicalId, EMAIL);
+ assert.equal(links.canonical(OIDC), EMAIL);
+ assert.deepEqual(links.aliases(EMAIL), [OIDC]);
+ assert.equal(links.canonical(EMAIL), undefined, "the canonical id is not itself an alias");
+ assert.equal((await links.list()).length, 1);
+ const removed = await links.unlink(OIDC);
+ assert.equal(removed?.principalId, OIDC);
+ assert.equal(links.canonical(OIDC), undefined);
+ assert.equal(await links.unlink(OIDC), null);
+ });
+
+ it("refuses self-links, chains, reversed links, missing evidence, and conflicting re-links", async () => {
+ const links = createPrincipalLinkService();
+ const reject = async (input: Parameters<typeof links.link>[0], status: number, re: RegExp) => {
+ await assert.rejects(links.link(input), (e: unknown) => {
+ assert.ok(e instanceof PrincipalLinkError);
+ assert.equal(e.status, status);
+ assert.match(e.message, re);
+ return true;
+ });
+ };
+ await reject(
+ { principalId: EMAIL, canonicalId: "[email protected]", evidence: EVIDENCE, linkedBy: "a" },
+ 400,
+ /itself/,
+ );
+ await reject({ principalId: OIDC, canonicalId: EMAIL, evidence: "", linkedBy: "a" }, 400, /evidence/);
+ await reject({ principalId: "", canonicalId: EMAIL, evidence: EVIDENCE, linkedBy: "a" }, 400, /non-empty/);
+ await links.link({ principalId: OIDC, canonicalId: EMAIL, evidence: EVIDENCE, linkedBy: "a" });
+ const again = await links.link({
+ principalId: OIDC,
+ canonicalId: EMAIL.toUpperCase(),
+ evidence: "x",
+ linkedBy: "b",
+ });
+ assert.equal(again.linkedBy, "a", "re-linking to the same canonical is idempotent and keeps the first record");
+ await reject(
+ { principalId: OIDC, canonicalId: "[email protected]", evidence: EVIDENCE, linkedBy: "a" },
+ 409,
+ /already/,
+ );
+ await reject(
+ { principalId: "U0OTHER", canonicalId: OIDC, evidence: EVIDENCE, linkedBy: "a" },
+ 400,
+ /itself linked/,
+ );
+ await reject(
+ { principalId: EMAIL, canonicalId: "[email protected]", evidence: EVIDENCE, linkedBy: "a" },
+ 400,
+ /canonical/,
+ );
+ });
+
+ it("reads links written by another process on refresh", async () => {
+ const backing = createMemoryMap<PrincipalLink>();
+ const links = createPrincipalLinkService(backing);
+ await links.refresh(true);
+ assert.equal(links.canonical(OIDC), undefined);
+ await backing.put(OIDC, {
+ principalId: OIDC,
+ canonicalId: EMAIL,
+ evidence: EVIDENCE,
+ linkedBy: "ops",
+ createdAt: 1,
+ });
+ await links.refresh(true);
+ assert.equal(links.canonical(OIDC), EMAIL);
+ });
+});
+
+describe("person primitives fold a linked sign-in to its canonical principal", () => {
+ afterEach(() => installPrincipalLinks(null));
+
+ async function installed() {
+ const links = createPrincipalLinkService();
+ await links.link({ principalId: OIDC, canonicalId: EMAIL, evidence: EVIDENCE, linkedBy: "admin" });
+ installPrincipalLinks(links);
+ return links;
+ }
+
+ it("personKey, samePerson, canonicalPerson and personIds agree", async () => {
+ assert.equal(samePerson(OIDC, EMAIL), false, "unlinked ids are different people");
+ await installed();
+ assert.equal(personKey(OIDC), EMAIL);
+ assert.equal(samePerson(OIDC, "[email protected]"), true);
+ assert.equal(canonicalPerson(OIDC), EMAIL);
+ assert.equal(canonicalPerson(EMAIL), EMAIL);
+ assert.equal(canonicalPerson("U0STRANGER"), "U0STRANGER");
+ assert.deepEqual(personIds(OIDC), [EMAIL, OIDC]);
+ assert.deepEqual(personIds(EMAIL), [EMAIL, OIDC]);
+ assert.deepEqual(personIds("U0STRANGER"), ["U0STRANGER"]);
+ assert.equal(samePerson(OIDC, "[email protected]"), false);
+ });
+
+ it("the directory bridge reaches a linked sign-in through the roster row", async () => {
+ await installed();
+ const dir = createDirectoryStore();
+ await dir.replace([{ principalId: EMAIL, displayName: "Jordan", type: "internal", slackId: SLACK }]);
+ assert.equal(await samePersonInDirectory(dir, OIDC, SLACK), true);
+ assert.equal(await samePersonInDirectory(dir, OIDC, "U0CASEY"), false);
+ });
+
+ it("the identity service classifies a linked sign-in as the canonical principal and deactivates the person", async () => {
+ const links = createPrincipalLinkService();
+ await links.link({ principalId: OIDC, canonicalId: EMAIL, evidence: EVIDENCE, linkedBy: "admin" });
+ installPrincipalLinks(links);
+ const identity = createIdentityService(undefined, { principalLinks: links });
+ await identity.refresh(true);
+ assert.equal(identity.classify(OIDC).id, EMAIL);
+ assert.equal(identity.resolve({ externalId: OIDC }).id, EMAIL);
+ assert.equal(identity.classify("U0STRANGER").id, "U0STRANGER");
+ await identity.deactivate(OIDC);
+ assert.equal(identity.classify(EMAIL).type, "guest", "deactivating one sign-in deactivates the person");
+ await identity.reactivate(EMAIL);
+ assert.equal(identity.classify(OIDC).type, "internal");
+ });
+
+ it("a deactivation recorded before the link is still reversible after it", async () => {
+ installPrincipalLinks(null);
+ const links = createPrincipalLinkService();
+ const identity = createIdentityService(undefined, { principalLinks: links });
+ await identity.deactivate(OIDC);
+ await identity.putExternalMember({
+ email: "[email protected]",
+ role: "member",
+ expiresAt: Date.now() + 60_000,
+ invitedBy: "admin",
+ createdAt: 1,
+ updatedAt: 1,
+ });
+ await links.link({ principalId: OIDC, canonicalId: EMAIL, evidence: EVIDENCE, linkedBy: "admin" });
+ await links.link({
+ principalId: "[email protected]",
+ canonicalId: "U0GUEST",
+ evidence: EVIDENCE,
+ linkedBy: "admin",
+ });
+ installPrincipalLinks(links);
+ await identity.refresh(true);
+ assert.equal(identity.classify(EMAIL).type, "guest");
+ await identity.reactivate(EMAIL);
+ await identity.refresh(true);
+ assert.equal(identity.classify(EMAIL).type, "internal", "reactivation survives a reload");
+ assert.equal(identity.classify(OIDC).type, "internal");
+ assert.ok(identity.externalMember("U0GUEST"));
+ await identity.removeExternalMember("U0GUEST");
+ await identity.refresh(true);
+ assert.equal(identity.externalMember("[email protected]"), undefined, "removal survives a reload");
+ });
+
+ it("the keychain stores new credentials under the canonical owner and lists legacy ones from either id", async () => {
+ await installed();
+ const creds = createMemoryMap<KeychainCredential>();
+ const keychain = createKeychain({
+ creds,
+ grants: createMemoryMap(),
+ asks: createMemoryMap(),
+ key: deriveConnectorKey("principal-links-test-key"),
+ });
+ const saved = await keychain.save({ ownerId: OIDC, service: "github", secret: "ghp_x", envKey: "GITHUB_TOKEN" });
+ assert.equal(saved.ownerId, EMAIL);
+ const rotated = await keychain.save({ ownerId: EMAIL, service: "github", secret: "ghp_y", envKey: "GITHUB_TOKEN" });
+ assert.equal(rotated.id, saved.id, "the same person saving the same service rotates one record");
+ assert.equal(await keychain.readOwnSecret(OIDC, saved.id), "ghp_y");
+ const legacy = await keychain.save({ ownerId: EMAIL, service: "linear", secret: "lin_x", envKey: "LINEAR_KEY" });
+ await creds.merge(legacy.id, { ownerId: OIDC });
+ const mine = await keychain.listByOwner(EMAIL);
+ assert.deepEqual(mine.map((c) => c.service).sort(), ["github", "linear"]);
+ const viaSignIn = await keychain.listByOwner(OIDC);
+ assert.deepEqual(viaSignIn.map((c) => c.service).sort(), ["github", "linear"]);
+ assert.equal(await keychain.readOwnSecret(OIDC, legacy.id), "lin_x");
+ assert.equal(await keychain.readOwnSecret("[email protected]", legacy.id), null);
+ });
+
+ it("an admin grant held by either id makes the person an admin, and the users list shows one row", async () => {
+ await installed();
+ const grants = [{ principalId: OIDC, scopeId: scopeId("org", "acme"), role: "org_admin" as const }];
+ assert.equal(adminStatusFromGrants(grants, EMAIL).isAdmin, true);
+ const users = computeUsers({
+ grants,
+ participants: [
+ { sessionId: "s1", principalId: OIDC, validFrom: 10, validTo: null, validFromSeq: null, validToSeq: null },
+ { sessionId: "s2", principalId: EMAIL, validFrom: 20, validTo: null, validFromSeq: null, validToSeq: null },
+ ],
+ turns: [],
+ });
+ assert.equal(users.length, 1);
+ assert.equal(users[0]!.principalId, EMAIL);
+ assert.equal(users[0]!.sessionCount, 2);
+ assert.equal(users[0]!.admin.isAdmin, true);
+ });
+});
+
+describe("linked sign-ins across the HTTP surface", () => {
+ const SECRET = "principal-links-source-secret".repeat(2);
+ let server: Server;
+ let base: string;
+ let built: BuiltApp;
+ let nonce = 0;
+
+ const signed = (method: string, rawPath: string, body = "", headers: Record<string, string> = {}) => {
+ const path = `${rawPath}${rawPath.includes("?") ? "&" : "?"}_n=${nonce++}`;
+ return fetch(`${base}${path}`, {
+ method,
+ headers: {
+ ...signedRequestHeaders(SECRET, method, path, body),
+ ...(body ? { "content-type": "application/json" } : {}),
+ ...headers,
+ },
+ ...(body ? { body } : {}),
+ });
+ };
+ const admin = { "x-admin-actor": "admin-alice@default-org" };
+ const capFor = (actorId: string, scope = scopeId("personal", actorId)) =>
+ mintCapabilityToken({ actorId, scopeId: scope, exp: Date.now() + CAPABILITY_TTL_MS }, SECRET);
+
+ before(async () => {
+ built = buildApp(testConfig({ dataDir: mkdtempSync(join(tmpdir(), "principal-links-")), signingSecret: SECRET }));
+ await built.app.upsertDirectory([{ principalId: EMAIL, displayName: "Jordan", type: "internal", slackId: SLACK }]);
+ server = createServer(built.app, {
+ signingSecret: SECRET,
+ admin: built.admin,
+ auditLog: built.auditLog,
+ keychain: built.keychain,
+ secretDrops: built.secretDrops,
+ deliveries: built.deliveries,
+ workspace: built.workspace,
+ runs: built.runs,
+ signals: built.signals,
+ identity: built.identity,
+ principalLinks: built.principalLinks,
+ directory: built.directory,
+ });
+ await new Promise<void>((resolve) => server.listen(0, resolve));
+ base = `http://localhost:${(server.address() as AddressInfo).port}`;
+ });
+
+ after(async () => {
+ await new Promise<void>((resolve) => server.close(() => resolve()));
+ });
+
+ it("only an org admin manages links, the agent never does, and a directory member stays canonical", async () => {
+ const body = JSON.stringify({ principalId: OIDC, canonicalId: EMAIL, evidence: EVIDENCE });
+ assert.equal(
+ (await signed("POST", "/v1/admin/principal-links", body, { "x-admin-actor": "U0STRANGER@default-org" })).status,
+ 403,
+ );
+ const agent = await fetch(`${base}/v1/admin/principal-links`, {
+ method: "POST",
+ headers: { "content-type": "application/json", "x-agent-capability": await capFor("admin-alice") },
+ body,
+ });
+ assert.equal(agent.status, 403);
+ for (const memberSide of [EMAIL, EMAIL.toUpperCase(), SLACK]) {
+ const reversed = await signed(
+ "POST",
+ "/v1/admin/principal-links",
+ JSON.stringify({ principalId: memberSide, canonicalId: OIDC, evidence: EVIDENCE }),
+ admin,
+ );
+ assert.equal(reversed.status, 400, `${memberSide} is a directory member and stays canonical`);
+ assert.match(((await reversed.json()) as { message: string }).message, /directory member/);
+ }
+ const escalation = await signed(
+ "POST",
+ "/v1/admin/principal-links",
+ JSON.stringify({ principalId: "admin-alice", canonicalId: "[email protected]", evidence: EVIDENCE }),
+ admin,
+ );
+ assert.equal(escalation.status, 400, "an admin sign-in cannot make a non-admin canonical principal an admin");
+ assert.match(((await escalation.json()) as { message: string }).message, /admin grant/);
+ assert.equal(adminStatusFromGrants(await built.admin.listGrants(), "[email protected]").isAdmin, false);
+ const created = await signed("POST", "/v1/admin/principal-links", body, admin);
+ assert.equal(created.status, 200);
+ const listed = (await (await signed("GET", "/v1/admin/principal-links", "", admin)).json()) as {
+ links: PrincipalLink[];
+ };
+ assert.equal(listed.links.length, 1);
+ assert.equal(listed.links[0]!.linkedBy, "admin-alice");
+ const audit = await built.auditLog.tail({ limit: 50, action: "principal_link.create" });
+ assert.ok(audit.some((e) => e.resource === `${OIDC} -> ${EMAIL}`));
+ });
+
+ it("surfaces resolve a sign-in to its canonical principal", async () => {
+ const r = await signed("GET", `/v1/principals/${encodeURIComponent(OIDC)}/canonical`);
+ assert.equal(r.status, 200);
+ assert.deepEqual(await r.json(), { principalId: OIDC, canonicalId: EMAIL });
+ const plain = await signed("GET", `/v1/principals/${encodeURIComponent(EMAIL)}/canonical`);
+ assert.deepEqual(await plain.json(), { principalId: EMAIL, canonicalId: EMAIL });
+ });
+
+ it("a secret drop minted for the Slack identity opens and redeems under the linked sign-in", async () => {
+ const minted = await fetch(`${base}/v1/keychain/drops`, {
+ method: "POST",
+ headers: { "content-type": "application/json", "x-agent-capability": await capFor(EMAIL) },
+ body: JSON.stringify({ service: "stripe", purpose: "charge cards" }),
+ });
+ assert.equal(minted.status, 200);
+ const { dropId, formPath } = (await minted.json()) as { dropId: string; formPath: string };
+ const t = new URL(formPath, "http://x").searchParams.get("t")!;
+ const owner = (id: string) => ({ "x-drop-owner": id, "x-drop-owner-org": "default-org" });
+ assert.equal(
+ (
+ await signed(
+ "GET",
+ `/v1/keychain/drops/${dropId}/form?t=${encodeURIComponent(t)}`,
+ "",
+ owner("[email protected]"),
+ )
+ ).status,
+ 403,
+ );
+ assert.equal(
+ (await signed("GET", `/v1/keychain/drops/${dropId}/form?t=${encodeURIComponent(t)}`, "", owner(OIDC))).status,
+ 200,
+ );
+ const redeemed = await signed(
+ "POST",
+ `/v1/keychain/drops/${dropId}?t=${encodeURIComponent(t)}`,
+ JSON.stringify({ secret: "sk_live_x" }),
+ owner(OIDC),
+ );
+ assert.equal(redeemed.status, 200);
+ const { credential } = (await redeemed.json()) as { credential: { id: string; ownerId: string } };
+ assert.equal(credential.ownerId, EMAIL, "the credential belongs to the canonical principal");
+ assert.equal(await built.keychain!.readOwnSecret(OIDC, credential.id), "sk_live_x");
+ });
+
+ it("deleting the link restores two separate principals", async () => {
+ const removed = await signed("DELETE", `/v1/admin/principal-links/${encodeURIComponent(OIDC)}`, "", admin);
+ assert.equal(removed.status, 200);
+ assert.equal(
+ (await signed("DELETE", `/v1/admin/principal-links/${encodeURIComponent(OIDC)}`, "", admin)).status,
+ 404,
+ );
+ assert.equal(samePerson(OIDC, EMAIL), false);
+ assert.equal(built.identity.classify(OIDC).id, OIDC);
+ });
+});
+
+describe("the portal identity gate accepts a linked sign-in for the canonical viewer", () => {
+ const PID = "portal-only-identity-secret-for-tests-02";
+ let server: Server;
+ let base: string;
+ let built: BuiltApp;
+
+ before(async () => {
+ built = buildApp(testConfig({ dataDir: mkdtempSync(join(tmpdir(), "principal-links-gate-")) }));
+ await built.principalLinks.link({ principalId: OIDC, canonicalId: EMAIL, evidence: EVIDENCE, linkedBy: "test" });
+ await built.identity.refresh(true);
+ server = createInsecureTestServer(built.app, {
+ portalIdentitySecret: PID,
+ requireSignedPortalIdentity: true,
+ scheduler: built.scheduler,
+ identity: built.identity,
+ sessionShares: built.sessionShares,
+ });
+ await new Promise<void>((resolve) => server.listen(0, resolve));
+ base = `http://localhost:${(server.address() as AddressInfo).port}`;
+ });
+
+ after(async () => {
+ await new Promise<void>((resolve) => server.close(() => resolve()));
+ });
+
+ const get = async (p: string, viewer: string) =>
+ fetch(`${base}/v1/sessions/nope?viewer=${encodeURIComponent(viewer)}`, {
+ headers: { "x-portal-identity": await mintSignedPayload({ p, exp: Date.now() + 60_000 }, PID) },
+ });
+
+ it("passes for the canonical viewer, the sign-in itself, and rejects another person", async () => {
+ assert.equal((await get(OIDC, EMAIL)).status, 404);
+ assert.equal((await get(OIDC, OIDC)).status, 404);
+ assert.equal((await get(EMAIL, OIDC)).status, 404);
+ assert.equal((await get(OIDC, "[email protected]")).status, 403);
+ });
+});
+
+describe("link mutation serialization", () => {
+ it("rejects concurrent chains", async () => {
+ const links = createPrincipalLinkService();
+ const results = await Promise.allSettled([
+ links.link({ principalId: "A", canonicalId: "B", evidence: "qa", linkedBy: "qa" }),
+ links.link({ principalId: "B", canonicalId: "C", evidence: "qa", linkedBy: "qa" }),
+ ]);
+ assert.equal(results.filter((r) => r.status === "fulfilled").length, 1);
+ assert.equal((await links.list()).length, 1);
+ });
+ it("does not reuse a snapshot begun before the mutation lock", async () => {
+ const { createMemoryAdvisoryLock } = await import("../src/persistence/advisory-lock.ts");
+ const backing = createMemoryMap<PrincipalLink>();
+ const lock = createMemoryAdvisoryLock();
+ const delayed = Promise.withResolvers<void>();
+ const started = Promise.withResolvers<void>();
+ let delay = true;
+ const a = createPrincipalLinkService(
+ {
+ ...backing,
+ async all() {
+ const rows = await backing.all();
+ if (delay) {
+ delay = false;
+ started.resolve();
+ await delayed.promise;
+ }
+ return rows;
+ },
+ },
+ lock,
+ );
+ const b = createPrincipalLinkService(backing, lock);
+ const pending = a.refresh(true);
+ await started.promise;
+ await b.link({ principalId: "B", canonicalId: "C", evidence: "qa", linkedBy: "qa" });
+ const result = a.link({ principalId: "A", canonicalId: "B", evidence: "qa", linkedBy: "qa" });
+ delayed.resolve();
+ await pending;
+ await assert.rejects(result, /itself linked/);
+ });
+ it("manual blocks win over directory records during hydration and refresh in either order", async () => {
+ for (const reverse of [false, true]) {
+ const links = createPrincipalLinkService();
+ await links.link({ principalId: "A", canonicalId: "B", evidence: "qa", linkedBy: "qa" });
+ installPrincipalLinks(links);
+ try {
+ const store = createMemoryMap<import("../src/identity/identity-service.ts").DeactivationRecord>();
+ const rows: import("../src/identity/identity-service.ts").DeactivationRecord[] = [
+ { principalId: "A", source: reverse ? "directory-sync" : "manual", at: 1 },
+ { principalId: "B", source: reverse ? "manual" : "directory-sync", at: 2 },
+ ];
+ for (const row of reverse ? rows.reverse() : rows) await store.put(row.principalId, row);
+ const identity = createIdentityService(store, { principalLinks: links, directorySyncProtected: ["B"] });
+ await identity.hydrate();
+ assert.equal(identity.classify("B").type, "guest");
+ await identity.refresh(true);
+ assert.equal(identity.classify("B").type, "guest");
+ } finally {
+ installPrincipalLinks(null);
+ }
+ }
+ });
+});
+
+describe("canonical portal claims retain proof of the original sign-in", () => {
+ it("accepts a linked sign-in and rejects its stale canonical claim after unlink", async () => {
+ const secret = "authenticated-as-test-secret-0123456789";
+ const app = buildApp(testConfig({ dataDir: mkdtempSync(join(tmpdir(), "slack-link-proof-")) }));
+ await app.principalLinks.link({ principalId: OIDC, canonicalId: EMAIL, evidence: EVIDENCE, linkedBy: "qa" });
+ await app.identity.refresh(true);
+ const server = createInsecureTestServer(app.app, {
+ portalIdentitySecret: secret,
+ requireSignedPortalIdentity: true,
+ identity: app.identity,
+ });
+ await new Promise<void>((resolve) => server.listen(0, resolve));
+ const base = `http://localhost:${(server.address() as AddressInfo).port}`;
+ const token = await mintSignedPayload({ p: EMAIL, authenticatedAs: OIDC, exp: Date.now() + 60000 }, secret);
+ const get = () =>
+ fetch(`${base}/v1/sessions/missing?viewer=${encodeURIComponent(EMAIL)}`, {
+ headers: { "x-portal-identity": token },
+ });
+ try {
+ assert.equal((await get()).status, 404);
+ const impersonation = await mintSignedPayload(
+ { p: "another-person", imp: EMAIL, authenticatedAs: OIDC, exp: Date.now() + 60000 },
+ secret,
+ );
+ const impersonate = () =>
+ fetch(`${base}/v1/sessions/missing?viewer=another-person`, {
+ headers: { "x-portal-identity": impersonation },
+ });
+ assert.equal((await impersonate()).status, 404);
+ await app.principalLinks.unlink(OIDC);
+ assert.equal((await impersonate()).status, 401);
+ assert.equal((await get()).status, 401);
+ } finally {
+ await new Promise<void>((resolve) => server.close(() => resolve()));
+ installPrincipalLinks(null);
+ }
+ });
+});