Skip to content

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

fix(skills): send the connected GitHub sign-in on skill import API requests

Ooi Pin Jun21f4afa93b1e
diff --git a/server/index.ts b/server/index.ts
index c0cc5e72dd..f785eb71aa 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 { createGhTools } from "./github/gh-cli.ts"; import { createGithubSignIn } from "./github/sign-in.ts"; import { provideGithubSignIn } from "./github/token.ts"; import { createGitCredentialRoutes } from "./github/git-credential.ts"; import { createGithubSignInRoutes } from "./routes/github-sign-in.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 { createGitCredentialRoutes } from "./github/git-credential.ts"; import { gitAudience } from "./github/git-access.ts"; import { createGithubSignInRoutes, githubAudience } 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";
@@ -384,7 +384,7 @@ import {
stageSkillWrite,
undoSkillWrite,
} from "./skills.ts";
-import { fetchSkillFromSource } from "./skill-fetch.ts";
+import { fetchSkillFromSource, skillImportToken } from "./skill-fetch.ts";
import { ensureTaskWorkspaceWithSkills, harnessSkillLinks } from "./skill-task-links.ts"; import { changedWords, createLendingLifts, handedInSince } from "./host/lending-lifts.ts"; import { deviceWord } from "./lent-computers.ts"; import { sendingSession } from "./sending-sessions.ts";
import { importedSkillRequest, parseSkillManageReferences, previousSkillVersion, skillCardCopy, skillRequestReferences } from "./skill-request-card.ts";
import { skillReferencesSha256 } from "./skill-storage.ts";
@@ -12000,7 +12000,7 @@ ROUTES.push(createBotLifecycleRoutes({
store, routines: () => routines, interruptAllDirectThreads, cancelDirectTurnDispatch, revokeInternalCapabilitiesForThread,
activeGroupTurnForBot, cancelGroupTurnOperations, runningTurnInstance, closeOpenApprovals, deleteBotWithLifecycle, deleteRefusal: (auth, botId) => memberDeleteRefusal(auth, store.bot(botId), Boolean(CLOUD_TEAM)),
}));
-const skillsRoutes = createBotSkillsRoutes({ store, cfg, listBotSkills, readBotSkillFile, stagedSkillListing }); ROUTES.push(skillsRoutes);
+const skillsRoutes = createBotSkillsRoutes({ store, cfg, listBotSkills, readBotSkillFile, stagedSkillListing, team: Boolean(CLOUD_TEAM) }); ROUTES.push(skillsRoutes);
ROUTES.push(createEmailRoutes({ service: emailService }));
ROUTES.push(phones.routes);
ROUTES.push(createSkillShareRoutes({ enabled: () => skillsHost.mode() !== "off", botExists: (id) => Boolean(store.bot(id)),
@@ -13416,7 +13416,7 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {
return json(res, 403, { error: "source conversation does not belong to sender" });
}
if (isSkillSwitchAction(received.action)) { const staged = skillSwitch.stage(from, fromThreadId, received.action, received, appliesDirectly(from.id, fromThreadId)); return json(res, staged.status, staged.body); }
- const body = await importedSkillRequest(received, fetch, callSignal); if ("importError" in body) return json(res, 422, { error: body.importError }); if (!internalCapabilityIsActive(internalCapability)) return json(res, 401, { error: TURN_ENDED_REFUSAL }); if (!skillAuthoringEnabled(cfg)) return json(res, 403, { error: "skill authoring is not enabled in Settings" });
+ const body = await importedSkillRequest(received, fetch, callSignal, () => skillImportToken(gitAudience(fromThreadId))); if ("importError" in body) return json(res, 422, { error: body.importError }); if (!internalCapabilityIsActive(internalCapability)) return json(res, 401, { error: TURN_ENDED_REFUSAL }); if (!skillAuthoringEnabled(cfg)) return json(res, 403, { error: "skill authoring is not enabled in Settings" });
const direct = appliesDirectly(from.id, fromThreadId);
const persistence = skillProposalPersistence(from.id, fromThreadId, !direct);
if (!persistence.ok) return json(res, persistence.status, { error: persistence.error });
@@ -14541,7 +14541,7 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {
const checked = z.object({ source: z.string().min(1).max(2000) }).strict().safeParse(await readBody(req));
if (!checked.success) return json(res, 400, { error: checked.error.message });
const input = checked.data;
- const fetched = await fetchSkillFromSource(input.source);
+ const fetched = await fetchSkillFromSource(input.source, fetch, undefined, () => skillImportToken(githubAudience(auth, Boolean(CLOUD_TEAM))));
if ("error" in fetched) return json(res, 422, { error: fetched.error });
const skills = [];
for (const skill of fetched.skills) {
diff --git a/server/routes/bot-skills.test.ts b/server/routes/bot-skills.test.ts
index 10610c8b58..edaeb72d9a 100644
--- a/server/routes/bot-skills.test.ts
+++ b/server/routes/bot-skills.test.ts
@@ -5,6 +5,7 @@ import { dirname, join } from "node:path";
import { afterEach, describe, expect, it, vi } from "vitest";
import { DATA_DIR, type AppConfig } from "../config.ts";
+import { provideGithubSignIn } from "../github/token.ts";
import { json, readBody } from "../harness/http.ts";
import type { RequestAuth } from "../request-auth.ts";
import { installLibrarySkill, readLibrarySkillFile, setLibrarySkillEveryBot } from "../skill-library.ts";
@@ -19,6 +20,7 @@ const SKILL = "---\nname: pdf-forms\ndescription: Fills PDF forms.\n---\n\n# PDF
const servers: Server[] = [];
afterEach(async () => {
+ provideGithubSignIn(null);
vi.unstubAllGlobals();
await Promise.all(servers.splice(0).map((server) => new Promise((done) => server.close(done))));
});
@@ -31,6 +33,7 @@ async function serve(botId: string) {
listBotSkills: () => [],
readBotSkillFile: () => null,
stagedSkillListing: (staged) => staged,
+ team: false,
})];
const server = createServer(async (req, res) => {
const url = new URL(req.url ?? "/", "http://localhost");
@@ -79,6 +82,76 @@ describe("importing a skill from GitHub into a bot", () => {
});
});
+describe("whose GitHub sign-in a bot import uses", () => {
+ const TOKEN = "gho_syntheticSkillImportToken";
+ const OWNER = "gho_ownerSignInMustNotLeak";
+ const SKILL_MD = "---\nname: pdf\ndescription: Does pdf things.\n---\n\n# pdf\n";
+
+ async function importAs(auth: RequestAuth) {
+ const asked: Array<string | null | undefined> = [];
+ provideGithubSignIn({
+ token: async (audience) => { asked.push(audience); return audience === "owner" ? TOKEN : OWNER; },
+ reportAuthFailure: () => {},
+ signedIn: () => true,
+ });
+ const botId = `route-auth-${Math.random().toString(36).slice(2, 10)}`;
+ const realFetch = globalThis.fetch;
+ const github = fakeGitHub({ "acme/skills": { "skills/pdf/SKILL.md": SKILL_MD } });
+ const calls: Array<{ url: string; headers: Headers }> = [];
+ const recording: typeof fetch = async (input, init) => {
+ calls.push({ url: String(input), headers: new Headers(init?.headers) });
+ return github.fetch(input, init);
+ };
+ vi.stubGlobal("fetch", recording);
+ const store = { bot: (id: string) => (id === botId ? { id } : undefined), bots: [] } as unknown as Store;
+ const routes = [createBotSkillsRoutes({
+ store,
+ cfg: {} as AppConfig,
+ listBotSkills: () => [],
+ readBotSkillFile: () => null,
+ stagedSkillListing: (staged) => staged,
+ team: false,
+ })];
+ const server = createServer(async (req, res) => {
+ const url = new URL(req.url ?? "/", "http://localhost");
+ if (!await dispatchRoutes(routes, { req, res, url, path: url.pathname, method: req.method ?? "GET", auth, json, readBody })) json(res, 404, {});
+ });
+ servers.push(server);
+ await new Promise<void>((ready) => server.listen(0, "127.0.0.1", ready));
+ const response = await realFetch(`http://127.0.0.1:${(server.address() as AddressInfo).port}/api/bots/${botId}/skills`, {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({ source: "acme/skills" }),
+ });
+ const body = await response.json() as { error?: string };
+ return { status: response.status, body, calls, asked };
+ }
+
+ it("sends the owner sign-in on API requests for an owner or admin", async () => {
+ const { status, body, calls, asked } = await importAs({ kind: "loopback", scopes: ["admin"] } as RequestAuth);
+ expect(status).toBe(201);
+ const api = calls.filter((call) => call.url.startsWith("https://api.github.com/"));
+ const raw = calls.filter((call) => call.url.startsWith("https://raw.githubusercontent.com/"));
+ expect(api.length).toBeGreaterThan(0);
+ expect(raw.length).toBeGreaterThan(0);
+ expect(api.every((call) => call.headers.get("authorization") === `Bearer ${TOKEN}`)).toBe(true);
+ expect(raw.every((call) => call.headers.get("authorization") === null)).toBe(true);
+ expect(asked).toContain("owner");
+ expect(JSON.stringify(body)).not.toContain(TOKEN);
+ expect(calls.every((call) => !call.url.includes(TOKEN))).toBe(true);
+ });
+
+ it("stays anonymous when this request may not use the server sign-in, even if that sign-in exists", async () => {
+ const { status, body, calls, asked } = await importAs({ kind: "loopback", scopes: ["admin"], trust: "service" } as RequestAuth);
+ expect(status).toBe(201);
+ expect(calls.some((call) => call.url.startsWith("https://api.github.com/"))).toBe(true);
+ expect(calls.every((call) => call.headers.get("authorization") === null)).toBe(true);
+ expect(asked).toEqual([]);
+ expect(JSON.stringify({ body, calls })).not.toContain(OWNER);
+ expect(JSON.stringify({ body, calls })).not.toContain(TOKEN);
+ });
+});
+
const learned = (name: string) => `---\nname: ${name}\ndescription: A skill.\n---\n\n# ${name}\n\nSteps.\n`;
describe("removing a skill from one bot", () => {
@@ -117,6 +190,7 @@ describe("removing a skill from one bot", () => {
] as never,
readBotSkillFile: () => null,
stagedSkillListing: (staged) => staged,
+ team: false,
})];
const server = createServer(async (req, res) => {
const url = new URL(req.url ?? "/", "http://localhost");
@@ -181,6 +255,7 @@ describe("removing a skill from one bot", () => {
listBotSkills: () => [],
readBotSkillFile: () => null,
stagedSkillListing: (staged) => staged,
+ team: false,
})];
const server = createServer(async (req, res) => {
const url = new URL(req.url ?? "/", "http://localhost");
diff --git a/server/routes/bot-skills.ts b/server/routes/bot-skills.ts
index d9f27dc785..b18216a7bf 100644
--- a/server/routes/bot-skills.ts
+++ b/server/routes/bot-skills.ts
@@ -5,7 +5,7 @@ import type { AppConfig } from "../config.ts";
import { setImportedSkillEnabled } from "../imported-skills.ts";
import { setNativeSkillEnabled } from "../native-skill-choices.ts";
import { botSkillTemplateSchema } from "../new-bot-defaults.ts";
-import { fetchSkillFromSource } from "../skill-fetch.ts";
+import { fetchSkillFromSource, skillImportToken } from "../skill-fetch.ts";
import { skillImportSummary } from "../skill-folder.ts";
import { installLibrarySkill, librarySkillOptOuts, listLibrarySkills, readLibrarySkillFile, readSkillLibraryIndex, setLibrarySkillEveryBot, setLibrarySkillOptOut, setLibrarySkillReviewState, skillsLibraryEnabled, unassignLibrarySkill } from "../skill-library.ts";
import {
@@ -13,6 +13,7 @@ import {
type SkillListing, type StagedSkillWrite,
} from "../skills.ts";
import type { BotRecord, Store } from "../store.ts";
+import { githubAudience } from "./github-sign-in.ts";
import { PASS, type RouteHandler } from "./table.ts";
export interface BotSkillsRouteDeps {
@@ -21,11 +22,12 @@ export interface BotSkillsRouteDeps {
listBotSkills(bot: BotRecord, threadId?: string): SkillListing[];
readBotSkillFile(bot: BotRecord, name: string): string | null;
stagedSkillListing(staged: StagedSkillWrite): Omit<StagedSkillWrite, "files" | "baseSha256" | "baseAppliedStageId">;
+ team: boolean;
}
export function createBotSkillsRoutes(deps: BotSkillsRouteDeps): RouteHandler {
- const { store, cfg, listBotSkills, readBotSkillFile, stagedSkillListing } = deps;
- return async ({ req, res, url, path, method, json, readBody }) => {
+ const { store, cfg, listBotSkills, readBotSkillFile, stagedSkillListing, team } = deps;
+ return async ({ req, res, url, path, method, auth, json, readBody }) => {
let m: RegExpMatchArray | null = null;
// Imports land DISABLED: a person enables one after reading SKILL.md and its scan warnings.
m = path.match(/^\/api\/bots\/([\w-]+)\/skill-template$/);
@@ -70,7 +72,7 @@ export function createBotSkillsRoutes(deps: BotSkillsRouteDeps): RouteHandler {
if (!store.bot(m[1])) return json(res, 404, { error: "no such bot" });
const parsed = z.object({ source: z.string().min(1).max(2000) }).safeParse(await readBody(req));
if (!parsed.success) return json(res, 400, { error: "source must be a GitHub or skills.sh URL, or owner/repo" });
- const fetched = await fetchSkillFromSource(parsed.data.source);
+ const fetched = await fetchSkillFromSource(parsed.data.source, fetch, undefined, () => skillImportToken(githubAudience(auth, team)));
if ("error" in fetched) return json(res, 422, { error: fetched.error });
const results = fetched.skills.map((skill) => ({ skill, result: installSkill(m![1]!, skill.source, skill.files, skill.github) }));
const errors = results.flatMap(({ result }) => ("error" in result ? [result.error] : []));
diff --git a/server/skill-fetch.test.ts b/server/skill-fetch.test.ts
index a631ccaef7..50627ab010 100644
--- a/server/skill-fetch.test.ts
+++ b/server/skill-fetch.test.ts
@@ -1,6 +1,7 @@
-import { describe, expect, it, vi } from "vitest";
+import { afterEach, describe, expect, it, vi } from "vitest";
-import { fetchSkillFromSource, githubSkillLink, latestSkillCommit, parseSkillSource } from "./skill-fetch.ts";
+import { githubToken, provideGithubSignIn } from "./github/token.ts";
+import { fetchSkillFromSource, githubSkillLink, latestSkillCommit, parseSkillSource, skillImportToken } from "./skill-fetch.ts";
import { SKILL_FOLDER_LIMITS } from "./skill-folder.ts";
import { fakeGitHub, type FakeRepoEntry } from "./testing/fake-github.ts";
@@ -24,6 +25,23 @@ const ok = <T,>(result: { skills: T[] } | { error: string }) => {
return result.skills;
};
+const SIGNED_IN = "gho_syntheticSkillImportToken";
+const OWNER_SIGN_IN = "gho_ownerSignInMustNotLeak";
+
+afterEach(() => provideGithubSignIn(null));
+
+function recordingFetch(inner: typeof fetch) {
+ const calls: Array<{ url: string; headers: Headers; redirect: RequestInit["redirect"] }> = [];
+ const fetcher: typeof fetch = async (input, init) => {
+ calls.push({ url: String(input), headers: new Headers(init?.headers), redirect: init?.redirect });
+ return inner(input, init);
+ };
+ return { fetch: fetcher, calls };
+}
+
+const apiCalls = <T extends { url: string }>(calls: readonly T[]) => calls.filter((call) => call.url.startsWith("https://api.github.com/"));
+const rawCalls = <T extends { url: string }>(calls: readonly T[]) => calls.filter((call) => call.url.startsWith("https://raw.githubusercontent.com/"));
+
describe("importing a skill's whole folder", () => {
it.each([
"https://github.com/a/b/tree/feature%2Fpdf/skills/pdf",
@@ -74,6 +92,89 @@ describe("importing a skill's whole folder", () => {
expect(github.requests.filter((url) => url.includes("/git/trees/"))).toHaveLength(1);
});
+ it("sends the connected GitHub sign-in on every API request and keeps raw downloads anonymous", async () => {
+ const github = fakeGitHub({ "a/b": PDF_SKILL });
+ const recorded = recordingFetch(github.fetch);
+ const [skill] = ok(await fetchSkillFromSource("https://github.com/a/b/tree/main/skills/pdf", recorded.fetch, undefined, async () => SIGNED_IN));
+ expect(skill!.github?.commit).toBe(github.commitOf("a/b"));
+ const api = apiCalls(recorded.calls);
+ const raw = rawCalls(recorded.calls);
+ expect(api.some((call) => call.url.includes("/commits/"))).toBe(true);
+ expect(api.some((call) => call.url.includes("/contents/"))).toBe(true);
+ expect(api.some((call) => call.url.includes("/git/trees/"))).toBe(true);
+ expect(recorded.calls.every((call) => !call.url.includes(SIGNED_IN))).toBe(true);
+ expect(api.every((call) => call.headers.get("authorization") === `Bearer ${SIGNED_IN}`)).toBe(true);
+ expect(api.find((call) => call.url.includes("/commits/"))?.headers.get("accept")).toBe("application/vnd.github.sha");
+ expect(api.every((call) => call.redirect === "error")).toBe(true);
+ expect(raw.length).toBeGreaterThan(0);
+ expect(raw.every((call) => call.headers.get("authorization") === null && call.redirect === "error")).toBe(true);
+ });
+
+ it("stays anonymous when the sign-in getter has no token", async () => {
+ const github = fakeGitHub({ "a/b": PDF_SKILL });
+ const recorded = recordingFetch(github.fetch);
+ const [skill] = ok(await fetchSkillFromSource("https://github.com/a/b/tree/main/skills/pdf", recorded.fetch, undefined, async () => null));
+ expect(skill!.files.length).toBeGreaterThan(0);
+ const api = apiCalls(recorded.calls);
+ const raw = rawCalls(recorded.calls);
+ expect(api.length).toBeGreaterThan(0);
+ expect(raw.length).toBeGreaterThan(0);
+ expect(recorded.calls.every((call) => call.headers.get("authorization") === null)).toBe(true);
+ expect(api.every((call) => call.redirect === undefined)).toBe(true);
+ expect(raw.every((call) => call.redirect === "error")).toBe(true);
+ });
+
+ it("stays anonymous for an explicit empty sign-in even when the server holds an owner token", async () => {
+ const asked: Array<string | null | undefined> = [];
+ provideGithubSignIn({
+ token: async (audience) => { asked.push(audience); return OWNER_SIGN_IN; },
+ reportAuthFailure: () => {},
+ signedIn: () => true,
+ });
+ const github = fakeGitHub({ "a/b": PDF_SKILL });
+ const recorded = recordingFetch(github.fetch);
+ ok(await fetchSkillFromSource("a/b", recorded.fetch, undefined, async () => null));
+ expect(recorded.calls.every((call) => call.headers.get("authorization") === null)).toBe(true);
+ expect(JSON.stringify(recorded.calls)).not.toContain(OWNER_SIGN_IN);
+ expect(asked).toEqual([]);
+ });
+
+ it("does not read the owner sign-in when the audience was refused", async () => {
+ const asked: Array<string | null | undefined> = [];
+ provideGithubSignIn({
+ token: async (audience) => {
+ asked.push(audience);
+ return audience === undefined || audience === null || audience === "owner" ? OWNER_SIGN_IN : null;
+ },
+ reportAuthFailure: () => {},
+ signedIn: () => true,
+ });
+ expect(await githubToken(null)).toBe(OWNER_SIGN_IN);
+ asked.length = 0;
+ expect(await skillImportToken(null)).toBeNull();
+ expect(asked).toEqual([]);
+ const github = fakeGitHub({ "a/b": PDF_SKILL });
+ const recorded = recordingFetch(github.fetch);
+ ok(await fetchSkillFromSource("a/b", recorded.fetch, undefined, () => skillImportToken(null)));
+ expect(recorded.calls.every((call) => call.headers.get("authorization") === null)).toBe(true);
+ expect(JSON.stringify(recorded.calls)).not.toContain(OWNER_SIGN_IN);
+ expect(asked).toEqual([]);
+ });
+
+ it("uses the server sign-in when the caller does not pass a getter", async () => {
+ provideGithubSignIn({ token: async () => SIGNED_IN, reportAuthFailure: () => {}, signedIn: () => true });
+ const github = fakeGitHub({ "a/b": PDF_SKILL });
+ const recorded = recordingFetch(github.fetch);
+ ok(await fetchSkillFromSource("a/b", recorded.fetch));
+ const api = apiCalls(recorded.calls);
+ const raw = rawCalls(recorded.calls);
+ expect(api.length).toBeGreaterThan(0);
+ expect(raw.length).toBeGreaterThan(0);
+ expect(api.every((call) => call.headers.get("authorization") === `Bearer ${SIGNED_IN}`)).toBe(true);
+ expect(raw.every((call) => call.headers.get("authorization") === null)).toBe(true);
+ expect(recorded.calls.every((call) => !call.url.includes(SIGNED_IN))).toBe(true);
+ });
+
it("records HEAD for a link that names no branch, so updates follow the default branch", async () => {
const github = fakeGitHub({ "a/b": { "SKILL.md": SKILL("root-skill"), "notes/a.md": "a" } });
const [skill] = ok(await fetchSkillFromSource("a/b", github.fetch));
@@ -175,7 +276,7 @@ describe("importing a skill's whole folder", () => {
skipped: [{ path: "", reason: "unlisted" }],
});
expect(await fetchSkillFromSource("https://github.com/a/b/tree/main/skills/pdf", github.fetch))
- .toEqual({ error: expect.stringContaining("limit for requests without sign-in") });
+ .toEqual({ error: expect.stringContaining("API rate limit was reached") });
});
it.each([
@@ -196,7 +297,11 @@ describe("importing a skill's whole folder", () => {
it("finds the commit a skill's link names now, and the link that imports it again", async () => {
const github = fakeGitHub({ "a/b": PDF_SKILL });
const [skill] = ok(await fetchSkillFromSource("https://github.com/a/b/tree/main/skills/pdf", github.fetch));
- expect(await latestSkillCommit(skill!.github!, github.fetch)).toBe(github.commitOf("a/b"));
+ const recorded = recordingFetch(github.fetch);
+ expect(await latestSkillCommit(skill!.github!, recorded.fetch, async () => SIGNED_IN)).toBe(github.commitOf("a/b"));
+ const lookups = recorded.calls.filter((call) => call.url.includes("/commits/"));
+ expect(lookups.length).toBeGreaterThan(0);
+ expect(lookups.every((call) => call.headers.get("authorization") === `Bearer ${SIGNED_IN}` && call.headers.get("accept") === "application/vnd.github.sha")).toBe(true);
const again = ok(await fetchSkillFromSource(githubSkillLink(skill!.github!), github.fetch));
expect(again[0]!.github).toEqual(skill!.github);
expect(await latestSkillCommit({ ...skill!.github!, repo: "gone" }, github.fetch)).toEqual({ error: expect.stringContaining("404") });
@@ -296,6 +401,48 @@ describe("skill fetch host pinning", () => {
expect(vi.mocked(fetcher).mock.calls.map(([input]) => String(input))).not.toContain(offhost);
});
+ it("does not follow an API redirect when the request carries a sign-in", async () => {
+ const github = fakeGitHub({ "a/b": PDF_SKILL });
+ const offhost = "https://evil.example.com/repos/a/b/commits/HEAD";
+ const fetcher = vi.fn(async (input: string | URL | Request, init?: RequestInit) => {
+ const url = String(input);
+ if (url === offhost) return new Response("relocated");
+ if (url.startsWith("https://api.github.com/") && url.includes("/commits/")) {
+ // Like the platform fetch: redirect "error" refuses, anything else follows the 302 off-origin.
+ if (init?.redirect === "error") throw new TypeError("fetch failed");
+ return fetcher(offhost, init);
+ }
+ return github.fetch(input, init);
+ }) as typeof fetch;
+ const result = await fetchSkillFromSource("a/b", fetcher, undefined, async () => SIGNED_IN);
+ const urls = vi.mocked(fetcher).mock.calls.map(([input]) => String(input));
+ expect(urls.some((url) => url.startsWith("https://api.github.com/") && url.includes("/commits/"))).toBe(true);
+ expect(urls).not.toContain(offhost);
+ expect(result).toEqual({ error: expect.any(String) });
+ expect(JSON.stringify(result)).not.toContain(SIGNED_IN);
+ const api = vi.mocked(fetcher).mock.calls.find(([input]) => String(input).includes("/commits/"));
+ expect(new Headers(api?.[1]?.headers).get("authorization")).toBe(`Bearer ${SIGNED_IN}`);
+ expect(api?.[1]?.redirect).toBe("error");
+ });
+
+ it("leaves a sign-in that cannot be a header out of the error", async () => {
+ const credential = "gho_not\r\na header";
+ const fetcher = vi.fn(async () => new Response("no", { status: 401 })) as typeof fetch;
+ const result = await fetchSkillFromSource("owner/repo", fetcher, undefined, async () => credential);
+ expect(result).toEqual({ error: expect.stringContaining("401") });
+ expect(JSON.stringify(result)).not.toContain("gho_not");
+ expect(new Headers(vi.mocked(fetcher).mock.calls[0]?.[1]?.headers).get("authorization")).toBeNull();
+ });
+
+ it("reports one refused API request and leaves the credential out of the error", async () => {
+ const fetcher = vi.fn(async () => new Response("no", { status: 401 })) as typeof fetch;
+ const result = await fetchSkillFromSource("owner/repo", fetcher, undefined, async () => SIGNED_IN);
+ expect(fetcher).toHaveBeenCalledTimes(1);
+ expect(result).toEqual({ error: expect.stringContaining("401") });
+ expect(JSON.stringify(result)).not.toContain(SIGNED_IN);
+ expect(new Headers(vi.mocked(fetcher).mock.calls[0]?.[1]?.headers).get("authorization")).toBe(`Bearer ${SIGNED_IN}`);
+ });
+
it("downloads only from the pinned raw host, with redirects refused", async () => {
const github = fakeGitHub({ "a/b": PDF_SKILL });
const fetcher = vi.fn(github.fetch) as typeof fetch;
diff --git a/server/skill-fetch.ts b/server/skill-fetch.ts
index bbf952f73f..626fd85aa8 100644
--- a/server/skill-fetch.ts
+++ b/server/skill-fetch.ts
@@ -3,6 +3,7 @@ import { z } from "zod";
import type { GitHubSkillOrigin, SkippedSkillFile } from "../shared/skill-import.ts";
import { SKILL_FILE_MAX_BYTES } from "../shared/skill-md.ts";
+import { githubToken } from "./github/token.ts";
import { planSkillFolder, SKILL_FOLDER_LIMITS, type FolderEntry, type SkillFolderFile } from "./skill-folder.ts";
const API = "https://api.github.com";
@@ -15,20 +16,61 @@ const PARALLEL_DOWNLOADS = 4;
class ImportLimitError extends Error {}
class GitHubApiError extends Error {}
+/** A refused audience (`null`) stays anonymous. `githubToken(null)` is the server sign-in off a Team Cloud. */
+export function skillImportToken(audience?: string | null): Promise<string | null> {
+ return audience === null ? Promise.resolve(null) : githubToken(audience);
+}
+
+function requestHref(input: Parameters<typeof fetch>[0]): string {
+ if (typeof input === "string") return input;
+ if (input instanceof URL) return input.href;
+ return input.url;
+}
+
+function isGitHubApiRequest(input: Parameters<typeof fetch>[0]): boolean {
+ try {
+ return new URL(requestHref(input)).origin === API;
+ } catch {
+ return false;
+ }
+}
+
+function withBearer(input: Parameters<typeof fetch>[0], init: RequestInit | undefined, credential: string): Headers | null {
+ // Headers.set quotes an illegal value in its TypeError, which would return the sign-in in the import error.
+ if (!/^[A-Za-z0-9_]+$/.test(credential)) return null;
+ const headers = new Headers(input instanceof Request ? input.headers : undefined);
+ if (init?.headers) new Headers(init.headers).forEach((value, key) => headers.set(key, value));
+ headers.set("authorization", `Bearer ${credential}`);
+ return headers;
+}
+
// One budget for the whole import, enforced while reading the stream.
-function boundedImportFetch(fetcher: typeof fetch, cancel?: AbortSignal): typeof fetch {
+function boundedImportFetch(
+ fetcher: typeof fetch,
+ cancel?: AbortSignal,
+ authorization: () => Promise<string | null> = () => skillImportToken(),
+): typeof fetch {
let apiRequests = 0;
let downloads = 0;
let bytes = 0;
const timeout = AbortSignal.timeout(IMPORT_LIMITS.ms);
const signal = cancel ? AbortSignal.any([timeout, cancel]) : timeout;
return async (input, init) => {
- const listing = String(input).startsWith(`${API}/`);
- if (listing ? ++apiRequests > IMPORT_LIMITS.apiRequests : ++downloads > IMPORT_LIMITS.downloads) {
+ const api = isGitHubApiRequest(input);
+ if (api ? ++apiRequests > IMPORT_LIMITS.apiRequests : ++downloads > IMPORT_LIMITS.downloads) {
throw new ImportLimitError("Import request limit reached — paste a specific skill folder instead.");
}
signal.throwIfAborted();
- const response = await fetcher(input, { ...init, signal });
+ const sent: RequestInit = { ...init, signal };
+ if (api) {
+ const credential = await authorization();
+ const headers = credential ? withBearer(input, init, credential) : null;
+ if (headers) {
+ sent.headers = headers;
+ sent.redirect = "error";
+ }
+ }
+ const response = await fetcher(input, sent);
if (!response.ok) {
await response.body?.cancel().catch(() => {});
return response;
@@ -43,7 +85,7 @@ function boundedImportFetch(fetcher: typeof fetch, cancel?: AbortSignal): typeof
if (chunk.done) break;
size += chunk.value.byteLength;
bytes += chunk.value.byteLength;
- if (size > (listing ? LISTING_MAX_BYTES : SKILL_FOLDER_LIMITS.fileBytes) || bytes > IMPORT_LIMITS.bytes) {
+ if (size > (api ? LISTING_MAX_BYTES : SKILL_FOLDER_LIMITS.fileBytes) || bytes > IMPORT_LIMITS.bytes) {
throw new ImportLimitError("Import size limit reached — paste a smaller skill folder instead.");
}
chunks.push(chunk.value);
@@ -159,7 +201,7 @@ function encodePath(path: string): string {
function apiError(response: Response, url: string): GitHubApiError {
const limited = response.status === 429 || (response.status === 403 && response.headers.get("x-ratelimit-remaining") === "0");
return new GitHubApiError(limited
- ? "GitHub's limit for requests without sign-in was reached — try again within the hour"
+ ? "GitHub's API rate limit was reached — try again later"
: `GitHub API ${response.status} for ${url}`);
}
@@ -359,10 +401,11 @@ export async function fetchSkillFromSource(
input: string,
fetcher: typeof fetch = fetch,
cancel?: AbortSignal,
+ authorization?: () => Promise<string | null>,
): Promise<{ skills: FetchedSkill[] } | { error: string }> {
const parsed = parseSkillSource(input);
if ("error" in parsed) return parsed;
- fetcher = boundedImportFetch(fetcher, cancel);
+ fetcher = boundedImportFetch(fetcher, cancel, authorization);
try {
return { skills: await fetchSkills(parsed, fetcher) };
} catch (error) {
@@ -377,9 +420,13 @@ export async function fetchSkillFromSource(
}
/** The commit a GitHub skill's link names now: newer than `origin.commit` means an update is available. */
-export async function latestSkillCommit(origin: GitHubSkillOrigin, fetcher: typeof fetch = fetch): Promise<string | { error: string }> {
+export async function latestSkillCommit(
+ origin: GitHubSkillOrigin,
+ fetcher: typeof fetch = fetch,
+ authorization?: () => Promise<string | null>,
+): Promise<string | { error: string }> {
try {
- return await resolveCommit(origin.owner, origin.repo, origin.ref, boundedImportFetch(fetcher));
+ return await resolveCommit(origin.owner, origin.repo, origin.ref, boundedImportFetch(fetcher, undefined, authorization));
} catch (error) {
return { error: error instanceof Error ? error.message : String(error) };
}
diff --git a/server/skill-request-card.test.ts b/server/skill-request-card.test.ts
index 8f41af7d4c..68dc66434f 100644
--- a/server/skill-request-card.test.ts
+++ b/server/skill-request-card.test.ts
@@ -64,4 +64,28 @@ describe("importedSkillRequest", () => {
expect(body).toEqual({ importError: expect.stringMatching(/^Could not import a skill from /) });
expect(calls).toBe(1);
});
+
+ it("forwards a sign-in getter onto GitHub API requests and leaves raw downloads anonymous", async () => {
+ const token = "gho_syntheticSkillImportToken";
+ const calls: Array<{ url: string; headers: Headers }> = [];
+ const fetcher: typeof fetch = async (input, init) => {
+ calls.push({ url: String(input), headers: new Headers(init?.headers) });
+ return github.fetch(input, init);
+ };
+ const body = await importedSkillRequest(
+ { action: "import", source: "https://github.com/acme/skills/tree/main/skills/pdf" },
+ fetcher,
+ undefined,
+ async () => token,
+ );
+ expect(body).toMatchObject({ action: "create", skill_md: SKILL("pdf") });
+ const api = calls.filter((call) => call.url.startsWith("https://api.github.com/"));
+ const raw = calls.filter((call) => call.url.startsWith("https://raw.githubusercontent.com/"));
+ expect(api.length).toBeGreaterThan(0);
+ expect(raw.length).toBeGreaterThan(0);
+ expect(api.every((call) => call.headers.get("authorization") === `Bearer ${token}`)).toBe(true);
+ expect(raw.every((call) => call.headers.get("authorization") === null)).toBe(true);
+ expect(JSON.stringify(body)).not.toContain(token);
+ expect(calls.every((call) => !call.url.includes(token))).toBe(true);
+ });
});
diff --git a/server/skill-request-card.ts b/server/skill-request-card.ts
index 3ad639c69b..e23dafa8a4 100644
--- a/server/skill-request-card.ts
+++ b/server/skill-request-card.ts
@@ -56,11 +56,16 @@ export function parseSkillManageReferences(value: unknown): SkillFile[] | { erro
* the person's computer) and turn it into a create request, so it gets the same card, scan and name checks as one the
* bot wrote. Only SKILL.md and its references/<topic>.md files come in; the card says what was left behind.
*/
-export async function importedSkillRequest<T extends Record<string, unknown>>(body: T, fetcher: typeof fetch = fetch, cancel?: AbortSignal): Promise<T | { importError: string }> {
+export async function importedSkillRequest<T extends Record<string, unknown>>(
+ body: T,
+ fetcher: typeof fetch = fetch,
+ cancel?: AbortSignal,
+ authorization?: () => Promise<string | null>,
+): Promise<T | { importError: string }> {
if (body.action !== "import") return body;
const source = typeof body.source === "string" ? body.source.trim() : "";
if (!source) return { importError: "skill_manage import needs source: owner/repo, a GitHub link to a skill folder or its SKILL.md, or a skills.sh link." };
- const fetched = await fetchSkillFromSource(source, fetcher, cancel);
+ const fetched = await fetchSkillFromSource(source, fetcher, cancel, authorization);
if ("error" in fetched) return { importError: `Could not import a skill from ${source}: ${fetched.error}` };
if (fetched.skills.length !== 1) {
const names = fetched.skills.map((skill) => skill.source.split("/").pop()).join(", ");