feat(connectors): connect Tailscale networks to SSH environments (#20617)

## Thinking Path

> - Paperclip manages work for AI agents.
> - SSH environments run tasks on computers that users own.
> - A Paperclip server needs network access before it can reach a
private computer.
> - A reusable Tailscale connection belongs in Connectors.
> - Connected machines should become choices in the existing SSH
environment form.
> - This change connects a tailnet and resolves selected machines
through a private network client.
> - Agents retain their choice of harness and AI account.

## Linked Issues or Issue Description

**Subsystem affected**

Connectors, environment settings, SSH execution, company secret storage,
and runtime packaging.

**Problem or motivation**

Entering a Tailscale address in the SSH form does not connect the
Paperclip server to that tailnet. Requiring a separate device key for
every environment also duplicates network setup.

**Proposed solution**

Add a Tailscale Connector with **Connect Tailscale Network**. Use
brokered OAuth consent to enroll one private network client per
connection. Let SSH environments select a connected network and stable
machine identity. Preserve the enrolled node state through the company
vault so a restart does not reuse the one-time token.

**Alternatives considered**

A separate Tailscale environment type would duplicate SSH behavior and
mix network access with harness selection. This change uses the existing
`ssh` driver. Related #15648 adds OAuth client credentials and a health
check; this change uses user consent and supplies outbound task
execution. Related #11743 concerns HTTPS brokering.

**Roadmap alignment**

This extends the existing Connected Apps, environment, and Personal &
Shared AI Accounts capabilities. This PR is stacked on #21248, which
provides SSH account selection independently of Tailscale. The hosted
OAuth broker is a companion control-plane change.

## What Changed

- Preserve Cloud reauthentication in the current browser tab. Explain
canceled or failed consent in the connector and offer a retry of the
same authorized saved connection.
- Record Cloud enrollment starts initiated through the Tailscale
connector in the company activity log.
- Check install-preparation descendant liveness through the kernel
process table in the Runner support test. Keep the direct child’s strict
reaping assertion and reject any non-zombie descendant.
- Align the application image stage contract with the Tailscale client
stage after the upstream Runner-image refactor. Keep the exact stage
list and check every application stage, including `tailscale-client`,
for prohibited Runner compiler commands.
- Group Tailscale consent, discovery, daemon lifecycle, pairing, and
deletion under `server/src/services/connectors/tailscale/`, with their
service tests. Update existing route, runtime, environment, vault, and
company-deletion imports. Keep the existing contracts, authorization,
audit, and transaction owners.
- Handle early stdin closure in the Kubernetes real-shell test helper.
Stop the input stream on `EPIPE`, preserve nonzero child exits, and
reject a zero exit when input was lost. Add two real-process regression
cases. Production transfer code and confinement checks are unchanged.
- Read configured Tailscale executable paths when a client starts, after
supported `.env` loading. Keep explicit command overrides available.
- Discard pending pairing results after switching to Direct SSH or
closing the form. Retain the existing company, connection, machine, and
port checks.
- Store network credentials with an immutable server-owned purpose from
their first vault row. Exclude them from generic catalogs, bindings,
environment projection, and value reads. Use a dedicated audited server
consumer for pinned connector reads. Block unclassified legacy
serialized node state at the same value boundary. Keep SSH private-key
binding separate from connector credentials.
- Gate network queries and setup on verified local-implicit or
instance-admin access. Hide Tailscale catalog rows for other members,
show an admin requirement on direct setup navigation, and avoid device
discovery before management access is known.
- Keep failed-client cleanup in the network manager. A failed request
cannot disconnect a newer retry for the same identity; explicit
connector disconnect and enrollment retirement still stop their
networks.
- Check for readable Ed25519, ECDSA, or RSA host public keys before
pairing edits `authorized_keys`. Print a known-hosts entry for every
available key, or fail before changing authorized keys if none are
available.
- Return self-hosted Cloud enrollment to the Tailscale connector. Save
the unprefixed setup path and let the shared callback add the verified
company prefix. Keep external and unrelated destinations rejected.
- Hide pairing instructions after an SSH port change. Ignore late
key-selection results for the old port. Operators prepare again for
matching known-hosts output.
- Retire connector references before deleting a company or its vault
credential. Stop company daemons after the database commit. Keep failed
secret retirement retryable and prevent late node-state writes from
restoring deleted connections. Discard retired state without blocking
behind the vault deletion lock.
- Reload a mismatched credential before replacing a ready daemon.
Recheck the active entry and manager generation after the read. An older
request cannot stop a newer healthy socket or cross shutdown.
- Pin connector credentials to the exact vault version and SHA-256
digest recorded by trusted enrollment and node-state writes. Ignore
generic secret rotations. Advance both fields with a compare-and-set
guard. Reject unpinned or tampered credentials before network startup.
- Save an explicit Direct SSH selection and clear old Tailscale fields
after config merging. Preserve the operator's entered direct host.
- Route all Tailscale SSH runtime access through the connection service
after SSH-key loading. Pin access to the environment's saved connector
identity and recheck after device discovery. Remove standalone key-based
daemon startup and reject raw enrollment keys or credential-only network
configurations. Align the shared config type and SDK pins.
- Correct two E2E assumptions exposed during connector qualification.
Keep the two-window chat fixture stale until its own mutation. Validate
the original failed run and its permitted write-revocation timestamp in
the legacy recovery browser test.
- Add the Tailscale Connector page, catalog entry, OAuth return flow,
connected-network management, device discovery, and disconnect. Document
all six routes in OpenAPI and the API reference, including their
instance-admin requirement.
- Add company-scoped connection storage in `0480_lazy_lethal_legion`,
trusted credential version/digest fields in `0481_round_pet_avengers`,
and server-owned secret purpose/backfill in
`0482_aberrant_rumiko_fujikawa`. Generate all three migrations through
the maintained command and retain the five newest snapshots.
- Add machine pairing that generates a fresh SSH key per request, stores
its private half in the company vault, and uses the generated public
half in the install command. Do not trust editable saved metadata.
Preserve existing authorized keys, including a file without a final
newline. Keep SSH username, workspace, and trusted host keys explicit.
- Use the existing SSH driver. Resolve the machine's current address
from its stable device ID. Reject disconnected, removed, offline, and
wrong-company selections.
- Hide Network when Direct is the only option. Select a sole connected
tailnet automatically and hide its selector. Remove the requested setup
helper copy. Do not restrict the harness to Claude.
- Run a private userspace Tailscale daemon with a separate socket.
Persist its node state before execution. Restore it after restart, bound
startup, serialize reconnect cleanup, and close it during server
shutdown.
- Guard OAuth completion with a durable attempt marker. Disconnect and
newer authorization invalidate older callbacks. Close replaced daemons
and remove cancelled enrollment secrets without changing newer
connection state.
- Preserve SSH host verification and tailnet-specific session identity.
Honor the configured Tailscale executable path, including spaces and
OpenSSH percent escaping.
- Package checksum-pinned Tailscale clients and their license in the
standard runtime image. Exercise the client build stage in PR CI and
include it in image smoke checks.

## Verification

- Merge status: all CI and image checks pass, and current-head Apex is
5/5 with no unresolved comments. GitHub rejected a direct merge because
the active master ruleset requires code-owner approval for
`.github/workflows/pr-trusted.yml`. The [CODEOWNERS workflow
pattern](https://github.com/paperclipai/paperclip/blob/master/.github/CODEOWNERS#L3)
applies; eligible maintainers already have review requests. Auto-merge
is enabled with the squash method for the verified head. The PR remains
open pending that required approval; no branch policy was bypassed.
- Final revision: `fdb29b2cc366f4945b7f4c3e2b2d25070329a21b`, including
master `999709b0a6dd416af335b5debded13e1de7fcb7a`. [Final CI
verification
passed](https://github.com/paperclipai/paperclip/actions/runs/43518584814/job/132213508320).
All required checks pass, all applicable test/build gates are green, and
the branch is mergeable against master. SSH prerequisite #21248 and
Cloud broker paperclipai/paperclip-cloud#1314 are already merged.
- [Apex reviewed this exact revision at
5/5](https://github.com/paperclipai/paperclip/pull/20617#issuecomment-6776629437).
There are no unresolved review threads. The PR is classified as Critical
impact.
- Final image qualification passes for the [application Runner
path](https://github.com/paperclipai/paperclip/actions/runs/43518584522/job/132206784267),
[amd64 Runner
image](https://github.com/paperclipai/paperclip/actions/runs/43518584544/job/132207296198),
and [arm64 Runner
image](https://github.com/paperclipai/paperclip/actions/runs/43518584544/job/132207296156).
Typechecks, Runner support, native/Rust tests, provider tests,
serialized-server suites, browser shards, and the remaining applicable
CI checks pass. This is source/image CI qualification, not a production
rollout.
- The last master conflict affected only Docker stage declarations and
their boundary test. Both the checksum-pinned Tailscale stage and
upstream `runner-lockfile` guard are retained, including the upstream
`deps` inheritance. The Tailscale client stage is byte-identical. All
180 cases across five Docker/image contract suites pass locally, along
with server and UI typechecks. The maintained 543-input SDK check has no
drift. Runtime and lock pins are unchanged. Secret/PII and whitespace
scans pass.
- Seven OAuth regression cases failed before the fixes. The current-tab
test uses the real handoff helper, checks that the session is stored
before reauthentication navigation, mounts the shared return page,
resumes consent, and verifies handoff cleanup. Callback tests check
trusted saved-connection context, fixed safe outcomes, failure audit
metadata, denied membership and expired-state rejection, JSON API
errors, and no provider text in browser returns. UI retries require a
connection in the current company's catalog. All 80 OAuth
route/service/UI/shared-handoff cases pass; server and UI source/test
typechecks pass.
- [Server shard 4/12 on the prior
refresh](https://github.com/paperclipai/paperclip/actions/runs/43510727031/job/132180301436)
passed 2,784 cases and skipped 21, then failed a reassignment fixture's
`TRUNCATE companies CASCADE` cleanup with PostgreSQL `40P01`. Its
automatic retry found the surviving `REA` prefix. The unchanged test
passes all three cases locally. A controlled reader/cleanup overlap
reproduces the same deadlock, but the exact competing CI query was not
logged. Each case now has a distinct company prefix and identifier; the
owned database is removed at suite end. The three test bodies and
assertions are byte-identical. Eight local reassignment/lock-release
cases pass, and the [final server shard 4/12
passes](https://github.com/paperclipai/paperclip/actions/runs/43518584814/job/132207159392).
Production reassignment logic, deadlines, and retries are unchanged.
- The initial master integration passed 330 cases across 17 suites.
Coverage includes connector state, device discovery, network lifecycle,
pairing, routes, SSH binding and exports, environment persistence, and
connector UI. All three unpublished migrations were regenerated after
master's `0479_short_darkstar`: `0480_lazy_lethal_legion`,
`0481_round_pet_avengers`, and `0482_aberrant_rumiko_fujikawa`. Each SQL
body is byte-identical to its earlier unpublished migration. Generated
snapshots preserve existing master tables and add only the intended
Tailscale table and secret-purpose column. Exactly five snapshots
remain, 0478–0482. Numbering, safety, compatibility, and snapshot-drift
checks pass. The later Docker refresh did not alter this migration
sequence.
- Earlier attempts remain part of the verification record. On `1c020a0`,
Rust cache restoration and server shard 5/12 were interrupted by
shutdown signals, Runner shard 2/3 lost communication with no
retrievable log, and an amd64 provider download failed with npm
`ECONNRESET`. Same-head retries recovered, without establishing the
cause of the communication loss. Later superseded runs also had
cancellations with incomplete logs. These interrupted attempts are not
counted as passes. The final revision has fresh successful CI.
- Local platform limits remain recorded. The Kubernetes suite on macOS
passed 191 cases, failed 12 Linux `/proc/self/fd` transfer cases, and
skipped four Linux-only cases. Unchanged source reproduced the same 12
failures. An initial run also lacked provider dependencies until the
maintained preparation command installed them. Those local attempts are
not green qualification. Final Linux provider CI passes. Local Docker
qualification was unavailable; final image checks passed in CI.
- Before PR separation, a live tailnet/SSH Claude Code task completed on
Ubuntu ARM64 without provider login for the remote user. The selected
Paperclip subscription ran it, wrote the expected file, posted
completion, and marked the task done. File contents and private runtime
cleanup were checked. This is prior live evidence; the final revision
was not live-retested. Other providers have automated coverage only.
Hosted registration for unrelated tailnets and production concurrency
remain qualification limits below.
- The Superagent security and supply-chain reports remain neutral and
inconclusive. Earlier attempts to restart the failed security scan
returned HTTP 404. Supply-chain intelligence lacked coverage for
extracted pinned dependencies and the shared workflow reference. These
reports do not establish successful security qualification. The required
CI and review gates pass; this external coverage gap remains disclosed.

## Risks

- The Superagent security and supply-chain reports are inconclusive. The
security scan re-run request returned HTTP 404, and the supply-chain
scanner lacks coverage for the extracted dependencies and shared
workflow reference. These neutral results are not successful security
qualification.
- The server-owned secret purpose is internal database metadata, not an
HTTP-writable field. The generic secret service owns enforcement so
direct API reads and runtime projection share the same restriction.
Previously copied node state remains valid outside Paperclip until the
enrolled device is revoked in Tailscale; a local disconnect cannot stop
an external copy.
- Tailscale network configurations now require a connected Connector and
selected machine. The unreleased key-only path is removed; any saved
configuration from that path needs Connector setup.
- The connector remains a pilot. The local test used an OAuth app
registered in the consenting user's tailnet. Qualify hosted app
registration for unrelated customer tailnets before general
availability.
- This implementation supports one serving process per instance.
Concurrent replicas need exclusive ownership of the persisted network
identity before production rollout. Preserve the database and company
vault master key across restarts.
- Each machine-pairing preparation creates a new vault secret. Unused
generated keys follow the existing secret deletion lifecycle. A saved
SSH key remains available as an explicit choice.
- Apply additive migrations `0480_lazy_lethal_legion`,
`0481_round_pet_avengers`, and `0482_aberrant_rumiko_fujikawa` before
application rollout. The new credential version and digest columns are
nullable. Existing unpinned connections require fresh OAuth consent; the
migration deliberately does not trust or backfill a generic secret
value. Regenerate or renumber migrations if master advances the sequence
before merge.
- The target needs an SSH server, its chosen harness, and allowed
tailnet access. A reachable network does not grant SSH or provider
authorization. Pairing reads standard `/etc/ssh` host-public-key files;
custom host-key locations require manual known-hosts configuration.
- Roll back the application revision to remove new entry points.
Existing connection secrets and registered Tailscale nodes retain their
separate lifecycle. Do not drop the table or delete node state as part
of an application rollback.
- Production qualification still needs denied-policy, revocation,
cancellation, and deployment-overlap checks. Local Docker and a
production deployment were not performed.

## Model Used

OpenAI Codex, gpt-6.1-sol, xhigh reasoning, with local code execution
and tool use.

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used
- [x] I have checked ROADMAP.md and this extends existing connector and
environment features
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have described the issue in-PR using the feature request fields
- [x] I have not referenced internal issues, local URLs, or private
machine identifiers
- [x] My branch name describes the change
- [x] I have run focused tests locally and they pass
- [x] I have added tests for new behavior and failure paths
- [x] I have updated documentation
- [x] I have documented migration and runtime risks
- [x] All Paperclip CI gates are green
- [ ] Required code-owner approval received for the workflow change
- [x] Greptile Apex is 5/5 on the final head with no unresolved comments
- [x] I will address CI and review findings before requesting merge

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
This commit is contained in:
Devin FoleyandPaperclip authored and GitHub committed 2026-11-13 15:15:43 -08:00
1 parent 1d112a504f
commit 21bf7ebcee
72 files changed
+5105 -73

No files matched your search

+3
View File
@@ -653,6 +653,9 @@ jobs:
- name: Run generated-file drift checks against the Docker build context
run: docker buildx build --file .github/docker-context-checks.Dockerfile .
- name: Verify Tailscale runtime clients
run: docker buildx build --file Dockerfile --target tailscale-client .
- name: Upload CI profile timings
continue-on-error: true
if: always() && env.PAPERCLIP_CI_PROFILE == 'true'
+22
View File
@@ -12,6 +12,24 @@ RUN usermod -u $USER_UID --non-unique node \
&& groupmod -g $USER_GID --non-unique node \
&& usermod -g $USER_GID -d /paperclip node
FROM base AS tailscale-client
ARG TARGETARCH
WORKDIR /out
RUN set -eu; \
case "$TARGETARCH" in \
amd64) digest=720cbbccbfc03d8b55df72afc19e5a72e31b0f65934700aa6fa38074d4ad7bf7 ;; \
arm64) digest=e900b0e6e25023a1e504b2c237ce2a32ea0535e006f8c1a1097a490886493b6c ;; \
*) echo "Unsupported Tailscale architecture: $TARGETARCH" >&2; exit 1 ;; \
esac; \
curl --fail --silent --show-error --location --retry 2 --connect-timeout 15 --max-time 120 --proto '=https' --proto-redir '=https' \
"https://pkgs.tailscale.com/stable/tailscale_1.104.5_${TARGETARCH}.tgz" -o tailscale.tgz; \
printf '%s tailscale.tgz\n' "$digest" > tailscale.sha256; \
sha256sum -c tailscale.sha256; \
tar -xzf tailscale.tgz --strip-components=1; \
gosu node /out/tailscale version; \
gosu node /out/tailscaled --version
COPY docker/tailscale.LICENSE /out/LICENSE
FROM base AS runner-lockfile
WORKDIR /runner-lockfile
COPY package.json pnpm-workspace.yaml pnpm-lock.yaml .npmrc ./
@@ -369,6 +387,10 @@ RUN echo "cli-tools-epoch: ${CLI_TOOLS_CACHE_EPOCH}" \
&& mkdir -p /paperclip \
&& chown node:node /paperclip
COPY --from=tailscale-client /out/tailscale /out/tailscaled /usr/local/bin/
COPY --from=tailscale-client /out/LICENSE /usr/local/share/licenses/tailscale/LICENSE
RUN gosu node tailscale version && gosu node tailscaled --version
COPY scripts/docker-entrypoint.sh /usr/local/bin/
RUN chmod +x /usr/local/bin/docker-entrypoint.sh
+231
View File
@@ -0,0 +1,231 @@
# Use Tailscale machines in SSH environments
The Tailscale connector gives Paperclip access to a tailnet. Paperclip joins a
separate device to that network, then uses the existing SSH environment driver
to run tasks on selected computers. The connector is managed from **Connectors**
and can serve multiple SSH environments in the same company. The computer is
not replaced or provisioned by Paperclip.
In **Connectors**, find **Tailscale**, open it and click **Connect Tailscale Network**.
After approving consent, click **Create SSH environment**, or create an SSH
environment and select **Tailscale** under **Network**. Choose the connection
and machine, then configure the SSH user, port, absolute workspace path, private
key, and trusted host keys. The Tailscale network option appears once a tailnet
is connected. On a Mac
with the normal Tailscale application, enable macOS Remote Login. Tailscale SSH
server support on macOS requires the open-source tailscaled variant; ordinary
OpenSSH over Tailscale works with the standard Mac application.
Cloud reauthentication saves the pending OAuth handoff in the current browser
tab before redirecting. If consent is canceled or completion fails after the
state and company checks, the browser returns to the saved connection with a
fixed explanation and a retry. The return URL contains only the connection ID
and a known outcome, without provider error text, claims, or OAuth state.
SSH setup hides the Network selector when Direct connection is the only
available option. A sole connected tailnet is selected automatically and its
connection selector is hidden; multiple connected tailnets remain selectable.
Switching an existing environment to **Direct connection** clears its saved
Tailscale machine and credential references and saves the direct host you enter.
After selecting a machine, **Prepare machine pairing** creates an SSH key in
Paperclip’s vault and displays a command containing only the public key. Each
preparation generates a fresh key pair. The command uses the public key produced
during that request, never mutable metadata from a saved secret. Run it
as the target SSH user. The command preserves existing authorized keys, including
files without a final newline. Before installing the key, it checks for readable
Ed25519, ECDSA, or RSA host public keys in `/etc/ssh` and stops without changing
`authorized_keys` if none are available. It prints that user's name, home
workspace path, and known-hosts entries for every available host key for the
form. You can also select an existing SSH private key secret.
Pairing output is tied to the selected company, tailnet, machine, and SSH port.
After editing the port, prepare pairing again for matching known-hosts output.
A late response for an earlier port cannot replace the selected private key.
Switching to Direct connection or closing the form also prevents pending pairing
results from changing the selected key.
Save the environment and test it. Select it as an agent’s environment and choose
any harness supported by SSH environments. Select the agent's AI account in
Paperclip. Runs use that account's subscription or API key, with private
credential directories on the target computer, just as sandbox runs do. The
computer supplies the installed harness and workspace; its SSH user's provider
login is not used for an agent with a configured AI account. Test the chosen
harness separately: SSH access does not prove provider authentication.
SSH's **Advanced** section includes **Use authentication configured on the remote
machine**. New environments leave it off, requiring the agent's Paperclip AI
account. Turn it on to use the remote user's provider login instead. Existing
SSH environments display it as on; opening or upgrading an installation does
not rewrite their saved configuration. The same option applies to direct SSH
and Tailscale connections.
The environment keeps the `ssh` driver. Machine selection stores the connector
ID and Tailscale’s stable device ID, and runtime
resolution looks up its current address through that connection’s private
socket. Offline, removed, disconnected, and wrong-company machines fail closed.
The host’s existing Tailscale connection is never a fallback.
## OAuth and credential custody
The connection uses the Cloud OAuth broker profile `tailscale.tailnet`, with
`auth_keys:create:once`. It is a network connector on the Connectors surface;
it does not publish agent tools or enter MCP discovery. Management requires an
instance administrator with access to the company. The catalog and setup page
check that access before requesting network data; other company members are
directed to an instance administrator. Existing SSH environment access governs
which agents can execute there. Self-hosted local
instances first complete the existing Paperclip Cloud enrollment and return to
their company's Tailscale connector page to continue network consent. Cloud
stacks use their existing broker identity and handoff.
Tailscale returns a single-use device enrollment token without a refresh token.
The broker seals it to the originating instance. The instance validates the
user, company, state expiry and single-use callback, stores the token through the
configured company secret provider, and immediately replaces its current value
with the enrolled node state before permitting execution. The connection records
the exact trusted vault version and a SHA-256 digest of the server-written value.
Runtime reads that version and verifies its digest. A generic company secret
rotation cannot change the authorized network. Trusted node-state saves advance
both fields together, with a compare-and-set guard so an older save cannot
replace a newer state. Reads keep using the previous trusted version until the
new version is committed. Tokens, private node state, digests and client secrets
never appear in connection or environment responses.
Enrollment tokens and node state are server-owned secrets with a durable
`system_purpose` classification. Generic company catalogs omit them. Generic
bindings, environment injection, and agent value reads reject them, including
bindings saved before the restriction. Renaming or rotating a secret cannot
remove this classification. Disconnecting or replacing a connection leaves its
old credential protected. Only the connector's server consumer can resolve its
trusted value; an SSH environment binds its private key, never the node state.
Unclassified legacy node-state values are also rejected by generic reads,
including state left behind by an earlier connection replacement.
Migration `0482_aberrant_rumiko_fujikawa` classifies existing connector-referenced secrets.
Apply it before running the updated server. If node state was copied before
this restriction, revoke that enrolled device in Tailscale; a local disconnect
cannot stop a copy outside Paperclip.
Connections created before migration `0481_round_pet_avengers` have no trusted version
and digest. They fail closed and require a fresh **Connect Tailscale Network**
consent. The migration leaves these fields empty; it does not trust or backfill a
generic secret's latest value.
Each connection has a separate userspace daemon and private socket. A stale
credential read reloads the trusted value before replacing a ready daemon and
rechecks which daemon is active after the reload. It preserves a healthy newer
socket and cannot cross a manager shutdown. Failed connection requests leave
cleanup to the network manager's exact client; they cannot disconnect a newer
retry using the same connector identity. The daemon accepts no subnet routes or
DNS changes and blocks incoming connections. Normal shutdown saves
node state and removes temporary files. A restart restores the enrolled device;
it does not reuse the OAuth token or require consent for every task. Disconnect
invalidates pending consent and stops the connection’s local daemon. A callback
already exchanging or saving credentials cannot reconnect after disconnect or
replace a newer authorization. Completion retains the consumed state's digest
as a private attempt marker, with no expiry; disconnect replaces that marker.
Database writes and credential reloads verify ownership without holding a database
lock across broker or daemon startup. Cancelled attempts close their daemon and
remove their newly created secret without touching a newer connection's state.
Disconnect does not remove the target computer from Tailscale.
Company deletion removes connector records before vault secrets in the company
transaction. After commit, it stops every daemon owned by those records. A
rolled-back deletion leaves the connector and its daemon intact. Deleting a
connector's vault secret invalidates pending consent, disconnects its network,
and clears the trusted credential reference before removing the secret. If
shutdown fails, the disconnected reference remains available for a deletion
retry. Late daemon state writes cannot restore a retired connector.
Task runtime resolution obtains its socket from this same guarded connection
service after loading the SSH key. It requires the connection to remain connected
with the environment's saved credential identity during credential reload,
daemon startup, and device discovery. A disconnect or replacement rejects the
run before returning a socket; runtime resolution cannot restart the connection
from a stale saved secret.
Saved network credentials without a connector and machine selection are rejected;
all Tailscale environments use the connector's lifecycle.
This implementation currently supports one serving process per instance.
Concurrent replicas need a durable connection ownership lease before rollout.
The enrollment token is consumed once; it is not the runtime credential.
Tailscale identity belongs to the persisted machine key in the saved node state,
not the container ID or hostname. A redeploy must retain both the database's
encrypted node state and the same vault master key. Cloud already materializes
the stable per-stack `PAPERCLIP_SECRETS_MASTER_KEY` across release rolls. Do not
make the connector ephemeral or replace its node state at each start. Losing
that state, device removal, or a tailnet reauthentication policy can require
fresh consent. The app-owned device has the consenting user's tailnet rights.
## Local development
Run the Paperclip instance at `http://localhost:3100` and the local Cloud broker
at `http://localhost:3000`. Register the OAuth app callback as
`http://localhost:3000/v1/connector/oauth/tailscale/callback` with scope
`auth_keys:create:once`. The OAuth app must be registered in the authorizing
user’s tailnet under Tailscale’s currently documented restriction.
Configure the local broker with:
- `CLOUD_HARNESS_CONNECTOR_TAILSCALE_ENABLED=1`
- `CLOUD_HARNESS_CONNECTOR_TAILSCALE_CLIENT_ID`
- `CLOUD_HARNESS_CONNECTOR_TAILSCALE_CLIENT_SECRET_REF=secret://local/tailscale`
- `CLOUD_HARNESS_CONNECTOR_TAILSCALE_LOCAL_CLIENT_SECRET_FILE`, an owner-only
regular file outside the checkout containing the OAuth app client secret
- `CLOUD_HARNESS_CONNECTOR_TAILSCALE_PILOT_INSTANCE_IDS`, the exact enrolled local
instance ID
The file credential path is accepted only for a loopback HTTP development broker
using the local fake provider. Hosted credentials continue to use the configured
provider secret store. Never regenerate an existing Cloud `.env` or identity
salt to configure this test.
The instance needs `tailscale` and `tailscaled`. Its OAuth return path is
`/api/tools/oauth/tailscale/callback`, and completion returns to the Tailscale
connector page. For a separate local userspace
client, install the pinned programs outside the checkout:
```sh
GOBIN="$HOME/.local/share/paperclip-tailscale/bin" go install tailscale.com/cmd/tailscale@v1.104.5
GOBIN="$HOME/.local/share/paperclip-tailscale/bin" go install tailscale.com/cmd/tailscaled@v1.104.5
```
Set `PAPERCLIP_TAILSCALE_CLI` and `PAPERCLIP_TAILSCALED` to their absolute paths.
These settings can be set in the supported `.env` files. Each new client reads
them at startup, after environment loading.
Set `PAPERCLIP_CLOUD_CONNECTOR_BASE_URL=http://localhost:3000` and
`PAPERCLIP_CLOUD_CONNECTOR_ENVIRONMENT=development` for local enrollment.
## Verification and rollout gates
Offline tests cover broker handoff and sealed claims, company and user binding,
expired and competing callbacks, disconnect during claim exchange, secret
creation, credential reload and daemon startup, superseding authorizations,
failed-enrollment cleanup, denied authorization, device discovery, driver
selection, private subprocess state, shutdown, and restart. These do not prove
live consent or remote execution.
Before rollout, qualify real consent, machine discovery, a Claude task that
writes a file on the selected computer, result streaming, cancellation, server
restart, machine sleep/reboot, and revocation. A local instance whose public URL
is localhost also needs an API path reachable by the remote agent for tasks that
call back to Paperclip unless the adapter uses the existing remote callback
bridge. Production Cloud uses its public HTTPS stack URL.
The connector's bundled artwork comes from the vendor's
`https://tailscale.com/favicon.png`, copied without modification (SHA-256
`680570c9090b604450792f68ceed10beeb33a69c9bccc2a92e398564c7075a5c`).
The GA announcement describes third-party integrations, but the published OAuth
setup guide still restricts each app to its own tailnet. This profile remains
behind explicit instance pilot admission. A local personal-tailnet test does not
establish that one Paperclip-owned OAuth app can authorize every customer’s
personal tailnet. Verify that provider registration path before general rollout.
Provider references:
- [OAuth apps](https://tailscale.com/docs/features/oauth-apps)
- [Device provisioning](https://tailscale.com/docs/features/oauth-apps/device-provisioning)
- [Tailscale SSH](https://tailscale.com/docs/features/tailscale-ssh)
+28
View File
@@ -0,0 +1,28 @@
BSD 3-Clause License
Copyright (c) 2020 Tailscale Inc & contributors.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+5
View File
@@ -62,3 +62,8 @@ List endpoints support standard pagination query parameters when applicable. Res
## Rate Limiting
No rate limiting is enforced in local deployments. Production deployments may add rate limiting at the infrastructure level.
## Network Connectors
[Tailscale connections](tailscale.md) let instance administrators connect a
company tailnet and select its machines in SSH environments.
+5
View File
@@ -5,6 +5,11 @@ summary: Secrets CRUD
Manage encrypted secrets that agents receive through environment bindings or fetch on demand.
Server-owned connector credentials, including Tailscale enrollment tokens and
node state, are excluded from company secret catalogs. Generic secret bindings,
runtime projection, and agent value reads cannot resolve them. Existing bindings
do not bypass this restriction; those requests return `403`.
## Agent List and Fetch
These routes require the current run-bound agent JWT. They are not available to
+56
View File
@@ -0,0 +1,56 @@
---
title: Tailscale Connections
summary: Connect a company tailnet and select its machines in SSH environments
---
These endpoints require a board operator with instance-admin rights and access
to the company. Local implicit board access is also accepted. Agent credentials
cannot manage a Tailscale connection. Browser mutations require a trusted Origin.
| Method | Path | Result |
|--------|------|--------|
| GET | `/api/companies/{companyId}/tailscale-connections` | Connection metadata |
| POST | `/api/companies/{companyId}/tailscale-connections` | Authorization URL |
| GET | `/api/companies/{companyId}/tailscale-connections/{connectionId}/devices` | Available machines |
| POST | `/api/companies/{companyId}/tailscale-connections/{connectionId}/pairing` | Public SSH pairing command |
| DELETE | `/api/companies/{companyId}/tailscale-connections/{connectionId}` | Disconnected connection metadata |
A connection response contains only `id`, `companyId`, `name`, and `status`.
Status is `pending`, `connecting`, `connected`, or `disconnected`. Responses do
not include enrollment tokens, persisted node state, or OAuth state digests.
To start consent, POST a JSON object with optional `name` and `connectionId`.
The name defaults to `My tailnet`. An existing connection ID starts a new
authorization for that connection. The `201` response contains `authorizationUrl`
and `expiresAt`. It also contains `connection` when consent can start immediately.
An instance without Cloud enrollment first returns the enrollment URL. Hosted
consent can include a `handoff` with `kind: "paperclip_cloud"` and an opaque
`session`. Use the normal browser connector flow for that signed handoff.
Machine discovery returns `id`, `name`, `hostname`, `address`, `os`, and `online`
for each peer. Use the stable `id` when configuring a Tailscale-backed SSH
environment. The current address is resolved again for execution.
An SSH environment with `network: "tailscale"` requires `tailscaleConnectionId`
and `tailscaleDeviceId`. Saving binds the connector's current credential identity.
Raw enrollment keys and credential-only configurations are rejected. Runtime
access checks the connection again after loading the SSH key and after device
discovery; a disconnected or replaced connection requires fresh setup.
To prepare pairing, POST `{ "deviceId": "<stable-device-id>", "port": 22 }`.
The port defaults to 22. The response contains `privateKeySecretId`, `publicKey`,
and `command`. Each preparation generates a fresh key pair. Run the command as
the target SSH user and configure the environment with the returned secret ID.
The private key never appears in this response.
The browser returns from consent to
`GET /api/tools/oauth/tailscale/callback` with required `state` and either
`claim_id` or an authorization `error`. The callback rechecks the initiating
operator's company access and consumes state once. On success it returns a
`303` redirect to the company's connector page with `Cache-Control: no-store`
and `Referrer-Policy: no-referrer`.
Disconnect invalidates both pending consent and callbacks already completing.
It stops the private network client and keeps the connection record. It does
not remove the target computer from Tailscale. A later authorization can replace
the saved connection; older callbacks cannot replace that newer authorization.
@@ -99,6 +99,7 @@ export function buildRemoteExecutionSessionIdentity(spec: SshRemoteExecutionSpec
return {
transport: "ssh",
...(typeof spec.useHostAuth === "boolean" ? { useHostAuth: spec.useHostAuth } : {}),
...(spec.tailscaleIdentity ? { tailscaleIdentity: spec.tailscaleIdentity } : {}),
host: spec.host,
port: spec.port,
username: spec.username,
@@ -114,6 +115,7 @@ export function remoteExecutionSessionMatches(saved: unknown, current: SshRemote
return (
asString(parsedSaved.transport) === currentIdentity.transport &&
parsedSaved.useHostAuth === currentIdentity.useHostAuth &&
asString(parsedSaved.tailscaleIdentity) === asString(currentIdentity.tailscaleIdentity) &&
asString(parsedSaved.host) === currentIdentity.host &&
asNumber(parsedSaved.port) === currentIdentity.port &&
asString(parsedSaved.username) === currentIdentity.username &&
@@ -0,0 +1,54 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { buildSshSpawnTarget, parseSshRemoteExecutionSpec } from "./ssh.js";
import { buildRemoteExecutionSessionIdentity, remoteExecutionSessionMatches } from "./remote-managed-runtime.js";
import { normalizeAdapterExecutionTargetSessionIdentity } from "./execution-target.js";
const spec = { host: "workstation.tailnet.test", port: 22, username: "developer", remoteWorkspacePath: "/workspace",
remoteCwd: "/workspace/task", privateKey: null, knownHosts: "host ssh-ed25519 fixture", strictHostKeyChecking: true };
describe("SSH task execution through Tailscale", () => {
afterEach(() => { vi.unstubAllEnvs(); });
it.each(["/tmp/Paperclip tools/tailscale", "/tmp/tools%h/tailscale"])("uses the configured Tailscale executable without interpreting its path (%s)", async cli => {
vi.stubEnv("PAPERCLIP_TAILSCALE_CLI", cli);
const target = await buildSshSpawnTarget({ spec: { ...spec, tailscaleSocket: "/tmp/paperclip-ts-test/socket" }, command: "true", args: [], env: {} });
try {
expect(target.args).toContain(`ProxyCommand='${cli.replaceAll("%", "%%")}' --socket=/tmp/paperclip-ts-test/socket nc %h %p`);
} finally { await target.cleanup(); }
});
it("uses the isolated tailnet socket for command execution while keeping host verification", async () => {
const target = await buildSshSpawnTarget({ spec: { ...spec, tailscaleSocket: "/tmp/paperclip-ts-test/socket" }, command: "true", args: [], env: {} });
try {
expect(target.command).toBe("ssh");
expect(target.args).toContain("ProxyCommand=tailscale --socket=/tmp/paperclip-ts-test/socket nc %h %p");
expect(target.args).toContain("StrictHostKeyChecking=yes");
expect(target.args).toContain("BatchMode=yes");
} finally { await target.cleanup(); }
});
it("leaves direct SSH connections independent of Tailscale", async () => {
const target = await buildSshSpawnTarget({ spec, command: "true", args: [], env: {} });
try { expect(target.args.some(arg => arg.startsWith("ProxyCommand"))).toBe(false); }
finally { await target.cleanup(); }
});
it.each(["/tmp/socket;touch bad", "/tmp/$(touch bad)", "relative/socket", "/tmp/socket%h"])("rejects unsafe socket %s", async tailscaleSocket => {
await expect(buildSshSpawnTarget({ spec: { ...spec, tailscaleSocket }, command: "true", args: [], env: {} })).rejects.toThrow("Invalid Tailscale socket");
expect(parseSshRemoteExecutionSpec({ ...spec, tailscaleSocket })).toBeNull();
});
it.each(["host;touch bad", "$(touch bad)", "-oProxyCommand=bad", "host%h"])("rejects host interpolation %s", async host => {
await expect(buildSshSpawnTarget({ spec: { ...spec, host, tailscaleSocket: "/tmp/socket" }, command: "true", args: [], env: {} })).rejects.toThrow("Invalid Tailscale host");
});
it("preserves the transport through execution-spec parsing and isolates sessions across tailnets", () => {
const tailscale = { ...spec, tailscaleSocket: "/tmp/socket", tailscaleIdentity: "company:connection-one" };
expect(parseSshRemoteExecutionSpec(tailscale)).toEqual(tailscale);
const saved = buildRemoteExecutionSessionIdentity(tailscale);
expect(normalizeAdapterExecutionTargetSessionIdentity(saved)).toEqual(saved);
expect(saved).not.toHaveProperty("tailscaleSocket");
expect(remoteExecutionSessionMatches(saved, { ...tailscale, tailscaleSocket: "/tmp/restarted/socket" })).toBe(true);
expect(remoteExecutionSessionMatches(saved, { ...tailscale, tailscaleIdentity: "company:connection-two" })).toBe(false);
expect(remoteExecutionSessionMatches(saved, spec)).toBe(false);
});
});
+18 -1
View File
@@ -30,6 +30,8 @@ const SSH_STDIN_COMMAND = "IFS= read -r paperclip_ssh_command_b64 || exit 125; p
export interface SshConnectionConfig {
useHostAuth?: boolean;
tailscaleSocket?: string;
tailscaleIdentity?: string;
host: string;
port: number;
username: string;
@@ -178,8 +180,14 @@ export function parseSshRemoteExecutionSpec(value: unknown): SshRemoteExecutionS
}
if (parsed.useHostAuth !== undefined && typeof parsed.useHostAuth !== "boolean") return null;
if (parsed.tailscaleSocket !== undefined && (typeof parsed.tailscaleSocket !== "string" || !/^\/[A-Za-z0-9_./-]+$/.test(parsed.tailscaleSocket))) return null;
if (parsed.tailscaleIdentity && !parsed.tailscaleSocket) return null;
return {
...(typeof parsed.useHostAuth === "boolean" ? { useHostAuth: parsed.useHostAuth } : {}),
...(typeof parsed.tailscaleSocket === "string" ? { tailscaleSocket: parsed.tailscaleSocket } : {}),
...(typeof parsed.tailscaleIdentity === "string" ? { tailscaleIdentity: parsed.tailscaleIdentity } : {}),
host,
port: portValue,
username,
@@ -382,7 +390,7 @@ async function withTempFile(
}
async function createSshAuthArgs(
config: Pick<SshConnectionConfig, "privateKey" | "knownHosts" | "strictHostKeyChecking">,
config: Pick<SshConnectionConfig, "privateKey" | "knownHosts" | "strictHostKeyChecking" | "tailscaleSocket" | "tailscaleIdentity" | "host">,
): Promise<{ args: string[]; cleanup: () => Promise<void> }> {
const tempFiles: Array<() => Promise<void>> = [];
const sshArgs = [
@@ -394,6 +402,15 @@ async function createSshAuthArgs(
`StrictHostKeyChecking=${config.strictHostKeyChecking ? "yes" : "no"}`,
];
if (config.tailscaleIdentity && !config.tailscaleSocket) throw new Error("Tailscale connection is unavailable");
if (config.tailscaleSocket) {
if (!net.isIP(config.host) && !/^[A-Za-z0-9][A-Za-z0-9_.-]*$/.test(config.host)) throw new Error("Invalid Tailscale host");
if (!/^\/[A-Za-z0-9_./-]+$/.test(config.tailscaleSocket)) throw new Error("Invalid Tailscale socket path");
const configuredCli = process.env.PAPERCLIP_TAILSCALE_CLI?.trim();
const cli = configuredCli ? shellQuote(configuredCli).replaceAll("%", "%%") : "tailscale";
sshArgs.push("-o", `ProxyCommand=${cli} --socket=${config.tailscaleSocket} nc %h %p`);
}
if (config.strictHostKeyChecking) {
if (config.knownHosts) {
const knownHosts = await withTempFile("paperclip-ssh-known-hosts-", config.knownHosts, 0o600);
@@ -0,0 +1,17 @@
CREATE TABLE "tailscale_connections" (
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
"company_id" uuid NOT NULL,
"name" text NOT NULL,
"status" text DEFAULT 'pending' NOT NULL,
"secret_id" uuid,
"created_by_user_id" text NOT NULL,
"oauth_state_hash" text,
"oauth_expires_at" timestamp with time zone,
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
"updated_at" timestamp with time zone DEFAULT now() NOT NULL
);
--> statement-breakpoint
ALTER TABLE "tailscale_connections" ADD CONSTRAINT "tailscale_connections_company_id_companies_id_fk" FOREIGN KEY ("company_id") REFERENCES "public"."companies"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
ALTER TABLE "tailscale_connections" ADD CONSTRAINT "tailscale_connections_secret_id_company_secrets_id_fk" FOREIGN KEY ("secret_id") REFERENCES "public"."company_secrets"("id") ON DELETE no action ON UPDATE no action;--> statement-breakpoint
CREATE INDEX "tailscale_connections_company_idx" ON "tailscale_connections" USING btree ("company_id");--> statement-breakpoint
CREATE UNIQUE INDEX "tailscale_connections_oauth_state_idx" ON "tailscale_connections" USING btree ("oauth_state_hash");
@@ -0,0 +1,2 @@
ALTER TABLE "tailscale_connections" ADD COLUMN "credential_version" integer;--> statement-breakpoint
ALTER TABLE "tailscale_connections" ADD COLUMN "credential_hash" text;
@@ -0,0 +1,7 @@
-- paperclip:migration-compat online_compatible: Nullable metadata ignored by older releases; backfill touches only connector-referenced secret rows through their primary keys.
ALTER TABLE "company_secrets" ADD COLUMN "system_purpose" text;
--> statement-breakpoint
UPDATE "company_secrets" AS secret
SET "system_purpose" = 'tailscale_network'
FROM "tailscale_connections" AS connection
WHERE secret.id = connection.secret_id AND secret.company_id = connection.company_id;
@@ -1,6 +1,6 @@
{
"id": "d5d69127-12de-4281-9816-c20e013bfeb7",
"prevId": "82dcdc57-0796-4162-9451-8ea08a72199e",
"id": "55a8c37c-453c-4be4-b657-b703932836a0",
"prevId": "f5f852bd-0568-4b2d-bc35-0dac5d9c8c5b",
"version": "7",
"dialect": "postgresql",
"tables": {
@@ -35261,6 +35261,12 @@
"notNull": true,
"default": 1
},
"native_source_cursors": {
"name": "native_source_cursors",
"type": "jsonb",
"primaryKey": false,
"notNull": false
},
"native_phase": {
"name": "native_phase",
"type": "text",
@@ -55947,6 +55953,141 @@
"checkConstraints": {},
"isRLSEnabled": false
},
"public.tailscale_connections": {
"name": "tailscale_connections",
"schema": "",
"columns": {
"id": {
"name": "id",
"type": "uuid",
"primaryKey": true,
"notNull": true,
"default": "gen_random_uuid()"
},
"company_id": {
"name": "company_id",
"type": "uuid",
"primaryKey": false,
"notNull": true
},
"name": {
"name": "name",
"type": "text",
"primaryKey": false,
"notNull": true
},
"status": {
"name": "status",
"type": "text",
"primaryKey": false,
"notNull": true,
"default": "'pending'"
},
"secret_id": {
"name": "secret_id",
"type": "uuid",
"primaryKey": false,
"notNull": false
},
"created_by_user_id": {
"name": "created_by_user_id",
"type": "text",
"primaryKey": false,
"notNull": true
},
"oauth_state_hash": {
"name": "oauth_state_hash",
"type": "text",
"primaryKey": false,
"notNull": false
},
"oauth_expires_at": {
"name": "oauth_expires_at",
"type": "timestamp with time zone",
"primaryKey": false,
"notNull": false
},
"created_at": {
"name": "created_at",
"type": "timestamp with time zone",
"primaryKey": false,
"notNull": true,
"default": "now()"
},
"updated_at": {
"name": "updated_at",
"type": "timestamp with time zone",
"primaryKey": false,
"notNull": true,
"default": "now()"
}
},
"indexes": {
"tailscale_connections_company_idx": {
"name": "tailscale_connections_company_idx",
"columns": [
{
"expression": "company_id",
"isExpression": false,
"asc": true,
"nulls": "last"
}
],
"isUnique": false,
"concurrently": false,
"method": "btree",
"with": {}
},
"tailscale_connections_oauth_state_idx": {
"name": "tailscale_connections_oauth_state_idx",
"columns": [
{
"expression": "oauth_state_hash",
"isExpression": false,
"asc": true,
"nulls": "last"
}
],
"isUnique": true,
"concurrently": false,
"method": "btree",
"with": {}
}
},
"foreignKeys": {
"tailscale_connections_company_id_companies_id_fk": {
"name": "tailscale_connections_company_id_companies_id_fk",
"tableFrom": "tailscale_connections",
"tableTo": "companies",
"columnsFrom": [
"company_id"
],
"columnsTo": [
"id"
],
"onDelete": "cascade",
"onUpdate": "no action"
},
"tailscale_connections_secret_id_company_secrets_id_fk": {
"name": "tailscale_connections_secret_id_company_secrets_id_fk",
"tableFrom": "tailscale_connections",
"tableTo": "company_secrets",
"columnsFrom": [
"secret_id"
],
"columnsTo": [
"id"
],
"onDelete": "no action",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"policies": {},
"checkConstraints": {},
"isRLSEnabled": false
},
"public.tool_access_audit_events": {
"name": "tool_access_audit_events",
"schema": "",
@@ -60996,6 +61137,392 @@
"checkConstraints": {},
"isRLSEnabled": false
},
"public.tool_mcp_tasks": {
"name": "tool_mcp_tasks",
"schema": "",
"columns": {
"id": {
"name": "id",
"type": "uuid",
"primaryKey": true,
"notNull": true,
"default": "gen_random_uuid()"
},
"company_id": {
"name": "company_id",
"type": "uuid",
"primaryKey": false,
"notNull": true
},
"invocation_id": {
"name": "invocation_id",
"type": "uuid",
"primaryKey": false,
"notNull": true
},
"connection_id": {
"name": "connection_id",
"type": "uuid",
"primaryKey": false,
"notNull": true
},
"grant_id": {
"name": "grant_id",
"type": "uuid",
"primaryKey": false,
"notNull": true
},
"agent_id": {
"name": "agent_id",
"type": "uuid",
"primaryKey": false,
"notNull": false
},
"issue_id": {
"name": "issue_id",
"type": "uuid",
"primaryKey": false,
"notNull": false
},
"run_id": {
"name": "run_id",
"type": "uuid",
"primaryKey": false,
"notNull": false
},
"actor_type": {
"name": "actor_type",
"type": "text",
"primaryKey": false,
"notNull": true
},
"actor_id": {
"name": "actor_id",
"type": "text",
"primaryKey": false,
"notNull": false
},
"responsible_user_id": {
"name": "responsible_user_id",
"type": "text",
"primaryKey": false,
"notNull": false
},
"identity_context_id": {
"name": "identity_context_id",
"type": "uuid",
"primaryKey": false,
"notNull": false
},
"catalog_tool_name": {
"name": "catalog_tool_name",
"type": "text",
"primaryKey": false,
"notNull": true
},
"request_hash": {
"name": "request_hash",
"type": "text",
"primaryKey": false,
"notNull": true
},
"endpoint_hash": {
"name": "endpoint_hash",
"type": "text",
"primaryKey": false,
"notNull": true
},
"sealed_caller_headers": {
"name": "sealed_caller_headers",
"type": "text",
"primaryKey": false,
"notNull": false
},
"protocol_version": {
"name": "protocol_version",
"type": "text",
"primaryKey": false,
"notNull": true
},
"sealed_provider_task_id": {
"name": "sealed_provider_task_id",
"type": "text",
"primaryKey": false,
"notNull": true
},
"provider_task_id_hash": {
"name": "provider_task_id_hash",
"type": "text",
"primaryKey": false,
"notNull": true
},
"status": {
"name": "status",
"type": "text",
"primaryKey": false,
"notNull": true
},
"poll_interval_ms": {
"name": "poll_interval_ms",
"type": "integer",
"primaryKey": false,
"notNull": false
},
"ttl_ms": {
"name": "ttl_ms",
"type": "integer",
"primaryKey": false,
"notNull": false
},
"expires_at": {
"name": "expires_at",
"type": "timestamp with time zone",
"primaryKey": false,
"notNull": true
},
"next_poll_at": {
"name": "next_poll_at",
"type": "timestamp with time zone",
"primaryKey": false,
"notNull": false
},
"last_polled_at": {
"name": "last_polled_at",
"type": "timestamp with time zone",
"primaryKey": false,
"notNull": false
},
"poll_failures": {
"name": "poll_failures",
"type": "integer",
"primaryKey": false,
"notNull": true,
"default": 0
},
"lease_expires_at": {
"name": "lease_expires_at",
"type": "timestamp with time zone",
"primaryKey": false,
"notNull": false
},
"lease_owner": {
"name": "lease_owner",
"type": "text",
"primaryKey": false,
"notNull": false
},
"arguments_identity": {
"name": "arguments_identity",
"type": "text",
"primaryKey": false,
"notNull": true
},
"answered_input_keys": {
"name": "answered_input_keys",
"type": "jsonb",
"primaryKey": false,
"notNull": true,
"default": "'[]'::jsonb"
},
"surfaced_input_keys": {
"name": "surfaced_input_keys",
"type": "jsonb",
"primaryKey": false,
"notNull": true,
"default": "'[]'::jsonb"
},
"input_wake_count": {
"name": "input_wake_count",
"type": "integer",
"primaryKey": false,
"notNull": true,
"default": 0
},
"input_wake_at": {
"name": "input_wake_at",
"type": "timestamp with time zone",
"primaryKey": false,
"notNull": false
},
"error_code": {
"name": "error_code",
"type": "text",
"primaryKey": false,
"notNull": false
},
"wake_requested_at": {
"name": "wake_requested_at",
"type": "timestamp with time zone",
"primaryKey": false,
"notNull": false
},
"delivered_at": {
"name": "delivered_at",
"type": "timestamp with time zone",
"primaryKey": false,
"notNull": false
},
"last_invocation_id": {
"name": "last_invocation_id",
"type": "uuid",
"primaryKey": false,
"notNull": false
},
"created_at": {
"name": "created_at",
"type": "timestamp with time zone",
"primaryKey": false,
"notNull": true,
"default": "now()"
},
"updated_at": {
"name": "updated_at",
"type": "timestamp with time zone",
"primaryKey": false,
"notNull": true,
"default": "now()"
}
},
"indexes": {
"tool_mcp_tasks_provider_task_uq": {
"name": "tool_mcp_tasks_provider_task_uq",
"columns": [
{
"expression": "company_id",
"isExpression": false,
"asc": true,
"nulls": "last"
},
{
"expression": "connection_id",
"isExpression": false,
"asc": true,
"nulls": "last"
},
{
"expression": "provider_task_id_hash",
"isExpression": false,
"asc": true,
"nulls": "last"
}
],
"isUnique": true,
"concurrently": false,
"method": "btree",
"with": {}
},
"tool_mcp_tasks_attach_idx": {
"name": "tool_mcp_tasks_attach_idx",
"columns": [
{
"expression": "company_id",
"isExpression": false,
"asc": true,
"nulls": "last"
},
{
"expression": "connection_id",
"isExpression": false,
"asc": true,
"nulls": "last"
},
{
"expression": "request_hash",
"isExpression": false,
"asc": true,
"nulls": "last"
}
],
"isUnique": false,
"concurrently": false,
"method": "btree",
"with": {}
},
"tool_mcp_tasks_invocation_idx": {
"name": "tool_mcp_tasks_invocation_idx",
"columns": [
{
"expression": "company_id",
"isExpression": false,
"asc": true,
"nulls": "last"
},
{
"expression": "invocation_id",
"isExpression": false,
"asc": true,
"nulls": "last"
}
],
"isUnique": false,
"concurrently": false,
"method": "btree",
"with": {}
},
"tool_mcp_tasks_next_poll_idx": {
"name": "tool_mcp_tasks_next_poll_idx",
"columns": [
{
"expression": "next_poll_at",
"isExpression": false,
"asc": true,
"nulls": "last"
}
],
"isUnique": false,
"where": "\"tool_mcp_tasks\".\"next_poll_at\" is not null",
"concurrently": false,
"method": "btree",
"with": {}
}
},
"foreignKeys": {
"tool_mcp_tasks_company_id_companies_id_fk": {
"name": "tool_mcp_tasks_company_id_companies_id_fk",
"tableFrom": "tool_mcp_tasks",
"tableTo": "companies",
"columnsFrom": [
"company_id"
],
"columnsTo": [
"id"
],
"onDelete": "cascade",
"onUpdate": "no action"
},
"tool_mcp_tasks_invocation_id_tool_invocations_id_fk": {
"name": "tool_mcp_tasks_invocation_id_tool_invocations_id_fk",
"tableFrom": "tool_mcp_tasks",
"tableTo": "tool_invocations",
"columnsFrom": [
"invocation_id"
],
"columnsTo": [
"id"
],
"onDelete": "cascade",
"onUpdate": "no action"
},
"tool_mcp_tasks_connection_id_tool_connections_id_fk": {
"name": "tool_mcp_tasks_connection_id_tool_connections_id_fk",
"tableFrom": "tool_mcp_tasks",
"tableTo": "tool_connections",
"columnsFrom": [
"connection_id"
],
"columnsTo": [
"id"
],
"onDelete": "cascade",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"policies": {},
"checkConstraints": {},
"isRLSEnabled": false
},
"public.tool_oauth_states": {
"name": "tool_oauth_states",
"schema": "",
@@ -1,6 +1,6 @@
{
"id": "82dcdc57-0796-4162-9451-8ea08a72199e",
"prevId": "ee1f1f66-0cbe-4b18-b364-5e96708a1f0b",
"id": "41eacc6a-6eab-4f01-965a-62aa0cd6778f",
"prevId": "55a8c37c-453c-4be4-b657-b703932836a0",
"version": "7",
"dialect": "postgresql",
"tables": {
@@ -35261,6 +35261,12 @@
"notNull": true,
"default": 1
},
"native_source_cursors": {
"name": "native_source_cursors",
"type": "jsonb",
"primaryKey": false,
"notNull": false
},
"native_phase": {
"name": "native_phase",
"type": "text",
@@ -55947,6 +55953,153 @@
"checkConstraints": {},
"isRLSEnabled": false
},
"public.tailscale_connections": {
"name": "tailscale_connections",
"schema": "",
"columns": {
"id": {
"name": "id",
"type": "uuid",
"primaryKey": true,
"notNull": true,
"default": "gen_random_uuid()"
},
"company_id": {
"name": "company_id",
"type": "uuid",
"primaryKey": false,
"notNull": true
},
"name": {
"name": "name",
"type": "text",
"primaryKey": false,
"notNull": true
},
"status": {
"name": "status",
"type": "text",
"primaryKey": false,
"notNull": true,
"default": "'pending'"
},
"secret_id": {
"name": "secret_id",
"type": "uuid",
"primaryKey": false,
"notNull": false
},
"credential_version": {
"name": "credential_version",
"type": "integer",
"primaryKey": false,
"notNull": false
},
"credential_hash": {
"name": "credential_hash",
"type": "text",
"primaryKey": false,
"notNull": false
},
"created_by_user_id": {
"name": "created_by_user_id",
"type": "text",
"primaryKey": false,
"notNull": true
},
"oauth_state_hash": {
"name": "oauth_state_hash",
"type": "text",
"primaryKey": false,
"notNull": false
},
"oauth_expires_at": {
"name": "oauth_expires_at",
"type": "timestamp with time zone",
"primaryKey": false,
"notNull": false
},
"created_at": {
"name": "created_at",
"type": "timestamp with time zone",
"primaryKey": false,
"notNull": true,
"default": "now()"
},
"updated_at": {
"name": "updated_at",
"type": "timestamp with time zone",
"primaryKey": false,
"notNull": true,
"default": "now()"
}
},
"indexes": {
"tailscale_connections_company_idx": {
"name": "tailscale_connections_company_idx",
"columns": [
{
"expression": "company_id",
"isExpression": false,
"asc": true,
"nulls": "last"
}
],
"isUnique": false,
"concurrently": false,
"method": "btree",
"with": {}
},
"tailscale_connections_oauth_state_idx": {
"name": "tailscale_connections_oauth_state_idx",
"columns": [
{
"expression": "oauth_state_hash",
"isExpression": false,
"asc": true,
"nulls": "last"
}
],
"isUnique": true,
"concurrently": false,
"method": "btree",
"with": {}
}
},
"foreignKeys": {
"tailscale_connections_company_id_companies_id_fk": {
"name": "tailscale_connections_company_id_companies_id_fk",
"tableFrom": "tailscale_connections",
"tableTo": "companies",
"columnsFrom": [
"company_id"
],
"columnsTo": [
"id"
],
"onDelete": "cascade",
"onUpdate": "no action"
},
"tailscale_connections_secret_id_company_secrets_id_fk": {
"name": "tailscale_connections_secret_id_company_secrets_id_fk",
"tableFrom": "tailscale_connections",
"tableTo": "company_secrets",
"columnsFrom": [
"secret_id"
],
"columnsTo": [
"id"
],
"onDelete": "no action",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"policies": {},
"checkConstraints": {},
"isRLSEnabled": false
},
"public.tool_access_audit_events": {
"name": "tool_access_audit_events",
"schema": "",
@@ -57564,6 +57717,12 @@
"primaryKey": false,
"notNull": false
},
"icons": {
"name": "icons",
"type": "jsonb",
"primaryKey": false,
"notNull": false
},
"risk_level": {
"name": "risk_level",
"type": "text",
@@ -59785,6 +59944,18 @@
"primaryKey": false,
"notNull": true
},
"model_context": {
"name": "model_context",
"type": "jsonb",
"primaryKey": false,
"notNull": false
},
"model_context_updated_at": {
"name": "model_context_updated_at",
"type": "timestamp with time zone",
"primaryKey": false,
"notNull": false
},
"created_at": {
"name": "created_at",
"type": "timestamp with time zone",
@@ -60978,6 +61149,392 @@
"checkConstraints": {},
"isRLSEnabled": false
},
"public.tool_mcp_tasks": {
"name": "tool_mcp_tasks",
"schema": "",
"columns": {
"id": {
"name": "id",
"type": "uuid",
"primaryKey": true,
"notNull": true,
"default": "gen_random_uuid()"
},
"company_id": {
"name": "company_id",
"type": "uuid",
"primaryKey": false,
"notNull": true
},
"invocation_id": {
"name": "invocation_id",
"type": "uuid",
"primaryKey": false,
"notNull": true
},
"connection_id": {
"name": "connection_id",
"type": "uuid",
"primaryKey": false,
"notNull": true
},
"grant_id": {
"name": "grant_id",
"type": "uuid",
"primaryKey": false,
"notNull": true
},
"agent_id": {
"name": "agent_id",
"type": "uuid",
"primaryKey": false,
"notNull": false
},
"issue_id": {
"name": "issue_id",
"type": "uuid",
"primaryKey": false,
"notNull": false
},
"run_id": {
"name": "run_id",
"type": "uuid",
"primaryKey": false,
"notNull": false
},
"actor_type": {
"name": "actor_type",
"type": "text",
"primaryKey": false,
"notNull": true
},
"actor_id": {
"name": "actor_id",
"type": "text",
"primaryKey": false,
"notNull": false
},
"responsible_user_id": {
"name": "responsible_user_id",
"type": "text",
"primaryKey": false,
"notNull": false
},
"identity_context_id": {
"name": "identity_context_id",
"type": "uuid",
"primaryKey": false,
"notNull": false
},
"catalog_tool_name": {
"name": "catalog_tool_name",
"type": "text",
"primaryKey": false,
"notNull": true
},
"request_hash": {
"name": "request_hash",
"type": "text",
"primaryKey": false,
"notNull": true
},
"endpoint_hash": {
"name": "endpoint_hash",
"type": "text",
"primaryKey": false,
"notNull": true
},
"sealed_caller_headers": {
"name": "sealed_caller_headers",
"type": "text",
"primaryKey": false,
"notNull": false
},
"protocol_version": {
"name": "protocol_version",
"type": "text",
"primaryKey": false,
"notNull": true
},
"sealed_provider_task_id": {
"name": "sealed_provider_task_id",
"type": "text",
"primaryKey": false,
"notNull": true
},
"provider_task_id_hash": {
"name": "provider_task_id_hash",
"type": "text",
"primaryKey": false,
"notNull": true
},
"status": {
"name": "status",
"type": "text",
"primaryKey": false,
"notNull": true
},
"poll_interval_ms": {
"name": "poll_interval_ms",
"type": "integer",
"primaryKey": false,
"notNull": false
},
"ttl_ms": {
"name": "ttl_ms",
"type": "integer",
"primaryKey": false,
"notNull": false
},
"expires_at": {
"name": "expires_at",
"type": "timestamp with time zone",
"primaryKey": false,
"notNull": true
},
"next_poll_at": {
"name": "next_poll_at",
"type": "timestamp with time zone",
"primaryKey": false,
"notNull": false
},
"last_polled_at": {
"name": "last_polled_at",
"type": "timestamp with time zone",
"primaryKey": false,
"notNull": false
},
"poll_failures": {
"name": "poll_failures",
"type": "integer",
"primaryKey": false,
"notNull": true,
"default": 0
},
"lease_expires_at": {
"name": "lease_expires_at",
"type": "timestamp with time zone",
"primaryKey": false,
"notNull": false
},
"lease_owner": {
"name": "lease_owner",
"type": "text",
"primaryKey": false,
"notNull": false
},
"arguments_identity": {
"name": "arguments_identity",
"type": "text",
"primaryKey": false,
"notNull": true
},
"answered_input_keys": {
"name": "answered_input_keys",
"type": "jsonb",
"primaryKey": false,
"notNull": true,
"default": "'[]'::jsonb"
},
"surfaced_input_keys": {
"name": "surfaced_input_keys",
"type": "jsonb",
"primaryKey": false,
"notNull": true,
"default": "'[]'::jsonb"
},
"input_wake_count": {
"name": "input_wake_count",
"type": "integer",
"primaryKey": false,
"notNull": true,
"default": 0
},
"input_wake_at": {
"name": "input_wake_at",
"type": "timestamp with time zone",
"primaryKey": false,
"notNull": false
},
"error_code": {
"name": "error_code",
"type": "text",
"primaryKey": false,
"notNull": false
},
"wake_requested_at": {
"name": "wake_requested_at",
"type": "timestamp with time zone",
"primaryKey": false,
"notNull": false
},
"delivered_at": {
"name": "delivered_at",
"type": "timestamp with time zone",
"primaryKey": false,
"notNull": false
},
"last_invocation_id": {
"name": "last_invocation_id",
"type": "uuid",
"primaryKey": false,
"notNull": false
},
"created_at": {
"name": "created_at",
"type": "timestamp with time zone",
"primaryKey": false,
"notNull": true,
"default": "now()"
},
"updated_at": {
"name": "updated_at",
"type": "timestamp with time zone",
"primaryKey": false,
"notNull": true,
"default": "now()"
}
},
"indexes": {
"tool_mcp_tasks_provider_task_uq": {
"name": "tool_mcp_tasks_provider_task_uq",
"columns": [
{
"expression": "company_id",
"isExpression": false,
"asc": true,
"nulls": "last"
},
{
"expression": "connection_id",
"isExpression": false,
"asc": true,
"nulls": "last"
},
{
"expression": "provider_task_id_hash",
"isExpression": false,
"asc": true,
"nulls": "last"
}
],
"isUnique": true,
"concurrently": false,
"method": "btree",
"with": {}
},
"tool_mcp_tasks_attach_idx": {
"name": "tool_mcp_tasks_attach_idx",
"columns": [
{
"expression": "company_id",
"isExpression": false,
"asc": true,
"nulls": "last"
},
{
"expression": "connection_id",
"isExpression": false,
"asc": true,
"nulls": "last"
},
{
"expression": "request_hash",
"isExpression": false,
"asc": true,
"nulls": "last"
}
],
"isUnique": false,
"concurrently": false,
"method": "btree",
"with": {}
},
"tool_mcp_tasks_invocation_idx": {
"name": "tool_mcp_tasks_invocation_idx",
"columns": [
{
"expression": "company_id",
"isExpression": false,
"asc": true,
"nulls": "last"
},
{
"expression": "invocation_id",
"isExpression": false,
"asc": true,
"nulls": "last"
}
],
"isUnique": false,
"concurrently": false,
"method": "btree",
"with": {}
},
"tool_mcp_tasks_next_poll_idx": {
"name": "tool_mcp_tasks_next_poll_idx",
"columns": [
{
"expression": "next_poll_at",
"isExpression": false,
"asc": true,
"nulls": "last"
}
],
"isUnique": false,
"where": "\"tool_mcp_tasks\".\"next_poll_at\" is not null",
"concurrently": false,
"method": "btree",
"with": {}
}
},
"foreignKeys": {
"tool_mcp_tasks_company_id_companies_id_fk": {
"name": "tool_mcp_tasks_company_id_companies_id_fk",
"tableFrom": "tool_mcp_tasks",
"tableTo": "companies",
"columnsFrom": [
"company_id"
],
"columnsTo": [
"id"
],
"onDelete": "cascade",
"onUpdate": "no action"
},
"tool_mcp_tasks_invocation_id_tool_invocations_id_fk": {
"name": "tool_mcp_tasks_invocation_id_tool_invocations_id_fk",
"tableFrom": "tool_mcp_tasks",
"tableTo": "tool_invocations",
"columnsFrom": [
"invocation_id"
],
"columnsTo": [
"id"
],
"onDelete": "cascade",
"onUpdate": "no action"
},
"tool_mcp_tasks_connection_id_tool_connections_id_fk": {
"name": "tool_mcp_tasks_connection_id_tool_connections_id_fk",
"tableFrom": "tool_mcp_tasks",
"tableTo": "tool_connections",
"columnsFrom": [
"connection_id"
],
"columnsTo": [
"id"
],
"onDelete": "cascade",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"policies": {},
"checkConstraints": {},
"isRLSEnabled": false
},
"public.tool_oauth_states": {
"name": "tool_oauth_states",
"schema": "",
@@ -1,6 +1,6 @@
{
"id": "ee1f1f66-0cbe-4b18-b364-5e96708a1f0b",
"prevId": "a7108924-4d75-41e2-9139-f43f9396c02d",
"id": "8b353a38-62df-4834-be55-7e9ebefad5c5",
"prevId": "41eacc6a-6eab-4f01-965a-62aa0cd6778f",
"version": "7",
"dialect": "postgresql",
"tables": {
@@ -3954,6 +3954,28 @@
"method": "btree",
"with": {}
},
"agent_wakeup_requests_company_run_idx": {
"name": "agent_wakeup_requests_company_run_idx",
"columns": [
{
"expression": "company_id",
"isExpression": false,
"asc": true,
"nulls": "last"
},
{
"expression": "run_id",
"isExpression": false,
"asc": true,
"nulls": "last"
}
],
"isUnique": false,
"where": "\"agent_wakeup_requests\".\"run_id\" IS NOT NULL",
"concurrently": true,
"method": "btree",
"with": {}
},
"agent_wakeup_requests_review_path_recovery_idempotency_uq": {
"name": "agent_wakeup_requests_review_path_recovery_idempotency_uq",
"columns": [
@@ -18070,6 +18092,12 @@
"notNull": true,
"default": "'company'"
},
"system_purpose": {
"name": "system_purpose",
"type": "text",
"primaryKey": false,
"notNull": false
},
"owner_user_id": {
"name": "owner_user_id",
"type": "text",
@@ -35239,6 +35267,12 @@
"notNull": true,
"default": 1
},
"native_source_cursors": {
"name": "native_source_cursors",
"type": "jsonb",
"primaryKey": false,
"notNull": false
},
"native_phase": {
"name": "native_phase",
"type": "text",
@@ -55925,6 +55959,153 @@
"checkConstraints": {},
"isRLSEnabled": false
},
"public.tailscale_connections": {
"name": "tailscale_connections",
"schema": "",
"columns": {
"id": {
"name": "id",
"type": "uuid",
"primaryKey": true,
"notNull": true,
"default": "gen_random_uuid()"
},
"company_id": {
"name": "company_id",
"type": "uuid",
"primaryKey": false,
"notNull": true
},
"name": {
"name": "name",
"type": "text",
"primaryKey": false,
"notNull": true
},
"status": {
"name": "status",
"type": "text",
"primaryKey": false,
"notNull": true,
"default": "'pending'"
},
"secret_id": {
"name": "secret_id",
"type": "uuid",
"primaryKey": false,
"notNull": false
},
"credential_version": {
"name": "credential_version",
"type": "integer",
"primaryKey": false,
"notNull": false
},
"credential_hash": {
"name": "credential_hash",
"type": "text",
"primaryKey": false,
"notNull": false
},
"created_by_user_id": {
"name": "created_by_user_id",
"type": "text",
"primaryKey": false,
"notNull": true
},
"oauth_state_hash": {
"name": "oauth_state_hash",
"type": "text",
"primaryKey": false,
"notNull": false
},
"oauth_expires_at": {
"name": "oauth_expires_at",
"type": "timestamp with time zone",
"primaryKey": false,
"notNull": false
},
"created_at": {
"name": "created_at",
"type": "timestamp with time zone",
"primaryKey": false,
"notNull": true,
"default": "now()"
},
"updated_at": {
"name": "updated_at",
"type": "timestamp with time zone",
"primaryKey": false,
"notNull": true,
"default": "now()"
}
},
"indexes": {
"tailscale_connections_company_idx": {
"name": "tailscale_connections_company_idx",
"columns": [
{
"expression": "company_id",
"isExpression": false,
"asc": true,
"nulls": "last"
}
],
"isUnique": false,
"concurrently": false,
"method": "btree",
"with": {}
},
"tailscale_connections_oauth_state_idx": {
"name": "tailscale_connections_oauth_state_idx",
"columns": [
{
"expression": "oauth_state_hash",
"isExpression": false,
"asc": true,
"nulls": "last"
}
],
"isUnique": true,
"concurrently": false,
"method": "btree",
"with": {}
}
},
"foreignKeys": {
"tailscale_connections_company_id_companies_id_fk": {
"name": "tailscale_connections_company_id_companies_id_fk",
"tableFrom": "tailscale_connections",
"tableTo": "companies",
"columnsFrom": [
"company_id"
],
"columnsTo": [
"id"
],
"onDelete": "cascade",
"onUpdate": "no action"
},
"tailscale_connections_secret_id_company_secrets_id_fk": {
"name": "tailscale_connections_secret_id_company_secrets_id_fk",
"tableFrom": "tailscale_connections",
"tableTo": "company_secrets",
"columnsFrom": [
"secret_id"
],
"columnsTo": [
"id"
],
"onDelete": "no action",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"policies": {},
"checkConstraints": {},
"isRLSEnabled": false
},
"public.tool_access_audit_events": {
"name": "tool_access_audit_events",
"schema": "",
@@ -57542,6 +57723,12 @@
"primaryKey": false,
"notNull": false
},
"icons": {
"name": "icons",
"type": "jsonb",
"primaryKey": false,
"notNull": false
},
"risk_level": {
"name": "risk_level",
"type": "text",
@@ -59763,6 +59950,18 @@
"primaryKey": false,
"notNull": true
},
"model_context": {
"name": "model_context",
"type": "jsonb",
"primaryKey": false,
"notNull": false
},
"model_context_updated_at": {
"name": "model_context_updated_at",
"type": "timestamp with time zone",
"primaryKey": false,
"notNull": false
},
"created_at": {
"name": "created_at",
"type": "timestamp with time zone",
@@ -60956,6 +61155,392 @@
"checkConstraints": {},
"isRLSEnabled": false
},
"public.tool_mcp_tasks": {
"name": "tool_mcp_tasks",
"schema": "",
"columns": {
"id": {
"name": "id",
"type": "uuid",
"primaryKey": true,
"notNull": true,
"default": "gen_random_uuid()"
},
"company_id": {
"name": "company_id",
"type": "uuid",
"primaryKey": false,
"notNull": true
},
"invocation_id": {
"name": "invocation_id",
"type": "uuid",
"primaryKey": false,
"notNull": true
},
"connection_id": {
"name": "connection_id",
"type": "uuid",
"primaryKey": false,
"notNull": true
},
"grant_id": {
"name": "grant_id",
"type": "uuid",
"primaryKey": false,
"notNull": true
},
"agent_id": {
"name": "agent_id",
"type": "uuid",
"primaryKey": false,
"notNull": false
},
"issue_id": {
"name": "issue_id",
"type": "uuid",
"primaryKey": false,
"notNull": false
},
"run_id": {
"name": "run_id",
"type": "uuid",
"primaryKey": false,
"notNull": false
},
"actor_type": {
"name": "actor_type",
"type": "text",
"primaryKey": false,
"notNull": true
},
"actor_id": {
"name": "actor_id",
"type": "text",
"primaryKey": false,
"notNull": false
},
"responsible_user_id": {
"name": "responsible_user_id",
"type": "text",
"primaryKey": false,
"notNull": false
},
"identity_context_id": {
"name": "identity_context_id",
"type": "uuid",
"primaryKey": false,
"notNull": false
},
"catalog_tool_name": {
"name": "catalog_tool_name",
"type": "text",
"primaryKey": false,
"notNull": true
},
"request_hash": {
"name": "request_hash",
"type": "text",
"primaryKey": false,
"notNull": true
},
"endpoint_hash": {
"name": "endpoint_hash",
"type": "text",
"primaryKey": false,
"notNull": true
},
"sealed_caller_headers": {
"name": "sealed_caller_headers",
"type": "text",
"primaryKey": false,
"notNull": false
},
"protocol_version": {
"name": "protocol_version",
"type": "text",
"primaryKey": false,
"notNull": true
},
"sealed_provider_task_id": {
"name": "sealed_provider_task_id",
"type": "text",
"primaryKey": false,
"notNull": true
},
"provider_task_id_hash": {
"name": "provider_task_id_hash",
"type": "text",
"primaryKey": false,
"notNull": true
},
"status": {
"name": "status",
"type": "text",
"primaryKey": false,
"notNull": true
},
"poll_interval_ms": {
"name": "poll_interval_ms",
"type": "integer",
"primaryKey": false,
"notNull": false
},
"ttl_ms": {
"name": "ttl_ms",
"type": "integer",
"primaryKey": false,
"notNull": false
},
"expires_at": {
"name": "expires_at",
"type": "timestamp with time zone",
"primaryKey": false,
"notNull": true
},
"next_poll_at": {
"name": "next_poll_at",
"type": "timestamp with time zone",
"primaryKey": false,
"notNull": false
},
"last_polled_at": {
"name": "last_polled_at",
"type": "timestamp with time zone",
"primaryKey": false,
"notNull": false
},
"poll_failures": {
"name": "poll_failures",
"type": "integer",
"primaryKey": false,
"notNull": true,
"default": 0
},
"lease_expires_at": {
"name": "lease_expires_at",
"type": "timestamp with time zone",
"primaryKey": false,
"notNull": false
},
"lease_owner": {
"name": "lease_owner",
"type": "text",
"primaryKey": false,
"notNull": false
},
"arguments_identity": {
"name": "arguments_identity",
"type": "text",
"primaryKey": false,
"notNull": true
},
"answered_input_keys": {
"name": "answered_input_keys",
"type": "jsonb",
"primaryKey": false,
"notNull": true,
"default": "'[]'::jsonb"
},
"surfaced_input_keys": {
"name": "surfaced_input_keys",
"type": "jsonb",
"primaryKey": false,
"notNull": true,
"default": "'[]'::jsonb"
},
"input_wake_count": {
"name": "input_wake_count",
"type": "integer",
"primaryKey": false,
"notNull": true,
"default": 0
},
"input_wake_at": {
"name": "input_wake_at",
"type": "timestamp with time zone",
"primaryKey": false,
"notNull": false
},
"error_code": {
"name": "error_code",
"type": "text",
"primaryKey": false,
"notNull": false
},
"wake_requested_at": {
"name": "wake_requested_at",
"type": "timestamp with time zone",
"primaryKey": false,
"notNull": false
},
"delivered_at": {
"name": "delivered_at",
"type": "timestamp with time zone",
"primaryKey": false,
"notNull": false
},
"last_invocation_id": {
"name": "last_invocation_id",
"type": "uuid",
"primaryKey": false,
"notNull": false
},
"created_at": {
"name": "created_at",
"type": "timestamp with time zone",
"primaryKey": false,
"notNull": true,
"default": "now()"
},
"updated_at": {
"name": "updated_at",
"type": "timestamp with time zone",
"primaryKey": false,
"notNull": true,
"default": "now()"
}
},
"indexes": {
"tool_mcp_tasks_provider_task_uq": {
"name": "tool_mcp_tasks_provider_task_uq",
"columns": [
{
"expression": "company_id",
"isExpression": false,
"asc": true,
"nulls": "last"
},
{
"expression": "connection_id",
"isExpression": false,
"asc": true,
"nulls": "last"
},
{
"expression": "provider_task_id_hash",
"isExpression": false,
"asc": true,
"nulls": "last"
}
],
"isUnique": true,
"concurrently": false,
"method": "btree",
"with": {}
},
"tool_mcp_tasks_attach_idx": {
"name": "tool_mcp_tasks_attach_idx",
"columns": [
{
"expression": "company_id",
"isExpression": false,
"asc": true,
"nulls": "last"
},
{
"expression": "connection_id",
"isExpression": false,
"asc": true,
"nulls": "last"
},
{
"expression": "request_hash",
"isExpression": false,
"asc": true,
"nulls": "last"
}
],
"isUnique": false,
"concurrently": false,
"method": "btree",
"with": {}
},
"tool_mcp_tasks_invocation_idx": {
"name": "tool_mcp_tasks_invocation_idx",
"columns": [
{
"expression": "company_id",
"isExpression": false,
"asc": true,
"nulls": "last"
},
{
"expression": "invocation_id",
"isExpression": false,
"asc": true,
"nulls": "last"
}
],
"isUnique": false,
"concurrently": false,
"method": "btree",
"with": {}
},
"tool_mcp_tasks_next_poll_idx": {
"name": "tool_mcp_tasks_next_poll_idx",
"columns": [
{
"expression": "next_poll_at",
"isExpression": false,
"asc": true,
"nulls": "last"
}
],
"isUnique": false,
"where": "\"tool_mcp_tasks\".\"next_poll_at\" is not null",
"concurrently": false,
"method": "btree",
"with": {}
}
},
"foreignKeys": {
"tool_mcp_tasks_company_id_companies_id_fk": {
"name": "tool_mcp_tasks_company_id_companies_id_fk",
"tableFrom": "tool_mcp_tasks",
"tableTo": "companies",
"columnsFrom": [
"company_id"
],
"columnsTo": [
"id"
],
"onDelete": "cascade",
"onUpdate": "no action"
},
"tool_mcp_tasks_invocation_id_tool_invocations_id_fk": {
"name": "tool_mcp_tasks_invocation_id_tool_invocations_id_fk",
"tableFrom": "tool_mcp_tasks",
"tableTo": "tool_invocations",
"columnsFrom": [
"invocation_id"
],
"columnsTo": [
"id"
],
"onDelete": "cascade",
"onUpdate": "no action"
},
"tool_mcp_tasks_connection_id_tool_connections_id_fk": {
"name": "tool_mcp_tasks_connection_id_tool_connections_id_fk",
"tableFrom": "tool_mcp_tasks",
"tableTo": "tool_connections",
"columnsFrom": [
"connection_id"
],
"columnsTo": [
"id"
],
"onDelete": "cascade",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"policies": {},
"checkConstraints": {},
"isRLSEnabled": false
},
"public.tool_oauth_states": {
"name": "tool_oauth_states",
"schema": "",
+21
View File
@@ -3347,6 +3347,27 @@
"when": 1794589077537,
"tag": "0479_short_darkstar",
"breakpoints": true
},
{
"idx": 480,
"version": "7",
"when": 1794604914931,
"tag": "0480_lazy_lethal_legion",
"breakpoints": true
},
{
"idx": 481,
"version": "7",
"when": 1794604943265,
"tag": "0481_round_pet_avengers",
"breakpoints": true
},
{
"idx": 482,
"version": "7",
"when": 1794604948355,
"tag": "0482_aberrant_rumiko_fujikawa",
"breakpoints": true
}
]
}
@@ -13,6 +13,7 @@ export const companySecrets = pgTable(
id: uuid("id").primaryKey().defaultRandom(),
companyId: uuid("company_id").notNull().references(() => companies.id),
scope: text("scope").notNull().default("company"),
systemPurpose: text("system_purpose"),
ownerUserId: text("owner_user_id"),
ownerAgentId: uuid("owner_agent_id"),
ownerProjectId: uuid("owner_project_id"),
+1
View File
@@ -285,4 +285,5 @@ export { issueThreadInteractionIdempotencyKeys } from "./issue_thread_interactio
export { projectTaskExecutionPolicies, executionAdmissions, executionAdmissionProjectCharges } from "./execution_admissions.js";
export { budgetEvaluationWork } from "./budget_evaluation_work.js";
export { tailscaleConnections } from "./tailscale_connections.js";
export { nativeProviderArtifacts, nativeProviderArtifactReferences } from "./native_provider_artifacts.js";
@@ -0,0 +1,21 @@
import { index, integer, pgTable, text, timestamp, uniqueIndex, uuid } from "drizzle-orm/pg-core";
import { companies } from "./companies.js";
import { companySecrets } from "./company_secrets.js";
export const tailscaleConnections = pgTable("tailscale_connections", {
id: uuid("id").primaryKey().defaultRandom(),
companyId: uuid("company_id").notNull().references(() => companies.id, { onDelete: "cascade" }),
name: text("name").notNull(),
status: text("status").notNull().default("pending"),
secretId: uuid("secret_id").references(() => companySecrets.id),
credentialVersion: integer("credential_version"),
credentialHash: text("credential_hash"),
createdByUserId: text("created_by_user_id").notNull(),
oauthStateHash: text("oauth_state_hash"),
oauthExpiresAt: timestamp("oauth_expires_at", { withTimezone: true }),
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
}, table => ({
companyIdx: index("tailscale_connections_company_idx").on(table.companyId),
stateIdx: uniqueIndex("tailscale_connections_oauth_state_idx").on(table.oauthStateHash),
}));
@@ -4,6 +4,7 @@ import { promises as fs } from "node:fs";
import os from "node:os";
import path from "node:path";
import { spawn } from "node:child_process";
import { PassThrough } from "node:stream";
import {
assertConfinedSandboxPath,
parseTarVerboseListingLine,
@@ -39,6 +40,7 @@ function makeRealExec(): { exec: PodStreamExec; calls: RecordedCall[] } {
return await new Promise((resolve, reject) => {
const child = spawn(command[0], command.slice(1));
let err = "";
let stdinError: NodeJS.ErrnoException | undefined;
child.stderr.on("data", (chunk: Buffer) => {
err += chunk.toString("utf-8");
});
@@ -49,6 +51,15 @@ function makeRealExec(): { exec: PodStreamExec; calls: RecordedCall[] } {
} else {
child.stdout.resume();
}
child.stdin.on("error", (error: NodeJS.ErrnoException) => {
if (error.code !== "EPIPE") {
reject(error);
return;
}
stdinError = error;
io.stdin?.unpipe(child.stdin);
io.stdin?.destroy();
});
if (io.stdin) {
io.stdin.on("error", reject);
io.stdin.pipe(child.stdin);
@@ -56,6 +67,10 @@ function makeRealExec(): { exec: PodStreamExec; calls: RecordedCall[] } {
child.stdin.end();
}
child.on("close", (code) => {
if (code === 0 && stdinError) {
reject(stdinError);
return;
}
resolve({ exitCode: code ?? 0, stderr: err });
});
});
@@ -96,6 +111,38 @@ afterEach(async () => {
await Promise.all(tmpDirs.splice(0).map((dir) => fs.rm(dir, { recursive: true, force: true })));
});
describe("shell exec stream lifecycle", () => {
it.each([0, 42])("handles an early stdin close while preserving exit status %i", async (exitCode) => {
const stdin = new PassThrough();
const stdout = new PassThrough();
stdout.once("data", () => stdin.end(Buffer.alloc(512 * 1024)));
const { exec } = makeRealExec();
try {
const result = exec([
process.execPath,
"-e",
`
require("node:fs").closeSync(0);
process.stdout.write("stdin closed\\n");
setTimeout(() => {
process.stderr.write("early rejection");
process.exit(${exitCode});
}, 100);
`,
], { stdin, stdout });
if (exitCode === 0) {
await expect(result).rejects.toMatchObject({ code: "EPIPE" });
} else {
await expect(result).resolves.toEqual({ exitCode, stderr: "early rejection" });
}
expect(stdin.destroyed).toBe(true);
} finally {
stdin.destroy();
stdout.destroy();
}
});
});
describe("kubernetes file-sync path confinement", () => {
it("rejects a target path that escapes the workspace remote dir", () => {
expect(() => assertConfinedSandboxPath("/workspace", "/workspace/../etc/passwd", "target")).toThrow(
+7
View File
@@ -13,6 +13,13 @@ export interface LocalEnvironmentConfig {
export interface SshEnvironmentConfig {
useHostAuth?: boolean;
tailscaleConnectionId?: string;
tailscaleDeviceId?: string;
network?: "direct" | "tailscale";
tailscaleAuthKey?: null;
tailscaleAuthKeySecretRef?: EnvSecretRefBinding | null;
tailscaleSocket?: string;
tailscaleIdentity?: string;
host: string;
port: number;
username: string;
+2
View File
@@ -36,6 +36,8 @@ echo "==> Verifying key binaries in image"
set -e
node --version
git --version
tailscale version
tailscaled --version
gh --version
rg --version
python3 --version
@@ -119,6 +119,47 @@ describeEmbeddedPostgres("agent secret routes", () => {
return app;
}
it("rejects an unclassified legacy node-state secret even through an existing agent binding", async () => {
const fixture = await seedAgentRun();
const svc = secretService(db);
const value = "paperclip-tailscale-state-v1:fixture-legacy-node-state";
const legacy = await svc.create(fixture.companyId, { name: "Legacy network", key: "LEGACY_NETWORK", provider: "local_encrypted", value });
await svc.createBinding({ companyId: fixture.companyId, secretId: legacy.id,
targetType: "agent", targetId: fixture.agentId, configPath: "env.ANTHROPIC_AUTH_TOKEN" });
const response = await request(createApp(fixture)).post("/api/agents/me/secrets/legacy_network/value");
expect(response.status).toBe(403);
expect(JSON.stringify(response.body)).not.toContain(value);
});
it("never returns server-owned network state through generic catalog, binding, runtime, or agent API reads", async () => {
const fixture = await seedAgentRun();
const svc = secretService(db);
const value = "paperclip-tailscale-state-v1:fixture-network-state";
const secret = await svc.createSystemSecret(fixture.companyId, {
key: "NETWORK_STATE", name: "Network fixture", provider: "local_encrypted", value,
}, "tailscale_network");
const app = createApp(fixture);
const catalog = await request(app).get(`/api/companies/${fixture.companyId}/secrets/catalog`);
expect(catalog.status).toBe(200);
expect(catalog.body).not.toEqual(expect.arrayContaining([expect.objectContaining({ id: secret.id })]));
await expect(svc.createBinding({ companyId: fixture.companyId, secretId: secret.id,
targetType: "agent", targetId: fixture.agentId, configPath: "env.ANTHROPIC_AUTH_TOKEN" })).rejects.toMatchObject({ status: 403 });
await expect(svc.resolveSecretValue(fixture.companyId, secret.id, "latest")).rejects.toMatchObject({ status: 403 });
await expect(svc.resolveAdapterConfigForRuntime(fixture.companyId, {
env: { ANTHROPIC_AUTH_TOKEN: { type: "secret_ref", secretId: secret.id, version: "latest" } },
})).rejects.toMatchObject({ status: 403 });
await db.insert(companySecretBindings).values({ companyId: fixture.companyId, secretId: secret.id,
targetType: "agent", targetId: fixture.agentId, configPath: "env.ANTHROPIC_AUTH_TOKEN" });
const response = await request(app).post("/api/agents/me/secrets/network_state/value");
expect(response.status).toBe(403);
expect(JSON.stringify(response.body)).not.toContain(value);
await svc.update(secret.id, { name: "Renamed", providerMetadata: {} });
await svc.rotate(secret.id, { value: "fixture-rotated-network-state" });
expect((await svc.getById(secret.id))?.systemPurpose).toBe("tailscale_network");
await expect(svc.resolveSecretValue(fixture.companyId, secret.id, 1)).rejects.toMatchObject({ status: 403 });
expect(await svc.resolveSystemSecretValue(fixture.companyId, secret.id, "latest", "tailscale_network", "fixture-network")).toBe("fixture-rotated-network-state");
});
it("lists metadata only, reads env and access grants, and audits success and failure", async () => {
const fixture = await seedAgentRun();
const svc = secretService(db);
@@ -163,7 +163,7 @@ describe("Application image Runner", () => {
it("compiles the Runner only in the runner-artifacts stages", () => {
const names = [...dockerfile.matchAll(/^FROM \S+ AS (\S+)$/gm)].map((match) => match[1]);
const application = names.filter((name) => !name.startsWith("runner-artifacts"));
expect(application).toEqual(["base", "runner-lockfile", "deps", "build", "runner-provider-pack", "production", "cloud-plugins", "cloud-server-deps", "cloud"]);
expect(application).toEqual(["base", "tailscale-client", "runner-lockfile", "deps", "build", "runner-provider-pack", "production", "cloud-plugins", "cloud-server-deps", "cloud"]);
for (const name of application) {
expect(stageBody(dockerfile, name), name).not.toMatch(/\b(?:cargo|rustup|rustc|gcc)\b/);
}
@@ -3,6 +3,17 @@ import { HttpError } from "../errors.js";
import { normalizeEnvironmentConfig, parseEnvironmentDriverConfig } from "../services/environment-config.ts";
describe("environment config helpers", () => {
it("uses a connected tailnet within the SSH driver and requires a complete machine selection", () => {
const config = { host: "100.64.0.1", username: "developer", remoteWorkspacePath: "/Users/developer/Paperclip", network: "tailscale",
tailscaleConnectionId: "11111111-1111-4111-8111-111111111111", tailscaleDeviceId: "stable-device-id" };
const normalized = normalizeEnvironmentConfig({ driver: "ssh", config });
expect(normalized).toMatchObject(config);
expect(parseEnvironmentDriverConfig({ driver: "ssh", config: normalized })).toMatchObject({ driver: "ssh", config });
expect(() => normalizeEnvironmentConfig({ driver: "ssh", config: { ...config, tailscaleDeviceId: "" } })).toThrow(HttpError);
expect(() => normalizeEnvironmentConfig({ driver: "ssh", config: { ...config, tailscaleConnectionId: undefined } })).toThrow(HttpError);
expect(() => normalizeEnvironmentConfig({ driver: "ssh", config: { ...config, network: "direct" } })).toThrow(HttpError);
expect(() => normalizeEnvironmentConfig({ driver: "ssh", config: { ...config, tailscaleAuthKey: "raw-token" } })).toThrow(HttpError);
});
it.each([undefined, true, false])("preserves SSH authentication compatibility when useHostAuth is %s", useHostAuth => {
const config = normalizeEnvironmentConfig({ driver: "ssh", config: {
host: "ssh.example.test", username: "fixture", remoteWorkspacePath: "/workspace",
@@ -13,7 +24,6 @@ describe("environment config helpers", () => {
expect(() => normalizeEnvironmentConfig({ driver: "ssh", config: { ...config, useHostAuth: "false" } })).toThrow(HttpError);
});
it("normalizes SSH config into its canonical stored shape", () => {
const config = normalizeEnvironmentConfig({
driver: "ssh",
@@ -47,6 +57,17 @@ describe("environment config helpers", () => {
});
});
it("accepts a secret-backed Tailscale machine and rejects runtime socket injection", () => {
const config = { host: "workstation", username: "developer", remoteWorkspacePath: "/workspace", network: "tailscale",
tailscaleConnectionId: "22222222-2222-4222-8222-222222222222", tailscaleDeviceId: "fixture-device",
tailscaleAuthKeySecretRef: { type: "secret_ref", secretId: "11111111-1111-1111-1111-111111111111", version: "latest" } };
expect(normalizeEnvironmentConfig({ driver: "ssh", config })).toMatchObject(config);
expect(() => normalizeEnvironmentConfig({ driver: "ssh", config: { ...config, tailscaleConnectionId: undefined, tailscaleDeviceId: undefined } })).toThrow(HttpError);
expect(() => normalizeEnvironmentConfig({ driver: "ssh", config: { ...config, tailscaleAuthKey: "tskey-auth-fixture" } })).toThrow(HttpError);
expect(() => normalizeEnvironmentConfig({ driver: "ssh", config: { ...config, tailscaleSocket: "/tmp/other-company" } })).toThrow(HttpError);
expect(() => normalizeEnvironmentConfig({ driver: "ssh", config: { ...config, tailscaleAuthKeySecretRef: { ...config.tailscaleAuthKeySecretRef, version: 1 } } })).toThrow(HttpError);
});
it("rejects raw SSH private keys in the stored config shape", () => {
expect(() =>
normalizeEnvironmentConfig({
@@ -2151,6 +2151,25 @@ describe("environment routes", () => {
expect(mockEnvironmentService.create).not.toHaveBeenCalled();
});
it("rejects standalone Tailscale enrollment keys before storing an environment secret", async () => {
const res = await request(createApp(localBoardActor())).post("/api/companies/company-1/environments").send({
name: "My workstation", driver: "ssh", config: { network: "tailscale", host: "workstation", username: "developer",
remoteWorkspacePath: "/workspace", tailscaleAuthKey: "tskey-auth-fixture" },
});
expect(res.status).toBe(422);
expect(mockSecretService.create).not.toHaveBeenCalled();
expect(mockEnvironmentService.create).not.toHaveBeenCalled();
expect(JSON.stringify(res.body)).not.toContain("tskey-auth-fixture");
});
it("rejects Tailscale environment setup from a non-admin before storing credentials", async () => {
const res = await request(createApp({ type: "board", userId: "member", source: "session", companyIds: ["company-1"] }))
.post("/api/companies/company-1/environments").send({ name: "My workstation", driver: "ssh", config: {
network: "tailscale", host: "workstation", username: "developer", remoteWorkspacePath: "/workspace", tailscaleAuthKey: "tskey-auth-fixture" } });
expect(res.status).toBe(403);
expect(mockSecretService.create).not.toHaveBeenCalled();
});
it("normalizes SSH private keys into secret refs before persistence", async () => {
const environment = createSecretBackedSshEnvironment();
mockEnvironmentService.create.mockResolvedValue(environment);
@@ -2,7 +2,7 @@ import { randomUUID } from "node:crypto";
import express from "express";
import request from "supertest";
import { and, eq, sql } from "drizzle-orm";
import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest";
import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
import {
agentWakeupRequests,
agents,
@@ -31,16 +31,13 @@ if (!embeddedPostgresSupport.supported) {
describeEmbeddedPostgres("reassigning a task whose previous assignee's run has not started", () => {
let db!: ReturnType<typeof createDb>;
let tempDb: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>> | null = null;
let companySequence = 0;
beforeAll(async () => {
tempDb = await startEmbeddedPostgresTestDatabase("paperclip-reassign-queued-");
db = createDb(tempDb.connectionString);
}, 30_000);
afterEach(async () => {
await db.execute(sql`TRUNCATE TABLE companies CASCADE`);
});
afterAll(async () => {
await db?.$client.end();
await tempDb?.cleanup();
@@ -71,8 +68,9 @@ describeEmbeddedPostgres("reassigning a task whose previous assignee's run has n
const morganId = randomUUID();
const issueId = randomUUID();
const queuedRunId = randomUUID();
const issuePrefix = `REA${++companySequence}`;
await db.insert(companies).values({
id: companyId, name: "Reassign Co", issuePrefix: "REA", requireBoardApprovalForNewAgents: false,
id: companyId, name: "Reassign Co", issuePrefix, requireBoardApprovalForNewAgents: false,
});
await db.insert(agents).values([ceoId, morganId].map((id, index) => ({
id, companyId, name: index === 0 ? "CEO" : "Morgan", role: index === 0 ? "ceo" : "engineer",
@@ -90,7 +88,7 @@ describeEmbeddedPostgres("reassigning a task whose previous assignee's run has n
status: "queued", contextSnapshot: { issueId, wakeReason: "issue_assigned" },
});
await db.insert(issues).values({
id: issueId, companyId, identifier: "REA-1", title: "Write the announcement", status: "todo",
id: issueId, companyId, identifier: `${issuePrefix}-1`, title: "Write the announcement", status: "todo",
priority: "medium", assigneeAgentId: ceoId, executionRunId: options.queuedRunHoldsLock === false ? null : queuedRunId,
});
return { companyId, ceoId, morganId, issueId, queuedRunId };
@@ -98,6 +98,7 @@ const apiPrefixes: Record<string, string> = {
"sidebar-preferences.ts": "/api",
"summary-slots.ts": "/api",
"status-cards.ts": "/api",
"tailscale-connections.ts": "/api",
"teams-catalog.ts": "/api",
"tool-access.ts": "/api",
"voice-sessions.ts": "/api",
@@ -1250,6 +1251,36 @@ describe("openapi routes", () => {
});
});
it("documents Tailscale management as instance-admin operations without credential responses", () => {
const { spec } = loadSpecRoutes();
const base = "/api/companies/{companyId}/tailscale-connections";
for (const [path, method] of [[base, "get"], [base, "post"], [base + "/{connectionId}", "delete"],
[base + "/{connectionId}/devices", "get"], [base + "/{connectionId}/pairing", "post"], ["/api/tools/oauth/tailscale/callback", "get"]]) {
const operation = spec.paths[path]?.[method];
expect(operation).toBeDefined();
expect(operation["x-paperclip-authorization"]).toEqual({ actor: "board", instanceAdmin: true });
expect(operation.security).toEqual([{ BoardSessionAuth: [] }, { BoardApiKeyAuth: [] }]);
expect(operation.responses["403"]).toBeDefined();
}
const connection = spec.paths[base].get.responses["200"].content["application/json"].schema.items;
expect(Object.keys(connection.properties).sort()).toEqual(["companyId", "id", "name", "status"]);
expect(connection.additionalProperties).toBe(false);
const start = spec.paths[base].post;
expect(start.requestBody.content["application/json"].schema).toMatchObject({ additionalProperties: false,
properties: { name: { minLength: 1, maxLength: 100 }, connectionId: { format: "uuid" } } });
expect(start.requestBody.content["application/json"].schema.required ?? []).toEqual([]);
const session = start.responses["201"].content["application/json"].schema;
expect(session.required).toEqual(["authorizationUrl", "expiresAt"]);
expect(session.properties.handoff.properties.kind).toEqual({ type: "string", enum: ["paperclip_cloud"] });
const pairing = spec.paths[base + "/{connectionId}/pairing"].post;
expect(pairing.requestBody.content["application/json"].schema).toMatchObject({ additionalProperties: false, required: ["deviceId"],
properties: { deviceId: { minLength: 1, maxLength: 256 }, port: { minimum: 1, maximum: 65535 } } });
expect(Object.keys(pairing.responses["200"].content["application/json"].schema.properties).sort()).toEqual(["command", "privateKeySecretId", "publicKey"]);
const callback = spec.paths["/api/tools/oauth/tailscale/callback"].get;
expect(callback.responses["303"].headers).toMatchObject({ Location: { schema: { type: "string" } }, "Cache-Control": { schema: { enum: ["no-store"] } } });
expect(callback.parameters).toContainEqual(expect.objectContaining({ in: "query", name: "state", required: true, schema: expect.objectContaining({ maxLength: 128 }) }));
});
it("covers the mounted server routes exactly", () => {
const {
routes: actualRoutes,
@@ -0,0 +1,119 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import { normalizeEnvironmentConfigForPersistence, resolveEnvironmentDriverConfigForRuntime } from "../services/environment-config.js";
import { unprocessable } from "../errors.js";
const fixture = vi.hoisted(() => ({
get: vi.fn(), binding: vi.fn(), connect: vi.fn(),
secrets: { resolveSecretValue: vi.fn(), resolveSecretVersion: vi.fn(), rotate: vi.fn() },
}));
vi.mock("../services/connectors/tailscale/connections.js", () => ({ tailscaleConnectionService: () => ({ get: fixture.get, environmentBinding: fixture.binding }) }));
vi.mock("../services/connectors/tailscale/network.js", async importOriginal => ({
...await importOriginal<typeof import("../services/connectors/tailscale/network.js")>(),
tailscaleNetworks: { connect: fixture.connect },
}));
vi.mock("../services/secrets.js", () => ({ secretService: () => fixture.secrets }));
const companyId = "11111111-1111-4111-8111-111111111111";
const connectionId = "22222222-2222-4222-8222-222222222222";
const secretId = "33333333-3333-4333-8333-333333333333";
const config = {
network: "tailscale", tailscaleConnectionId: connectionId, tailscaleDeviceId: "stable-machine-id",
host: "100.64.0.1", port: 22, username: "developer", remoteWorkspacePath: "/workspace",
tailscaleAuthKeySecretRef: { type: "secret_ref", secretId, version: "latest" },
};
const environment = { id: "44444444-4444-4444-8444-444444444444", driver: "ssh" as const, config };
describe("SSH environments using the Tailscale connector", () => {
beforeEach(() => {
vi.resetAllMocks();
fixture.get.mockResolvedValue({ id: connectionId, companyId, secretId, status: "connected" });
fixture.binding.mockResolvedValue({ host: "100.64.0.2", secretId, socket: "/tmp/private-tailscale/socket" });
fixture.connect.mockResolvedValue("/tmp/private-tailscale/socket");
fixture.secrets.resolveSecretValue.mockResolvedValue("fixture-encrypted-node-state");
fixture.secrets.resolveSecretVersion.mockResolvedValue(2);
});
it("uses the connector's company-scoped address and secret instead of client-supplied values", async () => {
const stored = await normalizeEnvironmentConfigForPersistence({ db: {} as never, companyId, environmentName: "Workstation", driver: "ssh", secretProvider: "local_encrypted",
config: { ...config, host: "untrusted.invalid", tailscaleAuthKeySecretRef: { ...config.tailscaleAuthKeySecretRef, secretId: "55555555-5555-4555-8555-555555555555" } } });
expect(fixture.binding).toHaveBeenCalledWith(companyId, connectionId, "stable-machine-id");
expect(stored).toMatchObject({ host: "100.64.0.2", tailscaleAuthKeySecretRef: { secretId } });
});
it("refreshes the selected machine address at execution and uses only the connector's private socket", async () => {
const resolved = await resolveEnvironmentDriverConfigForRuntime({} as never, companyId, environment);
expect(fixture.get).toHaveBeenCalledWith(companyId, connectionId);
expect(fixture.binding).toHaveBeenCalledWith(companyId, connectionId, "stable-machine-id", secretId);
expect(resolved).toMatchObject({ driver: "ssh", config: { host: "100.64.0.2", tailscaleSocket: "/tmp/private-tailscale/socket", tailscaleIdentity: `${companyId}:${secretId}` } });
expect(fixture.connect).not.toHaveBeenCalled();
expect(fixture.secrets.resolveSecretValue).not.toHaveBeenCalled();
});
it.each(["disconnected", "replaced"])("rejects a connector %s while the SSH key is loading", async state => {
let entered!: () => void, release!: () => void;
const loading = new Promise<void>(resolve => { entered = resolve; });
const paused = new Promise<void>(resolve => { release = resolve; });
fixture.secrets.resolveSecretValue.mockImplementationOnce(async () => { entered(); await paused; return "fixture-ssh-key"; });
const resolving = resolveEnvironmentDriverConfigForRuntime({} as never, companyId, { ...environment, config: { ...config,
privateKeySecretRef: { type: "secret_ref", secretId: "55555555-5555-4555-8555-555555555555", version: "latest" },
} });
const outcome = resolving.then(value => ({ value, error: null }), error => ({ value: null, error }));
try {
await Promise.race([loading, resolving.then(() => { throw new Error("Runtime resolved before loading the SSH key"); })]);
fixture.get.mockResolvedValue({ id: connectionId, companyId, secretId: state === "replaced" ? "new-secret" : secretId, status: state === "replaced" ? "connected" : state });
fixture.binding.mockRejectedValue(unprocessable("Reconnect Tailscale and save this environment again.", { code: "tailscale_reauthorization_required" }));
} finally { release(); }
expect((await outcome).error).toMatchObject({ status: 422, details: { code: "tailscale_reauthorization_required" } });
expect(fixture.connect).not.toHaveBeenCalled();
expect(fixture.binding).toHaveBeenCalledWith(companyId, connectionId, "stable-machine-id", secretId);
expect(fixture.binding.mock.invocationCallOrder[0]).toBeGreaterThan(fixture.secrets.resolveSecretValue.mock.invocationCallOrder[0]!);
});
it.each(["pending", "connecting", "disconnected"])("rejects a %s connector before reading any runtime credentials", async status => {
fixture.get.mockResolvedValue({ id: connectionId, companyId, secretId, status });
await expect(resolveEnvironmentDriverConfigForRuntime({} as never, companyId, environment)).rejects.toMatchObject({ status: 422 });
expect(fixture.secrets.resolveSecretValue).not.toHaveBeenCalled();
expect(fixture.connect).not.toHaveBeenCalled();
});
it("rejects a saved network credential without its connector instead of starting a standalone daemon", async () => {
const configWithoutConnection = { ...config, tailscaleConnectionId: undefined, tailscaleDeviceId: undefined };
await expect(resolveEnvironmentDriverConfigForRuntime({} as never, companyId, { ...environment, config: configWithoutConnection })).rejects.toMatchObject({ status: 422 });
await expect(normalizeEnvironmentConfigForPersistence({ db: {} as never, companyId, environmentName: "Workstation", driver: "ssh",
secretProvider: "local_encrypted", config: configWithoutConnection })).rejects.toMatchObject({ status: 422 });
expect(fixture.get).not.toHaveBeenCalled();
expect(fixture.secrets.resolveSecretValue).not.toHaveBeenCalled();
expect(fixture.connect).not.toHaveBeenCalled();
});
it("clears a saved tailnet when Direct is explicitly merged into an SSH environment", async () => {
const stored = await normalizeEnvironmentConfigForPersistence({ db: {} as never, companyId, environmentName: "Workstation", driver: "ssh",
secretProvider: "local_encrypted", config: { ...config, network: "direct", host: "direct.example.test" } });
expect(stored).toMatchObject({ network: "direct", host: "direct.example.test" });
for (const key of ["tailscaleConnectionId", "tailscaleDeviceId", "tailscaleAuthKeySecretRef", "tailscaleAuthKey"]) {
expect(stored).not.toHaveProperty(key);
}
expect(fixture.binding).not.toHaveBeenCalled();
expect(fixture.connect).not.toHaveBeenCalled();
});
it("requires company and environment context before opening a runtime binding", async () => {
await expect(resolveEnvironmentDriverConfigForRuntime({} as never, null, environment)).rejects.toMatchObject({ status: 422 });
await expect(resolveEnvironmentDriverConfigForRuntime({} as never, companyId, { ...environment, id: undefined })).rejects.toMatchObject({ status: 422 });
expect(fixture.binding).not.toHaveBeenCalled();
expect(fixture.connect).not.toHaveBeenCalled();
});
it("never falls back to a caller's host or the system tailnet when company access or device lookup fails", async () => {
fixture.binding.mockRejectedValue(new Error("machine unavailable in this company"));
await expect(resolveEnvironmentDriverConfigForRuntime({} as never, companyId, environment)).rejects.toThrow("machine unavailable");
expect(fixture.connect).not.toHaveBeenCalled();
});
it("keeps read-only inspection free of network and daemon activity", async () => {
const resolved = await resolveEnvironmentDriverConfigForRuntime({} as never, companyId, environment, { readOnlyInspection: true });
expect(resolved.driver).toBe("ssh");
expect(fixture.binding).not.toHaveBeenCalled();
expect(fixture.connect).not.toHaveBeenCalled();
});
});
@@ -0,0 +1,167 @@
import express from "express";
import request from "supertest";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { tailscaleConnectionRoutes } from "../routes/tailscale-connections.js";
import { boardMutationGuard } from "../middleware/board-mutation-guard.js";
import { errorHandler } from "../middleware/error-handler.js";
import { badRequest } from "../errors.js";
const fixture = vi.hoisted(() => ({
service: { list: vi.fn(), start: vi.fn(), devices: vi.fn(), complete: vi.fn(), disconnect: vi.fn(), pairing: vi.fn() },
configured: vi.fn(), enrollment: vi.fn(), activity: vi.fn(),
}));
vi.mock("../services/connectors/tailscale/connections.js", () => ({ tailscaleConnectionService: () => fixture.service }));
vi.mock("../services/paperclip-cloud-connector.js", () => ({ paperclipCloudConnectorConfigFromEnv: fixture.configured }));
vi.mock("../services/paperclip-cloud-connector-enrollment.js", () => ({ startPaperclipCloudConnectorEnrollment: fixture.enrollment }));
vi.mock("../services/activity-log.js", () => ({ logActivity: fixture.activity }));
vi.mock("../config.js", () => ({ loadConfig: () => ({ authPublicBaseUrl: "http://localhost:3100" }) }));
const companyId = "11111111-1111-4111-8111-111111111111";
const connectionId = "22222222-2222-4222-8222-222222222222";
const path = `/api/companies/${companyId}/tailscale-connections`;
const board = { type: "board", source: "session", userId: "fixture-user", isInstanceAdmin: true, companyIds: [companyId] };
function app(actor = board) {
const result = express();
result.use(express.json());
result.use((req, _res, next) => { (req as any).actor = actor; next(); });
result.use(boardMutationGuard());
result.use("/api", tailscaleConnectionRoutes({ select: () => ({ from: () => ({ where: async () => [{ prefix: "FIX" }] }) }) } as never));
result.use(errorHandler);
return result;
}
describe("Tailscale connector routes", () => {
beforeEach(() => {
vi.clearAllMocks();
fixture.configured.mockReturnValue({});
fixture.service.list.mockResolvedValue([{ id: connectionId, name: "Home", status: "connected", companyId }]);
fixture.service.start.mockResolvedValue({ connection: { id: connectionId }, authorizationUrl: "https://login.tailscale.com/a/oauth_authorize" });
fixture.service.devices.mockResolvedValue([{ id: "stable-device", name: "Home Mac", online: true }]);
fixture.service.complete.mockImplementation(async input => { input.authorizeCompany(companyId, connectionId); return { id: connectionId, companyId }; });
fixture.service.disconnect.mockResolvedValue({ id: connectionId, companyId, status: "disconnected" });
fixture.service.pairing.mockResolvedValue({ privateKeySecretId: "fixture-key-ref", publicKey: "fixture-public-key", command: "fixture-public-pairing-command" });
});
it("starts consent with the signed-in user, company, and fixed connector callback", async () => {
const response = await request(app()).post(path).set("Origin", "http://localhost:3100").send({ name: "Home" });
expect(response.status).toBe(201);
expect(fixture.service.start).toHaveBeenCalledWith({ companyId, userId: "fixture-user", name: "Home", returnUri: "http://localhost:3100/api/tools/oauth/tailscale/callback" });
expect(fixture.activity).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({ action: "tailscale.authorization_started", companyId }));
});
it("rejects foreign-origin browser mutations before starting consent", async () => {
const response = await request(app()).post(path).set("Origin", "https://untrusted.example.test").send({ name: "Home" });
expect(response.status).toBe(403);
expect(fixture.service.start).not.toHaveBeenCalled();
});
it("rejects agent and non-admin management", async () => {
for (const actor of [{ type: "agent", source: "agent_key", agentId: "fixture-agent", companyId }, { ...board, isInstanceAdmin: false }]) {
expect((await request(app(actor as any)).get(path)).status).toBe(403);
}
expect(fixture.service.list).not.toHaveBeenCalled();
});
it("checks company access before listing machines or mutating a connection", async () => {
const denied = app({ ...board, companyIds: [] });
expect((await request(denied).get(path + `/${connectionId}/devices`)).status).toBe(403);
expect((await request(denied).delete(path + `/${connectionId}`).set("Origin", "http://localhost:3100")).status).toBe(403);
expect(fixture.service.devices).not.toHaveBeenCalled();
expect(fixture.service.disconnect).not.toHaveBeenCalled();
});
it("returns machines only through the selected company connection", async () => {
expect((await request(app()).get(path + `/${connectionId}/devices`)).status).toBe(200);
expect(fixture.service.devices).toHaveBeenCalledWith(companyId, connectionId);
});
it("returns consent to the connector with only the connection identifier", async () => {
const response = await request(app()).get("/api/tools/oauth/tailscale/callback").query({ state: "s".repeat(43), claim_id: "opaque-claim" });
expect(response.status).toBe(303);
expect(response.headers.location).toBe(`/FIX/apps/tailscale?tailscale_connection=${connectionId}`);
expect(response.headers["cache-control"]).toBe("no-store");
});
it("rechecks current company membership on the callback", async () => {
expect((await request(app({ ...board, companyIds: [] })).get("/api/tools/oauth/tailscale/callback").query({ state: "s".repeat(43), claim_id: "opaque-claim" })).status).toBe(403);
expect(fixture.activity).not.toHaveBeenCalled();
});
it.each(["access_denied", "authorization_denied", "untrusted-provider-error<script>"])("returns %s consent to the same saved connection with a safe outcome", async error => {
fixture.service.complete.mockImplementationOnce(async input => {
input.authorizeCompany(companyId, connectionId);
throw badRequest("untrusted-provider-error with private state and claim data");
});
const response = await request(app()).get("/api/tools/oauth/tailscale/callback").set("Accept", "text/html").query({ state: "s".repeat(43), error });
expect(response.status).toBe(303);
const reason = error === "untrusted-provider-error<script>" ? "failed" : "cancelled";
expect(response.headers.location).toBe(`/FIX/apps/tailscale?tailscale_connection=${connectionId}&tailscale_error=${reason}`);
expect(response.headers["cache-control"]).toBe("no-store");
expect(response.headers["referrer-policy"]).toBe("no-referrer");
expect(response.text).not.toContain("untrusted-provider-error");
expect(fixture.activity).toHaveBeenCalledExactlyOnceWith(expect.anything(), {
companyId, actorType: "user", actorId: "fixture-user", action: "tailscale.authorization_failed",
entityType: "tailscale_connection", entityId: connectionId, details: { reason },
});
});
it("does not redirect an expired or unverified callback to a saved connection", async () => {
fixture.service.complete.mockRejectedValueOnce(badRequest("Authorization expired"));
const response = await request(app()).get("/api/tools/oauth/tailscale/callback").set("Accept", "text/html").query({ state: "s".repeat(43), error: "access_denied" });
expect(response.status).toBe(400);
expect(response.headers.location).toBeUndefined();
expect(fixture.activity).not.toHaveBeenCalled();
});
it("retains JSON error responses for programmatic callbacks", async () => {
fixture.service.complete.mockImplementationOnce(async input => {
input.authorizeCompany(companyId, connectionId);
throw badRequest("Authorization did not complete");
});
const response = await request(app()).get("/api/tools/oauth/tailscale/callback").set("Accept", "application/json").query({ state: "s".repeat(43), error: "access_denied" });
expect(response.status).toBe(400);
expect(response.headers.location).toBeUndefined();
expect(fixture.activity).not.toHaveBeenCalled();
});
it("starts existing instance enrollment when no broker identity exists", async () => {
fixture.configured.mockReturnValue(null);
fixture.enrollment.mockResolvedValue({ instanceId: "fixture-instance", environment: "development", status: "pending", verificationUrl: "http://localhost:3000/connections/enroll?id=fixture", expiresAt: "2099-01-01T00:00:00Z" });
const response = await request(app()).post(path).set("Origin", "http://localhost:3100").send({ name: "Home" });
expect(response.status).toBe(201);
expect(response.body.authorizationUrl).toContain("/connections/enroll");
expect(fixture.enrollment).toHaveBeenCalledWith(expect.objectContaining({ companyId, initiatedBy: "user:fixture-user", origin: "http://localhost:3100", returnTo: "/apps/tailscale" }));
expect(fixture.service.start).not.toHaveBeenCalled();
expect(fixture.activity).toHaveBeenCalledExactlyOnceWith(expect.anything(), {
companyId,
actorType: "user",
actorId: "fixture-user",
action: "paperclip_cloud_connector.enrollment_started",
entityType: "connector_instance",
entityId: "fixture-instance",
details: { environment: "development", status: "pending" },
});
});
it("checks origin, admin status, and company access before self-hosted enrollment", async () => {
fixture.configured.mockReturnValue(null);
for (const [actor, origin] of [
[board, "https://untrusted.example.test"],
[{ ...board, isInstanceAdmin: false }, "http://localhost:3100"],
[{ ...board, companyIds: [] }, "http://localhost:3100"],
[{ type: "agent", source: "agent_key", agentId: "fixture-agent", companyId }, "http://localhost:3100"],
] as const) {
expect((await request(app(actor as any)).post(path).set("Origin", origin).send({ name: "Home" })).status).toBe(403);
}
expect(fixture.enrollment).not.toHaveBeenCalled();
expect(fixture.service.start).not.toHaveBeenCalled();
expect(fixture.activity).not.toHaveBeenCalled();
});
it("does not record a successful enrollment start when enrollment fails", async () => {
fixture.configured.mockReturnValue(null);
fixture.enrollment.mockRejectedValue(new Error("Enrollment unavailable"));
const response = await request(app()).post(path).set("Origin", "http://localhost:3100").send({ name: "Home" });
expect(response.status).toBe(500);
expect(fixture.activity).not.toHaveBeenCalled();
expect(fixture.service.start).not.toHaveBeenCalled();
});
it("prepares machine pairing for an authorized board user without returning a private key", async () => {
const response = await request(app()).post(path + `/${connectionId}/pairing`).set("Origin", "http://localhost:3100").send({ deviceId: "stable-device" });
expect(response.status).toBe(200);
expect(fixture.service.pairing).toHaveBeenCalledWith(companyId, connectionId, "stable-device", 22, "fixture-user");
expect(response.body).toEqual({ privateKeySecretId: "fixture-key-ref", publicKey: "fixture-public-key", command: "fixture-public-pairing-command" });
});
it("rejects a foreign-origin pairing request before generating any key", async () => {
const response = await request(app()).post(path + `/${connectionId}/pairing`).set("Origin", "https://untrusted.example.test").send({ deviceId: "stable-device" });
expect(response.status).toBe(403);
expect(fixture.service.pairing).not.toHaveBeenCalled();
});
});
+2
View File
@@ -135,6 +135,7 @@ import { createSavedWorkspaceLoader } from "./services/remote-workspaces.js";
import { createSavedWorkspaceArchiveOpener } from "./services/saved-workspace-archive.js";
import { routineRoutes } from "./routes/routines.js";
import { environmentRoutes } from "./routes/environments.js";
import { tailscaleConnectionRoutes } from "./routes/tailscale-connections.js";
import { executionWorkspaceRoutes } from "./routes/execution-workspaces.js";
import { goalRoutes } from "./routes/goals.js";
import { onboardingSeedRoutes } from "./routes/onboarding-seed.js";
@@ -824,6 +825,7 @@ export async function createApp(
openSavedWorkspaceArchive: createSavedWorkspaceArchiveOpener(db, opts.storageService),
}) }));
api.use(routineRoutes(db, { pluginWorkerManager: workerManager }));
api.use(tailscaleConnectionRoutes(db));
api.use(
environmentRoutes(db, {
pluginWorkerManager: workerManager,
+2 -1
View File
@@ -1,3 +1,4 @@
import { tailscaleNetworks } from "./services/connectors/tailscale/network.js";
import type { IdleDeadlineOwners } from "./services/idle-deadline-types.js";
import { closeProcessRunAdmission, isProcessRunAdmissionClosed } from "./services/heartbeat/run-admission.js";
import { createRunStartHandover, registerRunStartHandover } from "./services/run-start-handover.js";
@@ -2354,7 +2355,7 @@ async function startServerWithDatabaseTeardown(
try { await appShutdown?.(); } finally {
await runStartHandover?.stop().catch(() => {});
registerRunStartHandover(null);
await stopControllerInstanceLease();
try { await tailscaleNetworks.close(); } finally { await stopControllerInstanceLease(); }
}
},
closeHttpListener: () =>
+74
View File
@@ -1628,6 +1628,12 @@ const BOARD_ONLY_OPERATIONS = new Set([
]);
const INSTANCE_ADMIN_OPERATIONS = new Set([
"GET /api/companies/{companyId}/tailscale-connections",
"POST /api/companies/{companyId}/tailscale-connections",
"GET /api/companies/{companyId}/tailscale-connections/{connectionId}/devices",
"DELETE /api/companies/{companyId}/tailscale-connections/{connectionId}",
"POST /api/companies/{companyId}/tailscale-connections/{connectionId}/pairing",
"GET /api/tools/oauth/tailscale/callback",
"POST /api/companies",
"POST /api/plugins/install",
"POST /api/instance/database-backups",
@@ -9597,6 +9603,74 @@ registry.registerPath({
responses: { 200: r.ok(), 400: r.badRequest, 401: r.unauthorized },
});
const tailscaleCompanyParams = z.object({ companyId: z.string().uuid() });
const tailscaleConnectionParams = tailscaleCompanyParams.extend({ connectionId: z.string().uuid() });
const tailscaleConnectionResponse = z.object({
id: z.string().uuid(), companyId: z.string().uuid(), name: z.string(),
status: z.enum(["pending", "connecting", "connected", "disconnected"]),
}).strict();
const tailscaleErrors = { 400: r.badRequest, 401: r.unauthorized, 403: r.forbidden, 404: r.notFound, 422: r.unprocessable };
registry.registerPath({
method: "get", path: "/api/companies/{companyId}/tailscale-connections", tags: ["tailscale"],
summary: "List company Tailscale connections",
description: "Requires an instance administrator with company access, or local implicit board access. Returns connection metadata without credentials or node state.",
request: { params: tailscaleCompanyParams },
responses: { 200: r.ok(z.array(tailscaleConnectionResponse)), ...tailscaleErrors },
});
registry.registerPath({
method: "post", path: "/api/companies/{companyId}/tailscale-connections", tags: ["tailscale"],
summary: "Start Tailscale network authorization",
description: "Requires an instance administrator with company access, or local implicit board access. Starts consent for a new connection or replaces consent for connectionId. An instance without a Cloud broker identity first returns an enrollment URL without a connection. Hosted authorization can return a signed Cloud handoff.",
request: { params: tailscaleCompanyParams, body: jsonBody(z.object({
name: z.string().trim().min(1).max(100).default("My tailnet"), connectionId: z.string().uuid().optional(),
}).strict()) },
responses: { 201: r.ok(z.object({
connection: tailscaleConnectionResponse.optional(), authorizationUrl: z.string().url(), expiresAt: z.string().datetime(),
handoff: z.object({ kind: z.literal("paperclip_cloud"), session: z.string().min(16).max(512).regex(/^[A-Za-z0-9_-]+$/) }).strict().optional(),
}).strict()), ...tailscaleErrors },
});
registry.registerPath({
method: "get", path: "/api/companies/{companyId}/tailscale-connections/{connectionId}/devices", tags: ["tailscale"],
summary: "List machines on a connected tailnet",
description: "Requires an instance administrator with company access, or local implicit board access. Resolves devices through this connection's private network client.",
request: { params: tailscaleConnectionParams },
responses: { 200: r.ok(z.array(z.object({
id: z.string(), name: z.string(), hostname: z.string(), address: z.string(), os: z.string(), online: z.boolean(),
}).strict())), ...tailscaleErrors },
});
registry.registerPath({
method: "delete", path: "/api/companies/{companyId}/tailscale-connections/{connectionId}", tags: ["tailscale"],
summary: "Disconnect a Tailscale network",
description: "Requires an instance administrator with company access, or local implicit board access. Invalidates pending consent and stops the private client. Keeps the saved connection record and does not remove the target machine from its tailnet.",
request: { params: tailscaleConnectionParams },
responses: { 200: r.ok(tailscaleConnectionResponse), ...tailscaleErrors },
});
registry.registerPath({
method: "post", path: "/api/companies/{companyId}/tailscale-connections/{connectionId}/pairing", tags: ["tailscale"],
summary: "Prepare an SSH machine pairing command",
description: "Requires an instance administrator with company access, or local implicit board access. Generates a fresh SSH key, stores its private half in the company vault, and returns its secret ID and public install command.",
request: { params: tailscaleConnectionParams, body: jsonBody(z.object({
deviceId: z.string().min(1).max(256), port: z.number().int().min(1).max(65535).default(22),
}).strict()) },
responses: { 200: r.ok(z.object({ privateKeySecretId: z.string().uuid(), publicKey: z.string(), command: z.string() }).strict()), ...tailscaleErrors },
});
registry.registerPath({
method: "get", path: "/api/tools/oauth/tailscale/callback", tags: ["tailscale"],
summary: "Complete Tailscale network authorization",
description: "Requires the initiating board operator to retain instance-admin and company access. Consumes user-bound consent state and an opaque broker claim. Redirects to the connector page without returning enrollment credentials.",
request: { query: z.object({ state: z.string().min(1).max(128), claim_id: z.string().max(256).optional(), error: z.string().max(128).optional() }) },
responses: { 303: { description: "Return to the company Tailscale connector", headers: {
Location: { schema: { type: "string" } }, "Cache-Control": { schema: { type: "string", enum: ["no-store"] } },
"Referrer-Policy": { schema: { type: "string", enum: ["no-referrer"] } },
} }, ...tailscaleErrors },
});
// ─── Environments ─────────────────────────────────────────────────────────────
registry.registerPath({
+104
View File
@@ -0,0 +1,104 @@
import { Router, type Request } from "express";
import { eq } from "drizzle-orm";
import { companies, type Db } from "@paperclipai/db";
import { z } from "zod";
import { loadConfig } from "../config.js";
import { forbidden, unprocessable } from "../errors.js";
import { validate } from "../middleware/validate.js";
import { tailscaleConnectionService } from "../services/connectors/tailscale/connections.js";
import { paperclipCloudConnectorConfigFromEnv } from "../services/paperclip-cloud-connector.js";
import { startPaperclipCloudConnectorEnrollment } from "../services/paperclip-cloud-connector-enrollment.js";
import { paperclipCloudEnrollmentPrincipal } from "../services/paperclip-cloud-connector-principal.js";
import { logActivity } from "../services/activity-log.js";
import { assertBoard, assertCompanyAccess, getActorInfo } from "./authz.js";
function operator(req: Request) {
assertBoard(req);
if (req.actor.source !== "local_implicit" && !req.actor.isInstanceAdmin) throw forbidden("Instance admin access required");
return getActorInfo(req).actorId;
}
export function tailscaleConnectionRoutes(db: Db) {
const router = Router();
const service = tailscaleConnectionService(db);
router.get("/companies/:companyId/tailscale-connections", async (req, res) => {
operator(req);
assertCompanyAccess(req, z.string().uuid().parse(req.params.companyId));
res.json(await service.list(z.string().uuid().parse(req.params.companyId)));
});
router.post("/companies/:companyId/tailscale-connections", validate(z.object({ name: z.string().trim().min(1).max(100).default("My tailnet"), connectionId: z.string().uuid().optional() }).strict()), async (req, res) => {
const userId = operator(req);
const companyId = z.string().uuid().parse(req.params.companyId);
assertCompanyAccess(req, companyId);
const origin = loadConfig().authPublicBaseUrl;
if (!origin) throw unprocessable("Set this instance's public URL before connecting Tailscale.");
if (!paperclipCloudConnectorConfigFromEnv()) {
const enrollment = await startPaperclipCloudConnectorEnrollment({ origin, companyId, initiatedBy: paperclipCloudEnrollmentPrincipal(req.actor),
returnTo: "/apps/tailscale",
});
await logActivity(db, {
companyId, actorType: "user", actorId: userId,
action: "paperclip_cloud_connector.enrollment_started",
entityType: "connector_instance", entityId: enrollment.instanceId ?? "pending",
details: { environment: enrollment.environment, status: enrollment.status },
});
res.status(201).json({ authorizationUrl: enrollment.verificationUrl, expiresAt: enrollment.expiresAt });
return;
}
const result = await service.start({ companyId, userId, ...req.body, returnUri: new URL("/api/tools/oauth/tailscale/callback", origin).toString() });
await logActivity(db, { companyId, actorType: "user", actorId: userId, action: "tailscale.authorization_started", entityType: "tailscale_connection", entityId: result.connection.id });
res.status(201).json(result);
});
router.get("/companies/:companyId/tailscale-connections/:connectionId/devices", async (req, res) => {
operator(req);
assertCompanyAccess(req, z.string().uuid().parse(req.params.companyId));
const id = z.string().uuid().parse(req.params.connectionId);
res.json(await service.devices(z.string().uuid().parse(req.params.companyId), id));
});
router.delete("/companies/:companyId/tailscale-connections/:connectionId", async (req, res) => {
const userId = operator(req);
const companyId = z.string().uuid().parse(req.params.companyId);
assertCompanyAccess(req, companyId);
const result = await service.disconnect(companyId, z.string().uuid().parse(req.params.connectionId));
await logActivity(db, { companyId, actorType: "user", actorId: userId, action: "tailscale.disconnected", entityType: "tailscale_connection", entityId: result.id });
res.json(result);
});
router.post("/companies/:companyId/tailscale-connections/:connectionId/pairing", validate(z.object({ deviceId: z.string().min(1).max(256), port: z.number().int().min(1).max(65535).default(22) }).strict()), async (req, res) => {
const userId = operator(req);
const companyId = z.string().uuid().parse(req.params.companyId);
assertCompanyAccess(req, companyId);
const id = z.string().uuid().parse(req.params.connectionId);
const result = await service.pairing(companyId, id, req.body.deviceId, req.body.port, userId);
await logActivity(db, { companyId, actorType: "user", actorId: userId, action: "tailscale.pairing_prepared", entityType: "tailscale_connection", entityId: id });
res.json(result);
});
router.get("/tools/oauth/tailscale/callback", async (req, res) => {
const userId = operator(req);
const query = z.object({ state: z.string().min(1).max(128), claim_id: z.string().max(256).optional(), error: z.string().max(128).optional() }).parse(req.query);
let authorizedConnection: { companyId: string; id: string } | undefined;
let result: { companyId: string; id: string };
let reason: "cancelled" | "failed" | undefined;
try {
result = await service.complete({ state: query.state, claimId: query.claim_id, error: query.error, userId,
authorizeCompany: (companyId, connectionId) => {
assertCompanyAccess(req, companyId);
authorizedConnection = { companyId, id: connectionId };
},
});
} catch (error) {
if (!authorizedConnection || !req.accepts("html")) throw error;
result = authorizedConnection;
reason = query.error === "access_denied" || query.error === "authorization_denied" ? "cancelled" : "failed";
}
await logActivity(db, { companyId: result.companyId, actorType: "user", actorId: userId,
action: reason ? "tailscale.authorization_failed" : "tailscale.connected", entityType: "tailscale_connection", entityId: result.id,
...(reason ? { details: { reason } } : {}),
});
const [company] = await db.select({ prefix: companies.issuePrefix }).from(companies).where(eq(companies.id, result.companyId));
res.setHeader("Cache-Control", "no-store");
res.setHeader("Referrer-Policy", "no-referrer");
const params = new URLSearchParams({ tailscale_connection: result.id, ...(reason ? { tailscale_error: reason } : {}) });
res.redirect(303, `/${encodeURIComponent(company!.prefix)}/apps/tailscale?${params}`);
});
return router;
}
@@ -27,6 +27,23 @@ describe("Cloud connector enrollment return path", () => {
);
});
it.each(["APP", "QA / Apps"])("returns Tailscale enrollment to the verified company once: %s", (prefix) => {
expect(cloudConnectorEnrollmentReturnPath(prefix, "/apps/tailscale")).toBe(
`/${encodeURIComponent(prefix)}/apps/tailscale?cloud_connector=enrolled`,
);
});
it.each([
"https://evil.example/apps/tailscale",
"//evil.example/apps/tailscale",
"/OTHER/apps/tailscale",
"/apps/tailscale/unknown",
])("rejects an untrusted Tailscale enrollment destination: %s", (returnTo) => {
expect(cloudConnectorEnrollmentReturnPath("APP", returnTo)).toBe(
"/APP/apps/connections?cloud_connector=enrolled",
);
});
it("rejects external and unrelated enrollment return paths", () => {
expect(cloudConnectorEnrollmentReturnPath("APP", "https://evil.example/apps/connect")).toBe(
"/APP/apps/connections?cloud_connector=enrolled",
+3 -2
View File
@@ -86,6 +86,7 @@ import {
startPaperclipCloudConnectorEnrollment,
} from "../services/paperclip-cloud-connector-enrollment.js";
import { reconcilePaperclipCloudConnectorEnrollmentStatus } from "../services/paperclip-cloud-connector-status.js";
import { paperclipCloudEnrollmentPrincipal } from "../services/paperclip-cloud-connector-principal.js";
import {
OAUTH_CLIENT_ID_METADATA_DOCUMENT_PATH,
oauthClientIdMetadataDocument,
@@ -209,7 +210,7 @@ function normalizeCloudConnectorEnrollmentReturnTo(returnTo?: string | null): st
const parsed = new URL(returnTo, "http://paperclip.local");
if (
parsed.origin !== "http://paperclip.local"
|| !["/apps/connect", "/apps/chat/connect"].includes(parsed.pathname)
|| !["/apps/connect", "/apps/chat/connect", "/apps/tailscale"].includes(parsed.pathname)
|| parsed.username
|| parsed.password
) return null;
@@ -464,7 +465,7 @@ export function toolAccessRoutes(
}
function connectorEnrollmentPrincipal(req: Request): string {
return req.actor.userId ? `user:${req.actor.userId}` : `source:${req.actor.source ?? "board"}`;
return paperclipCloudEnrollmentPrincipal(req.actor);
}
/**
+6 -1
View File
@@ -10,6 +10,7 @@ import { notifyInstructionCommit } from "./instruction-commit-notifications.js";
import { notifyScheduledRetryCancellation } from "./scheduled-retry-cancellation-notifications.js";
import { notifyChatCompanyConfiguration } from "./chat-channels/configuration-work-notifications.js";
import { chatCompanyDeletion } from "./chat-channels/company-deletion.js";
import { createTailscaleCompanyDeletion } from "./connectors/tailscale/deletion.js";
import { notifyToolConnectionHealth } from "./tool-connection-health-notifications.js";
import { notifyCompanyRetentionWork } from "./retention-work-notifications.js";
import { notifyToolReviewChange } from "./tool-review-work-notifications.js";
@@ -63,13 +64,14 @@ import {
} from "@paperclipai/db";
export async function deleteCompany(db: Db, id: string) {
const tailscaleDeletion = createTailscaleCompanyDeletion();
const lifecycle = createAgentLifecycle(db);
const companyAgents = await db.select({ id: agents.id }).from(agents).where(eq(agents.companyId, id));
for (const agent of companyAgents) {
await lifecycle.terminateAgent(agent.id);
await processAgentLifecycle(db, agent.id);
}
return withAccountHomeSecretMutationLock(undefined, id, () => db.transaction(async (tx) => {
const deleted = await withAccountHomeSecretMutationLock(undefined, id, () => db.transaction(async (tx) => {
// Exclude accounting writers before taking child locks. KEY SHARE must
// remain compatible: native writers can already hold a child row while
// saving a company-scoped result. FOR UPDATE would deadlock that save.
@@ -132,6 +134,7 @@ export async function deleteCompany(db: Db, id: string) {
await tx.delete(approvalComments).where(eq(approvalComments.companyId, id));
await notifyCompanyRetentionWork(tx, id);
await tx.delete(approvals).where(eq(approvals.companyId, id));
await tailscaleDeletion.deleteCompanyData(tx, id);
await tx.delete(companySecrets).where(eq(companySecrets.companyId, id));
await tx.delete(joinRequests).where(eq(joinRequests.companyId, id));
await tx.delete(invites).where(eq(invites.companyId, id));
@@ -159,4 +162,6 @@ export async function deleteCompany(db: Db, id: string) {
.returning();
return rows[0] ?? null;
}));
await tailscaleDeletion.stopNetworks();
return deleted;
}
@@ -0,0 +1,565 @@
import { randomUUID } from "node:crypto";
import { readFile } from "node:fs/promises";
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
import { companies, companySecrets, createDb, tailscaleConnections, type Db } from "@paperclipai/db";
import { eq, sql } from "drizzle-orm";
import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "../../../__tests__/helpers/embedded-postgres.js";
import { tailscaleConnectionService } from "./connections.js";
import type { PaperclipCloudConnector } from "../../paperclip-cloud-connector.js";
import { secretService } from "../../secrets.js";
import { createIsolatedTestHome } from "../../../__tests__/helpers/isolated-test-home.js";
import { tailscaleNetworks } from "./network.js";
import { deleteCompany } from "../../company-deletion.js";
import * as tailscaleDevices from "./devices.js";
import { collectEnvironmentSecretRefs } from "../../environment-config.js";
const support = await getEmbeddedPostgresTestSupport();
describe.skipIf(!support.supported)("durable Tailscale consent state", () => {
let db: Db;
let cleanup: () => Promise<void>;
let companyId: string;
let clock: Date;
let isolatedHome: ReturnType<typeof createIsolatedTestHome>;
let vault: ReturnType<typeof secretService>;
const running = new Set<string>();
const connectNetwork = vi.fn<typeof tailscaleNetworks.connect>();
const disconnectNetwork = vi.fn<typeof tailscaleNetworks.disconnect>();
const startAuthorization = vi.fn();
const claim = vi.fn();
let service: ReturnType<typeof tailscaleConnectionService>;
beforeAll(async () => {
isolatedHome = createIsolatedTestHome();
vi.stubEnv("PAPERCLIP_HOME", isolatedHome.home);
vi.stubEnv("PAPERCLIP_INSTANCE_ID", "tailscale-consent-fixture");
vi.stubEnv("PAPERCLIP_SECRETS_PROVIDER", "local_encrypted");
vi.stubEnv("PAPERCLIP_SECRETS_MASTER_KEY", "a".repeat(64));
const started = await startEmbeddedPostgresTestDatabase("tailscale-connections");
cleanup = started.cleanup;
db = createDb(started.connectionString);
});
afterAll(async () => { await cleanup?.(); vi.unstubAllEnvs(); isolatedHome?.cleanup(); });
beforeEach(async () => {
companyId = randomUUID();
clock = new Date("2020-01-01T00:00:00Z");
await db.insert(companies).values({ id: companyId, name: "Tailscale fixture", issuePrefix: randomUUID().slice(0, 8).toUpperCase() });
startAuthorization.mockReset().mockImplementation(async () => ({ authorizationUrl: "https://login.tailscale.com/a/oauth_authorize", expiresAt: new Date(clock.getTime() + 600_000).toISOString() }));
claim.mockReset().mockRejectedValue(new Error("simulated broker failure"));
vault = secretService(db);
running.clear();
connectNetwork.mockReset().mockImplementation(async input => {
await input.reload?.();
running.add(input.identity);
await input.persist("fixture-enrolled-node-state");
return "/private/tailscale-fixture/socket";
});
disconnectNetwork.mockReset().mockImplementation(async identity => { running.delete(identity); });
service = tailscaleConnectionService(db, { connector: () => ({ startAuthorization, claim }) as unknown as PaperclipCloudConnector, now: () => clock,
secrets: vault, networks: { connect: connectNetwork, disconnect: disconnectNetwork } });
});
async function start(connectionId?: string) {
const result = await service.start({ companyId, userId: "fixture-owner", name: "Home tailnet", connectionId, returnUri: "http://localhost:3100/api/tools/oauth/tailscale/callback" });
const state = startAuthorization.mock.calls.at(-1)![0].returnState as string;
return { result, state };
}
const authorizeCompany = (_: string) => undefined;
function deferred() {
let resolve!: () => void;
const promise = new Promise<void>(done => { resolve = done; });
return { promise, resolve };
}
it.each(["claim", "create", "reload", "connect"] as const)("does not undo disconnect while %s is pending", async phase => {
const { result, state } = await start();
const entered = deferred(), release = deferred();
const grant = { accessToken: "fixture-enrollment-token", accessTokenExpiresAt: new Date(clock.getTime() + 60_000).toISOString() };
claim.mockResolvedValue(grant);
const create = vault.createSystemSecret;
const created = vi.spyOn(vault, "createSystemSecret");
const removed = vi.spyOn(vault, "remove");
const pause = async () => { entered.resolve(); await release.promise; };
if (phase === "claim") claim.mockImplementationOnce(async () => { await pause(); return grant; });
if (phase === "create") {
created.mockImplementationOnce(async (...args) => { const secret = await create(...args); await pause(); return secret; });
}
if (phase === "reload") {
const read = vault.resolveSystemSecretValue;
vi.spyOn(vault, "resolveSystemSecretValue").mockImplementationOnce(async (...args) => { const value = await read(...args); await pause(); return value; });
}
if (phase === "connect") {
const connect = connectNetwork.getMockImplementation()!;
connectNetwork.mockImplementationOnce(async input => { const socket = await connect(input); await pause(); return socket; });
}
const completing = service.complete({ state, userId: "fixture-owner", claimId: "fixture-claim", authorizeCompany });
const resultAfterCompletion = completing.then(value => ({ value, error: null }), error => ({ value: null, error }));
try {
await Promise.race([entered.promise, completing.then(() => { throw new Error("Completion finished before the test pause"); })]);
await service.disconnect(companyId, result.connection.id);
expect(running.size).toBe(0);
} finally { release.resolve(); }
const completed = await resultAfterCompletion;
expect(completed.error).toMatchObject({ status: 422, details: { code: "tailscale_authorization_cancelled" } });
expect((await service.get(companyId, result.connection.id)).status).toBe("disconnected");
expect(running.size).toBe(0);
if (phase === "claim") expect(created).not.toHaveBeenCalled();
for (const call of created.mock.results) {
if (call.type !== "return") continue;
const secret = await call.value;
expect(removed).toHaveBeenCalledWith(secret.id);
const [stored] = await db.select().from(companySecrets).where(eq(companySecrets.id, secret.id));
expect(!stored || stored.status === "deleted").toBe(true);
}
});
it.each(["claim", "connect"] as const)("preserves a newer authorization while an older %s finishes", async phase => {
const { result, state } = await start();
const entered = deferred(), release = deferred();
const grant = { accessToken: "fixture-enrollment-token", accessTokenExpiresAt: new Date(clock.getTime() + 60_000).toISOString() };
claim.mockResolvedValue(grant);
const created = vi.spyOn(vault, "createSystemSecret");
const pause = async () => { entered.resolve(); await release.promise; };
if (phase === "claim") claim.mockImplementationOnce(async () => { await pause(); return grant; });
if (phase === "connect") {
const connect = connectNetwork.getMockImplementation()!;
connectNetwork.mockImplementationOnce(async input => { const socket = await connect(input); await pause(); return socket; });
}
const completing = service.complete({ state, userId: "fixture-owner", claimId: "first-claim", authorizeCompany });
const completed = completing.catch(error => error);
let newerSecretId: string | null = null;
try {
await Promise.race([entered.promise, completing.then(() => { throw new Error("Completion finished before the test pause"); })]);
const newer = await start(result.connection.id);
expect(await service.complete({ state: newer.state, userId: "fixture-owner", claimId: "newer-claim", authorizeCompany })).toMatchObject({ status: "connected" });
newerSecretId = (await service.get(companyId, result.connection.id)).secretId;
expect([...running]).toEqual([`${companyId}:${newerSecretId}`]);
} finally { release.resolve(); }
expect(await completed).toMatchObject({ status: 422, details: { code: "tailscale_authorization_cancelled" } });
expect(await service.get(companyId, result.connection.id)).toMatchObject({ status: "connected", secretId: newerSecretId });
expect([...running]).toEqual([`${companyId}:${newerSecretId}`]);
for (const call of created.mock.results) {
const secret = await call.value;
const [stored] = await db.select().from(companySecrets).where(eq(companySecrets.id, secret.id));
expect(Boolean(stored && stored.status !== "deleted")).toBe(secret.id === newerSecretId);
}
});
it("enrolls once, saves node state, and blocks access after disconnect", async () => {
const { result, state } = await start();
claim.mockResolvedValue({ accessToken: "fixture-enrollment-token", accessTokenExpiresAt: new Date(clock.getTime() + 60_000).toISOString() });
const connected = await service.complete({ state, userId: "fixture-owner", claimId: "fixture-claim", authorizeCompany });
expect(connected).toEqual({ id: result.connection.id, name: "Home tailnet", companyId, status: "connected" });
const row = await service.get(companyId, result.connection.id);
expect(await vault.resolveSystemSecretValue(companyId, row.secretId!, "latest", "tailscale_network", "fixture-network")).toBe("fixture-enrolled-node-state");
expect(row.oauthExpiresAt).toBeNull();
await expect(service.complete({ state, userId: "fixture-owner", claimId: "fixture-claim", authorizeCompany })).rejects.toMatchObject({ status: 400 });
expect(claim).toHaveBeenCalledOnce();
await service.disconnect(companyId, row.id);
await expect(service.environmentBinding(companyId, row.id, "fixture-device")).rejects.toMatchObject({ status: 422, details: { code: "tailscale_reauthorization_required" } });
expect(running.size).toBe(0);
expect(connectNetwork).toHaveBeenCalledOnce();
});
async function enroll() {
const { result, state } = await start();
claim.mockResolvedValue({ accessToken: "fixture-enrollment-token", accessTokenExpiresAt: new Date(clock.getTime() + 60_000).toISOString() });
await service.complete({ state, userId: "fixture-owner", claimId: "fixture-claim", authorizeCompany });
return service.get(companyId, result.connection.id);
}
it("keeps enrolled network state out of generic secret catalogs, bindings, and reads", async () => {
const row = await enroll();
expect((await vault.list(companyId)).map(secret => secret.id)).not.toContain(row.secretId);
await expect(vault.normalizeAdapterConfigForPersistence(companyId, {
env: { ANTHROPIC_AUTH_TOKEN: { type: "secret_ref", secretId: row.secretId!, version: "latest" } },
})).rejects.toMatchObject({ status: 403 });
await expect(vault.resolveSecretValue(companyId, row.secretId!, "latest")).rejects.toMatchObject({ status: 403 });
});
it("binds an SSH environment's private key without projecting its connector credential", async () => {
const row = await enroll();
const sshKey = await vault.create(companyId, { name: "SSH private key", provider: "local_encrypted", value: "fixture-ssh-key" });
const environment = { id: randomUUID(), driver: "ssh" as const, config: {
host: "100.64.0.2", username: "fixture-user", remoteWorkspacePath: "/workspace", network: "tailscale",
tailscaleConnectionId: row.id, tailscaleDeviceId: "fixture-device",
tailscaleAuthKeySecretRef: { type: "secret_ref", secretId: row.secretId!, version: "latest" },
privateKeySecretRef: { type: "secret_ref", secretId: sshKey.id, version: "latest" },
} };
const refs = await collectEnvironmentSecretRefs({ db, environment });
expect(refs).toEqual([{ secretId: sshKey.id, configPath: "privateKeySecretRef", versionSelector: "latest" }]);
await expect(vault.syncSecretRefsForTarget(companyId, { targetType: "environment", targetId: environment.id }, refs)).resolves.toHaveLength(1);
});
it.each(["disconnected", "replaced"] as const)("keeps %s network credentials server-only", async state => {
const row = await enroll();
if (state === "disconnected") await service.disconnect(companyId, row.id);
else {
const newer = await start(row.id);
await service.complete({ state: newer.state, userId: "fixture-owner", claimId: "newer-claim", authorizeCompany });
}
expect((await vault.getById(row.secretId!))?.systemPurpose).toBe("tailscale_network");
expect((await vault.list(companyId)).map(secret => secret.id)).not.toContain(row.secretId);
await expect(vault.resolveSecretValue(companyId, row.secretId!, "latest")).rejects.toMatchObject({ status: 403 });
});
it("backfills existing connector credentials without classifying ordinary company secrets", async () => {
const row = await enroll();
await db.update(companySecrets).set({ systemPurpose: null }).where(eq(companySecrets.id, row.secretId!));
const ordinary = await vault.create(companyId, { name: "Tailscale connection ordinary fixture", provider: "local_encrypted", value: "fixture-ordinary-secret" });
const migration = await readFile(new URL("../../../../../packages/db/src/migrations/0482_aberrant_rumiko_fujikawa.sql", import.meta.url), "utf8");
await db.execute(sql.raw(migration.split("--> statement-breakpoint")[1]!));
expect((await vault.getById(row.secretId!))?.systemPurpose).toBe("tailscale_network");
expect((await vault.getById(ordinary.id))?.systemPurpose).toBeNull();
await expect(vault.resolveSecretValue(companyId, row.secretId!, "latest")).rejects.toMatchObject({ status: 403 });
expect(await vault.resolveSecretValue(companyId, ordinary.id, "latest")).toBe("fixture-ordinary-secret");
});
it.each(["starting", "ready"] as const)("does not stop a %s retry when an older network request fails", async phase => {
const row = await enroll();
const identity = `${companyId}:${row.secretId}`;
const failedClosed = deferred(), rejectFailed = deferred(), retryStarted = deferred(), finishRetry = deferred();
const devices = vi.spyOn(tailscaleDevices, "readTailscaleDevices").mockResolvedValue([
{ id: "fixture-device", name: "Workstation", hostname: "workstation.example.test", os: "linux", address: "100.64.0.2", online: true },
]);
disconnectNetwork.mockClear();
connectNetwork.mockImplementationOnce(async input => {
running.delete(input.identity);
failedClosed.resolve();
await rejectFailed.promise;
throw new Error("fixture failed network client");
}).mockImplementationOnce(async input => {
await input.reload!();
running.add(input.identity);
retryStarted.resolve();
if (phase === "starting") await finishRetry.promise;
return "/private/tailscale-retry/socket";
});
const failed = service.environmentBinding(companyId, row.id, "fixture-device", row.secretId!);
const failure = failed.catch(error => error);
let retry: ReturnType<typeof service.environmentBinding> | undefined;
try {
await Promise.race([failedClosed.promise, failed]);
retry = service.environmentBinding(companyId, row.id, "fixture-device", row.secretId!);
await Promise.race([retryStarted.promise, retry]);
if (phase === "ready") await retry;
rejectFailed.resolve();
expect(await failure).toMatchObject({ message: "fixture failed network client" });
expect([...running]).toEqual([identity]);
expect(disconnectNetwork).not.toHaveBeenCalled();
finishRetry.resolve();
expect(await retry).toMatchObject({ socket: "/private/tailscale-retry/socket", secretId: row.secretId });
} finally {
rejectFailed.resolve(); finishRetry.resolve();
await Promise.allSettled([failure, retry]);
devices.mockRestore();
}
});
async function otherConnection() {
const otherId = randomUUID();
await db.insert(companies).values({ id: otherId, name: "Other tenant", issuePrefix: randomUUID().slice(0, 8).toUpperCase() });
const secret = await vault.create(otherId, { name: "Other network", provider: "local_encrypted", value: "fixture-other-node" });
const [connection] = await db.insert(tailscaleConnections).values({ companyId: otherId, name: "Other network", status: "connected", secretId: secret.id, createdByUserId: "fixture-owner" }).returning();
running.add(`${otherId}:${secret.id}`);
return { companyId: otherId, secret, connection: connection! };
}
it.each(["connected", "disconnected"] as const)("deletes a company with a %s Tailscale connector and stops only its daemon", async status => {
const row = await enroll();
const persist = connectNetwork.mock.calls.at(-1)![0].persist;
if (status === "disconnected") await service.disconnect(companyId, row.id);
const other = await otherConnection();
const stop = vi.spyOn(tailscaleNetworks, "disconnect").mockImplementation(async identity => {
expect(await db.select().from(companies).where(eq(companies.id, companyId))).toHaveLength(0);
await persist("fixture-late-node-state");
running.delete(identity);
});
try {
expect(await deleteCompany(db, companyId)).toMatchObject({ id: companyId });
expect(stop).toHaveBeenCalledWith(`${companyId}:${row.secretId}`, { discardState: true });
expect(await db.select().from(tailscaleConnections).where(eq(tailscaleConnections.companyId, companyId))).toHaveLength(0);
expect(await db.select().from(companySecrets).where(eq(companySecrets.companyId, companyId))).toHaveLength(0);
expect(await db.select().from(tailscaleConnections).where(eq(tailscaleConnections.id, other.connection.id))).toEqual([other.connection]);
expect([...running]).toEqual([`${other.companyId}:${other.secret.id}`]);
} finally { stop.mockRestore(); }
});
it.each(["connected", "disconnected"] as const)("deletes a %s connector secret after stopping and detaching its network", async status => {
const row = await enroll();
const persist = connectNetwork.mock.calls.at(-1)![0].persist;
if (status === "disconnected") await service.disconnect(companyId, row.id);
const other = await otherConnection();
const stop = vi.spyOn(tailscaleNetworks, "disconnect").mockImplementation(async identity => {
expect((await service.get(companyId, row.id)).status).toBe("disconnected");
await persist("fixture-late-node-state");
running.delete(identity);
});
try {
expect(await vault.remove(row.secretId!)).toMatchObject({ id: row.secretId });
expect(stop).toHaveBeenCalledWith(`${companyId}:${row.secretId}`, { discardState: true });
expect(await service.get(companyId, row.id)).toMatchObject({ status: "disconnected", secretId: null,
credentialVersion: null, credentialHash: null, oauthStateHash: null, oauthExpiresAt: null });
expect(await db.select().from(companySecrets).where(eq(companySecrets.id, row.secretId!))).toHaveLength(0);
expect(await db.select().from(tailscaleConnections).where(eq(tailscaleConnections.id, other.connection.id))).toEqual([other.connection]);
expect([...running]).toEqual([`${other.companyId}:${other.secret.id}`]);
} finally { stop.mockRestore(); }
});
it("keeps the connector reference retryable when daemon shutdown fails during secret deletion", async () => {
const row = await enroll();
const stop = vi.spyOn(tailscaleNetworks, "disconnect").mockRejectedValueOnce(new Error("fixture shutdown failed"))
.mockImplementation(async identity => { running.delete(identity); });
try {
await expect(vault.remove(row.secretId!)).rejects.toThrow("fixture shutdown failed");
expect(await service.get(companyId, row.id)).toMatchObject({ status: "disconnected", secretId: row.secretId });
expect(await vault.remove(row.secretId!)).toMatchObject({ id: row.secretId });
expect(stop).toHaveBeenCalledTimes(2);
expect((await service.get(companyId, row.id)).secretId).toBeNull();
expect(running.size).toBe(0);
} finally { stop.mockRestore(); }
});
it("does not stop a company's daemon when its deletion transaction rolls back", async () => {
const row = await enroll();
const transaction = db.transaction.bind(db);
const rollback = vi.spyOn(db, "transaction").mockImplementation(callback => transaction(async tx => {
await callback(tx);
throw new Error("fixture deletion rollback");
}));
const stop = vi.spyOn(tailscaleNetworks, "disconnect");
try {
await expect(deleteCompany(db, companyId)).rejects.toThrow("fixture deletion rollback");
expect(stop).not.toHaveBeenCalled();
expect(await service.get(companyId, row.id)).toEqual(row);
expect(await db.select().from(companySecrets).where(eq(companySecrets.id, row.secretId!))).toHaveLength(1);
expect([...running]).toEqual([`${companyId}:${row.secretId}`]);
} finally { rollback.mockRestore(); stop.mockRestore(); }
});
it("can remove a connector secret through a transactional secret client", async () => {
const row = await enroll();
const stop = vi.spyOn(tailscaleNetworks, "disconnect").mockImplementation(async (identity, options) => {
expect(options).toEqual({ discardState: true });
running.delete(identity);
});
try {
expect(await db.transaction(tx => secretService(tx).remove(row.secretId!))).toMatchObject({ id: row.secretId });
expect((await service.get(companyId, row.id)).secretId).toBeNull();
expect(running.size).toBe(0);
} finally { stop.mockRestore(); }
});
it.each(["company", "secret"] as const)("cancels an in-flight authorization when its %s is deleted", async target => {
const row = await enroll();
const pending = await start(row.id);
const entered = deferred(), release = deferred();
claim.mockImplementationOnce(async () => {
entered.resolve(); await release.promise;
return { accessToken: "fixture-delayed-token", accessTokenExpiresAt: new Date(clock.getTime() + 60_000).toISOString() };
});
const completing = service.complete({ state: pending.state, userId: "fixture-owner", claimId: "delayed-claim", authorizeCompany });
const outcome = completing.catch(error => error);
const stop = vi.spyOn(tailscaleNetworks, "disconnect").mockImplementation(async identity => { running.delete(identity); });
try {
await Promise.race([entered.promise, completing.then(() => { throw new Error("Claim completed before test pause"); })]);
if (target === "company") await deleteCompany(db, companyId);
else await vault.remove(row.secretId!);
release.resolve();
expect(await outcome).toMatchObject({ status: 422, details: { code: "tailscale_authorization_cancelled" } });
expect(running.size).toBe(0);
expect(await db.select().from(companySecrets).where(eq(companySecrets.companyId, companyId))).toHaveLength(0);
} finally { release.resolve(); await outcome; stop.mockRestore(); }
});
it("does not adopt an ordinary member's rotation of a connector secret", async () => {
const row = await enroll();
await vault.rotate(row.secretId!, { value: "tskey-auth-member-chosen-tailnet" }, { userId: "fixture-member" });
const devices = vi.spyOn(tailscaleDevices, "readTailscaleDevices").mockResolvedValue([{ id: "fixture-device", name: "Workstation", hostname: "workstation.example.test", os: "linux", address: "100.64.0.2", online: true }]);
connectNetwork.mockImplementationOnce(async input => {
expect(input.credential).toBe("fixture-enrolled-node-state");
expect(await input.reload!()).toBe("fixture-enrolled-node-state");
return "/private/tailscale-fixture/socket";
});
try { await expect(service.environmentBinding(companyId, row.id, "fixture-device")).resolves.toMatchObject({ host: "100.64.0.2" }); }
finally { devices.mockRestore(); }
});
it("pins the enrollment credential even if a member rotates it before installation", async () => {
const create = vault.createSystemSecret;
const created = vi.spyOn(vault, "createSystemSecret").mockImplementationOnce(async (...args) => {
const secret = await create(...args);
await vault.rotate(secret.id, { value: "tskey-auth-member-chosen-tailnet" }, { userId: "fixture-member" });
return secret;
});
connectNetwork.mockImplementationOnce(async input => {
expect(input.credential).toBe("fixture-enrollment-token");
expect(await input.reload!()).toBe("fixture-enrollment-token");
await input.persist("fixture-enrolled-node-state");
return "/private/tailscale-fixture/socket";
});
try {
const row = await enroll();
expect(row.credentialVersion).toBe(3);
expect(row.credentialHash).toMatch(/^[a-f0-9]{64}$/);
} finally { created.mockRestore(); }
});
it("rejects unpinned or tampered connector credentials before starting a daemon", async () => {
const row = await enroll();
const devices = vi.spyOn(tailscaleDevices, "readTailscaleDevices").mockResolvedValue([]);
const calls = connectNetwork.mock.calls.length;
const read = vi.spyOn(vault, "resolveSystemSecretValue").mockResolvedValueOnce("tskey-auth-member-chosen-tailnet");
try {
await expect(service.environmentBinding(companyId, row.id, "fixture-device")).rejects.toMatchObject({ status: 422, details: { code: "tailscale_credential_untrusted" } });
expect(connectNetwork).toHaveBeenCalledTimes(calls);
read.mockRestore();
await db.update(tailscaleConnections).set({ credentialVersion: null, credentialHash: null }).where(eq(tailscaleConnections.id, row.id));
await expect(service.environmentBinding(companyId, row.id, "fixture-device")).rejects.toMatchObject({ status: 422, details: { code: "tailscale_credential_untrusted" } });
expect(connectNetwork).toHaveBeenCalledTimes(calls);
expect(devices).not.toHaveBeenCalled();
} finally { read.mockRestore(); devices.mockRestore(); }
});
it("keeps the last trusted state readable while a new trusted version is being saved", async () => {
const row = await enroll();
const input = connectNetwork.mock.calls[0]![0];
const entered = deferred(), release = deferred();
const rotate = vault.rotate;
const rotating = vi.spyOn(vault, "rotate").mockImplementationOnce(async (...args) => {
const value = await rotate(...args); entered.resolve(); await release.promise; return value;
});
const saving = input.persist("fixture-next-node-state");
const settled = saving.catch(() => undefined);
try {
await entered.promise;
expect(await input.reload!()).toBe("fixture-enrolled-node-state");
await input.persist("fixture-newer-node-state");
expect(await input.reload!()).toBe("fixture-newer-node-state");
release.resolve();
await saving;
expect(await input.reload!()).toBe("fixture-newer-node-state");
} finally { release.resolve(); await settled; rotating.mockRestore(); }
});
it("closes the old network client when replacing a connected authorization", async () => {
const { result, state } = await start();
claim.mockResolvedValue({ accessToken: "fixture-enrollment-token", accessTokenExpiresAt: new Date(clock.getTime() + 60_000).toISOString() });
await service.complete({ state, userId: "fixture-owner", claimId: "first-claim", authorizeCompany });
const previous = await service.get(companyId, result.connection.id);
const next = await start(previous.id);
expect(next.result.connection.status).toBe("connected");
expect([...running]).toEqual([`${companyId}:${previous.secretId}`]);
await service.complete({ state: next.state, userId: "fixture-owner", claimId: "next-claim", authorizeCompany });
const current = await service.get(companyId, previous.id);
expect(current.secretId).not.toBe(previous.secretId);
expect(disconnectNetwork).toHaveBeenCalledWith(`${companyId}:${previous.secretId}`);
expect([...running]).toEqual([`${companyId}:${current.secretId}`]);
await service.disconnect(companyId, current.id);
expect(running.size).toBe(0);
});
it.each([
["disconnected", "credential read"], ["replaced", "credential read"],
["disconnected", "device discovery"], ["replaced", "device discovery"],
] as const)("rejects runtime access %s during %s", async (state, phase) => {
const { result, state: consentState } = await start();
claim.mockResolvedValue({ accessToken: "fixture-enrollment-token", accessTokenExpiresAt: new Date(clock.getTime() + 60_000).toISOString() });
await service.complete({ state: consentState, userId: "fixture-owner", claimId: "first-claim", authorizeCompany });
const original = await service.get(companyId, result.connection.id);
const entered = deferred(), release = deferred();
const inventory = [{ id: "fixture-device", name: "Fixture", hostname: "fixture.example.test", address: "100.64.0.2", os: "linux", online: true }];
const devices = vi.spyOn(tailscaleDevices, "readTailscaleDevices").mockResolvedValue(inventory);
expect(await service.environmentBinding(companyId, original.id, "fixture-device", original.secretId!)).toEqual({
host: "100.64.0.2", secretId: original.secretId, socket: "/private/tailscale-fixture/socket",
});
const read = vault.resolveSystemSecretValue;
const credential = vi.spyOn(vault, "resolveSystemSecretValue");
if (phase === "credential read") credential.mockImplementationOnce(async (...args) => {
const value = await read(...args); entered.resolve(); await release.promise; return value;
});
else devices.mockImplementationOnce(async () => { entered.resolve(); await release.promise; return inventory; });
const resolving = service.environmentBinding(companyId, original.id, "fixture-device", original.secretId!);
const outcome = resolving.then(value => ({ value, error: null }), error => ({ value: null, error }));
let activeSecretId: string | null = null;
try {
await Promise.race([entered.promise, resolving.then(() => { throw new Error("Runtime resolved before device discovery"); })]);
if (state === "disconnected") await service.disconnect(companyId, original.id);
else {
const newer = await start(original.id);
await service.complete({ state: newer.state, userId: "fixture-owner", claimId: "newer-claim", authorizeCompany });
activeSecretId = (await service.get(companyId, original.id)).secretId;
}
} finally { release.resolve(); }
try {
expect((await outcome).error).toMatchObject({ status: 422, details: { code: "tailscale_reauthorization_required" } });
expect([...running]).toEqual(activeSecretId ? [`${companyId}:${activeSecretId}`] : []);
const calls = connectNetwork.mock.calls.length;
await expect(service.environmentBinding(companyId, original.id, "fixture-device", original.secretId!)).rejects.toMatchObject({ status: 422 });
expect(connectNetwork).toHaveBeenCalledTimes(calls);
} finally { devices.mockRestore(); credential.mockRestore(); }
});
it("removes failed enrollment credentials even when daemon cleanup reports an error", async () => {
const { result, state } = await start();
claim.mockResolvedValue({ accessToken: "fixture-enrollment-token", accessTokenExpiresAt: new Date(clock.getTime() + 60_000).toISOString() });
const created = vi.spyOn(vault, "createSystemSecret");
connectNetwork.mockRejectedValueOnce(new Error("startup failed"));
disconnectNetwork.mockRejectedValueOnce(new Error("shutdown state save failed"));
await expect(service.complete({ state, userId: "fixture-owner", claimId: "fixture-claim", authorizeCompany })).rejects.toMatchObject({
errors: [expect.objectContaining({ message: "startup failed" }), expect.objectContaining({ message: "shutdown state save failed" })],
});
expect(await service.get(companyId, result.connection.id)).toMatchObject({ status: "disconnected", secretId: null });
const secret = await created.mock.results[0]!.value;
const [stored] = await db.select().from(companySecrets).where(eq(companySecrets.id, secret.id));
expect(!stored || stored.status === "deleted").toBe(true);
expect(running.size).toBe(0);
await expect(service.complete({ state, userId: "fixture-owner", claimId: "fixture-claim", authorizeCompany })).rejects.toMatchObject({ status: 400 });
});
it("binds OAuth to a company and user and stores only a digest of browser state", async () => {
const { result, state } = await start();
expect(startAuthorization).toHaveBeenCalledWith(expect.objectContaining({ subject: "fixture-owner", companyId, profile: "tailscale.tailnet", returnState: state }));
const [stored] = await db.select().from(tailscaleConnections).where(eq(tailscaleConnections.id, result.connection.id));
expect(stored!.oauthStateHash).toHaveLength(64);
expect(JSON.stringify(stored)).not.toContain(state);
expect(await service.list(companyId)).toEqual([expect.objectContaining({ id: result.connection.id, name: "Home tailnet", status: "pending" })]);
expect(JSON.stringify(await service.list(companyId))).not.toContain("oauthStateHash");
await expect(service.get(randomUUID(), result.connection.id)).rejects.toMatchObject({ status: 404 });
});
it("rejects another user without consuming the owner's state", async () => {
const { result, state } = await start();
await expect(service.complete({ state, userId: "another-user", claimId: "fixture-claim", authorizeCompany })).rejects.toMatchObject({ status: 400 });
expect((await service.get(companyId, result.connection.id)).oauthStateHash).toBeTruthy();
expect(claim).not.toHaveBeenCalled();
});
it("rejects expired consent before contacting the broker", async () => {
const { state } = await start();
clock = new Date(clock.getTime() + 11 * 60_000);
await expect(service.complete({ state, userId: "fixture-owner", claimId: "fixture-claim", authorizeCompany })).rejects.toMatchObject({ status: 400 });
expect(claim).not.toHaveBeenCalled();
});
it("consumes a denial once and never exchanges credentials", async () => {
const { result, state } = await start();
const authorize = vi.fn(authorizeCompany);
await expect(service.complete({ state, userId: "fixture-owner", error: "authorization_denied", authorizeCompany: authorize })).rejects.toMatchObject({ status: 400 });
expect(authorize).toHaveBeenCalledExactlyOnceWith(companyId, result.connection.id);
await expect(service.complete({ state, userId: "fixture-owner", claimId: "fixture-claim", authorizeCompany })).rejects.toMatchObject({ status: 400 });
expect(claim).not.toHaveBeenCalled();
});
it("rechecks current company authorization before exchanging credentials", async () => {
const { state } = await start();
await expect(service.complete({ state, userId: "fixture-owner", claimId: "fixture-claim", authorizeCompany: () => { throw new Error("membership revoked"); } })).rejects.toThrow("membership revoked");
expect(claim).not.toHaveBeenCalled();
});
it("disconnect invalidates a pending callback", async () => {
const { result, state } = await start();
expect(await service.disconnect(companyId, result.connection.id)).toMatchObject({ status: "disconnected" });
await expect(service.complete({ state, userId: "fixture-owner", claimId: "fixture-claim", authorizeCompany })).rejects.toMatchObject({ status: 400 });
expect(claim).not.toHaveBeenCalled();
});
it("allows only one competing callback to attempt redemption", async () => {
const { state } = await start();
await Promise.allSettled([1, 2].map(() => service.complete({ state, userId: "fixture-owner", claimId: "fixture-claim", authorizeCompany })));
expect(claim).toHaveBeenCalledOnce();
});
});
@@ -0,0 +1,178 @@
import { createHash, randomBytes } from "node:crypto";
import { and, eq, gt, isNull } from "drizzle-orm";
import { tailscaleConnections, type Db } from "@paperclipai/db";
import { badRequest, notFound, unprocessable } from "../../../errors.js";
import { createPaperclipCloudConnector, paperclipCloudConnectorConfigFromEnv, type PaperclipCloudConnector } from "../../paperclip-cloud-connector.js";
import { secretService } from "../../secrets.js";
import { getConfiguredSecretProvider } from "../../../secrets/configured-provider.js";
import { tailscaleNetworks } from "./network.js";
import { readTailscaleDevices } from "./devices.js";
import { createTailscalePairing } from "./pairing.js";
const hash = (state: string) => createHash("sha256").update(state).digest("hex");
const projection = (row: typeof tailscaleConnections.$inferSelect) => ({ id: row.id, name: row.name, status: row.status, companyId: row.companyId });
export function tailscaleConnectionService(db: Db, dependencies: {
connector?: () => PaperclipCloudConnector | null;
now?: () => Date;
secrets?: Pick<ReturnType<typeof secretService>, "create" | "createSystemSecret" | "resolveSystemSecretValue" | "rotate" | "remove">;
networks?: Pick<typeof tailscaleNetworks, "connect" | "disconnect">;
} = {}) {
const secrets = dependencies.secrets ?? secretService(db);
const networks = dependencies.networks ?? tailscaleNetworks;
const now = dependencies.now ?? (() => new Date());
const connector = () => {
const config = dependencies.connector ? null : paperclipCloudConnectorConfigFromEnv();
const result = dependencies.connector?.() ?? (config ? createPaperclipCloudConnector({ config }) : null);
if (!result) throw unprocessable("Connect this Paperclip instance to Paperclip Cloud before connecting Tailscale.", { code: "tailscale_oauth_unavailable" });
return result;
};
async function get(companyId: string, id: string) {
const [row] = await db.select().from(tailscaleConnections).where(and(eq(tailscaleConnections.id, id), eq(tailscaleConnections.companyId, companyId)));
if (!row) throw notFound("Tailscale connection not found");
return row;
}
const cancelled = () => unprocessable("Tailscale authorization was cancelled or replaced. Connect again.", { code: "tailscale_authorization_cancelled" });
async function open(companyId: string, id: string, attempt?: { secretId: string; stateHash: string }, expectedSecretId?: string) {
const assertExpected = (row: typeof tailscaleConnections.$inferSelect) => {
if (expectedSecretId !== undefined && (row.secretId !== expectedSecretId || row.status !== "connected")) {
throw unprocessable("Reconnect Tailscale and save this environment again.", { code: "tailscale_reauthorization_required" });
}
};
const row = await get(companyId, id);
assertExpected(row);
if (!row.secretId || (row.status !== "connected" && row.status !== "connecting")) {
if (attempt) throw cancelled();
throw unprocessable("Connect Tailscale before using this environment.", { code: "tailscale_reauthorization_required" });
}
const secretId = row.secretId;
const current = async () => {
const latest = await get(companyId, id);
assertExpected(latest);
if (latest.secretId !== secretId || (latest.status !== "connected" && latest.status !== "connecting")
|| (attempt && (attempt.secretId !== secretId || latest.oauthStateHash !== attempt.stateHash || latest.oauthExpiresAt !== null))) throw cancelled();
return latest;
};
const untrusted = () => unprocessable("Reconnect Tailscale to verify this network credential.", { code: "tailscale_credential_untrusted" });
const trusted = (saved: typeof tailscaleConnections.$inferSelect) => {
if (typeof saved.credentialVersion !== "number" || !Number.isInteger(saved.credentialVersion) || saved.credentialVersion < 1
|| typeof saved.credentialHash !== "string" || !/^[a-f0-9]{64}$/.test(saved.credentialHash)) throw untrusted();
return { version: saved.credentialVersion, hash: saved.credentialHash };
};
const read = async () => {
const pinned = trusted(await current());
const value = await secrets.resolveSystemSecretValue(companyId, secretId, pinned.version, "tailscale_network", `tailscale-connection:${id}`);
if (hash(value) !== pinned.hash) throw untrusted();
return value;
};
const credential = await read();
const socket = await networks.connect({
identity: `${companyId}:${secretId}`, credential, reload: read,
persist: async value => {
const [latest] = await db.select().from(tailscaleConnections).where(and(eq(tailscaleConnections.id, id), eq(tailscaleConnections.companyId, companyId)));
if (!latest || latest.secretId !== secretId || (latest.status !== "connected" && latest.status !== "connecting")) return;
const pinned = trusted(latest);
const saved = await secrets.rotate(secretId, { value });
await db.update(tailscaleConnections).set({ credentialVersion: saved.latestVersion, credentialHash: hash(value), updatedAt: now() })
.where(and(eq(tailscaleConnections.id, id), eq(tailscaleConnections.companyId, companyId), eq(tailscaleConnections.secretId, secretId),
eq(tailscaleConnections.credentialVersion, pinned.version), eq(tailscaleConnections.credentialHash, pinned.hash)));
},
});
return { row: await current(), socket, assertCurrent: current };
}
return {
get,
async disconnect(companyId: string, id: string) {
const [row] = await db.update(tailscaleConnections).set({ status: "disconnected", oauthStateHash: randomBytes(32).toString("hex"), oauthExpiresAt: null, updatedAt: now() })
.where(and(eq(tailscaleConnections.id, id), eq(tailscaleConnections.companyId, companyId))).returning();
if (!row) throw notFound("Tailscale connection not found");
if (row.secretId) await networks.disconnect(`${companyId}:${row.secretId}`);
return { ...projection(row), status: "disconnected" };
},
async list(companyId: string) {
return (await db.select().from(tailscaleConnections).where(eq(tailscaleConnections.companyId, companyId))).map(projection);
},
async start(input: { companyId: string; userId: string; name: string; returnUri: string; connectionId?: string }) {
const client = connector();
const state = randomBytes(32).toString("base64url");
const expires = new Date(now().getTime() + 10 * 60_000);
const row = input.connectionId ? await get(input.companyId, input.connectionId)
: (await db.insert(tailscaleConnections).values({ companyId: input.companyId, name: input.name, createdByUserId: input.userId }).returning())[0]!;
const [started] = await db.update(tailscaleConnections).set({ oauthStateHash: hash(state), oauthExpiresAt: expires, createdByUserId: input.userId,
status: row.status === "connected" ? "connected" : "pending", updatedAt: now() }).where(and(eq(tailscaleConnections.id, row.id), eq(tailscaleConnections.companyId, input.companyId),
row.oauthStateHash === null ? isNull(tailscaleConnections.oauthStateHash) : eq(tailscaleConnections.oauthStateHash, row.oauthStateHash))).returning();
if (!started) throw cancelled();
if (started.status === "pending" && started.secretId) await networks.disconnect(`${input.companyId}:${started.secretId}`);
const session = await client.startAuthorization({ subject: input.userId, companyId: input.companyId, profile: "tailscale.tailnet", returnUri: input.returnUri, returnState: state });
return { connection: projection(started), ...session };
},
async complete(input: { state: string; userId: string; claimId?: string; error?: string; authorizeCompany: (companyId: string, connectionId: string) => void }) {
if (!/^[A-Za-z0-9_-]{43}$/.test(input.state)) throw badRequest("Tailscale authorization expired. Connect again.");
const stateHash = hash(input.state);
const [row] = await db.update(tailscaleConnections).set({ oauthExpiresAt: null, updatedAt: now() }).where(and(
eq(tailscaleConnections.oauthStateHash, stateHash), eq(tailscaleConnections.createdByUserId, input.userId), gt(tailscaleConnections.oauthExpiresAt, now()),
)).returning();
if (!row) throw badRequest("Tailscale authorization expired. Connect again.");
const owned = and(eq(tailscaleConnections.id, row.id), eq(tailscaleConnections.companyId, row.companyId),
eq(tailscaleConnections.oauthStateHash, stateHash), isNull(tailscaleConnections.oauthExpiresAt));
let secretId: string | null = null;
try {
input.authorizeCompany(row.companyId, row.id);
if (input.error || !input.claimId) throw badRequest("Tailscale authorization did not complete. Connect again.");
const grant = await connector().claim({ subject: input.userId, companyId: row.companyId, profile: "tailscale.tailnet", claimId: input.claimId, redemptionId: input.state });
const expires = grant.accessTokenExpiresAt ? Date.parse(grant.accessTokenExpiresAt) : NaN;
if (grant.refreshToken || !Number.isFinite(expires) || expires <= now().getTime()) throw unprocessable("Tailscale authorization expired. Connect again.");
const [active] = await db.select({ id: tailscaleConnections.id }).from(tailscaleConnections).where(owned);
if (!active) throw cancelled();
const secret = await secrets.createSystemSecret(row.companyId, { name: `Tailscale connection ${row.id} ${randomBytes(4).toString("hex")}`,
provider: getConfiguredSecretProvider(), value: grant.accessToken }, "tailscale_network", { userId: input.userId });
secretId = secret.id;
const [installed] = await db.update(tailscaleConnections).set({ secretId, credentialVersion: secret.latestVersion, credentialHash: hash(grant.accessToken), status: "connecting", updatedAt: now() }).where(owned).returning();
if (!installed) throw cancelled();
if (row.secretId && row.secretId !== secretId) await networks.disconnect(`${row.companyId}:${row.secretId}`);
await open(row.companyId, row.id, { secretId, stateHash });
const [ready] = await db.update(tailscaleConnections).set({ status: "connected", updatedAt: now() })
.where(and(owned, eq(tailscaleConnections.secretId, secretId), eq(tailscaleConnections.status, "connecting"))).returning();
if (!ready) throw cancelled();
return projection(ready);
} catch (error) {
const cleanupErrors: unknown[] = [];
if (secretId) {
for (const clean of [
() => networks.disconnect(`${row.companyId}:${secretId}`),
() => db.update(tailscaleConnections).set({ secretId: null, credentialVersion: null, credentialHash: null, updatedAt: now() }).where(and(
eq(tailscaleConnections.id, row.id), eq(tailscaleConnections.companyId, row.companyId), eq(tailscaleConnections.secretId, secretId!),
)),
() => secrets.remove(secretId!),
]) { try { await clean(); } catch (failure) { cleanupErrors.push(failure); } }
}
try {
await db.update(tailscaleConnections).set({ oauthStateHash: randomBytes(32).toString("hex"), oauthExpiresAt: null, ...(secretId ? { status: "disconnected" } : {}), updatedAt: now() }).where(owned);
} catch (failure) { cleanupErrors.push(failure); }
if (cleanupErrors.length) throw new AggregateError([error, ...cleanupErrors], "Tailscale authorization cleanup failed");
throw error;
}
},
async devices(companyId: string, id: string) {
return readTailscaleDevices((await open(companyId, id)).socket);
},
async pairing(companyId: string, id: string, deviceId: string, port: number, userId: string) {
const { socket } = await open(companyId, id);
const device = (await readTailscaleDevices(socket)).find(device => device.id === deviceId);
if (!device) throw unprocessable("Choose a machine on this tailnet before pairing.");
return createTailscalePairing({ vault: secrets, provider: getConfiguredSecretProvider(), companyId, connectionId: id, deviceId, address: device.address, port, userId });
},
async environmentBinding(companyId: string, id: string, deviceId: string, expectedSecretId?: string) {
const { row, socket, assertCurrent } = await open(companyId, id, undefined, expectedSecretId);
const device = (await readTailscaleDevices(socket)).find(device => device.id === deviceId);
await assertCurrent();
if (!device) throw unprocessable("This machine is no longer available on the connected tailnet.", { code: "tailscale_machine_unavailable" });
if (!device.online) throw unprocessable("Your machine is offline. Wake it and retry the task.", { code: "tailscale_machine_offline" });
return { host: device.address, secretId: row.secretId!, socket };
},
};
}
@@ -0,0 +1,30 @@
import { and, eq } from "drizzle-orm";
import { tailscaleConnections, type Db } from "@paperclipai/db";
import type { CompanyDeletionParticipant } from "../../../lib/company-deletion.js";
import { tailscaleNetworks } from "./network.js";
export function createTailscaleCompanyDeletion(): CompanyDeletionParticipant & { stopNetworks(): Promise<void> } {
const identities = new Set<string>();
return {
async deleteCompanyData(tx, companyId) {
const rows = await tx.delete(tailscaleConnections).where(eq(tailscaleConnections.companyId, companyId))
.returning({ secretId: tailscaleConnections.secretId });
for (const row of rows) if (row.secretId) identities.add(`${companyId}:${row.secretId}`);
},
async stopNetworks() {
const results = await Promise.allSettled([...identities].map(identity => tailscaleNetworks.disconnect(identity, { discardState: true })));
const errors = results.flatMap(result => result.status === "rejected" ? [result.reason] : []);
if (errors.length) throw new AggregateError(errors, "Tailscale company network cleanup failed");
},
};
}
export async function retireTailscaleSecret(db: Pick<Db, "update">, companyId: string, secretId: string): Promise<void> {
const matching = and(eq(tailscaleConnections.companyId, companyId), eq(tailscaleConnections.secretId, secretId));
const rows = await db.update(tailscaleConnections).set({ status: "disconnected", oauthStateHash: null,
oauthExpiresAt: null, updatedAt: new Date() }).where(matching).returning({ id: tailscaleConnections.id });
if (!rows.length) return;
await tailscaleNetworks.disconnect(`${companyId}:${secretId}`, { discardState: true });
await db.update(tailscaleConnections).set({ secretId: null, credentialVersion: null, credentialHash: null,
updatedAt: new Date() }).where(matching);
}
@@ -0,0 +1,21 @@
import { describe, expect, it } from "vitest";
import { parseTailscaleDevices } from "./devices.js";
describe("Tailscale machine discovery", () => {
it("uses stable device IDs and preserves offline status without exposing peer metadata", () => {
expect(parseTailscaleDevices({ BackendState: "Running", Peer: {
a: { ID: "device-1", HostName: "Home Mac", DNSName: "home.example.ts.net.", TailscaleIPs: ["100.64.0.1"], OS: "macOS", Online: true, UserID: "private-user", PublicKey: "private-peer-metadata" },
b: { ID: "device-2", HostName: "Workstation", TailscaleIPs: ["100.64.0.2"], OS: "linux", Online: false },
invalid: { ID: "missing-address", TailscaleIPs: ["; shell command"] },
} })).toEqual([
{ id: "device-1", name: "Home Mac", hostname: "home.example.ts.net", address: "100.64.0.1", os: "macOS", online: true },
{ id: "device-2", name: "Workstation", hostname: "100.64.0.2", address: "100.64.0.2", os: "linux", online: false },
]);
});
it("requires a running authenticated connector and never substitutes the host machine's tailnet", () => {
for (const status of [null, {}, { BackendState: "NeedsLogin" }, { BackendState: "Stopped" }]) {
expect(() => parseTailscaleDevices(status)).toThrow("Reconnect Tailscale");
}
expect(parseTailscaleDevices({ BackendState: "Running" })).toEqual([]);
});
});
@@ -0,0 +1,28 @@
import { execFile } from "node:child_process";
import { isIP } from "node:net";
import { promisify } from "node:util";
import { unprocessable } from "../../../errors.js";
export type TailscaleDevice = { id: string; name: string; hostname: string; address: string; os: string; online: boolean };
export function parseTailscaleDevices(value: unknown): TailscaleDevice[] {
if (!value || typeof value !== "object" || !("BackendState" in value) || value.BackendState !== "Running") {
throw unprocessable("Reconnect Tailscale to view your machines.", { code: "tailscale_reauthorization_required" });
}
const peers = "Peer" in value && value.Peer && typeof value.Peer === "object" ? Object.values(value.Peer) : [];
return peers.flatMap((peer): TailscaleDevice[] => {
if (!peer || typeof peer !== "object" || typeof peer.ID !== "string" || !peer.ID) return [];
const address = Array.isArray(peer.TailscaleIPs) ? peer.TailscaleIPs.find((ip: unknown) => typeof ip === "string" && isIP(ip)) : undefined;
if (typeof address !== "string") return [];
const hostname = typeof peer.DNSName === "string" ? peer.DNSName.replace(/\.$/, "") : address;
return [{ id: peer.ID, name: typeof peer.HostName === "string" ? peer.HostName : hostname,
hostname, address, os: typeof peer.OS === "string" ? peer.OS : "unknown", online: peer.Online === true }];
}).sort((a, b) => a.name.localeCompare(b.name));
}
export async function readTailscaleDevices(socket: string): Promise<TailscaleDevice[]> {
const { stdout } = await promisify(execFile)(process.env.PAPERCLIP_TAILSCALE_CLI ?? "tailscale", [`--socket=${socket}`, "status", "--json"], {
timeout: 5000, maxBuffer: 2 * 1024 * 1024,
});
return parseTailscaleDevices(JSON.parse(stdout));
}
@@ -0,0 +1,291 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { promises as fs } from "node:fs";
import os from "node:os";
import path from "node:path";
import { createTailscaleNetworkManager, tailscaleNetworks } from "./network.js";
function deferred() {
let resolve!: () => void;
const promise = new Promise<void>(done => { resolve = done; });
return { promise, resolve };
}
describe("Tailscale environment network process boundary", () => {
let dir: string;
let manager: ReturnType<typeof createTailscaleNetworkManager>;
beforeEach(async () => {
dir = await fs.mkdtemp(path.join(os.tmpdir(), "paperclip-tailnet-test-"));
const daemon = path.join(dir, "tailscaled");
const cli = path.join(dir, "tailscale");
await fs.writeFile(daemon, `#!/usr/bin/env node
const fs = require('node:fs');
const path = require('node:path');
const socket = process.argv.find(arg => arg.startsWith('--socket=')).slice('--socket='.length);
fs.writeFileSync(path.join(path.dirname(socket), 'pid'), String(process.pid), { mode: 0o600 });
process.on('SIGTERM', () => process.exit(0));
setInterval(() => {}, 1000);
`, { mode: 0o700 });
await fs.writeFile(cli, `#!/usr/bin/env node
const fs = require('node:fs');
const path = require('node:path');
const args = process.argv.slice(2);
const dir = path.dirname(args[0].slice('--socket='.length));
const state = path.join(dir, 'state');
fs.appendFileSync(${JSON.stringify(path.join(dir, "calls"))}, JSON.stringify(args) + '\\n');
if (!fs.existsSync(path.join(dir, 'pid'))) process.exit(4);
if (args[1] === 'up') {
const key = args.find(a => a.startsWith('--auth-key=file:'));
if (key) {
const file = key.slice('--auth-key=file:'.length);
if ((fs.statSync(file).mode & 0o777) !== 0o600) process.exit(2);
if (!fs.readFileSync(file, 'utf8').startsWith('tskey-auth-')) process.exit(3);
fs.writeFileSync(state, JSON.stringify({ MachineKey: 'fixture-node-state' }), { mode: 0o600 });
}
} else if (args[1] === 'status') {
console.log(JSON.stringify({ BackendState: fs.existsSync(state) ? 'Running' : 'NeedsLogin' }));
}
`, { mode: 0o700 });
manager = createTailscaleNetworkManager({ daemon, cli });
});
afterEach(async () => { await manager.close(); vi.unstubAllEnvs(); await fs.rm(dir, { recursive: true, force: true }); });
it("uses executable settings loaded after the shared manager was imported", async () => {
vi.stubEnv("PAPERCLIP_TAILSCALE_CLI", path.join(dir, "tailscale"));
vi.stubEnv("PAPERCLIP_TAILSCALED", path.join(dir, "tailscaled"));
manager = tailscaleNetworks;
const socket = await manager.connect({ identity: "late-config", credential: "tskey-auth-fixture", persist: async () => {} });
expect((await fs.stat(path.dirname(socket))).isDirectory()).toBe(true);
expect(await fs.readFile(path.join(dir, "calls"), "utf8")).toContain('"up"');
});
it("uses a private key file, coalesces connections, and saves node state before use", async () => {
const persist = vi.fn().mockResolvedValue(undefined);
const input = { identity: "company:connection", credential: "tskey-auth-fixture", persist };
const [socket, sameSocket] = await Promise.all([manager.connect(input), manager.connect(input)]);
expect(socket).toBe(sameSocket);
expect((await fs.stat(path.dirname(socket))).mode & 0o777).toBe(0o700);
expect(persist).toHaveBeenCalledOnce();
const state = persist.mock.calls[0][0] as string;
expect(state).toMatch(/^paperclip-tailscale-state-v1:/);
expect(Buffer.from(state.split(":")[1], "base64").toString()).toContain("fixture-node-state");
expect(await manager.connect({ ...input, credential: state })).toBe(socket);
const calls = await fs.readFile(path.join(dir, "calls"), "utf8");
expect(calls).not.toContain(input.credential);
expect(calls).toContain("--auth-key=file:");
await expect(fs.stat(path.join(path.dirname(socket), "key"))).rejects.toThrow();
await manager.close();
await expect(fs.stat(path.dirname(socket))).rejects.toThrow();
});
it("restores an identity after a process restart without using the single-use key again", async () => {
const persist = vi.fn().mockResolvedValue(undefined);
await manager.connect({ identity: "same-connection", credential: "tskey-auth-fixture", persist });
const credential = persist.mock.calls[0][0] as string;
await manager.close();
await fs.writeFile(path.join(dir, "calls"), "");
await manager.connect({ identity: "same-connection", credential, persist });
expect(await fs.readFile(path.join(dir, "calls"), "utf8")).not.toContain("--auth-key");
});
it("retires a daemon without waiting for a shutdown state write blocked by secret deletion", async () => {
const entered = deferred(), release = deferred(), finished = deferred();
let persisting = false;
const persist = vi.fn(async () => {
if (persist.mock.calls.length === 2) { persisting = true; entered.resolve(); await release.promise; finished.resolve(); }
});
const identity = "retired-connection";
const socket = await manager.connect({ identity, credential: "tskey-auth-fixture", persist });
const remoteDir = path.dirname(socket);
const pid = Number(await fs.readFile(path.join(remoteDir, "pid"), "utf8"));
await fs.writeFile(path.join(remoteDir, "state"), JSON.stringify({ MachineKey: "fixture-updated-state" }));
const closing = manager.disconnect(identity);
try {
await Promise.race([entered.promise, closing.then(() => { throw new Error("Shutdown did not enter persistence"); })]);
await manager.disconnect(identity, { discardState: true });
expect(() => process.kill(pid, 0)).toThrow(expect.objectContaining({ code: "ESRCH" }));
await expect(fs.stat(remoteDir)).rejects.toMatchObject({ code: "ENOENT" });
} finally { release.resolve(); if (persisting) await finished.promise; await closing; }
});
it("fails closed if state cannot be stored, cleans up, and allows retry", async () => {
const persist = vi.fn().mockRejectedValueOnce(new Error("vault unavailable")).mockResolvedValue(undefined);
const input = { identity: "retry", credential: "tskey-auth-fixture", persist };
await expect(manager.connect(input)).rejects.toThrow("Tailscale could not connect");
const calls = (await fs.readFile(path.join(dir, "calls"), "utf8")).trim().split("\n").map(line => JSON.parse(line));
await expect(fs.stat(path.dirname(calls[0][0].slice("--socket=".length)))).rejects.toThrow();
await expect(manager.connect(input)).resolves.toContain("/paperclip-ts-");
});
it("does not mix identities and never exposes a failed credential", async () => {
const persist = vi.fn().mockResolvedValue(undefined);
const one = await manager.connect({ identity: "company-one", credential: "tskey-auth-fixture", persist });
const two = await manager.connect({ identity: "company-two", credential: "tskey-auth-fixture", persist });
expect(one).not.toBe(two);
await expect(manager.connect({ identity: "invalid", credential: "sensitive-invalid-key", persist })).rejects.toThrow("Tailscale could not connect");
await expect(manager.connect({ identity: "invalid", credential: "tskey-auth-fixed", persist })).resolves.toContain("/paperclip-ts-");
});
it.each([false, true])("keeps the current daemon when an older credential read resumes (replacement during reload=%s)", async replaceDuringReload => {
const state = (name: string) => "paperclip-tailscale-state-v1:" + Buffer.from(JSON.stringify({ MachineKey: name })).toString("base64");
const oldCredential = state("old-fixture-state");
let credential = state("current-fixture-state");
const persist = vi.fn().mockResolvedValue(undefined);
const input = { identity: "stale-read", credential, persist };
let currentSocket = await manager.connect(input);
const currentPid = Number(await fs.readFile(path.join(path.dirname(currentSocket), "pid"), "utf8"));
const loading = deferred();
const release = deferred();
const snapshot = credential;
const reload = vi.fn(async () => {
if (reload.mock.calls.length === 1) { loading.resolve(); await release.promise; return snapshot; }
return credential;
});
const connecting = manager.connect({ ...input, credential: oldCredential, reload });
const settled = connecting.catch(() => undefined);
try {
await loading.promise;
expect(() => process.kill(currentPid, 0)).not.toThrow();
await expect(fs.stat(path.dirname(currentSocket))).resolves.toBeDefined();
if (replaceDuringReload) {
credential = state("newer-fixture-state");
currentSocket = await manager.connect({ ...input, credential });
}
const latestPid = Number(await fs.readFile(path.join(path.dirname(currentSocket), "pid"), "utf8"));
release.resolve();
expect(await connecting).toBe(currentSocket);
expect(reload).toHaveBeenCalledTimes(replaceDuringReload ? 2 : 1);
expect(() => process.kill(latestPid, 0)).not.toThrow();
await expect(fs.stat(path.dirname(currentSocket))).resolves.toBeDefined();
const calls = (await fs.readFile(path.join(dir, "calls"), "utf8")).trim().split("\n").map(line => JSON.parse(line));
expect(calls.filter(args => args[1] === "up")).toHaveLength(replaceDuringReload ? 2 : 1);
} finally {
release.resolve();
await settled;
}
});
it("does not let a ready-daemon reload cross manager shutdown", async () => {
const state = (name: string) => "paperclip-tailscale-state-v1:" + Buffer.from(JSON.stringify({ MachineKey: name })).toString("base64");
const input = { identity: "reload-shutdown", credential: state("current-fixture-state"), persist: async () => undefined };
await manager.connect(input);
const loading = deferred();
const release = deferred();
const connecting = manager.connect({ ...input, credential: state("stale-fixture-state"),
reload: async () => { loading.resolve(); await release.promise; return input.credential; } });
const assertion = expect(connecting).rejects.toThrow("Tailscale");
try {
await loading.promise;
await manager.close();
const socket = await manager.connect({ ...input, credential: state("new-generation-fixture-state") });
const pid = Number(await fs.readFile(path.join(path.dirname(socket), "pid"), "utf8"));
release.resolve();
await assertion;
expect(() => process.kill(pid, 0)).not.toThrow();
await expect(fs.stat(path.dirname(socket))).resolves.toBeDefined();
const calls = (await fs.readFile(path.join(dir, "calls"), "utf8")).trim().split("\n").map(line => JSON.parse(line));
expect(calls.filter(args => args[1] === "up")).toHaveLength(2);
} finally {
release.resolve();
await connecting.catch(() => undefined);
}
});
it("handles a missing daemon without leaving a pending connection", async () => {
const missing = createTailscaleNetworkManager({ daemon: path.join(dir, "missing") });
await expect(missing.connect({ identity: "missing", credential: "tskey-auth-fixture", persist: async () => undefined })).rejects.toThrow("Tailscale could not connect");
await missing.close();
});
it("cancels startup before the daemon is launched", async () => {
const connecting = manager.connect({ identity: "cancel", credential: "tskey-auth-fixture", persist: async () => undefined });
const assertion = expect(connecting).rejects.toThrow("Tailscale could not connect");
await manager.close();
await assertion;
await expect(fs.stat(path.join(dir, "calls"))).rejects.toThrow();
});
it("waits for a stopped daemon's state write before reconnecting with current credentials", async () => {
const saving = deferred();
const release = deferred();
let credential = "tskey-auth-fixture";
let writes = 0;
const persist = vi.fn(async (value: string) => {
writes += 1;
if (writes === 2) {
saving.resolve();
await release.promise;
}
credential = value;
});
const reload = vi.fn(async () => credential);
const input = { identity: "closing", credential, persist, reload };
const socket = await manager.connect(input);
const staleCredential = credential;
await fs.writeFile(path.join(path.dirname(socket), "state"), JSON.stringify({ MachineKey: "rotated-fixture-state" }));
const pid = Number(await fs.readFile(path.join(path.dirname(socket), "pid"), "utf8"));
process.kill(pid, "SIGTERM");
await saving.promise;
let settled = false;
const reconnect = manager.connect({ ...input, credential: staleCredential }).then(value => { settled = true; return value; });
try {
await new Promise<void>(resolve => setImmediate(resolve));
expect(settled).toBe(false);
expect(reload).toHaveBeenCalledTimes(1);
} finally { release.resolve(); }
const nextSocket = await reconnect;
expect(nextSocket).not.toBe(socket);
expect(reload).toHaveBeenCalledTimes(2);
expect(JSON.parse(await fs.readFile(path.join(path.dirname(nextSocket), "state"), "utf8"))).toEqual({ MachineKey: "rotated-fixture-state" });
await expect(fs.stat(path.dirname(socket))).rejects.toThrow();
});
it("coalesces callers whose credential was refreshed while startup was pending", async () => {
const loading = deferred();
const release = deferred();
const credential = "paperclip-tailscale-state-v1:" + Buffer.from(JSON.stringify({ MachineKey: "current-fixture-state" })).toString("base64");
const reload = vi.fn(async () => { loading.resolve(); await release.promise; return credential; });
const input = { identity: "refresh-startup", credential: "tskey-auth-fixture", reload, persist: async () => undefined };
const first = manager.connect(input);
await loading.promise;
const second = manager.connect({ ...input, credential });
const pair = Promise.all([first, second]);
release.resolve();
const [one, two] = await pair;
expect(one).toBe(two);
expect(reload).toHaveBeenCalledOnce();
});
it.each(["disconnect", "close"] as const)("%s cancels startup while the credential provider is still loading", async operation => {
const loading = deferred();
const release = deferred();
const connecting = manager.connect({ identity: "cancel-load", credential: "tskey-auth-fixture", persist: async () => undefined,
reload: async () => { loading.resolve(); await release.promise; return "tskey-auth-fixture"; } });
const assertion = expect(connecting).rejects.toThrow("Tailscale could not connect");
await loading.promise;
if (operation === "disconnect") await manager.disconnect("cancel-load");
else await manager.close();
release.resolve();
await assertion;
await expect(fs.stat(path.join(dir, "calls"))).rejects.toThrow();
});
it("does not restart a queued reconnect after manager shutdown", async () => {
const saving = deferred();
const release = deferred();
let writes = 0;
const persist = vi.fn(async () => { writes += 1; if (writes === 2) { saving.resolve(); await release.promise; } });
const input = { identity: "stop-reconnect", credential: "tskey-auth-fixture", persist };
const socket = await manager.connect(input);
await fs.writeFile(path.join(path.dirname(socket), "state"), JSON.stringify({ MachineKey: "changed-fixture-state" }));
process.kill(Number(await fs.readFile(path.join(path.dirname(socket), "pid"), "utf8")), "SIGTERM");
await saving.promise;
const assertion = expect(manager.connect(input)).rejects.toThrow("Tailscale stopped");
const stopping = manager.close();
release.resolve();
await stopping;
await assertion;
const calls = (await fs.readFile(path.join(dir, "calls"), "utf8")).trim().split("\n").map(line => JSON.parse(line));
expect(calls.filter(args => args[1] === "up")).toHaveLength(1);
});
});
@@ -0,0 +1,171 @@
import { execFile, spawn, type ChildProcess } from "node:child_process";
import { promises as fs } from "node:fs";
import os from "node:os";
import path from "node:path";
import { promisify } from "node:util";
const exec = promisify(execFile);
const STATE_PREFIX = "paperclip-tailscale-state-v1:";
const MAX_STATE_BYTES = 2 * 1024 * 1024;
export function isTailscaleNodeState(value: string): boolean {
return value.startsWith(STATE_PREFIX);
}
type Connection = { credential: string; savedCredential?: string; child?: ChildProcess; closed: boolean; discardState: AbortController; closing?: Promise<void>; ready: Promise<string>; close: () => Promise<void> };
export function createTailscaleNetworkManager(commands: { cli?: string; daemon?: string } = {}) {
const connections = new Map<string, Connection>();
let generation = 0;
async function connect(input: {
identity: string;
credential: string;
persist: (credential: string) => Promise<void>;
reload?: () => Promise<string>;
}, expectedGeneration = generation): Promise<string> {
if (expectedGeneration !== generation) throw new Error("Tailscale stopped");
const existing = connections.get(input.identity);
if (existing?.closing) { await existing.closing; return connect(input, expectedGeneration); }
if (existing && (existing.credential === input.credential || existing.savedCredential === input.credential)) return existing.ready;
if (existing && !existing.savedCredential) { await existing.ready.catch(() => undefined); return connect(input, expectedGeneration); }
if (existing) {
const credential = input.reload ? await input.reload() : input.credential;
if (expectedGeneration !== generation) throw new Error("Tailscale stopped");
if (connections.get(input.identity) !== existing || existing.closing) {
return connect({ ...input, credential }, expectedGeneration);
}
if (existing.credential === credential || existing.savedCredential === credential) return existing.ready;
await existing.close();
return connect({ ...input, credential }, expectedGeneration);
}
const connection: Connection = {
credential: input.credential,
closed: false,
discardState: new AbortController(),
ready: Promise.resolve(""),
close: async () => {
connection.closed = true;
if (connections.get(input.identity) === connection) connections.delete(input.identity);
},
};
connections.set(input.identity, connection);
connection.ready = (async () => {
const credential = input.reload ? await input.reload() : input.credential;
if (connection.closed) throw new Error("Tailscale stopped");
connection.credential = credential;
return start({ ...input, credential }, connection);
})().catch(async () => {
await connection.close().catch(() => undefined);
if (connections.get(input.identity) === connection) connections.delete(input.identity);
throw new Error("Tailscale could not connect. Reconnect Tailscale and check its access policy.");
});
return connection.ready;
}
async function start(input: { identity: string; credential: string; persist: (credential: string) => Promise<void> }, connection: Connection) {
const restored = isTailscaleNodeState(input.credential);
const state = restored ? Buffer.from(input.credential.slice(STATE_PREFIX.length), "base64") : null;
if (state && (state.length > MAX_STATE_BYTES || !state.length)) throw new Error("Invalid state");
if (state) JSON.parse(state.toString("utf8"));
if (!restored && (!input.credential || input.credential.length > 4096 || /\s/.test(input.credential))) throw new Error("Invalid authorization token");
let dir: string | undefined;
let statePath: string | undefined;
connection.close = () => connection.closing ??= (async () => {
connection.closed = true;
const child = connection.child;
if (child?.pid && child.exitCode === null && child.signalCode === null) {
await new Promise<void>((resolve) => {
const timeout = setTimeout(() => { child.kill("SIGKILL"); }, 2_000);
child.once("exit", () => { clearTimeout(timeout); resolve(); });
child.kill("SIGTERM");
});
}
try {
if (!connection.discardState.signal.aborted && connection.savedCredential && statePath) {
const bytes = await fs.readFile(statePath);
if (bytes.length && bytes.length <= MAX_STATE_BYTES) {
const latest = STATE_PREFIX + bytes.toString("base64");
if (latest !== connection.savedCredential) {
const signal = connection.discardState.signal;
let discard!: () => void;
const discarded = new Promise<void>(resolve => { discard = resolve; });
signal.addEventListener("abort", discard, { once: true });
try {
// Deletion can hold the vault lock needed by a pending state flush.
if (!signal.aborted) await Promise.race([input.persist(latest), discarded]);
if (!signal.aborted) connection.savedCredential = latest;
} finally { signal.removeEventListener("abort", discard); }
}
}
}
} finally {
if (dir) await fs.rm(dir, { recursive: true, force: true });
if (connections.get(input.identity) === connection) connections.delete(input.identity);
}
})();
dir = await fs.mkdtemp(path.join(os.platform() === "win32" ? os.tmpdir() : "/tmp", "paperclip-ts-"));
if (connection.closed) { await fs.rm(dir, { recursive: true, force: true }); throw new Error("Tailscale stopped"); }
await fs.chmod(dir, 0o700);
const socket = path.join(dir, "socket");
statePath = path.join(dir, "state");
const keyPath = path.join(dir, "key");
if (state) await fs.writeFile(statePath, state, { mode: 0o600 });
if (connection.closed) throw new Error("Tailscale stopped");
const daemonCommand = commands.daemon ?? (process.env.PAPERCLIP_TAILSCALED?.trim() || "tailscaled");
const cliCommand = commands.cli ?? (process.env.PAPERCLIP_TAILSCALE_CLI?.trim() || "tailscale");
const child = spawn(daemonCommand, ["--tun=userspace-networking", "--port=0", `--socket=${socket}`, `--state=${statePath}`, `--statedir=${dir}`], {
stdio: "ignore",
});
connection.child = child;
let failed = false;
child.once("error", () => { failed = true; });
child.once("exit", () => { failed = true; void connection.close().catch(() => undefined); });
const cli = async (args: string[], timeout = 5_000) => {
if (failed || connection.closed) throw new Error("Tailscale stopped");
return exec(cliCommand, [`--socket=${socket}`, ...args], { timeout, maxBuffer: MAX_STATE_BYTES });
};
const deadline = Date.now() + 5_000;
for (;;) {
try { await cli(["status", "--json"]); break; } catch {
if (failed || connection.closed || Date.now() >= deadline) throw new Error("Tailscale startup timed out");
await new Promise((resolve) => setTimeout(resolve, 100));
}
}
if (!restored) await fs.writeFile(keyPath, input.credential, { mode: 0o600 });
try {
await cli(["up", "--accept-dns=false", "--accept-routes=false", "--shields-up", "--timeout=30s",
`--hostname=paperclip-${input.identity.replace(/[^a-z0-9]/gi, "").slice(-16)}`,
...(!restored ? [`--auth-key=file:${keyPath}`] : [])], 35_000);
} finally {
await fs.rm(keyPath, { force: true });
}
const status = JSON.parse((await cli(["status", "--json"])).stdout);
if (status.BackendState !== "Running") throw new Error("Tailscale requires authorization");
const nextState = await fs.readFile(statePath);
if (!nextState.length || nextState.length > MAX_STATE_BYTES) throw new Error("Invalid state");
const saved = STATE_PREFIX + nextState.toString("base64");
if (saved !== input.credential) await input.persist(saved);
connection.savedCredential = saved;
if (failed || connection.closed) throw new Error("Tailscale stopped");
return socket;
}
return {
connect: (input: Parameters<typeof connect>[0]) => connect(input),
async disconnect(identity: string, options: { discardState?: boolean } = {}) {
const connection = connections.get(identity);
if (!connection) return;
if (options.discardState) connection.discardState.abort();
await connection.close();
},
async close() {
generation += 1;
await Promise.all([...connections.values()].map((connection) => connection.close()));
},
};
}
export const tailscaleNetworks = createTailscaleNetworkManager();
@@ -0,0 +1,115 @@
import { execFile } from "node:child_process";
import { mkdir, mkdtemp, readFile, writeFile, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { promisify } from "node:util";
import { expect, it, vi } from "vitest";
import { createTailscalePairing } from "./pairing.js";
it("creates a real SSH key in the vault and returns only an id and public pairing command", async () => {
const dir = await mkdtemp(join(tmpdir(), "paperclip-pairing-test-"));
let saved: any;
let count = 0;
const vault = {
getByName: vi.fn(async () => saved ?? null),
create: vi.fn(async (_company: string, input: any) => { saved = { ...input, id: `fixture-private-key-ref-${++count}` }; return saved; }),
};
const input = { vault: vault as any, provider: "local_encrypted" as const, companyId: "fixture-company", connectionId: "fixture-connection", deviceId: "fixture-device", address: "100.64.0.1", port: 2222, userId: "fixture-user" };
try {
const result = await createTailscalePairing(input);
expect(saved.value).toContain("BEGIN OPENSSH PRIVATE KEY");
expect(result.privateKeySecretId).toBe("fixture-private-key-ref-1");
expect(JSON.stringify(result)).not.toContain("PRIVATE KEY");
expect(result.command).toContain("[100.64.0.1]:2222");
expect(result.command).toContain('>> "$HOME/.ssh/authorized_keys"');
const file = join(dir, "key");
await writeFile(file, saved.value, { mode: 0o600 });
const publicKey = (await promisify(execFile)("ssh-keygen", ["-y", "-f", file], { timeout: 5000 })).stdout.trim();
expect(result.publicKey).toBe(publicKey);
const next = await createTailscalePairing(input);
expect(next.privateKeySecretId).not.toBe(result.privateKeySecretId);
expect(next.publicKey).not.toBe(result.publicKey);
expect(vault.create).toHaveBeenCalledTimes(2);
expect(vault.getByName).not.toHaveBeenCalled();
await expect(createTailscalePairing({ ...input, address: "host; command" })).rejects.toThrow("valid Tailscale machine");
} finally { await rm(dir, { recursive: true, force: true }); }
});
it("does not install a public key substituted into mutable vault metadata", async () => {
let memberKey: any;
const input = { provider: "local_encrypted" as const, companyId: "fixture-company", connectionId: "fixture-connection",
deviceId: "fixture-device", address: "100.64.0.1", port: 22, userId: "fixture-user" };
const member = await createTailscalePairing({ ...input, vault: {
getByName: vi.fn(async () => null),
create: vi.fn(async (_company: string, secret: any) => { memberKey = secret; return { ...secret, id: "member-owned-key" }; }),
} as any });
const substituted = member.publicKey;
const vault = {
getByName: vi.fn(async () => ({ ...memberKey, id: "substituted-key", providerMetadata: { sshPublicKey: substituted } })),
create: vi.fn(async (_company: string, input: any) => ({ ...input, id: "new-pairing-key", providerMetadata: { sshPublicKey: substituted } })),
};
const result = await createTailscalePairing({ ...input, vault: vault as any });
expect(result.privateKeySecretId).toBe("new-pairing-key");
expect(result.publicKey).not.toBe(substituted);
expect(result.command).not.toContain(substituted);
expect(vault.create).toHaveBeenCalledOnce();
expect(vault.getByName).not.toHaveBeenCalled();
});
it.each(["", "ssh-ed25519 existing-key", "ssh-ed25519 existing-key\n"])("preserves existing authorized_keys and appends a separate key (existing=%j)", async existing => {
const dir = await mkdtemp(join(tmpdir(), "paperclip-pairing-command-test-"));
const vault = {
getByName: vi.fn(async () => null),
create: vi.fn(async (_company: string, input: any) => ({ ...input, id: "new-pairing-key" })),
};
try {
const result = await createTailscalePairing({ vault: vault as any, provider: "local_encrypted", companyId: "fixture-company", connectionId: "fixture-connection",
deviceId: "fixture-device", address: "100.64.0.1", port: 22, userId: "fixture-user" });
const hostKey = join(dir, "ssh_host_ed25519_key.pub");
await writeFile(hostKey, "ssh-ed25519 fixture-host-key\n");
await mkdir(join(dir, ".ssh"));
const authorizedKeys = join(dir, ".ssh", "authorized_keys");
await writeFile(authorizedKeys, existing);
const command = result.command.replaceAll("/etc/ssh/", `${dir}/`);
await promisify(execFile)("/bin/sh", ["-c", command], { env: { ...process.env, HOME: dir }, timeout: 5000 });
const expected = existing + (existing && !existing.endsWith("\n") ? "\n" : "") + result.publicKey + "\n";
expect(await readFile(authorizedKeys, "utf8")).toBe(expected);
await promisify(execFile)("/bin/sh", ["-c", command], { env: { ...process.env, HOME: dir }, timeout: 5000 });
expect(await readFile(authorizedKeys, "utf8")).toBe(expected);
} finally { await rm(dir, { recursive: true, force: true }); }
});
it.each(["ecdsa", "rsa", "all"] as const)("prints trusted known-hosts entries for available %s host keys", async kind => {
const dir = await mkdtemp(join(tmpdir(), "paperclip-pairing-host-keys-"));
const vault = { create: vi.fn(async (_company: string, input: any) => ({ ...input, id: "new-pairing-key" })) };
const algorithms = { ed25519: "ssh-ed25519", ecdsa: "ecdsa-sha2-nistp256", rsa: "ssh-rsa" };
const keys: (keyof typeof algorithms)[] = kind === "all" ? ["ed25519", "ecdsa", "rsa"] : [kind];
try {
const result = await createTailscalePairing({ vault: vault as any, provider: "local_encrypted", companyId: "fixture-company", connectionId: "fixture-connection",
deviceId: "fixture-device", address: "100.64.0.1", port: 2222, userId: "fixture-user" });
const publicKeys = keys.map(key => `${algorithms[key]} fixture-${key}-host-key`);
for (let index = 0; index < keys.length; index++) {
await writeFile(join(dir, `ssh_host_${keys[index]}_key.pub`), publicKeys[index]! + "\n");
}
const { stdout } = await promisify(execFile)("/bin/sh", ["-c", result.command.replaceAll("/etc/ssh/", `${dir}/`)], { env: { ...process.env, HOME: dir }, timeout: 5000 });
expect(stdout.split("Known hosts:\n")[1]).toBe(publicKeys.map(key => `[100.64.0.1]:2222 ${key}\n`).join(""));
expect(await readFile(join(dir, ".ssh", "authorized_keys"), "utf8")).toBe(result.publicKey + "\n");
} finally { await rm(dir, { recursive: true, force: true }); }
});
it("fails before editing authorized_keys when no supported SSH host public key exists", async () => {
const dir = await mkdtemp(join(tmpdir(), "paperclip-pairing-no-host-key-"));
const vault = { create: vi.fn(async (_company: string, input: any) => ({ ...input, id: "new-pairing-key" })) };
try {
const result = await createTailscalePairing({ vault: vault as any, provider: "local_encrypted", companyId: "fixture-company", connectionId: "fixture-connection",
deviceId: "fixture-device", address: "100.64.0.1", port: 22, userId: "fixture-user" });
await mkdir(join(dir, ".ssh"));
const authorizedKeys = join(dir, ".ssh", "authorized_keys");
const existing = "ssh-ed25519 fixture-existing-key";
await writeFile(authorizedKeys, existing);
const outcome = await promisify(execFile)("/bin/sh", ["-c", result.command.replaceAll("/etc/ssh/", `${dir}/`)], { env: { ...process.env, HOME: dir }, timeout: 5000 })
.then(() => null, error => error);
expect(await readFile(authorizedKeys, "utf8")).toBe(existing);
expect(outcome).toMatchObject({ code: 1, stderr: expect.stringContaining("SSH host public key") });
} finally { await rm(dir, { recursive: true, force: true }); }
});
@@ -0,0 +1,54 @@
import { execFile } from "node:child_process";
import { createHash, randomUUID } from "node:crypto";
import { mkdtemp, readFile, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { promisify } from "node:util";
import { isIP } from "node:net";
import type { secretService } from "../../secrets.js";
import type { SecretProvider } from "@paperclipai/shared";
import { unprocessable } from "../../../errors.js";
type Vault = Pick<ReturnType<typeof secretService>, "create">;
const quote = (value: string) => "'" + value.replaceAll("'", "'\"'\"'") + "'";
async function generateKeyPair() {
const dir = await mkdtemp(join(tmpdir(), "paperclip-ts-pairing-"));
try {
const file = join(dir, "key");
await promisify(execFile)("ssh-keygen", ["-q", "-t", "ed25519", "-N", "", "-C", "paperclip-tailscale", "-f", file], { timeout: 5000, maxBuffer: 4096 });
const [privateKey, publicKey] = await Promise.all([readFile(file, "utf8"), readFile(file + ".pub", "utf8")]);
return { privateKey, publicKey: publicKey.trim() };
} finally { await rm(dir, { recursive: true, force: true }); }
}
export async function createTailscalePairing(input: {
vault: Vault; provider: SecretProvider; companyId: string; connectionId: string; deviceId: string;
address: string; port: number; userId: string;
}) {
if (!isIP(input.address) || !Number.isInteger(input.port) || input.port < 1 || input.port > 65535) throw unprocessable("Choose a valid Tailscale machine and SSH port.");
const fingerprint = createHash("sha256").update(input.connectionId + ":" + input.deviceId).digest("hex").slice(0, 16);
const { privateKey, publicKey } = await generateKeyPair();
if (!/^ssh-ed25519 [A-Za-z0-9+/=]+(?: [^\r\n]*)?$/.test(publicKey)) throw unprocessable("This pairing key is unavailable. Choose a saved SSH key or create a new connection.");
const secret = await input.vault.create(input.companyId, { name: `Tailscale SSH ${fingerprint} ${randomUUID()}`, provider: input.provider, value: privateKey,
providerMetadata: { sshPublicKey: publicKey } }, { userId: input.userId });
const host = input.port === 22 ? input.address : `[${input.address}]:${input.port}`;
const command = [
"(", "set -eu", "umask 077", "set --",
"for host_key in /etc/ssh/ssh_host_ed25519_key.pub /etc/ssh/ssh_host_ecdsa_key.pub /etc/ssh/ssh_host_rsa_key.pub; do",
' if [ -f "$host_key" ] && [ -r "$host_key" ] && [ -s "$host_key" ]; then set -- "$@" "$host_key"; fi', "done",
'if [ "$#" -eq 0 ]; then',
" printf '%s\\n' 'No readable SSH host public key found in /etc/ssh. Configure SSH host keys before pairing.' >&2",
" exit 1", "fi", "mkdir -p \"$HOME/.ssh\"", "chmod 700 \"$HOME/.ssh\"",
`if ! grep -Fqx -- ${quote(publicKey)} "$HOME/.ssh/authorized_keys" 2>/dev/null; then`,
' if [ -s "$HOME/.ssh/authorized_keys" ] && [ -n "$(tail -c 1 "$HOME/.ssh/authorized_keys")" ]; then',
" printf '\\n' >> \"$HOME/.ssh/authorized_keys\"", " fi",
` printf '%s\\n' ${quote(publicKey)} >> "$HOME/.ssh/authorized_keys"`, "fi",
"chmod 600 \"$HOME/.ssh/authorized_keys\"",
"printf '\\nPaperclip username: '; id -un",
"printf '\\nPaperclip workspace: %s/Paperclip\\n' \"$HOME\"",
"printf '\\nKnown hosts:\\n'",
'for host_key in "$@"; do', ` printf '%s %s\\n' ${quote(host)} "$(cat "$host_key")"`, "done", ")",
].join("\n");
return { privateKeySecretId: secret.id, publicKey, command };
}
+64 -33
View File
@@ -1,4 +1,5 @@
import { z } from "zod";
import { tailscaleConnectionService } from "./connectors/tailscale/connections.js";
import { randomUUID } from "node:crypto";
import type { Db } from "@paperclipai/db";
import type {
@@ -39,6 +40,11 @@ const secretRefSchema = z.object({
const sshEnvironmentConfigSchema = z.object({
useHostAuth: z.boolean().optional(),
tailscaleConnectionId: z.string().uuid().optional(),
tailscaleDeviceId: z.string().trim().min(1).max(256).optional(),
network: z.enum(["direct", "tailscale"]).optional(),
tailscaleAuthKey: z.null().optional(),
tailscaleAuthKeySecretRef: secretRefSchema.extend({ version: z.literal("latest").optional().default("latest") }).optional().nullable(),
host: z.string({ error: "SSH environments require a host." }).trim().min(1, "SSH environments require a host."),
port: z.coerce.number().int().min(1).max(65535).default(22),
username: z.string({ error: "SSH environments require a username." }).trim().min(1, "SSH environments require a username."),
@@ -69,6 +75,16 @@ const sshEnvironmentConfigProbeSchema = sshEnvironmentConfigSchema.extend({
const sshEnvironmentConfigPersistenceSchema = sshEnvironmentConfigProbeSchema;
function assertTailscaleSelection(config: Record<string, unknown>) {
if (!config.tailscaleConnectionId || !config.tailscaleDeviceId || config.network !== "tailscale" || config.tailscaleAuthKey) {
throw unprocessable("Connect Tailscale and select a machine before saving this environment.");
}
}
function validateTailscaleSelection(config: Record<string, unknown>) {
if (config.network === "tailscale" || config.tailscaleConnectionId !== undefined || config.tailscaleDeviceId !== undefined) assertTailscaleSelection(config);
}
const fakeSandboxEnvironmentConfigSchema = z.object({
provider: z.literal("fake").default("fake"),
image: z
@@ -376,12 +392,9 @@ export async function collectEnvironmentSecretRefs(input: {
environment: Pick<Environment, "id" | "driver" | "config">;
}): Promise<Array<{ secretId: string; configPath: string; versionSelector?: SecretVersionSelector }>> {
const parsed = parseEnvironmentDriverConfig(input.environment);
if (parsed.driver === "ssh" && parsed.config.privateKeySecretRef) {
return [{
secretId: parsed.config.privateKeySecretRef.secretId,
configPath: "privateKeySecretRef",
versionSelector: parsed.config.privateKeySecretRef.version ?? "latest",
}];
if (parsed.driver === "ssh") {
const binding = parsed.config.privateKeySecretRef;
return binding ? [{ secretId: binding.secretId, configPath: "privateKeySecretRef", versionSelector: binding.version ?? "latest" }] : [];
}
if (parsed.driver === "sandbox" && parsed.config.provider !== "fake") {
const schema = await getSandboxProviderConfigSchema(input.db, parsed.config.provider);
@@ -445,6 +458,7 @@ export function normalizeEnvironmentConfig(input: {
}
if (input.driver === "ssh") {
validateTailscaleSelection(parseObject(input.config));
const parsed = sshEnvironmentConfigSchema.safeParse(parseObject(input.config));
if (!parsed.success) {
throw unprocessable(toErrorMessage(parsed.error), {
@@ -491,6 +505,7 @@ export function normalizeEnvironmentConfigForProbe(input: {
pluginWorkerManager?: PluginWorkerManager;
}): Promise<Record<string, unknown>> | Record<string, unknown> {
if (input.driver === "ssh") {
validateTailscaleSelection(parseObject(input.config));
const parsed = sshEnvironmentConfigProbeSchema.safeParse(parseObject(input.config));
if (!parsed.success) {
throw unprocessable(toErrorMessage(parsed.error), {
@@ -556,7 +571,12 @@ export async function normalizeEnvironmentConfigForPersistence(input: {
pluginWorkerManager?: PluginWorkerManager;
}): Promise<Record<string, unknown>> {
if (input.driver === "ssh") {
const parsed = sshEnvironmentConfigPersistenceSchema.safeParse(parseObject(input.config));
const raw = { ...parseObject(input.config) };
if (raw.network === "direct") {
for (const field of ["tailscaleConnectionId", "tailscaleDeviceId", "tailscaleAuthKeySecretRef", "tailscaleAuthKey"]) delete raw[field];
}
validateTailscaleSelection(raw);
const parsed = sshEnvironmentConfigPersistenceSchema.safeParse(raw);
if (!parsed.success) {
throw unprocessable(toErrorMessage(parsed.error), {
issues: parsed.error.issues,
@@ -564,6 +584,11 @@ export async function normalizeEnvironmentConfigForPersistence(input: {
}
const secrets = secretService(input.db);
const { privateKey, ...stored } = parsed.data;
if (stored.tailscaleConnectionId) {
const binding = await tailscaleConnectionService(input.db).environmentBinding(input.companyId, stored.tailscaleConnectionId, stored.tailscaleDeviceId!);
stored.host = binding.host;
stored.tailscaleAuthKeySecretRef = { type: "secret_ref", secretId: binding.secretId, version: "latest" };
}
let nextPrivateKeySecretRef = stored.privateKeySecretRef;
if (privateKey) {
nextPrivateKeySecretRef = await createEnvironmentSecret({
@@ -586,6 +611,7 @@ export async function normalizeEnvironmentConfigForPersistence(input: {
return {
...stored,
...(input.operation === "create" ? { useHostAuth: stored.useHostAuth ?? false } : {}),
...(stored.tailscaleAuthKeySecretRef ? { tailscaleAuthKey: null } : {}),
privateKey: null,
privateKeySecretRef: nextPrivateKeySecretRef,
} satisfies SshEnvironmentConfig;
@@ -673,34 +699,38 @@ export async function resolveEnvironmentDriverConfigForRuntime(
const parsed = parseEnvironmentDriverConfig(environment);
const secrets = secretService(db);
const environmentId = environment.id;
if (parsed.driver === "ssh" && parsed.config.privateKeySecretRef && !environmentId) {
throw unprocessable("Runtime secret resolution requires an environment id");
}
if (parsed.driver === "ssh" && parsed.config.privateKeySecretRef) {
if (!companyId) {
throw unprocessable("Runtime secret resolution requires a companyId context");
if (parsed.driver === "ssh") {
const config = { ...parsed.config };
const connectionService = config.tailscaleConnectionId ? tailscaleConnectionService(db) : null;
if (connectionService) {
if (!companyId) throw unprocessable("Tailscale requires a company context.");
const connection = await connectionService.get(companyId, config.tailscaleConnectionId!);
if (!connection.secretId || connection.status !== "connected" || connection.secretId !== config.tailscaleAuthKeySecretRef?.secretId) {
throw unprocessable("Reconnect Tailscale and save this environment again.", { code: "tailscale_reauthorization_required" });
}
}
return {
driver: "ssh",
config: {
...parsed.config,
privateKey: await secrets.resolveSecretValue(
companyId,
parsed.config.privateKeySecretRef.secretId,
parsed.config.privateKeySecretRef.version ?? "latest",
{
consumerType: "environment",
consumerId: environmentId!,
actorType: "system",
actorId: null,
issueId: context?.issueId ?? null,
heartbeatRunId: context?.heartbeatRunId ?? null,
configPath: "privateKeySecretRef",
},
),
},
const bindingContext = (configPath: string) => {
if (!environmentId || !companyId) throw unprocessable("Runtime secret resolution requires an environment and company context");
return { consumerType: "environment" as const, consumerId: environmentId,
actorType: "system" as const, actorId: null, issueId: context?.issueId ?? null,
heartbeatRunId: context?.heartbeatRunId ?? null, configPath };
};
if (config.privateKeySecretRef) {
const binding = config.privateKeySecretRef;
config.privateKey = await secrets.resolveSecretValue(companyId!, binding.secretId,
binding.version ?? "latest", bindingContext("privateKeySecretRef"));
}
if (config.network === "tailscale" && !context?.readOnlyInspection) {
const binding = config.tailscaleAuthKeySecretRef;
if (!binding) throw unprocessable("Connect Tailscale before running tasks in this environment.");
bindingContext("tailscaleAuthKeySecretRef");
if (!connectionService) throw unprocessable("Connect Tailscale and select a machine before running tasks.");
const connection = await connectionService.environmentBinding(companyId!, config.tailscaleConnectionId!, config.tailscaleDeviceId!, binding.secretId);
config.host = connection.host;
config.tailscaleIdentity = `${companyId}:${connection.secretId}`;
config.tailscaleSocket = connection.socket;
}
return { driver: "ssh", config };
}
if (parsed.driver === "sandbox" && parsed.config.provider !== "fake") {
@@ -807,6 +837,7 @@ export function parseEnvironmentDriverConfig(
}
if (environment.driver === "ssh") {
validateTailscaleSelection(parseObject(environment.config));
const parsed = sshEnvironmentConfigSchema.parse(parseObject(environment.config));
return {
driver: "ssh",
@@ -707,6 +707,7 @@ export async function resolveEnvironmentExecutionTarget(input: {
privateKey: parsed.config.privateKey,
knownHosts: parsed.config.knownHosts,
strictHostKeyChecking: parsed.config.strictHostKeyChecking,
...(parsed.config.tailscaleSocket ? { tailscaleSocket: parsed.config.tailscaleSocket, tailscaleIdentity: parsed.config.tailscaleIdentity } : {}),
remoteCwd,
},
};
+4
View File
@@ -284,6 +284,10 @@ export async function probeEnvironment(
});
}
if (parsed.config.network === "tailscale" && !parsed.config.tailscaleSocket) {
return { ok: false, driver: "ssh", summary: "Save the Tailscale environment before testing its connection.", details: null };
}
try {
const { remoteCwd } = await ensureSshWorkspaceReady(parsed.config);
@@ -0,0 +1,9 @@
import { expect, it } from "vitest";
import { paperclipCloudEnrollmentPrincipal } from "./paperclip-cloud-connector-principal.js";
it("uses the same enrollment principal namespace for users and local board actors", () => {
expect(paperclipCloudEnrollmentPrincipal({ userId: "fixture-user", source: "session" })).toBe("user:fixture-user");
expect(paperclipCloudEnrollmentPrincipal({ source: "local_implicit" })).toBe("source:local_implicit");
expect(paperclipCloudEnrollmentPrincipal({ userId: "source:local_implicit" })).toBe("user:source:local_implicit");
expect(paperclipCloudEnrollmentPrincipal({})).toBe("source:board");
});
@@ -0,0 +1,3 @@
export function paperclipCloudEnrollmentPrincipal(actor: { userId?: string | null; source?: string | null }): string {
return actor.userId ? `user:${actor.userId}` : `source:${actor.source ?? "board"}`;
}
@@ -37,8 +37,8 @@ export { GOOGLE_WORKSPACE_CONNECTOR_PROFILES };
export type PaperclipCloudConnectorEnvironment = "development" | "test" | "staging" | "production";
export type PaperclipCloudConnectorOperation = "status" | "session" | "claim" | "refresh" | "revoke" | "webhook-bind" | "event-lease" | "event-ack" | "github-app" | "slack-events" | "slack-forms" | "mcp-client-mirror" | "mcp-revocation-index";
export type PaperclipCloudConnectorProfileId = GoogleWorkspaceConnectorProfileId | GitHubConnectorProfileId | AsanaConnectorProfileId | "slack.manager" | "github.bot";
export type PaperclipCloudConnectorProvider = "google" | "github" | "asana" | "slack";
export type PaperclipCloudConnectorProfileId = GoogleWorkspaceConnectorProfileId | GitHubConnectorProfileId | AsanaConnectorProfileId | "slack.manager" | "github.bot" | "tailscale.tailnet";
export type PaperclipCloudConnectorProvider = "google" | "github" | "asana" | "slack" | "tailscale";
export type PaperclipCloudConnectorConfig = {
baseUrl: string;
@@ -946,6 +946,7 @@ function connectorProfileDefinition(profile: PaperclipCloudConnectorProfileId):
provider: PaperclipCloudConnectorProvider;
scopes: readonly string[];
} {
if (profile === "tailscale.tailnet") return { provider: "tailscale", scopes: ["auth_keys:create:once"] };
if (profile === "slack.manager") return { provider: "slack", scopes: SLACK_MANAGER_SCOPES };
if (profile === "github.bot") return { provider: "github", scopes: [] };
if (isAsanaConnectorProfileId(profile)) {
@@ -961,6 +962,7 @@ function isExpectedProviderAuthorizationUrl(
profile: PaperclipCloudConnectorProfileId,
url: URL,
): boolean {
if (profile === "tailscale.tailnet") return url.origin === "https://login.tailscale.com" && url.pathname === "/a/oauth_authorize";
if (profile === "slack.manager") return url.origin === "https://slack.com" && url.pathname === "/oauth/v2/authorize";
if (isAsanaConnectorProfileId(profile)) {
return url.origin === "https://app.asana.com" && url.pathname === "/-/oauth_authorize";
@@ -972,7 +974,7 @@ function isExpectedProviderAuthorizationUrl(
}
function isPaperclipCloudConnectorProfileId(value: string): value is PaperclipCloudConnectorProfileId {
return value === "slack.manager" || isGoogleWorkspaceConnectorProfileId(value) || isGitHubConnectorProfileId(value) || isAsanaConnectorProfileId(value);
return value === "tailscale.tailnet" || value === "slack.manager" || isGoogleWorkspaceConnectorProfileId(value) || isGitHubConnectorProfileId(value) || isAsanaConnectorProfileId(value);
}
async function sha256Base64Url(value: string): Promise<string> {
+29 -1
View File
@@ -1,5 +1,5 @@
import { randomUUID } from "node:crypto";
import { and, desc, eq, inArray, like, ne, notInArray, notLike, or, sql } from "drizzle-orm";
import { and, desc, eq, inArray, isNull, like, ne, notInArray, notLike, or, sql } from "drizzle-orm";
import type { Db } from "@paperclipai/db";
import {
agents,
@@ -66,6 +66,8 @@ import { isSecretProviderClientError } from "../secrets/types.js";
import { authorizationDeniedDetails, authorizationService } from "./authorization.js";
import { findActiveServerAdapter } from "../adapters/index.js";
import { logActivity } from "./activity-log.js";
import { retireTailscaleSecret } from "./connectors/tailscale/deletion.js";
import { isTailscaleNodeState } from "./connectors/tailscale/network.js";
// Only a `local_encrypted` secret can hold a literal directory path, so only a
// `local_encrypted` secret can ever name a Codex account-home directory. A
// create or a rotate that writes a new `local_encrypted` value runs inside
@@ -744,6 +746,7 @@ type SecretResolutionErrorCode =
| "secret_deleted"
| "secret_inactive"
| "secret_scope_invalid"
| "secret_system_only"
| "responsible_user_missing"
| "user_secret_definition_missing"
| "user_secret_definition_inactive"
@@ -844,6 +847,7 @@ function secretResolutionErrorCode(error: unknown): SecretResolutionErrorCode {
case "binding_missing":
case "secret_deleted":
case "secret_inactive":
case "secret_system_only":
case "version_missing":
case "version_inactive":
case "provider_error":
@@ -1003,6 +1007,7 @@ export function secretService(db: Db | DbTransaction) {
.where(and(
eq(companySecrets.companyId, companyId),
eq(companySecrets.scope, "company"),
isNull(companySecrets.systemPurpose),
eq(companySecrets.name, name),
ne(companySecrets.status, "deleted"),
))
@@ -1017,6 +1022,7 @@ export function secretService(db: Db | DbTransaction) {
eq(companySecrets.companyId, companyId),
eq(companySecrets.key, key),
eq(companySecrets.scope, "company"),
isNull(companySecrets.systemPurpose),
ne(companySecrets.status, "deleted"),
))
.then((rows) => rows[0] ?? null);
@@ -1226,6 +1232,7 @@ export function secretService(db: Db | DbTransaction) {
if (secret.status === "deleted") throw notFound("Secret not found");
if (secret.companyId !== companyId) throw unprocessable("Secret must belong to same company");
if (secret.scope !== "company") throw unprocessable("Secret references require company-scoped secrets");
if (secret.systemPurpose) throw forbidden("System-owned secrets cannot be bound to agent or environment credentials");
return secret;
}
@@ -1365,6 +1372,7 @@ export function secretService(db: Db | DbTransaction) {
options?: SecretResolutionOptions,
readOnlyEnvironmentInspection = false,
preloaded?: { secret: typeof companySecrets.$inferSelect; version: typeof companySecretVersions.$inferSelect | null },
systemPurpose?: "tailscale_network",
): Promise<RuntimeSecretResolution> {
const bindingContext = options?.bindingContext;
const accessContext = options?.accessContext ?? bindingContext;
@@ -1389,6 +1397,9 @@ export function secretService(db: Db | DbTransaction) {
if (secret.status !== "active") {
throw unprocessable("Secret is not active", { code: "secret_inactive" });
}
if ((secret.systemPurpose ?? null) !== (systemPurpose ?? null)) {
throw forbidden("System-owned secrets require their server-only consumer", { code: "secret_system_only" });
}
const binding = await assertBindingContext(companyId, secret.id, bindingContext);
const versionRow = preloaded?.secret === secret && preloaded.version?.version === resolvedVersion
? preloaded.version : await getSecretVersion(secret.id, resolvedVersion);
@@ -1414,6 +1425,9 @@ export function secretService(db: Db | DbTransaction) {
version: resolvedVersion,
},
});
if (isTailscaleNodeState(value) && systemPurpose !== "tailscale_network") {
throw forbidden("Network node state requires its server-only consumer", { code: "secret_system_only" });
}
if (!readOnlyEnvironmentInspection) await Promise.all([
db
.update(companySecrets)
@@ -2224,6 +2238,7 @@ export function secretService(db: Db | DbTransaction) {
},
actor?: { userId?: string | null; agentId?: string | null },
instanceOwner?: InstanceSecretOwner,
systemPurpose?: "tailscale_network",
) {
const existing = instanceOwner ? null : await getByName(companyId, input.name);
if (existing) throw conflict(`Secret already exists: ${input.name}`);
@@ -2268,6 +2283,7 @@ export function secretService(db: Db | DbTransaction) {
.values({
companyId,
scope: instanceOwner ? "instance" : "company",
systemPurpose: systemPurpose ?? null,
ownerAgentId: instanceOwner?.agentId ?? null,
ownerProjectId: instanceOwner?.projectId ?? null,
ownerPluginId: instanceOwner?.pluginId ?? null,
@@ -3444,6 +3460,7 @@ export function secretService(db: Db | DbTransaction) {
// New references now see the deleted status, so the caller can settle
// every reference that exists before the row and its cascades go.
await options.beforeDelete?.(secret);
await retireTailscaleSecret(db, secret.companyId, secretId);
const providerConfig = secret.providerConfigId
? await getProviderConfigById(secret.providerConfigId)
: null;
@@ -3842,6 +3859,7 @@ export function secretService(db: Db | DbTransaction) {
.where(and(
eq(companySecrets.companyId, companyId),
eq(companySecrets.scope, "company"),
isNull(companySecrets.systemPurpose),
ne(companySecrets.status, "deleted"),
))
.orderBy(desc(companySecrets.createdAt)),
@@ -4652,6 +4670,16 @@ export function secretService(db: Db | DbTransaction) {
getByName,
getByKey,
resolveSecretValue,
resolveSystemSecretValue: async (companyId: string, secretId: string, version: number | "latest", purpose: "tailscale_network", consumerId: string) =>
(await resolveSecretValueInternal(companyId, secretId, version, {
accessContext: { consumerType: "system", consumerId, actorType: "system", actorId: null },
}, false, undefined, purpose)).value,
createSystemSecret: async (companyId: string, input: Parameters<typeof createSecretUnlocked>[1], purpose: "tailscale_network",
actor?: { userId?: string | null; agentId?: string | null }) =>
withAccountHomeSecretMutationLock(undefined, companyId, async () => {
if (input.value) await assertAccountHomeCacheDirStillValid(undefined, companyId, input.value);
return createSecretUnlocked(companyId, input, actor, undefined, purpose);
}),
resolveSecretVersion,
resolveSecretVersionIdentity,
resolveSecretValueForAgentAccess,
+15 -1
View File
@@ -49,7 +49,22 @@ test.describe("chat destination partial updates", () => {
await expect(primarySwitch(page)).toBeChecked();
}
const staleView = await context.newPage();
const resourcesPath = "/api/chat-endpoints/endpoint-discord/resources";
const initialResources = staleView.waitForResponse(response =>
new URL(response.url()).pathname === resourcesPath && response.request().method() === "GET",
);
await staleView.goto(settingsUrl);
const snapshot = await (await initialResources).json();
let retainSnapshot = true;
await staleView.route(`**${resourcesPath}`, async route => {
const method = route.request().method();
if (method === "GET" && retainSnapshot) {
await fulfill(route, snapshot);
return;
}
if (method === "PUT") retainSnapshot = false;
await route.fallback();
});
await expect(primarySwitch(staleView)).toBeChecked({
checked: initiallyEnabled,
});
@@ -59,7 +74,6 @@ test.describe("chat destination partial updates", () => {
await expect(primarySwitch(page)).toBeChecked({
checked: !initiallyEnabled,
});
// Assert the stale prerequisite instead of assuming browser focus/refetch.
await expect(primarySwitch(staleView)).toBeChecked({
checked: initiallyEnabled,
});
@@ -151,8 +151,13 @@ for (const action of ["task_retry", "retry_after_reload", "inbox_retry", "messag
const runs = await db.select().from(heartbeatRuns).where(and(eq(heartbeatRuns.companyId, company.id), eq(heartbeatRuns.agentId, agent.id)));
expect(runs.filter(run => run.id !== sourceRunId)).toHaveLength(1);
const source = runs.find(run => run.id === sourceRunId)!;
expect(source.status).toBe("failed");
expect(Object.keys(source.resultJson ?? {}).filter(key => key !== "freshContinuationSupersededAt")).toEqual([]);
expect(source).toMatchObject({ status: "failed", errorCode: "process_lost", error: "Server restarted during startup" });
// Fresh continuation revokes the replaced run's write authority with this timestamp.
if (source.resultJson !== null) {
expect(source.resultJson).toEqual({ freshContinuationSupersededAt: expect.any(String) });
const supersededAt = source.resultJson.freshContinuationSupersededAt as string;
expect(new Date(supersededAt).toISOString()).toBe(supersededAt);
}
const prompts = await readFile(path.join(root, "prompts"), "utf8");
if (action === "queued_retry" || action === "automatic_message_on_reactivation") {
expect(prompts).toContain("Approved");
+4 -1
View File
@@ -5,6 +5,7 @@ import path from "node:path";
import { tmpdir } from "node:os";
import { afterEach, expect, it } from "vitest";
import { runOwnedInstalledPreparation, admitsInstalledChat, installedChatTreeIdentity, refreshInstalledChatPins, validateChatInstallConfiguration, CHAT_INSTALL_PLAN } from "./chat-installed-lane.js";
import { readProcessTable } from "./process-tree.js";
import type { MatrixExecution } from "./types.js";
const roots: string[] = []; const sha = (file: string) => createHash("sha256").update(readFileSync(file)).digest("hex");
afterEach(() => { for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true }); });
@@ -52,6 +53,8 @@ it("retires the exact timed-out preparation child while retaining only the owned
await expect(runOwnedInstalledPreparation(process.execPath, ["-e", source], { cwd: folder, env: { PATH: process.env.PATH }, timeout: 500 })).rejects.toThrow("preparation failed");
const { pid, descendantPid } = JSON.parse(readFileSync(partial, "utf8"));
expect(() => process.kill(pid, 0)).toThrow();
expect(() => process.kill(descendantPid, 0)).toThrow();
const table = await readProcessTable();
expect(table).not.toBeNull();
expect(table!.filter(row => row.pid === descendantPid && !row.state?.startsWith("Z"))).toEqual([]);
rmSync(folder, { recursive: true, force: true });
});
@@ -394,7 +394,7 @@
"packages/shared/src/types/decision.ts": "b0d40077d481ce6180de6b02bad6df5bb0fbf977",
"packages/shared/src/types/document-annotation.ts": "7769a42f1ccd707a2259774e7fe6aa536b5d183f",
"packages/shared/src/types/email.ts": "556ff6a0dcefa01eb704d6d00d3b191de81ff4dc",
"packages/shared/src/types/environment.ts": "16b9d9598abfa2583602181b44483b0fa24d5bc2",
"packages/shared/src/types/environment.ts": "62e62afcb3d5b7f246db1e8910a34fb0091f54db",
"packages/shared/src/types/execution-continuation.ts": "5afe62afd227efa03ff847d8f73291c14707ab5b",
"packages/shared/src/types/execution-projection.ts": "7a4b8567cb1a8204f9e9f878eb594b745a0428cc",
"packages/shared/src/types/external-object.ts": "7a225e0f5a6777d449019a30530c858b753eb4c1",
+6
View File
@@ -721,6 +721,12 @@
"provider": "Unikraft",
"catalogVisible": true,
"localAsset": "/brands/apps/unikraft.svg"
},
{
"slug": "tailscale",
"provider": "Tailscale",
"catalogVisible": false,
"localAsset": "/brands/apps/tailscale.png"
}
]
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

+2
View File
@@ -108,6 +108,7 @@ const AdvancedToolsRoute = lazy(() => import("./pages/tools/AdvancedToolsRoute")
const ProfileWizardRoute = lazy(() => import("./pages/tools/profiles/ProfileWizardRoute").then((module) => ({ default: module.ProfileWizardRoute })));
const ProfileDetailRoute = lazy(() => import("./pages/tools/profiles/ProfileDetailRoute").then((module) => ({ default: module.ProfileDetailRoute })));
const Browse = lazy(() => import("./pages/apps/Browse").then((module) => ({ default: module.Browse })));
const TailscaleConnector = lazy(() => import("./pages/apps/TailscaleConnector").then((module) => ({ default: module.TailscaleConnector })));
const AppsConnect = lazy(() => import("./pages/apps/AppsConnect").then((module) => ({ default: module.AppsConnect })));
const ChatEndpointSetup = lazy(() => import("./pages/apps/chat/ChatEndpointSetup").then((module) => ({ default: module.ChatEndpointSetup })));
const ChatEndpointDetail = lazy(() => import("./pages/apps/chat/ChatEndpointDetail").then((module) => ({ default: module.ChatEndpointDetail })));
@@ -199,6 +200,7 @@ function boardRoutes(streamlinedUiEnabled: boolean, combinedInboxTasksEnabled: b
<Route path="tools" element={<LegacyToolsRedirect />} />
<Route path="tools/:tab" element={<LegacyToolsRedirect />} />
<Route path="apps" element={<Browse />} />
<Route path="apps/tailscale" element={<TailscaleConnector />} />
<Route path="apps/assistant-connection" element={<AssistantConnection />} />
<Route path="apps/browse" element={<Navigate to="/apps" replace />} />
<Route path="apps/connections" element={<Navigate to="/apps" replace />} />
+12
View File
@@ -0,0 +1,12 @@
import type { ToolOAuthStartResult } from "@paperclipai/shared";
import { api } from "./client";
export type TailscaleConnection = { id: string; companyId: string; name: string; status: string };
export type TailscaleDevice = { id: string; name: string; hostname: string; address: string; os: string; online: boolean };
export const tailscaleApi = {
list: (companyId: string) => api.get<TailscaleConnection[]>(`/companies/${companyId}/tailscale-connections`),
connect: (companyId: string, connectionId?: string) => api.post<ToolOAuthStartResult>(`/companies/${companyId}/tailscale-connections`, { name: "My tailnet", ...(connectionId ? { connectionId } : {}) }),
devices: (companyId: string, id: string) => api.get<TailscaleDevice[]>(`/companies/${companyId}/tailscale-connections/${id}/devices`),
disconnect: (companyId: string, id: string) => api.delete<TailscaleConnection>(`/companies/${companyId}/tailscale-connections/${id}`),
pairing: (companyId: string, id: string, deviceId: string, port: number) => api.post<{ privateKeySecretId: string; publicKey: string; command: string }>(`/companies/${companyId}/tailscale-connections/${id}/pairing`, { deviceId, port }),
};
@@ -0,0 +1,77 @@
// @vitest-environment jsdom
import { flushSync } from "react-dom";
import { createRoot, type Root } from "react-dom/client";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { TailscaleSshMachine } from "./TailscaleSshMachine";
const pairing = vi.hoisted(() => vi.fn());
vi.mock("@/api/access", () => ({ accessApi: { getCurrentBoardAccess: async () => ({ source: "local_implicit", isInstanceAdmin: false }) } }));
vi.mock("@/api/tailscale", () => ({ tailscaleApi: {
list: async () => [{ id: "connection", companyId: "company", name: "Home tailnet", status: "connected" }],
devices: async () => [{ id: "device", name: "Workstation", address: "100.64.0.1", os: "linux", online: true }],
pairing,
} }));
vi.mock("@/lib/router", () => ({ Link: ({ to, children }: { to: string; children: React.ReactNode }) => <a href={to}>{children}</a> }));
const result = (port: number) => ({ privateKeySecretId: `key-${port}`, publicKey: "fixture public key", command: `pair workstation on port ${port}` });
let root: Root;
let container: HTMLDivElement;
let client: QueryClient;
const onPrivateKey = vi.fn<(secretId: string) => void>();
function render(port: number, visible = true) {
flushSync(() => root.render(<QueryClientProvider client={client}>
{visible ? <TailscaleSshMachine companyId="company" connectionId="connection" deviceId="device" port={port}
onPrivateKey={onPrivateKey} onChange={() => {}} /> : <p>Direct SSH configuration</p>}
</QueryClientProvider>));
}
function prepare() {
const button = [...container.querySelectorAll("button")].find(button => button.textContent === "Prepare machine pairing");
expect(button).toBeDefined();
flushSync(() => button!.click());
}
const command = () => container.querySelector<HTMLTextAreaElement>('textarea[aria-label="Machine pairing command"]');
async function settle() {
for (let i = 0; i < 6; i++) await new Promise(resolve => setTimeout(resolve, 0));
}
describe("Tailscale SSH pairing selection", () => {
beforeEach(() => {
pairing.mockReset().mockImplementation(async (_company, _connection, _device, port) => result(port));
onPrivateKey.mockReset();
container = document.createElement("div"); document.body.append(container);
root = createRoot(container);
client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
});
afterEach(() => { flushSync(() => root.unmount()); client.clear(); container.remove(); });
it("ignores a pending pairing response after switching to Direct", async () => {
let finish!: (value: ReturnType<typeof result>) => void;
pairing.mockImplementationOnce(() => new Promise(resolve => { finish = resolve; }));
render(22); await settle(); prepare(); await settle();
render(22, false);
finish(result(22)); await settle();
expect(onPrivateKey).not.toHaveBeenCalled();
expect(command()).toBeNull();
});
it.each([false, true])("requires current-port pairing after a port edit (old request pending=%s)", async pending => {
let finish!: (value: ReturnType<typeof result>) => void;
if (pending) pairing.mockImplementationOnce(() => new Promise(resolve => { finish = resolve; }));
render(22); await settle(); prepare(); await settle();
expect(pairing).toHaveBeenLastCalledWith("company", "connection", "device", 22);
if (!pending) {
expect(command()?.value).toBe(result(22).command);
expect(onPrivateKey).toHaveBeenCalledWith("key-22");
}
onPrivateKey.mockClear();
render(2222); await settle();
if (pending) { finish(result(22)); await settle(); }
expect(command()).toBeNull();
expect(onPrivateKey).not.toHaveBeenCalled();
prepare(); await settle();
expect(pairing).toHaveBeenLastCalledWith("company", "connection", "device", 2222);
expect(command()?.value).toBe(result(2222).command);
expect(onPrivateKey).toHaveBeenCalledExactlyOnceWith("key-2222");
});
});
+62
View File
@@ -0,0 +1,62 @@
import { useEffect, useRef } from "react";
import { useMutation, useQuery } from "@tanstack/react-query";
import { tailscaleApi } from "@/api/tailscale";
import { describeError } from "@/api/errors";
import { useTailscaleConnections } from "@/hooks/useTailscaleConnections";
import { Link } from "@/lib/router";
import { Button } from "./ui/button";
import { Field } from "./agent-config-primitives";
export function TailscaleSshMachine(props: {
companyId: string; connectionId: string; deviceId: string;
port: number; onPrivateKey: (secretId: string) => void;
onChange: (selection: { connectionId: string; deviceId: string; host: string }) => void;
}) {
const mounted = useRef(false);
useEffect(() => { mounted.current = true; return () => { mounted.current = false; }; }, []);
const connections = useTailscaleConnections(props.companyId);
const connected = (connections.data ?? []).filter(connection => connection.status === "connected");
const onlyConnectionId = connected.length === 1 ? connected[0]!.id : null;
const showConnectionSelector = connected.length > 1 || Boolean(props.connectionId && onlyConnectionId && props.connectionId !== onlyConnectionId);
useEffect(() => {
if (!props.connectionId && onlyConnectionId) props.onChange({ connectionId: onlyConnectionId, deviceId: "", host: "" });
}, [props.connectionId, onlyConnectionId, props.onChange]);
const devices = useQuery({ queryKey: ["tailscale-devices", props.companyId, props.connectionId], queryFn: () => tailscaleApi.devices(props.companyId, props.connectionId), enabled: Boolean(props.connectionId) && connections.canManage });
const pairing = useMutation({ mutationFn: (selection: { companyId: string; connectionId: string; deviceId: string; port: number }) => tailscaleApi.pairing(selection.companyId, selection.connectionId, selection.deviceId, selection.port),
onSuccess: (result, selection) => {
if (mounted.current && selection.companyId === props.companyId && selection.connectionId === props.connectionId && selection.deviceId === props.deviceId && selection.port === props.port) props.onPrivateKey(result.privateKeySecretId);
} });
const error = pairing.error ?? connections.error ?? devices.error;
if (!connections.canManage) return <p className="text-sm text-muted-foreground">An instance administrator must configure this Tailscale machine.</p>;
return <div className="grid gap-3">
<p className="text-sm text-muted-foreground"><Link className="underline" to="/apps/tailscale">Manage Tailscale connector</Link></p>
{showConnectionSelector ? <div className="flex items-center gap-3">
<Field label="Tailnet connection">
<select className="w-full rounded-md border border-border bg-transparent px-2.5 py-1.5 text-sm" value={props.connectionId}
onChange={event => props.onChange({ connectionId: event.target.value, deviceId: "", host: "" })}>
<option value="">Choose a connection</option>
{props.connectionId && !connected.some(connection => connection.id === props.connectionId) ? <option value={props.connectionId} disabled>Unavailable connection</option> : null}
{connected.map(connection => <option key={connection.id} value={connection.id}>{connection.name}</option>)}
</select>
</Field>
</div> : null}
{props.connectionId ? <Field label="Machine">
<select className="w-full rounded-md border border-border bg-transparent px-2.5 py-1.5 text-sm" value={props.deviceId}
disabled={devices.isPending} onChange={event => {
const device = devices.data?.find(device => device.id === event.target.value);
props.onChange({ connectionId: props.connectionId, deviceId: device?.id ?? "", host: device?.address ?? "" });
}}>
<option value="">{devices.isPending ? "Loading machines…" : "Choose a machine"}</option>
{(devices.data ?? []).map(device => <option key={device.id} value={device.id} disabled={!device.online}>{device.name}{device.hostname ? ` — ${device.hostname}` : ""} ({device.os}){device.online ? "" : " — Offline"}</option>)}
</select>
</Field> : null}
{props.deviceId ? <div className="grid gap-3">
<Button type="button" variant="outline" disabled={pairing.isPending} onClick={() => pairing.mutate({ companyId: props.companyId, connectionId: props.connectionId, deviceId: props.deviceId, port: props.port })}>Prepare machine pairing</Button>
{pairing.data && pairing.variables?.companyId === props.companyId && pairing.variables?.deviceId === props.deviceId && pairing.variables?.connectionId === props.connectionId && pairing.variables?.port === props.port ? <>
<p className="text-sm text-muted-foreground">Run this on the selected computer as the user who will run tasks. Enter the printed username, workspace, and known hosts below. Paperclip keeps the private key in its vault.</p>
<textarea aria-label="Machine pairing command" readOnly rows={8} className="w-full rounded-md border border-border bg-transparent p-3 font-mono text-sm" value={pairing.data.command} />
</> : null}
</div> : null}
{error ? <p role="alert" className="text-sm text-destructive">{describeError(error, { action: "connect Tailscale" }).body}</p> : null}
</div>;
}
+19
View File
@@ -0,0 +1,19 @@
import { useQuery } from "@tanstack/react-query";
import { tailscaleApi } from "@/api/tailscale";
import { accessApi } from "@/api/access";
import { queryKeys } from "@/lib/queryKeys";
export const tailscaleConnectionsKey = (companyId: string | null) => ["tailscale-connections", companyId] as const;
export function useTailscaleConnections(companyId: string | null) {
const access = useQuery({ queryKey: queryKeys.access.currentBoardAccess,
queryFn: () => accessApi.getCurrentBoardAccess(), enabled: Boolean(companyId), staleTime: 30_000 });
const canManage = access.data?.source === "local_implicit" || access.data?.isInstanceAdmin === true;
const connections = useQuery({
queryKey: tailscaleConnectionsKey(companyId),
queryFn: () => tailscaleApi.list(companyId!),
enabled: Boolean(companyId) && canManage,
staleTime: 30_000,
});
return { ...connections, data: canManage ? connections.data : undefined, canManage, access };
}
+137
View File
@@ -7,6 +7,14 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { TooltipProvider } from "@/components/ui/tooltip";
import { CompanyEnvironments } from "./CompanyEnvironments";
import { ApiError } from "@/api/client";
import { tailscaleApi } from "@/api/tailscale";
vi.mock("@/api/access", () => ({ accessApi: { getCurrentBoardAccess: async () => ({ source: "local_implicit", isInstanceAdmin: false }) } }));
vi.mock("@/api/tailscale", () => ({ tailscaleApi: {
list: vi.fn(async () => [{ id: "tailnet-connection", companyId: "company-1", name: "Home tailnet", status: "connected" }]),
devices: vi.fn(async () => [{ id: "stable-device", name: "Home Mac", address: "100.64.0.1", os: "macOS", online: true }]),
connect: vi.fn(),
} }));
const xtermMocks = vi.hoisted(() => {
class MockTerminal {
@@ -750,6 +758,135 @@ describe("CompanyEnvironments — test provider button", () => {
expect(getEnvironmentFormPage()).toBeNull();
});
it("defaults new SSH environments to the agent's Paperclip account", async () => {
root = createRoot(container);
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
await act(async () => { root!.render(renderCompanyEnvironments(queryClient, `${ENVIRONMENTS_PATH}/new`)); });
await waitForAssertion(() => {
const toggle = getEnvironmentFormPage()?.querySelector('[aria-label="Use authentication configured on the remote machine"]');
expect(toggle?.getAttribute("aria-checked")).toBe("false");
expect(toggle?.closest("details")?.open).toBe(false);
});
});
it.each([undefined, true, false])("preserves the remote-auth option when editing an existing SSH environment (saved=%s)", async useHostAuth => {
mockEnvironmentsApi.list.mockResolvedValue([{ id: "env-existing-ssh", name: "Existing SSH", driver: "ssh", description: null, envVars: {},
config: { ...(useHostAuth !== undefined ? { useHostAuth } : {}), host: "ssh.example.test", username: "developer", port: 22, remoteWorkspacePath: "/workspace", strictHostKeyChecking: true } }]);
root = createRoot(container);
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
await act(async () => { root!.render(renderCompanyEnvironments(queryClient, `${ENVIRONMENTS_PATH}/env-existing-ssh/edit`)); });
await waitForAssertion(() => {
expect(getEnvironmentFormPage()?.querySelector('[aria-label="Use authentication configured on the remote machine"]')?.getAttribute("aria-checked")).toBe(String(useHostAuth !== false));
});
await act(async () => { click(findButton(getEnvironmentFormPage()!, "Save environment")); });
await waitForAssertion(() => {
expect(mockEnvironmentsApi.update).toHaveBeenCalledWith("env-existing-ssh", expect.objectContaining({ config: expect.objectContaining({ useHostAuth: useHostAuth !== false }) }), "company-1");
});
});
it("offers tailnet setup through Connectors and hides the SSH network option until connected", async () => {
vi.mocked(tailscaleApi.list).mockResolvedValueOnce([]);
root = createRoot(container);
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
await act(async () => { root!.render(renderCompanyEnvironments(queryClient, `${ENVIRONMENTS_PATH}/new`)); });
await waitForAssertion(() => { expect(getEnvironmentFormPage()?.querySelector('a[href="/apps/tailscale"]')).not.toBeNull(); });
expect(getEnvironmentFormPage()!.querySelector('select[aria-label="SSH network"]')).toBeNull();
expect(findButton(getEnvironmentFormPage()!, "Connect Tailscale Network")).toBeUndefined();
});
it("keeps cached tailnet setup available when a background refresh fails", async () => {
root = createRoot(container);
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
const key = ["tailscale-connections", "company-1"];
queryClient.setQueryData(key, []);
await act(async () => { root!.render(renderCompanyEnvironments(queryClient, `${ENVIRONMENTS_PATH}/new`)); });
await waitForAssertion(() => { expect(getEnvironmentFormPage()?.querySelector('a[href="/apps/tailscale"]')).not.toBeNull(); });
vi.mocked(tailscaleApi.list).mockRejectedValueOnce(new ApiError("Network unavailable", 503, {}));
await act(async () => { await queryClient.refetchQueries({ queryKey: key }); });
await waitForAssertion(() => {
expect(getEnvironmentFormPage()?.querySelector('[role="alert"]')).not.toBeNull();
expect(getEnvironmentFormPage()?.querySelector('a[href="/apps/tailscale"]')).not.toBeNull();
});
});
it("automatically uses the sole connected tailnet without showing a connection selector", async () => {
vi.mocked(tailscaleApi.list).mockResolvedValueOnce([
{ id: "tailnet-connection", companyId: "company-1", name: "Home tailnet", status: "connected" },
{ id: "unfinished", companyId: "company-1", name: "Unfinished connection", status: "pending" },
]);
root = createRoot(container);
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
await act(async () => { root!.render(renderCompanyEnvironments(queryClient, `${ENVIRONMENTS_PATH}/new`)); });
await waitForAssertion(() => {
const network = getEnvironmentFormPage()!.querySelector<HTMLSelectElement>('select[aria-label="SSH network"]')!;
expect([...network.options].map(option => option.value)).toEqual(["direct", "tailscale"]);
});
await act(async () => setSelectValue(getEnvironmentFormPage()!.querySelector('select[aria-label="SSH network"]')!, "tailscale"));
await waitForAssertion(() => {
const page = getEnvironmentFormPage()!;
expect(page.textContent).toContain("Home Mac");
expect(page.textContent).not.toContain("Tailnet connection");
expect(vi.mocked(tailscaleApi.devices)).toHaveBeenCalledWith("company-1", "tailnet-connection");
});
});
it("retains the tailnet selector when multiple connected networks are available", async () => {
vi.mocked(tailscaleApi.list).mockResolvedValueOnce([
{ id: "tailnet-connection", companyId: "company-1", name: "Home tailnet", status: "connected" },
{ id: "work-tailnet", companyId: "company-1", name: "Work tailnet", status: "connected" },
]);
mockEnvironmentsApi.list.mockResolvedValue([{ id: "env-tailnet", name: "My workstation", driver: "ssh", description: null, envVars: {},
config: { network: "tailscale", host: "100.64.0.1", port: 22, username: "developer", remoteWorkspacePath: "/workspace",
tailscaleConnectionId: "tailnet-connection", tailscaleDeviceId: "stable-device", strictHostKeyChecking: true } }]);
root = createRoot(container);
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
await act(async () => { root!.render(renderCompanyEnvironments(queryClient, `${ENVIRONMENTS_PATH}/env-tailnet/edit`)); });
await waitForAssertion(() => {
const page = getEnvironmentFormPage()!;
expect(page.textContent).toContain("Tailnet connection");
expect(page.textContent).toContain("Home tailnet");
expect(page.textContent).toContain("Work tailnet");
});
});
it("saves a connected Tailscale machine as an SSH environment without a separate driver or harness restriction", async () => {
root = createRoot(container);
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
mockEnvironmentsApi.list.mockResolvedValue([{ id: "env-tailnet", name: "My workstation", driver: "ssh", description: null, envVars: {},
config: { network: "tailscale", host: "100.64.0.1", port: 22, username: "developer", remoteWorkspacePath: "/workspace",
tailscaleConnectionId: "tailnet-connection", tailscaleDeviceId: "stable-device", strictHostKeyChecking: true } }]);
await act(async () => { root!.render(renderCompanyEnvironments(queryClient, `${ENVIRONMENTS_PATH}/env-tailnet/edit`)); });
await waitForAssertion(() => { expect(getEnvironmentFormPage()?.textContent).toContain("Home Mac"); });
const page = getEnvironmentFormPage()!;
expect(page.textContent).not.toContain("Tailnet connection");
const driver = Array.from(page.querySelectorAll("select")).find(select => select.querySelector('option[value="ssh"]'))!;
expect(driver.value).toBe("ssh");
expect(driver.querySelector('option[value="tailscale"]')).toBeNull();
expect(findButton(page, "Connect Tailscale Network")).toBeUndefined();
expect(page.textContent).not.toContain("Claude");
expect(page.querySelector('input[aria-label="Tailscale connection key"]')).toBeNull();
await act(async () => { click(findButton(page, "Save environment")); });
await waitForAssertion(() => { expect(mockEnvironmentsApi.update).toHaveBeenCalledWith("env-tailnet", expect.objectContaining({ driver: "ssh", config: expect.objectContaining({
network: "tailscale", host: "100.64.0.1", username: "developer", remoteWorkspacePath: "/workspace", tailscaleConnectionId: "tailnet-connection", tailscaleDeviceId: "stable-device",
}) }), "company-1"); });
});
it("sends an explicit Direct selection when switching away from a saved tailnet", async () => {
mockEnvironmentsApi.list.mockResolvedValue([{ id: "env-tailnet", name: "My workstation", driver: "ssh", description: null, envVars: {},
config: { network: "tailscale", host: "100.64.0.1", port: 22, username: "developer", remoteWorkspacePath: "/workspace",
tailscaleConnectionId: "tailnet-connection", tailscaleDeviceId: "stable-device", strictHostKeyChecking: true } }]);
root = createRoot(container);
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
await act(async () => { root!.render(renderCompanyEnvironments(queryClient, `${ENVIRONMENTS_PATH}/env-tailnet/edit`)); });
await waitForAssertion(() => { expect(getEnvironmentFormPage()?.textContent).toContain("Home Mac"); });
const page = getEnvironmentFormPage()!;
const host = Array.from(page.querySelectorAll<HTMLInputElement>("input")).find(input => input.value === "100.64.0.1")!;
await act(async () => setSelectValue(page.querySelector('select[aria-label="SSH network"]')!, "direct"));
await act(async () => setInputValue(host, "direct.example.test"));
await act(async () => click(findButton(page, "Save environment")));
await waitForAssertion(() => { expect(mockEnvironmentsApi.update).toHaveBeenCalledWith("env-tailnet", expect.objectContaining({ driver: "ssh", config: expect.objectContaining({ network: "direct", host: "direct.example.test" }) }), "company-1"); });
});
it("opens the edit form on a standalone page with existing values and closes after save", async () => {
root = createRoot(container);
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
+58 -8
View File
@@ -27,6 +27,8 @@ import {
type EnvironmentCustomImageSetupSessionResult,
type EnvironmentUpdateResult,
} from "@/api/environments";
import { TailscaleSshMachine } from "@/components/TailscaleSshMachine";
import { useTailscaleConnections } from "@/hooks/useTailscaleConnections";
import { agentsApi } from "@/api/agents";
import { ApiError } from "@/api/client";
import { describeError } from "@/api/errors";
@@ -70,7 +72,11 @@ type EnvironmentFormState = {
name: string;
description: string;
driver: "local" | "ssh" | "sandbox";
sshNetwork: "direct" | "tailscale";
sshUseHostAuth: boolean;
tailscaleConnectionId: string;
tailscaleDeviceId: string;
tailscaleAuthKeySecretId: string;
sshHost: string;
sshPort: string;
sshUsername: string;
@@ -128,6 +134,10 @@ function buildEnvironmentPayload(form: EnvironmentFormState) {
form.driver === "ssh"
? {
useHostAuth: form.sshUseHostAuth,
...(form.sshNetwork === "tailscale" ? { network: "tailscale" as const,
...(form.tailscaleConnectionId ? { tailscaleConnectionId: form.tailscaleConnectionId, tailscaleDeviceId: form.tailscaleDeviceId } :
{ tailscaleAuthKeySecretRef: form.tailscaleAuthKeySecretId ? { type: "secret_ref" as const, secretId: form.tailscaleAuthKeySecretId, version: "latest" as const } : null }),
} : { network: "direct" as const }),
host: form.sshHost.trim(),
port: Number.parseInt(form.sshPort || "22", 10) || 22,
username: form.sshUsername.trim(),
@@ -150,11 +160,17 @@ function buildEnvironmentPayload(form: EnvironmentFormState) {
}
function createEmptyEnvironmentForm(): EnvironmentFormState {
const connectionId = typeof window === "undefined" ? "" : new URLSearchParams(window.location.search).get("tailscale_connection") ?? "";
const tailscaleSetup = Boolean(connectionId) || (typeof window !== "undefined" && new URLSearchParams(window.location.search).has("tailscale_setup"));
return {
name: "",
description: "",
driver: "ssh",
sshUseHostAuth: false,
sshNetwork: tailscaleSetup ? "tailscale" : "direct",
tailscaleConnectionId: connectionId,
tailscaleDeviceId: "",
tailscaleAuthKeySecretId: "",
sshHost: "",
sshPort: "22",
sshUsername: "",
@@ -186,6 +202,9 @@ function readSshConfig(environment: Environment) {
const config = environment.config ?? {};
return {
useHostAuth: config.useHostAuth !== false,
network: config.network === "tailscale" ? "tailscale" as const : "direct" as const,
tailscaleAuthKeySecretId: typeof (config.tailscaleAuthKeySecretRef as { secretId?: unknown } | null)?.secretId === "string"
? (config.tailscaleAuthKeySecretRef as { secretId: string }).secretId : "",
host: typeof config.host === "string" ? config.host : "",
port:
typeof config.port === "number"
@@ -231,7 +250,11 @@ function createEnvironmentFormFromEnvironment(environment: Environment): Environ
name: environment.name,
description: environment.description ?? "",
driver: "ssh",
tailscaleConnectionId: typeof environment.config.tailscaleConnectionId === "string" ? environment.config.tailscaleConnectionId : "",
tailscaleDeviceId: typeof environment.config.tailscaleDeviceId === "string" ? environment.config.tailscaleDeviceId : "",
sshUseHostAuth: ssh.useHostAuth,
sshNetwork: ssh.network,
tailscaleAuthKeySecretId: ssh.tailscaleAuthKeySecretId,
sshHost: ssh.host,
sshPort: ssh.port,
sshUsername: ssh.username,
@@ -1311,12 +1334,14 @@ export function CompanyEnvironments({ mode = "list" }: CompanyEnvironmentsProps)
const { environmentId: routeEnvironmentId } = useParams<{ environmentId?: string }>();
const navigate = useNavigate();
const { selectedCompanyId } = useCompany();
const tailscaleConnections = useTailscaleConnections(selectedCompanyId);
const { setBreadcrumbs } = useBreadcrumbs();
const { pushToast } = useToast();
const queryClient = useQueryClient();
const isEnvironmentFormPage = mode === "create" || mode === "edit";
const editingEnvironmentId = mode === "edit" ? routeEnvironmentId ?? null : null;
const [environmentForm, setEnvironmentForm] = useState<EnvironmentFormState>(createEmptyEnvironmentForm);
const hasConnectedTailnet = tailscaleConnections.data?.some(connection => connection.status === "connected") ?? false;
const environmentVariablesEditorRef = useRef<EnvironmentVariablesEditorHandle | null>(null);
const initializedFormKeyRef = useRef<string | null>(null);
// Fingerprint of the form as initialized; null until the form page has loaded its data.
@@ -1855,7 +1880,8 @@ export function CompanyEnvironments({ mode = "list" }: CompanyEnvironmentsProps)
(
environmentForm.sshHost.trim().length > 0 &&
environmentForm.sshUsername.trim().length > 0 &&
environmentForm.sshRemoteWorkspacePath.trim().length > 0
environmentForm.sshRemoteWorkspacePath.trim().length > 0 &&
(environmentForm.sshNetwork !== "tailscale" || Boolean(environmentForm.tailscaleConnectionId && environmentForm.tailscaleDeviceId))
)) &&
(environmentForm.driver !== "sandbox" ||
environmentForm.sandboxProvider.trim().length > 0 &&
@@ -2049,7 +2075,7 @@ export function CompanyEnvironments({ mode = "list" }: CompanyEnvironmentsProps)
<span>
{environment.name}
{isPlatformManagedEnvironment(environment) ? null : (
<span className="text-muted-foreground"> · {environment.driver}</span>
<span className="text-muted-foreground"> · {environment.driver === "ssh" && environment.config.network === "tailscale" ? "ssh via Tailscale" : environment.driver}</span>
)}
</span>
{isPlatformManagedEnvironment(environment) ? (
@@ -2186,6 +2212,7 @@ export function CompanyEnvironments({ mode = "list" }: CompanyEnvironmentsProps)
>
<EnvironmentVariablesEditor
ref={environmentVariablesEditorRef}
footerHint={null}
value={environmentForm.envVars}
secrets={secrets ?? []}
onCreateSecret={async (name, value) => await createSecret.mutateAsync({ name, value })}
@@ -2249,9 +2276,6 @@ export function CompanyEnvironments({ mode = "list" }: CompanyEnvironmentsProps)
) : null}
</div>
<h1 className="text-lg font-semibold">{editingEnvironmentId ? "Edit environment" : "Add environment"}</h1>
<p className="mt-1 max-w-3xl text-sm text-muted-foreground">
Configure a reusable execution target for your agents. Saved changes affect future runs; Paperclip may start fresh sessions or sandbox leases after environment config changes.
</p>
</div>
<div className="py-4">
@@ -2272,7 +2296,7 @@ export function CompanyEnvironments({ mode = "list" }: CompanyEnvironmentsProps)
onChange={(e) => setEnvironmentForm((current) => ({ ...current, description: e.target.value }))}
/>
</Field>
<Field label="Driver" hint="Sandbox stores plugin-backed provider config on the shared environment seam. SSH stores a remote machine target.">
<Field label="Driver" hint="Choose where agent tasks run. SSH connects to a machine you own.">
<select
className="w-full rounded-md border border-border bg-transparent px-2.5 py-1.5 text-sm outline-none"
value={environmentForm.driver}
@@ -2308,11 +2332,35 @@ export function CompanyEnvironments({ mode = "list" }: CompanyEnvironmentsProps)
{environmentForm.driver === "ssh" ? (
<div className="grid gap-3 md:grid-cols-2">
<Field label="Host" hint="DNS name or IP address for the remote machine.">
<div className="md:col-span-2">
{environmentForm.sshNetwork === "tailscale" || hasConnectedTailnet ? <Field label="Network" hint="Choose how Paperclip reaches this SSH server.">
<select aria-label="SSH network" className="w-full rounded-md border border-border bg-transparent px-2.5 py-1.5 text-sm" value={environmentForm.sshNetwork}
onChange={event => setEnvironmentForm(current => ({ ...current, sshNetwork: event.target.value === "tailscale" ? "tailscale" : "direct",
tailscaleConnectionId: "", tailscaleDeviceId: "", tailscaleAuthKeySecretId: "", sshHost: "", sshPrivateKey: "", sshPrivateKeySecretId: "", sshKnownHosts: "" }))}>
<option value="direct">Direct connection</option>
<option value="tailscale">Tailscale</option>
</select>
</Field> : null}
{tailscaleConnections.error ? <p role="alert" className="text-sm text-destructive">{describeError(tailscaleConnections.error, { action: "load Tailscale connections" }).body}</p> : null}
{tailscaleConnections.data !== undefined && !hasConnectedTailnet && environmentForm.sshNetwork === "direct" ?
<p className="text-sm text-muted-foreground"><Link className="underline" to="/apps/tailscale">Connect Tailscale Network</Link> to choose machines from your tailnet.</p> : null}
</div>
{environmentForm.sshNetwork === "tailscale" && selectedCompanyId ? (
<div className="md:col-span-2">
<TailscaleSshMachine companyId={selectedCompanyId} connectionId={environmentForm.tailscaleConnectionId} deviceId={environmentForm.tailscaleDeviceId}
port={Number(environmentForm.sshPort) || 22} onPrivateKey={secretId => {
setEnvironmentForm(current => ({ ...current, sshPrivateKey: "", sshPrivateKeySecretId: secretId }));
void queryClient.invalidateQueries({ queryKey: queryKeys.secrets.list(selectedCompanyId) });
}}
onChange={selection => setEnvironmentForm(current => ({ ...current, tailscaleConnectionId: selection.connectionId, tailscaleDeviceId: selection.deviceId, sshHost: selection.host, sshPrivateKey: "", sshPrivateKeySecretId: "", sshKnownHosts: "" }))} />
</div>
) : null}
<Field label="Host" hint={environmentForm.sshNetwork === "tailscale" ? "Tailscale IP address or MagicDNS name of your machine." : "DNS name or IP address for the remote machine."}>
<input
className="w-full rounded-md border border-border bg-transparent px-2.5 py-1.5 text-sm outline-none"
type="text"
value={environmentForm.sshHost}
readOnly={environmentForm.sshNetwork === "tailscale" && Boolean(environmentForm.tailscaleConnectionId)}
onChange={(e) => setEnvironmentForm((current) => ({ ...current, sshHost: e.target.value }))}
/>
</Field>
@@ -2490,6 +2538,7 @@ export function CompanyEnvironments({ mode = "list" }: CompanyEnvironmentsProps)
>
<EnvironmentVariablesEditor
ref={environmentVariablesEditorRef}
footerHint={null}
value={environmentForm.envVars}
secrets={secrets ?? []}
onCreateSecret={async (name, value) => await createSecret.mutateAsync({ name, value })}
@@ -2524,7 +2573,8 @@ export function CompanyEnvironments({ mode = "list" }: CompanyEnvironmentsProps)
<Button
variant="outline"
onClick={() => draftEnvironmentProbeMutation.mutate(flushEnvironmentForm())}
disabled={draftEnvironmentProbeMutation.isPending || !environmentFormValid}
disabled={draftEnvironmentProbeMutation.isPending || !environmentFormValid || (environmentForm.driver === "ssh" && environmentForm.sshNetwork === "tailscale")}
title={environmentForm.driver === "ssh" && environmentForm.sshNetwork === "tailscale" ? "Save this environment, then test its connection from the list." : undefined}
>
{draftEnvironmentProbeMutation.isPending ? "Testing..." : "Test"}
</Button>
+1 -1
View File
@@ -215,7 +215,7 @@ describe("CompanyEnvironments", () => {
});
});
it("omits the Local driver option and lists Sandbox before SSH", async () => {
it("omits the Local driver option and lists Sandbox before SSH and Tailscale", async () => {
const root = createRoot(container);
const queryClient = new QueryClient({
defaultOptions: { queries: { retry: false } },
+35
View File
@@ -55,6 +55,8 @@ vi.mock("@/api/ai-connection-pools", () => ({ aiConnectionPoolsApi: { list: pool
const assistantConnectionsMock = vi.hoisted(() => vi.fn());
vi.mock("@/api/publicMcp", () => ({ publicMcpApi: { connections: assistantConnectionsMock } }));
const tailscaleConnectionsMock = vi.hoisted(() => vi.fn(async () => [] as Array<{ id: string; companyId: string; name: string; status: string }>));
vi.mock("@/api/tailscale", () => ({ tailscaleApi: { list: tailscaleConnectionsMock } }));
const listGalleryMock = vi.hoisted(() => vi.fn());
const listApplicationsMock = vi.hoisted(() => vi.fn());
@@ -63,6 +65,7 @@ const listAiConnectionsMock = vi.hoisted(() => vi.fn());
const setAiDefaultMock = vi.hoisted(() => vi.fn());
vi.mock("@/api/ai-connections", () => ({ aiConnectionsApi: { list: listAiConnectionsMock, setDefault: setAiDefaultMock } }));
const listUserDirectoryMock = vi.hoisted(() => vi.fn());
const boardAccessMock = vi.hoisted(() => vi.fn());
const archiveConnectionMock = vi.hoisted(() => vi.fn());
const pushToastMock = vi.hoisted(() => vi.fn());
const navigateMock = vi.hoisted(() => vi.fn());
@@ -99,6 +102,7 @@ vi.mock("@/api/tools", () => ({
vi.mock("@/api/access", () => ({
accessApi: {
listUserDirectory: (companyId: string) => listUserDirectoryMock(companyId),
getCurrentBoardAccess: boardAccessMock,
},
}));
@@ -199,6 +203,7 @@ describe("Connectors landing page", () => {
let root: ReturnType<typeof createRoot>;
beforeEach(() => {
boardAccessMock.mockReset().mockResolvedValue({ source: "session", isInstanceAdmin: true });
accountIdentity.userId = "board-user"; accountIdentity.settled = true;
assistantConnectionsMock.mockReset().mockResolvedValue([]);
syncComposioAppsMock.mockReset().mockImplementation((...args) => listComposioAppsMock(...args));
@@ -304,6 +309,35 @@ describe("Connectors landing page", () => {
expect(chatSetupMock).not.toHaveBeenCalled();
});
it("finds Tailscale in Connectors and opens network setup without creating a tool connection", async () => {
await renderBrowse(false);
await search("Tailscale");
const button = container.querySelector<HTMLButtonElement>('[aria-label="Connect Tailscale"]');
expect(button).not.toBeNull();
await act(() => button!.click());
expect(navigateMock).toHaveBeenCalledWith("/apps/tailscale");
expect(container.textContent).not.toContain("No connectors match");
});
it("does not advertise Tailscale setup or request tailnets for non-instance-admin members", async () => {
boardAccessMock.mockResolvedValue({ source: "session", isInstanceAdmin: false });
await renderBrowse(false);
await search("Tailscale");
expect(container.querySelector('[aria-label="Connect Tailscale"]')).toBeNull();
expect(container.querySelector('[data-app-slug="tailscale"]')).toBeNull();
expect(tailscaleConnectionsMock).not.toHaveBeenCalled();
});
it("shows a connected tailnet in Installed and removes it when disconnected", async () => {
tailscaleConnectionsMock.mockResolvedValueOnce([{ id: "tailnet", companyId: "company-1", name: "Home tailnet", status: "connected" }]);
const client = await renderBrowse(false);
await clickButton("Installed", container);
expect(container.querySelector('[data-app-slug="tailscale"]')?.textContent).toContain("Home tailnet");
await act(async () => { await client.invalidateQueries({ queryKey: ["tailscale-connections", "company-1"] }); });
await flushReact();
expect(container.querySelector('[data-app-slug="tailscale"]')).toBeNull();
});
it("keeps assistant setup in the Paperclip catalog when filtering connection sources", async () => {
await renderBrowse(false);
const assistantButton = () => container.querySelector('[aria-label="Set up Assistant Connection (MCP)"]');
@@ -1388,6 +1422,7 @@ describe("Connectors landing page", () => {
"notion",
"slack",
"speko",
"tailscale",
"telegram",
"custom-mcp",
]);
+14 -2
View File
@@ -12,6 +12,9 @@ import {
RETIRED_COMPOSIO_MESSAGE,
} from "@paperclipai/shared";
import { AssistantConnectionCard, useAssistantConnections } from "./AssistantConnection";
import { TailscaleConnectorCard } from "./TailscaleConnector";
import { useTailscaleConnections } from "@/hooks/useTailscaleConnections";
import type { TailscaleConnection } from "@/api/tailscale";
import { ManagedAiConnectionRow } from "@/components/ai-connections/ManagedAiConnectionDetails";
import { useAiConnectionDefaults } from "@/components/ai-connections/useAiConnectionDefaults";
import { AiDefaultCrown, AiDefaultError, AiDefaultMenuItem } from "@/components/ai-connections/AiConnectionDefault";
@@ -130,6 +133,7 @@ type ConnectorRowModel = {
applications: ToolApplication[];
connections: ToolConnection[];
chatEndpoints: ChatEndpoint[];
networkConnections?: TailscaleConnection[];
aggregatorApp?: AggregatorAppCatalogEntry;
upstreamApps?: (ComposioAppSnapshot & Partial<Pick<AggregatorAppSnapshot, "provider" | "appSlug" | "appName" | "freshness">>)[];
upstreamCatalogApp?: AggregatorAppCatalogEntry;
@@ -288,6 +292,7 @@ function rowRank(row: ConnectorRowModel): number {
if (
row.chatEndpoints.some((endpoint) => endpoint.status !== "draft") ||
row.connections.some((connection) => connectionRank(connection) === 1) ||
row.networkConnections?.some(connection => connection.status === "connected") ||
row.upstreamApps?.some((app) => app.status === "connected")
)
return 2;
@@ -295,7 +300,7 @@ function rowRank(row: ConnectorRowModel): number {
}
function isInstalled(row: ConnectorRowModel) {
return row.connections.length > 0 || row.chatEndpoints.length > 0 || Boolean(row.upstreamApps?.some(app => app.accounts.length > 0));
return row.connections.length > 0 || row.chatEndpoints.length > 0 || Boolean(row.upstreamApps?.some(app => app.accounts.length > 0)) || Boolean(row.networkConnections?.some(connection => connection.status === "connected"));
}
function connectorAction(
@@ -390,6 +395,7 @@ export function Browse({ renderAccountDetails = (connection) => connection.conne
const { pushToast } = useToast();
const { selectedCompanyId } = useCompany();
const assistantConnections = useAssistantConnections();
const tailscaleConnections = useTailscaleConnections(selectedCompanyId);
const { userId: viewingUserId, settled: identitySettled } = useAccountIdentity();
const { enabled: chatConnectorsEnabled, githubEnabled } = useChatConnectorsEnabled();
const { enabled: memoryConnectorsEnabled } = useMemoryConnectorsEnabled();
@@ -634,6 +640,9 @@ export function Browse({ renderAccountDetails = (connection) => connection.conne
]),
);
const rowsBySlug = new Map<string, ConnectorRowModel>();
if (tailscaleConnections.canManage) rowsBySlug.set("tailscale", { key: "network:tailscale", slug: "tailscale", name: "Tailscale",
description: "Connect your tailnet to use its machines in SSH environments.", brandKey: "tailscale", entry: null,
applications: [], connections: [], chatEndpoints: [], networkConnections: tailscaleConnections.data ?? [] });
for (const entry of gallery) {
const slug = appDefinitionSlug(entry);
rowsBySlug.set(slug, {
@@ -899,6 +908,8 @@ export function Browse({ renderAccountDetails = (connection) => connection.conne
chatConnectorsEnabled,
githubEnabled,
connectionsQuery.data,
tailscaleConnections.data,
tailscaleConnections.canManage,
gallery,
galleryQuery.data,
googleWorkspaceConnectorEnabled,
@@ -925,6 +936,7 @@ export function Browse({ renderAccountDetails = (connection) => connection.conne
return scoped.filter((row) => {
const text = normalizeConnectionQuery([row.name, row.slug, row.description,
...(row.aggregatorApp?.aliases ?? []), ...row.connections.map((connection) => connection.name),
...(row.networkConnections ?? []).map(connection => connection.name),
...(row.upstreamApps ?? []).flatMap(app => app.accounts.map(account => account.alias)),
...row.chatEndpoints.map((endpoint) => endpoint.assignedAgentName)].join(" "));
return terms.every((term) => text.includes(term));
@@ -1039,7 +1051,7 @@ export function Browse({ renderAccountDetails = (connection) => connection.conne
<div className="space-y-3" role="list" aria-label="Connector list">
{showAssistantConnection && <AssistantConnectionCard onNavigate={navigate} />}
{paginatedRows.map((row) => (
<ConnectorCard
row.networkConnections ? <TailscaleConnectorCard key={row.key} onNavigate={navigate} /> : <ConnectorCard
renderAccountDetails={renderAccountDetails}
aiDefaults={aiDefaults}
key={row.key}
@@ -0,0 +1,169 @@
// @vitest-environment jsdom
import { flushSync } from "react-dom";
import { createRoot, type Root } from "react-dom/client";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { TailscaleConnector, TailscaleConnectorCard } from "./TailscaleConnector";
import { ApiError } from "@/api/client";
import { readPendingCloudHandoff } from "@/lib/oauthHandoff";
import { PaperclipCloudOAuthHandoffPage } from "./PaperclipCloudOAuthHandoff";
const fixture = vi.hoisted(() => ({ companyId: "company-1", search: "", navigate: vi.fn(), access: vi.fn(), list: vi.fn(), connect: vi.fn(), disconnect: vi.fn(), breadcrumbs: vi.fn() }));
vi.mock("@/api/access", () => ({ accessApi: { getCurrentBoardAccess: fixture.access } }));
vi.mock("@/api/tailscale", () => ({ tailscaleApi: { list: fixture.list, connect: fixture.connect, disconnect: fixture.disconnect } }));
vi.mock("@/context/CompanyContext", () => ({ useCompany: () => ({ selectedCompanyId: fixture.companyId }) }));
vi.mock("@/context/BreadcrumbContext", () => ({ useBreadcrumbs: () => ({ setBreadcrumbs: fixture.breadcrumbs }) }));
vi.mock("./AppLogo", () => ({ AppLogo: () => null }));
vi.mock("@/lib/router", () => ({ Link: ({ to, children, ...props }: { to: string; children: React.ReactNode }) => <a href={to} {...props}>{children}</a>, useSearchParams: () => [new URLSearchParams(fixture.search)] }));
vi.mock("@/lib/browserNavigation", () => ({ navigateTopLevel: (url: string) => fixture.navigate(url) }));
const connected = { id: "tailnet-1", companyId: "company-1", name: "Home tailnet", status: "connected" };
let root: Root;
let container: HTMLDivElement;
let client: QueryClient;
const render = () => flushSync(() => root.render(<QueryClientProvider client={client}><TailscaleConnector /></QueryClientProvider>));
async function settle() {
for (let i = 0; i < 6; i++) await new Promise(resolve => setTimeout(resolve, 0));
}
function button(label: string) {
const result = [...container.querySelectorAll("button")].find(element => element.textContent === label);
expect(result).toBeDefined();
return result!;
}
describe("Tailscale network connector", () => {
beforeEach(() => {
vi.clearAllMocks();
fixture.companyId = "company-1";
fixture.search = "";
window.sessionStorage.clear();
fixture.access.mockResolvedValue({ source: "session", isInstanceAdmin: true, companyIds: ["company-1", "company-2"] });
fixture.list.mockResolvedValue([connected]);
fixture.connect.mockImplementation(() => new Promise(() => {}));
fixture.disconnect.mockResolvedValue({ ...connected, status: "disconnected" });
container = document.createElement("div");document.body.append(container);
root = createRoot(container);
client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
});
afterEach(() => { flushSync(() => root.unmount());client.clear();container.remove();vi.unstubAllGlobals(); });
it("does not offer setup or request tailnets to a company member without instance-admin rights", async () => {
fixture.access.mockResolvedValue({ source: "session", isInstanceAdmin: false, companyIds: ["company-1"] });
flushSync(() => root.render(<QueryClientProvider client={client}><TailscaleConnectorCard onNavigate={vi.fn()} /></QueryClientProvider>));
await settle();
expect(fixture.list).not.toHaveBeenCalled();
expect(container.querySelector("button")).toBeNull();
render();await settle();
expect(container.textContent).toContain("instance administrator");
expect(container.querySelector("button")).toBeNull();
expect(fixture.list).not.toHaveBeenCalled();
});
it("waits for management access before requesting network data", async () => {
fixture.access.mockImplementationOnce(() => new Promise(() => {}));
render();await settle();
expect(container.textContent).toContain("Checking Tailscale management access");
expect(fixture.list).not.toHaveBeenCalled();
expect(fixture.connect).not.toHaveBeenCalled();
});
it("allows a local implicit board to manage its network", async () => {
fixture.access.mockResolvedValue({ source: "local_implicit", isInstanceAdmin: false });
render();await settle();
expect(fixture.list).toHaveBeenCalledWith("company-1");
expect(button("Connect Tailscale Network").disabled).toBe(false);
});
it("reuses an approved tailnet and links to an ordinary SSH environment", async () => {
render();await settle();
expect(fixture.list).toHaveBeenCalledWith("company-1");
expect(container.textContent).toContain("Home tailnet");
expect(container.textContent).toContain("any harness supported");
expect(container.textContent).not.toContain("Claude");
expect(container.querySelector('a[href="/company/settings/instance/environments/new?tailscale_connection=tailnet-1"]')?.textContent).toBe("Create SSH environment");
expect(fixture.connect).not.toHaveBeenCalled();
});
it("starts OAuth from Connectors only when the user clicks Connect", async () => {
render();await settle();
flushSync(() => button("Connect Tailscale Network").click());await settle();
expect(fixture.connect).toHaveBeenCalledWith("company-1", undefined);
expect(button("Connecting…").disabled).toBe(true);
});
it("reconnects the existing connection instead of creating another record", async () => {
fixture.list.mockResolvedValue([{ ...connected, status: "disconnected" }]);
render();await settle();
flushSync(() => button("Reconnect Home tailnet").click());await settle();
expect(fixture.connect).toHaveBeenCalledWith("company-1", "tailnet-1");
});
it("preserves the current tab's Cloud handoff through reauthentication and resumes consent", async () => {
const session = "tailscale_handoff_session_abcdefghijklmnop";
const reauthenticationUrl = new URL(`/cloud/connections/reauth?session=${session}`, window.location.origin).toString();
fixture.connect.mockResolvedValue({ authorizationUrl: "", handoff: { kind: "paperclip_cloud", session } });
vi.stubGlobal("fetch", vi.fn()
.mockResolvedValueOnce(Response.json({ error: "RECENT_LOGIN_REQUIRED", reauthenticationUrl }, { status: 401 }))
.mockResolvedValueOnce(Response.json({ authorizationUrl: "https://login.tailscale.com/a/oauth_authorize" })));
fixture.navigate.mockImplementationOnce(() => {
expect(readPendingCloudHandoff()).toEqual({ kind: "paperclip_cloud", session });
});
render();await settle();
flushSync(() => button("Connect Tailscale Network").click());await settle();
expect(readPendingCloudHandoff()).toEqual({ kind: "paperclip_cloud", session });
expect(fixture.navigate).toHaveBeenCalledWith(reauthenticationUrl);
flushSync(() => root.render(<PaperclipCloudOAuthHandoffPage />));await settle();
expect(fixture.navigate).toHaveBeenLastCalledWith("https://login.tailscale.com/a/oauth_authorize");
expect(readPendingCloudHandoff()).toBeNull();
expect(container.textContent).not.toContain("expired");
});
it.each(["cancelled", "failed"])("explains %s consent and retries the same saved connection", async outcome => {
fixture.search = `tailscale_connection=tailnet-1&tailscale_error=${outcome}`;
fixture.list.mockResolvedValue([{ ...connected, status: "pending" }]);
render();await settle();
expect(container.querySelector('[role="alert"]')?.textContent).toContain(outcome === "cancelled" ? "was canceled" : "could not be completed");
flushSync(() => button("Try again").click());await settle();
expect(fixture.connect).toHaveBeenCalledExactlyOnceWith("company-1", "tailnet-1");
});
it("does not offer a saved-connection retry for a connection outside the current company", async () => {
fixture.search = "tailscale_connection=foreign-connection&tailscale_error=cancelled";
render();await settle();
expect([...container.querySelectorAll("button")].some(element => element.textContent === "Try again")).toBe(false);
expect(fixture.connect).not.toHaveBeenCalled();
});
it("does not display untrusted error text from the return URL", async () => {
fixture.search = new URLSearchParams({ tailscale_connection: "tailnet-1", tailscale_error: "untrusted-provider-error<script>" }).toString();
render();await settle();
expect(container.textContent).not.toContain("untrusted-provider-error");
expect(fixture.connect).not.toHaveBeenCalled();
});
it("refreshes connector status after a deliberate disconnect", async () => {
fixture.list.mockResolvedValueOnce([connected]).mockResolvedValue([{ ...connected, status: "disconnected" }]);
render();await settle();
flushSync(() => button("Disconnect Home tailnet").click());await settle();
expect(fixture.disconnect).toHaveBeenCalledWith("company-1", "tailnet-1");
expect(container.textContent).toContain("Disconnected");
expect(container.textContent).not.toContain("Create SSH environment");
});
it("reports access failure without presenting a usable connection or starting OAuth", async () => {
fixture.list.mockRejectedValue(new ApiError("Instance admin access required", 403, { error: "forbidden" }));
render();await settle();
expect(container.querySelector('[role="alert"]')).not.toBeNull();
expect(button("Connect Tailscale Network").disabled).toBe(true);
expect(container.textContent).not.toContain("Home tailnet");
expect(fixture.connect).not.toHaveBeenCalled();
});
it("does not retain another company's tailnets when the organization changes", async () => {
fixture.list.mockImplementation(async companyId => companyId === "company-1" ? [connected] : []);
render();await settle();
expect(container.textContent).toContain("Home tailnet");
fixture.companyId = "company-2";render();await settle();
expect(container.textContent).not.toContain("Home tailnet");
expect(fixture.list).toHaveBeenCalledWith("company-2");
});
});
+80
View File
@@ -0,0 +1,80 @@
import { useEffect } from "react";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { tailscaleApi } from "@/api/tailscale";
import { describeError } from "@/api/errors";
import { Button } from "@/components/ui/button";
import { useCompany } from "@/context/CompanyContext";
import { useBreadcrumbs } from "@/context/BreadcrumbContext";
import { tailscaleConnectionsKey, useTailscaleConnections } from "@/hooks/useTailscaleConnections";
import { Link, useSearchParams } from "@/lib/router";
import { prepareOAuthNavigation, savePendingCloudHandoff } from "@/lib/oauthHandoff";
import { navigateTopLevel } from "@/lib/browserNavigation";
import { AppLogo } from "./AppLogo";
export const TAILSCALE_CONNECTOR_PATH = "/apps/tailscale";
export function TailscaleConnectorCard({ onNavigate }: { onNavigate: (href: string) => void }) {
const { selectedCompanyId } = useCompany();
const connections = useTailscaleConnections(selectedCompanyId);
const connected = connections.data?.filter(connection => connection.status === "connected") ?? [];
if (!connections.canManage) return null;
return <div role="listitem" data-app-slug="tailscale" data-connected={String(connected.length > 0)} className="overflow-hidden rounded-xl border border-border">
<div className="flex flex-wrap items-center gap-3 px-4 py-4">
<AppLogo name="Tailscale" brandKey="tailscale" size={36} />
<div className="min-w-0 flex-1">
<h2 className="text-sm font-semibold text-foreground">Tailscale</h2>
<p className="mt-0.5 text-xs text-muted-foreground">Connect your tailnet to use its machines in SSH environments.</p>
</div>
<Button type="button" size="sm" variant="outline" onClick={() => onNavigate(TAILSCALE_CONNECTOR_PATH)} aria-label={`${connected.length ? "Manage" : "Connect"} Tailscale`}>{connected.length ? "Manage" : "Connect"}</Button>
</div>
{connected.length > 0 && <p className="border-t border-border px-4 py-3 text-sm text-muted-foreground">{connected.map(connection => connection.name).join(", ")} · Connected</p>}
{connections.error && <p role="alert" className="border-t border-border px-4 py-3 text-sm text-destructive">{describeError(connections.error, { action: "load Tailscale connections" }).body}</p>}
</div>;
}
export function TailscaleConnector() {
const { selectedCompanyId } = useCompany();
const { setBreadcrumbs } = useBreadcrumbs();
const client = useQueryClient();
const [searchParams] = useSearchParams();
const connections = useTailscaleConnections(selectedCompanyId);
const connect = useMutation({ mutationFn: async (connectionId?: string) => {
const result = await tailscaleApi.connect(selectedCompanyId!, connectionId);
const target = await prepareOAuthNavigation(result);
if (target.kind === "reauthentication" && result.handoff) savePendingCloudHandoff(result.handoff.session);
navigateTopLevel(target.url);
} });
const disconnect = useMutation({ mutationFn: (connectionId: string) => tailscaleApi.disconnect(selectedCompanyId!, connectionId),
onSuccess: () => client.invalidateQueries({ queryKey: tailscaleConnectionsKey(selectedCompanyId) }) });
useEffect(() => {
setBreadcrumbs([{ label: "Connectors", href: "/apps" }, { label: "Tailscale" }]);
return () => setBreadcrumbs([]);
}, [setBreadcrumbs]);
if (!selectedCompanyId) return <p className="text-sm text-muted-foreground">Select an organization to connect Tailscale.</p>;
if (connections.access.isPending) return <p className="text-sm text-muted-foreground">Checking Tailscale management access…</p>;
if (connections.access.error) return <p role="alert" className="text-sm text-destructive">{describeError(connections.access.error, { action: "check Tailscale management access" }).body}</p>;
if (!connections.canManage) return <p className="text-sm text-muted-foreground">Ask an instance administrator to connect or manage Tailscale networks.</p>;
const error = connect.error ?? disconnect.error ?? connections.error;
const outcome = searchParams.get("tailscale_error");
const returnError = outcome === "cancelled" ? "Tailscale authorization was canceled. Try again to connect your network."
: outcome === "failed" ? "Tailscale authorization could not be completed. Try again." : null;
const retryConnection = connections.data?.find(connection => connection.id === searchParams.get("tailscale_connection"));
return <div className="max-w-3xl space-y-6 pb-8">
<header className="flex items-center gap-3"><AppLogo name="Tailscale" brandKey="tailscale" size={36} /><h1 className="text-xl font-semibold">Tailscale</h1></header>
<p className="text-sm text-muted-foreground">Give Paperclip access to your tailnet, then choose one of its machines when creating an SSH environment. Agents can use any harness supported by that environment.</p>
{connections.isPending && <p className="text-sm text-muted-foreground">Loading tailnet connections…</p>}
{returnError && <div role="alert" className="space-y-3"><p className="text-sm text-destructive">{returnError}</p>{retryConnection && <Button variant="outline" disabled={connect.isPending} onClick={() => connect.mutate(retryConnection.id)}>Try again</Button>}</div>}
{error && <div role="alert" className="space-y-3"><p className="text-sm text-destructive">{describeError(error, { action: "connect Tailscale" }).body}</p><Button variant="outline" onClick={() => void connections.refetch()}>Refresh connections</Button></div>}
<div className="divide-y divide-border">{(connections.data ?? []).map(connection => <div key={connection.id} className="flex flex-wrap items-center justify-between gap-3 py-3">
<div className="min-w-0 flex-1 space-y-1"><p className="font-medium">{connection.name}</p><p className="text-sm text-muted-foreground">{connection.status === "connected" ? "Connected" : connection.status === "connecting" ? "Connecting" : connection.status === "disconnected" ? "Disconnected" : "Authorization not completed"}</p></div>
{connection.status === "connected" ? <>
<Button variant="outline" asChild><Link to={`/company/settings/instance/environments/new?tailscale_connection=${encodeURIComponent(connection.id)}`}>Create SSH environment</Link></Button>
<Button variant="ghost" disabled={disconnect.isPending} onClick={() => disconnect.mutate(connection.id)}>Disconnect {connection.name}</Button>
</> : <Button variant="outline" disabled={connect.isPending} onClick={() => connect.mutate(connection.id)}>Reconnect {connection.name}</Button>}
</div>)}</div>
<footer className="flex items-center justify-between gap-3 border-t border-border pt-4">
<Button variant="ghost" asChild><Link to="/apps">Back to connectors</Link></Button>
<Button disabled={connect.isPending || connections.isError} onClick={() => connect.mutate(undefined)}>{connect.isPending ? "Connecting…" : "Connect Tailscale Network"}</Button>
</footer>
</div>;
}