third-party-notices.mjs 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184
  1. import { createHash } from "node:crypto";
  2. import { mkdir, readFile, writeFile } from "node:fs/promises";
  3. import { dirname, resolve } from "node:path";
  4. export const repositoryRoot = resolve(import.meta.dirname, "..");
  5. export const noticesFileName = "THIRD-PARTY-NOTICES.md";
  6. const hash = (bytes) => createHash("sha256").update(bytes).digest("hex");
  7. export async function readThirdPartyNotices(root = repositoryRoot) {
  8. // 开发和构建只消费已有声明;输入新鲜度由显式 license 检查负责,避免修改 skill 就阻断构建。
  9. return readFile(resolve(root, noticesFileName));
  10. }
  11. export async function readVerifiedNotices(root = repositoryRoot, { requireComplete = false } = {}) {
  12. const manifest = JSON.parse(await readFile(resolve(root, "third-party/inventory.json"), "utf8"));
  13. if (manifest.schemaVersion !== 1) throw new Error("Unsupported third-party inventory");
  14. const bytes = await readThirdPartyNotices(root);
  15. if (hash(bytes) !== manifest.noticesSha256)
  16. throw new Error("Third-party notices changed; regenerate the inventory");
  17. for (const [file, expected] of Object.entries(manifest.inputs)) {
  18. // 工作区文本允许 Windows checkout 的 CRLF;原始许可和发行声明另用字节哈希校验。
  19. if (hash((await readFile(resolve(root, file), "utf8")).replaceAll("\r\n", "\n")) !== expected) {
  20. throw new Error(`Third-party input changed: ${file}. Run node scripts/licenses.mjs notices`);
  21. }
  22. }
  23. if (requireComplete && !Array.isArray(manifest.reviewRequired))
  24. throw new Error("Missing material review inventory; regenerate third-party notices");
  25. if (requireComplete && manifest.reviewRequired.length) {
  26. throw new Error(
  27. `Unresolved third-party material obligations:\n${manifest.reviewRequired.map((item) => `${item.id}: ${item.reason}`).join("\n")}`,
  28. );
  29. }
  30. return bytes;
  31. }
  32. export async function stageThirdPartyNotices(directory, root = repositoryRoot) {
  33. const bytes = await readThirdPartyNotices(root);
  34. await mkdir(directory, { recursive: true });
  35. await writeFile(resolve(directory, noticesFileName), bytes);
  36. }
  37. export async function readNodeNotices(version, root = repositoryRoot) {
  38. const normalized = version.replace(/^v/u, "");
  39. const sources = JSON.parse(
  40. await readFile(resolve(root, "third-party/runtime/sources.json"), "utf8"),
  41. );
  42. const source = sources.node.find((item) => item.version === normalized);
  43. if (!source) throw new Error(`Missing Node ${normalized} license provenance`);
  44. const bytes = await readFile(resolve(root, source.file));
  45. return { source, bytes };
  46. }
  47. export async function stageNodeNotices(directory, version, root = repositoryRoot) {
  48. const { source, bytes } = await readNodeNotices(version, root);
  49. await mkdir(directory, { recursive: true });
  50. // 修复:复用二进制缓存时也必须刷新声明;只复制 bin/node 会丢掉内嵌库条款。
  51. await writeFile(resolve(directory, "LICENSE.node.txt"), bytes);
  52. await writeFile(resolve(directory, "NODE-SOURCES.json"), `${JSON.stringify(source, null, 2)}\n`);
  53. return resolve(directory, "LICENSE.node.txt");
  54. }
  55. export async function stageElectronNotices(extractedRoot, resources, version) {
  56. const directory = resolve(resources, "licenses/electron");
  57. const records = [];
  58. for (const name of ["LICENSE", "LICENSES.chromium.html"]) {
  59. let bytes;
  60. try {
  61. bytes = await readFile(resolve(extractedRoot, name));
  62. } catch (error) {
  63. if (name !== "LICENSE" || error.code !== "ENOENT") throw error;
  64. bytes = await readFile(resolve(extractedRoot, "LICENSE.electron.txt"));
  65. }
  66. await mkdir(directory, { recursive: true });
  67. await writeFile(resolve(directory, name), bytes);
  68. records.push({ file: name, sha256: hash(bytes) });
  69. }
  70. // 修复:取实际目标平台的解包材料,避免交叉编译误用宿主 Electron 的许可证集合。
  71. await writeFile(
  72. resolve(directory, "SOURCES.json"),
  73. `${JSON.stringify({ version, origin: "electron-builder target distribution", records }, null, 2)}\n`,
  74. );
  75. }
  76. export async function readNativeSearchNotices(root = repositoryRoot, { verify = false } = {}) {
  77. const inventoryPath = resolve(root, "third-party/native-search/sources.json");
  78. const inventory = JSON.parse(await readFile(inventoryPath, "utf8"));
  79. // 原生材料生成时显式核验;准备缓存、构建和打包不把过期登记当作门禁。
  80. if (verify) {
  81. for (const [file, expected] of Object.entries(inventory.inputs)) {
  82. if (hash(await readFile(resolve(root, file))) !== expected)
  83. throw new Error(`Native license versions changed: ${file}`);
  84. }
  85. }
  86. const records = new Map();
  87. for (const component of inventory.components) {
  88. for (const notice of component.notices) {
  89. const bytes = await readFile(resolve(root, notice.file));
  90. const sha256 = hash(bytes);
  91. if (verify && sha256 !== notice.sha256)
  92. throw new Error(`Changed native notice: ${notice.file}`);
  93. const record = records.get(sha256) ?? { bytes, components: new Set() };
  94. record.components.add(`${component.id} ${component.version ?? ""}`.trim());
  95. records.set(sha256, record);
  96. }
  97. }
  98. const parts = [
  99. "NATIVE SEARCH THIRD-PARTY NOTICES\n",
  100. inventory.scope,
  101. "Ripgrep is available under MIT or Unlicense. Zstd uses its BSD alternative. GCC runtime portions use GPL-3.0 with the GCC Runtime Library Exception 3.1. These component licenses do not relicense the application.",
  102. "Exact archive checksums, source URLs and notice hashes are recorded in SOURCES.json beside this file.",
  103. ];
  104. for (const record of records.values()) {
  105. parts.push(
  106. `\n===== ${[...record.components].join("; ")} =====\n`,
  107. record.bytes.toString("utf8"),
  108. );
  109. }
  110. return { inventory, bytes: Buffer.from(`${parts.join("\n\n")}\n`) };
  111. }
  112. export async function stageNativeSearchNotices(
  113. plan,
  114. root = repositoryRoot,
  115. { builtFromSource = false, origin } = {},
  116. ) {
  117. // 内网镜像与仓库归档是同一 SHA-256 的输入字节,来源标签由调用方如实记录;默认仍为仓库归档。
  118. const binaryOrigin = origin ?? (builtFromSource ? "source-build" : "repository-archive");
  119. const { inventory, bytes } = await readNativeSearchNotices(root);
  120. for (const artifact of plan.artifacts) {
  121. const directory = dirname(artifact.binaryPath);
  122. // 缓存命中也重写通知,避免旧二进制缓存继续缺失版权材料。
  123. await writeFile(resolve(directory, "THIRD-PARTY-NOTICES.txt"), bytes);
  124. await writeFile(
  125. resolve(directory, "SOURCES.json"),
  126. JSON.stringify(
  127. {
  128. ...inventory,
  129. archiveChecksumScope:
  130. "The archives list records repository binary inputs. Repackaged outputs containing these notices have different archive checksums; the binary below identifies this distribution.",
  131. binary: {
  132. toolId: artifact.toolId,
  133. version: artifact.version,
  134. sha256: hash(await readFile(artifact.binaryPath)),
  135. origin: binaryOrigin,
  136. ...(!builtFromSource ? { sourceArchiveSha256: artifact.archiveSha256 } : {}),
  137. },
  138. },
  139. null,
  140. 2,
  141. ) + "\n",
  142. );
  143. }
  144. }
  145. export function thirdPartyNoticesVitePlugin(root = repositoryRoot) {
  146. let base = "/";
  147. return {
  148. name: "zcode-third-party-notices",
  149. apply: "build",
  150. configResolved(config) {
  151. base = config.base;
  152. },
  153. async generateBundle() {
  154. this.emitFile({
  155. type: "asset",
  156. fileName: noticesFileName,
  157. source: await readThirdPartyNotices(root),
  158. });
  159. },
  160. transformIndexHtml: {
  161. order: "post",
  162. handler: () => [
  163. {
  164. tag: "link",
  165. attrs: {
  166. rel: "license",
  167. href: `${base}${noticesFileName}`,
  168. },
  169. injectTo: "head",
  170. },
  171. ],
  172. },
  173. };
  174. }