Files
PaperClipAI/server/src/services/paperclip-cloud-connector.ts
T
Devin FoleyandPaperclip 21bf7ebcee feat(connectors): connect Tailscale networks to SSH environments (#20617)
## Thinking Path

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

## Linked Issues or Issue Description

**Subsystem affected**

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

**Problem or motivation**

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

**Proposed solution**

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

**Alternatives considered**

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

**Roadmap alignment**

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

## What Changed

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

## Verification

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

## Risks

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

## Model Used

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

## Checklist

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

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-11-13 15:15:43 -08:00

1002 lines
50 KiB
TypeScript

import { assertMcpClientMirrorEnvelope } from "./public-mcp/client-mirror-wire.js";
import { providerRetryAt } from "./provider-retry-after.js";
import { SLACK_MANAGER_SCOPES, ASANA_CONNECTOR_SCOPES, isAsanaConnectorProfileId, type AsanaConnectorProfileId } from "@paperclipai/shared";
import {
createDecipheriv,
createHash,
createPrivateKey,
createPublicKey,
diffieHellman,
hkdfSync,
randomUUID,
sign,
type KeyObject,
} from "node:crypto";
import {
DEFAULT_OWNERSHIP_AVAILABILITY,
type AppDefinition,
GITHUB_CONNECTOR_PROFILES,
GOOGLE_WORKSPACE_CONNECTOR_PROFILES,
isGitHubConnectorProfileId,
isGoogleWorkspaceConnectorProfileId,
isGoogleWorkspaceScopeGrant,
type GitHubConnectorProfileId,
type GoogleWorkspaceConnectorProfileId,
} from "@paperclipai/shared";
import {
loadPaperclipCloudConnectorIdentity,
paperclipCloudConnectorEnrollmentStatus,
} from "./paperclip-cloud-connector-enrollment.js";
export const GMAIL_MCP_URL = "https://gmailmcp.googleapis.com/mcp/v1";
export const GMAIL_CONNECTOR_SCOPES = [
"https://www.googleapis.com/auth/gmail.readonly",
"https://www.googleapis.com/auth/gmail.compose",
] as const;
export { GOOGLE_WORKSPACE_CONNECTOR_PROFILES };
export type PaperclipCloudConnectorEnvironment = "development" | "test" | "staging" | "production";
export type PaperclipCloudConnectorOperation = "status" | "session" | "claim" | "refresh" | "revoke" | "webhook-bind" | "event-lease" | "event-ack" | "github-app" | "slack-events" | "slack-forms" | "mcp-client-mirror" | "mcp-revocation-index";
export type PaperclipCloudConnectorProfileId = GoogleWorkspaceConnectorProfileId | GitHubConnectorProfileId | AsanaConnectorProfileId | "slack.manager" | "github.bot" | "tailscale.tailnet";
export type PaperclipCloudConnectorProvider = "google" | "github" | "asana" | "slack" | "tailscale";
export type PaperclipCloudConnectorConfig = {
baseUrl: string;
instanceId: string;
environment: PaperclipCloudConnectorEnvironment;
signPrivateKey: string;
sealPrivateKey: string;
};
export type SealedConnectorCredentials = {
v: 1;
accessToken: string;
refreshToken: string | null;
tokenType: string;
accessTokenExpiresAt: string | null;
refreshTokenExpiresAt: string | null;
scopes: string[];
subject: string;
companyId: string;
instanceId: string;
environment: PaperclipCloudConnectorEnvironment;
provider: PaperclipCloudConnectorProvider;
profile: string;
appSlug?: string;
slackManager?: { appId: string; workspaceId: string; workspaceName: string; userId: string };
};
export type SealedGmailCredentials = SealedConnectorCredentials & { provider: "google" };
export type SealedGoogleWorkspaceCredentials = SealedGmailCredentials;
export type SealedConnectorEvents = {
v: 1;
instanceId: string;
environment: PaperclipCloudConnectorEnvironment;
leaseId: string;
events: Array<{
id: string;
provider: "github" | "slack";
event: string;
action: string | null;
installationId: string | null;
repositoryId: string | null;
payload: Record<string, unknown>;
createdAt: string;
bindingIds: string[];
}>;
};
type SealedEnvelopeProfileId = PaperclipCloudConnectorProfileId | "slack.events.v1" | "slack.form-open.v1" | "slack.callbacks.v1";
type SealedEnvelope = {
v: 1;
alg: "X25519-HKDF-SHA256-A256GCM";
purpose: "initial" | "access" | "events";
provider: PaperclipCloudConnectorProvider;
profile: SealedEnvelopeProfileId;
epk: string;
iv: string;
ct: string;
};
type ConnectorResponse = {
slackManager?: unknown;
confirmationUrl?: unknown;
authorizationUrl?: unknown;
handoff?: unknown;
expiresAt?: unknown;
scopes?: unknown;
claimId?: unknown;
sealed?: unknown;
profiles?: unknown;
protocolVersion?: unknown;
providers?: unknown;
active?: unknown;
status?: unknown;
leaseId?: unknown;
events?: unknown;
acknowledged?: unknown;
formReceipts?: unknown;
githubApps?: { version: number };
slackEvents?: { version: number };
slackForm?: unknown;
enrollment?: unknown;
retirement?: unknown;
eventWakeVersion?: unknown;
};
const ENDPOINTS: Record<PaperclipCloudConnectorOperation, string> = {
"mcp-client-mirror": "/v1/connector/mcp-client-mirror",
"mcp-revocation-index": "/v1/connector/mcp-revocation-index",
"slack-events": "/v1/connector/slack-events",
"slack-forms": "/v1/connector/slack-forms",
"github-app": "/v1/connector/github-apps",
status: "/v1/connector/instance-status",
session: "/v1/connector/sessions",
claim: "/v1/connector/claims",
refresh: "/v1/connector/refresh",
revoke: "/v1/connector/revoke",
"webhook-bind": "/v1/connector/webhook-bindings",
"event-lease": "/v1/connector/events/lease",
"event-ack": "/v1/connector/events/ack",
};
const JWS_TYP = "paperclip-cloud-connector-request+jwt";
const SEAL_ALGORITHM = "X25519-HKDF-SHA256-A256GCM";
const AES_TAG_BYTES = 16;
const RAW_PRIVATE_KEY_BYTES = 32;
const ED25519_PKCS8_PREFIX = Buffer.from("302e020100300506032b657004220420", "hex");
const X25519_PKCS8_PREFIX = Buffer.from("302e020100300506032b656e04220420", "hex");
const X25519_SPKI_PREFIX = Buffer.from("302a300506032b656e032100", "hex");
// Only fixed protocol codes may enter errors/logs. Never retain the broker's
// message, request data, return URI, or an arbitrary error/code string.
const BROKER_REJECTION_REASONS = new Set([
"RETURN_ORIGIN_NOT_ENROLLED", "INVALID_RETURN_URI", "INVALID_REQUEST",
"UNKNOWN_INSTANCE", "INSTANCE_APPROVAL_REQUIRED", "INSTANCE_SUSPENDED",
"ENVIRONMENT_MISMATCH", "PROFILE_NOT_AVAILABLE", "PROFILE_NOT_ELIGIBLE",
"REQUEST_EXPIRED", "REQUEST_REPLAYED", "SIGNATURE_REJECTED",
"AUDIENCE_MISMATCH", "OPERATION_MISMATCH", "PAYLOAD_MISMATCH",
"MALFORMED_REQUEST", "UNSUPPORTED_ALGORITHM", "RATE_LIMITED",
"PROVIDER_OPERATION_FAILED", "PROVIDER_REAUTHORIZATION_REQUIRED",
"SLACK_ENROLLMENT_GENERATION_CHANGED", "SLACK_ENROLLMENT_IDENTITY_CHANGED",
"SLACK_ENROLLMENT_CHANGED", "SLACK_ENROLLMENT_UNSETTLED", "SLACK_ENROLLMENT_DISABLED",
"SLACK_COMPANY_MISMATCH", "SLACK_EVENTS_UNAVAILABLE",
"SLACK_FORM_SUBJECT_CHANGED", "SLACK_FORM_INSTANCE_CHANGED", "SLACK_FORM_ENROLLMENT_CHANGED", "SLACK_FORM_CREDENTIAL_CHANGED",
"SLACK_FORM_RETIREMENT_CHANGED", "SLACK_FORM_RETIREMENT_PROOF_MISSING", "SLACK_FORM_CUSTODY_CHANGED", "SLACK_FORM_RETIREMENT_SIGNER_UNAVAILABLE", "SLACK_FORM_CANONICAL_FACT_CHANGED", "SLACK_FORM_CANONICAL_FACT_BUDGET_CHANGED", "SLACK_FORM_CANONICAL_FACT_PENDING",
]);
const UNKNOWN_BROKER_REASON = "UNKNOWN_BROKER_ERROR";
async function readBrokerRejectionReason(response: Response): Promise<string> {
if (response.bodyUsed || response.body?.locked) return UNKNOWN_BROKER_REASON;
const reader = response.body?.getReader();
if (!reader) return UNKNOWN_BROKER_REASON;
let timer: ReturnType<typeof setTimeout> | undefined;
try {
return await Promise.race([
(async () => {
const chunks: Uint8Array[] = [];
let size = 0;
while (true) {
const { done, value } = await reader.read();
if (done) break;
size += value.byteLength;
if (size > 4_096) return UNKNOWN_BROKER_REASON;
chunks.push(value);
}
const body: unknown = JSON.parse(Buffer.concat(chunks).toString("utf8"));
const reason = body && typeof body === "object" && "error" in body ? body.error : null;
return typeof reason === "string" && BROKER_REJECTION_REASONS.has(reason)
? reason : UNKNOWN_BROKER_REASON;
})(),
new Promise<string>((resolve) => {
timer = setTimeout(() => resolve(UNKNOWN_BROKER_REASON), 500);
}),
]);
} catch {
return UNKNOWN_BROKER_REASON;
} finally {
clearTimeout(timer);
// Diagnostic reads and cancellation must never delay the original failure.
void reader.cancel().catch(() => {});
}
}
/** Stable public code/status with only allowlisted broker diagnostics. */
export class PaperclipCloudConnectorError extends Error {
constructor(
message: string,
readonly code: string,
readonly status?: number,
readonly retryAt?: number,
readonly brokerReason?: string,
) {
super(message);
this.name = "PaperclipCloudConnectorError";
}
}
export function paperclipCloudConnectorConfigFromEnv(
env: NodeJS.ProcessEnv = process.env,
): PaperclipCloudConnectorConfig | null {
const localIdentity = loadPaperclipCloudConnectorIdentity();
const legacyConfigured = [
env.PAPERCLIP_ID_CONNECTOR_INSTANCE_ID,
env.PAPERCLIP_ID_CONNECTOR_SIGN_PRIVATE_KEY,
env.PAPERCLIP_ID_CONNECTOR_SEAL_PRIVATE_KEY,
env.PAPERCLIP_ID_CONNECTOR_ENVIRONMENT,
env.PAPERCLIP_ID_CONNECTOR_BASE_URL,
].some((value) => Boolean(value?.trim()));
const managedInstanceId = env.PAPERCLIP_CLOUD_CONNECTOR_INSTANCE_ID?.trim();
const managedSignPrivateKey = env.PAPERCLIP_CLOUD_CONNECTOR_SIGN_PRIVATE_KEY?.trim();
const managedSealPrivateKey = env.PAPERCLIP_CLOUD_CONNECTOR_SEAL_PRIVATE_KEY?.trim();
const managedEnvironment = env.PAPERCLIP_CLOUD_CONNECTOR_ENVIRONMENT?.trim();
const hasManagedIdentityOverride = [managedInstanceId, managedSignPrivateKey, managedSealPrivateKey]
.some(Boolean);
const localStatus = hasManagedIdentityOverride ? null : paperclipCloudConnectorEnrollmentStatus(env);
const hasActiveLocalIdentity = localIdentity?.status === "active" && localStatus?.configured === true;
if (!hasManagedIdentityOverride && !hasActiveLocalIdentity && legacyConfigured) {
throw new PaperclipCloudConnectorError(
"Paperclip ID connector settings use an incompatible legacy protocol; enroll this instance with Paperclip Cloud",
"CONNECTOR_MIGRATION_REQUIRED",
);
}
if (!hasManagedIdentityOverride && !hasActiveLocalIdentity) return null;
const instanceId = hasManagedIdentityOverride ? managedInstanceId : localIdentity!.instanceId;
const signPrivateKey = hasManagedIdentityOverride ? managedSignPrivateKey : localIdentity!.signPrivateKey;
const sealPrivateKey = hasManagedIdentityOverride ? managedSealPrivateKey : localIdentity!.sealPrivateKey;
const environment = hasManagedIdentityOverride ? managedEnvironment : localIdentity!.environment;
const baseUrl = env.PAPERCLIP_CLOUD_CONNECTOR_BASE_URL?.trim()
|| (hasActiveLocalIdentity ? localIdentity!.brokerBaseUrl : undefined)
|| "https://my.paperclip.app";
const values = [instanceId, signPrivateKey, sealPrivateKey, environment];
if (values.some((value) => !value)) {
throw new PaperclipCloudConnectorError("Paperclip Cloud connector configuration is incomplete", "CONNECTOR_CONFIG_INCOMPLETE");
}
if (environment !== "development" && environment !== "test" && environment !== "staging" && environment !== "production") {
throw new PaperclipCloudConnectorError("Paperclip Cloud connector environment is invalid", "CONNECTOR_CONFIG_INVALID");
}
const parsedBaseUrl = new URL(baseUrl);
if (parsedBaseUrl.protocol !== "https:" && !(parsedBaseUrl.protocol === "http:" && isLoopback(parsedBaseUrl.hostname))) {
throw new PaperclipCloudConnectorError("Paperclip Cloud connector URL must use HTTPS", "CONNECTOR_CONFIG_INVALID");
}
if (parsedBaseUrl.username || parsedBaseUrl.password || parsedBaseUrl.search || parsedBaseUrl.hash) {
throw new PaperclipCloudConnectorError("Paperclip Cloud connector URL is invalid", "CONNECTOR_CONFIG_INVALID");
}
const brokerHost = parsedBaseUrl.hostname.toLowerCase();
if ((brokerHost === "my.paperclip.app" && environment !== "production")
|| (brokerHost === "test.paperclip.app" && environment !== "test")
|| (brokerHost === "my-staging.paperclip.app" && environment !== "staging")) {
throw new PaperclipCloudConnectorError(
"Paperclip Cloud connector broker and environment do not match",
"CONNECTOR_CONFIG_INVALID",
);
}
parsedBaseUrl.pathname = parsedBaseUrl.pathname.replace(/\/$/, "");
return {
baseUrl: parsedBaseUrl.toString().replace(/\/$/, ""),
instanceId: instanceId!,
environment,
signPrivateKey: signPrivateKey!,
sealPrivateKey: sealPrivateKey!,
};
}
export function createPaperclipCloudConnector(input: {
config: PaperclipCloudConnectorConfig;
request?: typeof fetch;
now?: () => number;
}) {
const config = input.config;
const request = input.request ?? fetch;
const now = input.now ?? Date.now;
const signingKey = privateKey(config.signPrivateKey, "ed25519");
const sealKey = privateKey(config.sealPrivateKey, "x25519");
let eventWakeVersion: 1 | null = null;
async function call(
operation: PaperclipCloudConnectorOperation,
claims: { subject: string; companyId: string; profile?: PaperclipCloudConnectorProfileId; scopes?: string[]; returnUri?: string; returnState?: string; claimId?: string; redemptionId?: string; eventWakeVersion?: 0 | 1 },
secret?: { field: "refreshToken" | "token" | "binding" | "acknowledgement" | "enrollment" | "operation"; value: string },
): Promise<ConnectorResponse> {
const endpoint = new URL(ENDPOINTS[operation], `${config.baseUrl}/`).toString();
const issuedAt = Math.floor(now() / 1000);
const payload: Record<string, unknown> = {
iss: config.instanceId,
aud: endpoint,
sub: claims.subject,
cid: claims.companyId,
env: config.environment,
op: operation,
iat: issuedAt,
exp: issuedAt + 60,
jti: randomUUID(),
};
if (claims.eventWakeVersion !== undefined) payload.ewv = claims.eventWakeVersion;
if (claims.returnUri !== undefined) payload.ruri = claims.returnUri;
if (claims.returnState !== undefined) payload.rst = claims.returnState;
if (claims.claimId !== undefined) payload.cl = claims.claimId;
if (claims.redemptionId !== undefined) payload.rid = claims.redemptionId;
if (claims.profile !== undefined) {
const definition = connectorProfileDefinition(claims.profile);
payload.prv = definition.provider;
payload.prf = claims.profile;
if (claims.scopes && (claims.profile !== "workspace.all" || !isGoogleWorkspaceScopeGrant(claims.scopes))) {
throw new PaperclipCloudConnectorError("Invalid requested service permissions", "CONNECTOR_CONFIG_INVALID");
}
payload.scp = [...(claims.scopes ?? definition.scopes)];
}
if (secret) payload.sh = await sha256Base64Url(secret.value);
const body = {
request: signRequest(payload, signingKey),
...(secret ? { [secret.field]: secret.value } : {}),
};
const encodedBody = JSON.stringify(body);
if (operation === "mcp-client-mirror" && secret?.field === "binding") {
assertMcpClientMirrorEnvelope(body.request, secret.value, encodedBody);
}
let response: Response;
try {
response = await request(endpoint, {
method: "POST",
headers: { "content-type": "application/json", accept: "application/json" },
body: encodedBody,
signal: AbortSignal.timeout(15_000),
});
} catch {
throw new PaperclipCloudConnectorError("Paperclip Cloud connector is unavailable", "CONNECTOR_UNAVAILABLE");
}
if (operation === "revoke" && response.status === 204) return {};
if (!response.ok) {
const reason = await readBrokerRejectionReason(response);
throw new PaperclipCloudConnectorError(
`Paperclip Cloud connector rejected the request (operation=${operation}, status=${response.status}, reason=${reason})`,
response.status === 409 ? "REAUTHORIZATION_REQUIRED" : "CONNECTOR_REQUEST_FAILED",
response.status,
providerRetryAt(response.headers.get("retry-after"), now()),
reason,
);
}
try {
return await response.json() as ConnectorResponse;
} catch {
throw new PaperclipCloudConnectorError("Paperclip Cloud connector returned an invalid response", "CONNECTOR_BAD_RESPONSE");
}
}
function openCredentials(
response: ConnectorResponse,
purpose: SealedEnvelope["purpose"],
subject: string,
companyId: string,
profile: PaperclipCloudConnectorProfileId,
requestedScopes?: string[],
): SealedConnectorCredentials {
const definition = connectorProfileDefinition(profile);
const envelope = parseEnvelope(response.sealed, purpose, definition.provider, profile);
const credentials = unseal(
envelope,
sealKey,
config.instanceId,
config.environment,
definition.provider,
profile,
requestedScopes ?? definition.scopes,
);
if (
credentials.instanceId !== config.instanceId
|| credentials.environment !== config.environment
|| credentials.subject !== subject
|| credentials.companyId !== companyId
|| credentials.provider !== definition.provider
) {
throw new PaperclipCloudConnectorError("Paperclip Cloud credential binding did not match", "CONNECTOR_BINDING_MISMATCH");
}
if (credentials.profile !== profile) {
throw new PaperclipCloudConnectorError("Paperclip Cloud connector profile binding did not match", "CONNECTOR_BINDING_MISMATCH");
}
if (!(profile === "workspace.all" ? isGoogleWorkspaceScopeGrant(credentials.scopes) : sameStringSet(credentials.scopes, definition.scopes))) {
throw new PaperclipCloudConnectorError("Paperclip Cloud scope grant did not match", "REAUTHORIZATION_REQUIRED");
}
return credentials;
}
return {
instanceIdentity: () => Object.freeze({ instanceId: config.instanceId, environment: config.environment }),
async syncMcpClientMirror(serialized: string): Promise<unknown> {
const response = await call("mcp-client-mirror", {subject:"instance-client-metadata",companyId:"instance-client-metadata"}, {field:"binding",value:serialized});
return (response as ConnectorResponse & {mcpClientMirror?:unknown}).mcpClientMirror;
},
async syncMcpRevocationIndex(values: { subject: string; companyId: string; serialized: string }): Promise<unknown> {
const response = await call("mcp-revocation-index", values, { field: "binding", value: values.serialized });
return (response as ConnectorResponse & { mcpRevocationIndex?: unknown }).mcpRevocationIndex;
},
eventWakeVersion: () => eventWakeVersion,
async slackEventsAvailable() {
const response = await call("status", { subject: "instance-capabilities", companyId: "instance-capabilities" });
return response.active === true && response.slackEvents?.version === 1;
},
async slackFormOperation(values: { subject: string; companyId: string; operation: Record<string, unknown> }) {
const response = await call("slack-forms", values, { field: "operation", value: JSON.stringify(values.operation) });
if (!isRecord(response.slackForm)) throw badEnvelope();
if (values.operation.kind === "receipt" && values.operation.refreshAckReceipt !== undefined) {
if (values.operation.acceptedAckReceipt !== undefined || values.operation.releaseAckFact !== undefined
|| Object.keys(response.slackForm).join() !== "ackReceiptJws" || typeof response.slackForm.ackReceiptJws !== "string"
|| Buffer.byteLength(response.slackForm.ackReceiptJws, "ascii") > 12000
|| !/^[A-Za-z0-9_-]+[.][A-Za-z0-9_-]+[.][A-Za-z0-9_-]+$/.test(response.slackForm.ackReceiptJws)) throw badEnvelope();
return response.slackForm;
}
if (values.operation.kind === "receipt" && values.operation.releaseAckFact !== undefined) {
if (values.operation.acceptedAckReceipt !== undefined || Object.keys(response.slackForm).join() !== "releasedAckDigest"
|| typeof response.slackForm.releasedAckDigest !== "string" || !/^[a-f0-9]{64}$/.test(response.slackForm.releasedAckDigest)) throw badEnvelope();
return response.slackForm;
}
if (values.operation.kind === "receipt" && values.operation.acceptedAckReceipt !== undefined) {
if (Object.keys(response.slackForm).sort().join() !== "acceptedReceiptDigest,needsTerminalOriginal" || typeof response.slackForm.acceptedReceiptDigest !== "string"
|| !/^[a-f0-9]{64}$/.test(response.slackForm.acceptedReceiptDigest) || typeof response.slackForm.needsTerminalOriginal !== "boolean") throw badEnvelope();
return response.slackForm;
}
if (!["receipt", "terminal-ack"].includes(String(values.operation.kind))) return response.slackForm;
const envelope = parseEnvelope(response.slackForm.sealed, "events", "slack", "slack.form-open.v1");
const receipt = decryptEnvelope(envelope, sealKey, config.instanceId, config.environment, "slack", "slack.form-open.v1", []);
if (!isRecord(receipt) || receipt.version !== 1 || receipt.instanceId !== config.instanceId || receipt.environment !== config.environment) throw badEnvelope();
if (!isRecord(receipt.operation)) throw badEnvelope();
if (receipt.operation.closed !== null) {
if (!isRecord(receipt.operation.closed)) throw badEnvelope();
const closeEnvelope = parseEnvelope(receipt.operation.closed.evidence, "events", "slack", "slack.form-open.v1");
const evidence = decryptEnvelope(closeEnvelope, sealKey, config.instanceId, config.environment, "slack", "slack.form-open.v1", []);
if (!isRecord(evidence) || evidence.version !== 1 || !["close", "submission"].includes(String(evidence.kind)) || evidence.instanceId !== config.instanceId
|| evidence.environment !== config.environment || evidence.operationId !== receipt.operation.id) throw badEnvelope();
receipt.operation.closed = { ...receipt.operation.closed, evidence };
}
if (receipt.operation.rejection !== null) {
if (!isRecord(receipt.operation.rejection)) throw badEnvelope();
const rejectionEnvelope = parseEnvelope(receipt.operation.rejection.evidence, "events", "slack", "slack.form-open.v1");
const evidence = decryptEnvelope(rejectionEnvelope, sealKey, config.instanceId, config.environment, "slack", "slack.form-open.v1", []);
if (!isRecord(evidence) || evidence.version !== 1 || evidence.kind !== "rejection" || evidence.instanceId !== config.instanceId
|| evidence.environment !== config.environment || evidence.operationId !== receipt.operation.id
|| evidence.responseDigest !== receipt.operation.rejection.responseDigest) throw badEnvelope();
receipt.operation.rejection = { ...receipt.operation.rejection, evidence };
}
return receipt;
},
async slackEventEnrollment(values: { subject: string; companyId: string; enrollment: Record<string, unknown> }) {
const response = await call("slack-events", values, { field: "enrollment", value: JSON.stringify(values.enrollment) });
return values.enrollment.active === false ? response.retirement : response.enrollment;
},
async githubAppsAvailable() {
const response = await call("status", { subject: "instance-capabilities", companyId: "instance-capabilities" });
return response.active === true && response.githubApps?.version === 2;
},
async githubApp(values: { subject: string; companyId: string; binding: Record<string, unknown> }) {
return await call("github-app", values, { field: "binding", value: JSON.stringify(values.binding) }) as unknown as import("@paperclipai/shared").GitHubAppCloudState;
},
async claimGitHubApp(values: { subject: string; companyId: string; claimId: string; redemptionId: string }) {
const response = await call("claim", { ...values, profile: "github.bot" });
const envelope = parseEnvelope(response.sealed, "initial", "github", "github.bot");
const opened = decryptEnvelope(envelope, sealKey, config.instanceId, config.environment, "github", "github.bot", []) as Record<string, unknown>;
if (opened.v !== 1 || opened.instanceId !== config.instanceId || opened.environment !== config.environment
|| opened.subject !== values.subject || opened.companyId !== values.companyId || opened.provider !== "github"
|| opened.profile !== "github.bot" || !sameStringSet(opened.scopes, [])) throw badEnvelope();
return opened;
},
async getInstanceStatus(): Promise<"active" | "suspended" | "removed"> {
let response: ConnectorResponse;
try {
response = await call("status", {
subject: "instance-status",
companyId: "instance-status",
});
} catch (error) {
if (error instanceof PaperclipCloudConnectorError && error.status === 401) return "removed";
throw error;
}
if (response.status === "active" && response.active === true) return "active";
if (response.status === "suspended" && response.active === false) return "suspended";
if (response.status === "removed" && response.active === false) return "removed";
throw new PaperclipCloudConnectorError("Paperclip Cloud connector returned an invalid instance status", "CONNECTOR_BAD_RESPONSE");
},
async getCapabilities(): Promise<PaperclipCloudConnectorProfileId[]> {
let response: ConnectorResponse;
try {
response = await call("status", {
subject: "instance-capabilities",
companyId: "instance-capabilities",
});
} catch {
return [];
}
if (response.active !== true || response.status !== "active" || !Array.isArray(response.profiles)) return [];
return [...new Set(response.profiles.flatMap((value) =>
typeof value === "string" && isPaperclipCloudConnectorProfileId(value) ? [value] : []
))];
},
async getSlackManagerAppId(): Promise<string | null> {
const response = await call("status", { subject: "instance-capabilities", companyId: "instance-capabilities" });
const manager = response.slackManager;
if (response.active !== true || response.status !== "active" || !Array.isArray(response.profiles) || !response.profiles.includes("slack.manager")
|| !manager || typeof manager !== "object" || !("appId" in manager) || typeof manager.appId !== "string" || !/^A[A-Z0-9]+$/.test(manager.appId)) return null;
return manager.appId;
},
async startAuthorization(values: { subject: string; companyId: string; profile?: PaperclipCloudConnectorProfileId; scopes?: string[]; returnUri: string; returnState: string }) {
const profile = values.profile ?? "gmail.draft";
const response = await call("session", { ...values, profile });
if (typeof response.confirmationUrl !== "string" || typeof response.expiresAt !== "string") {
throw new PaperclipCloudConnectorError("Paperclip Cloud connector returned an invalid session", "CONNECTOR_BAD_RESPONSE");
}
let confirmationUrl: URL;
try {
confirmationUrl = new URL(response.confirmationUrl);
} catch {
throw new PaperclipCloudConnectorError("Paperclip Cloud connector returned an invalid confirmation URL", "CONNECTOR_BAD_RESPONSE");
}
const expectedBroker = new URL(config.baseUrl);
if (
confirmationUrl.origin !== expectedBroker.origin
|| confirmationUrl.pathname !== "/connections/confirm"
|| confirmationUrl.username
|| confirmationUrl.password
|| confirmationUrl.hash
) {
throw new PaperclipCloudConnectorError("Paperclip Cloud connector returned an invalid confirmation URL", "CONNECTOR_BAD_RESPONSE");
}
let authorizationUrl: URL | undefined;
if (response.authorizationUrl !== undefined) {
if (typeof response.authorizationUrl !== "string") {
throw new PaperclipCloudConnectorError("Paperclip Cloud connector returned an invalid provider URL", "CONNECTOR_BAD_RESPONSE");
}
try {
authorizationUrl = new URL(response.authorizationUrl);
} catch {
throw new PaperclipCloudConnectorError("Paperclip Cloud connector returned an invalid provider URL", "CONNECTOR_BAD_RESPONSE");
}
if (
authorizationUrl.protocol !== "https:"
|| authorizationUrl.username
|| authorizationUrl.password
|| authorizationUrl.hash
|| !isExpectedProviderAuthorizationUrl(profile, authorizationUrl)
) {
throw new PaperclipCloudConnectorError("Paperclip Cloud connector returned an invalid provider URL", "CONNECTOR_BAD_RESPONSE");
}
}
const handoff = parseCloudHandoff(response.handoff);
return {
authorizationUrl: authorizationUrl?.toString() ?? confirmationUrl.toString(),
expiresAt: response.expiresAt,
...(handoff ? { handoff } : {}),
};
},
async claim(values: { subject: string; companyId: string; profile?: PaperclipCloudConnectorProfileId; scopes?: string[]; claimId: string; redemptionId: string }) {
const profile = values.profile ?? "gmail.draft";
return openCredentials(await call("claim", { ...values, profile }), sealPurpose("initial", profile), values.subject, values.companyId, profile, values.scopes);
},
async refresh(values: { subject: string; companyId: string; profile?: PaperclipCloudConnectorProfileId; refreshToken: string }) {
const profile = values.profile ?? "gmail.draft";
return openCredentials(
await call("refresh", { ...values, profile }, { field: "refreshToken", value: values.refreshToken }),
sealPurpose("access", profile),
values.subject,
values.companyId,
profile,
);
},
async revoke(values: { subject: string; companyId: string; profile?: PaperclipCloudConnectorProfileId; token: string }) {
await call("revoke", { ...values, profile: values.profile ?? "gmail.draft" }, { field: "token", value: values.token });
},
async setWebhookBinding(values: {
subject: string;
companyId: string;
id: string;
installationId: string;
connectionId: string;
grantId: string;
active: boolean;
accessToken?: string;
}) {
if (values.active && !values.accessToken) {
throw new PaperclipCloudConnectorError(
"GitHub access token is required to authorize a webhook binding",
"CONNECTOR_CONFIG_INVALID",
);
}
const binding = JSON.stringify({
id: values.id,
installationId: values.installationId,
connectionId: values.connectionId,
grantId: values.grantId,
active: values.active,
...(values.active ? { accessToken: values.accessToken } : {}),
});
await call("webhook-bind", { ...values, profile: "github.code" }, { field: "binding", value: binding });
},
async leaseEvents(values: { subject: string; companyId: string; eventWakeVersion?: 0 | 1 }): Promise<{ leaseId: string; events: SealedConnectorEvents["events"]; failedEventIds?: string[] } | null> {
const response = await call("event-lease", values);
eventWakeVersion = response.eventWakeVersion === 1 && values.eventWakeVersion !== 0 ? 1 : null;
if (Array.isArray(response.events) && response.events.length === 0) return null;
if (typeof response.leaseId !== "string") {
throw new PaperclipCloudConnectorError("Paperclip Cloud connector returned an invalid event lease", "CONNECTOR_BAD_RESPONSE");
}
const envelope = parseEnvelope(response.sealed, "events", "github", "github.code");
const opened = unsealEvents(envelope, sealKey, config.instanceId, config.environment);
if (opened.leaseId !== response.leaseId) {
throw new PaperclipCloudConnectorError("Paperclip Cloud connector event lease did not match", "CONNECTOR_BINDING_MISMATCH");
}
const events: SealedConnectorEvents["events"] = [];
const failedEventIds: string[] = [];
for (const event of opened.events) {
const packet = event.payload.githubApp;
try {
if (isRecord(packet) && packet.sealed !== undefined) {
const sealed = parseEnvelope(packet.sealed, "events", "github", "github.bot");
const delivery = decryptEnvelope(sealed, sealKey, config.instanceId, config.environment, "github", "github.bot", []) as Record<string, unknown>;
if (!isRecord(delivery) || delivery.v !== 1 || delivery.instanceId !== config.instanceId || delivery.environment !== config.environment
|| delivery.registrationId !== packet.registrationId) throw badEnvelope();
event.payload = { githubApp: delivery };
}
if (event.provider === "slack") {
if (event.payload.slackCallback !== undefined) {
const packet = event.payload.slackCallback;
if (!isRecord(packet) || typeof packet.bindingId !== "string" || packet.sealed === undefined) throw badEnvelope();
const sealed = parseEnvelope(packet.sealed, "events", "slack", "slack.callbacks.v1");
const delivery = decryptEnvelope(sealed, sealKey, config.instanceId, config.environment, "slack", "slack.callbacks.v1", []);
if (!isRecord(delivery) || delivery.version !== 1 || delivery.instanceId !== config.instanceId || delivery.environment !== config.environment
|| delivery.bindingId !== packet.bindingId || delivery.acceptedAt !== event.createdAt || delivery.lane !== event.event
|| !["command", "action"].includes(String(delivery.lane))) throw badEnvelope();
event.payload = { slackCallback: delivery };
} else if (event.payload.slackFormOpen !== undefined) {
const packet = event.payload.slackFormOpen;
if (!isRecord(packet) || typeof packet.operationId !== "string" || packet.bindingId !== `slack-form-open:${packet.operationId}`) throw badEnvelope();
const sealed = parseEnvelope(packet.sealed, "events", "slack", "slack.form-open.v1");
const delivery = decryptEnvelope(sealed, sealKey, config.instanceId, config.environment, "slack", "slack.form-open.v1", []);
if (!isRecord(delivery) || delivery.version !== 1 || delivery.instanceId !== config.instanceId || delivery.environment !== config.environment
|| !isRecord(delivery.operation) || delivery.operation.id !== packet.operationId || delivery.acceptedAt !== event.createdAt) throw badEnvelope();
event.payload = { slackFormOpen: delivery };
} else {
const packet = event.payload.slackEvent;
if (!isRecord(packet) || typeof packet.bindingId !== "string" || packet.sealed === undefined) throw badEnvelope();
const sealed = parseEnvelope(packet.sealed, "events", "slack", "slack.events.v1");
const delivery = decryptEnvelope(sealed, sealKey, config.instanceId, config.environment, "slack", "slack.events.v1", []);
if (!isRecord(delivery) || delivery.version !== 1 || delivery.instanceId !== config.instanceId
|| delivery.environment !== config.environment || delivery.bindingId !== packet.bindingId
|| delivery.acceptedAt !== event.createdAt) throw badEnvelope();
event.payload = { slackEvent: delivery };
}
}
events.push(event);
} catch {
failedEventIds.push(event.id);
}
}
return { leaseId: opened.leaseId, events, ...(failedEventIds.length ? { failedEventIds } : {}) };
},
async acknowledgeEventsWithReceipts(values: { subject: string; companyId: string; leaseId: string; deliveryIds: string[] }): Promise<{ acknowledged: number; formReceipts: { deliveryId: string; receiptJws: string }[] }> {
const response = await call("event-ack", values, { field: "acknowledgement", value: JSON.stringify({ leaseId: values.leaseId, deliveryIds: values.deliveryIds }) });
if (typeof response.acknowledged !== "number" || !Number.isSafeInteger(response.acknowledged) || response.acknowledged < 0
|| !Array.isArray(response.formReceipts) || response.formReceipts.length > 50) throw badEnvelope();
const seen = new Set<string>();
const formReceipts = response.formReceipts.map((value: unknown) => {
if (!isRecord(value) || Object.keys(value).sort().join() !== "deliveryId,receiptJws" || typeof value.deliveryId !== "string"
|| !/^slack_form_[a-f0-9]{64}$/.test(value.deliveryId) || !values.deliveryIds.includes(value.deliveryId) || seen.has(value.deliveryId)
|| typeof value.receiptJws !== "string" || Buffer.byteLength(value.receiptJws, "ascii") > 12000) throw badEnvelope();
seen.add(value.deliveryId); return { deliveryId: value.deliveryId, receiptJws: value.receiptJws };
});
if (values.deliveryIds.filter(id => /^slack_form_[a-f0-9]{64}$/.test(id)).some(id => !seen.has(id))) throw badEnvelope();
return { acknowledged: response.acknowledged, formReceipts };
},
async acknowledgeEvents(values: { subject: string; companyId: string; leaseId: string; deliveryIds: string[] }): Promise<number> {
const acknowledgement = JSON.stringify({ leaseId: values.leaseId, deliveryIds: values.deliveryIds });
const response = await call("event-ack", values, { field: "acknowledgement", value: acknowledgement });
const acknowledged = response.acknowledged;
if (typeof acknowledged !== "number" || !Number.isSafeInteger(acknowledged) || acknowledged < 0) {
throw new PaperclipCloudConnectorError("Paperclip Cloud connector returned an invalid acknowledgement", "CONNECTOR_BAD_RESPONSE");
}
return acknowledged;
},
};
}
function parseCloudHandoff(value: unknown): { kind: "paperclip_cloud"; session: string } | undefined {
if (value === undefined) return undefined;
if (!value || typeof value !== "object" || Array.isArray(value)) {
throw new PaperclipCloudConnectorError("Paperclip Cloud connector returned an invalid handoff", "CONNECTOR_BAD_RESPONSE");
}
const record = value as Record<string, unknown>;
const session = record.session;
if (
record.kind !== "tenant_background"
|| typeof session !== "string"
|| session.length < 16
|| session.length > 512
|| !/^[A-Za-z0-9_-]+$/.test(session)
) {
throw new PaperclipCloudConnectorError("Paperclip Cloud connector returned an invalid handoff", "CONNECTOR_BAD_RESPONSE");
}
return { kind: "paperclip_cloud", session };
}
export type PaperclipCloudConnector = Omit<ReturnType<typeof createPaperclipCloudConnector>, "instanceIdentity" | "slackFormOperation"> & {
instanceIdentity?: () => Readonly<{ instanceId: string; environment: PaperclipCloudConnectorEnvironment }>;
slackFormOperation?: ReturnType<typeof createPaperclipCloudConnector>["slackFormOperation"];
};
export type PaperclipCloudGoogleWorkspaceConnector = PaperclipCloudConnector;
/** Accept persisted Paperclip ID-era records while all new records use the Cloud strategy. */
export function isPaperclipCloudConnectorStrategy(value: unknown): boolean {
return value === "paperclip_cloud_connector" || value === "paperclip_id_connector";
}
/** Use the same signed instance profiles for catalog display and setup validation. */
export function appWithPaperclipCloudConnectorAvailability(
app: AppDefinition,
profiles: readonly string[],
): AppDefinition {
const enabledProfiles = new Set(profiles);
const methods = app.methods.filter((method) =>
!isPaperclipCloudConnectorStrategy(method.oauthStrategy)
|| Boolean(method.connectorProfile && enabledProfiles.has(method.connectorProfile))
);
return {
...app,
methods,
ownershipAvailability: {
...DEFAULT_OWNERSHIP_AVAILABILITY,
...app.ownershipAvailability,
platform_shared: methods.some((method) => isPaperclipCloudConnectorStrategy(method.oauthStrategy)),
},
};
}
let capabilityCache: { key: string; expiresAt: number; profiles: PaperclipCloudConnectorProfileId[] } | null = null;
let capabilityCacheGeneration = 0;
export function invalidatePaperclipCloudConnectorCapabilities(): void {
capabilityCacheGeneration += 1;
capabilityCache = null;
}
export async function paperclipCloudConnectorCapabilitiesFromEnv(
env: NodeJS.ProcessEnv = process.env,
): Promise<PaperclipCloudConnectorProfileId[]> {
let config: PaperclipCloudConnectorConfig | null;
try {
config = paperclipCloudConnectorConfigFromEnv(env);
} catch (error) {
// Gallery discovery is useful even while connector enrollment is pending or
// local connector settings are incomplete. Treat every connector-config
// error as "no managed profiles" here; enrollment/status surfaces still
// report the actionable configuration problem.
if (error instanceof PaperclipCloudConnectorError) return [];
throw error;
}
if (!config) return [];
const key = `${config.baseUrl}|${config.instanceId}|${config.environment}`;
if (capabilityCache?.key === key && capabilityCache.expiresAt > Date.now()) return capabilityCache.profiles;
const generation = capabilityCacheGeneration;
const connector = createPaperclipCloudConnector({ config });
const profiles = await connector.getCapabilities();
if (generation === capabilityCacheGeneration) {
capabilityCache = { key, expiresAt: Date.now() + 60_000, profiles };
}
return profiles;
}
function signRequest(payload: Record<string, unknown>, key: KeyObject): string {
const header = { alg: "EdDSA", typ: JWS_TYP };
const signingInput = `${base64Url(JSON.stringify(header))}.${base64Url(JSON.stringify(payload))}`;
return `${signingInput}.${sign(null, Buffer.from(signingInput, "utf8"), key).toString("base64url")}`;
}
function privateKey(value: string, curve: "ed25519" | "x25519"): KeyObject {
try {
let parsed: KeyObject;
if (value.includes("BEGIN PRIVATE KEY")) {
parsed = createPrivateKey(value);
} else {
const raw = Buffer.from(value, "base64url");
parsed = raw.length === RAW_PRIVATE_KEY_BYTES
? createPrivateKey({
key: Buffer.concat([curve === "ed25519" ? ED25519_PKCS8_PREFIX : X25519_PKCS8_PREFIX, raw]),
format: "der",
type: "pkcs8",
})
: createPrivateKey({ key: raw, format: "der", type: "pkcs8" });
}
if (parsed.asymmetricKeyType !== curve) throw new Error("wrong key type");
return parsed;
} catch {
throw new PaperclipCloudConnectorError(`Paperclip Cloud ${curve} private key is invalid`, "CONNECTOR_CONFIG_INVALID");
}
}
function parseEnvelope(
value: unknown,
purpose: SealedEnvelope["purpose"],
provider: PaperclipCloudConnectorProvider,
profile: SealedEnvelopeProfileId,
): SealedEnvelope {
if (!value || typeof value !== "object" || Array.isArray(value)) throw badEnvelope();
const candidate = value as Partial<SealedEnvelope>;
if (candidate.v !== 1 || candidate.alg !== SEAL_ALGORITHM || candidate.purpose !== purpose
|| candidate.provider !== provider || candidate.profile !== profile
|| typeof candidate.epk !== "string" || typeof candidate.iv !== "string" || typeof candidate.ct !== "string") {
throw badEnvelope();
}
return candidate as SealedEnvelope;
}
function unseal(
envelope: SealedEnvelope,
recipientPrivateKey: KeyObject,
instanceId: string,
environment: string,
provider: PaperclipCloudConnectorProvider,
profile: PaperclipCloudConnectorProfileId,
scopes: readonly string[],
): SealedConnectorCredentials {
try {
const parsed = decryptEnvelope(envelope, recipientPrivateKey, instanceId, environment, provider, profile, scopes) as Partial<SealedConnectorCredentials>;
if (parsed.v !== 1 || typeof parsed.accessToken !== "string" || parsed.accessToken.length === 0
|| !(parsed.refreshToken === null || typeof parsed.refreshToken === "string")
|| typeof parsed.tokenType !== "string"
|| !(parsed.accessTokenExpiresAt === null || typeof parsed.accessTokenExpiresAt === "string")
|| !(parsed.refreshTokenExpiresAt === null || typeof parsed.refreshTokenExpiresAt === "string")
|| !Array.isArray(parsed.scopes) || !parsed.scopes.every((scope) => typeof scope === "string")
|| typeof parsed.subject !== "string" || typeof parsed.companyId !== "string"
|| typeof parsed.instanceId !== "string" || typeof parsed.environment !== "string"
|| !(parsed.appSlug === undefined || (typeof parsed.appSlug === "string" && /^[a-z0-9-]{1,100}$/.test(parsed.appSlug)))
|| parsed.provider !== provider || parsed.profile !== profile) {
throw badEnvelope();
}
return parsed as SealedConnectorCredentials;
} catch (error) {
if (error instanceof PaperclipCloudConnectorError) throw error;
throw badEnvelope();
}
}
function unsealEvents(
envelope: SealedEnvelope,
recipientPrivateKey: KeyObject,
instanceId: string,
environment: PaperclipCloudConnectorEnvironment,
): SealedConnectorEvents {
try {
const parsed = decryptEnvelope(envelope, recipientPrivateKey, instanceId, environment, "github", "github.code", []) as Partial<SealedConnectorEvents>;
if (parsed.v !== 1 || parsed.instanceId !== instanceId || parsed.environment !== environment
|| typeof parsed.leaseId !== "string" || !Array.isArray(parsed.events)) throw badEnvelope();
for (const event of parsed.events) {
if (!isRecord(event) || typeof event.id !== "string" || !["github", "slack"].includes(event.provider)
|| typeof event.event !== "string" || !isRecord(event.payload) || !Array.isArray(event.bindingIds)
|| !event.bindingIds.every((id) => typeof id === "string")) throw badEnvelope();
}
return parsed as SealedConnectorEvents;
} catch (error) {
if (error instanceof PaperclipCloudConnectorError) throw error;
throw badEnvelope();
}
}
function decryptEnvelope(
envelope: SealedEnvelope,
recipientPrivateKey: KeyObject,
instanceId: string,
environment: string,
provider: PaperclipCloudConnectorProvider,
profile: SealedEnvelopeProfileId,
scopes: readonly string[],
): unknown {
const ephemeralRaw = Buffer.from(envelope.epk, "base64url");
if (ephemeralRaw.length !== 32) throw badEnvelope();
const ephemeralKey = createPublicKey({
key: Buffer.concat([X25519_SPKI_PREFIX, ephemeralRaw]),
format: "der",
type: "spki",
});
const recipientJwk = createPublicKey(recipientPrivateKey).export({ format: "jwk" }) as { x?: string };
if (!recipientJwk.x) throw badEnvelope();
const recipientRaw = Buffer.from(recipientJwk.x, "base64url");
if (envelope.provider !== provider || envelope.profile !== profile) throw badEnvelope();
const aad = Buffer.from([
1,
SEAL_ALGORITHM,
envelope.purpose,
instanceId,
environment,
provider,
profile,
[...scopes].sort().join(" "),
].join("\n"), "utf8");
const key = Buffer.from(hkdfSync(
"sha256",
diffieHellman({ privateKey: recipientPrivateKey, publicKey: ephemeralKey }),
Buffer.concat([ephemeralRaw, recipientRaw]),
// The combined profile's scope binding exceeds Node's 1024-byte HKDF-info
// limit. Its new wire contract hashes that binding; legacy profiles retain
// their original derivation. GCM still authenticates the complete AAD.
provider === "google" && profile === "workspace.all" ? createHash("sha256").update(aad).digest() : aad,
32,
));
const iv = Buffer.from(envelope.iv, "base64url");
const combined = Buffer.from(envelope.ct, "base64url");
if (iv.length !== 12 || combined.length <= AES_TAG_BYTES) throw badEnvelope();
const decipher = createDecipheriv("aes-256-gcm", key, iv, { authTagLength: AES_TAG_BYTES });
decipher.setAAD(aad);
decipher.setAuthTag(combined.subarray(-AES_TAG_BYTES));
const plaintext = Buffer.concat([
decipher.update(combined.subarray(0, -AES_TAG_BYTES)),
decipher.final(),
]);
return JSON.parse(plaintext.toString("utf8")) as unknown;
}
function badEnvelope() {
return new PaperclipCloudConnectorError("Paperclip Cloud connector returned an invalid sealed credential", "CONNECTOR_BAD_RESPONSE");
}
function sealPurpose(
kind: "initial" | "access",
_profile: PaperclipCloudConnectorProfileId,
): SealedEnvelope["purpose"] {
return kind;
}
function connectorProfileDefinition(profile: PaperclipCloudConnectorProfileId): {
provider: PaperclipCloudConnectorProvider;
scopes: readonly string[];
} {
if (profile === "tailscale.tailnet") return { provider: "tailscale", scopes: ["auth_keys:create:once"] };
if (profile === "slack.manager") return { provider: "slack", scopes: SLACK_MANAGER_SCOPES };
if (profile === "github.bot") return { provider: "github", scopes: [] };
if (isAsanaConnectorProfileId(profile)) {
return { provider: "asana", scopes: ASANA_CONNECTOR_SCOPES };
}
if (isGitHubConnectorProfileId(profile)) {
return { provider: "github", scopes: GITHUB_CONNECTOR_PROFILES[profile].scopes };
}
return { provider: "google", scopes: GOOGLE_WORKSPACE_CONNECTOR_PROFILES[profile].scopes };
}
function isExpectedProviderAuthorizationUrl(
profile: PaperclipCloudConnectorProfileId,
url: URL,
): boolean {
if (profile === "tailscale.tailnet") return url.origin === "https://login.tailscale.com" && url.pathname === "/a/oauth_authorize";
if (profile === "slack.manager") return url.origin === "https://slack.com" && url.pathname === "/oauth/v2/authorize";
if (isAsanaConnectorProfileId(profile)) {
return url.origin === "https://app.asana.com" && url.pathname === "/-/oauth_authorize";
}
if (isGitHubConnectorProfileId(profile)) {
return url.origin === "https://github.com" && url.pathname === "/login/oauth/authorize";
}
return url.origin === "https://accounts.google.com" && url.pathname === "/o/oauth2/v2/auth";
}
function isPaperclipCloudConnectorProfileId(value: string): value is PaperclipCloudConnectorProfileId {
return value === "tailscale.tailnet" || value === "slack.manager" || isGoogleWorkspaceConnectorProfileId(value) || isGitHubConnectorProfileId(value) || isAsanaConnectorProfileId(value);
}
async function sha256Base64Url(value: string): Promise<string> {
return createHash("sha256").update(value, "utf8").digest("base64url");
}
function base64Url(value: string): string {
return Buffer.from(value, "utf8").toString("base64url");
}
function sameStringSet(value: unknown, expected: readonly string[]): boolean {
return Array.isArray(value)
&& value.every((item) => typeof item === "string")
&& value.length === expected.length
&& expected.every((item) => value.includes(item));
}
function isRecord(value: unknown): value is Record<string, unknown> {
return Boolean(value) && typeof value === "object" && !Array.isArray(value);
}
function isLoopback(hostname: string): boolean {
return hostname === "localhost" || hostname === "127.0.0.1" || hostname === "::1" || hostname === "[::1]";
}