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 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 diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..707912a --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,26 @@ +name: CIB CI + +on: + pull_request: + branches: [main] + push: + branches: [implementation/v1.0.1-foundation] + +permissions: + contents: read + +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 ci --no-audit --no-fund + - run: npm audit --audit-level=high + - run: npm test + - run: npm run build + - name: Build OCI container image + run: docker build --tag cib:ci . 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 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"] diff --git a/README.md b/README.md index 1bb1e3b..82f15f7 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,91 @@ -# ChatGPT_Intelligence_Bridge -ChatGPT integration Apple Intelligence & Siri. +# ChatGPT Intelligence Bridge — iPhone-first + +Robert Software Labs + +**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 + +## The simple version + +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 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. + +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. + +## Default request flow + +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. + +**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. + +## Build the single Shortcut on iPhone + +Create one Shortcut named **ChatGPT Intelligence Bridge** with these actions: + +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`. + +Use the Shortcuts variable picker to insert variables. Do not type variable names as ordinary text. + +The complete action sequence is recorded in [shortcuts/shortcut-manifest.json](shortcuts/shortcut-manifest.json). Siri permissions and model availability remain controlled by iOS. + +## Optional remote service + +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. + +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). + +Do not create hosting accounts, API keys, tokens, or paid services just to use the default CIB. + +If the optional TypeScript service is developed or tested, use: + +```bash +npm ci +npm test +npm run build +``` + +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). + +## Project layout + +- `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. diff --git a/REVIEW.md b/REVIEW.md new file mode 100644 index 0000000..d033893 --- /dev/null +++ b/REVIEW.md @@ -0,0 +1,44 @@ +# CIB — implementation review + +**Review date:** 2026-12-04 +**Reviewed branch:** `implementation/v1.0.1-foundation` +**Reviewed commit:** `3d55134fb020c46fec713865c9bfa44a899b8cc6` +**Pull request:** #1 — open, Draft, not merged + +## Verified in CI + +The GitHub Actions push workflow completed successfully for the reviewed commit. + +- `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/47370949920 + +## Changes reviewed + +- 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. +- 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. + +## Remaining deployment requirements + +This review does not certify production readiness. Before public deployment: + +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 + +**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. diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 0000000..f94552d --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,59 @@ +# 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. +- 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. +- 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. + +## Deployment requirements and remaining risks + +- 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. +- 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 + exposed. Never commit live credentials or place them in Shortcut URLs. +- 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. + +## 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`. diff --git a/config/bridge.config.json b/config/bridge.config.json new file mode 100644 index 0000000..f29e279 --- /dev/null +++ b/config/bridge.config.json @@ -0,0 +1,20 @@ +{ + "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 diff --git a/config/privacy.policy.json b/config/privacy.policy.json new file mode 100644 index 0000000..04a3e24 --- /dev/null +++ b/config/privacy.policy.json @@ -0,0 +1,32 @@ +{ + "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 diff --git a/config/providers.json b/config/providers.json new file mode 100644 index 0000000..dd1e1ec --- /dev/null +++ b/config/providers.json @@ -0,0 +1,23 @@ +{ + "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 diff --git a/docs/DEPLOYMENT.md b/docs/DEPLOYMENT.md new file mode 100644 index 0000000..bbf8254 --- /dev/null +++ b/docs/DEPLOYMENT.md @@ -0,0 +1,37 @@ +# Optional CIB server deployment + +**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. + +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. +- Container listens on `PORT` (defaults to `3000`). +- Start command: `node dist/server.js`. +- Health check: `GET /health`. +- Bridge endpoint: `POST /v1/bridge`. +- Public traffic requires HTTPS termination. + +## Optional environment + +| Variable | Required | Purpose | +| --- | --- | --- | +| `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 secrets in the repository, container image, build arguments, client-side configuration, Shortcut URL, or logs. API usage is billed separately from a ChatGPT subscription. + +## Security requirements before any deployment + +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. + +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. 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) 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" + } + } +} diff --git a/package.json b/package.json new file mode 100644 index 0000000..ece5225 --- /dev/null +++ b/package.json @@ -0,0 +1,18 @@ +{ + "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" + } +} 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 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 diff --git a/shortcuts/shortcut-manifest.json b/shortcuts/shortcut-manifest.json new file mode 100644 index 0000000..a40f54b --- /dev/null +++ b/shortcuts/shortcut-manifest.json @@ -0,0 +1,47 @@ +{ + "name": "ChatGPT Intelligence Bridge", + "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": "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" + } + ] + } + ], + "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 diff --git a/src/bridge.ts b/src/bridge.ts new file mode 100644 index 0000000..b2afd28 --- /dev/null +++ b/src/bridge.ts @@ -0,0 +1,42 @@ +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"; + +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(); + + 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) { + return { + ok: true, + route: "local", + spoken_text: localResult, + request_id: requestId + }; + } + + const answer = await cloudFallback(text); + return { + ok: true, + route: "openai", + spoken_text: answer, + request_id: requestId + }; +} diff --git a/src/openai.ts b/src/openai.ts new file mode 100644 index 0000000..4accbf4 --- /dev/null +++ b/src/openai.ts @@ -0,0 +1,72 @@ +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 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: options.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 fetcher = options.fetcher ?? fetch; + let response: Response; + try { + response = await fetcher(OPENAI_URL, { + method: "POST", + headers: { + Authorization: `Bearer ${apiKey}`, + "Content-Type": "application/json" + }, + body: JSON.stringify(payload), + signal: AbortSignal.timeout(options.timeoutMs ?? 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(); +} diff --git a/src/rate-limit.ts b/src/rate-limit.ts new file mode 100644 index 0000000..81b612b --- /dev/null +++ b/src/rate-limit.ts @@ -0,0 +1,71 @@ +export interface RateLimitOptions { + limit: number; + windowMs: number; + maxKeys?: number; + now?: () => number; +} + +interface WindowEntry { + count: number; + resetAt: number; +} + +export interface RateLimitResult { + allowed: boolean; + retryAfterSeconds: number; +} + +/** + * 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 || !Number.isFinite(windowMs) || windowMs < 1 || + !Number.isInteger(maxKeys) || 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 }; + } + }; +} diff --git a/src/server.ts b/src/server.ts new file mode 100644 index 0000000..dc44331 --- /dev/null +++ b/src/server.ts @@ -0,0 +1,141 @@ +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"; +import { parseBridgeRequest, RequestValidationError } from "./validation.js"; + +const MAX_BODY_BYTES = 64 * 1024; +type BridgeHandler = typeof handleBridge; + +export interface BridgeServerOptions { + token?: string; + rateLimit?: number; + rateWindowMs?: number; + maxRateLimitKeys?: number; + rateLimiter?: RateLimiter; + trustedProxies?: readonly string[]; + 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(expectedToken); + return supplied.length === target.length && timingSafeEqual(supplied, target); +} + +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"; +} + +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"); + } +} + +export function createBridgeServer(options: BridgeServerOptions = {}): Server { + const token = options.token ?? process.env.BRIDGE_TOKEN; + const limiter = options.rateLimiter ?? createRateLimiter({ + limit: options.rateLimit ?? 60, + windowMs: options.rateWindowMs ?? 60_000, + 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"); + res.setHeader("Cache-Control", "no-store"); + 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; + } + + let rate: Awaited>; + try { + rate = await limiter.check(resolveClientAddress(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" })); + return; + } + + if (!isAuthorized(req.headers.authorization, token)) { + res.writeHead(401).end(JSON.stringify({ ok: false, error: "Unauthorized" })); + return; + } + + 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; + } + + 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; + } + + 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" })); + } + }); + + // 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] && + 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}`)); +} 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)) + }; + } + }; +} 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); +} 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 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 } : {}) + }; +} 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/ + ); +}); 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/ + ); +}); diff --git a/tests/security.test.ts b/tests/security.test.ts new file mode 100644 index 0000000..5f46e74 --- /dev/null +++ b/tests/security.test.ts @@ -0,0 +1,174 @@ +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); +}); + + +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); +}); + + +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/); +}); diff --git a/tests/server.integration.test.ts b/tests/server.integration.test.ts new file mode 100644 index 0000000..c48d7de --- /dev/null +++ b/tests/server.integration.test.ts @@ -0,0 +1,248 @@ +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": "application/jsonp" }, + 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, 1); + }, { + 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("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, "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`, { + 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); + }); +}); + + +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"); + } + } + }); +}); + +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 }; + } + } + }); +}); 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"] })); +}); 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