@diviops/mcp-server 1.5.54 → 1.5.55
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +34 -1
- package/dist/index.js +67 -15
- package/dist/page-content-candidates.d.ts +34 -0
- package/dist/page-content-candidates.js +74 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -8,7 +8,38 @@ The Node.js MCP server inside the DiviOps harness. It gives Claude Code, Codex,
|
|
|
8
8
|
Claude Code <-> MCP Server (stdio) <-> WordPress REST API <-> DiviOps Agent plugin
|
|
9
9
|
```
|
|
10
10
|
|
|
11
|
-
## 1.5.
|
|
11
|
+
## 1.5.55 candidate release note
|
|
12
|
+
|
|
13
|
+
With Free 1.5.27, preset deletion supports real dry-run previews and guarded
|
|
14
|
+
`preset_ids` exact-set apply through `preset_delete_exact_v1`. Review the preview
|
|
15
|
+
and pass its registry checksum on apply; bounded reference checks run again.
|
|
16
|
+
Defaults, references and incomplete evidence refuse even with force. Legacy
|
|
17
|
+
single-ID deletion retains its default-only guard, without reference checks.
|
|
18
|
+
MCP refuses new safety parameters on old or capability-unverified handlers.
|
|
19
|
+
These checks are point-in-time, not a transaction or automatic rollback.
|
|
20
|
+
|
|
21
|
+
Native Code content strings may contain literal pseudo-escapes; shared validation
|
|
22
|
+
and write serialization checks still require valid JSON and block delimiters.
|
|
23
|
+
Free 1.5.27 also fixes uncached reads/readback of valid empty page content.
|
|
24
|
+
|
|
25
|
+
`diviops_page_update_content` can retain a successful reviewed dry-run using
|
|
26
|
+
`retain_content:true`; apply with `content_ref` instead of resending `content`,
|
|
27
|
+
keeping the same target, expected checksum and backup intent. References are
|
|
28
|
+
memory-only, MCP-process-local and one-use, expire five minutes from reservation,
|
|
29
|
+
and are limited to eight candidates, 2 MiB each and 8 MiB total. They are consumed
|
|
30
|
+
before apply checks/dispatch, even on failed or uncertain apply: inspect the
|
|
31
|
+
target and review a new dry-run instead of automatically retrying. Existing write
|
|
32
|
+
checks still run. Retention is not approval, a backup, cross-client isolation or
|
|
33
|
+
a reduction in content sent from MCP to WordPress. Direct-content calls remain.
|
|
34
|
+
|
|
35
|
+
Public builder companion 1.4.8 carries exact-ID deletion and retained-content
|
|
36
|
+
guidance, stable native FAQ wrapper sizing, and source-qualified Divi 5.13.1
|
|
37
|
+
generated guidance. Dependencies and compatibility floors are unchanged.
|
|
38
|
+
This is source preparation only: local source evidence does not qualify these
|
|
39
|
+
packages or establish that staging has the fixes. Package validation, runtime
|
|
40
|
+
adoption and publication require separate authorization.
|
|
41
|
+
|
|
42
|
+
## Previous 1.5.54 candidate release note
|
|
12
43
|
|
|
13
44
|
Adds optional `bounded:true` to `diviops_page_get` for UTF-8-safe raw content
|
|
14
45
|
chunks of at most 4096 bytes, with a full-page checksum and byte-offset
|
|
@@ -528,6 +559,8 @@ Every write tool accepts `dry_run: boolean` (default `false`). When `true`, the
|
|
|
528
559
|
|
|
529
560
|
`meta_wp_cli` and `scf_import` do not accept `dry_run` (raw passthrough / upstream gap respectively). `scf_sync` passes `dry_run` through to upstream `wp scf json sync --dry-run`, so its preview is the upstream plain-text summary rather than a plugin-built `data.plan`. For bulk preview-then-commit flows (preset reassign, preset cleanup), see [safety-patterns.md](../docs/safety-patterns.md).
|
|
530
561
|
|
|
562
|
+
Preset deletion requires `preset_delete_exact_v1` for real dry-run or guarded `preset_ids` (1-200 exact IDs). Preview returns a registry checksum; exact-set apply requires it and rechecks defaults/references across all post content, postmeta and canonical preset definitions. Incomplete evidence refuses, and force cannot bypass exact-set checks. Legacy `preset_id` remains default-guard-only, with its existing force override. MCP never forwards new safety parameters to old or capability-unverified handlers, which could otherwise ignore `dry_run` and delete. See [coverage, limits and nontransactional semantics](../docs/safety-patterns.md#exact-set-preset-deletion).
|
|
563
|
+
|
|
531
564
|
Selected guarded post-content write tools also accept `backup: true`. In apply
|
|
532
565
|
mode the Free plugin stores an option-backed rollback snapshot before writing
|
|
533
566
|
and returns `data.backup` evidence with the snapshot id and status. With
|
package/dist/index.js
CHANGED
|
@@ -14,6 +14,7 @@ import { z } from "zod";
|
|
|
14
14
|
import { WPClient } from "./wp-client.js";
|
|
15
15
|
import { BOUNDED_PAGE_CAPABILITY, boundedPageError, serializeBoundedPageRead } from "./bounded-page-read.js";
|
|
16
16
|
import { requestAuthoringWrite } from "./authoring-shape-integration.js";
|
|
17
|
+
import { PageContentCandidates, PAGE_CANDIDATE_LIMITS, candidateError } from "./page-content-candidates.js";
|
|
17
18
|
import { capabilityUpgradeHint, MissingCapabilityError, observedVersion, proToolGatesSatisfied, } from "./compatibility.js";
|
|
18
19
|
import { missingCapabilityEnvelope, } from "./capability-envelope.js";
|
|
19
20
|
import { ErrorCodes, envelopeMap, recordIdempotent, serializeEnvelope, withCode, wrapResponse, } from "./envelope.js";
|
|
@@ -56,6 +57,7 @@ const wp = new WPClient({
|
|
|
56
57
|
applicationPassword: WP_APP_PASSWORD,
|
|
57
58
|
});
|
|
58
59
|
const authoringWrite = (endpoint, method, body, operation, dryRun) => requestAuthoringWrite(wp, { endpoint, method, body, operation, dryRun });
|
|
60
|
+
const pageContentCandidates = new PageContentCandidates();
|
|
59
61
|
// WP-CLI (optional — Local by Flywheel via WP_PATH, or custom wrapper via WP_CLI_CMD)
|
|
60
62
|
const WP_PATH = process.env.WP_PATH ?? "";
|
|
61
63
|
const WP_CLI_CMD = process.env.WP_CLI_CMD?.trim() ?? "";
|
|
@@ -1284,13 +1286,16 @@ registerPluginTool("diviops_seo_metadata_update", {
|
|
|
1284
1286
|
};
|
|
1285
1287
|
});
|
|
1286
1288
|
registerPluginTool("diviops_page_update_content", {
|
|
1287
|
-
description: "Update the content of a page with Divi block markup. The content should be valid WordPress block markup using divi/* blocks. IMPORTANT: This overwrites the entire page content. Pass expected_checksum from diviops_page_get to refuse stale writes; omission preserves the legacy unconditional-write contract. Returns the standardized envelope { ok, data?, error: { code, message, hint? } }; missing page_id returns 'not_found', edit-permission failures return 'forbidden' (HTTP 403), stale content returns 'page.content_drift' (HTTP 409), and non-string content returns 'invalid_input' with `error.data = { field, received_type }`." +
|
|
1289
|
+
description: "Update the content of a page with Divi block markup. The content should be valid WordPress block markup using divi/* blocks. IMPORTANT: This overwrites the entire page content. Pass expected_checksum from diviops_page_get to refuse stale writes; omission preserves the legacy unconditional-write contract. Optionally set retain_content:true with dry_run:true and expected_checksum to retain a successful candidate in this process for 5 minutes (2 MiB each, 8 references / 8 MiB total). Returns data.content_ref, content_checksum, expires_at alongside the dry-run plan. Apply using content_ref instead of content, repeating the same page_id, expected_checksum and backup intent. References are process-local and single-use, consumed before writer dispatch even on failure; never automatically retry. Restart/expiry requires a new dry-run. Returns the standardized envelope { ok, data?, error: { code, message, hint? } }; missing page_id returns 'not_found', edit-permission failures return 'forbidden' (HTTP 403), stale content returns 'page.content_drift' (HTTP 409), and non-string content returns 'invalid_input' with `error.data = { field, received_type }`." +
|
|
1288
1290
|
DRY_RUN_DESC_SUFFIX,
|
|
1289
1291
|
inputSchema: {
|
|
1290
1292
|
page_id: z.number().describe("WordPress post/page ID to update"),
|
|
1291
1293
|
content: z
|
|
1292
1294
|
.string()
|
|
1295
|
+
.optional()
|
|
1293
1296
|
.describe("Full page content in WordPress block markup format (<!-- wp:divi/section -->...<!-- /wp:divi/section -->)"),
|
|
1297
|
+
content_ref: z.string().optional().describe("Single-use reference from a successful retained dry-run; apply only, mutually exclusive with content."),
|
|
1298
|
+
retain_content: z.boolean().optional().describe("Retain content only on an explicitly confirmed successful dry-run. Requires expected_checksum. content_checksum hashes exact submitted UTF-8 bytes, not normalized persisted bytes. Capacity and the 5-minute TTL begin before the upstream request. MCP-process-local, not isolated per client session."),
|
|
1294
1299
|
expected_checksum: z
|
|
1295
1300
|
.string()
|
|
1296
1301
|
.regex(/^sha256:[a-f0-9]{64}$/)
|
|
@@ -1301,7 +1306,24 @@ registerPluginTool("diviops_page_update_content", {
|
|
|
1301
1306
|
},
|
|
1302
1307
|
annotations: { idempotentHint: false },
|
|
1303
1308
|
_meta: { idempotent: "conditional" },
|
|
1304
|
-
}, async ({ page_id, content, expected_checksum, dry_run, backup }) => {
|
|
1309
|
+
}, async ({ page_id, content, content_ref, retain_content, expected_checksum, dry_run, backup }) => {
|
|
1310
|
+
const reply = (result) => ({ content: [{ type: "text", text: serializeEnvelope(result, "diviops_page_update_content") }] });
|
|
1311
|
+
if ((content === undefined) === (content_ref === undefined) ||
|
|
1312
|
+
(retain_content === true && (dry_run !== true || content === undefined)) ||
|
|
1313
|
+
(content_ref !== undefined && (dry_run === true || retain_content === true)) ||
|
|
1314
|
+
((retain_content === true || content_ref !== undefined) && (expected_checksum === undefined || !Number.isSafeInteger(page_id) || page_id <= 0))) {
|
|
1315
|
+
return reply(candidateError("invalid_input", "Provide exactly one of content or content_ref. Retention requires content, dry_run:true, a positive page_id and expected_checksum; reference apply requires the same page, checksum and backup intent."));
|
|
1316
|
+
}
|
|
1317
|
+
if (retain_content && Buffer.byteLength(content, "utf8") > PAGE_CANDIDATE_LIMITS.candidateBytes) {
|
|
1318
|
+
return reply(candidateError("page.content_ref_capacity", "Retained candidate exceeds the 2 MiB limit."));
|
|
1319
|
+
}
|
|
1320
|
+
const binding = { site: WP_URL, page_id, expected_checksum: expected_checksum, backup: backup === true };
|
|
1321
|
+
if (content_ref !== undefined) {
|
|
1322
|
+
const resolved = pageContentCandidates.consume(content_ref, binding);
|
|
1323
|
+
if (!resolved.ok)
|
|
1324
|
+
return reply(resolved);
|
|
1325
|
+
content = resolved.data;
|
|
1326
|
+
}
|
|
1305
1327
|
const backupGate = backupCapabilityError("diviops_page_update_content", backup);
|
|
1306
1328
|
if (backupGate)
|
|
1307
1329
|
return backupGate;
|
|
@@ -1318,12 +1340,27 @@ registerPluginTool("diviops_page_update_content", {
|
|
|
1318
1340
|
body.dry_run = true;
|
|
1319
1341
|
if (backup)
|
|
1320
1342
|
body.backup = true;
|
|
1321
|
-
const
|
|
1322
|
-
|
|
1323
|
-
|
|
1324
|
-
|
|
1325
|
-
|
|
1326
|
-
|
|
1343
|
+
const reservation = retain_content ? pageContentCandidates.reserve(binding, content) : undefined;
|
|
1344
|
+
if (reservation && !reservation.ok)
|
|
1345
|
+
return reply(reservation);
|
|
1346
|
+
try {
|
|
1347
|
+
const result = await authoringWrite(`/page/update-content/${page_id}`, "POST", body, "page_update_content", dry_run === true);
|
|
1348
|
+
if (reservation?.ok && result.ok) {
|
|
1349
|
+
const data = result.data;
|
|
1350
|
+
if (!data || typeof data !== "object" || !("dry_run" in data) || data.dry_run !== true) {
|
|
1351
|
+
return reply(candidateError("page.content_ref_unconfirmed", "Writer did not confirm a successful dry-run; no candidate retained."));
|
|
1352
|
+
}
|
|
1353
|
+
if (!pageContentCandidates.confirm(reservation.data.content_ref)) {
|
|
1354
|
+
return reply(candidateError("page.content_ref_invalid", "Candidate expired during dry-run; run a new retained dry-run."));
|
|
1355
|
+
}
|
|
1356
|
+
return reply({ ok: true, data: { ...data, ...reservation.data } });
|
|
1357
|
+
}
|
|
1358
|
+
return reply(result);
|
|
1359
|
+
}
|
|
1360
|
+
finally {
|
|
1361
|
+
if (reservation?.ok)
|
|
1362
|
+
pageContentCandidates.cancel(reservation.data.content_ref);
|
|
1363
|
+
}
|
|
1327
1364
|
});
|
|
1328
1365
|
registerPluginTool("diviops_page_update_meta", {
|
|
1329
1366
|
description: "Update page/post metadata fields without touching post_content. Supports title, slug, parent, and menu_order; use diviops_page_update_status for status changes. Slug input must already be in sanitized WordPress post_name form. When a published post's slug changes, preserve_old_slug defaults to true and records the previous slug in _wp_old_slug so WordPress old-slug redirects can work. Returns readback fields after apply. Returns the standardized envelope { ok, data?, error: { code, message, hint? } }; missing page_id or invalid parent returns 'not_found', edit-permission failures return 'forbidden' (HTTP 403), invalid/empty slug or malformed field values return 'invalid_input' with `error.data` documenting the field and sanitized slug where relevant." +
|
|
@@ -1424,7 +1461,7 @@ registerPluginTool("diviops_render_preview", {
|
|
|
1424
1461
|
};
|
|
1425
1462
|
});
|
|
1426
1463
|
registerPluginTool("diviops_validate_blocks", {
|
|
1427
|
-
description: "Validate Divi block markup before saving. Accepts EITHER inline `content` (string of block markup) OR `page_id` (loads `post_content` from the DB, requires edit_post capability on the page — useful for regression checks on shipped pages without round-tripping the markup blob). Provide exactly one. Checks structure (malformed comments, unknown blocks, missing builderVersion), required attributes (layout display on containers), and known pitfalls (button padding path, icon.enable, gradient enabled/positions). Returns the standardized envelope { ok, data?, error: { code, message, hint? } }; success payload is { valid: bool, total_blocks: number, errors: Finding[], warnings: Finding[] } where each Finding is { block, index, code, message, path? }. Note: shape errors detected in the markup surface as success-branch `data.errors[]` entries (NOT `validation_failed` envelopes) — the findings array is the payload, not an error. The envelope's error branch fires only for tool-level failures (`invalid_input` for neither/both supplied or invalid page_id; `forbidden` for missing edit_post; `not_found` for unknown page_id; `divi_error` for an exception in the walker).",
|
|
1464
|
+
description: "Validate Divi block markup before saving. Accepts EITHER inline `content` (string of block markup) OR `page_id` (loads `post_content` from the DB, requires edit_post capability on the page — useful for regression checks on shipped pages without round-tripping the markup blob). Provide exactly one. Checks shared write serialization and marker integrity (literal pseudo-escapes are allowed in native Code content strings), structure (malformed comments, unknown blocks, missing builderVersion), required attributes (layout display on containers), and known pitfalls (button padding path, icon.enable, gradient enabled/positions). Returns the standardized envelope { ok, data?, error: { code, message, hint? } }; success payload is { valid: bool, total_blocks: number, errors: Finding[], warnings: Finding[] } where each Finding is { block, index, code, message, path? }. Serialization failures return valid:false with invalid_serialization findings and total_blocks:0 because the tree was not walked. Note: shape errors detected in the markup surface as success-branch `data.errors[]` entries (NOT `validation_failed` envelopes) — the findings array is the payload, not an error. The envelope's error branch fires only for tool-level failures (`invalid_input` for neither/both supplied or invalid page_id; `forbidden` for missing edit_post; `not_found` for unknown page_id; `divi_error` for an exception in the walker).",
|
|
1428
1465
|
inputSchema: {
|
|
1429
1466
|
content: z
|
|
1430
1467
|
.string()
|
|
@@ -2227,20 +2264,35 @@ registerPluginTool("diviops_preset_update", {
|
|
|
2227
2264
|
};
|
|
2228
2265
|
});
|
|
2229
2266
|
registerPluginTool("diviops_preset_delete", {
|
|
2230
|
-
description: "Delete
|
|
2267
|
+
description: "Delete presets by exact ID. Legacy preset_id mode checks only the bucket default, NOT references; force=true deletes a default and clears its pointer. Additive preset_ids mode accepts 1-200 unique IDs, refuses defaults, references, unknown/ambiguous IDs, stale registry and incomplete evidence; force cannot bypass these checks. Preview with dry_run:true returns an exact plan and registry_checksum; apply requires expected_registry_checksum and rescans references. Scans all post_content (including revisions/Theme Builder), postmeta, canonical preset definitions/default pointers; conservative matches refuse. Evidence limits: 10000 rows per table, 64 MiB post evidence, nesting 64; unsupported/malformed evidence refuses. Only selected records are removed, in one registry write. No content edits, normalization, transactional guarantee or automatic rollback. Keep other writers idle. Real dry_run in either mode and all exact-set calls require preset_delete_exact_v1; older/unknown plugin capability refuses before dispatch. Returns the standardized envelope; exact-set conflicts carry error.data.reason. Legacy missing IDs return not_found.",
|
|
2231
2268
|
inputSchema: {
|
|
2232
|
-
preset_id: z.string().describe("
|
|
2269
|
+
preset_id: z.string().min(1).optional().describe("Legacy single ID; mutually exclusive with preset_ids. No reference safeguard."),
|
|
2270
|
+
preset_ids: z.array(z.string().regex(/^[A-Za-z0-9_-]{1,128}$/)).min(1).max(200).optional().describe("Exact guarded selection, never name/duplicate heuristics."),
|
|
2271
|
+
dry_run: z.boolean().optional().describe("True previews with zero writes; false/omitted applies. Capability-gated in both modes."),
|
|
2272
|
+
expected_registry_checksum: z.string().regex(/^sha256:[a-f0-9]{64}$/).optional().describe("Exact preview registry_checksum, required for preset_ids apply only."),
|
|
2233
2273
|
force: z
|
|
2234
2274
|
.boolean()
|
|
2235
2275
|
.optional()
|
|
2236
|
-
.describe("
|
|
2276
|
+
.describe("Legacy preset_id only: delete a default and clear its pointer. Ignored in exact-set mode; never bypasses its safeguards."),
|
|
2237
2277
|
},
|
|
2238
2278
|
annotations: { idempotentHint: true },
|
|
2239
2279
|
_meta: { idempotent: "true" },
|
|
2240
|
-
}, async ({ preset_id, force }) => {
|
|
2241
|
-
const
|
|
2280
|
+
}, async ({ preset_id, preset_ids, force, dry_run, expected_registry_checksum }) => {
|
|
2281
|
+
const exact = preset_ids !== undefined;
|
|
2282
|
+
if ((preset_id !== undefined) === exact || (exact && (new Set(preset_ids).size !== preset_ids.length || (!dry_run && expected_registry_checksum === undefined))) || (!exact && expected_registry_checksum !== undefined)) {
|
|
2283
|
+
return { content: [{ type: "text", text: serializeEnvelope({ ok: false, error: { code: "invalid_input", message: "Supply preset_id OR 1-200 unique preset_ids; exact-set apply requires expected_registry_checksum from preview." } }, "diviops_preset_delete") }] };
|
|
2284
|
+
}
|
|
2285
|
+
// Never let an old handler silently ignore preview/exact-set parameters and delete.
|
|
2286
|
+
if ((exact || dry_run !== undefined || expected_registry_checksum !== undefined) && (handshakeState.kind !== "ok" || handshakeState.capabilities.preset_delete_exact_v1 !== true)) {
|
|
2287
|
+
return missingCapabilityEnvelope(new MissingCapabilityError("preset_delete_exact_v1", handshakeState.kind === "ok" ? handshakeState.pluginVersion : undefined), "diviops_preset_delete", { serverVersion: SERVER_VERSION });
|
|
2288
|
+
}
|
|
2289
|
+
const body = exact ? { preset_ids } : { preset_id };
|
|
2242
2290
|
if (force !== undefined)
|
|
2243
2291
|
body.force = force;
|
|
2292
|
+
if (dry_run !== undefined)
|
|
2293
|
+
body.dry_run = dry_run;
|
|
2294
|
+
if (expected_registry_checksum !== undefined)
|
|
2295
|
+
body.expected_registry_checksum = expected_registry_checksum;
|
|
2244
2296
|
const result = await wp.requestEnveloped("/preset/delete", {
|
|
2245
2297
|
method: "POST",
|
|
2246
2298
|
body,
|
|
@@ -2714,7 +2766,7 @@ registerPluginTool("diviops_tb_layout_update", {
|
|
|
2714
2766
|
};
|
|
2715
2767
|
});
|
|
2716
2768
|
registerPluginTool("diviops_tb_layout_block_insert", {
|
|
2717
|
-
description: "Insert one or more serialized Divi blocks into an existing Theme Builder layout without replacing the whole layout. Target a unique parent with `parent_selector` (for example `divi/group[adminLabel=\"Legal Col\"]`, or `divi/group` only when it is unique) or an explicit zero-based `parent_path` from the parsed block tree such as `0.1.2`. `position=append|prepend` inserts as children of the target block; `position=before|after` inserts beside the target within its parent. Ambiguous selectors return ok:false with code 'invalid_input'; missing targets return 'not_found'. The route parses and validates the inserted blocks, rejects malformed pseudo-escapes such as bare `u003c
|
|
2769
|
+
description: "Insert one or more serialized Divi blocks into an existing Theme Builder layout without replacing the whole layout. Target a unique parent with `parent_selector` (for example `divi/group[adminLabel=\"Legal Col\"]`, or `divi/group` only when it is unique) or an explicit zero-based `parent_path` from the parsed block tree such as `0.1.2`. `position=append|prepend` inserts as children of the target block; `position=before|after` inserts beside the target within its parent. Ambiguous selectors return ok:false with code 'invalid_input'; missing targets return 'not_found'. The route parses and validates the inserted blocks, rejects malformed serialization (literal pseudo-escapes such as bare `u003c` are allowed in native Code content strings), validates the final serialized layout before saving, and returns a no-op when the exact requested block sequence already exists at the insertion point." +
|
|
2718
2770
|
DRY_RUN_DESC_SUFFIX,
|
|
2719
2771
|
inputSchema: {
|
|
2720
2772
|
layout_id: z.number().int().describe("Theme Builder layout post ID to mutate"),
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import type { DiviopsResponse } from "./envelope.js";
|
|
2
|
+
export declare const PAGE_CANDIDATE_LIMITS: Readonly<{
|
|
3
|
+
ttlMs: 300000;
|
|
4
|
+
count: 8;
|
|
5
|
+
candidateBytes: number;
|
|
6
|
+
totalBytes: number;
|
|
7
|
+
}>;
|
|
8
|
+
type Binding = {
|
|
9
|
+
site: string;
|
|
10
|
+
page_id: number;
|
|
11
|
+
expected_checksum: string;
|
|
12
|
+
backup: boolean;
|
|
13
|
+
};
|
|
14
|
+
export declare const candidateError: (code: string, message: string) => DiviopsResponse<never>;
|
|
15
|
+
/** Memory-only, process-local, single-use references. No payload is written to disk. */
|
|
16
|
+
export declare class PageContentCandidates {
|
|
17
|
+
private readonly now;
|
|
18
|
+
private entries;
|
|
19
|
+
private bytes;
|
|
20
|
+
private timer?;
|
|
21
|
+
constructor(now?: () => number);
|
|
22
|
+
private prune;
|
|
23
|
+
private remove;
|
|
24
|
+
private schedule;
|
|
25
|
+
reserve(binding: Binding, content: string): DiviopsResponse<{
|
|
26
|
+
content_ref: string;
|
|
27
|
+
content_checksum: string;
|
|
28
|
+
expires_at: string;
|
|
29
|
+
}>;
|
|
30
|
+
confirm(ref: string): boolean;
|
|
31
|
+
cancel(ref: string): void;
|
|
32
|
+
consume(ref: string, binding: Binding): DiviopsResponse<string>;
|
|
33
|
+
}
|
|
34
|
+
export {};
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
2
|
+
export const PAGE_CANDIDATE_LIMITS = Object.freeze({ ttlMs: 300_000, count: 8, candidateBytes: 2 * 1024 * 1024, totalBytes: 8 * 1024 * 1024 });
|
|
3
|
+
export const candidateError = (code, message) => ({ ok: false, error: { code, message } });
|
|
4
|
+
const checksum = (content) => `sha256:${createHash("sha256").update(content, "utf8").digest("hex")}`;
|
|
5
|
+
/** Memory-only, process-local, single-use references. No payload is written to disk. */
|
|
6
|
+
export class PageContentCandidates {
|
|
7
|
+
now;
|
|
8
|
+
entries = new Map();
|
|
9
|
+
bytes = 0;
|
|
10
|
+
timer;
|
|
11
|
+
constructor(now = Date.now) {
|
|
12
|
+
this.now = now;
|
|
13
|
+
}
|
|
14
|
+
prune() {
|
|
15
|
+
for (const [ref, entry] of this.entries) {
|
|
16
|
+
if (entry.expires <= this.now())
|
|
17
|
+
this.remove(ref, entry);
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
remove(ref, entry) {
|
|
21
|
+
this.entries.delete(ref);
|
|
22
|
+
this.bytes -= entry.bytes;
|
|
23
|
+
}
|
|
24
|
+
schedule() {
|
|
25
|
+
if (this.timer)
|
|
26
|
+
clearTimeout(this.timer);
|
|
27
|
+
this.timer = undefined;
|
|
28
|
+
if (!this.entries.size)
|
|
29
|
+
return;
|
|
30
|
+
const expires = Math.min(...Array.from(this.entries.values(), e => e.expires));
|
|
31
|
+
this.timer = setTimeout(() => { this.prune(); this.schedule(); }, Math.max(1, expires - this.now()));
|
|
32
|
+
this.timer.unref();
|
|
33
|
+
}
|
|
34
|
+
reserve(binding, content) {
|
|
35
|
+
this.prune();
|
|
36
|
+
const bytes = Buffer.byteLength(content, "utf8");
|
|
37
|
+
if (bytes > PAGE_CANDIDATE_LIMITS.candidateBytes || this.entries.size >= PAGE_CANDIDATE_LIMITS.count || this.bytes + bytes > PAGE_CANDIDATE_LIMITS.totalBytes) {
|
|
38
|
+
return candidateError("page.content_ref_capacity", "Candidate retention capacity exceeded; resend content after capacity becomes available.");
|
|
39
|
+
}
|
|
40
|
+
const ref = `pcr_${randomBytes(32).toString("hex")}`;
|
|
41
|
+
const entry = { ...binding, content, content_checksum: checksum(content), bytes, expires: this.now() + PAGE_CANDIDATE_LIMITS.ttlMs, ready: false };
|
|
42
|
+
this.entries.set(ref, entry);
|
|
43
|
+
this.bytes += bytes;
|
|
44
|
+
this.schedule();
|
|
45
|
+
return { ok: true, data: { content_ref: ref, content_checksum: entry.content_checksum, expires_at: new Date(entry.expires).toISOString() } };
|
|
46
|
+
}
|
|
47
|
+
confirm(ref) {
|
|
48
|
+
this.prune();
|
|
49
|
+
const entry = this.entries.get(ref);
|
|
50
|
+
if (!entry)
|
|
51
|
+
return false;
|
|
52
|
+
entry.ready = true;
|
|
53
|
+
return true;
|
|
54
|
+
}
|
|
55
|
+
cancel(ref) {
|
|
56
|
+
const entry = this.entries.get(ref);
|
|
57
|
+
if (entry && !entry.ready)
|
|
58
|
+
this.remove(ref, entry);
|
|
59
|
+
this.schedule();
|
|
60
|
+
}
|
|
61
|
+
consume(ref, binding) {
|
|
62
|
+
this.prune();
|
|
63
|
+
const entry = this.entries.get(ref);
|
|
64
|
+
if (!entry || !entry.ready)
|
|
65
|
+
return candidateError("page.content_ref_invalid", "Unknown, expired, or consumed content_ref. Run a new retained dry-run.");
|
|
66
|
+
if (entry.site !== binding.site || entry.page_id !== binding.page_id || entry.expected_checksum !== binding.expected_checksum || entry.backup !== binding.backup || checksum(entry.content) !== entry.content_checksum) {
|
|
67
|
+
return candidateError("page.content_ref_mismatch", "content_ref does not match the site, page, reviewed checksum, or backup intent.");
|
|
68
|
+
}
|
|
69
|
+
// Synchronous removal precedes every asynchronous writer dispatch, including failures.
|
|
70
|
+
this.remove(ref, entry);
|
|
71
|
+
this.schedule();
|
|
72
|
+
return { ok: true, data: entry.content };
|
|
73
|
+
}
|
|
74
|
+
}
|