generate-third-party-notices.mjs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210
  1. import { readFile, readdir, stat, writeFile } from "node:fs/promises";
  2. import { join, relative } from "node:path";
  3. import { collectNpmNotices, hashBytes } from "./third-party-npm.mjs";
  4. import {
  5. noticesFileName,
  6. readNativeSearchNotices,
  7. repositoryRoot,
  8. } from "./third-party-notices.mjs";
  9. export async function generateThirdPartyNotices(root = repositoryRoot) {
  10. const inputs = {};
  11. const readInput = async (file) => {
  12. const bytes = await readFile(join(root, file));
  13. inputs[file] = hashBytes(bytes.toString("utf8").replaceAll("\r\n", "\n"));
  14. return bytes;
  15. };
  16. const readJson = async (file) => JSON.parse(await readInput(file));
  17. const overrides = await readJson("third-party/npm-overrides.json");
  18. const copied = await readJson("third-party/copied-components.json");
  19. const embedded = await readJson("third-party/embedded-components.json");
  20. const runtimes = await readJson("third-party/runtime/sources.json");
  21. for (const runtime of runtimes.node) {
  22. if (hashBytes(await readInput(runtime.file)) !== runtime.sha256)
  23. throw new Error(`Changed Node ${runtime.version} license`);
  24. }
  25. const pkg = await readJson("package.json");
  26. await readInput("pnpm-lock.yaml");
  27. await readInput("pnpm-workspace.yaml");
  28. await readInput("third-party/native-search/sources.json");
  29. const { packages, notInstalled, workspaceManifests } = await collectNpmNotices(root, overrides);
  30. // 修复:递归扫描会把 bundled-agents/mock-cdn 的可删除缓存当作源码输入,重建立即失效。
  31. // workspace 边界由 pnpm 解析,同一份项目集合用于依赖图和 manifest 新鲜度检查。
  32. for (const file of workspaceManifests) await readInput(file);
  33. const currentPackages = new Set(
  34. [...packages, ...notInstalled].map((item) => `${item.name}@${item.version}`),
  35. );
  36. for (const item of overrides) {
  37. if (!currentPackages.has(item.package))
  38. throw new Error(`Stale npm notice override: ${item.package}`);
  39. }
  40. const textRecords = new Map();
  41. function addText(bytes, owner, origin) {
  42. const sha256 = hashBytes(bytes);
  43. const record = textRecords.get(sha256) ?? { bytes, references: [] };
  44. record.references.push({ owner, origin });
  45. textRecords.set(sha256, record);
  46. return sha256;
  47. }
  48. for (const record of overrides) if (record.file) await readInput(record.file);
  49. const packageInventory = packages.map(({ notices, ...item }) => ({
  50. ...item,
  51. notices: notices.map(({ member, bytes }) => ({
  52. member,
  53. sha256: addText(bytes, `${item.name}@${item.version}`, member),
  54. })),
  55. }));
  56. async function copiedFiles(file, files) {
  57. if ((await stat(join(root, file))).isDirectory()) {
  58. for (const child of (await readdir(join(root, file))).sort())
  59. await copiedFiles(`${file}/${child}`, files);
  60. } else {
  61. const bytes = await readInput(file);
  62. files.push({ file, sha256: hashBytes(bytes) });
  63. }
  64. }
  65. const copiedInventory = [];
  66. for (const record of copied) {
  67. if (record.file) {
  68. const bytes = await readInput(record.file);
  69. if (hashBytes(bytes) !== record.sha256)
  70. throw new Error(`Changed copied-source license: ${record.id}`);
  71. addText(bytes, record.id, record.source);
  72. } else if (!record.reviewRequired) {
  73. throw new Error(`Missing copied-source license or review: ${record.id}`);
  74. }
  75. const files = [];
  76. for (const file of record.roots) await copiedFiles(file, files);
  77. for (const file of record.modifiedFiles ?? []) {
  78. // 修复:集中 NOTICE 不能替代 Apache 4(b) 的文件内修改声明,重新生成时也不能抹掉这一义务。
  79. if (!files.some((entry) => entry.file === file))
  80. throw new Error(`Modified source outside copied roots: ${file}`);
  81. if (!(await readFile(join(root, file), "utf8")).includes("Modified by ZCode:"))
  82. throw new Error(`Missing file-local modification notice: ${file}`);
  83. }
  84. copiedInventory.push({ ...record, files });
  85. }
  86. for (const component of embedded) {
  87. if (!packages.some((item) => `${item.name}@${item.version}` === component.parentPackage))
  88. throw new Error(`Stale embedded component: ${component.parentPackage}`);
  89. for (const evidence of component.buildEvidence ?? []) {
  90. if (hashBytes(await readInput(evidence.file)) !== evidence.sha256)
  91. throw new Error(`Changed embedded build provenance: ${component.id}`);
  92. }
  93. for (const notice of component.notices) {
  94. const bytes = await readInput(notice.file);
  95. if (hashBytes(bytes) !== notice.sha256)
  96. throw new Error(`Changed embedded notice: ${component.id}`);
  97. addText(
  98. bytes,
  99. `${notice.component ?? component.id} (inside ${component.parentPackage})`,
  100. notice.source,
  101. );
  102. }
  103. }
  104. // 上游 AI Elements 的 LICENSE 是短版授权头,还需随包提供 Apache 2.0 全文。
  105. addText(
  106. await readInput("scripts/license-texts/Apache-2.0.txt"),
  107. "Apache-2.0 licensed components",
  108. "Apache License, Version 2.0",
  109. );
  110. const patches = [];
  111. for (const [name, file] of Object.entries(pkg.pnpm?.patchedDependencies ?? {})) {
  112. patches.push({ package: name, file, sha256: hashBytes(await readInput(file)) });
  113. }
  114. const native = await readNativeSearchNotices(root, { verify: true });
  115. for (const file of Object.keys(native.inventory.inputs)) await readInput(file);
  116. for (const component of native.inventory.components) {
  117. for (const notice of component.notices) await readInput(notice.file);
  118. }
  119. const sections = [
  120. "# Third-party notices",
  121. "Generated by `node scripts/licenses.mjs notices` from the current workspace production dependency graph, copied source/assets and native search tools. This is a conservative union across distributions; not every listed component is included on every platform. Versions, source references and hashes are recorded in `third-party/inventory.json` and `third-party/native-search/sources.json` in the source repository.",
  122. "Original copyright, license and NOTICE text is retained below. Identical text is shared by the components listed above it. Package metadata license identifiers are descriptive; they do not replace the original terms. Copyright holders are never inferred from npm author fields.",
  123. "## npm packages",
  124. ...packageInventory.map(
  125. (item) =>
  126. `- ${item.name}@${item.version} — ${typeof item.license === "string" ? item.license : JSON.stringify(item.license)}${item.acceptedMissingNotice ? `; ${item.acceptedMissingNotice}` : ""}`,
  127. ),
  128. "## Source evidence limitations",
  129. "Some publishers provide only a license identifier or a short README license section instead of a complete LICENSE file. For the following packages the supplied material explicitly identifies publisher metadata and standard terms; it is not represented as an original upstream LICENSE file. Any available README copyright notice is retained:",
  130. ...overrides
  131. .filter((item) => item.evidenceKind)
  132. .map((item) => `- ${item.package}: ${item.source}`),
  133. "The original import revisions of copied components are not recorded in the current checkout. Pinned license references below do not establish the original copy revision. They cover upstream-derived portions only; local adaptations do not change the upstream terms.",
  134. "## Copied source and assets",
  135. ...copied.map(
  136. (item) =>
  137. `- ${item.id} (${item.license ?? "not established"}): ${item.roots.join(", ")}. License reference: ${item.source ?? "not established"}. Original import revision: ${item.importRevision ?? "not recorded"}.${item.reviewRequired ? ` Review required: ${item.reviewRequired}` : ""}`,
  138. ),
  139. "Fig autocomplete source carries the repository's MIT license; the generated registry records npm @withfig/autocomplete@2.692.3 metadata as ISC. The original source MIT notice is retained below.",
  140. "## Embedded native and WASM components",
  141. ...embedded.map(
  142. (item) =>
  143. `- ${item.id} inside ${item.parentPackage}; upstream revision ${item.revision}; source: ${item.source}. ${item.reviewRequired ?? ""}`,
  144. ),
  145. "Electron/Chromium target-specific notices are shipped separately under Resources/licenses/electron. Distributions containing an independent Node runtime also include its exact-version LICENSE.node.txt; SEA includes that text in --licenses output.",
  146. "## Modified npm packages",
  147. ...patches.map(
  148. (item) =>
  149. `- ${item.package}: modified by ZCode; the changes are recorded in ${item.file} in the source repository.`,
  150. ),
  151. "## License and NOTICE texts",
  152. ];
  153. for (const [sha256, record] of textRecords) {
  154. sections.push(
  155. `### Notice ${sha256}`,
  156. ...record.references.map(({ owner, origin }) => `- ${owner}: ${origin}`),
  157. "",
  158. "````text\n" + record.bytes.toString("utf8") + "\n````",
  159. );
  160. }
  161. sections.push("## Native search tools", "````text\n" + native.bytes.toString("utf8") + "\n````");
  162. const bytes = Buffer.from(`${sections.join("\n\n")}\n`);
  163. const inventory = {
  164. schemaVersion: 1,
  165. inputHashEncoding:
  166. "UTF-8 with CRLF normalized to LF; notice and source snapshot hashes remain byte-exact",
  167. scope:
  168. "Production dependency union across current workspace projects, copied source/assets and native tools; not a per-installer SBOM or a certification of all licensing obligations.",
  169. noticesSha256: hashBytes(bytes),
  170. inputs: Object.fromEntries(Object.entries(inputs).sort(([a], [b]) => a.localeCompare(b, "en"))),
  171. packages: packageInventory,
  172. notInstalled,
  173. copied: copiedInventory,
  174. patches,
  175. exceptions: overrides.filter((item) => item.acceptedMissingNotice || item.evidenceKind),
  176. embedded,
  177. runtimes,
  178. reviewRequired: [
  179. // 修复:复制源码的缺口此前只写在 README,重生成清单后严格门禁也无法阻断。
  180. ...copied
  181. .filter((item) => item.reviewRequired)
  182. .map((item) => ({ id: item.id, reason: item.reviewRequired })),
  183. ...overrides
  184. .filter((item) => item.acceptedMissingNotice || item.evidenceKind)
  185. .map((item) => ({
  186. id: item.package,
  187. reason:
  188. "Original version-specific publisher copyright/license material remains incomplete.",
  189. })),
  190. ...embedded
  191. .filter((item) => item.reviewRequired)
  192. .map((item) => ({ id: item.id, reason: item.reviewRequired })),
  193. ...native.inventory.components
  194. .filter((item) => !item.notices.length)
  195. .map((item) => ({
  196. id: `${item.id}@${item.version}`,
  197. reason: "No original notice snapshot for this recorded native component.",
  198. })),
  199. ],
  200. };
  201. await writeFile(join(root, noticesFileName), bytes);
  202. await writeFile(
  203. join(root, "third-party/inventory.json"),
  204. `${JSON.stringify(inventory, null, 2)}\n`,
  205. );
  206. console.log(
  207. `${relative(root, join(root, noticesFileName))}: ${packages.length} package versions, ${copied.length} copied components, ${native.inventory.archives.length} native archives, ${bytes.length} bytes`,
  208. );
  209. }