⭐️⭐️⭐️ Open-source, self-hosted alternative to Linear and Plane. Project management and issue tracking where teams and AI agents work side by side to plan and ship products.
TypeScript agenticagileai-agentsbug-reportingbug-trackerganttissue-trackerjirajira-alternativekanbanlinearlinear-alternativeopen-sourceproduct-managementproject-managementroadmapself-hostedsprint-planningteam-collaborationtrello-alternative
fix: pin the resolved address for server-side fetches and reject IPv4-mapped private addresses (#313)
Croff13cff40f11a8
diff --git a/AGENTS.md b/AGENTS.mdindex 5315d642..48cd84c2 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -77,6 +77,7 @@ packages/db @repo/db — Drizzle client, schema, migrationspackages/auth @repo/auth — better-auth server instance + instance auth settingspackages/crypto @repo/crypto — AES-256-GCM encryption for secrets at restpackages/mailer @repo/mailer — SMTP/Resend transport for outbound email+packages/net @repo/net — SSRF guard for server-side fetches of a supplied URLpackages/agent-tools @repo/agent-tools — tool definitions for the AI agent runtimepackages/runner @itsaplan/runner — CLI that runs an external agent's queued tasks on the operator's own machinepackages/eslint-config @repo/eslint-config — shared ESLint configdiff --git a/apps/api/Dockerfile b/apps/api/Dockerfileindex 469f860e..5a511210 100644--- a/apps/api/Dockerfile+++ b/apps/api/Dockerfile@@ -17,6 +17,7 @@ COPY packages/auth/package.json ./packages/auth/COPY packages/agent-tools/package.json ./packages/agent-tools/COPY packages/crypto/package.json ./packages/crypto/COPY packages/mailer/package.json ./packages/mailer/+COPY packages/net/package.json ./packages/net/COPY packages/runner/package.json ./packages/runner/COPY packages/eslint-config/package.json ./packages/eslint-config/# --filter api installs only the api workspace and its dependency closure, so thediff --git a/apps/api/package.json b/apps/api/package.jsonindex 24cb1a48..f66c055b 100644--- a/apps/api/package.json+++ b/apps/api/package.json@@ -32,6 +32,7 @@"@repo/crypto": "workspace:*","@repo/db": "workspace:*","@repo/mailer": "workspace:*",+ "@repo/net": "workspace:*","croner": "^10.0.1","drizzle-orm": "^0.45.2","elysia": "^1.4.29",diff --git a/apps/api/src/modules/attachments/index.ts b/apps/api/src/modules/attachments/index.tsindex a08c3d87..06b37763 100644--- a/apps/api/src/modules/attachments/index.ts+++ b/apps/api/src/modules/attachments/index.ts@@ -4,7 +4,7 @@ import { authContext } from '#shared/auth-context';import { entityGuard } from '#shared/guards';import { HttpError } from '#shared/lib';import { getObject } from '#shared/s3';-import { assertPublicHttpUrl } from '#shared/net';+import { pinnedFetch } from '#shared/net';import { mcpTool } from '#mcp/generate';import { accessErrors, commonErrors, errors } from '#shared/responses';import { getIssueProjectId } from '#modules/issues/service';@@ -148,11 +148,11 @@ export const attachmentRoutes = new Elysia({let bytes: Buffer;let contentType: string;if (url != null) {- const target = await assertPublicHttpUrl(url);let res: Response;try {- res = await fetch(target, { redirect: 'manual', signal: AbortSignal.timeout(15000) });- } catch {+ res = await pinnedFetch(url, { timeoutMs: 15000 });+ } catch (err) {+ if (err instanceof HttpError) throw err;throw new HttpError(400, 'Could not fetch the url');}if (res.status >= 300 && res.status < 400) {diff --git a/apps/api/src/modules/git/connections-provider.ts b/apps/api/src/modules/git/connections-provider.tsindex 97c382f8..a1339232 100644--- a/apps/api/src/modules/git/connections-provider.ts+++ b/apps/api/src/modules/git/connections-provider.ts@@ -1,5 +1,5 @@import { HttpError } from '#shared/lib';-import { assertPublicHttpUrl } from '#shared/net';+import { assertPublicHttpUrl, pinnedFetch } from '#shared/net';import { pipelineStatus } from './providers';import type { PipelineEvent, PullRequestEvent, PullRequestState } from './providers';@@ -184,18 +184,18 @@ async function providerRequest(path: string,init: RequestInit = {},): Promise<Response> {- await assertPublicHttpUrl(input.baseUrl);const headers = providerHeaders(input.provider, input.token);if (init.body !== undefined) headers.set('content-type', 'application/json');let response: Response;try {- response = await fetch(`${apiBase(input.provider, input.baseUrl)}${path}`, {- ...init,+ response = await pinnedFetch(`${apiBase(input.provider, input.baseUrl)}${path}`, {+ method: init.method,headers,- redirect: 'manual',- signal: AbortSignal.timeout(15_000),+ body: init.body as string | undefined,+ timeoutMs: 15_000,});- } catch {+ } catch (err) {+ if (err instanceof HttpError) throw err;throw new HttpError(502,`${PROVIDER_LABEL[input.provider]} could not be reached. Check the provider URL and network access.`,diff --git a/apps/api/src/modules/webhooks/__tests__/integration/webhooks.test.ts b/apps/api/src/modules/webhooks/__tests__/integration/webhooks.test.tsindex 37aff0f2..2ca5b844 100644--- a/apps/api/src/modules/webhooks/__tests__/integration/webhooks.test.ts+++ b/apps/api/src/modules/webhooks/__tests__/integration/webhooks.test.ts@@ -96,6 +96,24 @@ describe('webhooks', () => {expect(res.status).toBe(400);});+ it('rejects an IPv4-mapped IPv6 url pointing at a private address', async () => {+ const { asOwner } = await setupOwnerProject();+ const res = await asOwner.projects({ projectKey: 'MKT' }).webhooks.post({+ url: 'https://[::ffff:169.254.169.254]/hook',+ events: ['issue.created'],+ });+ expect(res.status).toBe(400);+ });++ it('rejects a hostname that resolves to a private address', async () => {+ const { asOwner } = await setupOwnerProject();+ const res = await asOwner.projects({ projectKey: 'MKT' }).webhooks.post({+ url: 'https://localtest.me/hook',+ events: ['issue.created'],+ });+ expect(res.status).toBe(400);+ });+it('rejects an empty events list', async () => {const { asOwner } = await setupOwnerProject();const res = await asOwner.projects({ projectKey: 'MKT' }).webhooks.post({diff --git a/apps/api/src/modules/webhooks/index.ts b/apps/api/src/modules/webhooks/index.tsindex 4e787842..f4b66a87 100644--- a/apps/api/src/modules/webhooks/index.ts+++ b/apps/api/src/modules/webhooks/index.ts@@ -3,6 +3,7 @@ import { noContent } from '#shared/http';import { guards, entityGuard } from '#shared/guards';import { authContext } from '#shared/auth-context';import { HttpError } from '#shared/lib';+import { assertPublicHttpUrl } from '#shared/net';import { mcpTool } from '#mcp/generate';import { accessErrors, commonErrors } from '#shared/responses';import {@@ -22,58 +23,6 @@ import {listWebhookDeliveries,} from './service';-// A local, loopback, or private-range host — the SSRF-sensitive targets.-function isLocalHost(host: string): boolean {- return (- host === 'localhost' ||- host.endsWith('.local') ||- host === '0.0.0.0' ||- host === '::1' ||- /^127\./.test(host) ||- /^10\./.test(host) ||- /^192\.168\./.test(host) ||- /^172\.(1[6-9]|2[0-9]|3[0-1])\./.test(host) ||- /^169\.254\./.test(host) ||- /^f[cd][0-9a-f]{2}:/.test(host)- );-}--// An IPv4 or IPv6 literal (as opposed to a DNS name).-function isIpLiteral(host: string): boolean {- return /^\d{1,3}(\.\d{1,3}){3}$/.test(host) || host.includes(':');-}--// Rejects a url that is not https, or that targets a local or private address. This-// stops a subscription from reaching internal services (SSRF). The check is syntactic-// and runs at registration time. The delivery side runs the DNS-level check.-//-// Local development is the exception (NODE_ENV is neither production nor test): a-// localhost, 0.0.0.0, or IP-literal target passes over http, so an operator can-// register a local test receiver. Production and the test suite stay strict.-function validateWebhookUrl(raw: string): string {- let url: URL;- try {- url = new URL(raw);- } catch {- throw new HttpError(400, 'Webhook url must be a valid URL');- }- const host = url.hostname.toLowerCase();-- const devRelaxed =- process.env.NODE_ENV !== 'production' &&- process.env.NODE_ENV !== 'test' &&- (isLocalHost(host) || isIpLiteral(host));- if (devRelaxed) return raw;-- if (url.protocol !== 'https:') {- throw new HttpError(400, 'Webhook url must use https');- }- if (isLocalHost(host)) {- throw new HttpError(400, 'Webhook url must not point to a private or local address');- }- return raw;-}-export const webhookRoutes = new Elysia({ name: 'webhooks', detail: { tags: ['Webhooks'] } }).use(authContext).use(guards)@@ -99,10 +48,11 @@ export const webhookRoutes = new Elysia({ name: 'webhooks', detail: { tags: ['We.post('/projects/:projectKey/webhooks',async ({ project, body, set }) => {+ await assertPublicHttpUrl(body.url);set.status = 201;return createWebhook({projectId: project.id,- url: validateWebhookUrl(body.url),+ url: body.url,events: body.events,isActive: body.isActive,});@@ -118,11 +68,8 @@ export const webhookRoutes = new Elysia({ name: 'webhooks', detail: { tags: ['We.patch('/webhooks/:webhookId',async ({ params, body }) => {- const patch = {- ...body,- ...(body.url !== undefined ? { url: validateWebhookUrl(body.url) } : {}),- };- const updated = await updateWebhook(params.webhookId, patch);+ if (body.url !== undefined) await assertPublicHttpUrl(body.url);+ const updated = await updateWebhook(params.webhookId, body);if (!updated) throw new HttpError(404, 'Webhook not found');return updated;},diff --git a/apps/api/src/shared/net.ts b/apps/api/src/shared/net.tsindex 7aeb599c..beac44f7 100644--- a/apps/api/src/shared/net.ts+++ b/apps/api/src/shared/net.ts@@ -1,74 +1,23 @@-import { lookup } from 'node:dns/promises';+import {+ assertPublicHttpUrl as assertPublicUrl,+ pinnedFetch as pinnedFetchUrl,+ UrlNotAllowedError,+ type PinnedRequestInit,+} from '@repo/net';import { HttpError } from './lib';-// SSRF guards for server-side fetches of a user/agent-supplied URL. A URL that-// resolves to a loopback, link-local, or private-range address could reach internal-// services (including the cloud metadata endpoint at 169.254.169.254), so those are-// rejected. The check runs at fetch time and resolves DNS, so a public hostname that-// points at a private address is caught too.--// A hostname that is inherently local (not an IP literal).-function isLocalHostname(host: string): boolean {- return host === 'localhost' || host.endsWith('.local');+function as400<T>(run: () => Promise<T>): Promise<T> {+ return run().catch((err: unknown) => {+ if (err instanceof UrlNotAllowedError) throw new HttpError(400, err.message);+ throw err;+ });}-// An IPv4/IPv6 address in a loopback, link-local, or private range.-export function isPrivateIp(ip: string): boolean {- const v4 = ip.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/);- if (v4) {- const [a, b] = [Number(v4[1]), Number(v4[2])];- return (- a === 0 ||- a === 127 || // loopback- a === 10 || // private- (a === 172 && b >= 16 && b <= 31) || // private- (a === 192 && b === 168) || // private- (a === 169 && b === 254) || // link-local (incl. cloud metadata)- (a === 100 && b >= 64 && b <= 127) // CGNAT- );- }- const v6 = ip.toLowerCase();- return (- v6 === '::1' || // loopback- v6 === '::' ||- v6.startsWith('fe80:') || // link-local- /^f[cd][0-9a-f]{2}:/.test(v6) // unique local- );+// The shared SSRF guards, with their rejection turned into the API's 400.+export function assertPublicHttpUrl(raw: string): Promise<URL> {+ return as400(() => assertPublicUrl(raw));}-// Validates a user/agent-supplied URL for a server-side fetch: http(s) only, and it-// must not resolve to a local/private address. Returns the parsed URL. http is-// allowed only in local development (like validateWebhookUrl), production and tests-// require https. Throws HttpError(400) on any failure.-export async function assertPublicHttpUrl(raw: string): Promise<URL> {- let url: URL;- try {- url = new URL(raw);- } catch {- throw new HttpError(400, 'url must be a valid URL');- }-- const devRelaxed = process.env.NODE_ENV !== 'production' && process.env.NODE_ENV !== 'test';- if (url.protocol !== 'https:' && !(devRelaxed && url.protocol === 'http:')) {- throw new HttpError(400, 'url must use https');- }-- const host = url.hostname.toLowerCase();- if (isLocalHostname(host) || isPrivateIp(host)) {- if (!devRelaxed) throw new HttpError(400, 'url must not point to a private or local address');- return url;- }-- // Resolve the hostname and reject if any address is private, so a public name that- // points at an internal address cannot slip through.- try {- const addrs = await lookup(host, { all: true });- if (addrs.some((a) => isPrivateIp(a.address)) && !devRelaxed) {- throw new HttpError(400, 'url must not point to a private or local address');- }- } catch (err) {- if (err instanceof HttpError) throw err;- throw new HttpError(400, 'url host could not be resolved');- }- return url;+export function pinnedFetch(raw: string, init?: PinnedRequestInit): Promise<Response> {+ return as400(() => pinnedFetchUrl(raw, init));}diff --git a/apps/bot/Dockerfile b/apps/bot/Dockerfileindex b370981d..3899c15f 100644--- a/apps/bot/Dockerfile+++ b/apps/bot/Dockerfile@@ -17,6 +17,7 @@ COPY packages/auth/package.json ./packages/auth/COPY packages/agent-tools/package.json ./packages/agent-tools/COPY packages/crypto/package.json ./packages/crypto/COPY packages/mailer/package.json ./packages/mailer/+COPY packages/net/package.json ./packages/net/COPY packages/runner/package.json ./packages/runner/COPY packages/eslint-config/package.json ./packages/eslint-config/# --filter bot installs only the bot workspace and its dependency closure.diff --git a/apps/web/Dockerfile b/apps/web/Dockerfileindex 6f678804..076afca4 100644--- a/apps/web/Dockerfile+++ b/apps/web/Dockerfile@@ -17,6 +17,7 @@ COPY packages/auth/package.json ./packages/auth/COPY packages/agent-tools/package.json ./packages/agent-tools/COPY packages/crypto/package.json ./packages/crypto/COPY packages/mailer/package.json ./packages/mailer/+COPY packages/net/package.json ./packages/net/COPY packages/runner/package.json ./packages/runner/COPY packages/eslint-config/package.json ./packages/eslint-config/RUN bun install --frozen-lockfilediff --git a/apps/worker/Dockerfile b/apps/worker/Dockerfileindex ea33fcfa..61e09cb6 100644--- a/apps/worker/Dockerfile+++ b/apps/worker/Dockerfile@@ -17,6 +17,7 @@ COPY packages/auth/package.json ./packages/auth/COPY packages/agent-tools/package.json ./packages/agent-tools/COPY packages/crypto/package.json ./packages/crypto/COPY packages/mailer/package.json ./packages/mailer/+COPY packages/net/package.json ./packages/net/COPY packages/runner/package.json ./packages/runner/COPY packages/eslint-config/package.json ./packages/eslint-config/# --filter worker installs only the worker workspace and its dependency closure.diff --git a/apps/worker/package.json b/apps/worker/package.jsonindex 0838aa00..817eb520 100644--- a/apps/worker/package.json+++ b/apps/worker/package.json@@ -12,6 +12,7 @@},"dependencies": {"@repo/db": "workspace:*",+ "@repo/net": "workspace:*","croner": "^10.0.1","drizzle-orm": "^0.45.2"},diff --git a/apps/worker/src/delivery.ts b/apps/worker/src/delivery.tsindex 15b4f7fe..2bee18f1 100644--- a/apps/worker/src/delivery.ts+++ b/apps/worker/src/delivery.ts@@ -1,3 +1,4 @@+import { pinnedFetch, UrlNotAllowedError } from '@repo/net';import { signPayload } from './signature';export interface DeliverInput {@@ -37,9 +38,11 @@ export async function deliver(input: DeliverInput): Promise<DeliveryResult> {const ts = Math.floor(Date.now() / 1000);const signature = signPayload(input.secret, ts, input.body);try {- const res = await fetch(input.url, {+ // Re-checked here, not only at registration: the url was validated when it was+ // stored, but the hostname it resolves to can have changed since.+ const res = await pinnedFetch(input.url, {method: 'POST',- signal: AbortSignal.timeout(input.timeoutMs),+ timeoutMs: input.timeoutMs,headers: {'Content-Type': 'application/json','User-Agent': 'itsaplan-webhooks/1',@@ -61,10 +64,11 @@ export async function deliver(input: DeliverInput): Promise<DeliveryResult> {responseBody,};} catch (err) {- // Network error, DNS failure, or the AbortSignal timeout — all transient.+ // A url that no longer passes the guard is permanent; a network error, DNS+ // failure, or the timeout is transient.return {ok: false,- retryable: true,+ retryable: !(err instanceof UrlNotAllowedError),error: err instanceof Error ? err.message : 'request failed',};}diff --git a/bun.lock b/bun.lockindex 460ba28a..249a5a75 100644--- a/bun.lock+++ b/bun.lock@@ -32,6 +32,7 @@"@repo/crypto": "workspace:*","@repo/db": "workspace:*","@repo/mailer": "workspace:*",+ "@repo/net": "workspace:*","croner": "^10.0.1","drizzle-orm": "^0.45.2","elysia": "^1.4.29",@@ -151,6 +152,7 @@"version": "1.0.0","dependencies": {"@repo/db": "workspace:*",+ "@repo/net": "workspace:*","croner": "^10.0.1","drizzle-orm": "^0.45.2",},@@ -251,9 +253,19 @@"typescript": "^6.0.3",},},+ "packages/net": {+ "name": "@repo/net",+ "version": "0.0.0",+ "devDependencies": {+ "@repo/eslint-config": "workspace:*",+ "@types/bun": "latest",+ "eslint": "^9.39.0",+ "typescript": "^6.0.3",+ },+ },"packages/runner": {"name": "@itsaplan/runner",- "version": "0.4.0",+ "version": "0.5.0","bin": {"itsaplan-runner": "./dist/cli.js",},@@ -911,6 +923,8 @@"@repo/mailer": ["@repo/mailer@workspace:packages/mailer"],+ "@repo/net": ["@repo/net@workspace:packages/net"],+"@scalar/agent-chat": ["@scalar/[email protected]", "", { "dependencies": { "@ai-sdk/vue": "3.0.33", "@scalar/api-client": "3.15.0", "@scalar/components": "0.27.11", "@scalar/helpers": "0.10.0", "@scalar/icons": "0.7.5", "@scalar/json-magic": "0.12.20", "@scalar/openapi-types": "0.9.4", "@scalar/schemas": "0.8.1", "@scalar/themes": "0.17.2", "@scalar/types": "0.17.1", "@scalar/use-toasts": "0.10.4", "@scalar/validation": "0.6.2", "@scalar/workspace-store": "0.56.1", "@vueuse/core": "13.9.0", "ai": "6.0.33", "js-base64": "^3.7.8", "neverpanic": "0.0.8", "truncate-json": "3.0.1", "vue": "^3.5.40" } }, "sha512-wIDE//zXOIto05DJlTGLOdXiuRzSCMT+DOzLhLTWmRFaR8WeTMSneiNppQ7kQGMtukD6hpz/awQRRx+PY8XIYw=="],"@scalar/api-client": ["@scalar/[email protected]", "", { "dependencies": { "@headlessui/tailwindcss": "^0.2.2", "@headlessui/vue": "1.7.23", "@scalar/blocks": "0.1.10", "@scalar/components": "0.27.11", "@scalar/helpers": "0.10.0", "@scalar/icons": "0.7.5", "@scalar/oas-utils": "0.19.10", "@scalar/openapi-types": "0.9.4", "@scalar/sidebar": "0.9.35", "@scalar/snippetz": "0.9.25", "@scalar/themes": "0.17.2", "@scalar/typebox": "^0.1.3", "@scalar/types": "0.17.1", "@scalar/use-codemirror": "0.14.14", "@scalar/use-hooks": "0.4.9", "@scalar/use-toasts": "0.10.4", "@scalar/workspace-store": "0.56.1", "@vueuse/core": "13.9.0", "@vueuse/integrations": "13.9.0", "focus-trap": "^7.8.0", "fuse.js": "^7.5.0", "js-base64": "^3.7.8", "jsonc-parser": "3.3.1", "nanoid": "^5.1.6", "pretty-ms": "^9.3.0", "radix-vue": "^1.9.17", "set-cookie-parser": "3.1.0", "vue": "^3.5.40", "yaml": "^2.9.0", "zod": "^4.3.5" } }, "sha512-xWxb2JvIMKP7LoSJOfXiqyjdPy/C0FQd/nPOrt483gC/D/2TVtmyxtbVIF6huhOHzsR17Aeh0Awfghsj7tp7/A=="],@@ -2931,15 +2945,17 @@"@reduxjs/toolkit/reselect": ["[email protected]", "", {}, "sha512-K/BG6eIky/SBpzfHZv/dd+9JBFiS4SWV7FIujVyJRux6e45+73RaUHXLmIR1f7WOMaQ0U1km6qwklRQxpJJY0w=="],- "@repo/agent-tools/@types/bun": ["@types/[email protected]", "", { "dependencies": { "bun-types": "1.4.0" } }, "sha512-K+lZULY23vRgK/CfTjFIV+tyifaNdSMlPh9j+6mQ/cLfpOznLyAuzgV/JQysyECpkBQLVMSyvjlr2fBUSA9wFQ=="],+ "@repo/agent-tools/@types/bun": ["@types/[email protected]", "", { "dependencies": { "bun-types": "1.4.1" } }, "sha512-0AVGiTXGajf1rgKom3N+c5L7CBxuoyyv1i44M0nX4UDK0G/fnRAMiri93nHuVPIb429KKtAgj7HatVmmOjeQLA=="],++ "@repo/auth/@types/bun": ["@types/[email protected]", "", { "dependencies": { "bun-types": "1.4.1" } }, "sha512-0AVGiTXGajf1rgKom3N+c5L7CBxuoyyv1i44M0nX4UDK0G/fnRAMiri93nHuVPIb429KKtAgj7HatVmmOjeQLA=="],- "@repo/auth/@types/bun": ["@types/[email protected]", "", { "dependencies": { "bun-types": "1.4.0" } }, "sha512-K+lZULY23vRgK/CfTjFIV+tyifaNdSMlPh9j+6mQ/cLfpOznLyAuzgV/JQysyECpkBQLVMSyvjlr2fBUSA9wFQ=="],+ "@repo/crypto/@types/bun": ["@types/[email protected]", "", { "dependencies": { "bun-types": "1.4.1" } }, "sha512-0AVGiTXGajf1rgKom3N+c5L7CBxuoyyv1i44M0nX4UDK0G/fnRAMiri93nHuVPIb429KKtAgj7HatVmmOjeQLA=="],- "@repo/crypto/@types/bun": ["@types/[email protected]", "", { "dependencies": { "bun-types": "1.4.0" } }, "sha512-K+lZULY23vRgK/CfTjFIV+tyifaNdSMlPh9j+6mQ/cLfpOznLyAuzgV/JQysyECpkBQLVMSyvjlr2fBUSA9wFQ=="],+ "@repo/db/@types/bun": ["@types/[email protected]", "", { "dependencies": { "bun-types": "1.4.1" } }, "sha512-0AVGiTXGajf1rgKom3N+c5L7CBxuoyyv1i44M0nX4UDK0G/fnRAMiri93nHuVPIb429KKtAgj7HatVmmOjeQLA=="],- "@repo/db/@types/bun": ["@types/[email protected]", "", { "dependencies": { "bun-types": "1.4.0" } }, "sha512-K+lZULY23vRgK/CfTjFIV+tyifaNdSMlPh9j+6mQ/cLfpOznLyAuzgV/JQysyECpkBQLVMSyvjlr2fBUSA9wFQ=="],+ "@repo/mailer/@types/bun": ["@types/[email protected]", "", { "dependencies": { "bun-types": "1.4.1" } }, "sha512-0AVGiTXGajf1rgKom3N+c5L7CBxuoyyv1i44M0nX4UDK0G/fnRAMiri93nHuVPIb429KKtAgj7HatVmmOjeQLA=="],- "@repo/mailer/@types/bun": ["@types/[email protected]", "", { "dependencies": { "bun-types": "1.4.0" } }, "sha512-K+lZULY23vRgK/CfTjFIV+tyifaNdSMlPh9j+6mQ/cLfpOznLyAuzgV/JQysyECpkBQLVMSyvjlr2fBUSA9wFQ=="],+ "@repo/net/@types/bun": ["@types/[email protected]", "", { "dependencies": { "bun-types": "1.4.1" } }, "sha512-0AVGiTXGajf1rgKom3N+c5L7CBxuoyyv1i44M0nX4UDK0G/fnRAMiri93nHuVPIb429KKtAgj7HatVmmOjeQLA=="],"@scalar/agent-chat/@scalar/helpers": ["@scalar/[email protected]", "", {}, "sha512-IAfnpIZnXY6ni+zyFMwWHBa5b/7yr4mCSvoTGR84oS9q4Quy2wjgafnr7CyfL65ney3iilBZHigZYLYqdqCu3Q=="],@@ -3029,7 +3045,7 @@"ajv-formats/ajv": ["[email protected]", "", { "dependencies": { "fast-deep-equal": "^3.1.3", "fast-uri": "^3.0.1", "json-schema-traverse": "^1.0.0", "require-from-string": "^2.0.2" } }, "sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA=="],- "api/@types/bun": ["@types/[email protected]", "", { "dependencies": { "bun-types": "1.4.0" } }, "sha512-K+lZULY23vRgK/CfTjFIV+tyifaNdSMlPh9j+6mQ/cLfpOznLyAuzgV/JQysyECpkBQLVMSyvjlr2fBUSA9wFQ=="],+ "api/@types/bun": ["@types/[email protected]", "", { "dependencies": { "bun-types": "1.4.1" } }, "sha512-0AVGiTXGajf1rgKom3N+c5L7CBxuoyyv1i44M0nX4UDK0G/fnRAMiri93nHuVPIb429KKtAgj7HatVmmOjeQLA=="],"archiver-utils/readable-stream": ["[email protected]", "", { "dependencies": { "core-util-is": "~1.0.0", "inherits": "~2.0.3", "isarray": "~1.0.0", "process-nextick-args": "~2.0.0", "safe-buffer": "~5.1.1", "string_decoder": "~1.1.1", "util-deprecate": "~1.0.1" } }, "sha512-8p0AUk4XODgIewSi0l8Epjs+EVnWiK7NoDIEGU0HhE7+ZyY8D1IMY7odu5lRrFXGg71L15KG8QrPmum45RTtdA=="],@@ -3139,6 +3155,8 @@"which-builtin-type/isarray": ["[email protected]", "", {}, "sha512-xHjhDr3cNBK0BzdUJSPXZntQUx/mwMS5Rw4A7lPJ90XGAO6ISP/ePDNuo0vhqOZU+UD5JoodwCAAoZQd3FeAKw=="],+ "worker/@types/bun": ["@types/[email protected]", "", { "dependencies": { "bun-types": "1.4.1" } }, "sha512-0AVGiTXGajf1rgKom3N+c5L7CBxuoyyv1i44M0nX4UDK0G/fnRAMiri93nHuVPIb429KKtAgj7HatVmmOjeQLA=="],+"zip-stream/archiver-utils": ["[email protected]", "", { "dependencies": { "glob": "^7.2.3", "graceful-fs": "^4.2.0", "lazystream": "^1.0.0", "lodash.defaults": "^4.2.0", "lodash.difference": "^4.5.0", "lodash.flatten": "^4.4.0", "lodash.isplainobject": "^4.0.6", "lodash.union": "^4.6.0", "normalize-path": "^3.0.0", "readable-stream": "^3.6.0" } }, "sha512-KVgf4XQVrTjhyWmx6cte4RxonPLR9onExufI1jhvw/MQ4BB6IsZD5gT8Lq+u/+pRkWna/6JoHpiQioaqFP5Rzw=="],"@ai-sdk/vue/@ai-sdk/provider-utils/@ai-sdk/provider": ["@ai-sdk/[email protected]", "", { "dependencies": { "json-schema": "^0.4.0" } }, "sha512-HrEmNt/BH/hkQ7zpi2o6N3k1ZR1QTb7z85WYhYygiTxOQuaml4CMtHCWRbric5WPU+RNsYI7r1EpyVQMKO1pYw=="],@@ -3191,15 +3209,17 @@"@modelcontextprotocol/sdk/ajv/json-schema-traverse": ["[email protected]", "", {}, "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug=="],- "@repo/agent-tools/@types/bun/bun-types": ["[email protected]", "", { "dependencies": { "@types/node": "*" } }, "sha512-iIKw23BspnQQYd3prITOBxeUsxBHnwzX6YJfGMuNOZzeNcMmVqzIIVGRm1l69ogaPQmb4wB6BN8mA5bE9YuC5Q=="],+ "@repo/agent-tools/@types/bun/bun-types": ["[email protected]", "", { "dependencies": { "@types/node": "*" } }, "sha512-loKuVrAFZKfEv+JvWkHRS9GW5IqLuLRjVXN9p+vZvBN86O5hf/pBZQ5hSoyipsrMmWObZBDvWnlmKvjKTM0PdA=="],++ "@repo/auth/@types/bun/bun-types": ["[email protected]", "", { "dependencies": { "@types/node": "*" } }, "sha512-loKuVrAFZKfEv+JvWkHRS9GW5IqLuLRjVXN9p+vZvBN86O5hf/pBZQ5hSoyipsrMmWObZBDvWnlmKvjKTM0PdA=="],- "@repo/auth/@types/bun/bun-types": ["[email protected]", "", { "dependencies": { "@types/node": "*" } }, "sha512-iIKw23BspnQQYd3prITOBxeUsxBHnwzX6YJfGMuNOZzeNcMmVqzIIVGRm1l69ogaPQmb4wB6BN8mA5bE9YuC5Q=="],+ "@repo/crypto/@types/bun/bun-types": ["[email protected]", "", { "dependencies": { "@types/node": "*" } }, "sha512-loKuVrAFZKfEv+JvWkHRS9GW5IqLuLRjVXN9p+vZvBN86O5hf/pBZQ5hSoyipsrMmWObZBDvWnlmKvjKTM0PdA=="],- "@repo/crypto/@types/bun/bun-types": ["[email protected]", "", { "dependencies": { "@types/node": "*" } }, "sha512-iIKw23BspnQQYd3prITOBxeUsxBHnwzX6YJfGMuNOZzeNcMmVqzIIVGRm1l69ogaPQmb4wB6BN8mA5bE9YuC5Q=="],+ "@repo/db/@types/bun/bun-types": ["[email protected]", "", { "dependencies": { "@types/node": "*" } }, "sha512-loKuVrAFZKfEv+JvWkHRS9GW5IqLuLRjVXN9p+vZvBN86O5hf/pBZQ5hSoyipsrMmWObZBDvWnlmKvjKTM0PdA=="],- "@repo/db/@types/bun/bun-types": ["[email protected]", "", { "dependencies": { "@types/node": "*" } }, "sha512-iIKw23BspnQQYd3prITOBxeUsxBHnwzX6YJfGMuNOZzeNcMmVqzIIVGRm1l69ogaPQmb4wB6BN8mA5bE9YuC5Q=="],+ "@repo/mailer/@types/bun/bun-types": ["[email protected]", "", { "dependencies": { "@types/node": "*" } }, "sha512-loKuVrAFZKfEv+JvWkHRS9GW5IqLuLRjVXN9p+vZvBN86O5hf/pBZQ5hSoyipsrMmWObZBDvWnlmKvjKTM0PdA=="],- "@repo/mailer/@types/bun/bun-types": ["[email protected]", "", { "dependencies": { "@types/node": "*" } }, "sha512-iIKw23BspnQQYd3prITOBxeUsxBHnwzX6YJfGMuNOZzeNcMmVqzIIVGRm1l69ogaPQmb4wB6BN8mA5bE9YuC5Q=="],+ "@repo/net/@types/bun/bun-types": ["[email protected]", "", { "dependencies": { "@types/node": "*" } }, "sha512-loKuVrAFZKfEv+JvWkHRS9GW5IqLuLRjVXN9p+vZvBN86O5hf/pBZQ5hSoyipsrMmWObZBDvWnlmKvjKTM0PdA=="],"@scalar/icons/@types/node/undici-types": ["[email protected]", "", {}, "sha512-AsuCzffGHJybSaRrmr5eHr81mwJU3kjw6M+uprWvCXiNeN9SOGwQ3Jn8jb8m3Z6izVgknn1R0FTCEAP2QrLY/w=="],@@ -3213,7 +3233,7 @@"ajv-formats/ajv/json-schema-traverse": ["[email protected]", "", {}, "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug=="],- "api/@types/bun/bun-types": ["[email protected]", "", { "dependencies": { "@types/node": "*" } }, "sha512-iIKw23BspnQQYd3prITOBxeUsxBHnwzX6YJfGMuNOZzeNcMmVqzIIVGRm1l69ogaPQmb4wB6BN8mA5bE9YuC5Q=="],+ "api/@types/bun/bun-types": ["[email protected]", "", { "dependencies": { "@types/node": "*" } }, "sha512-loKuVrAFZKfEv+JvWkHRS9GW5IqLuLRjVXN9p+vZvBN86O5hf/pBZQ5hSoyipsrMmWObZBDvWnlmKvjKTM0PdA=="],"archiver-utils/readable-stream/string_decoder": ["[email protected]", "", { "dependencies": { "safe-buffer": "~5.1.0" } }, "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg=="],@@ -3347,6 +3367,8 @@"unzipper/readable-stream/string_decoder": ["[email protected]", "", { "dependencies": { "safe-buffer": "~5.1.0" } }, "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg=="],+ "worker/@types/bun/bun-types": ["[email protected]", "", { "dependencies": { "@types/node": "*" } }, "sha512-loKuVrAFZKfEv+JvWkHRS9GW5IqLuLRjVXN9p+vZvBN86O5hf/pBZQ5hSoyipsrMmWObZBDvWnlmKvjKTM0PdA=="],+"@typescript-eslint/typescript-estree/minimatch/brace-expansion/balanced-match": ["[email protected]", "", {}, "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA=="],"cmdk/@radix-ui/react-dialog/@radix-ui/react-dismissable-layer/@radix-ui/react-use-callback-ref": ["@radix-ui/[email protected]", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-xCso9j1/u8sEgP1RNHjFrXJLApL8LiqOkI1R4ywuN00rxWdYg4oQXuwKLS3i0j5NWLromUD27/4nlxj2UFVvIw=="],diff --git a/packages/net/eslint.config.mjs b/packages/net/eslint.config.mjsnew file mode 100644index 00000000..f9b96942--- /dev/null+++ b/packages/net/eslint.config.mjs@@ -0,0 +1,4 @@+import { config } from '@repo/eslint-config/base';++/** @type {import("eslint").Linter.Config[]} */+export default config;diff --git a/packages/net/package.json b/packages/net/package.jsonnew file mode 100644index 00000000..99cb0f79--- /dev/null+++ b/packages/net/package.json@@ -0,0 +1,20 @@+{+ "name": "@repo/net",+ "version": "0.0.0",+ "private": true,+ "type": "module",+ "exports": {+ ".": "./src/index.ts"+ },+ "scripts": {+ "lint": "eslint .",+ "typecheck": "tsc --noEmit",+ "test": "bun test"+ },+ "devDependencies": {+ "@repo/eslint-config": "workspace:*",+ "@types/bun": "latest",+ "eslint": "^9.39.0",+ "typescript": "^6.0.3"+ }+}diff --git a/packages/net/src/__tests__/net.test.ts b/packages/net/src/__tests__/net.test.tsnew file mode 100644index 00000000..09fb69c6--- /dev/null+++ b/packages/net/src/__tests__/net.test.ts@@ -0,0 +1,48 @@+import { describe, it, expect } from 'bun:test';+import { isPrivateIp } from '../index';++describe('isPrivateIp', () => {+ it('flags loopback, private, link-local, and CGNAT IPv4', () => {+ for (const ip of [+ '127.0.0.1',+ '10.1.2.3',+ '172.16.0.1',+ '192.168.0.10',+ '169.254.169.254',+ '100.64.0.1',+ '0.0.0.0',+ ]) {+ expect(isPrivateIp(ip)).toBe(true);+ }+ });++ it('passes public IPv4', () => {+ for (const ip of ['8.8.8.8', '1.1.1.1', '172.32.0.1', '100.128.0.1']) {+ expect(isPrivateIp(ip)).toBe(false);+ }+ });++ it('flags loopback, link-local, and unique-local IPv6', () => {+ for (const ip of ['::1', '::', 'fe80::1', 'fd00::1', 'FD00::1']) {+ expect(isPrivateIp(ip)).toBe(true);+ }+ });++ it('flags IPv4-mapped and IPv4-compatible IPv6 carrying a private IPv4', () => {+ for (const ip of [+ '::ffff:127.0.0.1',+ '::ffff:169.254.169.254',+ '::ffff:7f00:1',+ '::ffff:a9fe:a9fe',+ '::FFFF:A9FE:A9FE',+ '::127.0.0.1',+ ]) {+ expect(isPrivateIp(ip)).toBe(true);+ }+ });++ it('passes IPv4-mapped IPv6 carrying a public IPv4', () => {+ expect(isPrivateIp('::ffff:8.8.8.8')).toBe(false);+ expect(isPrivateIp('::ffff:808:808')).toBe(false);+ });+});diff --git a/packages/net/src/__tests__/pinned-fetch.test.ts b/packages/net/src/__tests__/pinned-fetch.test.tsnew file mode 100644index 00000000..16ebc677--- /dev/null+++ b/packages/net/src/__tests__/pinned-fetch.test.ts@@ -0,0 +1,26 @@+import { describe, it, expect } from 'bun:test';+import { pinnedFetch, UrlNotAllowedError } from '../index';++// The guard is strict under NODE_ENV=test, so these exercise the production rules.+describe('pinnedFetch', () => {+ it('rejects a literal private address', async () => {+ await expect(pinnedFetch('https://127.0.0.1/')).rejects.toBeInstanceOf(UrlNotAllowedError);+ await expect(pinnedFetch('https://[::ffff:169.254.169.254]/')).rejects.toBeInstanceOf(+ UrlNotAllowedError,+ );+ });++ it('rejects a public hostname that resolves to a private address', async () => {+ await expect(pinnedFetch('https://localtest.me/')).rejects.toBeInstanceOf(UrlNotAllowedError);+ });++ it('rejects a non-https url', async () => {+ await expect(pinnedFetch('http://example.com/')).rejects.toBeInstanceOf(UrlNotAllowedError);+ });++ it('reaches a public host, with TLS still verified against the hostname', async () => {+ const res = await pinnedFetch('https://example.com/', { timeoutMs: 15_000 });+ expect(res.status).toBe(200);+ expect((await res.text()).length).toBeGreaterThan(0);+ });+});diff --git a/packages/net/src/index.ts b/packages/net/src/index.tsnew file mode 100644index 00000000..3b86f3e5--- /dev/null+++ b/packages/net/src/index.ts@@ -0,0 +1,164 @@+import { lookup } from 'node:dns/promises';+import { request as httpRequest } from 'node:http';+import type { LookupFunction } from 'node:net';+import { request as httpsRequest } from 'node:https';++// SSRF guards for server-side fetches of a user/agent-supplied URL. A URL that+// resolves to a loopback, link-local, or private-range address could reach internal+// services (including the cloud metadata endpoint at 169.254.169.254), so those are+// rejected. The check resolves DNS, so a public hostname that points at a private+// address is caught too.++export class UrlNotAllowedError extends Error {}++// A hostname that is inherently local (not an IP literal).+function isLocalHostname(host: string): boolean {+ return host === 'localhost' || host.endsWith('.local');+}++// IPv4-mapped and IPv4-compatible IPv6 addresses (`::ffff:127.0.0.1`, `::ffff:7f00:1`,+// `::127.0.0.1`) reach the same host as the IPv4 they carry, so they are compared as+// that IPv4 rather than as an IPv6 the range checks below would not recognise.+function toIpv4(ip: string): string {+ const embedded = ip.match(/^::(?:ffff:)?(.+)$/);+ if (!embedded) return ip;+ const rest = embedded[1]!;+ if (/^\d{1,3}(\.\d{1,3}){3}$/.test(rest)) return rest;+ const hex = rest.match(/^([0-9a-f]{1,4}):([0-9a-f]{1,4})$/);+ if (!hex) return ip;+ const n = ((parseInt(hex[1]!, 16) << 16) | parseInt(hex[2]!, 16)) >>> 0;+ return [n >>> 24, (n >>> 16) & 255, (n >>> 8) & 255, n & 255].join('.');+}++// An IPv4/IPv6 address in a loopback, link-local, or private range.+export function isPrivateIp(ip: string): boolean {+ const normalized = toIpv4(ip.toLowerCase());+ const v4 = normalized.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/);+ if (v4) {+ const [a, b] = [Number(v4[1]), Number(v4[2])];+ return (+ a === 0 ||+ a === 127 || // loopback+ a === 10 || // private+ (a === 172 && b >= 16 && b <= 31) || // private+ (a === 192 && b === 168) || // private+ (a === 169 && b === 254) || // link-local (incl. cloud metadata)+ (a === 100 && b >= 64 && b <= 127) // CGNAT+ );+ }+ return (+ normalized === '::1' || // loopback+ normalized === '::' ||+ normalized.startsWith('fe80:') || // link-local+ /^f[cd][0-9a-f]{2}:/.test(normalized) // unique local+ );+}++interface Pin {+ address: string;+ family: number;+}++// Validates the URL and resolves its hostname once. `pin` is the address the caller+// must connect to; it is absent only when the host is already an IP literal.+async function vet(raw: string): Promise<{ url: URL; pin?: Pin }> {+ let url: URL;+ try {+ url = new URL(raw);+ } catch {+ throw new UrlNotAllowedError('url must be a valid URL');+ }++ const devRelaxed = process.env.NODE_ENV !== 'production' && process.env.NODE_ENV !== 'test';+ if (url.protocol !== 'https:' && !(devRelaxed && url.protocol === 'http:')) {+ throw new UrlNotAllowedError('url must use https');+ }++ const host = url.hostname.toLowerCase().replace(/^\[|\]$/g, '');+ if (isLocalHostname(host) || isPrivateIp(host)) {+ if (!devRelaxed) {+ throw new UrlNotAllowedError('url must not point to a private or local address');+ }+ return { url };+ }++ let addrs: Pin[];+ try {+ addrs = await lookup(host, { all: true });+ } catch {+ throw new UrlNotAllowedError('url host could not be resolved');+ }+ if (addrs.some((a) => isPrivateIp(a.address)) && !devRelaxed) {+ throw new UrlNotAllowedError('url must not point to a private or local address');+ }+ return { url, pin: addrs[0] };+}++// Validates a user/agent-supplied URL for a server-side fetch: http(s) only, and it+// must not resolve to a local/private address. Returns the parsed URL. http is+// allowed only in local development; production and tests require https. Throws+// UrlNotAllowedError on any failure.+export async function assertPublicHttpUrl(raw: string): Promise<URL> {+ return (await vet(raw)).url;+}++export interface PinnedRequestInit {+ method?: string;+ headers?: Record<string, string> | Headers;+ body?: string | Buffer;+ timeoutMs?: number;+}++// Validates the URL, then connects to the address that validation resolved instead of+// resolving the hostname a second time. Without the pin, a name that answers publicly+// during the check and privately during the connection (DNS rebinding) would defeat+// it. TLS still verifies against the hostname, so pinning does not weaken the+// certificate check. Redirects are never followed: the 3xx is returned as-is, so a+// caller cannot be steered to an address that was never validated.+export async function pinnedFetch(raw: string, init: PinnedRequestInit = {}): Promise<Response> {+ const { url, pin } = await vet(raw);+ const send = url.protocol === 'https:' ? httpsRequest : httpRequest;+ const headers =+ init.headers instanceof Headers ? Object.fromEntries(init.headers) : (init.headers ?? {});++ return new Promise<Response>((resolve, reject) => {+ const req = send(+ url,+ {+ method: init.method ?? 'GET',+ headers,+ ...(pin+ ? {+ lookup: ((_host, options, cb) => {+ if (options.all) cb(null, [pin]);+ else cb(null, pin.address, pin.family);+ }) as LookupFunction,+ }+ : {}),+ },+ (res) => {+ const chunks: Buffer[] = [];+ res.on('data', (chunk: Buffer) => chunks.push(chunk));+ res.on('error', reject);+ res.on('end', () => {+ const status = res.statusCode ?? 502;+ // Response rejects a body on these statuses; the receiver sent none anyway.+ const empty = status < 200 || status === 204 || status === 205 || status === 304;+ resolve(+ new Response(empty ? null : Buffer.concat(chunks), {+ status,+ headers: Object.entries(res.headers).flatMap(([k, v]) =>+ v == null ? [] : [[k, Array.isArray(v) ? v.join(', ') : v] as [string, string]],+ ),+ }),+ );+ });+ },+ );+ req.on('error', reject);+ if (init.timeoutMs) {+ req.setTimeout(init.timeoutMs, () => req.destroy(new Error('request timed out')));+ }+ req.end(init.body);+ });+}diff --git a/packages/net/tsconfig.json b/packages/net/tsconfig.jsonnew file mode 100644index 00000000..12ec9a86--- /dev/null+++ b/packages/net/tsconfig.json@@ -0,0 +1,7 @@+{+ "extends": "../../tsconfig.base.json",+ "compilerOptions": {+ "types": ["bun"]+ },+ "include": ["src"]+}