pantheon-opencode 1.4.3 → 1.5.0-beta.10
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/.pantheon/code-mode/README.md +93 -0
- package/.pantheon/code-mode/checkpoint-session.py +7 -0
- package/.pantheon/code-mode/checkpoint-session.sh +11 -0
- package/.pantheon/code-mode/checkpoint_session.py +481 -0
- package/.pantheon/code-mode/compress-inline.py +450 -0
- package/.pantheon/code-mode/eval-llm-judge.py +255 -0
- package/.pantheon/code-mode/eval-monte-carlo.py +368 -0
- package/.pantheon/code-mode/eval-run.py +197 -0
- package/.pantheon/code-mode/eval-static.py +321 -0
- package/.pantheon/code-mode/example-sync.sh +5 -0
- package/.pantheon/code-mode/manifest.json +21 -0
- package/.pantheon/code-mode/session-end-save.py +186 -0
- package/.pantheon/code-mode/session-end-save.sh +18 -0
- package/.pantheon/code-mode/test-allowed.sh +5 -0
- package/.pantheon/code-mode/test-auto-continue-checkpoint.sh +179 -0
- package/.pantheon/code-mode/test-env.sh +7 -0
- package/.pantheon/code-mode/test-prlimit.sh +9 -0
- package/.pantheon/code-mode/test-timeout.sh +6 -0
- package/CHANGELOG.md +1026 -0
- package/README.md +292 -1080
- package/README.pt-BR.md +308 -0
- package/bin/pantheon-init.mjs +207 -31
- package/opencode.json +1 -0
- package/package.json +34 -14
- package/plugin.json +15 -0
- package/pyproject.toml +65 -0
- package/scripts/_pantheon_paths.py +48 -7
- package/scripts/ci-validate-yaml.py +7 -2
- package/scripts/code_mode_server.py +451 -44
- package/scripts/cost.mjs +30 -14
- package/scripts/doctor.mjs +306 -129
- package/scripts/generate-preset-docs.mjs +127 -66
- package/scripts/generate-prompts.sh +2 -2
- package/scripts/install/cli-ui.mjs +23 -10
- package/scripts/install/config-migration.mjs +399 -0
- package/scripts/install/health-check.mjs +3 -3
- package/scripts/install/model-picker.mjs +72 -23
- package/scripts/install/opencode-version.mjs +47 -0
- package/scripts/install/opencode.mjs +396 -121
- package/scripts/install/plugin.mjs +89 -49
- package/scripts/install/shared.mjs +55 -159
- package/scripts/install/strings.mjs +129 -0
- package/scripts/install-mcp.mjs +45 -232
- package/scripts/manifest-inventory.mjs +410 -0
- package/scripts/mcp_persistence_server.py +798 -60
- package/scripts/mcp_resources_server.py +144 -40
- package/scripts/memory_mcp_server.py +2 -2
- package/scripts/package-evidence.mjs +242 -0
- package/scripts/probe-context-rehydrate.mjs +240 -0
- package/scripts/probe-pantheon-cost.mjs +313 -0
- package/scripts/recover-zenodo-deposition.mjs +146 -0
- package/scripts/release-beta-version.mjs +56 -60
- package/scripts/sync-artifacts.mjs +169 -0
- package/scripts/sync-tui.mjs +135 -42
- package/scripts/test-opencode-v1-v2-sandbox.sh +862 -0
- package/scripts/uninstall.mjs +298 -954
- package/scripts/validate-zenodo-release.mjs +154 -0
- package/scripts/validation-policy.mjs +7 -7
- package/scripts/version-check.mjs +113 -108
- package/scripts/versioning.mjs +230 -86
- package/scripts/zenodo-artifact.mjs +21 -0
- package/scripts/zenodo-release-state.mjs +53 -0
- package/src/agents/mnemosyne.md +1 -1
- package/src/agents/zeus.md +27 -16
- package/src/mcp/_pantheon_paths.py +48 -7
- package/src/mcp/code_mode_server.py +451 -44
- package/src/mcp/eval_store.py +1 -1
- package/src/mcp/mcp_persistence_server.py +798 -60
- package/src/mcp/mcp_resources_server.py +144 -40
- package/src/mcp/pantheon_vision_server.py +1 -1
- package/src/mcp/toon_codec.py +491 -0
- package/src/pantheon/auto-wake.ts +1 -5
- package/src/pantheon/background-job-board.ts +110 -2
- package/src/pantheon/compaction-handoff.ts +304 -0
- package/src/pantheon/cost-command.ts +356 -69
- package/src/pantheon/delegate-manager.ts +766 -0
- package/src/pantheon/delegation-classifier.ts +307 -0
- package/src/pantheon/delegation-enforce.ts +13 -12
- package/src/pantheon/delegation-finalize.ts +406 -0
- package/src/pantheon/delegation-notify.ts +212 -0
- package/src/pantheon/delegation-toast.ts +73 -0
- package/src/pantheon/delegation.ts +1337 -0
- package/src/pantheon/file-persistence-salvage.ts +64 -0
- package/src/pantheon/file-persistence.ts +194 -45
- package/src/pantheon/goal-loop.ts +2 -2
- package/src/pantheon/goal-store.ts +1 -1
- package/src/pantheon/hashline/tool.ts +2 -2
- package/src/pantheon/model-command.ts +2 -1
- package/src/pantheon/native-probe.ts +234 -0
- package/src/pantheon/native-task-status.ts +139 -0
- package/src/pantheon/permission-eval.ts +284 -0
- package/src/pantheon/provider-capabilities.ts +221 -0
- package/src/pantheon/provider-stream-tracker.ts +182 -0
- package/src/pantheon/shared-board.ts +37 -0
- package/src/pantheon/step-cap.ts +110 -0
- package/src/pantheon/task-result-guard.ts +107 -0
- package/src/pantheon/token-opt.ts +689 -0
- package/src/pantheon/tool-ceiling.ts +159 -0
- package/src/pantheon/toon-codec.ts +481 -0
- package/src/pantheon/tui-version-check.ts +1 -3
- package/src/pantheon/v2-bridge.ts +129 -0
- package/src/pantheon/v2-events.ts +148 -0
- package/src/pantheon/v2-hooks.ts +287 -0
- package/src/pantheon/v2-tool-definitions.ts +331 -0
- package/src/pantheon/zeus-delegate-with-retry.ts +406 -0
- package/src/plugin-v2/index.ts +21 -0
- package/src/plugin-v2.ts +824 -0
- package/src/plugin.ts +261 -51
- package/src/plugins/pantheon-hooks.ts +51 -0
- package/src/plugins/tui/dist/tui.d.ts +116 -24
- package/src/plugins/tui/dist/tui.d.ts.map +1 -1
- package/src/plugins/tui/dist/tui.js +416 -149
- package/src/plugins/tui/dist/tui.tsx +456 -87
- package/src/plugins/tui/package-lock.json +51 -51
- package/src/plugins/tui/package.json +7 -7
- package/src/plugins/tui/src/index.tsx +462 -95
- package/src/skills/README.md +0 -2
- package/src/pantheon/tool-context.ts +0 -41
|
@@ -17,7 +17,7 @@ from pathlib import Path
|
|
|
17
17
|
from typing import Any
|
|
18
18
|
|
|
19
19
|
import yaml
|
|
20
|
-
from _pantheon_paths import pantheon_home, pantheon_project
|
|
20
|
+
from _pantheon_paths import has_symlink_component, pantheon_home, pantheon_project
|
|
21
21
|
from eval_store import get_latest_eval, list_evals
|
|
22
22
|
from mcp.server.fastmcp import FastMCP
|
|
23
23
|
|
|
@@ -25,6 +25,88 @@ from mcp.server.fastmcp import FastMCP
|
|
|
25
25
|
_PANTHEON_HOME: Path = pantheon_home()
|
|
26
26
|
_PANTHEON_PROJECT: Path | None = pantheon_project()
|
|
27
27
|
|
|
28
|
+
|
|
29
|
+
def _within(path: Path, parent: Path) -> bool:
|
|
30
|
+
"""Return whether ``path`` is contained by ``parent`` after resolution."""
|
|
31
|
+
try:
|
|
32
|
+
path.relative_to(parent)
|
|
33
|
+
except ValueError:
|
|
34
|
+
return False
|
|
35
|
+
return True
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _safe_root(root: Path, parent: Path) -> Path | None:
|
|
39
|
+
"""Return a physical resource root only when its layout is trusted.
|
|
40
|
+
|
|
41
|
+
Local ``.opencode`` and ``.pantheon`` directories are trust boundaries:
|
|
42
|
+
accepting either as a symlink would make all resources below it
|
|
43
|
+
untrusted, even when the link happens to point inside the project.
|
|
44
|
+
"""
|
|
45
|
+
if parent.is_symlink() or has_symlink_component(parent):
|
|
46
|
+
return None
|
|
47
|
+
# Keep the project root lexical until this trust-boundary check. This
|
|
48
|
+
# rejects PANTHEON_PROJECT/cwd symlinks instead of resolving them away.
|
|
49
|
+
if parent.name in {".opencode", ".pantheon"} and parent.parent.is_symlink():
|
|
50
|
+
return None
|
|
51
|
+
if root.is_symlink():
|
|
52
|
+
return None
|
|
53
|
+
if not root.exists() or not root.is_dir():
|
|
54
|
+
return None
|
|
55
|
+
parent_resolved = parent.resolve()
|
|
56
|
+
resolved = root.resolve()
|
|
57
|
+
if parent.name in {".opencode", ".pantheon"} and not _within(
|
|
58
|
+
parent_resolved, parent.parent.resolve()
|
|
59
|
+
):
|
|
60
|
+
return None
|
|
61
|
+
return resolved if _within(resolved, parent_resolved) else None
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def _resource_root(name: str) -> Path | None:
|
|
65
|
+
"""Choose a project-local root before the global installation root.
|
|
66
|
+
|
|
67
|
+
A present but unsafe project root is ignored rather than followed; this
|
|
68
|
+
preserves the global fallback while preventing symlink escapes.
|
|
69
|
+
"""
|
|
70
|
+
candidates: list[tuple[Path, Path]] = []
|
|
71
|
+
if _PANTHEON_PROJECT is not None:
|
|
72
|
+
if name in {"agents", "skills"}:
|
|
73
|
+
local = _PANTHEON_PROJECT / ".opencode"
|
|
74
|
+
candidates.append((local / name, local))
|
|
75
|
+
elif name in {"deepwork", "memory-bank"}:
|
|
76
|
+
local = _PANTHEON_PROJECT / ".pantheon"
|
|
77
|
+
candidates.append((local / name, local))
|
|
78
|
+
candidates.append((_PANTHEON_HOME / name, _PANTHEON_HOME))
|
|
79
|
+
for root, parent in candidates:
|
|
80
|
+
safe = _safe_root(root, parent)
|
|
81
|
+
if safe is not None:
|
|
82
|
+
return safe
|
|
83
|
+
return None
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def _resource_roots(name: str) -> list[Path]:
|
|
87
|
+
"""Return safe resource roots in local-first precedence order."""
|
|
88
|
+
roots: list[Path] = []
|
|
89
|
+
if _PANTHEON_PROJECT is not None:
|
|
90
|
+
base_name = ".opencode" if name in {"agents", "skills"} else ".pantheon"
|
|
91
|
+
base = _PANTHEON_PROJECT / base_name
|
|
92
|
+
local = _safe_root(base / name, base)
|
|
93
|
+
if local is not None:
|
|
94
|
+
roots.append(local)
|
|
95
|
+
global_root = _safe_root(_PANTHEON_HOME / name, _PANTHEON_HOME)
|
|
96
|
+
if global_root is not None:
|
|
97
|
+
roots.append(global_root)
|
|
98
|
+
return roots
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def _safe_child(root: Path, relative: str) -> Path | None:
|
|
102
|
+
"""Resolve a child while rejecting every lexical symlink component."""
|
|
103
|
+
candidate = root / relative
|
|
104
|
+
if has_symlink_component(candidate):
|
|
105
|
+
return None
|
|
106
|
+
resolved = candidate.resolve()
|
|
107
|
+
return resolved if _within(resolved, root.resolve()) else None
|
|
108
|
+
|
|
109
|
+
|
|
28
110
|
# ── FastMCP App ───────────────────────────────────────────────────────────────
|
|
29
111
|
mcp = FastMCP(
|
|
30
112
|
"Pantheon Resources",
|
|
@@ -67,17 +149,27 @@ def _get_role_from_frontmatter(frontmatter: dict[str, Any]) -> str:
|
|
|
67
149
|
)
|
|
68
150
|
async def list_agents() -> str:
|
|
69
151
|
"""Return a markdown list of all agents with their roles."""
|
|
70
|
-
|
|
71
|
-
if not
|
|
152
|
+
agents_dirs = _resource_roots("agents")
|
|
153
|
+
if not agents_dirs:
|
|
72
154
|
return "Agents directory not found."
|
|
73
155
|
|
|
74
156
|
agents: list[str] = []
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
157
|
+
seen: set[str] = set()
|
|
158
|
+
for agents_dir in agents_dirs:
|
|
159
|
+
for entry in sorted(agents_dir.iterdir()):
|
|
160
|
+
f = _safe_child(agents_dir, entry.name)
|
|
161
|
+
if (
|
|
162
|
+
f is not None
|
|
163
|
+
and f.is_file()
|
|
164
|
+
and f.suffix == ".md"
|
|
165
|
+
and f.stem.lower() != "readme"
|
|
166
|
+
and f.name not in seen
|
|
167
|
+
):
|
|
168
|
+
seen.add(f.name)
|
|
169
|
+
frontmatter = _parse_yaml_frontmatter(f)
|
|
170
|
+
name = frontmatter.get("name", f.stem)
|
|
171
|
+
role = _get_role_from_frontmatter(frontmatter)
|
|
172
|
+
agents.append(f"- **{name}** — {role}")
|
|
81
173
|
|
|
82
174
|
return "\n".join(agents) if agents else "No agents found."
|
|
83
175
|
|
|
@@ -88,19 +180,23 @@ async def list_agents() -> str:
|
|
|
88
180
|
)
|
|
89
181
|
async def list_skills() -> str:
|
|
90
182
|
"""Return a markdown list of all skills with descriptions."""
|
|
91
|
-
|
|
92
|
-
if not
|
|
183
|
+
skills_dirs = _resource_roots("skills")
|
|
184
|
+
if not skills_dirs:
|
|
93
185
|
return "Skills directory not found."
|
|
94
186
|
|
|
95
187
|
skills: list[str] = []
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
188
|
+
seen: set[str] = set()
|
|
189
|
+
for skills_dir in skills_dirs:
|
|
190
|
+
for entry in sorted(skills_dir.iterdir()):
|
|
191
|
+
f = _safe_child(skills_dir, entry.name)
|
|
192
|
+
if f is not None and f.is_dir() and f.name not in seen:
|
|
193
|
+
skill_file = _safe_child(f, "SKILL.md")
|
|
194
|
+
if skill_file is not None and skill_file.is_file():
|
|
195
|
+
seen.add(f.name)
|
|
196
|
+
frontmatter = _parse_yaml_frontmatter(skill_file)
|
|
197
|
+
name = frontmatter.get("name", f.name)
|
|
198
|
+
desc = frontmatter.get("description", "No description")
|
|
199
|
+
skills.append(f"- **{name}** — {desc}")
|
|
104
200
|
|
|
105
201
|
return "\n".join(skills) if skills else "No skills found."
|
|
106
202
|
|
|
@@ -111,10 +207,10 @@ async def list_skills() -> str:
|
|
|
111
207
|
)
|
|
112
208
|
async def get_routing() -> str:
|
|
113
209
|
"""Return the full content of routing.yml."""
|
|
114
|
-
routing_file = _PANTHEON_HOME
|
|
115
|
-
if
|
|
116
|
-
routing_file = _PANTHEON_PROJECT / "src"
|
|
117
|
-
if not routing_file.exists():
|
|
210
|
+
routing_file = _safe_child(_PANTHEON_HOME, "routing.yml")
|
|
211
|
+
if routing_file is None and _PANTHEON_PROJECT:
|
|
212
|
+
routing_file = _safe_child(_PANTHEON_PROJECT / "src", "routing.yml")
|
|
213
|
+
if routing_file is None or not routing_file.exists():
|
|
118
214
|
return "routing.yml not found."
|
|
119
215
|
return routing_file.read_text(encoding="utf-8")
|
|
120
216
|
|
|
@@ -128,11 +224,17 @@ async def get_routing() -> str:
|
|
|
128
224
|
)
|
|
129
225
|
async def get_agent(agent_name: str) -> str:
|
|
130
226
|
"""Return the full content of an agent file, case-insensitively."""
|
|
131
|
-
agents_dir = _PANTHEON_HOME / "agents"
|
|
132
227
|
name_lower = agent_name.lower()
|
|
133
|
-
for
|
|
134
|
-
|
|
135
|
-
|
|
228
|
+
for agents_dir in _resource_roots("agents"):
|
|
229
|
+
for entry in agents_dir.iterdir():
|
|
230
|
+
f = _safe_child(agents_dir, entry.name)
|
|
231
|
+
if (
|
|
232
|
+
f is not None
|
|
233
|
+
and f.is_file()
|
|
234
|
+
and f.suffix == ".md"
|
|
235
|
+
and f.stem.lower() == name_lower
|
|
236
|
+
):
|
|
237
|
+
return f.read_text(encoding="utf-8")
|
|
136
238
|
return f"Agent '{agent_name}' not found."
|
|
137
239
|
|
|
138
240
|
|
|
@@ -142,10 +244,11 @@ async def get_agent(agent_name: str) -> str:
|
|
|
142
244
|
)
|
|
143
245
|
async def get_deepwork_plan(slug: str) -> str:
|
|
144
246
|
"""Return PLAN.md content for a deepwork slug."""
|
|
145
|
-
|
|
247
|
+
deepwork_dir = _resource_root("deepwork")
|
|
248
|
+
if deepwork_dir is None:
|
|
146
249
|
return f"Deepwork '{slug}' not found. (PANTHEON_PROJECT not set)"
|
|
147
|
-
plan_file =
|
|
148
|
-
if not plan_file.
|
|
250
|
+
plan_file = _safe_child(deepwork_dir, f"{slug}/PLAN.md")
|
|
251
|
+
if plan_file is None or not plan_file.is_file():
|
|
149
252
|
return f"Deepwork '{slug}' not found."
|
|
150
253
|
return plan_file.read_text(encoding="utf-8")
|
|
151
254
|
|
|
@@ -157,10 +260,11 @@ async def get_deepwork_plan(slug: str) -> str:
|
|
|
157
260
|
)
|
|
158
261
|
async def get_deepwork_status(slug: str) -> str:
|
|
159
262
|
"""Return STATUS.md content for a deepwork slug, or a default message."""
|
|
160
|
-
|
|
263
|
+
deepwork_dir = _resource_root("deepwork")
|
|
264
|
+
if deepwork_dir is None:
|
|
161
265
|
return "STATUS.md not found. (PANTHEON_PROJECT not set)"
|
|
162
|
-
status_file =
|
|
163
|
-
if not status_file.
|
|
266
|
+
status_file = _safe_child(deepwork_dir, f"{slug}/STATUS.md")
|
|
267
|
+
if status_file is None or not status_file.is_file():
|
|
164
268
|
return "STATUS.md not found. Current state: IN PROGRESS"
|
|
165
269
|
return status_file.read_text(encoding="utf-8")
|
|
166
270
|
|
|
@@ -171,8 +275,9 @@ async def get_deepwork_status(slug: str) -> str:
|
|
|
171
275
|
)
|
|
172
276
|
async def get_skill(name: str) -> str:
|
|
173
277
|
"""Return SKILL.md content for a skill directory."""
|
|
174
|
-
|
|
175
|
-
|
|
278
|
+
skills_dir = _resource_root("skills")
|
|
279
|
+
skill_file = _safe_child(skills_dir, f"{name}/SKILL.md") if skills_dir else None
|
|
280
|
+
if skill_file is None or not skill_file.is_file():
|
|
176
281
|
return f"Skill '{name}' not found."
|
|
177
282
|
return skill_file.read_text(encoding="utf-8")
|
|
178
283
|
|
|
@@ -188,12 +293,11 @@ async def get_memory_bank(path: str) -> str:
|
|
|
188
293
|
Security: resolves absolute path and verifies it stays within
|
|
189
294
|
.pantheon/memory-bank/ to prevent directory traversal attacks.
|
|
190
295
|
"""
|
|
191
|
-
|
|
296
|
+
memory_dir = _resource_root("memory-bank")
|
|
297
|
+
if memory_dir is None:
|
|
192
298
|
return "Memory bank not available. (PANTHEON_PROJECT not set)"
|
|
193
|
-
resolved = (
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
if not str(resolved).startswith(str(mb_dir)):
|
|
299
|
+
resolved = _safe_child(memory_dir, path)
|
|
300
|
+
if resolved is None:
|
|
197
301
|
return "Path traversal blocked: access denied."
|
|
198
302
|
|
|
199
303
|
if not resolved.exists() or not resolved.is_file():
|
|
@@ -25,7 +25,7 @@ import json
|
|
|
25
25
|
import os
|
|
26
26
|
import sqlite3
|
|
27
27
|
import time
|
|
28
|
-
from datetime import
|
|
28
|
+
from datetime import UTC, datetime
|
|
29
29
|
from pathlib import Path
|
|
30
30
|
from typing import Any
|
|
31
31
|
|
|
@@ -198,7 +198,7 @@ def _parse_iso_ts(value: str) -> float:
|
|
|
198
198
|
"""
|
|
199
199
|
dt = datetime.fromisoformat(value.replace("Z", "+00:00"))
|
|
200
200
|
if dt.tzinfo is None:
|
|
201
|
-
dt = dt.replace(tzinfo=
|
|
201
|
+
dt = dt.replace(tzinfo=UTC)
|
|
202
202
|
return dt.timestamp()
|
|
203
203
|
|
|
204
204
|
|
|
@@ -0,0 +1,242 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/** Build and verify the single immutable npm package evidence artifact. */
|
|
3
|
+
|
|
4
|
+
import { execFileSync } from 'node:child_process'
|
|
5
|
+
import { createHash } from 'node:crypto'
|
|
6
|
+
import {
|
|
7
|
+
existsSync,
|
|
8
|
+
lstatSync,
|
|
9
|
+
mkdirSync,
|
|
10
|
+
mkdtempSync,
|
|
11
|
+
readdirSync,
|
|
12
|
+
readFileSync,
|
|
13
|
+
realpathSync,
|
|
14
|
+
rmSync,
|
|
15
|
+
writeFileSync,
|
|
16
|
+
} from 'node:fs'
|
|
17
|
+
import { tmpdir } from 'node:os'
|
|
18
|
+
import { isAbsolute, join } from 'node:path'
|
|
19
|
+
import { validateInventory } from './manifest-inventory.mjs'
|
|
20
|
+
|
|
21
|
+
const CI_ARGS = ['ci', '--ignore-scripts', '--omit=dev', '--no-audit', '--no-fund']
|
|
22
|
+
const REQUIRED_PAYLOAD = [
|
|
23
|
+
'package/package.json',
|
|
24
|
+
'package/plugin.json',
|
|
25
|
+
'package/pyproject.toml',
|
|
26
|
+
'package/src/plugins/tui/package.json',
|
|
27
|
+
'package/src/plugins/tui/package-lock.json',
|
|
28
|
+
'package/src/plugin.ts',
|
|
29
|
+
'package/src/plugin-v2.ts',
|
|
30
|
+
'package/src/pantheon/v2-bridge.ts',
|
|
31
|
+
'package/src/plugins/tui/dist/tui.js',
|
|
32
|
+
'package/src/plugins/tui/dist/server.js',
|
|
33
|
+
'package/bin/pantheon-init.mjs',
|
|
34
|
+
'package/scripts/doctor.mjs',
|
|
35
|
+
'package/.pantheon/code-mode/compress-inline.py',
|
|
36
|
+
]
|
|
37
|
+
|
|
38
|
+
function fail(message) {
|
|
39
|
+
throw new Error(message)
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function resolveTargetSha(root, supplied) {
|
|
43
|
+
const raw =
|
|
44
|
+
supplied ?? execFileSync('git', ['rev-parse', 'HEAD'], { cwd: root, encoding: 'utf8' })
|
|
45
|
+
const sha = String(raw).trim().toLowerCase()
|
|
46
|
+
if (!/^[0-9a-f]{40}$/.test(sha))
|
|
47
|
+
fail('target SHA must be a full lowercase 40-character hexadecimal SHA')
|
|
48
|
+
return sha
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function createOutputDirectory(outputDir) {
|
|
52
|
+
const directory = outputDir ?? mkdtempSync(join(tmpdir(), 'pantheon-package-evidence-'))
|
|
53
|
+
mkdirSync(directory, { recursive: true })
|
|
54
|
+
if (readdirSync(directory).length !== 0) fail(`output directory must be empty: ${directory}`)
|
|
55
|
+
return { directory }
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function packOnce(root, outputDir) {
|
|
59
|
+
const raw = execFileSync(
|
|
60
|
+
'npm',
|
|
61
|
+
['pack', '--ignore-scripts', '--json', '--pack-destination', outputDir],
|
|
62
|
+
{ cwd: root, encoding: 'utf8', maxBuffer: 16 * 1024 * 1024 },
|
|
63
|
+
)
|
|
64
|
+
let result
|
|
65
|
+
try {
|
|
66
|
+
result = JSON.parse(raw)
|
|
67
|
+
} catch (error) {
|
|
68
|
+
fail(`npm pack returned malformed JSON: ${error.message}`)
|
|
69
|
+
}
|
|
70
|
+
if (!Array.isArray(result) || result.length !== 1 || typeof result[0]?.filename !== 'string') {
|
|
71
|
+
fail('npm pack must produce exactly one JSON result')
|
|
72
|
+
}
|
|
73
|
+
const tgzFiles = readdirSync(outputDir).filter((name) => name.endsWith('.tgz'))
|
|
74
|
+
if (tgzFiles.length !== 1)
|
|
75
|
+
fail(`package evidence requires exactly one .tgz, found ${tgzFiles.length}`)
|
|
76
|
+
if (tgzFiles[0] !== result[0].filename)
|
|
77
|
+
fail('npm pack result does not identify the sole .tgz artifact')
|
|
78
|
+
return join(outputDir, tgzFiles[0])
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
function validateArchiveEntries(tarball) {
|
|
82
|
+
const listing = execFileSync('tar', ['-tzf', tarball], { encoding: 'utf8' })
|
|
83
|
+
const entries = listing.split('\n').filter(Boolean)
|
|
84
|
+
if (entries.length === 0) fail('package tarball is empty')
|
|
85
|
+
for (const entry of entries) {
|
|
86
|
+
const normalized = entry.replace(/\/$/, '')
|
|
87
|
+
const parts = normalized.split('/')
|
|
88
|
+
if (
|
|
89
|
+
isAbsolute(normalized) ||
|
|
90
|
+
normalized.includes('\\') ||
|
|
91
|
+
parts.includes('..') ||
|
|
92
|
+
(!normalized.startsWith('package/') && normalized !== 'package')
|
|
93
|
+
) {
|
|
94
|
+
fail(`unsafe package archive entry: ${entry}`)
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
const detailed = execFileSync('tar', ['-tvzf', tarball], { encoding: 'utf8' })
|
|
98
|
+
for (const line of detailed.split('\n').filter(Boolean)) {
|
|
99
|
+
if (/^[lh]/i.test(line)) fail(`package archive contains a link entry: ${line}`)
|
|
100
|
+
}
|
|
101
|
+
return new Set(entries)
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
function extractSafely(tarball, workDir) {
|
|
105
|
+
const extractionRoot = join(workDir, 'extract')
|
|
106
|
+
mkdirSync(extractionRoot)
|
|
107
|
+
validateArchiveEntries(tarball)
|
|
108
|
+
execFileSync(
|
|
109
|
+
'tar',
|
|
110
|
+
['-xzf', tarball, '--directory', extractionRoot, '--no-same-owner', '--no-same-permissions'],
|
|
111
|
+
{ encoding: 'utf8' },
|
|
112
|
+
)
|
|
113
|
+
const realRoot = realpathSync(extractionRoot)
|
|
114
|
+
const walk = (current) => {
|
|
115
|
+
const stat = lstatSync(current)
|
|
116
|
+
if (stat.isSymbolicLink()) fail(`package archive extraction contains a symlink: ${current}`)
|
|
117
|
+
const resolved = realpathSync(current)
|
|
118
|
+
if (resolved !== realRoot && !resolved.startsWith(`${realRoot}/`)) {
|
|
119
|
+
fail(`package archive extraction escaped its temporary directory: ${current}`)
|
|
120
|
+
}
|
|
121
|
+
if (stat.isDirectory()) for (const name of readdirSync(current)) walk(join(current, name))
|
|
122
|
+
}
|
|
123
|
+
walk(extractionRoot)
|
|
124
|
+
return join(extractionRoot, 'package')
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
function validatePayload(packageRoot, inventory) {
|
|
128
|
+
for (const relativePath of REQUIRED_PAYLOAD) {
|
|
129
|
+
const path = join(packageRoot, relativePath.replace(/^package\//, ''))
|
|
130
|
+
if (!existsSync(path) || !lstatSync(path).isFile())
|
|
131
|
+
fail(`required package payload is missing: ${relativePath}`)
|
|
132
|
+
}
|
|
133
|
+
for (const document of inventory.documents) {
|
|
134
|
+
const { entry, path: sourcePath } = document
|
|
135
|
+
const packagedPath = join(packageRoot, entry.file)
|
|
136
|
+
if (entry.role === 'lock' && entry.file === 'package-lock.json' && !existsSync(packagedPath)) {
|
|
137
|
+
// npm-packlist excludes the package root lockfile by policy. It remains
|
|
138
|
+
// validated below as source evidence, but is not fabricated in the tgz.
|
|
139
|
+
continue
|
|
140
|
+
}
|
|
141
|
+
if (!existsSync(packagedPath) || !lstatSync(packagedPath).isFile())
|
|
142
|
+
fail(`versioned package payload is missing: package/${entry.file}`)
|
|
143
|
+
if (sha256(sourcePath) !== sha256(packagedPath))
|
|
144
|
+
fail(`published package payload differs from source: ${entry.file}`)
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
function collectLockfileEvidence(inventory, entries, packageRoot) {
|
|
149
|
+
return inventory.documents
|
|
150
|
+
.filter(({ entry }) => entry.role === 'lock')
|
|
151
|
+
.map(({ entry, data, path: sourcePath }) => {
|
|
152
|
+
const archivePath = `package/${entry.file}`
|
|
153
|
+
const packagedPath = join(packageRoot, entry.file)
|
|
154
|
+
const publishedInTarball = entries.has(archivePath)
|
|
155
|
+
return {
|
|
156
|
+
file: entry.file,
|
|
157
|
+
sourceSha256: sha256(sourcePath),
|
|
158
|
+
publishedSha256: publishedInTarball ? sha256(packagedPath) : null,
|
|
159
|
+
sourceName: data.name,
|
|
160
|
+
sourceVersion: data.version,
|
|
161
|
+
lockfileVersion: data.lockfileVersion,
|
|
162
|
+
parity: 'validated-against-manifest',
|
|
163
|
+
publishedInTarball,
|
|
164
|
+
}
|
|
165
|
+
})
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
function installProductionDependencies(root) {
|
|
169
|
+
// The root package-lock.json is source evidence only: npm-packlist omits it
|
|
170
|
+
// from the root of an npm package, so root ci must validate the source tree.
|
|
171
|
+
execFileSync('npm', CI_ARGS, { cwd: root, stdio: 'inherit' })
|
|
172
|
+
execFileSync('npm', CI_ARGS, {
|
|
173
|
+
cwd: join(root, 'src', 'plugins', 'tui'),
|
|
174
|
+
stdio: 'inherit',
|
|
175
|
+
})
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
function sha256(path) {
|
|
179
|
+
return createHash('sha256').update(readFileSync(path)).digest('hex')
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
export function createPackageEvidence(root, { outputDir, targetSha } = {}) {
|
|
183
|
+
const inventory = validateInventory(root)
|
|
184
|
+
const sha = resolveTargetSha(root, targetSha)
|
|
185
|
+
const output = createOutputDirectory(outputDir)
|
|
186
|
+
let workDir
|
|
187
|
+
try {
|
|
188
|
+
const tarball = packOnce(root, output.directory)
|
|
189
|
+
workDir = mkdtempSync(join(tmpdir(), 'pantheon-package-evidence-check-'))
|
|
190
|
+
const entries = validateArchiveEntries(tarball)
|
|
191
|
+
const packageRoot = extractSafely(tarball, workDir)
|
|
192
|
+
validatePayload(packageRoot, inventory)
|
|
193
|
+
installProductionDependencies(root)
|
|
194
|
+
const digest = sha256(tarball)
|
|
195
|
+
if (!/^[0-9a-f]{64}$/.test(digest)) fail('tarball SHA-256 is not lowercase 64-hex')
|
|
196
|
+
const metadata = {
|
|
197
|
+
version: inventory.sourceVersion,
|
|
198
|
+
targetSha: sha,
|
|
199
|
+
tarballSha256: digest,
|
|
200
|
+
tarball: tarball.split('/').at(-1),
|
|
201
|
+
lockfilePolicy: {
|
|
202
|
+
rootPackageLockfile: entries.has('package/package-lock.json')
|
|
203
|
+
? 'published-by-npm-pack'
|
|
204
|
+
: 'omitted-by-npm-pack',
|
|
205
|
+
note: entries.has('package/package-lock.json')
|
|
206
|
+
? 'npm pack published the root package-lock.json; lockfile parity is validated and recorded as source evidence, while tarball validation covers only the payload npm pack publishes.'
|
|
207
|
+
: 'npm pack omits the package root package-lock.json by policy; lockfile parity is validated and recorded as source evidence, while tarball validation covers only the payload npm pack publishes.',
|
|
208
|
+
},
|
|
209
|
+
lockfileEvidence: collectLockfileEvidence(inventory, entries, packageRoot),
|
|
210
|
+
}
|
|
211
|
+
writeFileSync(join(output.directory, 'metadata.json'), `${JSON.stringify(metadata, null, 2)}\n`)
|
|
212
|
+
writeFileSync(join(output.directory, 'version'), `${metadata.version}\n`)
|
|
213
|
+
writeFileSync(join(output.directory, 'target-sha'), `${metadata.targetSha}\n`)
|
|
214
|
+
writeFileSync(join(output.directory, 'tarball-sha256'), `${metadata.tarballSha256}\n`)
|
|
215
|
+
return { ...metadata, outputDir: output.directory, tarball }
|
|
216
|
+
} catch (error) {
|
|
217
|
+
rmSync(output.directory, { recursive: true, force: true })
|
|
218
|
+
throw error
|
|
219
|
+
} finally {
|
|
220
|
+
if (workDir) rmSync(workDir, { recursive: true, force: true })
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
function parseOptions(args) {
|
|
225
|
+
const options = {}
|
|
226
|
+
for (const arg of args) {
|
|
227
|
+
const match = /^--(output-dir|target-sha)=(.*)$/.exec(arg)
|
|
228
|
+
if (!match) fail(`unsupported package evidence option: ${arg}`)
|
|
229
|
+
options[match[1] === 'output-dir' ? 'outputDir' : 'targetSha'] = match[2]
|
|
230
|
+
}
|
|
231
|
+
return options
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
if (process.argv[1]?.endsWith('package-evidence.mjs')) {
|
|
235
|
+
try {
|
|
236
|
+
const evidence = createPackageEvidence(process.cwd(), parseOptions(process.argv.slice(2)))
|
|
237
|
+
console.log(JSON.stringify(evidence))
|
|
238
|
+
} catch (error) {
|
|
239
|
+
console.error(`package-evidence: ${error.message}`)
|
|
240
|
+
process.exit(1)
|
|
241
|
+
}
|
|
242
|
+
}
|