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: choose and show API key lifetimes

Petr Bauch34ab90556387
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 5a3582617..c578d2426 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
@@ -37,6 +37,7 @@ import {
import {
normaliseServerUrl,
type AddServerParams,
+ type ApiKeyLifetime,
type BundledChatSignIn,
type ClearDecisionSettingsResult,
type ClearTrustSettingsResult,
@@ -751,9 +752,10 @@ export const switchServersController = createRPCController({
createRegistrationKey: async (params: {
serverId: string;
label: string;
+ lifetime: ApiKeyLifetime;
}): Promise<CreatedRegistrationKey> => {
const server = await requireReachableServer(params.serverId);
- return createRegistrationKey(server, params.label);
+ return createRegistrationKey(server, params.label, params.lifetime);
},
/** One of the signed-in person's keys in full, for copying. */
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
index 9e4634c8b..38b90f6bc 100644
--- 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
@@ -128,28 +128,63 @@ describe('API keys', () => {
type: 'registration',
key_prefix: 'abc',
created_at: 'd1',
+ expires_at: 'e1',
},
{ 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' },
+ {
+ id: 'k1',
+ label: 'My scripts',
+ type: 'registration',
+ keyPrefix: 'abc',
+ createdAt: 'd1',
+ expiresAt: 'e1',
+ },
+ {
+ id: 'k2',
+ label: 'release-bot',
+ type: 'agent',
+ keyPrefix: 'def',
+ createdAt: 'd2',
+ expiresAt: null,
+ },
]);
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' })
+ response(200, {
+ id: 'k3',
+ label: 'CI',
+ key: 'secret-value',
+ created_at: 'd3',
+ expires_at: 'e3',
+ })
);
- await expect(createRegistrationKey(SERVER, 'CI')).resolves.toEqual({
+ await expect(createRegistrationKey(SERVER, 'CI', 90)).resolves.toEqual({
id: 'k3',
label: 'CI',
key: 'secret-value',
createdAt: 'd3',
+ expiresAt: 'e3',
+ });
+ expect(lastCall()).toMatchObject({
+ method: 'POST',
+ body: { label: 'CI', expires_in_days: 90 },
+ });
+ });
+
+ it('asks for a key that never expires', async () => {
+ fetchMock.mockImplementation(async () =>
+ response(200, { id: 'k4', label: 'CI', key: 'v', created_at: 'd4', expires_at: null })
+ );
+ await expect(createRegistrationKey(SERVER, 'CI', 'never')).resolves.toMatchObject({
+ expiresAt: null,
});
- expect(lastCall()).toMatchObject({ method: 'POST', body: { label: 'CI' } });
+ expect(lastCall()).toMatchObject({ body: { label: 'CI', expires_in_days: 'never' } });
});
it('reveals and deletes a key by id', async () => {
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 4a813b89d..5a8e9dd1f 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
@@ -105,6 +105,7 @@ import {
type RoomVisibility,
type RetireOutcome,
type SwitchApiKey,
+ type ApiKeyLifetime,
type CreatedRegistrationKey,
type RoomAutoRoute,
type SwitchAuthConfig,
@@ -5208,7 +5209,12 @@ export async function deleteManagedAgent(
}
type ApiKeyJson = { id: string; label: string; type: string };
-type ApiKeyDetailJson = ApiKeyJson & { key_prefix: string; created_at: string };
+// `expires_at` is absent on a server older than key expiry, where no key expires.
+type ApiKeyDetailJson = ApiKeyJson & {
+ key_prefix: string;
+ created_at: string;
+ expires_at?: string | null;
+};
/**
* The signed-in person's own API keys (`GET /api-keys`): the registration
@@ -5223,21 +5229,38 @@ export async function fetchMyApiKeys(server: SwitchServer): Promise<SwitchApiKey
type: key.type,
keyPrefix: key.key_prefix,
createdAt: key.created_at,
+ expiresAt: key.expires_at ?? null,
}));
}
-/** Make a registration key (`POST /api-keys`). Its value is in the answer and nowhere else. */
+/**
+ * Make a registration key (`POST /api-keys`) that works for `lifetime`. Its
+ * value is in the answer and nowhere else.
+ */
export async function createRegistrationKey(
server: SwitchServer,
- label: string
+ label: string,
+ lifetime: ApiKeyLifetime
): Promise<CreatedRegistrationKey> {
const res = await gatewayFetch(server, '/api-keys', {
authenticated: true,
method: 'POST',
- body: { label },
+ body: { label, expires_in_days: lifetime },
});
- 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 };
+ const json = (await res.json()) as {
+ id: string;
+ label: string;
+ key: string;
+ created_at: string;
+ expires_at?: string | null;
+ };
+ return {
+ id: json.id,
+ label: json.label,
+ key: json.key,
+ createdAt: json.created_at,
+ expiresAt: json.expires_at ?? null,
+ };
}
/** One of the signed-in person's keys in full (`GET /api-keys/{id}/reveal`). The server audits it. */
diff --git a/console/apps/switch-console-desktop/src/renderer/features/settings/pages/api-keys-page.tsx b/console/apps/switch-console-desktop/src/renderer/features/settings/pages/api-keys-page.tsx
index 95b73354e..66f0a8919 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/settings/pages/api-keys-page.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/settings/pages/api-keys-page.tsx
@@ -5,14 +5,25 @@ import { toast } from 'sonner';
import { PageHeader } from '@renderer/lib/components/page-header';
import { describeFailure } from '@renderer/lib/errors/describe-failure';
import { rpc } from '@renderer/lib/ipc';
+import { Alert } from '@renderer/lib/ui/alert';
import { Button } from '@renderer/lib/ui/button';
import { Input } from '@renderer/lib/ui/input';
+import { SegmentedControl } from '@renderer/lib/ui/segmented-control';
import { Spinner } from '@renderer/lib/ui/spinner';
import {
type CreatedRegistrationKey,
type SwitchApiKey,
} from '@shared/core/switch-servers/switch-servers';
-import { splitApiKeys } from './api-keys';
+import {
+ DEFAULT_KEY_LIFETIME,
+ describeCreatedKeyExpiry,
+ formatKeyExpiry,
+ KEY_LIFETIMES,
+ type KeyLifetimeChoice,
+ keyLifetime,
+ NEVER_EXPIRES_WARNING,
+ splitApiKeys,
+} from './api-keys';
import { OnSignedInServer, SectionLabel } from './settings-server';
/** Keyed on the person as well as the server, so one person's keys are never shown to the next to sign in. */
@@ -116,10 +127,17 @@ function CreateRegistrationKey({
onCreated: (key: CreatedRegistrationKey) => void;
}) {
const [label, setLabel] = useState('');
+ const [lifetime, setLifetime] = useState<KeyLifetimeChoice>(DEFAULT_KEY_LIFETIME);
const create = useMutation({
- mutationFn: () => rpc.switchServers.createRegistrationKey({ serverId, label: label.trim() }),
+ mutationFn: () =>
+ rpc.switchServers.createRegistrationKey({
+ serverId,
+ label: label.trim(),
+ lifetime: keyLifetime(lifetime),
+ }),
onSuccess: (key) => {
setLabel('');
+ setLifetime(DEFAULT_KEY_LIFETIME);
onCreated(key);
},
onError: (error) => {
@@ -129,24 +147,36 @@ function CreateRegistrationKey({
});
return (
<form
- className="flex items-center gap-2"
+ className="space-y-2"
onSubmit={(event) => {
event.preventDefault();
if (label.trim()) create.mutate();
}}
>
- <Input
- aria-label="New key's label"
- placeholder="Label, such as the agent or machine it is for"
- value={label}
- maxLength={255}
- onChange={(event) => setLabel(event.target.value)}
- className="max-w-sm"
- />
- <Button type="submit" size="sm" disabled={!label.trim() || create.isPending}>
- <Plus className="size-4" />
- Create registration key
- </Button>
+ <div className="flex flex-wrap items-center gap-2">
+ <Input
+ aria-label="New key's label"
+ placeholder="Label, such as the agent or machine it is for"
+ value={label}
+ maxLength={255}
+ onChange={(event) => setLabel(event.target.value)}
+ className="max-w-sm"
+ />
+ <Button type="submit" size="sm" disabled={!label.trim() || create.isPending}>
+ <Plus className="size-4" />
+ Create registration key
+ </Button>
+ </div>
+ <div className="flex items-center gap-2 text-sm text-foreground-muted">
+ <span>Expires after</span>
+ <SegmentedControl
+ value={lifetime}
+ onChange={setLifetime}
+ options={KEY_LIFETIMES}
+ ariaLabel="Expires after"
+ />
+ </div>
+ {lifetime === 'never' && <Alert variant="warning">{NEVER_EXPIRES_WARNING}</Alert>}
</form>
);
}
@@ -163,7 +193,7 @@ function CreatedKey({
<div className="space-y-2 rounded-lg border border-border bg-background-1 p-3">
<p className="text-sm text-foreground">
<span className="font-medium">{created.label}</span> is ready. Copy it here, or later from
- the list below.
+ the list below. {describeCreatedKeyExpiry(created.expiresAt)}
</p>
<div className="flex items-center gap-2">
<code className="min-w-0 flex-1 truncate rounded bg-background-2 px-2 py-1 font-mono text-xs">
@@ -192,6 +222,7 @@ function KeyTable({
onDeleted: () => void;
}) {
if (keys.length === 0) return <p className="text-sm text-foreground-muted">{empty}</p>;
+ const now = new Date();
return (
<div className="overflow-hidden rounded-lg border border-border">
<table className="w-full border-collapse text-sm">
@@ -201,6 +232,7 @@ function KeyTable({
{/* The start of the key's hash, not of the key: it tells keys apart without showing one. */}
<th className="px-3 py-2 font-normal">Fingerprint</th>
<th className="px-3 py-2 font-normal">Created</th>
+ <th className="px-3 py-2 font-normal">Expires</th>
<th className="px-3 py-2" />
</tr>
</thead>
@@ -210,6 +242,7 @@ function KeyTable({
<td className="px-3 py-2 text-foreground">{key.label}</td>
<td className="px-3 py-2 font-mono text-xs text-foreground-muted">{key.keyPrefix}</td>
<td className="px-3 py-2 text-foreground-muted">{key.createdAt.slice(0, 10)}</td>
+ <ExpiryCell expiresAt={key.expiresAt} now={now} />
<td className="px-3 py-2">
<span className="flex items-center justify-end gap-1">
<CopyButton
@@ -229,6 +262,16 @@ function KeyTable({
);
}
+function ExpiryCell({ expiresAt, now }: { expiresAt: string | null; now: Date }) {
+ const text = formatKeyExpiry(expiresAt, now);
+ const expired = expiresAt !== null && new Date(expiresAt) <= now;
+ return (
+ <td className={expired ? 'px-3 py-2 text-destructive' : 'px-3 py-2 text-foreground-muted'}>
+ {text}
+ </td>
+ );
+}
+
function CopyButton({ label, read }: { label: string; read: () => Promise<string> }) {
const [copied, setCopied] = useState(false);
const copy = async () => {
diff --git a/console/apps/switch-console-desktop/src/renderer/features/settings/pages/api-keys.ts b/console/apps/switch-console-desktop/src/renderer/features/settings/pages/api-keys.ts
index 649cb2eed..77b58c641 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/settings/pages/api-keys.ts
+++ b/console/apps/switch-console-desktop/src/renderer/features/settings/pages/api-keys.ts
@@ -1,4 +1,4 @@
-import { type SwitchApiKey } from '@shared/core/switch-servers/switch-servers';
+import { type ApiKeyLifetime, type SwitchApiKey } from '@shared/core/switch-servers/switch-servers';
/** Registration keys first, then agent keys; anything else is not the person's to manage here. */
export function splitApiKeys(keys: readonly SwitchApiKey[]): {
@@ -10,3 +10,33 @@ export function splitApiKeys(keys: readonly SwitchApiKey[]): {
agent: keys.filter((key) => key.type === 'agent'),
};
}
+
+/** The lifetimes a new registration key can have, as the gateway dashboard offers them. */
+export const KEY_LIFETIMES = [
+ { value: '90', label: '90 days' },
+ { value: '365', label: '1 year' },
+ { value: 'never', label: 'Never' },
+] as const;
+
+export type KeyLifetimeChoice = (typeof KEY_LIFETIMES)[number]['value'];
+
+export const DEFAULT_KEY_LIFETIME: KeyLifetimeChoice = '90';
+
+export const NEVER_EXPIRES_WARNING =
+ 'A key that never expires keeps working until you delete it, including if it leaks. Choose an expiry unless something depends on this key and cannot be given a new one.';
+
+export function keyLifetime(choice: KeyLifetimeChoice): ApiKeyLifetime {
+ return choice === 'never' ? 'never' : Number(choice);
+}
+
+/** A key's expiry for the list: its date, "Expired" and its date once past, or "No expiry". */
+export function formatKeyExpiry(expiresAt: string | null, now: Date): string {
+ if (expiresAt === null) return 'No expiry';
+ const date = expiresAt.slice(0, 10);
+ return new Date(expiresAt) <= now ? `Expired ${date}` : date;
+}
+
+/** The expiry line shown under a key just made. */
+export function describeCreatedKeyExpiry(expiresAt: string | null): string {
+ return expiresAt === null ? 'This key does not expire.' : `Expires ${expiresAt.slice(0, 10)}.`;
+}
diff --git a/console/apps/switch-console-desktop/src/renderer/tests/settings-pages.test.ts b/console/apps/switch-console-desktop/src/renderer/tests/settings-pages.test.ts
index 5b29357c9..01987ddb1 100644
--- a/console/apps/switch-console-desktop/src/renderer/tests/settings-pages.test.ts
+++ b/console/apps/switch-console-desktop/src/renderer/tests/settings-pages.test.ts
@@ -1,5 +1,10 @@
import { describe, expect, it } from 'vitest';
-import { splitApiKeys } from '@renderer/features/settings/pages/api-keys';
+import {
+ describeCreatedKeyExpiry,
+ formatKeyExpiry,
+ keyLifetime,
+ splitApiKeys,
+} from '@renderer/features/settings/pages/api-keys';
import {
resolveSettingsTab,
type SettingsAudience,
@@ -89,6 +94,7 @@ const key = (id: string, type: string): SwitchApiKey => ({
type,
keyPrefix: 'abc',
createdAt: '2026-11-03',
+ expiresAt: null,
});
describe('API keys', () => {
@@ -102,4 +108,22 @@ describe('API keys', () => {
expect(split.registration.map((k) => k.id)).toEqual(['r', 'b']);
expect(split.agent.map((k) => k.id)).toEqual(['a']);
});
+
+ it("shows a key's expiry, past expiry, or that it has none", () => {
+ const now = new Date('2026-11-06T12:00:00Z');
+ expect(formatKeyExpiry(null, now)).toBe('No expiry');
+ expect(formatKeyExpiry('2027-02-04T12:00:00Z', now)).toBe('2027-02-04');
+ expect(formatKeyExpiry('2026-11-01T12:00:00Z', now)).toBe('Expired 2026-11-01');
+ });
+
+ it("describes a new key's expiry", () => {
+ expect(describeCreatedKeyExpiry(null)).toBe('This key does not expire.');
+ expect(describeCreatedKeyExpiry('2027-02-04T12:00:00Z')).toBe('Expires 2027-02-04.');
+ });
+
+ it('sends the chosen lifetime as days or never', () => {
+ expect(keyLifetime('90')).toBe(90);
+ expect(keyLifetime('365')).toBe(365);
+ expect(keyLifetime('never')).toBe('never');
+ });
});
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 fa3f4fa9a..9da37bffb 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
@@ -203,7 +203,9 @@ export type SwitchServerDeclaration = {
* `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.
+ * hash, which identifies it without revealing it. `expiresAt` is when the key
+ * stops working, or null when it never does (agents' own keys and the
+ * bootstrap key, and every key on a server older than key expiry).
*/
export type SwitchApiKey = {
id: string;
@@ -211,10 +213,20 @@ export type SwitchApiKey = {
type: string;
keyPrefix: string;
createdAt: string;
+ expiresAt: string | null;
};
+/** How long a new registration key works: a number of days (1–365), or never. */
+export type ApiKeyLifetime = number | 'never';
+
/** A registration key just made, with its full value. */
-export type CreatedRegistrationKey = { id: string; label: string; key: string; createdAt: string };
+export type CreatedRegistrationKey = {
+ id: string;
+ label: string;
+ key: string;
+ createdAt: string;
+ expiresAt: string | null;
+};
/** The authenticated user, as returned by `GET /gateway/auth/me`. */
export type SwitchUser = {