Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 10 additions & 3 deletions apps/release-bot/.env.example
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,16 @@ DISCORD_BOT_TOKEN=
OPENAI_API_KEY=

# Required once any release source has a channel, for reading releases and the
# commits between them. Needs no scopes beyond public repository read. Without
# it the release sources stop at the start of the run, rather than falling back
# to unauthenticated requests, which GitHub limits to 60 an hour.
# commits between them, as the Outpost GitHub App: an installation token is
# minted each run, so nothing expires. Set all three or none. Without them the
# release sources stop at the start of the run, rather than falling back to
# unauthenticated requests, which GitHub limits to 60 an hour.
GITHUB_APP_ID=
GITHUB_PRIVATE_KEY=
GITHUB_INSTALLATION_ID=

# Local fallback, read only when none of the App variables above are set.
# Needs no scopes beyond public repository read.
GITHUB_TOKEN=

# Where each source posts. A source with no channel is skipped, so these can be
Expand Down
38 changes: 21 additions & 17 deletions apps/release-bot/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -277,22 +277,25 @@ It does not post, so it cannot exercise the length guard in the posting path.

## Environment

| Variable | Required | Purpose |
| ---------------------------- | ---------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `DISCORD_BOT_TOKEN` | yes | Posting, and reading the channel to see what was already announced |
| `OPENAI_API_KEY` | per source | Writing the release announcements. Required once any release source has a channel. Videos run first and need it not at all |
| `GITHUB_TOKEN` | per source | Reading releases and commits. Required once any release source has a channel. Needs no scopes beyond public read; unauthenticated is rate limited to 60 an hour |
| `AGUI_CHANNEL_ID` | per source | Channel for AG-UI releases |
| `CPK_CHANNEL_ID` | per source | Channel for CopilotKit releases, and for OpenBot unless given its own |
| `OPENBOT_CHANNEL_ID` | no | Gives OpenBot its own channel instead of sharing CopilotKit's. Setting it also turns the ping fallback off |
| `OPENBOT_PING_ROLE_ID` | no | Role to ping for OpenBot. Unset inherits `CPK_PING_ROLE_ID`, unless `OPENBOT_CHANNEL_ID` is set |
| `YOUTUBE_CHANNEL_DISCORD_ID` | per source | Channel for video announcements |
| `YOUTUBE_CHANNEL_ID` | per source | The YouTube channel to watch |
| `YOUTUBE_API_KEY` | no | Holds scheduled live streams until they actually start. Without it uploads are unaffected, but a stream posts when it is scheduled. See below |
| `AGUI_PING_ROLE_ID` | no | Role to ping for AG-UI releases. Unset means silent |
| `CPK_PING_ROLE_ID` | no | Role to ping for CopilotKit releases. Unset means silent |
| `YOUTUBE_PING_ROLE_ID` | no | Role to ping for videos. Unset means silent |
| `OPENAI_MODEL` | no | Defaults to `gpt-5.4` |
| Variable | Required | Purpose |
| ---------------------------- | ---------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `DISCORD_BOT_TOKEN` | yes | Posting, and reading the channel to see what was already announced |
| `OPENAI_API_KEY` | per source | Writing the release announcements. Required once any release source has a channel. Videos run first and need it not at all |
| `GITHUB_APP_ID` | per source | Reading releases and commits, as the Outpost GitHub App. Required once any release source has a channel. A fresh installation token is minted each run |
| `GITHUB_PRIVATE_KEY` | per source | The App private key (PEM). In Railway, reference the github-app service: `${{outpost-github-app.GITHUB_PRIVATE_KEY}}` |
| `GITHUB_INSTALLATION_ID` | per source | The App installation on the CopilotKit org. All watched repos are public, so `ag-ui-protocol/ag-ui` needs no installation of its own |
| `GITHUB_TOKEN` | no | Local fallback, used only when none of the App variables are set. Personal tokens expire; production uses the App |
| `AGUI_CHANNEL_ID` | per source | Channel for AG-UI releases |
| `CPK_CHANNEL_ID` | per source | Channel for CopilotKit releases, and for OpenBot unless given its own |
| `OPENBOT_CHANNEL_ID` | no | Gives OpenBot its own channel instead of sharing CopilotKit's. Setting it also turns the ping fallback off |
| `OPENBOT_PING_ROLE_ID` | no | Role to ping for OpenBot. Unset inherits `CPK_PING_ROLE_ID`, unless `OPENBOT_CHANNEL_ID` is set |
| `YOUTUBE_CHANNEL_DISCORD_ID` | per source | Channel for video announcements |
| `YOUTUBE_CHANNEL_ID` | per source | The YouTube channel to watch |
| `YOUTUBE_API_KEY` | no | Holds scheduled live streams until they actually start. Without it uploads are unaffected, but a stream posts when it is scheduled. See below |
| `AGUI_PING_ROLE_ID` | no | Role to ping for AG-UI releases. Unset means silent |
| `CPK_PING_ROLE_ID` | no | Role to ping for CopilotKit releases. Unset means silent |
| `YOUTUBE_PING_ROLE_ID` | no | Role to ping for videos. Unset means silent |
| `OPENAI_MODEL` | no | Defaults to `gpt-5.4` |

Announcements are silent by default, except that OpenBot inherits CopilotKit's
ping role while it shares CopilotKit's channel. At roughly eight a week across the three
Expand Down Expand Up @@ -404,7 +407,8 @@ allowance of 10,000 a day.
policy and the watch patterns, so none of those need setting in the dashboard.
3. Set the variables from the table above under Variables. At minimum
`DISCORD_BOT_TOKEN`, plus a channel id per source you want running. Release
sources also need `OPENAI_API_KEY` and `GITHUB_TOKEN`.
sources also need `OPENAI_API_KEY` and the three `GITHUB_APP_*` variables
(`GITHUB_APP_ID`, `GITHUB_PRIVATE_KEY`, `GITHUB_INSTALLATION_ID`).
4. Invite the bot to each Discord server with the permissions in the section
above. Check Read Message History in particular: without it nothing fails,
the bot just re-posts the newest release every run.
Expand Down
124 changes: 124 additions & 0 deletions apps/release-bot/src/__tests__/github-auth.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
import { createVerify, generateKeyPairSync } from 'node:crypto';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { appJwt, githubToken, resetGitHubAuth } from '../github-auth.js';

const ORIGINAL_FETCH = globalThis.fetch;
const VARIABLES = ['GITHUB_APP_ID', 'GITHUB_PRIVATE_KEY', 'GITHUB_INSTALLATION_ID', 'GITHUB_TOKEN'];

const { privateKey, publicKey } = generateKeyPairSync('rsa', { modulusLength: 2048 });
const PEM = privateKey.export({ type: 'pkcs1', format: 'pem' }).toString();

type Call = { url: string; init: RequestInit };

function serveToken(status = 200, failure: unknown = {}) {
const calls: Call[] = [];
vi.stubGlobal('fetch', (input: string | URL, init: RequestInit) => {
calls.push({ url: String(input), init });
const body =
status === 200
? { token: 'ghs_minted', expires_at: new Date(Date.now() + 3600_000).toISOString() }
: failure;
return Promise.resolve(new Response(JSON.stringify(body), { status }));
});
return calls;
}

describe('githubToken', () => {
const saved: Record<string, string | undefined> = {};

beforeEach(() => {
for (const name of VARIABLES) {
saved[name] = process.env[name];
delete process.env[name];
}
resetGitHubAuth();
});

afterEach(() => {
vi.stubGlobal('fetch', ORIGINAL_FETCH);
for (const [key, value] of Object.entries(saved)) {
if (value === undefined) delete process.env[key];
else process.env[key] = value;
}
});

it('mints an installation token from the App variables, asking for metadata only', async () => {
process.env.GITHUB_APP_ID = '123';
process.env.GITHUB_PRIVATE_KEY = PEM;
process.env.GITHUB_INSTALLATION_ID = '456';
process.env.GITHUB_TOKEN = 'ghp_dead';
const calls = serveToken();

await expect(githubToken()).resolves.toBe('ghs_minted');

expect(calls).toHaveLength(1);
expect(calls[0]!.url).toBe('https://api.github.com/app/installations/456/access_tokens');
expect(calls[0]!.init.method).toBe('POST');
expect(JSON.parse(String(calls[0]!.init.body))).toEqual({
permissions: { metadata: 'read' },
});
const auth = (calls[0]!.init.headers as Record<string, string>).Authorization;
const [header, payload, signature] = auth!.replace('Bearer ', '').split('.');
const verify = createVerify('RSA-SHA256');
verify.update(`${header}.${payload}`);
expect(verify.verify(publicKey, Buffer.from(signature!, 'base64url'))).toBe(true);
expect(JSON.parse(Buffer.from(payload!, 'base64url').toString()).iss).toBe('123');
});

it('reuses the token for the rest of the run', async () => {
process.env.GITHUB_APP_ID = '123';
process.env.GITHUB_PRIVATE_KEY = PEM;
process.env.GITHUB_INSTALLATION_ID = '456';
const calls = serveToken();

await githubToken();
await githubToken();

expect(calls).toHaveLength(1);
});

it('accepts a key whose newlines arrive escaped', async () => {
process.env.GITHUB_APP_ID = '123';
process.env.GITHUB_PRIVATE_KEY = PEM.replace(/\n/g, '\\n');
process.env.GITHUB_INSTALLATION_ID = '456';
serveToken();

await expect(githubToken()).resolves.toBe('ghs_minted');
});

it('names the missing App variable rather than falling back to GITHUB_TOKEN', async () => {
process.env.GITHUB_APP_ID = '123';
process.env.GITHUB_INSTALLATION_ID = '456';
process.env.GITHUB_TOKEN = 'ghp_dead';

await expect(githubToken()).rejects.toThrow(/^GITHUB_PRIVATE_KEY is not set/);
});

it('falls back to GITHUB_TOKEN when no App variable is set', async () => {
process.env.GITHUB_TOKEN = 'ghp_local';
await expect(githubToken()).resolves.toBe('ghp_local');
});

it('reports nothing configured as a missing App id', async () => {
await expect(githubToken()).rejects.toThrow(/^GITHUB_APP_ID is not set/);
});

it('surfaces a refused exchange with its status', async () => {
process.env.GITHUB_APP_ID = '123';
process.env.GITHUB_PRIVATE_KEY = PEM;
process.env.GITHUB_INSTALLATION_ID = '456';
serveToken(401, { message: 'A JSON web token could not be decoded' });

await expect(githubToken()).rejects.toThrow(/^GitHub 401 minting an installation token/);
});
});

describe('appJwt', () => {
it('backdates iat for clock drift and stays inside the 10-minute ceiling', () => {
const now = Date.UTC(2026, 0, 1);
const payload = JSON.parse(
Buffer.from(appJwt('9', PEM, now).split('.')[1]!, 'base64url').toString(),
);
expect(payload).toEqual({ iat: now / 1000 - 60, exp: now / 1000 + 540, iss: '9' });
});
});
118 changes: 118 additions & 0 deletions apps/release-bot/src/github-auth.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
/**
* The credential for GitHub reads: a GitHub App installation token, minted per run.
*
* The bot used to read with a personal token in `GITHUB_TOKEN`. That token
* expired, and every release source failed with 401 until someone noticed. An
* installation token is minted from the App's private key on each run and lasts
* an hour, so there is nothing to expire between runs.
*
* It is the same App the github-app service runs as, with the same three
* variables. It asks for `metadata: read` only, the one permission it needs:
* every repository this bot reads is public, and GitHub serves releases and
* compares of a public repository to any token. It must not ask for
* `contents: read`, which the App does not hold - GitHub refuses the whole
* exchange with a 422 rather than narrowing it. `ag-ui-protocol/ag-ui` is in
* another org with no installation, and is readable with this token all the
* same.
*
* `GITHUB_TOKEN` still works when the App variables are absent, for local runs.
*/

import { createSign } from 'node:crypto';
import { TIMEOUT_MS, parseJson } from './http.js';

const API = 'https://api.github.com';

const APP_VARIABLES = ['GITHUB_APP_ID', 'GITHUB_PRIVATE_KEY', 'GITHUB_INSTALLATION_ID'] as const;

/**
* Re-mint this long before GitHub's expiry. A token issued for an hour outlives
* the 20-minute run budget, so in practice one token serves the whole run; the
* margin covers a run that overruns its budget finishing the release in flight.
*/
const REFRESH_MARGIN_MS = 5 * 60_000;

let cached: { token: string; expiresAt: number } | undefined;

/** Forget the cached token. For tests. */
export function resetGitHubAuth() {
cached = undefined;
}

const base64url = (input: string | Buffer) => Buffer.from(input).toString('base64url');

/**
* The App's JWT, RS256-signed, as GitHub specifies: issued a minute in the past
* to absorb clock drift, expiring well inside GitHub's 10-minute ceiling.
*/
export function appJwt(appId: string, privateKey: string, now = Date.now()): string {
const seconds = Math.floor(now / 1000);
const header = base64url(JSON.stringify({ alg: 'RS256', typ: 'JWT' }));
const payload = base64url(
JSON.stringify({ iat: seconds - 60, exp: seconds + 540, iss: appId }),
);
const signer = createSign('RSA-SHA256');
signer.update(`${header}.${payload}`);
// A key pasted into a single-line variable arrives with literal `\n`.
const pem = privateKey.includes('\\n') ? privateKey.replace(/\\n/g, '\n') : privateKey;
return `${header}.${payload}.${signer.sign(pem).toString('base64url')}`;
}

async function mint(appId: string, privateKey: string, installationId: string) {
const res = await fetch(`${API}/app/installations/${installationId}/access_tokens`, {
method: 'POST',
headers: {
Accept: 'application/vnd.github+json',
'User-Agent': 'copilotkit-release-bot',
Authorization: `Bearer ${appJwt(appId, privateKey)}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({ permissions: { metadata: 'read' } }),
signal: AbortSignal.timeout(TIMEOUT_MS),
});
if (!res.ok) {
// The body is GitHub's error message, never the token: there is none on
// a failed exchange.
throw new Error(
`GitHub ${res.status} minting an installation token: ${(await res.text()).slice(0, 200)}`,
);
}
const body = await parseJson<{ token?: string; expires_at?: string }>(res, 'GitHub');
if (!body.token || !body.expires_at) {
throw new Error('GitHub returned an installation token response without a token.');
}
return { token: body.token, expiresAt: Date.parse(body.expires_at) };
}

/**
* The bearer token for a GitHub read.
*
* Throws `<NAME> is not set` for a missing credential, which index.ts treats as
* a misconfiguration that stops the run rather than one source. Setting some of
* the App variables and not others is reported the same way, naming the first
* one missing, rather than quietly falling back to `GITHUB_TOKEN`.
*/
export async function githubToken(): Promise<string> {
const values = APP_VARIABLES.map((name) => process.env[name]?.trim() || undefined);

if (values.every((value) => value === undefined)) {
const token = process.env.GITHUB_TOKEN;
if (!token) {
throw new Error(
'GITHUB_APP_ID is not set, and neither is GITHUB_TOKEN. Set the App variables ' +
'(GITHUB_APP_ID, GITHUB_PRIVATE_KEY, GITHUB_INSTALLATION_ID).',
);
}
return token;
}

const missing = APP_VARIABLES.find((_, i) => values[i] === undefined);
if (missing)
throw new Error(`${missing} is not set, though the other GitHub App variables are.`);

if (cached && cached.expiresAt - REFRESH_MARGIN_MS > Date.now()) return cached.token;

const [appId, privateKey, installationId] = values as [string, string, string];
cached = await mint(appId, privateKey, installationId);
return cached.token;
}
Loading
Loading