🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat(desktop): gate Canary first launch and enforce security updates (#20168)
Innei6f8af58d01f4
diff --git a/.agents/skills/desktop-security-update/SKILL.md b/.agents/skills/desktop-security-update/SKILL.mdnew file mode 100644index 00000000000..e0bdc04e75d--- /dev/null+++ b/.agents/skills/desktop-security-update/SKILL.md@@ -0,0 +1,63 @@+---+name: desktop-security-update+description: 'Inspect, mark, or revoke vulnerable LobeHub Desktop versions through the existing release workflow and signed R2 security policy. Use for forced security updates across Stable, Canary, Beta, and Nightly.'+---++# Desktop security updates++Operate `.github/workflows/release-desktop-core-ota.yml` using its `security_policy` input. This selects only the policy job; it does not build or publish Core. The policy is global across channels at `<UPDATE_SERVER_URL base>/security-policy.json` in the existing update bucket.++Read [the policy contract](../../../apps/desktop/docs/security-updates.md) for client behavior and delivery limitations. The deterministic operator is `apps/desktop/scripts/desktopSecurityPolicy.mjs`; it shares schema/signature validation with the client. Do not hand-sign JSON, fetch signing secrets locally, replace the whole rule set, or add a workflow.++## Resolve the request++For a mark, determine the installer build channel, platforms, `shell` or `core` target, affected npm SemVer range, fixed full-installer version, and reason. An exact version is a valid range. Do not guess the affected scope from the latest release. If scope is ambiguous, inspect the current policy while asking only for the missing scope. Publish the fixed installer first: the operator checks the public feed and installer availability for every requested platform, including both macOS architectures. Beta uses the Canary installer feed.++A concrete user instruction to mark or revoke a specified scope authorizes that operation. If the user only asks to investigate or prepare, stop after inspection/preview. Do not invent a security restriction while implementing or testing this tooling. Never automatically weaken a range or minimum to make a failed preflight pass.++## Inspect, preview, apply++1. Resolve the actual repository with `gh repo view --json nameWithOwner`. Use the trusted `canary` branch after this workflow change is merged. Check that the remote workflow at the selected ref contains `security_policy` before dispatching; an older workflow could otherwise run an ordinary Core release. Do not dispatch unreviewed code with production signing secrets.+2. Dispatch `{"action":"inspect"}`. Read the downloaded report, including storage revision, rule IDs, `publicRevision`, and `publicError`. Initial absence is revision 0. If an existing policy differs from the public endpoint, resolve that discrepancy before a mutation.+3. Prepare one mark or revoke request with the inspected `expectedRevision`, a concise reason, and `apply:false`. Dispatch it and show the concrete before/after rules and installer checks. A preview performs no writes and uses no private key.+4. If the requested concrete mutation is authorized, dispatch the same request with `apply:true`. If it is not authorized, ask for approval of this prepared change. An earlier explicit mark/revoke instruction is sufficient; do not ask again.+5. Read the report and the exact workflow run. Success requires `status: verified`, with the public URL serving the exact signed policy just written. Report the new revision, affected scope (or revoked rule), and run URL. `no-change` means no publication occurred.++Mark example (replace the illustrative values with the user's scope):++```json+{+ "action": "mark",+ "apply": false,+ "expectedRevision": 7,+ "reason": "Security fix in the full installer",+ "rule": {+ "channel": "stable",+ "platforms": ["darwin", "win32", "linux"],+ "target": "shell",+ "affectedVersions": ">=2.2.0 <2.2.20",+ "minimumInstallerVersion": "2.2.20"+ }+}+```++Revoke request: `{"action":"revoke","expectedRevision":8,"apply":false,"reason":"Restriction withdrawn","ruleId":"<64-character ID from inspect>"}`. Revocation publishes a newer signed revision; never delete the policy or restore an older revision. Marking the same scope updates its minimum; changing its scope creates another rule, so revoke the old rule separately when that is intended.++## Dispatch and collect evidence++Write JSON to a temporary file. Pass it with `gh workflow run --json` via stdin; never interpolate user text into shell commands. Use a fresh UUID as `security_policy_request_id` for **each** dispatch. The workflow title includes it, so unrelated concurrent runs cannot be mistaken for this operation.++```sh+POLICY_REQUEST_ID=$(uuidgen)+jq --arg id "$POLICY_REQUEST_ID" \+ '{channel:"canary",security_policy:tojson,security_policy_request_id:$id}' \+ /tmp/security-policy-request.json > /tmp/security-policy-dispatch.json+gh workflow run release-desktop-core-ota.yml --repo "$POLICY_REPO" --ref canary \+ --json < /tmp/security-policy-dispatch.json+```++Here `channel:canary` satisfies the existing workflow input; the policy request determines the actual affected channels. Locate the run by exact `displayTitle == "Desktop security policy (<UUID>)"`, `event == workflow_dispatch`, and `headBranch == canary` using `gh run list --workflow release-desktop-core-ota.yml --repo "$POLICY_REPO" --json databaseId,displayTitle,event,headBranch,headSha,url,status,conclusion`. Poll for at most two minutes to locate it; do not redispatch just because run discovery is delayed. Watch that run and download `desktop-security-policy-<run-id>` using `gh run download <run-id> --repo "$POLICY_REPO" --name ... --dir <unique-temp-directory>`. Inspect logs if no report was produced.++The publisher checks `expectedRevision`, preserves unrelated rules, signs in Actions, archives the signed revision, conditionally replaces the R2 object using its ETag, and verifies the ordinary public URL. R2 credentials and the OTA signing pair reuse existing workflow secrets.++On a revision/precondition conflict, stop that mutation and inspect again; do not blindly rerun a stale request. On `published-unverified`, the write already succeeded: inspect storage and public delivery, investigate caching, and do not bump revision just to retry. Ambiguous network failures after a write also require inspection. Keep reports/logs as evidence, but never treat a green job, archived object, or preview as proof that clients can fetch the new policy.diff --git a/.github/workflows/release-desktop-core-ota.yml b/.github/workflows/release-desktop-core-ota.ymlindex 98ce530f382..75a9e66499c 100644--- a/.github/workflows/release-desktop-core-ota.yml+++ b/.github/workflows/release-desktop-core-ota.yml@@ -1,4 +1,5 @@name: Release Desktop Core OTA+run-name: ${{ inputs.security_policy && format('Desktop security policy ({0})', inputs.security_policy_request_id || github.run_id) || 'Release Desktop Core OTA' }}# ============================================# core-only 发布(壳不变,只发 main/preload/renderer/cli)@@ -38,6 +39,14 @@ on:value: ${{ jobs.gate.outputs.version }}workflow_dispatch:inputs:+ security_policy:+ description: 'Optional security policy request JSON; skips Core release when set'+ required: false+ type: string+ security_policy_request_id:+ description: 'Unique operator request ID for locating the security policy run'+ required: false+ type: stringchannel:description: 'Update channel'required: true@@ -54,7 +63,7 @@ on:default: '1'concurrency:- group: desktop-core-ota-${{ inputs.channel }}+ group: ${{ inputs.security_policy && 'desktop-security-policy' || format('desktop-core-ota-{0}', inputs.channel) }}cancel-in-progress: falsepermissions: read-all@@ -63,8 +72,76 @@ env:NODE_VERSION: '24.11.1'jobs:+ security-policy:+ name: Inspect or publish desktop security policy+ if: github.event_name == 'workflow_dispatch' && inputs.security_policy != ''+ runs-on: ubuntu-latest+ timeout-minutes: 10+ steps:+ - uses: actions/checkout@v7+ - uses: actions/setup-node@v6+ with:+ node-version: ${{ env.NODE_VERSION }}+ - name: Prepare isolated publisher runtime+ run: |+ set -euo pipefail+ RUNTIME="$RUNNER_TEMP/security-policy-runtime"+ mkdir -p "$RUNTIME/scripts" "$RUNTIME/src/common"+ cp apps/desktop/scripts/desktopSecurityPolicy.mjs "$RUNTIME/scripts/"+ cp apps/desktop/src/common/{securityPolicy,signedJson}.ts "$RUNTIME/src/common/"+ cp apps/desktop/scripts/security-policy-runtime/package{,-lock}.json "$RUNTIME/"+ cd "$RUNTIME"+ npm ci --ignore-scripts --no-audit --no-fund+ - name: Validate security policy request without credentials+ id: policy-request+ env:+ SECURITY_POLICY_REQUEST: ${{ inputs.security_policy }}+ run: |+ set -euo pipefail+ node "$RUNNER_TEMP/security-policy-runtime/scripts/desktopSecurityPolicy.mjs" \+ --validate-request > "$RUNNER_TEMP/security-policy-request.json"+ jq -r '"apply=\(.apply // false)"' "$RUNNER_TEMP/security-policy-request.json" >> "$GITHUB_OUTPUT"+ - name: Inspect or preview security policy+ if: steps.policy-request.outputs.apply != 'true'+ env:+ UPDATE_SERVER_URL: ${{ secrets.UPDATE_SERVER_URL }}+ UPDATE_S3_ENDPOINT: ${{ secrets.UPDATE_S3_ENDPOINT }}+ UPDATE_S3_REGION: ${{ secrets.UPDATE_S3_REGION }}+ UPDATE_S3_BUCKET: ${{ secrets.UPDATE_S3_BUCKET }}+ UPDATE_AWS_ACCESS_KEY_ID: ${{ secrets.UPDATE_AWS_ACCESS_KEY_ID }}+ UPDATE_AWS_SECRET_ACCESS_KEY: ${{ secrets.UPDATE_AWS_SECRET_ACCESS_KEY }}+ RENDERER_OTA_PUBLIC_KEY: ${{ secrets.RENDERER_OTA_PUBLIC_KEY }}+ run: |+ node "$RUNNER_TEMP/security-policy-runtime/scripts/desktopSecurityPolicy.mjs" \+ --request "$RUNNER_TEMP/security-policy-request.json" \+ --output "$RUNNER_TEMP/security-policy-report.json"+ - name: Publish security policy+ if: steps.policy-request.outputs.apply == 'true'+ env:+ UPDATE_SERVER_URL: ${{ secrets.UPDATE_SERVER_URL }}+ UPDATE_S3_ENDPOINT: ${{ secrets.UPDATE_S3_ENDPOINT }}+ UPDATE_S3_REGION: ${{ secrets.UPDATE_S3_REGION }}+ UPDATE_S3_BUCKET: ${{ secrets.UPDATE_S3_BUCKET }}+ UPDATE_AWS_ACCESS_KEY_ID: ${{ secrets.UPDATE_AWS_ACCESS_KEY_ID }}+ UPDATE_AWS_SECRET_ACCESS_KEY: ${{ secrets.UPDATE_AWS_SECRET_ACCESS_KEY }}+ RENDERER_OTA_PUBLIC_KEY: ${{ secrets.RENDERER_OTA_PUBLIC_KEY }}+ RENDERER_OTA_PRIVATE_KEY: ${{ secrets.RENDERER_OTA_PRIVATE_KEY }}+ run: |+ node "$RUNNER_TEMP/security-policy-runtime/scripts/desktopSecurityPolicy.mjs" \+ --request "$RUNNER_TEMP/security-policy-request.json" \+ --output "$RUNNER_TEMP/security-policy-report.json"+ - name: Upload operation report+ if: always()+ uses: actions/upload-artifact@v7+ with:+ name: desktop-security-policy-${{ github.run_id }}+ path: ${{ runner.temp }}/security-policy-report.json+ if-no-files-found: warn+ retention-days: 90+gate:name: Shell ABI gate (${{ inputs.channel }})+ if: inputs.security_policy == ''runs-on: ubuntu-latestoutputs:app_version: ${{ steps.base.outputs.app_version }}diff --git a/.gitignore b/.gitignoreindex 69d8b35e1de..15786469594 100644--- a/.gitignore+++ b/.gitignore@@ -53,6 +53,7 @@ venv/node_modules/*.lockpackage-lock.json+!apps/desktop/scripts/security-policy-runtime/package-lock.jsonbun.lockb.pnpm-store/diff --git a/apps/desktop/docs/security-updates.md b/apps/desktop/docs/security-updates.mdnew file mode 100644index 00000000000..5538d2ad2c5--- /dev/null+++ b/apps/desktop/docs/security-updates.md@@ -0,0 +1,65 @@+# Desktop security update policy++Every packaged launch checks `<UPDATE_SERVER_URL base>/security-policy.json` in the background after the main window's first frame. Policy IO does not delay entry, including first installation. This is independent of the OTA channel eligibility, first-launch marker, rollout percentage, and automatic-update preference. Stable installers skip the initial OTA gate; Canary and Beta installers keep it.++The endpoint is independent of versioned Core feeds so one policy can cover existing installers. The client accepts a strict schema, a maximum 1 MiB response, and an Ed25519 signature verified with the packaged OTA public key. The request times out after five seconds.++```json+{+ "kind": "desktop-security-policy",+ "revision": 1,+ "rules": [+ {+ "channel": "stable",+ "platforms": ["darwin", "win32", "linux"],+ "target": "shell",+ "affectedVersions": ">=2.2.0 <2.2.20",+ "minimumInstallerVersion": "2.2.20"+ },+ {+ "channel": "canary",+ "platforms": ["darwin"],+ "target": "core",+ "affectedVersions": "2.2.20-canary.3",+ "minimumInstallerVersion": "2.2.20-canary.4"+ }+ ],+ "schemaVersion": 1,+ "signature": "<base64 Ed25519 signature>"+}+```++Sign the canonical JSON of all fields except `signature`, using the shared recursive sorted-key canonicalization in `src/common/signedJson.ts`. The schema lives in `src/common/securityPolicy.ts`; both the client and publisher consume these modules. `kind` separates the policy from an OTA manifest. Increment `revision` for every policy change, including revocation; an empty `rules` array with a newer revision clears restrictions. Publish the complete rule set each time. Lower or equal revisions cannot replace a verified local policy.++`channel` refers to the installer build channel, not a user-selected update preference. `target: shell` matches the installed full-package version. `target: core` matches the active Core version. `affectedVersions` uses npm SemVer ranges with prereleases included; an exact version is also valid. Rules are limited to the listed platforms. Overlapping rules all apply.++After a background check finds a matching restriction, the shell opens its required-update window, disables existing and newly created business windows, and offers Retry or Quit on failure. A retry that receives a newer policy revoking the restriction closes the update window and restores the prior enabled state of business windows. It fetches a full installer from its build channel (Beta uses the Canary installer feed), using Sparkle on macOS and electron-updater elsewhere. The available installer must meet every matched rule's minimum version and must not match any affected range for this channel/platform. Publish a usable fixed installer before publishing a restriction. A full installer is expected to ship a Core at that same version; the next startup evaluates the actual installed Shell and Core again.++Verified policies are persisted atomically in `security-update-policy.json` under userData. A failed request, invalid signature, missing endpoint, or older response retains the previous verified policy. If refresh fails offline, a cached matching restriction still triggers the required-update window after entry. Without any verified policy, unavailable policy service does not block ordinary startup. This is operational update enforcement, not protection against a user who deliberately modifies their local installation/cache.++## Publishing and operator skill++Use the repository [desktop-security-update skill](../../../.agents/skills/desktop-security-update/SKILL.md) to inspect, mark, preview, apply, and revoke restrictions. For example: “Mark Stable Windows shell versions >=2.2.0 <2.2.20 as vulnerable, requiring installer 2.2.20, because of the confirmed security fix.” Scope and release numbers must come from the actual incident.++The existing `release-desktop-core-ota.yml` workflow accepts an optional `security_policy` JSON input. When set, only the policy job runs; ordinary Core build/publish jobs are skipped. Existing manual Core releases and `workflow_call` callers retain their behavior. The isolated publisher installs from the committed manifest and lockfile in `scripts/security-policy-runtime/` using `npm ci --ignore-scripts`; dependency changes must update both files together. Policy operations serialize globally across channels. `security_policy_request_id` appears in the run title for unambiguous run discovery.++`apps/desktop/scripts/desktopSecurityPolicy.mjs` implements three request types:++- `inspect`: return authoritative storage revision and rule IDs, and compare public delivery.+- `mark`: upsert one rule, preserving unrelated rules. Requires `expectedRevision`, `reason`, and `rule`. A rule's ID hashes its channel, sorted platform set, target, and affected range; updating its repair minimum keeps the ID.+- `revoke`: remove one inspected `ruleId`, preserving unrelated rules. Requires `expectedRevision` and `reason`.++Mutations default to `apply:false`. Preview checks the public repair feeds and installer availability without writing. `apply:true` additionally signs with `RENDERER_OTA_PRIVATE_KEY`, checks it against `RENDERER_OTA_PUBLIC_KEY`, archives the signed policy under `security-policy-history/<revision>-<hash>.json`, and conditionally writes `security-policy.json` using the prior ETag (or `If-None-Match: *` on first publication). The request must match the authoritative revision. Repeating an identical mark is a no-op.++The policy uses the existing `UPDATE_SERVER_URL`, `UPDATE_S3_ENDPOINT`, `UPDATE_S3_REGION`, `UPDATE_S3_BUCKET`, `UPDATE_AWS_ACCESS_KEY_ID`, and `UPDATE_AWS_SECRET_ACCESS_KEY` secrets. Actions validates and normalizes the request without credentials, then routes it to inspection/preview or publication. Only the publication step for a validated `apply:true` request receives the signing private key; inspection and preview processes never receive it. Each run uploads a JSON report containing before/after rules, reason, actor, installer checks, publication status, and run URL. Signed policy history remains in the bucket; operation reports are retained for 90 days.++Success requires fetching and verifying the exact signed object through the ordinary public policy URL. A stale cache or failed readback fails the run after the write and leaves `published-unverified` in its report. Inspect before retrying: do not blindly republish, delete the object, or restore an older revision. Configure the public endpoint to respect the object's `Cache-Control: no-store, max-age=0`; bypass any CDN rule that forcibly caches this path, including cached 404s from before first publication.++Installer preflight checks the candidate version against all rules for the same channel/platform, signed Sparkle enclosure metadata on both macOS architectures, hashed Windows/Linux installer entries, and public HEAD availability. It does not replace platform signing, installation, or product acceptance. The client rechecks its installed Shell/Core on its next startup.++## Current delivery boundary++- Requires a new full installer containing this startup gate; older clients cannot learn this behavior through a policy file alone.+- Checks start in the background after the first frame on each launch; a matching result immediately opens the required-update window. No periodic policy polling or push subscription is included, so a later publication is picked up on a subsequent launch or a Retry in the required-update window.+- Merge the publisher/workflow to the trusted release branch before invoking the production skill. Implementing or testing the tooling does not publish a real restriction.+- First-launch Core OTA continues to use the existing signed feed and offline-first behavior, independently of the background security check.diff --git a/apps/desktop/electron-builder.mjs b/apps/desktop/electron-builder.mjsindex dc68f5cd9a5..5f29131750b 100644--- a/apps/desktop/electron-builder.mjs+++ b/apps/desktop/electron-builder.mjs@@ -203,6 +203,23 @@ const config = {console.info('📦 Building CLI for embedding...');execSync('npm run build:cli', { stdio: 'inherit', cwd: __dirname });+ // The shell window has no React/i18next runtime. Bundle only its translated strings.+ const updateStrings = {};+ for (const locale of ['en-US', 'zh-CN']) {+ const messages = JSON.parse(+ await fs.readFile(path.join(__dirname, '../../locales', locale, 'electron.json'), 'utf8'),+ );+ updateStrings[locale] = Object.fromEntries(+ Object.entries(messages)+ .filter(([key]) => key.startsWith('startupUpdate.'))+ .map(([key, value]) => [key.slice('startupUpdate.'.length), value]),+ );+ }+ await fs.writeFile(+ path.join(__dirname, 'shell/update/strings.json'),+ JSON.stringify(updateStrings, null, 2) + '\n',+ );+execSync('node scripts/shellAbi.mjs --write', { stdio: 'inherit', cwd: __dirname });const { shellAbi } = JSON.parse(await fs.readFile(path.join(__dirname, 'shell/abi.json'), 'utf8'),diff --git a/apps/desktop/scripts/__tests__/desktopSecurityPolicy.test.mjs b/apps/desktop/scripts/__tests__/desktopSecurityPolicy.test.mjsnew file mode 100644index 00000000000..4411bc0f6b4--- /dev/null+++ b/apps/desktop/scripts/__tests__/desktopSecurityPolicy.test.mjs@@ -0,0 +1,409 @@+import { execFile } from 'node:child_process';+import { generateKeyPairSync, sign } from 'node:crypto';+import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';+import { createServer } from 'node:http';+import os from 'node:os';+import path from 'node:path';+import { fileURLToPath } from 'node:url';+import { promisify } from 'node:util';++import { describe, expect, it, vi } from 'vitest';++import { canonicalJson, verifyManifestSignature } from '../../src/common/signedJson.ts';+import { SecurityUpdatePolicy } from '../../src/main/core/infrastructure/SecurityUpdatePolicy';+import { ruleId, runSecurityPolicy, verifyRepairInstallers } from '../desktopSecurityPolicy.mjs';++const keys = generateKeyPairSync('ed25519');+const publicKey = keys.publicKey.export({ format: 'pem', type: 'spki' }).toString();+const privateKey = keys.privateKey.export({ format: 'pem', type: 'pkcs8' }).toString();+const rule = {+ channel: 'stable',+ platforms: ['win32'],+ target: 'shell',+ affectedVersions: '<1.2.0',+ minimumInstallerVersion: '1.2.0',+};+const signed = (revision, rules) => {+ const payload = { kind: 'desktop-security-policy', schemaVersion: 1, revision, rules };+ return {+ ...payload,+ signature: sign(null, Buffer.from(canonicalJson(payload)), privateKey).toString('base64'),+ };+};+const mark = (overrides = {}) => ({+ action: 'mark',+ apply: true,+ expectedRevision: 0,+ reason: 'Repair a vulnerable installer',+ rule,+ ...overrides,+});+const fixture = (policy = null) => {+ let current = policy;+ const store = {+ read: vi.fn(async () => ({ policy: current, etag: current ? `"${current.revision}"` : null })),+ archive: vi.fn(async () => {}),+ write: vi.fn(async (body, etag) => {+ if (etag !== (current ? `"${current.revision}"` : null))+ throw new Error('PreconditionFailed');+ current = JSON.parse(body);+ }),+ };+ const fetchImpl = vi.fn(async (url, options) => {+ if (url.endsWith('/security-policy.json'))+ return current ? Response.json(current) : new Response('', { status: 404 });+ if (options?.method === 'HEAD')+ return new Response(null, { headers: { 'content-length': '123' } });+ if (url.endsWith('.xml'))+ return new Response(+ `<rss><channel><item><sparkle:shortVersionString>1.2.0</sparkle:shortVersionString><enclosure url="installer.zip" sparkle:edSignature="signature"/></item></channel></rss>`,+ );+ return new Response(+ 'version: 1.2.0\nfiles:\n - url: installer.exe\n sha512: abc\n - url: installer.AppImage\n sha512: def\n',+ );+ });+ return {+ store,+ fetchImpl,+ feedBaseUrl: 'https://updates.test',+ publicKey,+ privateKey,+ wait: async () => {},+ };+};++describe('credential-free workflow request validation', () => {+ const validate = (request) =>+ promisify(execFile)(+ process.execPath,+ [+ fileURLToPath(new URL('../desktopSecurityPolicy.mjs', import.meta.url)),+ '--validate-request',+ ],+ { env: { SECURITY_POLICY_REQUEST: JSON.stringify(request) } },+ );++ it('normalizes inspect and default preview requests without any credentials', async () => {+ const inspection = JSON.parse((await validate({ action: 'inspect' })).stdout);+ expect(inspection).toEqual({ action: 'inspect' });+ const preview = JSON.parse((await validate(mark({ apply: undefined }))).stdout);+ expect(preview.apply).toBe(false);+ expect(preview.rule).toEqual(rule);+ });++ it('allows the signing branch only for an explicitly true, valid mutation', async () => {+ const publication = JSON.parse((await validate(mark())).stdout);+ expect(publication.apply).toBe(true);+ expect(publication.action).toBe('mark');+ await expect(validate(mark({ apply: 'true' }))).rejects.toMatchObject({ stdout: '' });+ await expect(validate({ action: 'inspect', apply: true })).rejects.toMatchObject({+ stdout: '',+ });+ await expect(validate(mark({ expectedRevision: undefined }))).rejects.toMatchObject({+ stdout: '',+ });+ });+});++describe('security policy publication', () => {+ it('previews a valid restriction without requiring a signing key or writing objects', async () => {+ const env = fixture();+ const result = await runSecurityPolicy({+ ...env,+ privateKey: undefined,+ request: mark({ apply: false }),+ });+ expect(result.status).toBe('preview');+ expect(result.after.revision).toBe(1);+ expect(result.installers).toHaveLength(1);+ expect(env.store.write).not.toHaveBeenCalled();+ expect(env.store.archive).not.toHaveBeenCalled();+ });++ it('publishes a client-verifiable rule while preserving unrelated channels', async () => {+ const unrelated = { ...rule, channel: 'canary' };+ const env = fixture(signed(4, [unrelated]));+ const result = await runSecurityPolicy({ ...env, request: mark({ expectedRevision: 4 }) });+ const { policy } = await env.store.read();+ expect(result.status).toBe('verified');+ expect(policy.revision).toBe(5);+ expect(policy.rules).toEqual([unrelated, rule]);+ expect(verifyManifestSignature(policy, publicKey)).toBe(true);+ const userData = await mkdtemp(path.join(os.tmpdir(), 'policy-client-'));+ try {+ const client = new SecurityUpdatePolicy({+ channel: 'stable',+ coreVersion: () => '1.0.0',+ shellVersion: '1.0.0',+ platform: 'win32',+ userData,+ publicKey,+ feedBaseUrl: env.feedBaseUrl,+ fetchImpl: env.fetchImpl,+ });+ expect(await client.check()).toBe(true);+ expect(client.isInstallerSafe('1.2.0')).toBe(true);+ await runSecurityPolicy({+ ...env,+ request: {+ action: 'revoke',+ apply: true,+ expectedRevision: 5,+ reason: 'Resolved',+ ruleId: ruleId(rule),+ },+ });+ expect(await client.check()).toBe(false);+ expect((await env.store.read()).policy.rules).toEqual([unrelated]);+ } finally {+ await rm(userData, { recursive: true, force: true });+ }+ });++ it('revokes the last rule with a newer signed empty policy and no installer fetch', async () => {+ const env = fixture(signed(1, [rule]));+ const result = await runSecurityPolicy({+ ...env,+ request: {+ action: 'revoke',+ apply: true,+ expectedRevision: 1,+ reason: 'Withdraw',+ ruleId: ruleId(rule),+ },+ });+ expect(result.after).toEqual({ revision: 2, rules: [] });+ expect((await env.store.read()).policy.rules).toEqual([]);+ expect(env.fetchImpl.mock.calls.every(([url]) => url.endsWith('/security-policy.json'))).toBe(+ true,+ );+ });++ it('does not bump revision or write for an identical mark', async () => {+ const env = fixture(signed(1, [rule]));+ expect(+ (await runSecurityPolicy({ ...env, request: mark({ expectedRevision: 1 }) })).status,+ ).toBe('no-change');+ expect(env.store.write).not.toHaveBeenCalled();+ });++ it('refuses stale revisions before feed requests or writes', async () => {+ const env = fixture(signed(2, [rule]));+ await expect(runSecurityPolicy({ ...env, request: mark() })).rejects.toThrow(+ 'expected revision 0, found 2',+ );+ expect(env.store.write).not.toHaveBeenCalled();+ expect(env.fetchImpl).not.toHaveBeenCalled();+ });++ it('does not overwrite a concurrent publication after planning', async () => {+ const env = fixture();+ env.store.archive.mockImplementationOnce(async () =>+ env.store.write(JSON.stringify(signed(1, [{ ...rule, channel: 'canary' }])), null),+ );+ await expect(runSecurityPolicy({ ...env, request: mark() })).rejects.toThrow(+ 'PreconditionFailed',+ );+ expect((await env.store.read()).policy.rules[0].channel).toBe('canary');+ });++ it('refuses an invalid stored signature and mismatched private key without writing', async () => {+ const invalid = fixture({ ...signed(1, [rule]), revision: 3 });+ await expect(runSecurityPolicy({ ...invalid, request: { action: 'inspect' } })).rejects.toThrow(+ 'signature invalid',+ );+ const env = fixture();+ const otherKey = generateKeyPairSync('ed25519')+ .privateKey.export({ format: 'pem', type: 'pkcs8' })+ .toString();+ await expect(+ runSecurityPolicy({ ...env, privateKey: otherKey, request: mark() }),+ ).rejects.toThrow('Signing key does not match');+ expect(env.store.archive).not.toHaveBeenCalled();+ expect(env.store.write).not.toHaveBeenCalled();+ });++ it('reports a successful write with stale public delivery as unverified, then exposes it on inspect', async () => {+ const env = fixture();+ const fetchImpl = async (url, options) =>+ url.endsWith('/security-policy.json')+ ? new Response('', { status: 404 })+ : env.fetchImpl(url, options);+ const record = vi.fn();+ await expect(runSecurityPolicy({ ...env, fetchImpl, record, request: mark() })).rejects.toThrow(+ 'Policy was written but public verification failed',+ );+ expect(record.mock.calls.at(-1)[0].status).toBe('published-unverified');+ expect(env.store.write).toHaveBeenCalledTimes(1);+ const result = await runSecurityPolicy({ ...env, fetchImpl, request: { action: 'inspect' } });+ expect(result.before.revision).toBe(1);+ expect(result.publicRevision).toBeNull();+ expect(result.publicError).toContain('404');+ });++ it('refuses to publish when the fixed installer is unavailable', async () => {+ const env = fixture();+ const fetchImpl = (url, options) =>+ options?.method === 'HEAD' ? new Response('', { status: 404 }) : env.fetchImpl(url, options);+ await expect(runSecurityPolicy({ ...env, fetchImpl, request: mark() })).rejects.toThrow(+ 'Installer unavailable',+ );+ expect(env.store.write).not.toHaveBeenCalled();+ });++ it('rejects an installer covered by another restriction', async () => {+ const env = fixture(+ signed(1, [{ ...rule, affectedVersions: '1.2.0', minimumInstallerVersion: '1.2.1' }]),+ );+ await expect(+ runSecurityPolicy({ ...env, request: mark({ expectedRevision: 1 }) }),+ ).rejects.toThrow('does not satisfy');+ expect(env.store.write).not.toHaveBeenCalled();+ });++ it('checks both macOS architectures and the Beta Canary feed', async () => {+ const env = fixture();+ const betaRule = { ...rule, channel: 'beta', platforms: ['darwin', 'linux', 'win32'] };+ const result = await verifyRepairInstallers({+ ...env,+ policy: { rules: [betaRule] },+ rule: betaRule,+ });+ expect(result.map((entry) => entry.feed)).toEqual([+ 'https://updates.test/canary/appcast-arm64.xml',+ 'https://updates.test/canary/appcast-x64.xml',+ 'https://updates.test/canary/canary-linux.yml',+ 'https://updates.test/canary/canary.yml',+ ]);+ const fetchImpl = (url, options) =>+ url.endsWith('appcast-x64.xml')+ ? new Response('', { status: 404 })+ : env.fetchImpl(url, options);+ await expect(+ runSecurityPolicy({ ...env, fetchImpl, request: mark({ rule: betaRule }) }),+ ).rejects.toThrow('404');+ expect(env.store.write).not.toHaveBeenCalled();+ });++ it('refuses cross-origin installer URLs', async () => {+ const env = fixture();+ const fetchImpl = async () =>+ new Response(+ 'version: 1.2.0\nfiles:\n - url: https://elsewhere.test/install.exe\n sha512: abc\n',+ );+ await expect(runSecurityPolicy({ ...env, fetchImpl, request: mark() })).rejects.toThrow(+ 'outside the channel feed',+ );+ expect(env.store.write).not.toHaveBeenCalled();+ });+});++it('executes the real Node CLI and S3 conditional writes against isolated HTTP storage', async () => {+ const objects = new Map();+ const requests = [];+ let failWrite = false;+ const server = createServer(async (req, res) => {+ const key = new URL(req.url, 'http://localhost').pathname;+ if (key === '/stable/stable.yml')+ return res.end('version: 1.2.0\nfiles:\n - url: installer.exe\n sha512: abc\n');+ if (key === '/stable/installer.exe') {+ res.setHeader('content-length', '123');+ return res.end();+ }+ const storedKey = key === '/security-policy.json' ? '/bucket/security-policy.json' : key;+ const existing = objects.get(storedKey);+ if (req.method === 'PUT') {+ requests.push({ key, match: req.headers['if-match'], none: req.headers['if-none-match'] });+ if (key === '/bucket/security-policy.json' && failWrite) {+ failWrite = false;+ res.writeHead(500, { 'Content-Type': 'application/xml' });+ return res.end('<Error><Code>InternalError</Code></Error>');+ }+ if (+ (req.headers['if-none-match'] === '*' && existing) ||+ (req.headers['if-match'] && req.headers['if-match'] !== existing?.etag)+ ) {+ res.writeHead(412, { 'Content-Type': 'application/xml' });+ return res.end('<Error><Code>PreconditionFailed</Code></Error>');+ }+ const chunks = [];+ for await (const chunk of req) chunks.push(chunk);+ const body = Buffer.concat(chunks).toString();+ const etag = `"revision-${JSON.parse(body).revision}"`;+ objects.set(storedKey, { body, etag });+ res.setHeader('ETag', etag);+ return res.end();+ }+ if (!existing) {+ res.writeHead(404, { 'Content-Type': 'application/xml' });+ return res.end('<Error><Code>NoSuchKey</Code></Error>');+ }+ res.setHeader('ETag', existing.etag);+ res.end(existing.body);+ });+ await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));+ const base = `http://127.0.0.1:${server.address().port}`;+ const dir = await mkdtemp(path.join(os.tmpdir(), 'policy-cli-'));+ const requestFile = path.join(dir, 'request.json');+ const reportFile = path.join(dir, 'report.json');+ const execute = async (request) => {+ await writeFile(requestFile, JSON.stringify(request));+ await promisify(execFile)(+ process.execPath,+ [+ fileURLToPath(new URL('../desktopSecurityPolicy.mjs', import.meta.url)),+ '--request',+ requestFile,+ '--output',+ reportFile,+ ],+ {+ env: {+ ...process.env,+ UPDATE_SERVER_URL: base,+ UPDATE_S3_ENDPOINT: base,+ UPDATE_S3_REGION: 'auto',+ UPDATE_S3_BUCKET: 'bucket',+ UPDATE_AWS_ACCESS_KEY_ID: 'test-access',+ UPDATE_AWS_SECRET_ACCESS_KEY: 'test-secret',+ RENDERER_OTA_PUBLIC_KEY: publicKey,+ RENDERER_OTA_PRIVATE_KEY: privateKey,+ },+ },+ );+ return JSON.parse(await readFile(reportFile, 'utf8'));+ };+ try {+ expect((await execute({ action: 'inspect' })).before.revision).toBe(0);+ expect((await execute(mark({ apply: false }))).status).toBe('preview');+ expect(objects.size).toBe(0);+ failWrite = true;+ await expect(execute(mark())).rejects.toThrow();+ expect((await execute({ action: 'inspect' })).before.revision).toBe(0);+ expect(objects.size).toBe(1); // History exists, but the live pointer was not written.+ expect((await execute(mark())).status).toBe('verified');+ const live = JSON.parse(objects.get('/bucket/security-policy.json').body);+ expect(verifyManifestSignature(live, publicKey)).toBe(true);+ expect(+ (+ await execute({+ action: 'revoke',+ apply: true,+ expectedRevision: 1,+ reason: 'Resolved',+ ruleId: ruleId(rule),+ })+ ).status,+ ).toBe('verified');+ expect(JSON.parse(objects.get('/bucket/security-policy.json').body).rules).toEqual([]);+ expect(requests.filter((entry) => entry.key === '/bucket/security-policy.json')).toEqual([+ { key: '/bucket/security-policy.json', match: undefined, none: '*' },+ { key: '/bucket/security-policy.json', match: undefined, none: '*' },+ { key: '/bucket/security-policy.json', match: '"revision-1"', none: undefined },+ ]);+ expect(objects.size).toBe(3);+ } finally {+ await new Promise((resolve) => server.close(resolve));+ await rm(dir, { recursive: true, force: true });+ }+}, 30_000);diff --git a/apps/desktop/scripts/__tests__/shellAbi.test.mjs b/apps/desktop/scripts/__tests__/shellAbi.test.mjsindex 41491af2c58..3c0aeb6baa8 100644--- a/apps/desktop/scripts/__tests__/shellAbi.test.mjs+++ b/apps/desktop/scripts/__tests__/shellAbi.test.mjs@@ -122,3 +122,16 @@ describe('computeShellAbi', () => {expect(abi('KEY\r\n')).toBe(abi('KEY'));});});++it('hashes startup-window translations before packaging without depending on the generated copy', () => {+ const file = 'locales/en-US/electron.json';+ write(file, JSON.stringify({ 'startupUpdate.title': 'Ready', 'other': 'One' }));+ write('apps/desktop/shell/update/strings.json', '{}');+ git('add', '-A');+ const initial = abi();+ write('apps/desktop/shell/update/strings.json', '{"en-US":{"title":"Ready"}}');+ write(file, JSON.stringify({ 'startupUpdate.title': 'Ready', 'other': 'Two' }));+ expect(abi()).toBe(initial);+ write(file, JSON.stringify({ 'startupUpdate.title': 'Updated', 'other': 'Two' }));+ expect(abi()).not.toBe(initial);+});diff --git a/apps/desktop/scripts/core-ota-test/coreV4.integration.mjs b/apps/desktop/scripts/core-ota-test/coreV4.integration.mjsindex 69c679882d3..41ccbd33c83 100644--- a/apps/desktop/scripts/core-ota-test/coreV4.integration.mjs+++ b/apps/desktop/scripts/core-ota-test/coreV4.integration.mjs@@ -87,6 +87,27 @@ const stage = async (builtin, remote, current = null) =>remote: remote.manifest,});describe('v4 pack OTA', () => {+ it('reports startup download progress before applying a v4 update', async () => {+ const builtin = await build('1', files);+ const remote = await build('5', { ...files, 'cli/new.js': Buffer.from('new') });+ const events = [];+ const result = await new CoreStore(path.join(root, 'ota'), fetchImpl).stage({+ builtin,+ current: null,+ onApplying: () => events.push({ phase: 'applying' }),+ onDownloadProgress: (progress) => events.push({ phase: 'downloading', ...progress }),+ packsBaseUrl: BASE,+ remote: remote.manifest,+ });+ expect(events.length).toBeGreaterThan(1);+ expect(events.at(-2)).toMatchObject({+ phase: 'downloading',+ received: result.downloaded.bytes,+ });+ expect(result.downloaded.bytes).toBeGreaterThan(0);+ expect(events.at(-1)).toEqual({ phase: 'applying' });+ expect(await readFile(path.join(result.dir, 'cli/new.js'), 'utf8')).toBe('new');+ });it('reuses builtin renderer content when the current version is an overlay', async () => {const v1 = await build('1', files);const v5 = await build('5', { ...files, 'cli/new.js': Buffer.from('new') });diff --git a/apps/desktop/scripts/desktopSecurityPolicy.mjs b/apps/desktop/scripts/desktopSecurityPolicy.mjsnew file mode 100644index 00000000000..2d06776bbdd--- /dev/null+++ b/apps/desktop/scripts/desktopSecurityPolicy.mjs@@ -0,0 +1,410 @@+import { createHash, createPublicKey, sign } from 'node:crypto';+import { mkdir, readFile, writeFile } from 'node:fs/promises';+import path from 'node:path';+import { fileURLToPath } from 'node:url';+import { parseArgs } from 'node:util';++import { GetObjectCommand, PutObjectCommand, S3Client } from '@aws-sdk/client-s3';+import { parseXml } from 'builder-util-runtime';+import { gte, satisfies, valid } from 'semver';+import { parse as parseYaml } from 'yaml';+import * as z from 'zod/v4';++import {+ securityUpdatePolicySchema,+ securityUpdateRuleSchema,+} from '../src/common/securityPolicy.ts';+import { canonicalJson, verifyManifestSignature } from '../src/common/signedJson.ts';++const KEY = 'security-policy.json';+const MAX_BYTES = 1024 * 1024;+const mutation = {+ apply: z.boolean().default(false),+ expectedRevision: z+ .number()+ .int()+ .nonnegative()+ .max(Number.MAX_SAFE_INTEGER - 1),+ reason: z.string().trim().min(1).max(500),+};+export const securityPolicyRequestSchema = z.discriminatedUnion('action', [+ z.strictObject({ action: z.literal('inspect') }),+ z.strictObject({ ...mutation, action: z.literal('mark'), rule: securityUpdateRuleSchema }),+ z.strictObject({+ ...mutation,+ action: z.literal('revoke'),+ ruleId: z.string().regex(/^[a-f0-9]{64}$/),+ }),+]);++const digest = (value) => createHash('sha256').update(canonicalJson(value)).digest('hex');+// Stable across a repair-minimum change, and independent of platform ordering.+export const ruleId = ({ affectedVersions, channel, platforms, target }) =>+ digest({ affectedVersions, channel, platforms: [...new Set(platforms)].sort(), target });+const describe = (policy) => ({+ revision: policy?.revision ?? 0,+ rules: (policy?.rules ?? []).map((rule) => ({ id: ruleId(rule), ...rule })),+});+const parsePolicy = (value, publicKey) => {+ const policy = securityUpdatePolicySchema.parse(value);+ if (!verifyManifestSignature(policy, publicKey))+ throw new Error('Security policy signature invalid');+ return policy;+};+const asUrl = (value) => {+ const url = new URL(value);+ if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password) {+ throw new Error('Expected an HTTP(S) URL without credentials');+ }+ return url;+};++async function readText(response) {+ if (!response.ok) throw new Error(`HTTP ${response.status} for ${response.url}`);+ if (Number(response.headers.get('content-length')) > MAX_BYTES)+ throw new Error('Response too large');+ let size = 0;+ const chunks = [];+ for await (const chunk of response.body) {+ size += chunk.length;+ if (size > MAX_BYTES) {+ throw new Error('Response too large');+ }+ chunks.push(chunk);+ }+ return Buffer.concat(chunks).toString('utf8');+}+const fetchText = async (url, fetchImpl) =>+ readText(+ await fetchImpl(url.toString(), { cache: 'no-store', signal: AbortSignal.timeout(15_000) }),+ );++export function planSecurityPolicy(current, rawRequest) {+ const request = securityPolicyRequestSchema.parse(rawRequest);+ if (request.action === 'inspect') return { changed: false, policy: current, request };+ const revision = current?.revision ?? 0;+ if (revision !== request.expectedRevision) {+ throw new Error(+ `Policy changed: expected revision ${request.expectedRevision}, found ${revision}. Inspect before retrying.`,+ );+ }+ let rules = [...(current?.rules ?? [])];+ if (request.action === 'mark') {+ const rule = { ...request.rule, platforms: [...new Set(request.rule.platforms)].sort() };+ const id = ruleId(rule);+ const index = rules.findIndex((entry) => ruleId(entry) === id);+ if (index === -1) rules.push(rule);+ else rules[index] = rule;+ } else {+ if (!rules.some((entry) => ruleId(entry) === request.ruleId))+ throw new Error('Rule not found; inspect before revoking');+ rules = rules.filter((entry) => ruleId(entry) !== request.ruleId);+ }+ const changed = canonicalJson(rules) !== canonicalJson(current?.rules ?? []);+ const policy = {+ kind: 'desktop-security-policy',+ revision: revision + (changed ? 1 : 0),+ rules,+ schemaVersion: 1,+ };+ // Enforce client limits before any storage write, including the rule-count limit.+ securityUpdatePolicySchema.parse({ ...policy, signature: 'pending' });+ return { changed, policy, request };+}++/** Verify the same public feed clients use, including both supported macOS architectures. */+export async function verifyRepairInstallers({ policy, rule, feedBaseUrl, fetchImpl = fetch }) {+ const feedChannel = rule.channel === 'beta' ? 'canary' : rule.channel;+ const feed = new URL(`${feedChannel}/`, `${feedBaseUrl}/`);+ const relevant = policy.rules.filter((entry) => entry.channel === rule.channel);+ const checked = [];+ for (const platform of rule.platforms) {+ const feeds =+ platform === 'darwin'+ ? ['appcast-arm64.xml', 'appcast-x64.xml']+ : [platform === 'linux' ? `${feedChannel}-linux.yml` : `${feedChannel}.yml`];+ for (const filename of feeds) {+ const feedUrl = new URL(filename, feed);+ const raw = await fetchText(feedUrl, fetchImpl);+ let version;+ let urls;+ if (platform === 'darwin') {+ const item = parseXml(raw).element('channel').getElements('item')[0];+ if (!item) throw new Error(`Empty appcast: ${feedUrl}`);+ const enclosure = item.element('enclosure');+ version =+ item.elementValueOrEmpty('sparkle:shortVersionString') ||+ enclosure.attributes?.['sparkle:shortVersionString'];+ if (!enclosure.attributes?.['sparkle:edSignature'])+ throw new Error(`Unsigned Sparkle enclosure: ${feedUrl}`);+ urls = [enclosure.attribute('url')];+ } else {+ const manifest = parseYaml(raw, { maxAliasCount: 0 });+ version = manifest?.version;+ const extension = platform === 'linux' ? '.appimage' : '.exe';+ const files = manifest?.files?.filter(+ (file) => typeof file.url === 'string' && file.url.toLowerCase().endsWith(extension),+ );+ if (!files?.length || files.some((file) => !file.sha512))+ throw new Error(`No hashed installer in ${feedUrl}`);+ urls = files.map((file) => file.url);+ }+ if (+ !valid(version) ||+ relevant.some(+ (entry) =>+ entry.platforms.includes(platform) &&+ (!gte(version, entry.minimumInstallerVersion) ||+ satisfies(version, entry.affectedVersions, { includePrerelease: true })),+ )+ ) {+ throw new Error(+ `Installer ${version ?? '<unknown>'} in ${feedUrl} does not satisfy the security policy`,+ );+ }+ for (const value of urls) {+ const installer = asUrl(new URL(value, feed));+ if (installer.origin !== feed.origin || !installer.pathname.startsWith(feed.pathname)) {+ throw new Error(`Installer is outside the channel feed: ${installer}`);+ }+ const response = await fetchImpl(installer.toString(), {+ method: 'HEAD',+ cache: 'no-store',+ signal: AbortSignal.timeout(15_000),+ });+ if (+ !response.ok ||+ Number(response.headers.get('content-length')) <= 0 ||+ !response.headers.has('content-length')+ ) {+ throw new Error(`Installer unavailable: ${installer} (HTTP ${response.status})`);+ }+ checked.push({+ feed: feedUrl.toString(),+ installer: installer.toString(),+ platform,+ version,+ });+ }+ }+ }+ return checked;+}++export function createPolicyStore({ client, bucket }) {+ return {+ read: async () => {+ try {+ const response = await client.send(new GetObjectCommand({ Bucket: bucket, Key: KEY }));+ if (response.ContentLength > MAX_BYTES) throw new Error('Stored policy too large');+ const body = await readText(new Response(response.Body.transformToWebStream()));+ if (!response.ETag)+ throw new Error('Policy ETag missing; conditional publication unavailable');+ return { etag: response.ETag, policy: JSON.parse(body) };+ } catch (error) {+ if (error.name === 'NoSuchKey') return { etag: null, policy: null };+ throw error;+ }+ },+ archive: async (key, body) => {+ try {+ await client.send(+ new PutObjectCommand({+ Bucket: bucket,+ Key: key,+ Body: body,+ ContentType: 'application/json',+ IfNoneMatch: '*',+ }),+ );+ } catch (error) {+ // Content-addressed history is write-once. A retry may already have archived these bytes.+ if (error.name !== 'PreconditionFailed') throw error;+ const existing = await client.send(new GetObjectCommand({ Bucket: bucket, Key: key }));+ if ((await readText(new Response(existing.Body.transformToWebStream()))) !== body) {+ throw new Error('Existing history object differs from the signed policy', {+ cause: error,+ });+ }+ }+ },+ write: async (body, etag) => {+ await client.send(+ new PutObjectCommand({+ Bucket: bucket,+ Key: KEY,+ Body: body,+ ContentType: 'application/json',+ CacheControl: 'no-store, max-age=0',+ ...(etag ? { IfMatch: etag } : { IfNoneMatch: '*' }),+ }),+ );+ },+ };+}++export async function runSecurityPolicy({+ request: input,+ store,+ feedBaseUrl,+ publicKey,+ privateKey,+ fetchImpl = fetch,+ record = async () => {},+ wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms)),+}) {+ const request = securityPolicyRequestSchema.parse(input);+ asUrl(feedBaseUrl);+ const stored = await store.read();+ const current = stored.policy ? parsePolicy(stored.policy, publicKey) : null;+ const plan = planSecurityPolicy(current, request);+ let result = {+ action: request.action,+ before: describe(current),+ after: describe(plan.policy),+ status: 'inspected',+ };+ if (request.action === 'inspect') {+ // A public-cache mismatch is visible even after a prior run wrote successfully but failed readback.+ let publicRevision = null;+ let publicError;+ try {+ const policy = parsePolicy(+ JSON.parse(await fetchText(`${feedBaseUrl}/${KEY}`, fetchImpl)),+ publicKey,+ );+ publicRevision = policy.revision;+ if (!current || canonicalJson(policy) !== canonicalJson(current))+ publicError = 'Public policy differs from storage';+ } catch (error) {+ publicError = error.message;+ }+ result = { ...result, publicRevision, publicError };+ await record(result);+ return result;+ }+ result = { ...result, reason: request.reason, status: plan.changed ? 'planned' : 'no-change' };+ await record(result);+ if (!plan.changed) return result;+ const installers =+ request.action === 'mark'+ ? await verifyRepairInstallers({+ policy: plan.policy,+ rule: request.rule,+ feedBaseUrl,+ fetchImpl,+ })+ : [];+ result = { ...result, installers, status: request.apply ? 'prepared' : 'preview' };+ await record(result);+ if (!request.apply) return result;+ if (!privateKey) throw new Error('RENDERER_OTA_PRIVATE_KEY is required to apply');+ const derived = createPublicKey(privateKey).export({ format: 'der', type: 'spki' });+ if (!derived.equals(createPublicKey(publicKey).export({ format: 'der', type: 'spki' })))+ throw new Error('Signing key does not match the client public key');+ const policy = {+ ...plan.policy,+ signature: sign(null, Buffer.from(canonicalJson(plan.policy)), privateKey).toString('base64'),+ };+ parsePolicy(policy, publicKey);+ const body = JSON.stringify(policy, null, 2) + '\n';+ if (Buffer.byteLength(body) > MAX_BYTES) throw new Error('Policy exceeds client size limit');+ const archive = `security-policy-history/${policy.revision}-${digest(policy)}.json`;+ await store.archive(archive, body);+ await store.write(body, stored.etag);+ result = { ...result, archive, status: 'published-unverified' };+ await record(result);+ let failure;+ for (let attempt = 0; attempt < 3; attempt++) {+ try {+ const remote = parsePolicy(+ JSON.parse(await fetchText(`${feedBaseUrl}/${KEY}`, fetchImpl)),+ publicKey,+ );+ if (canonicalJson(remote) !== canonicalJson(policy))+ throw new Error('Public policy differs from the published policy');+ result = { ...result, status: 'verified', url: `${feedBaseUrl}/${KEY}` };+ await record(result);+ return result;+ } catch (error) {+ failure = error;+ }+ if (attempt < 2) await wait(2000);+ }+ throw new Error(+ `Policy was written but public verification failed: ${failure.message}. Inspect before retrying; do not republish blindly.`,+ );+}++async function main() {+ const { values } = parseArgs({+ options: {+ 'request': { type: 'string' },+ 'output': { type: 'string' },+ 'validate-request': { type: 'boolean' },+ },+ });+ const input = values.request+ ? await readFile(values.request, 'utf8')+ : process.env.SECURITY_POLICY_REQUEST;+ if (!input) throw new Error('Provide --request <json-file> or SECURITY_POLICY_REQUEST');+ const required = (name) => {+ const value = process.env[name];+ if (!value) throw new Error(`${name} is required`);+ return value;+ };+ const request = securityPolicyRequestSchema.parse(JSON.parse(input));+ if (values['validate-request']) {+ console.log(JSON.stringify(request));+ return;+ }+ const feedBaseUrl = required('UPDATE_SERVER_URL')+ .replace(/\/$/, '')+ .replace(/\/(stable|canary|beta|nightly)$/, '');+ const publicKey = required('RENDERER_OTA_PUBLIC_KEY');+ const client = new S3Client({+ region: process.env.UPDATE_S3_REGION || 'auto',+ endpoint: required('UPDATE_S3_ENDPOINT'),+ credentials: {+ accessKeyId: required('UPDATE_AWS_ACCESS_KEY_ID'),+ secretAccessKey: required('UPDATE_AWS_SECRET_ACCESS_KEY'),+ },+ maxAttempts: 1,+ });+ let report;+ const record = async (state) => {+ report = {+ ...state,+ actor: process.env.GITHUB_ACTOR,+ runUrl: process.env.GITHUB_RUN_ID+ ? `${process.env.GITHUB_SERVER_URL}/${process.env.GITHUB_REPOSITORY}/actions/runs/${process.env.GITHUB_RUN_ID}`+ : undefined,+ };+ if (values.output) {+ await mkdir(path.dirname(values.output), { recursive: true });+ await writeFile(values.output, JSON.stringify(report, null, 2) + '\n');+ }+ };+ try {+ await runSecurityPolicy({+ request,+ store: createPolicyStore({ client, bucket: required('UPDATE_S3_BUCKET') }),+ feedBaseUrl,+ publicKey,+ privateKey: process.env.RENDERER_OTA_PRIVATE_KEY,+ record,+ });+ console.log(JSON.stringify(report, null, 2));+ } catch (error) {+ await record({ ...report, error: error.message, status: report?.status ?? 'failed' });+ throw error;+ } finally {+ client.destroy();+ }+}+if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {+ main().catch((error) => {+ console.error(error.message);+ process.exitCode = 1;+ });+}diff --git a/apps/desktop/scripts/security-policy-runtime/package-lock.json b/apps/desktop/scripts/security-policy-runtime/package-lock.jsonnew file mode 100644index 00000000000..c796a5cb22d--- /dev/null+++ b/apps/desktop/scripts/security-policy-runtime/package-lock.json@@ -0,0 +1,1482 @@+{+ "name": "desktop-security-policy-runtime",+ "version": "1.0.0",+ "lockfileVersion": 3,+ "requires": true,+ "packages": {+ "": {+ "name": "desktop-security-policy-runtime",+ "version": "1.0.0",+ "dependencies": {+ "@aws-sdk/client-s3": "3.932.0",+ "builder-util-runtime": "9.7.0",+ "semver": "7.8.5",+ "yaml": "2.9.1",+ "zod": "4.6.5"+ }+ },+ "node_modules/@aws-crypto/crc32": {+ "version": "5.2.0",+ "resolved": "https://registry.npmjs.org/@aws-crypto/crc32/-/crc32-5.2.0.tgz",+ "integrity": "sha512-nLbCWqQNgUiwwtFsen1AdzAtvuLRsQS8rYgMuxCrdKf9kOssamGLuPwyTY9wyYblNr9+1XM8v6zoDTPPSIeANg==",+ "license": "Apache-2.0",+ "dependencies": {+ "@aws-crypto/util": "^5.2.0",+ "@aws-sdk/types": "^3.222.0",+ "tslib": "^2.6.2"+ },+ "engines": {+ "node": ">=16.0.0"+ }+ },+ "node_modules/@aws-crypto/crc32c": {+ "version": "5.2.0",+ "resolved": "https://registry.npmjs.org/@aws-crypto/crc32c/-/crc32c-5.2.0.tgz",+ "integrity": "sha512-+iWb8qaHLYKrNvGRbiYRHSdKRWhto5XlZUEBwDjYNf+ly5SVYG6zEoYIdxvf5R3zyeP16w4PLBn3rH1xc74Rag==",+ "license": "Apache-2.0",+ "dependencies": {+ "@aws-crypto/util": "^5.2.0",+ "@aws-sdk/types": "^3.222.0",+ "tslib": "^2.6.2"+ }+ },+ "node_modules/@aws-crypto/sha1-browser": {+ "version": "5.2.0",+ "resolved": "https://registry.npmjs.org/@aws-crypto/sha1-browser/-/sha1-browser-5.2.0.tgz",+ "integrity": "sha512-OH6lveCFfcDjX4dbAvCFSYUjJZjDr/3XJ3xHtjn3Oj5b9RjojQo8npoLeA/bNwkOkrSQ0wgrHzXk4tDRxGKJeg==",+ "license": "Apache-2.0",+ "dependencies": {+ "@aws-crypto/supports-web-crypto": "^5.2.0",+ "@aws-crypto/util": "^5.2.0",+ "@aws-sdk/types": "^3.222.0",+ "@aws-sdk/util-locate-window": "^3.0.0",+ "@smithy/util-utf8": "^2.0.0",+ "tslib": "^2.6.2"+ }+ },+ "node_modules/@aws-crypto/sha1-browser/node_modules/@smithy/util-utf8": {+ "version": "2.3.0",+ "resolved": "https://registry.npmjs.org/@smithy/util-utf8/-/util-utf8-2.3.0.tgz",+ "integrity": "sha512-R8Rdn8Hy72KKcebgLiv8jQcQkXoLMOGGv5uI1/k0l+snqkOzQ1R0ChUBCxWMlBsFMekWjq0wRudIweFs7sKT5A==",+ "license": "Apache-2.0",+ "dependencies": {+ "@smithy/util-buffer-from": "^2.2.0",+ "tslib": "^2.6.2"+ },+ "engines": {+ "node": ">=14.0.0"+ }+ },+ "node_modules/@aws-crypto/sha256-browser": {+ "version": "5.2.0",+ "resolved": "https://registry.npmjs.org/@aws-crypto/sha256-browser/-/sha256-browser-5.2.0.tgz",+ "integrity": "sha512-AXfN/lGotSQwu6HNcEsIASo7kWXZ5HYWvfOmSNKDsEqC4OashTp8alTmaz+F7TC2L083SFv5RdB+qU3Vs1kZqw==",+ "license": "Apache-2.0",+ "dependencies": {+ "@aws-crypto/sha256-js": "^5.2.0",+ "@aws-crypto/supports-web-crypto": "^5.2.0",+ "@aws-crypto/util": "^5.2.0",+ "@aws-sdk/types": "^3.222.0",+ "@aws-sdk/util-locate-window": "^3.0.0",+ "@smithy/util-utf8": "^2.0.0",+ "tslib": "^2.6.2"+ }+ },+ "node_modules/@aws-crypto/sha256-browser/node_modules/@smithy/util-utf8": {+ "version": "2.3.0",+ "resolved": "https://registry.npmjs.org/@smithy/util-utf8/-/util-utf8-2.3.0.tgz",+ "integrity": "sha512-R8Rdn8Hy72KKcebgLiv8jQcQkXoLMOGGv5uI1/k0l+snqkOzQ1R0ChUBCxWMlBsFMekWjq0wRudIweFs7sKT5A==",+ "license": "Apache-2.0",+ "dependencies": {+ "@smithy/util-buffer-from": "^2.2.0",+ "tslib": "^2.6.2"+ },+ "engines": {+ "node": ">=14.0.0"+ }+ },+ "node_modules/@aws-crypto/sha256-js": {+ "version": "5.2.0",+ "resolved": "https://registry.npmjs.org/@aws-crypto/sha256-js/-/sha256-js-5.2.0.tgz",+ "integrity": "sha512-FFQQyu7edu4ufvIZ+OadFpHHOt+eSTBaYaki44c+akjg7qZg9oOQeLlk77F6tSYqjDAFClrHJk9tMf0HdVyOvA==",+ "license": "Apache-2.0",+ "dependencies": {+ "@aws-crypto/util": "^5.2.0",+ "@aws-sdk/types": "^3.222.0",+ "tslib": "^2.6.2"+ },+ "engines": {+ "node": ">=16.0.0"+ }+ },+ "node_modules/@aws-crypto/supports-web-crypto": {+ "version": "5.2.0",+ "resolved": "https://registry.npmjs.org/@aws-crypto/supports-web-crypto/-/supports-web-crypto-5.2.0.tgz",+ "integrity": "sha512-iAvUotm021kM33eCdNfwIN//F77/IADDSs58i+MDaOqFrVjZo9bAal0NK7HurRuWLLpF1iLX7gbWrjHjeo+YFg==",+ "license": "Apache-2.0",+ "dependencies": {+ "tslib": "^2.6.2"+ }+ },+ "node_modules/@aws-crypto/util": {+ "version": "5.2.0",+ "resolved": "https://registry.npmjs.org/@aws-crypto/util/-/util-5.2.0.tgz",+ "integrity": "sha512-4RkU9EsI6ZpBve5fseQlGNUWKMa1RLPQ1dnjnQoe07ldfIzcsGb5hC5W0Dm7u423KWzawlrpbjXBrXCEv9zazQ==",+ "license": "Apache-2.0",+ "dependencies": {+ "@aws-sdk/types": "^3.222.0",+ "@smithy/util-utf8": "^2.0.0",+ "tslib": "^2.6.2"+ }+ },+ "node_modules/@aws-crypto/util/node_modules/@smithy/util-utf8": {+ "version": "2.3.0",+ "resolved": "https://registry.npmjs.org/@smithy/util-utf8/-/util-utf8-2.3.0.tgz",+ "integrity": "sha512-R8Rdn8Hy72KKcebgLiv8jQcQkXoLMOGGv5uI1/k0l+snqkOzQ1R0ChUBCxWMlBsFMekWjq0wRudIweFs7sKT5A==",+ "license": "Apache-2.0",+ "dependencies": {+ "@smithy/util-buffer-from": "^2.2.0",+ "tslib": "^2.6.2"+ },+ "engines": {+ "node": ">=14.0.0"+ }+ },+ "node_modules/@aws-sdk/client-s3": {+ "version": "3.932.0",+ "resolved": "https://registry.npmjs.org/@aws-sdk/client-s3/-/client-s3-3.932.0.tgz",+ "integrity": "sha512-qrlbJ3W5QR3Gzz2S+yaItH8ZhX7vaeA4j4fDAi8+0FmsVhXOfBbomWr+JO1wk/YojZMdyLfmfYRHrJvAQsLFVw==",+ "license": "Apache-2.0",+ "dependencies": {+ "@aws-crypto/sha1-browser": "5.2.0",+ "@aws-crypto/sha256-browser": "5.2.0",+ "@aws-crypto/sha256-js": "5.2.0",+ "@aws-sdk/core": "3.932.0",+ "@aws-sdk/credential-provider-node": "3.932.0",+ "@aws-sdk/middleware-bucket-endpoint": "3.930.0",+ "@aws-sdk/middleware-expect-continue": "3.930.0",+ "@aws-sdk/middleware-flexible-checksums": "3.932.0",+ "@aws-sdk/middleware-host-header": "3.930.0",+ "@aws-sdk/middleware-location-constraint": "3.930.0",+ "@aws-sdk/middleware-logger": "3.930.0",+ "@aws-sdk/middleware-recursion-detection": "3.930.0",+ "@aws-sdk/middleware-sdk-s3": "3.932.0",+ "@aws-sdk/middleware-ssec": "3.930.0",+ "@aws-sdk/middleware-user-agent": "3.932.0",+ "@aws-sdk/region-config-resolver": "3.930.0",+ "@aws-sdk/signature-v4-multi-region": "3.932.0",+ "@aws-sdk/types": "3.930.0",+ "@aws-sdk/util-endpoints": "3.930.0",+ "@aws-sdk/util-user-agent-browser": "3.930.0",+ "@aws-sdk/util-user-agent-node": "3.932.0",+ "@smithy/config-resolver": "^4.4.3",+ "@smithy/core": "^3.18.2",+ "@smithy/eventstream-serde-browser": "^4.2.5",+ "@smithy/eventstream-serde-config-resolver": "^4.3.5",+ "@smithy/eventstream-serde-node": "^4.2.5",+ "@smithy/fetch-http-handler": "^5.3.6",+ "@smithy/hash-blob-browser": "^4.2.6",+ "@smithy/hash-node": "^4.2.5",+ "@smithy/hash-stream-node": "^4.2.5",+ "@smithy/invalid-dependency": "^4.2.5",+ "@smithy/md5-js": "^4.2.5",+ "@smithy/middleware-content-length": "^4.2.5",+ "@smithy/middleware-endpoint": "^4.3.9",+ "@smithy/middleware-retry": "^4.4.9",+ "@smithy/middleware-serde": "^4.2.5",+ "@smithy/middleware-stack": "^4.2.5",+ "@smithy/node-config-provider": "^4.3.5",+ "@smithy/node-http-handler": "^4.4.5",+ "@smithy/protocol-http": "^5.3.5",+ "@smithy/smithy-client": "^4.9.5",+ "@smithy/types": "^4.9.0",+ "@smithy/url-parser": "^4.2.5",+ "@smithy/util-base64": "^4.3.0",+ "@smithy/util-body-length-browser": "^4.2.0",+ "@smithy/util-body-length-node": "^4.2.1",+ "@smithy/util-defaults-mode-browser": "^4.3.8",+ "@smithy/util-defaults-mode-node": "^4.2.11",+ "@smithy/util-endpoints": "^3.2.5",+ "@smithy/util-middleware": "^4.2.5",+ "@smithy/util-retry": "^4.2.5",+ "@smithy/util-stream": "^4.5.6",+ "@smithy/util-utf8": "^4.2.0",+ "@smithy/util-waiter": "^4.2.5",+ "tslib": "^2.6.2"+ },+ "engines": {+ "node": ">=18.0.0"+ }+ },+ "node_modules/@aws-sdk/client-sso": {+ "version": "3.932.0",+ "resolved": "https://registry.npmjs.org/@aws-sdk/client-sso/-/client-sso-3.932.0.tgz",+ "integrity": "sha512-XHqHa5iv2OQsKoM2tUQXs7EAyryploC00Wg0XSFra/KAKqyGizUb5XxXsGlyqhebB29Wqur+zwiRwNmejmN0+Q==",+ "license": "Apache-2.0",+ "dependencies": {+ "@aws-crypto/sha256-browser": "5.2.0",+ "@aws-crypto/sha256-js": "5.2.0",+ "@aws-sdk/core": "3.932.0",+ "@aws-sdk/middleware-host-header": "3.930.0",+ "@aws-sdk/middleware-logger": "3.930.0",+ "@aws-sdk/middleware-recursion-detection": "3.930.0",+ "@aws-sdk/middleware-user-agent": "3.932.0",+ "@aws-sdk/region-config-resolver": "3.930.0",+ "@aws-sdk/types": "3.930.0",+ "@aws-sdk/util-endpoints": "3.930.0",+ "@aws-sdk/util-user-agent-browser": "3.930.0",+ "@aws-sdk/util-user-agent-node": "3.932.0",+ "@smithy/config-resolver": "^4.4.3",+ "@smithy/core": "^3.18.2",+ "@smithy/fetch-http-handler": "^5.3.6",+ "@smithy/hash-node": "^4.2.5",+ "@smithy/invalid-dependency": "^4.2.5",+ "@smithy/middleware-content-length": "^4.2.5",+ "@smithy/middleware-endpoint": "^4.3.9",+ "@smithy/middleware-retry": "^4.4.9",+ "@smithy/middleware-serde": "^4.2.5",+ "@smithy/middleware-stack": "^4.2.5",+ "@smithy/node-config-provider": "^4.3.5",+ "@smithy/node-http-handler": "^4.4.5",+ "@smithy/protocol-http": "^5.3.5",+ "@smithy/smithy-client": "^4.9.5",+ "@smithy/types": "^4.9.0",+ "@smithy/url-parser": "^4.2.5",+ "@smithy/util-base64": "^4.3.0",+ "@smithy/util-body-length-browser": "^4.2.0",+ "@smithy/util-body-length-node": "^4.2.1",+ "@smithy/util-defaults-mode-browser": "^4.3.8",+ "@smithy/util-defaults-mode-node": "^4.2.11",+ "@smithy/util-endpoints": "^3.2.5",+ "@smithy/util-middleware": "^4.2.5",+ "@smithy/util-retry": "^4.2.5",+ "@smithy/util-utf8": "^4.2.0",+ "tslib": "^2.6.2"+ },+ "engines": {+ "node": ">=18.0.0"+ }+ },+ "node_modules/@aws-sdk/core": {+ "version": "3.932.0",+ "resolved": "https://registry.npmjs.org/@aws-sdk/core/-/core-3.932.0.tgz",+ "integrity": "sha512-AS8gypYQCbNojwgjvZGkJocC2CoEICDx9ZJ15ILsv+MlcCVLtUJSRSx3VzJOUY2EEIaGLRrPNlIqyn/9/fySvA==",+ "license": "Apache-2.0",+ "dependencies": {+ "@aws-sdk/types": "3.930.0",+ "@aws-sdk/xml-builder": "3.930.0",+ "@smithy/core": "^3.18.2",+ "@smithy/node-config-provider": "^4.3.5",+ "@smithy/property-provider": "^4.2.5",+ "@smithy/protocol-http": "^5.3.5",+ "@smithy/signature-v4": "^5.3.5",+ "@smithy/smithy-client": "^4.9.5",+ "@smithy/types": "^4.9.0",+ "@smithy/util-base64": "^4.3.0",+ "@smithy/util-middleware": "^4.2.5",+ "@smithy/util-utf8": "^4.2.0",+ "tslib": "^2.6.2"+ },+ "engines": {+ "node": ">=18.0.0"+ }+ },+ "node_modules/@aws-sdk/credential-provider-env": {+ "version": "3.932.0",+ "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-env/-/credential-provider-env-3.932.0.tgz",+ "integrity": "sha512-ozge/c7NdHUDyHqro6+P5oHt8wfKSUBN+olttiVfBe9Mw3wBMpPa3gQ0pZnG+gwBkKskBuip2bMR16tqYvUSEA==",+ "license": "Apache-2.0",+ "dependencies": {+ "@aws-sdk/core": "3.932.0",+ "@aws-sdk/types": "3.930.0",+ "@smithy/property-provider": "^4.2.5",+ "@smithy/types": "^4.9.0",+ "tslib": "^2.6.2"+ },+ "engines": {+ "node": ">=18.0.0"+ }+ },+ "node_modules/@aws-sdk/credential-provider-http": {+ "version": "3.932.0",+ "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-http/-/credential-provider-http-3.932.0.tgz",+ "integrity": "sha512-b6N9Nnlg8JInQwzBkUq5spNaXssM3h3zLxGzpPrnw0nHSIWPJPTbZzA5Ca285fcDUFuKP+qf3qkuqlAjGOdWhg==",+ "license": "Apache-2.0",+ "dependencies": {+ "@aws-sdk/core": "3.932.0",+ "@aws-sdk/types": "3.930.0",+ "@smithy/fetch-http-handler": "^5.3.6",+ "@smithy/node-http-handler": "^4.4.5",+ "@smithy/property-provider": "^4.2.5",+ "@smithy/protocol-http": "^5.3.5",+ "@smithy/smithy-client": "^4.9.5",+ "@smithy/types": "^4.9.0",+ "@smithy/util-stream": "^4.5.6",+ "tslib": "^2.6.2"+ },+ "engines": {+ "node": ">=18.0.0"+ }+ },+ "node_modules/@aws-sdk/credential-provider-ini": {+ "version": "3.932.0",+ "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-ini/-/credential-provider-ini-3.932.0.tgz",+ "integrity": "sha512-ZBjSAXVGy7danZRHCRMJQ7sBkG1Dz39thYlvTiUaf9BKZ+8ymeiFhuTeV1OkWUBBnY0ki2dVZJvboTqfINhNxA==",+ "license": "Apache-2.0",+ "dependencies": {+ "@aws-sdk/core": "3.932.0",+ "@aws-sdk/credential-provider-env": "3.932.0",+ "@aws-sdk/credential-provider-http": "3.932.0",+ "@aws-sdk/credential-provider-process": "3.932.0",+ "@aws-sdk/credential-provider-sso": "3.932.0",+ "@aws-sdk/credential-provider-web-identity": "3.932.0",+ "@aws-sdk/nested-clients": "3.932.0",+ "@aws-sdk/types": "3.930.0",+ "@smithy/credential-provider-imds": "^4.2.5",+ "@smithy/property-provider": "^4.2.5",+ "@smithy/shared-ini-file-loader": "^4.4.0",+ "@smithy/types": "^4.9.0",+ "tslib": "^2.6.2"+ },+ "engines": {+ "node": ">=18.0.0"+ }+ },+ "node_modules/@aws-sdk/credential-provider-node": {+ "version": "3.932.0",+ "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-node/-/credential-provider-node-3.932.0.tgz",+ "integrity": "sha512-SEG9t2taBT86qe3gTunfrK8BxT710GVLGepvHr+X5Pw+qW225iNRaGN0zJH+ZE/j91tcW9wOaIoWnURkhR5wIg==",+ "license": "Apache-2.0",+ "dependencies": {+ "@aws-sdk/credential-provider-env": "3.932.0",+ "@aws-sdk/credential-provider-http": "3.932.0",+ "@aws-sdk/credential-provider-ini": "3.932.0",+ "@aws-sdk/credential-provider-process": "3.932.0",+ "@aws-sdk/credential-provider-sso": "3.932.0",+ "@aws-sdk/credential-provider-web-identity": "3.932.0",+ "@aws-sdk/types": "3.930.0",+ "@smithy/credential-provider-imds": "^4.2.5",+ "@smithy/property-provider": "^4.2.5",+ "@smithy/shared-ini-file-loader": "^4.4.0",+ "@smithy/types": "^4.9.0",+ "tslib": "^2.6.2"+ },+ "engines": {+ "node": ">=18.0.0"+ }+ },+ "node_modules/@aws-sdk/credential-provider-process": {+ "version": "3.932.0",+ "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-process/-/credential-provider-process-3.932.0.tgz",+ "integrity": "sha512-BodZYKvT4p/Dkm28Ql/FhDdS1+p51bcZeMMu2TRtU8PoMDHnVDhHz27zASEKSZwmhvquxHrZHB0IGuVqjZUtSQ==",+ "license": "Apache-2.0",+ "dependencies": {+ "@aws-sdk/core": "3.932.0",+ "@aws-sdk/types": "3.930.0",+ "@smithy/property-provider": "^4.2.5",+ "@smithy/shared-ini-file-loader": "^4.4.0",+ "@smithy/types": "^4.9.0",+ "tslib": "^2.6.2"+ },+ "engines": {+ "node": ">=18.0.0"+ }+ },+ "node_modules/@aws-sdk/credential-provider-sso": {+ "version": "3.932.0",+ "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-sso/-/credential-provider-sso-3.932.0.tgz",+ "integrity": "sha512-XYmkv+ltBjjmPZ6AmR1ZQZkQfD0uzG61M18/Lif3HAGxyg3dmod0aWx9aL6lj9SvxAGqzscrx5j4PkgLqjZruw==",+ "license": "Apache-2.0",+ "dependencies": {+ "@aws-sdk/client-sso": "3.932.0",+ "@aws-sdk/core": "3.932.0",+ "@aws-sdk/token-providers": "3.932.0",+ "@aws-sdk/types": "3.930.0",+ "@smithy/property-provider": "^4.2.5",+ "@smithy/shared-ini-file-loader": "^4.4.0",+ "@smithy/types": "^4.9.0",+ "tslib": "^2.6.2"+ },+ "engines": {+ "node": ">=18.0.0"+ }+ },+ "node_modules/@aws-sdk/credential-provider-web-identity": {+ "version": "3.932.0",+ "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-web-identity/-/credential-provider-web-identity-3.932.0.tgz",+ "integrity": "sha512-Yw/hYNnC1KHuVIQF9PkLXbuKN7ljx70OSbJYDRufllQvej3kRwNcqQSnzI1M4KaObccqKaE6srg22DqpPy9p8w==",+ "license": "Apache-2.0",+ "dependencies": {+ "@aws-sdk/core": "3.932.0",+ "@aws-sdk/nested-clients": "3.932.0",+ "@aws-sdk/types": "3.930.0",+ "@smithy/property-provider": "^4.2.5",+ "@smithy/shared-ini-file-loader": "^4.4.0",+ "@smithy/types": "^4.9.0",+ "tslib": "^2.6.2"+ },+ "engines": {+ "node": ">=18.0.0"+ }+ },+ "node_modules/@aws-sdk/middleware-bucket-endpoint": {+ "version": "3.930.0",+ "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-bucket-endpoint/-/middleware-bucket-endpoint-3.930.0.tgz",+ "integrity": "sha512-cnCLWeKPYgvV4yRYPFH6pWMdUByvu2cy2BAlfsPpvnm4RaVioztyvxmQj5PmVN5fvWs5w/2d6U7le8X9iye2sA==",+ "license": "Apache-2.0",+ "dependencies": {+ "@aws-sdk/types": "3.930.0",+ "@aws-sdk/util-arn-parser": "3.893.0",+ "@smithy/node-config-provider": "^4.3.5",+ "@smithy/protocol-http": "^5.3.5",+ "@smithy/types": "^4.9.0",+ "@smithy/util-config-provider": "^4.2.0",+ "tslib": "^2.6.2"+ },+ "engines": {+ "node": ">=18.0.0"+ }+ },+ "node_modules/@aws-sdk/middleware-expect-continue": {+ "version": "3.930.0",+ "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-expect-continue/-/middleware-expect-continue-3.930.0.tgz",+ "integrity": "sha512-5HEQ+JU4DrLNWeY27wKg/jeVa8Suy62ivJHOSUf6e6hZdVIMx0h/kXS1fHEQNNiLu2IzSEP/bFXsKBaW7x7s0g==",+ "license": "Apache-2.0",+ "dependencies": {+ "@aws-sdk/types": "3.930.0",+ "@smithy/protocol-http": "^5.3.5",+ "@smithy/types": "^4.9.0",+ "tslib": "^2.6.2"+ },+ "engines": {+ "node": ">=18.0.0"+ }+ },+ "node_modules/@aws-sdk/middleware-flexible-checksums": {+ "version": "3.932.0",+ "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-flexible-checksums/-/middleware-flexible-checksums-3.932.0.tgz",+ "integrity": "sha512-hyvRz/XS/0HTHp9/Ld1mKwpOi7bZu5olI42+T112rkCTbt1bewkygzEl4oflY4H7cKMamQusYoL0yBUD/QSEvA==",+ "license": "Apache-2.0",+ "dependencies": {+ "@aws-crypto/crc32": "5.2.0",+ "@aws-crypto/crc32c": "5.2.0",+ "@aws-crypto/util": "5.2.0",+ "@aws-sdk/core": "3.932.0",+ "@aws-sdk/types": "3.930.0",+ "@smithy/is-array-buffer": "^4.2.0",+ "@smithy/node-config-provider": "^4.3.5",+ "@smithy/protocol-http": "^5.3.5",+ "@smithy/types": "^4.9.0",+ "@smithy/util-middleware": "^4.2.5",+ "@smithy/util-stream": "^4.5.6",+ "@smithy/util-utf8": "^4.2.0",+ "tslib": "^2.6.2"+ },+ "engines": {+ "node": ">=18.0.0"+ }+ },+ "node_modules/@aws-sdk/middleware-host-header": {+ "version": "3.930.0",+ "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-host-header/-/middleware-host-header-3.930.0.tgz",+ "integrity": "sha512-x30jmm3TLu7b/b+67nMyoV0NlbnCVT5DI57yDrhXAPCtdgM1KtdLWt45UcHpKOm1JsaIkmYRh2WYu7Anx4MG0g==",+ "license": "Apache-2.0",+ "dependencies": {+ "@aws-sdk/types": "3.930.0",+ "@smithy/protocol-http": "^5.3.5",+ "@smithy/types": "^4.9.0",+ "tslib": "^2.6.2"+ },+ "engines": {+ "node": ">=18.0.0"+ }+ },+ "node_modules/@aws-sdk/middleware-location-constraint": {+ "version": "3.930.0",+ "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-location-constraint/-/middleware-location-constraint-3.930.0.tgz",+ "integrity": "sha512-QIGNsNUdRICog+LYqmtJ03PLze6h2KCORXUs5td/hAEjVP5DMmubhtrGg1KhWyctACluUH/E/yrD14p4pRXxwA==",+ "license": "Apache-2.0",+ "dependencies": {+ "@aws-sdk/types": "3.930.0",+ "@smithy/types": "^4.9.0",+ "tslib": "^2.6.2"+ },+ "engines": {+ "node": ">=18.0.0"+ }+ },+ "node_modules/@aws-sdk/middleware-logger": {+ "version": "3.930.0",+ "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-logger/-/middleware-logger-3.930.0.tgz",+ "integrity": "sha512-vh4JBWzMCBW8wREvAwoSqB2geKsZwSHTa0nSt0OMOLp2PdTYIZDi0ZiVMmpfnjcx9XbS6aSluLv9sKx4RrG46A==",+ "license": "Apache-2.0",+ "dependencies": {+ "@aws-sdk/types": "3.930.0",+ "@smithy/types": "^4.9.0",+ "tslib": "^2.6.2"+ },+ "engines": {+ "node": ">=18.0.0"+ }+ },+ "node_modules/@aws-sdk/middleware-recursion-detection": {+ "version": "3.930.0",+ "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-recursion-detection/-/middleware-recursion-detection-3.930.0.tgz",+ "integrity": "sha512-gv0sekNpa2MBsIhm2cjP3nmYSfI4nscx/+K9u9ybrWZBWUIC4kL2sV++bFjjUz4QxUIlvKByow3/a9ARQyCu7Q==",+ "license": "Apache-2.0",+ "dependencies": {+ "@aws-sdk/types": "3.930.0",+ "@aws/lambda-invoke-store": "^0.1.1",+ "@smithy/protocol-http": "^5.3.5",+ "@smithy/types": "^4.9.0",+ "tslib": "^2.6.2"+ },+ "engines": {+ "node": ">=18.0.0"+ }+ },+ "node_modules/@aws-sdk/middleware-sdk-s3": {+ "version": "3.932.0",+ "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-sdk-s3/-/middleware-sdk-s3-3.932.0.tgz",+ "integrity": "sha512-bYMHxqQzseaAP9Z5qLI918z5AtbAnZRRtFi3POb4FLZyreBMgCgBNaPkIhdgywnkqaydTWvbMBX4s9f4gUwlTw==",+ "license": "Apache-2.0",+ "dependencies": {+ "@aws-sdk/core": "3.932.0",+ "@aws-sdk/types": "3.930.0",+ "@aws-sdk/util-arn-parser": "3.893.0",+ "@smithy/core": "^3.18.2",+ "@smithy/node-config-provider": "^4.3.5",+ "@smithy/protocol-http": "^5.3.5",+ "@smithy/signature-v4": "^5.3.5",+ "@smithy/smithy-client": "^4.9.5",+ "@smithy/types": "^4.9.0",+ "@smithy/util-config-provider": "^4.2.0",+ "@smithy/util-middleware": "^4.2.5",+ "@smithy/util-stream": "^4.5.6",+ "@smithy/util-utf8": "^4.2.0",+ "tslib": "^2.6.2"+ },+ "engines": {+ "node": ">=18.0.0"+ }+ },+ "node_modules/@aws-sdk/middleware-ssec": {+ "version": "3.930.0",+ "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-ssec/-/middleware-ssec-3.930.0.tgz",+ "integrity": "sha512-N2/SvodmaDS6h7CWfuapt3oJyn1T2CBz0CsDIiTDv9cSagXAVFjPdm2g4PFJqrNBeqdDIoYBnnta336HmamWHg==",+ "license": "Apache-2.0",+ "dependencies": {+ "@aws-sdk/types": "3.930.0",+ "@smithy/types": "^4.9.0",+ "tslib": "^2.6.2"+ },+ "engines": {+ "node": ">=18.0.0"+ }+ },+ "node_modules/@aws-sdk/middleware-user-agent": {+ "version": "3.932.0",+ "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-user-agent/-/middleware-user-agent-3.932.0.tgz",+ "integrity": "sha512-9BGTbJyA/4PTdwQWE9hAFIJGpsYkyEW20WON3i15aDqo5oRZwZmqaVageOD57YYqG8JDJjvcwKyDdR4cc38dvg==",+ "license": "Apache-2.0",+ "dependencies": {+ "@aws-sdk/core": "3.932.0",+ "@aws-sdk/types": "3.930.0",+ "@aws-sdk/util-endpoints": "3.930.0",+ "@smithy/core": "^3.18.2",+ "@smithy/protocol-http": "^5.3.5",+ "@smithy/types": "^4.9.0",+ "tslib": "^2.6.2"+ },+ "engines": {+ "node": ">=18.0.0"+ }+ },+ "node_modules/@aws-sdk/nested-clients": {+ "version": "3.932.0",+ "resolved": "https://registry.npmjs.org/@aws-sdk/nested-clients/-/nested-clients-3.932.0.tgz",+ "integrity": "sha512-E2ucBfiXSpxZflHTf3UFbVwao4+7v7ctAeg8SWuglc1UMqMlpwMFFgWiSONtsf0SR3+ZDoWGATyCXOfDWerJuw==",+ "license": "Apache-2.0",+ "dependencies": {+ "@aws-crypto/sha256-browser": "5.2.0",+ "@aws-crypto/sha256-js": "5.2.0",+ "@aws-sdk/core": "3.932.0",+ "@aws-sdk/middleware-host-header": "3.930.0",+ "@aws-sdk/middleware-logger": "3.930.0",+ "@aws-sdk/middleware-recursion-detection": "3.930.0",+ "@aws-sdk/middleware-user-agent": "3.932.0",+ "@aws-sdk/region-config-resolver": "3.930.0",+ "@aws-sdk/types": "3.930.0",+ "@aws-sdk/util-endpoints": "3.930.0",+ "@aws-sdk/util-user-agent-browser": "3.930.0",+ "@aws-sdk/util-user-agent-node": "3.932.0",+ "@smithy/config-resolver": "^4.4.3",+ "@smithy/core": "^3.18.2",+ "@smithy/fetch-http-handler": "^5.3.6",+ "@smithy/hash-node": "^4.2.5",+ "@smithy/invalid-dependency": "^4.2.5",+ "@smithy/middleware-content-length": "^4.2.5",+ "@smithy/middleware-endpoint": "^4.3.9",+ "@smithy/middleware-retry": "^4.4.9",+ "@smithy/middleware-serde": "^4.2.5",+ "@smithy/middleware-stack": "^4.2.5",+ "@smithy/node-config-provider": "^4.3.5",+ "@smithy/node-http-handler": "^4.4.5",+ "@smithy/protocol-http": "^5.3.5",+ "@smithy/smithy-client": "^4.9.5",+ "@smithy/types": "^4.9.0",+ "@smithy/url-parser": "^4.2.5",+ "@smithy/util-base64": "^4.3.0",+ "@smithy/util-body-length-browser": "^4.2.0",+ "@smithy/util-body-length-node": "^4.2.1",+ "@smithy/util-defaults-mode-browser": "^4.3.8",+ "@smithy/util-defaults-mode-node": "^4.2.11",+ "@smithy/util-endpoints": "^3.2.5",+ "@smithy/util-middleware": "^4.2.5",+ "@smithy/util-retry": "^4.2.5",+ "@smithy/util-utf8": "^4.2.0",+ "tslib": "^2.6.2"+ },+ "engines": {+ "node": ">=18.0.0"+ }+ },+ "node_modules/@aws-sdk/region-config-resolver": {+ "version": "3.930.0",+ "resolved": "https://registry.npmjs.org/@aws-sdk/region-config-resolver/-/region-config-resolver-3.930.0.tgz",+ "integrity": "sha512-KL2JZqH6aYeQssu1g1KuWsReupdfOoxD6f1as2VC+rdwYFUu4LfzMsFfXnBvvQWWqQ7rZHWOw1T+o5gJmg7Dzw==",+ "license": "Apache-2.0",+ "dependencies": {+ "@aws-sdk/types": "3.930.0",+ "@smithy/config-resolver": "^4.4.3",+ "@smithy/node-config-provider": "^4.3.5",+ "@smithy/types": "^4.9.0",+ "tslib": "^2.6.2"+ },+ "engines": {+ "node": ">=18.0.0"+ }+ },+ "node_modules/@aws-sdk/signature-v4-multi-region": {+ "version": "3.932.0",+ "resolved": "https://registry.npmjs.org/@aws-sdk/signature-v4-multi-region/-/signature-v4-multi-region-3.932.0.tgz",+ "integrity": "sha512-NCIRJvoRc9246RZHIusY1+n/neeG2yGhBGdKhghmrNdM+mLLN6Ii7CKFZjx3DhxtpHMpl1HWLTMhdVrGwP2upw==",+ "license": "Apache-2.0",+ "dependencies": {+ "@aws-sdk/middleware-sdk-s3": "3.932.0",+ "@aws-sdk/types": "3.930.0",+ "@smithy/protocol-http": "^5.3.5",+ "@smithy/signature-v4": "^5.3.5",+ "@smithy/types": "^4.9.0",+ "tslib": "^2.6.2"+ },+ "engines": {+ "node": ">=18.0.0"+ }+ },+ "node_modules/@aws-sdk/token-providers": {+ "version": "3.932.0",+ "resolved": "https://registry.npmjs.org/@aws-sdk/token-providers/-/token-providers-3.932.0.tgz",+ "integrity": "sha512-43u82ulVuHK4zWhcSPyuPS18l0LNHi3QJQ1YtP2MfP8bPf5a6hMYp5e3lUr9oTDEWcpwBYtOW0m1DVmoU/3veA==",+ "license": "Apache-2.0",+ "dependencies": {+ "@aws-sdk/core": "3.932.0",+ "@aws-sdk/nested-clients": "3.932.0",+ "@aws-sdk/types": "3.930.0",+ "@smithy/property-provider": "^4.2.5",+ "@smithy/shared-ini-file-loader": "^4.4.0",+ "@smithy/types": "^4.9.0",+ "tslib": "^2.6.2"+ },+ "engines": {+ "node": ">=18.0.0"+ }+ },+ "node_modules/@aws-sdk/types": {+ "version": "3.930.0",+ "resolved": "https://registry.npmjs.org/@aws-sdk/types/-/types-3.930.0.tgz",+ "integrity": "sha512-we/vaAgwlEFW7IeftmCLlLMw+6hFs3DzZPJw7lVHbj/5HJ0bz9gndxEsS2lQoeJ1zhiiLqAqvXxmM43s0MBg0A==",+ "license": "Apache-2.0",+ "dependencies": {+ "@smithy/types": "^4.9.0",+ "tslib": "^2.6.2"+ },+ "engines": {+ "node": ">=18.0.0"+ }+ },+ "node_modules/@aws-sdk/util-arn-parser": {+ "version": "3.893.0",+ "resolved": "https://registry.npmjs.org/@aws-sdk/util-arn-parser/-/util-arn-parser-3.893.0.tgz",+ "integrity": "sha512-u8H4f2Zsi19DGnwj5FSZzDMhytYF/bCh37vAtBsn3cNDL3YG578X5oc+wSX54pM3tOxS+NY7tvOAo52SW7koUA==",+ "license": "Apache-2.0",+ "dependencies": {+ "tslib": "^2.6.2"+ },+ "engines": {+ "node": ">=18.0.0"+ }+ },+ "node_modules/@aws-sdk/util-endpoints": {+ "version": "3.930.0",+ "resolved": "https://registry.npmjs.org/@aws-sdk/util-endpoints/-/util-endpoints-3.930.0.tgz",+ "integrity": "sha512-M2oEKBzzNAYr136RRc6uqw3aWlwCxqTP1Lawps9E1d2abRPvl1p1ztQmmXp1Ak4rv8eByIZ+yQyKQ3zPdRG5dw==",+ "license": "Apache-2.0",+ "dependencies": {+ "@aws-sdk/types": "3.930.0",+ "@smithy/types": "^4.9.0",+ "@smithy/url-parser": "^4.2.5",+ "@smithy/util-endpoints": "^3.2.5",+ "tslib": "^2.6.2"+ },+ "engines": {+ "node": ">=18.0.0"+ }+ },+ "node_modules/@aws-sdk/util-locate-window": {+ "version": "3.965.10",+ "resolved": "https://registry.npmjs.org/@aws-sdk/util-locate-window/-/util-locate-window-3.965.10.tgz",+ "integrity": "sha512-ycwH6Zd2GhuSqdXX9ihbCjeGTB6xOJs+O3+Jb8/zDG9978XU80qs75dfkPJRMNKe5MvBZPuNeFpd4JZKPoUF4g==",+ "license": "Apache-2.0",+ "dependencies": {+ "tslib": "^2.6.2"+ },+ "engines": {+ "node": ">=20.0.0"+ }+ },+ "node_modules/@aws-sdk/util-user-agent-browser": {+ "version": "3.930.0",+ "resolved": "https://registry.npmjs.org/@aws-sdk/util-user-agent-browser/-/util-user-agent-browser-3.930.0.tgz",+ "integrity": "sha512-q6lCRm6UAe+e1LguM5E4EqM9brQlDem4XDcQ87NzEvlTW6GzmNCO0w1jS0XgCFXQHjDxjdlNFX+5sRbHijwklg==",+ "license": "Apache-2.0",+ "dependencies": {+ "@aws-sdk/types": "3.930.0",+ "@smithy/types": "^4.9.0",+ "bowser": "^2.11.0",+ "tslib": "^2.6.2"+ }+ },+ "node_modules/@aws-sdk/util-user-agent-node": {+ "version": "3.932.0",+ "resolved": "https://registry.npmjs.org/@aws-sdk/util-user-agent-node/-/util-user-agent-node-3.932.0.tgz",+ "integrity": "sha512-/kC6cscHrZL74TrZtgiIL5jJNbVsw9duGGPurmaVgoCbP7NnxyaSWEurbNV3VPNPhNE3bV3g4Ci+odq+AlsYQg==",+ "license": "Apache-2.0",+ "dependencies": {+ "@aws-sdk/middleware-user-agent": "3.932.0",+ "@aws-sdk/types": "3.930.0",+ "@smithy/node-config-provider": "^4.3.5",+ "@smithy/types": "^4.9.0",+ "tslib": "^2.6.2"+ },+ "engines": {+ "node": ">=18.0.0"+ },+ "peerDependencies": {+ "aws-crt": ">=1.0.0"+ },+ "peerDependenciesMeta": {+ "aws-crt": {+ "optional": true+ }+ }+ },+ "node_modules/@aws-sdk/xml-builder": {+ "version": "3.930.0",+ "resolved": "https://registry.npmjs.org/@aws-sdk/xml-builder/-/xml-builder-3.930.0.tgz",+ "integrity": "sha512-YIfkD17GocxdmlUVc3ia52QhcWuRIUJonbF8A2CYfcWNV3HzvAqpcPeC0bYUhkK+8e8YO1ARnLKZQE0TlwzorA==",+ "license": "Apache-2.0",+ "dependencies": {+ "@smithy/types": "^4.9.0",+ "fast-xml-parser": "5.2.5",+ "tslib": "^2.6.2"+ },+ "engines": {+ "node": ">=18.0.0"+ }+ },+ "node_modules/@aws/lambda-invoke-store": {+ "version": "0.1.1",+ "resolved": "https://registry.npmjs.org/@aws/lambda-invoke-store/-/lambda-invoke-store-0.1.1.tgz",+ "integrity": "sha512-RcLam17LdlbSOSp9VxmUu1eI6Mwxp+OwhD2QhiSNmNCzoDb0EeUXTD2n/WbcnrAYMGlmf05th6QYq23VqvJqpA==",+ "license": "Apache-2.0",+ "engines": {+ "node": ">=18.0.0"+ }+ },+ "node_modules/@smithy/config-resolver": {+ "version": "4.7.2",+ "resolved": "https://registry.npmjs.org/@smithy/config-resolver/-/config-resolver-4.7.2.tgz",+ "integrity": "sha512-Y1XfSefHIOub9762qm3ShafdlEE/Va8h3kLUeMq765fNeWeNLcOP2YUPr86H1SlyGwZTOqQ67RlBZPZ3k9Djgg==",+ "license": "Apache-2.0",+ "dependencies": {+ "@smithy/core": "^3.33.2",+ "tslib": "^2.6.2"+ },+ "engines": {+ "node": ">=18.0.0"+ }+ },+ "node_modules/@smithy/core": {+ "version": "3.35.1",+ "resolved": "https://registry.npmjs.org/@smithy/core/-/core-3.35.1.tgz",+ "integrity": "sha512-i4YPS4B6ts7bjn7UwLnGjiZdprOvHvgGobFZsYK3GIY3E5hIqtj0rReU69BcTpGp+fvtraSNXeG1l+jtJvF55w==",+ "license": "Apache-2.0",+ "dependencies": {+ "@smithy/types": "^4.19.0",+ "tslib": "^2.6.2"+ },+ "engines": {+ "node": ">=18.0.0"+ }+ },+ "node_modules/@smithy/credential-provider-imds": {+ "version": "4.5.2",+ "resolved": "https://registry.npmjs.org/@smithy/credential-provider-imds/-/credential-provider-imds-4.5.2.tgz",+ "integrity": "sha512-A9uSdn72ozbRUSit0eib0TW7nXuNPlaeM0zcGkJ+nE6tFcSDbnmtwoxbTCFBukVQcszDAyvsd7+rTduPTXpygg==",+ "license": "Apache-2.0",+ "dependencies": {+ "@smithy/core": "^3.33.2",+ "@smithy/types": "^4.17.2",+ "tslib": "^2.6.2"+ },+ "engines": {+ "node": ">=18.0.0"+ }+ },+ "node_modules/@smithy/eventstream-serde-browser": {+ "version": "4.5.2",+ "resolved": "https://registry.npmjs.org/@smithy/eventstream-serde-browser/-/eventstream-serde-browser-4.5.2.tgz",+ "integrity": "sha512-HQ4l596buGUPnypSGfoYKp17GvR0sMMKyc6PQ/NHxLmh8sQjP7h3TRvy+lW/et12UN9BRPAbHJKa4d3XMMVszQ==",+ "license": "Apache-2.0",+ "dependencies": {+ "@smithy/core": "^3.33.2",+ "tslib": "^2.6.2"+ },+ "engines": {+ "node": ">=18.0.0"+ }+ },+ "node_modules/@smithy/eventstream-serde-config-resolver": {+ "version": "4.6.2",+ "resolved": "https://registry.npmjs.org/@smithy/eventstream-serde-config-resolver/-/eventstream-serde-config-resolver-4.6.2.tgz",+ "integrity": "sha512-GVWpmVKiVAvZDr3E0qRPu+A7TzeeMUctuP9SoFpzGx31lenW3Wk8zq7N97p8sJMwLCyVhXcbv5D0UTURCHdH0w==",+ "license": "Apache-2.0",+ "dependencies": {+ "@smithy/core": "^3.33.2",+ "tslib": "^2.6.2"+ },+ "engines": {+ "node": ">=18.0.0"+ }+ },+ "node_modules/@smithy/eventstream-serde-node": {+ "version": "4.5.2",+ "resolved": "https://registry.npmjs.org/@smithy/eventstream-serde-node/-/eventstream-serde-node-4.5.2.tgz",+ "integrity": "sha512-WkWkseIHXv+hr6RnrkpEOv5TOPHWLzzlOsocnPCCKsdfCOkBN7qhBn1/Pij9QZynkloJXYsQp9A5ykdIPVL2tg==",+ "license": "Apache-2.0",+ "dependencies": {+ "@smithy/core": "^3.33.2",+ "tslib": "^2.6.2"+ },+ "engines": {+ "node": ">=18.0.0"+ }+ },+ "node_modules/@smithy/fetch-http-handler": {+ "version": "5.8.0",+ "resolved": "https://registry.npmjs.org/@smithy/fetch-http-handler/-/fetch-http-handler-5.8.0.tgz",+ "integrity": "sha512-ycSJu3tFAQ4v04CBB0agqFMVsSQ1iG3yw+SpgxRqKfaURpQD4CZ8Wn0zPMmSnOuTpTh65Vz+EA0rMrw089wvkA==",+ "license": "Apache-2.0",+ "dependencies": {+ "@smithy/core": "^3.33.3",+ "@smithy/types": "^4.18.0",+ "tslib": "^2.6.2"+ },+ "engines": {+ "node": ">=18.0.0"+ }+ },+ "node_modules/@smithy/hash-blob-browser": {+ "version": "4.5.2",+ "resolved": "https://registry.npmjs.org/@smithy/hash-blob-browser/-/hash-blob-browser-4.5.2.tgz",+ "integrity": "sha512-+fx5GrWB/EElSRl/z+MQXa5RMaGH4ZH/MyZbBgH7CDE053KLD9o4kLGdrBGe8KicU/t22cHzdZs2cVwGL1yt9g==",+ "license": "Apache-2.0",+ "dependencies": {+ "@smithy/core": "^3.33.2",+ "tslib": "^2.6.2"+ },+ "engines": {+ "node": ">=18.0.0"+ }+ },+ "node_modules/@smithy/hash-node": {+ "version": "4.5.2",+ "resolved": "https://registry.npmjs.org/@smithy/hash-node/-/hash-node-4.5.2.tgz",+ "integrity": "sha512-OcD8fGClTkP0BWHVEAgUp1RZyCw8cKfqTPQ+DgrSF5jvR8zKkw2Aud79L4G/1Fu3QKLcsHExxRIPQCcKx7+xkg==",+ "license": "Apache-2.0",+ "dependencies": {+ "@smithy/core": "^3.33.2",+ "tslib": "^2.6.2"+ },+ "engines": {+ "node": ">=18.0.0"+ }+ },+ "node_modules/@smithy/hash-stream-node": {+ "version": "4.5.2",+ "resolved": "https://registry.npmjs.org/@smithy/hash-stream-node/-/hash-stream-node-4.5.2.tgz",+ "integrity": "sha512-0sx3A9RyCV8taQ1UM9P7K9JFH2bsLXhdIr85vNNXkhq7Q9TqUdm+XxGiBuInq76aA7vBdvUQFvvyBoB95DJf3Q==",+ "license": "Apache-2.0",+ "dependencies": {+ "@smithy/core": "^3.33.2",+ "tslib": "^2.6.2"+ },+ "engines": {+ "node": ">=18.0.0"+ }+ },+ "node_modules/@smithy/invalid-dependency": {+ "version": "4.5.2",+ "resolved": "https://registry.npmjs.org/@smithy/invalid-dependency/-/invalid-dependency-4.5.2.tgz",+ "integrity": "sha512-VONOgtCxIXtwXrLVZPUdxOELYpkFzNizkpbQE5CrJ/OEh12Osx+LVXsLEAF+JcvVqPODmUoOUaovlOjCQHTOow==",+ "license": "Apache-2.0",+ "dependencies": {+ "@smithy/core": "^3.33.2",+ "tslib": "^2.6.2"+ },+ "engines": {+ "node": ">=18.0.0"+ }+ },+ "node_modules/@smithy/is-array-buffer": {+ "version": "4.5.2",+ "resolved": "https://registry.npmjs.org/@smithy/is-array-buffer/-/is-array-buffer-4.5.2.tgz",+ "integrity": "sha512-ErISzsrBz6I4rREFd9l49An0nIuatPWDegdu446Hf4QU3/UTygVaBYrcGbWNOC6sbANf2eyvPun3DyI2aHV+jg==",+ "license": "Apache-2.0",+ "dependencies": {+ "@smithy/core": "^3.33.2",+ "tslib": "^2.6.2"+ },+ "engines": {+ "node": ">=18.0.0"+ }+ },+ "node_modules/@smithy/md5-js": {+ "version": "4.5.2",+ "resolved": "https://registry.npmjs.org/@smithy/md5-js/-/md5-js-4.5.2.tgz",+ "integrity": "sha512-EC8CXhy/Y3DHniNBPK63ECkYir91IpFhIbVOo/Z7y75hO3RMFY0v+b6MUPLVp0TBtTRo+A5uU73yqyrTecTJmw==",+ "license": "Apache-2.0",+ "dependencies": {+ "@smithy/core": "^3.33.2",+ "tslib": "^2.6.2"+ },+ "engines": {+ "node": ">=18.0.0"+ }+ },+ "node_modules/@smithy/middleware-content-length": {+ "version": "4.5.2",+ "resolved": "https://registry.npmjs.org/@smithy/middleware-content-length/-/middleware-content-length-4.5.2.tgz",+ "integrity": "sha512-43Ixsc2OE5rhruhc9a1vETUCmK3Yh1AIbg2+wwQUgloOIti2FgPHmPLLBkjIqx8vdmpABtsVlhazNr5TMZKJmA==",+ "license": "Apache-2.0",+ "dependencies": {+ "@smithy/core": "^3.33.2",+ "tslib": "^2.6.2"+ },+ "engines": {+ "node": ">=18.0.0"+ }+ },+ "node_modules/@smithy/middleware-endpoint": {+ "version": "4.7.2",+ "resolved": "https://registry.npmjs.org/@smithy/middleware-endpoint/-/middleware-endpoint-4.7.2.tgz",+ "integrity": "sha512-7HgK3/pQQHcD5w9lOPtK53/eDMKDp324Nd4KZ8XvxlcKHiWytuM9VwVOB2iy3rutsz/N1WNEWBkaRBayrGnuog==",+ "license": "Apache-2.0",+ "dependencies": {+ "@smithy/core": "^3.33.2",+ "tslib": "^2.6.2"+ },+ "engines": {+ "node": ">=18.0.0"+ }+ },+ "node_modules/@smithy/middleware-retry": {+ "version": "4.8.2",+ "resolved": "https://registry.npmjs.org/@smithy/middleware-retry/-/middleware-retry-4.8.2.tgz",+ "integrity": "sha512-wj0BTZ6SC7YI8hSLMbZCO1BP7k8JOuSUHjRYrZJApqNEiHL6jxaLs5Sr92EeXu5CuVzZOUCFUuewXusWxps0bQ==",+ "license": "Apache-2.0",+ "dependencies": {+ "@smithy/core": "^3.33.2",+ "tslib": "^2.6.2"+ },+ "engines": {+ "node": ">=18.0.0"+ }+ },+ "node_modules/@smithy/middleware-serde": {+ "version": "4.5.2",+ "resolved": "https://registry.npmjs.org/@smithy/middleware-serde/-/middleware-serde-4.5.2.tgz",+ "integrity": "sha512-5Qeqkw4IdmUQUGR/FRImBruFcnXiwGC8+EOVH377bonkQF66temzxM4HbCnOOQb8U/SClP1IdlFbC7CTmKux4Q==",+ "license": "Apache-2.0",+ "dependencies": {+ "@smithy/core": "^3.33.2",+ "tslib": "^2.6.2"+ },+ "engines": {+ "node": ">=18.0.0"+ }+ },+ "node_modules/@smithy/middleware-stack": {+ "version": "4.5.2",+ "resolved": "https://registry.npmjs.org/@smithy/middleware-stack/-/middleware-stack-4.5.2.tgz",+ "integrity": "sha512-db1TDSBA03WtomPMLWPy69L85vEaQbbnDHlmCYQ7hIqOdD22K+k8GlsVYdafYKaFkJaJW2OvcgcXOELGfhtptA==",+ "license": "Apache-2.0",+ "dependencies": {+ "@smithy/core": "^3.33.2",+ "tslib": "^2.6.2"+ },+ "engines": {+ "node": ">=18.0.0"+ }+ },+ "node_modules/@smithy/node-config-provider": {+ "version": "4.6.2",+ "resolved": "https://registry.npmjs.org/@smithy/node-config-provider/-/node-config-provider-4.6.2.tgz",+ "integrity": "sha512-zMrXu/O5tPa7GLtra8L4wFG6DACcXT9QV4Ay+WEAjUhXm1dVq7c/q9Qv9gkJZNLY8hmQKg08778kDcxpKNMqOA==",+ "license": "Apache-2.0",+ "dependencies": {+ "@smithy/core": "^3.33.2",+ "tslib": "^2.6.2"+ },+ "engines": {+ "node": ">=18.0.0"+ }+ },+ "node_modules/@smithy/node-http-handler": {+ "version": "4.12.1",+ "resolved": "https://registry.npmjs.org/@smithy/node-http-handler/-/node-http-handler-4.12.1.tgz",+ "integrity": "sha512-ThMkboGeONWXAelq9FvGsuJC4rOi+qyC4/zhUF58xYpxUg5sQKx2VXZYJmtNjr4dSuBJ1HeJXETQILCz3wOHvw==",+ "license": "Apache-2.0",+ "dependencies": {+ "@smithy/core": "^3.33.3",+ "@smithy/types": "^4.18.0",+ "tslib": "^2.6.2"+ },+ "engines": {+ "node": ">=18.0.0"+ }+ },+ "node_modules/@smithy/property-provider": {+ "version": "4.5.2",+ "resolved": "https://registry.npmjs.org/@smithy/property-provider/-/property-provider-4.5.2.tgz",+ "integrity": "sha512-SPJCSCCGpHf5g5b8244ig3WVKIdv2DS+X6cfmy4bpKEYo4VlLYM+bGHpHbfbmp76vegMKQBvs7DEpwQ5YuhKLA==",+ "license": "Apache-2.0",+ "dependencies": {+ "@smithy/core": "^3.33.2",+ "tslib": "^2.6.2"+ },+ "engines": {+ "node": ">=18.0.0"+ }+ },+ "node_modules/@smithy/protocol-http": {+ "version": "5.6.2",+ "resolved": "https://registry.npmjs.org/@smithy/protocol-http/-/protocol-http-5.6.2.tgz",+ "integrity": "sha512-Asd04MaxODN6FNY8EPTeCAM4kPNi3jDUAjZU0Y4F9rHvpLUrrUo7KLcxFgSthywFr6dZfIyDLIJda6jxmVTk5w==",+ "license": "Apache-2.0",+ "dependencies": {+ "@smithy/core": "^3.33.2",+ "tslib": "^2.6.2"+ },+ "engines": {+ "node": ">=18.0.0"+ }+ },+ "node_modules/@smithy/shared-ini-file-loader": {+ "version": "4.7.2",+ "resolved": "https://registry.npmjs.org/@smithy/shared-ini-file-loader/-/shared-ini-file-loader-4.7.2.tgz",+ "integrity": "sha512-XsIDj5gVG4YRxGS4n4TiBDAogPWRHXKZyor6JW/sEuaa/7BvKADe9j45jI2dPYCnYbKkLBmbZ4qN9ns0sH+kMQ==",+ "license": "Apache-2.0",+ "dependencies": {+ "@smithy/core": "^3.33.2",+ "tslib": "^2.6.2"+ },+ "engines": {+ "node": ">=18.0.0"+ }+ },+ "node_modules/@smithy/signature-v4": {+ "version": "5.7.4",+ "resolved": "https://registry.npmjs.org/@smithy/signature-v4/-/signature-v4-5.7.4.tgz",+ "integrity": "sha512-tHy0K0VtqNd5Y7Y41h0a0Lhh0L1GzC08dTWg0F7vRJWFtTENg7IZikf3wQkanYIRdb7ngoIPMTmqgUi401fEeQ==",+ "license": "Apache-2.0",+ "dependencies": {+ "@smithy/core": "^3.35.0",+ "@smithy/types": "^4.19.0",+ "tslib": "^2.6.2"+ },+ "engines": {+ "node": ">=18.0.0"+ }+ },+ "node_modules/@smithy/smithy-client": {+ "version": "4.15.2",+ "resolved": "https://registry.npmjs.org/@smithy/smithy-client/-/smithy-client-4.15.2.tgz",+ "integrity": "sha512-qweA7dHwcWmq8IN2mIGo7nAfeji1nwWBra+P3nz4R8W8yoQYE6Iy2bN33I0W3d50MN/V5EiDY/nElr4EHITsrg==",+ "license": "Apache-2.0",+ "dependencies": {+ "@smithy/core": "^3.33.2",+ "@smithy/types": "^4.17.2",+ "tslib": "^2.6.2"+ },+ "engines": {+ "node": ">=18.0.0"+ }+ },+ "node_modules/@smithy/types": {+ "version": "4.19.0",+ "resolved": "https://registry.npmjs.org/@smithy/types/-/types-4.19.0.tgz",+ "integrity": "sha512-r7jh49VJxGerfAcTQA6gXcKc+98zOp/tqRwzYjgOE+iSQsP6cEU1hq2QzbuipmP68QtYdY9wKEhiCQZIzHgZ4Q==",+ "license": "Apache-2.0",+ "dependencies": {+ "tslib": "^2.6.2"+ },+ "engines": {+ "node": ">=18.0.0"+ }+ },+ "node_modules/@smithy/url-parser": {+ "version": "4.5.2",+ "resolved": "https://registry.npmjs.org/@smithy/url-parser/-/url-parser-4.5.2.tgz",+ "integrity": "sha512-xqZcyU/YjOt9ofe8WM1y9aCaAmxel2iRiHpkT0x2BN++mRXw0M4VdxPAOtuux279JndY6wWMiOt5BJ2xmAuMYA==",+ "license": "Apache-2.0",+ "dependencies": {+ "@smithy/core": "^3.33.2",+ "tslib": "^2.6.2"+ },+ "engines": {+ "node": ">=18.0.0"+ }+ },+ "node_modules/@smithy/util-base64": {+ "version": "4.6.2",+ "resolved": "https://registry.npmjs.org/@smithy/util-base64/-/util-base64-4.6.2.tgz",+ "integrity": "sha512-wTQX1hPfElIqY6AzM/s6c4UgpMxCL4MwJ5u6340ksLPq78lur6Y+keheIDk5gMX4G3KFh4MERcDt6xhRq+ie1Q==",+ "license": "Apache-2.0",+ "dependencies": {+ "@smithy/core": "^3.33.2",+ "tslib": "^2.6.2"+ },+ "engines": {+ "node": ">=18.0.0"+ }+ },+ "node_modules/@smithy/util-body-length-browser": {+ "version": "4.5.2",+ "resolved": "https://registry.npmjs.org/@smithy/util-body-length-browser/-/util-body-length-browser-4.5.2.tgz",+ "integrity": "sha512-QyeUSin/R2nz0hXZ5ObTvhmCQomsr6+ZyHygab5AH5+fTY5xVDQeX1DFKp9uPEwOs6RW26jEn9yqq+4yqIZDrA==",+ "license": "Apache-2.0",+ "dependencies": {+ "@smithy/core": "^3.33.2",+ "tslib": "^2.6.2"+ },+ "engines": {+ "node": ">=18.0.0"+ }+ },+ "node_modules/@smithy/util-body-length-node": {+ "version": "4.5.2",+ "resolved": "https://registry.npmjs.org/@smithy/util-body-length-node/-/util-body-length-node-4.5.2.tgz",+ "integrity": "sha512-SErsW8pBKTCkFEA1RoChwW6/8JYzdcWqWDOsRP0xOtxMYsHOUMcldkcQjtujpKSy2FtlywqygCOxSKarc4TAZw==",+ "license": "Apache-2.0",+ "dependencies": {+ "@smithy/core": "^3.33.2",+ "tslib": "^2.6.2"+ },+ "engines": {+ "node": ">=18.0.0"+ }+ },+ "node_modules/@smithy/util-buffer-from": {+ "version": "2.2.0",+ "resolved": "https://registry.npmjs.org/@smithy/util-buffer-from/-/util-buffer-from-2.2.0.tgz",+ "integrity": "sha512-IJdWBbTcMQ6DA0gdNhh/BwrLkDR+ADW5Kr1aZmd4k3DIF6ezMV4R2NIAmT08wQJ3yUK82thHWmC/TnK/wpMMIA==",+ "license": "Apache-2.0",+ "dependencies": {+ "@smithy/is-array-buffer": "^2.2.0",+ "tslib": "^2.6.2"+ },+ "engines": {+ "node": ">=14.0.0"+ }+ },+ "node_modules/@smithy/util-buffer-from/node_modules/@smithy/is-array-buffer": {+ "version": "2.2.0",+ "resolved": "https://registry.npmjs.org/@smithy/is-array-buffer/-/is-array-buffer-2.2.0.tgz",+ "integrity": "sha512-GGP3O9QFD24uGeAXYUjwSTXARoqpZykHadOmA8G5vfJPK0/DC67qa//0qvqrJzL1xc8WQWX7/yc7fwudjPHPhA==",+ "license": "Apache-2.0",+ "dependencies": {+ "tslib": "^2.6.2"+ },+ "engines": {+ "node": ">=14.0.0"+ }+ },+ "node_modules/@smithy/util-config-provider": {+ "version": "4.5.2",+ "resolved": "https://registry.npmjs.org/@smithy/util-config-provider/-/util-config-provider-4.5.2.tgz",+ "integrity": "sha512-bAtInttsiHw9HX/vaNUU6Nj8pWqxMNKD0okEsjr8StgKwRdzN4mpl4/P7/en2JNCWlCyterSDOoveptct/jOGg==",+ "license": "Apache-2.0",+ "dependencies": {+ "@smithy/core": "^3.33.2",+ "tslib": "^2.6.2"+ },+ "engines": {+ "node": ">=18.0.0"+ }+ },+ "node_modules/@smithy/util-defaults-mode-browser": {+ "version": "4.6.2",+ "resolved": "https://registry.npmjs.org/@smithy/util-defaults-mode-browser/-/util-defaults-mode-browser-4.6.2.tgz",+ "integrity": "sha512-wENSdyLXVzupl1nyPK7JP/wt6Lkph/psRgocKli5NLh7O936L66FrZQ/I9HBHwZ5N0Z4MJUoj8qNdw+/6cTRgA==",+ "license": "Apache-2.0",+ "dependencies": {+ "@smithy/core": "^3.33.2",+ "tslib": "^2.6.2"+ },+ "engines": {+ "node": ">=18.0.0"+ }+ },+ "node_modules/@smithy/util-defaults-mode-node": {+ "version": "4.5.2",+ "resolved": "https://registry.npmjs.org/@smithy/util-defaults-mode-node/-/util-defaults-mode-node-4.5.2.tgz",+ "integrity": "sha512-3915rhdCibo7Do927AFV6pXxsIiaKOZGGexJ3LnT2l5CgJZi3DPqZ2ZMhYTIPjiRA3asHhPe0gaFBtxuqXC8aA==",+ "license": "Apache-2.0",+ "dependencies": {+ "@smithy/core": "^3.33.2",+ "tslib": "^2.6.2"+ },+ "engines": {+ "node": ">=18.0.0"+ }+ },+ "node_modules/@smithy/util-endpoints": {+ "version": "3.7.2",+ "resolved": "https://registry.npmjs.org/@smithy/util-endpoints/-/util-endpoints-3.7.2.tgz",+ "integrity": "sha512-16wQS3r4gXctr9/uYB0OUAUOm1LZLUKAsBeG364l64OalFwsRRvgO+AjL3OYxmxt060z1ExchX2ayrNVfM0r9Q==",+ "license": "Apache-2.0",+ "dependencies": {+ "@smithy/core": "^3.33.2",+ "tslib": "^2.6.2"+ },+ "engines": {+ "node": ">=18.0.0"+ }+ },+ "node_modules/@smithy/util-middleware": {+ "version": "4.5.2",+ "resolved": "https://registry.npmjs.org/@smithy/util-middleware/-/util-middleware-4.5.2.tgz",+ "integrity": "sha512-wmfA04AZqTwu10EWGKUu4dm/3BZfSedqlqAiQPWVr8OkwFh0MovRDBwc48Pzd2YEEjqpI0JwXVk65TBarff3wQ==",+ "license": "Apache-2.0",+ "dependencies": {+ "@smithy/core": "^3.33.2",+ "tslib": "^2.6.2"+ },+ "engines": {+ "node": ">=18.0.0"+ }+ },+ "node_modules/@smithy/util-retry": {+ "version": "4.6.2",+ "resolved": "https://registry.npmjs.org/@smithy/util-retry/-/util-retry-4.6.2.tgz",+ "integrity": "sha512-q6MXFNu+W4ZCNdNKutzDLP/Hzumd1FU9CQX++P/7ylanYIYiGhgZwSzwZWAw+G1RNcfY+RBYv61XcGlSYhj+BA==",+ "license": "Apache-2.0",+ "dependencies": {+ "@smithy/core": "^3.33.2",+ "tslib": "^2.6.2"+ },+ "engines": {+ "node": ">=18.0.0"+ }+ },+ "node_modules/@smithy/util-stream": {+ "version": "4.8.2",+ "resolved": "https://registry.npmjs.org/@smithy/util-stream/-/util-stream-4.8.2.tgz",+ "integrity": "sha512-R+S7jmu8VdbtOygMUSIGfkmOBp0SowT8+8LZdk21oXdmmKfN4G/bwN5IGIi0UH3RwWc9KJWDH1Dzm45DClyUvw==",+ "license": "Apache-2.0",+ "dependencies": {+ "@smithy/core": "^3.33.2",+ "tslib": "^2.6.2"+ },+ "engines": {+ "node": ">=18.0.0"+ }+ },+ "node_modules/@smithy/util-utf8": {+ "version": "4.5.2",+ "resolved": "https://registry.npmjs.org/@smithy/util-utf8/-/util-utf8-4.5.2.tgz",+ "integrity": "sha512-7wNWV7SugHpcMA7uzEawJNpE0GrasXM7a9E+1+Wm6NxVuDClESac/AKt+G7jMZNUz5vBLWqKlqVV7Sv7AtUr6Q==",+ "license": "Apache-2.0",+ "dependencies": {+ "@smithy/core": "^3.33.2",+ "tslib": "^2.6.2"+ },+ "engines": {+ "node": ">=18.0.0"+ }+ },+ "node_modules/@smithy/util-waiter": {+ "version": "4.6.2",+ "resolved": "https://registry.npmjs.org/@smithy/util-waiter/-/util-waiter-4.6.2.tgz",+ "integrity": "sha512-TNNK01i1HiSAR6hBF94J7q338JgEaHPrP8QKRSeQBsbSbw5O4+YGdZYitmsTeEWvHGX+2R/oQ7BzxyAjeZxuWg==",+ "license": "Apache-2.0",+ "dependencies": {+ "@smithy/core": "^3.33.2",+ "tslib": "^2.6.2"+ },+ "engines": {+ "node": ">=18.0.0"+ }+ },+ "node_modules/anynum": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/anynum/-/anynum-1.0.1.tgz",+ "integrity": "sha512-N6//FLET/tXYNM/F6ABca1oH6fWB+KlTt909Le28WMDBk8oaT4vY17DCrwg2MvmuqUKt3Ni4N5dGJ/EoBgcO6A==",+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/NaturalIntelligence"+ }+ ],+ "license": "MIT"+ },+ "node_modules/bowser": {+ "version": "2.14.1",+ "resolved": "https://registry.npmjs.org/bowser/-/bowser-2.14.1.tgz",+ "integrity": "sha512-tzPjzCxygAKWFOJP011oxFHs57HzIhOEracIgAePE4pqB3LikALKnSzUyU4MGs9/iCEUuHlAJTjTc5M+u7YEGg==",+ "license": "MIT"+ },+ "node_modules/builder-util-runtime": {+ "version": "9.7.0",+ "resolved": "https://registry.npmjs.org/builder-util-runtime/-/builder-util-runtime-9.7.0.tgz",+ "integrity": "sha512-g/kR520giAFYkSXTzcmF3kqQq7wi8F6N6SzeDgZrqTBN+VHdmgWOyTdD1yD7AATDId/yXLvuP34CxW46/BwCdw==",+ "license": "MIT",+ "dependencies": {+ "debug": "^4.3.4",+ "sax": "^1.2.4"+ },+ "engines": {+ "node": ">=12.0.0"+ }+ },+ "node_modules/debug": {+ "version": "4.4.3",+ "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",+ "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==",+ "license": "MIT",+ "dependencies": {+ "ms": "^2.1.3"+ },+ "engines": {+ "node": ">=6.0"+ },+ "peerDependenciesMeta": {+ "supports-color": {+ "optional": true+ }+ }+ },+ "node_modules/fast-xml-parser": {+ "version": "5.2.5",+ "resolved": "https://registry.npmjs.org/fast-xml-parser/-/fast-xml-parser-5.2.5.tgz",+ "integrity": "sha512-pfX9uG9Ki0yekDHx2SiuRIyFdyAr1kMIMitPvb0YBo8SUfKvia7w7FIyd/l6av85pFYRhZscS75MwMnbvY+hcQ==",+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/NaturalIntelligence"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "strnum": "^2.1.0"+ },+ "bin": {+ "fxparser": "src/cli/cli.js"+ }+ },+ "node_modules/ms": {+ "version": "2.1.3",+ "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",+ "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",+ "license": "MIT"+ },+ "node_modules/sax": {+ "version": "1.6.1",+ "resolved": "https://registry.npmjs.org/sax/-/sax-1.6.1.tgz",+ "integrity": "sha512-42tBVwLWnaQvW5zc4HbZrTuWccECCZfBi92FDuwtqxasH+JbPB3/FOKb1m222K42R4WxuxzzMsTswfzgtSu64Q==",+ "license": "BlueOak-1.0.0",+ "engines": {+ "node": ">=11.0.0"+ }+ },+ "node_modules/semver": {+ "version": "7.8.5",+ "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz",+ "integrity": "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==",+ "license": "ISC",+ "bin": {+ "semver": "bin/semver.js"+ },+ "engines": {+ "node": ">=10"+ }+ },+ "node_modules/strnum": {+ "version": "2.4.2",+ "resolved": "https://registry.npmjs.org/strnum/-/strnum-2.4.2.tgz",+ "integrity": "sha512-rDG3Ah4TV0k1hWvLSzkZtMmLN9+eS+h3knq4MP6A42Y3Yh5qGNnOUs1jJkoSr8FG5dsL28c7KgkIBzSEykqtuw==",+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/NaturalIntelligence"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "anynum": "^1.0.1"+ }+ },+ "node_modules/tslib": {+ "version": "2.8.1",+ "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz",+ "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==",+ "license": "0BSD"+ },+ "node_modules/yaml": {+ "version": "2.9.1",+ "resolved": "https://registry.npmjs.org/yaml/-/yaml-2.9.1.tgz",+ "integrity": "sha512-3NxN8+78OdzbT7C/WjGsyfPAtJaN3FNDsWxv7Y7mcDsT/oOmgW8BpyQQFFBnvZE3j9Y2Sdz1ULFLezL7Eb2yFw==",+ "license": "ISC",+ "bin": {+ "yaml": "bin.mjs"+ },+ "engines": {+ "node": ">= 14.6"+ },+ "funding": {+ "url": "https://github.com/sponsors/eemeli"+ }+ },+ "node_modules/zod": {+ "version": "4.6.5",+ "resolved": "https://registry.npmjs.org/zod/-/zod-4.6.5.tgz",+ "integrity": "sha512-v5l/aFXZQeai4awLbOpSoHecE9UiMrnfx75tEXLjNonXVARxQ5mOeipTjROUchszUNCqnE+hqAMujRsRHsut2Q==",+ "license": "MIT",+ "funding": {+ "url": "https://github.com/sponsors/colinhacks"+ }+ }+ }+}diff --git a/apps/desktop/scripts/security-policy-runtime/package.json b/apps/desktop/scripts/security-policy-runtime/package.jsonnew file mode 100644index 00000000000..9d1f486b5cb--- /dev/null+++ b/apps/desktop/scripts/security-policy-runtime/package.json@@ -0,0 +1,13 @@+{+ "name": "desktop-security-policy-runtime",+ "version": "1.0.0",+ "private": true,+ "type": "module",+ "dependencies": {+ "@aws-sdk/client-s3": "3.932.0",+ "builder-util-runtime": "9.7.0",+ "semver": "7.8.5",+ "yaml": "2.9.1",+ "zod": "4.6.5"+ }+}diff --git a/apps/desktop/scripts/shellAbi.mjs b/apps/desktop/scripts/shellAbi.mjsindex 769b561f78b..581304fd48c 100644--- a/apps/desktop/scripts/shellAbi.mjs+++ b/apps/desktop/scripts/shellAbi.mjs@@ -9,6 +9,8 @@ const ABI_FILE = 'apps/desktop/shell/abi.json';const TRACKED_INPUTS = ['apps/desktop/shell',+ 'locales/en-US/electron.json',+ 'locales/zh-CN/electron.json','apps/desktop/patches','apps/desktop/build','apps/desktop/electron-builder.mjs',@@ -20,7 +22,7 @@ const TRACKED_INPUTS = [];// set-desktop-version copies icon-<channel>.* over these before packaging; the variants stay hashed.const EXCLUDED =- /^apps\/desktop\/(?:shell\/(?:abi\.json$|__tests__\/)|build\/(?:icon\.png|icon\.ico|Icon\.icns)$)/;+ /^apps\/desktop\/(?:shell\/(?:abi\.json$|update\/strings\.json$|__tests__\/)|build\/(?:icon\.png|icon\.ico|Icon\.icns)$)/;const sha256 = (data) => createHash('sha256').update(data).digest('hex');@@ -66,7 +68,19 @@ export const shellAbiInputs = ({ root = REPO_ROOT, publicKey = '' } = {}) => {electron: pkg.devDependencies?.electron,sandbox: pkg.devDependencies?.['@anthropic-ai/sandbox-runtime'],}),- ...files.map((file) => `${sha256(read(file))} ${file}`),+ ...files.map((file) => {+ // Hash the source of the generated shell copy, not unrelated Core translations.+ const content = file.startsWith('locales/')+ ? stableJson(+ Object.fromEntries(+ Object.entries(JSON.parse(read(file))).filter(([key]) =>+ key.startsWith('startupUpdate.'),+ ),+ ),+ )+ : read(file);+ return `${sha256(content)} ${file}`;+ }),...lockEntries(read('apps/desktop/pnpm-lock.yaml').toString(),new Set(Object.keys(pkg.dependencies ?? {})),diff --git a/apps/desktop/shell/__tests__/core-loader.test.mjs b/apps/desktop/shell/__tests__/core-loader.test.mjsindex c03ebbe8df9..f7fead0426d 100644--- a/apps/desktop/shell/__tests__/core-loader.test.mjs+++ b/apps/desktop/shell/__tests__/core-loader.test.mjs@@ -526,3 +526,27 @@ describe('resolveCore', () => {expect(core.log.join('\n')).toMatch(/9\.9\.9/);});});++it('does not count time spent in the first-launch update gate as failed Core boots', () => {+ for (let i = 0; i < 5; i++) {+ const core = resolveCore({+ abi: ABI,+ builtinDir,+ publicKey: publicKeyPem,+ userData,+ deferBoot: true,+ });+ expect(core.source).toBe('builtin');+ }+ const core = resolveCore({+ abi: ABI,+ builtinDir,+ publicKey: publicKeyPem,+ userData,+ deferBoot: true,+ });+ core.startBoot();+ expect(readBoot().failures).toBe(1);+ core.markHealthy();+ expect(readBoot()).toMatchObject({ healthy: true, failures: 0 });+});diff --git a/apps/desktop/shell/__tests__/shell-main.test.mjs b/apps/desktop/shell/__tests__/shell-main.test.mjsindex 322b25030f7..4bf75d9bd1a 100644--- a/apps/desktop/shell/__tests__/shell-main.test.mjs+++ b/apps/desktop/shell/__tests__/shell-main.test.mjs@@ -9,6 +9,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';const mainPath = fileURLToPath(new URL('../main.js', import.meta.url));const loaderPath = fileURLToPath(new URL('../core-loader.js', import.meta.url));const rescuePath = fileURLToPath(new URL('../rescue/index.js', import.meta.url));+const updatePath = fileURLToPath(new URL('../update/index.js', import.meta.url));const abiPath = fileURLToPath(new URL('../abi.json', import.meta.url));const require = createRequire(mainPath);const electronPath = require.resolve('electron');@@ -23,6 +24,7 @@ const stub = (file, exports) => {};const loadMain = ({ app, electron = {}, resolveCore, runRescue = vi.fn() }) => {+ delete require.cache[updatePath];stub(electronPath, { app, ...electron });if (resolveCore) stub(loaderPath, { installShellResolver: vi.fn(), resolveCore });stub(rescuePath, { runRescue });@@ -52,6 +54,7 @@ const fakeCore = (source, body = 'module.exports = 1;') => {manifest: null,markBroken: vi.fn(),markHealthy: vi.fn(),+ startBoot: vi.fn(),source,};};@@ -69,6 +72,11 @@ beforeEach(() => {coreMain = path.join(tmp, 'core', 'dist', 'main', 'index.js');resourcesPath = process.resourcesPath;process.resourcesPath = path.join(tmp, 'resources');+ fs.mkdirSync(path.join(process.resourcesPath, 'core.asar'), { recursive: true });+ fs.writeFileSync(+ path.join(process.resourcesPath, 'core.asar/manifest.json'),+ JSON.stringify({ channel: 'stable' }),+ );});afterEach(() => {@@ -108,11 +116,84 @@ describe('shell main', () => {const { runRescue } = loadMain({ app: packagedApp(), resolveCore: () => core });expect(global.__BOOTED__).toBe(true);- expect(global.__SHELL__.markHealthy).toBe(core.markHealthy);+ global.__SHELL__.markHealthy();+ expect(core.markHealthy).toHaveBeenCalledOnce();expect(runRescue).not.toHaveBeenCalled();delete global.__BOOTED__;});+ it('starts stable boot validation without waiting for the background security check', async () => {+ const core = fakeCore('builtin');+ const resolveCore = vi.fn(({ deferBoot }) => {+ if (!deferBoot) core.startBoot();+ return core;+ });+ loadMain({ app: packagedApp(), resolveCore });+ const check = vi.fn();+ let release;+ const background = global.__SHELL__.startupUpdate.checkSecurity({+ check: () =>+ new Promise((resolve) => {+ release = resolve;+ }),+ });+ expect(resolveCore).toHaveBeenCalledWith(expect.objectContaining({ deferBoot: false }));+ expect(core.startBoot).toHaveBeenCalledOnce();+ expect(await global.__SHELL__.startupUpdate.run(check)).toBe(true);+ expect(check).not.toHaveBeenCalled();+ expect(core.startBoot).toHaveBeenCalledOnce();+ release(false);+ expect(await background).toBe(true);+ expect(core.startBoot).toHaveBeenCalledOnce();+ });++ it.each([+ ['stable', false],+ ['canary', true],+ ['beta', true],+ ])('counts early interrupted %s launches (existing: %s)', (channel, existing) => {+ const builtinDir = path.join(process.resourcesPath, 'core.asar');+ fs.writeFileSync(+ path.join(builtinDir, 'manifest.json'),+ JSON.stringify({ channel, version: '1.0.0' }),+ );+ const userData = path.join(tmp, 'userData');+ fs.mkdirSync(userData, { recursive: true });+ if (existing) fs.writeFileSync(path.join(userData, 'lobehub-settings.json'), '{}');+ // Never enter bootstrap or mark healthy, simulating interruption before App starts.+ coreMain = path.join(builtinDir, 'dist/main/index.js');+ fs.mkdirSync(path.dirname(coreMain), { recursive: true });+ fs.writeFileSync(coreMain, 'module.exports = 1;');+ delete require.cache[loaderPath];+ const { resolveCore } = require(loaderPath);+ for (let attempt = 1; attempt <= 3; attempt += 1) {+ loadMain({ app: packagedApp(), resolveCore });+ const boot = JSON.parse(fs.readFileSync(path.join(userData, 'core-ota/boot.json'), 'utf8'));+ expect(boot.failures).toBe(attempt);+ }+ const { runRescue } = loadMain({ app: packagedApp(), resolveCore });+ expect(runRescue).toHaveBeenCalledOnce();+ });++ it.each(['canary', 'beta'])(+ 'defers a fresh %s boot until the gate allows entry',+ async (channel) => {+ fs.writeFileSync(+ path.join(process.resourcesPath, 'core.asar/manifest.json'),+ JSON.stringify({ channel }),+ );+ const core = fakeCore('builtin');+ const resolveCore = vi.fn(({ deferBoot }) => {+ if (!deferBoot) core.startBoot();+ return core;+ });+ loadMain({ app: packagedApp(), electron: { net: { isOnline: () => false } }, resolveCore });+ expect(core.startBoot).not.toHaveBeenCalled();+ expect(await global.__SHELL__.startupUpdate.run(vi.fn())).toBe(true);+ expect(core.startBoot).toHaveBeenCalledOnce();+ },+ );+it('rescues in-process when the builtin core throws while loading', () => {const core = fakeCore('builtin', 'throw new Error("builtin boom");');const { runRescue } = loadMain({ app: packagedApp(), resolveCore: () => core });diff --git a/apps/desktop/shell/__tests__/startup-update.test.mjs b/apps/desktop/shell/__tests__/startup-update.test.mjsnew file mode 100644index 00000000000..2ab29bf9e1c--- /dev/null+++ b/apps/desktop/shell/__tests__/startup-update.test.mjs@@ -0,0 +1,378 @@+import { EventEmitter } from 'node:events';+import fs from 'node:fs';+import { createRequire } from 'node:module';+import os from 'node:os';+import path from 'node:path';++import { afterEach, beforeEach, expect, it, vi } from 'vitest';++const require = createRequire(import.meta.url);+const hostPlatform = process.platform;+const entry = require.resolve('../update');+const electron = require.resolve('electron');+const rescue = require.resolve('../rescue');+const sparklePath = require.resolve('../rescue/sparkle');+const updaterPath = require.resolve('../rescue/electron-updater.cjs');+let updater;+let userData, window, handler, app, online, createStartupUpdate, Window;+const flush = () => new Promise((resolve) => setTimeout(resolve, 0));+const marker = () =>+ JSON.parse(fs.readFileSync(path.join(userData, 'startup-update.json'), 'utf8'));+const action = (value) => handler({ sender: window.webContents }, value);+beforeEach(() => {+ window = undefined;+ online = true;+ userData = fs.mkdtempSync(path.join(os.tmpdir(), 'startup-update-'));+ app = Object.assign(new EventEmitter(), {+ exit: vi.fn(),+ quit: vi.fn(),+ getLocale: () => 'zh-CN',+ getPath: () => userData,+ whenReady: async () => {},+ releaseSingleInstanceLock: vi.fn(),+ relaunch: vi.fn(),+ });+ const windows = [];+ Window = class extends EventEmitter {+ static getAllWindows() {+ return windows.filter((win) => !win.isDestroyed());+ }+ constructor() {+ super();+ // eslint-disable-next-line @typescript-eslint/no-this-alias -- Expose the fake native window to the test.+ window = this;+ windows.push(this);+ this.enabled = true;+ app.emit('browser-window-created', {}, this);+ this.webContents = Object.assign(new EventEmitter(), {+ send: vi.fn(),+ setWindowOpenHandler: vi.fn(),+ });+ }+ center() {}+ isEnabled() {+ return this.enabled;+ }+ setEnabled(enabled) {+ this.enabled = enabled;+ }+ destroy() {+ this.destroyed = true;+ if (!app.emit('window-all-closed')) app.quit();+ }+ isDestroyed() {+ return this.destroyed;+ }+ async loadFile() {}+ show() {+ this.shown = true;+ }+ focus() {}+ };+ require.cache[electron] = {+ exports: {+ app,+ BrowserWindow: Window,+ nativeTheme: {},+ net: { isOnline: () => online },+ ipcMain: {+ handle: (_channel, callback) => {+ handler = callback;+ },+ removeHandler: vi.fn(),+ },+ },+ };+ require.cache[rescue] = {+ exports: {+ configureUpdater: vi.fn(),+ resolveChannel: () => 'stable',+ resolveFeedUrl: () => 'https://updates.test',+ },+ loaded: true,+ };+ updater = Object.assign(new EventEmitter(), {+ checkForUpdates: vi.fn(async () => ({+ isUpdateAvailable: true,+ updateInfo: { version: '2.0.0' },+ })),+ downloadUpdate: vi.fn(async () => {+ updater.emit('download-progress', { percent: 45 });+ }),+ quitAndInstall: vi.fn(),+ });+ require.cache[updaterPath] = { exports: { autoUpdater: updater }, loaded: true };+ require.cache[sparklePath] = { exports: { createSparkleUpdater: () => updater }, loaded: true };+ delete require.cache[entry];+ ({ createStartupUpdate } = require(entry));+});+afterEach(() => {+ Object.defineProperty(process, 'platform', { value: hostPlatform });+ for (const file of [entry, electron, rescue, updaterPath, sparklePath])+ delete require.cache[file];+ fs.rmSync(userData, { recursive: true, force: true });+});+it('keeps first launch pending until the check passes and the business renderer is healthy', async () => {+ const gate = createStartupUpdate({ userData, channel: 'canary' });+ gate.markHealthy();+ expect(marker().completed).toBe(false);+ await expect(gate.run(async () => 'ready')).resolves.toBe(true);+ expect(window.isDestroyed()).toBe(true);+ expect(app.quit).not.toHaveBeenCalled();+ expect(marker().completed).toBe(false);+ gate.markHealthy();+ expect(marker().completed).toBe(true);+ const check = vi.fn();+ await createStartupUpdate({ userData, channel: 'canary' }).run(check);+ expect(check).not.toHaveBeenCalled();+});+it('migrates existing installations without forcing them through first launch again', async () => {+ fs.writeFileSync(path.join(userData, 'lobehub-settings.json'), '{}');+ const check = vi.fn();+ await expect(createStartupUpdate({ userData, channel: 'canary' }).run(check)).resolves.toBe(true);+ expect(check).not.toHaveBeenCalled();+});+it('shows a recoverable error, ignores concurrent retries, and completes after a successful retry', async () => {+ let resume;+ const check = vi+ .fn()+ .mockRejectedValueOnce(new Error('offline'))+ .mockImplementationOnce(+ () =>+ new Promise((resolve) => {+ resume = resolve;+ }),+ );+ const result = createStartupUpdate({ userData, channel: 'canary' }).run(check);+ await flush();+ expect(action('state')).toMatchObject({ phase: 'error', language: 'zh-CN' });+ expect(window.shown).toBe(true);+ expect(marker().completed).toBe(false);+ action('retry');+ action('retry');+ expect(check).toHaveBeenCalledTimes(2);+ expect(() => handler({ sender: {} }, 'quit')).toThrow('Untrusted');+ resume('ready');+ await expect(result).resolves.toBe(true);+});+it('quits without completing first launch and retries the gate on the next launch', async () => {+ const result = createStartupUpdate({ userData, channel: 'canary' }).run(async () => {+ throw new Error('offline');+ });+ await flush();+ action('quit');+ await expect(result).resolves.toBe(false);+ expect(app.exit).toHaveBeenCalledWith(0);+ expect(createStartupUpdate({ userData, channel: 'canary' }).pending).toBe(true);+ expect(app.listenerCount('activate')).toBe(0);+});++it('uses the full installer when required and leaves first launch pending until the new app boots', async () => {+ updater.downloadUpdate.mockRejectedValueOnce(new Error('download failed'));+ const result = createStartupUpdate({ userData, channel: 'canary' }).run(+ async () => 'full-update',+ );+ await flush();+ expect(action('state').phase).toBe('error');+ expect(updater.quitAndInstall).not.toHaveBeenCalled();+ action('retry');+ await flush();+ expect(window.webContents.send).toHaveBeenCalledWith(+ 'shell:update-state',+ expect.objectContaining({ phase: 'downloading', percent: 45 }),+ );+ expect(updater.quitAndInstall).toHaveBeenCalledWith(true, true);+ expect(app.releaseSingleInstanceLock).toHaveBeenCalledOnce();+ expect(marker().completed).toBe(false);+ action('quit');+ await result;+ expect(updater.listenerCount('download-progress')).toBe(0);+});++it('opens the app without a window when first launch starts offline', async () => {+ online = false;+ const gate = createStartupUpdate({ userData, channel: 'canary' });+ const check = vi.fn();+ await expect(gate.run(check)).resolves.toBe(true);+ expect(check).not.toHaveBeenCalled();+ expect(window).toBeUndefined();+ gate.markHealthy();+ expect(marker().completed).toBe(true);+});++it('never shows the window when the check finishes quickly', async () => {+ await expect(+ createStartupUpdate({ userData, channel: 'canary' }).run(async () => 'ready'),+ ).resolves.toBe(true);+ expect(window.shown).toBeUndefined();+});++it('shows the window only once the check outlasts the delay', async () => {+ vi.useFakeTimers();+ try {+ let resume;+ const result = createStartupUpdate({ userData, channel: 'canary' }).run(+ () =>+ new Promise((resolve) => {+ resume = resolve;+ }),+ );+ await vi.advanceTimersByTimeAsync(599);+ expect(window.shown).toBeUndefined();+ await vi.advanceTimersByTimeAsync(1);+ expect(window.shown).toBe(true);+ resume('ready');+ await expect(result).resolves.toBe(true);+ } finally {+ vi.useRealTimers();+ }+});++it('opens the app instead of an error when the network drops during the update', async () => {+ const gate = createStartupUpdate({ userData, channel: 'canary' });+ const result = gate.run(async () => {+ online = false;+ throw new Error('net::ERR_INTERNET_DISCONNECTED');+ });+ await expect(result).resolves.toBe(true);+ expect(window.isDestroyed()).toBe(true);+ gate.markHealthy();+ expect(marker().completed).toBe(true);+});++for (const channel of ['stable', 'nightly']) {+ it(`skips the first-launch OTA gate for a ${channel} installer`, async () => {+ const check = vi.fn();+ const gate = createStartupUpdate({ userData, channel });+ await expect(gate.run(check)).resolves.toBe(true);+ expect(check).not.toHaveBeenCalled();+ expect(window).toBeUndefined();+ });+}+it('lets Stable enter while a delayed security fetch is still pending, then forces the update', async () => {+ let finishCheck;+ const security = {+ check: vi+ .fn()+ .mockImplementationOnce(+ () =>+ new Promise((resolve) => {+ finishCheck = resolve;+ }),+ )+ .mockResolvedValue(true),+ isInstallerSafe: () => true,+ };+ const gate = createStartupUpdate({ userData, channel: 'stable' });+ const check = vi.fn();+ await expect(gate.run(check)).resolves.toBe(true);+ const business = new Window();+ const background = gate.checkSecurity(security);+ expect(gate.checkSecurity(security)).toBe(background);+ await flush();+ expect(window).toBe(business);+ expect(business.isEnabled()).toBe(true);+ expect(check).not.toHaveBeenCalled();+ finishCheck(true);+ await flush();+ expect(window).not.toBe(business);+ expect(business.isEnabled()).toBe(false);+ expect(action('state').reason).toBe('required');+ action('quit');+ await expect(background).resolves.toBe(false);+});++it('keeps business windows interactive when the background policy does not match', async () => {+ const business = new Window();+ await createStartupUpdate({ userData, channel: 'stable' }).checkSecurity({+ check: async () => false,+ isInstallerSafe: () => true,+ });+ expect(window).toBe(business);+ expect(business.isEnabled()).toBe(true);+});++it('exits if the mandatory update window cannot load after a confirmed match', async () => {+ vi.spyOn(Window.prototype, 'loadFile').mockRejectedValueOnce(new Error('missing update UI'));+ const result = await createStartupUpdate({ userData, channel: 'stable' }).checkSecurity({+ check: async () => true,+ isInstallerSafe: () => true,+ });+ expect(result).toBe(false);+ expect(app.exit).toHaveBeenCalledWith(1);+});++it('blocks existing and newly created windows until a newer policy revokes the restriction', async () => {+ const business = new Window();+ const alreadyDisabled = new Window();+ alreadyDisabled.setEnabled(false);+ const security = {+ check: vi.fn().mockResolvedValueOnce(true).mockResolvedValueOnce(true).mockResolvedValue(false),+ isInstallerSafe: () => true,+ };+ updater.checkForUpdates.mockRejectedValueOnce(new Error('unavailable'));+ const result = createStartupUpdate({ userData, channel: 'stable' }).checkSecurity(security);+ await flush();+ const requiredWindow = window;+ const newBusiness = new Window();+ expect(business.isEnabled()).toBe(false);+ expect(newBusiness.isEnabled()).toBe(false);+ expect(requiredWindow.isEnabled()).toBe(true);+ window = requiredWindow;+ action('retry');+ await expect(result).resolves.toBe(true);+ expect(business.isEnabled()).toBe(true);+ expect(newBusiness.isEnabled()).toBe(true);+ expect(alreadyDisabled.isEnabled()).toBe(false);+ expect(app.listenerCount('browser-window-created')).toBe(0);+});+for (const channel of ['stable', 'canary']) {+ it.each(['darwin', 'win32', 'linux'])(+ `requires a safe full installer for an existing ${channel} installation on %s`,+ async (platform) => {+ Object.defineProperty(process, 'platform', { value: platform });+ fs.writeFileSync(path.join(userData, 'startup-update.json'), '{"completed":true}');+ const check = vi.fn();+ const security = { check: vi.fn(async () => true), isInstallerSafe: (v) => v === '2.0.0' };+ updater.checkForUpdates.mockResolvedValueOnce({+ isUpdateAvailable: true,+ updateInfo: { version: '1.0.0' },+ });+ const result = createStartupUpdate({ userData, channel }).checkSecurity(security);+ await flush();+ expect(action('state')).toMatchObject({ reason: 'required', phase: 'error' });+ expect(updater.downloadUpdate).not.toHaveBeenCalled();+ expect(updater.quitAndInstall).not.toHaveBeenCalled();+ expect(check).not.toHaveBeenCalled();+ action('retry');+ await flush();+ expect(updater.quitAndInstall).toHaveBeenCalledOnce();+ action('quit');+ await expect(result).resolves.toBe(false);+ },+ );+}+it('cannot bypass a known security restriction by going offline', async () => {+ online = false;+ updater.checkForUpdates.mockRejectedValue(new Error('offline'));+ const result = createStartupUpdate({ userData, channel: 'stable' }).checkSecurity({+ check: async () => true,+ isInstallerSafe: () => true,+ });+ await flush();+ expect(action('state')).toMatchObject({ reason: 'required', phase: 'error' });+ expect(window.isDestroyed()).toBeFalsy();+ action('quit');+ await expect(result).resolves.toBe(false);+});+it('allows entry when a newer policy revokes the restriction on retry', async () => {+ const security = {+ check: vi.fn().mockResolvedValueOnce(true).mockResolvedValueOnce(true).mockResolvedValue(false),+ isInstallerSafe: () => true,+ };+ updater.checkForUpdates.mockRejectedValueOnce(new Error('unavailable'));+ const result = createStartupUpdate({ userData, channel: 'stable' }).checkSecurity(security);+ await flush();+ action('retry');+ await expect(result).resolves.toBe(true);+});diff --git a/apps/desktop/shell/core-loader.js b/apps/desktop/shell/core-loader.jsindex bbe2bbbcf98..17f07786a19 100644--- a/apps/desktop/shell/core-loader.js+++ b/apps/desktop/shell/core-loader.js@@ -78,7 +78,14 @@ const verifyCandidate = (dir, { abi, builtinHashes, publicKey, storeDir }) => {return manifest;};-function resolveCore({ userData, builtinDir, abi, publicKey, platform = process.platform }) {+function resolveCore({+ userData,+ builtinDir,+ abi,+ publicKey,+ deferBoot = false,+ platform = process.platform,+}) {const otaRoot = path.join(userData, 'core-ota');const bootFile = path.join(otaRoot, 'boot.json');const pointerFile = path.join(otaRoot, 'pointer.json');@@ -210,8 +217,9 @@ function resolveCore({ userData, builtinDir, abi, publicKey, platform = process.break;}const healthy = boot.version === version && boot.healthy === true;- writeJson(bootFile, { failures: failures + 1, healthy, version });- return { dir, log, manifest, ...bootMarkers(version), source: 'external' };+ const startBoot = () => writeJson(bootFile, { failures: failures + 1, healthy, version });+ if (!deferBoot) startBoot();+ return { dir, log, manifest, ...bootMarkers(version), source: 'external', startBoot };} catch (error) {log.push(`core ${version} rejected: ${error.message}`);}@@ -224,22 +232,26 @@ function resolveCore({ userData, builtinDir, abi, publicKey, platform = process.log.push(`${builtinKey} failed ${builtinFailures} boots`);return { dir: builtinDir, log, manifest: builtinManifest, source: 'rescue' };}- try {- fs.mkdirSync(otaRoot, { recursive: true });- writeJson(bootFile, {- failures: builtinFailures + 1,- healthy: boot.version === builtinKey && boot.healthy === true,- version: builtinKey,- });- } catch (error) {- log.push(`builtin boot count failed: ${error.message}`);- }+ const startBoot = () => {+ try {+ fs.mkdirSync(otaRoot, { recursive: true });+ writeJson(bootFile, {+ failures: builtinFailures + 1,+ healthy: boot.version === builtinKey && boot.healthy === true,+ version: builtinKey,+ });+ } catch (error) {+ log.push(`builtin boot count failed: ${error.message}`);+ }+ };+ if (!deferBoot) startBoot();return {dir: builtinDir,log,manifest: builtinManifest,...bootMarkers(builtinKey),source: 'builtin',+ startBoot,};}diff --git a/apps/desktop/shell/main.js b/apps/desktop/shell/main.jsindex 5c0a9e16d1d..c4526ba7699 100644--- a/apps/desktop/shell/main.js+++ b/apps/desktop/shell/main.js@@ -61,11 +61,18 @@ try {};const abi = loadAbi();+ const startupUpdate = app.isPackaged+ ? require('./update').createStartupUpdate({+ channel: require(path.join(builtinDir, 'manifest.json')).channel,+ userData: app.getPath('userData'),+ })+ : undefined;core = app.isPackaged? resolveCore({abi: abi.shellAbi,builtinDir,+ deferBoot: startupUpdate.pending,publicKey: abi.publicKey,userData: app.getPath('userData'),})@@ -87,10 +94,27 @@ try {coreProtocol: 4,log: core.log,manifest: core.manifest,- markHealthy: core.markHealthy ?? (() => {}),+ markHealthy: () => {+ core.markHealthy?.();+ startupUpdate?.markHealthy();+ },publicKey: abi.publicKey,shellVersion: abi.shellVersion,source: core.source,+ startupUpdate: startupUpdate && {+ pending: startupUpdate.pending,+ checkSecurity: startupUpdate.checkSecurity,+ run: async (check) => {+ try {+ const ready = await startupUpdate.run(check);+ if (ready && startupUpdate.pending) core.startBoot();+ return ready;+ } catch (error) {+ rescue(error, core.log);+ return false;+ }+ },+ },};} catch (error) {rescue(error, core?.log);diff --git a/apps/desktop/shell/rescue/sparkle.js b/apps/desktop/shell/rescue/sparkle.jsindex 1c41a5400e6..ed0c586faff 100644--- a/apps/desktop/shell/rescue/sparkle.js+++ b/apps/desktop/shell/rescue/sparkle.js@@ -69,6 +69,7 @@ function createSparkleUpdater({ app, feedUrl, resourcesPath }) {rejectDownload = reject;}),on: events.on.bind(events),+ removeListener: events.removeListener.bind(events),quitAndInstall: () => bridge.installUpdateNow(),};}diff --git a/apps/desktop/shell/update/index.html b/apps/desktop/shell/update/index.htmlnew file mode 100644index 00000000000..7b273beffa8--- /dev/null+++ b/apps/desktop/shell/update/index.html@@ -0,0 +1,34 @@+<!doctype html>+<html lang="en">+<head>+<meta charset="utf-8" />+<meta name="viewport" content="width=device-width, initial-scale=1" />+<meta http-equiv="Content-Security-Policy" content="default-src 'none'; script-src 'self'; style-src 'self'; img-src 'self'; connect-src 'none'" />+<title>LobeHub</title>+<link rel="stylesheet" href="style.css" />+<script src="renderer.js" defer></script>+</head>+<body>+<div class="drag-bar" aria-hidden="true"></div>+<main aria-busy="true">+<svg+ class="brand"+ fill="currentColor"+ fill-rule="evenodd"+ viewBox="0 0 940 320"+ xmlns="http://www.w3.org/2000/svg"+ >+ <title>LobeHub</title>+ <path+ d="M15 240.035V87.172h39.24V205.75h66.192v34.285H15zM183.731 242c-11.759 0-22.196-2.621-31.313-7.862-9.116-5.241-16.317-12.447-21.601-21.619-5.153-9.317-7.729-19.945-7.729-31.883 0-11.937 2.576-22.492 7.729-31.664 5.164-8.963 12.159-15.98 20.982-21.05l.619-.351c9.117-5.241 19.554-7.861 31.313-7.861s22.196 2.62 31.313 7.861c9.248 5.096 16.449 12.229 21.601 21.401 5.153 9.172 7.729 19.727 7.729 31.664 0 11.938-2.576 22.566-7.729 31.883-5.152 9.172-12.353 16.378-21.601 21.619-9.117 5.241-19.554 7.862-31.313 7.862zm0-32.975c4.36 0 8.191-1.092 11.494-3.275 3.436-2.184 6.144-5.387 8.126-9.609 1.982-4.367 2.973-9.536 2.973-15.505 0-5.968-.991-10.991-2.973-15.067-1.906-4.06-4.483-7.177-7.733-9.352l-.393-.257c-3.303-2.184-7.134-3.276-11.494-3.276-4.228 0-8.059 1.092-11.495 3.276-3.303 2.184-6.011 5.387-8.125 9.609-1.982 4.076-2.973 9.099-2.973 15.067 0 5.969.991 11.138 2.973 15.505 2.114 4.222 4.822 7.425 8.125 9.609 3.436 2.183 7.267 3.275 11.495 3.275zM295.508 78l-.001 54.042a34.071 34.071 0 016.541-5.781c6.474-4.367 14.269-6.551 23.385-6.551 9.777 0 18.629 2.475 26.557 7.424 7.872 4.835 14.105 11.684 18.7 20.546l.325.637c4.756 9.026 7.135 19.799 7.135 32.319 0 12.666-2.379 23.585-7.135 32.757-4.624 9.026-10.966 16.087-19.025 21.182-7.928 4.95-16.78 7.425-26.557 7.425-9.644 0-17.704-2.184-24.178-6.551-2.825-1.946-5.336-4.355-7.532-7.226l.001 11.812h-35.87V78h37.654zm21.998 74.684c-4.228 0-8.059 1.092-11.494 3.276-3.303 2.184-6.012 5.387-8.126 9.609-1.982 4.076-2.972 9.099-2.972 15.067 0 5.969.99 11.138 2.972 15.505 2.114 4.222 4.823 7.425 8.126 9.609 3.435 2.183 7.266 3.275 11.494 3.275s7.994-1.092 11.297-3.275c3.435-2.184 6.143-5.387 8.125-9.609 2.114-4.367 3.171-9.536 3.171-15.505 0-5.968-1.057-10.991-3.171-15.067-1.906-4.06-4.483-7.177-7.732-9.352l-.393-.257c-3.303-2.184-7.069-3.276-11.297-3.276zm105.335 38.653l.084.337a27.857 27.857 0 002.057 5.559c2.246 4.222 5.417 7.498 9.513 9.827 4.096 2.184 8.984 3.276 14.665 3.276 5.285 0 9.777-.801 13.477-2.403 3.579-1.632 7.1-4.025 10.564-7.182l.732-.679 19.818 22.711c-5.153 6.26-11.494 11.064-19.025 14.413-7.531 3.203-16.449 4.804-26.755 4.804-12.683 0-23.782-2.621-33.294-7.862-9.381-5.386-16.713-12.665-21.998-21.837-5.153-9.317-7.729-19.872-7.729-31.665 0-11.792 2.51-22.274 7.53-31.446 5.036-9.105 11.902-16.195 20.596-21.268l.61-.351c8.984-5.241 19.091-7.861 30.322-7.861 10.311 0 19.743 2.286 28.294 6.859l.64.347c8.72 4.659 15.656 11.574 20.809 20.746 5.153 9.172 7.729 20.309 7.729 33.411 0 1.294-.052 2.761-.156 4.4l-.042.623-.17 2.353c-.075 1.01-.151 1.973-.227 2.888h-78.044zm21.365-42.147c-4.492 0-8.456 1.092-11.891 3.276-3.303 2.184-5.879 5.314-7.729 9.39a26.04 26.04 0 00-1.117 2.79 30.164 30.164 0 00-1.121 4.499l-.058.354h43.96l-.015-.106c-.401-2.638-1.122-5.055-2.163-7.252l-.246-.503c-1.776-3.774-4.282-6.742-7.519-8.906l-.409-.266c-3.303-2.184-7.2-3.276-11.692-3.276zm111.695-62.018l-.001 57.432h53.51V87.172h39.24v152.863h-39.24v-59.617H555.9l.001 59.617h-39.24V87.172h39.24zM715.766 242c-8.72 0-16.581-1.893-23.583-5.678-6.87-3.785-12.287-9.681-16.251-17.688-3.832-8.153-5.747-18.417-5.747-30.791v-66.168h37.654v59.398c0 9.172 1.519 15.723 4.558 19.654 3.171 3.931 7.597 5.896 13.278 5.896 3.7 0 7.069-.946 10.108-2.839 3.038-1.892 5.483-4.877 7.332-8.953 1.85-4.222 2.775-9.609 2.775-16.16v-56.996h37.654v118.36h-35.871l.004-12.38c-2.642 3.197-5.682 5.868-9.12 8.012-7.002 4.222-14.599 6.333-22.791 6.333zM841.489 78l-.001 54.041a34.1 34.1 0 016.541-5.78c6.474-4.367 14.269-6.551 23.385-6.551 9.777 0 18.629 2.475 26.556 7.424 7.873 4.835 14.106 11.684 18.701 20.546l.325.637c4.756 9.026 7.134 19.799 7.134 32.319 0 12.666-2.378 23.585-7.134 32.757-4.624 9.026-10.966 16.087-19.026 21.182-7.927 4.95-16.779 7.425-26.556 7.425-9.645 0-17.704-2.184-24.178-6.551-2.825-1.946-5.336-4.354-7.531-7.224v11.81h-35.87V78h37.654zm21.998 74.684c-4.228 0-8.059 1.092-11.495 3.276-3.303 2.184-6.011 5.387-8.125 9.609-1.982 4.076-2.973 9.099-2.973 15.067 0 5.969.991 11.138 2.973 15.505 2.114 4.222 4.822 7.425 8.125 9.609 3.436 2.183 7.267 3.275 11.495 3.275 4.228 0 7.993-1.092 11.296-3.275 3.435-2.184 6.144-5.387 8.126-9.609 2.114-4.367 3.171-9.536 3.171-15.505 0-5.968-1.057-10.991-3.171-15.067-1.906-4.06-4.484-7.177-7.733-9.352l-.393-.257c-3.303-2.184-7.068-3.276-11.296-3.276z"+ />+ </svg>+<div class="required" id="required" hidden><h1 id="title"></h1><p id="description"></p></div>+<div class="status" role="status" aria-live="polite"><span id="status"></span><span id="amount"></span></div>+<div class="slot">+<progress id="progress" aria-label="Update progress"></progress>+<div id="actions" hidden><button id="quit" class="secondary" type="button"></button><button id="retry" type="button"></button></div>+</div>+</main>+</body>+</html>diff --git a/apps/desktop/shell/update/index.js b/apps/desktop/shell/update/index.jsnew file mode 100644index 00000000000..2df9e624f4e--- /dev/null+++ b/apps/desktop/shell/update/index.js@@ -0,0 +1,257 @@+const fs = require('node:fs');+const path = require('node:path');+const { app, BrowserWindow, ipcMain, nativeTheme, net } = require('electron');++const { configureUpdater, resolveChannel, resolveFeedUrl } = require('../rescue');++const ACTION = 'shell:update-action';+const STATE = 'shell:update-state';+const SHOW_DELAY = 600;++// This runs in the synchronous shell boot chain, before Core creates its settings file.+function createStartupUpdate({ userData, channel }) {+ const marker = path.join(userData, 'startup-update.json');+ let pending;+ try {+ pending = JSON.parse(fs.readFileSync(marker, 'utf8')).completed !== true;+ } catch (error) {+ if (error.code !== 'ENOENT') throw error;+ pending = !fs.existsSync(path.join(userData, 'lobehub-settings.json'));+ fs.mkdirSync(userData, { recursive: true });+ fs.writeFileSync(marker, JSON.stringify({ completed: !pending }));+ }+ pending = pending && (channel === 'canary' || channel === 'beta');+ let approved = false;+ let securityCheck;+ return {+ pending,+ run: async (check) => {+ if (!pending) return true;+ await app.whenReady();+ // Offline first launch opens the app; Core's background check picks the update up later.+ approved = !net.isOnline() || (await runUpdateWindow({ check, reason: 'first-launch' }));+ return approved;+ },+ checkSecurity: (security) => {+ if (securityCheck) return securityCheck;+ securityCheck = (async () => {+ if (!(await security.check())) return true;+ try {+ return await runUpdateWindow({+ check: async () => ((await security.check()) ? 'full-update' : 'ready'),+ reason: 'required',+ updateChannel: channel === 'beta' ? 'canary' : channel,+ validateInstaller: security.isInstallerSafe,+ });+ } catch (error) {+ // A known restriction cannot be bypassed by a failure to create its window.+ console.error('[shell:update] Cannot display required update', error);+ app.exit(1);+ return false;+ }+ })().finally(() => {+ securityCheck = undefined;+ });+ return securityCheck;+ },+ markHealthy: () => {+ if (!pending || !approved) return;+ fs.writeFileSync(`${marker}.tmp`, JSON.stringify({ completed: true }));+ fs.renameSync(`${marker}.tmp`, marker);+ pending = false;+ },+ };+}++// Security updates share this surface, but can never use the offline first-launch bypass.+async function runUpdateWindow({ check, reason, updateChannel, validateInstaller }) {+ await app.whenReady();+ const win = new BrowserWindow({+ autoHideMenuBar: true,+ backgroundColor: nativeTheme.shouldUseDarkColors ? '#141414' : '#fafafa',+ height: 300,+ maximizable: false,+ minimizable: false,+ resizable: false,+ show: false,+ title: 'LobeHub',+ titleBarStyle: 'hidden',+ webPreferences: {+ contextIsolation: true,+ nodeIntegration: false,+ preload: path.join(__dirname, 'preload.js'),+ sandbox: true,+ },+ width: 420,+ });+ win.center();+ const focus = () => {+ if (!win.isDestroyed()) {+ win.show();+ win.focus();+ }+ };+ // A background security result can arrive after several business windows are open.+ // Keep all of them non-interactive until the restriction is revoked or the app exits.+ const disabledWindows = new Map();+ const disableWindow = (_event, other) => {+ if (other === win || other.isDestroyed() || disabledWindows.has(other)) return;+ disabledWindows.set(other, other.isEnabled());+ other.setEnabled(false);+ other.on('focus', focus);+ };+ if (reason === 'required') {+ BrowserWindow.getAllWindows().forEach((other) => disableWindow(undefined, other));+ app.on('browser-window-created', disableWindow);+ }+ app.on('activate', focus);+ app.on('second-instance', focus);+ win.webContents.setWindowOpenHandler(() => ({ action: 'deny' }));+ win.webContents.on('will-navigate', (event) => event.preventDefault());+ const language = app.getLocale().startsWith('zh') ? 'zh-CN' : 'en-US';+ const strings = require('./strings.json')[language];+ let state = { language, phase: 'checking', reason, strings };+ const update = (next) => {+ state = { language, reason, strings, ...next };+ if (!win.isDestroyed()) win.webContents.send(STATE, state);+ };+ let busy = false;+ let installing = false;+ let allowClose = false;+ let updater;+ let settled;+ const result = new Promise((resolve) => {+ settled = resolve;+ });+ const quit = () => {+ settled(false);+ app.exit(0);+ };+ win.on('close', (event) => {+ if (allowClose || installing) return;+ event.preventDefault();+ quit();+ });+ const finish = () => {+ // Keep Electron alive across the gap before Core creates its first window.+ app.once('window-all-closed', () => {});+ allowClose = true;+ settled(true);+ if (!win.isDestroyed()) win.destroy();+ };+ const fail = (error) => {+ installing = false;+ busy = false;+ if (reason === 'first-launch' && !net.isOnline()) {+ console.warn('[shell:update] Network lost, opening LobeHub', error);+ finish();+ return;+ }+ console.error('[shell:update] Update failed', error);+ update({ phase: 'error' });+ focus();+ };+ const onDownload = ({ percent }) => update({ phase: 'downloading', percent });+ const onInstallError = (error) => {+ if (installing) fail(error);+ };+ const attempt = async () => {+ if (busy) return;+ busy = true;+ update({ phase: 'checking' });+ try {+ const outcome = await check(update);+ if (win.isDestroyed()) return;+ if (outcome === 'ready') {+ finish();+ } else if (outcome === 'relaunch') {+ update({ phase: 'applying' });+ app.releaseSingleInstanceLock();+ app.relaunch(+ process.env.APPIMAGE+ ? { args: process.argv.slice(1), execPath: process.env.APPIMAGE }+ : { args: process.argv.slice(1) },+ );+ app.exit(0);+ } else if (outcome === 'full-update') {+ if (!updater) {+ const channel =+ updateChannel ??+ resolveChannel({+ resourcesPath: process.resourcesPath,+ userData: app.getPath('userData'),+ });+ const feedUrl = resolveFeedUrl({ channel, resourcesPath: process.resourcesPath });+ if (process.platform === 'darwin') {+ updater = require('../rescue/sparkle').createSparkleUpdater({+ app,+ feedUrl,+ resourcesPath: process.resourcesPath,+ });+ } else {+ updater = require('../rescue/electron-updater.cjs').autoUpdater;+ configureUpdater(updater, { channel, feedUrl, logger: console });+ }+ updater.on('download-progress', onDownload);+ updater.on('error', onInstallError);+ }+ let timeout;+ const found = await Promise.race([+ updater.checkForUpdates(),+ new Promise((_, reject) => {+ timeout = setTimeout(() => reject(new Error('Installer check timed out')), 30000);+ }),+ ]).finally(() => clearTimeout(timeout));+ if (!found?.isUpdateAvailable)+ throw new Error('A compatible installer is not available yet');+ if (validateInstaller && !validateInstaller(found.updateInfo?.version)) {+ throw new Error('The available installer does not satisfy the security policy');+ }+ update({ phase: 'downloading' });+ await updater.downloadUpdate();+ update({ phase: 'applying' });+ installing = true;+ app.releaseSingleInstanceLock();+ updater.quitAndInstall(true, true);+ } else {+ throw new Error(`Unexpected update outcome: ${outcome}`);+ }+ } catch (error) {+ fail(error);+ }+ };+ ipcMain.handle(ACTION, (event, action) => {+ if (event.sender !== win.webContents) throw new Error('Untrusted update window');+ if (action === 'state') return state;+ if (action === 'retry') {+ void attempt();+ return;+ }+ if (action === 'quit') quit();+ });+ let showTimer;+ try {+ await win.loadFile(path.join(__dirname, 'index.html'));+ void attempt();+ showTimer = setTimeout(focus, reason === 'required' ? 0 : SHOW_DELAY);+ return await result;+ } finally {+ clearTimeout(showTimer);+ app.removeListener('activate', focus);+ app.removeListener('second-instance', focus);+ ipcMain.removeHandler(ACTION);+ app.removeListener('browser-window-created', disableWindow);+ for (const [other, enabled] of disabledWindows) {+ other.removeListener('focus', focus);+ if (!other.isDestroyed()) other.setEnabled(enabled);+ }+ updater?.removeListener('download-progress', onDownload);+ updater?.removeListener('error', onInstallError);+ if (!win.isDestroyed()) {+ allowClose = true;+ win.destroy();+ }+ }+}++module.exports = { createStartupUpdate, runUpdateWindow };diff --git a/apps/desktop/shell/update/preload.js b/apps/desktop/shell/update/preload.jsnew file mode 100644index 00000000000..031760d9347--- /dev/null+++ b/apps/desktop/shell/update/preload.js@@ -0,0 +1,10 @@+const { contextBridge, ipcRenderer } = require('electron');++contextBridge.exposeInMainWorld('updateWindow', {+ onState: (callback) => {+ ipcRenderer.on('shell:update-state', (_event, state) => callback(state));+ ipcRenderer.invoke('shell:update-action', 'state').then(callback);+ },+ quit: () => ipcRenderer.invoke('shell:update-action', 'quit'),+ retry: () => ipcRenderer.invoke('shell:update-action', 'retry'),+});diff --git a/apps/desktop/shell/update/renderer.js b/apps/desktop/shell/update/renderer.jsnew file mode 100644index 00000000000..2c0b2f49ab3--- /dev/null+++ b/apps/desktop/shell/update/renderer.js@@ -0,0 +1,51 @@+const required = document.getElementById('required');+const title = document.getElementById('title');+const description = document.getElementById('description');+const status = document.getElementById('status');+const amount = document.getElementById('amount');+const progress = document.getElementById('progress');+const actions = document.getElementById('actions');+const retry = document.getElementById('retry');+const quit = document.getElementById('quit');+let previousPhase;+// The window stays hidden until the check outlasts its delay; play the draw-in when it appears.+const enter = () => {+ if (document.visibilityState !== 'visible') return;+ document.body.classList.add('enter');+ document.removeEventListener('visibilitychange', enter);+};+document.addEventListener('visibilitychange', enter);+enter();+window.updateWindow.onState((state) => {+ const t = state.strings;+ const error = state.phase === 'error';+ document.documentElement.lang = state.language;+ document.body.dataset.phase = state.phase;+ document.querySelector('main').setAttribute('aria-busy', String(!error));+ required.hidden = state.reason !== 'required';+ title.textContent = t.requiredTitle;+ description.textContent = t.requiredDescription;+ status.textContent = t[state.phase];+ amount.textContent = '';+ progress.removeAttribute('value');+ progress.setAttribute('aria-label', t[state.phase] || t.downloading);+ progress.hidden = error;+ actions.hidden = !error;+ retry.textContent = t.retry;+ quit.textContent = t.quit;+ if (state.phase === 'downloading') {+ const percent =+ state.percent ?? (state.total > 0 ? (state.received / state.total) * 100 : undefined);+ if (Number.isFinite(percent)) {+ progress.max = 100;+ progress.value = Math.max(0, Math.min(100, percent));+ amount.textContent = `${Math.floor(progress.value)}%`;+ } else if (state.received > 0) {+ amount.textContent = `${(state.received / 1024 / 1024).toFixed(1)} MB`;+ }+ }+ if (error && previousPhase !== 'error') retry.focus();+ previousPhase = state.phase;+});+retry.addEventListener('click', () => window.updateWindow.retry());+quit.addEventListener('click', () => window.updateWindow.quit());diff --git a/apps/desktop/shell/update/strings.json b/apps/desktop/shell/update/strings.jsonnew file mode 100644index 00000000000..da667d91189--- /dev/null+++ b/apps/desktop/shell/update/strings.json@@ -0,0 +1,22 @@+{+ "en-US": {+ "requiredTitle": "Update required",+ "requiredDescription": "This version has a security issue. Update to continue.",+ "checking": "Checking for updates…",+ "downloading": "Downloading update",+ "applying": "Restarting LobeHub…",+ "error": "Couldn’t finish the update",+ "retry": "Retry",+ "quit": "Quit"+ },+ "zh-CN": {+ "requiredTitle": "需要更新才能继续",+ "requiredDescription": "当前版本存在安全问题,请完成更新后继续使用。",+ "checking": "正在检查更新…",+ "downloading": "正在下载更新",+ "applying": "正在重新打开 LobeHub…",+ "error": "暂时无法完成更新",+ "retry": "重试",+ "quit": "退出"+ }+}diff --git a/apps/desktop/shell/update/style.css b/apps/desktop/shell/update/style.cssnew file mode 100644index 00000000000..d710a78894c--- /dev/null+++ b/apps/desktop/shell/update/style.css@@ -0,0 +1,32 @@+:root { color-scheme: light dark; --background: #fafafa; --foreground: #1f1f1f; --muted: #6e6e6e; --track: #e6e6e6; --border: rgba(0, 0, 0, .12); }+* { box-sizing: border-box; }+body { margin: 0; background: var(--background); color: var(--foreground); font: 13px/1.5 -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif; overflow: hidden; }+.drag-bar { position: fixed; inset: 0 0 auto; height: 36px; -webkit-app-region: drag; }+main { height: 100vh; display: grid; place-content: center; justify-items: center; padding: 24px 32px 12px; text-align: center; }+.brand { display: block; width: 120px; height: 41px; overflow: visible; }+.brand path { stroke: currentColor; stroke-width: .25em; stroke-dasharray: 1000; stroke-opacity: 0; }+.enter .brand path { animation: draw 1.4s cubic-bezier(.4, 0, .2, 1) both; }+[data-phase="error"] .brand { opacity: .28; }+.required { margin-top: 18px; display: grid; gap: 2px; }+h1 { margin: 0; font-size: 14px; font-weight: 600; letter-spacing: -.2px; }+p { margin: 0; color: var(--muted); font-size: 12px; }+.status { height: 20px; margin-top: 22px; display: flex; gap: 6px; justify-content: center; color: var(--muted); font-size: 12px; font-variant-numeric: tabular-nums; white-space: nowrap; }+.required:not([hidden]) + .status { margin-top: 10px; }+#amount { color: var(--foreground); font-weight: 500; }+[data-phase="error"] .status { color: var(--foreground); font-weight: 500; }+.slot { height: 30px; margin-top: 10px; display: grid; place-items: center; }+progress { display: block; width: 200px; height: 3px; border: 0; border-radius: 3px; overflow: hidden; appearance: none; background: var(--track); }+progress::-webkit-progress-bar { background: var(--track); }+progress::-webkit-progress-value { background: var(--foreground); border-radius: 3px; transition: width .25s linear; }+progress:not([value]) { background: linear-gradient(90deg, var(--track) 0 35%, var(--foreground) 50%, var(--track) 65% 100%); background-size: 250% 100%; animation: loading 1.3s ease-in-out infinite; }+progress:not([value])::-webkit-progress-bar { background: transparent; }+#actions { display: flex; gap: 8px; }+[hidden] { display: none !important; }+button { height: 28px; padding: 0 16px; border: .5px solid var(--border); border-radius: 7px; font: inherit; font-size: 12px; font-weight: 500; color: var(--background); background: var(--foreground); cursor: pointer; }+button.secondary { color: var(--foreground); background: transparent; }+button:hover { opacity: .85; }+button:focus-visible { outline: 2px solid #3b82f6; outline-offset: 2px; }+@keyframes draw { 0% { stroke-dashoffset: 1000; stroke-opacity: 1; fill-opacity: 0; } 30% { fill-opacity: .05; } 100% { stroke-dashoffset: 0; stroke-opacity: 0; fill-opacity: 1; } }+@keyframes loading { from { background-position: 100% 0; } to { background-position: -100% 0; } }+@media (prefers-color-scheme: dark) { :root { --background: #141414; --foreground: #f2f2f2; --muted: #9b9b9b; --track: #333; --border: rgba(255, 255, 255, .14); } }+@media (prefers-reduced-motion: reduce) { .enter .brand path, progress:not([value]) { animation: none; } }diff --git a/apps/desktop/src/common/securityPolicy.ts b/apps/desktop/src/common/securityPolicy.tsnew file mode 100644index 00000000000..6d91cb8edcc--- /dev/null+++ b/apps/desktop/src/common/securityPolicy.ts@@ -0,0 +1,22 @@+import { valid, validRange } from 'semver';+import * as z from 'zod/v4';++const channels = z.enum(['stable', 'canary', 'beta', 'nightly']);+export const securityUpdateRuleSchema = z.strictObject({+ affectedVersions: z+ .string()+ .min(1)+ .refine((value) => validRange(value) !== null),+ channel: channels,+ minimumInstallerVersion: z.string().refine((value) => valid(value) !== null),+ platforms: z.array(z.enum(['darwin', 'win32', 'linux'])).min(1),+ target: z.enum(['shell', 'core']),+});+export const securityUpdatePolicySchema = z.strictObject({+ kind: z.literal('desktop-security-policy'),+ revision: z.number().int().positive().max(Number.MAX_SAFE_INTEGER),+ rules: z.array(securityUpdateRuleSchema).max(1000),+ schemaVersion: z.literal(1),+ signature: z.string().min(1),+});+export type SecurityPolicy = z.infer<typeof securityUpdatePolicySchema>;diff --git a/apps/desktop/src/common/signedJson.ts b/apps/desktop/src/common/signedJson.tsnew file mode 100644index 00000000000..98063d23a17--- /dev/null+++ b/apps/desktop/src/common/signedJson.ts@@ -0,0 +1,31 @@+import { verify as cryptoVerify } from 'node:crypto';++export const canonicalJson = (value: unknown): string => {+ if (Array.isArray(value)) return `[${value.map(canonicalJson).join(',')}]`;+ if (value && typeof value === 'object') {+ const entries = Object.keys(value as Record<string, unknown>)+ .sort()+ .map(+ (key) => `${JSON.stringify(key)}:${canonicalJson((value as Record<string, unknown>)[key])}`,+ );+ return `{${entries.join(',')}}`;+ }+ return JSON.stringify(value);+};++export const verifyManifestSignature = (+ manifest: { signature: string },+ publicKeyPem: string,+): boolean => {+ const { signature, ...unsigned } = manifest;+ try {+ return cryptoVerify(+ null,+ Buffer.from(canonicalJson(unsigned)),+ publicKeyPem,+ Buffer.from(signature, 'base64'),+ );+ } catch {+ return false;+ }+};diff --git a/apps/desktop/src/main/const/shell.ts b/apps/desktop/src/main/const/shell.tsindex 529b411a57c..d48c8902410 100644--- a/apps/desktop/src/main/const/shell.ts+++ b/apps/desktop/src/main/const/shell.ts@@ -1,5 +1,18 @@import type { CoreManifest } from '@/core/infrastructure/coreOta/manifest';+export interface StartupUpdateProgress {+ phase: 'checking' | 'downloading' | 'applying';+ received?: number;+ total?: number;+}++export interface SecurityUpdateCheck {+ check: () => Promise<boolean>;+ isInstallerSafe: (version: string) => boolean;+}++export type StartupUpdateOutcome = 'ready' | 'relaunch' | 'full-update';+export interface ShellGlobal {readonly abi: string;readonly builtinDir: string;@@ -11,6 +24,13 @@ export interface ShellGlobal {readonly publicKey: string;readonly shellVersion: string;readonly source: 'builtin' | 'external';+ readonly startupUpdate?: {+ checkSecurity: (security: SecurityUpdateCheck) => Promise<boolean>;+ pending: boolean;+ run: (+ check: (update: (state: StartupUpdateProgress) => void) => Promise<StartupUpdateOutcome>,+ ) => Promise<boolean>;+ };}declare global {diff --git a/apps/desktop/src/main/core/App.ts b/apps/desktop/src/main/core/App.tsindex 7ec1155360b..dabf64dae02 100644--- a/apps/desktop/src/main/core/App.ts+++ b/apps/desktop/src/main/core/App.ts@@ -5,7 +5,7 @@ import type { DesktopBootProfilePayload } from '@lobechat/electron-client-ipc';import type { ElectronIPCEventHandler } from '@lobechat/electron-server-ipc';import { ElectronIPCServer } from '@lobechat/electron-server-ipc';import { enableManagedProcesses, shutdownManagedProcesses } from '@lobechat/utils/managedProcess';-import { app, ipcMain, nativeTheme, protocol } from 'electron';+import { app, ipcMain, nativeTheme, net, protocol } from 'electron';import { name } from '@/../../package.json';import { binDir, buildDir } from '@/const/dir';@@ -26,6 +26,7 @@ import {} from '@/modules/binaries';import { generateCliWrapper, getCliWrapperDir } from '@/modules/cliEmbedding';import { ScreenCaptureManager } from '@/modules/screenCapture/ScreenCaptureManager';+import { BUILD_CHANNEL, UPDATE_SERVER_URL } from '@/modules/updater/configs';import type { IServiceModule, ServiceLifecycle, ServiceModule } from '@/services';import LocalDatabaseService from '@/services/LocalDatabaseSrv';import { createLogger } from '@/utils/logger';@@ -41,6 +42,7 @@ import { IoCContainer } from './infrastructure/IoCContainer';import { LocalFileProtocolManager } from './infrastructure/LocalFileProtocolManager';import { ProtocolManager } from './infrastructure/ProtocolManager';import { RendererUrlManager } from './infrastructure/RendererUrlManager';+import { SecurityUpdatePolicy } from './infrastructure/SecurityUpdatePolicy';import { StaticFileServerManager } from './infrastructure/StaticFileServerManager';import { StoreManager } from './infrastructure/StoreManager';import type { UpdaterManager } from './infrastructure/UpdaterManager';@@ -60,6 +62,7 @@ type Class<T> = new (...args: any[]) => T;const importAll = (r: any) => Object.values(r).map((v: any) => v.default);export class App {+ startupUpdatePending = !!shellInfo?.startupUpdate;browserManager: BrowserManager;menuManager: MenuManager;i18n: I18nManager;@@ -279,6 +282,13 @@ export class App {// Reach Electron ready state, then create the main BrowserWindow before// native menus, local-file services, tray and updater initialization.await this.makeAppReady();+ if (shellInfo?.startupUpdate) {+ const ready = await shellInfo.startupUpdate.run(+ this.coreUpdateManager.checkBeforeFirstLaunch,+ );+ if (!ready) return;+ }+ this.startupUpdatePending = false;await this.browserManager.initializeBrowsers();this.prewarmLocalDatabaseAfterNavigation();await this.runControllerHooks('afterAppReady');@@ -318,6 +328,28 @@ export class App {private initializeAfterFirstFrame = async (initializeNativeShell: () => Promise<void>) => {await this.browserManager.waitForMainWindowFirstFrame();+ // Security policy IO must never delay the first usable window.+ if (shellInfo?.startupUpdate) {+ void shellInfo.startupUpdate+ .checkSecurity(+ new SecurityUpdatePolicy({+ channel: BUILD_CHANNEL,+ coreVersion: () => this.coreUpdateManager.getStatus().running,+ feedBaseUrl: (UPDATE_SERVER_URL ?? '')+ .replace(/\/(stable|nightly|canary|beta)\/?$/, '')+ .replace(/\/$/, ''),+ fetchImpl: (url, init) => net.fetch(url, init),+ platform: process.platform as 'darwin' | 'linux' | 'win32',+ publicKey: shellInfo.publicKey,+ shellVersion: shellInfo.shellVersion,+ userData: app.getPath('userData'),+ }),+ )+ .catch((error) => {+ logger.error('Background security update check failed:', error);+ });+ }+// GUI-launched apps do not inherit the user's login-shell PATH. Resolve it// asynchronously after the first frame so shell startup never blocks the// main process -> renderer navigation critical path.diff --git a/apps/desktop/src/main/core/__tests__/App.test.ts b/apps/desktop/src/main/core/__tests__/App.test.tsindex 82b60134366..eb50d735586 100644--- a/apps/desktop/src/main/core/__tests__/App.test.ts+++ b/apps/desktop/src/main/core/__tests__/App.test.ts@@ -2,10 +2,15 @@ import * as managedProcess from '@lobechat/utils/managedProcess';import { app as electronApp, ipcMain } from 'electron';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import type { ShellGlobal } from '@/const/shell';+// Import after mocks are set upimport LocalDatabaseService from '../../services/LocalDatabaseSrv';import { App } from '../App';+const shellState = vi.hoisted(() => ({ shellInfo: undefined as ShellGlobal | undefined }));+vi.mock('@/const/shell', () => shellState);+const mockPathExistsSync = vi.fn();// Mock electron modules@@ -69,6 +74,10 @@ vi.mock('fix-path', () => ({default: vi.fn(),}));+vi.mock('@/utils/shellPath', () => ({+ refreshShellPath: vi.fn(async () => {}),+}));+vi.mock('@/const/env', () => ({isDev: false,}));@@ -194,6 +203,8 @@ describe('App', () => {});afterEach(() => {+ shellState.shellInfo = undefined;+ vi.restoreAllMocks();vi.clearAllMocks();});@@ -208,6 +219,80 @@ describe('App', () => {});describe('service lifecycle', () => {+ it('shows business windows before starting a pending background security check', async () => {+ let firstFrame!: () => void;+ let finishCheck!: (ready: boolean) => void;+ const frame = new Promise<void>((resolve) => {+ firstFrame = resolve;+ });+ const checkSecurity = vi.fn(+ () =>+ new Promise<boolean>((resolve) => {+ finishCheck = resolve;+ }),+ );+ shellState.shellInfo = {+ abi: 'test',+ builtinDir: '/mock/core',+ coreDir: '/mock/core',+ log: [],+ manifest: null,+ markHealthy: vi.fn(),+ publicKey: '',+ shellVersion: '1.0.0',+ source: 'builtin',+ startupUpdate: { checkSecurity, pending: false, run: vi.fn(async () => true) },+ };+ appInstance = new App();+ vi.mocked(appInstance.browserManager.waitForMainWindowFirstFrame).mockReturnValue(frame);+ // Hold unrelated native setup; this test owns only the startup/security boundary.+ vi.spyOn(appInstance, 'runControllerHooks').mockImplementation(async (lifecycle) => {+ if (lifecycle === 'afterFirstFrame') await new Promise(() => {});+ });+ await appInstance.bootstrap();+ expect(appInstance.browserManager.initializeBrowsers).toHaveBeenCalledOnce();+ expect(checkSecurity).not.toHaveBeenCalled();+ expect(appInstance.startupUpdatePending).toBe(false);+ firstFrame();+ await vi.waitFor(() => expect(checkSecurity).toHaveBeenCalledOnce());+ expect(appInstance.startupUpdatePending).toBe(false);+ finishCheck(true);+ });++ it.each([true, false])(+ 'does not create business windows until startup checks allow entry (first launch: %s)',+ async (pending) => {+ let release!: (ready: boolean) => void;+ const run = vi.fn(+ () =>+ new Promise<boolean>((resolve) => {+ release = resolve;+ }),+ );+ shellState.shellInfo = {+ abi: 'test',+ builtinDir: '/mock/core',+ coreDir: '/mock/core',+ log: [],+ manifest: null,+ markHealthy: vi.fn(),+ publicKey: '',+ shellVersion: '1.0.0',+ source: 'builtin',+ startupUpdate: { checkSecurity: vi.fn(), pending, run },+ };+ appInstance = new App();+ const boot = appInstance.bootstrap();+ await vi.waitFor(() => expect(run).toHaveBeenCalledOnce());+ expect(appInstance.startupUpdatePending).toBe(true);+ expect(appInstance.browserManager.initializeBrowsers).not.toHaveBeenCalled();+ release(true);+ await boot;+ expect(appInstance.startupUpdatePending).toBe(false);+ expect(appInstance.browserManager.initializeBrowsers).toHaveBeenCalledOnce();+ },+ );+it('enables precise renderer heap metrics before Chromium is ready', async () => {appInstance = new App();diff --git a/apps/desktop/src/main/core/browser/BrowserManager.ts b/apps/desktop/src/main/core/browser/BrowserManager.tsindex c0861fe4158..54c05e144e0 100644--- a/apps/desktop/src/main/core/browser/BrowserManager.ts+++ b/apps/desktop/src/main/core/browser/BrowserManager.ts@@ -39,6 +39,7 @@ export class BrowserManager {}showMainWindow() {+ if (this.app.startupUpdatePending) return;logger.debug('Showing main window');const browser = this.getMainWindow();const window = browser.browserWindow;@@ -346,6 +347,7 @@ export class BrowserManager {* @param options Browser window options*/private retrieveOrInitialize(options: BrowserWindowOpts) {+ if (this.app.startupUpdatePending) throw new Error('Startup update is still pending');let browser = this.browsers.get(options.identifier);if (browser) {logger.debug(`Retrieved existing browser: ${options.identifier}`);diff --git a/apps/desktop/src/main/core/infrastructure/ProtocolManager.ts b/apps/desktop/src/main/core/infrastructure/ProtocolManager.tsindex fa0e870d627..de72d65133e 100644--- a/apps/desktop/src/main/core/infrastructure/ProtocolManager.ts+++ b/apps/desktop/src/main/core/infrastructure/ProtocolManager.ts@@ -151,7 +151,7 @@ export class ProtocolManager {logger.debug(`🔗 [Protocol] App ready state: ${app.isReady()}`);logger.debug(`🔗 [Protocol] Current pending URLs count: ${this.pendingUrls.length}`);- if (!app.isReady()) {+ if (!app.isReady() || this.app.startupUpdatePending) {// App not ready yet, store for later processinglogger.debug('🔗 [Protocol] App not ready, storing protocol URL for later processing');this.pendingUrls.push(url);diff --git a/apps/desktop/src/main/core/infrastructure/SecurityUpdatePolicy.ts b/apps/desktop/src/main/core/infrastructure/SecurityUpdatePolicy.tsnew file mode 100644index 00000000000..0eb4e5ce0c7--- /dev/null+++ b/apps/desktop/src/main/core/infrastructure/SecurityUpdatePolicy.ts@@ -0,0 +1,105 @@+import { mkdir, readFile, rename, writeFile } from 'node:fs/promises';+import path from 'node:path';++import { readBlobWithLimit } from '@lobechat/utils/imageToBase64';+import { gte, satisfies, valid } from 'semver';++import { createLogger } from '@/utils/logger';+import { type SecurityPolicy, securityUpdatePolicySchema } from '~common/securityPolicy';++import { verifyManifestSignature } from './coreOta/manifest';++const logger = createLogger('core:SecurityUpdatePolicy');+interface Options {+ channel: string;+ coreVersion: () => string | null;+ feedBaseUrl: string;+ fetchImpl: (url: string, init?: RequestInit) => Promise<Response>;+ platform: 'darwin' | 'linux' | 'win32';+ publicKey: string;+ shellVersion: string;+ userData: string;+}++/** Independent of OTA availability, rollout and the user's automatic-update preference. */+export class SecurityUpdatePolicy {+ private policy: SecurityPolicy | undefined;+ private readonly cacheFile: string;++ constructor(private readonly options: Options) {+ this.cacheFile = path.join(options.userData, 'security-update-policy.json');+ }++ private parse(value: unknown) {+ const policy = securityUpdatePolicySchema.parse(value);+ if (!verifyManifestSignature(policy, this.options.publicKey)) {+ throw new Error('Security policy signature invalid');+ }+ return policy;+ }++ check = async (): Promise<boolean> => {+ const { feedBaseUrl, fetchImpl, publicKey } = this.options;+ if (!publicKey || !feedBaseUrl) return false;+ if (!this.policy) {+ try {+ this.policy = this.parse(JSON.parse(await readFile(this.cacheFile, 'utf8')));+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') {+ logger.warn('Cannot load cached security policy', error);+ }+ }+ }+ try {+ const response = await fetchImpl(`${feedBaseUrl}/security-policy.json`, {+ cache: 'no-store',+ signal: AbortSignal.timeout(5000),+ });+ if (!response.ok) throw new Error(`Security policy fetch failed: ${response.status}`);+ const next = this.parse(+ JSON.parse(await (await readBlobWithLimit(response, 1024 * 1024)).text()),+ );+ // Only a newer signed policy can revoke or change a known restriction.+ if (!this.policy || next.revision > this.policy.revision) {+ this.policy = next;+ await mkdir(path.dirname(this.cacheFile), { recursive: true });+ await writeFile(`${this.cacheFile}.tmp`, JSON.stringify(next));+ await rename(`${this.cacheFile}.tmp`, this.cacheFile);+ }+ } catch (error) {+ // A missing/unreachable policy must not lock out unaffected installations.+ // Once a signed restriction is known, the cached policy still enforces it offline.+ logger.warn('Security policy refresh failed; retaining last verified policy', error);+ }+ return this.affectedRules.length > 0;+ };++ private get applicableRules() {+ return (this.policy?.rules ?? []).filter(+ (rule) =>+ rule.channel === this.options.channel && rule.platforms.includes(this.options.platform),+ );+ }++ private get affectedRules() {+ return this.applicableRules.filter((rule) => {+ const version =+ rule.target === 'shell' ? this.options.shellVersion : this.options.coreVersion();+ return (+ version &&+ valid(version) &&+ satisfies(version, rule.affectedVersions, { includePrerelease: true })+ );+ });+ }++ isInstallerSafe = (version: string): boolean => {+ if (!valid(version)) return false;+ return (+ this.affectedRules.every((rule) => gte(version, rule.minimumInstallerVersion)) &&+ this.applicableRules.every(+ (rule) => !satisfies(version, rule.affectedVersions, { includePrerelease: true }),+ )+ );+ };+}diff --git a/apps/desktop/src/main/core/infrastructure/__tests__/ProtocolManager.test.ts b/apps/desktop/src/main/core/infrastructure/__tests__/ProtocolManager.test.tsindex 8b730766418..f50eeed497c 100644--- a/apps/desktop/src/main/core/infrastructure/__tests__/ProtocolManager.test.ts+++ b/apps/desktop/src/main/core/infrastructure/__tests__/ProtocolManager.test.ts@@ -88,6 +88,20 @@ describe('ProtocolManager', () => {manager = new ProtocolManager(mockAppCore);});+ it('queues deep links while the startup update window is blocking entry', async () => {+ mockAppCore.startupUpdatePending = true;+ manager.initialize();+ openUrlHandler!(+ { preventDefault: vi.fn() },+ 'lobehub://plugin/install?url=https://example.com',+ );+ expect(mockShowMainWindow).not.toHaveBeenCalled();+ expect(mockHandleProtocolRequest).not.toHaveBeenCalled();+ mockAppCore.startupUpdatePending = false;+ await manager.processPendingUrls();+ expect(mockHandleProtocolRequest).toHaveBeenCalledOnce();+ });+describe('constructor', () => {it('should initialize with protocol scheme from getProtocolScheme', () => {expect(getProtocolScheme).toHaveBeenCalled();diff --git a/apps/desktop/src/main/core/infrastructure/__tests__/SecurityUpdatePolicy.test.ts b/apps/desktop/src/main/core/infrastructure/__tests__/SecurityUpdatePolicy.test.tsnew file mode 100644index 00000000000..70e35ce65bc--- /dev/null+++ b/apps/desktop/src/main/core/infrastructure/__tests__/SecurityUpdatePolicy.test.ts@@ -0,0 +1,126 @@+import { generateKeyPairSync, sign } from 'node:crypto';+import { mkdtemp, rm } from 'node:fs/promises';+import os from 'node:os';+import path from 'node:path';++import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { canonicalJson } from '../coreOta/manifest';+import { SecurityUpdatePolicy } from '../SecurityUpdatePolicy';++const keys = generateKeyPairSync('ed25519');+const publicKey = keys.publicKey.export({ format: 'pem', type: 'spki' }).toString();+let userData: string;+const rule = {+ affectedVersions: '>=1.0.0 <1.2.0',+ channel: 'stable',+ minimumInstallerVersion: '1.2.0',+ platforms: ['darwin'],+ target: 'shell',+};+const signed = (revision = 1, rules = [rule]) => {+ const payload = { kind: 'desktop-security-policy', revision, rules, schemaVersion: 1 };+ return {+ ...payload,+ signature: sign(null, Buffer.from(canonicalJson(payload)), keys.privateKey).toString('base64'),+ };+};+const create = (fetchImpl = vi.fn(async () => Response.json(signed())), overrides = {}) =>+ new SecurityUpdatePolicy({+ channel: 'stable',+ coreVersion: () => '1.1.0',+ feedBaseUrl: 'https://updates.test',+ fetchImpl,+ platform: 'darwin',+ publicKey,+ shellVersion: '1.1.0',+ userData,+ ...overrides,+ });+beforeEach(async () => {+ userData = await mkdtemp(path.join(os.tmpdir(), 'security-policy-'));+});+afterEach(async () => {+ await rm(userData, { force: true, recursive: true });+});++describe('signed security update policy', () => {+ it('blocks an affected stable shell and refuses vulnerable or insufficient installers', async () => {+ const policy = create();+ expect(await policy.check()).toBe(true);+ expect(policy.isInstallerSafe('1.1.9')).toBe(false);+ expect(policy.isInstallerSafe('invalid')).toBe(false);+ expect(policy.isInstallerSafe('1.2.0')).toBe(true);+ });+ it('enforces the repair minimum even outside the affected range and excludes newly vulnerable installers', async () => {+ const policy = create(+ vi.fn(async () =>+ Response.json(+ signed(1, [+ { ...rule, affectedVersions: '1.1.0', minimumInstallerVersion: '1.3.0' },+ { ...rule, affectedVersions: '1.4.0', minimumInstallerVersion: '1.4.1' },+ ]),+ ),+ ),+ );+ expect(await policy.check()).toBe(true);+ expect(policy.isInstallerSafe('1.2.0')).toBe(false);+ expect(policy.isInstallerSafe('1.3.0')).toBe(true);+ expect(policy.isInstallerSafe('1.4.0')).toBe(false);+ });++ it('supports exact prerelease versions and core-only restrictions', async () => {+ const fetchImpl = vi.fn(async () =>+ Response.json(+ signed(1, [+ {+ ...rule,+ channel: 'canary',+ target: 'core',+ affectedVersions: '2.0.0-canary.5',+ minimumInstallerVersion: '2.0.0-canary.6',+ },+ ]),+ ),+ );+ const policy = create(fetchImpl, { channel: 'canary', coreVersion: () => '2.0.0-canary.5' });+ expect(await policy.check()).toBe(true);+ expect(policy.isInstallerSafe('2.0.0-canary.5')).toBe(false);+ expect(policy.isInstallerSafe('2.0.0-canary.6')).toBe(true);+ });+ it('does not block unaffected versions, platforms or channels', async () => {+ for (const overrides of [+ { shellVersion: '1.2.0' },+ { channel: 'canary' },+ { platform: 'win32' },+ ]) {+ expect(await create(undefined, overrides).check()).toBe(false);+ }+ });+ it('rejects tampered policies without locking out an installation', async () => {+ const tampered = signed();+ tampered.rules[0] = { ...rule, affectedVersions: '*' };+ expect(await create(vi.fn(async () => Response.json(tampered))).check()).toBe(false);+ });+ it('retains verified restrictions offline and rejects rollback of a cached policy', async () => {+ expect(await create(vi.fn(async () => Response.json(signed(2)))).check()).toBe(true);+ const fetchImpl = vi.fn(async () => {+ throw new Error('offline');+ });+ expect(await create(fetchImpl).check()).toBe(true);+ expect(await create(vi.fn(async () => Response.json(signed(1, [])))).check()).toBe(true);+ expect(await create(vi.fn(async () => Response.json(signed(2, [])))).check()).toBe(true);+ expect(await create(vi.fn(async () => Response.json(signed(3, [])))).check()).toBe(false);+ expect(await create(fetchImpl).check()).toBe(false);+ });+ it('allows ordinary startup if the policy has not been published', async () => {+ expect(await create(vi.fn(async () => new Response('', { status: 404 }))).check()).toBe(false);+ });+ it('rejects malformed signed version ranges', async () => {+ expect(+ await create(+ vi.fn(async () => Response.json(signed(1, [{ ...rule, affectedVersions: 'nonsense' }]))),+ ).check(),+ ).toBe(false);+ });+});diff --git a/apps/desktop/src/main/core/infrastructure/coreOta/CoreUpdateManager.ts b/apps/desktop/src/main/core/infrastructure/coreOta/CoreUpdateManager.tsindex 0fad68dfbe5..a1879a4441b 100644--- a/apps/desktop/src/main/core/infrastructure/coreOta/CoreUpdateManager.ts+++ b/apps/desktop/src/main/core/infrastructure/coreOta/CoreUpdateManager.ts@@ -7,7 +7,12 @@ import type { UpdateChannel } from '@lobechat/electron-client-ipc';import { readBlobWithLimit } from '@lobechat/utils/imageToBase64';import { app as electronApp, BrowserWindow, net } from 'electron';-import { type ShellGlobal, shellInfo } from '@/const/shell';+import {+ type ShellGlobal,+ shellInfo,+ type StartupUpdateOutcome,+ type StartupUpdateProgress,+} from '@/const/shell';import {BUILD_CHANNEL,coerceStoredUpdateChannel,@@ -37,6 +42,7 @@ const DOWNLOAD_TIMEOUT = 15 * 60 * 1000;const LOAD_PING_TIMEOUT = 3000;const MAX_BOOT_CRASHES = 2;const CHECK_INTERVAL = 60 * 60 * 1000;+const NETWORK_POLL_INTERVAL = 15_000;const FIRST_CHECK_DELAY = Number(process.env['RENDERER_OTA_CHECK_DELAY']) || 0;const IDLE_APPLY_DELAY = 5 * 60 * 1000;const FEED_BASE_URL =@@ -68,6 +74,8 @@ export class CoreUpdateManager {private unloadPrevented = false;private rollbackPointer: CorePointer | null = null;private rollbackRenderer: RendererSource | null = null;+ private rendererVersion: string | null = null;+ private rollbackRendererVersion: string | null = null;private pendingBootCheck = false;private coldBootCheck = false;private deferredColdBootCheck = false;@@ -80,6 +88,7 @@ export class CoreUpdateManager {private loadPingTimer: NodeJS.Timeout | null = null;private checkTimer: NodeJS.Timeout | null = null;private checkInterval: NodeJS.Timeout | null = null;+ private networkInterval: NodeJS.Timeout | null = null;private scheduledChecksStarted = false;private appliedVersion: string | null = null;private idleTimer: NodeJS.Timeout | null = null;@@ -284,6 +293,7 @@ export class CoreUpdateManager {handleUnloadPrevented = () => {this.unloadPrevented = true;if (!this.pendingBootCheck || this.coldBootCheck) return;+ this.rendererVersion = this.rollbackRendererVersion;logger.info('Reload cancelled by renderer, restoring staged update');this.app.browserManager.browsers.forEach((browser) => browser.cancelUnloadConfirmation());this.unloadConfirmations.clear();@@ -340,6 +350,8 @@ export class CoreUpdateManager {this.staged = null;return false;}+ this.rollbackRendererVersion = this.rendererVersion;+ this.rendererVersion = version;this.rollbackPointer = this.pointer;this.savePointer({ current: version, previous: this.pointer.current, staged: null });this.staged = null;@@ -363,17 +375,38 @@ export class CoreUpdateManager {lastCheckAt: this.lastCheckAt,lastError: this.lastError,needsFullRelease: this.needsFullRelease,- running: this.shell?.manifest?.version ?? null,+ running: this.rendererVersion ?? this.shell?.manifest?.version ?? null,staged: this.staged?.version ?? null,});checkForUpdates = ({ manual = false }: { manual?: boolean } = {}) => {if (manual && this.staged) this.announceStaged();- this.checkTask = this.checkTask.catch(() => {}).then(() => this.runCheck());+ this.checkTask = this.checkTask+ .catch(() => {})+ .then(async () => {+ await this.runCheck();+ });return this.checkTask;};- private async runCheck() {+ checkBeforeFirstLaunch = async (+ update: (state: StartupUpdateProgress) => void,+ ): Promise<StartupUpdateOutcome> => {+ if (!this.enabled) throw new Error(`Core OTA unavailable: ${this.disabledReasons.join(', ')}`);+ const outcome = await this.runCheck(update);+ if (outcome === 'needs-full-release') return 'full-update';+ if (outcome === 'staged') return 'relaunch';+ if (+ outcome === 'up-to-date' ||+ outcome === 'already-current' ||+ outcome === 'rollout-excluded'+ ) {+ return 'ready';+ }+ throw new Error(this.lastError || `Startup update check did not complete: ${outcome}`);+ };++ private async runCheck(startupProgress?: (state: StartupUpdateProgress) => void) {if (!this.enabled || this.busy) {logger.info('Core OTA check skipped', { reason: !this.enabled ? 'disabled' : 'busy' });return;@@ -401,6 +434,7 @@ export class CoreUpdateManager {if (this.pointer.blacklist.includes(version)) throw new SkipCheck('blacklisted');if (!this.inRollout(version, remote.rollout)) throw new SkipCheck('rollout-excluded');+ startupProgress?.({ phase: 'downloading' });await this.gcTask;let current =this.shell!.source === 'external'@@ -422,6 +456,10 @@ export class CoreUpdateManager {const staged = await this.store.stage({builtin: { dir: this.shell!.builtinDir, manifest: this.builtinManifest! },current,+ onApplying: startupProgress ? () => startupProgress({ phase: 'applying' }) : undefined,+ onDownloadProgress: startupProgress+ ? (progress) => startupProgress({ phase: 'downloading', ...progress })+ : undefined,objectsBaseUrl: remote.schemaVersion === 3 ? remote.objectsBaseUrl : undefined,packsBaseUrl: feedUrl,remote,@@ -440,14 +478,14 @@ export class CoreUpdateManager {: { staged: version },);this.lastError = null;- this.announceStaged();+ if (!startupProgress) this.announceStaged();this.gc();- if (applyMode === 'reload') this.handleWindowBlur();+ if (!startupProgress && applyMode === 'reload') this.handleWindowBlur();outcome = 'staged';} catch (error) {if (error instanceof SkipCheck) {outcome = error.message;- return;+ return outcome;}outcome = 'failed';this.lastError = error instanceof Error ? error.message : String(error);@@ -459,6 +497,7 @@ export class CoreUpdateManager {if (generation === this.checkGeneration) this.busy = false;logger.info('Core OTA check finished', { channel: this.activeChannel, outcome });}+ return outcome;}private announceStaged() {@@ -543,6 +582,15 @@ export class CoreUpdateManager {this.checkInterval = setInterval(() => this.checkForUpdates(), CHECK_INTERVAL);this.checkTimer.unref?.();this.checkInterval.unref?.();+ if (this.networkInterval) clearInterval(this.networkInterval);+ let online = net.isOnline();+ // ponytail: main process has no online event; polling is cheap and catches offline launches.+ this.networkInterval = setInterval(() => {+ const next = net.isOnline();+ if (next && !online) this.checkForUpdates();+ online = next;+ }, NETWORK_POLL_INTERVAL);+ this.networkInterval.unref?.();}private relaunchIntoCore() {@@ -591,6 +639,7 @@ export class CoreUpdateManager {}this.app.rendererUrlManager.setActiveRenderer(this.rollbackRenderer);this.rollbackRenderer = null;+ this.rendererVersion = this.rollbackRendererVersion;this.rollbackPointer = null;this.unloadConfirmations.clear();this.gc();diff --git a/apps/desktop/src/main/core/infrastructure/coreOta/__tests__/CoreUpdateManager.int.test.ts b/apps/desktop/src/main/core/infrastructure/coreOta/__tests__/CoreUpdateManager.int.test.tsindex 09e20b541a6..0c4fe5cfc47 100644--- a/apps/desktop/src/main/core/infrastructure/coreOta/__tests__/CoreUpdateManager.int.test.ts+++ b/apps/desktop/src/main/core/infrastructure/coreOta/__tests__/CoreUpdateManager.int.test.ts@@ -55,7 +55,7 @@ const { electronMock, loggerMock } = vi.hoisted(() => ({releaseSingleInstanceLock: vi.fn(),},BrowserWindow: { getAllWindows: vi.fn(() => []) },- net: { fetch: vi.fn() },+ net: { fetch: vi.fn(), isOnline: vi.fn(() => true) },},loggerMock: { debug: vi.fn(), error: vi.fn(), info: vi.fn(), warn: vi.fn() },}));@@ -287,6 +287,30 @@ describe('CoreUpdateManager initialize', () => {}});+ it('checks again as soon as the network comes back', async () => {+ vi.useFakeTimers();+ electronMock.net.isOnline.mockReturnValue(false);+ try {+ const { manager } = await loadManager();+ manager.startScheduledChecks();+ await vi.advanceTimersByTimeAsync(1);+ expect(fetchImpl).toHaveBeenCalledTimes(1);++ await vi.advanceTimersByTimeAsync(30_000);+ expect(fetchImpl).toHaveBeenCalledTimes(1);++ electronMock.net.isOnline.mockReturnValue(true);+ await vi.advanceTimersByTimeAsync(15_000);+ expect(fetchImpl).toHaveBeenCalledTimes(2);++ await vi.advanceTimersByTimeAsync(60_000);+ expect(fetchImpl).toHaveBeenCalledTimes(2);+ } finally {+ electronMock.net.isOnline.mockReturnValue(true);+ vi.useRealTimers();+ }+ });+it('reports disabled reasons when shell is missing', async () => {const { manager } = await loadManager(makeApp(), null);expect(manager.enabled).toBe(false);@@ -431,15 +455,35 @@ describe('CoreUpdateManager initialize', () => {);};+ it('keeps the validated pointer intact until cold boot succeeds, then immediately checks', async () => {+ vi.useFakeTimers();+ try {+ serveLatest(mainChanged('1.0.2', 2));+ const { manager } = await bootExternal({ failures: 1, version: '1.0.1' });+ manager.startScheduledChecks();+ await vi.advanceTimersByTimeAsync(1);+ expect(readPointer(otaRoot(), ABI)).toMatchObject({ current: '1.0.1', previous: null });+ expect(fetchImpl).not.toHaveBeenCalled();+ const resumedCheck = vi.spyOn(manager, 'checkForUpdates');+ manager.handleBootPing('mounted');+ expect(resumedCheck).toHaveBeenCalledOnce();+ await resumedCheck.mock.results[0].value;+ expect(readPointer(otaRoot(), ABI)).toMatchObject({ current: '1.0.2', previous: '1.0.1' });+ } finally {+ vi.useRealTimers();+ }+ });+it('rolls back and relaunches when the first boot of a version never mounts', async () => {vi.useFakeTimers();try {+ serveLatest(mainChanged('1.0.2', 2));const { app, manager } = await bootExternal({ failures: 1, version: '1.0.1' });manager.startScheduledChecks();- vi.advanceTimersByTime(30_000);+ await vi.advanceTimersByTimeAsync(30_000);expect(electronMock.app.relaunch).not.toHaveBeenCalled();- vi.advanceTimersByTime(31_000);+ await vi.advanceTimersByTimeAsync(31_000);expect(readPointer(otaRoot(), ABI)).toMatchObject({ blacklist: ['1.0.1'], current: null });expect(electronMock.app.relaunch).toHaveBeenCalled();@@ -624,10 +668,9 @@ describe('CoreUpdateManager checkForUpdates', () => {expect(existsSync(coreDir('1.0.1'))).toBe(false);});- it('retains a healthy hot update for late subscribers without changing the booted core', async () => {+ it('retains a healthy hot update and its active renderer version for late subscribers', async () => {serveLatest(rendererOnly('1.0.1', 1));const { app, manager } = await loadManager();- const running = manager.getStatus().running;await manager.checkForUpdates();expect(manager.getStatus().appliedVersion).toBeNull();manager.applyStagedNow();@@ -638,7 +681,11 @@ describe('CoreUpdateManager checkForUpdates', () => {expect.anything(),);manager.handleBootPing('mounted');- expect(manager.getStatus()).toMatchObject({ appliedVersion: '1.0.1', running, staged: null });+ expect(manager.getStatus()).toMatchObject({+ appliedVersion: '1.0.1',+ running: '1.0.1',+ staged: null,+ });expect(app.browserManager.broadcastToAllWindows).toHaveBeenCalledWith('coreUpdateApplied','1.0.1',@@ -678,7 +725,11 @@ describe('CoreUpdateManager checkForUpdates', () => {await manager.checkForUpdates();- expect(manager.getStatus()).toMatchObject({ applyMode: 'reload', staged: '1.0.1' });+ expect(manager.getStatus()).toMatchObject({+ applyMode: 'reload',+ running: '1.0.0',+ staged: '1.0.1',+ });expect(app.browserManager.broadcastToAllWindows).toHaveBeenCalledWith('updateReady', {kind: 'core-reload',version: '1.0.1',@@ -697,7 +748,7 @@ describe('CoreUpdateManager checkForUpdates', () => {previous: null,staged: null,});- expect(manager.getStatus().staged).toBeNull();+ expect(manager.getStatus()).toMatchObject({ running: '1.0.1', staged: null });const reload =app.browserManager.browsers.get('main')!.browserWindow.webContents.reloadIgnoringCache;expect(reload).toHaveBeenCalledTimes(1);@@ -837,8 +888,10 @@ describe('CoreUpdateManager checkForUpdates', () => {await manager.checkForUpdates();manager.applyStagedNow();+ expect(manager.getStatus().running).toBe('1.0.1');manager.handleRendererCrash();manager.handleRendererCrash();+ expect(manager.getStatus().running).toBe('1.0.0');expect(app.rendererUrlManager.activeRenderer).toBe(builtinRenderer);expect(readPointer(otaRoot(), ABI)).toMatchObject({@@ -980,7 +1033,11 @@ describe('CoreUpdateManager checkForUpdates', () => {vi.advanceTimersByTime(60_000);expect(readPointer(otaRoot(), ABI).blacklist).toEqual([]);expect(manager.resolveUnloadConfirmation(1, false)).toBe(false);- expect(manager.getStatus()).toMatchObject({ staged: '1.0.1', appliedVersion: null });+ expect(manager.getStatus()).toMatchObject({+ staged: '1.0.1',+ appliedVersion: null,+ running: '1.0.0',+ });expect(manager.resolveUnloadConfirmation(1, true)).toBe(false);manager.applyStagedNow();manager.pauseForUnloadConfirmation(1);@@ -1068,7 +1125,7 @@ describe('CoreUpdateManager checkForUpdates', () => {await flushGc(manager);expect(readPointer(otaRoot(), ABI)).toMatchObject({ current: null, previous: null });- expect(existsSync(coreDir('1.0.1'))).toBe(false);+ await vi.waitFor(() => expect(existsSync(coreDir('1.0.1'))).toBe(false));});it('auto-applies a reload-mode stage after five idle minutes, even when staged while idle', async () => {@@ -1166,3 +1223,40 @@ describe('CoreUpdateManager checkForUpdates', () => {expect(existsSync(coreDir('1.0.1'))).toBe(false);});});++describe('first launch update gate', () => {+ it('opens only after a verified up-to-date response', async () => {+ serveLatest(builtinManifest);+ const { manager } = await loadManager();+ await expect(manager.checkBeforeFirstLaunch(vi.fn())).resolves.toBe('ready');+ });++ it('downloads and applies before opening, without broadcasting to business windows', async () => {+ serveLatest(rendererOnly('1.0.1', 1));+ const { manager, app } = await loadManager();+ const progress = vi.fn();+ await expect(manager.checkBeforeFirstLaunch(progress)).resolves.toBe('relaunch');+ expect(progress).toHaveBeenCalledWith(+ expect.objectContaining({ phase: 'downloading', received: expect.any(Number) }),+ );+ expect(progress).toHaveBeenLastCalledWith({ phase: 'applying' });+ expect(readPointer(otaRoot(), ABI).staged).toBe('1.0.1');+ expect(app.browserManager.broadcastToAllWindows).not.toHaveBeenCalled();+ await flushGc(manager);+ });++ it('fails closed on missing feed and invalid signature, and can retry', async () => {+ const { manager } = await loadManager();+ await expect(manager.checkBeforeFirstLaunch(vi.fn())).rejects.toThrow('feed-not-found');+ serveLatest({ ...builtinManifest, signature: 'invalid' });+ await expect(manager.checkBeforeFirstLaunch(vi.fn())).rejects.toThrow('signature');+ serveLatest(builtinManifest);+ await expect(manager.checkBeforeFirstLaunch(vi.fn())).resolves.toBe('ready');+ });++ it('requests a full installer when the signed update needs a different shell', async () => {+ serveLatest(buildManifest('1.0.1', 1, BASE_FILES, { shellAbi: 'b'.repeat(64) }));+ const { manager } = await loadManager();+ await expect(manager.checkBeforeFirstLaunch(vi.fn())).resolves.toBe('full-update');+ });+});diff --git a/apps/desktop/src/main/core/infrastructure/coreOta/manifest.ts b/apps/desktop/src/main/core/infrastructure/coreOta/manifest.tsindex 3726b132449..10c742868a9 100644--- a/apps/desktop/src/main/core/infrastructure/coreOta/manifest.ts+++ b/apps/desktop/src/main/core/infrastructure/coreOta/manifest.ts@@ -1,4 +1,4 @@-import { createHash, verify as cryptoVerify } from 'node:crypto';+import { createHash } from 'node:crypto';import { readFileSync } from 'node:fs';import path from 'node:path';@@ -6,6 +6,8 @@ import * as z from 'zod/v4';import type { ShellGlobal } from '@/const/shell';+export { canonicalJson, verifyManifestSignature } from '~common/signedJson';+const sha256Schema = z.string().regex(/^[0-9a-f]{64}$/);const packPathSchema = z.string().regex(/^packs\/[0-9a-f]{64}\.zip$/);const relativePathSchema = z.string().refine((value) => {@@ -158,36 +160,6 @@ export type CorePatch = z.infer<typeof corePatchSchema>;export type RendererArtifact = z.infer<typeof rendererArtifactSchema>;export type RendererTreeFile = z.infer<typeof rendererTreeFileSchema>;-export const canonicalJson = (value: unknown): string => {- if (Array.isArray(value)) return `[${value.map(canonicalJson).join(',')}]`;- if (value && typeof value === 'object') {- const entries = Object.keys(value as Record<string, unknown>)- .sort()- .map(- (key) => `${JSON.stringify(key)}:${canonicalJson((value as Record<string, unknown>)[key])}`,- );- return `{${entries.join(',')}}`;- }- return JSON.stringify(value);-};--export const verifyManifestSignature = (- manifest: { signature: string },- publicKeyPem: string,-): boolean => {- const { signature, ...unsigned } = manifest;- try {- return cryptoVerify(- null,- Buffer.from(canonicalJson(unsigned)),- publicKeyPem,- Buffer.from(signature, 'base64'),- );- } catch {- return false;- }-};-export const isValidManifestShape = (value: unknown): value is CoreManifest =>coreManifestSchema.safeParse(value).success;diff --git a/apps/desktop/src/main/core/infrastructure/coreOta/pack.ts b/apps/desktop/src/main/core/infrastructure/coreOta/pack.tsindex d54f067e849..cb12d8d35e8 100644--- a/apps/desktop/src/main/core/infrastructure/coreOta/pack.ts+++ b/apps/desktop/src/main/core/infrastructure/coreOta/pack.ts@@ -103,6 +103,7 @@ export class PackDownloader {local: Map<string, string>,baseUrl: string,put: (sha256: string, content: Buffer) => Promise<void>,+ onChunk?: (bytes: number) => void,) {const plan = planPackDownload(manifest, missing, local, this.timing);const downloaded = { bytes: 0, objects: 0, patches: 0 };@@ -137,6 +138,7 @@ export class PackDownloader {received += value.byteLength;downloaded.bytes += value.byteLength;if (received > expected) throw new Error('Oversized pack response');+ onChunk?.(value.byteLength);digest.update(value);let offset = 0;while (offset < value.length) {diff --git a/apps/desktop/src/main/core/infrastructure/coreOta/store.ts b/apps/desktop/src/main/core/infrastructure/coreOta/store.tsindex 509ae769758..1a99f6ee0cf 100644--- a/apps/desktop/src/main/core/infrastructure/coreOta/store.ts+++ b/apps/desktop/src/main/core/infrastructure/coreOta/store.ts@@ -30,6 +30,8 @@ type LocalCore = { dir: string; manifest: CoreManifest };type StageInput = {builtin: LocalCore;current: LocalCore | null;+ onApplying?: () => void;+ onDownloadProgress?: (progress: { received: number; total?: number }) => void;objectsBaseUrl?: string;packsBaseUrl: string;remote: CoreManifest;@@ -162,7 +164,23 @@ export class CoreStore {}}- private async stageCore({ builtin, current, objectsBaseUrl, packsBaseUrl, remote }: StageInput) {+ private async stageCore({+ builtin,+ current,+ objectsBaseUrl,+ packsBaseUrl,+ remote,+ onApplying,+ onDownloadProgress,+ }: StageInput) {+ let received = 0;+ let total: number | undefined;+ const onChunk = onDownloadProgress+ ? (bytes: number) => {+ received += bytes;+ onDownloadProgress({ received, total });+ }+ : undefined;if (!isSafeVersion(remote.version)) throw new Error(`Unsafe version: ${remote.version}`);await mkdir(this.storeDir, { mode: DIR_MODE, recursive: true });await mkdir(this.coresDir, { mode: DIR_MODE, recursive: true });@@ -202,7 +220,9 @@ export class CoreStore {byHash,packsBaseUrl,(hash, bytes) => this.putObject(hash, bytes),+ onChunk,);+ onApplying?.();return { ...result, dir: await this.assemble(remote, byHash, builtin) } satisfies StageResult;}const missing = [...new Set(remote.tree.map((file) => file.sha256))].filter(@@ -223,7 +243,7 @@ export class CoreStore {patch &&(await attempt(`patch ${patch.fromSha256}->${patch.toSha256}`, async () => {const url = `${objectsBaseUrl}/patches/${patch.fromSha256}-${patch.toSha256}.zst`;- const raw = await this.fetchBytes(url);+ const raw = await this.fetchBytes(url, onChunk);const base = await readFile(byHash.get(patch.fromSha256)!);await this.putObject(sha256, await applyZstdPatch(base, raw));downloaded.patches += 1;@@ -231,7 +251,7 @@ export class CoreStore {}));if (patched) return;const fetched = await attempt(`object ${sha256}`, async () => {- const raw = await this.fetchBytes(`${objectsBaseUrl}/objects/${sha256}.zst`);+ const raw = await this.fetchBytes(`${objectsBaseUrl}/objects/${sha256}.zst`, onChunk);await this.putObject(sha256, Buffer.from(await zstdDecompressAsync(raw)));downloaded.objects += 1;downloaded.bytes += raw.byteLength;@@ -242,7 +262,8 @@ export class CoreStore {const fallbackFull = failed.length > 0 || missing.length > FULL_FALLBACK_THRESHOLD;if (fallbackFull) {- const pack = await this.fetchBytes(`${packsBaseUrl}/${remote.full.path}`);+ total = received + remote.full.size;+ const pack = await this.fetchBytes(`${packsBaseUrl}/${remote.full.path}`, onChunk);if (sha256File(pack) !== remote.full.sha256) {throw new Error(`Core pack integrity mismatch: ${remote.full.path}`);}@@ -256,6 +277,7 @@ export class CoreStore {}}+ onApplying?.();const dir = await this.assemble(remote, byHash, builtin);return { dir, downloaded, fallbackFull } satisfies StageResult;}@@ -283,10 +305,23 @@ export class CoreStore {return path.join(this.storeDir, sha256);}- private async fetchBytes(url: string): Promise<Buffer> {+ private async fetchBytes(url: string, onChunk?: (bytes: number) => void): Promise<Buffer> {const response = await this.fetchImpl(url);if (!response.ok) throw new Error(`Core OTA fetch failed (${response.status}): ${url}`);- return Buffer.from(await response.arrayBuffer());+ if (!onChunk || !response.body) return Buffer.from(await response.arrayBuffer());+ const chunks: Buffer[] = [];+ const reader = response.body.getReader();+ try {+ while (true) {+ const { done, value } = await reader.read();+ if (done) break;+ chunks.push(Buffer.from(value));+ onChunk(value.byteLength);+ }+ return Buffer.concat(chunks);+ } finally {+ reader.releaseLock();+ }}private async putObject(sha256: string, content: Buffer) {diff --git a/locales/en-US/electron.json b/locales/en-US/electron.jsonindex 7bdbf7d02e5..b3c73530750 100644--- a/locales/en-US/electron.json+++ b/locales/en-US/electron.json@@ -119,6 +119,14 @@"remoteServer.statusConnected": "Connected","remoteServer.statusDisconnected": "Not connected","remoteServer.urlRequired": "Please enter the server address",+ "startupUpdate.applying": "Restarting LobeHub…",+ "startupUpdate.checking": "Checking for updates…",+ "startupUpdate.downloading": "Downloading update",+ "startupUpdate.error": "Couldn’t finish the update",+ "startupUpdate.quit": "Quit",+ "startupUpdate.requiredDescription": "This version has a security issue. Update to continue.",+ "startupUpdate.requiredTitle": "Update required",+ "startupUpdate.retry": "Retry","sync.continue": "Continue","sync.inCloud": "Currently using cloud sync","sync.inLocalStorage": "Currently using local storage",diff --git a/locales/zh-CN/electron.json b/locales/zh-CN/electron.jsonindex e0c872b96ee..a990700c4cf 100644--- a/locales/zh-CN/electron.json+++ b/locales/zh-CN/electron.json@@ -119,6 +119,14 @@"remoteServer.statusConnected": "已连接","remoteServer.statusDisconnected": "未连接","remoteServer.urlRequired": "请输入服务器地址",+ "startupUpdate.applying": "正在重新打开 LobeHub…",+ "startupUpdate.checking": "正在检查更新…",+ "startupUpdate.downloading": "正在下载更新",+ "startupUpdate.error": "暂时无法完成更新",+ "startupUpdate.quit": "退出",+ "startupUpdate.requiredDescription": "当前版本存在安全问题,请完成更新后继续使用。",+ "startupUpdate.requiredTitle": "需要更新才能继续",+ "startupUpdate.retry": "重试","sync.continue": "继续","sync.inCloud": "当前使用云端同步","sync.inLocalStorage": "当前使用本地存储",diff --git a/packages/locales/src/default/electron.ts b/packages/locales/src/default/electron.tsindex a92778fda7d..3bbac68c2bd 100644--- a/packages/locales/src/default/electron.ts+++ b/packages/locales/src/default/electron.ts@@ -1,4 +1,13 @@export default {+ 'startupUpdate.requiredTitle': 'Update required',+ 'startupUpdate.requiredDescription': 'This version has a security issue. Update to continue.',+ 'startupUpdate.checking': 'Checking for updates…',+ 'startupUpdate.downloading': 'Downloading update',+ 'startupUpdate.applying': 'Restarting LobeHub…',+ 'startupUpdate.error': 'Couldn’t finish the update',+ 'startupUpdate.retry': 'Retry',+ 'startupUpdate.quit': 'Quit',+'navigation.agentShare': 'Share','navigation.agents': 'Agents','navigation.channels': 'Channels',