Skip to content

Open-source AI teammates in Slack, Teams, Discord, Telegram and Mattermost. Self-host it, with any agent harness and any model.

Confirm chat account links from the account itself (CHOO-3881) (#1106)

Christian McDermott1d4bfecbb597
diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.test.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.test.ts
index 1be747407..afff26589 100644
--- a/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.test.ts
+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.test.ts
@@ -80,6 +80,11 @@ const {
fetchJoinableWorkspaces,
fetchBridgeTeams,
fetchMessagingAppInstalls,
+ fetchMyIdentities,
+ fetchMyPendingIdentities,
+ fetchUnconfirmedLinks,
+ requireLinkConfirmation,
+ searchBridgeDirectory,
fetchTeamsPackage,
joinWorkspaceByDomain,
fetchJoinDomains,
@@ -2340,6 +2345,164 @@ describe('messaging-app installs', () => {
});
});
+/**
+ * Links have to be confirmed with a code posted from the account (CHOO-3881).
+ * A server from before that sends none of the new fields, and every link it
+ * reports counts — so a missing `verified` reads as confirmed and a missing
+ * pending route as nothing pending.
+ */
+describe('linked messaging accounts', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ vi.stubGlobal('fetch', fetchMock);
+ getSessionCookie.mockResolvedValue(makeJwt(24 * 60 * 60));
+ });
+
+ afterEach(() => {
+ vi.unstubAllGlobals();
+ });
+
+ const LINKED = {
+ id: 'eu-1',
+ bridge_id: 'b1',
+ bridge_display_name: 'Acme',
+ bridge_type: 'slack',
+ external_user_id: 'U1',
+ external_username: 'ada',
+ };
+
+ it('reads whether each link is confirmed', async () => {
+ fetchMock.mockResolvedValue(jsonResponse([{ ...LINKED, verified: false }]) as never);
+
+ await expect(fetchMyIdentities(SERVER)).resolves.toMatchObject([{ verified: false }]);
+ });
+
+ it('reads a link from a server that predates confirming as confirmed', async () => {
+ fetchMock.mockResolvedValue(jsonResponse([LINKED]) as never);
+
+ await expect(fetchMyIdentities(SERVER)).resolves.toMatchObject([{ verified: true }]);
+ });
+
+ it('lists the links waiting for a code', async () => {
+ fetchMock.mockResolvedValue(
+ jsonResponse([
+ { ...LINKED, requested_by_name: 'Grace', code_expires_at: '2026-10-27T12:30:00Z' },
+ ]) as never
+ );
+
+ await expect(fetchMyPendingIdentities(SERVER)).resolves.toEqual([
+ {
+ id: 'eu-1',
+ bridgeId: 'b1',
+ bridgeDisplayName: 'Acme',
+ bridgeType: 'slack',
+ externalUserId: 'U1',
+ externalUsername: 'ada',
+ requestedByName: 'Grace',
+ codeExpiresAt: '2026-10-27T12:30:00Z',
+ },
+ ]);
+ const [url] = fetchMock.mock.calls[0] as unknown as [string];
+ expect(url).toBe('https://switch.example.com/gateway/auth/me/identities/pending');
+ });
+
+ it('reads a server without the pending route as having none pending', async () => {
+ fetchMock.mockResolvedValue(errorResponse(404, '{"detail":"Not Found"}') as never);
+
+ await expect(fetchMyPendingIdentities(SERVER)).resolves.toEqual([]);
+ });
+
+ it('raises on any other failure to list them', async () => {
+ fetchMock.mockResolvedValue(errorResponse(500, '{"detail":"boom"}') as never);
+
+ await expect(fetchMyPendingIdentities(SERVER)).rejects.toMatchObject({ status: 500 });
+ });
+
+ it('reads who has confirmed a directory entry, old servers as confirmed', async () => {
+ fetchMock.mockResolvedValue(
+ jsonResponse({
+ users: [
+ {
+ external_user_id: 'U1',
+ username: 'ada',
+ display_name: 'Ada',
+ claimed_by: [
+ { user_id: 'u1', user_name: 'Ada', verified: false },
+ { user_id: 'u2', user_name: 'Grace' },
+ ],
+ },
+ ],
+ }) as never
+ );
+
+ const { users } = await searchBridgeDirectory(SERVER, 'b1', 'ada');
+
+ expect(users[0]!.claimedBy).toEqual([
+ { userId: 'u1', userName: 'Ada', verified: false },
+ { userId: 'u2', userName: 'Grace', verified: true },
+ ]);
+ });
+});
+
+/**
+ * An admin can stop trusting a messaging app's links made before links had to
+ * be confirmed (CHOO-3881). A server from before that has neither route.
+ */
+describe('older links an admin can require confirming', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ vi.stubGlobal('fetch', fetchMock);
+ getSessionCookie.mockResolvedValue(makeJwt(24 * 60 * 60));
+ });
+
+ afterEach(() => {
+ vi.unstubAllGlobals();
+ });
+
+ it('lists them for one app', async () => {
+ fetchMock.mockResolvedValue(
+ jsonResponse([
+ {
+ id: 'eu-1',
+ external_user_id: 'U1',
+ external_username: 'ada',
+ user_id: 'u1',
+ user_name: 'Ada',
+ },
+ ]) as never
+ );
+
+ await expect(fetchUnconfirmedLinks(SERVER, 'b1')).resolves.toEqual([
+ { id: 'eu-1', externalUserId: 'U1', externalUsername: 'ada', userId: 'u1', userName: 'Ada' },
+ ]);
+ const [url] = fetchMock.mock.calls[0] as unknown as [string];
+ expect(url).toBe('https://switch.example.com/gateway/collaborations/b1/identities/unconfirmed');
+ });
+
+ it('reads a server without the route as having none', async () => {
+ fetchMock.mockResolvedValue(errorResponse(404, '{"detail":"Not Found"}') as never);
+
+ await expect(fetchUnconfirmedLinks(SERVER, 'b1')).resolves.toEqual([]);
+ });
+
+ it('raises when the caller may not see them', async () => {
+ fetchMock.mockResolvedValue(errorResponse(403, '{"detail":"Admins only"}') as never);
+
+ await expect(fetchUnconfirmedLinks(SERVER, 'b1')).rejects.toMatchObject({ status: 403 });
+ });
+
+ it('requires confirming them, and says how many moved', async () => {
+ fetchMock.mockResolvedValue(jsonResponse({ moved: 3 }) as never);
+
+ await expect(requireLinkConfirmation(SERVER, 'b1')).resolves.toBe(3);
+ const [url, init] = fetchMock.mock.calls[0] as unknown as [string, { method: string }];
+ expect(url).toBe(
+ 'https://switch.example.com/gateway/collaborations/b1/identities/require-confirmation'
+ );
+ expect(init.method).toBe('POST');
+ });
+});
+
describe('organizations', () => {
beforeEach(() => {
vi.clearAllMocks();
diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.ts
index f85745517..b78b2387e 100644
--- a/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.ts
+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.ts
@@ -81,9 +81,11 @@ import {
type ChatClaim,
type ConnectedChat,
type DeleteBridgeResult,
+ type LinkCode,
type LinkedIdentity,
type MessagingAppInstall,
type MessagingApps,
+ type PendingIdentity,
type RemoteAgentRoom,
type RemoteAgentSummary,
type RemoteBridge,
@@ -102,6 +104,7 @@ import {
type TeamsTeam,
type TeamsTeamsResult,
type TrustSettings,
+ type UnconfirmedLink,
type UpdateTrustSettingsParams,
} from '@shared/core/switch-servers/switch-servers';
import type {
@@ -2207,21 +2210,44 @@ export async function deleteMessagingAppInstall(
});
}
-/** The gateway `IdentityClaimant` wire shape. */
+/** The gateway `IdentityClaimant` wire shape. `verified` is absent from a
+ * server that predates confirming links, where every link counts the same. */
type IdentityClaimantJson = {
user_id: string;
user_name: string;
+ verified?: boolean;
};
-/** The gateway `ExternalUserSummary` wire shape. */
+/** The gateway `LinkCode` wire shape. */
+type LinkCodeJson = {
+ code: string;
+ expires_at: string;
+ /** Absent from a server that predates it. */
+ expires_in_seconds?: number;
+ instructions: string;
+};
+
+/** The gateway `ExternalUserSummary` wire shape. `link_request` is set when a
+ * claim is waiting for the account to confirm it, and absent from a server that
+ * predates confirming, which links straight away. */
type ExternalUserSummaryJson = {
id: string;
bridge_id: string;
external_user_id: string;
external_username: string;
claimed_by?: IdentityClaimantJson[];
+ link_request?: { user_id: string; code: LinkCodeJson | null } | null;
};
+export function mapLinkCode(json: LinkCodeJson): LinkCode {
+ return {
+ code: json.code,
+ expiresAt: json.expires_at,
+ expiresInSeconds: json.expires_in_seconds ?? null,
+ instructions: json.instructions,
+ };
+}
+
/**
* Union of external (bridged human) users across every bridge on the server
* (`GET /collaborations`, then each bridge's `/users`). The addressing policy's
@@ -2284,7 +2310,11 @@ export async function searchBridgeDirectory(
displayName: u.display_name,
email: u.email ?? null,
knownExternalUserId: u.known_external_user_id ?? null,
- claimedBy: (u.claimed_by ?? []).map((c) => ({ userId: c.user_id, userName: c.user_name })),
+ claimedBy: (u.claimed_by ?? []).map((c) => ({
+ userId: c.user_id,
+ userName: c.user_name,
+ verified: c.verified ?? true,
+ })),
})),
};
}
@@ -2298,6 +2328,11 @@ export async function searchBridgeDirectory(
* claimed is claimed normally; a 409 means only that the bridge is stopped and
* an unseen account cannot be provisioned, and surfaces as a `GatewayError`
* with that status.
+ *
+ * A current server answers with the link still pending and a code to post from
+ * the account (`link_request`); see {@link issueIdentityLinkCode}. It refuses a
+ * claim that does not say it can show that code (`expects_confirmation`), since
+ * a client that cannot would leave the link pending with no way to finish it.
*/
export async function claimBridgeIdentity(
server: SwitchServer,
@@ -2310,15 +2345,114 @@ export async function claimBridgeIdentity(
{
authenticated: true,
method: 'POST',
- body: { external_user_id: params.externalUserId, username: params.username },
+ body: {
+ external_user_id: params.externalUserId,
+ username: params.username,
+ expects_confirmation: true,
+ },
}
);
return (await res.json()) as ExternalUserSummaryJson;
}
/**
- * Drop one claim on a platform account
- * (`DELETE /collaborations/{id}/identities/{rowId}`). `externalUserRowId` is
+ * A fresh code confirming the signed-in user's link to a platform account
+ * (`POST /collaborations/{id}/identities/{rowId}/code`), for a link still
+ * pending or one made before links had to be confirmed. It replaces any code
+ * issued before; the server keeps none, so this is also how a lost code is
+ * "shown again". 409 means the link is already confirmed (or the account cannot
+ * be linked at all), 404 that there is nothing to confirm.
+ */
+export async function issueIdentityLinkCode(
+ server: SwitchServer,
+ bridgeId: string,
+ externalUserRowId: string
+): Promise<LinkCode> {
+ const res = await gatewayFetch(
+ server,
+ `/collaborations/${encodeURIComponent(bridgeId)}/identities/${encodeURIComponent(externalUserRowId)}/code`,
+ { authenticated: true, method: 'POST' }
+ );
+ return mapLinkCode((await res.json()) as LinkCodeJson);
+}
+
+/**
+ * Withdraw the signed-in user's confirmation waiting on a code
+ * (`DELETE /collaborations/{id}/identities/{rowId}/request`). Only the request
+ * goes: a link that already works — one made before links had to be confirmed
+ * — stays, which is what makes this the safe Cancel where
+ * {@link releaseBridgeIdentity} is not. 404 means nothing is waiting.
+ */
+export async function cancelIdentityLinkRequest(
+ server: SwitchServer,
+ bridgeId: string,
+ externalUserRowId: string
+): Promise<void> {
+ await gatewayFetch(
+ server,
+ `/collaborations/${encodeURIComponent(bridgeId)}/identities/${encodeURIComponent(externalUserRowId)}/request`,
+ { authenticated: true, method: 'DELETE' }
+ );
+}
+
+/**
+ * The links on a messaging app made before links had to be confirmed
+ * (`GET /collaborations/{id}/identities/unconfirmed`), which still count. Admin
+ * only. A server that predates confirming links has no such route and no such
+ * links, so its 404 reads as none — as does a bridge removed meanwhile.
+ */
+export async function fetchUnconfirmedLinks(
+ server: SwitchServer,
+ bridgeId: string
+): Promise<UnconfirmedLink[]> {
+ let res: Response;
+ try {
+ res = await gatewayFetch(
+ server,
+ `/collaborations/${encodeURIComponent(bridgeId)}/identities/unconfirmed`,
+ { authenticated: true }
+ );
+ } catch (cause) {
+ if (cause instanceof GatewayError && cause.status === 404) return [];
+ throw cause;
+ }
+ const json = (await res.json()) as Array<{
+ id: string;
+ external_user_id: string;
+ external_username: string;
+ user_id: string;
+ user_name: string;
+ }>;
+ return json.map((l) => ({
+ id: l.id,
+ externalUserId: l.external_user_id,
+ externalUsername: l.external_username,
+ userId: l.user_id,
+ userName: l.user_name,
+ }));
+}
+
+/**
+ * Stop trusting a messaging app's older links until each owner confirms theirs
+ * (`POST /collaborations/{id}/identities/require-confirmation`). Admin only.
+ * Each becomes a link waiting for its code and stops counting at once. Returns
+ * how many moved.
+ */
+export async function requireLinkConfirmation(
+ server: SwitchServer,
+ bridgeId: string
+): Promise<number> {
+ const res = await gatewayFetch(
+ server,
+ `/collaborations/${encodeURIComponent(bridgeId)}/identities/require-confirmation`,
+ { authenticated: true, method: 'POST' }
+ );
+ return ((await res.json()) as { moved: number }).moved;
+}
+
+/**
+ * Drop one claim on a platform account, along with any confirmation waiting on
+ * it (`DELETE /collaborations/{id}/identities/{rowId}`). `externalUserRowId` is
* the `ExternalUser` row id, not the platform's id.
*
* Several users can hold a claim on the same account, so `userId` says whose
@@ -2342,10 +2476,11 @@ export async function releaseBridgeIdentity(
}
/**
- * The messaging accounts the signed-in user has claimed
+ * The messaging accounts linked to the signed-in user
* (`GET /auth/me/identities`). An agent whose policy names its owner is
* unreachable by that owner on any bridge missing from this list, so this is
* what the addressing UI checks before letting a policy seal an agent off.
+ * Only links that count are listed: one still waiting for its code is not.
*/
export async function fetchMyIdentities(server: SwitchServer): Promise<LinkedIdentity[]> {
const res = await gatewayFetch(server, '/auth/me/identities', { authenticated: true });
@@ -2356,6 +2491,41 @@ export async function fetchMyIdentities(server: SwitchServer): Promise<LinkedIde
bridge_type: string;
external_user_id: string;
external_username: string;
+ verified?: boolean;
+ }>;
+ return json.map((i) => ({
+ id: i.id,
+ bridgeId: i.bridge_id,
+ bridgeDisplayName: i.bridge_display_name,
+ bridgeType: i.bridge_type,
+ externalUserId: i.external_user_id,
+ externalUsername: i.external_username,
+ verified: i.verified ?? true,
+ }));
+}
+
+/**
+ * The messaging accounts waiting to confirm a link to the signed-in user
+ * (`GET /auth/me/identities/pending`). A server that predates confirming links
+ * has no such route and no such links, so its 404 reads as none.
+ */
+export async function fetchMyPendingIdentities(server: SwitchServer): Promise<PendingIdentity[]> {
+ let res: Response;
+ try {
+ res = await gatewayFetch(server, '/auth/me/identities/pending', { authenticated: true });
+ } catch (cause) {
+ if (cause instanceof GatewayError && cause.status === 404) return [];
+ throw cause;
+ }
+ const json = (await res.json()) as Array<{
+ id: string;
+ bridge_id: string;
+ bridge_display_name: string;
+ bridge_type: string;
+ external_user_id: string;
+ external_username: string;
+ requested_by_name: string | null;
+ code_expires_at: string | null;
}>;
return json.map((i) => ({
id: i.id,
@@ -2364,6 +2534,8 @@ export async function fetchMyIdentities(server: SwitchServer): Promise<LinkedIde
bridgeType: i.bridge_type,
externalUserId: i.external_user_id,
externalUsername: i.external_username,
+ requestedByName: i.requested_by_name,
+ codeExpiresAt: i.code_expires_at,
}));
}
diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/identities.test.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/identities.test.ts
new file mode 100644
index 000000000..e7a68d013
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/identities.test.ts
@@ -0,0 +1,321 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+/**
+ * Linking a messaging account, read off the wire (CHOO-3881).
+ *
+ * A current server holds a new link pending until a one-time code is posted
+ * from the account, and hands the code back with the claim. A server from
+ * before that links on the spot and sends no such field — Console talks to
+ * both, so a missing field has to read as the old behaviour, never as a
+ * pending link with no code.
+ */
+
+const getSessionCookie = vi.hoisted(() => vi.fn());
+
+vi.mock('@main/core/managed-switch-server/managed-server-status', () => ({
+ managedServerHostBlocked: vi.fn(() => null),
+ managedServerStoppedPhase: vi.fn(() => null),
+ noteManagedServerUnanswered: vi.fn(),
+}));
+vi.mock('./servers-store', () => ({ getSessionCookie, setSessionCookie: vi.fn() }));
+vi.mock('./auth', () => ({
+ refreshSession: vi.fn(),
+ reauthenticateManagedServer: vi.fn(),
+ extractAuthCookie: vi.fn(() => null),
+}));
+vi.mock('./console-identity', () => ({ consoleIdentityHeaders: async () => ({}) }));
+
+const {
+ cancelLinkRequestOnServer,
+ claimIdentityOnServer,
+ issueLinkCodeOnServer,
+ requireLinkConfirmationOnServer,
+} = await import('./identities');
+
+const SERVER = {
+ id: 'srv-1',
+ name: 'S',
+ url: 'https://switch.example.com',
+ managed: false,
+} as never;
+
+function validJwt(): string {
+ const header = Buffer.from(JSON.stringify({ alg: 'HS256', typ: 'JWT' })).toString('base64url');
+ const exp = Math.floor(Date.now() / 1000) + 24 * 60 * 60;
+ const payload = Buffer.from(JSON.stringify({ sub: 'u1', exp })).toString('base64url');
+ return `${header}.${payload}.sig`;
+}
+
+function response(status: number, body: unknown): Response {
+ return {
+ status,
+ ok: status >= 200 && status < 300,
+ json: async () => body,
+ headers: { get: () => null, getSetCookie: () => [] },
+ text: async () => JSON.stringify(body),
+ } as unknown as Response;
+}
+
+const BRIDGES = [{ bridge_id: 'b1', bridge_type: 'slack', display_name: 'Acme', status: 'active' }];
+
+const SUMMARY = {
+ id: 'eu-1',
+ bridge_id: 'b1',
+ external_user_id: 'U1',
+ external_username: 'ada',
+ claimed_by: [],
+};
+
+const CODE = {
+ code: '7KQ2-M9XD',
+ expires_at: '2026-10-27T12:30:00Z',
+ expires_in_seconds: 1800,
+ instructions: 'Post `!link-account 7KQ2-M9XD` from that account.',
+};
+
+const fetchMock = vi.fn();
+
+/** Answer the claim with `claim`, and the bridge list with `BRIDGES`. */
+function serve(claim: Response): void {
+ fetchMock.mockImplementation(async (url: string) =>
+ url.endsWith('/collaborations') ? response(200, BRIDGES) : claim
+ );
+}
+
+const PARAMS = { bridgeId: 'b1', externalUserId: 'U1', username: 'ada' };
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ vi.stubGlobal('fetch', fetchMock);
+ getSessionCookie.mockResolvedValue(validJwt());
+});
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+});
+
+describe('claimIdentityOnServer', () => {
+ it('says it can show a code, which a current server requires', async () => {
+ serve(response(200, SUMMARY));
+
+ await claimIdentityOnServer(SERVER, PARAMS);
+
+ const claim = fetchMock.mock.calls.find(([url]) => String(url).endsWith('/identities'));
+ expect(JSON.parse((claim![1] as { body: string }).body)).toEqual({
+ external_user_id: 'U1',
+ username: 'ada',
+ expects_confirmation: true,
+ });
+ });
+
+ it('comes back pending, carrying the code, when the server wants proof', async () => {
+ serve(response(200, { ...SUMMARY, link_request: { user_id: 'u1', code: CODE } }));
+
+ await expect(claimIdentityOnServer(SERVER, PARAMS)).resolves.toEqual({
+ kind: 'pending',
+ pending: {
+ id: 'eu-1',
+ bridgeId: 'b1',
+ bridgeDisplayName: 'Acme',
+ bridgeType: 'slack',
+ externalUserId: 'U1',
+ externalUsername: 'ada',
+ requestedByName: null,
+ codeExpiresAt: '2026-10-27T12:30:00Z',
+ },
+ code: {
+ code: '7KQ2-M9XD',
+ expiresAt: '2026-10-27T12:30:00Z',
+ expiresInSeconds: 1800,
+ instructions: 'Post `!link-account 7KQ2-M9XD` from that account.',
+ },
+ alreadyLinked: false,
+ });
+ });
+
+ it('says when the caller already holds an unconfirmed link to the account', async () => {
+ // Re-claiming an account linked before confirming existed asks for a code
+ // too, but that link works meanwhile — cancelling must not take it away.
+ serve(
+ response(200, {
+ ...SUMMARY,
+ claimed_by: [{ user_id: 'u1', user_name: 'Ada', verified: false }],
+ link_request: { user_id: 'u1', code: CODE },
+ })
+ );
+
+ await expect(claimIdentityOnServer(SERVER, PARAMS)).resolves.toMatchObject({
+ kind: 'pending',
+ alreadyLinked: true,
+ });
+ });
+
+ it('does not count someone else’s link to the account as the caller’s', async () => {
+ serve(
+ response(200, {
+ ...SUMMARY,
+ claimed_by: [{ user_id: 'u2', user_name: 'Grace', verified: true }],
+ link_request: { user_id: 'u1', code: CODE },
+ })
+ );
+
+ await expect(claimIdentityOnServer(SERVER, PARAMS)).resolves.toMatchObject({
+ alreadyLinked: false,
+ });
+ });
+
+ it('comes back pending without a code when the server issued none', async () => {
+ serve(response(200, { ...SUMMARY, link_request: { user_id: 'u1', code: null } }));
+
+ const result = await claimIdentityOnServer(SERVER, PARAMS);
+
+ expect(result).toMatchObject({ kind: 'pending', code: null });
+ });
+
+ it('is linked and confirmed when the server sends no request back', async () => {
+ // The account was already linked and confirmed: nothing to wait for.
+ serve(response(200, { ...SUMMARY, link_request: null }));
+
+ await expect(claimIdentityOnServer(SERVER, PARAMS)).resolves.toMatchObject({
+ kind: 'claimed',
+ identity: { id: 'eu-1', verified: true },
+ });
+ });
+
+ it('is linked at once by a server that predates confirming links', async () => {
+ serve(response(200, SUMMARY));
+
+ await expect(claimIdentityOnServer(SERVER, PARAMS)).resolves.toEqual({
+ kind: 'claimed',
+ identity: {
+ id: 'eu-1',
+ bridgeId: 'b1',
+ bridgeDisplayName: 'Acme',
+ bridgeType: 'slack',
+ externalUserId: 'U1',
+ externalUsername: 'ada',
+ verified: true,
+ },
+ });
+ });
+});
+
+describe('issueLinkCodeOnServer', () => {
+ it('returns the fresh code', async () => {
+ fetchMock.mockResolvedValue(response(200, CODE));
+
+ await expect(issueLinkCodeOnServer(SERVER, 'b1', 'eu-1')).resolves.toEqual({
+ kind: 'issued',
+ code: {
+ code: '7KQ2-M9XD',
+ expiresAt: '2026-10-27T12:30:00Z',
+ expiresInSeconds: 1800,
+ instructions: 'Post `!link-account 7KQ2-M9XD` from that account.',
+ },
+ });
+ const [url, init] = fetchMock.mock.calls[0] as [string, { method: string }];
+ expect(url).toBe('https://switch.example.com/gateway/collaborations/b1/identities/eu-1/code');
+ expect(init.method).toBe('POST');
+ });
+
+ it('reads a code from a server that sends no lifetime', async () => {
+ // Such a server's expiry can only be read off its own clock, `expires_at`.
+ const { expires_in_seconds: _lifetime, ...older } = CODE;
+ fetchMock.mockResolvedValue(response(200, older));
+
+ await expect(issueLinkCodeOnServer(SERVER, 'b1', 'eu-1')).resolves.toMatchObject({
+ code: { expiresAt: '2026-10-27T12:30:00Z', expiresInSeconds: null },
+ });
+ });
+
+ it('passes on the server’s reason when the link is already confirmed', async () => {
+ fetchMock.mockResolvedValue(
+ response(409, { detail: 'This account has already confirmed the link' })
+ );
+
+ await expect(issueLinkCodeOnServer(SERVER, 'b1', 'eu-1')).resolves.toEqual({
+ kind: 'refused',
+ message: 'This account has already confirmed the link',
+ });
+ });
+
+ it('passes on the server’s reason when there is nothing to confirm', async () => {
+ fetchMock.mockResolvedValue(
+ response(404, { detail: 'You have not started linking this account. Link it first.' })
+ );
+
+ await expect(issueLinkCodeOnServer(SERVER, 'b1', 'eu-1')).resolves.toEqual({
+ kind: 'refused',
+ message: 'You have not started linking this account. Link it first.',
+ });
+ });
+
+ it('throws on anything it cannot name', async () => {
+ fetchMock.mockResolvedValue(response(500, { detail: 'boom' }));
+
+ await expect(issueLinkCodeOnServer(SERVER, 'b1', 'eu-1')).rejects.toMatchObject({
+ status: 500,
+ });
+ });
+});
+
+describe('cancelLinkRequestOnServer', () => {
+ it('withdraws only the waiting request, never the link', async () => {
+ fetchMock.mockResolvedValue(response(200, SUMMARY));
+
+ await expect(cancelLinkRequestOnServer(SERVER, 'b1', 'eu-1')).resolves.toEqual({
+ kind: 'cancelled',
+ });
+ const [url, init] = fetchMock.mock.calls[0] as [string, { method: string }];
+ expect(url).toBe(
+ 'https://switch.example.com/gateway/collaborations/b1/identities/eu-1/request'
+ );
+ expect(init.method).toBe('DELETE');
+ });
+
+ it('passes on the server’s reason when nothing is waiting', async () => {
+ fetchMock.mockResolvedValue(response(404, { detail: 'Nothing is waiting to be confirmed' }));
+
+ await expect(cancelLinkRequestOnServer(SERVER, 'b1', 'eu-1')).resolves.toEqual({
+ kind: 'refused',
+ message: 'Nothing is waiting to be confirmed',
+ });
+ });
+
+ it('throws on anything it cannot name', async () => {
+ fetchMock.mockResolvedValue(response(500, { detail: 'boom' }));
+
+ await expect(cancelLinkRequestOnServer(SERVER, 'b1', 'eu-1')).rejects.toMatchObject({
+ status: 500,
+ });
+ });
+});
+
+describe('requireLinkConfirmationOnServer', () => {
+ it('says how many links now wait for their code', async () => {
+ fetchMock.mockResolvedValue(response(200, { moved: 2 }));
+
+ await expect(requireLinkConfirmationOnServer(SERVER, 'b1')).resolves.toEqual({
+ kind: 'required',
+ moved: 2,
+ });
+ });
+
+ it('passes on the server’s reason when the caller is not an admin', async () => {
+ fetchMock.mockResolvedValue(response(403, { detail: 'Workspace admin access required' }));
+
+ await expect(requireLinkConfirmationOnServer(SERVER, 'b1')).resolves.toEqual({
+ kind: 'refused',
+ message: 'Workspace admin access required',
+ });
+ });
+
+ it('passes on the server’s reason when the app is gone', async () => {
+ fetchMock.mockResolvedValue(response(404, { detail: 'Bridge not found' }));
+
+ await expect(requireLinkConfirmationOnServer(SERVER, 'b1')).resolves.toEqual({
+ kind: 'refused',
+ message: 'Bridge not found',
+ });
+ });
+});
diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/identities.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/identities.ts
index dd231daeb..c27c55f1f 100644
--- a/console/apps/switch-console-desktop/src/main/core/switch-servers/identities.ts
+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/identities.ts
@@ -1,13 +1,20 @@
import {
+ cancelIdentityLinkRequest,
claimBridgeIdentity,
fetchBridges,
GatewayError,
+ issueIdentityLinkCode,
+ mapLinkCode,
+ requireLinkConfirmation,
searchBridgeDirectory,
} from '@main/core/switch-servers/gateway-client';
import type {
BridgeDirectorySearchResult,
+ CancelLinkRequestResult,
ClaimIdentityParams,
ClaimIdentityResult,
+ IssueLinkCodeResult,
+ RequireLinkConfirmationResult,
SwitchServer,
} from '@shared/core/switch-servers/switch-servers';
@@ -60,8 +67,14 @@ export async function searchDirectoryOnServer(
/**
* Claim a directory entry as the signed-in user's own account, resolving the
- * bridge's display name so the caller gets a complete `LinkedIdentity` rather
- * than a row it has to name itself.
+ * bridge's display name so the caller gets a complete row rather than one it
+ * has to name itself.
+ *
+ * A current server leaves the link pending until a code is posted from the
+ * account, and answers with that code; one that predates confirming links, or a
+ * link already confirmed, comes back claimed. Claiming an account the caller
+ * already holds an unconfirmed link to also comes back pending, and says so:
+ * that link works meanwhile, and cancelling must leave it standing.
*
* Nothing here refuses an account other people have claimed — the server
* allows it, and each claimant is recognised as themselves on the account.
@@ -76,25 +89,34 @@ export async function claimIdentityOnServer(
username: params.username,
});
const bridge = (await fetchBridges(server)).find((b) => b.id === claimed.bridge_id);
- return {
- kind: 'claimed',
- identity: {
- id: claimed.id,
- bridgeId: claimed.bridge_id,
- // A bridge deleted between the claim and this read leaves nothing to
- // name it by; its id still identifies the row rather than hiding it.
- bridgeDisplayName: bridge?.displayName ?? claimed.bridge_id,
- bridgeType: bridge?.type ?? '',
- externalUserId: claimed.external_user_id,
- externalUsername: claimed.external_username,
- },
+ const row = {
+ id: claimed.id,
+ bridgeId: claimed.bridge_id,
+ // A bridge deleted between the claim and this read leaves nothing to
+ // name it by; its id still identifies the row rather than hiding it.
+ bridgeDisplayName: bridge?.displayName ?? claimed.bridge_id,
+ bridgeType: bridge?.type ?? '',
+ externalUserId: claimed.external_user_id,
+ externalUsername: claimed.external_username,
};
+ const request = claimed.link_request ?? null;
+ if (request !== null) {
+ const code = request.code === null ? null : mapLinkCode(request.code);
+ return {
+ kind: 'pending',
+ pending: { ...row, requestedByName: null, codeExpiresAt: code?.expiresAt ?? null },
+ code,
+ alreadyLinked: (claimed.claimed_by ?? []).some((c) => c.user_id === request.user_id),
+ };
+ }
+ return { kind: 'claimed', identity: { ...row, verified: true } };
} catch (cause) {
if (cause instanceof GatewayError) {
if (cause.kind === 'unauthorized') return { kind: 'unauthenticated' };
// 409 — the bridge is not running, so an account Switch has never seen
- // cannot be provisioned. Claiming an account someone else has claimed is
- // not a conflict: claims are not exclusive.
+ // cannot be provisioned; or the account is a platform stand-in nobody
+ // can link. The server's wording says which. Claiming an account someone
+ // else has claimed is not a conflict: claims are not exclusive.
if (cause.kind === 'http' && cause.status === 409) {
return { kind: 'bridge-unavailable', message: cause.detail ?? cause.message };
}
@@ -103,3 +125,75 @@ export async function claimIdentityOnServer(
throw cause;
}
}
+
+/**
+ * A fresh code confirming the signed-in user's link to an account, replacing
+ * any issued before. 404 (nothing to confirm — the link was cancelled) and 409
+ * (already confirmed, or an account nobody can link) are the server's to word.
+ */
+export async function issueLinkCodeOnServer(
+ server: SwitchServer,
+ bridgeId: string,
+ identityId: string
+): Promise<IssueLinkCodeResult> {
+ try {
+ return { kind: 'issued', code: await issueIdentityLinkCode(server, bridgeId, identityId) };
+ } catch (cause) {
+ if (cause instanceof GatewayError) {
+ if (cause.kind === 'unauthorized') return { kind: 'unauthenticated' };
+ if (cause.kind === 'http' && (cause.status === 404 || cause.status === 409)) {
+ return { kind: 'refused', message: cause.detail ?? cause.message };
+ }
+ if (cause.kind === 'network') return { kind: 'error', message: cause.message };
+ }
+ throw cause;
+ }
+}
+
+/**
+ * Withdraw the signed-in user's confirmation waiting on a code, leaving any link
+ * that already works in place. 404 — nothing is waiting, because it was
+ * confirmed or cancelled meanwhile — is the server's to word.
+ */
+export async function cancelLinkRequestOnServer(
+ server: SwitchServer,
+ bridgeId: string,
+ identityId: string
+): Promise<CancelLinkRequestResult> {
+ try {
+ await cancelIdentityLinkRequest(server, bridgeId, identityId);
+ return { kind: 'cancelled' };
+ } catch (cause) {
+ if (cause instanceof GatewayError) {
+ if (cause.kind === 'unauthorized') return { kind: 'unauthenticated' };
+ if (cause.kind === 'http' && cause.status === 404) {
+ return { kind: 'refused', message: cause.detail ?? cause.message };
+ }
+ if (cause.kind === 'network') return { kind: 'error', message: cause.message };
+ }
+ throw cause;
+ }
+}
+
+/**
+ * Require confirmation of a messaging app's older links. 403 — the caller is
+ * not an admin of the workspace — and 404 — the app is gone, or the server
+ * predates this — are the server's to word.
+ */
+export async function requireLinkConfirmationOnServer(
+ server: SwitchServer,
+ bridgeId: string
+): Promise<RequireLinkConfirmationResult> {
+ try {
+ return { kind: 'required', moved: await requireLinkConfirmation(server, bridgeId) };
+ } catch (cause) {
+ if (cause instanceof GatewayError) {
+ if (cause.kind === 'unauthorized') return { kind: 'unauthenticated' };
+ if (cause.kind === 'http' && (cause.status === 403 || cause.status === 404)) {
+ return { kind: 'refused', message: cause.detail ?? cause.message };
+ }
+ if (cause.kind === 'network') return { kind: 'error', message: cause.message };
+ }
+ throw cause;
+ }
+}
diff --git a/console/apps/switch-console-desktop/src/main/core/telemetry/events.ts b/console/apps/switch-console-desktop/src/main/core/telemetry/events.ts
index 5b83fa194..5fe4c3dc9 100644
--- a/console/apps/switch-console-desktop/src/main/core/telemetry/events.ts
+++ b/console/apps/switch-console-desktop/src/main/core/telemetry/events.ts
@@ -191,6 +191,24 @@ export type TelemetryUpdateTrigger = 'user' | 'startup' | 'scheduled';
export type TelemetryBridgeFailure = 'none' | 'unauthenticated' | 'forbidden' | 'invalid' | 'error';
+/**
+ * How linking a messaging account came out. `pending` is a link the server is
+ * holding until a one-time code is posted from the account, which counts for
+ * nothing yet — reported apart from `success` so the links that are never
+ * confirmed stay visible. A server that predates confirming links answers
+ * `success` straight away.
+ */
+export type TelemetryIdentityClaimOutcome = 'success' | 'pending' | 'failure';
+
+/**
+ * Which link a confirmation finished. `new` was claimed and waiting on its
+ * code, so it follows a `pending` claim; `existing` was made before links had to
+ * be confirmed and counted all along. Kept apart so confirmations can be read
+ * against the claims that were waiting for them. `unknown` when the caller did
+ * not say.
+ */
+export type TelemetryIdentityLinkKind = 'new' | 'existing' | 'unknown';
+
export type TelemetryRoomCreateFailure =
| 'none'
| 'unauthenticated'
@@ -392,7 +410,16 @@ export type TelemetryEventMap = {
/** Someone linked their account on a messaging platform to their Switch user. */
bridge_identity_claimed: {
bridge_platform: TelemetryBridgePlatform;
- outcome: TelemetryOutcome;
+ outcome: TelemetryIdentityClaimOutcome;
+ };
+ /**
+ * A link was confirmed by posting its one-time code from the account. Only
+ * the confirmation screen sees this happen, and the server is asked before it
+ * is reported.
+ */
+ bridge_identity_confirmed: {
+ bridge_platform: TelemetryBridgePlatform;
+ link_kind: TelemetryIdentityLinkKind;
};
/**
* An agent was removed. `delete_in_switch` says whether its identity on the
@@ -632,6 +659,7 @@ export const TELEMETRY_EVENT_PROPERTIES = {
bridge_connected: ['bridge_platform', 'outcome', 'failure_reason'],
bridge_disconnected: ['bridge_platform', 'outcome'],
bridge_identity_claimed: ['bridge_platform', 'outcome'],
+ bridge_identity_confirmed: ['bridge_platform', 'link_kind'],
agent_removed: [
'agent_type',
'location',
diff --git a/console/apps/switch-console-desktop/src/main/core/telemetry/narrow.ts b/console/apps/switch-console-desktop/src/main/core/telemetry/narrow.ts
index bc9d4eb4a..5d5642d9e 100644
--- a/console/apps/switch-console-desktop/src/main/core/telemetry/narrow.ts
+++ b/console/apps/switch-console-desktop/src/main/core/telemetry/narrow.ts
@@ -10,6 +10,7 @@ import {
import type {
TelemetryAgentRemoveTrigger,
TelemetryEntryPoint,
+ TelemetryIdentityLinkKind,
TelemetryInstallMethod,
TelemetryRoomAgentsDirection,
TelemetrySessionProvisionTrigger,
@@ -76,3 +77,13 @@ export function updateTriggerOf(value: unknown): TelemetryUpdateTrigger {
export function installMethodOf(value: unknown): TelemetryInstallMethod {
return oneOf<TelemetryInstallMethod>([...INSTALL_METHODS, 'unspecified'], value, 'unspecified');
}
+
+/**
+ * The confirmation screen's own name for the link it waited on: `pending` is a
+ * new link, `unverified` one made before links had to be confirmed.
+ */
+export function identityLinkKindOf(value: unknown): TelemetryIdentityLinkKind {
+ if (value === 'pending') return 'new';
+ if (value === 'unverified') return 'existing';
+ return 'unknown';
+}
diff --git a/console/apps/switch-console-desktop/src/main/core/workspaces/controller.test.ts b/console/apps/switch-console-desktop/src/main/core/workspaces/controller.test.ts
index 552af2657..6e00b08b9 100644
--- a/console/apps/switch-console-desktop/src/main/core/workspaces/controller.test.ts
+++ b/console/apps/switch-console-desktop/src/main/core/workspaces/controller.test.ts
@@ -18,6 +18,11 @@ const runTemplateWithAgents = vi.hoisted(() => vi.fn());
const runTemplateDocument = vi.hoisted(() => vi.fn());
const fetchRoomDetail = vi.hoisted(() => vi.fn());
const fetchManagedAgent = vi.hoisted(() => vi.fn());
+const claimIdentityOnServer = vi.hoisted(() => vi.fn());
+const cancelLinkRequestOnServer = vi.hoisted(() => vi.fn());
+const fetchMyIdentities = vi.hoisted(() => vi.fn());
+const fetchUnconfirmedLinks = vi.hoisted(() => vi.fn());
+const requireLinkConfirmationOnServer = vi.hoisted(() => vi.fn());
const managedAgentLocator = vi.hoisted(() =>
vi.fn(async () => (controllerId: string) => (controllerId === 'c1' ? 'local' : 'remote'))
);
@@ -90,7 +95,10 @@ vi.mock('@main/core/switch-servers/disconnect-bridge', () => ({
bridgeInstallState,
}));
vi.mock('@main/core/switch-servers/identities', () => ({
- claimIdentityOnServer: vi.fn(),
+ cancelLinkRequestOnServer,
+ claimIdentityOnServer,
+ issueLinkCodeOnServer: vi.fn(),
+ requireLinkConfirmationOnServer,
searchDirectoryOnServer: vi.fn(),
}));
vi.mock('@main/core/switch-servers/teams-package', () => ({ saveTeamsPackage }));
@@ -115,7 +123,9 @@ vi.mock('@main/core/switch-servers/gateway-client', () => ({
fetchBridgeTypes: vi.fn(),
fetchConnectionAgents,
fetchWorkspaceServices,
- fetchMyIdentities: vi.fn(),
+ fetchMyIdentities,
+ fetchMyPendingIdentities: vi.fn(),
+ fetchUnconfirmedLinks,
fetchRoomAgentIds: vi.fn(),
fetchManagedAgent,
fetchRoomDetail,
@@ -209,6 +219,158 @@ describe('disconnecting a bridge', () => {
});
});
+describe('linking a messaging account', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ managedServerHostBlocked.mockReturnValue(null);
+ getServer.mockResolvedValue(server({}));
+ requireWorkspace.mockResolvedValue(workspace());
+ fetchBridges.mockResolvedValue([{ id: 'b1', type: 'slack' }]);
+ });
+
+ const PARAMS = { workspaceId: 'ws', bridgeId: 'b1', externalUserId: 'U1', username: 'ada' };
+
+ it('reports a link waiting for its code apart from one that took effect', async () => {
+ // A pending link counts for nothing until the code is posted; filing it
+ // under success would hide every link that is never confirmed.
+ claimIdentityOnServer.mockResolvedValue({ kind: 'pending', pending: {}, code: null });
+
+ await workspacesController.claimBridgeIdentity(PARAMS);
+
+ await vi.waitFor(() =>
+ expect(trackEvent).toHaveBeenCalledWith('bridge_identity_claimed', {
+ bridge_platform: 'slack',
+ outcome: 'pending',
+ })
+ );
+ });
+
+ it('reports a link that took effect at once as a success', async () => {
+ claimIdentityOnServer.mockResolvedValue({ kind: 'claimed', identity: {} });
+
+ await workspacesController.claimBridgeIdentity(PARAMS);
+
+ await vi.waitFor(() =>
+ expect(trackEvent).toHaveBeenCalledWith('bridge_identity_claimed', {
+ bridge_platform: 'slack',
+ outcome: 'success',
+ })
+ );
+ });
+
+ it('cancels a waiting confirmation through the request-only route', async () => {
+ // The full unlink would also drop a link made before confirming, which
+ // works today; Cancel must only ever withdraw the code.
+ cancelLinkRequestOnServer.mockResolvedValue({ kind: 'cancelled' });
+
+ await expect(
+ workspacesController.cancelIdentityLinkRequest({
+ workspaceId: 'ws',
+ bridgeId: 'b1',
+ identityId: 'eu-1',
+ })
+ ).resolves.toEqual({ kind: 'cancelled' });
+
+ expect(cancelLinkRequestOnServer).toHaveBeenCalledWith(expect.anything(), 'b1', 'eu-1');
+ });
+
+ describe('a confirmation the screen saw', () => {
+ const CONFIRMED = { id: 'eu-1', bridgeId: 'b1', bridgeType: 'slack', verified: true };
+ const REPORT = { workspaceId: 'ws', bridgeId: 'b1', identityId: 'eu-1', kind: 'pending' };
+
+ it('is reported once the server agrees the link is confirmed', async () => {
+ fetchMyIdentities.mockResolvedValue([CONFIRMED]);
+
+ await workspacesController.reportIdentityConfirmed(REPORT);
+
+ expect(trackEvent).toHaveBeenCalledWith('bridge_identity_confirmed', {
+ bridge_platform: 'slack',
+ link_kind: 'new',
+ });
+ });
+
+ it('names a link made before confirming as existing', async () => {
+ fetchMyIdentities.mockResolvedValue([CONFIRMED]);
+
+ await workspacesController.reportIdentityConfirmed({ ...REPORT, kind: 'unverified' });
+
+ expect(trackEvent).toHaveBeenCalledWith('bridge_identity_confirmed', {
+ bridge_platform: 'slack',
+ link_kind: 'existing',
+ });
+ });
+
+ it('reports a kind it does not recognise as unknown rather than passing it on', async () => {
+ fetchMyIdentities.mockResolvedValue([CONFIRMED]);
+
+ await workspacesController.reportIdentityConfirmed({ ...REPORT, kind: 'whatever' });
+
+ expect(trackEvent).toHaveBeenCalledWith('bridge_identity_confirmed', {
+ bridge_platform: 'slack',
+ link_kind: 'unknown',
+ });
+ });
+
+ it('is not reported when the server does not list the link as confirmed', async () => {
+ fetchMyIdentities.mockResolvedValue([{ ...CONFIRMED, verified: false }]);
+
+ await workspacesController.reportIdentityConfirmed(REPORT);
+
+ expect(trackEvent).not.toHaveBeenCalled();
+ });
+
+ it('asks the server nothing while sharing is off', async () => {
+ canSend.mockResolvedValueOnce(false);
+
+ await workspacesController.reportIdentityConfirmed(REPORT);
+
+ expect(fetchMyIdentities).not.toHaveBeenCalled();
+ expect(trackEvent).not.toHaveBeenCalled();
+ });
+
+ it('never fails, even when the server cannot be read', async () => {
+ fetchMyIdentities.mockRejectedValue(new Error('unreachable'));
+
+ await expect(workspacesController.reportIdentityConfirmed(REPORT)).resolves.toBeUndefined();
+ expect(trackEvent).not.toHaveBeenCalled();
+ });
+ });
+
+ it('lists one app’s older links from its server', async () => {
+ const LINKS = [
+ { id: 'eu-1', externalUserId: 'U1', externalUsername: 'ada', userId: 'u1', userName: 'Ada' },
+ ];
+ fetchUnconfirmedLinks.mockResolvedValue(LINKS);
+
+ await expect(
+ workspacesController.listUnconfirmedLinks({ workspaceId: 'ws', bridgeId: 'b1' })
+ ).resolves.toEqual(LINKS);
+ expect(fetchUnconfirmedLinks).toHaveBeenCalledWith(expect.anything(), 'b1');
+ });
+
+ it('requires confirming one app’s older links', async () => {
+ requireLinkConfirmationOnServer.mockResolvedValue({ kind: 'required', moved: 2 });
+
+ await expect(
+ workspacesController.requireLinkConfirmation({ workspaceId: 'ws', bridgeId: 'b1' })
+ ).resolves.toEqual({ kind: 'required', moved: 2 });
+ expect(requireLinkConfirmationOnServer).toHaveBeenCalledWith(expect.anything(), 'b1');
+ });
+
+ it('reports a refused claim as a failure', async () => {
+ claimIdentityOnServer.mockResolvedValue({ kind: 'bridge-unavailable', message: 'stopped' });
+
+ await workspacesController.claimBridgeIdentity(PARAMS);
+
+ await vi.waitFor(() =>
+ expect(trackEvent).toHaveBeenCalledWith('bridge_identity_claimed', {
+ bridge_platform: 'slack',
+ outcome: 'failure',
+ })
+ );
+ });
+});
+
describe('deleting a room', () => {
beforeEach(() => {
vi.clearAllMocks();
diff --git a/console/apps/switch-console-desktop/src/main/core/workspaces/controller.ts b/console/apps/switch-console-desktop/src/main/core/workspaces/controller.ts
index 1dc9012c0..b4198d4d9 100644
--- a/console/apps/switch-console-desktop/src/main/core/workspaces/controller.ts
+++ b/console/apps/switch-console-desktop/src/main/core/workspaces/controller.ts
@@ -39,6 +39,8 @@ import {
fetchManagedAgent,
fetchMessagingApps,
fetchMyIdentities,
+ fetchMyPendingIdentities,
+ fetchUnconfirmedLinks,
fetchRoomAgentIds,
fetchRoomDetail,
fetchRoomGroups,
@@ -80,7 +82,10 @@ import {
updateTemplate,
} from '@main/core/switch-servers/gateway-client';
import {
+ cancelLinkRequestOnServer,
claimIdentityOnServer,
+ issueLinkCodeOnServer,
+ requireLinkConfirmationOnServer,
searchDirectoryOnServer,
} from '@main/core/switch-servers/identities';
import { hostUnreachable } from '@main/core/switch-servers/require-server';
@@ -97,13 +102,18 @@ import { bridgePlatformOfType } from '@main/core/telemetry/bridge-platform';
import type {
TelemetryBridgeFailure,
TelemetryBridgePlatform,
+ TelemetryIdentityClaimOutcome,
TelemetryOutcome,
TelemetryRoomAgentsDirection,
TelemetryRoomCreateFailure,
TelemetryRoomCreateSource,
TelemetryServerKind,
} from '@main/core/telemetry/events';
-import { entryPointOf, roomAgentsDirectionOf } from '@main/core/telemetry/narrow';
+import {
+ entryPointOf,
+ identityLinkKindOf,
+ roomAgentsDirectionOf,
+} from '@main/core/telemetry/narrow';
import { telemetryService, trackEvent, trackEventAt } from '@main/core/telemetry/telemetry-service';
import { log } from '@main/lib/logger';
import type {
@@ -119,6 +129,7 @@ import type {
AgentIconBackfill,
AgentVerifyResult,
BridgeDirectorySearchResult,
+ CancelLinkRequestResult,
ChatClaim,
ClaimIdentityParams,
ConnectedChat,
@@ -129,8 +140,12 @@ import type {
CreateRoomResult,
DeleteBridgeParams,
DeleteBridgeResult,
+ IssueLinkCodeResult,
LinkedIdentity,
MessagingApps,
+ PendingIdentity,
+ RequireLinkConfirmationResult,
+ UnconfirmedLink,
RemoteAgentRoom,
RemoteAgentSummary,
RemoteBridge,
@@ -994,7 +1009,9 @@ export const workspacesController = createRPCController({
searchDirectoryOnServer(server, params.bridgeId, params.query)
),
- /** Claim a messaging-app account as the signed-in Switch user's own. */
+ /** Claim a messaging-app account as the signed-in Switch user's own. A
+ * current server holds the link pending until a code is posted from the
+ * account, and the result carries that code. */
claimBridgeIdentity: async (params: ClaimIdentityParams): Promise<ClaimIdentityResult> => {
const result = await withReachableWorkspaceSession(params.workspaceId, (server) =>
claimIdentityOnServer(server, {
@@ -1003,27 +1020,105 @@ export const workspacesController = createRPCController({
username: params.username,
})
);
+ const outcome: TelemetryIdentityClaimOutcome =
+ result.kind === 'claimed' ? 'success' : result.kind === 'pending' ? 'pending' : 'failure';
// Reported after the lease, not inside it: the platform lookup takes a lease
// of its own, and the bridge is still there to read afterwards.
reportWithBridge(bridgePlatformOf(params.workspaceId, params.bridgeId), (bridge_platform, at) =>
+ trackEventAt('bridge_identity_claimed', { bridge_platform, outcome }, at)
+ );
+ return result;
+ },
+
+ /** A fresh code confirming the signed-in user's link to a messaging-app
+ * account — one still pending, or one made before links had to be confirmed.
+ * Replaces any code issued before. */
+ issueIdentityLinkCode: (params: {
+ workspaceId: string;
+ bridgeId: string;
+ identityId: string;
+ }): Promise<IssueLinkCodeResult> =>
+ withReachableWorkspaceSession(params.workspaceId, (server) =>
+ issueLinkCodeOnServer(server, params.bridgeId, params.identityId)
+ ),
+
+ /**
+ * Report that a link the confirmation screen was waiting on is confirmed.
+ *
+ * The code is posted in the chat app, so the screen watching for it is the
+ * only thing that sees this happen; it says so, and `kind` is its own name for
+ * the link. The server is asked before anything is reported, so a screen that
+ * is wrong reports nothing — and nothing at all is asked while sharing is off.
+ * Never fails: a report that cannot be made is logged and dropped.
+ */
+ reportIdentityConfirmed: async (params: {
+ workspaceId: string;
+ bridgeId: string;
+ identityId: string;
+ kind: string;
+ }): Promise<void> => {
+ const at = Date.now();
+ try {
+ if (!(await telemetryService.canSend())) return;
+ const identities = await withWorkspaceSession(params.workspaceId, fetchMyIdentities);
+ const confirmed = identities.find(
+ (i) => i.id === params.identityId && i.bridgeId === params.bridgeId && i.verified
+ );
+ if (confirmed === undefined) return;
trackEventAt(
- 'bridge_identity_claimed',
+ 'bridge_identity_confirmed',
{
- bridge_platform,
- outcome: result.kind === 'claimed' ? 'success' : 'failure',
+ bridge_platform: bridgePlatformOfType(confirmed.bridgeType),
+ link_kind: identityLinkKindOf(params.kind),
},
at
- )
- );
- return result;
+ );
+ } catch (error) {
+ log.warn('A confirmed link could not be checked to report it', {
+ event: 'telemetry_identity_confirmed',
+ errorCode: error instanceof GatewayError ? error.kind : 'error',
+ error: String(error),
+ });
+ }
},
- /** Give up a claim on a messaging-app account, leaving any other user's claim
- * on it in place. `userId` is whose claim to drop — null for the signed-in
- * user, which is the only one this app offers. Failures propagate: unclaiming
- * is a deliberate act, and reporting success for one that did not happen
- * would leave the user thinking an agent is no longer reachable by them when
- * it still is. */
+ /** The links on a messaging app made before links had to be confirmed, which
+ * still count. Admin only; empty on a server that predates them. */
+ listUnconfirmedLinks: (params: {
+ workspaceId: string;
+ bridgeId: string;
+ }): Promise<UnconfirmedLink[]> =>
+ withWorkspaceSession(params.workspaceId, (server) =>
+ fetchUnconfirmedLinks(server, params.bridgeId)
+ ),
+
+ /** Stop trusting a messaging app's older links until each owner confirms
+ * theirs with a code. Admin only. */
+ requireLinkConfirmation: (params: {
+ workspaceId: string;
+ bridgeId: string;
+ }): Promise<RequireLinkConfirmationResult> =>
+ withReachableWorkspaceSession(params.workspaceId, (server) =>
+ requireLinkConfirmationOnServer(server, params.bridgeId)
+ ),
+
+ /** Withdraw the signed-in user's confirmation waiting on a code. A link that
+ * already works stays; unlinking is {@link releaseBridgeIdentity}. */
+ cancelIdentityLinkRequest: (params: {
+ workspaceId: string;
+ bridgeId: string;
+ identityId: string;
+ }): Promise<CancelLinkRequestResult> =>
+ withReachableWorkspaceSession(params.workspaceId, (server) =>
+ cancelLinkRequestOnServer(server, params.bridgeId, params.identityId)
+ ),
+
+ /** Give up a claim on a messaging-app account, along with any confirmation
+ * waiting on it, leaving any other user's claim on it in place. `userId` is
+ * whose claim to drop — null for the signed-in user, which is the only one
+ * this app offers. Failures propagate: unclaiming is a deliberate act, and
+ * reporting success for one that did not happen would leave the user thinking
+ * an agent is no longer reachable by them when it still is. */
releaseBridgeIdentity: (params: {
workspaceId: string;
bridgeId: string;
@@ -1034,10 +1129,17 @@ export const workspacesController = createRPCController({
releaseBridgeIdentity(server, params.bridgeId, params.identityId, params.userId)
),
- /** The messaging accounts the signed-in user has claimed in this workspace. */
+ /** The messaging accounts linked to the signed-in user in this workspace —
+ * only links that count; see {@link listMyPendingIdentities} for the rest. */
listMyIdentities: (workspaceId: string): Promise<LinkedIdentity[]> =>
withWorkspaceSession(workspaceId, fetchMyIdentities),
+ /** The messaging accounts waiting for a code to confirm a link to the
+ * signed-in user in this workspace. Empty on a server that predates
+ * confirming links. */
+ listMyPendingIdentities: (workspaceId: string): Promise<PendingIdentity[]> =>
+ withWorkspaceSession(workspaceId, fetchMyPendingIdentities),
+
/** Whether the signed-in user owns an agent here that is set to answer its
* owner, which is what makes an unlinked messaging account worth warning
* about. One agent-list read, so callers need not ration it. */
diff --git a/console/apps/switch-console-desktop/src/renderer/app/modal-registry.ts b/console/apps/switch-console-desktop/src/renderer/app/modal-registry.ts
index c6f868f65..546efd536 100644
--- a/console/apps/switch-console-desktop/src/renderer/app/modal-registry.ts
+++ b/console/apps/switch-console-desktop/src/renderer/app/modal-registry.ts
@@ -33,6 +33,7 @@ import { DeleteServerModal } from '@renderer/features/switch-servers/DeleteServe
import { DisconnectMessagingAppModal } from '@renderer/features/switch-servers/DisconnectMessagingAppModal';
import { RenameServerModal } from '@renderer/features/switch-servers/RenameServerModal';
import { ReplaceTokenModal } from '@renderer/features/switch-servers/ReplaceTokenModal';
+import { RequireLinkConfirmationModal } from '@renderer/features/switch-servers/RequireLinkConfirmationModal';
import { TeamsPlacementModal } from '@renderer/features/switch-servers/TeamsPlacementModal';
import { SaveTemplateModal } from '@renderer/features/templates/save-template-modal';
import { CreateWorkspaceModal } from '@renderer/features/workspaces/create-workspace-modal';
@@ -122,6 +123,10 @@ export const modalRegistry = {
size: 'md',
dismissOnOutsideClick: false,
}),
+ requireLinkConfirmationModal: createModal(RequireLinkConfirmationModal, {
+ size: 'md',
+ dismissOnOutsideClick: false,
+ }),
bundledChatSignInModal: createModal(BundledChatSignInModal, { size: 'sm' }),
disconnectMessagingAppModal: createModal(DisconnectMessagingAppModal, {
size: 'sm',
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/ClaimIdentityModal.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/ClaimIdentityModal.tsx
index 26ecb665a..73bcd5c75 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/ClaimIdentityModal.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/ClaimIdentityModal.tsx
@@ -1,6 +1,7 @@
import { useQuery } from '@tanstack/react-query';
import { Info } from 'lucide-react';
import { observer } from 'mobx-react-lite';
+import { useState } from 'react';
import { bridgePlatformLabel } from '@renderer/lib/components/bridge-platform';
import { rpc } from '@renderer/lib/ipc';
import { type BaseModalProps, useModalContext } from '@renderer/lib/modal/modal-provider';
@@ -11,8 +12,10 @@ import {
DialogHeader,
DialogTitle,
} from '@renderer/lib/ui/dialog';
-import type { LinkedIdentity } from '@shared/core/switch-servers/switch-servers';
+import type { LinkCode, LinkedIdentity } from '@shared/core/switch-servers/switch-servers';
+import { AccountLinkConfirmation, type AccountLinkTarget } from './account-link-confirmation';
import { BridgeIdentitySearch } from './bridge-identity-search';
+import { linkedIdentityOn } from './messaging-apps-warning';
import { useMyIdentities } from './use-my-identities';
type ClaimIdentityModalArgs = {
@@ -22,6 +25,10 @@ type ClaimIdentityModalArgs = {
workspaceId: string;
/** The messaging app to claim an account in. */
bridgeId: string;
+ /** Open on a link that is waiting for its code — a pending one, or one made
+ * before links had to be confirmed — rather than on the search. A fresh code
+ * is asked for on open, since the server keeps none to show again. */
+ confirm?: AccountLinkTarget;
};
type Props = BaseModalProps<{ identity: LinkedIdentity }> & ClaimIdentityModalArgs;
@@ -38,10 +45,15 @@ type Props = BaseModalProps<{ identity: LinkedIdentity }> & ClaimIdentityModalAr
* The search goes to the platform's own directory rather than Switch's record
* of who has spoken, so a user can find themselves in a workspace they have
* never posted in.
+ *
+ * Saying "this is me" proves nothing, so on a current server the link then
+ * waits for a one-time code posted from the account (CHOO-3881), and the
+ * dialog stays open on that code until it is.
*/
export const ClaimIdentityModal = observer(function ClaimIdentityModal({
workspaceId,
bridgeId,
+ confirm,
onSuccess,
onClose,
}: Props) {
@@ -50,6 +62,10 @@ export const ClaimIdentityModal = observer(function ClaimIdentityModal({
const { hasActiveCloseGuard } = useModalContext();
const { identities } = useMyIdentities(workspaceId);
+ const [waiting, setWaiting] = useState<{
+ target: AccountLinkTarget;
+ code: LinkCode | null;
+ } | null>(confirm ? { target: confirm, code: null } : null);
const bridgesQuery = useQuery({
queryKey: ['remote-bridges', workspaceId],
@@ -64,14 +80,48 @@ export const ClaimIdentityModal = observer(function ClaimIdentityModal({
// Not while re-reading: straight after an app is added the cached list does
// not have it yet.
const bridgeIsGone = !bridgesQuery.isFetching && bridges.length > 0 && selectedBridge === null;
- const alreadyLinked = (identities ?? []).find((i) => i.bridgeId === bridgeId) ?? null;
+ const alreadyLinked = identities === null ? null : linkedIdentityOn(bridgeId, identities);
+
+ const platform = bridgePlatformLabel(selectedBridge?.type);
+ const bridgeDisplayName = selectedBridge?.displayName ?? 'the workspace';
+
+ if (waiting !== null) {
+ return (
+ <>
+ <DialogHeader showCloseButton={false}>
+ <DialogTitle>Confirm your {platform} account</DialogTitle>
+ </DialogHeader>
+ <DialogContentArea className="pt-0">
+ <AccountLinkConfirmation
+ // A new target is a new code to wait on, not this one renamed.
+ key={waiting.target.identityId}
+ workspaceId={workspaceId}
+ bridgeId={bridgeId}
+ bridgeDisplayName={bridgeDisplayName}
+ target={waiting.target}
+ initialCode={waiting.code}
+ onConfirmed={(identity) => onSuccess({ identity })}
+ // Back to the search when it was reached from there — the likeliest
+ // reason to cancel is having picked the wrong account.
+ onCancelled={() => (confirm ? onClose() : setWaiting(null))}
+ onStartAgain={() => setWaiting(null)}
+ />
+ </DialogContentArea>
+ <DialogFooter>
+ {/* Closing is not cancelling: a pending link waits, and the app's row
+ on the server page offers a new code for it. */}
+ <Button variant="outline" onClick={onClose} disabled={hasActiveCloseGuard}>
+ Close
+ </Button>
+ </DialogFooter>
+ </>
+ );
+ }
return (
<>
<DialogHeader showCloseButton={false}>
- <DialogTitle>
- Link your {bridgePlatformLabel(selectedBridge?.type)} user account
- </DialogTitle>
+ <DialogTitle>Link your {platform} user account</DialogTitle>
</DialogHeader>
<DialogContentArea className="pt-0">
<div className="flex w-full flex-col gap-5">
@@ -100,11 +150,12 @@ export const ClaimIdentityModal = observer(function ClaimIdentityModal({
<BridgeIdentitySearch
workspaceId={workspaceId}
bridgeId={bridgeId}
- bridgeDisplayName={selectedBridge?.displayName ?? 'the workspace'}
+ bridgeDisplayName={bridgeDisplayName}
platform={bridgePlatformLabel(selectedBridge?.type ?? '')}
directorySearchSupported={selectedBridge?.directorySearchSupported ?? true}
autoFocus
onClaimed={(identity) => onSuccess({ identity })}
+ onConfirmationNeeded={(target, code) => setWaiting({ target, code })}
/>
</div>
</DialogContentArea>
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/MessagingAppsCard.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/MessagingAppsCard.tsx
index e8e86623a..709571ed5 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/MessagingAppsCard.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/MessagingAppsCard.tsx
@@ -1,6 +1,7 @@
import { useQueries, useQueryClient, useQuery } from '@tanstack/react-query';
import {
CircleAlert,
+ Clock,
Copy,
ExternalLink,
Info,
@@ -11,10 +12,13 @@ import {
MoreVertical,
Plus,
PlusCircle,
+ ShieldAlert,
+ ShieldCheck,
Trash2,
TriangleAlert,
Unlink,
Users,
+ X,
} from 'lucide-react';
import { observer } from 'mobx-react-lite';
import { Fragment, useEffect, useMemo, useState } from 'react';
@@ -41,21 +45,28 @@ import {
import { Spinner } from '@renderer/lib/ui/spinner';
import { Tooltip, TooltipContent, TooltipTrigger } from '@renderer/lib/ui/tooltip';
import { log } from '@renderer/utils/logger';
-import type { LinkedIdentity, RemoteBridge } from '@shared/core/switch-servers/switch-servers';
+import type {
+ LinkedIdentity,
+ PendingIdentity,
+ RemoteBridge,
+} from '@shared/core/switch-servers/switch-servers';
import { bridgeTypesQueryKey, fetchBridgeTypes } from './bridge-platforms-loader';
import { ConnectedChatsList } from './ConnectedChatsList';
import { LinkAccountPrompts } from './link-account-prompts';
+import { accountHandle, linkRequestFailureText } from './link-accounts-prose';
import { orderBridges } from './messaging-apps-order';
import {
hasUnlinkedMessagingApp,
identityLinkOrderingNote,
+ linkedIdentityOn,
unrecognisedMessagingApps,
unrecognisedMessagingAppsMessage,
} from './messaging-apps-warning';
import { mayReplaceToken, offersTokenReplacement, tokenFields } from './replace-token';
import { switchRoomsStore } from './switch-rooms-store';
import { switchServersStore } from './switch-servers-store';
-import { useMyIdentities } from './use-my-identities';
+import { unconfirmedLinksQuery } from './unconfirmed-links';
+import { useMyIdentities, useMyPendingIdentities } from './use-my-identities';
import { administersWorkspaceInScope } from './workspace-admin';
/**
@@ -89,6 +100,14 @@ const MESSAGING_APPS_PURPOSE =
const NO_ACCOUNT_EXPLANATION =
'Switch cannot tell which account in this app is you. Agents set to answer only their owner will not recognise you here, and messages from you read as if from a stranger.';
+/** Beside a link made before links had to be confirmed. */
+const NOT_CONFIRMED_EXPLANATION =
+ 'This link was made before Switch asked accounts to confirm them. It still works. Confirm it by posting a one-time code from the account.';
+
+/** Beside a link waiting for its code, which is not a link yet. */
+const WAITING_EXPLANATION =
+ 'This account is not linked until a one-time code is posted from it. Until then your agents do not recognise you here.';
+
export const MessagingAppsCard = observer(function MessagingAppsCard({
serverId,
className,
@@ -101,6 +120,7 @@ export const MessagingAppsCard = observer(function MessagingAppsCard({
const showDisconnectMessagingApp = useShowModal('disconnectMessagingAppModal');
const showReplaceToken = useShowModal('replaceTokenModal');
const showConnectChat = useShowModal('connectChatModal');
+ const showRequireLinkConfirmation = useShowModal('requireLinkConfirmationModal');
const workspaceId = workspacesStore.idOnServerInScope(serverId);
const isAdmin = administersWorkspaceInScope(serverId);
const flags = useFeatureFlags(serverId);
@@ -136,6 +156,7 @@ export const MessagingAppsCard = observer(function MessagingAppsCard({
error: identitiesError,
refresh: refreshIdentities,
} = useMyIdentities(workspaceId);
+ const { pending, error: pendingError } = useMyPendingIdentities(workspaceId);
// Whose claim to drop when unlinking. Every account here is one the signed-in
// user claimed, and other people may hold the same one — so name the user
// rather than let the server infer it. Null until the session is read back,
@@ -193,6 +214,28 @@ export const MessagingAppsCard = observer(function MessagingAppsCard({
const installStateOf = (bridge: RemoteBridge) =>
installStates[tokenCandidates.findIndex((b) => b.id === bridge.id)]?.data;
+ // Links made before links had to be confirmed, per app, which an admin can
+ // stop trusting. Never asked for anyone else: the route is admin-only.
+ const olderLinkQueries = useQueries({
+ queries: bridges.map((bridge) => ({
+ ...unconfirmedLinksQuery(workspaceId, bridge.id),
+ enabled: isAdmin && workspaceId !== null,
+ })),
+ });
+ const olderLinkCountOf = (bridge: RemoteBridge): number =>
+ isAdmin ? (olderLinkQueries[bridges.indexOf(bridge)]?.data?.length ?? 0) : 0;
+ // Like the probe above, a failure here costs only a menu item, so it is
+ // logged rather than shown.
+ const olderLinksError = olderLinkQueries.find((q) => q.error !== null)?.error ?? null;
+ useEffect(() => {
+ if (olderLinksError) {
+ log.warn('Could not read the older links on a messaging app', {
+ workspaceId,
+ error: olderLinksError,
+ });
+ }
+ }, [olderLinksError, workspaceId]);
+
const unrecognisedIn = unrecognisedMessagingApps({
bridges,
identities,
@@ -279,7 +322,12 @@ export const MessagingAppsCard = observer(function MessagingAppsCard({
)}
</div>
- <LinkAccountPrompts workspaceId={workspaceId} bridges={bridges} identities={identities} />
+ <LinkAccountPrompts
+ workspaceId={workspaceId}
+ bridges={bridges}
+ identities={identities}
+ pending={pending}
+ />
{/* Same shape as the addressing editor's owner warning, so the two
readings of one problem look like one problem.
@@ -303,6 +351,15 @@ export const MessagingAppsCard = observer(function MessagingAppsCard({
</p>
)}
+ {pendingError !== null && (
+ <p className="mt-2 text-xs text-destructive">
+ {failureText(
+ pendingError,
+ 'Could not load which links are waiting for a code, so this list may be incomplete.'
+ )}
+ </p>
+ )}
+
{bridgesQuery.isError ? (
<p className="mt-3 text-xs text-destructive">
{failureText(
@@ -331,8 +388,22 @@ export const MessagingAppsCard = observer(function MessagingAppsCard({
and offering to link an account the user already has is the
more confusing of the two. */
identities={identities}
+ pending={pending}
currentUserId={currentUserId}
onReleased={refreshIdentities}
+ olderLinks={
+ workspaceId !== null && olderLinkCountOf(bridge) > 0
+ ? {
+ count: olderLinkCountOf(bridge),
+ onRequireConfirmation: () =>
+ showRequireLinkConfirmation({
+ workspaceId,
+ bridgeId: bridge.id,
+ bridgeDisplayName: bridge.displayName,
+ }),
+ }
+ : null
+ }
showBundledSignIn={isManaged && bridge.type === 'mattermost'}
isAdmin={isAdmin}
savingChannelCreation={savingBridgeId === bridge.id}
@@ -420,16 +491,19 @@ export const MessagingAppsCard = observer(function MessagingAppsCard({
* Only Link stays outside the menu: an app you have not claimed an account on
* has exactly one thing worth doing to it, and burying that is what would make
* the row's warning unactionable. Everything else — changing or dropping the
- * account, channel creation, the bundled chat's credentials, opening the app,
- * replacing its token, disconnecting it — is in the menu.
+ * account, requiring older links be confirmed, channel creation, the bundled
+ * chat's credentials, opening the app, replacing its token, disconnecting it —
+ * is in the menu.
*/
export function MessagingAppRow({
workspaceId,
serverId,
bridge,
identities,
+ pending,
currentUserId,
onReleased,
+ olderLinks,
showBundledSignIn,
isAdmin,
savingChannelCreation,
@@ -444,10 +518,15 @@ export function MessagingAppRow({
/** Only for the bundled chat's sign-in, which is about the gateway. */
serverId: string;
bridge: RemoteBridge;
- /** Accounts the user has claimed in this workspace, or null while unknown. */
+ /** Accounts linked to the user in this workspace, or null while unknown. */
identities: LinkedIdentity[] | null;
+ /** The user's links still waiting for a code, or null while unknown. */
+ pending: PendingIdentity[] | null;
currentUserId: string | null;
onReleased: () => void;
+ /** Set for an admin when the app has links made before links had to be
+ * confirmed: how many, and how to stop trusting them. */
+ olderLinks: { count: number; onRequireConfirmation: () => void } | null;
showBundledSignIn: boolean;
isAdmin: boolean;
savingChannelCreation: boolean;
@@ -465,12 +544,27 @@ export function MessagingAppRow({
const [releasing, setReleasing] = useState(false);
const [releaseError, setReleaseError] = useState<string | null>(null);
- const identity = identities?.find((i) => i.bridgeId === bridge.id) ?? null;
+ const identity = identities === null ? null : linkedIdentityOn(bridge.id, identities);
+ // Only while nothing is linked here: a link that counts says more about the
+ // app than one still waiting for its code.
+ const waiting =
+ identity === null ? (pending?.find((p) => p.bridgeId === bridge.id) ?? null) : null;
const platform = bridgePlatformLabel(bridge.type);
const claim = () => {
if (workspaceId === null) return;
showClaimIdentity({ workspaceId, bridgeId: bridge.id });
};
+ const confirmLink = (
+ target: { id: string; externalUsername: string },
+ kind: 'pending' | 'unverified'
+ ) => {
+ if (workspaceId === null) return;
+ showClaimIdentity({
+ workspaceId,
+ bridgeId: bridge.id,
+ confirm: { identityId: target.id, externalUsername: target.externalUsername, kind },
+ });
+ };
// Offered only for the distributed Teams app: re-approving is exactly the
// "Add to Microsoft Teams" install flow run again, which only makes sense
@@ -525,6 +619,29 @@ export function MessagingAppRow({
}
};
+ // Withdraws only the waiting confirmation. Unlinking is `release`, and is
+ // never what Cancel means.
+ const cancelRequest = async (identityId: string) => {
+ if (workspaceId === null) return;
+ setReleasing(true);
+ setReleaseError(null);
+ try {
+ const result = await rpc.workspaces.cancelIdentityLinkRequest({
+ workspaceId,
+ bridgeId: bridge.id,
+ identityId,
+ });
+ // Re-read either way: a refusal means it was confirmed or cancelled
+ // meanwhile, and the row should say which.
+ onReleased();
+ if (result.kind !== 'cancelled') setReleaseError(linkRequestFailureText(result));
+ } catch (cause) {
+ setReleaseError(failureText(cause, 'Could not cancel this link.'));
+ } finally {
+ setReleasing(false);
+ }
+ };
+
// What it costs not to be linked, and — where the app has no directory to
// search — how to become linkable at all. The second half is not obvious and
// is the reason nothing offered to link on the way in.
@@ -569,7 +686,47 @@ export function MessagingAppRow({
<span className="shrink-0 text-xs text-destructive">{bridge.status}</span>
)}
</div>
- {identities === null ? null : identity === null ? (
+ {identities === null ? null : identity !== null ? (
+ <span className="flex min-w-0 items-center gap-1.5">
+ <span className="truncate font-mono text-xs text-foreground-muted">
+ {accountHandle(identity.externalUsername)}
+ </span>
+ {!identity.verified && (
+ <Tooltip>
+ <TooltipTrigger
+ render={
+ <span tabIndex={0} aria-label={NOT_CONFIRMED_EXPLANATION}>
+ <Badge variant="secondary">Not confirmed</Badge>
+ </span>
+ }
+ />
+ <TooltipContent className="max-w-xs">{NOT_CONFIRMED_EXPLANATION}</TooltipContent>
+ </Tooltip>
+ )}
+ </span>
+ ) : waiting !== null ? (
+ <span className="flex min-w-0 items-center gap-1 text-xs text-foreground-muted">
+ <Clock className="size-3 shrink-0" />
+ <span className="truncate">
+ <span className="font-mono">{accountHandle(waiting.externalUsername)}</span> ·
+ Waiting for confirmation
+ </span>
+ <Tooltip>
+ <TooltipTrigger
+ render={
+ <span
+ tabIndex={0}
+ aria-label={WAITING_EXPLANATION}
+ className="inline-flex text-foreground-muted"
+ >
+ <Info className="size-3" />
+ </span>
+ }
+ />
+ <TooltipContent className="max-w-xs">{WAITING_EXPLANATION}</TooltipContent>
+ </Tooltip>
+ </span>
+ ) : (
<span className="flex items-center gap-1 text-xs text-amber-600 dark:text-amber-500">
<TriangleAlert className="size-3 shrink-0" />
No account linked
@@ -588,10 +745,6 @@ export function MessagingAppRow({
<TooltipContent className="max-w-xs">{noAccountHelp}</TooltipContent>
</Tooltip>
</span>
- ) : (
- <span className="truncate font-mono text-xs text-foreground-muted">
- {handleOf(identity)}
- </span>
)}
{releaseError !== null && (
<p className="mt-0.5 text-xs text-destructive">{releaseError}</p>
@@ -599,16 +752,40 @@ export function MessagingAppRow({
</div>
{/* Linking is the one thing an unlinked app needs, so it stays a button
- rather than going into the menu with the rest. A linked app shows no
- button at all: the only thing left to do to it is destructive, and a
- control next to the handle would sit one mis-click from the action
- that *changes* the account (CHOO-2137). */}
- {identities !== null && identity === null && (
- <Button variant="outline" size="xs" className="shrink-0" onClick={claim}>
- <Link2 className="size-3" />
- Link
- </Button>
- )}
+ rather than going into the menu with the rest — as do the code that
+ finishes a waiting link and the one that confirms an old one. A
+ confirmed link shows no button at all: the only thing left to do to it
+ is destructive, and a control next to the handle would sit one
+ mis-click from the action that *changes* the account (CHOO-2137). */}
+ {identities !== null &&
+ (identity !== null ? (
+ !identity.verified && (
+ <Button
+ variant="outline"
+ size="xs"
+ className="shrink-0"
+ onClick={() => confirmLink(identity, 'unverified')}
+ >
+ <ShieldCheck className="size-3" />
+ Confirm
+ </Button>
+ )
+ ) : waiting !== null ? (
+ <Button
+ variant="outline"
+ size="xs"
+ className="shrink-0"
+ onClick={() => confirmLink(waiting, 'pending')}
+ >
+ <KeyRound className="size-3" />
+ Show code
+ </Button>
+ ) : (
+ <Button variant="outline" size="xs" className="shrink-0" onClick={claim}>
+ <Link2 className="size-3" />
+ Link
+ </Button>
+ ))}
<DropdownMenu>
<DropdownMenuTrigger
@@ -632,7 +809,19 @@ export function MessagingAppRow({
{identity !== null && (
<DropdownMenuItem onClick={() => void release(identity.id)}>
<Unlink className="size-4" />
- Unlink {handleOf(identity)}
+ Unlink {accountHandle(identity.externalUsername)}
+ </DropdownMenuItem>
+ )}
+ {waiting !== null && (
+ <DropdownMenuItem onClick={() => void cancelRequest(waiting.id)}>
+ <X className="size-4" />
+ Cancel link to {accountHandle(waiting.externalUsername)}
+ </DropdownMenuItem>
+ )}
+ {olderLinks !== null && (
+ <DropdownMenuItem onClick={olderLinks.onRequireConfirmation}>
+ <ShieldAlert className="size-4" />
+ Require confirmation for older links ({olderLinks.count})…
</DropdownMenuItem>
)}
@@ -796,13 +985,6 @@ async function copyWebhookAddress(url: string): Promise<void> {
}
}
-/** The claimed account as a handle. Platforms differ on whether the username
- * they report already carries the sigil, so add one only when it is missing. */
-function handleOf(identity: LinkedIdentity): string {
- const username = identity.externalUsername;
- return username.startsWith('@') ? username : `@${username}`;
-}
-
/** Turn a failed channel-creation toggle into something the user can act on. */
function messageForUpdate(result: { kind: string; message?: string }): string {
switch (result.kind) {
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/RequireLinkConfirmationModal.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/RequireLinkConfirmationModal.tsx
new file mode 100644
index 000000000..fa53e435b
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/RequireLinkConfirmationModal.tsx
@@ -0,0 +1,147 @@
+import { useQuery, useQueryClient } from '@tanstack/react-query';
+import { CircleAlert } from 'lucide-react';
+import { observer } from 'mobx-react-lite';
+import { useState } from 'react';
+import { failureText } from '@renderer/lib/errors/describe-failure';
+import { toast } from '@renderer/lib/hooks/use-toast';
+import { rpc } from '@renderer/lib/ipc';
+import { type BaseModalProps } from '@renderer/lib/modal/modal-provider';
+import { Button } from '@renderer/lib/ui/button';
+import { ConfirmButton } from '@renderer/lib/ui/confirm-button';
+import {
+ DialogContentArea,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from '@renderer/lib/ui/dialog';
+import { Spinner } from '@renderer/lib/ui/spinner';
+import { accountHandle, linkRequestFailureText } from './link-accounts-prose';
+import { unconfirmedLinksQuery, unconfirmedLinksQueryKey } from './unconfirmed-links';
+import { myIdentitiesQueryKey } from './use-my-identities';
+
+type RequireLinkConfirmationModalArgs = {
+ workspaceId: string;
+ bridgeId: string;
+ bridgeDisplayName: string;
+};
+
+type Props = BaseModalProps<{ moved: number }> & RequireLinkConfirmationModalArgs;
+
+/**
+ * Stop trusting a messaging app's links made before links had to be confirmed
+ * (CHOO-3881). Admin only.
+ *
+ * Nobody proved those accounts were theirs, so an admin can make each one wait
+ * for its owner's code like a new link. It stops counting at once, which locks
+ * people out of their own owner-only agents until they post the code — so the
+ * dialog names everyone affected and says so before anything moves.
+ */
+export const RequireLinkConfirmationModal = observer(function RequireLinkConfirmationModal({
+ workspaceId,
+ bridgeId,
+ bridgeDisplayName,
+ onSuccess,
+ onClose,
+}: Props) {
+ const queryClient = useQueryClient();
+ const linksQuery = useQuery(unconfirmedLinksQuery(workspaceId, bridgeId));
+ const links = linksQuery.data ?? null;
+ const [requiring, setRequiring] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+
+ const handleRequire = async () => {
+ setRequiring(true);
+ setError(null);
+ try {
+ const result = await rpc.workspaces.requireLinkConfirmation({ workspaceId, bridgeId });
+ if (result.kind !== 'required') {
+ setError(linkRequestFailureText(result));
+ setRequiring(false);
+ return;
+ }
+ // The linked and pending lists sit under one key; the older links are
+ // the ones just moved.
+ void queryClient.invalidateQueries({ queryKey: myIdentitiesQueryKey(workspaceId) });
+ void queryClient.invalidateQueries({
+ queryKey: unconfirmedLinksQueryKey(workspaceId, bridgeId),
+ });
+ toast({ title: movedText(result.moved) });
+ onSuccess({ moved: result.moved });
+ } catch (cause) {
+ setError(failureText(cause, 'Could not require confirmation.'));
+ setRequiring(false);
+ }
+ };
+
+ return (
+ <>
+ <DialogHeader showCloseButton={false}>
+ <DialogTitle>Require confirmation for older links?</DialogTitle>
+ </DialogHeader>
+ <DialogContentArea className="space-y-3 pt-0">
+ <p className="text-sm text-foreground-muted">
+ These links in {bridgeDisplayName} were made before links had to be confirmed, so nobody
+ proved they own the account.
+ </p>
+
+ {linksQuery.isError ? (
+ <p className="text-xs text-destructive">
+ {failureText(linksQuery.error, 'Could not read the older links.')}
+ </p>
+ ) : links === null ? (
+ <p className="flex items-center gap-2 text-xs text-foreground-muted">
+ <Spinner className="size-3.5" />
+ Reading the links…
+ </p>
+ ) : links.length === 0 ? (
+ <p className="text-xs text-foreground-muted">
+ No older links are left in {bridgeDisplayName}.
+ </p>
+ ) : (
+ <ul
+ className="flex max-h-56 flex-col gap-1 overflow-y-auto"
+ data-testid="unconfirmed-links"
+ >
+ {links.map((link) => (
+ <li
+ key={`${link.id}:${link.userId}`}
+ className="flex items-center justify-between gap-3 rounded-md border border-border px-2 py-1.5 text-sm"
+ >
+ <span className="truncate text-foreground">{link.userName}</span>
+ <span className="truncate font-mono text-xs text-foreground-muted">
+ {accountHandle(link.externalUsername)}
+ </span>
+ </li>
+ ))}
+ </ul>
+ )}
+
+ <div className="flex items-start gap-2 rounded-md border border-border bg-background-1 px-2 py-1.5 text-xs">
+ <CircleAlert className="mt-0.5 size-3.5 shrink-0 text-amber-500" />
+ <span>
+ Until each person posts the code Console shows them, agents that answer only their owner
+ won’t recognise them in {bridgeDisplayName}.
+ </span>
+ </div>
+
+ {error !== null && <p className="text-xs text-destructive">{error}</p>}
+ </DialogContentArea>
+ <DialogFooter>
+ <Button variant="outline" onClick={onClose} disabled={requiring}>
+ Cancel
+ </Button>
+ <ConfirmButton
+ onClick={() => void handleRequire()}
+ disabled={requiring || links === null || links.length === 0}
+ >
+ {requiring ? 'Requiring…' : 'Require confirmation'}
+ </ConfirmButton>
+ </DialogFooter>
+ </>
+ );
+});
+
+function movedText(moved: number): string {
+ if (moved === 0) return 'No links needed confirming';
+ return moved === 1 ? '1 link now needs confirming' : `${moved} links now need confirming`;
+}
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/account-link-confirmation.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/account-link-confirmation.tsx
new file mode 100644
index 000000000..a51d9de28
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/account-link-confirmation.tsx
@@ -0,0 +1,390 @@
+import { format } from 'date-fns';
+import { Check, Copy } from 'lucide-react';
+import { observer } from 'mobx-react-lite';
+import { Fragment, useCallback, useEffect, useRef, useState } from 'react';
+import { failureText } from '@renderer/lib/errors/describe-failure';
+import { rpc } from '@renderer/lib/ipc';
+import { useModalContext } from '@renderer/lib/modal/modal-provider';
+import { Button } from '@renderer/lib/ui/button';
+import { Spinner } from '@renderer/lib/ui/spinner';
+import { log } from '@renderer/utils/logger';
+import type { LinkCode, LinkedIdentity } from '@shared/core/switch-servers/switch-servers';
+import { accountHandle, linkRequestFailureText } from './link-accounts-prose';
+import { useMyIdentities, useMyPendingIdentities } from './use-my-identities';
+
+/** How often to look for the link having been confirmed. Nothing tells the app
+ * when the code is posted, so it asks — for as long as the code is on screen,
+ * expired or not: the expiry is read off this machine's clock, and one running
+ * fast must not stop the app noticing a code that was posted in time. */
+export const LINK_CONFIRMATION_POLL_MS = 3000;
+
+/** How long "Linked" stays on screen before the caller moves on, so the
+ * confirmation is seen rather than inferred from the dialog vanishing. */
+const CONFIRMED_HOLD_MS = 1200;
+
+/**
+ * The link being confirmed.
+ *
+ * `pending` counts for nothing until the code is posted, and cancelling drops
+ * it. `unverified` was made before links had to be confirmed and already
+ * counts: cancelling withdraws only the code, and the link stays as it was.
+ */
+export type AccountLinkTarget = {
+ /** The `ExternalUser` row id. */
+ identityId: string;
+ externalUsername: string;
+ kind: 'pending' | 'unverified';
+};
+
+/**
+ * Show the one-time code that confirms a link, and wait for it to be posted
+ * from the account (CHOO-3881).
+ *
+ * The server keeps no copy of a code, so there is no "show it again": every
+ * code shown after the first is a new one, and asking for it retires the last.
+ *
+ * A pending link can also be cancelled somewhere else — by an admin, on another
+ * device, by unlinking — and the screen notices rather than waiting forever.
+ * An unverified link cannot be watched that way: the pending list leaves out
+ * requests for links that already exist, so its absence there says nothing.
+ */
+export const AccountLinkConfirmation = observer(function AccountLinkConfirmation({
+ workspaceId,
+ bridgeId,
+ bridgeDisplayName,
+ target,
+ initialCode,
+ onConfirmed,
+ onCancelled,
+ onStartAgain,
+}: {
+ workspaceId: string;
+ bridgeId: string;
+ bridgeDisplayName: string;
+ target: AccountLinkTarget;
+ /** The code a claim came back with. Null asks for a fresh one on open. */
+ initialCode: LinkCode | null;
+ onConfirmed: (identity: LinkedIdentity) => void;
+ /** After the confirmation is withdrawn: a pending link is gone, an
+ * unverified one stays as it was. Either way the code screen is done. */
+ onCancelled: () => void;
+ /** After a pending link was found cancelled somewhere else, to link again. */
+ onStartAgain: () => void;
+}) {
+ const { setCloseGuard } = useModalContext();
+ const [openedAt] = useState(() => Date.now());
+ const [shown, setShown] = useState<ShownCode | null>(() =>
+ initialCode === null ? null : arrived(initialCode)
+ );
+ const code = shown?.code ?? null;
+ const [expiredCode, setExpiredCode] = useState<string | null>(null);
+ const [issuing, setIssuing] = useState(false);
+ const [cancelling, setCancelling] = useState(false);
+ const [copied, setCopied] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+ const [gone, setGone] = useState(false);
+ const expired = code !== null && expiredCode === code.code;
+
+ const pollMs = gone ? false : LINK_CONFIRMATION_POLL_MS;
+ const { identities, refresh } = useMyIdentities(workspaceId, pollMs);
+ const { pending, updatedAt: pendingReadAt } = useMyPendingIdentities(
+ target.kind === 'pending' ? workspaceId : null,
+ pollMs
+ );
+ const confirmed = identities?.find((i) => i.id === target.identityId && i.verified) ?? null;
+
+ const issueCode = useCallback(async () => {
+ setIssuing(true);
+ setCloseGuard(true);
+ setError(null);
+ try {
+ const result = await rpc.workspaces.issueIdentityLinkCode({
+ workspaceId,
+ bridgeId,
+ identityId: target.identityId,
+ });
+ // Either way the lists may have moved: a new code changes when the
+ // pending one expires, and a refusal may mean it was confirmed meanwhile.
+ refresh();
+ if (result.kind !== 'issued') {
+ setError(linkRequestFailureText(result));
+ return;
+ }
+ setShown(arrived(result.code));
+ setCopied(false);
+ } catch (cause) {
+ setError(failureText(cause, 'Could not get a new code.'));
+ } finally {
+ setIssuing(false);
+ setCloseGuard(false);
+ }
+ }, [workspaceId, bridgeId, target.identityId, refresh, setCloseGuard]);
+
+ // Once per mount: a second request would retire the code the first one is
+ // about to show.
+ const askedOnOpen = useRef(false);
+ useEffect(() => {
+ if (initialCode !== null || askedOnOpen.current) return;
+ askedOnOpen.current = true;
+ void issueCode();
+ }, [initialCode, issueCode]);
+
+ useEffect(() => {
+ if (shown === null || !Number.isFinite(shown.deadline)) return;
+ const timer = setTimeout(
+ () => setExpiredCode(shown.code.code),
+ Math.max(0, shown.deadline - Date.now())
+ );
+ return () => clearTimeout(timer);
+ }, [shown]);
+
+ // Gone from the pending list and not linked either. Posting the code turns
+ // the request into a link in one step, but the two lists are read separately,
+ // so one read of each can straddle it and show neither. The pending read
+ // counts only if it was made since the screen opened; then a read of the
+ // linked accounts begun after it settles which happened.
+ const absent =
+ target.kind === 'pending' &&
+ !gone &&
+ confirmed === null &&
+ identities !== null &&
+ pending !== null &&
+ pendingReadAt >= openedAt &&
+ !pending.some((p) => p.id === target.identityId) &&
+ !identities.some((i) => i.id === target.identityId);
+ useEffect(() => {
+ if (!absent) return;
+ let current = true;
+ rpc.workspaces.listMyIdentities(workspaceId).then(
+ (fresh) => {
+ if (!current) return;
+ if (fresh.some((i) => i.id === target.identityId)) refresh();
+ else setGone(true);
+ },
+ (error: unknown) => log.warn('Could not check whether a link was cancelled', { error })
+ );
+ return () => {
+ current = false;
+ };
+ }, [absent, workspaceId, target.identityId, refresh]);
+
+ // Reported once, and only for a confirmation this screen saw happen: one
+ // that was already confirmed when it opened is not a moment it witnessed.
+ const sawUnconfirmed = useRef(false);
+ const reportedConfirmation = useRef(false);
+ useEffect(() => {
+ if (identities === null) return;
+ if (confirmed === null) {
+ sawUnconfirmed.current = true;
+ return;
+ }
+ if (!sawUnconfirmed.current || reportedConfirmation.current) return;
+ reportedConfirmation.current = true;
+ rpc.workspaces
+ .reportIdentityConfirmed({
+ workspaceId,
+ bridgeId,
+ identityId: target.identityId,
+ kind: target.kind,
+ })
+ .catch((error: unknown) => log.warn('Could not report a confirmed link', { error }));
+ }, [identities, confirmed, workspaceId, bridgeId, target.identityId, target.kind]);
+
+ // Read through a ref so a caller's inline callback does not restart the hold
+ // on every render.
+ const onConfirmedRef = useRef(onConfirmed);
+ useEffect(() => {
+ onConfirmedRef.current = onConfirmed;
+ });
+ const reported = useRef(false);
+ useEffect(() => {
+ if (confirmed === null || reported.current) return;
+ const timer = setTimeout(() => {
+ reported.current = true;
+ onConfirmedRef.current(confirmed);
+ }, CONFIRMED_HOLD_MS);
+ return () => clearTimeout(timer);
+ }, [confirmed]);
+
+ const cancel = async () => {
+ setCancelling(true);
+ setCloseGuard(true);
+ setError(null);
+ try {
+ // Never the full unlink: that would also drop an unverified link, which
+ // works today and is not what Cancel is about.
+ const result = await rpc.workspaces.cancelIdentityLinkRequest({
+ workspaceId,
+ bridgeId,
+ identityId: target.identityId,
+ });
+ refresh();
+ if (result.kind !== 'cancelled') {
+ setError(linkRequestFailureText(result));
+ return;
+ }
+ onCancelled();
+ } catch (cause) {
+ setError(failureText(cause, 'Could not cancel.'));
+ } finally {
+ setCancelling(false);
+ setCloseGuard(false);
+ }
+ };
+
+ const copy = async () => {
+ if (code === null) return;
+ try {
+ await navigator.clipboard.writeText(code.code);
+ setCopied(true);
+ } catch {
+ setError('Could not copy the code. Select it and copy it by hand.');
+ }
+ };
+
+ const handle = accountHandle(target.externalUsername);
+
+ if (confirmed !== null) {
+ return (
+ <p className="flex items-center gap-2 text-sm text-green-600 dark:text-green-500">
+ <Check className="size-4 shrink-0" />
+ {target.kind === 'pending' ? `Linked to ${handle}.` : `${handle} is confirmed.`}
+ </p>
+ );
+ }
+
+ if (gone) {
+ return (
+ <div
+ className="flex w-full flex-col items-start gap-4"
+ data-testid="account-link-confirmation"
+ >
+ <p className="text-sm text-foreground">
+ The link to {handle} was cancelled, so its code no longer works.
+ </p>
+ <Button size="sm" onClick={onStartAgain}>
+ Start again
+ </Button>
+ </div>
+ );
+ }
+
+ const busy = issuing || cancelling;
+ return (
+ <div className="flex w-full flex-col gap-4" data-testid="account-link-confirmation">
+ <p className="text-sm text-foreground">
+ {target.kind === 'pending'
+ ? `To finish linking ${handle}, post this code from that account in ${bridgeDisplayName}.`
+ : `Confirm ${handle} is yours by posting this code from that account in ${bridgeDisplayName}. The link keeps working meanwhile.`}
+ </p>
+
+ <div className="flex items-center justify-between gap-3 rounded-md border border-border bg-background-1 px-3 py-2.5">
+ {code === null ? (
+ <span className="flex items-center gap-2 text-sm text-foreground-muted">
+ <Spinner className="size-3.5" />
+ Getting a code…
+ </span>
+ ) : (
+ <span
+ data-testid="link-code"
+ className={`font-mono text-xl tracking-widest select-all ${expired ? 'text-foreground-muted line-through' : 'text-foreground'}`}
+ >
+ {code.code}
+ </span>
+ )}
+ <Button
+ variant="outline"
+ size="sm"
+ className="shrink-0"
+ disabled={code === null || expired}
+ onClick={() => void copy()}
+ >
+ {copied ? <Check className="size-3" /> : <Copy className="size-3" />}
+ {copied ? 'Copied' : 'Copy'}
+ </Button>
+ </div>
+
+ {code !== null && (
+ <p className="text-xs text-foreground-muted">
+ <InlineCode text={code.instructions} />
+ </p>
+ )}
+
+ {shown !== null &&
+ (expired ? (
+ <p className="text-xs text-amber-600 dark:text-amber-500">
+ This code has expired. Get a new one to{' '}
+ {target.kind === 'pending' ? 'finish linking' : 'confirm the link'}.
+ </p>
+ ) : (
+ <p className="flex items-center gap-2 text-xs text-foreground-muted">
+ <Spinner className="size-3" />
+ {Number.isFinite(shown.deadline)
+ ? `Waiting for the code. It expires at ${format(shown.deadline, 'HH:mm')}.`
+ : 'Waiting for the code.'}
+ </p>
+ ))}
+
+ <div className="flex flex-wrap items-center gap-2">
+ <Button
+ variant={expired ? 'default' : 'outline'}
+ size="sm"
+ disabled={busy}
+ onClick={() => void issueCode()}
+ >
+ {issuing ? 'Getting a code…' : 'Get a new code'}
+ </Button>
+ <Button variant="ghost" size="sm" disabled={busy} onClick={() => void cancel()}>
+ {cancelling
+ ? 'Cancelling…'
+ : target.kind === 'pending'
+ ? 'Cancel link'
+ : 'Cancel confirmation'}
+ </Button>
+ </div>
+
+ {error !== null && <p className="text-xs text-destructive">{error}</p>}
+ </div>
+ );
+});
+
+/** A code with when it stops working, on this machine's clock. */
+type ShownCode = { code: LinkCode; deadline: number };
+
+/**
+ * The deadline is counted from when the code arrived, by the lifetime the
+ * server gave it, so a clock here that is minutes out still counts the right
+ * minutes — and the time shown agrees with the clock the user is looking at.
+ * The server's own `expiresAt` is used only when it sends no lifetime, and may
+ * be NaN, which shows no expiry at all rather than a wrong one.
+ */
+function arrived(code: LinkCode): ShownCode {
+ const deadline =
+ code.expiresInSeconds !== null
+ ? Date.now() + code.expiresInSeconds * 1000
+ : Date.parse(code.expiresAt);
+ return { code, deadline };
+}
+
+/** The server's instructions are a Markdown sentence whose only markup is
+ * inline code — the command to post. Unbalanced backticks are shown as typed. */
+function InlineCode({ text }: { text: string }) {
+ const parts = text.split('`');
+ if (parts.length % 2 === 0) return <>{text}</>;
+ return (
+ <>
+ {parts.map((part, i) =>
+ i % 2 === 1 ? (
+ <code
+ key={i}
+ className="rounded bg-background-2 px-1 py-0.5 font-mono text-[11px] text-foreground"
+ >
+ {part}
+ </code>
+ ) : (
+ <Fragment key={i}>{part}</Fragment>
+ )
+ )}
+ </>
+ );
+}
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/bridge-identity-search.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/bridge-identity-search.tsx
index 52e8c8a8d..a6baf7502 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/bridge-identity-search.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/bridge-identity-search.tsx
@@ -16,10 +16,13 @@ import type {
BridgeDirectorySearchResult,
BridgeDirectoryUser,
ClaimIdentityResult,
+ LinkCode,
LinkedIdentity,
+ PendingIdentity,
} from '@shared/core/switch-servers/switch-servers';
+import type { AccountLinkTarget } from './account-link-confirmation';
import { switchServersStore } from './switch-servers-store';
-import { useMyIdentities } from './use-my-identities';
+import { useMyIdentities, useMyPendingIdentities } from './use-my-identities';
/** How long to wait after the last keystroke before asking the platform. Every
* search is a live call out to Slack or Mattermost, so this is a courtesy to
@@ -46,6 +49,7 @@ export const BridgeIdentitySearch = observer(function BridgeIdentitySearch({
directorySearchSupported,
autoFocus,
onClaimed,
+ onConfirmationNeeded,
}: {
workspaceId: string;
bridgeId: string;
@@ -57,6 +61,10 @@ export const BridgeIdentitySearch = observer(function BridgeIdentitySearch({
directorySearchSupported: boolean;
autoFocus: boolean;
onClaimed: (identity: LinkedIdentity) => void;
+ /** A link that waits on a code posted from the account: one just made, one
+ * already waiting, or one made before links had to be confirmed. `code` is
+ * the one a claim came back with, else null. */
+ onConfirmationNeeded: (target: AccountLinkTarget, code: LinkCode | null) => void;
}) {
const { setCloseGuard } = useModalContext();
const queryClient = useQueryClient();
@@ -71,6 +79,7 @@ export const BridgeIdentitySearch = observer(function BridgeIdentitySearch({
const [error, setError] = useState<string | null>(null);
const { refresh: refreshIdentities } = useMyIdentities(workspaceId || null);
+ const { pending } = useMyPendingIdentities(workspaceId || null);
const debouncedQuery = useDebounce(search.trim(), SEARCH_DEBOUNCE_MS);
const searchable = !!workspaceId && debouncedQuery.length >= MIN_QUERY_LENGTH;
@@ -92,6 +101,18 @@ export const BridgeIdentitySearch = observer(function BridgeIdentitySearch({
externalUserId: person.externalUserId,
username: person.username,
});
+ if (result.kind === 'pending') {
+ refreshIdentities();
+ onConfirmationNeeded(
+ {
+ identityId: result.pending.id,
+ externalUsername: result.pending.externalUsername,
+ kind: result.alreadyLinked ? 'unverified' : 'pending',
+ },
+ result.code
+ );
+ return;
+ }
if (result.kind !== 'claimed') {
setError(claimFailureText(result));
return;
@@ -158,10 +179,12 @@ export const BridgeIdentitySearch = observer(function BridgeIdentitySearch({
result={directoryQuery.data ?? null}
fetchError={directoryQuery.error}
currentUserId={currentUserId}
+ pending={(pending ?? []).filter((p) => p.bridgeId === bridgeId)}
claimingId={claiming}
releasingId={releasing}
onClaim={(person) => void handleClaim(person)}
onRelease={(person) => void handleRelease(person)}
+ onConfirm={onConfirmationNeeded}
/>
{error && <p className="text-xs text-destructive">{error}</p>}
@@ -178,10 +201,12 @@ function DirectoryResults({
result,
fetchError,
currentUserId,
+ pending,
claimingId,
releasingId,
onClaim,
onRelease,
+ onConfirm,
}: {
query: string;
searchable: boolean;
@@ -197,12 +222,16 @@ function DirectoryResults({
result: BridgeDirectorySearchResult | null;
fetchError: unknown;
currentUserId: string | null;
+ /** The signed-in user's links on this app still waiting for a code. The
+ * directory knows nothing of them — it lists only links that count. */
+ pending: PendingIdentity[];
/** The platform id of the account being linked, or null when none is. */
claimingId: string | null;
/** The platform id of the account being unlinked, or null when none is. */
releasingId: string | null;
onClaim: (person: BridgeDirectoryUser) => void;
onRelease: (person: BridgeDirectoryUser) => void;
+ onConfirm: (target: AccountLinkTarget, code: LinkCode | null) => void;
}) {
if (!searchable) {
return (
@@ -277,14 +306,19 @@ function DirectoryResults({
// Nothing here is disabled because someone else holds the account: several
// people can be recognised on the same one, and the other claimants are shown
// so a shared or misidentified account is visible rather than silent.
- const pending = claimingId !== null || releasingId !== null;
+ const busy = claimingId !== null || releasingId !== null;
return (
<div className="flex flex-col gap-2">
{narrowed}
<ul className="flex max-h-64 flex-col gap-1 overflow-y-auto">
{result.users.map((person) => {
- const linkedToMe = person.claimedBy.some((c) => c.userId === currentUserId);
+ const rowId = person.knownExternalUserId;
+ const mine = person.claimedBy.find((c) => c.userId === currentUserId) ?? null;
const others = person.claimedBy.filter((c) => c.userId !== currentUserId);
+ const waiting =
+ mine === null
+ ? (pending.find((p) => p.externalUserId === person.externalUserId) ?? null)
+ : null;
return (
<li
key={person.externalUserId}
@@ -302,20 +336,60 @@ function DirectoryResults({
</span>
)}
</div>
- {linkedToMe ? (
+ {mine !== null ? (
<span className="flex shrink-0 items-center gap-2">
- <Badge variant="secondary">Linked to you</Badge>
+ <Badge variant="secondary">
+ {mine.verified ? 'Linked to you' : 'Linked, not confirmed'}
+ </Badge>
+ {!mine.verified && rowId !== null && (
+ <Button
+ size="sm"
+ disabled={busy}
+ onClick={() =>
+ onConfirm(
+ {
+ identityId: rowId,
+ externalUsername: person.username,
+ kind: 'unverified',
+ },
+ null
+ )
+ }
+ >
+ Confirm
+ </Button>
+ )}
<Button
variant="outline"
size="sm"
- disabled={pending || person.knownExternalUserId === null}
+ disabled={busy || rowId === null}
onClick={() => onRelease(person)}
>
{releasingId === person.externalUserId ? 'Unlinking…' : 'Unlink'}
</Button>
</span>
+ ) : waiting !== null ? (
+ <span className="flex shrink-0 items-center gap-2">
+ <Badge variant="secondary">Waiting for confirmation</Badge>
+ <Button
+ size="sm"
+ disabled={busy}
+ onClick={() =>
+ onConfirm(
+ {
+ identityId: waiting.id,
+ externalUsername: waiting.externalUsername,
+ kind: 'pending',
+ },
+ null
+ )
+ }
+ >
+ Show code
+ </Button>
+ </span>
) : (
- <Button size="sm" disabled={pending} onClick={() => onClaim(person)}>
+ <Button size="sm" disabled={busy} onClick={() => onClaim(person)}>
{claimingId === person.externalUserId ? 'Linking…' : 'This is me'}
</Button>
)}
@@ -328,7 +402,9 @@ function DirectoryResults({
}
/** Turn a failed claim into something the user can act on. */
-function claimFailureText(result: Exclude<ClaimIdentityResult, { kind: 'claimed' }>): string {
+function claimFailureText(
+ result: Exclude<ClaimIdentityResult, { kind: 'claimed' | 'pending' }>
+): string {
switch (result.kind) {
case 'unauthenticated':
return 'Your session for this server expired. Sign in again, then retry.';
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/link-account-prompts.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/link-account-prompts.tsx
index 97b26f40e..5aa87d5e3 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/link-account-prompts.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/link-account-prompts.tsx
@@ -1,57 +1,139 @@
-import { Link2 } from 'lucide-react';
+import { KeyRound, Link2, ShieldCheck } from 'lucide-react';
import { bridgePlatformLabel } from '@renderer/lib/components/bridge-platform';
import { useShowModal } from '@renderer/lib/modal/modal-provider';
import { Alert, AlertAction, AlertDescription, AlertTitle } from '@renderer/lib/ui/alert';
import { Button } from '@renderer/lib/ui/button';
-import type { LinkedIdentity, RemoteBridge } from '@shared/core/switch-servers/switch-servers';
-import { messagingAppsToLink } from './messaging-apps-warning';
+import type {
+ LinkedIdentity,
+ PendingIdentity,
+ RemoteBridge,
+} from '@shared/core/switch-servers/switch-servers';
+import type { AccountLinkTarget } from './account-link-confirmation';
+import { accountHandle } from './link-accounts-prose';
+import { type AccountLinkPrompt, accountLinkPrompts } from './messaging-apps-warning';
/**
- * "Link your <app> account", once for each active app the signed-in user has
- * no account linked on.
+ * One prompt for each active app whose account still needs something from the
+ * signed-in user: "Link your <app> account" while none is linked, "Finish
+ * linking" while a link waits for its code, and "Confirm" for a link made
+ * before links had to be confirmed.
*
* Adding an app ends with the link step, and the step can be skipped; this is
* where it is offered again, on the server home, until the account is linked.
- * Claiming refreshes the identity list it reads, so a prompt goes away as soon
- * as its account is linked.
+ * Claiming and confirming refresh the lists it reads, so a prompt goes away as
+ * soon as it is answered.
*/
export function LinkAccountPrompts({
workspaceId,
bridges,
identities,
+ pending,
}: {
workspaceId: string | null;
bridges: RemoteBridge[];
/** Null while unknown: nothing is prompted until the list has arrived. */
identities: LinkedIdentity[] | null;
+ /** Links waiting for a code; null while unknown. */
+ pending: PendingIdentity[] | null;
}) {
const showClaimIdentity = useShowModal('claimIdentityModal');
if (workspaceId === null) return null;
- const toLink = messagingAppsToLink(bridges, identities);
- if (toLink.length === 0) return null;
+ const prompts = accountLinkPrompts(bridges, identities, pending);
+ if (prompts.length === 0) return null;
return (
<div className="mt-2 flex flex-col gap-2">
- {toLink.map((bridge) => {
- const platform = bridgePlatformLabel(bridge.type);
- return (
- <Alert key={bridge.id} data-testid={`link-account-prompt-${bridge.id}`}>
- <Link2 className="size-4" />
- <AlertTitle>Link your {platform} account</AlertTitle>
- <AlertDescription>
- So your agents recognise you in {bridge.displayName}.
- </AlertDescription>
- <AlertAction>
- <Button
- size="sm"
- variant="outline"
- onClick={() => showClaimIdentity({ workspaceId, bridgeId: bridge.id })}
- >
- Link account
- </Button>
- </AlertAction>
- </Alert>
- );
- })}
+ {prompts.map((prompt) => (
+ <Alert key={prompt.bridge.id} data-testid={`link-account-prompt-${prompt.bridge.id}`}>
+ <PromptBody
+ prompt={prompt}
+ onAct={() => {
+ const confirm = confirmTargetOf(prompt);
+ showClaimIdentity(
+ confirm === null
+ ? { workspaceId, bridgeId: prompt.bridge.id }
+ : { workspaceId, bridgeId: prompt.bridge.id, confirm }
+ );
+ }}
+ />
+ </Alert>
+ ))}
</div>
);
}
+
+/** The link the dialog opens on, waiting for its code; null opens the search. */
+function confirmTargetOf(prompt: AccountLinkPrompt): AccountLinkTarget | null {
+ switch (prompt.kind) {
+ case 'link':
+ return null;
+ case 'pending':
+ return {
+ identityId: prompt.link.id,
+ externalUsername: prompt.link.externalUsername,
+ kind: 'pending',
+ };
+ case 'unverified':
+ return {
+ identityId: prompt.identity.id,
+ externalUsername: prompt.identity.externalUsername,
+ kind: 'unverified',
+ };
+ }
+}
+
+function PromptBody({ prompt, onAct }: { prompt: AccountLinkPrompt; onAct: () => void }) {
+ const platform = bridgePlatformLabel(prompt.bridge.type);
+ const app = prompt.bridge.displayName;
+ switch (prompt.kind) {
+ case 'link':
+ return (
+ <>
+ <Link2 className="size-4" />
+ <AlertTitle>Link your {platform} account</AlertTitle>
+ <AlertDescription>So your agents recognise you in {app}.</AlertDescription>
+ <AlertAction>
+ <Button size="sm" variant="outline" onClick={onAct}>
+ Link account
+ </Button>
+ </AlertAction>
+ </>
+ );
+ case 'pending': {
+ const handle = accountHandle(prompt.link.externalUsername);
+ return (
+ <>
+ <KeyRound className="size-4" />
+ <AlertTitle>Finish linking your {platform} account</AlertTitle>
+ <AlertDescription>
+ {prompt.link.requestedByName !== null
+ ? `${prompt.link.requestedByName} started linking ${handle} in ${app} to you. Post a code from that account to confirm it’s yours.`
+ : `Waiting for a code to be posted from ${handle} in ${app}.`}
+ </AlertDescription>
+ <AlertAction>
+ <Button size="sm" variant="outline" onClick={onAct}>
+ Show code
+ </Button>
+ </AlertAction>
+ </>
+ );
+ }
+ case 'unverified': {
+ const handle = accountHandle(prompt.identity.externalUsername);
+ return (
+ <>
+ <ShieldCheck className="size-4" />
+ <AlertTitle>Confirm your {platform} account</AlertTitle>
+ <AlertDescription>
+ {handle} in {app} is linked but not confirmed. Post a one-time code from it to show it’s
+ yours.
+ </AlertDescription>
+ <AlertAction>
+ <Button size="sm" variant="outline" onClick={onAct}>
+ Confirm
+ </Button>
+ </AlertAction>
+ </>
+ );
+ }
+ }
+}
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/link-accounts-prose.ts b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/link-accounts-prose.ts
index c71f473ba..28dd30314 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/link-accounts-prose.ts
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/link-accounts-prose.ts
@@ -1,3 +1,5 @@
+import type { LinkRequestFailure } from '@shared/core/switch-servers/switch-servers';
+
/**
* What linking is for, said where someone is deciding whether to bother.
*
@@ -19,3 +21,21 @@ export function connectedAppsSummary(serverName: string, count: number): string
if (count === 0) return `${serverName} has no messaging apps connected yet.`;
return `${serverName} has ${spellCount(count)} messaging app${count === 1 ? '' : 's'} connected.`;
}
+
+/** A platform username as a handle. Platforms differ on whether the username
+ * they report already carries the sigil, so add one only when it is missing. */
+export function accountHandle(username: string): string {
+ return username.startsWith('@') ? username : `@${username}`;
+}
+
+/** A request about a waiting confirmation that did nothing, said so the user
+ * can act on it. */
+export function linkRequestFailureText(failure: LinkRequestFailure): string {
+ switch (failure.kind) {
+ case 'unauthenticated':
+ return 'Your session for this server expired. Sign in again, then retry.';
+ case 'refused':
+ case 'error':
+ return failure.message;
+ }
+}
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/link-accounts-step.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/link-accounts-step.tsx
index 495a98e58..19275c25a 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/link-accounts-step.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/link-accounts-step.tsx
@@ -1,5 +1,13 @@
import { useQuery } from '@tanstack/react-query';
-import { Check, Link2, MessageSquare, TriangleAlert } from 'lucide-react';
+import {
+ Check,
+ Clock,
+ KeyRound,
+ Link2,
+ MessageSquare,
+ ShieldCheck,
+ TriangleAlert,
+} from 'lucide-react';
import { observer } from 'mobx-react-lite';
import { useState } from 'react';
import { workspacesStore } from '@renderer/features/workspaces/workspaces-store';
@@ -11,11 +19,18 @@ import { Button } from '@renderer/lib/ui/button';
import { ConfirmButton } from '@renderer/lib/ui/confirm-button';
import { Spinner } from '@renderer/lib/ui/spinner';
import { WizardFrame } from '@renderer/lib/ui/wizard-frame';
-import type { LinkedIdentity, RemoteBridge } from '@shared/core/switch-servers/switch-servers';
+import type {
+ LinkCode,
+ LinkedIdentity,
+ PendingIdentity,
+ RemoteBridge,
+} from '@shared/core/switch-servers/switch-servers';
+import { AccountLinkConfirmation, type AccountLinkTarget } from './account-link-confirmation';
import { BridgeIdentitySearch } from './bridge-identity-search';
-import { connectedAppsSummary, LINK_ACCOUNTS_LATER } from './link-accounts-prose';
+import { accountHandle, connectedAppsSummary, LINK_ACCOUNTS_LATER } from './link-accounts-prose';
import { orderBridges } from './messaging-apps-order';
-import { useMyIdentities } from './use-my-identities';
+import { linkedIdentityOn } from './messaging-apps-warning';
+import { useMyIdentities, useMyPendingIdentities } from './use-my-identities';
/**
* The last step of connecting to a server someone else runs: say which account
@@ -36,8 +51,12 @@ export const LinkAccountsStep = observer(function LinkAccountsStep({
}) {
// Which app's directory is open, or null while the list is. Linking happens
// in place: a second dialog on top of this one would bury the step it belongs
- // to and give the user two Backs meaning different things.
- const [linking, setLinking] = useState<RemoteBridge | null>(null);
+ // to and give the user two Backs meaning different things. `waiting` is set
+ // while a link waits for its code to be posted, which happens in place too.
+ const [linking, setLinking] = useState<{
+ bridge: RemoteBridge;
+ waiting: { target: AccountLinkTarget; code: LinkCode | null } | null;
+ } | null>(null);
const workspaceId = workspacesStore.idOnServerInScope(serverId);
const bridgesQuery = useQuery({
@@ -54,18 +73,21 @@ export const LinkAccountsStep = observer(function LinkAccountsStep({
? new Error(`Your account has no workspace on ${serverName} to link accounts in.`)
: null;
const { identities } = useMyIdentities(workspaceId);
+ const { pending } = useMyPendingIdentities(workspaceId);
// The footer's Back and the pager's back arrow are the same move, so they
// read one const.
const goBack = () => setLinking(null);
if (linking && workspaceId !== null) {
+ const { bridge, waiting } = linking;
+ const platform = bridgePlatformLabel(bridge.type);
return (
<WizardFrame
- title={`Link your ${bridgePlatformLabel(linking.type)} account`}
+ title={waiting ? `Confirm your ${platform} account` : `Link your ${platform} account`}
subtitle={null}
pager={{
- pageName: `Link ${bridgePlatformLabel(linking.type)}`,
+ pageName: `Link ${platform}`,
onBack: goBack,
onNext: null,
}}
@@ -75,20 +97,37 @@ export const LinkAccountsStep = observer(function LinkAccountsStep({
</Button>
}
>
- <div className="flex w-full flex-col gap-4">
- <p className="text-sm text-foreground-muted">
- Find yourself in {linking.displayName} and tell Switch that account is you.
- </p>
- <BridgeIdentitySearch
+ {waiting ? (
+ <AccountLinkConfirmation
+ key={waiting.target.identityId}
workspaceId={workspaceId}
- bridgeId={linking.id}
- bridgeDisplayName={linking.displayName}
- platform={bridgePlatformLabel(linking.type)}
- directorySearchSupported={linking.directorySearchSupported}
- autoFocus
- onClaimed={() => setLinking(null)}
+ bridgeId={bridge.id}
+ bridgeDisplayName={bridge.displayName}
+ target={waiting.target}
+ initialCode={waiting.code}
+ onConfirmed={goBack}
+ onCancelled={() => setLinking({ bridge, waiting: null })}
+ onStartAgain={() => setLinking({ bridge, waiting: null })}
/>
- </div>
+ ) : (
+ <div className="flex w-full flex-col gap-4">
+ <p className="text-sm text-foreground-muted">
+ Find yourself in {bridge.displayName} and tell Switch that account is you.
+ </p>
+ <BridgeIdentitySearch
+ workspaceId={workspaceId}
+ bridgeId={bridge.id}
+ bridgeDisplayName={bridge.displayName}
+ platform={platform}
+ directorySearchSupported={bridge.directorySearchSupported}
+ autoFocus
+ onClaimed={goBack}
+ onConfirmationNeeded={(target, code) =>
+ setLinking({ bridge, waiting: { target, code } })
+ }
+ />
+ </div>
+ )}
</WizardFrame>
);
}
@@ -106,12 +145,13 @@ export const LinkAccountsStep = observer(function LinkAccountsStep({
serverName={serverName}
bridges={bridgesQuery.isSuccess ? orderBridges(bridgesQuery.data) : null}
identities={identities}
+ pending={pending}
isPending={noWorkspace === null && bridgesQuery.isPending}
error={noWorkspace ?? (bridgesQuery.isError ? bridgesQuery.error : null)}
onRetry={() =>
void (noWorkspace === null ? bridgesQuery.refetch() : workspacesStore.refresh())
}
- onLink={setLinking}
+ onLink={(bridge, waiting) => setLinking({ bridge, waiting })}
/>
</WizardFrame>
);
@@ -121,6 +161,7 @@ function BridgeList({
serverName,
bridges,
identities,
+ pending,
isPending,
error,
onRetry,
@@ -131,10 +172,15 @@ function BridgeList({
* below, so this never stands in for either. */
bridges: RemoteBridge[] | null;
identities: LinkedIdentity[] | null;
+ pending: PendingIdentity[] | null;
isPending: boolean;
error: unknown;
onRetry: () => void;
- onLink: (bridge: RemoteBridge) => void;
+ /** Opens the app's search, or — with a link waiting for its code — the code. */
+ onLink: (
+ bridge: RemoteBridge,
+ waiting: { target: AccountLinkTarget; code: LinkCode | null } | null
+ ) => void;
}) {
if (isPending) {
return (
@@ -180,7 +226,9 @@ function BridgeList({
key={bridge.id}
bridge={bridge}
identities={identities}
- onLink={() => onLink(bridge)}
+ pending={pending}
+ onLink={() => onLink(bridge, null)}
+ onConfirm={(target) => onLink(bridge, { target, code: null })}
/>
))}
</ul>
@@ -194,15 +242,22 @@ function BridgeList({
function BridgeLinkRow({
bridge,
identities,
+ pending,
onLink,
+ onConfirm,
}: {
bridge: RemoteBridge;
/** Null while unknown — which is not the same as none, so the row shows
* neither a handle nor a Link button until the answer arrives. */
identities: LinkedIdentity[] | null;
+ /** Links waiting for a code; null while unknown. */
+ pending: PendingIdentity[] | null;
onLink: () => void;
+ onConfirm: (target: AccountLinkTarget) => void;
}) {
- const identity = identities?.find((i) => i.bridgeId === bridge.id) ?? null;
+ const identity = identities === null ? null : linkedIdentityOn(bridge.id, identities);
+ const waiting =
+ identity === null ? (pending?.find((p) => p.bridgeId === bridge.id) ?? null) : null;
return (
<li className="flex items-center gap-3 rounded-[10px] border border-border bg-[var(--surface-2)] px-3.5 py-3">
@@ -216,35 +271,70 @@ function BridgeLinkRow({
<div className="flex min-w-0 flex-1 flex-col">
<span className="truncate text-sm font-medium text-foreground">{bridge.displayName}</span>
- {identities === null ? null : identity === null ? (
+ {identities === null ? null : identity !== null ? (
+ <span className="truncate font-mono text-xs text-foreground-muted">
+ {accountHandle(identity.externalUsername)}
+ </span>
+ ) : waiting !== null ? (
+ <span className="flex items-center gap-1 truncate text-xs text-foreground-muted">
+ <Clock className="size-3 shrink-0" />
+ <span className="font-mono">{accountHandle(waiting.externalUsername)}</span> · Waiting
+ for confirmation
+ </span>
+ ) : (
<span className="flex items-center gap-1 text-xs text-amber-600 dark:text-amber-500">
<TriangleAlert className="size-3 shrink-0" />
No account linked
</span>
- ) : (
- <span className="truncate font-mono text-xs text-foreground-muted">
- {handleOf(identity)}
- </span>
)}
</div>
{identities !== null &&
- (identity === null ? (
+ (identity !== null ? (
+ identity.verified ? (
+ <span className="flex shrink-0 items-center gap-1.5 text-sm text-green-600 dark:text-green-500">
+ <Check className="size-4" />
+ Linked
+ </span>
+ ) : (
+ <Button
+ variant="outline"
+ size="sm"
+ className="shrink-0"
+ onClick={() =>
+ onConfirm({
+ identityId: identity.id,
+ externalUsername: identity.externalUsername,
+ kind: 'unverified',
+ })
+ }
+ >
+ <ShieldCheck className="size-3.5" />
+ Confirm
+ </Button>
+ )
+ ) : waiting !== null ? (
+ <Button
+ variant="outline"
+ size="sm"
+ className="shrink-0"
+ onClick={() =>
+ onConfirm({
+ identityId: waiting.id,
+ externalUsername: waiting.externalUsername,
+ kind: 'pending',
+ })
+ }
+ >
+ <KeyRound className="size-3.5" />
+ Show code
+ </Button>
+ ) : (
<Button variant="outline" size="sm" className="shrink-0" onClick={onLink}>
<Link2 className="size-3.5" />
Link account
</Button>
- ) : (
- <span className="flex shrink-0 items-center gap-1.5 text-sm text-green-600 dark:text-green-500">
- <Check className="size-4" />
- Linked
- </span>
))}
</li>
);
}
-
-function handleOf(identity: LinkedIdentity): string {
- const username = identity.externalUsername;
- return username.startsWith('@') ? username : `@${username}`;
-}
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/messaging-apps-warning.test.ts b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/messaging-apps-warning.test.ts
index 12ad84718..cd15592af 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/messaging-apps-warning.test.ts
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/messaging-apps-warning.test.ts
@@ -1,9 +1,14 @@
import { describe, expect, it } from 'vitest';
-import type { LinkedIdentity, RemoteBridge } from '@shared/core/switch-servers/switch-servers';
+import type {
+ LinkedIdentity,
+ PendingIdentity,
+ RemoteBridge,
+} from '@shared/core/switch-servers/switch-servers';
import {
+ accountLinkPrompts,
hasUnlinkedMessagingApp,
identityLinkOrderingNote,
- messagingAppsToLink,
+ linkedIdentityOn,
shouldOfferIdentityLinkOnConnect,
unrecognisedMessagingApps,
unrecognisedMessagingAppsMessage,
@@ -28,7 +33,7 @@ function bridge(id: string, displayName: string): RemoteBridge {
};
}
-function identity(bridgeId: string): LinkedIdentity {
+function identity(bridgeId: string, verified = true): LinkedIdentity {
return {
id: `identity-${bridgeId}`,
bridgeId,
@@ -36,6 +41,20 @@ function identity(bridgeId: string): LinkedIdentity {
bridgeType: 'slack',
externalUserId: 'U1',
externalUsername: 'me',
+ verified,
+ };
+}
+
+function pendingLink(bridgeId: string): PendingIdentity {
+ return {
+ id: `pending-${bridgeId}`,
+ bridgeId,
+ bridgeDisplayName: bridgeId,
+ bridgeType: 'slack',
+ externalUserId: 'U1',
+ externalUsername: 'me',
+ requestedByName: null,
+ codeExpiresAt: null,
};
}
@@ -128,6 +147,10 @@ describe('hasUnlinkedMessagingApp', () => {
it('is true when one app is unlinked', () => {
expect(hasUnlinkedMessagingApp([slack, mattermost], [identity('b-slack')])).toBe(true);
});
+
+ it('counts a link made before links had to be confirmed, which still works', () => {
+ expect(hasUnlinkedMessagingApp([slack], [identity('b-slack', false)])).toBe(false);
+ });
});
describe('unrecognisedMessagingAppsMessage', () => {
@@ -196,23 +219,77 @@ describe('what is said instead, where the link step is withheld', () => {
});
});
-describe('messagingAppsToLink', () => {
+describe('accountLinkPrompts', () => {
const slack = bridge('b-slack', 'Slack');
const discord = bridge('b-discord', 'Discord');
- it('names every active app with no linked account', () => {
- expect(messagingAppsToLink([slack, discord], [identity('b-discord')])).toEqual([slack]);
+ it('asks to link every active app with nothing linked or waiting', () => {
+ expect(accountLinkPrompts([slack, discord], [identity('b-discord')], [])).toEqual([
+ { kind: 'link', bridge: slack },
+ ]);
});
- it('names nothing once every app is linked', () => {
- expect(messagingAppsToLink([slack], [identity('b-slack')])).toEqual([]);
+ it('asks nothing once every app is linked and confirmed', () => {
+ expect(accountLinkPrompts([slack], [identity('b-slack')], [])).toEqual([]);
});
- it('names nothing while the linked accounts are unknown', () => {
- expect(messagingAppsToLink([slack], null)).toEqual([]);
+ it('asks nothing while the linked accounts are unknown', () => {
+ expect(accountLinkPrompts([slack], null, [])).toEqual([]);
});
it('leaves out a connection that is down', () => {
- expect(messagingAppsToLink([{ ...slack, status: 'error' }], [])).toEqual([]);
+ expect(accountLinkPrompts([{ ...slack, status: 'error' }], [], [])).toEqual([]);
+ });
+
+ it('says a link is waiting for its code rather than asking for it again', () => {
+ const waiting = pendingLink('b-slack');
+
+ expect(accountLinkPrompts([slack], [], [waiting])).toEqual([
+ { kind: 'pending', bridge: slack, link: waiting },
+ ]);
+ });
+
+ it('still asks to link when the pending links are unknown or failed to load', () => {
+ // Withholding the prompt until the pending list arrives would withhold it
+ // for good on a server where that read fails.
+ expect(accountLinkPrompts([slack], [], null)).toEqual([{ kind: 'link', bridge: slack }]);
+ });
+
+ it('asks to confirm a link made before links had to be confirmed', () => {
+ const old = identity('b-slack', false);
+
+ expect(accountLinkPrompts([slack], [old], null)).toEqual([
+ { kind: 'unverified', bridge: slack, identity: old },
+ ]);
+ });
+
+ it('asks nothing of an app with one confirmed link, whatever else is there', () => {
+ expect(
+ accountLinkPrompts(
+ [slack],
+ [identity('b-slack', false), { ...identity('b-slack'), id: 'other' }],
+ [pendingLink('b-slack')]
+ )
+ ).toEqual([]);
+ });
+});
+
+describe('linkedIdentityOn', () => {
+ const unconfirmed = { ...identity('b-slack', false), id: 'old', externalUsername: 'old' };
+ const confirmed = { ...identity('b-slack'), id: 'new', externalUsername: 'new' };
+
+ it('shows a confirmed account over an unconfirmed one, in either order', () => {
+ // Otherwise the row would say "Not confirmed" under a prompt that is
+ // satisfied, since the prompt asks whether any link is confirmed.
+ expect(linkedIdentityOn('b-slack', [unconfirmed, confirmed])).toBe(confirmed);
+ expect(linkedIdentityOn('b-slack', [confirmed, unconfirmed])).toBe(confirmed);
+ });
+
+ it('falls back to an unconfirmed account, which still counts', () => {
+ expect(linkedIdentityOn('b-slack', [unconfirmed])).toBe(unconfirmed);
+ });
+
+ it('is null for an app with nothing linked', () => {
+ expect(linkedIdentityOn('b-mm', [confirmed])).toBeNull();
});
});
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/messaging-apps-warning.ts b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/messaging-apps-warning.ts
index b7b84eef6..55b99bc64 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/messaging-apps-warning.ts
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/messaging-apps-warning.ts
@@ -1,4 +1,8 @@
-import type { LinkedIdentity, RemoteBridge } from '@shared/core/switch-servers/switch-servers';
+import type {
+ LinkedIdentity,
+ PendingIdentity,
+ RemoteBridge,
+} from '@shared/core/switch-servers/switch-servers';
/**
* When the "Messaging apps" card should warn that owner-only agents cannot
@@ -48,22 +52,59 @@ export function hasUnlinkedMessagingApp(
}
/**
- * The apps the server home keeps prompting "Link your <app> account" for: every
- * active one the signed-in user has claimed no account in. Unlike the warning
- * above it does not wait for an owner-addressed agent — it is the reminder for
- * a link step skipped after adding the app, and it stays until the account is
- * linked. Empty while the identity list is unknown, for the same reason as
- * there. A connection that is down is left out: nobody reaches an agent
- * through it until it is back.
+ * What the server home asks of the signed-in user about each active app's
+ * account, one prompt per app that needs one:
+ *
+ * - `link` — nothing is linked there. The reminder for a link step skipped
+ * after adding the app; it stays until the account is linked.
+ * - `pending` — a link is waiting for its code to be posted from the account,
+ * and counts for nothing until it is (CHOO-3881).
+ * - `unverified` — the link predates confirming links. It counts, and the
+ * prompt asks for it to be confirmed.
+ *
+ * Unlike the warning above it does not wait for an owner-addressed agent.
+ * Nothing is prompted while the linked accounts are unknown, for the same
+ * reason as there. The pending list is not waited on: one that is still loading
+ * or failed to load reads as empty, so an app with nothing linked is asked to
+ * link rather than left with no prompt at all — the worst case is offering a
+ * fresh link where one is already waiting, which re-claiming it handles. A
+ * connection that is down is left out: nobody reaches an agent through it until
+ * it is back.
*/
-export function messagingAppsToLink(
+export type AccountLinkPrompt =
+ | { kind: 'link'; bridge: RemoteBridge }
+ | { kind: 'pending'; bridge: RemoteBridge; link: PendingIdentity }
+ | { kind: 'unverified'; bridge: RemoteBridge; identity: LinkedIdentity };
+
+export function accountLinkPrompts(
bridges: RemoteBridge[],
- identities: LinkedIdentity[] | null
-): RemoteBridge[] {
+ identities: LinkedIdentity[] | null,
+ pending: PendingIdentity[] | null
+): AccountLinkPrompt[] {
if (identities === null) return [];
- return bridges.filter(
- (bridge) => bridge.status === 'active' && !identities.some((i) => i.bridgeId === bridge.id)
- );
+ return bridges
+ .filter((bridge) => bridge.status === 'active')
+ .flatMap((bridge): AccountLinkPrompt[] => {
+ const linked = linkedIdentityOn(bridge.id, identities);
+ if (linked?.verified) return [];
+ if (linked !== null) return [{ kind: 'unverified', bridge, identity: linked }];
+ const waiting = pending?.find((p) => p.bridgeId === bridge.id);
+ return [waiting ? { kind: 'pending', bridge, link: waiting } : { kind: 'link', bridge }];
+ });
+}
+
+/**
+ * The account to show for an app when several are linked there: a confirmed
+ * one if there is any, else any link that counts. Every surface that names one
+ * account per app reads it from here, so a row never shows an unconfirmed link
+ * while the prompt above it is satisfied by a confirmed one.
+ */
+export function linkedIdentityOn(
+ bridgeId: string,
+ identities: LinkedIdentity[]
+): LinkedIdentity | null {
+ const linked = identities.filter((i) => i.bridgeId === bridgeId);
+ return linked.find((i) => i.verified) ?? linked[0] ?? null;
}
/** The warning, as one sentence naming the apps. Callers pass a non-empty list
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/unconfirmed-links.ts b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/unconfirmed-links.ts
new file mode 100644
index 000000000..071a2f54e
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/unconfirmed-links.ts
@@ -0,0 +1,20 @@
+import { rpc } from '@renderer/lib/ipc';
+
+/** One messaging app's links made before links had to be confirmed. */
+export function unconfirmedLinksQueryKey(workspaceId: string | null, bridgeId: string): unknown[] {
+ return ['unconfirmed-identity-links', workspaceId, bridgeId];
+}
+
+/**
+ * The query for one app's older links (CHOO-3881), shared by the card that
+ * counts them and the dialog that lists them, so both read one cache entry.
+ * Admin only: a caller that is not one must leave it disabled rather than ask
+ * and be refused.
+ */
+export function unconfirmedLinksQuery(workspaceId: string | null, bridgeId: string) {
+ return {
+ queryKey: unconfirmedLinksQueryKey(workspaceId, bridgeId),
+ queryFn: () =>
+ rpc.workspaces.listUnconfirmedLinks({ workspaceId: workspaceId as string, bridgeId }),
+ };
+}
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/use-my-identities.ts b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/use-my-identities.ts
index bc13dd5d9..6ba770b80 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/use-my-identities.ts
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/use-my-identities.ts
@@ -1,26 +1,43 @@
import { useQuery, useQueryClient } from '@tanstack/react-query';
import { useCallback } from 'react';
import { rpc } from '@renderer/lib/ipc';
-import type { LinkedIdentity } from '@shared/core/switch-servers/switch-servers';
+import type { LinkedIdentity, PendingIdentity } from '@shared/core/switch-servers/switch-servers';
/** Shared so every surface that claims or releases an identity refreshes the
- * same cache entry the owner-only warning reads. */
+ * same cache entry the owner-only warning reads. Invalidating it refreshes the
+ * pending links too, which live under it. */
export function myIdentitiesQueryKey(workspaceId: string | null): unknown[] {
return ['my-switch-identities', workspaceId];
}
+/** Under {@link myIdentitiesQueryKey}, so everything that re-reads the linked
+ * accounts re-reads the ones still waiting for a code as well. */
+export function myPendingIdentitiesQueryKey(workspaceId: string | null): unknown[] {
+ return [...myIdentitiesQueryKey(workspaceId), 'pending'];
+}
+
/**
- * The messaging accounts the signed-in user has claimed in a workspace
- * (CHOO-2137).
+ * The messaging accounts linked to the signed-in user in a workspace
+ * (CHOO-2137). Only links that count: one still waiting for its code is in
+ * {@link useMyPendingIdentities} instead, and is never "linked" here.
*
* `identities` is null while the answer is unknown — not signed in, no
* workspace chosen, still loading, or the read failed. Callers must treat that as
* "unknown" rather than "none": warning that an owner-only agent is
* unreachable, on the strength of a list that has not arrived, is the same
* false alarm every time the page opens.
+ *
+ * `pollMs` re-reads on an interval while set, for a screen waiting on a code to
+ * be posted from the account — nothing tells the app when that happens.
+ * `updatedAt` is when the list was last read successfully (0 before then), for
+ * telling which of two lists read separately is the newer.
*/
-export function useMyIdentities(workspaceId: string | null): {
+export function useMyIdentities(
+ workspaceId: string | null,
+ pollMs: number | false = false
+): {
identities: LinkedIdentity[] | null;
+ updatedAt: number;
isLoading: boolean;
error: unknown;
refresh: () => void;
@@ -30,6 +47,7 @@ export function useMyIdentities(workspaceId: string | null): {
queryKey: myIdentitiesQueryKey(workspaceId),
queryFn: () => rpc.workspaces.listMyIdentities(workspaceId as string),
enabled: workspaceId !== null,
+ refetchInterval: pollMs,
});
const refresh = useCallback(() => {
@@ -38,8 +56,38 @@ export function useMyIdentities(workspaceId: string | null): {
return {
identities: query.isSuccess ? query.data : null,
+ updatedAt: query.dataUpdatedAt,
isLoading: query.isLoading,
error: query.error,
refresh,
};
}
+
+/**
+ * The messaging accounts waiting for a code to confirm a link to the signed-in
+ * user (CHOO-3881). They count for nothing yet, so nothing reads them as
+ * linked — they are shown so the person can finish or cancel the link.
+ *
+ * Null while unknown, as for {@link useMyIdentities}. A server that predates
+ * confirming links answers with none. `pollMs` and `updatedAt` are as there.
+ */
+export function useMyPendingIdentities(
+ workspaceId: string | null,
+ pollMs: number | false = false
+): {
+ pending: PendingIdentity[] | null;
+ updatedAt: number;
+ error: unknown;
+} {
+ const query = useQuery({
+ queryKey: myPendingIdentitiesQueryKey(workspaceId),
+ queryFn: () => rpc.workspaces.listMyPendingIdentities(workspaceId as string),
+ enabled: workspaceId !== null,
+ refetchInterval: pollMs,
+ });
+ return {
+ pending: query.isSuccess ? query.data : null,
+ updatedAt: query.dataUpdatedAt,
+ error: query.error,
+ };
+}
diff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/claim-identity-modal.test.tsx b/console/apps/switch-console-desktop/src/renderer/tests/browser/claim-identity-modal.test.tsx
new file mode 100644
index 000000000..c6a1e53e3
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/renderer/tests/browser/claim-identity-modal.test.tsx
@@ -0,0 +1,524 @@
+/**
+ * Linking a messaging account now waits for proof (CHOO-3881).
+ *
+ * "This is me" used to link the account on the spot, so anyone could say any
+ * account was theirs. A current server holds the link pending until a one-time
+ * code is posted from the account, so the dialog must not close on the claim:
+ * it shows the code, how to post it, when it runs out, and waits — offering a
+ * new code and a way to cancel — until the link turns up confirmed. A server
+ * that predates this links at once, and the dialog behaves as it always did.
+ */
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
+import { act } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+vi.hoisted(() => {
+ window.electronAPI ??= {
+ invoke: () => Promise.resolve(undefined),
+ eventOn: () => () => {},
+ eventSend: () => {},
+ } as unknown as typeof window.electronAPI;
+});
+
+const listBridges = vi.hoisted(() => vi.fn());
+const listMyIdentities = vi.hoisted(() => vi.fn());
+const listMyPendingIdentities = vi.hoisted(() => vi.fn());
+const searchBridgeDirectory = vi.hoisted(() => vi.fn());
+const claimBridgeIdentity = vi.hoisted(() => vi.fn());
+const issueIdentityLinkCode = vi.hoisted(() => vi.fn());
+const releaseBridgeIdentity = vi.hoisted(() => vi.fn());
+const cancelIdentityLinkRequest = vi.hoisted(() => vi.fn());
+const reportIdentityConfirmed = vi.hoisted(() => vi.fn());
+
+vi.mock('@renderer/lib/ipc', () => ({
+ rpc: {
+ workspaces: {
+ listBridges,
+ listMyIdentities,
+ listMyPendingIdentities,
+ searchBridgeDirectory,
+ claimBridgeIdentity,
+ issueIdentityLinkCode,
+ releaseBridgeIdentity,
+ cancelIdentityLinkRequest,
+ reportIdentityConfirmed,
+ },
+ },
+ events: { on: () => () => {}, emit: () => {} },
+}));
+
+import { format } from 'date-fns';
+import type { AccountLinkTarget } from '@renderer/features/switch-servers/account-link-confirmation';
+import { ClaimIdentityModal } from '@renderer/features/switch-servers/ClaimIdentityModal';
+import { myIdentitiesQueryKey } from '@renderer/features/switch-servers/use-my-identities';
+import { Dialog } from '@renderer/lib/ui/dialog';
+import type {
+ ClaimIdentityResult,
+ LinkCode,
+ LinkedIdentity,
+ PendingIdentity,
+ RemoteBridge,
+} from '@shared/core/switch-servers/switch-servers';
+
+const SLACK: RemoteBridge = {
+ id: 'b-slack',
+ type: 'slack',
+ displayName: 'Acme Slack',
+ status: 'active',
+ isDefault: false,
+ homeUrl: null,
+ channelCreationSupported: true,
+ canCreateChannels: true,
+ directorySearchSupported: true,
+ attention: null,
+ teamPlacementSupported: false,
+ channelIdsRefused: null,
+ receivesWebhooks: false,
+ webhookUrl: null,
+};
+
+const PERSON = {
+ externalUserId: 'U1',
+ username: 'ada',
+ displayName: 'Ada Lovelace',
+ email: null,
+ knownExternalUserId: 'eu-1',
+ claimedBy: [],
+};
+
+function inMinutes(minutes: number): string {
+ return new Date(Date.now() + minutes * 60_000).toISOString();
+}
+
+const CODE: LinkCode = {
+ code: '7KQ2-M9XD',
+ expiresAt: inMinutes(30),
+ expiresInSeconds: 1800,
+ instructions: 'Run `/link-account 7KQ2-M9XD` from that account in any channel Switch is in.',
+};
+
+const LINKED: LinkedIdentity = {
+ id: 'eu-1',
+ bridgeId: 'b-slack',
+ bridgeDisplayName: 'Acme Slack',
+ bridgeType: 'slack',
+ externalUserId: 'U1',
+ externalUsername: 'ada',
+ verified: true,
+};
+
+const PENDING_RESULT = {
+ kind: 'pending' as const,
+ pending: {
+ id: 'eu-1',
+ bridgeId: 'b-slack',
+ bridgeDisplayName: 'Acme Slack',
+ bridgeType: 'slack',
+ externalUserId: 'U1',
+ externalUsername: 'ada',
+ requestedByName: null,
+ codeExpiresAt: CODE.expiresAt,
+ },
+ code: CODE,
+ alreadyLinked: false,
+};
+
+const onSuccess = vi.fn();
+const onClose = vi.fn();
+
+/** The links the server is holding for a code, as the pending list reports them. */
+let pendingOnServer: PendingIdentity[] = [];
+
+/** Answer the claim with `result`, starting a waiting link when it is one. */
+function claimReturns(result: ClaimIdentityResult): void {
+ claimBridgeIdentity.mockImplementation(async () => {
+ if (result.kind === 'pending' && !result.alreadyLinked) pendingOnServer = [result.pending];
+ return result;
+ });
+}
+
+let container: HTMLDivElement | null = null;
+let root: Root | null = null;
+let client: QueryClient;
+
+beforeEach(() => {
+ for (const mock of [
+ listBridges,
+ listMyIdentities,
+ listMyPendingIdentities,
+ searchBridgeDirectory,
+ claimBridgeIdentity,
+ issueIdentityLinkCode,
+ releaseBridgeIdentity,
+ cancelIdentityLinkRequest,
+ reportIdentityConfirmed,
+ onSuccess,
+ onClose,
+ ]) {
+ mock.mockReset();
+ }
+ listBridges.mockResolvedValue([SLACK]);
+ listMyIdentities.mockResolvedValue([]);
+ pendingOnServer = [];
+ listMyPendingIdentities.mockImplementation(async () => pendingOnServer);
+ searchBridgeDirectory.mockResolvedValue({ kind: 'results', users: [PERSON], note: null });
+ releaseBridgeIdentity.mockResolvedValue(undefined);
+ cancelIdentityLinkRequest.mockResolvedValue({ kind: 'cancelled' });
+ reportIdentityConfirmed.mockResolvedValue(undefined);
+ client = new QueryClient({ defaultOptions: { queries: { retry: false, gcTime: 0 } } });
+});
+
+afterEach(async () => {
+ if (root) await act(async () => root!.unmount());
+ container?.remove();
+ container = null;
+ root = null;
+});
+
+async function render(confirm?: AccountLinkTarget): Promise<HTMLElement> {
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+ await act(async () =>
+ root!.render(
+ <QueryClientProvider client={client}>
+ <Dialog open onOpenChange={() => {}}>
+ <ClaimIdentityModal
+ workspaceId="ws-1"
+ bridgeId="b-slack"
+ {...(confirm ? { confirm } : {})}
+ onSuccess={onSuccess}
+ onClose={onClose}
+ />
+ </Dialog>
+ </QueryClientProvider>
+ )
+ );
+ await settle();
+ return document.body;
+}
+
+async function settle(): Promise<void> {
+ for (let i = 0; i < 10; i++) await act(async () => await Promise.resolve());
+}
+
+function button(el: HTMLElement, label: string): HTMLButtonElement | undefined {
+ return [...el.querySelectorAll('button')].find((b) => b.textContent?.trim() === label);
+}
+
+async function click(target: HTMLElement | undefined): Promise<void> {
+ expect(target).toBeDefined();
+ await act(async () => target!.click());
+ await settle();
+}
+
+/** Search for Ada and press "This is me". */
+async function claimAda(el: HTMLElement): Promise<void> {
+ const input = el.querySelector('input') as HTMLInputElement;
+ await act(async () => {
+ Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, 'value')!.set!.call(
+ input,
+ 'ada'
+ );
+ input.dispatchEvent(new Event('input', { bubbles: true }));
+ });
+ await vi.waitFor(() => expect(button(el, 'This is me')).toBeDefined());
+ await click(button(el, 'This is me'));
+}
+
+describe('linking an account on a server that wants proof', () => {
+ it('stays open on the code rather than closing on the claim', async () => {
+ claimReturns(PENDING_RESULT);
+ const el = await render();
+
+ await claimAda(el);
+
+ expect(onSuccess).not.toHaveBeenCalled();
+ expect(el.querySelector('[data-testid="link-code"]')?.textContent).toBe('7KQ2-M9XD');
+ expect(el.textContent).toContain('To finish linking @ada, post this code');
+ // The server's instructions, with the command set as code rather than
+ // showing its backticks.
+ const command = [...el.querySelectorAll('code')].map((c) => c.textContent);
+ expect(command).toContain('/link-account 7KQ2-M9XD');
+ expect(el.textContent).not.toContain('`');
+ expect(el.textContent).toMatch(/It expires at \d\d:\d\d/);
+ expect(button(el, 'Copy')).toBeDefined();
+ });
+
+ it('gives a new code in place of the old one', async () => {
+ claimReturns(PENDING_RESULT);
+ issueIdentityLinkCode.mockResolvedValue({
+ kind: 'issued',
+ code: { ...CODE, code: 'ZZ99-AB12' },
+ });
+ const el = await render();
+ await claimAda(el);
+
+ await click(button(el, 'Get a new code'));
+
+ expect(issueIdentityLinkCode).toHaveBeenCalledWith({
+ workspaceId: 'ws-1',
+ bridgeId: 'b-slack',
+ identityId: 'eu-1',
+ });
+ expect(el.querySelector('[data-testid="link-code"]')?.textContent).toBe('ZZ99-AB12');
+ });
+
+ it('says so when the server will not give a new code', async () => {
+ claimReturns(PENDING_RESULT);
+ issueIdentityLinkCode.mockResolvedValue({
+ kind: 'refused',
+ message: 'You have not started linking this account. Link it first.',
+ });
+ const el = await render();
+ await claimAda(el);
+
+ await click(button(el, 'Get a new code'));
+
+ expect(el.textContent).toContain('You have not started linking this account.');
+ });
+
+ it('cancels the link and goes back to the search', async () => {
+ claimReturns(PENDING_RESULT);
+ const el = await render();
+ await claimAda(el);
+
+ await click(button(el, 'Cancel link'));
+
+ expect(cancelIdentityLinkRequest).toHaveBeenCalledWith({
+ workspaceId: 'ws-1',
+ bridgeId: 'b-slack',
+ identityId: 'eu-1',
+ });
+ expect(releaseBridgeIdentity).not.toHaveBeenCalled();
+ expect(el.querySelector('[data-testid="link-code"]')).toBeNull();
+ expect(el.textContent).toContain('Search Acme Slack');
+ expect(onSuccess).not.toHaveBeenCalled();
+ });
+
+ it('shows the link confirmed once it turns up, then finishes', async () => {
+ claimReturns(PENDING_RESULT);
+ const el = await render();
+ await claimAda(el);
+
+ // What the poll finds once the code has been posted.
+ listMyIdentities.mockResolvedValue([LINKED]);
+ await act(async () => client.invalidateQueries({ queryKey: myIdentitiesQueryKey('ws-1') }));
+ await settle();
+
+ expect(el.textContent).toContain('Linked to @ada.');
+ await vi.waitFor(() => expect(onSuccess).toHaveBeenCalledWith({ identity: LINKED }), {
+ timeout: 3000,
+ });
+ // Counted once, for the link this screen watched become confirmed.
+ expect(reportIdentityConfirmed).toHaveBeenCalledTimes(1);
+ expect(reportIdentityConfirmed).toHaveBeenCalledWith({
+ workspaceId: 'ws-1',
+ bridgeId: 'b-slack',
+ identityId: 'eu-1',
+ kind: 'pending',
+ });
+ });
+
+ it('notices a link cancelled somewhere else, and offers to start again', async () => {
+ claimReturns(PENDING_RESULT);
+ const el = await render();
+ await claimAda(el);
+ await settle();
+ expect(el.querySelector('[data-testid="link-code"]')).not.toBeNull();
+
+ // An admin cancels it: it is neither waiting nor linked any more.
+ pendingOnServer = [];
+ await act(async () => client.invalidateQueries({ queryKey: myIdentitiesQueryKey('ws-1') }));
+ await vi.waitFor(() => expect(el.textContent).toContain('was cancelled'));
+
+ expect(el.querySelector('[data-testid="link-code"]')).toBeNull();
+ await click(button(el, 'Start again'));
+ expect(el.textContent).toContain('Search Acme Slack');
+ expect(reportIdentityConfirmed).not.toHaveBeenCalled();
+ });
+
+ it('does not mistake a confirmation landing between two reads for a cancel', async () => {
+ // The pending list is read after the code is posted and the linked list
+ // just before: neither shows the link. A fresh read of the linked list
+ // settles it.
+ claimReturns(PENDING_RESULT);
+ const el = await render();
+ await claimAda(el);
+ await settle();
+
+ pendingOnServer = [];
+ listMyIdentities.mockResolvedValueOnce([]).mockResolvedValue([LINKED]);
+ await act(async () => client.invalidateQueries({ queryKey: myIdentitiesQueryKey('ws-1') }));
+
+ await vi.waitFor(() => expect(el.textContent).toContain('Linked to @ada.'));
+ expect(el.textContent).not.toContain('was cancelled');
+ });
+
+ it('stays on the code when there was nothing left to cancel', async () => {
+ claimReturns(PENDING_RESULT);
+ cancelIdentityLinkRequest.mockResolvedValue({
+ kind: 'refused',
+ message: 'Nothing is waiting to be confirmed.',
+ });
+ const el = await render();
+ await claimAda(el);
+
+ await click(button(el, 'Cancel link'));
+
+ expect(el.textContent).toContain('Nothing is waiting to be confirmed.');
+ expect(el.querySelector('[data-testid="link-code"]')).not.toBeNull();
+ });
+
+ it('treats re-claiming an unconfirmed link as confirming it, which Cancel leaves standing', async () => {
+ // The server answers such a claim with a code like any other; the link it
+ // already has works meanwhile, so the screen must not talk of finishing a
+ // link, and Cancel must withdraw only the code.
+ claimReturns({ ...PENDING_RESULT, alreadyLinked: true });
+ const el = await render();
+ await claimAda(el);
+
+ expect(el.textContent).toContain('Confirm @ada is yours');
+ await click(button(el, 'Cancel confirmation'));
+
+ expect(cancelIdentityLinkRequest).toHaveBeenCalledTimes(1);
+ expect(releaseBridgeIdentity).not.toHaveBeenCalled();
+ expect(el.textContent).toContain('Search Acme Slack');
+ });
+
+ it('says when the code has run out, and offers a new one', async () => {
+ claimReturns({
+ ...PENDING_RESULT,
+ code: { ...CODE, expiresInSeconds: 0 },
+ });
+ const el = await render();
+ await claimAda(el);
+ await vi.waitFor(() => expect(el.textContent).toContain('This code has expired.'));
+
+ expect(button(el, 'Copy')?.disabled).toBe(true);
+ expect(button(el, 'Get a new code')?.disabled).toBe(false);
+ });
+
+ it('keeps looking for the link after the code seems to have run out', async () => {
+ // The expiry is read off this machine's clock. One running fast would
+ // otherwise stop the app noticing a code that was posted in time.
+ claimReturns({
+ ...PENDING_RESULT,
+ code: { ...CODE, expiresInSeconds: 0 },
+ });
+ const el = await render();
+ await claimAda(el);
+ await vi.waitFor(() => expect(el.textContent).toContain('This code has expired.'));
+
+ listMyIdentities.mockResolvedValue([LINKED]);
+
+ await vi.waitFor(() => expect(el.textContent).toContain('Linked to @ada.'), {
+ timeout: 6000,
+ });
+ });
+});
+
+describe('a clock on this machine that is wrong', () => {
+ it('counts a fresh code from when it arrived, not from the server’s clock', async () => {
+ // This machine runs 45 minutes fast, so the server's "expires at" is
+ // already in its past. The code has its full 30 minutes all the same.
+ claimReturns({
+ ...PENDING_RESULT,
+ code: { ...CODE, expiresAt: inMinutes(-15), expiresInSeconds: 1800 },
+ });
+ const before = format(Date.now() + 1_800_000, 'HH:mm');
+ const el = await render();
+ await claimAda(el);
+ const after = format(Date.now() + 1_800_000, 'HH:mm');
+
+ expect(el.textContent).not.toContain('This code has expired.');
+ expect(button(el, 'Copy')?.disabled).toBe(false);
+ // The deadline is shown on the clock the user is looking at.
+ const shown = /It expires at (\d\d:\d\d)/.exec(el.textContent ?? '')?.[1];
+ expect([before, after]).toContain(shown);
+ });
+
+ it('falls back to the server’s expiry from a server that sends no lifetime', async () => {
+ claimReturns({
+ ...PENDING_RESULT,
+ code: { ...CODE, expiresAt: inMinutes(-1), expiresInSeconds: null },
+ });
+ const el = await render();
+ await claimAda(el);
+
+ await vi.waitFor(() => expect(el.textContent).toContain('This code has expired.'));
+ });
+});
+
+describe('opening straight on a link that needs its code', () => {
+ it('asks for a fresh code on open, once', async () => {
+ pendingOnServer = [PENDING_RESULT.pending];
+ issueIdentityLinkCode.mockResolvedValue({ kind: 'issued', code: CODE });
+ const el = await render({ identityId: 'eu-1', externalUsername: 'ada', kind: 'pending' });
+
+ await vi.waitFor(() =>
+ expect(el.querySelector('[data-testid="link-code"]')?.textContent).toBe('7KQ2-M9XD')
+ );
+ expect(issueIdentityLinkCode).toHaveBeenCalledTimes(1);
+ expect(button(el, 'Cancel link')).toBeDefined();
+ });
+
+ it('withdraws only the code when confirming a link made before confirming', async () => {
+ // That link works today. Cancel takes back the code, never the link.
+ listMyIdentities.mockResolvedValue([{ ...LINKED, verified: false }]);
+ issueIdentityLinkCode.mockResolvedValue({ kind: 'issued', code: CODE });
+ const el = await render({ identityId: 'eu-1', externalUsername: 'ada', kind: 'unverified' });
+ await vi.waitFor(() => expect(el.querySelector('[data-testid="link-code"]')).not.toBeNull());
+
+ expect(el.textContent).toContain('Confirm @ada is yours');
+ expect(button(el, 'Cancel link')).toBeUndefined();
+ await click(button(el, 'Cancel confirmation'));
+
+ expect(cancelIdentityLinkRequest).toHaveBeenCalledWith({
+ workspaceId: 'ws-1',
+ bridgeId: 'b-slack',
+ identityId: 'eu-1',
+ });
+ expect(releaseBridgeIdentity).not.toHaveBeenCalled();
+ expect(onClose).toHaveBeenCalledTimes(1);
+ // Requests for links that already exist are not in the pending list, so
+ // it is not watched for one.
+ expect(listMyPendingIdentities).not.toHaveBeenCalled();
+ });
+
+ it('does not count a link that was already confirmed when it opened', async () => {
+ listMyIdentities.mockResolvedValue([LINKED]);
+ issueIdentityLinkCode.mockResolvedValue({ kind: 'issued', code: CODE });
+ const el = await render({ identityId: 'eu-1', externalUsername: 'ada', kind: 'unverified' });
+
+ await vi.waitFor(() => expect(el.textContent).toContain('@ada is confirmed.'));
+ await vi.waitFor(() => expect(onSuccess).toHaveBeenCalled(), { timeout: 3000 });
+ expect(reportIdentityConfirmed).not.toHaveBeenCalled();
+ });
+
+ it('closes without cancelling anything', async () => {
+ listMyIdentities.mockResolvedValue([{ ...LINKED, verified: false }]);
+ issueIdentityLinkCode.mockResolvedValue({ kind: 'issued', code: CODE });
+ const el = await render({ identityId: 'eu-1', externalUsername: 'ada', kind: 'unverified' });
+ await vi.waitFor(() => expect(el.querySelector('[data-testid="link-code"]')).not.toBeNull());
+
+ await click(button(el, 'Close'));
+
+ expect(onClose).toHaveBeenCalledTimes(1);
+ expect(cancelIdentityLinkRequest).not.toHaveBeenCalled();
+ expect(releaseBridgeIdentity).not.toHaveBeenCalled();
+ });
+});
+
+describe('a server that predates confirming links', () => {
+ it('links at once and closes, as before', async () => {
+ claimReturns({ kind: 'claimed', identity: LINKED });
+ const el = await render();
+
+ await claimAda(el);
+
+ expect(onSuccess).toHaveBeenCalledWith({ identity: LINKED });
+ expect(el.querySelector('[data-testid="link-code"]')).toBeNull();
+ });
+});
diff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/link-account-prompts.test.tsx b/console/apps/switch-console-desktop/src/renderer/tests/browser/link-account-prompts.test.tsx
index d0a531f75..45c6b826b 100644
--- a/console/apps/switch-console-desktop/src/renderer/tests/browser/link-account-prompts.test.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/tests/browser/link-account-prompts.test.tsx
@@ -3,7 +3,9 @@
*
* Adding an app ends with a link step the person may skip. While their account
* on an active app stays unlinked the server home keeps offering it, and the
- * offer goes away once the account is claimed.
+ * offer goes away once the account is claimed. A link waiting for its code, or
+ * one made before links had to be confirmed, gets a prompt of its own that
+ * opens on the code rather than the search.
*/
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { act } from 'react';
@@ -19,10 +21,11 @@ vi.hoisted(() => {
});
const listMyIdentities = vi.hoisted(() => vi.fn());
+const listMyPendingIdentities = vi.hoisted(() => vi.fn());
const showModal = vi.hoisted(() => vi.fn());
vi.mock('@renderer/lib/ipc', () => ({
- rpc: { workspaces: { listMyIdentities } },
+ rpc: { workspaces: { listMyIdentities, listMyPendingIdentities } },
events: { on: () => () => {}, emit: () => {} },
}));
vi.mock('@renderer/lib/modal/modal-provider', () => ({
@@ -33,8 +36,13 @@ import { LinkAccountPrompts } from '@renderer/features/switch-servers/link-accou
import {
myIdentitiesQueryKey,
useMyIdentities,
+ useMyPendingIdentities,
} from '@renderer/features/switch-servers/use-my-identities';
-import type { LinkedIdentity, RemoteBridge } from '@shared/core/switch-servers/switch-servers';
+import type {
+ LinkedIdentity,
+ PendingIdentity,
+ RemoteBridge,
+} from '@shared/core/switch-servers/switch-servers';
function bridge(id: string, type: string, patch: Partial<RemoteBridge> = {}): RemoteBridge {
return {
@@ -63,11 +71,31 @@ const SLACK_IDENTITY: LinkedIdentity = {
bridgeType: 'slack',
externalUserId: 'U1',
externalUsername: 'me',
+ verified: true,
+};
+
+const SLACK_PENDING: PendingIdentity = {
+ id: 'eu-1',
+ bridgeId: 'b-slack',
+ bridgeDisplayName: 'slack workspace',
+ bridgeType: 'slack',
+ externalUserId: 'U1',
+ externalUsername: 'me',
+ requestedByName: null,
+ codeExpiresAt: '2026-10-27T12:30:00Z',
};
function Home({ bridges }: { bridges: RemoteBridge[] }) {
const { identities } = useMyIdentities('ws-1');
- return <LinkAccountPrompts workspaceId="ws-1" bridges={bridges} identities={identities} />;
+ const { pending } = useMyPendingIdentities('ws-1');
+ return (
+ <LinkAccountPrompts
+ workspaceId="ws-1"
+ bridges={bridges}
+ identities={identities}
+ pending={pending}
+ />
+ );
}
let container: HTMLDivElement | null = null;
@@ -76,6 +104,7 @@ let client: QueryClient;
beforeEach(() => {
listMyIdentities.mockReset();
+ listMyPendingIdentities.mockReset().mockResolvedValue([]);
showModal.mockReset();
client = new QueryClient({ defaultOptions: { queries: { retry: false, gcTime: 0 } } });
});
@@ -152,4 +181,67 @@ describe('the link-your-account reminder', () => {
expect(el.textContent).toBe('');
});
+
+ it('says a link is waiting for its code, and opens on a fresh one', async () => {
+ listMyIdentities.mockResolvedValue([]);
+ listMyPendingIdentities.mockResolvedValue([SLACK_PENDING]);
+ const el = await render([bridge('b-slack', 'slack')]);
+
+ expect(el.textContent).toContain('Finish linking your Slack account');
+ expect(el.textContent).toContain('Waiting for a code to be posted from @me');
+ expect(el.textContent).not.toContain('Link your Slack account');
+
+ const show = [...el.querySelectorAll('button')].find((b) => b.textContent === 'Show code');
+ await act(async () => show!.click());
+ expect(showModal).toHaveBeenCalledWith('claimIdentityModal', {
+ workspaceId: 'ws-1',
+ bridgeId: 'b-slack',
+ confirm: { identityId: 'eu-1', externalUsername: 'me', kind: 'pending' },
+ });
+ });
+
+ it('names the admin who started a link on the person’s behalf', async () => {
+ listMyIdentities.mockResolvedValue([]);
+ listMyPendingIdentities.mockResolvedValue([
+ { ...SLACK_PENDING, requestedByName: 'Ada Admin', codeExpiresAt: null },
+ ]);
+ const el = await render([bridge('b-slack', 'slack')]);
+
+ expect(el.textContent).toContain('Ada Admin started linking @me');
+ });
+
+ it('asks to confirm a link made before links had to be confirmed', async () => {
+ listMyIdentities.mockResolvedValue([{ ...SLACK_IDENTITY, verified: false }]);
+ const el = await render([bridge('b-slack', 'slack')]);
+
+ expect(el.textContent).toContain('Confirm your Slack account');
+ expect(el.textContent).not.toContain('Link your Slack account');
+
+ const confirm = [...el.querySelectorAll('button')].find((b) => b.textContent === 'Confirm');
+ await act(async () => confirm!.click());
+ expect(showModal).toHaveBeenCalledWith('claimIdentityModal', {
+ workspaceId: 'ws-1',
+ bridgeId: 'b-slack',
+ confirm: { identityId: 'eu-1', externalUsername: 'me', kind: 'unverified' },
+ });
+ });
+
+ it('still asks to link when the pending links cannot be read', async () => {
+ listMyIdentities.mockResolvedValue([]);
+ listMyPendingIdentities.mockRejectedValue(new Error('pending links unavailable'));
+ const el = await render([bridge('b-slack', 'slack')]);
+
+ expect(el.textContent).toContain('Link your Slack account');
+ });
+
+ it('prompts as before against a server that predates confirming links', async () => {
+ // Such a server lists no pending links (its 404 reads as none) and every
+ // link it reports reads as confirmed.
+ listMyIdentities.mockResolvedValue([SLACK_IDENTITY]);
+ listMyPendingIdentities.mockResolvedValue([]);
+ const el = await render([bridge('b-slack', 'slack'), bridge('b-mm', 'mattermost')]);
+
+ expect(el.textContent).toContain('Link your Mattermost account');
+ expect(el.textContent).not.toContain('Slack');
+ });
});
diff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/messaging-app-row.test.tsx b/console/apps/switch-console-desktop/src/renderer/tests/browser/messaging-app-row.test.tsx
index 273cbe513..212f2e02f 100644
--- a/console/apps/switch-console-desktop/src/renderer/tests/browser/messaging-app-row.test.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/tests/browser/messaging-app-row.test.tsx
@@ -14,11 +14,15 @@ vi.hoisted(() => {
});
const beginMessagingAppInstall = vi.hoisted(() => vi.fn());
+const releaseBridgeIdentity = vi.hoisted(() => vi.fn());
+const cancelIdentityLinkRequest = vi.hoisted(() => vi.fn());
const openExternalUrl = vi.hoisted(() => vi.fn());
const showModal = vi.hoisted(() => vi.fn());
vi.mock('@renderer/lib/ipc', () => ({
- rpc: { workspaces: { beginMessagingAppInstall } },
+ rpc: {
+ workspaces: { beginMessagingAppInstall, releaseBridgeIdentity, cancelIdentityLinkRequest },
+ },
events: { on: () => () => {}, emit: () => {} },
}));
vi.mock('@renderer/lib/open-external', () => ({ openExternalUrl }));
@@ -38,7 +42,11 @@ vi.mock('@renderer/lib/modal/modal-provider', () => ({
* the row menu.
*/
import { MessagingAppRow } from '@renderer/features/switch-servers/MessagingAppsCard';
-import type { LinkedIdentity, RemoteBridge } from '@shared/core/switch-servers/switch-servers';
+import type {
+ LinkedIdentity,
+ PendingIdentity,
+ RemoteBridge,
+} from '@shared/core/switch-servers/switch-servers';
let container: HTMLDivElement | null = null;
let root: Root | null = null;
@@ -85,6 +93,18 @@ const IDENTITY: LinkedIdentity = {
bridgeType: 'slack',
externalUserId: 'U1',
externalUsername: 'amaudruz.louis',
+ verified: true,
+};
+
+const PENDING: PendingIdentity = {
+ id: 'eu-1',
+ bridgeId: 'b-slack',
+ bridgeDisplayName: 'Slack Test',
+ bridgeType: 'slack',
+ externalUserId: 'U1',
+ externalUsername: 'amaudruz.louis',
+ requestedByName: null,
+ codeExpiresAt: '2026-10-27T12:30:00Z',
};
function row(
@@ -92,6 +112,9 @@ function row(
workspaceId?: string | null;
bridge?: RemoteBridge;
identities?: LinkedIdentity[] | null;
+ pending?: PendingIdentity[] | null;
+ onReleased?: () => void;
+ olderLinks?: { count: number; onRequireConfirmation: () => void } | null;
isAdmin?: boolean;
onConnectChat?: (() => void) | null;
onDisconnect?: () => void;
@@ -103,8 +126,10 @@ function row(
serverId="srv-1"
bridge={overrides.bridge ?? bridge()}
identities={overrides.identities === undefined ? [] : overrides.identities}
+ pending={overrides.pending === undefined ? [] : overrides.pending}
currentUserId="u1"
- onReleased={() => {}}
+ onReleased={overrides.onReleased ?? (() => {})}
+ olderLinks={overrides.olderLinks ?? null}
showBundledSignIn={false}
isAdmin={overrides.isAdmin ?? false}
savingChannelCreation={false}
@@ -176,6 +201,116 @@ describe('the identity column', () => {
});
});
+/**
+ * Links have to be confirmed with a code posted from the account (CHOO-3881).
+ * One still waiting counts for nothing and must never read as linked; one made
+ * before confirming works, and asks to be confirmed.
+ */
+describe('a link that needs its code', () => {
+ it('shows a waiting link as waiting, with the code one click away', async () => {
+ const el = await render(row({ identities: [], pending: [PENDING] }));
+
+ expect(el.textContent).toContain('Waiting for confirmation');
+ expect(el.textContent).not.toContain('No account linked');
+ expect(buttonLabels(el)).not.toContain('Link');
+
+ const show = [...el.querySelectorAll('button')].find((b) => b.textContent === 'Show code');
+ await act(async () => show!.click());
+ expect(showModal).toHaveBeenCalledWith('claimIdentityModal', {
+ workspaceId: 'ws-1',
+ bridgeId: 'b-slack',
+ confirm: { identityId: 'eu-1', externalUsername: 'amaudruz.louis', kind: 'pending' },
+ });
+ });
+
+ it('cancels a waiting link from the menu, withdrawing only the request', async () => {
+ releaseBridgeIdentity.mockReset();
+ cancelIdentityLinkRequest.mockReset().mockResolvedValue({ kind: 'cancelled' });
+ const onReleased = vi.fn();
+ const el = await render(row({ identities: [], pending: [PENDING], onReleased }));
+
+ expect(await openMenu(el)).toContain('Cancel link to @amaudruz.louis');
+ const item = [...document.querySelectorAll<HTMLElement>('[role="menuitem"]')].find(
+ (i) => i.textContent?.trim() === 'Cancel link to @amaudruz.louis'
+ );
+ await act(async () => item!.click());
+ await settle();
+
+ expect(cancelIdentityLinkRequest).toHaveBeenCalledWith({
+ workspaceId: 'ws-1',
+ bridgeId: 'b-slack',
+ identityId: 'eu-1',
+ });
+ expect(releaseBridgeIdentity).not.toHaveBeenCalled();
+ expect(onReleased).toHaveBeenCalledTimes(1);
+ });
+
+ it('says why a cancel did nothing, in the server’s words', async () => {
+ cancelIdentityLinkRequest.mockReset().mockResolvedValue({
+ kind: 'refused',
+ message: 'Nothing is waiting to be confirmed.',
+ });
+ const el = await render(row({ identities: [], pending: [PENDING] }));
+
+ await openMenu(el);
+ const item = [...document.querySelectorAll<HTMLElement>('[role="menuitem"]')].find(
+ (i) => i.textContent?.trim() === 'Cancel link to @amaudruz.louis'
+ );
+ await act(async () => item!.click());
+ await settle();
+
+ expect(el.textContent).toContain('Nothing is waiting to be confirmed.');
+ });
+
+ it('names the confirmed account when several are linked on the app', async () => {
+ const el = await render(
+ row({
+ identities: [
+ { ...IDENTITY, id: 'eu-old', externalUsername: 'old.handle', verified: false },
+ IDENTITY,
+ ],
+ })
+ );
+
+ expect(el.textContent).toContain('@amaudruz.louis');
+ expect(el.textContent).not.toContain('@old.handle');
+ expect(el.textContent).not.toContain('Not confirmed');
+ expect(buttonLabels(el)).not.toContain('Confirm');
+ });
+
+ it('marks a link made before confirming as not confirmed, and offers to confirm it', async () => {
+ const el = await render(row({ identities: [{ ...IDENTITY, verified: false }] }));
+
+ expect(el.textContent).toContain('@amaudruz.louis');
+ expect(el.textContent).toContain('Not confirmed');
+
+ const confirm = [...el.querySelectorAll('button')].find((b) => b.textContent === 'Confirm');
+ await act(async () => confirm!.click());
+ expect(showModal).toHaveBeenCalledWith('claimIdentityModal', {
+ workspaceId: 'ws-1',
+ bridgeId: 'b-slack',
+ confirm: { identityId: 'eu-1', externalUsername: 'amaudruz.louis', kind: 'unverified' },
+ });
+ });
+
+ it('keeps Unlink, not Cancel, for a link made before confirming', async () => {
+ // Cancelling drops the link outright, and this one works today.
+ const el = await render(row({ identities: [{ ...IDENTITY, verified: false }] }));
+
+ const labels = await openMenu(el);
+ expect(labels).toContain('Unlink @amaudruz.louis');
+ expect(labels.some((l) => l.startsWith('Cancel link'))).toBe(false);
+ });
+
+ it('shows a confirmed link as before, with nothing to confirm', async () => {
+ const el = await render(row({ identities: [IDENTITY], pending: [PENDING] }));
+
+ expect(el.textContent).not.toContain('Not confirmed');
+ expect(el.textContent).not.toContain('Waiting for confirmation');
+ expect(buttonLabels(el)).not.toContain('Confirm');
+ });
+});
+
describe('the app name and its badges', () => {
it('keeps Default beside the name rather than adrift in the row', async () => {
// With the name set to grow, the badge was pushed away from what it
@@ -196,6 +331,30 @@ describe('the app name and its badges', () => {
});
});
+describe('requiring confirmation for older links', () => {
+ it('is offered with how many there are, and opens the confirmation', async () => {
+ const onRequireConfirmation = vi.fn();
+ const el = await render(
+ row({ isAdmin: true, olderLinks: { count: 3, onRequireConfirmation } })
+ );
+
+ expect(await openMenu(el)).toContain('Require confirmation for older links (3)…');
+ const item = [...document.querySelectorAll<HTMLElement>('[role="menuitem"]')].find(
+ (i) => i.textContent?.trim() === 'Require confirmation for older links (3)…'
+ );
+ await act(async () => item!.click());
+
+ expect(onRequireConfirmation).toHaveBeenCalledTimes(1);
+ });
+
+ it('is not offered when the card has nothing to offer', async () => {
+ const el = await render(row({ isAdmin: true, olderLinks: null }));
+
+ const labels = await openMenu(el);
+ expect(labels.some((l) => l.startsWith('Require confirmation'))).toBe(false);
+ });
+});
+
describe('the row menu', () => {
it('offers the webhook address of a connection that receives events on one', async () => {
const el = await render(
diff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/messaging-apps-card-older-links.test.tsx b/console/apps/switch-console-desktop/src/renderer/tests/browser/messaging-apps-card-older-links.test.tsx
new file mode 100644
index 000000000..cae57cd58
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/renderer/tests/browser/messaging-apps-card-older-links.test.tsx
@@ -0,0 +1,198 @@
+/**
+ * Requiring confirmation for a messaging app's older links (CHOO-3881).
+ *
+ * Links made before links had to be confirmed still count, though nobody
+ * proved the account was theirs. A workspace admin can make them wait for a
+ * code like new ones. The card offers that per app, only to an admin, only
+ * where there is something to move — and never asks the admin-only route on
+ * anyone else's behalf.
+ */
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
+import { act } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+vi.hoisted(() => {
+ window.electronAPI ??= {
+ invoke: () => Promise.resolve(undefined),
+ eventOn: () => () => {},
+ eventSend: () => {},
+ } as unknown as typeof window.electronAPI;
+});
+
+const listBridges = vi.hoisted(() => vi.fn());
+const listMyIdentities = vi.hoisted(() => vi.fn());
+const listMyPendingIdentities = vi.hoisted(() => vi.fn());
+const listUnconfirmedLinks = vi.hoisted(() => vi.fn());
+const ownsOwnerAddressedAgent = vi.hoisted(() => vi.fn());
+const bridgeInstallState = vi.hoisted(() => vi.fn());
+const showModal = vi.hoisted(() => vi.fn());
+const isAdmin = vi.hoisted(() => ({ value: true }));
+
+vi.mock('@renderer/lib/ipc', () => ({
+ rpc: {
+ workspaces: {
+ listBridges,
+ listMyIdentities,
+ listMyPendingIdentities,
+ listUnconfirmedLinks,
+ ownsOwnerAddressedAgent,
+ bridgeInstallState,
+ },
+ featureFlags: { get: () => Promise.resolve({ flags: {} }) },
+ },
+ events: { on: () => () => {}, emit: () => {} },
+}));
+vi.mock('@renderer/lib/modal/modal-provider', () => ({
+ useShowModal: (id: string) => (args: unknown) => showModal(id, args),
+}));
+vi.mock('@renderer/features/workspaces/workspaces-store', () => ({
+ workspacesStore: { idOnServerInScope: () => 'ws-1', serverIdFor: () => 'srv-1' },
+}));
+vi.mock('@renderer/features/switch-servers/workspace-admin', () => ({
+ administersWorkspaceInScope: () => isAdmin.value,
+}));
+vi.mock('@renderer/features/switch-servers/switch-servers-store', () => ({
+ switchServersStore: { servers: [], statusFor: () => null },
+}));
+vi.mock('@renderer/features/switch-servers/switch-rooms-store', () => ({
+ switchRoomsStore: { refreshRoomState: () => Promise.resolve() },
+}));
+vi.mock('@renderer/features/switch-servers/bridge-platforms-loader', () => ({
+ bridgeTypesQueryKey: (workspaceId: string | null) => ['bridge-types', workspaceId],
+ fetchBridgeTypes: () => Promise.resolve([]),
+}));
+
+import { MessagingAppsCard } from '@renderer/features/switch-servers/MessagingAppsCard';
+import type { RemoteBridge, UnconfirmedLink } from '@shared/core/switch-servers/switch-servers';
+
+function bridge(id: string, displayName: string): RemoteBridge {
+ return {
+ id,
+ type: 'slack',
+ displayName,
+ status: 'active',
+ isDefault: false,
+ homeUrl: null,
+ channelCreationSupported: true,
+ canCreateChannels: true,
+ directorySearchSupported: true,
+ attention: null,
+ teamPlacementSupported: false,
+ channelIdsRefused: null,
+ receivesWebhooks: false,
+ webhookUrl: null,
+ };
+}
+
+function link(n: number): UnconfirmedLink {
+ return {
+ id: `eu-${n}`,
+ externalUserId: `U${n}`,
+ externalUsername: `person${n}`,
+ userId: `u${n}`,
+ userName: `Person ${n}`,
+ };
+}
+
+let container: HTMLDivElement | null = null;
+let root: Root | null = null;
+
+beforeEach(() => {
+ for (const mock of [
+ listBridges,
+ listMyIdentities,
+ listMyPendingIdentities,
+ listUnconfirmedLinks,
+ ownsOwnerAddressedAgent,
+ bridgeInstallState,
+ showModal,
+ ]) {
+ mock.mockReset();
+ }
+ isAdmin.value = true;
+ listBridges.mockResolvedValue([bridge('b-acme', 'Acme Slack'), bridge('b-other', 'Other')]);
+ listMyIdentities.mockResolvedValue([]);
+ listMyPendingIdentities.mockResolvedValue([]);
+ ownsOwnerAddressedAgent.mockResolvedValue(false);
+ bridgeInstallState.mockResolvedValue('unknown');
+ listUnconfirmedLinks.mockImplementation(async ({ bridgeId }: { bridgeId: string }) =>
+ bridgeId === 'b-acme' ? [link(1), link(2)] : []
+ );
+});
+
+afterEach(async () => {
+ if (root) await act(async () => root!.unmount());
+ container?.remove();
+ container = null;
+ root = null;
+});
+
+async function render(): Promise<HTMLDivElement> {
+ const client = new QueryClient({ defaultOptions: { queries: { retry: false, gcTime: 0 } } });
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+ await act(async () =>
+ root!.render(
+ <QueryClientProvider client={client}>
+ <MessagingAppsCard serverId="srv-1" />
+ </QueryClientProvider>
+ )
+ );
+ for (let i = 0; i < 10; i++) await act(async () => await Promise.resolve());
+ return container;
+}
+
+/** The menu labels for the row of the app with this name. */
+async function menuOf(el: HTMLElement, displayName: string): Promise<HTMLElement[]> {
+ const trigger = el.querySelector<HTMLButtonElement>(
+ `button[aria-label="${displayName} actions"]`
+ );
+ expect(trigger, `no row for ${displayName}`).not.toBeNull();
+ await act(async () => trigger!.click());
+ return [...document.querySelectorAll<HTMLElement>('[role="menuitem"]')];
+}
+
+describe('older links on the messaging apps card', () => {
+ it('offers an admin to require confirming them, with the count', async () => {
+ const el = await render();
+ await vi.waitFor(() =>
+ expect(listUnconfirmedLinks).toHaveBeenCalledWith({ workspaceId: 'ws-1', bridgeId: 'b-acme' })
+ );
+
+ const item = (await menuOf(el, 'Acme Slack')).find(
+ (i) => i.textContent?.trim() === 'Require confirmation for older links (2)…'
+ );
+ expect(item).toBeDefined();
+ await act(async () => item!.click());
+
+ expect(showModal).toHaveBeenCalledWith('requireLinkConfirmationModal', {
+ workspaceId: 'ws-1',
+ bridgeId: 'b-acme',
+ bridgeDisplayName: 'Acme Slack',
+ });
+ });
+
+ it('offers nothing on an app with no older links', async () => {
+ const el = await render();
+ await vi.waitFor(() =>
+ expect(listUnconfirmedLinks).toHaveBeenCalledWith({
+ workspaceId: 'ws-1',
+ bridgeId: 'b-other',
+ })
+ );
+
+ const labels = (await menuOf(el, 'Other')).map((i) => i.textContent?.trim() ?? '');
+ expect(labels.some((l) => l.startsWith('Require confirmation'))).toBe(false);
+ });
+
+ it('never asks for them, nor offers it, to someone who is not an admin', async () => {
+ isAdmin.value = false;
+ const el = await render();
+
+ const labels = (await menuOf(el, 'Acme Slack')).map((i) => i.textContent?.trim() ?? '');
+ expect(labels.some((l) => l.startsWith('Require confirmation'))).toBe(false);
+ expect(listUnconfirmedLinks).not.toHaveBeenCalled();
+ });
+});
diff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/require-link-confirmation-modal.test.tsx b/console/apps/switch-console-desktop/src/renderer/tests/browser/require-link-confirmation-modal.test.tsx
new file mode 100644
index 000000000..6aea7c20d
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/renderer/tests/browser/require-link-confirmation-modal.test.tsx
@@ -0,0 +1,158 @@
+/**
+ * Confirming that a messaging app's older links must be confirmed (CHOO-3881).
+ *
+ * Every one of them stops counting at once, which locks its owner out of
+ * their own owner-only agents until they post a code. So the dialog names
+ * everyone affected and says what it costs before anything moves.
+ */
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
+import { act } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+vi.hoisted(() => {
+ window.electronAPI ??= {
+ invoke: () => Promise.resolve(undefined),
+ eventOn: () => () => {},
+ eventSend: () => {},
+ } as unknown as typeof window.electronAPI;
+});
+
+const listUnconfirmedLinks = vi.hoisted(() => vi.fn());
+const requireLinkConfirmation = vi.hoisted(() => vi.fn());
+const toast = vi.hoisted(() => vi.fn());
+
+vi.mock('@renderer/lib/ipc', () => ({
+ rpc: { workspaces: { listUnconfirmedLinks, requireLinkConfirmation } },
+ events: { on: () => () => {}, emit: () => {} },
+}));
+vi.mock('@renderer/lib/hooks/use-toast', () => ({ toast }));
+
+import { RequireLinkConfirmationModal } from '@renderer/features/switch-servers/RequireLinkConfirmationModal';
+import { unconfirmedLinksQueryKey } from '@renderer/features/switch-servers/unconfirmed-links';
+import { myIdentitiesQueryKey } from '@renderer/features/switch-servers/use-my-identities';
+import { Dialog } from '@renderer/lib/ui/dialog';
+
+const LINKS = [
+ { id: 'eu-1', externalUserId: 'U1', externalUsername: 'ada', userId: 'u1', userName: 'Ada' },
+ { id: 'eu-2', externalUserId: 'U2', externalUsername: '@grace', userId: 'u2', userName: 'Grace' },
+];
+
+const onSuccess = vi.fn();
+const onClose = vi.fn();
+
+let container: HTMLDivElement | null = null;
+let root: Root | null = null;
+let client: QueryClient;
+
+beforeEach(() => {
+ for (const mock of [listUnconfirmedLinks, requireLinkConfirmation, toast, onSuccess, onClose]) {
+ mock.mockReset();
+ }
+ listUnconfirmedLinks.mockResolvedValue(LINKS);
+ client = new QueryClient({ defaultOptions: { queries: { retry: false, gcTime: 0 } } });
+});
+
+afterEach(async () => {
+ if (root) await act(async () => root!.unmount());
+ container?.remove();
+ container = null;
+ root = null;
+});
+
+async function render(): Promise<HTMLElement> {
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+ await act(async () =>
+ root!.render(
+ <QueryClientProvider client={client}>
+ <Dialog open onOpenChange={() => {}}>
+ <RequireLinkConfirmationModal
+ workspaceId="ws-1"
+ bridgeId="b-acme"
+ bridgeDisplayName="Acme Slack"
+ onSuccess={onSuccess}
+ onClose={onClose}
+ />
+ </Dialog>
+ </QueryClientProvider>
+ )
+ );
+ await settle();
+ return document.body;
+}
+
+async function settle(): Promise<void> {
+ for (let i = 0; i < 10; i++) await act(async () => await Promise.resolve());
+}
+
+function button(el: HTMLElement, label: string): HTMLButtonElement | undefined {
+ return [...el.querySelectorAll('button')].find((b) => b.textContent?.trim().startsWith(label));
+}
+
+describe('requiring confirmation for older links', () => {
+ it('names everyone affected and what it costs them', async () => {
+ const el = await render();
+
+ expect(el.textContent).toContain('made before links had to be confirmed');
+ const rows = [...el.querySelectorAll('[data-testid="unconfirmed-links"] li')].map(
+ (li) => li.textContent
+ );
+ expect(rows).toEqual(['Ada@ada', 'Grace@grace']);
+ expect(el.textContent).toContain('Until each person posts the code Console shows them');
+ expect(button(el, 'Cancel')).toBeDefined();
+ });
+
+ it('moves them, says how many, refreshes the lists and closes', async () => {
+ requireLinkConfirmation.mockResolvedValue({ kind: 'required', moved: 2 });
+ const invalidate = vi.spyOn(client, 'invalidateQueries');
+ const el = await render();
+
+ await act(async () => button(el, 'Require confirmation')!.click());
+ await settle();
+
+ expect(requireLinkConfirmation).toHaveBeenCalledWith({
+ workspaceId: 'ws-1',
+ bridgeId: 'b-acme',
+ });
+ expect(toast).toHaveBeenCalledWith({ title: '2 links now need confirming' });
+ expect(invalidate).toHaveBeenCalledWith({ queryKey: myIdentitiesQueryKey('ws-1') });
+ expect(invalidate).toHaveBeenCalledWith({
+ queryKey: unconfirmedLinksQueryKey('ws-1', 'b-acme'),
+ });
+ expect(onSuccess).toHaveBeenCalledWith({ moved: 2 });
+ });
+
+ it('shows a refusal inline and stays open', async () => {
+ requireLinkConfirmation.mockResolvedValue({
+ kind: 'refused',
+ message: 'Workspace admin access required',
+ });
+ const el = await render();
+
+ await act(async () => button(el, 'Require confirmation')!.click());
+ await settle();
+
+ expect(el.textContent).toContain('Workspace admin access required');
+ expect(onSuccess).not.toHaveBeenCalled();
+ expect(button(el, 'Require confirmation')?.disabled).toBe(false);
+ });
+
+ it('has nothing to confirm when no older links are left', async () => {
+ listUnconfirmedLinks.mockResolvedValue([]);
+ const el = await render();
+
+ expect(el.textContent).toContain('No older links are left in Acme Slack.');
+ expect(button(el, 'Require confirmation')?.disabled).toBe(true);
+ });
+
+ it('cancels without moving anything', async () => {
+ const el = await render();
+
+ await act(async () => button(el, 'Cancel')!.click());
+
+ expect(onClose).toHaveBeenCalledTimes(1);
+ expect(requireLinkConfirmation).not.toHaveBeenCalled();
+ });
+});
diff --git a/console/apps/switch-console-desktop/src/shared/core/switch-servers/switch-servers.ts b/console/apps/switch-console-desktop/src/shared/core/switch-servers/switch-servers.ts
index caef488ac..0bd5798b0 100644
--- a/console/apps/switch-console-desktop/src/shared/core/switch-servers/switch-servers.ts
+++ b/console/apps/switch-console-desktop/src/shared/core/switch-servers/switch-servers.ts
@@ -776,6 +776,10 @@ export type RemoteExternalUser = {
export type IdentityClaimant = {
userId: string;
userName: string;
+ /** False for a link made before links had to be confirmed. It still counts;
+ * its owner is asked to confirm it. True from a server that predates
+ * confirming, where every link counts the same. */
+ verified: boolean;
};
/**
@@ -839,16 +843,25 @@ export type ClaimIdentityParams = {
* Outcome of claiming an identity. `bridge-unavailable` is the one failure a
* user can act on: an account Switch has never seen has to be provisioned on
* the platform's side, which a stopped bridge cannot do.
+ *
+ * `pending` is a link waiting for the code to be posted from the account
+ * (CHOO-3881). `code` is null only if the server issued none, in which case
+ * asking for one is the way on. `alreadyLinked` is set when the caller already
+ * held an unconfirmed link to the account, which keeps working meanwhile —
+ * otherwise the link counts for nothing until confirmed. A server that predates
+ * confirming links answers `claimed` straight away.
*/
export type ClaimIdentityResult =
| { kind: 'claimed'; identity: LinkedIdentity }
+ | { kind: 'pending'; pending: PendingIdentity; code: LinkCode | null; alreadyLinked: boolean }
| { kind: 'bridge-unavailable'; message: string }
| { kind: 'unauthenticated' }
| { kind: 'error'; message: string };
/**
- * One messaging account the signed-in user has claimed (mirrors the gateway
- * `LinkedIdentity`).
+ * One messaging account linked to the signed-in user (mirrors the gateway
+ * `LinkedIdentity`). Only links that count are listed; one still waiting for
+ * its code is a {@link PendingIdentity}.
*
* An agent whose addressing policy names its owner is only reachable by that
* owner over a bridge that appears in this list — which is why the app reads it
@@ -862,8 +875,89 @@ export type LinkedIdentity = {
bridgeType: string;
externalUserId: string;
externalUsername: string;
+ /** False for a link made before links had to be confirmed: it works, and its
+ * owner is asked to confirm it with a code. */
+ verified: boolean;
+};
+
+/**
+ * A messaging account waiting to confirm a link to the signed-in user (mirrors
+ * the gateway `PendingIdentity`). It counts for nothing until a code is posted
+ * from the account.
+ */
+export type PendingIdentity = {
+ /** The `ExternalUser` row id; what asking for a code and cancelling address. */
+ id: string;
+ bridgeId: string;
+ bridgeDisplayName: string;
+ bridgeType: string;
+ externalUserId: string;
+ externalUsername: string;
+ /** Who started the link, when it was someone else (an admin). */
+ requestedByName: string | null;
+ /** When the last code issued stops working; null when none has been. */
+ codeExpiresAt: string | null;
+};
+
+/**
+ * A one-time code that confirms a link when posted from the account (mirrors
+ * the gateway `LinkCode`). The server keeps no copy, so a lost one is replaced
+ * rather than shown again.
+ */
+export type LinkCode = {
+ code: string;
+ /** ISO timestamp, on the server's clock. */
+ expiresAt: string;
+ /** How long the code lasts, measured when it was issued. Counting from when
+ * it arrived is what keeps a wrong clock on this machine from showing a fresh
+ * code as expired. Null from a server that does not send it. */
+ expiresInSeconds: number | null;
+ /** How to post it on this platform, in Markdown — it differs per platform. */
+ instructions: string;
+};
+
+/**
+ * Why a request about confirming links did nothing. `refused` is the server
+ * declining in its own words: there is nothing to act on — the link was
+ * confirmed or cancelled meanwhile — or the caller may not do it.
+ */
+export type LinkRequestFailure =
+ | { kind: 'refused'; message: string }
+ | { kind: 'unauthenticated' }
+ | { kind: 'error'; message: string };
+
+/** Outcome of asking for a fresh link code. */
+export type IssueLinkCodeResult = { kind: 'issued'; code: LinkCode } | LinkRequestFailure;
+
+/**
+ * Outcome of withdrawing a confirmation that is waiting for its code. Only the
+ * request goes: a link that already works stays.
+ */
+export type CancelLinkRequestResult = { kind: 'cancelled' } | LinkRequestFailure;
+
+/**
+ * A link made before links had to be confirmed, as a workspace admin sees it
+ * (mirrors the gateway `UnconfirmedLink`). It counts until its owner confirms
+ * it, or until an admin requires that they do.
+ */
+export type UnconfirmedLink = {
+ /** The `ExternalUser` row id. */
+ id: string;
+ externalUserId: string;
+ externalUsername: string;
+ /** The Switch user who holds the link. */
+ userId: string;
+ userName: string;
};
+/**
+ * Outcome of requiring confirmation of a messaging app's older links. `moved`
+ * is how many became links waiting for their code; a second run moves none.
+ */
+export type RequireLinkConfirmationResult =
+ | { kind: 'required'; moved: number }
+ | LinkRequestFailure;
+
/**
* Scoped agent-addressing permissions (CHOO-1585). Each dimension is "*" (any)
* or an explicit id list ([] = none). A policy with no rules — or a null policy
diff --git a/console/packages/plugins/src/switch-skill/SKILL.md b/console/packages/plugins/src/switch-skill/SKILL.md
index aebf41918..cae164886 100644
--- a/console/packages/plugins/src/switch-skill/SKILL.md
+++ b/console/packages/plugins/src/switch-skill/SKILL.md
@@ -494,6 +494,15 @@ none of it is needed to take part in a conversation.
are commands for people: when someone asks you to rename or delete an agent
in chat, point them at the command, or use `update_agent_detail` yourself
for a rename once they confirm.
+
+ A person links their chat account to their Switch user in Switch Console,
+ which shows them a one-time code. The link counts only once they post
+ `!link-account CODE` from that chat account; Console says exactly how on each
+ platform (on Teams they @mention the Switch app with `link-account CODE`, on
+ Telegram they send `/link_account CODE`). `!unlink-account` lists the
+ Switch users a chat account is linked to, and `!unlink-account NAME` removes
+ one; both act only on the account that sends them. Never ask for a code or
+ post one yourself: it only works from the account it was issued for.
- **`request_agent_deletion`** — ask for another of your owner's agents to be
deleted. It deletes nothing: Switch posts the request in your connected
room, and only the agent's owner or a workspace admin can carry it out by
@@ -887,7 +896,9 @@ ui-avatars.com is not accepted.
runs, or self-hosted;
- the messaging apps, and how each platform would be added here: the official
Switch app or an app they create themselves;
- - whether their own chat account is linked, and their username on each app;
+ - whether their own chat account is linked (`your_account_link` says whether
+ it is confirmed or still waiting for its code), and their username on each
+ app;
- the services they connected and which agents use them;
- their agents and machines.
diff --git a/console/tooling-e2e/README.md b/console/tooling-e2e/README.md
index 7759fc615..937e3bd5b 100644
--- a/console/tooling-e2e/README.md
+++ b/console/tooling-e2e/README.md
@@ -137,7 +137,7 @@ passed or not. A teardown that leaves something behind fails the scenario.
| `unaddressed-history` | Five unaddressed messages arrive in the recipient's room history in the order sent, and none of them as a notification. | — |
| `operations-front-door` | The operations registry over HTTP: it lists the operations, `list_rooms` returns the room, `read_context` returns a message posted in it. | — |
| `mattermost-roundtrip` | A room on the Mattermost bridge: an addressed post from the human reaches the agent, and the agent's reply appears as its bot. | Mattermost |
-| `agent-identity` | Renaming an agent from the gateway and with `!rename-agent` renames its Mattermost bot in place, and mentions follow the new name; `!delete-agent`, confirmed, deletes it. | Mattermost |
+| `agent-identity` | The human links their chat account by posting the code the gateway issued, and a replaced code confirms nothing; renaming an agent from the gateway and with `!rename-agent` renames its Mattermost bot in place, and mentions follow the new name; `!delete-agent`, confirmed, deletes it. | Mattermost |
| `room-group-paths` | The same subgroup name under two parents: a bare name both share is refused naming each path, the path picks one, and a second group of that name under one parent is refused whatever its case. | — |
| `attachment-names` | A file whose name is not latin-1 is posted, listed by `read_context` and downloaded under its own name (`filename*` in `Content-Disposition`). | — |
| `client-mistakes` | An outsider inviting itself into a room or reading it gets a 403, and a history timestamp that is not ISO 8601 a 400 naming the parameter; never a 500. | — |
diff --git a/console/tooling-e2e/src/clients/switch-client.ts b/console/tooling-e2e/src/clients/switch-client.ts
index 320bd1cd3..02d57fbb1 100644
--- a/console/tooling-e2e/src/clients/switch-client.ts
+++ b/console/tooling-e2e/src/clients/switch-client.ts
@@ -864,15 +864,19 @@ export class SwitchClient {
/**
* `POST /gateway/collaborations/{bridge}/identities` on the default bridge
- * of `bridgeType` — link a chat account to the signed-in Switch user, so
- * Switch can recognise that person in a room (what the rename and delete
- * chat commands check).
+ * of `bridgeType` — start linking a chat account to the signed-in Switch
+ * user, so Switch can recognise that person in a room (what the rename and
+ * delete chat commands check).
+ *
+ * The link counts only once the account posts the returned code
+ * (`!link-account CODE`); `code` is null when the account had already
+ * confirmed it.
*/
async claimIdentity(
bridgeType: string,
externalUserId: string,
username: string,
- ): Promise<void> {
+ ): Promise<{ bridgeId: string; identityId: string; code: string | null }> {
const bridges = await this.gateway<
{ bridge_id: string; bridge_type: string; is_default?: boolean }[]
>("GET", "/collaborations");
@@ -882,15 +886,83 @@ export class SwitchClient {
throw new Error(
`No ${bridgeType} collaboration bridge on this Switch server`,
);
+ const body = await this.gateway<{
+ id: string;
+ link_request: { code: { code: string } | null } | null;
+ }>("POST", `/collaborations/${bridge.bridge_id}/identities`, {
+ external_user_id: externalUserId,
+ username,
+ user_id: null,
+ expects_confirmation: true,
+ });
+ if (body.link_request && !body.link_request.code)
+ throw new Error("A link for yourself came back without a code");
+ return {
+ bridgeId: bridge.bridge_id,
+ identityId: body.id,
+ code: body.link_request?.code?.code ?? null,
+ };
+ }
+
+ /**
+ * `DELETE /gateway/collaborations/{bridge}/identities/{identity}` — unlink
+ * the signed-in user from a chat account, or cancel a link still waiting
+ * for its code.
+ */
+ async releaseIdentity(bridgeId: string, identityId: string): Promise<void> {
await this.gateway(
+ "DELETE",
+ `/collaborations/${bridgeId}/identities/${identityId}`,
+ );
+ }
+
+ /**
+ * `DELETE /gateway/collaborations/{bridge}/identities/{identity}/request` —
+ * stop waiting for a chat account to confirm the signed-in user's link,
+ * leaving any link it already has.
+ */
+ async cancelLinkRequest(bridgeId: string, identityId: string): Promise<void> {
+ await this.gateway(
+ "DELETE",
+ `/collaborations/${bridgeId}/identities/${identityId}/request`,
+ );
+ }
+
+ /**
+ * `GET /gateway/collaborations/{bridge}/identities/unconfirmed` — the
+ * links on a bridge made before links needed confirming, by identity id.
+ * Admin only.
+ */
+ async unconfirmedLinkIds(bridgeId: string): Promise<string[]> {
+ const rows = await this.gateway<{ id: string }[]>(
+ "GET",
+ `/collaborations/${bridgeId}/identities/unconfirmed`,
+ );
+ return rows.map((row) => row.id);
+ }
+
+ /**
+ * `GET /gateway/auth/me/identities/pending` — the chat accounts waiting to
+ * confirm a link to the signed-in user, by identity id.
+ */
+ async pendingIdentityIds(): Promise<string[]> {
+ const rows = await this.gateway<{ id: string }[]>(
+ "GET",
+ "/auth/me/identities/pending",
+ );
+ return rows.map((row) => row.id);
+ }
+
+ /**
+ * `POST /gateway/collaborations/{bridge}/identities/{identity}/code` — a
+ * fresh code for the signed-in user's waiting link, replacing the last.
+ */
+ async issueLinkCode(bridgeId: string, identityId: string): Promise<string> {
+ const body = await this.gateway<{ code: string }>(
"POST",
- `/collaborations/${bridge.bridge_id}/identities`,
- {
- external_user_id: externalUserId,
- username,
- user_id: null,
- },
+ `/collaborations/${bridgeId}/identities/${identityId}/code`,
);
+ return body.code;
}
async listAgents(): Promise<AgentSummary[]> {
diff --git a/console/tooling-e2e/src/fast/agent-identity.ts b/console/tooling-e2e/src/fast/agent-identity.ts
index 090afcce7..4296d1aba 100644
--- a/console/tooling-e2e/src/fast/agent-identity.ts
+++ b/console/tooling-e2e/src/fast/agent-identity.ts
@@ -15,6 +15,12 @@ import { WRITABLE, type FastScenario } from "./scenario.ts";
* Renaming and deleting an agent on the Mattermost bridge, with the harness
* playing both the human and the agent:
*
+ * 0. the human links their chat account: the link waits, listed as pending,
+ * until the account posts a code from the gateway, which is what makes
+ * the chat commands recognise them. A link already in place (the stack's
+ * setup makes one, and one from before links needed confirming reads as
+ * unconfirmed) is undone first, so the confirmation always runs, and the
+ * account ends up linked and confirmed either way;
* 1. a rename from the gateway renames the agent's Mattermost bot in place,
* and the new name reaches the agent while the old one does not;
* 2. `!rename-agent` from the chat does the same, for the person who owns the
@@ -29,6 +35,11 @@ export const agentIdentity: FastScenario = {
covers: [
"PUT /gateway/agents/{agent_id}/name",
"POST /gateway/collaborations/{bridge_id}/identities",
+ "DELETE /gateway/collaborations/{bridge_id}/identities/{external_user_row_id}",
+ "DELETE /gateway/collaborations/{bridge_id}/identities/{external_user_row_id}/request",
+ "GET /gateway/auth/me/identities/pending",
+ "GET /gateway/collaborations/{bridge_id}/identities/unconfirmed",
+ "POST /gateway/collaborations/{bridge_id}/identities/{external_user_row_id}/code",
],
lane: "fast",
environments: WRITABLE,
@@ -42,13 +53,52 @@ export const agentIdentity: FastScenario = {
const bot = bridged.bots.get(agent.id)!;
const channelId = bridged.channel.id;
// The chat commands recognise the sender through the Switch user who linked
- // their chat account; the gateway admin the harness signs in as links it.
- await switchClient.claimIdentity(
- "mattermost",
- bridged.human.id,
- bridged.human.username,
+ // their chat account; the gateway admin the harness signs in as links it,
+ // and the account confirms by posting the code.
+ const claim = (): ReturnType<SwitchClient["claimIdentity"]> =>
+ switchClient.claimIdentity(
+ "mattermost",
+ bridged.human.id,
+ bridged.human.username,
+ );
+ let link = await claim();
+ // Already linked, confirmed (no code) or not (not listed as waiting).
+ if (
+ link.code === null ||
+ !(await switchClient.pendingIdentityIds()).includes(link.identityId)
+ ) {
+ await switchClient.releaseIdentity(link.bridgeId, link.identityId);
+ link = await claim();
+ }
+ expect(link.code).not.toBeNull();
+ expect(await switchClient.pendingIdentityIds()).toContain(link.identityId);
+ // Cancelling stops the wait; linking again starts a new one.
+ await switchClient.cancelLinkRequest(link.bridgeId, link.identityId);
+ expect(await switchClient.pendingIdentityIds()).not.toContain(
+ link.identityId,
);
+ link = await claim();
+ expect(link.code).not.toBeNull();
const admin = await mm.waitForBotUser("switch-admin", 30_000);
+ // A fresh code replaces the first, which then confirms nothing.
+ const code = await switchClient.issueLinkCode(
+ link.bridgeId,
+ link.identityId,
+ );
+ let sinceLink = Date.now();
+ await mm.post({ channelId, message: `!link-account ${link.code}` });
+ await switchReply(mm, channelId, admin.id, sinceLink, /doesn't match/);
+ sinceLink = Date.now();
+ await mm.post({ channelId, message: `!link-account ${code}` });
+ await switchReply(mm, channelId, admin.id, sinceLink, /Linked this/);
+ expect(await switchClient.pendingIdentityIds()).not.toContain(
+ link.identityId,
+ );
+ // Confirmed, so not among the older links an admin could demote.
+ expect(await switchClient.unconfirmedLinkIds(link.bridgeId)).not.toContain(
+ link.identityId,
+ );
+ log("linked the chat account by posting its code");
const reaches = (name: string, label: string): Promise<boolean> =>
reachesAgent(
switchClient,
diff --git a/console/tooling-e2e/surface/exemptions.json b/console/tooling-e2e/surface/exemptions.json
index 3b005f184..127c6e02e 100644
--- a/console/tooling-e2e/surface/exemptions.json
+++ b/console/tooling-e2e/surface/exemptions.json
@@ -20,6 +20,8 @@
"POST /gateway/auth/oidc/exchange": "Needs a code from a live OIDC sign-in; the harness signs in with a password.",
"POST /gateway/chats/{room_id}/agents": "Switch Console group chats. Covered by core's test_chats_groups.py against real Postgres; no scenario drives Console chats yet (every other /gateway/chats route is still in the backlog), and the stacks the harness builds do not turn on the group_chats flag these routes need.",
"POST /gateway/chats/{room_id}/unarchive": "Switch Console archived chats. Covered by core's test_chats_routes.py against real Postgres; no scenario drives Console chats yet (every other /gateway/chats route is still in the backlog).",
+ "POST /gateway/collaborations/{bridge_id}/identities/require-confirmation": "Demotes every older link on a bridge at once, so a scenario running on a shared stack (dev, staging) would demote every real person's link there. Core's test_identity_link_confirmation.py covers it against real Postgres; the agent-identity scenario covers the list it acts on.",
+ "POST /gateway/collaborations/{bridge_id}/identities/{external_user_row_id}/verify-session": "Used only by the bundled deployment's setup job, against the Mattermost account it seeds, before any channel has an agent to hear a code. Every bundled install runs it; core's test_identity_link_confirmation.py and test_setup_link_owner.py cover it.",
"POST /gateway/hosted-controller/machines/{machine_id}/observation": "Needs a hosted controller configured (HOSTED_CONTROLLER_CONFIG_PATH), which no stack the harness builds has.",
"POST /gateway/hosted-controller/machines/{machine_id}/prepare": "Needs a hosted controller configured (HOSTED_CONTROLLER_CONFIG_PATH), which no stack the harness builds has.",
"POST /gateway/rooms/{room_id}/sync-name": "Needs a bridged room whose linked channel was renamed on the platform, which the fast lane's stacks cannot stage. Covered by core's test_room_sync_name.py against real Postgres.",
@@ -102,7 +104,6 @@
"DELETE /gateway/chats/{room_id}/hidden",
"DELETE /gateway/chats/{room_id}/members/{member_user_id}",
"DELETE /gateway/collaborations/{bridge_id}",
- "DELETE /gateway/collaborations/{bridge_id}/identities/{external_user_row_id}",
"DELETE /gateway/collaborations/{bridge_id}/teams/{team_id}",
"DELETE /gateway/connector-apps/{service}",
"DELETE /gateway/documents/{document_id}",
diff --git a/console/tooling-e2e/surface/server-surface.json b/console/tooling-e2e/surface/server-surface.json
index f9f38d1e8..fb0dbd22a 100644
--- a/console/tooling-e2e/surface/server-surface.json
+++ b/console/tooling-e2e/surface/server-surface.json
@@ -113,6 +113,11 @@
"auth": "session",
"flags": []
},
+ {
+ "route": "DELETE /gateway/collaborations/{bridge_id}/identities/{external_user_row_id}/request",
+ "auth": "session",
+ "flags": []
+ },
{
"route": "DELETE /gateway/collaborations/{bridge_id}/teams/{team_id}",
"auth": "session",
@@ -342,6 +347,11 @@
"auth": "session",
"flags": []
},
+ {
+ "route": "GET /gateway/auth/me/identities/pending",
+ "auth": "session",
+ "flags": []
+ },
{
"route": "GET /gateway/auth/oidc/callback",
"auth": "none",
@@ -432,6 +442,11 @@
"auth": "session",
"flags": []
},
+ {
+ "route": "GET /gateway/collaborations/{bridge_id}/identities/unconfirmed",
+ "auth": "session",
+ "flags": []
+ },
{
"route": "GET /gateway/collaborations/{bridge_id}/teams",
"auth": "session",
@@ -1067,6 +1082,21 @@
"auth": "session",
"flags": []
},
+ {
+ "route": "POST /gateway/collaborations/{bridge_id}/identities/require-confirmation",
+ "auth": "session",
+ "flags": []
+ },
+ {
+ "route": "POST /gateway/collaborations/{bridge_id}/identities/{external_user_row_id}/code",
+ "auth": "session",
+ "flags": []
+ },
+ {
+ "route": "POST /gateway/collaborations/{bridge_id}/identities/{external_user_row_id}/verify-session",
+ "auth": "session",
+ "flags": []
+ },
{
"route": "POST /gateway/collaborations/{bridge_id}/teams/{team_id}",
"auth": "session",
diff --git a/core/switch_core/account_links.py b/core/switch_core/account_links.py
new file mode 100644
index 000000000..a41c00d99
--- /dev/null
+++ b/core/switch_core/account_links.py
@@ -0,0 +1,56 @@
+"""One-time codes that confirm a chat account belongs to a Switch user (CHOO-3881).
+
+A Switch user asks to link a chat account, Switch shows them a code, and they
+post it from that account. The code proves both halves at once: only the
+Switch user is shown it, and the platform says which account posted it.
+
+Eight characters of Crockford base32 is 40 bits. A code is single use, lives
+for `LINK_CODE_TTL`, and only redeems from the one account it was issued for,
+so guessing one means posting something like a trillion messages from that
+account inside half an hour. That is why there is no attempt counter.
+
+Only a hash is stored. The code is worthless without the chat account, so the
+hash is there to keep codes out of anything that reads the table, not to
+withstand a brute force.
+"""
+
+import hashlib
+import secrets
+import string
+from datetime import timedelta
+
+LINK_CODE_TTL = timedelta(minutes=30)
+
+# Crockford's base32: no I, L, O or U, so nothing reads as another character.
+_ALPHABET = "0123456789ABCDEFGHJKMNPQRSTVWXYZ"
+_LENGTH = 8
+# What people type for the letters the alphabet leaves out.
+_LOOKALIKES = str.maketrans({"O": "0", "I": "1", "L": "1"})
+_ASCII_ALNUM = frozenset(string.ascii_letters + string.digits)
+
+
+def new_link_code() -> str:
+ """A fresh code, grouped `XXXX-XXXX` for reading aloud or retyping."""
+ raw = "".join(secrets.choice(_ALPHABET) for _ in range(_LENGTH))
+ return f"{raw[:4]}-{raw[4:]}"
+
+
+def normalise_link_code(text: str) -> str | None:
+ """The code as stored, or None when `text` cannot be one.
+
+ Forgiving about what a person or a chat client does to it on the way:
+ case, the hyphen, spaces, the backticks the instructions show it in,
+ quotes, invisible characters a paste carries, and the letters that look
+ like digits. Any other letter or digit in `text` makes it the wrong
+ length.
+ """
+ kept = "".join(c for c in text if c in _ASCII_ALNUM)
+ cleaned = kept.upper().translate(_LOOKALIKES)
+ if len(cleaned) != _LENGTH or any(c not in _ALPHABET for c in cleaned):
+ return None
+ return cleaned
+
+
+def hash_link_code(code: str) -> str:
+ """The stored form of a code `normalise_link_code` accepted."""
+ return hashlib.sha256(code.encode()).hexdigest()
diff --git a/core/switch_core/accounts/deletion.py b/core/switch_core/accounts/deletion.py
index 9a1b80c27..6b2419fa8 100644
--- a/core/switch_core/accounts/deletion.py
+++ b/core/switch_core/accounts/deletion.py
@@ -133,6 +133,8 @@ USER_REFERENCES: dict[tuple[str, str], Handling] = {
("organization_members", "user_id"): "database cascades",
("template_installs", "owner_id"): "database cascades",
("external_user_claims", "user_id"): "database cascades",
+ ("external_user_link_requests", "user_id"): "database cascades",
+ ("external_user_link_requests", "requested_by_user_id"): "database clears",
("chat_operations", "user_id"): "database cascades",
("chat_hidden", "user_id"): "database cascades",
("chat_owner_grants", "user_id"): "database cascades",
diff --git a/core/switch_core/bridges/agent/commands.py b/core/switch_core/bridges/agent/commands.py
index 4757dd994..ee0bf1fdb 100644
--- a/core/switch_core/bridges/agent/commands.py
+++ b/core/switch_core/bridges/agent/commands.py
@@ -35,6 +35,7 @@ from switch_core.db.audit import AuditAction, record_audit_event
from switch_core.db.models import (
Agent,
CollaborationBridge,
+ ExternalUser,
Message,
Room,
User,
@@ -42,6 +43,7 @@ from switch_core.db.models import (
)
from switch_core.db.session_scope import tenant_session
from switch_core.db.stores.agent_runtime_state_store import AgentRuntimeStateStore
+from switch_core.db.stores.external_user_store import NoSuchLink
from switch_core.db.stores.session_activity_store import (
RETRYABLE_TURN_STATUSES,
AgentSessionActivityStore,
@@ -1378,6 +1380,21 @@ class _Authority:
refusal: str | None
+async def _sender_account(
+ host: CommandConsumer, session: AsyncSession, event: CommandEvent
+) -> ExternalUser | None:
+ """The chat account that sent this command, or None when it came from none.
+
+ A message written in Console, or by the platform on someone's behalf, is
+ no chat account's, so it proves nothing about one: only the platform
+ saying who posted a message does.
+ """
+ client = await host.client_store.get_by_transport_user_id(session, event.user_id)
+ if client is None:
+ return None
+ return await host._external_user_store.get_by_client_id(session, client.id)
+
+
async def _manage_authority(
host: CommandConsumer, session: AsyncSession, event: CommandEvent, agent: Agent
) -> _Authority:
@@ -1389,12 +1406,7 @@ async def _manage_authority(
account nobody has linked cannot be told apart from anyone else, so it is
refused with what to do about it.
"""
- client = await host.client_store.get_by_transport_user_id(session, event.user_id)
- external = (
- await host._external_user_store.get_by_client_id(session, client.id)
- if client is not None
- else None
- )
+ external = await _sender_account(host, session, event)
if external is None:
return _Authority(
None,
@@ -1406,7 +1418,8 @@ async def _manage_authority(
None,
"This chat account isn't linked to a Switch user, so I can't tell "
"whether you own this agent. Link it to your Switch user in Switch "
- "Console (Messaging apps), then try again.",
+ "Console (Messaging apps) and confirm it with the code shown there, "
+ "then try again.",
)
for user_id in claimants:
user = await host._user_store.get(session, user_id)
@@ -1427,6 +1440,208 @@ async def _manage_authority(
)
+async def _cmd_link_account(
+ client: AgentRecipient, room: RoomRef, event: CommandEvent, _is_direct: bool
+) -> None:
+ """Confirm a link to a Switch user with the code Console showed (CHOO-3881).
+
+ Only the Switch user was shown the code, and the platform says which
+ account posted it, so a match proves one person holds both. A code posted
+ from any other account matches nothing, which is why posting it in a busy
+ channel gives nothing away.
+ """
+ host = cast("CommandConsumer", client)
+ code = (event.args or "").strip()
+ if not code:
+ await _reply(
+ host,
+ room,
+ event,
+ "Usage: `!link-account CODE`, with the code Switch Console showed "
+ "you when you linked this account.",
+ )
+ return
+
+ async with host.session_factory() as session:
+ account = await _sender_account(host, session, event)
+ if account is None:
+ await _reply(
+ host,
+ room,
+ event,
+ "⚠️ Only a chat account can confirm a link to itself, by posting "
+ "the code from that account.",
+ )
+ return
+ request = await host._external_user_store.redeem_link_code(
+ session, account, code, host._user_store
+ )
+ if request is None:
+ await _reply(
+ host,
+ room,
+ event,
+ "⚠️ That code doesn't match a link waiting for this account, or "
+ "it has expired. Get a new code in Switch Console, and post it "
+ "from the account you're linking.",
+ )
+ return
+ user_id = request.user_id
+ linked = await host._user_store.get(session, user_id)
+ bridge = await session.get(CollaborationBridge, account.bridge_id)
+ # Both are held by foreign keys from the rows just written.
+ if linked is None or bridge is None:
+ raise RuntimeError(
+ f"Confirmed a link for user {user_id} on bridge "
+ f"{account.bridge_id}, but could not read either back"
+ )
+ name, platform = linked.name, bridge.display_name
+ username = account.external_username
+ await record_audit_event(
+ session,
+ tenant_id=account.tenant_id,
+ actor_user_id=user_id,
+ action=AuditAction.BRIDGE_IDENTITY_CLAIMED,
+ target_type="external_user",
+ target_id=account.id,
+ details={"bridge_id": account.bridge_id, "user_id": user_id, "by": "code"},
+ )
+ await session.commit()
+
+ # Names the Switch user, so whoever posted it sees who the account is now
+ # recognised as, and how to take that back if it is not them. "The way you
+ # ran this" because platforms differ in how a command reaches Switch: typed
+ # with `!`, as a slash command, or with the app mentioned.
+ await _reply(
+ host,
+ room,
+ event,
+ f"✅ Linked this {platform} account ({username}) to Switch user "
+ f"**{name}**. If that isn't you, run `unlink-account {name}` the way "
+ "you ran this command.",
+ )
+
+
+async def _cmd_unlink_account(
+ client: AgentRecipient, room: RoomRef, event: CommandEvent, _is_direct: bool
+) -> None:
+ """Show which Switch users this chat account is linked to, or remove one.
+
+ The account's own say over its links, for someone who has no Switch login
+ to fix one with: a link confirmed by mistake, or one made before links
+ needed confirming. It only ever touches the account that sent it.
+ """
+ host = cast("CommandConsumer", client)
+ wanted = _strip_quotes((event.args or "").strip())
+
+ async with host.session_factory() as session:
+ account = await _sender_account(host, session, event)
+ if account is None:
+ await _reply(
+ host,
+ room,
+ event,
+ "⚠️ Only a chat account can unlink itself, from that account.",
+ )
+ return
+ claims = (
+ await host._external_user_store.claims_for(session, [account.id])
+ ).get(account.id, [])
+ users = {
+ user.id: user
+ for user in await session.scalars(
+ select(User).where(User.id.in_([c.user_id for c in claims]))
+ )
+ }
+ linked = sorted(
+ (
+ (users[c.user_id].name, users[c.user_id].email, c)
+ for c in claims
+ if c.user_id in users
+ ),
+ key=lambda entry: entry[0].casefold(),
+ )
+ listing = "\n".join(
+ f"- **{name}**"
+ + (
+ ""
+ if claim.verified_at is not None
+ else " (made before links needed confirming)"
+ )
+ for name, _email, claim in linked
+ )
+
+ if not wanted:
+ await _reply(
+ host,
+ room,
+ event,
+ (
+ f"This account is linked to:\n{listing}\n\nRun "
+ "`!unlink-account NAME` to remove one."
+ )
+ if linked
+ else "This account isn't linked to any Switch user.",
+ )
+ return
+
+ needle = wanted.casefold()
+ matches = [
+ claim
+ for name, email, claim in linked
+ if needle in (name.casefold(), email.casefold())
+ ]
+ if not matches:
+ await _reply(
+ host,
+ room,
+ event,
+ f"⚠️ This account isn't linked to a Switch user called "
+ f"**{wanted}**." + (f" It is linked to:\n{listing}" if linked else ""),
+ )
+ return
+ if len(matches) > 1:
+ await _reply(
+ host,
+ room,
+ event,
+ f"⚠️ More than one Switch user linked to this account goes by "
+ f"**{wanted}**. Run `!unlink-account` with their email instead.",
+ )
+ return
+ user_id = matches[0].user_id
+ name = users[user_id].name
+ try:
+ await host._external_user_store.release(session, account, user_id)
+ except NoSuchLink:
+ # Unlinked some other way while this ran: the outcome asked for.
+ await _reply(
+ host,
+ room,
+ event,
+ f"This account is no longer linked to Switch user **{name}**.",
+ )
+ return
+ await record_audit_event(
+ session,
+ tenant_id=account.tenant_id,
+ actor_user_id=None,
+ action=AuditAction.BRIDGE_IDENTITY_RELEASED,
+ target_type="external_user",
+ target_id=account.id,
+ details={
+ "bridge_id": account.bridge_id,
+ "user_id": user_id,
+ "by": "chat_account",
+ },
+ )
+ await session.commit()
+
+ await _reply(
+ host, room, event, f"Unlinked this account from Switch user **{name}**."
+ )
+
+
async def _cmd_rename_agent(
client: AgentRecipient, room: RoomRef, event: CommandEvent, _is_direct: bool
) -> None:
@@ -2147,6 +2362,38 @@ COMMANDS: list[Command] = [
),
admin_owned=True,
),
+ Command(
+ "link-account",
+ "Confirm a link between this chat account and your Switch user, with "
+ "the code Switch Console showed you. Usage: `!link-account CODE`.",
+ _cmd_link_account,
+ args_spec=(
+ # Free text so a bridge passes it through as typed: a declared
+ # name-style argument comes back with an `@` in front.
+ CommandArg(
+ "code",
+ "The code Switch Console showed you",
+ required=True,
+ free_text=True,
+ ),
+ ),
+ admin_owned=True,
+ ),
+ Command(
+ "unlink-account",
+ "Show which Switch users this chat account is linked to, or remove "
+ "one. Usage: `!unlink-account`, or `!unlink-account NAME`.",
+ _cmd_unlink_account,
+ args_spec=(
+ CommandArg(
+ "user",
+ "The Switch user to unlink (leave empty to list them)",
+ required=False,
+ free_text=True,
+ ),
+ ),
+ admin_owned=True,
+ ),
Command(
"rename-agent",
"Rename an agent, and its display name with it. Owner or admin only. "
diff --git a/core/switch_core/bridges/agent/operations/my_context.py b/core/switch_core/bridges/agent/operations/my_context.py
index 2e14d55c4..0357aeca1 100644
--- a/core/switch_core/bridges/agent/operations/my_context.py
+++ b/core/switch_core/bridges/agent/operations/my_context.py
@@ -70,12 +70,18 @@ async def get_my_context() -> dict[str, Any]:
`messaging_apps`: {connected, how_to_add}.
`connected` lists the workspace's messaging apps, each {id, platform,
name, status, is_default, installed_with, your_account_linked,
- your_usernames}. `id` is the `bridge_id` that `create_room` takes.
+ your_account_link, your_usernames}. `id` is the `bridge_id` that `create_room` takes.
`installed_with` is "official_app" (the Switch app, added with one
click) or "own_app" (an app someone created and pasted tokens from).
`your_account_linked` is whether your owner's account on that platform
is linked to their Switch user; until it is, agents that answer only
their owner do not recognise them there.
+ `your_account_link` says more: "verified" (linked and confirmed from
+ the chat account), "unverified" (linked before links needed
+ confirming; it works, and Console asks them to confirm it), "pending"
+ (waiting for them to post, from that account, the code Console
+ shows them, so it does not count yet: they started linking, or an
+ admin required them to confirm an older link) or "none".
`your_usernames` are your owner's usernames on that app, empty until
their account is linked. People are named by these, never by their
Switch name, in `create_room`'s and `add_users_to_room`'s `user_names`
@@ -132,12 +138,24 @@ async def get_my_context() -> dict[str, Any]:
members = await session.scalar(select(func.count()).select_from(TenantMember))
agents = await protocol.agent_store.get_by_owner(session, owner.id)
usernames_by_bridge: dict[str, list[str]] = {}
- for identity in await protocol.external_user_store.get_by_user(
+ link_by_bridge: dict[str, str] = {}
+ for identity, claim in await protocol.external_user_store.claims_of_user(
session, owner.id
):
usernames_by_bridge.setdefault(identity.bridge_id, []).append(
identity.external_username
)
+ if claim.verified_at is not None:
+ link_by_bridge[identity.bridge_id] = "verified"
+ else:
+ link_by_bridge.setdefault(identity.bridge_id, "unverified")
+ for (
+ identity,
+ _request,
+ ) in await protocol.external_user_store.link_requests_of_user(
+ session, owner.id
+ ):
+ link_by_bridge.setdefault(identity.bridge_id, "pending")
installed_bridges = set(
await session.scalars(
select(MessagingInstall.bridge_id).where(
@@ -206,6 +224,7 @@ async def get_my_context() -> dict[str, Any]:
"official_app" if bridge.id in installed_bridges else "own_app"
),
"your_account_linked": bridge.id in usernames_by_bridge,
+ "your_account_link": link_by_bridge.get(bridge.id, "none"),
"your_usernames": sorted(usernames_by_bridge.get(bridge.id, [])),
}
for bridge in bridges
diff --git a/core/switch_core/bridges/collaboration/adapter.py b/core/switch_core/bridges/collaboration/adapter.py
index 6a59269e3..bf6df78d5 100644
--- a/core/switch_core/bridges/collaboration/adapter.py
+++ b/core/switch_core/bridges/collaboration/adapter.py
@@ -871,6 +871,42 @@ class PlatformAdapter(ABC):
"""
return None
+ @classmethod
+ def link_code_instructions(
+ cls, code: str, connection_config: Mapping[str, object]
+ ) -> str:
+ """How to post a link code from a chat account here, in Markdown
+ (CHOO-3881).
+
+ Per-platform because Switch does not hear every message everywhere:
+ some platforms deliver a channel message only when it mentions the
+ bot, or deliver no message text at all, and the instruction must name
+ a way that actually reaches Switch. A class method because Console asks
+ while showing the code, with or without a running adapter.
+ """
+ return f"Post `!link-account {code}` from that account in any channel Switch is in."
+
+ @classmethod
+ def unlinkable_account_reason(cls, external_user_id: str) -> str | None:
+ """Why this account cannot be linked to anyone, or None if it can.
+
+ For the platform's stand-in accounts, which several real people post
+ as. Linking one would recognise all of them as the same Switch user.
+ """
+ return None
+
+ async def account_id_for_session(self, token: str) -> str:
+ """The platform id of the account a session token belongs to.
+
+ Proves control of an account without posting from it, for the bundled
+ deployment's setup, which provisions both the account and its Switch
+ user before any channel has an agent to hear a code. Raise
+ `NotImplementedError` where the platform has no such check.
+ """
+ raise NotImplementedError(
+ f"{self.display_name} cannot confirm an account from a session token"
+ )
+
@classmethod
async def verify_credentials(cls, connection_config: dict[str, object]) -> None:
"""Prove the credentials work, before the bridge is persisted.
diff --git a/core/switch_core/bridges/collaboration/discord/adapter.py b/core/switch_core/bridges/collaboration/discord/adapter.py
index 37722b949..4eff30fef 100644
--- a/core/switch_core/bridges/collaboration/discord/adapter.py
+++ b/core/switch_core/bridges/collaboration/discord/adapter.py
@@ -5,7 +5,7 @@ import io
import logging
import re
from collections import OrderedDict
-from collections.abc import Awaitable, Callable, Coroutine
+from collections.abc import Awaitable, Callable, Coroutine, Mapping
from contextvars import ContextVar
from dataclasses import replace
from datetime import UTC, datetime, timedelta
@@ -1112,6 +1112,21 @@ class DiscordAdapter(PlatformAdapter):
option = COMMANDS_BY_NAME["invite-agent"].args_spec[0].name
return f"`/invite-agent {option}:agent-name` — the Discord slash command"
+ @classmethod
+ def link_code_instructions(
+ cls, code: str, connection_config: Mapping[str, object]
+ ) -> str:
+ option = COMMANDS_BY_NAME["link-account"].args_spec[0].name
+ slash = f"`/link-account {option}:{code}`"
+ if connection_config.get("event_delivery") == "shared":
+ # The shared connection is not given message text, so a typed
+ # `!link-account` never reaches Switch; the slash command does.
+ return f"Run {slash} from that account in a server channel Switch is in."
+ return (
+ f"Run {slash} from that account in a server channel Switch is in, "
+ f"or post `!link-account {code}` there."
+ )
+
async def admin_message(
self,
channel_id: str,
diff --git a/core/switch_core/bridges/collaboration/lifecycle_service.py b/core/switch_core/bridges/collaboration/lifecycle_service.py
index 366827b44..660d0e63b 100644
--- a/core/switch_core/bridges/collaboration/lifecycle_service.py
+++ b/core/switch_core/bridges/collaboration/lifecycle_service.py
@@ -627,6 +627,30 @@ class CollaborationBridgeLifecycleService:
return True
return adapter_cls.supports_directory_search
+ def link_code_instructions(
+ self, bridge_type: str, connection_config: Mapping[str, object], code: str
+ ) -> str:
+ """How to post a link code on this platform. See
+ `PlatformAdapter.link_code_instructions`."""
+ adapter_cls = self._adapter_registry.get(bridge_type)
+ if adapter_cls is None:
+ raise ValueError(
+ f"No adapter is registered for bridge type {bridge_type!r}"
+ )
+ return adapter_cls.link_code_instructions(code, connection_config)
+
+ def unlinkable_account_reason(
+ self, bridge_type: str, external_user_id: str
+ ) -> str | None:
+ """Why this account cannot be linked to anyone. See
+ `PlatformAdapter.unlinkable_account_reason`."""
+ adapter_cls = self._adapter_registry.get(bridge_type)
+ if adapter_cls is None:
+ raise ValueError(
+ f"No adapter is registered for bridge type {bridge_type!r}"
+ )
+ return adapter_cls.unlinkable_account_reason(external_user_id)
+
def renders_custom_url_schemes(self, bridge_type: str) -> bool:
"""Whether this platform makes a `switchdash://` link clickable.
diff --git a/core/switch_core/bridges/collaboration/mattermost/adapter.py b/core/switch_core/bridges/collaboration/mattermost/adapter.py
index b2f44caf2..ebdf00184 100644
--- a/core/switch_core/bridges/collaboration/mattermost/adapter.py
+++ b/core/switch_core/bridges/collaboration/mattermost/adapter.py
@@ -9,7 +9,7 @@ import threading
import uuid
import weakref
from collections import OrderedDict
-from collections.abc import Awaitable, Callable
+from collections.abc import Awaitable, Callable, Mapping
from contextvars import ContextVar
from dataclasses import dataclass, replace
from datetime import UTC, datetime
@@ -352,6 +352,20 @@ def _close_loop(loop: asyncio.AbstractEventLoop) -> None:
asyncio.set_event_loop(None)
+# The id a webhook's posts are filed under: the integration, never the person
+# who created it, whose user id Mattermost puts on the post. See `_ws_handler`.
+_WEBHOOK_STAND_IN_PREFIX = "webhook:"
+
+
+def _webhook_stand_in_name(props: dict[str, Any]) -> str:
+ """What a webhook's posts are shown as: the name it posts under, marked as
+ a webhook so nobody reading the room takes it for a person."""
+ name = str(
+ props.get("override_username") or props.get("webhook_display_name") or ""
+ )
+ return f"{name} (webhook)" if name.strip() else "webhook"
+
+
class MattermostAdapter(PlatformAdapter):
display_name: ClassVar[str] = "Mattermost"
channel_on_delete = "archived"
@@ -1748,7 +1762,10 @@ class MattermostAdapter(PlatformAdapter):
notifies nobody and reads as noise, and the message it decorates is
worth sending without it.
"""
- if not external_user_id:
+ if not external_user_id or external_user_id.startswith(
+ _WEBHOOK_STAND_IN_PREFIX
+ ):
+ # A webhook's stand-in is nobody Mattermost can notify.
return None
username = await self._username_for(external_user_id)
return f"@{username}" if username else None
@@ -2796,14 +2813,24 @@ class MattermostAdapter(PlatformAdapter):
raise RuntimeError("Cannot handle posted event: adapter not started")
ws_loop = asyncio.get_event_loop()
- try:
- user = await ws_loop.run_in_executor(
- None, self._admin_driver.users.get_user, user_id
- )
- username: str = user.get("username", user_id)
- except Exception:
- logger.exception("Failed to resolve Mattermost user %s", user_id)
- username = user_id
+ props = post.get("props") or {}
+ if str(props.get("from_webhook", "")).lower() == "true":
+ # An incoming webhook's post (or a custom slash command's reply)
+ # carries the user id of whoever set the integration up, though
+ # anyone holding its URL may have sent it. It is the integration
+ # talking, not that person, so it goes under a stand-in of its own
+ # that no link and no owner rule can match (CHOO-3881).
+ user_id = f"{_WEBHOOK_STAND_IN_PREFIX}{user_id}"
+ username = _webhook_stand_in_name(props)
+ else:
+ try:
+ user = await ws_loop.run_in_executor(
+ None, self._admin_driver.users.get_user, user_id
+ )
+ username = user.get("username", user_id)
+ except Exception:
+ logger.exception("Failed to resolve Mattermost user %s", user_id)
+ username = user_id
channel_type = self._to_channel_type(mm_channel_type)
stripped = message.strip()
@@ -2986,6 +3013,43 @@ class MattermostAdapter(PlatformAdapter):
)
self._dispatch(coro, loop) # type: ignore[arg-type]
+ @classmethod
+ def link_code_instructions(
+ cls, code: str, connection_config: Mapping[str, object]
+ ) -> str:
+ # Switch hears Mattermost through its agents' bots, so a channel with no
+ # agent in it is one where nothing reaches Switch, and someone linking
+ # while they set up a server may have no agent anywhere yet.
+ return (
+ f"Post `!link-account {code}` from that account in a Mattermost "
+ "channel that has a Switch agent in it. No agent yet? Add one first, "
+ "then get a new code here."
+ )
+
+ @classmethod
+ def unlinkable_account_reason(cls, external_user_id: str) -> str | None:
+ if external_user_id.startswith(_WEBHOOK_STAND_IN_PREFIX):
+ return (
+ "This stands for a Mattermost webhook, which anyone holding "
+ "its URL can post through."
+ )
+ return None
+
+ async def account_id_for_session(self, token: str) -> str:
+ driver = self._create_driver(token=token)
+ try:
+ me = await asyncio.to_thread(driver.login)
+ except NoAccessTokenProvided as e:
+ raise PermissionError("Mattermost did not accept that session token") from e
+ except sync_requests.RequestException as e:
+ raise RuntimeError(
+ f"Could not ask Mattermost whose session token that is: {e}"
+ ) from e
+ user_id = me.get("id") if isinstance(me, dict) else None
+ if not user_id:
+ raise RuntimeError("Mattermost did not say whose session token that is")
+ return str(user_id)
+
async def search_directory_users(self, query: str) -> list[DirectoryUser]:
"""Find team members via Mattermost's own user search.
diff --git a/core/switch_core/bridges/collaboration/slack/adapter.py b/core/switch_core/bridges/collaboration/slack/adapter.py
index 9e0457554..fe764cf9a 100644
--- a/core/switch_core/bridges/collaboration/slack/adapter.py
+++ b/core/switch_core/bridges/collaboration/slack/adapter.py
@@ -462,6 +462,11 @@ def _slack_failure_reason(exc: SlackApiError) -> FailureReason:
return "platform_error"
+# The ids Slack gives an app's bot, under which `_handle_message` bridges its
+# posts. A person's id starts with U or W.
+_SLACK_BOT_ID = re.compile(r"^B[A-Z0-9]+$")
+
+
class SlackAdapter(PlatformAdapter):
display_name: ClassVar[str] = "Slack"
# Slack apps cannot delete a channel outside Enterprise Grid's admin API.
@@ -1817,6 +1822,14 @@ class SlackAdapter(PlatformAdapter):
# invocation reads exactly like the `!` form.
return "`/invite-agent @agent-name` — the Slack slash command"
+ @classmethod
+ def unlinkable_account_reason(cls, external_user_id: str) -> str | None:
+ # An app's or a bot's posts are bridged under its `bot_id` (`B…`), and
+ # whoever can post through the app (a webhook, a workflow) posts as it.
+ if external_user_id == "USLACKBOT" or _SLACK_BOT_ID.match(external_user_id):
+ return "This is a Slack app's or bot's account, which isn't one person's."
+ return None
+
async def admin_message(
self,
channel_id: str,
diff --git a/core/switch_core/bridges/collaboration/teams/adapter.py b/core/switch_core/bridges/collaboration/teams/adapter.py
index 9d5bb1886..2d2d167a5 100644
--- a/core/switch_core/bridges/collaboration/teams/adapter.py
+++ b/core/switch_core/bridges/collaboration/teams/adapter.py
@@ -2978,6 +2978,17 @@ class TeamsAdapter(PlatformAdapter):
"`/invite-agent @agent-name` — the same thing, if you prefer the slash form"
)
+ @classmethod
+ def link_code_instructions(
+ cls, code: str, connection_config: Mapping[str, object]
+ ) -> str:
+ # Teams hands the bot a channel message only when it is mentioned, and
+ # a bare command name counts once it is.
+ return (
+ "From that account, @mention the Switch app in a channel or chat it "
+ f"is in and add `link-account {code}`."
+ )
+
def is_placeholder_username(self, username: str) -> bool:
# Every id Teams hands out for a person is one of two shapes: a
# channel-account id, prefixed with digits and a colon (`29:1AbC…`,
diff --git a/core/switch_core/bridges/collaboration/telegram/adapter.py b/core/switch_core/bridges/collaboration/telegram/adapter.py
index 314cb9d56..e097024d7 100644
--- a/core/switch_core/bridges/collaboration/telegram/adapter.py
+++ b/core/switch_core/bridges/collaboration/telegram/adapter.py
@@ -6,7 +6,7 @@ import logging
import re
import time
from collections import OrderedDict
-from collections.abc import Awaitable, Callable, Coroutine
+from collections.abc import Awaitable, Callable, Coroutine, Mapping
from contextvars import ContextVar
from dataclasses import replace
from typing import Any, ClassVar, Literal, NamedTuple
@@ -489,6 +489,16 @@ class TelegramConnectionConfig(BridgeConnectionConfig):
return self
+# Accounts Telegram posts as on behalf of someone it does not name, so many
+# people share each one. Linking one to a Switch user would recognise every
+# anonymous admin, or every channel, as that user (CHOO-3881).
+_STAND_IN_ACCOUNTS: dict[str, str] = {
+ "1087968824": "This is Telegram's stand-in for anonymous group admins, which any of them posts as.",
+ "136817688": "This is Telegram's stand-in for posts made as a channel.",
+ "777000": "This is Telegram's own service account.",
+}
+
+
class TelegramAdapter(PlatformAdapter):
"""Telegram collaboration bridge adapter.
@@ -1321,6 +1331,18 @@ class TelegramAdapter(PlatformAdapter):
"menu offers it (`/invite-agent` works too)"
)
+ @classmethod
+ def link_code_instructions(
+ cls, code: str, connection_config: Mapping[str, object]
+ ) -> str:
+ # Commands reach the bot even in a group where it is not an admin,
+ # which is where plain messages do not.
+ return f"Send `/link_account {code}` from that account in a group the Switch bot is in."
+
+ @classmethod
+ def unlinkable_account_reason(cls, external_user_id: str) -> str | None:
+ return _STAND_IN_ACCOUNTS.get(external_user_id)
+
async def admin_message(
self,
channel_id: str,
diff --git a/core/switch_core/db/audit.py b/core/switch_core/db/audit.py
index 81e721c40..592f7ebac 100644
--- a/core/switch_core/db/audit.py
+++ b/core/switch_core/db/audit.py
@@ -50,7 +50,13 @@ class AuditAction(StrEnum):
BRIDGE_UPDATED = "collaboration_bridge.updated"
BRIDGE_DEFAULT_SET = "collaboration_bridge.default_set"
BRIDGE_DELETED = "collaboration_bridge.deleted"
+ # A claim took effect: since CHOO-3881, when the account confirmed a link.
BRIDGE_IDENTITY_CLAIMED = "collaboration_bridge.identity_claimed"
+ BRIDGE_IDENTITY_LINK_REQUESTED = "collaboration_bridge.identity_link_requested"
+ BRIDGE_IDENTITY_LINK_CANCELLED = "collaboration_bridge.identity_link_cancelled"
+ BRIDGE_IDENTITY_CONFIRMATION_REQUIRED = (
+ "collaboration_bridge.identity_confirmation_required"
+ )
BRIDGE_IDENTITY_RELEASED = "collaboration_bridge.identity_released"
MESSAGING_INSTALL_STARTED = "messaging_install.started"
MESSAGING_INSTALL_CONNECTED = "messaging_install.connected"
diff --git a/core/switch_core/db/models.py b/core/switch_core/db/models.py
index efd9dadf7..b21093a67 100644
--- a/core/switch_core/db/models.py
+++ b/core/switch_core/db/models.py
@@ -2125,6 +2125,11 @@ class ExternalUserClaim(TenantScoped, Base):
An account with no claim at all satisfies no owner rule — unclaimed is
not "trusted by default".
+
+ A claim is only ever written once the account itself has confirmed it
+ (`ExternalUserLinkRequest`), so every row here is trusted. `verified_at`
+ is null on the claims made before confirmation existed (CHOO-3881): they
+ keep working, and the claimant is asked to confirm them.
"""
__tablename__ = "external_user_claims"
@@ -2148,6 +2153,66 @@ class ExternalUserClaim(TenantScoped, Base):
created_at: Mapped[str] = mapped_column(
DateTime(timezone=True), server_default=func.now(), nullable=False
)
+ verified_at: Mapped[datetime | None] = mapped_column(
+ DateTime(timezone=True), nullable=True
+ )
+
+
+class ExternalUserLinkRequest(TenantScoped, Base):
+ """A link from a platform account to a Switch user, waiting for the account
+ to confirm it (CHOO-3881).
+
+ Kept out of `external_user_claims` on purpose: every reader of that table
+ treats a row as trusted, so a request living there would be trusted by any
+ reader that forgot to filter it out, including a release from before this
+ table existed.
+
+ The account confirms by posting `code` from itself, which proves the same
+ person holds the Switch user (only they are shown the code) and the
+ platform account (the platform says who posted it). Only a hash is
+ stored, and `code_hash` is null until the Switch user asks for a code: an
+ admin may start a link for someone else, and must not be the one who sees
+ it.
+ """
+
+ __tablename__ = "external_user_link_requests"
+ __table_args__ = (
+ Index("ix_external_user_link_requests_tenant_id", "tenant_id"),
+ Index("ix_external_user_link_requests_user_id", "user_id"),
+ ForeignKeyConstraint(
+ ["tenant_id", "external_user_id"],
+ ["external_users.tenant_id", "external_users.id"],
+ name="fk_external_user_link_requests_external_user",
+ ondelete="CASCADE",
+ ),
+ )
+
+ external_user_id: Mapped[str] = mapped_column(Text, primary_key=True)
+ user_id: Mapped[str] = mapped_column(
+ Text,
+ ForeignKey(
+ "users.id",
+ name="fk_external_user_link_requests_user",
+ ondelete="CASCADE",
+ ),
+ primary_key=True,
+ )
+ requested_by_user_id: Mapped[str | None] = mapped_column(
+ Text,
+ ForeignKey(
+ "users.id",
+ name="fk_external_user_link_requests_requested_by",
+ ondelete="SET NULL",
+ ),
+ nullable=True,
+ )
+ code_hash: Mapped[str | None] = mapped_column(Text, nullable=True)
+ code_expires_at: Mapped[datetime | None] = mapped_column(
+ DateTime(timezone=True), nullable=True
+ )
+ created_at: Mapped[datetime] = mapped_column(
+ DateTime(timezone=True), server_default=func.now(), nullable=False
+ )
# ── Agent Sessions ────────────────────────────────────────────────────────────
diff --git a/core/switch_core/db/stores/external_user_store.py b/core/switch_core/db/stores/external_user_store.py
index 96467f230..e2632c500 100644
--- a/core/switch_core/db/stores/external_user_store.py
+++ b/core/switch_core/db/stores/external_user_store.py
@@ -1,11 +1,39 @@
from collections.abc import Collection
+from dataclasses import dataclass
+from datetime import datetime
from typing import Any, cast
-from sqlalchemy import CursorResult, delete, select
+from sqlalchemy import CursorResult, delete, func, literal, select
from sqlalchemy.dialects.postgresql import insert as pg_insert
from sqlalchemy.ext.asyncio import AsyncSession
-from switch_core.db.models import Client, ClientRoom, ExternalUser, ExternalUserClaim
+from switch_core.account_links import (
+ LINK_CODE_TTL,
+ hash_link_code,
+ new_link_code,
+ normalise_link_code,
+)
+from switch_core.db.models import (
+ Client,
+ ClientRoom,
+ ExternalUser,
+ ExternalUserClaim,
+ ExternalUserLinkRequest,
+)
+from switch_core.db.stores.user_store import UserStore
+
+
+class NoSuchLink(LookupError):
+ """There was no link, or no waiting one, between this account and user."""
+
+
+@dataclass(frozen=True)
+class LinkRelease:
+ """What unlinking dropped: a claim that counted, a request that was
+ waiting, or both."""
+
+ claim: bool
+ request: bool
class ExternalUserStore:
@@ -135,56 +163,350 @@ class ExternalUserStore:
)
return list(result.scalars().all())
- async def claimant_ids_for(
+ async def claims_of_user(
+ self, session: AsyncSession, switch_user_id: str
+ ) -> list[tuple[ExternalUser, ExternalUserClaim]]:
+ """`get_by_user` with each claim, for callers that show whether it was
+ verified."""
+ result = await session.execute(
+ select(ExternalUser, ExternalUserClaim)
+ .join(
+ ExternalUserClaim,
+ ExternalUserClaim.external_user_id == ExternalUser.id,
+ )
+ .where(ExternalUserClaim.user_id == switch_user_id)
+ )
+ return [(external, claim) for external, claim in result.tuples()]
+
+ async def claims_for(
self, session: AsyncSession, external_user_ids: list[str]
- ) -> dict[str, list[str]]:
- """`claimant_ids` for several identities at once, to avoid a query per
- row when listing a bridge's users."""
+ ) -> dict[str, list[ExternalUserClaim]]:
+ """The claims on several identities at once, to avoid a query per row
+ when listing a bridge's users."""
if not external_user_ids:
return {}
result = await session.execute(
- select(ExternalUserClaim.external_user_id, ExternalUserClaim.user_id).where(
+ select(ExternalUserClaim).where(
ExternalUserClaim.external_user_id.in_(external_user_ids)
)
)
- claims: dict[str, list[str]] = {}
- for external_user_id, user_id in result.all():
- claims.setdefault(external_user_id, []).append(user_id)
+ claims: dict[str, list[ExternalUserClaim]] = {}
+ for claim in result.scalars():
+ claims.setdefault(claim.external_user_id, []).append(claim)
return claims
- async def claim(
+ async def get_claim(
+ self, session: AsyncSession, external_user_id: str, switch_user_id: str
+ ) -> ExternalUserClaim | None:
+ """The claim as the database has it now, not as this session last saw
+ it: a confirmation committed elsewhere a moment ago has to show."""
+ return await session.get(
+ ExternalUserClaim,
+ (external_user_id, switch_user_id),
+ populate_existing=True,
+ )
+
+ async def release(
self, session: AsyncSession, external_user: ExternalUser, switch_user_id: str
- ) -> None:
- """Record that a Switch user considers this platform account theirs.
+ ) -> LinkRelease:
+ """Drop one Switch user's claim on this account, and any request to
+ link them to it, leaving anyone else's in place.
+
+ Says which of the two there was, and raises `NoSuchLink` when there
+ was neither, so a mistyped user id is not reported as an unlink.
+
+ The request goes first: confirming a link locks the request and then
+ writes the claim, and taking the two in the other order here could
+ deadlock against it.
+ """
+ requests = await session.execute(
+ delete(ExternalUserLinkRequest).where(
+ ExternalUserLinkRequest.external_user_id == external_user.id,
+ ExternalUserLinkRequest.user_id == switch_user_id,
+ )
+ )
+ claims = await session.execute(
+ delete(ExternalUserClaim).where(
+ ExternalUserClaim.external_user_id == external_user.id,
+ ExternalUserClaim.user_id == switch_user_id,
+ )
+ )
+ await session.flush()
+ released = LinkRelease(
+ claim=cast("CursorResult[Any]", claims).rowcount > 0,
+ request=cast("CursorResult[Any]", requests).rowcount > 0,
+ )
+ if not released.claim and not released.request:
+ raise NoSuchLink(
+ f"User {switch_user_id} has no link to account {external_user.id}"
+ )
+ return released
- Idempotent, and never a conflict: claiming an account someone else has
- also claimed is allowed by design. Left to the database rather than a
- read-then-write, so a double-clicked button races to the same row
- instead of to a primary-key violation.
+ async def unconfirmed_claims(
+ self, session: AsyncSession, bridge_id: str
+ ) -> list[tuple[ExternalUser, ExternalUserClaim]]:
+ """The claims on this bridge made before links needed confirming,
+ which count until their owners confirm them or an admin requires it."""
+ result = await session.execute(
+ select(ExternalUser, ExternalUserClaim)
+ .join(
+ ExternalUserClaim,
+ ExternalUserClaim.external_user_id == ExternalUser.id,
+ )
+ .where(
+ ExternalUser.bridge_id == bridge_id,
+ ExternalUserClaim.verified_at.is_(None),
+ )
+ )
+ return [(external, claim) for external, claim in result.tuples()]
+
+ async def require_confirmation(
+ self, session: AsyncSession, bridge_id: str, requested_by_user_id: str
+ ) -> list[tuple[str, str]]:
+ """Stop trusting this bridge's claims made before links needed
+ confirming, turning each into a request its owner confirms with a
+ code. Returns the `(external_user_id, user_id)` pairs moved.
+
+ A request already waiting (its owner started confirming) is kept, code
+ and all. The requests are written before the claims go, the order a
+ confirmation takes the two in, so the two cannot deadlock.
"""
+ on_bridge = select(ExternalUser.id).where(ExternalUser.bridge_id == bridge_id)
+ unconfirmed = select(
+ ExternalUserClaim.tenant_id,
+ ExternalUserClaim.external_user_id,
+ ExternalUserClaim.user_id,
+ literal(requested_by_user_id),
+ ).where(
+ ExternalUserClaim.external_user_id.in_(on_bridge),
+ ExternalUserClaim.verified_at.is_(None),
+ )
await session.execute(
- pg_insert(ExternalUserClaim)
- .values(external_user_id=external_user.id, user_id=switch_user_id)
+ pg_insert(ExternalUserLinkRequest)
+ .from_select(
+ ["tenant_id", "external_user_id", "user_id", "requested_by_user_id"],
+ unconfirmed,
+ )
.on_conflict_do_nothing(index_elements=["external_user_id", "user_id"])
)
+ moved = await session.execute(
+ delete(ExternalUserClaim)
+ .where(
+ ExternalUserClaim.external_user_id.in_(on_bridge),
+ ExternalUserClaim.verified_at.is_(None),
+ )
+ .returning(ExternalUserClaim.external_user_id, ExternalUserClaim.user_id)
+ )
+ pairs = [(external_user_id, user_id) for external_user_id, user_id in moved]
await session.flush()
+ return pairs
- async def release(
+ # ── Link requests (CHOO-3881) ────────────────────────────────────────────
+
+ async def request_link(
+ self,
+ session: AsyncSession,
+ external_user: ExternalUser,
+ switch_user_id: str,
+ requested_by_user_id: str,
+ ) -> ExternalUserLinkRequest:
+ """Start linking this account to a Switch user, pending the account's
+ confirmation.
+
+ Asking again keeps the request that is already waiting, code and all,
+ and only records who asked most recently.
+ """
+ await session.execute(
+ pg_insert(ExternalUserLinkRequest)
+ .values(
+ external_user_id=external_user.id,
+ user_id=switch_user_id,
+ requested_by_user_id=requested_by_user_id,
+ )
+ .on_conflict_do_update(
+ index_elements=["external_user_id", "user_id"],
+ set_={"requested_by_user_id": requested_by_user_id},
+ )
+ )
+ await session.flush()
+ request = await session.get(
+ ExternalUserLinkRequest,
+ (external_user.id, switch_user_id),
+ populate_existing=True,
+ )
+ if request is None:
+ raise RuntimeError("A link request was written but could not be read back")
+ return request
+
+ async def get_link_request(
+ self, session: AsyncSession, external_user_id: str, switch_user_id: str
+ ) -> ExternalUserLinkRequest | None:
+ return await session.get(
+ ExternalUserLinkRequest, (external_user_id, switch_user_id)
+ )
+
+ async def lock_link_request(
+ self, session: AsyncSession, external_user_id: str, switch_user_id: str
+ ) -> ExternalUserLinkRequest | None:
+ """The request as the database has it now, locked until the
+ transaction ends.
+
+ For a caller about to change or confirm it while a code may be
+ redeemed, or the request cancelled, at the same moment. Read past the
+ session's identity map, which may hold a copy from before either.
+ """
+ result = await session.execute(
+ select(ExternalUserLinkRequest)
+ .where(
+ ExternalUserLinkRequest.external_user_id == external_user_id,
+ ExternalUserLinkRequest.user_id == switch_user_id,
+ )
+ .with_for_update()
+ .execution_options(populate_existing=True)
+ )
+ return result.scalar_one_or_none()
+
+ async def cancel_link_request(
self, session: AsyncSession, external_user: ExternalUser, switch_user_id: str
- ) -> bool:
- """Drop one Switch user's claim, leaving anyone else's in place.
+ ) -> None:
+ """Drop a request waiting for the account to confirm it, leaving any
+ claim the pair already has (one made before links needed confirming)
+ as it is. Raises `NoSuchLink` when nothing was waiting."""
+ result = await session.execute(
+ delete(ExternalUserLinkRequest).where(
+ ExternalUserLinkRequest.external_user_id == external_user.id,
+ ExternalUserLinkRequest.user_id == switch_user_id,
+ )
+ )
+ await session.flush()
+ if cast("CursorResult[Any]", result).rowcount == 0:
+ raise NoSuchLink(
+ f"User {switch_user_id} has no link to account {external_user.id} "
+ "waiting to be confirmed"
+ )
+
+ async def link_requests_of_user(
+ self, session: AsyncSession, switch_user_id: str
+ ) -> list[tuple[ExternalUser, ExternalUserLinkRequest]]:
+ """Every account waiting to confirm a new link to this Switch user.
+
+ Leaves out a request to confirm a claim that already exists, made
+ before links needed confirming: that link counts already, and is
+ listed with the claims.
+ """
+ claimed = (
+ select(ExternalUserClaim.external_user_id)
+ .where(
+ ExternalUserClaim.external_user_id
+ == ExternalUserLinkRequest.external_user_id,
+ ExternalUserClaim.user_id == ExternalUserLinkRequest.user_id,
+ )
+ .exists()
+ )
+ result = await session.execute(
+ select(ExternalUser, ExternalUserLinkRequest)
+ .join(
+ ExternalUserLinkRequest,
+ ExternalUserLinkRequest.external_user_id == ExternalUser.id,
+ )
+ .where(ExternalUserLinkRequest.user_id == switch_user_id, ~claimed)
+ )
+ return [(external, request) for external, request in result.tuples()]
- Returns whether there was a claim to drop, so a caller can tell a real
- unlink from a no-op rather than reporting success either way.
+ async def issue_link_code(
+ self, session: AsyncSession, request: ExternalUserLinkRequest
+ ) -> tuple[str, datetime]:
+ """A fresh code for this request, replacing any code issued before.
+
+ Returns the code, which is never stored, and when it stops working.
"""
+ code = new_link_code()
+ normalised = normalise_link_code(code)
+ if normalised is None:
+ raise RuntimeError(f"Generated a link code that does not parse: {code!r}")
+ request.code_hash = hash_link_code(normalised)
+ # The database's clock, since the database's clock is what a redeem
+ # compares it to.
+ request.code_expires_at = func.now() + LINK_CODE_TTL # type: ignore[assignment]
+ await session.flush()
+ await session.refresh(request, ["code_expires_at"])
+ if request.code_expires_at is None:
+ raise RuntimeError("A link code was issued but its expiry was not stored")
+ return code, request.code_expires_at
+
+ async def redeem_link_code(
+ self,
+ session: AsyncSession,
+ external_user: ExternalUser,
+ code: str,
+ user_store: UserStore,
+ ) -> ExternalUserLinkRequest | None:
+ """Confirm the link this code was issued for, if it was issued for
+ this account, has not expired, and is for someone who still stands in
+ the workspace.
+
+ The request becomes a verified claim, upgrading an unverified one in
+ place. None when nothing matches, which the caller reports without
+ saying which part was wrong.
+
+ Standing is checked here as well as when the link was started, because
+ a request outlives a member's removal from the workspace and the claim
+ it turns into decides who the account is recognised as. It is asked of
+ `user_store` rather than read from `tenant_members`, because an
+ organization's `org_admin` stands in its workspaces without a
+ membership row there, and a link to them is started the same way.
+ """
+ normalised = normalise_link_code(code)
+ if normalised is None:
+ return None
result = await session.execute(
- delete(ExternalUserClaim).where(
- ExternalUserClaim.external_user_id == external_user.id,
- ExternalUserClaim.user_id == switch_user_id,
+ select(ExternalUserLinkRequest)
+ .where(
+ ExternalUserLinkRequest.external_user_id == external_user.id,
+ ExternalUserLinkRequest.code_hash == hash_link_code(normalised),
+ ExternalUserLinkRequest.code_expires_at > func.now(),
+ )
+ .with_for_update()
+ .execution_options(populate_existing=True)
+ )
+ request = result.scalar_one_or_none()
+ if request is None:
+ return None
+ if (
+ await user_store.effective_tenant_role(
+ session, request.tenant_id, request.user_id
+ )
+ is None
+ ):
+ return None
+ await self.confirm_link_request(session, request)
+ return request
+
+ async def confirm_link_request(
+ self, session: AsyncSession, request: ExternalUserLinkRequest
+ ) -> None:
+ """Turn a request the account has proved into a verified claim.
+
+ Idempotent on the claim, and never a conflict: claiming an account
+ someone else has also claimed is allowed by design, and an unverified
+ claim of the same pair is upgraded in place. Left to the database
+ rather than a read-then-write, so two confirmations race to the same
+ row instead of to a primary-key violation.
+ """
+ await session.execute(
+ pg_insert(ExternalUserClaim)
+ .values(
+ external_user_id=request.external_user_id,
+ user_id=request.user_id,
+ verified_at=func.now(),
+ )
+ .on_conflict_do_update(
+ index_elements=["external_user_id", "user_id"],
+ set_={"verified_at": func.now()},
)
)
+ await session.delete(request)
await session.flush()
- return cast("CursorResult[Any]", result).rowcount > 0
async def delete(self, session: AsyncSession, user_id: str) -> None:
user = await session.get(ExternalUser, user_id)
diff --git a/core/switch_core/delivery/addressing.py b/core/switch_core/delivery/addressing.py
index 87303ce24..3f782308d 100644
--- a/core/switch_core/delivery/addressing.py
+++ b/core/switch_core/delivery/addressing.py
@@ -96,7 +96,8 @@ ADDRESSING_DENIED_MESSAGE = (
ADDRESSING_UNCLAIMED_MESSAGE = (
"I only take instructions from my owner, and this chat account isn't "
"linked to a Switch user yet — so I can't tell whether that's you. If it "
- "is, link this account to your Switch user in Switch Console and try again."
+ "is, link this account to your Switch user in Switch Console, post the "
+ "code it shows you from this account, and try again."
)
diff --git a/core/switch_core/gateway/auth_routes.py b/core/switch_core/gateway/auth_routes.py
index 9f7409d81..c3df102f0 100644
--- a/core/switch_core/gateway/auth_routes.py
+++ b/core/switch_core/gateway/auth_routes.py
@@ -77,6 +77,7 @@ from switch_core.gateway.schemas import (
LinkedIdentity,
LoginRequest,
OidcLoginOptionView,
+ PendingIdentity,
ServerDeclaration,
SessionStateResponse,
SessionUserResponse,
@@ -398,11 +399,12 @@ async def my_identities(
An owner-only agent is only reachable by its owner over a bridge that
appears in this list, so Switch Console reads it to warn when an agent has
- been sealed on a platform where its owner cannot be recognised.
+ been sealed on a platform where its owner cannot be recognised. A link
+ still waiting for the account to confirm it is not one of them: see
+ `my_pending_identities`.
"""
- identities = await external_user_store.get_by_user(session, user.id)
linked: list[LinkedIdentity] = []
- for identity in identities:
+ for identity, claim in await external_user_store.claims_of_user(session, user.id):
bridge = await bridge_store.get(session, identity.bridge_id)
if bridge is None:
continue
@@ -414,11 +416,50 @@ async def my_identities(
bridge_type=bridge.type,
external_user_id=identity.external_user_id,
external_username=identity.external_username,
+ verified=claim.verified_at is not None,
)
)
return linked
[email protected]("/auth/me/identities/pending")
+async def my_pending_identities(
+ session: Annotated[AsyncSession, Depends(get_session)],
+ external_user_store: Annotated[ExternalUserStore, Depends(get_external_user_store)],
+ bridge_store: Annotated[CollaborationBridgeStore, Depends(get_bridge_store)],
+ user_store: Annotated[UserStore, Depends(get_user_store)],
+ user: Annotated[User, Depends(get_current_user)],
+) -> list[PendingIdentity]:
+ """The messaging-app accounts waiting to confirm a link to this user
+ (CHOO-3881), which count for nothing until they do."""
+ pending: list[PendingIdentity] = []
+ for identity, request in await external_user_store.link_requests_of_user(
+ session, user.id
+ ):
+ bridge = await bridge_store.get(session, identity.bridge_id)
+ if bridge is None:
+ continue
+ requested_by = request.requested_by_user_id
+ requester = (
+ await user_store.get(session, requested_by)
+ if requested_by is not None and requested_by != user.id
+ else None
+ )
+ pending.append(
+ PendingIdentity(
+ id=identity.id,
+ bridge_id=identity.bridge_id,
+ bridge_display_name=bridge.display_name,
+ bridge_type=bridge.type,
+ external_user_id=identity.external_user_id,
+ external_username=identity.external_username,
+ requested_by_name=requester.name if requester is not None else None,
+ code_expires_at=request.code_expires_at,
+ )
+ )
+ return pending
+
+
@router.delete("/auth/me")
async def delete_my_account(
req: DeleteAccountRequest,
diff --git a/core/switch_core/gateway/collaborations.py b/core/switch_core/gateway/collaborations.py
index 61d04cc87..6ef6a9ea4 100644
--- a/core/switch_core/gateway/collaborations.py
+++ b/core/switch_core/gateway/collaborations.py
@@ -11,6 +11,7 @@ from pydantic import ValidationError
from sqlalchemy.ext.asyncio import AsyncSession
from switch_core import messaging_platforms
+from switch_core.account_links import LINK_CODE_TTL
from switch_core.bridges.collaboration.adapter import (
ConfigEditRefused,
DirectorySearchBusy,
@@ -37,12 +38,14 @@ from switch_core.db.audit import AuditAction, record_audit_event
from switch_core.db.models import (
CollaborationBridge,
ExternalUser,
+ ExternalUserClaim,
+ ExternalUserLinkRequest,
MessagingInstall,
User,
require_tenant_id,
)
from switch_core.db.stores.collaboration_bridge_store import CollaborationBridgeStore
-from switch_core.db.stores.external_user_store import ExternalUserStore
+from switch_core.db.stores.external_user_store import ExternalUserStore, NoSuchLink
from switch_core.db.stores.messaging_install_store import MessagingInstallStore
from switch_core.db.stores.room_store import RoomStore
from switch_core.db.stores.user_store import UserStore
@@ -71,9 +74,14 @@ from switch_core.gateway.schemas import (
DirectoryUserSummary,
ExternalUserSummary,
IdentityClaimant,
+ LinkCode,
+ LinkRequestSummary,
+ RequireConfirmationResult,
SlackOwnAppSetup,
SlackTokensCheck,
SlackTokensChecked,
+ UnconfirmedLink,
+ VerifyIdentitySessionRequest,
)
from switch_core.request_validation import describe_errors
from switch_core.room_service import RoomService
@@ -601,7 +609,7 @@ async def list_bridge_users(
raise HTTPException(status_code=404, detail="Bridge not found")
users = await external_user_store.get_by_bridge(session, bridge_id)
- claims = await external_user_store.claimant_ids_for(session, [u.id for u in users])
+ claims = await external_user_store.claims_for(session, [u.id for u in users])
names = await _user_names(session, user_store, claims)
return [
ExternalUserSummary(
@@ -618,26 +626,32 @@ async def list_bridge_users(
async def _user_names(
session: AsyncSession,
user_store: UserStore,
- claims: dict[str, list[str]],
+ claims: dict[str, list[ExternalUserClaim]],
) -> dict[str, str]:
"""Display names for every Switch user appearing in these claims.
Resolved in one pass over the user table rather than a lookup per
claimant: a bridge's user list is otherwise N+1 in the number of claims.
"""
- wanted = {uid for ids in claims.values() for uid in ids}
+ wanted = {claim.user_id for found in claims.values() for claim in found}
if not wanted:
return {}
return {u.id: u.name for u in await user_store.get_all(session) if u.id in wanted}
-def _claimants(user_ids: list[str], names: dict[str, str]) -> list[IdentityClaimant]:
+def _claimants(
+ claims: list[ExternalUserClaim], names: dict[str, str]
+) -> list[IdentityClaimant]:
def label(user_id: str) -> str:
return names.get(user_id) or user_id
return [
- IdentityClaimant(user_id=user_id, user_name=label(user_id))
- for user_id in sorted(user_ids, key=lambda uid: label(uid).lower())
+ IdentityClaimant(
+ user_id=claim.user_id,
+ user_name=label(claim.user_id),
+ verified=claim.verified_at is not None,
+ )
+ for claim in sorted(claims, key=lambda c: label(c.user_id).lower())
]
@@ -700,7 +714,7 @@ async def search_bridge_directory(
except RuntimeError as e:
raise HTTPException(status_code=502, detail=str(e)) from e
- claims = await external_user_store.claimant_ids_for(
+ claims = await external_user_store.claims_for(
session, [u.id for u in known.values()]
)
names = await _user_names(session, user_store, claims)
@@ -775,10 +789,10 @@ async def _require_directory_account(
) -> None:
"""Raise unless the platform's directory really lists this account.
- This is an existence check, not an ownership one — anyone may claim any
- real account, deliberately. What it prevents is provisioning a
- human actor for an id that came from nowhere: the claim body is user-supplied,
- and the row it creates is permanent.
+ This is an existence check, not an ownership one: ownership is what the
+ account proves by confirming the link (CHOO-3881). What it prevents is
+ provisioning a human actor for an id that came from nowhere: the claim
+ body is user-supplied, and the row it creates is permanent.
Only reached for an account Switch has never seen. One it has recorded is
already proof the account exists, and the caller claims it without asking
@@ -827,12 +841,18 @@ async def claim_bridge_identity(
user: Annotated[User, Depends(get_current_user)],
is_admin: Annotated[bool, Depends(get_tenant_is_admin)],
) -> ExternalUserSummary:
- """Claim a platform identity for a Switch user (CHOO-2137).
+ """Start linking a platform identity to a Switch user (CHOO-2137).
This is what makes owner-only addressing enforceable: until the person
behind a Slack or Mattermost account is known to be a particular Switch
user, an owner-scoped rule can never recognise them.
+ The link waits until the account confirms it by posting a one-time code
+ (CHOO-3881), and counts for nothing before then: who an account is
+ recognised as is for the account's holder to say. A claim for yourself
+ comes back with the code; one an admin makes for someone else does not,
+ and the person asks for their own.
+
Claiming one for someone else is an admin action; claiming one for
yourself is not. Claims are **not exclusive** — several Switch users may
claim the same account, and each is then recognised as themselves on it.
@@ -844,16 +864,23 @@ async def claim_bridge_identity(
# session holds, the caller included, and an expired row cannot be
# reloaded from synchronous attribute access.
caller_id = user.id
+ if not payload.expects_confirmation:
+ raise HTTPException(
+ status_code=409,
+ detail=(
+ "Linking a chat account now has to be confirmed from that "
+ "account with a one-time code, and this version of Switch "
+ "Console cannot show one. Update Switch Console, then link the "
+ "account again."
+ ),
+ )
bridge = await bridge_store.get(session, bridge_id)
if bridge is None:
raise HTTPException(status_code=404, detail="Bridge not found")
- target_user_id = payload.user_id or caller_id
- if target_user_id != caller_id and not is_admin:
- raise HTTPException(
- status_code=403,
- detail="Only an admin may claim a messaging identity for another user",
- )
+ target_user_id = _require_self_or_admin(
+ user, is_admin, payload.user_id, "claim a messaging identity"
+ )
# Standing in this tenant, not existence: `users` is deployment-wide, and
# a claim names who the account is recognised as inside this tenant. An
# organization's `org_admin` stands in every workspace of it.
@@ -865,6 +892,9 @@ async def claim_bridge_identity(
):
raise HTTPException(status_code=404, detail="Switch user not found")
+ bridge_type, connection_config = bridge.type, bridge.connection_config or {}
+ _refuse_unlinkable(collab_lifecycle, bridge_type, payload.external_user_id)
+
external_user = await external_user_store.get_by_external_id(
session, bridge_id, payload.external_user_id
)
@@ -909,12 +939,48 @@ async def claim_bridge_identity(
detail="Identity was provisioned but could not be read back",
)
- await external_user_store.claim(session, external_user, target_user_id)
+ claim = await external_user_store.get_claim(
+ session, external_user.id, target_user_id
+ )
+ if claim is not None and claim.verified_at is not None:
+ # Already linked and confirmed: nothing to wait for.
+ return await _identity_summary(
+ session, external_user_store, user_store, external_user, None
+ )
+
+ request = await external_user_store.request_link(
+ session, external_user, target_user_id, requested_by_user_id=caller_id
+ )
+ # Read again now the request is written: a code posted while this ran may
+ # have confirmed the link, and a request for it would wait forever.
+ claim = await external_user_store.get_claim(
+ session, external_user.id, target_user_id
+ )
+ if claim is not None and claim.verified_at is not None:
+ await external_user_store.cancel_link_request(
+ session, external_user, target_user_id
+ )
+ await session.commit()
+ return await _identity_summary(
+ session, external_user_store, user_store, external_user, None
+ )
+ code = (
+ await _issue_code(
+ session,
+ external_user_store,
+ collab_lifecycle,
+ request,
+ bridge_type=bridge_type,
+ connection_config=connection_config,
+ )
+ if target_user_id == caller_id
+ else None
+ )
await record_audit_event(
session,
tenant_id=external_user.tenant_id,
actor_user_id=caller_id,
- action=AuditAction.BRIDGE_IDENTITY_CLAIMED,
+ action=AuditAction.BRIDGE_IDENTITY_LINK_REQUESTED,
target_type="external_user",
target_id=external_user.id,
details={"bridge_id": bridge_id, "user_id": target_user_id},
@@ -922,7 +988,31 @@ async def claim_bridge_identity(
await session.commit()
return await _identity_summary(
- session, external_user_store, user_store, external_user
+ session,
+ external_user_store,
+ user_store,
+ external_user,
+ LinkRequestSummary(user_id=target_user_id, code=code),
+ )
+
+
+async def _issue_code(
+ session: AsyncSession,
+ external_user_store: ExternalUserStore,
+ collab_lifecycle: CollaborationBridgeLifecycleService,
+ request: ExternalUserLinkRequest,
+ *,
+ bridge_type: str,
+ connection_config: dict[str, object],
+) -> LinkCode:
+ code, expires_at = await external_user_store.issue_link_code(session, request)
+ return LinkCode(
+ code=code,
+ expires_at=expires_at,
+ expires_in_seconds=int(LINK_CODE_TTL.total_seconds()),
+ instructions=collab_lifecycle.link_code_instructions(
+ bridge_type, connection_config, code
+ ),
)
@@ -931,19 +1021,320 @@ async def _identity_summary(
external_user_store: ExternalUserStore,
user_store: UserStore,
external_user: ExternalUser,
+ link_request: LinkRequestSummary | None,
) -> ExternalUserSummary:
- claims = {
- external_user.id: await external_user_store.claimant_ids(
- session, external_user.id
- )
- }
+ claims = await external_user_store.claims_for(session, [external_user.id])
names = await _user_names(session, user_store, claims)
return ExternalUserSummary(
id=external_user.id,
bridge_id=external_user.bridge_id,
external_user_id=external_user.external_user_id,
external_username=external_user.external_username,
- claimed_by=_claimants(claims[external_user.id], names),
+ claimed_by=_claimants(claims.get(external_user.id, []), names),
+ link_request=link_request,
+ )
+
+
+async def _identity_on_bridge(
+ session: AsyncSession,
+ external_user_store: ExternalUserStore,
+ bridge_id: str,
+ external_user_row_id: str,
+) -> ExternalUser:
+ external_user = await external_user_store.get(session, external_user_row_id)
+ if external_user is None or external_user.bridge_id != bridge_id:
+ raise HTTPException(status_code=404, detail="Identity not found")
+ return external_user
+
+
+def _refuse_unlinkable(
+ collab_lifecycle: CollaborationBridgeLifecycleService,
+ bridge_type: str,
+ external_user_id: str,
+) -> None:
+ unlinkable = collab_lifecycle.unlinkable_account_reason(
+ bridge_type, external_user_id
+ )
+ if unlinkable is not None:
+ raise HTTPException(
+ status_code=409,
+ detail=f"This account cannot be linked to anyone. {unlinkable}",
+ )
+
+
+def _require_self_or_admin(
+ caller: User, is_admin: bool, user_id: str | None, doing: str
+) -> str:
+ """The Switch user a request acts for: the caller, or anyone for an
+ admin."""
+ target_user_id = user_id or caller.id
+ if target_user_id != caller.id and not is_admin:
+ raise HTTPException(
+ status_code=403,
+ detail=f"Only an admin may {doing} for another user",
+ )
+ return target_user_id
+
+
[email protected]("/{bridge_id}/identities/{external_user_row_id}/code")
+async def issue_identity_link_code(
+ bridge_id: str,
+ external_user_row_id: str,
+ session: Annotated[AsyncSession, Depends(get_session)],
+ bridge_store: Annotated[CollaborationBridgeStore, Depends(get_bridge_store)],
+ external_user_store: Annotated[ExternalUserStore, Depends(get_external_user_store)],
+ collab_lifecycle: Annotated[
+ CollaborationBridgeLifecycleService, Depends(get_collab_lifecycle)
+ ],
+ user: Annotated[User, Depends(get_current_user)],
+) -> LinkCode:
+ """A fresh code that confirms the caller's link to this account
+ (CHOO-3881), replacing any code issued before.
+
+ For a link the caller started, one an admin started for them, or one made
+ before links needed confirming, which keeps working meanwhile. Only ever
+ for the caller: the code is the Switch half of the proof.
+ """
+ caller_id = user.id
+ bridge = await bridge_store.get(session, bridge_id)
+ if bridge is None:
+ raise HTTPException(status_code=404, detail="Bridge not found")
+ external_user = await _identity_on_bridge(
+ session, external_user_store, bridge_id, external_user_row_id
+ )
+ _refuse_unlinkable(collab_lifecycle, bridge.type, external_user.external_user_id)
+ # Locked first, so a code posted at this moment is either redeemed before
+ # this reads the claim or waits for the new code to replace it.
+ request = await external_user_store.lock_link_request(
+ session, external_user.id, caller_id
+ )
+ claim = await external_user_store.get_claim(session, external_user.id, caller_id)
+ if claim is not None and claim.verified_at is not None:
+ raise HTTPException(
+ status_code=409, detail="This account has already confirmed the link"
+ )
+ if request is None:
+ if claim is None:
+ raise HTTPException(
+ status_code=404,
+ detail="You have not started linking this account. Link it first.",
+ )
+ request = await external_user_store.request_link(
+ session, external_user, caller_id, requested_by_user_id=caller_id
+ )
+ await record_audit_event(
+ session,
+ tenant_id=external_user.tenant_id,
+ actor_user_id=caller_id,
+ action=AuditAction.BRIDGE_IDENTITY_LINK_REQUESTED,
+ target_type="external_user",
+ target_id=external_user.id,
+ details={"bridge_id": bridge_id, "user_id": caller_id},
+ )
+ code = await _issue_code(
+ session,
+ external_user_store,
+ collab_lifecycle,
+ request,
+ bridge_type=bridge.type,
+ connection_config=bridge.connection_config or {},
+ )
+ await session.commit()
+ return code
+
+
[email protected]("/{bridge_id}/identities/{external_user_row_id}/verify-session")
+async def verify_identity_with_session(
+ bridge_id: str,
+ external_user_row_id: str,
+ payload: VerifyIdentitySessionRequest,
+ session: Annotated[AsyncSession, Depends(get_session)],
+ external_user_store: Annotated[ExternalUserStore, Depends(get_external_user_store)],
+ user_store: Annotated[UserStore, Depends(get_user_store)],
+ collab_lifecycle: Annotated[
+ CollaborationBridgeLifecycleService, Depends(get_collab_lifecycle)
+ ],
+ user: Annotated[User, Depends(get_current_user)],
+) -> ExternalUserSummary:
+ """Confirm the caller's pending link with the account's own session token.
+
+ The alternative to posting a code, for the bundled deployment's setup: it
+ holds the login of the Mattermost account it creates, but no channel has
+ an agent in it yet to hear a code. A session token is as good a proof as a
+ post, since the platform says whose it is. Mattermost only.
+ """
+ caller_id = user.id
+ external_user = await _identity_on_bridge(
+ session, external_user_store, bridge_id, external_user_row_id
+ )
+ request = await external_user_store.get_link_request(
+ session, external_user.id, caller_id
+ )
+ if request is None:
+ raise HTTPException(
+ status_code=404,
+ detail="You have no link to this account waiting to be confirmed",
+ )
+ adapter = collab_lifecycle.get_adapter(bridge_id)
+ if adapter is None:
+ raise HTTPException(
+ status_code=409,
+ detail="Bridge is not running — cannot check this session token",
+ )
+ # Not held across the platform call.
+ await session.commit()
+ try:
+ account_id = await adapter.account_id_for_session(payload.token)
+ except NotImplementedError as e:
+ raise HTTPException(status_code=501, detail=str(e)) from e
+ except PermissionError as e:
+ raise HTTPException(status_code=403, detail=str(e)) from e
+ except RuntimeError as e:
+ raise HTTPException(status_code=502, detail=str(e)) from e
+ if account_id != external_user.external_user_id:
+ raise HTTPException(
+ status_code=403,
+ detail="That session token belongs to a different account",
+ )
+
+ request = await external_user_store.lock_link_request(
+ session, external_user.id, caller_id
+ )
+ if request is None:
+ raise HTTPException(
+ status_code=409, detail="The link was cancelled while it was being checked"
+ )
+ await external_user_store.confirm_link_request(session, request)
+ await record_audit_event(
+ session,
+ tenant_id=external_user.tenant_id,
+ actor_user_id=caller_id,
+ action=AuditAction.BRIDGE_IDENTITY_CLAIMED,
+ target_type="external_user",
+ target_id=external_user.id,
+ details={"bridge_id": bridge_id, "user_id": caller_id, "by": "session"},
+ )
+ await session.commit()
+ return await _identity_summary(
+ session, external_user_store, user_store, external_user, None
+ )
+
+
[email protected]("/{bridge_id}/identities/unconfirmed")
+async def list_unconfirmed_identity_links(
+ bridge_id: str,
+ session: Annotated[AsyncSession, Depends(get_session)],
+ bridge_store: Annotated[CollaborationBridgeStore, Depends(get_bridge_store)],
+ external_user_store: Annotated[ExternalUserStore, Depends(get_external_user_store)],
+ user_store: Annotated[UserStore, Depends(get_user_store)],
+ _admin: Annotated[User, Depends(require_tenant_admin)],
+) -> list[UnconfirmedLink]:
+ """The links on this bridge made before links needed confirming
+ (CHOO-3881), which count until their owners confirm them. What an admin
+ reads before `require_identity_confirmation` stops trusting them."""
+ if await bridge_store.get(session, bridge_id) is None:
+ raise HTTPException(status_code=404, detail="Bridge not found")
+ found = await external_user_store.unconfirmed_claims(session, bridge_id)
+ claims: dict[str, list[ExternalUserClaim]] = {}
+ for external, claim in found:
+ claims.setdefault(external.id, []).append(claim)
+ names = await _user_names(session, user_store, claims)
+ return sorted(
+ (
+ UnconfirmedLink(
+ id=external.id,
+ external_user_id=external.external_user_id,
+ external_username=external.external_username,
+ user_id=claim.user_id,
+ user_name=names.get(claim.user_id) or claim.user_id,
+ )
+ for external, claim in found
+ ),
+ key=lambda link: (link.user_name.casefold(), link.external_username.casefold()),
+ )
+
+
[email protected]("/{bridge_id}/identities/require-confirmation")
+async def require_identity_confirmation(
+ bridge_id: str,
+ session: Annotated[AsyncSession, Depends(get_session)],
+ bridge_store: Annotated[CollaborationBridgeStore, Depends(get_bridge_store)],
+ external_user_store: Annotated[ExternalUserStore, Depends(get_external_user_store)],
+ admin: Annotated[User, Depends(require_tenant_admin)],
+) -> RequireConfirmationResult:
+ """Stop trusting this bridge's links made before links needed confirming
+ (CHOO-3881), until each owner confirms theirs with a code.
+
+ Each becomes a link waiting for its account, as if its owner had just
+ started it, so it counts for nothing until then. Their owner-only agents
+ stop recognising them in the meantime, which is the point and what an
+ admin is told before running it. Links already confirmed, and other
+ bridges, are untouched; running it again moves nothing.
+ """
+ bridge = await bridge_store.get(session, bridge_id)
+ if bridge is None:
+ raise HTTPException(status_code=404, detail="Bridge not found")
+ moved = await external_user_store.require_confirmation(
+ session, bridge_id, requested_by_user_id=admin.id
+ )
+ await record_audit_event(
+ session,
+ tenant_id=bridge.tenant_id,
+ actor_user_id=admin.id,
+ action=AuditAction.BRIDGE_IDENTITY_CONFIRMATION_REQUIRED,
+ target_type="collaboration_bridge",
+ target_id=bridge_id,
+ details={"moved": len(moved)},
+ )
+ await session.commit()
+ return RequireConfirmationResult(moved=len(moved))
+
+
[email protected]("/{bridge_id}/identities/{external_user_row_id}/request")
+async def cancel_identity_link_request(
+ bridge_id: str,
+ external_user_row_id: str,
+ session: Annotated[AsyncSession, Depends(get_session)],
+ external_user_store: Annotated[ExternalUserStore, Depends(get_external_user_store)],
+ user_store: Annotated[UserStore, Depends(get_user_store)],
+ user: Annotated[User, Depends(get_current_user)],
+ is_admin: Annotated[bool, Depends(get_tenant_is_admin)],
+ user_id: str | None = None,
+) -> ExternalUserSummary:
+ """Stop waiting for the account to confirm a link (CHOO-3881) — your own,
+ or someone else's if you are an admin.
+
+ Never touches a claim: walking away from confirming a link made before
+ links needed confirming leaves that link working. Unlinking is
+ `release_bridge_identity`.
+ """
+ external_user = await _identity_on_bridge(
+ session, external_user_store, bridge_id, external_user_row_id
+ )
+ target_user_id = _require_self_or_admin(
+ user, is_admin, user_id, "cancel a link to a messaging identity"
+ )
+ try:
+ await external_user_store.cancel_link_request(
+ session, external_user, target_user_id
+ )
+ except NoSuchLink as e:
+ raise HTTPException(
+ status_code=404,
+ detail="That user has no link to this account waiting to be confirmed",
+ ) from e
+ await record_audit_event(
+ session,
+ tenant_id=external_user.tenant_id,
+ actor_user_id=user.id,
+ action=AuditAction.BRIDGE_IDENTITY_LINK_CANCELLED,
+ target_type="external_user",
+ target_id=external_user.id,
+ details={"bridge_id": bridge_id, "user_id": target_user_id},
+ )
+ await session.commit()
+ return await _identity_summary(
+ session, external_user_store, user_store, external_user, None
)
@@ -958,39 +1349,44 @@ async def release_bridge_identity(
is_admin: Annotated[bool, Depends(get_tenant_is_admin)],
user_id: str | None = None,
) -> ExternalUserSummary:
- """Drop a claim on a platform account — your own, or someone else's if you
- are an admin. Anyone else's claim on the same account is left standing."""
- external_user = await external_user_store.get(session, external_user_row_id)
- if external_user is None or external_user.bridge_id != bridge_id:
- raise HTTPException(status_code=404, detail="Identity not found")
+ """Drop a claim on a platform account, and any link to it still waiting to
+ be confirmed — your own, or someone else's if you are an admin. Anyone
+ else's claim on the same account is left standing."""
+ external_user = await _identity_on_bridge(
+ session, external_user_store, bridge_id, external_user_row_id
+ )
+ target_user_id = _require_self_or_admin(
+ user, is_admin, user_id, "release a messaging identity"
+ )
- target_user_id = user_id or user.id
- if target_user_id != user.id and not is_admin:
- raise HTTPException(
- status_code=403,
- detail="Only an admin may release another user's messaging identity",
+ try:
+ released = await external_user_store.release(
+ session, external_user, target_user_id
)
-
- released = await external_user_store.release(session, external_user, target_user_id)
- if not released:
+ except NoSuchLink as e:
# Deleting nothing and reporting success would make a mistyped user id
# look like an unlink that worked.
raise HTTPException(
status_code=404,
- detail="That user has no claim on this messaging account",
- )
+ detail="That user has no link to this messaging account",
+ ) from e
await record_audit_event(
session,
tenant_id=external_user.tenant_id,
actor_user_id=user.id,
- action=AuditAction.BRIDGE_IDENTITY_RELEASED,
+ # A link that never counted was cancelled, not released.
+ action=(
+ AuditAction.BRIDGE_IDENTITY_RELEASED
+ if released.claim
+ else AuditAction.BRIDGE_IDENTITY_LINK_CANCELLED
+ ),
target_type="external_user",
target_id=external_user.id,
details={"bridge_id": bridge_id, "user_id": target_user_id},
)
await session.commit()
return await _identity_summary(
- session, external_user_store, user_store, external_user
+ session, external_user_store, user_store, external_user, None
)
diff --git a/core/switch_core/gateway/schemas.py b/core/switch_core/gateway/schemas.py
index 264af0ad6..60aab4ba2 100644
--- a/core/switch_core/gateway/schemas.py
+++ b/core/switch_core/gateway/schemas.py
@@ -735,6 +735,32 @@ class IdentityClaimant(BaseModel):
user_id: str
user_name: str
+ # False for a claim made before accounts had to confirm their links
+ # (CHOO-3881). It still counts, and its owner is asked to confirm it.
+ verified: bool
+
+
+class LinkCode(BaseModel):
+ """A one-time code that confirms a link when posted from the account."""
+
+ code: str
+ expires_at: datetime
+ # Its lifetime when issued, so a client can count down on its own clock
+ # rather than compare `expires_at` with a clock that may be wrong.
+ expires_in_seconds: int
+ # How to post it on this platform, in Markdown. The platforms differ in
+ # which messages reach Switch at all, so this is the bridge's to say.
+ instructions: str
+
+
+class LinkRequestSummary(BaseModel):
+ """A link waiting for the platform account to confirm it."""
+
+ user_id: str
+ # Only for the Switch user being linked, and only on the response that
+ # issued it: the code is not stored, so a lost one is replaced, not shown
+ # again. An admin linking someone else never gets one.
+ code: LinkCode | None
class ExternalUserSummary(BaseModel):
@@ -746,6 +772,9 @@ class ExternalUserSummary(BaseModel):
# claiming is not exclusive, so an account shared by several Switch users
# satisfies an owner rule for any of them.
claimed_by: list[IdentityClaimant] = []
+ # Set on the response to a claim that is waiting for the account to
+ # confirm it, which counts for nothing until it does.
+ link_request: LinkRequestSummary | None = None
class DirectoryUserSummary(BaseModel):
@@ -793,6 +822,11 @@ class ClaimIdentityRequest(BaseModel):
# Omitted means "claim it for me"; only an admin may claim on behalf of
# someone else.
user_id: str | None = None
+ # That the caller knows the link will wait for the account to confirm it
+ # (CHOO-3881). A Console from before then leaves it out and would report
+ # a link that does not count as made, so the claim is refused with a
+ # reason it shows instead.
+ expects_confirmation: bool = False
class LinkedIdentity(BaseModel):
@@ -804,6 +838,52 @@ class LinkedIdentity(BaseModel):
bridge_type: str
external_user_id: str
external_username: str
+ # False for a link made before accounts had to confirm them: it works,
+ # and Console asks its owner to confirm it.
+ verified: bool
+
+
+class PendingIdentity(BaseModel):
+ """A platform account waiting to confirm a link to the signed-in user.
+
+ It counts for nothing yet. No code is listed, because none is stored:
+ asking for one issues a fresh one.
+ """
+
+ id: str
+ bridge_id: str
+ bridge_display_name: str
+ bridge_type: str
+ external_user_id: str
+ external_username: str
+ # Who started it, when that was someone else (an admin); null when it was
+ # the user themselves or the admin has since been deleted.
+ requested_by_name: str | None
+ # When the last code issued stops working; null when none has been issued,
+ # as for a link an admin started.
+ code_expires_at: datetime | None
+
+
+class UnconfirmedLink(BaseModel):
+ """A link made before links needed confirming. It counts until its owner
+ confirms it, or an admin requires them to."""
+
+ id: str
+ external_user_id: str
+ external_username: str
+ user_id: str
+ user_name: str
+
+
+class RequireConfirmationResult(BaseModel):
+ # How many links stopped counting and now wait for their owners' codes.
+ moved: int
+
+
+class VerifyIdentitySessionRequest(BaseModel):
+ """Confirm a link with the platform account's own session token."""
+
+ token: str
# ── Auth ─────────────────────────────────────────────────────────────────────
diff --git a/core/switch_core/migrations/versions/3b81c0e5d9a7_external_user_link_requests.py b/core/switch_core/migrations/versions/3b81c0e5d9a7_external_user_link_requests.py
new file mode 100644
index 000000000..63961da55
--- /dev/null
+++ b/core/switch_core/migrations/versions/3b81c0e5d9a7_external_user_link_requests.py
@@ -0,0 +1,112 @@
+"""external user link requests, and when a claim was verified
+
+A link from a chat account to a Switch user now waits in
+`external_user_link_requests` until the account confirms it by posting a
+one-time code, and only then becomes a row in `external_user_claims`.
+
+The requests get a table of their own rather than a state on the claims,
+because every reader of `external_user_claims` treats a row as trusted. A
+pending row there would be trusted by any reader that forgot to filter it out,
+and by every reader in a release from before this revision while the two run
+side by side.
+
+`external_user_claims.verified_at` says when the account confirmed a claim. It
+is null for every claim that exists before this revision: those keep working,
+and Console asks their owners to confirm them.
+
+The `tenant_isolation` policy is written out below rather than inherited,
+because `265ed188ad6f` installed the policies as they stood then and a table
+added afterwards has to bring its own. The DDL is a verbatim copy of
+`switch_core/db/rls_ddl.py` as it stood when this migration was written,
+copied rather than imported so a later edit to that module cannot change what
+this revision means. `tests/switch_core/db/test_frozen_ddl_matches_create_all.py`
+keeps the copy from drifting.
+
+Expand only: a release from before this revision never reads the new table or
+column, and its claims are written straight into `external_user_claims` as
+they always were, where they read as unverified.
+
+Revision ID: 3b81c0e5d9a7
+Revises: ad15e53358fe
+Create Date: 2026-10-27 19:00:00.000000
+
+"""
+
+from collections.abc import Sequence
+
+import sqlalchemy as sa
+from alembic import op
+
+revision: str = "3b81c0e5d9a7"
+down_revision: str | None = "ad15e53358fe"
+branch_labels: str | Sequence[str] | None = None
+depends_on: str | Sequence[str] | None = None
+expand_only: bool = True
+
+TABLE = "external_user_link_requests"
+POLICY_NAME = "tenant_isolation"
+
+ENABLE_RLS = f'ALTER TABLE "{TABLE}" ENABLE ROW LEVEL SECURITY'
+
+CREATE_POLICY = f"""CREATE POLICY {POLICY_NAME} ON "{TABLE}"
+ FOR ALL
+ USING ("tenant_id" = (SELECT require_tenant_id()))
+ WITH CHECK ("tenant_id" = (SELECT require_tenant_id()))"""
+
+DROP_POLICY = f'DROP POLICY IF EXISTS {POLICY_NAME} ON "{TABLE}"'
+
+
+def upgrade() -> None:
+ op.add_column(
+ "external_user_claims",
+ sa.Column("verified_at", sa.DateTime(timezone=True), nullable=True),
+ )
+ op.create_table(
+ TABLE,
+ sa.Column("external_user_id", sa.Text(), nullable=False),
+ sa.Column("user_id", sa.Text(), nullable=False),
+ sa.Column("requested_by_user_id", sa.Text(), nullable=True),
+ sa.Column("code_hash", sa.Text(), nullable=True),
+ sa.Column("code_expires_at", sa.DateTime(timezone=True), nullable=True),
+ sa.Column(
+ "created_at",
+ sa.DateTime(timezone=True),
+ server_default=sa.text("now()"),
+ nullable=False,
+ ),
+ sa.Column("tenant_id", sa.Text(), nullable=False),
+ sa.PrimaryKeyConstraint("external_user_id", "user_id"),
+ sa.ForeignKeyConstraint(
+ ["tenant_id"], ["tenants.id"], name="fk_external_user_link_requests_tenant"
+ ),
+ sa.ForeignKeyConstraint(
+ ["tenant_id", "external_user_id"],
+ ["external_users.tenant_id", "external_users.id"],
+ name="fk_external_user_link_requests_external_user",
+ ondelete="CASCADE",
+ ),
+ sa.ForeignKeyConstraint(
+ ["user_id"],
+ ["users.id"],
+ name="fk_external_user_link_requests_user",
+ ondelete="CASCADE",
+ ),
+ sa.ForeignKeyConstraint(
+ ["requested_by_user_id"],
+ ["users.id"],
+ name="fk_external_user_link_requests_requested_by",
+ ondelete="SET NULL",
+ ),
+ )
+ op.create_index("ix_external_user_link_requests_tenant_id", TABLE, ["tenant_id"])
+ op.create_index("ix_external_user_link_requests_user_id", TABLE, ["user_id"])
+ op.execute(ENABLE_RLS)
+ op.execute(CREATE_POLICY)
+
+
+def downgrade() -> None:
+ op.execute(DROP_POLICY)
+ op.drop_index("ix_external_user_link_requests_user_id", table_name=TABLE)
+ op.drop_index("ix_external_user_link_requests_tenant_id", table_name=TABLE)
+ op.drop_table(TABLE)
+ op.drop_column("external_user_claims", "verified_at")
diff --git a/core/switch_core/official_templates/switch-buddy/AGENT.md b/core/switch_core/official_templates/switch-buddy/AGENT.md
index 6cbcd3f58..98c093e2d 100644
--- a/core/switch_core/official_templates/switch-buddy/AGENT.md
+++ b/core/switch_core/official_templates/switch-buddy/AGENT.md
@@ -282,10 +282,23 @@ workspace. Offer to draft the message.
app instead" and paste the values.
- Never ask them to paste a token into this chat.
-**Their chat account** — when an app is connected but `your_account_linked` is
-false, agents that answer only their owner won't recognise them there. Link
-[the server's home](switchdash://open/home), where Messaging apps lets them link
-their account.
+**Their chat account** — read `your_account_link` for the app:
+- `none`: agents that answer only their owner won't recognise them there. Link
+ [the server's home](switchdash://open/home), where Messaging apps lets them
+ link their account.
+- `pending`: the link is waiting for the account to confirm it, so it doesn't
+ count yet. Either they started linking, or a workspace admin required them
+ to confirm a link made before links needed confirming. Switch Console showed them a code to post from that chat
+ account (for example `!link-account 7KQ2-M9XD`); tell them to post it, or to
+ get a new code from [the server's home](switchdash://open/home) if it has
+ expired.
+- `unverified`: it works, but was linked before links needed confirming. Suggest
+ confirming it from [the server's home](switchdash://open/home), which gives
+ them a code to post from that account.
+- `verified`: nothing to do.
+
+Never ask for the code or post it yourself: it only works when the chat account
+it was issued for posts it.
### Adding people to a room
@@ -296,8 +309,9 @@ person is left out.
- **The person you are talking to:** their usernames on each app are `your_usernames` in
`get_my_context` (`messaging_apps.connected`, matched to the room's `bridge_id` by `id`).
- When the list is empty their account is not linked there yet: ask for their username on
- that app, and link [the server's home](switchdash://open/home) so they can link it.
+ When the list is empty their account is not linked there yet, or the link is still
+ waiting for its code (see `your_account_link`): ask for their username on that app, and link
+ [the server's home](switchdash://open/home) so they can link it.
- **Anyone else:** ask for their username on that app, or the e-mail address they use
there. Never guess one from a first name.
- **Check the result.** `add_users_to_room` returns `unresolved`, the people it could not
@@ -417,7 +431,8 @@ Things people ask for that you should know:
(`switchdash://open/agent/<agent-id>?tab=settings`); "Anyone" admits anyone in the
rooms the agent is in. You can change it for an
agent with `update_agent_detail` once they say so. Warn them: a person whose chat account
- is not linked to Switch is not recognised, and the agent will not answer them.
+ is not linked to Switch is not recognised, and the agent will not answer them. A new link
+ counts once they post, from that account, the code Switch Console shows them.
- **"Put you (or an agent) in a channel."** Two steps, in this order, one message each:
1. **Add the Switch app to the channel.** A channel does nothing for Switch until the
Switch app is in it (on Slack: mention the app in the channel and accept the invite,
diff --git a/core/switch_core/official_templates/switch-expert/AGENT.md b/core/switch_core/official_templates/switch-expert/AGENT.md
index 21a56dd18..de7e1fbd2 100644
--- a/core/switch_core/official_templates/switch-expert/AGENT.md
+++ b/core/switch_core/official_templates/switch-expert/AGENT.md
@@ -221,7 +221,9 @@ properly, and the person will hit the gaps later rather than sooner.
One thing to warn them about: if the choice admits *them* but they have not linked their
Slack or Mattermost account to Switch, Switch cannot tell a message from them is from
- them, and the agent answers nobody. Switch Console says so on the setting itself.
+ them, and the agent answers nobody. Switch Console says so on the setting itself. A
+ link counts once they confirm it by posting, from that chat account, the code Switch
+ Console shows them.
6. **Run it somewhere that stays up — and let Switch Console do that for you.** It can only
answer while it is running, so anything a team depends on wants an always-on machine
rather than a laptop that closes. **This is much less work than it sounds.** All you need
diff --git a/core/tests/deploy/test_setup_link_owner.py b/core/tests/deploy/test_setup_link_owner.py
new file mode 100644
index 000000000..19b81d313
--- /dev/null
+++ b/core/tests/deploy/test_setup_link_owner.py
@@ -0,0 +1,228 @@
+"""The setup job links the seeded Mattermost account to the seeded admin, and
+confirms the link with that account's own session (CHOO-3881).
+
+A link counts only once the account confirms it. A person confirms by posting
+a code where an agent can hear it, and a fresh deployment has no agent yet, so
+setup proves the account the other way: it signs in as the account it
+created and hands Switch the session, then signs out.
+"""
+
+from __future__ import annotations
+
+import importlib.util
+import json
+import sys
+from pathlib import Path
+from types import SimpleNamespace
+from typing import Any
+
+import httpx
+import pytest
+
+_REPO_ROOT = Path(__file__).resolve().parents[3]
+_SETUP_PY = _REPO_ROOT / "deploy" / "shared_resources" / "setup.py"
+
+_ENV = {
+ "SWITCH_URL": "http://switch-core:8000",
+ "GATEWAY_ADMIN_EMAIL": "[email protected]",
+ "GATEWAY_ADMIN_PASSWORD": "setup-test-password",
+ "MATTERMOST_URL": "http://mattermost:8065",
+ "MATTERMOST_ADMIN_USER": "admin",
+ "MATTERMOST_ADMIN_PASSWORD": "setup-test-password",
+ "MATTERMOST_TEAM_NAME": "switch",
+ "MATTERMOST_USER": "user",
+ "MATTERMOST_USER_PASSWORD": "user-test-password",
+}
+
+
+def setup_script(monkeypatch: pytest.MonkeyPatch) -> Any:
+ for key, value in _ENV.items():
+ monkeypatch.setenv(key, value)
+ spec = importlib.util.spec_from_file_location("_switch_setup_link", _SETUP_PY)
+ assert spec and spec.loader
+ module = importlib.util.module_from_spec(spec)
+ sys.modules["_switch_setup_link"] = module
+ try:
+ spec.loader.exec_module(module)
+ yield module
+ finally:
+ sys.modules.pop("_switch_setup_link", None)
+
+
+class _Platforms:
+ """Switch's gateway and the bundled Mattermost, recording every call."""
+
+ def __init__(
+ self,
+ *,
+ claim: dict[str, Any],
+ login_status: int = 200,
+ linked: list[dict[str, Any]] | None = None,
+ ) -> None:
+ self.claim = claim
+ self.login_status = login_status
+ self.linked = linked or []
+ self.calls: list[tuple[str, str, Any]] = []
+
+ def gateway(self, request: httpx.Request) -> httpx.Response:
+ body = json.loads(request.content) if request.content else None
+ self.calls.append((request.method, request.url.path, body))
+ path = request.url.path
+ if path == "/gateway/auth/me/identities":
+ return httpx.Response(200, json=self.linked)
+ if path.endswith("/directory"):
+ return httpx.Response(200, json={"users": [{"external_user_id": "mm-1"}]})
+ if path.endswith("/identities"):
+ return httpx.Response(200, json=self.claim)
+ if path.endswith("/verify-session"):
+ return httpx.Response(200, json={**self.claim, "link_request": None})
+ return httpx.Response(404)
+
+ def mattermost(self, request: httpx.Request) -> httpx.Response:
+ body = json.loads(request.content) if request.content else None
+ self.calls.append(
+ (
+ request.method,
+ request.url.path,
+ body or request.headers.get("authorization"),
+ )
+ )
+ if request.url.path == "/api/v4/users/login":
+ if self.login_status != 200:
+ return httpx.Response(self.login_status, text="no")
+ return httpx.Response(200, headers={"Token": "mm-session"}, json={})
+ return httpx.Response(200, json={})
+
+
+def _run(
+ setup_script: Any, platforms: _Platforms, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ real_client = httpx.Client
+
+ def client(*, base_url: str, timeout: float) -> httpx.Client:
+ assert base_url == _ENV["MATTERMOST_URL"]
+ return real_client(
+ base_url=base_url,
+ timeout=timeout,
+ transport=httpx.MockTransport(platforms.mattermost),
+ )
+
+ monkeypatch.setattr(setup_script, "httpx", SimpleNamespace(Client=client))
+ gateway = real_client(
+ base_url=_ENV["SWITCH_URL"], transport=httpx.MockTransport(platforms.gateway)
+ )
+ setup_script.link_owner_identity(gateway, "bridge-1", "mm-1")
+
+
+_PENDING = {
+ "id": "identity-1",
+ "link_request": {"user_id": "admin-id", "code": {"code": "ABCD-EFGH"}},
+}
+
+
+def test_a_waiting_link_is_confirmed_with_the_accounts_session(
+ setup_script: Any, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ platforms = _Platforms(claim=_PENDING)
+
+ _run(setup_script, platforms, monkeypatch)
+
+ assert (
+ "POST",
+ "/api/v4/users/login",
+ {"login_id": "user", "password": "user-test-password"},
+ ) in platforms.calls
+ assert (
+ "POST",
+ "/gateway/collaborations/bridge-1/identities/identity-1/verify-session",
+ {"token": "mm-session"},
+ ) in platforms.calls
+ # Signed out again, with the session it opened.
+ assert platforms.calls[-1] == ("POST", "/api/v4/users/logout", "Bearer mm-session")
+
+
+def test_a_link_that_needs_no_confirming_opens_no_session(
+ setup_script: Any, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ platforms = _Platforms(claim={"id": "identity-1", "link_request": None})
+
+ _run(setup_script, platforms, monkeypatch)
+
+ assert not any(path.startswith("/api/v4/") for _m, path, _b in platforms.calls)
+
+
+def test_a_failed_sign_in_leaves_the_link_waiting(
+ setup_script: Any,
+ monkeypatch: pytest.MonkeyPatch,
+ capsys: pytest.CaptureFixture[str],
+) -> None:
+ platforms = _Platforms(claim=_PENDING, login_status=401)
+
+ _run(setup_script, platforms, monkeypatch)
+
+ assert not any(path.endswith("/verify-session") for _m, path, _b in platforms.calls)
+ assert "waiting to be confirmed" in capsys.readouterr().out
+
+
+def test_a_link_from_before_confirmation_is_confirmed_on_a_rerun(
+ setup_script: Any, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ platforms = _Platforms(
+ claim=_PENDING,
+ linked=[
+ {"bridge_id": "bridge-1", "external_user_id": "mm-1", "verified": False}
+ ],
+ )
+
+ _run(setup_script, platforms, monkeypatch)
+
+ assert any(path.endswith("/verify-session") for _m, path, _b in platforms.calls)
+
+
+def test_an_unconfirmed_link_to_another_account_is_left_alone(
+ setup_script: Any, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ # The admin linked their own account before confirmation existed: setup
+ # must not add the seeded one beside it.
+ platforms = _Platforms(
+ claim=_PENDING,
+ linked=[
+ {"bridge_id": "bridge-1", "external_user_id": "mm-other", "verified": False}
+ ],
+ )
+
+ _run(setup_script, platforms, monkeypatch)
+
+ assert [(m, path) for m, path, _b in platforms.calls] == [
+ ("GET", "/gateway/auth/me/identities")
+ ]
+
+
+def test_a_confirmed_link_is_left_alone(
+ setup_script: Any, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ platforms = _Platforms(
+ claim=_PENDING, linked=[{"bridge_id": "bridge-1", "verified": True}]
+ )
+
+ _run(setup_script, platforms, monkeypatch)
+
+ assert [(m, path) for m, path, _b in platforms.calls] == [
+ ("GET", "/gateway/auth/me/identities")
+ ]
+
+
+def test_the_claim_says_it_expects_confirmation(
+ setup_script: Any, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ platforms = _Platforms(claim=_PENDING)
+
+ _run(setup_script, platforms, monkeypatch)
+
+ claim = next(
+ body
+ for m, path, body in platforms.calls
+ if m == "POST" and path.endswith("/identities")
+ )
+ assert claim["expects_confirmation"] is True
diff --git a/core/tests/switch_core/bridges/agent/test_commands_link_account.py b/core/tests/switch_core/bridges/agent/test_commands_link_account.py
new file mode 100644
index 000000000..dfb38172b
--- /dev/null
+++ b/core/tests/switch_core/bridges/agent/test_commands_link_account.py
@@ -0,0 +1,305 @@
+"""`!link-account` and `!unlink-account`: a chat account's own say over its
+links to Switch users (CHOO-3881).
+
+Run against real Postgres with real stores: who sent a command is the whole
+point, and it is decided by which chat account's client the message came
+from, never by anything in the message.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+from types import SimpleNamespace
+from typing import Any
+
+import pytest
+from sqlalchemy import select
+from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
+
+from switch_core.bridges.agent.commands import _cmd_link_account, _cmd_unlink_account
+from switch_core.clients.command_consumer import CommandConsumer
+from switch_core.db.audit import AuditAction
+from switch_core.db.models import (
+ TENANT_ZERO_ID,
+ AuditEvent,
+ Client,
+ CollaborationBridge,
+ ExternalUser,
+ ExternalUserClaim,
+ TenantMember,
+ User,
+)
+from switch_core.db.stores.client_store import ClientStore
+from switch_core.db.stores.external_user_store import ExternalUserStore
+from switch_core.db.stores.user_store import UserStore
+
+_ROOM = SimpleNamespace(room_id="!room:test")
+_STORE = ExternalUserStore()
+
+
+@dataclass
+class _World:
+ host: CommandConsumer
+ replies: list[str]
+ session_factory: async_sessionmaker[AsyncSession]
+ ada: str
+ bob: str
+ ada_account: ExternalUser
+ ada_chat: str
+ bystander_chat: str
+ member_chat: str
+
+
+async def _user(session: AsyncSession, name: str) -> str:
+ user = User(name=name, email=f"{name}@test", role="user", password_hash="x")
+ session.add(user)
+ await session.flush()
+ session.add(TenantMember(tenant_id=TENANT_ZERO_ID, user_id=user.id, role="member"))
+ await session.flush()
+ return user.id
+
+
+async def _account(
+ session: AsyncSession, bridge_id: str, name: str
+) -> tuple[ExternalUser, str]:
+ client = Client(
+ transport_user_id=f"@chat-{name}:test", display_name=name, type="user"
+ )
+ session.add(client)
+ await session.flush()
+ account = ExternalUser(
+ bridge_id=bridge_id,
+ external_user_id=f"U-{name}",
+ external_username=name,
+ client_id=client.id,
+ )
+ session.add(account)
+ await session.flush()
+ return account, client.transport_user_id
+
+
+async def world(session_factory: async_sessionmaker[AsyncSession]) -> _World:
+ async with session_factory() as session:
+ bridge_client = Client(
+ transport_user_id="@bridge:test", display_name="bridge", type="bridge"
+ )
+ session.add(bridge_client)
+ await session.flush()
+ bridge = CollaborationBridge(
+ type="slack",
+ display_name="Acme Slack",
+ client_id=bridge_client.id,
+ status="active",
+ )
+ session.add(bridge)
+ await session.flush()
+ ada = await _user(session, "ada")
+ bob = await _user(session, "bob")
+ ada_account, ada_chat = await _account(session, bridge.id, "ada")
+ _bystander, bystander_chat = await _account(session, bridge.id, "bystander")
+ # Ada speaking in Console: a gateway member, not a chat account.
+ member = Client(
+ transport_user_id="@member-ada:test",
+ display_name="ada",
+ type="member",
+ user_id=ada,
+ )
+ session.add(member)
+ await session.commit()
+
+ replies: list[str] = []
+
+ async def reply_command(_room_id: str, body: str, **_kw: Any) -> None:
+ replies.append(body)
+
+ host = object.__new__(CommandConsumer)
+ host.actor = SimpleNamespace( # type: ignore[assignment]
+ session_factory=session_factory, client_store=ClientStore()
+ )
+ host._external_user_store = ExternalUserStore()
+ host._user_store = UserStore()
+ host.reply_command = reply_command # type: ignore[method-assign]
+ return _World(
+ host=host,
+ replies=replies,
+ session_factory=session_factory,
+ ada=ada,
+ bob=bob,
+ ada_account=ada_account,
+ ada_chat=ada_chat,
+ bystander_chat=bystander_chat,
+ member_chat=member.transport_user_id,
+ )
+
+
+def _event(command: str, args: str, sender: str) -> Any:
+ return SimpleNamespace(
+ command=command, args=args, user_id=sender, user_name="someone", thread_id="t1"
+ )
+
+
+async def _link(world: _World, args: str, sender: str) -> None:
+ await _cmd_link_account(
+ world.host, # type: ignore[arg-type]
+ _ROOM, # type: ignore[arg-type]
+ _event("link-account", args, sender),
+ False,
+ )
+
+
+async def _unlink(world: _World, args: str, sender: str) -> None:
+ await _cmd_unlink_account(
+ world.host, # type: ignore[arg-type]
+ _ROOM, # type: ignore[arg-type]
+ _event("unlink-account", args, sender),
+ False,
+ )
+
+
+async def _code_for(world: _World, user_id: str) -> str:
+ async with world.session_factory() as session:
+ request = await _STORE.request_link(
+ session, world.ada_account, user_id, requested_by_user_id=user_id
+ )
+ code, _expires = await _STORE.issue_link_code(session, request)
+ await session.commit()
+ return code
+
+
+async def _claimants(world: _World) -> list[str]:
+ async with world.session_factory() as session:
+ return sorted(await _STORE.claimant_ids(session, world.ada_account.id))
+
+
+class TestLinkAccount:
+ async def test_the_code_from_the_account_links_it_and_says_to_whom(
+ self, world: _World
+ ) -> None:
+ code = await _code_for(world, world.ada)
+
+ await _link(world, code, world.ada_chat)
+
+ assert await _claimants(world) == [world.ada]
+ assert len(world.replies) == 1
+ assert "**ada**" in world.replies[0]
+ assert "Acme Slack" in world.replies[0]
+ assert "`unlink-account ada` the way you ran this command" in world.replies[0]
+ async with world.session_factory() as session:
+ event = await session.scalar(
+ select(AuditEvent).where(
+ AuditEvent.action == AuditAction.BRIDGE_IDENTITY_CLAIMED
+ )
+ )
+ assert event is not None
+ assert event.actor_user_id == world.ada
+ assert event.details["by"] == "code"
+
+ async def test_the_code_from_another_account_links_nothing(
+ self, world: _World
+ ) -> None:
+ code = await _code_for(world, world.ada)
+
+ await _link(world, code, world.bystander_chat)
+
+ assert await _claimants(world) == []
+ assert world.replies[0].startswith("⚠️")
+
+ async def test_a_message_from_console_cannot_confirm(self, world: _World) -> None:
+ # The member client is Ada herself, but it is no chat account: the
+ # platform has said nothing about who holds the Slack account.
+ code = await _code_for(world, world.ada)
+
+ await _link(world, code, world.member_chat)
+
+ assert await _claimants(world) == []
+ assert "Only a chat account" in world.replies[0]
+
+ async def test_a_wrong_code_links_nothing(self, world: _World) -> None:
+ await _code_for(world, world.ada)
+
+ await _link(world, "ABCD-EFGH", world.ada_chat)
+
+ assert await _claimants(world) == []
+ assert "doesn't match" in world.replies[0]
+
+ async def test_no_code_gets_the_usage(self, world: _World) -> None:
+ await _link(world, " ", world.ada_chat)
+
+ assert world.replies[0].startswith("Usage:")
+
+
+class TestUnlinkAccount:
+ async def _link_both(self, world: _World) -> None:
+ async with world.session_factory() as session:
+ session.add(
+ ExternalUserClaim(
+ external_user_id=world.ada_account.id, user_id=world.bob
+ )
+ )
+ await session.commit()
+ await _link(world, await _code_for(world, world.ada), world.ada_chat)
+ world.replies.clear()
+
+ async def test_without_a_name_it_lists_the_links(self, world: _World) -> None:
+ await self._link_both(world)
+
+ await _unlink(world, "", world.ada_chat)
+
+ assert "- **ada**\n" in world.replies[0]
+ assert "- **bob** (made before links needed confirming)" in world.replies[0]
+
+ async def test_it_removes_only_the_named_link(self, world: _World) -> None:
+ await self._link_both(world)
+
+ await _unlink(world, "bob", world.ada_chat)
+
+ assert await _claimants(world) == [world.ada]
+ assert world.replies[0] == "Unlinked this account from Switch user **bob**."
+ async with world.session_factory() as session:
+ event = await session.scalar(
+ select(AuditEvent).where(
+ AuditEvent.action == AuditAction.BRIDGE_IDENTITY_RELEASED
+ )
+ )
+ assert event is not None
+ assert event.actor_user_id is None
+ assert event.details == {
+ "bridge_id": world.ada_account.bridge_id,
+ "user_id": world.bob,
+ "by": "chat_account",
+ }
+
+ async def test_a_link_can_be_named_by_email(self, world: _World) -> None:
+ await self._link_both(world)
+
+ await _unlink(world, "BOB@test", world.ada_chat)
+
+ assert await _claimants(world) == [world.ada]
+
+ async def test_another_account_cannot_unlink_it(self, world: _World) -> None:
+ await self._link_both(world)
+
+ await _unlink(world, "bob", world.bystander_chat)
+
+ assert await _claimants(world) == sorted([world.ada, world.bob])
+ assert "isn't linked to a Switch user called" in world.replies[0]
+
+ async def test_an_unknown_name_says_what_it_is_linked_to(
+ self, world: _World
+ ) -> None:
+ await self._link_both(world)
+
+ await _unlink(world, "carol", world.ada_chat)
+
+ assert await _claimants(world) == sorted([world.ada, world.bob])
+ assert "**carol**" in world.replies[0]
+ assert "- **bob**" in world.replies[0]
+
+ async def test_a_message_from_console_cannot_unlink(self, world: _World) -> None:
+ await self._link_both(world)
+
+ await _unlink(world, "bob", world.member_chat)
+
+ assert await _claimants(world) == sorted([world.ada, world.bob])
+ assert "Only a chat account" in world.replies[0]
diff --git a/core/tests/switch_core/bridges/collaboration/test_link_code_instructions.py b/core/tests/switch_core/bridges/collaboration/test_link_code_instructions.py
new file mode 100644
index 000000000..a6ebdb80e
--- /dev/null
+++ b/core/tests/switch_core/bridges/collaboration/test_link_code_instructions.py
@@ -0,0 +1,54 @@
+"""Each platform says how to post a link code where Switch will hear it
+(CHOO-3881)."""
+
+from __future__ import annotations
+
+from switch_core.bridges.collaboration.adapter import PlatformAdapter
+from switch_core.bridges.collaboration.discord.adapter import DiscordAdapter
+from switch_core.bridges.collaboration.mattermost.adapter import MattermostAdapter
+from switch_core.bridges.collaboration.slack.adapter import SlackAdapter
+from switch_core.bridges.collaboration.teams.adapter import TeamsAdapter
+from switch_core.bridges.collaboration.telegram.adapter import TelegramAdapter
+
+_CODE = "7KQ2-M9XD"
+
+
+def test_the_default_is_the_typed_command() -> None:
+ text = PlatformAdapter.link_code_instructions(_CODE, {})
+ assert f"`!link-account {_CODE}`" in text
+
+
+def test_slack_uses_the_typed_command() -> None:
+ # Slack apps set up before the slash command existed do not have it.
+ assert "`!link-account" in SlackAdapter.link_code_instructions(_CODE, {})
+ assert "/link-account" not in SlackAdapter.link_code_instructions(_CODE, {})
+
+
+def test_mattermost_needs_a_channel_with_an_agent_and_says_what_to_do_without_one() -> (
+ None
+):
+ text = MattermostAdapter.link_code_instructions(_CODE, {})
+ assert "channel that has a Switch agent in it" in text
+ assert "No agent yet? Add one first, then get a new code here." in text
+
+
+def test_the_shared_discord_connection_takes_only_the_slash_command() -> None:
+ shared = DiscordAdapter.link_code_instructions(_CODE, {"event_delivery": "shared"})
+ own = DiscordAdapter.link_code_instructions(
+ _CODE, {"event_delivery": "own_connection"}
+ )
+ assert f"`/link-account code:{_CODE}`" in shared
+ assert "!link-account" not in shared
+ assert f"`!link-account {_CODE}`" in own
+
+
+def test_teams_mentions_the_app() -> None:
+ text = TeamsAdapter.link_code_instructions(_CODE, {})
+ assert "@mention the Switch app" in text
+ assert f"`link-account {_CODE}`" in text
+
+
+def test_telegram_uses_its_command_spelling() -> None:
+ assert f"`/link_account {_CODE}`" in TelegramAdapter.link_code_instructions(
+ _CODE, {}
+ )
diff --git a/core/tests/switch_core/bridges/collaboration/test_mattermost_webhook_posts.py b/core/tests/switch_core/bridges/collaboration/test_mattermost_webhook_posts.py
new file mode 100644
index 000000000..5ca154f55
--- /dev/null
+++ b/core/tests/switch_core/bridges/collaboration/test_mattermost_webhook_posts.py
@@ -0,0 +1,125 @@
+"""A Mattermost webhook's posts are the integration's, not its creator's
+(CHOO-3881).
+
+Mattermost files an incoming webhook's post under the user id of whoever made
+the webhook, though anyone holding its URL may have sent it. Credited to that
+person, it could confirm or remove their links and speak to their agents as
+them, so it goes under a stand-in instead.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import json
+from typing import Any
+
+from switch_core.bridges.collaboration.mattermost.adapter import (
+ MattermostAdapter,
+ MattermostConnectionConfig,
+)
+from switch_core.bridges.collaboration.models import InboundCommand, InboundMessage
+
+_CREATOR = "creator-user-id"
+
+
+class _Users:
+ def get_user(self, user_id: str) -> dict[str, str]:
+ if user_id != _CREATOR:
+ raise AssertionError(f"looked up {user_id!r}, not a Mattermost user")
+ return {"id": _CREATOR, "username": "ada"}
+
+
+def _adapter() -> tuple[MattermostAdapter, list[Any]]:
+ adapter = MattermostAdapter(
+ config=MattermostConnectionConfig(
+ url="http://mm",
+ admin_user="admin",
+ admin_password="pw",
+ team_name="team",
+ )
+ )
+ adapter._admin_driver = type("_Driver", (), {"users": _Users()})() # type: ignore[assignment]
+ received: list[Any] = []
+
+ async def record(event: Any) -> None:
+ received.append(event)
+
+ adapter._on_message = record
+ adapter._on_command = record
+ return adapter, received
+
+
+def _deliver(adapter: MattermostAdapter, post: dict[str, Any]) -> None:
+ loop = asyncio.new_event_loop()
+ dispatched: list[Any] = []
+ adapter._main_loop = loop
+ adapter._dispatch = lambda coro, _loop: dispatched.append(coro) # type: ignore[method-assign]
+ event = {
+ "event": "posted",
+ "data": {"post": json.dumps(post), "channel_type": "O"},
+ }
+ try:
+ loop.run_until_complete(adapter._ws_handler(json.dumps(event), "some-agent"))
+ for coro in dispatched:
+ loop.run_until_complete(coro)
+ finally:
+ loop.close()
+
+
+def _post(message: str, **props: str) -> dict[str, Any]:
+ return {
+ "id": f"post-{message}",
+ "user_id": _CREATOR,
+ "channel_id": "channel-1",
+ "message": message,
+ "props": props,
+ }
+
+
+def test_a_persons_own_post_is_theirs() -> None:
+ adapter, received = _adapter()
+
+ _deliver(adapter, _post("hello"))
+
+ [message] = received
+ assert isinstance(message, InboundMessage)
+ assert (message.sender_id, message.sender_name) == (_CREATOR, "ada")
+
+
+def test_a_webhook_post_goes_under_a_stand_in_not_its_creator() -> None:
+ adapter, received = _adapter()
+
+ _deliver(
+ adapter, _post("build failed", from_webhook="true", override_username="ci")
+ )
+
+ [message] = received
+ assert isinstance(message, InboundMessage)
+ assert message.sender_id == f"webhook:{_CREATOR}"
+ assert message.sender_name == "ci (webhook)"
+
+
+def test_a_command_from_a_webhook_is_not_the_creators() -> None:
+ adapter, received = _adapter()
+
+ _deliver(adapter, _post("!unlink-account ada", from_webhook="true"))
+
+ [command] = received
+ assert isinstance(command, InboundCommand)
+ assert command.command == "unlink-account"
+ assert command.sender_id == f"webhook:{_CREATOR}"
+ assert command.sender_name == "webhook"
+
+
+def test_the_stand_in_cannot_be_linked() -> None:
+ assert MattermostAdapter.unlinkable_account_reason(f"webhook:{_CREATOR}")
+ assert MattermostAdapter.unlinkable_account_reason(_CREATOR) is None
+
+
+def test_the_stand_in_is_never_mentioned() -> None:
+ adapter, _received = _adapter()
+ loop = asyncio.new_event_loop()
+ try:
+ assert loop.run_until_complete(adapter._mention(f"webhook:{_CREATOR}")) is None
+ finally:
+ loop.close()
diff --git a/core/tests/switch_core/bridges/collaboration/test_unlinkable_accounts.py b/core/tests/switch_core/bridges/collaboration/test_unlinkable_accounts.py
new file mode 100644
index 000000000..bedd4f20b
--- /dev/null
+++ b/core/tests/switch_core/bridges/collaboration/test_unlinkable_accounts.py
@@ -0,0 +1,33 @@
+"""Accounts several people post as cannot be linked to one Switch user
+(CHOO-3881)."""
+
+from __future__ import annotations
+
+import pytest
+
+from switch_core.bridges.collaboration.adapter import PlatformAdapter
+from switch_core.bridges.collaboration.slack.adapter import SlackAdapter
+from switch_core.bridges.collaboration.telegram.adapter import TelegramAdapter
+
+
[email protected]("account", ["1087968824", "136817688", "777000"])
+def test_telegram_stand_ins_are_refused(account: str) -> None:
+ assert TelegramAdapter.unlinkable_account_reason(account) is not None
+
+
+def test_a_telegram_person_can_be_linked() -> None:
+ assert TelegramAdapter.unlinkable_account_reason("424242") is None
+
+
[email protected]("account", ["B0123ABCD", "USLACKBOT"])
+def test_slack_apps_and_bots_are_refused(account: str) -> None:
+ assert SlackAdapter.unlinkable_account_reason(account) is not None
+
+
[email protected]("account", ["U0123ABCD", "W0123ABCD"])
+def test_a_slack_person_can_be_linked(account: str) -> None:
+ assert SlackAdapter.unlinkable_account_reason(account) is None
+
+
+def test_by_default_any_account_can_be_linked() -> None:
+ assert PlatformAdapter.unlinkable_account_reason("anyone") is None
diff --git a/core/tests/switch_core/db/stores/test_external_user_claims.py b/core/tests/switch_core/db/stores/test_external_user_claims.py
index 514a62928..ad41d2927 100644
--- a/core/tests/switch_core/db/stores/test_external_user_claims.py
+++ b/core/tests/switch_core/db/stores/test_external_user_claims.py
@@ -1,28 +1,54 @@
-"""Claiming a platform identity is non-exclusive (CHOO-2137).
+"""Claiming a platform identity is non-exclusive (CHOO-2137), and takes the
+account's own confirmation (CHOO-3881).
Several Switch users may claim the same messaging account. An exclusive claim
would let whoever got there first keep the real person from ever being
recognised by their own agents, so the store records claims as a set rather
than as a single owner column on `external_users`.
+
+A claim is only written once the account confirms it, by posting the code its
+Switch user was shown; until then it is a link request, which nothing trusts.
"""
from __future__ import annotations
import uuid
+from datetime import UTC, datetime, timedelta
+import pytest
+from sqlalchemy import delete, select
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
from switch_core.db.models import (
+ TENANT_ZERO_ID,
Client,
CollaborationBridge,
ExternalUser,
+ ExternalUserClaim,
+ ExternalUserLinkRequest,
+ TenantMember,
User,
)
-from switch_core.db.stores.external_user_store import ExternalUserStore
+from switch_core.db.stores.external_user_store import (
+ ExternalUserStore,
+ LinkRelease,
+ NoSuchLink,
+)
+from switch_core.db.stores.user_store import UserStore
_STORE = ExternalUserStore()
+async def _claim(
+ session: AsyncSession, external_user: ExternalUser, user_id: str
+) -> None:
+ """A confirmed claim, the only kind the store writes."""
+ request = await _STORE.request_link(
+ session, external_user, user_id, requested_by_user_id=user_id
+ )
+ await _STORE.confirm_link_request(session, request)
+
+
async def _make_client(session: AsyncSession, *, client_type: str) -> str:
client = Client(
transport_user_id=f"@{client_type}-{uuid.uuid4().hex[:8]}:test",
@@ -69,6 +95,9 @@ async def _make_user(session: AsyncSession, *, name: str) -> str:
)
session.add(user)
await session.flush()
+ # A code only confirms a link for a member of the workspace.
+ session.add(TenantMember(tenant_id=TENANT_ZERO_ID, user_id=user.id, role="member"))
+ await session.flush()
return user.id
@@ -82,8 +111,8 @@ class TestClaimIsNonExclusive:
first = await _make_user(session, name="first")
second = await _make_user(session, name="second")
- await _STORE.claim(session, external_user, first)
- await _STORE.claim(session, external_user, second)
+ await _claim(session, external_user, first)
+ await _claim(session, external_user, second)
await session.commit()
async with session_factory() as session:
@@ -100,8 +129,8 @@ class TestClaimIsNonExclusive:
external_user = await _make_external_user(session, bridge_id=bridge_id)
user_id = await _make_user(session, name="repeat")
- await _STORE.claim(session, external_user, user_id)
- await _STORE.claim(session, external_user, user_id)
+ await _claim(session, external_user, user_id)
+ await _claim(session, external_user, user_id)
await session.commit()
async with session_factory() as session:
@@ -130,8 +159,8 @@ class TestRelease:
external_user = await _make_external_user(session, bridge_id=bridge_id)
leaving = await _make_user(session, name="leaving")
staying = await _make_user(session, name="staying")
- await _STORE.claim(session, external_user, leaving)
- await _STORE.claim(session, external_user, staying)
+ await _claim(session, external_user, leaving)
+ await _claim(session, external_user, staying)
await session.commit()
async with session_factory() as session:
@@ -141,7 +170,7 @@ class TestRelease:
async with session_factory() as session:
assert await _STORE.claimant_ids(session, external_user.id) == [staying]
- async def test_releasing_a_claim_that_was_never_made_is_a_no_op(
+ async def test_releasing_a_claim_that_was_never_made_says_so(
self, session_factory: async_sessionmaker[AsyncSession]
) -> None:
async with session_factory() as session:
@@ -149,12 +178,12 @@ class TestRelease:
external_user = await _make_external_user(session, bridge_id=bridge_id)
holder = await _make_user(session, name="holder")
stranger = await _make_user(session, name="stranger")
- await _STORE.claim(session, external_user, holder)
+ await _claim(session, external_user, holder)
await session.commit()
async with session_factory() as session:
- await _STORE.release(session, external_user, stranger)
- await session.commit()
+ with pytest.raises(NoSuchLink):
+ await _STORE.release(session, external_user, stranger)
async with session_factory() as session:
assert await _STORE.claimant_ids(session, external_user.id) == [holder]
@@ -166,9 +195,9 @@ class TestRelease:
bridge_id = await _make_bridge(session)
external_user = await _make_external_user(session, bridge_id=bridge_id)
user_id = await _make_user(session, name="returning")
- await _STORE.claim(session, external_user, user_id)
+ await _claim(session, external_user, user_id)
await _STORE.release(session, external_user, user_id)
- await _STORE.claim(session, external_user, user_id)
+ await _claim(session, external_user, user_id)
await session.commit()
async with session_factory() as session:
@@ -192,9 +221,9 @@ class TestGetByUser:
)
me = await _make_user(session, name="me")
them = await _make_user(session, name="them")
- await _STORE.claim(session, mine_a, me)
- await _STORE.claim(session, mine_b, me)
- await _STORE.claim(session, theirs, them)
+ await _claim(session, mine_a, me)
+ await _claim(session, mine_b, me)
+ await _claim(session, theirs, them)
await session.commit()
async with session_factory() as session:
@@ -209,8 +238,8 @@ class TestGetByUser:
shared = await _make_external_user(session, bridge_id=bridge_id)
first = await _make_user(session, name="first")
second = await _make_user(session, name="second")
- await _STORE.claim(session, shared, first)
- await _STORE.claim(session, shared, second)
+ await _claim(session, shared, first)
+ await _claim(session, shared, second)
await session.commit()
async with session_factory() as session:
@@ -234,7 +263,7 @@ class TestGetByUser:
assert await _STORE.get_by_user(session, nobody) == []
-class TestClaimantIdsFor:
+class TestClaimsFor:
async def test_batches_claims_by_identity(
self, session_factory: async_sessionmaker[AsyncSession]
) -> None:
@@ -251,17 +280,19 @@ class TestClaimantIdsFor:
)
first = await _make_user(session, name="first")
second = await _make_user(session, name="second")
- await _STORE.claim(session, shared, first)
- await _STORE.claim(session, shared, second)
- await _STORE.claim(session, solo, first)
+ await _claim(session, shared, first)
+ await _claim(session, shared, second)
+ await _claim(session, solo, first)
await session.commit()
async with session_factory() as session:
- claims = await _STORE.claimant_ids_for(
+ claims = await _STORE.claims_for(
session, [shared.id, solo.id, unclaimed.id]
)
- assert sorted(claims[shared.id]) == sorted([first, second])
- assert claims[solo.id] == [first]
+ assert sorted(c.user_id for c in claims[shared.id]) == sorted(
+ [first, second]
+ )
+ assert [c.user_id for c in claims[solo.id]] == [first]
# An unclaimed identity is absent rather than mapped to []: callers
# read it with .get(id, []).
assert unclaimed.id not in claims
@@ -278,20 +309,310 @@ class TestClaimantIdsFor:
session, bridge_id=bridge_id, username="other"
)
user_id = await _make_user(session, name="claimant")
- await _STORE.claim(session, asked, user_id)
- await _STORE.claim(session, other, user_id)
+ await _claim(session, asked, user_id)
+ await _claim(session, other, user_id)
await session.commit()
async with session_factory() as session:
- assert await _STORE.claimant_ids_for(session, [asked.id]) == {
- asked.id: [user_id]
- }
+ claims = await _STORE.claims_for(session, [asked.id])
+ assert list(claims) == [asked.id]
+ assert [c.user_id for c in claims[asked.id]] == [user_id]
async def test_empty_input_short_circuits(
self, session_factory: async_sessionmaker[AsyncSession]
) -> None:
async with session_factory() as session:
- assert await _STORE.claimant_ids_for(session, []) == {}
+ assert await _STORE.claims_for(session, []) == {}
+
+
+class TestLinkRequests:
+ async def test_a_request_is_trusted_by_nothing(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ async with session_factory() as session:
+ bridge_id = await _make_bridge(session)
+ account = await _make_external_user(session, bridge_id=bridge_id)
+ user_id = await _make_user(session, name="asker")
+ request = await _STORE.request_link(
+ session, account, user_id, requested_by_user_id=user_id
+ )
+ await _STORE.issue_link_code(session, request)
+ await session.commit()
+
+ async with session_factory() as session:
+ assert await _STORE.claimant_ids(session, account.id) == []
+ assert await _STORE.get_by_user(session, user_id) == []
+ assert [
+ (ext.id, req.user_id)
+ for ext, req in await _STORE.link_requests_of_user(session, user_id)
+ ] == [(account.id, user_id)]
+
+ async def test_the_code_from_its_own_account_confirms_the_link(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ async with session_factory() as session:
+ bridge_id = await _make_bridge(session)
+ account = await _make_external_user(session, bridge_id=bridge_id)
+ user_id = await _make_user(session, name="asker")
+ request = await _STORE.request_link(
+ session, account, user_id, requested_by_user_id=user_id
+ )
+ code, _expires = await _STORE.issue_link_code(session, request)
+ await session.commit()
+
+ async with session_factory() as session:
+ # Typed the way a person might: lower case, no hyphen, O for 0.
+ typed = code.replace("-", "").lower().replace("0", "o")
+ confirmed = await _STORE.redeem_link_code(
+ session, account, typed, UserStore()
+ )
+ assert confirmed is not None
+ assert confirmed.user_id == user_id
+ await session.commit()
+
+ async with session_factory() as session:
+ assert await _STORE.claimant_ids(session, account.id) == [user_id]
+ claim = await _STORE.get_claim(session, account.id, user_id)
+ assert claim is not None
+ assert claim.verified_at is not None
+ assert await _STORE.get_link_request(session, account.id, user_id) is None
+
+ async def test_a_code_is_single_use(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ async with session_factory() as session:
+ bridge_id = await _make_bridge(session)
+ account = await _make_external_user(session, bridge_id=bridge_id)
+ user_id = await _make_user(session, name="asker")
+ request = await _STORE.request_link(
+ session, account, user_id, requested_by_user_id=user_id
+ )
+ code, _expires = await _STORE.issue_link_code(session, request)
+ assert (
+ await _STORE.redeem_link_code(session, account, code, UserStore())
+ is not None
+ )
+ await _STORE.release(session, account, user_id)
+ await session.commit()
+
+ async with session_factory() as session:
+ assert (
+ await _STORE.redeem_link_code(session, account, code, UserStore())
+ is None
+ )
+ assert await _STORE.claimant_ids(session, account.id) == []
+
+ async def test_the_code_from_another_account_confirms_nothing(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ # Somebody else posting the code, having seen it in a channel, is the
+ # case that makes posting it in a channel safe.
+ async with session_factory() as session:
+ bridge_id = await _make_bridge(session)
+ account = await _make_external_user(session, bridge_id=bridge_id)
+ bystander = await _make_external_user(
+ session, bridge_id=bridge_id, username="bystander"
+ )
+ user_id = await _make_user(session, name="asker")
+ request = await _STORE.request_link(
+ session, account, user_id, requested_by_user_id=user_id
+ )
+ code, _expires = await _STORE.issue_link_code(session, request)
+ await session.commit()
+
+ async with session_factory() as session:
+ assert (
+ await _STORE.redeem_link_code(session, bystander, code, UserStore())
+ is None
+ )
+ await session.commit()
+
+ async with session_factory() as session:
+ assert await _STORE.claimant_ids(session, account.id) == []
+ assert await _STORE.claimant_ids(session, bystander.id) == []
+ assert await _STORE.get_link_request(session, account.id, user_id)
+
+ async def test_an_expired_code_confirms_nothing(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ async with session_factory() as session:
+ bridge_id = await _make_bridge(session)
+ account = await _make_external_user(session, bridge_id=bridge_id)
+ user_id = await _make_user(session, name="asker")
+ request = await _STORE.request_link(
+ session, account, user_id, requested_by_user_id=user_id
+ )
+ code, _expires = await _STORE.issue_link_code(session, request)
+ request.code_expires_at = datetime.now(UTC) - timedelta(seconds=1)
+ await session.commit()
+
+ async with session_factory() as session:
+ assert (
+ await _STORE.redeem_link_code(session, account, code, UserStore())
+ is None
+ )
+ assert await _STORE.claimant_ids(session, account.id) == []
+
+ async def test_a_new_code_replaces_the_old_one(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ async with session_factory() as session:
+ bridge_id = await _make_bridge(session)
+ account = await _make_external_user(session, bridge_id=bridge_id)
+ user_id = await _make_user(session, name="asker")
+ request = await _STORE.request_link(
+ session, account, user_id, requested_by_user_id=user_id
+ )
+ old, _expires = await _STORE.issue_link_code(session, request)
+ new, _expires = await _STORE.issue_link_code(session, request)
+ await session.commit()
+
+ async with session_factory() as session:
+ assert (
+ await _STORE.redeem_link_code(session, account, old, UserStore())
+ is None
+ )
+ assert (
+ await _STORE.redeem_link_code(session, account, new, UserStore())
+ is not None
+ )
+
+ async def test_text_that_cannot_be_a_code_confirms_nothing(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ async with session_factory() as session:
+ bridge_id = await _make_bridge(session)
+ account = await _make_external_user(session, bridge_id=bridge_id)
+ user_id = await _make_user(session, name="asker")
+ # A request with no code yet, as an admin leaves one.
+ await _STORE.request_link(
+ session, account, user_id, requested_by_user_id=user_id
+ )
+ await session.commit()
+
+ async with session_factory() as session:
+ for text in ("", "hello", "@ABCD-EFGH", "ABCD-EFGH-JKMN"):
+ assert (
+ await _STORE.redeem_link_code(session, account, text, UserStore())
+ is None
+ )
+
+ async def test_confirming_upgrades_an_unverified_claim(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ # A claim from before links needed confirming keeps working, and
+ # confirming it marks it verified in place rather than adding a row.
+ async with session_factory() as session:
+ bridge_id = await _make_bridge(session)
+ account = await _make_external_user(session, bridge_id=bridge_id)
+ user_id = await _make_user(session, name="old-timer")
+ session.add(ExternalUserClaim(external_user_id=account.id, user_id=user_id))
+ await session.flush()
+ request = await _STORE.request_link(
+ session, account, user_id, requested_by_user_id=user_id
+ )
+ code, _expires = await _STORE.issue_link_code(session, request)
+ await session.commit()
+
+ async with session_factory() as session:
+ assert (
+ await _STORE.redeem_link_code(session, account, code, UserStore())
+ is not None
+ )
+ await session.commit()
+
+ async with session_factory() as session:
+ rows = (
+ await session.scalars(
+ select(ExternalUserClaim).where(
+ ExternalUserClaim.external_user_id == account.id
+ )
+ )
+ ).all()
+ assert [(r.user_id, r.verified_at is not None) for r in rows] == [
+ (user_id, True)
+ ]
+
+ async def test_asking_again_keeps_the_waiting_code(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ # A second "This is me" must not invalidate a code someone is already
+ # about to post; only asking for a new code does.
+ async with session_factory() as session:
+ bridge_id = await _make_bridge(session)
+ account = await _make_external_user(session, bridge_id=bridge_id)
+ user_id = await _make_user(session, name="asker")
+ admin_id = await _make_user(session, name="admin")
+ request = await _STORE.request_link(
+ session, account, user_id, requested_by_user_id=user_id
+ )
+ code, _expires = await _STORE.issue_link_code(session, request)
+ again = await _STORE.request_link(
+ session, account, user_id, requested_by_user_id=admin_id
+ )
+ assert again.requested_by_user_id == admin_id
+ await session.commit()
+
+ async with session_factory() as session:
+ assert (
+ await _STORE.redeem_link_code(session, account, code, UserStore())
+ is not None
+ )
+
+ async def test_release_cancels_a_waiting_request(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ async with session_factory() as session:
+ bridge_id = await _make_bridge(session)
+ account = await _make_external_user(session, bridge_id=bridge_id)
+ user_id = await _make_user(session, name="asker")
+ request = await _STORE.request_link(
+ session, account, user_id, requested_by_user_id=user_id
+ )
+ code, _expires = await _STORE.issue_link_code(session, request)
+ await session.commit()
+
+ async with session_factory() as session:
+ assert await _STORE.release(session, account, user_id) == LinkRelease(
+ claim=False, request=True
+ )
+ await session.commit()
+
+ async with session_factory() as session:
+ with pytest.raises(NoSuchLink):
+ await _STORE.release(session, account, user_id)
+ assert (
+ await _STORE.redeem_link_code(session, account, code, UserStore())
+ is None
+ )
+
+ async def test_deleting_the_switch_user_drops_their_requests(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ async with session_factory() as session:
+ bridge_id = await _make_bridge(session)
+ account = await _make_external_user(session, bridge_id=bridge_id)
+ user_id = await _make_user(session, name="leaving")
+ await _STORE.request_link(
+ session, account, user_id, requested_by_user_id=user_id
+ )
+ await session.commit()
+
+ async with session_factory() as session:
+ await session.execute(
+ delete(TenantMember).where(TenantMember.user_id == user_id)
+ )
+ await session.delete(await session.get(User, user_id))
+ await session.commit()
+
+ async with session_factory() as session:
+ assert (
+ await session.scalars(
+ select(ExternalUserLinkRequest).where(
+ ExternalUserLinkRequest.external_user_id == account.id
+ )
+ )
+ ).all() == []
class TestClaimsAreCascaded:
@@ -305,11 +626,14 @@ class TestClaimsAreCascaded:
external_user = await _make_external_user(session, bridge_id=bridge_id)
leaving = await _make_user(session, name="leaving")
staying = await _make_user(session, name="staying")
- await _STORE.claim(session, external_user, leaving)
- await _STORE.claim(session, external_user, staying)
+ await _claim(session, external_user, leaving)
+ await _claim(session, external_user, staying)
await session.commit()
async with session_factory() as session:
+ await session.execute(
+ delete(TenantMember).where(TenantMember.user_id == leaving)
+ )
await session.delete(await session.get(User, leaving))
await session.commit()
@@ -325,7 +649,7 @@ class TestClaimsAreCascaded:
bridge_id = await _make_bridge(session)
external_user = await _make_external_user(session, bridge_id=bridge_id)
user_id = await _make_user(session, name="claimant")
- await _STORE.claim(session, external_user, user_id)
+ await _claim(session, external_user, user_id)
await session.commit()
async with session_factory() as session:
diff --git a/core/tests/switch_core/gateway/test_claim_identity_membership.py b/core/tests/switch_core/gateway/test_claim_identity_membership.py
index cd77418a2..0b49ed7f9 100644
--- a/core/tests/switch_core/gateway/test_claim_identity_membership.py
+++ b/core/tests/switch_core/gateway/test_claim_identity_membership.py
@@ -4,7 +4,8 @@
this tenant has any business recognising. The claim decides who an account is
treated as inside the tenant — owner-only addressing reads it — so the target
must be a member, and a non-member gets the same 404 as an id that does not
-exist.
+exist. Either way the link only waits for the account to confirm it
+(CHOO-3881); nobody is recognised by it yet.
"""
from __future__ import annotations
@@ -34,6 +35,21 @@ from switch_core.gateway.schemas import ClaimIdentityRequest
_EXTERNAL_USERS = ExternalUserStore()
+class _Lifecycle:
+ """The bridge-type questions a claim asks, for a platform with no
+ stand-in accounts."""
+
+ def unlinkable_account_reason(
+ self, _bridge_type: str, _external_user_id: str
+ ) -> None:
+ return None
+
+ def link_code_instructions(
+ self, _bridge_type: str, _connection_config: object, code: str
+ ) -> str:
+ return f"Post `!link-account {code}`."
+
+
async def _make_client(session: AsyncSession, client_type: str) -> str:
client = Client(
transport_user_id=f"@{client_type}-{uuid.uuid4().hex[:8]}:test",
@@ -99,12 +115,13 @@ async def _claim(
external_user_id=external_user.external_user_id,
username=external_user.external_username,
user_id=target_user_id,
+ expects_confirmation=True,
),
session,
CollaborationBridgeStore(),
_EXTERNAL_USERS,
UserStore(),
- None, # type: ignore[arg-type]
+ _Lifecycle(), # type: ignore[arg-type]
caller,
True,
)
@@ -127,14 +144,20 @@ async def test_admin_cannot_claim_an_identity_for_another_tenants_user(
assert refused.value.status_code == 404
async with session_factory() as session:
assert await _EXTERNAL_USERS.claimant_ids(session, external_user.id) == []
+ assert (
+ await _EXTERNAL_USERS.get_link_request(
+ session, external_user.id, outsider.id
+ )
+ is None
+ )
-async def test_admin_can_claim_an_identity_for_a_member(
+async def test_admin_can_start_linking_an_identity_to_a_member(
session_factory: async_sessionmaker[AsyncSession],
) -> None:
bridge_id, external_user, admin, member, _outsider = await _setup(session_factory)
- await _claim(
+ summary = await _claim(
session_factory,
bridge_id=bridge_id,
external_user=external_user,
@@ -142,10 +165,18 @@ async def test_admin_can_claim_an_identity_for_a_member(
target_user_id=member.id,
)
+ # The admin never sees the code: the member gets their own.
+ assert summary.link_request is not None # type: ignore[attr-defined]
+ assert summary.link_request.user_id == member.id # type: ignore[attr-defined]
+ assert summary.link_request.code is None # type: ignore[attr-defined]
async with session_factory() as session:
- assert await _EXTERNAL_USERS.claimant_ids(session, external_user.id) == [
- member.id
- ]
+ assert await _EXTERNAL_USERS.claimant_ids(session, external_user.id) == []
+ request = await _EXTERNAL_USERS.get_link_request(
+ session, external_user.id, member.id
+ )
+ assert request is not None
+ assert request.requested_by_user_id == admin.id
+ assert request.code_hash is None
class _ProvisioningLifecycle:
@@ -168,6 +199,16 @@ class _ProvisioningLifecycle:
def get(self, _bridge_id: str) -> _ProvisioningLifecycle:
return self
+ def unlinkable_account_reason(
+ self, _bridge_type: str, _external_user_id: str
+ ) -> None:
+ return None
+
+ def link_code_instructions(
+ self, _bridge_type: str, _connection_config: object, code: str
+ ) -> str:
+ return f"Post `!link-account {code}`."
+
async def search_directory_users(self, _query: str) -> list[DirectoryUser]:
return [
DirectoryUser(
@@ -193,7 +234,7 @@ class _ProvisioningLifecycle:
return external_user
-async def test_claiming_an_account_switch_has_not_seen_links_it_to_the_caller(
+async def test_claiming_an_account_switch_has_not_seen_starts_linking_it(
session_factory: async_sessionmaker[AsyncSession],
) -> None:
# What a fresh deployment does on its first run: the seeded admin claims
@@ -205,9 +246,11 @@ async def test_claiming_an_account_switch_has_not_seen_links_it_to_the_caller(
async with session_factory() as session:
caller = await session.get(User, admin.id)
assert caller is not None
- await claim_bridge_identity(
+ summary = await claim_bridge_identity(
bridge_id,
- ClaimIdentityRequest(external_user_id=unseen, username="user"),
+ ClaimIdentityRequest(
+ external_user_id=unseen, username="user", expects_confirmation=True
+ ),
session,
CollaborationBridgeStore(),
_EXTERNAL_USERS,
@@ -222,4 +265,7 @@ async def test_claiming_an_account_switch_has_not_seen_links_it_to_the_caller(
session, bridge_id, unseen
)
assert provisioned is not None
- assert await _EXTERNAL_USERS.claimant_ids(session, provisioned.id) == [admin.id]
+ assert await _EXTERNAL_USERS.claimant_ids(session, provisioned.id) == []
+ assert await _EXTERNAL_USERS.get_link_request(session, provisioned.id, admin.id)
+ assert summary.link_request is not None
+ assert summary.link_request.code is not None
diff --git a/core/tests/switch_core/gateway/test_collaborations_authz.py b/core/tests/switch_core/gateway/test_collaborations_authz.py
index e86ca7927..89793e48f 100644
--- a/core/tests/switch_core/gateway/test_collaborations_authz.py
+++ b/core/tests/switch_core/gateway/test_collaborations_authz.py
@@ -82,12 +82,15 @@ WRITE_METHODS = {"POST", "PATCH", "PUT", "DELETE"}
# scope to: the row it mutates is a link between a platform account and one
# Switch user, not part of the bridge itself, and a user must be able to claim
# their own without an admin. These routes carry a self-or-admin check inside
-# the handler instead — asserted by
-# `test_owner_scoped_identity_routes_check_self_or_admin` below, so the
-# exemption cannot hide an unauthorized route.
+# the handler instead — asserted by `TestIdentityRoutesAreSelfOrAdmin` below,
+# so the exemption cannot hide an unauthorized route. Confirming a link
+# (CHOO-3881) takes no user at all: it only ever acts for the caller.
_OWNER_SCOPED_PATHS = {
"/{bridge_id}/identities",
"/{bridge_id}/identities/{external_user_row_id}",
+ "/{bridge_id}/identities/{external_user_row_id}/code",
+ "/{bridge_id}/identities/{external_user_row_id}/request",
+ "/{bridge_id}/identities/{external_user_row_id}/verify-session",
}
@@ -131,6 +134,7 @@ class TestIdentityRoutesAreSelfOrAdmin:
external_user_id="U123",
username="them",
user_id="someone-else",
+ expects_confirmation=True,
),
session=object(), # type: ignore[arg-type]
bridge_store=_StubGet(object()), # type: ignore[arg-type]
diff --git a/core/tests/switch_core/gateway/test_directory_fallback.py b/core/tests/switch_core/gateway/test_directory_fallback.py
index c4af87eb1..2b5232b61 100644
--- a/core/tests/switch_core/gateway/test_directory_fallback.py
+++ b/core/tests/switch_core/gateway/test_directory_fallback.py
@@ -68,9 +68,9 @@ class _StubExternalUserStore:
) -> list[SimpleNamespace]:
return self._rows
- async def claimant_ids_for(
+ async def claims_for(
self, _session: object, _row_ids: list[str]
- ) -> dict[str, list[str]]:
+ ) -> dict[str, list[object]]:
return {}
diff --git a/core/tests/switch_core/gateway/test_held_connections.py b/core/tests/switch_core/gateway/test_held_connections.py
index 678de0c37..5296a8a1b 100644
--- a/core/tests/switch_core/gateway/test_held_connections.py
+++ b/core/tests/switch_core/gateway/test_held_connections.py
@@ -179,6 +179,11 @@ class _CollabLifecycle:
def supports_directory_search(self, bridge_type: str) -> bool:
return True
+ def unlinkable_account_reason(
+ self, bridge_type: str, external_user_id: str
+ ) -> str | None:
+ return None
+
def receives_webhooks(self, bridge_type: str) -> bool:
return False
@@ -569,7 +574,11 @@ class TestBridgeRoutes:
)
claimed = await client.post(
f"/bridges/{bridge.id}/identities",
- json={"external_user_id": "U1", "username": "ada"},
+ json={
+ "external_user_id": "U1",
+ "username": "ada",
+ "expects_confirmation": True,
+ },
)
deleted = await client.delete(f"/bridges/{bridge.id}")
diff --git a/core/tests/switch_core/gateway/test_identity_link_confirmation.py b/core/tests/switch_core/gateway/test_identity_link_confirmation.py
new file mode 100644
index 000000000..50fc3d2e0
--- /dev/null
+++ b/core/tests/switch_core/gateway/test_identity_link_confirmation.py
@@ -0,0 +1,850 @@
+"""A link from a chat account to a Switch user waits for the account to confirm
+it (CHOO-3881).
+
+Against real Postgres and real stores, calling the route handlers directly:
+what matters is which rows a request leaves behind, since a claim row is what
+every owner check trusts.
+"""
+
+from __future__ import annotations
+
+import uuid
+from collections.abc import Awaitable, Callable
+from datetime import datetime
+
+import pytest
+from fastapi import HTTPException
+from sqlalchemy import select
+from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
+
+from switch_core.db.audit import AuditAction
+from switch_core.db.models import (
+ TENANT_ZERO_ID,
+ AuditEvent,
+ Client,
+ CollaborationBridge,
+ ExternalUser,
+ ExternalUserClaim,
+ OrganizationMember,
+ TenantMember,
+ User,
+)
+from switch_core.db.stores.collaboration_bridge_store import CollaborationBridgeStore
+from switch_core.db.stores.external_user_store import ExternalUserStore
+from switch_core.db.stores.user_store import UserStore
+from switch_core.gateway.auth_routes import my_identities, my_pending_identities
+from switch_core.gateway.collaborations import (
+ cancel_identity_link_request,
+ claim_bridge_identity,
+ issue_identity_link_code,
+ list_unconfirmed_identity_links,
+ release_bridge_identity,
+ require_identity_confirmation,
+ verify_identity_with_session,
+)
+from switch_core.gateway.schemas import (
+ ClaimIdentityRequest,
+ VerifyIdentitySessionRequest,
+)
+
+_STORE = ExternalUserStore()
+_STAND_IN = "stand-in"
+
+
+class _Adapter:
+ def __init__(
+ self,
+ session_owner: str | Exception,
+ meanwhile: Callable[[], Awaitable[None]] | None = None,
+ ) -> None:
+ self._session_owner = session_owner
+ self._meanwhile = meanwhile
+
+ async def account_id_for_session(self, _token: str) -> str:
+ if self._meanwhile is not None:
+ await self._meanwhile()
+ if isinstance(self._session_owner, Exception):
+ raise self._session_owner
+ return self._session_owner
+
+
+class _Lifecycle:
+ def __init__(self, adapter: _Adapter | None = None) -> None:
+ self._adapter = adapter
+
+ def unlinkable_account_reason(
+ self, _bridge_type: str, external_user_id: str
+ ) -> str | None:
+ return "Many people post as it." if external_user_id == _STAND_IN else None
+
+ def link_code_instructions(
+ self, bridge_type: str, _connection_config: object, code: str
+ ) -> str:
+ return f"On {bridge_type}, post `!link-account {code}`."
+
+ def get_adapter(self, _bridge_id: str) -> _Adapter | None:
+ return self._adapter
+
+
+class _World:
+ def __init__(
+ self,
+ session_factory: async_sessionmaker[AsyncSession],
+ bridge_id: str,
+ account: ExternalUser,
+ ada: User,
+ bob: User,
+ ) -> None:
+ self.session_factory = session_factory
+ self.bridge_id = bridge_id
+ self.account = account
+ self.ada = ada
+ self.bob = bob
+
+
+async def _client(session: AsyncSession, client_type: str) -> str:
+ client = Client(
+ transport_user_id=f"@{client_type}-{uuid.uuid4().hex[:8]}:test",
+ display_name=client_type,
+ type=client_type,
+ )
+ session.add(client)
+ await session.flush()
+ return client.id
+
+
+async def _member(session: AsyncSession, name: str) -> User:
+ user = User(name=name, email=f"{name}-{uuid.uuid4().hex[:6]}@test", role="user")
+ session.add(user)
+ await session.flush()
+ session.add(TenantMember(tenant_id=TENANT_ZERO_ID, user_id=user.id, role="member"))
+ await session.flush()
+ return user
+
+
+async def world(session_factory: async_sessionmaker[AsyncSession]) -> _World:
+ async with session_factory() as session:
+ bridge = CollaborationBridge(
+ type="slack",
+ display_name="Acme Slack",
+ client_id=await _client(session, "bridge"),
+ status="active",
+ )
+ session.add(bridge)
+ await session.flush()
+ account = ExternalUser(
+ bridge_id=bridge.id,
+ external_user_id="U-ada",
+ external_username="ada",
+ client_id=await _client(session, "external_user"),
+ )
+ session.add(account)
+ for stand_in in (_STAND_IN,):
+ session.add(
+ ExternalUser(
+ bridge_id=bridge.id,
+ external_user_id=stand_in,
+ external_username="Group",
+ client_id=await _client(session, "external_user"),
+ )
+ )
+ ada = await _member(session, "ada")
+ bob = await _member(session, "bob")
+ await session.commit()
+ return _World(session_factory, bridge.id, account, ada, bob)
+
+
+async def _claim(
+ world: _World,
+ caller: User,
+ *,
+ external_user_id: str = "U-ada",
+ for_user: User | None = None,
+ is_admin: bool = False,
+ expects_confirmation: bool = True,
+) -> object:
+ async with world.session_factory() as session:
+ return await claim_bridge_identity(
+ world.bridge_id,
+ ClaimIdentityRequest(
+ external_user_id=external_user_id,
+ username="ada",
+ user_id=for_user.id if for_user is not None else None,
+ expects_confirmation=expects_confirmation,
+ ),
+ session,
+ CollaborationBridgeStore(),
+ _STORE,
+ UserStore(),
+ _Lifecycle(), # type: ignore[arg-type]
+ caller,
+ is_admin,
+ )
+
+
+async def _issue(world: _World, caller: User) -> object:
+ async with world.session_factory() as session:
+ return await issue_identity_link_code(
+ world.bridge_id,
+ world.account.id,
+ session,
+ CollaborationBridgeStore(),
+ _STORE,
+ _Lifecycle(), # type: ignore[arg-type]
+ caller,
+ )
+
+
+async def _verify(world: _World, caller: User, adapter: _Adapter | None) -> object:
+ async with world.session_factory() as session:
+ return await verify_identity_with_session(
+ world.bridge_id,
+ world.account.id,
+ VerifyIdentitySessionRequest(token="session-token"),
+ session,
+ _STORE,
+ UserStore(),
+ _Lifecycle(adapter), # type: ignore[arg-type]
+ caller,
+ )
+
+
+async def _claim_of(world: _World, user: User) -> ExternalUserClaim | None:
+ async with world.session_factory() as session:
+ return await _STORE.get_claim(session, world.account.id, user.id)
+
+
+class TestClaimWaitsForTheAccount:
+ async def test_a_claim_for_yourself_comes_back_with_a_code(
+ self, world: _World
+ ) -> None:
+ summary = await _claim(world, world.ada)
+
+ request = summary.link_request # type: ignore[attr-defined]
+ assert request is not None
+ assert request.user_id == world.ada.id
+ assert request.code is not None
+ assert request.code.instructions == (
+ f"On slack, post `!link-account {request.code.code}`."
+ )
+ assert isinstance(request.code.expires_at, datetime)
+ assert request.code.expires_in_seconds == 1800
+ assert summary.claimed_by == [] # type: ignore[attr-defined]
+ assert await _claim_of(world, world.ada) is None
+
+ async def test_an_account_already_confirmed_needs_nothing(
+ self, world: _World
+ ) -> None:
+ summary = await _claim(world, world.ada)
+ code = summary.link_request.code.code # type: ignore[attr-defined]
+ async with world.session_factory() as session:
+ assert await _STORE.redeem_link_code(
+ session, world.account, code, UserStore()
+ )
+ await session.commit()
+
+ again = await _claim(world, world.ada)
+
+ assert again.link_request is None # type: ignore[attr-defined]
+ assert [
+ (c.user_id, c.verified)
+ for c in again.claimed_by # type: ignore[attr-defined]
+ ] == [(world.ada.id, True)]
+
+ async def test_a_console_from_before_confirmation_is_told_to_update(
+ self, world: _World
+ ) -> None:
+ # It would otherwise drop the code and report a link that counts for
+ # nothing as made.
+ with pytest.raises(HTTPException) as refused:
+ await _claim(world, world.ada, expects_confirmation=False)
+
+ assert refused.value.status_code == 409
+ assert "Update Switch Console" in refused.value.detail
+ async with world.session_factory() as session:
+ assert (
+ await _STORE.get_link_request(session, world.account.id, world.ada.id)
+ is None
+ )
+
+ async def test_a_stand_in_account_cannot_be_linked(self, world: _World) -> None:
+ with pytest.raises(HTTPException) as refused:
+ await _claim(world, world.ada, external_user_id=_STAND_IN)
+
+ assert refused.value.status_code == 409
+ assert "Many people post as it." in refused.value.detail
+
+
+class TestIssuingACode:
+ async def test_a_new_code_for_a_waiting_link(self, world: _World) -> None:
+ first = await _claim(world, world.ada)
+
+ code = await _issue(world, world.ada)
+
+ assert code.code != first.link_request.code.code # type: ignore[attr-defined]
+ async with world.session_factory() as session:
+ assert (
+ await _STORE.redeem_link_code(
+ session,
+ world.account,
+ first.link_request.code.code, # type: ignore[attr-defined]
+ UserStore(),
+ )
+ is None
+ )
+ assert await _STORE.redeem_link_code(
+ session,
+ world.account,
+ code.code, # type: ignore[attr-defined]
+ UserStore(),
+ )
+
+ async def test_the_person_an_admin_linked_gets_the_code(
+ self, world: _World
+ ) -> None:
+ await _claim(world, world.bob, for_user=world.ada, is_admin=True)
+
+ code = await _issue(world, world.ada)
+
+ async with world.session_factory() as session:
+ confirmed = await _STORE.redeem_link_code(
+ session,
+ world.account,
+ code.code, # type: ignore[attr-defined]
+ UserStore(),
+ )
+ assert confirmed is not None
+ assert confirmed.user_id == world.ada.id
+
+ async def test_nobody_gets_a_code_for_someone_elses_link(
+ self, world: _World
+ ) -> None:
+ await _claim(world, world.ada)
+
+ with pytest.raises(HTTPException) as refused:
+ await _issue(world, world.bob)
+
+ assert refused.value.status_code == 404
+
+ async def test_a_link_from_before_confirmation_can_be_confirmed(
+ self, world: _World
+ ) -> None:
+ async with world.session_factory() as session:
+ session.add(
+ ExternalUserClaim(
+ external_user_id=world.account.id, user_id=world.ada.id
+ )
+ )
+ await session.commit()
+
+ code = await _issue(world, world.ada)
+
+ # Still trusted meanwhile, and verified once the code is posted.
+ claim = await _claim_of(world, world.ada)
+ assert claim is not None and claim.verified_at is None
+ async with world.session_factory() as session:
+ assert await _STORE.redeem_link_code(
+ session,
+ world.account,
+ code.code, # type: ignore[attr-defined]
+ UserStore(),
+ )
+ await session.commit()
+ claim = await _claim_of(world, world.ada)
+ assert claim is not None and claim.verified_at is not None
+
+ async def test_a_code_for_someone_since_removed_confirms_nothing(
+ self, world: _World
+ ) -> None:
+ summary = await _claim(world, world.ada)
+ async with world.session_factory() as session:
+ await session.delete(
+ await session.get(TenantMember, (TENANT_ZERO_ID, world.ada.id))
+ )
+ await session.commit()
+
+ async with world.session_factory() as session:
+ assert (
+ await _STORE.redeem_link_code(
+ session,
+ world.account,
+ summary.link_request.code.code, # type: ignore[attr-defined]
+ UserStore(),
+ )
+ is None
+ )
+ assert await _claim_of(world, world.ada) is None
+
+ async def test_an_organization_admin_with_no_membership_can_confirm(
+ self, world: _World
+ ) -> None:
+ # An org_admin stands in every workspace of their organization without
+ # a membership row in it, and may be linked there; the code must not
+ # then refuse them for want of the row.
+ async with world.session_factory() as session:
+ carol = User(
+ name="carol", email=f"carol-{uuid.uuid4().hex[:6]}@test", role="user"
+ )
+ session.add(carol)
+ await session.flush()
+ session.add(
+ OrganizationMember(
+ organization_id=TENANT_ZERO_ID, user_id=carol.id, role="org_admin"
+ )
+ )
+ await session.commit()
+ summary = await _claim(world, carol)
+
+ async with world.session_factory() as session:
+ assert await _STORE.redeem_link_code(
+ session,
+ world.account,
+ summary.link_request.code.code, # type: ignore[attr-defined]
+ UserStore(),
+ )
+ await session.commit()
+ assert await _claim_of(world, carol) is not None
+
+ async def test_a_confirmed_link_needs_no_code(self, world: _World) -> None:
+ summary = await _claim(world, world.ada)
+ async with world.session_factory() as session:
+ assert await _STORE.redeem_link_code(
+ session,
+ world.account,
+ summary.link_request.code.code, # type: ignore[attr-defined]
+ UserStore(),
+ )
+ await session.commit()
+
+ with pytest.raises(HTTPException) as refused:
+ await _issue(world, world.ada)
+
+ assert refused.value.status_code == 409
+
+
+class TestVerifyingWithASession:
+ async def test_the_accounts_own_session_confirms_the_link(
+ self, world: _World
+ ) -> None:
+ await _claim(world, world.ada)
+
+ summary = await _verify(world, world.ada, _Adapter("U-ada"))
+
+ assert [
+ (c.user_id, c.verified)
+ for c in summary.claimed_by # type: ignore[attr-defined]
+ ] == [(world.ada.id, True)]
+
+ async def test_another_accounts_session_confirms_nothing(
+ self, world: _World
+ ) -> None:
+ await _claim(world, world.ada)
+
+ with pytest.raises(HTTPException) as refused:
+ await _verify(world, world.ada, _Adapter("U-someone-else"))
+
+ assert refused.value.status_code == 403
+ assert await _claim_of(world, world.ada) is None
+
+ async def test_a_rejected_session_confirms_nothing(self, world: _World) -> None:
+ await _claim(world, world.ada)
+
+ with pytest.raises(HTTPException) as refused:
+ await _verify(world, world.ada, _Adapter(PermissionError("not accepted")))
+
+ assert refused.value.status_code == 403
+ assert await _claim_of(world, world.ada) is None
+
+ async def test_a_platform_without_session_checks_says_so(
+ self, world: _World
+ ) -> None:
+ await _claim(world, world.ada)
+
+ with pytest.raises(HTTPException) as refused:
+ await _verify(world, world.ada, _Adapter(NotImplementedError("no")))
+
+ assert refused.value.status_code == 501
+
+ async def test_a_link_cancelled_during_the_check_is_not_confirmed(
+ self, world: _World
+ ) -> None:
+ await _claim(world, world.ada)
+
+ async def cancel() -> None:
+ async with world.session_factory() as session:
+ await _STORE.release(session, world.account, world.ada.id)
+ await session.commit()
+
+ with pytest.raises(HTTPException) as refused:
+ await _verify(world, world.ada, _Adapter("U-ada", meanwhile=cancel))
+
+ assert refused.value.status_code == 409
+ assert await _claim_of(world, world.ada) is None
+
+ async def test_there_must_be_a_link_waiting(self, world: _World) -> None:
+ with pytest.raises(HTTPException) as refused:
+ await _verify(world, world.ada, _Adapter("U-ada"))
+
+ assert refused.value.status_code == 404
+ assert await _claim_of(world, world.ada) is None
+
+
+class TestCancelling:
+ async def test_unlinking_cancels_a_waiting_link(self, world: _World) -> None:
+ summary = await _claim(world, world.ada)
+
+ async with world.session_factory() as session:
+ await release_bridge_identity(
+ world.bridge_id,
+ world.account.id,
+ session,
+ _STORE,
+ UserStore(),
+ world.ada,
+ False,
+ )
+
+ async with world.session_factory() as session:
+ assert (
+ await _STORE.get_link_request(session, world.account.id, world.ada.id)
+ is None
+ )
+ assert (
+ await _STORE.redeem_link_code(
+ session,
+ world.account,
+ summary.link_request.code.code, # type: ignore[attr-defined]
+ UserStore(),
+ )
+ is None
+ )
+
+ async def test_cancelling_a_confirmation_keeps_an_older_link(
+ self, world: _World
+ ) -> None:
+ async with world.session_factory() as session:
+ session.add(
+ ExternalUserClaim(
+ external_user_id=world.account.id, user_id=world.ada.id
+ )
+ )
+ await session.commit()
+ code = await _issue(world, world.ada)
+
+ async with world.session_factory() as session:
+ await cancel_identity_link_request(
+ world.bridge_id,
+ world.account.id,
+ session,
+ _STORE,
+ UserStore(),
+ world.ada,
+ False,
+ )
+
+ claim = await _claim_of(world, world.ada)
+ assert claim is not None and claim.verified_at is None
+ async with world.session_factory() as session:
+ assert (
+ await _STORE.redeem_link_code(
+ session,
+ world.account,
+ code.code, # type: ignore[attr-defined]
+ UserStore(),
+ )
+ is None
+ )
+
+ async def test_cancelling_with_nothing_waiting_is_a_404(
+ self, world: _World
+ ) -> None:
+ async with world.session_factory() as session:
+ with pytest.raises(HTTPException) as refused:
+ await cancel_identity_link_request(
+ world.bridge_id,
+ world.account.id,
+ session,
+ _STORE,
+ UserStore(),
+ world.ada,
+ False,
+ )
+ assert refused.value.status_code == 404
+
+ async def test_cancelling_someone_elses_takes_an_admin(self, world: _World) -> None:
+ await _claim(world, world.ada)
+
+ async with world.session_factory() as session:
+ with pytest.raises(HTTPException) as refused:
+ await cancel_identity_link_request(
+ world.bridge_id,
+ world.account.id,
+ session,
+ _STORE,
+ UserStore(),
+ world.bob,
+ False,
+ user_id=world.ada.id,
+ )
+ assert refused.value.status_code == 403
+
+ async def test_unlinking_a_link_that_never_counted_is_audited_as_a_cancel(
+ self, world: _World
+ ) -> None:
+ await _claim(world, world.ada)
+
+ async with world.session_factory() as session:
+ await release_bridge_identity(
+ world.bridge_id,
+ world.account.id,
+ session,
+ _STORE,
+ UserStore(),
+ world.ada,
+ False,
+ )
+
+ async with world.session_factory() as session:
+ actions = list(
+ await session.scalars(
+ select(AuditEvent.action).where(
+ AuditEvent.target_id == world.account.id
+ )
+ )
+ )
+ assert AuditAction.BRIDGE_IDENTITY_LINK_CANCELLED in actions
+ assert AuditAction.BRIDGE_IDENTITY_RELEASED not in actions
+
+ async def test_unlinking_nothing_is_a_404(self, world: _World) -> None:
+ async with world.session_factory() as session:
+ with pytest.raises(HTTPException) as refused:
+ await release_bridge_identity(
+ world.bridge_id,
+ world.account.id,
+ session,
+ _STORE,
+ UserStore(),
+ world.ada,
+ False,
+ )
+ assert refused.value.status_code == 404
+
+
+class TestListingYourLinks:
+ async def test_a_waiting_link_is_listed_apart_from_the_ones_that_count(
+ self, world: _World
+ ) -> None:
+ await _claim(world, world.bob, for_user=world.ada, is_admin=True)
+
+ async with world.session_factory() as session:
+ linked = await my_identities(
+ session, _STORE, CollaborationBridgeStore(), world.ada
+ )
+ pending = await my_pending_identities(
+ session, _STORE, CollaborationBridgeStore(), UserStore(), world.ada
+ )
+
+ assert linked == []
+ assert [
+ (p.id, p.bridge_display_name, p.requested_by_name, p.code_expires_at)
+ for p in pending
+ ] == [(world.account.id, "Acme Slack", "bob", None)]
+
+ async def test_a_link_says_whether_it_was_confirmed(self, world: _World) -> None:
+ async with world.session_factory() as session:
+ session.add(
+ ExternalUserClaim(
+ external_user_id=world.account.id, user_id=world.ada.id
+ )
+ )
+ await session.commit()
+
+ async with world.session_factory() as session:
+ linked = await my_identities(
+ session, _STORE, CollaborationBridgeStore(), world.ada
+ )
+ pending = await my_pending_identities(
+ session, _STORE, CollaborationBridgeStore(), UserStore(), world.ada
+ )
+
+ assert [(i.id, i.verified) for i in linked] == [(world.account.id, False)]
+ assert pending == []
+
+ async def test_confirming_an_old_link_does_not_list_it_as_waiting(
+ self, world: _World
+ ) -> None:
+ async with world.session_factory() as session:
+ session.add(
+ ExternalUserClaim(
+ external_user_id=world.account.id, user_id=world.ada.id
+ )
+ )
+ await session.commit()
+ await _issue(world, world.ada)
+
+ async with world.session_factory() as session:
+ pending = await my_pending_identities(
+ session, _STORE, CollaborationBridgeStore(), UserStore(), world.ada
+ )
+
+ assert pending == []
+
+
+class TestRequiringConfirmationForOlderLinks:
+ """An admin can stop trusting the links made before links needed
+ confirming, until each owner confirms theirs."""
+
+ async def _older_link(self, world: _World, user: User) -> None:
+ async with world.session_factory() as session:
+ session.add(
+ ExternalUserClaim(external_user_id=world.account.id, user_id=user.id)
+ )
+ await session.commit()
+
+ async def _list(self, world: _World) -> list[object]:
+ async with world.session_factory() as session:
+ return list(
+ await list_unconfirmed_identity_links(
+ world.bridge_id,
+ session,
+ CollaborationBridgeStore(),
+ _STORE,
+ UserStore(),
+ world.bob,
+ )
+ )
+
+ async def _require(self, world: _World) -> int:
+ async with world.session_factory() as session:
+ result = await require_identity_confirmation(
+ world.bridge_id,
+ session,
+ CollaborationBridgeStore(),
+ _STORE,
+ world.bob,
+ )
+ return result.moved
+
+ async def test_the_older_links_are_listed(self, world: _World) -> None:
+ await self._older_link(world, world.ada)
+
+ [link] = await self._list(world)
+
+ assert (link.id, link.user_id, link.user_name, link.external_username) == ( # type: ignore[attr-defined]
+ world.account.id,
+ world.ada.id,
+ "ada",
+ "ada",
+ )
+
+ async def test_an_older_link_stops_counting_until_its_owner_confirms_it(
+ self, world: _World
+ ) -> None:
+ await self._older_link(world, world.ada)
+
+ assert await self._require(world) == 1
+
+ assert await _claim_of(world, world.ada) is None
+ async with world.session_factory() as session:
+ assert await _STORE.claimant_ids(session, world.account.id) == []
+ pending = await my_pending_identities(
+ session, _STORE, CollaborationBridgeStore(), UserStore(), world.ada
+ )
+ assert [(p.id, p.requested_by_name) for p in pending] == [
+ (world.account.id, "bob")
+ ]
+ # Confirmed the usual way, it counts again, now verified.
+ code = await _issue(world, world.ada)
+ async with world.session_factory() as session:
+ assert await _STORE.redeem_link_code(
+ session,
+ world.account,
+ code.code, # type: ignore[attr-defined]
+ UserStore(),
+ )
+ await session.commit()
+ claim = await _claim_of(world, world.ada)
+ assert claim is not None and claim.verified_at is not None
+
+ async def test_a_confirmed_link_is_untouched(self, world: _World) -> None:
+ summary = await _claim(world, world.ada)
+ async with world.session_factory() as session:
+ assert await _STORE.redeem_link_code(
+ session,
+ world.account,
+ summary.link_request.code.code, # type: ignore[attr-defined]
+ UserStore(),
+ )
+ await session.commit()
+
+ assert await self._require(world) == 0
+ assert await self._list(world) == []
+ claim = await _claim_of(world, world.ada)
+ assert claim is not None and claim.verified_at is not None
+
+ async def test_a_code_already_on_its_way_still_works(self, world: _World) -> None:
+ await self._older_link(world, world.ada)
+ code = await _issue(world, world.ada)
+
+ assert await self._require(world) == 1
+
+ async with world.session_factory() as session:
+ assert await _STORE.redeem_link_code(
+ session,
+ world.account,
+ code.code, # type: ignore[attr-defined]
+ UserStore(),
+ )
+
+ async def test_running_it_again_moves_nothing(self, world: _World) -> None:
+ await self._older_link(world, world.ada)
+
+ assert await self._require(world) == 1
+ assert await self._require(world) == 0
+
+ async def test_another_bridges_older_links_are_untouched(
+ self, world: _World
+ ) -> None:
+ async with world.session_factory() as session:
+ other = CollaborationBridge(
+ type="slack",
+ display_name="Other Slack",
+ client_id=await _client(session, "bridge"),
+ status="active",
+ )
+ session.add(other)
+ await session.flush()
+ elsewhere = ExternalUser(
+ bridge_id=other.id,
+ external_user_id="U-ada-elsewhere",
+ external_username="ada",
+ client_id=await _client(session, "external_user"),
+ )
+ session.add(elsewhere)
+ await session.flush()
+ session.add(
+ ExternalUserClaim(external_user_id=elsewhere.id, user_id=world.ada.id)
+ )
+ await session.commit()
+
+ assert await self._require(world) == 0
+
+ async with world.session_factory() as session:
+ assert await _STORE.claimant_ids(session, elsewhere.id) == [world.ada.id]
+
+ async def test_it_is_audited(self, world: _World) -> None:
+ await self._older_link(world, world.ada)
+
+ await self._require(world)
+
+ async with world.session_factory() as session:
+ event = await session.scalar(
+ select(AuditEvent).where(
+ AuditEvent.action
+ == AuditAction.BRIDGE_IDENTITY_CONFIRMATION_REQUIRED
+ )
+ )
+ assert event is not None
+ assert event.actor_user_id == world.bob.id
+ assert event.details == {"moved": 1}
diff --git a/core/tests/switch_core/management/test_my_context.py b/core/tests/switch_core/management/test_my_context.py
index 307f9161a..122b93568 100644
--- a/core/tests/switch_core/management/test_my_context.py
+++ b/core/tests/switch_core/management/test_my_context.py
@@ -27,6 +27,7 @@ from switch_core.db.models import (
Client,
CollaborationBridge,
ExternalUser,
+ ExternalUserClaim,
MessagingInstall,
ServiceGrant,
TenantMember,
@@ -154,8 +155,10 @@ async def _context(
async def _setup(harness: Harness) -> tuple[str, str, str]:
"""Ada, a member, with her buddy and a reviewer; a Slack workspace added
- with the Switch app, her account on it linked; a Discord server someone
- pasted tokens for. Returns the buddy's id and key, and Ada's id."""
+ with the Switch app, her account on it linked and confirmed; a Discord
+ server someone pasted tokens for, where she has started linking her
+ account but not confirmed it. Returns the buddy's id and key, and Ada's
+ id."""
ada = await add_member(harness.session_factory, "ada")
async with harness.session_factory() as session:
buddy, key = await _agent(
@@ -211,8 +214,29 @@ async def _setup(harness: Harness) -> tuple[str, str, str]:
client_id=account.id,
)
session.add(identity)
+ discord_account = Client(
+ type="external_user",
+ transport_user_id="@discord-ada:test",
+ display_name="ada",
+ )
+ session.add(discord_account)
+ await session.flush()
+ discord_identity = ExternalUser(
+ bridge_id=discord.id,
+ external_user_id="D1",
+ external_username="ada-on-discord",
+ client_id=discord_account.id,
+ )
+ session.add(discord_identity)
await session.flush()
- await ExternalUserStore().claim(session, identity, ada.id)
+ store = ExternalUserStore()
+ request = await store.request_link(
+ session, identity, ada.id, requested_by_user_id=ada.id
+ )
+ await store.confirm_link_request(session, request)
+ await store.request_link(
+ session, discord_identity, ada.id, requested_by_user_id=ada.id
+ )
await session.commit()
return buddy.id, key, ada.id
@@ -258,6 +282,7 @@ async def test_it_says_how_messaging_apps_are_and_would_be_set_up(
"is_default": False,
"installed_with": "own_app",
"your_account_linked": False,
+ "your_account_link": "pending",
"your_usernames": [],
},
{
@@ -268,6 +293,7 @@ async def test_it_says_how_messaging_apps_are_and_would_be_set_up(
"is_default": True,
"installed_with": "official_app",
"your_account_linked": True,
+ "your_account_link": "verified",
"your_usernames": ["ada"],
},
]
@@ -279,6 +305,25 @@ async def test_it_says_how_messaging_apps_are_and_would_be_set_up(
]
+async def test_a_link_from_before_confirmation_reads_as_unverified(
+ harness: Harness, client: httpx.AsyncClient
+) -> None:
+ buddy_id, key, ada_id = await _setup(harness)
+ async with harness.session_factory() as session:
+ await session.execute(
+ update(ExternalUserClaim)
+ .where(ExternalUserClaim.user_id == ada_id)
+ .values(verified_at=None)
+ )
+ await session.commit()
+
+ apps = (await _context(client, buddy_id, key))["messaging_apps"]["connected"]
+
+ slack = next(app for app in apps if app["platform"] == "slack")
+ assert slack["your_account_linked"] is True
+ assert slack["your_account_link"] == "unverified"
+
+
async def test_it_lists_only_the_persons_own_agents(
harness: Harness, client: httpx.AsyncClient
) -> None:
diff --git a/core/tests/switch_core/test_account_links.py b/core/tests/switch_core/test_account_links.py
new file mode 100644
index 000000000..5dd009201
--- /dev/null
+++ b/core/tests/switch_core/test_account_links.py
@@ -0,0 +1,38 @@
+"""Link codes survive what people and chat clients do to them (CHOO-3881)."""
+
+from __future__ import annotations
+
+import pytest
+
+from switch_core.account_links import new_link_code, normalise_link_code
+
+
+def test_a_new_code_reads_back_as_itself() -> None:
+ code = new_link_code()
+ assert normalise_link_code(code) == code.replace("-", "")
+
+
+ "typed",
+ [
+ "7KQ2-M9XD",
+ "7kq2m9xd",
+ " 7KQ2 M9XD ",
+ "`7KQ2-M9XD`",
+ '"7KQ2-M9XD".',
+ "7KQ2​-M9XD",
+ ],
+)
+def test_what_a_person_types_reads_as_the_code(typed: str) -> None:
+ assert normalise_link_code(typed) == "7KQ2M9XD"
+
+
+def test_letters_that_look_like_digits_read_as_the_digits() -> None:
+ assert normalise_link_code("OIL2-M9XD") == "0112M9XD"
+
+
+ "typed", ["", "7KQ2-M9X", "7KQ2-M9XD-1", "my code is 7KQ2-M9XD", "7KQ2-M9XU"]
+)
+def test_anything_else_is_not_a_code(typed: str) -> None:
+ assert normalise_link_code(typed) is None
diff --git a/deploy/shared_resources/setup.py b/deploy/shared_resources/setup.py
index 4cba067e4..8fefca8c6 100644
--- a/deploy/shared_resources/setup.py
+++ b/deploy/shared_resources/setup.py
@@ -365,15 +365,32 @@ def link_owner_identity(
deployment's own chat, and the Home page reports an account the user has to
link by hand (CHOO-2172).
- Only ever claims when the admin holds no identity on this bridge, so a
- re-run is a no-op. Someone who deliberately unlinks themselves and runs
- setup again does get relinked; that is the cost of repairing every existing
+ A link only counts once the account confirms it (CHOO-3881). A person does
+ that by posting a code, which needs a channel with an agent in it to hear
+ it, and a fresh deployment has none; so setup confirms it with the
+ account's own Mattermost session instead, which it can open because it
+ created the account.
+
+ Only ever claims when the admin holds no identity on this bridge, or holds
+ the seeded one unconfirmed, so a re-run is a no-op once it is confirmed.
+ Someone who deliberately unlinks themselves and runs setup again does get
+ relinked; that is the cost of repairing every existing
deployment on its next run, and the manual control to undo it is still
there.
"""
resp = client.get("/gateway/auth/me/identities")
if resp.is_success:
- if any(i.get("bridge_id") == bridge_id for i in resp.json()):
+ on_bridge = [i for i in resp.json() if i.get("bridge_id") == bridge_id]
+ # A link from before links needed confirming reads as unverified. One
+ # to the seeded account is confirmed below like a new link; one the
+ # admin made to some other account is theirs, and left alone.
+ unconfirmed_seeded = [
+ i
+ for i in on_bridge
+ if i.get("external_user_id") == external_user_id
+ and not i.get("verified", True)
+ ]
+ if on_bridge and not unconfirmed_seeded:
print(f"Gateway admin already linked to a Mattermost account: {bridge_id}")
return
else:
@@ -394,10 +411,20 @@ def link_owner_identity(
resp = client.post(
f"/gateway/collaborations/{bridge_id}/identities",
- json={"external_user_id": external_user_id, "username": MATTERMOST_USER},
+ json={
+ "external_user_id": external_user_id,
+ "username": MATTERMOST_USER,
+ "expects_confirmation": True,
+ },
)
if resp.is_success:
- print(f"Linked {GATEWAY_ADMIN_EMAIL} to Mattermost account {MATTERMOST_USER}")
+ identity = resp.json()
+ if identity.get("link_request") is None:
+ print(
+ f"Linked {GATEWAY_ADMIN_EMAIL} to Mattermost account {MATTERMOST_USER}"
+ )
+ else:
+ confirm_owner_identity(client, bridge_id, identity["id"])
return
print(
f"WARNING: Could not link {GATEWAY_ADMIN_EMAIL} to the Mattermost account "
@@ -407,6 +434,52 @@ def link_owner_identity(
)
+def confirm_owner_identity(
+ client: httpx.Client, bridge_id: str, identity_id: str
+) -> None:
+ """Confirm the admin's waiting link with the seeded account's own session.
+
+ The session is opened for this and closed straight after, so setup leaves
+ no login of the account behind.
+ """
+ mattermost = httpx.Client(base_url=MATTERMOST_URL, timeout=10)
+ try:
+ login = mattermost.post(
+ "/api/v4/users/login",
+ json={"login_id": MATTERMOST_USER, "password": MATTERMOST_USER_PASSWORD},
+ )
+ if not login.is_success:
+ print(
+ f"WARNING: Could not sign in to Mattermost as {MATTERMOST_USER} "
+ f"({login.status_code} {login.text}), so the link to "
+ f"{GATEWAY_ADMIN_EMAIL} is waiting to be confirmed. Confirm it "
+ "from the server's Messaging apps section."
+ )
+ return
+ token = login.headers["token"]
+ try:
+ resp = client.post(
+ f"/gateway/collaborations/{bridge_id}/identities/{identity_id}"
+ "/verify-session",
+ json={"token": token},
+ )
+ finally:
+ mattermost.post(
+ "/api/v4/users/logout", headers={"Authorization": f"Bearer {token}"}
+ )
+ finally:
+ mattermost.close()
+ if resp.is_success:
+ print(f"Linked {GATEWAY_ADMIN_EMAIL} to Mattermost account {MATTERMOST_USER}")
+ return
+ print(
+ f"WARNING: Could not confirm the link from {GATEWAY_ADMIN_EMAIL} to the "
+ f"Mattermost account {MATTERMOST_USER}: {resp.status_code} {resp.text}. "
+ "Owner-only agents will not recognise you in Mattermost until you confirm "
+ "it from the server's Messaging apps section."
+ )
+
+
def main() -> None:
print("Switch local setup starting...")
diff --git a/docs/TELEMETRY.md b/docs/TELEMETRY.md
index 2376d4b12..d9149d96d 100644
--- a/docs/TELEMETRY.md
+++ b/docs/TELEMETRY.md
@@ -89,7 +89,7 @@ id, no IP field, no Switch identity.
| Field | Complete set of possible values |
|---|---|
-| `outcome` | `success`, `failure` (on `session_ended`: `normal`, `failed`) |
+| `outcome` | `success`, `failure` (on `session_ended`: `normal`, `failed`; on `bridge_identity_claimed`, also `pending`) |
| `agent_type` | the AI provider, from a fixed registry: `claude`, `codex`, `gemini`, `cursor`, `copilot`, `opencode`, `grok`, `devin`, `qwen`, `droid`, `amp`, `goose`, `cline`, `continue`, `mistral`, `kiro`, `junie`, … and `unknown`. **Never an agent's name.** |
| `location` | `local`, `remote`, `unknown`. **Never a path, directory or project name.** |
| `server_kind` | `local`, `remote_managed`, `external`. **Never a server name or URL.** |
@@ -171,7 +171,8 @@ sign-in records `invalid_credentials` — not the username tried, not the server
|---|---|
| `bridge_connected` | `bridge`: `collaboration` · `bridge_platform`: `slack` · `outcome`: `failure` · `failure_reason`: `none` / `unauthenticated` / `forbidden` / `invalid` / `error` |
| `bridge_disconnected` | `bridge`: `collaboration` · `bridge_platform`: `mattermost` · `outcome` |
-| `bridge_identity_claimed` | `bridge_platform` · `outcome` |
+| `bridge_identity_claimed` | `bridge_platform` · `outcome`: `success` (linked) / `pending` (waiting for a one-time code to be posted from the account, which is what confirms the link) / `failure` |
+| `bridge_identity_confirmed` | `bridge_platform` · `link_kind`: `new` (a link that was waiting on its code) / `existing` (a link made before links had to be confirmed, which worked all along) / `unknown` — sent when the code is posted and the link confirmed, after asking the server that it is |
| `room_created` | `server_kind`: `local` · `bridge_platform`: `slack` · `agent_count`: `3` · `has_instructions`: `true` · `outcome` · `failure_reason`: `none` / `unauthenticated` / `bridge_unavailable` / `invalid` / `unreachable` / `error` · `source`: `dialog` / `template` |
| `room_deleted` | `server_kind` · `outcome` |
| `room_agents_added` | `agent_count`: `2` · `direction`: `agents_to_room` / `room_to_agents` |
diff --git a/docs/old/bridges/SLACK_DISTRIBUTED_APP.md b/docs/old/bridges/SLACK_DISTRIBUTED_APP.md
index 022f8e438..ac5cbc743 100644
--- a/docs/old/bridges/SLACK_DISTRIBUTED_APP.md
+++ b/docs/old/bridges/SLACK_DISTRIBUTED_APP.md
@@ -125,6 +125,8 @@ the same job once installed — the differences are all in `settings` and
{ "command": "/set-alias", "url": "https://HOST/messaging/slack/commands", "description": "Give an agent a room alias", "usage_hint": "@agent-name @alias", "should_escape": true },
{ "command": "/remove-alias", "url": "https://HOST/messaging/slack/commands", "description": "Remove a room alias", "usage_hint": "@alias (or @agent-name)", "should_escape": true },
{ "command": "/invite-agent", "url": "https://HOST/messaging/slack/commands", "description": "Add an existing agent to this room", "usage_hint": "@agent-name", "should_escape": true },
+ { "command": "/link-account", "url": "https://HOST/messaging/slack/commands", "description": "Confirm a link between your chat account and your Switch user", "usage_hint": "CODE", "should_escape": true },
+ { "command": "/unlink-account", "url": "https://HOST/messaging/slack/commands", "description": "List or remove the Switch users this chat account is linked to", "usage_hint": "[name]", "should_escape": true },
{ "command": "/rename-agent", "url": "https://HOST/messaging/slack/commands", "description": "Rename an agent (owner or admin)", "usage_hint": "@agent-name new-name [Display Name]", "should_escape": true },
{ "command": "/delete-agent", "url": "https://HOST/messaging/slack/commands", "description": "Delete an agent (owner or admin)", "usage_hint": "@agent-name [confirm]", "should_escape": true },
{ "command": "/agents-greet", "url": "https://HOST/messaging/slack/commands", "description": "Have agents in the room introduce themselves", "should_escape": false },
diff --git a/docs/old/bridges/SLACK_SETUP.md b/docs/old/bridges/SLACK_SETUP.md
index 6c4f8c21c..ff702d803 100644
--- a/docs/old/bridges/SLACK_SETUP.md
+++ b/docs/old/bridges/SLACK_SETUP.md
@@ -74,6 +74,8 @@ You need one Slack app for the whole bridge. There are two ways to create it —
{ "command": "/set-alias", "description": "Give an agent a room alias", "usage_hint": "@agent-name @alias", "should_escape": true },
{ "command": "/remove-alias", "description": "Remove a room alias", "usage_hint": "@alias (or @agent-name)", "should_escape": true },
{ "command": "/invite-agent", "description": "Add an existing agent to this room", "usage_hint": "@agent-name", "should_escape": true },
+ { "command": "/link-account", "description": "Confirm a link between your chat account and your Switch user", "usage_hint": "CODE", "should_escape": true },
+ { "command": "/unlink-account", "description": "List or remove the Switch users this chat account is linked to", "usage_hint": "[name]", "should_escape": true },
{ "command": "/rename-agent", "description": "Rename an agent (owner or admin)", "usage_hint": "@agent-name new-name [Display Name]", "should_escape": true },
{ "command": "/delete-agent", "description": "Delete an agent (owner or admin)", "usage_hint": "@agent-name [confirm]", "should_escape": true },
{ "command": "/agents-greet", "description": "Have agents in the room introduce themselves", "should_escape": false },
diff --git a/switch-expert/AGENT.md b/switch-expert/AGENT.md
index 21a56dd18..de7e1fbd2 100644
--- a/switch-expert/AGENT.md
+++ b/switch-expert/AGENT.md
@@ -221,7 +221,9 @@ properly, and the person will hit the gaps later rather than sooner.
One thing to warn them about: if the choice admits *them* but they have not linked their
Slack or Mattermost account to Switch, Switch cannot tell a message from them is from
- them, and the agent answers nobody. Switch Console says so on the setting itself.
+ them, and the agent answers nobody. Switch Console says so on the setting itself. A
+ link counts once they confirm it by posting, from that chat account, the code Switch
+ Console shows them.
6. **Run it somewhere that stays up — and let Switch Console do that for you.** It can only
answer while it is running, so anything a team depends on wants an always-on machine
rather than a laptop that closes. **This is much less work than it sounds.** All you need