@jjh32456/longlive 0.0.0-stage → 1.8.12
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/CHANGELOG.md +205 -0
- package/LICENSE +21 -0
- package/QUICKSTART.md +363 -0
- package/README.en.md +55 -0
- package/README.md +225 -2
- package/SPEC.md +211 -0
- package/build-info.json +1555 -0
- package/cordis.patch.yml +177 -0
- package/docs/A1-MIGRATION.md +75 -0
- package/docs/ANSWER-GUARD.md +92 -0
- package/docs/ARCHITECTURE.md +128 -0
- package/docs/AUTO-RECALL-WIRING.md +115 -0
- package/docs/AUTO-RECALL.md +237 -0
- package/docs/CONCEPTS.md +143 -0
- package/docs/CONFIG.md +807 -0
- package/docs/ERRORS.md +271 -0
- package/docs/FAQ.md +186 -0
- package/docs/FEATURES.md +579 -0
- package/docs/INDEX-FRESHNESS.md +21 -0
- package/docs/METRICS.md +244 -0
- package/docs/MIGRATION-1.6.0.md +220 -0
- package/docs/OPERATIONS.md +439 -0
- package/docs/PANEL-INTEGRATION.md +190 -0
- package/docs/PRIVACY.md +88 -0
- package/docs/QUICKSTART.md +155 -0
- package/docs/RAW-INDEX-POLICY.md +7 -0
- package/docs/README.en.md +46 -0
- package/docs/RESIDENT-WATCHER.md +90 -0
- package/docs/SESSION-WATCH.md +214 -0
- package/docs/TOOLS.md +184 -0
- package/docs/TROUBLESHOOTING.md +329 -0
- package/icon.svg +11 -0
- package/lib/client.js +436 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +160 -4
- package/runbook.md +343 -0
- package/scripts/archive-digest-build.mjs +668 -0
- package/scripts/auto-truncate-run.ps1 +752 -0
- package/scripts/backfill-auto-cards.mjs +98 -0
- package/scripts/edges-build.mjs +1003 -0
- package/scripts/index-maintain.mjs +39 -0
- package/scripts/index-reconcile.mjs +49 -0
- package/scripts/index-status.mjs +28 -0
- package/scripts/install-resident-watcher.ps1 +15 -0
- package/scripts/install-session-watch.ps1 +332 -0
- package/scripts/install-surgery-task.ps1 +174 -0
- package/scripts/lib/auto-truncate-run.ps1 +512 -0
- package/scripts/lib/session-watch-fixture.mjs +207 -0
- package/scripts/longlive-doctor.mjs +578 -0
- package/scripts/metrics-read.mjs +79 -0
- package/scripts/metrics-sample.mjs +215 -0
- package/scripts/migrate-180.mjs +163 -0
- package/scripts/migrate-a1-legacy.mjs +62 -0
- package/scripts/migrate-lifecycle.mjs +157 -0
- package/scripts/pack.mjs +392 -0
- package/scripts/recall-index-build.mjs +128 -0
- package/scripts/recall-links-build.mjs +420 -0
- package/scripts/rescore-cards.mjs +36 -0
- package/scripts/resident-watcher-status.ps1 +15 -0
- package/scripts/resident-watcher.ps1 +643 -0
- package/scripts/session-watch-drill.mjs +553 -0
- package/scripts/session-watch-status.ps1 +146 -0
- package/scripts/session-watch.mjs +1367 -0
- package/scripts/surgery-inspect.mjs +122 -0
- package/scripts/surgery-run.cmd +34 -0
- package/scripts/truncate-cli.mjs +279 -0
- package/scripts/unattended-surgery.ps1 +1019 -0
- package/scripts/uninstall-resident-watcher.ps1 +15 -0
- package/scripts/uninstall-session-watch.ps1 +192 -0
- package/scripts/verify-card-anchors.mjs +138 -0
- package/scripts/watch-loop.ps1 +916 -0
- package/src/actions/audit.js +125 -0
- package/src/actions/evidence.js +122 -0
- package/src/actions/fs.js +162 -0
- package/src/activity/index.js +873 -0
- package/src/activity/model.js +351 -0
- package/src/activity/store.js +786 -0
- package/src/activity/summary.js +180 -0
- package/src/activity/thinking.js +191 -0
- package/src/adapters/constants.js +11 -0
- package/src/adapters/engram/data/aliases.json +51 -0
- package/src/adapters/engram/data/policy.json +8 -0
- package/src/adapters/engram/data/routing-rules.json +546 -0
- package/src/adapters/engram/index.js +278 -0
- package/src/adapters/registry.js +315 -0
- package/src/answer/audit.js +238 -0
- package/src/answer/evidence.js +30 -0
- package/src/answer/guard.js +1370 -0
- package/src/answer/index.js +1086 -0
- package/src/answer/query.js +111 -0
- package/src/answer/second-hop.mjs +101 -0
- package/src/auto-truncate-status.js +164 -0
- package/src/auto-truncate.js +1181 -0
- package/src/autoprocedure/candidate.js +342 -0
- package/src/autoprocedure/config.js +122 -0
- package/src/autoprocedure/evidence.js +345 -0
- package/src/autoprocedure/index.js +83 -0
- package/src/autoprocedure/ledger.js +329 -0
- package/src/autoprocedure/lint.js +232 -0
- package/src/autoprocedure/llm.js +409 -0
- package/src/autoprocedure/locks.js +102 -0
- package/src/autoprocedure/paths.js +39 -0
- package/src/autoprocedure/privacy.js +87 -0
- package/src/autoprocedure/rules.js +288 -0
- package/src/autoprocedure/runtime.js +718 -0
- package/src/autoprocedure/session-reader.js +328 -0
- package/src/backup.js +146 -0
- package/src/bus/bus.mjs +1446 -0
- package/src/codec.js +269 -0
- package/src/compaction/cut-engine.js +44 -0
- package/src/compaction/engine-core.js +1237 -0
- package/src/compaction/entry.js +228 -0
- package/src/compaction.js +230 -0
- package/src/conclusion.js +366 -0
- package/src/config.js +824 -0
- package/src/d6/runtime.js +517 -0
- package/src/d6/surface.js +181 -0
- package/src/deps.js +189 -0
- package/src/engine-status.js +141 -0
- package/src/features.js +912 -0
- package/src/handoff/index.js +944 -0
- package/src/handoff/model.js +1010 -0
- package/src/handoff/store.js +1233 -0
- package/src/heartbeat.js +385 -0
- package/src/home.js +16 -0
- package/src/host-version.js +280 -0
- package/src/hot-truncate-diag.js +98 -0
- package/src/identity/card-marker.js +281 -0
- package/src/identity/handover.js +657 -0
- package/src/identity/index.js +337 -0
- package/src/identity/inject-position.js +131 -0
- package/src/identity/writeback.js +344 -0
- package/src/identity.js +118 -0
- package/src/index.js +647 -0
- package/src/lifecycle/gap-clocks.js +364 -0
- package/src/lifecycle/index.js +269 -0
- package/src/lifecycle/proactive.js +1426 -0
- package/src/live-target.js +212 -0
- package/src/live.js +1603 -0
- package/src/log-rotation.js +153 -0
- package/src/memory/a1-migration.js +124 -0
- package/src/memory/activity-capture.js +229 -0
- package/src/memory/anchor-fallback.js +116 -0
- package/src/memory/anchors.js +194 -0
- package/src/memory/audit-records.js +222 -0
- package/src/memory/auto-cards.js +441 -0
- package/src/memory/capture-host.js +228 -0
- package/src/memory/capture.js +457 -0
- package/src/memory/card-anchors.js +203 -0
- package/src/memory/card-priority.js +110 -0
- package/src/memory/cards.js +425 -0
- package/src/memory/conclusion-distill.js +332 -0
- package/src/memory/conclusion-drafts.js +239 -0
- package/src/memory/conflicts.js +147 -0
- package/src/memory/consolidate.js +815 -0
- package/src/memory/decay.js +311 -0
- package/src/memory/distill.js +485 -0
- package/src/memory/event-index.js +1826 -0
- package/src/memory/evidence-chain.js +295 -0
- package/src/memory/evidence.js +213 -0
- package/src/memory/filter-runner.js +555 -0
- package/src/memory/filter.js +1035 -0
- package/src/memory/forget-v2.js +410 -0
- package/src/memory/forget.js +512 -0
- package/src/memory/frames-activation.js +247 -0
- package/src/memory/frontmatter.js +454 -0
- package/src/memory/fts-query.js +342 -0
- package/src/memory/governance.js +604 -0
- package/src/memory/index-freshness.js +234 -0
- package/src/memory/index.js +362 -0
- package/src/memory/l2-gate.js +169 -0
- package/src/memory/lifecycle.js +107 -0
- package/src/memory/lock.js +121 -0
- package/src/memory/maintenance.js +785 -0
- package/src/memory/manifest.js +245 -0
- package/src/memory/migrate-lifecycle.js +1808 -0
- package/src/memory/migrate.js +139 -0
- package/src/memory/paths.js +229 -0
- package/src/memory/procedure.js +963 -0
- package/src/memory/provenance.js +119 -0
- package/src/memory/recall-v2.js +206 -0
- package/src/memory/recall.js +256 -0
- package/src/memory/reconcile.js +265 -0
- package/src/memory/records.js +433 -0
- package/src/memory/reinforce.js +145 -0
- package/src/memory/retention.js +128 -0
- package/src/memory/review.js +124 -0
- package/src/memory/state.js +279 -0
- package/src/memory/tiers.js +168 -0
- package/src/memory/topic-phrases.js +73 -0
- package/src/memory/trust.js +97 -0
- package/src/memory/version-chain.js +264 -0
- package/src/memory/wal.js +137 -0
- package/src/memory/working-frame.js +516 -0
- package/src/metrics/classify.mjs +189 -0
- package/src/metrics/estimate.mjs +108 -0
- package/src/metrics/index.mjs +204 -0
- package/src/metrics/measure.mjs +462 -0
- package/src/metrics/prestep-latency.mjs +307 -0
- package/src/metrics/store.mjs +264 -0
- package/src/original.js +294 -0
- package/src/policy/threshold-policy.js +224 -0
- package/src/policy-profile.js +463 -0
- package/src/recall/anaphora.mjs +87 -0
- package/src/recall/archive-fallback.mjs +235 -0
- package/src/recall/archive-search.mjs +425 -0
- package/src/recall/cards.mjs +202 -0
- package/src/recall/edges.js +379 -0
- package/src/recall/embedding.mjs +698 -0
- package/src/recall/entities.mjs +112 -0
- package/src/recall/explain.mjs +433 -0
- package/src/recall/force-policy.mjs +138 -0
- package/src/recall/index.js +1036 -0
- package/src/recall/inject-order.mjs +277 -0
- package/src/recall/link-recall.mjs +183 -0
- package/src/recall/links.mjs +696 -0
- package/src/recall/privacy.mjs +208 -0
- package/src/recall/recall-core.mjs +765 -0
- package/src/recall/shared-visibility.js +302 -0
- package/src/recall/time-normalizer.mjs +196 -0
- package/src/retention/config.js +106 -0
- package/src/retention/index.js +643 -0
- package/src/role/activation.js +191 -0
- package/src/role/attention.js +318 -0
- package/src/role/base.js +36 -0
- package/src/role/channels.js +423 -0
- package/src/role/index.js +425 -0
- package/src/role/interfaces.js +115 -0
- package/src/role/personality.js +370 -0
- package/src/role/readers.js +151 -0
- package/src/role/relationships.js +477 -0
- package/src/role/store.js +202 -0
- package/src/role/writeprotect.js +373 -0
- package/src/router/aliases.json +182 -0
- package/src/router/background/agent-runner.mjs +239 -0
- package/src/router/background/anchor.mjs +323 -0
- package/src/router/background/audit.mjs +337 -0
- package/src/router/background/budget-ledger.mjs +648 -0
- package/src/router/background/host-sim.mjs +451 -0
- package/src/router/background/index.mjs +81 -0
- package/src/router/background/memory.mjs +63 -0
- package/src/router/background/mock-llm.mjs +203 -0
- package/src/router/background/queue.mjs +224 -0
- package/src/router/background/retry.mjs +255 -0
- package/src/router/background/router.mjs +1459 -0
- package/src/router/background/stream.mjs +276 -0
- package/src/router/background/tool-policy.mjs +255 -0
- package/src/router/design-headings.json +221 -0
- package/src/router/face/config.mjs +155 -0
- package/src/router/face/context.mjs +284 -0
- package/src/router/face/face.mjs +466 -0
- package/src/router/face/identity.mjs +130 -0
- package/src/router/face/index.mjs +65 -0
- package/src/router/face/journal.mjs +119 -0
- package/src/router/face/llm.mjs +252 -0
- package/src/router/face/outbox.mjs +153 -0
- package/src/router/face/paths.mjs +54 -0
- package/src/router/judge.mjs +987 -0
- package/src/router/policies/generic.json +131 -0
- package/src/router/route.js +1766 -0
- package/src/router/router.mjs +535 -0
- package/src/router/routing-rules.json +816 -0
- package/src/router/run-sim.mjs +530 -0
- package/src/router/runtime.js +569 -0
- package/src/router/service/apply.mjs +1218 -0
- package/src/router/service/board.mjs +712 -0
- package/src/router/service/caller.mjs +131 -0
- package/src/router/service/config.mjs +361 -0
- package/src/router/service/context.mjs +314 -0
- package/src/router/service/hint.mjs +668 -0
- package/src/router/service/lease.mjs +494 -0
- package/src/router/service/live.mjs +251 -0
- package/src/router/service/lock.mjs +550 -0
- package/src/router/service/merge.mjs +255 -0
- package/src/router/service/model-resolve.mjs +350 -0
- package/src/router/service/paths.mjs +168 -0
- package/src/router/service/proposals.mjs +1461 -0
- package/src/router/service/queue.mjs +477 -0
- package/src/router/service/reconcile.mjs +271 -0
- package/src/router/service/service.mjs +2998 -0
- package/src/router/service/sources.mjs +352 -0
- package/src/router/service/status.mjs +520 -0
- package/src/router/service/store.mjs +476 -0
- package/src/router/service/ticklock.mjs +239 -0
- package/src/router/service/tokens.mjs +95 -0
- package/src/router/service/tools.mjs +248 -0
- package/src/router/service/wake.mjs +544 -0
- package/src/router/service/wal.mjs +685 -0
- package/src/router/shadow.mjs +821 -0
- package/src/surgery-recovery.js +1909 -0
- package/src/tool-output.js +485 -0
- package/src/tools.js +3146 -0
- package/src/truncate-visible.js +2416 -0
- package/src/truncate.js +999 -0
- package/src/ui/actions.js +1312 -0
- package/src/ui/flags.js +259 -0
- package/src/ui/panel-api.js +371 -0
- package/src/ui/panel-auth.js +251 -0
- package/src/ui/panel-integrity.js +243 -0
- package/src/ui/routes-readonly.js +759 -0
- package/src/ui/routes.js +284 -0
- package/src/util/append-store.js +368 -0
- package/src/util/local-day.js +30 -0
- package/src/util/redact.js +227 -0
- package/src/util/stale-locks.js +148 -0
- package/src/version.js +99 -0
- package/test/fixtures/pre-step-container.mjs +100 -0
- package/test/p1_probe.mjs +97 -0
|
@@ -0,0 +1,251 @@
|
|
|
1
|
+
// src/ui/panel-auth.js — M2-G 权限门(N38 / §12.2)
|
|
2
|
+
//
|
|
3
|
+
// 两个凭据**只存在于宿主进程内存**:capability secret 必须由宿主进程注入
|
|
4
|
+
// (profile 私有文件 / 宿主环境变量 DSH_LONGLIVE_PANEL_SECRET),审计 key boot 时 32B CSPRNG 生成:
|
|
5
|
+
// - panelCap: 签发面板能力令牌的 HMAC key;
|
|
6
|
+
// - auditKey: HMAC 链式审计 / evidence 签名 key。
|
|
7
|
+
// 磁盘上没有任何凭据文件,也没有任何 HTTP 路由能把它们读出来:
|
|
8
|
+
// 面板经宿主内部通道拿到的是**短 TTL 一次性 nonce 能力令牌**
|
|
9
|
+
// capability = HMAC(panelCap, `${nonce}|${pid}|${windowNonce}|${sessionNonce}`)
|
|
10
|
+
// 请求头 `x-longlive-cap` + `x-longlive-nonce`;服务端内存 nonce 注册表单次消费,TTL 默认 60s。
|
|
11
|
+
//
|
|
12
|
+
// 权限三门(HTTP / 工具 / CLI)走同一个 {@link actionGate}:
|
|
13
|
+
// - subagent 一律 403 `E_SUBAGENT_FORBIDDEN`(先于 token 校验);
|
|
14
|
+
// - 面板未装 → 401 `E_PANEL_ABSENT`;
|
|
15
|
+
// - 无令牌 → 401 `E_NO_CAP`;错令牌 → 401 `E_CAP_INVALID`;nonce 已用/过期 → 401 `E_CAP_CONSUMED/E_CAP_EXPIRED`。
|
|
16
|
+
// actor 由令牌绑定为 `host`,请求体里的 actor 字段一律忽略(绝不信任请求体)。
|
|
17
|
+
|
|
18
|
+
import crypto from 'node:crypto';
|
|
19
|
+
|
|
20
|
+
export const CAP_TTL_MS = 60_000;
|
|
21
|
+
export const CAP_HEADER = 'x-longlive-cap';
|
|
22
|
+
export const NONCE_HEADER = 'x-longlive-nonce';
|
|
23
|
+
export const ACTOR = 'host';
|
|
24
|
+
|
|
25
|
+
/** Errors carry `{code,status}` so the HTTP layer and the contract tests agree. */
|
|
26
|
+
export class PanelAuthError extends Error {
|
|
27
|
+
constructor(code, message, status = 401, details = undefined) {
|
|
28
|
+
super(message);
|
|
29
|
+
this.name = 'PanelAuthError';
|
|
30
|
+
this.code = code;
|
|
31
|
+
this.status = status;
|
|
32
|
+
if (details !== undefined) this.details = details;
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export function hmacHex(key, text) {
|
|
37
|
+
return crypto.createHmac('sha256', key).update(String(text), 'utf8').digest('hex');
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function normalizeHeaderValue(value) {
|
|
41
|
+
if (Array.isArray(value)) return value.length > 0 ? String(value[0]) : '';
|
|
42
|
+
return value === undefined || value === null ? '' : String(value);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function headerOf(headers, name) {
|
|
46
|
+
if (!headers || typeof headers !== 'object') return '';
|
|
47
|
+
const lower = name.toLowerCase();
|
|
48
|
+
if (headers[lower] !== undefined) return normalizeHeaderValue(headers[lower]);
|
|
49
|
+
for (const [key, value] of Object.entries(headers)) {
|
|
50
|
+
if (key.toLowerCase() === lower) return normalizeHeaderValue(value);
|
|
51
|
+
}
|
|
52
|
+
return '';
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* Create the in-memory credential holder + permission gate.
|
|
57
|
+
*
|
|
58
|
+
* @param {object} [options]
|
|
59
|
+
* @param {() => Date} [options.now] clock seam for tests.
|
|
60
|
+
* @param {(size:number)=>Buffer} [options.randomBytes] CSPRNG seam for tests.
|
|
61
|
+
* @param {boolean} [options.panelPresent] false simulates "panel uninstalled".
|
|
62
|
+
* @returns auth facade (credentials intentionally not enumerable).
|
|
63
|
+
*/
|
|
64
|
+
export function createPanelAuth(options = {}) {
|
|
65
|
+
const now = typeof options.now === 'function' ? options.now : () => new Date();
|
|
66
|
+
const randomBytes = typeof options.randomBytes === 'function' ? options.randomBytes : crypto.randomBytes;
|
|
67
|
+
// Monotonic clock: capability TTL must not stretch when the wall clock rolls
|
|
68
|
+
// back (N38: TTL ≤60s is enforced against elapsed process time).
|
|
69
|
+
const monoNow = typeof options.monoNow === 'function' ? options.monoNow : () => process.uptime() * 1000;
|
|
70
|
+
const panelPresent = options.panelPresent !== false;
|
|
71
|
+
// P0-1: capability secret is HOST-INJECTED. A module that merely imports this
|
|
72
|
+
// file cannot mint a usable capability: without the host secret, issue()/gate
|
|
73
|
+
// fail closed with E_PANEL_HOST_ONLY. The secret is never written to disk.
|
|
74
|
+
function decodeSecret(value) {
|
|
75
|
+
if (Buffer.isBuffer(value) && value.length >= 32) return Buffer.from(value);
|
|
76
|
+
if (typeof value === 'string' && value.trim() !== '') {
|
|
77
|
+
const raw = value.trim();
|
|
78
|
+
const hex = /^[0-9a-f]{64,}$/i.test(raw) ? Buffer.from(raw, 'hex') : null;
|
|
79
|
+
if (hex && hex.length >= 32) return hex;
|
|
80
|
+
try {
|
|
81
|
+
const b64 = Buffer.from(raw, 'base64');
|
|
82
|
+
if (b64.length >= 32) return b64;
|
|
83
|
+
} catch {
|
|
84
|
+
/* fallthrough */
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
return null;
|
|
88
|
+
}
|
|
89
|
+
const hostSecret = decodeSecret(options.hostSecret) ?? decodeSecret(process.env.DSH_LONGLIVE_PANEL_SECRET);
|
|
90
|
+
const hostCapable = hostSecret !== null;
|
|
91
|
+
const capabilitySecret = hostSecret ?? randomBytes(32); // host memory only
|
|
92
|
+
const auditKey = randomBytes(32); // host memory only
|
|
93
|
+
// R8/P1-1: independent in-memory key that anchors the panel integrity manifest.
|
|
94
|
+
// Tests may inject a fixed Buffer through options.panelIntegrityKey (host-side
|
|
95
|
+
// seam only); production always generates a fresh boot-scoped key.
|
|
96
|
+
const panelIntegrityKey = Buffer.isBuffer(options.panelIntegrityKey) && options.panelIntegrityKey.length >= 16
|
|
97
|
+
? Buffer.from(options.panelIntegrityKey)
|
|
98
|
+
: randomBytes(32);
|
|
99
|
+
/** nonce → { pid, windowNonce, sessionNonce, expiresAt, consumed } */
|
|
100
|
+
const nonces = new Map();
|
|
101
|
+
const stats = { issued: 0, verified: 0, rejected: 0, consumedReplays: 0 };
|
|
102
|
+
|
|
103
|
+
function currentMs() {
|
|
104
|
+
return now().getTime();
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
function prune(nowMono) {
|
|
108
|
+
for (const [nonce, entry] of nonces) {
|
|
109
|
+
if (entry.consumed || nowMono - entry.expiresMono > CAP_TTL_MS) nonces.delete(nonce);
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/**
|
|
114
|
+
* Host-internal channel mints a one-shot capability token for the panel.
|
|
115
|
+
* Never exposed over HTTP; never written to disk.
|
|
116
|
+
*/
|
|
117
|
+
function issue(opts = {}) {
|
|
118
|
+
if (!hostCapable) {
|
|
119
|
+
stats.rejected += 1;
|
|
120
|
+
throw new PanelAuthError('E_PANEL_HOST_ONLY', '能力签发只允许宿主进程(host-injected secret 缺失):外部 import 不得发 cap。', 403);
|
|
121
|
+
}
|
|
122
|
+
const pid = Number.isInteger(opts.pid) ? opts.pid : process.pid;
|
|
123
|
+
const windowNonce = typeof opts.windowNonce === 'string' && opts.windowNonce !== '' ? opts.windowNonce : 'boot';
|
|
124
|
+
const sessionNonce = typeof opts.sessionNonce === 'string' ? opts.sessionNonce : '';
|
|
125
|
+
const ttlMs = Number.isFinite(opts.ttlMs) && opts.ttlMs > 0 ? Math.min(opts.ttlMs, CAP_TTL_MS) : CAP_TTL_MS;
|
|
126
|
+
const nonce = randomBytes(16).toString('hex');
|
|
127
|
+
const mac = hmacHex(capabilitySecret, `${nonce}|${pid}|${windowNonce}|${sessionNonce}`);
|
|
128
|
+
const token = `${nonce}.${mac}`;
|
|
129
|
+
const nowMs = currentMs();
|
|
130
|
+
const nowMono = monoNow();
|
|
131
|
+
prune(nowMono);
|
|
132
|
+
nonces.set(nonce, {
|
|
133
|
+
pid,
|
|
134
|
+
windowNonce,
|
|
135
|
+
sessionNonce,
|
|
136
|
+
expiresAt: nowMs + ttlMs,
|
|
137
|
+
expiresMono: nowMono + ttlMs,
|
|
138
|
+
consumed: false,
|
|
139
|
+
});
|
|
140
|
+
stats.issued += 1;
|
|
141
|
+
return { token, nonce, expiresAt: new Date(nowMs + ttlMs).toISOString(), actor: ACTOR };
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
function verifyToken(headers) {
|
|
145
|
+
if (!panelPresent) {
|
|
146
|
+
stats.rejected += 1;
|
|
147
|
+
throw new PanelAuthError('E_PANEL_ABSENT', '面板未安装:所有面板接口暂停(长活核心不受影响)。');
|
|
148
|
+
}
|
|
149
|
+
const token = headerOf(headers, CAP_HEADER);
|
|
150
|
+
const nonceHeader = headerOf(headers, NONCE_HEADER);
|
|
151
|
+
if (token === '') {
|
|
152
|
+
stats.rejected += 1;
|
|
153
|
+
throw new PanelAuthError('E_NO_CAP', '缺少能力令牌(x-longlive-cap):动作与只读接口一律拒绝。');
|
|
154
|
+
}
|
|
155
|
+
const dot = token.indexOf('.');
|
|
156
|
+
if (dot <= 0 || dot === token.length - 1) {
|
|
157
|
+
stats.rejected += 1;
|
|
158
|
+
throw new PanelAuthError('E_CAP_INVALID', '能力令牌格式非法。');
|
|
159
|
+
}
|
|
160
|
+
const tokenNonce = token.slice(0, dot);
|
|
161
|
+
const mac = token.slice(dot + 1);
|
|
162
|
+
if (nonceHeader !== '' && nonceHeader !== tokenNonce) {
|
|
163
|
+
stats.rejected += 1;
|
|
164
|
+
throw new PanelAuthError('E_CAP_INVALID', '能力令牌与 nonce 请求头不匹配。');
|
|
165
|
+
}
|
|
166
|
+
const entry = nonces.get(tokenNonce);
|
|
167
|
+
if (entry === undefined) {
|
|
168
|
+
stats.rejected += 1;
|
|
169
|
+
throw new PanelAuthError('E_CAP_CONSUMED', 'nonce 不存在或已被消费(能力令牌一次性)。');
|
|
170
|
+
}
|
|
171
|
+
if (entry.consumed) {
|
|
172
|
+
stats.consumedReplays += 1;
|
|
173
|
+
stats.rejected += 1;
|
|
174
|
+
throw new PanelAuthError('E_CAP_CONSUMED', 'nonce 已被消费(重放被拒绝)。');
|
|
175
|
+
}
|
|
176
|
+
// TTL is enforced on the monotonic clock: a wall-clock rollback cannot
|
|
177
|
+
// extend a capability token's lifetime.
|
|
178
|
+
if (monoNow() > entry.expiresMono) {
|
|
179
|
+
stats.rejected += 1;
|
|
180
|
+
throw new PanelAuthError('E_CAP_EXPIRED', '能力令牌已过期(TTL ≤60s)。');
|
|
181
|
+
}
|
|
182
|
+
const expected = hmacHex(
|
|
183
|
+
capabilitySecret,
|
|
184
|
+
`${tokenNonce}|${entry.pid}|${entry.windowNonce}|${entry.sessionNonce}`,
|
|
185
|
+
);
|
|
186
|
+
const expectedBuf = Buffer.from(expected, 'utf8');
|
|
187
|
+
const macBuf = Buffer.from(mac, 'utf8');
|
|
188
|
+
// EA-12: timingSafeEqual throws RangeError on unequal lengths -> compare lengths first.
|
|
189
|
+
if (expectedBuf.length !== macBuf.length || !crypto.timingSafeEqual(expectedBuf, macBuf)) {
|
|
190
|
+
stats.rejected += 1;
|
|
191
|
+
throw new PanelAuthError('E_CAP_INVALID', '能力令牌验签失败。');
|
|
192
|
+
}
|
|
193
|
+
entry.consumed = true;
|
|
194
|
+
stats.verified += 1;
|
|
195
|
+
return { ok: true, actor: ACTOR, actorId: ACTOR, pid: entry.pid, nonce: tokenNonce };
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
/**
|
|
199
|
+
* The single permission door for HTTP routes, tools and the CLI.
|
|
200
|
+
* `source` only changes the audit label — the checks are identical by design.
|
|
201
|
+
* The request body is never consulted for identity.
|
|
202
|
+
*/
|
|
203
|
+
function actionGate({ source = 'http', headers = {}, actorKind = 'host' } = {}) {
|
|
204
|
+
if (!hostCapable) {
|
|
205
|
+
stats.rejected += 1;
|
|
206
|
+
throw new PanelAuthError('E_PANEL_HOST_ONLY', '权限门只允许宿主进程(host-injected secret 缺失)。', 403);
|
|
207
|
+
}
|
|
208
|
+
if (source !== 'http' && source !== 'tool' && source !== 'cli') {
|
|
209
|
+
throw new PanelAuthError('E_SOURCE_INVALID', `未知入口:${source}`, 400);
|
|
210
|
+
}
|
|
211
|
+
if (actorKind === 'subagent') {
|
|
212
|
+
stats.rejected += 1;
|
|
213
|
+
throw new PanelAuthError('E_SUBAGENT_FORBIDDEN', 'subagent 不具有面板动作权限(一律 403)。', 403);
|
|
214
|
+
}
|
|
215
|
+
const verdict = verifyToken(headers);
|
|
216
|
+
// P1-2: actor is injected by the host (token-bound); request bodies are never
|
|
217
|
+
// consulted. A verdict with no actor is refused instead of defaulting silently.
|
|
218
|
+
if (typeof verdict?.actor !== 'string' || verdict.actor === '') {
|
|
219
|
+
stats.rejected += 1;
|
|
220
|
+
throw new PanelAuthError('E_ACTOR_REQUIRED', 'actor 必须由宿主注入(令牌绑定),缺省拒绝。', 401);
|
|
221
|
+
}
|
|
222
|
+
return { ...verdict, source };
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
/** Host-internal accessor for the audit/evidence signer. Not exposed to the panel. */
|
|
226
|
+
function auditKeyBytes() {
|
|
227
|
+
return auditKey;
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
/** Host-internal accessor for the R8 manifest HMAC anchor (boot-scoped). */
|
|
231
|
+
function panelIntegrityKeyBytes() {
|
|
232
|
+
return panelIntegrityKey;
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
function hasCapabilitySecret() {
|
|
236
|
+
return hostCapable && Buffer.isBuffer(capabilitySecret) && capabilitySecret.length >= 32;
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
return {
|
|
240
|
+
panelPresent,
|
|
241
|
+
hostCapable,
|
|
242
|
+
issue,
|
|
243
|
+
verifyToken,
|
|
244
|
+
actionGate,
|
|
245
|
+
auditKeyBytes,
|
|
246
|
+
panelIntegrityKeyBytes,
|
|
247
|
+
hasCapabilitySecret,
|
|
248
|
+
stats,
|
|
249
|
+
CAP_TTL_MS,
|
|
250
|
+
};
|
|
251
|
+
}
|
|
@@ -0,0 +1,243 @@
|
|
|
1
|
+
// src/ui/panel-integrity.js — M2-G 面板包完整性(R8 / §12.10-R8 / §12.11-R9)
|
|
2
|
+
//
|
|
3
|
+
// 宿主包管理器在安装/更新面板包时生成 `.integrity/manifest.sha256`
|
|
4
|
+
// (逐文件 `<sha256> <relative-path>` + 末尾 `#hmac-sha256 <hex>`)。**关键**:
|
|
5
|
+
// manifest 用**宿主进程内存密钥**(`panelIntegrityKey`,boot 时 32B CSPRNG 生成、
|
|
6
|
+
// 进程退出即失)做 HMAC 锚定;校验时重算 HMAC。仅凭公开的逐文件 sha256 重写
|
|
7
|
+
// manifest 无法生成可通过校验的 HMAC —— 门不能自己给自己盖章。
|
|
8
|
+
//
|
|
9
|
+
// 本模块负责:
|
|
10
|
+
// 1) 加载时校验一次(createIntegrityGuard 构造即校验);
|
|
11
|
+
// 2) 每次动作前再校验(checkBeforeAction);
|
|
12
|
+
// 3) manifest 缺失 / 无签名 / HMAC 不符 / 文件不一致 → 动作全禁用 + 401
|
|
13
|
+
// `E_PANEL_INTEGRITY`,**只读展示保留**(status 照常返回)。
|
|
14
|
+
// panelRoot 由宿主显式传入(默认 `<DSH_HOME>/longlive-panel`,见 panel-api.js,
|
|
15
|
+
// 不再落在 memoryRoot 里)。不要求 Authenticode 代码签名(Lead 已签残余风险)。
|
|
16
|
+
|
|
17
|
+
import crypto from 'node:crypto';
|
|
18
|
+
import fs from 'node:fs';
|
|
19
|
+
import path from 'node:path';
|
|
20
|
+
|
|
21
|
+
export const INTEGRITY_DIR = '.integrity';
|
|
22
|
+
export const INTEGRITY_MANIFEST = 'manifest.sha256';
|
|
23
|
+
export const MANIFEST_VERSION = 'panel-integrity/v1';
|
|
24
|
+
export const HMAC_LINE_PREFIX = '#hmac-sha256 ';
|
|
25
|
+
|
|
26
|
+
export class PanelIntegrityError extends Error {
|
|
27
|
+
constructor(message, status = 401, statusPayload = undefined) {
|
|
28
|
+
super(message);
|
|
29
|
+
this.name = 'PanelIntegrityError';
|
|
30
|
+
this.code = 'E_PANEL_INTEGRITY';
|
|
31
|
+
this.status = status;
|
|
32
|
+
if (statusPayload !== undefined) this.statusPayload = statusPayload;
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export function manifestPathOf(panelRoot) {
|
|
37
|
+
return path.join(String(panelRoot ?? ''), INTEGRITY_DIR, INTEGRITY_MANIFEST);
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function sha256OfFile(file) {
|
|
41
|
+
return crypto.createHash('sha256').update(fs.readFileSync(file)).digest('hex');
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function hmacOfBody(body, signKey) {
|
|
45
|
+
return crypto.createHmac('sha256', signKey).update(`${MANIFEST_VERSION}\n${body}`, 'utf8').digest('hex');
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** Parse manifest text: file lines + mandatory host-HMAC trailer. */
|
|
49
|
+
export function parseManifest(text) {
|
|
50
|
+
const entries = [];
|
|
51
|
+
const bad = [];
|
|
52
|
+
let hmac = null;
|
|
53
|
+
for (const line of String(text ?? '').replace(/^\uFEFF/, '').split(/\r?\n/)) {
|
|
54
|
+
const trimmed = line.trim();
|
|
55
|
+
if (trimmed === '') continue;
|
|
56
|
+
if (trimmed.startsWith(HMAC_LINE_PREFIX.trim())) {
|
|
57
|
+
const value = trimmed.slice(HMAC_LINE_PREFIX.trim().length).trim();
|
|
58
|
+
if (/^[0-9a-f]{64}$/i.test(value)) hmac = value.toLowerCase();
|
|
59
|
+
else bad.push(trimmed);
|
|
60
|
+
continue;
|
|
61
|
+
}
|
|
62
|
+
if (trimmed.startsWith('#')) continue;
|
|
63
|
+
const match = /^([0-9a-fA-F]{64})\s{2}(.+)$/.exec(trimmed);
|
|
64
|
+
if (!match) {
|
|
65
|
+
bad.push(trimmed);
|
|
66
|
+
continue;
|
|
67
|
+
}
|
|
68
|
+
entries.push({ sha256: match[1].toLowerCase(), path: match[2].trim() });
|
|
69
|
+
}
|
|
70
|
+
return { entries, bad, hmac };
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** The unsigned body (what the HMAC covers). */
|
|
74
|
+
function manifestBodyOf(panelRoot, files = undefined) {
|
|
75
|
+
const root = path.resolve(String(panelRoot));
|
|
76
|
+
let rels = files;
|
|
77
|
+
if (!Array.isArray(rels)) {
|
|
78
|
+
rels = [];
|
|
79
|
+
const walk = (dir) => {
|
|
80
|
+
for (const name of fs.readdirSync(dir, { withFileTypes: true })) {
|
|
81
|
+
const full = path.join(dir, name.name);
|
|
82
|
+
if (name.isDirectory()) {
|
|
83
|
+
if (name.name === INTEGRITY_DIR) continue;
|
|
84
|
+
walk(full);
|
|
85
|
+
} else if (name.isFile()) {
|
|
86
|
+
rels.push(path.relative(root, full).split(path.sep).join('/'));
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
};
|
|
90
|
+
walk(root);
|
|
91
|
+
}
|
|
92
|
+
rels.sort();
|
|
93
|
+
return `${rels.map((rel) => `${sha256OfFile(path.join(root, rel))} ${rel}`).join('\n')}\n`;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* Compute manifest text.
|
|
98
|
+
*
|
|
99
|
+
* - `computeManifest(panelRoot, { signKey })` → **host-signed** manifest (only the
|
|
100
|
+
* host has the in-memory key; this is what install/update writes).
|
|
101
|
+
* - `computeManifest(panelRoot)` → public unsigned body only. Writing it back
|
|
102
|
+
* does NOT pass validation (no host key ⇒ no valid HMAC): `E_MANIFEST_UNSIGNED`.
|
|
103
|
+
*/
|
|
104
|
+
export function computeManifest(panelRoot, options = {}) {
|
|
105
|
+
if (Array.isArray(options)) {
|
|
106
|
+
// legacy shape: computeManifest(root, files[]) -> unsigned body
|
|
107
|
+
return manifestBodyOf(panelRoot, options);
|
|
108
|
+
}
|
|
109
|
+
const body = manifestBodyOf(panelRoot, options.files);
|
|
110
|
+
if (options.signKey === undefined || options.signKey === null) return body;
|
|
111
|
+
return `${body}${HMAC_LINE_PREFIX}${hmacOfBody(body, options.signKey)}\n`;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* Create the integrity guard.
|
|
116
|
+
*
|
|
117
|
+
* @param {object} options
|
|
118
|
+
* @param {string} options.panelRoot installed panel package root (outside memoryRoot).
|
|
119
|
+
* @param {Buffer|string} options.signKey host-memory panelIntegrityKey (required).
|
|
120
|
+
* @param {() => Date} [options.now]
|
|
121
|
+
* @returns guard with `status()`, `loadedStatus`, `checkBeforeAction()`,
|
|
122
|
+
* `writeSignedManifest()` (host install/update helper).
|
|
123
|
+
*/
|
|
124
|
+
export function createIntegrityGuard(options = {}) {
|
|
125
|
+
const panelRoot = typeof options.panelRoot === 'string' && options.panelRoot.trim() !== ''
|
|
126
|
+
? path.resolve(options.panelRoot)
|
|
127
|
+
: null;
|
|
128
|
+
const now = typeof options.now === 'function' ? options.now : () => new Date();
|
|
129
|
+
const signKey = options.signKey;
|
|
130
|
+
|
|
131
|
+
function fail(code, checkedAt, extra = {}) {
|
|
132
|
+
return { ok: false, manifestVersion: null, checkedAt, files: [], lastError: code, ...extra };
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
function verifyNow() {
|
|
136
|
+
const checkedAt = now().toISOString();
|
|
137
|
+
if (panelRoot === null) return fail('E_PANEL_ROOT_UNKNOWN', checkedAt);
|
|
138
|
+
if (signKey === undefined || signKey === null || (typeof signKey === 'string' && signKey === '')
|
|
139
|
+
|| (Buffer.isBuffer(signKey) && signKey.length === 0)) {
|
|
140
|
+
return fail('E_INTEGRITY_KEY_MISSING', checkedAt);
|
|
141
|
+
}
|
|
142
|
+
const file = manifestPathOf(panelRoot);
|
|
143
|
+
let text = '';
|
|
144
|
+
try {
|
|
145
|
+
text = fs.readFileSync(file, 'utf8');
|
|
146
|
+
} catch {
|
|
147
|
+
return fail('E_MANIFEST_MISSING', checkedAt);
|
|
148
|
+
}
|
|
149
|
+
const parsed = parseManifest(text);
|
|
150
|
+
if (parsed.hmac === null) {
|
|
151
|
+
// Garbage manifest vs. a well-formed but *unsigned* file list (the public
|
|
152
|
+
// `computeManifest()` rewrite attack): both fail closed, with distinct codes.
|
|
153
|
+
const invalid = parsed.bad.length > 0 || parsed.entries.length === 0;
|
|
154
|
+
return fail(invalid ? 'E_MANIFEST_INVALID' : 'E_MANIFEST_UNSIGNED', checkedAt);
|
|
155
|
+
}
|
|
156
|
+
// Recompute the HMAC over the exact body the manifest declares (entries +
|
|
157
|
+
// paths in file order — the signed form is canonical sorted). A public
|
|
158
|
+
// recompute of file hashes cannot know the host key, so rewriting the file
|
|
159
|
+
// list alone never validates.
|
|
160
|
+
const bodyText = `${parsed.entries.map((entry) => `${entry.sha256} ${entry.path}`).join('\n')}\n`;
|
|
161
|
+
const expected = hmacOfBody(bodyText, signKey);
|
|
162
|
+
if (expected !== parsed.hmac) {
|
|
163
|
+
return fail('E_MANIFEST_HMAC_INVALID', checkedAt);
|
|
164
|
+
}
|
|
165
|
+
if (parsed.bad.length > 0 || parsed.entries.length === 0) {
|
|
166
|
+
return fail(parsed.bad.length > 0 ? 'E_MANIFEST_INVALID' : 'E_MANIFEST_EMPTY', checkedAt);
|
|
167
|
+
}
|
|
168
|
+
const files = [];
|
|
169
|
+
let ok = true;
|
|
170
|
+
let lastError = null;
|
|
171
|
+
for (const entry of parsed.entries) {
|
|
172
|
+
const target = path.resolve(panelRoot, entry.path);
|
|
173
|
+
if (target !== panelRoot && !target.startsWith(`${panelRoot}${path.sep}`)) {
|
|
174
|
+
ok = false;
|
|
175
|
+
lastError = 'E_MANIFEST_PATH_ESCAPE';
|
|
176
|
+
files.push({ path: entry.path, ok: false, sha256: null });
|
|
177
|
+
continue;
|
|
178
|
+
}
|
|
179
|
+
let actual = null;
|
|
180
|
+
try {
|
|
181
|
+
actual = sha256OfFile(target);
|
|
182
|
+
} catch {
|
|
183
|
+
ok = false;
|
|
184
|
+
lastError = lastError ?? 'E_FILE_MISSING';
|
|
185
|
+
files.push({ path: entry.path, ok: false, sha256: null });
|
|
186
|
+
continue;
|
|
187
|
+
}
|
|
188
|
+
const match = actual === entry.sha256;
|
|
189
|
+
if (!match) {
|
|
190
|
+
ok = false;
|
|
191
|
+
lastError = 'E_FILE_MISMATCH';
|
|
192
|
+
}
|
|
193
|
+
files.push({ path: entry.path, ok: match, sha256: actual });
|
|
194
|
+
}
|
|
195
|
+
return {
|
|
196
|
+
ok,
|
|
197
|
+
manifestVersion: `panel+hmac:${parsed.hmac.slice(0, 16)}`,
|
|
198
|
+
checkedAt,
|
|
199
|
+
files,
|
|
200
|
+
lastError,
|
|
201
|
+
};
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/**
|
|
205
|
+
* Host-only install/update helper: hash the current files and write a manifest
|
|
206
|
+
* signed with the in-memory host key. A caller without the key cannot produce
|
|
207
|
+
* a valid manifest, so this function is unusable as a bypass.
|
|
208
|
+
*/
|
|
209
|
+
function writeSignedManifest() {
|
|
210
|
+
if (panelRoot === null) {
|
|
211
|
+
return { ok: false, code: 'E_PANEL_ROOT_UNKNOWN' };
|
|
212
|
+
}
|
|
213
|
+
if (signKey === undefined || signKey === null) {
|
|
214
|
+
return { ok: false, code: 'E_INTEGRITY_KEY_MISSING' };
|
|
215
|
+
}
|
|
216
|
+
const text = computeManifest(panelRoot, { signKey });
|
|
217
|
+
const file = manifestPathOf(panelRoot);
|
|
218
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
219
|
+
fs.writeFileSync(file, text, 'utf8');
|
|
220
|
+
const parsed = parseManifest(text);
|
|
221
|
+
return { ok: true, path: file, hmac: parsed.hmac, body: text };
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
const loadedStatus = verifyNow();
|
|
225
|
+
|
|
226
|
+
function checkBeforeAction() {
|
|
227
|
+
const status = verifyNow();
|
|
228
|
+
if (!status.ok) {
|
|
229
|
+
throw new PanelIntegrityError('面板包完整性校验失败:动作已全部禁用(只读展示保留)。', 401, status);
|
|
230
|
+
}
|
|
231
|
+
return status;
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
return {
|
|
235
|
+
panelRoot,
|
|
236
|
+
loadedStatus,
|
|
237
|
+
status: verifyNow,
|
|
238
|
+
checkBeforeAction,
|
|
239
|
+
writeSignedManifest,
|
|
240
|
+
manifestPath: panelRoot === null ? null : manifestPathOf(panelRoot),
|
|
241
|
+
hasHostKey: signKey !== undefined && signKey !== null,
|
|
242
|
+
};
|
|
243
|
+
}
|