Skip to content

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

Console calls for your account and your API keys

Simon Flack0918f073774d
diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/controller.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/controller.ts
index 6d93edb4b..6f985d8fb 100644
--- a/console/apps/switch-console-desktop/src/main/core/switch-servers/controller.ts
+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/controller.ts
@@ -35,14 +35,17 @@ import {
type AddServerParams,
type BundledChatSignIn,
type ClearTrustSettingsResult,
+ type CreatedRegistrationKey,
type FetchTrustSettingsResult,
type PasswordLoginParams,
type RenameServerParams,
type ServerConnectionStatus,
type SignupParams,
type SignupResult,
+ type SwitchApiKey,
type SwitchAuthConfig,
type SwitchServer,
+ type SwitchUser,
type UpdateServerParams,
type UpdateServerResult,
type UpdateTrustSettingsParams,
@@ -77,7 +80,13 @@ import {
createOrganization,
createOrganizationWorkspace,
fetchAuthConfig,
+ changeMyPassword,
+ createRegistrationKey,
+ deleteApiKey,
deleteMyAccount,
+ fetchMyApiKeys,
+ revealApiKey,
+ updateMyName,
fetchMe,
fetchJoinableWorkspaces,
fetchPendingInvitations,
@@ -646,6 +655,49 @@ export const switchServersController = createRPCController({
if (server) trackEvent('server_sign_out', { server_kind: serverKindOf(server) });
},
+ /** Change the signed-in person's display name; refreshes the signed-in status after. */
+ updateMyName: async (params: { serverId: string; name: string }): Promise<SwitchUser> => {
+ const server = await requireReachableServer(params.serverId);
+ return updateMyName(server, params.name);
+ },
+
+ /** Change the signed-in person's password. Refusals carry the server's reason. */
+ changeMyPassword: async (params: {
+ serverId: string;
+ currentPassword: string;
+ newPassword: string;
+ }): Promise<void> => {
+ const server = await requireReachableServer(params.serverId);
+ await changeMyPassword(server, params.currentPassword, params.newPassword);
+ },
+
+ /** The signed-in person's own API keys. */
+ listMyApiKeys: async (serverId: string): Promise<SwitchApiKey[]> => {
+ const server = await requireReachableServer(serverId);
+ return fetchMyApiKeys(server);
+ },
+
+ /** Make a registration key; the answer is the only time its value is shown. */
+ createRegistrationKey: async (params: {
+ serverId: string;
+ label: string;
+ }): Promise<CreatedRegistrationKey> => {
+ const server = await requireReachableServer(params.serverId);
+ return createRegistrationKey(server, params.label);
+ },
+
+ /** One of the signed-in person's keys in full, for copying. */
+ revealApiKey: async (params: { serverId: string; keyId: string }): Promise<string> => {
+ const server = await requireReachableServer(params.serverId);
+ return revealApiKey(server, params.keyId);
+ },
+
+ /** Delete one of the signed-in person's keys. */
+ deleteApiKey: async (params: { serverId: string; keyId: string }): Promise<void> => {
+ const server = await requireReachableServer(params.serverId);
+ await deleteApiKey(server, params.keyId);
+ },
+
/** Delete the signed-in account on the server, then forget its session here. */
deleteAccount: async (params: { serverId: string; email: string }): Promise<void> => {
const server = await requireReachableServer(params.serverId);
diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.account.test.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.account.test.ts
new file mode 100644
index 000000000..40d8274d4
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.account.test.ts
@@ -0,0 +1,147 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+const getSessionCookie = vi.hoisted(() => vi.fn());
+
+vi.mock('@main/core/managed-switch-server/managed-server-status', () => ({
+ managedServerHostBlocked: () => null,
+ managedServerStoppedPhase: () => null,
+ noteManagedServerUnanswered: () => undefined,
+}));
+vi.mock('./servers-store', () => ({ getSessionCookie, setSessionCookie: vi.fn() }));
+vi.mock('./auth', () => ({
+ refreshSession: vi.fn(),
+ reauthenticateManagedServer: vi.fn(),
+ extractAuthCookie: () => null,
+}));
+vi.mock('./console-identity', () => ({ consoleIdentityHeaders: async () => ({}) }));
+
+const {
+ changeMyPassword,
+ createRegistrationKey,
+ deleteApiKey,
+ fetchMyApiKeys,
+ revealApiKey,
+ updateMyName,
+} = await import('./gateway-client');
+
+const SERVER = {
+ id: 'srv-1',
+ name: 'S',
+ url: 'https://switch.example.com',
+ dashboardUrl: null,
+ managed: false,
+} as never;
+
+function makeJwt(secondsFromNow: number): string {
+ const header = Buffer.from(JSON.stringify({ alg: 'HS256', typ: 'JWT' })).toString('base64url');
+ const exp = Math.floor(Date.now() / 1000) + secondsFromNow;
+ 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 < 400,
+ json: async () => body,
+ headers: { get: () => null, getSetCookie: () => [] },
+ text: async () => JSON.stringify(body),
+ } as unknown as Response;
+}
+
+const fetchMock = vi.fn(async (_url: string, _init?: RequestInit) => response(200, {}));
+
+function lastCall(): { url: string; method: string; body: unknown } {
+ const [url, init] = fetchMock.mock.calls.at(-1) as [string, RequestInit | undefined];
+ return {
+ url,
+ method: init?.method ?? 'GET',
+ body: typeof init?.body === 'string' ? JSON.parse(init.body) : undefined,
+ };
+}
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ getSessionCookie.mockResolvedValue(makeJwt(2 * 60 * 60));
+ vi.stubGlobal('fetch', fetchMock);
+});
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+});
+
+describe('account', () => {
+ it('changes the display name and reads back the user', async () => {
+ fetchMock.mockImplementation(async () =>
+ response(200, { id: 'u1', name: 'Ada Lovelace', email: '[email protected]', role: 'user' })
+ );
+ const user = await updateMyName(SERVER, 'Ada Lovelace');
+ expect(lastCall()).toMatchObject({ method: 'PATCH', body: { name: 'Ada Lovelace' } });
+ expect(lastCall().url).toMatch(/\/auth\/me$/);
+ expect(user.name).toBe('Ada Lovelace');
+ });
+
+ it('changes the password in the server’s field names', async () => {
+ fetchMock.mockImplementation(async () => response(200, { ok: true }));
+ await changeMyPassword(SERVER, 'old-pass', 'new-password-1');
+ expect(lastCall()).toMatchObject({
+ method: 'PUT',
+ body: { current_password: 'old-pass', new_password: 'new-password-1' },
+ });
+ expect(lastCall().url).toMatch(/\/auth\/me\/password$/);
+ });
+
+ it('passes on the server’s reason when the current password is wrong', async () => {
+ fetchMock.mockImplementation(async () =>
+ response(403, { detail: 'Current password is incorrect' })
+ );
+ await expect(changeMyPassword(SERVER, 'nope', 'new-password-1')).rejects.toThrow(
+ 'Current password is incorrect'
+ );
+ });
+});
+
+describe('API keys', () => {
+ it('lists the signed-in person’s keys', async () => {
+ fetchMock.mockImplementation(async () =>
+ response(200, [
+ {
+ id: 'k1',
+ label: 'My scripts',
+ type: 'registration',
+ key_prefix: 'abc',
+ created_at: 'd1',
+ },
+ { id: 'k2', label: 'release-bot', type: 'agent', key_prefix: 'def', created_at: 'd2' },
+ ])
+ );
+ await expect(fetchMyApiKeys(SERVER)).resolves.toEqual([
+ { id: 'k1', label: 'My scripts', type: 'registration', keyPrefix: 'abc', createdAt: 'd1' },
+ { id: 'k2', label: 'release-bot', type: 'agent', keyPrefix: 'def', createdAt: 'd2' },
+ ]);
+ expect(lastCall().url).toMatch(/\/api-keys$/);
+ });
+
+ it('creates a registration key and returns its value once', async () => {
+ fetchMock.mockImplementation(async () =>
+ response(200, { id: 'k3', label: 'CI', key: 'secret-value', created_at: 'd3' })
+ );
+ await expect(createRegistrationKey(SERVER, 'CI')).resolves.toEqual({
+ id: 'k3',
+ label: 'CI',
+ key: 'secret-value',
+ createdAt: 'd3',
+ });
+ expect(lastCall()).toMatchObject({ method: 'POST', body: { label: 'CI' } });
+ });
+
+ it('reveals and deletes a key by id', async () => {
+ fetchMock.mockImplementation(async () => response(200, { key: 'full-key' }));
+ await expect(revealApiKey(SERVER, 'k1')).resolves.toBe('full-key');
+ expect(lastCall().url).toMatch(/\/api-keys\/k1\/reveal$/);
+ fetchMock.mockImplementation(async () => response(200, { ok: true }));
+ await deleteApiKey(SERVER, 'k1');
+ expect(lastCall()).toMatchObject({ method: 'DELETE' });
+ expect(lastCall().url).toMatch(/\/api-keys\/k1$/);
+ });
+});
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 88b2eaf95..a87edb030 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
@@ -97,6 +97,8 @@ import {
type RemoteRoomSummary,
type RemoveTeamsTeamResult,
type RetireOutcome,
+ type SwitchApiKey,
+ type CreatedRegistrationKey,
type SwitchAuthConfig,
type SwitchServer,
type SwitchServerDeclaration,
@@ -604,6 +606,46 @@ export async function deleteMyAccount(server: SwitchServer, email: string): Prom
}
}
+/**
+ * Change the signed-in person's display name (`PATCH /auth/me`), resolving to
+ * the user as the server now has it. A refusal surfaces in the server's words.
+ */
+export async function updateMyName(server: SwitchServer, name: string): Promise<SwitchUser> {
+ try {
+ const res = await gatewayFetch(server, '/auth/me', {
+ authenticated: true,
+ method: 'PATCH',
+ body: { name },
+ });
+ return mapUser((await res.json()) as UserResponseJson);
+ } catch (error) {
+ if (error instanceof GatewayError && error.detail) throw new Error(error.detail);
+ throw error;
+ }
+}
+
+/**
+ * Change the signed-in person's password (`PUT /auth/me/password`). Refused
+ * with the server's reason — a wrong current password, or an account that
+ * signs in through single sign-on and so has none.
+ */
+export async function changeMyPassword(
+ server: SwitchServer,
+ currentPassword: string,
+ newPassword: string
+): Promise<void> {
+ try {
+ await gatewayFetch(server, '/auth/me/password', {
+ authenticated: true,
+ method: 'PUT',
+ body: { current_password: currentPassword, new_password: newPassword },
+ });
+ } catch (error) {
+ if (error instanceof GatewayError && error.detail) throw new Error(error.detail);
+ throw error;
+ }
+}
+
export async function fetchMe(server: SwitchServer): Promise<SwitchUser> {
const res = await gatewayFetch(server, '/auth/me', { authenticated: true });
return mapUser((await res.json()) as UserResponseJson);
@@ -4727,6 +4769,53 @@ export async function deleteManagedAgent(
}
type ApiKeyJson = { id: string; label: string; type: string };
+type ApiKeyDetailJson = ApiKeyJson & { key_prefix: string; created_at: string };
+
+/**
+ * The signed-in person's own API keys (`GET /api-keys`): the registration
+ * keys they made, their agents' keys, and the deployment's bootstrap key when
+ * it was issued to them. Nobody else's.
+ */
+export async function fetchMyApiKeys(server: SwitchServer): Promise<SwitchApiKey[]> {
+ const res = await gatewayFetch(server, '/api-keys', { authenticated: true });
+ return ((await res.json()) as ApiKeyDetailJson[]).map((key) => ({
+ id: key.id,
+ label: key.label,
+ type: key.type,
+ keyPrefix: key.key_prefix,
+ createdAt: key.created_at,
+ }));
+}
+
+/** Make a registration key (`POST /api-keys`). Its value is in the answer and nowhere else. */
+export async function createRegistrationKey(
+ server: SwitchServer,
+ label: string
+): Promise<CreatedRegistrationKey> {
+ const res = await gatewayFetch(server, '/api-keys', {
+ authenticated: true,
+ method: 'POST',
+ body: { label },
+ });
+ const json = (await res.json()) as { id: string; label: string; key: string; created_at: string };
+ return { id: json.id, label: json.label, key: json.key, createdAt: json.created_at };
+}
+
+/** One of the signed-in person's keys in full (`GET /api-keys/{id}/reveal`). The server audits it. */
+export async function revealApiKey(server: SwitchServer, keyId: string): Promise<string> {
+ const res = await gatewayFetch(server, `/api-keys/${encodeURIComponent(keyId)}/reveal`, {
+ authenticated: true,
+ });
+ return ((await res.json()) as { key: string }).key;
+}
+
+/** Delete one of the signed-in person's keys (`DELETE /api-keys/{id}`); it stops working at once. */
+export async function deleteApiKey(server: SwitchServer, keyId: string): Promise<void> {
+ await gatewayFetch(server, `/api-keys/${encodeURIComponent(keyId)}`, {
+ authenticated: true,
+ method: 'DELETE',
+ });
+}
/**
* An agent's own API key, revealed through the owner's session
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 0bd5798b0..3e1cc9a67 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
@@ -199,6 +199,24 @@ export type SwitchServerDeclaration = {
};
/** The authenticated user, as returned by `GET /gateway/auth/me`. */
+/**
+ * One of the signed-in person's API keys (mirrors the gateway `ApiKeyDetail`).
+ * `type` is `registration` for a key they made to register agents with,
+ * `agent` for one of their agents' own keys, or `bootstrap` for the
+ * deployment's seeded registration key. `keyPrefix` is the start of the key's
+ * hash, which identifies it without revealing it.
+ */
+export type SwitchApiKey = {
+ id: string;
+ label: string;
+ type: string;
+ keyPrefix: string;
+ createdAt: string;
+};
+
+/** A registration key just made: the one time its full value is shown. */
+export type CreatedRegistrationKey = { id: string; label: string; key: string; createdAt: string };
+
export type SwitchUser = {
id: string;
name: string;