@manifest-network/manifest-agent-core 0.9.0
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 +39 -0
- package/dist/close-lease.d.ts +33 -0
- package/dist/close-lease.d.ts.map +1 -0
- package/dist/close-lease.js +138 -0
- package/dist/close-lease.js.map +1 -0
- package/dist/deploy-app.d.ts +24 -0
- package/dist/deploy-app.d.ts.map +1 -0
- package/dist/deploy-app.js +446 -0
- package/dist/deploy-app.js.map +1 -0
- package/dist/index.d.ts +8 -0
- package/dist/index.js +7 -0
- package/dist/internals/classify-deploy-error.d.ts +41 -0
- package/dist/internals/classify-deploy-error.d.ts.map +1 -0
- package/dist/internals/classify-deploy-error.js +79 -0
- package/dist/internals/classify-deploy-error.js.map +1 -0
- package/dist/internals/classify-deploy-response.d.ts +56 -0
- package/dist/internals/classify-deploy-response.d.ts.map +1 -0
- package/dist/internals/classify-deploy-response.js +33 -0
- package/dist/internals/classify-deploy-response.js.map +1 -0
- package/dist/internals/connection.d.ts +76 -0
- package/dist/internals/connection.d.ts.map +1 -0
- package/dist/internals/connection.js +94 -0
- package/dist/internals/connection.js.map +1 -0
- package/dist/internals/evaluate-readiness.d.ts +55 -0
- package/dist/internals/evaluate-readiness.d.ts.map +1 -0
- package/dist/internals/evaluate-readiness.js +131 -0
- package/dist/internals/evaluate-readiness.js.map +1 -0
- package/dist/internals/find-sku-uuid.d.ts +40 -0
- package/dist/internals/find-sku-uuid.d.ts.map +1 -0
- package/dist/internals/find-sku-uuid.js +20 -0
- package/dist/internals/find-sku-uuid.js.map +1 -0
- package/dist/internals/format-success.d.ts +35 -0
- package/dist/internals/format-success.d.ts.map +1 -0
- package/dist/internals/format-success.js +80 -0
- package/dist/internals/format-success.js.map +1 -0
- package/dist/internals/guarded-fetch.d.ts +138 -0
- package/dist/internals/guarded-fetch.d.ts.map +1 -0
- package/dist/internals/guarded-fetch.js +242 -0
- package/dist/internals/guarded-fetch.js.map +1 -0
- package/dist/internals/humanize-denom.d.ts +45 -0
- package/dist/internals/humanize-denom.d.ts.map +1 -0
- package/dist/internals/humanize-denom.js +105 -0
- package/dist/internals/humanize-denom.js.map +1 -0
- package/dist/internals/inspect-image.d.ts +31 -0
- package/dist/internals/inspect-image.d.ts.map +1 -0
- package/dist/internals/inspect-image.js +345 -0
- package/dist/internals/inspect-image.js.map +1 -0
- package/dist/internals/lease-items.d.ts +46 -0
- package/dist/internals/lease-items.d.ts.map +1 -0
- package/dist/internals/lease-items.js +58 -0
- package/dist/internals/lease-items.js.map +1 -0
- package/dist/internals/lease-state.d.ts +32 -0
- package/dist/internals/lease-state.d.ts.map +1 -0
- package/dist/internals/lease-state.js +80 -0
- package/dist/internals/lease-state.js.map +1 -0
- package/dist/internals/render-deployment-plan.d.ts +22 -0
- package/dist/internals/render-deployment-plan.d.ts.map +1 -0
- package/dist/internals/render-deployment-plan.js +135 -0
- package/dist/internals/render-deployment-plan.js.map +1 -0
- package/dist/internals/render-intent-recap.d.ts +43 -0
- package/dist/internals/render-intent-recap.d.ts.map +1 -0
- package/dist/internals/render-intent-recap.js +136 -0
- package/dist/internals/render-intent-recap.js.map +1 -0
- package/dist/internals/render-partial-success-prompt.d.ts +26 -0
- package/dist/internals/render-partial-success-prompt.d.ts.map +1 -0
- package/dist/internals/render-partial-success-prompt.js +53 -0
- package/dist/internals/render-partial-success-prompt.js.map +1 -0
- package/dist/internals/save-manifest.d.ts +105 -0
- package/dist/internals/save-manifest.d.ts.map +1 -0
- package/dist/internals/save-manifest.js +122 -0
- package/dist/internals/save-manifest.js.map +1 -0
- package/dist/internals/secret-denylist.d.ts +42 -0
- package/dist/internals/secret-denylist.d.ts.map +1 -0
- package/dist/internals/secret-denylist.js +59 -0
- package/dist/internals/secret-denylist.js.map +1 -0
- package/dist/internals/spec-normalize.d.ts +84 -0
- package/dist/internals/spec-normalize.d.ts.map +1 -0
- package/dist/internals/spec-normalize.js +169 -0
- package/dist/internals/spec-normalize.js.map +1 -0
- package/dist/internals/verify-domain-state.d.ts +20 -0
- package/dist/internals/verify-domain-state.d.ts.map +1 -0
- package/dist/internals/verify-domain-state.js +63 -0
- package/dist/internals/verify-domain-state.js.map +1 -0
- package/dist/internals/verify-recover.d.ts +120 -0
- package/dist/internals/verify-recover.d.ts.map +1 -0
- package/dist/internals/verify-recover.js +91 -0
- package/dist/internals/verify-recover.js.map +1 -0
- package/dist/manage-domain.d.ts +36 -0
- package/dist/manage-domain.d.ts.map +1 -0
- package/dist/manage-domain.js +230 -0
- package/dist/manage-domain.js.map +1 -0
- package/dist/troubleshoot.d.ts +23 -0
- package/dist/troubleshoot.d.ts.map +1 -0
- package/dist/troubleshoot.js +124 -0
- package/dist/troubleshoot.js.map +1 -0
- package/dist/types.d.ts +294 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +0 -0
- package/package.json +56 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"render-intent-recap.js","names":[],"sources":["../../src/internals/render-intent-recap.ts"],"sourcesContent":["import type {\n DeploySpec,\n ServiceDef,\n SingleServiceSpec,\n StackSpec,\n} from '../types.js';\nimport { isStackSpec, normalizeServices } from './spec-normalize.js';\n\n/**\n * Render the structural portion of the intent-recap block shown to the user\n * before any chain round-trips in the deploy-app orchestrator.\n *\n * The 4 deterministic items the recap covers:\n *\n * 1. Deployment surface (service count + per-service `name — image`)\n * 2. Connectivity (per-port ingress posture)\n * 3. Redacted sensitive-key inventory (env / label keys only; never values)\n * 4. Custom-domain + dual-tx clarifier + mainnet warning (when applicable)\n *\n * The 2 LLM-judgment items (\"what you provided vs auto-detected\", \"heads-up:\n * obvious gaps\") stay in prose — the orchestrator appends them between the\n * deterministic block and the `AskUserQuestion` prompt.\n *\n * **Sensitive-value posture:** env values and label values are NEVER\n * surfaced; only keys appear. Mirrors `summarizeSpec`'s contract. FQDNs are\n * not secrets so `customDomain` is surfaced verbatim.\n *\n * **Port-shape handling:** the CJS supports two runtime shapes for ports:\n * - Legacy single-service: `port: number` → renders one ingress=true entry.\n * - Services-map: `ports: Record<portKey, { ingress?: boolean }>` → one\n * entry per port-key with the declared ingress flag (default false).\n *\n * The frozen TS contract narrows `ServiceDef.ports` to `number[]` for the\n * common case; this port also handles the historical Record shape at runtime\n * (matching `summarizeSpec`'s defensive widening) so callers passing\n * unknown-typed input from JSON.parse don't silently drop ports.\n */\n\n/** Render output is a multi-paragraph plain-text block, ready to print verbatim. */\nexport interface RenderIntentRecapInput {\n /** The structured deploy spec (frozen `DeploySpec` shape). */\n spec: DeploySpec;\n /** Active chain — drives the mainnet permanence warning. */\n activeChain: 'testnet' | 'mainnet';\n}\n\ninterface NormalizedService {\n /** `null` for legacy single-service; the services-map key for stack leases. */\n name: string | null;\n /** Image string. Falls back to `(unknown image)` when missing. */\n image: string;\n /** Per-port ingress posture, in declaration order. */\n ports: { port: string; ingress: boolean }[];\n /** Sorted env keys (values redacted). */\n envKeys: string[];\n /** Sorted label keys (values redacted). */\n labelKeys: string[];\n}\n\nexport function renderIntentRecap(input: RenderIntentRecapInput): string {\n if (input.activeChain !== 'testnet' && input.activeChain !== 'mainnet') {\n throw new TypeError(\n `renderIntentRecap: activeChain must be \"testnet\" or \"mainnet\"; got \"${String(input.activeChain)}\"`,\n );\n }\n\n const services = projectServices(input.spec);\n\n const blocks: string[] = [\n renderServiceList(services, input.activeChain),\n renderConnectivity(services),\n renderRedactedInventory(services),\n ];\n const domainBlock = renderCustomDomain(input.spec, input.activeChain);\n if (domainBlock !== null) {\n blocks.push(domainBlock);\n }\n\n return blocks.join('\\n\\n');\n}\n\nfunction projectServices(spec: DeploySpec): NormalizedService[] {\n return normalizeServices(spec).map(({ name, raw }): NormalizedService => {\n const rawRecord = raw as unknown as Record<string, unknown>;\n const image =\n typeof rawRecord.image === 'string' && rawRecord.image.length > 0\n ? rawRecord.image\n : '(unknown image)';\n const ports =\n name === null\n ? extractPortsLegacy((raw as SingleServiceSpec).port)\n : extractPorts((raw as ServiceDef).ports);\n return {\n name,\n image,\n ports,\n envKeys: extractKeys(rawRecord.env),\n labelKeys: extractKeys(rawRecord.labels),\n };\n });\n}\n\n/**\n * Services-map shape: `{ \"80\": { ingress?: boolean }, \"9090\": { ... } }`.\n * Ingress flag may be absent — default `false` matches Fred's cluster-private\n * default. Also handles the typed `number[]` shape (frozen `ServiceDef.ports`)\n * by treating each entry as ingress=false (services-map default).\n */\nfunction extractPorts(ports: unknown): { port: string; ingress: boolean }[] {\n if (Array.isArray(ports)) {\n return ports\n .filter((p): p is number => typeof p === 'number')\n .map((p) => ({ port: String(p), ingress: false }));\n }\n if (ports !== null && typeof ports === 'object') {\n return Object.entries(ports as Record<string, unknown>).map(\n ([port, cfg]) => ({\n port,\n ingress: !!(\n cfg !== null &&\n typeof cfg === 'object' &&\n (cfg as { ingress?: unknown }).ingress\n ),\n }),\n );\n }\n return [];\n}\n\n/**\n * Legacy single-service shape: bare `port: number`. Fred treats this as\n * ingress=true by default — that's the whole point of the simplified\n * shape.\n *\n * Also handles the `number[]` form (the frozen-contract array form):\n * returns one `{ port, ingress: true }` entry per array element, each\n * with `ingress: true` matching the single-service convention. Returns\n * `[]` for any other value (undefined, non-number scalar, non-array\n * object).\n *\n * M2 fix: prior JSDoc incorrectly stated \"Returns `[]` for any other\n * value (including `number[]`...)\" — empirically wrong per the\n * `Array.isArray(port)` branch below.\n */\nfunction extractPortsLegacy(\n port: number | number[] | undefined,\n): { port: string; ingress: boolean }[] {\n if (typeof port === 'number') {\n return [{ port: String(port), ingress: true }];\n }\n if (Array.isArray(port)) {\n return port\n .filter((p): p is number => typeof p === 'number')\n .map((p) => ({ port: String(p), ingress: true }));\n }\n return [];\n}\n\nfunction extractKeys(obj: unknown): string[] {\n if (obj === null || typeof obj !== 'object' || Array.isArray(obj)) return [];\n return Object.keys(obj as Record<string, unknown>).sort();\n}\n\nfunction renderServiceList(\n services: NormalizedService[],\n activeChain: 'testnet' | 'mainnet',\n): string {\n const count = services.length;\n const noun = count === 1 ? 'service' : 'services';\n const lines = [`Deploying ${count} ${noun} on ${activeChain}:`];\n for (const svc of services) {\n const prefix = svc.name === null ? '' : `${svc.name} — `;\n lines.push(` - ${prefix}${svc.image}`);\n }\n return lines.join('\\n');\n}\n\nfunction renderConnectivity(services: NormalizedService[]): string {\n const lines = ['Connectivity:'];\n let total = 0;\n for (const svc of services) {\n if (svc.ports.length === 0) continue;\n for (const p of svc.ports) {\n total += 1;\n const prefix =\n svc.name === null ? `port ${p.port}` : `${svc.name} port ${p.port}`;\n const reach = p.ingress\n ? \"publicly reachable via the provider's HTTPS subdomain\"\n : 'internal only (cluster-private)';\n lines.push(` - ${prefix}: ${reach}`);\n }\n }\n if (total === 0) {\n lines.push(\n ' (no ports declared — the deployment will not expose any network surface)',\n );\n }\n return lines.join('\\n');\n}\n\nfunction renderRedactedInventory(services: NormalizedService[]): string {\n // Always render the section header even if everything is empty — the user\n // should know we'd have shown values if there were any. This is also\n // documentation of the redaction discipline.\n const lines = [\n 'Sensitive values are redacted in this recap (keys only, never values):',\n ];\n let anything = false;\n for (const svc of services) {\n const prefix = svc.name === null ? 'this service' : svc.name;\n const parts: string[] = [];\n if (svc.envKeys.length > 0) {\n anything = true;\n parts.push(`env keys [${svc.envKeys.join(', ')}]`);\n }\n if (svc.labelKeys.length > 0) {\n anything = true;\n parts.push(`label keys [${svc.labelKeys.join(', ')}]`);\n }\n if (parts.length === 0) {\n lines.push(` - ${prefix}: no env or labels supplied`);\n } else {\n lines.push(` - ${prefix}: ${parts.join('; ')}`);\n }\n }\n if (!anything) {\n lines.push(\n ' - (no env or labels supplied across any service — nothing to redact)',\n );\n }\n return lines.join('\\n');\n}\n\nfunction renderCustomDomain(\n spec: DeploySpec,\n activeChain: 'testnet' | 'mainnet',\n): string | null {\n const customDomain = (spec as { customDomain?: unknown }).customDomain;\n if (typeof customDomain !== 'string' || customDomain.length === 0) {\n return null;\n }\n // `serviceName` is only legal on StackSpec; for SingleServiceSpec the\n // single service implicitly receives the domain.\n const serviceName = isStackSpec(spec)\n ? (spec as StackSpec).serviceName\n : undefined;\n const target =\n typeof serviceName === 'string' && serviceName.length > 0\n ? `service ${serviceName}`\n : 'single-service lease';\n const lines = [`Custom domain: ${customDomain} → ${target}`];\n lines.push('');\n lines.push(\n 'Note: when a custom domain is set, deploy_app broadcasts TWO billing\\n' +\n 'transactions atomically: create-lease AND set-item-custom-domain. The\\n' +\n 'single permission prompt that fires later covers BOTH; this textual\\n' +\n 'recap is your per-tx review.',\n );\n if (activeChain === 'mainnet') {\n lines.push('');\n lines.push(\n `Mainnet warning: this transaction permanently associates ${customDomain}\\n` +\n 'with this lease on-chain until you --clear it via\\n' +\n '/manifest-agent:manage-domain or close the lease. FQDN squatting is\\n' +\n 'irreversible.',\n );\n }\n return lines.join('\\n');\n}\n"],"mappings":"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"}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { RecoveryOptionId } from "../types.js";
|
|
2
|
+
|
|
3
|
+
//#region src/internals/render-partial-success-prompt.d.ts
|
|
4
|
+
interface RenderPartialSuccessPromptInput {
|
|
5
|
+
/** The lease UUID created on-chain (validated RFC 4122). */
|
|
6
|
+
leaseUuid: string;
|
|
7
|
+
/** Canonical lease state name (e.g. `LEASE_STATE_PENDING`) — pre-decoded. */
|
|
8
|
+
decodedState: string;
|
|
9
|
+
/** Failure reason from the MCP error envelope or `classifyDeployError`. */
|
|
10
|
+
reason: string;
|
|
11
|
+
/** Optional: FQDN the user requested. Presence drives wording + retry option. */
|
|
12
|
+
requestedCustomDomain?: string;
|
|
13
|
+
}
|
|
14
|
+
interface PartialSuccessPrompt {
|
|
15
|
+
/** Multi-line prompt body to pass to AskUserQuestion. */
|
|
16
|
+
prompt: string;
|
|
17
|
+
/**
|
|
18
|
+
* Recovery options offered to the user. `retry_set_domain` is omitted
|
|
19
|
+
* when no domain was requested. Order matches the CJS's option list.
|
|
20
|
+
*/
|
|
21
|
+
options: RecoveryOptionId[];
|
|
22
|
+
}
|
|
23
|
+
declare function renderPartialSuccessPrompt(input: RenderPartialSuccessPromptInput): PartialSuccessPrompt;
|
|
24
|
+
//#endregion
|
|
25
|
+
export { PartialSuccessPrompt, RenderPartialSuccessPromptInput, renderPartialSuccessPrompt };
|
|
26
|
+
//# sourceMappingURL=render-partial-success-prompt.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"render-partial-success-prompt.d.ts","names":[],"sources":["../../src/internals/render-partial-success-prompt.ts"],"mappings":";;;UAmCiB,+BAAA;;EAEf,SAAA;EAF8C;EAI9C,YAAA;EAJ8C;EAM9C,MAAA;EAFA;EAIA,qBAAA;AAAA;AAAA,UAGe,oBAAA;EAHM;EAKrB,MAAA;EAFmC;;;;EAOnC,OAAA,EAAS,gBAAA;AAAA;AAAA,iBAGK,0BAAA,CACd,KAAA,EAAO,+BAAA,GACN,oBAAA"}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
//#region src/internals/render-partial-success-prompt.ts
|
|
2
|
+
/**
|
|
3
|
+
* Render the prompt body + recovery-option set for `deployApp`'s
|
|
4
|
+
* partial-success recovery branch. Uses a fixed structural template —
|
|
5
|
+
* wording stays consistent across runs regardless of LLM paraphrase
|
|
6
|
+
* tendencies.
|
|
7
|
+
*
|
|
8
|
+
* **Conditional inserts:** wording differs by whether a `customDomain`
|
|
9
|
+
* was requested. When absent, the failure description shifts to a
|
|
10
|
+
* generic "manifest upload or readiness poll failed" framing and the
|
|
11
|
+
* `retry_set_domain` recovery option is omitted (it's meaningless
|
|
12
|
+
* without a domain request to retry).
|
|
13
|
+
*
|
|
14
|
+
* The CJS emits a single-line JSON object on stdout
|
|
15
|
+
* (`{ prompt, options: string[] }`). The TS port returns a structured
|
|
16
|
+
* `PartialSuccessPrompt` with typed `RecoveryOptionId`s, so the
|
|
17
|
+
* `deployApp` orchestrator can route directly into the inline-closure
|
|
18
|
+
* recovery dispatch (per gate-2 verdict) without intermediate
|
|
19
|
+
* stringification.
|
|
20
|
+
*
|
|
21
|
+
* **Note on `decodedState`:** the caller is expected to have already
|
|
22
|
+
* decoded the chain integer / `LEASE_STATE_*` string via
|
|
23
|
+
* `lease-state.ts:decode` and pass the canonical name (or a
|
|
24
|
+
* `UNKNOWN(<raw>)` sentinel for unrecognized values). This module does
|
|
25
|
+
* not re-decode — the canonical name is shown verbatim in the lease
|
|
26
|
+
* status line so an explicit `LEASE_STATE_` prefix is preserved (the
|
|
27
|
+
* partial-success path surfaces the raw lease state for diagnostic
|
|
28
|
+
* fidelity, unlike `formatSuccess` which strips the prefix for display).
|
|
29
|
+
*/
|
|
30
|
+
/** RFC 4122 UUID — 36 chars, hex + 4 hyphens, lowercase or upper. */
|
|
31
|
+
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
|
|
32
|
+
function renderPartialSuccessPrompt(input) {
|
|
33
|
+
if (!UUID_RE.test(input.leaseUuid)) throw new TypeError(`renderPartialSuccessPrompt: leaseUuid must be a UUID; got "${input.leaseUuid}"`);
|
|
34
|
+
if (typeof input.decodedState !== "string" || input.decodedState.length === 0) throw new TypeError("renderPartialSuccessPrompt: decodedState must be a non-empty string");
|
|
35
|
+
if (typeof input.reason !== "string" || input.reason.length === 0) throw new TypeError("renderPartialSuccessPrompt: reason must be a non-empty string");
|
|
36
|
+
const hasDomain = typeof input.requestedCustomDomain === "string" && input.requestedCustomDomain.length > 0;
|
|
37
|
+
const lines = ["Deploy partially succeeded:", ` - Lease ${input.leaseUuid} was created on-chain (state: ${input.decodedState}).`];
|
|
38
|
+
if (hasDomain) lines.push(` - The set-domain step for ${input.requestedCustomDomain} did NOT complete: ${input.reason}.`, " The manifest was therefore NEVER uploaded to the provider — no app is running on this lease.");
|
|
39
|
+
else lines.push(` - The manifest upload or readiness poll failed: ${input.reason}.`, " The provider may or may not have started the app.");
|
|
40
|
+
lines.push("", "What do you want to do?");
|
|
41
|
+
const options = [];
|
|
42
|
+
if (hasDomain) options.push("retry_set_domain");
|
|
43
|
+
options.push("salvage_without_domain");
|
|
44
|
+
options.push("close_lease");
|
|
45
|
+
return {
|
|
46
|
+
prompt: lines.join("\n"),
|
|
47
|
+
options
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
//#endregion
|
|
51
|
+
export { renderPartialSuccessPrompt };
|
|
52
|
+
|
|
53
|
+
//# sourceMappingURL=render-partial-success-prompt.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"render-partial-success-prompt.js","names":[],"sources":["../../src/internals/render-partial-success-prompt.ts"],"sourcesContent":["import type { RecoveryOptionId } from '../types.js';\n\n/**\n * Render the prompt body + recovery-option set for `deployApp`'s\n * partial-success recovery branch. Uses a fixed structural template —\n * wording stays consistent across runs regardless of LLM paraphrase\n * tendencies.\n *\n * **Conditional inserts:** wording differs by whether a `customDomain`\n * was requested. When absent, the failure description shifts to a\n * generic \"manifest upload or readiness poll failed\" framing and the\n * `retry_set_domain` recovery option is omitted (it's meaningless\n * without a domain request to retry).\n *\n * The CJS emits a single-line JSON object on stdout\n * (`{ prompt, options: string[] }`). The TS port returns a structured\n * `PartialSuccessPrompt` with typed `RecoveryOptionId`s, so the\n * `deployApp` orchestrator can route directly into the inline-closure\n * recovery dispatch (per gate-2 verdict) without intermediate\n * stringification.\n *\n * **Note on `decodedState`:** the caller is expected to have already\n * decoded the chain integer / `LEASE_STATE_*` string via\n * `lease-state.ts:decode` and pass the canonical name (or a\n * `UNKNOWN(<raw>)` sentinel for unrecognized values). This module does\n * not re-decode — the canonical name is shown verbatim in the lease\n * status line so an explicit `LEASE_STATE_` prefix is preserved (the\n * partial-success path surfaces the raw lease state for diagnostic\n * fidelity, unlike `formatSuccess` which strips the prefix for display).\n */\n\n/** RFC 4122 UUID — 36 chars, hex + 4 hyphens, lowercase or upper. */\nconst UUID_RE =\n /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;\n\nexport interface RenderPartialSuccessPromptInput {\n /** The lease UUID created on-chain (validated RFC 4122). */\n leaseUuid: string;\n /** Canonical lease state name (e.g. `LEASE_STATE_PENDING`) — pre-decoded. */\n decodedState: string;\n /** Failure reason from the MCP error envelope or `classifyDeployError`. */\n reason: string;\n /** Optional: FQDN the user requested. Presence drives wording + retry option. */\n requestedCustomDomain?: string;\n}\n\nexport interface PartialSuccessPrompt {\n /** Multi-line prompt body to pass to AskUserQuestion. */\n prompt: string;\n /**\n * Recovery options offered to the user. `retry_set_domain` is omitted\n * when no domain was requested. Order matches the CJS's option list.\n */\n options: RecoveryOptionId[];\n}\n\nexport function renderPartialSuccessPrompt(\n input: RenderPartialSuccessPromptInput,\n): PartialSuccessPrompt {\n if (!UUID_RE.test(input.leaseUuid)) {\n throw new TypeError(\n `renderPartialSuccessPrompt: leaseUuid must be a UUID; got \"${input.leaseUuid}\"`,\n );\n }\n if (\n typeof input.decodedState !== 'string' ||\n input.decodedState.length === 0\n ) {\n throw new TypeError(\n 'renderPartialSuccessPrompt: decodedState must be a non-empty string',\n );\n }\n if (typeof input.reason !== 'string' || input.reason.length === 0) {\n throw new TypeError(\n 'renderPartialSuccessPrompt: reason must be a non-empty string',\n );\n }\n\n const hasDomain =\n typeof input.requestedCustomDomain === 'string' &&\n input.requestedCustomDomain.length > 0;\n\n const lines: string[] = [\n 'Deploy partially succeeded:',\n ` - Lease ${input.leaseUuid} was created on-chain (state: ${input.decodedState}).`,\n ];\n if (hasDomain) {\n lines.push(\n ` - The set-domain step for ${input.requestedCustomDomain} did NOT complete: ${input.reason}.`,\n ' The manifest was therefore NEVER uploaded to the provider — no app is running on this lease.',\n );\n } else {\n lines.push(\n ` - The manifest upload or readiness poll failed: ${input.reason}.`,\n ' The provider may or may not have started the app.',\n );\n }\n lines.push('', 'What do you want to do?');\n\n const options: RecoveryOptionId[] = [];\n if (hasDomain) {\n options.push('retry_set_domain');\n }\n options.push('salvage_without_domain');\n // CJS emits \"Cancel or close the lease\" as a single user-facing option\n // (3 total when hasDomain, 2 when not). The typed `RecoveryOptionId`\n // vocabulary splits this into two discrete IDs (`cancel_lease`,\n // `close_lease`) for the orchestrator's typed dispatch — `cancel_lease`\n // applies pre-active (abort without on-chain close); `close_lease`\n // applies post-active (on-chain close-lease tx). To preserve the CJS's\n // observable user-option count, we surface the more-general\n // `close_lease` here as the unified terminal choice; the orchestrator's\n // inline-closure dispatch (see `deploy-app.ts`, gate-2 verdict) inspects\n // the lease state at recovery time and routes to the precise terminal\n // tx. `cancel_lease` remains reachable from verify-recover-driven\n // non-user-prompted paths (e.g. terminal lease detected before user\n // input is solicited).\n options.push('close_lease');\n\n return { prompt: lines.join('\\n'), options };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgCA,MAAM,UACJ;AAuBF,SAAgB,2BACd,OACsB;AACtB,KAAI,CAAC,QAAQ,KAAK,MAAM,UAAU,CAChC,OAAM,IAAI,UACR,8DAA8D,MAAM,UAAU,GAC/E;AAEH,KACE,OAAO,MAAM,iBAAiB,YAC9B,MAAM,aAAa,WAAW,EAE9B,OAAM,IAAI,UACR,sEACD;AAEH,KAAI,OAAO,MAAM,WAAW,YAAY,MAAM,OAAO,WAAW,EAC9D,OAAM,IAAI,UACR,gEACD;CAGH,MAAM,YACJ,OAAO,MAAM,0BAA0B,YACvC,MAAM,sBAAsB,SAAS;CAEvC,MAAM,QAAkB,CACtB,+BACA,aAAa,MAAM,UAAU,gCAAgC,MAAM,aAAa,IACjF;AACD,KAAI,UACF,OAAM,KACJ,+BAA+B,MAAM,sBAAsB,qBAAqB,MAAM,OAAO,IAC7F,mGACD;KAED,OAAM,KACJ,qDAAqD,MAAM,OAAO,IAClE,wDACD;AAEH,OAAM,KAAK,IAAI,0BAA0B;CAEzC,MAAM,UAA8B,EAAE;AACtC,KAAI,UACF,SAAQ,KAAK,mBAAmB;AAElC,SAAQ,KAAK,yBAAyB;AActC,SAAQ,KAAK,cAAc;AAE3B,QAAO;EAAE,QAAQ,MAAM,KAAK,KAAK;EAAE;EAAS"}
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
//#region src/internals/save-manifest.d.ts
|
|
2
|
+
/**
|
|
3
|
+
* Persist a deployed manifest as a schema-version-3 wrapper to disk.
|
|
4
|
+
*
|
|
5
|
+
* Target directory is a **function argument** (`dataDir: string`) rather
|
|
6
|
+
* than an env-var read: per gate-1 verdict, agent-core's `platform: 'neutral'`
|
|
7
|
+
* build target forbids env-var reads at this layer; callers are responsible
|
|
8
|
+
* for resolving the manifests dir from their own env context and passing it in.
|
|
9
|
+
*
|
|
10
|
+
* **Wrapper shape (schema_version 3):**
|
|
11
|
+
*
|
|
12
|
+
* ```
|
|
13
|
+
* {
|
|
14
|
+
* schema_version: 3,
|
|
15
|
+
* lease_uuid, deployed_at_iso, deployed_at_unix,
|
|
16
|
+
* chain_id, image, size, meta_hash_hex,
|
|
17
|
+
* format, // "single" or "stack"
|
|
18
|
+
* manifest_json, // string — canonical Fred-rendered JSON
|
|
19
|
+
* custom_domain?, // (v3) FQDN attached to the lease item
|
|
20
|
+
* custom_domain_service_name? // (v3) stack-lease service holder
|
|
21
|
+
* }
|
|
22
|
+
* ```
|
|
23
|
+
*
|
|
24
|
+
* Schema-version compat: v2 wrappers remain readable by all downstream
|
|
25
|
+
* helpers; missing v3 fields are tolerated as undefined.
|
|
26
|
+
*
|
|
27
|
+
* **Audit guarantee:** SHA-256 of the bytes about to be persisted (after
|
|
28
|
+
* normalizing the heredoc-/Write-added trailing newline) MUST equal
|
|
29
|
+
* `metaHash`. Catches paste errors, accidental spec-vs-manifest_json
|
|
30
|
+
* swaps, and transit corruption. Mismatch throws a typed
|
|
31
|
+
* `SaveManifestError` (`code: 'sha256_mismatch'`).
|
|
32
|
+
*
|
|
33
|
+
* **Filesystem layout:** `<dataDir>/manifests/<lease_uuid>.json` with
|
|
34
|
+
* mode 0600; parent `<dataDir>` and `<dataDir>/manifests` ensured at
|
|
35
|
+
* mode 0700 (chmod-tightens an existing parent that was previously
|
|
36
|
+
* looser).
|
|
37
|
+
*
|
|
38
|
+
* **Dynamic node-import discipline** (mirrors `guarded-fetch.ts`): the
|
|
39
|
+
* `node:fs` / `node:path` / `node:crypto` imports are deferred to call
|
|
40
|
+
* time so module load doesn't violate the `platform: 'neutral'` build
|
|
41
|
+
* target. A `typeof process` check throws a clear "Node-only API" error
|
|
42
|
+
* if invoked outside a Node-like runtime.
|
|
43
|
+
*/
|
|
44
|
+
/** Input contract for `saveManifest`. All `*Hex` / UUID fields are validated. */
|
|
45
|
+
interface SaveManifestInput {
|
|
46
|
+
/** Validated lease UUID (RFC 4122 v1-v5). */
|
|
47
|
+
leaseUuid: string;
|
|
48
|
+
/** Canonical primary image reference (for the wrapper's `image` field). */
|
|
49
|
+
image: string;
|
|
50
|
+
/** SKU name (e.g. `docker-micro`) for the wrapper's `size` field. */
|
|
51
|
+
size: string;
|
|
52
|
+
/** SHA-256 hex of the canonical manifest JSON, from `build_manifest_preview`. */
|
|
53
|
+
metaHash: string;
|
|
54
|
+
/** Chain ID — e.g. `manifest-ledger-testnet-1`. */
|
|
55
|
+
chainId: string;
|
|
56
|
+
/**
|
|
57
|
+
* Canonical Fred-rendered manifest JSON (as a STRING, not a parsed
|
|
58
|
+
* object). The SHA-256 of these bytes (after trimming trailing
|
|
59
|
+
* whitespace) MUST equal `metaHash`.
|
|
60
|
+
*/
|
|
61
|
+
manifestJson: string;
|
|
62
|
+
/**
|
|
63
|
+
* Target data directory — the function writes
|
|
64
|
+
* `<dataDir>/manifests/<lease_uuid>.json`. Per gate-1 verdict,
|
|
65
|
+
* supplied by the caller (no env-var read).
|
|
66
|
+
*
|
|
67
|
+
* **MUST be a dedicated manifest-storage directory.** This function
|
|
68
|
+
* `chmod`-tightens any pre-existing `dataDir` (and its `manifests/`
|
|
69
|
+
* subdirectory) to mode `0o700`. Do NOT pass shared parents like
|
|
70
|
+
* `$HOME`, `~/.config`, or a generic data root — doing so would tighten
|
|
71
|
+
* those directories' permissions and potentially break other processes
|
|
72
|
+
* that depend on them. Callers must resolve this to a dedicated
|
|
73
|
+
* subdirectory (e.g. `$XDG_DATA_HOME/manifest-agent/`); the `manifests/`
|
|
74
|
+
* subdir is created inside automatically.
|
|
75
|
+
*/
|
|
76
|
+
dataDir: string;
|
|
77
|
+
/** Optional custom-domain FQDN attached to the lease item. */
|
|
78
|
+
customDomain?: string;
|
|
79
|
+
/**
|
|
80
|
+
* Optional stack-lease service name that holds the custom domain.
|
|
81
|
+
* Meaningless without `customDomain`; throws if supplied alone.
|
|
82
|
+
*/
|
|
83
|
+
customDomainServiceName?: string;
|
|
84
|
+
}
|
|
85
|
+
interface SaveManifestResult {
|
|
86
|
+
/** Absolute path to the persisted wrapper. */
|
|
87
|
+
manifestPath: string;
|
|
88
|
+
}
|
|
89
|
+
/** Typed error surface for the I/O + validation failure paths. */
|
|
90
|
+
declare class SaveManifestError extends Error {
|
|
91
|
+
readonly code: 'sha256_mismatch' | 'manifest_not_object' | 'invalid_uuid' | 'invalid_meta_hash' | 'invalid_data_dir' | 'service_name_without_domain' | 'manifest_parse_failed' | 'platform_unsupported';
|
|
92
|
+
constructor(code: SaveManifestError['code'], message: string);
|
|
93
|
+
}
|
|
94
|
+
/**
|
|
95
|
+
* Persist the manifest wrapper. Returns the absolute output path.
|
|
96
|
+
*
|
|
97
|
+
* Throws `SaveManifestError` for shape / validation failures; lets raw
|
|
98
|
+
* I/O errors (EACCES, ENOSPC, etc.) propagate so the orchestrator can
|
|
99
|
+
* decide whether to suppress them per step-16's "save-fail → success
|
|
100
|
+
* still returned" contract.
|
|
101
|
+
*/
|
|
102
|
+
declare function saveManifest(input: SaveManifestInput): Promise<SaveManifestResult>;
|
|
103
|
+
//#endregion
|
|
104
|
+
export { SaveManifestError, SaveManifestInput, SaveManifestResult, saveManifest };
|
|
105
|
+
//# sourceMappingURL=save-manifest.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"save-manifest.d.ts","names":[],"sources":["../../src/internals/save-manifest.ts"],"mappings":";;AAmDA;;;;;;;;;;;;;;;AAyCA;;;;;AAMA;;;;;;;;;;;;AA2BA;;;;;;;;;;UA1EiB,iBAAA;EA4EN;EA1ET,SAAA;EA0E2B;EAxE3B,KAAA;;EAEA,IAAA;;EAEA,QAAA;;EAEA,OAAA;;;;;;EAMA,YAAA;;;;;;;;;;;;;;;EAeA,OAAA;;EAEA,YAAA;;;;;EAKA,uBAAA;AAAA;AAAA,UAGe,kBAAA;;EAEf,YAAA;AAAA;;cAIW,iBAAA,SAA0B,KAAA;EAAA,SAC5B,IAAA;cAUG,IAAA,EAAM,iBAAA,UAA2B,OAAA;AAAA;;;;;;;;;iBAgBzB,YAAA,CACpB,KAAA,EAAO,iBAAA,GACN,OAAA,CAAQ,kBAAA"}
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
//#region src/internals/save-manifest.ts
|
|
2
|
+
/**
|
|
3
|
+
* Persist a deployed manifest as a schema-version-3 wrapper to disk.
|
|
4
|
+
*
|
|
5
|
+
* Target directory is a **function argument** (`dataDir: string`) rather
|
|
6
|
+
* than an env-var read: per gate-1 verdict, agent-core's `platform: 'neutral'`
|
|
7
|
+
* build target forbids env-var reads at this layer; callers are responsible
|
|
8
|
+
* for resolving the manifests dir from their own env context and passing it in.
|
|
9
|
+
*
|
|
10
|
+
* **Wrapper shape (schema_version 3):**
|
|
11
|
+
*
|
|
12
|
+
* ```
|
|
13
|
+
* {
|
|
14
|
+
* schema_version: 3,
|
|
15
|
+
* lease_uuid, deployed_at_iso, deployed_at_unix,
|
|
16
|
+
* chain_id, image, size, meta_hash_hex,
|
|
17
|
+
* format, // "single" or "stack"
|
|
18
|
+
* manifest_json, // string — canonical Fred-rendered JSON
|
|
19
|
+
* custom_domain?, // (v3) FQDN attached to the lease item
|
|
20
|
+
* custom_domain_service_name? // (v3) stack-lease service holder
|
|
21
|
+
* }
|
|
22
|
+
* ```
|
|
23
|
+
*
|
|
24
|
+
* Schema-version compat: v2 wrappers remain readable by all downstream
|
|
25
|
+
* helpers; missing v3 fields are tolerated as undefined.
|
|
26
|
+
*
|
|
27
|
+
* **Audit guarantee:** SHA-256 of the bytes about to be persisted (after
|
|
28
|
+
* normalizing the heredoc-/Write-added trailing newline) MUST equal
|
|
29
|
+
* `metaHash`. Catches paste errors, accidental spec-vs-manifest_json
|
|
30
|
+
* swaps, and transit corruption. Mismatch throws a typed
|
|
31
|
+
* `SaveManifestError` (`code: 'sha256_mismatch'`).
|
|
32
|
+
*
|
|
33
|
+
* **Filesystem layout:** `<dataDir>/manifests/<lease_uuid>.json` with
|
|
34
|
+
* mode 0600; parent `<dataDir>` and `<dataDir>/manifests` ensured at
|
|
35
|
+
* mode 0700 (chmod-tightens an existing parent that was previously
|
|
36
|
+
* looser).
|
|
37
|
+
*
|
|
38
|
+
* **Dynamic node-import discipline** (mirrors `guarded-fetch.ts`): the
|
|
39
|
+
* `node:fs` / `node:path` / `node:crypto` imports are deferred to call
|
|
40
|
+
* time so module load doesn't violate the `platform: 'neutral'` build
|
|
41
|
+
* target. A `typeof process` check throws a clear "Node-only API" error
|
|
42
|
+
* if invoked outside a Node-like runtime.
|
|
43
|
+
*/
|
|
44
|
+
/** SHA-256 hex digest — 64 lowercase hex chars. */
|
|
45
|
+
const META_HASH_RE = /^[0-9a-f]{64}$/i;
|
|
46
|
+
/** RFC 4122 UUID — 36 chars. */
|
|
47
|
+
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
|
|
48
|
+
/** Typed error surface for the I/O + validation failure paths. */
|
|
49
|
+
var SaveManifestError = class SaveManifestError extends Error {
|
|
50
|
+
constructor(code, message) {
|
|
51
|
+
super(message);
|
|
52
|
+
this.name = "SaveManifestError";
|
|
53
|
+
this.code = code;
|
|
54
|
+
Object.setPrototypeOf(this, SaveManifestError.prototype);
|
|
55
|
+
}
|
|
56
|
+
};
|
|
57
|
+
/**
|
|
58
|
+
* Persist the manifest wrapper. Returns the absolute output path.
|
|
59
|
+
*
|
|
60
|
+
* Throws `SaveManifestError` for shape / validation failures; lets raw
|
|
61
|
+
* I/O errors (EACCES, ENOSPC, etc.) propagate so the orchestrator can
|
|
62
|
+
* decide whether to suppress them per step-16's "save-fail → success
|
|
63
|
+
* still returned" contract.
|
|
64
|
+
*/
|
|
65
|
+
async function saveManifest(input) {
|
|
66
|
+
if (typeof process === "undefined" || typeof process.versions?.node !== "string") throw new SaveManifestError("platform_unsupported", "saveManifest: requires Node.js runtime (node:fs / node:crypto / node:path)");
|
|
67
|
+
if (typeof input.dataDir !== "string" || input.dataDir.trim().length === 0) throw new SaveManifestError("invalid_data_dir", `saveManifest: dataDir must be a non-empty path; got ${typeof input.dataDir === "string" ? `"${input.dataDir}"` : input.dataDir === null ? "null" : typeof input.dataDir}.`);
|
|
68
|
+
if (!UUID_RE.test(input.leaseUuid)) throw new SaveManifestError("invalid_uuid", `saveManifest: leaseUuid must be a UUID; got "${input.leaseUuid}"`);
|
|
69
|
+
if (!META_HASH_RE.test(input.metaHash)) throw new SaveManifestError("invalid_meta_hash", `saveManifest: metaHash must be a 64-character SHA-256 hex digest; got "${input.metaHash}"`);
|
|
70
|
+
if (input.customDomainServiceName && !input.customDomain) throw new SaveManifestError("service_name_without_domain", "saveManifest: customDomainServiceName requires customDomain");
|
|
71
|
+
const trimmed = input.manifestJson.trimEnd();
|
|
72
|
+
let parsed;
|
|
73
|
+
try {
|
|
74
|
+
parsed = JSON.parse(trimmed);
|
|
75
|
+
} catch (err) {
|
|
76
|
+
throw new SaveManifestError("manifest_parse_failed", `saveManifest: manifestJson is not valid JSON: ${err instanceof Error ? err.message : String(err)}`);
|
|
77
|
+
}
|
|
78
|
+
if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) throw new SaveManifestError("manifest_not_object", "saveManifest: manifestJson must encode a JSON object");
|
|
79
|
+
const parsedRec = parsed;
|
|
80
|
+
const format = parsedRec.services !== null && typeof parsedRec.services === "object" && !Array.isArray(parsedRec.services) ? "stack" : "single";
|
|
81
|
+
const { mkdirSync, chmodSync, writeFileSync, renameSync } = await import("node:fs");
|
|
82
|
+
const { createHash, randomUUID } = await import("node:crypto");
|
|
83
|
+
const { join, resolve: pathResolve } = await import("node:path");
|
|
84
|
+
const computedHash = createHash("sha256").update(trimmed).digest("hex");
|
|
85
|
+
if (computedHash !== input.metaHash.toLowerCase()) throw new SaveManifestError("sha256_mismatch", `saveManifest: SHA-256 mismatch. metaHash claims ${input.metaHash} but manifestJson content hashes to ${computedHash}. The wrong content was probably written (e.g. the structured spec instead of the canonical manifest_json string).`);
|
|
86
|
+
const absoluteDataDir = pathResolve(input.dataDir);
|
|
87
|
+
const manifestsDir = join(absoluteDataDir, "manifests");
|
|
88
|
+
mkdirSync(absoluteDataDir, {
|
|
89
|
+
recursive: true,
|
|
90
|
+
mode: 448
|
|
91
|
+
});
|
|
92
|
+
chmodSync(absoluteDataDir, 448);
|
|
93
|
+
mkdirSync(manifestsDir, {
|
|
94
|
+
recursive: true,
|
|
95
|
+
mode: 448
|
|
96
|
+
});
|
|
97
|
+
chmodSync(manifestsDir, 448);
|
|
98
|
+
const deployedAt = /* @__PURE__ */ new Date();
|
|
99
|
+
const wrapper = {
|
|
100
|
+
schema_version: 3,
|
|
101
|
+
lease_uuid: input.leaseUuid,
|
|
102
|
+
deployed_at_iso: deployedAt.toISOString(),
|
|
103
|
+
deployed_at_unix: Math.floor(deployedAt.getTime() / 1e3),
|
|
104
|
+
chain_id: input.chainId,
|
|
105
|
+
image: input.image,
|
|
106
|
+
size: input.size,
|
|
107
|
+
meta_hash_hex: input.metaHash.toLowerCase(),
|
|
108
|
+
format,
|
|
109
|
+
manifest_json: trimmed
|
|
110
|
+
};
|
|
111
|
+
if (input.customDomain) wrapper.custom_domain = input.customDomain;
|
|
112
|
+
if (input.customDomainServiceName) wrapper.custom_domain_service_name = input.customDomainServiceName;
|
|
113
|
+
const outPath = join(manifestsDir, `${input.leaseUuid}.json`);
|
|
114
|
+
const tmpPath = `${outPath}.tmp-${randomUUID()}`;
|
|
115
|
+
writeFileSync(tmpPath, `${JSON.stringify(wrapper, null, 2)}\n`, { mode: 384 });
|
|
116
|
+
renameSync(tmpPath, outPath);
|
|
117
|
+
return { manifestPath: outPath };
|
|
118
|
+
}
|
|
119
|
+
//#endregion
|
|
120
|
+
export { SaveManifestError, saveManifest };
|
|
121
|
+
|
|
122
|
+
//# sourceMappingURL=save-manifest.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"save-manifest.js","names":[],"sources":["../../src/internals/save-manifest.ts"],"sourcesContent":["/**\n * Persist a deployed manifest as a schema-version-3 wrapper to disk.\n *\n * Target directory is a **function argument** (`dataDir: string`) rather\n * than an env-var read: per gate-1 verdict, agent-core's `platform: 'neutral'`\n * build target forbids env-var reads at this layer; callers are responsible\n * for resolving the manifests dir from their own env context and passing it in.\n *\n * **Wrapper shape (schema_version 3):**\n *\n * ```\n * {\n * schema_version: 3,\n * lease_uuid, deployed_at_iso, deployed_at_unix,\n * chain_id, image, size, meta_hash_hex,\n * format, // \"single\" or \"stack\"\n * manifest_json, // string — canonical Fred-rendered JSON\n * custom_domain?, // (v3) FQDN attached to the lease item\n * custom_domain_service_name? // (v3) stack-lease service holder\n * }\n * ```\n *\n * Schema-version compat: v2 wrappers remain readable by all downstream\n * helpers; missing v3 fields are tolerated as undefined.\n *\n * **Audit guarantee:** SHA-256 of the bytes about to be persisted (after\n * normalizing the heredoc-/Write-added trailing newline) MUST equal\n * `metaHash`. Catches paste errors, accidental spec-vs-manifest_json\n * swaps, and transit corruption. Mismatch throws a typed\n * `SaveManifestError` (`code: 'sha256_mismatch'`).\n *\n * **Filesystem layout:** `<dataDir>/manifests/<lease_uuid>.json` with\n * mode 0600; parent `<dataDir>` and `<dataDir>/manifests` ensured at\n * mode 0700 (chmod-tightens an existing parent that was previously\n * looser).\n *\n * **Dynamic node-import discipline** (mirrors `guarded-fetch.ts`): the\n * `node:fs` / `node:path` / `node:crypto` imports are deferred to call\n * time so module load doesn't violate the `platform: 'neutral'` build\n * target. A `typeof process` check throws a clear \"Node-only API\" error\n * if invoked outside a Node-like runtime.\n */\n\n/** SHA-256 hex digest — 64 lowercase hex chars. */\nconst META_HASH_RE = /^[0-9a-f]{64}$/i;\n\n/** RFC 4122 UUID — 36 chars. */\nconst UUID_RE =\n /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;\n\n/** Input contract for `saveManifest`. All `*Hex` / UUID fields are validated. */\nexport interface SaveManifestInput {\n /** Validated lease UUID (RFC 4122 v1-v5). */\n leaseUuid: string;\n /** Canonical primary image reference (for the wrapper's `image` field). */\n image: string;\n /** SKU name (e.g. `docker-micro`) for the wrapper's `size` field. */\n size: string;\n /** SHA-256 hex of the canonical manifest JSON, from `build_manifest_preview`. */\n metaHash: string;\n /** Chain ID — e.g. `manifest-ledger-testnet-1`. */\n chainId: string;\n /**\n * Canonical Fred-rendered manifest JSON (as a STRING, not a parsed\n * object). The SHA-256 of these bytes (after trimming trailing\n * whitespace) MUST equal `metaHash`.\n */\n manifestJson: string;\n /**\n * Target data directory — the function writes\n * `<dataDir>/manifests/<lease_uuid>.json`. Per gate-1 verdict,\n * supplied by the caller (no env-var read).\n *\n * **MUST be a dedicated manifest-storage directory.** This function\n * `chmod`-tightens any pre-existing `dataDir` (and its `manifests/`\n * subdirectory) to mode `0o700`. Do NOT pass shared parents like\n * `$HOME`, `~/.config`, or a generic data root — doing so would tighten\n * those directories' permissions and potentially break other processes\n * that depend on them. Callers must resolve this to a dedicated\n * subdirectory (e.g. `$XDG_DATA_HOME/manifest-agent/`); the `manifests/`\n * subdir is created inside automatically.\n */\n dataDir: string;\n /** Optional custom-domain FQDN attached to the lease item. */\n customDomain?: string;\n /**\n * Optional stack-lease service name that holds the custom domain.\n * Meaningless without `customDomain`; throws if supplied alone.\n */\n customDomainServiceName?: string;\n}\n\nexport interface SaveManifestResult {\n /** Absolute path to the persisted wrapper. */\n manifestPath: string;\n}\n\n/** Typed error surface for the I/O + validation failure paths. */\nexport class SaveManifestError extends Error {\n readonly code:\n | 'sha256_mismatch'\n | 'manifest_not_object'\n | 'invalid_uuid'\n | 'invalid_meta_hash'\n | 'invalid_data_dir'\n | 'service_name_without_domain'\n | 'manifest_parse_failed'\n | 'platform_unsupported';\n\n constructor(code: SaveManifestError['code'], message: string) {\n super(message);\n this.name = 'SaveManifestError';\n this.code = code;\n Object.setPrototypeOf(this, SaveManifestError.prototype);\n }\n}\n\n/**\n * Persist the manifest wrapper. Returns the absolute output path.\n *\n * Throws `SaveManifestError` for shape / validation failures; lets raw\n * I/O errors (EACCES, ENOSPC, etc.) propagate so the orchestrator can\n * decide whether to suppress them per step-16's \"save-fail → success\n * still returned\" contract.\n */\nexport async function saveManifest(\n input: SaveManifestInput,\n): Promise<SaveManifestResult> {\n if (\n typeof process === 'undefined' ||\n typeof process.versions?.node !== 'string'\n ) {\n throw new SaveManifestError(\n 'platform_unsupported',\n 'saveManifest: requires Node.js runtime (node:fs / node:crypto / node:path)',\n );\n }\n // Copilot review fix (PR #58 r3267373130): reject empty / whitespace-\n // only / non-string `dataDir` BEFORE any I/O. `pathResolve('')` returns\n // `process.cwd()`, and the later `chmodSync(absoluteDataDir, 0o700)`\n // would then tighten the caller's working directory — a real safety\n // hazard if a misconfigured env (`MANIFEST_DATA_DIR=\"\"`) reaches\n // here. Failing fast at the boundary keeps the hazard from\n // materializing.\n if (typeof input.dataDir !== 'string' || input.dataDir.trim().length === 0) {\n throw new SaveManifestError(\n 'invalid_data_dir',\n `saveManifest: dataDir must be a non-empty path; got ${\n typeof input.dataDir === 'string'\n ? `\"${input.dataDir}\"`\n : input.dataDir === null\n ? 'null'\n : typeof input.dataDir\n }.`,\n );\n }\n if (!UUID_RE.test(input.leaseUuid)) {\n throw new SaveManifestError(\n 'invalid_uuid',\n `saveManifest: leaseUuid must be a UUID; got \"${input.leaseUuid}\"`,\n );\n }\n if (!META_HASH_RE.test(input.metaHash)) {\n throw new SaveManifestError(\n 'invalid_meta_hash',\n `saveManifest: metaHash must be a 64-character SHA-256 hex digest; got \"${input.metaHash}\"`,\n );\n }\n if (input.customDomainServiceName && !input.customDomain) {\n throw new SaveManifestError(\n 'service_name_without_domain',\n 'saveManifest: customDomainServiceName requires customDomain',\n );\n }\n\n // Trim trailing newline (heredoc/Write convention) so the SHA-256 of the\n // persisted bytes matches the meta_hash_hex returned by\n // build_manifest_preview.\n const trimmed = input.manifestJson.trimEnd();\n\n // Parse for shape sanity + format derivation. Failures throw a typed\n // `SaveManifestError(manifest_parse_failed)` rather than the raw\n // SyntaxError.\n let parsed: unknown;\n try {\n parsed = JSON.parse(trimmed);\n } catch (err) {\n const reason = err instanceof Error ? err.message : String(err);\n throw new SaveManifestError(\n 'manifest_parse_failed',\n `saveManifest: manifestJson is not valid JSON: ${reason}`,\n );\n }\n if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {\n throw new SaveManifestError(\n 'manifest_not_object',\n 'saveManifest: manifestJson must encode a JSON object',\n );\n }\n const parsedRec = parsed as Record<string, unknown>;\n const isStack =\n parsedRec.services !== null &&\n typeof parsedRec.services === 'object' &&\n !Array.isArray(parsedRec.services);\n const format: 'single' | 'stack' = isStack ? 'stack' : 'single';\n\n // Dynamic imports — node-only deps deferred per the `platform: 'neutral'`\n // build target. Mirrors `guarded-fetch.ts`'s lazy-init pattern.\n const { mkdirSync, chmodSync, writeFileSync, renameSync } = await import(\n 'node:fs'\n );\n const { createHash, randomUUID } = await import('node:crypto');\n const { join, resolve: pathResolve } = await import('node:path');\n\n // SHA-256 audit: catches the most common foot-gun (passing the\n // structured spec where the canonical manifest_json was expected).\n const computedHash = createHash('sha256').update(trimmed).digest('hex');\n if (computedHash !== input.metaHash.toLowerCase()) {\n throw new SaveManifestError(\n 'sha256_mismatch',\n `saveManifest: SHA-256 mismatch. metaHash claims ${input.metaHash} but manifestJson content hashes to ${computedHash}. The wrong content was probably written (e.g. the structured spec instead of the canonical manifest_json string).`,\n );\n }\n\n // C5 fix: resolve dataDir to absolute BEFORE constructing paths.\n // `SaveManifestResult.manifestPath` is documented as absolute; the\n // prior `join(input.dataDir, ...)` returned a relative path when the\n // caller passed a relative dataDir. `path.resolve()` normalizes\n // against the process CWD if input is relative; idempotent for\n // already-absolute inputs.\n const absoluteDataDir = pathResolve(input.dataDir);\n\n // Ensure dataDir + manifests/ exist with tight perms. chmod after mkdir\n // so a pre-existing looser parent gets tightened (mkdir won't chmod\n // existing dirs).\n const manifestsDir = join(absoluteDataDir, 'manifests');\n mkdirSync(absoluteDataDir, { recursive: true, mode: 0o700 });\n chmodSync(absoluteDataDir, 0o700);\n mkdirSync(manifestsDir, { recursive: true, mode: 0o700 });\n chmodSync(manifestsDir, 0o700);\n\n // Copilot review fix (PR #58 r3267708600): single-source the deploy\n // timestamp. The prior code called `new Date().toISOString()` and\n // `Math.floor(Date.now() / 1000)` separately — two distinct clock\n // reads. If the function spans a second boundary, the iso + unix\n // fields refer to different instants, violating the audit\n // metadata's internal-consistency invariant (any tooling cross-\n // checking the pair would flag the drift).\n const deployedAt = new Date();\n const wrapper: Record<string, unknown> = {\n schema_version: 3,\n lease_uuid: input.leaseUuid,\n deployed_at_iso: deployedAt.toISOString(),\n deployed_at_unix: Math.floor(deployedAt.getTime() / 1000),\n chain_id: input.chainId,\n image: input.image,\n size: input.size,\n meta_hash_hex: input.metaHash.toLowerCase(),\n format,\n manifest_json: trimmed,\n };\n if (input.customDomain) {\n wrapper.custom_domain = input.customDomain;\n }\n if (input.customDomainServiceName) {\n wrapper.custom_domain_service_name = input.customDomainServiceName;\n }\n\n const outPath = join(manifestsDir, `${input.leaseUuid}.json`);\n // Atomic write: temp file in same dir + rename. Survives crash mid-write\n // without leaving a partial file at the canonical name. The randomUUID\n // suffix avoids collisions if multiple concurrent saves target the same\n // lease (rare, but the CJS's atomicWrite helper uses the same pattern).\n const tmpPath = `${outPath}.tmp-${randomUUID()}`;\n writeFileSync(tmpPath, `${JSON.stringify(wrapper, null, 2)}\\n`, {\n mode: 0o600,\n });\n renameSync(tmpPath, outPath);\n\n return { manifestPath: outPath };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4CA,MAAM,eAAe;;AAGrB,MAAM,UACJ;;AAkDF,IAAa,oBAAb,MAAa,0BAA0B,MAAM;CAW3C,YAAY,MAAiC,SAAiB;AAC5D,QAAM,QAAQ;AACd,OAAK,OAAO;AACZ,OAAK,OAAO;AACZ,SAAO,eAAe,MAAM,kBAAkB,UAAU;;;;;;;;;;;AAY5D,eAAsB,aACpB,OAC6B;AAC7B,KACE,OAAO,YAAY,eACnB,OAAO,QAAQ,UAAU,SAAS,SAElC,OAAM,IAAI,kBACR,wBACA,6EACD;AASH,KAAI,OAAO,MAAM,YAAY,YAAY,MAAM,QAAQ,MAAM,CAAC,WAAW,EACvE,OAAM,IAAI,kBACR,oBACA,uDACE,OAAO,MAAM,YAAY,WACrB,IAAI,MAAM,QAAQ,KAClB,MAAM,YAAY,OAChB,SACA,OAAO,MAAM,QACpB,GACF;AAEH,KAAI,CAAC,QAAQ,KAAK,MAAM,UAAU,CAChC,OAAM,IAAI,kBACR,gBACA,gDAAgD,MAAM,UAAU,GACjE;AAEH,KAAI,CAAC,aAAa,KAAK,MAAM,SAAS,CACpC,OAAM,IAAI,kBACR,qBACA,0EAA0E,MAAM,SAAS,GAC1F;AAEH,KAAI,MAAM,2BAA2B,CAAC,MAAM,aAC1C,OAAM,IAAI,kBACR,+BACA,8DACD;CAMH,MAAM,UAAU,MAAM,aAAa,SAAS;CAK5C,IAAI;AACJ,KAAI;AACF,WAAS,KAAK,MAAM,QAAQ;UACrB,KAAK;AAEZ,QAAM,IAAI,kBACR,yBACA,iDAHa,eAAe,QAAQ,IAAI,UAAU,OAAO,IAAI,GAI9D;;AAEH,KAAI,WAAW,QAAQ,OAAO,WAAW,YAAY,MAAM,QAAQ,OAAO,CACxE,OAAM,IAAI,kBACR,uBACA,uDACD;CAEH,MAAM,YAAY;CAKlB,MAAM,SAHJ,UAAU,aAAa,QACvB,OAAO,UAAU,aAAa,YAC9B,CAAC,MAAM,QAAQ,UAAU,SAAS,GACS,UAAU;CAIvD,MAAM,EAAE,WAAW,WAAW,eAAe,eAAe,MAAM,OAChE;CAEF,MAAM,EAAE,YAAY,eAAe,MAAM,OAAO;CAChD,MAAM,EAAE,MAAM,SAAS,gBAAgB,MAAM,OAAO;CAIpD,MAAM,eAAe,WAAW,SAAS,CAAC,OAAO,QAAQ,CAAC,OAAO,MAAM;AACvE,KAAI,iBAAiB,MAAM,SAAS,aAAa,CAC/C,OAAM,IAAI,kBACR,mBACA,mDAAmD,MAAM,SAAS,sCAAsC,aAAa,oHACtH;CASH,MAAM,kBAAkB,YAAY,MAAM,QAAQ;CAKlD,MAAM,eAAe,KAAK,iBAAiB,YAAY;AACvD,WAAU,iBAAiB;EAAE,WAAW;EAAM,MAAM;EAAO,CAAC;AAC5D,WAAU,iBAAiB,IAAM;AACjC,WAAU,cAAc;EAAE,WAAW;EAAM,MAAM;EAAO,CAAC;AACzD,WAAU,cAAc,IAAM;CAS9B,MAAM,6BAAa,IAAI,MAAM;CAC7B,MAAM,UAAmC;EACvC,gBAAgB;EAChB,YAAY,MAAM;EAClB,iBAAiB,WAAW,aAAa;EACzC,kBAAkB,KAAK,MAAM,WAAW,SAAS,GAAG,IAAK;EACzD,UAAU,MAAM;EAChB,OAAO,MAAM;EACb,MAAM,MAAM;EACZ,eAAe,MAAM,SAAS,aAAa;EAC3C;EACA,eAAe;EAChB;AACD,KAAI,MAAM,aACR,SAAQ,gBAAgB,MAAM;AAEhC,KAAI,MAAM,wBACR,SAAQ,6BAA6B,MAAM;CAG7C,MAAM,UAAU,KAAK,cAAc,GAAG,MAAM,UAAU,OAAO;CAK7D,MAAM,UAAU,GAAG,QAAQ,OAAO,YAAY;AAC9C,eAAc,SAAS,GAAG,KAAK,UAAU,SAAS,MAAM,EAAE,CAAC,KAAK,EAC9D,MAAM,KACP,CAAC;AACF,YAAW,SAAS,QAAQ;AAE5B,QAAO,EAAE,cAAc,SAAS"}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
//#region src/internals/secret-denylist.d.ts
|
|
2
|
+
/**
|
|
3
|
+
* Secret-key denylist + prototype-pollution guard. Used by
|
|
4
|
+
* `verify-recover.ts` to scrub a verifier's diagnostic payload before it
|
|
5
|
+
* reaches the host callback (or the journal record in ENG-124).
|
|
6
|
+
*
|
|
7
|
+
* Two exports:
|
|
8
|
+
*
|
|
9
|
+
* - `SECRET_KEY_DENYLIST` — case-insensitive substring match on KEY names
|
|
10
|
+
* only; values are never inspected. Narrow on purpose: covers the
|
|
11
|
+
* high-confidence sensitive shapes (mnemonic + keyfile password) plus
|
|
12
|
+
* credential-shaped suffixes that catch obvious caller mistakes
|
|
13
|
+
* (`api[_-]?key`, `private[_-]?key`, `secret[_-]?key`, `auth[_-]?token`,
|
|
14
|
+
* `bearer[_-]?token`). The blanket `token` and `secret` keywords are NOT
|
|
15
|
+
* here — this is a blockchain context where `gas_token`, `fee_token`,
|
|
16
|
+
* `token_id`, `token_symbol` are legitimate non-sensitive field names.
|
|
17
|
+
*
|
|
18
|
+
* - `stripDenylist` (in `verify-recover.ts`) — recursive walker over
|
|
19
|
+
* objects + arrays; drops any key matching the denylist regex; ALSO
|
|
20
|
+
* skips the three prototype-pollution-capable keys `__proto__`,
|
|
21
|
+
* `constructor`, `prototype` because `JSON.parse` materializes them as
|
|
22
|
+
* own properties that a bare `out[k] = v` assignment would treat as a
|
|
23
|
+
* prototype mutation.
|
|
24
|
+
*/
|
|
25
|
+
declare const SECRET_KEY_DENYLIST: RegExp;
|
|
26
|
+
declare const PROTOTYPE_POLLUTION_KEYS: ReadonlySet<string>;
|
|
27
|
+
/**
|
|
28
|
+
* Recursively walk a value and remove any object keys that:
|
|
29
|
+
* - Match `SECRET_KEY_DENYLIST` (case-insensitive substring on key name), or
|
|
30
|
+
* - Are one of the prototype-pollution keys (`__proto__`, `constructor`,
|
|
31
|
+
* `prototype`).
|
|
32
|
+
*
|
|
33
|
+
* Arrays are walked element-wise. Primitives (string/number/boolean/null/
|
|
34
|
+
* undefined) pass through untouched.
|
|
35
|
+
*
|
|
36
|
+
* Returns `unknown` because the structural shape changes: object inputs may
|
|
37
|
+
* have fewer keys than they started with. Callers narrow at use sites.
|
|
38
|
+
*/
|
|
39
|
+
declare function stripDenylist(value: unknown): unknown;
|
|
40
|
+
//#endregion
|
|
41
|
+
export { PROTOTYPE_POLLUTION_KEYS, SECRET_KEY_DENYLIST, stripDenylist };
|
|
42
|
+
//# sourceMappingURL=secret-denylist.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"secret-denylist.d.ts","names":[],"sources":["../../src/internals/secret-denylist.ts"],"mappings":";;AAwBA;;;;;AAGA;;;;;AAkBA;;;;;;;;;;;;cArBa,mBAAA,EAAmB,MAAA;AAAA,cAGnB,wBAAA,EAA0B,WAAA;;;;;;;;;;;;;iBAkBvB,aAAA,CAAc,KAAA"}
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
//#region src/internals/secret-denylist.ts
|
|
2
|
+
/**
|
|
3
|
+
* Secret-key denylist + prototype-pollution guard. Used by
|
|
4
|
+
* `verify-recover.ts` to scrub a verifier's diagnostic payload before it
|
|
5
|
+
* reaches the host callback (or the journal record in ENG-124).
|
|
6
|
+
*
|
|
7
|
+
* Two exports:
|
|
8
|
+
*
|
|
9
|
+
* - `SECRET_KEY_DENYLIST` — case-insensitive substring match on KEY names
|
|
10
|
+
* only; values are never inspected. Narrow on purpose: covers the
|
|
11
|
+
* high-confidence sensitive shapes (mnemonic + keyfile password) plus
|
|
12
|
+
* credential-shaped suffixes that catch obvious caller mistakes
|
|
13
|
+
* (`api[_-]?key`, `private[_-]?key`, `secret[_-]?key`, `auth[_-]?token`,
|
|
14
|
+
* `bearer[_-]?token`). The blanket `token` and `secret` keywords are NOT
|
|
15
|
+
* here — this is a blockchain context where `gas_token`, `fee_token`,
|
|
16
|
+
* `token_id`, `token_symbol` are legitimate non-sensitive field names.
|
|
17
|
+
*
|
|
18
|
+
* - `stripDenylist` (in `verify-recover.ts`) — recursive walker over
|
|
19
|
+
* objects + arrays; drops any key matching the denylist regex; ALSO
|
|
20
|
+
* skips the three prototype-pollution-capable keys `__proto__`,
|
|
21
|
+
* `constructor`, `prototype` because `JSON.parse` materializes them as
|
|
22
|
+
* own properties that a bare `out[k] = v` assignment would treat as a
|
|
23
|
+
* prototype mutation.
|
|
24
|
+
*/
|
|
25
|
+
const SECRET_KEY_DENYLIST = /(mnemonic|password|private[_-]?key|secret[_-]?key|api[_-]?key|auth[_-]?token|bearer[_-]?token)/i;
|
|
26
|
+
const PROTOTYPE_POLLUTION_KEYS = new Set([
|
|
27
|
+
"__proto__",
|
|
28
|
+
"constructor",
|
|
29
|
+
"prototype"
|
|
30
|
+
]);
|
|
31
|
+
/**
|
|
32
|
+
* Recursively walk a value and remove any object keys that:
|
|
33
|
+
* - Match `SECRET_KEY_DENYLIST` (case-insensitive substring on key name), or
|
|
34
|
+
* - Are one of the prototype-pollution keys (`__proto__`, `constructor`,
|
|
35
|
+
* `prototype`).
|
|
36
|
+
*
|
|
37
|
+
* Arrays are walked element-wise. Primitives (string/number/boolean/null/
|
|
38
|
+
* undefined) pass through untouched.
|
|
39
|
+
*
|
|
40
|
+
* Returns `unknown` because the structural shape changes: object inputs may
|
|
41
|
+
* have fewer keys than they started with. Callers narrow at use sites.
|
|
42
|
+
*/
|
|
43
|
+
function stripDenylist(value) {
|
|
44
|
+
if (Array.isArray(value)) return value.map((v) => stripDenylist(v));
|
|
45
|
+
if (value !== null && typeof value === "object") {
|
|
46
|
+
const out = {};
|
|
47
|
+
for (const [k, v] of Object.entries(value)) {
|
|
48
|
+
if (PROTOTYPE_POLLUTION_KEYS.has(k)) continue;
|
|
49
|
+
if (SECRET_KEY_DENYLIST.test(k)) continue;
|
|
50
|
+
out[k] = stripDenylist(v);
|
|
51
|
+
}
|
|
52
|
+
return out;
|
|
53
|
+
}
|
|
54
|
+
return value;
|
|
55
|
+
}
|
|
56
|
+
//#endregion
|
|
57
|
+
export { PROTOTYPE_POLLUTION_KEYS, SECRET_KEY_DENYLIST, stripDenylist };
|
|
58
|
+
|
|
59
|
+
//# sourceMappingURL=secret-denylist.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"secret-denylist.js","names":[],"sources":["../../src/internals/secret-denylist.ts"],"sourcesContent":["/**\n * Secret-key denylist + prototype-pollution guard. Used by\n * `verify-recover.ts` to scrub a verifier's diagnostic payload before it\n * reaches the host callback (or the journal record in ENG-124).\n *\n * Two exports:\n *\n * - `SECRET_KEY_DENYLIST` — case-insensitive substring match on KEY names\n * only; values are never inspected. Narrow on purpose: covers the\n * high-confidence sensitive shapes (mnemonic + keyfile password) plus\n * credential-shaped suffixes that catch obvious caller mistakes\n * (`api[_-]?key`, `private[_-]?key`, `secret[_-]?key`, `auth[_-]?token`,\n * `bearer[_-]?token`). The blanket `token` and `secret` keywords are NOT\n * here — this is a blockchain context where `gas_token`, `fee_token`,\n * `token_id`, `token_symbol` are legitimate non-sensitive field names.\n *\n * - `stripDenylist` (in `verify-recover.ts`) — recursive walker over\n * objects + arrays; drops any key matching the denylist regex; ALSO\n * skips the three prototype-pollution-capable keys `__proto__`,\n * `constructor`, `prototype` because `JSON.parse` materializes them as\n * own properties that a bare `out[k] = v` assignment would treat as a\n * prototype mutation.\n */\n\nexport const SECRET_KEY_DENYLIST =\n /(mnemonic|password|private[_-]?key|secret[_-]?key|api[_-]?key|auth[_-]?token|bearer[_-]?token)/i;\n\nexport const PROTOTYPE_POLLUTION_KEYS: ReadonlySet<string> = new Set([\n '__proto__',\n 'constructor',\n 'prototype',\n]);\n\n/**\n * Recursively walk a value and remove any object keys that:\n * - Match `SECRET_KEY_DENYLIST` (case-insensitive substring on key name), or\n * - Are one of the prototype-pollution keys (`__proto__`, `constructor`,\n * `prototype`).\n *\n * Arrays are walked element-wise. Primitives (string/number/boolean/null/\n * undefined) pass through untouched.\n *\n * Returns `unknown` because the structural shape changes: object inputs may\n * have fewer keys than they started with. Callers narrow at use sites.\n */\nexport function stripDenylist(value: unknown): unknown {\n if (Array.isArray(value)) {\n return value.map((v) => stripDenylist(v));\n }\n if (value !== null && typeof value === 'object') {\n const out: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(value as Record<string, unknown>)) {\n if (PROTOTYPE_POLLUTION_KEYS.has(k)) continue;\n if (SECRET_KEY_DENYLIST.test(k)) continue;\n out[k] = stripDenylist(v);\n }\n return out;\n }\n return value;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAwBA,MAAa,sBACX;AAEF,MAAa,2BAAgD,IAAI,IAAI;CACnE;CACA;CACA;CACD,CAAC;;;;;;;;;;;;;AAcF,SAAgB,cAAc,OAAyB;AACrD,KAAI,MAAM,QAAQ,MAAM,CACtB,QAAO,MAAM,KAAK,MAAM,cAAc,EAAE,CAAC;AAE3C,KAAI,UAAU,QAAQ,OAAO,UAAU,UAAU;EAC/C,MAAM,MAA+B,EAAE;AACvC,OAAK,MAAM,CAAC,GAAG,MAAM,OAAO,QAAQ,MAAiC,EAAE;AACrE,OAAI,yBAAyB,IAAI,EAAE,CAAE;AACrC,OAAI,oBAAoB,KAAK,EAAE,CAAE;AACjC,OAAI,KAAK,cAAc,EAAE;;AAE3B,SAAO;;AAET,QAAO"}
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
import { DeploySpec, ServiceDef, SingleServiceSpec, SpecSummary, StackSpec } from "../types.js";
|
|
2
|
+
|
|
3
|
+
//#region src/internals/spec-normalize.d.ts
|
|
4
|
+
/**
|
|
5
|
+
* Spec normalization + summarization helpers. Exports `isStack`,
|
|
6
|
+
* `firstImage`, `normalizeServices`, `summarizeSpec`, and `validateSpec`
|
|
7
|
+
* (the latter surfaces pre-broadcast shape violations).
|
|
8
|
+
*
|
|
9
|
+
* Two spec shapes are supported (frozen in ENG-128's `types.ts`):
|
|
10
|
+
* - **services-map (StackSpec)** — `{ services: { <name>: ServiceDef }, customDomain?, serviceName? }`
|
|
11
|
+
* - **legacy single-service (SingleServiceSpec)** — `{ image, port?, env?, customDomain? }`
|
|
12
|
+
*
|
|
13
|
+
* `normalizeServices` collapses the two shapes into a single iterable form
|
|
14
|
+
* so callers (Plan summary, manifest builder, etc.) walk one structure
|
|
15
|
+
* regardless of which form the user passed.
|
|
16
|
+
*
|
|
17
|
+
* Validation: `validateSpec` throws a plain `TypeError` on shape violations
|
|
18
|
+
* — agent-core has no workspace dep on `@manifest-network/manifest-mcp-core`
|
|
19
|
+
* in PR 1/2 (per parent's REV 1), so `ManifestMCPError` isn't available
|
|
20
|
+
* here. PR 3's high-level `deployApp` re-wraps `TypeError` into
|
|
21
|
+
* `ManifestMCPError(INVALID_CONFIG)` at the public-API boundary.
|
|
22
|
+
*/
|
|
23
|
+
/**
|
|
24
|
+
* True when `spec` uses the services-map shape (StackSpec). Mirrors
|
|
25
|
+
* `_spec.cjs#isStack`: `services` is a non-null, non-array object.
|
|
26
|
+
*/
|
|
27
|
+
declare function isStackSpec(spec: DeploySpec | null | undefined): spec is StackSpec;
|
|
28
|
+
/**
|
|
29
|
+
* Return the canonical first image string for a spec. For legacy single-
|
|
30
|
+
* service: `spec.image`. For stack: the first non-empty `image` in
|
|
31
|
+
* `Object.values(spec.services)`. Returns `null` when neither shape
|
|
32
|
+
* carries an image (or `spec` is malformed).
|
|
33
|
+
*/
|
|
34
|
+
declare function firstImage(spec: DeploySpec | null | undefined): string | null;
|
|
35
|
+
/**
|
|
36
|
+
* Walk a spec as `[{name, raw}]` where:
|
|
37
|
+
* - `name === null` for legacy single-service (only one entry, raw is the spec itself).
|
|
38
|
+
* - `name === <key>` for each services-map entry; `raw` is the per-service ServiceDef.
|
|
39
|
+
*
|
|
40
|
+
* Stable iteration order matches `Object.entries` (insertion order in v8/modern engines).
|
|
41
|
+
*/
|
|
42
|
+
interface NormalizedService {
|
|
43
|
+
/** `null` for legacy single-service; the services-map key for stack leases. */
|
|
44
|
+
name: string | null;
|
|
45
|
+
/** The per-service object exactly as the spec stores it. No field projection. */
|
|
46
|
+
raw: ServiceDef | SingleServiceSpec;
|
|
47
|
+
}
|
|
48
|
+
declare function normalizeServices(spec: DeploySpec | null | undefined): NormalizedService[];
|
|
49
|
+
/**
|
|
50
|
+
* Produce the frozen `SpecSummary` shape for inclusion in the `Plan`
|
|
51
|
+
* (camelCase fields: `serviceCount`, etc.).
|
|
52
|
+
*
|
|
53
|
+
* Port count rules:
|
|
54
|
+
* - SingleServiceSpec `port: number` → +1 port.
|
|
55
|
+
* - SingleServiceSpec `port: number[]` → +length ports.
|
|
56
|
+
* - ServiceDef `ports: number[]` (per type) → +length ports.
|
|
57
|
+
* - ServiceDef `ports` shaped as a Record (older codepath) → +key count.
|
|
58
|
+
*
|
|
59
|
+
* Env key uniqueness is computed across services (one `env_keys` set
|
|
60
|
+
* spans the whole spec); `envCount` is the size of that set; `envKeys`
|
|
61
|
+
* is sorted ascending.
|
|
62
|
+
*/
|
|
63
|
+
declare function summarizeSpec(spec: DeploySpec): SpecSummary;
|
|
64
|
+
/**
|
|
65
|
+
* Validate a `DeploySpec` shape pre-broadcast. Throws `TypeError` on the
|
|
66
|
+
* first violation. The frozen type union (`SingleServiceSpec | StackSpec`)
|
|
67
|
+
* already enforces most structural rules at compile time; this runtime
|
|
68
|
+
* check defends against `unknown`-cast callers and `JSON.parse`-decoded
|
|
69
|
+
* inputs.
|
|
70
|
+
*
|
|
71
|
+
* Rules (mirror fred's `deployApp.ts` input validation):
|
|
72
|
+
* - `spec` must be a non-null object.
|
|
73
|
+
* - Stack: `services` must have ≥1 entry; each entry's `image` must be a
|
|
74
|
+
* non-empty string.
|
|
75
|
+
* - Single: `image` must be a non-empty string.
|
|
76
|
+
* - Mutually exclusive `image` AND `services` not allowed.
|
|
77
|
+
*
|
|
78
|
+
* The high-level `deployApp` in PR 3 layers domain checks on top
|
|
79
|
+
* (`customDomain` shape, `serviceName` membership, etc.).
|
|
80
|
+
*/
|
|
81
|
+
declare function validateSpec(spec: DeploySpec | null | undefined): void;
|
|
82
|
+
//#endregion
|
|
83
|
+
export { NormalizedService, firstImage, isStackSpec, normalizeServices, summarizeSpec, validateSpec };
|
|
84
|
+
//# sourceMappingURL=spec-normalize.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"spec-normalize.d.ts","names":[],"sources":["../../src/internals/spec-normalize.ts"],"mappings":";;;;;AAgCA;;;;;;;;;;AAmBA;;;;;AAyBA;;;;;;iBA5CgB,WAAA,CACd,IAAA,EAAM,UAAA,sBACL,IAAA,IAAQ,SAAA;;;;AAiDX;;;iBAhCgB,UAAA,CAAW,IAAA,EAAM,UAAA;;;;;;AA+DjC;;UAtCiB,iBAAA;EAsC2C;EApC1D,IAAA;EAoC4B;EAlC5B,GAAA,EAAK,UAAA,GAAa,iBAAA;AAAA;AAAA,iBAGJ,iBAAA,CACd,IAAA,EAAM,UAAA,sBACL,iBAAA;AAwFH;;;;;;;;;;;;;;AAAA,iBA3DgB,aAAA,CAAc,IAAA,EAAM,UAAA,GAAa,WAAA;;;;;;;;;;;;;;;;;;iBA2DjC,YAAA,CAAa,IAAA,EAAM,UAAA"}
|