dshmarket 1.73.23 → 1.73.25

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.
package/README.md CHANGED
@@ -118,7 +118,7 @@ Installs prefer repo-verified npm packages, then author-supplied prebuilt GitHub
118
118
  - Installs are restricted to sources listed in the curated [awesome-dsh-plugin](https://awesome-dsh-plugin.com) registry — anything else is rejected
119
119
  - Build scripts stay blocked by default (pnpm ≥10); allowing one is your explicit per-package choice
120
120
  - Terminal/CLI-surface plugins are flagged before you install them into the web profile
121
- - The install endpoint accepts same-origin POST only; the market never phones home
121
+ - The install endpoint accepts same-origin POST only; one anonymous count a day, no personal information, can be turned off in Settings (details in SECURITY.md)
122
122
  - Backups can contain credentials from your profile config — the UI warns before export and upload; WebDAV sync is https-only, refuses private-network targets, and never stores your password in the browser
123
123
  - Authenticated Gist requests always go directly to `api.github.com`; bearer tokens are never sent to a public GitHub acceleration service. GitHub source archives also stay on canonical codeload URLs so pnpm's integrity policy remains in force
124
124
  - The restart endpoint additionally requires a direct loopback client (forwarded requests are rejected) and relaunches the exact DSH entry, arguments, environment, and working directory
package/README.zh.md CHANGED
@@ -108,7 +108,7 @@ profile,因此不会出现在桌面端。请通过应用内的 **设置 →
108
108
  - 只允许安装 [awesome-dsh-plugin](https://awesome-dsh-plugin.com) 精选列表内的来源,其它一律拒绝
109
109
  - 构建脚本默认禁止执行(pnpm ≥10),放行与否由你按包显式决定
110
110
  - 终端/命令行类插件装进网页版前会被明确提醒
111
- - 安装接口只接受同源 POST;市场不会向任何地方上报数据
111
+ - 安装接口只接受同源 POST;每天一次匿名计数,不含任何个人信息,可在设置里关闭(详见 SECURITY.md)
112
112
  - 备份可能包含 profile 配置里的密钥——导出与上传前 UI 会明确提醒;WebDAV 同步仅限 https、拒绝内网地址,且密码永不落盘浏览器
113
113
  - 带鉴权的 Gist 请求始终直连 `api.github.com`,Bearer token 不会交给公共 GitHub 加速服务;GitHub 源码归档也保持 canonical codeload URL,以保留 pnpm 的完整性校验边界
114
114
  - 重启接口还要求客户端直接来自环回地址(拒绝代理转发请求),并使用原入口、参数、环境和工作目录重新启动 DSH
package/client/client.js CHANGED
@@ -224,6 +224,7 @@ window.__ModuleLoader__.load({ id: "dshmarket", factory: (require) => {
224
224
  setSelfUpdateWaiting: "新版等待中",
225
225
  setSelfUpdateHint: "更新会下载新版本,重启后生效。",
226
226
  setSelfUpToDateHint: "",
227
+ setSelfChangedHint: "上次检查后有插件被安装或移除。请打开「插件市场 → 已安装 → 更新检查」,点「立即检查」刷新结果。",
227
228
  setSelfHostManagedHint: "这份市场由桌面端安装,新版本请在桌面端更新。",
228
229
  setSelfUpdate: "更新",
229
230
  setSelfUpdatedHint: "已下载完成。重启 DeepSeek Harness 后新版本才会生效——页面会先显示新版本号。",
@@ -255,6 +256,10 @@ window.__ModuleLoader__.load({ id: "dshmarket", factory: (require) => {
255
256
  setRegionGlobalHint: "从 npm 和 GitHub 官方源下载。",
256
257
  setRegionChinaHint: "中国大陆访问更快。仅改变下载线路,插件来源不变。",
257
258
  setRegionAuto: "已根据网络状况自动选择,可随时切换。",
259
+ setCount: "匿名使用统计",
260
+ setCountHint: "每天一次匿名计数,不含任何个人信息,可随时关闭。只发送:随机安装编号、市场版本、DSH 版本、桌面端或网页端、下载区域,以及当天有没有打开过市场。",
261
+ setCountOn: "开启",
262
+ setCountOff: "关闭",
258
263
  setGithubProxy: "GitHub 加速",
259
264
  setGithubProxyAutoHint: "自动选择可用线路,失败时才切换。",
260
265
  setGithubProxyCustom: "自定义",
@@ -1108,6 +1113,7 @@ window.__ModuleLoader__.load({ id: "dshmarket", factory: (require) => {
1108
1113
  setSelfUpdateWaiting: "New version pending",
1109
1114
  setSelfUpdateHint: "Updating downloads the new version; it takes effect after a restart.",
1110
1115
  setSelfUpToDateHint: "",
1116
+ setSelfChangedHint: "A plugin was installed or removed after the last check. Open Plugin Market → Installed → Update checks and select Check now to refresh the results.",
1111
1117
  setSelfHostManagedHint: "This copy was installed by the desktop app; update it from there.",
1112
1118
  setSelfUpdate: "Update",
1113
1119
  setSelfUpdatedHint: "Downloaded. Restart DeepSeek Harness for it to take effect — the page will already show the new version.",
@@ -1139,6 +1145,10 @@ window.__ModuleLoader__.load({ id: "dshmarket", factory: (require) => {
1139
1145
  setRegionGlobalHint: "Downloads directly from npm and GitHub.",
1140
1146
  setRegionChinaHint: "Faster in mainland China. Changes the download route, not the source.",
1141
1147
  setRegionAuto: "Selected from a network check. Change it anytime.",
1148
+ setCount: "Anonymous usage count",
1149
+ setCountHint: "One anonymous count a day, no personal information, can be turned off anytime. It sends only: a random install ID, market version, DSH version, desktop or web, download region, and whether you opened the market that day.",
1150
+ setCountOn: "On",
1151
+ setCountOff: "Off",
1142
1152
  setGithubProxy: "GitHub acceleration",
1143
1153
  setGithubProxyAutoHint: "Chooses a working route automatically and switches only after a failure.",
1144
1154
  setGithubProxyCustom: "Custom",
@@ -1991,6 +2001,7 @@ window.__ModuleLoader__.load({ id: "dshmarket", factory: (require) => {
1991
2001
  setSelfUpdateWaiting: "新バージョン(更新待ち)",
1992
2002
  setSelfUpdateHint: "更新すると新しいバージョンをダウンロードし、再起動後に有効になります。",
1993
2003
  setSelfUpToDateHint: "",
2004
+ setSelfChangedHint: "前回の確認後にプラグインが追加または削除されました。「プラグインマーケット → インストール済み → 更新の確認」で「今すぐ確認」を選択してください。",
1994
2005
  setSelfHostManagedHint: "このマーケットはデスクトップアプリがインストールしたものです。新しいバージョンへの更新はデスクトップアプリで行ってください。",
1995
2006
  setSelfUpdate: "更新",
1996
2007
  setSelfUpdatedHint: "ダウンロードが完了しました。新しいバージョンは DeepSeek Harness を再起動すると有効になります。ページには先に新しいバージョン番号が表示されます。",
@@ -2022,6 +2033,10 @@ window.__ModuleLoader__.load({ id: "dshmarket", factory: (require) => {
2022
2033
  setRegionGlobalHint: "npm と GitHub の公式ソースからダウンロードします。",
2023
2034
  setRegionChinaHint: "中国本土ではより高速です。ダウンロード経路が変わるだけで、プラグインの入手元は変わりません。",
2024
2035
  setRegionAuto: "ネットワーク状況から自動で選択済みです。いつでも切り替えできます。",
2036
+ setCount: "匿名の利用カウント",
2037
+ setCountHint: "1日1回の匿名カウントです。個人情報は含まれず、いつでもオフにできます。送るのは、ランダムなインストール ID、マーケットのバージョン、DSH のバージョン、デスクトップかウェブか、ダウンロード地域、その日にマーケットを開いたかどうかだけです。",
2038
+ setCountOn: "オン",
2039
+ setCountOff: "オフ",
2025
2040
  setGithubProxy: "GitHub 高速化",
2026
2041
  setGithubProxyAutoHint: "使える経路を自動で選び、失敗したときだけ切り替えます。",
2027
2042
  setGithubProxyCustom: "カスタム",
@@ -21253,7 +21268,22 @@ window.__ModuleLoader__.load({ id: "dshmarket", factory: (require) => {
21253
21268
  * /dsh-market/* host routes, with install/update/uninstall flows and the
21254
21269
  * pending-restart bookkeeping in sessionStorage.
21255
21270
  */
21271
+ /**
21272
+ * Tell the Node side the page was opened. The server keeps the first one of
21273
+ * each UTC day for the anonymous count and drops the rest; this only avoids
21274
+ * repeating the call within a day, so a window left open overnight still
21275
+ * reports the next time the page is shown. A failure changes nothing the user
21276
+ * can see.
21277
+ */
21278
+ let openedReportedOn = "";
21279
+ function reportOpened() {
21280
+ const day = (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
21281
+ if (openedReportedOn === day) return;
21282
+ openedReportedOn = day;
21283
+ fetch(api("/dsh-market/telemetry/opened"), { method: "POST" }).catch(() => {});
21284
+ }
21256
21285
  function MarketSection(props) {
21286
+ (0, react.useEffect)(reportOpened, []);
21257
21287
  const c1 = useMarketState({ props });
21258
21288
  const c2 = useMarketSync({
21259
21289
  props,
@@ -21647,7 +21677,8 @@ window.__ModuleLoader__.load({ id: "dshmarket", factory: (require) => {
21647
21677
  githubProxyManaged: body.githubProxyManaged === true,
21648
21678
  selfManaged: body.selfManaged !== false,
21649
21679
  selfUninstallReachable: body.selfUninstallReachable !== false,
21650
- buildEnv: body.buildEnv ?? {}
21680
+ buildEnv: body.buildEnv ?? {},
21681
+ anonymousCount: typeof body.anonymousCount === "boolean" ? body.anonymousCount : null
21651
21682
  };
21652
21683
  }
21653
21684
  /** Render the effective build environment as one `KEY=value` line each. */
@@ -21776,7 +21807,8 @@ window.__ModuleLoader__.load({ id: "dshmarket", factory: (require) => {
21776
21807
  githubProxyManaged: false,
21777
21808
  selfManaged: true,
21778
21809
  selfUninstallReachable: true,
21779
- buildEnv: {}
21810
+ buildEnv: {},
21811
+ anonymousCount: null
21780
21812
  });
21781
21813
  }
21782
21814
  try {
@@ -21929,6 +21961,25 @@ window.__ModuleLoader__.load({ id: "dshmarket", factory: (require) => {
21929
21961
  }
21930
21962
  })();
21931
21963
  }, [post, t]);
21964
+ /** Turn the anonymous daily count on or off; shows what the server saved. */
21965
+ const onCount = (0, react.useCallback)((next) => {
21966
+ setError(null);
21967
+ (async () => {
21968
+ try {
21969
+ const body = await post(api("/dsh-market/telemetry"), { enabled: next });
21970
+ if (body.ok !== true) {
21971
+ setError(body.error ?? t("setSelfFailed"));
21972
+ return;
21973
+ }
21974
+ setStatus((current) => current === null ? current : {
21975
+ ...current,
21976
+ anonymousCount: body.enabled ?? next
21977
+ });
21978
+ } catch (cause) {
21979
+ setError(cause instanceof Error ? cause.message : String(cause));
21980
+ }
21981
+ })();
21982
+ }, [post, t]);
21932
21983
  /** Save or clear the single user-facing GitHub escape route. */
21933
21984
  const onGithubProxy = (0, react.useCallback)((proxy) => {
21934
21985
  setError(null);
@@ -22072,7 +22123,7 @@ window.__ModuleLoader__.load({ id: "dshmarket", factory: (require) => {
22072
22123
  const offeredVersion = update?.eligibleVersion ?? update?.latest ?? null;
22073
22124
  const held = update?.heldUpdate;
22074
22125
  const heldVersionText = held != null && typeof held.latest === "string" && held.latest !== "" && (update?.updateAvailable !== true || held.latest !== offeredVersion) ? marketHeldVersionText(held, activeLocale, t) : null;
22075
- const body = phase === "removed" ? row(t("setSelfRemoved"), t("setSelfRemovedHint"), null) : (0, react.createElement)(react.Fragment, null, advanced, row(t("setIndexSource"), t("setIndexSourceHint"), null), status?.selfManaged === true ? row((update?.updateAvailable === true || update?.hostManaged === true) && offeredVersion !== null ? `${t("setSelfUpdateReady")} ${offeredVersion}` : update?.channelSwitch != null ? `${t("setChannelSwitch")} ${update.channelSwitch}` : checkFailed ? t("updateChecksFailed") : pluginListChanged ? t("updateChecksChanged") : update?.profileBlocked != null || heldVersionText !== null ? t("setSelfUpdateWaiting") : update === null ? t("updateChecksPending") : t("setSelfUpToDate"), phase === "updated" ? t("setSelfUpdatedHint") : update?.channelSwitch != null ? t("setChannelSwitchHint") : update?.updateAvailable === true ? [t("setSelfUpdateHint"), heldVersionText].filter(Boolean).join(" · ") : update?.hostManaged === true && update.latest !== null ? t("setSelfHostManagedHint") : checkFailed ? t("updateChecksFailedHint") : pluginListChanged ? t("updateChecksChangedHint") : update?.profileBlocked != null ? profileBlockedText(update.profileBlocked, t) : heldVersionText ?? t("setSelfUpToDateHint"), phase === "updated" ? null : update?.updateAvailable === true ? (0, react.createElement)(_deepseek_ai_dsh_client_ui_primitives.Button, {
22126
+ const body = phase === "removed" ? row(t("setSelfRemoved"), t("setSelfRemovedHint"), null) : (0, react.createElement)(react.Fragment, null, advanced, row(t("setIndexSource"), t("setIndexSourceHint"), null), status?.selfManaged === true ? row((update?.updateAvailable === true || update?.hostManaged === true) && offeredVersion !== null ? `${t("setSelfUpdateReady")} ${offeredVersion}` : update?.channelSwitch != null ? `${t("setChannelSwitch")} ${update.channelSwitch}` : checkFailed ? t("updateChecksFailed") : pluginListChanged ? t("updateChecksChanged") : update?.profileBlocked != null || heldVersionText !== null ? t("setSelfUpdateWaiting") : update === null ? t("updateChecksPending") : t("setSelfUpToDate"), phase === "updated" ? t("setSelfUpdatedHint") : update?.channelSwitch != null ? t("setChannelSwitchHint") : update?.updateAvailable === true ? [t("setSelfUpdateHint"), heldVersionText].filter(Boolean).join(" · ") : update?.hostManaged === true && update.latest !== null ? t("setSelfHostManagedHint") : checkFailed ? t("updateChecksFailedHint") : pluginListChanged ? t("setSelfChangedHint") : update?.profileBlocked != null ? profileBlockedText(update.profileBlocked, t) : heldVersionText ?? t("setSelfUpToDateHint"), phase === "updated" ? null : update?.updateAvailable === true ? (0, react.createElement)(_deepseek_ai_dsh_client_ui_primitives.Button, {
22076
22127
  variant: "primary",
22077
22128
  size: "sm",
22078
22129
  disabled: busy,
@@ -22112,7 +22163,16 @@ window.__ModuleLoader__.load({ id: "dshmarket", factory: (require) => {
22112
22163
  onClick: () => {
22113
22164
  onRegion(id);
22114
22165
  }
22115
- }, t(REGION_LABEL[id]))))), row(t("setGithubProxy"), status?.githubProxyManaged === true ? t("setGithubProxyManagedHint") : status?.githubProxyCustom !== null && status?.githubProxyCustom !== void 0 ? t("setGithubProxyCustomHint") : t("setGithubProxyAutoHint"), status?.githubProxyManaged === true ? null : status?.githubProxyCustom !== null && status?.githubProxyCustom !== void 0 ? (0, react.createElement)("div", { className: Market_module_css_default.setInlineActions }, (0, react.createElement)(_deepseek_ai_dsh_client_ui_primitives.Button, {
22166
+ }, t(REGION_LABEL[id]))))), status?.anonymousCount !== null && status?.anonymousCount !== void 0 ? row(t("setCount"), t("setCountHint"), (0, react.createElement)("div", { className: Market_module_css_default.setSeg }, [true, false].map((value) => (0, react.createElement)("button", {
22167
+ key: String(value),
22168
+ type: "button",
22169
+ className: status.anonymousCount === value ? `${Market_module_css_default.setSegBtn} ${Market_module_css_default.setSegOn}` : Market_module_css_default.setSegBtn,
22170
+ disabled: busy,
22171
+ "aria-pressed": status.anonymousCount === value,
22172
+ onClick: () => {
22173
+ if (status.anonymousCount !== value) onCount(value);
22174
+ }
22175
+ }, t(value ? "setCountOn" : "setCountOff"))))) : null, row(t("setGithubProxy"), status?.githubProxyManaged === true ? t("setGithubProxyManagedHint") : status?.githubProxyCustom !== null && status?.githubProxyCustom !== void 0 ? t("setGithubProxyCustomHint") : t("setGithubProxyAutoHint"), status?.githubProxyManaged === true ? null : status?.githubProxyCustom !== null && status?.githubProxyCustom !== void 0 ? (0, react.createElement)("div", { className: Market_module_css_default.setInlineActions }, (0, react.createElement)(_deepseek_ai_dsh_client_ui_primitives.Button, {
22116
22176
  variant: "outline",
22117
22177
  size: "sm",
22118
22178
  disabled: proxySaving,
package/lib/routes.js CHANGED
@@ -58,6 +58,7 @@ import { DEFAULT_UPDATE_CHECK_INTERVAL_HOURS, isUpdateCheckIntervalHours } from
58
58
  import { createThemeManager } from './themes.js';
59
59
  import { readJsonBody, refuseUnadmitted, sameOrigin, sendJson } from './http.js';
60
60
  import { resolveDshHome } from './home-paths.js';
61
+ import { readTelemetryState, sendOpened, setTelemetryEnabled, startHeartbeat } from './telemetry.js';
61
62
  import { clearWebdavSecret, readWebdavSecret, webdavSecretFor, writeWebdavSecret } from './webdav-secret.js';
62
63
  import { detectedDebugger, detectedSupervisor, restartAllowed, scheduleRestart, servingPort, trustedRestartRequest, trustedDownloadRequest, trustedSelfUninstallRequest, selfUninstallReachableFrom, restartReachableFrom } from './restart.js';
63
64
  import { activationAfterReplace, brokenClientBundles, bundlePatchIsEmpty, checkClientBundle, defaultHostRuntimeFacts, findUnservedConfigNamespaces, hasHostHalf, hostPeerGate, isDeclaredLibraryDsh, newlyBrokenBundles, peerGateRemedy, verifyActivation } from './verify.js';
@@ -3127,7 +3128,65 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
3127
3128
  },
3128
3129
  });
3129
3130
  };
3131
+ const telemetryOptions = {
3132
+ version: marketVersion(),
3133
+ hostVersion: () => dshHostInfo()?.version ?? null,
3134
+ kind: () => (config.desktopHost === true ? 'desktop' : 'web'),
3135
+ region: () => region,
3136
+ };
3130
3137
  const disposers = [
3138
+ // The market page was opened. The page says so once per load; the count
3139
+ // keeps the first one of each UTC day and ignores the rest. Answered at
3140
+ // once: the page never waits on a network round trip for a count.
3141
+ registerRoute({
3142
+ kind: 'exact',
3143
+ path: '/dsh-market/telemetry/opened',
3144
+ handler: async (request, response) => {
3145
+ if (request.method !== 'POST') {
3146
+ response.writeHead(405, { allow: 'POST' });
3147
+ response.end();
3148
+ return;
3149
+ }
3150
+ if (!sameOrigin(request)) {
3151
+ sendJson(response, 403, { error: 'untrusted origin' });
3152
+ return;
3153
+ }
3154
+ void sendOpened(telemetryOptions);
3155
+ response.writeHead(204);
3156
+ response.end();
3157
+ },
3158
+ }),
3159
+ registerRoute({
3160
+ kind: 'exact',
3161
+ path: '/dsh-market/telemetry',
3162
+ handler: async (request, response) => {
3163
+ if (request.method === 'GET') {
3164
+ sendJson(response, 200, { enabled: readTelemetryState().enabled });
3165
+ return;
3166
+ }
3167
+ if (request.method !== 'POST') {
3168
+ response.writeHead(405, { allow: 'GET, POST' });
3169
+ response.end();
3170
+ return;
3171
+ }
3172
+ if (!sameOrigin(request)) {
3173
+ sendJson(response, 403, { error: 'untrusted origin' });
3174
+ return;
3175
+ }
3176
+ try {
3177
+ const body = await readJsonBody(request);
3178
+ if (body === null || typeof body !== 'object' || typeof body.enabled !== 'boolean') {
3179
+ sendJson(response, 400, { error: 'enabled must be a boolean' });
3180
+ return;
3181
+ }
3182
+ setTelemetryEnabled(body.enabled);
3183
+ sendJson(response, 200, { ok: true, enabled: body.enabled });
3184
+ }
3185
+ catch {
3186
+ sendJson(response, 400, { error: '没能保存这个设置,请再试一次。 / Could not save this setting. Try again.' });
3187
+ }
3188
+ },
3189
+ }),
3131
3190
  registerRoute({
3132
3191
  kind: 'exact',
3133
3192
  path: '/dsh-market/update-notifications',
@@ -5174,6 +5233,7 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
5174
5233
  channels: CHANNELS,
5175
5234
  region,
5176
5235
  regions: REGIONS,
5236
+ anonymousCount: readTelemetryState().enabled,
5177
5237
  // The padded/PATH- and CI-safe build environment currently pinned
5178
5238
  // (issue #336): composition plus any card-saved override. The card
5179
5239
  // edits exactly what this reports, so the form never shows a stale
@@ -9012,8 +9072,10 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
9012
9072
  })),
9013
9073
  ];
9014
9074
  startCheckoutRepair();
9075
+ const stopHeartbeat = startHeartbeat(telemetryOptions);
9015
9076
  return async () => {
9016
9077
  disposed = true;
9078
+ stopHeartbeat();
9017
9079
  checkoutRepairRound = undefined;
9018
9080
  if (checkoutRepairTimer !== undefined)
9019
9081
  clearTimeout(checkoutRepairTimer);
@@ -0,0 +1,125 @@
1
+ import { randomBytes } from 'node:crypto';
2
+ import { mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
3
+ import { dirname, join } from 'node:path';
4
+ import { resolveDshHome } from './home-paths.js';
5
+ import { logEvent } from './log.js';
6
+ import { marketFetch } from './net.js';
7
+ /**
8
+ * The anonymous daily count.
9
+ *
10
+ * One POST per install per UTC day, from the Node side only, carrying five
11
+ * fields (see `Ping`). On a day the user opens the market page, a second POST
12
+ * carries the same five plus `opened: true` — the only thing it adds is that
13
+ * the page was opened, never what was done there. It is on by default and off
14
+ * with one switch in the settings card or with an environment variable.
15
+ * Everything about it is best effort: a failure changes nothing for the user
16
+ * and is never an error.
17
+ */
18
+ export const TELEMETRY_URL = 'https://t.dshmarket.com/v1/ping';
19
+ const TIMEOUT_MS = 10_000;
20
+ const START_DELAY_MS = 30_000;
21
+ const RECHECK_MS = 6 * 60 * 60 * 1000;
22
+ export function telemetryFile(home = resolveDshHome()) {
23
+ return join(home, 'dsh-market', 'telemetry.json');
24
+ }
25
+ export function readTelemetryState(file = telemetryFile()) {
26
+ try {
27
+ const value = JSON.parse(readFileSync(file, 'utf8'));
28
+ return {
29
+ ...(typeof value.id === 'string' && /^[0-9a-f]{32}$/.test(value.id) ? { id: value.id } : {}),
30
+ ...(typeof value.lastDay === 'string' ? { lastDay: value.lastDay } : {}),
31
+ ...(typeof value.lastOpenDay === 'string' ? { lastOpenDay: value.lastOpenDay } : {}),
32
+ enabled: value.enabled !== false,
33
+ };
34
+ }
35
+ catch {
36
+ return { enabled: true };
37
+ }
38
+ }
39
+ function writeState(state, file) {
40
+ mkdirSync(dirname(file), { recursive: true });
41
+ const temp = `${file}.${process.pid}.tmp`;
42
+ writeFileSync(temp, JSON.stringify(state));
43
+ renameSync(temp, file);
44
+ }
45
+ /** Turn the count on or off. Keeps the rest of the file; deletes nothing else. */
46
+ export function setTelemetryEnabled(enabled, file = telemetryFile()) {
47
+ writeState({ ...readTelemetryState(file), enabled }, file);
48
+ }
49
+ const utcDay = (now) => new Date(now).toISOString().slice(0, 10);
50
+ /** Why nothing may be sent right now, or null. Explicit opt-outs always win. */
51
+ export function suppressedBy(env) {
52
+ if (env.DSH_MARKET_TELEMETRY === '0')
53
+ return 'DSH_MARKET_TELEMETRY=0';
54
+ if (env.DO_NOT_TRACK === '1')
55
+ return 'DO_NOT_TRACK=1';
56
+ // Tests and CI never count, unless a test points the URL at its own server.
57
+ const overridden = (env.DSH_MARKET_TELEMETRY_URL ?? '') !== '';
58
+ if (!overridden && env.CI !== undefined && env.CI !== '' && env.CI !== '0' && env.CI !== 'false')
59
+ return 'CI';
60
+ if (!overridden && (env.VITEST !== undefined || env.NODE_ENV === 'test'))
61
+ return 'test run';
62
+ return null;
63
+ }
64
+ async function send(options, opened) {
65
+ try {
66
+ const env = options.env ?? process.env;
67
+ const file = options.file ?? telemetryFile();
68
+ if (suppressedBy(env) !== null)
69
+ return 'skipped';
70
+ const state = readTelemetryState(file);
71
+ if (!state.enabled)
72
+ return 'skipped';
73
+ const day = utcDay((options.now ?? Date.now)());
74
+ if ((opened ? state.lastOpenDay : state.lastDay) === day)
75
+ return 'skipped';
76
+ const id = state.id ?? randomBytes(16).toString('hex');
77
+ const ping = {
78
+ id, v: options.version, hv: options.hostVersion(), kind: options.kind(), region: options.region(),
79
+ ...(opened ? { opened: true } : {}),
80
+ };
81
+ const response = await (options.fetch ?? marketFetch)(env.DSH_MARKET_TELEMETRY_URL || TELEMETRY_URL, {
82
+ method: 'POST',
83
+ headers: { 'content-type': 'application/json' },
84
+ body: JSON.stringify(ping),
85
+ signal: AbortSignal.timeout(TIMEOUT_MS),
86
+ });
87
+ if (response.status < 200 || response.status > 299)
88
+ return 'failed';
89
+ // Re-read: the user may have turned it off while the request was in flight.
90
+ // An open also counts as today's heartbeat: the server row is the same.
91
+ writeState({ ...readTelemetryState(file), id, lastDay: day, ...(opened ? { lastOpenDay: day } : {}) }, file);
92
+ return 'sent';
93
+ }
94
+ catch (error) {
95
+ logEvent('info', 'telemetry', `not sent: ${error instanceof Error ? error.message : 'unknown'}`);
96
+ return 'failed';
97
+ }
98
+ }
99
+ /** Send today's count if it is due. Never throws. */
100
+ export function sendHeartbeat(options) {
101
+ return send(options, false);
102
+ }
103
+ /** Note that the market page was opened today, if that has not been sent yet. Never throws. */
104
+ export function sendOpened(options) {
105
+ return send(options, true);
106
+ }
107
+ /** Start the schedule: first check after a short delay, then every ~6 hours. */
108
+ export function startHeartbeat(options, delayMs = START_DELAY_MS, everyMs = RECHECK_MS) {
109
+ let stopped = false;
110
+ let timer;
111
+ const tick = () => {
112
+ if (stopped)
113
+ return;
114
+ void sendHeartbeat(options).finally(() => {
115
+ if (stopped)
116
+ return;
117
+ timer = setTimeout(tick, everyMs);
118
+ timer.unref?.();
119
+ });
120
+ };
121
+ timer = setTimeout(tick, delayMs);
122
+ timer.unref?.();
123
+ return () => { stopped = true; if (timer !== undefined)
124
+ clearTimeout(timer); };
125
+ }
@@ -89,6 +89,7 @@ export declare function configuredProxy(): string | null;
89
89
  export declare function marketFetch(url: string, init?: {
90
90
  signal?: AbortSignal;
91
91
  headers?: Record<string, string>;
92
- method?: 'GET' | 'HEAD';
92
+ method?: 'GET' | 'HEAD' | 'POST';
93
+ body?: string;
93
94
  redirect?: 'follow' | 'manual';
94
95
  }): Promise<Response>;
@@ -0,0 +1,52 @@
1
+ import { marketFetch } from './net.ts';
2
+ /**
3
+ * The anonymous daily count.
4
+ *
5
+ * One POST per install per UTC day, from the Node side only, carrying five
6
+ * fields (see `Ping`). On a day the user opens the market page, a second POST
7
+ * carries the same five plus `opened: true` — the only thing it adds is that
8
+ * the page was opened, never what was done there. It is on by default and off
9
+ * with one switch in the settings card or with an environment variable.
10
+ * Everything about it is best effort: a failure changes nothing for the user
11
+ * and is never an error.
12
+ */
13
+ export declare const TELEMETRY_URL = "https://t.dshmarket.com/v1/ping";
14
+ /** The whole payload. Adding a field here is a privacy change: update SECURITY.md. */
15
+ export interface Ping {
16
+ id: string;
17
+ v: string;
18
+ hv: string | null;
19
+ kind: 'desktop' | 'web';
20
+ region: string;
21
+ /** Present (and true) only on the day's first open of the market page. */
22
+ opened?: true;
23
+ }
24
+ interface TelemetryState {
25
+ id?: string;
26
+ lastDay?: string;
27
+ lastOpenDay?: string;
28
+ enabled: boolean;
29
+ }
30
+ export declare function telemetryFile(home?: string): string;
31
+ export declare function readTelemetryState(file?: string): TelemetryState;
32
+ /** Turn the count on or off. Keeps the rest of the file; deletes nothing else. */
33
+ export declare function setTelemetryEnabled(enabled: boolean, file?: string): void;
34
+ /** Why nothing may be sent right now, or null. Explicit opt-outs always win. */
35
+ export declare function suppressedBy(env: Record<string, string | undefined>): string | null;
36
+ export interface HeartbeatOptions {
37
+ version: string;
38
+ hostVersion: () => string | null;
39
+ kind: () => 'desktop' | 'web';
40
+ region: () => string;
41
+ file?: string;
42
+ env?: Record<string, string | undefined>;
43
+ now?: () => number;
44
+ fetch?: typeof marketFetch;
45
+ }
46
+ /** Send today's count if it is due. Never throws. */
47
+ export declare function sendHeartbeat(options: HeartbeatOptions): Promise<'sent' | 'skipped' | 'failed'>;
48
+ /** Note that the market page was opened today, if that has not been sent yet. Never throws. */
49
+ export declare function sendOpened(options: HeartbeatOptions): Promise<'sent' | 'skipped' | 'failed'>;
50
+ /** Start the schedule: first check after a short delay, then every ~6 hours. */
51
+ export declare function startHeartbeat(options: HeartbeatOptions, delayMs?: number, everyMs?: number): () => void;
52
+ export {};
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "dshmarket",
3
3
  "description": "Visual plugin market inside DeepSeek Harness — browse, search, and one-click install community plugins. · DSH 可视化插件市场:逛一逛,点一下,装好。",
4
- "version": "1.73.23",
4
+ "version": "1.73.25",
5
5
  "icon": "assets/logo.svg",
6
6
  "type": "module",
7
7
  "main": "lib/index.js",