@rei-standard/amsg-server 2.6.0-next.2 → 2.6.0-next.21

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 (85) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +599 -24
  3. package/dist/adapters/d1.d.ts +416 -0
  4. package/dist/adapters/factory.d.ts +39 -0
  5. package/dist/adapters/interface.d.ts +306 -0
  6. package/dist/adapters/neon.d.ts +88 -0
  7. package/dist/adapters/pg-shared.d.ts +161 -0
  8. package/dist/adapters/pg.d.ts +84 -0
  9. package/dist/adapters/schema.d.ts +57 -0
  10. package/dist/adapters/schema.sqlite.d.ts +49 -0
  11. package/dist/chunk-7NMQFTDJ.cjs +148 -0
  12. package/dist/chunk-E7OWP3VL.cjs +135 -0
  13. package/dist/chunk-GN44PST5.mjs +148 -0
  14. package/dist/chunk-KOJQVOYS.mjs +5847 -0
  15. package/dist/chunk-QHVID3V2.cjs +5847 -0
  16. package/dist/chunk-ZGGF4GMA.mjs +135 -0
  17. package/dist/cloudflare/single-user-worker.d.ts +37 -0
  18. package/dist/cloudflare.cjs +39 -2
  19. package/dist/cloudflare.d.ts +10 -2
  20. package/dist/cloudflare.mjs +40 -3
  21. package/dist/handlers/cancel-message.d.ts +3 -0
  22. package/dist/handlers/capabilities.d.ts +4 -0
  23. package/dist/handlers/client-state.d.ts +7 -0
  24. package/dist/handlers/get-message.d.ts +3 -0
  25. package/dist/handlers/get-user-key.d.ts +3 -0
  26. package/dist/handlers/init-tenant.d.ts +23 -0
  27. package/dist/handlers/llm-credentials.d.ts +5 -0
  28. package/dist/handlers/messages.d.ts +3 -0
  29. package/dist/handlers/outbox.d.ts +7 -0
  30. package/dist/handlers/push-subscription.d.ts +5 -0
  31. package/dist/handlers/schedule-message.d.ts +3 -0
  32. package/dist/handlers/send-notifications.d.ts +3 -0
  33. package/dist/handlers/single-user-init.d.ts +13 -0
  34. package/dist/handlers/update-message.d.ts +3 -0
  35. package/dist/handlers/vapid-public-key.d.ts +19 -0
  36. package/dist/index.cjs +133 -44
  37. package/dist/index.d.cts +131 -766
  38. package/dist/index.d.ts +131 -766
  39. package/dist/index.mjs +125 -36
  40. package/dist/lib/agentic-fire.d.ts +108 -0
  41. package/dist/lib/client-state-store.d.ts +80 -0
  42. package/dist/lib/constant-time.d.ts +14 -0
  43. package/dist/lib/db-errors.d.ts +10 -0
  44. package/dist/lib/encryption.d.ts +48 -0
  45. package/dist/lib/errors.d.ts +215 -0
  46. package/dist/lib/llm-credentials-store.d.ts +147 -0
  47. package/dist/lib/llm.d.ts +1 -0
  48. package/dist/lib/message-processor.d.ts +73 -0
  49. package/dist/lib/outbox-store.d.ts +95 -0
  50. package/dist/lib/push-subscription-store.d.ts +94 -0
  51. package/dist/lib/recurrence.d.ts +51 -0
  52. package/dist/lib/request.d.ts +182 -0
  53. package/dist/lib/result-emitter.d.ts +54 -0
  54. package/dist/lib/run-tick.d.ts +115 -0
  55. package/dist/lib/schema-version.d.ts +50 -0
  56. package/dist/lib/state-accessors.d.ts +70 -0
  57. package/dist/lib/state-chunks.d.ts +55 -0
  58. package/dist/lib/task-projection.d.ts +92 -0
  59. package/dist/lib/validation.d.ts +97 -0
  60. package/dist/lib/version.d.ts +7 -0
  61. package/dist/lib/webcrypto-utils.d.ts +1 -0
  62. package/dist/lib/webpush-webcrypto.d.ts +78 -0
  63. package/dist/{neon-BFUS25UX.cjs → neon-KP2CPA57.cjs} +110 -10
  64. package/dist/{neon-CU5N3CSW.mjs → neon-ZIMHALYI.mjs} +106 -6
  65. package/dist/{pg-QO6NKTGL.mjs → pg-QGC2XHUT.mjs} +94 -5
  66. package/dist/{pg-IIH3M4OM.cjs → pg-RZPQGXR3.cjs} +98 -9
  67. package/dist/single-user.d.ts +95 -0
  68. package/dist/tenant/blob-store.d.ts +30 -0
  69. package/dist/tenant/context.d.ts +47 -0
  70. package/dist/tenant/single-user-context.d.ts +29 -0
  71. package/dist/tenant/token.d.ts +26 -0
  72. package/package.json +3 -3
  73. package/dist/chunk-5ENJGVZX.mjs +0 -72
  74. package/dist/chunk-GN5QTMCL.cjs +0 -1870
  75. package/dist/chunk-PVNLB6TF.mjs +0 -1870
  76. package/dist/chunk-RGECD4OH.cjs +0 -72
  77. package/dist/cloudflare-B-E51VjP.d.cts +0 -2848
  78. package/dist/cloudflare-B-E51VjP.d.ts +0 -2848
  79. package/dist/cloudflare.d.cts +0 -2
  80. package/dist/neon-CJl66EGy.d.cts +0 -251
  81. package/dist/neon-DYvGnCzx.d.ts +0 -251
  82. package/dist/pg-07S-u_H4.d.cts +0 -246
  83. package/dist/pg-Du-pN_UT.d.ts +0 -246
  84. package/dist/schema-C8OnYk6j.d.cts +0 -74
  85. package/dist/schema-C8OnYk6j.d.ts +0 -74
@@ -1,1870 +0,0 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }// src/server/lib/validation.js
2
- var _amsgshared = require('@rei-standard/amsg-shared');
3
- function isValidISO8601(dateString) {
4
- const date = new Date(dateString);
5
- return date instanceof Date && !isNaN(date.getTime());
6
- }
7
- function isValidUrl(urlString) {
8
- try {
9
- new URL(urlString);
10
- return true;
11
- } catch (e) {
12
- return false;
13
- }
14
- }
15
- function isValidUUID(uuid) {
16
- const uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
17
- return uuidRegex.test(uuid);
18
- }
19
- function isValidUUIDv4(uuid) {
20
- const uuidV4Regex = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
21
- return uuidV4Regex.test(uuid);
22
- }
23
- var VALID_LLM_MESSAGE_ROLES = /* @__PURE__ */ new Set(["system", "user", "assistant", "tool"]);
24
- var SPLIT_PATTERN_MAX_LENGTH = 200;
25
- var SPLIT_PATTERN_MAX_ITEMS = 10;
26
- function validateSplitPattern(value) {
27
- if (value === void 0 || value === null) return null;
28
- const isArray = Array.isArray(value);
29
- const items = isArray ? value : [value];
30
- if (isArray && items.length === 0) return null;
31
- if (items.length > SPLIT_PATTERN_MAX_ITEMS) {
32
- return `splitPattern \u6570\u7EC4\u6700\u591A ${SPLIT_PATTERN_MAX_ITEMS} \u9879`;
33
- }
34
- for (let i = 0; i < items.length; i++) {
35
- const s = items[i];
36
- const label = isArray ? `splitPattern[${i}]` : "splitPattern";
37
- if (typeof s !== "string") return `${label} \u5FC5\u987B\u662F\u5B57\u7B26\u4E32`;
38
- if (s.length > SPLIT_PATTERN_MAX_LENGTH) {
39
- return `${label} \u4E0D\u80FD\u8D85\u8FC7 ${SPLIT_PATTERN_MAX_LENGTH} \u5B57\u7B26`;
40
- }
41
- try {
42
- new RegExp(s);
43
- } catch (_) {
44
- return `${label} \u4E0D\u662F\u6709\u6548\u6B63\u5219\u8868\u8FBE\u5F0F`;
45
- }
46
- }
47
- return null;
48
- }
49
- function validateLlmMessagesArray(messages) {
50
- if (!Array.isArray(messages) || messages.length === 0) {
51
- return "messages must be a non-empty array";
52
- }
53
- for (let i = 0; i < messages.length; i++) {
54
- const m = messages[i];
55
- if (!m || typeof m !== "object" || Array.isArray(m)) {
56
- return `messages[${i}] must be an object`;
57
- }
58
- if (!VALID_LLM_MESSAGE_ROLES.has(m.role)) {
59
- return `messages[${i}].role must be one of system / user / assistant / tool`;
60
- }
61
- if (typeof m.content === "string") {
62
- if (!m.content) return `messages[${i}].content must be a non-empty string`;
63
- } else if (Array.isArray(m.content)) {
64
- if (m.content.length === 0) return `messages[${i}].content array must be non-empty`;
65
- } else {
66
- return `messages[${i}].content must be a non-empty string or a non-empty array`;
67
- }
68
- }
69
- return null;
70
- }
71
- function validateScheduleMessagePayload(payload) {
72
- if (!payload.contactName || typeof payload.contactName !== "string") {
73
- return { valid: false, errorCode: "INVALID_PARAMETERS", errorMessage: "\u7F3A\u5C11\u5FC5\u9700\u53C2\u6570\u6216\u53C2\u6570\u683C\u5F0F\u9519\u8BEF", details: { missingFields: ["contactName"] } };
74
- }
75
- if (!payload.messageType || !["fixed", "prompted", "auto", "instant"].includes(payload.messageType)) {
76
- return { valid: false, errorCode: "INVALID_MESSAGE_TYPE", errorMessage: "\u6D88\u606F\u7C7B\u578B\u65E0\u6548", details: { providedType: payload.messageType, allowedTypes: ["fixed", "prompted", "auto", "instant"] } };
77
- }
78
- if (!payload.firstSendTime || !isValidISO8601(payload.firstSendTime)) {
79
- return { valid: false, errorCode: "INVALID_TIMESTAMP", errorMessage: "\u65F6\u95F4\u683C\u5F0F\u65E0\u6548", details: { field: "firstSendTime" } };
80
- }
81
- if (payload.firstSendTime && new Date(payload.firstSendTime) <= /* @__PURE__ */ new Date()) {
82
- return { valid: false, errorCode: "INVALID_TIMESTAMP", errorMessage: "\u65F6\u95F4\u5FC5\u987B\u5728\u672A\u6765", details: { field: "firstSendTime", reason: "must be in the future" } };
83
- }
84
- if (!payload.pushSubscription || typeof payload.pushSubscription !== "object") {
85
- return { valid: false, errorCode: "INVALID_PARAMETERS", errorMessage: "\u7F3A\u5C11\u5FC5\u9700\u53C2\u6570\u6216\u53C2\u6570\u683C\u5F0F\u9519\u8BEF", details: { missingFields: ["pushSubscription"] } };
86
- }
87
- if (payload.recurrenceType && !["none", "daily", "weekly"].includes(payload.recurrenceType)) {
88
- return { valid: false, errorCode: "INVALID_PARAMETERS", errorMessage: "\u7F3A\u5C11\u5FC5\u9700\u53C2\u6570\u6216\u53C2\u6570\u683C\u5F0F\u9519\u8BEF", details: { invalidFields: ["recurrenceType"] } };
89
- }
90
- if (payload.maxTokens !== void 0 && payload.maxTokens !== null && (!Number.isInteger(payload.maxTokens) || payload.maxTokens <= 0)) {
91
- return { valid: false, errorCode: "INVALID_PARAMETERS", errorMessage: "\u7F3A\u5C11\u5FC5\u9700\u53C2\u6570\u6216\u53C2\u6570\u683C\u5F0F\u9519\u8BEF", details: { invalidFields: ["maxTokens"] } };
92
- }
93
- if (payload.messageType === "fixed") {
94
- if (!payload.userMessage) {
95
- return { valid: false, errorCode: "INVALID_PARAMETERS", errorMessage: "\u7F3A\u5C11\u5FC5\u9700\u53C2\u6570\u6216\u53C2\u6570\u683C\u5F0F\u9519\u8BEF", details: { missingFields: ["userMessage (required for fixed type)"] } };
96
- }
97
- }
98
- const promptCheck = (() => {
99
- const hasCompletePrompt = payload.completePrompt !== void 0 && payload.completePrompt !== null && payload.completePrompt !== "";
100
- const hasMessages = payload.messages !== void 0 && payload.messages !== null;
101
- if (hasCompletePrompt && hasMessages) {
102
- return {
103
- error: { code: "INVALID_PARAMETERS", message: "exactly one of `completePrompt` or `messages` must be provided\uFF08\u4E24\u8005\u4E0D\u80FD\u540C\u65F6\u51FA\u73B0\uFF09", details: { invalidFields: ["completePrompt", "messages"] } },
104
- hasCompletePrompt: true,
105
- hasMessages: true
106
- };
107
- }
108
- if (hasMessages) {
109
- const err = validateLlmMessagesArray(payload.messages);
110
- if (err) {
111
- return {
112
- error: { code: "INVALID_PARAMETERS", message: err, details: { invalidFields: ["messages"] } },
113
- hasCompletePrompt: false,
114
- hasMessages: true
115
- };
116
- }
117
- }
118
- return { error: null, hasCompletePrompt, hasMessages };
119
- })();
120
- if (promptCheck.error) {
121
- return { valid: false, errorCode: promptCheck.error.code, errorMessage: promptCheck.error.message, details: promptCheck.error.details };
122
- }
123
- const hasPrompt = promptCheck.hasCompletePrompt || promptCheck.hasMessages;
124
- if (payload.messageType === "prompted" || payload.messageType === "auto") {
125
- const missingAiFields = [];
126
- if (!hasPrompt) missingAiFields.push("completePrompt or messages");
127
- if (!payload.apiUrl) missingAiFields.push("apiUrl");
128
- if (!payload.apiKey) missingAiFields.push("apiKey");
129
- if (!payload.primaryModel) missingAiFields.push("primaryModel");
130
- if (missingAiFields.length > 0) {
131
- return { valid: false, errorCode: "INVALID_PARAMETERS", errorMessage: "\u7F3A\u5C11\u5FC5\u9700\u53C2\u6570\u6216\u53C2\u6570\u683C\u5F0F\u9519\u8BEF", details: { missingFields: missingAiFields } };
132
- }
133
- }
134
- if (payload.messageType === "instant") {
135
- if (payload.recurrenceType && payload.recurrenceType !== "none") {
136
- return { valid: false, errorCode: "INVALID_PARAMETERS", errorMessage: "instant \u7C7B\u578B\u7684 recurrenceType \u5FC5\u987B\u4E3A none", details: { invalidFields: ['recurrenceType (must be "none" for instant type)'] } };
137
- }
138
- const hasAiConfig = hasPrompt && payload.apiUrl && payload.apiKey && payload.primaryModel;
139
- const hasUserMessage = payload.userMessage;
140
- if (!hasAiConfig && !hasUserMessage) {
141
- return { valid: false, errorCode: "INVALID_PARAMETERS", errorMessage: "instant \u7C7B\u578B\u5FC5\u987B\u63D0\u4F9B userMessage \u6216\u5B8C\u6574\u7684 AI \u914D\u7F6E", details: { missingFields: ["userMessage or ((completePrompt | messages) + apiUrl + apiKey + primaryModel)"] } };
142
- }
143
- }
144
- if (payload.temperature !== void 0 && payload.temperature !== null && (typeof payload.temperature !== "number" || !Number.isFinite(payload.temperature))) {
145
- return { valid: false, errorCode: "INVALID_PARAMETERS", errorMessage: "\u7F3A\u5C11\u5FC5\u9700\u53C2\u6570\u6216\u53C2\u6570\u683C\u5F0F\u9519\u8BEF", details: { invalidFields: ["temperature (must be a finite number)"] } };
146
- }
147
- const avatarErr = _amsgshared.validateAvatarUrl.call(void 0, payload.avatarUrl);
148
- if (avatarErr) {
149
- console.warn("[amsg-server] avatarUrl \u4E0D\u5408\u6CD5\uFF0C\u5DF2\u7F6E\u7A7A\uFF1A", avatarErr);
150
- payload.avatarUrl = null;
151
- }
152
- if (payload.uuid && !isValidUUID(payload.uuid)) {
153
- return { valid: false, errorCode: "INVALID_PARAMETERS", errorMessage: "\u7F3A\u5C11\u5FC5\u9700\u53C2\u6570\u6216\u53C2\u6570\u683C\u5F0F\u9519\u8BEF", details: { invalidFields: ["uuid (invalid UUID format)"] } };
154
- }
155
- if (payload.messageSubtype !== void 0 && payload.messageSubtype !== null && typeof payload.messageSubtype !== "string") {
156
- return { valid: false, errorCode: "INVALID_PARAMETERS", errorMessage: "\u7F3A\u5C11\u5FC5\u9700\u53C2\u6570\u6216\u53C2\u6570\u683C\u5F0F\u9519\u8BEF", details: { invalidFields: ["messageSubtype"] } };
157
- }
158
- const splitErr = validateSplitPattern(payload.splitPattern);
159
- if (splitErr) {
160
- return { valid: false, errorCode: "INVALID_PARAMETERS", errorMessage: splitErr, details: { invalidFields: ["splitPattern"] } };
161
- }
162
- return { valid: true };
163
- }
164
-
165
- // src/server/lib/webcrypto-utils.js
166
-
167
- var TEXT_ENCODER = new TextEncoder();
168
- var TEXT_DECODER = new TextDecoder("utf-8", { fatal: false });
169
- function utf8(str) {
170
- return TEXT_ENCODER.encode(String(str));
171
- }
172
- function utf8Decode(buf) {
173
- return TEXT_DECODER.decode(_amsgshared.toUint8.call(void 0, buf));
174
- }
175
- function bytesToBase64(buf) {
176
- const bytes = _amsgshared.toUint8.call(void 0, buf);
177
- let bin = "";
178
- for (let i = 0; i < bytes.length; i++) {
179
- bin += String.fromCharCode(bytes[i]);
180
- }
181
- return typeof btoa === "function" ? btoa(bin) : Buffer.from(bin, "binary").toString("base64");
182
- }
183
- function bytesToBase64Url(buf) {
184
- return bytesToBase64(buf).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/g, "");
185
- }
186
- function bytesToHex(buf) {
187
- const bytes = _amsgshared.toUint8.call(void 0, buf);
188
- let out = "";
189
- for (let i = 0; i < bytes.length; i++) {
190
- out += bytes[i].toString(16).padStart(2, "0");
191
- }
192
- return out;
193
- }
194
- function hexToBytes(hex) {
195
- const out = new Uint8Array(hex.length / 2);
196
- for (let i = 0; i < out.length; i++) {
197
- out[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);
198
- }
199
- return out;
200
- }
201
- function jsonToBase64Url(value) {
202
- return bytesToBase64Url(utf8(JSON.stringify(value)));
203
- }
204
- function randomUUID() {
205
- return globalThis.crypto.randomUUID();
206
- }
207
- function randomBytes(n) {
208
- const out = new Uint8Array(n);
209
- globalThis.crypto.getRandomValues(out);
210
- return out;
211
- }
212
-
213
- // src/server/lib/encryption.js
214
- var base64ToBytes = _amsgshared.base64UrlToBytes;
215
- var TAG_LENGTH_BYTES = 16;
216
- function importAesKey(hexKey, usage) {
217
- return globalThis.crypto.subtle.importKey(
218
- "raw",
219
- hexToBytes(hexKey),
220
- { name: "AES-GCM" },
221
- false,
222
- [usage]
223
- );
224
- }
225
- async function aesGcmSeal(hexKey, iv, plaintextBytes) {
226
- const key = await importAesKey(hexKey, "encrypt");
227
- const sealed = new Uint8Array(await globalThis.crypto.subtle.encrypt(
228
- { name: "AES-GCM", iv, tagLength: TAG_LENGTH_BYTES * 8 },
229
- key,
230
- plaintextBytes
231
- ));
232
- return {
233
- ciphertext: sealed.slice(0, sealed.length - TAG_LENGTH_BYTES),
234
- authTag: sealed.slice(sealed.length - TAG_LENGTH_BYTES)
235
- };
236
- }
237
- async function aesGcmOpen(hexKey, iv, ciphertext, authTag) {
238
- const key = await importAesKey(hexKey, "decrypt");
239
- const tagBits = authTag.length * 8;
240
- const tagLength = tagBits >= 96 && tagBits <= 128 ? tagBits : 128;
241
- const plain = await globalThis.crypto.subtle.decrypt(
242
- { name: "AES-GCM", iv, tagLength },
243
- key,
244
- _amsgshared.concatBytes.call(void 0, ciphertext, authTag)
245
- );
246
- return new Uint8Array(plain);
247
- }
248
- async function deriveUserEncryptionKey(userId, masterKey) {
249
- const digest = await globalThis.crypto.subtle.digest("SHA-256", utf8(masterKey + userId));
250
- return bytesToHex(new Uint8Array(digest)).slice(0, 64);
251
- }
252
- async function decryptPayload(encryptedPayload, encryptionKey) {
253
- const { iv, authTag, encryptedData } = encryptedPayload;
254
- const plain = await aesGcmOpen(
255
- encryptionKey,
256
- base64ToBytes(iv),
257
- base64ToBytes(encryptedData),
258
- base64ToBytes(authTag)
259
- );
260
- return JSON.parse(utf8Decode(plain));
261
- }
262
- async function encryptPayload(payload, encryptionKey) {
263
- const plaintext = typeof payload === "string" ? payload : JSON.stringify(payload);
264
- const iv = randomBytes(12);
265
- const { ciphertext, authTag } = await aesGcmSeal(encryptionKey, iv, utf8(plaintext));
266
- return {
267
- iv: bytesToBase64(iv),
268
- authTag: bytesToBase64(authTag),
269
- encryptedData: bytesToBase64(ciphertext)
270
- };
271
- }
272
- async function encryptForStorage(text, encryptionKey) {
273
- const iv = randomBytes(16);
274
- const { ciphertext, authTag } = await aesGcmSeal(encryptionKey, iv, utf8(text));
275
- return `${bytesToHex(iv)}:${bytesToHex(authTag)}:${bytesToHex(ciphertext)}`;
276
- }
277
- async function decryptFromStorage(encryptedText, encryptionKey) {
278
- const [ivHex, authTagHex, encryptedDataHex] = encryptedText.split(":");
279
- const plain = await aesGcmOpen(
280
- encryptionKey,
281
- hexToBytes(ivHex),
282
- hexToBytes(encryptedDataHex),
283
- hexToBytes(authTagHex)
284
- );
285
- return utf8Decode(plain);
286
- }
287
-
288
- // src/server/lib/request.js
289
- var REQUEST_ERRORS = {
290
- INVALID_JSON: { code: "INVALID_JSON", message: "\u8BF7\u6C42\u4F53\u4E0D\u662F\u6709\u6548\u7684 JSON" },
291
- INVALID_REQUEST_BODY: { code: "INVALID_REQUEST_BODY", message: "\u8BF7\u6C42\u4F53\u683C\u5F0F\u65E0\u6548" },
292
- INVALID_ENCRYPTED_PAYLOAD: { code: "INVALID_ENCRYPTED_PAYLOAD", message: "\u52A0\u5BC6\u6570\u636E\u683C\u5F0F\u9519\u8BEF" }
293
- };
294
- function parseBodyAsObject(body, options = {}) {
295
- const invalidJson = options.invalidJson || REQUEST_ERRORS.INVALID_JSON;
296
- const invalidType = options.invalidType || REQUEST_ERRORS.INVALID_REQUEST_BODY;
297
- let parsed = body;
298
- if (typeof parsed === "string") {
299
- try {
300
- parsed = JSON.parse(parsed);
301
- } catch (e2) {
302
- return { ok: false, error: invalidJson };
303
- }
304
- }
305
- if (!isPlainObject(parsed)) {
306
- return { ok: false, error: invalidType };
307
- }
308
- return { ok: true, data: parsed };
309
- }
310
- function parseJsonBody(body) {
311
- return parseBodyAsObject(body, {
312
- invalidJson: REQUEST_ERRORS.INVALID_JSON,
313
- invalidType: REQUEST_ERRORS.INVALID_REQUEST_BODY
314
- });
315
- }
316
- function isPlainObject(value) {
317
- return typeof value === "object" && value !== null && !Array.isArray(value);
318
- }
319
- function isEncryptedEnvelope(payload) {
320
- if (!isPlainObject(payload)) return false;
321
- return typeof payload.iv === "string" && typeof payload.authTag === "string" && typeof payload.encryptedData === "string";
322
- }
323
- function parseEncryptedBody(body) {
324
- const parsedBody = parseBodyAsObject(body, {
325
- invalidJson: REQUEST_ERRORS.INVALID_ENCRYPTED_PAYLOAD,
326
- invalidType: REQUEST_ERRORS.INVALID_ENCRYPTED_PAYLOAD
327
- });
328
- if (!parsedBody.ok) {
329
- return parsedBody;
330
- }
331
- if (!isEncryptedEnvelope(parsedBody.data)) {
332
- return { ok: false, error: REQUEST_ERRORS.INVALID_ENCRYPTED_PAYLOAD };
333
- }
334
- return parsedBody;
335
- }
336
- function getHeader(headers = {}, name) {
337
- if (!headers || typeof headers !== "object") {
338
- return "";
339
- }
340
- const lowerName = String(name || "").toLowerCase();
341
- if (!lowerName) return "";
342
- for (const [key, value] of Object.entries(headers)) {
343
- if (String(key).toLowerCase() === lowerName) {
344
- return String(value || "").trim();
345
- }
346
- }
347
- return "";
348
- }
349
-
350
- // src/server/handlers/get-user-key.js
351
- function createGetUserKeyHandler(ctx) {
352
- async function GET(url, headers) {
353
- const effectiveHeaders = headers || url || {};
354
- const tenantResult = await ctx.tenantManager.resolveTenant(effectiveHeaders);
355
- if (!tenantResult.ok) {
356
- return tenantResult.error;
357
- }
358
- const { masterKey } = tenantResult.context;
359
- const userId = getHeader(effectiveHeaders, "x-user-id");
360
- if (!userId) {
361
- return {
362
- status: 400,
363
- body: { success: false, error: { code: "USER_ID_REQUIRED", message: "\u7F3A\u5C11\u7528\u6237\u6807\u8BC6\u7B26" } }
364
- };
365
- }
366
- if (!isValidUUIDv4(userId)) {
367
- return {
368
- status: 400,
369
- body: { success: false, error: { code: "INVALID_USER_ID_FORMAT", message: "X-User-Id \u5FC5\u987B\u662F UUID v4 \u683C\u5F0F" } }
370
- };
371
- }
372
- return {
373
- status: 200,
374
- body: {
375
- success: true,
376
- data: {
377
- userKey: await deriveUserEncryptionKey(userId, masterKey),
378
- version: 1
379
- }
380
- }
381
- };
382
- }
383
- return { GET };
384
- }
385
-
386
- // src/server/lib/db-errors.js
387
- function isUniqueViolation(error) {
388
- if (!error || typeof error !== "object") return false;
389
- const code = error.code;
390
- if (code === "23505") return true;
391
- const message = typeof error.message === "string" ? error.message.toLowerCase() : "";
392
- return message.includes("duplicate key") || message.includes("unique constraint");
393
- }
394
-
395
- // src/server/lib/message-processor.js
396
-
397
-
398
-
399
-
400
-
401
-
402
- var DEFAULT_SPLIT_REGEX = /([。!?!?]+)/;
403
- var SLEEP_BETWEEN_MESSAGES_MS = 1500;
404
- function splitOnceByRegex(chunk, regex) {
405
- const out = chunk.split(regex).reduce((acc, part, i, arr) => {
406
- if (i % 2 === 0 && part.trim()) {
407
- const punctuation = arr[i + 1] || "";
408
- acc.push(part.trim() + punctuation);
409
- }
410
- return acc;
411
- }, []).filter((s) => s.length > 0);
412
- return out.length > 0 ? out : [chunk];
413
- }
414
- function splitMessageIntoSentences(messageContent, splitPattern = null) {
415
- const sources = splitPattern == null ? null : Array.isArray(splitPattern) ? splitPattern : [splitPattern];
416
- const regexes = sources && sources.length > 0 ? sources.map((s) => new RegExp(s)) : [DEFAULT_SPLIT_REGEX];
417
- let chunks = [messageContent];
418
- for (const regex of regexes) {
419
- chunks = chunks.flatMap((c) => splitOnceByRegex(c, regex));
420
- }
421
- return chunks.length > 0 ? chunks : [messageContent];
422
- }
423
- async function processSingleMessage(task, ctx, providedMasterKey) {
424
- try {
425
- const masterKey = providedMasterKey || ctx.masterKey;
426
- if (!masterKey) {
427
- return { success: false, messagesSent: 0, error: "TENANT_MASTER_KEY_MISSING" };
428
- }
429
- const userKey = await deriveUserEncryptionKey(task.user_id, masterKey);
430
- const decryptedPayload = JSON.parse(await decryptFromStorage(task.encrypted_payload, userKey));
431
- let messageContent;
432
- let llmResponse = null;
433
- if (decryptedPayload.messageType === "fixed") {
434
- messageContent = decryptedPayload.userMessage;
435
- } else if (decryptedPayload.messageType === "instant") {
436
- const hasPrompt = !!decryptedPayload.completePrompt || Array.isArray(decryptedPayload.messages) && decryptedPayload.messages.length > 0;
437
- if (hasPrompt && decryptedPayload.apiUrl && decryptedPayload.apiKey && decryptedPayload.primaryModel) {
438
- const aiResult = await _callAI(decryptedPayload);
439
- messageContent = aiResult.content;
440
- llmResponse = aiResult.response;
441
- } else if (decryptedPayload.userMessage) {
442
- messageContent = decryptedPayload.userMessage;
443
- } else {
444
- throw new Error("Invalid instant message: no content source available");
445
- }
446
- } else if (decryptedPayload.messageType === "prompted" || decryptedPayload.messageType === "auto") {
447
- const aiResult = await _callAI(decryptedPayload);
448
- messageContent = aiResult.content;
449
- llmResponse = aiResult.response;
450
- } else {
451
- throw new Error("Invalid message configuration: no content source available");
452
- }
453
- const reasoning = _amsgshared.readReasoningContent.call(void 0, llmResponse);
454
- if (reasoning) {
455
- messageContent = _amsgshared.stripReasoningTags.call(void 0, messageContent);
456
- }
457
- const messages = splitMessageIntoSentences(messageContent, _nullishCoalesce(decryptedPayload.splitPattern, () => ( null)));
458
- if (!ctx.vapid.email || !ctx.vapid.publicKey || !ctx.vapid.privateKey) {
459
- throw new Error("VAPID configuration missing - push notifications cannot be sent");
460
- }
461
- const pushSubscription = decryptedPayload.pushSubscription;
462
- const sessionId = task.id != null ? `sess_task_${task.id}` : `sess_${randomUUID()}`;
463
- const source = decryptedPayload.messageType === "instant" ? "instant" : "scheduled";
464
- const messageSubtype = decryptedPayload.messageSubtype || "chat";
465
- const avatarUrl = decryptedPayload.avatarUrl || null;
466
- const metadata = decryptedPayload.metadata || {};
467
- const messageIdBase = task.id != null ? `msg_task_${task.id}` : `msg_${randomUUID()}_instant`;
468
- if (reasoning) {
469
- const reasoningPush = _amsgshared.buildReasoningPush.call(void 0, {
470
- messageType: decryptedPayload.messageType,
471
- source,
472
- messageId: `${messageIdBase}_reasoning`,
473
- sessionId,
474
- reasoningContent: reasoning,
475
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
476
- title: `\u6765\u81EA ${decryptedPayload.contactName}`,
477
- contactName: decryptedPayload.contactName,
478
- avatarUrl,
479
- messageSubtype,
480
- metadata
481
- });
482
- await ctx.webpush.sendNotification(pushSubscription, JSON.stringify(reasoningPush));
483
- await new Promise((resolve) => setTimeout(resolve, SLEEP_BETWEEN_MESSAGES_MS));
484
- }
485
- for (let i = 0; i < messages.length; i++) {
486
- const contentPush = _amsgshared.buildContentPush.call(void 0, {
487
- messageType: decryptedPayload.messageType,
488
- source,
489
- messageId: `${messageIdBase}_${i}`,
490
- sessionId,
491
- message: messages[i],
492
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
493
- title: `\u6765\u81EA ${decryptedPayload.contactName}`,
494
- contactName: decryptedPayload.contactName,
495
- avatarUrl,
496
- messageSubtype,
497
- messageIndex: i + 1,
498
- totalMessages: messages.length,
499
- taskId: task.id || null,
500
- metadata
501
- });
502
- await ctx.webpush.sendNotification(pushSubscription, JSON.stringify(contentPush));
503
- if (i < messages.length - 1) {
504
- await new Promise((resolve) => setTimeout(resolve, SLEEP_BETWEEN_MESSAGES_MS));
505
- }
506
- }
507
- return { success: true, messagesSent: messages.length };
508
- } catch (error) {
509
- return { success: false, messagesSent: 0, error: error.message };
510
- }
511
- }
512
- async function processMessagesByUuid(uuid, ctx, maxRetries = 2, userId, providedMasterKey) {
513
- let retryCount = 0;
514
- const masterKey = providedMasterKey || ctx.masterKey;
515
- if (!masterKey) {
516
- return {
517
- success: false,
518
- error: { code: "TENANT_MASTER_KEY_MISSING", message: "\u79DF\u6237\u4E3B\u5BC6\u94A5\u4E0D\u5B58\u5728\u6216\u914D\u7F6E\u5F02\u5E38" }
519
- };
520
- }
521
- while (retryCount <= maxRetries) {
522
- let task;
523
- try {
524
- task = userId ? await ctx.db.getTaskByUuid(uuid, userId) : await ctx.db.getTaskByUuidOnly(uuid);
525
- } catch (error) {
526
- if (retryCount < maxRetries) {
527
- retryCount++;
528
- await new Promise((resolve) => setTimeout(resolve, 1e3 * retryCount));
529
- continue;
530
- }
531
- return {
532
- success: false,
533
- error: { code: "INTERNAL_ERROR", message: error.message, retriesAttempted: retryCount }
534
- };
535
- }
536
- if (!task) {
537
- return { success: false, error: { code: "TASK_NOT_FOUND", message: "\u4EFB\u52A1\u4E0D\u5B58\u5728\u6216\u5DF2\u5904\u7406" } };
538
- }
539
- const result = await processSingleMessage(task, ctx, masterKey);
540
- if (!result.success) {
541
- if (retryCount < maxRetries) {
542
- retryCount++;
543
- await new Promise((resolve) => setTimeout(resolve, 1e3 * retryCount));
544
- continue;
545
- }
546
- try {
547
- await ctx.db.updateTaskById(task.id, { status: "failed", retry_count: retryCount });
548
- } catch (_updateError) {
549
- }
550
- return {
551
- success: false,
552
- error: { code: "PROCESSING_ERROR", message: result.error, retriesAttempted: retryCount }
553
- };
554
- }
555
- try {
556
- await ctx.db.deleteTaskById(task.id);
557
- } catch (error) {
558
- try {
559
- await ctx.db.updateTaskById(task.id, { status: "sent", retry_count: 0 });
560
- } catch (_markSentError) {
561
- }
562
- return {
563
- success: false,
564
- error: {
565
- code: "POST_SEND_CLEANUP_FAILED",
566
- message: "\u6D88\u606F\u5DF2\u53D1\u9001\uFF0C\u4F46\u4EFB\u52A1\u6E05\u7406\u5931\u8D25",
567
- details: { error: error.message }
568
- }
569
- };
570
- }
571
- return { success: true, messagesSent: result.messagesSent, retriesUsed: retryCount };
572
- }
573
- }
574
- async function _callAI(payload) {
575
- const normalizedApiUrl = normalizeAiApiUrl(payload.apiUrl);
576
- const requestBody = buildAiRequestBody(payload);
577
- const aiResponse = await fetch(normalizedApiUrl, {
578
- method: "POST",
579
- headers: {
580
- "Content-Type": "application/json",
581
- "Authorization": `Bearer ${payload.apiKey}`
582
- },
583
- body: JSON.stringify(requestBody),
584
- signal: AbortSignal.timeout(3e5)
585
- });
586
- if (!aiResponse.ok) {
587
- if (aiResponse.status === 405) {
588
- throw new Error(
589
- `AI API error: 405 Method Not Allowed. apiUrl must point to a full chat endpoint (for example: /chat/completions). Received: ${normalizedApiUrl}`
590
- );
591
- }
592
- throw new Error(
593
- `AI API error: ${aiResponse.status} ${aiResponse.statusText || "Unknown Error"}. Request URL: ${normalizedApiUrl}`
594
- );
595
- }
596
- const aiData = await aiResponse.json();
597
- const content = _optionalChain([aiData, 'optionalAccess', _2 => _2.choices, 'optionalAccess', _3 => _3[0], 'optionalAccess', _4 => _4.message, 'optionalAccess', _5 => _5.content]);
598
- if (typeof content !== "string" || !content.trim()) {
599
- throw new Error("AI API error: response missing choices[0].message.content");
600
- }
601
- return { response: aiData, content: content.trim() };
602
- }
603
- function buildAiRequestBody(payload) {
604
- const llmMessages = Array.isArray(payload.messages) && payload.messages.length > 0 ? payload.messages : [{ role: "user", content: payload.completePrompt }];
605
- const requestBody = {
606
- model: payload.primaryModel,
607
- messages: llmMessages
608
- };
609
- if (payload.temperature !== void 0 && payload.temperature !== null) {
610
- requestBody.temperature = payload.temperature;
611
- } else if (!Array.isArray(payload.messages)) {
612
- requestBody.temperature = 0.8;
613
- }
614
- if (payload.maxTokens === void 0 || payload.maxTokens === null) {
615
- return requestBody;
616
- }
617
- if (!Number.isInteger(payload.maxTokens) || payload.maxTokens <= 0) {
618
- throw new Error("Invalid maxTokens: maxTokens must be a positive integer when provided.");
619
- }
620
- requestBody.max_tokens = payload.maxTokens;
621
- return requestBody;
622
- }
623
- function normalizeAiApiUrl(apiUrl) {
624
- if (typeof apiUrl !== "string" || !apiUrl.trim()) {
625
- throw new Error(
626
- "Invalid apiUrl: apiUrl is required. Please provide a chat endpoint URL (for example: https://api.openai.com or https://api.openai.com/v1/chat/completions)."
627
- );
628
- }
629
- const trimmedApiUrl = apiUrl.trim();
630
- let parsedUrl;
631
- try {
632
- parsedUrl = new URL(trimmedApiUrl);
633
- } catch (e3) {
634
- throw new Error(
635
- `Invalid apiUrl: "${apiUrl}". Please provide a valid absolute URL.`
636
- );
637
- }
638
- let path = parsedUrl.pathname.replace(/\/+$/, "") || "/";
639
- if (/\/chat\/completions$/.test(path)) {
640
- } else if (path === "/") {
641
- path = "/v1/chat/completions";
642
- } else if (/\/v\d+$/.test(path)) {
643
- path = `${path}/chat/completions`;
644
- }
645
- parsedUrl.pathname = path;
646
- return parsedUrl.toString();
647
- }
648
-
649
- // src/server/handlers/schedule-message.js
650
- function createScheduleMessageHandler(ctx) {
651
- async function POST(headers, body) {
652
- const tenantResult = await ctx.tenantManager.resolveTenant(headers);
653
- if (!tenantResult.ok) {
654
- return tenantResult.error;
655
- }
656
- const tenantCtx = tenantResult.context;
657
- const db = tenantCtx.db;
658
- const masterKey = tenantCtx.masterKey;
659
- const isEncrypted = getHeader(headers, "x-payload-encrypted") === "true";
660
- const encryptionVersion = getHeader(headers, "x-encryption-version");
661
- const userId = getHeader(headers, "x-user-id");
662
- if (!isEncrypted) {
663
- return { status: 400, body: { success: false, error: { code: "ENCRYPTION_REQUIRED", message: "\u8BF7\u6C42\u4F53\u5FC5\u987B\u52A0\u5BC6" } } };
664
- }
665
- if (!userId) {
666
- return { status: 400, body: { success: false, error: { code: "USER_ID_REQUIRED", message: "\u7F3A\u5C11\u7528\u6237\u6807\u8BC6\u7B26" } } };
667
- }
668
- if (!isValidUUIDv4(userId)) {
669
- return { status: 400, body: { success: false, error: { code: "INVALID_USER_ID_FORMAT", message: "X-User-Id \u5FC5\u987B\u662F UUID v4 \u683C\u5F0F" } } };
670
- }
671
- if (encryptionVersion !== "1") {
672
- return { status: 400, body: { success: false, error: { code: "UNSUPPORTED_ENCRYPTION_VERSION", message: "\u52A0\u5BC6\u7248\u672C\u4E0D\u652F\u6301" } } };
673
- }
674
- const parsedBody = parseEncryptedBody(body);
675
- if (!parsedBody.ok) {
676
- return { status: 400, body: { success: false, error: parsedBody.error } };
677
- }
678
- const encryptedBody = parsedBody.data;
679
- const userKey = await deriveUserEncryptionKey(userId, masterKey);
680
- let payload;
681
- try {
682
- payload = await decryptPayload(encryptedBody, userKey);
683
- } catch (error) {
684
- if (error instanceof SyntaxError) {
685
- return { status: 400, body: { success: false, error: { code: "INVALID_PAYLOAD_FORMAT", message: "\u89E3\u5BC6\u540E\u7684\u6570\u636E\u4E0D\u662F\u6709\u6548 JSON" } } };
686
- }
687
- const message = typeof error.message === "string" ? error.message : "";
688
- if (message.includes("auth") || message.includes("Unsupported state")) {
689
- return { status: 400, body: { success: false, error: { code: "DECRYPTION_FAILED", message: "\u8BF7\u6C42\u4F53\u89E3\u5BC6\u5931\u8D25" } } };
690
- }
691
- return { status: 400, body: { success: false, error: { code: "DECRYPTION_FAILED", message: "\u8BF7\u6C42\u4F53\u89E3\u5BC6\u5931\u8D25" } } };
692
- }
693
- if (!isPlainObject(payload)) {
694
- return { status: 400, body: { success: false, error: { code: "INVALID_PAYLOAD_FORMAT", message: "\u89E3\u5BC6\u540E\u7684\u6570\u636E\u5FC5\u987B\u662F JSON \u5BF9\u8C61" } } };
695
- }
696
- const validationResult = validateScheduleMessagePayload(payload);
697
- if (!validationResult.valid) {
698
- return { status: 400, body: { success: false, error: { code: validationResult.errorCode, message: validationResult.errorMessage, details: validationResult.details } } };
699
- }
700
- const taskUuid = payload.uuid || randomUUID();
701
- const fullTaskData = {
702
- contactName: payload.contactName,
703
- avatarUrl: payload.avatarUrl || null,
704
- messageType: payload.messageType,
705
- messageSubtype: payload.messageSubtype || "chat",
706
- userMessage: payload.userMessage || null,
707
- firstSendTime: payload.firstSendTime,
708
- recurrenceType: payload.recurrenceType || "none",
709
- apiUrl: payload.apiUrl || null,
710
- apiKey: payload.apiKey || null,
711
- primaryModel: payload.primaryModel || null,
712
- // Prompt is one-of: legacy completePrompt (string) OR messages (OpenAI-
713
- // style array). Validation has already enforced exactly-one-of, so
714
- // exactly one of these will be non-null when an AI config is provided.
715
- completePrompt: payload.completePrompt || null,
716
- messages: Array.isArray(payload.messages) ? payload.messages : null,
717
- maxTokens: _nullishCoalesce(payload.maxTokens, () => ( null)),
718
- temperature: _nullishCoalesce(payload.temperature, () => ( null)),
719
- // 0.6.0+: optional caller-provided regex (string or string[]) used by
720
- // the message processor to chunk LLM output into individual pushes.
721
- // null → processor falls back to the default /([。!?!?]+)/ regex.
722
- splitPattern: _nullishCoalesce(payload.splitPattern, () => ( null)),
723
- pushSubscription: payload.pushSubscription,
724
- metadata: payload.metadata || {}
725
- };
726
- const encryptedPayload = await encryptForStorage(JSON.stringify(fullTaskData), userKey);
727
- if (payload.messageType === "instant") {
728
- if (!ctx.vapid.email || !ctx.vapid.publicKey || !ctx.vapid.privateKey) {
729
- return {
730
- status: 500,
731
- body: {
732
- success: false,
733
- error: {
734
- code: "VAPID_CONFIG_ERROR",
735
- message: "VAPID \u914D\u7F6E\u7F3A\u5931\uFF0C\u65E0\u6CD5\u53D1\u9001\u5373\u65F6\u6D88\u606F",
736
- details: {
737
- missingKeys: [
738
- !ctx.vapid.email && "VAPID_EMAIL",
739
- !ctx.vapid.publicKey && "NEXT_PUBLIC_VAPID_PUBLIC_KEY",
740
- !ctx.vapid.privateKey && "VAPID_PRIVATE_KEY"
741
- ].filter(Boolean)
742
- }
743
- }
744
- }
745
- };
746
- }
747
- }
748
- let dbResult;
749
- try {
750
- dbResult = await db.createTask({
751
- user_id: userId,
752
- uuid: taskUuid,
753
- encrypted_payload: encryptedPayload,
754
- next_send_at: payload.firstSendTime,
755
- message_type: payload.messageType
756
- });
757
- } catch (error) {
758
- if (isUniqueViolation(error)) {
759
- return {
760
- status: 409,
761
- body: {
762
- success: false,
763
- error: {
764
- code: "TASK_UUID_CONFLICT",
765
- message: "\u4EFB\u52A1 UUID \u5DF2\u5B58\u5728\uFF0C\u8BF7\u4F7F\u7528\u65B0\u7684 uuid \u91CD\u65B0\u63D0\u4EA4"
766
- }
767
- }
768
- };
769
- }
770
- throw error;
771
- }
772
- if (!dbResult) {
773
- return { status: 500, body: { success: false, error: { code: "TASK_CREATE_FAILED", message: "\u521B\u5EFA\u4EFB\u52A1\u5931\u8D25" } } };
774
- }
775
- if (payload.messageType === "instant") {
776
- try {
777
- const sendResult = await processMessagesByUuid(taskUuid, {
778
- ...ctx,
779
- db,
780
- masterKey
781
- }, 2, userId, masterKey);
782
- if (!sendResult.success) {
783
- return { status: 500, body: { success: false, error: { code: "MESSAGE_SEND_FAILED", message: "\u6D88\u606F\u53D1\u9001\u5931\u8D25", details: sendResult.error } } };
784
- }
785
- return {
786
- status: 200,
787
- body: {
788
- success: true,
789
- data: {
790
- uuid: taskUuid,
791
- contactName: payload.contactName,
792
- messagesSent: sendResult.messagesSent,
793
- sentAt: (/* @__PURE__ */ new Date()).toISOString(),
794
- status: "sent",
795
- retriesUsed: sendResult.retriesUsed || 0
796
- }
797
- }
798
- };
799
- } catch (error) {
800
- return { status: 500, body: { success: false, error: { code: "MESSAGE_SEND_FAILED", message: "\u6D88\u606F\u53D1\u9001\u5931\u8D25", details: { error: error.message } } } };
801
- }
802
- }
803
- return {
804
- status: 201,
805
- body: {
806
- success: true,
807
- data: {
808
- id: dbResult.id,
809
- uuid: dbResult.uuid,
810
- contactName: payload.contactName,
811
- nextSendAt: dbResult.next_send_at,
812
- status: dbResult.status,
813
- createdAt: dbResult.created_at
814
- }
815
- }
816
- };
817
- }
818
- return { POST };
819
- }
820
-
821
- // src/server/lib/run-tick.js
822
- async function runScheduledTick(ctx) {
823
- const db = ctx.db;
824
- const masterKey = ctx.masterKey;
825
- const startTime = Date.now();
826
- const tasks = await db.getPendingTasks(50);
827
- const MAX_CONCURRENT = 8;
828
- const results = {
829
- totalTasks: tasks.length,
830
- successCount: 0,
831
- failedCount: 0,
832
- deletedOnceOffTasks: 0,
833
- updatedRecurringTasks: 0,
834
- failedTasks: []
835
- };
836
- async function handleDeliveryFailure(task, reason) {
837
- results.failedCount++;
838
- try {
839
- if (task.retry_count >= 3) {
840
- await db.updateTaskById(task.id, { status: "failed" });
841
- results.failedTasks.push({ taskId: task.id, reason, retryCount: task.retry_count, status: "permanently_failed" });
842
- } else {
843
- const nextRetryTime = new Date(Date.now() + (task.retry_count + 1) * 2 * 60 * 1e3);
844
- await db.updateTaskById(task.id, { next_send_at: nextRetryTime.toISOString(), retry_count: task.retry_count + 1 });
845
- results.failedTasks.push({ taskId: task.id, reason, retryCount: task.retry_count + 1, nextRetryAt: nextRetryTime.toISOString() });
846
- }
847
- } catch (updateError) {
848
- results.failedTasks.push({ taskId: task.id, reason, status: "retry_update_failed", updateError: updateError.message });
849
- }
850
- }
851
- async function handlePostSendPersistenceFailure(task, reason) {
852
- results.failedCount++;
853
- let markedSent = false;
854
- try {
855
- await db.updateTaskById(task.id, { status: "sent", retry_count: 0 });
856
- markedSent = true;
857
- } catch (_markSentError) {
858
- markedSent = false;
859
- }
860
- results.failedTasks.push({
861
- taskId: task.id,
862
- reason,
863
- status: markedSent ? "post_send_cleanup_failed_marked_sent" : "post_send_cleanup_failed",
864
- messageDelivered: true
865
- });
866
- }
867
- async function processTask(task) {
868
- let sendResult;
869
- try {
870
- sendResult = await processSingleMessage(task, { ...ctx, db, masterKey }, masterKey);
871
- } catch (error) {
872
- await handleDeliveryFailure(task, error.message || "\u6D88\u606F\u53D1\u9001\u5931\u8D25");
873
- return;
874
- }
875
- if (!sendResult.success) {
876
- await handleDeliveryFailure(task, sendResult.error || "\u6D88\u606F\u53D1\u9001\u5931\u8D25");
877
- return;
878
- }
879
- try {
880
- const userKey = await deriveUserEncryptionKey(task.user_id, masterKey);
881
- const decryptedPayload = JSON.parse(await decryptFromStorage(task.encrypted_payload, userKey));
882
- if (decryptedPayload.recurrenceType === "none") {
883
- await db.deleteTaskById(task.id);
884
- results.deletedOnceOffTasks++;
885
- } else {
886
- let nextSendAt;
887
- const currentSendAt = new Date(task.next_send_at);
888
- if (decryptedPayload.recurrenceType === "daily") {
889
- nextSendAt = new Date(currentSendAt.getTime() + 24 * 60 * 60 * 1e3);
890
- } else if (decryptedPayload.recurrenceType === "weekly") {
891
- nextSendAt = new Date(currentSendAt.getTime() + 7 * 24 * 60 * 60 * 1e3);
892
- }
893
- await db.updateTaskById(task.id, { next_send_at: nextSendAt.toISOString(), retry_count: 0 });
894
- results.updatedRecurringTasks++;
895
- }
896
- results.successCount++;
897
- } catch (error) {
898
- await handlePostSendPersistenceFailure(task, error.message || "\u53D1\u9001\u540E\u72B6\u6001\u66F4\u65B0\u5931\u8D25");
899
- }
900
- }
901
- const taskQueue = [...tasks];
902
- const processing = [];
903
- while (taskQueue.length > 0 || processing.length > 0) {
904
- while (processing.length < MAX_CONCURRENT && taskQueue.length > 0) {
905
- const task = taskQueue.shift();
906
- const promise = processTask(task);
907
- processing.push(promise);
908
- promise.finally(() => {
909
- const index = processing.indexOf(promise);
910
- if (index > -1) processing.splice(index, 1);
911
- });
912
- }
913
- if (processing.length > 0) {
914
- await Promise.race(processing);
915
- }
916
- }
917
- await db.cleanupOldTasks(7);
918
- const executionTime = Date.now() - startTime;
919
- return {
920
- totalTasks: results.totalTasks,
921
- successCount: results.successCount,
922
- failedCount: results.failedCount,
923
- processedAt: (/* @__PURE__ */ new Date()).toISOString(),
924
- executionTime,
925
- details: {
926
- deletedOnceOffTasks: results.deletedOnceOffTasks,
927
- updatedRecurringTasks: results.updatedRecurringTasks,
928
- failedTasks: results.failedTasks
929
- }
930
- };
931
- }
932
-
933
- // src/server/handlers/update-message.js
934
- function createUpdateMessageHandler(ctx) {
935
- async function PUT(url, headers, body) {
936
- const tenantResult = await ctx.tenantManager.resolveTenant(headers, { url });
937
- if (!tenantResult.ok) {
938
- return tenantResult.error;
939
- }
940
- const tenantCtx = tenantResult.context;
941
- const db = tenantCtx.db;
942
- const masterKey = tenantCtx.masterKey;
943
- const u = new URL(url, "https://dummy");
944
- const taskUuid = u.searchParams.get("id");
945
- if (!taskUuid) {
946
- return { status: 400, body: { success: false, error: { code: "TASK_ID_REQUIRED", message: "\u7F3A\u5C11\u4EFB\u52A1ID" } } };
947
- }
948
- const userId = getHeader(headers, "x-user-id");
949
- if (!userId) {
950
- return { status: 400, body: { success: false, error: { code: "USER_ID_REQUIRED", message: "\u7F3A\u5C11\u7528\u6237\u6807\u8BC6\u7B26" } } };
951
- }
952
- if (!isValidUUIDv4(userId)) {
953
- return { status: 400, body: { success: false, error: { code: "INVALID_USER_ID_FORMAT", message: "X-User-Id \u5FC5\u987B\u662F UUID v4 \u683C\u5F0F" } } };
954
- }
955
- const isEncrypted = getHeader(headers, "x-payload-encrypted") === "true";
956
- const encryptionVersion = getHeader(headers, "x-encryption-version");
957
- if (!isEncrypted) {
958
- return { status: 400, body: { success: false, error: { code: "ENCRYPTION_REQUIRED", message: "\u8BF7\u6C42\u4F53\u5FC5\u987B\u52A0\u5BC6" } } };
959
- }
960
- if (encryptionVersion !== "1") {
961
- return { status: 400, body: { success: false, error: { code: "UNSUPPORTED_ENCRYPTION_VERSION", message: "\u52A0\u5BC6\u7248\u672C\u4E0D\u652F\u6301" } } };
962
- }
963
- const parsedBody = parseEncryptedBody(body);
964
- if (!parsedBody.ok) {
965
- return { status: 400, body: { success: false, error: parsedBody.error } };
966
- }
967
- const encryptedBody = parsedBody.data;
968
- const userKey = await deriveUserEncryptionKey(userId, masterKey);
969
- let updates;
970
- try {
971
- updates = await decryptPayload(encryptedBody, userKey);
972
- } catch (_error) {
973
- return { status: 400, body: { success: false, error: { code: "DECRYPTION_FAILED", message: "\u8BF7\u6C42\u4F53\u89E3\u5BC6\u5931\u8D25" } } };
974
- }
975
- if (!isPlainObject(updates)) {
976
- return { status: 400, body: { success: false, error: { code: "INVALID_UPDATE_DATA", message: "\u66F4\u65B0\u6570\u636E\u683C\u5F0F\u9519\u8BEF" } } };
977
- }
978
- if (updates.nextSendAt && !isValidISO8601(updates.nextSendAt)) {
979
- return { status: 400, body: { success: false, error: { code: "INVALID_UPDATE_DATA", message: "\u66F4\u65B0\u6570\u636E\u683C\u5F0F\u9519\u8BEF", details: { invalidFields: ["nextSendAt"] } } } };
980
- }
981
- if (updates.recurrenceType && !["none", "daily", "weekly"].includes(updates.recurrenceType)) {
982
- return { status: 400, body: { success: false, error: { code: "INVALID_UPDATE_DATA", message: "\u66F4\u65B0\u6570\u636E\u683C\u5F0F\u9519\u8BEF", details: { invalidFields: ["recurrenceType"] } } } };
983
- }
984
- if (Object.prototype.hasOwnProperty.call(updates, "maxTokens") && updates.maxTokens !== null && (!Number.isInteger(updates.maxTokens) || updates.maxTokens <= 0)) {
985
- return { status: 400, body: { success: false, error: { code: "INVALID_UPDATE_DATA", message: "\u66F4\u65B0\u6570\u636E\u683C\u5F0F\u9519\u8BEF", details: { invalidFields: ["maxTokens"] } } } };
986
- }
987
- if (updates.completePrompt && updates.messages !== void 0 && updates.messages !== null) {
988
- return { status: 400, body: { success: false, error: { code: "INVALID_UPDATE_DATA", message: "completePrompt \u4E0E messages \u4E0D\u80FD\u540C\u65F6\u66F4\u65B0\uFF08\u4E8C\u9009\u4E00\uFF09", details: { invalidFields: ["completePrompt", "messages"] } } } };
989
- }
990
- if (updates.messages !== void 0 && updates.messages !== null) {
991
- const msgErr = validateLlmMessagesArray(updates.messages);
992
- if (msgErr) {
993
- return { status: 400, body: { success: false, error: { code: "INVALID_UPDATE_DATA", message: msgErr, details: { invalidFields: ["messages"] } } } };
994
- }
995
- }
996
- if (Object.prototype.hasOwnProperty.call(updates, "temperature") && updates.temperature !== null && (typeof updates.temperature !== "number" || !Number.isFinite(updates.temperature))) {
997
- return { status: 400, body: { success: false, error: { code: "INVALID_UPDATE_DATA", message: "\u66F4\u65B0\u6570\u636E\u683C\u5F0F\u9519\u8BEF", details: { invalidFields: ["temperature"] } } } };
998
- }
999
- if (Object.prototype.hasOwnProperty.call(updates, "splitPattern")) {
1000
- const splitErr = validateSplitPattern(updates.splitPattern);
1001
- if (splitErr) {
1002
- return { status: 400, body: { success: false, error: { code: "INVALID_UPDATE_DATA", message: splitErr, details: { invalidFields: ["splitPattern"] } } } };
1003
- }
1004
- }
1005
- if (Object.prototype.hasOwnProperty.call(updates, "avatarUrl")) {
1006
- const avatarErr = _amsgshared.validateAvatarUrl.call(void 0, updates.avatarUrl);
1007
- if (avatarErr) {
1008
- console.warn("[amsg-server] update-message avatarUrl \u4E0D\u5408\u6CD5\uFF0C\u5DF2\u5FFD\u7565\uFF1A", avatarErr);
1009
- delete updates.avatarUrl;
1010
- }
1011
- }
1012
- const existingTask = await db.getTaskByUuid(taskUuid, userId);
1013
- if (!existingTask) {
1014
- const taskStatus = await db.getTaskStatus(taskUuid, userId);
1015
- if (!taskStatus) {
1016
- return { status: 404, body: { success: false, error: { code: "TASK_NOT_FOUND", message: "\u6307\u5B9A\u7684\u4EFB\u52A1\u4E0D\u5B58\u5728\u6216\u5DF2\u88AB\u5220\u9664" } } };
1017
- }
1018
- return { status: 409, body: { success: false, error: { code: "TASK_ALREADY_COMPLETED", message: "\u4EFB\u52A1\u5DF2\u5B8C\u6210\u6216\u5DF2\u5931\u8D25\uFF0C\u65E0\u6CD5\u66F4\u65B0" } } };
1019
- }
1020
- const existingData = JSON.parse(await decryptFromStorage(existingTask.encrypted_payload, userKey));
1021
- const promptUpdates = {};
1022
- if (updates.completePrompt) {
1023
- promptUpdates.completePrompt = updates.completePrompt;
1024
- promptUpdates.messages = null;
1025
- } else if (updates.messages !== void 0 && updates.messages !== null) {
1026
- promptUpdates.messages = updates.messages;
1027
- promptUpdates.completePrompt = null;
1028
- }
1029
- const updatedData = {
1030
- ...existingData,
1031
- ...promptUpdates,
1032
- ...updates.userMessage && { userMessage: updates.userMessage },
1033
- ...updates.recurrenceType && { recurrenceType: updates.recurrenceType },
1034
- ...updates.avatarUrl && { avatarUrl: updates.avatarUrl },
1035
- ...updates.metadata && { metadata: updates.metadata },
1036
- ...Object.prototype.hasOwnProperty.call(updates, "maxTokens") && { maxTokens: _nullishCoalesce(updates.maxTokens, () => ( null)) },
1037
- ...Object.prototype.hasOwnProperty.call(updates, "temperature") && { temperature: _nullishCoalesce(updates.temperature, () => ( null)) },
1038
- // splitPattern: hasOwnProperty so that explicit `null` (= revert to
1039
- // default) doesn't get swallowed by truthy-spread the way the optional
1040
- // string fields above are.
1041
- ...Object.prototype.hasOwnProperty.call(updates, "splitPattern") && { splitPattern: _nullishCoalesce(updates.splitPattern, () => ( null)) }
1042
- };
1043
- const encryptedPayload = await encryptForStorage(JSON.stringify(updatedData), userKey);
1044
- const extraFields = updates.nextSendAt ? { next_send_at: updates.nextSendAt } : void 0;
1045
- const result = await db.updateTaskByUuid(taskUuid, userId, encryptedPayload, extraFields);
1046
- if (!result) {
1047
- return { status: 409, body: { success: false, error: { code: "UPDATE_CONFLICT", message: "\u4EFB\u52A1\u66F4\u65B0\u5931\u8D25\uFF0C\u4EFB\u52A1\u53EF\u80FD\u5DF2\u88AB\u4FEE\u6539\u6216\u5220\u9664" } } };
1048
- }
1049
- return {
1050
- status: 200,
1051
- body: {
1052
- success: true,
1053
- data: {
1054
- uuid: taskUuid,
1055
- updatedFields: Object.keys(updates),
1056
- updatedAt: result.updated_at
1057
- }
1058
- }
1059
- };
1060
- }
1061
- return { PUT };
1062
- }
1063
-
1064
- // src/server/handlers/cancel-message.js
1065
- function createCancelMessageHandler(ctx) {
1066
- async function DELETE(url, headers) {
1067
- const tenantResult = await ctx.tenantManager.resolveTenant(headers, { url });
1068
- if (!tenantResult.ok) {
1069
- return tenantResult.error;
1070
- }
1071
- const db = tenantResult.context.db;
1072
- const u = new URL(url, "https://dummy");
1073
- const taskUuid = u.searchParams.get("id");
1074
- if (!taskUuid) {
1075
- return { status: 400, body: { success: false, error: { code: "TASK_ID_REQUIRED", message: "\u7F3A\u5C11\u4EFB\u52A1ID" } } };
1076
- }
1077
- const userId = getHeader(headers, "x-user-id");
1078
- if (!userId) {
1079
- return { status: 400, body: { success: false, error: { code: "USER_ID_REQUIRED", message: "\u7F3A\u5C11\u7528\u6237\u6807\u8BC6\u7B26" } } };
1080
- }
1081
- if (!isValidUUIDv4(userId)) {
1082
- return { status: 400, body: { success: false, error: { code: "INVALID_USER_ID_FORMAT", message: "X-User-Id \u5FC5\u987B\u662F UUID v4 \u683C\u5F0F" } } };
1083
- }
1084
- const deleted = await db.deleteTaskByUuid(taskUuid, userId);
1085
- if (!deleted) {
1086
- return {
1087
- status: 404,
1088
- body: { success: false, error: { code: "TASK_NOT_FOUND", message: "\u6307\u5B9A\u7684\u4EFB\u52A1\u4E0D\u5B58\u5728\u6216\u5DF2\u88AB\u5220\u9664" } }
1089
- };
1090
- }
1091
- return {
1092
- status: 200,
1093
- body: {
1094
- success: true,
1095
- data: { uuid: taskUuid, message: "\u4EFB\u52A1\u5DF2\u6210\u529F\u53D6\u6D88", deletedAt: (/* @__PURE__ */ new Date()).toISOString() }
1096
- }
1097
- };
1098
- }
1099
- return { DELETE };
1100
- }
1101
-
1102
- // src/server/handlers/messages.js
1103
- function createMessagesHandler(ctx) {
1104
- async function GET(url, headers) {
1105
- const tenantResult = await ctx.tenantManager.resolveTenant(headers, { url });
1106
- if (!tenantResult.ok) {
1107
- return tenantResult.error;
1108
- }
1109
- const tenantCtx = tenantResult.context;
1110
- const db = tenantCtx.db;
1111
- const masterKey = tenantCtx.masterKey;
1112
- const userId = getHeader(headers, "x-user-id");
1113
- if (!userId) {
1114
- return {
1115
- status: 400,
1116
- body: { success: false, error: { code: "USER_ID_REQUIRED", message: "\u5FC5\u987B\u63D0\u4F9B X-User-Id \u8BF7\u6C42\u5934" } }
1117
- };
1118
- }
1119
- if (!isValidUUIDv4(userId)) {
1120
- return {
1121
- status: 400,
1122
- body: { success: false, error: { code: "INVALID_USER_ID_FORMAT", message: "X-User-Id \u5FC5\u987B\u662F UUID v4 \u683C\u5F0F" } }
1123
- };
1124
- }
1125
- const u = new URL(url, "https://dummy");
1126
- const status = u.searchParams.get("status") || "all";
1127
- const limit = Math.min(parseInt(u.searchParams.get("limit") || "20", 10), 100);
1128
- const offset = parseInt(u.searchParams.get("offset") || "0", 10);
1129
- if (isNaN(limit) || limit < 1) {
1130
- return { status: 400, body: { success: false, error: { code: "INVALID_PARAMETERS", message: "limit \u53C2\u6570\u65E0\u6548\uFF0C\u5FC5\u987B\u4E3A\u6B63\u6574\u6570" } } };
1131
- }
1132
- if (isNaN(offset) || offset < 0) {
1133
- return { status: 400, body: { success: false, error: { code: "INVALID_PARAMETERS", message: "offset \u53C2\u6570\u65E0\u6548\uFF0C\u5FC5\u987B\u4E3A\u975E\u8D1F\u6574\u6570" } } };
1134
- }
1135
- const { tasks, total } = await db.listTasks(userId, { status, limit, offset });
1136
- const userKey = await deriveUserEncryptionKey(userId, masterKey);
1137
- const decryptedTasks = await Promise.all(tasks.map(async (task) => {
1138
- const decrypted = JSON.parse(await decryptFromStorage(task.encrypted_payload, userKey));
1139
- return {
1140
- id: task.id,
1141
- uuid: task.uuid,
1142
- contactName: decrypted.contactName,
1143
- messageType: task.message_type,
1144
- messageSubtype: decrypted.messageSubtype,
1145
- nextSendAt: task.next_send_at,
1146
- recurrenceType: decrypted.recurrenceType,
1147
- status: task.status,
1148
- retryCount: task.retry_count,
1149
- createdAt: task.created_at,
1150
- updatedAt: task.updated_at
1151
- };
1152
- }));
1153
- const responsePayload = {
1154
- tasks: decryptedTasks,
1155
- pagination: { total, limit, offset, hasMore: offset + limit < total }
1156
- };
1157
- const encryptedResponse = await encryptPayload(responsePayload, userKey);
1158
- return {
1159
- status: 200,
1160
- body: {
1161
- success: true,
1162
- encrypted: true,
1163
- version: 1,
1164
- data: encryptedResponse
1165
- }
1166
- };
1167
- }
1168
- return { GET };
1169
- }
1170
-
1171
- // src/server/adapters/schema.sqlite.js
1172
- var SQLITE_TABLE_SQL = `
1173
- CREATE TABLE IF NOT EXISTS scheduled_messages (
1174
- id INTEGER PRIMARY KEY AUTOINCREMENT,
1175
- user_id TEXT NOT NULL,
1176
- uuid TEXT,
1177
- encrypted_payload TEXT NOT NULL,
1178
- message_type TEXT NOT NULL CHECK (message_type IN ('fixed', 'prompted', 'auto', 'instant')),
1179
- next_send_at TEXT NOT NULL,
1180
- status TEXT NOT NULL DEFAULT 'pending' CHECK (status IN ('pending', 'sent', 'failed')),
1181
- retry_count INTEGER NOT NULL DEFAULT 0,
1182
- created_at TEXT NOT NULL,
1183
- updated_at TEXT NOT NULL
1184
- )
1185
- `;
1186
- var SQLITE_INDEXES = [
1187
- {
1188
- name: "idx_pending_tasks_optimized",
1189
- sql: `CREATE INDEX IF NOT EXISTS idx_pending_tasks_optimized
1190
- ON scheduled_messages (status, next_send_at, id, retry_count)
1191
- WHERE status = 'pending'`,
1192
- description: "Main query index (Cron Job finds pending tasks)",
1193
- critical: false
1194
- },
1195
- {
1196
- name: "idx_cleanup_completed",
1197
- sql: `CREATE INDEX IF NOT EXISTS idx_cleanup_completed
1198
- ON scheduled_messages (status, updated_at)
1199
- WHERE status IN ('sent', 'failed')`,
1200
- description: "Cleanup query index",
1201
- critical: false
1202
- },
1203
- {
1204
- name: "idx_failed_retry",
1205
- sql: `CREATE INDEX IF NOT EXISTS idx_failed_retry
1206
- ON scheduled_messages (status, retry_count, next_send_at)
1207
- WHERE status = 'failed' AND retry_count < 3`,
1208
- description: "Failed retry index",
1209
- critical: false
1210
- },
1211
- {
1212
- name: "idx_user_id",
1213
- sql: `CREATE INDEX IF NOT EXISTS idx_user_id
1214
- ON scheduled_messages (user_id)`,
1215
- description: "User task query index",
1216
- critical: false
1217
- },
1218
- {
1219
- name: "uidx_uuid",
1220
- sql: `CREATE UNIQUE INDEX IF NOT EXISTS uidx_uuid
1221
- ON scheduled_messages (uuid)
1222
- WHERE uuid IS NOT NULL`,
1223
- description: "UUID uniqueness guard",
1224
- critical: true
1225
- }
1226
- ];
1227
-
1228
- // src/server/adapters/d1.js
1229
- var UPDATABLE_COLUMNS = /* @__PURE__ */ new Set([
1230
- "user_id",
1231
- "uuid",
1232
- "encrypted_payload",
1233
- "message_type",
1234
- "next_send_at",
1235
- "status",
1236
- "retry_count",
1237
- "created_at",
1238
- "updated_at"
1239
- ]);
1240
- var D1Adapter = class {
1241
- /** @param {{ prepare: (sql: string) => any }} db - Cloudflare D1 binding */
1242
- constructor(db) {
1243
- this._db = db;
1244
- }
1245
- /** @private */
1246
- _now() {
1247
- return (/* @__PURE__ */ new Date()).toISOString();
1248
- }
1249
- /** @private */
1250
- _iso(value) {
1251
- const d = new Date(value);
1252
- if (Number.isNaN(d.getTime())) {
1253
- throw new Error(`[amsg-server D1] invalid timestamp: ${value}`);
1254
- }
1255
- return d.toISOString();
1256
- }
1257
- async initSchema() {
1258
- await this._db.prepare(SQLITE_TABLE_SQL).run();
1259
- const indexResults = [];
1260
- for (const index of SQLITE_INDEXES) {
1261
- try {
1262
- await this._db.prepare(index.sql).run();
1263
- indexResults.push({ name: index.name, status: "success", description: index.description, critical: !!index.critical });
1264
- } catch (error) {
1265
- indexResults.push({ name: index.name, status: "failed", description: index.description, critical: !!index.critical, error: error.message });
1266
- }
1267
- }
1268
- const criticalFailures = indexResults.filter((i) => i.critical && i.status === "failed");
1269
- if (criticalFailures.length > 0) {
1270
- const names = criticalFailures.map((i) => i.name).join(", ");
1271
- throw new Error(
1272
- `Critical index creation failed (${names}). Please remove duplicate UUID rows and run initSchema again.`
1273
- );
1274
- }
1275
- return {
1276
- columnsCreated: 10,
1277
- indexesCreated: indexResults.filter((r) => r.status === "success").length,
1278
- indexesFailed: indexResults.filter((r) => r.status === "failed").length,
1279
- columns: [],
1280
- indexes: indexResults
1281
- };
1282
- }
1283
- async dropSchema() {
1284
- await this._db.prepare("DROP TABLE IF EXISTS scheduled_messages").run();
1285
- }
1286
- async createTask(params) {
1287
- const now = this._now();
1288
- const nextSendAt = this._iso(params.next_send_at);
1289
- const res = await this._db.prepare(
1290
- `INSERT INTO scheduled_messages
1291
- (user_id, uuid, encrypted_payload, next_send_at, message_type, status, retry_count, created_at, updated_at)
1292
- VALUES (?, ?, ?, ?, ?, 'pending', 0, ?, ?)`
1293
- ).bind(params.user_id, params.uuid, params.encrypted_payload, nextSendAt, params.message_type, now, now).run();
1294
- const id = res.meta.last_row_id;
1295
- return this._db.prepare(
1296
- `SELECT id, uuid, next_send_at, status, created_at FROM scheduled_messages WHERE id = ?`
1297
- ).bind(id).first();
1298
- }
1299
- async getTaskByUuid(uuid, userId) {
1300
- return this._db.prepare(
1301
- `SELECT id, user_id, uuid, encrypted_payload, message_type, next_send_at, status, retry_count
1302
- FROM scheduled_messages
1303
- WHERE uuid = ? AND user_id = ? AND status = 'pending'
1304
- LIMIT 1`
1305
- ).bind(uuid, userId).first();
1306
- }
1307
- async getTaskByUuidOnly(uuid) {
1308
- return this._db.prepare(
1309
- `SELECT id, user_id, uuid, encrypted_payload, message_type, next_send_at, status, retry_count
1310
- FROM scheduled_messages
1311
- WHERE uuid = ? AND status = 'pending'
1312
- LIMIT 1`
1313
- ).bind(uuid).first();
1314
- }
1315
- async updateTaskById(taskId, updates) {
1316
- const sets = [];
1317
- const values = [];
1318
- for (const [key, value] of Object.entries(updates)) {
1319
- if (!UPDATABLE_COLUMNS.has(key)) {
1320
- throw new Error(`[amsg-server D1] rejected unknown update column: ${key}`);
1321
- }
1322
- sets.push(`${key} = ?`);
1323
- values.push(key === "next_send_at" ? this._iso(value) : value);
1324
- }
1325
- if (!Object.prototype.hasOwnProperty.call(updates, "updated_at")) {
1326
- sets.push("updated_at = ?");
1327
- values.push(this._now());
1328
- }
1329
- values.push(taskId);
1330
- await this._db.prepare(
1331
- `UPDATE scheduled_messages SET ${sets.join(", ")} WHERE id = ?`
1332
- ).bind(...values).run();
1333
- return this._db.prepare("SELECT * FROM scheduled_messages WHERE id = ?").bind(taskId).first();
1334
- }
1335
- async updateTaskByUuid(uuid, userId, encryptedPayload, extraFields) {
1336
- const now = this._now();
1337
- const sets = ["encrypted_payload = ?", "updated_at = ?"];
1338
- const values = [encryptedPayload, now];
1339
- if (extraFields) {
1340
- for (const [key, value] of Object.entries(extraFields)) {
1341
- if (!UPDATABLE_COLUMNS.has(key)) {
1342
- throw new Error(`[amsg-server D1] rejected unknown update column: ${key}`);
1343
- }
1344
- sets.push(`${key} = ?`);
1345
- values.push(key === "next_send_at" ? this._iso(value) : value);
1346
- }
1347
- }
1348
- values.push(uuid, userId);
1349
- const res = await this._db.prepare(
1350
- `UPDATE scheduled_messages SET ${sets.join(", ")}
1351
- WHERE uuid = ? AND user_id = ? AND status = 'pending'`
1352
- ).bind(...values).run();
1353
- if (!res.meta.changes) return null;
1354
- return { uuid, updated_at: now };
1355
- }
1356
- async deleteTaskById(taskId) {
1357
- const res = await this._db.prepare("DELETE FROM scheduled_messages WHERE id = ?").bind(taskId).run();
1358
- return res.meta.changes > 0;
1359
- }
1360
- async deleteTaskByUuid(uuid, userId) {
1361
- const res = await this._db.prepare(
1362
- "DELETE FROM scheduled_messages WHERE uuid = ? AND user_id = ?"
1363
- ).bind(uuid, userId).run();
1364
- return res.meta.changes > 0;
1365
- }
1366
- async getPendingTasks(limit = 50) {
1367
- const res = await this._db.prepare(
1368
- `SELECT id, user_id, uuid, encrypted_payload, message_type, next_send_at, status, retry_count
1369
- FROM scheduled_messages
1370
- WHERE status = 'pending' AND next_send_at <= ?
1371
- ORDER BY next_send_at ASC
1372
- LIMIT ?`
1373
- ).bind(this._now(), limit).all();
1374
- return res.results || [];
1375
- }
1376
- async listTasks(userId, opts = {}) {
1377
- const { status = "all", limit = 20, offset = 0 } = opts;
1378
- const conditions = ["user_id = ?"];
1379
- const params = [userId];
1380
- if (status !== "all") {
1381
- conditions.push("status = ?");
1382
- params.push(status);
1383
- }
1384
- const where = conditions.join(" AND ");
1385
- const countRow = await this._db.prepare(
1386
- `SELECT COUNT(*) as count FROM scheduled_messages WHERE ${where}`
1387
- ).bind(...params).first();
1388
- const total = Number(countRow.count) || 0;
1389
- const res = await this._db.prepare(
1390
- `SELECT id, user_id, uuid, encrypted_payload, message_type, next_send_at, status, retry_count, created_at, updated_at
1391
- FROM scheduled_messages
1392
- WHERE ${where}
1393
- ORDER BY next_send_at ASC
1394
- LIMIT ? OFFSET ?`
1395
- ).bind(...params, limit, offset).all();
1396
- return { tasks: res.results || [], total };
1397
- }
1398
- async cleanupOldTasks(days = 7) {
1399
- const safeDays = Math.max(1, Math.floor(Number(days)));
1400
- const cutoff = new Date(Date.now() - safeDays * 24 * 60 * 60 * 1e3).toISOString();
1401
- const res = await this._db.prepare(
1402
- `DELETE FROM scheduled_messages
1403
- WHERE status IN ('sent', 'failed') AND updated_at < ?`
1404
- ).bind(cutoff).run();
1405
- return res.meta.changes || 0;
1406
- }
1407
- async getTaskStatus(uuid, userId) {
1408
- const row = await this._db.prepare(
1409
- "SELECT status FROM scheduled_messages WHERE uuid = ? AND user_id = ? LIMIT 1"
1410
- ).bind(uuid, userId).first();
1411
- return row ? row.status : null;
1412
- }
1413
- };
1414
- function createD1Adapter(db) {
1415
- if (!db || typeof db.prepare !== "function") {
1416
- throw new Error("[amsg-server] createD1Adapter requires a D1 database binding (env.DB)");
1417
- }
1418
- return new D1Adapter(db);
1419
- }
1420
-
1421
- // src/server/lib/constant-time.js
1422
- async function constantTimeEqual(a, b) {
1423
- const enc = new TextEncoder();
1424
- const keyBytes = globalThis.crypto.getRandomValues(new Uint8Array(32));
1425
- const key = await globalThis.crypto.subtle.importKey(
1426
- "raw",
1427
- keyBytes,
1428
- { name: "HMAC", hash: "SHA-256" },
1429
- false,
1430
- ["sign"]
1431
- );
1432
- const da = new Uint8Array(await globalThis.crypto.subtle.sign("HMAC", key, enc.encode(String(a))));
1433
- const db = new Uint8Array(await globalThis.crypto.subtle.sign("HMAC", key, enc.encode(String(b))));
1434
- let diff = 0;
1435
- for (let i = 0; i < da.length; i++) {
1436
- diff |= da[i] ^ db[i];
1437
- }
1438
- return diff === 0;
1439
- }
1440
-
1441
- // src/server/tenant/single-user-context.js
1442
- function createSingleUserContextManager({ db, masterKey, serverToken } = {}) {
1443
- if (!db) throw new Error("[amsg-server single-user] db (adapter) is required");
1444
- if (!masterKey) throw new Error("[amsg-server single-user] masterKey is required");
1445
- const token = String(serverToken || "").trim();
1446
- async function isAuthorized(headers) {
1447
- if (!token) return true;
1448
- const provided = getHeader(headers, "x-client-token");
1449
- if (!provided) return false;
1450
- return constantTimeEqual(provided, token);
1451
- }
1452
- async function resolveTenant(headers) {
1453
- if (!await isAuthorized(headers)) {
1454
- return {
1455
- ok: false,
1456
- error: {
1457
- status: 401,
1458
- body: { success: false, error: { code: "INVALID_CLIENT_TOKEN", message: "\u5171\u4EAB\u5BC6\u94A5\u65E0\u6548\u6216\u7F3A\u5931" } }
1459
- }
1460
- };
1461
- }
1462
- return {
1463
- ok: true,
1464
- context: { tenantId: "single", tokenType: "tenant", db, masterKey }
1465
- };
1466
- }
1467
- async function initializeTenant() {
1468
- const schema = await db.initSchema();
1469
- return { tenantId: "single", schema };
1470
- }
1471
- return { resolveTenant, initializeTenant };
1472
- }
1473
-
1474
- // src/server/handlers/single-user-init.js
1475
- function createSingleUserInitHandler(ctx) {
1476
- async function POST(headers) {
1477
- const auth = await ctx.tenantManager.resolveTenant(headers || {});
1478
- if (!auth.ok) {
1479
- return auth.error;
1480
- }
1481
- try {
1482
- const result = await ctx.tenantManager.initializeTenant();
1483
- return {
1484
- status: 200,
1485
- body: { success: true, data: { tenantId: result.tenantId, schema: result.schema } }
1486
- };
1487
- } catch (error) {
1488
- return {
1489
- status: 500,
1490
- body: { success: false, error: { code: "INIT_FAILED", message: error.message } }
1491
- };
1492
- }
1493
- }
1494
- return { POST };
1495
- }
1496
-
1497
- // src/server/handlers/vapid-public-key.js
1498
- function createVapidPublicKeyHandler(ctx) {
1499
- async function GET(url, headers) {
1500
- const effectiveHeaders = headers || url || {};
1501
- const tenantResult = await ctx.tenantManager.resolveTenant(effectiveHeaders);
1502
- if (!tenantResult.ok) {
1503
- return tenantResult.error;
1504
- }
1505
- const publicKey = ctx.vapid && ctx.vapid.publicKey;
1506
- if (!publicKey) {
1507
- return {
1508
- status: 503,
1509
- body: {
1510
- success: false,
1511
- error: {
1512
- code: "VAPID_NOT_CONFIGURED",
1513
- message: "VAPID \u516C\u94A5\u672A\u914D\u7F6E\uFF1A\u8BF7\u4E3A\u672C Worker \u8BBE\u7F6E VAPID_PUBLIC_KEY"
1514
- }
1515
- }
1516
- };
1517
- }
1518
- return {
1519
- status: 200,
1520
- body: { success: true, publicKey }
1521
- };
1522
- }
1523
- return { GET };
1524
- }
1525
-
1526
- // src/server/single-user.js
1527
- function createSingleUserServer(config) {
1528
- if (!config || !config.db) throw new Error("[amsg-server single-user] config.db is required");
1529
- if (!config.masterKey) throw new Error("[amsg-server single-user] config.masterKey is required");
1530
- const vapid = config.vapid || {};
1531
- const tenantManager = createSingleUserContextManager({
1532
- db: config.db,
1533
- masterKey: config.masterKey,
1534
- serverToken: config.serverToken
1535
- });
1536
- const ctx = {
1537
- vapid: {
1538
- email: vapid.email || "",
1539
- publicKey: vapid.publicKey || "",
1540
- privateKey: vapid.privateKey || ""
1541
- },
1542
- webpush: config.webpush || null,
1543
- tenantManager
1544
- };
1545
- return {
1546
- ctx,
1547
- handlers: {
1548
- init: createSingleUserInitHandler(ctx),
1549
- getUserKey: createGetUserKeyHandler(ctx),
1550
- scheduleMessage: createScheduleMessageHandler(ctx),
1551
- updateMessage: createUpdateMessageHandler(ctx),
1552
- cancelMessage: createCancelMessageHandler(ctx),
1553
- messages: createMessagesHandler(ctx),
1554
- vapidPublicKey: createVapidPublicKeyHandler(ctx)
1555
- }
1556
- };
1557
- }
1558
-
1559
- // src/server/lib/webpush-webcrypto.js
1560
-
1561
- var KEY_INFO_PREFIX = utf8("WebPush: info\0");
1562
- var CEK_INFO = utf8("Content-Encoding: aes128gcm\0");
1563
- var NONCE_INFO = utf8("Content-Encoding: nonce\0");
1564
- var VAPID_DEFAULT_TTL = 60;
1565
- var VAPID_TOKEN_LIFETIME = 12 * 3600;
1566
- var RECORD_SIZE = 4096;
1567
- async function sendWebPush({ subscription, payload, vapid, ttl, fetch: fetchImpl }) {
1568
- if (!subscription || typeof subscription.endpoint !== "string") {
1569
- throw new Error("sendWebPush: invalid subscription");
1570
- }
1571
- if (typeof payload !== "string") {
1572
- throw new Error("sendWebPush: payload must be a string");
1573
- }
1574
- if (!vapid || !vapid.email || !vapid.publicKey || !vapid.privateKey) {
1575
- throw new Error("VAPID_CONFIG_MISSING");
1576
- }
1577
- const subscriptionKeys = subscription.keys || {};
1578
- if (typeof subscriptionKeys.p256dh !== "string" || typeof subscriptionKeys.auth !== "string") {
1579
- throw new Error("sendWebPush: subscription.keys.p256dh and .auth are required");
1580
- }
1581
- const encryptedBody = await encryptPushPayload({
1582
- plaintext: utf8(payload),
1583
- uaPublicKey: _amsgshared.base64UrlToBytes.call(void 0, subscriptionKeys.p256dh),
1584
- authSecret: _amsgshared.base64UrlToBytes.call(void 0, subscriptionKeys.auth)
1585
- });
1586
- const jwt = await buildVapidJwt({
1587
- audience: originOf(subscription.endpoint),
1588
- subject: _amsgshared.normalizeVapidSubject.call(void 0, vapid.email),
1589
- publicKey: vapid.publicKey,
1590
- privateKey: vapid.privateKey
1591
- });
1592
- const fetchFn = fetchImpl || globalThis.fetch;
1593
- if (typeof fetchFn !== "function") {
1594
- throw new Error("sendWebPush: no fetch implementation available");
1595
- }
1596
- const res = await fetchFn(subscription.endpoint, {
1597
- method: "POST",
1598
- headers: {
1599
- "Content-Type": "application/octet-stream",
1600
- "Content-Encoding": "aes128gcm",
1601
- "TTL": String(Number.isFinite(ttl) ? ttl : VAPID_DEFAULT_TTL),
1602
- "Authorization": `vapid t=${jwt}, k=${vapid.publicKey}`
1603
- },
1604
- body: encryptedBody
1605
- });
1606
- if (!res.ok) {
1607
- const text = await safeReadText(res);
1608
- const err = new Error(
1609
- `Web Push delivery failed: ${res.status} ${res.statusText || ""}${text ? ` \u2014 ${text}` : ""}`
1610
- );
1611
- err.code = "PUSH_SEND_FAILED";
1612
- err.statusCode = res.status;
1613
- throw err;
1614
- }
1615
- return {
1616
- statusCode: res.status,
1617
- body: await safeReadText(res),
1618
- headers: res.headers
1619
- };
1620
- }
1621
- async function encryptPushPayload({ plaintext, uaPublicKey, authSecret }) {
1622
- const asKeyPair = await globalThis.crypto.subtle.generateKey(
1623
- { name: "ECDH", namedCurve: "P-256" },
1624
- true,
1625
- ["deriveBits"]
1626
- );
1627
- const asPublicRaw = new Uint8Array(
1628
- await globalThis.crypto.subtle.exportKey("raw", asKeyPair.publicKey)
1629
- );
1630
- const uaPublicCryptoKey = await globalThis.crypto.subtle.importKey(
1631
- "raw",
1632
- uaPublicKey,
1633
- { name: "ECDH", namedCurve: "P-256" },
1634
- false,
1635
- []
1636
- );
1637
- const ecdhSecret = new Uint8Array(
1638
- await globalThis.crypto.subtle.deriveBits(
1639
- { name: "ECDH", public: uaPublicCryptoKey },
1640
- asKeyPair.privateKey,
1641
- 256
1642
- )
1643
- );
1644
- const keyInfo = _amsgshared.concatBytes.call(void 0, KEY_INFO_PREFIX, uaPublicKey, asPublicRaw);
1645
- const ikm = await hkdfSha256(authSecret, ecdhSecret, keyInfo, 32);
1646
- const salt = randomBytes(16);
1647
- const cekBytes = await hkdfSha256(salt, ikm, CEK_INFO, 16);
1648
- const cek = await globalThis.crypto.subtle.importKey(
1649
- "raw",
1650
- cekBytes,
1651
- { name: "AES-GCM" },
1652
- false,
1653
- ["encrypt"]
1654
- );
1655
- const nonce = await hkdfSha256(salt, ikm, NONCE_INFO, 12);
1656
- const padded = _amsgshared.concatBytes.call(void 0, plaintext, new Uint8Array([2]));
1657
- const ciphertext = new Uint8Array(
1658
- await globalThis.crypto.subtle.encrypt({ name: "AES-GCM", iv: nonce }, cek, padded)
1659
- );
1660
- const header = new Uint8Array(16 + 4 + 1 + asPublicRaw.byteLength);
1661
- header.set(salt, 0);
1662
- writeUint32BE(header, 16, RECORD_SIZE);
1663
- header[20] = asPublicRaw.byteLength;
1664
- header.set(asPublicRaw, 21);
1665
- return _amsgshared.concatBytes.call(void 0, header, ciphertext);
1666
- }
1667
- async function hkdfSha256(salt, ikm, info, length) {
1668
- const baseKey = await globalThis.crypto.subtle.importKey(
1669
- "raw",
1670
- _amsgshared.toUint8.call(void 0, ikm),
1671
- { name: "HKDF" },
1672
- false,
1673
- ["deriveBits"]
1674
- );
1675
- const bits = await globalThis.crypto.subtle.deriveBits(
1676
- {
1677
- name: "HKDF",
1678
- hash: "SHA-256",
1679
- salt: _amsgshared.toUint8.call(void 0, salt),
1680
- info: _amsgshared.toUint8.call(void 0, info)
1681
- },
1682
- baseKey,
1683
- length * 8
1684
- );
1685
- return new Uint8Array(bits);
1686
- }
1687
- async function buildVapidJwt({ audience, subject, publicKey, privateKey }) {
1688
- const header = jsonToBase64Url({ typ: "JWT", alg: "ES256" });
1689
- const payload = jsonToBase64Url({
1690
- aud: audience,
1691
- exp: Math.floor(Date.now() / 1e3) + VAPID_TOKEN_LIFETIME,
1692
- sub: subject
1693
- });
1694
- const signingInput = utf8(`${header}.${payload}`);
1695
- const pubBytes = _amsgshared.base64UrlToBytes.call(void 0, publicKey);
1696
- const privBytes = _amsgshared.base64UrlToBytes.call(void 0, privateKey);
1697
- if (pubBytes.length !== 65 || pubBytes[0] !== 4) {
1698
- throw new Error("VAPID publicKey must be a 65-byte uncompressed P-256 point (base64url).");
1699
- }
1700
- if (privBytes.length !== 32) {
1701
- throw new Error("VAPID privateKey must be a 32-byte scalar (base64url).");
1702
- }
1703
- const jwk = {
1704
- kty: "EC",
1705
- crv: "P-256",
1706
- d: bytesToBase64Url(privBytes),
1707
- x: bytesToBase64Url(pubBytes.subarray(1, 33)),
1708
- y: bytesToBase64Url(pubBytes.subarray(33, 65)),
1709
- ext: true
1710
- };
1711
- const key = await globalThis.crypto.subtle.importKey(
1712
- "jwk",
1713
- jwk,
1714
- { name: "ECDSA", namedCurve: "P-256" },
1715
- false,
1716
- ["sign"]
1717
- );
1718
- const sig = await globalThis.crypto.subtle.sign(
1719
- { name: "ECDSA", hash: "SHA-256" },
1720
- key,
1721
- signingInput
1722
- );
1723
- return `${header}.${payload}.${bytesToBase64Url(sig)}`;
1724
- }
1725
- function originOf(endpoint) {
1726
- return new URL(endpoint).origin;
1727
- }
1728
- function writeUint32BE(buf, offset, value) {
1729
- buf[offset] = value >>> 24 & 255;
1730
- buf[offset + 1] = value >>> 16 & 255;
1731
- buf[offset + 2] = value >>> 8 & 255;
1732
- buf[offset + 3] = value & 255;
1733
- }
1734
- async function safeReadText(res) {
1735
- try {
1736
- return await res.text();
1737
- } catch (e4) {
1738
- return "";
1739
- }
1740
- }
1741
- var SCHEDULED_DEFAULT_TTL = 2419200;
1742
- function createWebCryptoWebPush(vapid = {}, { ttl = SCHEDULED_DEFAULT_TTL } = {}) {
1743
- return {
1744
- async sendNotification(subscription, payload) {
1745
- return sendWebPush({
1746
- subscription,
1747
- payload,
1748
- ttl,
1749
- vapid: {
1750
- email: vapid.email,
1751
- publicKey: vapid.publicKey,
1752
- privateKey: vapid.privateKey
1753
- },
1754
- fetch: globalThis.fetch
1755
- });
1756
- }
1757
- };
1758
- }
1759
-
1760
- // src/server/cloudflare/single-user-worker.js
1761
- function headersToObject(h) {
1762
- const out = {};
1763
- for (const [k, v] of h) out[k] = v;
1764
- return out;
1765
- }
1766
- function jsonResponse(status, body, extraHeaders) {
1767
- return new Response(JSON.stringify(body), {
1768
- status,
1769
- headers: { "Content-Type": "application/json; charset=utf-8", ...extraHeaders || {} }
1770
- });
1771
- }
1772
- var CORS_ALLOW_HEADERS = "Content-Type, X-User-Id, X-Payload-Encrypted, X-Encryption-Version, X-Response-Encrypted, X-Client-Token";
1773
- var CORS_ALLOW_METHODS = "GET, POST, PUT, DELETE, OPTIONS";
1774
- function corsHeadersFor(cors, requestOrigin) {
1775
- if (!cors || cors.origin == null) return null;
1776
- const allowOrigin = typeof cors.origin === "function" ? cors.origin(requestOrigin) || null : cors.origin;
1777
- if (!allowOrigin) return null;
1778
- const headers = {
1779
- "Access-Control-Allow-Origin": allowOrigin,
1780
- "Access-Control-Allow-Methods": CORS_ALLOW_METHODS,
1781
- "Access-Control-Allow-Headers": cors.allowHeaders || CORS_ALLOW_HEADERS,
1782
- "Access-Control-Max-Age": String(_nullishCoalesce(cors.maxAge, () => ( 86400)))
1783
- };
1784
- if (allowOrigin !== "*") headers["Vary"] = "Origin";
1785
- return headers;
1786
- }
1787
- function createSingleUserCloudflareWorker(buildConfig) {
1788
- async function resolveConfig(env) {
1789
- const cfg = await buildConfig(env);
1790
- if (!cfg.db) cfg.db = createD1Adapter(env.DB);
1791
- return cfg;
1792
- }
1793
- async function fetch2(request, env) {
1794
- try {
1795
- const cfg = await resolveConfig(env);
1796
- const cors = corsHeadersFor(cfg.cors, request.headers.get("origin") || "");
1797
- const method = request.method.toUpperCase();
1798
- if (method === "OPTIONS") {
1799
- return cors ? new Response(null, { status: 204, headers: cors }) : jsonResponse(404, { success: false, error: { code: "NOT_FOUND", message: "Unknown route" } });
1800
- }
1801
- const server = createSingleUserServer(cfg);
1802
- const url = request.url;
1803
- const pathname = new URL(url).pathname.replace(/\/+$/, "") || "/";
1804
- const headers = headersToObject(request.headers);
1805
- let result;
1806
- if (method === "POST" && pathname.endsWith("/init-tenant")) {
1807
- result = await server.handlers.init.POST(headers, await request.text());
1808
- } else if (method === "GET" && pathname.endsWith("/get-user-key")) {
1809
- result = await server.handlers.getUserKey.GET(url, headers);
1810
- } else if (method === "POST" && pathname.endsWith("/schedule-message")) {
1811
- result = await server.handlers.scheduleMessage.POST(headers, await request.text());
1812
- } else if (method === "GET" && pathname.endsWith("/messages")) {
1813
- result = await server.handlers.messages.GET(url, headers);
1814
- } else if (method === "PUT" && pathname.endsWith("/update-message")) {
1815
- result = await server.handlers.updateMessage.PUT(url, headers, await request.text());
1816
- } else if (method === "DELETE" && pathname.endsWith("/cancel-message")) {
1817
- result = await server.handlers.cancelMessage.DELETE(url, headers);
1818
- } else if (method === "GET" && pathname.endsWith("/vapid-public-key")) {
1819
- result = await server.handlers.vapidPublicKey.GET(url, headers);
1820
- } else {
1821
- result = { status: 404, body: { success: false, error: { code: "NOT_FOUND", message: "Unknown route" } } };
1822
- }
1823
- return jsonResponse(result.status, result.body, cors);
1824
- } catch (error) {
1825
- console.error("[amsg single-user] fetch() unhandled error:", error && error.message);
1826
- return jsonResponse(500, { success: false, error: { code: "INTERNAL_ERROR", message: "\u670D\u52A1\u5668\u5185\u90E8\u9519\u8BEF" } });
1827
- }
1828
- }
1829
- async function scheduled(event, env) {
1830
- const cfg = await resolveConfig(env);
1831
- const vapid = cfg.vapid || {};
1832
- if (!cfg.webpush || !vapid.email || !vapid.publicKey || !vapid.privateKey) {
1833
- console.error("[amsg single-user] scheduled(): VAPID/webpush not configured; skipping tick");
1834
- return;
1835
- }
1836
- try {
1837
- await runScheduledTick({ db: cfg.db, masterKey: cfg.masterKey, vapid, webpush: cfg.webpush });
1838
- } catch (error) {
1839
- console.error("[amsg single-user] scheduled(): tick failed:", error && error.message);
1840
- }
1841
- }
1842
- return { fetch: fetch2, scheduled };
1843
- }
1844
-
1845
-
1846
-
1847
-
1848
-
1849
-
1850
-
1851
-
1852
-
1853
-
1854
-
1855
-
1856
-
1857
-
1858
-
1859
-
1860
-
1861
-
1862
-
1863
-
1864
-
1865
-
1866
-
1867
-
1868
-
1869
-
1870
- exports.validateAvatarUrl = _amsgshared.validateAvatarUrl; exports.isValidISO8601 = isValidISO8601; exports.isValidUrl = isValidUrl; exports.isValidUUID = isValidUUID; exports.isValidUUIDv4 = isValidUUIDv4; exports.validateSplitPattern = validateSplitPattern; exports.validateLlmMessagesArray = validateLlmMessagesArray; exports.validateScheduleMessagePayload = validateScheduleMessagePayload; exports.parseJsonBody = parseJsonBody; exports.getHeader = getHeader; exports.deriveUserEncryptionKey = deriveUserEncryptionKey; exports.decryptPayload = decryptPayload; exports.encryptForStorage = encryptForStorage; exports.decryptFromStorage = decryptFromStorage; exports.createGetUserKeyHandler = createGetUserKeyHandler; exports.createScheduleMessageHandler = createScheduleMessageHandler; exports.runScheduledTick = runScheduledTick; exports.createUpdateMessageHandler = createUpdateMessageHandler; exports.createCancelMessageHandler = createCancelMessageHandler; exports.createMessagesHandler = createMessagesHandler; exports.createD1Adapter = createD1Adapter; exports.createSingleUserServer = createSingleUserServer; exports.createWebCryptoWebPush = createWebCryptoWebPush; exports.createSingleUserCloudflareWorker = createSingleUserCloudflareWorker;