diff --git a/docs/README.md b/docs/README.md index 9a6a97fe..7a8d4ac6 100644 --- a/docs/README.md +++ b/docs/README.md @@ -5,6 +5,8 @@ - [Project Zomboid backups](./project-zomboid-backups.md) - [Gitea Kanban CLI](./gitea-kanban-cli.md) - [AFFiNE document typography](./affine-typography.md) +- [Native AFFiNE deployment and migration](./affine-native.md) +- [ChatGPT subscription connector for AFFiNE](./affine-chatgpt.md) ## Gitea runner labels diff --git a/docs/affine-chatgpt.md b/docs/affine-chatgpt.md new file mode 100644 index 00000000..78a85572 --- /dev/null +++ b/docs/affine-chatgpt.md @@ -0,0 +1,206 @@ +# AFFiNE ChatGPT subscription connector + +`affine-chatgpt` uses the official Sign in with ChatGPT preview flow. It does not +use browser cookies, another application's OAuth client, or an API-billing +fallback. Account eligibility and usage limits are controlled by OpenAI. + +## Native service + +The reusable NixOS module is `hectic.services.affine-chatgpt`. The hectic-lab +host enables it in `nixos/system/hectic-lab/affine-chatgpt.nix`. + +- Unit: `affine-chatgpt.service`, running as `affine-chatgpt`. +- Listener: `127.0.0.1:3012`; no public port or Docker dependency. +- OAuth state: `/var/lib/affine-chatgpt/session`, mode `0700`. +- Credentials and stable gateway key: owner-only files, mode `0600`. +- Gateway key: `/var/lib/affine-chatgpt/gateway-key`. + +Do not put credentials or key contents in Nix expressions, the Nix store, +environment variables, command arguments, logs, screenshots, or Git. The +service receives only the protected key's path. Keep the key stable: AFFiNE +stores its value as an encrypted workspace BYOK credential. + +The service is deliberately not started when the OAuth credential file is +absent. Provision the state before starting it, using the service account's +ownership. Preserve the original private directory/file permissions. + +## Authorize and move a session + +On the computer running the user's regular browser: + +```sh +nix run .#affine-chatgpt -- login +nix run .#affine-chatgpt -- status +nix run .#affine-chatgpt -- models +``` + +Open the printed OpenAI authorization URL in the normal browser, not a +temporary automation browser. Complete login, any passkey challenge, and app +consent. The loopback callback is `http://127.0.0.1:1455/auth/callback`; the +listener expires after 15 minutes unless `login --timeout` is specified. + +For a self-hosted VM, securely transfer the complete credential record over +SSH. Create and persist a distinct VM host ID in `session/host.json`; do not +overwrite it with the laptop's host ID. Associate the imported credential's +`host_id` with that VM. Use the same issued client registration, not the +`dynamic_agent_client` registration entrypoint, for subsequent token exchanges. + +After a successful remote model and inference test, remove the local active +credential record. Only the VM should rotate the imported refresh token. +Never copy a different application's credential record or session cookies. + +Login and model-list success prove enrollment and catalog access, not working +inference. Require a streamed request ending with `response.completed` before +claiming that the subscription works. + +## AFFiNE configuration + +Configure these settings through AFFiNE's supported administrator API/UI, not +direct SQL or source-embedded secrets: + +```json +{ + "copilot.enabled": true, + "copilot.byok.enabled": true, + "copilot.byok.allowedProviders": ["openai"], + "copilot.byok.allowCustomEndpoint": true, + "copilot.byok.allowPrivateEndpoint": true +} +``` + +The native AFFiNE wrapper sets `DEPLOYMENT_TYPE=selfhosted`, required for custom +endpoints. The stable AFFiNE `private.key` must be preserved so stored BYOK +credentials remain decryptable. + +Add a workspace BYOK provider: + +- Provider: `openai`. +- Endpoint kind: `openai_compatible`. +- URL: `http://127.0.0.1:3012/v1`. +- Dialect: `responses`, not Chat Completions. +- Credential: the protected gateway key, not an OpenAI token. +- Model: a slug returned by the authorized account's catalog. +- Initial capabilities: text input/output and `tool_calling`, no attachments. + +Persistent AFFiNE BYOK is workspace-wide. All authorized workspace members can +consume the connected account's limits and send document context/tool results +to OpenAI. User consent to shared access does not replace OpenAI's account and +subscription terms. + +## Supported transport + +The gateway authenticates requests before reading their bodies. It supports +`GET /v1/models` and `POST /v1/responses`, text history, function/custom tools, +and function-call results. AFFiNE executes tools; the gateway never executes +shell commands or document tools itself. + +Upstream requests always use `store:false` and `stream:true`. Non-streaming +AFFiNE probes are assembled from completed SSE output items and the final +completion event. An explicitly non-SSE Content-Type is rejected; a missing +Content-Type is accepted only through the same strict SSE parser. Failed, +incomplete, malformed, or interrupted streams are not reported as successful. + +Image generation, image/file/audio attachments, hosted MCP, Code Interpreter, +and persistent Responses conversation IDs are not supported. Do not declare +those capabilities in AFFiNE. + +## Verification and development + +```sh +nix build .#affine-chatgpt +nix build .#checks.x86_64-linux.affine-chatgpt-enrollment +nix build .#checks.x86_64-linux.affine-chatgpt-module +nix build .#checks.x86_64-linux.affine-model-picker +nix build .#affine-chatgpt.pythonEnv --out-link package/affine-chatgpt/.venv +pyright --project package/affine-chatgpt/pyrightconfig.json \ + --pythonpath package/affine-chatgpt/.venv/bin/python3 +``` + +Package checks use fake credentials and local HTTP fixtures only. Real smoke +tests should verify unauthenticated `401`, model filtering, text response, +function-call output, streamed completion, restart, and token refresh without +printing credentials. A successful direct gateway test is not proof that +AFFiNE's workspace provider and chat UI have been configured. + +References: + +- +- +- + +## hectic-lab deployment + +The native service is active and the shared AFFiNE workspace has an enabled +`ChatGPT subscription` BYOK profile pointing at `http://127.0.0.1:3012/v1`. +The profile offers these account-catalog models, each with text input/output +and tool calling: + +- `gpt-5.6-luna` +- `gpt-5.6-terra` +- `gpt-5.6-sol` +- `gpt-6-luna` +- `gpt-6-sol` +- `gpt-6-astra` +- `gpt-6.1-terra` +- `gpt-6.1-sol` + +The existing first/default model remains `gpt-5.6-luna`. All eight models passed +AFFiNE's chat and tool-calling probes. A two-turn chat switched from +`gpt-5.6-luna` to `gpt-6.1-sol`; the second model recovered a random marker from +the first turn, confirming conversation history is retained across the switch. +The temporary test conversation was removed through AFFiNE's API. Model changes +use the existing workspace profile and do not replace its encrypted credential +or require another OAuth login. Reload an already-open client to refresh its +model catalog. + +The pinned AFFiNE frontend originally exposed only managed route choices, which +are empty on self-hosted servers. `package/affine/byok-model-picker.patch` adds +workspace BYOK models to the existing Model menu and forwards the selected +profile/model separately from managed route IDs. Auto and managed selections +remain supported; retries retain the last request selection in memory. + +BYOK discovery uses the existing owner/admin settings API. Owners and workspace +admins can choose these models in the patched selector; ordinary members retain +Auto and can use the shared default profile without gaining settings access. +No backend permission or Enterprise source code is changed. + +The native module's optional `frontendPackage` mounts matching source-built +static assets read-only into the application service. Backend binaries and +migration units stay unchanged during this frontend-only rollout. Compatibility +checks require matching release and source revision. The host explicitly enables +this override; a standalone module with no override keeps its bundled frontend. + +For a frontend-only rollout, build the static artifact and picker check, inspect +the host activation plan, then activate the host configuration normally: + +```sh +nix build .#affine-frontend-static .#checks.x86_64-linux.affine-model-picker +nixos-rebuild switch --flake '.#hectic-lab|x86_64-linux' +``` + +Only `affine-native.service` should restart for a static-only change. Its +migration unit, dedicated PostgreSQL and Redis must keep their existing package +and restart triggers. Reload the client with a hard refresh after deployment to +discard cached frontend chunks. + +### Verified picker rollout + +The patched selector is deployed in NixOS generation +`1mvb1nb5xqhaj8xfskxi00lj39lmbpzl`. It binds frontend static package +`hrg3dkcacg5drizifiinjx481k6k33d5` over the unchanged native backend's static +directory. The activation restarted only AFFiNE; PostgreSQL, Redis and migration +unit process/state timestamps remained unchanged. + +An authenticated headless browser verified all eight menu choices and selected +`gpt-6.1-sol`. The real selector returned the expected `profileId` and `modelId` +with no managed `routeTargetId`; the trigger displayed the selected model. +Open the AI input's Auto/current-model control, then its Model submenu. Use a +hard refresh (`Ctrl+F5`) if the old interface is still cached. + +Account OAuth enrollment, remote catalog access, text generation, function +calls and streamed tool results were tested. AFFiNE's own provider probes and +chat SSE endpoint also passed, including automatic profile routing. + +Only the server now owns the imported rotating session; the local active +credential copy was removed after remote verification. Images and attachments +remain unsupported and are not advertised by the profile. diff --git a/docs/affine-native.md b/docs/affine-native.md index 33e5480b..7e06567e 100644 --- a/docs/affine-native.md +++ b/docs/affine-native.md @@ -144,3 +144,145 @@ before upgrades. Production migration remains a separate, explicit operation. AFFiNE backend source has its own license; review it before production use. This module does not grant production authorization or alter upstream license terms. + +## hectic-lab host configuration + +`nixos/system/hectic-lab/affine.nix` stages the reusable native module alongside +the original deployment. `hectic.affineDeployment.nativeActive` defaults to +`false`: the legacy Docker units and nginx port 3010 remain selected. The old +configuration is preserved in `affine-docker.nix` for staging and rollback. +Set `nativeActive = true` only after the final frozen-state restore and native +verification; this removes the legacy unit declarations and selects nginx port +3011. Source declarations alone are not evidence that production has migrated. + +The host configuration intentionally uses isolated dependencies: + +| Component | Unit | Endpoint/state | +| --- | --- | --- | +| AFFiNE | `affine-native.service` | `127.0.0.1:3011`, `/var/lib/affine-native` | +| Migration | `affine-native-migrate.service` | Same user, environment and state | +| PostgreSQL 16 | `affine-postgresql.service` | Unix socket `/run/affine-postgresql`, port 5433, `/var/lib/affine-postgresql` | +| Redis | `redis-affine.service` | `127.0.0.1:6388` | +| ChatGPT connector | `affine-chatgpt.service` | `127.0.0.1:3012`, separate protected state | + +The database cluster does not listen on TCP and does not replace the host's +shared `postgresql.service`. It uses peer authentication, a non-superuser role +and database named `affine-native`, and pgvector `0.8.7` from the pinned +official release. PostgreSQL pre-creates `vector` and `pgcrypto` as its cluster +administrator. The cluster locale matches the existing Docker database's +`en_US.utf8`; do not silently substitute a different collation. + +Both AFFiNE units are gated by `/var/lib/affine-native/environment`. Create that +file only after staging the correct database/config/storage. It must be +protected outside Git and the Nix store. Its required connection settings are: + +```text +DATABASE_URL=postgresql://affine-native@localhost:5433/affine-native?host=/run/affine-postgresql +AFFINE_INDEXER_ENABLED=false +``` + +The database URL contains no password because the Unix socket uses peer auth. +The environment file may also carry secrets; treat the entire file as private. + +## Docker-to-native migration procedure + +1. Build the source package, exact pgvector version, native service units and + targeted checks before scheduling an outage. Inspect the activation plan; + do not restart the shared PostgreSQL cluster or unrelated Redis instances. +2. Inventory the running AFFiNE revision, database extensions/locale, workspace + and user counts, config/private key, storage file manifest and nginx route. + Never print secret values or document contents. +3. Make an owner-only custom-format PostgreSQL backup and config/storage + snapshot. Verify `pg_restore --list`, archive readability and checksums. + A listed archive is not a tested restore or an offsite backup. +4. Start only the dedicated PostgreSQL and Redis units. Restore a rehearsal + dump into their isolated database, preserving role ownership. Pre-created + extensions avoid giving the application superuser privileges. Use + `pg_restore --exit-on-error --no-owner --no-acl --no-comments + --role=affine-native`; investigate any error instead of ignoring it. +5. Copy the complete Docker config and storage to + `/var/lib/affine-native/.affine/{config,storage}`. Preserve `private.key` + byte-for-byte. Give the native account ownership and private permissions. + Update copied server/listen/port and Redis settings for native paths; + preserve authentication, external URL and all encryption material. +6. Run migration/startup against the rehearsal database and copied storage + only. Never point staging workers at the live Docker database/storage. + Verify `/info` reports `selfhosted` and compatibility `0.27.4`, then test + authenticated workspaces, representative documents and stored attachments. +7. Announce the write freeze. Stop all Docker AFFiNE application/worker writers + without deleting its PostgreSQL volume. Take a fresh final dump and final + config/storage snapshot after the freeze. Restore that final snapshot into + a clean native database; stop staging units before replacing state. +8. Start native migration and application units. Verify entity counts, + checksums, login, documents, attachments and readiness before switching + `hectic.affineDeployment.nativeActive` to `true` and nginx from port 3010 to + 3011. Inspect the activation plan and test nginx configuration first. +9. Confirm the public HTTPS route, WebSockets/live editing and signup policy. + Confirm the cutover removed/disabled the old Docker `affine.service` and + `affine-frontend.service`. Retain their image/config/data and final snapshot; + do not delete old state as part of cutover. +10. Configure the [native ChatGPT connector](./affine-chatgpt.md) through AFFiNE's + administrator API/UI and verify an actual AFFiNE AI request, not only a + direct upstream probe. + +Before native production writes, rollback can return nginx/application to the +frozen Docker state. After native writes begin, that state is stale: rollback +requires a new consistent export and compatible restore, not a proxy flip to +an old database. NixOS generation rollback alone does not restore application +data. + +If SSH, package copying, extension build, rehearsal restore or verification is +blocked, leave the Docker production route intact. Do not create the runtime +environment marker or activate a half-prepared native application. + +## Completed hectic-lab cutover: 2026-10-31 + +Production now explicitly sets `hectic.affineDeployment.nativeActive = true`. +The activated persistent NixOS generation is: + +```text +/nix/store/6vp7qb6id8krb9l5ff1dkdi7nzxifhwd-nixos-system-hectic-lab-26.05.20261006.b253099 +``` + +Final write-frozen backup: + +```text +/var/backups/affine/native-cutover-20261031T231824Z +``` + +The backup directory is `0700`; database/config/storage archives are `0600`. +It includes the final database dump, verified archive listings, config and +storage snapshots, previous generation references, and matching before/after +data fingerprints. Keep it private. It is local recovery material, not an +offsite backup. + +Cutover verification matched all rows/fingerprints in `users`, `workspaces`, +`workspace_members`, `workspace_pages`, `snapshots`, `updates`, and `blobs`: +5 users, 2 workspaces, 5 memberships, 44 pages, 53 snapshots, 0 pending update +rows, and 49 blob records. All 98 storage files (19,341,496 bytes) and the +original `private.key` were preserved. Rehearsal authenticated document bytes +and a 3,049,505-byte attachment matched the Docker source; final HTTPS login, +document reads, attachment retrieval and frontend assets passed. + +The final `switch-to-configuration switch` completed successfully. The Docker +AFFiNE application/PostgreSQL/Redis containers are gone; their original +`/var/lib/affine` state remains retained. The host Docker daemon still serves +unrelated applications and was not removed. + +The staging `test` activation encountered a pre-existing D-Bus reload timeout +(the journal also records it on 2026-10-10); the bus remained active and was +not restarted. The final cutover activation did not reload D-Bus and completed +successfully. Shared `postgresql.service` remained active throughout. + +The native [ChatGPT connector](./affine-chatgpt.md) is enabled through the +workspace's persistent BYOK profile `ChatGPT subscription`. Text and function +probes were verified, and an actual AFFiNE SSE chat returned the expected +response with both explicit and automatic provider selection. Two authenticated +WebSocket connections joined the workspace and read identical document state +without writing documents. + +After restarting both native AFFiNE and the connector, public login, document +and attachment reads, two-client WebSocket reads, and an automatic-routed AI +chat associated with an existing document passed again. Local validation also +passed 61 connector tests, Pyright with its Nix Python environment, and the +runtime, typography, native-module, production and connector Nix checks. diff --git a/docs/affine-typography.md b/docs/affine-typography.md index 8f3a9d51..951a02f5 100644 --- a/docs/affine-typography.md +++ b/docs/affine-typography.md @@ -36,6 +36,20 @@ The backend used by that check still requires explicit unfree evaluation. ## Current hectic-lab rollout +Since 2026-10-31, hectic-lab runs the source-built backend and patched frontend +together through `hectic.services.affine` and `affine-native.service`. Its +dedicated PostgreSQL, Redis and ChatGPT connector are native services as well. +There is no production AFFiNE container or `affine-frontend.service` mount. +See [native deployment and migration](./affine-native.md) for the cutover, +verification and backup record. The frontend patch remains part of the same +pinned AFFiNE source package; a read-only browser check after migration confirmed +the real document's H2 blocks retain the 24px scale. + +## Historical Docker rollout + +The following describes the earlier frontend-only rollout, retained for the +staging/rollback configuration. It is not the current production topology. + `affine-frontend-static` contains regular, copied web assets, including admin and mobile directories and upstream license notices. It does not contain symlinks into store paths that would be unavailable inside a container. diff --git a/nixos/module/hectic/service/affine-chatgpt.nix b/nixos/module/hectic/service/affine-chatgpt.nix new file mode 100644 index 00000000..3e3488b2 --- /dev/null +++ b/nixos/module/hectic/service/affine-chatgpt.nix @@ -0,0 +1,64 @@ +{ ... }: +{ config, lib, pkgs, ... }: let + cfg = config.hectic.services.affine-chatgpt; + stateDirectory = "/var/lib/affine-chatgpt"; +in { + options.hectic.services.affine-chatgpt = { + enable = lib.mkEnableOption "native ChatGPT subscription gateway for AFFiNE"; + package = lib.mkOption { + type = lib.types.package; + default = pkgs.hectic.affine-chatgpt; + description = "Package providing the affine-chatgpt executable."; + }; + port = lib.mkOption { + type = lib.types.port; + default = 3012; + description = "Loopback-only gateway port."; + }; + gatewayKeyFile = lib.mkOption { + type = lib.types.path; + default = "${stateDirectory}/gateway-key"; + description = "Owner-only runtime bearer key readable by affine-chatgpt; never put its contents in Nix."; + }; + }; + + config = lib.mkIf cfg.enable { + users.groups.affine-chatgpt = {}; + users.users.affine-chatgpt = { + isSystemUser = true; + group = "affine-chatgpt"; + home = stateDirectory; + }; + systemd.services.affine-chatgpt = { + description = "Native ChatGPT subscription gateway for AFFiNE"; + wantedBy = [ "multi-user.target" ]; + after = [ "network-online.target" ]; + wants = [ "network-online.target" ]; + unitConfig.ConditionPathExists = "${stateDirectory}/session/credentials.json"; + preStart = '' + install -d -m 0700 ${stateDirectory}/session + ''; + serviceConfig = { + Type = "simple"; + User = "affine-chatgpt"; + Group = "affine-chatgpt"; + StateDirectory = "affine-chatgpt"; + StateDirectoryMode = "0700"; + ExecStart = "${cfg.package}/bin/affine-chatgpt --state-dir ${stateDirectory}/session serve --host 127.0.0.1 --port ${toString cfg.port} --gateway-key-file ${cfg.gatewayKeyFile}"; + Restart = "on-failure"; + RestartSec = "5s"; + UMask = "0077"; + NoNewPrivileges = true; + PrivateTmp = true; + ProtectHome = true; + ProtectSystem = "strict"; + ReadWritePaths = [ stateDirectory ]; + RestrictAddressFamilies = [ "AF_INET" "AF_INET6" "AF_UNIX" ]; + CapabilityBoundingSet = ""; + LimitCORE = 0; + MemoryMax = "256M"; + TasksMax = 64; + }; + }; + }; +} diff --git a/nixos/module/hectic/service/affine.nix b/nixos/module/hectic/service/affine.nix index 3ec6067a..1e3ec08f 100644 --- a/nixos/module/hectic/service/affine.nix +++ b/nixos/module/hectic/service/affine.nix @@ -67,6 +67,8 @@ in { inherit inputs; system = pkgs.stdenv.hostPlatform.system; nodejs = pkgs.nodejs_22; + # Baseline bundle intentionally excludes independently deployed picker patches. + frontendPatches = [ (flake + "/package/affine/gitea-document-typography.patch") ]; }; defaultText = lib.literalExpression "pkgs.callPackage ./package/affine { ...; }"; description = '' @@ -78,6 +80,15 @@ in { ''; }; + frontendPackage = lib.mkOption { + type = lib.types.nullOr lib.types.package; + default = null; + description = '' + Optional source-built AFFiNE web, admin, and mobile static assets to + bind over the native server's bundled frontend. + ''; + }; + environmentFile = lib.mkOption { type = lib.types.path; description = '' @@ -133,10 +144,33 @@ in { }; config = lib.mkIf cfg.enable { - assertions = [{ - assertion = pkgs.stdenv.hostPlatform.system == "x86_64-linux"; - message = "hectic.services.affine currently supports only x86_64-linux."; - }]; + assertions = [ + { + assertion = pkgs.stdenv.hostPlatform.system == "x86_64-linux"; + message = "hectic.services.affine currently supports only x86_64-linux."; + } + { + assertion = cfg.frontendPackage == null || ( + cfg.package ? version && + cfg.frontendPackage ? version && + cfg.frontendPackage.version == cfg.package.version + ); + message = "hectic.services.affine.frontendPackage version must match hectic.services.affine.package version."; + } + { + assertion = cfg.frontendPackage == null || ( + cfg.package ? frontendStatic && + cfg.package.frontendStatic ? revision && + builtins.isString cfg.package.frontendStatic.revision && + cfg.package.frontendStatic.revision != "" && + cfg.frontendPackage ? revision && + builtins.isString cfg.frontendPackage.revision && + cfg.frontendPackage.revision != "" && + cfg.frontendPackage.revision == cfg.package.frontendStatic.revision + ); + message = "hectic.services.affine.frontendPackage revision must be a non-empty string matching package.frontendStatic.revision."; + } + ]; users.groups.affine-native = {}; users.users.affine-native = { @@ -167,12 +201,14 @@ in { wantedBy = [ "multi-user.target" ]; environment = commonEnvironment; preStart = prepareState; - restartTriggers = [ cfg.package initialConfig ]; + restartTriggers = [ cfg.package initialConfig ] ++ lib.optional (cfg.frontendPackage != null) cfg.frontendPackage; serviceConfig = commonServiceConfig // { Type = "simple"; ExecStart = "${cfg.package}/bin/affine-server"; Restart = "on-failure"; RestartSec = "5s"; + BindReadOnlyPaths = lib.optional (cfg.frontendPackage != null) + "${cfg.frontendPackage}:${cfg.package}/share/affine/static"; }; }; }; diff --git a/nixos/system/hectic-lab/affine-chatgpt.nix b/nixos/system/hectic-lab/affine-chatgpt.nix new file mode 100644 index 00000000..1e1ed1e8 --- /dev/null +++ b/nixos/system/hectic-lab/affine-chatgpt.nix @@ -0,0 +1,8 @@ +{ ... }: { + hectic.services.affine-chatgpt.enable = true; + + systemd.services.affine-native = { + wants = [ "affine-chatgpt.service" ]; + after = [ "affine-chatgpt.service" ]; + }; +} diff --git a/nixos/system/hectic-lab/affine-docker.nix b/nixos/system/hectic-lab/affine-docker.nix new file mode 100644 index 00000000..d9a4da14 --- /dev/null +++ b/nixos/system/hectic-lab/affine-docker.nix @@ -0,0 +1,289 @@ +{ + domain, + ... +}: { + pkgs, + lib, + ... +}: let + affineDomain = "affine.${domain}"; + stateDirectory = "/var/lib/affine"; + environmentFile = "${stateDirectory}/.env"; + bootstrapDirectory = "/var/lib/affine-bootstrap"; + bootstrapPasswordFile = "${bootstrapDirectory}/password"; + authFile = "${bootstrapDirectory}/htpasswd"; + + affineImage = "ghcr.io/toeverything/affine:0.27.4@sha256:c312116a134184947d98749c8a8e29f4e3bc97f4f2a51c9a3497f9baea2eec2b"; + postgresImage = "pgvector/pgvector:pg16@sha256:a97d77306ff47cc1d8add4d000cec2207da2e110746318df3137ce53c337ca30"; + redisImage = "redis:7-alpine@sha256:8be847644e195abc4c10c8d9936cfa45332eccc6b714fa7b186ff43f1f4d5579"; + + logging = { + driver = "json-file"; + options = { + max-file = "3"; + max-size = "10m"; + }; + }; + + commonEnvironment = { + AFFINE_INDEXER_ENABLED = "false"; + DATABASE_URL = "postgresql://affine:\${DB_PASSWORD}@postgres:5432/affine"; + REDIS_SERVER_HOST = "redis"; + }; + + composeFile = (pkgs.formats.yaml {}).generate "affine-compose.yaml" { + services = { + affine = { + image = affineImage; + restart = "unless-stopped"; + mem_limit = "2g"; + inherit logging; + ports = [ "127.0.0.1:3010:3010" ]; + volumes = [ + "${stateDirectory}/data/storage:/root/.affine/storage" + "${stateDirectory}/data/config:/root/.affine/config" + ]; + environment = commonEnvironment; + depends_on = { + migration.condition = "service_completed_successfully"; + postgres.condition = "service_healthy"; + redis.condition = "service_healthy"; + }; + }; + + migration = { + image = affineImage; + command = [ + "sh" + "-c" + "node ./scripts/self-host-predeploy.js" + ]; + mem_limit = "1g"; + inherit logging; + volumes = [ + "${stateDirectory}/data/storage:/root/.affine/storage" + "${stateDirectory}/data/config:/root/.affine/config" + ]; + environment = commonEnvironment; + depends_on = { + postgres.condition = "service_healthy"; + redis.condition = "service_healthy"; + }; + }; + + postgres = { + image = postgresImage; + restart = "unless-stopped"; + mem_limit = "512m"; + inherit logging; + environment = { + POSTGRES_DB = "affine"; + POSTGRES_PASSWORD = "\${POSTGRES_PASSWORD}"; + POSTGRES_USER = "affine"; + }; + volumes = [ "${stateDirectory}/data/postgres:/var/lib/postgresql/data" ]; + healthcheck = { + test = [ "CMD-SHELL" "pg_isready -U affine -d affine" ]; + interval = "10s"; + timeout = "5s"; + retries = 5; + start_period = "10s"; + }; + }; + + redis = { + image = redisImage; + restart = "unless-stopped"; + mem_limit = "128m"; + inherit logging; + command = [ + "redis-server" + "--save" + "60" + "1" + "--maxmemory" + "96mb" + "--maxmemory-policy" + "noeviction" + ]; + healthcheck = { + test = [ "CMD" "redis-cli" "ping" ]; + interval = "10s"; + timeout = "5s"; + retries = 5; + }; + }; + }; + }; + + configFile = pkgs.writeText "affine-config.json" (builtins.toJSON { + server = { + externalUrl = "https://${affineDomain}"; + name = "Hectic AFFiNE"; + }; + copilot.enabled = false; + auth = { + allowSignup = false; + allowSignupForOauth = false; + newAccountShareActionDelay = 0; + }; + }); + + compose = "${pkgs.docker-compose}/bin/docker-compose --project-name affine --env-file ${environmentFile} --file ${composeFile}"; + frontendStatic = pkgs.hectic.affine-frontend-static; + frontendOverride = (pkgs.formats.yaml {}).generate "affine-frontend-compose.yaml" { + services.affine.volumes = [ "${frontendStatic}:/app/static:ro" ]; + }; + frontendCompose = "${compose} --file ${frontendOverride}"; +in { + assertions = [ + { + assertion = lib.hasPrefix "ghcr.io/toeverything/affine:${frontendStatic.version}@sha256:" affineImage; + message = "AFFiNE frontend assets and the deployed backend image must use the same release."; + } + { + assertion = frontendStatic.revision == "b4c8548c09da21b2898443559a5b846f0ccf5dd8"; + message = "AFFiNE frontend source revision must match the pinned 0.27.4 backend."; + } + ]; + + systemd.tmpfiles.rules = [ + "d ${stateDirectory} 0750 root root -" + "d ${stateDirectory}/data 0750 root root -" + "d ${stateDirectory}/data/config 0750 root root -" + "d ${stateDirectory}/data/postgres 0750 999 999 -" + "d ${stateDirectory}/data/storage 0750 root root -" + "d ${bootstrapDirectory} 0750 root nginx -" + ]; + + systemd.services.affine = { + description = "AFFiNE Docker Compose stack"; + wantedBy = [ "multi-user.target" ]; + wants = [ "network-online.target" ]; + after = [ + "docker.service" + "network-online.target" + "systemd-tmpfiles-setup.service" + ]; + requires = [ + "docker.service" + "network-online.target" + ]; + restartIfChanged = true; + serviceConfig = { + Type = "oneshot"; + RemainAfterExit = true; + ExecStartPre = pkgs.writeShellScript "affine-prepare" '' + set -eu + umask 077 + + if [ ! -s ${environmentFile} ]; then + environment_tmp="$(${pkgs.coreutils}/bin/mktemp ${stateDirectory}/.env.XXXXXX)" + trap '${pkgs.coreutils}/bin/rm -f "$environment_tmp"' EXIT + password="$(${pkgs.openssl}/bin/openssl rand -hex 32)" + ${pkgs.coreutils}/bin/printf 'DB_PASSWORD=%s\nPOSTGRES_PASSWORD=%s\n' "$password" "$password" > "$environment_tmp" + ${pkgs.coreutils}/bin/chmod 0600 "$environment_tmp" + ${pkgs.coreutils}/bin/chown root:root "$environment_tmp" + ${pkgs.coreutils}/bin/mv "$environment_tmp" ${environmentFile} + trap - EXIT + fi + + if [ ! -e ${stateDirectory}/data/config/config.json ]; then + ${pkgs.coreutils}/bin/install -m 0644 ${configFile} ${stateDirectory}/data/config/config.json + fi + + ${pkgs.coreutils}/bin/chmod 0600 ${environmentFile} + ${pkgs.coreutils}/bin/chown root:root ${environmentFile} + ''; + ExecStart = "${compose} up --detach --wait"; + ExecStop = "${compose} down"; + TimeoutStartSec = "15min"; + TimeoutStopSec = "5min"; + }; + }; + + # Reconcile only the application container; leave the database and migration job alone. + systemd.services.affine-frontend = { + description = "Source-built AFFiNE frontend assets"; + wantedBy = [ "multi-user.target" ]; + requires = [ "affine.service" ]; + after = [ "affine.service" ]; + partOf = [ "affine.service" ]; + reloadIfChanged = true; + restartIfChanged = false; + serviceConfig = { + Type = "oneshot"; + RemainAfterExit = true; + ExecStart = "${frontendCompose} up --detach --no-deps --force-recreate affine"; + ExecReload = "${frontendCompose} up --detach --no-deps --force-recreate affine"; + ExecStop = "${compose} up --detach --no-deps --force-recreate affine"; + TimeoutStartSec = "5min"; + TimeoutStopSec = "5min"; + }; + }; + + systemd.services.affine-bootstrap = { + description = "Prepare AFFiNE pilot basic authentication"; + requiredBy = [ "nginx.service" ]; + before = [ "nginx.service" ]; + after = [ "systemd-tmpfiles-setup.service" ]; + serviceConfig = { + Type = "oneshot"; + RemainAfterExit = true; + }; + script = '' + set -eu + umask 077 + + if [ ! -s ${bootstrapPasswordFile} ]; then + password_tmp="$(${pkgs.coreutils}/bin/mktemp ${bootstrapDirectory}/.password.XXXXXX)" + trap '${pkgs.coreutils}/bin/rm -f "$password_tmp"' EXIT + ${pkgs.openssl}/bin/openssl rand -hex 32 > "$password_tmp" + ${pkgs.coreutils}/bin/chmod 0600 "$password_tmp" + ${pkgs.coreutils}/bin/chown root:root "$password_tmp" + ${pkgs.coreutils}/bin/mv "$password_tmp" ${bootstrapPasswordFile} + trap - EXIT + fi + + if [ ! -s ${authFile} ]; then + auth_tmp="$(${pkgs.coreutils}/bin/mktemp ${bootstrapDirectory}/.htpasswd.XXXXXX)" + trap '${pkgs.coreutils}/bin/rm -f "$auth_tmp"' EXIT + hash="$(${pkgs.openssl}/bin/openssl passwd -6 -stdin < ${bootstrapPasswordFile})" + ${pkgs.coreutils}/bin/printf 'affine:%s\n' "$hash" > "$auth_tmp" + ${pkgs.coreutils}/bin/chmod 0640 "$auth_tmp" + ${pkgs.coreutils}/bin/chown root:nginx "$auth_tmp" + ${pkgs.coreutils}/bin/mv "$auth_tmp" ${authFile} + trap - EXIT + fi + + ${pkgs.coreutils}/bin/chmod 0600 ${bootstrapPasswordFile} + ${pkgs.coreutils}/bin/chown root:root ${bootstrapPasswordFile} + ${pkgs.coreutils}/bin/chmod 0640 ${authFile} + ${pkgs.coreutils}/bin/chown root:nginx ${authFile} + ''; + }; + + services.nginx.virtualHosts.${affineDomain} = { + enableACME = true; + forceSSL = true; + # Create this marker only after configuring the administrator and signup policy. + extraConfig = '' + client_max_body_size 100m; + set $affine_bootstrap_realm "AFFiNE setup"; + if (-f ${bootstrapDirectory}/initialized) { + set $affine_bootstrap_realm off; + } + ''; + + locations."/" = { + proxyPass = "http://127.0.0.1:3010"; + proxyWebsockets = true; + extraConfig = '' + auth_basic $affine_bootstrap_realm; + auth_basic_user_file ${authFile}; + proxy_read_timeout 3600s; + proxy_send_timeout 3600s; + ''; + }; + }; +} diff --git a/nixos/system/hectic-lab/affine.nix b/nixos/system/hectic-lab/affine.nix index d9a4da14..31355229 100644 --- a/nixos/system/hectic-lab/affine.nix +++ b/nixos/system/hectic-lab/affine.nix @@ -1,289 +1,189 @@ { domain, ... -}: { - pkgs, +}: args@{ + config, lib, + pkgs, ... }: let + cfg = config.hectic.affineDeployment; affineDomain = "affine.${domain}"; - stateDirectory = "/var/lib/affine"; - environmentFile = "${stateDirectory}/.env"; - bootstrapDirectory = "/var/lib/affine-bootstrap"; - bootstrapPasswordFile = "${bootstrapDirectory}/password"; - authFile = "${bootstrapDirectory}/htpasswd"; + databaseName = "affine-native"; + environmentFile = "/var/lib/affine-native/environment"; + postgresqlDataDirectory = "/var/lib/affine-postgresql"; + postgresqlSocketDirectory = "/run/affine-postgresql"; - affineImage = "ghcr.io/toeverything/affine:0.27.4@sha256:c312116a134184947d98749c8a8e29f4e3bc97f4f2a51c9a3497f9baea2eec2b"; - postgresImage = "pgvector/pgvector:pg16@sha256:a97d77306ff47cc1d8add4d000cec2207da2e110746318df3137ce53c337ca30"; - redisImage = "redis:7-alpine@sha256:8be847644e195abc4c10c8d9936cfa45332eccc6b714fa7b186ff43f1f4d5579"; - - logging = { - driver = "json-file"; - options = { - max-file = "3"; - max-size = "10m"; - }; - }; - - commonEnvironment = { - AFFINE_INDEXER_ENABLED = "false"; - DATABASE_URL = "postgresql://affine:\${DB_PASSWORD}@postgres:5432/affine"; - REDIS_SERVER_HOST = "redis"; - }; - - composeFile = (pkgs.formats.yaml {}).generate "affine-compose.yaml" { - services = { - affine = { - image = affineImage; - restart = "unless-stopped"; - mem_limit = "2g"; - inherit logging; - ports = [ "127.0.0.1:3010:3010" ]; - volumes = [ - "${stateDirectory}/data/storage:/root/.affine/storage" - "${stateDirectory}/data/config:/root/.affine/config" - ]; - environment = commonEnvironment; - depends_on = { - migration.condition = "service_completed_successfully"; - postgres.condition = "service_healthy"; - redis.condition = "service_healthy"; - }; - }; - - migration = { - image = affineImage; - command = [ - "sh" - "-c" - "node ./scripts/self-host-predeploy.js" - ]; - mem_limit = "1g"; - inherit logging; - volumes = [ - "${stateDirectory}/data/storage:/root/.affine/storage" - "${stateDirectory}/data/config:/root/.affine/config" - ]; - environment = commonEnvironment; - depends_on = { - postgres.condition = "service_healthy"; - redis.condition = "service_healthy"; - }; - }; - - postgres = { - image = postgresImage; - restart = "unless-stopped"; - mem_limit = "512m"; - inherit logging; - environment = { - POSTGRES_DB = "affine"; - POSTGRES_PASSWORD = "\${POSTGRES_PASSWORD}"; - POSTGRES_USER = "affine"; - }; - volumes = [ "${stateDirectory}/data/postgres:/var/lib/postgresql/data" ]; - healthcheck = { - test = [ "CMD-SHELL" "pg_isready -U affine -d affine" ]; - interval = "10s"; - timeout = "5s"; - retries = 5; - start_period = "10s"; - }; - }; - - redis = { - image = redisImage; - restart = "unless-stopped"; - mem_limit = "128m"; - inherit logging; - command = [ - "redis-server" - "--save" - "60" - "1" - "--maxmemory" - "96mb" - "--maxmemory-policy" - "noeviction" - ]; - healthcheck = { - test = [ "CMD" "redis-cli" "ping" ]; - interval = "10s"; - timeout = "5s"; - retries = 5; - }; - }; - }; - }; - - configFile = pkgs.writeText "affine-config.json" (builtins.toJSON { - server = { - externalUrl = "https://${affineDomain}"; - name = "Hectic AFFiNE"; - }; - copilot.enabled = false; - auth = { - allowSignup = false; - allowSignupForOauth = false; - newAccountShareActionDelay = 0; + affinePgvector = pkgs.postgresql_16.pkgs.pgvector.overrideAttrs (_: { + version = "0.8.7"; + # v0.8.7 resolves to release commit f37c13f68b57d2c3472b2214fbcff699d6d34876. + src = pkgs.fetchFromGitHub { + owner = "pgvector"; + repo = "pgvector"; + rev = "v0.8.7"; + hash = "sha256-YYXz8zqiuqYWpJwImAhMry/QTLHKOP5MzuY0Of+aflc="; }; }); - - compose = "${pkgs.docker-compose}/bin/docker-compose --project-name affine --env-file ${environmentFile} --file ${composeFile}"; - frontendStatic = pkgs.hectic.affine-frontend-static; - frontendOverride = (pkgs.formats.yaml {}).generate "affine-frontend-compose.yaml" { - services.affine.volumes = [ "${frontendStatic}:/app/static:ro" ]; - }; - frontendCompose = "${compose} --file ${frontendOverride}"; + affinePostgresql = pkgs.postgresql_16.withPackages (_: [ affinePgvector ]); + dockerConfig = (import ./affine-docker.nix { inherit domain; }) args; in { - assertions = [ + options.hectic.affineDeployment.nativeActive = lib.mkOption { + type = lib.types.bool; + default = false; + description = "Route production traffic to native AFFiNE and disable legacy Docker units."; + }; + + config = lib.mkMerge [ { - assertion = lib.hasPrefix "ghcr.io/toeverything/affine:${frontendStatic.version}@sha256:" affineImage; - message = "AFFiNE frontend assets and the deployed backend image must use the same release."; - } - { - assertion = frontendStatic.revision == "b4c8548c09da21b2898443559a5b846f0ccf5dd8"; - message = "AFFiNE frontend source revision must match the pinned 0.27.4 backend."; + hectic.services.affine = { + enable = true; + frontendPackage = pkgs.hectic.affine-frontend-static; + externalUrl = "https://${affineDomain}"; + serverName = "Hectic AFFiNE"; + address = "127.0.0.1"; + port = 3011; + redisHost = "127.0.0.1"; + redisPort = 6388; + inherit environmentFile; + settings = { + copilot.enabled = false; + auth = { + allowSignup = false; + allowSignupForOauth = false; + newAccountShareActionDelay = 0; + }; + }; + }; + + users.groups.affine-postgres = {}; + users.users.affine-postgres = { + isSystemUser = true; + group = "affine-postgres"; + home = postgresqlDataDirectory; + }; + + systemd.services.affine-postgresql = { + description = "Isolated PostgreSQL cluster for AFFiNE"; + wantedBy = [ "multi-user.target" ]; + after = [ "local-fs.target" ]; + unitConfig.RequiresMountsFor = postgresqlDataDirectory; + path = [ affinePostgresql ]; + environment.POSTGRESQL_VERSION = affinePostgresql.version; + restartTriggers = [ affinePgvector ]; + preStart = '' + if [ ! -s ${postgresqlDataDirectory}/PG_VERSION ]; then + initdb \ + --pgdata=${postgresqlDataDirectory} \ + --username=affine-postgres \ + --encoding=UTF8 \ + --locale=en_US.utf8 \ + --auth-local=peer \ + --auth-host=reject + fi + + cat > ${postgresqlDataDirectory}/pg_hba.conf <<'EOF' + local all all peer + host all all 0.0.0.0/0 reject + host all all ::0/0 reject + EOF + ''; + postStart = '' + ready=0 + for attempt in $(seq 1 60); do + if pg_isready --host=${postgresqlSocketDirectory} --port=5433 --username=affine-postgres; then + ready=1 + break + fi + sleep 1 + done + if [ "$ready" -ne 1 ]; then + echo "AFFiNE PostgreSQL did not become ready" >&2 + exit 1 + fi + + psql --host=${postgresqlSocketDirectory} --port=5433 --dbname=postgres \ + --set=ON_ERROR_STOP=1 <<'SQL' + DO $role$ + BEGIN + IF NOT EXISTS (SELECT FROM pg_catalog.pg_roles WHERE rolname = 'affine-native') THEN + CREATE ROLE "affine-native" LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE; + END IF; + END + $role$; + ALTER ROLE "affine-native" LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE; + SELECT 'CREATE DATABASE "affine-native" OWNER "affine-native"' + WHERE NOT EXISTS (SELECT FROM pg_database WHERE datname = 'affine-native')\gexec + ALTER DATABASE "affine-native" OWNER TO "affine-native"; + SQL + + psql --host=${postgresqlSocketDirectory} --port=5433 --dbname=${databaseName} \ + --set=ON_ERROR_STOP=1 <<'SQL' + CREATE EXTENSION IF NOT EXISTS vector; + CREATE EXTENSION IF NOT EXISTS pgcrypto; + SQL + ''; + serviceConfig = { + Type = "notify"; + User = "affine-postgres"; + Group = "affine-postgres"; + StateDirectory = "affine-postgresql"; + StateDirectoryMode = "0700"; + RuntimeDirectory = "affine-postgresql"; + RuntimeDirectoryMode = "0755"; + ExecStart = "${affinePostgresql}/bin/postgres -D ${postgresqlDataDirectory} -k ${postgresqlSocketDirectory} -p 5433 -c \"listen_addresses=\""; + ExecReload = "${pkgs.coreutils}/bin/kill -HUP $MAINPID"; + KillSignal = "SIGINT"; + TimeoutStopSec = "120s"; + MemoryMax = "512M"; + Restart = "on-failure"; + RestartSec = "5s"; + }; + }; + + services.redis.servers.affine = { + enable = true; + bind = "127.0.0.1"; + port = 6388; + settings = { + maxmemory = "96mb"; + maxmemory-policy = "noeviction"; + }; + }; + + systemd.services.redis-affine.serviceConfig.MemoryMax = "128M"; + + # Live data restore is intentionally external. Main stages config, private.key, + # storage, and the database before creating this runtime environment file. + systemd.services.affine-native-migrate = { + after = [ "affine-postgresql.service" "redis-affine.service" ]; + requires = [ "affine-postgresql.service" "redis-affine.service" ]; + unitConfig.ConditionPathExists = environmentFile; + }; + + systemd.services.affine-native = { + unitConfig.ConditionPathExists = environmentFile; + serviceConfig.MemoryMax = "2G"; + }; } + + (lib.mkIf (!cfg.nativeActive) dockerConfig) + + (lib.mkIf cfg.nativeActive { + services.nginx.virtualHosts.${affineDomain} = { + enableACME = true; + forceSSL = true; + extraConfig = '' + client_max_body_size 100m; + ''; + locations."/" = { + proxyPass = "http://127.0.0.1:3011"; + proxyWebsockets = true; + extraConfig = '' + proxy_read_timeout 3600s; + proxy_send_timeout 3600s; + ''; + }; + }; + }) ]; - - systemd.tmpfiles.rules = [ - "d ${stateDirectory} 0750 root root -" - "d ${stateDirectory}/data 0750 root root -" - "d ${stateDirectory}/data/config 0750 root root -" - "d ${stateDirectory}/data/postgres 0750 999 999 -" - "d ${stateDirectory}/data/storage 0750 root root -" - "d ${bootstrapDirectory} 0750 root nginx -" - ]; - - systemd.services.affine = { - description = "AFFiNE Docker Compose stack"; - wantedBy = [ "multi-user.target" ]; - wants = [ "network-online.target" ]; - after = [ - "docker.service" - "network-online.target" - "systemd-tmpfiles-setup.service" - ]; - requires = [ - "docker.service" - "network-online.target" - ]; - restartIfChanged = true; - serviceConfig = { - Type = "oneshot"; - RemainAfterExit = true; - ExecStartPre = pkgs.writeShellScript "affine-prepare" '' - set -eu - umask 077 - - if [ ! -s ${environmentFile} ]; then - environment_tmp="$(${pkgs.coreutils}/bin/mktemp ${stateDirectory}/.env.XXXXXX)" - trap '${pkgs.coreutils}/bin/rm -f "$environment_tmp"' EXIT - password="$(${pkgs.openssl}/bin/openssl rand -hex 32)" - ${pkgs.coreutils}/bin/printf 'DB_PASSWORD=%s\nPOSTGRES_PASSWORD=%s\n' "$password" "$password" > "$environment_tmp" - ${pkgs.coreutils}/bin/chmod 0600 "$environment_tmp" - ${pkgs.coreutils}/bin/chown root:root "$environment_tmp" - ${pkgs.coreutils}/bin/mv "$environment_tmp" ${environmentFile} - trap - EXIT - fi - - if [ ! -e ${stateDirectory}/data/config/config.json ]; then - ${pkgs.coreutils}/bin/install -m 0644 ${configFile} ${stateDirectory}/data/config/config.json - fi - - ${pkgs.coreutils}/bin/chmod 0600 ${environmentFile} - ${pkgs.coreutils}/bin/chown root:root ${environmentFile} - ''; - ExecStart = "${compose} up --detach --wait"; - ExecStop = "${compose} down"; - TimeoutStartSec = "15min"; - TimeoutStopSec = "5min"; - }; - }; - - # Reconcile only the application container; leave the database and migration job alone. - systemd.services.affine-frontend = { - description = "Source-built AFFiNE frontend assets"; - wantedBy = [ "multi-user.target" ]; - requires = [ "affine.service" ]; - after = [ "affine.service" ]; - partOf = [ "affine.service" ]; - reloadIfChanged = true; - restartIfChanged = false; - serviceConfig = { - Type = "oneshot"; - RemainAfterExit = true; - ExecStart = "${frontendCompose} up --detach --no-deps --force-recreate affine"; - ExecReload = "${frontendCompose} up --detach --no-deps --force-recreate affine"; - ExecStop = "${compose} up --detach --no-deps --force-recreate affine"; - TimeoutStartSec = "5min"; - TimeoutStopSec = "5min"; - }; - }; - - systemd.services.affine-bootstrap = { - description = "Prepare AFFiNE pilot basic authentication"; - requiredBy = [ "nginx.service" ]; - before = [ "nginx.service" ]; - after = [ "systemd-tmpfiles-setup.service" ]; - serviceConfig = { - Type = "oneshot"; - RemainAfterExit = true; - }; - script = '' - set -eu - umask 077 - - if [ ! -s ${bootstrapPasswordFile} ]; then - password_tmp="$(${pkgs.coreutils}/bin/mktemp ${bootstrapDirectory}/.password.XXXXXX)" - trap '${pkgs.coreutils}/bin/rm -f "$password_tmp"' EXIT - ${pkgs.openssl}/bin/openssl rand -hex 32 > "$password_tmp" - ${pkgs.coreutils}/bin/chmod 0600 "$password_tmp" - ${pkgs.coreutils}/bin/chown root:root "$password_tmp" - ${pkgs.coreutils}/bin/mv "$password_tmp" ${bootstrapPasswordFile} - trap - EXIT - fi - - if [ ! -s ${authFile} ]; then - auth_tmp="$(${pkgs.coreutils}/bin/mktemp ${bootstrapDirectory}/.htpasswd.XXXXXX)" - trap '${pkgs.coreutils}/bin/rm -f "$auth_tmp"' EXIT - hash="$(${pkgs.openssl}/bin/openssl passwd -6 -stdin < ${bootstrapPasswordFile})" - ${pkgs.coreutils}/bin/printf 'affine:%s\n' "$hash" > "$auth_tmp" - ${pkgs.coreutils}/bin/chmod 0640 "$auth_tmp" - ${pkgs.coreutils}/bin/chown root:nginx "$auth_tmp" - ${pkgs.coreutils}/bin/mv "$auth_tmp" ${authFile} - trap - EXIT - fi - - ${pkgs.coreutils}/bin/chmod 0600 ${bootstrapPasswordFile} - ${pkgs.coreutils}/bin/chown root:root ${bootstrapPasswordFile} - ${pkgs.coreutils}/bin/chmod 0640 ${authFile} - ${pkgs.coreutils}/bin/chown root:nginx ${authFile} - ''; - }; - - services.nginx.virtualHosts.${affineDomain} = { - enableACME = true; - forceSSL = true; - # Create this marker only after configuring the administrator and signup policy. - extraConfig = '' - client_max_body_size 100m; - set $affine_bootstrap_realm "AFFiNE setup"; - if (-f ${bootstrapDirectory}/initialized) { - set $affine_bootstrap_realm off; - } - ''; - - locations."/" = { - proxyPass = "http://127.0.0.1:3010"; - proxyWebsockets = true; - extraConfig = '' - auth_basic $affine_bootstrap_realm; - auth_basic_user_file ${authFile}; - proxy_read_timeout 3600s; - proxy_send_timeout 3600s; - ''; - }; - }; } diff --git a/nixos/system/hectic-lab/default.nix b/nixos/system/hectic-lab/default.nix index fbef820a..2da520c1 100644 --- a/nixos/system/hectic-lab/default.nix +++ b/nixos/system/hectic-lab/default.nix @@ -27,7 +27,14 @@ in self.lib.nixpkgs-lib.nixosSystem { }) ]; config.allowUnfreePredicate = pkg: - builtins.elem (inputs.nixpkgs.lib.getName pkg) [ "steamcmd" "steam-unwrapped" "p4d" "p4" ]; + builtins.elem (inputs.nixpkgs.lib.getName pkg) [ + "affine" + "affine-server-native" + "steamcmd" + "steam-unwrapped" + "p4d" + "p4" + ]; }; modules = [ { networking.hostName = name; } diff --git a/nixos/system/hectic-lab/hectic-lab.nix b/nixos/system/hectic-lab/hectic-lab.nix index 0f5106e6..ddb3bd4a 100644 --- a/nixos/system/hectic-lab/hectic-lab.nix +++ b/nixos/system/hectic-lab/hectic-lab.nix @@ -63,6 +63,7 @@ in { inputs.iana-angl.nixosModules.iana-angl (import ./affine.nix { inherit domain; }) + ./affine-chatgpt.nix (import ./attic.nix { inherit flake self inputs domain; }) (import ./containers.nix { inherit flake self inputs; }) ./experimental-sshd.nix @@ -93,6 +94,7 @@ in { security.acme.defaults.email = lib.mkForce "security@${domain}"; hectic = { + affineDeployment.nativeActive = true; archetype.dev.enable = true; hardware.hetzner-cloud = { enable = true; diff --git a/package/affine-chatgpt/.gitignore b/package/affine-chatgpt/.gitignore new file mode 100644 index 00000000..0ce2e531 --- /dev/null +++ b/package/affine-chatgpt/.gitignore @@ -0,0 +1,3 @@ +.venv +__pycache__/ +*.pyc diff --git a/package/affine-chatgpt/README.md b/package/affine-chatgpt/README.md new file mode 100644 index 00000000..9e6b7003 --- /dev/null +++ b/package/affine-chatgpt/README.md @@ -0,0 +1,41 @@ +# affine-chatgpt + +Local ChatGPT OAuth enrollment companion and minimal OpenAI Responses gateway +for AFFiNE. It supports sign-in, safe status inspection, visible-model listing, +text Responses, and client-executed function/custom tools. Gateway runs in +foreground and has no login or administration HTTP endpoints. + +```sh +affine-chatgpt login +affine-chatgpt status +affine-chatgpt models +affine-chatgpt serve --gateway-key-file /run/keys/affine-chatgpt +``` + +`login` binds only `127.0.0.1:1455` (override with `--port`) before printing a +public authorization URL. Open that URL in a local browser and personally +approve access. State defaults to `~/.local/state/affine-chatgpt`; override it +with `--state-dir`. Files are owner-only and must never be copied into the Nix +store, source control, logs, or shared AFFiNE configuration. + +`serve` binds `127.0.0.1:3012` by default (`--host` and `--port` override it). +Gateway key file is required, must contain at least 32 characters, and must be +an owner-only regular file. Every `/v1/models` and `/v1/responses` request +requires `Authorization: Bearer `. `/healthz` returns only generic +readiness. Configure AFFiNE for Responses dialect and choose one of models +returned by `/v1/models`; gateway does not select or invent default model. + +Incoming Responses requests are reduced to preview-compatible fields and sent +upstream with `store:false`, `stream:true`, and complete array input history. +Streaming callers receive official SSE events unchanged. Non-stream callers +receive actual terminal completed Response JSON, including text, function +calls, and usage. AFFiNE executes tools and returns `function_call_output` in +next request; gateway never executes tools. + +OAuth plan usage remains preview functionality. Supported inputs are text +messages, function-call history/output, and necessary reasoning history. +Function/custom tools are grouped in Responses namespaces. Unsupported: +images/media, files, audio, image generation, file search, Code Interpreter, +hosted MCP/connectors, conversations, background mode, persistent response +continuation, and Chat Completions conversion. No billing fallback exists. +A successful login/model listing does not prove inference entitlement. diff --git a/package/affine-chatgpt/default.nix b/package/affine-chatgpt/default.nix new file mode 100644 index 00000000..5cf2ab51 --- /dev/null +++ b/package/affine-chatgpt/default.nix @@ -0,0 +1,51 @@ +{ + lib, + makeWrapper, + stdenvNoCC, + python3, +}: + +let + pythonEnv = python3.withPackages (ps: [ + ps.requests + ps.pyjwt + ps.cryptography + ]); +in +stdenvNoCC.mkDerivation { + pname = "affine-chatgpt"; + version = "0.1.0"; + src = lib.cleanSourceWith { + src = ./.; + filter = path: type: + !(builtins.elem (builtins.baseNameOf path) [ "__pycache__" ".venv" ]) && !(lib.hasSuffix ".pyc" path); + }; + + nativeBuildInputs = [ makeWrapper ]; + passthru = { inherit pythonEnv; }; + + doCheck = true; + checkPhase = '' + runHook preCheck + PYTHONPATH="$PWD/src" ${pythonEnv}/bin/python3 -m unittest discover -s test -v + runHook postCheck + ''; + + installPhase = '' + runHook preInstall + install -Dm444 src/affine_chatgpt.py "$out/share/affine-chatgpt/affine_chatgpt.py" + install -Dm444 src/affine_gateway.py "$out/share/affine-chatgpt/affine_gateway.py" + makeWrapper ${pythonEnv}/bin/python3 "$out/bin/affine-chatgpt" \ + --add-flags "$out/share/affine-chatgpt/affine_chatgpt.py" \ + --run 'umask 077' + runHook postInstall + ''; + + meta = { + description = "Local ChatGPT OAuth enrollment companion for AFFiNE"; + homepage = "https://developers.openai.com/siwc/token-sharing-open-source/"; + license = lib.licenses.mit; + mainProgram = "affine-chatgpt"; + platforms = lib.platforms.unix; + }; +} diff --git a/package/affine-chatgpt/pyrightconfig.json b/package/affine-chatgpt/pyrightconfig.json new file mode 100644 index 00000000..c8717450 --- /dev/null +++ b/package/affine-chatgpt/pyrightconfig.json @@ -0,0 +1,5 @@ +{ + "venvPath": ".", + "venv": ".venv", + "extraPaths": ["src"] +} diff --git a/package/affine-chatgpt/src/affine_chatgpt.py b/package/affine-chatgpt/src/affine_chatgpt.py new file mode 100644 index 00000000..eb70d47a --- /dev/null +++ b/package/affine-chatgpt/src/affine_chatgpt.py @@ -0,0 +1,617 @@ +#!/usr/bin/env python3 +"""Secure local ChatGPT OAuth enrollment and model discovery.""" + +import argparse +import base64 +import contextlib +import fcntl +import hashlib +import hmac +import ipaddress +import json +import os +import re +import secrets +import stat +import sys +import tempfile +import threading +import time +import uuid +from datetime import datetime, timezone +from http.server import BaseHTTPRequestHandler, HTTPServer +from pathlib import Path +from socketserver import ThreadingMixIn +from urllib.parse import parse_qs, urlencode, urlsplit + +import jwt +import requests + + +# The installed wrapper executes this file directly; keep lazy gateway imports +# on the same module instance so expected AppError exceptions remain catchable. +sys.modules.setdefault("affine_chatgpt", sys.modules[__name__]) + + +ISSUER = "https://auth.openai.com" +DISCOVERY_URL = ISSUER + "/.well-known/openid-configuration" +AUTHORIZE_URL = ISSUER + "/api/accounts/authorize" +TOKEN_URL = ISSUER + "/api/accounts/oauth/token" +JWKS_URL = ISSUER + "/.well-known/jwks.json" +RESOURCE = "https://api.openai.com/v1" +MODELS_URL = RESOURCE + "/models" +RESPONSES_URL = RESOURCE + "/responses" +DYNAMIC_CLIENT = "dynamic_agent_client" +AGENT_NAME = "Hearth AFFiNE ChatGPT connector" +SCOPES = "openid profile email offline_access resource.invoke chatgpt.tokens.use.direct" +REQUIRED_SCOPE = "chatgpt.tokens.use.direct" +HTTP_TIMEOUT = 15 +SOCKET_TIMEOUT = 5 +MAX_CALLBACK = 8192 +CLIENT_RE = re.compile(r"^[A-Za-z0-9._~-]{1,256}$") + + +class AppError(Exception): + """Expected failure with a non-sensitive stable error code.""" + + +def new_session(): + session = requests.Session() + session.trust_env = False + return session + + +def utc_now(): + return datetime.now(timezone.utc).isoformat() + + +def default_state_dir(): + return Path.home() / ".local" / "state" / "affine-chatgpt" + + +def secure_dir(path): + path = Path(path).expanduser() + try: + info = path.lstat() + except FileNotFoundError: + path.mkdir(parents=True, mode=0o700) + info = path.lstat() + if stat.S_ISLNK(info.st_mode) or not stat.S_ISDIR(info.st_mode): + raise AppError("unsafe_state_dir") + os.chmod(path, 0o700) + return path + + +def _regular_nofollow(path): + try: + info = Path(path).lstat() + except FileNotFoundError: + return False + if stat.S_ISLNK(info.st_mode) or not stat.S_ISREG(info.st_mode): + raise AppError("unsafe_state_file") + if info.st_mode & 0o077: + raise AppError("unsafe_state_file") + return True + + +def read_json(path): + if not _regular_nofollow(path): + return None + try: + with open(path, "r", encoding="utf-8") as stream: + return json.load(stream) + except (ValueError, TypeError): + raise AppError("invalid_state") from None + + +def atomic_json(path, value): + path = Path(path) + secure_dir(path.parent) + _regular_nofollow(path) + descriptor, temporary = tempfile.mkstemp(prefix=".tmp-", dir=path.parent) + try: + os.fchmod(descriptor, 0o600) + with os.fdopen(descriptor, "w", encoding="utf-8") as stream: + descriptor = -1 + json.dump(value, stream, sort_keys=True, separators=(",", ":")) + stream.write("\n") + stream.flush() + os.fsync(stream.fileno()) + os.replace(temporary, path) + os.chmod(path, 0o600) + directory_descriptor = os.open(path.parent, os.O_RDONLY | os.O_DIRECTORY) + try: + os.fsync(directory_descriptor) + finally: + os.close(directory_descriptor) + finally: + if descriptor >= 0: + os.close(descriptor) + with contextlib.suppress(FileNotFoundError): + os.unlink(temporary) + + +def host_id(state_dir, supplied=None): + target = secure_dir(state_dir) / "host.json" + saved = read_json(target) + if saved is not None: + if not isinstance(saved, dict): + raise AppError("invalid_state") + saved_value = saved.get("host_id") + if not isinstance(saved_value, str): + raise AppError("invalid_state") + value = saved_value + elif supplied: + source = Path(supplied).expanduser() + if not _regular_nofollow(source) or source.stat().st_mode & 0o077: + raise AppError("unsafe_host_id_file") + try: + value = source.read_text(encoding="ascii").strip() + except OSError: + raise AppError("invalid_host_id") from None + else: + value = "urn:uuid:" + str(uuid.uuid4()) + try: + if not value.startswith("urn:uuid:"): + raise ValueError + parsed = uuid.UUID(value.removeprefix("urn:uuid:")) + if parsed.version != 4: + raise ValueError + except (ValueError, AttributeError): + raise AppError("invalid_host_id") from None + value = "urn:uuid:" + str(parsed) + if saved is None: + atomic_json(target, {"host_id": value}) + return value + + +def pkce_challenge(verifier): + digest = hashlib.sha256(verifier.encode("ascii")).digest() + return base64.urlsafe_b64encode(digest).rstrip(b"=").decode("ascii") + + +def _safe_response(response, expected=200): + if response.is_redirect or response.status_code != expected: + raise AppError("oauth_http_error") + try: + value = response.json() + except (requests.RequestException, ValueError): + raise AppError("oauth_response_invalid") from None + if not isinstance(value, dict): + raise AppError("oauth_response_invalid") + return value + + +def _request(session, method, url, **kwargs): + if url not in {DISCOVERY_URL, TOKEN_URL, JWKS_URL, MODELS_URL, RESPONSES_URL}: + raise AppError("endpoint_not_allowed") + kwargs.update(timeout=HTTP_TIMEOUT, allow_redirects=False) + try: + return session.request(method, url, **kwargs) + except requests.RequestException: + raise AppError("network_error") from None + + +def check_discovery(session): + data = _safe_response(_request(session, "GET", DISCOVERY_URL)) + if ( + data.get("issuer") != ISSUER + or data.get("authorization_endpoint") != AUTHORIZE_URL + or data.get("token_endpoint") != TOKEN_URL + or data.get("jwks_uri") != JWKS_URL + ): + raise AppError("discovery_mismatch") + + +def fetch_jwks(session): + data = _safe_response(_request(session, "GET", JWKS_URL)) + if not isinstance(data.get("keys"), list): + raise AppError("jwks_invalid") + return data + + +def validate_id_token(encoded, client_id, nonce, session, now=None): + try: + header = jwt.get_unverified_header(encoded) + except jwt.PyJWTError: + raise AppError("id_token_invalid") from None + kid = header.get("kid") + if header.get("alg") != "RS256" or not isinstance(kid, str) or not kid: + raise AppError("id_token_invalid") + try: + key_set = jwt.PyJWKSet.from_dict(fetch_jwks(session)) + key = next(item.key for item in key_set.keys if item.key_id == kid) + claims = jwt.decode( + encoded, + key, + algorithms=["RS256"], + audience=client_id, + issuer=ISSUER, + options={"require": ["iss", "aud", "exp", "iat", "nonce", "sub"]}, + leeway=0, + ) + except (jwt.PyJWTError, StopIteration, ValueError, TypeError): + raise AppError("id_token_invalid") from None + if now is not None and claims.get("exp", 0) <= now: + raise AppError("id_token_invalid") + if not hmac.compare_digest(str(claims["nonce"]), nonce): + raise AppError("id_token_invalid") + if not isinstance(claims["sub"], str) or not claims["sub"]: + raise AppError("id_token_invalid") + return claims + + +def validate_token_response(data): + required = ("access_token", "refresh_token", "id_token", "scope") + if any(not isinstance(data.get(field), str) or not data[field] for field in required): + raise AppError("token_response_invalid") + if data.get("token_type") != "Bearer" or isinstance(data.get("expires_in"), bool): + raise AppError("token_response_invalid") + if not isinstance(data.get("expires_in"), int) or data["expires_in"] <= 0: + raise AppError("token_response_invalid") + scopes = sorted(set(data["scope"].split())) + if REQUIRED_SCOPE not in scopes: + raise AppError("scope_missing") + return scopes + + +class CallbackAttempt: + def __init__(self, state, client_id, deadline): + self.state = state + self.client_id = client_id + self.deadline = deadline + self.result = None + self.consumed = False + self.lock = threading.Lock() + + def process(self, raw_query, host, expected_host, now=None): + now = time.monotonic() if now is None else now + if len(raw_query) > MAX_CALLBACK or host != expected_host or now > self.deadline: + raise AppError("callback_invalid") + try: + values = parse_qs(raw_query, keep_blank_values=True, strict_parsing=True) + except ValueError: + raise AppError("callback_invalid") from None + allowed = {"state", "code", "scope", "client_id", "error", "error_description"} + if not values or set(values) - allowed or any(len(items) != 1 for items in values.values()): + raise AppError("callback_invalid") + if any(len(items[0]) > 4096 for items in values.values()): + raise AppError("callback_invalid") + returned_state = values.get("state", [""])[0] + if not hmac.compare_digest(returned_state, self.state): + raise AppError("state_mismatch") + with self.lock: + if self.consumed: + raise AppError("callback_replayed") + if "error" in values: + if "code" in values or not values["error"][0]: + raise AppError("callback_invalid") + self.consumed = True + self.result = {"denied": True} + return self.result + code = values.get("code", [""])[0] + if not code: + raise AppError("callback_invalid") + supplied = values.get("client_id", [None])[0] + if self.client_id == DYNAMIC_CLIENT: + if not supplied or supplied == DYNAMIC_CLIENT or not CLIENT_RE.fullmatch(supplied): + raise AppError("client_id_invalid") + issued = supplied + else: + if supplied is not None and supplied != self.client_id: + raise AppError("client_id_mismatch") + issued = self.client_id + self.consumed = True + self.result = {"denied": False, "code": code, "client_id": issued} + return self.result + + +class LoopbackHTTPServer(ThreadingMixIn, HTTPServer): + daemon_threads = True + block_on_close = False + + def handle_error(self, request, client_address): + return + + def get_request(self): + request, address = super().get_request() + request.settimeout(SOCKET_TIMEOUT) + return request, address + + +def callback_handler(attempt, expected_host): + class Handler(BaseHTTPRequestHandler): + def log_message(self, format, *args): + return + + def _reply(self, status, text): + body = (text + "\n").encode("utf-8") + try: + self.send_response(status) + self.send_header("Content-Type", "text/plain; charset=utf-8") + self.send_header("Referrer-Policy", "no-referrer") + self.send_header("Cache-Control", "no-store") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + except OSError: + return + + def do_GET(self): + split = urlsplit(self.path) + if split.path != "/auth/callback" or split.fragment or len(self.path) > MAX_CALLBACK: + self._reply(404, "Not found") + return + try: + result = attempt.process(split.query, self.headers.get("Host", ""), expected_host) + except AppError: + self._reply(400, "Invalid callback. Return to the terminal and retry if needed.") + return + if result["denied"]: + self._reply(200, "Authorization declined. You may close this page.") + else: + self._reply(200, "Authorization received. You may close this page.") + + return Handler + + +def credentials_path(state_dir): + return secure_dir(state_dir) / "credentials.json" + + +def credentials_valid(value): + strings = ( + "issuer", + "subject", + "client_id", + "host_id", + "access_token", + "refresh_token", + "id_token", + "token_type", + "saved_at", + ) + return bool( + isinstance(value, dict) + and all(isinstance(value.get(field), str) and value[field] for field in strings) + and value["issuer"] == ISSUER + and value["token_type"] == "Bearer" + and isinstance(value.get("scopes"), list) + and REQUIRED_SCOPE in value["scopes"] + and not isinstance(value.get("expires_at"), bool) + and isinstance(value.get("expires_at"), (int, float)) + ) + + +def read_credentials(directory): + value = read_json(credentials_path(directory)) + if value is not None and not credentials_valid(value): + raise AppError("invalid_state") + return value + + +@contextlib.contextmanager +def credential_lock(state_dir): + directory = secure_dir(state_dir) + lock_path = directory / "credentials.lock" + _regular_nofollow(lock_path) + descriptor = os.open(lock_path, os.O_CREAT | os.O_RDWR | os.O_NOFOLLOW, 0o600) + try: + os.fchmod(descriptor, 0o600) + fcntl.flock(descriptor, fcntl.LOCK_EX) + yield directory + finally: + os.close(descriptor) + + +def exchange_code(session, code, verifier, redirect_uri, client_id): + response = _request( + session, + "POST", + TOKEN_URL, + data={ + "grant_type": "authorization_code", + "client_id": client_id, + "code": code, + "code_verifier": verifier, + "redirect_uri": redirect_uri, + "resource": RESOURCE, + }, + ) + return _safe_response(response) + + +def login(args, session=None): + session = session or new_session() + with credential_lock(args.state_dir) as directory: + host = host_id(directory, args.host_id_file) + old = read_credentials(directory) + requested_client = old["client_id"] if old else DYNAMIC_CLIENT + verifier = secrets.token_urlsafe(64) + state = secrets.token_urlsafe(32) + nonce = secrets.token_urlsafe(32) + server = LoopbackHTTPServer(("127.0.0.1", args.port), BaseHTTPRequestHandler) + port = server.server_address[1] + expected_host = f"127.0.0.1:{port}" + redirect_uri = f"http://{expected_host}/auth/callback" + attempt = CallbackAttempt(state, requested_client, time.monotonic() + args.timeout) + server.RequestHandlerClass = callback_handler(attempt, expected_host) + server.timeout = min(1, args.timeout) + query = { + "client_id": requested_client, + "ext_agent_host_id": host, + "response_type": "code", + "redirect_uri": redirect_uri, + "scope": SCOPES, + "resource": RESOURCE, + "state": state, + "nonce": nonce, + "code_challenge_method": "S256", + "code_challenge": pkce_challenge(verifier), + } + if requested_client == DYNAMIC_CLIENT: + query["agent_name_hint"] = AGENT_NAME + print(AUTHORIZE_URL + "?" + urlencode(query), flush=True) + try: + while attempt.result is None and time.monotonic() <= attempt.deadline: + server.handle_request() + finally: + server.server_close() + if attempt.result is None: + raise AppError("callback_timeout") + if attempt.result["denied"]: + raise AppError("authorization_denied") + check_discovery(session) + issued = attempt.result["client_id"] + token = exchange_code(session, attempt.result["code"], verifier, redirect_uri, issued) + scopes = validate_token_response(token) + claims = validate_id_token(token["id_token"], issued, nonce, session) + if old and old["subject"] != claims["sub"]: + raise AppError("account_mismatch") + now = time.time() + saved = { + "issuer": ISSUER, + "subject": claims["sub"], + "client_id": issued, + "host_id": host, + "access_token": token["access_token"], + "refresh_token": token["refresh_token"], + "id_token": token["id_token"], + "token_type": "Bearer", + "scopes": scopes, + "saved_at": utc_now(), + "expires_at": now + token["expires_in"], + } + atomic_json(credentials_path(directory), saved) + print(json.dumps({"authorized": True})) + + +def status(args): + directory = secure_dir(args.state_dir) + host_data = read_json(directory / "host.json") + if host_data is not None and ( + not isinstance(host_data, dict) or not isinstance(host_data.get("host_id"), str) + ): + raise AppError("invalid_state") + creds = read_credentials(directory) + authorized = credentials_valid(creds) + result = { + "authorized": authorized, + "access_token_expired": not isinstance(creds, dict) + or not isinstance(creds.get("expires_at"), (int, float)) + or creds.get("expires_at", 0) <= time.time(), + } + if host_data and isinstance(host_data.get("host_id"), str): + result["host_id"] = host_data["host_id"] + print(json.dumps(result, sort_keys=True)) + + +def refresh(session, path, creds): + response = _request( + session, + "POST", + TOKEN_URL, + data={ + "grant_type": "refresh_token", + "client_id": creds["client_id"], + "refresh_token": creds["refresh_token"], + "resource": RESOURCE, + }, + ) + data = _safe_response(response) + scopes = validate_token_response({**data, "id_token": data.get("id_token", creds.get("id_token"))}) + if data["refresh_token"] == creds["refresh_token"]: + raise AppError("refresh_not_rotated") + updated = dict(creds) + updated.update( + access_token=data["access_token"], + refresh_token=data["refresh_token"], + token_type="Bearer", + scopes=scopes, + saved_at=utc_now(), + expires_at=time.time() + data["expires_in"], + ) + atomic_json(path, updated) + return updated + + +def models(args, session=None): + session = session or new_session() + with credential_lock(args.state_dir) as directory: + path = credentials_path(directory) + creds = read_credentials(directory) + if not isinstance(creds, dict): + raise AppError("not_authorized") + if creds.get("expires_at", 0) <= time.time() + 120: + creds = refresh(session, path, creds) + response = _request( + session, + "GET", + MODELS_URL, + headers={"Authorization": "Bearer " + creds["access_token"]}, + ) + data = _safe_response(response) + entries = data.get("models") + if not isinstance(entries, list): + raise AppError("models_response_invalid") + visible = [] + for item in entries: + if ( + isinstance(item, dict) + and item.get("visibility") == "list" + and isinstance(item.get("slug"), str) + and isinstance(item.get("display_name"), str) + ): + visible.append({"slug": item["slug"], "display_name": item["display_name"]}) + print(json.dumps(visible, separators=(",", ":"))) + + +def parser(): + result = argparse.ArgumentParser(prog="affine-chatgpt") + result.add_argument("--state-dir", type=Path, default=default_state_dir()) + commands = result.add_subparsers(dest="command", required=True) + login_parser = commands.add_parser("login") + login_parser.add_argument("--port", type=int, default=1455) + login_parser.add_argument("--timeout", type=int, default=900) + login_parser.add_argument("--host-id-file", type=Path) + commands.add_parser("status") + commands.add_parser("models") + serve_parser = commands.add_parser("serve") + serve_parser.add_argument("--host", default="127.0.0.1") + serve_parser.add_argument("--port", type=int, default=3012) + serve_parser.add_argument("--gateway-key-file", type=Path, required=True) + return result + + +def main(argv=None): + args = parser().parse_args(argv) + try: + if args.command == "login": + if not 0 <= args.port <= 65535 or args.timeout <= 0: + raise AppError("invalid_argument") + login(args) + elif args.command == "status": + status(args) + elif args.command == "models": + models(args) + else: + if not 0 <= args.port <= 65535: + raise AppError("invalid_argument") + try: + ipaddress.ip_address(args.host) + except ValueError: + raise AppError("invalid_argument") from None + from affine_gateway import serve + + serve(args) + except AppError as error: + print(f"error: {error}", file=sys.stderr) + return 1 + except OSError: + print("error: local_io_error", file=sys.stderr) + return 1 + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/package/affine-chatgpt/src/affine_gateway.py b/package/affine-chatgpt/src/affine_gateway.py new file mode 100644 index 00000000..d381b04e --- /dev/null +++ b/package/affine-chatgpt/src/affine_gateway.py @@ -0,0 +1,612 @@ +"""Minimal OpenAI Responses-compatible gateway for AFFiNE.""" + +import hmac +import json +import os +import re +import socket +import stat +import threading +import time +from typing import cast +from http.server import BaseHTTPRequestHandler, HTTPServer +from socketserver import ThreadingMixIn +from urllib.parse import urlsplit + +import requests + +import affine_chatgpt as auth + + +MAX_BODY = 2 * 1024 * 1024 +MAX_EVENT = 8 * 1024 * 1024 +CONNECT_TIMEOUT = 15 +READ_TIMEOUT = 90 +SOCKET_TIMEOUT = 95 +HEADER_TIMEOUT = 10 +CATALOG_TTL = 300 +MAX_CONCURRENT = 16 +MAX_CONNECTIONS = 32 +NAMESPACE = "affine" +NAME_RE = re.compile(r"^[A-Za-z0-9_.-]{1,128}$") +NAMESPACE_RE = re.compile(r"^[A-Za-z0-9_-]{1,64}$") +SAFE_UPSTREAM_CODES = { + "invalid_request_error", + "model_not_found", + "rate_limit_exceeded", + "server_error", + "insufficient_quota", +} +IGNORED_FIELDS = { + "max_output_tokens", + "max_tool_calls", + "metadata", + "moderation", + "multi_agent", + "prompt_cache_retention", + "safety_identifier", + "temperature", + "top_logprobs", + "top_p", + "truncation", + "user", +} +REJECTED_FIELDS = {"background", "conversation", "previous_response_id", "prompt"} + + +class GatewayError(Exception): + """Expected client/upstream failure safe for public output.""" + + def __init__(self, status, code): + super().__init__(code) + self.status = status + self.code = code + + +def read_gateway_key(path): + try: + info = path.lstat() + except OSError: + raise auth.AppError("invalid_gateway_key") from None + if stat.S_ISLNK(info.st_mode) or not stat.S_ISREG(info.st_mode) or info.st_mode & 0o077: + raise auth.AppError("invalid_gateway_key") + try: + descriptor = os.open(path, os.O_RDONLY | os.O_NOFOLLOW) + with os.fdopen(descriptor, "r", encoding="utf-8") as stream: + value = stream.read(4097).strip() + except (OSError, UnicodeError): + raise auth.AppError("invalid_gateway_key") from None + if len(value) < 32 or len(value) > 4096 or "\n" in value or "\r" in value: + raise auth.AppError("invalid_gateway_key") + return value + + +def new_session(): + session = requests.Session() + session.trust_env = False + return session + + +def _response_json(response, code): + if response.is_redirect: + raise GatewayError(response.status_code, "upstream_redirect") + try: + value = response.json() + except (requests.RequestException, ValueError): + raise GatewayError(502, code) from None + if not isinstance(value, dict): + raise GatewayError(502, code) + return value + + +class Provider: + def __init__(self, state_dir, session=None, now=time.time): + self.state_dir = state_dir + self.session = session or new_session() + self.now = now + self.catalog = None + self.catalog_at = 0 + self.lock = threading.Lock() + + def credentials(self): + with auth.credential_lock(self.state_dir) as directory: + path = auth.credentials_path(directory) + creds = auth.read_credentials(directory) + if not isinstance(creds, dict): + raise auth.AppError("not_authorized") + if creds.get("expires_at", 0) <= self.now() + 120: + creds = auth.refresh(self.session, path, creds) + return creds + + def ready(self): + self.credentials() + + def models(self): + with self.lock: + if self.catalog is not None and self.now() - self.catalog_at < CATALOG_TTL: + return list(self.catalog) + creds = self.credentials() + response = auth._request( + self.session, + "GET", + auth.MODELS_URL, + headers={"Authorization": "Bearer " + creds["access_token"]}, + ) + if response.is_redirect or response.status_code != 200: + raise GatewayError(response.status_code, "upstream_models_error") + data = _response_json(response, "upstream_models_invalid") + entries = data.get("models") + if not isinstance(entries, list): + raise GatewayError(502, "upstream_models_invalid") + catalog = [] + for item in entries: + if ( + isinstance(item, dict) + and item.get("visibility") == "list" + and isinstance(item.get("slug"), str) + and item["slug"] + and isinstance(item.get("display_name"), str) + ): + catalog.append((item["slug"], item["display_name"])) + self.catalog = catalog + self.catalog_at = self.now() + return list(catalog) + + def response(self, body): + if auth.RESPONSES_URL != "https://api.openai.com/v1/responses": + raise GatewayError(500, "endpoint_not_allowed") + creds = self.credentials() + try: + return self.session.request( + "POST", + auth.RESPONSES_URL, + headers={ + "Authorization": "Bearer " + creds["access_token"], + "Content-Type": "application/json", + "Accept": "text/event-stream", + }, + json=body, + stream=True, + timeout=(CONNECT_TIMEOUT, READ_TIMEOUT), + allow_redirects=False, + ) + except requests.RequestException: + raise GatewayError(502, "upstream_network_error") from None + + +def _copy_keys(value, allowed): + return {key: value[key] for key in allowed if key in value} + + +def _normalize_content(content, role): + if isinstance(content, str): + return [{"type": "output_text" if role == "assistant" else "input_text", "text": content}] + if not isinstance(content, list) or not content: + raise GatewayError(400, "invalid_input") + result = [] + for part in content: + if not isinstance(part, dict) or part.get("type") not in {"input_text", "output_text"}: + raise GatewayError(400, "unsupported_media") + if not isinstance(part.get("text"), str): + raise GatewayError(400, "invalid_input") + result.append({"type": part["type"], "text": part["text"]}) + return result + + +def _normalize_item(item): + if not isinstance(item, dict): + raise GatewayError(400, "invalid_input") + item_type = item.get("type") + if item_type in (None, "message"): + role = item.get("role") + if role == "system": + role = "developer" + if role not in {"user", "assistant", "developer"}: + raise GatewayError(400, "invalid_input") + return { + "type": "message", + "role": role, + "content": _normalize_content(item.get("content"), role), + } + if item_type == "function_call": + result = _copy_keys(item, {"id", "call_id", "name", "arguments", "namespace", "status"}) + if not all(isinstance(result.get(key), str) and result[key] for key in ("call_id", "name", "arguments")): + raise GatewayError(400, "invalid_input") + result["type"] = item_type + return result + if item_type == "function_call_output": + result = _copy_keys(item, {"id", "call_id", "output", "status"}) + if not isinstance(result.get("call_id"), str) or not result["call_id"] or not isinstance(result.get("output"), str): + raise GatewayError(400, "invalid_input") + result["type"] = item_type + return result + if item_type == "reasoning": + result = _copy_keys(item, {"id", "summary", "content", "encrypted_content", "status"}) + if not any(key in result for key in ("summary", "content", "encrypted_content")): + raise GatewayError(400, "invalid_input") + result["type"] = item_type + return result + raise GatewayError(400, "unsupported_input_type") + + +def _normalize_inner_tool(tool): + if not isinstance(tool, dict) or tool.get("type") not in {"function", "custom"}: + raise GatewayError(400, "unsupported_tool") + name = tool.get("name") + if not isinstance(name, str) or not NAME_RE.fullmatch(name): + raise GatewayError(400, "invalid_tool") + if tool["type"] == "function": + allowed = {"type", "name", "description", "parameters", "strict"} + else: + allowed = {"type", "name", "description", "format"} + if set(tool) - allowed: + raise GatewayError(400, "unsupported_tool_field") + return _copy_keys(tool, allowed) + + +def _normalize_tools(tools): + if not isinstance(tools, list) or not tools: + raise GatewayError(400, "invalid_tools") + if all(isinstance(tool, dict) and tool.get("type") in {"function", "custom"} for tool in tools): + return [{ + "type": "namespace", + "name": NAMESPACE, + "description": "Functions provided and executed by AFFiNE.", + "tools": [_normalize_inner_tool(tool) for tool in tools], + }] + result = [] + for namespace in tools: + if not isinstance(namespace, dict) or set(namespace) - {"type", "name", "description", "tools"}: + raise GatewayError(400, "unsupported_tool") + name = namespace.get("name") + nested = namespace.get("tools") + if namespace.get("type") != "namespace" or not isinstance(name, str) or not NAMESPACE_RE.fullmatch(name): + raise GatewayError(400, "unsupported_tool") + if not isinstance(namespace.get("description"), str) or not isinstance(nested, list) or not nested: + raise GatewayError(400, "invalid_tools") + result.append({ + "type": "namespace", + "name": name, + "description": namespace["description"], + "tools": [_normalize_inner_tool(tool) for tool in nested], + }) + return result + + +def _normalize_choice(choice, had_flat_tools): + if isinstance(choice, str) and choice in {"auto", "none", "required"}: + return choice + if not isinstance(choice, dict): + raise GatewayError(400, "unsupported_tool_choice") + result = dict(choice) + if result.get("type") in {"function", "custom"} and had_flat_tools: + if set(result) - {"type", "name"} or not isinstance(result.get("name"), str): + raise GatewayError(400, "unsupported_tool_choice") + result["namespace"] = NAMESPACE + return result + if result.get("type") in {"function", "custom"}: + if set(result) - {"type", "name", "namespace"}: + raise GatewayError(400, "unsupported_tool_choice") + return result + raise GatewayError(400, "unsupported_tool_choice") + + +def normalize_request(value, eligible): + if not isinstance(value, dict): + raise GatewayError(400, "invalid_json") + allowed = {"model", "input", "instructions", "tools", "tool_choice", "store", "stream"} + unknown = set(value) - allowed - IGNORED_FIELDS - REJECTED_FIELDS + if set(value) & REJECTED_FIELDS: + raise GatewayError(400, "unsupported_parameter") + if unknown: + raise GatewayError(400, "unsupported_parameter") + if "stream" in value and not isinstance(value["stream"], bool): + raise GatewayError(400, "invalid_stream") + if "store" in value and not isinstance(value["store"], bool): + raise GatewayError(400, "invalid_store") + model = value.get("model") + if not isinstance(model, str) or model not in eligible: + raise GatewayError(400, "model_not_available") + incoming = value.get("input") + if not isinstance(incoming, list) or not incoming: + raise GatewayError(400, "invalid_input") + result = { + "model": model, + "input": [_normalize_item(item) for item in incoming], + "store": False, + "stream": True, + } + if "instructions" in value: + if not isinstance(value["instructions"], str): + raise GatewayError(400, "invalid_instructions") + result["instructions"] = value["instructions"] + if "tools" in value: + flat = all(isinstance(tool, dict) and tool.get("type") in {"function", "custom"} for tool in value["tools"]) if isinstance(value["tools"], list) else False + result["tools"] = _normalize_tools(value["tools"]) + if "tool_choice" in value: + result["tool_choice"] = _normalize_choice(value["tool_choice"], flat) + elif "tool_choice" in value: + raise GatewayError(400, "unsupported_tool_choice") + return result + + +def _events(response): + buffer = b"" + try: + for chunk in response.iter_content(chunk_size=16384): + if not chunk: + continue + buffer += chunk + if len(buffer) > MAX_EVENT: + raise GatewayError(502, "upstream_stream_invalid") + while True: + positions = [(buffer.find(b"\n\n"), 2), (buffer.find(b"\r\n\r\n"), 4)] + positions = [(position, size) for position, size in positions if position >= 0] + if not positions: + break + position, size = min(positions) + raw, buffer = buffer[: position + size], buffer[position + size :] + yield raw, _event_data(raw) + if buffer.strip(): + raise GatewayError(502, "upstream_stream_interrupted") + except requests.RequestException: + raise GatewayError(502, "upstream_stream_interrupted") from None + + +def _event_data(raw): + data = [] + for line in raw.replace(b"\r\n", b"\n").split(b"\n"): + if line.startswith(b"data:"): + data.append(line[5:].lstrip()) + if not data or b"\n".join(data) == b"[DONE]": + return None + try: + value = json.loads(b"\n".join(data)) + except (ValueError, UnicodeError): + raise GatewayError(502, "upstream_stream_invalid") from None + if not isinstance(value, dict) or not isinstance(value.get("type"), str): + raise GatewayError(502, "upstream_stream_invalid") + return value + + +def _upstream_error(response): + code = "upstream_http_error" + try: + value = response.json() + candidate = value.get("error", {}).get("code") + if candidate in SAFE_UPSTREAM_CODES: + code = candidate + except (requests.RequestException, ValueError, AttributeError): + return GatewayError(response.status_code, code) + return GatewayError(response.status_code, code) + + +class GatewayServer(ThreadingMixIn, HTTPServer): + daemon_threads = True + block_on_close = False + + def __init__( + self, + address, + provider, + key, + max_concurrent=MAX_CONCURRENT, + max_connections=MAX_CONNECTIONS, + ): + self.provider = provider + self.gateway_key = key + self.capacity = threading.BoundedSemaphore(max_concurrent) + self.connection_capacity = threading.BoundedSemaphore(max_connections) + super().__init__(address, GatewayHandler) + + def get_request(self): + request, address = super().get_request() + request.settimeout(HEADER_TIMEOUT) + return request, address + + def process_request(self, request, client_address): + if not self.connection_capacity.acquire(blocking=False): + self.shutdown_request(request) + return + try: + super().process_request(request, client_address) + except BaseException: + self.connection_capacity.release() + raise + + def process_request_thread(self, request, client_address): + try: + super().process_request_thread(request, client_address) + finally: + self.connection_capacity.release() + + def handle_error(self, request, client_address): + return + + +class GatewayHandler(BaseHTTPRequestHandler): + protocol_version = "HTTP/1.1" + + def log_message(self, format, *args): + return + + @property + def gateway(self): + return cast(GatewayServer, self.server) + + def _authorized(self): + value = self.headers.get("Authorization", "") + prefix = "Bearer " + supplied = value[len(prefix) :] if value.startswith(prefix) else "" + return hmac.compare_digest(supplied.encode(), self.gateway.gateway_key.encode()) + + def _json(self, status, value): + body = json.dumps(value, separators=(",", ":")).encode() + try: + self.send_response(status) + self.send_header("Content-Type", "application/json") + self.send_header("Cache-Control", "no-store") + self.send_header("Connection", "close") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + self.close_connection = True + except OSError: + return + + def _error(self, error): + self.close_connection = True + self._json(error.status, {"error": {"message": "Gateway request failed.", "type": "gateway_error", "code": error.code}}) + + def _enter(self): + if not self.gateway.capacity.acquire(blocking=False): + self._error(GatewayError(503, "gateway_busy")) + return False + return True + + def do_GET(self): + self.connection.settimeout(SOCKET_TIMEOUT) + if not self._enter(): + return + try: + target = urlsplit(self.path) + if target.query or target.fragment: + self._error(GatewayError(404, "not_found")) + return + path = target.path + if path == "/healthz": + self._json(200, {"status": "ready"}) + return + if not self._authorized(): + self._error(GatewayError(401, "unauthorized")) + return + if path != "/v1/models": + self._error(GatewayError(404, "not_found")) + return + data = [{"id": slug, "object": "model", "created": 0, "owned_by": "openai"} for slug, _name in self.gateway.provider.models()] + self._json(200, {"object": "list", "data": data}) + except GatewayError as error: + self._error(error) + except (auth.AppError, OSError): + self._error(GatewayError(503, "credentials_unavailable")) + finally: + self.gateway.capacity.release() + + def do_POST(self): + self.connection.settimeout(SOCKET_TIMEOUT) + if not self._enter(): + return + upstream = None + try: + if not self._authorized(): + raise GatewayError(401, "unauthorized") + target = urlsplit(self.path) + if target.path != "/v1/responses" or target.query or target.fragment: + raise GatewayError(404, "not_found") + if self.headers.get("Transfer-Encoding") is not None: + raise GatewayError(400, "unsupported_transfer_encoding") + content_type = self.headers.get("Content-Type", "").lower().replace(" ", "") + if content_type not in {"application/json", "application/json;charset=utf-8"}: + raise GatewayError(415, "unsupported_content_type") + lengths = self.headers.get_all("Content-Length", []) + if len(lengths) != 1: + raise GatewayError(400, "invalid_content_length") + raw_length = lengths[0] + try: + length = int(raw_length) if raw_length is not None else -1 + except ValueError: + length = -1 + if length < 0: + raise GatewayError(411, "content_length_required") + if length > MAX_BODY: + raise GatewayError(413, "request_too_large") + try: + value = json.loads(self.rfile.read(length)) + except (ValueError, UnicodeError): + raise GatewayError(400, "invalid_json") from None + eligible = {slug for slug, _name in self.gateway.provider.models()} + body = normalize_request(value, eligible) + wants_stream = value.get("stream") is True + upstream = self.gateway.provider.response(body) + if upstream.is_redirect or upstream.status_code != 200: + raise _upstream_error(upstream) + media_type = upstream.headers.get("Content-Type", "").split(";", 1)[0].strip().lower() + if media_type and media_type != "text/event-stream": + raise GatewayError(502, "upstream_content_type_invalid") + if wants_stream: + self._stream(upstream) + else: + self._aggregate(upstream) + except GatewayError as error: + self._error(error) + except (auth.AppError, OSError): + self._error(GatewayError(503, "credentials_unavailable")) + finally: + if upstream is not None: + upstream.close() + self.gateway.capacity.release() + + def _stream(self, upstream): + self.send_response(200) + self.send_header("Content-Type", "text/event-stream") + self.send_header("Cache-Control", "no-store") + self.send_header("Connection", "close") + self.end_headers() + terminal = False + try: + for raw, event in _events(upstream): + self.wfile.write(raw) + self.wfile.flush() + if event and event["type"] in {"response.completed", "response.failed", "response.incomplete", "error"}: + terminal = True + if not terminal: + raise GatewayError(502, "upstream_stream_interrupted") + except (GatewayError, OSError): + if not terminal: + safe = b'event: error\ndata: {"type":"error","code":"upstream_stream_interrupted","message":"Gateway stream interrupted."}\n\n' + try: + self.wfile.write(safe) + self.wfile.flush() + except OSError: + return + finally: + self.close_connection = True + + def _aggregate(self, upstream): + completed = None + terminal_error = None + output_items = {} + for _raw, event in _events(upstream): + if event is None: + continue + if event["type"] == "response.output_item.done": + index = event.get("output_index") + item = event.get("item") + if isinstance(index, int) and not isinstance(index, bool) and 0 <= index < 1024 and isinstance(item, dict): + output_items[index] = item + else: + terminal_error = "upstream_response_invalid" + elif event["type"] == "response.completed": + response = event.get("response") + if isinstance(response, dict) and response.get("status") == "completed" and isinstance(response.get("output"), list): + completed = response + else: + terminal_error = "upstream_response_invalid" + elif event["type"] in {"response.failed", "response.incomplete", "error"}: + terminal_error = "upstream_response_failed" + if terminal_error or completed is None: + raise GatewayError(502, terminal_error or "upstream_stream_interrupted") + if not completed["output"] and output_items: + completed = {**completed, "output": [output_items[index] for index in sorted(output_items)]} + self._json(200, completed) + + +def serve(args): + key = read_gateway_key(args.gateway_key_file) + provider = Provider(args.state_dir) + provider.ready() + server = GatewayServer((args.host, args.port), provider, key) + try: + server.serve_forever(poll_interval=0.25) + finally: + server.server_close() diff --git a/package/affine-chatgpt/test/test_affine_chatgpt.py b/package/affine-chatgpt/test/test_affine_chatgpt.py new file mode 100644 index 00000000..da54b423 --- /dev/null +++ b/package/affine-chatgpt/test/test_affine_chatgpt.py @@ -0,0 +1,706 @@ +import io +import http.client +import json +import os +import socket +import stat +import tempfile +import threading +import time +import unittest +from contextlib import redirect_stderr, redirect_stdout +from pathlib import Path +from types import SimpleNamespace +from unittest import mock +from urllib.parse import parse_qs, urlencode, urlsplit + +import jwt +import requests +from cryptography.hazmat.primitives.asymmetric import rsa + +import affine_chatgpt as app + + +class Response: + def __init__(self, data=None, status=200, redirect=False): + self.data = data + self.status_code = status + self.is_redirect = redirect + + def json(self): + if isinstance(self.data, Exception): + raise self.data + return self.data + + +class Session: + def __init__(self, responses=()): + self.trust_env = True + self.responses = list(responses) + self.calls = [] + + def request(self, method, url, **kwargs): + self.calls.append((method, url, kwargs)) + result = self.responses.pop(0) + if isinstance(result, Exception): + raise result + return result + + +class ProviderSession: + def __init__(self, key, subject="account-subject"): + self.key = key + self.subject = subject + self.nonce = None + self.calls = [] + + def request(self, method, url, **kwargs): + self.calls.append((method, url, kwargs)) + if url == app.DISCOVERY_URL: + return Response( + { + "issuer": app.ISSUER, + "authorization_endpoint": app.AUTHORIZE_URL, + "token_endpoint": app.TOKEN_URL, + "jwks_uri": app.JWKS_URL, + } + ) + if url == app.TOKEN_URL: + now = int(time.time()) + client_id = kwargs["data"]["client_id"] + identity = jwt.encode( + { + "iss": app.ISSUER, + "aud": client_id, + "exp": now + 300, + "iat": now, + "nonce": self.nonce, + "sub": self.subject, + }, + self.key, + algorithm="RS256", + headers={"kid": "integration-key"}, + ) + return Response( + { + "access_token": "integration-access", + "refresh_token": "integration-refresh", + "id_token": identity, + "token_type": "Bearer", + "expires_in": 3600, + "scope": app.SCOPES, + } + ) + if url == app.JWKS_URL: + return Response({"keys": [jwk_for(self.key, "integration-key")]}) + raise AssertionError(f"unexpected provider URL: {url}") + + +def jwk_for(key, kid="test-key"): + numbers = key.public_key().public_numbers() + + def encoded(number): + size = (number.bit_length() + 7) // 8 + return app.base64.urlsafe_b64encode(number.to_bytes(size, "big")).rstrip(b"=").decode() + + return { + "kty": "RSA", + "kid": kid, + "use": "sig", + "alg": "RS256", + "n": encoded(numbers.n), + "e": encoded(numbers.e), + } + + +class SecurityTests(unittest.TestCase): + def setUp(self): + self.temporary = tempfile.TemporaryDirectory() + self.state = Path(self.temporary.name) / "state" + + def tearDown(self): + self.temporary.cleanup() + + def test_pkce_is_deterministic_and_unpadded(self): + self.assertEqual( + app.pkce_challenge("verifier"), + "iMnq5o6zALKXGivsnlom_0F5_WYda32GHkxlV7mq7hQ", + ) + self.assertNotIn("=", app.pkce_challenge("verifier")) + + def test_login_default_session_ignores_proxy_environment(self): + session = Session() + args = SimpleNamespace(state_dir=self.state, host_id_file=None, port=0, timeout=0) + with mock.patch.object(app.requests, "Session", return_value=session): + with redirect_stdout(io.StringIO()): + with self.assertRaisesRegex(app.AppError, "callback_timeout"): + app.login(args) + self.assertFalse(session.trust_env) + + def test_atomic_permissions_and_symlink_protection(self): + path = self.state / "credentials.json" + app.atomic_json(path, {"safe": True}) + self.assertEqual(stat.S_IMODE(self.state.stat().st_mode), 0o700) + self.assertEqual(stat.S_IMODE(path.stat().st_mode), 0o600) + path.unlink() + target = Path(self.temporary.name) / "target" + target.write_text("unchanged", encoding="utf-8") + path.symlink_to(target) + with self.assertRaisesRegex(app.AppError, "unsafe_state_file"): + app.atomic_json(path, {"unsafe": True}) + self.assertEqual(target.read_text(encoding="utf-8"), "unchanged") + + def test_state_directory_symlink_rejected(self): + real = Path(self.temporary.name) / "real" + real.mkdir() + self.state.symlink_to(real, target_is_directory=True) + with self.assertRaisesRegex(app.AppError, "unsafe_state_dir"): + app.secure_dir(self.state) + + def test_atomic_write_syncs_file_and_parent_directory(self): + original_fsync = os.fsync + synced_directories = [] + + def record_fsync(descriptor): + synced_directories.append(stat.S_ISDIR(os.fstat(descriptor).st_mode)) + original_fsync(descriptor) + + with mock.patch.object(app.os, "fsync", side_effect=record_fsync): + app.atomic_json(self.state / "credentials.json", {"safe": True}) + self.assertEqual(synced_directories, [False, True]) + + def test_insecure_existing_file_rejected(self): + self.state.mkdir(mode=0o700) + path = self.state / "credentials.json" + path.write_text("{}", encoding="utf-8") + path.chmod(0o644) + with self.assertRaisesRegex(app.AppError, "unsafe_state_file"): + app.read_json(path) + + def test_status_exposes_only_allowed_fields(self): + app.atomic_json(self.state / "host.json", {"host_id": "urn:uuid:test"}) + app.atomic_json( + self.state / "credentials.json", + { + "issuer": app.ISSUER, + "subject": "private-subject", + "client_id": "issued", + "host_id": "urn:uuid:test", + "access_token": "access-secret", + "refresh_token": "refresh-secret", + "id_token": "identity-secret", + "token_type": "Bearer", + "saved_at": "date", + "expires_at": time.time() + 60, + "scopes": [app.REQUIRED_SCOPE], + }, + ) + output = io.StringIO() + with redirect_stdout(output): + app.status(SimpleNamespace(state_dir=self.state)) + result = json.loads(output.getvalue()) + self.assertEqual(set(result), {"authorized", "access_token_expired", "host_id"}) + self.assertTrue(result["authorized"]) + self.assertNotIn("secret", output.getvalue()) + self.assertNotIn("subject", output.getvalue()) + + def test_status_handles_malformed_json_shape(self): + app.atomic_json(self.state / "credentials.json", ["malformed"]) + with self.assertRaisesRegex(app.AppError, "invalid_state"): + app.status(SimpleNamespace(state_dir=self.state)) + + def test_main_sanitizes_malformed_json_and_shape(self): + cases = ("{broken", '["wrong-shape"]') + for content in cases: + with self.subTest(content=content): + self.state.mkdir(mode=0o700, exist_ok=True) + path = self.state / "credentials.json" + path.write_text(content, encoding="utf-8") + path.chmod(0o600) + stderr = io.StringIO() + with redirect_stderr(stderr): + result = app.main( + ["--state-dir", str(self.state), "login", "--port", "0", "--timeout", "1"] + ) + self.assertEqual(result, 1) + self.assertEqual(stderr.getvalue(), "error: invalid_state\n") + + def test_main_sanitizes_malformed_host_shape(self): + app.atomic_json(self.state / "host.json", ["wrong-shape"]) + stderr = io.StringIO() + with redirect_stderr(stderr): + result = app.main( + ["--state-dir", str(self.state), "login", "--port", "0", "--timeout", "1"] + ) + self.assertEqual(result, 1) + self.assertEqual(stderr.getvalue(), "error: invalid_state\n") + + def test_occupied_port_is_sanitized_local_io_error(self): + listener = socket.socket() + listener.bind(("127.0.0.1", 0)) + listener.listen() + try: + port = listener.getsockname()[1] + stderr = io.StringIO() + with redirect_stderr(stderr): + result = app.main( + ["--state-dir", str(self.state), "login", "--port", str(port), "--timeout", "1"] + ) + self.assertEqual(result, 1) + self.assertEqual(stderr.getvalue(), "error: local_io_error\n") + finally: + listener.close() + + +class CallbackTests(unittest.TestCase): + def attempt(self, client=app.DYNAMIC_CLIENT): + return app.CallbackAttempt("expected-state", client, 100) + + def test_state_nonce_mismatch_does_not_consume(self): + attempt = self.attempt() + with self.assertRaisesRegex(app.AppError, "state_mismatch"): + attempt.process("state=wrong&error=access_denied", "127.0.0.1:1455", "127.0.0.1:1455", 1) + self.assertFalse(attempt.consumed) + + +class LoopbackIntegrationTests(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.key = rsa.generate_private_key(public_exponent=65537, key_size=2048) + + def setUp(self): + self.temporary = tempfile.TemporaryDirectory() + self.state = Path(self.temporary.name) / "state" + + def tearDown(self): + self.temporary.cleanup() + + def start_login(self, provider): + output = io.StringIO() + errors = io.StringIO() + failures = [] + args = SimpleNamespace( + state_dir=self.state, + host_id_file=None, + port=0, + timeout=5, + ) + + def run(): + try: + with mock.patch.object(app, "SOCKET_TIMEOUT", 0.1): + with redirect_stdout(output), redirect_stderr(errors): + app.login(args, provider) + except Exception as error: + failures.append(error) + + thread = threading.Thread(target=run) + thread.start() + deadline = time.time() + 2 + while "\n" not in output.getvalue() and time.time() < deadline: + time.sleep(0.01) + self.assertIn("\n", output.getvalue()) + authorization = output.getvalue().splitlines()[0] + query = parse_qs(urlsplit(authorization).query) + provider.nonce = query["nonce"][0] + return thread, output, errors, failures, query + + def callback(self, redirect_uri, parameters): + target = urlsplit(redirect_uri) + connection = http.client.HTTPConnection(target.hostname, target.port, timeout=2) + path = target.path + "?" + urlencode(parameters) + connection.request("GET", path, headers={"Host": f"127.0.0.1:{target.port}"}) + response = connection.getresponse() + body = response.read() + connection.close() + return response.status, body + + def test_real_listener_retries_malformed_callback_and_logs_nothing(self): + provider = ProviderSession(self.key) + thread, output, errors, failures, query = self.start_login(provider) + redirect_uri = query["redirect_uri"][0] + target = urlsplit(redirect_uri) + host, port = target.hostname, target.port + if not isinstance(host, str) or not isinstance(port, int): + self.fail("redirect URI did not contain loopback host and port") + + stalled = socket.create_connection((host, port), timeout=1) + + secret_code = "must-not-appear-in-http-log" + status, body = self.callback( + redirect_uri, + {"state": "wrong-state", "code": secret_code, "client_id": "issued-client"}, + ) + self.assertEqual(status, 400) + self.assertNotIn(secret_code.encode(), body) + + status, body = self.callback( + redirect_uri, + { + "state": query["state"][0], + "code": "valid-code", + "client_id": "issued-client", + }, + ) + self.assertEqual(status, 200) + self.assertNotIn(b"valid-code", body) + stalled.close() + thread.join(3) + self.assertFalse(thread.is_alive()) + self.assertEqual(failures, []) + self.assertEqual(errors.getvalue(), "") + self.assertNotIn(secret_code, output.getvalue()) + saved = app.read_json(self.state / "credentials.json") + assert isinstance(saved, dict) + self.assertEqual(saved["subject"], "account-subject") + self.assertEqual(saved["client_id"], "issued-client") + token_call = next(call for call in provider.calls if call[1] == app.TOKEN_URL) + self.assertEqual(token_call[2]["data"]["code"], "valid-code") + + def test_valid_rsa_failure_preserves_old_credentials(self): + host = "urn:uuid:00000000-0000-4000-8000-000000000000" + app.atomic_json(self.state / "host.json", {"host_id": host}) + old = { + "issuer": app.ISSUER, + "subject": "old-subject", + "client_id": "issued-client", + "host_id": host, + "access_token": "old-access", + "refresh_token": "old-refresh", + "id_token": "old-identity", + "token_type": "Bearer", + "scopes": [app.REQUIRED_SCOPE], + "saved_at": "old-date", + "expires_at": time.time() + 60, + } + path = self.state / "credentials.json" + app.atomic_json(path, old) + before = path.read_bytes() + provider = ProviderSession(self.key, subject="different-subject") + thread, _output, errors, failures, query = self.start_login(provider) + status, _body = self.callback( + query["redirect_uri"][0], + {"state": query["state"][0], "code": "valid-code"}, + ) + self.assertEqual(status, 200) + thread.join(3) + self.assertFalse(thread.is_alive()) + self.assertEqual(len(failures), 1) + self.assertIsInstance(failures[0], app.AppError) + self.assertEqual(str(failures[0]), "account_mismatch") + self.assertEqual(errors.getvalue(), "") + self.assertEqual(path.read_bytes(), before) + + def test_disconnected_browser_does_not_abandon_valid_callback(self): + provider = ProviderSession(self.key) + thread, _output, errors, failures, query = self.start_login(provider) + target = urlsplit(query["redirect_uri"][0]) + host, port = target.hostname, target.port + if not isinstance(host, str) or not isinstance(port, int): + self.fail("redirect URI did not contain loopback host and port") + path = target.path + "?" + urlencode( + { + "state": query["state"][0], + "code": "valid-code", + "client_id": "issued-client", + } + ) + browser = socket.create_connection((host, port), timeout=1) + browser.sendall( + ( + f"GET {path} HTTP/1.1\r\n" + f"Host: 127.0.0.1:{target.port}\r\n" + "Connection: close\r\n\r\n" + ).encode("ascii") + ) + browser.close() + thread.join(3) + self.assertFalse(thread.is_alive()) + self.assertEqual(failures, []) + self.assertEqual(errors.getvalue(), "") + saved = app.read_json(self.state / "credentials.json") + assert isinstance(saved, dict) + self.assertEqual(saved["subject"], "account-subject") + + +class LockingTests(unittest.TestCase): + def attempt(self, client=app.DYNAMIC_CLIENT): + return app.CallbackAttempt("expected-state", client, 100) + + def test_authorization_lock_serializes_concurrent_operation(self): + with tempfile.TemporaryDirectory() as temporary: + state = Path(temporary) / "state" + acquired = threading.Event() + release = threading.Event() + second_acquired = threading.Event() + + def first(): + with app.credential_lock(state): + acquired.set() + release.wait(2) + + def second(): + with app.credential_lock(state): + second_acquired.set() + + first_thread = threading.Thread(target=first) + second_thread = threading.Thread(target=second) + first_thread.start() + self.assertTrue(acquired.wait(1)) + second_thread.start() + self.assertFalse(second_acquired.wait(0.1)) + release.set() + first_thread.join(1) + second_thread.join(1) + self.assertTrue(second_acquired.is_set()) + + def test_client_mismatch_and_valid_retry(self): + attempt = self.attempt("saved-client") + query = "state=expected-state&code=secret-code&client_id=other" + with self.assertRaisesRegex(app.AppError, "client_id_mismatch"): + attempt.process(query, "127.0.0.1:1455", "127.0.0.1:1455", 1) + result = attempt.process( + "state=expected-state&code=secret-code&client_id=saved-client", + "127.0.0.1:1455", + "127.0.0.1:1455", + 1, + ) + self.assertEqual(result["client_id"], "saved-client") + + def test_dynamic_client_must_be_replaced(self): + for returned in ("", app.DYNAMIC_CLIENT, "bad client"): + attempt = self.attempt() + suffix = "" if not returned else "&client_id=" + returned.replace(" ", "+") + with self.assertRaisesRegex(app.AppError, "client_id_invalid"): + attempt.process( + "state=expected-state&code=code" + suffix, + "127.0.0.1:1455", + "127.0.0.1:1455", + 1, + ) + + def test_replay_rejected(self): + attempt = self.attempt() + query = "state=expected-state&code=code&client_id=issued-client" + attempt.process(query, "127.0.0.1:1455", "127.0.0.1:1455", 1) + with self.assertRaisesRegex(app.AppError, "callback_replayed"): + attempt.process(query, "127.0.0.1:1455", "127.0.0.1:1455", 1) + + def test_denial_is_terminal_and_nonsecret(self): + attempt = self.attempt() + result = attempt.process( + "state=expected-state&error=access_denied&error_description=private", + "127.0.0.1:1455", + "127.0.0.1:1455", + 1, + ) + self.assertEqual(result, {"denied": True}) + self.assertNotIn("private", str(result)) + + def test_duplicate_and_unknown_query_fields_rejected(self): + bad_queries = ( + "state=expected-state&state=expected-state&code=x&client_id=issued", + "state=expected-state&code=x&client_id=issued&extra=x", + ) + for query in bad_queries: + with self.subTest(query=query): + with self.assertRaisesRegex(app.AppError, "callback_invalid"): + self.attempt().process(query, "127.0.0.1:1455", "127.0.0.1:1455", 1) + + def test_host_and_expiry_rejected_without_consuming(self): + attempt = self.attempt() + query = "state=expected-state&code=x&client_id=issued" + with self.assertRaisesRegex(app.AppError, "callback_invalid"): + attempt.process(query, "localhost:1455", "127.0.0.1:1455", 1) + with self.assertRaisesRegex(app.AppError, "callback_invalid"): + attempt.process(query, "127.0.0.1:1455", "127.0.0.1:1455", 101) + self.assertFalse(attempt.consumed) + + +class TokenTests(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.key = rsa.generate_private_key(public_exponent=65537, key_size=2048) + cls.jwks = {"keys": [jwk_for(cls.key)]} + + def token(self, **changes): + now = int(time.time()) + claims = { + "iss": app.ISSUER, + "aud": "issued-client", + "exp": now + 300, + "iat": now, + "nonce": "expected-nonce", + "sub": "account-subject", + } + claims.update(changes) + return jwt.encode(claims, self.key, algorithm="RS256", headers={"kid": "test-key"}) + + def session(self): + return Session([Response(self.jwks)]) + + def test_rsa_signature_verification(self): + claims = app.validate_id_token(self.token(), "issued-client", "expected-nonce", self.session()) + self.assertEqual(claims["sub"], "account-subject") + + def test_wrong_issuer_audience_expiry_and_nonce_rejected(self): + cases = ( + self.token(iss="https://evil.example"), + self.token(aud="wrong-client"), + self.token(exp=int(time.time()) - 1), + self.token(iat=int(time.time()) + 300), + self.token(nonce="wrong-nonce"), + ) + for encoded in cases: + with self.subTest(encoded=encoded[-12:]): + with self.assertRaisesRegex(app.AppError, "id_token_invalid"): + app.validate_id_token(encoded, "issued-client", "expected-nonce", self.session()) + + def test_wrong_signature_and_untrusted_jku_rejected(self): + other = rsa.generate_private_key(public_exponent=65537, key_size=2048) + encoded = jwt.encode( + jwt.decode(self.token(), options={"verify_signature": False}), + other, + algorithm="RS256", + headers={"kid": "test-key", "jku": "https://evil.example/jwks"}, + ) + with self.assertRaisesRegex(app.AppError, "id_token_invalid"): + app.validate_id_token(encoded, "issued-client", "expected-nonce", self.session()) + + def test_missing_scope_rejected(self): + response = { + "access_token": "access", + "refresh_token": "refresh", + "id_token": "identity", + "token_type": "Bearer", + "expires_in": 3600, + "scope": "openid offline_access", + } + with self.assertRaisesRegex(app.AppError, "scope_missing"): + app.validate_token_response(response) + + +class NetworkAndModelsTests(unittest.TestCase): + def setUp(self): + self.temporary = tempfile.TemporaryDirectory() + self.state = Path(self.temporary.name) / "state" + self.path = self.state / "credentials.json" + self.creds = { + "issuer": app.ISSUER, + "subject": "subject", + "client_id": "issued-client", + "host_id": "urn:uuid:00000000-0000-4000-8000-000000000000", + "access_token": "old-access-secret", + "refresh_token": "old-refresh-secret", + "id_token": "old-id-token", + "token_type": "Bearer", + "scopes": [app.REQUIRED_SCOPE], + "saved_at": "date", + "expires_at": time.time() - 1, + } + app.atomic_json(self.path, self.creds) + + def tearDown(self): + self.temporary.cleanup() + + def test_models_default_session_ignores_proxy_environment(self): + credentials = {**self.creds, "expires_at": time.time() + 3600} + app.atomic_json(self.path, credentials) + session = Session([Response({"models": []})]) + with mock.patch.object(app.requests, "Session", return_value=session): + with redirect_stdout(io.StringIO()): + app.models(SimpleNamespace(state_dir=self.state)) + self.assertFalse(session.trust_env) + + def test_refresh_rotation_and_models_visibility_filter(self): + refreshed = { + "access_token": "new-access-secret", + "refresh_token": "new-refresh-secret", + "token_type": "Bearer", + "expires_in": 3600, + "scope": app.REQUIRED_SCOPE + " openid", + } + catalog = { + "models": [ + {"slug": "visible", "display_name": "Visible", "visibility": "list", "secret": "drop"}, + {"slug": "hidden", "display_name": "Hidden", "visibility": "hide"}, + {"slug": 1, "display_name": "Malformed", "visibility": "list"}, + ] + } + session = Session([Response(refreshed), Response(catalog)]) + output = io.StringIO() + with redirect_stdout(output): + app.models(SimpleNamespace(state_dir=self.state), session) + self.assertEqual(json.loads(output.getvalue()), [{"slug": "visible", "display_name": "Visible"}]) + saved = app.read_json(self.path) + assert isinstance(saved, dict) + self.assertEqual(saved["refresh_token"], "new-refresh-secret") + self.assertEqual(saved["id_token"], "old-id-token") + self.assertEqual(session.calls[1][2]["headers"]["Authorization"], "Bearer new-access-secret") + + def test_refresh_failure_preserves_good_credentials(self): + before = self.path.read_bytes() + session = Session([Response({"error": "invalid_grant"}, status=400)]) + with self.assertRaisesRegex(app.AppError, "oauth_http_error"): + app.models(SimpleNamespace(state_dir=self.state), session) + self.assertEqual(self.path.read_bytes(), before) + + def test_malformed_credentials_fail_closed(self): + app.atomic_json(self.path, {"scopes": [app.REQUIRED_SCOPE], "expires_at": 0}) + with self.assertRaisesRegex(app.AppError, "invalid_state"): + app.models(SimpleNamespace(state_dir=self.state), Session()) + + def test_unrotated_refresh_rejected_and_preserved(self): + before = self.path.read_bytes() + response = { + "access_token": "new-access", + "refresh_token": "old-refresh-secret", + "token_type": "Bearer", + "expires_in": 3600, + "scope": app.REQUIRED_SCOPE, + } + with self.assertRaisesRegex(app.AppError, "refresh_not_rotated"): + app.models(SimpleNamespace(state_dir=self.state), Session([Response(response)])) + self.assertEqual(self.path.read_bytes(), before) + + def test_redirect_refused_for_credentials(self): + with self.assertRaisesRegex(app.AppError, "oauth_http_error"): + app.refresh(Session([Response({}, status=302, redirect=True)]), self.path, self.creds) + + def test_lock_symlink_rejected_without_traceback(self): + target = Path(self.temporary.name) / "elsewhere" + target.write_text("safe", encoding="utf-8") + (self.state / "credentials.lock").symlink_to(target) + with self.assertRaisesRegex(app.AppError, "unsafe_state_file"): + app.models(SimpleNamespace(state_dir=self.state), Session()) + + def test_network_timeout_and_output_are_sanitized(self): + secret = "refresh-token-must-not-leak" + self.creds["refresh_token"] = secret + app.atomic_json(self.path, self.creds) + stderr = io.StringIO() + with mock.patch.object(app.requests, "Session", return_value=Session([requests.Timeout(secret)])): + with redirect_stderr(stderr): + result = app.main(["--state-dir", str(self.state), "models"]) + self.assertEqual(result, 1) + self.assertEqual(stderr.getvalue(), "error: network_error\n") + self.assertNotIn(secret, stderr.getvalue()) + + def test_all_credential_requests_disable_redirects_and_have_timeout(self): + response = { + "access_token": "new-access", + "refresh_token": "new-refresh", + "token_type": "Bearer", + "expires_in": 3600, + "scope": app.REQUIRED_SCOPE, + } + session = Session([Response(response)]) + app.refresh(session, self.path, self.creds) + kwargs = session.calls[0][2] + self.assertIs(kwargs["allow_redirects"], False) + self.assertEqual(kwargs["timeout"], app.HTTP_TIMEOUT) + self.assertNotIn("old-refresh-secret", str({k: v for k, v in kwargs.items() if k != "data"})) + + +if __name__ == "__main__": + unittest.main() diff --git a/package/affine-chatgpt/test/test_affine_gateway.py b/package/affine-chatgpt/test/test_affine_gateway.py new file mode 100644 index 00000000..c71e0dec --- /dev/null +++ b/package/affine-chatgpt/test/test_affine_gateway.py @@ -0,0 +1,498 @@ +import http.client +import json +import os +import socket +import subprocess +import sys +import tempfile +import threading +import time +import unittest +from pathlib import Path +from types import SimpleNamespace +from unittest import mock + +import requests + +import affine_chatgpt as auth +import affine_gateway as gateway + + +KEY = "gateway-test-key-0123456789abcdef" +MODEL = "gpt-5.6-luna" + + +def completed_response(output=None): + response = { + "id": "resp_test", + "object": "response", + "status": "completed", + "model": MODEL, + "output": output if output is not None else [{"type": "message", "role": "assistant", "content": [{"type": "output_text", "text": "ok"}]}], + "usage": {"input_tokens": 1, "output_tokens": 1, "total_tokens": 2}, + } + event = json.dumps({"type": "response.completed", "response": response}, separators=(",", ":")) + return response, ("event: response.completed\ndata: " + event + "\n\n").encode() + + +class FakeResponse: + def __init__(self, chunks=(), status=200, data=None, redirect=False, error=None, headers=None): + self.chunks = list(chunks) + self.status_code = status + self.data = data + self.is_redirect = redirect + self.error = error + self.headers = headers if headers is not None else {"Content-Type": "text/event-stream"} + self.closed = False + + def iter_content(self, chunk_size=1): + for chunk in self.chunks: + if isinstance(chunk, Exception): + raise chunk + yield chunk + + def json(self): + if isinstance(self.data, Exception): + raise self.data + return self.data + + def close(self): + self.closed = True + + +class FakeProvider: + def __init__(self, responses=()): + self.responses = list(responses) + self.calls = [] + + def models(self): + self.calls.append("models") + return [(MODEL, "GPT 5.6 Luna")] + + def response(self, body): + self.calls.append(("response", body)) + return self.responses.pop(0) + + +class GatewayCase(unittest.TestCase): + def setUp(self): + self.temporary = tempfile.TemporaryDirectory() + + def tearDown(self): + self.temporary.cleanup() + + def valid(self, **changes): + value = {"model": MODEL, "input": [{"role": "user", "content": "hello"}]} + value.update(changes) + return value + + +class KeyAndNormalizationTests(GatewayCase): + def test_key_requires_owner_only_regular_nonempty_file(self): + path = Path(self.temporary.name) / "key" + path.write_text(KEY + "\n", encoding="utf-8") + path.chmod(0o600) + self.assertEqual(gateway.read_gateway_key(path), KEY) + path.chmod(0o640) + with self.assertRaisesRegex(auth.AppError, "invalid_gateway_key"): + gateway.read_gateway_key(path) + path.unlink() + target = Path(self.temporary.name) / "target" + target.write_text(KEY, encoding="utf-8") + path.symlink_to(target) + with self.assertRaisesRegex(auth.AppError, "invalid_gateway_key"): + gateway.read_gateway_key(path) + + def test_serve_fails_before_listener_without_credentials(self): + path = Path(self.temporary.name) / "key" + path.write_text(KEY, encoding="utf-8") + path.chmod(0o600) + args = SimpleNamespace( + gateway_key_file=path, + state_dir=Path(self.temporary.name) / "state", + host="127.0.0.1", + port=0, + ) + with self.assertRaisesRegex(auth.AppError, "not_authorized"): + gateway.serve(args) + + def test_direct_script_sanitizes_gateway_startup_error(self): + path = Path(self.temporary.name) / "key" + path.write_text(KEY, encoding="utf-8") + path.chmod(0o600) + self.assertIsNotNone(auth.__file__) + script = Path(str(auth.__file__)) + result = subprocess.run( + [ + sys.executable, + str(script), + "--state-dir", + str(Path(self.temporary.name) / "state"), + "serve", + "--gateway-key-file", + str(path), + ], + capture_output=True, + text=True, + timeout=5, + check=False, + ) + self.assertEqual(result.returncode, 1) + self.assertEqual(result.stderr, "error: not_authorized\n") + self.assertNotIn("Traceback", result.stderr) + + def test_normalization_forces_preview_contract_and_strips_sampling(self): + value = self.valid( + stream=False, + temperature=0.1, + max_output_tokens=20, + input=[{"role": "system", "content": [{"type": "input_text", "text": "rules"}]}], + ) + result = gateway.normalize_request(value, {MODEL}) + self.assertEqual(result["input"][0]["role"], "developer") + self.assertIs(result["store"], False) + self.assertIs(result["stream"], True) + self.assertNotIn("temperature", result) + self.assertNotIn("max_output_tokens", result) + + def test_normalization_accepts_boolean_store_and_always_disables_it(self): + for incoming in (True, False): + with self.subTest(store=incoming): + result = gateway.normalize_request(self.valid(store=incoming), {MODEL}) + self.assertIs(result["store"], False) + + def test_flat_function_and_custom_tools_become_namespace(self): + tools = [ + {"type": "function", "name": "artifactRead", "description": "Read", "parameters": {"type": "object"}}, + {"type": "custom", "name": "artifactSearch", "format": {"type": "text"}}, + ] + result = gateway.normalize_request( + self.valid(tools=tools, tool_choice={"type": "function", "name": "artifactRead"}), + {MODEL}, + ) + namespace = result["tools"][0] + self.assertEqual(namespace["type"], "namespace") + self.assertEqual(namespace["name"], "affine") + self.assertEqual([tool["name"] for tool in namespace["tools"]], ["artifactRead", "artifactSearch"]) + self.assertEqual(result["tool_choice"]["namespace"], "affine") + + def test_nested_namespace_validates_function_custom_only(self): + tools = [{"type": "namespace", "name": "affine", "description": "AFFiNE", "tools": [{"type": "function", "name": "artifactRead"}]}] + self.assertEqual(gateway.normalize_request(self.valid(tools=tools), {MODEL})["tools"], tools) + tools[0]["tools"] = [{"type": "web_search"}] + with self.assertRaisesRegex(gateway.GatewayError, "unsupported_tool"): + gateway.normalize_request(self.valid(tools=tools), {MODEL}) + + def test_history_preserves_function_calls_outputs_and_reasoning_ciphertext(self): + history = [ + {"type": "function_call", "id": "fc", "call_id": "call", "name": "artifactRead", "arguments": "{}", "namespace": "affine"}, + {"type": "function_call_output", "call_id": "call", "output": "result"}, + {"type": "reasoning", "id": "rs", "summary": [], "encrypted_content": "ciphertext"}, + ] + result = gateway.normalize_request(self.valid(input=history), {MODEL}) + self.assertEqual(result["input"], history) + + def test_rejects_unknown_model_media_tools_state_and_unknown_fields(self): + cases = [ + (self.valid(model="fake-model"), "model_not_available"), + (self.valid(input=[{"role": "user", "content": [{"type": "input_image", "image_url": "x"}]}]), "unsupported_media"), + (self.valid(tools=[{"type": "code_interpreter"}]), "unsupported_tool"), + (self.valid(previous_response_id="resp"), "unsupported_parameter"), + (self.valid(secret_extension=True), "unsupported_parameter"), + (self.valid(stream="true"), "invalid_stream"), + (self.valid(store="false"), "invalid_store"), + ] + for value, code in cases: + with self.subTest(code=code), self.assertRaisesRegex(gateway.GatewayError, code): + gateway.normalize_request(value, {MODEL}) + + def test_endpoint_allowlist_includes_only_official_response_url(self): + with self.assertRaisesRegex(auth.AppError, "endpoint_not_allowed"): + auth._request(mock.Mock(), "POST", "https://example.invalid/v1/responses") + self.assertEqual(auth.RESPONSES_URL, "https://api.openai.com/v1/responses") + + +class ProviderTests(GatewayCase): + def credentials(self, expires_at=None): + return { + "issuer": auth.ISSUER, + "subject": "subject", + "client_id": "client", + "host_id": "urn:uuid:00000000-0000-4000-8000-000000000000", + "access_token": "old-access-secret", + "refresh_token": "old-refresh-secret", + "id_token": "identity", + "token_type": "Bearer", + "saved_at": "date", + "expires_at": expires_at if expires_at is not None else time.time() + 3600, + "scopes": [auth.REQUIRED_SCOPE], + } + + def test_new_session_ignores_proxy_environment(self): + self.assertIs(gateway.new_session().trust_env, False) + + def test_catalog_filters_and_caches_visible_models(self): + response = FakeResponse(data={"models": [ + {"slug": MODEL, "display_name": "Luna", "visibility": "list"}, + {"slug": "hidden", "display_name": "Hidden", "visibility": "hide"}, + ]}) + session = mock.Mock() + session.request.return_value = response + state = Path(self.temporary.name) / "state" + auth.atomic_json(state / "credentials.json", self.credentials()) + provider = gateway.Provider(state, session=session) + self.assertEqual(provider.models(), [(MODEL, "Luna")]) + self.assertEqual(provider.models(), [(MODEL, "Luna")]) + self.assertEqual(session.request.call_count, 1) + kwargs = session.request.call_args.kwargs + self.assertIs(kwargs["allow_redirects"], False) + + def test_refresh_rotation_under_lock_preserves_identity_token(self): + refreshed = FakeResponse(data={ + "access_token": "new-access", + "refresh_token": "new-refresh", + "token_type": "Bearer", + "expires_in": 3600, + "scope": auth.REQUIRED_SCOPE, + }) + session = mock.Mock() + session.request.return_value = refreshed + state = Path(self.temporary.name) / "state" + auth.atomic_json(state / "credentials.json", self.credentials(expires_at=0)) + provider = gateway.Provider(state, session=session) + self.assertEqual(provider.credentials()["access_token"], "new-access") + saved = auth.read_json(state / "credentials.json") + assert isinstance(saved, dict) + self.assertEqual(saved["refresh_token"], "new-refresh") + self.assertEqual(saved["id_token"], "identity") + + def test_response_transport_has_timeouts_no_redirects_and_sanitizes_network_error(self): + session = mock.Mock() + session.request.side_effect = requests.Timeout("access-secret-must-not-leak") + state = Path(self.temporary.name) / "state" + auth.atomic_json(state / "credentials.json", self.credentials()) + provider = gateway.Provider(state, session=session) + with self.assertRaisesRegex(gateway.GatewayError, "upstream_network_error") as caught: + provider.response({"model": MODEL}) + self.assertNotIn("secret", str(caught.exception)) + kwargs = session.request.call_args.kwargs + self.assertEqual(kwargs["timeout"], (15, 90)) + self.assertIs(kwargs["allow_redirects"], False) + self.assertIs(kwargs["stream"], True) + + +class LoopbackGatewayTests(GatewayCase): + def start_server(self, provider): + server = gateway.GatewayServer(("127.0.0.1", 0), provider, KEY) + thread = threading.Thread(target=server.serve_forever, kwargs={"poll_interval": 0.01}) + thread.start() + self.addCleanup(server.server_close) + self.addCleanup(thread.join, 2) + self.addCleanup(server.shutdown) + return server + + def request(self, server, method, path, body=None, headers=None): + connection = http.client.HTTPConnection("127.0.0.1", server.server_address[1], timeout=2) + encoded = None if body is None else json.dumps(body).encode() + actual = dict(headers or {}) + if encoded is not None: + actual.setdefault("Content-Type", "application/json") + actual.setdefault("Content-Length", str(len(encoded))) + connection.request(method, path, body=encoded, headers=actual) + response = connection.getresponse() + data = response.read() + result = response.status, dict(response.getheaders()), data + connection.close() + return result + + def authorized(self): + return {"Authorization": "Bearer " + KEY} + + def test_unauthorized_request_does_not_parse_or_touch_provider(self): + provider = FakeProvider() + server = self.start_server(provider) + status, _headers, body = self.request( + server, + "POST", + "/v1/responses", + body=b"not-json".decode(), + headers={"Authorization": "Bearer wrong", "Content-Type": "text/plain"}, + ) + self.assertEqual(status, 401) + self.assertEqual(provider.calls, []) + self.assertNotIn(b"not-json", body) + + def test_connections_are_bounded_before_header_parsing(self): + provider = FakeProvider() + server = gateway.GatewayServer(("127.0.0.1", 0), provider, KEY, max_connections=1) + thread = threading.Thread(target=server.serve_forever, kwargs={"poll_interval": 0.01}) + thread.start() + first = socket.create_connection(("127.0.0.1", server.server_address[1]), timeout=2) + deadline = time.time() + 1 + while time.time() < deadline: + if not server.connection_capacity.acquire(blocking=False): + break + server.connection_capacity.release() + time.sleep(0.01) + else: + self.fail("first connection was not admitted") + second = socket.create_connection(("127.0.0.1", server.server_address[1]), timeout=2) + second.settimeout(1) + second.sendall(b"GET /healthz HTTP/1.1\r\nHost: localhost\r\n\r\n") + self.assertEqual(second.recv(1), b"") + second.close() + first.close() + server.shutdown() + thread.join(2) + server.server_close() + + def test_health_and_models_are_minimal_and_no_store(self): + provider = FakeProvider() + server = self.start_server(provider) + status, headers, body = self.request(server, "GET", "/healthz") + self.assertEqual((status, json.loads(body)), (200, {"status": "ready"})) + self.assertEqual(headers["Cache-Control"], "no-store") + status, _headers, body = self.request(server, "GET", "/v1/models", headers=self.authorized()) + self.assertEqual(status, 200) + self.assertEqual(json.loads(body)["data"][0]["id"], MODEL) + + def test_invalid_oversize_and_chunked_bodies_never_reach_provider(self): + provider = FakeProvider() + server = self.start_server(provider) + base = {**self.authorized(), "Content-Type": "text/plain"} + status, _headers, _body = self.request(server, "POST", "/v1/responses", {}, base) + self.assertEqual(status, 415) + raw = socket.create_connection(("127.0.0.1", server.server_address[1]), timeout=2) + raw.sendall(( + "POST /v1/responses HTTP/1.1\r\nHost: localhost\r\n" + f"Authorization: Bearer {KEY}\r\nContent-Type: application/json\r\n" + "Transfer-Encoding: chunked\r\n\r\n2\r\n{}\r\n0\r\n\r\n" + ).encode()) + self.assertIn(b" 400 ", raw.recv(4096)) + raw.close() + malformed = socket.create_connection(("127.0.0.1", server.server_address[1]), timeout=2) + malformed.sendall(( + "POST /v1/responses HTTP/1.1\r\nHost: localhost\r\n" + f"Authorization: Bearer {KEY}\r\nContent-Type: application/json\r\n" + "Content-Length: 7\r\n\r\n{broken" + ).encode()) + self.assertIn(b" 400 ", malformed.recv(4096)) + malformed.close() + headers = {**self.authorized(), "Content-Type": "application/json", "Content-Length": str(gateway.MAX_BODY + 1)} + status, _headers, _body = self.request(server, "POST", "/v1/responses", None, headers) + self.assertEqual(status, 413) + self.assertEqual(provider.calls, []) + + def test_query_endpoint_and_non_sse_upstream_are_rejected(self): + provider = FakeProvider([FakeResponse(headers={"Content-Type": "application/json"})]) + server = self.start_server(provider) + status, _headers, _body = self.request(server, "POST", "/v1/responses?debug=1", self.valid(), self.authorized()) + self.assertEqual(status, 404) + status, _headers, body = self.request(server, "POST", "/v1/responses", self.valid(), self.authorized()) + self.assertEqual(status, 502) + self.assertIn(b"upstream_content_type_invalid", body) + + def test_nonstream_returns_actual_completed_response_with_function_call(self): + output = [{"type": "function_call", "call_id": "call", "name": "artifactRead", "arguments": "{}", "namespace": "affine"}] + expected, event = completed_response(output) + upstream = FakeResponse([event[:19], event[19:]]) + provider = FakeProvider([upstream]) + server = self.start_server(provider) + status, headers, body = self.request(server, "POST", "/v1/responses", self.valid(stream=False), self.authorized()) + self.assertEqual(status, 200) + self.assertEqual(json.loads(body), expected) + self.assertEqual(headers["Cache-Control"], "no-store") + self.assertTrue(upstream.closed) + sent = provider.calls[-1][1] + self.assertIs(sent["stream"], True) + self.assertIs(sent["store"], False) + + def test_missing_upstream_content_type_requires_valid_completed_sse(self): + expected, event = completed_response() + for payload, expected_status in ((event, 200), (b"not an SSE response", 502)): + with self.subTest(expected_status=expected_status): + provider = FakeProvider([FakeResponse([payload], headers={})]) + server = self.start_server(provider) + status, _headers, body = self.request(server, "POST", "/v1/responses", self.valid(stream=False), self.authorized()) + self.assertEqual(status, expected_status) + if status == 200: + self.assertEqual(json.loads(body), expected) + else: + self.assertIn(b"upstream_stream_interrupted", body) + + def test_nonstream_collects_done_items_when_completed_output_is_empty(self): + items = [ + {"type": "message", "role": "assistant", "content": [{"type": "output_text", "text": "OK"}]}, + {"type": "function_call", "call_id": "call", "name": "affine_probe", "arguments": "{}"}, + ] + _response, completed = completed_response([]) + events = [ + ("data: " + json.dumps({"type": "response.output_item.done", "output_index": index, "item": item}) + "\n\n").encode() + for index, item in enumerate(items) + ] + provider = FakeProvider([FakeResponse(events + [completed], headers={})]) + server = self.start_server(provider) + status, _headers, body = self.request(server, "POST", "/v1/responses", self.valid(stream=False), self.authorized()) + self.assertEqual(status, 200) + self.assertEqual(json.loads(body)["output"], items) + + def test_nonstream_failure_and_interruption_are_non_200_sanitized(self): + failed = b'event: response.failed\ndata: {"type":"response.failed","response":{"status":"failed","error":{"message":"private"}}}\n\n' + for upstream in (FakeResponse([failed]), FakeResponse([b"event: response.created\ndata: {\"type\":\"response.created\"}\n\n"])): + with self.subTest(chunks=upstream.chunks): + provider = FakeProvider([upstream]) + server = self.start_server(provider) + status, _headers, body = self.request(server, "POST", "/v1/responses", self.valid(), self.authorized()) + self.assertEqual(status, 502) + self.assertNotIn(b"private", body) + + def test_stream_relays_complete_failure_and_interruption_without_fake_success(self): + _response, completed = completed_response() + failed = b'event: response.failed\ndata: {"type":"response.failed","response":{"status":"failed"}}\n\n' + interrupted = b'event: response.output_text.delta\ndata: {"type":"response.output_text.delta","delta":"x"}\n\n' + for payload, expected in ((completed, b"response.completed"), (failed, b"response.failed"), (interrupted, b"upstream_stream_interrupted")): + with self.subTest(expected=expected): + provider = FakeProvider([FakeResponse([payload])]) + server = self.start_server(provider) + status, headers, body = self.request(server, "POST", "/v1/responses", self.valid(stream=True), self.authorized()) + self.assertEqual(status, 200) + self.assertEqual(headers["Content-Type"], "text/event-stream") + self.assertIn(expected, body) + if expected != b"response.completed": + self.assertNotIn(b"response.completed", body) + + def test_upstream_status_and_allowlisted_code_preserved_without_body_reflection(self): + upstream = FakeResponse(status=429, data={"error": {"code": "rate_limit_exceeded", "message": "private account detail"}}) + provider = FakeProvider([upstream]) + server = self.start_server(provider) + status, _headers, body = self.request(server, "POST", "/v1/responses", self.valid(), self.authorized()) + self.assertEqual(status, 429) + self.assertIn(b"rate_limit_exceeded", body) + self.assertNotIn(b"private account detail", body) + + def test_stream_disconnect_closes_upstream(self): + class Endless(FakeResponse): + def iter_content(self, chunk_size=1): + for _index in range(10000): + yield b'event: response.output_text.delta\ndata: {"type":"response.output_text.delta","delta":"xxxxxxxxxxxxxxxx"}\n\n' + time.sleep(0.001) + + upstream = Endless() + provider = FakeProvider([upstream]) + server = self.start_server(provider) + connection = socket.create_connection(("127.0.0.1", server.server_address[1]), timeout=2) + body = json.dumps(self.valid(stream=True)).encode() + connection.sendall(( + "POST /v1/responses HTTP/1.1\r\nHost: localhost\r\n" + f"Authorization: Bearer {KEY}\r\nContent-Type: application/json\r\nContent-Length: {len(body)}\r\n\r\n" + ).encode() + body) + connection.recv(512) + connection.close() + deadline = time.time() + 2 + while not upstream.closed and time.time() < deadline: + time.sleep(0.01) + self.assertTrue(upstream.closed) + + +if __name__ == "__main__": + unittest.main() diff --git a/package/affine/byok-model-picker.patch b/package/affine/byok-model-picker.patch new file mode 100644 index 00000000..2e9c1958 --- /dev/null +++ b/package/affine/byok-model-picker.patch @@ -0,0 +1,238 @@ +diff --git a/packages/frontend/core/src/blocksuite/ai/components/ai-chat-input/ai-chat-input.ts b/packages/frontend/core/src/blocksuite/ai/components/ai-chat-input/ai-chat-input.ts +--- a/packages/frontend/core/src/blocksuite/ai/components/ai-chat-input/ai-chat-input.ts ++++ b/packages/frontend/core/src/blocksuite/ai/components/ai-chat-input/ai-chat-input.ts +@@ -860,7 +860,7 @@ + control: this.trackOptions?.control, + reasoning: this._isReasoningActive, + toolsConfig: this.aiToolsConfigService.config.value, +- routeTargetId: this.aiModelService.modelId.value, ++ ...this.aiModelService.getSelection(), + userInfo: { + userId: userInfo?.id, + userName: userInfo?.name, +diff --git a/packages/frontend/core/src/blocksuite/ai/runtime/chat/runtime.ts b/packages/frontend/core/src/blocksuite/ai/runtime/chat/runtime.ts +--- a/packages/frontend/core/src/blocksuite/ai/runtime/chat/runtime.ts ++++ b/packages/frontend/core/src/blocksuite/ai/runtime/chat/runtime.ts +@@ -30,6 +30,10 @@ + private createSessionPromise: Promise< + CopilotChatHistoryFragment | null | undefined + > | null = null; ++ private readonly sessionSelections = new Map< ++ string, ++ Pick ++ >(); + private snapshot: AIChatSnapshot; + + constructor(private readonly options: RuntimeOptions) { +@@ -69,6 +73,7 @@ + this.createSessionPromise = null; + this.createSessionPromiseKey = null; + this.streamAbortController?.abort(); ++ this.sessionSelections.clear(); + this.listeners.clear(); + } + +@@ -389,6 +394,10 @@ + this.updateScopeSelection({ syncing: false }); + } + ++ const selection = options.profileId && options.modelId ++ ? { profileId: options.profileId, modelId: options.modelId } ++ : { routeTargetId: options.routeTargetId ?? this.snapshot.composer.routeTargetId }; ++ this.sessionSelections.set(session.sessionId, selection); + const stream = (await this.options.request.executeAction('chat', { + workspaceId: this.snapshot.scope.workspaceId, + docId: +@@ -407,8 +416,7 @@ + ], + reasoning: options.reasoning ?? this.snapshot.composer.reasoning, + toolsConfig: options.toolsConfig ?? this.snapshot.composer.toolsConfig, +- routeTargetId: +- options.routeTargetId ?? this.snapshot.composer.routeTargetId, ++ ...selection, + isRootSession: options.isRootSession, + where: options.where, + control: options.control, +@@ -474,6 +482,7 @@ + workspaceId: this.snapshot.scope.workspaceId, + sessionId: this.snapshot.activeSessionId, + liveEditorContext, ++ ...this.sessionSelections.get(this.snapshot.activeSessionId), + retry: true, + stream: true, + signal: this.streamAbortController.signal, +diff --git a/packages/frontend/core/src/blocksuite/ai/runtime/chat/actions.ts b/packages/frontend/core/src/blocksuite/ai/runtime/chat/actions.ts +--- a/packages/frontend/core/src/blocksuite/ai/runtime/chat/actions.ts ++++ b/packages/frontend/core/src/blocksuite/ai/runtime/chat/actions.ts +@@ -16,6 +16,8 @@ + reasoning?: boolean; + toolsConfig?: unknown; + routeTargetId?: string; ++ profileId?: string; ++ modelId?: string; + userInfo?: { + userId?: string; + userName?: string; +diff --git a/packages/frontend/core/src/modules/ai-button/services/models.ts b/packages/frontend/core/src/modules/ai-button/services/models.ts +--- a/packages/frontend/core/src/modules/ai-button/services/models.ts ++++ b/packages/frontend/core/src/modules/ai-button/services/models.ts +@@ -1,4 +1,7 @@ +-import { getCopilotRouteOptionsQuery } from '@affine/graphql'; ++import { ++ getCopilotRouteOptionsQuery, ++ workspaceByokSettingsQuery, ++} from '@affine/graphql'; + import { signal } from '@preact/signals-core'; + import { Service } from '@toeverything/infra'; + +@@ -13,7 +16,24 @@ + category: string; + version: string; + available: boolean; ++ profileId?: string; ++ modelId?: string; + } ++ ++export type AIModelSelection = ++ | { routeTargetId?: undefined; profileId?: undefined; modelId?: undefined } ++ | { routeTargetId: string; profileId?: undefined; modelId?: undefined } ++ | { routeTargetId?: undefined; profileId: string; modelId: string }; ++ ++const isPermissionDenied = (error: unknown) => ++ typeof error === 'object' && ++ error !== null && ++ 'isStatus' in error && ++ typeof error.isStatus === 'function' && ++ error.isStatus(403); ++ ++const supportsText = (capability: { input: string[]; output: string[] }) => ++ capability.input.includes('text') && capability.output.includes('text'); + + export class AIModelService extends Service { + readonly modelId = signal(undefined); +@@ -31,7 +51,9 @@ export class AIModelService extends Service { + super(); + const subscription = subscriptionService.subscription.ai$.subscribe(() => { + if (this.workspaceId && this.routeId) { +- this.load(this.workspaceId, this.routeId).catch(console.error); ++ this.load(this.workspaceId, this.routeId).catch(() => ++ console.error('Failed to load AI models') ++ ); + } + }); + this.disposables.push(() => subscription.unsubscribe()); +@@ -43,13 +65,26 @@ export class AIModelService extends Service { + this.routeId = routeId; + this.models.value = []; + this.modelId.value = undefined; +- this.load(workspaceId, routeId).catch(console.error); ++ this.load(workspaceId, routeId).catch(() => ++ console.error('Failed to load AI models') ++ ); + } + + resetModel() { + this.setModel(undefined); + } + ++ getSelection(): AIModelSelection { ++ const model = this.models.value.find( ++ candidate => candidate.id === this.modelId.value && candidate.available ++ ); ++ if (!model) return {}; ++ if (model.profileId && model.modelId) { ++ return { profileId: model.profileId, modelId: model.modelId }; ++ } ++ return { routeTargetId: model.id }; ++ } ++ + setModel(modelId: string | undefined) { + if (!this.workspaceId || !this.routeId) return; + if ( +@@ -67,18 +102,42 @@ + + private async load(workspaceId: string, routeId: string) { + const requestId = ++this.requestId; +- const result = await this.gqlService.gql({ +- query: getCopilotRouteOptionsQuery, +- variables: { promptName: routeId }, +- }); ++ const to = new Date(); ++ const from = new Date(to.getTime()); ++ from.setDate(from.getDate() - 30); ++ const [managedResponse, byokResponse] = await Promise.allSettled([ ++ this.gqlService.gql({ ++ query: getCopilotRouteOptionsQuery, ++ variables: { promptName: routeId }, ++ }), ++ this.gqlService ++ .gql({ ++ query: workspaceByokSettingsQuery, ++ variables: { ++ id: workspaceId, ++ from: from.toISOString(), ++ to: to.toISOString(), ++ }, ++ }) ++ .catch(error => { ++ if (isPermissionDenied(error)) return undefined; ++ throw error; ++ }), ++ ]); + if (requestId !== this.requestId) return; +- const options = result.currentUser?.copilot?.routeOptions; +- if (!options) { +- this.models.value = []; +- this.modelId.value = undefined; +- return; +- } +- this.models.value = options.choices.map(choice => { ++ if (byokResponse.status === 'rejected') { ++ console.error('Failed to load workspace BYOK models'); ++ throw byokResponse.reason; ++ } ++ if (managedResponse.status === 'rejected') { ++ console.error('Failed to load managed AI models'); ++ } ++ const managedResult = ++ managedResponse.status === 'fulfilled' ? managedResponse.value : undefined; ++ const byokResult = ++ byokResponse.status === 'fulfilled' ? byokResponse.value : undefined; ++ const options = managedResult?.currentUser?.copilot?.routeOptions; ++ const managedModels = options?.choices.map(choice => { + const [category] = choice.displayName.split(' '); + return { + id: choice.id, +@@ -87,7 +146,31 @@ + version: choice.displayName.slice(category.length + 1), + available: choice.available, + }; +- }); ++ }) ?? []; ++ const settings = byokResult?.workspace?.byokSettings; ++ const byokModels = ++ settings?.serverEntitled && settings.policy.enabled ++ ? settings.profiles.flatMap(profile => { ++ if ( ++ !profile.enabled || ++ !settings.policy.allowedProviders.includes(profile.provider) ++ ) { ++ return []; ++ } ++ return profile.definition.models ++ .filter(model => model.enabled && model.capabilities.some(supportsText)) ++ .map(model => ({ ++ id: `byok:${profile.profileId}:${encodeURIComponent(model.modelId)}`, ++ name: model.modelId, ++ category: model.modelId, ++ version: profile.name, ++ available: true, ++ profileId: profile.profileId, ++ modelId: model.modelId, ++ })); ++ }) ++ : []; ++ this.models.value = [...managedModels, ...byokModels]; + const selected = this.globalStateService.globalState.get( + this.storageKey(workspaceId, routeId) + ); diff --git a/package/affine/default.nix b/package/affine/default.nix index 0c6c5314..874dc5ff 100644 --- a/package/affine/default.nix +++ b/package/affine/default.nix @@ -14,7 +14,7 @@ openssl, inputs, system, - frontendPatches ? [ ./gitea-document-typography.patch ], + frontendPatches ? [ ./gitea-document-typography.patch ./byok-model-picker.patch ], }: let @@ -151,7 +151,7 @@ let runHook postConfigure ''; - frontend = stdenv.mkDerivation { + frontend = stdenv.mkDerivation ({ pname = "affine-frontend"; inherit version src yarnOfflineCache; missingHashes = ./missing-hashes.json; @@ -188,13 +188,20 @@ let cp -R packages/frontend/apps/mobile/dist "$out/mobile" runHook postInstall ''; - }; + } // lib.optionalAttrs (builtins.elem ./byok-model-picker.patch frontendPatches) { + doCheck = true; + checkPhase = '' + runHook preCheck + AFFINE_SOURCE_DIR="$PWD" ${nodejs}/bin/node ${../../test/package/affine/test/model-picker.cjs} + runHook postCheck + ''; + }); frontendStatic = runCommand "affine-frontend-static-${version}" { inherit version; passthru = { inherit revision; }; meta = { - description = "Source-built AFFiNE web assets with document typography patches"; + description = "Source-built AFFiNE web assets with typography and BYOK model selection"; license = [ lib.licenses.mit lib.licenses.mpl20 ]; platforms = [ "x86_64-linux" ]; }; diff --git a/package/default.nix b/package/default.nix index 66a9f372..0743507a 100644 --- a/package/default.nix +++ b/package/default.nix @@ -150,6 +150,7 @@ in { deploy = pkgs.callPackage ./deploy { inherit inputs; }; element-web = pkgs.callPackage ./element-web { pnpm = giteaPkgs.pnpm_10; }; shellplot = pkgs.callPackage ./shellplot {}; + affine-chatgpt = pkgs.callPackage ./affine-chatgpt {}; gitea-kanban-tui = pkgs.callPackage ./gitea-kanban-tui rust.commonArgs; routine-server = pkgs.callPackage ./routine-server rust.commonArgs; routine-tui = pkgs.callPackage ./routine-tui rust.commonArgs; diff --git a/test/nixos/affine-chatgpt.nix b/test/nixos/affine-chatgpt.nix new file mode 100644 index 00000000..861636b6 --- /dev/null +++ b/test/nixos/affine-chatgpt.nix @@ -0,0 +1,56 @@ +{ system, inputs, pkgs, ... }: +pkgs.lib.optionalAttrs (system == "x86_64-linux") (let + lib = inputs.nixpkgs.lib; + fakePackage = pkgs.writeShellScriptBin "affine-chatgpt" "exit 0"; + mkSystem = enabled: (lib.nixosSystem { + inherit system; + modules = [ + (import ../../nixos/module/hectic/service/affine-chatgpt.nix {}) + { + system.stateVersion = "26.05"; + hectic.services.affine-chatgpt = { enable = enabled; package = fakePackage; }; + } + ]; + }).config; + cfg = mkSystem true; + disabledCfg = mkSystem false; + app = cfg.systemd.services.affine-chatgpt; + hostCfg = (lib.nixosSystem { + inherit system; + modules = [ + (import ../../nixos/module/hectic/service/affine-chatgpt.nix {}) + (import ../../nixos/module/hectic/service/affine.nix { inherit inputs; flake = ../..; }) + ../../nixos/system/hectic-lab/affine-chatgpt.nix + { + system.stateVersion = "26.05"; + hectic.services.affine = { + enable = true; + package = fakePackage; + environmentFile = "/run/secrets/affine-test.env"; + }; + hectic.services.affine-chatgpt.package = fakePackage; + } + ]; + }).config; +in { + affine-chatgpt-module = + assert !(disabledCfg.systemd.services ? affine-chatgpt); + assert cfg.users.users.affine-chatgpt.isSystemUser; + assert app.serviceConfig.User == "affine-chatgpt"; + assert app.serviceConfig.Group == "affine-chatgpt"; + assert app.serviceConfig.Type == "simple"; + assert app.serviceConfig.StateDirectoryMode == "0700"; + assert lib.hasSuffix "--gateway-key-file /var/lib/affine-chatgpt/gateway-key" app.serviceConfig.ExecStart; + assert app.unitConfig.ConditionPathExists == "/var/lib/affine-chatgpt/session/credentials.json"; + assert lib.hasInfix "serve --host 127.0.0.1 --port 3012" app.serviceConfig.ExecStart; + assert app.serviceConfig.NoNewPrivileges; + assert app.serviceConfig.ProtectSystem == "strict"; + assert !(cfg.systemd.services ? affine); + assert !cfg.virtualisation.docker.enable; + assert cfg.networking.firewall.allowedTCPPorts == []; + assert hostCfg.hectic.services.affine-chatgpt.enable; + assert lib.elem "affine-chatgpt.service" hostCfg.systemd.services.affine-native.wants; + assert lib.elem "affine-chatgpt.service" hostCfg.systemd.services.affine-native.after; + assert lib.hasInfix "serve --host 127.0.0.1 --port 3012" hostCfg.systemd.services.affine-chatgpt.serviceConfig.ExecStart; + pkgs.runCommand "affine-chatgpt-module" {} ''touch "$out"''; +}) diff --git a/test/nixos/affine-frontend.nix b/test/nixos/affine-frontend.nix index 8a001732..00e36f31 100644 --- a/test/nixos/affine-frontend.nix +++ b/test/nixos/affine-frontend.nix @@ -1,52 +1,5 @@ -{ system, inputs, pkgs, ... }: -pkgs.lib.optionalAttrs (system == "x86_64-linux") (let - lib = inputs.nixpkgs.lib; - revision = "b4c8548c09da21b2898443559a5b846f0ccf5dd8"; - mkSystem = version: sourceRevision: lib.nixosSystem { - inherit system; - modules = [ - (import ../../nixos/system/hectic-lab/affine.nix { domain = "example.test"; }) - { - system.stateVersion = "26.05"; - nixpkgs.overlays = [ (_: _: { - hectic.affine-frontend-static = pkgs.runCommand "affine-static-test" { - inherit version; - passthru.revision = sourceRevision; - } ''mkdir -p "$out"''; - }) ]; - } - ]; - }; - cfg = (mkSystem "0.27.4" revision).config; - mismatchedCfg = (mkSystem "0.27.5" revision).config; - mismatchedRevisionCfg = (mkSystem "0.27.4" "different-source").config; - main = cfg.systemd.services.affine; - frontend = cfg.systemd.services.affine-frontend; -in { - affine-frontend-module = - assert frontend.requires == [ "affine.service" ]; - assert frontend.after == [ "affine.service" ]; - assert frontend.partOf == [ "affine.service" ]; - assert frontend.reloadIfChanged; - assert !frontend.restartIfChanged; - assert frontend.serviceConfig.Type == "oneshot"; - assert frontend.serviceConfig.RemainAfterExit; - assert frontend.serviceConfig.ExecStart == frontend.serviceConfig.ExecReload; - assert lib.hasInfix "affine-frontend-compose.yaml up --detach --no-deps --force-recreate affine" frontend.serviceConfig.ExecStart; - assert frontend.serviceConfig.ExecStop == lib.replaceStrings - [ " up --detach --wait" ] [ " up --detach --no-deps --force-recreate affine" ] main.serviceConfig.ExecStart; - assert lib.hasSuffix "affine-compose.yaml up --detach --wait" main.serviceConfig.ExecStart; - assert lib.hasSuffix "affine-compose.yaml down" main.serviceConfig.ExecStop; - assert !lib.hasInfix "affine-frontend-compose.yaml" main.serviceConfig.ExecStart; - assert cfg.services.nginx.virtualHosts."affine.example.test".locations."/".proxyPass == "http://127.0.0.1:3010"; - assert !(cfg.systemd.services ? affine-native); - assert lib.any (check: - check.message == "AFFiNE frontend assets and the deployed backend image must use the same release." && - !check.assertion - ) mismatchedCfg.assertions; - assert lib.any (check: - check.message == "AFFiNE frontend source revision must match the pinned 0.27.4 backend." && - !check.assertion - ) mismatchedRevisionCfg.assertions; - pkgs.runCommand "affine-frontend-module" {} ''touch "$out"''; -}) +args: let + checks = import ./affine-production.nix args; +in checks // args.pkgs.lib.optionalAttrs (checks ? affine-production) { + affine-frontend-module = checks.affine-production; +} diff --git a/test/nixos/affine-production.nix b/test/nixos/affine-production.nix new file mode 100644 index 00000000..0437c6c4 --- /dev/null +++ b/test/nixos/affine-production.nix @@ -0,0 +1,136 @@ +{ system, inputs, pkgs, ... }: +pkgs.lib.optionalAttrs (system == "x86_64-linux") (let + lib = inputs.nixpkgs.lib; + environmentFile = "/var/lib/affine-native/environment"; + fakePackage = pkgs.runCommand "affine-production-test-package" { + pname = "affine"; + version = "0.27.4"; + passthru.frontendStatic.revision = "b4c8548c09da21b2898443559a5b846f0ccf5dd8"; + } '' + mkdir -p "$out/bin" + touch "$out/bin/affine-server" "$out/bin/affine-migrate" + chmod +x "$out/bin/affine-server" "$out/bin/affine-migrate" + ''; + fakeFrontend = pkgs.runCommand "affine-production-test-frontend" { + version = "0.27.4"; + passthru.revision = "b4c8548c09da21b2898443559a5b846f0ccf5dd8"; + } '' + mkdir -p "$out" + ''; + mkConfig = deploymentConfig: (lib.nixosSystem { + inherit system; + modules = [ + (import ../../nixos/module/hectic/service/affine.nix { + inherit inputs; + flake = ../..; + }) + (import ../../nixos/system/hectic-lab/affine.nix { domain = "example.test"; }) + { + system.stateVersion = "26.05"; + hectic.services.affine.package = fakePackage; + nixpkgs.overlays = [ (_: _: { + hectic.affine-frontend-static = fakeFrontend; + }) ]; + } + deploymentConfig + ]; + }).config; + cfg = mkConfig { + hectic.affineDeployment.nativeActive = true; + }; + stagingCfg = mkConfig {}; + app = cfg.systemd.services.affine-native; + migrate = cfg.systemd.services.affine-native-migrate; + postgres = cfg.systemd.services.affine-postgresql; + redis = cfg.services.redis.servers.affine; + vector = builtins.head postgres.restartTriggers; +in { + affine-production = + assert cfg.hectic.affineDeployment.nativeActive; + assert cfg.hectic.services.affine.enable; + assert cfg.hectic.services.affine.package == fakePackage; + assert cfg.hectic.services.affine.frontendPackage == fakeFrontend; + assert cfg.hectic.services.affine.externalUrl == "https://affine.example.test"; + assert cfg.hectic.services.affine.serverName == "Hectic AFFiNE"; + assert cfg.hectic.services.affine.address == "127.0.0.1"; + assert cfg.hectic.services.affine.port == 3011; + assert cfg.hectic.services.affine.redisHost == "127.0.0.1"; + assert cfg.hectic.services.affine.redisPort == 6388; + assert cfg.hectic.services.affine.environmentFile == environmentFile; + assert !cfg.hectic.services.affine.settings.auth.allowSignup; + assert !cfg.hectic.services.affine.settings.auth.allowSignupForOauth; + assert cfg.hectic.services.affine.settings.auth.newAccountShareActionDelay == 0; + assert !cfg.hectic.services.affine.settings.copilot.enabled; + assert cfg.users.users.affine-native.home == "/var/lib/affine-native"; + assert app.serviceConfig.User == "affine-native"; + assert app.serviceConfig.StateDirectory == "affine-native"; + assert app.serviceConfig.MemoryMax == "2G"; + assert app.serviceConfig.BindReadOnlyPaths == [ + "${fakeFrontend}:${fakePackage}/share/affine/static" + ]; + assert lib.elem fakeFrontend app.restartTriggers; + assert app.unitConfig.ConditionPathExists == environmentFile; + assert !(cfg.systemd.services ? affine); + assert !(cfg.systemd.services ? affine-frontend); + assert !(cfg.systemd.services ? affine-bootstrap); + assert !cfg.services.postgresql.enable; + assert cfg.users.users.affine-postgres.home == "/var/lib/affine-postgresql"; + assert postgres.serviceConfig.User == "affine-postgres"; + assert postgres.serviceConfig.StateDirectory == "affine-postgresql"; + assert postgres.serviceConfig.RuntimeDirectory == "affine-postgresql"; + assert postgres.serviceConfig.RuntimeDirectoryMode == "0755"; + assert postgres.serviceConfig.MemoryMax == "512M"; + assert lib.versions.major postgres.environment.POSTGRESQL_VERSION == "16"; + assert lib.hasInfix "/bin/postgres" postgres.serviceConfig.ExecStart; + assert lib.hasInfix "-D /var/lib/affine-postgresql" postgres.serviceConfig.ExecStart; + assert lib.hasInfix "-k /run/affine-postgresql" postgres.serviceConfig.ExecStart; + assert lib.hasInfix "-p 5433" postgres.serviceConfig.ExecStart; + assert lib.hasInfix "listen_addresses=" postgres.serviceConfig.ExecStart; + assert lib.hasInfix "--auth-local=peer" postgres.preStart; + assert lib.hasInfix "--locale=en_US.utf8" postgres.preStart; + assert lib.hasInfix "host all all 0.0.0.0/0 reject" postgres.preStart; + assert lib.hasInfix "CREATE ROLE \"affine-native\" LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE" postgres.postStart; + assert lib.hasInfix "CREATE EXTENSION IF NOT EXISTS vector" postgres.postStart; + assert lib.hasInfix "CREATE EXTENSION IF NOT EXISTS pgcrypto" postgres.postStart; + assert vector.version == "0.8.7"; + assert vector.src.rev == "v0.8.7"; + assert redis.enable; + assert redis.bind == "127.0.0.1"; + assert redis.port == 6388; + assert redis.settings.maxmemory == "96mb"; + assert redis.settings.maxmemory-policy == "noeviction"; + assert cfg.systemd.services.redis-affine.serviceConfig.MemoryMax == "128M"; + assert lib.elem "affine-postgresql.service" migrate.after; + assert lib.elem "redis-affine.service" migrate.after; + assert migrate.requires == [ "affine-postgresql.service" "redis-affine.service" ]; + assert migrate.unitConfig.ConditionPathExists == environmentFile; + assert !(migrate.serviceConfig ? BindReadOnlyPaths); + assert !(lib.elem fakeFrontend migrate.restartTriggers); + assert !(lib.elem fakeFrontend postgres.restartTriggers); + assert !(lib.elem fakeFrontend cfg.systemd.services.redis-affine.restartTriggers); + assert !(lib.elem "postgresql.service" migrate.after); + assert cfg.services.nginx.virtualHosts."affine.example.test".locations."/".proxyPass == "http://127.0.0.1:3011"; + assert cfg.services.nginx.virtualHosts."affine.example.test".locations."/".proxyWebsockets; + assert lib.hasInfix "client_max_body_size 100m" cfg.services.nginx.virtualHosts."affine.example.test".extraConfig; + assert !cfg.virtualisation.docker.enable; + assert !stagingCfg.hectic.affineDeployment.nativeActive; + assert stagingCfg.systemd.services ? affine; + assert stagingCfg.systemd.services ? affine-frontend; + assert stagingCfg.systemd.services ? affine-bootstrap; + assert stagingCfg.systemd.services ? affine-native; + assert stagingCfg.systemd.services ? affine-native-migrate; + assert stagingCfg.systemd.services ? affine-postgresql; + assert stagingCfg.services.redis.servers.affine.enable; + assert stagingCfg.systemd.services.affine-native.unitConfig.ConditionPathExists == environmentFile; + assert stagingCfg.hectic.services.affine.frontendPackage == fakeFrontend; + assert stagingCfg.systemd.services.affine-native.serviceConfig.BindReadOnlyPaths == [ + "${fakeFrontend}:${fakePackage}/share/affine/static" + ]; + assert !(lib.elem fakeFrontend stagingCfg.systemd.services.affine-native-migrate.restartTriggers); + assert stagingCfg.systemd.services.affine-native-migrate.unitConfig.ConditionPathExists == environmentFile; + assert stagingCfg.services.nginx.virtualHosts."affine.example.test".locations."/".proxyPass == "http://127.0.0.1:3010"; + assert lib.hasInfix "affine-compose.yaml up --detach --wait" stagingCfg.systemd.services.affine.serviceConfig.ExecStart; + pkgs.runCommand "affine-production" {} '' + touch "$out" + ''; +}) diff --git a/test/nixos/affine.nix b/test/nixos/affine.nix index da30bb12..6226b18c 100644 --- a/test/nixos/affine.nix +++ b/test/nixos/affine.nix @@ -6,6 +6,37 @@ let touch "$out/bin/affine-server" "$out/bin/affine-migrate" chmod +x "$out/bin/affine-server" "$out/bin/affine-migrate" ''; + revision = "b4c8548c09da21b2898443559a5b846f0ccf5dd8"; + fakeVersionedPkg = pkgs.runCommand "affine-versioned-test-package" { + version = "0.27.4"; + passthru.frontendStatic = { inherit revision; }; + } '' + mkdir -p "$out/bin" "$out/share/affine/static" + touch "$out/bin/affine-server" "$out/bin/affine-migrate" + ''; + fakeFrontend = pkgs.runCommand "affine-test-frontend" { + version = "0.27.4"; + passthru = { inherit revision; }; + } '' + mkdir -p "$out" + ''; + fakeWrongVersionFrontend = fakeFrontend.overrideAttrs (_: { + version = "0.27.5"; + }); + fakeWrongRevisionFrontend = fakeFrontend.overrideAttrs (_: { + passthru.revision = "wrong-revision"; + }); + fakeMissingRevisionFrontend = fakeFrontend.overrideAttrs (_: { + passthru = {}; + }); + fakeMissingVersionFrontend = pkgs.runCommand "affine-test-frontend-without-version" { + passthru = { inherit revision; }; + } '' + mkdir -p "$out" + ''; + fakeMissingBackendRevision = fakeVersionedPkg.overrideAttrs (_: { + passthru.frontendStatic = {}; + }); environmentFile = "/run/secrets/affine-native.env"; mkSystemFor = targetSystem: module: lib.nixosSystem { @@ -28,6 +59,32 @@ let }).config; app = enabledCfg.systemd.services.affine-native; migrate = enabledCfg.systemd.services.affine-native-migrate; + frontendCfg = (mkSystem { + hectic.services.affine = { + enable = true; + package = fakeVersionedPkg; + frontendPackage = fakeFrontend; + inherit environmentFile; + }; + }).config; + frontendApp = frontendCfg.systemd.services.affine-native; + frontendMigrate = frontendCfg.systemd.services.affine-native-migrate; + mkFrontendCfg = package: frontendPackage: (mkSystem { + hectic.services.affine = { + enable = true; + inherit package frontendPackage environmentFile; + }; + }).config; + wrongVersionCfg = mkFrontendCfg fakeVersionedPkg fakeWrongVersionFrontend; + wrongRevisionCfg = mkFrontendCfg fakeVersionedPkg fakeWrongRevisionFrontend; + missingFrontendRevisionCfg = mkFrontendCfg fakeVersionedPkg fakeMissingRevisionFrontend; + missingFrontendVersionCfg = mkFrontendCfg fakeVersionedPkg fakeMissingVersionFrontend; + missingBackendRevisionCfg = mkFrontendCfg fakeMissingBackendRevision fakeFrontend; + missingBackendVersionCfg = mkFrontendCfg fakePkg fakeFrontend; + versionMessage = "hectic.services.affine.frontendPackage version must match hectic.services.affine.package version."; + revisionMessage = "hectic.services.affine.frontendPackage revision must be a non-empty string matching package.frontendStatic.revision."; + assertionFor = message: cfg: + (lib.findFirst (check: check.message == message) null cfg.assertions).assertion; defaultPackageCfg = (mkSystem { nixpkgs.config.allowUnfreePredicate = package: builtins.elem (lib.getName package) [ "affine" "affine-server-native" ]; @@ -78,12 +135,27 @@ in { assert app.serviceConfig.EnvironmentFile == environmentFile; assert app.serviceConfig.StateDirectory == "affine-native"; assert app.serviceConfig.StateDirectoryMode == "0700"; + assert app.serviceConfig.BindReadOnlyPaths == []; assert lib.hasInfix "/var/lib/affine-native/.affine/config" app.preStart; assert lib.hasInfix "/var/lib/affine-native/.affine/storage" app.preStart; assert !(enabledCfg.systemd.services ? affine); assert !enabledCfg.virtualisation.docker.enable; assert !enabledCfg.services.postgresql.enable; assert enabledCfg.services.redis.servers == {}; + assert frontendApp.serviceConfig.BindReadOnlyPaths == [ + "${fakeFrontend}:${fakeVersionedPkg}/share/affine/static" + ]; + assert lib.elem fakeFrontend frontendApp.restartTriggers; + assert !(lib.elem fakeFrontend frontendMigrate.restartTriggers); + assert !(frontendMigrate.serviceConfig ? BindReadOnlyPaths); + assert assertionFor versionMessage frontendCfg; + assert assertionFor revisionMessage frontendCfg; + assert !(assertionFor versionMessage wrongVersionCfg); + assert !(assertionFor revisionMessage wrongRevisionCfg); + assert !(assertionFor revisionMessage missingFrontendRevisionCfg); + assert !(assertionFor revisionMessage missingBackendRevisionCfg); + assert !(assertionFor versionMessage missingFrontendVersionCfg); + assert !(assertionFor versionMessage missingBackendVersionCfg); assert defaultPackageCfg.hectic.services.affine.package.pname == "affine"; assert builtins.isString defaultPackageCfg.hectic.services.affine.package.drvPath; # Nixpkgs explicitly lets NIXPKGS_ALLOW_UNFREE override its configuration. diff --git a/test/nixos/default.nix b/test/nixos/default.nix index eb835fd8..10e5c98b 100644 --- a/test/nixos/default.nix +++ b/test/nixos/default.nix @@ -34,6 +34,7 @@ let }; }).config; in (import ./affine.nix { inherit system inputs self pkgs; }) // + (import ./affine-chatgpt.nix { inherit system inputs pkgs; }) // (import ./affine-frontend.nix { inherit system inputs pkgs; }) // { p4d-module-basic = assert enabledCfg.users.users.p4d.isSystemUser; diff --git a/test/package/affine/default.nix b/test/package/affine/default.nix index 666b3c10..8220d2c8 100644 --- a/test/package/affine/default.nix +++ b/test/package/affine/default.nix @@ -17,6 +17,10 @@ let touch "$out" ''; in pkgs.lib.optionalAttrs (system == "x86_64-linux") { + affine-model-picker = pkgs.runCommand "affine-model-picker" {} '' + test -s ${self.packages.${system}.affine-frontend-static}/index.html + touch "$out" + ''; affine-runtime = check "affine-runtime" {}; affine-typography = check "affine-typography" { nativeBuildInputs = runtimeInputs ++ [ pkgs.playwright-driver ]; diff --git a/test/package/affine/test/model-picker.cjs b/test/package/affine/test/model-picker.cjs new file mode 100644 index 00000000..8e93ad00 --- /dev/null +++ b/test/package/affine/test/model-picker.cjs @@ -0,0 +1,263 @@ +#!/usr/bin/env node +'use strict'; + +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const path = require('node:path'); +const Module = require('node:module'); + +const sourceDir = path.resolve(process.env.AFFINE_SOURCE_DIR || process.argv[2] || '.'); +const typescript = require(path.join(sourceDir, 'node_modules/typescript')); + +function signal(value) { + return { value }; +} + +class Service { + constructor() { + this.disposables = []; + } +} + +function loadTypeScript(relativePath, mocks) { + const filename = path.join(sourceDir, relativePath); + const source = fs.readFileSync(filename, 'utf8'); + const output = typescript.transpileModule(source, { + compilerOptions: { + module: typescript.ModuleKind.CommonJS, + target: typescript.ScriptTarget.ES2022, + }, + }).outputText; + const mod = new Module(filename); + mod.filename = filename; + mod.paths = Module._nodeModulePaths(path.dirname(filename)); + mod.require = request => { + if (Object.hasOwn(mocks, request)) return mocks[request]; + return Module.prototype.require.call(mod, request); + }; + mod._compile(output, filename); + return mod.exports; +} + +function settings(models, overrides = {}) { + return { + workspace: { + byokSettings: { + serverEntitled: true, + policy: { enabled: true, allowedProviders: ['openai'] }, + profiles: [ + { + profileId: 'profile-sol', + provider: 'openai', + name: 'Solar provider', + enabled: true, + definition: { models }, + }, + ], + ...overrides, + }, + }, + }; +} + +const text = { input: ['text'], output: ['text'] }; +const model = (modelId, enabled = true, capabilities = [text]) => ({ + modelId, + enabled, + capabilities, +}); +const managed = choices => ({ + currentUser: { copilot: { routeOptions: choices === null ? null : { choices } } }, +}); +const choice = (id, available = true) => ({ + id, + displayName: `Managed ${id}`, + available, +}); + +function createModelService(gql, saved = new Map()) { + const { AIModelService } = loadTypeScript( + 'packages/frontend/core/src/modules/ai-button/services/models.ts', + { + '@affine/graphql': { + getCopilotRouteOptionsQuery: { op: 'managed' }, + workspaceByokSettingsQuery: { op: 'byok' }, + }, + '@preact/signals-core': { signal }, + '@toeverything/infra': { Service }, + } + ); + const state = { + globalState: { + get: key => saved.get(key), + set: (key, value) => saved.set(key, value), + }, + }; + const subscriptions = { + subscription: { ai$: { subscribe: () => ({ unsubscribe() {} }) } }, + }; + return { service: new AIModelService(state, { gql }, subscriptions), saved }; +} + +async function settle() { + await new Promise(resolve => setImmediate(resolve)); + await new Promise(resolve => setImmediate(resolve)); +} + +async function testModelPicker() { + const eight = Array.from({ length: 8 }, (_, index) => + model(index === 5 ? 'target6.1Sol' : `model-${index + 1}`) + ); + const { service, saved } = createModelService(options => + Promise.resolve(options.query.op === 'managed' ? managed([]) : settings(eight)) + ); + service.setScope('workspace-a', 'chat'); + await settle(); + assert.equal(service.models.value.length, 8, 'managed-empty retains eight BYOK choices'); + const target = service.models.value.find(item => item.modelId === 'target6.1Sol'); + assert.equal(target.category, 'target6.1Sol'); + assert.equal(target.version, 'Solar provider'); + assert.deepEqual(target && service.getSelection(), {}, 'Auto is default'); + service.setModel(target.id); + assert.deepEqual(service.getSelection(), { + profileId: 'profile-sol', + modelId: 'target6.1Sol', + }); + assert.equal(saved.get('AIManagedRouteTarget:workspace-a:chat'), target.id); + assert.match(target.id, /^byok:profile-sol:target6\.1Sol$/); + + service.models.value = [ + { id: 'managed-id', name: 'Managed', category: 'Managed', version: 'id', available: true }, + ]; + service.setModel('managed-id'); + assert.deepEqual(service.getSelection(), { routeTargetId: 'managed-id' }); + + const filtered = createModelService(options => + Promise.resolve( + options.query.op === 'managed' + ? managed([choice('keep'), choice('locked', false)]) + : settings([model('disabled', false), model('vision', true, [{ input: ['image'], output: ['text'] }])]) + ) + ); + filtered.saved.set('AIManagedRouteTarget:workspace-b:route', 'removed-model'); + filtered.service.setScope('workspace-b', 'route'); + await settle(); + assert.deepEqual(filtered.service.models.value.map(item => item.id), ['keep', 'locked']); + assert.equal( + filtered.saved.get('AIManagedRouteTarget:workspace-b:route'), + undefined, + 'invalid scope selection is removed' + ); + filtered.service.setModel('locked'); + assert.equal(filtered.service.modelId.value, undefined, 'disabled choices cannot be selected'); + + const denied = createModelService(options => + options.query.op === 'managed' + ? Promise.resolve(managed([choice('good')])) + : Promise.reject({ isStatus: code => code === 403 }) + ); + denied.service.setScope('workspace-c', 'route'); + await settle(); + assert.deepEqual(denied.service.models.value.map(item => item.id), ['good']); + + const managedFailure = createModelService(options => + options.query.op === 'managed' + ? Promise.reject(new Error('managed unavailable')) + : Promise.resolve(settings([model('byok-still-works')])) + ); + managedFailure.service.setScope('workspace-managed-failure', 'route'); + await settle(); + assert.deepEqual( + managedFailure.service.models.value.map(item => item.modelId), + ['byok-still-works'], + 'BYOK remains usable when managed route options fail' + ); + + const rejected = createModelService(options => + options.query.op === 'managed' + ? Promise.resolve(managed([choice('good')])) + : Promise.reject(new Error('schema failure')) + ); + await assert.rejects(() => rejected.service.load('workspace-d', 'route'), /schema failure/); + + const pending = new Map(); + const stale = createModelService(options => { + const key = `${options.query.op}:${options.variables.id || options.variables.promptName}`; + return new Promise(resolve => pending.set(key, resolve)); + }); + const first = stale.service.load('old', 'old-route'); + const second = stale.service.load('new', 'new-route'); + pending.get('managed:new-route')(managed([choice('new')])); + pending.get('byok:new')(settings([])); + await second; + pending.get('managed:old-route')(managed([choice('old')])); + pending.get('byok:old')(settings([])); + await first; + assert.deepEqual(stale.service.models.value.map(item => item.id), ['new'], 'stale scope is ignored'); +} + +async function testRuntimeForwarding() { + const { AIChatRuntime } = loadTypeScript( + 'packages/frontend/core/src/blocksuite/ai/runtime/chat/runtime.ts', + { + '@affine/graphql': {}, + './actions': {}, + './session-strategy': {}, + './state': { + createDraftTab: () => ({}), + createInitialComposerState: () => ({}), + sessionToTab: () => ({}), + }, + } + ); + const calls = []; + const runtime = Object.create(AIChatRuntime.prototype); + runtime.options = { + request: { + executeAction: async (_kind, options) => { + calls.push(options); + return (async function* () {})(); + }, + getActiveEditorContext: () => undefined, + waitForSelectedSources: async () => {}, + }, + }; + runtime.requestSeq = 0; + runtime.streamAbortController = null; + runtime.sessionSelections = new Map(); + runtime.snapshot = { + scope: { workspaceId: 'workspace' }, + uiPolicy: { canSend: true }, + composer: { + text: '', attachments: [], reasoning: false, toolsConfig: {}, routeTargetId: 'composer-route', + scopeSelection: { items: [], syncing: false, error: null }, focus: { items: [] }, + }, + messages: [], activeSessionId: 'session', tabs: [], status: 'success', + }; + runtime.commit = patch => { runtime.snapshot = { ...runtime.snapshot, ...patch }; }; + runtime.ensureSession = async () => ({ sessionId: 'session' }); + runtime.activateEditorContext = async () => undefined; + runtime.createMessage = () => ({}); + runtime.markActiveTabHasMessages = tabs => tabs; + runtime.refreshLastMessageId = async () => {}; + runtime.bindActiveSessionToDoc = async () => {}; + runtime.appendAssistantContent = () => {}; + runtime.updateScopeSelection = () => {}; + runtime.toError = error => error; + await runtime.send({ input: 'hello', profileId: 'profile-sol', modelId: 'target6.1Sol' }); + assert.equal(calls[0].routeTargetId, undefined, 'BYOK suppresses composer route target'); + assert.equal(calls[0].profileId, 'profile-sol'); + assert.equal(calls[0].modelId, 'target6.1Sol'); + await runtime.retry(); + assert.equal(calls[1].profileId, 'profile-sol', 'retry retains in-memory selection'); + assert.equal(calls[1].modelId, 'target6.1Sol'); +} + +Promise.resolve() + .then(testModelPicker) + .then(testRuntimeForwarding) + .then(() => process.stdout.write('AFFiNE BYOK model-picker regression tests passed\n')) + .catch(error => { + console.error(error); + process.exitCode = 1; + }); diff --git a/test/package/default.nix b/test/package/default.nix index 0631d711..9b0197ba 100644 --- a/test/package/default.nix +++ b/test/package/default.nix @@ -15,6 +15,16 @@ in (import ./linux-devshell { inherit system inputs self pkgs; }) // (import ./windows-devshell { inherit system inputs self pkgs; }) // { + affine-chatgpt-enrollment = pkgs.runCommand "affine-chatgpt-enrollment" { + nativeBuildInputs = [ self.packages.${system}.affine-chatgpt pkgs.jq ]; + } '' + export HOME="$TMPDIR/home" + mkdir -p "$HOME" + affine-chatgpt status > status.json + jq -e '.authorized == false and .access_token_expired == true' status.json + touch "$out" + ''; + pg-smtp-client-metadata = assert builtins.all (package: package.pname == "pg_smtp_client") smtpPackages; assert builtins.all (package: package.version == "0.2.0") smtpPackages;