@memrov2/pentcloud-tool-runtime 0.0.0-stage → 0.1.1-dev.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 PentCloud contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,5 @@
1
- # Temporary Holding Version
1
+ # PentCloud tool runtime
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Shared native Cloudflare Durable Object execution support for PentCloud’s tool SDKs: serialized commands, pinned-image verification, bounded binary attachments and native streamed Workflow evidence.
4
+
5
+ Version 0.1.0. See [release and integration instructions](https://github.com/Memrov/PentCloud-tools/blob/main/docs/releases.md). This package does not launch an assessment or deploy an application by itself.
@@ -0,0 +1,3 @@
1
+ # Third-party notices
2
+
3
+ The adapter is MIT licensed. Tool images preserve their original upstream notices. See the repository build metadata and pack documentation for pinned software and assets.
package/package.json CHANGED
@@ -1,6 +1,34 @@
1
1
  {
2
2
  "name": "@memrov2/pentcloud-tool-runtime",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1-dev.0",
4
+ "type": "module",
5
+ "license": "MIT",
6
+ "description": "Cloudflare-native tool-runtime tool pack",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "https://github.com/Memrov/PentCloud-tools.git",
10
+ "directory": "packages/runtime"
11
+ },
12
+ "engines": {
13
+ "node": ">=22"
14
+ },
15
+ "exports": {
16
+ ".": {
17
+ "types": "./src/index.d.mts",
18
+ "import": "./src/index.mjs"
19
+ },
20
+ "./worker": {
21
+ "types": "./src/worker.d.mts",
22
+ "import": "./src/worker.mjs"
23
+ }
24
+ },
25
+ "files": [
26
+ "src",
27
+ "tools.lock.json",
28
+ "LICENSE",
29
+ "THIRD_PARTY_NOTICES.md"
30
+ ],
31
+ "publishConfig": {
32
+ "access": "public"
33
+ }
34
+ }
@@ -0,0 +1,73 @@
1
+ export interface ToolCommand {
2
+ argv: string[];
3
+ stdin: string;
4
+ timeoutMs: number;
5
+ requiredFiles?: string[];
6
+ }
7
+ export interface PackLock {
8
+ packId: string;
9
+ packVersion: string;
10
+ tools: readonly { tool: string; version: string }[];
11
+ }
12
+ export interface ToolResult {
13
+ tool: string;
14
+ toolVersion: string;
15
+ packId: string;
16
+ packVersion: string;
17
+ image: string;
18
+ readyMs: number;
19
+ startedAt: string;
20
+ finishedAt: string;
21
+ argv: string[];
22
+ exitCode: number;
23
+ stdout: string;
24
+ stderr: string;
25
+ timedOut: boolean;
26
+ truncated: boolean;
27
+ error?: string;
28
+ inputHashes?: Record<string, string>;
29
+ processMs: number;
30
+ firstJSONMs: number;
31
+ cpuUserMs: number;
32
+ cpuSystemMs: number;
33
+ maxRSSKiB: number;
34
+ }
35
+ export declare function request(
36
+ input: unknown,
37
+ allowed: string[],
38
+ tools: string[],
39
+ ): URL;
40
+
41
+ export interface StreamStep {
42
+ do(
43
+ name: string,
44
+ config: { retries: { limit: 0; delay: "1 second" }; timeout: "3 minutes" },
45
+ callback: () => Promise<ReadableStream<Uint8Array>>,
46
+ ): Promise<ReadableStream<Uint8Array>>;
47
+ }
48
+ export declare function runWorkflowStep<I>(
49
+ step: StreamStep,
50
+ runner: {
51
+ run(input: I, files?: Record<string, Uint8Array>): Promise<ToolResult>;
52
+ },
53
+ input: I,
54
+ files?: Record<string, Uint8Array>,
55
+ ): Promise<
56
+ Omit<
57
+ ToolResult,
58
+ | "stdout"
59
+ | "stderr"
60
+ | "argv"
61
+ | "processMs"
62
+ | "firstJSONMs"
63
+ | "cpuUserMs"
64
+ | "cpuSystemMs"
65
+ | "maxRSSKiB"
66
+ | "readyMs"
67
+ > & { stdoutBytes: number; stderrBytes: number; evidenceStep: string }
68
+ >;
69
+
70
+ export declare function prepareFiles(
71
+ required: string[],
72
+ files?: Record<string, Uint8Array>,
73
+ ): Promise<Record<string, { base64: string; sha256: string }>>;
package/src/index.mjs ADDED
@@ -0,0 +1,101 @@
1
+ export function request(input, allowed, tools) {
2
+ if (
3
+ !input ||
4
+ typeof input !== "object" ||
5
+ Array.isArray(input) ||
6
+ Object.keys(input).some((k) => !allowed.includes(k)) ||
7
+ !tools.includes(input.tool)
8
+ )
9
+ throw new TypeError("Unsupported tool or request fields");
10
+ if (
11
+ typeof input.target !== "string" ||
12
+ !input.target ||
13
+ input.target.length > 2048 ||
14
+ /[\s\x00-\x1f\x7f\\]/.test(input.target)
15
+ )
16
+ throw new TypeError("Invalid target");
17
+ const url = new URL(input.target);
18
+ if (
19
+ !["http:", "https:"].includes(url.protocol) ||
20
+ !url.hostname ||
21
+ url.username ||
22
+ url.password ||
23
+ url.hash
24
+ )
25
+ throw new TypeError("Use an HTTP(S) URL without credentials or a fragment");
26
+ return url;
27
+ }
28
+
29
+ export async function prepareFiles(required, input = {}) {
30
+ if (
31
+ !input ||
32
+ typeof input !== "object" ||
33
+ Array.isArray(input) ||
34
+ Object.keys(input).length !== required.length ||
35
+ Object.keys(input).some((name) => !required.includes(name))
36
+ )
37
+ throw new TypeError("Supply exactly the required input files");
38
+ let total = 0;
39
+ const files = required.map((name) => {
40
+ const value = input[name];
41
+ if (
42
+ !(value instanceof Uint8Array) ||
43
+ value.byteLength === 0 ||
44
+ (total += value.byteLength) > 2097152
45
+ )
46
+ throw new TypeError("Input files must total at most two MiB");
47
+ return [name, new Uint8Array(value)];
48
+ });
49
+ return Object.fromEntries(
50
+ await Promise.all(
51
+ files.map(async ([name, value]) => {
52
+ const digest = await crypto.subtle.digest("SHA-256", value);
53
+ let binary = "";
54
+ for (let offset = 0; offset < value.length; offset += 8192)
55
+ binary += String.fromCharCode(
56
+ ...value.subarray(offset, offset + 8192),
57
+ );
58
+ return [
59
+ name,
60
+ {
61
+ base64: btoa(binary),
62
+ sha256: [...new Uint8Array(digest)]
63
+ .map((v) => v.toString(16).padStart(2, "0"))
64
+ .join(""),
65
+ },
66
+ ];
67
+ }),
68
+ ),
69
+ );
70
+ }
71
+
72
+ /** Persist full output using Workflows' native stream support; complete with metadata only. */
73
+ export async function runWorkflowStep(step, runner, input, files) {
74
+ const stream = await step.do(
75
+ "tool-evidence",
76
+ { retries: { limit: 0, delay: "1 second" }, timeout: "3 minutes" },
77
+ async () => {
78
+ const result = await runner.run(input, files);
79
+ return new Blob([JSON.stringify(result)], {
80
+ type: "application/json",
81
+ }).stream();
82
+ },
83
+ );
84
+ const result = await new Response(stream).json();
85
+ return {
86
+ packId: result.packId,
87
+ packVersion: result.packVersion,
88
+ tool: result.tool,
89
+ toolVersion: result.toolVersion,
90
+ image: result.image,
91
+ exitCode: result.exitCode,
92
+ timedOut: result.timedOut,
93
+ truncated: result.truncated,
94
+ startedAt: result.startedAt,
95
+ finishedAt: result.finishedAt,
96
+ stdoutBytes: new TextEncoder().encode(result.stdout).length,
97
+ stderrBytes: new TextEncoder().encode(result.stderr).length,
98
+ evidenceStep: "tool-evidence",
99
+ ...(result.inputHashes ? { inputHashes: result.inputHashes } : {}),
100
+ };
101
+ }
@@ -0,0 +1,20 @@
1
+ import { DurableObject } from "cloudflare:workers";
2
+ import type { ToolCommand, ToolResult, PackLock } from "./index.mjs";
3
+ declare class ToolRunner<I> extends DurableObject {
4
+ ready(): Promise<{ image: string; instance: "lite" | "standard-1"; readyMs: number }>;
5
+ run(input: I, files?: Record<string, Uint8Array>): Promise<ToolResult>;
6
+ retire(): Promise<{ stopped: boolean; retired: true }>;
7
+ stop(): Promise<{ stopped: boolean }>;
8
+ capabilities(): Promise<{
9
+ platform: string;
10
+ architecture: string;
11
+ rawPacketSocket: boolean;
12
+ rawPacketError?: string;
13
+ image: string;
14
+ readyMs: number;
15
+ }>;
16
+ }
17
+ export declare function createRunner<I>(
18
+ lock: PackLock,
19
+ buildCommand: (input: I) => ToolCommand,
20
+ ): new (ctx: DurableObjectState, env: unknown) => ToolRunner<I>;
package/src/worker.mjs ADDED
@@ -0,0 +1,168 @@
1
+ import { DurableObject } from "cloudflare:workers";
2
+ import { prepareFiles } from "./index.mjs";
3
+ const decode = (data) => new TextDecoder().decode(data);
4
+ const hash = async (value) =>
5
+ [
6
+ ...new Uint8Array(
7
+ await crypto.subtle.digest(
8
+ "SHA-256",
9
+ new TextEncoder().encode(JSON.stringify(value)),
10
+ ),
11
+ ),
12
+ ]
13
+ .map((x) => x.toString(16).padStart(2, "0"))
14
+ .join("");
15
+ async function exec(container, argv, body, signal) {
16
+ const process = await container.exec(argv, {
17
+ signal,
18
+ ...(body ? { stdin: new Blob([body]).stream() } : {}),
19
+ });
20
+ const result = await process.output();
21
+ return {
22
+ exitCode: result.exitCode,
23
+ stdout: decode(result.stdout),
24
+ stderr: decode(result.stderr),
25
+ };
26
+ }
27
+ export function createRunner(lock, buildCommand) {
28
+ const root = "/opt/pentcloud-" + lock.packId;
29
+ return class ToolRunner extends DurableObject {
30
+ #queue = Promise.resolve();
31
+ #serialize(action) {
32
+ const result = this.#queue.then(action);
33
+ this.#queue = result.catch(() => {});
34
+ return result;
35
+ }
36
+ async #ready() {
37
+ if (await this.ctx.storage.get("retired")) throw new Error("Owned tool runtime is retired");
38
+ const container = this.ctx.container,
39
+ image = container.images[lock.packId],
40
+ start = Date.now();
41
+ if (!image)
42
+ throw new Error("Configure the " + lock.packId + " named image");
43
+ if (container.running) {
44
+ if ((await container.inspect())?.image !== image)
45
+ throw new Error(
46
+ "Image changed; stop the current runtime before upgrading",
47
+ );
48
+ } else
49
+ container.start({
50
+ image,
51
+ instance: lock.packId === "password" ? "standard-1" : "lite",
52
+ enableInternet: lock.runtime?.enableInternet ?? true,
53
+ labels: { pack: lock.packId, version: lock.packVersion },
54
+ });
55
+ await container.setInactivityTimeout(120000);
56
+ const signal = AbortSignal.timeout(90000);
57
+ while (true) {
58
+ try {
59
+ if (
60
+ (await exec(container, ["/bin/true"], undefined, signal))
61
+ .exitCode === 0
62
+ )
63
+ break;
64
+ } catch (error) {
65
+ if (signal.aborted)
66
+ throw new Error("Container readiness exceeded 90 seconds");
67
+ }
68
+ if (signal.aborted || Date.now() - start >= 90000)
69
+ throw new Error("Container readiness exceeded 90 seconds");
70
+ await new Promise((resolve) =>
71
+ setTimeout(resolve, Math.min(1000, 90000 - (Date.now() - start))),
72
+ );
73
+ }
74
+ const marker = await exec(
75
+ container,
76
+ ["/bin/cat", root + "/pack.json"],
77
+ undefined,
78
+ signal,
79
+ );
80
+ let release;
81
+ try {
82
+ release = JSON.parse(marker.stdout);
83
+ } catch {
84
+ throw new Error("Invalid pack image manifest");
85
+ }
86
+ if (marker.exitCode !== 0 || release.lockSha256 !== (await hash(lock)))
87
+ throw new Error("Pack image and SDK pins do not match");
88
+ if ((await container.inspect())?.image !== image)
89
+ throw new Error("Unable to verify pack image identity");
90
+ return { image, instance: lock.packId === "password" ? "standard-1" : "lite", readyMs: Date.now() - start };
91
+ }
92
+ ready() {
93
+ return this.#serialize(() => this.#ready());
94
+ }
95
+ run(input, files) {
96
+ const { requiredFiles = [], ...command } = buildCommand(input),
97
+ tool = input.tool;
98
+ const prepared = prepareFiles(requiredFiles, files);
99
+ prepared.catch(() => {});
100
+ return this.#serialize(async () => {
101
+ const attachments = await prepared;
102
+ const startedAt = new Date().toISOString(),
103
+ ready = await this.#ready();
104
+ const output = await exec(
105
+ this.ctx.container,
106
+ [root + "/bin/pack-exec"],
107
+ JSON.stringify({
108
+ ...command,
109
+ ...(Object.keys(attachments).length ? { files: attachments } : {}),
110
+ }),
111
+ AbortSignal.timeout(90000),
112
+ );
113
+ if (output.exitCode !== 0)
114
+ throw new Error("Pack execution helper failed");
115
+ let result;
116
+ try {
117
+ result = JSON.parse(output.stdout);
118
+ } catch {
119
+ throw new Error("Invalid pack execution response");
120
+ }
121
+ if (
122
+ !Number.isInteger(result.exitCode) ||
123
+ typeof result.stdout !== "string" ||
124
+ typeof result.stderr !== "string" ||
125
+ typeof result.timedOut !== "boolean" ||
126
+ typeof result.truncated !== "boolean"
127
+ )
128
+ throw new Error("Incomplete pack execution response");
129
+ return {
130
+ ...result,
131
+ ...ready,
132
+ tool,
133
+ toolVersion: lock.tools.find((t) => t.tool === tool).version,
134
+ packId: lock.packId,
135
+ packVersion: lock.packVersion,
136
+ startedAt,
137
+ finishedAt: new Date().toISOString(),
138
+ };
139
+ });
140
+ }
141
+ retire() {
142
+ return this.#serialize(async () => {
143
+ await this.ctx.storage.put("retired", true);
144
+ if (this.ctx.container.running) await this.ctx.container.destroy();
145
+ return { stopped: !this.ctx.container.running, retired: true };
146
+ });
147
+ }
148
+ stop() {
149
+ return this.#serialize(async () => {
150
+ if (this.ctx.container.running) await this.ctx.container.destroy();
151
+ return { stopped: !this.ctx.container.running };
152
+ });
153
+ }
154
+ capabilities() {
155
+ return this.#serialize(async () => {
156
+ const ready = await this.#ready();
157
+ const result = await exec(
158
+ this.ctx.container,
159
+ [root + "/bin/pack-exec", "--capabilities"],
160
+ undefined,
161
+ AbortSignal.timeout(10000),
162
+ );
163
+ if (result.exitCode !== 0) throw new Error("Capability probe failed");
164
+ return { ...JSON.parse(result.stdout), ...ready };
165
+ });
166
+ }
167
+ };
168
+ }