// cms-sign-worker.mjs
// Signs one immutable CMS text generation with the Encypher API, then verifies
// the signed text it gets back. One job in (JSON on stdin), one result out
// (JSON on stdout).
// exit 0 signed and verified: store the result, then publish
// exit 75 run the same job again after retry_after_seconds
// exit 1 do not retry automatically: read "status" and "code"
//
// Scope: the signing step only. Your CMS still owns the queue, the generation
// compare-and-set, storage and publication. Node.js 18 or later, no packages.
// ENCYPHER_API_KEY required; keep it on the server
// ENCYPHER_API_BASE optional; default https://api.encypher.com/api/v1
import { createHash, randomUUID } from "node:crypto";
const API_BASE = process.env.ENCYPHER_API_BASE || "https://api.encypher.com/api/v1";
const MAX_ATTEMPTS = 3; // tries in this run; longer waits go back to your queue
const MAX_WAIT_SECONDS = 30; // a longer Retry-After is handed back as exit 75
const RETRY_LATER = 75;
const sleep = (seconds) => new Promise((resolve) => setTimeout(resolve, seconds * 1000));
function retryAfterSeconds(response) {
const value = response.headers?.get("retry-after");
if (!value) return null;
const seconds = Number(value);
if (Number.isFinite(seconds)) return Math.max(0, Math.ceil(seconds));
const date = Date.parse(value);
return Number.isNaN(date) ? null : Math.max(0, Math.ceil((date - Date.now()) / 1000));
}
async function post(path, body, headers, timeoutMs) {
const requestId = `cms-${randomUUID()}`; // sent as X-Request-ID; log it
try {
const response = await fetch(API_BASE + path, {
method: "POST",
headers: { "Content-Type": "application/json", Accept: "application/json", "X-Request-ID": requestId, ...headers },
body,
redirect: "error",
signal: AbortSignal.timeout(timeoutMs),
});
// An edge rejection can be HTML, so check the type before parsing.
let json = null;
if ((response.headers.get("content-type") || "").includes("application/json")) {
json = await response.json().catch(() => null);
} else {
await response.text();
}
return { status: response.status, json, headers: response.headers, requestId };
} catch (error) {
// Timeout or network failure. The request may still have succeeded.
return { status: 0, json: null, headers: null, requestId, transport: error.name };
}
}
// "retry": same key, same bytes, later. "blocked": the key, plan, allowance or
// signing certificate needs a person. "rejected": this job is wrong; fix the
// integration, or create a new generation if the content changed.
function classify(response) {
const { status } = response;
const error = response.json?.error || {};
if (status === 0 || status === 408) return "retry";
if (status === 409) return error.code === "SIGNING_IN_PROGRESS" ? "retry" : "rejected";
if (status === 429) return error.error ? "blocked" : "retry"; // error.error names a spent allowance
if (status === 401 || status === 402 || status === 403) return "blocked";
if (status === 503 && error.code === "SIGNING_CERT_UNAVAILABLE") return "blocked";
if (status >= 500) return "retry";
return "rejected"; // 400, 404, 409 conflict, 410 purged, 413, 422
}
function outcome(status, response, extra = {}) {
const error = response.json?.error || {};
return {
status,
http_status: response.status,
code: error.code || response.transport || null,
message: error.message || null,
correlation_id: response.json?.correlation_id || response.headers?.get("x-request-id") || response.requestId,
...extra,
};
}
async function main(job) {
for (const field of ["site_id", "post_id", "generation", "text"]) {
if (typeof job[field] !== "string" || job[field] === "") {
return [1, { status: "rejected", code: "INVALID_JOB", message: `${field} is required` }];
}
}
const previous = job.previous || null;
if (previous ? !(previous.instance_id && previous.signed_text) : !job.digital_source_type) {
const message = "a first generation needs digital_source_type; an edit needs previous.instance_id and previous.signed_text";
return [1, { status: "rejected", code: "INVALID_JOB", message }];
}
const apiKey = process.env.ENCYPHER_API_KEY;
if (!apiKey) return [1, { status: "blocked", code: "MISSING_API_KEY", message: "set ENCYPHER_API_KEY on the server" }];
const base = new URL(API_BASE);
if (base.protocol !== "https:" && !["localhost", "127.0.0.1"].includes(base.hostname)) {
return [1, { status: "blocked", code: "INSECURE_API_BASE", message: "the API key is only sent over https" }];
}
// One generation: one key, one document id, one exact request body. A retry
// sends the same bytes under the same key, so a lost response replays the
// first result instead of signing twice.
const workDigest = createHash("sha256").update([job.site_id, job.post_id].join("\0")).digest("hex");
const digest = createHash("sha256").update([job.site_id, job.post_id, job.generation].join("\0")).digest("hex");
const ids = { generation: job.generation, work_id: `cms_work_${workDigest}`, idempotency_key: `cms-sign-${digest}` };
const provenance = previous
? { action: "c2pa.edited", previous_instance_id: previous.instance_id, previous_signed_content: previous.signed_text }
: { action: "c2pa.created" };
if (job.digital_source_type) provenance.digital_source_type = job.digital_source_type;
const body = JSON.stringify({
text: job.text,
document_id: `cms_${digest.slice(0, 60)}`,
document_title: job.title,
document_url: job.canonical_url,
options: { document_type: "article", work_id: ids.work_id, store_c2pa_manifest: true, ...provenance },
});
const auth = { Authorization: `Bearer ${apiKey}`, "Idempotency-Key": ids.idempotency_key };
let signed;
for (let attempt = 1; ; attempt += 1) {
signed = await post("/sign", body, auth, 30000);
if (signed.status >= 200 && signed.status < 300) break;
const kind = classify(signed);
if (kind !== "retry") return [1, { ...outcome(kind, signed), ...ids }];
const wait = retryAfterSeconds(signed) ?? 2 ** (attempt - 1);
if (attempt >= MAX_ATTEMPTS || wait > MAX_WAIT_SECONDS) {
return [RETRY_LATER, { ...outcome("retry_later", signed), ...ids, retry_after_seconds: Math.max(wait, 1) }];
}
await sleep(wait);
}
const doc = signed.json?.data?.document;
if (signed.json?.success !== true || !doc?.signed_text || !doc.document_id) {
return [1, { ...outcome("rejected", signed, { code: "UNEXPECTED_RESPONSE" }), ...ids }];
}
// Check the exact text you will store. Running this job again after a
// verify failure replays the signature above; it does not sign again.
const check = await post("/public/verify", JSON.stringify({ text: doc.signed_text }), {}, 15000);
if (check.status === 0 || check.status === 429 || check.status >= 500) {
return [RETRY_LATER, { ...outcome("retry_later", check), ...ids, retry_after_seconds: retryAfterSeconds(check) ?? 30 }];
}
if (check.status !== 200 || check.json?.success !== true || check.json?.valid !== true || check.json?.tampered === true) {
const reason = { code: check.json?.reason_code || null, document_id: doc.document_id };
return [1, { ...outcome("verification_failed", check, reason), ...ids }];
}
return [0, {
status: "signed",
...ids,
document_id: doc.document_id, // store the id the API returns
instance_id: doc.instance_id ?? null, // the next edit's previous_instance_id
signed_text: doc.signed_text, // serve this; the next edit's previous_signed_content
verification_url: doc.verification_url,
reused: doc.reused === true,
correlation_id: signed.json?.correlation_id || signed.requestId,
}];
}
let input = "";
process.stdin.setEncoding("utf8");
for await (const chunk of process.stdin) input += chunk;
let job = null;
try {
job = JSON.parse(input);
} catch {
job = null;
}
const [exitCode, result] = job && typeof job === "object"
? await main(job)
: [1, { status: "rejected", code: "INVALID_JOB", message: "stdin must be one JSON object" }];
process.stdout.write(`${JSON.stringify(result)}\n`);
process.exitCode = exitCode;