feat(cli): 30-day CLI login tokens with expiry picker and token roll (#12621)

* feat(cli): 30-day default CLI login tokens, expiry picker and wmill workspace login

The browser authorization page minted CLI tokens that never expired. It now
offers an expiration (30 days by default) within max_token_expiration_days.
An expired or revoked stored token gets a clear message before the CLI signs
in again, and `wmill workspace login` replaces a profile's token on demand,
revoking the previous one when the browser login created it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(cli): keep re-login output off stdout, reject a mismatched --base-url

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(cli): keep a token other profiles still use, log login port to stderr

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Ruben Fiszel
2026-11-24 11:17:57 +01:00
committed by GitHub
co-authored by Claude Opus 5.5
parent 7d5a09af83
commit e810cbb93a
9 changed files with 202 additions and 19 deletions
+107
View File
@@ -551,6 +551,106 @@ async function remove(_opts: GlobalOptions, name: string) {
await removeWorkspace(name, false, _opts);
}
const CLI_LOGIN_TOKEN_LABEL_PREFIX = "cli-login:";
// Only a token the CLI's own browser login minted is revoked: a token pasted into the profile may
// also be used elsewhere (CI, another machine), so deleting it could break more than this profile.
async function revokeCliLoginToken(token: string): Promise<boolean> {
const prefix = token.substring(0, 10);
const perPage = 100;
for (let page = 1; page <= 50; page++) {
const tokens = await wmill.listTokens({ excludeEphemeral: true, page, perPage });
const match = tokens.find((t) => t.token_prefix === prefix);
if (match) {
if (!match.label?.startsWith(CLI_LOGIN_TOKEN_LABEL_PREFIX)) {
return false;
}
await wmill.deleteToken({ tokenPrefix: prefix });
return true;
}
if (tokens.length < perPage) {
return false;
}
}
return false;
}
async function login(opts: GlobalOptions, workspaceName?: string) {
const workspace = workspaceName
? await getWorkspaceByName(workspaceName, opts.configDir)
: await getActiveWorkspace(opts);
if (!workspace) {
log.info(
colors.red.bold(
workspaceName
? `! Workspace profile ${workspaceName} does not exist locally`
: "! No active workspace profile. Add one with 'wmill workspace add'."
)
);
return process.exit(1);
}
if (
opts.baseUrl &&
new URL(opts.baseUrl).toString() !== new URL(workspace.remote).toString()
) {
log.info(
colors.red.bold(
`! --base-url ${opts.baseUrl} does not match profile ${workspace.name} (${workspace.remote}). Use 'wmill workspace add' for another instance.`
)
);
return process.exit(1);
}
let token = await tryGetLoginInfo(opts);
if (!token) {
if (!(process.stdin.isTTY ?? false)) {
log.info("Not a TTY, can't login interactively. Pass the token in --token");
return process.exit(1);
}
log.info(
`Signing in again to ${workspace.workspaceId} on ${workspace.remote} for profile ${workspace.name}`
);
token = await loginInteractive(workspace.remote);
}
if (!token) {
log.info(colors.red.bold("! Login failed, the profile was left unchanged."));
return process.exit(1);
}
const remote = workspace.remote.substring(0, workspace.remote.length - 1);
setClient(token, remote);
try {
await wmill.whoami({ workspace: workspace.workspaceId });
} catch (e) {
log.info(
colors.red.bold(
`! The new token cannot access workspace ${workspace.workspaceId}, the profile was left unchanged.`
)
);
throw e;
}
const oldToken = workspace.token;
await addWorkspace({ ...workspace, token }, opts);
// `wmill instance pull --include-workspaces` copies one token into the instance profile and
// every workspace profile it creates: revoking it would sign all the others out.
const { allInstances } = await import("../instance/instance.ts");
const stillReferenced =
(await allWorkspaces(opts.configDir)).some((w) => w.token === oldToken) ||
(await allInstances()).some((i) => i.token === oldToken);
if (oldToken && oldToken !== token && !stillReferenced) {
try {
if (await revokeCliLoginToken(oldToken)) {
log.info("Revoked the profile's previous token.");
}
} catch {
// Already expired or deleted, or owned by another user: nothing left to revoke.
}
}
log.info(colors.green.underline(`Successfully signed in again for profile ${workspace.name}`));
}
async function whoami(_opts: GlobalOptions) {
const whoamiInfo = await requireLogin(_opts);
log.info(JSON.stringify(whoamiInfo, null, 2));
@@ -937,6 +1037,13 @@ const command = new Command()
.description("Remove a workspace")
.arguments("<workspace_name:string>")
.action(remove as any)
.command("login")
.complete("workspace", async () => (await allWorkspaces()).map((x) => x.name))
.description(
"Sign in again for a workspace profile (default: the active one) and replace its token, e.g. to extend one about to expire. The previous token is revoked when the CLI's browser login created it."
)
.arguments("[workspace_name:string:workspace]")
.action(login as any)
.command("whoami")
.description("Show the currently active user")
.action(whoami as any)
+15 -7
View File
@@ -122,19 +122,27 @@ export async function requireLogin(
return process.exit(1);
}
log.infoStderr(
"! Could not reach API given existing credentials. Attempting to reauth..."
);
const isUnauthorized = error && typeof error === "object" &&
"name" in error && (error as { name: unknown }).name === "ApiError" &&
(error as { status?: number }).status === 401;
log.infoStderr(colors.yellow(
isUnauthorized
? `! The token of workspace profile '${workspace.name}' has expired or was revoked. Sign in again to continue.`
: "! Could not reach API given existing credentials. Attempting to reauth..."
));
const newToken = await loginInteractive(workspace.remote);
if (!newToken) {
throw new Error("Unauthorized: Could not authenticate with the provided credentials");
throw new Error(
`Unauthorized: Could not authenticate with the provided credentials. Run 'wmill workspace login ${workspace.name}' in a terminal to sign in again.`
);
}
// Update workspace token
// Removed silently first: `addWorkspace` logs the update to stdout, which would land in the
// output of the command being run (e.g. `wmill variable get … > file`).
const { removeWorkspace, addWorkspace } = await import("../commands/workspace/workspace.ts");
removeWorkspace(workspace.name, false, opts);
await removeWorkspace(workspace.name, true, opts);
workspace.token = newToken;
addWorkspace(workspace, opts);
await addWorkspace(workspace, opts);
setClient(
newToken,
+1 -1
View File
@@ -97,7 +97,7 @@ export async function browserLogin(
// Start the server
server.listen(port, () => {
console.log(`Listening on port ${port}`);
log.infoStderr(`Listening on port ${port}`);
});
});
}
+1
View File
@@ -9703,6 +9703,7 @@ workspace related commands
- \`--create-workspace-name <workspace_name:string>\` - Specify the workspace name. Ignored if --create is not specified or the workspace already exists. Will default to the workspace id.
- \`--create-username <username:string>\` - Specify your own username in the newly created workspace. Ignored if --create is not specified, the workspace already exists or automatic username creation is enabled on the instance.
- \`workspace remove <workspace_name:string>\` - Remove a workspace
- \`workspace login [workspace_name:string:workspace]\` - Sign in again for a workspace profile (default: the active one) and replace its token, e.g. to extend one about to expire. The previous token is revoked when the CLI's browser login created it.
- \`workspace whoami\` - Show the currently active user
- \`workspace list\` - List local workspace profiles
- \`workspace list-remote\` - List workspaces on the remote server that you have access to
+8 -5
View File
@@ -37,11 +37,14 @@ Symbols, not line numbers, are cited: they drift less.
so until `whoami` answers that browser still renders as its own last user.
- **`tokens/impersonate`** (superadmin) returns a multi-use token and sets no cookie.
- **`max_token_expiration_days`** caps `POST /users/tokens/create` and `tokens/impersonate`, by
shortening the stored expiration (`cap_token_expiration`), never by refusing: the CLI
authorization page, `wmill user create-token` and the editor's language-server token all pick a
lifetime without reading the setting, and CLIs already installed never will. The CLI signs in
again on its own when its token expires, which is why the authorization page labels it
`cli-login:<username>`, reserved in `is_user_token` so its expiry does not email the user. A token
shortening the stored expiration (`cap_token_expiration`), never by refusing: `wmill user
create-token` and the editor's language-server token pick a lifetime without reading the
setting, and CLIs already installed never will. The CLI authorization page (`/user/cli`) reads
it only to offer the lifetimes that would be kept (30 days by default). The CLI signs in again
on its own when its token expires, which is why the authorization page labels it
`cli-login:<username>`, reserved in `is_user_token` so its expiry does not email the user.
`wmill workspace login` replaces a profile's token before it expires, and revokes the previous
one only when that label shows the browser login minted it. A token
owned by a service account is exempt: one in the workspace the token names, or in any workspace
for a workspace-less token (for `tokens/impersonate`, the impersonated account). Any workspace
admin can therefore create and impersonate a service account to hold an uncapped token, so the
@@ -1,25 +1,72 @@
<script lang="ts">
import { untrack } from 'svelte'
import { UserService } from '$lib/gen'
import { onMount, untrack } from 'svelte'
import { SettingService, UserService } from '$lib/gen'
import { page } from '$app/state'
import CenteredModal from '$lib/components/CenteredModal.svelte'
import { Button } from '$lib/components/common'
import { userStore, workspaceStore } from '$lib/stores'
import Select from '$lib/components/select/Select.svelte'
import { userStore, usersWorkspaceStore, workspaceStore } from '$lib/stores'
import { parseMaxTokenExpirationDays } from '$lib/tokenExpiration'
let port = $state(Number(page.url.searchParams.get('port')))
let host: string = page.url.searchParams.get('host') || 'localhost'
let scheme: string = page.url.searchParams.get('scheme') || 'http'
port = untrack(() => port) == 0 || Number.isNaN(untrack(() => port)) ? 80 : untrack(() => port)
const DEFAULT_DAYS = 30
const CHOICES_DAYS = [1, 7, 30, 90, 365]
const daysLabel = (days: number) => (days === 1 ? '1 day' : `${days} days`)
// `max_token_expiration_days`: the server shortens a longer token itself, so the picker only
// offers what it would keep. A service account is exempt from it, as on the token form.
let maxExpirationDays = $state<number | undefined>(undefined)
onMount(async () => {
try {
maxExpirationDays = parseMaxTokenExpirationDays(
await SettingService.getGlobal({ key: 'max_token_expiration_days' })
)
} catch {}
})
const ceilingDays = $derived(
($usersWorkspaceStore?.workspaces ?? []).some((w) => w.is_service_account)
? undefined
: maxExpirationDays
)
const expirationItems = $derived(
ceilingDays == undefined
? [
...CHOICES_DAYS.map((d) => ({ label: daysLabel(d), value: d })),
{ label: 'No expiration', value: 0 }
]
: [
...CHOICES_DAYS.filter((d) => d < ceilingDays).map((d) => ({
label: daysLabel(d),
value: d
})),
{ label: `${daysLabel(ceilingDays)} (maximum)`, value: ceilingDays }
]
)
// 0 stands for no expiration, since the Select clears to undefined.
let pickedDays = $state<number | undefined>(undefined)
const expirationDays = $derived.by(() => {
const picked = pickedDays ?? DEFAULT_DAYS
if (ceilingDays == undefined) return picked
return picked === 0 || picked > ceilingDays ? ceilingDays : picked
})
async function authorizeToken(): Promise<void> {
const username = $userStore?.username
// `cli-login:` is reserved in `is_user_token` (windmill-common): the CLI signs in again on
// its own once this token expires, so it must not email the user about it.
const label = `cli-login:${username ?? ''}`
const expiration =
expirationDays === 0
? undefined
: new Date(Date.now() + expirationDays * 24 * 60 * 60 * 1000).toISOString()
const newToken = await UserService.createToken({
requestBody: {
label,
expiration: undefined
expiration
}
})
@@ -33,8 +80,22 @@
<p class="text-center text-lg mb-6">
Token will be posted to {host == 'localhost' ? 'your local machine' : host} to port {port}
</p>
<div class="flex flex-col gap-1">
<span class="text-xs font-semibold text-emphasis">Token expires in</span>
<Select
bind:value={() => expirationDays, (v) => (pickedDays = v)}
inputClass="w-full"
items={expirationItems}
/>
<p class="text-2xs text-hint">
{#if ceilingDays != undefined}
This instance limits tokens to {daysLabel(ceilingDays)}.
{/if}
Once it expires, the CLI asks you to sign in again.
</p>
</div>
<div class="flex flex-row justify-around pt-4 gap-x-1">
<Button variant="default" destructive size="lg" href="/">Decline</Button>
<Button variant="accent" size="lg" on:click={authorizeToken}>Authorize</Button>
<Button variant="default" destructive unifiedSize="lg" href="/">Decline</Button>
<Button variant="accent" unifiedSize="lg" onClick={authorizeToken}>Authorize</Button>
</div>
</CenteredModal>
@@ -823,6 +823,7 @@ workspace related commands
- `--create-workspace-name <workspace_name:string>` - Specify the workspace name. Ignored if --create is not specified or the workspace already exists. Will default to the workspace id.
- `--create-username <username:string>` - Specify your own username in the newly created workspace. Ignored if --create is not specified, the workspace already exists or automatic username creation is enabled on the instance.
- `workspace remove <workspace_name:string>` - Remove a workspace
- `workspace login [workspace_name:string:workspace]` - Sign in again for a workspace profile (default: the active one) and replace its token, e.g. to extend one about to expire. The previous token is revoked when the CLI's browser login created it.
- `workspace whoami` - Show the currently active user
- `workspace list` - List local workspace profiles
- `workspace list-remote` - List workspaces on the remote server that you have access to
+1
View File
@@ -4936,6 +4936,7 @@ workspace related commands
- \`--create-workspace-name <workspace_name:string>\` - Specify the workspace name. Ignored if --create is not specified or the workspace already exists. Will default to the workspace id.
- \`--create-username <username:string>\` - Specify your own username in the newly created workspace. Ignored if --create is not specified, the workspace already exists or automatic username creation is enabled on the instance.
- \`workspace remove <workspace_name:string>\` - Remove a workspace
- \`workspace login [workspace_name:string:workspace]\` - Sign in again for a workspace profile (default: the active one) and replace its token, e.g. to extend one about to expire. The previous token is revoked when the CLI's browser login created it.
- \`workspace whoami\` - Show the currently active user
- \`workspace list\` - List local workspace profiles
- \`workspace list-remote\` - List workspaces on the remote server that you have access to
@@ -828,6 +828,7 @@ workspace related commands
- `--create-workspace-name <workspace_name:string>` - Specify the workspace name. Ignored if --create is not specified or the workspace already exists. Will default to the workspace id.
- `--create-username <username:string>` - Specify your own username in the newly created workspace. Ignored if --create is not specified, the workspace already exists or automatic username creation is enabled on the instance.
- `workspace remove <workspace_name:string>` - Remove a workspace
- `workspace login [workspace_name:string:workspace]` - Sign in again for a workspace profile (default: the active one) and replace its token, e.g. to extend one about to expire. The previous token is revoked when the CLI's browser login created it.
- `workspace whoami` - Show the currently active user
- `workspace list` - List local workspace profiles
- `workspace list-remote` - List workspaces on the remote server that you have access to