Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

pair --ttl keeps a code open up to a day; token create makes CI tokens

milind-sonic831e5d3fbd3
diff --git a/docs/deploy-vps.md b/docs/deploy-vps.md
index cf6a02ee9d..80923f5a40 100644
--- a/docs/deploy-vps.md
+++ b/docs/deploy-vps.md
@@ -199,7 +199,7 @@ open or scan: https://c-7f3a9c.openmausbot.com/pair#code=RR8Y-BLR6-H939
- **The desktop app:** copy the link, then in the app's **Server** menu choose **Add Server from Copied Pairing Link…**. The menu switches between your own machine and every server you added.
- **The phone:** scan the QR code from the iOS app's pairing screen, or paste the whole link into its address field. The phone can chat, approve, and read; creating bots, changing models, and connecting apps stay with you in the server's UI.
-Worth knowing: a code works **once** and expires after **five minutes**; the link only works on that address (typing the code by hand: open `…/pair` and enter it); ten wrong codes in a minute from one address pause pairing for that address for a minute; `--client` mints a code for a device that may chat and approve but not change settings or pair others.
+Worth knowing: a code works **once** and expires after **five minutes** (`--ttl 24h` keeps it open up to a day, for a device you set up later; it is still single use, and a server restart ends every open code); the link only works on that address (typing the code by hand: open `…/pair` and enter it); ten wrong codes in a minute from one address pause pairing for that address for a minute; `--client` mints a code for a device that may chat and approve but not change settings or pair others.
## Manage devices
@@ -330,7 +330,7 @@ Read this before putting anything else in front of the server.
**"forbidden: pair this device to use the server remotely" / "this request came through a proxy".** Expected before pairing, and for tools that call the API without a session. Pair the device. Scripts send `Authorization: Bearer <token>` with the token from the pairing response instead of a cookie.
-**Pairing code refused.** It expired (five minutes) or was used. Mint a new one. "Too many failed pairing attempts" means wait a minute.
+**Pairing code refused.** It expired (five minutes, or its `--ttl`) or was used. Mint a new one. "Too many failed pairing attempts" means wait a minute.
**A bot says the engine is not signed in.** Sign that engine in again on the server.
diff --git a/docs/headless-cli.md b/docs/headless-cli.md
index e2f69b968f..457c75e1c1 100644
--- a/docs/headless-cli.md
+++ b/docs/headless-cli.md
@@ -34,7 +34,9 @@ openmausbot connect https://maus.example.com --code ABCD1234 --out ~/.openmausbo
openmausbot doctor --url https://maus.example.com --token-file ~/.openmausbot-token
```
-Get the code in the app under **Settings → Phone → Set up a phone**. On this
+Get the code in the app under **Settings → Phone → Set up a phone**, or on
+the server with `openmausbot pair --client --ttl 24h` (a code lasts five
+minutes unless `--ttl` says otherwise, at most a day, and works once). On this
computer's own server, `connect` makes the code itself (`--client` gives a
token that can chat but not change settings). The token goes to a file only
you can read, and is never printed. Pass it with `--token-file FILE` or
@@ -42,13 +44,28 @@ you can read, and is never printed. Pass it with `--token-file FILE` or
read by other programs. A token is never sent while the command is still
looking for a server: with a token, name the server.
+For CI, make an access token that ends on a date you choose:
+
+```sh
+openmausbot token create "Nightly CI" --scope client --expires 90d --out ci-token # on the server, or with an admin token
+openmausbot token list # name, scope, end date, last used (never the token)
+openmausbot token revoke ID # it stops working at once
+```
+
+A `connect` session renews itself while it is used, up to 180 days; an access
+token never renews and ends on its date. `--expires` is at most the server's
+session limit (180 days unless `OMB_SESSION_MAX_DAYS` says otherwise), and
+`--scope client`, the default, can chat and answer approvals but not change
+settings. Tokens are listed and revoked like any session (`openmausbot
+sessions`, and Settings), and the token itself is written only to `--out`.
+
## Output and exit codes
Without `--json` you get plain lines. With `--json` you get exactly one JSON
document on stdout, a failure included (`{ "ok": false, "error", "hint",
"exitCode" }`). Progress goes to stderr as one JSON object per line; `--quiet`
drops it. Everything printed, either way, has secrets removed (the same
-redaction the transcript uses). Durations are written `90`, `90s`, `5m` or `2h`.
+redaction the transcript uses). Durations are written `90`, `90s`, `5m`, `2h` or `30d`.
| Exit code | Meaning |
|---|---|
@@ -81,6 +98,7 @@ one of its conversations.
| `team apply FILE`, `team export --out FILE` | Makes the workspace match a team file, or writes one (below). |
| `engine set KIND`, `engine list` | Gives the workspace an engine key without a screen (below). |
| `connect [URL]` | Gets a token for a workspace elsewhere. |
+| `token create NAME`, `token list`, `token revoke ID` | Access tokens for CI that end on their date (above). |
| `new-bot`, `new-channel`, `set-model`, `edit` | Make a bot or a room, change a bot's model, rewrite an earlier message. |
| `mcp` | The OpenMausBot MCP server on stdin and stdout ([docs/mcp-server.md](mcp-server.md)). |
diff --git a/server/cli-pair.test.ts b/server/cli-pair.test.ts
index f37613952a..02e9fb4913 100644
--- a/server/cli-pair.test.ts
+++ b/server/cli-pair.test.ts
@@ -203,3 +203,20 @@ describe("the phone-app link `openmausbot pair` prints", () => {
expect(printed()).not.toContain("phone app:");
});
});
+
+describe("pair --ttl", () => {
+ it("asks the server to keep the code open that long, skips the phone questions, and prints the day it ends", async () => {
+ const day = Date.now() + 86_400_000;
+ fetchMock.mockImplementation(async (input, init) => {
+ const url = String(input);
+ if (url.endsWith("/api/health")) return Response.json({ app: "openmausbot", pid: 12345 });
+ if (url.endsWith("/api/auth/pairing") && init?.method === "POST") return Response.json({ code, expiresAt: day, url: null, hint: "set OMB_PUBLIC_URL" });
+ throw new Error(`Unexpected fixture request: ${url}`);
+ });
+ expect(await runPair({ ...options, pairTtlMs: 86_400_000 })).toBe(0);
+ const posted = fetchMock.mock.calls.find(([, init]) => init?.method === "POST");
+ expect(JSON.parse(String(posted![1]!.body))).toEqual({ ttlMs: 86_400_000 });
+ expect(mocks.ui.choose).not.toHaveBeenCalled();
+ expect(vi.mocked(console.log).mock.calls.map(([line]) => String(line)).join("\n")).toContain(`expires: ${new Date(day).toLocaleString()} (single use)`);
+ });
+});
diff --git a/server/cli-pairing.ts b/server/cli-pairing.ts
index 0c288fc13c..604fa64a53 100644
--- a/server/cli-pairing.ts
+++ b/server/cli-pairing.ts
@@ -13,7 +13,9 @@ export function pairingBlock(input: {
hint?: string | null;
phone?: "ios" | "android";
}): string {
- const lines = [`pairing code: ${input.code}`, `expires: ${new Date(input.expiresAt).toLocaleTimeString()} (single use)`];
+ const expires = new Date(input.expiresAt);
+ const when = input.expiresAt - Date.now() > 12 * 3_600_000 ? expires.toLocaleString() : expires.toLocaleTimeString();
+ const lines = [`pairing code: ${input.code}`, `expires: ${when} (single use)`];
if (input.localUrl) lines.push(`this computer: ${input.localUrl}`);
if (!input.url && !input.inviteUrl) {
lines.push(`open: /pair on the address you use for this server, and type the code`);
@@ -59,3 +61,15 @@ export function qrToString(text: string): string {
});
return out;
}
+
+export function formatSessions(sessions: Array<{ id: string; label: string; scopes: string[]; lastSeenAt: number; expiresAt: number; token?: true }>, now = Date.now()): string {
+ const age = (ms: number) => {
+ const m = Math.max(0, Math.floor((now - ms) / 60_000));
+ return m < 1 ? "just now" : m < 60 ? `${m} min ago` : m < 1440 ? `${Math.round(m / 60)} h ago` : `${Math.round(m / 1440)} d ago`;
+ };
+ const rows = sessions.map((s) => [s.id, `${s.label || "(unnamed)"}${s.token ? " (token)" : ""}`, s.scopes.includes("admin") ? "admin" : "client", age(s.lastSeenAt), new Date(s.expiresAt).toISOString().slice(0, 10)]);
+ const head = ["id", "device", "scope", "last seen", "expires"];
+ const widths = head.map((h, i) => Math.max(h.length, ...rows.map((r) => r[i].length)));
+ const line = (r: string[]) => r.map((c, i) => c.padEnd(widths[i])).join(" ");
+ return [line(head), ...rows.map(line), "", "revoke one with: openmausbot sessions revoke <id>"].join("\n");
+}
diff --git a/server/cli-usage.ts b/server/cli-usage.ts
index 11b19eaf86..26226a39c2 100644
--- a/server/cli-usage.ts
+++ b/server/cli-usage.ts
@@ -13,6 +13,7 @@ export const HEADLESS_USAGE = `Drive a running workspace (scripts, CI, other age
openmausbot team apply FILE make the workspace match a team file (team export writes one)
openmausbot engine set claude --key-env ANTHROPIC_API_KEY give it an engine without a screen
openmausbot connect URL --code CODE --out FILE get a token for a workspace elsewhere
+ openmausbot token create NAME --out FILE [--expires 90d] a token for CI that ends on its date (token list, token revoke ID)
openmausbot new-bot | new-channel | set-model | edit | mcp
Server: --url URL (or OPENMAUSBOT_URL), --port N (or OMB_PORT), else this computer's.
@@ -26,7 +27,7 @@ export const USAGE = `openmausbot — your team of AI bots, ready in a few steps
openmausbot start [the same options as serve]
openmausbot serve [--port 8799] [--data-dir DIR] [--label NAME]
[--public-url https://host] [--tailscale | --tunnel | --domain HOST] [--no-pair]
- openmausbot pair [--label NAME] [--client] [--phone ios|android]
+ openmausbot pair [--label NAME] [--client] [--phone ios|android] [--ttl 24h]
[--public-url https://host]
openmausbot sessions [revoke ID]
openmausbot status
@@ -46,7 +47,8 @@ export const USAGE = `openmausbot — your team of AI bots, ready in a few steps
setup choose AI access and optional phone access; keep existing bots and chats
start same as openmausbot: use your saved settings and open the workspace
serve starts the server without prompts and prints a pairing link + QR code
-pair mints a pairing code against a running server (--client: chat only)
+pair mints a pairing code against a running server (--client: chat only;
+ --ttl keeps it open up to 24h, still single use)
sessions lists paired devices; "sessions revoke ID" signs one out
status what the server says about itself
login signs this machine in to an OpenMausBot account (an emailed code)
diff --git a/server/cli.test.ts b/server/cli.test.ts
index 040c8f3437..bc63e2da2c 100644
--- a/server/cli.test.ts
+++ b/server/cli.test.ts
@@ -5,8 +5,8 @@ import { dirname, join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-import { applyStartupPreferences, formatSessions, parseArgs, runAccess, runLogin, runOnboardingCommand, serverEntry, type CliOptions, verifyPhoneEndpoint } from "./cli.ts";
-import { browserSignInLines, pairingBlock, qrToString } from "./cli-pairing.ts";
+import { applyStartupPreferences, parseArgs, runAccess, runLogin, runOnboardingCommand, serverEntry, type CliOptions, verifyPhoneEndpoint } from "./cli.ts";
+import { browserSignInLines, formatSessions, pairingBlock, qrToString } from "./cli-pairing.ts";
import { readAdminActivityRange } from "./admin-activity.ts";
import { SetupCancelled } from "./cli-prompts.ts";
import { removeTempDir, waitForExit } from "./testing/cleanup.ts";
@@ -25,6 +25,10 @@ describe("openmausbot command line", () => {
expect(serve).toMatchObject({ command: "serve", port: 9001, dataDir: resolve("/tmp/x"), label: "cab mini", tailscale: true, pair: false });
expect(parseArgs(["pair", "--client", "--public-url", "https://h/"], {})).toMatchObject({ command: "pair", client: true, publicUrl: "https://h" });
expect(parseArgs(["sessions", "revoke", "abc"], {})).toMatchObject({ command: "sessions", revoke: "abc" });
+ expect(parseArgs(["pair", "--client", "--ttl", "24h"], {})).toMatchObject({ command: "pair", client: true, pairTtlMs: 86_400_000 });
+ expect(parseArgs(["pair", "--ttl", "2d"], {})).toEqual({ error: "--ttl must be a duration from 1m to 24h, such as 90, 90s, 5m or 2h" });
+ expect(parseArgs(["pair", "--ttl", "30s"], {})).toMatchObject({ error: expect.stringContaining("from 1m to 24h") });
+ expect(parseArgs(["serve", "--ttl", "1h"], {})).toEqual({ error: 'unknown argument "--ttl"' });
expect(parseArgs(["fleet", "create", "acme", "--admin", "[email protected]", "--member", "@acme.test", "--member", "[email protected]", "--cap", "40", "--memory", "1G", "--dry-run"], {})).toMatchObject({
command: "fleet", fleetAction: "create", slug: "acme", admins: ["[email protected]"], members: ["@acme.test", "[email protected]"], cap: 40, memory: "1G", dryRun: true,
});
@@ -141,6 +145,7 @@ describe("openmausbot command line", () => {
expect(table).toMatch(/a1\s+My MacBook\s+admin\s+just now/);
expect(table).toMatch(/b2\s+\(unnamed\)\s+client\s+3 h ago/);
expect(table).toContain("sessions revoke <id>");
+ expect(formatSessions([{ id: "c3", label: "Nightly CI", scopes: ["client"], lastSeenAt: now, expiresAt: now, token: true }], now)).toContain("Nightly CI (token)");
});
it("finds the server next to itself: bundled index.js in a package, the TypeScript source in a checkout", () => {
diff --git a/server/cli.ts b/server/cli.ts
index 466d6f87d3..99caa59778 100644
--- a/server/cli.ts
+++ b/server/cli.ts
@@ -38,7 +38,8 @@ import { explainTailscaleFailure, tailscaleServe, tailscaleServeOff, tailscaleSt
import { defaultSetupIo, SetupCancelled, type SetupIo } from "./cli-prompts.ts";
import { HEADLESS_VERB_NAMES, USAGE } from "./cli-usage.ts";
import { normalizePhoneOrigin, phonePairingInstructions, runPhoneSetup } from "./cli-phone-setup.ts";
-import { browserSignInLines, pairingBlock } from "./cli-pairing.ts";
+import { browserSignInLines, formatSessions, pairingBlock } from "./cli-pairing.ts";
+import { parseDuration } from "./headless/args.ts";
import type { AppConfig } from "./config.ts";
import {
cleanupTunnelOrigin,
@@ -108,6 +109,8 @@ export interface CliOptions {
open?: boolean;
guided?: boolean;
phone?: "ios" | "android";
+ /** `pair --ttl 24h`: how long the code stays open. */
+ pairTtlMs?: number;
}
const COMMANDS = ["setup", "start", "serve", "pair", "sessions", "status", "login", "logout", "access", "service", "browser", "fleet", "help", "--help", "-h"];
@@ -157,6 +160,7 @@ export function parseArgs(argv: string[], env: NodeJS.ProcessEnv = process.env):
if (kind !== "ios" && kind !== "android") return { error: "--phone takes ios or android" };
options.phone = kind;
}
+ else if (options.command === "pair" && arg === "--ttl") options.pairTtlMs = parseDuration(value(), "--ttl", { min: 60_000 });
else if (arg === "--no-pair") options.pair = false;
else if (arg === "--no-open") options.open = false;
else if (arg === "--local") options.local = true;
@@ -345,10 +349,8 @@ async function showPhonePairing(options: CliOptions, origin: string | undefined,
return true;
}
-async function mintPairing(port: number, options: { label?: string; client?: boolean; publicUrl?: string; phone?: "ios" | "android"; guided?: boolean }): Promise<string> {
- const request: { label?: string; scopes?: string[] } = {};
- if (options.label) request.label = options.label;
- if (options.client) request.scopes = ["client"];
+async function mintPairing(port: number, options: { label?: string; client?: boolean; publicUrl?: string; phone?: "ios" | "android"; guided?: boolean; ttlMs?: number }): Promise<string> {
+ const request = { ...(options.label ? { label: options.label } : {}), ...(options.client ? { scopes: ["client"] } : {}), ...(options.ttlMs ? { ttlMs: options.ttlMs } : {}) };
const { status, body } = await api(port, "/api/auth/pairing", { method: "POST", body: JSON.stringify(request) });
if (refusedAsService(status, body)) throw new Error(SERVICE_TRUST_HELP);
if (status !== 200) throw new Error(`server refused to mint a pairing code: ${typeof body?.error === "string" ? body.error : status}`);
@@ -366,7 +368,7 @@ export async function runPair(options: CliOptions): Promise<number> {
console.error(`no OpenMausBot server on http://127.0.0.1:${options.port}; start one with \`openmausbot serve\` or set OMB_PORT`);
return 1;
}
- if (process.stdin.isTTY && process.stdout.isTTY && !options.label && !options.client) {
+ if (process.stdin.isTTY && process.stdout.isTTY && !options.label && !options.client && !options.pairTtlMs) {
const advertised = await api(options.port, "/api/auth/pairing");
let launch = options;
let origin = options.publicUrl ?? (typeof advertised.body?.publicUrl === "string" ? advertised.body.publicUrl : undefined);
@@ -397,7 +399,7 @@ export async function runPair(options: CliOptions): Promise<number> {
return 130;
}
}
- console.log(await mintPairing(options.port, { label: options.label, client: options.client, publicUrl: options.publicUrl, phone: options.phone }));
+ console.log(await mintPairing(options.port, { label: options.label, client: options.client, publicUrl: options.publicUrl, phone: options.phone, ttlMs: options.pairTtlMs }));
if (options.client) console.log("(client scope: chat and approvals only; cannot change settings or pair others)");
return 0;
}
@@ -442,18 +444,6 @@ export async function runSessions(options: CliOptions): Promise<number> {
return 0;
}
-export function formatSessions(sessions: Array<{ id: string; label: string; scopes: string[]; lastSeenAt: number; expiresAt: number }>, now = Date.now()): string {
- const age = (ms: number) => {
- const m = Math.max(0, Math.floor((now - ms) / 60_000));
- return m < 1 ? "just now" : m < 60 ? `${m} min ago` : m < 1440 ? `${Math.round(m / 60)} h ago` : `${Math.round(m / 1440)} d ago`;
- };
- const rows = sessions.map((s) => [s.id, s.label || "(unnamed)", s.scopes.includes("admin") ? "admin" : "client", age(s.lastSeenAt), new Date(s.expiresAt).toISOString().slice(0, 10)]);
- const head = ["id", "device", "scope", "last seen", "expires"];
- const widths = head.map((h, i) => Math.max(h.length, ...rows.map((r) => r[i].length)));
- const line = (r: string[]) => r.map((c, i) => c.padEnd(widths[i])).join(" ");
- return [line(head), ...rows.map(line), "", "revoke one with: openmausbot sessions revoke <id>"].join("\n");
-}
-
export async function runStatus(options: CliOptions, io: CliIo = defaultIo()): Promise<number> {
let code = 0;
try {
diff --git a/server/headless/args.test.ts b/server/headless/args.test.ts
index 20490ccc98..fcff173213 100644
--- a/server/headless/args.test.ts
+++ b/server/headless/args.test.ts
@@ -40,10 +40,10 @@ describe("parseCommand", () => {
});
it("knows which verbs change something", () => {
- for (const verb of ["send", "run", "interrupt", "team apply", "engine set"]) expect(MUTATING_VERBS.has(verb), verb).toBe(true);
+ for (const verb of ["send", "run", "interrupt", "team apply", "engine set", "token create", "token revoke"]) expect(MUTATING_VERBS.has(verb), verb).toBe(true);
for (const verb of ["doctor", "bots", "wait", "messages", "export", "events", "team export", "engine list"]) expect(MUTATING_VERBS.has(verb), verb).toBe(false);
expect([...HEADLESS_VERBS].sort()).toEqual(["bots", "channels", "connect", "doctor", "edit", "engine", "events", "export", "interrupt", "mcp",
- "messages", "models", "new-bot", "new-channel", "run", "send", "send-channel", "set-model", "team", "wait"]);
+ "messages", "models", "new-bot", "new-channel", "run", "send", "send-channel", "set-model", "team", "token", "wait"]);
});
});
@@ -55,6 +55,9 @@ describe("durations, sizes, counts and choices", () => {
expect(parseDuration("2h", "--timeout")).toBe(7_200_000);
expect(parseDuration("0", "--wait-idle", { min: 0 })).toBe(0);
for (const bad of ["0", "25h", "soon", "-5", "5d"]) expect(usage(() => parseDuration(bad, "--timeout")).message).toBe("--timeout must be a duration from 1s to 24h, such as 90, 90s, 5m or 2h");
+ expect(parseDuration("90d", "--expires", { max: 3_650 * 86_400_000 })).toBe(90 * 86_400_000);
+ expect(usage(() => parseDuration("30m", "--expires", { min: 3_600_000, max: 3_650 * 86_400_000 })).message)
+ .toBe("--expires must be a duration from 1h to 3650d, such as 12h, 30d or 90d");
});
it("reads sizes, counts and one-of choices", () => {
diff --git a/server/headless/args.ts b/server/headless/args.ts
index 0c9a396347..fb46abf03c 100644
--- a/server/headless/args.ts
+++ b/server/headless/args.ts
@@ -105,13 +105,16 @@ const VERBS: Record<string, { options: ParseArgsOptionsConfig; positionals: numb
positionals: 1,
},
mcp: { options: {}, positionals: 0 },
+ "token create": { options: { out: { type: "string" }, scope: { type: "string" }, expires: { type: "string" }, force: { type: "boolean" } }, positionals: 1 },
+ "token list": { options: {}, positionals: 0 },
+ "token revoke": { options: {}, positionals: 1 },
};
export const HEADLESS_VERBS: ReadonlySet<string> = new Set(Object.keys(VERBS).map((verb) => verb.split(" ")[0]!));
/** Verbs that change something; control-omb refuses them on a discovered server. */
export const MUTATING_VERBS: ReadonlySet<string> = new Set([
- "send", "send-channel", "run", "interrupt", "new-bot", "new-channel", "set-model", "edit", "team apply", "engine set",
+ "send", "send-channel", "run", "interrupt", "new-bot", "new-channel", "set-model", "edit", "team apply", "engine set", "token create", "token revoke",
]);
export type Flags = Record<string, string | boolean | string[] | undefined>;
@@ -122,15 +125,17 @@ export interface ParsedCommand {
positionals: string[];
}
+const SUBCOMMANDS = new Map([["team", ["apply", "export"]], ["engine", ["set", "list"]], ["token", ["create", "list", "revoke"]]]);
+
/** Strict: an unknown flag or a missing value is a usage error (exit 2). */
export function parseCommand(argv: readonly string[]): ParsedCommand {
const [head, ...rest] = argv;
if (!head) throw usageError("name a verb", "run openmausbot help");
let verb = head;
let args = rest;
- if (head === "team" || head === "engine") {
+ const actions = SUBCOMMANDS.get(head);
+ if (actions) {
const action = rest[0];
- const actions = head === "team" ? ["apply", "export"] : ["set", "list"];
if (!action || !actions.includes(action)) {
if (action === "--help" || action === "-h") return { verb: head, flags: { help: true }, positionals: [] };
throw usageError(`${head} needs one of: ${actions.join(", ")}`, `run openmausbot help ${head}`);
@@ -164,23 +169,25 @@ export function requiredFlag(flags: Flags, name: string): string {
return value;
}
-const DURATION = /^(\d+(?:\.\d+)?)(ms|s|m|h)?$/;
-const UNIT: Record<string, number> = { ms: 1, s: 1_000, m: 60_000, h: 3_600_000 };
+const DURATION = /^(\d+(?:\.\d+)?)(ms|s|m|h|d)?$/;
+const DAY = 24 * 3_600_000;
+const UNIT: Record<string, number> = { ms: 1, s: 1_000, m: 60_000, h: 3_600_000, d: DAY };
-/** `90`, `90s`, `5m`, `2h` (a bare number is seconds) to milliseconds. */
+/** `90`, `90s`, `5m`, `2h`, `30d` (a bare number is seconds) to milliseconds. */
export function parseDuration(raw: string, name: string, bounds: { min?: number; max?: number } = {}): number {
const match = DURATION.exec(raw.trim());
const min = bounds.min ?? 1_000;
- const max = bounds.max ?? 24 * 3_600_000;
+ const max = bounds.max ?? DAY;
const ms = match ? Math.round(Number(match[1]) * UNIT[match[2] ?? "s"]!) : NaN;
if (!Number.isFinite(ms) || ms < min || ms > max) {
- throw usageError(`${name} must be a duration from ${describeMs(min)} to ${describeMs(max)}, such as 90, 90s, 5m or 2h`);
+ throw usageError(`${name} must be a duration from ${describeMs(min)} to ${describeMs(max)}, such as ${max > DAY ? "12h, 30d or 90d" : "90, 90s, 5m or 2h"}`);
}
return ms;
}
export const describeMs = (ms: number): string =>
- ms === 0 ? "0s" : ms % 3_600_000 === 0 ? `${ms / 3_600_000}h` : ms % 60_000 === 0 ? `${ms / 60_000}m` : ms % 1_000 === 0 ? `${ms / 1_000}s` : `${ms}ms`;
+ ms === 0 ? "0s" : ms > DAY && ms % DAY === 0 ? `${ms / DAY}d` : ms % 3_600_000 === 0 ? `${ms / 3_600_000}h`
+ : ms % 60_000 === 0 ? `${ms / 60_000}m` : ms % 1_000 === 0 ? `${ms / 1_000}s` : `${ms}ms`;
const SIZE = /^(\d+(?:\.\d+)?)\s*(b|kb|mb|gb)?$/i;
const SIZE_UNIT: Record<string, number> = { b: 1, kb: 1_000, mb: 1_000_000, gb: 1_000_000_000 };
diff --git a/server/headless/connect.ts b/server/headless/connect.ts
index 2be24b5336..be4509ebc8 100644
--- a/server/headless/connect.ts
+++ b/server/headless/connect.ts
@@ -60,7 +60,7 @@ export async function connectVerb(ctx: VerbContext): Promise<VerbOutcome> {
}
const paired = await call(origin, "/api/auth/pair", { method: "POST", body: JSON.stringify({ code, label }) });
if (paired.status !== 200 || typeof paired.body.token !== "string") {
- throw new HeadlessError(`the code was not accepted${paired.body.error ? `: ${paired.body.error}` : ""}`, EXIT.unreachable, "codes are single use and expire after five minutes: get a new one");
+ throw new HeadlessError(`the code was not accepted${paired.body.error ? `: ${paired.body.error}` : ""}`, EXIT.unreachable, "codes are single use and expire (after five minutes, unless made with openmausbot pair --ttl): get a new one");
}
writeTokenFile(out, paired.body.token, ctx.flags.force === true);
const session = paired.body.session ?? {};
diff --git a/server/headless/main.ts b/server/headless/main.ts
index d3f9698581..42cd433804 100644
--- a/server/headless/main.ts
+++ b/server/headless/main.ts
@@ -10,6 +10,7 @@ import { exportVerb } from "./export.ts";
import { Output, processIo, type HeadlessIo } from "./output.ts";
import { runVerb, waitVerb } from "./run.ts";
import { teamApplyVerb, teamExportVerb } from "./team-apply.ts";
+import { tokenVerb } from "./token.ts";
const T = "TARGET is a bot or room by name or id, or --bot ID, --channel ID, --thread ID; --task ID picks one of its conversations.";
@@ -77,6 +78,14 @@ export const VERB_HELP: Record<string, string> = {
On this computer's own server the code is made for you; elsewhere, get one from Settings → Phone.
Then use it: --url URL --token-file FILE (or OPENMAUSBOT_URL and OPENMAUSBOT_TOKEN).`,
mcp: "openmausbot mcp\n Serve the OpenMausBot MCP tools on stdin and stdout, for an agent (docs/mcp-server.md).",
+ token: "openmausbot token create NAME --out FILE … | token list | token revoke ID (see help token create)",
+ "token create": `openmausbot token create NAME --out FILE [--scope client|admin] [--expires 90d] [--force]
+ An access token for CI and scripts, saved to FILE (only you can read it) and never printed.
+ It ends on its date (--expires, at most the server's session limit: 180 days unless OMB_SESSION_MAX_DAYS)
+ and never renews. --scope client (the default) can chat and answer approvals; admin can change settings.
+ Then: --url URL --token-file FILE. It is listed with openmausbot sessions too.`,
+ "token list": "openmausbot token list\n The access tokens, their scope, when each ends and when it was last used (never the token).",
+ "token revoke": "openmausbot token revoke ID\n End an access token at once (openmausbot token list shows the ids).",
};
export interface HeadlessOptions {
@@ -94,6 +103,7 @@ const VERBS: Record<string, (ctx: VerbContext) => Promise<VerbOutcome>> = {
doctor, bots: list, channels: list, models: list, messages, send, "send-channel": send, run: runVerb, wait: waitVerb,
interrupt, "new-bot": newBot, "new-channel": newChannel, "set-model": setModel, edit, export: exportVerb, events: eventsVerb,
"team apply": teamApplyVerb, "team export": teamExportVerb, "engine set": engineVerb, "engine list": engineVerb, connect: connectVerb,
+ "token create": tokenVerb, "token list": tokenVerb, "token revoke": tokenVerb,
};
async function execute(argv: readonly string[], options: HeadlessOptions, io: HeadlessIo): Promise<{ outcome: VerbOutcome; output: Output; client?: HeadlessClient }> {
diff --git a/server/headless/token.test.ts b/server/headless/token.test.ts
new file mode 100644
index 0000000000..ee4a07050c
--- /dev/null
+++ b/server/headless/token.test.ts
@@ -0,0 +1,120 @@
+import "../testing/scrub-ambient-omb-env.ts";
+
+import { mkdtempSync, readFileSync, statSync, writeFileSync } from "node:fs";
+import { createServer, type Server } from "node:http";
+import type { AddressInfo } from "node:net";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";
+
+import { pairingRequest, SessionRegistry } from "../sessions.ts";
+import { removeTempDir } from "../testing/cleanup.ts";
+import type { HeadlessIo } from "./output.ts";
+import { runHeadless } from "./main.ts";
+
+const dir = mkdtempSync(join(tmpdir(), "omb-token-"));
+let server: Server;
+let origin: string;
+let registry: SessionRegistry;
+/** A server from before access tokens: it ignores tokenTtlMs. */
+let oldServer = false;
+const DAY = 24 * 3_600_000;
+
+beforeAll(async () => {
+ server = createServer(async (req, res) => {
+ let raw = "";
+ for await (const chunk of req) raw += chunk;
+ const body = raw ? JSON.parse(raw) : undefined;
+ const send = (status: number, payload: unknown) => { res.writeHead(status, { "content-type": "application/json" }); res.end(JSON.stringify(payload)); };
+ if (req.method === "POST" && req.url === "/api/auth/pairing") {
+ const request = pairingRequest(body);
+ if ("error" in request) return send(400, request);
+ const { tokenTtlMs: _ignored, ...plain } = request;
+ return send(200, registry.openPairing(oldServer ? plain : request));
+ }
+ if (req.method === "POST" && req.url === "/api/auth/pair") {
+ const paired = registry.exchange({ code: body.code, label: body.label ?? "", source: "test" });
+ return paired.ok ? send(200, paired) : send(paired.status, { error: paired.error });
+ }
+ if (req.method === "GET" && req.url === "/api/auth/sessions") return send(200, { sessions: registry.list() });
+ const revoking = /^\/api\/auth\/sessions\/([\w-]+)$/.exec(req.url ?? "");
+ if (req.method === "DELETE" && revoking) return registry.revoke(revoking[1]!) ? send(200, { ok: true }) : send(404, { error: "no such session" });
+ send(404, { error: "no route" });
+ });
+ await new Promise<void>((ready) => server.listen(0, "127.0.0.1", ready));
+ origin = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
+});
+beforeEach(() => {
+ oldServer = false;
+ registry = new SessionRegistry({ file: join(mkdtempSync(join(dir, "data-")), "sessions.json") });
+});
+afterAll(async () => {
+ await new Promise((done) => server.close(done));
+ await removeTempDir(dir);
+});
+
+const run = async (argv: string[]) => {
+ const out: string[] = [];
+ const err: string[] = [];
+ const io: HeadlessIo = { out: (text) => out.push(text), err: (text) => err.push(text), readStdin: async () => "" };
+ const code = await runHeadless([...argv, "--url", origin], { io, env: {} });
+ return { code, out, err };
+};
+
+describe("token", () => {
+ it("makes a client token that ends on its date, saves it to a private file, and never prints it", async () => {
+ const file = join(dir, "ci-token");
+ const made = await run(["token", "create", "Nightly CI", "--expires", "90d", "--out", file, "--json"]);
+ expect(made.code).toBe(0);
+ const token = readFileSync(file, "utf8").trim();
+ expect(token).toMatch(/^omb_sess_/);
+ if (process.platform !== "win32") expect(statSync(file).mode & 0o777).toBe(0o600);
+ expect(JSON.stringify(made)).not.toContain(token);
+ const result = JSON.parse(made.out[0]!);
+ expect(result).toMatchObject({ ok: true, tokenFile: file, token: { name: "Nightly CI", scope: "client" } });
+ expect(result.token.expiresAt - Date.now()).toBeGreaterThan(90 * DAY - 60_000);
+ expect(registry.authenticate(token)).toMatchObject({ scopes: ["client"], token: true });
+ });
+
+ it("lists tokens only, and revokes one by id but never a device's session", async () => {
+ const device = registry.exchange({ code: registry.openPairing({ label: "Phone" }).code, label: "", source: "x" });
+ if (!device.ok) throw new Error(device.error);
+ expect((await run(["token", "create", "Deploys", "--scope", "admin", "--out", join(dir, "deploy-token")])).code).toBe(0);
+ const listed = await run(["token", "list", "--json"]);
+ const tokens = JSON.parse(listed.out[0]!).tokens;
+ expect(tokens).toEqual([expect.objectContaining({ name: "Deploys", scope: "admin" })]);
+ const refused = await run(["token", "revoke", device.session.id]);
+ expect(refused.code).toBe(1);
+ expect(refused.err[1]).toContain("openmausbot sessions revoke");
+ expect(registry.list()).toHaveLength(2);
+ expect((await run(["token", "revoke", tokens[0].id])).code).toBe(0);
+ expect(registry.list().map((session) => session.label)).toEqual(["Phone"]);
+ });
+
+ it("refuses before minting anything: an existing file, a bad scope or term, and no name", async () => {
+ const file = join(dir, "taken");
+ writeFileSync(file, "old\n");
+ for (const argv of [["Taken", "--out", file], ["CI", "--out", join(dir, "a"), "--scope", "root"], ["CI", "--out", join(dir, "b"), "--expires", "30m"],
+ ["--out", join(dir, "c")], ["CI"]]) {
+ expect((await run(["token", "create", ...argv])).code, argv.join(" ")).toBe(2);
+ }
+ expect(readFileSync(file, "utf8")).toBe("old\n");
+ expect(registry.list()).toEqual([]);
+ });
+
+ it("ends the session an older server opened instead, and says the server cannot make tokens (5)", async () => {
+ oldServer = true;
+ const file = join(dir, "old-token");
+ const made = await run(["token", "create", "CI", "--out", file]);
+ expect(made.code).toBe(5);
+ expect(made.err[0]).toBe("error: this OpenMausBot server cannot make access tokens");
+ expect(registry.list()).toEqual([]);
+ expect(() => readFileSync(file)).toThrow();
+ });
+
+ it("passes on the server's own limit on a token's term", async () => {
+ const made = await run(["token", "create", "CI", "--expires", "3000d", "--out", join(dir, "long-token")]);
+ expect(made.code).toBe(1);
+ expect(made.err[0]).toContain("OMB_SESSION_MAX_DAYS");
+ });
+});
diff --git a/server/headless/token.ts b/server/headless/token.ts
new file mode 100644
index 0000000000..eb0e27a168
--- /dev/null
+++ b/server/headless/token.ts
@@ -0,0 +1,74 @@
+// An access token is a session made for a script: it ends on its date and never renews. It is listed and revoked like
+// any session, and, like `connect`'s, written to a file only you can read and never printed.
+import { existsSync } from "node:fs";
+
+import { EXIT, flag, HeadlessError, oneOf, parseDuration, usageError } from "./args.ts";
+import { writeTokenFile } from "./connect.ts";
+import type { VerbContext, VerbOutcome } from "./context.ts";
+
+type Rec = Record<string, any>;
+
+const DAY = 24 * 3_600_000;
+const day = (ms: number) => new Date(ms).toISOString().slice(0, 10);
+const scopeOf = (session: Rec) => (Array.isArray(session.scopes) && session.scopes.includes("admin") ? "admin" : "client");
+
+async function tokens(ctx: VerbContext): Promise<Rec[]> {
+ const listed = await (await ctx.client()).json<Rec>("/api/auth/sessions");
+ return (Array.isArray(listed.sessions) ? listed.sessions : []).filter((session: Rec) => session.token === true);
+}
+
+async function create(ctx: VerbContext): Promise<VerbOutcome> {
+ const name = ctx.positionals[0]?.trim();
+ if (!name) throw usageError("name the token", "openmausbot token create NAME --out FILE [--scope client|admin] [--expires 90d]");
+ const out = flag(ctx.flags, "out")?.trim();
+ if (!out) throw usageError("--out FILE is required: where to keep the token");
+ if (existsSync(out) && ctx.flags.force !== true) throw usageError(`${out} already exists`, "pass --force to replace it");
+ const scope = oneOf(flag(ctx.flags, "scope"), "--scope", ["client", "admin"] as const, "client");
+ const raw = flag(ctx.flags, "expires");
+ const ttlMs = raw ? parseDuration(raw, "--expires", { min: 3_600_000, max: 3_650 * DAY }) : 90 * DAY;
+ const client = await ctx.client();
+ const minted = await client.json<Rec>("/api/auth/pairing", {
+ method: "POST", body: JSON.stringify({ label: name, scopes: scope === "admin" ? ["admin", "client"] : ["client"], tokenTtlMs: ttlMs }),
+ });
+ const paired = await client.json<Rec>("/api/auth/pair", { method: "POST", body: JSON.stringify({ code: minted.code, label: name }) });
+ const session: Rec = paired.session ?? {};
+ if (session.token !== true) {
+ // A server from before tokens opened an ordinary session that renews itself: end it rather than hand it out.
+ if (typeof session.id === "string") await client.json(`/api/auth/sessions/${encodeURIComponent(session.id)}`, { method: "DELETE" }).catch(() => undefined);
+ throw new HeadlessError("this OpenMausBot server cannot make access tokens", EXIT.unreachable, "update OpenMausBot on the server, or use openmausbot connect");
+ }
+ writeTokenFile(out, paired.token, ctx.flags.force === true);
+ return {
+ result: { ok: true, tokenFile: out, url: client.baseUrl, token: { id: session.id, name: session.label, scope, expiresAt: session.expiresAt } },
+ exitCode: EXIT.done,
+ human: [
+ `Token "${session.label}" (${scope === "admin" ? "full access" : "chat and approvals only"}) until ${day(session.expiresAt)}, id ${session.id}.`,
+ `Saved to ${out}. Use it with: openmausbot ${scope === "admin" ? "doctor" : "bots"} --url ${client.baseUrl} --token-file ${out}`,
+ `Revoke it with: openmausbot token revoke ${session.id}`,
+ ],
+ };
+}
+
+async function list(ctx: VerbContext): Promise<VerbOutcome> {
+ const found = (await tokens(ctx)).map((session) => ({ id: session.id, name: session.label, scope: scopeOf(session), createdAt: session.createdAt,
+ lastSeenAt: session.lastSeenAt, expiresAt: session.expiresAt }));
+ return {
+ result: { tokens: found }, exitCode: EXIT.done,
+ human: found.length
+ ? found.map((token) => `${token.name} · ${token.scope} · until ${day(token.expiresAt)} · last used ${day(token.lastSeenAt)} · id ${token.id}`)
+ : ["No access tokens. Make one with: openmausbot token create NAME --out FILE"],
+ };
+}
+
+async function revoke(ctx: VerbContext): Promise<VerbOutcome> {
+ const id = ctx.positionals[0]?.trim();
+ if (!id) throw usageError("give the token's id", "openmausbot token list shows them");
+ const token = (await tokens(ctx)).find((session) => session.id === id);
+ if (!token) throw new HeadlessError(`no access token with id ${id}`, EXIT.failed, "openmausbot token list shows them; a device's session is revoked with openmausbot sessions revoke ID");
+ await (await ctx.client()).json(`/api/auth/sessions/${encodeURIComponent(id)}`, { method: "DELETE" });
+ return { result: { ok: true, revoked: { id, name: token.label } }, exitCode: EXIT.done, human: [`Revoked "${token.label}" (${id}): it no longer works.`] };
+}
+
+export function tokenVerb(ctx: VerbContext): Promise<VerbOutcome> {
+ return ctx.verb === "token create" ? create(ctx) : ctx.verb === "token list" ? list(ctx) : revoke(ctx);
+}
diff --git a/server/index.ts b/server/index.ts
index 8b3834bc13..25af8f37e1 100644
--- a/server/index.ts
+++ b/server/index.ts
@@ -548,7 +548,7 @@ import {
serializeSessionCookie,
sessionCookieName, ownerOrAdmin,
} from "./request-auth.ts";
-import { cookieMaxAgeSeconds, formatPairingCode, SessionRegistry, type Scope, type SessionRecord } from "./sessions.ts";
+import { cookieMaxAgeSeconds, formatPairingCode, pairingRequest, SessionRegistry, type SessionRecord } from "./sessions.ts";
import { ThreadStarters } from "./thread-starters.ts";
import {
appendAdminAction,
@@ -12805,11 +12805,11 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {
if (auth.kind === "session" && !sessions.isLive(auth.session.id)) {
return json(res, 401, { error: "Your session ended. Sign in again before creating a pairing code." });
}
- const requested: unknown = body?.scopes;
- const scopes = Array.isArray(requested) ? requested.filter((v): v is Scope => v === "admin" || v === "client") : undefined;
+ const requested = pairingRequest(body);
+ if ("error" in requested) return json(res, 400, requested);
let opened: ReturnType<typeof sessions.openPairing>;
try {
- opened = sessions.openPairing({ label: typeof body?.label === "string" ? body.label : undefined, scopes });
+ opened = sessions.openPairing(requested);
} catch (error) {
if ((error as { code?: unknown }).code === "cloud_personal") return json(res, 403, { error: (error as Error).message, code: "cloud_personal", ...userErrorFields(error) });
throw error;
diff --git a/server/sessions.test.ts b/server/sessions.test.ts
index 89a50ed8ee..4b9ac758be 100644
--- a/server/sessions.test.ts
+++ b/server/sessions.test.ts
@@ -13,7 +13,9 @@ import {
LOCKOUT,
normalizePairingCode,
PAIRING_CODE_ALPHABET,
+ PAIRING_CODE_MAX_TTL_MS,
PAIRING_CODE_TTL_MS,
+ pairingRequest,
SESSION_TTL_MS,
SessionRegistry,
STREAM_TICKET_TTL_MS,
@@ -180,6 +182,25 @@ describe("pairing codes", () => {
expect(registry.openPairings()).toEqual([]);
});
+ it("stay open as long as asked, up to a day, and still work once", () => {
+ const { code, expiresAt } = registry.openPairing({ label: "server", ttlMs: PAIRING_CODE_MAX_TTL_MS });
+ expect(expiresAt).toBe(clock + 24 * 3_600_000);
+ clock += 23 * 3_600_000;
+ expect(registry.exchange({ code, label: "", source: "a" }).ok).toBe(true);
+ expect(registry.exchange({ code, label: "", source: "a" }).ok).toBe(false);
+ const { code: late } = registry.openPairing({ ttlMs: PAIRING_CODE_MAX_TTL_MS });
+ clock += PAIRING_CODE_MAX_TTL_MS + 1;
+ expect(registry.exchange({ code: late, label: "", source: "b" }).ok).toBe(false);
+ });
+
+ it("takes a code's term and a token's from the request, and refuses either out of bounds", () => {
+ expect(pairingRequest({ label: "CI", scopes: ["client", "root"], ttlMs: 86_400_000 })).toEqual({ label: "CI", scopes: ["client"], ttlMs: 86_400_000 });
+ expect(pairingRequest({ tokenTtlMs: SESSION_MAX_AGE_MS })).toEqual({ tokenTtlMs: SESSION_MAX_AGE_MS });
+ expect(pairingRequest(null)).toEqual({});
+ for (const ttlMs of [86_400_001, 59_999, 1.5e6 + 0.5, "24h"]) expect(pairingRequest({ ttlMs }), String(ttlMs)).toMatchObject({ error: expect.stringContaining("24 hours") });
+ expect(pairingRequest({ tokenTtlMs: SESSION_MAX_AGE_MS + 1 })).toMatchObject({ error: expect.stringContaining("OMB_SESSION_MAX_DAYS") });
+ });
+
it("locks a source out after repeated failures, and forgets on success", () => {
for (let i = 0; i < LOCKOUT.failures; i++) {
expect(registry.exchange({ code: "AAAAAAAAAAAA", label: "", source: "attacker" }).ok).toBe(false);
@@ -523,6 +544,29 @@ describe("sessions", () => {
expect(statSync(file()).mtimeMs).toBeGreaterThanOrEqual(before);
});
+ it("opens an access token that lasts exactly its term, never renews, and stays one after a restart", () => {
+ const term = 90 * 24 * 3_600_000;
+ const { code } = registry.openPairing({ label: "Nightly CI", scopes: ["client"], tokenTtlMs: term });
+ const paired = registry.exchange({ code, label: "", source: "ci" });
+ if (!paired.ok) throw new Error(paired.error);
+ expect(paired.session).toMatchObject({ label: "Nightly CI", scopes: ["client"], token: true, expiresAt: clock + term });
+ clock += term - 60_000;
+ expect(registry.authenticate(paired.token)?.id).toBe(paired.session.id);
+ expect(registry.renew(paired.session.id)).toBe(false);
+ expect(new SessionRegistry({ file: file(), now: () => clock }).list()).toMatchObject([{ id: paired.session.id, token: true, expiresAt: paired.session.expiresAt }]);
+ clock += 60_001;
+ expect(registry.authenticate(paired.token)).toBeNull();
+ });
+
+ it("never makes a token of a browser sign-in, and caps a token at the longest session", () => {
+ const browser = registry.openPairing({ browser: true, tokenTtlMs: 3_600_000 });
+ const signedIn = registry.exchange({ code: browser.credential, label: "", source: "b", browser: true });
+ expect(signedIn.ok && signedIn.session.token).toBeFalsy();
+ const { code } = registry.openPairing({ tokenTtlMs: SESSION_MAX_AGE_MS * 2 });
+ const long = registry.exchange({ code, label: "", source: "c" });
+ expect(long.ok && long.session.expiresAt).toBe(clock + SESSION_MAX_AGE_MS);
+ });
+
it("renews a session with half its term or less left, and never revives an expired one", () => {
const { token, session } = pair();
clock += SESSION_TTL_MS / 2 - 60_000;
diff --git a/server/sessions.ts b/server/sessions.ts
index da861e4e6a..aae085b848 100644
--- a/server/sessions.ts
+++ b/server/sessions.ts
@@ -1,4 +1,4 @@
-// Pairing codes (60-bit, single use, 5 min), sessions (256-bit, only the sha256 stored) and stream tickets (EventSource cannot set headers).
+// Pairing codes (60-bit, single use, 5 min unless asked for up to a day), sessions (256-bit, only the sha256 stored) and stream tickets (EventSource cannot set headers).
import { createHash, randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
import { closeSync, existsSync, fsyncSync, mkdirSync, openSync, readFileSync, unlinkSync } from "node:fs";
import { dirname } from "node:path";
@@ -13,6 +13,7 @@ export const SCOPES: readonly Scope[] = ["admin", "client"];
export const PAIRING_CODE_ALPHABET = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ";
export const PAIRING_CODE_LENGTH = 12;
export const PAIRING_CODE_TTL_MS = 5 * 60_000;
+export const PAIRING_CODE_MAX_TTL_MS = 24 * 3_600_000;
/** Not clamped: an invalid value falls back to the default, so a typo never becomes a policy. */
export function daysMs(value: string | undefined, fallbackDays: number): number {
const days = Number(value);
@@ -29,7 +30,7 @@ export function cookieMaxAgeSeconds(session: { expiresAt: number }, now = Date.n
return Math.max(1, Math.floor((session.expiresAt - now) / 1000));
}
export const STREAM_TICKET_TTL_MS = 5 * 60_000;
-/** Slow-down only: a 60-bit code cannot be guessed online in five minutes, and sources are shared (NAT), so the lock stays short. */
+/** Slow-down only: a 60-bit code cannot be guessed online in a day, and sources are shared (NAT), so the lock stays short. */
export const LOCKOUT = { failures: 10, windowMs: 60_000, lockMs: 60_000 } as const;
/** A consumed code re-presented with the same client-made attempt id gets the same answer; sharing an address is not enough. */
export const EXCHANGE_REPLAY_MS = 60_000;
@@ -61,6 +62,8 @@ const sessionSchema = z.object({
owner: z.string().max(254).optional(),
/** A Team Cloud's sign-in for moving one bot in (server/team-move-in.ts): it reaches that bot's move routes only. */
moveIn: z.string().regex(/^[\w-]{1,128}$/).optional(),
+ /** An access token for a script (`openmausbot token create`): it ends at expiresAt and never renews. */
+ token: z.literal(true).optional(),
});
const fileSchema = z.object({ version: z.literal(1), sessions: z.array(sessionSchema) });
@@ -78,6 +81,7 @@ export interface PublicSession {
email?: string;
owner?: string;
teamRole?: TeamRole;
+ token?: true;
}
export interface PairingCode {
@@ -95,6 +99,8 @@ export interface PairingCode {
member?: TeamMember;
/** A code a member made from their own session: when the Admin last vouched for them. Absent on the Admin's own. */
memberCheckedAt?: number;
+ /** The session it opens is an access token that lasts exactly this long. */
+ tokenTtlMs?: number;
}
export interface PublicPairing {
@@ -171,9 +177,36 @@ function publicSession(record: SessionRecord): PublicSession {
if (record.email) view.email = record.email;
if (record.owner) view.owner = record.owner;
if (record.teamRole) view.teamRole = record.teamRole;
+ if (record.token) view.token = true;
return view;
}
+export interface PairingRequest {
+ label?: string;
+ scopes?: Scope[];
+ ttlMs?: number;
+ tokenTtlMs?: number;
+}
+
+const DAY_MS = 24 * 3_600_000;
+const within = (value: unknown, min: number, max: number): number | null | undefined =>
+ value === undefined ? undefined : typeof value === "number" && Number.isInteger(value) && value >= min && value <= max ? value : null;
+
+/** POST /api/auth/pairing's body: `ttlMs` keeps the code open up to a day; `tokenTtlMs` makes the session it opens an
+ * access token, bounded by OMB_SESSION_MAX_DAYS like every session. */
+export function pairingRequest(body: unknown): PairingRequest | { error: string } {
+ const record: Record<string, unknown> = body && typeof body === "object" && !Array.isArray(body) ? Object(body) : {};
+ const ttlMs = within(record.ttlMs, 60_000, PAIRING_CODE_MAX_TTL_MS);
+ if (ttlMs === null) return { error: "ttlMs must be a whole number of milliseconds, from one minute to 24 hours" };
+ const tokenTtlMs = within(record.tokenTtlMs, 60_000, SESSION_MAX_AGE_MS);
+ if (tokenTtlMs === null) return { error: `a token lasts from one minute to ${Math.floor(SESSION_MAX_AGE_MS / DAY_MS)} days on this server (OMB_SESSION_MAX_DAYS)` };
+ const scopes = Array.isArray(record.scopes) ? record.scopes.filter((v): v is Scope => v === "admin" || v === "client") : undefined;
+ return {
+ ...(typeof record.label === "string" ? { label: record.label } : {}), ...(scopes ? { scopes } : {}),
+ ...(ttlMs !== undefined ? { ttlMs } : {}), ...(tokenTtlMs !== undefined ? { tokenTtlMs } : {}),
+ };
+}
+
export type EmailScopesResolver = (email: string) => readonly Scope[] | null;
export interface SessionStoreOptions {
file: string;
@@ -316,7 +349,7 @@ export class SessionRegistry {
}
}
- openPairing(input: { scopes?: Scope[]; label?: string; ttlMs?: number; browser?: boolean; owner?: string; member?: TeamMember; memberCheckedAt?: number } = {}): { id: string; code: string; credential: string; expiresAt: number } {
+ openPairing(input: { scopes?: Scope[]; label?: string; ttlMs?: number; tokenTtlMs?: number; browser?: boolean; owner?: string; member?: TeamMember; memberCheckedAt?: number } = {}): { id: string; code: string; credential: string; expiresAt: number } {
this.prune();
const now = this.now();
const code = generatePairingCode();
@@ -333,6 +366,7 @@ export class SessionRegistry {
expiresAt: now + (input.ttlMs ?? PAIRING_CODE_TTL_MS),
...(input.browser ? { browser: true as const, ...(input.owner ? { owner: input.owner } : {}) } : {}),
...(input.member ? { member: input.member, ...(input.memberCheckedAt !== undefined ? { memberCheckedAt: input.memberCheckedAt } : {}) } : {}),
+ ...(input.tokenTtlMs !== undefined && !input.browser && !input.member ? { tokenTtlMs: input.tokenTtlMs } : {}),
};
this.pairings.push(pairing);
return { id: pairing.id, code, credential, expiresAt: pairing.expiresAt };
@@ -421,7 +455,8 @@ export class SessionRegistry {
scopes: [...pairing.scopes],
createdAt: now,
lastSeenAt: now,
- expiresAt: pairing.member ? teamSessionExpiresAt(checkedAt, now + SESSION_TTL_MS) : now + Math.min(SESSION_TTL_MS, SESSION_MAX_AGE_MS),
+ expiresAt: pairing.member ? teamSessionExpiresAt(checkedAt, now + SESSION_TTL_MS) : now + Math.min(pairing.tokenTtlMs ?? SESSION_TTL_MS, SESSION_MAX_AGE_MS),
+ ...(pairing.tokenTtlMs !== undefined ? { token: true as const } : {}),
...(pairing.browser ? { cookieOnly: true as const, ...(pairing.owner ? { owner: pairing.owner } : {}) } : {}),
...(pairing.member ? { email: pairing.member.email, teamRole: pairing.member.role, membershipAuthority: "team" as const } : {}),
...(pairing.member && pairing.memberCheckedAt !== undefined ? { memberCheckedAt: pairing.memberCheckedAt } : {}),
@@ -586,7 +621,7 @@ export class SessionRegistry {
this.recheckMembership();
const record = this.sessions.find((s) => s.id === sessionId);
const now = this.now();
- if (!record || record.expiresAt <= now) return false;
+ if (!record || record.expiresAt <= now || record.token) return false;
if (record.expiresAt - now > SESSION_RENEW_WHEN_LEFT_MS) return false;
const proposed = Math.min(now + SESSION_TTL_MS, record.createdAt + SESSION_MAX_AGE_MS);
const next = record.membershipAuthority === "team" ? teamSessionExpiresAt(record.memberCheckedAt ?? record.createdAt, proposed) : proposed;