mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-16 11:59:26 +01:00
## Thinking Path > - Paperclip manages work for AI-agent companies. > - Chat connections deliver provider messages and user answers. > - Slack requires a response within its original three-second deadline. > - Forms and their delivery receipts must survive retries and tenant restarts. > - This change uses the existing connector queue and durable form owners. > - Current authorization, exact receipt checks and normal ACK rules stay in force. > - The tenant can settle useful work while keeping the connection enabled. ## Linked Issues or Issue Description Refs #19019 and #19348. Companion Cloud PR: paperclipai/paperclip-cloud#1250. ## What Changed - Preserve form grants, sessions, encrypted evidence, terminal receipts and company-authorized Retry. - Check initial form enrollment before the provider send. Keep a typed preparation wait only while an exact current enrollment obligation exists. - Refund the attempt only when the claimed attempt and credential lease still match and provider invocation has not started. Possible or accepted sends retain uncertain-delivery custody. An ordinary error with the same text still uses the normal five-attempt limit. - Notify the existing publication worker when normal enrollment commits. Reconstruct pending work from durable state after a lost reply or owner restart. - Page settled history before proving idle safety. Keep unfinished, malformed and foreign receipts visible beyond the first 1,000 rows. - Keep Slack callback, answer, receipt and ACK rules in their provider owners. Support body-bound Cloud idle capabilities when a complete catalog exceeds the header budget. - Add focused regression coverage, an enabled quiet/reactivation recipe and explicit fixture port checks. - Keep SDK evidence tests tied to a normally built reviewed reference, with a separate strict refusal for actual unreviewed CI outputs. ## Verification App head: `6284d6881b5dc38a9ee149bcbde35e69a67dd8ca`, including actual master `dff8bed007e01c32f3826144b893ec80603d1335`. Companion Cloud head: `f83b38187dc7e6b2e219fe865dc16d268cc66fdb`, including actual Cloud master `b1dcc3421a91efffee631a61536cf48f357c22fc`. Cloud #1250 is merged at `1d07d81f23d4627ab7b6dcf49176b4128a2f8f9b` after exact-head passing checks and complete Greptile 5/5. Current exact-head CI typecheck, build, tests and aggregate verification are green; the complete edited Greptile review is 5/5 and all 13 review threads and nested comment pages are resolved. - Both latest enrollment findings were reproduced against the preceding product. The pure readiness control returned no wait for the first enrollment. The real-PostgreSQL control observed a provider call while that enrollment was still staged. - The repaired source passes three whole files: 21 readiness controls, 80 real-PostgreSQL milestone controls and 37 tenant-actor middleware controls. All 138 pass with zero excluded or TODO cases. The SQL case reconstructs the worker through seven waits, preserves the attempt budget, recovers a controlled lost enrollment reply, and commits one provider-port call and one exact grant. Replaying the selected attempt does not duplicate them. Authorization, SDK and enrollment-response ports are controlled in that SQL case. - The same files cover ordinary five-attempt exhaustion, accepted and possible sends, stale ownership, malformed bindings, attention states and current actor restrictions. One synthetic mismatched-binding parameter uses generation 2 against current generation 1; it is not evidence for an older-generation control. - The normal server-package typecheck passes at the measured source. It runs the normal Runner TypeScript, protocol, SDK and declaration prerequisites and all seven main App programs. The separate declaration configuration is also recorded. A worker union-narrowing error was found, fixed with an explicit callable/null branch, and verified by that normal compiler. No cast or test relaxation was used. - The normal merge of current master preserves all 78 owned paths and 15,783 unrelated master entries and modes. The three measured test files and their changed feature paths are unchanged. New upstream DB code adds only the normal nonunique concurrent native-session index and its migration classification. Shared and adapter-utils changes alter unrelated prompt or denial wording. The 138-case proof carries for those unchanged behaviors; it is not reported as a rerun after the merge. The normal Shared/SDK ensure, DB build, adapter-utils build and complete server-package check also pass at the current merged head. Their fresh inventory contains 8,143 outputs; canonical SQL and journal copies match. This build did not apply the new index migration. - Earlier real-PostgreSQL retained-history coverage reproduced the missing proof with 1,005 settled rows. Its repair retains the existing two-second/64-query inspection budget, current endpoint bound and exact owner snapshot. The 46 source-bound controls cover unfinished and invalid tails, exact cross-page action references, Retry, rollback and lost receipt responses. - Earlier enabled quiet/reactivation coverage produced ordinary useful work, kept configuration enabled, accepted fresh signed work plus a duplicate, and produced exactly one second useful reply. Its two App-worker windows lasted at least 30 seconds with zero measured PG writes, connection or outbound activity after settlement. That evidence stays tied to its measured revision. A missing worker EXIT marker limits that earlier proof; parent evidence does not replace it. - Earlier three-second callback, terminal ACK, current-question race and complete body-size controls remain source-bound. The 500-owner/1,000-binding body measured 313,875 bytes with a 618-byte JWT; signature tampering failed closed. - Final managed-provider acceptance now passes all five fresh Node boots: A/A, A/AB, B/A rejection, B/AB recovery, B/B final. Two independently configured, challenged, verified, linked and enrolled Slack identities exercise ACK and retirement debt separately. Normal provider factory/materialization delivers the configuration through a controlled external stack-provider boundary. The registered opening returns HTTP 200 in 21 ms within the original 3-second deadline. Two answers persist, normal ACK is accepted, exact retirement and lost acceptance/GC replies recover, and the original canonical snapshot remains unchanged without duplicate provider sends or submissions. - The separate complete committed-preflight case passes. A committed `update_attempted` response is lost before SDK entry; normal service-owner reconstruction after the original lease/deadline recovers the same useful update and one answer without a second trigger. This reconstructs service owners within one App process; the separate five fresh Node boots cover process restart and managed signing-key rotation. - Assertion-time PG socket reports balance 15 opens/15 closes across the five boots and 5/5 in preflight, peak 2 and zero live sockets or unexpected attempts. Worker terminal EXIT markers were missing and are not replaced by parent EXIT markers. These are domain/recovery and assertion-time connection proofs, not a new whole-worker terminal quiet measurement. All known owners/groups closed; independent SQL audits were empty; only successful fixture databases were removed. Earlier failed fixture databases/logs remain retained. No product guard, deadline or assertion was weakened. Exact runtime source and normal outputs are unchanged by the three test files in the current follow-up, so these source-bound proofs carry without repeating those journeys. - The preceding App CI ran 11,312 support cases: 11,289 passed, three SDK-evidence cases failed, and 20 external cases skipped. Normal CI dependency setup resolved six stale Slack patch-hash references and produced an unreviewed lock. The public SDK proof correctly refused that lock; the tests incorrectly assumed the CI output was a reviewed reference. The three-file test repair keeps the protected lock policy, source/compiler/parser/Zod pins, scanner and redaction rules unchanged. It builds an owned reviewed reference using the existing normal Shared/SDK producers for the positive seal test, while a separate negative requires actual unreviewed-build privacy refusal and no retained SDK bytes. It does not relabel the CI build as certified or admit a new lock hash. - All four whole SDK support files pass locally: public type 30, evidence 16, public-input synchronizer 8 and lock preparation 10, totaling 64 with zero excluded/TODO cases in 28.73 seconds. The genuine fresh reference build/positive seal and separate invalidated-reference privacy refusal passed within their original 120-second bounds. Original installed dependencies, SDK outputs/cache and runtime source stayed unchanged; normal global setup produced only its own Runner JavaScript outputs. PostgreSQL was denied throughout, all four worker markers were observed, and the owned process group/private test root closed. The local canonical-lock negative mutates only its own reference; fresh remote CI also passes the actual resolved-CI-lock branch: all 16 evidence and 30 public-type tests pass, including the genuine reviewed-reference positive and the strict actual-unreviewed-build refusal. The upstream synchronizer file runs its current 10 cases in CI. - The first complete CI attempt on this head also exposed two separate 30-second timeouts: one real reporter-artifact test and the `agent-test-environment` module-loading hook. Full original logs remain preserved. Their exact test, sanitizer and evidence source blobs are unchanged from the preceding head; inspection found no deterministic setup cause. After the original run finished, one retry of only the failed jobs passed on the same synthetic merge `168851e210671ebe97e7a778e8cf891807e80502`: Runner support reports 11,304 passes and 20 external skips; serialized shard 6 reports all 395 passes, including all 67 route bodies. No source, timeout or assertion changed. This proves recovery; the original causes remain unexplained. - The final pre-merge tree audit uses actual master `17136a6c25ef6cb7c816a29140a4c48c2c75fb31` (refreshed after the earlier `85dec046` audit). The expected normal squash preserves all 81 owned paths and 15,816 unrelated master entries and modes. Only OpenAPI has edits from both sides, and its complete content composition preserves the new project route and token help alongside this PR's API entries. The shared inbound selection changes preserve the same candidate set; new concurrent indexes, Native/workspace behavior and shutdown changes remain upstream behavior. The scoped form proof uses process agents and does not qualify the new Native/sandbox branches. The latest question-schema change still accepts the explicit version-1 payload exercised here. The last master delta also changes managed AI/Native credential refresh and writeback; those branches are outside the measured process-agent form paths. Existing 8,143 local outputs remain tied to their measured revision; no new whole-tree output equality or deployed suspension is claimed. - Reproduce the public path with `doc/testing/slack-cloud-qualification.md`, the companion Cloud checkout, Node 24/22 and fresh owned fixture databases. Aggregate local `pnpm -r typecheck`, `pnpm test:run` and `pnpm build` were not rerun as one command set. Current exact-head required CI and the complete Greptile 5/5 review now pass; the full edited summaries and all paginated threads were read. Local worker quiet does not prove deployed host or Neon suspension. Photon and Discord remain separate work; this PR completes the described Slack slice. ## Risks Use compatible App and Cloud readers before transferring custody. Signatures prove authenticity; current authorization and exact ownership still control execution. Preserve old targets, secrets and terminal facts until their normal owners release them. Keep the managed seal identity stable while custody remains. The required Slack adapter patch remains pinned. Upstream's concurrent index uses the normal top-level migration path. ## Model Used OpenAI `gpt-6.1-sol` implemented and tested the changes. A GPT-6-based Codex managing agent reviewed and integrated them. The host does not expose the managing agent's exact model ID or context-window sizes. The agents used code execution and test tools. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used, its version and tool capabilities - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have linked public related issues or PRs - [x] I have not referenced internal or instance-local Paperclip issues or links - [x] My branch name describes the change and contains no internal Paperclip ticket id - [x] I have run the local tests listed above and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation - [x] I have considered and documented risks - [x] All Paperclip CI gates are green for the current head - [x] Greptile is 5/5 with no open findings for the current head - [x] I will address all reviewer comments before requesting merge --------- Co-authored-by: Paperclip <noreply@paperclip.ing>
635 lines
24 KiB
TypeScript
635 lines
24 KiB
TypeScript
import { DEFAULT_JSON_BODY_LIMIT_BYTES } from "../http/body-limits.js";
|
|
import { parseIdleCapabilities, type IdleCapabilities } from "./idle-incoming-wake-capability.js";
|
|
import { createHash, createPublicKey, timingSafeEqual, verify, type JsonWebKey } from "node:crypto";
|
|
import { eq } from "drizzle-orm";
|
|
import type { Db } from "@paperclipai/db";
|
|
import { instanceSettings } from "@paperclipai/db";
|
|
|
|
export const CLOUD_RUNTIME_IDENTITY_HEADER = "x-paperclip-cloud-runtime-identity";
|
|
export const CLOUD_RUNTIME_IDENTITY_AUDIENCE = "paperclip-runtime-identity/v1";
|
|
export const CLOUD_RUNTIME_IDENTITY_ISSUER = "paperclip-cloud";
|
|
export const CLOUD_RUNTIME_IDENTITY_JWS_TYPE = "paperclip-cloud-runtime-identity+jwt";
|
|
|
|
const SINGLETON_KEY = "cloud-runtime-identity/v1";
|
|
const MAX_ASSERTION_LIFETIME_SECONDS = 10 * 60;
|
|
const MAX_CLOCK_SKEW_SECONDS = 30;
|
|
const STACK_SLUG_PATTERN = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;
|
|
|
|
type PersistedRuntimeIdentity = {
|
|
stackId: string;
|
|
claimId: string;
|
|
previousOrigin: string;
|
|
canonicalOrigin: string;
|
|
stackSlug: string;
|
|
appliedAt: Date;
|
|
};
|
|
|
|
type RuntimeIdentityDb = Pick<Db, "select" | "insert">;
|
|
|
|
export type CloudRuntimeIdentitySnapshot = {
|
|
stackId: string;
|
|
claimId: string;
|
|
previousOrigin: string;
|
|
canonicalOrigin: string;
|
|
stackSlug: string;
|
|
appliedAt: Date;
|
|
};
|
|
|
|
export type RuntimeIdentityClaims = {
|
|
v: 1;
|
|
iss: typeof CLOUD_RUNTIME_IDENTITY_ISSUER;
|
|
aud: typeof CLOUD_RUNTIME_IDENTITY_AUDIENCE;
|
|
sub: string;
|
|
claimId: string;
|
|
previousOrigin: string;
|
|
canonicalOrigin: string;
|
|
stackSlug: string;
|
|
iat: number;
|
|
exp: number;
|
|
};
|
|
|
|
let initialized = false;
|
|
let startupOrigin: string | null = null;
|
|
let currentIdentity: CloudRuntimeIdentitySnapshot | null = null;
|
|
|
|
function nonEmpty(value: string | undefined): string | null {
|
|
const normalized = value?.trim();
|
|
return normalized ? normalized : null;
|
|
}
|
|
|
|
function exactHttpsOrigin(value: unknown): string | null {
|
|
if (typeof value !== "string" || value.length === 0 || value.length > 2048) return null;
|
|
try {
|
|
const parsed = new URL(value);
|
|
if (
|
|
parsed.protocol !== "https:"
|
|
|| parsed.username
|
|
|| parsed.password
|
|
|| parsed.pathname !== "/"
|
|
|| parsed.search
|
|
|| parsed.hash
|
|
|| parsed.origin !== value
|
|
) {
|
|
return null;
|
|
}
|
|
return parsed.origin;
|
|
} catch {
|
|
return null;
|
|
}
|
|
}
|
|
|
|
function configuredStartupOrigin(env: NodeJS.ProcessEnv): string | null {
|
|
const candidate = nonEmpty(env.PAPERCLIP_PUBLIC_URL)
|
|
?? nonEmpty(env.PAPERCLIP_AUTH_PUBLIC_BASE_URL)
|
|
?? nonEmpty(env.PAPERCLIP_API_URL);
|
|
return candidate ? exactHttpsOrigin(candidate) : null;
|
|
}
|
|
|
|
function snapshot(row: PersistedRuntimeIdentity): CloudRuntimeIdentitySnapshot {
|
|
return {
|
|
stackId: row.stackId,
|
|
claimId: row.claimId,
|
|
previousOrigin: row.previousOrigin,
|
|
canonicalOrigin: row.canonicalOrigin,
|
|
stackSlug: row.stackSlug,
|
|
appliedAt: row.appliedAt,
|
|
};
|
|
}
|
|
|
|
function parsePersistedIdentity(row: {
|
|
general: Record<string, unknown>;
|
|
createdAt: Date;
|
|
}): PersistedRuntimeIdentity {
|
|
const value = row.general;
|
|
if (
|
|
value.v !== 1
|
|
|| typeof value.stackId !== "string"
|
|
|| typeof value.claimId !== "string"
|
|
|| typeof value.previousOrigin !== "string"
|
|
|| typeof value.canonicalOrigin !== "string"
|
|
|| typeof value.stackSlug !== "string"
|
|
) {
|
|
throw new Error("Persisted Cloud runtime identity is malformed");
|
|
}
|
|
return {
|
|
stackId: value.stackId,
|
|
claimId: value.claimId,
|
|
previousOrigin: value.previousOrigin,
|
|
canonicalOrigin: value.canonicalOrigin,
|
|
stackSlug: value.stackSlug,
|
|
appliedAt: row.createdAt,
|
|
};
|
|
}
|
|
|
|
async function readPersistedIdentity(db: RuntimeIdentityDb): Promise<PersistedRuntimeIdentity | null> {
|
|
const row = await db
|
|
.select({
|
|
general: instanceSettings.general,
|
|
createdAt: instanceSettings.createdAt,
|
|
})
|
|
.from(instanceSettings)
|
|
.where(eq(instanceSettings.singletonKey, SINGLETON_KEY))
|
|
.limit(1)
|
|
.then((rows) => rows[0] ?? null);
|
|
return row ? parsePersistedIdentity(row) : null;
|
|
}
|
|
|
|
function applyCompatibilityEnvironment(identity: CloudRuntimeIdentitySnapshot, env: NodeJS.ProcessEnv) {
|
|
const hostname = new URL(identity.canonicalOrigin).hostname;
|
|
env.PAPERCLIP_PUBLIC_URL = identity.canonicalOrigin;
|
|
env.PAPERCLIP_AUTH_PUBLIC_BASE_URL = identity.canonicalOrigin;
|
|
env.PAPERCLIP_API_URL = identity.canonicalOrigin;
|
|
env.PAPERCLIP_PRIMARY_HOST = hostname;
|
|
env.PAPERCLIP_STACK_SLUG = identity.stackSlug;
|
|
|
|
const existingCandidates = (() => {
|
|
try {
|
|
const parsed = JSON.parse(env.PAPERCLIP_RUNTIME_API_CANDIDATES_JSON ?? "[]");
|
|
return Array.isArray(parsed) ? parsed.filter((value): value is string => typeof value === "string") : [];
|
|
} catch {
|
|
return [];
|
|
}
|
|
})();
|
|
env.PAPERCLIP_RUNTIME_API_CANDIDATES_JSON = JSON.stringify([
|
|
identity.canonicalOrigin,
|
|
...existingCandidates.filter((candidate) => candidate !== identity.canonicalOrigin),
|
|
]);
|
|
}
|
|
|
|
function assertPersistedIdentityMatchesStack(row: PersistedRuntimeIdentity, env: NodeJS.ProcessEnv) {
|
|
const configuredStackId = nonEmpty(env.PAPERCLIP_CLOUD_STACK_ID);
|
|
if (!configuredStackId || configuredStackId !== row.stackId) {
|
|
throw new Error("Persisted Cloud runtime identity does not match PAPERCLIP_CLOUD_STACK_ID");
|
|
}
|
|
if (!exactHttpsOrigin(row.previousOrigin) || !exactHttpsOrigin(row.canonicalOrigin)) {
|
|
throw new Error("Persisted Cloud runtime identity contains an invalid origin");
|
|
}
|
|
if (!STACK_SLUG_PATTERN.test(row.stackSlug) || new URL(row.canonicalOrigin).hostname.split(".")[0] !== row.stackSlug) {
|
|
throw new Error("Persisted Cloud runtime identity contains an invalid stack slug");
|
|
}
|
|
}
|
|
|
|
/** Load the durable claim before auth, routes, and child-runtime configuration. */
|
|
export async function initializeCloudRuntimeIdentity(
|
|
db: Db,
|
|
env: NodeJS.ProcessEnv = process.env,
|
|
): Promise<CloudRuntimeIdentitySnapshot | null> {
|
|
startupOrigin = configuredStartupOrigin(env);
|
|
// Self-hosted servers have no Cloud stack identity to restore. Avoid touching
|
|
// the singleton table on that path; besides keeping the feature inert, this
|
|
// preserves lightweight startup/test database seams that intentionally do
|
|
// not construct a database client.
|
|
if (!nonEmpty(env.PAPERCLIP_CLOUD_STACK_ID)) {
|
|
initialized = true;
|
|
currentIdentity = null;
|
|
return null;
|
|
}
|
|
const row = await readPersistedIdentity(db);
|
|
initialized = true;
|
|
if (!row) {
|
|
currentIdentity = null;
|
|
return null;
|
|
}
|
|
assertPersistedIdentityMatchesStack(row, env);
|
|
currentIdentity = snapshot(row);
|
|
applyCompatibilityEnvironment(currentIdentity, env);
|
|
return currentIdentity;
|
|
}
|
|
|
|
export function getCloudRuntimeIdentity(): CloudRuntimeIdentitySnapshot | null {
|
|
return currentIdentity ? { ...currentIdentity } : null;
|
|
}
|
|
|
|
/** The live canonical origin, falling back to startup configuration off Cloud. */
|
|
export function runtimePublicOrigin(env: NodeJS.ProcessEnv = process.env): string | null {
|
|
if (env === process.env && currentIdentity) return currentIdentity.canonicalOrigin;
|
|
const candidate = nonEmpty(env.PAPERCLIP_PUBLIC_URL)
|
|
?? nonEmpty(env.PAPERCLIP_AUTH_PUBLIC_BASE_URL)
|
|
?? nonEmpty(env.PAPERCLIP_API_URL);
|
|
if (!candidate) return null;
|
|
try {
|
|
return new URL(candidate).origin;
|
|
} catch {
|
|
return null;
|
|
}
|
|
}
|
|
|
|
/** The asserted Cloud origin only. Callers retain their non-Cloud precedence. */
|
|
export function runtimeCanonicalOrigin(): string | null {
|
|
return currentIdentity?.canonicalOrigin ?? null;
|
|
}
|
|
|
|
function decodeJsonPart(part: string, label: string): Record<string, unknown> {
|
|
if (!/^[A-Za-z0-9_-]+$/.test(part)) throw new Error(`Cloud runtime identity has an invalid ${label}`);
|
|
let parsed: unknown;
|
|
try {
|
|
parsed = JSON.parse(Buffer.from(part, "base64url").toString("utf8"));
|
|
} catch {
|
|
throw new Error(`Cloud runtime identity has an invalid ${label}`);
|
|
}
|
|
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
|
|
throw new Error(`Cloud runtime identity has an invalid ${label}`);
|
|
}
|
|
return parsed as Record<string, unknown>;
|
|
}
|
|
|
|
export function cloudRuntimePublicKeyForKid(env: NodeJS.ProcessEnv, kid: string) {
|
|
const raw = nonEmpty(env.PAPERCLIP_CLOUD_RUNTIME_IDENTITY_JWKS);
|
|
if (!raw) throw new Error("PAPERCLIP_CLOUD_RUNTIME_IDENTITY_JWKS is not configured");
|
|
let parsed: unknown;
|
|
try {
|
|
parsed = JSON.parse(raw);
|
|
} catch {
|
|
throw new Error("PAPERCLIP_CLOUD_RUNTIME_IDENTITY_JWKS is invalid");
|
|
}
|
|
const keys = parsed && typeof parsed === "object" && !Array.isArray(parsed)
|
|
? (parsed as { keys?: unknown }).keys
|
|
: undefined;
|
|
if (!Array.isArray(keys)) throw new Error("PAPERCLIP_CLOUD_RUNTIME_IDENTITY_JWKS is invalid");
|
|
const matches = keys.filter((candidate): candidate is JsonWebKey & { kid: string } => {
|
|
if (!candidate || typeof candidate !== "object" || Array.isArray(candidate)) return false;
|
|
const key = candidate as JsonWebKey & { kid?: unknown };
|
|
return key.kid === kid;
|
|
});
|
|
if (matches.length !== 1) throw new Error("Cloud runtime identity uses an unknown signing key");
|
|
const jwk = matches[0];
|
|
if (jwk.kty !== "OKP" || jwk.crv !== "Ed25519" || jwk.use !== "sig" || jwk.alg !== "EdDSA" || !jwk.x || jwk.d) {
|
|
throw new Error("Cloud runtime identity signing key is invalid");
|
|
}
|
|
return createPublicKey({ key: jwk, format: "jwk" });
|
|
}
|
|
|
|
function verifyClaims(input: {
|
|
compactJws: string;
|
|
env: NodeJS.ProcessEnv;
|
|
now: Date;
|
|
}): RuntimeIdentityClaims {
|
|
const parts = input.compactJws.split(".");
|
|
if (parts.length !== 3 || parts.some((part) => part.length === 0)) {
|
|
throw new Error("Cloud runtime identity assertion is not a compact JWS");
|
|
}
|
|
const [encodedHeader, encodedPayload, encodedSignature] = parts;
|
|
const header = decodeJsonPart(encodedHeader, "protected header");
|
|
if (
|
|
header.alg !== "EdDSA"
|
|
|| header.typ !== CLOUD_RUNTIME_IDENTITY_JWS_TYPE
|
|
|| typeof header.kid !== "string"
|
|
|| !header.kid
|
|
) {
|
|
throw new Error("Cloud runtime identity protected header is invalid");
|
|
}
|
|
const key = cloudRuntimePublicKeyForKid(input.env, header.kid);
|
|
const signature = Buffer.from(encodedSignature, "base64url");
|
|
const signingInput = Buffer.from(`${encodedHeader}.${encodedPayload}`, "ascii");
|
|
if (!verify(null, signingInput, key, signature)) {
|
|
throw new Error("Cloud runtime identity signature is invalid");
|
|
}
|
|
|
|
const payload = decodeJsonPart(encodedPayload, "payload");
|
|
const nowSeconds = Math.floor(input.now.getTime() / 1000);
|
|
if (
|
|
payload.v !== 1
|
|
|| payload.iss !== CLOUD_RUNTIME_IDENTITY_ISSUER
|
|
|| payload.aud !== CLOUD_RUNTIME_IDENTITY_AUDIENCE
|
|
|| typeof payload.sub !== "string"
|
|
|| typeof payload.claimId !== "string"
|
|
|| typeof payload.previousOrigin !== "string"
|
|
|| typeof payload.canonicalOrigin !== "string"
|
|
|| typeof payload.stackSlug !== "string"
|
|
|| typeof payload.iat !== "number"
|
|
|| !Number.isInteger(payload.iat)
|
|
|| typeof payload.exp !== "number"
|
|
|| !Number.isInteger(payload.exp)
|
|
) {
|
|
throw new Error("Cloud runtime identity claims are incomplete");
|
|
}
|
|
if (
|
|
payload.exp <= nowSeconds
|
|
|| payload.iat > nowSeconds + MAX_CLOCK_SKEW_SECONDS
|
|
|| payload.exp <= payload.iat
|
|
|| payload.exp - payload.iat > MAX_ASSERTION_LIFETIME_SECONDS
|
|
) {
|
|
throw new Error("Cloud runtime identity assertion is expired or has an invalid lifetime");
|
|
}
|
|
return payload as RuntimeIdentityClaims;
|
|
}
|
|
|
|
/** Verify that an assertion is signed for this exact, still-unclaimed instance. */
|
|
export function verifyCloudRuntimeIdentityAssertion(input: {
|
|
compactJws: string;
|
|
env?: NodeJS.ProcessEnv;
|
|
now?: Date;
|
|
expectedPreviousOrigin: string | null;
|
|
}): RuntimeIdentityClaims {
|
|
const env = input.env ?? process.env;
|
|
const claims = verifyClaims({ compactJws: input.compactJws, env, now: input.now ?? new Date() });
|
|
const configuredStackId = nonEmpty(env.PAPERCLIP_CLOUD_STACK_ID);
|
|
if (!configuredStackId || claims.sub !== configuredStackId) {
|
|
throw new Error("Cloud runtime identity stack does not match this instance");
|
|
}
|
|
const previousOrigin = exactHttpsOrigin(claims.previousOrigin);
|
|
const canonicalOrigin = exactHttpsOrigin(claims.canonicalOrigin);
|
|
if (!previousOrigin || !canonicalOrigin || previousOrigin !== input.expectedPreviousOrigin) {
|
|
throw new Error("Cloud runtime identity previous or canonical origin is invalid");
|
|
}
|
|
if (
|
|
!STACK_SLUG_PATTERN.test(claims.stackSlug)
|
|
|| new URL(canonicalOrigin).hostname.split(".")[0] !== claims.stackSlug
|
|
|| claims.claimId.length > 256
|
|
|| claims.claimId.trim() !== claims.claimId
|
|
|| !claims.claimId
|
|
) {
|
|
throw new Error("Cloud runtime identity destination is invalid");
|
|
}
|
|
return claims;
|
|
}
|
|
|
|
function assertionsEqual(row: PersistedRuntimeIdentity, claims: RuntimeIdentityClaims): boolean {
|
|
const left = Buffer.from(JSON.stringify([
|
|
row.stackId,
|
|
row.claimId,
|
|
row.previousOrigin,
|
|
row.canonicalOrigin,
|
|
row.stackSlug,
|
|
]));
|
|
const right = Buffer.from(JSON.stringify([
|
|
claims.sub,
|
|
claims.claimId,
|
|
claims.previousOrigin,
|
|
claims.canonicalOrigin,
|
|
claims.stackSlug,
|
|
]));
|
|
return left.length === right.length && timingSafeEqual(left, right);
|
|
}
|
|
|
|
/** Verify and durably apply the one-time Cloud claim assertion. */
|
|
export async function applyCloudRuntimeIdentityAssertion(input: {
|
|
db: Db;
|
|
compactJws: string;
|
|
env?: NodeJS.ProcessEnv;
|
|
now?: Date;
|
|
}): Promise<CloudRuntimeIdentitySnapshot> {
|
|
const env = input.env ?? process.env;
|
|
if (!initialized) throw new Error("Cloud runtime identity provider is not initialized");
|
|
const claims = verifyCloudRuntimeIdentityAssertion({
|
|
compactJws: input.compactJws,
|
|
env,
|
|
now: input.now,
|
|
// After a natural restart the provider env may already be canonical, but
|
|
// an identical retry of the original claim is still safe and idempotent.
|
|
// The durable row preserves the pool origin that assertion had to match
|
|
// on first application.
|
|
expectedPreviousOrigin: currentIdentity?.previousOrigin ?? startupOrigin,
|
|
});
|
|
const previousOrigin = claims.previousOrigin;
|
|
const canonicalOrigin = claims.canonicalOrigin;
|
|
|
|
const row = await input.db.transaction(async (tx) => {
|
|
const existing = await readPersistedIdentity(tx);
|
|
if (existing) {
|
|
if (!assertionsEqual(existing, claims)) {
|
|
throw new Error("Cloud runtime identity is already claimed by another assertion");
|
|
}
|
|
return existing;
|
|
}
|
|
|
|
const now = input.now ?? new Date();
|
|
await tx
|
|
.insert(instanceSettings)
|
|
.values({
|
|
singletonKey: SINGLETON_KEY,
|
|
general: {
|
|
v: 1,
|
|
stackId: claims.sub,
|
|
claimId: claims.claimId,
|
|
previousOrigin,
|
|
canonicalOrigin,
|
|
stackSlug: claims.stackSlug,
|
|
},
|
|
experimental: {},
|
|
createdAt: now,
|
|
updatedAt: now,
|
|
})
|
|
.onConflictDoNothing({ target: instanceSettings.singletonKey });
|
|
const durable = await readPersistedIdentity(tx);
|
|
if (!durable || !assertionsEqual(durable, claims)) {
|
|
throw new Error("Cloud runtime identity is already claimed by another assertion");
|
|
}
|
|
return durable;
|
|
});
|
|
|
|
currentIdentity = snapshot(row);
|
|
applyCompatibilityEnvironment(currentIdentity, env);
|
|
return { ...currentIdentity };
|
|
}
|
|
|
|
/** Test seam for modules that intentionally share a process. */
|
|
export function resetCloudRuntimeIdentityForTests() {
|
|
initialized = false;
|
|
startupOrigin = null;
|
|
currentIdentity = null;
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Cloud control assertions
|
|
//
|
|
// A second, deliberately separate use of the same Cloud signing key: where the
|
|
// runtime identity assertion above is a ONE-TIME origin claim applied at
|
|
// bootstrap, a control assertion authorizes a single management call from the
|
|
// Cloud control plane — today, only the task-drain admission hold, so Cloud
|
|
// can stop new agent work and wait for quiescence before it restarts the
|
|
// container for a deploy. The audience, JWS type, and claim shape are
|
|
// disjoint from the runtime identity assertion, so neither token can ever be
|
|
// replayed as the other, and the verifier binds each assertion to one exact
|
|
// action so a "read status" token cannot start or stop a drain.
|
|
// ---------------------------------------------------------------------------
|
|
|
|
export const CLOUD_CONTROL_HEADER = "x-paperclip-cloud-control";
|
|
export const CLOUD_CONTROL_AUDIENCE = "paperclip-cloud-control/v1";
|
|
export const CLOUD_CONTROL_JWS_TYPE = "paperclip-cloud-control+jwt";
|
|
export const CLOUD_CONTROL_ACTIONS = [
|
|
"ephemeral-enrollment:prepare",
|
|
"task-drain:read",
|
|
"task-drain:read-body",
|
|
"task-drain:start",
|
|
"task-drain:stop",
|
|
"lifecycle:read",
|
|
"lifecycle:unarchive-primary",
|
|
"connector-events:wake",
|
|
"mcp-device:mint",
|
|
"mcp-dot:principal",
|
|
] as const;
|
|
export type CloudControlAction = (typeof CLOUD_CONTROL_ACTIONS)[number];
|
|
|
|
/** Control calls are immediate; a stolen assertion should age out fast. */
|
|
const CLOUD_CONTROL_MAX_LIFETIME_SECONDS = 5 * 60;
|
|
|
|
/**
|
|
* Single-use fence: a verified assertion's requestId is consumed atomically
|
|
* (module state; JS execution is single-threaded per process) and a replay
|
|
* of the same id is rejected for as long as the original could still be
|
|
* alive. Process-local on purpose — the drain state this protects is
|
|
* itself process-local, so a restart clears both together. Entries prune
|
|
* lazily at their expiry.
|
|
*/
|
|
const consumedControlRequestIds = new Map<string, number>();
|
|
|
|
function consumeControlRequestId(requestId: string, expSeconds: number, nowMs: number): boolean {
|
|
for (const [id, expiresAtMs] of consumedControlRequestIds) {
|
|
if (expiresAtMs <= nowMs) consumedControlRequestIds.delete(id);
|
|
}
|
|
if (consumedControlRequestIds.has(requestId)) {
|
|
return false;
|
|
}
|
|
consumedControlRequestIds.set(requestId, expSeconds * 1000);
|
|
return true;
|
|
}
|
|
|
|
/** Test seam: modules sharing a process must be able to reset the fence. */
|
|
export function resetCloudControlReplayFenceForTests() {
|
|
consumedControlRequestIds.clear();
|
|
}
|
|
|
|
export type CloudControlClaims = {
|
|
v: 1;
|
|
iss: typeof CLOUD_RUNTIME_IDENTITY_ISSUER;
|
|
aud: typeof CLOUD_CONTROL_AUDIENCE;
|
|
sub: string;
|
|
action: CloudControlAction;
|
|
requestId: string;
|
|
idleCapabilities?: IdleCapabilities;
|
|
bodySha256?: string;
|
|
iat: number;
|
|
exp: number;
|
|
};
|
|
|
|
/**
|
|
* Verify a Cloud control assertion for one exact action on this instance.
|
|
* Signed with the same key set as the runtime identity assertion
|
|
* (PAPERCLIP_CLOUD_RUNTIME_IDENTITY_JWKS) but under its own JWS type and
|
|
* audience. Instances without a Cloud stack identity reject every assertion —
|
|
* the feature is inert when self-hosted.
|
|
*/
|
|
export function verifyCloudControlAssertion(input: {
|
|
compactJws: string;
|
|
rawBody?: Uint8Array;
|
|
expectedAction: CloudControlAction;
|
|
env?: NodeJS.ProcessEnv;
|
|
now?: Date;
|
|
}): CloudControlClaims {
|
|
const env = input.env ?? process.env;
|
|
const now = input.now ?? new Date();
|
|
const parts = input.compactJws.split(".");
|
|
if (parts.length !== 3 || parts.some((part) => part.length === 0)) {
|
|
throw new Error("Cloud control assertion is not a compact JWS");
|
|
}
|
|
const [encodedHeader, encodedPayload, encodedSignature] = parts;
|
|
const header = decodeJsonPart(encodedHeader, "protected header");
|
|
if (
|
|
header.alg !== "EdDSA"
|
|
|| header.typ !== CLOUD_CONTROL_JWS_TYPE
|
|
|| typeof header.kid !== "string"
|
|
|| !header.kid
|
|
) {
|
|
throw new Error("Cloud control protected header is invalid");
|
|
}
|
|
const key = cloudRuntimePublicKeyForKid(env, header.kid);
|
|
const signature = Buffer.from(encodedSignature, "base64url");
|
|
const signingInput = Buffer.from(`${encodedHeader}.${encodedPayload}`, "ascii");
|
|
if (!verify(null, signingInput, key, signature)) {
|
|
throw new Error("Cloud control signature is invalid");
|
|
}
|
|
|
|
const payload = decodeJsonPart(encodedPayload, "payload");
|
|
const configuredStackId = nonEmpty(env.PAPERCLIP_CLOUD_STACK_ID);
|
|
const nowSeconds = Math.floor(now.getTime() / 1000);
|
|
if (
|
|
payload.v !== 1
|
|
|| payload.iss !== CLOUD_RUNTIME_IDENTITY_ISSUER
|
|
|| payload.aud !== CLOUD_CONTROL_AUDIENCE
|
|
|| typeof payload.sub !== "string"
|
|
|| typeof payload.action !== "string"
|
|
|| typeof payload.requestId !== "string"
|
|
|| typeof payload.iat !== "number"
|
|
|| !Number.isInteger(payload.iat)
|
|
|| typeof payload.exp !== "number"
|
|
|| !Number.isInteger(payload.exp)
|
|
) {
|
|
throw new Error("Cloud control claims are incomplete");
|
|
}
|
|
if (!configuredStackId || payload.sub !== configuredStackId) {
|
|
throw new Error("Cloud control assertion stack does not match this instance");
|
|
}
|
|
if (
|
|
!(CLOUD_CONTROL_ACTIONS as readonly string[]).includes(payload.action)
|
|
|| payload.action !== input.expectedAction
|
|
) {
|
|
throw new Error("Cloud control assertion does not authorize this action");
|
|
}
|
|
if (
|
|
!payload.requestId
|
|
|| payload.requestId.trim() !== payload.requestId
|
|
|| payload.requestId.length > 256
|
|
) {
|
|
throw new Error("Cloud control assertion request id is invalid");
|
|
}
|
|
if (
|
|
payload.exp <= nowSeconds
|
|
|| payload.iat > nowSeconds + MAX_CLOCK_SKEW_SECONDS
|
|
|| payload.exp <= payload.iat
|
|
|| payload.exp - payload.iat > CLOUD_CONTROL_MAX_LIFETIME_SECONDS
|
|
) {
|
|
throw new Error("Cloud control assertion is expired or has an invalid lifetime");
|
|
}
|
|
if (payload.action === "task-drain:read-body") {
|
|
if (payload.idleCapabilities !== undefined || typeof payload.bodySha256 !== "string" || !/^[a-f0-9]{64}$/.test(payload.bodySha256)
|
|
|| !input.rawBody || input.rawBody.byteLength === 0 || input.rawBody.byteLength > DEFAULT_JSON_BODY_LIMIT_BYTES) {
|
|
throw new Error("Invalid Cloud idle status body binding");
|
|
}
|
|
const raw = Buffer.from(input.rawBody);
|
|
if (createHash("sha256").update(raw).digest("hex") !== payload.bodySha256) throw new Error("Cloud idle status body digest changed");
|
|
const text = new TextDecoder("utf-8", { fatal: true }).decode(raw);
|
|
let body: unknown;
|
|
try { body = JSON.parse(text); }
|
|
catch { throw new Error("Invalid Cloud idle status body JSON"); }
|
|
if (!body || typeof body !== "object" || Array.isArray(body) || Object.keys(body).join() !== "idleCapabilities") {
|
|
throw new Error("Invalid Cloud idle status body");
|
|
}
|
|
payload.idleCapabilities = parseIdleCapabilities(Reflect.get(body, "idleCapabilities"));
|
|
} else {
|
|
if (payload.bodySha256 !== undefined) throw new Error("Cloud body binding requires task-drain:read-body");
|
|
if (payload.idleCapabilities !== undefined) {
|
|
if (payload.action !== "task-drain:read") throw new Error("Idle capabilities require task-drain:read");
|
|
payload.idleCapabilities = parseIdleCapabilities(payload.idleCapabilities);
|
|
}
|
|
}
|
|
// Consumed LAST, only after every other check passed: a rejected
|
|
// assertion must not burn its request id, or an attacker could deny a
|
|
// legitimate call by replaying a mangled copy of it first.
|
|
if (!consumeControlRequestId(payload.requestId, payload.exp + MAX_CLOCK_SKEW_SECONDS, now.getTime())) {
|
|
throw new Error("Cloud control assertion has already been used");
|
|
}
|
|
return payload as CloudControlClaims;
|
|
}
|
|
|
|
export function verifyCloudConnectorReceipt<T extends { binding: { instanceId: string } }>(input: { compactJws: string; env?: NodeJS.ProcessEnv }, parseReceipt: (value: unknown) => T): T {
|
|
const env = input.env ?? process.env;
|
|
if (Buffer.byteLength(input.compactJws, "ascii") > 12_000 || !/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/.test(input.compactJws))
|
|
throw new Error("Invalid connector ACK receipt encoding");
|
|
const [headerPart, payloadPart, signaturePart] = input.compactJws.split(".");
|
|
const header = decodeJsonPart(headerPart, "connector receipt header");
|
|
if (Object.keys(header).sort().join() !== "alg,kid,typ" || header.alg !== "EdDSA"
|
|
|| header.typ !== "paperclip-connector-ack-receipt+jwt" || typeof header.kid !== "string" || !header.kid)
|
|
throw new Error("Invalid connector ACK receipt header");
|
|
const key = cloudRuntimePublicKeyForKid(env, header.kid);
|
|
if (!verify(null, Buffer.from(`${headerPart}.${payloadPart}`, "ascii"), key, Buffer.from(signaturePart, "base64url")))
|
|
throw new Error("Invalid connector ACK receipt signature");
|
|
const claims = decodeJsonPart(payloadPart, "connector receipt claims");
|
|
if (Object.keys(claims).sort().join() !== "aud,iss,receipt,sub,v" || claims.v !== 1 || claims.iss !== CLOUD_RUNTIME_IDENTITY_ISSUER
|
|
|| claims.aud !== "paperclip-connector-ack-receipt/v1" || claims.sub !== nonEmpty(env.PAPERCLIP_CLOUD_STACK_ID))
|
|
throw new Error("Invalid connector ACK receipt claims");
|
|
const receipt = parseReceipt(claims.receipt);
|
|
if (receipt.binding.instanceId !== claims.sub) throw new Error("Connector ACK receipt instance changed");
|
|
return receipt;
|
|
}
|