蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

离线实测商店发布契约、安装包 SHA-256/MD5 防篡改、本地 latest.yml 回环更新服务及 SemVer 分级

JAVASCRIPTWindows x64、Node.js v24.22.3 本地运行环境。explore-release.mjs
explore-release.mjs170 行
import crypto from 'node:crypto';
import fs from 'node:fs/promises';
import http from 'node:http';
import os from 'node:os';
import path from 'node:path';

function caseStoreReleasePipelinesAudit() {
  const stores = {
    microsoftStore: { tool: 'electron-windows-store', packageExt: '.msix', portal: 'Store Partner Center' },
    macAppStore: { packageExts: ['.pkg', '.app'], notarizationRequired: true, uploader: 'Xcode/Transporter' },
    snapStore: { config: 'snapcraft.yaml', packageExt: '.snap', uploader: 'Snapcraft Store' },
  };
  const reviewChecklist = ['icons_and_screenshots', 'description_and_privacy_policy', 'stability_testing', 'allowed_apis_only'];
  const actual = {
    storeCount: Object.keys(stores).length,
    msixExt: stores.microsoftStore.packageExt,
    macNotarize: stores.macAppStore.notarizationRequired,
    snapConfig: stores.snapStore.config,
    checklistCount: reviewChecklist.length,
  };
  const expected = {
    storeCount: 3,
    msixExt: '.msix',
    macNotarize: true,
    snapConfig: 'snapcraft.yaml',
    checklistCount: 4,
  };
  return { name: 'store_release_pipelines_audit', passed: JSON.stringify(actual) === JSON.stringify(expected), expected, actual };
}

async function caseDirectDistributionChecksumVerify() {
  const tmpDir = await fs.mkdtemp(path.join(os.tmpdir(), 'electron-release-'));
  try {
    const payload = Buffer.from('Electron-Installer-Binary-v1.0.2-Payload', 'utf8');
    const installerPath = path.join(tmpDir, 'MyElectronApp-1.0.2.exe');
    await fs.writeFile(installerPath, payload);

    const diskBytes = await fs.readFile(installerPath);
    const sha256 = crypto.createHash('sha256').update(diskBytes).digest('hex');
    const md5 = crypto.createHash('md5').update(diskBytes).digest('hex');

    const tampered = Buffer.from('Electron-Installer-Binary-v1.0.2-Tampered', 'utf8');
    const tamperedSha256 = crypto.createHash('sha256').update(tampered).digest('hex');

    const actual = {
      sha256Length: sha256.length,
      md5Length: md5.length,
      intactVerified: sha256 === crypto.createHash('sha256').update(payload).digest('hex'),
      tamperedRejected: tamperedSha256 !== sha256,
      supportedDirectExts: ['.exe', '.dmg', '.AppImage'],
    };
    const expected = {
      sha256Length: 64,
      md5Length: 32,
      intactVerified: true,
      tamperedRejected: true,
      supportedDirectExts: ['.exe', '.dmg', '.AppImage'],
    };
    return { name: 'direct_distribution_checksum_verify', passed: JSON.stringify(actual) === JSON.stringify(expected), expected, actual };
  } finally {
    await fs.rm(tmpDir, { recursive: true, force: true });
  }
}

async function caseSelfHostedUpdateServerLoopback() {
  const binary = Buffer.from('MyElectronApp-1.0.2-release-bytes', 'utf8');
  const sha512 = crypto.createHash('sha512').update(binary).digest('base64');
  const latestYml = [
    'version: 1.0.2',
    'files:',
    '  - url: MyElectronApp-1.0.2.exe',
    `    sha512: "${sha512}"`,
    'releaseDate: "2025-10-15T00:00:00Z"',
  ].join('\n');

  const server = http.createServer((req, res) => {
    if (req.url === '/latest.yml') {
      res.writeHead(200, { 'Content-Type': 'text/yaml; charset=utf-8' });
      res.end(latestYml);
      return;
    }
    if (req.url === '/MyElectronApp-1.0.2.exe') {
      res.writeHead(200, { 'Content-Type': 'application/octet-stream' });
      res.end(binary);
      return;
    }
    res.writeHead(404);
    res.end();
  });

  await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
  const { port } = server.address();
  try {
    const ymlText = await (await fetch(`http://127.0.0.1:${port}/latest.yml`)).text();
    const version = ymlText.match(/^version:\s*(.+)$/m)?.[1].trim();
    const fileUrl = ymlText.match(/url:\s*(.+)$/m)?.[1].trim();
    const declaredSha512 = ymlText.match(/sha512:\s*"([^"]+)"/m)?.[1];

    const binBuf = Buffer.from(await (await fetch(`http://127.0.0.1:${port}/${fileUrl}`)).arrayBuffer());
    const computedSha512 = crypto.createHash('sha512').update(binBuf).digest('base64');

    const actual = {
      version,
      fileUrl,
      sha512Matched: computedSha512 === declaredSha512,
      downloadedBytes: binBuf.length,
    };
    const expected = {
      version: '1.0.2',
      fileUrl: 'MyElectronApp-1.0.2.exe',
      sha512Matched: true,
      downloadedBytes: binary.length,
    };
    return { name: 'self_hosted_update_server_loopback', passed: JSON.stringify(actual) === JSON.stringify(expected), expected, actual };
  } finally {
    await new Promise((resolve) => server.close(resolve));
  }
}

function compareSemver(a, b) {
  const pa = a.split('.').map(Number);
  const pb = b.split('.').map(Number);
  for (let i = 0; i < 3; i++) {
    if (pa[i] !== pb[i]) return pa[i] > pb[i] ? 1 : -1;
  }
  return 0;
}

function classifyRelease(prev, next) {
  const [maj1, min1, pat1] = prev.split('.').map(Number);
  const [maj2, min2, pat2] = next.split('.').map(Number);
  if (maj2 > maj1) return 'major';
  if (min2 > min1) return 'minor';
  if (pat2 > pat1) return 'patch';
  return 'none';
}

function caseSemverAndRolloutStrategy() {
  const versions = ['1.0.1', '1.0.2', '1.1.0', '2.0.0'];
  const sorted = [...versions].reverse().sort(compareSemver);
  const triggers = ['startup_check', 'periodic_poll', 'manual_trigger'];

  const actual = {
    sorted,
    upgradeAvailable: compareSemver('1.0.2', '1.0.1') > 0,
    patchKind: classifyRelease('1.0.1', '1.0.2'),
    minorKind: classifyRelease('1.0.2', '1.1.0'),
    majorKind: classifyRelease('1.1.0', '2.0.0'),
    triggersCount: triggers.length,
  };
  const expected = {
    sorted: ['1.0.1', '1.0.2', '1.1.0', '2.0.0'],
    upgradeAvailable: true,
    patchKind: 'patch',
    minorKind: 'minor',
    majorKind: 'major',
    triggersCount: 3,
  };
  return { name: 'semver_and_rollout_strategy', passed: JSON.stringify(actual) === JSON.stringify(expected), expected, actual };
}

const cases = [
  caseStoreReleasePipelinesAudit(),
  await caseDirectDistributionChecksumVerify(),
  await caseSelfHostedUpdateServerLoopback(),
  caseSemverAndRolloutStrategy(),
];

console.log(JSON.stringify({ version: process.version, cases }));
本例需在 Windows x64、Node.js v24.22.3 本地运行环境。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows x64、Node.js v24.22.3 本地运行环境。

入口文件:projects/electron-release-lab/explore-release.mjs

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-release.mjs,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、Node.js v24.22.3 本地运行环境。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:Electron

课程关联工程包(登记关联21章) · 含当前章节或实例 · mbskycom202612a1081.zip

下载课程关联工程包:Electron

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1094.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习