Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

feat(os): share connected accounts across local agents (#1024)

Dee023ae4117d4a
diff --git a/docs/naming-system.md b/docs/naming-system.md
index b9bb0818d..90fdc7d1e 100644
--- a/docs/naming-system.md
+++ b/docs/naming-system.md
@@ -58,6 +58,7 @@ and **Browser**. Technical documentation may still call the terminal interface a
| **Project** | The files and working context for the work, on a particular computer. | Choose the website project. |
| **Task** | The work requested. | Add a search field. |
| **Browser** | The optional browser for web content and visual review. | Open the browser. |
+| **Connections** | Service accounts available to agents running as the same local user on a Harness computer. | Open Connections; connect GitHub. |
| **Viewer** | A surface for inspecting or interacting with work. | The game viewer; the HTML preview. |
| **This computer** | The local execution machine. | Run on This computer. |
| **Store** | The catalog of reusable harnesses and viewers. | Install a harness from the Store. |
diff --git a/os/INSTALL.md b/os/INSTALL.md
index 86f827403..ce3ed5398 100644
--- a/os/INSTALL.md
+++ b/os/INSTALL.md
@@ -1,6 +1,6 @@
# Install Harness on a ThinkPad
-These instructions are for **0.1.1**, using a Mac to prepare the USB.
+These instructions are for **0.1.2-preview.1**, using a Mac to prepare the USB.
The USB opens the installer directly. Installation begins only when you choose **Install Harness**
in the installer; it erases the entire selected disk.
@@ -21,20 +21,20 @@ compute still need testing on the actual hardware.
## 2. Download and verify on the Mac
-From the [0.1.1 release](https://github.com/autonomous-ai/openharness/releases/tag/os-v0.1.1),
+From the [0.1.2-preview.1 release](https://github.com/autonomous-ai/openharness/releases/tag/os-v0.1.2-preview.1),
download both files into the same folder:
-- `harness-0.1.1-x86_64.iso`
-- `harness-0.1.1-x86_64.iso.sha256`
+- `harness-0.1.2-preview.1-x86_64.iso`
+- `harness-0.1.2-preview.1-x86_64.iso.sha256`
If they are in Downloads, open Terminal and run:
```sh
cd ~/Downloads
-shasum -a 256 -c harness-0.1.1-x86_64.iso.sha256
+shasum -a 256 -c harness-0.1.2-preview.1-x86_64.iso.sha256
```
-The result must say `harness-0.1.1-x86_64.iso: OK`.
+The result must say `harness-0.1.2-preview.1-x86_64.iso: OK`.
If it does not, download the files again before flashing.
## 3. Flash the USB
diff --git a/os/README.md b/os/README.md
index 4d518881d..90a244514 100644
--- a/os/README.md
+++ b/os/README.md
@@ -11,7 +11,7 @@ audience, not its name.
Product names and interface copy follow the [Naming System](../docs/naming-system.md).
-**Harness 0.1.1:** the USB opens the installer directly. Installation works offline.
+**Harness 0.1.2-preview.1:** the USB opens the installer directly. Installation works offline.
After shutdown, remove the USB and boot the installed disk. If disconnected,
the Wi-Fi page opens first and advances automatically when connected; Ethernet
skips that step. OpenCode starts on the left with two real terminals on the right.
@@ -77,6 +77,18 @@ hardware and automatic T2 kernel upgrades remain unverified. Apple Silicon and R
installable Harness images yet. See the [hardware targets](DEVELOPMENT.md#mac-support-targets)
for requirements and remaining work.
+## Connected accounts
+
+Run `harness connections` to open the local Connections page. Connect GitHub,
+Notion, Linear, Asana or Figma with a personal token, then any local agent can
+use the account through the same CLI. Tokens stay outside projects and agent
+configuration. No Intern hardware or device registration is required.
+
+This preview includes manual-token connections. Browser OAuth and automatic
+token renewal are not available yet. Existing installations receive the feature
+through the OS update channel after publication; no reinstall is needed. See
+[Connections](connectors/README.md) for the exact scope and validation limits.
+
## Design
- Arch Linux, glibc, systemd and the LTS kernel. User space is rolling; LTS here
diff --git a/os/connectors/LICENSE b/os/connectors/LICENSE
new file mode 100644
index 000000000..d64569567
--- /dev/null
+++ b/os/connectors/LICENSE
@@ -0,0 +1,202 @@
+
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright [yyyy] [name of copyright owner]
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
diff --git a/os/connectors/README.md b/os/connectors/README.md
new file mode 100644
index 000000000..59f9fb407
--- /dev/null
+++ b/os/connectors/README.md
@@ -0,0 +1,97 @@
+# Harness connections
+
+An OS-owned CLI and on-demand local settings page. No new engine integration,
+MCP server, desktop release, always-on daemon or third-party Python dependency.
+
+## Provenance
+
+`connector.py` and `../tests/test_connector_upstream.py` are adapted from
+[Autonomous Intern](https://github.com/autonomous-ai/Physical-AI-Operating-System)
+at `57faee5d8e7ee094701120c9bff4ce6ef8001fb2`:
+
+- `skills/connectors/scripts/connector.py`
+- `skills/connectors/tests/test_connector.py`
+
+Licensed under Apache-2.0; see LICENSE. Harness changes: per-user paths, private
+atomic storage shared across agents, JSON discovery, expiry
+handling, Figma/Linear personal-token headers, response size checks and local
+connection management. The small service guide adapts Intern's connector
+instructions; it omits Intern hardware, MQTT and agent-runtime setup.
+
+Provider-specific authentication was checked against
+[Figma](https://developers.figma.com/docs/rest-api/personal-access-tokens/),
+[Linear](https://linear.app/developers/graphql) and their account identity
+endpoints. Provider account tests remain a separate acceptance requirement.
+
+## Commands
+
+```sh
+harness connections # opens local settings; exits immediately
+harness connections list --json # no secrets; shared by all local agents
+harness connections info github
+harness connections call github GET https://api.github.com/user
+harness connections disconnect github
+```
+
+State is under `$XDG_DATA_HOME/harness-os/connections`, normally
+`~/.local/share/harness-os/connections`: directory 0700, files 0600. The
+per-service JSON shape stays compatible with Intern. Credentials are not copied
+into projects or agent config. This avoids routine token exposure; it is not a
+sandbox against an agent running arbitrary code as the same Unix user.
+
+The page binds only 127.0.0.1, requires an unpredictable per-process capability
+for every API request, validates Host/Origin, serves no CORS access and does not
+log requests. Its capability is delivered in a URL fragment and retained only
+in that browser tab's session storage so refreshing the page works.
+Nothing is loaded from a CDN. The process exits after 15 minutes without
+authenticated requests; reopening the CLI reuses a live instance or starts one.
+
+## Architecture
+
+Connections belong to the local user on an ordinary computer running Harness.
+Connect an account once, then Claude Code, Codex, OpenCode, pi or another agent
+can use the same CLI and service instructions. Agents name a connection; the CLI
+reads its credentials. Changing agents does not require reconnecting accounts.
+Another computer or Unix user has a separate connection store.
+
+Intern is the source of the reusable connector code. There is no Intern device,
+MQTT connection, device key, hardware registration or additional agent runtime.
+No provider app secret belongs in an OS image, project or agent configuration.
+The settings page runs only when needed and does not require a cloud account for
+manual token connections.
+
+## Browser sign-in — not implemented yet
+
+Manual tokens work for GitHub, Notion, Linear, Asana and Figma. Browser OAuth and
+automatic renewal are not enabled. Expired credentials remain saved but cannot
+be used; the CLI asks the user to reconnect. A `backend.json` from an earlier
+development draft is ignored and cannot enable Intern device authentication.
+
+The remaining integration must deliver the result of browser consent to the
+local connection request, without an Intern device record. For providers that
+require a confidential OAuth client, its secret stays on the authorization
+server. The computer receives the user's authorized credentials and stores them
+locally. Credential delivery must be short-lived, single-use and bound to the
+requesting client; renewal must handle concurrent agents and rotated tokens.
+Disconnecting local access and revoking access at the provider are different
+operations and must be described accurately.
+
+The existing Intern server code was reviewed read-only. Its provider integration
+can inform this work, but its hardware delivery mechanism is not an OS
+requirement. No private backend implementation or configuration is included.
+Do not add device enrollment or require a different product account to bridge
+that gap. Complete real browser sign-in, renewal, disconnect and cross-agent
+acceptance before enabling OAuth-only services such as Gmail, Calendar and Drive.
+
+## Local review
+
+```sh
+CONNECTOR_CONFIGS_DIR=/tmp/harness-connections-review \
+ python3 os/connectors/connections.py serve
+```
+
+Open the printed local URL. This creates only isolated review state; enter a
+real token only when intentionally testing that account. Unit tests use mocked
+provider responses and disposable credentials. Packaging includes the CLI,
+page, guide and license in the normal OS package, so installed machines receive
+it via an OS update without an ISO. No update has been published by this change.
diff --git a/os/connectors/connection_store.py b/os/connectors/connection_store.py
new file mode 100644
index 000000000..b30362f96
--- /dev/null
+++ b/os/connectors/connection_store.py
@@ -0,0 +1,192 @@
+"""Per-user Intern-format credentials. No engine-specific copies or cloud sync."""
+import contextlib
+import fcntl
+import json
+import os
+from pathlib import Path
+import stat
+import tempfile
+import time
+import urllib.request
+
+SERVICES = {
+ "gmail": "Gmail", "google_calendar": "Google Calendar", "google_drive": "Google Drive",
+ "github": "GitHub", "notion": "Notion", "linear": "Linear", "asana": "Asana",
+ "figma": "Figma", "figma-api": "Figma API", "facebook": "Facebook", "ahrefs": "Ahrefs",
+}
+MAX_BYTES = 65536
+
+
+class StoreError(Exception):
+ """Safe, credential-free diagnostic."""
+
+
+def directory():
+ base = Path(os.environ.get("XDG_DATA_HOME", str(Path.home() / ".local/share")))
+ return Path(os.environ.get("CONNECTOR_CONFIGS_DIR", str(base / "harness-os/connections")))
+
+
+def validate_code(code):
+ if code not in SERVICES:
+ raise StoreError("Unknown connection.")
+ return code
+
+
+def private_directory(root):
+ root.mkdir(mode=0o700, parents=True, exist_ok=True)
+ info = root.lstat()
+ if not stat.S_ISDIR(info.st_mode) or info.st_uid != os.getuid():
+ raise StoreError("Connections must be stored in your own directory, without a symlink.")
+ root.chmod(0o700)
+
+
+def read_private(path):
+ try:
+ fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK)
+ except FileNotFoundError:
+ return None
+ except OSError:
+ raise StoreError("Cannot read connection settings.")
+ with os.fdopen(fd, "rb") as handle:
+ info = os.fstat(handle.fileno())
+ if (not stat.S_ISREG(info.st_mode) or info.st_uid != os.getuid() or
+ stat.S_IMODE(info.st_mode) & 0o077 or info.st_size > MAX_BYTES):
+ raise StoreError("Connection settings must be private, regular files owned by you.")
+ try:
+ data = json.loads(handle.read(MAX_BYTES + 1))
+ except (ValueError, OSError):
+ raise StoreError("Cannot read connection settings.")
+ if not isinstance(data, dict):
+ raise StoreError("Invalid connection settings.")
+ return data
+
+
+def write_private(path, data):
+ private_directory(path.parent)
+ raw = (json.dumps(data, indent=2) + "\n").encode()
+ if len(raw) > MAX_BYTES:
+ raise StoreError("Connection settings are too large.")
+ fd, name = tempfile.mkstemp(prefix=".incoming-", dir=path.parent)
+ try:
+ with os.fdopen(fd, "wb") as handle:
+ handle.write(raw)
+ handle.flush()
+ os.fsync(handle.fileno())
+ os.replace(name, path)
+ finally:
+ Path(name).unlink(missing_ok=True)
+
+
+def locked(root):
+ private_directory(root)
+ fd = os.open(root / ".lock", os.O_RDWR | os.O_CREAT | os.O_NOFOLLOW | os.O_NONBLOCK, 0o600)
+ with os.fdopen(fd, "r+") as handle:
+ info = os.fstat(handle.fileno())
+ if not stat.S_ISREG(info.st_mode) or info.st_uid != os.getuid():
+ raise StoreError("Invalid connection lock.")
+ # Serialize credential changes across agents running as this user.
+ deadline = time.monotonic() + 35
+ while True:
+ try:
+ fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
+ break
+ except BlockingIOError:
+ if time.monotonic() >= deadline:
+ raise StoreError("Another connection operation is still running. Try again.")
+ time.sleep(0.05)
+ try:
+ yield
+ finally:
+ fcntl.flock(fd, fcntl.LOCK_UN)
+
+
+def clean_entry(entry):
+ if not isinstance(entry, dict):
+ raise StoreError("Invalid connection.")
+ result = {}
+ for key in ("access_token", "api_key", "refresh_token", "token_type", "client_id", "user_email", "auth_type"):
+ value = entry.get(key, "")
+ if not isinstance(value, str) or len(value) > 8192 or any(ord(c) < 32 or ord(c) == 127 for c in value):
+ raise StoreError("Invalid connection fields.")
+ if value:
+ result[key] = value
+ if result.get("auth_type", "oauth") not in ("pat", "oauth"):
+ raise StoreError("Unsupported authentication type.")
+ if not (result.get("access_token") or result.get("api_key")):
+ raise StoreError("No access token was supplied.")
+ for key in ("expires_at", "obtained_at"):
+ value = entry.get(key, 0)
+ if type(value) is not int or value < 0:
+ raise StoreError("Invalid connection expiry.")
+ result[key] = value
+ scopes = entry.get("scopes", [])
+ if not isinstance(scopes, list) or len(scopes) > 100 or any(not isinstance(s, str) or len(s) > 1024 for s in scopes):
+ raise StoreError("Invalid connection permissions.")
+ result["scopes"] = scopes
+ result["refresh"] = entry.get("refresh") is True
+ creds = entry.get("credentials", {})
+ if not isinstance(creds, dict):
+ raise StoreError("Invalid connection metadata.")
+ result["credentials"] = {k: v for k, v in creds.items() if k in ("page_id", "email") and isinstance(v, str) and len(v) < 1024}
+ return result
+
+
+class NoRedirect(urllib.request.HTTPRedirectHandler):
+ def redirect_request(self, req, fp, code, msg, headers, newurl):
+ return None
+
+
+class Store:
+ def __init__(self, root=None):
+ self.root = directory() if root is None else Path(root)
+
+ def path(self, code):
+ return self.root / (validate_code(code) + "_access_tokens.json")
+
+ def load(self, code):
+ if self.root.is_symlink():
+ raise StoreError("Connection storage must not be a symlink.")
+ data = read_private(self.path(code))
+ if data is None:
+ return None
+ entries = data.get("connectors")
+ if not isinstance(entries, dict):
+ raise StoreError("Invalid connection settings.")
+ entry = entries.get(code)
+ return clean_entry(entry)
+
+ def save(self, code, entry):
+ path = self.path(code)
+ entry = clean_entry(entry)
+ with locked(self.root):
+ write_private(path, {"connectors": {code: entry}})
+
+ def disconnect(self, code):
+ path = self.path(code)
+ with locked(self.root):
+ path.unlink(missing_ok=True)
+
+ def ready(self, code):
+ with locked(self.root):
+ entry = self.load(code)
+ if not entry:
+ raise StoreError("Not connected. Open harness connections to connect an account.")
+ expires = entry["expires_at"]
+ if expires and expires <= time.time():
+ raise StoreError("This account has expired. Reconnect it in Connections.")
+ return entry
+
+ def status(self, code):
+ entry = self.load(code)
+ if not entry:
+ return {"connector": code, "name": SERVICES[code], "state": "not_connected", "scopes": []}
+ expires = entry["expires_at"]
+ return {
+ "connector": code, "name": SERVICES[code],
+ "state": "expired" if expires and expires <= time.time() else "connected",
+ "account": entry.get("user_email") or entry["credentials"].get("email", ""),
+ "auth_type": entry.get("auth_type", "oauth"), "scopes": entry["scopes"],
+ "expires_at": expires or None,
+ "auto_refresh": False, # Browser authorization and renewal are not enabled yet.
+ }
diff --git a/os/connectors/connections.py b/os/connectors/connections.py
new file mode 100644
index 000000000..bf562fce1
--- /dev/null
+++ b/os/connectors/connections.py
@@ -0,0 +1,281 @@
+#!/usr/bin/env python3
+"""On-demand, loopback-only Connections page for Harness OS."""
+import argparse
+import contextlib
+import hmac
+from http.server import BaseHTTPRequestHandler, HTTPServer
+import io
+import json
+import os
+from pathlib import Path
+import re
+import secrets
+import shutil
+import subprocess
+import sys
+import time
+import urllib.request
+
+import connector
+import connection_store as store
+
+ASSETS = Path(__file__).parent / "web"
+
+
+def identity_proof(key, nonce):
+ return hmac.new(key.encode(), ("harness-connections-v1:" + nonce).encode(), "sha256").hexdigest()
+
+
+# Read-only identity checks. API keys are not saved until the check succeeds.
+# OAuth-only services stay unavailable until browser authorization and renewal
+# work for a local Harness user. Intern hardware enrollment is not part of this.
+MANUAL = {
+ "github": ("GET", "https://api.github.com/user", [], "https://github.com/settings/tokens"),
+ "notion": ("GET", "https://api.notion.com/v1/users/me", [], "https://www.notion.so/profile/integrations"),
+ "linear": ("POST", "https://api.linear.app/graphql", ["--json", '{"query":"{ viewer { id name email } }"}'],
+ "https://linear.app/settings/api"),
+ "asana": ("GET", "https://app.asana.com/api/1.0/users/me", [], "https://app.asana.com/0/my-apps"),
+ "figma": ("GET", "https://api.figma.com/v1/me", [], "https://developers.figma.com/docs/rest-api/personal-access-tokens/"),
+}
+
+
+def catalog(vault):
+ items = []
+ for code in store.SERVICES:
+ if code == "figma-api" and not vault.path(code).exists():
+ continue
+ try:
+ item = vault.status(code)
+ except store.StoreError:
+ item = {"connector": code, "name": store.SERVICES[code], "state": "unreadable", "scopes": []}
+ item["manual"] = code in MANUAL
+ item["manage_url"] = MANUAL[code][3] if code in MANUAL else None
+ items.append(item)
+ return items
+
+
+def connect_token(vault, code, token):
+ if code not in MANUAL:
+ raise store.StoreError("Browser sign-in is not available for this service yet.")
+ entry = store.clean_entry({"auth_type": "pat", "api_key": token, "obtained_at": int(time.time())})
+ method, url, args, _ = MANUAL[code]
+ output, error = io.StringIO(), io.StringIO()
+ with contextlib.redirect_stdout(output), contextlib.redirect_stderr(error):
+ status = connector.cmd_call(code, method, url, args, entry_override=entry)
+ if status:
+ raise store.StoreError("Could not verify this token. Check its permissions and your connection, then try again.")
+ try:
+ result = json.loads(output.getvalue())
+ if not isinstance(result, dict):
+ raise ValueError()
+ if code == "linear":
+ if result.get("errors"):
+ raise ValueError()
+ account = result["data"]["viewer"]
+ elif code == "asana":
+ account = result["data"]
+ else:
+ account = result
+ if not isinstance(account, dict) or not (account.get("id") or account.get("gid")):
+ raise ValueError()
+ identity = account.get("email") or account.get("login") or account.get("name") or account.get("handle") or ""
+ if not isinstance(identity, str):
+ raise ValueError()
+ entry["user_email"] = identity[:512]
+ except (ValueError, KeyError, TypeError):
+ raise store.StoreError("The service did not confirm this account. The token was not saved.")
+ vault.save(code, entry)
+ return vault.status(code)
+
+
+class PageServer(HTTPServer):
+ allow_reuse_address = False
+
+ def __init__(self, vault=None, port=0, idle_seconds=900):
+ self.vault = vault or store.Store()
+ self.key = secrets.token_urlsafe(32)
+ self.idle_seconds = idle_seconds
+ self.last_request = time.monotonic()
+ super().__init__(("127.0.0.1", port), PageHandler)
+ self.origin = "http://127.0.0.1:" + str(self.server_address[1])
+ self.timeout = 1
+
+ def serve_until_idle(self):
+ while time.monotonic() - self.last_request < self.idle_seconds:
+ self.handle_request()
+
+
+class PageHandler(BaseHTTPRequestHandler):
+ server_version = "Harness"
+
+ def setup(self):
+ super().setup()
+ self.connection.settimeout(5)
+
+ def log_message(self, *_args):
+ pass # Do not log account names, request bodies or session credentials.
+
+ def reply(self, status, body, content_type="application/json"):
+ raw = json.dumps(body).encode() if content_type == "application/json" else body
+ self.send_response(status)
+ self.send_header("Content-Type", content_type)
+ self.send_header("Content-Length", str(len(raw)))
+ self.send_header("Cache-Control", "no-store")
+ self.send_header("X-Content-Type-Options", "nosniff")
+ self.send_header("Referrer-Policy", "no-referrer")
+ self.send_header("Content-Security-Policy", "default-src 'none'; script-src 'self'; style-src 'self'; connect-src 'self'; frame-ancestors 'none'; base-uri 'none'; form-action 'none'")
+ self.end_headers()
+ self.wfile.write(raw)
+
+ def local(self):
+ return (self.headers.get("Host") == self.server.origin.removeprefix("http://") and
+ self.headers.get("Sec-Fetch-Site", "none") in ("none", "same-origin"))
+
+ def authenticated(self):
+ key = self.headers.get("X-Harness-Connections", "")
+ return self.local() and hmac.compare_digest(key.encode(), self.server.key.encode())
+
+ def do_GET(self):
+ if not self.local():
+ self.reply(403, {"error": "Open Connections from this computer."})
+ return
+ if self.path == "/api/identity":
+ nonce = self.headers.get("X-Harness-Probe", "")
+ if not re.fullmatch(r"[0-9a-f]{64}", nonce):
+ self.reply(400, {"error": "Invalid identity challenge."})
+ return
+ self.reply(200, {"proof": identity_proof(self.server.key, nonce)})
+ return
+ if self.path == "/api/connections":
+ if not self.authenticated():
+ self.reply(403, {"error": "Open harness connections again to continue."})
+ return
+ self.server.last_request = time.monotonic()
+ self.reply(200, {"connections": catalog(self.server.vault)})
+ return
+ files = {"/": ("index.html", "text/html; charset=utf-8"),
+ "/style.css": ("style.css", "text/css; charset=utf-8"),
+ "/page.js": ("page.js", "text/javascript; charset=utf-8")}
+ if self.path not in files:
+ self.reply(404, {"error": "Not found."})
+ return
+ name, kind = files[self.path]
+ self.reply(200, (ASSETS / name).read_bytes(), kind)
+
+ def do_POST(self):
+ if (not self.authenticated() or self.headers.get("Origin") != self.server.origin or
+ self.headers.get("Content-Type") != "application/json" or self.headers.get("Transfer-Encoding")):
+ self.reply(403, {"error": "Open Connections from this computer."})
+ return
+ try:
+ length = int(self.headers.get("Content-Length", "0"))
+ if length <= 0 or length > 16384:
+ self.reply(413, {"error": "Request is too large."})
+ return
+ data = json.loads(self.rfile.read(length))
+ if not isinstance(data, dict):
+ raise ValueError()
+ code = store.validate_code(data.get("connector"))
+ self.server.last_request = time.monotonic()
+ if self.path == "/api/connect":
+ result = connect_token(self.server.vault, code, data.get("token"))
+ elif self.path == "/api/disconnect":
+ self.server.vault.disconnect(code)
+ result = self.server.vault.status(code)
+ else:
+ self.reply(404, {"error": "Not found."})
+ return
+ self.reply(200, result)
+ except (store.StoreError, connector.Failure) as error:
+ self.reply(400, {"error": str(error)})
+ except (ValueError, TypeError):
+ self.reply(400, {"error": "Invalid request."})
+ except (OSError, TimeoutError):
+ self.reply(503, {"error": "Connection unavailable. Try again."})
+
+
+def running_page(vault):
+ data = store.read_private(vault.root / "page.json")
+ if not data or type(data.get("port")) is not int or not 1024 <= data["port"] <= 65535 or not isinstance(data.get("key"), str):
+ return None
+ origin = "http://127.0.0.1:" + str(data["port"])
+ # An unrelated local process can reclaim an expired server's port. Never
+ # disclose the capability while checking whether that server is still ours.
+ nonce = secrets.token_hex(32)
+ req = urllib.request.Request(origin + "/api/identity", headers={"X-Harness-Probe": nonce})
+ try:
+ with urllib.request.build_opener(store.NoRedirect, urllib.request.ProxyHandler({})).open(req, timeout=1) as response:
+ raw = response.read(1025)
+ result = json.loads(raw) if len(raw) <= 1024 else None
+ proof = result.get("proof") if isinstance(result, dict) else None
+ if (response.status == 200 and isinstance(proof, str) and re.fullmatch(r"[0-9a-f]{64}", proof) and
+ hmac.compare_digest(proof, identity_proof(data["key"], nonce))):
+ return origin + "/#" + data["key"]
+ except (OSError, ValueError):
+ pass
+ return None
+
+
+def forget_page(vault, identity):
+ # A newer launcher may already own page.json. Remove only this instance.
+ with store.locked(vault.root):
+ path = vault.root / "page.json"
+ if store.read_private(path) == identity:
+ path.unlink(missing_ok=True)
+
+
+def open_page():
+ browser = shutil.which("hn-browser")
+ if not browser:
+ raise store.StoreError("Open this page on a Harness computer, or run 'connections.py serve' for local review.")
+ vault = store.Store()
+ with store.locked(vault.root):
+ url = running_page(vault)
+ if not url:
+ child = subprocess.Popen([sys.executable, str(Path(__file__).resolve()), "serve", "--background"],
+ stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL,
+ stderr=subprocess.DEVNULL, start_new_session=True)
+ deadline = time.monotonic() + 4
+ while time.monotonic() < deadline and child.poll() is None:
+ url = running_page(vault)
+ if url:
+ break
+ time.sleep(0.1)
+ if not url:
+ raise store.StoreError("Could not open Connections.")
+ subprocess.Popen([browser, url], stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
+ print("Connections opened in the browser.")
+
+
+def main(argv):
+ try:
+ if not argv or argv == ["open"]:
+ open_page()
+ return 0
+ if argv[0] != "serve":
+ return connector.main(argv)
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("serve")
+ parser.add_argument("--port", type=int, default=0)
+ parser.add_argument("--background", action="store_true")
+ args = parser.parse_args(argv)
+ with PageServer(port=args.port) as server:
+ identity = {"port": server.server_address[1], "key": server.key}
+ store.write_private(server.vault.root / "page.json", identity)
+ try:
+ if not args.background:
+ print(server.origin + "/#" + server.key, flush=True)
+ server.serve_until_idle()
+ finally:
+ with contextlib.suppress(store.StoreError, OSError):
+ forget_page(server.vault, identity)
+ return 0
+ except (store.StoreError, OSError) as error:
+ print(str(error) if isinstance(error, store.StoreError) else "Could not open Connections.", file=sys.stderr)
+ return 1
+ except KeyboardInterrupt:
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main(sys.argv[1:]))
diff --git a/os/connectors/connector.py b/os/connectors/connector.py
new file mode 100644
index 000000000..189c77f23
--- /dev/null
+++ b/os/connectors/connector.py
@@ -0,0 +1,408 @@
+#!/usr/bin/env python3
+# Adapted for Harness OS from Autonomous Intern, Apache-2.0.
+# Upstream revision and changes: README.md in this directory.
+"""Call a linked service without putting its credential in shell arguments.
+
+The agent names a connector, a method and a URL; this helper reads the token
+from the device's connector config, attaches it, sends the request, and prints
+the response body. Tokens stay out of routine tool output. This is not a
+security boundary against arbitrary code running as the same Unix user.
+
+Usage:
+ harness connections Open account settings
+ harness connections list [--json]
+ harness connections info <code>
+ harness connections disconnect <code>
+ harness connections call <code> <METHOD> <url> [options]
+
+Options for `call`:
+ --query K=V URL query parameter, URL-encoded for you (repeatable)
+ --json BODY JSON request body; `-` reads it from stdin
+ --data K=V form field, sent application/x-www-form-urlencoded (repeatable)
+ --form K=V multipart field; `K=@/path` uploads a file (repeatable)
+ --header K:V extra request header (repeatable; Authorization is refused)
+ --token-param NAME send the credential as query parameter NAME instead of a
+ header (repeatable; only for endpoints that reject the header)
+
+Exit codes: 0 success (2xx) · 1 HTTP error or network failure · 2 usage error ·
+3 not connected / unusable credential · 4 host not allowed for this connector.
+On any failure nothing is written to stdout, so a following `| jq` sees empty
+input instead of an error body it could mistake for an empty result.
+"""
+import json
+import mimetypes
+import os
+import sys
+import time
+import urllib.error
+import urllib.parse
+import urllib.request
+import uuid
+from pathlib import Path
+import connection_store as store
+
+CONFIGS_DIR = store.directory()
+TIMEOUT_SECONDS = 60
+MAX_RESPONSE_BYTES = 8 * 1024 * 1024
+
+# Official API hosts per connector. A credential is only ever sent to one of
+# these (exact host or a subdomain of it). A connector that is not listed is
+# refused: the helper never sends a credential to a host it cannot vouch for.
+OFFICIAL_HOSTS = {
+ "gmail": ("googleapis.com",),
+ "google_calendar": ("googleapis.com",),
+ "google_drive": ("googleapis.com",),
+ "facebook": ("graph.facebook.com",),
+ "figma": ("api.figma.com",),
+ "figma-api": ("api.figma.com",),
+ "github": ("api.github.com",),
+ "ahrefs": ("api.ahrefs.com",),
+ "notion": ("api.notion.com",),
+ "linear": ("api.linear.app",),
+ "asana": ("app.asana.com",),
+}
+GOOGLE_CODES = ("gmail", "google_calendar", "google_drive")
+
+# Connectors whose API only accepts the credential as a query parameter on
+# some endpoints (Facebook feed-post DELETE, debug_token).
+TOKEN_PARAM_CODES = ("facebook",)
+
+# Files that may be uploaded with `--form K=@path`: media and documents only,
+# never from a directory that holds credentials or device configuration.
+UPLOAD_SUFFIXES = (
+ ".jpg", ".jpeg", ".png", ".gif", ".webp", ".heic",
+ ".mp4", ".mov", ".webm", ".mp3", ".m4a", ".wav", ".ogg",
+ ".pdf", ".txt", ".md", ".csv",
+)
+UPLOAD_FORBIDDEN_DIRS = tuple(str(p.resolve()) for p in (
+ CONFIGS_DIR, Path.home() / ".ssh", Path.home() / ".gnupg",
+ Path.home() / ".config", Path.home() / ".local/share", Path.home() / ".harness",
+ Path.home() / ".codex", Path.home() / ".claude", Path("/etc"), Path("/proc"), Path("/sys"),
+))
+UPLOAD_ALLOWED_DIRS = ()
+
+
+class Failure(Exception):
+ def __init__(self, code, message):
+ super().__init__(message)
+ self.code = code
+
+
+def fmt_time(ts):
+ """Local time plus the zone, so nobody reads a UTC stamp as local."""
+ if not ts:
+ return "never"
+ return time.strftime("%Y-%m-%d %H:%M:%S %Z", time.localtime(int(ts)))
+
+
+def load_json(path):
+ try:
+ with open(path) as f:
+ return json.load(f)
+ except FileNotFoundError:
+ return None
+ except (OSError, ValueError) as e:
+ raise Failure(3, f"cannot read {path.name}: {type(e).__name__}")
+
+
+def load_entry(code):
+ """Return the stored entry for a connector, or None when it is not linked."""
+ return store.Store(CONFIGS_DIR).load(code)
+
+
+def account_of(entry):
+ creds = entry.get("credentials") or {}
+ if entry.get("auth_type") == "pat" and creds.get("email"):
+ return creds["email"]
+ return entry.get("user_email") or creds.get("email") or ""
+
+
+def cmd_list(as_json=False):
+ """Discover the same per-user connections regardless of the current agent."""
+ found = 0
+ problems = []
+ records = []
+ for code in store.SERVICES:
+ try:
+ entry = load_entry(code)
+ if entry:
+ records.append(store.Store(CONFIGS_DIR).status(code))
+ except (Failure, store.StoreError) as e:
+ problems.append(str(e))
+ continue
+ if entry:
+ found += 1
+ if not as_json:
+ print(describe(code, entry))
+ for p in problems:
+ print(f"verification failed: {p}", file=sys.stderr)
+ if problems:
+ return 3
+ if as_json:
+ print(json.dumps(records))
+ elif not found:
+ print("no connectors linked")
+ return 0
+
+
+def describe(code, entry):
+ parts = [account_of(entry), entry.get("auth_type") or "oauth"]
+ state = "expired" if entry.get("expires_at") and entry["expires_at"] <= time.time() else "connected"
+ return f"{code}: {state} (" + ", ".join(p for p in parts if p) + ")"
+
+
+def cmd_info(code):
+ entry = load_entry(code)
+ if not entry:
+ raise Failure(3, f"{code}: not connected")
+ expires = int(entry.get("expires_at") or 0)
+ info = {
+ "connector": code,
+ "auth_type": entry.get("auth_type") or "oauth",
+ "account": account_of(entry),
+ "scopes": entry.get("scopes") or [],
+ "auto_refresh": store.Store(CONFIGS_DIR).status(code)["auto_refresh"],
+ "expires": "not reported" if not expires else fmt_time(expires),
+ "expired": bool(expires) and expires < time.time(),
+ "obtained": fmt_time(entry.get("obtained_at")),
+ }
+ page_id = (entry.get("credentials") or {}).get("page_id")
+ if page_id:
+ info["page_id"] = page_id
+ print(json.dumps(info, indent=2))
+ return 0
+
+
+def host_allowed(code, host):
+ allowed = OFFICIAL_HOSTS.get(code)
+ if not allowed:
+ return False
+ return any(host == h or host.endswith("." + h) for h in allowed)
+
+
+class _NoRedirect(urllib.request.HTTPRedirectHandler):
+ """Never follow a redirect: urllib would re-send the Authorization header
+ (and a credential in the query) to wherever the Location points."""
+
+ def redirect_request(self, req, fp, code, msg, headers, newurl):
+ return None
+
+
+_OPENER = urllib.request.build_opener(_NoRedirect)
+
+
+def upload_path(raw):
+ """Resolve an `@path` upload and refuse anything that is not plain media or
+ a document outside the device's credential and configuration folders."""
+ path = Path(raw).expanduser()
+ try:
+ real = path.resolve(strict=True)
+ except (OSError, RuntimeError):
+ raise Failure(2, f"cannot read upload {raw}")
+ text = str(real)
+ allowed_dir = any(text == d or text.startswith(d + "/") for d in UPLOAD_ALLOWED_DIRS)
+ forbidden_dir = any(text == d or text.startswith(d + "/") for d in UPLOAD_FORBIDDEN_DIRS)
+ if (forbidden_dir and not allowed_dir) or not real.is_file():
+ raise Failure(2, f"refusing to upload {raw}: not a media file the helper may send")
+ if real.suffix.lower() not in UPLOAD_SUFFIXES or path.suffix.lower() not in UPLOAD_SUFFIXES:
+ raise Failure(2, f"refusing to upload {raw}: only {', '.join(UPLOAD_SUFFIXES)} files")
+ return real
+
+
+def pair(value, sep, flag):
+ if sep not in value:
+ raise Failure(2, f"{flag} expects K{sep}V, got {value!r}")
+ k, v = value.split(sep, 1)
+ return k.strip(), v if sep == "=" else v.strip()
+
+
+def multipart(fields):
+ boundary = uuid.uuid4().hex
+ chunks = []
+ for key, value in fields:
+ head = f'--{boundary}\r\nContent-Disposition: form-data; name="{key}"'
+ if value.startswith("@"):
+ path = upload_path(value[1:])
+ try:
+ content = path.read_bytes()
+ except OSError as e:
+ raise Failure(2, f"cannot read upload {path}: {type(e).__name__}")
+ ctype = mimetypes.guess_type(path.name)[0] or "application/octet-stream"
+ head += f'; filename="{path.name}"\r\nContent-Type: {ctype}'
+ else:
+ content = value.encode()
+ chunks += [head.encode() + b"\r\n\r\n", content, b"\r\n"]
+ chunks.append(f"--{boundary}--\r\n".encode())
+ return b"".join(chunks), f"multipart/form-data; boundary={boundary}"
+
+
+def parse_call_args(args):
+ opts = {"query": [], "json": None, "data": [], "form": [], "header": [], "token_param": []}
+ i = 0
+ while i < len(args):
+ flag = args[i]
+ if i + 1 >= len(args):
+ raise Failure(2, f"{flag} needs a value")
+ value = args[i + 1]
+ if flag == "--query":
+ opts["query"].append(pair(value, "=", flag))
+ elif flag == "--data":
+ opts["data"].append(pair(value, "=", flag))
+ elif flag == "--form":
+ opts["form"].append(pair(value, "=", flag))
+ elif flag == "--header":
+ opts["header"].append(pair(value, ":", flag))
+ elif flag == "--json":
+ opts["json"] = sys.stdin.read() if value == "-" else value
+ elif flag == "--token-param":
+ opts["token_param"].append(value)
+ else:
+ raise Failure(2, f"unknown option {flag}")
+ i += 2
+ if sum(bool(x) for x in (opts["json"] is not None, opts["data"], opts["form"])) > 1:
+ raise Failure(2, "use only one of --json, --data, --form")
+ return opts
+
+
+def cmd_call(code, method, url, args, *, entry_override=None):
+ opts = parse_call_args(args)
+ method = method.upper()
+
+ parsed = urllib.parse.urlsplit(url)
+ if parsed.scheme != "https" or not parsed.hostname:
+ raise Failure(4, f"refusing {url!r}: only https:// URLs are allowed")
+ if parsed.username is not None or parsed.password is not None or parsed.port not in (None, 443):
+ raise Failure(4, f"refusing {url!r}: no user info or custom port in the URL")
+ if code not in OFFICIAL_HOSTS:
+ raise Failure(4, f"{code}: the helper has no official API host for this connector — use its MCP tools if it has them")
+ if not host_allowed(code, parsed.hostname):
+ allowed = ", ".join(OFFICIAL_HOSTS[code])
+ raise Failure(4, f"refusing to send the {code} credential to {parsed.hostname}; allowed: {allowed}")
+ if opts["token_param"] and code not in TOKEN_PARAM_CODES:
+ raise Failure(2, f"--token-param is only for {', '.join(TOKEN_PARAM_CODES)}")
+
+ entry = entry_override if entry_override is not None else store.Store(CONFIGS_DIR).ready(code)
+ if code in GOOGLE_CODES and entry.get("auth_type") == "pat":
+ raise Failure(3, f"{code}: linked with an app password; Google REST APIs reject it — use IMAP/SMTP (see SKILL.md)")
+ token = entry.get("access_token") or entry.get("api_key")
+ if not token:
+ raise Failure(3, f"{code}: linked but no usable credential stored")
+
+ query = urllib.parse.parse_qsl(parsed.query, keep_blank_values=True) + opts["query"]
+ for name in opts["token_param"]:
+ query.append((name, token))
+ full_url = urllib.parse.urlunsplit(
+ (parsed.scheme, parsed.netloc, parsed.path, urllib.parse.urlencode(query), "")
+ )
+
+ headers = {"Accept": "application/json", "User-Agent": "Harness-Connections"}
+ if code == "notion":
+ headers["Notion-Version"] = "2022-06-28"
+ for k, v in opts["header"]:
+ if k.lower() in ("authorization", "host", "proxy-authorization", "cookie", "x-figma-token"):
+ raise Failure(2, f"do not pass {k}; the helper sets it (or it is not allowed)")
+ headers[k] = v
+ if not opts["token_param"]:
+ if code in ("figma", "figma-api") and entry.get("auth_type") == "pat":
+ headers["X-Figma-Token"] = token
+ else:
+ headers["Authorization"] = token if code == "linear" and entry.get("auth_type") == "pat" else "Bearer " + token
+
+ body = None
+ if opts["json"] is not None:
+ body = opts["json"].encode()
+ headers.setdefault("Content-Type", "application/json")
+ elif opts["data"]:
+ body = urllib.parse.urlencode(opts["data"]).encode()
+ headers.setdefault("Content-Type", "application/x-www-form-urlencoded")
+ elif opts["form"]:
+ body, headers["Content-Type"] = multipart(opts["form"])
+
+ req = urllib.request.Request(full_url, data=body, method=method, headers=headers)
+ try:
+ with _OPENER.open(req, timeout=TIMEOUT_SECONDS) as resp:
+ out = resp.read(MAX_RESPONSE_BYTES + 1)
+ if len(out) > MAX_RESPONSE_BYTES:
+ raise Failure(1, "Response is too large. Use a smaller page size.")
+ status = resp.status
+ except urllib.error.HTTPError as e:
+ detail = e.read(MAX_RESPONSE_BYTES).decode("utf-8", "replace")
+ print(f"HTTP {e.code} from {parsed.hostname}", file=sys.stderr)
+ if 300 <= e.code < 400:
+ print("redirect not followed: the credential is only sent to the official host", file=sys.stderr)
+ elif detail.strip():
+ print(scrub_entry(detail, entry), file=sys.stderr)
+ if e.code == 401:
+ expires = int(entry.get("expires_at") or 0)
+ print(
+ f"credential: expires {fmt_time(expires) if expires else 'not reported'}; "
+ "reconnect in harness connections",
+ file=sys.stderr,
+ )
+ return 1
+ except (urllib.error.URLError, OSError) as e:
+ reason = getattr(e, "reason", e)
+ print(f"request to {parsed.hostname} failed: {type(reason).__name__}", file=sys.stderr)
+ return 1
+
+ text = out.decode("utf-8", "replace")
+ if text:
+ sys.stdout.write(scrub_entry(text, entry))
+ if not text.endswith("\n"):
+ sys.stdout.write("\n")
+ elif status == 204:
+ print("{}")
+ return 0
+
+
+def scrub_entry(text, entry):
+ for field in ("access_token", "refresh_token", "api_key"):
+ text = scrub(text, entry.get(field))
+ return text
+
+
+def scrub(text, token):
+ if not token:
+ return text
+ for form in {token, urllib.parse.quote(token, safe=""), urllib.parse.quote_plus(token)}:
+ text = text.replace(form, "[credential]")
+ return text
+
+
+def main(argv):
+ try:
+ if argv in (["list"], ["list", "--json"]):
+ return cmd_list("--json" in argv)
+ if len(argv) == 2 and argv[0] == "info":
+ return cmd_info(argv[1])
+ if len(argv) >= 4 and argv[0] == "call":
+ return cmd_call(argv[1], argv[2], argv[3], argv[4:])
+ if len(argv) == 2 and argv[0] == "disconnect":
+ store.Store(CONFIGS_DIR).disconnect(argv[1])
+ print("Disconnected on this computer. Revoke access at the provider to remove it elsewhere.")
+ return 0
+ print(__doc__.split("\n\n", 2)[2], file=sys.stderr)
+ return 2
+ except Failure as e:
+ print(str(e), file=sys.stderr)
+ return e.code
+ except store.StoreError as e:
+ print(str(e), file=sys.stderr)
+ return 3
+ except BrokenPipeError:
+ raise
+ except Exception as e: # never let a traceback echo request details
+ print(f"connector helper failed: {type(e).__name__}", file=sys.stderr)
+ return 1
+
+
+if __name__ == "__main__":
+ try:
+ code = main(sys.argv[1:])
+ sys.stdout.flush()
+ except BrokenPipeError:
+ # The reader (e.g. a failing `| jq`) closed the pipe; its own error is
+ # the one worth showing, not a Python traceback.
+ os.dup2(os.open(os.devnull, os.O_WRONLY), sys.stdout.fileno())
+ code = 1
+ sys.exit(code)
diff --git a/os/connectors/web/index.html b/os/connectors/web/index.html
new file mode 100644
index 000000000..d44a75c00
--- /dev/null
+++ b/os/connectors/web/index.html
@@ -0,0 +1,28 @@
+<!doctype html>
+<html lang="en">
+<meta charset="utf-8">
+<meta name="viewport" content="width=device-width, initial-scale=1">
+<title>Connections · Harness</title>
+<link rel="stylesheet" href="/style.css">
+<script src="/page.js" defer></script>
+<body>
+<main>
+ <header><span class="brand">harness<span> / connections</span></span></header>
+ <h1>Connect once.<br>Work with any agent.</h1>
+ <p class="intro">Your connected accounts, available to agents on this computer.</p>
+ <p id="notice" role="status" aria-live="polite"></p>
+ <div id="connections" aria-label="Connected services"></div>
+ <footer>Connections stay on this computer. You choose what each service can access.</footer>
+</main>
+<dialog id="connect-dialog">
+ <form id="connect-form">
+ <h2 id="service-name">Connect</h2>
+ <p>Use a token from your account. <a id="manage-link" target="_blank" rel="noreferrer">Manage permissions ↗</a></p>
+ <label for="token">Access token</label>
+ <input id="token" type="password" autocomplete="off" spellcheck="false" required maxlength="8192">
+ <p id="connect-error" role="status" aria-live="polite"></p>
+ <div class="actions"><button type="button" id="cancel">Cancel</button><button class="primary" id="save" type="submit">Connect</button></div>
+ </form>
+</dialog>
+</body>
+</html>
diff --git a/os/connectors/web/page.js b/os/connectors/web/page.js
new file mode 100644
index 000000000..975ec45ef
--- /dev/null
+++ b/os/connectors/web/page.js
@@ -0,0 +1,93 @@
+"use strict";
+let key = location.hash.slice(1) || sessionStorage.getItem("harness-connections") || "";
+if (key) sessionStorage.setItem("harness-connections", key);
+history.replaceState(null, "", location.pathname);
+const list = document.querySelector("#connections");
+const notice = document.querySelector("#notice");
+const dialog = document.querySelector("#connect-dialog");
+const form = document.querySelector("#connect-form");
+const input = document.querySelector("#token");
+const save = document.querySelector("#save");
+const error = document.querySelector("#connect-error");
+let selected = null;
+
+async function request(path, body) {
+ const response = await fetch(path, {
+ method: body ? "POST" : "GET",
+ headers: {"X-Harness-Connections": key, ...(body ? {"Content-Type": "application/json"} : {})},
+ ...(body ? {body: JSON.stringify(body)} : {})
+ });
+ const result = await response.json();
+ if (!response.ok) throw new Error(result.error || "Could not update this connection.");
+ return result;
+}
+function node(tag, text, className) {
+ const element = document.createElement(tag);
+ element.textContent = text;
+ if (className) element.className = className;
+ return element;
+}
+function connect(item) {
+ selected = item.connector;
+ document.querySelector("#service-name").textContent = "Connect " + item.name;
+ document.querySelector("#manage-link").href = item.manage_url;
+ error.textContent = "";
+ input.value = "";
+ dialog.showModal();
+ input.focus();
+}
+async function refresh() {
+ const result = await request("/api/connections");
+ list.replaceChildren();
+ for (const item of result.connections) {
+ const row = node("section", "", "service");
+ const info = node("div", "");
+ info.append(node("h2", item.name));
+ const connected = item.state === "connected";
+ const state = connected ? (item.account || "Connected") : ({
+ expired: "Reconnect this account", unreadable: "Connection settings need attention",
+ not_connected: item.manual ? "Not connected" : "Browser sign-in is not available yet"
+ }[item.state]);
+ info.append(node("div", state, "detail" + (connected ? " connected" : "")));
+ if (connected) info.append(node("div",
+ item.scopes.length ? "Permissions: " + item.scopes.join(", ") : "Permissions managed at the provider", "detail"));
+ row.append(info);
+ const actions = node("div", "", "service-actions");
+ if (item.manual && item.state !== "connected") {
+ const button = node("button", item.state === "not_connected" ? "Connect" : "Reconnect");
+ button.addEventListener("click", () => connect(item));
+ actions.append(button);
+ }
+ if (item.state !== "not_connected") {
+ const disconnect = node("button", "Disconnect");
+ disconnect.addEventListener("click", async () => {
+ disconnect.disabled = true;
+ try {
+ await request("/api/disconnect", {connector: item.connector});
+ notice.textContent = item.name + " disconnected here. To revoke the token everywhere, use the service’s settings.";
+ await refresh();
+ } catch (e) {notice.textContent = e.message; disconnect.disabled = false;}
+ });
+ actions.append(disconnect);
+ } else if (!item.manual) actions.append(node("span", "Unavailable", "unavailable"));
+ row.append(actions);
+ list.append(row);
+ }
+}
+document.querySelector("#cancel").addEventListener("click", () => dialog.close());
+dialog.addEventListener("close", () => {input.value = ""; selected = null;});
+form.addEventListener("submit", async (event) => {
+ event.preventDefault();
+ save.disabled = true;
+ save.textContent = "Connecting…";
+ error.textContent = "";
+ try {
+ await request("/api/connect", {connector: selected, token: input.value.trim()});
+ dialog.close();
+ notice.textContent = "Connected. Your agents can use this account now.";
+ await refresh();
+ } catch (e) {error.textContent = e.message;}
+ finally {input.value = ""; save.disabled = false; save.textContent = "Connect";}
+});
+if (!key) notice.textContent = "Open “harness connections” from the terminal to manage your accounts.";
+else refresh().catch(e => {notice.textContent = e.message;});
diff --git a/os/connectors/web/style.css b/os/connectors/web/style.css
new file mode 100644
index 000000000..7628e4b2a
--- /dev/null
+++ b/os/connectors/web/style.css
@@ -0,0 +1,20 @@
+:root{color-scheme:dark;font:16px/1.6 ui-monospace,SFMono-Regular,Consolas,monospace;color:#e7e8de;background:#11140f}
+*{box-sizing:border-box}
+body{margin:0}
+main{max-width:880px;margin:auto;padding:48px 32px}
+a{color:inherit;text-underline-offset:4px}
+.brand{text-decoration:none;font-weight:700}.brand span{color:#a1a593;font-weight:400}
+header{margin-bottom:64px}h1{font-size:clamp(28px,4vw,40px);line-height:1.3;letter-spacing:-.04em;font-weight:400;margin:0 0 20px}
+.intro,footer{color:#a1a593}#notice{min-height:26px;color:#d9f69c;margin:28px 0 12px}
+.service{border-top:1px solid #353c2b;display:grid;grid-template-columns:minmax(0,1fr) auto;align-items:center;gap:20px;padding:20px 0}
+.service h2{font:inherit;margin:0}.detail{font-size:13px;color:#a1a593;overflow-wrap:anywhere}.detail.connected{color:#d9f69c}
+button,input{font:inherit}button{min-height:40px;background:transparent;color:inherit;border:1px solid #59634b;padding:6px 16px;cursor:pointer;white-space:nowrap}
+button:hover{border-color:#d9f69c}button:focus-visible,a:focus-visible,input:focus-visible{outline:2px solid #d9f69c;outline-offset:4px}
+button:disabled{opacity:.5;cursor:wait}.primary{color:#11140f;background:#d9f69c;border-color:#d9f69c}
+.unavailable{color:#818a76;font-size:13px;text-align:right}footer{border-top:1px solid #353c2b;padding-top:24px;margin-top:16px;font-size:13px}
+.service-actions{display:flex;gap:8px;flex-wrap:wrap;justify-content:flex-end}
+dialog{width:min(520px,calc(100% - 32px));border:1px solid #59634b;background:#191e15;color:inherit;padding:32px}
+dialog::backdrop{background:#000b}dialog h2{margin:0;font-size:22px;font-weight:400}dialog p{font-size:14px;color:#a1a593}
+label{display:block;margin:24px 0 8px}input{width:100%;padding:12px;background:#11140f;color:inherit;border:1px solid #59634b}
+.actions{display:flex;justify-content:flex-end;gap:12px;margin-top:24px}#connect-error{color:#f1ac95;min-height:24px}
+@media(max-width:540px){main{padding:28px 20px}header{margin-bottom:40px}.service{gap:12px}.unavailable{max-width:110px}button{padding:6px 10px}}
diff --git a/os/lock.json b/os/lock.json
index 982e84a7d..ff0950265 100644
--- a/os/lock.json
+++ b/os/lock.json
@@ -1,8 +1,12 @@
{
- "version": "0.1.1",
+ "version": "0.1.2-preview.1",
"arch_snapshot": "2026/10/01",
"architecture": "x86_64",
"upgrades_from": [
+ {
+ "version": "0.1.1",
+ "arch_snapshot": "2026/10/01"
+ },
{
"version": "0.1.0-preview.14",
"arch_snapshot": "2026/10/01"
diff --git a/os/packaging/fedora/AGENTS.md b/os/packaging/fedora/AGENTS.md
index 0a5d73747..fa4de9b51 100644
--- a/os/packaging/fedora/AGENTS.md
+++ b/os/packaging/fedora/AGENTS.md
@@ -31,6 +31,10 @@ and running agents. Read `guide.md` and the shipped TUI reference before advisin
## Network, tools and diagnosis
+- `harness connections` manages this computer's service accounts. Read
+ `/usr/share/harness-os/connections.md` before using them. All local agents
+ share the helper; credentials do not synchronize to other computers.
+
- Fedora's NetworkManager owns networking. `hn-os wifi` opens the root-owned
network form through sudo; passwords stay in its masked input. Explicit login
setup grants only that form's two exact commands to the selected user. Do not
diff --git a/os/packaging/fedora/harness-os-session.spec b/os/packaging/fedora/harness-os-session.spec
index 85ac70b14..acb11dfce 100644
--- a/os/packaging/fedora/harness-os-session.spec
+++ b/os/packaging/fedora/harness-os-session.spec
@@ -7,7 +7,7 @@ Name: harness-os-session
Version: %{harness_version}
Release: %{harness_release}
Summary: Harness OS terminal and agent session for Fedora
-License: MIT
+License: MIT AND Apache-2.0
URL: https://github.com/autonomous-ai/openharness
ExclusiveArch: aarch64
Source0: payload.tar.gz
diff --git a/os/projects.py b/os/projects.py
index 77a197264..2c0d789a5 100644
--- a/os/projects.py
+++ b/os/projects.py
@@ -2,10 +2,52 @@
"""Prepare the OS project root and reserve a per-agent folder without collisions."""
import argparse
from datetime import datetime
+import os
from pathlib import Path
import re
+import stat
+import tempfile
import unicodedata
+CONNECTION_HINT = """<!-- harness-os-connections -->
+## Connected accounts on this computer
+
+Read `/usr/share/harness-os/connections.md` when a task involves connected
+services. `harness connections list --json` discovers this user's accounts;
+`harness connections` opens the local settings page. Any agent can use the
+same helper. Keep credentials out of chat, project files and agent settings.
+<!-- /harness-os-connections -->
+"""
+
+
+def connection_instructions(root):
+ # A small pointer stays current with the packaged guide. Keep user-authored
+ # instructions, including symlinked files, untouched except for an append.
+ for name in ("AGENTS.md", "CLAUDE.md"):
+ path = root / name
+ if path.is_symlink():
+ continue
+ try:
+ if path.exists() and (not stat.S_ISREG(path.stat().st_mode) or path.stat().st_size > 1024 * 1024):
+ continue
+ original = path.read_text() if path.exists() else ""
+ if "<!-- harness-os-connections -->" in original:
+ continue
+ mode = stat.S_IMODE(path.stat().st_mode) if path.exists() else 0o644
+ fd, temporary = tempfile.mkstemp(prefix=".harness-instructions-", dir=root)
+ try:
+ with os.fdopen(fd, "w") as handle:
+ handle.write(original.rstrip() + ("\n\n" if original else "") + CONNECTION_HINT)
+ os.chmod(temporary, mode)
+ # Do not replace an edit made while preparing this hint.
+ if not path.is_symlink() and (path.read_text() if path.exists() else "") == original:
+ os.replace(temporary, path)
+ finally:
+ Path(temporary).unlink(missing_ok=True)
+ except (OSError, UnicodeError):
+ # A protected user instruction file must not prevent opening hn.
+ continue
+
def prepare(home=None):
home = Path.home() if home is None else Path(home)
@@ -16,6 +58,7 @@ def prepare(home=None):
legacy.rename(root)
legacy.symlink_to('projects', target_is_directory=True)
root.mkdir(parents=True, exist_ok=True)
+ connection_instructions(root)
return root
diff --git a/os/root/usr/bin/harness b/os/root/usr/bin/harness
index 267ce36e7..a3281d10f 100644
--- a/os/root/usr/bin/harness
+++ b/os/root/usr/bin/harness
@@ -1,4 +1,8 @@
#!/bin/sh
+if [ "${1:-}" = connections ]; then
+ shift
+ exec /usr/bin/python3 /usr/lib/harness-os/connections/connections.py "$@"
+fi
case "${1:-}" in
install|upgrade|rollback)
/usr/bin/hn-os _require-pc-system || exit "$?"
diff --git a/os/root/usr/share/harness-os/AGENTS.md b/os/root/usr/share/harness-os/AGENTS.md
index 1d208f51c..f6fc7993a 100644
--- a/os/root/usr/share/harness-os/AGENTS.md
+++ b/os/root/usr/share/harness-os/AGENTS.md
@@ -10,6 +10,10 @@ is required.
## System operations
+- For connected services, read `/usr/share/harness-os/connections.md`.
+ `harness connections list --json` discovers this user's connected accounts.
+ Use the shared helper from any agent; keep credentials out of conversations.
+
- `Super+u` starts the update inside hn. `harness updates` opens its screen;
click Update to start the same action. No confirmation or password is needed.
The user timer checks hn and CLI releases and prepares verified downloads.
diff --git a/os/root/usr/share/harness-os/connections.md b/os/root/usr/share/harness-os/connections.md
new file mode 100644
index 000000000..6d58cec65
--- /dev/null
+++ b/os/root/usr/share/harness-os/connections.md
@@ -0,0 +1,56 @@
+# Connected accounts
+
+Use `harness connections list --json` to discover accounts on this computer.
+Every agent running as this user reads the same connection store. A connection
+on another computer does not grant access here. Do not copy tokens between
+machines or into agent configuration.
+
+Open `harness connections` when the user needs to connect or disconnect an
+account. Secrets belong in that local form, never in chat, shell arguments or
+project files. Read `harness connections info CODE` for account identity,
+reported permissions and expiry. Unknown permissions are not unlimited access.
+
+Call the connected service with:
+
+```sh
+harness connections call CODE METHOD https://OFFICIAL-API-HOST/PATH
+```
+
+Options: `--query KEY=VALUE`, `--header NAME:VALUE`, `--json BODY` (or
+`--json -` for stdin), `--data KEY=VALUE`, `--form KEY=VALUE`. Form uploads
+use `KEY=@/path/to/file`. Name the connection; do not read its credential file
+or construct authorization headers yourself. Normal agent approval rules apply.
+Connecting an account is not approval to send messages, publish, delete or
+change permissions. Ask when the requested action lacks authorization.
+
+Read the service's current API reference when an endpoint or schema is unknown.
+Check the command exit code, response body and a read-back before reporting a
+write as successful. GraphQL can return errors with HTTP 200. A 401 means
+reconnect; a 403 can mean insufficient permissions or inaccessible content;
+rate limits and unavailable services are not empty results. Do not automatically
+repeat a write after a timeout: check whether it succeeded first.
+
+## Service entry points
+
+| Connection | Read-only starting request | Notes |
+| --- | --- | --- |
+| github | `GET https://api.github.com/user` | Repositories: `GET /user/repos`; repository/organization access depends on the token. |
+| notion | `GET https://api.notion.com/v1/users/me` | Search: `POST /v1/search` with `--json '{"page_size":10}'`. The helper defaults to Notion-Version 2022-06-28; set a version header explicitly when using a newer schema. |
+| linear | `POST https://api.linear.app/graphql` with `--json '{"query":"{ viewer { id name } }"}'` | Read the `errors` array, not only the exit status. Personal keys and OAuth use different auth headers; the helper selects them. |
+| asana | `GET https://app.asana.com/api/1.0/users/me` | Discover workspaces before projects/tasks. |
+| figma | `GET https://api.figma.com/v1/me` | Requires current_user:read for the connection check. File access depends on the token's scopes. |
+| gmail | `GET https://gmail.googleapis.com/gmail/v1/users/me/profile` | OAuth sign-in is not enabled in this build. Google app passwords do not work with this REST helper. |
+| google_calendar | `GET https://www.googleapis.com/calendar/v3/users/me/calendarList` | Separate connection and permissions from Gmail. OAuth sign-in pending. |
+| google_drive | `GET https://www.googleapis.com/drive/v3/files` with `--query pageSize=10` | Separate connection and permissions. OAuth sign-in pending. |
+| facebook | `GET https://graph.facebook.com/me` | Connection setup pending. Page actions need the correct page token and permissions. |
+| ahrefs | `GET https://api.ahrefs.com/v3/subscription-info/limits-and-usage` | Connection setup pending; API access depends on the service plan. |
+
+Manual tokens can be connected for GitHub, Notion, Linear, Asana and Figma.
+Browser sign-in and automatic renewal are not enabled in this build; expired
+accounts must be reconnected. No Intern device, device key or hardware
+registration is required. These tools are shared by agents running as the same
+local user on an ordinary computer with Harness installed.
+
+`harness connections disconnect CODE` removes local access for future requests.
+An in-flight request cannot be recalled. This does not revoke the token at its
+provider or remove it on other computers. Use the provider's settings for that.
diff --git a/os/root/usr/share/harness-os/guide.md b/os/root/usr/share/harness-os/guide.md
index b20f6693c..e4ed283c5 100644
--- a/os/root/usr/share/harness-os/guide.md
+++ b/os/root/usr/share/harness-os/guide.md
@@ -82,6 +82,12 @@ new line in compatible agent prompts. Do not intercept agent shortcuts needlessl
## Multiple computers
+For service accounts (Gmail, GitHub, Notion and other services), use
+`harness connections` and read `/usr/share/harness-os/connections.md`.
+These are separate from connecting computers. All agents running as the same
+user on this computer can use its connected accounts without signing in again.
+Account credentials are not synchronized to other computers.
+
The **Connect a computer** action opens Harness's existing connection flow.
This computer works without a Harness account. Connecting other computers uses
the existing sign-in/link flow. If signed out, choose **Sign in on this computer**,
diff --git a/os/tests/connections_vm.py b/os/tests/connections_vm.py
new file mode 100644
index 000000000..1c1c8a0f8
--- /dev/null
+++ b/os/tests/connections_vm.py
@@ -0,0 +1,74 @@
+"""Exercise the installed Connections command and browser inside a disposable VM."""
+import base64
+import shlex
+
+from install_first import wait_installer_screen
+
+
+def exercise(vm):
+ # Fixture credentials stay inside the disposable guest and never reach a provider.
+ script = r'''
+import json, os, pathlib, subprocess, sys, tempfile, time, urllib.error, urllib.request
+assert sys.platform == 'linux' and os.geteuid() != 0
+assert subprocess.check_output(['lsblk', '-dn', '-o', 'SERIAL', '/dev/vda'], text=True).strip() == 'HN_OS_TEST'
+sys.path.insert(0, '/usr/lib/harness-os/connections')
+import connection_store
+with tempfile.TemporaryDirectory(prefix='connections-native-') as temporary:
+ root = pathlib.Path(temporary) / 'accounts'
+ env = dict(os.environ, CONNECTOR_CONFIGS_DIR=str(root))
+ def cli(*args):
+ return subprocess.check_output(['harness', 'connections', *args], env=env, text=True, timeout=10)
+ assert json.loads(cli('list', '--json')) == []
+ vault = connection_store.Store(root)
+ vault.save('github', {'auth_type': 'pat', 'api_key': 'native-fixture-not-a-real-token', 'user_email': '[email protected]'})
+ for _ in range(3):
+ # Separate command processes use the same credentials, independent of an engine.
+ info = json.loads(cli('info', 'github'))
+ assert info['account'] == '[email protected]', info
+ assert 'native-fixture-not-a-real-token' not in json.dumps(info)
+ assert not (root / 'backend.json').exists()
+ process = subprocess.Popen(['harness', 'connections', 'serve', '--background'], env=env,
+ stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
+ try:
+ deadline = time.monotonic() + 5
+ while not (root / 'page.json').exists() and time.monotonic() < deadline:
+ assert process.poll() is None
+ time.sleep(.05)
+ page = connection_store.read_private(root / 'page.json')
+ origin = 'http://127.0.0.1:' + str(page['port'])
+ opener = urllib.request.build_opener(urllib.request.ProxyHandler({}))
+ try:
+ opener.open(origin + '/api/connections', timeout=3)
+ raise AssertionError('Unauthenticated request was accepted')
+ except urllib.error.HTTPError as error:
+ assert error.code == 403
+ error.close()
+ request = urllib.request.Request(origin + '/api/disconnect',
+ data=b'{"connector":"github"}', headers={'X-Harness-Connections': page['key'],
+ 'Origin': origin, 'Content-Type': 'application/json'})
+ with opener.open(request, timeout=3) as response:
+ assert json.load(response)['state'] == 'not_connected'
+ assert json.loads(cli('list', '--json')) == []
+ finally:
+ process.terminate()
+ process.wait(timeout=5)
+print('Installed Connections CLI, shared local credentials and authenticated disconnect passed')
+'''
+ encoded = base64.b64encode(script.encode()).decode()
+ vm.command('printf %s ' + shlex.quote(encoded) + ' | base64 -d | python3', timeout=30)
+ vm.command('harness connections', timeout=15)
+ try:
+ wait_installer_screen(vm, r'Connect once', 'connections-page', timeout=30)
+ vm.keys('tab')
+ vm.keys('ret')
+ wait_installer_screen(vm, r'Access token', 'connections-token-form', timeout=15)
+ vm.keys('esc')
+ finally:
+ vm.keys('alt', 'f4')
+ # The helper is on demand, but waits 15 minutes for inactivity. Stop
+ # this fixture's helper before the image test records idle RAM.
+ pattern = r'^/usr/bin/python3 /usr/lib/harness-os/connections/connections[.]py serve --background$'
+ vm.command('pkill -INT -u "$(id -u)" -f ' + shlex.quote(pattern) + '; '
+ 'for n in $(seq 1 30); do ! pgrep -u "$(id -u)" -f ' + shlex.quote(pattern) +
+ ' >/dev/null && exit 0; sleep .1; done; exit 1', timeout=10)
+ return {'status': 'passed', 'scope': 'Installed CLI, shared fixture credentials, local API boundary, browser and keyboard token form; no provider authentication'}
diff --git a/os/tests/test_connections.py b/os/tests/test_connections.py
new file mode 100644
index 000000000..fcee83e27
--- /dev/null
+++ b/os/tests/test_connections.py
@@ -0,0 +1,244 @@
+"""Connections lifecycle and loopback boundary checks; no provider accounts."""
+import contextlib
+import http.client
+import io
+import json
+import os
+from pathlib import Path
+import stat
+import subprocess
+import sys
+import tempfile
+import threading
+import time
+import unittest
+from unittest.mock import patch
+
+SOURCE = Path(__file__).resolve().parents[1] / "connectors"
+sys.path.insert(0, str(SOURCE))
+import connection_store as store
+import connections
+import connector
+
+TOKEN = "fixture-access-token-not-real"
+
+
+class Response:
+ status = 200
+
+ def __init__(self, body):
+ self.body = json.dumps(body).encode()
+
+ def read(self, limit=-1):
+ return self.body[:limit]
+
+ def __enter__(self):
+ return self
+
+ def __exit__(self, *args):
+ return False
+
+
+class Credentials(unittest.TestCase):
+ def setUp(self):
+ folder = tempfile.TemporaryDirectory()
+ self.addCleanup(folder.cleanup)
+ self.root = Path(folder.name) / "connections"
+ self.vault = store.Store(self.root)
+ self.entry = {"auth_type": "oauth", "access_token": TOKEN, "refresh_token": "fixture-refresh",
+ "refresh": True, "expires_at": int(time.time()) + 3600, "scopes": ["read"]}
+
+ def test_private_atomic_storage_shared_across_agent_processes_and_disconnect(self):
+ self.vault.save("github", self.entry)
+ self.assertEqual(stat.S_IMODE(self.root.stat().st_mode), 0o700)
+ self.assertEqual(stat.S_IMODE(self.vault.path("github").stat().st_mode), 0o600)
+ for engine in ("codex", "claude", "opencode"):
+ result = subprocess.run([sys.executable, str(SOURCE / "connections.py"), "list", "--json"],
+ env={**os.environ, "CONNECTOR_CONFIGS_DIR": str(self.root), "HARNESS_ENGINE": engine},
+ capture_output=True, text=True, timeout=10)
+ self.assertEqual(result.returncode, 0, result.stderr)
+ self.assertEqual(json.loads(result.stdout)[0]["connector"], "github")
+ self.assertNotIn(TOKEN, result.stdout + result.stderr)
+ self.vault.disconnect("github")
+ with self.assertRaisesRegex(store.StoreError, "Not connected"):
+ store.Store(self.root).ready("github")
+ self.assertFalse(list(self.root.glob(".incoming-*")))
+
+ def test_symlinks_broad_permissions_and_path_traversal_cannot_read_credentials(self):
+ self.vault.save("github", self.entry)
+ path = self.vault.path("github")
+ path.chmod(0o644)
+ with self.assertRaises(store.StoreError):
+ self.vault.load("github")
+ path.chmod(0o600)
+ alias = self.root / "notion_access_tokens.json"
+ alias.symlink_to(path)
+ with self.assertRaises(store.StoreError):
+ self.vault.load("notion")
+ for code in ("../github", "/etc/passwd", "new"):
+ with self.assertRaises(store.StoreError):
+ self.vault.path(code)
+ symlink = self.root.parent / "alias"
+ symlink.symlink_to(self.root)
+ with self.assertRaises(store.StoreError):
+ store.Store(symlink).save("github", self.entry)
+
+ def test_expired_tokens_stop_without_contacting_a_device_backend(self):
+ self.vault.save("github", dict(self.entry, expires_at=1))
+ # A leftover development config must not turn on Intern device renewal.
+ store.write_private(self.root / "backend.json", {
+ "base_url": "https://backend.invalid/api/v1/ai/v1",
+ "api_key": "fixture-device", "device_id": "fixture-device-id",
+ })
+ old = self.vault.path("github").read_bytes()
+ self.assertEqual(self.vault.status("github")["state"], "expired")
+ self.assertFalse(self.vault.status("github")["auto_refresh"])
+ with patch("urllib.request.OpenerDirector.open") as request:
+ with self.assertRaisesRegex(store.StoreError, "expired"):
+ self.vault.ready("github")
+ request.assert_not_called()
+ self.assertEqual(self.vault.path("github").read_bytes(), old)
+
+ def test_valid_tokens_need_no_backend_or_device_registration(self):
+ self.vault.save("github", self.entry)
+ self.assertFalse((self.root / "backend.json").exists())
+ self.assertEqual(self.vault.ready("github")["access_token"], TOKEN)
+ # Even an unreadable old backend config cannot affect local connections.
+ (self.root / "backend.json").symlink_to(self.root / "missing-config")
+ self.assertEqual(self.vault.status("github")["state"], "connected")
+ self.assertFalse(self.vault.status("github")["auto_refresh"])
+ self.assertEqual(self.vault.ready("github")["access_token"], TOKEN)
+
+ def test_provider_headers_and_failed_identity_do_not_save_token(self):
+ cases = [
+ ("github", {"id": 42, "login": "fixture"}, "Authorization", "Bearer " + TOKEN),
+ ("notion", {"id": "bot"}, "Authorization", "Bearer " + TOKEN),
+ ("linear", {"data": {"viewer": {"id": "user", "email": "[email protected]"}}}, "Authorization", TOKEN),
+ ("asana", {"data": {"gid": "user", "name": "Fixture"}}, "Authorization", "Bearer " + TOKEN),
+ ("figma", {"id": "user", "email": "[email protected]"}, "X-figma-token", TOKEN),
+ ]
+ for code, body, header, value in cases:
+ seen = []
+ def respond(req, timeout):
+ seen.append(req)
+ return Response(body)
+ with patch.object(connector._OPENER, "open", side_effect=respond):
+ connections.connect_token(self.vault, code, TOKEN)
+ self.assertEqual(seen[0].get_header(header), value)
+ self.assertIsNone(seen[0].get_header("X-device-id"))
+ self.assertEqual(self.vault.status(code)["state"], "connected")
+ self.vault.disconnect("linear")
+ with patch.object(connector._OPENER, "open", return_value=Response({"errors": [{"message": "bad key"}]})):
+ with self.assertRaises(store.StoreError):
+ connections.connect_token(self.vault, "linear", TOKEN)
+ self.assertIsNone(self.vault.load("linear"))
+
+ def test_cli_rejects_oversized_response_and_redacts_both_credentials(self):
+ self.vault.save("github", self.entry)
+ for body, expected in [("x" * 128, 1), (TOKEN + " fixture-refresh", 0)]:
+ output, error = io.StringIO(), io.StringIO()
+ with patch.object(connector, "CONFIGS_DIR", self.root), patch.object(connector, "MAX_RESPONSE_BYTES", 100), \
+ patch.object(connector._OPENER, "open", return_value=Response(body)), \
+ contextlib.redirect_stdout(output), contextlib.redirect_stderr(error):
+ status = connector.main(["call", "github", "GET", "https://api.github.com/user"])
+ self.assertEqual(status, expected)
+ self.assertNotIn(TOKEN, output.getvalue() + error.getvalue())
+ self.assertNotIn("fixture-refresh", output.getvalue() + error.getvalue())
+
+
+class BrowserBoundary(unittest.TestCase):
+ def setUp(self):
+ folder = tempfile.TemporaryDirectory()
+ self.addCleanup(folder.cleanup)
+ self.vault = store.Store(Path(folder.name) / "connections")
+ self.server = connections.PageServer(self.vault)
+ self.thread = threading.Thread(target=self.server.serve_forever, kwargs={"poll_interval": .02}, daemon=True)
+ self.thread.start()
+ self.addCleanup(self.close)
+
+ def close(self):
+ self.server.shutdown()
+ self.thread.join(timeout=2)
+ self.server.server_close()
+
+ def request(self, path, method="GET", body=None, headers=None):
+ client = http.client.HTTPConnection(*self.server.server_address, timeout=3)
+ try:
+ client.request(method, path, body=json.dumps(body) if body is not None else None, headers=headers or {})
+ response = client.getresponse()
+ return response.status, dict(response.getheaders()), response.read()
+ finally:
+ client.close()
+
+ def auth(self):
+ return {"X-Harness-Connections": self.server.key, "Origin": self.server.origin, "Content-Type": "application/json"}
+
+ def test_no_cross_site_or_unauthenticated_access_even_on_loopback(self):
+ for headers in ({}, {**self.auth(), "Host": "evil.invalid"}, {**self.auth(), "Sec-Fetch-Site": "cross-site"}):
+ self.assertEqual(self.request("/api/connections", headers=headers)[0], 403)
+ headers = {**self.auth(), "Origin": "https://evil.invalid"}
+ self.assertEqual(self.request("/api/disconnect", "POST", {"connector": "github"}, headers)[0], 403)
+ self.assertEqual(self.request("/api/disconnect?connector=github", headers=self.auth())[0], 404)
+ self.assertEqual(self.request("/../connection_store.py")[0], 404)
+
+ def test_reuse_requires_server_proof_without_sending_the_capability(self):
+ identity = {"port": self.server.server_port, "key": self.server.key}
+ store.write_private(self.vault.root / "page.json", identity)
+ self.assertEqual(connections.running_page(self.vault), self.server.origin + "/#" + self.server.key)
+ # An impostor on this port knows the request but not the saved secret.
+ identity["key"] = "fixture-secret-not-known-to-this-server"
+ store.write_private(self.vault.root / "page.json", identity)
+ self.assertIsNone(connections.running_page(self.vault))
+ with patch("urllib.request.OpenerDirector.open", return_value=Response({"connections": []})) as request:
+ self.assertIsNone(connections.running_page(self.vault))
+ probe = request.call_args.args[0]
+ self.assertIsNone(probe.get_header("X-harness-connections"))
+ self.assertNotIn(identity["key"], probe.full_url + repr(probe.headers))
+ with patch("urllib.request.OpenerDirector.open", return_value=Response({"proof": connections.identity_proof(identity["key"], "0" * 64)})):
+ self.assertIsNone(connections.running_page(self.vault), "An old proof cannot answer a new challenge")
+
+ def test_identity_probe_cannot_keep_an_unused_page_alive(self):
+ before = self.server.last_request
+ self.assertEqual(self.request("/api/identity", headers={"X-Harness-Probe": "0" * 64})[0], 200)
+ self.assertEqual(self.server.last_request, before)
+ self.assertEqual(self.request("/api/identity", headers={"X-Harness-Probe": "bad"})[0], 400)
+
+ def test_page_cleanup_preserves_a_newer_server(self):
+ identity = {"port": self.server.server_port, "key": self.server.key}
+ path = self.vault.root / "page.json"
+ store.write_private(path, identity)
+ connections.forget_page(self.vault, dict(identity, key="older-server"))
+ self.assertEqual(store.read_private(path), identity)
+ connections.forget_page(self.vault, identity)
+ self.assertFalse(path.exists())
+
+ def test_real_http_connect_list_disconnect_without_token_response_or_static_leak(self):
+ with patch.object(connector._OPENER, "open", return_value=Response({"id": 1, "login": "fixture"})):
+ status, _, raw = self.request("/api/connect", "POST", {"connector": "github", "token": TOKEN}, self.auth())
+ self.assertEqual(status, 200, raw)
+ self.assertNotIn(TOKEN.encode(), raw)
+ status, headers, raw = self.request("/api/connections", headers=self.auth())
+ self.assertEqual(status, 200)
+ self.assertEqual(headers["Cache-Control"], "no-store")
+ self.assertNotIn(TOKEN.encode(), raw)
+ status, headers, _ = self.request("/")
+ self.assertEqual(status, 200)
+ self.assertIn("frame-ancestors 'none'", headers["Content-Security-Policy"])
+ status, _, raw = self.request("/api/disconnect", "POST", {"connector": "github"}, self.auth())
+ self.assertEqual(status, 200)
+ self.assertEqual(json.loads(raw)["state"], "not_connected")
+ self.assertIsNone(self.vault.load("github"))
+
+ def test_bad_request_and_unverified_services_do_not_create_accounts(self):
+ for body in ({"connector": "../outside", "token": TOKEN}, {"connector": "gmail", "token": TOKEN},
+ {"connector": "github", "token": ["bad"]}):
+ status, _, raw = self.request("/api/connect", "POST", body, self.auth())
+ self.assertEqual(status, 400, raw)
+ self.assertFalse(self.root_exists())
+
+ def root_exists(self):
+ return self.vault.root.exists()
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/os/tests/test_connector_upstream.py b/os/tests/test_connector_upstream.py
new file mode 100644
index 000000000..916d400f5
--- /dev/null
+++ b/os/tests/test_connector_upstream.py
@@ -0,0 +1,227 @@
+"""Intern behavior tests, adapted for Harness private storage; no network.
+
+Apache-2.0. Provenance: ../connectors/README.md.
+"""
+import contextlib
+import importlib.util
+import io
+import json
+import os
+import sys
+from pathlib import Path
+import tempfile
+import time
+import unittest
+import urllib.error
+from unittest.mock import patch
+
+SCRIPT = Path(__file__).parents[1] / 'connectors/connector.py'
+sys.path.insert(0, str(SCRIPT.parent))
+TOKEN = 'tok-' + 'x' * 40
+
+
+def load_module(configs_dir):
+ with patch.dict(os.environ, {'CONNECTOR_CONFIGS_DIR': str(configs_dir)}):
+ spec = importlib.util.spec_from_file_location('connector_skill', SCRIPT)
+ module = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(module)
+ return module
+
+
+class FakeResponse:
+ def __init__(self, body, status=200):
+ self.body = body.encode()
+ self.status = status
+
+ def read(self, _limit=None):
+ return self.body
+
+ def __enter__(self):
+ return self
+
+ def __exit__(self, *exc):
+ return False
+
+
+class ConnectorHelperTests(unittest.TestCase):
+ def setUp(self):
+ self.temp = tempfile.TemporaryDirectory()
+ self.addCleanup(self.temp.cleanup)
+ self.dir = Path(self.temp.name)
+ self.write('google_calendar', {
+ 'auth_type': 'oauth', 'access_token': TOKEN, 'refresh_token': 'r', 'refresh': True,
+ 'expires_at': int(time.time()) + 3600, 'user_email': '[email protected]',
+ 'scopes': ['https://www.googleapis.com/auth/calendar.events'],
+ })
+ self.mod = load_module(self.dir)
+
+ def write(self, code, entry):
+ path = self.dir / f'{code}_access_tokens.json'
+ path.write_text(json.dumps({'connectors': {code: entry}}))
+ path.chmod(0o600)
+
+ def run_main(self, *argv):
+ out, err = io.StringIO(), io.StringIO()
+ with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err):
+ code = self.mod.main(list(argv))
+ return code, out.getvalue(), err.getvalue()
+
+ def test_list_names_connector_without_secret(self):
+ code, out, _ = self.run_main('list')
+ self.assertEqual(code, 0)
+ self.assertIn('google_calendar: connected ([email protected], oauth)', out)
+ self.assertNotIn(TOKEN, out)
+
+ def test_list_reports_unreadable_file_as_verification_failure(self):
+ (self.dir / 'google_calendar_access_tokens.json').write_text('{not json')
+ code, _, err = self.run_main('list')
+ self.assertEqual(code, 3)
+ self.assertIn('verification failed', err)
+
+ def test_info_has_no_secret(self):
+ code, out, _ = self.run_main('info', 'google_calendar')
+ self.assertEqual(code, 0)
+ info = json.loads(out)
+ self.assertFalse(info['auto_refresh'], 'Refresh metadata alone does not enable automatic renewal')
+ self.assertFalse(info['expired'])
+ self.assertNotIn(TOKEN, out)
+
+ def test_call_sends_header_and_encodes_query(self):
+ seen = {}
+
+ def fake_urlopen(req, timeout):
+ seen['url'] = req.full_url
+ seen['auth'] = req.get_header('Authorization')
+ return FakeResponse('{"items": []}')
+
+ with patch.object(self.mod._OPENER, 'open', fake_urlopen):
+ code, out, _ = self.run_main(
+ 'call', 'google_calendar', 'GET',
+ 'https://www.googleapis.com/calendar/v3/calendars/primary/events',
+ '--query', 'timeMin=2026-07-13T00:00:00+07:00')
+ self.assertEqual(code, 0)
+ self.assertEqual(seen['auth'], 'Bearer ' + TOKEN)
+ self.assertIn('timeMin=2026-07-13T00%3A00%3A00%2B07%3A00', seen['url'])
+ self.assertEqual(json.loads(out), {'items': []})
+
+ def test_http_error_goes_to_stderr_only(self):
+ def fake_urlopen(req, timeout):
+ raise urllib.error.HTTPError(req.full_url, 401, 'Unauthorized', {}, io.BytesIO(b'{"error":{"code":401}}'))
+
+ with patch.object(self.mod._OPENER, 'open', fake_urlopen):
+ code, out, err = self.run_main('call', 'google_calendar', 'GET', 'https://www.googleapis.com/x')
+ self.assertEqual(code, 1)
+ self.assertEqual(out, '')
+ self.assertIn('HTTP 401 from www.googleapis.com', err)
+ self.assertIn('reconnect in harness connections', err)
+
+ def test_refuses_foreign_host_for_known_connector(self):
+ with patch.object(self.mod._OPENER, 'open') as urlopen:
+ code, _, err = self.run_main('call', 'google_calendar', 'GET', 'https://evil.example.com/collect')
+ self.assertEqual(code, 4)
+ self.assertIn('refusing', err)
+ urlopen.assert_not_called()
+
+ def test_refuses_lookalike_host(self):
+ code, _, _ = self.run_main('call', 'google_calendar', 'GET', 'https://googleapis.com.evil.example/x')
+ self.assertEqual(code, 4)
+
+ def test_refuses_plain_http(self):
+ code, _, _ = self.run_main('call', 'google_calendar', 'GET', 'http://www.googleapis.com/x')
+ self.assertEqual(code, 4)
+
+ def test_refuses_caller_authorization_header(self):
+ code, _, err = self.run_main('call', 'google_calendar', 'GET', 'https://www.googleapis.com/x',
+ '--header', 'Authorization: Basic abc')
+ self.assertEqual(code, 2)
+ self.assertIn('Authorization', err)
+
+ def test_google_app_password_is_refused(self):
+ self.write('gmail', {'auth_type': 'pat', 'api_key': 'app-pass', 'credentials': {'email': '[email protected]'}})
+ code, _, err = self.run_main('call', 'gmail', 'GET', 'https://gmail.googleapis.com/gmail/v1/users/me/messages')
+ self.assertEqual(code, 3)
+ self.assertIn('IMAP', err)
+
+ def test_not_connected(self):
+ code, _, err = self.run_main('call', 'google_drive', 'GET', 'https://www.googleapis.com/drive/v3/files')
+ self.assertEqual(code, 3)
+ self.assertIn('not connected', err.lower())
+
+ def test_token_param_uses_query_not_header(self):
+ self.write('facebook', {'api_key': TOKEN, 'credentials': {'page_id': '123'}})
+ seen = {}
+
+ def fake_urlopen(req, timeout):
+ seen['url'] = req.full_url
+ seen['auth'] = req.get_header('Authorization')
+ return FakeResponse('{"success": true}')
+
+ with patch.object(self.mod._OPENER, 'open', fake_urlopen):
+ code, out, _ = self.run_main('call', 'facebook', 'DELETE', 'https://graph.facebook.com/v19.0/1_2',
+ '--token-param', 'access_token')
+ self.assertEqual(code, 0)
+ self.assertIsNone(seen['auth'])
+ self.assertIn('access_token=' + TOKEN, seen['url'])
+ self.assertNotIn(TOKEN, out)
+
+ def test_response_echoing_token_is_scrubbed(self):
+ with patch.object(self.mod._OPENER, 'open', lambda req, timeout: FakeResponse(TOKEN)):
+ code, out, _ = self.run_main('call', 'google_calendar', 'GET', 'https://www.googleapis.com/x')
+ self.assertEqual(code, 0)
+ self.assertNotIn(TOKEN, out)
+
+ def test_unlisted_connector_is_refused(self):
+ self.write('mystery', {'access_token': TOKEN})
+ with patch.object(self.mod._OPENER, 'open') as opener:
+ code, _, err = self.run_main('call', 'mystery', 'GET', 'https://attacker.example/collect')
+ self.assertEqual(code, 4)
+ self.assertIn('no official API host', err)
+ opener.assert_not_called()
+
+ def test_userinfo_and_custom_port_are_refused(self):
+ for url in ('https://[email protected]/x', 'https://www.googleapis.com:8443/x'):
+ code, _, _ = self.run_main('call', 'google_calendar', 'GET', url)
+ self.assertEqual(code, 4, url)
+
+ def test_token_param_only_for_facebook(self):
+ code, _, err = self.run_main('call', 'google_calendar', 'GET', 'https://www.googleapis.com/x',
+ '--token-param', 'access_token')
+ self.assertEqual(code, 2)
+ self.assertIn('--token-param', err)
+
+ def test_redirect_is_not_followed(self):
+ handler = self.mod._NoRedirect()
+ req = self.mod.urllib.request.Request('https://www.googleapis.com/x', headers={'Authorization': 'Bearer ' + TOKEN})
+ self.assertIsNone(handler.redirect_request(req, None, 302, 'Found', {}, 'https://attacker.example/'))
+
+ def test_upload_refuses_credentials_and_non_media(self):
+ token_file = self.dir / 'google_calendar_access_tokens.json'
+ alias = self.dir / 'innocent.jpg'
+ alias.symlink_to(token_file)
+ for raw in (str(token_file), str(alias), '/root/config/config.json'):
+ with self.assertRaises(self.mod.Failure, msg=raw):
+ self.mod.upload_path(raw)
+ image = self.dir.parent / (self.dir.name + '-pic.png')
+ self.addCleanup(image.unlink, missing_ok=True)
+ image.write_bytes(b'png')
+ self.assertEqual(self.mod.upload_path(str(image)), image.resolve())
+
+ def test_scrub_covers_url_encoded_token(self):
+ token = 'a/b+c=='
+ text = 'x ' + token + ' y a%2Fb%2Bc%3D%3D z'
+ self.assertNotIn('a%2Fb', self.mod.scrub(text, token))
+ self.assertNotIn(token, self.mod.scrub(text, token))
+
+ def test_multipart_upload(self):
+ image = self.dir.parent / (self.dir.name + '-pic.jpg')
+ self.addCleanup(image.unlink, missing_ok=True)
+ image.write_bytes(b'\xff\xd8data')
+ body, ctype = self.mod.multipart([('source', '@' + str(image)), ('message', 'hi')])
+ self.assertTrue(ctype.startswith('multipart/form-data; boundary='))
+ self.assertIn(('filename="' + image.name + '"').encode(), body)
+ self.assertIn(b'\xff\xd8data', body)
+ self.assertIn(b'name="message"\r\n\r\nhi', body)
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/os/tests/test_fedora_package.py b/os/tests/test_fedora_package.py
index 0ae36437f..ffd3de105 100644
--- a/os/tests/test_fedora_package.py
+++ b/os/tests/test_fedora_package.py
@@ -67,6 +67,8 @@ class FedoraPayload(unittest.TestCase):
self.assertNotIn('usr/lib/harness-os/' + name, result['files'])
self.assertNotIn('usr/share/harness-os/lock.json', result['files'])
self.assertIn('usr/lib/harness-os/live_update.py', result['files'])
+ self.assertIn('usr/lib/harness-os/connections/connections.py', result['files'])
+ self.assertIn('usr/share/harness-os/connections.md', result['files'])
self.assertIn('usr/lib/harness-os/screen-action', result['files'])
self.assertEqual((destination / 'usr/lib/harness-os/screen-action').stat().st_mode & 0o777, 0o755)
self.assertIn('usr/lib/systemd/user/harness-update.timer', result['files'])
diff --git a/os/tests/test_package.py b/os/tests/test_package.py
index d20270250..352802e58 100644
--- a/os/tests/test_package.py
+++ b/os/tests/test_package.py
@@ -24,6 +24,11 @@ class PackageIdentity(unittest.TestCase):
with patch.object(package, 'validate_runtime', return_value={'source_commit': 'a' * 40}):
identity = package.stage(Path(__file__).resolve().parents[2], runtime, destination, 'a' * 40)
config = destination / 'etc/skel/.config/opencode'
+ self.assertTrue((destination / 'usr/lib/harness-os/connections/connections.py').is_file())
+ self.assertTrue((destination / 'usr/lib/harness-os/connections/web/index.html').is_file())
+ self.assertTrue((destination / 'usr/share/licenses/harness-os-connections/LICENSE').is_file())
+ self.assertIn('harness connections', (destination / 'usr/share/harness-os/connections.md').read_text())
+ self.assertIn('/usr/lib/harness-os/connections/connections.py', (destination / 'usr/bin/harness').read_text())
self.assertFalse((config / 'AGENTS.md').is_symlink())
self.assertIn('/usr/share/harness-os/guide.md', (config / 'AGENTS.md').read_text())
self.assertIn('Super+n', (destination / 'usr/share/harness-os/guide.md').read_text())
diff --git a/os/tests/test_projects.py b/os/tests/test_projects.py
index f5783ba1b..2773202a5 100644
--- a/os/tests/test_projects.py
+++ b/os/tests/test_projects.py
@@ -10,6 +10,22 @@ spec.loader.exec_module(projects)
class Projects(unittest.TestCase):
+ def test_existing_users_get_shared_account_discovery_without_replacing_instructions(self):
+ with tempfile.TemporaryDirectory() as temp:
+ home = Path(temp)
+ root = home / 'projects'
+ root.mkdir()
+ (root / 'AGENTS.md').write_text('My instructions.\n')
+ target = home / 'user-managed.md'
+ target.write_text('Keep linked instructions.\n')
+ (root / 'CLAUDE.md').symlink_to(target)
+ projects.prepare(home)
+ projects.prepare(home)
+ self.assertEqual((root / 'AGENTS.md').read_text().count('<!-- harness-os-connections -->'), 1)
+ self.assertTrue((root / 'AGENTS.md').read_text().startswith('My instructions.\n'))
+ self.assertEqual(target.read_text(), 'Keep linked instructions.\n')
+ self.assertTrue((root / 'CLAUDE.md').is_symlink())
+
def test_agent_folders_match_cli_convention_and_never_reuse_work(self):
with tempfile.TemporaryDirectory() as temp:
now = datetime(2026, 10, 4, 9, 5, 7)
diff --git a/os/tests/update_vm.py b/os/tests/update_vm.py
index 2ddce9772..146f1f2d8 100644
--- a/os/tests/update_vm.py
+++ b/os/tests/update_vm.py
@@ -161,6 +161,8 @@ def main():
receipt['system_channel']['checks'].append(finish_after_reboot(vm))
receipt['system_channel']['reboot_keyboard'] = check_graphical_keyboard(vm, 'system-channel-reboot')
receipt['checks'].append('The OS-channel update boots its rebuilt encrypted image and accepts keyboard input')
+ from connections_vm import exercise as check_connections
+ receipt['connections'] = check_connections(vm)
receipt['status'] = 'passed'
except BaseException as error:
receipt['status'] = 'failed'
diff --git a/os/tests/vm.py b/os/tests/vm.py
index f0c5111b1..c2fedb76e 100644
--- a/os/tests/vm.py
+++ b/os/tests/vm.py
@@ -1129,6 +1129,9 @@ def main():
result['checks'].append('Harness unlock screen renders, masks input, accepts a retry after a wrong password, and unlocks after the deliberate 100-second wait')
result['installed_keyboard_readiness'] = check_graphical_keyboard(vm, 'installed')
result['checks'].append('Installed graphical hn accepts physical-keyboard shell input, returns output and returns home after closing the pane')
+ from connections_vm import exercise as check_connections
+ result['connections'] = check_connections(vm)
+ result['checks'].append('Installed Connections opens in the browser and shares local credentials between command processes without device registration')
if config['encrypt']:
installed = json.loads(vm.read_file('/var/lib/harness-os/install.json'))
budget = installed['pbkdf_memory_limit_kib']
diff --git a/os/tools/build-fedora-package.py b/os/tools/build-fedora-package.py
index eda2f8084..f24272997 100644
--- a/os/tools/build-fedora-package.py
+++ b/os/tools/build-fedora-package.py
@@ -45,7 +45,8 @@ def file_list(root):
name = '/' + str(path.relative_to(root))
if path.is_dir() and not path.is_symlink():
if name in ['/usr/lib/harness', '/usr/lib/harness-os', '/usr/lib/harness-opencode',
- '/usr/share/licenses/harness-os', '/usr/share/licenses/harness-opencode'] or name.startswith('/usr/share/harness-os'):
+ '/usr/share/licenses/harness-os', '/usr/share/licenses/harness-opencode',
+ '/usr/share/licenses/harness-os-connections'] or name.startswith(('/usr/share/harness-os', '/usr/lib/harness-os/connections')):
lines.append('%dir ' + name)
else:
lines.append(('%license ' if name.startswith('/usr/share/licenses/') else '') + name)
diff --git a/os/tools/build-package.py b/os/tools/build-package.py
index 2fe2e4631..0380acedd 100644
--- a/os/tools/build-package.py
+++ b/os/tools/build-package.py
@@ -23,7 +23,7 @@ def package_info(version, timestamp, size, compositor_dependencies=()):
'pkgdesc = Harness session and verified Harness runtime\n'
'url = https://github.com/autonomous-ai/openharness\n'
f'builddate = {timestamp}\npackager = OpenHarness\nsize = {size}\n'
- 'arch = x86_64\nlicense = MIT\nlicense = GPL-2.0-only\n'
+ 'arch = x86_64\nlicense = MIT\nlicense = GPL-2.0-only\nlicense = Apache-2.0\n'
+ ''.join(f'depend = {name}\n' for name in dict.fromkeys((*DEPENDENCIES, *compositor_dependencies))))
@@ -54,6 +54,11 @@ def stage(source, runtime, destination, commit):
info = validate_runtime(runtime, commit)
os_source = source / 'os'
shutil.copytree(os_source / 'root', destination, symlinks=True)
+ shutil.copytree(os_source / 'connectors', destination / 'usr/lib/harness-os/connections',
+ ignore=shutil.ignore_patterns('__pycache__', '*.pyc'))
+ license_dir = destination / 'usr/share/licenses/harness-os-connections'
+ license_dir.mkdir(parents=True, exist_ok=True)
+ shutil.copyfile(os_source / 'connectors/LICENSE', license_dir / 'LICENSE')
special = {
'LICENSE': 'usr/share/licenses/harness-os/LICENSE',
'os/installer.py': 'usr/lib/harness-os/install.py',
diff --git a/os/tools/fedora_payload.py b/os/tools/fedora_payload.py
index 3e1d73bce..f35197b5b 100644
--- a/os/tools/fedora_payload.py
+++ b/os/tools/fedora_payload.py
@@ -46,6 +46,11 @@ def runtime_identity(runtime, commit):
def stage(source, runtime, destination, commit, runtime_commit, agent=None):
info = runtime_identity(runtime, runtime_commit)
+ shutil.copytree(source / 'os/connectors', destination / 'usr/lib/harness-os/connections',
+ ignore=shutil.ignore_patterns('__pycache__', '*.pyc'))
+ license_dir = destination / 'usr/share/licenses/harness-os-connections'
+ license_dir.mkdir(parents=True, exist_ok=True)
+ shutil.copyfile(source / 'os/connectors/LICENSE', license_dir / 'LICENSE')
# An allowlist keeps PC hooks and private fixture provisioning out of RPMs.
paths = [
'usr/bin/hn', 'usr/bin/harness', 'usr/bin/hn-browser',
@@ -71,6 +76,7 @@ def stage(source, runtime, destination, commit, runtime_commit, agent=None):
('docs/naming-system.md', 'usr/share/harness-os/guide/naming.md'),
('os/packaging/fedora/guide.md', 'usr/share/harness-os/guide.md'),
('os/packaging/fedora/AGENTS.md', 'usr/share/harness-os/AGENTS.md'),
+ ('os/root/usr/share/harness-os/connections.md', 'usr/share/harness-os/connections.md'),
('LICENSE', 'usr/share/licenses/harness-os/LICENSE'),
]:
target = destination / name