Skip to content

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

GitHub sign-in on the server: GitHub CLI's device code, a pasted token, or the person's own gh (#7248)

Milind Sonied8cb727891a
diff --git a/apps/docs/content/docs/connected-apps/github-sign-in.mdx b/apps/docs/content/docs/connected-apps/github-sign-in.mdx
new file mode 100644
index 0000000000..412a0849ec
--- /dev/null
+++ b/apps/docs/content/docs/connected-apps/github-sign-in.mdx
@@ -0,0 +1,47 @@
+---
+title: GitHub sign-in
+description: How MausBot signs in to GitHub for its own git and GitHub actions, what GitHub shows, and how to revoke it.
+icon: KeyRound
+---
+
+MausBot can sign in to GitHub once, so the server can clone, push and open pull requests for your bots. Nothing has to be registered first: MausBot uses GitHub's own command line tool, **GitHub CLI**, and its device-code sign-in.
+
+## How the sign-in works
+
+1. You start the sign-in. Where GitHub CLI is not installed, as on a MausBot Cloud or a computer without it, the first sign-in first downloads it (about 15 MB). MausBot checks the download against the release it pins before anything runs.
+2. MausBot shows a one-time code, such as `ABCD-1234`, and the address **https://github.com/login/device**.
+3. Open that address, sign in to GitHub if asked, type the code and approve the request.
+4. MausBot shows **Signed in as** your GitHub username.
+
+The code is good for 15 minutes. If it expires or you cancel, start again for a new code.
+
+## What GitHub shows
+
+GitHub lists the grant as **GitHub CLI** under your account's authorized OAuth apps. It asks for the same scopes GitHub CLI always asks for:
+
+- `repo`: your repositories, including private ones
+- `read:org`: which organizations and teams you belong to
+- `gist`: your gists
+
+MausBot asks GitHub for a sign-in that does not expire, and GitHub normally gives one. If GitHub gives a sign-in that expires instead, GitHub CLI renews it whenever MausBot uses it. Either way it works until you revoke it on GitHub or sign out in MausBot.
+
+## Where the sign-in is kept
+
+- **MausBot Cloud and self-hosted servers.** Each sign-in has its own private folder in the server's data folder. Where bots run in their sandbox, as on every MausBot Cloud, that folder is never inside it. The folder is never part of a backup, so a Cloud restored from a backup or moved to another server starts without the sign-in: sign in again there. The server uses the token for git and GitHub actions on the bots' behalf and never hands it to a bot.
+- **Team Cloud.** Each member signs in with their own GitHub account. Nobody can use another member's sign-in.
+- **This computer.** If you already signed in with GitHub CLI yourself (`gh auth login`), MausBot shows **signed in via GitHub CLI** and asks nothing more. MausBot reads that sign-in and never changes it. To sign out of it, run `gh auth logout` in your own terminal.
+
+On Windows, GitHub CLI keeps sign-ins in Windows Credential Manager, which MausBot cannot keep separate. So on Windows MausBot starts its own sign-in only when your own GitHub CLI says it is signed out, or when Credential Manager holds no GitHub CLI entry at all. Otherwise it asks you to paste a token instead.
+
+## Using a token instead
+
+You can paste a fine-grained personal access token instead of using the code. Create one at **https://github.com/settings/personal-access-tokens**, give it access to the repositories your bots should work on, then paste it into MausBot. MausBot checks the token with GitHub once and keeps it in its encrypted Vault on this server. Like a GitHub CLI sign-in, the token is never shown back and never reaches a bot.
+
+## Signing out and revoking
+
+Signing out in MausBot deletes the sign-in from the server. It does not revoke the sign-in on GitHub. To cut off access completely:
+
+1. Open **https://github.com/settings/applications** and choose **Authorized OAuth Apps**.
+2. Select **GitHub CLI**, then **Revoke**.
+
+Revoking also signs out every other copy of GitHub CLI you signed in with that account, on any computer. For a pasted token, delete it at **https://github.com/settings/personal-access-tokens**.
diff --git a/apps/docs/content/docs/connected-apps/meta.json b/apps/docs/content/docs/connected-apps/meta.json
index e330172376..18990203fb 100644
--- a/apps/docs/content/docs/connected-apps/meta.json
+++ b/apps/docs/content/docs/connected-apps/meta.json
@@ -1,5 +1,5 @@
{
"title": "Connected apps",
"icon": "PlugZap",
- "pages": ["index", "multiple-accounts", "self-hosted-composio"]
+ "pages": ["index", "multiple-accounts", "github-sign-in", "self-hosted-composio"]
}
diff --git a/server/bot-box/plan.test.ts b/server/bot-box/plan.test.ts
index 198ccaedeb..2cf3b6b006 100644
--- a/server/bot-box/plan.test.ts
+++ b/server/bot-box/plan.test.ts
@@ -2,6 +2,7 @@ import { join } from "node:path";
import { describe, expect, it } from "vitest";
import { engineInstallRoots } from "../engine-roots.ts";
+import { githubFolders } from "../github/sign-in.ts";
import { BOX_MUTATIONS, CPU_LIST_FILES, argvPaths, bwrapArgs, planBox, taskWorkspaceIds, under, visibleInBox, type BoxAudience, type BoxMutation, type BoxRequest, type BoxSetup } from "./plan.ts";
const home = "/data";
@@ -265,6 +266,23 @@ linuxBox("the box plan", () => {
expect(visibleInBox(ask({ CODEX_HOME: join(dataDir, "providers", "codex-1") }, false), join(dataDir, "providers", "codex-1", "auth.json"))).toBe("rw");
});
+ it("never shows a GitHub sign-in's folder (its token, gh's config and HOME), whatever the turn asks", () => {
+ const owner = githubFolders(dataDir, "owner"), member = githubFolders(dataDir, `p_${"a".repeat(22)}`);
+ const files = [join(owner.config, "hosts.yml"), join(owner.home, ".gitconfig"), join(member.config, "hosts.yml"), join(dataDir, "github")];
+ const memberHome = join(dataDir, "engine-homes", "member-aaaaaaaaaaaaaaaa");
+ const plans = [
+ turn(),
+ planBox(setup(), { command: "opencode", args: ["acp"], cwd, env: { HOME: home }, botThreads: true }),
+ planBox(setup(), { command: "/usr/local/bin/claude", args: [], cwd, env: { HOME: memberHome }, home: memberHome }),
+ // A command line or a configured server's environment naming the folder is not a grant.
+ planBox(setup(), { command: "/usr/bin/gh", args: ["auth", "token", join(owner.config, "hosts.yml")], cwd, env: { HOME: home }, botId: "bot-a" }),
+ planBox(setup(), { command: "sh", args: [], cwd, env: { XDG_CONFIG_HOME: owner.home, XDG_CACHE_HOME: join(dataDir, "github") }, botId: "bot-a", configured: true }),
+ ];
+ for (const plan of plans) for (const file of files) expect(visibleInBox(plan, file), file).toBe("none");
+ // The check bites: with the data folder bound, the token file is there.
+ expect(visibleInBox(turn(["bind-data"]), join(owner.config, "hosts.yml"))).toBe("rw");
+ });
+
it("each mutation opens exactly the hole it names", () => {
const base = turn();
const flips: Record<BoxMutation, (plan: ReturnType<typeof turn>) => boolean> = {
diff --git a/server/github/fixtures/2.102.0/login-clipboard.stderr.txt b/server/github/fixtures/2.102.0/login-clipboard.stderr.txt
new file mode 100644
index 0000000000..5c841ac39e
--- /dev/null
+++ b/server/github/fixtures/2.102.0/login-clipboard.stderr.txt
@@ -0,0 +1,4 @@
+
+! One-time code (0DE6-7337) copied to clipboard
+Open this URL to continue in your web browser: https://github.com/login/device
+failed to authenticate via web browser: Post "https://github.com/login/oauth/access_token": read tcp 192.0.2.10:60511->192.0.2.20:443: read: can't assign requested address
diff --git a/server/github/fixtures/2.102.0/login.stderr.txt b/server/github/fixtures/2.102.0/login.stderr.txt
new file mode 100644
index 0000000000..b03df790e3
--- /dev/null
+++ b/server/github/fixtures/2.102.0/login.stderr.txt
@@ -0,0 +1,4 @@
+
+! First copy your one-time code: 6C49-C9EB
+Open this URL to continue in your web browser: https://github.com/login/device
+failed to authenticate via web browser: Post "https://github.com/login/oauth/access_token": read tcp 192.0.2.10:60808->192.0.2.20:443: read: can't assign requested address
diff --git a/server/github/fixtures/2.102.0/status-invalid.stderr.txt b/server/github/fixtures/2.102.0/status-invalid.stderr.txt
new file mode 100644
index 0000000000..44e9e95cf7
--- /dev/null
+++ b/server/github/fixtures/2.102.0/status-invalid.stderr.txt
@@ -0,0 +1,6 @@
+github.com
+ X Failed to log in to github.com account octo-fixture (/tmp/x.FIXTURE/cfg/hosts.yml)
+ - Active account: true
+ - The token in /tmp/x.FIXTURE/cfg/hosts.yml is invalid.
+ - To re-authenticate, run: gh auth refresh -h github.com
+ - To forget about this account, run: gh auth logout -h github.com -u octo-fixture
diff --git a/server/github/fixtures/2.102.0/status-json-invalid.stdout.txt b/server/github/fixtures/2.102.0/status-json-invalid.stdout.txt
new file mode 100644
index 0000000000..8a0ac36342
--- /dev/null
+++ b/server/github/fixtures/2.102.0/status-json-invalid.stdout.txt
@@ -0,0 +1 @@
+{"hosts":{"github.com":[{"state":"error","error":"HTTP 401: Bad credentials (https://api.github.com/)","active":true,"host":"github.com","login":"octo-fixture","tokenSource":"/tmp/x.FIXTURE/cfg/hosts.yml","gitProtocol":"https"}]}}
diff --git a/server/github/fixtures/2.102.0/status-json-signedout.stdout.txt b/server/github/fixtures/2.102.0/status-json-signedout.stdout.txt
new file mode 100644
index 0000000000..378fd9d196
--- /dev/null
+++ b/server/github/fixtures/2.102.0/status-json-signedout.stdout.txt
@@ -0,0 +1 @@
+{"hosts":{}}
diff --git a/server/github/fixtures/2.102.0/version.stdout.txt b/server/github/fixtures/2.102.0/version.stdout.txt
new file mode 100644
index 0000000000..7ad9e83406
--- /dev/null
+++ b/server/github/fixtures/2.102.0/version.stdout.txt
@@ -0,0 +1,2 @@
+gh version 2.102.0 (2026-09-30)
+https://github.com/cli/cli/releases/tag/v2.102.0
diff --git a/server/github/fixtures/2.103.3/login-expired.stderr.txt b/server/github/fixtures/2.103.3/login-expired.stderr.txt
new file mode 100644
index 0000000000..3a5f9abc68
--- /dev/null
+++ b/server/github/fixtures/2.103.3/login-expired.stderr.txt
@@ -0,0 +1,4 @@
+
+! First copy your one-time code: 89E3-9558
+Open this URL to continue in your web browser: https://github.com/login/device
+failed to authenticate via web browser: This 'device_code' has expired. (expired_token)
diff --git a/server/github/fixtures/2.103.3/login-network-failure.stderr.txt b/server/github/fixtures/2.103.3/login-network-failure.stderr.txt
new file mode 100644
index 0000000000..a60d52d0c7
--- /dev/null
+++ b/server/github/fixtures/2.103.3/login-network-failure.stderr.txt
@@ -0,0 +1,4 @@
+
+! First copy your one-time code: 926F-1B66
+Open this URL to continue in your web browser: https://github.com/login/device
+failed to authenticate via web browser: Post "https://github.com/login/oauth/access_token": read tcp 192.0.2.10:62513->192.0.2.20:443: read: operation timed out
diff --git a/server/github/fixtures/2.103.3/login.stderr.txt b/server/github/fixtures/2.103.3/login.stderr.txt
new file mode 100644
index 0000000000..30a822f94b
--- /dev/null
+++ b/server/github/fixtures/2.103.3/login.stderr.txt
@@ -0,0 +1,3 @@
+
+! First copy your one-time code: B1A5-0221
+Open this URL to continue in your web browser: https://github.com/login/device
diff --git a/server/github/fixtures/2.103.3/status-invalid.stderr.txt b/server/github/fixtures/2.103.3/status-invalid.stderr.txt
new file mode 100644
index 0000000000..44e9e95cf7
--- /dev/null
+++ b/server/github/fixtures/2.103.3/status-invalid.stderr.txt
@@ -0,0 +1,6 @@
+github.com
+ X Failed to log in to github.com account octo-fixture (/tmp/x.FIXTURE/cfg/hosts.yml)
+ - Active account: true
+ - The token in /tmp/x.FIXTURE/cfg/hosts.yml is invalid.
+ - To re-authenticate, run: gh auth refresh -h github.com
+ - To forget about this account, run: gh auth logout -h github.com -u octo-fixture
diff --git a/server/github/fixtures/2.103.3/status-json-invalid.stdout.txt b/server/github/fixtures/2.103.3/status-json-invalid.stdout.txt
new file mode 100644
index 0000000000..8a0ac36342
--- /dev/null
+++ b/server/github/fixtures/2.103.3/status-json-invalid.stdout.txt
@@ -0,0 +1 @@
+{"hosts":{"github.com":[{"state":"error","error":"HTTP 401: Bad credentials (https://api.github.com/)","active":true,"host":"github.com","login":"octo-fixture","tokenSource":"/tmp/x.FIXTURE/cfg/hosts.yml","gitProtocol":"https"}]}}
diff --git a/server/github/fixtures/2.103.3/status-json-offline.stdout.txt b/server/github/fixtures/2.103.3/status-json-offline.stdout.txt
new file mode 100644
index 0000000000..1ae0ad5c0d
--- /dev/null
+++ b/server/github/fixtures/2.103.3/status-json-offline.stdout.txt
@@ -0,0 +1 @@
+{"hosts":{"github.com":[{"state":"error","error":"Get \"https://api.github.com/\": proxyconnect tcp: dial tcp 127.0.0.1:9: connect: connection refused","active":true,"host":"github.com","login":"octo-fixture","tokenSource":"/tmp/x.FIXTURE/cfg/hosts.yml","gitProtocol":"https"}]}}
diff --git a/server/github/fixtures/2.103.3/status-offline.stderr.txt b/server/github/fixtures/2.103.3/status-offline.stderr.txt
new file mode 100644
index 0000000000..44e9e95cf7
--- /dev/null
+++ b/server/github/fixtures/2.103.3/status-offline.stderr.txt
@@ -0,0 +1,6 @@
+github.com
+ X Failed to log in to github.com account octo-fixture (/tmp/x.FIXTURE/cfg/hosts.yml)
+ - Active account: true
+ - The token in /tmp/x.FIXTURE/cfg/hosts.yml is invalid.
+ - To re-authenticate, run: gh auth refresh -h github.com
+ - To forget about this account, run: gh auth logout -h github.com -u octo-fixture
diff --git a/server/github/fixtures/2.103.3/status-signedout.stderr.txt b/server/github/fixtures/2.103.3/status-signedout.stderr.txt
new file mode 100644
index 0000000000..8b4d2a5c98
--- /dev/null
+++ b/server/github/fixtures/2.103.3/status-signedout.stderr.txt
@@ -0,0 +1 @@
+You are not logged into any GitHub hosts. To log in, run: gh auth login
diff --git a/server/github/fixtures/2.103.3/version.stdout.txt b/server/github/fixtures/2.103.3/version.stdout.txt
new file mode 100644
index 0000000000..edff62ecaf
--- /dev/null
+++ b/server/github/fixtures/2.103.3/version.stdout.txt
@@ -0,0 +1,2 @@
+gh version 2.103.3 (2026-10-26)
+https://github.com/cli/cli/releases/tag/v2.103.3
diff --git a/server/github/fixtures/2.40.1/login-clipboard-flag.stderr.txt b/server/github/fixtures/2.40.1/login-clipboard-flag.stderr.txt
new file mode 100644
index 0000000000..23ad8eb3ad
--- /dev/null
+++ b/server/github/fixtures/2.40.1/login-clipboard-flag.stderr.txt
@@ -0,0 +1,12 @@
+unknown flag: --clipboard
+
+Usage: gh auth login [flags]
+
+Flags:
+ -p, --git-protocol string The protocol to use for git operations on this host: {ssh|https}
+ -h, --hostname string The hostname of the GitHub instance to authenticate with
+ --insecure-storage Save authentication credentials in plain text instead of credential store
+ -s, --scopes strings Additional authentication scopes to request
+ -w, --web Open a browser to authenticate
+ --with-token Read token from standard input
+
diff --git a/server/github/fixtures/2.40.1/login.stderr.txt b/server/github/fixtures/2.40.1/login.stderr.txt
new file mode 100644
index 0000000000..9cd15b6e49
--- /dev/null
+++ b/server/github/fixtures/2.40.1/login.stderr.txt
@@ -0,0 +1,3 @@
+
+! First copy your one-time code: 7E95-AA50
+Open this URL to continue in your web browser: https://github.com/login/device
diff --git a/server/github/fixtures/2.40.1/status-invalid.stdout.txt b/server/github/fixtures/2.40.1/status-invalid.stdout.txt
new file mode 100644
index 0000000000..42776ef6c5
--- /dev/null
+++ b/server/github/fixtures/2.40.1/status-invalid.stdout.txt
@@ -0,0 +1,6 @@
+github.com
+ X Failed to log in to github.com account octo-fixture (/tmp/x.FIXTURE/cfg/hosts.yml)
+ - Active account: true
+ - The token in /tmp/x.FIXTURE/cfg/hosts.yml is invalid.
+ - To re-authenticate, run: gh auth login -h github.com
+ - To forget about this account, run: gh auth logout -h github.com -u octo-fixture
diff --git a/server/github/fixtures/2.40.1/status-json.stderr.txt b/server/github/fixtures/2.40.1/status-json.stderr.txt
new file mode 100644
index 0000000000..a232f3e7bb
--- /dev/null
+++ b/server/github/fixtures/2.40.1/status-json.stderr.txt
@@ -0,0 +1,8 @@
+unknown flag: --json
+
+Usage: gh auth status [flags]
+
+Flags:
+ -h, --hostname string Check a specific hostname's auth status
+ -t, --show-token Display the auth token
+
diff --git a/server/github/fixtures/2.40.1/status-offline.stdout.txt b/server/github/fixtures/2.40.1/status-offline.stdout.txt
new file mode 100644
index 0000000000..42776ef6c5
--- /dev/null
+++ b/server/github/fixtures/2.40.1/status-offline.stdout.txt
@@ -0,0 +1,6 @@
+github.com
+ X Failed to log in to github.com account octo-fixture (/tmp/x.FIXTURE/cfg/hosts.yml)
+ - Active account: true
+ - The token in /tmp/x.FIXTURE/cfg/hosts.yml is invalid.
+ - To re-authenticate, run: gh auth login -h github.com
+ - To forget about this account, run: gh auth logout -h github.com -u octo-fixture
diff --git a/server/github/fixtures/2.40.1/status-signedout.stderr.txt b/server/github/fixtures/2.40.1/status-signedout.stderr.txt
new file mode 100644
index 0000000000..8b4d2a5c98
--- /dev/null
+++ b/server/github/fixtures/2.40.1/status-signedout.stderr.txt
@@ -0,0 +1 @@
+You are not logged into any GitHub hosts. To log in, run: gh auth login
diff --git a/server/github/fixtures/2.40.1/version.stdout.txt b/server/github/fixtures/2.40.1/version.stdout.txt
new file mode 100644
index 0000000000..ba2a57711e
--- /dev/null
+++ b/server/github/fixtures/2.40.1/version.stdout.txt
@@ -0,0 +1,2 @@
+gh version 2.40.1 (2023-12-13)
+https://github.com/cli/cli/releases/tag/v2.40.1
diff --git a/server/github/fixtures/constructed/hosts.yml.txt b/server/github/fixtures/constructed/hosts.yml.txt
new file mode 100644
index 0000000000..be00c941dd
--- /dev/null
+++ b/server/github/fixtures/constructed/hosts.yml.txt
@@ -0,0 +1,7 @@
+github.com:
+ users:
+ octo-fixture:
+ oauth_token: TOKEN
+ git_protocol: https
+ oauth_token: TOKEN
+ user: octo-fixture
diff --git a/server/github/fixtures/constructed/status-json-success.stdout.txt b/server/github/fixtures/constructed/status-json-success.stdout.txt
new file mode 100644
index 0000000000..4ae3361da0
--- /dev/null
+++ b/server/github/fixtures/constructed/status-json-success.stdout.txt
@@ -0,0 +1 @@
+{"hosts":{"github.com":[{"state":"success","active":true,"host":"github.com","login":"octo-fixture","tokenSource":"/tmp/x.FIXTURE/config/hosts.yml","scopes":"gist, read:org, repo","gitProtocol":"https"}]}}
diff --git a/server/github/fixtures/constructed/status-text-success-before-2.40.stdout.txt b/server/github/fixtures/constructed/status-text-success-before-2.40.stdout.txt
new file mode 100644
index 0000000000..3adba90803
--- /dev/null
+++ b/server/github/fixtures/constructed/status-text-success-before-2.40.stdout.txt
@@ -0,0 +1,5 @@
+github.com
+ ✓ Logged in to github.com as octo-fixture (/tmp/x.FIXTURE/config/hosts.yml)
+ ✓ Git operations for github.com configured to use https protocol.
+ ✓ Token: gho_************************************
+ ✓ Token scopes: gist, read:org, repo
diff --git a/server/github/fixtures/constructed/status-text-success.stderr.txt b/server/github/fixtures/constructed/status-text-success.stderr.txt
new file mode 100644
index 0000000000..3f35d16832
--- /dev/null
+++ b/server/github/fixtures/constructed/status-text-success.stderr.txt
@@ -0,0 +1,6 @@
+github.com
+ ✓ Logged in to github.com account octo-fixture (/tmp/x.FIXTURE/config/hosts.yml)
+ - Active account: true
+ - Git operations protocol: https
+ - Token: gho_************************************
+ - Token scopes: 'gist', 'read:org', 'repo'
diff --git a/server/github/gh-cli.test.ts b/server/github/gh-cli.test.ts
new file mode 100644
index 0000000000..e693e72479
--- /dev/null
+++ b/server/github/gh-cli.test.ts
@@ -0,0 +1,42 @@
+import { describe, expect, it } from "vitest";
+
+import { ghCredentialTargets, loginArgs, ownGhEnv, windowsGhDirs } from "./gh-cli.ts";
+
+describe("running GitHub CLI for OpenMausBot's own sign-in", () => {
+ it("passes on no token, no D-Bus session and none of the server's HOME", () => {
+ const env = ownGhEnv({ home: "/data/github/owner/home", config: "/data/github/owner/config" }, {
+ PATH: "/usr/bin", HOME: "/data", GH_TOKEN: "x", GITHUB_TOKEN: "x", GH_ENTERPRISE_TOKEN: "x", DBUS_SESSION_BUS_ADDRESS: "unix:path=/run/user/1000/bus",
+ HTTPS_PROXY: "http://proxy:3128", OMB_ANYTHING: "x",
+ }, "linux");
+ expect(env).toMatchObject({ PATH: "/usr/bin", HOME: "/data/github/owner/home", GH_CONFIG_DIR: "/data/github/owner/config", HTTPS_PROXY: "http://proxy:3128",
+ DBUS_SESSION_BUS_ADDRESS: "unix:path=/data/github/owner/home/.run/no-bus", XDG_RUNTIME_DIR: "/data/github/owner/home/.run" });
+ for (const name of ["GH_TOKEN", "GITHUB_TOKEN", "GH_ENTERPRISE_TOKEN", "OMB_ANYTHING"]) expect(env[name], name).toBeUndefined();
+ expect(ownGhEnv({ home: "C:\\h", config: "C:\\c" }, { PATH: "C:\\Windows" }, "win32")).toMatchObject({ USERPROFILE: "C:\\h", APPDATA: "C:\\h\\AppData\\Roaming" });
+ });
+
+ it("asks for a non-expiring token only where gh takes the flag", () => {
+ expect(loginArgs([2, 103, 3])).toContain("--expiring=false");
+ expect(loginArgs([2, 102, 0])).not.toContain("--expiring=false");
+ expect(loginArgs([2, 102, 0])).toEqual(expect.arrayContaining(["--insecure-storage", "--clipboard=false", "--web"]));
+ });
+
+ it("looks for gh where GitHub CLI's Windows installers put it", () => {
+ const dirs = windowsGhDirs({ ProgramFiles: "C:\\Program Files", LOCALAPPDATA: "C:\\Users\\ada\\AppData\\Local" }, "C:\\Users\\ada");
+ expect(dirs.join("|")).toMatch(/Program Files.GitHub CLI/u);
+ expect(dirs.join("|")).toMatch(/WinGet.Links/u);
+ expect(dirs.join("|")).toMatch(/scoop.shims/u);
+ });
+
+ it("finds gh's entries in Credential Manager's list", () => {
+ const listing = [
+ "Currently stored credentials:", "",
+ " Target: LegacyGeneric:target=gh:github.com:octo-fixture", " Type: Generic", " User: octo-fixture", "",
+ " Target: LegacyGeneric:target=gh:github.com:", " Type: Generic", "",
+ " Target: LegacyGeneric:target=gh:_refreshable:github.com:octo-fixture", "",
+ " Target: LegacyGeneric:target=git:https://github.com", "",
+ " Target: MicrosoftAccount:target=SSO_POP_Device", "",
+ ].join("\r\n");
+ expect(ghCredentialTargets(listing)).toEqual(["gh:github.com:octo-fixture", "gh:github.com:", "gh:_refreshable:github.com:octo-fixture"]);
+ expect(ghCredentialTargets("Currently stored credentials:\r\n\r\n* NONE *\r\n")).toEqual([]);
+ });
+});
diff --git a/server/github/gh-cli.ts b/server/github/gh-cli.ts
new file mode 100644
index 0000000000..60a04c20d0
--- /dev/null
+++ b/server/github/gh-cli.ts
@@ -0,0 +1,177 @@
+// Finding and running GitHub CLI for the sign-in (sign-in.ts). Two copies can run:
+// - the person's own `gh` on This computer, found on PATH: read for their own sign-in, and run for OpenMausBot's sign-in
+// when it is new enough (GH_SIGN_IN_FLOOR) to take every flag below;
+// - the app's pinned copy (gh-release.ts), downloaded and checked on the first sign-in that needs it.
+// Security: gh keeps a sign-in in the OS credential store under one name whatever its config folder, and its login and
+// logout delete entries there. OpenMausBot's own runs therefore get a private HOME (macOS finds no login keychain
+// through it), a D-Bus session address that leads nowhere (godbus uses a set address as it is, and without one it would
+// find /run/user/<uid>/bus by the uid: the person's Secret Service) and `--insecure-storage`, so the token is only ever
+// in the private config folder; and they never run `gh auth logout` (sign-in.ts deletes the folder instead). Windows'
+// Credential Manager cannot be redirected: there sign-in.ts starts a sign-in only when the person's own gh positively
+// has none and Credential Manager holds no gh entry (windowsGhCredentials).
+import { spawn, execFile, type ChildProcess } from "node:child_process";
+import { homedir } from "node:os";
+import { delimiter, isAbsolute, join, relative } from "node:path";
+
+import { stripWorkspaceCredentialEnv } from "../credential-env.ts";
+import { installStandaloneEngine, standaloneCurrentVersion, standaloneRoot, type StandaloneInstallOptions } from "../engine-standalone.ts";
+import { augmentedPath, findCliCandidates } from "../env-path.ts";
+import { GH_STANDALONE } from "./gh-release.ts";
+import { parseGhVersion, versionAtLeast } from "./gh-output.ts";
+
+/** The first release recorded taking `--clipboard=false` and `--insecure-storage` (fixtures/2.102.0); 2.40.1 refuses
+ * `--clipboard`, and without it 2.102.0 copies the code to the computer's clipboard. */
+export const GH_SIGN_IN_FLOOR = [2, 102, 0] as const;
+/** From here gh takes `--expiring=false`, which asks GitHub for a token that does not expire. */
+const EXPIRING_FLAG_FROM = [2, 103, 0] as const;
+const OUTPUT_MAX = 64 * 1024;
+export const GH_CALL_TIMEOUT_MS = 30_000;
+
+export interface GhRun { code: number; stdout: string; stderr: string }
+export interface GhChild {
+ stdout: NodeJS.ReadableStream;
+ stderr: NodeJS.ReadableStream;
+ once(event: "close", listener: (code: number | null) => void): unknown;
+ once(event: "error", listener: (error: Error) => void): unknown;
+ kill(signal?: NodeJS.Signals): boolean;
+}
+
+/** Everything sign-in.ts asks of the machine, so its tests can stand a fake gh in. */
+export interface GhTools {
+ /** The person's own gh on This computer, never the app's copy; null where their own may not be used (a Cloud home, a
+ * boxed server) or there is none. */
+ personal(): string | null;
+ version(file: string): Promise<[number, number, number] | null>;
+ /** The app's pinned copy when it is installed and checked in this run, without downloading. */
+ pinnedReady(): string | null;
+ /** The app's folder names the pinned version as installed (not checked): a sign-in would not download. */
+ pinnedOnDisk(): boolean;
+ /** The app's pinned copy, downloading and checking it when needed. */
+ install(): Promise<string>;
+ spawn(file: string, args: readonly string[], env: Record<string, string>): GhChild;
+ run(file: string, args: readonly string[], env: Record<string, string>, timeoutMs?: number): Promise<GhRun>;
+ /** Windows only: the gh entries in the person's Credential Manager (`cmdkey /list`), null when it could not be read. */
+ windowsGhCredentials(): Promise<string[] | null>;
+}
+
+/** Where GitHub CLI's own Windows installers put gh, which a server started before the install may not have on PATH:
+ * the MSI, WinGet's links and scoop's shims. */
+export function windowsGhDirs(env: NodeJS.ProcessEnv = process.env, home: string = homedir()): string[] {
+ const localAppData = env.LOCALAPPDATA ?? join(home, "AppData", "Local");
+ return [join(env.ProgramFiles ?? "C:\\Program Files", "GitHub CLI"), join(localAppData, "Microsoft", "WinGet", "Links"), join(env.SCOOP ?? join(home, "scoop"), "shims")];
+}
+
+/** gh's Credential Manager targets in `cmdkey /list` output: `gh:github.com:<login>`, `gh:_refreshable:github.com:...`. */
+export function ghCredentialTargets(output: string): string[] {
+ const found = new Set<string>();
+ for (const match of output.matchAll(/Target:\s*(?:LegacyGeneric:target=)?(gh:(?:_refreshable:)?github\.com\S*)/giu)) found.add(match[1]!);
+ return [...found];
+}
+
+/** gh's `auth login` for OpenMausBot's own sign-in. */
+export function loginArgs(version: readonly number[] | null): string[] {
+ return ["auth", "login", "--hostname", "github.com", "--git-protocol", "https", "--web", "--insecure-storage", "--clipboard=false",
+ ...(versionAtLeast(version, EXPIRING_FLAG_FROM) ? ["--expiring=false"] : [])];
+}
+
+/** What the server passes on to OpenMausBot's own gh runs: where programs are, the proxy and certificate settings, and on
+ * Windows what any program needs to start. Never a token (GH_TOKEN, GITHUB_TOKEN), a D-Bus address or the server's HOME. */
+const PASSED = ["PATH", "LANG", "LC_ALL", "HTTPS_PROXY", "https_proxy", "HTTP_PROXY", "http_proxy", "NO_PROXY", "no_proxy", "ALL_PROXY", "all_proxy",
+ "SSL_CERT_FILE", "SSL_CERT_DIR", "SystemRoot", "SYSTEMROOT", "windir", "ComSpec", "PATHEXT", "TEMP", "TMP", "TMPDIR"] as const;
+
+/** The environment of OpenMausBot's own gh runs for one sign-in folder (`home` and `config` are private to it). */
+export function ownGhEnv(folders: { home: string; config: string }, base: NodeJS.ProcessEnv = process.env, platform: NodeJS.Platform = process.platform): Record<string, string> {
+ const env: Record<string, string> = {};
+ for (const name of PASSED) {
+ const value = base[name];
+ if (typeof value === "string" && value) env[name] = value;
+ }
+ if (!env.PATH) env.PATH = platform === "win32" ? "" : "/usr/local/bin:/usr/bin:/bin";
+ Object.assign(env, {
+ HOME: folders.home,
+ GH_CONFIG_DIR: folders.config,
+ XDG_CONFIG_HOME: `${folders.home}/.config`,
+ XDG_DATA_HOME: `${folders.home}/.local/share`,
+ XDG_STATE_HOME: `${folders.home}/.local/state`,
+ XDG_CACHE_HOME: `${folders.home}/.cache`,
+ XDG_RUNTIME_DIR: `${folders.home}/.run`,
+ // A session bus address that leads nowhere: godbus takes a set address as it is, so the keyring is simply unavailable.
+ // Unset, it would find the person's session bus at /run/user/<uid>/bus by the uid and reach their Secret Service.
+ DBUS_SESSION_BUS_ADDRESS: `unix:path=${folders.home}/.run/no-bus`,
+ GH_NO_UPDATE_NOTIFIER: "1",
+ GH_NO_EXTENSION_UPDATE_NOTIFIER: "1",
+ GH_TELEMETRY: "false",
+ DO_NOT_TRACK: "1",
+ GH_PROMPT_DISABLED: "1",
+ GH_SPINNER_DISABLED: "1",
+ NO_COLOR: "1",
+ // gh asks git to use it as git's credential helper; that setting lands in this private HOME, never the person's.
+ GIT_CONFIG_NOSYSTEM: "1",
+ });
+ if (platform === "win32") Object.assign(env, { USERPROFILE: folders.home, APPDATA: `${folders.home}\\AppData\\Roaming`, LOCALAPPDATA: `${folders.home}\\AppData\\Local` });
+ return env;
+}
+
+/** The person's own gh reads their own sign-in: their environment, without the workspace's credentials. */
+export function personalGhEnv(base: NodeJS.ProcessEnv = process.env): Record<string, string> {
+ const env: Record<string, string | undefined> = { ...base, PATH: augmentedPath(), GH_NO_UPDATE_NOTIFIER: "1", GH_PROMPT_DISABLED: "1", GH_SPINNER_DISABLED: "1", NO_COLOR: "1" };
+ stripWorkspaceCredentialEnv(env);
+ for (const name of Object.keys(env)) if (name.startsWith("OMB_")) delete env[name];
+ return Object.fromEntries(Object.entries(env).filter((entry): entry is [string, string] => typeof entry[1] === "string"));
+}
+
+function inside(parent: string, child: string): boolean {
+ const rel = relative(parent, child);
+ return rel !== "" && !rel.startsWith("..") && !isAbsolute(rel);
+}
+
+export interface GhToolsOptions {
+ dataDir: string;
+ /** Whether the person's own gh may be used here: This computer, with no bot box. */
+ personalAllowed(): boolean;
+ install?: StandaloneInstallOptions;
+}
+
+export function createGhTools(options: GhToolsOptions): GhTools {
+ let pinned: string | null = null;
+ const versions = new Map<string, Promise<[number, number, number] | null>>();
+ const run = (file: string, args: readonly string[], env: Record<string, string>, timeoutMs = GH_CALL_TIMEOUT_MS) => new Promise<GhRun>((resolve) => {
+ execFile(file, [...args], { env, timeout: timeoutMs, killSignal: "SIGKILL", maxBuffer: OUTPUT_MAX, windowsHide: true, encoding: "utf8" }, (error, stdout, stderr) => {
+ const failed = error as (NodeJS.ErrnoException & { code?: number | string }) | null;
+ resolve({ code: failed ? (typeof failed.code === "number" ? failed.code : 1) : 0, stdout: String(stdout ?? ""), stderr: String(stderr ?? "") });
+ });
+ });
+ return {
+ personal() {
+ if (!options.personalAllowed()) return null;
+ const own = standaloneRoot(options.dataDir);
+ const path = process.platform === "win32" ? [augmentedPath(), ...windowsGhDirs()].join(delimiter) : augmentedPath();
+ return findCliCandidates("gh", path).find((found) => !inside(own, found)) ?? null;
+ },
+ version(file) {
+ let known = versions.get(file);
+ if (!known) {
+ known = run(file, ["--version"], { PATH: process.env.PATH ?? "", GH_NO_UPDATE_NOTIFIER: "1", ...(process.env.SystemRoot ? { SystemRoot: process.env.SystemRoot } : {}) }).then((result) => (result.code === 0 ? parseGhVersion(result.stdout) : null));
+ versions.set(file, known);
+ }
+ return known;
+ },
+ pinnedReady: () => pinned,
+ pinnedOnDisk: () => standaloneCurrentVersion(GH_STANDALONE, options.dataDir) === GH_STANDALONE.version,
+ async install() {
+ const installed = await installStandaloneEngine(GH_STANDALONE, { baseDir: options.dataDir, ...options.install });
+ pinned = installed.executablePath;
+ return pinned;
+ },
+ spawn(file, args, env) {
+ const child: ChildProcess = spawn(file, [...args], { env, stdio: ["ignore", "pipe", "pipe"], windowsHide: true });
+ return child as unknown as GhChild;
+ },
+ run,
+ async windowsGhCredentials() {
+ const system = process.env.SystemRoot ?? process.env.SYSTEMROOT ?? "C:\\Windows";
+ const result = await run(join(system, "System32", "cmdkey.exe"), ["/list"], { SystemRoot: system, PATH: process.env.PATH ?? "" });
+ return result.code === 0 ? ghCredentialTargets(result.stdout) : null;
+ },
+ };
+}
diff --git a/server/github/gh-dbus.test.ts b/server/github/gh-dbus.test.ts
new file mode 100644
index 0000000000..5f2dd9d60c
--- /dev/null
+++ b/server/github/gh-dbus.test.ts
@@ -0,0 +1,55 @@
+// Linux, with a real gh on PATH (GitHub's Linux runners have one): gh reaches the keyring through the session bus address
+// it is given, so the dead address ownGhEnv sets is the one it dials, never the person's Secret Service. Without an
+// address godbus would find /run/user/<uid>/bus by the uid; this proves a set address is what decides.
+import { execFile } from "node:child_process";
+import { mkdirSync, mkdtempSync, rmSync } from "node:fs";
+import { createServer, type Server } from "node:net";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { afterEach, describe, expect, it } from "vitest";
+
+import { findCliCandidates } from "../env-path.ts";
+import { ownGhEnv } from "./gh-cli.ts";
+
+const gh = process.platform === "linux" ? findCliCandidates("gh")[0] : undefined;
+
+const run = (env: Record<string, string>) => new Promise<{ code: number | null; output: string }>((resolve) => {
+ execFile(gh!, ["auth", "token", "--hostname", "github.com"], { env, timeout: 60_000, encoding: "utf8" }, (error, stdout, stderr) => {
+ resolve({ code: error ? (typeof (error as { code?: unknown }).code === "number" ? (error as { code: number }).code : 1) : 0, output: `${stdout}${stderr}` });
+ });
+});
+
+let dir = "";
+let bus: Server | null = null;
+afterEach(() => {
+ bus?.close();
+ bus = null;
+ if (dir) rmSync(dir, { recursive: true, force: true });
+});
+
+describe.skipIf(!gh)("GitHub CLI and the D-Bus session (Linux)", () => {
+ it("dials the address it is given, so OpenMausBot's dead one keeps it away from the person's keyring", async () => {
+ dir = mkdtempSync(join(tmpdir(), "omb-gh-dbus-"));
+ const folders = { home: join(dir, "home"), config: join(dir, "config") };
+ for (const folder of [folders.home, folders.config, join(folders.home, ".run")]) mkdirSync(folder, { recursive: true });
+ let dialled = 0;
+ const socket = join(dir, "bus.sock");
+ bus = createServer((connection) => {
+ dialled++;
+ connection.destroy();
+ });
+ await new Promise<void>((resolve) => bus!.listen(socket, resolve));
+
+ // With no saved sign-in, gh asks the keyring, over the session bus at the address it was given.
+ const listening = await run({ ...ownGhEnv(folders), DBUS_SESSION_BUS_ADDRESS: `unix:path=${socket}` });
+ expect(listening.code).not.toBe(0);
+ expect(dialled).toBeGreaterThan(0);
+
+ // OpenMausBot's own address: nothing there, the keyring is unavailable, and gh simply has no token.
+ dialled = 0;
+ const own = await run(ownGhEnv(folders));
+ expect(own.code).not.toBe(0);
+ expect(own.output).not.toMatch(/gh[ou]_|github_pat_/u);
+ expect(dialled).toBe(0);
+ });
+});
diff --git a/server/github/gh-output.test.ts b/server/github/gh-output.test.ts
new file mode 100644
index 0000000000..fee56e4502
--- /dev/null
+++ b/server/github/gh-output.test.ts
@@ -0,0 +1,100 @@
+// fixtures/<version>/ is what those GitHub CLI releases printed on 2026-11-24, run without a terminal in an empty
+// config folder (temp paths and addresses replaced). fixtures/constructed/ is built from gh's own format strings
+// (pkg/cmd/auth/status/status.go) for the answers a recording cannot give without a real account: a working sign-in.
+import { readFileSync } from "node:fs";
+import { describe, expect, it } from "vitest";
+
+import { hostsFileLogin, hostsFileToken, loginFailure, parseDeviceCode, parseGhVersion, parseScopes, parseStatusJson, parseStatusText, tokenFrom, VERIFICATION_URL, versionAtLeast } from "./gh-output.ts";
+
+const fixture = (name: string) => readFileSync(new URL(`./fixtures/${name}`, import.meta.url), "utf8");
+
+describe("GitHub CLI's output", () => {
+ it("reads the code and the device page from every recorded release, with or without the clipboard line", () => {
+ expect(parseDeviceCode(fixture("2.40.1/login.stderr.txt"))).toEqual({ code: "7E95-AA50", verificationUrl: VERIFICATION_URL });
+ expect(parseDeviceCode(fixture("2.102.0/login.stderr.txt"))).toEqual({ code: "6C49-C9EB", verificationUrl: VERIFICATION_URL });
+ expect(parseDeviceCode(fixture("2.102.0/login-clipboard.stderr.txt"))).toEqual({ code: "0DE6-7337", verificationUrl: VERIFICATION_URL });
+ expect(parseDeviceCode(fixture("2.103.3/login.stderr.txt"))).toEqual({ code: "B1A5-0221", verificationUrl: VERIFICATION_URL });
+ // Colour codes and Windows line ends change nothing.
+ expect(parseDeviceCode("\u001b[33m!\u001b[0m First copy your one-time code: \u001b[1mABCD-1234\u001b[0m\r\nOpen this URL to continue in your web browser: https://github.com/login/device\r\n")?.code).toBe("ABCD-1234");
+ });
+
+ it("waits for both lines, and never takes another site as the place to type the code", () => {
+ expect(parseDeviceCode("! First copy your one-time code: ABCD-1234\n")).toBeNull();
+ expect(parseDeviceCode("Open this URL to continue in your web browser: https://github.com/login/device")).toBeNull();
+ expect(parseDeviceCode("! First copy your one-time code: ABCD-1234\nOpen this URL: https://github.com.evil.example/login/device")).toBeNull();
+ expect(parseDeviceCode("! First copy your one-time code: ABCD-1234\nOpen this URL: http://github.com/login/device")).toBeNull();
+ expect(parseDeviceCode("! First copy your one-time code: ABCD-1234\nOpen this URL: https://evil.example/?u=https://github.com/login/device")).toBeNull();
+ });
+
+ it("reads versions, and which releases take the sign-in's flags", () => {
+ expect(parseGhVersion(fixture("2.40.1/version.stdout.txt"))).toEqual([2, 40, 1]);
+ expect(parseGhVersion(fixture("2.102.0/version.stdout.txt"))).toEqual([2, 102, 0]);
+ expect(parseGhVersion(fixture("2.103.3/version.stdout.txt"))).toEqual([2, 103, 3]);
+ expect(parseGhVersion("git version 2.46.0")).toBeNull();
+ expect(versionAtLeast([2, 102, 0], [2, 102, 0])).toBe(true);
+ expect(versionAtLeast([2, 40, 1], [2, 102, 0])).toBe(false);
+ expect(versionAtLeast([3, 0, 0], [2, 102, 0])).toBe(true);
+ expect(versionAtLeast(null, [2, 102, 0])).toBe(false);
+ // 2.40.1 refuses the clipboard flag the floor exists for.
+ expect(fixture("2.40.1/login-clipboard-flag.stderr.txt")).toContain("unknown flag: --clipboard");
+ });
+
+ it("counts a token as refused only on GitHub's own 401, never on no network", () => {
+ for (const version of ["2.102.0", "2.103.3"]) {
+ expect(parseStatusJson(fixture(`${version}/status-json-invalid.stdout.txt`))).toEqual({ state: "invalid", login: "octo-fixture", scopes: [], error: "HTTP 401: Bad credentials (https://api.github.com/)" });
+ }
+ // The same `error` state with the network cut (HTTPS_PROXY to a closed port): unknown, not refused.
+ expect(parseStatusJson(fixture("2.103.3/status-json-offline.stdout.txt"))).toMatchObject({ state: "unknown", login: "octo-fixture" });
+ // The text reads the same for both (2.40.1 on stdout, 2.103.3 on stderr), so it is never taken as a refusal.
+ for (const name of ["2.102.0/status-invalid.stderr.txt", "2.103.3/status-invalid.stderr.txt", "2.40.1/status-invalid.stdout.txt", "2.103.3/status-offline.stderr.txt", "2.40.1/status-offline.stdout.txt"]) {
+ expect(parseStatusText(fixture(name)), name).toMatchObject({ state: "unknown", login: "octo-fixture" });
+ }
+ expect(fixture("2.103.3/status-offline.stderr.txt")).toBe(fixture("2.103.3/status-invalid.stderr.txt"));
+ expect(parseStatusText("github.com\n X Token for github.com account octo-fixture (keyring) has expired\n")).toMatchObject({ state: "invalid", login: "octo-fixture" });
+ // 2.40.1 has no --json: its answer is no JSON, so the text is read instead.
+ expect(parseStatusJson(fixture("2.40.1/status-json.stderr.txt"))).toBeNull();
+ });
+
+ it("reads signed out from every release", () => {
+ expect(parseStatusJson(fixture("2.102.0/status-json-signedout.stdout.txt"))).toBe("signed-out");
+ expect(parseStatusText(fixture("2.40.1/status-signedout.stderr.txt"))).toBe("signed-out");
+ expect(parseStatusText(fixture("2.103.3/status-signedout.stderr.txt"))).toBe("signed-out");
+ });
+
+ it("reads a working sign-in, its login and scopes, in each format", () => {
+ const want = { state: "success", login: "octo-fixture", scopes: ["gist", "read:org", "repo"] };
+ expect(parseStatusJson(fixture("constructed/status-json-success.stdout.txt"))).toEqual(want);
+ expect(parseStatusText(fixture("constructed/status-text-success.stderr.txt"))).toEqual(want);
+ expect(parseStatusText(fixture("constructed/status-text-success-before-2.40.stdout.txt"))).toEqual(want);
+ expect(parseScopes("repo, read:org, gist, <script>")).toEqual(["gist", "read:org", "repo"]);
+ });
+
+ it("answers null for anything it cannot recognise", () => {
+ for (const text of ["", "{", "{\"hosts\":[]}", "{\"hosts\":{\"github.com\":\"x\"}}", "something else entirely"]) {
+ expect(parseStatusJson(text)).toBeNull();
+ }
+ expect(parseStatusText("something else entirely")).toBeNull();
+ expect(parseStatusJson("{\"hosts\":{\"github.com\":[{\"state\":\"success\",\"active\":true,\"login\":\"bad login;rm\"}]}}")).toMatchObject({ state: "success", login: null });
+ });
+
+ it("says why a login ended in one plain line", () => {
+ expect(loginFailure(fixture("2.103.3/login-network-failure.stderr.txt"))).toEqual({ outcome: "failed", reason: "GitHub could not be reached from this server. Check its network connection, then try again." });
+ // gh 2.103.3 left waiting: it gave up by itself after 899 s with this line and exit code 1.
+ expect(loginFailure(fixture("2.103.3/login-expired.stderr.txt"))).toEqual({ outcome: "expired", reason: "The code expired before it was entered on GitHub." });
+ expect(loginFailure("failed to authenticate via web browser: access_denied")).toMatchObject({ outcome: "failed", reason: "The sign-in was turned down on GitHub." });
+ const other = loginFailure(`${fixture("2.103.3/login.stderr.txt")}something odd happened\n`);
+ expect(other).toEqual({ outcome: "failed", reason: "GitHub CLI stopped: something odd happened" });
+ });
+
+ it("reads the login from gh's config file, and a token only when it looks like one", () => {
+ expect(hostsFileLogin(fixture("constructed/hosts.yml.txt"))).toBe("octo-fixture");
+ const saved = ["gho", "y".repeat(36)].join("_");
+ expect(hostsFileToken(fixture("constructed/hosts.yml.txt").replaceAll("TOKEN", saved))).toBe(saved);
+ expect(hostsFileToken("gitlab.com:\n oauth_token: x\n")).toBeNull();
+ expect(hostsFileLogin("gitlab.com:\n user: someone\n")).toBeNull();
+ const token = ["gho", "x".repeat(36)].join("_");
+ expect(tokenFrom(`${token}\n`)).toBe(token);
+ expect(tokenFrom("no oauth token found for github.com")).toBeNull();
+ expect(tokenFrom("")).toBeNull();
+ });
+});
diff --git a/server/github/gh-output.ts b/server/github/gh-output.ts
new file mode 100644
index 0000000000..a92575f290
--- /dev/null
+++ b/server/github/gh-output.ts
@@ -0,0 +1,145 @@
+// Reading what GitHub CLI prints. Its text is for people and changes between releases, so every reader here takes what it
+// can recognise and answers null otherwise; fixtures/ holds what real releases printed (gh-output.test.ts).
+import { stripVTControlCharacters } from "node:util";
+
+export const VERIFICATION_URL = "https://github.com/login/device";
+
+/** gh's own wording around the code: `! First copy your one-time code: ABCD-1234`, or `! One-time code (ABCD-1234) copied
+ * to clipboard` when it put it on the clipboard. GitHub's user codes are eight letters and digits with a dash. */
+const CODE = /one-time code(?: \(|: )([A-Z0-9]{4}-[A-Z0-9]{4})\b/iu;
+const URL_IN_LINE = /https:\/\/[^\s"'<>]+/gu;
+
+export function plain(text: string): string {
+ return stripVTControlCharacters(text).replace(/\r\n?/gu, "\n");
+}
+
+/** `gh version 2.103.3 (2026-10-26)` → [2, 103, 3]. */
+export function parseGhVersion(text: string): [number, number, number] | null {
+ const match = /\bgh version (\d+)\.(\d+)\.(\d+)\b/u.exec(plain(text));
+ return match ? [Number(match[1]), Number(match[2]), Number(match[3])] : null;
+}
+
+export function versionAtLeast(version: readonly number[] | null, floor: readonly number[]): boolean {
+ if (!version) return false;
+ for (let i = 0; i < floor.length; i++) {
+ const have = version[i] ?? 0, want = floor[i] ?? 0;
+ if (have !== want) return have > want;
+ }
+ return true;
+}
+
+/** The code and where to type it, once gh has printed both. Only GitHub's own device page counts: any other address in
+ * the output is never shown to the person as the place to type a code. */
+export function parseDeviceCode(output: string): { code: string; verificationUrl: string } | null {
+ const text = plain(output);
+ const code = CODE.exec(text)?.[1]?.toUpperCase();
+ if (!code) return null;
+ for (const raw of text.match(URL_IN_LINE) ?? []) {
+ try {
+ const url = new URL(raw.replace(/[.,;)]+$/u, ""));
+ if (url.protocol === "https:" && url.host === "github.com" && url.pathname.replace(/\/$/u, "") === "/login/device") return { code, verificationUrl: VERIFICATION_URL };
+ } catch {
+ continue;
+ }
+ }
+ return null;
+}
+
+/** Why a login that gh ended without signing in ended, in one plain line, never gh's whole output. */
+export function loginFailure(output: string): { outcome: "expired" | "failed"; reason: string } {
+ const text = plain(output);
+ if (/expired_token|device[_ ]code[^\n]*expired|code has expired|token has expired/iu.test(text)) return { outcome: "expired", reason: "The code expired before it was entered on GitHub." };
+ if (/access_denied|denied|cancel+ed the authori[sz]ation/iu.test(text)) return { outcome: "failed", reason: "The sign-in was turned down on GitHub." };
+ if (/timed out|timeout|no such host|connection refused|network is unreachable|dial tcp|read tcp|EOF\b/iu.test(text)) return { outcome: "failed", reason: "GitHub could not be reached from this server. Check its network connection, then try again." };
+ const line = text.split("\n").map((one) => one.trim()).filter((one) => one && !CODE.test(one) && !one.startsWith("Open this URL")).at(-1);
+ return { outcome: "failed", reason: line ? `GitHub CLI stopped: ${line.slice(0, 200)}` : "GitHub CLI stopped before the sign-in finished." };
+}
+
+export interface GhAccount {
+ /** success: the token works; invalid: GitHub said so (HTTP 401, an expired or rejected token); unknown: anything else,
+ * such as no network. gh reports a network failure with the same `error` state as a refused token, so only GitHub's own
+ * 401 counts as refused. */
+ state: "success" | "invalid" | "unknown";
+ login: string | null;
+ scopes: string[];
+ error?: string;
+}
+
+const LOGIN = /^[A-Za-z0-9](?:[A-Za-z0-9-]{0,38})$/u;
+const cleanLogin = (value: unknown) => (typeof value === "string" && LOGIN.test(value) ? value : null);
+
+/** `X-OAuth-Scopes`-style `repo, read:org, gist`, or gh's quoted `'gist', 'read:org', 'repo'`. */
+export function parseScopes(value: unknown): string[] {
+ if (typeof value !== "string") return [];
+ return [...new Set(value.split(",").map((one) => one.trim().replace(/^'|'$/gu, "").trim()).filter((one) => /^[a-z:_]{1,40}$/u.test(one)))].sort();
+}
+
+/** `gh auth status --hostname github.com --json hosts` (gh 2.7x and later): the active github.com account. */
+export function parseStatusJson(stdout: string): GhAccount | "signed-out" | null {
+ let parsed: unknown;
+ try {
+ parsed = JSON.parse(plain(stdout).trim());
+ } catch {
+ return null;
+ }
+ const hosts = (parsed as { hosts?: unknown })?.hosts;
+ if (!hosts || typeof hosts !== "object" || Array.isArray(hosts)) return null;
+ const entries = (hosts as Record<string, unknown>)["github.com"];
+ if (entries === undefined) return "signed-out";
+ if (!Array.isArray(entries)) return null;
+ const entry = (entries.find((one) => (one as { active?: unknown })?.active === true) ?? entries[0]) as Record<string, unknown> | undefined;
+ if (!entry) return "signed-out";
+ const error = typeof entry.error === "string" ? entry.error.slice(0, 200) : undefined;
+ const refused = (entry.state === "error" && error !== undefined && /\bHTTP 401\b|Bad credentials/u.test(error)) || entry.state === "expired" || entry.state === "refresh_expired";
+ const state = entry.state === "success" ? "success" : refused ? "invalid" : "unknown";
+ return { state, login: cleanLogin(entry.login), scopes: parseScopes(entry.scopes), ...(error ? { error } : {}) };
+}
+
+/** `gh auth status --hostname github.com` as text, for a gh without `--json` (before 2.7x). Older releases print it on
+ * stdout with exit 0 even for a refused token, newer ones on stderr with exit 1, so both streams are read together. Its
+ * "Failed to log in" reads the same for a refused token and for no network (fixtures/*-offline), so it is unknown. */
+export function parseStatusText(output: string): GhAccount | "signed-out" | null {
+ const text = plain(output);
+ if (/not logged in(?:to any GitHub hosts| to any hosts)/iu.test(text)) return "signed-out";
+ const ok = /Logged in to github\.com (?:account|as) (\S+)/u.exec(text);
+ const refused = /(?:Token for github\.com account (\S+) [^\n]*has expired|Refresh token for github\.com account (\S+) was rejected)/u.exec(text);
+ const unchecked = /(?:Failed|Timeout trying) to log in to github\.com (?:account|as) (\S+)/u.exec(text);
+ const scopes = parseScopes(/Token scopes: ([^\n]*)/u.exec(text)?.[1]);
+ if (ok) return { state: "success", login: cleanLogin(ok[1]), scopes };
+ if (refused) return { state: "invalid", login: cleanLogin(refused[1] ?? refused[2]), scopes, error: "GitHub no longer accepts this sign-in." };
+ if (unchecked) return { state: "unknown", login: cleanLogin(unchecked[1]), scopes };
+ return null;
+}
+
+/** The account gh's own config file names for github.com (`user:` under the host), read without running gh. */
+export function hostsFileLogin(text: string): string | null {
+ const lines = plain(text).split("\n");
+ let inHost = false;
+ for (const line of lines) {
+ if (/^\S/u.test(line)) inHost = /^github\.com:\s*$/u.test(line);
+ else if (inHost) {
+ const match = /^ {4}user:\s*(\S+)\s*$/u.exec(line) ?? /^\s+user:\s*(\S+)\s*$/u.exec(line);
+ if (match) return cleanLogin(match[1]);
+ }
+ }
+ return null;
+}
+
+/** The token gh's config file holds for github.com with `--insecure-storage` (`oauth_token:` under the host), or null. */
+export function hostsFileToken(text: string): string | null {
+ let inHost = false;
+ for (const line of plain(text).split("\n")) {
+ if (/^\S/u.test(line)) inHost = /^github\.com:\s*$/u.test(line);
+ else if (inHost) {
+ const match = /^ {4}oauth_token:\s*(\S+)\s*$/u.exec(line);
+ if (match) return tokenFrom(match[1]!);
+ }
+ }
+ return null;
+}
+
+/** What `gh auth token` printed, when it looks like a GitHub token and nothing else. */
+export function tokenFrom(stdout: string): string | null {
+ const token = stdout.trim();
+ return /^[A-Za-z0-9_]{20,255}$/u.test(token) ? token : null;
+}
diff --git a/server/github/gh-release.ts b/server/github/gh-release.ts
new file mode 100644
index 0000000000..f65d1dd187
--- /dev/null
+++ b/server/github/gh-release.ts
@@ -0,0 +1,38 @@
+// GitHub CLI (`gh`, MIT, github.com/cli/cli), for signing in to GitHub where the person has none of their own: a Cloud
+// home's image ships git but not gh. It is installed on the first sign-in through the same checked pipeline as the AIs'
+// own builds (engine-standalone.ts), never at start-up: it is not in STANDALONE_RELEASES, so no boot step looks at it.
+// From https://github.com/cli/cli/releases/tag/v2.103.3 (2026-10-26). Each archive SHA-256 is the `digest` GitHub reports
+// for the asset, and equals the line in gh_2.103.3_checksums.txt and `shasum -a 256` of the downloaded file (all three
+// checked on 2026-11-24). Each size is the asset's byte count. Each program SHA-256 is `shasum -a 256` of bin/gh (or
+// bin/gh.exe) unpacked from that verified archive (`tar -xzO` / `unzip -p`). The macOS programs are signed with GitHub's
+// Developer ID, Team VEKTX9H2N7 (codesign -dvv on 2026-11-24). gh is a static Go program, so the glibc builds also run
+// on a Linux without glibc.
+import type { StandaloneAsset, StandaloneRelease } from "../contracts.ts";
+
+export const GH_VERSION = "2.103.3";
+const RELEASE = `https://github.com/cli/cli/releases/download/v${GH_VERSION}`;
+const dir = (platform: string) => `gh_${GH_VERSION}_${platform}`;
+
+const LINUX_X64: StandaloneAsset = { url: `${RELEASE}/${dir("linux_amd64")}.tar.gz`, archive: "tar.gz", executable: `${dir("linux_amd64")}/bin/gh`, approxBytes: 15_031_972, sha256: "4c806978ffce1cec70853302a56d70ac6da4f19bae7adca4e1a8ab00633dd91d", executableSha256: "b768184570b12536be4ac1528893f6340d1c6a7b40b56ad45bca9cd0e87ad34d" };
+const LINUX_ARM64: StandaloneAsset = { url: `${RELEASE}/${dir("linux_arm64")}.tar.gz`, archive: "tar.gz", executable: `${dir("linux_arm64")}/bin/gh`, approxBytes: 13_661_485, sha256: "ee32df2323c8847f5fac6cb6b4b69ca75828e9329a8f22f677021f7b3306ce63", executableSha256: "a82a52e1bbe05bcd485f8cbbd5aa67e11a76fce6bdad394a2d179e1c24cfe367" };
+
+export const GH_STANDALONE: StandaloneRelease = {
+ name: "GitHub CLI",
+ engine: "github-cli",
+ version: GH_VERSION,
+ // github.com answers with a redirect to GitHub's release-asset host.
+ hosts: ["github.com", "release-assets.githubusercontent.com", "objects.githubusercontent.com"],
+ macTeamId: "VEKTX9H2N7",
+ // gh's own update check would tell the server about a newer gh it cannot install; the pin moves with a release.
+ runEnv: { GH_NO_UPDATE_NOTIFIER: "1", GH_TELEMETRY: "false", DO_NOT_TRACK: "1" },
+ assets: {
+ "linux-x64": LINUX_X64,
+ "linux-arm64": LINUX_ARM64,
+ "linux-x64-musl": LINUX_X64,
+ "linux-arm64-musl": LINUX_ARM64,
+ "darwin-x64": { url: `${RELEASE}/${dir("macOS_amd64")}.zip`, archive: "zip", executable: `${dir("macOS_amd64")}/bin/gh`, approxBytes: 15_702_601, sha256: "a2f86418f4350ae6e9ec60d5000bdf7665728436946a97fc27fe50e6ae752682", executableSha256: "547afd9491efe0730c7f42791b53529dccecda647837155cbd18ddedf92f799f" },
+ "darwin-arm64": { url: `${RELEASE}/${dir("macOS_arm64")}.zip`, archive: "zip", executable: `${dir("macOS_arm64")}/bin/gh`, approxBytes: 14_106_091, sha256: "d700207eae9ae98fe2b89535c2c087c07823d4628c56364695a5a07ef311c062", executableSha256: "5f8d7527e2bdf584249b030cdd1550c91d75e8afb40aa3c11573d416817a1260" },
+ "win32-x64": { url: `${RELEASE}/${dir("windows_amd64")}.zip`, archive: "zip", executable: "bin/gh.exe", approxBytes: 15_197_187, sha256: "98d0cfa794721665d7973dd728c78aff7bd836d58f10f6d7a03568eccb0a22e0", executableSha256: "d303d8ac3f5e9438bf7c977b64dd6425513eae46218f8881d30694f28c1d0dfd" },
+ "win32-arm64": { url: `${RELEASE}/${dir("windows_arm64")}.zip`, archive: "zip", executable: "bin/gh.exe", approxBytes: 13_637_549, sha256: "197211c98687d7770ac331fe8a3b6c198c389108c1536cdbedf659fe4703e484", executableSha256: "c387d066328aadb51a8c385f7d361995589904c4fcec1b412957b033e97b3dad" },
+ },
+};
diff --git a/server/github/sign-in.test.ts b/server/github/sign-in.test.ts
new file mode 100644
index 0000000000..f49966774a
--- /dev/null
+++ b/server/github/sign-in.test.ts
@@ -0,0 +1,492 @@
+import { EventEmitter } from "node:events";
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { PassThrough } from "node:stream";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import { createGhTools, type GhChild, type GhRun, type GhTools } from "./gh-cli.ts";
+import { createGithubSignIn, DEVICE_CODE_TTL_MS, githubFolders, GithubSignInError, type GithubSignInDeps } from "./sign-in.ts";
+
+const fixture = (name: string) => readFileSync(new URL(`./fixtures/${name}`, import.meta.url), "utf8");
+// Assembled here, never written out whole: it only has to look like a GitHub token.
+const TOKEN = ["gho", "Fixture0000000000000000000000000000x"].join("_");
+const PASTED = ["github", "pat", "11FIXTURE0", "x".repeat(40)].join("_");
+const MEMBER = `p_${"m".repeat(22)}`, OTHER = `p_${"o".repeat(22)}`;
+
+class FakeChild extends EventEmitter implements GhChild {
+ stdout = new PassThrough();
+ stderr = new PassThrough();
+ killed: NodeJS.Signals[] = [];
+ readonly file: string;
+ readonly args: readonly string[];
+ readonly env: Record<string, string>;
+ constructor(file: string, args: readonly string[], env: Record<string, string>) {
+ super();
+ this.file = file;
+ this.args = args;
+ this.env = env;
+ }
+ kill(signal: NodeJS.Signals = "SIGTERM") {
+ this.killed.push(signal);
+ queueMicrotask(() => this.emit("close", null));
+ return true;
+ }
+ /** What gh does once the code is entered: writes its config, then exits 0. */
+ approve(login = "octo-fixture") {
+ mkdirSync(this.env.GH_CONFIG_DIR!, { recursive: true });
+ writeFileSync(join(this.env.GH_CONFIG_DIR!, "hosts.yml"), fixture("constructed/hosts.yml.txt").replaceAll("TOKEN", TOKEN).replaceAll("octo-fixture", login));
+ this.emit("close", 0);
+ }
+ print(text: string) {
+ this.stderr.write(text);
+ }
+}
+
+interface Fake {
+ tools: GhTools;
+ children: FakeChild[];
+ calls: Array<{ file: string; args: readonly string[]; env: Record<string, string> }>;
+ set: { personal: string | null; version: [number, number, number] | null; pinned: string | null; onDisk: boolean; install: () => Promise<string>; personalStatus: GhRun; personalToken: GhRun; ownStatus: GhRun; winCreds: string[] | null };
+ installs: () => number;
+}
+
+const ok = (stdout: string): GhRun => ({ code: 0, stdout, stderr: "" });
+
+function fakeTools(): Fake {
+ const children: FakeChild[] = [];
+ const calls: Fake["calls"] = [];
+ let installs = 0;
+ const set: Fake["set"] = {
+ personal: null, version: [2, 103, 3], pinned: "/data/tools/standalone/github-cli/bin/gh", onDisk: true, install: () => Promise.resolve("/data/tools/standalone/github-cli/bin/gh"), winCreds: [],
+ personalStatus: ok(fixture("2.102.0/status-json-signedout.stdout.txt")), personalToken: { code: 1, stdout: "", stderr: "no oauth token found for github.com" },
+ ownStatus: ok(fixture("constructed/status-json-success.stdout.txt")),
+ };
+ const tools: GhTools = {
+ personal: () => set.personal,
+ version: async () => set.version,
+ pinnedReady: () => set.pinned,
+ pinnedOnDisk: () => set.pinned !== null || set.onDisk,
+ install: async () => {
+ installs++;
+ const file = await set.install();
+ set.pinned = file;
+ return file;
+ },
+ spawn(file, args, env) {
+ const child = new FakeChild(file, args, env);
+ children.push(child);
+ return child;
+ },
+ async run(file, args, env) {
+ calls.push({ file, args, env });
+ const personal = env.GH_CONFIG_DIR === undefined;
+ if (args[0] === "auth" && args[1] === "status") return personal ? set.personalStatus : set.ownStatus;
+ if (args[0] === "auth" && args[1] === "token") {
+ if (personal) return set.personalToken;
+ return existsSync(join(env.GH_CONFIG_DIR!, "hosts.yml")) ? ok(`${TOKEN}\n`) : { code: 1, stdout: "", stderr: "no oauth token found for github.com" };
+ }
+ if (args[0] === "api" && args[1] === "user/orgs") return ok("acme\nwidgets\n");
+ return { code: 1, stdout: "", stderr: "unknown command" };
+ },
+ windowsGhCredentials: async () => set.winCreds,
+ };
+ return { tools, children, calls, set, installs: () => installs };
+}
+
+function fakeVault(): GithubSignInDeps["vault"] & { saved: Map<string, { token: string; login: string }> } {
+ const saved = new Map<string, { token: string; login: string }>();
+ return {
+ saved,
+ githubToken: (audience) => saved.get(audience) ?? null,
+ setGithubToken: (audience, value) => {
+ if (value) saved.set(audience, value);
+ else saved.delete(audience);
+ },
+ };
+}
+
+const settle = () => new Promise<void>((resolve) => setImmediate(resolve));
+
+let dataDir: string;
+let clock: number;
+beforeEach(() => {
+ dataDir = mkdtempSync(join(tmpdir(), "omb-github-"));
+ clock = 1_000_000;
+});
+afterEach(() => {
+ vi.restoreAllMocks();
+ rmSync(dataDir, { recursive: true, force: true });
+});
+
+function setup(options: { team?: boolean; fetchImpl?: typeof fetch; platform?: NodeJS.Platform } = {}) {
+ const fake = fakeTools(), vault = fakeVault();
+ const remembered: string[] = [];
+ const signIn = createGithubSignIn({ dataDir, team: options.team ?? false, tools: fake.tools, vault, now: () => clock, fetchImpl: options.fetchImpl, remember: (token) => remembered.push(token), platform: options.platform ?? "linux" });
+ return { ...fake, vault, signIn, remembered };
+}
+
+async function showCode(fake: ReturnType<typeof setup>, audience = "owner") {
+ const started = await fake.signIn.start(audience);
+ expect(started.state).toBe("installing");
+ await settle();
+ const child = fake.children.at(-1)!;
+ child.print(fixture("2.103.3/login.stderr.txt"));
+ await settle();
+ return child;
+}
+
+describe("GitHub sign-in with GitHub CLI's device code", () => {
+ it("shows the code, then is signed in once it is entered on GitHub", async () => {
+ vi.stubEnv("GH_TOKEN", "from-the-server-environment");
+ vi.stubEnv("DBUS_SESSION_BUS_ADDRESS", "unix:path=/run/user/1000/bus");
+ const fake = setup();
+ expect(await fake.signIn.status("owner")).toEqual({ state: "signed-out", download: false });
+ const child = await showCode(fake);
+ expect(await fake.signIn.status("owner")).toEqual({ state: "signing-in", code: "B1A5-0221", verificationUrl: "https://github.com/login/device", expiresAt: clock + DEVICE_CODE_TTL_MS });
+ // A second Start joins the one running.
+ expect((await fake.signIn.start("owner")).state).toBe("signing-in");
+ expect(fake.children).toHaveLength(1);
+
+ expect(child.file).toBe("/data/tools/standalone/github-cli/bin/gh");
+ expect(child.args).toEqual(["auth", "login", "--hostname", "github.com", "--git-protocol", "https", "--web", "--insecure-storage", "--clipboard=false", "--expiring=false"]);
+ const folders = githubFolders(dataDir, "owner");
+ expect(child.env).toMatchObject({ HOME: folders.home, GH_CONFIG_DIR: folders.config, GH_PROMPT_DISABLED: "1", GH_TELEMETRY: "false", NO_COLOR: "1" });
+ for (const name of ["GH_TOKEN", "GITHUB_TOKEN", "GH_ENTERPRISE_TOKEN"]) expect(child.env[name], name).toBeUndefined();
+ // Never the person's session bus: an address in the private folder where nothing listens.
+ expect(child.env.DBUS_SESSION_BUS_ADDRESS).toBe(`unix:path=${folders.home}/.run/no-bus`);
+
+ child.approve();
+ await settle();
+ expect(await fake.signIn.status("owner")).toEqual({ state: "signed-in", login: "octo-fixture", source: "mausbot", scopes: ["gist", "read:org", "repo"], orgs: ["acme", "widgets"], checkedAt: clock });
+ expect(await fake.signIn.token()).toBe(TOKEN);
+ expect(fake.remembered).toEqual([TOKEN]);
+ // Cached: asking again does not ask GitHub, until someone asks for a check or a git action reports a refusal.
+ const statusCalls = () => fake.calls.filter((call) => call.args[1] === "status").length;
+ const before = statusCalls();
+ await fake.signIn.status("owner");
+ expect(statusCalls()).toBe(before);
+ await fake.signIn.status("owner", { check: true });
+ expect(statusCalls()).toBe(before + 1);
+ fake.set.ownStatus = ok(fixture("2.103.3/status-json-invalid.stdout.txt"));
+ fake.signIn.reportAuthFailure("owner");
+ expect(await fake.signIn.status("owner")).toMatchObject({ state: "invalid", login: "octo-fixture", source: "mausbot" });
+ });
+
+ it("reports an expired code when gh gives up, and when the code's time passed while gh still waits", async () => {
+ const fake = setup();
+ const child = await showCode(fake);
+ child.print(fixture("2.103.3/login-expired.stderr.txt").split("\n").slice(3).join("\n"));
+ child.emit("close", 1);
+ await settle();
+ expect(await fake.signIn.status("owner")).toMatchObject({ state: "signed-out", last: { outcome: "expired" } });
+
+ const second = await showCode(fake);
+ clock += DEVICE_CODE_TTL_MS + 1;
+ expect(await fake.signIn.status("owner")).toMatchObject({ state: "signed-out", last: { outcome: "expired" } });
+ expect(second.killed).toEqual(["SIGTERM"]);
+ expect(await fake.signIn.token()).toBeNull();
+ });
+
+ it("cancel stops gh, and gh's own exit afterwards changes nothing", async () => {
+ const fake = setup();
+ const child = await showCode(fake);
+ expect(await fake.signIn.cancel("owner")).toMatchObject({ state: "signed-out", last: { outcome: "cancelled" } });
+ expect(child.killed).toEqual(["SIGTERM"]);
+ child.approve();
+ await settle();
+ // gh wrote its file after the cancel: that is a sign-in GitHub made, so it shows; the attempt itself stays cancelled.
+ expect((await fake.signIn.status("owner")).state).toBe("signed-in");
+ });
+
+ it("a failed login says why, in one line of its own", async () => {
+ const fake = setup();
+ const child = await showCode(fake);
+ child.print(fixture("2.103.3/login-network-failure.stderr.txt").split("\n").slice(3).join("\n"));
+ child.emit("close", 1);
+ await settle();
+ expect(await fake.signIn.status("owner")).toMatchObject({ state: "signed-out", last: { outcome: "failed", reason: "GitHub could not be reached from this server. Check its network connection, then try again." } });
+ });
+
+ it("with no gh anywhere, Start downloads the pinned one first, and says so when that fails", async () => {
+ const fake = setup();
+ fake.set.pinned = null;
+ fake.set.onDisk = false;
+ let finish!: (file: string) => void;
+ fake.set.install = () => new Promise((resolve) => { finish = resolve; });
+ expect(await fake.signIn.status("owner")).toEqual({ state: "signed-out", download: true });
+ expect(await fake.signIn.start("owner")).toEqual({ state: "installing" });
+ expect(fake.children).toHaveLength(0);
+ finish("/data/tools/standalone/github-cli/bin/gh");
+ await settle();
+ expect(fake.children).toHaveLength(1);
+ await fake.signIn.cancel("owner");
+
+ const broken = setup();
+ broken.set.pinned = null;
+ broken.set.onDisk = false;
+ broken.set.install = () => Promise.reject(new Error("GitHub CLI has no download for this computer."));
+ await broken.signIn.start("owner");
+ await settle();
+ expect(await broken.signIn.status("owner")).toEqual({ state: "signed-out", download: true, last: { outcome: "failed", reason: "GitHub CLI has no download for this computer.", at: clock } });
+ expect(broken.children).toHaveLength(0);
+ });
+
+ it("a download that fails its checksum installs nothing and the sign-in says so", async () => {
+ const fetchImpl = vi.fn(async () => new Response(Buffer.from("this is not GitHub CLI"), { status: 200 })) as unknown as typeof fetch;
+ const tools = createGhTools({ dataDir, personalAllowed: () => false, install: { fetchImpl, platformKey: "linux-x64" } });
+ const spawn = vi.spyOn(tools, "spawn");
+ const signIn = createGithubSignIn({ dataDir, team: false, tools, vault: fakeVault(), now: () => clock });
+ expect(await signIn.start("owner")).toEqual({ state: "installing" });
+ for (let i = 0; i < 250 && (await signIn.status("owner")).state === "installing"; i++) await new Promise((resolve) => setTimeout(resolve, 20));
+ const status = await signIn.status("owner");
+ expect(status).toMatchObject({ state: "signed-out", download: true, last: { outcome: "failed" } });
+ expect((status as { last?: { reason?: string } }).last?.reason).toMatch(/safety check/u);
+ expect(fetchImpl).toHaveBeenCalledWith("https://github.com/cli/cli/releases/download/v2.103.3/gh_2.103.3_linux_amd64.tar.gz", expect.anything());
+ expect(spawn).not.toHaveBeenCalled();
+ expect(existsSync(join(dataDir, "tools", "standalone", "github-cli", "2.103.3"))).toBe(false);
+ });
+});
+
+describe("the person's own GitHub CLI on This computer", () => {
+ it("is used to sign in when it is new enough, and the pinned copy when it is not", async () => {
+ const fake = setup();
+ fake.set.personal = "/opt/homebrew/bin/gh";
+ fake.set.version = [2, 102, 0];
+ await showCode(fake);
+ expect(fake.children[0]!.file).toBe("/opt/homebrew/bin/gh");
+ expect(fake.children[0]!.args).not.toContain("--expiring=false");
+ await fake.signIn.cancel("owner");
+
+ fake.set.version = [2, 40, 1];
+ await showCode(fake);
+ expect(fake.children[1]!.file).toBe("/data/tools/standalone/github-cli/bin/gh");
+ });
+
+ it("is reported as the sign-in when it works, and Start is refused rather than touching its credential store", async () => {
+ const fake = setup();
+ fake.set.personal = "/usr/local/bin/gh";
+ fake.set.personalStatus = ok(fixture("constructed/status-json-success.stdout.txt"));
+ fake.set.personalToken = ok(`${TOKEN}\n`);
+ expect(await fake.signIn.status("owner")).toMatchObject({ state: "signed-in", login: "octo-fixture", source: "cli" });
+ await expect(fake.signIn.start("owner")).rejects.toMatchObject({ status: 409 });
+ expect(fake.children).toHaveLength(0);
+ expect(await fake.signIn.token()).toBe(TOKEN);
+ // Sign out is theirs to do, in their own terminal.
+ await expect(fake.signIn.signOut("owner")).rejects.toMatchObject({ status: 409 });
+ // Its own text format (before --json) counts the same.
+ const text = setup();
+ text.set.personal = "/usr/local/bin/gh";
+ text.tools.run = async (_file, args) => (args.includes("--json") ? { code: 1, stdout: "", stderr: fixture("2.40.1/status-json.stderr.txt") } : ok(fixture("constructed/status-text-success-before-2.40.stdout.txt")));
+ await expect(text.signIn.start("owner")).rejects.toBeInstanceOf(GithubSignInError);
+ expect(text.children).toHaveLength(0);
+ });
+
+ it("a sign-in of theirs that GitHub refuses (401) shows as such, and OpenMausBot's own sign-in may then start", async () => {
+ const fake = setup();
+ fake.set.personal = "/usr/local/bin/gh";
+ fake.set.version = [2, 40, 1];
+ fake.set.personalStatus = ok(fixture("2.103.3/status-json-invalid.stdout.txt"));
+ expect(await fake.signIn.status("owner")).toMatchObject({ state: "invalid", login: "octo-fixture", source: "cli" });
+ expect((await fake.signIn.start("owner")).state).toBe("installing");
+ });
+
+ it("when theirs cannot be checked (no network, an old gh's text, an answer it cannot read), Start is refused", async () => {
+ const offline = setup();
+ offline.set.personal = "/usr/local/bin/gh";
+ offline.set.personalStatus = ok(fixture("2.103.3/status-json-offline.stdout.txt"));
+ expect(await offline.signIn.status("owner")).toMatchObject({ state: "signed-in", login: "octo-fixture", source: "cli", checkedAt: null });
+ await expect(offline.signIn.start("owner")).rejects.toMatchObject({ status: 409 });
+
+ const old = setup();
+ old.set.personal = "/usr/local/bin/gh";
+ old.tools.run = async (_file, args) => (args.includes("--json") ? { code: 1, stdout: "", stderr: "unknown flag: --json" } : ok(fixture("2.40.1/status-offline.stdout.txt")));
+ await expect(old.signIn.start("owner")).rejects.toMatchObject({ status: 409 });
+
+ const garbled = setup();
+ garbled.set.personal = "/usr/local/bin/gh";
+ garbled.tools.run = async () => ({ code: 1, stdout: "", stderr: "segmentation fault" });
+ await expect(garbled.signIn.start("owner")).rejects.toMatchObject({ status: 409 });
+ for (const fake of [offline, old, garbled]) expect(fake.children).toHaveLength(0);
+ });
+
+ it("its own sign-in stays signed in, unchecked, when GitHub cannot be reached", async () => {
+ const fake = setup();
+ const child = await showCode(fake);
+ child.approve();
+ await settle();
+ fake.set.ownStatus = ok(fixture("2.103.3/status-json-offline.stdout.txt"));
+ expect(await fake.signIn.status("owner")).toMatchObject({ state: "signed-in", login: "octo-fixture", source: "mausbot", checkedAt: null });
+ fake.set.ownStatus = { code: 1, stdout: "", stderr: "" };
+ expect(await fake.signIn.status("owner", { check: true })).toMatchObject({ state: "signed-in", login: "octo-fixture", checkedAt: null });
+ });
+
+ it("is never looked at on a Team Cloud", async () => {
+ const fake = setup({ team: true });
+ fake.set.personal = "/usr/local/bin/gh";
+ fake.set.personalStatus = ok(fixture("constructed/status-json-success.stdout.txt"));
+ fake.set.personalToken = ok(`${TOKEN}\n`);
+ expect(await fake.signIn.status(MEMBER)).toMatchObject({ state: "signed-out" });
+ expect(await fake.signIn.token(MEMBER)).toBeNull();
+ expect(fake.calls.filter((call) => call.env.GH_CONFIG_DIR === undefined)).toEqual([]);
+ });
+});
+
+describe("a pasted token, sign out, and whose sign-in is whose", () => {
+ const github = (login: string | null) => vi.fn(async (_url: string | URL, init?: RequestInit) => {
+ const auth = new Headers(init?.headers).get("authorization");
+ if (!login || auth !== `Bearer ${PASTED}`) return new Response("{}", { status: 401 });
+ return Response.json({ login }, { headers: { "x-oauth-scopes": "" } });
+ }) as unknown as typeof fetch;
+
+ it("keeps a pasted token in the Vault, never in an answer, and replaces OpenMausBot's own gh sign-in", async () => {
+ const fake = setup({ fetchImpl: github("octo-fixture") });
+ const child = await showCode(fake);
+ child.approve();
+ await settle();
+ const logs = [vi.spyOn(console, "log"), vi.spyOn(console, "warn"), vi.spyOn(console, "error"), vi.spyOn(console, "info")];
+ const saved = await fake.signIn.saveToken("owner", ` ${PASTED}\n`);
+ expect(saved).toMatchObject({ state: "signed-in", login: "octo-fixture", source: "token", scopes: [] });
+ expect(JSON.stringify(saved)).not.toContain(PASTED);
+ expect(existsSync(githubFolders(dataDir, "owner").root)).toBe(false);
+ expect(fake.vault.saved.get("owner")).toEqual({ token: PASTED, login: "octo-fixture" });
+ expect(await fake.signIn.token()).toBe(PASTED);
+ expect(JSON.stringify(await fake.signIn.status("owner", { check: true }))).not.toContain(PASTED);
+ for (const log of logs) for (const call of log.mock.calls) expect(JSON.stringify(call)).not.toContain(PASTED);
+
+ await expect(fake.signIn.saveToken("owner", "not a token")).rejects.toMatchObject({ status: 400 });
+ // A rate-limited 403 is not a refusal: the saved token stays, shown unchecked.
+ const limited = vi.fn(async () => new Response("{}", { status: 403, headers: { "x-ratelimit-remaining": "0" } })) as unknown as typeof fetch;
+ const later = createGithubSignIn({ dataDir, team: false, tools: fake.tools, vault: fake.vault, now: () => clock, fetchImpl: limited });
+ expect(await later.status("owner")).toMatchObject({ state: "signed-in", source: "token", checkedAt: null });
+ await expect(later.saveToken("owner", PASTED)).rejects.toMatchObject({ status: 502 });
+ const refused = setup({ fetchImpl: github(null) });
+ await expect(refused.signIn.saveToken("owner", PASTED)).rejects.toMatchObject({ status: 400 });
+ expect(refused.vault.saved.size).toBe(0);
+ });
+
+ it("sign out forgets the folder and the token without running gh auth logout", async () => {
+ const fake = setup();
+ const child = await showCode(fake);
+ child.approve();
+ await settle();
+ expect(await fake.signIn.signOut("owner")).toEqual({ state: "signed-out", download: false });
+ expect(existsSync(githubFolders(dataDir, "owner").root)).toBe(false);
+ expect(fake.calls.some((call) => call.args.includes("logout"))).toBe(false);
+ expect(await fake.signIn.token()).toBeNull();
+ });
+
+ it("on a Team Cloud each member has their own, and no one falls back to another's or the team's", async () => {
+ const fake = setup({ team: true });
+ const child = await showCode(fake, MEMBER);
+ expect(child.env.GH_CONFIG_DIR).toBe(githubFolders(dataDir, MEMBER).config);
+ child.approve("member-login");
+ await settle();
+ expect(await fake.signIn.token(MEMBER)).toBe(TOKEN);
+ expect(await fake.signIn.token(OTHER)).toBeNull();
+ expect(await fake.signIn.token()).toBeNull();
+ expect(await fake.signIn.token("owner")).toBeNull();
+ expect((await fake.signIn.status(OTHER)).state).toBe("signed-out");
+ await expect(fake.signIn.status("owner")).rejects.toMatchObject({ status: 403 });
+ await expect(fake.signIn.start("../owner")).rejects.toMatchObject({ status: 403 });
+ fake.signIn.forgetPerson(MEMBER);
+ expect(existsSync(githubFolders(dataDir, MEMBER).root)).toBe(false);
+ expect(await fake.signIn.token(MEMBER)).toBeNull();
+ });
+
+ it("off a Team Cloud only the server's own sign-in exists", async () => {
+ const fake = setup();
+ await expect(fake.signIn.status(MEMBER)).rejects.toMatchObject({ status: 403 });
+ expect(await fake.signIn.token(MEMBER)).toBeNull();
+ });
+
+ it("runs nothing until asked: creating it starts no gh, no download and no request", () => {
+ const fake = setup({ fetchImpl: vi.fn() as unknown as typeof fetch });
+ const install = vi.spyOn(fake.tools, "install");
+ expect(fake.children).toHaveLength(0);
+ expect(fake.calls).toHaveLength(0);
+ expect(install).not.toHaveBeenCalled();
+ expect(existsSync(join(dataDir, "github"))).toBe(false);
+ });
+});
+
+describe("the accessor for server-side callers", () => {
+ it("answers null until a sign-in is provided, then that sign-in's token, never another person's", async () => {
+ const { githubToken, provideGithubSignIn, reportGithubAuthFailure } = await import("./token.ts");
+ expect(await githubToken()).toBeNull();
+ const fake = setup({ team: true });
+ const child = await showCode(fake, MEMBER);
+ child.approve();
+ await settle();
+ provideGithubSignIn(fake.signIn);
+ try {
+ expect(await githubToken(MEMBER)).toBe(TOKEN);
+ expect(await githubToken(OTHER)).toBeNull();
+ expect(await githubToken()).toBeNull();
+ reportGithubAuthFailure(MEMBER);
+ fake.set.ownStatus = ok(fixture("2.103.3/status-json-invalid.stdout.txt"));
+ expect(await fake.signIn.status(MEMBER)).toMatchObject({ state: "invalid", source: "mausbot" });
+ } finally {
+ provideGithubSignIn(null);
+ }
+ });
+});
+
+describe("only Start downloads, and overlapping asks share one answer", () => {
+ it("a signed-in folder with no pinned gh on disk (a newer pin) is shown unchecked and its token read from gh's file", async () => {
+ const fake = setup();
+ const child = await showCode(fake);
+ child.approve();
+ await settle();
+ fake.set.pinned = null;
+ fake.set.onDisk = false;
+ const fresh = createGithubSignIn({ dataDir, team: false, tools: fake.tools, vault: fakeVault(), now: () => clock });
+ expect(await fresh.status("owner", { check: true })).toMatchObject({ state: "signed-in", login: "octo-fixture", source: "mausbot", checkedAt: null });
+ expect(await fresh.token()).toBe(TOKEN);
+ expect(fake.installs()).toBe(0);
+ });
+
+ it("parallel checks start gh once", async () => {
+ const fake = setup();
+ const child = await showCode(fake);
+ child.approve();
+ await settle();
+ await fake.signIn.status("owner");
+ const before = fake.calls.filter((call) => call.args[1] === "status").length;
+ const answers = await Promise.all([1, 2, 3].map(() => fake.signIn.status("owner", { check: true })));
+ expect(new Set(answers.map((answer) => JSON.stringify(answer))).size).toBe(1);
+ expect(fake.calls.filter((call) => call.args[1] === "status").length).toBe(before + 1);
+ });
+});
+
+describe("Windows: Credential Manager is one store, so only a positive none lets Start go ahead", () => {
+ const entry = ["gh", "github.com", "octo-fixture"].join(":");
+ it("refuses while Credential Manager holds a gh entry, or cannot be read, and their gh is not there to say signed out", async () => {
+ for (const creds of [[entry], [`gh:_refreshable:github.com:octo-fixture`], null]) {
+ const fake = setup({ platform: "win32" });
+ fake.set.winCreds = creds;
+ await expect(fake.signIn.start("owner")).rejects.toMatchObject({ status: 409 });
+ expect(fake.children).toHaveLength(0);
+ }
+ const empty = setup({ platform: "win32" });
+ empty.set.winCreds = [];
+ expect((await empty.signIn.start("owner")).state).toBe("installing");
+ });
+
+ it("goes ahead when their own gh says signed out, and refuses on their refused (401) sign-in too", async () => {
+ const out = setup({ platform: "win32" });
+ out.set.personal = "C:\\Program Files\\GitHub CLI\\gh.exe";
+ out.set.winCreds = [entry];
+ expect((await out.signIn.start("owner")).state).toBe("installing");
+
+ const refused = setup({ platform: "win32" });
+ refused.set.personal = "C:\\Program Files\\GitHub CLI\\gh.exe";
+ refused.set.personalStatus = ok(fixture("2.103.3/status-json-invalid.stdout.txt"));
+ await expect(refused.signIn.start("owner")).rejects.toMatchObject({ status: 409 });
+ // Elsewhere a refused sign-in of theirs lets OpenMausBot's own start.
+ const linux = setup({ platform: "linux" });
+ linux.set.personal = "/usr/bin/gh";
+ linux.set.personalStatus = ok(fixture("2.103.3/status-json-invalid.stdout.txt"));
+ expect((await linux.signIn.start("owner")).state).toBe("installing");
+ });
+});
diff --git a/server/github/sign-in.ts b/server/github/sign-in.ts
new file mode 100644
index 0000000000..a7117441e9
--- /dev/null
+++ b/server/github/sign-in.ts
@@ -0,0 +1,489 @@
+// GitHub sign-in for the server's own git and GitHub actions: GitHub CLI's device-code login (the person types a code on
+// github.com; nothing is registered by the person or by OpenMausBot), or a pasted fine-grained token, or on This computer
+// the person's own GitHub CLI sign-in, which is only ever read.
+//
+// One sign-in per audience: `owner` off a Team Cloud (the server's one), a member's person key on one, each in its own
+// folder <data>/github/<audience>/ (config/: gh's config with the token, home/: gh's HOME). The data folder is never in a
+// bot's box, and this folder is kept out of backups (workspace-backup-policy.ts). A token is never logged, never in a
+// route's answer and never in a bot's environment: server code asks githubToken() for it.
+//
+// Nothing here runs at start-up and nothing runs on a timer. A login lives in memory only: after a restart it is gone
+// (a gh that outlived the old server can still finish it, and then the folder simply shows signed in). Whether a saved
+// sign-in still works is asked of GitHub when someone asks (status with check, or its first status in this run) or after
+// a git action reported it refused (reportGithubAuthFailure), never otherwise.
+import { existsSync, mkdirSync, readFileSync, rmSync } from "node:fs";
+import { join } from "node:path";
+
+import type { GithubSignInLast, GithubSignInSource, GithubSignInStatus } from "../../shared/github-sign-in.ts";
+import type { VaultStore } from "../vault-store.ts";
+import { GH_SIGN_IN_FLOOR, loginArgs, ownGhEnv, personalGhEnv, type GhChild, type GhTools } from "./gh-cli.ts";
+import { hostsFileLogin, hostsFileToken, loginFailure, parseDeviceCode, parseScopes, parseStatusJson, parseStatusText, plain, tokenFrom, versionAtLeast, type GhAccount } from "./gh-output.ts";
+
+/** GitHub's device codes last 15 minutes (its `expires_in`, 900 s); gh does not print it. */
+export const DEVICE_CODE_TTL_MS = 15 * 60_000;
+/** A gh that has printed no code this long after it started is not going to. */
+const NO_CODE_MS = 2 * 60_000;
+const OUTPUT_MAX = 64 * 1024;
+const AUDIENCE = /^(?:owner|p_[\w-]{22})$/u;
+const OWNER = "owner";
+
+export class GithubSignInError extends Error {
+ readonly status: 400 | 403 | 409 | 502;
+ constructor(status: 400 | 403 | 409 | 502, message: string) {
+ super(message);
+ this.status = status;
+ this.name = "GithubSignInError";
+ }
+}
+
+interface Attempt {
+ child: GhChild | null;
+ phase: "installing" | "signing-in";
+ startedAt: number;
+ code?: string;
+ verificationUrl?: string;
+ expiresAt?: number;
+ output: string;
+ cancelled: boolean;
+ /** Which gh ran it, so its later status and token calls use the same one. */
+ gh?: string;
+}
+
+type Known = Extract<GithubSignInStatus, { state: "signed-in" | "invalid" }>;
+
+interface Audience {
+ attempt: Attempt | null;
+ last?: GithubSignInLast;
+ /** The last answer GitHub gave about the saved sign-in, until it changes or someone asks again. */
+ known?: Known;
+ /** The person's own GitHub CLI was read in this run and had no sign-in: not read again until asked to check. */
+ personalNone?: boolean;
+ stale: boolean;
+}
+
+export interface GithubSignInDeps {
+ dataDir: string;
+ /** A Team Cloud: every audience is a member's person key, and none is the server's. */
+ team: boolean;
+ tools: GhTools;
+ vault: Pick<VaultStore, "githubToken" | "setGithubToken">;
+ fetchImpl?: typeof fetch;
+ now?: () => number;
+ /** Tests only: the platform whose credential-store rules apply. */
+ platform?: NodeJS.Platform;
+ /** A token just read, so held-secret redaction masks it wherever text reaches a bot or a transcript. */
+ remember?(token: string): void;
+}
+
+export interface GithubSignIn {
+ status(audience: string, options?: { check?: boolean }): Promise<GithubSignInStatus>;
+ start(audience: string): Promise<GithubSignInStatus>;
+ cancel(audience: string): Promise<GithubSignInStatus>;
+ saveToken(audience: string, token: string): Promise<GithubSignInStatus>;
+ signOut(audience: string): Promise<GithubSignInStatus>;
+ /** The token for server-side git and GitHub calls, or null. Never logged, never a route's answer, never a bot's env. */
+ token(audience?: string | null): Promise<string | null>;
+ /** A git or GitHub call with this audience's token was refused: the next status asks GitHub again. */
+ reportAuthFailure(audience?: string | null): void;
+ /** A member who left a Team Cloud: their sign-in folder and pasted token go. */
+ forgetPerson(person: string): void;
+}
+
+export function githubFolders(dataDir: string, audience: string): { root: string; config: string; home: string } {
+ if (!AUDIENCE.test(audience)) throw new GithubSignInError(403, "Sign in to this server to connect GitHub.");
+ const root = join(dataDir, "github", audience);
+ return { root, config: join(root, "config"), home: join(root, "home") };
+}
+
+export function createGithubSignIn(deps: GithubSignInDeps): GithubSignIn {
+ const now = deps.now ?? Date.now;
+ const fetchImpl = deps.fetchImpl ?? fetch;
+ const audiences = new Map<string, Audience>();
+ const of = (audience: string): Audience => {
+ let found = audiences.get(audience);
+ if (!found) {
+ found = { attempt: null, stale: false };
+ audiences.set(audience, found);
+ }
+ return found;
+ };
+ /** Off a Team Cloud the one audience is the server's; on one, only a member's own key, and never a fallback. */
+ const resolve = (audience: string | null | undefined): string | null => {
+ if (deps.team) return audience && audience !== OWNER && AUDIENCE.test(audience) ? audience : null;
+ return audience === undefined || audience === null || audience === OWNER ? OWNER : null;
+ };
+ const must = (audience: string): string => {
+ const key = resolve(audience);
+ if (!key) throw new GithubSignInError(403, "Sign in to this server to connect GitHub.");
+ return key;
+ };
+ const hostsFile = (audience: string) => join(githubFolders(deps.dataDir, audience).config, "hosts.yml");
+ const ownLogin = (audience: string): string | null | undefined => {
+ try {
+ return hostsFileLogin(readFileSync(hostsFile(audience), "utf8"));
+ } catch {
+ return undefined;
+ }
+ };
+ const ownSignedIn = (audience: string) => ownLogin(audience) !== undefined;
+ /** The person's own gh may run OpenMausBot's sign-in only off a Team Cloud and when it takes every flag. */
+ const personalForLogin = async (): Promise<string | null> => {
+ const own = deps.team ? null : deps.tools.personal();
+ return own && versionAtLeast(await deps.tools.version(own), GH_SIGN_IN_FLOOR) ? own : null;
+ };
+ /** A gh for OpenMausBot's own sign-in folder: the one that signed it in this run, the person's own, or the pinned copy. */
+ /** A gh for OpenMausBot's own sign-in folder, never a download: only Start installs. The pinned copy is checked again
+ * (installStandaloneEngine's reuse path) only when its folder names the pinned version, so a newer pin waits for Start. */
+ const ownGh = async (audience: string): Promise<string | null> => of(audience).attempt?.gh ?? (await personalForLogin()) ?? deps.tools.pinnedReady()
+ ?? (deps.tools.pinnedOnDisk() ? await deps.tools.install().catch(() => null) : null);
+ const ownEnv = (audience: string) => {
+ const folders = githubFolders(deps.dataDir, audience);
+ for (const folder of [folders.config, folders.home, join(folders.home, ".run")]) mkdirSync(folder, { recursive: true, mode: 0o700 });
+ return ownGhEnv(folders);
+ };
+
+ async function ghAccount(file: string, env: Record<string, string>): Promise<GhAccount | "signed-out" | null> {
+ const json = await deps.tools.run(file, ["auth", "status", "--hostname", "github.com", "--json", "hosts"], env);
+ const fromJson = json.code === 0 ? parseStatusJson(json.stdout) : null;
+ if (fromJson) return fromJson;
+ const text = await deps.tools.run(file, ["auth", "status", "--hostname", "github.com"], env);
+ return parseStatusText(`${text.stdout}\n${text.stderr}`);
+ }
+
+ async function orgsOf(file: string, env: Record<string, string>): Promise<string[] | undefined> {
+ const result = await deps.tools.run(file, ["api", "user/orgs", "--paginate", "--jq", ".[].login"], env);
+ if (result.code !== 0) return undefined;
+ return plain(result.stdout).split("\n").map((line) => line.trim()).filter((line) => /^[A-Za-z0-9][A-Za-z0-9-]{0,38}$/u.test(line)).slice(0, 200);
+ }
+
+ function known(source: GithubSignInSource, account: GhAccount, fallbackLogin: string | null, orgs?: string[]): Known {
+ const login = account.login ?? fallbackLogin;
+ if (account.state === "invalid" || (!login && account.state === "success")) {
+ return { state: "invalid", login, source, reason: source === "cli" ? "GitHub no longer accepts your GitHub CLI's sign-in. Sign in again there with `gh auth login`." : "GitHub no longer accepts this sign-in. Sign in again." };
+ }
+ // Unknown (no network, a timeout, an answer gh could not give): the sign-in is there and stays, just not checked.
+ return { state: "signed-in", login: login ?? "unknown", source, scopes: account.scopes, ...(orgs ? { orgs } : {}), checkedAt: account.state === "success" ? now() : null };
+ }
+
+ /** What GitHub says of OpenMausBot's own gh sign-in. */
+ async function checkOwn(audience: string, withOrgs: boolean): Promise<Known> {
+ const login = ownLogin(audience) ?? null;
+ try {
+ const file = await ownGh(audience);
+ if (!file) return { state: "signed-in", login: login ?? "unknown", source: "mausbot", scopes: [], checkedAt: null };
+ const env = ownEnv(audience);
+ const account = await ghAccount(file, env);
+ // The config file is there, so an answer gh could not give is not a refusal: shown as signed in, unchecked.
+ if (account === "signed-out" || account === null) return { state: "signed-in", login: login ?? "unknown", source: "mausbot", scopes: [], checkedAt: null };
+ const orgs = withOrgs && account.state === "success" ? await orgsOf(file, env) : of(audience).known?.state === "signed-in" ? (of(audience).known as { orgs?: string[] }).orgs : undefined;
+ return known("mausbot", account, login, orgs);
+ } catch {
+ // gh could not be put in place or run: the sign-in is there, its check is not.
+ return { state: "signed-in", login: login ?? "unknown", source: "mausbot", scopes: [], checkedAt: null };
+ }
+ }
+
+ async function checkToken(token: string, savedLogin: string | null): Promise<Known | "unreachable"> {
+ let response: Response;
+ try {
+ response = await fetchImpl("https://api.github.com/user", {
+ headers: { authorization: `Bearer ${token}`, accept: "application/vnd.github+json", "user-agent": "OpenMausBot", "x-github-api-version": "2022-11-28" },
+ signal: AbortSignal.timeout(20_000),
+ });
+ } catch {
+ return "unreachable";
+ }
+ // Only 401 is GitHub refusing the token; a 403 is also how it answers a rate limit, so it proves nothing.
+ if (response.status === 401) return { state: "invalid", login: savedLogin, source: "token", reason: "GitHub no longer accepts this token. Paste a new one." };
+ if (!response.ok) return "unreachable";
+ const body = await response.json().catch(() => null) as { login?: unknown } | null;
+ const login = typeof body?.login === "string" && /^[A-Za-z0-9][A-Za-z0-9-]{0,38}$/u.test(body.login) ? body.login : savedLogin;
+ if (!login) return "unreachable";
+ return { state: "signed-in", login, source: "token", scopes: parseScopes(response.headers.get("x-oauth-scopes")), checkedAt: now() };
+ }
+
+ /** The person's own GitHub CLI sign-in on This computer, read and never changed: null when they have no gh (or may not
+ * use it here), "signed-out" when it says so, "unreadable" when its answer could not be read. */
+ async function personalAccount(): Promise<Known | "signed-out" | "unreadable" | null> {
+ const own = deps.team ? null : deps.tools.personal();
+ if (!own) return null;
+ const account = await ghAccount(own, personalGhEnv()).catch(() => null);
+ if (account === "signed-out") return "signed-out";
+ if (account === null) return "unreadable";
+ return known("cli", account, null);
+ }
+
+ /** Ends an attempt whose time is up: a code past its expiry, or a gh that never printed one. No timer: asked on read. */
+ function settleLate(audience: string): void {
+ const state = of(audience), attempt = state.attempt;
+ if (!attempt || !attempt.child) return;
+ const late = attempt.phase === "signing-in" ? attempt.expiresAt !== undefined && now() > attempt.expiresAt : now() - attempt.startedAt > NO_CODE_MS;
+ if (!late) return;
+ attempt.child.kill("SIGTERM");
+ state.attempt = null;
+ state.last = attempt.phase === "signing-in" ? { outcome: "expired", reason: "The code expired before it was entered on GitHub.", at: now() } : { outcome: "failed", reason: "GitHub did not send a code in time. Try again.", at: now() };
+ }
+
+ function current(audience: string): GithubSignInStatus | null {
+ settleLate(audience);
+ const state = of(audience), attempt = state.attempt;
+ if (!attempt) return null;
+ if (attempt.phase === "signing-in" && attempt.code && attempt.verificationUrl && attempt.expiresAt) {
+ return { state: "signing-in", code: attempt.code, verificationUrl: attempt.verificationUrl, expiresAt: attempt.expiresAt };
+ }
+ return { state: "installing" };
+ }
+
+ const withLast = (audience: string, status: GithubSignInStatus): GithubSignInStatus => {
+ const last = of(audience).last;
+ return last && status.state !== "signed-in" ? { ...status, last } : status;
+ };
+
+ /** Status calls of one audience that overlap share one answer, so parallel asks never each start gh. */
+ const asking = new Map<string, Promise<GithubSignInStatus>>();
+ function status(audienceIn: string, options: { check?: boolean } = {}): Promise<GithubSignInStatus> {
+ let audience: string;
+ try {
+ audience = must(audienceIn);
+ } catch (error) {
+ return Promise.reject(error);
+ }
+ const running = asking.get(audience);
+ if (running) return running;
+ const answer = readStatus(audience, options).finally(() => asking.delete(audience));
+ asking.set(audience, answer);
+ return answer;
+ }
+
+ async function readStatus(audience: string, options: { check?: boolean }): Promise<GithubSignInStatus> {
+ const live = current(audience);
+ if (live) return withLast(audience, live);
+ const state = of(audience);
+ const ask = options.check === true || state.stale || !state.known;
+ if (ownSignedIn(audience)) {
+ if (ask || state.known?.source !== "mausbot") {
+ state.known = await checkOwn(audience, state.known?.source !== "mausbot" || options.check === true);
+ state.stale = false;
+ }
+ return state.known;
+ }
+ const saved = deps.vault.githubToken(audience);
+ if (saved) {
+ if (ask || state.known?.source !== "token") {
+ const checked = await checkToken(saved.token, saved.login);
+ state.known = checked === "unreachable" ? { state: "signed-in", login: saved.login, source: "token", scopes: [], checkedAt: null } : checked;
+ state.stale = false;
+ }
+ return state.known;
+ }
+ if (!deps.team && deps.tools.personal()) {
+ if (options.check === true || state.stale || (state.known?.source !== "cli" && !state.personalNone)) {
+ const account = await personalAccount();
+ state.known = typeof account === "object" && account !== null ? account : undefined;
+ state.personalNone = state.known === undefined;
+ state.stale = false;
+ }
+ if (state.known?.source === "cli") return state.known;
+ }
+ state.known = undefined;
+ const download = !(await personalForLogin()) && !deps.tools.pinnedReady() && !deps.tools.pinnedOnDisk();
+ return withLast(audience, { state: "signed-out", download });
+ }
+
+ function finish(audience: string, attempt: Attempt, code: number | null): void {
+ const state = of(audience);
+ if (state.attempt !== attempt) return;
+ state.attempt = null;
+ if (attempt.cancelled) {
+ state.last = { outcome: "cancelled", at: now() };
+ return;
+ }
+ if (code === 0 && ownSignedIn(audience)) {
+ state.last = undefined;
+ state.stale = true;
+ // One source at a time: a pasted token steps aside for the sign-in just made.
+ if (deps.vault.githubToken(audience)) deps.vault.setGithubToken(audience, null);
+ return;
+ }
+ const failure = loginFailure(attempt.output);
+ state.last = { outcome: failure.outcome, reason: failure.reason, at: now() };
+ }
+
+ function launch(audience: string, attempt: Attempt, file: string, version: [number, number, number] | null): void {
+ attempt.gh = file;
+ attempt.phase = "installing";
+ let child: GhChild;
+ try {
+ child = deps.tools.spawn(file, loginArgs(version), ownEnv(audience));
+ } catch {
+ finish(audience, attempt, 1);
+ return;
+ }
+ attempt.child = child;
+ const receive = (chunk: Buffer | string) => {
+ if (attempt.output.length < OUTPUT_MAX) attempt.output += String(chunk).slice(0, OUTPUT_MAX - attempt.output.length);
+ if (attempt.code) return;
+ const shown = parseDeviceCode(attempt.output);
+ if (!shown) return;
+ Object.assign(attempt, { phase: "signing-in", code: shown.code, verificationUrl: shown.verificationUrl, expiresAt: now() + DEVICE_CODE_TTL_MS });
+ };
+ child.stdout.on("data", receive);
+ child.stderr.on("data", receive);
+ child.once("error", (error) => {
+ attempt.output += `\n${error.message}`;
+ finish(audience, attempt, 1);
+ });
+ child.once("close", (code) => finish(audience, attempt, code));
+ }
+
+ async function start(audienceIn: string): Promise<GithubSignInStatus> {
+ const audience = must(audienceIn);
+ const live = current(audience);
+ if (live) return live;
+ if (ownSignedIn(audience)) throw new GithubSignInError(409, "GitHub is already signed in here. Sign out first to use another account.");
+ // Held from here, so a second Start while this one looks around joins it rather than starting another gh.
+ const state = of(audience);
+ const attempt: Attempt = { child: null, phase: "installing", startedAt: now(), output: "", cancelled: false };
+ state.attempt = attempt;
+ state.last = undefined;
+ const stillOurs = () => state.attempt === attempt && !attempt.cancelled;
+ try {
+ // Security: the person's own gh keeps its sign-in in the OS credential store, which a gh login touches whatever its
+ // folder (gh-cli.ts). While their own sign-in works, OpenMausBot never starts one of its own.
+ // Only a positive answer lets it go ahead: no gh of theirs, theirs signed out, or GitHub refusing theirs (401).
+ const theirs = deps.team ? null : await personalAccount();
+ if (theirs === "unreadable") throw new GithubSignInError(409, "Your own GitHub CLI's sign-in could not be checked, so nothing was changed. Try again.");
+ if (theirs !== null && theirs !== "signed-out" && theirs.state === "signed-in") {
+ state.known = theirs;
+ throw new GithubSignInError(409, `GitHub is already signed in on this computer as ${theirs.login}, with your own GitHub CLI.`);
+ }
+ // Windows' Credential Manager is one store whatever gh's folder (gh-cli.ts), so there only a positive "none" will do:
+ // their gh saying signed out, or no gh entry there at all. A refused sign-in of theirs (401) is not enough either:
+ // its entry, under the same login, would be what our new sign-in resolves to.
+ if ((deps.platform ?? process.platform) === "win32" && !deps.team && theirs !== "signed-out") {
+ const entries = theirs === null ? await deps.tools.windowsGhCredentials() : null;
+ if (theirs !== null || entries === null || entries.length > 0) {
+ throw new GithubSignInError(409, "This computer's Windows Credential Manager already holds a GitHub CLI sign-in, which signing in here could change. Paste a GitHub token instead, or sign in again with your own GitHub CLI.");
+ }
+ }
+ const file = (await personalForLogin()) ?? deps.tools.pinnedReady();
+ if (file) {
+ const version = await deps.tools.version(file);
+ if (stillOurs()) launch(audience, attempt, file, version);
+ } else {
+ // The first sign-in here fetches the pinned GitHub CLI; the card shows "installing" and asks again.
+ void deps.tools.install().then(async (installed) => {
+ const version = await deps.tools.version(installed);
+ if (!stillOurs()) return;
+ // The clock for a code starts when gh does.
+ attempt.startedAt = now();
+ launch(audience, attempt, installed, version);
+ }, (error: unknown) => {
+ if (state.attempt !== attempt) return;
+ state.attempt = null;
+ state.last = { outcome: "failed", reason: error instanceof Error ? error.message.slice(0, 300) : "GitHub CLI could not be installed.", at: now() };
+ });
+ }
+ } catch (error) {
+ if (state.attempt === attempt) state.attempt = null;
+ throw error;
+ }
+ return withLast(audience, current(audience) ?? (await readStatus(audience, {})));
+ }
+
+ function stopAttempt(audience: string): void {
+ const state = of(audience), attempt = state.attempt;
+ if (!attempt) return;
+ attempt.cancelled = true;
+ state.attempt = null;
+ state.last = { outcome: "cancelled", at: now() };
+ attempt.child?.kill("SIGTERM");
+ }
+
+ async function cancel(audienceIn: string): Promise<GithubSignInStatus> {
+ const audience = must(audienceIn);
+ stopAttempt(audience);
+ return readStatus(audience, {});
+ }
+
+ async function saveToken(audienceIn: string, raw: string): Promise<GithubSignInStatus> {
+ const audience = must(audienceIn);
+ const token = typeof raw === "string" ? raw.trim() : "";
+ if (!/^[A-Za-z0-9_]{20,255}$/u.test(token)) throw new GithubSignInError(400, "Paste a GitHub token: it starts with github_pat_ (fine-grained) or ghp_.");
+ const checked = await checkToken(token, null);
+ if (checked === "unreachable") throw new GithubSignInError(502, "GitHub could not check the token just now. Try again in a minute.");
+ if (checked.state !== "signed-in") throw new GithubSignInError(400, "GitHub did not accept this token. Check it and paste it again.");
+ stopAttempt(audience);
+ // One source at a time: the pasted token replaces OpenMausBot's own gh sign-in.
+ rmSync(githubFolders(deps.dataDir, audience).root, { recursive: true, force: true });
+ deps.vault.setGithubToken(audience, { token, login: checked.login });
+ const state = of(audience);
+ Object.assign(state, { known: checked, stale: false, last: undefined });
+ return checked;
+ }
+
+ async function signOut(audienceIn: string): Promise<GithubSignInStatus> {
+ const audience = must(audienceIn);
+ stopAttempt(audience);
+ const ours = ownSignedIn(audience) || existsSync(githubFolders(deps.dataDir, audience).root) || deps.vault.githubToken(audience) !== null;
+ if (!ours) {
+ const shown = await readStatus(audience, {});
+ if (shown.state !== "signed-out" && "source" in shown && shown.source === "cli") {
+ throw new GithubSignInError(409, "This sign-in is your own GitHub CLI's. Sign out there with `gh auth logout`.");
+ }
+ return shown;
+ }
+ // Never `gh auth logout`: it also deletes the OS credential store's entries for github.com, which on This computer are
+ // the person's own (gh-cli.ts). The token was only ever in this folder, so removing the folder forgets it; neither
+ // revokes it on GitHub (docs: GitHub sign-in).
+ rmSync(githubFolders(deps.dataDir, audience).root, { recursive: true, force: true });
+ if (deps.vault.githubToken(audience)) deps.vault.setGithubToken(audience, null);
+ Object.assign(of(audience), { known: undefined, stale: false, last: undefined });
+ return readStatus(audience, {});
+ }
+
+ async function token(audienceIn?: string | null): Promise<string | null> {
+ const audience = resolve(audienceIn);
+ if (!audience) return null;
+ const remember = (value: string | null) => {
+ if (value) deps.remember?.(value);
+ return value;
+ };
+ try {
+ if (ownSignedIn(audience)) {
+ // gh renews an expiring sign-in itself when asked for its token.
+ const file = await ownGh(audience);
+ // No gh to ask (a newer pin not yet installed): the token gh saved in its own file, as gh itself would read it.
+ if (!file) return remember(hostsFileToken(readFileSync(hostsFile(audience), "utf8")));
+ const result = await deps.tools.run(file, ["auth", "token", "--hostname", "github.com"], ownEnv(audience));
+ return remember(result.code === 0 ? tokenFrom(result.stdout) : null);
+ }
+ const saved = deps.vault.githubToken(audience);
+ if (saved) return remember(saved.token);
+ const own = deps.team ? null : deps.tools.personal();
+ if (!own) return null;
+ const result = await deps.tools.run(own, ["auth", "token", "--hostname", "github.com"], personalGhEnv());
+ return remember(result.code === 0 ? tokenFrom(result.stdout) : null);
+ } catch {
+ return null;
+ }
+ }
+
+ return {
+ status, start, cancel, saveToken, signOut, token,
+ reportAuthFailure(audienceIn) {
+ const audience = resolve(audienceIn);
+ if (audience) of(audience).stale = true;
+ },
+ forgetPerson(person) {
+ if (!AUDIENCE.test(person) || person === OWNER) return;
+ const state = audiences.get(person);
+ if (state?.attempt) {
+ state.attempt.cancelled = true;
+ state.attempt.child?.kill("SIGTERM");
+ }
+ audiences.delete(person);
+ rmSync(githubFolders(deps.dataDir, person).root, { recursive: true, force: true });
+ },
+ };
+}
diff --git a/server/github/token.ts b/server/github/token.ts
new file mode 100644
index 0000000000..a3b2908c9e
--- /dev/null
+++ b/server/github/token.ts
@@ -0,0 +1,22 @@
+// The GitHub sign-in for server-side callers (a git credential grant, opening a pull request), without reaching into
+// index.ts. index.ts provides the one sign-in at start-up; until then, and where there is none, every answer is null.
+// Security: the token is for the server's own calls only. Never log it, put it in a route's answer, or put it in a bot's
+// environment or arguments.
+import type { GithubSignIn } from "./sign-in.ts";
+
+let current: Pick<GithubSignIn, "token" | "reportAuthFailure"> | null = null;
+
+export function provideGithubSignIn(signIn: Pick<GithubSignIn, "token" | "reportAuthFailure"> | null): void {
+ current = signIn;
+}
+
+/** The token for `audience`: off a Team Cloud the server's one (null, undefined or "owner"); on a Team Cloud a member's
+ * person key (person-key.ts personKey of their address), and null for anything else: never another person's. */
+export function githubToken(audience?: string | null): Promise<string | null> {
+ return current ? current.token(audience) : Promise.resolve(null);
+}
+
+/** A git or GitHub call made with that token was refused (401): the next status asks GitHub again. */
+export function reportGithubAuthFailure(audience?: string | null): void {
+ current?.reportAuthFailure(audience);
+}
diff --git a/server/index.ts b/server/index.ts
index 4df76a9b1e..6f3baecd21 100644
--- a/server/index.ts
+++ b/server/index.ts
@@ -114,7 +114,7 @@ import { boatCreateRecoverySnapshot } from "./boat-create-idempotency.ts";
import { boatDeletionSnapshot } from "./boat-delete-journal.ts";
import { liveDecisionRefusal } from "../shared/live-approval.ts"; import type { PersonWaitKind } from "../shared/person-wait.ts";
import { vpsLeftBehindNotice, vpsNotChosenReason } from "./cloud-backend.ts";
-import * as composio from "./composio.ts"; import { createConnectorListingRoutes } from "./routes/connectors-listing.ts";
+import * as composio from "./composio.ts"; import { createConnectorListingRoutes } from "./routes/connectors-listing.ts"; import { createGhTools } from "./github/gh-cli.ts"; import { createGithubSignIn } from "./github/sign-in.ts"; import { provideGithubSignIn } from "./github/token.ts"; import { createGithubSignInRoutes } from "./routes/github-sign-in.ts";
import { appSandboxRule, connectorCallFromFrame, connectorRefusalText, connectorScopeRefusalText, connectorUnrecognizedText, evaluateConnectorTools } from "./connector-verdict.ts";
import { signInCardText } from "./connector-card-text.ts";
import { BOT_HELD_CODE, BOT_PAUSED_CODE } from "../shared/bot-limit.ts"; import { createBotHolds } from "./host/bot-holds.ts"; import { createBotHoldRoutes } from "./routes/bot-holds.ts"; import { createCliLogin } from "./routes/cli-login.ts"; import { createStarterAwake } from "./host/starter-awake.ts"; import { createStarterCaps } from "./host/starter-caps.ts"; import { createStarterRoutineWake, workInFlight, type StarterRoutineWake } from "./host/starter-routine-wake.ts"; import { createStarterAwakeRoutes } from "./routes/starter-awake.ts"; import { chiefOfStaffPrompt, chiefOfStaffSystemPrompt } from "./chief-of-staff.ts"; import { coordinateMessageMax, coordinateTooLong, reportBackTooLong } from "./too-long.ts"; import { chiefAbsentFrom, createChiefRooms } from "./host/chief-rooms.ts"; import { chiefLevel, readTeamRolesWith } from "./chief-level.ts"; import { defaultBotRefusal, ensureDefaultBot } from "./default-bot.ts";
@@ -12059,7 +12059,7 @@ const teamMoveIn = CLOUD_TEAM ? createTeamMoveIn({ team: CLOUD_TEAM, dataDir: DA
if (CLOUD_TEAM) teamHost.adoptServerProfile(sessions.list().flatMap((session) => session.email ? [session.email] : []));
const sidebarRoutes = createSidebarSectionRoutes({ store, teamComputers, maxBots: MAX_WORKSPACE_BOTS, assertTeamComputerChangeIdle, wireBot, renamed: (from, to) => (to ? botHolds.rename(from, to) : botHolds.forget("department", from)) }); ROUTES.push(teamPresence.routes, sidebarRoutes, createPresenceRoutes({ isOwner: ownerOrAdmin, heard: (auth, language) => personLanguages.heard(auth.kind === "session" ? actorKey(auth) : THIS_COMPUTER, language), sawChat: (_auth, threadId) => { if (store.botByThread(threadId)) sawThread(threadId); }, active: async (source, zone, language) => { const answer = await proactive.brief.active(source, zone, language); firstHourHooks.arrived(); return answer; }, ...(CLOUD_TEAM ? { member: (auth) => { noAiNotice.flush(); return teamMessages.arrived(auth); } } : {}) }), createMeRoutes({ team: CLOUD_TEAM, session: (auth) => (auth.kind === "session" ? auth.session : null), welcome: teamWelcome, profile: teamHost.memberProfile, save: teamHost.saveMemberProfile, seed: teamHost.seedMemberProfile, seeded: teamHost.seededFields, changed: () => broadcast({ kind: "config", ...configStatus() }), names: SELF_HOSTED ? { store: personNames, shownAs: sessionPersonName } : null }), teamAway.routes, createTeamPhoneRoutes({ team: CLOUD_TEAM, sessions, publicBase: (req, auth) => pairingLinkBase(publicUrl(), auth.kind === "session" ? requestOrigin(req) : null) }),
createTeamConnectionRoutes({ host: teamConnections, cfg: () => cfg, composio, policy: managedPolicy, publicOrigin: CLOUD_HOME?.publicOrigin ?? null, record: (auth, row) => appendAdminAction(DATA_DIR, { ...row, actor: decisionActorFor(auth) }) }), createSignInCardRoutes({ settle: signInSettle.settle, saveLogin: (botId, threadId, messageId, body, auth) => CLOUD_TEAM && !auth.scopes.includes("admin") ? Promise.resolve({ status: 403 as const, body: memberLoginRefusal(CLOUD_TEAM) }) : saveLoginFromCard(botId, threadId, messageId, body), saveTarget: signInSaveTarget, threadVisible: (auth, threadId) => visibleTo(viewerFor(auth)).thread(threadId), vault: createSignInVaultChoices({ logins, cardBots: (id) => botLogins.cardBots(id), settle: signInSettle.settle, openCard: (botId, threadId, messageId) => { const card = signInMessage(botId, threadId, messageId)?.signIn; return card && card.place === "browser" && !card.superseded && !card.answeredInChat && !card.stopped && !signInOutcome(card) ? card : null; } }) })); const appSuggestions = createAppSuggestions({ dataDir: DATA_DIR, store, configured: () => composio.configured(cfg), catalog: () => composio.listToolkits(cfg), services: async (live) => live ? composio.connectedServices(cfg) : (await composio.sharedConnectedInventory(cfg)).services, offerable: (slug) => !managedPolicy.appRefusal(slug) && !managedConnectorUnavailableReason(composio.connectionMode(cfg), slug) && !teamConnections.personApps().includes(slug), pickAvailable: () => appPickAvailable(cfg), decider }); ROUTES.push(createAppSuggestionRoutes(appSuggestions));
-ROUTES.push(createConnectorListingRoutes({ cfg: () => cfg, composio, managedHost: DESKTOP_MANAGED || CLOUD_HOME !== null })); composio.rememberCatalogIn(DATA_DIR); composio.onCatalogChange(() => broadcast({ kind: "apps-catalog" }, { adminOnly: true }));
+ROUTES.push(createConnectorListingRoutes({ cfg: () => cfg, composio, managedHost: DESKTOP_MANAGED || CLOUD_HOME !== null })); composio.rememberCatalogIn(DATA_DIR); composio.onCatalogChange(() => broadcast({ kind: "apps-catalog" }, { adminOnly: true })); const githubSignIn = createGithubSignIn({ dataDir: DATA_DIR, team: Boolean(CLOUD_TEAM), vault: logins, tools: createGhTools({ dataDir: DATA_DIR, personalAllowed: () => !CLOUD_HOME && !HOSTED_WORKSPACE && !botBox.enabled() }), remember: (token) => heldSecrets.remember(token, "password") }); provideGithubSignIn(githubSignIn); ROUTES.push(createGithubSignInRoutes({ signIn: githubSignIn, team: Boolean(CLOUD_TEAM) }));
ROUTES.push(createRoomHoldRoutes({
group: (id) => store.group(id),
groupFor: personRooms.groupForAuth,
@@ -12155,7 +12155,7 @@ const taskRoutes = createTaskRoutes({
revokeInternalCapabilitiesForThread,
stagedSkillCleanupsForThread,
rejectDeletedThreadSkillStages,
-}); ROUTES.push(taskRoutes); const leaveTeam = CLOUD_TEAM ? createTeamMemberLeft({ dataDir: DATA_DIR, store, openedBy: (person) => threadStarters.threadsOf(person, 50_000), privateTo: teamHost.privateTo, sharesLeft: conversationSharing.personLeft, revokeSessions: (email) => sessions.revokeMember(email), busy: threadBusy, stop: (botId, threadId) => interruptDirectThread(botId, threadId, "The person left the team"), deleteTasks: taskRoutes.deleteTasks, stopBot: (botId) => memberOwnBot.stopWork(botId, "The person left the team"), deleteBot: memberOwnBot.remove, threadsReferencing, deleteAttachment: (name) => deleteAttachment(join(ATTACHMENTS_DIR, name)), eraseBrowsers: eraseAudienceBrowsers, forgetConnections: (person) => { connectionHealth.forgetPerson(person); personRooms.reads?.forgetPerson(person); return teamConnections.forgetPerson(person); }, forgetSecrets: (person) => { logins.forgetPerson(person); }, ...teamRoutines.leaving, forgetOnBots: (email) => forgetMember(store, email, (bot, access) => writeAccess({ store, publicGroupState, broadcast, audienceChanged }, bot, access)).length, ownerOf: (botId) => { const bot = store.bot(botId); return bot ? botOwner(bot) : null; }, record: (row) => appendAdminAction(DATA_DIR, { ...row, actor: { kind: "session", sessionId: "", label: "MausBot Cloud" } }) }) : null; const teamSlack = createTeamSlackHost({ cloudHome: CLOUD_HOME, dataDir: DATA_DIR, ...(personalSlackMessages ? { messages: personalSlackMessages } : {}), owner: (auth) => (cloudOwnerSession(auth) ? CLOUD_OWNER_KEY : null), store, visibleFor: (auth) => visibleTo(viewerFor(auth)), sender: messageSender, trigger: usageTriggerFor, actor: runActor, audienceOf: teamHost.audienceOf, starters: threadStarters, shareFromSlack: (threadId, person) => void conversationShares.share(threadId, person, "team", Date.now(), "slack"), discard: (botId, threadId) => void taskRoutes.deleteTasks(botId, [threadId]), send: (input) => acceptDirectSend(input), busy: threadBusy, handedOn: directRootPending, request: (threadId) => directRequestOwners.get(threadId), stopRefusal: (threadId, by) => runOwners.stopRefusal(threadId, by), removeRefusal: (threadId, sender, by) => runOwners.removeRefusal(threadId, sender, by), stopThread: stopThreadForPerson, language: personLanguages.forLine }); ROUTES.push(createTeamSlackRoutes({ host: teamSlack }));
+}); ROUTES.push(taskRoutes); const leaveTeam = CLOUD_TEAM ? createTeamMemberLeft({ dataDir: DATA_DIR, store, openedBy: (person) => threadStarters.threadsOf(person, 50_000), privateTo: teamHost.privateTo, sharesLeft: conversationSharing.personLeft, revokeSessions: (email) => sessions.revokeMember(email), busy: threadBusy, stop: (botId, threadId) => interruptDirectThread(botId, threadId, "The person left the team"), deleteTasks: taskRoutes.deleteTasks, stopBot: (botId) => memberOwnBot.stopWork(botId, "The person left the team"), deleteBot: memberOwnBot.remove, threadsReferencing, deleteAttachment: (name) => deleteAttachment(join(ATTACHMENTS_DIR, name)), eraseBrowsers: eraseAudienceBrowsers, forgetConnections: (person) => { connectionHealth.forgetPerson(person); personRooms.reads?.forgetPerson(person); return teamConnections.forgetPerson(person); }, forgetSecrets: (person) => { logins.forgetPerson(person); githubSignIn.forgetPerson(person); }, ...teamRoutines.leaving, forgetOnBots: (email) => forgetMember(store, email, (bot, access) => writeAccess({ store, publicGroupState, broadcast, audienceChanged }, bot, access)).length, ownerOf: (botId) => { const bot = store.bot(botId); return bot ? botOwner(bot) : null; }, record: (row) => appendAdminAction(DATA_DIR, { ...row, actor: { kind: "session", sessionId: "", label: "MausBot Cloud" } }) }) : null; const teamSlack = createTeamSlackHost({ cloudHome: CLOUD_HOME, dataDir: DATA_DIR, ...(personalSlackMessages ? { messages: personalSlackMessages } : {}), owner: (auth) => (cloudOwnerSession(auth) ? CLOUD_OWNER_KEY : null), store, visibleFor: (auth) => visibleTo(viewerFor(auth)), sender: messageSender, trigger: usageTriggerFor, actor: runActor, audienceOf: teamHost.audienceOf, starters: threadStarters, shareFromSlack: (threadId, person) => void conversationShares.share(threadId, person, "team", Date.now(), "slack"), discard: (botId, threadId) => void taskRoutes.deleteTasks(botId, [threadId]), send: (input) => acceptDirectSend(input), busy: threadBusy, handedOn: directRootPending, request: (threadId) => directRequestOwners.get(threadId), stopRefusal: (threadId, by) => runOwners.stopRefusal(threadId, by), removeRefusal: (threadId, sender, by) => runOwners.removeRefusal(threadId, sender, by), stopThread: stopThreadForPerson, language: personLanguages.forLine }); ROUTES.push(createTeamSlackRoutes({ host: teamSlack }));
ROUTES.push(createTeamRoutes({
store,
authorName: (auth) => CLOUD_TEAM ? (auth.kind === "session" ? teamHost.memberProfile(auth.session).name || undefined : undefined) : cfg.profile?.name?.trim(),
diff --git a/server/perf/disk-categories.ts b/server/perf/disk-categories.ts
index e989d80fa2..7219f2bed9 100644
--- a/server/perf/disk-categories.ts
+++ b/server/perf/disk-categories.ts
@@ -67,12 +67,12 @@ const DATA_FOLDERS: Readonly<Record<string, StorageCategory>> = {
// (themes/store.ts), org-library (org-library.ts), share (share.ts), usage (usage-ledger.ts), decisions and
// admin-activity (decision-log.ts, admin-activity.ts: the audit log readDecisions reads), prompt-split (drivers/prompt-split.ts),
// codex-instructions (drivers/codex-instructions.ts), local-vm-stops, skill-switch, hook-tokens (drivers/claude.ts),
- // claude-user-skills (turn-settings.ts), box (bot-box/boot.ts).
+ // claude-user-skills (turn-settings.ts), box (bot-box/boot.ts), github (github/sign-in.ts).
providers: "settings", people: "settings", "people-connections": "settings", caddy: "settings", ssh: "settings",
skills: "settings", "skills-library": "settings", "imported-skills": "settings", "skill-state": "settings", "skill-switch": "settings",
themes: "settings", "org-library": "settings", share: "settings", usage: "settings", decisions: "settings", "admin-activity": "settings",
"prompt-split": "settings", "codex-instructions": "settings", "local-vm-stops": "settings", "hook-tokens": "settings",
- "claude-user-skills": "settings", box: "settings",
+ "claude-user-skills": "settings", box: "settings", github: "settings",
// engine-homes/layout.ts (a Team Cloud's per-audience engine homes); drivers/pi-session.ts.
"engine-homes": "engine_state", "pi-sessions": "engine_state",
// host/team-files.ts (container-computer.ts's vm-home and vm-homes are placed in dataPlacement).
diff --git a/server/request-auth.ts b/server/request-auth.ts
index 438e1600b6..3e37a0bda7 100644
--- a/server/request-auth.ts
+++ b/server/request-auth.ts
@@ -515,6 +515,10 @@ export const CLIENT_ALLOW: ReadonlyArray<{ methods: readonly string[]; path: Reg
{ methods: ["POST"], path: /^\/api\/skill-burgers\/[^/]+\/paths$/ },
{ methods: ["POST"], path: /^\/api\/skill-burger-summary$/ },
{ methods: ["POST"], path: /^\/api\/slack\/team\/messages(?:\/[0-9a-f-]{36}\/stop)?$/ },
+ // GitHub sign-in: a Team Cloud member's own only; anywhere else the handler takes the owner or an admin alone and never
+ // answers with a token (routes/github-sign-in.ts)
+ { methods: ["GET"], path: /^\/api\/github\/sign-in$/ },
+ { methods: ["POST"], path: /^\/api\/github\/sign-in\/(?:start|cancel|token|sign-out)$/ },
];
export function requiredScope(method: string, path: string, features: { sharedComputers?: boolean } = {}): Scope {
diff --git a/server/routes/github-sign-in.test.ts b/server/routes/github-sign-in.test.ts
new file mode 100644
index 0000000000..3cac00d181
--- /dev/null
+++ b/server/routes/github-sign-in.test.ts
@@ -0,0 +1,112 @@
+import type { IncomingMessage, ServerResponse } from "node:http";
+import { describe, expect, it, vi } from "vitest";
+
+import { GithubSignInError, type GithubSignIn } from "../github/sign-in.ts";
+import { personKey } from "../person-key.ts";
+import { requiredScope, type RequestAuth } from "../request-auth.ts";
+import type { SessionRecord } from "../sessions.ts";
+import { createGithubSignInRoutes, githubAudience } from "./github-sign-in.ts";
+import { PASS } from "./table.ts";
+
+const PASTED = ["github", "pat", "11FIXTURE0", "y".repeat(40)].join("_");
+const session = (fields: Partial<SessionRecord>, scopes: Array<"admin" | "client">): RequestAuth => ({
+ kind: "session", via: "cookie", scopes, session: { id: "s-1", tokenHash: "0".repeat(64), label: "Desktop", scopes, createdAt: 1, lastSeenAt: 1, expiresAt: 9_000, ...fields } as SessionRecord,
+});
+const OWNER_WINDOW: RequestAuth = { kind: "loopback", scopes: ["admin"] };
+const BOT_SHELL: RequestAuth = { kind: "loopback", scopes: ["admin"], trust: "service" };
+const ADMIN_DEVICE = session({}, ["admin"]);
+const PHONE = session({}, ["client"]);
+const ADA = session({ email: "[email protected]", teamRole: "member", membershipAuthority: "team" }, ["client"]);
+const TEAM_ADMIN = session({ email: "[email protected]", teamRole: "admin", membershipAuthority: "team" }, ["admin", "client"]);
+
+function fakeSignIn() {
+ const seen: Array<{ action: string; audience: string; token?: string }> = [];
+ const signIn: Pick<GithubSignIn, "status" | "start" | "cancel" | "saveToken" | "signOut"> = {
+ status: vi.fn(async (audience: string) => { seen.push({ action: "status", audience }); return { state: "signed-out" as const, download: false }; }),
+ start: vi.fn(async (audience: string) => { seen.push({ action: "start", audience }); return { state: "signing-in" as const, code: "ABCD-1234", verificationUrl: "https://github.com/login/device", expiresAt: 5 }; }),
+ cancel: vi.fn(async (audience: string) => { seen.push({ action: "cancel", audience }); return { state: "signed-out" as const, download: false }; }),
+ saveToken: vi.fn(async (audience: string, token: string) => {
+ seen.push({ action: "token", audience, token });
+ if (token !== PASTED) throw new GithubSignInError(400, "GitHub did not accept this token. Check it and paste it again.");
+ return { state: "signed-in" as const, login: "octo-fixture", source: "token" as const, scopes: [], checkedAt: 1 };
+ }),
+ signOut: vi.fn(async (audience: string) => { seen.push({ action: "sign-out", audience }); throw new Error(`gh said something about ${PASTED}`); }),
+ };
+ return { signIn, seen };
+}
+
+async function call(team: boolean, auth: RequestAuth, method: string, path: string, options: { body?: unknown; headers?: Record<string, string> } = {}) {
+ const { signIn, seen } = fakeSignIn();
+ const route = createGithubSignInRoutes({ signIn, team });
+ const answers: Array<{ status: number; body: unknown }> = [];
+ const headers: Record<string, string> = { host: "127.0.0.1:8799", ...options.headers };
+ const out = await route({
+ req: { headers, socket: { remoteAddress: "127.0.0.1" } } as unknown as IncomingMessage, res: { setHeader: () => {} } as unknown as ServerResponse,
+ url: new URL(`http://127.0.0.1:8799${path}`), path: path.split("?")[0]!, method, auth,
+ json: (_res, status, body) => { answers.push({ status, body }); }, readBody: async () => options.body,
+ });
+ return { out, answer: answers[0], seen };
+}
+
+describe("GitHub sign-in routes", () => {
+ it("off a Team Cloud: the owner's window and an admin reach the server's one sign-in, nobody else", async () => {
+ for (const auth of [OWNER_WINDOW, ADMIN_DEVICE]) {
+ const { answer, seen } = await call(false, auth, "POST", "/api/github/sign-in/start");
+ expect(answer?.status).toBe(200);
+ expect(seen).toEqual([{ action: "start", audience: "owner" }]);
+ }
+ for (const auth of [BOT_SHELL, PHONE, ADA]) {
+ const { answer, seen } = await call(false, auth, "GET", "/api/github/sign-in");
+ expect(answer?.status).toBe(403);
+ expect(seen).toEqual([]);
+ }
+ });
+
+ it("on a Team Cloud: each member reaches only their own, and the loopback or a session without membership none", async () => {
+ const ada = await call(true, ADA, "GET", "/api/github/sign-in?check=1");
+ expect(ada.answer?.status).toBe(200);
+ expect(ada.seen).toEqual([{ action: "status", audience: personKey({ id: "", email: "[email protected]" }) }]);
+ const bo = await call(true, TEAM_ADMIN, "POST", "/api/github/sign-in/cancel");
+ expect(bo.seen).toEqual([{ action: "cancel", audience: personKey({ id: "", email: "[email protected]" }) }]);
+ for (const auth of [OWNER_WINDOW, BOT_SHELL, ADMIN_DEVICE, PHONE]) {
+ const { answer, seen } = await call(true, auth, "POST", "/api/github/sign-in/start");
+ expect(answer?.status).toBe(403);
+ expect(seen).toEqual([]);
+ }
+ expect(githubAudience(ADA, true)).not.toBe(githubAudience(TEAM_ADMIN, true));
+ });
+
+ it("is reachable by a client session only so a Team Cloud member can use it, and only these paths", () => {
+ expect(requiredScope("GET", "/api/github/sign-in")).toBe("client");
+ for (const action of ["start", "cancel", "token", "sign-out"]) expect(requiredScope("POST", `/api/github/sign-in/${action}`)).toBe("client");
+ expect(requiredScope("GET", "/api/github/sign-in/token")).toBe("admin");
+ expect(requiredScope("POST", "/api/github/sign-in/other")).toBe("admin");
+ });
+
+ it("takes changes only from this server's own page", async () => {
+ const cross = await call(false, ADMIN_DEVICE, "POST", "/api/github/sign-in/start", { headers: { origin: "https://evil.example", "sec-fetch-site": "cross-site" } });
+ expect(cross.answer?.status).toBe(403);
+ expect(cross.seen).toEqual([]);
+ const own = await call(false, ADMIN_DEVICE, "POST", "/api/github/sign-in/start", { headers: { origin: "http://127.0.0.1:8799", "sec-fetch-site": "same-origin" } });
+ expect(own.answer?.status).toBe(200);
+ });
+
+ it("never answers with a token, even from an error", async () => {
+ const saved = await call(false, OWNER_WINDOW, "POST", "/api/github/sign-in/token", { body: { token: PASTED } });
+ expect(saved.answer?.status).toBe(200);
+ expect(JSON.stringify(saved.answer)).not.toContain(PASTED);
+ const refused = await call(false, OWNER_WINDOW, "POST", "/api/github/sign-in/token", { body: { token: "wrong" } });
+ expect(refused.answer).toEqual({ status: 400, body: { error: "GitHub did not accept this token. Check it and paste it again." } });
+ const failed = await call(false, OWNER_WINDOW, "POST", "/api/github/sign-in/sign-out");
+ expect(failed.answer?.status).toBe(500);
+ expect(JSON.stringify(failed.answer)).not.toContain(PASTED);
+ expect((await call(false, OWNER_WINDOW, "POST", "/api/github/sign-in/token", { body: {} })).answer?.status).toBe(400);
+ });
+
+ it("passes other paths on and refuses wrong methods", async () => {
+ expect((await call(false, OWNER_WINDOW, "GET", "/api/github/other-thing")).out).toBe(PASS);
+ expect((await call(false, OWNER_WINDOW, "POST", "/api/github/sign-in")).answer?.status).toBe(405);
+ expect((await call(false, OWNER_WINDOW, "GET", "/api/github/sign-in/start")).answer?.status).toBe(405);
+ expect((await call(false, OWNER_WINDOW, "POST", "/api/github/sign-in/nope")).answer?.status).toBe(404);
+ });
+});
diff --git a/server/routes/github-sign-in.ts b/server/routes/github-sign-in.ts
new file mode 100644
index 0000000000..b5d27ec8e4
--- /dev/null
+++ b/server/routes/github-sign-in.ts
@@ -0,0 +1,60 @@
+// GitHub sign-in (server/github/sign-in.ts; shapes in shared/github-sign-in.ts). Whose sign-in a request reaches:
+// - off a Team Cloud, the server's one, for its owner or an admin (ownerOrAdmin): a client session gets 403;
+// - on a Team Cloud, the session's own member's (sessionMember → personKey of their address), so these paths are in
+// CLIENT_ALLOW; the loopback, a device session and anyone without a membership get 403, and no request ever reaches
+// another person's or the team's.
+// No answer ever carries a token. Changes must come from this server's own page.
+import { GITHUB_SIGN_IN_PATH } from "../../shared/github-sign-in.ts";
+import { GithubSignInError, type GithubSignIn } from "../github/sign-in.ts";
+import { personKey } from "../person-key.ts";
+import { fromBrowser, isSameOrigin, ownerOrAdmin, type RequestAuth } from "../request-auth.ts";
+import { sessionMember } from "./team-phone.ts";
+import { PASS, type RouteHandler } from "./table.ts";
+
+export interface GithubSignInRouteDeps {
+ signIn: Pick<GithubSignIn, "status" | "start" | "cancel" | "saveToken" | "signOut">;
+ /** This server is a Team Cloud: each member signs in for themselves. */
+ team: boolean;
+}
+
+const ACTIONS = new Set(["start", "cancel", "token", "sign-out"]);
+const TOKEN_BODY_MAX = 4 * 1024;
+
+/** Whose sign-in this request may reach, or null. */
+export function githubAudience(auth: RequestAuth, team: boolean): string | null {
+ if (!team) return ownerOrAdmin(auth) ? "owner" : null;
+ const member = auth.kind === "session" ? sessionMember(auth.session) : null;
+ return member ? personKey({ id: "", email: member.member.email }) : null;
+}
+
+export function createGithubSignInRoutes(deps: GithubSignInRouteDeps): RouteHandler {
+ return async ({ req, res, url, path, method, auth, json, readBody }) => {
+ if (path !== GITHUB_SIGN_IN_PATH && !path.startsWith(`${GITHUB_SIGN_IN_PATH}/`)) return PASS;
+ const action = path === GITHUB_SIGN_IN_PATH ? null : path.slice(GITHUB_SIGN_IN_PATH.length + 1);
+ if (action !== null && !ACTIONS.has(action)) return json(res, 404, { error: "not found" });
+ if (method !== (action === null ? "GET" : "POST")) return json(res, 405, { error: "method not allowed" });
+ res.setHeader("cache-control", "no-store");
+ const audience = githubAudience(auth, deps.team);
+ if (!audience) {
+ return json(res, 403, { error: deps.team ? "Sign in to this team's Cloud to connect your own GitHub." : "Only the owner or an admin of this server can connect GitHub." });
+ }
+ if (action !== null && fromBrowser(req) && !isSameOrigin(req)) return json(res, 403, { error: "forbidden: cross-origin request" });
+ try {
+ switch (action) {
+ case null: return json(res, 200, await deps.signIn.status(audience, { check: url.searchParams.get("check") === "1" }));
+ case "start": return json(res, 200, await deps.signIn.start(audience));
+ case "cancel": return json(res, 200, await deps.signIn.cancel(audience));
+ case "sign-out": return json(res, 200, await deps.signIn.signOut(audience));
+ default: {
+ const body = await readBody(req, TOKEN_BODY_MAX).catch(() => null) as { token?: unknown } | null;
+ if (typeof body?.token !== "string") return json(res, 400, { error: "Paste a GitHub token." });
+ return json(res, 200, await deps.signIn.saveToken(audience, body.token));
+ }
+ }
+ } catch (error) {
+ if (error instanceof GithubSignInError) return json(res, error.status, { error: error.message });
+ // Never the error's text: it could hold what gh or GitHub said about the token.
+ return json(res, 500, { error: "GitHub sign-in did not work this time. Try again." });
+ }
+ };
+}
diff --git a/server/vault-store.test.ts b/server/vault-store.test.ts
index 24fc0b4fc0..5507b3b5f9 100644
--- a/server/vault-store.test.ts
+++ b/server/vault-store.test.ts
@@ -448,3 +448,30 @@ describe("the held-secret scrubber", () => {
expect(redactSecretsInText("My password is fake-hunter2, enjoy.")).toBe("My password is fake-hunter2, enjoy.");
});
});
+
+describe("a pasted GitHub token", () => {
+ // Assembled here: it only has to look like one.
+ const token = ["github", "pat", "11FIXTURE0", "z".repeat(40)].join("_");
+ const member = `p_${"a".repeat(22)}`;
+
+ it("is kept sealed per sign-in, masked like every saved secret, never listed and never a bot's", () => {
+ const store = new VaultStore({ dataDir: dir });
+ store.setGithubToken("owner", { token, login: "octo-fixture" });
+ store.setGithubToken(member, { token: `${token}m`, login: "member-login" });
+ expect(readFileSync(join(dir, LOGINS_FILE), "utf8")).not.toContain(token);
+ const again = new VaultStore({ dataDir: dir });
+ expect(again.githubToken("owner")).toEqual({ token, login: "octo-fixture" });
+ expect(again.githubToken(member)?.login).toBe("member-login");
+ expect(again.secretValues()).toEqual(expect.arrayContaining([token, `${token}m`]));
+ expect(again.listSecrets(TEAM_READER)).toEqual([]);
+ expect(again.listSecrets({ person: member, team: false })).toEqual([]);
+ expect(again.secretNamesFor("bot-a", TEAM_READER)).toEqual([]);
+ expect(new HeldSecrets(again).scrub(`clone with ${token} please`)).not.toContain(token);
+
+ again.forgetPerson(member);
+ expect(again.githubToken(member)).toBeNull();
+ expect(again.githubToken("owner")?.token).toBe(token);
+ again.setGithubToken("owner", null);
+ expect(new VaultStore({ dataDir: dir }).githubToken("owner")).toBeNull();
+ });
+});
diff --git a/server/vault-store.ts b/server/vault-store.ts
index 016dc95fe0..bd64b90afd 100644
--- a/server/vault-store.ts
+++ b/server/vault-store.ts
@@ -83,6 +83,9 @@ const fileSchema = z.object({
/** Security: MCP server name → the items whose `vault:<id>` that server may read. Written only when a bot's secretRef
* is redeemed into the server (or a move carries the server), so a pointer planted in config.json reads nothing. */
mcpKeys: z.record(z.string(), z.array(z.string().min(1))).optional(),
+ /** A pasted GitHub token per sign-in (`owner`, or a Team Cloud member's person key): server-side git and GitHub calls
+ * only (server/github/sign-in.ts), never a bot's, never listed with the saved secrets. */
+ github: z.record(z.string(), z.object({ token: z.string().min(1), login: z.string(), savedAt: z.number() })).optional(),
});
const memberSecretsSchema = z.object({
@@ -447,8 +450,9 @@ export class VaultStore {
forgetPerson(person: string): number {
const data = this.read();
const gone = (data.secrets ?? []).filter((secret) => secret.person === person).map((secret) => secret.id);
+ if (data.github?.[person]) this.setGithubToken(person, null);
if (!gone.length) return 0;
- this.write({ ...data, secrets: data.secrets!.filter((secret) => secret.person !== person) });
+ this.write({ ...this.read(), secrets: data.secrets!.filter((secret) => secret.person !== person) });
for (const id of gone) this.secretChanged(id);
return gone.length;
}
@@ -555,9 +559,23 @@ export class VaultStore {
this.write(Object.keys(grants).length ? { ...rest, onePasswordItemGrants: grants } : rest);
}
+ /** The GitHub token pasted for one sign-in (sign-in.ts): never a route's answer, never a bot's. */
+ githubToken(audience: string): { token: string; login: string } | null {
+ const saved = this.read().github?.[audience];
+ return saved ? { token: saved.token, login: saved.login } : null;
+ }
+
+ setGithubToken(audience: string, saved: { token: string; login: string } | null): void {
+ const { github, ...rest } = this.read();
+ const { [audience]: _previous, ...others } = github ?? {};
+ const next = saved ? { ...others, [audience]: { ...saved, savedAt: this.now() } } : others;
+ this.write(Object.keys(next).length ? { ...rest, github: next } : rest);
+ }
+
secretValues(): string[] {
const data = this.read();
return [
+ ...Object.values(data.github ?? {}).map((saved) => saved.token),
...data.logins.flatMap((login) => [login.password, ...(login.totp ? [login.totp.secret] : [])]),
...(data.onePassword ? [data.onePassword.token] : []),
...(data.bitwarden ? [data.bitwarden.clientSecret, data.bitwarden.password] : []),
diff --git a/server/workspace-backup-policy.test.ts b/server/workspace-backup-policy.test.ts
index 6946aa686e..d01eebb528 100644
--- a/server/workspace-backup-policy.test.ts
+++ b/server/workspace-backup-policy.test.ts
@@ -61,6 +61,13 @@ describe("workspace backup data boundary", () => {
for (const path of ["logins.json", "logins.md", "workspaces/bot/logins.json.enc", "attachments/logins-key"]) expect(excludedWorkspaceAuthPath(path)).toBe(false);
});
+ it("never exports a GitHub sign-in's folder, whose config holds its token", () => {
+ for (const path of ["github", "github/owner/config/hosts.yml", "github/p_abcdefghijklmnopqrstuv/config/hosts.yml", "github/owner/home/.gitconfig"]) {
+ expect(excludedWorkspaceAuthPath(path)).toBe(true);
+ }
+ for (const path of ["workspaces/bot/github/notes.md", "githubber/x", "task-workspaces/b/t/github"]) expect(excludedWorkspaceAuthPath(path)).toBe(false);
+ });
+
it("never exports or restores a Cloud home's connected-apps installation", () => {
for (const path of ["connected-apps-installation.json", "connected-apps-installation.json.4242.05a7b3e0-1234-4abc-8def-0123456789ab.tmp"]) {
expect(excludedWorkspaceAuthPath(path)).toBe(true);
diff --git a/server/workspace-backup-policy.ts b/server/workspace-backup-policy.ts
index e937591542..ab769682d1 100644
--- a/server/workspace-backup-policy.ts
+++ b/server/workspace-backup-policy.ts
@@ -48,6 +48,8 @@ export function excludedWorkspaceAuthPath(path: string): boolean {
if (/^team-policy\.json(?:$|\.\d+\.[0-9a-f-]+\.tmp$)/.test(path)) return true;
// A Team Cloud member's own installation, keys and sign-ins: theirs, never in the team's backup.
if (/^people-connections(?:\/|$)/.test(path)) return true;
+ // GitHub sign-ins (github/sign-in.ts): each holds its token in plain text for GitHub CLI, and stays on this server.
+ if (/^github(?:\/|$)/.test(path)) return true;
// A dated copy of the settings file, and the copy of one that could not be understood: they hold the credentials
// the settings file holds, so they never leave the computer they were taken on.
if (/^config\.json\.(?:bak\.\d{8}-\d{6}(?:-\d+)?|unreadable-[0-9a-f]{12})(?:\.\d+\.[0-9a-f-]+\.tmp)?$/.test(path)) return true;
diff --git a/shared/github-sign-in.ts b/shared/github-sign-in.ts
new file mode 100644
index 0000000000..d4fa2e9d67
--- /dev/null
+++ b/shared/github-sign-in.ts
@@ -0,0 +1,29 @@
+// GitHub sign-in for the server's own git and GitHub actions (server/github/). What a client sees: never a token.
+// GET /api/github/sign-in[?check=1] → GithubSignInStatus check=1: ask GitHub again whether the sign-in works
+// POST /api/github/sign-in/start → GithubSignInStatus the code to type at verificationUrl
+// POST /api/github/sign-in/cancel → GithubSignInStatus
+// POST /api/github/sign-in/token {token} → GithubSignInStatus a pasted fine-grained token instead
+// POST /api/github/sign-in/sign-out → GithubSignInStatus
+export const GITHUB_SIGN_IN_PATH = "/api/github/sign-in";
+
+/** Where the sign-in comes from: OpenMausBot's own GitHub CLI sign-in, a pasted token, or the person's own GitHub CLI
+ * on this computer (which OpenMausBot reads and never changes). */
+export type GithubSignInSource = "mausbot" | "token" | "cli";
+
+/** How the last sign-in attempt ended, when it did not sign in. */
+export interface GithubSignInLast {
+ outcome: "expired" | "failed" | "cancelled";
+ reason?: string;
+ at: number;
+}
+
+export type GithubSignInStatus = { last?: GithubSignInLast } & (
+ /** `download`: Start first fetches GitHub CLI (about 15 MB). */
+ | { state: "signed-out"; download: boolean }
+ /** Getting GitHub CLI (a download the first time) and the code ready: ask again shortly. */
+ | { state: "installing" }
+ | { state: "signing-in"; code: string; verificationUrl: string; expiresAt: number }
+ | { state: "signed-in"; login: string; source: GithubSignInSource; scopes: string[]; orgs?: string[]; checkedAt: number | null }
+ /** The saved sign-in no longer works (revoked, expired): sign in again. */
+ | { state: "invalid"; login: string | null; source: GithubSignInSource; reason: string }
+);