mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-29 23:56:43 +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
@@ -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;
|
||||
|
||||
Reference in new issue
Block a user