Merge remote-tracking branch 'origin/master' into worktree/npm-registry-mirror-config-029a47

# Conflicts:
#	apps/web/tests/expected/plugin-install-cancel/cancelled.expected.md
#	docs/event-producer-consumer.i18n.yaml
#	docs/event-producer-consumer.md
#	docs/event-producer-consumer.zh.md
#	packages/boot/plugin-manager/README.i18n.yaml
#	packages/boot/plugin-manager/README.md
#	packages/boot/plugin-manager/README.zh.md
#	packages/client/ui-plugin-manager/README.i18n.yaml
#	packages/client/ui-plugin-manager/README.md
#	packages/client/ui-plugin-manager/README.zh.md
#	packages/client/ui-plugin-manager/src/client/PluginManagerPage.tsx
This commit is contained in:
Yichen Jiang committed 2026-09-18 20:21:59 +08:00
commit 1dfd026b84
426 files changed
+7353 -1671

No files matched your search

@@ -2,5 +2,5 @@
# side as of the last confirmed-consistent state. Both languages carry equal authority;
# after editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-07-25-web-client-session-scope-and-provide-channel.md
2026-07-25-web-client-session-scope-and-provide-channel.md: 6126d06e48111a551a0dc57247659a3086986c66
2026-07-25-web-client-session-scope-and-provide-channel.zh.md: e7bf4aa6952b4fd7b187c91e2ac5d64aac32cabb
2026-07-25-web-client-session-scope-and-provide-channel.md: 990a9b6eef862a7ac4a549358beae7f9081eaa0b
2026-07-25-web-client-session-scope-and-provide-channel.zh.md: 5c90611fab36611766bb407138c4f0c8a6b3a01b
@@ -63,21 +63,21 @@ Session instances share the scope's lifecycle, while the catalog reports discove
A session "materialized but with no first prompt" is governed by the summary-derived bit `blank` (a derived column, not a header field; SessionHeader stays immutable):
- The host criterion: `session.seq === 0` (zero log events = no user message yet). A live session reads `summarize()` straight from memory; a cold session is always `false` — the JSONL provider's lazy-create contract guarantees a never-appended session never enters `persistence.list()`, so blank never touches disk.
- The Host criterion is absence of `turn/start`; slash-command and configuration events do not clear `blank`. Live summaries use the Session projection. Cold summaries use cached metadata, leaving cache misses visible as unknown. Reuse acquires the writer under [blank Session acquisition](2026-09-17-process-local-blank-sessions.md).
- The wire carries it in two places: the required `SessionSummary.blank` column, and the required `blank` field on the `host/session-added` frame (always true at creation, letting other tabs enter the same blank-session state into their mirrors).
- The client mirror only lowers, never raises (monotonic), flipped from three sources, all reusing existing wire signals:
- The sender's own tab: the **successful response** to the first `prompt()` flips false (acceptance proves the user/message is already in the host log — this flip is confirmation, not optimism; `onEngaged` synchronously updates the list mirror, converting the current `New Session` row in place to an ordinary title, adding no list row). A rejected first prompt keeps the session blank: aligned with host authority, still shown as `New Session`, keeping its connectWorkspace reuse eligibility while it remains a Workspace member.
- Other tabs: the `host/session-status (running:true)` frame flips it — a blank session never runs, so the first running necessarily means no longer blank;
- Reconnect alignment: `session.list`'s summary.blank is authoritative, so a tab that missed frames aligns naturally on its next pull; a stale blank:true can never mark a converted session back to blank.
- List discipline: the store retains every row; the Workspace browser's grouping, flat view, search, and counts share one visible projection — every non-blank session shows, while blank sessions show only the row retained by the `mainView` source, with its title forced to `New Session`. After a Workspace switch, the old blank entity stays in the mirror but is hidden from the list while the target Workspace's main blank shows; the user-visible surface therefore holds at most one blank row globally.
- The residue ledger takes zero GC: after a refresh, blank sessions come back with the bit intact and are reused on the next same-workspace connect while they remain members, so the ordinary single-tab path keeps at most one per workspace; after a host restart, blanks leave no disk trace and simply evaporate; the extra empty shells from multi-tab races only become non-current hidden rows, digested by later reuse, with no coordination.
- Blank Sessions can persist through creation checkpoints and command events. Browser reloads and Host restarts reuse eligible blanks after acquiring their writer; occupied blanks are skipped. Old logs remain on disk without automatic cleanup.
### connectWorkspace: the sole entry point of New Session
`workspaces.connectWorkspace(workspaceId): Promise<SessionId>` (owned by WorkspaceRuntime — it holds both the workspace canonical path and the sessions reference):
- The reuse arm: the list mirror is searched for `blank && cwd == workspace.path && sessionIds.includes(id)` — the host's own membership rule, never cwd alone. A cwd match without the account slot (a CLI/TUI session birthed at the host cwd, or a deleted/recreated registration) would open a session no grouping surface can show under this Workspace, so it falls through to the create arm instead (see the [membership reuse fix](../../archived/bug-fix/2026-08-05-workspace-blank-session-reuse-membership.md)); a hit returns that id directly, creating nothing.
- The create arm: on a miss, `session.create({workspaceId})` returns the new id.
- The reuse arm: the list mirror is searched for `blank && cwd == workspace.path && sessionIds.includes(id)` — the host's own membership rule, never cwd alone. A cwd match without the account slot (a CLI/TUI session birthed at the host cwd, or a deleted/recreated registration) would open a session no grouping surface can show under this Workspace, so it falls through to the create arm instead (see the [membership reuse fix](../../archived/bug-fix/2026-08-05-workspace-blank-session-reuse-membership.md)); a hit is adopted with explicit-id `session.create`, which acquires and retains the writer before returning. Only writer contention skips a candidate.
- The create arm: when no candidate can be acquired, `session.create({workspaceId})` returns the new id.
- An unknown workspaceId fails loud (never silently creating somewhere else).
- The resolution guarantee (one contract for both arms): when the promise resolves, the returned id is already in the list store. The view owner then retains it synchronously, so a draft mover can write text through that binding before history readiness without waiting for a notifier flush.
- The caller takes the id and installs a `mainView` reference; sending the first prompt is an ordinary `session.prompt` — the Session already exists, a failure is an ordinary prompt failure, the draft text is still in the machine, and a retry is simply sending again.
@@ -135,6 +135,6 @@ Blank Sessions retain the header's leading and corner slots so navigation contro
- Plugins gain session context isomorphic to the host's: per-session state hangs on the actx and mounts/tears down in one piece with the scope fiber, making leaks structurally impossible; two-session isolation is structurally guaranteed by the scope filter.
- The client object layer converges to a wire mirror: session identity, lifecycle, and capability adjudication all defer to the host entity — the input system (the next layer) always faces a session with a real Agent, and providers like slash/skill uniformly address by sessionId directly.
- Blank-session governance takes zero dedicated mechanisms: state rides one derived bit, visibility rides the unified list projection (only the current blank shows, as `New Session`), reclamation rides lazy persistence's existing contract (evaporation on restart), and the ordinary ceiling rides same-Workspace reuse.
- Blank-session governance takes zero dedicated mechanisms: state rides one derived bit, visibility rides the unified list projection (only the current blank shows, as `New Session`), reuse acquires the persisted writer, and the ordinary ceiling rides same-Workspace reuse.
- The cost: the id→ctx handoff discipline and provide's Concurrent discipline are conventions rather than type-enforced, pinned by review and tests. The single state axis still withholds machine faces until a Session exists; the [resident conversation shell](../../../../packages/client/ui-conversation/README.md) routes activation to the Workspace picker during that interval.
- Known gaps: approval/question recovery across prune (TODO); model selection returns in live-mutation shape (the host `selectModel` trio is ready-made, its client consumer not yet built).
@@ -63,21 +63,21 @@ Session 实例与 scope 同生命周期;catalog 只报告可发现性,不持
「实体化但无首条提示词」的会话经 summary 派生位 `blank` 治理(派生列而非 header 字段,SessionHeader 保持不可变):
- host 判据:`session.seq === 0`(零日志事件 = 尚无用户消息)。live 会话 `summarize()` 内存直读;cold 会话恒 `false`——JSONL provider 的 lazy-create 约定保证 never-appended 会话不进入 `persistence.list()`,所以 blank 从不落盘。
- Host 判据是没有 `turn/start`;slash 命令与配置事件不会清除 `blank`。Live summary 使用 Session 投影。Cold summary 使用缓存元数据,缓存缺失时以未知状态保留在列表中。复用按[空白 Session 获取](2026-09-17-process-local-blank-sessions.zh.md)规则取得写锁。
- wire 承载两处:`SessionSummary.blank` 必填列;`host/session-added` 帧必填 `blank` 字段(创建时恒 true,供别的 tab 按同一空会话状态入镜像)。
- client 镜像只降不升(单调),三来源翻转,全部复用既有 wire 信号:
- 发送方本地:首次 `prompt()` 的**成功响应**翻 false(受理即证明用户消息已入 host 日志——此点翻转是确证而非乐观;`onEngaged` 同步更新列表镜像,当前 `New Session` 行原地转为普通标题,不新增列表行)。首条提示词被拒则会话保持 blank:与 host 权威对齐、继续显示为 `New Session`、在仍为该工作区成员时保持 connectWorkspace 复用资格。
- 其他端:`host/session-status (running:true)` 帧翻转——blank 会话从不 running,首次 running 必然已非 blank;
- 重连对齐:`session.list` 的 summary.blank 是权威,错过帧的端下次拉取自然对齐;陈旧的 blank:true 不能把已转正的会话重新标回 blank。
- 列表纪律:store 保留全部行;Workspace browser 的分组、平铺、搜索和计数共用同一可见投影——所有非 blank 会话都显示,blank 会话只显示由 `mainView` 来源持有的一行,并强制标题为 `New Session`。切换 Workspace 后,旧 blank 实体仍在镜像中但从列表隐藏,目标 Workspace 的主 blank 显示;因此用户可见面全局至多一条 blank 行。
- 残留账零 GC:刷新后 blank 会话带位回来,下次同 workspace 且仍为成员时复用,普通单端路径使每个 workspace 至多保留一个;host 重启后 blank 无盘痕自然蒸发;多 tab 竞态多出的空壳只会成为非 current 隐藏行,后续复用消化,不做协调。
- 空白 Session 可以通过创建检查点与命令事件持久化。浏览器刷新与 Host 重启会在取得写锁后复用符合条件的空白会话,并跳过被占用的候选。旧日志保留在磁盘上,不自动清理。
### connectWorkspace:New Session 的唯一入口
`workspaces.connectWorkspace(workspaceId): Promise<SessionId>`(归属 WorkspaceRuntime——它同时持有 workspace 规范 path 与 sessions 引用):
- 复用臂:list mirror 中找 `blank && cwd == workspace.path && sessionIds.includes(id)`——host 自己的成员规则,绝不只按 cwd。没有账户槽位的 cwd 匹配(CLI(命令行界面)/TUI 在 host cwd 创建的会话,或已删除/重建的注册)会打开一个任何分组表面都无法显示在该工作区下的会话,因此落到新建臂(见[成员复用修复](../../archived/bug-fix/2026-08-05-workspace-blank-session-reuse-membership.md));命中直接返回该 id,不新建。
- 新建臂:未命中则 `session.create({workspaceId})`,返回新 id。
- 复用臂:list mirror 中找 `blank && cwd == workspace.path && sessionIds.includes(id)`——host 自己的成员规则,绝不只按 cwd。没有账户槽位的 cwd 匹配(CLI(命令行界面)/TUI 在 host cwd 创建的会话,或已删除/重建的注册)会打开一个任何分组表面都无法显示在该工作区下的会话,因此落到新建臂(见[成员复用修复](../../archived/bug-fix/2026-08-05-workspace-blank-session-reuse-membership.md));命中后通过显式 ID 的 `session.create` 收养,在返回前取得并持续持有写锁。仅写锁争用会跳过候选。
- 新建臂:没有可获取的候选时,`session.create({workspaceId})`,返回新 id。
- 未知 workspaceId fail loud(不静默创建到别处)。
- 解析保证(两臂同约定):promise resolve 时返回的 id 已在 list store。视图 owner 随后同步 retain,因此 draft 搬运方可以在历史就绪前通过该 binding 写入文本,无需等待 notifier flush。
- 调用方拿 id 安装一份 `mainView` reference;首条提示词发送就是普通 `session.prompt`——Session 本来就在,失败即普通提示词失败,draft 文本还在 machine 里,重试即再次发送。
@@ -135,6 +135,6 @@ blank Session 保留 header 的 leading 与 corner slot,让右侧栏展开入
- 插件获得与 host 同构的会话上下文:逐会话状态挂 actx、随 scope fiber 一次拆装,泄漏结构性不可能;双会话隔离由 scope filter 结构性保证。
- client 对象层收敛为 wire 镜像:会话身份、生命周期、能力判别全部以 host 实体为准——输入体系(下一层)面对的永远是「有真 Agent 的会话」,slash/skill 等提供方一律以 sessionId 直接寻址。
- 空会话治理零专用机制:状态靠一个派生位,可见性靠统一列表投影(仅 current blank 以 `New Session` 展示),回收靠 lazy persistence 的既有约定(重启蒸发),常规上限靠同 Workspace 复用。
- 空会话治理零专用机制:状态靠一个派生位,可见性靠统一列表投影(仅 current blank 以 `New Session` 展示),复用时获取持久化写锁,常规上限靠同 Workspace 复用。
- 代价:id→ctx 换乘纪律、provide 的 Concurrent 纪律都是约定而非类型强制,靠 review 与测试钉住。单一状态轴仍会在 Session 存在前隐藏 machine face;这段时间内,[常驻会话壳](../../../../packages/client/ui-conversation/README.zh.md)会把激活操作转到 Workspace picker。
- 已知欠账:approval/question 跨 prune 恢复(TODO);模型选择以 live-mutation 形状回归(host `selectModel` 三件套现成,其 client 消费方尚未构建)。
@@ -2,5 +2,5 @@
# side as of the last confirmed-consistent state. Both languages carry equal authority;
# after editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-08-24-browser-token-authentication.md
2026-08-24-browser-token-authentication.md: cdfed1f250de6def39e386cf9fcd2e536c6c97e4
2026-08-24-browser-token-authentication.zh.md: 29f3a6c0a2d83ed1c17b9c0bc5988c9472741f3f
2026-08-24-browser-token-authentication.md: 47d6afe1bf4cd8169eb4e8ec92a30bf0fee32c8a
2026-08-24-browser-token-authentication.zh.md: 13ecf55e41c7bb1455177bdd6a87a3a83d94ca6f
@@ -12,9 +12,9 @@ The Web Host runs tool-capable Sessions with the current operating-system user's
`dsh-client-connection` authenticates the complete Host API before dispatch. Every API Proxy method, Remote unary call, generic Connection channel, and Remote WebSocket stream requires the same browser session; endpoint ownership and method names do not alter authority. The existing Host/Origin checks run first and retain their DNS-rebinding and cross-site-request role, returning 403 when they fail. A trusted Host without a valid browser session receives 401. The browser-trust rules remain owned by the [carrier-level browser trust decision](2026-07-28-api-browser-trust-boundary.md).
Each Host process generates a random launch token, retained by the root application context across Connection hot reloads. `dsh-web-app` prints and opens the normal root URL with that token in the query once per process. `frontend-static` asks Connection to authorize index responses: only `GET /?token=...` exchanges the process token for a cookie, then redirects to clean `/`; the token is not accepted on API paths or in an Authorization header. An obsolete token paired with a valid cookie redirects to clean `/`. Missing and invalid credentials receive one minimal 401 response. Static non-index assets remain public.
Each Host process generates a random launch token, retained by the root application context across Connection hot reloads. `dsh-web-app` prints and opens the normal root URL with that token in the query once per process. `frontend-static` asks Connection to authorize index responses: only `GET /?token=...` exchanges the process token for a cookie, then redirects to clean `./`; the token is not accepted on API paths or in an Authorization header. An obsolete token paired with a valid cookie redirects to clean `./`. Missing and invalid credentials receive one minimal 401 response. Static non-index assets remain public.
The cookie is a signed, authority-bound bearer. Its deterministic name and signed payload both include the normalized hostname plus port, so one Harness home can run independent Web ports without cookie collisions. The payload carries safe-integer issue and expiry times under an absolute lifetime; `cookieMaxAgeDays` defaults to 30. The cookie is host-only, `Path=/`, `HttpOnly`, and `SameSite=Strict`. It omits `Secure` because the shipped server uses loopback HTTP. There is no logout operation or reverse-proxy-specific handling.
The cookie is a signed, authority-bound bearer. Its deterministic name and signed payload both include the normalized hostname plus port, so one Harness home can run independent Web ports without cookie collisions. The payload carries safe-integer issue and expiry times under an absolute lifetime; `cookieMaxAgeDays` defaults to 30. The cookie is host-only, `Path=/`, `HttpOnly`, and `SameSite=Strict`. It omits `Secure` because the shipped server uses loopback HTTP. There is no logout operation.
The HMAC secret is a versioned `grant` record at `client-connection/browser-session` in `ctx.credentials`; the local provider stores it in `$DSH_HOME/.credentials.yaml`. Connection loads or creates the record during activation and retains the secret for synchronous request verification. An active Connection continues using its loaded secret if the durable record changes; the next activation loads the replacement or creates a missing record, so deleting the record and restarting the process revokes every existing cookie. Invalid owner payloads fail loud instead of being replaced. The launch token itself is never persisted and changes on every process start, while an unexpired cookie remains valid across restarts on the same authority.
@@ -12,9 +12,9 @@ Web Host 以当前操作系统用户的权限运行具有工具能力的 Session
`dsh-client-connection` 在分发前认证完整 Host API。每个 API Proxy 方法、Remote 一元调用、通用 Connection channel 和 Remote WebSocket stream 都要求同一个浏览器会话;endpoint 所有权与方法名称不改变 authority。既有 Host/Origin 校验先执行,继续负责 DNS rebinding 和跨站请求防御,失败时返回 403。Host 可信但没有有效浏览器会话时返回 401。浏览器信任规则仍由[载体级浏览器信任决策](2026-07-28-api-browser-trust-boundary.zh.md)持有。
每个 Host 进程生成随机启动令牌,并由应用根 context 跨 Connection 热重载保留。`dsh-web-app` 每个进程只打印并打开一次 query 中带该令牌的普通根 URL。`frontend-static` 请求 Connection 授权 index 响应:只有 `GET /?token=...` 会把进程令牌交换为 cookie,再重定向到干净的 `/`;API 路径和 Authorization header 都不接受该令牌。过时令牌如果同时带有有效 cookie,会重定向到干净的 `/`。缺失与无效凭据得到同一份最小 401 响应。非 index 静态资产保持公开。
每个 Host 进程生成随机启动令牌,并由应用根 context 跨 Connection 热重载保留。`dsh-web-app` 每个进程只打印并打开一次 query 中带该令牌的普通根 URL。`frontend-static` 请求 Connection 授权 index 响应:只有 `GET /?token=...` 会把进程令牌交换为 cookie,再重定向到干净的 `./`;API 路径和 Authorization header 都不接受该令牌。过时令牌如果同时带有有效 cookie,会重定向到干净的 `./`。缺失与无效凭据得到同一份最小 401 响应。非 index 静态资产保持公开。
cookie 是签名且绑定 authority 的 bearer。确定性名称与签名 payload 都包含规范化 hostname 和 port,因此同一 Harness home 可以在不同 Web port 运行而不发生 cookie 冲突。payload 在绝对有效期内携带安全整数形式的签发与过期时间;`cookieMaxAgeDays` 默认为 30。cookie 是 host-only、`Path=/`、`HttpOnly`、`SameSite=Strict`。随附服务器使用 loopback HTTP,因此不设置 `Secure`。这里没有 logout 操作或反向代理专用处理。
cookie 是签名且绑定 authority 的 bearer。确定性名称与签名 payload 都包含规范化 hostname 和 port,因此同一 Harness home 可以在不同 Web port 运行而不发生 cookie 冲突。payload 在绝对有效期内携带安全整数形式的签发与过期时间;`cookieMaxAgeDays` 默认为 30。cookie 是 host-only、`Path=/`、`HttpOnly`、`SameSite=Strict`。随附服务器使用 loopback HTTP,因此不设置 `Secure`。这里没有 logout 操作。
HMAC 密钥是 `ctx.credentials` 中位于 `client-connection/browser-session` 的版本化 `grant` 记录;本地提供方将其存入 `$DSH_HOME/.credentials.yaml`。Connection 在激活期间加载或创建该记录,并保留密钥以同步校验请求。持久记录发生变化后,当前 Connection 继续使用已加载的密钥;下一次激活会加载替换记录或创建缺失记录,因此删除记录并重启进程会撤销全部既有 cookie。无效 owner payload 会明确失败,而不是被覆盖。启动令牌本身绝不持久化并在每次进程启动时变化;未过期 cookie 则能在相同 authority 上跨重启继续有效。
@@ -0,0 +1,6 @@
# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each
# side as of the last confirmed-consistent state. Both languages carry equal authority;
# after editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-09-14-web-document-relative-app-routes.md
2026-09-14-web-document-relative-app-routes.md: fbf30253bbfcc23eb09847f93c1b1f047459d31b
2026-09-14-web-document-relative-app-routes.zh.md: c302ec88a4205239148132513d1ff2a4385033e8
@@ -0,0 +1,47 @@
# Agent Note: Web app-owned routes are document-relative
Status: implemented
English | [中文](2026-09-14-web-document-relative-app-routes.zh.md)
## Problem
Every browser reference to a shell-owned route was origin-root absolute: `/api/...` RPC, `/plugins/??...` plugin bundles, the Remote stream mux, the HMR event stream, and the launch entry's token-cleanup redirect to `/`. One listener served behind a prefix-stripping proxy (a mount such as `https://host/tools/dsh/` that forwards `/tools/dsh/...` as `/...`) therefore saw those requests at the origin root, where no route answers them: the shell, its plugin bundles, and its streams all missed. A single bundle has to serve both the origin root and any mount without a second build.
The mount cannot be recovered from the transport. A configured base URL makes it deployment input, forwarded-prefix inference makes a request header authoritative for routing, and response rewriting in the proxy reimplements the same fact in fragments. The one place that already knows the mount is the served document itself.
## Decision
The served HTTP shell owns its document base. Its index carries exactly one `<base href="./">`, spliced in after the opening head tag once the index taps have run, so it precedes the boot manifest, every plugin-resource row, and any markup a tap inserted. The base freezes the entry directory: `/mount/` and `/mount/index.html` are the supported entries, and a document URL that later moves (an in-page `pushState`) does not move the base. Nothing infers a prefix, so deep direct loads and reloads are not entry points; a bare mount still needs the proxy's own normalization to its slash form.
Browser references to those routes are relative to that document — `api/x`, `plugins/x` — while server route keys stay absolute pathnames: the RPC channel key `/api`, the `webServer` registration paths, and the response tables keyed by the combo route `/plugins/??...&rev=...`. A shared constant that names a key (`*_PATH`, `*_ENDPOINT`) is stripped at the boundary (`KEY.slice(1)`) before browser code uses it, and the browser form lives beside it as `*_ROUTE`.
The Host composes browser references in one place per producer. Module graph rows and batch descriptors carry the document-relative combo reference; the source-map trailer carries the combo query alone, because a script's source-map reference resolves against that script's own directory (`.../plugins/`) rather than the document. The response table stays keyed by the absolute route, which is also what a request reaches after the proxy strips its prefix.
The launch entry follows the same rule. `authenticatedUrl` adds the process token to the caller's URL and keeps its authority and mount, and the token exchange redirects to `./`, which removes the query token while preserving the request URL's directory. The Host/Origin fence and the cookie rules are unchanged.
Consumers that need an absolute URL resolve against `document.baseURI`: the Gateway when it constructs its WebSocket URL and selects `ws:` or `wss:`, and the Inspector when it locates its own bundle from the boot graph.
Desktop is the other document owner. Its window loads `dsh-app://app/`, an origin that serves the same dist at that root and forwards every app-owned path to the shell-owned Host, so its document directory already is the root and no base row is injected for it; it names that Host origin for the Gateway through the transport's `streamBaseUrl` instead. Its resources live at that root, which is also why the served HTTP shell's `./` does not apply to it.
## Alternatives considered
**A configured base URL as the routing base (`publicUrl`).** Rejected: the document already knows its own URL, so this adds a second, drift-prone source for a fact the page can read, and it would have to be plumbed to every consumer instead of one shell decision. The advertised public URL remains an operator-facing print/open input, not a routing input.
**Inferring the mount from a forwarded-prefix header.** Rejected: it makes a request header authoritative for routing, so any client that sets it could move app-owned routes, and the proxy contract becomes server-visible configuration.
**A shared `Connection.resolveUrl` or routes base.** The HTTP carrier's document base and the worker tunnel's Host-root mapping differ. Resolving every target in Connection would prepend a static preview path to worker-local routes or lose a served mount. Each carrier resolves its own targets; UI resource consumers use the document base.
**An absolute `/` redirect with the proxy rewriting `Location`.** Rejected: the browser already knows the request's directory, and a configured redirect target cannot be right for both the loopback entry and a proxy mount.
## Consequences
One bundle serves the origin root and any mount, and the served document is the single source of the mount. The costs are explicit: the supported entries are only the dist root and the configured index path, a bare mount depends on the proxy's slash normalization, and a reload of a deep in-page path re-enters at that path rather than the frozen one.
Routes owned by feature packages (open-in-app, deliverables, session-log export, uploads, markdown media) follow the same rule through their own `*_ROUTE` constants; the static gate that keeps browser sources on this rule is recorded with those changes.
## Testing
The frontend-static real-composition test serves the index through the Loader and asserts one `<base href="./">` that precedes an injected plugin-resource row and tap markup. The client-modules node-half suite asserts that graph rows, batch descriptors, and the source-map trailer are document-relative while the response table still serves them by route, and the client test roster plus the assembled-boot fixture carry the same relative form. `browser-auth.host.spec.ts` covers the `./` redirect and the authority- and mount-preserving `authenticatedUrl`; `frontend-static.spec.ts` and `apps/cli/tests/web-auth.e2e.ts` run the exchange through a real Loader composition and the built CLI.
`apps/web/tests/public-mount.e2e.ts` is the browser proof: a real Chromium reaches one listener through the prefix-stripping proxy, the mounted WebSocket streams both ways, a `pushState` to a deeper path leaves `document.baseURI` at the mount, and a document-relative `fetch('api/session/create')` still succeeds beneath it.
@@ -0,0 +1,47 @@
# Agent Note: Web 应用自有路由相对文档寻址
Status: implemented
[English](2026-09-14-web-document-relative-app-routes.md) | 中文
## 问题
浏览器对外壳自有路由的每一处引用都以源站根绝对形式书写:`/api/...` RPC、`/plugins/??...` 插件 bundle、Remote 流 mux、HMR 事件流,以及启动入口清理 token 时重定向到的 `/`。当一个监听端口位于剥离前缀的代理之后(例如 `https://host/tools/dsh/` 这样的挂载,把 `/tools/dsh/...` 转发为 `/...`),这些请求会落在源站根,那里没有任何路由应答:外壳、插件 bundle、流全部落空。同一份 bundle 必须同时服务源站根与任一挂载,而不能为此再构建一次。
挂载点无法从传输层恢复。配置 base URL 会把它变成部署输入,转发前缀推断会让请求头对路由具有权威性,代理内改写在碎片里重复同一事实。唯一已经知道挂载点的地方,就是所服务的文档自身。
## 决策
所服务的 HTTP 外壳拥有自己的文档 base。其 index 携带唯一的 `<base href="./">`,在原始 index 转换执行后拼接于起始 head 标签之后,因此它先于启动 manifest、每一行插件资源,以及任何转换插入的标记。该 base 冻结入口目录:`/mount/` 与 `/mount/index.html` 是受支持的入口,而文档 URL 之后移动(页面内 `pushState`)不会移动 base。系统不推断任何前缀,因此深层直接加载与重新加载不是入口;裸挂载仍需依赖代理自身的规范化补齐尾部斜杠。
浏览器对这些路由的引用相对该文档——`api/x`、`plugins/x`——而服务端路由键保持绝对路径名:RPC channel 键 `/api`、`webServer` 注册路径,以及以 combo 路由 `/plugins/??...&rev=...` 为键的响应表。命名路由键的共享常量(`*_PATH`、`*_ENDPOINT`)在边界处被剥去前导斜杠(`KEY.slice(1)`)后浏览器代码才使用,浏览器形式以 `*_ROUTE` 与之并列。
宿主在每个生产者里只在一处组合浏览器引用。模块启动图 row 与批次描述符携带文档相对的 combo 引用;source-map trailer 只携带 combo 查询,因为脚本的 source-map 引用相对该脚本自身目录(`.../plugins/`)解析,而非相对文档。响应表仍以绝对路由为键,而请求在代理剥去前缀后到达的也正是该路由。
启动入口遵循同一规则。`authenticatedUrl` 把进程 token 加到调用方的 URL 上并保留其 authority 与挂载;token 交换重定向到 `./`,移除 query token 的同时保留请求 URL 的目录。Host/Origin 栅栏与 cookie 规则不变。
需要绝对 URL 的消费方相对 `document.baseURI` 解析:Gateway 构造 WebSocket URL 并选择 `ws:` 或 `wss:` 时,以及 Inspector 从启动图定位自身 bundle 时。
Desktop 是另一个文档所有者。它的窗口加载 `dsh-app://app/`:该来源在根目录提供同一份 dist,并把其他所有应用路径转发给它拥有的 Host,因此它的文档目录本就是根目录,无需为它注入 base 行;它改为通过传输层的 `streamBaseUrl` 为 Gateway 指定该 Host origin。它的资源就位于该根目录,这也是所服务 HTTP 外壳的 `./` 不适用于它的原因。
## 曾考虑的替代方案
**把配置 base URL 当作路由 base(`publicUrl`)。** 否决:文档已经知道自己的 URL,因此这是为页面本可读取的事实引入第二个易漂移来源,而且必须把它接入每个消费方,而不是只做一次外壳决策。对外公告的公开 URL 仍是面向运维的打印/打开输入,不是路由输入。
**从转发前缀请求头推断挂载点。** 否决:这会让请求头对路由具有权威性,任何设置该头的客户端都能挪动应用自有路由,代理约定也会变成服务端可见的配置。
**共享 `Connection.resolveUrl` 或 routes base。** HTTP 载体的文档基准与 worker tunnel 的 Host 根路径映射不同。在 Connection 中统一解析所有目标,会把静态 preview 路径加到 worker 本地路由之前,或丢失所服务的挂载。各载体解析自己的目标;UI 资源消费方使用文档基准。
**保留绝对 `/` 重定向并让代理改写 `Location`。** 否决:浏览器已经知道请求所在目录,而配置出来的重定向目标无法同时适用于 loopback 入口与代理挂载。
## 后果
一份 bundle 服务源站根与任一挂载,所服务的文档是挂载点的唯一来源。代价是显式的:受支持的入口只有 dist 根与配置的 index 路径;裸挂载依赖代理的斜杠规范化;页面内深层路径重新加载会在该路径重新进入,而非冻结目录。
功能包自有的路由(open-in-app、deliverables、会话日志导出、上传、markdown 媒体)通过各自的 `*_ROUTE` 常量遵循同一规则;让浏览器源码持续遵守该规则的静态门禁随那些改动一并记录。
## 测试
frontend-static 的真实组合测试通过 Loader 提供 index,并断言唯一的 `<base href="./">` 先于注入的插件资源行与转换标记。client-modules node 半侧测试断言启动图 row、批次描述符与 source-map trailer 均为文档相对,而响应表仍按路由提供它们,客户端测试 roster 与 assembled-boot fixture 携带同一相对形式。`browser-auth.host.spec.ts` 覆盖 `./` 重定向与保留 authority 和挂载的 `authenticatedUrl`;`frontend-static.spec.ts` 与 `apps/cli/tests/web-auth.e2e.ts` 分别经真实 Loader 组合与构建后的 CLI 运行该交换。
`apps/web/tests/public-mount.e2e.ts` 是浏览器证据:真实 Chromium 经剥离前缀的代理到达同一监听端口,挂载下的 WebSocket 双向成流,`pushState` 到更深路径后 `document.baseURI` 仍停在挂载点,而文档相对的 `fetch('api/session/create')` 在其下依然成功。
@@ -0,0 +1,6 @@
# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each
# side as of the last confirmed-consistent state. Both languages carry equal authority;
# after editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-09-17-process-local-blank-sessions.md
2026-09-17-process-local-blank-sessions.md: 58d222185ae67c1f70874c0d0a73910eaa1e0e5b
2026-09-17-process-local-blank-sessions.zh.md: 0f3fdf050931d11a80e92d98577ac8b42628bb60
@@ -0,0 +1,35 @@
# Agent Note: Writer acquisition for blank Session reuse
Status: implemented
English | [中文](2026-09-17-process-local-blank-sessions.zh.md)
## Problem
Two Hosts sharing Session storage can select the same blank Session when opening a Workspace. A blank Session already owns a live Agent, accepts slash commands, and can hold its writer lock after the creation checkpoint. An unowned persisted blank also carries command settings that remain useful after a Host restart.
## Decision
The Session catalog includes persisted blanks. Startup restoration selects the saved blank; ordinary Workspace navigation selects the first eligible unarchived member in catalog order. Explicit-id `session.create` resumes that Session and acquires its writer before opening history. Only `session/writer-held` triggers creation of a new Session. Other errors propagate. Concurrent Workspace connects in one Client share the acquisition and fallback. Later navigation cancels a pending startup selection.
The Agent retains the acquired handle throughout its lifetime. Checking ownership and releasing a probe lock would leave a race before resume. No PID or process identity enters persisted data or the Remote schema.
This decision extends the blank-reuse policy in the [Client Session scope decision](2026-07-25-web-client-session-scope-and-provide-channel.md); its real-Session slash support and Provider adoption rationale remain active.
## Alternatives considered
**Client-only drafts.** Slash commands and Session-scoped plugins require a real Session before the first prompt. Deferring creation requires a separate command lifecycle.
**Release a live blank's writer lock.** Blank means no `turn/start`, not no events. A live Agent can still append command and configuration events, so releasing its lock permits competing writers.
**Hide every cold blank.** This discards reusable command settings from navigation and creates another blank after every restart, even when the old writer is free.
**Persist a creator PID.** Kernel writer ownership already arbitrates acquisition. PID reuse and stale creator records add no authority.
## Consequences
A Host can reuse its own live blank or reclaim an unowned persisted blank with its slash state. Separate Hosts create distinct blanks while existing writers remain held. A held selected blank causes fresh creation even when another blank is free; navigation does not search for another candidate. No cleanup is added. Opening the same established conversation from two Hosts can still encounter writer contention. Unknown projection hints remain visible without cold body scans; automatic reuse requires known blank metadata. A non-contention acquisition failure aborts New Session and is currently reported only to the console; hidden blanks have no recovery action in this flow.
## Verification
Navigation tests cover saved selection, single-candidate contention fallback, non-contention failures, overlapping acquisition, and superseding navigation. A shipped Web-composition test holds a real persistence writer, verifies fresh creation despite another free blank, and reclaims the released selected blank with its plan state. The fresh-round-trip recorded Session scenario reloads its blank before submitting the recorded prompt.
@@ -0,0 +1,35 @@
# Agent Note: 复用空白 Session 时获取写锁
Status: implemented
[English](2026-09-17-process-local-blank-sessions.md) | 中文
## Problem
两个共享 Session 存储的 Host 在打开 Workspace 时可能选中同一个空白 Session。空白 Session 已有活动 Agent,可以接受 slash 命令,并且可能在创建检查点后持有写锁。无人占用的持久化空白会话也可能带有 Host 重启后仍有用的命令设置。
## Decision
Session 列表包含持久化空白会话。启动恢复选择已保存的空白会话;普通 Workspace 导航按列表顺序选择第一个符合条件且未归档的成员。显式 ID 的 `session.create` 会恢复该 Session,并在打开历史前取得写锁。只有 `session/writer-held` 会触发新建 Session。其他错误返回调用方。同一 Client 的并发 Workspace 连接共享获取与回退过程。后续导航会取消尚未完成的启动选择。
Agent 在整个生命周期内持有取得的句柄。检查占用后释放探测锁,会在恢复前留下竞态。持久化数据与 Remote schema 均不引入 PID 或进程身份。
本决策扩展 [Client Session scope 决策](2026-07-25-web-client-session-scope-and-provide-channel.zh.md)中的空白会话复用策略;其真实 Session 支持 slash 以及 Provider 收养的理由仍然有效。
## Alternatives considered
**纯客户端草稿。** Slash 命令与 Session 作用域插件在首条提示词之前就需要真实 Session。延迟创建需要单独的命令生命周期。
**释放活动空白会话的写锁。** Blank 表示没有 `turn/start`,并不表示没有事件。活动 Agent 仍可能追加命令与配置事件,因此释放其锁会允许多个写入方竞争。
**隐藏所有冷空白会话。** 这会让导航丢失可复用的命令设置,并且每次重启都创建另一空白会话,即使旧写锁已空闲。
**持久化创建者 PID。** 内核写锁已能仲裁获取操作。PID 复用与过时的创建者记录无法增加权威性。
## Consequences
Host 可以复用自己的活动空白会话,也可以接管无人占用的持久化空白会话并保留其 slash 状态。现有写锁被持有时,不同 Host 创建不同的空白会话。所选空白会话被占用时,即使另有空闲空白会话也会新建;导航不再寻找其他候选。不增加清理逻辑。两个 Host 打开同一个已有对话时仍可能遇到写锁争用。未知投影提示仍可见且不扫描冷日志正文;自动复用要求已知的空白元数据。非锁争用的获取错误会中止新建会话,目前只报告到控制台;此流程没有针对隐藏空白会话的恢复操作。
## Verification
导航测试覆盖已保存选择、单候选锁争用回退、其他错误、重叠获取以及后续导航替代。实际 Web 组合测试持有真实持久化写锁,验证另有空闲空白会话时仍新建,并接管已释放的所选空白会话及其 plan 状态。fresh-round-trip 的录制 Session 场景在提交已录制的提示词前刷新空白会话。
@@ -2,5 +2,5 @@
# side as of the last confirmed-consistent state. Both languages carry equal authority;
# after editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write .agents/notes/implemented/feature/2026-09-07-composer-session-stats-pills.md
2026-09-07-composer-session-stats-pills.md: d165aab471bc5958cb7a0b287d278a0ae48485ee
2026-09-07-composer-session-stats-pills.zh.md: dac136d4e60e50b026ed082eb7a006a80059c328
2026-09-07-composer-session-stats-pills.md: 50d3d3294ed012773657ba9849e45835c361d8be
2026-09-07-composer-session-stats-pills.zh.md: 97b91b601e62e8b06ab13a764babb4dd3b25bfce
@@ -10,6 +10,8 @@ The session stats strip under the composer (`StatsLine`, ui-chat, mounted on `co
## Decision
The [performance and usage preference](2026-09-16-performance-usage-preference.md) governs statistic visibility and removes the completed-turn elapsed-time action.
`StatsPills` (packages/client/ui-chat/src/client/chat/StatsPills.tsx) replaces `StatsLine` on the same `conversation.composer.dock` slot; the losing variant is deleted, its shared helpers (`deriveStats`, `formatDuration`, `cacheHitPercent`, `billedInputTokens`) absorbed into the new module, and the dead `stats.llm`, `stats.toolCall`, `stats.ttftAverage`, `stats.tokensPerSecond`, and `stats.tokens` locale keys removed.
- **Two icon pills, two dialogs.** A gauge pill (new `IconGaugeOutlineRegular`, dial center optically dropped to y=8.75 because the bottom-open arc reads high) shows `{turns} 轮 {steps} 步` plus output TPS and click-opens the 会话统计 dialog (LLM time, tool time, average TTFT, TPS); a log with no timed figure would open an empty dialog, so that pill renders as a static reading instead of a button. A database pill (`IconDatabaseOutlineRegular`) shows the compact billed total plus cache-hit share and click-opens the Token 用量 dialog (cache hit, uncached input, cache read, output, and cache write when non-zero — exact counts). Both dialogs wear the shared `stat-dialog` module (portal panel, anchored placement, outside-dismiss, optionally externally owned open state) extracted for exactly this two-consumer split; the pills row owns one exclusive open slot, so opening either dialog closes the other, and each button carries an explicit `aria-label` that separates with ` · ` the segments the aria-hidden sep glyph joins visually. [StatsPills](../../../../packages/client/ui-chat/src/client/chat/StatsPills.tsx) owns the zero cache-write omission.
@@ -10,6 +10,8 @@ Status: implemented
## 决定
[性能与用量偏好](2026-09-16-performance-usage-preference.zh.md)管理统计可见性,并移除已完成轮次的耗时操作。
`StatsPills`(packages/client/ui-chat/src/client/chat/StatsPills.tsx)在同一 `conversation.composer.dock` 插槽上取代 `StatsLine`;落选变体已删除,其共享工具函数(`deriveStats`、`formatDuration`、`cacheHitPercent`、`billedInputTokens`)并入新模块,废弃的 `stats.llm`、`stats.toolCall`、`stats.ttftAverage`、`stats.tokensPerSecond`、`stats.tokens` 文案键一并移除。
- **两个图标 pill、两个弹层。** 仪表盘 pill(新增 `IconGaugeOutlineRegular`,因下开口圆弧视觉偏高而把表盘中心光学下移到 y=8.75)展示 `{turns} 轮 {steps} 步` 加输出 TPS,点击打开「会话统计」弹层(模型用时、工具调用用时、首 token 平均、输出速度);日志里没有任何计时数字时弹层会是空的,此时该 pill 渲染为静态读数而非按钮。数据库 pill(`IconDatabaseOutlineRegular`)展示紧凑计费总量加缓存命中率,点击打开「Token 用量」弹层(缓存命中、未缓存输入、缓存读取、输出,以及非零时的缓存写入——精确计数)。两个弹层共用为这两处消费者抽出的 `stat-dialog` 模块(portal 面板、锚定定位、点击外部关闭、可选的外部持有开合状态);pill 行持有唯一的互斥开合槽位,打开任一弹层即关闭另一个,且每个按钮携带显式 `aria-label`,用 ` · ` 分隔 aria-hidden 分隔符在视觉上连接的两段文本。[StatsPills](../../../../packages/client/ui-chat/src/client/chat/StatsPills.tsx)负责缓存写入为零时省略该行的规则。
@@ -2,5 +2,5 @@
# side as of the last confirmed-consistent state. Both languages carry equal authority;
# after editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write .agents/notes/implemented/feature/2026-09-08-feedback-dialog-and-categories.md
2026-09-08-feedback-dialog-and-categories.md: ee656946a9e5d2921a02a1b642041e5965661f31
2026-09-08-feedback-dialog-and-categories.zh.md: ef2b2d4670aad12398125925dd1e1a7e7c10a5f0
2026-09-08-feedback-dialog-and-categories.md: 1d544e6ef978c10008ac62768b6faaf9eaaf8b73
2026-09-08-feedback-dialog-and-categories.zh.md: 6e58820bf308a3a9f7d15b64027f90e7e6771bd4
@@ -14,10 +14,14 @@ The Web client had two disconnected feedback paths with no visible outcome. `/fe
`ui-message-feedback` becomes the Web feedback surface. A per-session `FeedbackSurface` owns the message-feedback controller, a `FeedbackDialogController` for the draft, the submission, and the toast sequence, and the routing between them: a message target puts its selected judgment with the dialog's category and note through the message controller, while the Session target records through `ctx.remote.sessionFeedback`. A `FeedbackDialog` entry of `conversation.input.overlay` renders the Modal and Toast primitives from the dialog store. A decoration on the Host's `feedback` command opens the dialog for the Session from a menu pick or a bare Enter while `/feedback <text>` still reaches the Host; it uses the `action` kind in `CommandUiSpec`, which consumes the trigger token and runs a client callback without submitting anything. The later [symmetric message feedback submission](2026-09-10-symmetric-message-feedback-submission.md) decision owns the rating entry rule: either unrecorded rating opens the dialog, while clicking the recorded rating retracts it. The note popover, `clearNote`, and `clear` remain absent because the dialog is the only note editor.
The Session Header's more-actions menu also opens the Session dialog through the `feedbackUi.openSession` Client service. The menu remains owned by `session-log-export`, while the existing per-session feedback controller owns the draft and submission. An observable tracks the optional feedback plugin's availability, so unloading feedback removes only its menu row and leaves export usable. Opening or dismissing the form writes no feedback event; Submit records one Session remark.
The dialog is the shared Modal card at the design's width; the design's checkbox for including the conversation log is not built, because the log travels with every feedback event and is not optional. An oversized description still fails on submit with `note-too-large`; the dialog stays open with its draft and a warning toast presents the localized failure.
## Alternatives considered
**A child slot for Header menu actions.** A slot would let each plugin own its menu row, but requires a shared menu-item API beyond the feedback entry requested in #4445. The optional `feedbackUi` service keeps this change local while leaving dialog state and submission in the feedback plugin.
**Encode the category into the note text.** A prefix in free text is not filterable without parsing and would leak into the verbatim note that telemetry uploads; a durable id in the payload is what a consumer can group by.
**Submit the dialog through the command plane as `/feedback <text>`.** The command rejects empty text, cannot carry a category, and writes an acknowledgement row the design replaces with a toast; the Remote records the same event with neither constraint.
@@ -14,10 +14,14 @@ Web 客户端有两条互不相连的反馈路径,且都没有可见结果。`
`ui-message-feedback` 成为 Web 反馈界面。每个 Session 一个 `FeedbackSurface`,拥有消息反馈控制器、负责草稿、提交与 toast 序号的 `FeedbackDialogController`,以及两者之间的路由:消息目标经消息控制器 put 一条带弹窗分类与备注的所选评分,Session 目标经 `ctx.remote.sessionFeedback` 记录。`conversation.input.overlay` 的 `FeedbackDialog` 条目从弹窗 store 渲染 Modal 与 Toast 基元。宿主 `feedback` 命令上的装饰让菜单选中或不带参数的回车为 Session 打开弹窗,而 `/feedback <text>` 仍到达宿主;它使用 `CommandUiSpec` 中的 `action` 种类:裸调用消费触发 token 后运行一个客户端回调,不提交任何内容。后续的[对称消息反馈提交](2026-09-10-symmetric-message-feedback-submission.zh.md)决策拥有评分入口规则:任一未记录的评分都会打开弹窗,再次点击已记录的评分则撤回。备注浮层、`clearNote` 与 `clear` 继续保持移除,因为弹窗是唯一的备注编辑器。
会话标题栏的更多操作菜单也通过 `feedbackUi.openSession` Client 服务打开 Session 弹窗。菜单仍由 `session-log-export` 持有,现有的逐 Session 反馈控制器持有草稿与提交。一个可观察值跟踪可选反馈插件的可用状态,因此卸载反馈插件只移除其菜单行,导出仍然可用。打开或关闭表单不写反馈事件;点击提交才记录一条 Session 反馈。
弹窗是共用的 Modal 卡片,宽度按设计稿;设计稿里「包括当前对话的日志」复选框不做,因为日志随每个反馈事件一起投递,不是可选项。超长描述仍在提交时以 `note-too-large` 失败;弹窗保留草稿并通过警告 toast 展示本地化错误。
## 考虑过的替代方案
**为标题栏菜单动作声明子 slot。** slot 可以让每个插件持有自己的菜单行,但需要共享菜单项 API,超出 #4445 所需反馈入口的范围。可选的 `feedbackUi` 服务将改动限制在局部,同时让弹窗状态与提交继续由反馈插件持有。
**把分类编进备注文本。** 自由文本里的前缀不解析就无法过滤,还会混进遥测上传的原样备注;载荷里的持久 id 才是消费方能分组的东西。
**让弹窗经命令平面以 `/feedback <text>` 提交。** 命令拒绝空文本、带不了分类,还会写一行设计稿已用 toast 取代的确认;Remote 记录同一个事件且没有这两个约束。
@@ -2,5 +2,5 @@
# side as of the last confirmed-consistent state. Both languages carry equal authority;
# after editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write .agents/notes/implemented/feature/2026-09-08-present-workspace-source-files.md
2026-09-08-present-workspace-source-files.md: e1bc2bbc56d423741ca53550af2879fed3f01ecf
2026-09-08-present-workspace-source-files.zh.md: e4f21172b36a5fef50e44a79adca71011ee90a3b
2026-09-08-present-workspace-source-files.md: 52cc3e9cdbcd30d378117a327b86062523a2cb3e
2026-09-08-present-workspace-source-files.zh.md: 99b7b9df1d9ca2da2175df1ae7e9d8acbb5c5fdd
@@ -12,7 +12,7 @@ Users need to open and edit the files produced in their workspace, including she
The [present tool](../../../../packages/deliverables/tool-present/README.md) declares existing regular source files under the [Session filesystem access policy](2026-09-09-present-filesystem-access.md). It records paths and optional descriptions without reading or copying contents. The [deliverables plugin](../../../../packages/client/ui-deliverables/README.md) opens current workspace sources in the Host's default application. Edits are visible on the next open; deletion or movement makes the declaration unavailable. File-content preservation and copy-on-write storage are deferred until a persistence design owns them.
The tool description requires `present` after writing a file the user asked to receive and before the final response, including files created through Bash or code execution. A prose path reference does not replace the call. The recorded [SVG delivery scenario](../../../../snapshots/web/present-svg/snapshot.yml) uses a user request that does not name `present`, and checks the resulting file, delivery event, and card. Its UI snapshot covers the expanded Chat transcript; navigation and composer controls belong to their own scenarios, so unrelated chrome changes cannot invalidate file-delivery expectations.
The [tool description](../../../../packages/deliverables/tool-present/README.md#model-experience) guides the model's choice of files for explicit delivery. A declaration remains distinct from a prose file reference. The recorded [SVG delivery scenario](../../../../snapshots/web/present-svg/snapshot.yml) covers the resulting file, delivery event, and card. New recordings explicitly request a separate file card; replay preserves the recorded request. This scenario verifies explicit delivery, not a requirement to call `present` for every SVG. Its UI snapshot covers the expanded Chat transcript; navigation and composer controls belong to their own scenarios, so unrelated chrome changes cannot invalidate file-delivery expectations.
The tool remains an ordinary package with shared filesystem and tool error classes. Its pure type entry owns the delivery event without importing Host code into the browser. The `standard`, `ptc`, and `cordis` presets mount it; `minimal` retains its two tools. Each plugin instance correlates its executions with successful final `tools/result` notifications before appending `deliverables/presented`. Native and nested calls share this rule. A later enclosing program failure does not revoke a completed nested declaration; blocked results publish none, and same-name scoped replacements cannot publish another instance's results.
@@ -12,7 +12,7 @@ Status: implemented
[present 工具](../../../../packages/deliverables/tool-present/README.zh.md)声明交付[Session 文件系统访问策略](2026-09-09-present-filesystem-access.zh.md)允许的已有普通源文件。它记录路径和可选说明,不读取或复制内容。[交付插件](../../../../packages/client/ui-deliverables/README.zh.md)使用 Host 默认应用打开当前工作区源文件。下次打开会看到编辑后的内容;删除或移动文件会使声明不可用。文件内容保留与写时复制存储延期到有持久化设计负责时实现。
工具说明要求在写好用户要求接收的文件后、最终回复前调用 `present`,包括通过 Bash 或代码执行创建的文件。正文中的路径引用不能替代调用。录制的 [SVG 交付场景](../../../../snapshots/web/present-svg/snapshot.yml)使用未提及 `present` 的用户请求,检查生成文件、交付事件和卡片。其 UI 快照覆盖展开后的 Chat 对话内容;导航和输入框控件由各自场景负责,避免无关界面改动使文件交付预期失效。
[工具说明](../../../../packages/deliverables/tool-present/README.zh.md#model-experience)指导模型选择需要显式交付的文件。交付声明与正文中的文件引用各自独立。录制的 [SVG 交付场景](../../../../snapshots/web/present-svg/snapshot.yml)覆盖生成文件、交付事件和卡片。新录制明确请求独立文件卡片,回放保留录制时的请求。该场景验证显式交付,不要求所有 SVG 都调用 `present`。其 UI 快照覆盖展开后的 Chat 对话内容;导航和输入框控件由各自场景负责,避免无关界面改动使文件交付预期失效。
工具保持为普通包,共享文件系统和工具错误类型。其纯类型入口拥有交付事件,不向浏览器导入 Host 代码。`standard`、`ptc` 与 `cordis` preset 挂载工具;`minimal` 保持两个工具。每个插件实例将其执行与成功的最终 `tools/result` 通知关联,再追加 `deliverables/presented`。原生与嵌套调用遵循同一规则。外层程序随后失败不会撤销已完成的嵌套声明;被阻止的结果不发布声明,同名作用域替换也不能发布其他实例的结果。
@@ -0,0 +1,6 @@
# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each
# side as of the last confirmed-consistent state. Both languages carry equal authority;
# after editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write .agents/notes/implemented/feature/2026-09-16-open-in-default-app-for-sidebar-files.md
2026-09-16-open-in-default-app-for-sidebar-files.md: fa7506be77e8a62e5dfd97b59de6ebc4be510ae0
2026-09-16-open-in-default-app-for-sidebar-files.zh.md: af124182dc1b38658ff55736277e499e963a6281
@@ -0,0 +1,29 @@
# Agent Note: Open Sidebar-previewed files in the default application
Status: implemented
English | [中文](2026-09-16-open-in-default-app-for-sidebar-files.zh.md)
## Problem
Opening a file in its Host default application or showing it in the file manager existed only on the delivery cards, through routes and a fetch controller private to `ui-deliverables` and addressed by Session, declaration-event sequence, and file index. The right Sidebar's document preview offered no native handoff: a video, an archive, an office document, a file the reader rejected as non-text, or an oversized file dead-ended on an explanation, with Retry as the only control even where a second read could not help (issue #3932). Those files have no delivery event to address, so the existing plumbing could not serve a second surface. A first implementation (PR #4120, by Yifffan) added a new `ui-open-locally` package with its own Host routes and moved the delivery cards onto it; product review asked instead that file opening live in the existing open-in-app feature and accepted an intermediate state for this iteration.
## Decision
[ui-open-in-app](../../../../packages/client/ui-open-in-app/README.md) owns the browser controls. The document preview of [ui-sidebar-documentpreview](../../../../packages/client/ui-sidebar-documentpreview/README.md) declares two Session-scoped list child slots whose owner props carry the file’s absolute execution-environment path, rendered only once the file's metadata reports that path: `sidebar.right.tab.document.actions` after the header's own controls, in every state that shows the header, and `sidebar.right.tab.document.unpreviewable` where Retry would stand. The preview classifies an empty-state read failure: `not-text` and `too-large` are readable files the preview cannot render and offer the unpreviewable slot; `not-found` and `not-regular-file` offer only their explanation; every other failure keeps Retry because a second read may resolve it. The unsupported-suffix empty state, which never reads, offers the same slot.
ui-open-in-app fills both slots: an "Open ▾" split button whose main button opens the file in the default application and whose menu adds the file-manager reveal, and an "Open in default app" empty-state button. Neither control renders until the Host answered that a desktop exists. The controls call the Session Remote the Host already publishes, `session.canOpenWorkspacePath` once per page and `session.openWorkspacePath` per gesture with the absolute path and, for reveal, `action: 'reveal'`; no new Host route exists. Both controls share one gesture hook: only the control the user pressed disables while its call settles, a failed call resolves as a failure kind, and that control announces it once through a transient toast, so no failure state persists on a control.
## Alternatives considered
**A new `ui-open-locally` package with its own Host routes** (PR #4120) is where the slot pair, the failure classification, the split-button design, and the toast rule come from. It was set aside because the repository already has an open-in-app feature and a second package for opening things locally duplicates it; the shared Session Remote owns verification of the Host path through the composed filesystem.
**Host routes in `dsh-host-open-in-app`** serving desktop facts and a path open would let the Host name the file manager and distinguish a missing file from a failed launch. They would make the Host half depend on `sessionController`, `workspaceFiles`, and `fs` for two calls the Session Remote already publishes, so the Remote is used directly and the reveal label stays generic.
**Moving the delivery cards onto these controls now** would repeat the largest part of PR #4120, including the cross-plugin runtime import its review rejected and the recorded delivery scenarios it had to migrate. The cards keep their own routes this iteration.
## Consequences
Every previewed file with a verified Host mapping can be opened locally from the Sidebar, including files that were never delivered. Paths without that mapping are refused before native opening. The delivery cards and the preview run two openers over one Host capability; unifying them, and deciding per surface between the full application list and the default application only, is the next step the product direction names. The reveal menu item says "Show file location" on every platform because the Session Remote reports no file manager. Default-application open carries the Host's file-association execution semantics for what it opens; the guard is the explicit user gesture on a file the Session can already read, and no new Host authority was granted.
Unit tests cover the failure classification, the preview's rendering of each recourse and its withholding of the seats before a Host path is known, the path controller's desktop read and gesture outcomes, both controls' visibility, busy isolation, and toast, and the plugin's registration and fiber-disposal removal. The keyless Web document-preview scenario drives the unsupported-suffix controls against a stubbed opener on POSIX hosts, and the seeded-history file-preview golden pins the header control.
@@ -0,0 +1,29 @@
# Agent Note:用默认应用打开 Sidebar 预览的文件
Status: implemented
[English](2026-09-16-open-in-default-app-for-sidebar-files.md) | 中文
## 问题
用 Host 默认应用打开文件、或在文件管理器中显示文件,此前只存在于交付卡片上,走的是 `ui-deliverables` 私有的路由与 fetch 控制器,按 Session、声明事件序号和文件下标定位。右侧 Sidebar 的文档预览没有任何本地交接:视频、压缩包、office 文档、被读取器判为非文本的文件、过大的文件,都停在一行说明上,唯一的控件是重试,哪怕再读一次也无济于事(issue #3932)。这些文件没有交付事件可供定位,所以现有管线无法服务第二个界面。第一版实现(PR #4120,作者 Yifffan)新增了 `ui-open-locally` 包,自带 Host 路由,并把交付卡片也迁了过去;产品评审要求改为把文件打开放进现有的 open-in-app 功能,并接受本期先落一个中间态。
## 决定
[ui-open-in-app](../../../../packages/client/ui-open-in-app/README.zh.md) 拥有浏览器侧的控件。[ui-sidebar-documentpreview](../../../../packages/client/ui-sidebar-documentpreview/README.zh.md) 的文档预览声明两个 Session 作用域的 list 子 slot,owner props 携带文件在执行环境中的绝对路径,只在文件元数据报出该路径后渲染:`sidebar.right.tab.document.actions` 在每个显示头部的状态里跟在头部自有控件之后,`sidebar.right.tab.document.unpreviewable` 占据原本放重试的位置。预览对空态的读取失败分类:`not-text` 与 `too-large` 是可读但预览无法渲染的文件,提供 unpreviewable slot;`not-found` 与 `not-regular-file` 只给说明;其余失败保留重试,因为再读一次可能解决。不支持后缀的空态不发起读取,提供同一个 slot。
ui-open-in-app 填满这两个 slot:一个「打开 ▾」分体按钮,主按钮用默认应用打开文件,菜单再加文件管理器定位;一个空态的「用默认应用打开」按钮。Host 回答有桌面之前,两个控件都不渲染。控件调用 Host 早已发布的 Session Remote:每页调用一次 `session.canOpenWorkspacePath`,每个手势调用一次 `session.openWorkspacePath`,带上绝对路径,定位时再带 `action: 'reveal'`;没有新增任何 Host 路由。两个控件共用一个手势 hook:只有用户按下的那个控件在调用结算期间禁用,失败的调用解析为一个失败种类,由该控件通过短暂 toast 提示一次,控件上不残留失败状态。
## 考虑过的备选
**新建自带 Host 路由的 `ui-open-locally` 包**(PR #4120)是这对 slot、失败分类、分体按钮设计和 toast 规则的来源。放弃它是因为仓库已经有 open-in-app 功能,再来一个负责本地打开的包属于重复;共享的 Session Remote 负责通过当前文件系统验证 Host 路径。
**在 `dsh-host-open-in-app` 里加 Host 路由**提供桌面信息和按路径打开,能让 Host 报出文件管理器的名字,并区分文件不存在和启动失败。但这会让 Host 半边为了 Session Remote 已经发布的两个调用而依赖 `sessionController`、`workspaceFiles` 与 `fs`,所以直接使用 Remote,定位标签保持通用说法。
**现在就把交付卡片迁到这些控件上**会重做 PR #4120 里最大的那部分,包括评审否决的跨插件运行时导入,以及它不得不迁移的交付录制场景。本期卡片保留自己的路由。
## 后果
每个有经过验证的 Host 映射的预览文件都能从 Sidebar 本地打开,包括从未交付过的文件。没有这种映射的路径会在原生打开前被拒绝。交付卡片和预览在同一项 Host 能力上跑着两套打开器;把它们统一起来,并按界面决定展示完整应用列表还是只展示默认应用,是产品方向点名的下一步。定位菜单项在所有平台都写「显示文件位置」,因为 Session Remote 不报告文件管理器。用默认应用打开带有 Host 文件关联的执行语义;护栏是用户对 Session 已可读文件的明确手势,没有授予任何新的 Host 权限。
单元测试覆盖失败分类、预览对每种出路的渲染以及在 Host 路径未知时对座位的保留、路径控制器的桌面读取与手势结果、两个控件的可见性、忙碌隔离与 toast,以及插件的注册与 fiber 释放时的移除。无密钥的 Web 文档预览场景在 POSIX 主机上用桩打开器驱动不支持后缀的控件,seeded-history 的文件预览 golden 固定住头部控件。
@@ -0,0 +1,6 @@
# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each
# side as of the last confirmed-consistent state. Both languages carry equal authority;
# after editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write .agents/notes/implemented/feature/2026-09-16-performance-usage-preference.md
2026-09-16-performance-usage-preference.md: 36ab30561fccc6c824ee8483f5a533a9178f11c5
2026-09-16-performance-usage-preference.zh.md: ecfd19c41c861116d18829b355bf8c8df4ea929a
@@ -0,0 +1,31 @@
# Agent Note: Performance and usage detail preference
Status: implemented
English | [中文](2026-09-16-performance-usage-preference.zh.md)
## Problem
Always-visible counts and accounting controls add density to Chat even when readers only need output speed and cache effectiveness.
## Decision
Chat owns `ui-chat.performanceUsage` in its existing settings namespace. General Settings offers Compact and Detailed, with Detailed as the default to preserve access to accounting. Both the composer and turn-tail renderer consume the same accepted settings source through framework-bound hooks. Host settings own persistence, validation, and failed-write recovery.
Compact retains only available output speed and cache-hit percentage under the composer. These readings are plain text with no statistics dialog. Detailed retains session statistic dialogs and per-Turn usage. Neither mode renders the elapsed-time action in the completed-turn footer. This preference changes presentation, never telemetry collection, accounting, or Session events.
The [composer statistics decision](2026-09-07-composer-session-stats-pills.md) remains authoritative for accounting sources, dialog exclusivity, and composer spacing in Detailed mode.
The requested footer design prioritizes message actions and token accounting in both modes. Completed turns therefore expose no per-turn elapsed-time control; Detailed restores accounting detail, not that control. The running clock and session-wide timing statistics remain independent of this choice.
## Alternatives considered
**Default to Compact.** This would hide accounting controls for existing users without an explicit choice. The request defines both modes but no default, so Detailed preserves their access.
**Filter telemetry when Compact is selected.** This would discard information needed after switching to Detailed or reopening history. A display preference must not change recorded data.
## Consequences
Unavailable speed or cache-hit data is omitted rather than replaced with invented values. The settings scope provides one accepted value to all consumers without duplicating subscription state. Component coverage checks mode-specific visibility; the [recorded-session browser scenario](../../../../apps/web/tests/message-actions.e2e.ts) exercises selection, reload persistence, and Compact output.
On non-loopback browsers, the preference remains process-local because the settings scope cannot persist writes. Explicit selections update every consumer immediately; accepted Host settings reconcile the live value on loopback browsers.
@@ -0,0 +1,31 @@
# Agent Note:性能与用量详细程度偏好
Status: implemented
[English](2026-09-16-performance-usage-preference.md) | 中文
## Problem
当读者只需要输出速度和缓存效果时,始终显示的计数和记账控件会增加聊天界面的密度。
## Decision
Chat 在既有设置命名空间中拥有 `ui-chat.performanceUsage`。通用设置提供简洁和详细选项,默认详细以保留记账入口。输入框和轮次页脚渲染器通过框架绑定的 Hook 消费同一个已接受设置源。Host 设置负责持久化、校验和写入失败恢复。
简洁模式仅在输入框下方保留可用的输出速度和缓存命中率。这些读数为纯文本,不提供统计卡片。详细模式保留会话统计卡片和每轮用量。两种模式均不渲染已完成轮次页脚中的耗时操作。该偏好只改变展示,不改变遥测收集、记账或 Session 事件。
[输入框统计决策](2026-09-07-composer-session-stats-pills.zh.md)仍负责详细模式中的记账来源、卡片互斥和输入框间距。
所要求的页脚设计在两种模式下均优先展示消息操作和 token 记账。因此,已完成轮次不提供单轮耗时控件;详细模式恢复记账详情,不恢复该控件。运行中的时钟和会话级计时统计独立于此选择。
## Alternatives considered
**默认简洁。** 这会在已有用户未明确选择时隐藏记账控件。需求定义了两种模式但未指定默认值,因此详细模式保留既有入口。
**选择简洁时过滤遥测。** 这会丢弃切换回详细模式或重新打开历史时需要的信息。展示偏好不能改变记录数据。
## Consequences
不可用的速度或缓存命中数据会被省略,不填入虚构值。设置作用域为所有消费者提供同一个已接受值,无需复制订阅状态。组件覆盖检查不同模式的可见性;[录制会话浏览器场景](../../../../apps/web/tests/message-actions.e2e.ts)验证选择、刷新持久化和简洁模式输出。
在非回环地址浏览器中,设置作用域无法持久化写入,因此该偏好仅在当前进程内生效。明确选择会立即更新所有使用方;回环地址浏览器收到 Host 已接受的设置后会同步当前值。
@@ -2,5 +2,5 @@
# side as of the last confirmed-consistent state. Both languages carry equal authority;
# after editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write .agents/notes/implemented/process/2026-09-17-windows-runtime-signature-cache.md
2026-09-17-windows-runtime-signature-cache.md: 909e39b5c06ed9d529df7553de324295aadf43fe
2026-09-17-windows-runtime-signature-cache.zh.md: c7ee5e1ca5105c21e3a7f4b43342dee20331e88b
2026-09-17-windows-runtime-signature-cache.md: 911e0277199bac55165fbc4adebb22e2599043b9
2026-09-17-windows-runtime-signature-cache.zh.md: bb8cdd6bdca445c94e8e77cddb68008d7b27f7ad
@@ -12,6 +12,12 @@ Windows packaging reconstructs unsigned native dependencies on each build. Signi
Cache complete signed runtime files by original content, public certificate, SignTool bytes, signing-script bytes and cache format. Keep valid vendor signatures. Restore a cache hit through a private staged copy only after checking the input record, signed-file digest, Windows trust, timestamp and configured certificate; reject invalid entries without automatic repair or hardware fallback. Publish complete entries atomically, and retain an existing valid entry when concurrent publishers collide.
Share the cache only within the current Windows account. Require a fixed local drive, current-account ownership and a private destination DACL; reject linked or redirected paths. Programs running as that account remain trusted. Explicit migration copies complete integrity-checked entries without modifying its source or replacing an existing valid entry. Different timestamp bytes at the same input/policy key do not require replacement; every actual restoration still verifies Windows trust.
The default cache lives beside the account's existing signing state under the user profile. AppData is unsuitable for this default because an MSIX launcher can redirect new files into its private package storage, separating otherwise identical worktrees launched from different programs. A validated explicit directory remains available for isolated build storage.
Serialize each complete signing stage and cache-maintenance operation with an exclusive Windows file handle. The lock covers preflight, primary-runtime signing, application-runtime signing and artifact creation separately, leaving compilation and preparation concurrent. A waiter rechecks the cache after acquisition. Stage ownership and the retained hardware-attempt interlock have different lifetimes: closing the stage handle releases contention, while hardware failures and interruptions retain the existing attempt evidence and never authorize an automatic retry.
Group public-key inspection into bounded batches of 32 files with at most four processes. Require one ordered result for every requested path and await every process in a failed batch. Preserve verification immediately after each hardware signature, before the next signing request.
The [primary-runtime decision](../feature/2026-09-14-desktop-primary-runtime.md) continues to own runtime contents, vendor-signature preservation and execution checks. The [release decision](../architecture/2026-08-25-electron-desktop-packaging-and-updates.md) continues to own release identity and signing. Neither is superseded. The cache must preserve their supervised preflight, per-user signing interlock, single-file hardware calls, signed inventory and final packaged-runtime validation.
@@ -24,12 +30,18 @@ The [primary-runtime decision](../feature/2026-09-14-desktop-primary-runtime.md)
**Whole signed-runtime artifacts only.** They can also avoid extraction and copying, but require assembly and dependency-graph identities. Per-file caching can reuse unchanged native dependencies when application code or one dependency changes.
**Per-entry locks only.** They avoid duplicate signatures for one key but do not coordinate different files, preflight or installer signing against the same hardware token. Stage-wide ownership covers those calls without holding a lock during unrelated compilation.
**Cache-age expiry.** Age alone does not establish that a timestamped signature is invalid. Rechecking current Windows trust preserves the validation requirement without periodically repeating unchanged hardware signatures.
## Consequences
Repeated builds with unchanged native inputs avoid hardware calls for cached files while retaining preflight and final artifact signing. Changed content or signing policy misses the cache. Corrupt, incomplete, untrusted or incorrectly timestamped entries fail without replacing the target or retrying hardware. Concurrent publication and interrupted processes cannot expose incomplete entries or damage another build's files.
Six complete signed Windows x64 builds cover an empty signature cache, repeated inputs, application changes and one controlled native-file content change. Warm builds reduce hardware calls from 379 to 17 and elapsed time from 37:38 to 12:36–12:42 on the measured host, while final runtime checks pass. Download caches remain populated; the controlled file change tests invalidation, not a dependency-version upgrade. Installer execution and update qualification remain separate.
Complete signed Windows x64 builds on one host measure an empty shared cache and reuse from a separate fresh worktree: hardware calls fall from 379 to 17, elapsed time from 37:03 to 13:45, and all 362 runtime entries hit. Cache restoration takes 132 seconds, including 130 seconds of current trust verification. Both builds pass final runtime smoke and signed-artifact checks. Downloads are prepared before timing; each scenario is one complete run. A separate controlled native-file change produces miss/hit/miss with two hardware calls; it tests invalidation, not a dependency-version upgrade. Installer execution and update qualification remain separate.
## Risks
The cache consumes local disk and depends on the build account controlling its files and records. It is not a distribution format for untrusted remote caches. Signature validation still depends on Windows trust services; cache hits do not authorize clearing a signing interlock or retrying a failed token operation. A timestamp-service failure can interrupt a cold build even after a successful preflight.
No automatic capacity eviction runs. Explicit maintenance waits for stage ownership and retires complete entries before deleting their files; interrupted staging directories remain distinguishable from published entries. Runtime summaries count actual publications separately from retained collisions, and report cache verification time separately from signing time. They do not measure the entire package's verification cost.
@@ -12,6 +12,12 @@ Windows 打包每次都会重新生成未签名的原生依赖。为未变化的
按原始内容、公开证书、SignTool 字节、签名脚本字节和缓存格式缓存完整已签名运行时文件。保留有效厂商签名。缓存命中后,通过私有暂存副本核对输入记录、已签名文件摘要、Windows 信任、时间戳和配置的证书,再恢复目标文件;无效缓存项直接失败,不自动修复或回退到硬件签名。完整缓存项原子发布,并发发布冲突时保留已有有效项。
缓存仅在当前 Windows 账户内共享。要求固定本地磁盘、当前账户所有权及私有目标目录 DACL;拒绝带链接或被重定向的路径。同账户运行的程序仍受信任。显式迁移复制通过完整性检查的完整缓存项,不修改源目录,也不替换已有有效项。同一输入和策略键下的时间戳字节不同,不构成替换理由;每次实际恢复仍验证 Windows 信任。
默认缓存位于用户目录下,与账户已有签名状态放在一起。AppData 不适合作为此默认位置,因为 MSIX 启动器可能将新文件重定向到私有包存储,使不同程序启动的相同 worktree 使用不同缓存。独立构建存储仍可指定经过验证的显式目录。
通过 Windows 独占文件句柄串行执行每个完整签名阶段及缓存维护操作。锁分别覆盖预检、主要运行时签名、应用运行时签名及产物生成,编译和准备仍可并行。等待者在获取锁后重新检查缓存。阶段所有权与持久保留的硬件尝试互锁具有不同生命周期:关闭阶段句柄释放竞争锁,而硬件失败或中断保留现有尝试证据,绝不构成自动重试授权。
公钥验签按每批 32 个文件分组,最多同时运行四个进程。要求每个请求路径都有一条顺序对应的结果,并等待失败批次中的所有进程退出。每次硬件签名后仍立即验签,通过后才开始下一个签名请求。
[主要运行时决策](../feature/2026-09-14-desktop-primary-runtime.zh.md) 继续定义运行时内容、厂商签名保留和执行检查。[发布决策](../architecture/2026-08-25-electron-desktop-packaging-and-updates.zh.md) 继续定义发布身份和签名。两者均未被取代。缓存必须保留受监督预检、每用户签名互锁、单文件硬件调用、已签名内容清单和最终打包运行时验证。
@@ -24,12 +30,18 @@ Windows 打包每次都会重新生成未签名的原生依赖。为未变化的
**仅复用整个已签名运行时制品。** 该方案还可以省去解压和复制,但需要标识组装流程及依赖图。逐文件缓存可以在应用代码或单个依赖变化时复用其余未变化的原生依赖。
**仅使用逐项锁。** 它能避免同一键的重复签名,却无法协调不同文件、预检或安装器签名对同一硬件令牌的访问。阶段级所有权覆盖这些调用,不在无关编译期间持锁。
**按缓存年龄过期。** 年龄本身不能说明带时间戳的签名无效。重新检查当前 Windows 信任可以保留验证要求,同时避免周期性重复未变化的硬件签名。
## Consequences
原生输入未变化的重复构建不再为缓存覆盖的文件调用硬件签名,但仍执行预检和最终制品签名。内容或签名策略变化时缓存未命中。损坏、不完整、不可信或时间戳不合格的缓存项必须失败,不替换目标文件,也不重试硬件。并发发布和进程中断不能暴露不完整缓存项或损坏其他构建的文件。
六轮完整 Windows x64 签名构建覆盖空签名缓存、重复输入、应用变化和单个原生文件的受控内容变化。在测量主机上,热构建将硬件调用从 379 次降至 17 次,耗时从 37:38 降至 12:36–12:42,且最终运行时检查通过。下载缓存保持已填充;受控文件变化验证缓存失效,不代表依赖版本升级。安装器执行和更新验收仍需单独进行。
同一主机上的完整 Windows x64 签名构建测量空共享缓存与另一个全新 worktree 的复用:硬件调用从 379 次降至 17 次,耗时从 37:03 降至 13:45,362 个运行时缓存项全部命中。缓存恢复耗时 132 秒,其中当前信任验证占 130 秒。两轮均通过最终运行时 smoke 及签名产物检查。下载内容在计时前准备好;每种场景均为一次完整运行。另一次受控原生文件变更产生未命中、命中、未命中的结果,合计两次硬件调用;它验证缓存失效,不代表依赖版本升级。安装器执行和更新验收仍需单独进行。
## Risks
缓存占用本地磁盘,并依赖构建账户控制缓存文件及记录。它不是用于不可信远程缓存的分发格式。签名验证仍依赖 Windows 信任服务;缓存命中不构成清除签名互锁或重试失败令牌操作的授权。即使预检成功,时间戳服务故障仍可能中断冷构建。
不执行自动容量淘汰。显式维护等待阶段所有权,在删除文件前先将完整缓存项移出已发布名称;中断的暂存目录仍可与已发布项区分。运行时摘要区分实际发布和冲突保留,并将缓存验证耗时与签名耗时分别记录;它不测量整个安装包的验证成本。
@@ -138,7 +138,7 @@ function start(f: ReturnType<typeof fixture>, extra: string[] = []) {
expect(response.status).toBe(200)
const html = await response.text()
expect(html).toContain('__DSH_BOOT__')
const bundlePath = /<script src="(\/plugins\/[^"]+)"/u.exec(html)?.[1]?.replaceAll('&amp;', '&')
const bundlePath = /<script src="(plugins\/[^"]+)"/u.exec(html)?.[1]?.replaceAll('&amp;', '&')
if (!bundlePath) throw new Error('Missing bootstrap bundle URL')
const bundle = await fetch(new URL(bundlePath, url), { headers: { cookie }, signal: AbortSignal.timeout(10_000) })
expect(bundle.status).toBe(200)
+1 -1
View File
@@ -172,7 +172,7 @@ describe('dsh web authentication through the real CLI', () => {
const exchange = await fetch(first.launchUrl, { redirect: 'manual' })
expect(exchange.status).toBe(303)
expect(exchange.headers.get('location')).toBe('/')
expect(exchange.headers.get('location')).toBe('./')
const setCookie = exchange.headers.get('set-cookie')
if (setCookie === null) throw new Error('real CLI token exchange omitted Set-Cookie')
expect(setCookie).toContain('HttpOnly')
+14 -4
View File
@@ -4,12 +4,22 @@ DSH_DESKTOP_APP_ID=com.deepseek.harness
DSH_DESKTOP_AUTO_UPDATE_ENV=test
DOWNLOAD_TEST_ORIGIN=
# Workspace tarball workers; omit to use 4. Must be a positive integer.
DSH_DESKTOP_MACOS_PACK_CONCURRENCY=4
# Optional independent proxy origins; empty values preserve inherited networking.
# Downloads: HTTP/HTTPS proxy for Electron, runtime assets, pnpm and builder downloads.
DSH_DESKTOP_MACOS_DOWNLOAD_PROXY=
# Apple tools: HTTP proxy temporarily applied to the active macOS network service.
# Requires permission to change system proxies; affects other applications during notarization.
DSH_DESKTOP_MACOS_NOTARIZATION_PROXY=
# The selected mandatory-update origin is required, including unsigned and preparation builds.
DSH_DESKTOP_MANDATORY_UPDATE_TEST_ORIGIN=https://harness-test.deepseek.com
DSH_DESKTOP_MANDATORY_UPDATE_PROD_ORIGIN=https://harness.deepseek.com
# Optional polling and fallback-page options; origin and authentication are selected automatically.
DSH_DESKTOP_MANDATORY_UPDATE_TEST_ORIGIN=
DSH_DESKTOP_MANDATORY_UPDATE_PROD_ORIGIN=
# Set approved login origins for test builds; omit allowedAuthOrigins for production.
# Optional polling and fallback-page options belong in the same JSON value.
# The fallback-page allowlist defaults to the selected service origin.
# DSH_DESKTOP_MANDATORY_UPDATE_CONFIG='{"intervalMs":600000}'
DSH_DESKTOP_MANDATORY_UPDATE_CONFIG='{"allowedAuthOrigins":["https://login.example.com"]}'
DSH_DESKTOP_MACOS_SIGNING_IDENTITY=
DSH_DESKTOP_MACOS_TEAM_ID=
+9 -5
View File
@@ -1,21 +1,25 @@
# Copy to .env.windows (Git ignored). Use UTF-8 and quote secrets containing # or spaces.
# Paths may be absolute or relative to apps/desktop. Values are not shell-expanded.
# Credential file paths may be absolute or relative to apps/desktop. Values are not shell-expanded.
DSH_DESKTOP_APP_ID=com.deepseek.harness
DSH_DESKTOP_AUTO_UPDATE_ENV=test
DOWNLOAD_TEST_ORIGIN=
# The selected mandatory-update origin is required, including unsigned and preparation builds.
DSH_DESKTOP_MANDATORY_UPDATE_TEST_ORIGIN=https://harness-test.deepseek.com
DSH_DESKTOP_MANDATORY_UPDATE_PROD_ORIGIN=https://harness.deepseek.com
# Optional polling and fallback-page options; origin and authentication are selected automatically.
DSH_DESKTOP_MANDATORY_UPDATE_TEST_ORIGIN=
DSH_DESKTOP_MANDATORY_UPDATE_PROD_ORIGIN=
# Set approved login origins for test builds; omit allowedAuthOrigins for production.
# Optional polling and fallback-page options belong in the same JSON value.
# The fallback-page allowlist defaults to the selected service origin.
# DSH_DESKTOP_MANDATORY_UPDATE_CONFIG='{"intervalMs":600000}'
DSH_DESKTOP_MANDATORY_UPDATE_CONFIG='{"allowedAuthOrigins":["https://login.example.com"]}'
DSH_DESKTOP_WINDOWS_CER_FILE=
DSH_DESKTOP_WINDOWS_SIGNTOOL=
DSH_DESKTOP_WINDOWS_KEY_CONTAINER=
DSH_DESKTOP_WINDOWS_TOKEN_PIN=
# Optional absolute, private local directory; defaults to %USERPROFILE%\.dsh-desktop-signing\signature-cache\v1.
# DSH_DESKTOP_WINDOWS_SIGNATURE_CACHE_DIR=C:\Users\build\.dsh-desktop-signing\signature-cache\v1
# Optional upload configuration; packaging does not require these credentials.
# DOWNLOAD_TEST_COS_BUCKET=
# DOWNLOAD_TEST_COS_SECRET_ID=
+2 -2
View File
@@ -2,5 +2,5 @@
# side as of the last confirmed-consistent state. Both languages carry equal authority;
# after editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write apps/desktop/README.md
README.md: 531c168c0d3fc3091a330f5350d0a85ac3009f08
README.zh.md: 6a20f83623a54e8f87d05104280b97ddfb2a796a
README.md: eb185783e77422d229c476eccb2b2ea817b1fdef
README.zh.md: 95f2c011af23d6dd16da32f8a0c58f8899b24619
+27 -4
View File
@@ -186,7 +186,23 @@ The macOS configuration uses the required release environment instead of accepti
macOS signing visits real files without following Framework symlink aliases. PAK resources retain all shipped languages and are sealed by the enclosing Framework or application signature instead of receiving individual signatures. The [release policy](../../.agents/notes/implemented/architecture/2026-08-25-electron-desktop-packaging-and-updates.md) owns the dependency patch and verification requirements.
Company proxies can accelerate uploads to Apple's notarization service. See the company internal documentation for configuration.
macOS runtime preparation caches verified single-architecture Mach-O signatures in `.desktop-build/targets/<target>/signature-cache`. Keys include input bytes and permissions, the signing probe’s actual leaf certificate, identifier, entitlement bytes, macOS version, and signing tools and policy. Git commits do not determine reuse: uncommitted byte changes invalidate the affected file. Every hit verifies cached bytes, the strict signature, certificate, identifier, entitlements, secure timestamp and hardened runtime before replacing an unchanged input. Universal binaries are signed each time. Runtime integrity and smoke checks, App signing, and Apple notarization still run. The cache requires trusted local build storage. Cache corruption or unsafe links fail the build; stop packaging before deleting the affected cache directory and retrying. Successful signing stages prune complete entries to a one-GiB payload budget; interrupted temporary entries require manual removal. Concurrent eviction can fail a reader safely. Logs report hit, miss and uncached counts.
Mac package commands print `DESKTOP_PACKAGING_RECORD` with a unique directory under `apps/desktop/.desktop-build/packaging-runs/`. After reading local configuration, each run retains `run.json` (version, Git commit, dirty-worktree flag, target and Node version), `events.jsonl` (timestamped phases, durations, parallel output attribution and proxy restoration), redacted child `stdout.log` / `stderr.log`, and `result.json` (overall outcome, stage results and artifact directory). Events also record pack concurrency and whether each proxy is configured. Logs survive failures and later builds; no automatic deletion runs. Missing `result.json` means completion is unconfirmed. Known credential values are redacted; environments and notarytool authentication arguments are not recorded. Runtime preparation records package staging, installation, materialization, signing, manifests, smoke checks, descriptor verification and cleanup separately. Nested phase durations overlap and must not be added together.
App and DMG notarization each record a submission ID and separate `notarytool:upload:*` and `notarytool:wait:*` durations. Upload uses `submit --no-wait` and includes authentication, local validation, transfer and server acceptance; it is not pure transfer time. Waiting starts after that command returns and includes polling and remaining Apple processing; Apple can start processing before upload submission returns. Apple status and diagnostic logs are retained, including rejection; signature checks, acceptance checks and stapling remain owned by `@electron/notarize`. Directory-only package commands use this same measured App notarization path. Individual subprocess output remains live in the terminal, while phase failures and nested errors are retained in the journal. Both platforms record parent-process packaging failures and print redacted diagnostics, including proxy recovery instructions, to the terminal. The configuration-only `check:package` command creates no run log.
Mac packaging reads three tuning fields from `.env.macos`:
| Setting | Default | Scope |
|---|---|---|
| `DSH_DESKTOP_MACOS_PACK_CONCURRENCY` | `4` | Workers for first-party and vendor workspace tarballs; requires a positive integer. |
| `DSH_DESKTOP_MACOS_DOWNLOAD_PROXY` | Empty | HTTP/HTTPS proxy origin for Electron, runtime assets, pnpm installation and builder downloads. |
| `DSH_DESKTOP_MACOS_NOTARIZATION_PROXY` | Empty | HTTP proxy origin for Apple tools through temporary system proxy settings. |
The proxy fields are independent and reject URL credentials, paths, queries and fragments. Empty values preserve inherited networking. An explicit download proxy replaces child-process proxy variables and bypasses local hosts only; it does not change system settings. Windows and standalone `release:pack` retain their existing concurrency defaults. Company proxy addresses belong in the ignored local file; see internal documentation for addresses.
Apple tooling uses the active macOS network service's HTTP/HTTPS proxies. Configured notarization routing checks proxy reachability, saves that service's settings, enables the proxy around both artifact lanes, and restores the saved settings after both lanes settle. An originally disabled proxy with an empty server and port zero is restored by disabling it; the temporary server and port may remain stored but inactive. Directory-only builds apply it to App notarization after the signed directory build. This temporarily affects other applications and requires permission to change system proxies; PAC, auto-discovery, SOCKS and authenticated proxy configurations must be disabled first. Packaging and recovery acquire the same per-user POSIX file lock before reading recovery data or changing proxies; process exit releases ownership, while the lock file remains in place. This prevents overlapping proxy transactions across checkouts; other users and network-setting tools must not change these settings concurrently. SIGINT/SIGTERM wait for active work before restoration. After forced termination or a restoration error, stop any remaining notarization processes and run `pnpm --dir apps/desktop run restore:mac-proxy`; the saved record remains until restoration succeeds. Configuration checks validate URL syntax without changing system settings or contacting the proxy.
### Unsigned Windows test installer
@@ -210,7 +226,13 @@ Run `pnpm --dir apps/desktop run test:installer` from the repository root on an
### Windows EV signing
Runtime signing caches complete signed files under `.desktop-build/targets/win-x64/signature-cache`. Entries identify the original bytes, public certificate and signing toolchain. Restoring an entry checks its digest, Windows trust, timestamp and certificate before replacing the unsigned file; invalid entries stop packaging without hardware fallback. The cache requires trusted local build storage and retains entries until removed. Preflight, hardware interlocks and final artifact signing still apply. Cache qualification and design limits are tracked in the [runtime signature cache decision](../../.agents/notes/implemented/process/2026-09-17-windows-runtime-signature-cache.md).
Runtime signing shares complete signed files across the current Windows account's worktrees. `DSH_DESKTOP_WINDOWS_SIGNATURE_CACHE_DIR` in `.env.windows` selects an absolute fixed-drive directory; the default is `%USERPROFILE%\.dsh-desktop-signing\signature-cache\v1`. Cache directories must belong to the current account and exclude other ordinary accounts from their access permissions; linked paths are rejected. Entries identify the original bytes, public certificate and signing toolchain. Every restoration checks the digest, Windows trust, timestamp and certificate before replacing the unsigned file; invalid entries stop packaging without hardware fallback. Cache age alone does not trigger signing. The cache trusts programs running as the same account and does not defend against administrators. The [runtime signature cache decision](../../.agents/notes/implemented/process/2026-09-17-windows-runtime-signature-cache.md) owns qualification and design limits.
Preflight, primary-runtime signing, application-runtime signing and artifact creation each hold the account's signing-stage lock until their supervised child processes settle. Other builds wait before entering those stages; compilation and preparation do not hold the lock. Runtime signing workers own their locks, so terminating only the outer packaging process does not unlock a surviving cache user. Migration and maintenance acquire the same lock; older or external signing commands do not participate and must be scheduled separately. Stage waiting is outside the preflight deadline. Closing the stage handle releases ordinary contention without removing the separate hardware-attempt interlock; a retained hardware failure still requires operator recovery.
Each runtime stage writes `SIGNATURE_CACHE_SUMMARY` to stdout and its packaging journal, including the actual directory, policy identity, hit/miss counts, newly published and retained entries, signing requests, avoided signing requests and validation failures. Timings distinguish signing, trust verification of restored and newly signed files, and restoration; restoration includes its trust check and staging cleanup. These counters exclude preflight, final artifact signing and the outer runtime signature checks. Stage lock events record waiting separately.
Use `pnpm --dir apps/desktop run cache:windows-signatures --usage` to inspect structurally complete-entry bytes and counts, or `--from <absolute-old-cache>` to import an explicitly selected cache owned by the same account. Migration leaves the source unchanged, skips staging names, rejects corrupt entries and retains valid existing entries even when their timestamp bytes differ. `--clear` explicitly removes complete entries under the stage lock; no automatic capacity eviction runs. `--directory <absolute-cache>` selects a maintenance destination without loading release credentials. Incomplete staging entries remain untouched and are counted separately; inspect them only after all builds have stopped. These commands never clear hardware failure evidence. Default storage is outside AppData so MSIX launcher virtualization does not split the account's cache; redirected overrides fail explicitly.
Signed Windows builds run a supervised signing preflight before compilation or dependency preparation. Static configuration, certificate validity, audit storage, compiler availability and any retained signing interlock are checked without token access. The local .NET Framework C# compiler creates a small private probe; the production signer signs it once, and verification requires the configured certificate and a timestamp before building continues. The probe is never executed. The overall 60-second preflight deadline includes timestamp attempts; deadline expiry, hardware signing errors and verification failures stop the run without another hardware attempt. Success proves the current signing path works, not that the PIN was independently authenticated: SafeNet may reuse login state. Do not log out or repeat authentication to test the PIN. `--check`, preparation-only and `--unsigned` modes do not run this hardware preflight; unsigned artifacts remain ineligible for release upload. Automated regression tests use a fake signer; release operators qualify real hardware separately.
@@ -275,15 +297,16 @@ Confirmed Host exit without successful task teardown displays localized recovery
### Mandatory update policy
The [mandatory client decision](../../.agents/notes/implemented/feature/2026-09-11-desktop-mandatory-update-client.md) owns policy polling and the blocking window. Packaging reads `.env.windows` or `.env.macos`: `DSH_DESKTOP_AUTO_UPDATE_ENV=test` (the default) selects `DSH_DESKTOP_MANDATORY_UPDATE_TEST_ORIGIN`; `production` selects `DSH_DESKTOP_MANDATORY_UPDATE_PROD_ORIGIN`. Templates use `https://harness-test.deepseek.com` and `https://harness.deepseek.com`, respectively. The selected origin is required before preparation or signing, including unsigned and preparation-only builds; the unselected origin is optional. These settings never fall back to the parent environment or the other deployment. Packaging embeds the selected policy with the application ID; packaged applications ignore runtime overrides.
The [mandatory client decision](../../.agents/notes/implemented/feature/2026-09-11-desktop-mandatory-update-client.md) owns policy polling and the blocking window. Packaging reads `.env.windows` or `.env.macos`: `DSH_DESKTOP_AUTO_UPDATE_ENV=test` (the default) selects `DSH_DESKTOP_MANDATORY_UPDATE_TEST_ORIGIN`; `production` selects `DSH_DESKTOP_MANDATORY_UPDATE_PROD_ORIGIN`. The templates leave both origins blank; fill in the selected deployment origin in the ignored local dotenv file. The selected origin is required before preparation or signing, including unsigned and preparation-only builds; the unselected origin is optional. These settings never fall back to the parent environment or the other deployment. Packaging embeds the selected policy with the application ID; packaged applications ignore runtime overrides.
Optional `DSH_DESKTOP_MANDATORY_UPDATE_CONFIG` JSON supplies polling and download-page options; packaging rejects `origin` and `authentication` inside it. The page allowlist defaults to the selected service origin; explicitly allow other approved download-page origins when needed. Test builds select `feishu-test`, and production selects `anonymous`. Policy requests reject redirects; only test authentication carries gateway cookies. Unpackaged development instead reads a complete policy JSON from this variable and requires `DSH_DESKTOP_APP_ID`; absent JSON disables development policy queries, and only anonymous development permits HTTP `127.0.0.1`. A user-initiated ordinary check triggers policy work concurrently but never waits for or reports a policy failure. Only a confirmed blocking decision cancels ordinary dialogs. Test authentication waits until the active ordinary dialog finishes, and cancellation or failure does not discard the updater result.
`DSH_DESKTOP_MANDATORY_UPDATE_CONFIG` JSON supplies test login origins and optional polling and download-page options; packaging rejects `origin` and `authentication` inside it. The page allowlist defaults to the selected service origin; explicitly allow other approved download-page origins when needed. Test builds select `feishu-test` and require `allowedAuthOrigins` in `DSH_DESKTOP_MANDATORY_UPDATE_CONFIG`; production selects `anonymous` and rejects that field. Each login origin must be an HTTPS origin without credentials, path, query, or fragment. The login window permits document navigation only to the selected policy origin and these configured origins. Policy requests reject redirects; only test authentication carries gateway cookies. Unpackaged development instead reads a complete policy JSON from this variable and requires `DSH_DESKTOP_APP_ID`; absent JSON disables development policy queries, and only anonymous development permits HTTP `127.0.0.1`. A user-initiated ordinary check triggers policy work concurrently but never waits for or reports a policy failure. Only a confirmed blocking decision cancels ordinary dialogs. Test authentication waits until the active ordinary dialog finishes, and cancellation or failure does not discard the updater result.
| Resolved policy field | Meaning and default |
|---|---|
| `origin` | Required HTTPS API origin, without credentials, path, query, or fragment; requests use `/api/v0/check_client_update` |
| `allowedPageOrigins` | Nonempty array of exact HTTPS origins; packaging defaults to the selected API origin; subdomains and alternate ports are not implied |
| `authentication` | Packaging selects `feishu-test` for test and `anonymous` for production; unpackaged development defaults to `anonymous` |
| `allowedAuthOrigins` | Nonempty array of exact HTTPS login document origins for test authentication; forbidden for production |
| `intervalMs` | Polling interval; default `600000` |
| `timeoutMs` | Request deadline; default `15000` |
| `maxBackoffMs` | Maximum failed-request interval including jitter; default `3600000`, at least `intervalMs` |
+27 -4
View File
@@ -187,7 +187,23 @@ macOS 配置使用必填发布环境,不会接受钥匙串中最先发现的
macOS 签名遍历真实文件,不跟随 Framework 的软链接别名。PAK 资源保留全部随附语言,由外层 Framework 或应用签名记录完整性,不逐个签名。[发布策略](../../.agents/notes/implemented/architecture/2026-08-25-electron-desktop-packaging-and-updates.zh.md)负责依赖补丁和验证要求。
可通过公司代理加速向 Apple 公证服务上传。代理配置参见公司内部文档。
macOS 运行时准备将已验证的单架构 Mach-O 签名缓存在 `.desktop-build/targets/<target>/signature-cache`。缓存键包含输入字节与权限、签名探针实际使用的叶证书、签名标识、entitlement 字节、macOS 版本,以及签名工具与策略。复用不取决于 Git 提交:未提交的字节变更会使对应文件失效。每次命中都验证缓存字节、严格签名、证书、标识、entitlements、安全时间戳和 hardened runtime,再替换未被并发修改的输入。通用二进制每次重新签名。运行时完整性与 smoke 检查、App 签名和 Apple 公证仍会执行。缓存要求受信任的本地构建存储。缓存损坏或不安全链接会令构建失败;停止打包后删除对应缓存目录再重试。成功的签名阶段会将完整缓存条目的内容总量裁剪至一 GiB;中断留下的临时条目需手动清理。并发淘汰可能使读取方安全失败。日志记录命中、未命中及未缓存数量。
Mac 打包命令通过 `DESKTOP_PACKAGING_RECORD` 输出 `apps/desktop/.desktop-build/packaging-runs/` 下的唯一目录。读取本地配置后,每次运行保留 `run.json`(版本、Git 提交、工作区是否有改动、目标及 Node 版本)、`events.jsonl`(带时间戳的阶段、耗时、并行输出归属及代理恢复状态)、脱敏后的子进程 `stdout.log` / `stderr.log`,以及 `result.json`(整体结果、阶段结果和产物目录)。事件还记录打包并发数及各代理是否配置。失败和后续打包不会清除日志;没有自动删除流程。缺少 `result.json` 表示完成状态未经确认。已知凭据值会被遮盖;不记录环境变量全集或 notarytool 认证参数。运行时准备分别记录包暂存、安装、依赖树复制、签名、清单生成、smoke 检查、描述文件校验和清理。嵌套阶段的耗时存在重叠,不能直接相加。
App 和 DMG 公证分别记录 submission ID,以及独立的 `notarytool:upload:*` 和 `notarytool:wait:*` 耗时。上传使用 `submit --no-wait`,包含认证、本地校验、传输和服务端受理,并非纯传输时间。等待从该命令返回后开始,包含轮询及剩余的 Apple 处理时间;Apple 可能在上传提交命令返回前已开始处理。日志保留 Apple 状态与诊断信息,包括拒绝结果;签名检查、接受状态校验和 stapling 仍由 `@electron/notarize` 负责。仅生成目录的打包命令也使用同一条可计时的 App 公证路径。各子进程输出仍实时显示在终端,阶段失败及嵌套错误保留在事件日志中。两个平台均记录父进程打包失败,并在终端显示脱敏诊断,包括代理恢复操作指引。仅检查配置的 `check:package` 命令不创建运行日志。
Mac 打包从 `.env.macos` 读取三个调优字段:
| 设置 | 默认值 | 作用范围 |
|---|---|---|
| `DSH_DESKTOP_MACOS_PACK_CONCURRENCY` | `4` | 第一方与 vendor workspace tarball 的打包 worker 数;必须是正整数。 |
| `DSH_DESKTOP_MACOS_DOWNLOAD_PROXY` | 空 | Electron、运行时资源、pnpm 安装及 builder 下载使用的 HTTP/HTTPS 代理 origin。 |
| `DSH_DESKTOP_MACOS_NOTARIZATION_PROXY` | 空 | 通过临时系统代理设置供 Apple 工具使用的 HTTP 代理 origin。 |
两个代理字段互相独立,拒绝 URL 中的凭证、路径、查询参数和片段。空值沿用继承的网络设置。显式下载代理会替换子进程的代理变量,仅绕过本地主机;它不修改系统设置。Windows 与独立 `release:pack` 保持现有并发默认值。公司代理地址仅写入 Git 忽略的本地文件;具体地址参见内部文档。
Apple 工具使用 macOS 当前活动网络服务的 HTTP/HTTPS 代理。配置公证代理后,打包会检查代理可达性、保存该服务的设置,在两条产物任务期间启用代理,并在两条任务均结束后恢复原设置。对于原本关闭、服务器为空且端口为零的代理,恢复时仅关闭代理;临时服务器和端口可能保留,但不生效。仅生成目录的打包会在签名目录构建完成后的 App 公证期间启用代理。这会临时影响其他应用,并要求修改系统代理的权限;必须先禁用 PAC、自动发现、SOCKS 及需要认证的代理配置。打包和恢复在读取恢复记录或修改代理前获取同一个用户级 POSIX 文件锁;进程退出会释放锁的持有权,锁文件保留。这会阻止不同 checkout 的代理事务重叠;其他用户及网络设置工具不得同时修改这些设置。SIGINT/SIGTERM 会等待活动任务结束后恢复。强制终止或恢复失败后,先停止残留公证进程,再运行 `pnpm --dir apps/desktop run restore:mac-proxy`;保存的记录会保留到恢复成功。配置检查仅验证 URL 语法,不修改系统设置或连接代理。
### 未签名 Windows 测试安装包
@@ -211,7 +227,13 @@ Windows 打包使用 Visual C++ Build Tools 和 Windows SDK 编译 x86 Win32/GDI
### Windows EV 签名
运行时签名将完整的已签名文件缓存在 `.desktop-build/targets/win-x64/signature-cache`。缓存项标识原始字节、公钥证书和签名工具链。恢复缓存项时,先检查摘要、Windows 信任状态、时间戳和证书,再替换未签名文件;缓存项无效会停止打包,不回退到硬件签名。缓存要求受信任的本地构建存储,并保留缓存项直到被移除。预检、硬件互锁和最终产物签名仍然执行。[运行时签名缓存决策](../../.agents/notes/implemented/process/2026-09-17-windows-runtime-signature-cache.zh.md)记录缓存验收要求和设计限制。
运行时签名在当前 Windows 账户的各 worktree 间共享完整的已签名文件。`.env.windows` 中的 `DSH_DESKTOP_WINDOWS_SIGNATURE_CACHE_DIR` 指定固定本地磁盘上的绝对目录;默认值为 `%USERPROFILE%\.dsh-desktop-signing\signature-cache\v1`。缓存目录必须属于当前账户,访问权限不得向其他普通账户开放;带链接的路径会被拒绝。缓存项标识原始字节、公钥证书和签名工具链。每次恢复都检查摘要、Windows 信任状态、时间戳和证书,再替换未签名文件;缓存项无效会停止打包,不回退到硬件签名。不会仅因缓存较旧而重新签名。缓存信任同账户运行的程序,不防御管理员。[运行时签名缓存决策](../../.agents/notes/implemented/process/2026-09-17-windows-runtime-signature-cache.zh.md)定义验收要求和设计限制。
预检、主要运行时签名、应用运行时签名和产物生成分别持有账户级签名阶段锁,直到受监督的子进程结束。其他构建进入这些阶段前等待;编译和准备步骤不持锁。运行时签名进程自行持锁,因此仅终止外层打包进程不会释放仍在访问缓存的阶段锁。迁移及维护获取同一把锁;旧版或外部签名命令不参与排队,应另行避免并发。阶段等待不计入预检期限。关闭阶段句柄会释放普通竞争锁,不删除独立的硬件尝试互锁;遗留硬件失败仍需操作人员恢复。
每个运行时阶段向标准输出及打包日志写入 `SIGNATURE_CACHE_SUMMARY`,包含实际目录、策略标识、命中及未命中数、新发布及保留项数、签名请求数、省去的签名请求数和验证失败数。计时区分签名、恢复文件和新签名文件的信任验证及恢复;恢复耗时包含其信任检查和暂存清理。这些统计不包含预检、最终产物签名及外层运行时验签。阶段锁事件单独记录等待时间。
使用 `pnpm --dir apps/desktop run cache:windows-signatures --usage` 查看结构完整的缓存项字节数和数量,或用 `--from <absolute-old-cache>` 导入显式指定、属于同账户的旧缓存。迁移不修改源目录,跳过暂存名称,拒绝损坏项,并保留已有有效项,即使它们的时间戳字节不同。`--clear` 在阶段锁保护下显式删除完整缓存项;不执行自动容量淘汰。`--directory <absolute-cache>` 指定维护目标目录,无需加载发布凭据。不完整暂存项保持原状并单独计数;仅在所有构建停止后检查它们。这些命令绝不清除硬件失败证据。默认存储位于 AppData 之外,避免 MSIX 启动器虚拟化将账户缓存拆开;被重定向的覆盖目录会明确失败。
Windows 签名构建在编译或准备依赖前执行受监督的签名预检。静态配置、证书有效期、审计存储、编译器可用性及遗留签名锁的检查不访问 Token。本地 .NET Framework C# 编译器生成一个专用小探针,由正式签名器仅签名一次,随后必须验出配置的证书和时间戳才能继续构建。探针绝不执行。预检的整体 60 秒期限包含时间戳尝试;超时、硬件签名报错或验签失败都会停止本轮流程,不再次调用硬件。成功只证明当前签名路径可用,不证明 PIN 已独立认证:SafeNet 可能复用登录状态。不要为了验证 PIN 而注销或重复认证。`--check`、仅准备和 `--unsigned` 模式不执行此硬件预检;未签名产物仍不能发布上传。自动回归测试使用假签名器,真实硬件由发布操作人员单独验收。
@@ -276,15 +298,16 @@ macOS 打包在组装 App 时、代码签名前写入 `Contents/Resources/app-up
### 强制更新策略
[强更客户端决策](../../.agents/notes/implemented/feature/2026-09-11-desktop-mandatory-update-client.zh.md)负责策略查询和阻塞窗口。打包读取 `.env.windows` 或 `.env.macos`:`DSH_DESKTOP_AUTO_UPDATE_ENV=test`(默认值)选择 `DSH_DESKTOP_MANDATORY_UPDATE_TEST_ORIGIN`;`production` 选择 `DSH_DESKTOP_MANDATORY_UPDATE_PROD_ORIGIN`。模板分别使用 `https://harness-test.deepseek.com` 和 `https://harness.deepseek.com`。在准备产物或签名前,所选源站必须配置,包括未签名和仅准备构建;未选环境的源站可不填。这些配置不会回退到父进程环境或另一部署环境。打包将选定策略与应用 ID 写入元数据;打包应用忽略运行时覆盖。
[强更客户端决策](../../.agents/notes/implemented/feature/2026-09-11-desktop-mandatory-update-client.zh.md)负责策略查询和阻塞窗口。打包读取 `.env.windows` 或 `.env.macos`:`DSH_DESKTOP_AUTO_UPDATE_ENV=test`(默认值)选择 `DSH_DESKTOP_MANDATORY_UPDATE_TEST_ORIGIN`;`production` 选择 `DSH_DESKTOP_MANDATORY_UPDATE_PROD_ORIGIN`。模板将两个源站留空;在 Git 忽略的目标 dotenv 文件中填写所选部署的源站。在准备产物或签名前,所选源站必须配置,包括未签名和仅准备构建;未选环境的源站可不填。这些配置不会回退到父进程环境或另一部署环境。打包将选定策略与应用 ID 写入元数据;打包应用忽略运行时覆盖。
可选的 `DSH_DESKTOP_MANDATORY_UPDATE_CONFIG` JSON 提供轮询和下载页面选项;打包拒绝其中的 `origin` 和 `authentication`。页面白名单默认只包含所选服务源站;需要其他已批准下载页面源站时应显式配置。测试包选择 `feishu-test`,正式包选择 `anonymous`。策略请求拒绝重定向;仅测试鉴权携带网关 Cookie。未打包开发模式则从此变量读取完整策略 JSON,并要求 `DSH_DESKTOP_APP_ID`;缺少 JSON 会禁用开发模式策略查询,仅匿名开发允许 HTTP `127.0.0.1`。用户发起常规检查时会并发触发策略检查,但不会等待或展示策略失败。只有已确认的强更决定可以关闭常规弹窗。测试环境鉴权会等待当前常规弹窗结束,取消或失败不会丢弃 updater 结果。
`DSH_DESKTOP_MANDATORY_UPDATE_CONFIG` JSON 提供测试登录源站,以及可选的轮询和下载页面选项;打包拒绝其中的 `origin` 和 `authentication`。页面白名单默认只包含所选服务源站;需要其他已批准下载页面源站时应显式配置。测试包选择 `feishu-test`,且必须在 `DSH_DESKTOP_MANDATORY_UPDATE_CONFIG` 中配置 `allowedAuthOrigins`;正式包选择 `anonymous`,并拒绝该字段。每个登录源站必须是没有凭据、路径、查询或片段的 HTTPS origin。登录窗口仅允许文档导航到所选策略源站和这些已配置源站。策略请求拒绝重定向;仅测试鉴权携带网关 Cookie。未打包开发模式则从此变量读取完整策略 JSON,并要求 `DSH_DESKTOP_APP_ID`;缺少 JSON 会禁用开发模式策略查询,仅匿名开发允许 HTTP `127.0.0.1`。用户发起常规检查时会并发触发策略检查,但不会等待或展示策略失败。只有已确认的强更决定可以关闭常规弹窗。测试环境鉴权会等待当前常规弹窗结束,取消或失败不会丢弃 updater 结果。
| 解析后的策略字段 | 含义与默认值 |
|---|---|
| `origin` | 必填 HTTPS API 源站,不含凭据、路径、查询或片段;请求使用 `/api/v0/check_client_update` |
| `allowedPageOrigins` | 非空的精确 HTTPS 源站数组;打包时默认只包含所选 API 源站;不隐含子域名或其他端口 |
| `authentication` | 打包时测试环境选择 `feishu-test`,正式环境选择 `anonymous`;未打包开发模式默认为 `anonymous` |
| `allowedAuthOrigins` | 测试鉴权必填的非空 HTTPS 登录文档源站数组;正式环境禁止配置 |
| `intervalMs` | 轮询间隔;默认 `600000` |
| `timeoutMs` | 请求截止时间;默认 `15000` |
| `maxBackoffMs` | 含抖动的失败请求最大间隔;默认 `3600000`,不小于 `intervalMs` |
+4
View File
@@ -15,12 +15,14 @@
"prepare:runtime": "tsx scripts/prepare-runtime.ts",
"prepare:primary-runtime": "tsx scripts/prepare-primary-runtime.ts",
"sign:primary-runtime": "tsx scripts/sign-primary-runtime.ts",
"cache:windows-signatures": "node scripts/manage-windows-signature-cache.mjs",
"prepare:packages": "tsx scripts/prepare-package-set.ts",
"prepare:dsh": "tsx scripts/prepare-dsh.ts",
"prepare:package": "tsx scripts/package-target.ts --prepare-only",
"verify:mac-signature": "node scripts/verify-macos-signature.mjs",
"package": "tsx scripts/package-target.ts",
"check:package": "tsx scripts/package-target.ts --check",
"restore:mac-proxy": "tsx scripts/macos-notarization-proxy.ts",
"package:dir": "tsx scripts/package-target.ts --dir",
"package:mac:arm64": "tsx scripts/package-target.ts mac-arm64",
"package:mac:arm64:dir": "tsx scripts/package-target.ts mac-arm64 --dir",
@@ -40,6 +42,7 @@
"devDependencies": {
"@deepseek-ai/dsh-app-boot": "workspace:^",
"@deepseek-ai/dsh-home-paths": "workspace:^",
"@deepseek-ai/node-addon-system": "workspace:^",
"@electron/get": "^5.1.0",
"@electron/notarize": "2.5.0",
"@types/js-yaml": "^4.0.9",
@@ -52,6 +55,7 @@
"extract-zip": "^2.0.1",
"fflate": "^0.8.2",
"js-yaml": "^4.2.0",
"koffi": "^3.1.0",
"pnpm": "11.7.0",
"tar": "^7.5.0",
"typescript": "^6.0.3"
@@ -8,11 +8,13 @@ import { resolveDesktopAppId, resolveMacOSNotarizationEnvironment, resolveMacOSS
import { resolveDesktopAutoUpdateConfig } from './desktop-auto-update-environment.mjs'
import { createWindowsTokenSigner } from './windows-sign.mjs'
import { resolveDesktopPolicyEnvironment } from './desktop-policy-environment.mjs'
import { resolveMacOSPackageSettings } from './macos-package-settings.mjs'
import { resolveWindowsSignatureCacheDirectory } from './windows-signature-cache-directory.mjs'
const APP_ROOT = fileURLToPath(new URL('..', import.meta.url))
const SHARED_SETTING = /^(?:DSH_DESKTOP_(?:APP_ID|AUTO_UPDATE_ENV|MANDATORY_UPDATE_(?:CONFIG|(?:TEST|PROD)_ORIGIN))|DOWNLOAD_(?:TEST|PROD)_(?:ORIGIN|COS_BUCKET|COS_SECRET_ID|COS_SECRET_KEY))$/u
const WINDOWS_SETTING = /^DSH_DESKTOP_WINDOWS_(?:CER_FILE|SIGNTOOL|KEY_CONTAINER|TOKEN_PIN)$/u
const MACOS_SETTING = /^(?:DSH_DESKTOP_MACOS_(?:SIGNING_IDENTITY|TEAM_ID)|APPLE_(?:API_KEY|API_KEY_ID|API_ISSUER|ID|APP_SPECIFIC_PASSWORD|TEAM_ID|KEYCHAIN|KEYCHAIN_PROFILE)|CSC_(?:LINK|KEY_PASSWORD))$/u
const WINDOWS_SETTING = /^DSH_DESKTOP_WINDOWS_(?:CER_FILE|SIGNTOOL|KEY_CONTAINER|TOKEN_PIN|SIGNATURE_CACHE_DIR)$/u
const MACOS_SETTING = /^(?:DSH_DESKTOP_MACOS_(?:SIGNING_IDENTITY|TEAM_ID|PACK_CONCURRENCY|DOWNLOAD_PROXY|NOTARIZATION_PROXY)|APPLE_(?:API_KEY|API_KEY_ID|API_ISSUER|ID|APP_SPECIFIC_PASSWORD|TEAM_ID|KEYCHAIN|KEYCHAIN_PROFILE)|CSC_(?:LINK|KEY_PASSWORD))$/u
const AMBIENT_RELEASE_SETTING = /^(?:DSH_DESKTOP_(?:APP_ID|AUTO_UPDATE_ENV|MANDATORY_UPDATE_.*|WINDOWS_.*|MACOS_.*)|APPLE_.*|(?:WIN_)?CSC_.*|DOWNLOAD_(?:TEST|PROD)_.*)$/iu
const FILE_SETTINGS = ['DSH_DESKTOP_WINDOWS_CER_FILE', 'DSH_DESKTOP_WINDOWS_SIGNTOOL', 'APPLE_API_KEY', 'APPLE_KEYCHAIN', 'CSC_LINK']
@@ -76,6 +78,7 @@ function requireReadableFile(environment, name) {
export function validateDesktopPackageEnvironment(environment, target, options = {}) {
resolveDesktopAppId(environment)
resolveDesktopPolicyEnvironment(environment)
if (target.platform === 'darwin') resolveMacOSPackageSettings(environment)
if (options.unsigned) return
if (!options.prepareOnly) resolveDesktopAutoUpdateConfig(environment, target.platform, target.arch)
if (target.platform === 'win32') {
@@ -85,6 +88,7 @@ export function validateDesktopPackageEnvironment(environment, target, options =
tokenPin: environment.DSH_DESKTOP_WINDOWS_TOKEN_PIN,
keyContainer: environment.DSH_DESKTOP_WINDOWS_KEY_CONTAINER,
})
if (!options.prepareOnly) resolveWindowsSignatureCacheDirectory(environment)
} else {
resolveMacOSSigningEnvironment(environment)
const strategies = [
@@ -2,6 +2,7 @@
export interface DesktopPolicyEnvironment {
origin: string
allowedPageOrigins: string[]
allowedAuthOrigins?: string[]
authentication: 'anonymous' | 'feishu-test'
[key: string]: unknown
}
@@ -30,7 +30,15 @@ export function resolveDesktopPolicyEnvironment(environment) {
}
const pages = settings.allowedPageOrigins ?? [selected]
if (!Array.isArray(pages) || pages.length === 0) throw new Error('desktop package: allowedPageOrigins must be a nonempty array')
const authOrigins = settings.allowedAuthOrigins
if (deployment === 'test' && (!Array.isArray(authOrigins) || authOrigins.length === 0)) {
throw new Error('desktop package: test policy requires nonempty allowedAuthOrigins')
}
if (deployment === 'production' && authOrigins !== undefined) {
throw new Error('desktop package: production policy must not configure allowedAuthOrigins')
}
return { ...settings, origin: selected,
allowedPageOrigins: pages.map(value => origin(value, 'allowedPageOrigins')),
...(deployment === 'test' ? { allowedAuthOrigins: authOrigins.map(value => origin(value, 'allowedAuthOrigins')) } : {}),
authentication: deployment === 'test' ? 'feishu-test' : 'anonymous' }
}
@@ -0,0 +1,9 @@
/** Separate upload and Apple processing timings without replacing electron-notarize's qualification. */
/**
* Run the requested Apple command, splitting submit --wait into submit --no-wait and wait.
* @param args Arguments from the pinned electron-notarize library.
* @param directory Existing packaging journal.
* @param invoke Apple command executor.
* @returns Final tool output consumed by electron-notarize; upload failure prevents waiting.
*/
export function runLoggedNotarytool(args: readonly string[], directory?: string, invoke?: (args: readonly string[]) => Promise<string>): Promise<string>
+83
View File
@@ -0,0 +1,83 @@
#!/usr/bin/env node
/** Adapt electron-notarize's combined submit/wait into separately timed Apple operations. */
import { execFile } from 'node:child_process'
import { basename, resolve } from 'node:path'
import { fileURLToPath } from 'node:url'
import { promisify } from 'node:util'
import { recordPackagingEvent, packagingOutputRedactor } from './packaging-run.mjs'
import { packagingStep } from './packaging-step.mjs'
const exec = promisify(execFile)
const AUTH_FLAGS = new Set(['--apple-id', '--password', '--team-id', '--key', '--key-id', '--issuer', '--keychain', '--keychain-profile'])
async function execute(args) {
try {
const { stdout } = await exec('/usr/bin/xcrun', ['notarytool', ...args], { encoding: 'utf8', maxBuffer: 16 * 1024 * 1024 })
return stdout
} catch (error) {
// Apple can report rejection with a nonzero exit; electron-notarize needs its JSON ID to retrieve diagnostics.
if (args[0] === 'wait' && typeof error.code === 'number' && typeof error.stdout === 'string' && error.stdout.trim()) return error.stdout
throw error
}
}
/**
* Return only the final JSON to electron-notarize, which owns acceptance checks and stapling retries.
* @param {readonly string[]} args Arguments supplied by the pinned electron-notarize library.
* @param {string | undefined} directory Existing packaging journal.
* @param {(args: readonly string[]) => Promise<string>} invoke Apple command executor.
* @returns {Promise<string>} Tool output; a failed upload never starts waiting.
*/
export async function runLoggedNotarytool(args, directory, invoke = execute) {
const credentials = args.filter((_, index) => AUTH_FLAGS.has(args[index - 1]))
if (args[0] !== 'submit' || !args.includes('--wait')) {
return packagingStep(directory, `notarytool:${args[0]}`, async () => {
const output = await invoke(args)
if (directory && args[0] === 'log') {
let text = ''
const redactor = packagingOutputRedactor(credentials, chunk => { text += chunk })
redactor.write(Buffer.from(output))
redactor.end()
recordPackagingEvent(directory, { type: 'notary-diagnostics', submissionId: args[1], text })
}
return output
}, credentials)
}
const artifact = basename(args[1])
const uploaded = await packagingStep(directory, `notarytool:upload:${artifact}`,
() => invoke(args.filter(arg => arg !== '--wait').concat('--no-wait')), credentials)
const submission = JSON.parse(uploaded)
if (typeof submission.id !== 'string' || !/^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/iu.test(submission.id)) {
throw new Error('desktop notarization: submit returned no valid submission ID')
}
if (directory) recordPackagingEvent(directory, { type: 'notary-submission', artifact, submissionId: submission.id })
const authorization = args.flatMap((arg, index) => AUTH_FLAGS.has(arg) ? [arg, args[index + 1]] : [])
const rejected = new Error('desktop notarization: Apple did not accept the submission')
let rejectedOutput
try {
return await packagingStep(directory, `notarytool:wait:${artifact}`, async () => {
const output = await invoke(['wait', submission.id, ...authorization, '--output-format', 'json'])
const result = JSON.parse(output)
if (directory) recordPackagingEvent(directory, { type: 'notary-result', artifact, submissionId: submission.id, status: result.status })
if (result.id !== submission.id) throw new Error('desktop notarization: wait returned a different submission ID')
if (result.status !== 'Accepted') {
rejectedOutput = output
throw rejected
}
return output
}, credentials)
} catch (error) {
// Preserve rejected JSON for electron-notarize's diagnostic retrieval without marking the wait successful.
if (error === rejected) return rejectedOutput
throw error
}
}
if (process.argv[1] && fileURLToPath(import.meta.url) === resolve(process.argv[1])) {
try { process.stdout.write(await runLoggedNotarytool(process.argv.slice(2), process.env.DSH_DESKTOP_PACKAGING_RUN_DIR)) }
catch {
// execFile errors include credential-bearing argv; detailed failures are redacted in the journal.
process.stderr.write('desktop notarization: Apple command failed; see packaging events.jsonl\n')
process.exitCode = 1
}
}
@@ -0,0 +1,61 @@
/** Bind reusable thin Mach-O signatures to the actual certificate, tools, identifier, and entitlements. */
import { spawnSync } from 'node:child_process'
import { createHash } from 'node:crypto'
import { mkdtempSync, readFileSync, rmSync } from 'node:fs'
import { tmpdir, release } from 'node:os'
import { join } from 'node:path'
import { isDeepStrictEqual } from 'node:util'
import type { MacOSSigningEnvironment } from './desktop-release-environment.mjs'
import { assertMacOSRuntimeSignatureDetails, signMacOSRuntimeCode } from './verify-macos-signature.mjs'
import type { MacOSCachedSigner } from './macos-signature-cache.ts'
function apple(command: string, args: string[], input?: string): { stdout: string; stderr: string } {
const result = spawnSync(command, args, { encoding: 'utf8', input, timeout: 120_000 })
if (result.error || result.status !== 0 || result.signal) throw new Error(`macOS signature cache: ${command} verification failed`)
return result
}
function digest(bytes: Buffer): string { return createHash('sha256').update(bytes).digest('hex') }
function plist(xml: string): unknown {
if (xml.trim() === '') return {}
return JSON.parse(apple('/usr/bin/plutil', ['-convert', 'json', '-o', '-', '-'], xml).stdout) as unknown
}
function inspect(path: string): { certificate: string; details: string; entitlements: unknown } {
const directory = mkdtempSync(join(tmpdir(), 'dsh-signature-policy-'))
try {
const prefix = join(directory, 'certificate')
const result = apple('/usr/bin/codesign', ['--display', '--verbose=4', `--extract-certificates=${prefix}`, '--entitlements', '-', '--xml', path])
return { certificate: digest(readFileSync(`${prefix}0`)), details: result.stderr, entitlements: plist(result.stdout) }
} finally { rmSync(directory, { recursive: true, force: true }) }
}
/**
* Resolve a policy from the keychain's signed probe and current implementation; no credential enters the key.
* @param probe Verified thin executable signed by this invocation's temporary keychain.
* @returns Factory for per-file signing and verification policies.
*/
export function macOSCachePolicy(probe: string):
(identifier: string, expected: MacOSSigningEnvironment, entitlements?: string) => MacOSCachedSigner {
const certificate = inspect(probe).certificate
const tools = ['/usr/bin/codesign', join(import.meta.dirname, 'verify-macos-signature.mjs'),
join(import.meta.dirname, 'macos-cache-policy.ts'), join(import.meta.dirname, 'macos-signature-cache.ts')].map(path => digest(readFileSync(path)))
return (identifier, expected, entitlements) => {
const entitlementBytes = entitlements === undefined ? undefined : readFileSync(entitlements)
const desired = entitlementBytes === undefined ? {} : plist(entitlementBytes.toString('utf8'))
return {
policy: JSON.stringify({ certificate, identifier, expected, entitlements: entitlementBytes?.toString('base64') ?? null, tools, os: release() }),
sign: path => signMacOSRuntimeCode(path, identifier, expected, entitlements),
verify: (path) => {
if (!['cefaedfe', 'cffaedfe', 'feedface', 'feedfacf'].includes(readFileSync(path).subarray(0, 4).toString('hex'))) {
throw new Error('macOS signature cache: only thin Mach-O files can be reused')
}
apple('/usr/bin/codesign', ['--verify', '--strict', '--verbose=2', path])
const actual = inspect(path)
assertMacOSRuntimeSignatureDetails(actual.details, expected)
if (actual.certificate !== certificate || !actual.details.split(/\r?\n/u).includes(`Identifier=${identifier}`)
|| !isDeepStrictEqual(actual.entitlements, desired)) {
throw new Error('macOS signature cache: signature does not match certificate, identifier, or entitlements')
}
},
}
}
}
@@ -0,0 +1,222 @@
/** Temporarily route Apple tools through the active macOS service; retain recovery data before mutation. */
import { execFileSync } from 'node:child_process'
import { closeSync, mkdirSync, openSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
import { connect } from 'node:net'
import { homedir } from 'node:os'
import { dirname, join, resolve } from 'node:path'
import { tryLockExclusive } from '@deepseek-ai/node-addon-system/flock'
interface ProxyState {
readonly enabled: boolean
readonly server: string
readonly port: number
}
interface ProxyRecord {
readonly pid: number
readonly service: string
readonly http: ProxyState
readonly https: ProxyState
}
interface ProxyOperations {
readonly command: (executable: string, args: readonly string[]) => string
readonly reachable: (url: URL) => Promise<void>
readonly ownerAlive: (pid: number) => boolean
}
const LOCK = join(homedir(), 'Library', 'Caches', 'com.deepseek.harness', 'notarization-proxy')
const RECOVERY = 'pnpm --dir apps/desktop run restore:mac-proxy'
const NETWORKSETUP = '/usr/sbin/networksetup'
const operations: ProxyOperations = {
command(executable, args) {
return execFileSync(executable, [...args], { encoding: 'utf8', env: { PATH: '/usr/bin:/bin:/usr/sbin:/sbin', LANG: 'C' }, timeout: 15_000 })
},
reachable(url) {
return new Promise((resolveConnection, reject) => {
const socket = connect({ host: url.hostname.replace(/^\[|\]$/gu, ''), port: Number(url.port || '80') })
let failure: Error | undefined
socket.setTimeout(5000, () => socket.destroy(new Error('desktop package: notarization proxy connection timed out')))
socket.once('error', () => { failure = new Error('desktop package: notarization proxy is unreachable') })
socket.once('connect', () => socket.destroy())
socket.once('close', () => { if (failure) reject(failure); else resolveConnection() })
})
},
ownerAlive(pid) {
try { process.kill(pid, 0); return true } catch (error) {
if ((error as NodeJS.ErrnoException).code === 'ESRCH') return false
throw error
}
},
}
async function withProxyLock<T>(lock: string, action: () => Promise<T>): Promise<T> {
mkdirSync(dirname(lock), { recursive: true, mode: 0o700 })
// Keep this inode across transactions: unlinking it would allow two independent locks.
const fd = openSync(`${lock}.flock`, 'a', 0o600)
try {
try { await tryLockExclusive(fd) } catch (error) {
const code = (error as NodeJS.ErrnoException).code
if (code !== 'EAGAIN' && code !== 'EWOULDBLOCK') throw error
throw new Error('desktop package: another run or proxy recovery is active; wait for it to finish')
}
return await action()
} finally { closeSync(fd) }
}
function readProxy(service: string, secure: boolean, ops: ProxyOperations): ProxyState {
const output = ops.command(NETWORKSETUP, [secure ? '-getsecurewebproxy' : '-getwebproxy', service])
const enabled = /^Enabled: (Yes|No)$/mu.exec(output)?.[1]
const server = /^Server:[ \t]?(.*)$/mu.exec(output)?.[1]
const port = /^Port: (\d+)$/mu.exec(output)?.[1]
if (enabled === undefined || server === undefined || port === undefined
|| !/^Authenticated Proxy Enabled: 0$/mu.test(output) || Number(port) > 65535) {
throw new Error('desktop package: cannot preserve system proxy settings; authenticated proxies are unsupported')
}
return { enabled: enabled === 'Yes', server, port: Number(port) }
}
function activeService(ops: ProxyOperations): string {
const route = ops.command('/sbin/route', ['-n', 'get', 'default'])
const device = /^\s*interface: (\S+)$/mu.exec(route)?.[1]
const services = ops.command(NETWORKSETUP, ['-listnetworkserviceorder'])
const matches = [...services.matchAll(/^\(\d+\) (.+)\n\(Hardware Port: .+, Device: ([^)]+)\)$/gmu)]
.filter(match => match[2] === device)
if (!device || matches.length !== 1) throw new Error('desktop package: cannot identify one active network service for notarization proxy')
return matches[0]![1]!
}
function setProxy(service: string, secure: boolean, state: ProxyState, ops: ProxyOperations): void {
ops.command(NETWORKSETUP, [secure ? '-setsecurewebproxy' : '-setwebproxy', service, state.server, String(state.port), 'off'])
ops.command(NETWORKSETUP, [secure ? '-setsecurewebproxystate' : '-setwebproxystate', service, state.enabled ? 'on' : 'off'])
const actual = readProxy(service, secure, ops)
if (JSON.stringify(actual) !== JSON.stringify(state)) throw new Error('desktop package: system proxy change did not take effect')
}
function restore(record: ProxyRecord, ops: ProxyOperations): void {
const errors: unknown[] = []
for (const [secure, state] of [[false, record.http], [true, record.https]] as const) {
try {
if (!state.enabled && state.server === '' && state.port === 0) {
ops.command(NETWORKSETUP, [secure ? '-setsecurewebproxystate' : '-setwebproxystate', record.service, 'off'])
if (readProxy(record.service, secure, ops).enabled) throw new Error('desktop package: system proxy disable did not take effect')
} else setProxy(record.service, secure, state, ops)
} catch (error) { errors.push(error) }
}
if (errors.length) throw new AggregateError(errors, `desktop package: proxy restoration failed; retry ${RECOVERY}`)
}
function readRecord(lock: string): ProxyRecord {
const value: unknown = JSON.parse(readFileSync(join(lock, 'original.json'), 'utf8'))
function isState(state: unknown): state is ProxyState {
if (state === null || typeof state !== 'object') return false
const s = state as Partial<ProxyState>
return typeof s.enabled === 'boolean' && typeof s.server === 'string' && !/[\r\n\0]/u.test(s.server)
&& typeof s.port === 'number' && Number.isInteger(s.port) && s.port >= 0 && s.port <= 65535
}
if (value === null || typeof value !== 'object') throw new Error('desktop package: invalid proxy recovery record')
const record = value as Partial<ProxyRecord>
if (!Number.isSafeInteger(record.pid) || record.pid! <= 0 || typeof record.service !== 'string'
|| !record.service || /[\r\n\0]/u.test(record.service) || !isState(record.http) || !isState(record.https)) {
throw new Error('desktop package: invalid proxy recovery record')
}
return record as ProxyRecord
}
/**
* Restore an interrupted run only after its owner exits; active or incomplete records fail closed.
* Originally empty proxies are disabled; their temporary server and port may remain stored.
* @param lock Per-user lock shared across checkouts; tests supply a private directory.
* @param ops Host operations; tests supply isolated system settings.
* @returns Resolves after restoration under the shared file lock; retains the record on failure.
*/
export async function restoreMacOSNotarizationProxy(lock: string = LOCK, ops: ProxyOperations = operations): Promise<void> {
await withProxyLock(lock, async () => {
const record = readRecord(lock)
if (ops.ownerAlive(record.pid)) throw new Error('desktop package: proxy owner is still running; wait for packaging to finish')
restore(record, ops)
rmSync(lock, { recursive: true })
})
}
/**
* Hold the system HTTP/HTTPS proxy until all callback work settles, including after SIGINT/SIGTERM.
* @param proxyUrl Validated HTTP proxy origin, or undefined for unchanged system networking.
* @param action Work that drains every notarization lane before resolving or rejecting.
* @param lock Per-user exclusive recovery directory, shared across checkouts.
* @param ops Host operations; tests supply isolated system settings.
* @param report Reports restoration state to the packaging journal without exposing proxy addresses.
* @returns Callback result after verified restoration; forced termination leaves a recovery record.
*/
export async function withMacOSNotarizationProxy<T>(
proxyUrl: string | undefined,
action: () => Promise<T>,
lock: string = LOCK,
ops: ProxyOperations = operations,
report: (status: 'not-used' | 'restoration-pending' | 'enabled' | 'restored' | 'restore-failed') => void = () => {},
): Promise<T> {
if (proxyUrl === undefined) { report('not-used'); return action() }
const url = new URL(proxyUrl)
await ops.reachable(url)
return withProxyLock(lock, async () => {
try { mkdirSync(lock, { mode: 0o700 }) } catch (error) {
if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error
throw new Error(`desktop package: another run or interrupted proxy record exists; after its owner exits, run ${RECOVERY}`)
}
let original: ProxyRecord | undefined
let saved = false
let workError: unknown
let signal: string | undefined
const interrupted = (received: string) => {
signal = received
process.stderr.write('desktop package: waiting for notarization work to stop before restoring the system proxy\n')
}
process.on('SIGINT', interrupted)
process.on('SIGTERM', interrupted)
try {
const service = activeService(ops)
// PAC, discovery and SOCKS can override explicit proxies; do not silently change those policies.
const pac = ops.command(NETWORKSETUP, ['-getautoproxyurl', service])
const discovery = ops.command(NETWORKSETUP, ['-getproxyautodiscovery', service])
const socks = ops.command(NETWORKSETUP, ['-getsocksfirewallproxy', service])
if (!/^Enabled: No$/mu.test(pac) || !/^Auto Proxy Discovery: Off$/mu.test(discovery) || !/^Enabled: No$/mu.test(socks)) {
throw new Error('desktop package: disable PAC, proxy discovery and SOCKS on the active service before configuring a notarization proxy')
}
original = { pid: process.pid, service, http: readProxy(service, false, ops), https: readProxy(service, true, ops) }
writeFileSync(join(lock, 'original.json'), `${JSON.stringify(original)}\n`, { flag: 'wx', mode: 0o600, flush: true })
saved = true
report('restoration-pending')
const state = { enabled: true, server: url.hostname.replace(/^\[|\]$/gu, ''), port: Number(url.port || '80') }
setProxy(service, false, state, ops)
setProxy(service, true, state, ops)
report('enabled')
const result = await action()
if (signal) throw new Error(`desktop package: interrupted by ${signal}`)
return result
} catch (error) {
workError = error
throw error
} finally {
try {
if (saved && original) {
try { restore(original, ops) } catch (error) { report('restore-failed'); throw error }
report('restored')
}
rmSync(lock, { recursive: true })
} catch (error) {
if (workError !== undefined) {
throw new AggregateError([workError, error], `desktop package: work and proxy cleanup failed; run ${RECOVERY}`)
}
throw error
} finally {
process.off('SIGINT', interrupted)
process.off('SIGTERM', interrupted)
}
}
})
}
if (process.argv[1] !== undefined && import.meta.filename === resolve(process.argv[1])) {
if (process.platform !== 'darwin') throw new Error('desktop package: proxy recovery requires macOS')
await restoreMacOSNotarizationProxy()
console.log('desktop package: original system proxy restored')
}
@@ -0,0 +1,23 @@
/** File-owned macOS packaging concurrency and stage-specific proxies. */
/** Validated settings shared by preflight and stage execution. */
export interface MacOSPackageSettings {
readonly packConcurrency: number
readonly downloadProxy?: string
readonly notarizationProxy?: string
}
/**
* Validate tuning before any build or network operation.
* @param environment File-owned packaging settings.
* @returns Resolved settings; empty proxy fields preserve inherited networking.
*/
export function resolveMacOSPackageSettings(environment: NodeJS.ProcessEnv): MacOSPackageSettings
/**
* Override routing only in download-capable subprocesses without mutating the parent.
* @param environment Parent environment.
* @param proxyUrl Validated proxy, or undefined to preserve inherited settings.
* @returns Child environment; explicit routing bypasses only local hosts.
*/
export function macOSDownloadEnvironment(environment: NodeJS.ProcessEnv, proxyUrl?: string): NodeJS.ProcessEnv
@@ -0,0 +1,47 @@
/** Resolve file-owned macOS packaging concurrency and stage-specific proxies. */
function proxy(environment, name, protocols) {
const value = environment[name]?.trim()
if (!value) return undefined
let parsed
try { parsed = new URL(value) } catch { throw new Error(`desktop package: ${name} must be a proxy URL`) }
if (!protocols.includes(parsed.protocol) || !parsed.hostname || parsed.username || parsed.password
|| parsed.pathname !== '/' || parsed.search || parsed.hash) {
throw new Error(`desktop package: ${name} requires an unauthenticated ${protocols.join('/')} proxy origin`)
}
return parsed.origin
}
/**
* Validate tuning before any build or network operation.
* @param {NodeJS.ProcessEnv} environment File-owned packaging settings.
* @returns {{packConcurrency: number, downloadProxy?: string, notarizationProxy?: string}} Resolved settings; empty proxy fields preserve inherited networking.
*/
export function resolveMacOSPackageSettings(environment) {
const concurrency = environment.DSH_DESKTOP_MACOS_PACK_CONCURRENCY ?? '4'
if (!/^[1-9]\d*$/u.test(concurrency) || !Number.isSafeInteger(Number(concurrency))) {
throw new Error('desktop package: DSH_DESKTOP_MACOS_PACK_CONCURRENCY must be a positive integer')
}
return {
packConcurrency: Number(concurrency),
downloadProxy: proxy(environment, 'DSH_DESKTOP_MACOS_DOWNLOAD_PROXY', ['http:', 'https:']),
notarizationProxy: proxy(environment, 'DSH_DESKTOP_MACOS_NOTARIZATION_PROXY', ['http:']),
}
}
/**
* Override proxy routing only in download-capable subprocesses, including Electron and pnpm.
* @param {NodeJS.ProcessEnv} environment Parent environment, never mutated.
* @param {string | undefined} proxyUrl Validated download proxy, or undefined to preserve inherited settings.
* @returns {NodeJS.ProcessEnv} Child environment; explicit routing bypasses only local hosts.
*/
export function macOSDownloadEnvironment(environment, proxyUrl) {
if (proxyUrl === undefined) return { ...environment }
return {
...Object.fromEntries(Object.entries(environment).filter(([name]) =>
!/^(?:(?:https?|all|no)_proxy|npm_config_(?:https?_proxy|proxy|noproxy)|ELECTRON_GET_USE_PROXY)$/iu.test(name))),
HTTP_PROXY: proxyUrl, HTTPS_PROXY: proxyUrl, http_proxy: proxyUrl, https_proxy: proxyUrl,
NO_PROXY: 'localhost,127.0.0.1,::1', no_proxy: 'localhost,127.0.0.1,::1',
ELECTRON_GET_USE_PROXY: '1',
}
}
+25 -6
View File
@@ -5,15 +5,17 @@ import { closeSync, openSync, readSync } from 'node:fs'
import { join } from 'node:path'
import { inventoryDesktopRuntime } from '../src/runtime-tree.ts'
import type { MacOSSigningEnvironment } from './desktop-release-environment.mjs'
import { cachedMacOSSignature, pruneMacOSSignatureCache } from './macos-signature-cache.ts'
import { macOSCachePolicy } from './macos-cache-policy.ts'
import { signMacOSRuntimeCode, verifyMacOSRuntimeCode } from './verify-macos-signature.mjs'
const MACH_O_MAGICS = new Set(['cafebabe', 'cafebabf', 'cefaedfe', 'cffaedfe', 'feedface', 'feedfacf', 'bebafeca', 'bfbafeca'])
function isMachO(path: string): boolean {
function magic(path: string): string {
const descriptor = openSync(path, 'r')
try {
const header = Buffer.alloc(4)
return readSync(descriptor, header, 0, 4, 0) === 4 && MACH_O_MAGICS.has(header.toString('hex'))
return readSync(descriptor, header, 0, 4, 0) === 4 ? header.toString('hex') : ''
} finally { closeSync(descriptor) }
}
@@ -22,10 +24,16 @@ function isMachO(path: string): boolean {
* @param root - Self-contained production runtime without symlinks.
* @param appId - Release application identifier.
* @param expected - Required signing identity.
* @param cacheDirectory Optional content-addressed cache; requires the keychain-owned signing probe.
* @returns Number of signed native files.
*/
export async function signMacOSRuntime(root: string, appId: string, expected: MacOSSigningEnvironment): Promise<number> {
const files = inventoryDesktopRuntime(root).map(file => file.path).filter(path => isMachO(join(root, path)))
export async function signMacOSRuntime(
root: string, appId: string, expected: MacOSSigningEnvironment, cacheDirectory?: string,
): Promise<number> {
const files = inventoryDesktopRuntime(root).map(file => file.path).filter(path => MACH_O_MAGICS.has(magic(join(root, path))))
const policy = cacheDirectory === undefined ? undefined : macOSCachePolicy(process.env.DSH_DESKTOP_MACOS_SIGNING_PROBE ?? '')
let hits = 0
let misses = 0
let next = 0
const workers = Array.from({ length: Math.min(4, files.length) }, async () => {
for (;;) {
@@ -34,12 +42,23 @@ export async function signMacOSRuntime(root: string, appId: string, expected: Ma
const identifier = `${appId}.runtime.${createHash('sha256').update(path).digest('hex')}`
const entitlements = path === 'dependencies/node/bin/node'
? join(import.meta.dirname, 'node-entitlements.plist') : undefined
await signMacOSRuntimeCode(join(root, path), identifier, expected, entitlements)
verifyMacOSRuntimeCode(join(root, path), expected)
const file = join(root, path)
const thin = ['cefaedfe', 'cffaedfe', 'feedface', 'feedfacf'].includes(magic(file))
if (cacheDirectory !== undefined && policy !== undefined && thin) {
if (await cachedMacOSSignature(file, cacheDirectory, policy(identifier, expected, entitlements))) hits++
else misses++
} else {
await signMacOSRuntimeCode(file, identifier, expected, entitlements)
verifyMacOSRuntimeCode(file, expected)
}
}
})
const results = await Promise.allSettled(workers)
const errors = results.filter(result => result.status === 'rejected').map(result => result.reason as unknown)
if (errors.length > 0) throw new AggregateError(errors, 'desktop runtime: native signing failed')
if (cacheDirectory !== undefined) {
pruneMacOSSignatureCache(cacheDirectory)
console.info(`desktop macOS signing cache: ${hits} hits, ${misses} misses, ${files.length - hits - misses} uncached`)
}
return files.length
}
@@ -0,0 +1,121 @@
/** Reuse verified standalone signatures by file content and complete signing policy. */
import { createHash } from 'node:crypto'
import { chmodSync, copyFileSync, existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, renameSync, rmSync, writeFileSync } from 'node:fs'
import { dirname, join } from 'node:path'
function digest(bytes: Buffer | string): string { return createHash('sha256').update(bytes).digest('hex') }
function regular(path: string): void {
if (!lstatSync(path).isFile()) throw new Error(`macOS signature cache: expected regular file ${path}`)
}
function directory(path: string): void {
if (!lstatSync(path).isDirectory()) throw new Error(`macOS signature cache: expected directory ${path}`)
}
function ensureDirectory(path: string): void {
if (dirname(path) !== path) ensureDirectory(dirname(path))
if (!existsSync(path)) {
try { mkdirSync(path, { mode: 0o700 }) }
catch (error) { if (!(error instanceof Error && 'code' in error && error.code === 'EEXIST')) throw error }
}
directory(path)
}
function readEntry(entry: string, key: string): { payload: string; sha256: string } {
directory(entry)
const record = join(entry, 'record.json')
const payload = join(entry, 'code')
regular(record); regular(payload)
const metadata = JSON.parse(readFileSync(record, 'utf8')) as { key?: unknown; sha256?: unknown }
if (metadata.key !== key || typeof metadata.sha256 !== 'string') throw new Error(`macOS signature cache: invalid record ${entry}`)
if (digest(readFileSync(payload)) !== metadata.sha256) throw new Error(`macOS signature cache: damaged payload ${entry}`)
return { payload, sha256: metadata.sha256 }
}
/** A signer whose verifier checks all policy fields represented by its stable key. */
export interface MacOSCachedSigner {
readonly policy: string
/** @param path Private executable copy to sign. @returns Completion after all owned signing activity settles. */
sign: (path: string) => Promise<void>
/** @param path Executable whose signature must satisfy the complete policy. */
verify: (path: string) => void
}
/**
* Sign a private copy or validate a cached copy, then atomically replace an unchanged input.
* @param path Regular standalone executable owned by this build.
* @param cacheRoot Private content-addressed signature storage.
* @param signer Complete signing policy and its signing/verification operations.
* @returns Whether a previously verified signature was reused.
*/
export async function cachedMacOSSignature(path: string, cacheRoot: string, signer: MacOSCachedSigner): Promise<boolean> {
regular(path)
const mode = lstatSync(path).mode & 0o777
const input = digest(readFileSync(path))
const key = digest(JSON.stringify({ schema: 1, input, mode, policy: signer.policy }))
ensureDirectory(cacheRoot)
const entry = join(cacheRoot, key)
const work = mkdtempSync(join(dirname(path), '.dsh-sign-'))
const candidate = join(work, 'code')
const unchanged = (): void => {
regular(path)
if (digest(readFileSync(path)) !== input || (lstatSync(path).mode & 0o777) !== mode) {
throw new Error('macOS signature cache: input changed during signing')
}
}
try {
const hit = existsSync(entry)
if (hit) {
const { payload, sha256 } = readEntry(entry, key)
copyFileSync(payload, candidate)
if (digest(readFileSync(candidate)) !== sha256) throw new Error(`macOS signature cache: damaged payload ${entry}`)
} else {
copyFileSync(path, candidate)
if (digest(readFileSync(candidate)) !== input) throw new Error('macOS signature cache: input changed while copying')
await signer.sign(candidate)
}
chmodSync(candidate, mode)
const signed = digest(readFileSync(candidate))
signer.verify(candidate)
if (digest(readFileSync(candidate)) !== signed) throw new Error('macOS signature cache: candidate changed during verification')
unchanged()
if (!hit) {
const staging = mkdtempSync(join(cacheRoot, '.pending-'))
try {
copyFileSync(candidate, join(staging, 'code'))
if (digest(readFileSync(join(staging, 'code'))) !== signed) throw new Error('macOS signature cache: staged payload changed')
writeFileSync(join(staging, 'record.json'), `${JSON.stringify({ key, sha256: signed })}\n`, { mode: 0o600, flag: 'wx', flush: true })
try { renameSync(staging, entry) }
catch (error) {
if (!(error instanceof Error && 'code' in error && ['ENOTEMPTY', 'EEXIST'].includes(String(error.code)))) throw error
const winner = readEntry(entry, key)
signer.verify(winner.payload)
}
} finally { rmSync(staging, { recursive: true, force: true }) }
}
unchanged()
renameSync(candidate, path)
return hit
} finally { rmSync(work, { recursive: true, force: true }) }
}
/**
* Retain newest complete cache entries within a one-GiB payload budget; active readers fail closed on eviction races.
* @param root Cache directory owned by packaging.
* @returns Nothing.
*/
export function pruneMacOSSignatureCache(root: string): void {
if (!existsSync(root)) return
directory(root)
const entries = readdirSync(root).filter(name => /^[a-f0-9]{64}$/u.test(name)).map((name) => {
const path = join(root, name)
directory(path)
const payload = join(path, 'code')
regular(payload)
const stat = lstatSync(payload)
return { path, bytes: stat.size, time: stat.mtimeMs }
}).sort((a, b) => b.time - a.time)
let bytes = 0
for (const entry of entries) {
bytes += entry.bytes
if (bytes > 1024 ** 3) rmSync(entry.path, { recursive: true })
}
}
@@ -49,7 +49,7 @@ export async function withMacOSSigningKeychain(environment, action, run = execut
run('/bin/cp', ['/usr/bin/true', probe])
run('/usr/bin/codesign', ['--force', '--sign', `Developer ID Application: ${environment.DSH_DESKTOP_MACOS_SIGNING_IDENTITY}`, '--keychain', keychain, '--timestamp', '--options', 'runtime', probe])
run('/usr/bin/codesign', ['--verify', '--strict', probe])
const childEnvironment = { ...environment, CSC_KEYCHAIN: keychain }
const childEnvironment = { ...environment, CSC_KEYCHAIN: keychain, DSH_DESKTOP_MACOS_SIGNING_PROBE: probe }
delete childEnvironment.CSC_LINK
delete childEnvironment.CSC_KEY_PASSWORD
await action(childEnvironment)
@@ -0,0 +1,28 @@
/** Explicit current-account migration and storage inspection under the signing-stage lock. */
import { parseArgs } from 'node:util'
import { loadDesktopPackageEnvironment } from './desktop-package-environment.mjs'
import { prepareWindowsSignatureCacheDirectory, resolveWindowsSignatureCacheDirectory } from './windows-signature-cache-directory.mjs'
import { maintainSignatureCache, migrateSignatureCache } from './windows-signature-cache.mjs'
import { withWindowsSigningStage } from './windows-signing-stage.mjs'
const { values } = parseArgs({ options: {
from: { type: 'string' }, usage: { type: 'boolean' }, clear: { type: 'boolean' }, directory: { type: 'string' },
} })
if ([values.from !== undefined, values.usage === true, values.clear === true].filter(Boolean).length !== 1) {
throw new Error('Specify exactly one of --from <old-cache>, --usage or --clear')
}
const environment = values.directory === undefined ? loadDesktopPackageEnvironment('win32')
: { DSH_DESKTOP_WINDOWS_SIGNATURE_CACHE_DIR: values.directory }
const root = resolveWindowsSignatureCacheDirectory(environment)
const record = event => process.stdout.write(`${JSON.stringify(event)}\n`)
await withWindowsSigningStage({ stage: values.from !== undefined ? 'cache-migration' : 'cache-maintenance', record }, async () => {
await prepareWindowsSignatureCacheDirectory(root)
if (values.from !== undefined) {
const source = resolveWindowsSignatureCacheDirectory({ DSH_DESKTOP_WINDOWS_SIGNATURE_CACHE_DIR: values.from })
await prepareWindowsSignatureCacheDirectory(source, true)
record({ type: 'signature-cache-migration-summary', ...await migrateSignatureCache({ source, root, record }) })
return
}
record({ type: values.clear ? 'signature-cache-cleared' : 'signature-cache-usage', root,
...await maintainSignatureCache(root, values.clear) })
})
@@ -1,6 +1,6 @@
/** Notarize and qualify macOS disk images after electron-builder creates them. */
import { notarize } from '@electron/notarize'
import { notarizeMacOS } from './notarize-macos.mjs'
import { rmSync } from 'node:fs'
import { resolveMacOSNotarizationEnvironment } from './desktop-release-environment.mjs'
import { verifyMacOSDiskImage } from './verify-macos-signature.mjs'
@@ -18,7 +18,7 @@ export async function notarizeMacOSDiskImageArtifact(
artifact,
env,
expected,
submit = notarize,
submit = notarizeMacOS,
verify = verifyMacOSDiskImage,
) {
if (!artifact.file.endsWith('.dmg')) return
@@ -0,0 +1,8 @@
/** Notarize with separate upload and wait timings while preserving signature checks and stapling. */
import type { MacOSNotarizationEnvironment } from './desktop-release-environment.mjs'
/**
* Notarize and staple an App or DMG through the measured notarytool adapter.
* @param options Validated Apple credentials and artifact path.
* @returns Resolves after acceptance and stapling; failures remain in the packaging journal.
*/
export function notarizeMacOS(options: MacOSNotarizationEnvironment & { appPath: string }): Promise<void>
+15
View File
@@ -0,0 +1,15 @@
/** Preserve electron-notarize's signature checks and stapling while recording separate Apple phases. */
import { fileURLToPath } from 'node:url'
import { notarize } from '@electron/notarize'
import { packagingStep } from './packaging-step.mjs'
/**
* Notarize and staple one App or DMG through the measured notarytool adapter.
* @param {object} options Validated credentials and appPath accepted by electron-notarize.
* @returns {Promise<void>} Resolves only after Apple acceptance and stapling.
*/
export async function notarizeMacOS(options) {
const secrets = Object.entries(options).filter(([name]) => /password|key|appleId/iu.test(name)).map(([, value]) => String(value))
await packagingStep(process.env.DSH_DESKTOP_PACKAGING_RUN_DIR, 'notarize-and-staple',
() => notarize({ ...options, notarytoolPath: fileURLToPath(new URL('./logged-notarytool.mjs', import.meta.url)) }), secrets)
}
+8 -6
View File
@@ -4,7 +4,8 @@ import { execFile } from 'node:child_process'
import { mkdtemp, rename, rm, stat } from 'node:fs/promises'
import { basename, dirname, join } from 'node:path'
import { promisify } from 'node:util'
import { notarize } from '@electron/notarize'
import { notarizeMacOS } from './notarize-macos.mjs'
import { packagingStep } from './packaging-step.mjs'
import {
resolveMacOSNotarizationEnvironment,
resolveMacOSSigningEnvironment,
@@ -45,15 +46,15 @@ const operations: MacOSArtifactOperations = {
async copyApp(source, destination) {
await execute('/usr/bin/ditto', [source, destination])
},
notarize,
notarize: notarizeMacOS,
verifySignature: verifyMacOSSignature,
verifyNotarization: verifyMacOSNotarizedApplication,
}
async function timed(label: string, action: () => Promise<void>): Promise<void> {
async function timed(label: string, action: () => Promise<void>, secrets: readonly string[]): Promise<void> {
const start = performance.now()
process.stdout.write(`desktop macOS packaging: ${label} started at ${new Date().toISOString()}\n`)
await action()
await packagingStep(process.env.DSH_DESKTOP_PACKAGING_RUN_DIR, label, action, secrets)
process.stdout.write(`desktop macOS packaging: ${label} completed in ${((performance.now() - start) / 1000).toFixed(2)}s\n`)
}
@@ -73,6 +74,7 @@ export async function packageMacOSArtifacts(
apple: MacOSArtifactOperations = operations,
): Promise<void> {
const { arch, version, artifactsRoot, environment } = request
const secrets = Object.entries(environment).filter(([name]) => /KEY|SECRET|TOKEN|PASSWORD|APPLE_ID/iu.test(name)).map(([, value]) => value ?? '')
const expected = resolveMacOSSigningEnvironment(environment)
const credentials = resolveMacOSNotarizationEnvironment(environment)
const update = resolveDesktopAutoUpdateConfig(environment, 'darwin', arch)
@@ -95,10 +97,10 @@ export async function packageMacOSArtifacts(
await apple.notarize({ appPath: zipApp, ...credentials })
apple.verifyNotarization(zipApp, expected)
await build({ format: 'zip', appPath: zipApp, output: zipOutput })
}),
}, secrets),
timed('DMG creation and notarization', async () => {
await build({ format: 'dmg', appPath: dmgApp, output: dmgOutput })
}),
}, secrets),
])
const failures = results.filter(result => result.status === 'rejected')
if (failures.length > 0) {
+83 -23
View File
@@ -1,6 +1,6 @@
/** Build one release target with matching Electron and dsh architecture. */
import { spawn } from 'node:child_process'
import { execFileSync, spawn } from 'node:child_process'
import { mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs'
import { parseArgs } from 'node:util'
import { join, resolve } from 'node:path'
@@ -11,8 +11,15 @@ import {
import { desktopTargetBuildPaths } from './desktop-build-paths.mjs'
import { packageMacOSArtifacts, type DesktopPrepackagedArtifact } from './package-macos.ts'
import { loadDesktopPackageEnvironment, validateDesktopPackageEnvironment } from './desktop-package-environment.mjs'
import { createPackagingRun } from './packaging-run.mjs'
import { createPackagingRun, recordPackagingEvent } from './packaging-run.mjs'
import { withWindowsSigningStage } from './windows-signing-stage.mjs'
import { prepareWindowsSignatureCacheDirectory, resolveWindowsSignatureCacheDirectory } from './windows-signature-cache-directory.mjs'
import { withMacOSSigningKeychain } from './macos-signing-keychain.mjs'
import { macOSDownloadEnvironment, resolveMacOSPackageSettings } from './macos-package-settings.mjs'
import { packagingErrorDetails, packagingStep } from './packaging-step.mjs'
import { notarizeMacOS } from './notarize-macos.mjs'
import { resolveMacOSNotarizationEnvironment } from './desktop-release-environment.mjs'
import { withMacOSNotarizationProxy } from './macos-notarization-proxy.ts'
const APP_ROOT = resolve(import.meta.dirname, '..')
const REPOSITORY_ROOT = resolve(APP_ROOT, '..', '..')
@@ -22,6 +29,7 @@ const WINDOWS_SIGNING_ENV_NAMES = [
'DSH_DESKTOP_WINDOWS_KEY_CONTAINER',
'DSH_DESKTOP_WINDOWS_SIGNTOOL',
'DSH_DESKTOP_WINDOWS_TOKEN_PIN',
'DSH_DESKTOP_WINDOWS_SIGNATURE_CACHE_DIR',
] as const
const DESKTOP_UPLOAD_CREDENTIAL_ENV_NAMES = new Set([
'DOWNLOAD_TEST_COS_SECRET_ID',
@@ -280,32 +288,51 @@ async function main(): Promise<void> {
const invocation = parseDesktopPackageInvocation(process.argv.slice(2))
const { target } = invocation
const environment = loadDesktopPackageEnvironment(target.platform)
validateDesktopPackageEnvironment(environment, target, invocation)
if (invocation.check) {
validateDesktopPackageEnvironment(environment, target, invocation)
process.stdout.write(`desktop package: ${target.name} local configuration valid; signing and notarization were not attempted\n`)
return
}
const run = target.platform === 'win32'
? createPackagingRun(join(APP_ROOT, '.desktop-build', 'packaging-runs'), {
target: target.name, unsigned: invocation.unsigned, version: packageVersion(join(APP_ROOT, 'package.json'), 'desktop package'),
}) : undefined
if (run !== undefined) console.log(`DESKTOP_PACKAGING_RECORD ${run.directory}`)
const secrets = Object.entries(environment).filter(([name]) => /KEY|SECRET|TOKEN|PASSWORD|APPLE_ID/iu.test(name)).map(([, value]) => value ?? '')
const run = createPackagingRun(join(APP_ROOT, '.desktop-build', 'packaging-runs'), {
target: target.name, unsigned: invocation.unsigned, directory: invocation.directory, prepareOnly: invocation.prepareOnly,
version: packageVersion(join(APP_ROOT, 'package.json'), 'desktop package'), node: process.version,
commit: execFileSync('git', ['rev-parse', 'HEAD'], { cwd: REPOSITORY_ROOT, encoding: 'utf8' }).trim(),
dirty: execFileSync('git', ['status', '--porcelain', '--untracked-files=normal'], { cwd: REPOSITORY_ROOT, encoding: 'utf8' }).trim() !== '',
}, { parallel: target.platform === 'darwin', secrets })
console.log(`DESKTOP_PACKAGING_RECORD ${run.directory}`)
const previousDirectory = process.env.DSH_DESKTOP_PACKAGING_RUN_DIR
process.env.DSH_DESKTOP_PACKAGING_RUN_DIR = run.directory
let success = false
try {
await packagingStep(run.directory, 'configuration', async () => { validateDesktopPackageEnvironment(environment, target, invocation) }, secrets)
if (target.platform === 'darwin') {
await withMacOSSigningKeychain(environment, signingEnvironment => packageTarget(invocation, signingEnvironment, run))
const settings = resolveMacOSPackageSettings(environment)
recordPackagingEvent(run.directory, { type: 'macos-settings', packConcurrency: settings.packConcurrency,
downloadProxyConfigured: settings.downloadProxy !== undefined,
notarizationProxyConfigured: settings.notarizationProxy !== undefined })
await packagingStep(run.directory, 'macos-package', () => withMacOSSigningKeychain(environment,
signingEnvironment => packageTarget(invocation, signingEnvironment, run)), secrets)
} else {
await packageTarget(invocation, environment, run)
await packagingStep(run.directory, 'windows-package', () => packageTarget(invocation, environment, run), secrets)
}
success = true
} finally { run?.finish(success) }
} catch (error) {
process.stderr.write(`${packagingErrorDetails(error, secrets)}\n`)
process.stderr.write(`desktop package: failed; see ${run.directory}/events.jsonl\n`)
process.exitCode = 1
} finally {
if (previousDirectory === undefined) delete process.env.DSH_DESKTOP_PACKAGING_RUN_DIR
else process.env.DSH_DESKTOP_PACKAGING_RUN_DIR = previousDirectory
run.finish(success)
}
}
/**
* Prepare one release only after its signing preflight, without publishing from the builder.
* @param invocation Validated host, target and packaging mode.
* @param environment File-owned release configuration.
* @param run Windows stage supervisor; required for signed Windows packaging.
* @param run Persistent stage supervisor; required for signed Windows packaging and enabled for all release commands.
* @returns Resolves after preparation or complete packaging; any failed stage prevents a release record.
*/
export async function packageTarget(
@@ -315,6 +342,10 @@ export async function packageTarget(
): Promise<void> {
const { target } = invocation
const execute = (args: readonly string[], env: NodeJS.ProcessEnv, cwd: string = APP_ROOT) => runPnpm(args, env, cwd, run)
const journal = target.platform === 'darwin' ? process.env.DSH_DESKTOP_PACKAGING_RUN_DIR : undefined
const proxyEvent = (status: string) => { if (journal) recordPackagingEvent(journal, { type: 'notarization-proxy', status }) }
const mac = target.platform === 'darwin' ? resolveMacOSPackageSettings(environment) : undefined
const packArguments = mac === undefined ? [] : ['--concurrency', String(mac.packConcurrency)]
const buildPaths = desktopTargetBuildPaths(target.name)
const releaseRecordPath = join(buildPaths.artifacts, desktopBuildRecordFilename(target.name))
if (!invocation.prepareOnly && !invocation.unsigned) {
@@ -327,19 +358,42 @@ export async function packageTarget(
DSH_DESKTOP_TARGET_PLATFORM: target.platform,
DSH_DESKTOP_TARGET_ARCH: target.arch,
}
const electronBuilderEnv = desktopElectronBuilderEnvironment(targetEnv, invocation.unsigned)
const downloadEnv = macOSDownloadEnvironment(targetEnv, mac?.downloadProxy)
const electronBuilderEnv = desktopElectronBuilderEnvironment(downloadEnv, invocation.unsigned)
for (const name of WINDOWS_SIGNING_ENV_NAMES) {
if (!invocation.unsigned && environment[name] !== undefined) electronBuilderEnv[name] = environment[name]
}
const signPrimaryRuntime = target.platform === 'win32' && !invocation.unsigned && !invocation.prepareOnly
const signedStage = async (stage: string, operation: () => Promise<void>): Promise<void> => {
if (!signPrimaryRuntime) return operation()
if (run === undefined) throw new Error('desktop package: signed Windows packaging requires a supervised run')
const controller = new AbortController()
const interrupted = (): void => controller.abort()
const detach = (): void => {
process.removeListener('SIGINT', interrupted)
process.removeListener('SIGTERM', interrupted)
}
process.once('SIGINT', interrupted)
process.once('SIGTERM', interrupted)
try {
const options = { stage, signal: controller.signal, record: (event: object): void => recordPackagingEvent(run.directory, event) }
await withWindowsSigningStage(options, async () => {
detach()
await operation()
})
} finally { detach() }
}
if (signPrimaryRuntime) {
if (run === undefined) throw new Error('desktop package: signed Windows packaging requires a supervised run')
await run.run('preflight:windows-signing', process.execPath,
['--import', 'tsx/esm', join(APP_ROOT, 'scripts/windows-signing-preflight.ts')],
{ cwd: APP_ROOT, env: electronBuilderEnv, timeoutMs: 60_000 })
await signedStage('preflight', async () => {
await prepareWindowsSignatureCacheDirectory(resolveWindowsSignatureCacheDirectory(environment))
await run.run('preflight:windows-signing', process.execPath,
['--import', 'tsx/esm', join(APP_ROOT, 'scripts/windows-signing-preflight.ts')],
{ cwd: APP_ROOT, env: electronBuilderEnv, timeoutMs: 60_000 })
})
}
await execute(['run', 'build:official'], buildEnv, REPOSITORY_ROOT)
await execute(['run', 'release:pack', '--family', 'dsh', '--out', buildPaths.packedDsh], buildEnv, REPOSITORY_ROOT)
await execute(['run', 'release:pack', '--family', 'dsh', '--out', buildPaths.packedDsh, ...packArguments], buildEnv, REPOSITORY_ROOT)
await execute([
'--dir',
'apps/desktop-host',
@@ -347,7 +401,7 @@ export async function packageTarget(
'--pack-destination',
buildPaths.packedDsh,
], buildEnv, REPOSITORY_ROOT)
await execute(['run', 'release:pack', '--family', 'vendor', '--out', buildPaths.packedVendor], buildEnv, REPOSITORY_ROOT)
await execute(['run', 'release:pack', '--family', 'vendor', '--out', buildPaths.packedVendor, ...packArguments], buildEnv, REPOSITORY_ROOT)
rmSync(buildPaths.packedLandlock, { recursive: true, force: true })
mkdirSync(buildPaths.packedLandlock, { recursive: true })
await execute(['--dir', 'native/system', 'run', 'build:ts'], buildEnv, REPOSITORY_ROOT)
@@ -358,10 +412,10 @@ export async function packageTarget(
'--pack-destination',
buildPaths.packedLandlock,
], buildEnv, REPOSITORY_ROOT)
await execute(['run', 'prepare:runtime', ...(signPrimaryRuntime ? ['--defer-primary-runtime-smoke'] : [])], targetEnv)
await execute(['run', 'prepare:runtime', ...(signPrimaryRuntime ? ['--defer-primary-runtime-smoke'] : [])], downloadEnv)
if (signPrimaryRuntime) await execute(['run', 'sign:primary-runtime'], electronBuilderEnv)
await execute(['run', 'prepare:packages'], targetEnv)
await execute(['run', 'prepare:dsh', ...(signPrimaryRuntime ? ['--defer-runtime-smoke'] : [])], targetEnv)
await execute(['run', 'prepare:dsh', ...(signPrimaryRuntime ? ['--defer-runtime-smoke'] : [])], downloadEnv)
if (signPrimaryRuntime) await execute(['run', 'sign:primary-runtime', '--dsh'], electronBuilderEnv)
if (invocation.prepareOnly) return
if (target.platform === 'darwin' && !invocation.directory) {
@@ -369,17 +423,23 @@ export async function packageTarget(
...desktopElectronBuilderArguments(target, true),
'--config.mac.notarize=false',
], electronBuilderEnv)
await packageMacOSArtifacts({
await withMacOSNotarizationProxy(mac?.notarizationProxy, () => packageMacOSArtifacts({
arch: target.arch,
version: packageVersion(join(APP_ROOT, 'package.json'), 'desktop package'),
artifactsRoot: buildPaths.artifacts,
environment: electronBuilderEnv,
}, artifact => execute(desktopElectronBuilderArguments(target, false, artifact), electronBuilderEnv))
}, artifact => execute(desktopElectronBuilderArguments(target, false, artifact), electronBuilderEnv)), undefined, undefined, proxyEvent)
} else if (target.platform === 'darwin') {
await execute([...desktopElectronBuilderArguments(target, true), '--config.mac.notarize=false'], electronBuilderEnv)
const appPath = join(buildPaths.artifacts, target.arch === 'arm64' ? 'mac-arm64' : 'mac', 'DeepSeek Harness.app')
await withMacOSNotarizationProxy(mac?.notarizationProxy,
() => notarizeMacOS({ appPath, ...resolveMacOSNotarizationEnvironment(environment) }), undefined, undefined, proxyEvent)
} else {
await execute(desktopElectronBuilderArguments(target, invocation.directory), electronBuilderEnv)
await signedStage('artifacts', () => execute(desktopElectronBuilderArguments(target, invocation.directory), electronBuilderEnv))
}
if (signPrimaryRuntime) await execute(['exec', 'tsx', 'scripts/smoke-packaged-runtime.ts'], targetEnv)
if (!invocation.directory && !invocation.unsigned) writeReleaseRecord(target, electronBuilderEnv, buildPaths.artifacts)
if (journal) recordPackagingEvent(journal, { type: 'artifacts', directory: buildPaths.artifacts })
}
if (process.argv[1] !== undefined && import.meta.filename === resolve(process.argv[1])) await main()
+2 -1
View File
@@ -26,9 +26,10 @@ export function packagingOutputRedactor(secrets: readonly string[], emit: (text:
* Allocate retained evidence and supervise sequential child-process stages.
* @param root Parent directory for retained records.
* @param metadata Public target/version metadata only.
* @param settings Opt-in parallel stages and additional credentials to redact.
* @returns A run that blocks later stages after failure and awaits owned process termination.
*/
export function createPackagingRun(root: string, metadata: object): {
export function createPackagingRun(root: string, metadata: object, settings?: { parallel?: boolean; secrets?: readonly string[] }): {
directory: string
run(stage: string, executable: string, args: readonly string[], options: {
cwd: string
+21 -12
View File
@@ -1,6 +1,7 @@
/** Persist redacted packaging evidence and terminate the owned stage tree on fatal signing failures. */
import { randomUUID } from 'node:crypto'
import { spawn } from 'node:child_process'
import { appendFileSync, existsSync, mkdirSync, mkdtempSync, realpathSync, writeFileSync } from 'node:fs'
import { appendFileSync, existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, writeFileSync } from 'node:fs'
import { join, resolve } from 'node:path'
import { StringDecoder } from 'node:string_decoder'
@@ -59,22 +60,26 @@ export function packagingOutputRedactor(secrets, emit) {
* Allocate a run whose failures never become release completion records.
* @param {string} root Parent for retained packaging records.
* @param {object} metadata Public target/version metadata only.
* @param {{parallel?: boolean, secrets?: readonly string[]}} settings Parallel stages are opt-in; secrets include credentials removed from child environments.
* @returns {{directory: string, run: (stage: string, executable: string, args: readonly string[], options: {cwd: string, env: NodeJS.ProcessEnv, timeoutMs?: number}) => Promise<void>, finish: (success: boolean) => void}} Owned run supervisor; an optional stage deadline records timeout independently of exit status and awaits termination.
*/
export function createPackagingRun(root, metadata) {
export function createPackagingRun(root, metadata, settings = {}) {
const started = performance.now()
mkdirSync(root, { recursive: true })
const directory = realpathSync(mkdtempSync(join(resolve(root), `${new Date().toISOString().replaceAll(':', '-')}-`)))
for (const name of ['events.jsonl', 'stdout.log', 'stderr.log']) {
writeFileSync(join(directory, name), '', { flag: 'wx', mode: 0o600 })
}
writeFileSync(join(directory, 'run.json'), `${JSON.stringify({ startedAt: new Date().toISOString(), pid: process.pid, ...metadata })}\n`, { flag: 'wx', flush: true })
writeFileSync(join(directory, 'run.json'), `${JSON.stringify({ startedAt: new Date().toISOString(), pid: process.pid, ...metadata })}\n`, { flag: 'wx', mode: 0o600, flush: true })
let failed = false
let active = false
let active = 0
const fatal = join(directory, 'fatal.json')
async function run(stage, executable, args, options) {
if (failed || existsSync(fatal)) throw new Error(`desktop package: run is blocked; see ${directory}`)
if (active) throw new Error('desktop package: supervised stages must run sequentially')
active = true
if (active && !settings.parallel) throw new Error('desktop package: supervised stages must run sequentially')
active++
const stageId = randomUUID()
const started = performance.now()
let child
let fatalObserved = false
let launchError = false
@@ -112,22 +117,23 @@ export function createPackagingRun(root, metadata) {
process.once('SIGINT', interrupted)
process.once('SIGTERM', interrupted)
try {
recordPackagingEvent(directory, { type: 'stage-start', stage })
recordPackagingEvent(directory, { type: 'stage-start', stage, stageId })
child = spawn(executable, [...args], { cwd: options.cwd, env: { ...options.env, DSH_DESKTOP_PACKAGING_RUN_DIR: directory },
windowsHide: true, detached: process.platform !== 'win32', stdio: ['ignore', 'pipe', 'pipe'] })
closed = new Promise(resolveClose => {
child.once('error', () => { launchError = true })
child.once('close', (code, signal) => { stageClosed = true; resolveClose({ code, signal }) })
})
recordPackagingEvent(directory, { type: 'stage-spawn', stage, childPid: child.pid })
recordPackagingEvent(directory, { type: 'stage-spawn', stage, stageId, childPid: child.pid })
if (options.timeoutMs !== undefined) deadline = setTimeout(() => { timedOut = true; stop() }, options.timeoutMs)
const secrets = Object.entries(options.env).filter(([name]) => /KEY|SECRET|TOKEN|PASSWORD/iu.test(name)).map(([, value]) => value ?? '')
const secrets = [...(settings.secrets ?? []), ...Object.entries(options.env).filter(([name]) => /KEY|SECRET|TOKEN|PASSWORD|APPLE_ID/iu.test(name)).map(([, value]) => value ?? '')]
const streams = [['stdout', child.stdout, process.stdout], ['stderr', child.stderr, process.stderr]]
for (const [name, stream, consoleStream] of streams) {
let notification = ''
const redactor = packagingOutputRedactor(secrets, text => {
try {
appendFileSync(join(directory, `${name}.log`), text, { flush: true })
if (settings.parallel) recordPackagingEvent(directory, { type: 'output', stage, stageId, stream: name, text })
consoleStream.write(text)
} catch { outputError = true; stop() }
notification += text
@@ -142,7 +148,7 @@ export function createPackagingRun(root, metadata) {
const result = await closed
await termination
fatalObserved ||= existsSync(fatal)
recordPackagingEvent(directory, { type: 'stage-end', stage, ...result, timedOut, fatalObserved, launchError, outputError, terminationCode, terminationError })
recordPackagingEvent(directory, { type: 'stage-end', stage, stageId, elapsedMs: performance.now() - started, ...result, timedOut, fatalObserved, launchError, outputError, terminationCode, terminationError })
if (result.code !== 0 || result.signal !== null || fatalObserved || launchError || outputError || terminationError) {
failed = true
throw new Error(`desktop package: ${stage} failed; evidence: ${directory}`)
@@ -157,7 +163,7 @@ export function createPackagingRun(root, metadata) {
clearTimeout(deadline)
process.removeListener('SIGINT', interrupted)
process.removeListener('SIGTERM', interrupted)
active = false
active--
}
}
return {
@@ -165,7 +171,10 @@ export function createPackagingRun(root, metadata) {
run,
finish(success) {
if (active) throw new Error('desktop package: cannot finish an active run')
writeFileSync(join(directory, 'result.json'), `${JSON.stringify({ completedAt: new Date().toISOString(), success: success && !failed && !existsSync(fatal) })}\n`, { flag: 'wx', flush: true })
const events = readFileSync(join(directory, 'events.jsonl'), 'utf8').trim().split('\n').filter(Boolean).map(line => JSON.parse(line))
const stages = events.filter(event => event.type === 'stage-end')
const proxy = events.filter(event => event.type === 'notarization-proxy').at(-1)?.status ?? 'not-used'
writeFileSync(join(directory, 'result.json'), `${JSON.stringify({ completedAt: new Date().toISOString(), elapsedMs: performance.now() - started, success: success && !failed && !existsSync(fatal), proxy, artifacts: events.filter(event => event.type === 'artifacts').at(-1)?.directory, stages })}\n`, { flag: 'wx', mode: 0o600, flush: true })
},
}
}
+18
View File
@@ -0,0 +1,18 @@
/** Persist in-process and Apple-tool phases in the packaging journal. */
/**
* Record a phase outcome and redacted nested failure details.
* @param directory Existing run directory; undefined retains unrecorded callers.
* @param stage Public phase label, never credentials.
* @param action Work that settles all owned activity before returning.
* @param secrets Credential values removed from errors.
* @returns Action result; logging failures also reject the phase.
*/
export function packagingStep<T>(directory: string | undefined, stage: string, action: () => Promise<T>, secrets?: readonly string[]): Promise<T>
/**
* Format nested errors with credential values removed for journal and terminal output.
* @param error Failure including optional causes or aggregate errors.
* @param secrets Credential values removed from output.
* @returns Redacted diagnostic including nested recovery instructions.
*/
export function packagingErrorDetails(error: unknown, secrets: readonly string[]): string
+49
View File
@@ -0,0 +1,49 @@
/** Record in-process and Apple-tool phases in the same journal as packaging subprocesses. */
import { randomUUID } from 'node:crypto'
import { recordPackagingEvent, packagingOutputRedactor } from './packaging-run.mjs'
/**
* Persist a phase outcome, including nested failure details, without logging arguments or environments.
* @param {string | undefined} directory Existing run directory; undefined retains unrecorded callers.
* @param {string} stage Public phase label, never credentials.
* @param {() => Promise<unknown>} action Work that settles all owned activity before returning.
* @param {readonly string[]} secrets Credential values removed from errors.
* @returns {Promise<unknown>} Action result; logging failures also reject the phase.
*/
export async function packagingStep(directory, stage, action, secrets = Object.entries(process.env).filter(([name]) => /KEY|SECRET|TOKEN|PASSWORD|APPLE_ID/iu.test(name)).map(([, value]) => value ?? '')) {
if (directory === undefined) return action()
const stageId = randomUUID()
const started = performance.now()
recordPackagingEvent(directory, { type: 'stage-start', stage, stageId })
try {
const result = await action()
recordPackagingEvent(directory, { type: 'stage-end', stage, stageId, elapsedMs: performance.now() - started, success: true })
return result
} catch (error) {
const message = packagingErrorDetails(error, secrets)
recordPackagingEvent(directory, { type: 'stage-end', stage, stageId, elapsedMs: performance.now() - started, success: false, error: message })
throw error
}
}
/**
* Format nested errors with credential values removed for journal and terminal output.
* @param {unknown} error Failure including optional causes or aggregate errors.
* @param {readonly string[]} secrets Credential values removed from output.
* @returns {string} Redacted diagnostic including nested recovery instructions.
*/
export function packagingErrorDetails(error, secrets) {
const seen = new Set()
function details(value) {
if (!(value instanceof Error)) return String(value)
if (seen.has(value)) return '[circular error]'
seen.add(value)
return [value.stack ?? value.message, ...(value instanceof AggregateError ? value.errors.map(details) : []),
...(value.cause === undefined ? [] : [details(value.cause)])].join('\n')
}
let message = ''
const redactor = packagingOutputRedactor(secrets, text => { message += text })
redactor.write(Buffer.from(details(error)))
redactor.end()
return message
}
+34 -21
View File
@@ -1,5 +1,6 @@
/** Materialize the complete production runtime before publishing Desktop resources. */
import { packagingStep } from './packaging-step.mjs'
import { spawn } from 'node:child_process'
import { copyFileSync, cpSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
@@ -107,20 +108,24 @@ function runPnpm(args: readonly string[]): Promise<void> {
}
async function main(): Promise<void> {
rmSync(DSH_OUTPUT_ROOT, { recursive: true, force: true })
rmSync(PNPM_BUILD_STATE, { recursive: true, force: true })
mkdirSync(STORE_ROOT, { recursive: true })
try {
await packagingStep(process.env.DSH_DESKTOP_PACKAGING_RUN_DIR, 'runtime:reset', async () => {
rmSync(DSH_OUTPUT_ROOT, { recursive: true, force: true })
rmSync(PNPM_BUILD_STATE, { recursive: true, force: true })
mkdirSync(STORE_ROOT, { recursive: true })
})
const release = desktopRelease()
copyFileSync(join(PACKAGE_SET_ROOT, DESKTOP_PACKAGE_SET_FILE), join(BUILD_ROOT, DESKTOP_PACKAGE_SET_FILE))
cpSync(join(PACKAGE_SET_ROOT, DESKTOP_PACKAGES_DIR), join(BUILD_ROOT, DESKTOP_PACKAGES_DIR), { recursive: true })
createRuntimeProjectMetadata(BUILD_ROOT, release)
await runPnpm(['install', '--lockfile-only'])
await packagingStep(process.env.DSH_DESKTOP_PACKAGING_RUN_DIR, 'runtime:stage-packages', async () => {
copyFileSync(join(PACKAGE_SET_ROOT, DESKTOP_PACKAGE_SET_FILE), join(BUILD_ROOT, DESKTOP_PACKAGE_SET_FILE))
cpSync(join(PACKAGE_SET_ROOT, DESKTOP_PACKAGES_DIR), join(BUILD_ROOT, DESKTOP_PACKAGES_DIR), { recursive: true })
createRuntimeProjectMetadata(BUILD_ROOT, release)
})
await packagingStep(process.env.DSH_DESKTOP_PACKAGING_RUN_DIR, 'runtime:lockfile', () => runPnpm(['install', '--lockfile-only']))
verifyDesktopCoreLockfile(
readFileSync(join(BUILD_ROOT, 'pnpm-lock.yaml'), 'utf8'),
readDesktopCorePackageSet(BUILD_ROOT, release.version),
)
await runPnpm(['install', '--prod', '--frozen-lockfile', '--trust-lockfile'])
await packagingStep(process.env.DSH_DESKTOP_PACKAGING_RUN_DIR, 'runtime:install', () => runPnpm(['install', '--prod', '--frozen-lockfile', '--trust-lockfile']))
const packageSet = readDesktopCorePackageSet(BUILD_ROOT, release.version)
const targetName = resolveDesktopBuildTarget()
const target = { platform: process.platform, arch: targetName.endsWith('arm64') ? 'arm64' : 'x64' }
@@ -128,9 +133,11 @@ async function main(): Promise<void> {
const officeManifest = JSON.parse(readFileSync(join(modules, '@deepseek-ai/libreoffice-kit/package.json'), 'utf8'))
const officeEngine = selectOfficeEngine(officeManifest, target)
mkdirSync(DSH_OUTPUT_ROOT, { recursive: true })
cpSync(modules, join(DSH_OUTPUT_ROOT, 'node_modules'), {
recursive: true, dereference: true,
filter: source => desktopRuntimeFileExclusion(relative(modules, source), target, officeEngine) === undefined,
await packagingStep(process.env.DSH_DESKTOP_PACKAGING_RUN_DIR, 'runtime:materialize-modules', async () => {
cpSync(modules, join(DSH_OUTPUT_ROOT, 'node_modules'), {
recursive: true, dereference: true,
filter: source => desktopRuntimeFileExclusion(relative(modules, source), target, officeEngine) === undefined,
})
})
writeFileSync(join(DSH_OUTPUT_ROOT, 'package.json'), `${JSON.stringify({
name: '@deepseek-ai/dsh-desktop-runtime', private: true, version: release.version, type: 'module',
@@ -145,23 +152,29 @@ async function main(): Promise<void> {
throw new Error(`desktop runtime: missing required LibreOffice engine ${officeEngine}`)
}
if (process.platform === 'darwin') {
await signMacOSRuntime(DSH_OUTPUT_ROOT, resolveDesktopAppId(process.env), resolveMacOSSigningEnvironment(process.env))
await signMacOSRuntime(join(RUNTIME_ROOT, 'primary-runtime'), resolveDesktopAppId(process.env), resolveMacOSSigningEnvironment(process.env))
await packagingStep(process.env.DSH_DESKTOP_PACKAGING_RUN_DIR, 'sign:dsh-native', () => signMacOSRuntime(DSH_OUTPUT_ROOT, resolveDesktopAppId(process.env), resolveMacOSSigningEnvironment(process.env), join(BUILD_PATHS.root, 'signature-cache')))
await packagingStep(process.env.DSH_DESKTOP_PACKAGING_RUN_DIR, 'sign:primary-native', () => signMacOSRuntime(join(RUNTIME_ROOT, 'primary-runtime'), resolveDesktopAppId(process.env), resolveMacOSSigningEnvironment(process.env), join(BUILD_PATHS.root, 'signature-cache')))
}
await prepareRuntimeManifests(DSH_OUTPUT_ROOT)
smokePrimaryRuntime(join(RUNTIME_ROOT, 'primary-runtime'))
writeDesktopRuntime(DSH_OUTPUT_ROOT, release, packageSet.packages.map(entry => entry.name), target)
const descriptor = await verifyDesktopRuntime(DSH_OUTPUT_ROOT, release.version, target)
await packagingStep(process.env.DSH_DESKTOP_PACKAGING_RUN_DIR, 'runtime:manifests', () => prepareRuntimeManifests(DSH_OUTPUT_ROOT))
await packagingStep(process.env.DSH_DESKTOP_PACKAGING_RUN_DIR, 'runtime:primary-smoke', async () => smokePrimaryRuntime(join(RUNTIME_ROOT, 'primary-runtime')))
await packagingStep(process.env.DSH_DESKTOP_PACKAGING_RUN_DIR, 'runtime:write-descriptor', async () => writeDesktopRuntime(DSH_OUTPUT_ROOT, release, packageSet.packages.map(entry => entry.name), target))
const descriptor = await packagingStep(process.env.DSH_DESKTOP_PACKAGING_RUN_DIR, 'runtime:verify-before-smoke', () => verifyDesktopRuntime(DSH_OUTPUT_ROOT, release.version, target))
if (!process.argv.includes('--defer-runtime-smoke')) {
await smokePreparedRuntime(DSH_OUTPUT_ROOT, NODE, RUNTIME_ROOT, descriptor)
await verifyDesktopRuntime(DSH_OUTPUT_ROOT, release.version, target)
await packagingStep(process.env.DSH_DESKTOP_PACKAGING_RUN_DIR, 'runtime:smoke', () => smokePreparedRuntime(DSH_OUTPUT_ROOT, NODE, RUNTIME_ROOT, descriptor))
await packagingStep(process.env.DSH_DESKTOP_PACKAGING_RUN_DIR, 'runtime:verify-after-smoke', () => verifyDesktopRuntime(DSH_OUTPUT_ROOT, release.version, target))
}
} catch (error) {
rmSync(DSH_OUTPUT_ROOT, { recursive: true, force: true })
throw error
} finally {
rmSync(BUILD_ROOT, { recursive: true, force: true })
rmSync(PNPM_BUILD_STATE, { recursive: true, force: true })
let cleaned = false
const cleanup = (): void => {
try { rmSync(BUILD_ROOT, { recursive: true, force: true }) }
finally { rmSync(PNPM_BUILD_STATE, { recursive: true, force: true }) }
cleaned = true
}
try { await packagingStep(process.env.DSH_DESKTOP_PACKAGING_RUN_DIR, 'runtime:cleanup', async () => cleanup()) }
finally { if (!cleaned) cleanup() }
}
}
+6 -3
View File
@@ -1,5 +1,6 @@
/** Prepare the target Electron distribution and pinned pnpm CLI. */
import { packagingStep } from './packaging-step.mjs'
import { execFileSync } from 'node:child_process'
import { chmodSync, cpSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
import { createRequire } from 'node:module'
@@ -32,9 +33,10 @@ async function main(): Promise<void> {
const arch = target.endsWith('arm64') ? 'arm64' : 'x64'
const require = createRequire(import.meta.url)
const { version } = require('electron/package.json') as { version: string }
const archive = await downloadArtifact({ version, platform, arch, artifactName: 'electron', cacheRoot: BUILD_PATHS.downloads })
const archive = await packagingStep(process.env.DSH_DESKTOP_PACKAGING_RUN_DIR, 'download:electron',
() => downloadArtifact({ version, platform, arch, artifactName: 'electron', cacheRoot: BUILD_PATHS.downloads }))
rmSync(BUILD_PATHS.electron, { recursive: true, force: true })
await extractZip(archive, { dir: BUILD_PATHS.electron })
await packagingStep(process.env.DSH_DESKTOP_PACKAGING_RUN_DIR, 'extract:electron', () => extractZip(archive, { dir: BUILD_PATHS.electron }))
const executable = join(BUILD_PATHS.electron, platform === 'win32' ? 'electron.exe' : 'Electron.app/Contents/MacOS/Electron')
const nodeVersion = execFileSync(executable, ['-p', 'process.versions.node'], {
encoding: 'utf8', env: { ...process.env, ELECTRON_RUN_AS_NODE: '1' },
@@ -49,7 +51,8 @@ async function main(): Promise<void> {
node: nodeVersion,
pnpm: pnpmVersion,
}, undefined, 2)}\n`)
await preparePrimaryRuntime({ deferSmoke: values['defer-primary-runtime-smoke'] })
await packagingStep(process.env.DSH_DESKTOP_PACKAGING_RUN_DIR, 'prepare:primary-runtime',
() => preparePrimaryRuntime({ deferSmoke: values['defer-primary-runtime-smoke'] }))
}
await main()
+33 -23
View File
@@ -5,6 +5,8 @@ import { join, resolve } from 'node:path'
import { createWindowsTokenSigner } from './windows-sign.mjs'
import { inspectWindowsRuntimeSignature, signWindowsCode, type WindowsCodeSigningOptions } from './windows-runtime-signature.mjs'
import { createCachedSigner, signatureCacheIdentity } from './windows-signature-cache.mjs'
import { prepareWindowsSignatureCacheDirectory, resolveWindowsSignatureCacheDirectory } from './windows-signature-cache-directory.mjs'
import { withWindowsSigningStage } from './windows-signing-stage.mjs'
import { failPackagingRun, recordPackagingEvent } from './packaging-run.mjs'
import { resolveDesktopBuildTarget, resolveDesktopTargetBuildPaths } from './desktop-build-paths.mjs'
import { smokePrimaryRuntime } from './prepare-primary-runtime.ts'
@@ -50,30 +52,38 @@ async function main(): Promise<void> {
const certificateFile = process.env.DSH_DESKTOP_WINDOWS_CER_FILE
if (!certificateFile) throw new Error('primary runtime signing requires the configured certificate')
const thumbprint = new X509Certificate(await readFile(certificateFile)).fingerprint.replaceAll(':', '')
const record = (event: object): void => { recordPackagingEvent(runDirectory, event) }
try {
const paths = resolveDesktopTargetBuildPaths()
const record = (event: object): void => { recordPackagingEvent(runDirectory, event) }
const sign = createWindowsTokenSigner({ certificateFile, signTool: process.env.DSH_DESKTOP_WINDOWS_SIGNTOOL,
keyContainer: process.env.DSH_DESKTOP_WINDOWS_KEY_CONTAINER, tokenPin: process.env.DSH_DESKTOP_WINDOWS_TOKEN_PIN })
const identity = await signatureCacheIdentity([
await realpath(certificateFile), await realpath(process.env.DSH_DESKTOP_WINDOWS_SIGNTOOL!),
join(import.meta.dirname, 'windows-sign.cmd'), join(import.meta.dirname, 'windows-sign.mjs'),
join(import.meta.dirname, 'windows-timestamp.mjs'),
])
const options = {
thumbprint,
sign: createCachedSigner({ root: join(paths.root, 'signature-cache'), identity, thumbprint,
sign, inspect: inspectWindowsRuntimeSignature, record }),
record,
}
if (process.argv.includes('--dsh')) {
const version = JSON.parse(await readFile(join(paths.dsh, 'package.json'), 'utf8')).version as string
await signWindowsDesktopRuntime(paths.dsh, version, { ...options,
smoke: descriptor => smokePreparedRuntime(paths.dsh, join(paths.electron, 'electron.exe'), paths.runtime, descriptor),
})
} else {
await signWindowsPrimaryRuntime(join(paths.runtime, 'primary-runtime'), { ...options, smoke: smokePrimaryRuntime })
}
await withWindowsSigningStage({ stage: process.argv.includes('--dsh') ? 'dsh-runtime' : 'primary-runtime', record }, async () => {
const paths = resolveDesktopTargetBuildPaths()
const sign = createWindowsTokenSigner({ certificateFile, signTool: process.env.DSH_DESKTOP_WINDOWS_SIGNTOOL,
keyContainer: process.env.DSH_DESKTOP_WINDOWS_KEY_CONTAINER, tokenPin: process.env.DSH_DESKTOP_WINDOWS_TOKEN_PIN })
const identity = await signatureCacheIdentity([
await realpath(certificateFile), await realpath(process.env.DSH_DESKTOP_WINDOWS_SIGNTOOL!),
join(import.meta.dirname, 'windows-sign.cmd'), join(import.meta.dirname, 'windows-sign.mjs'),
join(import.meta.dirname, 'windows-timestamp.mjs'),
])
const cacheRoot = resolveWindowsSignatureCacheDirectory(process.env)
await prepareWindowsSignatureCacheDirectory(cacheRoot)
const cachedSign = createCachedSigner({ root: cacheRoot, identity, thumbprint,
sign, inspect: inspectWindowsRuntimeSignature, record })
const options = { thumbprint, sign: cachedSign, record }
record({ type: 'signature-cache-open', root: cachedSign.summary().root, identity })
try {
if (process.argv.includes('--dsh')) {
const version = JSON.parse(await readFile(join(paths.dsh, 'package.json'), 'utf8')).version as string
await signWindowsDesktopRuntime(paths.dsh, version, { ...options,
smoke: descriptor => smokePreparedRuntime(paths.dsh, join(paths.electron, 'electron.exe'), paths.runtime, descriptor),
})
} else {
await signWindowsPrimaryRuntime(join(paths.runtime, 'primary-runtime'), { ...options, smoke: smokePrimaryRuntime })
}
} finally {
const summary = cachedSign.summary()
record({ type: 'signature-cache-summary', ...summary })
process.stdout.write(`SIGNATURE_CACHE_SUMMARY ${JSON.stringify(summary)}\n`)
}
})
} catch (error) {
failPackagingRun(runDirectory, 'primary-runtime-signing-or-smoke-failed')
throw error
@@ -44,7 +44,9 @@ try {
DSH_DESKTOP_TARGET_PLATFORM: 'win32', DSH_DESKTOP_TARGET_ARCH: 'x64',
DSH_DESKTOP_UNSIGNED: '1', CSC_IDENTITY_AUTO_DISCOVERY: 'false', ELECTRON_BUILDER_7Z_FILTER: 'BCJ',
DSH_DESKTOP_MANDATORY_UPDATE_TEST_ORIGIN: signingEnvironment.DSH_DESKTOP_MANDATORY_UPDATE_TEST_ORIGIN
?? 'https://harness-test.deepseek.com',
?? 'https://test.example.com',
DSH_DESKTOP_MANDATORY_UPDATE_CONFIG: signingEnvironment.DSH_DESKTOP_MANDATORY_UPDATE_CONFIG
?? JSON.stringify({ allowedAuthOrigins: ['https://login.example.com'] }),
...signingRun ? { DSH_DESKTOP_PACKAGING_RUN_DIR: signingRun.directory } : {},
})
const { createElectronBuilderConfig } = await import('../electron-builder.config.mjs')
@@ -0,0 +1,14 @@
/**
* Resolve the current account's cache or a file-owned absolute local override.
* @param environment Packaging configuration; an absent override uses the current account's signing-state directory.
* @returns Normalized drive path; rejects relative, network, device and alternate-stream paths.
*/
export function resolveWindowsSignatureCacheDirectory(environment: NodeJS.ProcessEnv): string
/**
* Validate directory ownership, links, drive type and destination access permissions.
* @param path Absolute directory to create or inspect.
* @param existingSource Validate an existing migration source without changing its permissions.
* @returns Resolves after validation; never reads cache entries from another account's directory.
*/
export function prepareWindowsSignatureCacheDirectory(path: string, existingSource?: boolean): Promise<void>
@@ -0,0 +1,38 @@
/** Resolve and validate the current account's shared runtime-signature cache. */
import { execFile } from 'node:child_process'
import { homedir } from 'node:os'
import { realpath } from 'node:fs/promises'
import { join, resolve, win32 } from 'node:path'
import { promisify } from 'node:util'
import { scrubWindowsSigningEnvironment } from './windows-sign.mjs'
/**
* Resolve the file-owned override or the current account's signing-state cache without reading its contents.
* @param {NodeJS.ProcessEnv} environment File-owned packaging configuration.
* @returns {string} Absolute local cache path; relative, network, device and alternate-stream paths are rejected.
*/
export function resolveWindowsSignatureCacheDirectory(environment) {
const path = environment.DSH_DESKTOP_WINDOWS_SIGNATURE_CACHE_DIR
?? win32.join(homedir(), '.dsh-desktop-signing', 'signature-cache', 'v1')
if (!/^[a-z]:[\\/]/iu.test(path) || path.slice(2).includes(':') || /[\0\r\n]/u.test(path)) {
throw new Error('DSH_DESKTOP_WINDOWS_SIGNATURE_CACHE_DIR must be an absolute local drive directory')
}
return win32.resolve(path)
}
/**
* Create private current-account storage or validate an explicitly selected migration source.
* @param {string} path Absolute local directory.
* @param {boolean} existingSource Require an existing, current-account-owned migration source without changing its permissions.
* @returns {Promise<void>} Resolves after checking drive type, ancestor links, ownership and destination permissions.
*/
export async function prepareWindowsSignatureCacheDirectory(path, existingSource = false) {
if (process.platform !== 'win32') throw new Error('Windows signature cache directory validation requires Windows')
await promisify(execFile)('powershell.exe', ['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-File',
join(import.meta.dirname, 'windows-signature-cache-directory.ps1'), '-CachePath', resolve(path),
...(existingSource ? ['-ExistingSource'] : []),
], { env: scrubWindowsSigningEnvironment(process.env), windowsHide: true, timeout: 60_000 })
if ((await realpath(path)).toLowerCase() !== resolve(path).toLowerCase()) {
throw new Error('Signature cache directory is redirected; configure DSH_DESKTOP_WINDOWS_SIGNATURE_CACHE_DIR outside redirected storage')
}
}
@@ -0,0 +1,40 @@
# Validate account ownership before accessing cache contents; new caches receive a private DACL.
param([Parameter(Mandatory=$true)][string]$CachePath, [switch]$ExistingSource)
$ErrorActionPreference = 'Stop'
[Console]::OutputEncoding = [System.Text.UTF8Encoding]::new()
Import-Module "$PSHOME/Modules/Microsoft.PowerShell.Security/Microsoft.PowerShell.Security.psd1" -ErrorAction Stop
$currentSid = [System.Security.Principal.WindowsIdentity]::GetCurrent().User
$fullPath = [System.IO.Path]::GetFullPath($CachePath)
if ($fullPath -notmatch '^[A-Za-z]:\\' -or $CachePath -notmatch '^[A-Za-z]:[\\/]') { throw 'Signature cache requires an absolute local drive path' }
$drive = [System.IO.DriveInfo]::new([System.IO.Path]::GetPathRoot($fullPath))
if ($drive.DriveType -ne [System.IO.DriveType]::Fixed) { throw 'Signature cache requires a fixed local drive' }
for ($ancestor = [System.IO.DirectoryInfo]::new($fullPath); $null -ne $ancestor; $ancestor = $ancestor.Parent) {
if ($ancestor.Exists -and ($ancestor.Attributes -band [System.IO.FileAttributes]::ReparsePoint)) {
throw 'Signature cache cannot use reparse points in its path'
}
}
if ([System.IO.File]::Exists($fullPath)) { throw 'Signature cache path must be a directory' }
if (-not [System.IO.Directory]::Exists($fullPath)) {
if ($ExistingSource) { throw 'Signature cache migration source does not exist' }
$null = [System.IO.Directory]::CreateDirectory($fullPath)
$acl = [System.Security.AccessControl.DirectorySecurity]::new()
$acl.SetOwner($currentSid)
$acl.SetAccessRuleProtection($true, $false)
foreach ($sid in @($currentSid.Value, 'S-1-5-18', 'S-1-5-32-544')) {
$identity = [System.Security.Principal.SecurityIdentifier]::new($sid)
$rule = [System.Security.AccessControl.FileSystemAccessRule]::new($identity, 'FullControl', 'ContainerInherit,ObjectInherit', 'None', 'Allow')
$acl.AddAccessRule($rule)
}
Set-Acl -LiteralPath $fullPath -AclObject $acl
}
$acl = Get-Acl -LiteralPath $fullPath
if ($acl.GetOwner([System.Security.Principal.SecurityIdentifier]).Value -ne $currentSid.Value) {
throw 'Signature cache directory must belong to the current Windows account'
}
if (-not $ExistingSource) {
foreach ($rule in $acl.GetAccessRules($true, $true, [System.Security.Principal.SecurityIdentifier])) {
if ($rule.AccessControlType -eq 'Allow' -and $rule.IdentityReference.Value -notin @($currentSid.Value, 'S-1-5-18', 'S-1-5-32-544')) {
throw 'Signature cache permissions must exclude other ordinary Windows accounts'
}
}
}
@@ -18,9 +18,53 @@ export interface WindowsSignatureCacheOptions {
*/
export function signatureCacheIdentity(files: readonly string[]): Promise<string>
/** Counters include failed attempts; verification covers both restored and newly signed files, while restore time includes its verification and staging cleanup. */
export interface WindowsSignatureCacheSummary {
root: string
identity: string
hits: number
misses: number
published: number
retained: number
signingCalls: number
avoidedSigningCalls: number
validationFailures: number
verificationMs: number
restoreMs: number
signingMs: number
}
/** Serial cache callback with a snapshot of this instance's completed and failed operations. */
export type WindowsCachedSigner = ReturnType<typeof createWindowsTokenSigner> & {
/** @returns Current counters and elapsed times; does not wait for queued operations. */
summary(): WindowsSignatureCacheSummary
}
/**
* Reuse complete signed files only after input, integrity, identity and timestamp checks.
* @param options Cache policy, supervised signer, public-key verifier and audit sink.
* @returns Serial signer that stops its queue on any failure and never repairs invalid cache entries.
*/
export function createCachedSigner(options: WindowsSignatureCacheOptions): ReturnType<typeof createWindowsTokenSigner>
export function createCachedSigner(options: WindowsSignatureCacheOptions): WindowsCachedSigner
/** The caller validates ownership and holds the user-wide signing-stage lock throughout migration. */
export interface SignatureCacheMigrationOptions {
source: string
root: string
record: (event: object) => void
}
/**
* Copy complete entries without changing the source or replacing valid destination entries.
* @param options Validated directories and credential-free audit sink.
* @returns Counts of published, retained and skipped entries; corruption rejects without repair. Actual use rechecks trust.
*/
export function migrateSignatureCache(options: SignatureCacheMigrationOptions): Promise<{ published: number, retained: number, skipped: number }>
/**
* Inspect or explicitly clear complete entries under the caller's signing-stage lock.
* @param root Validated current-account cache directory.
* @param clear Remove complete entries after atomic retirement; incomplete staging directories remain untouched.
* @returns Count and bytes of complete entries, plus the number of skipped incomplete entries.
*/
export function maintainSignatureCache(root: string, clear?: boolean): Promise<{ entries: number, bytes: number, incomplete: number }>
+147 -26
View File
@@ -1,6 +1,6 @@
/** Cache complete signed files; corrupt entries stop the caller before hardware access. */
import { createHash } from 'node:crypto'
import { copyFile, lstat, mkdir, mkdtemp, readFile, realpath, rename, rm, writeFile } from 'node:fs/promises'
import { createHash, randomUUID } from 'node:crypto'
import { copyFile, lstat, mkdir, mkdtemp, readFile, readdir, realpath, rename, rm, rmdir, unlink, writeFile } from 'node:fs/promises'
import { basename, dirname, join, resolve, toNamespacedPath } from 'node:path'
const digest = bytes => createHash('sha256').update(bytes).digest('hex')
@@ -22,7 +22,8 @@ async function regularFile(path) {
async function directory(path) {
const stat = await lstat(path)
if (!stat.isDirectory() || stat.isSymbolicLink() || await realpath(path) !== resolve(path)) {
const normalize = value => process.platform === 'win32' ? toNamespacedPath(resolve(value)).toLowerCase() : resolve(value)
if (!stat.isDirectory() || stat.isSymbolicLink() || normalize(await realpath(path)) !== normalize(path)) {
throw new Error(`signature cache: expected unlinked directory: ${path}`)
}
}
@@ -32,21 +33,113 @@ function validSignature(signature, thumbprint) {
&& signature.thumbprint?.toUpperCase() === thumbprint.toUpperCase()
}
async function readCacheEntry(entry, key) {
await directory(entry)
const record = JSON.parse((await regularFile(join(entry, 'record.json'))).toString('utf8'))
if (record === null || typeof record !== 'object' || record.version !== 1 || record.key !== key
|| typeof record.inputDigest !== 'string' || !/^[a-f\d]{64}$/u.test(record.inputDigest)
|| typeof record.identity !== 'string' || typeof record.signedDigest !== 'string'
|| !/^[a-f\d]{64}$/u.test(record.signedDigest)
|| digest(JSON.stringify({ version: 1, inputDigest: record.inputDigest, identity: record.identity })) !== key) {
throw new Error('signature cache: invalid input record')
}
if (digest(await regularFile(join(entry, 'payload'))) !== record.signedDigest) throw new Error('signature cache: corrupt signed payload')
return record
}
/**
* Import complete integrity-checked entries while the caller holds the signing-stage lock.
* @param {import('./windows-signature-cache.mjs').SignatureCacheMigrationOptions} options Validated source, private destination and audit sink.
* @returns {Promise<{published: number, retained: number, skipped: number}>} Counts; existing valid entries win even when timestamp bytes differ. Trust is rechecked at actual use.
*/
export async function migrateSignatureCache(options) {
if (resolve(options.source).toLowerCase() === resolve(options.root).toLowerCase()) throw new Error('signature cache: migration source equals destination')
await directory(options.source)
await mkdir(options.root, { recursive: true })
await directory(options.root)
const counts = { published: 0, retained: 0, skipped: 0 }
for (const key of await readdir(options.source)) {
if (!/^[a-f\d]{64}$/u.test(key)) {
counts.skipped++
options.record({ type: 'signature-cache-migration-skipped', reason: 'not-complete-entry-name' })
continue
}
const source = join(options.source, key)
await readCacheEntry(source, key)
const target = join(options.root, key)
let exists = false
try { await lstat(target); exists = true }
catch (error) { if (error.code !== 'ENOENT') throw error }
if (exists) {
await readCacheEntry(target, key)
counts.retained++
continue
}
const staging = await mkdtemp(toNamespacedPath(join(options.root, '.publish-')))
try {
await copyFile(join(source, 'record.json'), join(staging, 'record.json'))
await copyFile(join(source, 'payload'), join(staging, 'payload'))
await readCacheEntry(staging, key)
await rename(staging, target)
counts.published++
} finally { await rm(staging, { recursive: true, force: true }) }
}
return counts
}
/**
* Count or explicitly clear complete entries while the caller holds the signing-stage lock.
* @param {string} root Validated, current-account cache directory.
* @param {boolean} clear Retire each complete entry atomically before removing its two regular files.
* @returns {Promise<{entries: number, bytes: number, incomplete: number}>} Complete-entry size and count; incomplete entries are left untouched.
*/
export async function maintainSignatureCache(root, clear = false) {
await directory(root)
let entries = 0
let bytes = 0
let incomplete = 0
for (const name of await readdir(root)) {
if (!/^[a-f\d]{64}$/u.test(name)) { incomplete++; continue }
const entry = join(root, name)
await directory(entry)
const files = await readdir(entry)
if (files.length !== 2 || !files.includes('record.json') || !files.includes('payload')) {
throw new Error('signature cache: unexpected files prevent cache maintenance')
}
for (const file of files) {
const stat = await lstat(join(entry, file))
if (!stat.isFile() || stat.isSymbolicLink()) throw new Error('signature cache: expected a regular entry file')
bytes += stat.size
}
if (clear) {
const retired = join(root, `.clear-${randomUUID()}`)
await rename(entry, retired)
for (const file of files) await unlink(join(retired, file))
await rmdir(retired)
}
entries++
}
return { entries, bytes, incomplete }
}
/**
* Wrap a supervised signer with immutable entries keyed by unsigned bytes and signing policy.
* @param {import('./windows-signature-cache.mjs').WindowsSignatureCacheOptions} options Cache policy and existing supervised operations.
* @returns {ReturnType<typeof import('./windows-sign.mjs').createWindowsTokenSigner>} Serial, fail-stop signing callback; cache hits still verify trust and timestamp.
* @returns {import('./windows-signature-cache.mjs').WindowsCachedSigner} Serial, fail-stop callback with counters; cache hits still verify trust and timestamp.
*/
export function createCachedSigner(options) {
let pending = Promise.resolve()
const statistics = { hits: 0, misses: 0, published: 0, retained: 0, signingCalls: 0, validationFailures: 0,
verificationMs: 0, restoreMs: 0, signingMs: 0 }
async function verify(path) {
const start = performance.now()
try {
if (!validSignature(await options.inspect(path), options.thumbprint)) throw new Error('signature cache: invalid signature')
} finally { statistics.verificationMs += performance.now() - start }
}
async function readEntry(entry, key, inputDigest) {
await directory(entry)
const record = JSON.parse((await regularFile(join(entry, 'record.json'))).toString('utf8'))
if (record === null || typeof record !== 'object' || record.version !== 1 || record.key !== key || record.inputDigest !== inputDigest
|| record.identity !== options.identity || typeof record.signedDigest !== 'string'
|| !/^[a-f\d]{64}$/u.test(record.signedDigest)) throw new Error('signature cache: invalid input record')
const payload = await regularFile(join(entry, 'payload'))
if (digest(payload) !== record.signedDigest) throw new Error('signature cache: corrupt signed payload')
const record = await readCacheEntry(entry, key)
if (record.inputDigest !== inputDigest || record.identity !== options.identity) throw new Error('signature cache: invalid input record')
return record
}
async function sign(configuration) {
@@ -60,38 +153,66 @@ export function createCachedSigner(options) {
try { await lstat(entry); hit = true }
catch (error) { if (error.code !== 'ENOENT') throw error }
if (hit) {
const record = await readEntry(entry, key, inputDigest)
const staging = await mkdtemp(toNamespacedPath(join(dirname(configuration.path), '.signature-restore-')))
const start = performance.now()
try {
const candidate = join(staging, basename(configuration.path))
await copyFile(join(entry, 'payload'), candidate)
if (digest(await regularFile(candidate)) !== record.signedDigest) throw new Error('signature cache: restore changed signed bytes')
if (!validSignature(await options.inspect(candidate), options.thumbprint)) throw new Error('signature cache: invalid cached signature')
if (digest(await regularFile(configuration.path)) !== inputDigest) throw new Error('signature cache: target changed before restore')
await rename(candidate, configuration.path)
} finally { await rm(staging, { recursive: true, force: true }) }
const record = await readEntry(entry, key, inputDigest)
const staging = await mkdtemp(toNamespacedPath(join(dirname(configuration.path), '.signature-restore-')))
try {
const candidate = join(staging, basename(configuration.path))
await copyFile(join(entry, 'payload'), candidate)
if (digest(await regularFile(candidate)) !== record.signedDigest) throw new Error('signature cache: restore changed signed bytes')
try { await verify(candidate) }
catch (error) { throw new Error('signature cache: invalid cached signature', { cause: error }) }
if (digest(await regularFile(configuration.path)) !== inputDigest) throw new Error('signature cache: target changed before restore')
await rename(candidate, configuration.path)
} finally { await rm(staging, { recursive: true, force: true }) }
} catch (error) {
statistics.validationFailures++
options.record({ type: 'signature-cache-validation-failed', key, path: configuration.path })
throw error
} finally { statistics.restoreMs += performance.now() - start }
statistics.hits++
options.record({ type: 'signature-cache-hit', key, path: configuration.path })
return
}
statistics.misses++
options.record({ type: 'signature-cache-miss', key, path: configuration.path })
await options.sign(configuration)
if (!validSignature(await options.inspect(configuration.path), options.thumbprint)) throw new Error('signature cache: new signature verification failed')
const start = performance.now()
statistics.signingCalls++
try { await options.sign(configuration) }
finally { statistics.signingMs += performance.now() - start }
try { await verify(configuration.path) }
catch (error) {
statistics.validationFailures++
options.record({ type: 'signature-cache-validation-failed', key, path: configuration.path })
throw new Error('signature cache: new signature verification failed', { cause: error })
}
const staging = await mkdtemp(toNamespacedPath(join(options.root, '.publish-')))
try {
await copyFile(configuration.path, join(staging, 'payload'))
const signedDigest = digest(await regularFile(join(staging, 'payload')))
if (signedDigest !== digest(await regularFile(configuration.path))) throw new Error('signature cache: signed file changed during publication')
await writeFile(join(staging, 'record.json'), JSON.stringify({ version: 1, key, inputDigest, identity: options.identity, signedDigest }), { flag: 'wx', flush: true })
try { await rename(staging, entry) }
let published = false
try { await rename(staging, entry); published = true }
catch (error) {
if (!['EEXIST', 'ENOTEMPTY', 'EPERM'].includes(error.code)) throw error
await readEntry(entry, key, inputDigest)
try { await readEntry(entry, key, inputDigest) }
catch (validationError) {
statistics.validationFailures++
options.record({ type: 'signature-cache-validation-failed', key, path: configuration.path })
throw validationError
}
}
options.record({ type: 'signature-cache-published', key, path: configuration.path })
if (published) statistics.published++
else statistics.retained++
options.record({ type: published ? 'signature-cache-published' : 'signature-cache-retained', key, path: configuration.path })
} finally { await rm(staging, { recursive: true, force: true }) }
}
return configuration => {
const signer = configuration => {
pending = pending.then(() => sign(configuration))
return pending
}
signer.summary = () => ({ root: options.root, identity: options.identity, ...statistics, avoidedSigningCalls: statistics.hits })
return signer
}
@@ -0,0 +1,16 @@
/** Stage-wide ownership is independent of the retained hardware-attempt interlock. */
export interface WindowsSigningStageOptions {
stage: string
record: (event: object) => void
signal?: AbortSignal
/** Test-only storage isolates independent processes from the real account's signing state. */
stateDirectory?: string
}
/**
* Queue one complete signing or cache-maintenance stage under the account's exclusive file handle.
* @param options Audit sink, optional wait cancellation and isolated test storage.
* @param operation Stage that awaits all owned children before settling.
* @returns The stage result, after releasing the handle; acquisition errors never run the stage.
*/
export function withWindowsSigningStage<T>(options: WindowsSigningStageOptions, operation: () => Promise<T>): Promise<T>
@@ -0,0 +1,62 @@
/** Serialize complete signing and cache-maintenance stages without clearing hardware failure evidence. */
import { lstat, mkdir, realpath } from 'node:fs/promises'
import { homedir } from 'node:os'
import { join, resolve, toNamespacedPath } from 'node:path'
import { setTimeout } from 'node:timers/promises'
let bindings
async function windows() {
if (process.platform !== 'win32') throw new Error('Windows signing stages require Windows')
if (bindings !== undefined) return bindings
const koffi = (await import('koffi')).default
const kernel = koffi.load('kernel32.dll')
bindings = {
open: kernel.func('__stdcall', 'CreateFileW', 'intptr', ['str16', 'uint', 'uint', 'void*', 'uint', 'uint', 'intptr']),
close: kernel.func('__stdcall', 'CloseHandle', 'int', ['intptr']),
error: kernel.func('__stdcall', 'GetLastError', 'uint', []),
}
return bindings
}
/**
* Hold one account-wide exclusive file handle until a stage and its children have settled.
* @template T
* @param {import('./windows-signing-stage.mjs').WindowsSigningStageOptions} options Audit sink, cancellation and isolated test storage.
* @param {() => Promise<T>} operation Entire stage, including verification and cache publication.
* @returns {Promise<T>} Stage result; contention waits, all other acquisition errors stop before the operation.
*/
export async function withWindowsSigningStage(options, operation) {
const api = await windows()
const root = options.stateDirectory ?? join(homedir(), '.dsh-desktop-signing')
await mkdir(root, { recursive: true })
const stat = await lstat(root)
const normalize = value => toNamespacedPath(resolve(value)).toLowerCase()
if (!stat.isDirectory() || stat.isSymbolicLink() || normalize(await realpath(root)) !== normalize(root)) {
throw new Error('Windows signing stage requires an unlinked local state directory')
}
const path = join(root, 'stage.lock')
try {
const file = await lstat(path)
if (!file.isFile() || file.isSymbolicLink()) throw new Error('Windows signing stage requires a regular lock file')
} catch (error) { if (error.code !== 'ENOENT') throw error }
const start = performance.now()
let handle
let waiting = false
for (;;) {
options.signal?.throwIfAborted()
// OPEN_ALWAYS retains the same file; denying sharing prevents concurrent holders and deletion.
handle = api.open(toNamespacedPath(path), 0xc0000000, 0, null, 4, 0x80, 0)
if (handle !== -1) break
const code = api.error()
if (code !== 32) throw new Error(`Windows signing stage cannot open its lock (Win32 ${code})`)
if (!waiting) { options.record({ type: 'signing-stage-wait', stage: options.stage }); waiting = true }
await setTimeout(100, undefined, { signal: options.signal })
}
try {
options.record({ type: 'signing-stage-acquired', stage: options.stage, waitMs: performance.now() - start })
return await operation()
} finally {
if (api.close(handle) === 0) throw new Error(`Windows signing stage cannot release its lock (Win32 ${api.error()})`)
options.record({ type: 'signing-stage-released', stage: options.stage })
}
}
+2 -1
View File
@@ -735,7 +735,8 @@ async function main(): Promise<void> {
const policyConfig = resolveDesktopPolicyConfig(policyInput, !app.isPackaged)
if (policyConfig !== undefined) {
if (policyConfig.authentication === 'feishu-test') {
policyAuth = new DesktopPolicyTestAuth(policyConfig.origin, locale, () => mandatoryUI?.confirmationWindow ?? mainWindow,
policyAuth = new DesktopPolicyTestAuth(policyConfig.origin, policyConfig.allowedAuthOrigins, locale,
() => mandatoryUI?.confirmationWindow ?? mainWindow,
(event) => { console.info(`desktop policy authentication: ${event}`); updateJournal?.action(`policy-login-${event}`) })
}
const bundleId = app.isPackaged
@@ -16,6 +16,7 @@ export interface DesktopPolicyIdentity {
export interface DesktopPolicyConfig {
readonly origin: string
readonly allowedPageOrigins: readonly string[]
readonly allowedAuthOrigins: readonly string[]
readonly intervalMs: number
readonly timeoutMs: number
readonly maxBackoffMs: number
@@ -74,12 +75,20 @@ export function resolveDesktopPolicyConfig(input: unknown, allowLoopback = false
if (authentication !== 'anonymous' && authentication !== 'feishu-test') {
throw new Error('desktop policy: authentication must be anonymous or feishu-test')
}
const authOrigins = value.allowedAuthOrigins
if (authentication === 'feishu-test' && (!Array.isArray(authOrigins) || authOrigins.length === 0)) {
throw new Error('desktop policy: test authentication requires nonempty allowedAuthOrigins')
}
if (authentication === 'anonymous' && authOrigins !== undefined) {
throw new Error('desktop policy: anonymous policy must not configure allowedAuthOrigins')
}
if (typeof jitter !== 'number' || !Number.isFinite(jitter) || jitter < 0 || jitter > 1 || maxBackoffMs < intervalMs) {
throw new Error('desktop policy: jitter must be in [0, 1] and maxBackoffMs must cover intervalMs')
}
return {
origin: origin(value.origin, authentication === 'anonymous' && allowLoopback),
allowedPageOrigins: value.allowedPageOrigins.map(item => origin(item, false)),
allowedAuthOrigins: authentication === 'feishu-test' ? (authOrigins as unknown[]).map(item => origin(item, false)) : [],
intervalMs, timeoutMs: duration('timeoutMs', 15_000), maxBackoffMs, jitter, authentication,
}
}
+4 -5
View File
@@ -3,9 +3,6 @@ import { randomUUID } from 'node:crypto'
import { BrowserWindow, session } from 'electron'
import type { DesktopLocale } from './locale.ts'
const FEISHU_ORIGINS = ['https://open.feishu.cn', 'https://accounts.feishu.cn',
'https://passport.feishu.cn', 'https://login.feishu.cn']
/** Packaged placeholder document; it is the window's first document and needs no network. */
const LOGIN_LOADING_PAGE = 'renderer/policy-login-loading.html'
@@ -28,11 +25,13 @@ export class DesktopPolicyTestAuth {
/**
* @param origin Validated HTTPS policy origin; login always starts at its root with fresh gateway state.
* @param allowedAuthOrigins Validated HTTPS origins for login document navigation.
* @param locale Shell-owned login title.
* @param parent Current application or mandatory-update window.
* @param record Fixed, nonsecret login outcomes for diagnostic evidence.
*/
constructor(private readonly origin: string, private readonly locale: DesktopLocale,
constructor(private readonly origin: string, private readonly allowedAuthOrigins: readonly string[],
private readonly locale: DesktopLocale,
private readonly parent: () => BrowserWindow | undefined,
private readonly record: (event: 'opened' | DesktopPolicyLoginResult) => void) {
this.browserSession.setPermissionRequestHandler((_contents, _permission, callback) => { callback(false) })
@@ -144,7 +143,7 @@ export class DesktopPolicyTestAuth {
let url: URL
try { url = new URL(value) } catch { return false }
return url.protocol === 'https:' && url.username === '' && url.password === ''
&& (url.origin === this.origin || FEISHU_ORIGINS.includes(url.origin))
&& (url.origin === this.origin || this.allowedAuthOrigins.includes(url.origin))
}
/**
@@ -6,7 +6,8 @@ import { loadDesktopPackageEnvironment, validateDesktopPackageEnvironment } from
const WINDOWS = { platform: 'win32', arch: 'x64' } as const
const MACOS = { platform: 'darwin', arch: 'arm64' } as const
const POLICY = { DSH_DESKTOP_MANDATORY_UPDATE_TEST_ORIGIN: 'https://policy.example.com' }
const POLICY = { DSH_DESKTOP_MANDATORY_UPDATE_TEST_ORIGIN: 'https://policy.example.com',
DSH_DESKTOP_MANDATORY_UPDATE_CONFIG: JSON.stringify({ allowedAuthOrigins: ['https://login.example.com'] }) }
const RELEASE = { ...POLICY, DSH_DESKTOP_APP_ID: 'com.example.desktop', DOWNLOAD_TEST_ORIGIN: 'https://updates.example.com' }
const MAC_IDENTITY = { DSH_DESKTOP_MACOS_SIGNING_IDENTITY: 'Example Company (TEAMID1234)', DSH_DESKTOP_MACOS_TEAM_ID: 'TEAMID1234' }
@@ -134,3 +135,14 @@ describe('Desktop local packaging configuration', () => {
})
})
})
it('owns macOS tuning in the local file and validates it before signing credentials', async () => {
await withDirectory(async (directory) => {
await writeFile(join(directory, '.env.macos'), 'DSH_DESKTOP_MACOS_PACK_CONCURRENCY=2\nDSH_DESKTOP_MACOS_DOWNLOAD_PROXY=http://proxy.example:8080\nDSH_DESKTOP_MACOS_NOTARIZATION_PROXY=\n')
const env = loadDesktopPackageEnvironment('darwin', { DSH_DESKTOP_MACOS_PACK_CONCURRENCY: '99' }, directory)
expect(env.DSH_DESKTOP_MACOS_PACK_CONCURRENCY).toBe('2')
expect(env.DSH_DESKTOP_MACOS_NOTARIZATION_PROXY).toBe('')
expect(() =>{ validateDesktopPackageEnvironment({ ...RELEASE, DSH_DESKTOP_MACOS_PACK_CONCURRENCY: '' }, MACOS) }).toThrow('PACK_CONCURRENCY')
expect(() =>{ validateDesktopPackageEnvironment({ ...RELEASE, DSH_DESKTOP_MACOS_NOTARIZATION_PROXY: 'socks5://localhost:8080' }, MACOS) }).toThrow('NOTARIZATION_PROXY')
})
})
@@ -3,28 +3,32 @@ import { resolveDesktopPolicyEnvironment } from '../scripts/desktop-policy-envir
import { validateDesktopPackageEnvironment } from '../scripts/desktop-package-environment.mjs'
import { resolveDesktopPolicyConfig } from '../src/mandatory-update-policy.ts'
const origins = { DSH_DESKTOP_MANDATORY_UPDATE_TEST_ORIGIN: 'https://harness-test.deepseek.com',
DSH_DESKTOP_MANDATORY_UPDATE_PROD_ORIGIN: 'https://harness.deepseek.com' }
const origins = { DSH_DESKTOP_MANDATORY_UPDATE_TEST_ORIGIN: 'https://test.example.com',
DSH_DESKTOP_MANDATORY_UPDATE_PROD_ORIGIN: 'https://prod.example.com' }
const auth = { DSH_DESKTOP_MANDATORY_UPDATE_CONFIG: JSON.stringify({ allowedAuthOrigins: ['https://login.example.com'] }) }
it.each(['test', 'production'] as const)('selects the %s policy and authentication together', (deployment) => {
const policy = resolveDesktopPolicyEnvironment({ ...origins, DSH_DESKTOP_AUTO_UPDATE_ENV: deployment })
const policy = resolveDesktopPolicyEnvironment({ ...origins, ...(deployment === 'test' ? auth : {}), DSH_DESKTOP_AUTO_UPDATE_ENV: deployment })
const origin = deployment === 'test' ? origins.DSH_DESKTOP_MANDATORY_UPDATE_TEST_ORIGIN : origins.DSH_DESKTOP_MANDATORY_UPDATE_PROD_ORIGIN
expect(policy).toEqual({ origin, allowedPageOrigins: [origin], authentication: deployment === 'test' ? 'feishu-test' : 'anonymous' })
expect(policy).toEqual({ origin, allowedPageOrigins: [origin],
...(deployment === 'test' ? { allowedAuthOrigins: ['https://login.example.com'] } : {}),
authentication: deployment === 'test' ? 'feishu-test' : 'anonymous' })
expect(resolveDesktopPolicyConfig(policy)).toMatchObject(policy)
})
it('requires only the selected origin, defaults to test, and accepts explicit page restrictions', () => {
const policy = resolveDesktopPolicyEnvironment({
DSH_DESKTOP_MANDATORY_UPDATE_TEST_ORIGIN: origins.DSH_DESKTOP_MANDATORY_UPDATE_TEST_ORIGIN,
DSH_DESKTOP_MANDATORY_UPDATE_CONFIG: JSON.stringify({ allowedPageOrigins: ['https://download.deepseek.com'], intervalMs: 5000 }) })
expect(policy).toMatchObject({ authentication: 'feishu-test', intervalMs: 5000, allowedPageOrigins: ['https://download.deepseek.com'] })
DSH_DESKTOP_MANDATORY_UPDATE_CONFIG: JSON.stringify({ allowedAuthOrigins: ['https://login.example.com'],
allowedPageOrigins: ['https://download.example.com'], intervalMs: 5000 }) })
expect(policy).toMatchObject({ authentication: 'feishu-test', intervalMs: 5000, allowedPageOrigins: ['https://download.example.com'] })
expect(() => resolveDesktopPolicyEnvironment({ ...origins, DSH_DESKTOP_AUTO_UPDATE_ENV: 'prod' })).toThrow('production')
})
it.each([undefined, '', 'http://harness-test.deepseek.com', 'https://user:secret@harness-test.deepseek.com',
'https://harness-test.deepseek.com/api', 'https://harness-test.deepseek.com/?secret=value'])('rejects invalid selected origin %s', (origin) => {
expect(() => resolveDesktopPolicyEnvironment({ DSH_DESKTOP_MANDATORY_UPDATE_TEST_ORIGIN: origin })).toThrow('HTTPS origin')
expect(() => resolveDesktopPolicyEnvironment({ DSH_DESKTOP_MANDATORY_UPDATE_TEST_ORIGIN: origin })).not.toThrow('secret=value')
it.each([undefined, '', 'http://test.example.com', 'https://user:secret@test.example.com',
'https://test.example.com/api', 'https://test.example.com/?secret=value'])('rejects invalid selected origin %s', (origin) => {
expect(() => resolveDesktopPolicyEnvironment({ ...auth, DSH_DESKTOP_MANDATORY_UPDATE_TEST_ORIGIN: origin })).toThrow('HTTPS origin')
expect(() => resolveDesktopPolicyEnvironment({ ...auth, DSH_DESKTOP_MANDATORY_UPDATE_TEST_ORIGIN: origin })).not.toThrow('secret=value')
})
it.each(['{', 'null', '[]', '{"origin":"https://old.example.com"}', '{"authentication":"anonymous"}',
@@ -32,6 +36,17 @@ it.each(['{', 'null', '[]', '{"origin":"https://old.example.com"}', '{"authentic
expect(() => resolveDesktopPolicyEnvironment({ ...origins, DSH_DESKTOP_MANDATORY_UPDATE_CONFIG: options })).toThrow()
})
it.each([undefined, '[]', '["http://login.example.com"]', '["https://login.example.com/path"]',
'["https://user:[email protected]"]'])('rejects missing or invalid test login origins %s', (value) => {
const settings = value === undefined ? {} : { allowedAuthOrigins: JSON.parse(value) as unknown }
expect(() => resolveDesktopPolicyEnvironment({ ...origins, DSH_DESKTOP_MANDATORY_UPDATE_CONFIG: JSON.stringify(settings) })).toThrow()
})
it('rejects login origins in production', () => {
expect(() => resolveDesktopPolicyEnvironment({ ...origins, ...auth, DSH_DESKTOP_AUTO_UPDATE_ENV: 'production' }))
.toThrow('must not configure allowedAuthOrigins')
})
it.each([{ unsigned: true }, { prepareOnly: true }, {}])('fails before signing/preparation when policy is absent in %j', (options) => {
for (const platform of ['win32', 'darwin'] as const) {
expect(() => { validateDesktopPackageEnvironment({ DSH_DESKTOP_APP_ID: 'com.example.test' }, { platform, arch: 'x64' }, options) })
+15
View File
@@ -0,0 +1,15 @@
/** Exercise one independent signature-cache writer through native TypeScript stripping. */
import { readFileSync, writeFileSync } from 'node:fs'
import { cachedMacOSSignature } from '../../scripts/macos-signature-cache.ts'
const [file, cache] = process.argv.slice(2)
await cachedMacOSSignature(file, cache, {
policy: 'cross-process-fixture',
sign: async path => {
const ready = new Promise(resolve => process.once('message', resolve))
process.send('ready')
await ready
writeFileSync(path, `${readFileSync(path, 'utf8')}:signed`)
},
verify: path => { if (readFileSync(path, 'utf8') !== 'original:signed') throw Error('invalid signature') },
})
process.disconnect()
+27
View File
@@ -0,0 +1,27 @@
/** Independent process exercising stage ownership and cache reuse with a hardware-free signer. */
import { appendFile, readFile, writeFile } from 'node:fs/promises'
import { join } from 'node:path'
import { withWindowsSigningStage } from '../../scripts/windows-signing-stage.mjs'
import { createCachedSigner, maintainSignatureCache } from '../../scripts/windows-signature-cache.mjs'
const [root, input, mode] = process.argv.slice(2)
const release = new Promise(resolve => process.once('message', resolve))
await withWindowsSigningStage({ stateDirectory: join(root, 'state'), stage: 'fixture', record: event => process.send(event) }, async () => {
process.send({ type: 'entered' })
await release
if (mode === 'clear') {
await maintainSignatureCache(join(root, 'cache'), true)
return
}
const thumbprint = 'A'.repeat(40)
const signer = createCachedSigner({ root: join(root, 'cache'), identity: 'fixture', thumbprint,
record: event => process.send(event),
inspect: async path => ({ status: (await readFile(path, 'utf8')).startsWith('signed:') ? 'Valid' : 'NotSigned', timestamped: true, thumbprint }),
sign: async ({ path }) => {
await appendFile(join(root, 'hardware-calls'), 'call\n')
await writeFile(path, `signed:${await readFile(path, 'utf8')}`)
},
})
await signer({ path: input, hash: 'sha256', isNest: false })
})
process.disconnect()
@@ -20,6 +20,7 @@ vi.mock('../scripts/windows-sign.mjs', () => ({
const versions = ['0.1.6-nightly.20260914.1', '0.1.6-nightly.20260914.2'] as const
const environment = { DSH_DESKTOP_AUTO_UPDATE_ENV: 'test', DOWNLOAD_TEST_ORIGIN: 'https://download-test.deepseek.com',
DSH_DESKTOP_MANDATORY_UPDATE_TEST_ORIGIN: 'https://policy.example.com',
DSH_DESKTOP_MANDATORY_UPDATE_CONFIG: JSON.stringify({ allowedAuthOrigins: ['https://login.example.com'] }),
DOWNLOAD_TEST_COS_BUCKET: 'bj-toc-download-test-1320056602' }
const require = createRequire(import.meta.url)
const { validateConfiguration } = require('app-builder-lib/out/util/config/config.js') as {
@@ -61,7 +61,7 @@ async function fixture(body: (context: {
await writeFile(join(source, 'package.json'), JSON.stringify({ name: `dsh-update-test-${run.id}`, version,
dshDesktopAppId: run.appId, main: 'qualification-bootstrap.mjs', type: 'module',
dshMandatoryUpdatePolicy: { origin: 'https://policy.example.com', allowedPageOrigins: ['https://policy.example.com'],
authentication: 'feishu-test' } }))
authentication: 'feishu-test', allowedAuthOrigins: ['https://login.example.com'] } }))
for (const name of ['electron-updater', 'semver']) {
await mkdir(join(source, 'node_modules', name), { recursive: true })
await cp(require.resolve(`${name}/package.json`), join(source, 'node_modules', name, 'package.json'))
@@ -16,7 +16,7 @@ describe('installer preparation preserves application dependencies', () => {
const { createElectronBuilderConfig } = await import('../scripts/electron-builder-config.mjs')
expect(() => createElectronBuilderConfig({ DSH_DESKTOP_APP_ID: 'com.example.installer',
DSH_DESKTOP_AUTO_UPDATE_ENV: 'production',
DSH_DESKTOP_MANDATORY_UPDATE_TEST_ORIGIN: 'https://harness-test.deepseek.com',
DSH_DESKTOP_MANDATORY_UPDATE_TEST_ORIGIN: 'https://test.example.com',
}, platform, 'x64')).toThrow('DSH_DESKTOP_MANDATORY_UPDATE_PROD_ORIGIN')
})
it.each(['win32', 'darwin'] as const)('keeps electron-builder responsible for node_modules on %s', async (platform) => {
@@ -24,6 +24,7 @@ describe('installer preparation preserves application dependencies', () => {
const env = {
DSH_DESKTOP_APP_ID: 'com.example.installer',
DSH_DESKTOP_MANDATORY_UPDATE_TEST_ORIGIN: 'https://policy.example.com',
DSH_DESKTOP_MANDATORY_UPDATE_CONFIG: JSON.stringify({ allowedAuthOrigins: ['https://login.example.com'] }),
DSH_DESKTOP_TARGET_PLATFORM: platform,
DSH_DESKTOP_TARGET_ARCH: 'x64',
DSH_DESKTOP_UNSIGNED: platform === 'win32' ? '1' : '0',
@@ -0,0 +1,33 @@
import { expect, it, vi } from 'vitest'
import { runLoggedNotarytool } from '../scripts/logged-notarytool.mjs'
const command = vi.hoisted(() => vi.fn<(...args: unknown[]) => Promise<{ stdout: string; stderr: string }>>())
vi.mock('node:child_process', async (importOriginal) => {
const { promisify } = await import('node:util')
return {
...await importOriginal<typeof import('node:child_process')>(),
execFile: Object.assign(() => {}, { [promisify.custom]: command }),
}
})
const id = '11111111-2222-3333-4444-555555555555'
const args = ['submit', '/fixture/app.zip', '--keychain-profile', 'fixture', '--wait', '--output-format', 'json']
it('passes Apple rejection JSON from a nonzero wait exit back to electron-notarize for diagnostic retrieval', async () => {
command.mockReset()
command.mockResolvedValueOnce({ stdout: JSON.stringify({ id }), stderr: '' })
command.mockRejectedValueOnce(Object.assign(new Error('notarytool exited 65'), {
code: 65, stdout: JSON.stringify({ id, status: 'Invalid' }), stderr: '',
}))
expect(JSON.parse(await runLoggedNotarytool(args))).toEqual({ id, status: 'Invalid' })
expect(command).toHaveBeenCalledTimes(2)
})
it('does not treat failed upload output as a completed submission', async () => {
command.mockReset()
command.mockRejectedValueOnce(Object.assign(new Error('upload failed'), {
code: 1, stdout: JSON.stringify({ id }), stderr: '',
}))
await expect(runLoggedNotarytool(args)).rejects.toThrow('upload failed')
expect(command).toHaveBeenCalledOnce()
})
@@ -0,0 +1,82 @@
import { mkdtemp, readFile, rm } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { expect, it, vi } from 'vitest'
import { runLoggedNotarytool } from '../scripts/logged-notarytool.mjs'
import { createPackagingRun } from '../scripts/packaging-run.mjs'
const id = '11111111-2222-3333-4444-555555555555'
const args = ['submit', '/fixture/app.zip', '--apple-id', '[email protected]', '--password', 'secret-value', '--team-id', 'TEAM', '--wait', '--output-format', 'json']
async function fixture(action: (directory: string) => Promise<void>) {
const root = await mkdtemp(join(tmpdir(), 'notary-log-'))
try { await action(createPackagingRun(root, {}).directory) } finally { await rm(root, { recursive: true, force: true }) }
}
it('finishes submission before starting wait and records the ID and separate timings', async () => {
await fixture(async (directory) => {
const uploaded = Promise.withResolvers<string>()
const execute = vi.fn(async (command: readonly string[]) => command[0] === 'submit' ? uploaded.promise : JSON.stringify({ id, status: 'Accepted' }))
const work = runLoggedNotarytool(args, directory, execute)
try {
expect(execute).toHaveBeenCalledExactlyOnceWith(args.filter(arg => arg !== '--wait').concat('--no-wait'))
expect(await readFile(join(directory, 'events.jsonl'), 'utf8')).not.toContain('notarytool:wait')
} finally { uploaded.resolve(JSON.stringify({ id })) }
expect(JSON.parse(await work)).toEqual({ id, status: 'Accepted' })
expect(execute.mock.calls[1]![0]).toEqual(['wait', id, '--apple-id', '[email protected]', '--password', 'secret-value', '--team-id', 'TEAM', '--output-format', 'json'])
const log = await readFile(join(directory, 'events.jsonl'), 'utf8')
expect(log).toContain('notary-submission')
expect(log).toContain('notarytool:upload:app.zip')
expect(log).toContain('notarytool:wait:app.zip')
expect(log).toContain('elapsedMs')
expect(log).not.toContain('[email protected]')
expect(log).not.toContain('secret-value')
})
})
it('records a redacted upload error without starting wait', async () => {
await fixture(async (directory) => {
const execute = vi.fn(async () => { throw new Error('rejected secret-value [email protected]') })
await expect(runLoggedNotarytool(args, directory, execute)).rejects.toThrow('rejected')
expect(execute).toHaveBeenCalledOnce()
const log = await readFile(join(directory, 'events.jsonl'), 'utf8')
expect(log).toContain('"success":false')
expect(log).not.toContain('secret-value')
expect(log).not.toContain('[email protected]')
})
})
it.each(['Invalid', 'Rejected'])('preserves %s for electron-notarize rejection handling', async (status) => {
const execute = vi.fn(async (command: readonly string[]) => JSON.stringify(command[0] === 'submit' ? { id } : { id, status }))
await fixture(async (directory) => {
expect(JSON.parse(await runLoggedNotarytool(args, directory, execute))).toEqual({ id, status })
const log = await readFile(join(directory, 'events.jsonl'), 'utf8')
expect(log).toContain('\"success\":false')
expect(log).toContain(status)
})
})
it('rejects missing submission IDs and mismatched wait results', async () => {
await expect(runLoggedNotarytool(args, undefined, async () => '{}')).rejects.toThrow('submission ID')
await expect(runLoggedNotarytool(args, undefined, async command => JSON.stringify(command[0] === 'submit' ? { id } : { id: 'other', status: 'Accepted' }))).rejects.toThrow('different submission ID')
})
it.each([
['--key', '/private/AuthKey.p8', '--key-id', 'KEY123', '--issuer', id],
['--keychain-profile', 'release', '--keychain', '/private/release.keychain'],
])('preserves API-key and keychain authentication when waiting: %j', async (...auth) => {
const execute = vi.fn(async () => JSON.stringify({ id, status: 'Accepted' }))
await runLoggedNotarytool(['submit', '/fixture/release.dmg', ...auth, '--wait', '--output-format', 'json'], undefined, execute)
expect(execute.mock.calls[1]).toEqual([['wait', id, ...auth, '--output-format', 'json']])
})
it('retains redacted Apple diagnostics and passes the original result to electron-notarize', async () => {
await fixture(async (directory) => {
const output = 'diagnostic for [email protected]'
const command = ['log', id, '--apple-id', '[email protected]']
expect(await runLoggedNotarytool(command, directory, async () => output)).toBe(output)
const log = await readFile(join(directory, 'events.jsonl'), 'utf8')
expect(log).toContain('notary-diagnostics')
expect(log).toContain('[REDACTED]')
expect(log).not.toContain('[email protected]')
})
})
@@ -0,0 +1,57 @@
import { spawnSync } from 'node:child_process'
import { writeFileSync } from 'node:fs'
import { join } from 'node:path'
import { afterEach, beforeEach, expect, it, vi } from 'vitest'
import { macOSCachePolicy } from '../scripts/macos-cache-policy.ts'
vi.mock('node:child_process', async importOriginal => ({ ...await importOriginal<typeof import('node:child_process')>(), spawnSync: vi.fn() }))
vi.mock('node:fs', async (importOriginal) => {
const fs = await importOriginal<typeof import('node:fs')>()
return { ...fs, readFileSync: (...args: Parameters<typeof fs.readFileSync>) => args[0] === '/usr/bin/codesign' ? Buffer.from('codesign-tool') : args[0] === 'candidate' ? Buffer.from(header, 'hex') : fs.readFileSync(...args) }
})
const identity = { signingIdentity: 'Example (TEAM123456)', teamId: 'TEAM123456' }
const expectedDetails = 'Authority=Developer ID Application: Example (TEAM123456)\nTeamIdentifier=TEAM123456\nTimestamp=today\nCodeDirectory v=20500 flags=0x10000(runtime)\nIdentifier=com.example.file\n'
let header = 'cffaedfe'
let details = expectedDetails
let certificate = 'leaf-certificate'
let entitlements = ''
let rejectVerify = false
beforeEach(() => {
header = 'cffaedfe'; details = expectedDetails; certificate = 'leaf-certificate'; entitlements = ''; rejectVerify = false
vi.mocked(spawnSync).mockImplementation((command, args, options) => {
const argv = args as string[]
if (command === '/usr/bin/plutil') {
const input = (options as { input: string }).input
return { pid: 1, output: [], status: 0, signal: null, stdout: JSON.stringify(input.includes('allow-jit') ? { 'com.apple.security.cs.allow-jit': true } : {}), stderr: '' }
}
const extraction = argv.find(arg => arg.startsWith('--extract-certificates='))
if (extraction) writeFileSync(`${extraction.slice('--extract-certificates='.length)}0`, certificate)
return { pid: 1, output: [], status: rejectVerify && argv.includes('--verify') ? 1 : 0, signal: null, stdout: entitlements, stderr: details }
})
})
afterEach(() => { vi.resetAllMocks() })
it('accepts only a signature matching the resolved policy', () => {
const signer = macOSCachePolicy('probe')('com.example.file', identity)
expect(() => { signer.verify('candidate') }).not.toThrow()
})
it.each(['certificate', 'identifier', 'team', 'authority', 'timestamp', 'runtime', 'entitlements', 'strict', 'universal'])('rejects mismatched %s', (field) => {
const signer = macOSCachePolicy('probe')('com.example.file', identity)
if (field === 'certificate') certificate = 'another-certificate'
if (field === 'identifier') details = details.replace('com.example.file', 'com.other.file')
if (field === 'team') details = details.replace('TeamIdentifier=TEAM123456', 'TeamIdentifier=OTHER12345')
if (field === 'authority') details = details.replace('Authority=Developer', 'Authority=Other')
if (field === 'timestamp') details = details.replace('Timestamp=today', '')
if (field === 'runtime') details = details.replace('flags=0x10000(runtime)', 'flags=0x0(none)')
if (field === 'entitlements') entitlements = '<key>com.apple.security.cs.allow-jit</key>'
if (field === 'strict') rejectVerify = true
if (field === 'universal') header = 'cafebabe'
expect(() => { signer.verify('candidate') }).toThrow()
})
it('includes certificate, identifier and entitlement contents in the cache policy', () => {
const create = macOSCachePolicy('probe')
const original = create('com.example.file', identity).policy
expect(create('com.other.file', identity).policy).not.toBe(original)
expect(create('com.example.file', identity, join(import.meta.dirname, '../scripts/node-entitlements.plist')).policy).not.toBe(original)
certificate = 'renewed-certificate'
expect(macOSCachePolicy('probe')('com.example.file', identity).policy).not.toBe(original)
})
@@ -0,0 +1,273 @@
import { existsSync, readFileSync } from 'node:fs'
import { spawn } from 'node:child_process'
import { once } from 'node:events'
import { mkdtemp, rm, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { expect, it as test, vi } from 'vitest'
import { restoreMacOSNotarizationProxy, withMacOSNotarizationProxy } from '../scripts/macos-notarization-proxy.ts'
// System proxy transactions use POSIX flock, which is unavailable on Windows.
const it = test.skipIf(process.platform === 'win32')
async function fixture(action: (fixture: ReturnType<typeof fakeSystem>, lock: string) => Promise<void>): Promise<void> {
const root = await mkdtemp(join(tmpdir(), 'mac-proxy-test-'))
try { await action(fakeSystem(), join(root, 'lock')) } finally { await rm(root, { recursive: true, force: true }) }
}
function fakeSystem() {
const states = {
http: { enabled: false, server: 'old-http', port: 3128 },
https: { enabled: true, server: 'old-https', port: 8080 },
}
const original = structuredClone(states)
const control = { failSet: 0, setCount: 0, pac: false, authenticated: false, serverSpace: true, ignoreDisable: false }
const ops = {
reachable: vi.fn(async (_url: URL) => {}),
ownerAlive: vi.fn((_pid: number) => false),
command: vi.fn((executable: string, args: readonly string[]) => {
if (executable === '/sbin/route') return ' interface: en9\n'
if (args[0] === '-listnetworkserviceorder') return '(1) Ethernet\n(Hardware Port: USB LAN, Device: en9)\n\n(2) Wi-Fi\n(Hardware Port: Wi-Fi, Device: en0)\n'
expect(args[1]).toBe('Ethernet')
if (args[0] === '-getautoproxyurl') return `URL: http://pac\nEnabled: ${control.pac ? 'Yes' : 'No'}\n`
if (args[0] === '-getproxyautodiscovery') return 'Auto Proxy Discovery: Off\n'
if (args[0] === '-getsocksfirewallproxy') return 'Enabled: No\n'
const state = args[0]!.includes('secure') ? states.https : states.http
if (args[0]!.startsWith('-get')) return `Enabled: ${state.enabled ? 'Yes' : 'No'}\nServer:${control.serverSpace ? ' ' : ''}${state.server}\nPort: ${state.port}\nAuthenticated Proxy Enabled: ${control.authenticated ? '1' : '0'}\n`
control.setCount++
if (control.setCount === control.failSet) throw new Error('system write failed')
if (args[0]!.endsWith('state')) {
if (!(control.ignoreDisable && args[2] === 'off')) state.enabled = args[2] === 'on'
}
else { state.server = args[2]!; state.port = Number(args[3]); state.enabled = true }
return ''
}),
}
return { ops, states, original, control }
}
it('preserves the network when no Apple proxy is configured', async () => {
await fixture(async ({ ops }, lock) => {
await expect(withMacOSNotarizationProxy(undefined, async () => 42, lock, ops)).resolves.toBe(42)
expect(ops.command).not.toHaveBeenCalled()
expect(ops.reachable).not.toHaveBeenCalled()
expect(existsSync(lock)).toBe(false)
})
})
it.each([false, true])('restores both original proxies after settled work (failure=%s)', async (fail) => {
await fixture(async ({ ops, states, original }, lock) => {
const statuses: string[] = []
const work = withMacOSNotarizationProxy('http://localhost:8888', async () => {
expect(states.http).toEqual({ enabled: true, server: 'localhost', port: 8888 })
expect(states.https).toEqual(states.http)
const record = JSON.parse(readFileSync(join(lock, 'original.json'), 'utf8')) as { service: string }
expect(record.service).toBe('Ethernet')
if (fail) throw new Error('Apple refused')
return 42
}, lock, ops, (status) => { statuses.push(status) })
if (fail) await expect(work).rejects.toThrow('Apple refused')
else await expect(work).resolves.toBe(42)
expect(statuses).toEqual(['restoration-pending', 'enabled', 'restored'])
expect(states).toEqual(original)
expect(existsSync(lock)).toBe(false)
})
})
it.each([false, true])('disables originally empty proxies without writing empty endpoints (space=%s)', async (space) => {
await fixture(async ({ ops, states, control }, lock) => {
control.serverSpace = space
states.http = { enabled: false, server: '', port: 0 }
states.https = { enabled: false, server: '', port: 0 }
await expect(withMacOSNotarizationProxy('http://localhost:8888', async () => {
expect(states.http.enabled).toBe(true)
expect(states.https.enabled).toBe(true)
throw new Error('Apple refused')
}, lock, ops)).rejects.toThrow('Apple refused')
expect(states.http).toEqual({ enabled: false, server: 'localhost', port: 8888 })
expect(states.https).toEqual(states.http)
const setters = ops.command.mock.calls.filter(([, args]) => ['-setwebproxy', '-setsecurewebproxy'].includes(args[0]!))
expect(setters).toHaveLength(2)
expect(setters.every(([, args]) => args[2] === 'localhost')).toBe(true)
expect(existsSync(lock)).toBe(false)
})
})
it('retains an empty-proxy recovery record after failed disabling and retries it', async () => {
await fixture(async ({ ops, states, control }, lock) => {
states.http = { enabled: false, server: '', port: 0 }
states.https = { enabled: false, server: '', port: 0 }
control.failSet = 5
await expect(withMacOSNotarizationProxy('http://localhost:8888', async () => {}, lock, ops)).rejects.toThrow('restoration failed')
expect(existsSync(lock)).toBe(true)
expect(states.http.enabled).toBe(true)
expect(states.https.enabled).toBe(false)
await restoreMacOSNotarizationProxy(lock, ops)
expect(states.http.enabled).toBe(false)
expect(states.https.enabled).toBe(false)
expect(existsSync(lock)).toBe(false)
})
})
it('keeps the recovery record when disabling an originally empty proxy has no effect', async () => {
await fixture(async ({ ops, states, control }, lock) => {
states.http = { enabled: false, server: '', port: 0 }
control.ignoreDisable = true
await expect(withMacOSNotarizationProxy('http://localhost:8888', async () => {}, lock, ops)).rejects.toThrow('restoration failed')
expect(states.http.enabled).toBe(true)
expect(existsSync(lock)).toBe(true)
control.ignoreDisable = false
await restoreMacOSNotarizationProxy(lock, ops)
expect(states.http.enabled).toBe(false)
expect(existsSync(lock)).toBe(false)
})
})
it('does not steal a live lock and holds the proxy until concurrent work drains', async () => {
await fixture(async ({ ops, states, original }, lock) => {
const entered = Promise.withResolvers<undefined>()
const finish = Promise.withResolvers<undefined>()
const running = withMacOSNotarizationProxy('http://localhost:8888', async () => { entered.resolve(undefined); await finish.promise }, lock, ops)
try {
await entered.promise
await expect(withMacOSNotarizationProxy('http://localhost:8889', async () => {}, lock, ops)).rejects.toThrow('another run')
await expect(restoreMacOSNotarizationProxy(lock, ops)).rejects.toThrow('another run')
expect(ops.ownerAlive).not.toHaveBeenCalled()
expect(states.http.port).toBe(8888)
expect(existsSync(lock)).toBe(true)
} finally { finish.resolve(undefined); await running }
expect(states).toEqual(original)
})
})
it('excludes both operations across processes and releases ownership after forced exit', async () => {
await fixture(async ({ ops, states, original, control }, lock) => {
control.failSet = 5
await expect(withMacOSNotarizationProxy('http://localhost:8888', async () => {}, lock, ops)).rejects.toThrow('restoration failed')
const saved = readFileSync(join(lock, 'original.json'), 'utf8')
// Coverage builds the addon, but does not emit the package's JavaScript entry.
const flockSource = new URL('../../../native/system/packages/entry/src/flock.ts', import.meta.url).href
const child = spawn(process.execPath, ['--input-type=module', '-e', `
import { openSync } from 'node:fs';
import { tryLockExclusive } from ${JSON.stringify(flockSource)};
const fd = openSync(process.argv[1], 'a', 0o600);
await tryLockExclusive(fd);
process.send('locked');
process.stdin.resume();
`, `${lock}.flock`], { stdio: ['pipe', 'ignore', 'pipe', 'ipc'], env: { PATH: process.env.PATH } })
const exited = once(child, 'exit')
const closed = once(child, 'close')
let stderr = ''
child.stderr!.setEncoding('utf8').on('data', (chunk: string) => { stderr = (stderr + chunk).slice(-8192) })
try {
await Promise.race([
once(child, 'message').then(([message]) => { expect(message).toBe('locked') }),
closed.then(([code, signal]) => { throw new Error(`lock holder exited before readiness: ${code}/${signal}\n${stderr}`) }),
])
ops.command.mockClear()
ops.ownerAlive.mockClear()
await expect(restoreMacOSNotarizationProxy(lock, ops)).rejects.toThrow('another run')
await expect(withMacOSNotarizationProxy('http://localhost:8889', async () => {}, lock, ops)).rejects.toThrow('another run')
expect(ops.command).not.toHaveBeenCalled()
expect(ops.ownerAlive).not.toHaveBeenCalled()
expect(readFileSync(join(lock, 'original.json'), 'utf8')).toBe(saved)
} finally {
child.kill('SIGKILL')
await closed
}
expect(await exited).toEqual([null, 'SIGKILL'])
await restoreMacOSNotarizationProxy(lock, ops)
expect(states).toEqual(original)
expect(existsSync(lock)).toBe(false)
expect(existsSync(`${lock}.flock`)).toBe(true)
await withMacOSNotarizationProxy('http://localhost:8889', async () => {}, lock, ops)
expect(states).toEqual(original)
})
})
it('restores partial setup and never calls Apple after a system write failure', async () => {
await fixture(async ({ ops, states, original, control }, lock) => {
control.failSet = 3
const action = vi.fn(async () => {})
await expect(withMacOSNotarizationProxy('http://localhost:8888', action, lock, ops)).rejects.toThrow('system write failed')
expect(action).not.toHaveBeenCalled()
expect(states).toEqual(original)
expect(existsSync(lock)).toBe(false)
})
})
it.each(['pac', 'authenticated'] as const)('rejects unpreservable %s settings before mutation', async (kind) => {
await fixture(async ({ ops, states, original, control }, lock) => {
control[kind] = true
const action = vi.fn(async () => {})
await expect(withMacOSNotarizationProxy('http://localhost:8888', action, lock, ops)).rejects.toThrow(/proxy|proxies/u)
expect(control.setCount).toBe(0)
expect(action).not.toHaveBeenCalled()
expect(states).toEqual(original)
})
})
it('fails unreachable proxies before acquiring a lock or changing settings', async () => {
await fixture(async ({ ops }, lock) => {
ops.reachable.mockRejectedValueOnce(new Error('unreachable'))
await expect(withMacOSNotarizationProxy('http://localhost:8888', async () => {}, lock, ops)).rejects.toThrow('unreachable')
expect(ops.command).not.toHaveBeenCalled()
expect(existsSync(lock)).toBe(false)
})
})
it('retains recovery data after failed restoration, rejects live owners, then recovers after owner exit', async () => {
await fixture(async ({ ops, states, original, control }, lock) => {
control.failSet = 5
await expect(withMacOSNotarizationProxy('http://localhost:8888', async () => {}, lock, ops)).rejects.toThrow('restoration failed')
expect(existsSync(join(lock, 'original.json'))).toBe(true)
ops.ownerAlive.mockReturnValueOnce(true)
await expect(restoreMacOSNotarizationProxy(lock, ops)).rejects.toThrow('still running')
await restoreMacOSNotarizationProxy(lock, ops)
expect(states).toEqual(original)
expect(existsSync(lock)).toBe(false)
})
})
it('rejects malformed saved state without invoking host commands', async () => {
await fixture(async ({ ops, control }, lock) => {
control.failSet = 5
await expect(withMacOSNotarizationProxy('http://localhost:8888', async () => {}, lock, ops)).rejects.toThrow('restoration failed')
await writeFile(join(lock, 'original.json'), '{"pid":-1}')
ops.command.mockClear()
await expect(restoreMacOSNotarizationProxy(lock, ops)).rejects.toThrow('invalid proxy recovery record')
expect(ops.command).not.toHaveBeenCalled()
})
})
it('defers interruption until work settles and removes its signal listeners after restoration', async () => {
await fixture(async ({ ops, states, original }, lock) => {
const before = process.listenerCount('SIGTERM')
const entered = Promise.withResolvers<undefined>()
const finish = Promise.withResolvers<undefined>()
const stderr = vi.spyOn(process.stderr, 'write').mockReturnValue(true)
const running = withMacOSNotarizationProxy('http://localhost:8888', async () => { entered.resolve(undefined); await finish.promise }, lock, ops)
const result = expect(running).rejects.toThrow('interrupted by SIGTERM')
try {
await entered.promise
// Deliver only the listener owned by this invocation; never signal the test runner or other suites.
const listener = process.listeners('SIGTERM').at(-1)!
listener('SIGTERM')
expect(states.http.port).toBe(8888)
expect(existsSync(lock)).toBe(true)
} finally { finish.resolve(undefined); await result; stderr.mockRestore() }
expect(states).toEqual(original)
expect(process.listenerCount('SIGTERM')).toBe(before)
})
})
it('retains both the Apple failure and restoration failure', async () => {
await fixture(async ({ ops, control }, lock) => {
control.failSet = 5
const appleError = new Error('Apple refused')
const result = withMacOSNotarizationProxy('http://localhost:8888', async () => { throw appleError }, lock, ops)
await expect(result).rejects.toMatchObject({ errors: [appleError, expect.any(AggregateError)] })
expect(existsSync(join(lock, 'original.json'))).toBe(true)
await restoreMacOSNotarizationProxy(lock, ops)
})
})
@@ -0,0 +1,34 @@
import { expect, it } from 'vitest'
import { macOSDownloadEnvironment, resolveMacOSPackageSettings } from '../scripts/macos-package-settings.mjs'
it('defaults to four workers and keeps download and Apple proxies independent', () => {
expect(resolveMacOSPackageSettings({})).toEqual({ packConcurrency: 4 })
expect(resolveMacOSPackageSettings({ DSH_DESKTOP_MACOS_PACK_CONCURRENCY: '2',
DSH_DESKTOP_MACOS_DOWNLOAD_PROXY: 'https://download.example:8080',
DSH_DESKTOP_MACOS_NOTARIZATION_PROXY: 'http://apple.example:8081',
})).toEqual({ packConcurrency: 2, downloadProxy: 'https://download.example:8080', notarizationProxy: 'http://apple.example:8081' })
expect(resolveMacOSPackageSettings({ DSH_DESKTOP_MACOS_DOWNLOAD_PROXY: ' ', DSH_DESKTOP_MACOS_NOTARIZATION_PROXY: '' })).toEqual({ packConcurrency: 4 })
})
it.each(['', '0', '-1', '1.5', '1e2', 'Infinity', '9007199254740992'])('rejects invalid concurrency %j', (value) => {
expect(() => resolveMacOSPackageSettings({ DSH_DESKTOP_MACOS_PACK_CONCURRENCY: value })).toThrow('PACK_CONCURRENCY')
})
it.each(['socks5://host:8080', 'http://user:secret@host', 'http://host/path', 'http://host?query', 'http://host#fragment', 'invalid'])
('rejects unsupported proxy input without echoing it: %s', (value) => {
expect(() => resolveMacOSPackageSettings({ DSH_DESKTOP_MACOS_NOTARIZATION_PROXY: value })).toThrow('NOTARIZATION_PROXY')
expect(() => resolveMacOSPackageSettings({ DSH_DESKTOP_MACOS_NOTARIZATION_PROXY: value })).not.toThrow(value)
})
it('overrides conflicting child proxy variables while preserving the parent and unrelated settings', () => {
const parent = { PATH: 'tools', HTTPS_PROXY: 'http://old', http_proxy: 'http://lower', ALL_PROXY: 'socks5://old',
NO_PROXY: '*', npm_config_proxy: 'http://npm', ELECTRON_GET_USE_PROXY: '0' }
expect(macOSDownloadEnvironment(parent)).toEqual(parent)
const child = macOSDownloadEnvironment(parent, 'http://new:8080')
expect(child).toMatchObject({ PATH: 'tools', HTTP_PROXY: 'http://new:8080', HTTPS_PROXY: 'http://new:8080',
http_proxy: 'http://new:8080', https_proxy: 'http://new:8080', ELECTRON_GET_USE_PROXY: '1', NO_PROXY: 'localhost,127.0.0.1,::1' })
expect(child).not.toHaveProperty('ALL_PROXY')
expect(child).not.toHaveProperty('npm_config_proxy')
expect(parent.HTTPS_PROXY).toBe('http://old')
expect(parent.NO_PROXY).toBe('*')
})
@@ -0,0 +1,139 @@
import { fork } from 'node:child_process'
import { once } from 'node:events'
import { chmodSync, existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, realpathSync, rmSync, symlinkSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, expect, it, vi } from 'vitest'
import { cachedMacOSSignature, type MacOSCachedSigner } from '../scripts/macos-signature-cache.ts'
const roots: string[] = []
afterEach(() => { for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true }) })
function fixture(): { root: string; file: string; cache: string; signer: MacOSCachedSigner } {
const root = realpathSync(mkdtempSync(join(tmpdir(), 'mac-signature-cache-')))
roots.push(root)
const file = join(root, 'code')
writeFileSync(file, 'original', { mode: 0o755 })
return { root, file, cache: join(root, 'cache'), signer: {
policy: 'certificate+identifier+entitlements+tools',
sign: vi.fn(async (path: string) => { writeFileSync(path, `${readFileSync(path, 'utf8')}:signed`) }),
verify: vi.fn((path: string) => { if (!readFileSync(path, 'utf8').endsWith(':signed')) throw Error('invalid signature') }),
} }
}
it('reuses verified bytes without sharing mutable cache storage', async () => {
const { file, cache, signer } = fixture()
expect(await cachedMacOSSignature(file, cache, signer)).toBe(false)
writeFileSync(file, 'original')
expect(await cachedMacOSSignature(file, cache, signer)).toBe(true)
expect(signer.sign).toHaveBeenCalledTimes(1)
expect(signer.verify).toHaveBeenCalledTimes(2)
expect(readFileSync(file, 'utf8')).toBe('original:signed')
if (process.platform !== 'win32') expect(lstatSync(file).mode & 0o777).toBe(0o755)
writeFileSync(file, 'later mutation')
writeFileSync(file, 'original')
expect(await cachedMacOSSignature(file, cache, signer)).toBe(true)
})
it.each(['input', 'policy', 'mode'])('invalidates changed %s without consulting git', async (change) => {
const { file, cache, signer } = fixture()
await cachedMacOSSignature(file, cache, signer)
writeFileSync(file, change === 'input' ? 'uncommitted' : 'original')
if (change === 'mode') {
if (process.platform === 'win32') return
chmodSync(file, 0o644)
}
expect(await cachedMacOSSignature(file, cache, change === 'policy' ? { ...signer, policy: 'new-policy' } : signer)).toBe(false)
expect(signer.sign).toHaveBeenCalledTimes(2)
})
it.each(['payload', 'record', 'signature'])('rejects corrupted %s without replacing the input', async (damage) => {
const { file, cache, signer } = fixture()
await cachedMacOSSignature(file, cache, signer)
writeFileSync(file, 'original')
const entry = join(cache, readdirSync(cache)[0]!)
if (damage === 'payload') writeFileSync(join(entry, 'code'), 'truncated')
if (damage === 'record') writeFileSync(join(entry, 'record.json'), '{"key":"wrong"}')
if (damage === 'signature') signer.verify = () => { throw Error('invalid signature') }
await expect(cachedMacOSSignature(file, cache, signer)).rejects.toThrow()
expect(readFileSync(file, 'utf8')).toBe('original')
})
it('never publishes or replaces input after signing fails', async () => {
const { file, cache, signer } = fixture()
signer.sign = async () => { throw Error('interrupted signing') }
await expect(cachedMacOSSignature(file, cache, signer)).rejects.toThrow('interrupted')
expect(readFileSync(file, 'utf8')).toBe('original')
expect(readdirSync(cache)).toEqual([])
})
it('rejects a concurrently changed target', async () => {
const { file, cache, signer } = fixture()
const sign = signer.sign
signer.sign = async (candidate) => { await sign(candidate); writeFileSync(file, 'concurrent edit') }
await expect(cachedMacOSSignature(file, cache, signer)).rejects.toThrow('input changed')
expect(readFileSync(file, 'utf8')).toBe('concurrent edit')
expect(readdirSync(cache)).toEqual([])
})
it.skipIf(process.platform === 'win32')('allows competing writers to publish only complete entries', async () => {
const { root, file, cache, signer } = fixture()
const second = join(root, 'other')
writeFileSync(second, 'original', { mode: 0o755 })
let ready!: () => void
const both = new Promise<void>((resolve) => { ready = resolve })
let count = 0
const sign = signer.sign
signer.sign = async (path) => { if (++count === 2) ready(); await both; await sign(path) }
await Promise.all([cachedMacOSSignature(file, cache, signer), cachedMacOSSignature(second, cache, signer)])
expect(readdirSync(cache)).toHaveLength(1)
expect(readFileSync(file, 'utf8')).toBe('original:signed')
expect(readFileSync(second, 'utf8')).toBe('original:signed')
writeFileSync(file, 'original')
expect(await cachedMacOSSignature(file, cache, signer)).toBe(true)
})
it.skipIf(process.platform === 'win32')('rejects links in the target and cache ancestry', async () => {
const { root, file, cache, signer } = fixture()
const link = join(root, 'link')
symlinkSync(file, link)
await expect(cachedMacOSSignature(link, cache, signer)).rejects.toThrow('regular file')
const real = join(root, 'real')
mkdirSync(real)
symlinkSync(real, cache)
await expect(cachedMacOSSignature(file, join(cache, 'nested'), signer)).rejects.toThrow('directory')
expect(existsSync(join(real, 'nested'))).toBe(false)
})
it.skipIf(process.platform === 'win32')('publishes reusable entries across independent processes', async () => {
const { root, file, cache } = fixture()
const second = join(root, 'second')
writeFileSync(second, 'original', { mode: 0o755 })
// Windows directory replacement uses different errors; this cache is owned by macOS packaging.
const children: ReturnType<typeof fork>[] = []
const exits: Promise<[number | null, NodeJS.Signals | null]>[] = []
try {
for (const path of [file, second]) {
const child = fork(join(import.meta.dirname, 'fixtures/macos-cache-writer.mjs'), [path, cache], {
execArgv: [], stdio: ['ignore', 'pipe', 'pipe', 'ipc'],
})
children.push(child)
exits.push(new Promise((resolve, reject) => {
child.once('error', reject)
child.once('exit', (code, signal) => { resolve([code, signal]) })
}))
}
await Promise.all(children.map((child, index) => Promise.race([once(child, 'message'), exits[index]!.then(() => { throw Error('cache writer exited before ready') })])))
for (const child of children) child.send('continue')
for (const [code, signal] of await Promise.all(exits)) {
expect(signal).toBeNull()
expect(code).toBe(0)
}
expect(readdirSync(cache)).toHaveLength(1)
expect(readFileSync(file, 'utf8')).toBe('original:signed')
expect(readFileSync(second, 'utf8')).toBe('original:signed')
} finally {
for (const child of children) if (child.exitCode === null && child.signalCode === null) child.kill()
await Promise.allSettled(exits)
}
})
it('rejects candidate mutation during verification', async () => {
const { file, cache, signer } = fixture()
signer.verify = (candidate) => { writeFileSync(candidate, 'mutated') }
await expect(cachedMacOSSignature(file, cache, signer)).rejects.toThrow('candidate changed')
expect(readFileSync(file, 'utf8')).toBe('original')
expect(readdirSync(cache)).toEqual([])
})
@@ -14,6 +14,7 @@ import {
const RELEASE_ENVIRONMENT = {
DSH_DESKTOP_APP_ID: 'com.example.desktop',
DSH_DESKTOP_MANDATORY_UPDATE_TEST_ORIGIN: 'https://policy.example.com',
DSH_DESKTOP_MANDATORY_UPDATE_CONFIG: JSON.stringify({ allowedAuthOrigins: ['https://login.example.com'] }),
DSH_DESKTOP_TARGET_PLATFORM: 'darwin',
DSH_DESKTOP_TARGET_ARCH: 'arm64',
DSH_DESKTOP_MACOS_SIGNING_IDENTITY: 'Example Company (TEAMID1234)',
@@ -97,6 +98,7 @@ describe('desktop macOS release signature', () => {
expect(() => createElectronBuilderConfig({
DSH_DESKTOP_APP_ID: RELEASE_ENVIRONMENT.DSH_DESKTOP_APP_ID,
DSH_DESKTOP_MANDATORY_UPDATE_TEST_ORIGIN: 'https://policy.example.com',
DSH_DESKTOP_MANDATORY_UPDATE_CONFIG: JSON.stringify({ allowedAuthOrigins: ['https://login.example.com'] }),
DSH_DESKTOP_TARGET_PLATFORM: 'win32',
}, 'win32')).toThrow(/DSH_DESKTOP_WINDOWS_CER_FILE/u)
})
@@ -106,6 +108,7 @@ describe('desktop macOS release signature', () => {
const config = createElectronBuilderConfig({
DSH_DESKTOP_APP_ID: RELEASE_ENVIRONMENT.DSH_DESKTOP_APP_ID,
DSH_DESKTOP_MANDATORY_UPDATE_TEST_ORIGIN: 'https://policy.example.com',
DSH_DESKTOP_MANDATORY_UPDATE_CONFIG: JSON.stringify({ allowedAuthOrigins: ['https://login.example.com'] }),
DSH_DESKTOP_TARGET_PLATFORM: 'win32',
DSH_DESKTOP_UNSIGNED: '1',
}, 'win32', 'x64')
+6 -6
View File
@@ -340,7 +340,7 @@ describe('desktop main startup', () => {
})
it('shows one explained startup login before Host readiness and joins concurrent checks without reopening it', async () => {
harness.embeddedPolicy = { origin: 'https://policy.example.com', authentication: 'feishu-test',
harness.embeddedPolicy = { origin: 'https://policy.example.com', authentication: 'feishu-test', allowedAuthOrigins: ['https://login.example.com'],
allowedPageOrigins: ['https://downloads.example.com'], intervalMs: 1000, jitter: 0 }
vi.stubGlobal('fetch', vi.fn<typeof fetch>().mockImplementation(async () =>
Response.json({ error: { code: 'UNAUTHENTICATED' } }, { status: 401 })))
@@ -383,7 +383,7 @@ describe('desktop main startup', () => {
})
it.each(['returned', 'cancelled', 'failed'] as const)('requires explicit test login and handles %s without downloading', async (outcome) => {
harness.embeddedPolicy = { origin: 'https://policy.example.com', authentication: 'feishu-test',
harness.embeddedPolicy = { origin: 'https://policy.example.com', authentication: 'feishu-test', allowedAuthOrigins: ['https://login.example.com'],
allowedPageOrigins: ['https://downloads.example.com'], intervalMs: 10_000, jitter: 0 }
const request = vi.fn<typeof fetch>().mockImplementation(async () => Response.json({ error: { code: 'UNAUTHENTICATED' } }, { status: 401 }))
vi.stubGlobal('fetch', request)
@@ -410,7 +410,7 @@ describe('desktop main startup', () => {
})
it('does not open Feishu when the user declines test login', async () => {
harness.embeddedPolicy = { origin: 'https://policy.example.com', authentication: 'feishu-test',
harness.embeddedPolicy = { origin: 'https://policy.example.com', authentication: 'feishu-test', allowedAuthOrigins: ['https://login.example.com'],
allowedPageOrigins: ['https://downloads.example.com'] }
vi.stubGlobal('fetch', vi.fn<typeof fetch>().mockImplementation(async () => Response.json({ error: { code: 'UNAUTHENTICATED' } }, { status: 401 })))
await readyForUpdate()
@@ -420,7 +420,7 @@ describe('desktop main startup', () => {
})
it('does not require gateway login to download an already available ordinary update', async () => {
harness.embeddedPolicy = { origin: 'https://policy.example.com', authentication: 'feishu-test',
harness.embeddedPolicy = { origin: 'https://policy.example.com', authentication: 'feishu-test', allowedAuthOrigins: ['https://login.example.com'],
allowedPageOrigins: ['https://downloads.example.com'] }
vi.stubGlobal('fetch', vi.fn<typeof fetch>().mockImplementation(async () =>
Response.json({ error: { code: 'UNAUTHENTICATED' } }, { status: 401 })))
@@ -433,7 +433,7 @@ describe('desktop main startup', () => {
})
it('retains the same blocking window and running Host after expired test login is cancelled', async () => {
harness.embeddedPolicy = { origin: 'https://policy.example.com', authentication: 'feishu-test',
harness.embeddedPolicy = { origin: 'https://policy.example.com', authentication: 'feishu-test', allowedAuthOrigins: ['https://login.example.com'],
allowedPageOrigins: ['https://downloads.example.com'], intervalMs: 1000, jitter: 0 }
const request = vi.fn<typeof fetch>().mockImplementation(async () =>
Response.json({ error: { code: 'UNAUTHENTICATED' } }, { status: 401 }))
@@ -937,7 +937,7 @@ describe('desktop main startup', () => {
})
it('queues policy authentication until the ordinary result dialog closes', async () => {
harness.embeddedPolicy = { origin: 'https://policy.example.com', authentication: 'feishu-test',
harness.embeddedPolicy = { origin: 'https://policy.example.com', authentication: 'feishu-test', allowedAuthOrigins: ['https://login.example.com'],
allowedPageOrigins: ['https://downloads.example.com'], intervalMs: 10_000, jitter: 0 }
const request = vi.fn<typeof fetch>()
.mockResolvedValueOnce(Response.json({ code: 0, data: { biz_code: 0, biz_data: null } }))
@@ -13,7 +13,7 @@ const instances: DesktopMandatoryUpdatePolicy[] = []
function fixture(authentication: 'anonymous' | 'feishu-test' = 'anonymous') {
const request = vi.fn<typeof fetch>().mockResolvedValue(Response.json(clear))
const publish = vi.fn<(state: DesktopPolicyState) => void>()
const policy = new DesktopMandatoryUpdatePolicy(resolveDesktopPolicyConfig({ ...deployment, authentication })!,
const policy = new DesktopMandatoryUpdatePolicy(resolveDesktopPolicyConfig({ ...deployment, authentication, ...(authentication === 'feishu-test' ? { allowedAuthOrigins: ['https://login.example.com'] } : {}) })!,
identity, publish, request)
instances.push(policy)
return { policy, request, publish }
@@ -162,6 +162,15 @@ describe('mandatory update policy', () => {
})
describe('policy deployment and page validation', () => {
it('requires validated login origins only for test authentication', () => {
expect(() => resolveDesktopPolicyConfig({ ...deployment, authentication: 'feishu-test' })).toThrow('allowedAuthOrigins')
expect(() => resolveDesktopPolicyConfig({ ...deployment, allowedAuthOrigins: ['https://login.example.com'] })).toThrow('anonymous')
expect(() => resolveDesktopPolicyConfig({ ...deployment, authentication: 'feishu-test',
allowedAuthOrigins: ['https://login.example.com/path'] })).toThrow('HTTPS origin')
expect(resolveDesktopPolicyConfig({ ...deployment, authentication: 'feishu-test',
allowedAuthOrigins: ['https://login.example.com'] })?.allowedAuthOrigins).toEqual(['https://login.example.com'])
})
it('requires explicit production origins and confines HTTP to an explicit local policy fixture', () => {
expect(resolveDesktopPolicyConfig(undefined)).toBeUndefined()
expect(() => resolveDesktopPolicyConfig({ ...deployment, origin: 'http://127.0.0.1:19001' })).toThrow('HTTPS')
@@ -0,0 +1,69 @@
import { mkdtemp, readFile, rm } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { fileURLToPath } from 'node:url'
import { expect, it, vi } from 'vitest'
const state = vi.hoisted(() => ({ root: '', directory: '' }))
vi.mock('../scripts/desktop-package-environment.mjs', () => ({
loadDesktopPackageEnvironment: () => ({ DSH_DESKTOP_WINDOWS_TOKEN_PIN: 'credential-sentinel' }),
validateDesktopPackageEnvironment: () => {},
}))
vi.mock('../scripts/macos-signing-keychain.mjs', () => ({
withMacOSSigningKeychain: async (_environment: object, action: (environment: object) => Promise<unknown>) => action({}),
}))
vi.mock('node:fs', async importOriginal => ({
...await importOriginal<typeof import('node:fs')>(),
rmSync: () => { throw new AggregateError([new Error('credential-sentinel')], 'restore:mac-proxy recovery required') },
}))
vi.mock('../scripts/packaging-run.mjs', async (importOriginal) => {
const original = await importOriginal<typeof import('../scripts/packaging-run.mjs')>()
return { ...original, createPackagingRun: (...args: Parameters<typeof original.createPackagingRun>) => {
const run = original.createPackagingRun(state.root, args[1], args[2])
state.directory = run.directory
return run
} }
})
it.each(['win32', 'darwin'] as const)('records and prints redacted parent failures on %s', async (platform) => {
state.root = await mkdtemp(join(tmpdir(), 'package-errors-'))
const savedPlatform = Object.getOwnPropertyDescriptor(process, 'platform')!
const savedArch = Object.getOwnPropertyDescriptor(process, 'arch')!
const savedArgv = process.argv
const savedExit = process.exitCode
const stderr = vi.spyOn(process.stderr, 'write').mockImplementation(() => true)
const consoleLog = vi.spyOn(console, 'log').mockImplementation(() => {})
const savedDirectory = process.env.DSH_DESKTOP_PACKAGING_RUN_DIR
try {
Object.defineProperty(process, 'platform', { ...savedPlatform, value: platform })
Object.defineProperty(process, 'arch', { ...savedArch, value: 'x64' })
process.argv = [process.execPath, fileURLToPath(new URL('../scripts/package-target.ts', import.meta.url)), platform === 'win32' ? 'win-x64' : 'mac-x64']
vi.resetModules()
await import('../scripts/package-target.ts')
expect(process.exitCode).toBe(1)
const events = await readFile(join(state.directory, 'events.jsonl'), 'utf8')
const output = stderr.mock.calls.map(([text]) => String(text)).join('')
for (const diagnostic of [events, output]) {
expect(diagnostic).toContain('restore:mac-proxy recovery required')
expect(diagnostic).toContain('[REDACTED]')
expect(diagnostic).not.toContain('credential-sentinel')
}
expect(JSON.parse(await readFile(join(state.directory, 'result.json'), 'utf8'))).toMatchObject({
success: false, stages: [
{ stage: 'configuration', success: true },
{ stage: platform === 'win32' ? 'windows-package' : 'macos-package', success: false },
],
})
expect(process.env.DSH_DESKTOP_PACKAGING_RUN_DIR).toBe(savedDirectory)
} finally {
Object.defineProperty(process, 'platform', savedPlatform)
Object.defineProperty(process, 'arch', savedArch)
process.argv = savedArgv
process.exitCode = savedExit
if (savedDirectory === undefined) delete process.env.DSH_DESKTOP_PACKAGING_RUN_DIR
else process.env.DSH_DESKTOP_PACKAGING_RUN_DIR = savedDirectory
stderr.mockRestore()
consoleLog.mockRestore()
await rm(state.root, { recursive: true, force: true })
}
})
@@ -1,6 +1,24 @@
import { writeFileSync } from 'node:fs'
import { afterEach, expect, it, vi } from 'vitest'
import { packageTarget, parseDesktopPackageInvocation } from '../scripts/package-target.ts'
import { withMacOSNotarizationProxy } from '../scripts/macos-notarization-proxy.ts'
import { packageMacOSArtifacts } from '../scripts/package-macos.ts'
import { withWindowsSigningStage } from '../scripts/windows-signing-stage.mjs'
import { prepareWindowsSignatureCacheDirectory } from '../scripts/windows-signature-cache-directory.mjs'
vi.mock('../scripts/macos-notarization-proxy.ts', () => ({
withMacOSNotarizationProxy: vi.fn(async (_proxy: string | undefined, action: () => Promise<void>) => action()),
}))
vi.mock('../scripts/notarize-macos.mjs', () => ({ notarizeMacOS: vi.fn(async () => {}) }))
vi.mock('../scripts/package-macos.ts', () => ({ packageMacOSArtifacts: vi.fn(async () => {}) }))
vi.mock('../scripts/windows-signing-stage.mjs', () => ({
withWindowsSigningStage: vi.fn(async (_options: object, operation: () => Promise<void>) => operation()),
}))
vi.mock('../scripts/windows-signature-cache-directory.mjs', () => ({
prepareWindowsSignatureCacheDirectory: vi.fn(async () => {}),
resolveWindowsSignatureCacheDirectory: vi.fn(() => 'C:\\fixture-cache'),
}))
// Keep the real orchestration and manifest reads; this suite owns no release directories or subprocesses.
vi.mock('node:fs', async importOriginal => ({
@@ -29,6 +47,8 @@ it('requires one signing preflight before building, then records only the comple
await packageTarget(parseDesktopPackageInvocation(['win-x64'], 'win32', 'x64'), environment, run)
expect(stages.slice(0, 2)).toEqual(['preflight:windows-signing', 'run build:official'])
expect(stages.filter(stage => stage === 'preflight:windows-signing')).toHaveLength(1)
expect(vi.mocked(withWindowsSigningStage).mock.calls.map(([options]) => options.stage))
.toEqual(['preflight', 'artifacts'])
expect(run.run.mock.calls[0]![3]).toMatchObject({ env: { DSH_DESKTOP_WINDOWS_TOKEN_PIN: 'fixture-pin' }, timeoutMs: 60_000 })
expect(run.run.mock.calls[1]![3].env).not.toHaveProperty('DSH_DESKTOP_WINDOWS_TOKEN_PIN')
expect(stages.indexOf('run sign:primary-runtime --dsh')).toBeGreaterThan(stages.indexOf('run prepare:dsh --defer-runtime-smoke'))
@@ -41,6 +61,16 @@ it('requires one signing preflight before building, then records only the comple
expect(writeFileSync).toHaveBeenCalledOnce()
})
it('initializes shared storage only after acquiring the preflight stage lock', async () => {
const { run } = supervisor()
vi.mocked(withWindowsSigningStage).mockImplementationOnce(async (_options, operation) => {
expect(prepareWindowsSignatureCacheDirectory).not.toHaveBeenCalled()
await operation()
expect(prepareWindowsSignatureCacheDirectory).toHaveBeenCalledOnce()
})
await packageTarget(parseDesktopPackageInvocation(['win-x64'], 'win32', 'x64'), environment, run)
})
it.each(['preflight:windows-signing', 'run build:official', 'run sign:primary-runtime', 'run prepare:dsh --defer-runtime-smoke', 'run sign:primary-runtime --dsh',
'exec tsx scripts/smoke-packaged-runtime.ts',
'exec electron-builder --config electron-builder.config.mjs --win --x64 --publish never'])
@@ -59,6 +89,46 @@ it.each(['--unsigned', '--prepare-only'])('keeps %s hardware-free and creates no
expect(stages).not.toContain('preflight:windows-signing')
expect(stages).not.toContain('run sign:primary-runtime')
expect(stages).not.toContain('run sign:primary-runtime --dsh')
expect(withWindowsSigningStage).not.toHaveBeenCalled()
for (const call of run.run.mock.calls) expect(call[3].env).not.toHaveProperty('DSH_DESKTOP_WINDOWS_TOKEN_PIN')
expect(writeFileSync).not.toHaveBeenCalled()
})
it.each([undefined, '2'])('passes macOS pack concurrency %s only to workspace packing and download routing only to download stages', async (concurrency) => {
const { run } = supervisor()
await packageTarget(parseDesktopPackageInvocation(['mac-arm64', '--prepare-only'], 'darwin', 'arm64'), {
...environment, DSH_DESKTOP_MACOS_PACK_CONCURRENCY: concurrency,
DSH_DESKTOP_MACOS_DOWNLOAD_PROXY: 'http://downloads.example:8080',
DSH_DESKTOP_MACOS_NOTARIZATION_PROXY: 'http://apple.example:8081',
}, run)
const calls = run.run.mock.calls
const packs = calls.filter(call => call[0].startsWith('run release:pack'))
expect(packs).toHaveLength(2)
for (const call of packs) expect(call[2].slice(-2)).toEqual(['--concurrency', concurrency ?? '4'])
for (const call of calls) {
expect(call[3].env.HTTP_PROXY).toBe(/^run prepare:(?:runtime|dsh)$/u.test(call[0]) ? 'http://downloads.example:8080' : undefined)
}
expect(withMacOSNotarizationProxy).not.toHaveBeenCalled()
})
it.each([false, true])('scopes the Apple proxy around notarization (directory=%s)', async (directory) => {
const { run } = supervisor()
await packageTarget(parseDesktopPackageInvocation(['mac-arm64', ...(directory ? ['--dir'] : [])], 'darwin', 'arm64'), {
...environment, APPLE_KEYCHAIN_PROFILE: 'fixture', DSH_DESKTOP_MACOS_NOTARIZATION_PROXY: 'http://apple.example:8081',
}, run)
expect(withMacOSNotarizationProxy).toHaveBeenCalledExactlyOnceWith('http://apple.example:8081', expect.any(Function), undefined, undefined, expect.any(Function))
expect(packageMacOSArtifacts).toHaveBeenCalledTimes(directory ? 0 : 1)
if (!directory) {
const signing = run.run.mock.calls.findIndex(call => call[0].includes('--config.mac.notarize=false'))
expect(signing).toBeGreaterThan(-1)
expect(run.run.mock.invocationCallOrder[signing]).toBeLessThan(vi.mocked(withMacOSNotarizationProxy).mock.invocationCallOrder[0]!)
}
})
it('does not write a release completion record when Apple proxy cleanup fails', async () => {
const { run } = supervisor()
vi.mocked(withMacOSNotarizationProxy).mockRejectedValueOnce(new Error('proxy restoration failed'))
await expect(packageTarget(parseDesktopPackageInvocation(['mac-arm64'], 'darwin', 'arm64'), environment, run))
.rejects.toThrow('proxy restoration failed')
expect(writeFileSync).not.toHaveBeenCalled()
})
+40 -1
View File
@@ -47,7 +47,20 @@ describe('packaging run records', () => {
cwd: root, env: environment,
})).rejects.toThrow('fatal failed')
const descendant = JSON.parse(await readFile(join(run.directory, 'descendant.json'), 'utf8')) as { pid: number }
expect(() => process.kill(descendant.pid, 0)).toThrow()
// Linux can retain a dead descendant as a zombie until its new parent reaps it.
await expect.poll(async () => {
try {
if (process.platform === 'linux') {
const status = await readFile(`/proc/${descendant.pid}/status`, 'utf8')
return /^State:\s+[ZXx]\b/m.test(status)
}
process.kill(descendant.pid, 0)
return false
} catch (error) {
if (['ENOENT', 'ESRCH'].includes((error as NodeJS.ErrnoException).code ?? '')) return true
throw error
}
}, { timeout: 5_000 }).toBe(true)
const events = (await readFile(join(run.directory, 'events.jsonl'), 'utf8')).trim().split('\n').map(line => JSON.parse(line) as { type: string; fatalObserved?: boolean; terminationError?: boolean })
expect(events.at(-1)).toMatchObject({ type: 'stage-end', fatalObserved: true, terminationError: false })
run.finish(false)
@@ -94,3 +107,29 @@ describe('packaging run records', () => {
} finally { await rm(root, { recursive: true, force: true }) }
})
})
it('allows parallel Mac stages, attributes their output, and refuses finish until both settle', async () => {
const root = await mkdtemp(join(tmpdir(), 'dsh-parallel-log-'))
try {
const run = createPackagingRun(root, { target: 'mac-fixture' }, { parallel: true, secrets: ['removed-p12-password'] })
const script = "process.stdout.write(process.argv[1]+' removed-p12-password')"
const first = run.run('app', process.execPath, ['-e', script, 'app'], { cwd: root, env: environment })
const second = run.run('dmg', process.execPath, ['-e', script, 'dmg'], { cwd: root, env: environment })
const settled = Promise.allSettled([first, second])
try { expect(() => { run.finish(true) }).toThrow('active run') } finally { await settled }
const results = await settled
expect(results.map(result => result.status)).toEqual(['fulfilled', 'fulfilled'])
run.finish(true)
const log = await readFile(join(run.directory, 'events.jsonl'), 'utf8')
const events = log.trim().split('\n').map(line => JSON.parse(line) as { type: string; stage: string; text?: string })
expect(events.filter(event => event.type === 'stage-start' || event.type === 'stage-end').slice(0, 2).map(event => event.type))
.toEqual(['stage-start', 'stage-start'])
expect(events.filter(event => event.type === 'output').map(event => event.stage).sort()).toEqual(['app', 'dmg'])
expect(log).not.toContain('removed-p12-password')
expect(events.filter(event => event.type === 'output').every(event => event.text?.includes('[REDACTED]'))).toBe(true)
const summary = JSON.parse(await readFile(join(run.directory, 'result.json'), 'utf8')) as { stages: unknown[]; elapsedMs: number }
expect(summary).toMatchObject({ success: true, proxy: 'not-used' })
expect(typeof summary.elapsedMs).toBe('number')
expect(summary.stages).toHaveLength(2)
} finally { await rm(root, { recursive: true, force: true }) }
})
+39
View File
@@ -0,0 +1,39 @@
import { mkdtemp, readFile, rm } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { expect, it } from 'vitest'
import { createPackagingRun, recordPackagingEvent } from '../scripts/packaging-run.mjs'
import { packagingStep } from '../scripts/packaging-step.mjs'
it('retains nested failures without credentials and includes the restored proxy in the final summary', async () => {
const root = await mkdtemp(join(tmpdir(), 'packaging-step-'))
try {
const run = createPackagingRun(root, { target: 'fixture' })
const work = packagingStep(run.directory, 'notarization', async () => {
throw new AggregateError([new Error('secret-sentinel'), new Error('outer', { cause: new Error('secret-sentinel') })], 'Apple refused')
}, ['secret-sentinel'])
await expect(work).rejects.toThrow('Apple refused')
recordPackagingEvent(run.directory, { type: 'notarization-proxy', status: 'restored' })
run.finish(false)
const events = await readFile(join(run.directory, 'events.jsonl'), 'utf8')
const summary = await readFile(join(run.directory, 'result.json'), 'utf8')
expect(events).toContain('[REDACTED]')
expect(events).toContain('outer')
expect(events).not.toContain('secret-sentinel')
expect(summary).not.toContain('secret-sentinel')
expect(JSON.parse(summary)).toMatchObject({ success: false, proxy: 'restored', stages: [{ stage: 'notarization', success: false }] })
} finally { await rm(root, { recursive: true, force: true }) }
})
it('preserves unrecorded callers and records successful return values without persisting them', async () => {
const root = await mkdtemp(join(tmpdir(), 'packaging-step-result-'))
try {
const run = createPackagingRun(root, {})
expect(await packagingStep(undefined, 'plain', async () => 42)).toBe(42)
expect(await packagingStep(run.directory, 'logged', async () => 'private-return-value')).toBe('private-return-value')
run.finish(true)
const events = await readFile(join(run.directory, 'events.jsonl'), 'utf8')
expect(events).toContain('"success":true')
expect(events).not.toContain('private-return-value')
} finally { await rm(root, { recursive: true, force: true }) }
})
+6 -6
View File
@@ -35,7 +35,7 @@ beforeEach(() => {
vi.clearAllMocks()
browserSession = makeSession(); window = makeWindow()
native.partition.mockReturnValue(browserSession); native.create.mockReturnValue(window)
auth = new DesktopPolicyTestAuth('https://policy.example.com', resolveDesktopLocale('zh'), () => undefined, record)
auth = new DesktopPolicyTestAuth('https://policy.example.com', ['https://login.example.com'], resolveDesktopLocale('zh'), () => undefined, record)
})
afterEach(async () => { await auth.dispose() })
@@ -64,7 +64,7 @@ it('opens a sandboxed window on explicit action and coalesces logins without aut
expect(window.loadURL).not.toHaveBeenCalled()
await vi.waitFor(() => { expect(window.loadURL).toHaveBeenCalledWith('https://policy.example.com/') })
expect(window.loadFile).toHaveBeenCalledTimes(1)
window.webContents.emit('did-navigate', {}, 'https://accounts.feishu.cn/open-apis/authen/v1/index?state=secret')
window.webContents.emit('did-navigate', {}, 'https://login.example.com/open-apis/authen/v1/index?state=secret')
expect(window.isDestroyed()).toBe(false)
window.webContents.emit('did-navigate', {}, 'https://policy.example.com/')
expect(await pending).toBe('returned')
@@ -121,7 +121,7 @@ it('cancels a login closed while the placeholder is still loading, without start
it.each(['will-navigate', 'will-redirect'])('refuses unapproved %s targets without logging OAuth data', async (eventName) => {
const pending = auth.login()
const event = { preventDefault: vi.fn() }
window.webContents.emit(eventName, event, 'https://accounts.feishu.cn.evil.example/?code=secret')
window.webContents.emit(eventName, event, 'https://login.example.com.evil.example/?code=secret')
expect(event.preventDefault).toHaveBeenCalledOnce()
expect(await pending).toBe('failed')
expect(record.mock.calls).toEqual([['opened'], ['failed']])
@@ -144,8 +144,8 @@ it('rejects child-frame escapes, permissions, downloads, new windows and HTTP au
expect(await pending).toBe('failed')
})
it.each(['https://open.feishu.cn/', 'https://accounts.feishu.cn/', 'https://passport.feishu.cn/',
'https://login.feishu.cn/'])('allows reviewed login documents: %s', (url) => {
it.each(['https://login.example.com/', 'https://login.example.com/', 'https://login.example.com/',
'https://login.example.com/'])('allows reviewed login documents: %s', (url) => {
const callback = vi.fn()
browserSession.webRequest.onBeforeRequest.mock.calls[0]![0]({ resourceType: 'mainFrame', url }, callback)
expect(callback).toHaveBeenCalledWith({ cancel: false })
@@ -157,7 +157,7 @@ it('keeps manual login open until close, reports cancellation once, and permits
expect(await pending).toBe('cancelled')
window = makeWindow(); native.create.mockReturnValue(window)
const retry = auth.login()
window.webContents.emit('did-fail-load', {}, -105, 'raw URL error', 'https://accounts.feishu.cn/?state=secret', true)
window.webContents.emit('did-fail-load', {}, -105, 'raw URL error', 'https://login.example.com/?state=secret', true)
expect(await retry).toBe('failed')
expect(record.mock.calls).toEqual([['opened'], ['cancelled'], ['opened'], ['failed']])
})
@@ -166,6 +166,7 @@ it.each([true, false])('validates the real builder hook for unsigned=%s', async
await writeFile(certificate, 'fixture public certificate')
const config = createElectronBuilderConfig({
DSH_DESKTOP_APP_ID: 'com.example.unpack', DSH_DESKTOP_MANDATORY_UPDATE_TEST_ORIGIN: 'https://policy.example.com',
DSH_DESKTOP_MANDATORY_UPDATE_CONFIG: JSON.stringify({ allowedAuthOrigins: ['https://login.example.com'] }),
DSH_DESKTOP_TARGET_PLATFORM: 'win32', DSH_DESKTOP_TARGET_ARCH: 'x64', DSH_DESKTOP_UNSIGNED: unsigned ? '1' : '0',
DSH_DESKTOP_WINDOWS_CER_FILE: certificate, DOWNLOAD_TEST_ORIGIN: 'https://updates.example.com',
}, 'win32', 'x64', input.source)
+2
View File
@@ -161,8 +161,10 @@ describe('Windows token signing', () => {
validateDesktopPackageEnvironment({
DSH_DESKTOP_APP_ID: 'com.example.desktop', DOWNLOAD_TEST_ORIGIN: 'https://updates.example.com',
DSH_DESKTOP_MANDATORY_UPDATE_TEST_ORIGIN: 'https://policy.example.com',
DSH_DESKTOP_MANDATORY_UPDATE_CONFIG: JSON.stringify({ allowedAuthOrigins: ['https://login.example.com'] }),
DSH_DESKTOP_WINDOWS_CER_FILE: certificateFile, DSH_DESKTOP_WINDOWS_SIGNTOOL: signTool,
DSH_DESKTOP_WINDOWS_TOKEN_PIN: 'fixture-pin', DSH_DESKTOP_WINDOWS_KEY_CONTAINER: 'fixture-container',
DSH_DESKTOP_WINDOWS_SIGNATURE_CACHE_DIR: 'C:\\fixture\\signature-cache',
}, { platform: 'win32', arch: 'x64' })
expect(execFile).not.toHaveBeenCalled()
vi.mocked(execFile).mockImplementationOnce((...args: unknown[]) => {
@@ -0,0 +1,44 @@
import { execFile } from 'node:child_process'
import { mkdtemp, rm, symlink } from 'node:fs/promises'
import { join } from 'node:path'
import { homedir } from 'node:os'
import { promisify } from 'node:util'
import { expect, it, vi } from 'vitest'
import { prepareWindowsSignatureCacheDirectory, resolveWindowsSignatureCacheDirectory } from '../scripts/windows-signature-cache-directory.mjs'
it.skipIf(process.platform !== 'win32')('resolves an account cache independently of checkout and LocalAppData virtualization', () => {
expect(resolveWindowsSignatureCacheDirectory({ LOCALAPPDATA: 'C:\\Users\\build\\AppData\\Local' }))
.toBe(join(homedir(), '.dsh-desktop-signing', 'signature-cache', 'v1'))
})
it('accepts an explicit local cache directory', () => {
expect(resolveWindowsSignatureCacheDirectory({ DSH_DESKTOP_WINDOWS_SIGNATURE_CACHE_DIR: 'D:/private-cache' }))
.toBe('D:\\private-cache')
})
it.skipIf(process.platform !== 'win32')('prepares storage when the inherited process execution policy is Restricted', async (t) => {
const root = await mkdtemp(join(import.meta.dirname, 'directory-test-'))
t.onTestFinished(() => rm(root, { recursive: true, force: true }))
vi.stubEnv('PSExecutionPolicyPreference', 'Restricted')
t.onTestFinished(() => { vi.unstubAllEnvs() })
await prepareWindowsSignatureCacheDirectory(join(root, 'private'))
expect(process.env.PSExecutionPolicyPreference).toBe('Restricted')
})
it.each(['', 'cache', 'C:cache', '\\cache', '\\\\server\\share', '\\\\?\\C:\\cache', 'C:\\cache:stream'])
('rejects unsupported cache path %j', (path) => {
expect(() => resolveWindowsSignatureCacheDirectory({ DSH_DESKTOP_WINDOWS_SIGNATURE_CACHE_DIR: path })).toThrow(/absolute local/u)
})
it.skipIf(process.platform !== 'win32')('creates private storage and rejects linked or publicly readable cache roots', async (t) => {
const root = await mkdtemp(join(import.meta.dirname, 'directory-test-'))
t.onTestFinished(() => rm(root, { recursive: true, force: true }))
const cache = join(root, 'private')
await prepareWindowsSignatureCacheDirectory(cache)
await prepareWindowsSignatureCacheDirectory(cache)
const link = join(root, 'linked')
await symlink(cache, link, 'junction')
await expect(prepareWindowsSignatureCacheDirectory(join(link, 'child'))).rejects.toThrow(/reparse/u)
await promisify(execFile)('icacls.exe', [cache, '/grant', '*S-1-1-0:(OI)(CI)R'], { windowsHide: true })
await expect(prepareWindowsSignatureCacheDirectory(cache)).rejects.toThrow(/permissions/u)
})
@@ -3,7 +3,7 @@ import { it as test, type TestContext } from 'vitest'
import assert from 'node:assert/strict'
import { mkdtemp, readFile, readdir, rm, writeFile, mkdir, symlink } from 'node:fs/promises'
import { join } from 'node:path'
import { createCachedSigner, signatureCacheIdentity } from '../scripts/windows-signature-cache.mjs'
import { createCachedSigner, maintainSignatureCache, migrateSignatureCache, signatureCacheIdentity } from '../scripts/windows-signature-cache.mjs'
async function fixture(t: TestContext) {
const root = await mkdtemp(join(import.meta.dirname, 'cache-test-'))
@@ -34,6 +34,20 @@ test('unchanged bytes restored in another file avoid another hardware call', asy
assert.equal(f.state.events.filter(e => 'type' in e && e.type === 'signature-cache-hit').length, 1)
})
test('cache summaries distinguish avoided signatures from actual signing attempts', async (t) => {
const f = await fixture(t)
const signer = createCachedSigner(f.options)
await signer(f.request)
await writeFile(f.path, 'original')
await signer(f.request)
const { verificationMs, restoreMs, signingMs, ...summary } = signer.summary()
assert.deepEqual(summary, { root: f.cache, identity: f.options.identity, hits: 1, misses: 1,
published: 1, retained: 0, signingCalls: 1, avoidedSigningCalls: 1, validationFailures: 0 })
assert(verificationMs >= 0 && restoreMs >= 0 && signingMs >= 0)
assert.equal(f.state.hardwareCalls, summary.signingCalls)
assert.equal(await readFile(f.path, 'utf8'), 'signed:original')
})
test('restores cached signatures into deeply nested dependency paths', async (t) => {
const f = await fixture(t)
await createCachedSigner(f.options)(f.request)
@@ -64,7 +78,10 @@ for (const corrupt of ['payload', 'record.json']) test(`corrupt ${corrupt} stops
const entry = (await readdir(f.cache)).find(name => !name.startsWith('.'))
assert(entry)
await writeFile(join(f.cache, entry, corrupt), 'corrupt')
await assert.rejects(createCachedSigner(f.options)(f.request))
const signer = createCachedSigner(f.options)
await assert.rejects(signer(f.request))
assert.equal(signer.summary().validationFailures, 1)
assert.equal(signer.summary().avoidedSigningCalls, 0)
assert.equal(f.state.hardwareCalls, 1)
assert.equal(await readFile(f.path, 'utf8'), 'original')
})
@@ -89,6 +106,8 @@ test('hardware failure rejects queued work without publishing an entry or retryi
assert(results.every(result => result.status === 'rejected'))
assert.equal(f.state.hardwareCalls, 1)
assert.deepEqual(await readdir(f.cache), [])
assert.equal(signer.summary().signingCalls, 1)
assert.equal(signer.summary().validationFailures, 0)
})
test('a failed new signature verification never publishes a cache entry', async (t) => {
@@ -140,6 +159,8 @@ test('two writers publish one complete entry without overwriting another writer'
createCachedSigner(options)({ ...f.request, path: second }),
])
for (const result of results) if (result.status === 'rejected') throw result.reason
assert.equal(f.state.events.filter(e => 'type' in e && e.type === 'signature-cache-published').length, 1)
assert.equal(f.state.events.filter(e => 'type' in e && e.type === 'signature-cache-retained').length, 1)
assert.equal((await readdir(f.cache)).length, 1)
await writeFile(f.path, 'original')
await createCachedSigner(f.options)(f.request)
@@ -166,3 +187,67 @@ test('a target changed during verification is never replaced with stale cache by
assert.equal(f.state.hardwareCalls, 1)
assert(!(await readdir(f.root)).some(name => name.startsWith('.signature-restore-')))
})
test('migration preserves different valid timestamp bytes at the same destination key', async (t) => {
const f = await fixture(t)
await createCachedSigner(f.options)(f.request)
const destination = join(f.root, 'shared')
await writeFile(f.path, 'original')
await createCachedSigner({ ...f.options, root: destination,
sign: async ({ path }) => writeFile(path, 'signed:original:another-timestamp'),
})(f.request)
const key = (await readdir(f.cache))[0]!
const sourceRecord = await readFile(join(f.cache, key, 'record.json'), 'utf8')
const counts = await migrateSignatureCache({ source: f.cache, root: destination, record: () => {} })
assert.deepEqual(counts, { published: 0, retained: 1, skipped: 0 })
assert.equal(await readFile(join(destination, key, 'payload'), 'utf8'), 'signed:original:another-timestamp')
assert.equal(await readFile(join(f.cache, key, 'record.json'), 'utf8'), sourceRecord)
})
test('migration copies complete entries and skips staging directories without reading them', async (t) => {
const f = await fixture(t)
await createCachedSigner(f.options)(f.request)
await mkdir(join(f.cache, '.publish-incomplete'))
const destination = join(f.root, 'shared')
assert.deepEqual(await migrateSignatureCache({ source: f.cache, root: destination, record: () => {} }),
{ published: 1, retained: 0, skipped: 1 })
await writeFile(f.path, 'original')
await createCachedSigner({ ...f.options, root: destination })(f.request)
assert.equal(f.state.hardwareCalls, 1)
assert.equal(await readFile(f.path, 'utf8'), 'signed:original')
assert.equal((await readdir(destination)).length, 1)
})
test('migration refuses a corrupt existing destination instead of replacing it', async (t) => {
const f = await fixture(t)
await createCachedSigner(f.options)(f.request)
const destination = join(f.root, 'shared')
await migrateSignatureCache({ source: f.cache, root: destination, record: () => {} })
const key = (await readdir(destination))[0]!
await writeFile(join(destination, key, 'payload'), 'corrupt')
await assert.rejects(migrateSignatureCache({ source: f.cache, root: destination, record: () => {} }), /corrupt/u)
assert.equal(await readFile(join(destination, key, 'payload'), 'utf8'), 'corrupt')
})
test('maintenance counts and clears complete entries while preserving incomplete staging', async (t) => {
const f = await fixture(t)
await createCachedSigner(f.options)(f.request)
await mkdir(join(f.cache, '.publish-incomplete'))
const usage = await maintainSignatureCache(f.cache)
assert.equal(usage.entries, 1)
assert(usage.bytes > 0)
assert.equal(usage.incomplete, 1)
assert.deepEqual(await maintainSignatureCache(f.cache, true), usage)
assert.deepEqual(await readdir(f.cache), ['.publish-incomplete'])
assert.equal(await readFile(f.path, 'utf8'), 'signed:original')
})
test('maintenance refuses unexpected entry contents without deleting them', async (t) => {
const f = await fixture(t)
await createCachedSigner(f.options)(f.request)
const key = (await readdir(f.cache))[0]!
const unexpected = join(f.cache, key, 'unrecognized')
await writeFile(unexpected, 'keep')
await assert.rejects(maintainSignatureCache(f.cache, true), /unexpected files/u)
assert.equal(await readFile(unexpected, 'utf8'), 'keep')
})
@@ -0,0 +1,134 @@
import { fork, type ChildProcess } from 'node:child_process'
import { mkdtemp, readFile, readdir, rm, writeFile } from 'node:fs/promises'
import { join } from 'node:path'
import { expect, it, type TestContext } from 'vitest'
import { withWindowsSigningStage } from '../scripts/windows-signing-stage.mjs'
const test = it.skipIf(process.platform !== 'win32')
interface StageChild {
process: ChildProcess
events: string[]
closed: Promise<{ code: number | null; signal: NodeJS.Signals | null }>
wait: (event: string) => Promise<void>
}
async function fixture(t: TestContext) {
const root = await mkdtemp(join(import.meta.dirname, 'stage-test-'))
const children: StageChild[] = []
t.onTestFinished(async () => {
for (const item of children) {
if (item.process.exitCode === null && item.process.signalCode === null) item.process.kill()
await item.closed
}
await rm(root, { recursive: true, force: true })
})
function child(input: string, mode = 'sign'): StageChild {
const process = fork(join(import.meta.dirname, 'fixtures/windows-signing-stage.mjs'), [root, input, mode], {
execArgv: [], stdio: ['ignore', 'ignore', 'pipe', 'ipc'],
})
const events: string[] = []
let stderr = ''
process.stderr!.on('data', (chunk) => { stderr += String(chunk) })
const waiters = new Map<string, () => void>()
process.on('message', (message: { type: string }) => { events.push(message.type); waiters.get(message.type)?.() })
const closed = new Promise<{ code: number | null; signal: NodeJS.Signals | null }>((resolve) => {
process.once('close', (code, signal) => { resolve({ code, signal }) })
})
const failed = new Promise<never>((_resolve, reject) => { process.once('error', reject) })
const item = { process, events, closed,
wait: (event: string) => Promise.race([
events.includes(event) ? Promise.resolve() : new Promise<void>(resolve => waiters.set(event, resolve)),
closed.then((result) => { throw new Error(`fixture exited before ${event}: ${JSON.stringify(result)} ${stderr}`) }),
failed,
]),
}
children.push(item)
return item
}
const first = join(root, 'first.node')
const second = join(root, 'second.node')
await writeFile(first, 'original')
await writeFile(second, 'original')
return { root, first, second, child }
}
test('independent signing stages wait and recheck the cache before accessing hardware', async (t) => {
const f = await fixture(t)
const first = f.child(f.first)
await first.wait('entered')
const second = f.child(f.second)
await second.wait('signing-stage-wait')
expect(second.events).not.toContain('entered')
first.process.send('release')
expect(await first.closed).toEqual({ code: 0, signal: null })
await second.wait('entered')
second.process.send('release')
expect(await second.closed).toEqual({ code: 0, signal: null })
expect(await readFile(join(f.root, 'hardware-calls'), 'utf8')).toBe('call\n')
expect(await readFile(f.second, 'utf8')).toBe('signed:original')
expect(second.events).toContain('signature-cache-hit')
})
test('an interrupted holder releases only the stage lock and retains hardware failure evidence', async (t) => {
const f = await fixture(t)
const first = f.child(f.first)
await first.wait('entered')
const evidence = join(f.root, 'state/attempt.json')
await writeFile(evidence, 'retained hardware attempt')
first.process.kill()
await first.closed
await withWindowsSigningStage({ stateDirectory: join(f.root, 'state'), stage: 'inspect', record: () => {} }, async () => {
expect(await readFile(evidence, 'utf8')).toBe('retained hardware attempt')
})
})
test('a failed stage releases its handle before another process enters', async (t) => {
const f = await fixture(t)
await expect(withWindowsSigningStage({ stateDirectory: join(f.root, 'state'), stage: 'failed', record: () => {} }, async () => {
throw new Error('stage failed')
})).rejects.toThrow('stage failed')
const next = f.child(f.first)
await next.wait('entered')
next.process.send('release')
expect(await next.closed).toEqual({ code: 0, signal: null })
})
test('accepts a state directory whose spelling differs only in Windows path case', async (t) => {
const f = await fixture(t)
let entered = false
await withWindowsSigningStage({ stateDirectory: join(f.root, 'state').toUpperCase(), stage: 'case', record: () => {} }, async () => {
entered = true
})
expect(entered).toBe(true)
})
test('a cancelled waiter never enters and does not release another process lock', async (t) => {
const f = await fixture(t)
const holder = f.child(f.first)
await holder.wait('entered')
const controller = new AbortController()
let entered = false
await expect(withWindowsSigningStage({ stateDirectory: join(f.root, 'state'), stage: 'cancelled', signal: controller.signal,
record: (event) => { if ('type' in event && event.type === 'signing-stage-wait') controller.abort() },
}, async () => { entered = true })).rejects.toThrow()
expect(entered).toBe(false)
holder.process.send('release')
expect(await holder.closed).toEqual({ code: 0, signal: null })
})
test('cache clearing waits until another process finishes signing and publishing', async (t) => {
const f = await fixture(t)
const signer = f.child(f.first)
await signer.wait('entered')
const cleaner = f.child(f.second, 'clear')
await cleaner.wait('signing-stage-wait')
expect(cleaner.events).not.toContain('entered')
signer.process.send('release')
expect(await signer.closed).toEqual({ code: 0, signal: null })
await cleaner.wait('entered')
cleaner.process.send('release')
expect(await cleaner.closed).toEqual({ code: 0, signal: null })
expect(await readdir(join(f.root, 'cache'))).toEqual([])
expect(await readFile(f.first, 'utf8')).toBe('signed:original')
})
Loaded 100 of 426 files, more files were not shown because too many files have changed in this diff. Show more