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
16 changes: 16 additions & 0 deletions pm-stack/projector/src/config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
export const DEFAULT_PORT = 7801;

/** Parse the projector's listening port without accepting Number() coercions. */
export function parsePort(raw: string | undefined): number {
if (raw === undefined) return DEFAULT_PORT;

if (!/^[0-9]+$/.test(raw)) {
throw new Error(`Invalid PORT ${JSON.stringify(raw)}; expected a decimal integer in range 1-65535`);
}

const port = Number(raw);
if (!Number.isSafeInteger(port) || port < 1 || port > 65535) {
throw new Error(`Invalid PORT ${JSON.stringify(raw)}; expected a decimal integer in range 1-65535`);
}
return port;
}
16 changes: 15 additions & 1 deletion pm-stack/projector/src/github.ts
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,19 @@ export interface GitHubAuth {

const discoveredInstallations = new Map<string, number>();

function parseConfiguredInstallId(raw: string | undefined): number | undefined {
if (raw === undefined || raw === "") return undefined;

if (!/^[0-9]+$/.test(raw)) {
throw new Error(`Invalid GITHUB_APP_INSTALL_ID ${JSON.stringify(raw)}; expected a positive decimal integer`);
}
const installId = Number(raw);
if (!Number.isSafeInteger(installId) || installId <= 0) {
throw new Error(`Invalid GITHUB_APP_INSTALL_ID ${JSON.stringify(raw)}; expected a positive decimal integer`);
}
return installId;
}

/**
* Resolve the installation id for one repo via GET /repos/{repo}/installation
* (App JWT). An app installed on several accounts (an org + a user) has one
Expand Down Expand Up @@ -122,11 +135,12 @@ export async function apiTokenFor(
fetchFn: typeof fetch = fetch,
installationIds?: Record<string, number>,
): Promise<GitHubAuth> {
const configuredInstallId = parseConfiguredInstallId(env.GITHUB_APP_INSTALL_ID);
let installId = installationIds?.[repo];
if (!installId && env.GITHUB_APP_ID && env.GITHUB_APP_PRIVATE_KEY) {
installId = await discoverInstallationId(env, repo, fetchFn);
}
if (!installId && env.GITHUB_APP_INSTALL_ID) installId = Number(env.GITHUB_APP_INSTALL_ID);
if (!installId) installId = configuredInstallId;
if (env.GITHUB_APP_ID && env.GITHUB_APP_PRIVATE_KEY && installId) {
const jwt = await appJwt(env);
const res = await fetchFn(`https://api.github.com/app/installations/${installId}/access_tokens`, {
Expand Down
3 changes: 2 additions & 1 deletion pm-stack/projector/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
// Entry point: migrate + serve the projector HTTP API.
import { openDb, migrate } from "./store";
import { serve, type ServerEnv } from "./server";
import { parsePort } from "./config";

const env = process.env as unknown as ServerEnv;
const port = Number(env.PORT ?? 7801);
const port = parsePort(env.PORT);

const db = openDb(env);
await migrate(db);
Expand Down
31 changes: 31 additions & 0 deletions pm-stack/projector/test/config.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import { describe, test, expect } from "bun:test";
import { DEFAULT_PORT, parsePort } from "../src/config";

describe("parsePort", () => {
test("uses the existing default only when PORT is unset", () => {
expect(DEFAULT_PORT).toBe(7801);
expect(parsePort(undefined)).toBe(7801);
});

test("accepts plain decimal ports in the valid range", () => {
expect(parsePort("1")).toBe(1);
expect(parsePort("7801")).toBe(7801);
expect(parsePort("65535")).toBe(65535);
});

test("rejects zero, malformed, non-decimal, and out-of-range values", () => {
for (const raw of ["", "0", "-1", "99999", "4870.5", "abc", "1e2", "0x10", "+5", " 5", "5 "]) {
let thrown: unknown;
try {
parsePort(raw);
} catch (error) {
thrown = error;
}
expect(thrown).toBeInstanceOf(Error);
const message = (thrown as Error).message;
expect(message).toContain("PORT");
expect(message).toContain(JSON.stringify(raw));
expect(message).toContain("1-65535");
}
});
});
47 changes: 47 additions & 0 deletions pm-stack/projector/test/github.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -87,4 +87,51 @@ describe("apiTokenFor installation resolution", () => {
const auth = await apiTokenFor(env, "acme/widgets", fetchFn as unknown as typeof fetch);
expect(auth).toEqual({ kind: "app", token: "inst-token" });
});

test("rejects a present invalid static installation ID instead of falling back", async () => {
for (const raw of ["abc", "12.5", "0", "-1", "9007199254740992"]) {
const calls: string[] = [];
const fetchFn = async (url: string) => {
calls.push(url);
return new Response("{}", { status: 404 });
};
const result = await apiTokenFor(
{ GITHUB_APP_INSTALL_ID: raw, GITHUB_TOKEN: "plain-token" },
"acme/invalid-static",
fetchFn as unknown as typeof fetch,
).catch((error: unknown) => error);
expect(result).toBeInstanceOf(Error);
expect((result as Error).message).toContain("GITHUB_APP_INSTALL_ID");
expect((result as Error).message).toContain(JSON.stringify(raw));
expect(calls).toEqual([]);
}
});

test("keeps the plain-token fallback for absent or empty static IDs", async () => {
for (const raw of [undefined, ""]) {
const auth = await apiTokenFor(
{ GITHUB_APP_INSTALL_ID: raw, GITHUB_TOKEN: "plain-token" },
"acme/no-app",
);
expect(auth).toEqual({ kind: "token", token: "plain-token" });
}
});

test("uses a valid static installation ID when discovery is unavailable", async () => {
const env = {
GITHUB_APP_ID: "123",
GITHUB_APP_PRIVATE_KEY: testKeyB64("pkcs8"),
GITHUB_APP_INSTALL_ID: "42",
};
const calls: string[] = [];
const fetchFn = async (url: string) => {
calls.push(url);
if (url === "https://api.github.com/repos/acme/static/installation") return new Response("{}", { status: 404 });
if (url === "https://api.github.com/app/installations/42/access_tokens") return Response.json({ token: "static-token" });
return new Response("{}", { status: 404 });
};
const auth = await apiTokenFor(env, "acme/static", fetchFn as unknown as typeof fetch);
expect(auth).toEqual({ kind: "app", token: "static-token" });
expect(calls).toContain("https://api.github.com/app/installations/42/access_tokens");
});
});
Loading