dsh-crate 0.0.0-stage → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (132) hide show
  1. package/LICENSE +27 -0
  2. package/README.md +288 -2
  3. package/README.zh.md +263 -0
  4. package/UPDATE-API-V1.md +207 -0
  5. package/assets/logo.svg +37 -0
  6. package/client/client.js +18964 -0
  7. package/cordis.patch.yml +4 -0
  8. package/lib/accelerate.js +194 -0
  9. package/lib/agents.js +67 -0
  10. package/lib/backup.js +688 -0
  11. package/lib/body-progress.js +173 -0
  12. package/lib/catalog-local-match.js +160 -0
  13. package/lib/catalog-npm.js +180 -0
  14. package/lib/changelog.js +462 -0
  15. package/lib/channels.js +64 -0
  16. package/lib/check.js +1557 -0
  17. package/lib/compatibility.js +265 -0
  18. package/lib/crate-catalog.js +179 -0
  19. package/lib/diagnostics.js +49 -0
  20. package/lib/discovery-compatibility.js +476 -0
  21. package/lib/drain-journal.js +164 -0
  22. package/lib/drain.js +1043 -0
  23. package/lib/dsh-cli.js +1373 -0
  24. package/lib/dsh-install.js +259 -0
  25. package/lib/entry-identity.js +85 -0
  26. package/lib/gist.js +369 -0
  27. package/lib/groups.js +108 -0
  28. package/lib/home-paths.js +29 -0
  29. package/lib/host-recovery.js +187 -0
  30. package/lib/hot.js +918 -0
  31. package/lib/http.js +252 -0
  32. package/lib/index.js +394 -0
  33. package/lib/install.js +1147 -0
  34. package/lib/lifecycle.js +37 -0
  35. package/lib/log-redaction.js +24 -0
  36. package/lib/log.js +204 -0
  37. package/lib/ndjson.js +154 -0
  38. package/lib/net.js +174 -0
  39. package/lib/official-desktop.js +619 -0
  40. package/lib/order.js +284 -0
  41. package/lib/patch.js +943 -0
  42. package/lib/pending-rows.js +142 -0
  43. package/lib/pending-updates.js +346 -0
  44. package/lib/pnpm-compat.js +972 -0
  45. package/lib/presets.js +282 -0
  46. package/lib/probe-context.js +20 -0
  47. package/lib/proc-text.js +69 -0
  48. package/lib/profile.js +1989 -0
  49. package/lib/recovery.js +1059 -0
  50. package/lib/region-probe.js +93 -0
  51. package/lib/regions.js +283 -0
  52. package/lib/registry.js +308 -0
  53. package/lib/release-candidates.js +115 -0
  54. package/lib/release-updates.js +70 -0
  55. package/lib/restart.js +688 -0
  56. package/lib/routes.js +7960 -0
  57. package/lib/settings.js +164 -0
  58. package/lib/shelfry-catalog.js +179 -0
  59. package/lib/snapshot.js +506 -0
  60. package/lib/source-migration.js +164 -0
  61. package/lib/sources.js +1005 -0
  62. package/lib/state.js +38 -0
  63. package/lib/store.js +163 -0
  64. package/lib/themes.js +350 -0
  65. package/lib/trial.js +125 -0
  66. package/lib/types/accelerate.d.ts +85 -0
  67. package/lib/types/agents.d.ts +52 -0
  68. package/lib/types/backup.d.ts +171 -0
  69. package/lib/types/body-progress.d.ts +94 -0
  70. package/lib/types/catalog-local-match.d.ts +39 -0
  71. package/lib/types/catalog-npm.d.ts +77 -0
  72. package/lib/types/changelog.d.ts +131 -0
  73. package/lib/types/channels.d.ts +56 -0
  74. package/lib/types/check.d.ts +381 -0
  75. package/lib/types/compatibility.d.ts +83 -0
  76. package/lib/types/crate-catalog.d.ts +48 -0
  77. package/lib/types/diagnostics.d.ts +29 -0
  78. package/lib/types/discovery-compatibility.d.ts +145 -0
  79. package/lib/types/drain-journal.d.ts +25 -0
  80. package/lib/types/drain.d.ts +306 -0
  81. package/lib/types/dsh-cli.d.ts +481 -0
  82. package/lib/types/dsh-install.d.ts +106 -0
  83. package/lib/types/entry-identity.d.ts +68 -0
  84. package/lib/types/gist.d.ts +79 -0
  85. package/lib/types/groups.d.ts +34 -0
  86. package/lib/types/home-paths.d.ts +13 -0
  87. package/lib/types/host-recovery.d.ts +95 -0
  88. package/lib/types/hot.d.ts +434 -0
  89. package/lib/types/http.d.ts +114 -0
  90. package/lib/types/index.d.ts +52 -0
  91. package/lib/types/install.d.ts +463 -0
  92. package/lib/types/lifecycle.d.ts +14 -0
  93. package/lib/types/log-redaction.d.ts +2 -0
  94. package/lib/types/log.d.ts +43 -0
  95. package/lib/types/ndjson.d.ts +52 -0
  96. package/lib/types/net.d.ts +94 -0
  97. package/lib/types/official-desktop.d.ts +59 -0
  98. package/lib/types/order.d.ts +100 -0
  99. package/lib/types/patch.d.ts +218 -0
  100. package/lib/types/pending-rows.d.ts +81 -0
  101. package/lib/types/pending-updates.d.ts +161 -0
  102. package/lib/types/pnpm-compat.d.ts +102 -0
  103. package/lib/types/presets.d.ts +94 -0
  104. package/lib/types/probe-context.d.ts +14 -0
  105. package/lib/types/proc-text.d.ts +29 -0
  106. package/lib/types/profile.d.ts +551 -0
  107. package/lib/types/recovery.d.ts +342 -0
  108. package/lib/types/region-probe.d.ts +50 -0
  109. package/lib/types/regions.d.ts +134 -0
  110. package/lib/types/registry.d.ts +160 -0
  111. package/lib/types/release-candidates.d.ts +42 -0
  112. package/lib/types/release-updates.d.ts +15 -0
  113. package/lib/types/restart.d.ts +279 -0
  114. package/lib/types/routes.d.ts +130 -0
  115. package/lib/types/settings.d.ts +112 -0
  116. package/lib/types/shelfry-catalog.d.ts +48 -0
  117. package/lib/types/snapshot.d.ts +93 -0
  118. package/lib/types/source-migration.d.ts +100 -0
  119. package/lib/types/sources.d.ts +391 -0
  120. package/lib/types/state.d.ts +20 -0
  121. package/lib/types/store.d.ts +47 -0
  122. package/lib/types/themes.d.ts +46 -0
  123. package/lib/types/trial.d.ts +61 -0
  124. package/lib/types/update-api-v1.d.ts +83 -0
  125. package/lib/types/updates.d.ts +273 -0
  126. package/lib/types/verify.d.ts +277 -0
  127. package/lib/update-api-v1.js +273 -0
  128. package/lib/updates.js +981 -0
  129. package/lib/verify.js +930 -0
  130. package/locale/en.json +5 -0
  131. package/locale/zh.json +6 -0
  132. package/package.json +113 -4
@@ -0,0 +1,160 @@
1
+ /**
2
+ * Registry access: crate 的目录(dsh-crate.json)每次请求都重新拉取。
3
+ * 这里只负责抓取、重试、校验与 304 复用;字段映射见 src/crate-catalog.ts。
4
+ */
5
+ import { type Region } from './regions.ts';
6
+ export interface RegistryPlugin {
7
+ name: string;
8
+ owner: string;
9
+ url: string;
10
+ /** One legacy category id or several category ids. */
11
+ category: string | string[];
12
+ description: Record<string, string>;
13
+ npm?: string | null;
14
+ tarball?: string | null;
15
+ stars?: number | null;
16
+ starsCheckedAt?: string | null;
17
+ /** All public Release assets in this repository, lifetime count; never npm's window. */
18
+ githubReleaseDownloads?: number | null;
19
+ githubReleaseDownloadsCheckedAt?: string | null;
20
+ /** Public package declarations at this exact pinned install tag. */
21
+ releaseManifest?: {
22
+ tarball: string;
23
+ checkedAt: string;
24
+ version: string | null;
25
+ enginesDsh: string | null;
26
+ peerDependencies: Record<string, string>;
27
+ };
28
+ /**
29
+ * npm downloads in the last 30 days, when the entry has a published
30
+ * package. `null`/absent means "no npm package" — a coverage gap, not a
31
+ * zero — so sorting must not read it as "less popular than 0".
32
+ */
33
+ downloads?: number | null;
34
+ /** Source-reported download window (YYYY-MM-DD), not lifetime totals. */
35
+ downloadsStart?: string | null;
36
+ downloadsEnd?: string | null;
37
+ /** When the source checked this statistic; never the client's fetch time. */
38
+ downloadsCheckedAt?: string | null;
39
+ /**
40
+ * npm `latest` reported by the catalog (#348). A string when known;
41
+ * `null`/absent when github-only or not yet backfilled — the UI omits the
42
+ * byline segment rather than showing a placeholder.
43
+ */
44
+ version?: string | null;
45
+ /**
46
+ * Catalog-declared storefront tile (icon). Same trust boundary as screenshots:
47
+ * the catalog is untrusted input, so the client re-validates the URL before
48
+ * creating an <img>. Absent = fall back to the owner's GitHub avatar.
49
+ */
50
+ icon?: string | null;
51
+ install: string;
52
+ added: string;
53
+ /**
54
+ * Catalog-side deprecation flags (#60): an optional extra on top of the
55
+ * core contract, absent for every normal entry — the market only consumes
56
+ * them, so a catalog without the fields behaves exactly as before.
57
+ */
58
+ deprecated?: boolean;
59
+ /** Catalog name of the suggested replacement plugin, when deprecated. */
60
+ replacement?: string;
61
+ /**
62
+ * npm package names this entry used BEFORE its current one (#1012).
63
+ *
64
+ * The catalog is the only place a rename can be stated ahead of time: the
65
+ * old name's npm metadata is gone (no dist-tags, no `deprecated` message),
66
+ * so nothing the market can fetch still knows the two names are one plugin.
67
+ * Same trust boundary as `deprecated`/`replacement` — absent for every
68
+ * normal entry, and a catalog without the field behaves exactly as before.
69
+ *
70
+ * Values are validated where they are consumed (normalized by
71
+ * {@link pluginPreviousNpm}, cross-entry rules in scripts/validate-registry.mjs):
72
+ * a former name must never be a live package in the catalog, and one former
73
+ * name may only have one successor.
74
+ */
75
+ previousNpm?: string[];
76
+ /**
77
+ * Capability disclosure (#401): what a static scan of the artifact a user
78
+ * would install reported touching — `shell`, `network`, `credentials`,
79
+ * `fs-read`, `fs-write`, `env`, `llm`, `dynamic-code`, ...
80
+ *
81
+ * Disclosure, not a verdict, and the type says so by being ABSENT when the
82
+ * entry was never scanned: `capabilities: []` means "scanned, nothing
83
+ * detected" and `undefined` means "we could not look". The two render
84
+ * differently (未检出 vs 未扫描) because they are different sentences, and
85
+ * only one of them is a statement about the plugin.
86
+ */
87
+ capabilities?: string[];
88
+ /** Combinations a reader should look at, in the scanner's own words. */
89
+ capabilityRedLines?: string[];
90
+ /** When the scan behind those fields ran (ISO 8601). */
91
+ capabilityCheckedAt?: string | null;
92
+ }
93
+ /**
94
+ * Category ids for one catalog entry, de-duplicated in declaration order.
95
+ *
96
+ * Catalog JSON is an external input, so malformed array members are omitted
97
+ * here and an entry with no usable category is rejected by `asRegistry`.
98
+ */
99
+ export declare function pluginCategories(plugin: Pick<RegistryPlugin, 'category'>): string[];
100
+ export interface Registry {
101
+ updated: string;
102
+ count: number;
103
+ categories: Record<string, Record<string, string>>;
104
+ plugins: RegistryPlugin[];
105
+ }
106
+ /**
107
+ * Former npm names for one catalog entry, normalized (#1012).
108
+ *
109
+ * Catalog JSON is external input, so a malformed declaration is dropped
110
+ * rather than trusted: only syntactically valid npm names survive, an entry
111
+ * may not list itself (its own `npm` or `name`), and duplicates collapse in
112
+ * declaration order. Cross-entry rules — a former name that is still live
113
+ * elsewhere, or two entries claiming one former name — cannot be judged per
114
+ * entry; the validator enforces them for the catalog, and
115
+ * `findCatalogRename` fails closed on ambiguity at runtime.
116
+ */
117
+ export declare function pluginPreviousNpm(plugin: Pick<RegistryPlugin, 'name' | 'npm' | 'previousNpm'>): string[];
118
+ /**
119
+ * Drop what we remember, so the next call is unconditional.
120
+ *
121
+ * Exists for tests: the memo is module state, and a spec that asserted a
122
+ * 304 would otherwise leak a validator into the next one.
123
+ */
124
+ export declare function forgetCatalog(): void;
125
+ /**
126
+ * The catalog, revalidated every time it is asked for.
127
+ *
128
+ * There used to be three answers here — live, a one-hour in-memory cache,
129
+ * and a snapshot bundled into the npm package — and only the first was
130
+ * correct. The other two were indistinguishable from it on screen, so a
131
+ * machine that could not reach the registry browsed the publish-time file
132
+ * (839 entries against 1367 live, and frozen forever for anyone on an older
133
+ * release), while a machine that COULD reach it still saw an hour-old
134
+ * listing of a catalog that grows by ~250 entries a day.
135
+ *
136
+ * For a catalog, stale is not a degraded answer, it is a wrong one: a plugin
137
+ * published this morning reads as "does not exist". So there is one source
138
+ * now, and a failure is a failure — the caller reports it and offers a
139
+ * retry, which is a state the user can act on. In particular a network
140
+ * failure is NEVER answered from `served`: an origin that cannot be reached
141
+ * has not confirmed anything, and quietly handing back the last catalog
142
+ * would rebuild exactly the fallback this replaced.
143
+ * @throws when the catalog cannot be fetched or does not look like one.
144
+ */
145
+ export declare function loadRegistry(region?: Region): Promise<Registry>;
146
+ /**
147
+ * A catalog failure with the facts needed to classify it, in the message
148
+ * itself.
149
+ *
150
+ * The market shows this string and the log export carries it, so it is the
151
+ * whole of what a bug report will contain. "The operation was aborted due to
152
+ * timeout" alone cannot distinguish a slow link from a blocked one from a
153
+ * proxy this process cannot use — and Node's `fetch` ignores HTTP_PROXY
154
+ * entirely (measured on Node 25), so a machine whose only route out is a
155
+ * proxy fails here every time while every other tool on it works.
156
+ */
157
+ export declare function describeFetchFailure(error: unknown, elapsedMs: number, attempts?: number, failures?: readonly {
158
+ source: string;
159
+ reason: string;
160
+ }[]): string;
@@ -0,0 +1,42 @@
1
+ /** Issue #991: pure, fail-closed selector for official Desktop npm stable updates. */
2
+ export interface NpmPackument {
3
+ versions?: Record<string, unknown>;
4
+ time?: Record<string, unknown>;
5
+ 'dist-tags'?: Record<string, unknown>;
6
+ }
7
+ export interface MatureUpdatePolicy {
8
+ minimumReleaseAgeMs: number;
9
+ exemptPackage?: boolean;
10
+ exemptVersions?: ReadonlySet<string>;
11
+ latestFromEndpoint?: string | null;
12
+ /** Existing compatibility dialog may request a lower stable release. */
13
+ maxVersion?: string;
14
+ }
15
+ export interface MatureUpdateSelection {
16
+ candidate: string | null;
17
+ latest: string | null;
18
+ held: string | null;
19
+ reason: 'eligible' | 'current' | 'held' | 'unknown-age' | 'inconsistent' | 'invalid-installed' | 'policy-unknown';
20
+ nextMaturityAt: number | null;
21
+ latestMaturityAt: number | null;
22
+ }
23
+ /** Accept stable SemVer, including build metadata, at both API boundaries. */
24
+ export declare function isStableReleaseVersion(value: unknown): value is string;
25
+ export declare function strictPublishTime(value: unknown): number | null;
26
+ export declare function selectMatureUpdate(packument: NpmPackument, installed: string | null, now: number, policy: MatureUpdatePolicy): MatureUpdateSelection;
27
+ /**
28
+ * Judge ONE requested version against the same wait policy selectMatureUpdate
29
+ * enforces, without selecting anything. The compatibility dialog names a
30
+ * precise version ("update to 1.7.11: it declares support for this DSH") that
31
+ * the age gate may still hold; the caller needs that fact in prose, not a 409.
32
+ * Fail-closed like its sibling: an exempt package does not make a fabricated
33
+ * or missing timestamp installable, and an unknown policy is not a pass.
34
+ */
35
+ export interface VersionMaturity {
36
+ publishedAt: number | null;
37
+ matureAt: number | null;
38
+ exempt: boolean;
39
+ mature: boolean;
40
+ policyKnown: boolean;
41
+ }
42
+ export declare function versionMaturity(packument: NpmPackument, version: string, now: number, policy: MatureUpdatePolicy): VersionMaturity;
@@ -0,0 +1,15 @@
1
+ export interface CatalogReleaseSource {
2
+ repo: string;
3
+ asset: string;
4
+ manifest: string;
5
+ }
6
+ /** Only the catalog's own floating asset opts an existing archive into updates. */
7
+ export declare function catalogReleaseSourceOf(spec: string, entry: {
8
+ url: string;
9
+ npm?: unknown;
10
+ tarball?: unknown;
11
+ }): CatalogReleaseSource | null;
12
+ export declare function publishedReleaseUpdate(source: CatalogReleaseSource, name: string): Promise<{
13
+ version: string;
14
+ target: string;
15
+ } | null>;
@@ -0,0 +1,279 @@
1
+ /**
2
+ * Self-restart: relaunch the exact DSH invocation that booted this host so
3
+ * pending (non-hot) plugin changes take effect without the user leaving the
4
+ * UI. Contributed in #14 by @ysyyhhh; ported onto the layered architecture.
5
+ *
6
+ * Safety model: the endpoint accepts only same-origin requests whose Host
7
+ * names an authority this deployment serves — a loopback authority reached
8
+ * directly (no forwarding headers), or a name the host DECLARED
9
+ * (`dsh web --trusted-host <name>`), which is how a deployment behind a
10
+ * tunnel or a reverse proxy is reached. It refuses while a plugin operation
11
+ * runs, and deployments under a supervisor (systemd/launchd/pm2) can disable
12
+ * the whole feature with `allowRestart: false` — the supervisor owns restarts.
13
+ */
14
+ import type { IncomingMessage } from 'node:http';
15
+ import type { RecoveryConfig } from './recovery.ts';
16
+ /**
17
+ * What a caller has to know to schedule a restart with a recovery surface:
18
+ * the plugin inventory and the profile paths, but NOT the port, the log
19
+ * files, or the respawn invocation — those are decided here, where the
20
+ * restart actually happens, so no caller can get them subtly wrong.
21
+ */
22
+ export type RecoveryHandoffConfig = Omit<RecoveryConfig, 'port' | 'logs' | 'spawn' | 'cwd'>;
23
+ /** @internal test hook — production callers use detectedDebugger() only. */
24
+ export declare function setDetectedDebuggerOverride(value: 'inspector' | null | undefined): void;
25
+ /**
26
+ * The process supervisor running this host, when one can be identified —
27
+ * `null` when nothing says so.
28
+ *
29
+ * This exists because the failure it prevents is the worst one the market
30
+ * can cause. Under systemd's default `KillMode=control-group`, everything in
31
+ * the unit's cgroup dies with the main process — including the detached
32
+ * helper that was supposed to bring the replacement up. So "restart" killed
33
+ * a production service and nothing came back (#229 by @SkillBase-Al: "杀死了
34
+ * 服务但是无法重复启动服务"). `allowRestart: false` was always the documented
35
+ * answer, but it is opt-in, and nothing told the operator to opt in until
36
+ * after they had already lost the service.
37
+ *
38
+ * TWO signals are required, and the second is the whole reason this function
39
+ * is not a one-line env check. `INVOCATION_ID` is INHERITED: every
40
+ * descendant of a systemd unit carries it, which on Linux includes an
41
+ * ordinary desktop terminal (its shell descends from a user-session unit)
42
+ * and a CI runner (the agent is a unit — this repo's own smoke test caught
43
+ * that). Treating inheritance as ownership would disable the button for a
44
+ * large population of hosts where it works fine, which is a worse bug than
45
+ * the one being fixed.
46
+ *
47
+ * The parent test is what distinguishes being the unit's own main process
48
+ * from merely descending from one: a terminal's node has the shell as its
49
+ * parent and a runner's has the agent. It used to be `ppid === 1`, which is
50
+ * only true for SYSTEM units. A per-user unit's service is forked by that
51
+ * user's manager instance — `systemd --user`, an ordinary PID — so user-unit
52
+ * hosts read as unsupervised, and one-click restart killed them for good
53
+ * (#471 by @automagik-genie, with the journal to prove the whole chain:
54
+ * clean SIGTERM exit → `Restart=on-failure` does not fire → `KillMode=mixed`
55
+ * SIGKILLs the detached helper before it can spawn the replacement). So the
56
+ * parent counts as a manager when it is PID 1 or its comm is `systemd` —
57
+ * the one name both manager instances share and the false-positive parents
58
+ * (shells, CI agents) never carry. `/proc` is Linux-only, which is exactly
59
+ * as wide as systemd itself; anywhere it cannot be read the answer stays
60
+ * "not a manager".
61
+ *
62
+ * Scoped to systemd on purpose. pm2 sets `pm_id`, but it is inherited the
63
+ * same way and pm2's God daemon — not PID 1 — is the parent, so there is no
64
+ * equivalent second signal; a guess there would reintroduce exactly the
65
+ * false positive this pair exists to avoid. launchd has no marker at all.
66
+ * Both still need the explicit setting: detection is a safety net over the
67
+ * documented option, never a replacement for it.
68
+ */
69
+ export declare function detectedSupervisor(env?: NodeJS.ProcessEnv, ppid?: number, parentComm?: (pid: number) => string | null): string | null;
70
+ /**
71
+ * Whether this host process is under a debugger, when one can be identified —
72
+ * `'inspector'` or `null`.
73
+ *
74
+ * Parallel to `detectedSupervisor()` (#229): a runtime latch for the restart
75
+ * route and status poll, NOT an entry in `restartAllowed()`. Folding it into
76
+ * `restartAllowed()` would write `allowRestart: false` through the settings
77
+ * page while a debug session is open, and the switch would stay off after
78
+ * the debugger detaches (#447).
79
+ *
80
+ * An explicit `allowRestart: true` does NOT override this latch either —
81
+ * unlike systemd, there is no documented deployment shape where killing a
82
+ * debug-attached host from the market UI is the right answer.
83
+ *
84
+ * Primary signal: `inspector.url()` is set (covers `--inspect` at boot,
85
+ * `inspector.open()`, and SIGUSR1 attach). Secondary: inspect-family flags
86
+ * in `execArgv` and `NODE_OPTIONS`, matched by token prefix — not a
87
+ * `/inspect/` substring, so script paths like `.../inspect-tool.js` do not
88
+ * false-positive. Includes `--inspect-wait` for Node versions that expose it
89
+ * as a distinct flag before `inspector.url()` is populated.
90
+ *
91
+ * Accepted false positive (same trade as #229 not guessing pm2): a host left
92
+ * listening on an inspector port — including `NODE_OPTIONS=--inspect` with
93
+ * nobody attached — is treated as debug-owned and gets no one-click restart.
94
+ */
95
+ export declare function detectedDebugger(inspectorUrl?: string | undefined, execArgv?: readonly string[], nodeOptions?: string): 'inspector' | null;
96
+ /**
97
+ * Self-restart is enabled by default, disabled by an explicit false — and
98
+ * disabled by DEFAULT under a detected supervisor, which owns restarts and
99
+ * whose process group would take the replacement helper down with it.
100
+ *
101
+ * An explicit `true` still wins: an operator who has configured their unit
102
+ * for it (`KillMode=process`, or a wrapper that survives) is making a
103
+ * statement about their own deployment, and this should not overrule it.
104
+ */
105
+ export declare function restartAllowed(config: {
106
+ allowRestart?: boolean;
107
+ }, env?: NodeJS.ProcessEnv, ppid?: number): boolean;
108
+ /**
109
+ * The port this process is serving on, read off the request that asked for
110
+ * the restart.
111
+ *
112
+ * The alternative is to parse it out of the launch argv, which is wrong for
113
+ * every host that binds from config or an env var. The Host header is what
114
+ * the browser actually reached us on, so it is the port the replacement has
115
+ * to take over — and it is already validated against Origin by the guard
116
+ * below before any of this runs.
117
+ * @returns the port, or null when the header carries none (a default port).
118
+ */
119
+ export declare function servingPort(request: Pick<IncomingMessage, 'headers'> & {
120
+ socket?: {
121
+ localPort?: unknown;
122
+ };
123
+ }): number | null;
124
+ /**
125
+ * Whether a restart request made from the same page as THIS request could pass
126
+ * the fence (#782): the answer the status poll reports so the banner can say
127
+ * why there is no button, instead of rendering one that always answers 403.
128
+ *
129
+ * Read off the request that asked for status, not off configuration. Behind an
130
+ * Ingress or any reverse proxy the restart POST arrives from the same page over
131
+ * the same path, so it fails for the same reasons this request shows — a proxy
132
+ * peer, forwarding headers, a non-loopback Host. It is a prediction, never a
133
+ * grant: the route still runs the full fence, including `Origin`, on the POST.
134
+ *
135
+ * A deployment that DECLARES its public name answers it truthfully now: the
136
+ * status poll sees the declared Host and reports the restart as reachable,
137
+ * exactly as the route will judge it.
138
+ */
139
+ export declare function restartReachableFrom(request: Pick<IncomingMessage, 'headers' | 'socket'>): boolean;
140
+ /**
141
+ * Whether a self-uninstall request may proceed.
142
+ *
143
+ * Same door as the restart route, plus the desktop proxy's headerless shape
144
+ * (#903): on Desktop the market's own card is the place users go to remove it,
145
+ * and the fence was refusing every such click because the proxy had stripped
146
+ * the very headers it required. Restart keeps the stricter predicate — it
147
+ * spawns a replacement host, which is not something a desktop-managed profile
148
+ * should get from here.
149
+ */
150
+ export declare function trustedSelfUninstallRequest(request: Pick<IncomingMessage, 'headers' | 'socket'>): boolean;
151
+ /**
152
+ * Whether the request that asked for status could uninstall the market (#903).
153
+ *
154
+ * The prediction, like the restart one, leaves `Origin` out: the status poll
155
+ * is a same-origin GET and carries none, so a prediction that required one
156
+ * would hide the button on every deployment that has a declared authority —
157
+ * the same shape the route accepts.
158
+ */
159
+ export declare function selfUninstallReachableFrom(request: Pick<IncomingMessage, 'headers' | 'socket'>): boolean;
160
+ /** Whether a process-control request came from this Web host on loopback. */
161
+ export declare function trustedRestartRequest(request: Pick<IncomingMessage, 'headers' | 'socket'>): boolean;
162
+ /**
163
+ * Whether a download navigation may fetch a sensitive GET export.
164
+ * Browsers do NOT send an Origin header on same-origin GET navigations
165
+ * (`<a href="/..." download>`), so unlike process-control requests a missing
166
+ * Origin is the NORMAL shape of a user-initiated download and must pass.
167
+ * Keep the rest of the posture: the Host must name an authority this
168
+ * deployment serves (loopback, or one the host declared), and — when an
169
+ * Origin IS present (fetch/CORS attempts) — it must still match Host so a
170
+ * cross-origin page cannot read the export.
171
+ */
172
+ export declare function trustedDownloadRequest(request: Pick<IncomingMessage, 'headers' | 'socket'>): boolean;
173
+ /** The exact boot invocation the detached restart helper replays. */
174
+ export declare function restartLaunch(): {
175
+ file: string;
176
+ args: string[];
177
+ cwd: string;
178
+ viaShell: boolean;
179
+ };
180
+ /**
181
+ * Platform-correct spawn invocation for the replacement host (#40 by
182
+ * @1123762794): on Windows a `detached` spawn maps to DETACHED_PROCESS — the
183
+ * new host gets NO console, and every console child it later spawns (e.g.
184
+ * DSH sandbox tool runners) pops a visible node window. Wrapping the launch
185
+ * in `powershell -WindowStyle Hidden` gives the host a HIDDEN console that
186
+ * children inherit instead. POSIX keeps the plain detached spawn.
187
+ *
188
+ * The helper that runs this invocation spawns it with `windowsHide`, because
189
+ * the helper has no console of its own to hand down and Windows would
190
+ * otherwise create a visible one for PowerShell (#624).
191
+ */
192
+ export declare function respawnInvocation(launch: {
193
+ file: string;
194
+ args: string[];
195
+ viaShell: boolean;
196
+ }, platform?: NodeJS.Platform): {
197
+ file: string;
198
+ args: string[];
199
+ viaShell: boolean;
200
+ detached: boolean;
201
+ };
202
+ /** What scheduleRestart reports back to the caller for logging/response. */
203
+ export interface RestartResult {
204
+ pid: number;
205
+ helperPid: number | undefined;
206
+ logOut: string;
207
+ logErr: string;
208
+ /** The recovery handoff, when one was written for this restart. */
209
+ recovery: {
210
+ config: string;
211
+ script: string;
212
+ } | null;
213
+ }
214
+ /**
215
+ * Where the recovery script lives beside this module.
216
+ *
217
+ * The built layout is `lib/restart.js` + `lib/recovery.js`, and the source
218
+ * layout has no runnable sibling at all (a spawned `node` cannot load a `.ts`
219
+ * file), so the answer is the built path or nothing. Nothing is a supported
220
+ * outcome, not a failure: the helper then behaves exactly as it did before the
221
+ * recovery surface existed — it notes the failure and exits — and every test
222
+ * that drives the handoff passes its own script instead of relying on a build
223
+ * having happened.
224
+ * @returns the absolute path, or null when this checkout has no built copy.
225
+ */
226
+ export declare function recoveryScriptPath(): string | null;
227
+ /**
228
+ * Source for the detached helper that outlives this process and brings the
229
+ * replacement up.
230
+ *
231
+ * Extracted so the waiting can be tested by RUNNING it, which is the only
232
+ * way this class of bug shows itself: every part of the old helper looked
233
+ * right in isolation.
234
+ *
235
+ * What it fixes (#177, reported on Windows 11, reproducible every time): the
236
+ * helper slept a flat 1500ms and spawned. The old process had exited, but
237
+ * the listening socket had not been released yet, so the replacement died
238
+ * instantly with EADDRINUSE — and the spawn was wrapped in `catch {}`, so
239
+ * nothing was written anywhere. The user saw a restart button that did
240
+ * nothing. The docstring above it even claimed the helper "waits for our
241
+ * port to free up"; it never did.
242
+ *
243
+ * So: wait for the port to actually go quiet, then start, then CHECK that
244
+ * something came up, and write a diagnosis when it did not. A restart that
245
+ * fails must leave evidence — this one is invisible by construction, since
246
+ * the process that would have logged it is the one that just exited.
247
+ * @param port - the port the replacement must bind; when unknown, the helper
248
+ * falls back to the old fixed delay, which is better than nothing.
249
+ */
250
+ export declare function restartHelperSource(spawned: {
251
+ file: string;
252
+ args: string[];
253
+ viaShell: boolean;
254
+ detached: boolean;
255
+ }, launch: {
256
+ cwd: string;
257
+ }, logs: {
258
+ out: string;
259
+ err: string;
260
+ }, port: number | null, recovery?: {
261
+ script: string;
262
+ config: string;
263
+ } | null): string;
264
+ /**
265
+ * Relaunch this exact DSH entry after a detached handoff, then stop this
266
+ * process. The helper outlives us (detached + unref), waits for our port to
267
+ * be released before starting the replacement, and logs under tmpdir.
268
+ *
269
+ * When a recovery config is supplied it is written out BEFORE the helper
270
+ * starts, because it describes the state of the world this process is about
271
+ * to leave behind: the plugin inventory as the live loader sees it, and the
272
+ * exact invocation the replacement needs. Nothing downstream could
273
+ * reconstruct either — the process that knows them is the one being replaced.
274
+ * @param port - the port this process is serving on, so the helper can wait
275
+ * for it rather than guessing at a delay.
276
+ * @param recovery - what the recovery surface needs, when the restart should
277
+ * leave one behind; omitted by callers that do not want one.
278
+ */
279
+ export declare function scheduleRestart(port?: number | null, recovery?: RecoveryHandoffConfig): RestartResult;
@@ -0,0 +1,130 @@
1
+ /**
2
+ * HTTP routes bridging the browser market UI to the host. This layer only
3
+ * parses requests, calls the service modules, and serializes responses —
4
+ * process spawning lives in dsh-cli.ts, filesystem reads in profile.ts,
5
+ * orchestration in install.ts / themes.ts / updates.ts.
6
+ *
7
+ * Security: the install route executes a shell command, so it accepts only
8
+ * same-origin POSTs and only sources present in the curated registry.
9
+ */
10
+ import type { IncomingMessage, ServerResponse } from 'node:http';
11
+ import { type PluginCommandRuntime } from './dsh-cli.ts';
12
+ import { type AgentsLookup } from './agents.ts';
13
+ import { type Channel } from './channels.ts';
14
+ import { type Region } from './regions.ts';
15
+ import { type LoaderEntry } from './themes.ts';
16
+ export type { LoaderEntry } from './themes.ts';
17
+ export type { UpdateStatus } from './updates.ts';
18
+ export interface WebServerService {
19
+ register(route: {
20
+ kind: 'exact' | 'prefix';
21
+ path: string;
22
+ handler: (request: IncomingMessage, response: ServerResponse) => void | Promise<void>;
23
+ }): () => void;
24
+ }
25
+ export interface MarketHost {
26
+ webServer: WebServerService;
27
+ loader: {
28
+ entries(): Iterable<LoaderEntry>;
29
+ };
30
+ plugin(plugin: unknown, config: unknown): {
31
+ await(): Promise<unknown>;
32
+ dispose(): Promise<unknown> | void;
33
+ };
34
+ on?(event: string, callback: (payload: unknown) => void): () => void;
35
+ logger?: {
36
+ info?(message: string): void;
37
+ warn(message: string): void;
38
+ };
39
+ }
40
+ /**
41
+ * A host that owns activation for the whole composition.
42
+ *
43
+ * Some hosts watch the profile and replay it the moment the manifest lands
44
+ * (measured against a bun-hmr watcher), which makes the market's own hot
45
+ * mount a SECOND loader entry for an id the live composition already serves:
46
+ * duplicate prefix routes, and a "restart required" verdict for a plugin that
47
+ * is already up. Where the host publishes this bridge, the market asks it to
48
+ * replay and reports what it answers, instead of mounting on its own.
49
+ *
50
+ * Optional by construction: absent on every host without the capability, and
51
+ * named with `pluginActivation?` so a host that only knows `current` keeps
52
+ * working unchanged.
53
+ */
54
+ export interface HostPluginActivation {
55
+ activate(): Promise<{
56
+ ok: true;
57
+ } | {
58
+ ok: false;
59
+ error: string;
60
+ }>;
61
+ }
62
+ export interface MarketConfig {
63
+ /** Profile the market installs into; matches the profile serving this UI. */
64
+ profile: string;
65
+ /** Host-authoritative profile directory; ordinary DSH derives it from DSH_HOME. */
66
+ profileDirectory?: string;
67
+ /** Installation-owned bundles live beside this host, outside the Desktop profile. */
68
+ dshInstallDir?: string;
69
+ /**
70
+ * Whether a DSH Desktop shell serves this process — the shell owns the
71
+ * window and the process lifecycle, which is what the capability bits mean
72
+ * by "desktop".
73
+ *
74
+ * Kept separate from `profileDirectory` on purpose: since #639 the dsh
75
+ * launcher hands every profile its own directory, so an explicit directory
76
+ * no longer tells a desktop shell apart from an ordinary `dsh` run.
77
+ */
78
+ desktopHost?: boolean;
79
+ /**
80
+ * How long to wait for the host's own replay of a fresh install before
81
+ * hot-mounting it (#814). A desktop shell that watches the profile replays
82
+ * the composition itself, about two seconds after the manifest lands; one
83
+ * that does not publish `pluginActivation` gives the market no way to ask,
84
+ * and mounting first made the host's replay fail as a duplicate. Unset,
85
+ * the wait follows the host's own profile watcher instead (#827).
86
+ */
87
+ hostReplayWaitMs?: number;
88
+ /** Detached self-restart is unsafe under systemd/launchd/pm2; operators can disable it (#14). */
89
+ allowRestart?: boolean;
90
+ /** Which release channel the market offers ITSELF from; other plugins never follow it. */
91
+ channel?: Channel;
92
+ /** Which mirrors every outbound request uses; undefined until decided. */
93
+ region?: Region;
94
+ /** Snapshots retained per profile (issue #98); defaults to DEFAULT_MAX_SNAPSHOTS. */
95
+ maxSnapshots?: number;
96
+ /**
97
+ * Environment variables pinned for plugin build/install commands (issue
98
+ * #336): the compiler (CC/CXX) or anything else a native build reads, for
99
+ * hosts whose dsh process cannot inherit a shell environment. These may
100
+ * override values the parent process inherited, but never the PATH or CI
101
+ * the market computes for its children.
102
+ */
103
+ buildEnv?: Record<string, string>;
104
+ /**
105
+ * Where `profile` came from, for the exported log (#744). Not used for any
106
+ * decision: it exists because "why did the market think this was the web
107
+ * profile" stalled an investigation for want of exactly this line.
108
+ */
109
+ origin?: {
110
+ /** Which source named the profile. */
111
+ profileSource: string;
112
+ /** The launcher's `profileContext` as the market saw it at start. */
113
+ launcherAtStart: string;
114
+ /**
115
+ * The same, read again now. Absent at start but present later means the
116
+ * service arrived after the market mounted (timing); absent both times
117
+ * means the market cannot see it at all (scope) — the two causes need
118
+ * different fixes, and only a live read tells them apart.
119
+ */
120
+ launcherNow: () => string;
121
+ };
122
+ }
123
+ export declare function marketVersion(): string;
124
+ /**
125
+ * Register the market's HTTP routes.
126
+ * @param host - Acquired webServer + shell services.
127
+ * @param config - Validated market configuration.
128
+ * @returns Disposer removing every registered route.
129
+ */
130
+ export declare function mountMarketRoutes(host: MarketHost, config: MarketConfig, commandRuntime?: PluginCommandRuntime, agentsLookup?: AgentsLookup, hostActivation?: HostPluginActivation): () => void;