doukui 0.0.0-stage → 0.3.1

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.
Files changed (137) hide show
  1. package/LICENSE +21 -0
  2. package/README.en.md +42 -0
  3. package/README.md +147 -2
  4. package/bin/commands/build.js +178 -0
  5. package/bin/commands/config.js +88 -0
  6. package/bin/commands/help.js +83 -0
  7. package/bin/commands/init.js +194 -0
  8. package/bin/commands/install.js +202 -0
  9. package/bin/commands/interactive.js +352 -0
  10. package/bin/commands/list.js +108 -0
  11. package/bin/commands/loop-server.js +357 -0
  12. package/bin/commands/loop.js +1443 -0
  13. package/bin/commands/migrate.js +120 -0
  14. package/bin/commands/setup-global.js +81 -0
  15. package/bin/commands/status.js +140 -0
  16. package/bin/commands/team-cleanup.js +190 -0
  17. package/bin/commands/validate-config.js +35 -0
  18. package/bin/commands/validate.js +21 -0
  19. package/bin/commands/version.js +22 -0
  20. package/bin/context.js +143 -0
  21. package/bin/doukui.js +216 -0
  22. package/package.json +47 -4
  23. package/plugins/contracts/capabilities.js +268 -0
  24. package/plugins/contracts/checkresult-schema.json +75 -0
  25. package/plugins/contracts/config-schema.json +179 -0
  26. package/plugins/contracts/plugin-interface.js +262 -0
  27. package/plugins/contracts/plugin-schema.json +104 -0
  28. package/plugins/core/hook-session-start/index.js +281 -0
  29. package/plugins/core/hook-session-start/plugin.json +7 -0
  30. package/plugins/core/hook-skill-gate/index.js +661 -0
  31. package/plugins/core/hook-skill-gate/plugin.json +12 -0
  32. package/plugins/core/provider-loop-engine/index.js +1411 -0
  33. package/plugins/core/provider-loop-engine/plugin.json +15 -0
  34. package/plugins/core/provider-memory-store/index.js +510 -0
  35. package/plugins/core/provider-memory-store/plugin.json +9 -0
  36. package/plugins/core/provider-role-registry/index.js +376 -0
  37. package/plugins/core/provider-role-registry/plugin.json +9 -0
  38. package/plugins/core/provider-state-store/index.js +244 -0
  39. package/plugins/core/provider-state-store/plugin.json +9 -0
  40. package/plugins/core/provider-watchdog/assets/daemon-config.template.json +32 -0
  41. package/plugins/core/provider-watchdog/assets/lib/watchdog-multi-window.js +676 -0
  42. package/plugins/core/provider-watchdog/assets/watchdog.js +754 -0
  43. package/plugins/core/provider-watchdog/index.js +151 -0
  44. package/plugins/core/provider-watchdog/plugin.json +13 -0
  45. package/plugins/core/skill-agent-dispatcher/cleanup-reference.md +214 -0
  46. package/plugins/core/skill-agent-dispatcher/daemon-helpers-reference.md +249 -0
  47. package/plugins/core/skill-agent-dispatcher/plugin.json +13 -0
  48. package/plugins/core/skill-agent-dispatcher/roles-reference.md +253 -0
  49. package/plugins/core/skill-agent-dispatcher/skill.md +1291 -0
  50. package/plugins/core/skill-agentic-loop/plugin.json +20 -0
  51. package/plugins/core/skill-agentic-loop/skill.md +588 -0
  52. package/plugins/core/skill-batch-task-creator/plugin.json +15 -0
  53. package/plugins/core/skill-batch-task-creator/skill.md +620 -0
  54. package/plugins/core/skill-checklist/plugin.json +10 -0
  55. package/plugins/core/skill-checklist/skill.md +171 -0
  56. package/plugins/core/skill-completion-report/plugin.json +10 -0
  57. package/plugins/core/skill-completion-report/skill.md +331 -0
  58. package/plugins/core/skill-doukui-plan/plugin.json +15 -0
  59. package/plugins/core/skill-doukui-plan/skill.md +233 -0
  60. package/plugins/core/skill-doukui-sync/plugin.json +10 -0
  61. package/plugins/core/skill-doukui-sync/skill.md +76 -0
  62. package/plugins/core/skill-experience-logger/plugin.json +10 -0
  63. package/plugins/core/skill-experience-logger/skill.md +235 -0
  64. package/plugins/core/skill-human-checkpoint/plugin.json +10 -0
  65. package/plugins/core/skill-human-checkpoint/skill.md +194 -0
  66. package/plugins/core/skill-progress-tracker/plugin.json +10 -0
  67. package/plugins/core/skill-progress-tracker/skill.md +228 -0
  68. package/plugins/core/skill-role-manager/plugin.json +10 -0
  69. package/plugins/core/skill-role-manager/skill.md +252 -0
  70. package/plugins/core/skill-split-work-package/plugin.json +15 -0
  71. package/plugins/core/skill-split-work-package/skill.md +441 -0
  72. package/plugins/core/skill-task-archive/plugin.json +10 -0
  73. package/plugins/core/skill-task-archive/skill.md +116 -0
  74. package/plugins/core/skill-task-creator/plugin.json +15 -0
  75. package/plugins/core/skill-task-creator/skill.md +886 -0
  76. package/plugins/core/skill-team-cleanup/plugin.json +10 -0
  77. package/plugins/core/skill-team-cleanup/skill.md +266 -0
  78. package/plugins/core/skill-watchdog-manager/plugin.json +10 -0
  79. package/plugins/core/skill-watchdog-manager/skill.md +143 -0
  80. package/plugins/core/skill-workflow-orchestrator/plugin.json +13 -0
  81. package/plugins/core/skill-workflow-orchestrator/skill.md +273 -0
  82. package/plugins/core/validator-doc-sync/index.js +248 -0
  83. package/plugins/core/validator-doc-sync/plugin.json +12 -0
  84. package/plugins/core/validator-work-package/index.js +300 -0
  85. package/plugins/core/validator-work-package/plugin.json +12 -0
  86. package/plugins/plugin-registry.json +186 -0
  87. package/plugins/runtime/agent-def-generator.js +150 -0
  88. package/plugins/runtime/audit-logger.js +311 -0
  89. package/plugins/runtime/build-cli.js +89 -0
  90. package/plugins/runtime/checkresult-validator.js +131 -0
  91. package/plugins/runtime/claude-md-injector.js +159 -0
  92. package/plugins/runtime/cleanup-utils.js +293 -0
  93. package/plugins/runtime/config-manager.js +317 -0
  94. package/plugins/runtime/config-validator.js +320 -0
  95. package/plugins/runtime/context-window.js +81 -0
  96. package/plugins/runtime/event-bus.js +207 -0
  97. package/plugins/runtime/executor-claude.js +828 -0
  98. package/plugins/runtime/executor-default.js +448 -0
  99. package/plugins/runtime/executor-local.js +178 -0
  100. package/plugins/runtime/executor-sdk.js +415 -0
  101. package/plugins/runtime/harness-build.js +1037 -0
  102. package/plugins/runtime/hook-dispatcher.js +315 -0
  103. package/plugins/runtime/logger.js +192 -0
  104. package/plugins/runtime/loop-actuator.js +292 -0
  105. package/plugins/runtime/loop-coordinator.js +347 -0
  106. package/plugins/runtime/loop-defaults.js +29 -0
  107. package/plugins/runtime/loop-dispatch-batch.js +247 -0
  108. package/plugins/runtime/loop-executor.js +120 -0
  109. package/plugins/runtime/loop-report.js +327 -0
  110. package/plugins/runtime/loop-server-core.js +750 -0
  111. package/plugins/runtime/loop-snapshot.js +581 -0
  112. package/plugins/runtime/loop-trace.js +242 -0
  113. package/plugins/runtime/loop-worktree.js +404 -0
  114. package/plugins/runtime/manifest-resolver.js +457 -0
  115. package/plugins/runtime/multi-window-coordinator.js +560 -0
  116. package/plugins/runtime/objective-verifier.js +136 -0
  117. package/plugins/runtime/plan-lint.js +100 -0
  118. package/plugins/runtime/plan-reader.js +763 -0
  119. package/plugins/runtime/plugin-loader.js +798 -0
  120. package/plugins/runtime/plugin-trust.js +182 -0
  121. package/plugins/runtime/plugin-validator.js +491 -0
  122. package/plugins/runtime/provider-failover.js +114 -0
  123. package/plugins/runtime/provider-resolver.js +342 -0
  124. package/plugins/runtime/reflection-evaluator.js +545 -0
  125. package/plugins/runtime/resolve-plugin-path.js +297 -0
  126. package/plugins/runtime/safe-path.js +119 -0
  127. package/plugins/runtime/sandbox-context.js +235 -0
  128. package/plugins/runtime/sandbox-manager.js +609 -0
  129. package/plugins/runtime/sandbox-worker.js +215 -0
  130. package/plugins/runtime/self-rescue-ladder.js +38 -0
  131. package/plugins/runtime/settings-merger.js +172 -0
  132. package/plugins/runtime/state-store.js +527 -0
  133. package/plugins/runtime/team-cleanup.js +497 -0
  134. package/plugins/runtime/text-tokenize.js +25 -0
  135. package/plugins/runtime/validator-pipeline.js +475 -0
  136. package/plugins/runtime/yaml-parser.js +692 -0
  137. package/templates/harness-config.yaml +394 -0
@@ -0,0 +1,297 @@
1
+ /**
2
+ * resolve-plugin-path - Shared plugin path resolution
3
+ *
4
+ * Centralizes the path resolution logic used by both harness-build.js
5
+ * and plugin-loader.js. Supports absolute paths, relative paths, and
6
+ * the default core/ subdirectory convention.
7
+ *
8
+ * Supports sourceType field for external plugin sources:
9
+ * - 'core' (default) — built-in plugins under plugins/core/
10
+ * - 'npm' — npm package resolved via require.resolve()
11
+ * - 'local' — absolute or relative path outside core/
12
+ *
13
+ * @module resolve-plugin-path
14
+ */
15
+
16
+ 'use strict';
17
+
18
+ var fs = require('fs');
19
+ var path = require('path');
20
+ var safePath = require('./safe-path');
21
+ var isWithin = safePath.isWithin;
22
+
23
+ var VALID_SOURCE_TYPES = ['core', 'npm', 'local'];
24
+
25
+ /**
26
+ * Cross-platform absolute path check.
27
+ *
28
+ * Node's path.isAbsolute() is platform-specific: on POSIX it only
29
+ * recognizes /-prefixed paths; on Windows it only recognizes drive-letter
30
+ * and UNC paths. A plugin registry may contain Windows-style paths on a
31
+ * POSIX host (or vice versa), so we check both conventions.
32
+ *
33
+ * @internal
34
+ * @param {string} p - path to test
35
+ * @returns {boolean} true if p is absolute on either Windows or POSIX
36
+ */
37
+ function isAbsolutePath(p) {
38
+ if (path.isAbsolute(p)) return true;
39
+ // Windows drive-letter absolute path: C:\ D:/ etc.
40
+ if (/^[A-Za-z]:[\\\/]/.test(p)) return true;
41
+ return false;
42
+ }
43
+
44
+ /**
45
+ * Resolve the filesystem directory for a plugin entry.
46
+ *
47
+ * Resolution strategy by sourceType:
48
+ * - 'core' (default):
49
+ * 1. If source is absolute → use directly (must be a real directory)
50
+ * 2. If source has path separators → resolve relative to registryDir
51
+ * (S3: must remain inside the repo root, i.e. registryDir's parent;
52
+ * `..` escapes that climb past the repo root are rejected)
53
+ * 3. Otherwise → join defaultPluginsDir with source
54
+ * - 'npm':
55
+ * Resolve via require.resolve(packageName) and extract the directory.
56
+ * The source field is interpreted as an npm package name (with optional
57
+ * sub-path, e.g. 'doukui-plugin-foo/sub/path').
58
+ * - 'local':
59
+ * Absolute or relative path. Relative paths resolve against registryDir
60
+ * (S3: must remain inside the repo root).
61
+ *
62
+ * S3 SECURITY NOTE (path traversal):
63
+ * Relative sources may legitimately climb one level to a sibling directory
64
+ * inside the repository (e.g. '../custom-plugins/my-plugin'), but they may
65
+ * NOT escape the repository root entirely (e.g. '../../etc/passwd'). The
66
+ * repo root is taken to be the parent of registryDir. Absolute sources are
67
+ * allowed for trusted local/third-party installs and are NOT containment-
68
+ * checked (a user who points at an absolute path is opting into that path).
69
+ *
70
+ * @public
71
+ * @param {object} entry - Plugin registry entry
72
+ * @param {string} entry.name - Plugin name
73
+ * @param {string} [entry.source] - Source identifier (defaults to entry.name)
74
+ * @param {string} [entry.sourceType] - Source type: 'core' (default), 'npm', 'local'
75
+ * @param {string} defaultPluginsDir - Base directory for core plugins (e.g. .../plugins/core)
76
+ * @param {string} registryDir - Directory containing plugin-registry.json
77
+ * @returns {string} resolved absolute path to the plugin directory
78
+ * @throws {Error} if sourceType is invalid, npm package cannot be resolved,
79
+ * or a relative source escapes the repository root (S3)
80
+ */
81
+ function resolvePluginPath(entry, defaultPluginsDir, registryDir) {
82
+ var source = entry.source || entry.name;
83
+ if (!source) {
84
+ return path.join(defaultPluginsDir, 'unknown');
85
+ }
86
+
87
+ var sourceType = entry.sourceType || 'core';
88
+
89
+ // Validate sourceType
90
+ if (VALID_SOURCE_TYPES.indexOf(sourceType) === -1) {
91
+ throw new Error(
92
+ 'Invalid sourceType "' + sourceType + '" for plugin "' + (entry.name || 'unknown') +
93
+ '". Valid values: ' + VALID_SOURCE_TYPES.join(', ')
94
+ );
95
+ }
96
+
97
+ // npm source: resolve via require.resolve
98
+ if (sourceType === 'npm') {
99
+ return resolveNpmPath(source, entry.name);
100
+ }
101
+
102
+ // The repository root is the parent of registryDir (plugins/ → repo root).
103
+ // Relative sources must remain within this root.
104
+ var repoRoot = path.resolve(registryDir, '..');
105
+
106
+ // WP-S3-fix:字面层穿越守卫。POSIX 主机上 path.resolve 不识别反斜杠分隔符,
107
+ // Windows 风格 source(如 '..\\..\\Windows\\System32')会被当成单个字面段,
108
+ // 导致后续 assertWithinRepo 的 path.relative 看不到 '..' 而漏判。这里在 resolve
109
+ // 之前对相对 source 做净深度扫描,相对 registryDir 上爬 > 1 级即逃逸 repoRoot,
110
+ // 直接拒绝。绝对 source 已由 isAbsolutePath 分流为可信 opt-in,不进这里。
111
+ var sourceHasTraversal = !isAbsolutePath(source) && sourceEscapesRepoRoot(source);
112
+
113
+ // local source: absolute or relative path
114
+ if (sourceType === 'local') {
115
+ if (isAbsolutePath(source)) {
116
+ return source; // opt-in absolute path, trusted
117
+ }
118
+ if (sourceHasTraversal) {
119
+ throw new Error(
120
+ 'Plugin "' + (entry.name || 'unknown') + '" source path escapes the repository root: ' +
121
+ source + ' (root: ' + repoRoot + '). Refusing to resolve path-traversal source.'
122
+ );
123
+ }
124
+ var localResolved = path.resolve(registryDir, source);
125
+ assertWithinRepo(localResolved, repoRoot, entry.name);
126
+ return localResolved;
127
+ }
128
+
129
+ // core (default): existing behavior
130
+ // Absolute path → use directly (opt-in absolute path, trusted)
131
+ if (isAbsolutePath(source)) {
132
+ return source;
133
+ }
134
+
135
+ // Relative path containing path separators → resolve relative to registry directory
136
+ // (e.g. '../custom-plugins/my-plugin' or './my-plugin')
137
+ if (source.indexOf('/') !== -1 || source.indexOf('\\') !== -1) {
138
+ if (sourceHasTraversal) {
139
+ throw new Error(
140
+ 'Plugin "' + (entry.name || 'unknown') + '" source path escapes the repository root: ' +
141
+ source + ' (root: ' + repoRoot + '). Refusing to resolve path-traversal source.'
142
+ );
143
+ }
144
+ var resolved = path.resolve(registryDir, source);
145
+ assertWithinRepo(resolved, repoRoot, entry.name);
146
+ return resolved;
147
+ }
148
+
149
+ // Default: core plugin → join with defaultPluginsDir (a bare name, no traversal risk)
150
+ return path.join(defaultPluginsDir, source);
151
+ }
152
+
153
+ /**
154
+ * Reject a resolved path that escapes the repository root.
155
+ * Allows the path to equal the repo root or live anywhere beneath it, but
156
+ * not its ancestors/siblings outside the repo.
157
+ *
158
+ * @internal
159
+ * @param {string} resolved - absolute resolved plugin path
160
+ * @param {string} repoRoot - absolute repository root (parent of registryDir)
161
+ * @param {string} [pluginName] - for error messages
162
+ * @throws {Error} if resolved is not within repoRoot
163
+ */
164
+ function assertWithinRepo(resolved, repoRoot, pluginName) {
165
+ var rel = path.relative(path.resolve(repoRoot), path.resolve(resolved));
166
+ // rel === '' means the path IS the repo root (allowed).
167
+ // rel starts with '..' means it escaped the repo root (reject).
168
+ if (rel !== '' && (rel === '..' || rel.indexOf('..' + path.sep) === 0 ||
169
+ rel.indexOf('../') === 0 || rel.indexOf('..\\') === 0)) {
170
+ throw new Error(
171
+ 'Plugin "' + (pluginName || 'unknown') + '" source path escapes the repository root: ' +
172
+ resolved + ' (root: ' + repoRoot + '). Refusing to resolve path-traversal source.'
173
+ );
174
+ }
175
+ }
176
+
177
+ /**
178
+ * 字面层穿越检测:按两种路径分隔符(/ 与 \)切分 source,统计净目录深度。
179
+ * 用于在 path.resolve(POSIX 主机不识别反斜杠)之前拦截 Windows 风格的逃逸。
180
+ *
181
+ * 仅判定「相对 source 相对 registryDir 的净上爬深度」;绝对路径(含盘符/UNC)由
182
+ * 调用方 isAbsolutePath 提前分流,不经过本函数。
183
+ *
184
+ * 语义与 assertWithinRepo 对齐:repoRoot = registryDir 的父目录,故相对 registryDir
185
+ * 允许上爬至多 1 级(到达 repoRoot 本身或其下的同级目录)。瞬时深度低于 repoRoot
186
+ * (< -1)即逃逸 repoRoot。
187
+ *
188
+ * 必须用「扫描过程中的最小瞬时深度」而非「最终净深度」判定:一旦 `..` 把路径带到
189
+ * repoRoot 之上,后续下钻段只会从那个外部点继续往下走,并不能把路径拉回 repoRoot 之内。
190
+ * 净深度算法会被 `..\..\Windows\System32` 这类「先上爬再下钻」构造中和为 0 而漏判
191
+ * (CI 回归:POSIX 主机红、Windows 主机靠 assertWithinRepo 兜底而绿)。
192
+ *
193
+ * 例(min 深度 = 扫描过程中相对 registryDir 的最小瞬时深度,repoRoot = -1):
194
+ * '../custom-plugins/my-plugin' → min -1(恰达 repoRoot)→ 允许(同级目录)
195
+ * '../../etc/passwd' → min -2 → 拒绝
196
+ * '..\\..\\Windows\\System32' → min -2(先上爬出 repoRoot 再下钻,仍属逃逸)→ 拒绝
197
+ *
198
+ * @internal
199
+ * @param {string} source 待检测的相对 source 串
200
+ * @returns {boolean} true 表示该 source 扫描过程中瞬时深度低于 repoRoot(< -1),即逃逸 repoRoot
201
+ */
202
+ function sourceEscapesRepoRoot(source) {
203
+ if (typeof source !== 'string' || source === '') return false;
204
+ // 同时按两种分隔符切分,兼容跨平台 registry(Windows 风格 source 在 POSIX 主机上)。
205
+ var segs = source.split(/[\\/]/);
206
+ // depth = 相对 registryDir 的瞬时深度(registryDir 自身 = 0,repoRoot = -1)。
207
+ // 记录扫描过程中的最小值;后续下钻段无法抵消已经发生的上爬逃逸。
208
+ var depth = 0;
209
+ var minDepth = 0;
210
+ for (var i = 0; i < segs.length; i++) {
211
+ var s = segs[i];
212
+ if (s === '..') {
213
+ depth -= 1;
214
+ if (depth < minDepth) minDepth = depth;
215
+ } else if (s !== '' && s !== '.') {
216
+ depth += 1;
217
+ }
218
+ }
219
+ // repoRoot 是 registryDir 的父目录(深度 -1);瞬时深度 < -1 即逃出 repoRoot。
220
+ return minDepth < -1;
221
+ }
222
+
223
+ /**
224
+ * Resolve an npm package path using require.resolve().
225
+ *
226
+ * For a package like 'doukui-plugin-foo', resolves to the package root.
227
+ * For a scoped or sub-path like '@scope/foo/sub', resolves the sub-path.
228
+ *
229
+ * @internal
230
+ * @param {string} source - npm package name (with optional sub-path)
231
+ * @param {string} [pluginName] - plugin name for error messages
232
+ * @returns {string} resolved absolute path to the package directory
233
+ * @throws {Error} if the package cannot be resolved
234
+ */
235
+ function resolveNpmPath(source, pluginName) {
236
+ try {
237
+ // require.resolve with the package name gives us the entry point
238
+ // (package.json "main" or index.js). Extract directory from that.
239
+ var resolved = require.resolve(source);
240
+ // If the resolved path ends with index.js or similar, walk up to the package root.
241
+ // For packages that export a directory, require.resolve may return the directory itself.
242
+ var resolvedDir = resolved;
243
+
244
+ // Check if the resolved path is a file (has extension) — get its directory
245
+ var basename = path.basename(resolved);
246
+ if (basename === 'index.js' || basename === 'index.json' || basename.endsWith('.js') || basename.endsWith('.json')) {
247
+ // Walk up to find the package root (directory containing package.json)
248
+ resolvedDir = findPackageRoot(resolved);
249
+ }
250
+
251
+ return resolvedDir;
252
+ } catch (err) {
253
+ throw new Error(
254
+ 'Failed to resolve npm plugin "' + source + '"' +
255
+ (pluginName ? ' (plugin: ' + pluginName + ')' : '') +
256
+ ': ' + err.message +
257
+ '. Ensure the package is installed (npm install ' + source + ')'
258
+ );
259
+ }
260
+ }
261
+
262
+ /**
263
+ * Walk up from a resolved file path to find the package root directory.
264
+ * The package root is the nearest ancestor directory containing package.json.
265
+ *
266
+ * @internal
267
+ * @param {string} startPath - starting file or directory path
268
+ * @returns {string} package root directory
269
+ */
270
+ function findPackageRoot(startPath) {
271
+ var current = path.dirname(startPath);
272
+ var root = path.parse(current).root;
273
+
274
+ while (current !== root) {
275
+ var pkgJsonPath = path.join(current, 'package.json');
276
+ try {
277
+ if (fs.existsSync(pkgJsonPath)) {
278
+ return current;
279
+ }
280
+ } catch (e) {
281
+ // ignore
282
+ }
283
+ current = path.dirname(current);
284
+ }
285
+
286
+ // Fallback: return the directory of the resolved file
287
+ return path.dirname(startPath);
288
+ }
289
+
290
+ module.exports = {
291
+ resolvePluginPath: resolvePluginPath,
292
+ resolveNpmPath: resolveNpmPath,
293
+ VALID_SOURCE_TYPES: VALID_SOURCE_TYPES,
294
+ // 导出纯函数字面层守卫,便于跨平台单测覆盖(Windows 主机上 path.resolve 兜底会掩盖
295
+ // 该函数的语义回归,故必须直接单测)。仅用于测试,非公开 API。
296
+ sourceEscapesRepoRoot: sourceEscapesRepoRoot
297
+ };
@@ -0,0 +1,119 @@
1
+ /**
2
+ * safe-path - Shared path-safety primitives
3
+ *
4
+ * 统一全仓的「安全名称校验」与「路径包含判断」,替代散落各处的
5
+ * - child.indexOf(parent) === 0 (S6:/foo 误判为 /foobar 父目录)
6
+ * - 各模块自写的正则/拼接 (S4:loopId/wpId 路径穿越)
7
+ *
8
+ * 设计参考 team-cleanup.js 的 validateTeamName / isPathSafe(审查报告评为
9
+ * "全仓安全模范"),将其抽为可复用的纯函数。所有函数均无副作用、无 I/O,
10
+ * 便于单元测试。
11
+ *
12
+ * @module plugins/runtime/safe-path
13
+ */
14
+
15
+ 'use strict';
16
+
17
+ var path = require('path');
18
+ var fs = require('fs');
19
+
20
+ /**
21
+ * 合法标识符字符集:首字符字母/数字,其余允许 字母/数字/_/-,长度 1-64。
22
+ * 显式拒绝 '.', '..', '' 及任何路径分隔符(/ \ :)。
23
+ * 与 team-cleanup.validateTeamName 一致。
24
+ */
25
+ var SAFE_NAME_RE = /^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/;
26
+
27
+ /**
28
+ * 校验一个标识符是否只含安全字符(可用于 loopId / wpId / team 等拼进文件路径的输入)。
29
+ *
30
+ * @public
31
+ * @param {string} name 待校验的标识符
32
+ * @returns {{ok:true} | {ok:false, reason:string}}
33
+ * reason: 'empty' | 'invalid_chars' | 'too_long' | 'not_string'
34
+ */
35
+ function validateSafeName(name) {
36
+ if (name === undefined || name === null || name === '') {
37
+ return { ok: false, reason: 'empty' };
38
+ }
39
+ if (typeof name !== 'string') {
40
+ return { ok: false, reason: 'not_string' };
41
+ }
42
+ if (name === '.' || name === '..') {
43
+ return { ok: false, reason: 'invalid_chars' };
44
+ }
45
+ if (name.length > 64) {
46
+ return { ok: false, reason: 'too_long' };
47
+ }
48
+ // 拒绝任何路径分隔符或盘符冒号(防 'a/../../etc' 这类)
49
+ if (/[\/\\:]/.test(name)) {
50
+ return { ok: false, reason: 'invalid_chars' };
51
+ }
52
+ if (!SAFE_NAME_RE.test(name)) {
53
+ return { ok: false, reason: 'invalid_chars' };
54
+ }
55
+ return { ok: true };
56
+ }
57
+
58
+ /**
59
+ * 断言式校验:非法即抛错(携带原因),合法返回原值。
60
+ *
61
+ * 供拼路径前做前置守卫用:
62
+ * var safeLoopId = assertSafeName(loopId, 'loopId');
63
+ * path.join(stateDir, safeLoopId, 'directive.json');
64
+ *
65
+ * @public
66
+ * @param {string} name 待校验标识符
67
+ * @param {string} [label] 用于错误信息的字段名(如 'loopId')
68
+ * @returns {string} 校验通过的 name 原值
69
+ * @throws {Error} 当 name 非法时,message 形如 "Invalid loopId: <reason>"
70
+ */
71
+ function assertSafeName(name, label) {
72
+ var r = validateSafeName(name);
73
+ if (!r.ok) {
74
+ throw new Error('Invalid ' + (label || 'name') + ': ' + r.reason);
75
+ }
76
+ return name;
77
+ }
78
+
79
+ /**
80
+ * 判断 child 路径是否严格位于 parent 目录之内(S6 的正确实现)。
81
+ *
82
+ * 修复经典反模式 child.indexOf(parent) === 0:那会把 /foo 当成 /foobar 的父目录。
83
+ * 这里用 path.relative 计算:结果不以 '..' 开头且非空串即视为包含。
84
+ * 会对两端做 path.resolve(绝对化),故传入相对路径也安全。
85
+ *
86
+ * @public
87
+ * @param {string} parent 父目录(绝对或相对)
88
+ * @param {string} child 待判定的子路径
89
+ * @returns {boolean}
90
+ */
91
+ function isWithin(parent, child) {
92
+ if (typeof parent !== 'string' || typeof child !== 'string') return false;
93
+ var rel = path.relative(path.resolve(parent), path.resolve(child));
94
+ if (rel === '') return false; // 完全相同不算"包含在内"
95
+ return rel !== '..' && rel.indexOf('..' + path.sep) !== 0 && rel.indexOf('..' + '/') !== 0;
96
+ }
97
+
98
+ /**
99
+ * 判断一个路径条目是否为符号链接(用于 cleanup 前 lstat 防护,S5)。
100
+ *
101
+ * @public
102
+ * @param {string} p 路径
103
+ * @returns {boolean} true 表示是 symlink(含 Windows junction)
104
+ */
105
+ function isSymlink(p) {
106
+ try {
107
+ return fs.lstatSync(p).isSymbolicLink();
108
+ } catch (_e) {
109
+ return false;
110
+ }
111
+ }
112
+
113
+ module.exports = {
114
+ SAFE_NAME_RE: SAFE_NAME_RE,
115
+ validateSafeName: validateSafeName,
116
+ assertSafeName: assertSafeName,
117
+ isWithin: isWithin,
118
+ isSymlink: isSymlink,
119
+ };
@@ -0,0 +1,235 @@
1
+ /**
2
+ * SandboxContext - Standalone RPC proxy context factory
3
+ *
4
+ * Provides two utilities:
5
+ * 1. createSandboxProxy() - creates a PluginContext-like proxy object that
6
+ * forwards method calls through a message port (used inside Worker Threads)
7
+ * 2. createMainThreadBridge() - creates a message handler for the main thread
8
+ * side that dispatches RPC calls to real services
9
+ *
10
+ * This module complements the inline SandboxContext in sandbox-worker.js by
11
+ * providing a testable factory that can be used outside of Worker Threads.
12
+ *
13
+ * @module sandbox-context
14
+ */
15
+
16
+ 'use strict';
17
+
18
+ /**
19
+ * Create a sandbox proxy object that mimics PluginContext interface.
20
+ * All method calls are forwarded as RPC messages through the given port.
21
+ *
22
+ * This is the main-thread side factory for creating proxy objects
23
+ * that can be tested without Worker Threads.
24
+ *
25
+ * @experimental
26
+ * @param {string} pluginName - plugin name
27
+ * @param {object} port - message port with postMessage/on/off methods
28
+ * @returns {object} proxy context object
29
+ */
30
+ function createSandboxProxy(pluginName, port) {
31
+ var rpcId = 0;
32
+
33
+ /**
34
+ * Send an RPC call and wait for the response.
35
+ * @param {string} method
36
+ * @param {Array} args
37
+ * @returns {Promise<any>}
38
+ */
39
+ function rpc(method, args) {
40
+ var id = ++rpcId;
41
+
42
+ return new Promise(function (resolve, reject) {
43
+ var handler = function (msg) {
44
+ if (msg.type === 'rpc-response' && msg.id === id) {
45
+ port.off('message', handler);
46
+ if (msg.error) {
47
+ reject(new Error(msg.error));
48
+ } else {
49
+ resolve(msg.result);
50
+ }
51
+ }
52
+ };
53
+
54
+ port.on('message', handler);
55
+ port.postMessage({
56
+ type: 'rpc-request',
57
+ id: id,
58
+ method: method,
59
+ args: args,
60
+ });
61
+ });
62
+ }
63
+
64
+ return {
65
+ pluginName: pluginName,
66
+ _rpc: rpc,
67
+
68
+ eventBus: {
69
+ emit: function (event, data) {
70
+ return rpc('eventBus.emit', [event, data]);
71
+ },
72
+ },
73
+
74
+ stateStore: {
75
+ get: function (key) {
76
+ return rpc('stateStore.get', [key]);
77
+ },
78
+ set: function (key, value) {
79
+ return rpc('stateStore.set', [key, value]);
80
+ },
81
+ delete: function (key) {
82
+ return rpc('stateStore.delete', [key]);
83
+ },
84
+ },
85
+
86
+ logger: {
87
+ info: function (msg) {
88
+ return rpc('logger.info', [msg]);
89
+ },
90
+ warn: function (msg) {
91
+ return rpc('logger.warn', [msg]);
92
+ },
93
+ error: function (msg) {
94
+ return rpc('logger.error', [msg]);
95
+ },
96
+ },
97
+
98
+ config: {
99
+ get: function (key) {
100
+ return rpc('config.get', [key]);
101
+ },
102
+ },
103
+
104
+ getProvider: function (name) {
105
+ return rpc('getProvider', [name]);
106
+ },
107
+
108
+ getPlugin: function () {
109
+ return undefined; // Not supported in sandbox
110
+ },
111
+ };
112
+ }
113
+
114
+ /**
115
+ * Create a main-thread RPC handler that dispatches calls to real services.
116
+ *
117
+ * @experimental
118
+ * @param {object} services - { eventBus, stateStore, logger, configManager, getProvider }
119
+ * @param {object} options
120
+ * @param {Function} [options.onRpc] - callback for each RPC call (for testing/auditing)
121
+ * @returns {Function} message handler function (to attach to worker/port 'message' event)
122
+ */
123
+ function createMainThreadBridge(services, options) {
124
+ options = options || {};
125
+
126
+ /**
127
+ * Message handler for RPC dispatch.
128
+ *
129
+ * @param {object} msg - RPC request message
130
+ * @param {object} [respondTo] - object with postMessage method (e.g. Worker or test port)
131
+ */
132
+ return function handleRpcMessage(msg, respondTo) {
133
+ if (!msg || msg.type !== 'rpc-request') return;
134
+
135
+ var id = msg.id;
136
+ var method = msg.method;
137
+ var args = msg.args || [];
138
+
139
+ // Notify callback
140
+ if (options.onRpc) {
141
+ options.onRpc(method, args);
142
+ }
143
+
144
+ // Execute the method
145
+ try {
146
+ var result = callService(services, method, args);
147
+
148
+ if (result && typeof result.then === 'function') {
149
+ result.then(function (resolved) {
150
+ sendResponse(respondTo, id, resolved, null);
151
+ }).catch(function (err) {
152
+ sendResponse(respondTo, id, null, err.message);
153
+ });
154
+ } else {
155
+ sendResponse(respondTo, id, result, null);
156
+ }
157
+ } catch (err) {
158
+ sendResponse(respondTo, id, null, err.message);
159
+ }
160
+ };
161
+ }
162
+
163
+ /**
164
+ * Call a service method by name.
165
+ *
166
+ * @internal
167
+ * @param {object} services
168
+ * @param {string} method
169
+ * @param {Array} args
170
+ * @returns {*}
171
+ */
172
+ function callService(services, method, args) {
173
+ // Known methods: if service is available, call it; if not, return undefined
174
+ if (method === 'eventBus.emit') {
175
+ return services.eventBus ? services.eventBus.emit(args[0], args[1]) : undefined;
176
+ }
177
+ if (method === 'stateStore.get') {
178
+ return services.stateStore ? services.stateStore.get(args[0]) : undefined;
179
+ }
180
+ if (method === 'stateStore.set') {
181
+ return services.stateStore ? services.stateStore.set(args[0], args[1]) : undefined;
182
+ }
183
+ if (method === 'stateStore.delete') {
184
+ return services.stateStore ? services.stateStore.delete(args[0]) : undefined;
185
+ }
186
+ if (method === 'logger.info') {
187
+ return services.logger ? services.logger.info(args[0]) : undefined;
188
+ }
189
+ if (method === 'logger.warn') {
190
+ return services.logger ? services.logger.warn(args[0]) : undefined;
191
+ }
192
+ if (method === 'logger.error') {
193
+ return services.logger ? services.logger.error(args[0]) : undefined;
194
+ }
195
+ if (method === 'config.get') {
196
+ return services.configManager ? services.configManager.get(args[0]) : undefined;
197
+ }
198
+ if (method === 'getProvider') {
199
+ return services.getProvider ? services.getProvider(args[0]) : undefined;
200
+ }
201
+
202
+ throw new Error('Unknown RPC method: ' + method);
203
+ }
204
+
205
+ /**
206
+ * Send an RPC response.
207
+ *
208
+ * @internal
209
+ * @param {object|null} respondTo - object with postMessage method
210
+ * @param {number} id - RPC call ID
211
+ * @param {*} result - result value
212
+ * @param {string|null} error - error message
213
+ */
214
+ function sendResponse(respondTo, id, result, error) {
215
+ if (!respondTo) return;
216
+
217
+ var response = {
218
+ type: 'rpc-response',
219
+ id: id,
220
+ };
221
+
222
+ if (error) {
223
+ response.error = error;
224
+ } else {
225
+ response.result = result;
226
+ }
227
+
228
+ respondTo.postMessage(response);
229
+ }
230
+
231
+ module.exports = {
232
+ createSandboxProxy: createSandboxProxy,
233
+ createMainThreadBridge: createMainThreadBridge,
234
+ callService: callService,
235
+ };