skill-family-doc-render 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright (c) 2026 skill-family-foundation-workspace contributors
190
+ Copyright (c) 2026 广州市风荷科技有限公司
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,139 @@
1
+ # skill-family-doc-render
2
+
3
+ Config-driven GitHub Pages knowledge-site renderer for skill-family projects (multi-repo capable).
4
+
5
+ Reads `public-release.json` from the current working directory, renders every repo carrying a
6
+ `site` field from its site source directory to its target directory (typically `docs/`), injects
7
+ nav / pager / footer, replaces version placeholders, copies assets, writes `.nojekyll` and a
8
+ tree baseline (`site-baseline.json`), and runs a content-level leak scan before any write.
9
+
10
+ ## Install
11
+
12
+ ```sh
13
+ npm install skill-family-doc-render
14
+ ```
15
+
16
+ Requires Node.js `>=22.22.2 <23` (aligned with the skill-family foundation packages).
17
+
18
+ ## CLI
19
+
20
+ ```sh
21
+ # render all repos with a site field (writes to disk)
22
+ npx skill-family-doc-render
23
+
24
+ # drift check only: compare in-memory render against committed site-baseline.json, write nothing
25
+ npx skill-family-doc-render --check
26
+
27
+ # render / check a single repo by name
28
+ npx skill-family-doc-render --repo <name>
29
+
30
+ # additionally assert every rendered file is tracked in the git index
31
+ npx skill-family-doc-render --assert-git
32
+ ```
33
+
34
+ Exit codes: `0` success, `1` drift / check failure / leak-scan hit, `2` configuration or
35
+ schema validation error (the message includes the JSON field path).
36
+
37
+ ## Configuration: `public-release.json`
38
+
39
+ The config file lives at the workspace root (resolved from `process.cwd()`). It is validated
40
+ against `schemas/public-release.schema.json` (JSON Schema 2020-12, strict policy) before
41
+ anything runs.
42
+
43
+ ```json
44
+ {
45
+ "owner": "your-org",
46
+ "defaultBranch": "main",
47
+ "license": "Apache-2.0",
48
+ "repos": [
49
+ {
50
+ "name": "my-project",
51
+ "source": "packages/my-project",
52
+ "tagPrefix": "my-project-v",
53
+ "site": {
54
+ "dir": "site-src",
55
+ "target": "docs",
56
+ "pages": "pages.json",
57
+ "tokens": { "@CUSTOM_NOTE@": "any static placeholder" }
58
+ }
59
+ }
60
+ ],
61
+ "forbiddenPublicPaths": ["public-release.json"],
62
+ "privateLiterals": []
63
+ }
64
+ ```
65
+
66
+ - Only repos with a `site` field are rendered; `--repo <name>` selects one by `name`.
67
+ - `site.pages` points to a pages manifest: `{ "pages": [{ "id", "title", "order", "inPager" }] }`.
68
+ Pages are sorted by `order`; `inPager: false` excludes a page from the prev/next pager.
69
+ - `forbiddenPublicPaths` / `privateLiterals` append project-specific literals to the leak scan.
70
+
71
+ ## Placeholders
72
+
73
+ Source pages use three HTML-comment injection points, replaced at render time:
74
+
75
+ - `<!--NAV-->` — table-of-contents nav (active page gets `class="active"`)
76
+ - `<!--PAGER-->` — circular prev/next pager
77
+ - `<!--FOOTER-->` — site footer (owner + license)
78
+
79
+ Version tokens are derived automatically from the repo's `package.json` version and `name`
80
+ (uppercased, non-alphanumeric runs collapsed to `_`):
81
+
82
+ - `@{NAME}_TAG@` — e.g. `my-project` → `@MY_PROJECT_TAG@` = `tagPrefix` + version
83
+ - `@{NAME}_VERSION@` — the bare version
84
+
85
+ `site.tokens` adds arbitrary static placeholder replacements on top.
86
+
87
+ ## Leak scan
88
+
89
+ Every rendered page is scanned **before** any write (`scripts/lib/leak-scan.mjs`). The scanner
90
+ decodes HTML entities and JS escape sequences first, then matches the decoded text against
91
+ built-in private literals (absolute home paths) and secret regexes (private keys, GitHub /
92
+ Slack / AWS / OpenAI tokens), plus the configured `forbiddenPublicPaths` / `privateLiterals`.
93
+ Any hit fails the run fast — encoding tricks do not slip through.
94
+
95
+ ## Tree baseline
96
+
97
+ After writing, the renderer records `site-baseline.json` in the target directory:
98
+
99
+ ```json
100
+ { "sha256": "<closure digest>", "files": ["<sorted relative paths, excluding the baseline itself>"] }
101
+ ```
102
+
103
+ `--check` recomputes the digest from the in-memory render and fails on any drift. The digest is
104
+ a deterministic set-level sha256 over the contained resources.
105
+
106
+ ## Foundation dependencies
107
+
108
+ This package is a thin domain layer over the skill-family foundation and adds no other runtime
109
+ dependencies:
110
+
111
+ - [`skill-family-harness-node`](https://github.com/ifoohoo/skill-family-harness-node) — all file
112
+ reads go through `resolveContained` / `readFileContained` (path traversal, symlink and realpath
113
+ escapes rejected), all writes through `writeFileAtomic` (containment + atomic rename), and the
114
+ tree baseline is computed with `computeResourceClosure`.
115
+ - [`skill-family-contracts`](https://github.com/ifoohoo/skill-family-contracts) —
116
+ `validateDocument` (JSON Schema 2020-12, strict policy) validates `public-release.json` and
117
+ `site-baseline.json`; validation failure aborts with exit code 2.
118
+
119
+ ## License
120
+
121
+ Apache-2.0
122
+
123
+ <!-- release-skill:capability:safe-first-command -->
124
+ > **Start here:** `npx skill-family-doc-render --check` — the drift check is read-only:
125
+ > it renders in memory, compares against the committed `site-baseline.json`, writes
126
+ > nothing, and touches no network, git, or credentials.
127
+
128
+ <!-- release-skill:capability:external-write-boundary -->
129
+ > **External write boundary:** this CLI writes only inside the site target directories
130
+ > declared by the project's own `public-release.json` (via contained, atomic writes).
131
+ > It performs no git operations, no network calls, and no writes outside those
132
+ > directories. The pre-write leak scan fails closed on private literals.
133
+
134
+ ## Minimal example
135
+
136
+ ```sh
137
+ npx skill-family-doc-render --help # show usage
138
+ npx skill-family-doc-render --check # read-only drift check — the safe first command
139
+ ```
@@ -0,0 +1,29 @@
1
+ #!/usr/bin/env node
2
+ // SPDX-License-Identifier: Apache-2.0
3
+ // CLI 入口:从 process.cwd() 解析 public-release.json,
4
+ // 转发 --check / --repo <name> / --assert-git 到渲染器主流程。
5
+ import { main, RenderError } from '../scripts/render-public-site.mjs';
6
+
7
+ const argv = process.argv.slice(2);
8
+
9
+ if (argv.includes('--help') || argv.includes('-h')) {
10
+ console.log(`skill-family-doc-render — config-driven GitHub Pages knowledge-site renderer
11
+
12
+ Usage:
13
+ skill-family-doc-render render every repo with a site field (writes)
14
+ skill-family-doc-render --check read-only drift check against site-baseline.json
15
+ skill-family-doc-render --repo <name> render / check a single repo by name
16
+ skill-family-doc-render --assert-git also assert rendered files are git-tracked
17
+
18
+ Reads public-release.json from the current working directory.`);
19
+ process.exitCode = 0;
20
+ } else {
21
+ main(argv, { cwd: process.cwd() })
22
+ .then((code) => {
23
+ process.exitCode = code;
24
+ })
25
+ .catch((err) => {
26
+ console.error(err.message);
27
+ process.exitCode = err instanceof RenderError ? err.exitCode : 1;
28
+ });
29
+ }
package/package.json ADDED
@@ -0,0 +1,30 @@
1
+ {
2
+ "name": "skill-family-doc-render",
3
+ "version": "0.1.0",
4
+ "description": "Config-driven GitHub Pages knowledge-site renderer for skill-family projects (multi-repo capable).",
5
+ "author": "广州市风荷科技有限公司",
6
+ "license": "Apache-2.0",
7
+ "type": "module",
8
+ "engines": {
9
+ "node": ">=22.22.2 <23"
10
+ },
11
+ "bin": {
12
+ "skill-family-doc-render": "bin/skill-family-doc-render.mjs"
13
+ },
14
+ "files": [
15
+ "bin",
16
+ "scripts",
17
+ "schemas",
18
+ "README.md",
19
+ "LICENSE"
20
+ ],
21
+ "scripts": {
22
+ "test": "node --test test/*.test.mjs",
23
+ "render:site": "node bin/skill-family-doc-render.mjs",
24
+ "render:site:check": "node bin/skill-family-doc-render.mjs --check"
25
+ },
26
+ "dependencies": {
27
+ "skill-family-contracts": "0.2.1",
28
+ "skill-family-harness-node": "0.2.1"
29
+ }
30
+ }
@@ -0,0 +1,52 @@
1
+ {
2
+ "$id": "https://github.com/ifoohoo/skill-family-doc-render/schemas/public-release.schema.json",
3
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
4
+ "title": "public-release.json",
5
+ "description": "skill-family-doc-render 的渲染配置真源:谁带 site 字段就渲染谁。",
6
+ "type": "object",
7
+ "additionalProperties": false,
8
+ "required": ["repos"],
9
+ "properties": {
10
+ "owner": { "type": "string", "minLength": 1 },
11
+ "defaultBranch": { "type": "string", "minLength": 1 },
12
+ "license": { "type": "string", "minLength": 1 },
13
+ "repos": {
14
+ "type": "array",
15
+ "minItems": 1,
16
+ "items": {
17
+ "type": "object",
18
+ "additionalProperties": false,
19
+ "required": ["name", "source"],
20
+ "properties": {
21
+ "name": { "type": "string", "minLength": 1 },
22
+ "source": { "type": "string", "minLength": 1 },
23
+ "tagPrefix": { "type": "string", "minLength": 1 },
24
+ "site": {
25
+ "type": "object",
26
+ "additionalProperties": false,
27
+ "required": ["dir", "target", "pages"],
28
+ "properties": {
29
+ "dir": { "type": "string", "minLength": 1 },
30
+ "target": { "type": "string", "minLength": 1 },
31
+ "pages": { "type": "string", "minLength": 1 },
32
+ "tokens": {
33
+ "type": "object",
34
+ "additionalProperties": {
35
+ "anyOf": [{ "type": "string" }, { "type": "number" }, { "type": "boolean" }]
36
+ }
37
+ }
38
+ }
39
+ }
40
+ }
41
+ }
42
+ },
43
+ "forbiddenPublicPaths": {
44
+ "type": "array",
45
+ "items": { "type": "string", "minLength": 1 }
46
+ },
47
+ "privateLiterals": {
48
+ "type": "array",
49
+ "items": { "type": "string", "minLength": 1 }
50
+ }
51
+ }
52
+ }
@@ -0,0 +1,16 @@
1
+ {
2
+ "$id": "https://github.com/ifoohoo/skill-family-doc-render/schemas/site-baseline.schema.json",
3
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
4
+ "title": "site-baseline.json",
5
+ "description": "站点树基线:closure 集合级 sha256 + 排序后的相对路径列表(排除基线自身)。",
6
+ "type": "object",
7
+ "additionalProperties": false,
8
+ "required": ["sha256", "files"],
9
+ "properties": {
10
+ "sha256": { "type": "string", "pattern": "^[0-9a-f]{64}$" },
11
+ "files": {
12
+ "type": "array",
13
+ "items": { "type": "string", "minLength": 1 }
14
+ }
15
+ }
16
+ }
@@ -0,0 +1,56 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ // 内容级泄漏扫描:解码后再匹配,防 HTML 实体 / JS 反转义绕过。
3
+ // 默认扫描绝对路径与私钥 / Token;项目特定的私有字面量通过调用方传入
4
+ // (来自 public-release.json 的 forbiddenPublicPaths / privateLiterals)。
5
+ export const DEFAULT_LITERALS = [
6
+ '/Users/',
7
+ 'C:\\Users\\',
8
+ '/home/',
9
+ '/private/',
10
+ ];
11
+
12
+ export const DEFAULT_REGEXES = [
13
+ /-----BEGIN (?:RSA |EC |OPENSSH |DSA |PGP )?PRIVATE KEY-----/,
14
+ /ghp_[A-Za-z0-9]{36}/,
15
+ /gho_[A-Za-z0-9]{36}/,
16
+ /ghu_[A-Za-z0-9]{36}/,
17
+ /github_pat_[A-Za-z0-9_]{82}/,
18
+ /xox[baprs]-[A-Za-z0-9-]+/,
19
+ /AKIA[0-9A-Z]{16}/,
20
+ /sk-[A-Za-z0-9]{32,}/,
21
+ ];
22
+
23
+ // 对文本做 HTML 实体解码 + JS 反转义,得到规范化文本,与原文拼接后扫描,
24
+ // 使绕过者无法用实体 / 转义把敏感字面量藏过简单 includes 检查。
25
+ export function decodeText(s) {
26
+ let d = s
27
+ .replace(/&amp;/g, '&')
28
+ .replace(/&lt;/g, '<')
29
+ .replace(/&gt;/g, '>')
30
+ .replace(/&quot;/g, '"')
31
+ .replace(/&#x([0-9a-fA-F]+);/g, (m, h) => String.fromCodePoint(parseInt(h, 16)))
32
+ .replace(/&#(\d+);/g, (m, d) => String.fromCodePoint(parseInt(d, 10)));
33
+ d = d
34
+ .replace(/\\x([0-9a-fA-F]{2})/g, (m, h) => String.fromCharCode(parseInt(h, 16)))
35
+ .replace(/\\u\{([0-9a-fA-F]+)\}/g, (m, h) => String.fromCodePoint(parseInt(h, 16)))
36
+ .replace(/\\u([0-9a-fA-F]{4})/g, (m, h) => String.fromCharCode(parseInt(h, 16)))
37
+ .replace(/\\([0-7]{3})/g, (m, o) => String.fromCharCode(parseInt(o, 8)));
38
+ return s + '\n' + d;
39
+ }
40
+
41
+ // relPath: 仅用于报错信息;text: 待扫描原文;opts.literals / opts.regexes 为追加项。
42
+ export function scanLeak(relPath, text, { literals = [], regexes = [] } = {}) {
43
+ const probe = decodeText(text);
44
+ const allLit = [...DEFAULT_LITERALS, ...literals];
45
+ for (const lit of allLit) {
46
+ for (const enc of ['utf8', 'utf16le']) {
47
+ if (Buffer.from(probe, enc).includes(Buffer.from(lit, enc))) {
48
+ throw new Error(`[泄漏扫描] ${relPath} 命中私有字面量: ${lit}`);
49
+ }
50
+ }
51
+ }
52
+ const allRe = [...DEFAULT_REGEXES, ...regexes];
53
+ for (const re of allRe) {
54
+ if (re.test(probe)) throw new Error(`[泄漏扫描] ${relPath} 命中私有正则: ${re}`);
55
+ }
56
+ }
@@ -0,0 +1,294 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ // 通用 GitHub Pages 知识站渲染器(配置驱动,多仓库)。
3
+ // 遍历 public-release.json 中所有带 site 字段的 repo,渲染各自 docs/public/site/ 源到 docs/。
4
+ // 注入 nav / pager / footer、替换版本占位符、拷贝 assets、写 .nojekyll 与 tree 基线。
5
+ // 写盘前做内容级泄漏扫描(解码后再匹配,防 HTML 实体 / JS 反转义绕过)。
6
+ //
7
+ // harness 化:所有配置 / 源文件读取经 readFileContained,所有写盘经 writeFileAtomic
8
+ // (收容 + 原子写,见 skill-family-harness-node);树基线摘要改用 computeResourceClosure。
9
+ // 配置与基线文件先经 skill-family-contracts validateDocument(JSON Schema 2020-12,
10
+ // strict 策略)校验,校验失败 fail-fast。
11
+ import { existsSync, readFileSync } from 'node:fs';
12
+ import { readdir, rm } from 'node:fs/promises';
13
+ import { resolve, relative, extname, join, dirname } from 'node:path';
14
+ import { fileURLToPath } from 'node:url';
15
+ import { execSync } from 'node:child_process';
16
+ import {
17
+ resolveContained,
18
+ readFileContained,
19
+ writeFileAtomic,
20
+ computeResourceClosure,
21
+ } from 'skill-family-harness-node';
22
+ import { validateDocument } from 'skill-family-contracts';
23
+ import { scanLeak } from './lib/leak-scan.mjs';
24
+
25
+ const __dirname = dirname(fileURLToPath(import.meta.url));
26
+
27
+ // 包内 schema(渲染器自身资源,不属于工作区文件,直接读取)
28
+ const publicReleaseSchema = JSON.parse(
29
+ readFileSync(join(__dirname, '..', 'schemas', 'public-release.schema.json'), 'utf8'),
30
+ );
31
+ const siteBaselineSchema = JSON.parse(
32
+ readFileSync(join(__dirname, '..', 'schemas', 'site-baseline.schema.json'), 'utf8'),
33
+ );
34
+
35
+ // 可预期失败(配置缺失、校验失败、check 漂移等)以此类型抛出,携带退出码。
36
+ export class RenderError extends Error {
37
+ constructor(message, exitCode = 2) {
38
+ super(message);
39
+ this.exitCode = exitCode;
40
+ }
41
+ }
42
+
43
+ function assertValid(doc, schema, label) {
44
+ const { valid, errors } = validateDocument(doc, { schema, dialect: '2020-12', policy: 'strict' });
45
+ if (!valid) {
46
+ const detail = errors.map((e) => `${e.instancePath || '(root)'}: ${e.message}`).join('; ');
47
+ throw new RenderError(`[render-public-site] ${label} 校验失败: ${detail}`, 2);
48
+ }
49
+ }
50
+
51
+ function tokenName(name) {
52
+ return name.toUpperCase().replace(/[^A-Z0-9]+/g, '_');
53
+ }
54
+
55
+ async function pkgVersion(root, src) {
56
+ try {
57
+ return JSON.parse(await readFileContained(root, join(src, 'package.json'), { encoding: 'utf8' })).version;
58
+ } catch {
59
+ return '0.0.0';
60
+ }
61
+ }
62
+
63
+ // --- 树摘要(基于 computeResourceClosure,排除 site-baseline.json 自身,防 hash 循环) ---
64
+ async function treeDigest(rootAbs, files) {
65
+ const closure = await computeResourceClosure({
66
+ root: rootAbs,
67
+ resources: files.map((path) => ({ path, role: 'input' })),
68
+ });
69
+ return closure.digest;
70
+ }
71
+
72
+ async function listTargetFiles(rootAbs) {
73
+ const out = [];
74
+ async function walk(d) {
75
+ for (const e of await readdir(d, { withFileTypes: true })) {
76
+ const fp = join(d, e.name);
77
+ if (e.isDirectory()) await walk(fp);
78
+ else out.push(relative(rootAbs, fp));
79
+ }
80
+ }
81
+ await walk(rootAbs);
82
+ return out.filter((f) => f !== 'site-baseline.json').sort();
83
+ }
84
+
85
+ // --- 渲染单仓 ---
86
+ async function renderRepo(root, repo, release, leakLiterals, { check, assertGit }) {
87
+ const site = repo.site;
88
+ const dirRel = join(repo.source, site.dir);
89
+ const pagesRel = join(dirRel, site.pages);
90
+ const targetRel = join(repo.source, site.target);
91
+ const targetAbs = resolve(root, targetRel);
92
+ if (!existsSync(resolve(root, pagesRel))) {
93
+ throw new RenderError(`[render-public-site] ${repo.name}: pages.json 未找到: ${pagesRel}`, 2);
94
+ }
95
+ const pages = JSON.parse(await readFileContained(root, pagesRel, { encoding: 'utf8' })).pages;
96
+ const ordered = [...pages].sort((a, b) => a.order - b.order);
97
+ const pagerPages = ordered.filter((p) => p.inPager !== false);
98
+
99
+ function navHtml(currentId) {
100
+ const items = ordered
101
+ .map((p) => ` <a href="${p.id}.html"${p.id === currentId ? ' class="active"' : ''}>${p.title}</a>`)
102
+ .join('\n');
103
+ return `<nav class="toc">\n${items}\n </nav>`;
104
+ }
105
+ function pagerHtml(currentId) {
106
+ const idx = pagerPages.findIndex((p) => p.id === currentId);
107
+ if (idx < 0) return '<nav class="pager"></nav>';
108
+ const prev = pagerPages[(idx - 1 + pagerPages.length) % pagerPages.length];
109
+ const next = pagerPages[(idx + 1) % pagerPages.length];
110
+ return `<nav class="pager">\n <a href="${prev.id}.html">← ${prev.title}</a>\n <span class="spacer"></span>\n <a href="${next.id}.html">${next.title} →</a>\n </nav>`;
111
+ }
112
+ function footerHtml() {
113
+ const owner = release.owner || 'your-org';
114
+ return `<footer class="site">\n <div>© ${owner} · <a href="https://www.apache.org/licenses/LICENSE-2.0" rel="noopener noreferrer">Apache-2.0</a></div>\n <div class="generated">generated by skill-family-doc-render</div>\n</footer>`;
115
+ }
116
+
117
+ // 版本占位符:按 repo 名自动派生(@{NAME}_TAG@ / @{NAME}_VERSION@)+ site.tokens 静态补充
118
+ const version = await pkgVersion(root, repo.source);
119
+ const tn = tokenName(repo.name);
120
+ const tokens = {
121
+ [`@${tn}_TAG@`]: (repo.tagPrefix || `${repo.name}-v`) + version,
122
+ [`@${tn}_VERSION@`]: version,
123
+ ...(site.tokens || {}),
124
+ };
125
+ function replaceTokens(s) {
126
+ let out = s;
127
+ for (const [k, v] of Object.entries(tokens)) out = out.split(k).join(String(v));
128
+ return out;
129
+ }
130
+
131
+ const rendered = [];
132
+ for (const p of ordered) {
133
+ let html = await readFileContained(root, join(dirRel, p.id + '.html'), { encoding: 'utf8' });
134
+ html = html
135
+ .replace(/<!--NAV-->/g, navHtml(p.id))
136
+ .replace(/<!--PAGER-->/g, pagerHtml(p.id))
137
+ .replace(/<!--FOOTER-->/g, footerHtml());
138
+ html = replaceTokens(html);
139
+ rendered.push({ p, html });
140
+ }
141
+ for (const { p, html } of rendered) scanLeak(`${repo.name}/${p.id}.html`, html, { literals: leakLiterals });
142
+
143
+ if (check) {
144
+ if (!existsSync(targetAbs)) {
145
+ throw new RenderError(
146
+ `[render-public-site --check] ${repo.name}: 目标 ${targetRel} 不存在,请先运行渲染`,
147
+ 1,
148
+ );
149
+ }
150
+ // 不写盘,仅依据内存产物计算树摘要,与已提交的 site-baseline.json 比对
151
+ const memFiles = [];
152
+ for (const { p } of rendered) memFiles.push(p.id + '.html');
153
+ const assetSrc = resolve(root, dirRel, 'assets');
154
+ if (existsSync(assetSrc)) {
155
+ for (const f of await readdir(assetSrc)) {
156
+ if (['.html', '.css', '.js', '.svg'].includes(extname(f))) memFiles.push('assets/' + f);
157
+ }
158
+ }
159
+ memFiles.push('.nojekyll');
160
+ const memHash = await treeDigest(targetAbs, memFiles);
161
+ const baselineRel = join(targetRel, 'site-baseline.json');
162
+ if (!existsSync(resolve(root, baselineRel))) {
163
+ throw new RenderError(
164
+ `[render-public-site --check] ${repo.name}: 未找到已提交基线 site-baseline.json(请先渲染并提交)`,
165
+ 1,
166
+ );
167
+ }
168
+ const base = JSON.parse(await readFileContained(root, baselineRel, { encoding: 'utf8' }));
169
+ assertValid(base, siteBaselineSchema, `${repo.name} site-baseline.json`);
170
+ if (base.sha256 !== memHash) {
171
+ throw new RenderError(
172
+ `[render-public-site --check] ${repo.name}: 漂移:内存产物树摘要与基线不一致`,
173
+ 1,
174
+ );
175
+ }
176
+ console.log(`[render-public-site --check] ${repo.name}: 一致,无漂移`);
177
+ return;
178
+ }
179
+
180
+ // 写盘:清空 target 后重建(docs/ 即站点目录)。
181
+ // harness 不提供删除原语,先经 resolveContained 证明目标收容在工作区内,再整目录重建;
182
+ // 之后所有文件写入均走 writeFileAtomic(收容 + 原子写)。
183
+ await resolveContained(root, targetRel);
184
+ await rm(targetAbs, { recursive: true, force: true });
185
+ for (const { p, html } of rendered) {
186
+ await writeFileAtomic(
187
+ root,
188
+ join(targetRel, p.id + '.html'),
189
+ '<!-- generated by skill-family-doc-render -->\n' + html,
190
+ );
191
+ }
192
+ // 拷贝 assets(allowlist:html/css/js/svg,不含 png;配图全部自绘 SVG)
193
+ const assetSrc = resolve(root, dirRel, 'assets');
194
+ if (existsSync(assetSrc)) {
195
+ for (const f of await readdir(assetSrc)) {
196
+ if (['.html', '.css', '.js', '.svg'].includes(extname(f))) {
197
+ const bytes = await readFileContained(root, join(dirRel, 'assets', f));
198
+ await writeFileAtomic(root, join(targetRel, 'assets', f), bytes);
199
+ }
200
+ }
201
+ }
202
+ // .nojekyll:禁止 GitHub Pages 跑 Jekyll
203
+ await writeFileAtomic(root, join(targetRel, '.nojekyll'), '');
204
+ // 树基线(防漂移)
205
+ const files = await listTargetFiles(targetAbs);
206
+ const treeHash = await treeDigest(targetAbs, files);
207
+ await writeFileAtomic(
208
+ root,
209
+ join(targetRel, 'site-baseline.json'),
210
+ JSON.stringify({ sha256: treeHash, files }, null, 2),
211
+ );
212
+
213
+ console.log(`[render-public-site] ${repo.name}: 已渲染 ${rendered.length} 页 + assets 到 ${targetRel}`);
214
+ console.log(`[render-public-site] ${repo.name}: tree-sha256=${treeHash.slice(0, 16)}…`);
215
+
216
+ // 可选:对真实导出快照逐页断言
217
+ if (assertGit) {
218
+ const expected = ordered.map((p) => `${targetRel}/${p.id}.html`);
219
+ expected.push(`${targetRel}/assets/style.css`);
220
+ expected.push(`${targetRel}/.nojekyll`);
221
+ expected.push(`${targetRel}/index.html`);
222
+ let missing = 0;
223
+ for (const f of expected) {
224
+ try {
225
+ execSync(`git ls-files --error-unmatch ${f}`, { cwd: root, stdio: 'pipe' });
226
+ } catch {
227
+ console.error(`[assert-git] ${repo.name}: 未跟踪(需 git add 并提交): ${f}`);
228
+ missing++;
229
+ }
230
+ }
231
+ if (missing) {
232
+ throw new RenderError(
233
+ `[assert-git] ${repo.name}: ${missing} 个文件未进 Git 快照,站点无法进入发布`,
234
+ 1,
235
+ );
236
+ }
237
+ console.log(`[assert-git] ${repo.name}: 全部站点文件已在 Git 快照中`);
238
+ }
239
+ }
240
+
241
+ // === 主流程 ===
242
+ // argv: CLI 参数(不含 node/script 名);cwd: 工作区根(public-release.json 所在目录)。
243
+ // 返回退出码 0;可预期失败抛 RenderError(携带 exitCode),其余异常原样抛出。
244
+ export async function main(argv = process.argv.slice(2), { cwd = process.cwd() } = {}) {
245
+ const check = argv.includes('--check');
246
+ const assertGit = argv.includes('--assert-git');
247
+ const repoIdx = argv.indexOf('--repo');
248
+ const repoArg = repoIdx >= 0 ? argv[repoIdx + 1] : null;
249
+
250
+ const root = resolve(cwd);
251
+
252
+ // --- 读取发布配置 ---
253
+ const releasePath = resolve(root, 'public-release.json');
254
+ if (!existsSync(releasePath)) {
255
+ throw new RenderError('[render-public-site] 未找到 public-release.json', 2);
256
+ }
257
+ const release = JSON.parse(await readFileContained(root, 'public-release.json', { encoding: 'utf8' }));
258
+ assertValid(release, publicReleaseSchema, 'public-release.json');
259
+
260
+ // 泄漏扫描追加字面量(来自配置;路径类用 forbiddenPublicPaths,任意私有词用 privateLiterals)
261
+ const leakLiterals = [
262
+ ...(release.forbiddenPublicPaths || []),
263
+ ...(release.privateLiterals || []),
264
+ ];
265
+
266
+ // 选 repo:所有带 site 者;--repo 指定则只取该 name
267
+ let selected = (release.repos || []).filter((r) => r.site);
268
+ if (repoArg) {
269
+ const hit = selected.find((r) => r.name === repoArg);
270
+ if (!hit) {
271
+ throw new RenderError(`[render-public-site] 未找到带 site 的 repo: ${repoArg}`, 2);
272
+ }
273
+ selected = [hit];
274
+ }
275
+ if (!selected.length) {
276
+ throw new RenderError('[render-public-site] public-release.json 中没有带 site 字段的 repo', 2);
277
+ }
278
+
279
+ for (const repo of selected) await renderRepo(root, repo, release, leakLiterals, { check, assertGit });
280
+ return 0;
281
+ }
282
+
283
+ // CLI 自执行(直接 node scripts/render-public-site.mjs 时;bin 入口亦走 main)
284
+ const invokedAsCli = process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url);
285
+ if (invokedAsCli) {
286
+ main()
287
+ .then((code) => {
288
+ process.exitCode = code;
289
+ })
290
+ .catch((err) => {
291
+ console.error(err.message);
292
+ process.exitCode = err instanceof RenderError ? err.exitCode : 1;
293
+ });
294
+ }