mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-16 03:31:44 +01:00
Connect Tailscale networks through device sign-in (#21526)
## Thinking Path > - Paperclip manages AI agents and the environments where they run. > - SSH environments can reach machines through a company Tailscale connection. > - The initial connector requires a managed OAuth app that Tailscale limits to its own tailnet. > - Customers need to connect their own tailnets without registering an app or supplying a key. > - This pull request uses Tailscale's normal device sign-in for new connections. > - Customers approve the Paperclip device and then select their machines in SSH environments. ## Linked Issues or Issue Description **Problem or motivation** The current Tailscale enrollment path cannot serve independent customer tailnets through the documented self-service OAuth app model. It also requires Cloud broker configuration and pilot admission before a customer can start. **Proposed solution** Start a private Tailscale device in the tenant and open its normal sign-in link. Save its encrypted device state before reporting a successful connection. Retain the existing SSH machine selection and agent account behavior. **Alternatives considered** Auth-key entry would require customers to copy a credential. A public OAuth integration still needs a confirmed registration path. Device sign-in uses a documented Tailscale flow without either requirement. See [device authentication](https://tailscale.com/docs/features/tsnet#device-creation-and-authentication) and [OAuth app limitations](https://tailscale.com/docs/features/oauth-apps). **Related PR search** Searched GitHub PRs for `tailscale` and `device sign-in`, and issues for `tailscale`. This follows the merged network connector in [#20617](https://github.com/paperclipai/paperclip/pull/20617) and preserves the SSH agent-account support in [#21248](https://github.com/paperclipai/paperclip/pull/21248). The open [#15648](https://github.com/paperclipai/paperclip/pull/15648) proposes storing an OAuth client and checking its health; this change instead enrolls a device through interactive sign-in so customers do not need an OAuth app. ## What Changed - New connections use device sign-in. Existing connected devices and pending legacy OAuth callbacks remain supported. - Pending sign-ins are bound to their company and initiating user. They have a fixed ten-minute deadline. Device state uses server-owned vault secrets with trusted version and digest checks. - The active Tailscale CLI waits for consent and device approval. Cancellation, expiry, secret deletion, and stale completion cannot restore a cancelled connection. - The connector stays open during sign-in. It provides a link when popups are blocked and shows device approval separately. Progress checks stop on completion, failure, expiry, or unmount. - Shared response types, OpenAPI contracts, SDK source pins, and the API/setup documentation describe the new flow. No database migration or Cloud provider configuration is required. ## Verification - 109 focused tests cover network processes, the real database and encrypted vault, routes, UI, and legacy connection behavior. - Server and UI typechecks pass. - Follow-up `29cf296a597`: reproduced the missing OpenAPI route failure locally. All 70 OpenAPI and Tailscale route tests and server typecheck pass after synchronizing the API contract. - Follow-up `79de05f38b9`: the transient-recovery regression failed before the fix; all 20 connector UI tests and UI typecheck pass after it. The query-error policy check reports no findings. - The public SDK input registry check passes. - [CI attempt 2](https://github.com/paperclipai/paperclip/actions/runs/43535594257/attempts/2) passed on the final head, `29cf296a597e470d432b84767050bc539caa280e`: 57 successful checks, no failures or pending checks. The interrupted canary, E2E shard, and serialized-suite jobs passed on rerun. Greptile is 5/5 on this head with no unresolved review threads. - `pnpm verify --explain` exits 2 because the documentation change selects broad CI coverage. Focused local checks passed; broad CI passed on `29cf296a597e470d432b84767050bc539caa280e`. - Live local qualification on `29cf296a597e470d432b84767050bc539caa280e`: native device sign-in completed with interactive user approval. An isolated Ubuntu 24.04 ARM64 EC2 machine appeared in discovery and passed SSH pairing and workspace probes. The assigned Claude Code agent used a Paperclip-managed subscription, created `hello_world.txt` containing exactly `Hello, world!` plus a newline, posted a completion comment, and marked the task done. An independent read through the private connector verified the bytes, remote user, and hostname. The remote machine had no stored Claude login and no leftover temporary credential directories. - Restarted the local Paperclip server and verified the same Tailscale device identity, online peer discovery, successful SSH probe, and unchanged file without new consent. Temporary public SSH ingress was removed. - Local qualification covers one user tailnet and the final Core revision. Browser UI acceptance, two unrelated tailnets, a hosted restart, and an agent task on the final staging revision are not yet verified. ## Risks - The enrollment method changes. It must pass the live qualification above before broad rollout claims. - Existing encrypted device state and the vault master key must survive a restart or redeploy. Device expiry or removal still requires reconnecting. - The existing one-serving-process-per-instance constraint remains. Concurrent replicas need durable network ownership. - Pending setup uses bounded progress requests and an event-driven CLI with a deadline. It adds no idle database scan. ## Model Used OpenAI GPT-6 Astra (`gpt-6-astra`) through Codex in T3 Code, with xhigh reasoning. Context window size was not exposed by the runtime. No subagents were used. ## Checklist - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] My branch name describes the change and contains no internal ticket or instance details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation - [x] I have considered and documented the risks - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip <noreply@paperclip.ing>
This commit is contained in:
1 parent
cefef8f11d
commit
0a96f972e1
18 files changed
+796
-183
No files matched your search
@@ -16,11 +16,12 @@ 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.
|
||||
Device sign-in opens Tailscale in a separate tab and keeps the connector page
|
||||
open. A normal sign-in link remains available if the browser blocks the tab.
|
||||
Approve the Paperclip device in your own tailnet; no OAuth app, API key, Cloud
|
||||
broker credential, or per-instance pilot admission is needed. If your tailnet
|
||||
requires device approval, the connector shows that separate pending state.
|
||||
Sign-in expires after ten minutes and can be cancelled from the connector.
|
||||
|
||||
SSH setup hides the Network selector when Direct connection is the only
|
||||
available option. A sole connected tailnet is selected automatically and its
|
||||
@@ -66,30 +67,35 @@ 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
|
||||
## Device sign-in 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.
|
||||
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. Only the person who started a pending sign-in can retrieve
|
||||
its sign-in link. Existing SSH environment access governs which agents execute
|
||||
there. Cloud and self-hosted instances use the same Tailscale device sign-in.
|
||||
|
||||
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 instance starts a private userspace Tailscale device and returns its generated
|
||||
`https://login.tailscale.com/a/...` sign-in address. Pending device state is stored
|
||||
in the configured company vault before the address is returned. The active
|
||||
`tailscale up` command watches Tailscale state until consent and any required
|
||||
device approval complete, or the ten-minute deadline expires. It saves the
|
||||
registered device state before marking the connection connected. Pending sign-ins
|
||||
can resume from the saved state after a server restart without extending their
|
||||
deadline. There is no background database scan: browser progress requests exist
|
||||
only during the bounded sign-in, and the CLI waits for Tailscale state events.
|
||||
|
||||
The previous OAuth callback remains available for already-started pilot flows;
|
||||
existing enrolled devices continue to use their saved state. New connections
|
||||
use device sign-in and do not call the Cloud OAuth broker.
|
||||
|
||||
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
|
||||
new version is committed. Private node state, digests and enrollment credentials
|
||||
never appear in connection or environment responses.
|
||||
|
||||
Enrollment tokens and node state are server-owned secrets with a durable
|
||||
@@ -150,7 +156,6 @@ 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
|
||||
@@ -161,31 +166,10 @@ 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:
|
||||
Run the Paperclip instance at `http://localhost:3100`. No local Cloud broker or
|
||||
Tailscale OAuth app is required. The instance needs `tailscale` and `tailscaled`.
|
||||
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
|
||||
@@ -195,19 +179,18 @@ GOBIN="$HOME/.local/share/paperclip-tailscale/bin" go install tailscale.com/cmd/
|
||||
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.
|
||||
Offline tests cover device sign-in without an auth key, saved state and restart,
|
||||
separate company identities, initiator binding, cancellation and expiry, stale
|
||||
completion, trusted credential versions, device approval, popup fallback, and
|
||||
route authorization/CSRF. Existing tests retain legacy broker callback, SSH,
|
||||
pairing, and network lifecycle coverage. These do not prove live consent or
|
||||
remote execution.
|
||||
|
||||
Before rollout, qualify real consent, machine discovery, a Claude task that
|
||||
Before rollout, qualify two unrelated customer tailnets through ordinary device
|
||||
sign-in, machine discovery, and an agent task using its selected AI account 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
|
||||
@@ -218,14 +201,15 @@ 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.
|
||||
The old managed OAuth profile remains disabled unless explicitly configured for
|
||||
its existing pilot. Its same-tailnet registration restriction does not apply to
|
||||
the new device sign-in path. Do not configure a customer-specific OAuth app or
|
||||
admit a pilot instance to make device sign-in work.
|
||||
|
||||
Provider references:
|
||||
|
||||
- [Device authentication](https://tailscale.com/docs/features/tsnet#device-creation-and-authentication)
|
||||
- [Tailscale CLI](https://tailscale.com/docs/reference/tailscale-cli/up)
|
||||
- [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)
|
||||
+26
-11
@@ -10,22 +10,37 @@ 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 |
|
||||
| POST | `/api/companies/{companyId}/tailscale-connections` | Start device sign-in |
|
||||
| POST | `/api/companies/{companyId}/tailscale-connections/{connectionId}/device-login` | Resume device sign-in and read progress |
|
||||
| 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.
|
||||
Status is `pending`, `authorizing`, `connecting`, `connected`, `disconnected`,
|
||||
`expired`, or `error`. 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.
|
||||
To start device sign-in, POST a JSON object with optional `name` and
|
||||
`connectionId`. The name defaults to `My tailnet`. No OAuth app, Cloud broker
|
||||
enrollment, or pasted auth key is required. An existing connection ID resumes an
|
||||
unexpired sign-in or starts a new attempt. Disconnect a connected network before
|
||||
replacing it. Pending sign-in is bound to the initiating user and expires after
|
||||
ten minutes; progress requests do not extend that deadline.
|
||||
|
||||
The `201` response contains `connection` and `expiresAt`, plus `authorizationUrl`
|
||||
when the sign-in link is ready. Open that link so the user can approve the
|
||||
Paperclip device in their tailnet. `needsApproval: true` means a tailnet
|
||||
administrator must approve the device. `expiresAt` is null when no sign-in is
|
||||
pending. No Cloud handoff is returned.
|
||||
|
||||
POST to `/{connectionId}/device-login` under the connections path to resume the
|
||||
private client and read progress. This endpoint takes no request body and
|
||||
returns the same shape with status `200`. Only the user who started the sign-in
|
||||
may continue it, with the same instance-admin and company access checks. Both
|
||||
responses use `Cache-Control: no-store` and `Referrer-Policy: no-referrer`.
|
||||
Stop progress requests when the connection leaves `authorizing` or the deadline
|
||||
passes. DELETE the connection to cancel a pending attempt.
|
||||
|
||||
Machine discovery returns `id`, `name`, `hostname`, `address`, `os`, and `online`
|
||||
for each peer. Use the stable `id` when configuring a Tailscale-backed SSH
|
||||
@@ -43,7 +58,7 @@ 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
|
||||
Pending legacy OAuth flows can still return 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
|
||||
|
||||
@@ -2967,3 +2967,4 @@ export {
|
||||
export { recognizeLinkPreview, type LinkPreviewTarget, type LinkPreviewState, type LinkPreview, type LinkPreviewResult } from "./link-preview.js";
|
||||
export * from "./mcp-apps.js";
|
||||
export * from "./mcp-skills.js";
|
||||
export type { TailscaleConnection, TailscaleDeviceLogin } from "./types/tailscale.js";
|
||||
@@ -0,0 +1,7 @@
|
||||
export type TailscaleConnection = { id: string; companyId: string; name: string; status: string };
|
||||
export type TailscaleDeviceLogin = {
|
||||
connection: TailscaleConnection;
|
||||
expiresAt: string | null;
|
||||
authorizationUrl?: string;
|
||||
needsApproval?: boolean;
|
||||
};
|
||||
@@ -1255,6 +1255,7 @@ describe("openapi routes", () => {
|
||||
const { spec } = loadSpecRoutes();
|
||||
const base = "/api/companies/{companyId}/tailscale-connections";
|
||||
for (const [path, method] of [[base, "get"], [base, "post"], [base + "/{connectionId}", "delete"],
|
||||
[base + "/{connectionId}/device-login", "post"],
|
||||
[base + "/{connectionId}/devices", "get"], [base + "/{connectionId}/pairing", "post"], ["/api/tools/oauth/tailscale/callback", "get"]]) {
|
||||
const operation = spec.paths[path]?.[method];
|
||||
expect(operation).toBeDefined();
|
||||
@@ -1265,13 +1266,27 @@ describe("openapi routes", () => {
|
||||
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);
|
||||
expect(connection.properties.status.enum).toEqual(["pending", "authorizing", "connecting", "connected", "disconnected", "expired", "error"]);
|
||||
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"] });
|
||||
expect(session.required).toEqual(["connection", "expiresAt"]);
|
||||
expect(Object.keys(session.properties).sort()).toEqual(["authorizationUrl", "connection", "expiresAt", "needsApproval"]);
|
||||
expect(session.properties.expiresAt).toMatchObject({ type: "string", format: "date-time", nullable: true });
|
||||
expect(session.properties.authorizationUrl).toMatchObject({ type: "string", format: "uri" });
|
||||
expect(session.properties.needsApproval).toEqual({ type: "boolean" });
|
||||
expect(session.additionalProperties).toBe(false);
|
||||
const progress = spec.paths[base + "/{connectionId}/device-login"].post;
|
||||
expect(progress.responses["200"].content["application/json"].schema).toEqual(session);
|
||||
expect(progress.requestBody).toBeUndefined();
|
||||
for (const response of [start.responses["201"], progress.responses["200"]]) {
|
||||
expect(response.headers).toMatchObject({
|
||||
"Cache-Control": { schema: { enum: ["no-store"] } },
|
||||
"Referrer-Policy": { schema: { enum: ["no-referrer"] } },
|
||||
});
|
||||
}
|
||||
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 } } });
|
||||
|
||||
@@ -7,10 +7,11 @@ 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() },
|
||||
service: { list: vi.fn(), start: vi.fn(), devices: vi.fn(), complete: vi.fn(), disconnect: vi.fn(), pairing: vi.fn(), resume: vi.fn() },
|
||||
configured: vi.fn(), enrollment: vi.fn(), activity: vi.fn(),
|
||||
}));
|
||||
vi.mock("../services/connectors/tailscale/connections.js", () => ({ tailscaleConnectionService: () => fixture.service }));
|
||||
vi.mock("../services/connectors/tailscale/device-login.js", () => ({ tailscaleDeviceLoginService: () => 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 }));
|
||||
@@ -41,10 +42,10 @@ describe("Tailscale connector routes", () => {
|
||||
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 () => {
|
||||
it("starts device sign-in with the signed-in user and company", 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.service.start).toHaveBeenCalledWith({ companyId, userId: "fixture-user", name: "Home" });
|
||||
expect(fixture.activity).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({ action: "tailscale.authorization_started", companyId }));
|
||||
});
|
||||
it("rejects foreign-origin browser mutations before starting consent", async () => {
|
||||
@@ -113,26 +114,15 @@ describe("Tailscale connector routes", () => {
|
||||
expect(response.headers.location).toBeUndefined();
|
||||
expect(fixture.activity).not.toHaveBeenCalled();
|
||||
});
|
||||
it("starts existing instance enrollment when no broker identity exists", async () => {
|
||||
it("starts device sign-in without a Cloud broker identity or pilot admission", 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" },
|
||||
});
|
||||
expect(fixture.enrollment).not.toHaveBeenCalled();
|
||||
expect(fixture.service.start).toHaveBeenCalledWith({ companyId, userId: "fixture-user", name: "Home" });
|
||||
expect(response.headers["cache-control"]).toBe("no-store");
|
||||
});
|
||||
it("checks origin, admin status, and company access before self-hosted enrollment", async () => {
|
||||
fixture.configured.mockReturnValue(null);
|
||||
it("checks origin, admin status, and company access before device sign-in and status requests", async () => {
|
||||
for (const [actor, origin] of [
|
||||
[board, "https://untrusted.example.test"],
|
||||
[{ ...board, isInstanceAdmin: false }, "http://localhost:3100"],
|
||||
@@ -140,18 +130,25 @@ describe("Tailscale connector routes", () => {
|
||||
[{ 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((await request(app(actor as any)).post(path + `/${connectionId}/device-login`).set("Origin", origin).send({})).status).toBe(403);
|
||||
}
|
||||
expect(fixture.enrollment).not.toHaveBeenCalled();
|
||||
expect(fixture.service.start).not.toHaveBeenCalled();
|
||||
expect(fixture.service.resume).not.toHaveBeenCalled();
|
||||
expect(fixture.activity).not.toHaveBeenCalled();
|
||||
});
|
||||
it("returns device sign-in progress only to the authorized initiator", async () => {
|
||||
fixture.service.resume.mockResolvedValue({ connection: { id: connectionId, status: "authorizing" }, needsApproval: true });
|
||||
const response = await request(app()).post(path + `/${connectionId}/device-login`).set("Origin", "http://localhost:3100").send({});
|
||||
expect(response.status).toBe(200);
|
||||
expect(fixture.service.resume).toHaveBeenCalledWith(companyId, connectionId, "fixture-user");
|
||||
expect(response.body.needsApproval).toBe(true);
|
||||
expect(response.headers["cache-control"]).toBe("no-store");
|
||||
});
|
||||
it("does not record a successful enrollment start when enrollment fails", async () => {
|
||||
fixture.configured.mockReturnValue(null);
|
||||
fixture.enrollment.mockRejectedValue(new Error("Enrollment unavailable"));
|
||||
fixture.service.start.mockRejectedValueOnce(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" });
|
||||
|
||||
@@ -1630,6 +1630,7 @@ const BOARD_ONLY_OPERATIONS = new Set([
|
||||
const INSTANCE_ADMIN_OPERATIONS = new Set([
|
||||
"GET /api/companies/{companyId}/tailscale-connections",
|
||||
"POST /api/companies/{companyId}/tailscale-connections",
|
||||
"POST /api/companies/{companyId}/tailscale-connections/{connectionId}/device-login",
|
||||
"GET /api/companies/{companyId}/tailscale-connections/{connectionId}/devices",
|
||||
"DELETE /api/companies/{companyId}/tailscale-connections/{connectionId}",
|
||||
"POST /api/companies/{companyId}/tailscale-connections/{connectionId}/pairing",
|
||||
@@ -9607,8 +9608,20 @@ 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"]),
|
||||
status: z.enum(["pending", "authorizing", "connecting", "connected", "disconnected", "expired", "error"]),
|
||||
}).strict();
|
||||
const tailscaleDeviceLoginResponse = {
|
||||
...r.ok(z.object({
|
||||
connection: tailscaleConnectionResponse,
|
||||
expiresAt: z.string().datetime().nullable(),
|
||||
authorizationUrl: z.string().url().optional(),
|
||||
needsApproval: z.boolean().optional(),
|
||||
}).strict()),
|
||||
headers: {
|
||||
"Cache-Control": { schema: { type: "string", enum: ["no-store"] } },
|
||||
"Referrer-Policy": { schema: { type: "string", enum: ["no-referrer"] } },
|
||||
},
|
||||
};
|
||||
const tailscaleErrors = { 400: r.badRequest, 401: r.unauthorized, 403: r.forbidden, 404: r.notFound, 422: r.unprocessable };
|
||||
|
||||
registry.registerPath({
|
||||
@@ -9621,15 +9634,20 @@ registry.registerPath({
|
||||
|
||||
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.",
|
||||
summary: "Start Tailscale device sign-in",
|
||||
description: "Requires an instance administrator with company access, or local implicit board access. Starts device sign-in without a Cloud broker or OAuth app. Reuses an unexpired sign-in for connectionId; a connected network must be disconnected before replacement. Pending sign-in is bound to its initiating user and has a fixed ten-minute deadline. The authorization URL is present when sign-in is ready; needsApproval identifies a device waiting for tailnet administrator approval.",
|
||||
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 },
|
||||
responses: { 201: tailscaleDeviceLoginResponse, ...tailscaleErrors },
|
||||
});
|
||||
|
||||
registry.registerPath({
|
||||
method: "post", path: "/api/companies/{companyId}/tailscale-connections/{connectionId}/device-login", tags: ["tailscale"],
|
||||
summary: "Resume Tailscale device sign-in and read its progress",
|
||||
description: "Requires the initiating user to retain instance-admin and company access, or local implicit board access. Resumes the private client for an existing sign-in without extending its deadline. Returns connection metadata, an optional sign-in URL or device approval flag, and expiresAt (null when no sign-in is pending). Does not return credentials or node state.",
|
||||
request: { params: tailscaleConnectionParams },
|
||||
responses: { 200: tailscaleDeviceLoginResponse, ...tailscaleErrors },
|
||||
});
|
||||
|
||||
registry.registerPath({
|
||||
|
||||
@@ -2,13 +2,10 @@ 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 { forbidden } 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 { tailscaleDeviceLoginService } from "../services/connectors/tailscale/device-login.js";
|
||||
import { logActivity } from "../services/activity-log.js";
|
||||
import { assertBoard, assertCompanyAccess, getActorInfo } from "./authz.js";
|
||||
|
||||
@@ -21,6 +18,7 @@ function operator(req: Request) {
|
||||
export function tailscaleConnectionRoutes(db: Db) {
|
||||
const router = Router();
|
||||
const service = tailscaleConnectionService(db);
|
||||
const deviceLogin = tailscaleDeviceLoginService(db);
|
||||
router.get("/companies/:companyId/tailscale-connections", async (req, res) => {
|
||||
operator(req);
|
||||
assertCompanyAccess(req, z.string().uuid().parse(req.params.companyId));
|
||||
@@ -30,25 +28,21 @@ export function tailscaleConnectionRoutes(db: Db) {
|
||||
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() });
|
||||
const result = await deviceLogin.start({ companyId, userId, ...req.body });
|
||||
await logActivity(db, { companyId, actorType: "user", actorId: userId, action: "tailscale.authorization_started", entityType: "tailscale_connection", entityId: result.connection.id });
|
||||
res.setHeader("Cache-Control", "no-store");
|
||||
res.setHeader("Referrer-Policy", "no-referrer");
|
||||
res.status(201).json(result);
|
||||
});
|
||||
router.post("/companies/:companyId/tailscale-connections/:connectionId/device-login", async (req, res) => {
|
||||
const userId = operator(req);
|
||||
const companyId = z.string().uuid().parse(req.params.companyId);
|
||||
assertCompanyAccess(req, companyId);
|
||||
const result = await deviceLogin.resume(companyId, z.string().uuid().parse(req.params.connectionId), userId);
|
||||
res.setHeader("Cache-Control", "no-store");
|
||||
res.setHeader("Referrer-Policy", "no-referrer");
|
||||
res.json(result);
|
||||
});
|
||||
router.get("/companies/:companyId/tailscale-connections/:connectionId/devices", async (req, res) => {
|
||||
operator(req);
|
||||
assertCompanyAccess(req, z.string().uuid().parse(req.params.companyId));
|
||||
|
||||
@@ -0,0 +1,108 @@
|
||||
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 } from "./network.js";
|
||||
import { parseTailscaleLoginStatus } from "./device-login-status.js";
|
||||
|
||||
describe("Tailscale interactive device enrollment", () => {
|
||||
let dir: string;
|
||||
let manager: ReturnType<typeof createTailscaleNetworkManager>;
|
||||
beforeEach(async () => {
|
||||
dir = await fs.mkdtemp(path.join(os.tmpdir(), "paperclip-ts-login-test-"));
|
||||
await fs.writeFile(path.join(dir, "daemon"), `#!/usr/bin/env node
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const dir = path.dirname(process.argv.find(arg => arg.startsWith('--socket=')).slice(9));
|
||||
fs.writeFileSync(path.join(dir, 'pid'), String(process.pid));
|
||||
process.on('SIGTERM', () => process.exit(0));
|
||||
setInterval(() => {}, 1000);
|
||||
`, { mode: 0o700 });
|
||||
await fs.writeFile(path.join(dir, "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(9));
|
||||
const statePath = path.join(dir, 'state');
|
||||
if (!fs.existsSync(path.join(dir, 'pid'))) process.exit(4);
|
||||
let state = JSON.parse(fs.readFileSync(statePath, 'utf8'));
|
||||
if (args[1] === 'up') {
|
||||
if (args.some(arg => arg.startsWith('--auth-key'))) process.exit(5);
|
||||
if (state.BackendState === 'Running') process.exit(0);
|
||||
state = { MachineKey: state.MachineKey || path.basename(dir), BackendState: 'NeedsLogin', AuthURL: 'https://login.tailscale.com/a/fixture' };
|
||||
fs.writeFileSync(statePath, JSON.stringify(state));
|
||||
fs.watch(dir, () => {
|
||||
if (JSON.parse(fs.readFileSync(statePath, 'utf8')).BackendState === 'Running') process.exit(0);
|
||||
});
|
||||
} else if (args[1] === 'status') console.log(JSON.stringify(state));
|
||||
`, { mode: 0o700 });
|
||||
manager = createTailscaleNetworkManager({ daemon: path.join(dir, "daemon"), cli: path.join(dir, "cli") });
|
||||
});
|
||||
afterEach(async () => { await manager.close(); await fs.rm(dir, { recursive: true, force: true }); });
|
||||
|
||||
const emptyState = "paperclip-tailscale-state-v1:" + Buffer.from("{}").toString("base64");
|
||||
it("returns a login URL without a key, persists consent, and restores the same device", async () => {
|
||||
let credential = emptyState;
|
||||
const authorized = vi.fn().mockResolvedValue(undefined);
|
||||
const input = { identity: "company:secret", credential, persist: async (value: string) => { credential = value; },
|
||||
login: { expiresAt: Date.now() + 60_000, onAuthorized: authorized, onFailure: vi.fn() } };
|
||||
const socket = await manager.connect(input);
|
||||
expect(await manager.loginStatus(input.identity)).toEqual({ status: "authorizing", authorizationUrl: "https://login.tailscale.com/a/fixture" });
|
||||
const statePath = path.join(path.dirname(socket), "state");
|
||||
const state = JSON.parse(await fs.readFile(statePath, "utf8"));
|
||||
expect(credential).not.toBe(emptyState);
|
||||
expect(authorized).not.toHaveBeenCalled();
|
||||
await fs.writeFile(statePath, JSON.stringify({ ...state, BackendState: "Running", AuthURL: "" }));
|
||||
await vi.waitFor(() => expect(authorized).toHaveBeenCalledOnce());
|
||||
await manager.close();
|
||||
const restored = await manager.connect({ identity: input.identity, credential, persist: input.persist });
|
||||
expect(JSON.parse(await fs.readFile(path.join(path.dirname(restored), "state"), "utf8")).MachineKey).toBe(state.MachineKey);
|
||||
});
|
||||
|
||||
it("reports device approval separately and cancels pending enrollment", async () => {
|
||||
const authorized = vi.fn();
|
||||
const input = { identity: "awaiting-approval", credential: emptyState, persist: vi.fn(),
|
||||
login: { expiresAt: Date.now() + 60_000, onAuthorized: authorized, onFailure: vi.fn() } };
|
||||
const socket = await manager.connect(input);
|
||||
const statePath = path.join(path.dirname(socket), "state");
|
||||
await fs.writeFile(statePath, JSON.stringify({ BackendState: "NeedsMachineAuth" }));
|
||||
expect(await manager.loginStatus(input.identity)).toEqual({ status: "needs_approval" });
|
||||
await manager.disconnect(input.identity);
|
||||
expect(await manager.loginStatus(input.identity)).toBeNull();
|
||||
expect(authorized).not.toHaveBeenCalled();
|
||||
expect(input.login.onFailure).not.toHaveBeenCalled();
|
||||
await expect(fs.stat(path.dirname(socket))).rejects.toMatchObject({ code: "ENOENT" });
|
||||
});
|
||||
|
||||
it("stops an expired sign-in without accepting late consent", async () => {
|
||||
const authorized = vi.fn();
|
||||
const failure = vi.fn().mockResolvedValue(undefined);
|
||||
const socket = await manager.connect({ identity: "expires", credential: emptyState, persist: vi.fn(),
|
||||
login: { expiresAt: Date.now() + 1200, onAuthorized: authorized, onFailure: failure } });
|
||||
await vi.waitFor(() => expect(failure).toHaveBeenCalledOnce(), { timeout: 4000 });
|
||||
await vi.waitFor(async () => expect(await manager.loginStatus("expires")).toBeNull());
|
||||
expect(authorized).not.toHaveBeenCalled();
|
||||
await expect(fs.stat(path.dirname(socket))).rejects.toMatchObject({ code: "ENOENT" });
|
||||
});
|
||||
|
||||
it("lets secret deletion cancel a blocked credential save", async () => {
|
||||
let saveEntered!: () => void, releaseSave!: () => void;
|
||||
const entered = new Promise<void>(resolve => { saveEntered = resolve; });
|
||||
const blocked = new Promise<void>(resolve => { releaseSave = resolve; });
|
||||
const connecting = manager.connect({ identity: "deleted-secret", credential: emptyState,
|
||||
persist: async () => { saveEntered(); await blocked; },
|
||||
login: { expiresAt: Date.now() + 60_000, onAuthorized: vi.fn(), onFailure: vi.fn() } });
|
||||
const settled = connecting.catch(() => undefined);
|
||||
try {
|
||||
await entered;
|
||||
await manager.disconnect("deleted-secret", { discardState: true });
|
||||
await expect(connecting).rejects.toThrow("Tailscale");
|
||||
expect(await manager.loginStatus("deleted-secret")).toBeNull();
|
||||
} finally { releaseSave(); await settled; }
|
||||
});
|
||||
|
||||
it.each(["http://login.tailscale.com/a/fixture", "https://attacker.example/a/fixture", "https://login.tailscale.com/a/fixture?redirect=elsewhere",
|
||||
"https://user:password@login.tailscale.com/a/fixture", "https://login.tailscale.com/a/fixture#token"])("rejects an unexpected sign-in address: %s", AuthURL => {
|
||||
expect(() => parseTailscaleLoginStatus({ BackendState: "NeedsLogin", AuthURL })).toThrow("Invalid Tailscale");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,14 @@
|
||||
export type TailscaleLoginStatus = { status: "authorizing" | "needs_approval" | "connected"; authorizationUrl?: string };
|
||||
|
||||
export function parseTailscaleLoginStatus(value: unknown): TailscaleLoginStatus {
|
||||
const status = value as { BackendState?: unknown; AuthURL?: unknown } | null;
|
||||
if (status?.BackendState === "Running") return { status: "connected" };
|
||||
if (status?.BackendState === "NeedsMachineAuth") return { status: "needs_approval" };
|
||||
if (typeof status?.AuthURL === "string" && status.AuthURL) {
|
||||
const url = new URL(status.AuthURL);
|
||||
if (url.origin !== "https://login.tailscale.com" || url.username || url.password || url.search || url.hash
|
||||
|| !/^\/a\/[a-zA-Z0-9_-]+$/.test(url.pathname)) throw new Error("Invalid Tailscale sign-in address");
|
||||
return { status: "authorizing", authorizationUrl: url.toString() };
|
||||
}
|
||||
return { status: "authorizing" };
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { companies, createDb, tailscaleConnections, type Db } from "@paperclipai/db";
|
||||
import { eq } from "drizzle-orm";
|
||||
import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "../../../__tests__/helpers/embedded-postgres.js";
|
||||
import { createIsolatedTestHome } from "../../../__tests__/helpers/isolated-test-home.js";
|
||||
import { secretService } from "../../secrets.js";
|
||||
import { tailscaleDeviceLoginService } from "./device-login.js";
|
||||
import { tailscaleConnectionService } from "./connections.js";
|
||||
import { tailscaleNetworks } from "./network.js";
|
||||
|
||||
const support = await getEmbeddedPostgresTestSupport();
|
||||
describe.skipIf(!support.supported)("durable device sign-in", () => {
|
||||
let db: Db;
|
||||
let cleanup: () => Promise<void>;
|
||||
let home: ReturnType<typeof createIsolatedTestHome>;
|
||||
let companyId: string;
|
||||
let now: Date;
|
||||
let vault: ReturnType<typeof secretService>;
|
||||
let service: ReturnType<typeof tailscaleDeviceLoginService>;
|
||||
const connect = vi.fn<typeof tailscaleNetworks.connect>();
|
||||
const disconnect = vi.fn<typeof tailscaleNetworks.disconnect>();
|
||||
const loginStatus = vi.fn<typeof tailscaleNetworks.loginStatus>();
|
||||
const state = (machine: string) => "paperclip-tailscale-state-v1:" + Buffer.from(JSON.stringify({ MachineKey: machine })).toString("base64");
|
||||
beforeAll(async () => {
|
||||
home = createIsolatedTestHome();
|
||||
vi.stubEnv("PAPERCLIP_HOME", home.home);
|
||||
vi.stubEnv("PAPERCLIP_INSTANCE_ID", "tailscale-device-login-fixture");
|
||||
vi.stubEnv("PAPERCLIP_SECRETS_PROVIDER", "local_encrypted");
|
||||
vi.stubEnv("PAPERCLIP_SECRETS_MASTER_KEY", "b".repeat(64));
|
||||
const started = await startEmbeddedPostgresTestDatabase("tailscale-device-login");
|
||||
cleanup = started.cleanup;
|
||||
db = createDb(started.connectionString);
|
||||
});
|
||||
afterAll(async () => { await cleanup?.(); vi.unstubAllEnvs(); home?.cleanup(); });
|
||||
beforeEach(async () => {
|
||||
companyId = randomUUID();
|
||||
now = new Date();
|
||||
await db.insert(companies).values({ id: companyId, name: "Device login fixture", issuePrefix: randomUUID().slice(0, 8).toUpperCase() });
|
||||
vault = secretService(db);
|
||||
connect.mockReset().mockImplementation(async input => { await input.reload?.(); await input.persist(state(input.identity)); return "/private/tailscale-fixture/socket"; });
|
||||
disconnect.mockReset().mockResolvedValue(undefined);
|
||||
loginStatus.mockReset().mockResolvedValue({ status: "authorizing", authorizationUrl: "https://login.tailscale.com/a/fixture" });
|
||||
service = tailscaleDeviceLoginService(db, { secrets: vault, networks: { connect, disconnect, loginStatus }, now: () => now });
|
||||
});
|
||||
const start = () => service.start({ companyId, userId: "fixture-user", name: "Home" });
|
||||
async function row(id: string) { return (await db.select().from(tailscaleConnections).where(eq(tailscaleConnections.id, id)))[0]!; }
|
||||
|
||||
it("stores device state without an OAuth app and completes only after the daemon confirms consent", async () => {
|
||||
const result = await start();
|
||||
expect(result).toMatchObject({ connection: { companyId, status: "authorizing" }, authorizationUrl: "https://login.tailscale.com/a/fixture" });
|
||||
expect(JSON.stringify(result)).not.toContain("MachineKey");
|
||||
const saved = await row(result.connection.id);
|
||||
const input = connect.mock.calls[0]![0];
|
||||
expect(await vault.resolveSystemSecretValue(companyId, saved.secretId!, saved.credentialVersion!, "tailscale_network", "fixture")).toBe(state(input.identity));
|
||||
await input.login!.onAuthorized();
|
||||
expect(await service.resume(companyId, saved.id, "fixture-user")).toMatchObject({ connection: { status: "connected" }, expiresAt: null });
|
||||
expect(await row(saved.id)).toMatchObject({ secretId: saved.secretId, oauthExpiresAt: null, status: "connected" });
|
||||
});
|
||||
|
||||
it("resumes an interrupted sign-in with the same encrypted state and deadline", async () => {
|
||||
const first = await start();
|
||||
const saved = await row(first.connection.id);
|
||||
const resumedService = tailscaleDeviceLoginService(db, { secrets: vault, networks: { connect, disconnect, loginStatus }, now: () => now });
|
||||
const resumed = await resumedService.resume(companyId, saved.id, "fixture-user");
|
||||
expect(resumed.expiresAt).toBe(first.expiresAt);
|
||||
expect(connect.mock.calls[1]![0].credential).toBe(state(connect.mock.calls[0]![0].identity));
|
||||
expect((await row(saved.id)).secretId).toBe(saved.secretId);
|
||||
});
|
||||
|
||||
it("keeps independent companies and sign-in initiators isolated", async () => {
|
||||
const first = await start();
|
||||
await expect(service.resume(randomUUID(), first.connection.id, "fixture-user")).rejects.toMatchObject({ status: 404 });
|
||||
await expect(service.resume(companyId, first.connection.id, "other-user")).rejects.toMatchObject({ status: 403 });
|
||||
const secondCompany = randomUUID();
|
||||
await db.insert(companies).values({ id: secondCompany, name: "Separate tailnet", issuePrefix: randomUUID().slice(0, 8).toUpperCase() });
|
||||
const second = await service.start({ companyId: secondCompany, userId: "other-user", name: "Work" });
|
||||
expect(connect.mock.calls[0]![0].identity).not.toBe(connect.mock.calls[1]![0].identity);
|
||||
expect((await row(first.connection.id)).secretId).not.toBe((await row(second.connection.id)).secretId);
|
||||
});
|
||||
|
||||
it("does not revive a disconnected or replaced sign-in when an old daemon finishes", async () => {
|
||||
const first = await start();
|
||||
const old = connect.mock.calls[0]![0];
|
||||
const connections = tailscaleConnectionService(db, { secrets: vault, networks: { connect, disconnect } });
|
||||
await connections.disconnect(companyId, first.connection.id);
|
||||
await expect(old.login!.onAuthorized()).rejects.toMatchObject({ status: 422 });
|
||||
const before = await row(first.connection.id);
|
||||
await old.persist(state("stale"));
|
||||
expect((await row(first.connection.id)).credentialVersion).toBe(before.credentialVersion);
|
||||
const replacement = await service.start({ companyId, userId: "fixture-user", name: "Home", connectionId: first.connection.id });
|
||||
const latest = connect.mock.calls.at(-1)![0];
|
||||
await latest.login!.onAuthorized();
|
||||
await old.login!.onFailure();
|
||||
expect((await row(replacement.connection.id)).status).toBe("connected");
|
||||
expect(latest.identity).not.toBe(old.identity);
|
||||
});
|
||||
|
||||
it("expires pending consent and stops its network without extending the deadline", async () => {
|
||||
const first = await start();
|
||||
const input = connect.mock.calls[0]![0];
|
||||
now = new Date(Date.parse(first.expiresAt!) + 1);
|
||||
expect(await service.resume(companyId, first.connection.id, "fixture-user")).toMatchObject({ connection: { status: "expired" }, expiresAt: null });
|
||||
expect(disconnect).toHaveBeenCalledWith(input.identity);
|
||||
await expect(input.login!.onAuthorized()).rejects.toMatchObject({ status: 422 });
|
||||
expect(connect).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it("does not stop an approved connection when an older progress request fails", async () => {
|
||||
const first = await start();
|
||||
const input = connect.mock.calls[0]![0];
|
||||
let entered!: () => void, reject!: (error: Error) => void;
|
||||
const waiting = new Promise<void>(resolve => { entered = resolve; });
|
||||
connect.mockImplementationOnce(() => { entered(); return new Promise((_resolve, fail) => { reject = fail; }); });
|
||||
const older = service.resume(companyId, first.connection.id, "fixture-user");
|
||||
const failed = expect(older).rejects.toMatchObject({ status: 422 });
|
||||
await waiting;
|
||||
await input.login!.onAuthorized();
|
||||
reject(new Error("Old request failed"));
|
||||
await failed;
|
||||
expect((await row(first.connection.id)).status).toBe("connected");
|
||||
expect(disconnect).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("removes the new secret if disconnect wins while sign-in is being prepared", async () => {
|
||||
const first = await start();
|
||||
const connections = tailscaleConnectionService(db, { secrets: vault, networks: { connect, disconnect } });
|
||||
await connections.disconnect(companyId, first.connection.id);
|
||||
let entered!: () => void, release!: () => void;
|
||||
const waiting = new Promise<void>(resolve => { entered = resolve; });
|
||||
const blocked = new Promise<void>(resolve => { release = resolve; });
|
||||
const create = vault.createSystemSecret.bind(vault);
|
||||
let createdId = "";
|
||||
vi.spyOn(vault, "createSystemSecret").mockImplementationOnce(async (...args) => {
|
||||
const created = await create(...args); createdId = created.id; entered(); await blocked; return created;
|
||||
});
|
||||
const removed = vi.spyOn(vault, "remove");
|
||||
const replacement = service.start({ companyId, userId: "fixture-user", name: "Home", connectionId: first.connection.id });
|
||||
const failed = expect(replacement).rejects.toMatchObject({ status: 422 });
|
||||
await waiting;
|
||||
await connections.disconnect(companyId, first.connection.id);
|
||||
release();
|
||||
await failed;
|
||||
expect(removed).toHaveBeenCalledWith(createdId);
|
||||
expect((await row(first.connection.id)).status).toBe("disconnected");
|
||||
});
|
||||
|
||||
it("rejects a rotated credential instead of joining another tailnet", async () => {
|
||||
const first = await start();
|
||||
const saved = await row(first.connection.id);
|
||||
await vault.rotate(saved.secretId!, { value: "tskey-auth-untrusted" });
|
||||
await service.resume(companyId, saved.id, "fixture-user");
|
||||
expect(connect.mock.calls.at(-1)![0].credential).toBe(state(connect.mock.calls[0]![0].identity));
|
||||
await db.update(tailscaleConnections).set({ credentialHash: "0".repeat(64) }).where(eq(tailscaleConnections.id, saved.id));
|
||||
await expect(service.resume(companyId, saved.id, "fixture-user")).rejects.toMatchObject({ status: 422 });
|
||||
expect(connect).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,121 @@
|
||||
import { createHash, randomBytes } from "node:crypto";
|
||||
import { and, eq, gt, isNull } from "drizzle-orm";
|
||||
import { tailscaleConnections, type Db } from "@paperclipai/db";
|
||||
import type { TailscaleDeviceLogin } from "@paperclipai/shared";
|
||||
import { forbidden, notFound, unprocessable } from "../../../errors.js";
|
||||
import { logActivity } from "../../activity-log.js";
|
||||
import { secretService } from "../../secrets.js";
|
||||
import { getConfiguredSecretProvider } from "../../../secrets/configured-provider.js";
|
||||
import { tailscaleNetworks } from "./network.js";
|
||||
|
||||
const digest = (value: string) => createHash("sha256").update(value).digest("hex");
|
||||
const emptyState = "paperclip-tailscale-state-v1:" + Buffer.from("{}").toString("base64");
|
||||
const projection = (row: typeof tailscaleConnections.$inferSelect) => ({ id: row.id, companyId: row.companyId, name: row.name, status: row.status });
|
||||
|
||||
export function tailscaleDeviceLoginService(db: Db, dependencies: {
|
||||
networks?: Pick<typeof tailscaleNetworks, "connect" | "disconnect" | "loginStatus">;
|
||||
secrets?: Pick<ReturnType<typeof secretService>, "createSystemSecret" | "resolveSystemSecretValue" | "rotate" | "remove">;
|
||||
now?: () => Date;
|
||||
} = {}) {
|
||||
const networks = dependencies.networks ?? tailscaleNetworks;
|
||||
const secrets = dependencies.secrets ?? secretService(db);
|
||||
const now = dependencies.now ?? (() => new Date());
|
||||
const cancelled = () => unprocessable("Tailscale sign-in expired or was cancelled. Connect again.", { code: "tailscale_authorization_cancelled" });
|
||||
async function get(companyId: string, id: string) {
|
||||
const [row] = await db.select().from(tailscaleConnections).where(and(eq(tailscaleConnections.companyId, companyId), eq(tailscaleConnections.id, id)));
|
||||
if (!row) throw notFound("Tailscale connection not found");
|
||||
return row;
|
||||
}
|
||||
|
||||
async function resume(companyId: string, id: string, userId: string): Promise<TailscaleDeviceLogin> {
|
||||
const row = await get(companyId, id);
|
||||
if (row.createdByUserId !== userId) throw forbidden("Only the person who started this sign-in can continue it.");
|
||||
if (row.status !== "authorizing") return { connection: projection(row), expiresAt: null };
|
||||
if (!row.secretId || !row.oauthStateHash?.startsWith("device:")) throw cancelled();
|
||||
const secretId = row.secretId;
|
||||
const identity = `${companyId}:${secretId}`;
|
||||
const owned = and(eq(tailscaleConnections.companyId, companyId), eq(tailscaleConnections.id, id),
|
||||
eq(tailscaleConnections.secretId, secretId), eq(tailscaleConnections.oauthStateHash, row.oauthStateHash));
|
||||
if (!row.oauthExpiresAt || row.oauthExpiresAt <= now()) {
|
||||
const expired = await db.update(tailscaleConnections).set({ status: "expired", oauthExpiresAt: null, updatedAt: now() })
|
||||
.where(and(owned, eq(tailscaleConnections.status, "authorizing"))).returning();
|
||||
if (expired.length) await networks.disconnect(identity);
|
||||
return { connection: projection(await get(companyId, id)), expiresAt: null };
|
||||
}
|
||||
async function current() {
|
||||
const latest = await get(companyId, id);
|
||||
if (latest.secretId !== secretId || latest.oauthStateHash !== row.oauthStateHash
|
||||
|| !["authorizing", "connected"].includes(latest.status)) throw cancelled();
|
||||
if (!latest.credentialVersion || !latest.credentialHash) throw cancelled();
|
||||
return latest;
|
||||
}
|
||||
const read = async () => {
|
||||
const latest = await current();
|
||||
const value = await secrets.resolveSystemSecretValue(companyId, secretId, latest.credentialVersion!, "tailscale_network", `tailscale-connection:${id}`);
|
||||
if (digest(value) !== latest.credentialHash) throw cancelled();
|
||||
return value;
|
||||
};
|
||||
try {
|
||||
await networks.connect({ identity, credential: await read(), reload: read,
|
||||
persist: async value => {
|
||||
const latest = await get(companyId, id);
|
||||
if (latest.secretId !== secretId || latest.oauthStateHash !== row.oauthStateHash
|
||||
|| !["authorizing", "connected"].includes(latest.status)) return;
|
||||
const saved = await secrets.rotate(secretId, { value });
|
||||
const [updated] = await db.update(tailscaleConnections).set({ credentialVersion: saved.latestVersion, credentialHash: digest(value), updatedAt: now() })
|
||||
.where(and(owned, eq(tailscaleConnections.credentialVersion, latest.credentialVersion!), eq(tailscaleConnections.credentialHash, latest.credentialHash!))).returning();
|
||||
if (!updated) throw cancelled();
|
||||
},
|
||||
login: { expiresAt: row.oauthExpiresAt.getTime(),
|
||||
onAuthorized: async () => {
|
||||
await db.transaction(async tx => {
|
||||
const [ready] = await tx.update(tailscaleConnections).set({ status: "connected", oauthExpiresAt: null, updatedAt: now() })
|
||||
.where(and(owned, eq(tailscaleConnections.status, "authorizing"), gt(tailscaleConnections.oauthExpiresAt, now()))).returning();
|
||||
if (!ready) throw cancelled();
|
||||
await logActivity(tx as unknown as Db, { companyId, actorType: "user", actorId: userId, action: "tailscale.connected", entityType: "tailscale_connection", entityId: id });
|
||||
});
|
||||
},
|
||||
onFailure: async () => {
|
||||
await db.update(tailscaleConnections).set({ status: row.oauthExpiresAt! <= now() ? "expired" : "error", oauthExpiresAt: null, updatedAt: now() })
|
||||
.where(and(owned, eq(tailscaleConnections.status, "authorizing")));
|
||||
},
|
||||
},
|
||||
});
|
||||
const status = await networks.loginStatus(identity);
|
||||
const latest = await current();
|
||||
return { connection: projection(latest), expiresAt: latest.oauthExpiresAt?.toISOString() ?? null,
|
||||
...(latest.status === "authorizing" && status ? { authorizationUrl: status.authorizationUrl, needsApproval: status.status === "needs_approval" } : {}) };
|
||||
} catch {
|
||||
const failed = await db.update(tailscaleConnections).set({ status: "error", oauthExpiresAt: null, updatedAt: now() })
|
||||
.where(and(owned, eq(tailscaleConnections.status, "authorizing"))).returning();
|
||||
if (failed.length) await networks.disconnect(identity);
|
||||
throw unprocessable("Tailscale sign-in could not start. Check that Tailscale is installed, then try again.", { code: "tailscale_device_login_failed" });
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
resume,
|
||||
async start(input: { companyId: string; userId: string; name: string; connectionId?: string }): Promise<TailscaleDeviceLogin> {
|
||||
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]!;
|
||||
if (row.status === "connected") throw unprocessable("Disconnect this network before replacing its connection.");
|
||||
if (row.status === "authorizing" && row.oauthExpiresAt && row.oauthExpiresAt > now()) return resume(input.companyId, row.id, input.userId);
|
||||
const state = `device:${randomBytes(32).toString("hex")}`;
|
||||
const expiresAt = new Date(now().getTime() + 10 * 60_000);
|
||||
const secret = await secrets.createSystemSecret(input.companyId, { name: `Tailscale connection ${row.id} ${randomBytes(4).toString("hex")}`,
|
||||
provider: getConfiguredSecretProvider(), value: emptyState }, "tailscale_network", { userId: input.userId });
|
||||
try {
|
||||
const [started] = await db.update(tailscaleConnections).set({ status: "authorizing", secretId: secret.id,
|
||||
credentialVersion: secret.latestVersion, credentialHash: digest(emptyState), oauthStateHash: state, oauthExpiresAt: expiresAt,
|
||||
createdByUserId: input.userId, updatedAt: now() }).where(and(eq(tailscaleConnections.id, row.id), eq(tailscaleConnections.companyId, input.companyId), eq(tailscaleConnections.status, row.status),
|
||||
row.oauthStateHash === null ? isNull(tailscaleConnections.oauthStateHash) : eq(tailscaleConnections.oauthStateHash, row.oauthStateHash))).returning();
|
||||
if (!started) throw cancelled();
|
||||
} catch (error) {
|
||||
await secrets.remove(secret.id);
|
||||
throw error;
|
||||
}
|
||||
if (row.secretId) await networks.disconnect(`${input.companyId}:${row.secretId}`);
|
||||
return resume(input.companyId, row.id, input.userId);
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -3,6 +3,7 @@ import { promises as fs } from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { promisify } from "node:util";
|
||||
import { parseTailscaleLoginStatus, type TailscaleLoginStatus } from "./device-login-status.js";
|
||||
|
||||
const exec = promisify(execFile);
|
||||
const STATE_PREFIX = "paperclip-tailscale-state-v1:";
|
||||
@@ -12,7 +13,10 @@ 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> };
|
||||
type DeviceLogin = { expiresAt: number; onAuthorized: () => Promise<void>; onFailure: () => Promise<void> };
|
||||
type Connection = { credential: string; savedCredential?: string; child?: ChildProcess; loginChild?: ChildProcess;
|
||||
loginStatus?: () => Promise<TailscaleLoginStatus>; 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>();
|
||||
@@ -23,6 +27,7 @@ export function createTailscaleNetworkManager(commands: { cli?: string; daemon?:
|
||||
credential: string;
|
||||
persist: (credential: string) => Promise<void>;
|
||||
reload?: () => Promise<string>;
|
||||
login?: DeviceLogin;
|
||||
}, expectedGeneration = generation): Promise<string> {
|
||||
if (expectedGeneration !== generation) throw new Error("Tailscale stopped");
|
||||
const existing = connections.get(input.identity);
|
||||
@@ -64,7 +69,7 @@ export function createTailscaleNetworkManager(commands: { cli?: string; daemon?:
|
||||
return connection.ready;
|
||||
}
|
||||
|
||||
async function start(input: { identity: string; credential: string; persist: (credential: string) => Promise<void> }, connection: Connection) {
|
||||
async function start(input: { identity: string; credential: string; persist: (credential: string) => Promise<void>; login?: DeviceLogin }, 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");
|
||||
@@ -73,8 +78,34 @@ export function createTailscaleNetworkManager(commands: { cli?: string; daemon?:
|
||||
|
||||
let dir: string | undefined;
|
||||
let statePath: string | undefined;
|
||||
let saving = Promise.resolve();
|
||||
const persist = async (value: string) => {
|
||||
const signal = connection.discardState.signal;
|
||||
if (signal.aborted) return;
|
||||
let discard!: () => void;
|
||||
const discarded = new Promise<void>(resolve => { discard = resolve; });
|
||||
signal.addEventListener("abort", discard, { once: true });
|
||||
try {
|
||||
await Promise.race([input.persist(value), discarded]);
|
||||
if (!signal.aborted) connection.savedCredential = value;
|
||||
} finally { signal.removeEventListener("abort", discard); }
|
||||
};
|
||||
const save = () => {
|
||||
const pending = saving.then(async () => {
|
||||
if (connection.discardState.signal.aborted || !statePath) return;
|
||||
const bytes = await fs.readFile(statePath);
|
||||
if (!bytes.length || bytes.length > MAX_STATE_BYTES) throw new Error("Invalid state");
|
||||
const next = STATE_PREFIX + bytes.toString("base64");
|
||||
if (next !== connection.savedCredential) {
|
||||
await persist(next);
|
||||
}
|
||||
});
|
||||
saving = pending.catch(() => undefined);
|
||||
return pending;
|
||||
};
|
||||
connection.close = () => connection.closing ??= (async () => {
|
||||
connection.closed = true;
|
||||
connection.loginChild?.kill("SIGKILL");
|
||||
const child = connection.child;
|
||||
if (child?.pid && child.exitCode === null && child.signalCode === null) {
|
||||
await new Promise<void>((resolve) => {
|
||||
@@ -84,20 +115,13 @@ export function createTailscaleNetworkManager(commands: { cli?: string; daemon?:
|
||||
});
|
||||
}
|
||||
try {
|
||||
await saving;
|
||||
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); }
|
||||
await persist(latest);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -134,6 +158,48 @@ export function createTailscaleNetworkManager(commands: { cli?: string; daemon?:
|
||||
await new Promise((resolve) => setTimeout(resolve, 100));
|
||||
}
|
||||
}
|
||||
if (input.login) {
|
||||
const login = input.login;
|
||||
const remaining = login.expiresAt - Date.now();
|
||||
if (remaining <= 0 || remaining > 10 * 60_000) throw new Error("Tailscale sign-in expired");
|
||||
const up = exec(cliCommand, [`--socket=${socket}`, "up", "--accept-dns=false", "--accept-routes=false", "--shields-up",
|
||||
`--timeout=${remaining}ms`, `--hostname=paperclip-${input.identity.replace(/[^a-z0-9]/gi, "").slice(-16)}`],
|
||||
{ timeout: remaining + 1000, maxBuffer: MAX_STATE_BYTES });
|
||||
connection.loginChild = up.child;
|
||||
let loginFailed = false;
|
||||
const completion = up.then(async () => {
|
||||
if (connection.closed) return;
|
||||
if (Date.now() >= login.expiresAt) throw new Error("Tailscale sign-in expired");
|
||||
const status = parseTailscaleLoginStatus(JSON.parse((await cli(["status", "--json"])).stdout));
|
||||
if (status.status !== "connected") throw new Error("Tailscale sign-in did not complete");
|
||||
await save();
|
||||
if (!connection.closed) await login.onAuthorized();
|
||||
}).catch(async () => {
|
||||
loginFailed = true;
|
||||
if (connection.closed) return;
|
||||
try { await login.onFailure(); } finally { await connection.close(); }
|
||||
});
|
||||
// The active CLI watches Tailscale events until consent, cancellation, or expiry.
|
||||
void completion.catch(() => undefined);
|
||||
connection.loginStatus = async () => {
|
||||
if (loginFailed || connection.closed) throw new Error("Tailscale sign-in did not complete");
|
||||
const status = parseTailscaleLoginStatus(JSON.parse((await cli(["status", "--json"])).stdout));
|
||||
if (status.status === "connected") await completion;
|
||||
if (loginFailed || connection.closed) throw new Error("Tailscale sign-in did not complete");
|
||||
return status;
|
||||
};
|
||||
const loginDeadline = Math.min(login.expiresAt, Date.now() + 10_000);
|
||||
for (;;) {
|
||||
const status = await connection.loginStatus();
|
||||
if (status.status !== "authorizing" || status.authorizationUrl) {
|
||||
await save();
|
||||
if (failed || connection.closed) throw new Error("Tailscale stopped");
|
||||
return socket;
|
||||
}
|
||||
if (Date.now() >= loginDeadline) throw new Error("Tailscale sign-in 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",
|
||||
@@ -144,17 +210,20 @@ export function createTailscaleNetworkManager(commands: { cli?: string; daemon?:
|
||||
}
|
||||
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;
|
||||
connection.savedCredential = input.credential;
|
||||
await save();
|
||||
if (failed || connection.closed) throw new Error("Tailscale stopped");
|
||||
return socket;
|
||||
}
|
||||
|
||||
return {
|
||||
connect: (input: Parameters<typeof connect>[0]) => connect(input),
|
||||
async loginStatus(identity: string) {
|
||||
const connection = connections.get(identity);
|
||||
if (!connection) return null;
|
||||
await connection.ready;
|
||||
return connection.loginStatus ? connection.loginStatus() : { status: "connected" as const };
|
||||
},
|
||||
async disconnect(identity: string, options: { discardState?: boolean } = {}) {
|
||||
const connection = connections.get(identity);
|
||||
if (!connection) return;
|
||||
|
||||
@@ -268,7 +268,7 @@
|
||||
"packages/shared/src/home-paths.ts": "fa4f1c440653b76b3dbb7a51026d557287deb45d",
|
||||
"packages/shared/src/humanize-connection.test.ts": "ba9e90a44c63452b0bf9f733adb90241921e8eca",
|
||||
"packages/shared/src/humanize-connection.ts": "fbd414476a0ef7106a7c80d8572208781b091699",
|
||||
"packages/shared/src/index.ts": "17f32ce6e701bef6a98cdf685ab1616ab10e99b9",
|
||||
"packages/shared/src/index.ts": "2d2b5ba044c9c7a22ff99022c0fac1e0da5e4a94",
|
||||
"packages/shared/src/issue-activity-identity.test.ts": "3dc294640f54c2be67943e3e0149cf4eff2c95ca",
|
||||
"packages/shared/src/issue-activity-identity.ts": "1b0f07ec3fe0506aaaf80a4fa9893f3baf8f0075",
|
||||
"packages/shared/src/issue-attribution.test.ts": "84563685e7f3c48029243cf1cc24a3a09ee3cde9",
|
||||
@@ -427,6 +427,7 @@
|
||||
"packages/shared/src/types/skill-source.ts": "f34624008f2f852df198bb5f499f75f657c4f30e",
|
||||
"packages/shared/src/types/smoke-lab.ts": "534b1a1ef3f8fda6ae9a15e009c4f247a6f0b9e3",
|
||||
"packages/shared/src/types/summary-slot.ts": "9698bb7d628be3f2310d050037e30157d474ed48",
|
||||
"packages/shared/src/types/tailscale.ts": "d02a917945d7779009a2dea4c4b535e9478e0680",
|
||||
"packages/shared/src/types/task-workspace.ts": "a23afa13d2cb58dc2eb72692ed28c16ed6fb84fb",
|
||||
"packages/shared/src/types/teams-catalog.ts": "632fe75f8e5a4cfc455843c2a1a2daff28a022be",
|
||||
"packages/shared/src/types/tool-access.ts": "4c05d176f9bb1d30593fd904c7c4fc3e91b431ca",
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
import type { ToolOAuthStartResult } from "@paperclipai/shared";
|
||||
import type { TailscaleConnection, TailscaleDeviceLogin } from "@paperclipai/shared";
|
||||
import { api } from "./client";
|
||||
|
||||
export type TailscaleConnection = { id: string; companyId: string; name: string; status: string };
|
||||
export type { TailscaleConnection } from "@paperclipai/shared";
|
||||
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 } : {}) }),
|
||||
connect: (companyId: string, connectionId?: string) => api.post<TailscaleDeviceLogin>(`/companies/${companyId}/tailscale-connections`, { name: "My tailnet", ...(connectionId ? { connectionId } : {}) }),
|
||||
deviceLogin: (companyId: string, connectionId: string) => api.post<TailscaleDeviceLogin>(`/companies/${companyId}/tailscale-connections/${connectionId}/device-login`, {}),
|
||||
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 }),
|
||||
|
||||
@@ -5,12 +5,11 @@ 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";
|
||||
import { shouldRetryRequest } from "@/lib/query-client";
|
||||
|
||||
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() }));
|
||||
const fixture = vi.hoisted(() => ({ companyId: "company-1", search: "", navigate: vi.fn(), access: vi.fn(), list: vi.fn(), connect: vi.fn(), deviceLogin: 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("@/api/tailscale", () => ({ tailscaleApi: { list: fixture.list, connect: fixture.connect, deviceLogin: fixture.deviceLogin, disconnect: fixture.disconnect } }));
|
||||
vi.mock("@/context/CompanyContext", () => ({ useCompany: () => ({ selectedCompanyId: fixture.companyId }) }));
|
||||
vi.mock("@/context/BreadcrumbContext", () => ({ useBreadcrumbs: () => ({ setBreadcrumbs: fixture.breadcrumbs }) }));
|
||||
vi.mock("./AppLogo", () => ({ AppLogo: () => null }));
|
||||
@@ -33,6 +32,8 @@ function button(label: string) {
|
||||
describe("Tailscale network connector", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
vi.spyOn(window, "open").mockReturnValue(null);
|
||||
fixture.deviceLogin.mockResolvedValue({ connection: { ...connected, status: "authorizing" }, authorizationUrl: "https://login.tailscale.com/a/fixture", expiresAt: new Date(Date.now() + 600_000).toISOString() });
|
||||
fixture.companyId = "company-1";
|
||||
fixture.search = "";
|
||||
window.sessionStorage.clear();
|
||||
@@ -83,7 +84,7 @@ describe("Tailscale network connector", () => {
|
||||
expect(fixture.connect).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("starts OAuth from Connectors only when the user clicks Connect", async () => {
|
||||
it("starts device sign-in 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);
|
||||
@@ -97,24 +98,77 @@ describe("Tailscale network connector", () => {
|
||||
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 });
|
||||
});
|
||||
it("keeps the connector open and offers a sign-in link when popups are blocked", async () => {
|
||||
fixture.connect.mockResolvedValue({ connection: { ...connected, status: "authorizing" }, authorizationUrl: "https://login.tailscale.com/a/fixture", expiresAt: new Date(Date.now() + 600_000).toISOString() });
|
||||
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");
|
||||
expect(window.open).toHaveBeenCalledWith("about:blank", "_blank");
|
||||
expect(fixture.navigate).not.toHaveBeenCalled();
|
||||
expect(fixture.deviceLogin).toHaveBeenCalledWith("company-1", "tailnet-1");
|
||||
expect(container.querySelector('a[href="https://login.tailscale.com/a/fixture"]')?.textContent).toBe("Continue to Tailscale");
|
||||
expect(button("Cancel sign-in")).toBeDefined();
|
||||
});
|
||||
|
||||
it("shows administrator approval separately from sign-in", async () => {
|
||||
fixture.list.mockResolvedValue([{ ...connected, status: "authorizing" }]);
|
||||
fixture.deviceLogin.mockResolvedValue({ connection: { ...connected, status: "authorizing" }, needsApproval: true, expiresAt: new Date(Date.now() + 600_000).toISOString() });
|
||||
render();await settle();
|
||||
expect(container.textContent).toContain("Tailscale administrator");
|
||||
expect(container.querySelector('a[href="https://login.tailscale.com/admin/machines"]')).not.toBeNull();
|
||||
});
|
||||
|
||||
it("recovers a transient sign-in status failure using the shared retry policy", async () => {
|
||||
client.setDefaultOptions({ queries: { retry: shouldRetryRequest, retryDelay: 0 } });
|
||||
fixture.list.mockResolvedValue([{ ...connected, status: "authorizing" }]);
|
||||
fixture.deviceLogin.mockRejectedValueOnce(new ApiError("Unavailable", 503, {}));
|
||||
render();await settle();
|
||||
expect(fixture.deviceLogin).toHaveBeenCalledTimes(2);
|
||||
expect(container.querySelector('a[href="https://login.tailscale.com/a/fixture"]')).not.toBeNull();
|
||||
expect(container.querySelector('[role="alert"]')).toBeNull();
|
||||
});
|
||||
|
||||
it("does not automatically retry a denied sign-in status request", async () => {
|
||||
client.setDefaultOptions({ queries: { retry: shouldRetryRequest, retryDelay: 0 } });
|
||||
fixture.list.mockResolvedValue([{ ...connected, status: "authorizing" }]);
|
||||
fixture.deviceLogin.mockRejectedValue(new ApiError("Forbidden", 403, {}));
|
||||
render();await settle();
|
||||
expect(fixture.deviceLogin).toHaveBeenCalledOnce();
|
||||
expect(container.querySelector('[role="alert"]')).not.toBeNull();
|
||||
expect(button("Check again")).toBeDefined();
|
||||
});
|
||||
|
||||
it("shows the connected network when the server confirms enrollment", async () => {
|
||||
fixture.list.mockResolvedValue([{ ...connected, status: "authorizing" }]);
|
||||
fixture.deviceLogin.mockResolvedValue({ connection: connected, expiresAt: null });
|
||||
render();await settle();
|
||||
expect(container.textContent).toContain("Create SSH environment");
|
||||
expect(container.textContent).not.toContain("Cancel sign-in");
|
||||
});
|
||||
|
||||
it("does not open a late sign-in response after changing companies", async () => {
|
||||
let complete!: (value: unknown) => void;
|
||||
fixture.connect.mockImplementation(() => new Promise(resolve => { complete = resolve; }));
|
||||
const assign = vi.fn();
|
||||
vi.spyOn(window, "open").mockReturnValue({ opener: null, closed: false, location: { assign }, focus: vi.fn(), close: vi.fn() } as unknown as Window);
|
||||
fixture.list.mockImplementation(async id => id === "company-1" ? [connected] : []);
|
||||
render();await settle();
|
||||
flushSync(() => button("Connect Tailscale Network").click());await settle();
|
||||
fixture.companyId = "company-2";render();await settle();
|
||||
complete({ connection: { ...connected, status: "authorizing" }, authorizationUrl: "https://login.tailscale.com/a/fixture", expiresAt: new Date(Date.now() + 600_000).toISOString() });
|
||||
await settle();
|
||||
expect(assign).not.toHaveBeenCalled();
|
||||
expect(container.textContent).not.toContain("Home tailnet");
|
||||
});
|
||||
|
||||
it("stops polling and gives a recovery action when the sign-in deadline passes", async () => {
|
||||
fixture.list.mockResolvedValue([{ ...connected, status: "authorizing" }]);
|
||||
fixture.deviceLogin.mockResolvedValue({ connection: { ...connected, status: "authorizing" }, authorizationUrl: "https://login.tailscale.com/a/fixture", expiresAt: new Date(Date.now() - 1).toISOString() });
|
||||
render();await settle();
|
||||
expect(container.textContent).toContain("Sign-in expired");
|
||||
expect(container.querySelector('a[href="https://login.tailscale.com/a/fixture"]')).toBeNull();
|
||||
await new Promise(resolve => setTimeout(resolve, 2100));
|
||||
expect(fixture.deviceLogin).toHaveBeenCalledOnce();
|
||||
expect(button("Cancel sign-in")).toBeDefined();
|
||||
});
|
||||
|
||||
it.each(["cancelled", "failed"])("explains %s consent and retries the same saved connection", async outcome => {
|
||||
@@ -149,7 +203,7 @@ describe("Tailscale network connector", () => {
|
||||
expect(container.textContent).not.toContain("Create SSH environment");
|
||||
});
|
||||
|
||||
it("reports access failure without presenting a usable connection or starting OAuth", async () => {
|
||||
it("reports access failure without presenting a usable connection or starting sign-in", async () => {
|
||||
fixture.list.mockRejectedValue(new ApiError("Instance admin access required", 403, { error: "forbidden" }));
|
||||
render();await settle();
|
||||
expect(container.querySelector('[role="alert"]')).not.toBeNull();
|
||||
|
||||
@@ -1,15 +1,15 @@
|
||||
import { useEffect } from "react";
|
||||
import { useEffect, useRef } from "react";
|
||||
import { useMutation, useQueryClient } from "@tanstack/react-query";
|
||||
import { tailscaleApi } from "@/api/tailscale";
|
||||
import { tailscaleApi, type TailscaleConnection } 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 { useAuthorizationWindow } from "@/hooks/useAuthorizationWindow";
|
||||
import { AppLogo } from "./AppLogo";
|
||||
import { TailscaleDeviceSignIn } from "./TailscaleDeviceSignIn";
|
||||
|
||||
export const TAILSCALE_CONNECTOR_PATH = "/apps/tailscale";
|
||||
|
||||
@@ -38,14 +38,26 @@ export function TailscaleConnector() {
|
||||
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 authorization = useAuthorizationWindow();
|
||||
const company = useRef(selectedCompanyId);
|
||||
company.current = selectedCompanyId;
|
||||
const connect = useMutation({ mutationFn: async (input: { companyId: string; connectionId?: string }) => {
|
||||
const result = await tailscaleApi.connect(input.companyId, input.connectionId);
|
||||
client.setQueryData<TailscaleConnection[]>(tailscaleConnectionsKey(input.companyId), rows => [
|
||||
...(rows ?? []).filter(row => row.id !== result.connection.id), result.connection,
|
||||
]);
|
||||
if (company.current !== input.companyId) return;
|
||||
if (result.authorizationUrl) await authorization.open(result.authorizationUrl);
|
||||
else authorization.cancel();
|
||||
}, onError: () => authorization.cancel() });
|
||||
const start = (connectionId?: string) => {
|
||||
if (!selectedCompanyId) return;
|
||||
authorization.reserve();
|
||||
connect.mutate({ companyId: selectedCompanyId, connectionId });
|
||||
};
|
||||
const disconnect = useMutation({ mutationFn: (connectionId: string) => tailscaleApi.disconnect(selectedCompanyId!, connectionId),
|
||||
onSuccess: () => client.invalidateQueries({ queryKey: tailscaleConnectionsKey(selectedCompanyId) }) });
|
||||
onSuccess: () => { authorization.cancel(); return client.invalidateQueries({ queryKey: tailscaleConnectionsKey(selectedCompanyId) }); } });
|
||||
useEffect(() => authorization.cancel, [selectedCompanyId, authorization.cancel]);
|
||||
useEffect(() => {
|
||||
setBreadcrumbs([{ label: "Connectors", href: "/apps" }, { label: "Tailscale" }]);
|
||||
return () => setBreadcrumbs([]);
|
||||
@@ -63,18 +75,19 @@ export function TailscaleConnector() {
|
||||
<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>}
|
||||
{returnError && <div role="alert" className="space-y-3"><p className="text-sm text-destructive">{returnError}</p>{retryConnection && <Button variant="outline" disabled={connect.isPending} onClick={() => start(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>
|
||||
<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 === "authorizing" ? "Waiting for sign-in" : connection.status === "connecting" ? "Connecting" : connection.status === "disconnected" ? "Disconnected" : connection.status === "expired" ? "Sign-in expired" : "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>}
|
||||
</> : connection.status === "authorizing" ? <TailscaleDeviceSignIn key={`${selectedCompanyId}:${connection.id}`} connection={connection} cancel={() => disconnect.mutate(connection.id)} disabled={disconnect.isPending} />
|
||||
: <Button variant="outline" disabled={connect.isPending} onClick={() => start(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>
|
||||
<Button disabled={connect.isPending || connections.isError || connections.data?.some(connection => connection.status === "authorizing")} onClick={() => start()}>{connect.isPending ? "Connecting…" : "Connect Tailscale Network"}</Button>
|
||||
</footer>
|
||||
</div>;
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import type { TailscaleConnection } from "@paperclipai/shared";
|
||||
import { tailscaleApi } from "@/api/tailscale";
|
||||
import { describeError } from "@/api/errors";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { tailscaleConnectionsKey } from "@/hooks/useTailscaleConnections";
|
||||
|
||||
export function TailscaleDeviceSignIn({ connection, cancel, disabled }: {
|
||||
connection: TailscaleConnection; cancel: () => void; disabled: boolean;
|
||||
}) {
|
||||
const client = useQueryClient();
|
||||
const [expired, setExpired] = useState(false);
|
||||
const status = useQuery({
|
||||
queryKey: ["tailscale-device-login", connection.companyId, connection.id],
|
||||
queryFn: () => tailscaleApi.deviceLogin(connection.companyId, connection.id),
|
||||
gcTime: 0,
|
||||
refetchInterval: query => expired || query.state.error || query.state.data?.connection.status !== "authorizing" ? false : 2000,
|
||||
refetchOnWindowFocus: !expired,
|
||||
});
|
||||
useEffect(() => {
|
||||
const next = status.data?.connection;
|
||||
if (!next || next.status === "authorizing") return;
|
||||
client.setQueryData<TailscaleConnection[]>(tailscaleConnectionsKey(connection.companyId), rows => rows?.map(row => row.id === next.id ? next : row));
|
||||
}, [status.data, client, connection.companyId]);
|
||||
useEffect(() => {
|
||||
const deadline = status.data?.expiresAt ? Date.parse(status.data.expiresAt) : Date.now() + 10 * 60_000;
|
||||
const timer = window.setTimeout(() => setExpired(true), Math.max(0, deadline - Date.now()));
|
||||
return () => window.clearTimeout(timer);
|
||||
}, [status.data?.expiresAt]);
|
||||
return <div className="space-y-3">
|
||||
<p className="text-sm text-muted-foreground" role="status">{expired ? "Sign-in expired. Cancel and connect again."
|
||||
: status.data?.needsApproval ? "Waiting for a Tailscale administrator to approve this device."
|
||||
: "Approve the connection in Tailscale. This page will update when you finish."}</p>
|
||||
{status.error && <p role="alert" className="text-sm text-destructive">{describeError(status.error, { action: "check Tailscale sign-in" }).body}</p>}
|
||||
<div className="flex flex-wrap items-center gap-3">
|
||||
{!expired && status.data?.authorizationUrl && <Button variant="outline" asChild><a href={status.data.authorizationUrl} target="_blank" rel="noopener noreferrer">Continue to Tailscale</a></Button>}
|
||||
{status.data?.needsApproval && !expired && <Button variant="outline" asChild><a href="https://login.tailscale.com/admin/machines" target="_blank" rel="noopener noreferrer">Open Tailscale devices</a></Button>}
|
||||
{status.error && !expired && <Button variant="outline" onClick={() => void status.refetch()}>Check again</Button>}
|
||||
<Button variant="ghost" disabled={disabled} onClick={cancel}>Cancel sign-in</Button>
|
||||
</div>
|
||||
</div>;
|
||||
}
|
||||
Reference in new issue
Block a user