Surf Studio commited on
Commit
1402637
·
1 Parent(s): 7e409fc

数据库搬到 HF:内嵌 Postgres + 加密快照到私有数据集;线上是唯一写入方,工作室只读镜像并保活

Browse files
README.md CHANGED
@@ -49,6 +49,14 @@ X Cookie、Telegram 登录、企业微信地址都保存在数据库里,可以
49
 
50
  Telegram 若被限流(FLOOD_WAIT)会自动暂停读取;赠链接口被限流会自动冷却 10 分钟;企业微信只在出现有效赠链时推送,且每个赠链只推一次(多个实例并发也不会重复推送)。
51
 
 
 
 
 
 
 
 
 
52
  ## 密钥自动同步
53
 
54
  工作室(开发环境)的 Surf 密钥是会自动轮换的会话密钥,线上 Space 里的副本会过期。工作室每 2 小时检查一次:一旦密钥变化就自动更新到 Space 的 Secret 并重启 Space,避免线上出现「invalid session key / 数据加载失败」。若要彻底免维护,可在 Surf 平台申请长期密钥后直接写入 Space 的 `SURF_API_KEY`。
 
49
 
50
  Telegram 若被限流(FLOOD_WAIT)会自动暂停读取;赠链接口被限流会自动冷却 10 分钟;企业微信只在出现有效赠链时推送,且每个赠链只推一次(多个实例并发也不会重复推送)。
51
 
52
+ ## 数据库(HF 自带,不依赖平台)
53
+
54
+ 数据存放在应用进程内的 Postgres(PGlite)里,并加密快照到私有数据集 `Ethscriptions/cut-data`:
55
+
56
+ - 线上 Space 是**唯一写入方**:每 5 分钟把变化加密后提交一次快照(密钥在 Space Secret `SNAPSHOT_KEY`)。
57
+ - 容器重建时自动从快照恢复(Telegram 会话、X cookie、通知记录都在里面),所以重启不会丢数据、也不用重新登录。
58
+ - 工作室预览只做只读镜像:每 5 分钟拉一次快照,并给线上发一次保活请求(避免 HF 让 Space 休眠导致定时任务停摆)。
59
+
60
  ## 密钥自动同步
61
 
62
  工作室(开发环境)的 Surf 密钥是会自动轮换的会话密钥,线上 Space 里的副本会过期。工作室每 2 小时检查一次:一旦密钥变化就自动更新到 Space 的 Secret 并重启 Space,避免线上出现「invalid session key / 数据加载失败」。若要彻底免维护,可在 Surf 平台申请长期密钥后直接写入 Space 的 `SURF_API_KEY`。
bun.lock CHANGED
@@ -5,6 +5,8 @@
5
  "": {
6
  "name": "backend",
7
  "dependencies": {
 
 
8
  "@surf-ai/sdk": "1.0.5",
9
  "express": "4.22.1",
10
  "telegram": "^2.26.22",
@@ -16,6 +18,8 @@
16
 
17
  "@drizzle-team/brocli": ["@drizzle-team/brocli@0.10.2", "", {}, "sha512-z33Il7l5dKjUgGULTqBsQBQwckHh5AbIuxhdsIxDDiZAzBOrZO6q9ogcWC65kU382AfynTfgNumVcNIjuIua6w=="],
18
 
 
 
19
  "@esbuild-kit/core-utils": ["@esbuild-kit/core-utils@3.3.2", "", { "dependencies": { "esbuild": "~0.18.20", "source-map-support": "^0.5.21" } }, "sha512-sPRAnw9CdSsRmEtnsl2WXWdyquogVpB3yZ3dgwJfe8zrOzTsV7cJvmwrKVa+0ma5BoiGJ+BoqkMvawbayKUsqQ=="],
20
 
21
  "@esbuild-kit/esm-loader": ["@esbuild-kit/esm-loader@2.6.5", "", { "dependencies": { "@esbuild-kit/core-utils": "^3.3.2", "get-tsconfig": "^4.7.0" } }, "sha512-FxEMIkJKnodyA1OaCUoEvbYRkoZlLZ4d/eXFu9Fh8CbBBgP5EmZxrfTRyN0qpXZ4vOvqnE5YdRdcrmUUXuU+dA=="],
@@ -72,10 +76,20 @@
72
 
73
  "@esbuild/win32-x64": ["@esbuild/win32-x64@0.25.12", "", { "os": "win32", "cpu": "x64" }, "sha512-alJC0uCZpTFrSL0CCDjcgleBXPnCrEAhTBILpeAp7M/OFgoqtAetfBzX0xM00MUsVVPpVjlPuMbREqnZCXaTnA=="],
74
 
 
 
 
 
 
 
 
 
75
  "@surf-ai/sdk": ["@surf-ai/sdk@1.0.5", "", { "dependencies": { "cors": "^2.8.5", "croner": "^9.0.0", "drizzle-kit": "^0.31.0", "drizzle-orm": "^0.44.0", "express": "^4.22.0" } }, "sha512-SrvlVyfQdRn1H9GnkvBpLhQUdxF7tgSGIsXMne81slB6YohdhiG7QzNCQy6EmSwv1Ugq4vwVunaQeDf7KUL+RQ=="],
76
 
77
  "accepts": ["accepts@1.3.8", "", { "dependencies": { "mime-types": "~2.1.34", "negotiator": "0.6.3" } }, "sha512-PYAthTa2m2VKxuvSD3DPC/Gy+U+sOA1LAuT8mkmRuvw+NACSaeXEQ+NHcVF7rONl6qcaxV3Uuemwawk+7+SJLw=="],
78
 
 
 
79
  "array-flatten": ["array-flatten@1.1.1", "", {}, "sha512-PCVAQswWemu6UdxsDFFX/+gVeYqKAod3D3UVm91jHwynguOwAvYPhx8nNlM++NqRcK6CxxpUafjmhIdKiHibqg=="],
80
 
81
  "async-mutex": ["async-mutex@0.3.2", "", { "dependencies": { "tslib": "^2.3.1" } }, "sha512-HuTK7E7MT7jZEh1P9GtRW9+aTWiDWWi9InbZ5hjxrnRa39KS4BW04+xLBhYNS2aXhHUIKZSw3gj4Pn1pj+qGAA=="],
@@ -98,6 +112,8 @@
98
 
99
  "call-bound": ["call-bound@1.0.4", "", { "dependencies": { "call-bind-apply-helpers": "^1.0.2", "get-intrinsic": "^1.3.0" } }, "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg=="],
100
 
 
 
101
  "content-disposition": ["content-disposition@0.5.4", "", { "dependencies": { "safe-buffer": "5.2.1" } }, "sha512-FveZTNuGw04cxlAiWbzi6zTAL/lhehaWbTtgluJh4/E95DqMwTmha3KZN1aAWA8cFIhHzMZUvLevkw5Rqk+tSQ=="],
102
 
103
  "content-type": ["content-type@1.0.5", "", {}, "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA=="],
@@ -134,6 +150,8 @@
134
 
135
  "ee-first": ["ee-first@1.1.1", "", {}, "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow=="],
136
 
 
 
137
  "encodeurl": ["encodeurl@2.0.0", "", {}, "sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg=="],
138
 
139
  "entities": ["entities@2.2.0", "", {}, "sha512-p92if5Nz619I0w+akJrLZH0MX0Pb5DX39XOwQTtXSdQQOaYH03S1uIQp4mhOZtAXrxq4ViO67YTiLBo2638o9A=="],
@@ -174,6 +192,8 @@
174
 
175
  "function-bind": ["function-bind@1.1.2", "", {}, "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA=="],
176
 
 
 
177
  "get-intrinsic": ["get-intrinsic@1.3.0", "", { "dependencies": { "call-bind-apply-helpers": "^1.0.2", "es-define-property": "^1.0.1", "es-errors": "^1.3.0", "es-object-atoms": "^1.1.1", "function-bind": "^1.1.2", "get-proto": "^1.0.1", "gopd": "^1.2.0", "has-symbols": "^1.1.0", "hasown": "^2.0.2", "math-intrinsics": "^1.1.0" } }, "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ=="],
178
 
179
  "get-proto": ["get-proto@1.0.1", "", { "dependencies": { "dunder-proto": "^1.0.1", "es-object-atoms": "^1.0.0" } }, "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g=="],
@@ -204,6 +224,8 @@
204
 
205
  "ipaddr.js": ["ipaddr.js@1.9.1", "", {}, "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g=="],
206
 
 
 
207
  "is-typedarray": ["is-typedarray@1.0.0", "", {}, "sha512-cyA56iCMHAh5CdzjJIa4aohJyeO1YbwLi3Jc35MmRU6poroFjIGZzUzupGiRPOjgHg9TLu43xbpwXk523fMxKA=="],
208
 
209
  "math-intrinsics": ["math-intrinsics@1.1.0", "", {}, "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g=="],
@@ -288,6 +310,10 @@
288
 
289
  "store2": ["store2@2.14.4", "", {}, "sha512-srTItn1GOvyvOycgxjAnPA63FZNwy0PTyUBFMHRM+hVFltAeoh0LmNBz9SZqUS9mMqGk8rfyWyXn3GH5ReJ8Zw=="],
290
 
 
 
 
 
291
  "telegram": ["telegram@2.26.22", "", { "dependencies": { "@cryptography/aes": "^0.1.1", "async-mutex": "^0.3.0", "big-integer": "^1.6.48", "buffer": "^6.0.3", "htmlparser2": "^6.1.0", "mime": "^3.0.0", "node-localstorage": "^2.2.1", "pako": "^2.0.3", "path-browserify": "^1.0.1", "real-cancellable-promise": "^1.1.1", "socks": "^2.6.2", "store2": "^2.13.0", "ts-custom-error": "^3.2.0", "websocket": "^1.0.34" }, "optionalDependencies": { "bufferutil": "^4.0.3", "utf-8-validate": "^5.0.5" } }, "sha512-EIj7Yrjiu0Yosa3FZ/7EyPg9s6UiTi/zDQrFmR/2Mg7pIUU+XjAit1n1u9OU9h2oRnRM5M+67/fxzQluZpaJJg=="],
292
 
293
  "toidentifier": ["toidentifier@1.0.1", "", {}, "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA=="],
 
5
  "": {
6
  "name": "backend",
7
  "dependencies": {
8
+ "@electric-sql/pglite": "^0.5.14",
9
+ "@huggingface/hub": "^2.17.10",
10
  "@surf-ai/sdk": "1.0.5",
11
  "express": "4.22.1",
12
  "telegram": "^2.26.22",
 
18
 
19
  "@drizzle-team/brocli": ["@drizzle-team/brocli@0.10.2", "", {}, "sha512-z33Il7l5dKjUgGULTqBsQBQwckHh5AbIuxhdsIxDDiZAzBOrZO6q9ogcWC65kU382AfynTfgNumVcNIjuIua6w=="],
20
 
21
+ "@electric-sql/pglite": ["@electric-sql/pglite@0.5.14", "", {}, "sha512-aAQe7iArcFB2w1xtx91l3l9trxhMzD6aZf+WnosSHNhwgp70EJz80Igw/bHnW14fUEFYWPBoQ1sGom8Xc0Jttg=="],
22
+
23
  "@esbuild-kit/core-utils": ["@esbuild-kit/core-utils@3.3.2", "", { "dependencies": { "esbuild": "~0.18.20", "source-map-support": "^0.5.21" } }, "sha512-sPRAnw9CdSsRmEtnsl2WXWdyquogVpB3yZ3dgwJfe8zrOzTsV7cJvmwrKVa+0ma5BoiGJ+BoqkMvawbayKUsqQ=="],
24
 
25
  "@esbuild-kit/esm-loader": ["@esbuild-kit/esm-loader@2.6.5", "", { "dependencies": { "@esbuild-kit/core-utils": "^3.3.2", "get-tsconfig": "^4.7.0" } }, "sha512-FxEMIkJKnodyA1OaCUoEvbYRkoZlLZ4d/eXFu9Fh8CbBBgP5EmZxrfTRyN0qpXZ4vOvqnE5YdRdcrmUUXuU+dA=="],
 
76
 
77
  "@esbuild/win32-x64": ["@esbuild/win32-x64@0.25.12", "", { "os": "win32", "cpu": "x64" }, "sha512-alJC0uCZpTFrSL0CCDjcgleBXPnCrEAhTBILpeAp7M/OFgoqtAetfBzX0xM00MUsVVPpVjlPuMbREqnZCXaTnA=="],
78
 
79
+ "@huggingface/blake3-jit": ["@huggingface/blake3-jit@0.0.2", "", {}, "sha512-Bq7B5qabyjrJfhBsl85Jd2QBtf+HzRD7h7A9GfN2lzrrsABhOa5evVPgzoCTxR7Ub0QFj7YDK1YkYRWBU25+2w=="],
80
+
81
+ "@huggingface/hub": ["@huggingface/hub@2.17.10", "", { "dependencies": { "@huggingface/tasks": "^0.22.1", "@huggingface/xetchunk-wasm": "^0.2.0" }, "optionalDependencies": { "cli-progress": "^3.12.0" }, "bin": { "hfjs": "dist/cli.js" } }, "sha512-+2W2KKBMEMmfgFEgaWknCytsCQlyQ9Xpghv9BN5qOqkjb0l5f6mVhXBNyAVOmt/Gjny4I3Cb1ZKaUv28+0+17A=="],
82
+
83
+ "@huggingface/tasks": ["@huggingface/tasks@0.22.2", "", {}, "sha512-m+LqKsOQPlG3UYolaQo9q154VlCV9cE26GL2bdqkhNVOeeeQYCzqZG7C9JvVl6+rwgupvmFIFxPrkTDbFp8U9w=="],
84
+
85
+ "@huggingface/xetchunk-wasm": ["@huggingface/xetchunk-wasm@0.2.0", "", { "dependencies": { "@huggingface/blake3-jit": "0.0.2", "gearhash-jit": "1.0.2" } }, "sha512-cmp7oAAWeCpZGrVQTP/LxDtJdzGMfpxwkEVsZsk5jZQ2FwP2njm8LnyobhnQvLpkSAcJJwUzFJC0PYS9ZsqeTg=="],
86
+
87
  "@surf-ai/sdk": ["@surf-ai/sdk@1.0.5", "", { "dependencies": { "cors": "^2.8.5", "croner": "^9.0.0", "drizzle-kit": "^0.31.0", "drizzle-orm": "^0.44.0", "express": "^4.22.0" } }, "sha512-SrvlVyfQdRn1H9GnkvBpLhQUdxF7tgSGIsXMne81slB6YohdhiG7QzNCQy6EmSwv1Ugq4vwVunaQeDf7KUL+RQ=="],
88
 
89
  "accepts": ["accepts@1.3.8", "", { "dependencies": { "mime-types": "~2.1.34", "negotiator": "0.6.3" } }, "sha512-PYAthTa2m2VKxuvSD3DPC/Gy+U+sOA1LAuT8mkmRuvw+NACSaeXEQ+NHcVF7rONl6qcaxV3Uuemwawk+7+SJLw=="],
90
 
91
+ "ansi-regex": ["ansi-regex@5.0.1", "", {}, "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ=="],
92
+
93
  "array-flatten": ["array-flatten@1.1.1", "", {}, "sha512-PCVAQswWemu6UdxsDFFX/+gVeYqKAod3D3UVm91jHwynguOwAvYPhx8nNlM++NqRcK6CxxpUafjmhIdKiHibqg=="],
94
 
95
  "async-mutex": ["async-mutex@0.3.2", "", { "dependencies": { "tslib": "^2.3.1" } }, "sha512-HuTK7E7MT7jZEh1P9GtRW9+aTWiDWWi9InbZ5hjxrnRa39KS4BW04+xLBhYNS2aXhHUIKZSw3gj4Pn1pj+qGAA=="],
 
112
 
113
  "call-bound": ["call-bound@1.0.4", "", { "dependencies": { "call-bind-apply-helpers": "^1.0.2", "get-intrinsic": "^1.3.0" } }, "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg=="],
114
 
115
+ "cli-progress": ["cli-progress@3.12.0", "", { "dependencies": { "string-width": "^4.2.3" } }, "sha512-tRkV3HJ1ASwm19THiiLIXLO7Im7wlTuKnvkYaTkyoAPefqjNg7W7DHKUlGRxy9vxDvbyCYQkQozvptuMkGCg8A=="],
116
+
117
  "content-disposition": ["content-disposition@0.5.4", "", { "dependencies": { "safe-buffer": "5.2.1" } }, "sha512-FveZTNuGw04cxlAiWbzi6zTAL/lhehaWbTtgluJh4/E95DqMwTmha3KZN1aAWA8cFIhHzMZUvLevkw5Rqk+tSQ=="],
118
 
119
  "content-type": ["content-type@1.0.5", "", {}, "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA=="],
 
150
 
151
  "ee-first": ["ee-first@1.1.1", "", {}, "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow=="],
152
 
153
+ "emoji-regex": ["emoji-regex@8.0.0", "", {}, "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A=="],
154
+
155
  "encodeurl": ["encodeurl@2.0.0", "", {}, "sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg=="],
156
 
157
  "entities": ["entities@2.2.0", "", {}, "sha512-p92if5Nz619I0w+akJrLZH0MX0Pb5DX39XOwQTtXSdQQOaYH03S1uIQp4mhOZtAXrxq4ViO67YTiLBo2638o9A=="],
 
192
 
193
  "function-bind": ["function-bind@1.1.2", "", {}, "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA=="],
194
 
195
+ "gearhash-jit": ["gearhash-jit@1.0.2", "", {}, "sha512-UhzJL4KXSdqAKepy/tZwmi2Rcy0YMmtiC4DQS4SURCuIWdh8ECZtnXK2ePRMLigfB61hRKdLK/Vgg2bSw73izQ=="],
196
+
197
  "get-intrinsic": ["get-intrinsic@1.3.0", "", { "dependencies": { "call-bind-apply-helpers": "^1.0.2", "es-define-property": "^1.0.1", "es-errors": "^1.3.0", "es-object-atoms": "^1.1.1", "function-bind": "^1.1.2", "get-proto": "^1.0.1", "gopd": "^1.2.0", "has-symbols": "^1.1.0", "hasown": "^2.0.2", "math-intrinsics": "^1.1.0" } }, "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ=="],
198
 
199
  "get-proto": ["get-proto@1.0.1", "", { "dependencies": { "dunder-proto": "^1.0.1", "es-object-atoms": "^1.0.0" } }, "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g=="],
 
224
 
225
  "ipaddr.js": ["ipaddr.js@1.9.1", "", {}, "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g=="],
226
 
227
+ "is-fullwidth-code-point": ["is-fullwidth-code-point@3.0.0", "", {}, "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg=="],
228
+
229
  "is-typedarray": ["is-typedarray@1.0.0", "", {}, "sha512-cyA56iCMHAh5CdzjJIa4aohJyeO1YbwLi3Jc35MmRU6poroFjIGZzUzupGiRPOjgHg9TLu43xbpwXk523fMxKA=="],
230
 
231
  "math-intrinsics": ["math-intrinsics@1.1.0", "", {}, "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g=="],
 
310
 
311
  "store2": ["store2@2.14.4", "", {}, "sha512-srTItn1GOvyvOycgxjAnPA63FZNwy0PTyUBFMHRM+hVFltAeoh0LmNBz9SZqUS9mMqGk8rfyWyXn3GH5ReJ8Zw=="],
312
 
313
+ "string-width": ["string-width@4.2.3", "", { "dependencies": { "emoji-regex": "^8.0.0", "is-fullwidth-code-point": "^3.0.0", "strip-ansi": "^6.0.1" } }, "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g=="],
314
+
315
+ "strip-ansi": ["strip-ansi@6.0.1", "", { "dependencies": { "ansi-regex": "^5.0.1" } }, "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A=="],
316
+
317
  "telegram": ["telegram@2.26.22", "", { "dependencies": { "@cryptography/aes": "^0.1.1", "async-mutex": "^0.3.0", "big-integer": "^1.6.48", "buffer": "^6.0.3", "htmlparser2": "^6.1.0", "mime": "^3.0.0", "node-localstorage": "^2.2.1", "pako": "^2.0.3", "path-browserify": "^1.0.1", "real-cancellable-promise": "^1.1.1", "socks": "^2.6.2", "store2": "^2.13.0", "ts-custom-error": "^3.2.0", "websocket": "^1.0.34" }, "optionalDependencies": { "bufferutil": "^4.0.3", "utf-8-validate": "^5.0.5" } }, "sha512-EIj7Yrjiu0Yosa3FZ/7EyPg9s6UiTi/zDQrFmR/2Mg7pIUU+XjAit1n1u9OU9h2oRnRM5M+67/fxzQluZpaJJg=="],
318
 
319
  "toidentifier": ["toidentifier@1.0.1", "", {}, "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA=="],
cron.json CHANGED
@@ -5,7 +5,8 @@
5
  "schedule": "*/5 * * * *",
6
  "handler": "cron/mystery-fast.js",
7
  "enabled": true,
8
- "timeout": 120
 
9
  },
10
  {
11
  "id": "mystery-tracker-quick",
@@ -13,7 +14,8 @@
13
  "schedule": "*/15 * * * *",
14
  "handler": "cron/mystery-quick.js",
15
  "enabled": true,
16
- "timeout": 240
 
17
  },
18
  {
19
  "id": "mystery-tracker-refresh",
@@ -21,7 +23,8 @@
21
  "schedule": "0 */6 * * *",
22
  "handler": "cron/mystery-refresh.js",
23
  "enabled": true,
24
- "timeout": 280
 
25
  },
26
  {
27
  "id": "hf-key-sync",
@@ -30,5 +33,13 @@
30
  "handler": "cron/hf-key-sync.js",
31
  "enabled": true,
32
  "timeout": 90
 
 
 
 
 
 
 
 
33
  }
34
  ]
 
5
  "schedule": "*/5 * * * *",
6
  "handler": "cron/mystery-fast.js",
7
  "enabled": true,
8
+ "timeout": 120,
9
+ "studioOnly": false
10
  },
11
  {
12
  "id": "mystery-tracker-quick",
 
14
  "schedule": "*/15 * * * *",
15
  "handler": "cron/mystery-quick.js",
16
  "enabled": true,
17
+ "timeout": 240,
18
+ "studioOnly": false
19
  },
20
  {
21
  "id": "mystery-tracker-refresh",
 
23
  "schedule": "0 */6 * * *",
24
  "handler": "cron/mystery-refresh.js",
25
  "enabled": true,
26
+ "timeout": 280,
27
+ "studioOnly": false
28
  },
29
  {
30
  "id": "hf-key-sync",
 
33
  "handler": "cron/hf-key-sync.js",
34
  "enabled": true,
35
  "timeout": 90
36
+ },
37
+ {
38
+ "id": "db-sync",
39
+ "name": "Save / reload the HF-hosted database and keep the deployed app awake",
40
+ "schedule": "*/5 * * * *",
41
+ "handler": "cron/db-sync.js",
42
+ "enabled": true,
43
+ "timeout": 120
44
  }
45
  ]
cron/db-sync.js ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * Keeps the two halves in sync.
3
+ *
4
+ * Deployed app (the only writer): saves the database to the encrypted snapshot
5
+ * on Hugging Face whenever something changed.
6
+ *
7
+ * Studio preview (read-only): pulls that snapshot back in, and pings the
8
+ * deployed app so Hugging Face never puts it to sleep — sleeping would stop the
9
+ * scan / push schedule.
10
+ */
11
+ const local = require('../lib/localdb')
12
+
13
+ const REMOTE_BASE = process.env.REMOTE_BASE || 'https://ethscriptions-cut.hf.space'
14
+ const IS_STUDIO = Boolean(process.env.BASE_PATH)
15
+
16
+ exports.handler = async () => {
17
+ if (!IS_STUDIO) {
18
+ const result = await local.snapshot({ reason: 'auto' })
19
+ return result
20
+ }
21
+
22
+ const ping = await fetch(`${REMOTE_BASE}/api/health`, {
23
+ signal: AbortSignal.timeout(30000),
24
+ })
25
+ .then((res) => res.status)
26
+ .catch(() => 0)
27
+
28
+ let refreshed = { restored: false, reason: 'skipped' }
29
+ try {
30
+ refreshed = await local.restore()
31
+ } catch (err) {
32
+ refreshed = { restored: false, reason: err.message }
33
+ }
34
+ return { studio: true, ping, ...refreshed }
35
+ }
cron/mystery-fast.js CHANGED
@@ -1,3 +1,10 @@
 
 
 
 
 
 
 
1
  const { fastRefresh } = require('../lib/mystery')
2
 
3
  exports.handler = async () => {
 
1
+ // The deployed app is the only instance that scans; the studio preview just
2
+ // shows what it found.
3
+ if (process.env.BASE_PATH) {
4
+ exports.handler = async () => ({ skipped: 'studio' })
5
+ return
6
+ }
7
+
8
  const { fastRefresh } = require('../lib/mystery')
9
 
10
  exports.handler = async () => {
cron/mystery-quick.js CHANGED
@@ -1,3 +1,10 @@
 
 
 
 
 
 
 
1
  const { quickRefresh } = require('../lib/mystery')
2
 
3
  exports.handler = async () => {
 
1
+ // The deployed app is the only instance that scans; the studio preview just
2
+ // shows what it found.
3
+ if (process.env.BASE_PATH) {
4
+ exports.handler = async () => ({ skipped: 'studio' })
5
+ return
6
+ }
7
+
8
  const { quickRefresh } = require('../lib/mystery')
9
 
10
  exports.handler = async () => {
cron/mystery-refresh.js CHANGED
@@ -1,3 +1,10 @@
 
 
 
 
 
 
 
1
  const { refresh } = require('../lib/mystery')
2
 
3
  exports.handler = async () => {
 
1
+ // The deployed app is the only instance that scans; the studio preview just
2
+ // shows what it found.
3
+ if (process.env.BASE_PATH) {
4
+ exports.handler = async () => ({ skipped: 'studio' })
5
+ return
6
+ }
7
+
8
  const { refresh } = require('../lib/mystery')
9
 
10
  exports.handler = async () => {
frontend/src/App.tsx CHANGED
@@ -25,6 +25,8 @@ type TrackerResponse = {
25
  mode: string | null
26
  } | null
27
  refreshing: boolean
 
 
28
  }
29
 
30
  const TRACKED_URL = 'asksurf.ai/mystery-box/g/'
@@ -197,6 +199,23 @@ export default function App() {
197
  )
198
  )}
199
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
200
  <SourcePanel onChanged={() => refetch()} />
201
 
202
  <div className="mt-6 flex flex-wrap items-center justify-between gap-3">
 
25
  mode: string | null
26
  } | null
27
  refreshing: boolean
28
+ readOnly?: boolean
29
+ remoteBase?: string
30
  }
31
 
32
  const TRACKED_URL = 'asksurf.ai/mystery-box/g/'
 
199
  )
200
  )}
201
 
202
+ {data?.readOnly && (
203
+ <div className="mt-4 flex flex-wrap items-center gap-2 rounded-[14px] border border-[var(--border-strong)] bg-[var(--bg-subtle)] px-4 py-3 text-xs text-fg-muted">
204
+ <span className="rounded-full bg-[var(--accent)]/15 px-2 py-0.5 font-medium text-[var(--accent)]">
205
+ 只读预览
206
+ </span>
207
+ <span>这里是线上的镜像:抓取、检查赠链和推送都在线上运行,数据每 5 分钟同步过来。</span>
208
+ <a
209
+ href={data.remoteBase}
210
+ target="_blank"
211
+ rel="noreferrer"
212
+ className="font-medium text-[var(--accent)] underline decoration-dotted"
213
+ >
214
+ 打开线上版
215
+ </a>
216
+ </div>
217
+ )}
218
+
219
  <SourcePanel onChanged={() => refetch()} />
220
 
221
  <div className="mt-6 flex flex-wrap items-center justify-between gap-3">
frontend/tsconfig.tsbuildinfo CHANGED
The diff for this file is too large to render. See raw diff
 
lib/auth.js CHANGED
@@ -12,8 +12,16 @@ async function adminKey() {
12
  return (await getSetting('admin_key')) || process.env.ADMIN_KEY || null
13
  }
14
 
 
 
 
 
 
15
  async function requireKey(req, res, next) {
16
  try {
 
 
 
17
  const key = await adminKey()
18
  if (!key) return next()
19
  const provided = req.get('x-admin-key') || req.query.key || req.body?.key
 
12
  return (await getSetting('admin_key')) || process.env.ADMIN_KEY || null
13
  }
14
 
15
+ // The studio preview never writes: scanning, pushes and settings all happen on
16
+ // the deployed app, which owns the database.
17
+ const READ_ONLY_HINT =
18
+ '工作室预览是只读的:抓取、推送和设置都在线上运行,请到 https://ethscriptions-cut.hf.space 操作'
19
+
20
  async function requireKey(req, res, next) {
21
  try {
22
+ if (process.env.BASE_PATH && req.method !== 'GET' && req.method !== 'HEAD') {
23
+ return res.status(409).json({ error: READ_ONLY_HINT, readOnly: true })
24
+ }
25
  const key = await adminKey()
26
  if (!key) return next()
27
  const provided = req.get('x-admin-key') || req.query.key || req.body?.key
lib/localdb.js ADDED
@@ -0,0 +1,391 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * The tracker's own database.
3
+ *
4
+ * Data lives in an embedded Postgres that runs inside the app process, and is
5
+ * snapshotted to a private Hugging Face dataset so it survives restarts of the
6
+ * deployed Space. Nothing here talks to the Surf platform database, which is
7
+ * what used to break the deployed app whenever the platform rotated its keys.
8
+ *
9
+ * The deployed Space is the only writer; the studio preview restores the same
10
+ * snapshot in read-only mode and shows exactly what the live app shows.
11
+ */
12
+ const crypto = require('node:crypto')
13
+ const fs = require('node:fs')
14
+ const path = require('node:path')
15
+ const { PGlite } = require('@electric-sql/pglite')
16
+
17
+ const DATA_DIR = process.env.PGLITE_DIR || '/tmp/cut-pgdata'
18
+ const DATASET = process.env.HF_DATA_REPO || 'Ethscriptions/cut-data'
19
+ const SNAPSHOT_PATH = 'snapshot.json'
20
+ const LOCAL_SNAPSHOT = path.join(path.dirname(DATA_DIR), 'snapshot.json')
21
+ const KEY_FILE = process.env.SNAPSHOT_KEY_FILE || path.join(path.dirname(DATA_DIR), 'snapshot.key')
22
+ const MIN_SNAPSHOT_GAP_MS = 2 * 60 * 1000
23
+
24
+ const COLUMNS = {
25
+ mystery_posts: [
26
+ 'tweet_id', 'handle', 'author_name', 'avatar_url', 'text_content', 'created_at',
27
+ 'likes', 'replies', 'reposts', 'views', 'media', 'links', 'tweet_url',
28
+ 'resolved_url', 'gift_code', 'has_link', 'matched_query', 'snippet', 'source',
29
+ 'link_checked_at', 'invite_status', 'seats_left', 'invite_expires_at',
30
+ 'inviter_name', 'box_tier', 'invite_checked_at', 'notified_at', 'notified_by',
31
+ 'first_seen_at', 'updated_at',
32
+ ],
33
+ tracker_settings: ['key', 'value', 'updated_at'],
34
+ tracker_runs: [
35
+ 'id', 'started_at', 'finished_at', 'queries', 'candidates', 'new_posts',
36
+ 'with_link', 'errors', 'mode',
37
+ ],
38
+ }
39
+ const TABLES = Object.keys(COLUMNS)
40
+ const JSON_COLUMNS = new Set(['media', 'links'])
41
+
42
+ const DDL = `
43
+ CREATE TABLE IF NOT EXISTS mystery_posts (
44
+ tweet_id text PRIMARY KEY,
45
+ handle text NOT NULL,
46
+ author_name text,
47
+ avatar_url text,
48
+ text_content text,
49
+ created_at bigint NOT NULL,
50
+ likes integer DEFAULT 0,
51
+ replies integer DEFAULT 0,
52
+ reposts integer DEFAULT 0,
53
+ views bigint DEFAULT 0,
54
+ media jsonb,
55
+ links jsonb,
56
+ tweet_url text,
57
+ resolved_url text,
58
+ gift_code text,
59
+ has_link boolean DEFAULT false,
60
+ matched_query text,
61
+ snippet text,
62
+ source text DEFAULT 'search',
63
+ link_checked_at timestamptz,
64
+ invite_status text,
65
+ seats_left integer,
66
+ invite_expires_at bigint,
67
+ inviter_name text,
68
+ box_tier text,
69
+ invite_checked_at timestamptz,
70
+ notified_at timestamptz,
71
+ notified_by text,
72
+ first_seen_at timestamptz DEFAULT now(),
73
+ updated_at timestamptz DEFAULT now()
74
+ );
75
+ CREATE INDEX IF NOT EXISTS mystery_posts_created_idx ON mystery_posts (created_at DESC);
76
+ CREATE INDEX IF NOT EXISTS mystery_posts_gift_idx ON mystery_posts (gift_code);
77
+ CREATE TABLE IF NOT EXISTS tracker_settings (
78
+ key text PRIMARY KEY,
79
+ value text,
80
+ updated_at timestamptz DEFAULT now()
81
+ );
82
+ CREATE TABLE IF NOT EXISTS tracker_runs (
83
+ id serial PRIMARY KEY,
84
+ started_at timestamptz DEFAULT now(),
85
+ finished_at timestamptz,
86
+ queries integer,
87
+ candidates integer,
88
+ new_posts integer,
89
+ with_link integer,
90
+ errors text,
91
+ mode text DEFAULT 'full'
92
+ );
93
+ `
94
+
95
+ let handlePromise = null
96
+ let lastSnapshotAt = 0
97
+ let lastSnapshotHash = ''
98
+
99
+ async function handle() {
100
+ if (!handlePromise) {
101
+ handlePromise = (async () => {
102
+ fs.mkdirSync(DATA_DIR, { recursive: true })
103
+ // int8 (oid 20) carries unix seconds and counters — hand it over as a number.
104
+ const db = new PGlite({ dataDir: DATA_DIR, parsers: { 20: (value) => Number(value) } })
105
+ await db.waitReady
106
+ await db.exec(DDL)
107
+ return db
108
+ })()
109
+ }
110
+ return handlePromise
111
+ }
112
+
113
+ /** Low-level query — never triggers the startup restore. */
114
+ async function raw(sql, params = []) {
115
+ const db = await handle()
116
+ const result = await db.query(sql, params)
117
+ const rows = result.rows || []
118
+ return { rows, rowCount: result.affectedRows ?? rows.length, fields: result.fields || [] }
119
+ }
120
+
121
+ let bootPromise = null
122
+
123
+ /** First use on a fresh container pulls the latest snapshot back in. */
124
+ function ensureBooted() {
125
+ if (!bootPromise) {
126
+ bootPromise = (async () => {
127
+ await handle()
128
+ const current = await counts()
129
+ if (current.posts > 0 || current.settings > 0) return { initialized: true, ...current }
130
+ const result = await restore()
131
+ if (result.restored) console.log(`[db] restored ${result.posts} posts from the snapshot (${result.origin})`)
132
+ else console.log(`[db] starting with an empty database (${result.reason || 'no snapshot'})`)
133
+ return { initialized: false, ...result }
134
+ })().catch((err) => {
135
+ console.error('[db] startup restore failed:', err.message)
136
+ return { initialized: false, error: err.message }
137
+ })
138
+ }
139
+ return bootPromise
140
+ }
141
+
142
+ /** Same shape as the platform helper: { rows, rowCount, fields }. */
143
+ async function dbQuery(sql, params = []) {
144
+ await ensureBooted()
145
+ return raw(sql, params)
146
+ }
147
+
148
+ /**
149
+ * The snapshot carries the Telegram session and the X cookies, so it is always
150
+ * encrypted before it leaves the machine (HF also rejects files that look like
151
+ * they contain credentials).
152
+ */
153
+ async function snapshotKey() {
154
+ const fromEnv = process.env.SNAPSHOT_KEY
155
+ if (fromEnv) return crypto.createHash('sha256').update(fromEnv).digest()
156
+ try {
157
+ if (fs.existsSync(KEY_FILE)) {
158
+ const raw = fs.readFileSync(KEY_FILE, 'utf8').trim()
159
+ if (raw) return crypto.createHash('sha256').update(raw).digest()
160
+ }
161
+ } catch {
162
+ /* fall through to the database */
163
+ }
164
+ try {
165
+ const { rows } = await raw(`SELECT value FROM tracker_settings WHERE key = 'snapshot_key'`)
166
+ const raw = rows[0]?.value
167
+ if (raw) return crypto.createHash('sha256').update(raw).digest()
168
+ } catch {
169
+ /* no key available */
170
+ }
171
+ return null
172
+ }
173
+
174
+ function encryptPayload(json, key) {
175
+ const iv = crypto.randomBytes(12)
176
+ const cipher = crypto.createCipheriv('aes-256-gcm', key, iv)
177
+ const data = Buffer.concat([cipher.update(json, 'utf8'), cipher.final()])
178
+ return JSON.stringify({
179
+ version: 1,
180
+ alg: 'aes-256-gcm',
181
+ saved_at: new Date().toISOString(),
182
+ iv: iv.toString('base64'),
183
+ tag: cipher.getAuthTag().toString('base64'),
184
+ data: data.toString('base64'),
185
+ })
186
+ }
187
+
188
+ function decryptPayload(text, key) {
189
+ const envelope = JSON.parse(text)
190
+ if (!envelope || envelope.alg !== 'aes-256-gcm') return null
191
+ const decipher = crypto.createDecipheriv('aes-256-gcm', key, Buffer.from(envelope.iv, 'base64'))
192
+ decipher.setAuthTag(Buffer.from(envelope.tag, 'base64'))
193
+ return Buffer.concat([decipher.update(Buffer.from(envelope.data, 'base64')), decipher.final()]).toString('utf8')
194
+ }
195
+
196
+ async function readToken() {
197
+ if (process.env.HF_TOKEN) return process.env.HF_TOKEN
198
+ if (process.env.HF_HUB_TOKEN) return process.env.HF_HUB_TOKEN
199
+ try {
200
+ const { rows } = await raw(`SELECT value FROM tracker_settings WHERE key = 'hf_token'`)
201
+ return rows[0]?.value || ''
202
+ } catch {
203
+ return ''
204
+ }
205
+ }
206
+
207
+ function normalizeRow(table, row) {
208
+ return COLUMNS[table].map((column) => {
209
+ const value = row[column]
210
+ if (value === undefined || value === null) return null
211
+ if (JSON_COLUMNS.has(column)) {
212
+ return typeof value === 'string' ? value : JSON.stringify(value)
213
+ }
214
+ if (value instanceof Date) return value.toISOString()
215
+ return value
216
+ })
217
+ }
218
+
219
+ async function writeRows(table, rows) {
220
+ if (!rows.length) return 0
221
+ const columns = COLUMNS[table]
222
+ const placeholders = columns.map((column, index) => (JSON_COLUMNS.has(column) ? `$${index + 1}::jsonb` : `$${index + 1}`))
223
+ const sql = `INSERT INTO ${table} (${columns.join(', ')}) VALUES (${placeholders.join(', ')}) ON CONFLICT DO NOTHING`
224
+ let written = 0
225
+ for (const row of rows) {
226
+ try {
227
+ await raw(sql, normalizeRow(table, row))
228
+ written += 1
229
+ } catch {
230
+ /* a broken row must never abort the whole restore */
231
+ }
232
+ }
233
+ if (table === 'tracker_runs') {
234
+ await raw(`SELECT setval(pg_get_serial_sequence('tracker_runs', 'id'), COALESCE((SELECT MAX(id) FROM tracker_runs), 1))`).catch(() => {})
235
+ }
236
+ return written
237
+ }
238
+
239
+ async function counts() {
240
+ const { rows } = await raw(`
241
+ SELECT
242
+ (SELECT count(*) FROM mystery_posts)::int AS posts,
243
+ (SELECT count(*) FROM tracker_settings)::int AS settings
244
+ `)
245
+ return rows[0] || { posts: 0, settings: 0 }
246
+ }
247
+
248
+ async function dump() {
249
+ const payload = { version: 1, saved_at: new Date().toISOString(), tables: {} }
250
+ for (const table of TABLES) {
251
+ const { rows } = await raw(`SELECT * FROM ${table}`)
252
+ payload.tables[table] = rows
253
+ }
254
+ return payload
255
+ }
256
+
257
+ async function load(payload, { replace = true } = {}) {
258
+ const tables = payload?.tables || {}
259
+ for (const table of TABLES) {
260
+ if (replace) await raw(`DELETE FROM ${table}`)
261
+ await writeRows(table, tables[table] || [])
262
+ }
263
+ return counts()
264
+ }
265
+
266
+ /** Upload the current data to the HF dataset (the durable copy). */
267
+ async function snapshot({ reason = 'auto', force = false } = {}) {
268
+ const payload = await dump()
269
+ const json = JSON.stringify(payload)
270
+ try {
271
+ fs.writeFileSync(LOCAL_SNAPSHOT, json)
272
+ } catch {
273
+ /* local cache is a nice-to-have */
274
+ }
275
+
276
+ const now = Date.now()
277
+ if (!force && json === lastSnapshotHash) return { saved: false, reason: 'unchanged' }
278
+ if (!force && now - lastSnapshotAt < MIN_SNAPSHOT_GAP_MS) return { saved: false, reason: 'too-soon' }
279
+ lastSnapshotHash = json
280
+ lastSnapshotAt = now
281
+
282
+ const token = await readToken()
283
+ if (!token) return { saved: false, reason: 'no-token' }
284
+
285
+ const key = await snapshotKey()
286
+ if (!key) return { saved: false, reason: 'no-encryption-key' }
287
+ const body = encryptPayload(json, key)
288
+
289
+ const { uploadFiles, createRepo } = require('@huggingface/hub')
290
+ const repo = { type: 'dataset', name: DATASET }
291
+ const commitTitle = `snapshot ${reason} ${new Date().toISOString().slice(0, 16).replace('T', ' ')}`
292
+ try {
293
+ await uploadFiles({
294
+ repo,
295
+ accessToken: token,
296
+ files: [{ path: SNAPSHOT_PATH, content: new Blob([body]) }],
297
+ commitTitle,
298
+ })
299
+ } catch (err) {
300
+ const message = String(err?.message || err)
301
+ if (!/404|not found/i.test(message)) return { saved: false, reason: `upload-failed: ${message.slice(0, 120)}` }
302
+ try {
303
+ await createRepo({ repo, accessToken: token, visibility: 'private' })
304
+ await uploadFiles({
305
+ repo,
306
+ accessToken: token,
307
+ files: [{ path: SNAPSHOT_PATH, content: new Blob([body]) }],
308
+ commitTitle,
309
+ })
310
+ } catch (retryErr) {
311
+ return { saved: false, reason: `upload-failed: ${String(retryErr?.message || retryErr).slice(0, 120)}` }
312
+ }
313
+ }
314
+ return { saved: true, bytes: body.length, posts: (payload.tables.mystery_posts || []).length, encrypted: true }
315
+ }
316
+
317
+ /** Pull the latest snapshot into the local database. */
318
+ async function restore({ replace = true } = {}) {
319
+ const token = await readToken()
320
+ let json = null
321
+ let origin = ''
322
+ if (token) {
323
+ try {
324
+ const { downloadFile } = require('@huggingface/hub')
325
+ const blob = await downloadFile({ repo: { type: 'dataset', name: DATASET }, path: SNAPSHOT_PATH, accessToken: token })
326
+ if (blob) {
327
+ json = await blob.text()
328
+ origin = 'hf'
329
+ }
330
+ } catch {
331
+ /* fall back to the local cache below */
332
+ }
333
+ }
334
+ if (!json && fs.existsSync(LOCAL_SNAPSHOT)) {
335
+ json = fs.readFileSync(LOCAL_SNAPSHOT, 'utf8')
336
+ origin = 'local'
337
+ }
338
+ if (!json) return { restored: false, reason: 'no-snapshot' }
339
+
340
+ let payload
341
+ try {
342
+ payload = JSON.parse(json)
343
+ } catch {
344
+ return { restored: false, reason: 'bad-snapshot' }
345
+ }
346
+ try {
347
+ const { rows } = await raw(`SELECT value FROM tracker_settings WHERE key = 'db_applied_at'`)
348
+ if (rows[0]?.value && payload?.saved_at && rows[0].value === payload.saved_at) {
349
+ return { restored: false, reason: 'up-to-date' }
350
+ }
351
+ } catch {
352
+ /* keep going */
353
+ }
354
+ if (payload && payload.alg === 'aes-256-gcm') {
355
+ const key = await snapshotKey()
356
+ if (!key) return { restored: false, reason: 'no-encryption-key' }
357
+ try {
358
+ payload = JSON.parse(decryptPayload(json, key))
359
+ } catch {
360
+ return { restored: false, reason: 'decrypt-failed' }
361
+ }
362
+ }
363
+ const result = await load(payload, { replace })
364
+ await raw(
365
+ `INSERT INTO tracker_settings (key, value, updated_at) VALUES ('db_applied_at', $1, now())
366
+ ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value, updated_at = now()`,
367
+ [String(payload.saved_at || '')]
368
+ ).catch(() => {})
369
+ lastSnapshotHash = json
370
+ lastSnapshotAt = Date.now()
371
+ return { restored: true, origin, savedAt: payload.saved_at, ...result }
372
+ }
373
+
374
+ /** Called at startup: an empty database gets filled from the snapshot. */
375
+ async function boot() {
376
+ return ensureBooted()
377
+ }
378
+
379
+ module.exports = {
380
+ dbQuery,
381
+ raw,
382
+ boot,
383
+ snapshot,
384
+ restore,
385
+ dump,
386
+ load,
387
+ counts,
388
+ DATA_DIR,
389
+ DATASET,
390
+ SNAPSHOT_PATH,
391
+ }
lib/mystery.js CHANGED
@@ -9,7 +9,7 @@
9
  * Everything is persisted so repeat views are free and history accumulates.
10
  */
11
  const { dataApi } = require('@surf-ai/sdk/server')
12
- const { dbQuery } = require('@surf-ai/sdk/db')
13
  const telegramLib = require('./telegram')
14
  const xtimeline = require('./xtimeline')
15
  const xauth = require('./xauth')
 
9
  * Everything is persisted so repeat views are free and history accumulates.
10
  */
11
  const { dataApi } = require('@surf-ai/sdk/server')
12
+ const { dbQuery } = require('./localdb')
13
  const telegramLib = require('./telegram')
14
  const xtimeline = require('./xtimeline')
15
  const xauth = require('./xauth')
lib/notify.js CHANGED
@@ -4,7 +4,7 @@
4
  * Every gift code is announced once, the moment it is first seen with seats
5
  * left. The webhook can be overridden from the settings UI.
6
  */
7
- const { dbQuery } = require('@surf-ai/sdk/db')
8
  const { getSetting } = require('./settings')
9
 
10
  /** Webhook comes from the settings table (set in the UI) or the env var. */
 
4
  * Every gift code is announced once, the moment it is first seen with seats
5
  * left. The webhook can be overridden from the settings UI.
6
  */
7
+ const { dbQuery } = require('./localdb')
8
  const { getSetting } = require('./settings')
9
 
10
  /** Webhook comes from the settings table (set in the UI) or the env var. */
lib/settings.js CHANGED
@@ -1,5 +1,5 @@
1
  /** Key/value settings shared by every data source (stored in Postgres). */
2
- const { dbQuery } = require('@surf-ai/sdk/db')
3
 
4
  async function getSetting(key) {
5
  const { rows } = await dbQuery('SELECT value FROM tracker_settings WHERE key = $1', [key])
 
1
  /** Key/value settings shared by every data source (stored in Postgres). */
2
+ const { dbQuery } = require('./localdb')
3
 
4
  async function getSetting(key) {
5
  const { rows } = await dbQuery('SELECT value FROM tracker_settings WHERE key = $1', [key])
lib/telegram.js CHANGED
@@ -6,7 +6,7 @@
6
  * Fallback: for public channels the t.me web preview is read anonymously, so
7
  * the tracker still works before anyone logs in.
8
  */
9
- const { dbQuery } = require('@surf-ai/sdk/db')
10
  const { getSetting, setSetting, getJson } = require('./settings')
11
  const telegramUser = require('./telegramUser')
12
 
 
6
  * Fallback: for public channels the t.me web preview is read anonymously, so
7
  * the tracker still works before anyone logs in.
8
  */
9
+ const { dbQuery } = require('./localdb')
10
  const { getSetting, setSetting, getJson } = require('./settings')
11
  const telegramUser = require('./telegramUser')
12
 
lib/telegramUser.js CHANGED
@@ -9,7 +9,7 @@
9
  const { TelegramClient, Api } = require('telegram')
10
  const { StringSession } = require('telegram/sessions')
11
  const { computeCheck } = require('telegram/Password')
12
- const { dbQuery } = require('@surf-ai/sdk/db')
13
  const { getSetting, setSetting, clearSetting, getJson } = require('./settings')
14
 
15
  /** Telegram Desktop's public API credentials — the usual default for tools. */
 
9
  const { TelegramClient, Api } = require('telegram')
10
  const { StringSession } = require('telegram/sessions')
11
  const { computeCheck } = require('telegram/Password')
12
+ const { dbQuery } = require('./localdb')
13
  const { getSetting, setSetting, clearSetting, getJson } = require('./settings')
14
 
15
  /** Telegram Desktop's public API credentials — the usual default for tools. */
package.json CHANGED
@@ -5,6 +5,8 @@
5
  "dev": "node scripts/check-env.js node --watch server.js"
6
  },
7
  "dependencies": {
 
 
8
  "@surf-ai/sdk": "1.0.5",
9
  "express": "4.22.1",
10
  "telegram": "^2.26.22"
 
5
  "dev": "node scripts/check-env.js node --watch server.js"
6
  },
7
  "dependencies": {
8
+ "@electric-sql/pglite": "^0.5.14",
9
+ "@huggingface/hub": "^2.17.10",
10
  "@surf-ai/sdk": "1.0.5",
11
  "express": "4.22.1",
12
  "telegram": "^2.26.22"
routes/tracker.js CHANGED
@@ -1,5 +1,5 @@
1
  const express = require('express')
2
- const { dbQuery } = require('@surf-ai/sdk/db')
3
  const { requireKey } = require('../lib/auth')
4
  const {
5
  refresh,
@@ -52,6 +52,9 @@ router.get('/', async (_req, res) => {
52
  },
53
  lastRun: runs[0] || null,
54
  refreshing: isRefreshing(),
 
 
 
55
  })
56
  } catch (err) {
57
  res.status(500).json({ error: err.message })
 
1
  const express = require('express')
2
+ const { dbQuery } = require('../lib/localdb')
3
  const { requireKey } = require('../lib/auth')
4
  const {
5
  refresh,
 
52
  },
53
  lastRun: runs[0] || null,
54
  refreshing: isRefreshing(),
55
+ // the studio preview is a mirror of the deployed app
56
+ readOnly: Boolean(process.env.BASE_PATH),
57
+ remoteBase: process.env.REMOTE_BASE || 'https://ethscriptions-cut.hf.space',
58
  })
59
  } catch (err) {
60
  res.status(500).json({ error: err.message })