:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(agent-platform): add @posthog/github-app-request native tool (#72054)
Tom Piccirello596a0f770184
diff --git a/products/agent_platform/services/agent-tools/src/registry.ts b/products/agent_platform/services/agent-tools/src/registry.tsindex b2d6402b3dae..125143abf8e3 100644--- a/products/agent_platform/services/agent-tools/src/registry.ts+++ b/products/agent_platform/services/agent-tools/src/registry.ts@@ -11,6 +11,7 @@import { defineNativeTool, NativeTool, NativeToolSchema, Type } from '@posthog/agent-shared'+import { githubAppRequestV1 } from './tools/github-app-request.v1'import { httpRequestV1 } from './tools/http-request.v1'import { identityConnectV1 } from './tools/identity-connect.v1'import { identityFetchV1 } from './tools/identity-fetch.v1'@@ -155,6 +156,7 @@ export const ALL_TOOLS: NativeTool[] = [slackReadThreadV1,slackReactV1,httpRequestV1,+ githubAppRequestV1,identityConnectV1,identityFetchV1,webSearchV1,diff --git a/products/agent_platform/services/agent-tools/src/tools/github-app-request.v1.test.ts b/products/agent_platform/services/agent-tools/src/tools/github-app-request.v1.test.tsnew file mode 100644index 000000000000..f1c25460ec99--- /dev/null+++ b/products/agent_platform/services/agent-tools/src/tools/github-app-request.v1.test.ts@@ -0,0 +1,452 @@+import { createVerify, generateKeyPairSync } from 'node:crypto'++import type { HttpFetcher } from '@posthog/agent-shared'++import { makeCtx } from '../test-helpers'+import { githubAppRequestV1 } from './github-app-request.v1'++const { privateKey, publicKey } = generateKeyPairSync('rsa', { modulusLength: 2048 })+// GitHub ships App keys as PKCS#1 ("BEGIN RSA PRIVATE KEY") PEM.+const PEM = privateKey.export({ type: 'pkcs1', format: 'pem' }) as string+// A second, unrelated key — stands in for an attacker's self-generated PEM.+const OTHER_PEM = generateKeyPairSync('rsa', { modulusLength: 2048 }).privateKey.export({+ type: 'pkcs1',+ format: 'pem',+}) as string++/** Unique app id per test — the tool caches minted tokens per (app, installation). */+let appIdCounter = 9000+function nextAppId(): string {+ return String(appIdCounter++)+}++interface RecordedCall {+ url: string+ init?: RequestInit+}++function fakeResponse(opts: {+ status?: number+ text?: string+ contentType?: string+ headers?: Record<string, string>+}): Response {+ const status = opts.status ?? 200+ const text = opts.text ?? ''+ const headerEntries: Array<[string, string]> = Object.entries(opts.headers ?? {})+ if (opts.contentType !== undefined) {+ headerEntries.push(['content-type', opts.contentType])+ }+ return {+ ok: status >= 200 && status < 300,+ status,+ text: async () => text,+ json: async () => JSON.parse(text),+ headers: {+ get: (k: string) => headerEntries.find(([h]) => h.toLowerCase() === k.toLowerCase())?.[1] ?? null,+ entries: () => headerEntries[Symbol.iterator](),+ },+ } as unknown as Response+}++/**+ * Routed fake of api.github.com: answers the App-auth endpoints (installation+ * lookup, token mint) and returns `apiResponse` for everything else. Records+ * every call so tests can assert which credential went where.+ */+function fakeGithub(opts?: {+ installationId?: number+ tokenExpiresInSeconds?: number+ mintStatus?: number+ apiResponse?: Response+}): { http: HttpFetcher; calls: RecordedCall[]; mintedTokens: string[] } {+ const installationId = opts?.installationId ?? 42+ const calls: RecordedCall[] = []+ const mintedTokens: string[] = []+ const http: HttpFetcher = {+ fetch: async (input, init) => {+ const url = typeof input === 'string' ? input : input instanceof URL ? input.toString() : ''+ calls.push({ url, init })+ const mintMatch = url.match(/^https:\/\/api\.github\.com\/app\/installations\/(\d+)\/access_tokens$/)+ if (mintMatch) {+ if (opts?.mintStatus !== undefined && opts.mintStatus >= 400) {+ return fakeResponse({ status: opts.mintStatus, text: '{"message":"nope"}' })+ }+ const token = `ghs_${mintMatch[1]}_${mintedTokens.length}`+ mintedTokens.push(token)+ const expiresAt = new Date(Date.now() + (opts?.tokenExpiresInSeconds ?? 3600) * 1000).toISOString()+ return fakeResponse({+ status: 201,+ text: JSON.stringify({ token, expires_at: expiresAt }),+ contentType: 'application/json',+ })+ }+ if (/^https:\/\/api\.github\.com\/repos\/[^/]+\/[^/]+\/installation$/.test(url)) {+ return fakeResponse({+ status: 200,+ text: JSON.stringify({ id: installationId }),+ contentType: 'application/json',+ })+ }+ return (+ opts?.apiResponse ?? fakeResponse({ status: 200, text: '{"ok":true}', contentType: 'application/json' })+ )+ },+ }+ return { http, calls, mintedTokens }+}++function makeGithubCtx(+ http: HttpFetcher,+ appId: string,+ pem: string = PEM,+ allowedOwners?: string+): ReturnType<typeof makeCtx> {+ return makeCtx({+ http,+ secret: (name: string) => {+ if (name === 'GITHUB_APP_ID') {+ return appId+ }+ if (name === 'GITHUB_APP_PRIVATE_KEY') {+ return pem+ }+ if (name === 'GITHUB_APP_ALLOWED_OWNERS') {+ return allowedOwners+ }+ return undefined+ },+ })+}++/** Parse the JSON body recorded on a captured mint call (`/access_tokens`). */+function mintBody(calls: RecordedCall[]): unknown {+ const mint = calls.find((c) => c.url.endsWith('/access_tokens'))+ const raw = mint?.init?.body+ return typeof raw === 'string' ? JSON.parse(raw) : raw+}++function bearerOf(call: RecordedCall): string {+ const headers = (call.init?.headers ?? {}) as Record<string, string>+ const auth = Object.entries(headers).find(([k]) => k.toLowerCase() === 'authorization')?.[1] ?? ''+ return auth.replace(/^Bearer /, '')+}++function decodeJwtClaims(jwt: string): Record<string, unknown> {+ const [, payload] = jwt.split('.')+ return JSON.parse(Buffer.from(payload, 'base64url').toString()) as Record<string, unknown>+}++describe('@posthog/github-app-request', () => {+ describe('App auth flow', () => {+ it('mints an installation token with a signed App JWT, then calls the API with the installation token', async () => {+ const appId = nextAppId()+ const { http, calls, mintedTokens } = fakeGithub()+ const out = await githubAppRequestV1.run(+ { path: '/repos/PostHog/posthog/pulls/7/files', installation_id: 42 },+ makeGithubCtx(http, appId)+ )++ const mintCall = calls.find((c) => c.url.endsWith('/access_tokens'))+ expect(mintCall).not.toBeUndefined()+ expect(mintCall?.init?.method).toBe('POST')++ // The mint call authenticates with a valid RS256 App JWT.+ const jwt = bearerOf(mintCall as RecordedCall)+ const [header, payload, signature] = jwt.split('.')+ const verifier = createVerify('RSA-SHA256').update(`${header}.${payload}`)+ expect(verifier.verify(publicKey, signature, 'base64url')).toBe(true)+ expect(JSON.parse(Buffer.from(header, 'base64url').toString())).toEqual({ alg: 'RS256', typ: 'JWT' })+ const claims = decodeJwtClaims(jwt)+ expect(claims.iss).toBe(appId)+ const nowSeconds = Math.floor(Date.now() / 1000)+ expect(claims.iat as number).toBeLessThanOrEqual(nowSeconds)+ // GitHub rejects App JWTs whose exp is more than 10 minutes out.+ expect(claims.exp as number).toBeLessThanOrEqual(nowSeconds + 600)+ expect(claims.exp as number).toBeGreaterThan(nowSeconds)++ // The API call itself carries the installation token, not the JWT.+ const apiCall = calls.find((c) => c.url.includes('/pulls/7/files'))+ expect(apiCall).not.toBeUndefined()+ expect(bearerOf(apiCall as RecordedCall)).toBe(mintedTokens[0])+ const apiHeaders = (apiCall?.init?.headers ?? {}) as Record<string, string>+ expect(apiHeaders['Accept']).toBe('application/vnd.github+json')+ expect(apiHeaders['X-GitHub-Api-Version']).toBe('2022-11-28')++ expect(out.status).toBe(200)+ expect(out.body).toBe('{"ok":true}')+ })++ it('never returns the installation token, JWT, or key material to the model', async () => {+ const appId = nextAppId()+ const { http, mintedTokens } = fakeGithub()+ const out = await githubAppRequestV1.run(+ { path: '/repos/PostHog/posthog/pulls/7', installation_id: 42 },+ makeGithubCtx(http, appId)+ )+ const serialized = JSON.stringify(out)+ expect(serialized).not.toContain(mintedTokens[0])+ expect(serialized).not.toContain('PRIVATE KEY')+ expect(serialized).not.toContain('eyJhbGciOiJSUzI1NiI')+ })++ it('reuses a cached installation token across calls instead of re-minting', async () => {+ const appId = nextAppId()+ const { http, calls } = fakeGithub()+ const ctx = makeGithubCtx(http, appId)+ await githubAppRequestV1.run({ path: '/repos/a/b/issues', installation_id: 42 }, ctx)+ await githubAppRequestV1.run({ path: '/repos/a/b/pulls', installation_id: 42 }, ctx)+ expect(calls.filter((c) => c.url.endsWith('/access_tokens'))).toHaveLength(1)+ })++ it('does not serve a cached token to a caller holding a different private key', async () => {+ // Cross-tenant guard: the cache key binds to a fingerprint of the+ // key, so an agent that declares the victim's public App id ++ // installation id but a different (forged) key gets a cache MISS and+ // mints with its own key — it never rides the victim's token.+ const appId = nextAppId()+ const { http, calls } = fakeGithub()+ await githubAppRequestV1.run(+ { path: '/repos/a/b/issues', installation_id: 42 },+ makeGithubCtx(http, appId, PEM)+ )+ await githubAppRequestV1.run(+ { path: '/repos/a/b/issues', installation_id: 42 },+ makeGithubCtx(http, appId, OTHER_PEM)+ )+ // Two distinct keys → two mints, not a shared cache hit.+ expect(calls.filter((c) => c.url.endsWith('/access_tokens'))).toHaveLength(2)+ })++ it('rejects a host-bound private-key secret (would let http-request exfiltrate the key)', async () => {+ const appId = nextAppId()+ const { http } = fakeGithub()+ const ctx = makeCtx({+ http,+ secret: (name: string) =>+ name === 'GITHUB_APP_ID' ? appId : name === 'GITHUB_APP_PRIVATE_KEY' ? PEM : undefined,+ secretAllowedHosts: (name: string) =>+ name === 'GITHUB_APP_PRIVATE_KEY' ? ['api.github.com'] : undefined,+ })+ await expect(+ githubAppRequestV1.run({ path: '/repos/a/b/pulls', installation_id: 42 }, ctx)+ ).rejects.toThrow(/github_app_private_key_host_bound/)+ })++ it('re-mints when the cached token is close to expiry', async () => {+ const appId = nextAppId()+ const { http, calls } = fakeGithub({ tokenExpiresInSeconds: 60 })+ const ctx = makeGithubCtx(http, appId)+ await githubAppRequestV1.run({ path: '/repos/a/b/issues', installation_id: 42 }, ctx)+ await githubAppRequestV1.run({ path: '/repos/a/b/pulls', installation_id: 42 }, ctx)+ expect(calls.filter((c) => c.url.endsWith('/access_tokens'))).toHaveLength(2)+ })++ it('resolves the installation from the repo in the path when installation_id is omitted', async () => {+ const appId = nextAppId()+ const { http, calls, mintedTokens } = fakeGithub({ installationId: 77 })+ const out = await githubAppRequestV1.run(+ { path: '/repos/PostHog/posthog/pulls/7/files' },+ makeGithubCtx(http, appId)+ )+ const lookup = calls.find((c) => c.url.endsWith('/repos/PostHog/posthog/installation'))+ expect(lookup).not.toBeUndefined()+ expect(calls.some((c) => c.url.includes('/app/installations/77/access_tokens'))).toBe(true)+ const apiCall = calls.find((c) => c.url.includes('/pulls/7/files'))+ expect(bearerOf(apiCall as RecordedCall)).toBe(mintedTokens[0])+ expect(out.status).toBe(200)+ })++ it('requires installation_id for paths that are not repo-scoped', async () => {+ const appId = nextAppId()+ const { http } = fakeGithub()+ await expect(+ githubAppRequestV1.run({ path: '/orgs/PostHog/repos' }, makeGithubCtx(http, appId))+ ).rejects.toThrow(/github_app_installation_id_required/)+ })++ it('accepts a private key pasted with literal \\n escapes', async () => {+ const appId = nextAppId()+ const { http } = fakeGithub()+ const escapedPem = PEM.replace(/\n/g, '\\n')+ const out = await githubAppRequestV1.run(+ { path: '/repos/a/b/pulls', installation_id: 42 },+ makeGithubCtx(http, appId, escapedPem)+ )+ expect(out.status).toBe(200)+ })++ it('fails with a clear error when the App secrets are not set', async () => {+ const { http } = fakeGithub()+ await expect(+ githubAppRequestV1.run({ path: '/repos/a/b/pulls', installation_id: 42 }, makeCtx({ http }))+ ).rejects.toThrow(/github_app_secret_missing: GITHUB_APP_ID/)+ })++ it('surfaces the mint failure status when GitHub refuses the token exchange', async () => {+ const appId = nextAppId()+ const { http } = fakeGithub({ mintStatus: 401 })+ await expect(+ githubAppRequestV1.run({ path: '/repos/a/b/pulls', installation_id: 42 }, makeGithubCtx(http, appId))+ ).rejects.toThrow(/github_app_token_mint_failed: 401/)+ })+ })++ describe('blast-radius controls', () => {+ it('down-scopes the minted token to the repo in the path', async () => {+ const appId = nextAppId()+ const { http, calls } = fakeGithub()+ await githubAppRequestV1.run(+ { path: '/repos/PostHog/posthog/pulls/7/files', installation_id: 42 },+ makeGithubCtx(http, appId)+ )+ expect(mintBody(calls)).toEqual({ repositories: ['posthog'] })+ })++ it('mints an unscoped token for a non-repo path (nothing to scope to)', async () => {+ const appId = nextAppId()+ const { http, calls } = fakeGithub()+ await githubAppRequestV1.run(+ { path: '/orgs/PostHog/repos', installation_id: 42 },+ makeGithubCtx(http, appId)+ )+ expect(mintBody(calls)).toBeUndefined()+ })++ it('does not reuse a repo-scoped token for a different repo', async () => {+ // Same install + key, different repo → different scope → separate mint,+ // so the cache never hands repo B's caller a token scoped to repo A.+ const appId = nextAppId()+ const { http, calls } = fakeGithub()+ const ctx = makeGithubCtx(http, appId)+ await githubAppRequestV1.run({ path: '/repos/PostHog/posthog/pulls', installation_id: 42 }, ctx)+ await githubAppRequestV1.run({ path: '/repos/PostHog/other-repo/pulls', installation_id: 42 }, ctx)+ expect(calls.filter((c) => c.url.endsWith('/access_tokens'))).toHaveLength(2)+ })++ it('allows a request whose owner is in GITHUB_APP_ALLOWED_OWNERS', async () => {+ const appId = nextAppId()+ const { http } = fakeGithub()+ const out = await githubAppRequestV1.run(+ { path: '/repos/PostHog/posthog/pulls/7', installation_id: 42 },+ makeGithubCtx(http, appId, PEM, 'PostHog, AnotherOrg')+ )+ expect(out.status).toBe(200)+ })++ it('refuses a request whose owner is not in GITHUB_APP_ALLOWED_OWNERS, before minting', async () => {+ const appId = nextAppId()+ const { http, calls } = fakeGithub()+ await expect(+ githubAppRequestV1.run(+ { path: '/repos/evil-org/x/pulls/7', installation_id: 99 },+ makeGithubCtx(http, appId, PEM, 'PostHog')+ )+ ).rejects.toThrow(/github_app_owner_not_allowed/)+ expect(calls).toHaveLength(0)+ })++ it('fails closed when the allowlist is set but the path names no owner', async () => {+ const appId = nextAppId()+ const { http } = fakeGithub()+ await expect(+ githubAppRequestV1.run(+ { path: '/app/installations', installation_id: 42 },+ makeGithubCtx(http, appId, PEM, 'PostHog')+ )+ ).rejects.toThrow(/github_app_owner_unverifiable/)+ })+ })++ describe('request dispatch', () => {+ it.each(['//evil.com/pwn', 'https://evil.com/x', 'repos/missing-slash', ''])(+ 'refuses a path that does not resolve to api.github.com: %s',+ async (path) => {+ const appId = nextAppId()+ const { http, calls } = fakeGithub()+ await expect(+ githubAppRequestV1.run({ path, installation_id: 42 }, makeGithubCtx(http, appId))+ ).rejects.toThrow(/github_app_path_invalid/)+ expect(calls).toHaveLength(0)+ }+ )++ it('JSON-encodes an object body and sets Content-Type', async () => {+ const appId = nextAppId()+ const { http, calls } = fakeGithub()+ await githubAppRequestV1.run(+ {+ path: '/repos/a/b/pulls/7/reviews',+ method: 'POST',+ body: { event: 'APPROVE', body: 'lgtm' },+ installation_id: 42,+ },+ makeGithubCtx(http, appId)+ )+ const apiCall = calls.find((c) => c.url.includes('/reviews'))+ expect(apiCall?.init?.method).toBe('POST')+ expect(apiCall?.init?.body).toBe(JSON.stringify({ event: 'APPROVE', body: 'lgtm' }))+ const headers = (apiCall?.init?.headers ?? {}) as Record<string, string>+ expect(headers['Content-Type']).toContain('application/json')+ })++ it('rejects a body on a default-GET instead of silently dropping it', async () => {+ // The model that passes a body but forgets method must not get a+ // silent GET back — it would think its mutation ran.+ const appId = nextAppId()+ const { http } = fakeGithub()+ await expect(+ githubAppRequestV1.run(+ { path: '/repos/a/b/issues/1/labels', body: { labels: ['bug'] }, installation_id: 42 },+ makeGithubCtx(http, appId)+ )+ ).rejects.toThrow(/github_app_body_with_get/)+ })++ it('lets the caller override Accept (e.g. to fetch a PR as a unified diff)', async () => {+ const appId = nextAppId()+ const { http, calls } = fakeGithub({+ apiResponse: fakeResponse({ status: 200, text: 'diff --git a/x b/x', contentType: 'text/plain' }),+ })+ const out = await githubAppRequestV1.run(+ { path: '/repos/a/b/pulls/7', accept: 'application/vnd.github.v3.diff', installation_id: 42 },+ makeGithubCtx(http, appId)+ )+ const apiCall = calls.find((c) => c.url.includes('/pulls/7'))+ const headers = (apiCall?.init?.headers ?? {}) as Record<string, string>+ expect(headers['Accept']).toBe('application/vnd.github.v3.diff')+ expect(out.body).toBe('diff --git a/x b/x')+ })++ it('surfaces the link header so the model can paginate', async () => {+ const appId = nextAppId()+ const link = '<https://api.github.com/repos/a/b/pulls/7/files?page=2>; rel="next"'+ const { http } = fakeGithub({+ apiResponse: fakeResponse({+ status: 200,+ text: '[]',+ contentType: 'application/json',+ headers: { link },+ }),+ })+ const out = await githubAppRequestV1.run(+ { path: '/repos/a/b/pulls/7/files', installation_id: 42 },+ makeGithubCtx(http, appId)+ )+ expect(out.headers['link']).toBe(link)+ })++ it('truncates responses larger than max_response_bytes', async () => {+ const appId = nextAppId()+ const { http } = fakeGithub({+ apiResponse: fakeResponse({ status: 200, text: 'x'.repeat(500), contentType: 'text/plain' }),+ })+ const out = await githubAppRequestV1.run(+ { path: '/repos/a/b/pulls/7', installation_id: 42, max_response_bytes: 100 },+ makeGithubCtx(http, appId)+ )+ expect(out.truncated).toBe(true)+ expect(out.body).toHaveLength(100)+ })+ })+})diff --git a/products/agent_platform/services/agent-tools/src/tools/github-app-request.v1.ts b/products/agent_platform/services/agent-tools/src/tools/github-app-request.v1.tsnew file mode 100644index 000000000000..e9237e70a7a6--- /dev/null+++ b/products/agent_platform/services/agent-tools/src/tools/github-app-request.v1.ts@@ -0,0 +1,481 @@+/**+ * GitHub REST client that authenticates as a GitHub App.+ *+ * Why a dedicated tool instead of `@posthog/http-request`: App auth requires+ * SIGNING an RS256 JWT with the App's private key and exchanging it for a+ * short-lived installation access token — a computation over the secret, not a+ * `${NAME}` pass-through, so header substitution can't express it. And custom+ * tools can't do it either: their sandbox has no network and only sees secret+ * nonces. The runner is the one place that legitimately holds plaintext+ * secrets and egress, so the mint happens here and neither the private key,+ * the JWT, nor the installation token ever reaches the model's context.+ *+ * The agent declares two secrets (author-set via the env editor):+ * - `GITHUB_APP_ID` — the App's numeric id+ * - `GITHUB_APP_PRIVATE_KEY` — the App's PEM private key (PKCS#1 as GitHub+ * ships it, or PKCS#8; literal `\n` escapes from+ * copy-paste are tolerated)+ * Declare them as bare strings: this tool reads them directly, and the bare+ * form means `@posthog/http-request` refuses to substitute them anywhere.+ *+ * Egress is pinned to `https://api.github.com` — `path` is joined to that+ * base and re-validated after parsing, so a crafted path can't redirect the+ * minted token elsewhere. SSRF beyond that is smokescreen's job, same as+ * every proxy-bound tool.+ *+ * Blast-radius controls for an App installed across many orgs, where+ * `installation_id` and the repo path are model-controlled:+ * - Minted tokens are down-scoped to the repo in the path (`repositories`),+ * so a token only works on the resource being accessed.+ * - An optional `GITHUB_APP_ALLOWED_OWNERS` secret restricts which accounts+ * the tool may act on, refusing off-list requests before any mint.+ * The durable fix — binding the installation to the signature-verified trigger+ * payload instead of a model arg — is a platform change tracked separately.+ */++import { createHash, createPrivateKey, createSign, type KeyObject } from 'node:crypto'++import { defineNativeTool, type ToolContext, Type } from '@posthog/agent-shared'++import {+ ABSOLUTE_MAX_RESPONSE_BYTES,+ ABSOLUTE_MAX_TIMEOUT_MS,+ DEFAULT_MAX_RESPONSE_BYTES,+ DEFAULT_TIMEOUT_MS,+ fetchWithTimeout,+ pickHeaders,+ readCappedBody,+} from './http-shared'++const API_BASE = 'https://api.github.com'+const API_HOST = 'api.github.com'+const API_VERSION = '2022-11-28'+const DEFAULT_ACCEPT = 'application/vnd.github+json'+const ERR_PREFIX = 'github_app_request'++export const GITHUB_APP_ID_SECRET = 'GITHUB_APP_ID'+export const GITHUB_APP_PRIVATE_KEY_SECRET = 'GITHUB_APP_PRIVATE_KEY'+/** Optional comma/space-separated list of GitHub account logins (orgs or users)+ * the tool may act on. When set, a request whose path targets any other owner+ * is refused before a token is minted — the durable guard for an App installed+ * across many orgs, where installation_id and the repo path are otherwise+ * model-controlled. Unset = no restriction. */+export const GITHUB_APP_ALLOWED_OWNERS_SECRET = 'GITHUB_APP_ALLOWED_OWNERS'++/** GitHub rejects App JWTs whose exp is more than 10 minutes out; stay well under. */+const JWT_TTL_SECONDS = 540+/** Backdate iat to absorb clock drift between us and GitHub (their documented recommendation). */+const JWT_CLOCK_DRIFT_SECONDS = 60++/** Response headers worth returning to the model — includes `link` for pagination. */+const HEADER_ALLOWLIST = new Set([+ 'content-type',+ 'link',+ 'retry-after',+ 'x-ratelimit-remaining',+ 'x-ratelimit-reset',+ 'date',+])++/** Re-mint when a cached token has less than this long left — installation+ * tokens live 1h and a review session can outlast the tail of one. */+const TOKEN_REFRESH_MARGIN_MS = 5 * 60 * 1000+const TOKEN_CACHE_MAX_ENTRIES = 200++/**+ * Process-local mint cache. This module is shared across every session a+ * worker runs concurrently (different teams included), so the key MUST bind+ * the entry to proof of key possession, not just the public (app id,+ * installation id) pair — otherwise any agent declaring a victim's public App+ * id plus any parseable PEM could read a cached token it never had the key to+ * mint. The key fingerprint (a hash of the private key, never the key itself)+ * closes that: a different key yields a different cache slot, so a forged key+ * falls through to a real mint that GitHub rejects. Bounded and expiring —+ * a latency/rate-limit optimization, not a store.+ */+const tokenCache = new Map<string, { token: string; expiresAtMs: number }>()++interface AppIdentity {+ appId: string+ /** Normalized PEM — kept as a string so the fast path never has to parse it. */+ pem: string+ /** Opaque hash of the private key, safe to use in the cache key and to log. */+ keyFingerprint: string+}++/**+ * Read the App id + private key from the agent's secrets WITHOUT parsing the+ * key (cheap enough to run on every call, including cache hits). Refuses a+ * host-bound private-key secret: declaring `GITHUB_APP_PRIVATE_KEY` with+ * `allowed_hosts` would let `@posthog/http-request` substitute the raw signing+ * key into an outbound request, so the safety property the tool relies on is+ * enforced here rather than left to a doc convention.+ */+function resolveAppIdentity(ctx: ToolContext): AppIdentity {+ const appId = ctx.secret(GITHUB_APP_ID_SECRET)+ if (!appId) {+ throw new Error(`github_app_secret_missing: ${GITHUB_APP_ID_SECRET}`)+ }+ if (Array.isArray(ctx.secretAllowedHosts(GITHUB_APP_PRIVATE_KEY_SECRET))) {+ throw new Error(+ `github_app_private_key_host_bound: declare ${GITHUB_APP_PRIVATE_KEY_SECRET} as a bare secret, not with allowed_hosts — a signing key must never be sendable to a host`+ )+ }+ const pem = ctx.secret(GITHUB_APP_PRIVATE_KEY_SECRET)+ if (!pem) {+ throw new Error(`github_app_secret_missing: ${GITHUB_APP_PRIVATE_KEY_SECRET}`)+ }+ // Keys pasted into single-line env forms commonly arrive with literal \n.+ const normalized = pem.includes('\\n') ? pem.split('\\n').join('\n') : pem+ return {+ appId: appId.trim(),+ pem: normalized,+ keyFingerprint: createHash('sha256').update(normalized).digest('hex'),+ }+}++function parsePrivateKey(pem: string): KeyObject {+ try {+ return createPrivateKey(pem)+ } catch {+ // Never echo key material back — not even in the parse error.+ throw new Error(`github_app_invalid_private_key: ${GITHUB_APP_PRIVATE_KEY_SECRET} is not a parseable PEM key`)+ }+}++function base64UrlJson(value: unknown): string {+ return Buffer.from(JSON.stringify(value)).toString('base64url')+}++function mintAppJwt(appId: string, privateKey: KeyObject): string {+ const nowSeconds = Math.floor(Date.now() / 1000)+ const signingInput = `${base64UrlJson({ alg: 'RS256', typ: 'JWT' })}.${base64UrlJson({+ iat: nowSeconds - JWT_CLOCK_DRIFT_SECONDS,+ exp: nowSeconds + JWT_TTL_SECONDS,+ iss: appId,+ })}`+ const signature = createSign('RSA-SHA256').update(signingInput).sign(privateKey, 'base64url')+ return `${signingInput}.${signature}`+}++function appAuthHeaders(jwt: string): Record<string, string> {+ return { Authorization: `Bearer ${jwt}`, Accept: DEFAULT_ACCEPT, 'X-GitHub-Api-Version': API_VERSION }+}++interface RepoRef {+ owner: string+ repo: string+}++/** Parse `/repos/{owner}/{repo}` from a request path; null for non-repo paths. */+function parseRepo(pathname: string): RepoRef | null {+ const m = pathname.match(/^\/repos\/([^/]+)\/([^/]+)/)+ return m ? { owner: m[1], repo: m[2] } : null+}++/** The GitHub account (org or user) a path acts on, for the owner allowlist.+ * Covers the model-facing surfaces: /repos/{owner}/…, /orgs/{owner}…, /users/{owner}…. */+function parseOwner(pathname: string): string | null {+ const m = pathname.match(/^\/(?:repos|orgs|users)\/([^/]+)/)+ return m ? m[1] : null+}++/**+ * Enforce the optional owner allowlist against the model's requested path.+ * When set, a request must target one of the listed accounts; a path that+ * names no owner is refused too (fail closed — the author opted into a+ * restriction, so an uncheckable request can't slip past it).+ */+function enforceOwnerAllowlist(ctx: ToolContext, pathname: string): void {+ const raw = ctx.secret(GITHUB_APP_ALLOWED_OWNERS_SECRET)+ if (!raw || raw.trim().length === 0) {+ return+ }+ const allowed = new Set(+ raw+ .split(/[,\s]+/)+ .filter(Boolean)+ .map((o) => o.toLowerCase())+ )+ const owner = parseOwner(pathname)+ if (owner === null) {+ throw new Error(+ `github_app_owner_unverifiable: ${GITHUB_APP_ALLOWED_OWNERS_SECRET} is set but this path names no owner to check`+ )+ }+ if (!allowed.has(owner.toLowerCase())) {+ throw new Error(`github_app_owner_not_allowed: ${owner} is not in ${GITHUB_APP_ALLOWED_OWNERS_SECRET}`)+ }+}++/**+ * Resolve which installation to act as: the explicit arg (webhook payloads+ * carry it at `installation.id`), else derived from the repo in the path via+ * the App-JWT lookup endpoint. Non-repo paths can't be derived, so they+ * require the arg.+ */+async function resolveInstallationId(+ ctx: ToolContext,+ jwt: string,+ repo: RepoRef | null,+ explicitId: number | undefined,+ timeoutMs: number+): Promise<number> {+ if (explicitId !== undefined) {+ return explicitId+ }+ if (!repo) {+ throw new Error(+ 'github_app_installation_id_required: pass installation_id (webhook payloads carry it at installation.id) for paths outside /repos/{owner}/{repo}'+ )+ }+ const res = await fetchWithTimeout(+ ctx,+ `${API_BASE}/repos/${repo.owner}/${repo.repo}/installation`,+ { method: 'GET', headers: appAuthHeaders(jwt) },+ timeoutMs,+ ERR_PREFIX+ )+ if (!res.ok) {+ throw new Error(`github_app_installation_lookup_failed: ${res.status}`)+ }+ const data = (await res.json()) as { id?: number }+ if (typeof data.id !== 'number') {+ throw new Error('github_app_installation_lookup_failed: response carried no installation id')+ }+ return data.id+}++/** A cached token is usable until it's within the refresh margin of expiry. */+function freshCachedToken(cacheKey: string): string | undefined {+ const cached = tokenCache.get(cacheKey)+ if (cached && cached.expiresAtMs - Date.now() > TOKEN_REFRESH_MARGIN_MS) {+ return cached.token+ }+ return undefined+}++/** Store a minted token. delete-then-set gives LRU insertion order (a refresh+ * moves the key to the tail), and evicting only after removing the current+ * key means a refresh at capacity never drops an unrelated live entry. */+function cacheToken(cacheKey: string, token: string, expiresAtMs: number): void {+ tokenCache.delete(cacheKey)+ if (tokenCache.size >= TOKEN_CACHE_MAX_ENTRIES) {+ const oldest = tokenCache.keys().next().value+ if (oldest !== undefined) {+ tokenCache.delete(oldest)+ }+ }+ tokenCache.set(cacheKey, { token, expiresAtMs })+}++async function getInstallationToken(+ ctx: ToolContext,+ installationIdArg: number | undefined,+ repo: RepoRef | null,+ timeoutMs: number+): Promise<string> {+ const identity = resolveAppIdentity(ctx)+ // Down-scope the token to the repo in the path so it only works on the+ // resource being accessed — even a prompt injection that targets an allowed+ // owner can't pivot to other repos in the installation. Non-repo (org-level)+ // paths can't be repo-scoped, so they get a full-installation token.+ const repoScope = repo?.repo+ const scopeKey = repoScope ?? '*'++ // Fast path: an explicit installation id can hit the cache with no crypto+ // and no key parse. The key fingerprint in the cache key is what makes this+ // safe across tenants — see the tokenCache comment.+ if (installationIdArg !== undefined) {+ const hit = freshCachedToken(`${identity.appId}:${installationIdArg}:${identity.keyFingerprint}:${scopeKey}`)+ if (hit) {+ return hit+ }+ }++ const jwt = mintAppJwt(identity.appId, parsePrivateKey(identity.pem))+ const installationId = await resolveInstallationId(ctx, jwt, repo, installationIdArg, timeoutMs)+ const cacheKey = `${identity.appId}:${installationId}:${identity.keyFingerprint}:${scopeKey}`+ // A derived installation id may now hit the cache the explicit fast path couldn't reach.+ const hit = freshCachedToken(cacheKey)+ if (hit) {+ return hit+ }++ const mintHeaders = appAuthHeaders(jwt)+ let mintBody: string | undefined+ if (repoScope) {+ mintHeaders['Content-Type'] = 'application/json'+ // `repositories` names are relative to the installation account, which+ // is this repo's owner (the installation was resolved from it).+ mintBody = JSON.stringify({ repositories: [repoScope] })+ }+ const res = await fetchWithTimeout(+ ctx,+ `${API_BASE}/app/installations/${installationId}/access_tokens`,+ { method: 'POST', headers: mintHeaders, body: mintBody },+ timeoutMs,+ ERR_PREFIX+ )+ if (!res.ok) {+ throw new Error(`github_app_token_mint_failed: ${res.status}`)+ }+ const data = (await res.json()) as { token?: string; expires_at?: string }+ if (typeof data.token !== 'string') {+ throw new Error('github_app_token_mint_failed: response carried no token')+ }+ const expiresAtMs = Date.parse(data.expires_at ?? '')+ if (!Number.isNaN(expiresAtMs)) {+ cacheToken(cacheKey, data.token, expiresAtMs)+ }+ ctx.log('info', 'github_app.token.minted', { installation_id: installationId, repo_scope: repoScope ?? null })+ return data.token+}++/**+ * Join `path` onto the pinned base and re-validate what actually parsed —+ * refuses protocol-relative (`//…`) and absolute-URL smuggling so the minted+ * token can only ever be sent to api.github.com.+ */+function buildApiUrl(path: string): URL {+ if (!path.startsWith('/') || path.startsWith('//')) {+ throw new Error(`github_app_path_invalid: path must start with a single '/' — got ${JSON.stringify(path)}`)+ }+ let url: URL+ try {+ url = new URL(`${API_BASE}${path}`)+ } catch {+ throw new Error(`github_app_path_invalid: ${JSON.stringify(path)} does not form a valid URL`)+ }+ if (url.host !== API_HOST || url.protocol !== 'https:') {+ throw new Error(`github_app_path_invalid: requests are pinned to ${API_BASE}`)+ }+ return url+}++export const githubAppRequestV1 = defineNativeTool({+ id: '@posthog/github-app-request',+ // Same stance as @posthog/http-request: proxy-bound egress pinned to one+ // host, wielding a credential the author explicitly configured — allow.+ approval: 'allow',+ description: [+ 'Make an authenticated request to the GitHub REST API (api.github.com only), acting as a GitHub App.',+ 'Auth is handled inside the runner: it signs a short-lived App JWT with the GITHUB_APP_PRIVATE_KEY',+ 'secret, exchanges it for an installation access token, caches it, and attaches it to the request —',+ 'no credential ever appears in the conversation. Requires the GITHUB_APP_ID and',+ 'GITHUB_APP_PRIVATE_KEY secrets to be set on the agent. Pass installation_id (found in webhook',+ 'payloads at installation.id) when the path is not repo-scoped; repo paths can resolve it themselves.',+ "Set accept to 'application/vnd.github.v3.diff' on a pull request endpoint to fetch the unified diff.",+ ].join(' '),+ args: Type.Object({+ path: Type.String({+ description:+ "GitHub REST API path starting with '/', joined to https://api.github.com. May include a query string, e.g. /repos/PostHog/posthog/pulls/123/files?per_page=100&page=2",+ }),+ method: Type.Optional(+ Type.Union(+ [+ Type.Literal('GET'),+ Type.Literal('POST'),+ Type.Literal('PUT'),+ Type.Literal('PATCH'),+ Type.Literal('DELETE'),+ ],+ { default: 'GET', description: 'HTTP method. Default GET.' }+ )+ ),+ body: Type.Optional(+ Type.Union([Type.String(), Type.Record(Type.String(), Type.Unknown())], {+ description:+ 'Request body. Objects are JSON-encoded with Content-Type application/json; strings are sent verbatim.',+ })+ ),+ accept: Type.Optional(+ Type.String({+ description: `Override the Accept header, e.g. application/vnd.github.v3.diff for a unified diff. Defaults to ${DEFAULT_ACCEPT}.`,+ })+ ),+ installation_id: Type.Optional(+ Type.Integer({+ description:+ 'GitHub App installation id — webhook payloads carry it at installation.id. Optional for /repos/{owner}/{repo}/… paths (resolved via the App), required otherwise.',+ })+ ),+ timeout_ms: Type.Optional(+ Type.Integer({+ minimum: 1,+ maximum: ABSOLUTE_MAX_TIMEOUT_MS,+ description: `Per-request timeout in ms (default ${DEFAULT_TIMEOUT_MS}, max ${ABSOLUTE_MAX_TIMEOUT_MS}).`,+ })+ ),+ max_response_bytes: Type.Optional(+ Type.Integer({+ minimum: 1,+ maximum: ABSOLUTE_MAX_RESPONSE_BYTES,+ description: `Cap on response body bytes returned to the model (default ${DEFAULT_MAX_RESPONSE_BYTES}, max ${ABSOLUTE_MAX_RESPONSE_BYTES}). Bodies larger than this are truncated.`,+ })+ ),+ }),+ returns: Type.Object({+ status: Type.Number(),+ body: Type.String(),+ content_type: Type.String(),+ /** Selected response headers — includes `link` so the model can paginate. */+ headers: Type.Record(Type.String(), Type.String()),+ truncated: Type.Boolean({ description: 'True if the response body was clipped to max_response_bytes.' }),+ }),+ requires: {},+ cost_hint: 'medium',+ async run(args, ctx) {+ const url = buildApiUrl(args.path)+ enforceOwnerAllowlist(ctx, url.pathname)+ const method = args.method ?? 'GET'+ const timeoutMs = args.timeout_ms ?? DEFAULT_TIMEOUT_MS+ const maxBytes = args.max_response_bytes ?? DEFAULT_MAX_RESPONSE_BYTES++ const token = await getInstallationToken(ctx, args.installation_id, parseRepo(url.pathname), timeoutMs)++ const headers: Record<string, string> = {+ Authorization: `Bearer ${token}`,+ Accept: args.accept ?? DEFAULT_ACCEPT,+ 'X-GitHub-Api-Version': API_VERSION,+ }+ // A GET carries no body. Dropping a supplied body silently would let the+ // model believe a mutation ran when it fetched instead — fail loudly so+ // it re-issues with an explicit method.+ if (args.body !== undefined && method === 'GET') {+ throw new Error(+ 'github_app_body_with_get: a request body requires an explicit method (POST/PATCH/PUT/DELETE)'+ )+ }+ let body: string | undefined+ if (args.body !== undefined) {+ if (typeof args.body === 'string') {+ body = args.body+ } else {+ body = JSON.stringify(args.body)+ headers['Content-Type'] = 'application/json; charset=utf-8'+ }+ }++ const res = await fetchWithTimeout(ctx, url.toString(), { method, headers, body }, timeoutMs, ERR_PREFIX)+ const { body: bodyOut, bytesRead, truncated } = await readCappedBody(res, maxBytes)+ const headersOut = pickHeaders(res, HEADER_ALLOWLIST)++ ctx.log('info', 'github_app.request.completed', {+ method,+ path: url.pathname,+ status: res.status,+ response_bytes: bytesRead,+ truncated,+ })++ return {+ status: res.status,+ body: bodyOut,+ content_type: res.headers.get('content-type') ?? '',+ headers: headersOut,+ truncated,+ }+ },+})diff --git a/products/agent_platform/services/agent-tools/src/tools/http-request.v1.ts b/products/agent_platform/services/agent-tools/src/tools/http-request.v1.tsindex b4c6b019bba4..6a467f8f7893 100644--- a/products/agent_platform/services/agent-tools/src/tools/http-request.v1.ts+++ b/products/agent_platform/services/agent-tools/src/tools/http-request.v1.ts@@ -28,6 +28,15 @@import { defineNativeTool, secretHostMatches, type ToolContext, Type } from '@posthog/agent-shared'+import {+ ABSOLUTE_MAX_RESPONSE_BYTES,+ ABSOLUTE_MAX_TIMEOUT_MS,+ DEFAULT_MAX_RESPONSE_BYTES,+ DEFAULT_TIMEOUT_MS,+ fetchWithTimeout,+ pickHeaders,+ readCappedBody,+} from './http-shared'import { parseFetchableUrl } from './http-url'const SECRET_REF = /\$\{([A-Z][A-Z0-9_]*)\}/g@@ -155,65 +164,7 @@ function serializeBody(return { body: substituteSecrets(JSON.stringify(body), host, ctx), headers: finalHeaders }}-const DEFAULT_MAX_RESPONSE_BYTES = 1_000_000-const ABSOLUTE_MAX_RESPONSE_BYTES = 5_000_000-const DEFAULT_TIMEOUT_MS = 15_000-const ABSOLUTE_MAX_TIMEOUT_MS = 60_000--/**- * Read the response body up to `maxBytes`, streaming so an oversized or- * highly-compressed response is never fully materialized before truncation.- * Stops at the cap and cancels the stream, which tears down the underlying- * connection so we don't keep pulling bytes we'll throw away. Falls back to- * `res.text()` only when the response exposes no readable stream (e.g. an- * empty body or a non-streaming test mock), still capping the result.- */-async function readCappedBody(- res: Response,- maxBytes: number-): Promise<{ body: string; bytesRead: number; truncated: boolean }> {- const stream = res.body- if (!stream) {- const text = await res.text()- const bytes = new TextEncoder().encode(text)- if (bytes.byteLength <= maxBytes) {- return { body: text, bytesRead: bytes.byteLength, truncated: false }- }- return { body: new TextDecoder().decode(bytes.subarray(0, maxBytes)), bytesRead: maxBytes, truncated: true }- }-- const reader = stream.getReader()- const chunks: Uint8Array[] = []- let total = 0- let truncated = false- try {- while (total < maxBytes) {- const { done, value } = await reader.read()- if (done) {- break- }- if (total + value.byteLength > maxBytes) {- chunks.push(value.subarray(0, maxBytes - total))- total = maxBytes- truncated = true- break- }- chunks.push(value)- total += value.byteLength- }- } finally {- // Cancel rather than drain: releases the socket so we never pull past the cap.- await reader.cancel().catch(() => {})- }-- const buf = new Uint8Array(total)- let offset = 0- for (const chunk of chunks) {- buf.set(chunk, offset)- offset += chunk.byteLength- }- return { body: new TextDecoder().decode(buf), bytesRead: total, truncated }-}+const HEADER_ALLOWLIST = new Set(['content-type', 'content-length', 'location', 'retry-after', 'date'])export const httpRequestV1 = defineNativeTool({id: '@posthog/http-request',@@ -298,38 +249,10 @@ export const httpRequestV1 = defineNativeTool({const maxBytes = args.max_response_bytes ?? DEFAULT_MAX_RESPONSE_BYTESconst timeoutMs = args.timeout_ms ?? DEFAULT_TIMEOUT_MS- const controller = new AbortController()- const abortTimer = setTimeout(() => controller.abort(), timeoutMs)-- let res: Response- try {- res = await ctx.http.fetch(url, {- method,- headers: finalHeaders,- body,- signal: controller.signal,- })- } catch (err) {- const e = err as Error & { name?: string }- if (e.name === 'AbortError') {- throw new Error(`http_request_timeout: ${timeoutMs}ms`)- }- throw new Error(`http_request_failed: ${e.message ?? 'unknown'}`)- } finally {- clearTimeout(abortTimer)- }+ const res = await fetchWithTimeout(ctx, url, { method, headers: finalHeaders, body }, timeoutMs, 'http_request')const { body: bodyOut, bytesRead, truncated } = await readCappedBody(res, maxBytes)-- // Surface a small fixed set of useful response headers; sending every- // header back inflates the context for no model-side payoff.- const HEADER_ALLOWLIST = new Set(['content-type', 'content-length', 'location', 'retry-after', 'date'])- const headersOut: Record<string, string> = {}- for (const [k, v] of res.headers.entries()) {- if (HEADER_ALLOWLIST.has(k.toLowerCase())) {- headersOut[k] = v- }- }+ const headersOut = pickHeaders(res, HEADER_ALLOWLIST)ctx.log('info', 'http.request.completed', {method,diff --git a/products/agent_platform/services/agent-tools/src/tools/http-shared.ts b/products/agent_platform/services/agent-tools/src/tools/http-shared.tsnew file mode 100644index 000000000000..774ddbc909a4--- /dev/null+++ b/products/agent_platform/services/agent-tools/src/tools/http-shared.ts@@ -0,0 +1,113 @@+/**+ * Shared plumbing for the HTTP-ish native tools (`@posthog/http-request`,+ * `@posthog/github-app-request`). One definition each of the egress budgets,+ * the timeout wrapper, response-body capping, and header selection so the two+ * tools can't drift on policy.+ */++import type { ToolContext } from '@posthog/agent-shared'++/** Platform-wide egress budgets — how much a tool may return to the model and+ * how long an outbound call may hang. One source so the tools stay in step. */+export const DEFAULT_MAX_RESPONSE_BYTES = 1_000_000+export const ABSOLUTE_MAX_RESPONSE_BYTES = 5_000_000+export const DEFAULT_TIMEOUT_MS = 15_000+export const ABSOLUTE_MAX_TIMEOUT_MS = 60_000++/**+ * Fetch through the tool's proxy-bound client with an abort timeout.+ * `errPrefix` namespaces the thrown error per tool (`http_request`,+ * `github_app_request`) so callers keep their existing error codes.+ */+export async function fetchWithTimeout(+ ctx: ToolContext,+ url: string,+ init: RequestInit,+ timeoutMs: number,+ errPrefix: string+): Promise<Response> {+ const controller = new AbortController()+ const abortTimer = setTimeout(() => controller.abort(), timeoutMs)+ try {+ return await ctx.http.fetch(url, { ...init, signal: controller.signal })+ } catch (err) {+ const e = err as Error & { name?: string }+ if (e.name === 'AbortError') {+ throw new Error(`${errPrefix}_timeout: ${timeoutMs}ms`)+ }+ throw new Error(`${errPrefix}_failed: ${e.message ?? 'unknown'}`)+ } finally {+ clearTimeout(abortTimer)+ }+}++/**+ * Return the allowlisted response headers, keys lower-cased. Sending every+ * header back inflates the model's context for no payoff; lower-casing gives+ * the model one stable spelling to read (`headers['content-type']`).+ */+export function pickHeaders(res: Response, allowlist: ReadonlySet<string>): Record<string, string> {+ const out: Record<string, string> = {}+ for (const [k, v] of res.headers.entries()) {+ const lower = k.toLowerCase()+ if (allowlist.has(lower)) {+ out[lower] = v+ }+ }+ return out+}++/**+ * Read the response body up to `maxBytes`, streaming so an oversized or+ * highly-compressed response is never fully materialized before truncation.+ * Stops at the cap and cancels the stream, which tears down the underlying+ * connection so we don't keep pulling bytes we'll throw away. Falls back to+ * `res.text()` only when the response exposes no readable stream (e.g. an+ * empty body or a non-streaming test mock), still capping the result.+ */+export async function readCappedBody(+ res: Response,+ maxBytes: number+): Promise<{ body: string; bytesRead: number; truncated: boolean }> {+ const stream = res.body+ if (!stream) {+ const text = await res.text()+ const bytes = new TextEncoder().encode(text)+ if (bytes.byteLength <= maxBytes) {+ return { body: text, bytesRead: bytes.byteLength, truncated: false }+ }+ return { body: new TextDecoder().decode(bytes.subarray(0, maxBytes)), bytesRead: maxBytes, truncated: true }+ }++ const reader = stream.getReader()+ const chunks: Uint8Array[] = []+ let total = 0+ let truncated = false+ try {+ while (total < maxBytes) {+ const { done, value } = await reader.read()+ if (done) {+ break+ }+ if (total + value.byteLength > maxBytes) {+ chunks.push(value.subarray(0, maxBytes - total))+ total = maxBytes+ truncated = true+ break+ }+ chunks.push(value)+ total += value.byteLength+ }+ } finally {+ // Cancel rather than drain: releases the socket so we never pull past the cap.+ await reader.cancel().catch(() => {})+ }++ const buf = new Uint8Array(total)+ let offset = 0+ for (const chunk of chunks) {+ buf.set(chunk, offset)+ offset += chunk.byteLength+ }+ return { body: new TextDecoder().decode(buf), bytesRead: total, truncated }+}