Free, open-source 3D sculpting for Linux, macOS and Windows: dense meshes, remeshing, painting, built-in AI (image/text to 3D), Send to Unreal, game-ready LODs, Gaussian splats and OpenUSD.
C++ 3d3d-sculptingcppdear-imguidigital-sculptingfbxgame-developmentgaussian-splattinggltfimage-to-3dmcpopenglopenusdsculptingtext-to-3dunreal-engine
Studio controls for AI/MCP: managed policy, audit log, provider presets + keychain keys, OIDC device sign-in
islandmedd464b4cd02fa
diff --git a/.github/workflows/release.yml b/.github/workflows/release.ymlindex f58258f2..6215c14f 100644--- a/.github/workflows/release.yml+++ b/.github/workflows/release.yml@@ -287,6 +287,8 @@ jobs:cp "dist/sculptforge_bridge-$V.zip" dist/sculptforge_bridge.zip- name: Maya shelf script (Python source and its README; nothing to build)run: python3 -m zipfile -c dist/sculptforge_maya.zip integrations/maya/sculptforge_maya.py integrations/maya/README.md+ - name: Software bill of materials (CycloneDX; covered by the checksums and their signature)+ run: python3 tools/release/sbom.py --version "${TAG#v}" --out "dist/SculptForge-${TAG#v}-sbom.cdx.json"- name: Checksumsrun: cd dist && sha256sum * > SHA256SUMS.txt && cat SHA256SUMS.txt- name: Sign the checksums (one-click update checks SHA256SUMS.txt.sig, src/core/SelfUpdate.h)diff --git a/CMakeLists.txt b/CMakeLists.txtindex c0a4c5ff..cf35ac47 100644--- a/CMakeLists.txt+++ b/CMakeLists.txt@@ -100,6 +100,8 @@ add_library(sculptforge_core STATICsrc/core/SelfUpdate.cppsrc/core/MemberBuilds.cppsrc/core/Keychain.cpp+ src/core/ManagedPolicy.cpp+ src/core/AuditLog.cppsrc/core/BrushGallery.cppsrc/core/VertexPaint.cppsrc/core/PaintLayer.cpp@@ -233,6 +235,9 @@ target_link_libraries(sculptforge_core PUBLIC glm::glm Threads::Threads)if(UNIX AND NOT APPLE)target_link_libraries(sculptforge_core PRIVATE ${CMAKE_DL_LIBS}) # core/Keychain.cpp: libsecret, loaded at run timeendif()+if(APPLE)+ target_link_libraries(sculptforge_core PRIVATE "-framework Security" "-framework CoreFoundation") # core/Keychain.cpp+endif()# zstd for Focus Detail tiles (core/FocusDetail.h), when the system has it; without it the tiles use our own codec.# Not on macOS: Homebrew's zstd is single-architecture and breaks the universal (x86_64 + arm64) build.find_package(PkgConfig QUIET)@@ -258,7 +263,7 @@ set_source_files_properties(third_party/xatlas/xatlas.cpp third_party/tinyexr/tiPROPERTIES SKIP_PRECOMPILE_HEADERS ON)# --- Bring-your-own-AI (brush assistant). HTTPS via WinHTTP or libcurl. ----add_library(sculptforge_ai STATIC src/ai/Http.cpp src/ai/AiPolicy.cpp src/ai/BrushAssistant.cpp src/ai/Generator3D.cpp+add_library(sculptforge_ai STATIC src/ai/Http.cpp src/ai/AiPolicy.cpp src/ai/Providers.cpp src/ai/Secrets.cpp src/ai/Oidc.cpp src/ai/BrushAssistant.cpp src/ai/Generator3D.cppsrc/ai/ImageTo3DService.cpp src/ai/GradioClient.cpp src/ai/ComfyUI.cpp src/ai/AiCommands.cpp src/ai/BrushGalleryClient.cpp src/link/Socket.cppsrc/link/UnrealLink.cpp src/ai/Process.cpp src/ai/SplatTrainer.cpp)# Lets a build run from its tree find the bundled ComfyUI workflows (integrations/comfyui/workflows).@@ -747,6 +752,8 @@ if(SCULPTFORGE_BUILD_TESTS)# Every interface label has a Spanish and a Traditional Chinese translation (or is a name kept in English,# tools/i18n/keep_english.txt): a new label without one fails here, not in a release.add_test(NAME i18n_coverage COMMAND ${Python3_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/tools/i18n/coverage.py --check)+ # The release's SBOM (tools/release/sbom.py, docs/guide/security.md): every fetched archive is a listed component.+ add_test(NAME sbom COMMAND ${Python3_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/tools/release/sbom.py --check)add_test(NAME marks_self_test COMMAND ${Python3_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/tools/check_marks.py --self-test)# The same marks read off the pixels of every tracked image and video (OCR, cached by file hash), and the deploy's# takedown of flagged ones (tools/media_takedown.py).diff --git a/SECURITY.md b/SECURITY.mdindex 3df227d8..777396f8 100644--- a/SECURITY.md+++ b/SECURITY.md@@ -23,5 +23,7 @@ SculptForge opens files from untrusted sources (OBJ, FBX, glTF, PLY, USD/USDZ, inetwork services you configure (AI providers, Hugging Face Spaces, the Unreal Editor). Crashes or memoryerrors from malformed files, and anything that could leak API keys, are in scope.-API keys you enter are stored in your user settings folder (`ai.json`) with owner-only file permissions.-They are only ever sent to the service they belong to.+API keys you enter, and studio sign-in tokens, are stored in the operating system's keychain (macOS Keychain,+Windows Credential Manager, Linux Secret Service), never in settings files or logs. They are only ever sent to the+service they belong to. SculptForge opens no network listener for AI tools (MCP is stdio only) or for sign-in (the+device authorization grant). For IT reviews, see docs/guide/security.md.diff --git a/assets/fonts/NotoSansTC-UI.otf b/assets/fonts/NotoSansTC-UI.otfindex 8b703fc3..244b7f93 100644Binary files a/assets/fonts/NotoSansTC-UI.otf and b/assets/fonts/NotoSansTC-UI.otf differdiff --git a/changes/feat-studio-ready.md b/changes/feat-studio-ready.mdnew file mode 100644index 00000000..c05395ad--- /dev/null+++ b/changes/feat-studio-ready.md@@ -0,0 +1,36 @@+---+whats_new: **Studio controls**: IT can deploy a policy file that locks AI, network features, AI providers, AI tools and+ updates (**Managed by your studio** shows on locked settings), keep an audit log of every AI action, and sign artists+ in with the studio account (the guide's "SculptForge for studios" page, IT deployment).+whats_new: **AI providers**: **Edit > Preferences > AI > Provider** has presets for Anthropic, OpenAI, Ollama, LM Studio,+ vLLM, llama.cpp, a LiteLLM studio gateway and OpenRouter. Keys now live in your system keychain.+highlight: Studio-ready AI: policy, audit log, single sign-on+added: **Managed policy for studios** (docs/guide/studios.md "IT deployment"): `policy.json` in `/etc/sculptforge`,+ `/Library/Application Support/SculptForge` or `C:\ProgramData\SculptForge` (or `SF_POLICY` when there is none) locks+ AI on or off, network features, the allowed AI providers and addresses, sign-in for AI, AI tools (MCP on or off, never+ controlling the window, allowed kinds of command), the update check, channel and feed. Locked settings say **Managed by+ your studio**; a broken policy fails closed. `sculptforge-cli --policy` shows what it manages.+added: **AI audit log**: every AI tool (MCP) command, refused ones too, and every Brush Lab and Generate 3D request is a+ JSON line (time, user, host, client, command, a summary of its settings, result) in a local file or a share the policy+ names, rotated by size. No artwork, keys or long text. `sculptforge-cli --audit-log` prints the path.+added: **Studio sign-in** (Okta, Microsoft Entra ID, Google Workspace, Auth0, Keycloak): OpenID Connect device sign-in in+ the artist's browser, no local listener; tokens in the keychain, sent only to the studio's own AI gateway.+ **Edit > Preferences > AI > Studio sign-in**, or `sculptforge-cli --sign-in`.+added: **AI provider presets** in **Edit > Preferences > AI > Provider** (also in Brush Lab): Anthropic, OpenAI, Ollama,+ LM Studio, vLLM, llama.cpp server, LiteLLM proxy (a studio gateway for Bedrock, Vertex AI and Azure OpenAI) and+ OpenRouter.+added: Each release carries a CycloneDX software bill of materials (`SculptForge-<version>-sbom.cdx.json`), covered by the+ signed checksums. A one-page security overview for IT reviews is in the guide.+security: AI keys (Brush Lab, Hugging Face, fal.ai, Meshy) are stored in the operating system's keychain (macOS Keychain,+ Windows Credential Manager, Linux Secret Service) instead of `ai.json`; keys already in `ai.json` move there at the+ first start. Without a keychain (`SF_KEYCHAIN=none`), a key lasts for the session; environment variables still work.+testers:+ - Any OS: Edit > Preferences > AI > Provider: pick each preset; the endpoint and note change; save; restart; the+ choice stays and the key is still used (and ai.json has no key in it).+ - Linux: write /etc/sculptforge/policy.json with "ai": {"enabled": false}; start: Enable AI features is greyed with+ "Managed by your studio". Break the file (a typo in a key): AI, AI tools and network features are off.+ - Any OS: run an AI tool against `sculptforge-cli --mcp`; each command appears in the audit log+ (`sculptforge-cli --audit-log`).+---+Policy: src/core/ManagedPolicy.*; audit: src/core/AuditLog.*; presets ai/Providers.*; keys ai/Secrets.* and+core/Keychain.cpp (macOS Keychain added); sign-in ai/Oidc.* (mock IdP tests in tests/test_studio_policy.cpp).diff --git a/docs/ai-services.md b/docs/ai-services.mdindex 92bcecba..54f5b89e 100644--- a/docs/ai-services.md+++ b/docs/ai-services.md@@ -13,7 +13,8 @@ or the picture or text you give Generate 3D) goes to the service you picked.Generate 3D are hidden, their commands (`brush_ai`, `image_to_3d`, `text_to_3d`, `comfyui_check`)are not registered in the app, `sculptforge-cli`, Python or the MCP tool list, and no AI request ismade. The setting is `"enabled"` in `ai.json`. `SF_AI=off` in the environment (or `--no-ai`) turns-it off and locks it, for studios; `SF_AI=on` turns it on whatever was saved.+it off and locks it, for studios; `SF_AI=on` turns it on whatever was saved. A studio's policy file locks it either+way (see [IT deployment](guide/studios.md#it-deployment)).## What is sent where@@ -24,8 +25,15 @@ it off and locks it, for studios; `SF_AI=on` turns it on whatever was saved.| Generate 3D (text) | Hugging Face Spaces (free), fal.ai, Meshy, your own ComfyUI | Your text description | As above || Send to Unreal | Your own Unreal Editor (local network) | The exported FBX | None |-Keys are stored in your local settings file (`ai.json`, owner-only permissions) or read from-environment variables (`ANTHROPIC_API_KEY`, `OPENAI_API_KEY`, `HF_TOKEN`, `FAL_KEY`, `MESHY_API_KEY`).+Keys are stored in your operating system's keychain (macOS Keychain, Windows Credential Manager, or the Secret+Service on Linux), never in a settings file, or read from environment variables (`ANTHROPIC_API_KEY`,+`OPENAI_API_KEY`, `OPENROUTER_API_KEY`, `HF_TOKEN`, `FAL_KEY`, `MESHY_API_KEY`). Keys saved by older versions in+`ai.json` move into the keychain at the first start.++**Preferences > AI > Provider** has presets for Anthropic, OpenAI, Ollama, LM Studio, vLLM, llama.cpp server,+a LiteLLM proxy (a studio's own gateway, which can front Amazon Bedrock, Google Vertex AI and Azure OpenAI) and+OpenRouter. Studios can limit which providers and addresses artists may use, require their single sign-on, and keep+an audit log of every AI action: see [IT deployment](guide/studios.md#it-deployment).## The free Brush Lab modeldiff --git a/docs/guide/brush-lab.md b/docs/guide/brush-lab.mdindex 4ab7e076..bbe4d2f4 100644--- a/docs/guide/brush-lab.md+++ b/docs/guide/brush-lab.md@@ -82,18 +82,25 @@ only. The choice is saved in the brush's `.sfbrush` file, so a shared brush keep## Choose an AI providerBrush Lab works out of the box with no account or key. Open the **AI provider** section of Brush Lab (also in-**Mesh > Generate 3D > AI brush provider**) to choose another service.+**Mesh > Generate 3D > AI brush provider** and **Edit > Preferences > AI > Provider**) to choose another service.+Each choice fills in the address and a model:| Provider | What you need | Notes ||---|---|---|| **Free - no account or key** (default) | Nothing | An open model (GPT-OSS 20B) hosted by Pollinations.ai. Only your description and settings are sent. Rate limited to about one request every few seconds. If it can't be reached, a running local Ollama is used instead. |-| **Anthropic (Claude) - your key** | An Anthropic API key | Uses `claude-opus-5-5` by default. **Effort** (low, medium, high) trades speed for more considered brushes. |-| **OpenAI-compatible (OpenAI, Ollama, LM Studio...)** | An endpoint, a model name and, for hosted services, a key | Any server that speaks the OpenAI chat completions API, including local models. |--For Anthropic and OpenAI-compatible providers you can edit the **Endpoint**, **Model** and **API key** fields.-Leave the key empty to use the `ANTHROPIC_API_KEY` or `OPENAI_API_KEY` environment variable. Click-**Save settings** to keep your choice; settings and keys are stored only on your computer, in `ai.json` in the-SculptForge settings folder (readable only by you). Requests go only to the endpoint you set.+| **Anthropic (Claude)** | An Anthropic API key | Uses `claude-opus-5-5` by default. **Effort** (low, medium, high) trades speed for more considered brushes. |+| **OpenAI** | An OpenAI API key | Click **Find models** to pick one. |+| **Ollama (this computer)**, **LM Studio (this computer)** | The app running on your computer | Private and offline, no key. See below. |+| **vLLM server**, **llama.cpp server** | A server on your computer or at your studio | Change the address to your server's. |+| **LiteLLM proxy (studio gateway)** | Your studio's gateway address | One address for every model your studio allows; a key from your studio, or your studio sign-in. See [IT deployment](studios.md#ai-providers). |+| **OpenRouter** | An OpenRouter key | Many models through one key. |+| **Other OpenAI-compatible server** | An endpoint, a model name and, for hosted services, a key | Any server that speaks the OpenAI chat completions API. |++You can edit the **Endpoint**, **Model** and **API key** fields. Leave the key empty to use the+`ANTHROPIC_API_KEY`, `OPENAI_API_KEY` or `OPENROUTER_API_KEY` environment variable. Click **Save settings** to keep+your choice. Keys are kept in your system's keychain (macOS Keychain, Windows Credential Manager, or the Secret+Service on Linux), never in a settings file. Requests go only to the endpoint you set. If your studio manages+SculptForge, some providers may be greyed out with **Managed by your studio**.### Run a model on your own computer@@ -101,11 +108,10 @@ For private, offline use with no rate limits, run a local model with Ollama or L1. Install [Ollama](https://ollama.com/download) and download the recommended model:`ollama pull qwen3:4b-instruct` (2.5 GB, works without a graphics card).-2. In **AI provider**, choose **OpenAI-compatible (OpenAI, Ollama, LM Studio...)**.-3. Click **Ollama** (or **LM Studio**) to fill in the local endpoint.-4. Click **Find models**. SculptForge checks the connection, shows "Connected" with the number of installed+2. In **AI provider**, choose **Ollama (this computer)** (or **LM Studio (this computer)**).+3. Click **Find models**. SculptForge checks the connection, shows "Connected" with the number of installedmodels, and lets you pick one from the **Model** list.-5. Click **Save settings**.+4. Click **Save settings**.The **Run a model on this computer** section in the panel shows the install steps for your operating system.The model needs about 4 GB of free memory; expect 10-20 seconds per brush on a laptop CPU and a few secondsdiff --git a/docs/guide/index.md b/docs/guide/index.mdindex 7f94746b..7f2a210d 100644--- a/docs/guide/index.md+++ b/docs/guide/index.md@@ -79,14 +79,15 @@ Read it inside SculptForge (**Help > User Guide**, or <kbd>Shift</kbd>+<kbd>F1</39. [Scripting and automation](scripting.md)40. [Packs and macros](packs-and-macros.md)41. [SculptForge for studios](studios.md)+42. [Security overview for IT reviews](security.md)## Reference-42. [Keyboard and mouse](shortcuts.md)-43. [Performance and big meshes](performance.md)-44. [Troubleshooting: tablets, display, crashes and FAQ](troubleshooting.md)-45. [Glossary](glossary.md)-46. [Show SculptForge on Discord](discord.md)+43. [Keyboard and mouse](shortcuts.md)+44. [Performance and big meshes](performance.md)+45. [Troubleshooting: tablets, display, crashes and FAQ](troubleshooting.md)+46. [Glossary](glossary.md)+47. [Show SculptForge on Discord](discord.md)## Getting helpdiff --git a/docs/guide/security.md b/docs/guide/security.mdnew file mode 100644index 00000000..b3e007f2--- /dev/null+++ b/docs/guide/security.md@@ -0,0 +1,65 @@+# Security overview for IT reviews++A one-page summary for a studio's security or IT review. Details and settings are in+[SculptForge for studios](studios.md#it-deployment).++## What SculptForge is++A desktop sculpting application (GPL-3.0, source on GitHub), a command-line tool (`sculptforge-cli`) and a Python+module. No account, no licence server, no servers of our own. It runs as the signed-in user with no elevated rights+and installs no services, drivers or background processes.++## Network++| | |+|---|---|+| Telemetry, analytics, crash upload | **None.** Crash logs stay on the computer. |+| Listening ports | **None by default**, and never for AI tools or sign-in. Two features listen while the artist uses them: phone capture (on the local network, so the phone can reach it) and the Unreal link. With the network off by policy, they may use only this computer unless `network.localNetwork` allows the studio network. The Blender and Maya bridges exchange files. |+| Outbound connections | Only what the artist uses: the daily update check (a small file from the website, or your own feed), the community brush gallery, and the AI service the artist chose. With `"network": {"enabled": false}` in the policy, a single gate refuses everything except the addresses you list, before anything is sent, and follows no redirects. |+| AI features | Optional, and lockable off by policy. Only the request goes to the chosen service: a brush description, or the picture or text given to Generate 3D. Sculpts are never uploaded or used for training. Providers and addresses can be limited to your own gateway or local models. |++## AI tools (MCP)++`sculptforge-cli --mcp` serves the Model Context Protocol over **stdio only**: the AI tool starts it as a child+process; nothing listens on a port. Each command an AI tool runs is checked against the policy's allowed categories+(read, edit, files, scripts, network, AI) and written to the audit log. AI tools can't install, remove or switch+packs. Controlling an open SculptForge window can be forbidden outright (`"mcp": {"live": "never"}`), and MCP can be+turned off entirely.++## Data at rest++| | Where |+|---|---|+| Artwork | Wherever the artist saves it. SculptForge doesn't copy it elsewhere. |+| Settings | The user's settings folder, owner-only permissions. No secrets in them. |+| API keys, sign-in tokens | The OS keychain only: macOS Keychain, Windows Credential Manager, Linux Secret Service. Never in files or logs. |+| Audit log | JSON lines, local or on a share you choose; no artwork, keys or long text. |++## Identity++Single sign-on uses OpenID Connect with the **device authorization grant** (RFC 8628) against your identity provider:+the artist signs in in their own browser with your MFA, and no local listener or embedded browser is involved. The+token is sent only to the addresses your policy names (your AI gateway).++## Central control++A read-only policy file (`/etc/sculptforge/policy.json`, `/Library/Application Support/SculptForge/policy.json`,+`C:\ProgramData\SculptForge\policy.json`) locks AI on or off, network features, allowed AI providers and addresses,+AI tool access, sign-in, the audit log and updates. A broken policy fails closed. An artist can't override it with+environment variables while it is installed.++## Supply chain++| | Status |+|---|---|+| Builds | Built from the public repository by GitHub Actions, from tagged commits, with every third-party archive pinned by SHA-256 (`cmake/Fetch.cmake`). |+| Release integrity | Every release has `SHA256SUMS.txt` and an Ed25519 signature of it (`SHA256SUMS.txt.sig`); the app's own updater checks both. |+| SBOM | Each release carries a CycloneDX SBOM (`SculptForge-<version>-sbom.cdx.json`), covered by the signed checksums. Licences: `THIRD_PARTY_NOTICES.md`. |+| Code signing | **Not yet.** Windows installers are not Authenticode-signed (SmartScreen warns), and the macOS app is ad-hoc signed, not notarized. Verify downloads with the signed checksums until then. |+| Updates | Off, or from your own feed or mirror, by policy. A studio build reads only its own channel. |+| Vulnerability reports | Private reporting on GitHub (see `SECURITY.md`); fixes go to the latest release. |++## See also++- [SculptForge for studios: IT deployment](studios.md#it-deployment)+- [AI services: privacy and model licences](https://github.com/islandmed/SculptForge/blob/main/docs/ai-services.md)diff --git a/docs/guide/studios.md b/docs/guide/studios.mdindex 3f7504a7..82f91192 100644--- a/docs/guide/studios.md+++ b/docs/guide/studios.md@@ -3,7 +3,8 @@SculptForge is built to drop into animation, VFX and game studios that run their own pipelines: native onLinux, scriptable, standards-based, with no licence server and nothing that phones home. This chapter is forpipeline TDs and IT: the VFX Reference Platform builds, Rez deployment, shared brush libraries, environment-variables, headless use and licensing.+variables, headless use, licensing and [IT deployment](#it-deployment) (a managed policy, the AI audit log, single+sign-on, AI gateways and air-gapped use).## VFX Reference Platform builds@@ -79,16 +80,18 @@ rez-env sculptforge -- sculptforge| `SF_AI` | `off`: every AI feature off and locked (app, `sculptforge-cli`, MCP, Python); `on`: on whatever was saved. `--no-ai` does the same as `off` for one start || `SF_STUDIO_PROFILE` | A studio profile (`studio.json`) to start in studio mode with, like `--studio` (see [Your studio build](#your-studio-build)) || `SF_OFFLINE` | `1`: studio mode with nothing allowed, like `--offline` |+| `SF_POLICY` | A policy file, when there is no system-wide one (see [The policy file](#the-policy-file)) |+| `SF_KEYCHAIN` | `none`: don't use the OS keychain (render nodes, CI); keys last for the session or come from the environment || `SCULPTFORGE_BRUSH_PATH` | Read-only studio brush folders (`:`-separated, `;` on Windows) || `SCULPTFORGE_STUDIO_BRUSHES` | With the Rez package: appended to `SCULPTFORGE_BRUSH_PATH` || `SCULPTFORGE_BRUSH_GALLERY` | Use another community brush gallery index (a URL or a folder), for example an in-house mirror || `HF_TOKEN` (or `HUGGING_FACE_HUB_TOKEN`) | Hugging Face token for the free image-to-3D models || `FAL_KEY`, `MESHY_API_KEY` | Keys for the paid generation services |-| `ANTHROPIC_API_KEY`, `OPENAI_API_KEY` | Keys for Brush Lab providers |+| `ANTHROPIC_API_KEY`, `OPENAI_API_KEY`, `OPENROUTER_API_KEY` | Keys for Brush Lab providers || `XDG_DATA_HOME` (Linux), `APPDATA` (Windows) | Move the settings folder (see [where settings live](troubleshooting.md#where-settings-live)) |-Keys from the environment are used when none is saved in the app, so a launcher can supply them without-writing them to each artist's settings.+Keys from the environment are used when none is saved in the app (keys saved in the app live in the OS keychain), so+a launcher can supply them without storing them for each artist.## Headless and farm use@@ -241,6 +244,172 @@ To install on machines without internet access:4. To test studio mode on any machine, `sculptforge --offline` turns it on with nothing allowed; `SF_OFFLINE=1`does the same for the CLI and Python.+## IT deployment++Everything an IT team needs to roll SculptForge out under its own rules: a policy file that locks settings, an+audit log of what AI did, the studio's own AI gateway and single sign-on, and offline use. Nothing here needs a+studio build; it works on the public one. For a security review, see the [security overview](security.md).++### The policy file++Put a `policy.json` where only administrators can write it:++| OS | Path |+|---|---|+| Linux | `/etc/sculptforge/policy.json` |+| macOS | `/Library/Application Support/SculptForge/policy.json` |+| Windows | `C:\ProgramData\SculptForge\policy.json` (deploy it with Group Policy, Intune, SCCM or your usual tool) |++SculptForge reads it at every start (the app, `sculptforge-cli`, MCP and the Python module). Each setting it locks+is greyed out in **Edit > Preferences** with **Managed by your studio** next to it. Without a system file,+`SF_POLICY=/path/policy.json` names one, for testing a policy or setting it from a launcher or a Rez package; while+the system file exists, `SF_POLICY` is ignored, so an artist can't loosen it.++```json+{+ "format": "sculptforge-policy", "version": 1,+ "organization": "Acme Animation",+ "ai": {"enabled": true, "providers": ["litellm", "comfyui"],+ "endpoints": ["https://llm.acme.internal/", "http://comfy.acme.internal:8188/"], "requireSignIn": true},+ "network": {"enabled": false, "allow": ["https://sw.acme.internal/"], "localNetwork": false},+ "mcp": {"enabled": true, "live": "never", "categories": ["info", "edit", "files"]},+ "audit": {"path": "//fs01/audit/sculptforge/{user}@{host}.jsonl", "maxMB": 20, "keep": 10, "required": true},+ "signIn": {"issuer": "https://acme.okta.com/oauth2/default", "clientId": "0oa1example",+ "useFor": ["https://llm.acme.internal/"]},+ "telemetry": "none",+ "updates": {"check": true, "channel": "stable", "feed": "https://sw.acme.internal/sculptforge/latest.json"}+}+```++Every key is optional: what the policy leaves out stays the artist's choice. An unknown key or a wrong value is an+error, so a typo never quietly drops a lock, and **a broken or unreadable policy fails closed**: AI, network+features and AI tools stay off until it is fixed. `sculptforge-cli --policy` shows what the policy manages (exit+code 2 when it is broken); use it to check a file before you deploy it.++| Key | What it does |+|---|---|+| `organization` | Shown as "Managed by Acme Animation" |+| `ai.enabled` | `false`: every AI feature off and locked (as `SF_AI=off`). `true`: on and locked. Left out: the artist's choice |+| `ai.providers` | The only AI providers artists can pick: `free`, `anthropic`, `openai`, `ollama`, `lmstudio`, `vllm`, `llamacpp`, `litellm`, `openrouter`, `openai-compatible` (Brush Lab) and `huggingface`, `fal`, `meshy`, `comfyui`, `command` (Generate 3D) |+| `ai.endpoints` | The only addresses AI requests may go to (URL prefixes, matched at a `/`) |+| `ai.requireSignIn` | AI works only while the artist is signed in with the studio account (needs `signIn`) |+| `network.enabled` | `false`: studio mode (see [Offline deployment](#offline-deployment)): no outside connection except `network.allow`, `ai.endpoints`, the identity provider and your update feed |+| `network.allow` | More URL prefixes that stay reachable while the network is off |+| `network.localNetwork` | `true`: the Unreal link and phone capture may use the studio network while the network is off |+| `mcp.enabled` | `false`: no AI tool can connect (`sculptforge-cli --mcp` refuses to start) |+| `mcp.live` | `"never"`: AI tools work only on their own scene and can never control an open SculptForge window |+| `mcp.categories` | The kinds of command AI tools may use: `info` (read the scene), `edit` (change it in memory), `files` (open, save, export, bridges), `scripts` (macros), `network` (brush gallery, Unreal), `ai` (AI generation). Left out: all |+| `audit.path`, `audit.maxMB`, `audit.keep` | Where the [audit log](#audit-log) goes, when it rotates (10 MB) and how many old files it keeps (5) |+| `audit.required` | `true`: an AI action whose audit line can't be written (the share is down) is refused |+| `signIn.issuer`, `signIn.clientId` | Your identity provider and the app registration (see [Single sign-on](#single-sign-on)) |+| `signIn.clientSecret` | Only for providers that issue one to installed apps and require it (Google); it isn't secret there, and artists can read the policy |+| `signIn.scopes`, `signIn.audience` | Scopes to ask for (default `openid profile email offline_access`); an audience, if your provider needs one (Auth0) |+| `signIn.useFor` | Addresses that get the sign-in as a bearer token (default: `ai.endpoints`) |+| `telemetry` | Only `"none"`: SculptForge has no telemetry. The key is there so your checklist can state it |+| `updates.check` | `false`: no update check, and the artist can't turn it on |+| `updates.channel` | `"stable"` or `"preview"`, locked |+| `updates.feed`, `updates.mirror` | Your own update feed (a URL) and mirror (a URL or a file on a share) instead of the public one |++The policy works alongside a [studio profile](#your-studio-build): a profile bakes in content and branding, the+policy locks settings. When both turn the network off, both allow lists apply.++### Audit log++Every AI action is one line of JSON in a local file: each command an AI tool (MCP) runs, refused ones included, and+every Brush Lab and Generate 3D request, from the app, `sculptforge-cli` and Python.++```json+{"time":"2026-11-05T14:03:22.120Z","user":"ana","host":"ws042","client":"mcp:claude-code 2.1.0","tool":"mcp",+ "command":"export_glb","args":{"path":"/show/troll/assets/rock.glb"},"result":"ok","message":"Exported","ms":930}+```++- **What is never written:** artwork (meshes, images, textures), keys and tokens (any argument named like a key,+ token, password or secret is `<redacted>`), and long text (strings are cut to 120 characters; a long prompt is+ recorded as its length). File paths are kept: they say what was read or written.+- **Where:** `audit.path` from the policy, with `{user}`, `{host}` and `{date}` filled in, so each machine can write+ its own file on a share. Without a policy, `audit/ai-audit.jsonl` in the [settings+ folder](troubleshooting.md#where-settings-live). **Edit > Preferences > AI** shows the path;+ `sculptforge-cli --audit-log` prints it.+- **Rotation:** past `audit.maxMB` the file becomes `.1`, `.1` becomes `.2`, and so on up to `audit.keep`.+- Nothing is sent anywhere: collect the files with your own tools (any log shipper reads JSON lines).++### AI providers++**Edit > Preferences > AI > Provider** has presets that fill in the address and a model, so artists pick a name+instead of typing URLs:++| Preset | Address | Key |+|---|---|---|+| Anthropic (Claude) | `https://api.anthropic.com/v1/messages` | The artist's or the studio's API key |+| OpenAI | `https://api.openai.com/v1/chat/completions` | API key |+| Ollama | `http://localhost:11434/v1/chat/completions` | None |+| LM Studio | `http://localhost:1234/v1/chat/completions` | None |+| vLLM server | `http://localhost:8000/v1/chat/completions` (or your GPU server) | Optional |+| llama.cpp server | `http://localhost:8080/v1/chat/completions` (or your server) | None |+| LiteLLM proxy (studio gateway) | `http://localhost:4000/v1/chat/completions` (change it to your gateway) | A virtual key, or the studio sign-in |+| OpenRouter | `https://openrouter.ai/api/v1/chat/completions` | API key |++**Amazon Bedrock, Google Vertex AI and Azure OpenAI** go through a [LiteLLM proxy](https://docs.litellm.ai/docs/simple_proxy)+your studio runs: the proxy holds the cloud credentials, applies your budgets and model list, and SculptForge talks+only to it. A minimal proxy configuration:++```yaml+model_list:+ - model_name: claude+ litellm_params: {model: "bedrock/<Bedrock model id>", aws_region_name: us-west-2}+ - model_name: gemini+ litellm_params: {model: "vertex_ai/<Vertex model id>", vertex_project: acme-render, vertex_location: us-central1}+ - model_name: gpt+ litellm_params: {model: "azure/<your deployment>", api_base: "https://acme.openai.azure.com", api_version: "<API version>"}+```++Point the preset at `https://llm.acme.internal/v1/chat/completions`, list that prefix in `ai.endpoints`, allow only+`litellm` in `ai.providers`, and artists can reach no other AI service. To validate the studio sign-in at the+gateway, use LiteLLM's JWT authentication with your identity provider's keys.++**Keys are kept in the operating system's keychain**: macOS Keychain, Windows Credential Manager, or the Secret+Service on Linux (GNOME Keyring, KWallet, KeePassXC). They are never written to a settings file; keys from older+versions move into the keychain at the first start. Where there is no keychain (`SF_KEYCHAIN=none`, a render node),+a key typed in lasts until SculptForge quits; the environment variables `ANTHROPIC_API_KEY`, `OPENAI_API_KEY`,+`OPENROUTER_API_KEY`, `HF_TOKEN`, `FAL_KEY` and `MESHY_API_KEY` work everywhere.++### Single sign-on++With `signIn` in the policy, **Edit > Preferences > AI > Studio sign-in** signs the artist in with the studio+account (Okta, Microsoft Entra ID, Google Workspace, Auth0, Keycloak or any OpenID Connect provider). It uses the+**device authorization grant** only: SculptForge shows a short code and opens your provider's page, and the artist+signs in there, in their browser, with your usual login and MFA. Nothing on the artist's computer listens for the+answer: no local port, no redirect, no embedded browser. `sculptforge-cli --sign-in` does the same in a terminal.++The tokens are kept in the keychain and refreshed when they expire. The access token is sent as+`Authorization: Bearer` only to the addresses in `signIn.useFor` (default: `ai.endpoints`), such as your AI gateway;+never to anyone else. SculptForge reads the ID token's name and email only to show who is signed in: your+services verify the access token.++To set it up, register a **public client** (no client secret) with the device flow turned on:++| Provider | Where | Issuer |+|---|---|---|+| Okta | Applications > Create App Integration > OIDC > Native Application; Grant type: Device Authorization | `https://<org>.okta.com/oauth2/default` |+| Microsoft Entra ID | App registrations > New registration; Authentication > Allow public client flows: Yes | `https://login.microsoftonline.com/<tenant id>/v2.0` |+| Google Workspace | Google Cloud console > Credentials > OAuth client ID > TVs and Limited Input devices | `https://accounts.google.com` (list `https://oauth2.googleapis.com/` in `network.allow` when the network is off) |+| Auth0 | Applications > Native; Advanced settings > Grant types: Device Code | `https://<tenant>.auth0.com/` (set `signIn.audience` to your API) |+| Keycloak | Clients > Create; Client authentication: Off; OAuth 2.0 Device Authorization Grant: On | `https://<host>/realms/<realm>` |++Put the client id in `signIn.clientId`. Google's device flow also wants the client's secret, which Google documents+as not confidential for this client type: put it in `signIn.clientSecret`. Google's access tokens are meant for+Google's own APIs, so with Google Workspace have your gateway validate the ID token instead.++### Offline and air-gapped use++- `"network": {"enabled": false}` in the policy, or `sculptforge --offline` / `SF_OFFLINE=1`, turns on studio+ mode: every request goes through one gate that refuses anything not allowed before it is sent, follows no redirect,+ and sockets open only on loopback (see [Offline deployment](#offline-deployment)).+- AI can stay on in an air-gapped facility with local models: allow `ollama`, `lmstudio`, `vllm`, `llamacpp` or+ `comfyui` and list their addresses in `ai.endpoints`.+- Updates come from `updates.feed` / `updates.mirror` only; copy a release's `latest.json` there when you are ready.+- Install from the signed checksums as described under [Offline deployment](#offline-deployment).+## Not yetPlanned pipeline features, roughly in order: OpenColorIO viewport display, Alembic export, fuller USD@@ -254,3 +423,4 @@ requests are welcome as issues on the project's GitHub page.- [Brush Lab and sharing brushes](brush-lab.md)- [Image and text to 3D](generate-3d.md): running models on your own ComfyUI server- [Troubleshooting](troubleshooting.md)+- [Security overview for IT reviews](security.md)diff --git a/docs/local-ai.md b/docs/local-ai.mdindex b6f8d378..e94d4916 100644--- a/docs/local-ai.md+++ b/docs/local-ai.md@@ -109,9 +109,9 @@ Ollama listens on `http://localhost:11434`. Opening that address in a browser sh## 3. Connect SculptForge1. Open **Brush Lab** and expand **AI provider**.-2. Choose **OpenAI-compatible**.-3. Click **Ollama** to fill in the address, then **Find models**. You should see- "Connected - 1 model installed", and the model appears in the **Model** list.+2. Choose **Ollama (this computer)**: the address is filled in.+3. Click **Find models**. You should see "Connected - 1 model installed", and the model appears in the **Model**+ list.4. Click **Save settings**, then describe a brush: "dry cracked mud".Leave **API key** empty. Local servers don't need one.@@ -134,7 +134,7 @@ if you'd rather not use a terminal.1. Install LM Studio and open it.2. Search for **Qwen3 4B Instruct** in the **Discover** tab and download it.3. Open the **Developer** tab, load the model and switch the server **on** (it serves on port 1234).-4. In SculptForge choose **OpenAI-compatible → LM Studio → Find models**.+4. In SculptForge choose **LM Studio (this computer)**, then **Find models**.## Running the model on another computerdiff --git a/src/ai/AiCommands.cpp b/src/ai/AiCommands.cppindex 6a50cacf..371946e0 100644--- a/src/ai/AiCommands.cpp+++ b/src/ai/AiCommands.cpp@@ -1,6 +1,7 @@// SculptForge - open source digital sculpting// SPDX-License-Identifier: GPL-3.0-or-later#include "ai/AiCommands.h"+#include "core/AuditLog.h"#include "ai/AiPolicy.h"#include "ai/BrushGalleryClient.h"@@ -68,9 +69,29 @@ CommandResult importGenerated(Document& doc, const Args& a, const GeneratorResul} // namespacevoid addAiFeatureCommands(CommandRegistry& registry, std::function<AiSettings()> settings) {+ // Every run goes into the audit log (core/AuditLog.h), from the app, a script, the CLI or an AI tool; with the+ // policy's audit.required, a run whose line can't be written is refused before anything is sent.+ auto add = [®istry](Command c) {+ c.run = [name = c.name, run = std::move(c.run)](Document& doc, const Args& a) -> CommandResult {+ audit::Entry e;+ e.tool = "ai";+ e.command = name;+ e.args = audit::summarizeArgs(a);+ const auto start = std::chrono::steady_clock::now();+ CommandResult r;+ if (std::string why; audit::required() && !audit::writable(&why)) r = {false, why};+ else r = run(doc, a);+ e.ok = r.ok;+ e.message = r.message;+ e.ms = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now() - start).count();+ audit::record(e);+ return r;+ };+ registry.add(std::move(c));+ };using T = ParamSpec::Type;removeAiFeatureCommands(registry); // never twice- registry.add({"brush_ai",+ add({"brush_ai","Design a brush from a description. Free by default (a hosted open model, no key); or ""provider=anthropic (ANTHROPIC_API_KEY), or provider=openai-compatible endpoint=... model=... ""for OpenAI, Ollama, LM Studio etc.",@@ -91,7 +112,7 @@ void addAiFeatureCommands(CommandRegistry& registry, std::function<AiSettings()>return {true, "'" + r.recipe.name + "': " + r.reply};}});- registry.add({"image_to_3d",+ add({"image_to_3d","Reconstruct a full 3D model from one picture (character, creature, prop) and make it sculptable. ""Free by default via Hugging Face Spaces (Hunyuan3D, TRELLIS.2, Stable Fast 3D; HF_TOKEN raises the ""daily quota), paid via fal.ai (FAL_KEY) / Meshy (MESHY_API_KEY), or any workflow on your own "@@ -133,7 +154,7 @@ void addAiFeatureCommands(CommandRegistry& registry, std::function<AiSettings()>return importGenerated(doc, a, r, mode, "");}});- registry.add({"text_to_3d",+ add({"text_to_3d","Create a 3D model from a description and make it sculptable. Free by default via Hugging Face ""(Hunyuan3D 2 / 2 mini Turbo; HF_TOKEN raises the daily quota), or paid via fal.ai (FAL_KEY) / ""Meshy (MESHY_API_KEY), or a workflow on your own ComfyUI (service=comfyui workflow=FILE). Replaces the scene.",@@ -182,7 +203,7 @@ void addAiFeatureCommands(CommandRegistry& registry, std::function<AiSettings()>return importGenerated(doc, a, r, mode, " from text");}});- registry.add({"comfyui_check",+ add({"comfyui_check","Check that a ComfyUI server answers (for service=comfyui) and show its version and GPU.",{{"url", T::String, "Server address. Default http://127.0.0.1:8188 or your saved one.", false}},[settings](Document&, const Args& a) -> CommandResult {diff --git a/src/ai/AiPolicy.cpp b/src/ai/AiPolicy.cppindex 86e6daf4..0feb1c30 100644--- a/src/ai/AiPolicy.cpp+++ b/src/ai/AiPolicy.cpp@@ -2,6 +2,7 @@// SPDX-License-Identifier: GPL-3.0-or-later#include "ai/AiPolicy.h"+#include "core/ManagedPolicy.h"#include "core/NetworkPolicy.h"#include <algorithm>@@ -16,7 +17,10 @@ std::atomic<bool> gEnabled{true};std::atomic<bool> gForcedOff{false};std::atomic<bool> gStudioAllows{false};// Studio mode turns AI off and locks it, unless the studio's profile asks for it ("ai": true).-bool studioOff() { return net::offlineMode() && !gStudioAllows; }+// A managed policy (core/ManagedPolicy.h) that turns AI on allows it in studio mode too (its endpoints are reachable).+bool studioOff() { return net::offlineMode() && !gStudioAllows && policy::current().ai != policy::Lock::On; }+bool managedOff() { return policy::current().ai == policy::Lock::Off; }+bool managedOn() { return policy::current().ai == policy::Lock::On; }} // namespacevoid setStudioAiAllowed(bool on) { gStudioAllows = on; }@@ -33,10 +37,15 @@ AiOverride aiEnvOverride() {void setAiForcedOff(bool off) { gForcedOff = off; }-bool aiPolicyLocked() { return gForcedOff || studioOff() || aiEnvOverride() != AiOverride::None; }+bool aiPolicyLocked() {+ return gForcedOff || studioOff() || managedOff() || managedOn() || aiEnvOverride() != AiOverride::None;+}++bool aiManaged() { return managedOff() || managedOn(); }bool aiFeaturesAllowed(bool saved) {- if (gForcedOff || studioOff()) return false;+ if (gForcedOff || studioOff() || managedOff()) return false;+ if (managedOn()) return true; // the studio's policy wins over SF_AI and the saved choiceswitch (aiEnvOverride()) {case AiOverride::Off: return false;case AiOverride::On: return true;@@ -49,6 +58,7 @@ void setAiEnabled(bool on) { gEnabled = on; }bool aiEnabled() { return gEnabled; }std::string aiOffError() {+ if (managedOff()) return "AI features are turned off by your studio's policy";if (studioOff()) return "AI features are off in this studio build";return aiPolicyLocked() ? "AI features are turned off on this computer (SF_AI=off or --no-ai)": "AI features are off (Preferences > AI > Enable AI features)";diff --git a/src/ai/AiPolicy.h b/src/ai/AiPolicy.hindex 32137721..f64351f9 100644--- a/src/ai/AiPolicy.h+++ b/src/ai/AiPolicy.h@@ -24,8 +24,10 @@ AiOverride aiEnvOverride();void setAiForcedOff(bool off); // --no-ai: as SF_AI=off for this process// Studio mode locks AI off unless its profile says "ai": true (core/StudioProfile.h).void setStudioAiAllowed(bool on);-// True when the environment or --no-ai decides, so the saved choice can't change it.+// True when the environment, --no-ai, studio mode or a studio's policy decides, so the saved choice can't change it.bool aiPolicyLocked();+// True when a studio's policy file (core/ManagedPolicy.h) decides: the UI says "Managed by your studio".+bool aiManaged();// The effective switch: the environment (or --no-ai) wins over the saved preference.bool aiFeaturesAllowed(bool saved);diff --git a/src/ai/BrushAssistant.cpp b/src/ai/BrushAssistant.cppindex a4a9d911..7f718675 100644--- a/src/ai/BrushAssistant.cpp+++ b/src/ai/BrushAssistant.cpp@@ -4,6 +4,10 @@#include "ai/AiPolicy.h"#include "ai/Http.h"+#include "ai/Oidc.h"+#include "ai/Providers.h"+#include "ai/Secrets.h"+#include "core/ManagedPolicy.h"#include "core/BrushLibrary.h"#include <cstdlib>@@ -100,18 +104,24 @@ const char* AiSettings::providerName(Provider provider) {std::string AiSettings::resolvedKey() const {if (provider == Provider::Free) return {};if (!apiKey.empty()) return apiKey;- const char* env = std::getenv(provider == Provider::Anthropic ? "ANTHROPIC_API_KEY" : "OPENAI_API_KEY");+ const std::string id = providerId(*this);+ if (std::string k = secrets::cached(secrets::presetAccount(id)); !k.empty()) return k;+ const ProviderPreset* p = findProviderPreset(id);+ const char* name = p && *p->keyEnv ? p->keyEnv : provider == Provider::Anthropic ? "ANTHROPIC_API_KEY" : "OPENAI_API_KEY";+ const char* env = std::getenv(name);return env ? env : "";}std::string AiSettings::resolvedFalKey() const {if (!falKey.empty()) return falKey;+ if (std::string k = secrets::cached(secrets::kFal); !k.empty()) return k;const char* env = std::getenv("FAL_KEY");return env ? env : "";}std::string AiSettings::resolvedHfToken() const {if (!hfToken.empty()) return hfToken;+ if (std::string k = secrets::cached(secrets::kHuggingFace); !k.empty()) return k;for (const char* name : {"HF_TOKEN", "HUGGING_FACE_HUB_TOKEN"})if (const char* env = std::getenv(name)) return env;return {};@@ -119,27 +129,26 @@ std::string AiSettings::resolvedHfToken() const {std::string AiSettings::resolvedMeshyKey() const {if (!meshyKey.empty()) return meshyKey;+ if (std::string k = secrets::cached(secrets::kMeshy); !k.empty()) return k;const char* env = std::getenv("MESHY_API_KEY");return env ? env : "";}Json AiSettings::toJson() const {Json j = Json::object();+ // (no keys: they are in the keychain, ai/Secrets.h)j.set("provider", providerName(provider));+ j.set("preset", providerId(*this)); // (also marks a file from 0.11.4 on: see fromJson)j.set("endpoint", endpoint);j.set("model", model);- j.set("apiKey", apiKey);j.set("effort", effort);j.set("generatorService", generatorService);j.set("generatorCommand", generatorCommand);- j.set("hfToken", hfToken);j.set("hfModel", hfModel);j.set("hfModelChosen", hfModelChosen);j.set("hunyuanNoticeShown", hunyuanNoticeShown);- j.set("falKey", falKey);j.set("falModel", falModel);j.set("falEndpoint", falEndpoint);- j.set("meshyKey", meshyKey);j.set("meshyModel", meshyModel);j.set("meshyEndpoint", meshyEndpoint);j.set("comfyUrl", comfyUrl);@@ -152,15 +161,17 @@ Json AiSettings::toJson() const {AiSettings AiSettings::fromJson(const Json& j) {// Settings saved before the free tier existed defaulted to Anthropic; without// a key they never worked, so those move to Free.+ // (Files with a "preset" are newer: their key is in the keychain, not missing.)Provider p = providerFromName(j["provider"].asString());- if (p == Provider::Anthropic && j["apiKey"].asString().empty() && !std::getenv("ANTHROPIC_API_KEY") &&+ if (p == Provider::Anthropic && !j.has("preset") && j["apiKey"].asString().empty() && !std::getenv("ANTHROPIC_API_KEY") &&j["endpoint"].asString() == kAnthropicUrl)p = Provider::Free;AiSettings s = defaults(p);const bool keepEndpoint = p == providerFromName(j["provider"].asString());if (keepEndpoint && !j["endpoint"].asString().empty()) s.endpoint = j["endpoint"].asString();if (keepEndpoint && !j["model"].asString().empty()) s.model = j["model"].asString();- s.apiKey = j["apiKey"].asString();+ if (keepEndpoint && findProviderPreset(j["preset"].asString())) s.preset = j["preset"].asString();+ s.apiKey = j["apiKey"].asString(); // (an older ai.json's key: moved to the keychain, ai/Secrets.h)if (!j["effort"].asString().empty()) s.effort = j["effort"].asString();s.generatorCommand = j["generatorCommand"].asString();auto text = [&](const char* key, std::string& field) {@@ -279,6 +290,12 @@ std::string requestUrl(const AiSettings& s) { return s.endpoint; }std::vector<std::string> requestHeaders(const AiSettings& s) {std::vector<std::string> h = {"Content-Type: application/json"};const std::string key = s.resolvedKey();+ // The studio sign-in goes to the studio's own gateway (core/ManagedPolicy.h signIn.useFor), instead of a key.+ if (const std::string bearer = oidc::bearerHeaderFor(requestUrl(s)); !bearer.empty()) {+ h.push_back(bearer);+ if (s.provider == AiSettings::Provider::Anthropic) h.push_back("anthropic-version: 2023-06-01");+ return h;+ }if (s.provider == AiSettings::Provider::Anthropic) {h.push_back("x-api-key: " + key);h.push_back("anthropic-version: 2023-06-01");@@ -388,6 +405,7 @@ std::vector<std::string> listModels(const AiSettings& s, std::string& error) {error = aiOffError();return out;}+ if (!aiRequestAllowed(providerId(s), modelsUrl(s.endpoint), error)) return out;HttpResponse r = httpRequest("GET", modelsUrl(s.endpoint), requestHeaders(s), {}, 5);if (!r.error.empty()) {error = "Nothing is answering at " + s.endpoint + " - is Ollama or LM Studio running? (" + r.error + ")";@@ -409,6 +427,7 @@ std::string smallestOllamaModel(std::string& error) {error = aiOffError();return {};}+ if (!aiRequestAllowed("ollama", "http://localhost:11434/api/tags", error)) return {};HttpResponse r = httpRequest("GET", "http://localhost:11434/api/tags", {}, {}, 2);Json j;if (r.status != 200 || !Json::parse(r.body, j, error)) return {};@@ -424,6 +443,14 @@ std::string smallestOllamaModel(std::string& error) {return best;}+bool aiRequestAllowed(const std::string& id, const std::string& url, std::string& error) {+ if (!aiEnabled()) return (error = aiOffError(), false);+ if (!policy::aiProviderAllowed(id, &error) || !policy::aiEndpointAllowed(url, &error)) return false;+ if (policy::current().requireSignIn && oidc::state() != oidc::State::SignedIn)+ return (error = "Sign in with your studio account first (Preferences > AI > Studio sign-in)", false);+ return true;+}+BrushSuggestion requestBrush(const AiSettings& s, const std::vector<ChatMessage>& history,std::string* rawAssistantJson) {if (!aiEnabled()) {@@ -431,7 +458,8 @@ BrushSuggestion requestBrush(const AiSettings& s, const std::vector<ChatMessage>out.error = aiOffError();return out;}- if (s.provider == AiSettings::Provider::Anthropic && s.resolvedKey().empty()) {+ if (BrushSuggestion out; !aiRequestAllowed(providerId(s), requestUrl(s), out.error)) return out;+ if (s.provider == AiSettings::Provider::Anthropic && s.resolvedKey().empty() && !oidc::usesSignIn(requestUrl(s))) {BrushSuggestion out;out.error = "No Anthropic API key - add one in AI settings or set ANTHROPIC_API_KEY, or switch to Free.";return out;diff --git a/src/ai/BrushAssistant.h b/src/ai/BrushAssistant.hindex 67e4999d..f8148e4e 100644--- a/src/ai/BrushAssistant.h+++ b/src/ai/BrushAssistant.h@@ -22,9 +22,12 @@ struct AiSettings {// key), falling back to a local Ollama if it is running.enum class Provider { Free, Anthropic, OpenAICompatible };Provider provider = Provider::Free;+ std::string preset; // the provider preset (ai/Providers.h: "ollama", "litellm", ...); "" = from provider/endpointstd::string endpoint;std::string model;- std::string apiKey; // Free: unused; empty = use ANTHROPIC_API_KEY / OPENAI_API_KEY from the environment+ // Keys (apiKey, hfToken, falKey, meshyKey) are kept in the OS keychain (ai/Secrets.h), never in ai.json: these+ // fields hold one typed in this session, or read from an older ai.json (moved to the keychain at start-up).+ std::string apiKey; // Free: unused; empty = the keychain, then ANTHROPIC_API_KEY / OPENAI_API_KEY / the preset'sstd::string effort = "low";// Image to 3D. service: "huggingface" (free Spaces), "fal", "meshy",// "comfyui" (your ComfyUI server), "command" (generatorCommand with@@ -55,7 +58,7 @@ struct AiSettings {Json toJson() const;static AiSettings fromJson(const Json& j);- // Stored in the user's config directory with owner-only permissions.+ // Stored in the user's config directory with owner-only permissions, without the keys.bool save(const std::string& path, std::string& error) const;static AiSettings load(const std::string& path);};@@ -95,6 +98,10 @@ std::vector<std::string> listModels(const AiSettings& s, std::string& error);// The smallest model a local Ollama has installed, or empty if none is running.std::string smallestOllamaModel(std::string& error);+// The studio policy's gate for one AI request (core/ManagedPolicy.h): the provider, the address and, when the policy+// requires it, the studio sign-in. False with ERROR set (and nothing sent) when it may not go.+bool aiRequestAllowed(const std::string& providerId, const std::string& url, std::string& error);+// Blocking (run on a worker thread): sends the conversation, whose last// message must be the user's, and returns a recipe.BrushSuggestion requestBrush(const AiSettings& s, const std::vector<ChatMessage>& history,diff --git a/src/ai/ComfyUI.cpp b/src/ai/ComfyUI.cppindex 382cf6f3..0430cec9 100644--- a/src/ai/ComfyUI.cpp+++ b/src/ai/ComfyUI.cpp@@ -255,6 +255,7 @@ bool checkServer(const std::string& url, ServerInfo& info, std::string& error, ireturn false;}const std::string base = normalizeUrl(url);+ if (!aiRequestAllowed("comfyui", base + "/system_stats", error)) return false; // (a studio's policy)HttpResponse r = httpRequest("GET", base + "/system_stats", {}, {}, timeoutSeconds);if (!r.error.empty()) {error = unreachable(base, r.error);@@ -575,6 +576,7 @@ GeneratorResult run(const AiSettings& s, const std::string& workflowPath, constconst std::string& prompt, const std::string& outputStem, GenerationProgress* p,std::optional<uint64_t> seed) {if (!aiEnabled()) return {false, {}, aiOffError()};+ if (std::string why; !aiRequestAllowed("comfyui", normalizeUrl(s.comfyUrl) + "/prompt", why)) return {false, {}, why};GeneratorResult result;const bool text = imagePath.empty();const std::string kind = text ? "text" : "image";diff --git a/src/ai/ImageTo3DService.cpp b/src/ai/ImageTo3DService.cppindex d3dfd6f8..1887ae31 100644--- a/src/ai/ImageTo3DService.cpp+++ b/src/ai/ImageTo3DService.cpp@@ -1,6 +1,7 @@// SculptForge - open source digital sculpting// SPDX-License-Identifier: GPL-3.0-or-later#include "ai/ImageTo3DService.h"+#include "core/ManagedPolicy.h"#include "ai/AiPolicy.h"#include "ai/ComfyUI.h"@@ -549,9 +550,23 @@ std::string findModelUrl(const Json& result, std::string* extension) {return url;}+namespace {+// The studio policy's gate (core/ManagedPolicy.h ai.providers / ai.endpoints / requireSignIn) for the chosen service.+// "inflate" is offline and not AI: always allowed. "command" runs a local program: its provider id alone decides.+bool serviceAllowed(const AiSettings& s, std::string& error) {+ const std::string& svc = s.generatorService;+ if (svc == "inflate") return true;+ const std::string url = svc == "fal" ? s.falEndpoint : svc == "meshy" ? s.meshyEndpoint : svc == "comfyui" ? s.comfyUrl+ : svc == "command" ? std::string() : std::string("https://huggingface.co/");+ if (url.empty()) return policy::aiProviderAllowed(svc, &error);+ return aiRequestAllowed(svc == "fal" || svc == "meshy" || svc == "comfyui" ? svc : "huggingface", url, error);+}+} // namespace+GeneratorResult generate3D(const AiSettings& s, const std::string& imagePath, const std::string& outputStem,GenerationProgress* progress) {if (!aiEnabled()) return {false, {}, aiOffError()};+ if (std::string why; !serviceAllowed(s, why)) return {false, {}, why};if (s.generatorService == "meshy") return runMeshy(s, imagePath, outputStem, progress);if (s.generatorService == "command") {status(progress, "Running your generator...");@@ -586,6 +601,7 @@ std::string falTextBody(const std::string& prompt, const std::string& model) {GeneratorResult generate3DFromText(const AiSettings& s, const std::string& prompt, const std::string& outputStem,GenerationProgress* progress) {if (!aiEnabled()) return {false, {}, aiOffError()};+ if (std::string why; !serviceAllowed(s, why)) return {false, {}, why};GeneratorResult result;if (prompt.find_first_not_of(" \t\r\n") == std::string::npos) {result.error = "Describe the model you want";diff --git a/src/ai/Oidc.cpp b/src/ai/Oidc.cppnew file mode 100644index 00000000..8eda15c3--- /dev/null+++ b/src/ai/Oidc.cpp@@ -0,0 +1,394 @@+// SculptForge - open source digital sculpting+// SPDX-License-Identifier: GPL-3.0-or-later+#include "ai/Oidc.h"++#include "core/Json.h"+#include "core/Keychain.h"+#include "core/ManagedPolicy.h"+#include "core/NetworkPolicy.h"++#include <algorithm>+#include <cctype>+#include <chrono>+#include <mutex>+#include <thread>++namespace sf::ai::oidc {++namespace {++std::string formEncode(const std::string& s) {+ static const char* hex = "0123456789ABCDEF";+ std::string out;+ for (unsigned char c : s) {+ if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '-' || c == '_' || c == '.' || c == '~')+ out += char(c);+ else if (c == ' ')+ out += '+';+ else+ out += '%', out += hex[c >> 4], out += hex[c & 15];+ }+ return out;+}++bool endpointOk(const std::string& url) {+ net::UrlParts u;+ if (!net::parseUrl(url, u)) return false;+ return u.scheme == "https" || (u.scheme == "http" && net::isLoopbackAddress(u.host));+}++std::string trimSlash(std::string s) {+ while (!s.empty() && s.back() == '/') s.pop_back();+ return s;+}++std::string base64UrlDecode(const std::string& in) {+ auto value = [](char c) -> int {+ if (c >= 'A' && c <= 'Z') return c - 'A';+ if (c >= 'a' && c <= 'z') return c - 'a' + 26;+ if (c >= '0' && c <= '9') return c - '0' + 52;+ if (c == '-' || c == '+') return 62;+ if (c == '_' || c == '/') return 63;+ return -1;+ };+ std::string out;+ int bits = 0, acc = 0;+ for (char c : in) {+ const int v = value(c);+ if (v < 0) break; // '=' padding or anything else ends it+ acc = (acc << 6) | v;+ bits += 6;+ if (bits >= 8) {+ bits -= 8;+ out += char((acc >> bits) & 0xff);+ }+ }+ return out;+}++// Safe for every keychain (Windows target names are ASCII here).+std::string accountFor(const std::string& clientId) {+ std::string a = "sso/";+ for (char c : clientId) a += (std::isalnum(static_cast<unsigned char>(c)) || c == '-' || c == '_' || c == '.') ? c : '_';+ return a;+}++std::mutex gMutex;+Transport gTestTransport;+std::function<void(int)> gSleep;+std::function<int64_t()> gClock;+Tokens gTokens;+bool gLoaded = false;++int64_t now() {+ if (gClock) return gClock();+ return std::chrono::duration_cast<std::chrono::seconds>(std::chrono::system_clock::now().time_since_epoch()).count();+}++void sleepFor(int seconds) {+ if (gSleep) gSleep(seconds);+ else std::this_thread::sleep_for(std::chrono::seconds(seconds));+}++HttpResponse doGetBody(const std::string& url) {+ if (gTestTransport.get) return gTestTransport.get(url);+ // The discovery document: this one URL, no redirect followed, at most 1 MB.+ std::string body;+ HttpResponse r = httpGetRestricted(+ url, [&url](const std::string& u) { return u == url; }, 15,+ [&body](const char* d, size_t n) {+ body.append(d, n);+ return body.size() < (1u << 20);+ });+ r.body = body;+ return r;+}++HttpResponse doPost(const std::string& url, const std::string& body) {+ if (gTestTransport.post) return gTestTransport.post(url, body);+ return httpPostNoRedirect(url, {"Content-Type: application/x-www-form-urlencoded", "Accept: application/json"}, body, 20);+}++bool discover(const policy::Policy& p, Discovery& d, std::string& error) {+ const std::string url = discoveryUrl(p.issuer);+ if (std::string why; !net::urlAllowed(url, &why)) return (error = "The sign-in page can't be reached: " + why, false);+ HttpResponse r = doGetBody(url);+ if (r.status != 200) {+ error = r.status ? "The identity provider answered " + std::to_string(r.status) + " for its configuration"+ : "Can't reach the identity provider" + (r.error.empty() ? std::string() : ": " + r.error);+ return false;+ }+ return parseDiscovery(r.body, p.issuer, d, error);+}++void saveLocked(const policy::Policy& p) { keychain::store(accountFor(p.clientId), tokensToSecret(gTokens)); }++} // namespace++std::string discoveryUrl(const std::string& issuer) { return trimSlash(issuer) + "/.well-known/openid-configuration"; }++bool parseDiscovery(const std::string& json, const std::string& expectedIssuer, Discovery& out, std::string& error) {+ Json j;+ if (!Json::parse(json, j, error) || !j.isObject()) return (error = "The identity provider's configuration isn't JSON", false);+ Discovery d;+ d.issuer = j["issuer"].asString();+ d.deviceEndpoint = j["device_authorization_endpoint"].asString();+ d.tokenEndpoint = j["token_endpoint"].asString();+ if (trimSlash(d.issuer) != trimSlash(expectedIssuer))+ return (error = "The identity provider names another issuer (" + d.issuer.substr(0, 120) + "): check signIn.issuer", false);+ if (d.deviceEndpoint.empty())+ return (error = "This identity provider doesn't offer device sign-in: turn on the device authorization grant "+ "for the app",+ false);+ if (!endpointOk(d.deviceEndpoint) || !endpointOk(d.tokenEndpoint))+ return (error = "The identity provider's endpoints must be https", false);+ out = d;+ return true;+}++bool parseDeviceCode(const std::string& json, int64_t t, DeviceCode& out, std::string& error) {+ Json j;+ if (!Json::parse(json, j, error) || !j.isObject()) return (error = "Unexpected answer from the identity provider", false);+ if (j["error"].isString()) {+ error = "The identity provider refused: " + j["error"].asString().substr(0, 80);+ if (j["error_description"].isString()) error += " (" + j["error_description"].asString().substr(0, 160) + ")";+ return false;+ }+ DeviceCode d;+ d.deviceCode = j["device_code"].asString();+ d.userCode = j["user_code"].asString();+ // (Google calls it verification_url)+ d.verificationUri = j["verification_uri"].isString() ? j["verification_uri"].asString() : j["verification_url"].asString();+ d.verificationUriComplete = j["verification_uri_complete"].asString();+ d.interval = std::max(1, int(j["interval"].asNumber(5)));+ d.expiresAt = t + int64_t(j["expires_in"].asNumber(600));+ if (d.deviceCode.empty() || d.userCode.empty() || d.userCode.size() > 32 || !endpointOk(d.verificationUri))+ return (error = "Unexpected answer from the identity provider", false);+ if (!d.verificationUriComplete.empty() && !endpointOk(d.verificationUriComplete)) d.verificationUriComplete.clear();+ out = d;+ return true;+}++TokenReply parseTokenReply(long status, const std::string& json, int64_t t, Tokens& tokens, std::string& error) {+ Json j;+ if (!Json::parse(json, j, error) || !j.isObject()) {+ error = "Unexpected answer from the identity provider (HTTP " + std::to_string(status) + ")";+ return TokenReply::Error;+ }+ if (j["error"].isString()) {+ const std::string e = j["error"].asString();+ if (e == "authorization_pending") return TokenReply::Pending;+ if (e == "slow_down") return TokenReply::SlowDown;+ if (e == "expired_token" || e == "invalid_grant") return (error = "The sign-in expired: sign in again", TokenReply::Expired);+ if (e == "access_denied") return (error = "Sign-in was declined", TokenReply::Denied);+ error = "The identity provider refused: " + e.substr(0, 80);+ return TokenReply::Error;+ }+ if (status != 200 || !j["access_token"].isString() || j["access_token"].asString().empty()) {+ error = "Unexpected answer from the identity provider (HTTP " + std::to_string(status) + ")";+ return TokenReply::Error;+ }+ const std::string type = j["token_type"].asString();+ if (!type.empty() && type != "Bearer" && type != "bearer") return (error = "Unsupported token type", TokenReply::Error);+ Tokens out;+ out.access = j["access_token"].asString();+ out.refresh = j["refresh_token"].isString() ? j["refresh_token"].asString() : tokens.refresh; // (a refresh may not rotate it)+ out.id = j["id_token"].isString() ? j["id_token"].asString() : tokens.id;+ out.accessExpiresAt = t + int64_t(j["expires_in"].asNumber(3600));+ tokens = out;+ return TokenReply::Ok;+}++namespace {+std::string secretPart(const std::string& clientSecret) {+ return clientSecret.empty() ? std::string() : "&client_secret=" + formEncode(clientSecret);+}+} // namespace++std::string deviceBody(const std::string& clientId, const std::vector<std::string>& scopes, const std::string& audience,+ const std::string& clientSecret) {+ std::string scope;+ for (const std::string& s : scopes.empty() ? std::vector<std::string>{"openid", "profile", "email", "offline_access"} : scopes)+ scope += (scope.empty() ? "" : " ") + s;+ std::string b = "client_id=" + formEncode(clientId) + "&scope=" + formEncode(scope);+ if (!audience.empty()) b += "&audience=" + formEncode(audience); // (Auth0: the API the token is for)+ return b + secretPart(clientSecret);+}++std::string pollBody(const std::string& clientId, const std::string& deviceCode, const std::string& clientSecret) {+ return "grant_type=" + formEncode("urn:ietf:params:oauth:grant-type:device_code") + "&device_code=" ++ formEncode(deviceCode) + "&client_id=" + formEncode(clientId) + secretPart(clientSecret);+}++std::string refreshBody(const std::string& clientId, const std::string& refreshToken, const std::string& clientSecret) {+ return "grant_type=refresh_token&refresh_token=" + formEncode(refreshToken) + "&client_id=" + formEncode(clientId) ++ secretPart(clientSecret);+}++Identity parseIdToken(const std::string& idToken) {+ Identity id;+ const size_t a = idToken.find('.'), b = a == std::string::npos ? a : idToken.find('.', a + 1);+ if (b == std::string::npos) return id;+ Json j;+ std::string err;+ if (!Json::parse(base64UrlDecode(idToken.substr(a + 1, b - a - 1)), j, err) || !j.isObject()) return id;+ auto clean = [](const std::string& s) {+ std::string o;+ for (unsigned char c : s)+ if (c >= 0x20 && c != 0x7f && o.size() < 80) o += char(c);+ return o;+ };+ id.subject = clean(j["sub"].asString());+ id.email = clean(j["email"].asString());+ id.name = clean(j["name"].isString() ? j["name"].asString() : j["preferred_username"].asString());+ return id;+}++std::string tokensToSecret(const Tokens& t) {+ Json j = Json::object();+ j.set("access", t.access);+ j.set("refresh", t.refresh);+ j.set("id", t.id);+ j.set("expires", double(t.accessExpiresAt));+ return j.dump();+}++bool tokensFromSecret(const std::string& secret, Tokens& t) {+ Json j;+ std::string err;+ if (!Json::parse(secret, j, err) || !j.isObject()) return false;+ Tokens out;+ out.access = j["access"].asString();+ out.refresh = j["refresh"].asString();+ out.id = j["id"].asString();+ out.accessExpiresAt = int64_t(j["expires"].asNumber(0));+ if (out.access.empty() && out.refresh.empty()) return false;+ t = out;+ return true;+}++void setTransportForTests(Transport t) {+ std::lock_guard lock(gMutex);+ gTestTransport = std::move(t);+ gTokens = {};+ gLoaded = true; // (tests start signed out: never the real keychain's tokens)+}+void setSleepForTests(std::function<void(int)> sleep) { gSleep = std::move(sleep); }+void setClockForTests(std::function<int64_t()> clock) { gClock = std::move(clock); }++State state() {+ const policy::Policy& p = policy::current();+ if (!p.signInConfigured()) return State::NotConfigured;+ std::lock_guard lock(gMutex);+ return gTokens.access.empty() && gTokens.refresh.empty() ? State::SignedOut : State::SignedIn;+}++std::string signedInAs() {+ std::lock_guard lock(gMutex);+ if (gTokens.access.empty() && gTokens.refresh.empty()) return {};+ const std::string d = parseIdToken(gTokens.id).display();+ return d.empty() ? "signed in" : d;+}++void loadSaved() {+ const policy::Policy& p = policy::current();+ if (!p.signInConfigured()) return;+ {+ std::lock_guard lock(gMutex);+ if (gLoaded) return;+ }+ std::string secret;+ Tokens t;+ const bool ok = keychain::load(accountFor(p.clientId), secret) && tokensFromSecret(secret, t);+ std::lock_guard lock(gMutex);+ if (ok && gTokens.access.empty()) gTokens = t;+ gLoaded = true;+}++bool signIn(const std::function<bool(const DeviceCode&)>& onCode, const std::function<bool()>& cancel, std::string& error) {+ const policy::Policy& p = policy::current();+ if (!p.signInConfigured()) return (error = "No studio sign-in is set up (the policy's signIn)", false);+ Discovery d;+ if (!discover(p, d, error)) return false;+ HttpResponse r = doPost(d.deviceEndpoint, deviceBody(p.clientId, p.scopes, p.audience, p.clientSecret));+ if (r.status == 0) return (error = "Can't reach the identity provider" + (r.error.empty() ? "" : ": " + r.error), false);+ DeviceCode code;+ if (!parseDeviceCode(r.body, now(), code, error)) return false;+ if (onCode && !onCode(code)) return (error = "Sign-in cancelled", false);+ int interval = code.interval;+ for (;;) {+ // Sleep in one-second steps so a cancel is quick.+ for (int i = 0; i < interval; ++i) {+ if (cancel && cancel()) return (error = "Sign-in cancelled", false);+ sleepFor(1);+ }+ if (now() >= code.expiresAt) return (error = "The code expired: sign in again", false);+ HttpResponse pr = doPost(d.tokenEndpoint, pollBody(p.clientId, code.deviceCode, p.clientSecret));+ if (pr.status == 0) continue; // the network blinked: keep polling until the code expires+ Tokens t;+ switch (parseTokenReply(pr.status, pr.body, now(), t, error)) {+ case TokenReply::Ok: {+ std::lock_guard lock(gMutex);+ gTokens = t;+ saveLocked(p);+ error.clear();+ return true;+ }+ case TokenReply::Pending: break;+ case TokenReply::SlowDown: interval += 5; break; // RFC 8628 3.5+ default: return false;+ }+ }+}++void signOut() {+ const policy::Policy& p = policy::current();+ std::lock_guard lock(gMutex);+ gTokens = {};+ if (p.signInConfigured()) keychain::erase(accountFor(p.clientId));+}++std::string accessToken() {+ const policy::Policy& p = policy::current();+ if (!p.signInConfigured()) return {};+ loadSaved();+ Tokens t;+ {+ std::lock_guard lock(gMutex);+ t = gTokens;+ }+ if (t.usable(now())) return t.access;+ if (t.refresh.empty()) return {};+ Discovery d;+ std::string error;+ if (!discover(p, d, error)) return {};+ HttpResponse r = doPost(d.tokenEndpoint, refreshBody(p.clientId, t.refresh, p.clientSecret));+ const TokenReply reply = parseTokenReply(r.status, r.body, now(), t, error);+ std::lock_guard lock(gMutex);+ if (reply == TokenReply::Ok) {+ gTokens = t;+ saveLocked(p);+ return t.access;+ }+ if (reply == TokenReply::Expired || reply == TokenReply::Denied) { // the refresh token is gone: signed out+ gTokens = {};+ keychain::erase(accountFor(p.clientId));+ }+ return {};+}++bool usesSignIn(const std::string& url) {+ const policy::Policy& p = policy::current();+ if (!p.signInConfigured()) return false;+ for (const std::string& prefix : p.signInUseFor.empty() ? p.aiEndpoints : p.signInUseFor)+ if (net::urlUnderPrefix(url, prefix)) return true;+ return false;+}++std::string bearerHeaderFor(const std::string& url) {+ if (!usesSignIn(url)) return {};+ const std::string token = accessToken();+ return token.empty() ? std::string() : "Authorization: Bearer " + token;+}++} // namespace sf::ai::oidcdiff --git a/src/ai/Oidc.h b/src/ai/Oidc.hnew file mode 100644index 00000000..5da0201a--- /dev/null+++ b/src/ai/Oidc.h@@ -0,0 +1,98 @@+// SculptForge - open source digital sculpting+// SPDX-License-Identifier: GPL-3.0-or-later+//+// Studio sign-in: OpenID Connect with the OAuth 2.0 device authorization grant (RFC 8628) against the studio's+// identity provider (Okta, Microsoft Entra ID, Google Workspace, Auth0, Keycloak, ...). The issuer and client id come+// from the studio's policy (core/ManagedPolicy.h "signIn"); the client is a public one (no secret).+//+// Device flow only: SculptForge shows a short code and opens the provider's page; the artist signs in there, in their+// browser, with the studio's usual login and MFA. No local listener, no redirect URI, no embedded browser, so nothing+// on this computer can intercept the sign-in.+//+// The tokens live in the OS keychain (core/Keychain.h, account "sso/<client id>"), never in files or logs. The access+// token is sent as "Authorization: Bearer" only to the URLs the policy lists in signIn.useFor (default: its+// ai.endpoints): the studio's AI gateway (a LiteLLM proxy) or other studio services, which validate it. SculptForge+// reads the ID token's name and email only to show who is signed in.+#pragma once++#include "ai/Http.h"++#include <cstdint>+#include <functional>+#include <string>+#include <vector>++namespace sf::ai::oidc {++struct Discovery {+ std::string issuer, deviceEndpoint, tokenEndpoint;+};+// The provider's /.well-known/openid-configuration. Its issuer must be EXPECTED (a trailing '/' aside), and the+// endpoints https (http only on this computer, for tests); a provider without device authorization is an error.+bool parseDiscovery(const std::string& json, const std::string& expectedIssuer, Discovery& out, std::string& error);+std::string discoveryUrl(const std::string& issuer);++struct DeviceCode {+ std::string deviceCode; // only sent back to the token endpoint+ std::string userCode; // shown: "WDJB-MJHT"+ std::string verificationUri; // where to type it+ std::string verificationUriComplete; // the same with the code filled in ("" if the provider has none)+ int interval = 5;+ int64_t expiresAt = 0;+};+bool parseDeviceCode(const std::string& json, int64_t now, DeviceCode& out, std::string& error);++struct Tokens {+ std::string access, refresh, id;+ int64_t accessExpiresAt = 0; // unix time; 0 = unknown (treated as an hour after it was issued)+ bool usable(int64_t now) const { return !access.empty() && (accessExpiresAt == 0 || now < accessExpiresAt - 60); }+};++enum class TokenReply { Ok, Pending, SlowDown, Expired, Denied, Error };+// The token endpoint's answer to a device poll or a refresh (RFC 8628 3.5, RFC 6749 5.1/5.2).+TokenReply parseTokenReply(long status, const std::string& json, int64_t now, Tokens& tokens, std::string& error);++// Form bodies (application/x-www-form-urlencoded).+// CLIENT_SECRET only for providers that require one from installed apps (Google; "" = left out).+std::string deviceBody(const std::string& clientId, const std::vector<std::string>& scopes, const std::string& audience,+ const std::string& clientSecret = {});+std::string pollBody(const std::string& clientId, const std::string& deviceCode, const std::string& clientSecret = {});+std::string refreshBody(const std::string& clientId, const std::string& refreshToken, const std::string& clientSecret = {});++// Who is signed in, from the ID token's payload (not verified: display only; services verify the access token).+struct Identity {+ std::string subject, email, name;+ std::string display() const { return !name.empty() ? name : !email.empty() ? email : subject; }+};+Identity parseIdToken(const std::string& idToken);++std::string tokensToSecret(const Tokens& t);+bool tokensFromSecret(const std::string& secret, Tokens& t);++// How requests are made (tests: a mock identity provider).+struct Transport {+ std::function<HttpResponse(const std::string& url)> get;+ std::function<HttpResponse(const std::string& url, const std::string& formBody)> post;+};+void setTransportForTests(Transport t); // {} = the real one+void setSleepForTests(std::function<void(int seconds)> sleep);+void setClockForTests(std::function<int64_t()> now);++// The process's sign-in (the policy's issuer and client id). Blocking calls: worker threads (or the CLI).+enum class State { NotConfigured, SignedOut, SignedIn };+State state();+std::string signedInAs(); // "Ana Ruiz" ("" when signed out)+// Reads the saved tokens from the keychain (start-up).+void loadSaved();+// The whole device flow: discovery, the code (ON_CODE shows it; return false to stop), then polling until the+// artist finishes, says no, the code expires or CANCEL becomes true. True when signed in.+bool signIn(const std::function<bool(const DeviceCode&)>& onCode, const std::function<bool()>& cancel, std::string& error);+void signOut();+// A valid access token, refreshed if it expired ("" when signed out or the refresh failed).+std::string accessToken();+// The bearer header for URL when it is one the policy sends the sign-in to ("" otherwise).+std::string bearerHeaderFor(const std::string& url);+// True when URL gets the sign-in (signIn.useFor, else ai.endpoints).+bool usesSignIn(const std::string& url);++} // namespace sf::ai::oidcdiff --git a/src/ai/Providers.cpp b/src/ai/Providers.cppnew file mode 100644index 00000000..a3cec55d--- /dev/null+++ b/src/ai/Providers.cpp@@ -0,0 +1,69 @@+// SculptForge - open source digital sculpting+// SPDX-License-Identifier: GPL-3.0-or-later+#include "ai/Providers.h"++#include <iterator>++namespace sf::ai {++namespace {++using P = AiSettings::Provider;++constexpr ProviderPreset kPresets[] = {+ {"free", "Free - no account or key", P::Free, "https://text.pollinations.ai/openai", "openai", "", false, false,+ "An open model hosted by Pollinations.ai. Only your brush description and settings are sent."},+ {"anthropic", "Anthropic (Claude)", P::Anthropic, "https://api.anthropic.com/v1/messages", "claude-opus-5-5",+ "ANTHROPIC_API_KEY", true, false, "Your Anthropic API key (console.anthropic.com)."},+ {"openai", "OpenAI", P::OpenAICompatible, "https://api.openai.com/v1/chat/completions", "", "OPENAI_API_KEY",+ true, false, "Your OpenAI API key (platform.openai.com); then Find models."},+ {"ollama", "Ollama (this computer)", P::OpenAICompatible, "http://localhost:11434/v1/chat/completions",+ "qwen3:4b-instruct", "", false, true, "Private: the model runs on this computer. No key."},+ {"lmstudio", "LM Studio (this computer)", P::OpenAICompatible, "http://localhost:1234/v1/chat/completions", "", "",+ false, true, "Private: start LM Studio's server (Developer tab), then Find models. No key."},+ {"vllm", "vLLM server", P::OpenAICompatible, "http://localhost:8000/v1/chat/completions", "", "OPENAI_API_KEY", false,+ true, "A vLLM server (vllm serve <model>): this computer or a GPU server at your studio."},+ {"llamacpp", "llama.cpp server", P::OpenAICompatible, "http://localhost:8080/v1/chat/completions", "", "", false, true,+ "llama-server -m model.gguf: this computer or a server at your studio. No key."},+ {"litellm", "LiteLLM proxy (studio gateway)", P::OpenAICompatible, "http://localhost:4000/v1/chat/completions", "",+ "OPENAI_API_KEY", false, false,+ "Your studio's gateway: one address for every model your studio allows (Bedrock, Vertex AI, Azure OpenAI and "+ "others behind it). A virtual key, or your studio sign-in."},+ {"openrouter", "OpenRouter", P::OpenAICompatible, "https://openrouter.ai/api/v1/chat/completions", "openai/gpt-oss-20b",+ "OPENROUTER_API_KEY", true, false, "Many models through one key (openrouter.ai/keys)."},+ {"openai-compatible", "Other OpenAI-compatible server", P::OpenAICompatible, "", "", "OPENAI_API_KEY", false, false,+ "Any server with an OpenAI-style /v1/chat/completions endpoint."},+};++} // namespace++std::span<const ProviderPreset> providerPresets() { return kPresets; }++const ProviderPreset* findProviderPreset(std::string_view id) {+ for (const ProviderPreset& p : kPresets)+ if (id == p.id) return &p;+ return nullptr;+}++std::string providerId(const AiSettings& s) {+ if (const ProviderPreset* p = findProviderPreset(s.preset); p && p->kind == s.provider) return p->id;+ if (s.provider == P::Free) return "free";+ if (s.provider == P::Anthropic) return "anthropic";+ for (const ProviderPreset& p : kPresets) // a file from before presets: its endpoint names the server+ if (p.kind == P::OpenAICompatible && *p.endpoint && s.endpoint == p.endpoint) return p.id;+ return "openai-compatible";+}++AiSettings withPreset(const AiSettings& settings, std::string_view id) {+ AiSettings s = settings;+ const ProviderPreset* p = findProviderPreset(id);+ if (!p) return s;+ s.preset = p->id;+ s.provider = p->kind;+ if (*p->endpoint || p->kind != P::OpenAICompatible) s.endpoint = p->endpoint;+ s.model = p->model;+ s.apiKey.clear(); // each preset has its own key (ai/Secrets.h)+ return s;+}++} // namespace sf::aidiff --git a/src/ai/Providers.h b/src/ai/Providers.hnew file mode 100644index 00000000..a845e3fe--- /dev/null+++ b/src/ai/Providers.h@@ -0,0 +1,40 @@+// SculptForge - open source digital sculpting+// SPDX-License-Identifier: GPL-3.0-or-later+//+// AI provider presets (Preferences > AI > Provider): one click fills the endpoint and a model for a known service, so+// an artist or a studio's IT picks "LiteLLM proxy" instead of typing URLs. Every preset is the Free tier, Anthropic's+// Messages API or an OpenAI-compatible chat endpoint (ai/BrushAssistant.h); the endpoint can be edited after.+// Bedrock, Vertex AI and Azure OpenAI go through a LiteLLM proxy (docs/guide/studios.md "AI providers").+// The preset id is what a studio's policy lists in ai.providers (core/ManagedPolicy.h).+#pragma once++#include "ai/BrushAssistant.h"++#include <span>+#include <string>+#include <string_view>++namespace sf::ai {++struct ProviderPreset {+ const char* id; // "litellm" (ai.json "preset", the policy's ai.providers, the keychain account)+ const char* label; // "LiteLLM proxy (studio gateway)"+ AiSettings::Provider kind;+ const char* endpoint; // "" = the artist types it+ const char* model; // a sensible first model ("" = pick with Find models)+ const char* keyEnv; // the environment variable read when no key is saved ("" = none)+ bool needsKey; // a key is required (local servers usually take none)+ bool local; // runs on this computer by default+ const char* note; // one line under the picker+};++std::span<const ProviderPreset> providerPresets();+// The preset with this id, or nullptr.+const ProviderPreset* findProviderPreset(std::string_view id);+// The preset id of SETTINGS: its saved preset, else the one its provider kind and endpoint match, else+// "openai-compatible" / "anthropic" / "free".+std::string providerId(const AiSettings& settings);+// SETTINGS switched to preset ID (provider, endpoint, model; the rest is kept).+AiSettings withPreset(const AiSettings& settings, std::string_view id);++} // namespace sf::aidiff --git a/src/ai/Secrets.cpp b/src/ai/Secrets.cppnew file mode 100644index 00000000..a2bc718f--- /dev/null+++ b/src/ai/Secrets.cpp@@ -0,0 +1,130 @@+// SculptForge - open source digital sculpting+// SPDX-License-Identifier: GPL-3.0-or-later+#include "ai/Secrets.h"++#include "ai/BrushAssistant.h"+#include "ai/Providers.h"+#include "core/Json.h"+#include "core/Keychain.h"++#include <filesystem>+#include <fstream>+#include <iterator>+#include <map>+#include <mutex>++namespace sf::ai::secrets {++namespace {++std::mutex gMutex;+std::map<std::string, std::string>& cache() {+ static std::map<std::string, std::string> m;+ return m;+}+std::map<std::string, bool>& tried() { // accounts already read from the keychain+ static std::map<std::string, bool> m;+ return m;+}+bool gLazy = true;++} // namespace++std::string presetAccount(const std::string& presetId) { return "ai/" + presetId; }++std::vector<std::string> allAccounts() {+ std::vector<std::string> out;+ for (const ProviderPreset& p : providerPresets())+ if (p.kind != AiSettings::Provider::Free) out.push_back(presetAccount(p.id));+ out.push_back(kHuggingFace);+ out.push_back(kFal);+ out.push_back(kMeshy);+ return out;+}++void preload() {+ for (const std::string& account : allAccounts()) {+ std::string value;+ const bool found = keychain::load(account, value);+ std::lock_guard lock(gMutex);+ tried()[account] = true;+ if (found && !cache().count(account)) cache()[account] = value; // (a key typed in meanwhile wins)+ }+}++std::string cached(const std::string& account) {+ {+ std::lock_guard lock(gMutex);+ auto it = cache().find(account);+ if (it != cache().end()) return it->second;+ if (!gLazy || tried()[account]) return {};+ tried()[account] = true;+ }+ std::string value;+ if (!keychain::load(account, value)) return {};+ std::lock_guard lock(gMutex);+ cache()[account] = value;+ return value;+}++void setLazy(bool lazy) {+ std::lock_guard lock(gMutex);+ gLazy = lazy;+}++bool put(const std::string& account, const std::string& value) {+ {+ std::lock_guard lock(gMutex);+ auto it = cache().find(account);+ if (it != cache().end() && it->second == value) return true; // unchanged: no keychain call (no prompt)+ if (value.empty()) cache().erase(account);+ else cache()[account] = value;+ }+ return value.empty() ? keychain::erase(account) : keychain::store(account, value);+}++bool available() { return keychain::available(); }++bool storeKeys(const AiSettings& s) {+ bool ok = true;+ if (!s.apiKey.empty() && s.provider != AiSettings::Provider::Free) ok = put(presetAccount(providerId(s)), s.apiKey) && ok;+ if (!s.hfToken.empty()) ok = put(kHuggingFace, s.hfToken) && ok;+ if (!s.falKey.empty()) ok = put(kFal, s.falKey) && ok;+ if (!s.meshyKey.empty()) ok = put(kMeshy, s.meshyKey) && ok;+ return ok;+}++bool migrateLegacyKeys(const std::string& path, std::string& message) {+ message.clear();+ std::ifstream f(std::filesystem::path(std::u8string(path.begin(), path.end())), std::ios::binary);+ if (!f) return true;+ const std::string text((std::istreambuf_iterator<char>(f)), std::istreambuf_iterator<char>());+ f.close();+ Json j;+ std::string err;+ if (!Json::parse(text, j, err) || !j.isObject()) return true;+ bool any = false;+ for (const char* k : {"apiKey", "hfToken", "falKey", "meshyKey"}) any = any || !j[k].asString().empty();+ if (!any) return true;+ const AiSettings s = AiSettings::fromJson(j);+ if (!keychain::available() || !storeKeys(s)) {+ message = "AI keys: no keychain on this computer, so they can't be kept between sessions (the environment "+ "variables ANTHROPIC_API_KEY, OPENAI_API_KEY, HF_TOKEN, FAL_KEY, MESHY_API_KEY work instead)";+ // They are still dropped from the file: keys never stay in plain files. This session has them.+ } else {+ message = "AI keys moved into the system keychain (they are no longer in ai.json)";+ }+ if (!s.save(path, err)) {+ message = "AI keys: " + err;+ return false;+ }+ return true;+}++void clearCacheForTests() {+ std::lock_guard lock(gMutex);+ cache().clear();+ tried().clear();+}++} // namespace sf::ai::secretsdiff --git a/src/ai/Secrets.h b/src/ai/Secrets.hnew file mode 100644index 00000000..7c0213b2--- /dev/null+++ b/src/ai/Secrets.h@@ -0,0 +1,51 @@+// SculptForge - open source digital sculpting+// SPDX-License-Identifier: GPL-3.0-or-later+//+// AI keys live in the OS keychain (core/Keychain.h), never in ai.json. One keychain account per key:+// ai/<preset id> a Brush Lab provider's API key (ai/Providers.h: "ai/anthropic", "ai/openrouter", ...)+// ai/huggingface the Hugging Face token; ai/fal, ai/meshy the Generate 3D services' keys+// The app reads the keychain once (preload, on a worker thread at start-up) into a process cache, so drawing a panel+// never waits on it; the CLI and Python read an account the first time a command needs it (setLazy). Keys found in+// an older ai.json move into the keychain and out of the file (migrateLegacyKeys). With no keychain (SF_KEYCHAIN=none, a Linux without the Secret Service), a key typed in lasts+// until the app quits; the environment variables (ANTHROPIC_API_KEY, ...) work everywhere.+#pragma once++#include <string>+#include <vector>++namespace sf::ai {+struct AiSettings;+}++namespace sf::ai::secrets {++constexpr const char* kHuggingFace = "ai/huggingface";+constexpr const char* kFal = "ai/fal";+constexpr const char* kMeshy = "ai/meshy";+// The account of a Brush Lab preset's key.+std::string presetAccount(const std::string& presetId);+// Every account SculptForge may keep AI keys under.+std::vector<std::string> allAccounts();++// Reads every account into the cache (blocking: a worker thread, or a CLI start).+void preload();+// The cached key ("" if none). Lazy (the default): an account not read yet is read from the keychain now (blocking);+// the app turns that off and preloads instead.+std::string cached(const std::string& account);+void setLazy(bool lazy);+// Stores (or, for "", erases) a key in the keychain and the cache. False: not kept in the keychain (none, or it+// refused); the cache still holds it for this session.+bool put(const std::string& account, const std::string& value);+bool available();++// The keys SETTINGS holds in memory (typed in, or read from an older ai.json), into the keychain. Blocking.+// False if any couldn't be stored (they stay in memory for this session).+bool storeKeys(const AiSettings& settings);+// Moves keys found in the ai.json at PATH into the keychain and rewrites the file without them. Blocking; does+// nothing when the file holds no key. MESSAGE says what happened ("" when nothing did).+bool migrateLegacyKeys(const std::string& path, std::string& message);++// Tests: empty the cache.+void clearCacheForTests();++} // namespace sf::ai::secretsdiff --git a/src/app/App.cpp b/src/app/App.cppindex db375f1c..220847d0 100644--- a/src/app/App.cpp+++ b/src/app/App.cpp@@ -16,6 +16,12 @@#include "core/PerfTrace.h"#include "ai/AiCommands.h"+#include "ai/Oidc.h"+#include "ai/Secrets.h"+#include "core/AuditLog.h"+#include "core/Keychain.h"+#include "core/ManagedPolicy.h"+#include "ai/Providers.h"#include "app/Demo.h"#include "app/Shell.h"#include "app/Theme.h"@@ -234,8 +240,24 @@ bool App::init(const AppOptions& options) {} else {io.IniFilename = nullptr;}+ if (!options.uiTest.empty()) policy::resetPolicyForTests(); // (a UI test's ui_policy never reaches the next one)// Preferences > AI: tests, renders and videos start with AI on whatever this computer chose (SF_AI still wins).ai::setAiEnabled(ai::aiFeaturesAllowed(headless || !options.demo.empty() || aiSettings_.enabled));+ // AI keys and the studio sign-in are in the OS keychain (ai/Secrets.h, ai/Oidc.h), read on a worker so no frame+ // waits on an unlock prompt. Tests, renders and benchmarks never touch the user's keychain.+ audit::setClient("app");+ ai::secrets::setLazy(false);+ if (headless || !options.uiTest.empty() || !options.demo.empty() || options.benchmark) {+ keychain::useMemoryForTests(true);+ } else {+ std::thread([path = aiSettingsPath_] {+ std::string message;+ if (!path.empty()) ai::secrets::migrateLegacyKeys(path, message);+ if (!message.empty()) SDL_Log("%s", message.c_str());+ ai::secrets::preload();+ ai::oidc::loadSaved();+ }).detach();+ }ai::registerAiCommands(commands_, [this] { return aiSettings_; });registerPaintUiCommands();registerViewUiCommands(); // light, xray, view_resolution, save_render (PanelView.cpp)@@ -3206,16 +3228,36 @@ bool App::beginPanel(const char* name, bool* open, float width) {void App::drawAiSettings() {using P = ai::AiSettings::Provider;- const char* providers[] = {"Free - no account or key", "Anthropic (Claude) - your key",- "OpenAI-compatible (OpenAI, Ollama, LM Studio...)"};- int provider = int(aiSettings_.provider);+ // Presets (ai/Providers.h): one click fills the endpoint and a model. A studio's policy may allow only some+ // (core/ManagedPolicy.h ai.providers): the others are greyed with "Managed by your studio".+ const std::string current = ai::providerId(aiSettings_);+ const ai::ProviderPreset* chosen = ai::findProviderPreset(current);ImGui::SetNextItemWidth(-1);- if (ImGui::Combo("##provider", &provider, providers, 3)) {- // Only the brush provider changes; the image-to-3D settings stay.- const ai::AiSettings d = ai::AiSettings::defaults(P(provider));- aiSettings_.provider = d.provider;- aiSettings_.endpoint = d.endpoint;- aiSettings_.model = d.model;+ if (ImGui::BeginCombo("##provider", chosen ? tr(chosen->label) : current.c_str())) {+ for (const ai::ProviderPreset& p : ai::providerPresets()) {+ const bool allowed = policy::aiProviderAllowed(p.id);+ ImGui::BeginDisabled(!allowed);+ if (ImGui::Selectable(tr(p.label), current == p.id)) {+ // Only the brush provider changes; the image-to-3D settings stay.+ aiSettings_ = ai::withPreset(aiSettings_, p.id);+ modelsChecked_ = false;+ }+ ImGui::EndDisabled();+ if (!allowed && ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenDisabled))+ ImGui::SetTooltip("%s", ui::ManagedByText().c_str());+ }+ ImGui::EndCombo();+ }+ if (!policy::current().aiProviders.empty()) ui::ManagedBadge();+ if (std::string why; !policy::aiProviderAllowed(current, &why)) { // (saved before the policy came)+ ImGui::PushStyleColor(ImGuiCol_Text, ImVec4(0.95f, 0.6f, 0.4f, 1));+ ImGui::TextWrapped("%s", tr(policy::current().ai == policy::Lock::Off ? why : std::string("Your studio doesn't allow this provider: pick another")).c_str());+ ImGui::PopStyleColor();+ }+ if (chosen) {+ ImGui::PushStyleColor(ImGuiCol_Text, ImGui::GetStyleColorVec4(ImGuiCol_TextDisabled));+ ImGui::TextWrapped("%s", tr(chosen->note));+ ImGui::PopStyleColor();}auto textField = [](const char* label, std::string& value, ImGuiInputTextFlags flags = 0) {char buf[512];@@ -3224,20 +3266,8 @@ void App::drawAiSettings() {if (ImGui::InputText(label, buf, sizeof buf, flags)) value = buf;};if (aiSettings_.provider == P::OpenAICompatible) {- // One-click presets for the two common local servers.- const float third = (ImGui::GetContentRegionAvail().x - 2 * ImGui::GetStyle().ItemSpacing.x) / 3;- if (ImGui::Button("Ollama", ImVec2(third, 0))) {- aiSettings_.endpoint = "http://localhost:11434/v1/chat/completions";- modelsChecked_ = false;- }- ImGui::SameLine();- if (ImGui::Button("LM Studio", ImVec2(third, 0))) {- aiSettings_.endpoint = "http://localhost:1234/v1/chat/completions";- modelsChecked_ = false;- }- ImGui::SameLine();ImGui::BeginDisabled(pendingModels_.valid());- if (ImGui::Button(pendingModels_.valid() ? "Checking..." : "Find models", ImVec2(third, 0))) {+ if (ImGui::Button(pendingModels_.valid() ? tr("Checking...") : tr("Find models"), ImVec2(-1, 0))) {auto promise = std::make_shared<std::promise<ModelList>>();pendingModels_ = promise->get_future();std::thread([promise, settings = aiSettings_] {@@ -3257,18 +3287,37 @@ void App::drawAiSettings() {}}if (aiSettings_.provider != P::Free) {- textField("Endpoint", aiSettings_.endpoint);+ textField(tr("Endpoint"), aiSettings_.endpoint);+ if (std::string why; !aiSettings_.endpoint.empty() && !policy::aiEndpointAllowed(aiSettings_.endpoint, &why)) {+ ImGui::PushStyleColor(ImGuiCol_Text, ImVec4(0.95f, 0.6f, 0.4f, 1));+ ImGui::TextWrapped("%s", tr(why).c_str());+ ImGui::PopStyleColor();+ }if (aiSettings_.provider == P::OpenAICompatible && modelsChecked_ && !localModels_.models.empty()) {ImGui::SetNextItemWidth(-ImGui::CalcTextSize("Endpoint").x - ImGui::GetStyle().ItemInnerSpacing.x);- if (ImGui::BeginCombo("Model", aiSettings_.model.c_str())) {+ if (ImGui::BeginCombo(tr("Model"), aiSettings_.model.c_str())) {for (const auto& m : localModels_.models)if (ImGui::Selectable(m.c_str(), m == aiSettings_.model)) aiSettings_.model = m;ImGui::EndCombo();}} else {- textField("Model", aiSettings_.model);+ textField(tr("Model"), aiSettings_.model);+ }+ if (ai::oidc::usesSignIn(aiSettings_.endpoint)) {+ // The studio gateway takes the studio sign-in instead of a key (ai/Oidc.h).+ ImGui::TextDisabled("%s", tr("Uses your studio sign-in (Preferences > AI > Studio sign-in)"));+ } else {+ textField(tr("API key"), aiSettings_.apiKey, ImGuiInputTextFlags_Password);+ const ai::ProviderPreset* p = ai::findProviderPreset(current);+ const char* env = p && *p->keyEnv ? p->keyEnv : nullptr;+ if (aiSettings_.apiKey.empty()) {+ const char* where = !ai::secrets::cached(ai::secrets::presetAccount(current)).empty()+ ? tr("Saved in your system keychain.")+ : env && std::getenv(env) ? tr("Using the key from the environment.")+ : nullptr;+ if (where) ImGui::TextDisabled("%s", where);+ }}- textField("API key", aiSettings_.apiKey, ImGuiInputTextFlags_Password);}if (aiSettings_.provider == P::OpenAICompatible && modelsChecked_) {const bool ok = localModels_.error.empty();@@ -3280,19 +3329,20 @@ void App::drawAiSettings() {ImGui::TextWrapped("%s", localModels_.error.c_str());ImGui::PopStyleColor();}- if (aiSettings_.provider == P::OpenAICompatible && ImGui::TreeNode("Run a model on this computer")) {+ if ((current == "ollama" || current == "lmstudio" || current == "openai-compatible") &&+ ImGui::TreeNode("Run a model on this computer")) {// Steps for the platform we're on; the guide covers the others.#if defined(_WIN32)ImGui::TextWrapped("1. Install Ollama from ollama.com/download, or in PowerShell:\n"" winget install Ollama.Ollama\n""2. Download the model (in PowerShell):\n"" ollama pull qwen3:4b-instruct\n"- "3. Ollama runs in the system tray. Click Ollama above, then Find models.");+ "3. Ollama runs in the system tray. Pick Ollama above, then Find models.");#elif defined(__APPLE__)ImGui::TextWrapped("1. Install Ollama from ollama.com/download and drag it to Applications.\n""2. Download the model (in Terminal):\n"" ollama pull qwen3:4b-instruct\n"- "3. Ollama runs in the menu bar. Click Ollama above, then Find models.");+ "3. Ollama runs in the menu bar. Pick Ollama above, then Find models.");#elseImGui::TextWrapped("1. Install Ollama (or use your package manager, e.g. sudo pacman -S ollama):\n"" curl -fsSL https://ollama.com/install.sh | sh\n"@@ -3300,7 +3350,7 @@ void App::drawAiSettings() {" sudo systemctl enable --now ollama\n""3. Download the model:\n"" ollama pull qwen3:4b-instruct\n"- "4. Click Ollama above, then Find models.");+ "4. Pick Ollama above, then Find models.");#endifImGui::TextWrapped("The 2.5 GB model needs about 4 GB of free memory and works without a graphics card ""(10-20 s per brush on a laptop CPU, a few seconds with a GPU).");@@ -3318,16 +3368,16 @@ void App::drawAiSettings() {std::string err;status_ = aiSettingsPath_.empty() || !aiSettings_.save(aiSettingsPath_, err) ? "Could not save AI settings " + err: "AI settings saved";+ storeAiKeys();}ImGui::PushStyleColor(ImGuiCol_Text, ImGui::GetStyleColorVec4(ImGuiCol_TextDisabled));if (aiSettings_.provider == P::Free)- ImGui::TextWrapped("Free: an open model (GPT-OSS 20B) hosted by Pollinations.ai, no sign-up. Only your "- "brush description and settings are sent. Rate limited to a request every few seconds; "- "if it can't be reached, a running Ollama is used instead.");+ ImGui::TextWrapped("%s", tr("Rate limited to a request every few seconds; if it can't be reached, a running "+ "Ollama is used instead."));else- ImGui::TextWrapped("Requests go only to the endpoint above. Keys are stored on this computer only "- "(owner-readable ai.json); leave empty to use ANTHROPIC_API_KEY / OPENAI_API_KEY. "- "For private, offline use, run Ollama and pick OpenAI-compatible.");+ ImGui::TextWrapped("%s", tr("Requests go only to the endpoint above. Keys are kept in your system keychain "+ "(never in a settings file); leave empty to use the environment (ANTHROPIC_API_KEY, "+ "OPENAI_API_KEY). For private, offline use, pick Ollama or LM Studio."));ImGui::PopStyleColor();}@@ -3558,6 +3608,14 @@ void App::showHunyuanNoticeOnce() {saved.save(aiSettingsPath_, err);}+void App::storeAiKeys() {+ // Into the keychain on a worker (an unlock prompt never holds up a frame); ai.json never has them.+ std::thread([settings = aiSettings_] {+ if (!ai::secrets::storeKeys(settings))+ SDL_Log("AI keys: no keychain on this computer, so they last until SculptForge quits (or set them in the environment)");+ }).detach();+}+void App::drawAiPrefsSection() {ImGui::SetNextItemWidth(-1);ImGui::InputTextWithHint("##hftoken", "Hugging Face token (hf_...)", hfToken_, sizeof hfToken_, ImGuiInputTextFlags_Password);@@ -3573,6 +3631,7 @@ void App::drawAiPrefsSection() {std::string err;status_ = !aiSettingsPath_.empty() && saved.save(aiSettingsPath_, err) ? "Hugging Face token saved": "Save failed " + err;+ storeAiKeys();}}@@ -3831,6 +3890,7 @@ void App::drawImageTo3D() {std::string err;status_ = !aiSettingsPath_.empty() && aiSettings_.save(aiSettingsPath_, err) ? "Image to 3D settings saved": "Save failed " + err;+ storeAiKeys();}if (textMode_) {diff --git a/src/app/App.h b/src/app/App.hindex 10c64f09..9f6be065 100644--- a/src/app/App.h+++ b/src/app/App.h@@ -116,6 +116,7 @@ struct AppOptions {};class Demo;+struct StudioSignInJob; // PanelAi.cpp: the studio sign-in on a worker (ai/Oidc.h)// Wakes the main loop from any thread (SDL_PushEvent): the app draws only when something changed (#14), so work// that finishes off the main thread (a file dialog's answer, a phone message) calls this to be seen at once.@@ -541,9 +542,15 @@ private:// Preferences > AI (PanelAi.cpp, ai/AiPolicy.h): Enable AI features. Off removes the AI commands, the Brush Lab// and Generate 3D entries and closes their windows; saved in ai.json at once (not in tests). SF_AI / --no-ai lock it.void setAiFeatures(bool on);+ void applyAiFeatures(bool on, bool save); // the switch itself, whatever locks it (setAiFeatures, a policy)+ void registerPolicyTestCommand(); // ui_policy: UI tests only (tests/ui/studio_policy.sfui)void registerAiActions(); // ui.brush_lab, ui.generate3d: only while AI is onvoid drawAiPrefs(); // the Preferences > AI section and the first-run question+ void drawAiStudioPrefs(); // Preferences > AI: what the studio's policy manages, the studio sign-in, the audit log+ void storeAiKeys();+ void applyUpdatePolicy(); // a studio policy's update check and channel (core/ManagedPolicy.h) over the saved ones // the keys aiSettings_ holds, into the OS keychain (a worker; ai/Secrets.h)// Brush Lab (AI brush designer)+ std::shared_ptr<StudioSignInJob> signInJob_; // Preferences > AI > Studio sign-in, while it runsbool showBrushLab_ = false; // floating; opened from the top shelf's AI Brush or the Brush palettebool hideUi_ = false;uint64_t seenSplatsVersion_ = 0;diff --git a/src/app/I18nSpanish.cpp b/src/app/I18nSpanish.cppindex 3f62943d..6c078ce6 100644--- a/src/app/I18nSpanish.cpp+++ b/src/app/I18nSpanish.cpp@@ -3614,6 +3614,61 @@ constexpr Entry kSpanish[] = {"Tu propio código con la API de xAI: sculptforge-cli --schema da las definiciones de las herramientas (ejemplos en la guía del usuario, Scripting > AI agents). xAI factura el uso de la API."},{"xAI's coding agent (the grok command). Run once in a terminal; it signs in with your xAI account in the browser.","El agente de programación de xAI (el comando grok). Ejecútalo una vez en una terminal; inicia sesión con tu cuenta de xAI en el navegador."},+ // --- Studio controls: Preferences > AI (PanelAi.cpp, ai/Providers.cpp, core/ManagedPolicy.cpp) ---+ {"AI tools (MCP)", "Herramientas de IA (MCP)"},+ {"AI tools can't connect: your studio turned them off.", "Las herramientas de IA no pueden conectarse: tu estudio las desactivó."},+ {"AI tools may use only the kinds of command your studio allows.", "Las herramientas de IA solo pueden usar los tipos de comando que permite tu estudio."},+ {"AI tools work on their own scene; your studio doesn't let them control this window.", "Las herramientas de IA trabajan en su propia escena; tu estudio no les permite controlar esta ventana."},+ {"API key", "Clave de API"},+ {"Audit log", "Registro de auditoría"},+ {"Connecting...", "Conectando..."},+ {"Copy code", "Copiar código"},+ {"Copy path", "Copiar ruta"},+ {"Endpoint", "Endpoint"},+ {"Every AI action (AI tools, AI Brush, Generate 3D) is recorded on this computer: time, tool, command and settings, never your artwork or keys.", "Cada acción de IA (herramientas de IA, AI Brush, Generar 3D) se registra en este equipo: hora, herramienta, comando y ajustes, nunca tus obras ni tus claves."},+ {"Find models", "Buscar modelos"},+ {"In your browser, sign in and enter this code:", "En tu navegador, inicia sesión y escribe este código:"},+ {"Managed by", "Gestionado por"},+ {"Managed by your studio", "Gestionado por tu estudio"},+ {"Model", "Modelo"},+ {"Open the sign-in page", "Abrir la página de inicio de sesión"},+ {"Provider", "Proveedor"},+ {"Requests go only to the endpoint above. Keys are kept in your system keychain (never in a settings file); leave empty to use the environment (ANTHROPIC_API_KEY, OPENAI_API_KEY). For private, offline use, pick Ollama or LM Studio.", "Las solicitudes van solo al endpoint de arriba. Las claves se guardan en el llavero del sistema (nunca en un archivo de ajustes); déjala vacía para usar el entorno (ANTHROPIC_API_KEY, OPENAI_API_KEY). Para un uso privado y sin conexión, elige Ollama o LM Studio."},+ {"Saved in your system keychain.", "Guardada en el llavero del sistema."},+ {"SculptForge has no telemetry: nothing about you or your work is collected.", "SculptForge no tiene telemetría: no se recopila nada sobre ti ni sobre tu trabajo."},+ {"Sign in with your studio account", "Iniciar sesión con la cuenta del estudio"},+ {"Signed in as", "Sesión iniciada como"},+ {"Signed out of your studio account", "Sesión de la cuenta del estudio cerrada"},+ {"Signs in through your studio's own login page in your browser. Nothing on this computer listens for it; the sign-in is kept in your system keychain.", "Inicia sesión con la página de acceso de tu estudio en tu navegador. Nada en este equipo queda a la escucha; la sesión se guarda en el llavero del sistema."},+ {"Studio sign-in", "Inicio de sesión del estudio"},+ {"The studio policy can't be used, so AI, network features and AI tools are off:", "La política del estudio no se puede usar, así que la IA, las funciones de red y las herramientas de IA están desactivadas:"},+ {"Uses your studio sign-in (Preferences > AI > Studio sign-in)", "Usa el inicio de sesión del estudio (Preferencias > IA > Inicio de sesión del estudio)"},+ {"Using the key from the environment.", "Se usa la clave del entorno."},+ {"Your studio requires the sign-in for AI features.", "Tu estudio exige iniciar sesión para usar la IA."},+ {"Free - no account or key", "Gratis - sin cuenta ni clave"},+ {"Anthropic (Claude)", "Anthropic (Claude)"},+ {"OpenAI", "OpenAI"},+ {"Ollama (this computer)", "Ollama (este equipo)"},+ {"LM Studio (this computer)", "LM Studio (este equipo)"},+ {"vLLM server", "Servidor vLLM"},+ {"llama.cpp server", "Servidor llama.cpp"},+ {"LiteLLM proxy (studio gateway)", "Proxy LiteLLM (pasarela del estudio)"},+ {"OpenRouter", "OpenRouter"},+ {"Other OpenAI-compatible server", "Otro servidor compatible con OpenAI"},+ {"An open model hosted by Pollinations.ai. Only your brush description and settings are sent.", "Un modelo abierto alojado por Pollinations.ai. Solo se envían la descripción y los ajustes del pincel."},+ {"Your Anthropic API key (console.anthropic.com).", "Tu clave de API de Anthropic (console.anthropic.com)."},+ {"Your OpenAI API key (platform.openai.com); then Find models.", "Tu clave de API de OpenAI (platform.openai.com); luego, Buscar modelos."},+ {"Private: the model runs on this computer. No key.", "Privado: el modelo se ejecuta en este equipo. Sin clave."},+ {"Private: start LM Studio's server (Developer tab), then Find models. No key.", "Privado: inicia el servidor de LM Studio (pestaña Developer) y luego Buscar modelos. Sin clave."},+ {"A vLLM server (vllm serve <model>): this computer or a GPU server at your studio.", "Un servidor vLLM (vllm serve <modelo>): este equipo o un servidor GPU de tu estudio."},+ {"llama-server -m model.gguf: this computer or a server at your studio. No key.", "llama-server -m model.gguf: este equipo o un servidor de tu estudio. Sin clave."},+ {"Your studio's gateway: one address for every model your studio allows (Bedrock, Vertex AI, Azure OpenAI and others behind it). A virtual key, or your studio sign-in.", "La pasarela de tu estudio: una dirección para todos los modelos que permite tu estudio (Bedrock, Vertex AI, Azure OpenAI y otros detrás). Una clave virtual o el inicio de sesión del estudio."},+ {"Many models through one key (openrouter.ai/keys).", "Muchos modelos con una sola clave (openrouter.ai/keys)."},+ {"Any server with an OpenAI-style /v1/chat/completions endpoint.", "Cualquier servidor con un endpoint /v1/chat/completions al estilo de OpenAI."},+ {"Your studio's policy doesn't allow AI requests to this address", "La política de tu estudio no permite solicitudes de IA a esta dirección"},+ {"AI features are turned off by your studio's policy", "La política de tu estudio desactivó las funciones de IA"},+ {"Rate limited to a request every few seconds; if it can't be reached, a running Ollama is used instead.", "Limitado a una solicitud cada pocos segundos; si no se puede conectar, se usa Ollama si está en marcha."},+ {"Your studio doesn't allow this provider: pick another", "Tu estudio no permite este proveedor: elige otro"},};} // namespacediff --git a/src/app/I18nTraditionalChinese.cpp b/src/app/I18nTraditionalChinese.cppindex 16e81367..d535a14c 100644--- a/src/app/I18nTraditionalChinese.cpp+++ b/src/app/I18nTraditionalChinese.cpp@@ -3146,6 +3146,61 @@ constexpr Entry kTraditionalChinese[] = {"以 xAI API 撰寫你自己的程式:sculptforge-cli --schema 提供工具定義(範例見使用者指南,Scripting > AI agents)。API 用量由 xAI 計費。"},{"xAI's coding agent (the grok command). Run once in a terminal; it signs in with your xAI account in the browser.","xAI 的程式設計代理(grok 命令)。在終端機執行一次;它會在瀏覽器中以你的 xAI 帳號登入。"},+ // --- Studio controls: Preferences > AI (PanelAi.cpp, ai/Providers.cpp, core/ManagedPolicy.cpp) ---+ {"AI tools (MCP)", "AI 工具(MCP)"},+ {"AI tools can't connect: your studio turned them off.", "AI 工具無法連線:你的工作室已將其關閉。"},+ {"AI tools may use only the kinds of command your studio allows.", "AI 工具只能使用你的工作室允許的指令類型。"},+ {"AI tools work on their own scene; your studio doesn't let them control this window.", "AI 工具在自己的場景中運作;你的工作室不允許它們控制這個視窗。"},+ {"API key", "API 金鑰"},+ {"Audit log", "稽核記錄"},+ {"Connecting...", "連線中..."},+ {"Copy code", "複製代碼"},+ {"Copy path", "複製路徑"},+ {"Endpoint", "端點"},+ {"Every AI action (AI tools, AI Brush, Generate 3D) is recorded on this computer: time, tool, command and settings, never your artwork or keys.", "每個 AI 動作(AI 工具、AI Brush、生成 3D)都會記錄在這台電腦上:時間、工具、指令與設定,絕不包含你的作品或金鑰。"},+ {"Find models", "尋找模型"},+ {"In your browser, sign in and enter this code:", "請在瀏覽器中登入並輸入此代碼:"},+ {"Managed by", "管理者:"},+ {"Managed by your studio", "由你的工作室管理"},+ {"Model", "模型"},+ {"Open the sign-in page", "開啟登入頁面"},+ {"Provider", "提供者"},+ {"Requests go only to the endpoint above. Keys are kept in your system keychain (never in a settings file); leave empty to use the environment (ANTHROPIC_API_KEY, OPENAI_API_KEY). For private, offline use, pick Ollama or LM Studio.", "請求只會送到上方的端點。金鑰保存在系統鑰匙圈中(絕不存在設定檔裡);留空則使用環境變數(ANTHROPIC_API_KEY、OPENAI_API_KEY)。若要私密、離線使用,請選擇 Ollama 或 LM Studio。"},+ {"Saved in your system keychain.", "已儲存在系統鑰匙圈中。"},+ {"SculptForge has no telemetry: nothing about you or your work is collected.", "SculptForge 沒有遙測:不會收集任何關於你或你作品的資料。"},+ {"Sign in with your studio account", "使用工作室帳號登入"},+ {"Signed in as", "已登入:"},+ {"Signed out of your studio account", "已登出工作室帳號"},+ {"Signs in through your studio's own login page in your browser. Nothing on this computer listens for it; the sign-in is kept in your system keychain.", "透過你的工作室在瀏覽器中的登入頁面登入。這台電腦上沒有任何程式在等待連線;登入資訊保存在系統鑰匙圈中。"},+ {"Studio sign-in", "工作室登入"},+ {"The studio policy can't be used, so AI, network features and AI tools are off:", "無法使用工作室政策,因此 AI、網路功能與 AI 工具都已關閉:"},+ {"Uses your studio sign-in (Preferences > AI > Studio sign-in)", "使用你的工作室登入(偏好設定 > AI > 工作室登入)"},+ {"Using the key from the environment.", "使用環境變數中的金鑰。"},+ {"Your studio requires the sign-in for AI features.", "你的工作室要求登入後才能使用 AI 功能。"},+ {"Free - no account or key", "免費 - 不需帳號或金鑰"},+ {"Anthropic (Claude)", "Anthropic(Claude)"},+ {"OpenAI", "OpenAI"},+ {"Ollama (this computer)", "Ollama(這台電腦)"},+ {"LM Studio (this computer)", "LM Studio(這台電腦)"},+ {"vLLM server", "vLLM 伺服器"},+ {"llama.cpp server", "llama.cpp 伺服器"},+ {"LiteLLM proxy (studio gateway)", "LiteLLM 代理(工作室閘道)"},+ {"OpenRouter", "OpenRouter"},+ {"Other OpenAI-compatible server", "其他相容 OpenAI 的伺服器"},+ {"An open model hosted by Pollinations.ai. Only your brush description and settings are sent.", "由 Pollinations.ai 託管的開放模型。只會傳送你的筆刷描述與設定。"},+ {"Your Anthropic API key (console.anthropic.com).", "你的 Anthropic API 金鑰(console.anthropic.com)。"},+ {"Your OpenAI API key (platform.openai.com); then Find models.", "你的 OpenAI API 金鑰(platform.openai.com);然後按「尋找模型」。"},+ {"Private: the model runs on this computer. No key.", "私密:模型在這台電腦上執行。不需金鑰。"},+ {"Private: start LM Studio's server (Developer tab), then Find models. No key.", "私密:啟動 LM Studio 的伺服器(Developer 分頁),然後按「尋找模型」。不需金鑰。"},+ {"A vLLM server (vllm serve <model>): this computer or a GPU server at your studio.", "vLLM 伺服器(vllm serve <模型>):這台電腦或你工作室的 GPU 伺服器。"},+ {"llama-server -m model.gguf: this computer or a server at your studio. No key.", "llama-server -m model.gguf:這台電腦或你工作室的伺服器。不需金鑰。"},+ {"Your studio's gateway: one address for every model your studio allows (Bedrock, Vertex AI, Azure OpenAI and others behind it). A virtual key, or your studio sign-in.", "你的工作室閘道:一個位址即可使用工作室允許的所有模型(背後可接 Bedrock、Vertex AI、Azure OpenAI 等)。使用虛擬金鑰或工作室登入。"},+ {"Many models through one key (openrouter.ai/keys).", "一把金鑰即可使用多種模型(openrouter.ai/keys)。"},+ {"Any server with an OpenAI-style /v1/chat/completions endpoint.", "任何提供 OpenAI 風格 /v1/chat/completions 端點的伺服器。"},+ {"Your studio's policy doesn't allow AI requests to this address", "你的工作室政策不允許向此位址發出 AI 請求"},+ {"AI features are turned off by your studio's policy", "你的工作室政策已關閉 AI 功能"},+ {"Rate limited to a request every few seconds; if it can't be reached, a running Ollama is used instead.", "每隔幾秒才能發出一次請求;若無法連線,會改用正在執行的 Ollama。"},+ {"Your studio doesn't allow this provider: pick another", "你的工作室不允許此提供者:請選擇其他提供者"},};} // namespacediff --git a/src/app/Palettes.cpp b/src/app/Palettes.cppindex 6db519a1..ce4f7f27 100644--- a/src/app/Palettes.cpp+++ b/src/app/Palettes.cpp@@ -657,7 +657,10 @@ void App::drawPalette_Preferences() {if (subpalette("preferences.ai", "AI")) {tray::Section section;drawAiPrefs(); // the switch (PanelAi.cpp)+ drawAiStudioPrefs(); // what the studio's policy manages, the studio sign-in, the audit log (PanelAi.cpp)if (ai::aiEnabled()) {+ ImGui::SeparatorText(tr("Provider"));+ drawAiSettings(); // the brush provider: presets, endpoint, key (keychain)ImGui::Spacing();drawAiPrefsSection(); // the Hugging Face token}diff --git a/src/app/PanelAi.cpp b/src/app/PanelAi.cppindex 7f39f3c7..a32777fb 100644--- a/src/app/PanelAi.cpp+++ b/src/app/PanelAi.cpp@@ -7,15 +7,49 @@// AI network entry point refuses. Saved in ai.json at once, so the CLI, Python and MCP server follow it.// SF_AI=off (or --no-ai) locks it for studios.#include "app/App.h"+#include "app/I18n.h"#include "app/Ui.h"#include "ai/AiCommands.h"+#include "ai/Oidc.h"+#include "core/AuditLog.h"+#include "core/ManagedPolicy.h"#include <IconsLucide.h>#include <imgui.h>+#include <atomic>+#include <filesystem>+#include <fstream>+#include <mutex>+#include <thread>+namespace sf {+void App::registerPolicyTestCommand() {+ // UI tests only (never registered otherwise, so no script or AI tool can change a studio's policy): a policy as+ // if IT had deployed it, for tests/ui/studio_policy.sfui. The next script starts without one.+ if (options_.uiTest.empty()) return;+ policy::resetPolicyForTests();+ commands_.add({"ui_policy", "UI tests: apply a studio policy (policy.json text; \"\" removes it).",+ {{"json", ParamSpec::Type::String, "The policy file's text.", true}},+ [this](Document&, const Args& a) -> CommandResult {+ const std::string text = argString(a, "json");+ if (text.empty()) {+ policy::resetPolicyForTests();+ } else { // through a file, as IT deploys it (a broken one fails closed with its error)+ const std::filesystem::path path = audit::logPath() + ".policy.json"; // (the test's folder)+ std::error_code ec;+ std::filesystem::create_directories(path.parent_path(), ec);+ std::ofstream(path, std::ios::binary) << text;+ policy::setPolicyForTests(policy::loadPolicyFile(path.string(), "ui_policy"));+ }+ applyAiFeatures(ai::aiFeaturesAllowed(true), false); // (UI tests start with AI on)+ applyUpdatePolicy();+ return {true, policy::describe(policy::current())};+ }});+}+void App::registerAiActions() {// The switch itself: always there, so the command palette finds "AI" to turn it back on.Action sw;@@ -74,6 +108,10 @@ void App::setAiFeatures(bool on) {status_ = ai::aiOffError();return;}+ applyAiFeatures(on, true);+}++void App::applyAiFeatures(bool on, bool save) {const bool changed = on != ai::aiEnabled();aiSettings_.enabled = on;ai::setAiEnabled(on);@@ -93,6 +131,7 @@ void App::setAiFeatures(bool on) {showBrushLab_ = false;showImageTo3D_ = false;}+ if (!save) return;std::string err;if (!uiConfigDeterministic_ && !aiSettingsPath_.empty() && !aiSettings_.save(aiSettingsPath_, err))status_ = "AI features " + std::string(on ? "on" : "off") + ", but " + err;@@ -107,7 +146,8 @@ void App::drawAiPrefs() {if (ImGui::Checkbox("Enable AI features##prefs.ai", &on)) setAiFeatures(on);ImGui::EndDisabled();ui::HelpAction(*this, "prefs.ai_features");- if (locked) ImGui::TextDisabled("Set by this computer (SF_AI or --no-ai).");+ if (ai::aiManaged()) ui::ManagedBadge();+ else if (locked) ImGui::TextDisabled("Set by this computer (SF_AI or --no-ai).");ImGui::PushStyleColor(ImGuiCol_Text, ImGui::GetStyleColorVec4(ImGuiCol_TextDisabled));ImGui::TextWrapped("AI Brush and Generate 3D. Off: they are hidden and SculptForge makes no AI network calls.");ImGui::TextWrapped("%s", ai::kPrivacyLine);@@ -116,4 +156,118 @@ void App::drawAiPrefs() {SDL_OpenURL("https://github.com/islandmed/SculptForge/blob/main/docs/ai-services.md");}+// The studio sign-in runs on a worker (ai/Oidc.h: discovery, the device code, polling); the panel shows the code.+struct StudioSignInJob {+ std::mutex mutex;+ ai::oidc::DeviceCode code; // (userCode and the URIs only are shown)+ bool haveCode = false;+ bool opened = false; // the sign-in page, opened once from the UI thread+ std::string error;+ std::atomic<bool> done{false}, ok{false}, cancel{false};+};++void App::drawAiStudioPrefs() {+ const policy::Policy& p = policy::current();+ auto hint = [](const std::string& text) {+ ImGui::PushStyleColor(ImGuiCol_Text, ImGui::GetStyleColorVec4(ImGuiCol_TextDisabled));+ ImGui::TextWrapped("%s", text.c_str());+ ImGui::PopStyleColor();+ };+ if (p.present) {+ ImGui::TextUnformatted((std::string(ICON_LC_BUILDING_2 " ") + ui::ManagedByText()).c_str());+ if (p.broken) {+ ImGui::PushStyleColor(ImGuiCol_Text, ImVec4(0.95f, 0.6f, 0.4f, 1));+ ImGui::TextWrapped("%s %s", tr("The studio policy can't be used, so AI, network features and AI tools are off:"),+ p.error.c_str());+ ImGui::PopStyleColor();+ }+ if (ImGui::IsItemHovered(ImGuiHoveredFlags_DelayShort)) ImGui::SetTooltip("%s", p.source.c_str());+ }+ // The studio sign-in (only when the policy names an identity provider).+ if (p.signInConfigured()) {+ ImGui::SeparatorText(tr("Studio sign-in"));+ const auto state = ai::oidc::state();+ if (signInJob_ && signInJob_->done) {+ if (!signInJob_->ok && !signInJob_->cancel) status_ = signInJob_->error;+ signInJob_.reset();+ }+ if (signInJob_) {+ std::lock_guard lock(signInJob_->mutex);+ if (signInJob_->haveCode) {+ const auto& c = signInJob_->code;+ if (!signInJob_->opened) {+ SDL_OpenURL((c.verificationUriComplete.empty() ? c.verificationUri : c.verificationUriComplete).c_str());+ signInJob_->opened = true;+ }+ ImGui::TextWrapped("%s", tr("In your browser, sign in and enter this code:"));+ ImGui::TextColored(ImGui::GetStyleColorVec4(ImGuiCol_CheckMark), "%s", signInJob_->code.userCode.c_str());+ ImGui::SameLine();+ if (ImGui::SmallButton(tr("Copy code"))) ImGui::SetClipboardText(signInJob_->code.userCode.c_str());+ if (ImGui::SmallButton(tr("Open the sign-in page")))+ SDL_OpenURL((signInJob_->code.verificationUriComplete.empty() ? signInJob_->code.verificationUri+ : signInJob_->code.verificationUriComplete)+ .c_str());+ ImGui::SameLine();+ hint(signInJob_->code.verificationUri);+ } else {+ ImGui::TextDisabled("%s", tr("Connecting..."));+ }+ if (ImGui::Button(tr("Cancel"), ImVec2(-1, 0))) signInJob_->cancel = true;+ } else if (state == ai::oidc::State::SignedIn) {+ ImGui::TextWrapped("%s %s", tr("Signed in as"), ai::oidc::signedInAs().c_str());+ if (ImGui::Button(tr("Sign out"), ImVec2(-1, 0))) {+ ai::oidc::signOut(); // (a keychain erase: quick, and the artist asked for it)+ status_ = tr("Signed out of your studio account");+ }+ } else {+ if (ImGui::Button(tr("Sign in with your studio account"), ImVec2(-1, 0))) {+ auto job = std::make_shared<StudioSignInJob>();+ signInJob_ = job;+ std::thread([job] {+ std::string error;+ const bool ok = ai::oidc::signIn(+ [job](const ai::oidc::DeviceCode& c) {+ {+ std::lock_guard lock(job->mutex);+ job->code = c;+ job->code.deviceCode.clear(); // (never shown, never kept by the panel)+ job->haveCode = true;+ }+ return !job->cancel;+ },+ [job] { return job->cancel.load(); }, error);+ {+ std::lock_guard lock(job->mutex);+ job->error = error;+ }+ job->ok = ok;+ job->done = true;+ }).detach();+ }+ if (p.requireSignIn) hint(tr("Your studio requires the sign-in for AI features."));+ }+ hint(tr("Signs in through your studio's own login page in your browser. Nothing on this computer listens for it; "+ "the sign-in is kept in your system keychain."));+ }+ // What is recorded, and where (core/AuditLog.h).+ ImGui::SeparatorText(tr("Audit log"));+ hint(tr("Every AI action (AI tools, AI Brush, Generate 3D) is recorded on this computer: time, tool, command and "+ "settings, never your artwork or keys."));+ const std::string path = audit::logPath();+ ImGui::TextWrapped("%s", path.c_str());+ if (ImGui::SmallButton(tr("Copy path##audit"))) ImGui::SetClipboardText(path.c_str());+ if (!p.auditPath.empty()) {+ ImGui::SameLine();+ ui::ManagedBadge();+ }+ if (p.present && (p.mcp == policy::Lock::Off || !p.mcpCategories.empty() || !p.mcpLiveAllowed)) {+ ImGui::SeparatorText(tr("AI tools (MCP)"));+ hint(p.mcp == policy::Lock::Off ? tr("AI tools can't connect: your studio turned them off.")+ : !p.mcpLiveAllowed ? tr("AI tools work on their own scene; your studio doesn't let them control this window.")+ : tr("AI tools may use only the kinds of command your studio allows."));+ ui::ManagedBadge();+ }+ hint(tr("SculptForge has no telemetry: nothing about you or your work is collected."));+}+} // namespace sfdiff --git a/src/app/PanelProject.cpp b/src/app/PanelProject.cppindex 3a0a8b7b..9a92256d 100644--- a/src/app/PanelProject.cpp+++ b/src/app/PanelProject.cpp@@ -9,6 +9,7 @@#include "app/Support.h"#include "app/BigMeshTip.h"#include "app/LookSchemes.h"+#include "core/ManagedPolicy.h"#include "app/CrashLog.h"#include "core/LegacyNames.h"#include "core/SplatCapture.h"@@ -113,6 +114,7 @@ void App::initProject() {if (prefs["member_login"].isString()) memberLogin_ = prefs["member_login"].asString().substr(0, 39);if (prefs["update_channel"].isString())updateChannel_ = prefs["update_channel"].asString() == "preview" ? UpdateChannel::Preview : UpdateChannel::Stable;+ applyUpdatePolicy();// The membership cards (Support.h). ("support_card": false, the old switch, and "supporter" from before// 0.11.1 are honoured as they were: a member said so.)supportCardPrefs_.supporter = prefs["supporter"].asBool(false) || !prefs["support_card"].asBool(true);@@ -161,6 +163,7 @@ void App::initProject() {#if SF_UPDATE_CHECKconst int64_t now = std::chrono::duration_cast<std::chrono::seconds>(std::chrono::system_clock::now().time_since_epoch()).count();+ applyUpdatePolicy();if (checkUpdates_ && options_.uiTest.empty() && !std::getenv("SF_NO_UPDATE_CHECK") && updateCheckDue(updateCheckedAt_, now))startUpdateCheck(false);#endif@@ -864,18 +867,33 @@ void App::drawUpdateBanner() {ImGui::End();}+void App::applyUpdatePolicy() {+ // A studio's policy (core/ManagedPolicy.h "updates") locks these.+ const policy::Policy& p = policy::current();+ if (p.updateCheck != policy::Lock::Unset) checkUpdates_ = p.updateCheck == policy::Lock::On;+ if (!p.updateChannel.empty()) updateChannel_ = p.updateChannel == "preview" ? UpdateChannel::Preview : UpdateChannel::Stable;+}+void App::drawUpdatesSection() {#if SF_UPDATE_CHECK+ const policy::Policy& managed = policy::current();+ const bool checkLocked = managed.updateCheck != policy::Lock::Unset, channelLocked = !managed.updateChannel.empty();+ ImGui::BeginDisabled(checkLocked);if (ImGui::Checkbox(tr("Check for updates"), &checkUpdates_)) saveProjectPrefs();+ ImGui::EndDisabled();+ if (checkLocked) ui::ManagedBadge();ui::HelpText("Check for updates", nullptr,"Once a day at startup, download a small file from the SculptForge website that names the newest ""version, and show a banner when there is a newer one. Nothing about you or your computer is sent.","Preferences > Updates");ImGui::TextUnformatted(tr("Update channel"));int channel = updateChannel_ == UpdateChannel::Preview ? 1 : 0;+ ImGui::BeginDisabled(channelLocked);bool changed = ImGui::RadioButton((std::string(tr("Stable")) + "##prefs.update_stable").c_str(), &channel, 0);ImGui::SameLine();changed |= ImGui::RadioButton((std::string(tr("Preview (betas)")) + "##prefs.update_preview").c_str(), &channel, 1);+ ImGui::EndDisabled();+ if (channelLocked) ui::ManagedBadge();ui::HelpText("Update channel", nullptr,"Stable offers only finished releases. Preview also offers the betas the update feed names. Betas ""are a member perk: members get them from the private members' repository and the #members channel "diff --git a/src/app/Shell.cpp b/src/app/Shell.cppindex 0ff3175d..752dd1de 100644--- a/src/app/Shell.cpp+++ b/src/app/Shell.cpp@@ -499,6 +499,7 @@ void App::registerShellActions() {actions_.add(std::move(a));}registerAiActions(); // AI Brush, Generate 3D: only while AI is on (PanelAi.cpp)+ registerPolicyTestCommand(); // (UI tests only)flag("ui.brush_gallery", "Community brushes", ICON_LC_GLOBE, "Brush", "", &showBrushGallery_,"Browse, search and install brushes other sculptors shared.");diff --git a/src/app/Ui.cpp b/src/app/Ui.cppindex 70cf65f9..25f6bff4 100644--- a/src/app/Ui.cpp+++ b/src/app/Ui.cpp@@ -7,6 +7,9 @@#include "app/I18n.h"#include "app/Shell.h"#include "app/Theme.h"+#include "core/ManagedPolicy.h"++#include <IconsLucide.h>#include <imgui_internal.h>@@ -143,6 +146,21 @@ void HelpText(const char* title, const char* shortcut, const char* description,g_help.disabled = (ImGui::GetItemFlags() & ImGuiItemFlags_Disabled) != 0;}+std::string ManagedByText() {+ const std::string& org = policy::current().organization;+ return org.empty() ? std::string(tr(policy::kManagedLabel)) : std::string(tr("Managed by")) + " " + org;+}++void ManagedBadge() {+ ImGui::PushStyleColor(ImGuiCol_Text, ImGui::GetStyleColorVec4(ImGuiCol_TextDisabled));+ ImGui::TextUnformatted((std::string(ICON_LC_LOCK " ") + tr("Managed by your studio")).c_str());+ ImGui::PopStyleColor();+ if (ImGui::IsItemHovered(ImGuiHoveredFlags_DelayShort)) {+ const policy::Policy& p = policy::current();+ ImGui::SetTooltip("%s\n%s", ManagedByText().c_str(), p.source.c_str());+ }+}+bool IsModeAction(std::string_view id) {auto starts = [&](std::string_view p) { return id.substr(0, p.size()) == p; };if (id == "tool.draw" || id == "tool.move" || id == "tool.scale" || id == "tool.rotate") return true;diff --git a/src/app/Ui.h b/src/app/Ui.hindex 92167453..0e6c7746 100644--- a/src/app/Ui.h+++ b/src/app/Ui.h@@ -41,6 +41,11 @@ bool Checkbox(const char* label, bool* v);bool GlyphButton(const char* id, const char* glyph, ImVec2 size);// Draws a one-icon `glyph` centred by its ink in the rect a..b (a longer text is centred by its size).void CentredGlyph(ImDrawList* drawList, ImFont* font, ImVec2 a, ImVec2 b, ImU32 col, const char* glyph);+// "Managed by your studio" (with a lock) on the line after a setting a studio's policy file locks+// (core/ManagedPolicy.h); hovering names the organisation and the policy file.+void ManagedBadge();+// "Managed by your studio", or "Managed by Acme Animation" with the policy's organisation, translated.+std::string ManagedByText();// Ctrl-hover help for the last item.void HelpText(const char* title, const char* shortcut, const char* description, const char* path = nullptr);void HelpAction(App& app, const char* actionId);diff --git a/src/cli/McpServer.cpp b/src/cli/McpServer.cppindex 1fc7819a..dc198c76 100644--- a/src/cli/McpServer.cpp+++ b/src/cli/McpServer.cpp@@ -3,10 +3,12 @@#include "cli/McpServer.h"#include "cli/McpTools.h"-+#include "core/AuditLog.h"#include "core/BrushLibrary.h"#include "core/Json.h"+#include "core/ManagedPolicy.h"+#include <chrono>#include <iostream>#ifndef SCULPTFORGE_VERSION@@ -25,10 +27,19 @@ bool hiddenFromAgents(const std::string& name) {return name == "pack_install" || name == "pack_remove" || name == "pack_enable" || name == "pack_disable";}+std::vector<std::string> paramNames(const Command& c) {+ std::vector<std::string> names;+ for (const auto& p : c.params) names.push_back(p.name);+ return names;+}++// A studio's policy (core/ManagedPolicy.h) may allow only some kinds of tool: the rest are neither listed nor run.+bool policyAllows(const Command& c, std::string* why = nullptr) { return policy::mcpToolAllowed(c.name, paramNames(c), why); }+Json toolList(const CommandRegistry& registry) {Json tools = Json::array();for (const auto& c : registry.all()) {- if (hiddenFromAgents(c.name)) continue;+ if (hiddenFromAgents(c.name) || !policyAllows(c)) continue;Json props = Json::object(), required = Json::array();for (const auto& p : c.params) {Json prop = Json::object();@@ -47,7 +58,7 @@ Json toolList(const CommandRegistry& registry) {tool.set("inputSchema", schema);tools.push(tool);}- tools.push(viewportImageTool()); // drawn here (cli/McpTools.h), not a registry command+ if (policy::mcpToolAllowed("viewport_image", {})) tools.push(viewportImageTool()); // (cli/McpTools.h; reads: "info")Json result = Json::object();result.set("tools", tools);return result;@@ -83,6 +94,7 @@ std::string handleMcpMessage(const CommandRegistry& registry, Document& doc, conif (!msg.has("id")) return {}; // notification (e.g. notifications/initialized)if (method == "initialize") {+ audit::setClient(audit::clientFromInitialize(msg["params"])); // (the audit log's "client")Json result = Json::object();const std::string requested = msg["params"]["protocolVersion"].asString();result.set("protocolVersion", requested.empty() ? kLatestProtocol : requested);@@ -125,7 +137,9 @@ std::string handleMcpMessage(const CommandRegistry& registry, Document& doc, conif (name == "viewport_image") {Json content;std::string error;- const bool ok = renderViewportImage(doc, msg["params"]["arguments"], content, error);+ const auto start = std::chrono::steady_clock::now();+ bool ok = policy::mcpToolAllowed(name, {}, &error) && (!audit::required() || audit::writable(&error));+ ok = ok && renderViewportImage(doc, msg["params"]["arguments"], content, error);if (!ok) {Json text = Json::object();text.set("type", "text");@@ -133,12 +147,20 @@ std::string handleMcpMessage(const CommandRegistry& registry, Document& doc, concontent = Json::array();content.push(text);}+ audit::Entry entry; // (the picture itself is never logged)+ entry.tool = "mcp";+ entry.command = name;+ entry.ok = ok;+ entry.message = ok ? "image" : error;+ entry.ms = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now() - start).count();+ audit::record(entry);Json result = Json::object();result.set("content", content);result.set("isError", !ok);return reply(id, result).dump();}- if (!registry.find(name) || hiddenFromAgents(name)) return errorReply(id, -32602, "Unknown tool: " + name).dump();+ const Command* command = registry.find(name);+ if (!command || hiddenFromAgents(name)) return errorReply(id, -32602, "Unknown tool: " + name).dump();Args args;for (const auto& [key, value] : msg["params"]["arguments"].members()) {if (value.isBool()) args[key] = value.asBool();@@ -146,7 +168,22 @@ std::string handleMcpMessage(const CommandRegistry& registry, Document& doc, conelse if (value.isString()) args[key] = value.asString();else args[key] = value.dump();}- CommandResult r = registry.execute(doc, name, args);+ // Every call goes into the audit log (core/AuditLog.h), refused ones too; with audit.required, a call whose+ // line can't be written is refused before it runs.+ audit::Entry entry;+ entry.tool = "mcp";+ entry.command = name;+ entry.args = audit::summarizeArgs(args);+ std::string why;+ CommandResult r;+ const auto start = std::chrono::steady_clock::now();+ if (!policyAllows(*command, &why)) r = {false, why};+ else if (audit::required() && !audit::writable(&why)) r = {false, why};+ else r = registry.execute(doc, name, args);+ entry.ok = r.ok;+ entry.message = r.message;+ entry.ms = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now() - start).count();+ audit::record(entry);Json text = Json::object();text.set("type", "text");text.set("text", r.message);@@ -161,6 +198,10 @@ std::string handleMcpMessage(const CommandRegistry& registry, Document& doc, con}int runMcpServer(const CommandRegistry& registry, std::istream& in, std::ostream& out) {+ if (std::string why; !policy::mcpAllowed(&why)) {+ std::cerr << "sculptforge: " << why << "\n";+ return 3;+ }Document doc;// stdout is the protocol: library messages go to stderr.for (const auto& message : loadBrushLibrary(doc)) std::cerr << "sculptforge: " << message << "\n";diff --git a/src/cli/main.cpp b/src/cli/main.cppindex 6e6a72a1..eec09923 100644--- a/src/cli/main.cpp+++ b/src/cli/main.cpp@@ -5,11 +5,15 @@// pipelines and AI agents.#include "ai/AiCommands.h"#include "ai/AiPolicy.h"+#include "ai/Oidc.h"+#include "ai/Secrets.h"#include "ai/SplatTrainer.h"#include "cli/McpServer.h"#include "core/Benchmark.h"+#include "core/AuditLog.h"#include "core/BrushLibrary.h"#include "core/Commands.h"+#include "core/ManagedPolicy.h"#include "core/Pack.h"#include "core/Script.h"#include "core/StudioProfile.h"@@ -40,6 +44,10 @@ void usage() {" --no-packs Safe mode: leave every installed pack out (pack_install still works)\n"" --studio FILE Studio mode with this studio profile (studio.json; docs/studios.md)\n"" --offline Studio mode without a profile: no outside connection at all\n"+ " --policy Show what your studio's policy file manages (docs/studios.md \"IT deployment\")\n"+ " --sign-in Sign in with your studio account (the policy's identity provider; device code)\n"+ " --sign-out Sign out of your studio account\n"+ " --audit-log Print where the AI audit log is written\n"" --bench Run the performance benchmark (CPU side; the app's --bench adds the GPU)\n"" --bench-sizes 4,16,32 Benchmark sizes in millions of triangles\n"" --bench-dabs N Dabs per benchmark stroke (default 40)\n"@@ -79,6 +87,12 @@ int main(int argc, char** argv) {sf::ai::setStudioAiAllowed(studio.profile.ai);for (const std::string& m : studio.messages) std::fprintf(stderr, "%s\n", m.c_str());}+ sf::audit::setClient("cli"); // (the MCP server sets the agent's name: core/AuditLog.h)+ { // AI keys from an older ai.json into the keychain (ai/Secrets.h)+ std::string message;+ sf::ai::secrets::migrateLegacyKeys(sf::ai::defaultAiSettingsPath(), message);+ if (!message.empty()) std::fprintf(stderr, "%s\n", message.c_str());+ }sf::ai::setAiEnabled(sf::ai::aiFeaturesAllowed(sf::ai::AiSettings::load(sf::ai::defaultAiSettingsPath()).enabled));sf::ai::registerAiCommands(registry, [] { return sf::ai::AiSettings::load(sf::ai::defaultAiSettingsPath()); });// splat_train: trains in the foreground with the app's tool settings (ai/SplatTrainer.h).@@ -127,6 +141,34 @@ int main(int argc, char** argv) {std::printf(" %s%s %s\n", p.name.c_str(), p.required ? " (required)" : "", p.description.c_str());}return 0;+ } else if (a == "--policy") {+ const sf::policy::Policy& p = sf::policy::current();+ std::printf("%s\n", p.present ? ("Policy " + p.source + "\n" + sf::policy::describe(p)).c_str()+ : ("No policy (" + sf::policy::systemPolicyPath() + " or SF_POLICY): nothing is managed").c_str());+ return p.broken ? 2 : 0;+ } else if (a == "--audit-log") {+ std::printf("%s\n", sf::audit::logPath().c_str());+ return 0;+ } else if (a == "--sign-in") {+ std::string err;+ const bool ok = sf::ai::oidc::signIn(+ [](const sf::ai::oidc::DeviceCode& c) {+ std::fprintf(stderr, "To sign in, open %s and enter the code %s\n",+ c.verificationUri.c_str(), c.userCode.c_str());+ if (!c.verificationUriComplete.empty()) std::fprintf(stderr, "(or open %s)\n", c.verificationUriComplete.c_str());+ return true;+ },+ {}, err);+ if (!ok) {+ std::fprintf(stderr, "error: %s\n", err.c_str());+ return 1;+ }+ std::printf("Signed in as %s\n", sf::ai::oidc::signedInAs().c_str());+ return 0;+ } else if (a == "--sign-out") {+ sf::ai::oidc::signOut();+ std::puts("Signed out");+ return 0;} else if (a == "--mcp") {return sf::runMcpServer(registry, std::cin, std::cout);} else if (a == "--schema") {diff --git a/src/core/AuditLog.cpp b/src/core/AuditLog.cppnew file mode 100644index 00000000..a92f38d5--- /dev/null+++ b/src/core/AuditLog.cpp@@ -0,0 +1,214 @@+// SculptForge - open source digital sculpting+// SPDX-License-Identifier: GPL-3.0-or-later+#include "core/AuditLog.h"++#include "core/BrushLibrary.h"+#include "core/ManagedPolicy.h"++#include <algorithm>+#include <cctype>+#include <chrono>+#include <cstdio>+#include <cstdlib>+#include <ctime>+#include <filesystem>+#include <fstream>+#include <mutex>++namespace sf::audit {++namespace fs = std::filesystem;++namespace {++std::mutex gMutex;+std::string gClient = "app";+std::string gTestPath;++fs::path fsp(const std::string& s) { return fs::path(std::u8string(s.begin(), s.end())); }++// Printable ASCII only, cut to N characters (log lines stay one line, readable by any tool).+std::string clean(const std::string& s, size_t n) {+ std::string out;+ for (unsigned char c : s) {+ if (out.size() >= n) {+ out += "...";+ break;+ }+ out += c >= 0x20 && c != 0x7f ? char(c) : ' ';+ }+ return out;+}++std::string lower(std::string s) {+ std::transform(s.begin(), s.end(), s.begin(), [](unsigned char c) { return char(std::tolower(c)); });+ return s;+}++bool secretKey(const std::string& key) {+ const std::string k = lower(key);+ for (const char* w : {"key", "token", "secret", "password", "passwd", "auth", "credential", "cookie"})+ if (k.find(w) != std::string::npos) return true;+ return false;+}++// Arguments that carry artwork or bulk data rather than settings.+bool dataKey(const std::string& key) {+ const std::string k = lower(key);+ for (const char* w : {"json", "code", "data", "image", "points", "pixels", "mesh", "base64", "content"})+ if (k == w || k.ends_with(std::string("_") + w)) return true;+ return false;+}++bool textKey(const std::string& key) {+ const std::string k = lower(key);+ for (const char* w : {"prompt", "description", "text", "request", "message"})+ if (k == w || k.ends_with(std::string("_") + w)) return true;+ return false;+}++std::string nowIso() {+ using namespace std::chrono;+ const auto now = system_clock::now();+ const std::time_t t = system_clock::to_time_t(now);+ const int ms = int(duration_cast<milliseconds>(now.time_since_epoch()).count() % 1000);+ std::tm tm{};+#if defined(_WIN32)+ gmtime_s(&tm, &t);+#else+ gmtime_r(&t, &tm);+#endif+ char buf[40];+ std::snprintf(buf, sizeof buf, "%04d-%02d-%02dT%02d:%02d:%02d.%03dZ", tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday,+ tm.tm_hour, tm.tm_min, tm.tm_sec, ms);+ return buf;+}++std::string envOr(const char* a, const char* b) {+ if (const char* v = std::getenv(a); v && *v) return v;+ if (const char* v = std::getenv(b); v && *v) return v;+ return {};+}++void rotate(const fs::path& path, uint64_t maxBytes, int keep) {+ std::error_code ec;+ const auto size = fs::file_size(path, ec);+ if (ec || size < maxBytes) return;+ if (keep <= 0) {+ fs::remove(path, ec);+ return;+ }+ auto numbered = [&](int i) { return fs::path(path.native() + fs::path("." + std::to_string(i)).native()); };+ fs::remove(numbered(keep), ec);+ for (int i = keep - 1; i >= 1; --i)+ if (fs::exists(numbered(i), ec)) fs::rename(numbered(i), numbered(i + 1), ec);+ fs::rename(path, numbered(1), ec);+}++} // namespace++void setClient(const std::string& c) {+ std::lock_guard lock(gMutex);+ gClient = clean(c, 64);+}++std::string client() {+ std::lock_guard lock(gMutex);+ return gClient;+}++std::string clientFromInitialize(const Json& params) {+ const Json& info = params["clientInfo"];+ std::string name = info["name"].asString(), version = info["version"].asString();+ if (name.empty()) name = "unknown";+ return clean("mcp:" + name + (version.empty() ? "" : " " + version), 64);+}++Json summarizeArgs(const Args& args) {+ Json out = Json::object();+ for (const auto& [key, value] : args) {+ if (secretKey(key)) {+ out.set(key, "<redacted>");+ } else if (const auto* s = std::get_if<std::string>(&value)) {+ if (dataKey(key)) out.set(key, "<" + std::to_string(s->size()) + " bytes>");+ else if (textKey(key) && s->size() > 120) out.set(key, "<" + std::to_string(s->size()) + " characters>");+ else out.set(key, clean(*s, 120));+ } else if (const auto* b = std::get_if<bool>(&value)) {+ out.set(key, *b);+ } else {+ out.set(key, std::get<double>(value));+ }+ }+ return out;+}++std::string logPath() {+ if (!gTestPath.empty()) return gTestPath;+ const policy::Policy& p = policy::current();+ if (!p.auditPath.empty()) return policy::expandPathTemplate(p.auditPath);+ const std::string dir = appDataDir();+#if defined(_WIN32)+ return (dir.empty() ? std::string(".") : dir) + "\\audit\\ai-audit.jsonl";+#else+ return (dir.empty() ? std::string(".") : dir) + "/audit/ai-audit.jsonl";+#endif+}++bool required() { return policy::current().auditRequired; }++bool record(const Entry& e, std::string* error) {+ Json line = Json::object();+ line.set("time", nowIso());+ line.set("user", clean(envOr("USER", "USERNAME"), 64));+ {+ // (the host name is the same one the path template uses)+ std::string host = policy::expandPathTemplate("{host}");+ line.set("host", host);+ }+ line.set("client", e.client.empty() ? client() : clean(e.client, 64));+ line.set("tool", clean(e.tool, 32));+ line.set("command", clean(e.command, 64));+ line.set("args", e.args.isObject() ? e.args : Json::object());+ line.set("result", e.ok ? "ok" : "error");+ if (!e.message.empty()) line.set("message", clean(e.message, 200));+ if (e.ms >= 0) line.set("ms", double(e.ms));+ if (!e.endpoint.empty()) line.set("endpoint", clean(e.endpoint, 120));+ const std::string text = line.dump() + "\n";++ std::lock_guard lock(gMutex);+ const fs::path path = fsp(logPath());+ std::error_code ec;+ if (path.has_parent_path()) fs::create_directories(path.parent_path(), ec);+ const policy::Policy& p = policy::current();+ rotate(path, uint64_t(std::max(0.1, p.auditMaxMB) * 1024 * 1024), p.auditKeep);+ // Append mode: several processes (the app, the CLI, an agent) can share one file.+ std::ofstream f(path, std::ios::binary | std::ios::app);+ if (f) f << text;+ if (f) f.flush();+ if (!f) {+ if (error) *error = "can't write the audit log " + logPath();+ return false;+ }+#if !defined(_WIN32)+ if (p.auditPath.empty() && gTestPath.empty()) fs::permissions(path, fs::perms::owner_read | fs::perms::owner_write, ec);+#endif+ return true;+}++bool writable(std::string* error) {+ std::lock_guard lock(gMutex);+ const fs::path path = fsp(logPath());+ std::error_code ec;+ if (path.has_parent_path()) fs::create_directories(path.parent_path(), ec);+ std::ofstream f(path, std::ios::binary | std::ios::app);+ if (f) return true;+ if (error) *error = "can't write the audit log " + logPath() + ", which your studio requires";+ return false;+}++void setPathForTests(const std::string& path) {+ std::lock_guard lock(gMutex);+ gTestPath = path;+}++} // namespace sf::auditdiff --git a/src/core/AuditLog.h b/src/core/AuditLog.hnew file mode 100644index 00000000..a769cbc3--- /dev/null+++ b/src/core/AuditLog.h@@ -0,0 +1,60 @@+// SculptForge - open source digital sculpting+// SPDX-License-Identifier: GPL-3.0-or-later+//+// The audit log: one JSON line per AI or MCP action (an AI tool calling a command, Brush Lab, Generate 3D), so a+// studio can see what AI did on which machine. Local, append-only, rotated; nothing is sent anywhere.+//+// {"time":"2026-11-05T14:03:22.120Z","user":"ana","host":"ws042","client":"mcp:claude-code 2.1","tool":"mcp",+// "command":"remesh","args":{"resolution":256},"result":"ok","message":"Remeshed: 812k triangles","ms":930}+//+// What is never written: artwork (meshes, images, textures), secrets (any argument named like a key, token,+// password or secret), and long text (strings are cut to 120 characters; a prompt's length is kept, not its+// words, unless it is short). File paths are kept: they say what was read or written.+//+// Path: the policy's audit.path ({user}, {host}, {date} filled in; core/ManagedPolicy.h), e.g. a network share,+// else <settings folder>/audit/ai-audit.jsonl. Rotation: past audit.maxMB (10) the file becomes .1, .1 becomes .2,+// ... up to audit.keep (5) old files. With audit.required, an action whose line can't be written is refused.+#pragma once++#include "core/Commands.h"+#include "core/Json.h"++#include <cstdint>+#include <string>++namespace sf::audit {++struct Entry {+ std::string client; // "app", "cli", "python", "mcp:<client name> <version>"; "" = the process's (setClient)+ std::string tool; // the surface: "mcp", "mcp-live", "ai"+ std::string command; // "remesh", "brush_ai", "tools/list", ...+ Json args = Json::object(); // already summarized (summarizeArgs)+ bool ok = true;+ std::string message; // the result's message (cut to 200 characters)+ int64_t ms = -1; // how long it took; -1 = not timed+ std::string endpoint; // AI requests: the host they went to+};++// The process's client ("app", "cli", "python"; the MCP server sets "mcp:<name>" from the agent's initialize).+void setClient(const std::string& client);+std::string client();+// "mcp:" + the agent's clientInfo name and version from an initialize request's params ("mcp:unknown" if none),+// made safe for a log (printable, at most 64 characters).+std::string clientFromInitialize(const Json& params);++// The arguments with secrets, artwork and long text left out (see above).+Json summarizeArgs(const Args& args);++// Appends one line. False when it couldn't be written (MESSAGE in `error`). Thread-safe.+bool record(const Entry& e, std::string* error = nullptr);+// True when the policy requires the log: callers refuse the action if record() of its start fails.+bool required();+// Whether a line could be written now (with audit.required, checked before the action runs).+bool writable(std::string* error = nullptr);+// Where lines go now.+std::string logPath();++// Tests: write here instead (empty: back to the policy / default).+void setPathForTests(const std::string& path);++} // namespace sf::auditdiff --git a/src/core/Keychain.cpp b/src/core/Keychain.cppindex ebc40a2e..b91b4b3a 100644--- a/src/core/Keychain.cpp+++ b/src/core/Keychain.cpp@@ -2,20 +2,96 @@// SPDX-License-Identifier: GPL-3.0-or-later#include "core/Keychain.h"+#include <atomic>+#include <cstdlib>#include <cstring>+#include <map>+#include <mutex>#if defined(_WIN32)#define WIN32_LEAN_AND_MEAN#define NOMINMAX#include <windows.h>#include <wincred.h>+#elif defined(__APPLE__)+#include <CoreFoundation/CoreFoundation.h>+#include <Security/Security.h>#elif defined(__linux__)#include <dlfcn.h>-#include <mutex>#endifnamespace sf::keychain {+namespace {++std::atomic<bool> gMemory{false};+std::mutex gMemoryMutex;+std::map<std::string, std::string>& memoryStore() {+ static std::map<std::string, std::string> m;+ return m;+}++bool disabledByEnv() {+ const char* v = std::getenv("SF_KEYCHAIN");+ return v && (std::strcmp(v, "none") == 0 || std::strcmp(v, "off") == 0);+}++// What the OS keychain shows for an account.+const char* labelFor(const std::string& account) {+ if (account.rfind("member-builds", 0) == 0) return "SculptForge member builds (GitHub sign-in)";+ if (account.rfind("sso/", 0) == 0) return "SculptForge studio sign-in";+ if (account.rfind("ai/", 0) == 0) return "SculptForge AI provider key";+ return "SculptForge";+}++} // namespace++void useMemoryForTests(bool on) {+ gMemory = on;+ std::lock_guard lock(gMemoryMutex);+ memoryStore().clear();+}++namespace os {+bool store(const std::string& account, const std::string& secret);+bool load(const std::string& account, std::string& secret);+bool erase(const std::string& account);+bool available();+} // namespace os++bool store(const std::string& account, const std::string& secret) {+ if (gMemory) {+ std::lock_guard lock(gMemoryMutex);+ memoryStore()[account] = secret;+ return true;+ }+ return !disabledByEnv() && os::store(account, secret);+}++bool load(const std::string& account, std::string& secret) {+ if (gMemory) {+ std::lock_guard lock(gMemoryMutex);+ auto it = memoryStore().find(account);+ if (it == memoryStore().end()) return false;+ secret = it->second;+ return true;+ }+ return !disabledByEnv() && os::load(account, secret);+}++bool erase(const std::string& account) {+ if (gMemory) {+ std::lock_guard lock(gMemoryMutex);+ memoryStore().erase(account);+ return true;+ }+ return disabledByEnv() || os::erase(account);+}++bool available() { return gMemory || (!disabledByEnv() && os::available()); }++namespace os {+#if defined(_WIN32)namespace {@@ -54,6 +130,8 @@ bool erase(const std::string& account) {return CredDeleteW(target(account).c_str(), CRED_TYPE_GENERIC, 0) != FALSE || GetLastError() == ERROR_NOT_FOUND;}+bool available() { return true; }+#elif defined(__linux__)// libsecret's C API, declared here so nothing links against it: a system without it simply has no keychain.@@ -128,7 +206,7 @@ bool store(const std::string& account, const std::string& secret) {const Secret& s = secretLib();if (!s.ok) return false;GErrorC* error = nullptr;- const int r = s.store(schema(), nullptr, "SculptForge member builds (GitHub sign-in)", secret.c_str(), nullptr, &error,+ const int r = s.store(schema(), nullptr, labelFor(account), secret.c_str(), nullptr, &error,"account", account.c_str(), static_cast<char*>(nullptr));return done(s, error, r);}@@ -155,12 +233,90 @@ bool erase(const std::string& account) {return !error ? true : (s.errorFree(error), false);}-#else // macOS: the Keychain follows (Security framework); until then the sign-in isn't kept between sessions.+bool available() { return secretLib().ok; }++#elif defined(__APPLE__)++// A generic password per account: service "SculptForge", the account name as kSecAttrAccount, this user's login+// keychain, readable only by this app (the Keychain asks the user before another app may read it).+namespace {++struct Cf {+ CFTypeRef ref = nullptr;+ explicit Cf(CFTypeRef r) : ref(r) {}+ ~Cf() {+ if (ref) CFRelease(ref);+ }+ Cf(const Cf&) = delete;+ Cf& operator=(const Cf&) = delete;+};++CFStringRef cfString(const std::string& s) {+ return CFStringCreateWithBytes(nullptr, reinterpret_cast<const UInt8*>(s.data()), CFIndex(s.size()), kCFStringEncodingUTF8, false);+}++// The query that names one account's item.+CFMutableDictionaryRef query(const std::string& account) {+ CFMutableDictionaryRef q = CFDictionaryCreateMutable(nullptr, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);+ Cf service(cfString("SculptForge")), acct(cfString(account));+ CFDictionarySetValue(q, kSecClass, kSecClassGenericPassword);+ CFDictionarySetValue(q, kSecAttrService, service.ref);+ CFDictionarySetValue(q, kSecAttrAccount, acct.ref);+ return q;+}++} // namespace++bool store(const std::string& account, const std::string& secret) {+ Cf q(query(account));+ Cf data(CFDataCreate(nullptr, reinterpret_cast<const UInt8*>(secret.data()), CFIndex(secret.size())));+ CFMutableDictionaryRef update = CFDictionaryCreateMutable(nullptr, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);+ Cf updateRef(update);+ CFDictionarySetValue(update, kSecValueData, data.ref);+ OSStatus st = SecItemUpdate(static_cast<CFDictionaryRef>(q.ref), update);+ if (st == errSecItemNotFound) {+ CFMutableDictionaryRef add = CFDictionaryCreateMutableCopy(nullptr, 0, static_cast<CFDictionaryRef>(q.ref));+ Cf addRef(add);+ Cf label(cfString(labelFor(account)));+ CFDictionarySetValue(add, kSecValueData, data.ref);+ CFDictionarySetValue(add, kSecAttrLabel, label.ref);+ CFDictionarySetValue(add, kSecAttrAccessible, kSecAttrAccessibleWhenUnlocked); // this Mac only, while unlocked+ st = SecItemAdd(add, nullptr);+ }+ return st == errSecSuccess;+}++bool load(const std::string& account, std::string& secret) {+ CFMutableDictionaryRef q = query(account);+ Cf qRef(q);+ CFDictionarySetValue(q, kSecReturnData, kCFBooleanTrue);+ CFDictionarySetValue(q, kSecMatchLimit, kSecMatchLimitOne);+ CFTypeRef result = nullptr;+ if (SecItemCopyMatching(q, &result) != errSecSuccess || !result) return false;+ Cf resultRef(result);+ if (CFGetTypeID(result) != CFDataGetTypeID()) return false;+ const auto data = static_cast<CFDataRef>(result);+ secret.assign(reinterpret_cast<const char*>(CFDataGetBytePtr(data)), size_t(CFDataGetLength(data)));+ return true;+}++bool erase(const std::string& account) {+ Cf q(query(account));+ const OSStatus st = SecItemDelete(static_cast<CFDictionaryRef>(q.ref));+ return st == errSecSuccess || st == errSecItemNotFound;+}++bool available() { return true; }++#else // another OS: nothing is kept between sessions.bool store(const std::string&, const std::string&) { return false; }bool load(const std::string&, std::string&) { return false; }bool erase(const std::string&) { return true; }+bool available() { return false; }#endif+} // namespace os+} // namespace sf::keychaindiff --git a/src/core/Keychain.h b/src/core/Keychain.hindex 3311e5c8..ddf07ad9 100644--- a/src/core/Keychain.h+++ b/src/core/Keychain.h@@ -1,10 +1,12 @@// SculptForge - open source digital sculpting// SPDX-License-Identifier: GPL-3.0-or-later//-// A secret in the operating system's keychain (the member-builds sign-in, core/MemberBuilds.h): Windows Credential-// Manager, the Secret Service on Linux (libsecret, loaded at run time: GNOME Keyring, KWallet, KeePassXC), macOS-// Keychain later. Where there is none, nothing is stored: the sign-in lasts until the app quits. Secrets never go-// to files, the preferences or the log. These calls can wait on the keychain (an unlock prompt): worker threads only.+// A secret in the operating system's keychain (the member-builds sign-in, core/MemberBuilds.h; AI provider keys,+// ai/Secrets.h; the studio sign-in, core/Oidc.h): Windows Credential Manager, the Secret Service on Linux (libsecret,+// loaded at run time: GNOME Keyring, KWallet, KeePassXC), the macOS Keychain (Security framework, a generic password+// per account under the service "SculptForge"). Where there is none, nothing is stored: a secret lasts until the app+// quits. Secrets never go to files, the preferences or the log. These calls can wait on the keychain (an unlock+// prompt): prefer worker threads. SF_KEYCHAIN=none turns the keychain off (render farms, CI).#pragma once#include <string>@@ -14,5 +16,10 @@ namespace sf::keychain {bool store(const std::string& account, const std::string& secret); // false: not stored (no keychain, or it refused)bool load(const std::string& account, std::string& secret); // false: none storedbool erase(const std::string& account); // true when nothing is stored afterwards+// Whether this computer has a keychain SculptForge can use (Linux: libsecret is installed).+bool available();++// Tests: an in-memory keychain instead of the real one, so no test reads or writes the user's.+void useMemoryForTests(bool on);} // namespace sf::keychaindiff --git a/src/core/ManagedPolicy.cpp b/src/core/ManagedPolicy.cppnew file mode 100644index 00000000..cb214604--- /dev/null+++ b/src/core/ManagedPolicy.cpp@@ -0,0 +1,421 @@+// SculptForge - open source digital sculpting+// SPDX-License-Identifier: GPL-3.0-or-later+#include "core/ManagedPolicy.h"++#include "core/Json.h"+#include "core/NetworkPolicy.h"++#include <algorithm>+#include <chrono>+#include <cstdlib>+#include <ctime>+#include <fstream>+#include <iterator>+#include <mutex>+#include <sstream>++#if defined(_WIN32)+#define WIN32_LEAN_AND_MEAN+#define NOMINMAX+#include <windows.h>+#else+#include <sys/stat.h>+#include <unistd.h>+#endif++namespace sf::policy {++namespace {++Policy gPolicy;+std::once_flag gOnce;++bool isUrl(const std::string& s) { return s.rfind("https://", 0) == 0 || s.rfind("http://", 0) == 0; }++bool contains(const std::vector<std::string>& v, std::string_view s) { return std::find(v.begin(), v.end(), s) != v.end(); }++bool checkKeys(const Json& j, std::initializer_list<const char*> keys, const std::string& where, std::string& error) {+ if (!j.isObject()) return (error = where + " must be an object", false);+ for (const auto& [k, v] : j.members()) {+ bool known = false;+ for (const char* key : keys) known = known || k == key;+ if (!known) return (error = "unknown key \"" + (where.empty() ? k : where + "." + k) + "\"", false);+ }+ return true;+}++bool readLock(const Json& j, const char* key, Lock& out, const std::string& where, std::string& error) {+ if (!j.has(key)) return true;+ if (!j[key].isBool()) return (error = where + "." + key + " must be true or false", false);+ out = j[key].asBool() ? Lock::On : Lock::Off;+ return true;+}++bool readStrings(const Json& j, const char* key, std::vector<std::string>& out, const std::string& where,+ std::string& error) {+ if (!j.has(key)) return true;+ if (!j[key].isArray()) return (error = where + "." + key + " must be a list of strings", false);+ for (const Json& v : j[key].items()) {+ if (!v.isString() || v.asString().empty()) return (error = where + "." + key + " must be a list of strings", false);+ out.push_back(v.asString());+ }+ return true;+}++// http(s) URL prefixes with no user info. Plain http only to this computer (a local model server, the mock IdP).+bool readUrls(const Json& j, const char* key, std::vector<std::string>& out, const std::string& where, std::string& error,+ bool httpsOnly = false) {+ if (!readStrings(j, key, out, where, error)) return false;+ for (const std::string& u : out) {+ net::UrlParts p;+ if (!isUrl(u) || !net::parseUrl(u, p)) return (error = where + "." + key + ": \"" + u + "\" is not an http(s) URL", false);+ if (httpsOnly && p.scheme != "https" && !net::isLoopbackAddress(p.host))+ return (error = where + "." + key + ": \"" + u + "\" must be https", false);+ }+ return true;+}++std::string envOr(const char* a, const char* b = nullptr) {+ if (const char* v = std::getenv(a); v && *v) return v;+ if (b)+ if (const char* v = std::getenv(b); v && *v) return v;+ return {};+}++// Path-safe: letters, digits, '.', '-', '_' (a user or host name that would climb out of the folder can't).+std::string safePart(std::string s) {+ for (char& c : s)+ if (!((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '.' || c == '-' || c == '_'))+ c = '_';+ if (s.empty() || s == "." || s == "..") s = "unknown";+ return s;+}++std::string hostName() {+#if defined(_WIN32)+ char buf[256];+ DWORD n = sizeof buf;+ if (GetComputerNameA(buf, &n)) return std::string(buf, n);+ return envOr("COMPUTERNAME");+#else+ char buf[256] = {};+ if (gethostname(buf, sizeof buf - 1) == 0) return buf;+ return {};+#endif+}++void replaceAll(std::string& s, const std::string& from, const std::string& to) {+ for (size_t at = s.find(from); at != std::string::npos; at = s.find(from, at + to.size())) s.replace(at, from.size(), to);+}++Policy failClosed(const std::string& source, const std::string& error) {+ Policy p;+ p.present = true;+ p.broken = true;+ p.source = source;+ p.error = error;+ p.ai = Lock::Off;+ p.network = Lock::Off;+ p.mcp = Lock::Off;+ p.mcpLiveAllowed = false;+ p.updateCheck = Lock::Off;+ return p;+}++} // namespace++const std::vector<std::string>& mcpCategoryNames() {+ static const std::vector<std::string> names = {"info", "edit", "files", "scripts", "network", "ai"};+ return names;+}++const std::vector<std::string>& aiProviderIds() {+ static const std::vector<std::string> ids = {+ // Brush Lab (ai/Providers.h)+ "free", "anthropic", "openai", "ollama", "lmstudio", "vllm", "llamacpp", "litellm", "openrouter", "openai-compatible",+ // Generate 3D (ai/ImageTo3DService.h)+ "huggingface", "fal", "meshy", "comfyui", "command"};+ return ids;+}++bool parsePolicy(const std::string& text, const std::string& source, Policy& out, std::string& error) {+ Json j;+ if (!Json::parseStrict(text, j, error)) return false;+ if (!checkKeys(j, {"format", "version", "organization", "ai", "network", "mcp", "audit", "signIn", "telemetry", "updates"},+ "", error))+ return false;+ if (j["format"].asString() != kPolicyFormat) return (error = "format must be \"sculptforge-policy\"", false);+ if (!j["version"].isNumber() || int(j["version"].asNumber()) != kPolicyVersion) return (error = "unsupported version (1 is current)", false);+ Policy p;+ p.present = true;+ p.source = source;+ p.organization = j["organization"].asString();+ if (p.organization.size() > 80) return (error = "organization: at most 80 characters", false);++ if (j.has("ai")) {+ const Json& a = j["ai"];+ if (!checkKeys(a, {"enabled", "providers", "endpoints", "requireSignIn"}, "ai", error)) return false;+ if (!readLock(a, "enabled", p.ai, "ai", error) || !readStrings(a, "providers", p.aiProviders, "ai", error) ||+ !readUrls(a, "endpoints", p.aiEndpoints, "ai", error))+ return false;+ for (const std::string& id : p.aiProviders)+ if (!contains(aiProviderIds(), id)) return (error = "ai.providers: unknown provider \"" + id + "\"", false);+ if (a.has("requireSignIn") && !a["requireSignIn"].isBool()) return (error = "ai.requireSignIn must be true or false", false);+ p.requireSignIn = a["requireSignIn"].asBool(false);+ }+ if (j.has("network")) {+ const Json& n = j["network"];+ if (!checkKeys(n, {"enabled", "allow", "localNetwork"}, "network", error)) return false;+ if (!readLock(n, "enabled", p.network, "network", error) || !readUrls(n, "allow", p.networkAllow, "network", error))+ return false;+ if (n.has("localNetwork") && !n["localNetwork"].isBool()) return (error = "network.localNetwork must be true or false", false);+ p.localNetwork = n["localNetwork"].asBool(false);+ }+ if (j.has("mcp")) {+ const Json& m = j["mcp"];+ if (!checkKeys(m, {"enabled", "live", "categories"}, "mcp", error)) return false;+ if (!readLock(m, "enabled", p.mcp, "mcp", error) || !readStrings(m, "categories", p.mcpCategories, "mcp", error))+ return false;+ for (const std::string& c : p.mcpCategories)+ if (!contains(mcpCategoryNames(), c)) return (error = "mcp.categories: unknown category \"" + c + "\"", false);+ if (m.has("live")) {+ const std::string live = m["live"].asString();+ if (live != "never" && live != "allowed") return (error = "mcp.live must be \"never\" or \"allowed\"", false);+ p.mcpLiveAllowed = live == "allowed";+ }+ if (p.mcp == Lock::Off) p.mcpLiveAllowed = false;+ }+ if (j.has("audit")) {+ const Json& a = j["audit"];+ if (!checkKeys(a, {"path", "maxMB", "keep", "required"}, "audit", error)) return false;+ if (a.has("path") && (!a["path"].isString() || a["path"].asString().empty()))+ return (error = "audit.path must be a file path", false);+ p.auditPath = a["path"].asString();+ if (a.has("maxMB")) {+ if (!a["maxMB"].isNumber() || a["maxMB"].asNumber() < 0.1 || a["maxMB"].asNumber() > 4096)+ return (error = "audit.maxMB: 0.1 to 4096", false);+ p.auditMaxMB = a["maxMB"].asNumber();+ }+ if (a.has("keep")) {+ if (!a["keep"].isNumber() || a["keep"].asNumber() < 0 || a["keep"].asNumber() > 1000)+ return (error = "audit.keep: 0 to 1000 old files", false);+ p.auditKeep = int(a["keep"].asNumber());+ }+ if (a.has("required") && !a["required"].isBool()) return (error = "audit.required must be true or false", false);+ p.auditRequired = a["required"].asBool(false);+ }+ if (j.has("signIn")) {+ const Json& s = j["signIn"];+ if (!checkKeys(s, {"issuer", "clientId", "clientSecret", "scopes", "audience", "useFor"}, "signIn", error)) return false;+ p.issuer = s["issuer"].asString();+ p.clientId = s["clientId"].asString();+ p.audience = s["audience"].asString();+ p.clientSecret = s["clientSecret"].asString();+ net::UrlParts u;+ if (!isUrl(p.issuer) || !net::parseUrl(p.issuer, u) || (u.scheme != "https" && !net::isLoopbackAddress(u.host)))+ return (error = "signIn.issuer must be the identity provider's https URL", false);+ if (p.clientId.empty() || p.clientId.size() > 256) return (error = "signIn.clientId: the app's client id", false);+ if (!readStrings(s, "scopes", p.scopes, "signIn", error) || !readUrls(s, "useFor", p.signInUseFor, "signIn", error, true))+ return false;+ for (const std::string& sc : p.scopes)+ if (sc.find_first_of(" \t\r\n\"") != std::string::npos) return (error = "signIn.scopes: one scope per entry", false);+ }+ if (p.requireSignIn && !p.signInConfigured()) return (error = "ai.requireSignIn needs signIn.issuer and signIn.clientId", false);+ if (j.has("telemetry")) {+ // SculptForge has no telemetry. The key exists so an IT checklist can state it; anything but "none" is a mistake.+ const Json& t = j["telemetry"];+ if (!((t.isString() && (t.asString() == "none" || t.asString() == "off")) || (t.isBool() && !t.asBool())))+ return (error = "telemetry: SculptForge has no telemetry; the only value is \"none\"", false);+ }+ if (j.has("updates")) {+ const Json& u = j["updates"];+ if (!checkKeys(u, {"check", "channel", "feed", "mirror"}, "updates", error)) return false;+ if (!readLock(u, "check", p.updateCheck, "updates", error)) return false;+ p.updateChannel = u["channel"].asString();+ if (u.has("channel") && p.updateChannel != "stable" && p.updateChannel != "preview")+ return (error = "updates.channel must be \"stable\" or \"preview\"", false);+ p.updateFeed = u["feed"].asString();+ p.updateMirror = u["mirror"].asString();+ net::UrlParts parts;+ if (!p.updateFeed.empty() && (!isUrl(p.updateFeed) || !net::parseUrl(p.updateFeed, parts)))+ return (error = "updates.feed must be an http(s) URL", false);+ if (!p.updateMirror.empty() && isUrl(p.updateMirror) && !net::parseUrl(p.updateMirror, parts))+ return (error = "updates.mirror must be an http(s) URL or a file", false);+ }+ out = std::move(p);+ return true;+}++std::string systemPolicyPath() {+#if defined(_WIN32)+ const std::string base = envOr("ProgramData", "ALLUSERSPROFILE");+ return (base.empty() ? std::string("C:\\ProgramData") : base) + "\\SculptForge\\policy.json";+#elif defined(__APPLE__)+ return "/Library/Application Support/SculptForge/policy.json";+#else+ return "/etc/sculptforge/policy.json";+#endif+}++Policy loadPolicyFile(const std::string& path, const std::string& origin, std::vector<std::string>* messages) {+ std::ifstream f(path, std::ios::binary);+ if (!f) {+ if (messages) messages->push_back("Policy " + origin + " can't be read: AI, network features and MCP are off");+ return failClosed(origin, "can't be read");+ }+ const std::string text((std::istreambuf_iterator<char>(f)), std::istreambuf_iterator<char>());+ std::string error;+ Policy p;+ if (text.size() > (1u << 20)) error = "larger than 1 MB";+ else if (parsePolicy(text, origin, p, error)) {+#if !defined(_WIN32)+ // A system policy anyone can edit locks nothing: say so (it still applies).+ struct stat st{};+ if (stat(path.c_str(), &st) == 0 && (st.st_mode & 0022) && messages)+ messages->push_back("Policy " + path + " is writable by other users: make it writable by administrators only");+#endif+ return p; // (describe() says what it locks: sculptforge-cli --policy, Preferences > AI)+ }+ if (messages) messages->push_back("Policy " + origin + ": " + error + ". AI, network features and MCP are off until it is fixed");+ return failClosed(origin, error);+}++const Policy& startPolicy(std::vector<std::string>* messages) {+ std::call_once(gOnce, [messages] {+ const std::string system = systemPolicyPath();+ const std::string env = envOr("SF_POLICY");+ if (std::ifstream(system, std::ios::binary)) {+ if (!env.empty() && messages) messages->push_back("Policy: SF_POLICY is ignored while " + system + " is installed");+ gPolicy = loadPolicyFile(system, system, messages);+ } else if (!env.empty()) {+ gPolicy = loadPolicyFile(env, "SF_POLICY=" + env, messages);+ }+ });+ return gPolicy;+}++const Policy& current() { return gPolicy; }++void setPolicyForTests(const Policy& p) { gPolicy = p; }+void resetPolicyForTests() { gPolicy = Policy{}; }++std::string managedBy() {+ return gPolicy.organization.empty() ? std::string(kManagedLabel) : "Managed by " + gPolicy.organization;+}++bool aiProviderAllowed(std::string_view providerId, std::string* why) {+ if (gPolicy.ai == Lock::Off) {+ if (why) *why = "AI features are turned off by your studio's policy";+ return false;+ }+ if (gPolicy.aiProviders.empty() || contains(gPolicy.aiProviders, providerId)) return true;+ if (why) *why = "Your studio's policy doesn't allow this AI provider (" + std::string(providerId) + ")";+ return false;+}++bool aiEndpointAllowed(const std::string& url, std::string* why) {+ if (gPolicy.ai == Lock::Off) {+ if (why) *why = "AI features are turned off by your studio's policy";+ return false;+ }+ if (gPolicy.aiEndpoints.empty()) return true;+ for (const std::string& prefix : gPolicy.aiEndpoints)+ if (net::urlUnderPrefix(url, prefix)) return true;+ if (why) *why = "Your studio's policy doesn't allow AI requests to this address";+ return false;+}++bool mcpAllowed(std::string* why) {+ if (gPolicy.mcp != Lock::Off) return true;+ if (why) *why = "AI tools (MCP) are turned off by your studio's policy";+ return false;+}++bool mcpLiveAllowed(std::string* why) {+ if (gPolicy.mcp != Lock::Off && gPolicy.mcpLiveAllowed) return true;+ if (why) *why = "Your studio's policy doesn't let AI tools control the app window";+ return false;+}++std::vector<std::string> mcpCategories(std::string_view name, const std::vector<std::string>& paramNames) {+ static const char* kNetwork[] = {"brush_gallery_search", "brush_gallery_install", "unreal_editors", "unreal_send",+ "export_unreal"};+ static const char* kScripts[] = {"macro_run", "run_script", "python"};+ static const char* kBridges[] = {"goz_send", "blender_send", "blender_receive", "maya_send", "maya_receive"};+ static const char* kAi[] = {"brush_ai", "image_to_3d", "text_to_3d", "comfyui_check"};+ auto in = [&](const auto& list) {+ for (const char* n : list)+ if (name == n) return true;+ return false;+ };+ std::vector<std::string> c;+ if (in(kAi)) c.push_back("ai"), c.push_back("network");+ if (in(kNetwork)) c.push_back("network");+ if (in(kScripts)) c.push_back("scripts");+ bool files = in(kBridges);+ for (const std::string& p : paramNames) files = files || p == "path" || p == "folder" || p == "file";+ if (files) c.push_back("files");+ const bool info = name == "mesh_info" || name.ends_with("_info") || name.ends_with("_list") || name == "brush_library";+ if (c.empty()) c.push_back(info ? "info" : "edit");+ return c;+}++bool mcpToolAllowed(std::string_view name, const std::vector<std::string>& paramNames, std::string* why) {+ if (!mcpAllowed(why)) return false;+ if (gPolicy.mcpCategories.empty()) return true;+ for (const std::string& c : mcpCategories(name, paramNames))+ if (!contains(gPolicy.mcpCategories, c)) {+ if (why) *why = "Your studio's policy doesn't allow AI tools to use " + std::string(name) + " (" + c + ")";+ return false;+ }+ return true;+}++std::string describe(const Policy& p) {+ if (!p.present) return "no policy: nothing is managed";+ if (p.broken) return "broken (" + p.error + "): AI, network features and MCP are off";+ std::ostringstream o;+ auto lock = [](Lock l) { return l == Lock::Off ? "off" : l == Lock::On ? "on" : "artist's choice"; };+ auto list = [](const std::vector<std::string>& v, const char* none) {+ if (v.empty()) return std::string(none);+ std::string s;+ for (const std::string& x : v) s += (s.empty() ? "" : ", ") + x;+ return s;+ };+ if (!p.organization.empty()) o << p.organization << ": ";+ o << "AI " << lock(p.ai);+ if (p.ai != Lock::Off) {+ o << " (providers: " << list(p.aiProviders, "any") << "; endpoints: " << list(p.aiEndpoints, "any");+ if (p.requireSignIn) o << "; sign-in required";+ o << ")";+ }+ o << "; network " << (p.network == Lock::Off ? "off (allowed: " + list(p.networkAllow, "nothing") + ")" : "on");+ o << "; MCP " << (p.mcp == Lock::Off ? "off" : "on (tools: " + list(p.mcpCategories, "all") + "; live mode " ++ (p.mcpLiveAllowed ? "allowed" : "never") + ")");+ o << "; audit log " << (p.auditPath.empty() ? "default path" : p.auditPath) << (p.auditRequired ? " (required)" : "");+ if (p.signInConfigured()) o << "; sign-in " << p.issuer;+ o << "; telemetry none (SculptForge has none)";+ o << "; updates " << (p.updateCheck == Lock::Off ? "off" : p.updateChannel.empty() ? "artist's choice" : p.updateChannel);+ if (!p.updateFeed.empty()) o << " from " << p.updateFeed;+ return o.str();+}++std::string expandPathTemplate(const std::string& path) {+ std::string out = path;+ if (out.find('{') == std::string::npos) return out;+ const std::time_t t = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());+ std::tm tm{};+#if defined(_WIN32)+ gmtime_s(&tm, &t);+#else+ gmtime_r(&t, &tm);+#endif+ char date[16];+ std::strftime(date, sizeof date, "%Y-%m-%d", &tm);+ replaceAll(out, "{user}", safePart(envOr("USER", "USERNAME")));+ replaceAll(out, "{host}", safePart(hostName()));+ replaceAll(out, "{date}", date);+ return out;+}++} // namespace sf::policydiff --git a/src/core/ManagedPolicy.h b/src/core/ManagedPolicy.hnew file mode 100644index 00000000..794fa530--- /dev/null+++ b/src/core/ManagedPolicy.h@@ -0,0 +1,133 @@+// SculptForge - open source digital sculpting+// SPDX-License-Identifier: GPL-3.0-or-later+//+// Managed configuration: a policy file a studio's IT deploys (docs/guide/studios.md "IT deployment"). It locks what an+// artist may change; the app shows "Managed by your studio" on each locked setting. It is data only: nothing in it runs.+//+// Where it comes from, first found wins:+// 1. the system-wide file, writable only by administrators:+// Linux /etc/sculptforge/policy.json+// macOS /Library/Application Support/SculptForge/policy.json+// Windows %ProgramData%\SculptForge\policy.json (C:\ProgramData\SculptForge\policy.json)+// 2. SF_POLICY=FILE, only when there is no system-wide file (IT testing a policy, a launcher, a Rez package):+// a user can't loosen a deployed policy by pointing SF_POLICY elsewhere.+// No file: nothing is managed and everything works as before.+//+// {+// "format": "sculptforge-policy", "version": 1,+// "organization": "Acme Animation",+// "ai": {"enabled": true, "providers": ["litellm", "comfyui"], "endpoints": ["https://llm.acme.internal/"],+// "requireSignIn": true},+// "network": {"enabled": false, "allow": ["https://sw.acme.internal/"], "localNetwork": false},+// "mcp": {"enabled": true, "live": "never", "categories": ["info", "edit", "files"]},+// "audit": {"path": "//fs01/audit/sculptforge/{user}@{host}.jsonl", "maxMB": 20, "keep": 10, "required": true},+// "signIn": {"issuer": "https://acme.okta.com/oauth2/default", "clientId": "0oa1...", "scopes": ["openid", "email",+// "offline_access"], "audience": "", "useFor": ["https://llm.acme.internal/"]},+// "telemetry": "none",+// "updates": {"check": true, "channel": "stable", "feed": "https://sw.acme.internal/sculptforge/latest.json"}+// }+// Every key is optional: what the policy leaves out stays the artist's choice. Unknown keys are errors, so a typo never+// quietly drops a lock. A broken policy fails closed: AI, network features, MCP and live mode off (policy().broken).+#pragma once++#include <string>+#include <string_view>+#include <vector>++namespace sf::policy {++constexpr const char* kPolicyFormat = "sculptforge-policy";+constexpr int kPolicyVersion = 1;+// Shown next to every setting the policy locks (translated with tr()).+constexpr const char* kManagedLabel = "Managed by your studio";++// A setting the policy may lock: Unset = the artist decides.+enum class Lock { Unset, Off, On };++// What an MCP tool does, for mcp.categories. A tool needs every category it is in.+// info reads the scene (mesh_info, part_list, ...)+// edit changes the scene in memory (sculpt, remesh, masks, undo, ...)+// files reads or writes files (open, export_*, save, anything with a path), and the bridges to other apps+// scripts runs macros or scripts+// network reaches beyond this computer (brush gallery, Unreal link)+// ai the AI features (brush_ai, image_to_3d, text_to_3d, comfyui_check)+const std::vector<std::string>& mcpCategoryNames();++struct Policy {+ bool present = false; // a policy file was found+ bool broken = false; // found but unusable: fails closed (everything below off)+ std::string source; // the file it came from, for messages+ std::string error; // why it is broken+ std::string organization; // shown in "Managed by ..." tooltips and Help > About++ Lock ai = Lock::Unset; // ai.enabled+ std::vector<std::string> aiProviders; // allowed provider ids (aiProviderIds()); empty = any+ std::vector<std::string> aiEndpoints; // allowed URL prefixes for AI requests; empty = any+ bool requireSignIn = false; // AI only while signed in (signIn below)++ Lock network = Lock::Unset; // network.enabled: Off = studio mode (only `allow`)+ std::vector<std::string> networkAllow; // more URL prefixes reachable while network is off+ bool localNetwork = false;++ Lock mcp = Lock::Unset; // mcp.enabled: Off = no MCP server (sculptforge-cli --mcp refuses)+ bool mcpLiveAllowed = true; // mcp.live: "never" | "allowed"+ std::vector<std::string> mcpCategories; // allowed categories; empty = all++ std::string auditPath; // with {user}, {host}, {date} filled in; "" = the default+ double auditMaxMB = 10;+ int auditKeep = 5;+ bool auditRequired = false; // refuse an AI/MCP action whose audit record can't be written++ std::string issuer, clientId, audience;+ std::string clientSecret; // only where the provider requires one for installed apps (Google)+ std::vector<std::string> scopes; // default openid profile email offline_access+ std::vector<std::string> signInUseFor; // URL prefixes that get the bearer token; empty = aiEndpoints++ Lock updateCheck = Lock::Unset; // updates.check+ std::string updateChannel; // "stable" | "preview" | "" (artist's choice)+ std::string updateFeed, updateMirror; // the studio's own feed (a URL) and mirror (a URL or a file)++ bool signInConfigured() const { return !issuer.empty() && !clientId.empty(); }+};++// Every provider id ai.providers accepts: the Brush Lab presets (ai/Providers.h) and the Generate 3D services.+const std::vector<std::string>& aiProviderIds();++// Reads and checks a policy (SOURCE names it in messages). False: ERROR says what is wrong.+bool parsePolicy(const std::string& text, const std::string& source, Policy& out, std::string& error);++// Reads the policy at PATH (ORIGIN names it in messages). A file that can't be read or parsed fails closed (broken).+// MESSAGES gets warnings (a file other users can write).+Policy loadPolicyFile(const std::string& path, const std::string& origin, std::vector<std::string>* messages = nullptr);++// The system-wide path for this OS (see above).+std::string systemPolicyPath();++// Finds and loads the policy (system file, else SF_POLICY), once per process; later calls return it. A file that+// can't be read or parsed fails closed. MESSAGES gets what to log.+const Policy& startPolicy(std::vector<std::string>* messages = nullptr);+// The process's policy (an empty one before startPolicy).+const Policy& current();+// Tests: replace the process's policy ("" text: none). Not thread-safe: only before workers start.+void setPolicyForTests(const Policy& p);+void resetPolicyForTests();++// The checks the rest of the app makes. WHY gets a sentence an artist can read.+bool aiProviderAllowed(std::string_view providerId, std::string* why = nullptr);+bool aiEndpointAllowed(const std::string& url, std::string* why = nullptr);+bool mcpAllowed(std::string* why = nullptr);+bool mcpLiveAllowed(std::string* why = nullptr);+// The categories of command NAME (needs the registry's parameter names: a "path", "folder" or "file" parameter is files).+std::vector<std::string> mcpCategories(std::string_view name, const std::vector<std::string>& paramNames);+bool mcpToolAllowed(std::string_view name, const std::vector<std::string>& paramNames, std::string* why = nullptr);++// "Managed by your studio" or "Managed by Acme Animation", for tooltips.+std::string managedBy();++// A readable summary of what the policy locks (sculptforge-cli --policy, Help > About, the log).+std::string describe(const Policy& p);++// {user}, {host} and {date} (YYYY-MM-DD, UTC) in a path.+std::string expandPathTemplate(const std::string& path);++} // namespace sf::policydiff --git a/src/core/StudioProfile.cpp b/src/core/StudioProfile.cppindex 682f7071..912e8b1f 100644--- a/src/core/StudioProfile.cpp+++ b/src/core/StudioProfile.cpp@@ -3,9 +3,11 @@#include "core/StudioProfile.h"#include "core/Json.h"+#include "core/ManagedPolicy.h"#include "core/Pack.h"#include "core/UpdateCheck.h"+#include <algorithm>#include <cstdlib>#include <filesystem>#include <fstream>@@ -145,6 +147,29 @@ std::string findInstalledStudioDir(const std::string& exeDir) {return {};}+net::NetworkPolicy withManagedPolicy(net::NetworkPolicy policy, const policy::Policy& managed) {+ if (managed.network != policy::Lock::Off) return policy;+ policy.offline = true;+ auto add = [&](const std::string& u) {+ if ((u.rfind("https://", 0) == 0 || u.rfind("http://", 0) == 0) &&+ std::find(policy.allow.begin(), policy.allow.end(), u) == policy.allow.end())+ policy.allow.push_back(u);+ };+ for (const std::string& u : managed.networkAllow) add(u);+ for (const std::string& u : managed.aiEndpoints) add(u);+ for (const std::string& u : managed.signInUseFor) add(u);+ // The identity provider's whole site: its device and token endpoints are often beside the issuer path, not under+ // it (Entra ID). Google's live on another host: list https://oauth2.googleapis.com/ in network.allow.+ if (net::UrlParts u; managed.signInConfigured() && net::parseUrl(managed.issuer, u)) {+ const bool defaultPort = (u.scheme == "https" && u.port == 443) || (u.scheme == "http" && u.port == 80);+ add(u.scheme + "://" + u.host + (defaultPort ? std::string() : ":" + std::to_string(u.port)) + "/");+ }+ add(managed.updateFeed);+ add(managed.updateMirror);+ policy.localNetwork = policy.localNetwork || managed.localNetwork;+ return policy;+}+StudioStart startStudioMode(const std::string& exeDir, const std::string& overridePath, bool forceOffline) {StudioStart s;std::string error;@@ -167,6 +192,7 @@ StudioStart startStudioMode(const std::string& exeDir, const std::string& overriif (found) policy = studioNetworkPolicy(s.profile);// Fail closed: a studio build, --offline or SF_OFFLINE=1 is offline even without a usable profile.if (isStudioBuild() || forceOffline || (envOffline && std::string(envOffline) == "1")) policy.offline = true;+ policy = withManagedPolicy(policy, policy::startPolicy(&s.messages));s.active = policy.offline;net::setNetworkPolicy(policy);if (found && !s.profile.brushPaths.empty()) { // read-only shares, ahead of any already set@@ -215,6 +241,12 @@ const StudioStart& studioMode() { return gStudio; }std::string updateFeedSource(const StudioStart& s, const char* envFeed, std::string& fallback) {fallback.clear();+ if (const policy::Policy& p = policy::current(); !p.updateFeed.empty() || !p.updateMirror.empty()) {+ // The studio's policy names its own channel: only that, then its mirror.+ if (p.updateFeed.empty()) return p.updateMirror;+ fallback = p.updateMirror;+ return p.updateFeed;+ }if (s.active) { // only the studio's own channel, then its mirrorif (s.profile.updateFeed.empty()) return s.profile.updateMirror;fallback = s.profile.updateMirror;diff --git a/src/core/StudioProfile.h b/src/core/StudioProfile.hindex 5cbb9eba..f5b83580 100644--- a/src/core/StudioProfile.h+++ b/src/core/StudioProfile.h@@ -61,6 +61,11 @@ bool loadStudioProfile(const std::string& path, StudioProfile& out, std::string&// What the profile allows: offline, the update channel and mirror (when they are URLs) plus its allow list.net::NetworkPolicy studioNetworkPolicy(const StudioProfile& p);+// POLICY with a studio's managed policy applied (core/ManagedPolicy.h): network features off is studio mode, with+// what the managed policy names reachable (its allow list, AI endpoints, the identity provider, its update feed).+namespace policy { struct Policy; }+net::NetworkPolicy withManagedPolicy(net::NetworkPolicy policy, const policy::Policy& managed);+// The profile compiled into this build ("" in public builds; core/StudioBuild.cpp, generated by CMake).const char* builtInStudioProfile();bool isStudioBuild();diff --git a/src/python/module.cpp b/src/python/module.cppindex 2d829aef..aeaea594 100644--- a/src/python/module.cpp+++ b/src/python/module.cpp@@ -17,6 +17,7 @@#include "core/BrushLibrary.h"#include "core/Commands.h"#include "core/Multires.h"+#include "core/AuditLog.h"#include "core/Script.h"#include "core/SelectionSets.h"#include "core/StudioProfile.h"@@ -126,6 +127,7 @@ PYBIND11_MODULE(sculptforge, m) {py::register_exception<CommandError>(m, "CommandError", PyExc_RuntimeError);// Studio mode (SF_STUDIO_PROFILE, SF_OFFLINE=1 or a studio build; core/StudioProfile.h), as in the app.sf::ai::setStudioAiAllowed(startStudioMode("", "", false).profile.ai);+ sf::audit::setClient("python"); // (the AI audit log, core/AuditLog.h)py::class_<Document>(m, "Document", "A scene: the sculpt mesh (with layers), Gaussian splats and edit history.").def(py::init([] {diff --git a/tests/test_core.cpp b/tests/test_core.cppindex 61879fb1..84d6c10d 100644--- a/tests/test_core.cpp+++ b/tests/test_core.cpp@@ -602,8 +602,11 @@ TEST(ai_free_provider_is_the_default) {Json missing = Json::object();CHECK(AiSettings::fromJson(missing).provider == AiSettings::Provider::Free);if (!std::getenv("ANTHROPIC_API_KEY")) {- AiSettings old = AiSettings::defaults(AiSettings::Provider::Anthropic);- AiSettings migrated = AiSettings::fromJson(old.toJson());+ Json old = Json::object(); // an ai.json from before the free tier (and before presets)+ old.set("provider", "anthropic");+ old.set("endpoint", "https://api.anthropic.com/v1/messages");+ old.set("model", "claude-opus-5-5");+ AiSettings migrated = AiSettings::fromJson(old);CHECK(migrated.provider == AiSettings::Provider::Free && migrated.model == "openai");}AiSettings keyed = AiSettings::defaults(AiSettings::Provider::Anthropic);@@ -1367,7 +1370,8 @@ TEST(free_huggingface_models) {chosen.hfModelChosen = true;chosen.hfToken = "hf_test";ai::AiSettings loaded = ai::AiSettings::fromJson(chosen.toJson());- CHECK(loaded.hfModel == "hunyuan3d-2-turbo" && loaded.hfModelChosen && loaded.resolvedHfToken() == "hf_test");+ // (the token itself goes to the keychain, never ai.json: test_studio_policy.cpp)+ CHECK(loaded.hfModel == "hunyuan3d-2-turbo" && loaded.hfModelChosen && loaded.hfToken.empty());ai::AiSettings unchosen;unchosen.hfModel = "trellis-2"; // saved by "Save settings" without picking a modelCHECK(ai::AiSettings::fromJson(unchosen.toJson()).hfModel == "hunyuan3d-2.1");diff --git a/tests/test_main.cpp b/tests/test_main.cppindex a517b92f..88ec578f 100644--- a/tests/test_main.cpp+++ b/tests/test_main.cpp@@ -8,6 +8,8 @@// `--nightly` (ctest entry sculptforge_tests_nightly, label nightly: T3 of docs/testing-flow.md), never in a shard.#include "TestHarness.h"+#include "core/Keychain.h"+#include <chrono>#include <cstdio>#include <cstring>@@ -16,6 +18,7 @@int main(int argc, char** argv) {using namespace sf::test;+ sf::keychain::useMemoryForTests(true); // no test reads or writes the user's keychain (AI keys, sign-ins)int shard = 0, shards = 1;bool nightly = false;std::vector<const char*> filters;diff --git a/tests/test_studio_policy.cpp b/tests/test_studio_policy.cppnew file mode 100644index 00000000..3bc4004b--- /dev/null+++ b/tests/test_studio_policy.cpp@@ -0,0 +1,532 @@+// SculptForge - open source digital sculpting+// SPDX-License-Identifier: GPL-3.0-or-later+//+// Studio controls (docs/guide/studios.md "IT deployment"): the managed policy file (core/ManagedPolicy.h), the AI+// audit log (core/AuditLog.h), provider presets and keys in the keychain (ai/Providers.h, ai/Secrets.h) and the+// studio sign-in against a mock identity provider (ai/Oidc.h).+#include "TestHarness.h"++#include "ai/AiCommands.h"+#include "ai/AiPolicy.h"+#include "ai/Http.h"+#include "ai/Oidc.h"+#include "ai/Providers.h"+#include "ai/Secrets.h"+#include "cli/McpServer.h"+#include "core/AuditLog.h"+#include "core/Keychain.h"+#include "core/ManagedPolicy.h"+#include "core/StudioProfile.h"++#include <filesystem>+#include <fstream>+#include <set>+#include <sstream>++using namespace sf;+namespace fs = std::filesystem;++namespace {++std::string tempDir(const char* name) {+ const fs::path d = fs::temp_directory_path() / (std::string("sf_studio_") + name);+ std::error_code ec;+ fs::remove_all(d, ec);+ fs::create_directories(d, ec);+ return d.string();+}++std::string readFile(const std::string& path) {+ std::ifstream f(path, std::ios::binary);+ std::stringstream ss;+ ss << f.rdbuf();+ return ss.str();+}++std::vector<std::string> lines(const std::string& text) {+ std::vector<std::string> out;+ std::stringstream ss(text);+ for (std::string l; std::getline(ss, l);)+ if (!l.empty()) out.push_back(l);+ return out;+}++policy::Policy parsed(const std::string& text) {+ policy::Policy p;+ std::string error;+ CHECK(policy::parsePolicy(text, "test", p, error));+ if (!error.empty()) std::printf(" policy error: %s\n", error.c_str());+ return p;+}++std::string parseError(const std::string& text) {+ policy::Policy p;+ std::string error;+ CHECK(!policy::parsePolicy(text, "test", p, error));+ return error;+}++// The policy, the audit log path, the keychain and the AI switch back as they were, whatever a test did.+struct StudioState {+ std::string auditDir;+ explicit StudioState(const char* name) : auditDir(tempDir(name)) {+ policy::resetPolicyForTests();+ audit::setPathForTests(auditDir + "/audit.jsonl");+ keychain::useMemoryForTests(true);+ ai::secrets::clearCacheForTests();+ ai::setAiEnabled(true);+ }+ ~StudioState() {+ policy::resetPolicyForTests();+ audit::setPathForTests({});+ audit::setClient("app");+ ai::secrets::clearCacheForTests();+ ai::oidc::setTransportForTests({});+ ai::oidc::setSleepForTests({});+ ai::oidc::setClockForTests({});+ ai::setAiEnabled(true);+ }+ std::string auditPath() const { return auditDir + "/audit.jsonl"; }+};++constexpr const char* kFullPolicy = R"({+ "format": "sculptforge-policy", "version": 1,+ "organization": "Acme Animation",+ "ai": {"enabled": true, "providers": ["litellm", "comfyui"], "endpoints": ["https://llm.acme.internal/"], "requireSignIn": true},+ "network": {"enabled": false, "allow": ["https://sw.acme.internal/"], "localNetwork": true},+ "mcp": {"enabled": true, "live": "never", "categories": ["info", "edit"]},+ "audit": {"path": "/mnt/audit/{user}@{host}.jsonl", "maxMB": 20, "keep": 10, "required": true},+ "signIn": {"issuer": "https://acme.okta.com/oauth2/default", "clientId": "0oa1abc", "scopes": ["openid", "email"],+ "useFor": ["https://llm.acme.internal/"]},+ "telemetry": "none",+ "updates": {"check": true, "channel": "stable", "feed": "https://sw.acme.internal/sculptforge/latest.json"}+})";++} // namespace++TEST(studio_policy_parses_every_key) {+ const policy::Policy p = parsed(kFullPolicy);+ CHECK(p.present && !p.broken && p.organization == "Acme Animation");+ CHECK(p.ai == policy::Lock::On && p.aiProviders.size() == 2 && p.aiEndpoints.size() == 1 && p.requireSignIn);+ CHECK(p.network == policy::Lock::Off && p.networkAllow.size() == 1 && p.localNetwork);+ CHECK(p.mcp == policy::Lock::On && !p.mcpLiveAllowed && p.mcpCategories.size() == 2);+ CHECK(p.auditPath == "/mnt/audit/{user}@{host}.jsonl" && p.auditMaxMB == 20 && p.auditKeep == 10 && p.auditRequired);+ CHECK(p.signInConfigured() && p.clientId == "0oa1abc" && p.scopes.size() == 2 && p.signInUseFor.size() == 1);+ CHECK(p.updateCheck == policy::Lock::On && p.updateChannel == "stable" && !p.updateFeed.empty());+ // Everything is optional: the smallest policy manages nothing.+ const policy::Policy empty = parsed(R"({"format": "sculptforge-policy", "version": 1})");+ CHECK(empty.ai == policy::Lock::Unset && empty.network == policy::Lock::Unset && empty.mcpLiveAllowed);+ CHECK(policy::describe(p).find("telemetry none") != std::string::npos);+}++TEST(studio_policy_rejects_mistakes) {+ // A typo never quietly drops a lock.+ CHECK(parseError(R"({"format": "sculptforge-policy", "version": 1, "AI": {}})").find("unknown key") != std::string::npos);+ CHECK(parseError(R"({"format": "sculptforge-policy", "version": 1, "ai": {"enable": false}})").find("ai.enable") !=+ std::string::npos);+ CHECK(!parseError(R"({"format": "sculptforge-studio", "version": 1})").empty());+ CHECK(!parseError(R"({"format": "sculptforge-policy", "version": 2})").empty());+ CHECK(!parseError(R"({"format": "sculptforge-policy", "version": 1, "ai": {"enabled": "no"}})").empty());+ CHECK(!parseError(R"({"format": "sculptforge-policy", "version": 1, "ai": {"providers": ["skynet"]}})").empty());+ CHECK(!parseError(R"({"format": "sculptforge-policy", "version": 1, "ai": {"endpoints": ["ftp://x/"]}})").empty());+ CHECK(!parseError(R"({"format": "sculptforge-policy", "version": 1, "mcp": {"categories": ["everything"]}})").empty());+ CHECK(!parseError(R"({"format": "sculptforge-policy", "version": 1, "mcp": {"live": "sometimes"}})").empty());+ // There is no telemetry to turn on.+ CHECK(parseError(R"({"format": "sculptforge-policy", "version": 1, "telemetry": true})").find("no telemetry") !=+ std::string::npos);+ CHECK(parsed(R"({"format": "sculptforge-policy", "version": 1, "telemetry": false})").present);+ // Sign-in required needs an identity provider; the issuer must be https.+ CHECK(!parseError(R"({"format": "sculptforge-policy", "version": 1, "ai": {"requireSignIn": true}})").empty());+ CHECK(!parseError(R"({"format": "sculptforge-policy", "version": 1, "signIn": {"issuer": "http://idp.acme.com", "clientId": "x"}})")+ .empty());+ CHECK(!parseError(R"({"format": "sculptforge-policy", "version": 1, "updates": {"channel": "nightly"}})").empty());+ CHECK(!parseError("not json").empty());+}++TEST(studio_policy_fails_closed) {+ const std::string dir = tempDir("failclosed");+ std::ofstream(dir + "/policy.json") << R"({"format": "sculptforge-policy", "version": 1, "ai": {"enabeld": true}})";+ std::vector<std::string> messages;+ const policy::Policy broken = policy::loadPolicyFile(dir + "/policy.json", "test", &messages);+ CHECK(broken.present && broken.broken && !messages.empty());+ CHECK(broken.ai == policy::Lock::Off && broken.network == policy::Lock::Off && broken.mcp == policy::Lock::Off);+ CHECK(!broken.mcpLiveAllowed && broken.updateCheck == policy::Lock::Off);+ const policy::Policy missing = policy::loadPolicyFile(dir + "/none.json", "test");+ CHECK(missing.broken && missing.ai == policy::Lock::Off);+ std::ofstream(dir + "/good.json") << kFullPolicy;+ CHECK(!policy::loadPolicyFile(dir + "/good.json", "test").broken);+}++TEST(studio_policy_locks_the_ai_switch) {+ StudioState state("ai_switch");+ CHECK(!ai::aiManaged());+ policy::Policy off = parsed(R"({"format": "sculptforge-policy", "version": 1, "ai": {"enabled": false}})");+ policy::setPolicyForTests(off);+ CHECK(ai::aiManaged() && ai::aiPolicyLocked() && !ai::aiFeaturesAllowed(true));+ CHECK(ai::aiOffError().find("studio") != std::string::npos);+ policy::setPolicyForTests(parsed(R"({"format": "sculptforge-policy", "version": 1, "ai": {"enabled": true}})"));+ CHECK(ai::aiManaged() && ai::aiPolicyLocked() && ai::aiFeaturesAllowed(false));+ policy::resetPolicyForTests();+ CHECK(!ai::aiFeaturesAllowed(false) && ai::aiFeaturesAllowed(true));+}++TEST(studio_policy_gates_ai_providers_and_endpoints) {+ StudioState state("gate");+ policy::setPolicyForTests(parsed(R"({"format": "sculptforge-policy", "version": 1,+ "ai": {"providers": ["litellm", "ollama"], "endpoints": ["https://llm.acme.internal/v1/", "http://localhost:11434/"]}})"));+ std::string error;+ CHECK(ai::aiRequestAllowed("litellm", "https://llm.acme.internal/v1/chat/completions", error));+ CHECK(!ai::aiRequestAllowed("anthropic", "https://llm.acme.internal/v1/chat/completions", error) &&+ error.find("provider") != std::string::npos);+ CHECK(!ai::aiRequestAllowed("litellm", "https://llm.acme.internal.evil.com/v1/chat", error));+ CHECK(!ai::aiRequestAllowed("litellm", "https://llm.acme.internal/v10/chat", error)); // a '/' boundary+ // Nothing is sent for a refused request: Brush Lab with the free tier, Generate 3D with Hugging Face.+ const uint64_t before = ai::httpRequestCount();+ ai::AiSettings free = ai::AiSettings::defaults(ai::AiSettings::Provider::Free);+ ai::ChatMessage m{ai::ChatMessage::Role::User, "a clay brush", "a clay brush"};+ const ai::BrushSuggestion s = ai::requestBrush(free, {m}, nullptr);+ CHECK(!s.ok && s.error.find("policy") != std::string::npos);+ ai::AiSettings anthropic = ai::withPreset(free, "anthropic");+ anthropic.apiKey = "sk-test";+ CHECK(!ai::requestBrush(anthropic, {m}, nullptr).ok);+ CHECK(ai::httpRequestCount() == before);+ // Sign-in required: refused until signed in.+ policy::Policy signIn = parsed(R"({"format": "sculptforge-policy", "version": 1, "ai": {"requireSignIn": true},+ "signIn": {"issuer": "https://idp.acme.test", "clientId": "sf"}})");+ policy::setPolicyForTests(signIn);+ ai::oidc::setTransportForTests({}); // (starts signed out)+ CHECK(!ai::aiRequestAllowed("free", "https://text.pollinations.ai/openai", error) && error.find("Sign in") != std::string::npos);+}++TEST(studio_policy_mcp_categories) {+ StudioState state("mcp_categories");+ CHECK(policy::mcpCategories("mesh_info", {}) == std::vector<std::string>{"info"});+ CHECK(policy::mcpCategories("remesh", {"resolution"}) == std::vector<std::string>{"edit"});+ CHECK(policy::mcpCategories("export_glb", {"path"}) == std::vector<std::string>{"files"});+ CHECK(policy::mcpCategories("macro_run", {"name"}) == std::vector<std::string>{"scripts"});+ const auto ai = policy::mcpCategories("image_to_3d", {"path"});+ CHECK(std::set<std::string>(ai.begin(), ai.end()) == std::set<std::string>({"ai", "network", "files"}));+ for (const auto& c : {"info", "edit", "files", "scripts", "network", "ai"})+ CHECK(std::find(policy::mcpCategoryNames().begin(), policy::mcpCategoryNames().end(), c) != policy::mcpCategoryNames().end());++ policy::setPolicyForTests(parsed(R"({"format": "sculptforge-policy", "version": 1, "mcp": {"categories": ["info", "edit"]}})"));+ CommandRegistry registry;+ Document doc;+ // tools/list leaves out what the policy doesn't allow.+ Json list;+ std::string err;+ CHECK(Json::parse(handleMcpMessage(registry, doc, R"({"jsonrpc":"2.0","id":1,"method":"tools/list"})"), list, err));+ std::set<std::string> names;+ for (const auto& t : list["result"]["tools"].items()) names.insert(t["name"].asString());+ CHECK(names.count("new_sphere") && names.count("mesh_info") && !names.count("export_glb") && !names.count("open"));+ // tools/call refuses it, says why, and the refusal is in the audit log.+ Json call;+ CHECK(Json::parse(handleMcpMessage(registry, doc,+ R"({"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"export_glb","arguments":{"path":"/tmp/x.glb"}}})"),+ call, err));+ CHECK(call["result"]["isError"].asBool() && call["result"]["content"][0]["text"].asString().find("policy") != std::string::npos);+ CHECK(readFile(state.auditPath()).find("\"export_glb\"") != std::string::npos);+ // MCP off: the server doesn't start.+ policy::setPolicyForTests(parsed(R"({"format": "sculptforge-policy", "version": 1, "mcp": {"enabled": false}})"));+ std::istringstream in(R"({"jsonrpc":"2.0","id":1,"method":"initialize","params":{}})");+ std::ostringstream out;+ CHECK(runMcpServer(registry, in, out) == 3 && out.str().empty());+ CHECK(!policy::mcpLiveAllowed());+ policy::resetPolicyForTests();+ CHECK(policy::mcpLiveAllowed() && policy::mcpToolAllowed("export_glb", {"path"}));+}++TEST(studio_audit_log_records_mcp_calls) {+ StudioState state("audit_mcp");+ CommandRegistry registry;+ Document doc;+ handleMcpMessage(registry, doc,+ R"({"jsonrpc":"2.0","id":1,"method":"initialize","params":{"clientInfo":{"name":"claude-code","version":"2.1.0"}}})");+ handleMcpMessage(registry, doc,+ R"({"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"new_sphere","arguments":{"subdivisions":3}}})");+ handleMcpMessage(registry, doc,+ R"({"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"brush_install","arguments":{"code":"SFB1-0123456789abcdef","api_key":"sk-secret"}}})");+ const auto l = lines(readFile(state.auditPath()));+ CHECK(l.size() == 2);+ Json first, second;+ std::string err;+ CHECK(Json::parse(l[0], first, err) && Json::parse(l[1], second, err));+ CHECK(first["client"].asString() == "mcp:claude-code 2.1.0" && first["tool"].asString() == "mcp");+ CHECK(first["command"].asString() == "new_sphere" && first["args"]["subdivisions"].asNumber() == 3);+ CHECK(first["result"].asString() == "ok" && first["time"].asString().size() == 24 && first["ms"].isNumber());+ CHECK(!first["user"].isNull() && !first["host"].asString().empty());+ // Secrets and artwork never reach the log.+ CHECK(second["args"]["api_key"].asString() == "<redacted>");+ CHECK(second["args"]["code"].asString().find("bytes") != std::string::npos);+ CHECK(l[1].find("sk-secret") == std::string::npos && l[1].find("0123456789abcdef") == std::string::npos);+}++TEST(studio_audit_log_rotates_and_can_be_required) {+ StudioState state("audit_rotate");+ policy::Policy p = parsed(R"({"format": "sculptforge-policy", "version": 1, "audit": {"maxMB": 0.1, "keep": 2}})");+ policy::setPolicyForTests(p);+ audit::Entry e;+ e.tool = "ai";+ e.command = "brush_ai";+ e.message = std::string(400, 'x');+ for (int i = 0; i < 1200; ++i) CHECK(audit::record(e));+ CHECK(fs::exists(state.auditPath()) && fs::exists(state.auditPath() + ".1") && fs::exists(state.auditPath() + ".2"));+ CHECK(!fs::exists(state.auditPath() + ".3"));+ CHECK(fs::file_size(state.auditPath()) <= uint64_t(0.1 * 1024 * 1024) + 1024);+ // Required and unwritable: the AI tool's call is refused before it runs.+ p.auditRequired = true;+ policy::setPolicyForTests(p);+ const std::string blocker = state.auditDir + "/file";+ std::ofstream(blocker) << "x";+ audit::setPathForTests(blocker + "/audit.jsonl"); // (a folder under a file can't exist)+ CommandRegistry registry;+ Document doc;+ Json call;+ std::string err;+ CHECK(Json::parse(handleMcpMessage(registry, doc,+ R"({"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"new_sphere","arguments":{}}})"),+ call, err));+ CHECK(call["result"]["isError"].asBool() && call["result"]["content"][0]["text"].asString().find("audit log") != std::string::npos);+ // The path template: user and host names can't climb out of the folder.+ CHECK(policy::expandPathTemplate("/a/{user}/x").find("..") == std::string::npos);+ CHECK(policy::expandPathTemplate("/a/b.jsonl") == "/a/b.jsonl");+}++TEST(studio_provider_presets) {+ std::set<std::string> ids;+ for (const ai::ProviderPreset& p : ai::providerPresets()) {+ CHECK(ids.insert(p.id).second); // unique+ // Every preset is one a studio's policy can name.+ CHECK(std::find(policy::aiProviderIds().begin(), policy::aiProviderIds().end(), p.id) != policy::aiProviderIds().end());+ CHECK(*p.label && *p.note);+ }+ for (const char* id : {"anthropic", "ollama", "lmstudio", "vllm", "llamacpp", "litellm", "openrouter"}) CHECK(ids.count(id));+ ai::AiSettings s = ai::withPreset(ai::AiSettings::defaults(ai::AiSettings::Provider::Free), "litellm");+ CHECK(s.provider == ai::AiSettings::Provider::OpenAICompatible && ai::providerId(s) == "litellm");+ s.endpoint = "https://llm.acme.internal/v1/chat/completions"; // the studio's own address keeps the preset+ CHECK(ai::providerId(ai::AiSettings::fromJson(s.toJson())) == "litellm");+ // An ai.json from before presets: its endpoint names the server.+ ai::AiSettings old = ai::AiSettings::defaults(ai::AiSettings::Provider::OpenAICompatible);+ CHECK(ai::providerId(old) == "ollama");+ old.endpoint = "http://gpu7:9000/v1/chat/completions";+ CHECK(ai::providerId(old) == "openai-compatible");+}++TEST(studio_keys_live_in_the_keychain) {+ StudioState state("keys");+ ai::AiSettings s = ai::withPreset(ai::AiSettings::defaults(ai::AiSettings::Provider::Free), "openrouter");+ s.apiKey = "sk-or-test";+ s.hfToken = "hf_test";+ s.falKey = "fal-test";+ s.meshyKey = "msy-test";+ const std::string json = s.toJson().dump();+ for (const char* secret : {"sk-or-test", "hf_test", "fal-test", "msy-test"}) CHECK(json.find(secret) == std::string::npos);+ CHECK(ai::secrets::storeKeys(s));+ std::string v;+ CHECK(keychain::load("ai/openrouter", v) && v == "sk-or-test");+ CHECK(keychain::load(ai::secrets::kHuggingFace, v) && v == "hf_test");+ // A fresh load gets them from the keychain.+ ai::secrets::clearCacheForTests();+ const ai::AiSettings loaded = ai::AiSettings::fromJson(s.toJson());+ CHECK(loaded.apiKey.empty() && loaded.resolvedKey() == "sk-or-test" && loaded.resolvedHfToken() == "hf_test");+ CHECK(loaded.resolvedFalKey() == "fal-test" && loaded.resolvedMeshyKey() == "msy-test");+ // An older ai.json with keys in it: moved to the keychain, and out of the file.+ keychain::useMemoryForTests(true);+ ai::secrets::clearCacheForTests();+ const std::string path = state.auditDir + "/ai.json";+ Json legacy = s.toJson();+ legacy.set("apiKey", "sk-or-old");+ legacy.set("hfToken", "hf_old");+ std::ofstream(path) << legacy.dump();+ std::string message;+ CHECK(ai::secrets::migrateLegacyKeys(path, message) && message.find("keychain") != std::string::npos);+ const std::string after = readFile(path);+ CHECK(after.find("sk-or-old") == std::string::npos && after.find("hf_old") == std::string::npos);+ CHECK(keychain::load("ai/openrouter", v) && v == "sk-or-old");+ CHECK(ai::AiSettings::load(path).resolvedHfToken() == "hf_old");+ // Nothing to move: the file is left alone.+ const auto stamp = fs::last_write_time(path);+ CHECK(ai::secrets::migrateLegacyKeys(path, message) && message.empty() && fs::last_write_time(path) == stamp);+}++namespace {++// A mock identity provider: discovery, device authorization and a token endpoint that answers "pending" a few+// times, then "slow_down" once, then tokens. It records what it was sent.+struct MockIdp {+ std::string issuer = "https://idp.acme.test/realms/art";+ int pendingPolls = 2;+ bool slowDownOnce = true;+ bool deny = false;+ bool advertiseDevice = true;+ std::string discoveredIssuer;+ std::vector<std::string> posts;+ int64_t clock = 1'800'000'000;+ int slept = 0;+ int refreshes = 0;++ static std::string idToken() {+ // {"sub":"u1","email":"[email protected]","name":"Ana Ruiz"} base64url, unsigned (display only)+ return "eyJhbGciOiJub25lIn0.eyJzdWIiOiJ1MSIsImVtYWlsIjoiYW5hQGFjbWUudGVzdCIsIm5hbWUiOiJBbmEgUnVpeiJ9.";+ }+ void install() {+ ai::oidc::setTransportForTests(+ {[this](const std::string& url) {+ ai::HttpResponse r;+ if (url != issuer + "/.well-known/openid-configuration") return r.status = 404, r;+ Json d = Json::object();+ d.set("issuer", discoveredIssuer.empty() ? issuer : discoveredIssuer);+ if (advertiseDevice) d.set("device_authorization_endpoint", issuer + "/device");+ d.set("token_endpoint", issuer + "/token");+ r.status = 200;+ r.body = d.dump();+ return r;+ },+ [this](const std::string& url, const std::string& body) {+ posts.push_back(url + " " + body);+ ai::HttpResponse r;+ r.status = 200;+ if (url == issuer + "/device") {+ r.body = R"({"device_code":"dev-123","user_code":"WDJB-MJHT","verification_uri":"https://idp.acme.test/device",+ "verification_uri_complete":"https://idp.acme.test/device?code=WDJB-MJHT","interval":2,"expires_in":300})";+ } else if (body.find("grant_type=refresh_token") != std::string::npos) {+ ++refreshes;+ r.body = R"({"access_token":"at-2","token_type":"Bearer","expires_in":3600})";+ } else if (deny) {+ r.status = 400, r.body = R"({"error":"access_denied"})";+ } else if (pendingPolls > 0) {+ --pendingPolls;+ r.status = 400, r.body = R"({"error":"authorization_pending"})";+ } else if (slowDownOnce) {+ slowDownOnce = false;+ r.status = 400, r.body = R"({"error":"slow_down"})";+ } else {+ Json t = Json::object();+ t.set("access_token", "at-1");+ t.set("token_type", "Bearer");+ t.set("expires_in", 600);+ t.set("refresh_token", "rt-1");+ t.set("id_token", idToken());+ r.body = t.dump();+ }+ return r;+ }});+ ai::oidc::setSleepForTests([this](int s) {+ slept += s;+ clock += s;+ });+ ai::oidc::setClockForTests([this] { return clock; });+ }+ policy::Policy policyFor() const {+ return parsed(R"({"format": "sculptforge-policy", "version": 1, "ai": {"endpoints": ["https://llm.acme.test/"]},+ "signIn": {"issuer": ")" + issuer + R"(", "clientId": "sculptforge-desktop", "audience": "sf-gateway"}})");+ }+};++} // namespace++TEST(studio_sign_in_device_flow_with_a_mock_idp) {+ StudioState state("oidc");+ MockIdp idp;+ policy::setPolicyForTests(idp.policyFor());+ idp.install();+ CHECK(ai::oidc::state() == ai::oidc::State::SignedOut);+ std::string shownCode, error;+ const bool ok = ai::oidc::signIn(+ [&](const ai::oidc::DeviceCode& c) {+ shownCode = c.userCode;+ CHECK(c.verificationUriComplete.find("WDJB-MJHT") != std::string::npos);+ return true;+ },+ {}, error);+ CHECK(ok && error.empty() && shownCode == "WDJB-MJHT");+ // Pending twice (2 s each), slow_down (+5 s), then the tokens: the client waited as RFC 8628 asks.+ CHECK(idp.slept == 2 + 2 + 2 + 7);+ CHECK(idp.posts.front().find("client_id=sculptforge-desktop") != std::string::npos);+ CHECK(idp.posts.front().find("scope=openid+profile+email+offline_access") != std::string::npos);+ CHECK(idp.posts.front().find("audience=sf-gateway") != std::string::npos);+ CHECK(idp.posts.back().find("grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Adevice_code") != std::string::npos);+ CHECK(ai::oidc::state() == ai::oidc::State::SignedIn && ai::oidc::signedInAs() == "Ana Ruiz");+ // The tokens are in the keychain, not a file.+ std::string secret;+ CHECK(keychain::load("sso/sculptforge-desktop", secret) && secret.find("at-1") != std::string::npos);+ // The bearer goes to the studio gateway only.+ CHECK(ai::oidc::bearerHeaderFor("https://llm.acme.test/v1/chat/completions") == "Authorization: Bearer at-1");+ CHECK(ai::oidc::bearerHeaderFor("https://api.openai.com/v1/chat/completions").empty());+ ai::AiSettings gw = ai::withPreset(ai::AiSettings::defaults(ai::AiSettings::Provider::Free), "litellm");+ gw.endpoint = "https://llm.acme.test/v1/chat/completions";+ gw.apiKey = "should-not-be-sent";+ const auto headers = ai::requestHeaders(gw);+ CHECK(std::find(headers.begin(), headers.end(), "Authorization: Bearer at-1") != headers.end());+ for (const auto& h : headers) CHECK(h.find("should-not-be-sent") == std::string::npos);+ // Expired: refreshed with the refresh token.+ idp.clock += 3600;+ CHECK(ai::oidc::accessToken() == "at-2" && idp.refreshes == 1);+ // Signing out forgets them.+ ai::oidc::signOut();+ CHECK(ai::oidc::state() == ai::oidc::State::SignedOut && !keychain::load("sso/sculptforge-desktop", secret));+ CHECK(ai::oidc::bearerHeaderFor("https://llm.acme.test/v1/chat/completions").empty());+}++TEST(studio_sign_in_refusals) {+ StudioState state("oidc_refusals");+ std::string error;+ {+ MockIdp idp;+ idp.deny = true;+ policy::setPolicyForTests(idp.policyFor());+ idp.install();+ CHECK(!ai::oidc::signIn({}, {}, error) && error.find("declined") != std::string::npos);+ CHECK(ai::oidc::state() == ai::oidc::State::SignedOut);+ }+ {+ MockIdp idp; // another issuer in the discovery document: refused before anything is posted+ idp.discoveredIssuer = "https://evil.test/";+ policy::setPolicyForTests(idp.policyFor());+ idp.install();+ CHECK(!ai::oidc::signIn({}, {}, error) && error.find("issuer") != std::string::npos && idp.posts.empty());+ }+ {+ MockIdp idp;+ idp.advertiseDevice = false;+ policy::setPolicyForTests(idp.policyFor());+ idp.install();+ CHECK(!ai::oidc::signIn({}, {}, error) && error.find("device") != std::string::npos);+ }+ {+ MockIdp idp; // the code runs out while the artist is away+ idp.pendingPolls = 1000;+ policy::setPolicyForTests(idp.policyFor());+ idp.install();+ CHECK(!ai::oidc::signIn({}, {}, error) && error.find("expired") != std::string::npos);+ }+ {+ MockIdp idp; // cancelled from the panel+ idp.pendingPolls = 1000;+ policy::setPolicyForTests(idp.policyFor());+ idp.install();+ int calls = 0;+ CHECK(!ai::oidc::signIn({}, [&] { return ++calls > 3; }, error) && error.find("cancelled") != std::string::npos);+ }+ // Parsers on their own.+ ai::oidc::Tokens t;+ CHECK(ai::oidc::parseTokenReply(400, R"({"error":"expired_token"})", 0, t, error) == ai::oidc::TokenReply::Expired);+ CHECK(ai::oidc::parseTokenReply(200, R"({"access_token":"x","token_type":"mac"})", 0, t, error) == ai::oidc::TokenReply::Error);+ ai::oidc::DeviceCode d;+ CHECK(!ai::oidc::parseDeviceCode(R"({"device_code":"a","user_code":"b","verification_uri":"http://evil.test/"})", 0, d, error));+ CHECK(ai::oidc::parseIdToken("garbage").display().empty());+ policy::resetPolicyForTests();+ CHECK(ai::oidc::state() == ai::oidc::State::NotConfigured && !ai::oidc::signIn({}, {}, error));+}++TEST(studio_policy_network_off_is_studio_mode) {+ const policy::Policy p = parsed(kFullPolicy);+ const net::NetworkPolicy n = withManagedPolicy({}, p);+ CHECK(n.offline && n.localNetwork);+ auto allowed = [&](const std::string& u) { return std::find(n.allow.begin(), n.allow.end(), u) != n.allow.end(); };+ CHECK(allowed("https://sw.acme.internal/") && allowed("https://llm.acme.internal/") && allowed("https://acme.okta.com/"));+ CHECK(allowed("https://sw.acme.internal/sculptforge/latest.json"));+ // Network on (or not managed): unchanged.+ const net::NetworkPolicy open = withManagedPolicy({}, parsed(R"({"format": "sculptforge-policy", "version": 1})"));+ CHECK(!open.offline && open.allow.empty());+}diff --git a/tests/ui/ai_provider.sfui b/tests/ui/ai_provider.sfuiindex 7cc461ba..e6bf32c7 100644--- a/tests/ui/ai_provider.sfui+++ b/tests/ui/ai_provider.sfui@@ -11,11 +11,10 @@ expect_not "Endpoint"shot ai-freeclick "##provider"-click "OpenAI-compatible (OpenAI, Ollama, LM Studio...)"-expect "Ollama"-expect "LM Studio"+click "Ollama (this computer)"expect "Find models"expect "Endpoint"+expect_text Private: the model runs on this computerclick "Run a model on this computer"expect_text ollama pull qwen3:4b-instructshot ai-local-help@@ -27,6 +26,7 @@ wait_idle 15expect_text Nothing is answeringshot ai-not-running-click "LM Studio"-click "Ollama"+# Another preset starts fresh.+click "##provider"+click "LM Studio (this computer)"expect_no_text Nothing is answeringdiff --git a/tests/ui/studio_policy.sfui b/tests/ui/studio_policy.sfuinew file mode 100644index 00000000..6a28ba3d--- /dev/null+++ b/tests/ui/studio_policy.sfui@@ -0,0 +1,42 @@+# A studio's policy file (core/ManagedPolicy.h, docs/guide/studios.md "IT deployment"): each locked setting says+# "Managed by your studio"; Preferences > AI shows the studio, the studio sign-in and the audit log; providers the+# policy doesn't allow are greyed; a broken policy fails closed (AI off). ui_policy exists only in UI tests.+run ui_look look=classic layout=classic # written for the Classic look and the classic palette bar and shelves+run ui_policy json="{\"format\":\"sculptforge-policy\",\"version\":1,\"organization\":\"Acme Animation\",\"ai\":{\"enabled\":true,\"providers\":[\"litellm\",\"ollama\"],\"endpoints\":[\"https://llm.acme.internal/\"],\"requireSignIn\":true},\"mcp\":{\"live\":\"never\",\"categories\":[\"info\",\"edit\"]},\"signIn\":{\"issuer\":\"https://acme.okta.com/oauth2/default\",\"clientId\":\"0oa1example\"},\"updates\":{\"channel\":\"stable\"}}"+expect_value ai_enabled == 1+click "Preferences##palette.preferences"+click "AI##preferences.ai"+expect_text Managed by your studio+expect_text Managed by Acme Animation+expect_text Studio sign-in+expect "Sign in with your studio account"+expect_text Your studio requires the sign-in for AI features.+expect_text Audit log+expect_text AI tools work on their own scene+expect_text SculptForge has no telemetry+shot studio-policy-ai++# Only the allowed providers can be picked.+click "##provider"+shot studio-policy-providers+key escape # (closes Preferences too)++click "Preferences##palette.preferences"+click "AI##preferences.ai" # (closed, so Updates is on screen)+click "Updates##preferences.updates"+expect_text Managed by your studio+shot studio-policy-updates++# A broken policy (a typo in a key) turns AI, network features and AI tools off until it is fixed.+run ui_policy json="{\"format\":\"sculptforge-policy\",\"version\":1,\"ai\":{\"enabeld\":true}}"+expect_value ai_enabled == 0+expect_not "AI Brush"+run_fails brush_ai prompt=sharp+expect_value http_requests == 0+click "Updates##preferences.updates"+click "AI##preferences.ai"+expect_text The studio policy can't be used+shot studio-policy-broken++run ui_policy json=""+expect_value ai_enabled == 1diff --git a/tools/release/sbom.py b/tools/release/sbom.pynew file mode 100755index 00000000..3aecaa0b--- /dev/null+++ b/tools/release/sbom.py@@ -0,0 +1,108 @@+#!/usr/bin/env python3+# SculptForge - open source digital sculpting+# SPDX-License-Identifier: GPL-3.0-or-later+"""Writes the release's software bill of materials (CycloneDX 1.5 JSON) for IT reviews (docs/guide/security.md).++ tools/release/sbom.py --version 0.11.4 --out dist/SculptForge-0.11.4-sbom.cdx.json+ tools/release/sbom.py --check every fetched pin is in THIRD_PARTY_NOTICES.md (ctest sbom)++Components come from THIRD_PARTY_NOTICES.md's first table (name, version, licence, what for); the archives the build+fetches add their URL and SHA-256 from cmake/Fetch.cmake's pins. The release workflow writes it into dist/ before the+checksums, so SHA256SUMS.txt and its signature cover it.+"""+import argparse+import json+import re+import sys+import uuid+from pathlib import Path++ROOT = Path(__file__).resolve().parents[2]+NOTICES = ROOT / "THIRD_PARTY_NOTICES.md"+FETCH = ROOT / "cmake" / "Fetch.cmake"++# Fetch.cmake pin name -> the component's name in THIRD_PARTY_NOTICES.md+PIN_NAMES = {"glm": "GLM", "SDL3": "SDL 3", "imgui": "Dear ImGui", "mbedtls": "Mbed TLS", "libdatachannel": "libdatachannel",+ "ldc_usrsctp": "usrsctp", "ldc_libjuice": "libjuice", "ldc_plog": "plog", "pybind11": "pybind11"}+LICENSES = {"MIT License": "MIT", "zlib License": "Zlib", "BSD 3-Clause License": "BSD-3-Clause",+ "Apache License 2.0": "Apache-2.0", "Mozilla Public License 2.0": "MPL-2.0",+ "SIL Open Font License 1.1": "OFL-1.1", "CC0 1.0 (public domain)": "CC0-1.0", "BSD-style": "BSD-3-Clause"}+++def pins():+ text = FETCH.read_text(encoding="utf-8")+ return {m[0]: (m[1], m[2]) for m in re.findall(r"set\(SF_PIN_(\w+)\s+(\S+)\s+([0-9a-f]{64})\)", text)}+++def notice_rows():+ rows = []+ for line in NOTICES.read_text(encoding="utf-8").splitlines():+ if line.startswith("| Tool |"):+ break # the second table: tools downloaded at run time, not in the binaries+ cells = [c.strip() for c in line.strip().strip("|").split("|")]+ if len(cells) < 4 or cells[0] in ("Component", "") or set(cells[0]) <= {"-", " "}:+ continue+ m = re.match(r"\[([^\]]+)\]\(([^)]+)\)", cells[0])+ name, url = (m.group(1), m.group(2)) if m else (cells[0], "")+ rows.append({"name": name, "url": url, "version": cells[1], "license": cells[2], "use": cells[3]})+ return rows+++def license_entry(text):+ for k, v in LICENSES.items():+ if text.startswith(k):+ return {"license": {"id": v}}+ return {"license": {"name": text[:120]}}+++def build(version):+ p = pins()+ by_name = {v: k for k, v in PIN_NAMES.items()}+ components = []+ for r in notice_rows():+ if "not shipped" in r["use"] or "nothing vendored" in r["version"] or r["version"] in ("—", "colour values only") or "formulas only" in r["version"]:+ continue # credited references, not code in the binaries+ c = {"type": "library", "name": r["name"], "version": r["version"], "description": r["use"][:300],+ "licenses": [license_entry(r["license"])]}+ if r["url"]:+ c["externalReferences"] = [{"type": "website", "url": r["url"]}]+ pin = by_name.get(r["name"])+ if pin and pin in p:+ url, sha = p[pin]+ c["hashes"] = [{"alg": "SHA-256", "content": sha}]+ c.setdefault("externalReferences", []).append({"type": "distribution", "url": url})+ components.append(c)+ return {+ "bomFormat": "CycloneDX", "specVersion": "1.5", "version": 1,+ "serialNumber": "urn:uuid:" + str(uuid.uuid5(uuid.NAMESPACE_URL, "https://sculptforge.app/sbom/" + version)),+ "metadata": {"component": {"type": "application", "name": "SculptForge", "version": version,+ "licenses": [{"license": {"id": "GPL-3.0-or-later"}}]}},+ "components": components,+ }+++def main():+ ap = argparse.ArgumentParser()+ ap.add_argument("--version", default="0.0.0")+ ap.add_argument("--out")+ ap.add_argument("--check", action="store_true")+ a = ap.parse_args()+ if a.check:+ names = {r["name"] for r in notice_rows()}+ missing = [PIN_NAMES.get(k, k) for k in pins() if PIN_NAMES.get(k, k) not in names and k != "pybind11"]+ unmapped = [k for k in pins() if k not in PIN_NAMES]+ if missing or unmapped:+ print("sbom: fetched but not in THIRD_PARTY_NOTICES.md:", ", ".join(missing + unmapped))+ return 1+ print(f"sbom: {len(build(a.version)['components'])} components")+ return 0+ text = json.dumps(build(a.version), indent=2) + "\n"+ if a.out:+ Path(a.out).write_text(text, encoding="utf-8")+ else:+ sys.stdout.write(text)+ return 0+++if __name__ == "__main__":+ sys.exit(main())