From d948887d1cf9c5f75c15458f6343e28e4e934342 Mon Sep 17 00:00:00 2001 From: ComRobertSoftwareLabsIncon Date: Fri, 4 Dec 2026 14:33:13 +0000 Subject: [PATCH 01/75] docs: publish v1.0.0 project documentation --- README.md | 75 +++++++++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 73 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 1bb1e3b..21cba61 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,73 @@ -# ChatGPT_Intelligence_Bridge -ChatGPT integration Apple Intelligence & Siri. +# ChatGPT Intelligence Bridge — v1.0.0 + +Robert Software Labs +Runtime: iPhone Apple Shortcuts + HTTPS TypeScript service +Strategy: Hybrid (on-device model first, ChatGPT API only when needed) +Output: Siri speaks the final answer + +## Platform boundary + +Apple Shortcuts does not execute TypeScript directly. The iPhone Shortcut calls this TypeScript service over HTTPS, so the service must run on a Node.js host. + +The JSON files in `shortcuts/` are manifests and build instructions, not importable `.shortcut` files. iOS has no supported universal JSON-to-Shortcut importer. + +The on-device Qwen / Apple Intelligence step runs inside Shortcuts using a model action exposed by iOS. Only a result beginning with `NEED_CLOUD` triggers the OpenAI API fallback. + +## Request flow + +1. Siri starts the Shortcut and dictates the request. +2. Shortcuts invokes **Use Model**, selecting Qwen if available or another on-device model exposed by iOS. +3. The model answers locally where possible; when remote information or stronger cloud reasoning is required, it begins with `NEED_CLOUD`. +4. Shortcuts sends `text` and `local_result` to `POST /v1/bridge`. +5. The service returns the local answer or calls OpenAI's Responses API. +6. Shortcuts extracts `spoken_text` and invokes **Speak Text**. + +The Bridge does not open the ChatGPT app. It uses the OpenAI API, billed separately from a ChatGPT subscription. + +## Project layout + +- `src/server.ts`: dependency-free Node.js HTTP service. +- `src/bridge.ts`: local/cloud routing policy. +- `src/openai.ts`: OpenAI Responses API adapter. +- `src/types.ts`: request and response contracts. +- `config/`: bridge, provider and privacy configuration. +- `shortcuts/`: action manifest, local prompt and request example. + +## Requirements and deployment + +- Node.js 20+ +- HTTPS hosting +- `OPENAI_API_KEY` and `BRIDGE_TOKEN` configured as host-side secrets +- Optional `OPENAI_MODEL` and host-provided `PORT` + +Run: + +```bash +npm install +npm run build +npm start +``` + +Never commit secrets or place them in Shortcut URLs. Keep `OPENAI_API_KEY` on the server and the separate `BRIDGE_TOKEN` in the Shortcut's Authorization header. + +## Build the Shortcut on iPhone + +Create a Shortcut named **ChatGPT Intelligence Bridge**: + +1. **Dictate Text** → save as `UserRequest`. +2. **Use Model** → select Qwen if available, otherwise an iOS-exposed on-device model; use `shortcuts/local-model-prompt.txt` and save as `LocalResult`. +3. **Get Contents of URL** → POST to `https://YOUR-HOST.example/v1/bridge`, with JSON body keys `text`, `local_result`, and `session_id`; set `Content-Type: application/json` and `Authorization: Bearer YOUR_BRIDGE_TOKEN`. +4. Extract `spoken_text` from the response. +5. **Speak Text** using that value. + +Insert Shortcuts variables with the variable picker rather than typing their names as literal strings. Siri confirmations and privacy prompts remain controlled by iOS. + +## Behaviour and limitations + +- A normal local answer is returned without calling OpenAI. +- Only the `NEED_CLOUD` prefix triggers cloud fallback. +- The service uses `/v1/responses`. +- It does not call private Siri or Apple Intelligence frameworks. +- It cannot bypass iOS permission prompts or privacy indicators. +- Do not send passwords, authentication codes, financial secrets or sensitive personal data to the cloud. +- The server is stateless and does not persist conversation history or log prompt contents. From 70ac9e39b2329f24c564b7a22b0c1d1369b27dd4 Mon Sep 17 00:00:00 2001 From: ComRobertSoftwareLabsIncon Date: Fri, 4 Dec 2026 14:33:24 +0000 Subject: [PATCH 02/75] chore: publish source file package.json --- package.json | 1 + 1 file changed, 1 insertion(+) create mode 100644 package.json diff --git a/package.json b/package.json new file mode 100644 index 0000000..fd72c52 --- /dev/null +++ b/package.json @@ -0,0 +1 @@ +{"name":"chatgpt-intelligence-bridge","version":"1.0.0","private":true,"type":"module","engines":{"node":">=20"},"scripts":{"build":"tsc -p tsconfig.json","start":"node dist/server.js","dev":"tsx watch src/server.ts"},"devDependencies":{"@types/node":"^22.0.0","tsx":"^4.19.0","typescript":"^5.7.0"}} \ No newline at end of file From 13febaef1c03cc11c25265abd08fd791ef2ed19e Mon Sep 17 00:00:00 2001 From: ComRobertSoftwareLabsIncon Date: Fri, 4 Dec 2026 14:33:26 +0000 Subject: [PATCH 03/75] chore: publish source file tsconfig.json --- tsconfig.json | 1 + 1 file changed, 1 insertion(+) create mode 100644 tsconfig.json diff --git a/tsconfig.json b/tsconfig.json new file mode 100644 index 0000000..7fc12b2 --- /dev/null +++ b/tsconfig.json @@ -0,0 +1 @@ +{"compilerOptions":{"target":"ES2022","module":"NodeNext","moduleResolution":"NodeNext","rootDir":"src","outDir":"dist","strict":true,"esModuleInterop":true,"skipLibCheck":true,"forceConsistentCasingInFileNames":true},"include":["src/**/*.ts"]} \ No newline at end of file From f9aa8548d9aac5f8398c302efa3a0ecb5d464af9 Mon Sep 17 00:00:00 2001 From: ComRobertSoftwareLabsIncon Date: Fri, 4 Dec 2026 14:33:28 +0000 Subject: [PATCH 04/75] chore: publish source file src/types.ts --- src/types.ts | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 src/types.ts diff --git a/src/types.ts b/src/types.ts new file mode 100644 index 0000000..03f606a --- /dev/null +++ b/src/types.ts @@ -0,0 +1,3 @@ +export interface BridgeRequest { text: string; local_result: string; session_id?: string; } +export interface BridgeResponse { ok: boolean; route: "local" | "openai"; spoken_text: string; request_id: string; } +export interface OpenAIResponsesPayload { model: string; input: Array<{ role: "system" | "user"; content: string }>; max_output_tokens: number; } \ No newline at end of file From 922b2ff7974b21a85f230f56da83f63dda4da445 Mon Sep 17 00:00:00 2001 From: ComRobertSoftwareLabsIncon Date: Fri, 4 Dec 2026 14:33:30 +0000 Subject: [PATCH 05/75] chore: publish source file src/bridge.ts --- src/bridge.ts | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 src/bridge.ts diff --git a/src/bridge.ts b/src/bridge.ts new file mode 100644 index 0000000..97a9cdf --- /dev/null +++ b/src/bridge.ts @@ -0,0 +1,18 @@ +import { randomUUID } from "node:crypto"; +import { askOpenAI } from "./openai.js"; +import type { BridgeRequest, BridgeResponse } from "./types.js"; +const MAX_INPUT = 12_000; +const MAX_LOCAL = 16_000; +const CLOUD_MARKER = "NEED_CLOUD"; +export async function handleBridge(input: BridgeRequest): Promise { + const text = input.text.trim(); + const localResult = input.local_result.trim(); + if (!text) throw new Error("text is required"); + if (text.length > MAX_INPUT) throw new Error("text exceeds maximum length"); + if (localResult.length > MAX_LOCAL) throw new Error("local_result exceeds maximum length"); + const requestId = randomUUID(); + const needsCloud = localResult.toUpperCase().startsWith(CLOUD_MARKER); + if (!needsCloud && localResult) return { ok: true, route: "local", spoken_text: localResult, request_id: requestId }; + const answer = await askOpenAI(text); + return { ok: true, route: "openai", spoken_text: answer, request_id: requestId }; +} \ No newline at end of file From 6bdea050f4402cda809c3fb9a29f75fe268dd3be Mon Sep 17 00:00:00 2001 From: ComRobertSoftwareLabsIncon Date: Fri, 4 Dec 2026 14:33:32 +0000 Subject: [PATCH 06/75] chore: publish source file src/openai.ts --- src/openai.ts | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 src/openai.ts diff --git a/src/openai.ts b/src/openai.ts new file mode 100644 index 0000000..a3141b0 --- /dev/null +++ b/src/openai.ts @@ -0,0 +1,14 @@ +import type { OpenAIResponsesPayload } from "./types.js"; +const OPENAI_URL = "https://api.openai.com/v1/responses"; +type ResponsesApiResult = { output?: Array<{ type?: string; content?: Array<{ type?: string; text?: string }> }>; output_text?: string; }; +export async function askOpenAI(userText: string): Promise { + const apiKey = process.env.OPENAI_API_KEY; + if (!apiKey) throw new Error("OPENAI_API_KEY is not configured"); + const payload: OpenAIResponsesPayload = { model: process.env.OPENAI_MODEL || "gpt-6-luna", max_output_tokens: 700, input: [{ role: "system", content: "You are the cloud fallback for a voice assistant. Answer clearly and concisely. Do not claim to have performed actions you cannot perform. If a request requires an external action, explain what is needed." }, { role: "user", content: userText }] }; + const response = await fetch(OPENAI_URL, { method: "POST", headers: { Authorization: `Bearer ${apiKey}`, "Content-Type": "application/json" }, body: JSON.stringify(payload), signal: AbortSignal.timeout(25_000) }); + if (!response.ok) { const detail = await response.text(); throw new Error(`OpenAI API returned ${response.status}: ${detail.slice(0, 500)}`); } + const data = await response.json() as ResponsesApiResult; + const outputText = data.output_text ?? data.output?.flatMap(item => item.content ?? []).filter(part => part.type === "output_text" && typeof part.text === "string").map(part => part.text).join("\n"); + if (!outputText?.trim()) throw new Error("OpenAI returned an empty response"); + return outputText.trim(); +} \ No newline at end of file From 7234a3987313c86d816a017f0aa109364e5544c2 Mon Sep 17 00:00:00 2001 From: ComRobertSoftwareLabsIncon Date: Fri, 4 Dec 2026 14:33:34 +0000 Subject: [PATCH 07/75] chore: publish source file src/server.ts --- src/server.ts | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 src/server.ts diff --git a/src/server.ts b/src/server.ts new file mode 100644 index 0000000..ec364c3 --- /dev/null +++ b/src/server.ts @@ -0,0 +1,34 @@ +import { createServer } from "node:http"; +import { timingSafeEqual } from "node:crypto"; +import { handleBridge } from "./bridge.js"; +import type { BridgeRequest } from "./types.js"; +const PORT = Number(process.env.PORT || 3000); +const MAX_BODY_BYTES = 64 * 1024; +function isAuthorized(header: string | undefined): boolean { + const expected = process.env.BRIDGE_TOKEN; + if (!expected || !header?.startsWith("Bearer ")) return false; + const supplied = Buffer.from(header.slice(7)); + const target = Buffer.from(expected); + return supplied.length === target.length && timingSafeEqual(supplied, target); +} +const server = createServer(async (req, res) => { + res.setHeader("Content-Type", "application/json; charset=utf-8"); + res.setHeader("Cache-Control", "no-store"); + if (req.method === "GET" && req.url === "/health") { res.writeHead(200).end(JSON.stringify({ ok: true, service: "chatgpt-intelligence-bridge" })); return; } + if (req.method !== "POST" || req.url !== "/v1/bridge") { res.writeHead(404).end(JSON.stringify({ ok: false, error: "Not found" })); return; } + if (!isAuthorized(req.headers.authorization)) { res.writeHead(401).end(JSON.stringify({ ok: false, error: "Unauthorized" })); return; } + try { + const chunks: Buffer[] = []; let size = 0; + for await (const chunk of req) { const part = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk); size += part.length; if (size > MAX_BODY_BYTES) { res.writeHead(413).end(JSON.stringify({ ok: false, error: "Payload too large" })); return; } chunks.push(part); } + const body = JSON.parse(Buffer.concat(chunks).toString("utf8")) as Partial; + if (typeof body.text !== "string" || typeof body.local_result !== "string") { res.writeHead(400).end(JSON.stringify({ ok: false, error: "text and local_result are required strings" })); return; } + const result = await handleBridge({ text: body.text, local_result: body.local_result, session_id: typeof body.session_id === "string" ? body.session_id : undefined }); + res.writeHead(200).end(JSON.stringify(result)); + } catch (error) { + const message = error instanceof Error ? error.message : "Internal error"; + const status = message.includes("required") || message.includes("maximum") ? 400 : 502; + console.error(JSON.stringify({ event: "bridge_error", message: message.slice(0, 300) })); + res.writeHead(status).end(JSON.stringify({ ok: false, error: "Bridge request failed" })); + } +}); +server.listen(PORT, () => console.log(`ChatGPT Intelligence Bridge listening on port ${PORT}`)); \ No newline at end of file From f9300411713b3bd78756e6308b8b0ce277ae26e4 Mon Sep 17 00:00:00 2001 From: ComRobertSoftwareLabsIncon Date: Fri, 4 Dec 2026 14:33:36 +0000 Subject: [PATCH 08/75] chore: publish source file config/bridge.config.json --- config/bridge.config.json | 1 + 1 file changed, 1 insertion(+) create mode 100644 config/bridge.config.json diff --git a/config/bridge.config.json b/config/bridge.config.json new file mode 100644 index 0000000..48bb8fc --- /dev/null +++ b/config/bridge.config.json @@ -0,0 +1 @@ +{"name":"ChatGPT Intelligence Bridge","version":"1.0.0","owner":"Robert Software Labs","runtime":"apple-shortcuts-plus-https-typescript","strategy":"hybrid","execution_order":["on_device_model","openai_responses_api"],"cloud_trigger":"local_result_starts_with_NEED_CLOUD","response_channel":"siri_speak_text","session_storage":"stateless","max_input_characters":12000,"max_local_result_characters":16000,"request_timeout_ms":30000} \ No newline at end of file From f8818678c8e5a8102f09d1da51dacf5f1fcea260 Mon Sep 17 00:00:00 2001 From: ComRobertSoftwareLabsIncon Date: Fri, 4 Dec 2026 14:33:38 +0000 Subject: [PATCH 09/75] chore: publish source file config/providers.json --- config/providers.json | 1 + 1 file changed, 1 insertion(+) create mode 100644 config/providers.json diff --git a/config/providers.json b/config/providers.json new file mode 100644 index 0000000..5dc0f6e --- /dev/null +++ b/config/providers.json @@ -0,0 +1 @@ +{"providers":[{"id":"qwen-on-device","type":"shortcuts-use-model","priority":1,"execution_location":"iphone","enabled":true,"role":"local_first","notes":"Selected in the iOS Shortcuts Use Model action when exposed by the device."},{"id":"apple-intelligence","type":"shortcuts-use-model","priority":2,"execution_location":"iphone","enabled":true,"role":"on_device_or_system_model_fallback","notes":"Use only if available in the device's Shortcuts model picker."},{"id":"openai-responses","type":"https","priority":3,"execution_location":"bridge-server","endpoint":"https://api.openai.com/v1/responses","enabled":true,"role":"cloud_fallback","secret_env":"OPENAI_API_KEY"}]} \ No newline at end of file From 90db6d1b314f97526d01020f99f61fe089cffd73 Mon Sep 17 00:00:00 2001 From: ComRobertSoftwareLabsIncon Date: Fri, 4 Dec 2026 14:33:40 +0000 Subject: [PATCH 10/75] chore: publish source file config/privacy.policy.json --- config/privacy.policy.json | 1 + 1 file changed, 1 insertion(+) create mode 100644 config/privacy.policy.json diff --git a/config/privacy.policy.json b/config/privacy.policy.json new file mode 100644 index 0000000..f7c1f65 --- /dev/null +++ b/config/privacy.policy.json @@ -0,0 +1 @@ +{"version":"1.0","principles":["local_first","data_minimisation","no_prompt_logging","secrets_server_side"],"cloud_transfer":{"enabled_only_when":"local_result begins with NEED_CLOUD","payload_fields":["text"],"exclude_fields":["device_identifiers","contacts","location","files","credentials"]},"retention":{"request_body":"not_persisted","application_logs":"metadata_only"},"user_controls":{"cloud_fallback_can_be_disabled":true,"siri_prompts_and_permissions":"controlled_by_ios"}} \ No newline at end of file From 96c8014cdbd5a4caefe76ff89e1333d9bbf3db58 Mon Sep 17 00:00:00 2001 From: ComRobertSoftwareLabsIncon Date: Fri, 4 Dec 2026 14:33:42 +0000 Subject: [PATCH 11/75] chore: publish source file shortcuts/request.example.json --- shortcuts/request.example.json | 1 + 1 file changed, 1 insertion(+) create mode 100644 shortcuts/request.example.json diff --git a/shortcuts/request.example.json b/shortcuts/request.example.json new file mode 100644 index 0000000..e480a52 --- /dev/null +++ b/shortcuts/request.example.json @@ -0,0 +1 @@ +{"text":"Explique resumidamente o que é uma API.","local_result":"Uma API é uma interface que permite que sistemas diferentes troquem informações e solicitem funções entre si.","session_id":"replace-with-a-random-installation-id"} \ No newline at end of file From ce1fe015fc7d4c578e2b7066ff2e9ad4e760ef28 Mon Sep 17 00:00:00 2001 From: ComRobertSoftwareLabsIncon Date: Fri, 4 Dec 2026 14:33:46 +0000 Subject: [PATCH 12/75] chore: publish source file shortcuts/local-model-prompt.txt --- shortcuts/local-model-prompt.txt | 10 ++++++++++ 1 file changed, 10 insertions(+) create mode 100644 shortcuts/local-model-prompt.txt diff --git a/shortcuts/local-model-prompt.txt b/shortcuts/local-model-prompt.txt new file mode 100644 index 0000000..4cc1092 --- /dev/null +++ b/shortcuts/local-model-prompt.txt @@ -0,0 +1,10 @@ +You are the on-device, privacy-first assistant in ChatGPT Intelligence Bridge. + +Answer locally whenever possible. Do not claim to have current web access, remote knowledge, or capabilities unavailable in this on-device context. + +If the request genuinely requires remote information or cloud reasoning unavailable locally, output exactly this prefix on the first line: +NEED_CLOUD + +After that prefix, do not include an answer. The Bridge sends only the user's original text to the configured cloud provider. + +Otherwise, provide a concise, useful answer without any routing marker. \ No newline at end of file From f225cbcb79c930ae80694989a44a7bc80f97b08e Mon Sep 17 00:00:00 2001 From: ComRobertSoftwareLabsIncon Date: Fri, 4 Dec 2026 14:33:48 +0000 Subject: [PATCH 13/75] chore: publish source file .gitignore --- .gitignore | 6 ++++++ 1 file changed, 6 insertions(+) create mode 100644 .gitignore diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..ff25022 --- /dev/null +++ b/.gitignore @@ -0,0 +1,6 @@ +node_modules/ +dist/ +.env +.env.* +!.env.example +*.log \ No newline at end of file From bb45c112f34faa4711870af0f849a2f591006976 Mon Sep 17 00:00:00 2001 From: ComRobertSoftwareLabsIncon Date: Fri, 4 Dec 2026 14:33:50 +0000 Subject: [PATCH 14/75] chore: publish source file .env.example --- .env.example | 4 ++++ 1 file changed, 4 insertions(+) create mode 100644 .env.example diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..f3609b7 --- /dev/null +++ b/.env.example @@ -0,0 +1,4 @@ +PORT=3000 +OPENAI_API_KEY= +BRIDGE_TOKEN= +OPENAI_MODEL= \ No newline at end of file From e24e8b9fa781ef1cc505d7b13a38bcac365a59fb Mon Sep 17 00:00:00 2001 From: ComRobertSoftwareLabsIncon Date: Fri, 4 Dec 2026 14:33:56 +0000 Subject: [PATCH 15/75] docs: publish iOS Shortcut action manifest --- shortcuts/shortcut-manifest.json | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 shortcuts/shortcut-manifest.json diff --git a/shortcuts/shortcut-manifest.json b/shortcuts/shortcut-manifest.json new file mode 100644 index 0000000..004929e --- /dev/null +++ b/shortcuts/shortcut-manifest.json @@ -0,0 +1,14 @@ +{ + "name": "ChatGPT Intelligence Bridge", + "invocation": "Siri", + "platform": "iOS Shortcuts", + "is_importable_shortcut": false, + "steps": [ + {"index":1,"action":"Dictate Text","output_variable":"UserRequest"}, + {"index":2,"action":"Use Model","model_selection":"Qwen if available; otherwise an iOS-exposed on-device model","prompt_file":"local-model-prompt.txt","output_variable":"LocalResult"}, + {"index":3,"action":"Get Contents of URL","method":"POST","url":"https://YOUR-HOST.example/v1/bridge","headers":{"Content-Type":"application/json","Authorization":"Bearer YOUR_BRIDGE_TOKEN"},"json_body":{"text":"UserRequest variable","local_result":"LocalResult variable","session_id":"YOUR_RANDOM_SHORTCUT_SESSION_ID"},"output_variable":"BridgeResponse"}, + {"index":4,"action":"Get Dictionary Value","dictionary":"BridgeResponse","key":"spoken_text","output_variable":"SpokenText"}, + {"index":5,"action":"Speak Text","input_variable":"SpokenText"} + ], + "notes":["Use Shortcuts variable insertion, not literal variable-name strings.","Set the Bridge URL and token after deployment.","iOS may show model, network, or privacy confirmations.","Use Model labels and model choices vary by iOS version and device."] +} \ No newline at end of file From bde7f91a3af2ea405a7c4920f22687e5ab7fc06f Mon Sep 17 00:00:00 2001 From: ComRobertSoftwareLabsIncon Date: Fri, 4 Dec 2026 14:33:59 +0000 Subject: [PATCH 16/75] fix: require explicit local routing result before cloud fallback --- src/bridge.ts | 23 +++++++++++++++++++++-- 1 file changed, 21 insertions(+), 2 deletions(-) diff --git a/src/bridge.ts b/src/bridge.ts index 97a9cdf..b9ac060 100644 --- a/src/bridge.ts +++ b/src/bridge.ts @@ -1,18 +1,37 @@ import { randomUUID } from "node:crypto"; import { askOpenAI } from "./openai.js"; import type { BridgeRequest, BridgeResponse } from "./types.js"; + const MAX_INPUT = 12_000; const MAX_LOCAL = 16_000; const CLOUD_MARKER = "NEED_CLOUD"; + export async function handleBridge(input: BridgeRequest): Promise { const text = input.text.trim(); const localResult = input.local_result.trim(); + if (!text) throw new Error("text is required"); if (text.length > MAX_INPUT) throw new Error("text exceeds maximum length"); + if (!localResult) throw new Error("local_result is required"); if (localResult.length > MAX_LOCAL) throw new Error("local_result exceeds maximum length"); + const requestId = randomUUID(); const needsCloud = localResult.toUpperCase().startsWith(CLOUD_MARKER); - if (!needsCloud && localResult) return { ok: true, route: "local", spoken_text: localResult, request_id: requestId }; + + if (!needsCloud) { + return { + ok: true, + route: "local", + spoken_text: localResult, + request_id: requestId + }; + } + const answer = await askOpenAI(text); - return { ok: true, route: "openai", spoken_text: answer, request_id: requestId }; + return { + ok: true, + route: "openai", + spoken_text: answer, + request_id: requestId + }; } \ No newline at end of file From 51e8c4f7a17255eb47d30742b8ae75302514d3a7 Mon Sep 17 00:00:00 2001 From: ComRobertSoftwareLabsIncon Date: Fri, 4 Dec 2026 14:45:44 +0000 Subject: [PATCH 17/75] Make cloud fallback injectable for routing tests --- src/bridge.ts | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/src/bridge.ts b/src/bridge.ts index b9ac060..b2afd28 100644 --- a/src/bridge.ts +++ b/src/bridge.ts @@ -6,7 +6,12 @@ const MAX_INPUT = 12_000; const MAX_LOCAL = 16_000; const CLOUD_MARKER = "NEED_CLOUD"; -export async function handleBridge(input: BridgeRequest): Promise { +type CloudFallback = (text: string) => Promise; + +export async function handleBridge( + input: BridgeRequest, + cloudFallback: CloudFallback = askOpenAI +): Promise { const text = input.text.trim(); const localResult = input.local_result.trim(); @@ -27,11 +32,11 @@ export async function handleBridge(input: BridgeRequest): Promise Date: Fri, 4 Dec 2026 14:45:46 +0000 Subject: [PATCH 18/75] Add automated test script --- package.json | 19 ++++++++++++++++++- 1 file changed, 18 insertions(+), 1 deletion(-) diff --git a/package.json b/package.json index fd72c52..ece5225 100644 --- a/package.json +++ b/package.json @@ -1 +1,18 @@ -{"name":"chatgpt-intelligence-bridge","version":"1.0.0","private":true,"type":"module","engines":{"node":">=20"},"scripts":{"build":"tsc -p tsconfig.json","start":"node dist/server.js","dev":"tsx watch src/server.ts"},"devDependencies":{"@types/node":"^22.0.0","tsx":"^4.19.0","typescript":"^5.7.0"}} \ No newline at end of file +{ + "name": "chatgpt-intelligence-bridge", + "version": "1.0.0", + "private": true, + "type": "module", + "engines": { "node": ">=20" }, + "scripts": { + "build": "tsc -p tsconfig.json", + "test": "tsx --test tests/*.test.ts", + "start": "node dist/server.js", + "dev": "tsx watch src/server.ts" + }, + "devDependencies": { + "@types/node": "^22.0.0", + "tsx": "^4.19.0", + "typescript": "^5.7.0" + } +} From 472aa4abadb0fce9d95b595dfe2c5ab5b4a9afa6 Mon Sep 17 00:00:00 2001 From: ComRobertSoftwareLabsIncon Date: Fri, 4 Dec 2026 14:45:49 +0000 Subject: [PATCH 19/75] Add automated bridge routing tests --- tests/bridge.test.ts | 75 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 75 insertions(+) create mode 100644 tests/bridge.test.ts diff --git a/tests/bridge.test.ts b/tests/bridge.test.ts new file mode 100644 index 0000000..5f3002f --- /dev/null +++ b/tests/bridge.test.ts @@ -0,0 +1,75 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { handleBridge } from "../src/bridge.js"; +import type { BridgeRequest } from "../src/types.js"; + +const request: BridgeRequest = { + text: "Olá, CIB", + local_result: "Resposta local" +}; + +test("uses the local result without calling the cloud fallback", async () => { + let cloudCalls = 0; + const result = await handleBridge(request, async () => { + cloudCalls += 1; + return "Resposta da nuvem"; + }); + + assert.equal(result.ok, true); + assert.equal(result.route, "local"); + assert.equal(result.spoken_text, "Resposta local"); + assert.equal(cloudCalls, 0); + assert.ok(result.request_id.length > 0); +}); + +test("calls the cloud fallback only when NEED_CLOUD is explicit", async () => { + let receivedText = ""; + const result = await handleBridge( + { ...request, local_result: "NEED_CLOUD: não consegui responder localmente" }, + async (text) => { + receivedText = text; + return "Resposta da nuvem"; + } + ); + + assert.equal(result.route, "openai"); + assert.equal(result.spoken_text, "Resposta da nuvem"); + assert.equal(receivedText, request.text); +}); + +test("accepts the NEED_CLOUD marker case-insensitively", async () => { + const result = await handleBridge( + { ...request, local_result: "need_cloud: fallback" }, + async () => "Cloud answer" + ); + + assert.equal(result.route, "openai"); +}); + +test("rejects an empty user prompt", async () => { + await assert.rejects( + handleBridge({ ...request, text: " " }), + /text is required/ + ); +}); + +test("rejects an empty local result", async () => { + await assert.rejects( + handleBridge({ ...request, local_result: " " }), + /local_result is required/ + ); +}); + +test("rejects a user prompt above the configured limit", async () => { + await assert.rejects( + handleBridge({ ...request, text: "x".repeat(12_001) }), + /text exceeds maximum length/ + ); +}); + +test("rejects a local result above the configured limit", async () => { + await assert.rejects( + handleBridge({ ...request, local_result: "x".repeat(16_001) }), + /local_result exceeds maximum length/ + ); +}); From 7aac97914f73d5451137646ba2129fab7b74c2a3 Mon Sep 17 00:00:00 2001 From: ComRobertSoftwareLabsIncon Date: Fri, 4 Dec 2026 14:46:07 +0000 Subject: [PATCH 20/75] Run CIB automated tests and build in GitHub Actions --- .github/workflows/ci.yml | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 .github/workflows/ci.yml diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..0b038d1 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,20 @@ +name: CIB CI + +on: + pull_request: + branches: [main] + push: + branches: [implementation/v1.0.1-foundation] + +jobs: + test-and-build: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: 22 + cache: npm + - run: npm install + - run: npm test + - run: npm run build From 65621b72df1af8c2dbec86b3e61ba1e0518e9cef Mon Sep 17 00:00:00 2001 From: ComRobertSoftwareLabsIncon Date: Fri, 4 Dec 2026 14:47:15 +0000 Subject: [PATCH 21/75] Fix CI setup by removing npm cache without lockfile --- .github/workflows/ci.yml | 1 - 1 file changed, 1 deletion(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 0b038d1..9760acd 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -14,7 +14,6 @@ jobs: - uses: actions/setup-node@v4 with: node-version: 22 - cache: npm - run: npm install - run: npm test - run: npm run build From d695f435193dd75e5de5cba3671676bb4a9b46fd Mon Sep 17 00:00:00 2001 From: ComRobertSoftwareLabsIncon Date: Fri, 4 Dec 2026 14:49:20 +0000 Subject: [PATCH 22/75] Add strict bridge request validation --- src/validation.ts | 54 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 src/validation.ts diff --git a/src/validation.ts b/src/validation.ts new file mode 100644 index 0000000..4737376 --- /dev/null +++ b/src/validation.ts @@ -0,0 +1,54 @@ +import type { BridgeRequest } from "./types.js"; + +const MAX_INPUT = 12_000; +const MAX_LOCAL = 16_000; +const MAX_SESSION_ID = 128; + +export class RequestValidationError extends Error { + constructor(message: string) { + super(message); + this.name = "RequestValidationError"; + } +} + +export function parseBridgeRequest(value: unknown): BridgeRequest { + if (typeof value !== "object" || value === null || Array.isArray(value)) { + throw new RequestValidationError("request body must be a JSON object"); + } + + const body = value as Record; + const allowedKeys = new Set(["text", "local_result", "session_id"]); + if (Object.keys(body).some((key) => !allowedKeys.has(key))) { + throw new RequestValidationError("request contains unsupported fields"); + } + + if (typeof body.text !== "string" || !body.text.trim()) { + throw new RequestValidationError("text is required"); + } + if (body.text.trim().length > MAX_INPUT) { + throw new RequestValidationError("text exceeds maximum length"); + } + + if (typeof body.local_result !== "string" || !body.local_result.trim()) { + throw new RequestValidationError("local_result is required"); + } + if (body.local_result.trim().length > MAX_LOCAL) { + throw new RequestValidationError("local_result exceeds maximum length"); + } + + if (body.session_id !== undefined) { + if ( + typeof body.session_id !== "string" || + body.session_id.length > MAX_SESSION_ID || + /[\u0000-\u001f\u007f]/.test(body.session_id) + ) { + throw new RequestValidationError("session_id is invalid"); + } + } + + return { + text: body.text, + local_result: body.local_result, + ...(typeof body.session_id === "string" ? { session_id: body.session_id } : {}) + }; +} From f0454fb6da49d260a9193bef88b25682d35b05d5 Mon Sep 17 00:00:00 2001 From: ComRobertSoftwareLabsIncon Date: Fri, 4 Dec 2026 14:49:22 +0000 Subject: [PATCH 23/75] Add bounded in-memory request rate limiter --- src/rate-limit.ts | 62 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 src/rate-limit.ts diff --git a/src/rate-limit.ts b/src/rate-limit.ts new file mode 100644 index 0000000..c78515e --- /dev/null +++ b/src/rate-limit.ts @@ -0,0 +1,62 @@ +interface RateLimitOptions { + limit: number; + windowMs: number; + maxKeys?: number; + now?: () => number; +} + +interface WindowEntry { + count: number; + resetAt: number; +} + +export interface RateLimitResult { + allowed: boolean; + retryAfterSeconds: number; +} + +export function createRateLimiter(options: RateLimitOptions) { + const { limit, windowMs, maxKeys = 10_000, now = Date.now } = options; + const entries = new Map(); + let operations = 0; + + if (!Number.isInteger(limit) || limit < 1 || windowMs < 1 || maxKeys < 1) { + throw new Error("invalid rate limiter configuration"); + } + + function removeExpired(currentTime: number): void { + for (const [key, entry] of entries) { + if (entry.resetAt <= currentTime) entries.delete(key); + } + } + + return { + check(key: string): RateLimitResult { + const currentTime = now(); + operations += 1; + + if (operations % 256 === 0 || entries.size >= maxKeys) { + removeExpired(currentTime); + } + + const existing = entries.get(key); + if (existing && existing.resetAt > currentTime) { + if (existing.count >= limit) { + return { + allowed: false, + retryAfterSeconds: Math.max(1, Math.ceil((existing.resetAt - currentTime) / 1000)) + }; + } + existing.count += 1; + return { allowed: true, retryAfterSeconds: 0 }; + } + + if (entries.size >= maxKeys) { + return { allowed: false, retryAfterSeconds: Math.max(1, Math.ceil(windowMs / 1000)) }; + } + + entries.set(key, { count: 1, resetAt: currentTime + windowMs }); + return { allowed: true, retryAfterSeconds: 0 }; + } + }; +} From ba722d6d38a3bfb46922e8ebb3742a3719ae66fc Mon Sep 17 00:00:00 2001 From: ComRobertSoftwareLabsIncon Date: Fri, 4 Dec 2026 14:50:09 +0000 Subject: [PATCH 24/75] Harden bridge HTTP endpoint --- src/server.ts | 89 +++++++++++++++++++++++++++++++++++++++++++-------- 1 file changed, 75 insertions(+), 14 deletions(-) diff --git a/src/server.ts b/src/server.ts index ec364c3..52475ef 100644 --- a/src/server.ts +++ b/src/server.ts @@ -1,9 +1,14 @@ import { createServer } from "node:http"; import { timingSafeEqual } from "node:crypto"; +import type { IncomingMessage } from "node:http"; import { handleBridge } from "./bridge.js"; -import type { BridgeRequest } from "./types.js"; +import { createRateLimiter } from "./rate-limit.js"; +import { parseBridgeRequest, RequestValidationError } from "./validation.js"; + const PORT = Number(process.env.PORT || 3000); const MAX_BODY_BYTES = 64 * 1024; +const rateLimiter = createRateLimiter({ limit: 60, windowMs: 60_000, maxKeys: 10_000 }); + function isAuthorized(header: string | undefined): boolean { const expected = process.env.BRIDGE_TOKEN; if (!expected || !header?.startsWith("Bearer ")) return false; @@ -11,24 +16,80 @@ function isAuthorized(header: string | undefined): boolean { const target = Buffer.from(expected); return supplied.length === target.length && timingSafeEqual(supplied, target); } + +function clientKey(req: IncomingMessage): string { + return req.socket.remoteAddress || "unknown"; +} + +async function readJsonBody(req: IncomingMessage): Promise { + const chunks: Buffer[] = []; + let size = 0; + + for await (const chunk of req) { + const part = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk); + size += part.length; + if (size > MAX_BODY_BYTES) { + throw new RequestValidationError("payload too large"); + } + chunks.push(part); + } + + try { + return JSON.parse(Buffer.concat(chunks).toString("utf8")) as unknown; + } catch { + throw new RequestValidationError("invalid JSON"); + } +} + const server = createServer(async (req, res) => { res.setHeader("Content-Type", "application/json; charset=utf-8"); res.setHeader("Cache-Control", "no-store"); - if (req.method === "GET" && req.url === "/health") { res.writeHead(200).end(JSON.stringify({ ok: true, service: "chatgpt-intelligence-bridge" })); return; } - if (req.method !== "POST" || req.url !== "/v1/bridge") { res.writeHead(404).end(JSON.stringify({ ok: false, error: "Not found" })); return; } - if (!isAuthorized(req.headers.authorization)) { res.writeHead(401).end(JSON.stringify({ ok: false, error: "Unauthorized" })); return; } + res.setHeader("X-Content-Type-Options", "nosniff"); + + if (req.method === "GET" && req.url === "/health") { + res.writeHead(200).end(JSON.stringify({ ok: true, service: "chatgpt-intelligence-bridge" })); + return; + } + + if (req.method !== "POST" || req.url !== "/v1/bridge") { + res.writeHead(404).end(JSON.stringify({ ok: false, error: "Not found" })); + return; + } + + if (!isAuthorized(req.headers.authorization)) { + res.writeHead(401).end(JSON.stringify({ ok: false, error: "Unauthorized" })); + return; + } + + const rate = rateLimiter.check(clientKey(req)); + if (!rate.allowed) { + res.setHeader("Retry-After", String(rate.retryAfterSeconds)); + res.writeHead(429).end(JSON.stringify({ ok: false, error: "Too many requests" })); + return; + } + + if (!req.headers["content-type"]?.toLowerCase().startsWith("application/json")) { + res.writeHead(415).end(JSON.stringify({ ok: false, error: "Content-Type must be application/json" })); + return; + } + try { - const chunks: Buffer[] = []; let size = 0; - for await (const chunk of req) { const part = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk); size += part.length; if (size > MAX_BODY_BYTES) { res.writeHead(413).end(JSON.stringify({ ok: false, error: "Payload too large" })); return; } chunks.push(part); } - const body = JSON.parse(Buffer.concat(chunks).toString("utf8")) as Partial; - if (typeof body.text !== "string" || typeof body.local_result !== "string") { res.writeHead(400).end(JSON.stringify({ ok: false, error: "text and local_result are required strings" })); return; } - const result = await handleBridge({ text: body.text, local_result: body.local_result, session_id: typeof body.session_id === "string" ? body.session_id : undefined }); + const body = parseBridgeRequest(await readJsonBody(req)); + const result = await handleBridge(body); res.writeHead(200).end(JSON.stringify(result)); } catch (error) { - const message = error instanceof Error ? error.message : "Internal error"; - const status = message.includes("required") || message.includes("maximum") ? 400 : 502; - console.error(JSON.stringify({ event: "bridge_error", message: message.slice(0, 300) })); - res.writeHead(status).end(JSON.stringify({ ok: false, error: "Bridge request failed" })); + if (error instanceof RequestValidationError) { + const status = error.message === "payload too large" ? 413 : 400; + res.writeHead(status).end(JSON.stringify({ ok: false, error: error.message })); + return; + } + + console.error(JSON.stringify({ + event: "bridge_error", + error_type: error instanceof Error ? error.name : "UnknownError" + })); + res.writeHead(502).end(JSON.stringify({ ok: false, error: "Bridge request failed" })); } }); -server.listen(PORT, () => console.log(`ChatGPT Intelligence Bridge listening on port ${PORT}`)); \ No newline at end of file + +server.listen(PORT, () => console.log(`ChatGPT Intelligence Bridge listening on port ${PORT}`)); From 430dc737714e5810d493b18a7c1831539a5b0266 Mon Sep 17 00:00:00 2001 From: ComRobertSoftwareLabsIncon Date: Fri, 4 Dec 2026 14:50:12 +0000 Subject: [PATCH 25/75] Sanitize cloud provider errors --- src/openai.ts | 68 ++++++++++++++++++++++++++++++++++++++++++++------- 1 file changed, 59 insertions(+), 9 deletions(-) diff --git a/src/openai.ts b/src/openai.ts index a3141b0..46bb90c 100644 --- a/src/openai.ts +++ b/src/openai.ts @@ -1,14 +1,64 @@ import type { OpenAIResponsesPayload } from "./types.js"; + const OPENAI_URL = "https://api.openai.com/v1/responses"; -type ResponsesApiResult = { output?: Array<{ type?: string; content?: Array<{ type?: string; text?: string }> }>; output_text?: string; }; + +type ResponsesApiResult = { + output?: Array<{ + type?: string; + content?: Array<{ type?: string; text?: string }>; + }>; + output_text?: string; +}; + export async function askOpenAI(userText: string): Promise { const apiKey = process.env.OPENAI_API_KEY; - if (!apiKey) throw new Error("OPENAI_API_KEY is not configured"); - const payload: OpenAIResponsesPayload = { model: process.env.OPENAI_MODEL || "gpt-6-luna", max_output_tokens: 700, input: [{ role: "system", content: "You are the cloud fallback for a voice assistant. Answer clearly and concisely. Do not claim to have performed actions you cannot perform. If a request requires an external action, explain what is needed." }, { role: "user", content: userText }] }; - const response = await fetch(OPENAI_URL, { method: "POST", headers: { Authorization: `Bearer ${apiKey}`, "Content-Type": "application/json" }, body: JSON.stringify(payload), signal: AbortSignal.timeout(25_000) }); - if (!response.ok) { const detail = await response.text(); throw new Error(`OpenAI API returned ${response.status}: ${detail.slice(0, 500)}`); } - const data = await response.json() as ResponsesApiResult; - const outputText = data.output_text ?? data.output?.flatMap(item => item.content ?? []).filter(part => part.type === "output_text" && typeof part.text === "string").map(part => part.text).join("\n"); - if (!outputText?.trim()) throw new Error("OpenAI returned an empty response"); + if (!apiKey) throw new Error("Cloud fallback is not configured"); + + const payload: OpenAIResponsesPayload = { + model: process.env.OPENAI_MODEL || "gpt-6-luna", + max_output_tokens: 700, + input: [ + { + role: "system", + content: "You are the cloud fallback for a voice assistant. Answer clearly and concisely. Do not claim to have performed actions you cannot perform. If a request requires an external action, explain what is needed." + }, + { role: "user", content: userText } + ] + }; + + let response: Response; + try { + response = await fetch(OPENAI_URL, { + method: "POST", + headers: { + Authorization: `Bearer ${apiKey}`, + "Content-Type": "application/json" + }, + body: JSON.stringify(payload), + signal: AbortSignal.timeout(25_000) + }); + } catch { + throw new Error("Cloud provider is temporarily unavailable"); + } + + if (!response.ok) { + await response.body?.cancel(); + throw new Error(`Cloud provider request failed with status ${response.status}`); + } + + let data: ResponsesApiResult; + try { + data = await response.json() as ResponsesApiResult; + } catch { + throw new Error("Cloud provider returned an invalid response"); + } + + const outputText = data.output_text ?? + data.output?.flatMap((item) => item.content ?? []) + .filter((part) => part.type === "output_text" && typeof part.text === "string") + .map((part) => part.text) + .join("\n"); + + if (!outputText?.trim()) throw new Error("Cloud provider returned an empty response"); return outputText.trim(); -} \ No newline at end of file +} From 890c7c9c9b0adf5c3c892a3e154aa1400c409aec Mon Sep 17 00:00:00 2001 From: ComRobertSoftwareLabsIncon Date: Fri, 4 Dec 2026 14:50:14 +0000 Subject: [PATCH 26/75] Add request validation and rate limit tests --- tests/security.test.ts | 83 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 83 insertions(+) create mode 100644 tests/security.test.ts diff --git a/tests/security.test.ts b/tests/security.test.ts new file mode 100644 index 0000000..8ea095a --- /dev/null +++ b/tests/security.test.ts @@ -0,0 +1,83 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { parseBridgeRequest, RequestValidationError } from "../src/validation.js"; +import { createRateLimiter } from "../src/rate-limit.js"; + +test("accepts a valid bridge request", () => { + assert.deepEqual(parseBridgeRequest({ + text: "Hello", + local_result: "Local answer", + session_id: "session-1" + }), { + text: "Hello", + local_result: "Local answer", + session_id: "session-1" + }); +}); + +test("rejects non-object request bodies", () => { + assert.throws(() => parseBridgeRequest([]), RequestValidationError); + assert.throws(() => parseBridgeRequest(null), RequestValidationError); +}); + +test("rejects unexpected request properties", () => { + assert.throws(() => parseBridgeRequest({ + text: "Hello", + local_result: "Answer", + api_key: "must-not-be-accepted" + }), /unsupported fields/); +}); + +test("rejects invalid and oversized session identifiers", () => { + assert.throws(() => parseBridgeRequest({ + text: "Hello", + local_result: "Answer", + session_id: "bad\nvalue" + }), /session_id is invalid/); + assert.throws(() => parseBridgeRequest({ + text: "Hello", + local_result: "Answer", + session_id: "x".repeat(129) + }), /session_id is invalid/); +}); + +test("enforces request text length limits", () => { + assert.throws(() => parseBridgeRequest({ + text: "x".repeat(12_001), + local_result: "Answer" + }), /text exceeds maximum length/); + assert.throws(() => parseBridgeRequest({ + text: "Hello", + local_result: "x".repeat(16_001) + }), /local_result exceeds maximum length/); +}); + +test("rate limiter permits the configured number and blocks the next request", () => { + let currentTime = 1_000; + const limiter = createRateLimiter({ + limit: 2, + windowMs: 10_000, + now: () => currentTime + }); + + assert.equal(limiter.check("client-a").allowed, true); + assert.equal(limiter.check("client-a").allowed, true); + const blocked = limiter.check("client-a"); + assert.equal(blocked.allowed, false); + assert.equal(blocked.retryAfterSeconds, 10); + + currentTime += 10_000; + assert.equal(limiter.check("client-a").allowed, true); +}); + +test("rate limiter bounds the number of tracked clients", () => { + const limiter = createRateLimiter({ + limit: 1, + windowMs: 10_000, + maxKeys: 1, + now: () => 1_000 + }); + + assert.equal(limiter.check("client-a").allowed, true); + assert.equal(limiter.check("client-b").allowed, false); +}); From 86c24df8ce37d4f44dee3498b33dfbb316e5ae57 Mon Sep 17 00:00:00 2001 From: ComRobertSoftwareLabsIncon Date: Fri, 4 Dec 2026 14:52:20 +0000 Subject: [PATCH 27/75] Refactor HTTP server for integration testing and throttle authentication attempts --- src/server.ts | 126 +++++++++++++++++++++++++++++--------------------- 1 file changed, 74 insertions(+), 52 deletions(-) diff --git a/src/server.ts b/src/server.ts index 52475ef..de351ba 100644 --- a/src/server.ts +++ b/src/server.ts @@ -1,19 +1,26 @@ import { createServer } from "node:http"; import { timingSafeEqual } from "node:crypto"; -import type { IncomingMessage } from "node:http"; +import { pathToFileURL } from "node:url"; +import type { IncomingMessage, Server } from "node:http"; import { handleBridge } from "./bridge.js"; import { createRateLimiter } from "./rate-limit.js"; import { parseBridgeRequest, RequestValidationError } from "./validation.js"; -const PORT = Number(process.env.PORT || 3000); const MAX_BODY_BYTES = 64 * 1024; -const rateLimiter = createRateLimiter({ limit: 60, windowMs: 60_000, maxKeys: 10_000 }); +type BridgeHandler = typeof handleBridge; -function isAuthorized(header: string | undefined): boolean { - const expected = process.env.BRIDGE_TOKEN; - if (!expected || !header?.startsWith("Bearer ")) return false; +export interface BridgeServerOptions { + token?: string; + rateLimit?: number; + rateWindowMs?: number; + maxRateLimitKeys?: number; + handler?: BridgeHandler; +} + +function isAuthorized(header: string | undefined, expectedToken: string | undefined): boolean { + if (!expectedToken || !header?.startsWith("Bearer ")) return false; const supplied = Buffer.from(header.slice(7)); - const target = Buffer.from(expected); + const target = Buffer.from(expectedToken); return supplied.length === target.length && timingSafeEqual(supplied, target); } @@ -28,9 +35,7 @@ async function readJsonBody(req: IncomingMessage): Promise { for await (const chunk of req) { const part = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk); size += part.length; - if (size > MAX_BODY_BYTES) { - throw new RequestValidationError("payload too large"); - } + if (size > MAX_BODY_BYTES) throw new RequestValidationError("payload too large"); chunks.push(part); } @@ -41,55 +46,72 @@ async function readJsonBody(req: IncomingMessage): Promise { } } -const server = createServer(async (req, res) => { - res.setHeader("Content-Type", "application/json; charset=utf-8"); - res.setHeader("Cache-Control", "no-store"); - res.setHeader("X-Content-Type-Options", "nosniff"); +export function createBridgeServer(options: BridgeServerOptions = {}): Server { + const token = options.token ?? process.env.BRIDGE_TOKEN; + const limiter = createRateLimiter({ + limit: options.rateLimit ?? 60, + windowMs: options.rateWindowMs ?? 60_000, + maxKeys: options.maxRateLimitKeys ?? 10_000 + }); + const handler = options.handler ?? handleBridge; - if (req.method === "GET" && req.url === "/health") { - res.writeHead(200).end(JSON.stringify({ ok: true, service: "chatgpt-intelligence-bridge" })); - return; - } + return createServer(async (req, res) => { + res.setHeader("Content-Type", "application/json; charset=utf-8"); + res.setHeader("Cache-Control", "no-store"); + res.setHeader("X-Content-Type-Options", "nosniff"); - if (req.method !== "POST" || req.url !== "/v1/bridge") { - res.writeHead(404).end(JSON.stringify({ ok: false, error: "Not found" })); - return; - } + if (req.method === "GET" && req.url === "/health") { + res.writeHead(200).end(JSON.stringify({ ok: true, service: "chatgpt-intelligence-bridge" })); + return; + } - if (!isAuthorized(req.headers.authorization)) { - res.writeHead(401).end(JSON.stringify({ ok: false, error: "Unauthorized" })); - return; - } + if (req.method !== "POST" || req.url !== "/v1/bridge") { + res.writeHead(404).end(JSON.stringify({ ok: false, error: "Not found" })); + return; + } - const rate = rateLimiter.check(clientKey(req)); - if (!rate.allowed) { - res.setHeader("Retry-After", String(rate.retryAfterSeconds)); - res.writeHead(429).end(JSON.stringify({ ok: false, error: "Too many requests" })); - return; - } + const rate = limiter.check(clientKey(req)); + if (!rate.allowed) { + res.setHeader("Retry-After", String(rate.retryAfterSeconds)); + res.writeHead(429).end(JSON.stringify({ ok: false, error: "Too many requests" })); + return; + } - if (!req.headers["content-type"]?.toLowerCase().startsWith("application/json")) { - res.writeHead(415).end(JSON.stringify({ ok: false, error: "Content-Type must be application/json" })); - return; - } + if (!isAuthorized(req.headers.authorization, token)) { + res.writeHead(401).end(JSON.stringify({ ok: false, error: "Unauthorized" })); + return; + } - try { - const body = parseBridgeRequest(await readJsonBody(req)); - const result = await handleBridge(body); - res.writeHead(200).end(JSON.stringify(result)); - } catch (error) { - if (error instanceof RequestValidationError) { - const status = error.message === "payload too large" ? 413 : 400; - res.writeHead(status).end(JSON.stringify({ ok: false, error: error.message })); + if (!req.headers["content-type"]?.toLowerCase().startsWith("application/json")) { + res.writeHead(415).end(JSON.stringify({ ok: false, error: "Content-Type must be application/json" })); return; } - console.error(JSON.stringify({ - event: "bridge_error", - error_type: error instanceof Error ? error.name : "UnknownError" - })); - res.writeHead(502).end(JSON.stringify({ ok: false, error: "Bridge request failed" })); - } -}); + try { + const body = parseBridgeRequest(await readJsonBody(req)); + const result = await handler(body); + res.writeHead(200).end(JSON.stringify(result)); + } catch (error) { + if (error instanceof RequestValidationError) { + const status = error.message === "payload too large" ? 413 : 400; + res.writeHead(status).end(JSON.stringify({ ok: false, error: error.message })); + return; + } -server.listen(PORT, () => console.log(`ChatGPT Intelligence Bridge listening on port ${PORT}`)); + console.error(JSON.stringify({ + event: "bridge_error", + error_type: error instanceof Error ? error.name : "UnknownError" + })); + res.writeHead(502).end(JSON.stringify({ ok: false, error: "Bridge request failed" })); + } + }); +} + +const isDirectExecution = process.argv[1] && + import.meta.url === pathToFileURL(process.argv[1]).href; + +if (isDirectExecution) { + const port = Number(process.env.PORT || 3000); + const server = createBridgeServer(); + server.listen(port, () => console.log(`ChatGPT Intelligence Bridge listening on port ${port}`)); +} From d921eadb2ce990232466c12198ca900189761f00 Mon Sep 17 00:00:00 2001 From: ComRobertSoftwareLabsIncon Date: Fri, 4 Dec 2026 14:52:22 +0000 Subject: [PATCH 28/75] Add HTTP security integration tests --- tests/server.integration.test.ts | 163 +++++++++++++++++++++++++++++++ 1 file changed, 163 insertions(+) create mode 100644 tests/server.integration.test.ts diff --git a/tests/server.integration.test.ts b/tests/server.integration.test.ts new file mode 100644 index 0000000..d0b83c3 --- /dev/null +++ b/tests/server.integration.test.ts @@ -0,0 +1,163 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import type { AddressInfo } from "node:net"; +import { createBridgeServer } from "../src/server.js"; + +const TOKEN = "test-bridge-token"; + +async function withServer( + run: (baseUrl: string) => Promise, + options: Parameters[0] = {} +): Promise { + const server = createBridgeServer({ token: TOKEN, ...options }); + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + const address = server.address() as AddressInfo; + try { + await run(`http://127.0.0.1:${address.port}`); + } finally { + await new Promise((resolve, reject) => + server.close((error) => error ? reject(error) : resolve()) + ); + } +} + +const validBody = { text: "Hello CIB", local_result: "Local answer" }; +const authHeaders = { + authorization: `Bearer ${TOKEN}`, + "content-type": "application/json" +}; + +test("health endpoint is available and does not expose secrets", async () => { + await withServer(async (baseUrl) => { + const response = await fetch(`${baseUrl}/health`); + assert.equal(response.status, 200); + assert.equal(response.headers.get("cache-control"), "no-store"); + assert.deepEqual(await response.json(), { + ok: true, + service: "chatgpt-intelligence-bridge" + }); + }); +}); + +test("rejects missing and incorrect bearer tokens", async () => { + await withServer(async (baseUrl) => { + const missing = await fetch(`${baseUrl}/v1/bridge`, { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify(validBody) + }); + assert.equal(missing.status, 401); + + const incorrect = await fetch(`${baseUrl}/v1/bridge`, { + method: "POST", + headers: { ...authHeaders, authorization: "Bearer wrong-token" }, + body: JSON.stringify(validBody) + }); + assert.equal(incorrect.status, 401); + }); +}); + +test("rejects unsupported content types", async () => { + await withServer(async (baseUrl) => { + const response = await fetch(`${baseUrl}/v1/bridge`, { + method: "POST", + headers: { authorization: `Bearer ${TOKEN}`, "content-type": "text/plain" }, + body: "not-json" + }); + assert.equal(response.status, 415); + }); +}); + +test("rejects malformed JSON with a safe client error", async () => { + await withServer(async (baseUrl) => { + const response = await fetch(`${baseUrl}/v1/bridge`, { + method: "POST", + headers: authHeaders, + body: "{invalid" + }); + assert.equal(response.status, 400); + assert.deepEqual(await response.json(), { ok: false, error: "invalid JSON" }); + }); +}); + +test("rejects oversized request bodies", async () => { + await withServer(async (baseUrl) => { + const response = await fetch(`${baseUrl}/v1/bridge`, { + method: "POST", + headers: authHeaders, + body: JSON.stringify({ text: "x".repeat(70_000), local_result: "ok" }) + }); + assert.equal(response.status, 413); + }); +}); + +test("routes valid requests locally and returns no-store headers", async () => { + let calls = 0; + await withServer(async (baseUrl) => { + const response = await fetch(`${baseUrl}/v1/bridge`, { + method: "POST", + headers: authHeaders, + body: JSON.stringify(validBody) + }); + assert.equal(response.status, 200); + assert.equal(response.headers.get("cache-control"), "no-store"); + const body = await response.json() as { route: string; spoken_text: string }; + assert.equal(body.route, "local"); + assert.equal(body.spoken_text, "Local answer"); + assert.equal(calls, 0); + }, { + handler: async (request) => { + calls += 1; + return { + ok: true, + route: "local", + spoken_text: request.local_result, + request_id: "test-request" + }; + } + }); +}); + +test("rate limits repeated requests from the same client", async () => { + await withServer(async (baseUrl) => { + const send = () => fetch(`${baseUrl}/v1/bridge`, { + method: "POST", + headers: authHeaders, + body: JSON.stringify(validBody) + }); + + assert.equal((await send()).status, 200); + assert.equal((await send()).status, 200); + const blocked = await send(); + assert.equal(blocked.status, 429); + assert.ok(Number(blocked.headers.get("retry-after")) >= 1); + }, { + rateLimit: 2, + rateWindowMs: 60_000 + }); +}); + +test("does not expose internal provider errors to clients", async () => { + await withServer(async (baseUrl) => { + const response = await fetch(`${baseUrl}/v1/bridge`, { + method: "POST", + headers: authHeaders, + body: JSON.stringify(validBody) + }); + assert.equal(response.status, 502); + const body = await response.text(); + assert.equal(body, JSON.stringify({ ok: false, error: "Bridge request failed" })); + assert.equal(body.includes("private-provider-detail"), false); + }, { + handler: async () => { + throw new Error("private-provider-detail"); + } + }); +}); + +test("returns 404 for unknown routes", async () => { + await withServer(async (baseUrl) => { + const response = await fetch(`${baseUrl}/unknown`); + assert.equal(response.status, 404); + }); +}); From 4582c4addc02db2a000e649d23b28e70e3dddcab Mon Sep 17 00:00:00 2001 From: ComRobertSoftwareLabsIncon Date: Fri, 4 Dec 2026 14:52:56 +0000 Subject: [PATCH 29/75] Fix injected handler invocation expectation in HTTP test --- tests/server.integration.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/server.integration.test.ts b/tests/server.integration.test.ts index d0b83c3..c7cf161 100644 --- a/tests/server.integration.test.ts +++ b/tests/server.integration.test.ts @@ -104,7 +104,7 @@ test("routes valid requests locally and returns no-store headers", async () => { const body = await response.json() as { route: string; spoken_text: string }; assert.equal(body.route, "local"); assert.equal(body.spoken_text, "Local answer"); - assert.equal(calls, 0); + assert.equal(calls, 1); }, { handler: async (request) => { calls += 1; From 0ffeace997b4b1c44d34cfd9bb374ef25451f710 Mon Sep 17 00:00:00 2001 From: ComRobertSoftwareLabsIncon Date: Fri, 4 Dec 2026 14:57:42 +0000 Subject: [PATCH 30/75] Allow injectable shared rate limiter and validate JSON media type --- src/server.ts | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/src/server.ts b/src/server.ts index de351ba..b461699 100644 --- a/src/server.ts +++ b/src/server.ts @@ -3,7 +3,7 @@ import { timingSafeEqual } from "node:crypto"; import { pathToFileURL } from "node:url"; import type { IncomingMessage, Server } from "node:http"; import { handleBridge } from "./bridge.js"; -import { createRateLimiter } from "./rate-limit.js"; +import { createRateLimiter, type RateLimiter } from "./rate-limit.js"; import { parseBridgeRequest, RequestValidationError } from "./validation.js"; const MAX_BODY_BYTES = 64 * 1024; @@ -14,6 +14,7 @@ export interface BridgeServerOptions { rateLimit?: number; rateWindowMs?: number; maxRateLimitKeys?: number; + rateLimiter?: RateLimiter; handler?: BridgeHandler; } @@ -25,6 +26,8 @@ function isAuthorized(header: string | undefined, expectedToken: string | undefi } function clientKey(req: IncomingMessage): string { + // Deliberately use the socket address. Do not trust forwarded headers unless a + // separately configured trusted-proxy boundary has validated them. return req.socket.remoteAddress || "unknown"; } @@ -48,7 +51,7 @@ async function readJsonBody(req: IncomingMessage): Promise { export function createBridgeServer(options: BridgeServerOptions = {}): Server { const token = options.token ?? process.env.BRIDGE_TOKEN; - const limiter = createRateLimiter({ + const limiter = options.rateLimiter ?? createRateLimiter({ limit: options.rateLimit ?? 60, windowMs: options.rateWindowMs ?? 60_000, maxKeys: options.maxRateLimitKeys ?? 10_000 @@ -70,7 +73,7 @@ export function createBridgeServer(options: BridgeServerOptions = {}): Server { return; } - const rate = limiter.check(clientKey(req)); + const rate = await limiter.check(clientKey(req)); if (!rate.allowed) { res.setHeader("Retry-After", String(rate.retryAfterSeconds)); res.writeHead(429).end(JSON.stringify({ ok: false, error: "Too many requests" })); @@ -82,7 +85,8 @@ export function createBridgeServer(options: BridgeServerOptions = {}): Server { return; } - if (!req.headers["content-type"]?.toLowerCase().startsWith("application/json")) { + const contentType = req.headers["content-type"]?.split(";", 1)[0]?.trim().toLowerCase(); + if (contentType !== "application/json") { res.writeHead(415).end(JSON.stringify({ ok: false, error: "Content-Type must be application/json" })); return; } From dfead2fad53969add87e6a4a88467d0543f5124a Mon Sep 17 00:00:00 2001 From: ComRobertSoftwareLabsIncon Date: Fri, 4 Dec 2026 14:57:45 +0000 Subject: [PATCH 31/75] Define async-compatible rate limiter contract --- src/rate-limit.ts | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/src/rate-limit.ts b/src/rate-limit.ts index c78515e..81b612b 100644 --- a/src/rate-limit.ts +++ b/src/rate-limit.ts @@ -1,4 +1,4 @@ -interface RateLimitOptions { +export interface RateLimitOptions { limit: number; windowMs: number; maxKeys?: number; @@ -15,12 +15,21 @@ export interface RateLimitResult { retryAfterSeconds: number; } -export function createRateLimiter(options: RateLimitOptions) { +/** + * Implementations may use process-local memory or an atomic shared store. + * Shared implementations must apply the increment/check as one atomic operation. + */ +export interface RateLimiter { + check(key: string): RateLimitResult | Promise; +} + +export function createRateLimiter(options: RateLimitOptions): RateLimiter { const { limit, windowMs, maxKeys = 10_000, now = Date.now } = options; const entries = new Map(); let operations = 0; - if (!Number.isInteger(limit) || limit < 1 || windowMs < 1 || maxKeys < 1) { + if (!Number.isInteger(limit) || limit < 1 || !Number.isFinite(windowMs) || windowMs < 1 || + !Number.isInteger(maxKeys) || maxKeys < 1) { throw new Error("invalid rate limiter configuration"); } From 16af3cc822cbd0fe5fd0900a6bdc4c7e6990bf2b Mon Sep 17 00:00:00 2001 From: ComRobertSoftwareLabsIncon Date: Fri, 4 Dec 2026 14:57:47 +0000 Subject: [PATCH 32/75] Test strict content type and shared rate limiter injection --- tests/server.integration.test.ts | 23 ++++++++++++++++++++++- 1 file changed, 22 insertions(+), 1 deletion(-) diff --git a/tests/server.integration.test.ts b/tests/server.integration.test.ts index c7cf161..e1bbb84 100644 --- a/tests/server.integration.test.ts +++ b/tests/server.integration.test.ts @@ -61,7 +61,7 @@ test("rejects unsupported content types", async () => { await withServer(async (baseUrl) => { const response = await fetch(`${baseUrl}/v1/bridge`, { method: "POST", - headers: { authorization: `Bearer ${TOKEN}`, "content-type": "text/plain" }, + headers: { authorization: `Bearer ${TOKEN}`, "content-type": "application/jsonp" }, body: "not-json" }); assert.equal(response.status, 415); @@ -137,6 +137,27 @@ test("rate limits repeated requests from the same client", async () => { }); }); +test("supports an asynchronous shared rate limiter", async () => { + let checkedKey = ""; + await withServer(async (baseUrl) => { + const response = await fetch(`${baseUrl}/v1/bridge`, { + method: "POST", + headers: authHeaders, + body: JSON.stringify(validBody) + }); + assert.equal(response.status, 429); + assert.equal(response.headers.get("retry-after"), "17"); + assert.equal(checkedKey, "::ffff:127.0.0.1"); + }, { + rateLimiter: { + async check(key) { + checkedKey = key; + return { allowed: false, retryAfterSeconds: 17 }; + } + } + }); +}); + test("does not expose internal provider errors to clients", async () => { await withServer(async (baseUrl) => { const response = await fetch(`${baseUrl}/v1/bridge`, { From c4cae9f1e8b660d891f2b36857da780fde7b1165 Mon Sep 17 00:00:00 2001 From: ComRobertSoftwareLabsIncon Date: Fri, 4 Dec 2026 14:57:48 +0000 Subject: [PATCH 33/75] Document CIB security review and deployment boundaries --- SECURITY.md | 48 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 SECURITY.md diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 0000000..0ac0b0f --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,48 @@ +# CIB security review — v1.0.1 foundation + +## Scope + +This review covers the HTTP bridge, request validation, authentication, rate limiting, +and the cloud fallback adapter on `implementation/v1.0.1-foundation`. + +## Controls confirmed in source + +- Bearer-token authentication uses a length check and `timingSafeEqual`. +- The request body is capped at 64 KiB while it is streamed. +- Request fields are allow-listed and individual text/session fields have limits. +- Provider failures are returned to clients as a generic 502 response. +- Prompt contents and credentials are not written to application logs. +- Responses use `Cache-Control: no-store` and `X-Content-Type-Options: nosniff`. +- Cloud fallback requires the explicit `NEED_CLOUD` marker. +- The OpenAI adapter uses a 25-second timeout and does not expose provider error bodies. + +## Changes in this review + +- The server now accepts a `RateLimiter` dependency whose `check` method may be asynchronous. + This permits a host-specific shared/atomic store without making Redis or another vendor a + mandatory dependency. The in-memory implementation remains the default for a single process. +- The JSON media type is checked exactly after removing optional parameters; values such as + `application/jsonp` are rejected. +- The in-memory limiter now validates finite window sizes and integer key limits. + +## Deployment requirements and remaining risks + +- The default in-memory limiter is process-local. Multiple server instances must inject a + shared implementation that performs increment/check atomically across instances. +- The current client key is the TCP peer address. Behind a reverse proxy, configure the + proxy/network so the application receives traffic only from trusted proxy paths. Do not + blindly trust `X-Forwarded-For`. +- Terminate HTTPS at a trusted hosting platform or reverse proxy. This Node server does not + configure TLS itself. +- Store `BRIDGE_TOKEN` and `OPENAI_API_KEY` in the host's secret manager; rotate them if + exposed. Never commit live credentials or place them in Shortcut URLs. +- Apply platform-level connection, header, and request timeouts and an overall concurrency + limit before public deployment. +- The health endpoint is intentionally unauthenticated and returns only service status. +- A successful source review and CI run are not a penetration test or a production security + certification. + +## Model configuration + +The code keeps `gpt-6-luna` as its default. Confirmed against the current OpenAI API model +catalog/pricing documentation on 2026-12-04. Deployments may override it with `OPENAI_MODEL`. From 26c3cc4487cc39a7ad9e64eab809fa0fead80630 Mon Sep 17 00:00:00 2001 From: "Robert Software Labs, Inc." Date: Fri, 4 Dec 2026 14:58:16 +0000 Subject: [PATCH 34/75] Fix expected peer address in shared limiter test --- tests/server.integration.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/server.integration.test.ts b/tests/server.integration.test.ts index e1bbb84..5fae618 100644 --- a/tests/server.integration.test.ts +++ b/tests/server.integration.test.ts @@ -147,7 +147,7 @@ test("supports an asynchronous shared rate limiter", async () => { }); assert.equal(response.status, 429); assert.equal(response.headers.get("retry-after"), "17"); - assert.equal(checkedKey, "::ffff:127.0.0.1"); + assert.equal(checkedKey, "127.0.0.1"); }, { rateLimiter: { async check(key) { From e9f712ea9e6663a3c1454130103c83bb61b461fa Mon Sep 17 00:00:00 2001 From: "Robert Software Labs, Inc." Date: Fri, 4 Dec 2026 15:06:07 +0000 Subject: [PATCH 35/75] Make OpenAI adapter testable through injected dependencies --- src/openai.ts | 18 +++++++++++++----- 1 file changed, 13 insertions(+), 5 deletions(-) diff --git a/src/openai.ts b/src/openai.ts index 46bb90c..4accbf4 100644 --- a/src/openai.ts +++ b/src/openai.ts @@ -10,12 +10,19 @@ type ResponsesApiResult = { output_text?: string; }; -export async function askOpenAI(userText: string): Promise { - const apiKey = process.env.OPENAI_API_KEY; +export interface OpenAIOptions { + apiKey?: string; + model?: string; + fetcher?: typeof fetch; + timeoutMs?: number; +} + +export async function askOpenAI(userText: string, options: OpenAIOptions = {}): Promise { + const apiKey = options.apiKey ?? process.env.OPENAI_API_KEY; if (!apiKey) throw new Error("Cloud fallback is not configured"); const payload: OpenAIResponsesPayload = { - model: process.env.OPENAI_MODEL || "gpt-6-luna", + model: options.model ?? process.env.OPENAI_MODEL ?? "gpt-6-luna", max_output_tokens: 700, input: [ { @@ -26,16 +33,17 @@ export async function askOpenAI(userText: string): Promise { ] }; + const fetcher = options.fetcher ?? fetch; let response: Response; try { - response = await fetch(OPENAI_URL, { + response = await fetcher(OPENAI_URL, { method: "POST", headers: { Authorization: `Bearer ${apiKey}`, "Content-Type": "application/json" }, body: JSON.stringify(payload), - signal: AbortSignal.timeout(25_000) + signal: AbortSignal.timeout(options.timeoutMs ?? 25_000) }); } catch { throw new Error("Cloud provider is temporarily unavailable"); From 43edcd4cae1bd0bf03be564be268acda0eb91a13 Mon Sep 17 00:00:00 2001 From: "Robert Software Labs, Inc." Date: Fri, 4 Dec 2026 15:06:09 +0000 Subject: [PATCH 36/75] Add isolated OpenAI adapter resilience tests --- tests/openai.test.ts | 88 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 88 insertions(+) create mode 100644 tests/openai.test.ts diff --git a/tests/openai.test.ts b/tests/openai.test.ts new file mode 100644 index 0000000..af6af72 --- /dev/null +++ b/tests/openai.test.ts @@ -0,0 +1,88 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { askOpenAI } from "../src/openai.js"; + +const API_KEY = "test-api-key"; + +test("requires an API key before making a request", async () => { + await assert.rejects( + askOpenAI("hello", { apiKey: "" }), + /Cloud fallback is not configured/ + ); +}); + +test("sends a Responses API request and returns output_text", async () => { + let requestedUrl = ""; + let requestInit: RequestInit | undefined; + + const answer = await askOpenAI("hello", { + apiKey: API_KEY, + model: "test-model", + fetcher: async (input, init) => { + requestedUrl = String(input); + requestInit = init; + return Response.json({ output_text: " Hello from cloud " }); + } + }); + + assert.equal(requestedUrl, "https://api.openai.com/v1/responses"); + assert.equal(answer, "Hello from cloud"); + assert.equal(requestInit?.method, "POST"); + assert.equal(new Headers(requestInit?.headers).get("authorization"), `Bearer ${API_KEY}`); + const payload = JSON.parse(String(requestInit?.body)) as { model: string; input: Array<{ role: string; content: string }> }; + assert.equal(payload.model, "test-model"); + assert.equal(payload.input[1]?.role, "user"); + assert.equal(payload.input[1]?.content, "hello"); +}); + +test("extracts output_text from structured response content", async () => { + const answer = await askOpenAI("hello", { + apiKey: API_KEY, + fetcher: async () => Response.json({ + output: [{ content: [{ type: "output_text", text: "Structured answer" }] }] + }) + }); + assert.equal(answer, "Structured answer"); +}); + +test("sanitizes network and timeout failures", async () => { + await assert.rejects( + askOpenAI("hello", { + apiKey: API_KEY, + fetcher: async () => { throw new Error("secret socket detail"); } + }), + (error: Error) => error.message === "Cloud provider is temporarily unavailable" && + !error.message.includes("secret") + ); +}); + +test("sanitizes non-success provider responses", async () => { + await assert.rejects( + askOpenAI("hello", { + apiKey: API_KEY, + fetcher: async () => new Response("private provider detail", { status: 503 }) + }), + (error: Error) => error.message === "Cloud provider request failed with status 503" && + !error.message.includes("private") + ); +}); + +test("rejects invalid JSON from the provider", async () => { + await assert.rejects( + askOpenAI("hello", { + apiKey: API_KEY, + fetcher: async () => new Response("not-json", { status: 200 }) + }), + /Cloud provider returned an invalid response/ + ); +}); + +test("rejects empty provider output", async () => { + await assert.rejects( + askOpenAI("hello", { + apiKey: API_KEY, + fetcher: async () => Response.json({ output_text: " " }) + }), + /Cloud provider returned an empty response/ + ); +}); From e24ec7c4c2840488ff90dbea007ce6dc04cdc4de Mon Sep 17 00:00:00 2001 From: "Robert Software Labs, Inc." Date: Fri, 4 Dec 2026 15:17:41 +0000 Subject: [PATCH 37/75] Generate and commit npm lockfile, then use npm ci --- .github/workflows/ci.yml | 19 ++++++++++++++++++- 1 file changed, 18 insertions(+), 1 deletion(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 9760acd..970b5c5 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -6,6 +6,9 @@ on: push: branches: [implementation/v1.0.1-foundation] +permissions: + contents: write + jobs: test-and-build: runs-on: ubuntu-latest @@ -14,6 +17,20 @@ jobs: - uses: actions/setup-node@v4 with: node-version: 22 - - run: npm install + cache: npm + - name: Generate lockfile if missing + if: hashFiles('package-lock.json') == '' + run: | + npm install --package-lock-only --ignore-scripts --no-audit --no-fund --fetch-retries=3 --fetch-timeout=60000 + if [ "$GITHUB_EVENT_NAME" = "push" ]; then + git config user.name "github-actions[bot]" + git config user.email "41898282+github-actions[bot]@users.noreply.github.com" + git add package-lock.json + if ! git diff --cached --quiet; then + git commit -m "chore: add reproducible npm lockfile" + git push origin "HEAD:${GITHUB_REF_NAME}" + fi + fi + - run: npm ci --no-audit --no-fund - run: npm test - run: npm run build From 14eb1652cbcec4fa461ba29b57dff277f2aca985 Mon Sep 17 00:00:00 2001 From: "Robert Software Labs, Inc." Date: Fri, 4 Dec 2026 15:19:07 +0000 Subject: [PATCH 38/75] Fix lockfile bootstrap before npm cache setup --- .github/workflows/ci.yml | 1 - 1 file changed, 1 deletion(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 970b5c5..6eff446 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -17,7 +17,6 @@ jobs: - uses: actions/setup-node@v4 with: node-version: 22 - cache: npm - name: Generate lockfile if missing if: hashFiles('package-lock.json') == '' run: | From 6936920c8d8d2e448a32119228e9399ec90c3ad7 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Fri, 4 Dec 2026 15:19:17 +0000 Subject: [PATCH 39/75] chore: add reproducible npm lockfile --- package-lock.json | 569 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 569 insertions(+) create mode 100644 package-lock.json diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 0000000..9a33824 --- /dev/null +++ b/package-lock.json @@ -0,0 +1,569 @@ +{ + "name": "chatgpt-intelligence-bridge", + "version": "1.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "chatgpt-intelligence-bridge", + "version": "1.0.0", + "devDependencies": { + "@types/node": "^22.0.0", + "tsx": "^4.19.0", + "typescript": "^5.7.0" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/@esbuild/aix-ppc64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.28.2.tgz", + "integrity": "sha512-XExcO+dvLKvVtNTibSTBej1NCAbaGhWn9Ww1ZPx80qsahhPFe/8jgWP0IchNe0F3HwkU7n8ejhH8bjonqht8mQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.28.2.tgz", + "integrity": "sha512-kXXoiPVVGQcnIYGOeaovwOURpniDBpSq4A03qkQ+BMQqtGG6HYap3xne9C1O1yo4TR3qxlCX5IqqmX6fFo2Lqg==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.28.2.tgz", + "integrity": "sha512-5YfKeeI8qWfBZIX+u2xZC3Zlb3Os/gLS2sbEKM+I4ZOcsWmHS2WLysCcQZDAFRslDUU5Oiq44gf6PYN1vGwG5A==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.28.2.tgz", + "integrity": "sha512-O387ite7SzUyCcy3JQX4P4bLtEA7bLLkx+esve5JHnyYfNTxcVpXZo9jhdB0lTKN44gztELTdU7nS8Nr16Fs1Q==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.28.2.tgz", + "integrity": "sha512-n4KqkOQrraxHJcgjM1RvwbigfQKIKJVpM7xp+KsxiyUSrRdIXnt73VhrPAx0fV44hgfmIVKjxMN9J1t5jySVkw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.28.2.tgz", + "integrity": "sha512-uq6suIWYP37qzGddBKPw5QEQPi6HiLGsO7UmkpfyaYNQ3D+rN6w6WfwH+nuqcGXWvawGwxOEroO4YGnFh95azw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.28.2.tgz", + "integrity": "sha512-n+I0BTSRIoy+d6RPKnEVwql5UwBJolytvY4mAOIEJorKlqgPII8ix6slVVrfZ5Tnj7glIZvloylbB/EJPMWEXw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.28.2.tgz", + "integrity": "sha512-78XJTJkvPs0kz2w61301PJjXl4g7q3JqiYMZ/M/yVI73EHBrCRTgkhu9oqG7vPqq+a/yadEW8aD+agKlk5xrmg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.28.2.tgz", + "integrity": "sha512-XlDnu2q5yoqems+xay6wSAcg9DDD7K9RLKZEBOMZm3ckNpJBvOX20tSfby8KfrrhINDyv9V2YVZKY/SpoGJI8w==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.28.2.tgz", + "integrity": "sha512-pW4AC0P3it8c7do9MVM4p51FzHzdM/TZrerurgRcHJ2WTa1VQ1CIq18xncfpBJw4ojkiZZrKW2yIBWBP92j6Ug==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ia32": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.28.2.tgz", + "integrity": "sha512-CYbnj78HsIeA+DhgUKgFCfvNsTHFhMMrinUrMZpDXJXKN8T3XViTZ/+wtHeVxEWY8ewSzTFN+nRmSwO2tZaLUQ==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-loong64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.28.2.tgz", + "integrity": "sha512-buwkd8nsph4R+ajRvw0qM5Hja/TXQow3ptzWO2EbG/cqcIkHloRrdlBtQlshyYGTNFvfkfJ5tpPLVkY4DtsPfQ==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-mips64el": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.28.2.tgz", + "integrity": "sha512-ZVykbDyk7519VwiNb9Lcj9m8XM6v5V9uKPvrEMkkEedVewf+0itkhahp4HDpgERXhwLRpWFypsGbG/J8s0QjJA==", + "cpu": [ + "mips64el" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ppc64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.28.2.tgz", + "integrity": "sha512-CAXl+Dtd9UUuJd8pKKdwh6MLm3MUMiqMPmhZ3tTSXPqfyQ3vDl6R5hZdZ/kYojK4ofXtdfSv1tFq8XzWx3heNQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-riscv64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.28.2.tgz", + "integrity": "sha512-GeXCej4IQtU1B+QlDV8W/RRvbzI3O/Stss+/bCXv4lZls5WGRtu2a+3JkA3i4qIUlMXpcHebWpF8AkJhATowuA==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-s390x": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.28.2.tgz", + "integrity": "sha512-3H1weTYZPxt/WOhByszQZybS9w5lKzUn1FDMsgEChbHWQwHYQQRfBxgCcZvPhjHfKyJjIievvMmEUawJrdY9Dg==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.28.2.tgz", + "integrity": "sha512-4xTZr1FUmSoQW4XIWmit3tzQrUTZM+N3P0XV8xROKYF50XfI7xeO90+1bZvNwxIufQ9hDQVRJH5YhgPVF8A/HQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.28.2.tgz", + "integrity": "sha512-sSATRjPeDBg3pdgHoQfoYBob11Kk1FGa9lui5RIHZCoCkJa9QKlvl3/vKz2usCmYYjs7ymJR/2Nnsqe+Hjt5nw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.28.2.tgz", + "integrity": "sha512-lqnzCV+mM0gIADaKihiCg6ifgfU2L3h5E33rNQBN1Y4MaVGnzryzmvvf7UHxprpQdE8hpqLolJ9Rl+SkIRDpyw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.28.2.tgz", + "integrity": "sha512-AL2qJILH7lNjrDmCQDvdxMfAUIv8KMNZOvrwAQ8i8//ntL9FflhOyMJ8OZSMBb8/AWXe3/5v5S20y3zCoZWKoQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.28.2.tgz", + "integrity": "sha512-QtiuPytchRyC4rwUKhexJdQKvDuZ6hWloi3igqPQNUJCS1/v9EiO3UTOXR6A3FoMo4fnAKbWJdqaIwhOzh8qEw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openharmony-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.28.2.tgz", + "integrity": "sha512-WkhYDmpTjLvGlScA1rwjRUmhl4k8oXR3cIbtqWmELgU/dFeHHlEllxDvdWcNJV9rbzCexB5vz8gtNewWLgCT7Q==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/sunos-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.28.2.tgz", + "integrity": "sha512-GPMSkTOtMnv2U2F8gxe4Io6qmVs+YKyp832Etqqxr0hFngmXQ3rzwytelm3GIn7T4VviRUlf3sOgBOiTdvaf7g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.28.2.tgz", + "integrity": "sha512-PIhhEkE9uPBleRBrQEJpUn7MBnibZzbGzYWPmY3x+YoVg/95zbjB4CxPPOQ8l5tYYM4mMaCthF8/1DIfBQQyWQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-ia32": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.28.2.tgz", + "integrity": "sha512-YmJbfTlvU7Sdn9BB+4PRES4oB6pxgS37MAONj+hBr/cpXS1aBPKXxNnDbu+QCWPj0o9dgyxeq79g6c5P8KeuYA==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.28.2.tgz", + "integrity": "sha512-5ebpxr3nWMzrL/rnUI755Jkuee0bHL/Gq0WTF9lvcpv73wAp5eu8MfBUgWK9bhWvZjj7yX8etf/8tI8Ney695g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@types/node": { + "version": "22.20.7", + "resolved": "https://registry.npmjs.org/@types/node/-/node-22.20.7.tgz", + "integrity": "sha512-F/Mcc4pD3YwXQCG50hb8BjB5RmrOere6hge7n2XHf0V8tpkZOVEjwYv9Ql7n0MpMn8Bv7+q12P9w6UHsBm0Sfw==", + "dev": true, + "license": "MIT", + "dependencies": { + "undici-types": "~6.21.0" + } + }, + "node_modules/esbuild": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.28.2.tgz", + "integrity": "sha512-HKVLS8dvII+xoKW9kmqxbRKrnWEXfJJr/FZhhJmiqIB0e053QNYFqOBouTMO/k5sID4MvCiUCvv8b9M4h32wIA==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=18" + }, + "optionalDependencies": { + "@esbuild/aix-ppc64": "0.28.2", + "@esbuild/android-arm": "0.28.2", + "@esbuild/android-arm64": "0.28.2", + "@esbuild/android-x64": "0.28.2", + "@esbuild/darwin-arm64": "0.28.2", + "@esbuild/darwin-x64": "0.28.2", + "@esbuild/freebsd-arm64": "0.28.2", + "@esbuild/freebsd-x64": "0.28.2", + "@esbuild/linux-arm": "0.28.2", + "@esbuild/linux-arm64": "0.28.2", + "@esbuild/linux-ia32": "0.28.2", + "@esbuild/linux-loong64": "0.28.2", + "@esbuild/linux-mips64el": "0.28.2", + "@esbuild/linux-ppc64": "0.28.2", + "@esbuild/linux-riscv64": "0.28.2", + "@esbuild/linux-s390x": "0.28.2", + "@esbuild/linux-x64": "0.28.2", + "@esbuild/netbsd-arm64": "0.28.2", + "@esbuild/netbsd-x64": "0.28.2", + "@esbuild/openbsd-arm64": "0.28.2", + "@esbuild/openbsd-x64": "0.28.2", + "@esbuild/openharmony-arm64": "0.28.2", + "@esbuild/sunos-x64": "0.28.2", + "@esbuild/win32-arm64": "0.28.2", + "@esbuild/win32-ia32": "0.28.2", + "@esbuild/win32-x64": "0.28.2" + } + }, + "node_modules/fsevents": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", + "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/tsx": { + "version": "4.23.15", + "resolved": "https://registry.npmjs.org/tsx/-/tsx-4.23.15.tgz", + "integrity": "sha512-Yiex1Ovn8z2xPpOWckIiysV1SSyRMY9BkLF++q0yKiDxCqRhosKfMg3janKkiLBwZ5c/YryloKwGZcrEmtwxKw==", + "dev": true, + "license": "MIT", + "dependencies": { + "esbuild": "~0.28.0" + }, + "bin": { + "tsx": "dist/cli.mjs" + }, + "engines": { + "node": ">=18.0.0" + }, + "optionalDependencies": { + "fsevents": "~2.3.3" + } + }, + "node_modules/typescript": { + "version": "5.9.3", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz", + "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=14.17" + } + }, + "node_modules/undici-types": { + "version": "6.21.0", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz", + "integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==", + "dev": true, + "license": "MIT" + } + } +} From 27f52900514c17171941b8fd7fae45147c6135a8 Mon Sep 17 00:00:00 2001 From: "Robert Software Labs, Inc." Date: Fri, 4 Dec 2026 15:19:40 +0000 Subject: [PATCH 40/75] Enable npm cache now that lockfile is committed --- .github/workflows/ci.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 6eff446..970b5c5 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -17,6 +17,7 @@ jobs: - uses: actions/setup-node@v4 with: node-version: 22 + cache: npm - name: Generate lockfile if missing if: hashFiles('package-lock.json') == '' run: | From f399e32ba572f654c03a74f0f561503e01779baf Mon Sep 17 00:00:00 2001 From: "Robert Software Labs, Inc." Date: Fri, 4 Dec 2026 15:29:16 +0000 Subject: [PATCH 41/75] Reduce CI permissions and require committed lockfile --- .github/workflows/ci.yml | 15 +-------------- 1 file changed, 1 insertion(+), 14 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 970b5c5..f36fdfc 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -7,7 +7,7 @@ on: branches: [implementation/v1.0.1-foundation] permissions: - contents: write + contents: read jobs: test-and-build: @@ -18,19 +18,6 @@ jobs: with: node-version: 22 cache: npm - - name: Generate lockfile if missing - if: hashFiles('package-lock.json') == '' - run: | - npm install --package-lock-only --ignore-scripts --no-audit --no-fund --fetch-retries=3 --fetch-timeout=60000 - if [ "$GITHUB_EVENT_NAME" = "push" ]; then - git config user.name "github-actions[bot]" - git config user.email "41898282+github-actions[bot]@users.noreply.github.com" - git add package-lock.json - if ! git diff --cached --quiet; then - git commit -m "chore: add reproducible npm lockfile" - git push origin "HEAD:${GITHUB_REF_NAME}" - fi - fi - run: npm ci --no-audit --no-fund - run: npm test - run: npm run build From aa182904247cd815843876a947d788b992bd4942 Mon Sep 17 00:00:00 2001 From: "Robert Software Labs, Inc." Date: Fri, 4 Dec 2026 15:29:19 +0000 Subject: [PATCH 42/75] Add concurrent and per-client rate-limit coverage --- tests/security.test.ts | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/tests/security.test.ts b/tests/security.test.ts index 8ea095a..97740d8 100644 --- a/tests/security.test.ts +++ b/tests/security.test.ts @@ -81,3 +81,32 @@ test("rate limiter bounds the number of tracked clients", () => { assert.equal(limiter.check("client-a").allowed, true); assert.equal(limiter.check("client-b").allowed, false); }); + + +test("rate limiter enforces its limit under concurrent checks", async () => { + const limit = 7; + const limiter = createRateLimiter({ + limit, + windowMs: 10_000, + now: () => 1_000 + }); + + const results = await Promise.all( + Array.from({ length: 100 }, () => Promise.resolve(limiter.check("same-client"))) + ); + + assert.equal(results.filter((result) => result.allowed).length, limit); + assert.equal(results.filter((result) => !result.allowed).length, 100 - limit); +}); + +test("rate limiter isolates independent clients", () => { + const limiter = createRateLimiter({ + limit: 1, + windowMs: 10_000, + now: () => 1_000 + }); + + assert.equal(limiter.check("client-a").allowed, true); + assert.equal(limiter.check("client-a").allowed, false); + assert.equal(limiter.check("client-b").allowed, true); +}); From ba320d908e6e3f7ef3678df6aaf5d971bcb33454 Mon Sep 17 00:00:00 2001 From: "Robert Software Labs, Inc." Date: Fri, 4 Dec 2026 15:29:26 +0000 Subject: [PATCH 43/75] Document CI permission hardening and rate-limit tests --- SECURITY.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/SECURITY.md b/SECURITY.md index 0ac0b0f..afb0ff5 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -24,6 +24,8 @@ and the cloud fallback adapter on `implementation/v1.0.1-foundation`. - The JSON media type is checked exactly after removing optional parameters; values such as `application/jsonp` are rejected. - The in-memory limiter now validates finite window sizes and integer key limits. +- CI now uses the committed lockfile with `npm ci` and has read-only repository contents permission. +- Rate-limit tests cover concurrent checks and isolation between client keys. ## Deployment requirements and remaining risks From 291b423bf8de3f31439decc9f9250b73b0a2d914 Mon Sep 17 00:00:00 2001 From: "Robert Software Labs, Inc." Date: Fri, 4 Dec 2026 15:31:18 +0000 Subject: [PATCH 44/75] Fail closed on rate limiter errors and bound HTTP timeouts --- src/server.ts | 21 +++++++++++++++++++-- 1 file changed, 19 insertions(+), 2 deletions(-) diff --git a/src/server.ts b/src/server.ts index b461699..37fe631 100644 --- a/src/server.ts +++ b/src/server.ts @@ -58,7 +58,7 @@ export function createBridgeServer(options: BridgeServerOptions = {}): Server { }); const handler = options.handler ?? handleBridge; - return createServer(async (req, res) => { + const server = createServer(async (req, res) => { res.setHeader("Content-Type", "application/json; charset=utf-8"); res.setHeader("Cache-Control", "no-store"); res.setHeader("X-Content-Type-Options", "nosniff"); @@ -73,7 +73,18 @@ export function createBridgeServer(options: BridgeServerOptions = {}): Server { return; } - const rate = await limiter.check(clientKey(req)); + let rate: Awaited>; + try { + rate = await limiter.check(clientKey(req)); + } catch (error) { + console.error(JSON.stringify({ + event: "rate_limiter_error", + error_type: error instanceof Error ? error.name : "UnknownError" + })); + res.writeHead(503).end(JSON.stringify({ ok: false, error: "Service temporarily unavailable" })); + return; + } + if (!rate.allowed) { res.setHeader("Retry-After", String(rate.retryAfterSeconds)); res.writeHead(429).end(JSON.stringify({ ok: false, error: "Too many requests" })); @@ -109,6 +120,12 @@ export function createBridgeServer(options: BridgeServerOptions = {}): Server { res.writeHead(502).end(JSON.stringify({ ok: false, error: "Bridge request failed" })); } }); + + // Bound slow header/body delivery at the HTTP server boundary. + server.headersTimeout = 10_000; + server.requestTimeout = 30_000; + server.keepAliveTimeout = 5_000; + return server; } const isDirectExecution = process.argv[1] && From fea769683d0f7556c91e179116034663facd6de4 Mon Sep 17 00:00:00 2001 From: "Robert Software Labs, Inc." Date: Fri, 4 Dec 2026 15:31:21 +0000 Subject: [PATCH 45/75] Test safe handling of rate limiter outages --- tests/server.integration.test.ts | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/tests/server.integration.test.ts b/tests/server.integration.test.ts index 5fae618..67c7edf 100644 --- a/tests/server.integration.test.ts +++ b/tests/server.integration.test.ts @@ -182,3 +182,25 @@ test("returns 404 for unknown routes", async () => { assert.equal(response.status, 404); }); }); + + +test("returns a generic 503 when the rate limiter is unavailable", async () => { + await withServer(async (baseUrl) => { + const response = await fetch(`${baseUrl}/v1/bridge`, { + method: "POST", + headers: authHeaders, + body: JSON.stringify(validBody) + }); + assert.equal(response.status, 503); + assert.deepEqual(await response.json(), { + ok: false, + error: "Service temporarily unavailable" + }); + }, { + rateLimiter: { + check() { + throw new Error("private-shared-store-detail"); + } + } + }); +}); From b9ccf968b9fa35de0fbffbea3a3a0264c560f163 Mon Sep 17 00:00:00 2001 From: "Robert Software Labs, Inc." Date: Fri, 4 Dec 2026 15:32:00 +0000 Subject: [PATCH 46/75] Complete security review notes for HTTP timeout and limiter failure handling --- SECURITY.md | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/SECURITY.md b/SECURITY.md index afb0ff5..c061269 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -24,6 +24,8 @@ and the cloud fallback adapter on `implementation/v1.0.1-foundation`. - The JSON media type is checked exactly after removing optional parameters; values such as `application/jsonp` are rejected. - The in-memory limiter now validates finite window sizes and integer key limits. +- The HTTP server applies 10-second header, 30-second request, and 5-second keep-alive timeouts. +- A rate-limiter backend failure now returns a generic 503 response instead of leaving the request unresolved. - CI now uses the committed lockfile with `npm ci` and has read-only repository contents permission. - Rate-limit tests cover concurrent checks and isolation between client keys. @@ -38,8 +40,8 @@ and the cloud fallback adapter on `implementation/v1.0.1-foundation`. configure TLS itself. - Store `BRIDGE_TOKEN` and `OPENAI_API_KEY` in the host's secret manager; rotate them if exposed. Never commit live credentials or place them in Shortcut URLs. -- Apply platform-level connection, header, and request timeouts and an overall concurrency - limit before public deployment. +- Apply platform-level connection limits and an overall concurrency limit before public deployment; + application-level HTTP timeouts do not replace edge/proxy connection controls. - The health endpoint is intentionally unauthenticated and returns only service status. - A successful source review and CI run are not a penetration test or a production security certification. From 73651f37659b764b8d18a5fbeb177909a3edd935 Mon Sep 17 00:00:00 2001 From: "Robert Software Labs, Inc." Date: Fri, 4 Dec 2026 15:32:57 +0000 Subject: [PATCH 47/75] Add dependency vulnerability audit to CI --- .github/workflows/ci.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index f36fdfc..9fed6f8 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -19,5 +19,6 @@ jobs: node-version: 22 cache: npm - run: npm ci --no-audit --no-fund + - run: npm audit --audit-level=high - run: npm test - run: npm run build From 3265a8225bcdd465ceaee2f72164443fa966e101 Mon Sep 17 00:00:00 2001 From: "Robert Software Labs, Inc." Date: Fri, 4 Dec 2026 15:34:22 +0000 Subject: [PATCH 48/75] Add implementation review and remaining deployment checklist --- REVIEW.md | 42 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 REVIEW.md diff --git a/REVIEW.md b/REVIEW.md new file mode 100644 index 0000000..bf75ffe --- /dev/null +++ b/REVIEW.md @@ -0,0 +1,42 @@ +# CIB — implementation review + +**Review date:** 2026-12-04 +**Reviewed branch:** `implementation/v1.0.1-foundation` +**Reviewed commit:** `73651f37659b764b8d18a5fbeb177909a3edd935` +**Pull request:** #1 — open, Draft, not merged + +## Verified in CI + +The GitHub Actions push and pull-request workflows completed successfully for the reviewed commit. + +- `npm ci --no-audit --no-fund`: passed using the committed npm lockfile. +- `npm audit --audit-level=high`: passed; 0 vulnerabilities reported. +- `npm test`: 34 tests passed, 0 failed. +- `npm run build`: passed. + +CI run: https://github.com/ComRobertSoftwareLabsIncon/ChatGPT_Intelligence_Bridge/actions/runs/47366057599 + +## Changes reviewed + +- Reproducible dependency installation through the committed `package-lock.json` and `npm ci`. +- CI repository permission reduced to read-only. +- Integration coverage for authentication, content type, malformed and oversized bodies, routing, rate limiting, and safe provider failures. +- Rate-limit tests cover concurrent checks and client-key isolation. +- Rate-limiter backend failures return a generic 503 response. +- HTTP server header, request, and keep-alive timeouts are bounded. +- OpenAI fallback has an injectable fetch implementation, bounded timeout, and sanitized provider errors. + +## Remaining deployment requirements + +This review does not certify production readiness. Before public deployment: + +1. Inject a shared, atomic rate limiter when running multiple instances; the default limiter is process-local. +2. Restrict traffic to trusted reverse-proxy paths and configure trusted client identity handling; do not blindly trust `X-Forwarded-For`. +3. Terminate HTTPS at a trusted platform or reverse proxy. +4. Store and rotate `BRIDGE_TOKEN` and `OPENAI_API_KEY` through a secrets manager. +5. Set platform-level connection limits and overall concurrency controls. +6. Perform deployment-specific security testing, including penetration testing where appropriate. + +## Review decision + +**Implementation branch CI is green and the current changes are ready for human review in PR #1.** Keep the PR in Draft until the remaining deployment requirements, architecture decisions, and review feedback are addressed. No merge to `main` is performed by this review. From b936c7c0f9b522b5d0b19f087b1ff548a0d86f1a Mon Sep 17 00:00:00 2001 From: "Robert Software Labs, Inc." Date: Fri, 4 Dec 2026 15:37:08 +0000 Subject: [PATCH 49/75] Document reproducible npm ci installation --- README.md | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 21cba61..6b63772 100644 --- a/README.md +++ b/README.md @@ -40,14 +40,16 @@ The Bridge does not open the ChatGPT app. It uses the OpenAI API, billed separat - `OPENAI_API_KEY` and `BRIDGE_TOKEN` configured as host-side secrets - Optional `OPENAI_MODEL` and host-provided `PORT` -Run: +Run from the repository root: ```bash -npm install +npm ci npm run build npm start ``` +`package-lock.json` is committed and must be kept in sync with `package.json`. Use `npm ci` for clean, repeatable installs in CI and deployments; it installs the exact dependency tree recorded in the lockfile and fails if the manifest and lockfile disagree. Use `npm install` only when intentionally changing dependencies, then commit both `package.json` and the regenerated `package-lock.json` together. + Never commit secrets or place them in Shortcut URLs. Keep `OPENAI_API_KEY` on the server and the separate `BRIDGE_TOKEN` in the Shortcut's Authorization header. ## Build the Shortcut on iPhone From de8b972f8dcd933fe7288f98532fedd5a4ccde89 Mon Sep 17 00:00:00 2001 From: "Robert Software Labs, Inc." Date: Fri, 4 Dec 2026 15:39:39 +0000 Subject: [PATCH 50/75] Add provider-neutral shared rate limiter adapter --- src/shared-rate-limit.ts | 76 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 76 insertions(+) create mode 100644 src/shared-rate-limit.ts diff --git a/src/shared-rate-limit.ts b/src/shared-rate-limit.ts new file mode 100644 index 0000000..71dcf3e --- /dev/null +++ b/src/shared-rate-limit.ts @@ -0,0 +1,76 @@ +import { createHash } from "node:crypto"; +import type { RateLimitResult, RateLimiter } from "./rate-limit.js"; + +/** + * A storage adapter must implement increment + first-write expiry atomically. + * It must return the resulting count and the absolute expiry time in epoch ms. + * Expired keys should be removed by the backend's TTL mechanism. + */ +export interface AtomicRateLimitStore { + increment( + key: string, + windowMs: number + ): Promise<{ count: number; resetAt: number }>; +} + +export interface SharedRateLimiterOptions { + store: AtomicRateLimitStore; + limit: number; + windowMs: number; + namespace?: string; + now?: () => number; +} + +/** + * Provider-neutral shared rate limiter. + * + * The raw client key is hashed before it reaches shared storage. The injected + * store remains responsible for an atomic increment and fixed-window expiry. + */ +export function createSharedRateLimiter( + options: SharedRateLimiterOptions +): RateLimiter { + const { + store, + limit, + windowMs, + namespace = "cib:rate-limit:v1", + now = Date.now + } = options; + + if (!store || typeof store.increment !== "function" || + !Number.isInteger(limit) || limit < 1 || + !Number.isFinite(windowMs) || windowMs < 1 || + typeof namespace !== "string" || namespace.trim().length === 0) { + throw new Error("invalid shared rate limiter configuration"); + } + + return { + async check(clientKey: string): Promise { + if (typeof clientKey !== "string" || clientKey.length === 0) { + throw new Error("rate limit client key is required"); + } + + const storageKey = createHash("sha256") + .update(namespace) + .update("\0") + .update(clientKey) + .digest("hex"); + + const result = await store.increment(storageKey, windowMs); + if (!result || !Number.isSafeInteger(result.count) || result.count < 1 || + !Number.isFinite(result.resetAt)) { + throw new Error("shared rate limiter returned an invalid result"); + } + + if (result.count <= limit) { + return { allowed: true, retryAfterSeconds: 0 }; + } + + return { + allowed: false, + retryAfterSeconds: Math.max(1, Math.ceil((result.resetAt - now()) / 1000)) + }; + } + }; +} From 5e0d06b688569350aad4fc06f3c2f080591d927b Mon Sep 17 00:00:00 2001 From: "Robert Software Labs, Inc." Date: Fri, 4 Dec 2026 15:39:49 +0000 Subject: [PATCH 51/75] Test shared rate limiter adapter and key hashing --- tests/security.test.ts | 62 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 62 insertions(+) diff --git a/tests/security.test.ts b/tests/security.test.ts index 97740d8..5f46e74 100644 --- a/tests/security.test.ts +++ b/tests/security.test.ts @@ -110,3 +110,65 @@ test("rate limiter isolates independent clients", () => { assert.equal(limiter.check("client-a").allowed, false); assert.equal(limiter.check("client-b").allowed, true); }); + + +import { createSharedRateLimiter } from "../src/shared-rate-limit.js"; + +test("shared rate limiter hashes client keys and enforces the atomic count", async () => { + const records = new Map(); + const receivedKeys: string[] = []; + const limiter = createSharedRateLimiter({ + limit: 2, + windowMs: 10_000, + namespace: "test-bridge", + now: () => 1_000, + store: { + async increment(key, windowMs) { + receivedKeys.push(key); + const current = records.get(key) ?? { count: 0, resetAt: 11_000 }; + current.count += 1; + current.resetAt = Math.max(current.resetAt, 1_000 + windowMs); + records.set(key, current); + return current; + } + } + }); + + assert.deepEqual(await limiter.check("192.0.2.10"), { + allowed: true, + retryAfterSeconds: 0 + }); + assert.deepEqual(await limiter.check("192.0.2.10"), { + allowed: true, + retryAfterSeconds: 0 + }); + assert.deepEqual(await limiter.check("192.0.2.10"), { + allowed: false, + retryAfterSeconds: 10 + }); + assert.equal(receivedKeys.length, 3); + assert.ok(receivedKeys.every((key) => /^[a-f0-9]{64}$/.test(key))); + assert.ok(receivedKeys.every((key) => key !== "192.0.2.10")); +}); + +test("shared rate limiter rejects invalid backend results", async () => { + const limiter = createSharedRateLimiter({ + limit: 2, + windowMs: 10_000, + store: { + async increment() { + return { count: Number.NaN, resetAt: 10_000 }; + } + } + }); + + await assert.rejects(() => limiter.check("client-a"), /invalid result/); +}); + +test("shared rate limiter validates its configuration", () => { + assert.throws(() => createSharedRateLimiter({ + limit: 0, + windowMs: 10_000, + store: { async increment() { return { count: 1, resetAt: 10_000 }; } } + }), /invalid shared rate limiter configuration/); +}); From a1bfb1e149b49d191fe0c0422565dc9d014dada0 Mon Sep 17 00:00:00 2001 From: "Robert Software Labs, Inc." Date: Fri, 4 Dec 2026 15:40:05 +0000 Subject: [PATCH 52/75] Document shared rate limiter integration --- README.md | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/README.md b/README.md index 6b63772..84a2f06 100644 --- a/README.md +++ b/README.md @@ -30,6 +30,8 @@ The Bridge does not open the ChatGPT app. It uses the OpenAI API, billed separat - `src/bridge.ts`: local/cloud routing policy. - `src/openai.ts`: OpenAI Responses API adapter. - `src/types.ts`: request and response contracts. +- `src/rate-limit.ts`: process-local rate limiter and shared limiter contract. +- `src/shared-rate-limit.ts`: provider-neutral adapter for atomic shared storage. - `config/`: bridge, provider and privacy configuration. - `shortcuts/`: action manifest, local prompt and request example. @@ -73,3 +75,25 @@ Insert Shortcuts variables with the variable picker rather than typing their nam - It cannot bypass iOS permission prompts or privacy indicators. - Do not send passwords, authentication codes, financial secrets or sensitive personal data to the cloud. - The server is stateless and does not persist conversation history or log prompt contents. + + +## Shared rate limiting + +The default limiter stores counters in process memory and is suitable only for a +single server process. For multiple instances, inject a shared implementation: + +- Implement `AtomicRateLimitStore.increment(key, windowMs)`. +- The backend operation must atomically increment the counter and establish the + expiry on the first write; return `{ count, resetAt }`, where `resetAt` is + an absolute Unix timestamp in milliseconds. +- Do not implement this as separate read, increment and expiry calls: concurrent + requests could exceed the configured limit. +- Use the provider-neutral adapter and inject it through + `createBridgeServer({ rateLimiter })`. +- The adapter hashes the client key before passing it to storage. The storage + provider, credentials, connection lifecycle and availability remain the + responsibility of the hosting application. + +No Redis, database or other storage vendor is bundled or required. If the +shared store fails, the HTTP service returns a generic 503 response; it does +not silently fall back to a per-instance limiter. From e62ca8653c4097dcc2f9b0866eefa23e3e0070d0 Mon Sep 17 00:00:00 2001 From: "Robert Software Labs, Inc." Date: Fri, 4 Dec 2026 15:40:07 +0000 Subject: [PATCH 53/75] Document shared rate limiter security contract --- SECURITY.md | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/SECURITY.md b/SECURITY.md index c061269..2eac752 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -19,6 +19,7 @@ and the cloud fallback adapter on `implementation/v1.0.1-foundation`. ## Changes in this review - The server now accepts a `RateLimiter` dependency whose `check` method may be asynchronous. +- Added a provider-neutral shared limiter adapter. It hashes client keys before storage and requires a backend-provided atomic increment with first-write expiry. This permits a host-specific shared/atomic store without making Redis or another vendor a mandatory dependency. The in-memory implementation remains the default for a single process. - The JSON media type is checked exactly after removing optional parameters; values such as @@ -31,8 +32,10 @@ and the cloud fallback adapter on `implementation/v1.0.1-foundation`. ## Deployment requirements and remaining risks -- The default in-memory limiter is process-local. Multiple server instances must inject a - shared implementation that performs increment/check atomically across instances. +- The default in-memory limiter is process-local. Multiple server instances must inject the + `createSharedRateLimiter` adapter with an `AtomicRateLimitStore` implementation that performs + increment and first-write expiry atomically across instances. The repository does not bundle + or mandate Redis or another storage provider. - The current client key is the TCP peer address. Behind a reverse proxy, configure the proxy/network so the application receives traffic only from trusted proxy paths. Do not blindly trust `X-Forwarded-For`. From ff78f437c54c26c7be2808485a713a1e5cd74ab7 Mon Sep 17 00:00:00 2001 From: "Robert Software Labs, Inc." Date: Fri, 4 Dec 2026 15:40:48 +0000 Subject: [PATCH 54/75] Update implementation review for shared rate limiter --- REVIEW.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/REVIEW.md b/REVIEW.md index bf75ffe..258d68e 100644 --- a/REVIEW.md +++ b/REVIEW.md @@ -2,7 +2,7 @@ **Review date:** 2026-12-04 **Reviewed branch:** `implementation/v1.0.1-foundation` -**Reviewed commit:** `73651f37659b764b8d18a5fbeb177909a3edd935` +**Reviewed commit:** `e62ca8653c4097dcc2f9b0866eefa23e3e0070d0` **Pull request:** #1 — open, Draft, not merged ## Verified in CI @@ -11,10 +11,10 @@ The GitHub Actions push and pull-request workflows completed successfully for th - `npm ci --no-audit --no-fund`: passed using the committed npm lockfile. - `npm audit --audit-level=high`: passed; 0 vulnerabilities reported. -- `npm test`: 34 tests passed, 0 failed. +- `npm test`: 37 tests passed, 0 failed. - `npm run build`: passed. -CI run: https://github.com/ComRobertSoftwareLabsIncon/ChatGPT_Intelligence_Bridge/actions/runs/47366057599 +CI run: https://github.com/ComRobertSoftwareLabsIncon/ChatGPT_Intelligence_Bridge/actions/runs/47367360133 ## Changes reviewed @@ -30,7 +30,7 @@ CI run: https://github.com/ComRobertSoftwareLabsIncon/ChatGPT_Intelligence_Bridg This review does not certify production readiness. Before public deployment: -1. Inject a shared, atomic rate limiter when running multiple instances; the default limiter is process-local. +1. Supply and test a production `AtomicRateLimitStore` implementation when running multiple instances; the generic adapter is present, but no concrete storage backend is bundled. 2. Restrict traffic to trusted reverse-proxy paths and configure trusted client identity handling; do not blindly trust `X-Forwarded-For`. 3. Terminate HTTPS at a trusted platform or reverse proxy. 4. Store and rotate `BRIDGE_TOKEN` and `OPENAI_API_KEY` through a secrets manager. From 8d9c80fc23aca53f83bb3d8d2a72af1776b36150 Mon Sep 17 00:00:00 2001 From: "Robert Software Labs, Inc." Date: Fri, 4 Dec 2026 15:58:13 +0000 Subject: [PATCH 55/75] Add explicit trusted proxy client identity handling --- src/server.ts | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/server.ts b/src/server.ts index 37fe631..dc44331 100644 --- a/src/server.ts +++ b/src/server.ts @@ -1,6 +1,7 @@ import { createServer } from "node:http"; import { timingSafeEqual } from "node:crypto"; import { pathToFileURL } from "node:url"; +import { createTrustedProxyResolver } from "./trusted-proxy.js"; import type { IncomingMessage, Server } from "node:http"; import { handleBridge } from "./bridge.js"; import { createRateLimiter, type RateLimiter } from "./rate-limit.js"; @@ -15,6 +16,7 @@ export interface BridgeServerOptions { rateWindowMs?: number; maxRateLimitKeys?: number; rateLimiter?: RateLimiter; + trustedProxies?: readonly string[]; handler?: BridgeHandler; } @@ -57,6 +59,7 @@ export function createBridgeServer(options: BridgeServerOptions = {}): Server { maxKeys: options.maxRateLimitKeys ?? 10_000 }); const handler = options.handler ?? handleBridge; + const resolveClientAddress = createTrustedProxyResolver({ trustedProxies: options.trustedProxies }); const server = createServer(async (req, res) => { res.setHeader("Content-Type", "application/json; charset=utf-8"); @@ -75,7 +78,7 @@ export function createBridgeServer(options: BridgeServerOptions = {}): Server { let rate: Awaited>; try { - rate = await limiter.check(clientKey(req)); + rate = await limiter.check(resolveClientAddress(req)); } catch (error) { console.error(JSON.stringify({ event: "rate_limiter_error", From 91787c004eaa6e191e1ff3b53957b4021fba35e2 Mon Sep 17 00:00:00 2001 From: "Robert Software Labs, Inc." Date: Fri, 4 Dec 2026 15:58:16 +0000 Subject: [PATCH 56/75] Add trusted proxy address resolver --- src/trusted-proxy.ts | 88 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 88 insertions(+) create mode 100644 src/trusted-proxy.ts diff --git a/src/trusted-proxy.ts b/src/trusted-proxy.ts new file mode 100644 index 0000000..e3e5cd4 --- /dev/null +++ b/src/trusted-proxy.ts @@ -0,0 +1,88 @@ +import { BlockList, isIP } from "node:net"; +import type { IncomingMessage } from "node:http"; + +export interface TrustedProxyOptions { + /** Explicit proxy addresses or CIDRs, e.g. "10.0.0.0/8" or "2001:db8::/32". */ + trustedProxies?: readonly string[]; +} + +function normalizeAddress(address: string): string { + const value = address.trim(); + const mapped = /^::ffff:(\\d{1,3}(?:\\.\\d{1,3}){3})$/i.exec(value); + return mapped ? mapped[1] : value; +} + +function createTrustedProxyList(entries: readonly string[]): BlockList { + const list = new BlockList(); + + for (const entry of entries) { + if (typeof entry !== "string" || entry.trim() !== entry || entry.length === 0) { + throw new Error("invalid trusted proxy entry"); + } + + const parts = entry.split("/"); + if (parts.length > 2) throw new Error("invalid trusted proxy entry"); + + const address = normalizeAddress(parts[0]); + const family = isIP(address); + if (family === 0) throw new Error("invalid trusted proxy address"); + + const maxPrefix = family === 4 ? 32 : 128; + const prefix = parts.length === 1 ? maxPrefix : Number(parts[1]); + if (!Number.isInteger(prefix) || prefix < 0 || prefix > maxPrefix) { + throw new Error("invalid trusted proxy CIDR prefix"); + } + + list.addSubnet(address, prefix, family === 4 ? "ipv4" : "ipv6"); + } + + return list; +} + +function isTrusted(address: string, list: BlockList): boolean { + const normalized = normalizeAddress(address); + const family = isIP(normalized); + if (family === 0) return false; + return list.check(normalized, family === 4 ? "ipv4" : "ipv6"); +} + +/** + * Resolve the rate-limit identity without trusting client-supplied forwarding + * headers. X-Forwarded-For is considered only when the TCP peer is trusted. + * The chain is walked right-to-left, stopping at the first untrusted hop. + */ +export function resolveClientAddress( + req: IncomingMessage, + trustedProxyList: BlockList +): string { + const peer = req.socket.remoteAddress; + if (!peer) return "unknown"; + + if (!isTrusted(peer, trustedProxyList)) return normalizeAddress(peer); + + const forwarded = req.headers["x-forwarded-for"]; + if (typeof forwarded !== "string" || forwarded.length === 0) { + return normalizeAddress(peer); + } + + const entries = forwarded.split(","); + if (entries.length > 20) return normalizeAddress(peer); + + const chain = entries.map((entry) => normalizeAddress(entry.trim())); + if (chain.some((address) => isIP(address) === 0)) { + return normalizeAddress(peer); + } + + let candidate = normalizeAddress(peer); + for (let index = chain.length - 1; index >= 0; index -= 1) { + if (!isTrusted(candidate, trustedProxyList)) break; + candidate = chain[index]; + } + + return candidate; +} + +export function createTrustedProxyResolver(options: TrustedProxyOptions = {}) { + const list = createTrustedProxyList(options.trustedProxies ?? []); + return (req: IncomingMessage): string => resolveClientAddress(req, list); +} From e37cbdd88df1bcd8aa5c27b2f9dc264219d6650b Mon Sep 17 00:00:00 2001 From: "Robert Software Labs, Inc." Date: Fri, 4 Dec 2026 15:59:02 +0000 Subject: [PATCH 57/75] Test trusted and untrusted proxy identity handling --- tests/server.integration.test.ts | 42 ++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) diff --git a/tests/server.integration.test.ts b/tests/server.integration.test.ts index 67c7edf..c48d7de 100644 --- a/tests/server.integration.test.ts +++ b/tests/server.integration.test.ts @@ -204,3 +204,45 @@ test("returns a generic 503 when the rate limiter is unavailable", async () => { } }); }); + +test("ignores spoofed X-Forwarded-For from an untrusted peer", async () => { + let checkedKey = ""; + await withServer(async (baseUrl) => { + const response = await fetch(`${baseUrl}/v1/bridge`, { + method: "POST", + headers: { ...authHeaders, "x-forwarded-for": "198.51.100.77" }, + body: JSON.stringify(validBody) + }); + assert.equal(response.status, 429); + assert.equal(checkedKey, "127.0.0.1"); + }, { + trustedProxies: ["192.0.2.0/24"], + rateLimiter: { + check(key) { + checkedKey = key; + return { allowed: false, retryAfterSeconds: 1 }; + } + } + }); +}); + +test("uses X-Forwarded-For only when the TCP peer is a trusted proxy", async () => { + let checkedKey = ""; + await withServer(async (baseUrl) => { + const response = await fetch(`${baseUrl}/v1/bridge`, { + method: "POST", + headers: { ...authHeaders, "x-forwarded-for": "198.51.100.77" }, + body: JSON.stringify(validBody) + }); + assert.equal(response.status, 429); + assert.equal(checkedKey, "198.51.100.77"); + }, { + trustedProxies: ["127.0.0.1/32"], + rateLimiter: { + check(key) { + checkedKey = key; + return { allowed: false, retryAfterSeconds: 1 }; + } + } + }); +}); From ecce89f3f9a05ef9c9acd43bdabd0a8b35af03ca Mon Sep 17 00:00:00 2001 From: "Robert Software Labs, Inc." Date: Fri, 4 Dec 2026 15:59:05 +0000 Subject: [PATCH 58/75] Add trusted proxy resolver unit tests --- tests/trusted-proxy.test.ts | 54 +++++++++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 tests/trusted-proxy.test.ts diff --git a/tests/trusted-proxy.test.ts b/tests/trusted-proxy.test.ts new file mode 100644 index 0000000..f4bd59f --- /dev/null +++ b/tests/trusted-proxy.test.ts @@ -0,0 +1,54 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { createTrustedProxyResolver } from "../src/trusted-proxy.js"; +import type { IncomingMessage } from "node:http"; + +function request(peer: string, forwarded?: string): IncomingMessage { + return { + socket: { remoteAddress: peer }, + headers: forwarded === undefined ? {} : { "x-forwarded-for": forwarded } + } as unknown as IncomingMessage; +} + +test("ignores X-Forwarded-For when the TCP peer is not trusted", () => { + const resolve = createTrustedProxyResolver({ trustedProxies: ["192.0.2.0/24"] }); + assert.equal(resolve(request("203.0.113.10", "198.51.100.7")), "203.0.113.10"); +}); + +test("uses the forwarded client address from an explicitly trusted IPv4 proxy", () => { + const resolve = createTrustedProxyResolver({ trustedProxies: ["127.0.0.1/32"] }); + assert.equal(resolve(request("127.0.0.1", "198.51.100.7")), "198.51.100.7"); +}); + +test("walks a forwarded chain from right to left through trusted proxies", () => { + const resolve = createTrustedProxyResolver({ + trustedProxies: ["127.0.0.1/32", "10.0.0.0/8"] + }); + assert.equal(resolve(request("127.0.0.1", "198.51.100.7, 10.2.3.4")), "198.51.100.7"); +}); + +test("stops at the first untrusted proxy in the forwarded chain", () => { + const resolve = createTrustedProxyResolver({ trustedProxies: ["127.0.0.1/32"] }); + assert.equal(resolve(request("127.0.0.1", "198.51.100.7, 203.0.113.9")), "203.0.113.9"); +}); + +test("falls back to the TCP peer when X-Forwarded-For is malformed", () => { + const resolve = createTrustedProxyResolver({ trustedProxies: ["127.0.0.1"] }); + assert.equal(resolve(request("127.0.0.1", "198.51.100.7, not-an-ip")), "127.0.0.1"); +}); + +test("falls back when the forwarded chain exceeds the hop limit", () => { + const resolve = createTrustedProxyResolver({ trustedProxies: ["127.0.0.1"] }); + assert.equal(resolve(request("127.0.0.1", Array(21).fill("198.51.100.7").join(", "))), "127.0.0.1"); +}); + +test("supports IPv6 proxy CIDRs and IPv4-mapped socket addresses", () => { + const resolve = createTrustedProxyResolver({ trustedProxies: ["2001:db8:abcd::/48", "127.0.0.1/32"] }); + assert.equal(resolve(request("2001:db8:abcd::5", "198.51.100.8")), "198.51.100.8"); + assert.equal(resolve(request("::ffff:127.0.0.1", "198.51.100.9")), "198.51.100.9"); +}); + +test("rejects invalid trusted proxy configuration", () => { + assert.throws(() => createTrustedProxyResolver({ trustedProxies: ["not-an-ip"] })); + assert.throws(() => createTrustedProxyResolver({ trustedProxies: ["192.0.2.1/33"] })); +}); From fc1b9bb312e49b0b7a75b28e1639a6d6906c4461 Mon Sep 17 00:00:00 2001 From: "Robert Software Labs, Inc." Date: Fri, 4 Dec 2026 15:59:39 +0000 Subject: [PATCH 59/75] Document trusted reverse proxy configuration --- README.md | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/README.md b/README.md index 84a2f06..fe0d37b 100644 --- a/README.md +++ b/README.md @@ -97,3 +97,27 @@ single server process. For multiple instances, inject a shared implementation: No Redis, database or other storage vendor is bundled or required. If the shared store fails, the HTTP service returns a generic 503 response; it does not silently fall back to a per-instance limiter. + + +## Trusted reverse proxies + +By default, the service uses the TCP peer address for rate-limit identity and +ignores `X-Forwarded-For`. This prevents arbitrary clients from choosing their +own rate-limit identity. + +If the service is reachable only through a reverse proxy, explicitly configure +the proxy's exact IP addresses or CIDR ranges when creating the server: + +```ts +const server = createBridgeServer({ + trustedProxies: ["10.20.0.10/32", "2001:db8:1234::/48"] +}); +``` + +Only requests whose direct TCP peer matches this allow-list can use +`X-Forwarded-For`. The service walks the forwarded chain from right to left, +skipping trusted proxy hops and selecting the first untrusted address. Invalid +chains and chains longer than 20 hops fall back to the TCP peer. Do not add +client-controlled networks or broad ranges to `trustedProxies`; configure the +actual proxy egress addresses and ensure the application is not directly +reachable around that proxy. From 3d55134fb020c46fec713865c9bfa44a899b8cc6 Mon Sep 17 00:00:00 2001 From: "Robert Software Labs, Inc." Date: Fri, 4 Dec 2026 15:59:41 +0000 Subject: [PATCH 60/75] Document trusted proxy security boundary --- SECURITY.md | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/SECURITY.md b/SECURITY.md index 2eac752..f94552d 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -19,6 +19,8 @@ and the cloud fallback adapter on `implementation/v1.0.1-foundation`. ## Changes in this review - The server now accepts a `RateLimiter` dependency whose `check` method may be asynchronous. +- Trusted reverse-proxy handling is opt-in through `trustedProxies`; untrusted forwarded + headers cannot override the TCP peer used for rate limiting. - Added a provider-neutral shared limiter adapter. It hashes client keys before storage and requires a backend-provided atomic increment with first-write expiry. This permits a host-specific shared/atomic store without making Redis or another vendor a mandatory dependency. The in-memory implementation remains the default for a single process. @@ -36,9 +38,11 @@ and the cloud fallback adapter on `implementation/v1.0.1-foundation`. `createSharedRateLimiter` adapter with an `AtomicRateLimitStore` implementation that performs increment and first-write expiry atomically across instances. The repository does not bundle or mandate Redis or another storage provider. -- The current client key is the TCP peer address. Behind a reverse proxy, configure the - proxy/network so the application receives traffic only from trusted proxy paths. Do not - blindly trust `X-Forwarded-For`. +- Rate-limit identity uses the TCP peer address by default; `X-Forwarded-For` is ignored. + The optional `trustedProxies` allow-list accepts exact IPs/CIDRs. Forwarded chains are + considered only when the direct TCP peer is trusted, are traversed right-to-left, and + fall back to the TCP peer when malformed or longer than 20 hops. Configure only actual + proxy egress addresses and prevent direct access that bypasses the proxy. - Terminate HTTPS at a trusted hosting platform or reverse proxy. This Node server does not configure TLS itself. - Store `BRIDGE_TOKEN` and `OPENAI_API_KEY` in the host's secret manager; rotate them if From 750ea27968f1e1a7ce413adcbf3480fca5891eba Mon Sep 17 00:00:00 2001 From: "Robert Software Labs, Inc." Date: Fri, 4 Dec 2026 16:00:16 +0000 Subject: [PATCH 61/75] Record trusted proxy review and CI results --- REVIEW.md | 28 +++++++++++++++------------- 1 file changed, 15 insertions(+), 13 deletions(-) diff --git a/REVIEW.md b/REVIEW.md index 258d68e..d033893 100644 --- a/REVIEW.md +++ b/REVIEW.md @@ -2,27 +2,29 @@ **Review date:** 2026-12-04 **Reviewed branch:** `implementation/v1.0.1-foundation` -**Reviewed commit:** `e62ca8653c4097dcc2f9b0866eefa23e3e0070d0` +**Reviewed commit:** `3d55134fb020c46fec713865c9bfa44a899b8cc6` **Pull request:** #1 — open, Draft, not merged ## Verified in CI -The GitHub Actions push and pull-request workflows completed successfully for the reviewed commit. +The GitHub Actions push workflow completed successfully for the reviewed commit. -- `npm ci --no-audit --no-fund`: passed using the committed npm lockfile. -- `npm audit --audit-level=high`: passed; 0 vulnerabilities reported. -- `npm test`: 37 tests passed, 0 failed. +- `npm ci --no-audit --no-fund`: passed. +- `npm audit --audit-level=high`: passed. +- `npm test`: 47 tests passed, 0 failed. - `npm run build`: passed. -CI run: https://github.com/ComRobertSoftwareLabsIncon/ChatGPT_Intelligence_Bridge/actions/runs/47367360133 +CI run: https://github.com/ComRobertSoftwareLabsIncon/ChatGPT_Intelligence_Bridge/actions/runs/47370949920 ## Changes reviewed -- Reproducible dependency installation through the committed `package-lock.json` and `npm ci`. +- Reproducible dependency installation through the committed npm lockfile and `npm ci`. - CI repository permission reduced to read-only. - Integration coverage for authentication, content type, malformed and oversized bodies, routing, rate limiting, and safe provider failures. -- Rate-limit tests cover concurrent checks and client-key isolation. -- Rate-limiter backend failures return a generic 503 response. +- Shared rate limiter adapter hashes client keys before storage and requires atomic increment with first-write expiry. +- Trusted reverse-proxy handling is opt-in through `trustedProxies`; forwarded headers are ignored unless the direct TCP peer matches an explicit IP/CIDR allow-list. +- Forwarded chains are traversed right-to-left through trusted hops; malformed chains and chains longer than 20 hops fall back to the TCP peer. +- Tests cover spoofed headers, trusted/untrusted peers, IPv4, IPv6 CIDRs, mapped IPv4 addresses, malformed chains, and invalid configuration. - HTTP server header, request, and keep-alive timeouts are bounded. - OpenAI fallback has an injectable fetch implementation, bounded timeout, and sanitized provider errors. @@ -30,13 +32,13 @@ CI run: https://github.com/ComRobertSoftwareLabsIncon/ChatGPT_Intelligence_Bridg This review does not certify production readiness. Before public deployment: -1. Supply and test a production `AtomicRateLimitStore` implementation when running multiple instances; the generic adapter is present, but no concrete storage backend is bundled. -2. Restrict traffic to trusted reverse-proxy paths and configure trusted client identity handling; do not blindly trust `X-Forwarded-For`. -3. Terminate HTTPS at a trusted platform or reverse proxy. +1. Supply and test a production `AtomicRateLimitStore` implementation when running multiple instances; no concrete storage backend is bundled. +2. Configure `trustedProxies` with only the actual proxy egress IPs/CIDRs, and prevent direct application access that bypasses the proxy. +3. Terminate HTTPS at a trusted hosting platform or reverse proxy. 4. Store and rotate `BRIDGE_TOKEN` and `OPENAI_API_KEY` through a secrets manager. 5. Set platform-level connection limits and overall concurrency controls. 6. Perform deployment-specific security testing, including penetration testing where appropriate. ## Review decision -**Implementation branch CI is green and the current changes are ready for human review in PR #1.** Keep the PR in Draft until the remaining deployment requirements, architecture decisions, and review feedback are addressed. No merge to `main` is performed by this review. +**The implementation branch CI is green for the reviewed commit and the changes are ready for human review in PR #1.** Keep the PR in Draft until deployment requirements, architecture decisions, and review feedback are addressed. No merge to `main` is performed by this review. From f96bca05e5b29b05ffb372714791002855e7b06b Mon Sep 17 00:00:00 2001 From: "Robert Software Labs, Inc." Date: Fri, 4 Dec 2026 16:00:18 +0000 Subject: [PATCH 62/75] List trusted proxy resolver in project layout --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index fe0d37b..3a24ec2 100644 --- a/README.md +++ b/README.md @@ -32,6 +32,7 @@ The Bridge does not open the ChatGPT app. It uses the OpenAI API, billed separat - `src/types.ts`: request and response contracts. - `src/rate-limit.ts`: process-local rate limiter and shared limiter contract. - `src/shared-rate-limit.ts`: provider-neutral adapter for atomic shared storage. +- `src/trusted-proxy.ts`: explicit trusted-proxy IP/CIDR validation and client address resolution. - `config/`: bridge, provider and privacy configuration. - `shortcuts/`: action manifest, local prompt and request example. From 3eefa6b8d8fac9dc9e53eb3465577a4f7cabbf19 Mon Sep 17 00:00:00 2001 From: "Robert Software Labs, Inc." Date: Fri, 4 Dec 2026 16:05:29 +0000 Subject: [PATCH 63/75] Add portable OCI container build --- Dockerfile | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 Dockerfile diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..aed060a --- /dev/null +++ b/Dockerfile @@ -0,0 +1,26 @@ +# syntax=docker/dockerfile:1 + +FROM node:22-bookworm-slim AS build +WORKDIR /app + +COPY package.json package-lock.json ./ +RUN npm ci --no-audit --no-fund + +COPY tsconfig.json ./ +COPY src ./src +RUN npm run build + +FROM node:22-bookworm-slim AS runtime +ENV NODE_ENV=production +WORKDIR /app + +COPY --from=build --chown=node:node /app/package.json ./package.json +COPY --from=build --chown=node:node /app/dist ./dist + +USER node +EXPOSE 3000 + +HEALTHCHECK --interval=30s --timeout=3s --start-period=10s --retries=3 \ + CMD node -e "fetch('http://127.0.0.1:'+(process.env.PORT||3000)+'/health').then(r=>process.exit(r.ok?0:1)).catch(()=>process.exit(1))" + +CMD ["node", "dist/server.js"] From 2194c7a02a399a733a3a221804f36f3531bb2817 Mon Sep 17 00:00:00 2001 From: "Robert Software Labs, Inc." Date: Fri, 4 Dec 2026 16:05:31 +0000 Subject: [PATCH 64/75] Exclude local and sensitive files from container context --- .dockerignore | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 .dockerignore diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..c37eaf3 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,13 @@ +.git +.github +node_modules +dist +coverage +.env +.env.* +!.env.example +*.log +tests +README.md +REVIEW.md +SECURITY.md From 1f05cf4a592e62b0621694b4c01dadf6936ee8ae Mon Sep 17 00:00:00 2001 From: "Robert Software Labs, Inc." Date: Fri, 4 Dec 2026 16:05:33 +0000 Subject: [PATCH 65/75] Document portable mobile-managed deployment contract --- docs/DEPLOYMENT.md | 60 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 docs/DEPLOYMENT.md diff --git a/docs/DEPLOYMENT.md b/docs/DEPLOYMENT.md new file mode 100644 index 0000000..379ec2f --- /dev/null +++ b/docs/DEPLOYMENT.md @@ -0,0 +1,60 @@ +# CIB deployment contract + +This document defines the portable container contract for the ChatGPT Intelligence +Bridge. It does not select a hosting vendor or deploy the service. + +## Runtime + +- OCI-compatible container built from the repository's `Dockerfile`. +- Node.js 22 runtime. +- Container listens on `PORT` (defaults to `3000`). +- Start command: `node dist/server.js`. +- Health check: `GET /health`. +- Bridge endpoint: `POST /v1/bridge`. +- The hosting platform must terminate HTTPS before public traffic reaches the service. + +## Required environment + +Configure these values in the hosting platform's secret/environment settings: + +| Variable | Required | Purpose | +| --- | --- | --- | +| `BRIDGE_TOKEN` | Yes | High-entropy bearer token used by the iPhone Shortcut | +| `OPENAI_API_KEY` | Only when cloud fallback is enabled | Server-side OpenAI API credential | +| `PORT` | No | Port supplied by the host; defaults to 3000 | +| `OPENAI_MODEL` | No | Overrides the code's default model identifier | + +Never put either secret in the image, repository, build arguments, client-side configuration, +Shortcut URL, or logs. `BRIDGE_TOKEN` and `OPENAI_API_KEY` are separate credentials. + +## Safe initial deployment profile + +1. Use one service instance while the default in-memory rate limiter is active. +2. Keep the service private until HTTPS, secrets, and proxy identity are configured. +3. Set platform request/body limits and concurrency limits at the edge. +4. Confirm `GET /health` succeeds over the platform's HTTPS URL. +5. Send a local-only test request before enabling cloud fallback. +6. Enable cloud fallback only after the server-side API key and model access are verified. + +Do not scale to multiple instances until a shared `AtomicRateLimitStore` implementation is +injected through `createSharedRateLimiter`. The store must provide an atomic increment and +first-write expiry across every instance. The repository intentionally does not select a +storage vendor. + +## Reverse-proxy identity + +The server ignores `X-Forwarded-For` unless the direct TCP peer matches the configured +`trustedProxies` IP/CIDR allow-list. Obtain the exact proxy egress addresses from the chosen +hosting provider's current documentation before setting this option. Do not guess, use +client-controlled ranges, or trust all forwarded headers. + +A hosting platform that hides its proxy addresses may require a different provider-supported +client-IP mechanism or an edge rate limiter. Until that is resolved, the in-process limiter +may see all requests as coming from the same proxy address. + +## Not yet production-certified + +The container definition makes builds portable; it does not itself complete production +security review. Before public release, validate the chosen provider's HTTPS termination, +proxy behavior, request/concurrency limits, secret handling, log retention, health checks, +and rate-limit behavior. A successful CI run is not a penetration test. From 5150dfcad0dee0421a65e72996d9e892e52cbb90 Mon Sep 17 00:00:00 2001 From: "Robert Software Labs, Inc." Date: Fri, 4 Dec 2026 16:05:47 +0000 Subject: [PATCH 66/75] Document portable container deployment --- README.md | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/README.md b/README.md index 3a24ec2..e885367 100644 --- a/README.md +++ b/README.md @@ -122,3 +122,10 @@ chains and chains longer than 20 hops fall back to the TCP peer. Do not add client-controlled networks or broad ranges to `trustedProxies`; configure the actual proxy egress addresses and ensure the application is not directly reachable around that proxy. + + +## Portable container deployment + +The repository includes an OCI-compatible multi-stage `Dockerfile` and a deployment contract in [docs/DEPLOYMENT.md](docs/DEPLOYMENT.md). The image runs as the unprivileged Node.js user, contains only the compiled service, and exposes the host-provided `PORT` (default 3000). Its health check calls `/health`. + +This keeps the runtime portable across container-capable hosts. No hosting vendor has been selected and no live service has been deployed. Review the deployment contract before connecting a public hostname, especially its single-instance rate-limit and trusted-proxy requirements. From d69931ab2c8ba25f228d38556c15d4ee3ab914fb Mon Sep 17 00:00:00 2001 From: "Robert Software Labs, Inc." Date: Fri, 4 Dec 2026 16:05:50 +0000 Subject: [PATCH 67/75] Validate OCI container image in CI --- .github/workflows/ci.yml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 9fed6f8..707912a 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -22,3 +22,5 @@ jobs: - run: npm audit --audit-level=high - run: npm test - run: npm run build + - name: Build OCI container image + run: docker build --tag cib:ci . From a8f8f637ef0db7d15c8ae2a6f7608e1567fb5645 Mon Sep 17 00:00:00 2001 From: "Robert Software Labs, Inc." Date: Sat, 5 Dec 2026 08:41:03 +0000 Subject: [PATCH 68/75] docs: assess GitHub Actions as CIB runtime --- docs/GITHUB_ACTIONS_RUNTIME_ASSESSMENT.md | 63 +++++++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 docs/GITHUB_ACTIONS_RUNTIME_ASSESSMENT.md diff --git a/docs/GITHUB_ACTIONS_RUNTIME_ASSESSMENT.md b/docs/GITHUB_ACTIONS_RUNTIME_ASSESSMENT.md new file mode 100644 index 0000000..9058063 --- /dev/null +++ b/docs/GITHUB_ACTIONS_RUNTIME_ASSESSMENT.md @@ -0,0 +1,63 @@ +# GitHub Actions runtime assessment + +Status: evaluated; not approved as the production request transport. + +## Decision + +Keep GitHub Actions responsible for repository automation (CI, tests, builds, security checks, and release preparation). Do not treat a GitHub Actions workflow as the public HTTPS runtime for the iPhone Shortcut. + +The CIB currently exposes a synchronous HTTP contract: + +- `GET /health` +- `POST /v1/bridge` +- Bearer authentication through `BRIDGE_TOKEN` +- JSON request and response bodies +- A response returned during the same HTTP request + +A GitHub-hosted Actions job is an ephemeral workflow execution, not a continuously listening Node.js HTTP service. It cannot directly replace the current endpoint without changing the client protocol and request lifecycle. + +## What GitHub can provide + +GitHub supports manually or API-triggered workflows through `workflow_dispatch`. The workflow file must exist on the repository's default branch for this event to trigger. The REST endpoint requires an authenticated token with repository Actions write permission. Dispatch inputs are limited to 25 top-level properties and 65,535 characters total. + +This can be useful for asynchronous jobs, maintenance tasks, and controlled operator-triggered operations. It is not a drop-in HTTPS endpoint for Siri Shortcuts. + +## Security and privacy constraints + +The CIB repository is currently public. A workflow-based request/response transport would introduce additional data handling: + +- The iPhone would need an authenticated GitHub credential capable of dispatching a workflow and reading its result. +- Request content would be sent to GitHub as workflow input. +- Results would need a retrieval channel (for example, an artifact or job output), with explicit access and retention controls. +- Workflow logs, artifacts, run metadata, and retention settings must be treated as potentially exposed to repository readers unless access controls are proven otherwise. +- A broad or long-lived personal access token embedded in a Shortcut is not an acceptable default credential design. +- Workflow execution is asynchronous and may add startup and polling latency. + +Do not send personal prompts, local model output, API credentials, or other private content through the current public repository's workflow inputs, logs, artifacts, or commits. + +## Conditions for reconsidering this approach + +A GitHub Actions transport may be prototyped only after all of the following are designed and verified: + +1. The repository's visibility and access model are explicitly chosen by the owner. +2. The iPhone authentication flow uses a narrowly scoped, revocable credential and does not expose it in exported Shortcut content or logs. +3. Request and response confidentiality is demonstrated end to end. +4. The workflow returns results without publishing prompt or response content to public logs, artifacts, commits, or summaries. +5. Request IDs, timeouts, polling, retries, duplicate dispatches, cancellation, and retention are specified. +6. The user experience is tested from iPhone Shortcuts, including failure and cold-start cases. +7. GitHub Actions usage limits and current billing are checked before enabling regular use. + +## Current implementation boundary + +- Keep the existing Node.js HTTPS service contract unchanged. +- Keep Docker as the portable deployment format. +- Continue using GitHub Actions for CI and build verification. +- Do not add a workflow that accepts real user prompts until the security and privacy conditions above are satisfied. +- Do not change repository visibility, merge the draft PR, create credentials, or enable a paid service as part of this assessment. + +## Official GitHub references + +- [REST API: Create a workflow dispatch event](https://docs.github.com/en/rest/actions/workflows#create-a-workflow-dispatch-event) +- [Triggering a workflow](https://docs.github.com/en/actions/how-tos/write-workflows/choose-when-workflows-run/trigger-a-workflow) +- [GitHub Actions workflow limits](https://docs.github.com/en/actions/reference/limits) +- [GITHUB_TOKEN security model](https://docs.github.com/en/actions/concepts/security/github_token) From b8a101b28fdd2e46286a104af694f5d132b703a2 Mon Sep 17 00:00:00 2001 From: "Robert Software Labs, Inc." Date: Sat, 5 Dec 2026 08:41:13 +0000 Subject: [PATCH 69/75] docs: link GitHub Actions runtime assessment --- README.md | 43 +++++++++++++------------------------------ 1 file changed, 13 insertions(+), 30 deletions(-) diff --git a/README.md b/README.md index e885367..95b4dde 100644 --- a/README.md +++ b/README.md @@ -77,37 +77,23 @@ Insert Shortcuts variables with the variable picker rather than typing their nam - Do not send passwords, authentication codes, financial secrets or sensitive personal data to the cloud. - The server is stateless and does not persist conversation history or log prompt contents. - ## Shared rate limiting -The default limiter stores counters in process memory and is suitable only for a -single server process. For multiple instances, inject a shared implementation: +The default limiter stores counters in process memory and is suitable only for a single server process. For multiple instances, inject a shared implementation: - Implement `AtomicRateLimitStore.increment(key, windowMs)`. -- The backend operation must atomically increment the counter and establish the - expiry on the first write; return `{ count, resetAt }`, where `resetAt` is - an absolute Unix timestamp in milliseconds. -- Do not implement this as separate read, increment and expiry calls: concurrent - requests could exceed the configured limit. -- Use the provider-neutral adapter and inject it through - `createBridgeServer({ rateLimiter })`. -- The adapter hashes the client key before passing it to storage. The storage - provider, credentials, connection lifecycle and availability remain the - responsibility of the hosting application. - -No Redis, database or other storage vendor is bundled or required. If the -shared store fails, the HTTP service returns a generic 503 response; it does -not silently fall back to a per-instance limiter. +- The backend operation must atomically increment the counter and establish the expiry on the first write; return `{ count, resetAt }`, where `resetAt` is an absolute Unix timestamp in milliseconds. +- Do not implement this as separate read, increment and expiry calls: concurrent requests could exceed the configured limit. +- Use the provider-neutral adapter and inject it through `createBridgeServer({ rateLimiter })`. +- The adapter hashes the client key before passing it to storage. The storage provider, credentials, connection lifecycle and availability remain the responsibility of the hosting application. +No Redis, database or other storage vendor is bundled or required. If the shared store fails, the HTTP service returns a generic 503 response; it does not silently fall back to a per-instance limiter. ## Trusted reverse proxies -By default, the service uses the TCP peer address for rate-limit identity and -ignores `X-Forwarded-For`. This prevents arbitrary clients from choosing their -own rate-limit identity. +By default, the service uses the TCP peer address for rate-limit identity and ignores `X-Forwarded-For`. This prevents arbitrary clients from choosing their own rate-limit identity. -If the service is reachable only through a reverse proxy, explicitly configure -the proxy's exact IP addresses or CIDR ranges when creating the server: +If the service is reachable only through a reverse proxy, explicitly configure the proxy's exact IP addresses or CIDR ranges when creating the server: ```ts const server = createBridgeServer({ @@ -115,17 +101,14 @@ const server = createBridgeServer({ }); ``` -Only requests whose direct TCP peer matches this allow-list can use -`X-Forwarded-For`. The service walks the forwarded chain from right to left, -skipping trusted proxy hops and selecting the first untrusted address. Invalid -chains and chains longer than 20 hops fall back to the TCP peer. Do not add -client-controlled networks or broad ranges to `trustedProxies`; configure the -actual proxy egress addresses and ensure the application is not directly -reachable around that proxy. - +Only requests whose direct TCP peer matches this allow-list can use `X-Forwarded-For`. The service walks the forwarded chain from right to left, skipping trusted proxy hops and selecting the first untrusted address. Invalid chains and chains longer than 20 hops fall back to the TCP peer. Do not add client-controlled networks or broad ranges to `trustedProxies`; configure the actual proxy egress addresses and ensure the application is not directly reachable around that proxy. ## Portable container deployment The repository includes an OCI-compatible multi-stage `Dockerfile` and a deployment contract in [docs/DEPLOYMENT.md](docs/DEPLOYMENT.md). The image runs as the unprivileged Node.js user, contains only the compiled service, and exposes the host-provided `PORT` (default 3000). Its health check calls `/health`. This keeps the runtime portable across container-capable hosts. No hosting vendor has been selected and no live service has been deployed. Review the deployment contract before connecting a public hostname, especially its single-instance rate-limit and trusted-proxy requirements. + +## GitHub Actions runtime assessment + +GitHub Actions remains the CIB's CI/build automation environment, not its live HTTPS request server. A workflow-dispatch design would require a separate authentication, request/response, privacy, and retention model. See [docs/GITHUB_ACTIONS_RUNTIME_ASSESSMENT.md](docs/GITHUB_ACTIONS_RUNTIME_ASSESSMENT.md) before considering that alternative. From b7590add81e8a2ff944c1476ab67db679ba3f9f9 Mon Sep 17 00:00:00 2001 From: "Robert Software Labs, Inc." Date: Sat, 5 Dec 2026 08:53:11 +0000 Subject: [PATCH 70/75] Make the iPhone Shortcut local-first and remove mandatory server calls --- shortcuts/shortcut-manifest.json | 45 +++++++++++++++++++++++++++----- 1 file changed, 39 insertions(+), 6 deletions(-) diff --git a/shortcuts/shortcut-manifest.json b/shortcuts/shortcut-manifest.json index 004929e..a40f54b 100644 --- a/shortcuts/shortcut-manifest.json +++ b/shortcuts/shortcut-manifest.json @@ -3,12 +3,45 @@ "invocation": "Siri", "platform": "iOS Shortcuts", "is_importable_shortcut": false, + "default_mode": "on_device_only", "steps": [ - {"index":1,"action":"Dictate Text","output_variable":"UserRequest"}, - {"index":2,"action":"Use Model","model_selection":"Qwen if available; otherwise an iOS-exposed on-device model","prompt_file":"local-model-prompt.txt","output_variable":"LocalResult"}, - {"index":3,"action":"Get Contents of URL","method":"POST","url":"https://YOUR-HOST.example/v1/bridge","headers":{"Content-Type":"application/json","Authorization":"Bearer YOUR_BRIDGE_TOKEN"},"json_body":{"text":"UserRequest variable","local_result":"LocalResult variable","session_id":"YOUR_RANDOM_SHORTCUT_SESSION_ID"},"output_variable":"BridgeResponse"}, - {"index":4,"action":"Get Dictionary Value","dictionary":"BridgeResponse","key":"spoken_text","output_variable":"SpokenText"}, - {"index":5,"action":"Speak Text","input_variable":"SpokenText"} + { + "index": 1, + "action": "Dictate Text", + "output_variable": "UserRequest" + }, + { + "index": 2, + "action": "Use Model", + "model_selection": "On-Device", + "prompt_file": "local-model-prompt.txt", + "input_variable": "UserRequest", + "output_variable": "LocalResult" + }, + { + "index": 3, + "action": "If", + "condition": "LocalResult begins with NEED_CLOUD", + "then": [ + { + "action": "Speak Text", + "text": "Não consigo concluir essa solicitação apenas com o processamento local. Nenhum serviço externo foi chamado." + } + ], + "otherwise": [ + { + "action": "Speak Text", + "input_variable": "LocalResult" + } + ] + } ], - "notes":["Use Shortcuts variable insertion, not literal variable-name strings.","Set the Bridge URL and token after deployment.","iOS may show model, network, or privacy confirmations.","Use Model labels and model choices vary by iOS version and device."] + "network_requests": 0, + "notes": [ + "This default Shortcut does not require a server, API key, account token, or hosting provider.", + "Select the On-Device option in the Use Model action; do not select a cloud or extension model for the no-cost default path.", + "Use Shortcuts variable insertion, not literal variable-name strings.", + "If On-Device is not available in the model picker, do not silently replace it with a cloud model.", + "This JSON is a build manifest, not an importable Apple Shortcut file." + ] } \ No newline at end of file From 73d46ac9afe9ccbdde1b1ba3e175496c8d5b29b4 Mon Sep 17 00:00:00 2001 From: "Robert Software Labs, Inc." Date: Sat, 5 Dec 2026 08:53:14 +0000 Subject: [PATCH 71/75] Set the CIB default runtime to on-device iPhone execution --- config/bridge.config.json | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/config/bridge.config.json b/config/bridge.config.json index 48bb8fc..f29e279 100644 --- a/config/bridge.config.json +++ b/config/bridge.config.json @@ -1 +1,20 @@ -{"name":"ChatGPT Intelligence Bridge","version":"1.0.0","owner":"Robert Software Labs","runtime":"apple-shortcuts-plus-https-typescript","strategy":"hybrid","execution_order":["on_device_model","openai_responses_api"],"cloud_trigger":"local_result_starts_with_NEED_CLOUD","response_channel":"siri_speak_text","session_storage":"stateless","max_input_characters":12000,"max_local_result_characters":16000,"request_timeout_ms":30000} \ No newline at end of file +{ + "name": "ChatGPT Intelligence Bridge", + "version": "1.0.1", + "owner": "Robert Software Labs", + "runtime": "apple-shortcuts-on-device", + "strategy": "local_first", + "execution_order": [ + "iphone_on_device_model", + "siri_speak_text" + ], + "cloud_fallback": { + "enabled_by_default": false, + "requires_explicit_future_opt_in": true + }, + "response_channel": "siri_speak_text", + "session_storage": "none", + "network_requests_by_default": 0, + "max_input_characters": 12000, + "max_local_result_characters": 16000 +} \ No newline at end of file From f4c4432cb361331d373a0ed422c1f34c55d9df96 Mon Sep 17 00:00:00 2001 From: "Robert Software Labs, Inc." Date: Sat, 5 Dec 2026 08:53:16 +0000 Subject: [PATCH 72/75] Default CIB privacy policy to local-only processing --- config/privacy.policy.json | 33 ++++++++++++++++++++++++++++++++- 1 file changed, 32 insertions(+), 1 deletion(-) diff --git a/config/privacy.policy.json b/config/privacy.policy.json index f7c1f65..04a3e24 100644 --- a/config/privacy.policy.json +++ b/config/privacy.policy.json @@ -1 +1,32 @@ -{"version":"1.0","principles":["local_first","data_minimisation","no_prompt_logging","secrets_server_side"],"cloud_transfer":{"enabled_only_when":"local_result begins with NEED_CLOUD","payload_fields":["text"],"exclude_fields":["device_identifiers","contacts","location","files","credentials"]},"retention":{"request_body":"not_persisted","application_logs":"metadata_only"},"user_controls":{"cloud_fallback_can_be_disabled":true,"siri_prompts_and_permissions":"controlled_by_ios"}} \ No newline at end of file +{ + "version": "1.1", + "default_mode": "on_device_only", + "principles": [ + "local_first", + "data_minimisation", + "no_prompt_logging", + "no_network_by_default", + "no_secrets_on_device" + ], + "cloud_transfer": { + "enabled_by_default": false, + "requires_explicit_future_opt_in": true, + "default_payload_fields": [], + "excluded_fields": [ + "device_identifiers", + "contacts", + "location", + "files", + "credentials" + ] + }, + "retention": { + "request_body": "not_persisted_by_cib", + "application_logs": "not_applicable_to_local_shortcut" + }, + "user_controls": { + "cloud_fallback": "not_configured_in_default_shortcut", + "model_selection": "controlled_by_user_in_apple_shortcuts", + "siri_prompts_and_permissions": "controlled_by_ios" + } +} \ No newline at end of file From c0dc92929063ae2701f24aaad881d825ad97a8ec Mon Sep 17 00:00:00 2001 From: "Robert Software Labs, Inc." Date: Sat, 5 Dec 2026 08:53:17 +0000 Subject: [PATCH 73/75] Remove automatic cloud providers from the default CIB configuration --- config/providers.json | 24 +++++++++++++++++++++++- 1 file changed, 23 insertions(+), 1 deletion(-) diff --git a/config/providers.json b/config/providers.json index 5dc0f6e..dd1e1ec 100644 --- a/config/providers.json +++ b/config/providers.json @@ -1 +1,23 @@ -{"providers":[{"id":"qwen-on-device","type":"shortcuts-use-model","priority":1,"execution_location":"iphone","enabled":true,"role":"local_first","notes":"Selected in the iOS Shortcuts Use Model action when exposed by the device."},{"id":"apple-intelligence","type":"shortcuts-use-model","priority":2,"execution_location":"iphone","enabled":true,"role":"on_device_or_system_model_fallback","notes":"Use only if available in the device's Shortcuts model picker."},{"id":"openai-responses","type":"https","priority":3,"execution_location":"bridge-server","endpoint":"https://api.openai.com/v1/responses","enabled":true,"role":"cloud_fallback","secret_env":"OPENAI_API_KEY"}]} \ No newline at end of file +{ + "default_provider": { + "id": "apple-on-device", + "type": "shortcuts-use-model", + "priority": 1, + "execution_location": "iphone", + "enabled": true, + "role": "default_local_inference", + "network_required": false, + "notes": "Select the On-Device option in the iOS Shortcuts Use Model action." + }, + "optional_providers": [ + { + "id": "openai-responses", + "type": "https", + "execution_location": "optional_external_service", + "enabled": false, + "requires_explicit_opt_in": true, + "secret_env": "OPENAI_API_KEY", + "notes": "Not used by the default iPhone Shortcut. Enabling this provider may incur separate API charges and requires a hosted service." + } + ] +} \ No newline at end of file From a73e9cc04dd37cae51e0e186ca67a2f85f8f80f8 Mon Sep 17 00:00:00 2001 From: "Robert Software Labs, Inc." Date: Sat, 5 Dec 2026 08:53:20 +0000 Subject: [PATCH 74/75] Clarify that server deployment is optional and not required by the iPhone workflow --- docs/DEPLOYMENT.md | 61 +++++++++++++++------------------------------- 1 file changed, 19 insertions(+), 42 deletions(-) diff --git a/docs/DEPLOYMENT.md b/docs/DEPLOYMENT.md index 379ec2f..bbf8254 100644 --- a/docs/DEPLOYMENT.md +++ b/docs/DEPLOYMENT.md @@ -1,9 +1,10 @@ -# CIB deployment contract +# Optional CIB server deployment -This document defines the portable container contract for the ChatGPT Intelligence -Bridge. It does not select a hosting vendor or deploy the service. +**The default CIB does not require a server deployment.** The iPhone Shortcut runs the selected on-device model and speaks its result directly through Siri. Do not create a hosting account, configure a domain, or add API credentials for the default workflow. -## Runtime +This document applies only if a future version explicitly enables a remote provider. + +## Optional runtime - OCI-compatible container built from the repository's `Dockerfile`. - Node.js 22 runtime. @@ -11,50 +12,26 @@ Bridge. It does not select a hosting vendor or deploy the service. - Start command: `node dist/server.js`. - Health check: `GET /health`. - Bridge endpoint: `POST /v1/bridge`. -- The hosting platform must terminate HTTPS before public traffic reaches the service. - -## Required environment +- Public traffic requires HTTPS termination. -Configure these values in the hosting platform's secret/environment settings: +## Optional environment | Variable | Required | Purpose | | --- | --- | --- | -| `BRIDGE_TOKEN` | Yes | High-entropy bearer token used by the iPhone Shortcut | -| `OPENAI_API_KEY` | Only when cloud fallback is enabled | Server-side OpenAI API credential | -| `PORT` | No | Port supplied by the host; defaults to 3000 | +| `BRIDGE_TOKEN` | Yes, for a deployed endpoint | Bearer token for an explicitly configured remote client | +| `OPENAI_API_KEY` | Only if OpenAI fallback is explicitly enabled | Server-side OpenAI API credential | +| `PORT` | No | Port supplied by the host; defaults to `3000` | | `OPENAI_MODEL` | No | Overrides the code's default model identifier | -Never put either secret in the image, repository, build arguments, client-side configuration, -Shortcut URL, or logs. `BRIDGE_TOKEN` and `OPENAI_API_KEY` are separate credentials. - -## Safe initial deployment profile - -1. Use one service instance while the default in-memory rate limiter is active. -2. Keep the service private until HTTPS, secrets, and proxy identity are configured. -3. Set platform request/body limits and concurrency limits at the edge. -4. Confirm `GET /health` succeeds over the platform's HTTPS URL. -5. Send a local-only test request before enabling cloud fallback. -6. Enable cloud fallback only after the server-side API key and model access are verified. - -Do not scale to multiple instances until a shared `AtomicRateLimitStore` implementation is -injected through `createSharedRateLimiter`. The store must provide an atomic increment and -first-write expiry across every instance. The repository intentionally does not select a -storage vendor. - -## Reverse-proxy identity - -The server ignores `X-Forwarded-For` unless the direct TCP peer matches the configured -`trustedProxies` IP/CIDR allow-list. Obtain the exact proxy egress addresses from the chosen -hosting provider's current documentation before setting this option. Do not guess, use -client-controlled ranges, or trust all forwarded headers. +Never put secrets in the repository, container image, build arguments, client-side configuration, Shortcut URL, or logs. API usage is billed separately from a ChatGPT subscription. -A hosting platform that hides its proxy addresses may require a different provider-supported -client-IP mechanism or an edge rate limiter. Until that is resolved, the in-process limiter -may see all requests as coming from the same proxy address. +## Security requirements before any deployment -## Not yet production-certified +1. Keep the service private until HTTPS, secrets, and proxy identity are configured. +2. Confirm `GET /health` over the platform's HTTPS URL. +3. Keep the default in-memory rate limiter to one service process, or inject a shared atomic store before scaling. +4. Configure exact trusted proxy IP/CIDR ranges; do not trust arbitrary forwarded headers. +5. Verify provider request limits, concurrency limits, secret handling, and log retention. +6. Test with non-sensitive data before enabling any cloud provider. -The container definition makes builds portable; it does not itself complete production -security review. Before public release, validate the chosen provider's HTTPS termination, -proxy behavior, request/concurrency limits, secret handling, log retention, health checks, -and rate-limit behavior. A successful CI run is not a penetration test. +No hosting vendor is selected. No live service is deployed. Deployment is not part of the default CIB setup and should not be undertaken unless a concrete feature requires it. From e3de61ebc01d7f74f717d98526c9fb47c2789ca4 Mon Sep 17 00:00:00 2001 From: "Robert Software Labs, Inc." Date: Sat, 5 Dec 2026 08:53:46 +0000 Subject: [PATCH 75/75] Document the zero-hosting local-only CIB workflow --- README.md | 157 +++++++++++++++++++++++------------------------------- 1 file changed, 67 insertions(+), 90 deletions(-) diff --git a/README.md b/README.md index 95b4dde..82f15f7 100644 --- a/README.md +++ b/README.md @@ -1,114 +1,91 @@ -# ChatGPT Intelligence Bridge — v1.0.0 +# ChatGPT Intelligence Bridge — iPhone-first -Robert Software Labs -Runtime: iPhone Apple Shortcuts + HTTPS TypeScript service -Strategy: Hybrid (on-device model first, ChatGPT API only when needed) -Output: Siri speaks the final answer +Robert Software Labs -## Platform boundary +**Default runtime:** Apple Shortcuts on iPhone +**Default strategy:** on-device first, no network requests +**Output:** Siri speaks the answer +**Server:** optional; not required for normal use -Apple Shortcuts does not execute TypeScript directly. The iPhone Shortcut calls this TypeScript service over HTTPS, so the service must run on a Node.js host. +## The simple version -The JSON files in `shortcuts/` are manifests and build instructions, not importable `.shortcut` files. iOS has no supported universal JSON-to-Shortcut importer. +The default CIB is one iPhone Shortcut. Siri captures the request, the Shortcuts **Use Model** action runs the selected **On-Device** model, and **Speak Text** reads the result. -The on-device Qwen / Apple Intelligence step runs inside Shortcuts using a model action exposed by iOS. Only a result beginning with `NEED_CLOUD` triggers the OpenAI API fallback. +The default path does not require: +- A hosting provider, server, domain, or Docker deployment. +- An OpenAI API key, API billing, or a bridge token. +- GitHub Actions at runtime. +- A database, Redis, or conversation-history service. +- Multiple Shortcuts or separate provider-specific automations. -## Request flow +The JSON file in `shortcuts/` is a build manifest, not an importable Apple Shortcut file. Apple does not provide a universal JSON-to-Shortcut importer. -1. Siri starts the Shortcut and dictates the request. -2. Shortcuts invokes **Use Model**, selecting Qwen if available or another on-device model exposed by iOS. -3. The model answers locally where possible; when remote information or stronger cloud reasoning is required, it begins with `NEED_CLOUD`. -4. Shortcuts sends `text` and `local_result` to `POST /v1/bridge`. -5. The service returns the local answer or calls OpenAI's Responses API. -6. Shortcuts extracts `spoken_text` and invokes **Speak Text**. +## Default request flow -The Bridge does not open the ChatGPT app. It uses the OpenAI API, billed separately from a ChatGPT subscription. +1. Siri starts **ChatGPT Intelligence Bridge** and captures the user's request with **Dictate Text**. +2. **Use Model** is explicitly set to **On-Device**. +3. The model produces a local answer. +4. **Speak Text** reads that answer. +5. If the model returns the `NEED_CLOUD` marker, the Shortcut speaks a short notice that local processing could not complete the request. It does not call a server or silently switch to a cloud model. -## Project layout - -- `src/server.ts`: dependency-free Node.js HTTP service. -- `src/bridge.ts`: local/cloud routing policy. -- `src/openai.ts`: OpenAI Responses API adapter. -- `src/types.ts`: request and response contracts. -- `src/rate-limit.ts`: process-local rate limiter and shared limiter contract. -- `src/shared-rate-limit.ts`: provider-neutral adapter for atomic shared storage. -- `src/trusted-proxy.ts`: explicit trusted-proxy IP/CIDR validation and client address resolution. -- `config/`: bridge, provider and privacy configuration. -- `shortcuts/`: action manifest, local prompt and request example. - -## Requirements and deployment - -- Node.js 20+ -- HTTPS hosting -- `OPENAI_API_KEY` and `BRIDGE_TOKEN` configured as host-side secrets -- Optional `OPENAI_MODEL` and host-provided `PORT` - -Run from the repository root: - -```bash -npm ci -npm run build -npm start -``` - -`package-lock.json` is committed and must be kept in sync with `package.json`. Use `npm ci` for clean, repeatable installs in CI and deployments; it installs the exact dependency tree recorded in the lockfile and fails if the manifest and lockfile disagree. Use `npm install` only when intentionally changing dependencies, then commit both `package.json` and the regenerated `package-lock.json` together. +**Important:** Do not replace **On-Device** with a cloud or extension model if the goal is to avoid network use and additional charges. If the On-Device option is unavailable, stop and check device language, region, and Apple Intelligence availability rather than silently selecting another provider. -Never commit secrets or place them in Shortcut URLs. Keep `OPENAI_API_KEY` on the server and the separate `BRIDGE_TOKEN` in the Shortcut's Authorization header. +## Build the single Shortcut on iPhone -## Build the Shortcut on iPhone +Create one Shortcut named **ChatGPT Intelligence Bridge** with these actions: -Create a Shortcut named **ChatGPT Intelligence Bridge**: +1. **Dictate Text** — save the result as `UserRequest`. +2. **Use Model** — choose **On-Device**, pass `UserRequest` as input, and use the instructions in [shortcuts/local-model-prompt.txt](shortcuts/local-model-prompt.txt). Save the result as `LocalResult`. +3. **If** `LocalResult` begins with `NEED_CLOUD`: + - **Speak Text:** "Não consigo concluir essa solicitação apenas com o processamento local. Nenhum serviço externo foi chamado." +4. **Otherwise:** + - **Speak Text** using `LocalResult`. -1. **Dictate Text** → save as `UserRequest`. -2. **Use Model** → select Qwen if available, otherwise an iOS-exposed on-device model; use `shortcuts/local-model-prompt.txt` and save as `LocalResult`. -3. **Get Contents of URL** → POST to `https://YOUR-HOST.example/v1/bridge`, with JSON body keys `text`, `local_result`, and `session_id`; set `Content-Type: application/json` and `Authorization: Bearer YOUR_BRIDGE_TOKEN`. -4. Extract `spoken_text` from the response. -5. **Speak Text** using that value. +Use the Shortcuts variable picker to insert variables. Do not type variable names as ordinary text. -Insert Shortcuts variables with the variable picker rather than typing their names as literal strings. Siri confirmations and privacy prompts remain controlled by iOS. +The complete action sequence is recorded in [shortcuts/shortcut-manifest.json](shortcuts/shortcut-manifest.json). Siri permissions and model availability remain controlled by iOS. -## Behaviour and limitations +## Optional remote service -- A normal local answer is returned without calling OpenAI. -- Only the `NEED_CLOUD` prefix triggers cloud fallback. -- The service uses `/v1/responses`. -- It does not call private Siri or Apple Intelligence frameworks. -- It cannot bypass iOS permission prompts or privacy indicators. -- Do not send passwords, authentication codes, financial secrets or sensitive personal data to the cloud. -- The server is stateless and does not persist conversation history or log prompt contents. +The TypeScript service remains in this repository for a future, explicitly requested remote-provider integration. It is not part of the default Shortcut and should not be deployed for ordinary local use. -## Shared rate limiting +A remote OpenAI fallback requires a separately hosted HTTPS service and an API key. OpenAI API usage is billed separately from a ChatGPT subscription. The default configuration disables optional providers; see [config/providers.json](config/providers.json), [config/bridge.config.json](config/bridge.config.json), and [config/privacy.policy.json](config/privacy.policy.json). -The default limiter stores counters in process memory and is suitable only for a single server process. For multiple instances, inject a shared implementation: +Do not create hosting accounts, API keys, tokens, or paid services just to use the default CIB. -- Implement `AtomicRateLimitStore.increment(key, windowMs)`. -- The backend operation must atomically increment the counter and establish the expiry on the first write; return `{ count, resetAt }`, where `resetAt` is an absolute Unix timestamp in milliseconds. -- Do not implement this as separate read, increment and expiry calls: concurrent requests could exceed the configured limit. -- Use the provider-neutral adapter and inject it through `createBridgeServer({ rateLimiter })`. -- The adapter hashes the client key before passing it to storage. The storage provider, credentials, connection lifecycle and availability remain the responsibility of the hosting application. +If the optional TypeScript service is developed or tested, use: -No Redis, database or other storage vendor is bundled or required. If the shared store fails, the HTTP service returns a generic 503 response; it does not silently fall back to a per-instance limiter. - -## Trusted reverse proxies - -By default, the service uses the TCP peer address for rate-limit identity and ignores `X-Forwarded-For`. This prevents arbitrary clients from choosing their own rate-limit identity. - -If the service is reachable only through a reverse proxy, explicitly configure the proxy's exact IP addresses or CIDR ranges when creating the server: - -```ts -const server = createBridgeServer({ - trustedProxies: ["10.20.0.10/32", "2001:db8:1234::/48"] -}); +```bash +npm ci +npm test +npm run build ``` -Only requests whose direct TCP peer matches this allow-list can use `X-Forwarded-For`. The service walks the forwarded chain from right to left, skipping trusted proxy hops and selecting the first untrusted address. Invalid chains and chains longer than 20 hops fall back to the TCP peer. Do not add client-controlled networks or broad ranges to `trustedProxies`; configure the actual proxy egress addresses and ensure the application is not directly reachable around that proxy. - -## Portable container deployment - -The repository includes an OCI-compatible multi-stage `Dockerfile` and a deployment contract in [docs/DEPLOYMENT.md](docs/DEPLOYMENT.md). The image runs as the unprivileged Node.js user, contains only the compiled service, and exposes the host-provided `PORT` (default 3000). Its health check calls `/health`. +The repository's GitHub Actions workflow runs CI only. It is not the runtime for Siri requests. See [docs/GITHUB_ACTIONS_RUNTIME_ASSESSMENT.md](docs/GITHUB_ACTIONS_RUNTIME_ASSESSMENT.md). -This keeps the runtime portable across container-capable hosts. No hosting vendor has been selected and no live service has been deployed. Review the deployment contract before connecting a public hostname, especially its single-instance rate-limit and trusted-proxy requirements. - -## GitHub Actions runtime assessment +## Project layout -GitHub Actions remains the CIB's CI/build automation environment, not its live HTTPS request server. A workflow-dispatch design would require a separate authentication, request/response, privacy, and retention model. See [docs/GITHUB_ACTIONS_RUNTIME_ASSESSMENT.md](docs/GITHUB_ACTIONS_RUNTIME_ASSESSMENT.md) before considering that alternative. +- `shortcuts/shortcut-manifest.json`: single local-only Shortcut action manifest. +- `shortcuts/local-model-prompt.txt`: local model instructions. +- `config/bridge.config.json`: default local runtime configuration. +- `config/providers.json`: default and optional provider policy. +- `config/privacy.policy.json`: local-first privacy defaults. +- `src/`: optional TypeScript HTTP bridge and remote provider adapter. +- `tests/`: automated tests for the optional TypeScript service. +- `docs/DEPLOYMENT.md`: optional server deployment requirements. + +## Privacy and limitations + +- The default Shortcut sends no prompt to a CIB server. +- No CIB conversation history is stored. +- Model processing location is determined by the selected **On-Device** option; do not assume cloud and on-device choices are equivalent. +- Local models may not answer requests requiring live web information or remote actions. +- The `NEED_CLOUD` branch is intentionally a notice, not an automatic cloud handoff. +- Do not send passwords, authentication codes, or other secrets to an AI model. + +## Project status + +- The original `main` branch remains preserved. +- Implementation changes are maintained on `implementation/v1.0.1-foundation`. +- Pull request #1 remains a draft and has not been merged. +- No hosting vendor has been selected, no paid service has been enabled, and no deployment has been performed.