@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,2848 +0,0 @@
1
- import { validateAvatarUrl, toUint8, concatBytes, base64UrlToBytes, readReasoningContent, stripReasoningTags, buildReasoningPush, buildContentPush, normalizeVapidSubject } from '@rei-standard/amsg-shared';
2
-
3
- /**
4
- * Validation utility library (SDK version)
5
- * ReiStandard SDK v2.0.1
6
- */
7
-
8
-
9
- /**
10
- * Validate ISO 8601 date string.
11
- * @param {string} dateString
12
- * @returns {boolean}
13
- */
14
- function isValidISO8601(dateString) {
15
- const date = new Date(dateString);
16
- return date instanceof Date && !isNaN(date.getTime());
17
- }
18
-
19
- /**
20
- * Validate URL format.
21
- * @param {string} urlString
22
- * @returns {boolean}
23
- */
24
- function isValidUrl(urlString) {
25
- try {
26
- new URL(urlString);
27
- return true;
28
- } catch {
29
- return false;
30
- }
31
- }
32
-
33
- /**
34
- * Validate UUID format.
35
- * @param {string} uuid
36
- * @returns {boolean}
37
- */
38
- function isValidUUID(uuid) {
39
- const uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
40
- return uuidRegex.test(uuid);
41
- }
42
-
43
- /**
44
- * Validate UUID v4 format.
45
- * @param {string} uuid
46
- * @returns {boolean}
47
- */
48
- function isValidUUIDv4(uuid) {
49
- 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;
50
- return uuidV4Regex.test(uuid);
51
- }
52
-
53
- const VALID_LLM_MESSAGE_ROLES = new Set(['system', 'user', 'assistant', 'tool']);
54
-
55
- const SPLIT_PATTERN_MAX_LENGTH = 200;
56
- const SPLIT_PATTERN_MAX_ITEMS = 10;
57
-
58
- /**
59
- * Validate the optional `splitPattern` field (amsg-server scheduled tasks
60
- * only; amsg-instant 0.8.0 dropped its request-level `splitPattern`).
61
- * Accepts `string`, `string[]`, or absent/null. Returns an error message
62
- * string, or null when valid.
63
- *
64
- * Limits (per-item length ≤ 200, array ≤ 10 items, must compile via
65
- * `new RegExp(item)`) are an **input-size guard**, NOT a ReDoS defense —
66
- * a 6-character pattern like `(a+)+$` is enough to trigger catastrophic
67
- * backtracking. The real backstop is Worker / runtime CPU limits + the
68
- * fact that splitPattern is stored under the user's own encrypted task
69
- * and matched against output from the user's own LLM API key, so the
70
- * blast radius is self-inflicted only (no cross-tenant attack surface).
71
- *
72
- * @param {unknown} value
73
- * @returns {string | null}
74
- */
75
- function validateSplitPattern(value) {
76
- if (value === undefined || value === null) return null;
77
- const isArray = Array.isArray(value);
78
- const items = isArray ? value : [value];
79
- if (isArray && items.length === 0) return null; // empty array = use default
80
- if (items.length > SPLIT_PATTERN_MAX_ITEMS) {
81
- return `splitPattern 数组最多 ${SPLIT_PATTERN_MAX_ITEMS} 项`;
82
- }
83
- for (let i = 0; i < items.length; i++) {
84
- const s = items[i];
85
- const label = isArray ? `splitPattern[${i}]` : 'splitPattern';
86
- if (typeof s !== 'string') return `${label} 必须是字符串`;
87
- if (s.length > SPLIT_PATTERN_MAX_LENGTH) {
88
- return `${label} 不能超过 ${SPLIT_PATTERN_MAX_LENGTH} 字符`;
89
- }
90
- try { new RegExp(s); }
91
- catch (_) { return `${label} 不是有效正则表达式`; }
92
- }
93
- return null;
94
- }
95
-
96
- /**
97
- * Validate an OpenAI-style messages array. Same shape contract as
98
- * `@rei-standard/amsg-instant` (kept in lockstep on purpose — both packages
99
- * end up forwarding this to the same LLM body).
100
- *
101
- * @param {unknown} messages
102
- * @returns {string | null} Error message, or null if valid.
103
- */
104
- function validateLlmMessagesArray(messages) {
105
- if (!Array.isArray(messages) || messages.length === 0) {
106
- return 'messages must be a non-empty array';
107
- }
108
- for (let i = 0; i < messages.length; i++) {
109
- const m = messages[i];
110
- if (!m || typeof m !== 'object' || Array.isArray(m)) {
111
- return `messages[${i}] must be an object`;
112
- }
113
- if (!VALID_LLM_MESSAGE_ROLES.has(m.role)) {
114
- return `messages[${i}].role must be one of system / user / assistant / tool`;
115
- }
116
- if (typeof m.content === 'string') {
117
- if (!m.content) return `messages[${i}].content must be a non-empty string`;
118
- } else if (Array.isArray(m.content)) {
119
- if (m.content.length === 0) return `messages[${i}].content array must be non-empty`;
120
- // Element schema is intentionally not enforced — passed through to LLM as-is.
121
- } else {
122
- return `messages[${i}].content must be a non-empty string or a non-empty array`;
123
- }
124
- }
125
- return null;
126
- }
127
-
128
- /**
129
- * Validate the schedule-message request payload.
130
- *
131
- * @param {Object} payload
132
- * @returns {{ valid: boolean, errorCode?: string, errorMessage?: string, details?: Object }}
133
- */
134
- function validateScheduleMessagePayload(payload) {
135
- if (!payload.contactName || typeof payload.contactName !== 'string') {
136
- return { valid: false, errorCode: 'INVALID_PARAMETERS', errorMessage: '缺少必需参数或参数格式错误', details: { missingFields: ['contactName'] } };
137
- }
138
-
139
- if (!payload.messageType || !['fixed', 'prompted', 'auto', 'instant'].includes(payload.messageType)) {
140
- return { valid: false, errorCode: 'INVALID_MESSAGE_TYPE', errorMessage: '消息类型无效', details: { providedType: payload.messageType, allowedTypes: ['fixed', 'prompted', 'auto', 'instant'] } };
141
- }
142
-
143
- if (!payload.firstSendTime || !isValidISO8601(payload.firstSendTime)) {
144
- return { valid: false, errorCode: 'INVALID_TIMESTAMP', errorMessage: '时间格式无效', details: { field: 'firstSendTime' } };
145
- }
146
-
147
- if (payload.firstSendTime && new Date(payload.firstSendTime) <= new Date()) {
148
- return { valid: false, errorCode: 'INVALID_TIMESTAMP', errorMessage: '时间必须在未来', details: { field: 'firstSendTime', reason: 'must be in the future' } };
149
- }
150
-
151
- if (!payload.pushSubscription || typeof payload.pushSubscription !== 'object') {
152
- return { valid: false, errorCode: 'INVALID_PARAMETERS', errorMessage: '缺少必需参数或参数格式错误', details: { missingFields: ['pushSubscription'] } };
153
- }
154
-
155
- if (payload.recurrenceType && !['none', 'daily', 'weekly'].includes(payload.recurrenceType)) {
156
- return { valid: false, errorCode: 'INVALID_PARAMETERS', errorMessage: '缺少必需参数或参数格式错误', details: { invalidFields: ['recurrenceType'] } };
157
- }
158
-
159
- if (
160
- payload.maxTokens !== undefined &&
161
- payload.maxTokens !== null &&
162
- (!Number.isInteger(payload.maxTokens) || payload.maxTokens <= 0)
163
- ) {
164
- return { valid: false, errorCode: 'INVALID_PARAMETERS', errorMessage: '缺少必需参数或参数格式错误', details: { invalidFields: ['maxTokens'] } };
165
- }
166
-
167
- if (payload.messageType === 'fixed') {
168
- if (!payload.userMessage) {
169
- return { valid: false, errorCode: 'INVALID_PARAMETERS', errorMessage: '缺少必需参数或参数格式错误', details: { missingFields: ['userMessage (required for fixed type)'] } };
170
- }
171
- }
172
-
173
- // ─── Prompt schema (shared by prompted / auto / instant AI configs) ──
174
- //
175
- // Callers provide *exactly one of* `completePrompt` (string) or `messages`
176
- // (OpenAI-style array). Same contract as @rei-standard/amsg-instant; the
177
- // server's LLM path forwards either verbatim.
178
- const promptCheck = (() => {
179
- const hasCompletePrompt = payload.completePrompt !== undefined && payload.completePrompt !== null && payload.completePrompt !== '';
180
- const hasMessages = payload.messages !== undefined && payload.messages !== null;
181
- if (hasCompletePrompt && hasMessages) {
182
- return {
183
- error: { code: 'INVALID_PARAMETERS', message: 'exactly one of `completePrompt` or `messages` must be provided(两者不能同时出现)', details: { invalidFields: ['completePrompt', 'messages'] } },
184
- hasCompletePrompt: true, hasMessages: true,
185
- };
186
- }
187
- if (hasMessages) {
188
- const err = validateLlmMessagesArray(payload.messages);
189
- if (err) {
190
- return {
191
- error: { code: 'INVALID_PARAMETERS', message: err, details: { invalidFields: ['messages'] } },
192
- hasCompletePrompt: false, hasMessages: true,
193
- };
194
- }
195
- }
196
- return { error: null, hasCompletePrompt, hasMessages };
197
- })();
198
-
199
- if (promptCheck.error) {
200
- return { valid: false, errorCode: promptCheck.error.code, errorMessage: promptCheck.error.message, details: promptCheck.error.details };
201
- }
202
- const hasPrompt = promptCheck.hasCompletePrompt || promptCheck.hasMessages;
203
-
204
- if (payload.messageType === 'prompted' || payload.messageType === 'auto') {
205
- const missingAiFields = [];
206
- if (!hasPrompt) missingAiFields.push('completePrompt or messages');
207
- if (!payload.apiUrl) missingAiFields.push('apiUrl');
208
- if (!payload.apiKey) missingAiFields.push('apiKey');
209
- if (!payload.primaryModel) missingAiFields.push('primaryModel');
210
- if (missingAiFields.length > 0) {
211
- return { valid: false, errorCode: 'INVALID_PARAMETERS', errorMessage: '缺少必需参数或参数格式错误', details: { missingFields: missingAiFields } };
212
- }
213
- }
214
-
215
- if (payload.messageType === 'instant') {
216
- if (payload.recurrenceType && payload.recurrenceType !== 'none') {
217
- return { valid: false, errorCode: 'INVALID_PARAMETERS', errorMessage: 'instant 类型的 recurrenceType 必须为 none', details: { invalidFields: ['recurrenceType (must be "none" for instant type)'] } };
218
- }
219
- const hasAiConfig = hasPrompt && payload.apiUrl && payload.apiKey && payload.primaryModel;
220
- const hasUserMessage = payload.userMessage;
221
- if (!hasAiConfig && !hasUserMessage) {
222
- return { valid: false, errorCode: 'INVALID_PARAMETERS', errorMessage: 'instant 类型必须提供 userMessage 或完整的 AI 配置', details: { missingFields: ['userMessage or ((completePrompt | messages) + apiUrl + apiKey + primaryModel)'] } };
223
- }
224
- }
225
-
226
- if (
227
- payload.temperature !== undefined &&
228
- payload.temperature !== null &&
229
- (typeof payload.temperature !== 'number' || !Number.isFinite(payload.temperature))
230
- ) {
231
- return { valid: false, errorCode: 'INVALID_PARAMETERS', errorMessage: '缺少必需参数或参数格式错误', details: { invalidFields: ['temperature (must be a finite number)'] } };
232
- }
233
-
234
- const avatarErr = validateAvatarUrl(payload.avatarUrl);
235
- if (avatarErr) {
236
- // Soft-strip: a bad avatarUrl (data: URI / oversized / malformed) used to
237
- // 400 the whole schedule. Avatar is cosmetic — drop the field, log, and
238
- // let the rest of the task ship. See standards §6.2.
239
- console.warn('[amsg-server] avatarUrl 不合法,已置空:', avatarErr);
240
- payload.avatarUrl = null;
241
- }
242
- if (payload.uuid && !isValidUUID(payload.uuid)) {
243
- return { valid: false, errorCode: 'INVALID_PARAMETERS', errorMessage: '缺少必需参数或参数格式错误', details: { invalidFields: ['uuid (invalid UUID format)'] } };
244
- }
245
- // messageSubtype is a free-form string tag forwarded to SW-side push payload
246
- // for classification. Only the type is enforced; the taxonomy is the
247
- // consumer's call (previously the enum was chat/forum/moment).
248
- if (
249
- payload.messageSubtype !== undefined &&
250
- payload.messageSubtype !== null &&
251
- typeof payload.messageSubtype !== 'string'
252
- ) {
253
- return { valid: false, errorCode: 'INVALID_PARAMETERS', errorMessage: '缺少必需参数或参数格式错误', details: { invalidFields: ['messageSubtype'] } };
254
- }
255
-
256
- const splitErr = validateSplitPattern(payload.splitPattern);
257
- if (splitErr) {
258
- return { valid: false, errorCode: 'INVALID_PARAMETERS', errorMessage: splitErr, details: { invalidFields: ['splitPattern'] } };
259
- }
260
-
261
- return { valid: true };
262
- }
263
-
264
- /**
265
- * Request payload utilities.
266
- * Keeps body parsing and shape validation consistent across handlers.
267
- */
268
-
269
- const REQUEST_ERRORS = {
270
- INVALID_JSON: { code: 'INVALID_JSON', message: '请求体不是有效的 JSON' },
271
- INVALID_REQUEST_BODY: { code: 'INVALID_REQUEST_BODY', message: '请求体格式无效' },
272
- INVALID_ENCRYPTED_PAYLOAD: { code: 'INVALID_ENCRYPTED_PAYLOAD', message: '加密数据格式错误' }
273
- };
274
-
275
- /**
276
- * @typedef {{ code: string, message: string }} ValidationError
277
- */
278
-
279
- /**
280
- * @typedef {{
281
- * invalidJson?: ValidationError,
282
- * invalidType?: ValidationError
283
- * }} ParseBodyOptions
284
- */
285
-
286
- /**
287
- * @typedef {{
288
- * ok: true,
289
- * data: Record<string, any>
290
- * } | {
291
- * ok: false,
292
- * error: ValidationError
293
- * }} ParseBodyResult
294
- */
295
-
296
- /**
297
- * Parse body into a JSON object.
298
- *
299
- * @param {unknown} body
300
- * @param {ParseBodyOptions} [options]
301
- * @returns {ParseBodyResult}
302
- */
303
- function parseBodyAsObject(body, options = {}) {
304
- const invalidJson = options.invalidJson || REQUEST_ERRORS.INVALID_JSON;
305
- const invalidType = options.invalidType || REQUEST_ERRORS.INVALID_REQUEST_BODY;
306
-
307
- let parsed = body;
308
- if (typeof parsed === 'string') {
309
- try {
310
- parsed = JSON.parse(parsed);
311
- } catch {
312
- return { ok: false, error: invalidJson };
313
- }
314
- }
315
-
316
- if (!isPlainObject(parsed)) {
317
- return { ok: false, error: invalidType };
318
- }
319
-
320
- return { ok: true, data: parsed };
321
- }
322
-
323
- /**
324
- * Parse a standard JSON object body.
325
- *
326
- * @param {unknown} body
327
- * @returns {ParseBodyResult}
328
- */
329
- function parseJsonBody(body) {
330
- return parseBodyAsObject(body, {
331
- invalidJson: REQUEST_ERRORS.INVALID_JSON,
332
- invalidType: REQUEST_ERRORS.INVALID_REQUEST_BODY
333
- });
334
- }
335
-
336
- /**
337
- * Check if a value is a plain object (and not null/array).
338
- *
339
- * @param {unknown} value
340
- * @returns {value is Record<string, any>}
341
- */
342
- function isPlainObject(value) {
343
- return typeof value === 'object' && value !== null && !Array.isArray(value);
344
- }
345
-
346
- /**
347
- * Check if an object follows the encrypted payload envelope shape.
348
- *
349
- * @param {unknown} payload
350
- * @returns {payload is { iv: string, authTag: string, encryptedData: string }}
351
- */
352
- function isEncryptedEnvelope(payload) {
353
- if (!isPlainObject(payload)) return false;
354
-
355
- return (
356
- typeof payload.iv === 'string' &&
357
- typeof payload.authTag === 'string' &&
358
- typeof payload.encryptedData === 'string'
359
- );
360
- }
361
-
362
- /**
363
- * Parse and validate an encrypted payload envelope.
364
- *
365
- * @param {unknown} body
366
- * @returns {ParseBodyResult}
367
- */
368
- function parseEncryptedBody(body) {
369
- const parsedBody = parseBodyAsObject(body, {
370
- invalidJson: REQUEST_ERRORS.INVALID_ENCRYPTED_PAYLOAD,
371
- invalidType: REQUEST_ERRORS.INVALID_ENCRYPTED_PAYLOAD
372
- });
373
-
374
- if (!parsedBody.ok) {
375
- return parsedBody;
376
- }
377
-
378
- if (!isEncryptedEnvelope(parsedBody.data)) {
379
- return { ok: false, error: REQUEST_ERRORS.INVALID_ENCRYPTED_PAYLOAD };
380
- }
381
-
382
- return parsedBody;
383
- }
384
-
385
- /**
386
- * Read a header value case-insensitively.
387
- *
388
- * @param {Record<string, any>} headers
389
- * @param {string} name
390
- * @returns {string}
391
- */
392
- function getHeader(headers = {}, name) {
393
- if (!headers || typeof headers !== 'object') {
394
- return '';
395
- }
396
-
397
- const lowerName = String(name || '').toLowerCase();
398
- if (!lowerName) return '';
399
-
400
- for (const [key, value] of Object.entries(headers)) {
401
- if (String(key).toLowerCase() === lowerName) {
402
- return String(value || '').trim();
403
- }
404
- }
405
-
406
- return '';
407
- }
408
-
409
- /**
410
- * Runtime-neutral crypto + encoding helpers.
411
- *
412
- * Everything in here is implemented on top of WHATWG-standard primitives
413
- * (`globalThis.crypto.subtle`, `TextEncoder`, `Uint8Array`) so the package
414
- * runs on Cloudflare Workers, Vercel Edge, Netlify Edge, Deno, Bun, and
415
- * Node ≥ 19 with zero polyfills. The Node adapter polyfills
416
- * `globalThis.crypto` for Node 18 deployments before any of these are
417
- * touched.
418
- */
419
-
420
- const TEXT_ENCODER = new TextEncoder();
421
- const TEXT_DECODER = new TextDecoder('utf-8', { fatal: false });
422
-
423
- /** UTF-8 encode a string into a Uint8Array. */
424
- function utf8(str) {
425
- return TEXT_ENCODER.encode(String(str));
426
- }
427
-
428
- /** UTF-8 decode a Uint8Array / ArrayBuffer into a string. */
429
- function utf8Decode(buf) {
430
- return TEXT_DECODER.decode(toUint8(buf));
431
- }
432
-
433
-
434
- /** Encode bytes as standard base64 (with padding). */
435
- function bytesToBase64(buf) {
436
- const bytes = toUint8(buf);
437
- let bin = '';
438
- for (let i = 0; i < bytes.length; i++) {
439
- bin += String.fromCharCode(bytes[i]);
440
- }
441
- // btoa is available in all Web Crypto runtimes (browsers, Workers, Node 16+).
442
- return (typeof btoa === 'function')
443
- ? btoa(bin)
444
- : Buffer.from(bin, 'binary').toString('base64');
445
- }
446
-
447
- /** Encode bytes as base64url (no padding). */
448
- function bytesToBase64Url(buf) {
449
- return bytesToBase64(buf).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/g, '');
450
- }
451
-
452
- /** Encode bytes as lowercase hex. */
453
- function bytesToHex(buf) {
454
- const bytes = toUint8(buf);
455
- let out = '';
456
- for (let i = 0; i < bytes.length; i++) {
457
- out += bytes[i].toString(16).padStart(2, '0');
458
- }
459
- return out;
460
- }
461
-
462
- /** Decode a hex string into a Uint8Array. */
463
- function hexToBytes(hex) {
464
- const out = new Uint8Array(hex.length / 2);
465
- for (let i = 0; i < out.length; i++) {
466
- out[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);
467
- }
468
- return out;
469
- }
470
-
471
-
472
- /** Encode a JSON-serializable value as base64url (UTF-8 JSON). */
473
- function jsonToBase64Url(value) {
474
- return bytesToBase64Url(utf8(JSON.stringify(value)));
475
- }
476
-
477
- /** `crypto.randomUUID()`. The Node adapter polyfills `globalThis.crypto`. */
478
- function randomUUID() {
479
- return globalThis.crypto.randomUUID();
480
- }
481
-
482
- /** Cryptographically random bytes. */
483
- function randomBytes(n) {
484
- const out = new Uint8Array(n);
485
- globalThis.crypto.getRandomValues(out);
486
- return out;
487
- }
488
-
489
- /**
490
- * Encryption utility library (SDK version)
491
- *
492
- * Wraps AES-256-GCM operations for request/response and storage encryption.
493
- * Implemented on `globalThis.crypto.subtle` (Web Crypto) so the module runs
494
- * on Cloudflare Workers and other edge runtimes without `nodejs_compat`, as
495
- * well as on Node ≥ 19. All exports are async because SubtleCrypto is.
496
- *
497
- * Wire formats are byte-identical to the previous node:crypto implementation
498
- * (pinned by test/encryption-compat.test.mjs):
499
- * - payload: 12-byte IV, base64 `{ iv, authTag, encryptedData }`
500
- * - storage: 16-byte IV, hex `iv:authTag:encryptedData`
501
- * Web Crypto appends the GCM auth tag to the ciphertext, while these formats
502
- * carry it detached — aesGcmSeal / aesGcmOpen below own that seam.
503
- */
504
-
505
-
506
- // Decoder for the wire formats' base64 fields. base64UrlToBytes normalizes
507
- // the url-safe alphabet and padding first, so it accepts both standard and
508
- // url-safe base64 — same leniency as node's Buffer.from(x, 'base64').
509
- const base64ToBytes = base64UrlToBytes;
510
-
511
- const TAG_LENGTH_BYTES = 16; // AES-GCM auth tag emitted on encrypt
512
-
513
- function importAesKey(hexKey, usage) {
514
- return globalThis.crypto.subtle.importKey(
515
- 'raw',
516
- hexToBytes(hexKey),
517
- { name: 'AES-GCM' },
518
- false,
519
- [usage]
520
- );
521
- }
522
-
523
- /** AES-256-GCM encrypt; returns the ciphertext and the detached 16-byte tag. */
524
- async function aesGcmSeal(hexKey, iv, plaintextBytes) {
525
- const key = await importAesKey(hexKey, 'encrypt');
526
- const sealed = new Uint8Array(await globalThis.crypto.subtle.encrypt(
527
- { name: 'AES-GCM', iv, tagLength: TAG_LENGTH_BYTES * 8 },
528
- key,
529
- plaintextBytes
530
- ));
531
- return {
532
- ciphertext: sealed.slice(0, sealed.length - TAG_LENGTH_BYTES),
533
- authTag: sealed.slice(sealed.length - TAG_LENGTH_BYTES)
534
- };
535
- }
536
-
537
- /** AES-256-GCM decrypt from detached-tag form; returns plaintext bytes. */
538
- async function aesGcmOpen(hexKey, iv, ciphertext, authTag) {
539
- const key = await importAesKey(hexKey, 'decrypt');
540
- // node's decipher accepted GCM tags truncated down to 96 bits; mirror that
541
- // by sizing tagLength from the provided tag. Anything outside the standard
542
- // 96–128-bit range keeps 128 and fails authentication, as it did before.
543
- const tagBits = authTag.length * 8;
544
- const tagLength = tagBits >= 96 && tagBits <= 128 ? tagBits : 128;
545
- const plain = await globalThis.crypto.subtle.decrypt(
546
- { name: 'AES-GCM', iv, tagLength },
547
- key,
548
- concatBytes(ciphertext, authTag)
549
- );
550
- return new Uint8Array(plain);
551
- }
552
-
553
- /**
554
- * Derive a user-specific encryption key from the master key.
555
- *
556
- * @param {string} userId - Unique user identifier.
557
- * @param {string} masterKey - 64-char hex master key.
558
- * @returns {Promise<string>} 64-char hex key.
559
- */
560
- async function deriveUserEncryptionKey(userId, masterKey) {
561
- const digest = await globalThis.crypto.subtle.digest('SHA-256', utf8(masterKey + userId));
562
- return bytesToHex(new Uint8Array(digest)).slice(0, 64);
563
- }
564
-
565
- /**
566
- * Decrypt a client-encrypted request body (AES-256-GCM, base64 encoded).
567
- *
568
- * @param {{ iv: string, authTag: string, encryptedData: string }} encryptedPayload
569
- * @param {string} encryptionKey - 64-char hex key.
570
- * @returns {Promise<Object>} Decrypted JSON object.
571
- */
572
- async function decryptPayload(encryptedPayload, encryptionKey) {
573
- const { iv, authTag, encryptedData } = encryptedPayload;
574
- const plain = await aesGcmOpen(
575
- encryptionKey,
576
- base64ToBytes(iv),
577
- base64ToBytes(encryptedData),
578
- base64ToBytes(authTag)
579
- );
580
- return JSON.parse(utf8Decode(plain));
581
- }
582
-
583
- /**
584
- * Encrypt a JSON payload for API transfer (AES-256-GCM, base64 encoded).
585
- *
586
- * @param {string|Object} payload
587
- * @param {string} encryptionKey - 64-char hex key.
588
- * @returns {Promise<{ iv: string, authTag: string, encryptedData: string }>}
589
- */
590
- async function encryptPayload(payload, encryptionKey) {
591
- const plaintext = typeof payload === 'string' ? payload : JSON.stringify(payload);
592
- const iv = randomBytes(12);
593
- const { ciphertext, authTag } = await aesGcmSeal(encryptionKey, iv, utf8(plaintext));
594
-
595
- return {
596
- iv: bytesToBase64(iv),
597
- authTag: bytesToBase64(authTag),
598
- encryptedData: bytesToBase64(ciphertext)
599
- };
600
- }
601
-
602
- /**
603
- * Encrypt data for database storage (hex encoded, colon-separated).
604
- *
605
- * @param {string} text - Plaintext string.
606
- * @param {string} encryptionKey - 64-char hex key.
607
- * @returns {Promise<string>} Format: iv:authTag:encryptedData
608
- */
609
- async function encryptForStorage(text, encryptionKey) {
610
- const iv = randomBytes(16);
611
- const { ciphertext, authTag } = await aesGcmSeal(encryptionKey, iv, utf8(text));
612
- return `${bytesToHex(iv)}:${bytesToHex(authTag)}:${bytesToHex(ciphertext)}`;
613
- }
614
-
615
- /**
616
- * Decrypt data from database storage format.
617
- *
618
- * @param {string} encryptedText - Format: iv:authTag:encryptedData
619
- * @param {string} encryptionKey - 64-char hex key.
620
- * @returns {Promise<string>} Plaintext string.
621
- */
622
- async function decryptFromStorage(encryptedText, encryptionKey) {
623
- const [ivHex, authTagHex, encryptedDataHex] = encryptedText.split(':');
624
- const plain = await aesGcmOpen(
625
- encryptionKey,
626
- hexToBytes(ivHex),
627
- hexToBytes(encryptedDataHex),
628
- hexToBytes(authTagHex)
629
- );
630
- return utf8Decode(plain);
631
- }
632
-
633
- /**
634
- * Handler: get-user-key
635
- * ReiStandard SDK v2.0.1
636
- *
637
- * @param {Object} ctx - Server context.
638
- * @returns {{ GET: function }}
639
- */
640
-
641
-
642
- function createGetUserKeyHandler(ctx) {
643
- async function GET(url, headers) {
644
- const effectiveHeaders = headers || url || {};
645
- const tenantResult = await ctx.tenantManager.resolveTenant(effectiveHeaders);
646
- if (!tenantResult.ok) {
647
- return tenantResult.error;
648
- }
649
-
650
- const { masterKey } = tenantResult.context;
651
- const userId = getHeader(effectiveHeaders, 'x-user-id');
652
-
653
- if (!userId) {
654
- return {
655
- status: 400,
656
- body: { success: false, error: { code: 'USER_ID_REQUIRED', message: '缺少用户标识符' } }
657
- };
658
- }
659
-
660
- if (!isValidUUIDv4(userId)) {
661
- return {
662
- status: 400,
663
- body: { success: false, error: { code: 'INVALID_USER_ID_FORMAT', message: 'X-User-Id 必须是 UUID v4 格式' } }
664
- };
665
- }
666
-
667
- return {
668
- status: 200,
669
- body: {
670
- success: true,
671
- data: {
672
- userKey: await deriveUserEncryptionKey(userId, masterKey),
673
- version: 1
674
- }
675
- }
676
- };
677
- }
678
-
679
- return { GET };
680
- }
681
-
682
- /**
683
- * Database error helpers.
684
- */
685
-
686
- /**
687
- * Check whether an error is caused by a unique-constraint violation.
688
- *
689
- * @param {unknown} error
690
- * @returns {boolean}
691
- */
692
- function isUniqueViolation(error) {
693
- if (!error || typeof error !== 'object') return false;
694
-
695
- const code = error.code;
696
- if (code === '23505') return true;
697
-
698
- const message = typeof error.message === 'string' ? error.message.toLowerCase() : '';
699
- return message.includes('duplicate key') || message.includes('unique constraint');
700
- }
701
-
702
- /**
703
- * Message Processor (SDK version)
704
- * ReiStandard amsg-server v2.4.0
705
- *
706
- * Handles single message content generation and Web Push delivery for
707
- * scheduled tasks (`fixed` / `prompted` / `auto`) and the
708
- * in-server instant path (`messageType: 'instant'`).
709
- *
710
- * Push wire shape comes from `@rei-standard/amsg-shared`'s
711
- * discriminated union (`AmsgPush`). The SW (`@rei-standard/amsg-sw`)
712
- * routes on `messageKind`. Server-driven pushes always carry
713
- * `source: 'instant'` (for the in-server instant path) or
714
- * `source: 'scheduled'` (for everything else).
715
- *
716
- * v2.4.0: when the LLM response carries non-empty
717
- * `choices[0].message.reasoning_content`, the processor now emits a
718
- * standalone `ReasoningPush` **before** the `ContentPush` burst.
719
- * `messagesSent` in the return value continues to reflect the sentence
720
- * count only (reasoning is an auxiliary push, not a sentence).
721
- */
722
-
723
-
724
- const DEFAULT_SPLIT_REGEX = /([。!?!?]+)/;
725
-
726
- // Pacing between consecutive Web Push deliveries (reasoning → content, and
727
- // between content sentences) so the client renders a natural typing cadence.
728
- // Kept equal to amsg-instant's SLEEP_BETWEEN_MESSAGES_MS default.
729
- const SLEEP_BETWEEN_MESSAGES_MS = 1500;
730
-
731
- /**
732
- * Split a single chunk by one regex; on no-match return [chunk] so a later
733
- * regex in a cascade can still take a swing at it.
734
- */
735
- function splitOnceByRegex(chunk, regex) {
736
- const out = chunk
737
- .split(regex)
738
- .reduce((acc, part, i, arr) => {
739
- if (i % 2 === 0 && part.trim()) {
740
- const punctuation = arr[i + 1] || '';
741
- acc.push(part.trim() + punctuation);
742
- }
743
- return acc;
744
- }, [])
745
- .filter(s => s.length > 0);
746
- return out.length > 0 ? out : [chunk];
747
- }
748
-
749
- /**
750
- * Sentence splitter for amsg-server's scheduled `splitPattern` feature
751
- * (see standards §6.1). Server-only: amsg-instant 0.8.0 dropped its
752
- * request-level `splitPattern`, so there is no instant counterpart to keep
753
- * in lockstep.
754
- *
755
- * @param {string} messageContent
756
- * @param {string | string[] | null} [splitPattern=null]
757
- * @returns {string[]}
758
- */
759
- function splitMessageIntoSentences(messageContent, splitPattern = null) {
760
- const sources =
761
- splitPattern == null ? null :
762
- Array.isArray(splitPattern) ? splitPattern :
763
- [splitPattern];
764
-
765
- const regexes = (sources && sources.length > 0)
766
- ? sources.map(s => new RegExp(s))
767
- : [DEFAULT_SPLIT_REGEX];
768
-
769
- let chunks = [messageContent];
770
- for (const regex of regexes) {
771
- chunks = chunks.flatMap(c => splitOnceByRegex(c, regex));
772
- }
773
-
774
- return chunks.length > 0 ? chunks : [messageContent];
775
- }
776
-
777
- /**
778
- * @typedef {Object} ProcessorContext
779
- * @property {Object} webpush - The web-push module instance (already VAPID-configured).
780
- * @property {Object} vapid - { email, publicKey, privateKey }
781
- * @property {import('../adapters/interface.js').DbAdapter} db
782
- */
783
-
784
- /**
785
- * Process a single database task row: decrypt → generate content → push.
786
- *
787
- * @param {import('../adapters/interface.js').TaskRow} task
788
- * @param {ProcessorContext} ctx
789
- * @param {string} [providedMasterKey]
790
- * @returns {Promise<{ success: boolean, messagesSent: number, error?: string }>}
791
- */
792
- async function processSingleMessage(task, ctx, providedMasterKey) {
793
- try {
794
- const masterKey = providedMasterKey || ctx.masterKey;
795
- if (!masterKey) {
796
- return { success: false, messagesSent: 0, error: 'TENANT_MASTER_KEY_MISSING' };
797
- }
798
-
799
- const userKey = await deriveUserEncryptionKey(task.user_id, masterKey);
800
- const decryptedPayload = JSON.parse(await decryptFromStorage(task.encrypted_payload, userKey));
801
-
802
- let messageContent;
803
- /** @type {unknown} */
804
- let llmResponse = null;
805
-
806
- if (decryptedPayload.messageType === 'fixed') {
807
- messageContent = decryptedPayload.userMessage;
808
-
809
- } else if (decryptedPayload.messageType === 'instant') {
810
- const hasPrompt = !!decryptedPayload.completePrompt
811
- || (Array.isArray(decryptedPayload.messages) && decryptedPayload.messages.length > 0);
812
- if (hasPrompt && decryptedPayload.apiUrl && decryptedPayload.apiKey && decryptedPayload.primaryModel) {
813
- const aiResult = await _callAI(decryptedPayload);
814
- messageContent = aiResult.content;
815
- llmResponse = aiResult.response;
816
- } else if (decryptedPayload.userMessage) {
817
- messageContent = decryptedPayload.userMessage;
818
- } else {
819
- throw new Error('Invalid instant message: no content source available');
820
- }
821
-
822
- } else if (decryptedPayload.messageType === 'prompted' || decryptedPayload.messageType === 'auto') {
823
- const aiResult = await _callAI(decryptedPayload);
824
- messageContent = aiResult.content;
825
- llmResponse = aiResult.response;
826
- } else {
827
- throw new Error('Invalid message configuration: no content source available');
828
- }
829
-
830
- // Auto-extract reasoning BEFORE the sentence split: when reasoning
831
- // came from the `<think>` fallback inside message.content, the same
832
- // span is still embedded in messageContent and would otherwise leak
833
- // as raw markup into ContentPush.
834
- const reasoning = readReasoningContent(llmResponse);
835
- if (reasoning) {
836
- messageContent = stripReasoningTags(messageContent);
837
- }
838
-
839
- // Sentence splitting (mirrors @rei-standard/amsg-instant
840
- // splitMessageIntoSentences — keep in lockstep; do not drift). Caller may
841
- // override the default regex via decryptedPayload.splitPattern (string
842
- // for a single regex, string[] for a cascade). Validation already enforces
843
- // length cap + RegExp compilability upstream.
844
- const messages = splitMessageIntoSentences(messageContent, decryptedPayload.splitPattern ?? null);
845
-
846
- if (!ctx.vapid.email || !ctx.vapid.publicKey || !ctx.vapid.privateKey) {
847
- throw new Error('VAPID configuration missing - push notifications cannot be sent');
848
- }
849
-
850
- const pushSubscription = decryptedPayload.pushSubscription;
851
- // sessionId is shared across the optional ReasoningPush and every
852
- // ContentPush from this LLM round. Pin it to the task id when
853
- // available (scheduled tasks) so retries reuse the same id;
854
- // otherwise mint a UUID.
855
- const sessionId = task.id != null
856
- ? `sess_task_${task.id}`
857
- : `sess_${randomUUID()}`;
858
- const source = decryptedPayload.messageType === 'instant' ? 'instant' : 'scheduled';
859
- const messageSubtype = decryptedPayload.messageSubtype || 'chat';
860
- const avatarUrl = decryptedPayload.avatarUrl || null;
861
- const metadata = decryptedPayload.metadata || {};
862
-
863
- // `messageId` format — deterministic when we have a task.id so a
864
- // retry produces the same id for the same (task, sentence) pair
865
- // (downstream dedupers can key on it). Falls back to a UUID for
866
- // the in-server instant path that has no row id.
867
- const messageIdBase = task.id != null
868
- ? `msg_task_${task.id}`
869
- : `msg_${randomUUID()}_instant`;
870
-
871
- // ReasoningPush — auto-emitted before the content burst when the
872
- // LLM response carried non-empty reasoning_content. `fixed` and
873
- // explicit-userMessage paths produce no LLM response, so this
874
- // block is naturally skipped for them (llmResponse stays null).
875
- if (reasoning) {
876
- const reasoningPush = buildReasoningPush({
877
- messageType: decryptedPayload.messageType,
878
- source,
879
- messageId: `${messageIdBase}_reasoning`,
880
- sessionId,
881
- reasoningContent: reasoning,
882
- timestamp: new Date().toISOString(),
883
- title: `来自 ${decryptedPayload.contactName}`,
884
- contactName: decryptedPayload.contactName,
885
- avatarUrl,
886
- messageSubtype,
887
- metadata,
888
- });
889
- await ctx.webpush.sendNotification(pushSubscription, JSON.stringify(reasoningPush));
890
- await new Promise(resolve => setTimeout(resolve, SLEEP_BETWEEN_MESSAGES_MS));
891
- }
892
-
893
- for (let i = 0; i < messages.length; i++) {
894
- const contentPush = buildContentPush({
895
- messageType: decryptedPayload.messageType,
896
- source,
897
- messageId: `${messageIdBase}_${i}`,
898
- sessionId,
899
- message: messages[i],
900
- timestamp: new Date().toISOString(),
901
- title: `来自 ${decryptedPayload.contactName}`,
902
- contactName: decryptedPayload.contactName,
903
- avatarUrl,
904
- messageSubtype,
905
- messageIndex: i + 1,
906
- totalMessages: messages.length,
907
- taskId: task.id || null,
908
- metadata,
909
- });
910
-
911
- await ctx.webpush.sendNotification(pushSubscription, JSON.stringify(contentPush));
912
-
913
- if (i < messages.length - 1) {
914
- await new Promise(resolve => setTimeout(resolve, SLEEP_BETWEEN_MESSAGES_MS));
915
- }
916
- }
917
-
918
- return { success: true, messagesSent: messages.length };
919
-
920
- } catch (error) {
921
- return { success: false, messagesSent: 0, error: error.message };
922
- }
923
- }
924
-
925
- /**
926
- * Process a single message identified by UUID (used for instant type).
927
- *
928
- * @param {string} uuid
929
- * @param {ProcessorContext} ctx
930
- * @param {number} [maxRetries=2]
931
- * @param {string} [userId]
932
- * @param {string} [providedMasterKey]
933
- * @returns {Promise<{ success: boolean, messagesSent?: number, retriesUsed?: number, error?: Object }>}
934
- */
935
- async function processMessagesByUuid(uuid, ctx, maxRetries = 2, userId, providedMasterKey) {
936
- let retryCount = 0;
937
- const masterKey = providedMasterKey || ctx.masterKey;
938
-
939
- if (!masterKey) {
940
- return {
941
- success: false,
942
- error: { code: 'TENANT_MASTER_KEY_MISSING', message: '租户主密钥不存在或配置异常' }
943
- };
944
- }
945
-
946
- while (retryCount <= maxRetries) {
947
- let task;
948
- try {
949
- task = userId
950
- ? await ctx.db.getTaskByUuid(uuid, userId)
951
- : await ctx.db.getTaskByUuidOnly(uuid);
952
- } catch (error) {
953
- if (retryCount < maxRetries) {
954
- retryCount++;
955
- await new Promise(resolve => setTimeout(resolve, 1000 * retryCount));
956
- continue;
957
- }
958
-
959
- return {
960
- success: false,
961
- error: { code: 'INTERNAL_ERROR', message: error.message, retriesAttempted: retryCount }
962
- };
963
- }
964
-
965
- if (!task) {
966
- return { success: false, error: { code: 'TASK_NOT_FOUND', message: '任务不存在或已处理' } };
967
- }
968
-
969
- const result = await processSingleMessage(task, ctx, masterKey);
970
-
971
- if (!result.success) {
972
- if (retryCount < maxRetries) {
973
- retryCount++;
974
- await new Promise(resolve => setTimeout(resolve, 1000 * retryCount));
975
- continue;
976
- }
977
-
978
- try {
979
- await ctx.db.updateTaskById(task.id, { status: 'failed', retry_count: retryCount });
980
- } catch (_updateError) {
981
- // best-effort status update; keep original processing error as primary signal
982
- }
983
-
984
- return {
985
- success: false,
986
- error: { code: 'PROCESSING_ERROR', message: result.error, retriesAttempted: retryCount }
987
- };
988
- }
989
-
990
- try {
991
- await ctx.db.deleteTaskById(task.id);
992
- } catch (error) {
993
- try {
994
- await ctx.db.updateTaskById(task.id, { status: 'sent', retry_count: 0 });
995
- } catch (_markSentError) {
996
- // best effort: avoid re-sending if storage mutation partially fails
997
- }
998
-
999
- return {
1000
- success: false,
1001
- error: {
1002
- code: 'POST_SEND_CLEANUP_FAILED',
1003
- message: '消息已发送,但任务清理失败',
1004
- details: { error: error.message }
1005
- }
1006
- };
1007
- }
1008
-
1009
- return { success: true, messagesSent: result.messagesSent, retriesUsed: retryCount };
1010
- }
1011
- }
1012
-
1013
- /**
1014
- * Call an OpenAI-compatible API.
1015
- *
1016
- * Returns the full response object alongside the extracted (trimmed)
1017
- * `content` string. Callers that only need the text can ignore
1018
- * `response`; callers that want `reasoning_content` / `tool_calls`
1019
- * read from `response.choices[0].message`.
1020
- *
1021
- * @private
1022
- * @param {Object} payload
1023
- * @returns {Promise<{ response: unknown, content: string }>}
1024
- */
1025
- async function _callAI(payload) {
1026
- const normalizedApiUrl = normalizeAiApiUrl(payload.apiUrl);
1027
- const requestBody = buildAiRequestBody(payload);
1028
-
1029
- const aiResponse = await fetch(normalizedApiUrl, {
1030
- method: 'POST',
1031
- headers: {
1032
- 'Content-Type': 'application/json',
1033
- 'Authorization': `Bearer ${payload.apiKey}`
1034
- },
1035
- body: JSON.stringify(requestBody),
1036
- signal: AbortSignal.timeout(300000)
1037
- });
1038
-
1039
- if (!aiResponse.ok) {
1040
- if (aiResponse.status === 405) {
1041
- throw new Error(
1042
- `AI API error: 405 Method Not Allowed. ` +
1043
- `apiUrl must point to a full chat endpoint (for example: /chat/completions). ` +
1044
- `Received: ${normalizedApiUrl}`
1045
- );
1046
- }
1047
-
1048
- throw new Error(
1049
- `AI API error: ${aiResponse.status} ${aiResponse.statusText || 'Unknown Error'}. ` +
1050
- `Request URL: ${normalizedApiUrl}`
1051
- );
1052
- }
1053
-
1054
- const aiData = await aiResponse.json();
1055
- const content = aiData?.choices?.[0]?.message?.content;
1056
- if (typeof content !== 'string' || !content.trim()) {
1057
- throw new Error('AI API error: response missing choices[0].message.content');
1058
- }
1059
-
1060
- return { response: aiData, content: content.trim() };
1061
- }
1062
-
1063
- /**
1064
- * Build OpenAI-compatible request body.
1065
- *
1066
- * `max_tokens` is optional:
1067
- * - include it only when payload.maxTokens is provided
1068
- * - omit it when payload.maxTokens is undefined / null
1069
- *
1070
- * @param {Object} payload
1071
- * @returns {Object}
1072
- */
1073
- function buildAiRequestBody(payload) {
1074
- // messages mode (added in v2.2.0): forward the caller's OpenAI-style array
1075
- // verbatim — same contract as @rei-standard/amsg-instant 0.5.0+. No auto
1076
- // role injection, no concatenation back to a single user message. Lets
1077
- // the upstream app preserve system / multi-turn context byte-for-byte
1078
- // across the schedule-message path.
1079
- const llmMessages = Array.isArray(payload.messages) && payload.messages.length > 0
1080
- ? payload.messages
1081
- : [{ role: 'user', content: payload.completePrompt }];
1082
-
1083
- const requestBody = {
1084
- model: payload.primaryModel,
1085
- messages: llmMessages,
1086
- };
1087
-
1088
- // Match the instant package's behavior: only inject default temperature
1089
- // for the legacy completePrompt path; messages mode forwards whatever the
1090
- // upstream app set (or nothing) so behavior matches their main chat path.
1091
- if (payload.temperature !== undefined && payload.temperature !== null) {
1092
- requestBody.temperature = payload.temperature;
1093
- } else if (!Array.isArray(payload.messages)) {
1094
- requestBody.temperature = 0.8;
1095
- }
1096
-
1097
- if (payload.maxTokens === undefined || payload.maxTokens === null) {
1098
- return requestBody;
1099
- }
1100
-
1101
- if (!Number.isInteger(payload.maxTokens) || payload.maxTokens <= 0) {
1102
- throw new Error('Invalid maxTokens: maxTokens must be a positive integer when provided.');
1103
- }
1104
-
1105
- requestBody.max_tokens = payload.maxTokens;
1106
- return requestBody;
1107
- }
1108
-
1109
- /**
1110
- * Normalize AI API URL for OpenAI-compatible chat endpoints.
1111
- *
1112
- * **Keep in sync** with `@rei-standard/amsg-instant`'s
1113
- * `src/message-processor.js` `normalizeAiApiUrl` — same rules, same
1114
- * tests. The two packages share this logic but each carry their own copy
1115
- * to avoid an architectural dependency (server should not depend on the
1116
- * stateless worker package).
1117
- *
1118
- * @param {string} apiUrl
1119
- * @returns {string}
1120
- */
1121
- function normalizeAiApiUrl(apiUrl) {
1122
- if (typeof apiUrl !== 'string' || !apiUrl.trim()) {
1123
- throw new Error(
1124
- 'Invalid apiUrl: apiUrl is required. ' +
1125
- 'Please provide a chat endpoint URL ' +
1126
- '(for example: https://api.openai.com or https://api.openai.com/v1/chat/completions).'
1127
- );
1128
- }
1129
-
1130
- const trimmedApiUrl = apiUrl.trim();
1131
- let parsedUrl;
1132
-
1133
- try {
1134
- parsedUrl = new URL(trimmedApiUrl);
1135
- } catch {
1136
- throw new Error(
1137
- `Invalid apiUrl: "${apiUrl}". Please provide a valid absolute URL.`
1138
- );
1139
- }
1140
-
1141
- let path = parsedUrl.pathname.replace(/\/+$/, '') || '/';
1142
-
1143
- if (/\/chat\/completions$/.test(path)) ; else if (path === '/') {
1144
- // Bare host → assume OpenAI shape.
1145
- path = '/v1/chat/completions';
1146
- } else if (/\/v\d+$/.test(path)) {
1147
- // Path ends in `/v1`, `/v2`, … — caller already versioned the URL.
1148
- // Append only `/chat/completions`; never re-add `/v1`.
1149
- path = `${path}/chat/completions`;
1150
- }
1151
- // Any other custom path is left untouched on purpose.
1152
-
1153
- parsedUrl.pathname = path;
1154
- return parsedUrl.toString();
1155
- }
1156
-
1157
- /**
1158
- * Handler: schedule-message
1159
- * ReiStandard SDK v2.0.1
1160
- *
1161
- * @param {Object} ctx - Server context.
1162
- * @returns {{ POST: function }}
1163
- */
1164
-
1165
-
1166
- function createScheduleMessageHandler(ctx) {
1167
- async function POST(headers, body) {
1168
- const tenantResult = await ctx.tenantManager.resolveTenant(headers);
1169
- if (!tenantResult.ok) {
1170
- return tenantResult.error;
1171
- }
1172
-
1173
- const tenantCtx = tenantResult.context;
1174
- const db = tenantCtx.db;
1175
- const masterKey = tenantCtx.masterKey;
1176
- const isEncrypted = getHeader(headers, 'x-payload-encrypted') === 'true';
1177
- const encryptionVersion = getHeader(headers, 'x-encryption-version');
1178
- const userId = getHeader(headers, 'x-user-id');
1179
-
1180
- if (!isEncrypted) {
1181
- return { status: 400, body: { success: false, error: { code: 'ENCRYPTION_REQUIRED', message: '请求体必须加密' } } };
1182
- }
1183
- if (!userId) {
1184
- return { status: 400, body: { success: false, error: { code: 'USER_ID_REQUIRED', message: '缺少用户标识符' } } };
1185
- }
1186
- if (!isValidUUIDv4(userId)) {
1187
- return { status: 400, body: { success: false, error: { code: 'INVALID_USER_ID_FORMAT', message: 'X-User-Id 必须是 UUID v4 格式' } } };
1188
- }
1189
- if (encryptionVersion !== '1') {
1190
- return { status: 400, body: { success: false, error: { code: 'UNSUPPORTED_ENCRYPTION_VERSION', message: '加密版本不支持' } } };
1191
- }
1192
-
1193
- // Decrypt request body
1194
- const parsedBody = parseEncryptedBody(body);
1195
- if (!parsedBody.ok) {
1196
- return { status: 400, body: { success: false, error: parsedBody.error } };
1197
- }
1198
-
1199
- const encryptedBody = parsedBody.data;
1200
- const userKey = await deriveUserEncryptionKey(userId, masterKey);
1201
-
1202
- let payload;
1203
- try {
1204
- payload = await decryptPayload(encryptedBody, userKey);
1205
- } catch (error) {
1206
- if (error instanceof SyntaxError) {
1207
- return { status: 400, body: { success: false, error: { code: 'INVALID_PAYLOAD_FORMAT', message: '解密后的数据不是有效 JSON' } } };
1208
- }
1209
-
1210
- const message = typeof error.message === 'string' ? error.message : '';
1211
- if (message.includes('auth') || message.includes('Unsupported state')) {
1212
- return { status: 400, body: { success: false, error: { code: 'DECRYPTION_FAILED', message: '请求体解密失败' } } };
1213
- }
1214
-
1215
- return { status: 400, body: { success: false, error: { code: 'DECRYPTION_FAILED', message: '请求体解密失败' } } };
1216
- }
1217
-
1218
- if (!isPlainObject(payload)) {
1219
- return { status: 400, body: { success: false, error: { code: 'INVALID_PAYLOAD_FORMAT', message: '解密后的数据必须是 JSON 对象' } } };
1220
- }
1221
-
1222
- // Validate
1223
- const validationResult = validateScheduleMessagePayload(payload);
1224
- if (!validationResult.valid) {
1225
- return { status: 400, body: { success: false, error: { code: validationResult.errorCode, message: validationResult.errorMessage, details: validationResult.details } } };
1226
- }
1227
-
1228
- const taskUuid = payload.uuid || randomUUID();
1229
-
1230
- const fullTaskData = {
1231
- contactName: payload.contactName,
1232
- avatarUrl: payload.avatarUrl || null,
1233
- messageType: payload.messageType,
1234
- messageSubtype: payload.messageSubtype || 'chat',
1235
- userMessage: payload.userMessage || null,
1236
- firstSendTime: payload.firstSendTime,
1237
- recurrenceType: payload.recurrenceType || 'none',
1238
- apiUrl: payload.apiUrl || null,
1239
- apiKey: payload.apiKey || null,
1240
- primaryModel: payload.primaryModel || null,
1241
- // Prompt is one-of: legacy completePrompt (string) OR messages (OpenAI-
1242
- // style array). Validation has already enforced exactly-one-of, so
1243
- // exactly one of these will be non-null when an AI config is provided.
1244
- completePrompt: payload.completePrompt || null,
1245
- messages: Array.isArray(payload.messages) ? payload.messages : null,
1246
- maxTokens: payload.maxTokens ?? null,
1247
- temperature: payload.temperature ?? null,
1248
- // 0.6.0+: optional caller-provided regex (string or string[]) used by
1249
- // the message processor to chunk LLM output into individual pushes.
1250
- // null → processor falls back to the default /([。!?!?]+)/ regex.
1251
- splitPattern: payload.splitPattern ?? null,
1252
- pushSubscription: payload.pushSubscription,
1253
- metadata: payload.metadata || {}
1254
- };
1255
-
1256
- const encryptedPayload = await encryptForStorage(JSON.stringify(fullTaskData), userKey);
1257
-
1258
- /**
1259
- * In-server instant path. Delivers an instant message through this
1260
- * server's own task queue (create task → process by UUID → delete task).
1261
- * The task is written to the database before processing, so delivery is
1262
- * not tied to the request connection: even if the client disconnects, the
1263
- * row stays and the generation keeps running (and can be retried) for as
1264
- * long as it needs. Use this when you have a database and want long or
1265
- * guaranteed-complete generations with no dropped messages.
1266
- *
1267
- * The stateless alternative is `@rei-standard/amsg-instant`: it streams
1268
- * over SSE with a Web Push backup and needs no database, which makes it a
1269
- * good fit for edge runtimes (e.g. Cloudflare Workers). Its work rides the
1270
- * response connection, so after the client disconnects it only has the
1271
- * platform's brief grace window to finish (≈20-30s observed on Deno
1272
- * Deploy) — ideal for short instant messages that complete quickly.
1273
- */
1274
- // Instant type: check VAPID before creating the task to avoid orphaned rows
1275
- if (payload.messageType === 'instant') {
1276
- if (!ctx.vapid.email || !ctx.vapid.publicKey || !ctx.vapid.privateKey) {
1277
- return {
1278
- status: 500,
1279
- body: {
1280
- success: false,
1281
- error: {
1282
- code: 'VAPID_CONFIG_ERROR',
1283
- message: 'VAPID 配置缺失,无法发送即时消息',
1284
- details: {
1285
- missingKeys: [
1286
- !ctx.vapid.email && 'VAPID_EMAIL',
1287
- !ctx.vapid.publicKey && 'NEXT_PUBLIC_VAPID_PUBLIC_KEY',
1288
- !ctx.vapid.privateKey && 'VAPID_PRIVATE_KEY'
1289
- ].filter(Boolean)
1290
- }
1291
- }
1292
- }
1293
- };
1294
- }
1295
- }
1296
-
1297
- // Insert into database
1298
- let dbResult;
1299
- try {
1300
- dbResult = await db.createTask({
1301
- user_id: userId,
1302
- uuid: taskUuid,
1303
- encrypted_payload: encryptedPayload,
1304
- next_send_at: payload.firstSendTime,
1305
- message_type: payload.messageType
1306
- });
1307
- } catch (error) {
1308
- if (isUniqueViolation(error)) {
1309
- return {
1310
- status: 409,
1311
- body: {
1312
- success: false,
1313
- error: {
1314
- code: 'TASK_UUID_CONFLICT',
1315
- message: '任务 UUID 已存在,请使用新的 uuid 重新提交'
1316
- }
1317
- }
1318
- };
1319
- }
1320
- throw error;
1321
- }
1322
-
1323
- if (!dbResult) {
1324
- return { status: 500, body: { success: false, error: { code: 'TASK_CREATE_FAILED', message: '创建任务失败' } } };
1325
- }
1326
-
1327
- /**
1328
- * In-server instant path. Delivers an instant message through this
1329
- * server's own task queue (create task → process by UUID → delete task).
1330
- * The task is written to the database before processing, so delivery is
1331
- * not tied to the request connection: even if the client disconnects, the
1332
- * row stays and the generation keeps running (and can be retried) for as
1333
- * long as it needs. Use this when you have a database and want long or
1334
- * guaranteed-complete generations with no dropped messages.
1335
- *
1336
- * The stateless alternative is `@rei-standard/amsg-instant`: it streams
1337
- * over SSE with a Web Push backup and needs no database, which makes it a
1338
- * good fit for edge runtimes (e.g. Cloudflare Workers). Its work rides the
1339
- * response connection, so after the client disconnects it only has the
1340
- * platform's brief grace window to finish (≈20-30s observed on Deno
1341
- * Deploy) — ideal for short instant messages that complete quickly.
1342
- */
1343
- // Instant type: send immediately
1344
- if (payload.messageType === 'instant') {
1345
- try {
1346
- const sendResult = await processMessagesByUuid(taskUuid, {
1347
- ...ctx,
1348
- db,
1349
- masterKey
1350
- }, 2, userId, masterKey);
1351
-
1352
- if (!sendResult.success) {
1353
- return { status: 500, body: { success: false, error: { code: 'MESSAGE_SEND_FAILED', message: '消息发送失败', details: sendResult.error } } };
1354
- }
1355
-
1356
- return {
1357
- status: 200,
1358
- body: {
1359
- success: true,
1360
- data: {
1361
- uuid: taskUuid,
1362
- contactName: payload.contactName,
1363
- messagesSent: sendResult.messagesSent,
1364
- sentAt: new Date().toISOString(),
1365
- status: 'sent',
1366
- retriesUsed: sendResult.retriesUsed || 0
1367
- }
1368
- }
1369
- };
1370
- } catch (error) {
1371
- return { status: 500, body: { success: false, error: { code: 'MESSAGE_SEND_FAILED', message: '消息发送失败', details: { error: error.message } } } };
1372
- }
1373
- }
1374
-
1375
- // Non-instant: return scheduled response
1376
- return {
1377
- status: 201,
1378
- body: {
1379
- success: true,
1380
- data: {
1381
- id: dbResult.id,
1382
- uuid: dbResult.uuid,
1383
- contactName: payload.contactName,
1384
- nextSendAt: dbResult.next_send_at,
1385
- status: dbResult.status,
1386
- createdAt: dbResult.created_at
1387
- }
1388
- }
1389
- };
1390
- }
1391
-
1392
- return { POST };
1393
- }
1394
-
1395
- /**
1396
- * Scheduled tick core: fetch due tasks, deliver, reschedule/retry, cleanup.
1397
- * Extracted verbatim from the send-notifications handler so both the HTTP
1398
- * handler (multi-tenant) and the CF scheduled() path (single-user) share it.
1399
- *
1400
- * @param {Object} ctx - { db, masterKey, vapid, webpush }
1401
- * @returns {Promise<Object>} summary { totalTasks, successCount, failedCount, processedAt, executionTime, details }
1402
- */
1403
-
1404
-
1405
- async function runScheduledTick(ctx) {
1406
- const db = ctx.db;
1407
- const masterKey = ctx.masterKey;
1408
-
1409
- const startTime = Date.now();
1410
- const tasks = await db.getPendingTasks(50);
1411
-
1412
- const MAX_CONCURRENT = 8;
1413
- const results = {
1414
- totalTasks: tasks.length,
1415
- successCount: 0,
1416
- failedCount: 0,
1417
- deletedOnceOffTasks: 0,
1418
- updatedRecurringTasks: 0,
1419
- failedTasks: []
1420
- };
1421
-
1422
- async function handleDeliveryFailure(task, reason) {
1423
- results.failedCount++;
1424
- try {
1425
- if (task.retry_count >= 3) {
1426
- await db.updateTaskById(task.id, { status: 'failed' });
1427
- results.failedTasks.push({ taskId: task.id, reason, retryCount: task.retry_count, status: 'permanently_failed' });
1428
- } else {
1429
- const nextRetryTime = new Date(Date.now() + (task.retry_count + 1) * 2 * 60 * 1000);
1430
- await db.updateTaskById(task.id, { next_send_at: nextRetryTime.toISOString(), retry_count: task.retry_count + 1 });
1431
- results.failedTasks.push({ taskId: task.id, reason, retryCount: task.retry_count + 1, nextRetryAt: nextRetryTime.toISOString() });
1432
- }
1433
- } catch (updateError) {
1434
- results.failedTasks.push({ taskId: task.id, reason, status: 'retry_update_failed', updateError: updateError.message });
1435
- }
1436
- }
1437
-
1438
- async function handlePostSendPersistenceFailure(task, reason) {
1439
- results.failedCount++;
1440
- let markedSent = false;
1441
- try {
1442
- await db.updateTaskById(task.id, { status: 'sent', retry_count: 0 });
1443
- markedSent = true;
1444
- } catch (_markSentError) {
1445
- markedSent = false;
1446
- }
1447
- results.failedTasks.push({
1448
- taskId: task.id,
1449
- reason,
1450
- status: markedSent ? 'post_send_cleanup_failed_marked_sent' : 'post_send_cleanup_failed',
1451
- messageDelivered: true
1452
- });
1453
- }
1454
-
1455
- async function processTask(task) {
1456
- let sendResult;
1457
- try {
1458
- sendResult = await processSingleMessage(task, { ...ctx, db, masterKey }, masterKey);
1459
- } catch (error) {
1460
- await handleDeliveryFailure(task, error.message || '消息发送失败');
1461
- return;
1462
- }
1463
-
1464
- if (!sendResult.success) {
1465
- await handleDeliveryFailure(task, sendResult.error || '消息发送失败');
1466
- return;
1467
- }
1468
-
1469
- try {
1470
- const userKey = await deriveUserEncryptionKey(task.user_id, masterKey);
1471
- const decryptedPayload = JSON.parse(await decryptFromStorage(task.encrypted_payload, userKey));
1472
-
1473
- if (decryptedPayload.recurrenceType === 'none') {
1474
- await db.deleteTaskById(task.id);
1475
- results.deletedOnceOffTasks++;
1476
- } else {
1477
- let nextSendAt;
1478
- const currentSendAt = new Date(task.next_send_at);
1479
- if (decryptedPayload.recurrenceType === 'daily') {
1480
- nextSendAt = new Date(currentSendAt.getTime() + 24 * 60 * 60 * 1000);
1481
- } else if (decryptedPayload.recurrenceType === 'weekly') {
1482
- nextSendAt = new Date(currentSendAt.getTime() + 7 * 24 * 60 * 60 * 1000);
1483
- }
1484
- await db.updateTaskById(task.id, { next_send_at: nextSendAt.toISOString(), retry_count: 0 });
1485
- results.updatedRecurringTasks++;
1486
- }
1487
-
1488
- results.successCount++;
1489
- } catch (error) {
1490
- await handlePostSendPersistenceFailure(task, error.message || '发送后状态更新失败');
1491
- }
1492
- }
1493
-
1494
- const taskQueue = [...tasks];
1495
- const processing = [];
1496
-
1497
- while (taskQueue.length > 0 || processing.length > 0) {
1498
- while (processing.length < MAX_CONCURRENT && taskQueue.length > 0) {
1499
- const task = taskQueue.shift();
1500
- const promise = processTask(task);
1501
- processing.push(promise);
1502
- promise.finally(() => {
1503
- const index = processing.indexOf(promise);
1504
- if (index > -1) processing.splice(index, 1);
1505
- });
1506
- }
1507
- if (processing.length > 0) {
1508
- await Promise.race(processing);
1509
- }
1510
- }
1511
-
1512
- await db.cleanupOldTasks(7);
1513
-
1514
- const executionTime = Date.now() - startTime;
1515
-
1516
- return {
1517
- totalTasks: results.totalTasks,
1518
- successCount: results.successCount,
1519
- failedCount: results.failedCount,
1520
- processedAt: new Date().toISOString(),
1521
- executionTime,
1522
- details: {
1523
- deletedOnceOffTasks: results.deletedOnceOffTasks,
1524
- updatedRecurringTasks: results.updatedRecurringTasks,
1525
- failedTasks: results.failedTasks
1526
- }
1527
- };
1528
- }
1529
-
1530
- /**
1531
- * Handler: update-message
1532
- * ReiStandard SDK v2.0.1
1533
- *
1534
- * @param {Object} ctx - Server context.
1535
- * @returns {{ PUT: function }}
1536
- */
1537
-
1538
-
1539
- function createUpdateMessageHandler(ctx) {
1540
- async function PUT(url, headers, body) {
1541
- const tenantResult = await ctx.tenantManager.resolveTenant(headers, { url });
1542
- if (!tenantResult.ok) {
1543
- return tenantResult.error;
1544
- }
1545
-
1546
- const tenantCtx = tenantResult.context;
1547
- const db = tenantCtx.db;
1548
- const masterKey = tenantCtx.masterKey;
1549
- const u = new URL(url, 'https://dummy');
1550
- const taskUuid = u.searchParams.get('id');
1551
-
1552
- if (!taskUuid) {
1553
- return { status: 400, body: { success: false, error: { code: 'TASK_ID_REQUIRED', message: '缺少任务ID' } } };
1554
- }
1555
-
1556
- const userId = getHeader(headers, 'x-user-id');
1557
- if (!userId) {
1558
- return { status: 400, body: { success: false, error: { code: 'USER_ID_REQUIRED', message: '缺少用户标识符' } } };
1559
- }
1560
- if (!isValidUUIDv4(userId)) {
1561
- return { status: 400, body: { success: false, error: { code: 'INVALID_USER_ID_FORMAT', message: 'X-User-Id 必须是 UUID v4 格式' } } };
1562
- }
1563
-
1564
- const isEncrypted = getHeader(headers, 'x-payload-encrypted') === 'true';
1565
- const encryptionVersion = getHeader(headers, 'x-encryption-version');
1566
-
1567
- if (!isEncrypted) {
1568
- return { status: 400, body: { success: false, error: { code: 'ENCRYPTION_REQUIRED', message: '请求体必须加密' } } };
1569
- }
1570
-
1571
- if (encryptionVersion !== '1') {
1572
- return { status: 400, body: { success: false, error: { code: 'UNSUPPORTED_ENCRYPTION_VERSION', message: '加密版本不支持' } } };
1573
- }
1574
-
1575
- const parsedBody = parseEncryptedBody(body);
1576
- if (!parsedBody.ok) {
1577
- return { status: 400, body: { success: false, error: parsedBody.error } };
1578
- }
1579
-
1580
- const encryptedBody = parsedBody.data;
1581
- const userKey = await deriveUserEncryptionKey(userId, masterKey);
1582
- let updates;
1583
-
1584
- try {
1585
- updates = await decryptPayload(encryptedBody, userKey);
1586
- } catch (_error) {
1587
- return { status: 400, body: { success: false, error: { code: 'DECRYPTION_FAILED', message: '请求体解密失败' } } };
1588
- }
1589
-
1590
- if (!isPlainObject(updates)) {
1591
- return { status: 400, body: { success: false, error: { code: 'INVALID_UPDATE_DATA', message: '更新数据格式错误' } } };
1592
- }
1593
-
1594
- if (updates.nextSendAt && !isValidISO8601(updates.nextSendAt)) {
1595
- return { status: 400, body: { success: false, error: { code: 'INVALID_UPDATE_DATA', message: '更新数据格式错误', details: { invalidFields: ['nextSendAt'] } } } };
1596
- }
1597
-
1598
- if (updates.recurrenceType && !['none', 'daily', 'weekly'].includes(updates.recurrenceType)) {
1599
- return { status: 400, body: { success: false, error: { code: 'INVALID_UPDATE_DATA', message: '更新数据格式错误', details: { invalidFields: ['recurrenceType'] } } } };
1600
- }
1601
-
1602
- if (
1603
- Object.prototype.hasOwnProperty.call(updates, 'maxTokens') &&
1604
- updates.maxTokens !== null &&
1605
- (!Number.isInteger(updates.maxTokens) || updates.maxTokens <= 0)
1606
- ) {
1607
- return { status: 400, body: { success: false, error: { code: 'INVALID_UPDATE_DATA', message: '更新数据格式错误', details: { invalidFields: ['maxTokens'] } } } };
1608
- }
1609
-
1610
- // Reject updates that try to set both completePrompt and messages at
1611
- // once. We don't enforce one-of-required here (callers may patch other
1612
- // fields), but the two prompt sources are mutually exclusive and must
1613
- // stay that way in storage too.
1614
- if (
1615
- updates.completePrompt &&
1616
- updates.messages !== undefined && updates.messages !== null
1617
- ) {
1618
- return { status: 400, body: { success: false, error: { code: 'INVALID_UPDATE_DATA', message: 'completePrompt 与 messages 不能同时更新(二选一)', details: { invalidFields: ['completePrompt', 'messages'] } } } };
1619
- }
1620
- if (updates.messages !== undefined && updates.messages !== null) {
1621
- const msgErr = validateLlmMessagesArray(updates.messages);
1622
- if (msgErr) {
1623
- return { status: 400, body: { success: false, error: { code: 'INVALID_UPDATE_DATA', message: msgErr, details: { invalidFields: ['messages'] } } } };
1624
- }
1625
- }
1626
- if (
1627
- Object.prototype.hasOwnProperty.call(updates, 'temperature') &&
1628
- updates.temperature !== null &&
1629
- (typeof updates.temperature !== 'number' || !Number.isFinite(updates.temperature))
1630
- ) {
1631
- return { status: 400, body: { success: false, error: { code: 'INVALID_UPDATE_DATA', message: '更新数据格式错误', details: { invalidFields: ['temperature'] } } } };
1632
- }
1633
- if (Object.prototype.hasOwnProperty.call(updates, 'splitPattern')) {
1634
- const splitErr = validateSplitPattern(updates.splitPattern);
1635
- if (splitErr) {
1636
- return { status: 400, body: { success: false, error: { code: 'INVALID_UPDATE_DATA', message: splitErr, details: { invalidFields: ['splitPattern'] } } } };
1637
- }
1638
- }
1639
- if (Object.prototype.hasOwnProperty.call(updates, 'avatarUrl')) {
1640
- const avatarErr = validateAvatarUrl(updates.avatarUrl);
1641
- if (avatarErr) {
1642
- // Soft-strip: drop the bad avatarUrl from the patch (keeps the
1643
- // existing stored avatar untouched) and continue applying the rest
1644
- // of the update. See standards §6.2.
1645
- console.warn('[amsg-server] update-message avatarUrl 不合法,已忽略:', avatarErr);
1646
- delete updates.avatarUrl;
1647
- }
1648
- }
1649
-
1650
- // Fetch existing task
1651
- const existingTask = await db.getTaskByUuid(taskUuid, userId);
1652
-
1653
- if (!existingTask) {
1654
- const taskStatus = await db.getTaskStatus(taskUuid, userId);
1655
- if (!taskStatus) {
1656
- return { status: 404, body: { success: false, error: { code: 'TASK_NOT_FOUND', message: '指定的任务不存在或已被删除' } } };
1657
- }
1658
- return { status: 409, body: { success: false, error: { code: 'TASK_ALREADY_COMPLETED', message: '任务已完成或已失败,无法更新' } } };
1659
- }
1660
-
1661
- const existingData = JSON.parse(await decryptFromStorage(existingTask.encrypted_payload, userKey));
1662
-
1663
- // When the caller switches prompt source (completePrompt ↔ messages),
1664
- // null out the other so storage stays one-of (matches schedule-message
1665
- // shape and prevents buildAiRequestBody from accidentally seeing both).
1666
- const promptUpdates = {};
1667
- if (updates.completePrompt) {
1668
- promptUpdates.completePrompt = updates.completePrompt;
1669
- promptUpdates.messages = null;
1670
- } else if (updates.messages !== undefined && updates.messages !== null) {
1671
- promptUpdates.messages = updates.messages;
1672
- promptUpdates.completePrompt = null;
1673
- }
1674
-
1675
- const updatedData = {
1676
- ...existingData,
1677
- ...promptUpdates,
1678
- ...(updates.userMessage && { userMessage: updates.userMessage }),
1679
- ...(updates.recurrenceType && { recurrenceType: updates.recurrenceType }),
1680
- ...(updates.avatarUrl && { avatarUrl: updates.avatarUrl }),
1681
- ...(updates.metadata && { metadata: updates.metadata }),
1682
- ...(Object.prototype.hasOwnProperty.call(updates, 'maxTokens') && { maxTokens: updates.maxTokens ?? null }),
1683
- ...(Object.prototype.hasOwnProperty.call(updates, 'temperature') && { temperature: updates.temperature ?? null }),
1684
- // splitPattern: hasOwnProperty so that explicit `null` (= revert to
1685
- // default) doesn't get swallowed by truthy-spread the way the optional
1686
- // string fields above are.
1687
- ...(Object.prototype.hasOwnProperty.call(updates, 'splitPattern') && { splitPattern: updates.splitPattern ?? null })
1688
- };
1689
-
1690
- const encryptedPayload = await encryptForStorage(JSON.stringify(updatedData), userKey);
1691
- const extraFields = updates.nextSendAt ? { next_send_at: updates.nextSendAt } : undefined;
1692
-
1693
- const result = await db.updateTaskByUuid(taskUuid, userId, encryptedPayload, extraFields);
1694
-
1695
- if (!result) {
1696
- return { status: 409, body: { success: false, error: { code: 'UPDATE_CONFLICT', message: '任务更新失败,任务可能已被修改或删除' } } };
1697
- }
1698
-
1699
- return {
1700
- status: 200,
1701
- body: {
1702
- success: true,
1703
- data: {
1704
- uuid: taskUuid,
1705
- updatedFields: Object.keys(updates),
1706
- updatedAt: result.updated_at
1707
- }
1708
- }
1709
- };
1710
- }
1711
-
1712
- return { PUT };
1713
- }
1714
-
1715
- /**
1716
- * Handler: cancel-message
1717
- * ReiStandard SDK v2.0.1
1718
- *
1719
- * @param {Object} ctx - Server context.
1720
- * @returns {{ DELETE: function }}
1721
- */
1722
-
1723
-
1724
- function createCancelMessageHandler(ctx) {
1725
- async function DELETE(url, headers) {
1726
- const tenantResult = await ctx.tenantManager.resolveTenant(headers, { url });
1727
- if (!tenantResult.ok) {
1728
- return tenantResult.error;
1729
- }
1730
-
1731
- const db = tenantResult.context.db;
1732
- const u = new URL(url, 'https://dummy');
1733
- const taskUuid = u.searchParams.get('id');
1734
-
1735
- if (!taskUuid) {
1736
- return { status: 400, body: { success: false, error: { code: 'TASK_ID_REQUIRED', message: '缺少任务ID' } } };
1737
- }
1738
-
1739
- const userId = getHeader(headers, 'x-user-id');
1740
- if (!userId) {
1741
- return { status: 400, body: { success: false, error: { code: 'USER_ID_REQUIRED', message: '缺少用户标识符' } } };
1742
- }
1743
- if (!isValidUUIDv4(userId)) {
1744
- return { status: 400, body: { success: false, error: { code: 'INVALID_USER_ID_FORMAT', message: 'X-User-Id 必须是 UUID v4 格式' } } };
1745
- }
1746
-
1747
- const deleted = await db.deleteTaskByUuid(taskUuid, userId);
1748
-
1749
- if (!deleted) {
1750
- return {
1751
- status: 404,
1752
- body: { success: false, error: { code: 'TASK_NOT_FOUND', message: '指定的任务不存在或已被删除' } }
1753
- };
1754
- }
1755
-
1756
- return {
1757
- status: 200,
1758
- body: {
1759
- success: true,
1760
- data: { uuid: taskUuid, message: '任务已成功取消', deletedAt: new Date().toISOString() }
1761
- }
1762
- };
1763
- }
1764
-
1765
- return { DELETE };
1766
- }
1767
-
1768
- /**
1769
- * Handler: messages
1770
- * ReiStandard SDK v2.0.1
1771
- *
1772
- * @param {Object} ctx - Server context.
1773
- * @returns {{ GET: function }}
1774
- */
1775
-
1776
-
1777
- function createMessagesHandler(ctx) {
1778
- async function GET(url, headers) {
1779
- const tenantResult = await ctx.tenantManager.resolveTenant(headers, { url });
1780
- if (!tenantResult.ok) {
1781
- return tenantResult.error;
1782
- }
1783
-
1784
- const tenantCtx = tenantResult.context;
1785
- const db = tenantCtx.db;
1786
- const masterKey = tenantCtx.masterKey;
1787
- const userId = getHeader(headers, 'x-user-id');
1788
-
1789
- if (!userId) {
1790
- return {
1791
- status: 400,
1792
- body: { success: false, error: { code: 'USER_ID_REQUIRED', message: '必须提供 X-User-Id 请求头' } }
1793
- };
1794
- }
1795
- if (!isValidUUIDv4(userId)) {
1796
- return {
1797
- status: 400,
1798
- body: { success: false, error: { code: 'INVALID_USER_ID_FORMAT', message: 'X-User-Id 必须是 UUID v4 格式' } }
1799
- };
1800
- }
1801
-
1802
- const u = new URL(url, 'https://dummy');
1803
- const status = u.searchParams.get('status') || 'all';
1804
- const limit = Math.min(parseInt(u.searchParams.get('limit') || '20', 10), 100);
1805
- const offset = parseInt(u.searchParams.get('offset') || '0', 10);
1806
-
1807
- if (isNaN(limit) || limit < 1) {
1808
- return { status: 400, body: { success: false, error: { code: 'INVALID_PARAMETERS', message: 'limit 参数无效,必须为正整数' } } };
1809
- }
1810
-
1811
- if (isNaN(offset) || offset < 0) {
1812
- return { status: 400, body: { success: false, error: { code: 'INVALID_PARAMETERS', message: 'offset 参数无效,必须为非负整数' } } };
1813
- }
1814
-
1815
- const { tasks, total } = await db.listTasks(userId, { status, limit, offset });
1816
-
1817
- const userKey = await deriveUserEncryptionKey(userId, masterKey);
1818
-
1819
- const decryptedTasks = await Promise.all(tasks.map(async task => {
1820
- const decrypted = JSON.parse(await decryptFromStorage(task.encrypted_payload, userKey));
1821
- return {
1822
- id: task.id,
1823
- uuid: task.uuid,
1824
- contactName: decrypted.contactName,
1825
- messageType: task.message_type,
1826
- messageSubtype: decrypted.messageSubtype,
1827
- nextSendAt: task.next_send_at,
1828
- recurrenceType: decrypted.recurrenceType,
1829
- status: task.status,
1830
- retryCount: task.retry_count,
1831
- createdAt: task.created_at,
1832
- updatedAt: task.updated_at
1833
- };
1834
- }));
1835
-
1836
- const responsePayload = {
1837
- tasks: decryptedTasks,
1838
- pagination: { total, limit, offset, hasMore: offset + limit < total }
1839
- };
1840
- const encryptedResponse = await encryptPayload(responsePayload, userKey);
1841
-
1842
- return {
1843
- status: 200,
1844
- body: {
1845
- success: true,
1846
- encrypted: true,
1847
- version: 1,
1848
- data: encryptedResponse
1849
- }
1850
- };
1851
- }
1852
-
1853
- return { GET };
1854
- }
1855
-
1856
- /**
1857
- * SQLite (Cloudflare D1) dialect schema for scheduled_messages.
1858
- *
1859
- * Differences from the Postgres schema (adapters/schema.js):
1860
- * - id: INTEGER PRIMARY KEY AUTOINCREMENT (vs SERIAL)
1861
- * - timestamps stored as TEXT ISO8601 UTC (vs TIMESTAMP WITH TIME ZONE)
1862
- * - no NOW()/DEFAULT; the adapter always writes timestamps explicitly
1863
- * - retry_count is NOT NULL here (Postgres omits NOT NULL); every write path
1864
- * sets it explicitly, so the tighter constraint just documents that intent
1865
- * Partial indexes and CHECK constraints are native to SQLite, so they carry over.
1866
- * Index entries mirror the Postgres INDEXES shape ({ name, sql, description,
1867
- * critical }) so both adapters' initSchema() return the same index metadata.
1868
- */
1869
-
1870
- const SQLITE_TABLE_SQL = `
1871
- CREATE TABLE IF NOT EXISTS scheduled_messages (
1872
- id INTEGER PRIMARY KEY AUTOINCREMENT,
1873
- user_id TEXT NOT NULL,
1874
- uuid TEXT,
1875
- encrypted_payload TEXT NOT NULL,
1876
- message_type TEXT NOT NULL CHECK (message_type IN ('fixed', 'prompted', 'auto', 'instant')),
1877
- next_send_at TEXT NOT NULL,
1878
- status TEXT NOT NULL DEFAULT 'pending' CHECK (status IN ('pending', 'sent', 'failed')),
1879
- retry_count INTEGER NOT NULL DEFAULT 0,
1880
- created_at TEXT NOT NULL,
1881
- updated_at TEXT NOT NULL
1882
- )
1883
- `;
1884
-
1885
- const SQLITE_INDEXES = [
1886
- {
1887
- name: 'idx_pending_tasks_optimized',
1888
- sql: `CREATE INDEX IF NOT EXISTS idx_pending_tasks_optimized
1889
- ON scheduled_messages (status, next_send_at, id, retry_count)
1890
- WHERE status = 'pending'`,
1891
- description: 'Main query index (Cron Job finds pending tasks)',
1892
- critical: false
1893
- },
1894
- {
1895
- name: 'idx_cleanup_completed',
1896
- sql: `CREATE INDEX IF NOT EXISTS idx_cleanup_completed
1897
- ON scheduled_messages (status, updated_at)
1898
- WHERE status IN ('sent', 'failed')`,
1899
- description: 'Cleanup query index',
1900
- critical: false
1901
- },
1902
- {
1903
- name: 'idx_failed_retry',
1904
- sql: `CREATE INDEX IF NOT EXISTS idx_failed_retry
1905
- ON scheduled_messages (status, retry_count, next_send_at)
1906
- WHERE status = 'failed' AND retry_count < 3`,
1907
- description: 'Failed retry index',
1908
- critical: false
1909
- },
1910
- {
1911
- name: 'idx_user_id',
1912
- sql: `CREATE INDEX IF NOT EXISTS idx_user_id
1913
- ON scheduled_messages (user_id)`,
1914
- description: 'User task query index',
1915
- critical: false
1916
- },
1917
- {
1918
- name: 'uidx_uuid',
1919
- sql: `CREATE UNIQUE INDEX IF NOT EXISTS uidx_uuid
1920
- ON scheduled_messages (uuid)
1921
- WHERE uuid IS NOT NULL`,
1922
- description: 'UUID uniqueness guard',
1923
- critical: true
1924
- }
1925
- ];
1926
-
1927
- /**
1928
- * Cloudflare D1 (SQLite) Database Adapter.
1929
- *
1930
- * @implements {import('./interface.js').DbAdapter}
1931
- *
1932
- * Timestamps are stored as ISO8601 UTC TEXT. Every timestamp is normalized
1933
- * with new Date(v).toISOString() before store/compare so lexical ordering
1934
- * equals chronological ordering (mixed offsets like +08:00 vs Z are unified).
1935
- */
1936
-
1937
-
1938
- // Update methods build a dynamic SET clause from object keys. Callers pass only
1939
- // hardcoded column names today, but enforcing a whitelist keeps a future caller
1940
- // from ever turning a caller-supplied key into interpolated SQL.
1941
- const UPDATABLE_COLUMNS = new Set([
1942
- 'user_id', 'uuid', 'encrypted_payload', 'message_type',
1943
- 'next_send_at', 'status', 'retry_count', 'created_at', 'updated_at'
1944
- ]);
1945
-
1946
- class D1Adapter {
1947
- /** @param {{ prepare: (sql: string) => any }} db - Cloudflare D1 binding */
1948
- constructor(db) {
1949
- /** @private */
1950
- this._db = db;
1951
- }
1952
-
1953
- /** @private */
1954
- _now() {
1955
- return new Date().toISOString();
1956
- }
1957
-
1958
- /** @private */
1959
- _iso(value) {
1960
- const d = new Date(value);
1961
- if (Number.isNaN(d.getTime())) {
1962
- throw new Error(`[amsg-server D1] invalid timestamp: ${value}`);
1963
- }
1964
- return d.toISOString();
1965
- }
1966
-
1967
- async initSchema() {
1968
- await this._db.prepare(SQLITE_TABLE_SQL).run();
1969
-
1970
- const indexResults = [];
1971
- for (const index of SQLITE_INDEXES) {
1972
- try {
1973
- await this._db.prepare(index.sql).run();
1974
- indexResults.push({ name: index.name, status: 'success', description: index.description, critical: !!index.critical });
1975
- } catch (error) {
1976
- indexResults.push({ name: index.name, status: 'failed', description: index.description, critical: !!index.critical, error: error.message });
1977
- }
1978
- }
1979
-
1980
- const criticalFailures = indexResults.filter((i) => i.critical && i.status === 'failed');
1981
- if (criticalFailures.length > 0) {
1982
- const names = criticalFailures.map((i) => i.name).join(', ');
1983
- throw new Error(
1984
- `Critical index creation failed (${names}). ` +
1985
- 'Please remove duplicate UUID rows and run initSchema again.'
1986
- );
1987
- }
1988
-
1989
- return {
1990
- columnsCreated: 10,
1991
- indexesCreated: indexResults.filter((r) => r.status === 'success').length,
1992
- indexesFailed: indexResults.filter((r) => r.status === 'failed').length,
1993
- columns: [],
1994
- indexes: indexResults
1995
- };
1996
- }
1997
-
1998
- async dropSchema() {
1999
- await this._db.prepare('DROP TABLE IF EXISTS scheduled_messages').run();
2000
- }
2001
-
2002
- async createTask(params) {
2003
- const now = this._now();
2004
- const nextSendAt = this._iso(params.next_send_at);
2005
- const res = await this._db.prepare(
2006
- `INSERT INTO scheduled_messages
2007
- (user_id, uuid, encrypted_payload, next_send_at, message_type, status, retry_count, created_at, updated_at)
2008
- VALUES (?, ?, ?, ?, ?, 'pending', 0, ?, ?)`
2009
- ).bind(params.user_id, params.uuid, params.encrypted_payload, nextSendAt, params.message_type, now, now).run();
2010
-
2011
- const id = res.meta.last_row_id;
2012
- return this._db.prepare(
2013
- `SELECT id, uuid, next_send_at, status, created_at FROM scheduled_messages WHERE id = ?`
2014
- ).bind(id).first();
2015
- }
2016
-
2017
- async getTaskByUuid(uuid, userId) {
2018
- return this._db.prepare(
2019
- `SELECT id, user_id, uuid, encrypted_payload, message_type, next_send_at, status, retry_count
2020
- FROM scheduled_messages
2021
- WHERE uuid = ? AND user_id = ? AND status = 'pending'
2022
- LIMIT 1`
2023
- ).bind(uuid, userId).first();
2024
- }
2025
-
2026
- async getTaskByUuidOnly(uuid) {
2027
- return this._db.prepare(
2028
- `SELECT id, user_id, uuid, encrypted_payload, message_type, next_send_at, status, retry_count
2029
- FROM scheduled_messages
2030
- WHERE uuid = ? AND status = 'pending'
2031
- LIMIT 1`
2032
- ).bind(uuid).first();
2033
- }
2034
-
2035
- async updateTaskById(taskId, updates) {
2036
- const sets = [];
2037
- const values = [];
2038
- for (const [key, value] of Object.entries(updates)) {
2039
- if (!UPDATABLE_COLUMNS.has(key)) {
2040
- throw new Error(`[amsg-server D1] rejected unknown update column: ${key}`);
2041
- }
2042
- sets.push(`${key} = ?`);
2043
- values.push(key === 'next_send_at' ? this._iso(value) : value);
2044
- }
2045
- // Callers may pass updated_at explicitly (tests); otherwise stamp now.
2046
- if (!Object.prototype.hasOwnProperty.call(updates, 'updated_at')) {
2047
- sets.push('updated_at = ?');
2048
- values.push(this._now());
2049
- }
2050
- values.push(taskId);
2051
-
2052
- await this._db.prepare(
2053
- `UPDATE scheduled_messages SET ${sets.join(', ')} WHERE id = ?`
2054
- ).bind(...values).run();
2055
-
2056
- return this._db.prepare('SELECT * FROM scheduled_messages WHERE id = ?').bind(taskId).first();
2057
- }
2058
-
2059
- async updateTaskByUuid(uuid, userId, encryptedPayload, extraFields) {
2060
- const now = this._now();
2061
- const sets = ['encrypted_payload = ?', 'updated_at = ?'];
2062
- const values = [encryptedPayload, now];
2063
- if (extraFields) {
2064
- for (const [key, value] of Object.entries(extraFields)) {
2065
- if (!UPDATABLE_COLUMNS.has(key)) {
2066
- throw new Error(`[amsg-server D1] rejected unknown update column: ${key}`);
2067
- }
2068
- sets.push(`${key} = ?`);
2069
- values.push(key === 'next_send_at' ? this._iso(value) : value);
2070
- }
2071
- }
2072
- values.push(uuid, userId);
2073
-
2074
- const res = await this._db.prepare(
2075
- `UPDATE scheduled_messages SET ${sets.join(', ')}
2076
- WHERE uuid = ? AND user_id = ? AND status = 'pending'`
2077
- ).bind(...values).run();
2078
-
2079
- if (!res.meta.changes) return null;
2080
- return { uuid, updated_at: now };
2081
- }
2082
-
2083
- async deleteTaskById(taskId) {
2084
- const res = await this._db.prepare('DELETE FROM scheduled_messages WHERE id = ?').bind(taskId).run();
2085
- return res.meta.changes > 0;
2086
- }
2087
-
2088
- async deleteTaskByUuid(uuid, userId) {
2089
- const res = await this._db.prepare(
2090
- 'DELETE FROM scheduled_messages WHERE uuid = ? AND user_id = ?'
2091
- ).bind(uuid, userId).run();
2092
- return res.meta.changes > 0;
2093
- }
2094
-
2095
- async getPendingTasks(limit = 50) {
2096
- const res = await this._db.prepare(
2097
- `SELECT id, user_id, uuid, encrypted_payload, message_type, next_send_at, status, retry_count
2098
- FROM scheduled_messages
2099
- WHERE status = 'pending' AND next_send_at <= ?
2100
- ORDER BY next_send_at ASC
2101
- LIMIT ?`
2102
- ).bind(this._now(), limit).all();
2103
- return res.results || [];
2104
- }
2105
-
2106
- async listTasks(userId, opts = {}) {
2107
- const { status = 'all', limit = 20, offset = 0 } = opts;
2108
- const conditions = ['user_id = ?'];
2109
- const params = [userId];
2110
- if (status !== 'all') {
2111
- conditions.push('status = ?');
2112
- params.push(status);
2113
- }
2114
- const where = conditions.join(' AND ');
2115
-
2116
- const countRow = await this._db.prepare(
2117
- `SELECT COUNT(*) as count FROM scheduled_messages WHERE ${where}`
2118
- ).bind(...params).first();
2119
- const total = Number(countRow.count) || 0;
2120
-
2121
- const res = await this._db.prepare(
2122
- `SELECT id, user_id, uuid, encrypted_payload, message_type, next_send_at, status, retry_count, created_at, updated_at
2123
- FROM scheduled_messages
2124
- WHERE ${where}
2125
- ORDER BY next_send_at ASC
2126
- LIMIT ? OFFSET ?`
2127
- ).bind(...params, limit, offset).all();
2128
-
2129
- return { tasks: res.results || [], total };
2130
- }
2131
-
2132
- async cleanupOldTasks(days = 7) {
2133
- const safeDays = Math.max(1, Math.floor(Number(days)));
2134
- const cutoff = new Date(Date.now() - safeDays * 24 * 60 * 60 * 1000).toISOString();
2135
- const res = await this._db.prepare(
2136
- `DELETE FROM scheduled_messages
2137
- WHERE status IN ('sent', 'failed') AND updated_at < ?`
2138
- ).bind(cutoff).run();
2139
- return res.meta.changes || 0;
2140
- }
2141
-
2142
- async getTaskStatus(uuid, userId) {
2143
- const row = await this._db.prepare(
2144
- 'SELECT status FROM scheduled_messages WHERE uuid = ? AND user_id = ? LIMIT 1'
2145
- ).bind(uuid, userId).first();
2146
- return row ? row.status : null;
2147
- }
2148
- }
2149
-
2150
- /**
2151
- * Create a D1 adapter from a Cloudflare D1 binding (env.DB).
2152
- * @param {{ prepare: (sql: string) => any }} db
2153
- * @returns {import('./interface.js').DbAdapter}
2154
- */
2155
- function createD1Adapter(db) {
2156
- if (!db || typeof db.prepare !== 'function') {
2157
- throw new Error('[amsg-server] createD1Adapter requires a D1 database binding (env.DB)');
2158
- }
2159
- return new D1Adapter(db);
2160
- }
2161
-
2162
- /**
2163
- * Portable constant-time string comparison.
2164
- *
2165
- * Runs identically on Node (tests) and Cloudflare Workers (prod). We avoid
2166
- * both node:crypto's timingSafeEqual (undefined on Workers historically) and
2167
- * crypto.subtle.timingSafeEqual (absent on Node). Instead we HMAC-SHA256 both
2168
- * inputs under one fresh random key, then compare the two digests. Because the
2169
- * key is random per call, an attacker can't precompute or replay a stable
2170
- * timing oracle; digests are a fixed 32 bytes, so the XOR-accumulate compare
2171
- * runs the same number of steps regardless of input length, with no early-out.
2172
- *
2173
- * globalThis.crypto (Web Crypto) is available on Node >= 20 and on Workers.
2174
- */
2175
- async function constantTimeEqual(a, b) {
2176
- const enc = new TextEncoder();
2177
- const keyBytes = globalThis.crypto.getRandomValues(new Uint8Array(32));
2178
- const key = await globalThis.crypto.subtle.importKey(
2179
- 'raw',
2180
- keyBytes,
2181
- { name: 'HMAC', hash: 'SHA-256' },
2182
- false,
2183
- ['sign']
2184
- );
2185
- const da = new Uint8Array(await globalThis.crypto.subtle.sign('HMAC', key, enc.encode(String(a))));
2186
- const db = new Uint8Array(await globalThis.crypto.subtle.sign('HMAC', key, enc.encode(String(b))));
2187
-
2188
- let diff = 0;
2189
- for (let i = 0; i < da.length; i++) {
2190
- diff |= da[i] ^ db[i];
2191
- }
2192
- return diff === 0;
2193
- }
2194
-
2195
- /**
2196
- * Single-user tenant context manager.
2197
- *
2198
- * Interface-compatible with createTenantContextManager (resolveTenant /
2199
- * initializeTenant), so the existing business handlers reuse it unchanged.
2200
- * No blob registry, no tenant token — db and masterKey come from the caller
2201
- * (the Worker resolves them from env + D1 binding per request).
2202
- */
2203
-
2204
-
2205
- function createSingleUserContextManager({ db, masterKey, serverToken } = {}) {
2206
- if (!db) throw new Error('[amsg-server single-user] db (adapter) is required');
2207
- if (!masterKey) throw new Error('[amsg-server single-user] masterKey is required');
2208
- const token = String(serverToken || '').trim();
2209
-
2210
- async function isAuthorized(headers) {
2211
- if (!token) return true; // open when no shared secret configured
2212
- const provided = getHeader(headers, 'x-client-token');
2213
- if (!provided) return false;
2214
- return constantTimeEqual(provided, token);
2215
- }
2216
-
2217
- async function resolveTenant(headers) {
2218
- if (!(await isAuthorized(headers))) {
2219
- return {
2220
- ok: false,
2221
- error: {
2222
- status: 401,
2223
- body: { success: false, error: { code: 'INVALID_CLIENT_TOKEN', message: '共享密钥无效或缺失' } }
2224
- }
2225
- };
2226
- }
2227
- return {
2228
- ok: true,
2229
- context: { tenantId: 'single', tokenType: 'tenant', db, masterKey }
2230
- };
2231
- }
2232
-
2233
- async function initializeTenant() {
2234
- const schema = await db.initSchema();
2235
- return { tenantId: 'single', schema };
2236
- }
2237
-
2238
- return { resolveTenant, initializeTenant };
2239
- }
2240
-
2241
- /**
2242
- * Handler: single-user-init
2243
- *
2244
- * Idempotent "just create the tables" endpoint for single-user deployments
2245
- * (the degenerate form of init-tenant). Reuses resolveTenant purely to enforce
2246
- * the optional shared secret, then runs initSchema. Issues no token.
2247
- *
2248
- * @param {Object} ctx - Single-user server context (ctx.tenantManager).
2249
- * @returns {{ POST: function }}
2250
- */
2251
- function createSingleUserInitHandler(ctx) {
2252
- async function POST(headers /* , body */) {
2253
- const auth = await ctx.tenantManager.resolveTenant(headers || {});
2254
- if (!auth.ok) {
2255
- return auth.error;
2256
- }
2257
- try {
2258
- const result = await ctx.tenantManager.initializeTenant();
2259
- return {
2260
- status: 200,
2261
- body: { success: true, data: { tenantId: result.tenantId, schema: result.schema } }
2262
- };
2263
- } catch (error) {
2264
- return {
2265
- status: 500,
2266
- body: { success: false, error: { code: 'INIT_FAILED', message: error.message } }
2267
- };
2268
- }
2269
- }
2270
-
2271
- return { POST };
2272
- }
2273
-
2274
- /**
2275
- * Handler: vapid-public-key
2276
- *
2277
- * Exposes this worker's own VAPID public key so a browser frontend can build a
2278
- * Web Push subscription (`applicationServerKey`) at runtime. Each self-hosted
2279
- * worker owns its keypair, so the key can't be baked into the frontend — it
2280
- * pulls it from here.
2281
- *
2282
- * Auth funnels through the same resolveTenant as every other endpoint, so with
2283
- * a serverToken configured this route requires `X-Client-Token` too (the
2284
- * all-or-nothing contract). The public key itself is not a secret; gating it
2285
- * just keeps every endpoint consistent.
2286
- *
2287
- * @param {Object} ctx - Server context ({ vapid, tenantManager, ... }).
2288
- * @returns {{ GET: function }}
2289
- */
2290
-
2291
- function createVapidPublicKeyHandler(ctx) {
2292
- async function GET(url, headers) {
2293
- const effectiveHeaders = headers || url || {};
2294
- const tenantResult = await ctx.tenantManager.resolveTenant(effectiveHeaders);
2295
- if (!tenantResult.ok) {
2296
- return tenantResult.error;
2297
- }
2298
-
2299
- const publicKey = ctx.vapid && ctx.vapid.publicKey;
2300
- if (!publicKey) {
2301
- return {
2302
- status: 503,
2303
- body: {
2304
- success: false,
2305
- error: {
2306
- code: 'VAPID_NOT_CONFIGURED',
2307
- message: 'VAPID 公钥未配置:请为本 Worker 设置 VAPID_PUBLIC_KEY'
2308
- }
2309
- }
2310
- };
2311
- }
2312
-
2313
- return {
2314
- status: 200,
2315
- body: { success: true, publicKey }
2316
- };
2317
- }
2318
-
2319
- return { GET };
2320
- }
2321
-
2322
- /**
2323
- * Single-user ReiStandard server assembly.
2324
- *
2325
- * Same shape as createReiServer ({ handlers }), but wired for a single user:
2326
- * - tenant context comes from createSingleUserContextManager (db + masterKey
2327
- * supplied by the caller; no blob registry, no tenant token)
2328
- * - only the 5 business handlers + an idempotent init route are exposed
2329
- * - send-notifications is NOT exposed over HTTP (cron runs via CF scheduled())
2330
- *
2331
- * @param {Object} config
2332
- * @param {import('./adapters/interface.js').DbAdapter} config.db
2333
- * @param {string} config.masterKey
2334
- * @param {string} [config.serverToken] - optional shared secret (X-Client-Token)
2335
- * @param {{ email?: string, publicKey?: string, privateKey?: string }} [config.vapid]
2336
- * @param {{ sendNotification: function }} [config.webpush] - web-push-compatible sender
2337
- * @returns {{ handlers: Object, ctx: Object }}
2338
- */
2339
-
2340
-
2341
- function createSingleUserServer(config) {
2342
- if (!config || !config.db) throw new Error('[amsg-server single-user] config.db is required');
2343
- if (!config.masterKey) throw new Error('[amsg-server single-user] config.masterKey is required');
2344
-
2345
- const vapid = config.vapid || {};
2346
- const tenantManager = createSingleUserContextManager({
2347
- db: config.db,
2348
- masterKey: config.masterKey,
2349
- serverToken: config.serverToken
2350
- });
2351
-
2352
- const ctx = {
2353
- vapid: {
2354
- email: vapid.email || '',
2355
- publicKey: vapid.publicKey || '',
2356
- privateKey: vapid.privateKey || ''
2357
- },
2358
- webpush: config.webpush || null,
2359
- tenantManager
2360
- };
2361
-
2362
- return {
2363
- ctx,
2364
- handlers: {
2365
- init: createSingleUserInitHandler(ctx),
2366
- getUserKey: createGetUserKeyHandler(ctx),
2367
- scheduleMessage: createScheduleMessageHandler(ctx),
2368
- updateMessage: createUpdateMessageHandler(ctx),
2369
- cancelMessage: createCancelMessageHandler(ctx),
2370
- messages: createMessagesHandler(ctx),
2371
- vapidPublicKey: createVapidPublicKeyHandler(ctx)
2372
- }
2373
- };
2374
- }
2375
-
2376
- /**
2377
- * Web Push — RFC 8030 (transport) + RFC 8291 (aes128gcm payload encryption)
2378
- * + RFC 8292 (VAPID).
2379
- *
2380
- * Pure-WebCrypto implementation. Zero runtime dependencies. Runs natively on
2381
- * Cloudflare Workers, Vercel Edge, Netlify Edge, Deno, Bun, and Node ≥ 19.
2382
- * Node 18 deployments must go through the `adapters/node` entry which
2383
- * polyfills `globalThis.crypto` from `node:crypto.webcrypto`.
2384
- *
2385
- * The wire format produced here is byte-identical to the `web-push` npm
2386
- * package and to the Push API in any modern browser, so amsg-sw and any
2387
- * existing Web Push subscriptions keep working untouched.
2388
- */
2389
-
2390
-
2391
- // RFC 8291 fixed labels (each followed by a NUL byte per HKDF "info" framing).
2392
- const KEY_INFO_PREFIX = utf8('WebPush: info\0');
2393
- const CEK_INFO = utf8('Content-Encoding: aes128gcm\0');
2394
- const NONCE_INFO = utf8('Content-Encoding: nonce\0');
2395
-
2396
- const VAPID_DEFAULT_TTL = 60; // seconds — short, matches single-shot instant.
2397
- const VAPID_TOKEN_LIFETIME = 12 * 3600; // 12h — comfortably under the 24h RFC 8292 cap.
2398
- const RECORD_SIZE = 4096; // arbitrary — must be ≥ ciphertext length.
2399
-
2400
- /**
2401
- * Send a single Web Push notification.
2402
- *
2403
- * @param {Object} args
2404
- * @param {Object} args.subscription - Standard PushSubscription JSON.
2405
- * @param {string} args.subscription.endpoint
2406
- * @param {Object} args.subscription.keys
2407
- * @param {string} args.subscription.keys.p256dh - base64url, 65 B uncompressed P-256 point.
2408
- * @param {string} args.subscription.keys.auth - base64url, 16 B auth secret.
2409
- * @param {string} args.payload - Already-stringified JSON to deliver.
2410
- * @param {Object} args.vapid
2411
- * @param {string} args.vapid.email - VAPID `sub` (mailto: auto-prepended if missing).
2412
- * @param {string} args.vapid.publicKey - base64url, 65 B uncompressed P-256 point.
2413
- * @param {string} args.vapid.privateKey - base64url, 32 B scalar.
2414
- * @param {number} [args.ttl=60] - Push service TTL header, seconds.
2415
- * @param {typeof fetch} [args.fetch] - Override fetch impl (testing / proxy).
2416
- * @returns {Promise<{ statusCode: number, body: string, headers: Headers }>}
2417
- * @throws {Error} err.code = 'PUSH_SEND_FAILED' on push-service error.
2418
- */
2419
- async function sendWebPush({ subscription, payload, vapid, ttl, fetch: fetchImpl }) {
2420
- if (!subscription || typeof subscription.endpoint !== 'string') {
2421
- throw new Error('sendWebPush: invalid subscription');
2422
- }
2423
- if (typeof payload !== 'string') {
2424
- throw new Error('sendWebPush: payload must be a string');
2425
- }
2426
- if (!vapid || !vapid.email || !vapid.publicKey || !vapid.privateKey) {
2427
- throw new Error('VAPID_CONFIG_MISSING');
2428
- }
2429
-
2430
- const subscriptionKeys = subscription.keys || {};
2431
- if (typeof subscriptionKeys.p256dh !== 'string' || typeof subscriptionKeys.auth !== 'string') {
2432
- throw new Error('sendWebPush: subscription.keys.p256dh and .auth are required');
2433
- }
2434
-
2435
- const encryptedBody = await encryptPushPayload({
2436
- plaintext: utf8(payload),
2437
- uaPublicKey: base64UrlToBytes(subscriptionKeys.p256dh),
2438
- authSecret: base64UrlToBytes(subscriptionKeys.auth),
2439
- });
2440
-
2441
- const jwt = await buildVapidJwt({
2442
- audience: originOf(subscription.endpoint),
2443
- subject: normalizeVapidSubject(vapid.email),
2444
- publicKey: vapid.publicKey,
2445
- privateKey: vapid.privateKey,
2446
- });
2447
-
2448
- const fetchFn = fetchImpl || globalThis.fetch;
2449
- if (typeof fetchFn !== 'function') {
2450
- throw new Error('sendWebPush: no fetch implementation available');
2451
- }
2452
-
2453
- const res = await fetchFn(subscription.endpoint, {
2454
- method: 'POST',
2455
- headers: {
2456
- 'Content-Type': 'application/octet-stream',
2457
- 'Content-Encoding': 'aes128gcm',
2458
- 'TTL': String(Number.isFinite(ttl) ? ttl : VAPID_DEFAULT_TTL),
2459
- 'Authorization': `vapid t=${jwt}, k=${vapid.publicKey}`,
2460
- },
2461
- body: encryptedBody,
2462
- });
2463
-
2464
- // Push services return 201 (RFC 8030) or 200/202 depending on implementation.
2465
- if (!res.ok) {
2466
- const text = await safeReadText(res);
2467
- const err = new Error(
2468
- `Web Push delivery failed: ${res.status} ${res.statusText || ''}${text ? ` — ${text}` : ''}`
2469
- );
2470
- err.code = 'PUSH_SEND_FAILED';
2471
- err.statusCode = res.status;
2472
- throw err;
2473
- }
2474
-
2475
- return {
2476
- statusCode: res.status,
2477
- body: await safeReadText(res),
2478
- headers: res.headers,
2479
- };
2480
- }
2481
-
2482
- // ─── RFC 8291: aes128gcm payload encryption ────────────────────────────
2483
-
2484
- /**
2485
- * @param {Object} args
2486
- * @param {Uint8Array} args.plaintext
2487
- * @param {Uint8Array} args.uaPublicKey - recipient p256dh, 65 B uncompressed.
2488
- * @param {Uint8Array} args.authSecret - recipient auth, 16 B.
2489
- * @returns {Promise<Uint8Array>} encryption header || ciphertext
2490
- */
2491
- async function encryptPushPayload({ plaintext, uaPublicKey, authSecret }) {
2492
- // 1. Ephemeral ECDH key pair (as = "application server" per RFC 8291).
2493
- const asKeyPair = await globalThis.crypto.subtle.generateKey(
2494
- { name: 'ECDH', namedCurve: 'P-256' },
2495
- true,
2496
- ['deriveBits']
2497
- );
2498
- const asPublicRaw = new Uint8Array(
2499
- await globalThis.crypto.subtle.exportKey('raw', asKeyPair.publicKey)
2500
- );
2501
-
2502
- // 2. ECDH shared secret with recipient's p256dh.
2503
- const uaPublicCryptoKey = await globalThis.crypto.subtle.importKey(
2504
- 'raw',
2505
- uaPublicKey,
2506
- { name: 'ECDH', namedCurve: 'P-256' },
2507
- false,
2508
- []
2509
- );
2510
- const ecdhSecret = new Uint8Array(
2511
- await globalThis.crypto.subtle.deriveBits(
2512
- { name: 'ECDH', public: uaPublicCryptoKey },
2513
- asKeyPair.privateKey,
2514
- 256
2515
- )
2516
- );
2517
-
2518
- // 3. IKM = HKDF-SHA256(salt=auth_secret, ikm=ecdh_secret,
2519
- // info="WebPush: info\0" || ua_public || as_public, L=32)
2520
- const keyInfo = concatBytes(KEY_INFO_PREFIX, uaPublicKey, asPublicRaw);
2521
- const ikm = await hkdfSha256(authSecret, ecdhSecret, keyInfo, 32);
2522
-
2523
- // 4. encryption_salt (random, 16 B). Goes into the header so the recipient
2524
- // can re-derive CEK / NONCE.
2525
- const salt = randomBytes(16);
2526
-
2527
- // 5. CEK = HKDF-SHA256(salt, ikm, "Content-Encoding: aes128gcm\0", 16)
2528
- const cekBytes = await hkdfSha256(salt, ikm, CEK_INFO, 16);
2529
- const cek = await globalThis.crypto.subtle.importKey(
2530
- 'raw',
2531
- cekBytes,
2532
- { name: 'AES-GCM' },
2533
- false,
2534
- ['encrypt']
2535
- );
2536
-
2537
- // 6. NONCE = HKDF-SHA256(salt, ikm, "Content-Encoding: nonce\0", 12)
2538
- const nonce = await hkdfSha256(salt, ikm, NONCE_INFO, 12);
2539
-
2540
- // 7. Single-record AES-128-GCM. Padding delimiter 0x02 marks the final
2541
- // (and only) record per RFC 8188 §2.
2542
- const padded = concatBytes(plaintext, new Uint8Array([0x02]));
2543
- const ciphertext = new Uint8Array(
2544
- await globalThis.crypto.subtle.encrypt({ name: 'AES-GCM', iv: nonce }, cek, padded)
2545
- );
2546
-
2547
- // 8. aes128gcm content-encoding framing (RFC 8188 §2.1):
2548
- // salt(16) || rs(4 BE) || idlen(1) || keyid(idlen) || ciphertext
2549
- // For Web Push, keyid is the application-server public key (65 B).
2550
- const header = new Uint8Array(16 + 4 + 1 + asPublicRaw.byteLength);
2551
- header.set(salt, 0);
2552
- writeUint32BE(header, 16, RECORD_SIZE);
2553
- header[20] = asPublicRaw.byteLength;
2554
- header.set(asPublicRaw, 21);
2555
-
2556
- return concatBytes(header, ciphertext);
2557
- }
2558
-
2559
- /**
2560
- * HKDF-SHA-256 (extract-then-expand) via WebCrypto.
2561
- *
2562
- * @param {Uint8Array} salt
2563
- * @param {Uint8Array} ikm
2564
- * @param {Uint8Array} info
2565
- * @param {number} length - desired output length in bytes (≤ 32 in our usage).
2566
- * @returns {Promise<Uint8Array>}
2567
- */
2568
- async function hkdfSha256(salt, ikm, info, length) {
2569
- const baseKey = await globalThis.crypto.subtle.importKey(
2570
- 'raw',
2571
- toUint8(ikm),
2572
- { name: 'HKDF' },
2573
- false,
2574
- ['deriveBits']
2575
- );
2576
- const bits = await globalThis.crypto.subtle.deriveBits(
2577
- {
2578
- name: 'HKDF',
2579
- hash: 'SHA-256',
2580
- salt: toUint8(salt),
2581
- info: toUint8(info),
2582
- },
2583
- baseKey,
2584
- length * 8
2585
- );
2586
- return new Uint8Array(bits);
2587
- }
2588
-
2589
- // ─── RFC 8292: VAPID JWT ───────────────────────────────────────────────
2590
-
2591
- /**
2592
- * Build a VAPID `Authorization` JWT for a single push.
2593
- *
2594
- * @param {Object} args
2595
- * @param {string} args.audience - Origin of the push endpoint (e.g. https://fcm.googleapis.com).
2596
- * @param {string} args.subject - VAPID `sub` claim, typically `mailto:you@example.com`.
2597
- * @param {string} args.publicKey - base64url, 65 B uncompressed P-256 point.
2598
- * @param {string} args.privateKey - base64url, 32 B scalar.
2599
- * @returns {Promise<string>} compact JWS (three base64url segments).
2600
- */
2601
- async function buildVapidJwt({ audience, subject, publicKey, privateKey }) {
2602
- const header = jsonToBase64Url({ typ: 'JWT', alg: 'ES256' });
2603
- const payload = jsonToBase64Url({
2604
- aud: audience,
2605
- exp: Math.floor(Date.now() / 1000) + VAPID_TOKEN_LIFETIME,
2606
- sub: subject,
2607
- });
2608
-
2609
- const signingInput = utf8(`${header}.${payload}`);
2610
-
2611
- const pubBytes = base64UrlToBytes(publicKey);
2612
- const privBytes = base64UrlToBytes(privateKey);
2613
- if (pubBytes.length !== 65 || pubBytes[0] !== 0x04) {
2614
- throw new Error('VAPID publicKey must be a 65-byte uncompressed P-256 point (base64url).');
2615
- }
2616
- if (privBytes.length !== 32) {
2617
- throw new Error('VAPID privateKey must be a 32-byte scalar (base64url).');
2618
- }
2619
-
2620
- // Import as JWK so we can supply both private scalar (d) and public point
2621
- // (x, y) in one step — required by WebCrypto for ECDSA signing.
2622
- const jwk = {
2623
- kty: 'EC',
2624
- crv: 'P-256',
2625
- d: bytesToBase64Url(privBytes),
2626
- x: bytesToBase64Url(pubBytes.subarray(1, 33)),
2627
- y: bytesToBase64Url(pubBytes.subarray(33, 65)),
2628
- ext: true,
2629
- };
2630
- const key = await globalThis.crypto.subtle.importKey(
2631
- 'jwk',
2632
- jwk,
2633
- { name: 'ECDSA', namedCurve: 'P-256' },
2634
- false,
2635
- ['sign']
2636
- );
2637
-
2638
- // WebCrypto ECDSA produces a raw 64-byte (r || s) signature — exactly the
2639
- // wire format JOSE/JWS expects, so no DER unwrapping is needed.
2640
- const sig = await globalThis.crypto.subtle.sign(
2641
- { name: 'ECDSA', hash: 'SHA-256' },
2642
- key,
2643
- signingInput
2644
- );
2645
-
2646
- return `${header}.${payload}.${bytesToBase64Url(sig)}`;
2647
- }
2648
-
2649
- // ─── Helpers ───────────────────────────────────────────────────────────
2650
-
2651
- function originOf(endpoint) {
2652
- return new URL(endpoint).origin;
2653
- }
2654
-
2655
- function writeUint32BE(buf, offset, value) {
2656
- buf[offset] = (value >>> 24) & 0xff;
2657
- buf[offset + 1] = (value >>> 16) & 0xff;
2658
- buf[offset + 2] = (value >>> 8) & 0xff;
2659
- buf[offset + 3] = value & 0xff;
2660
- }
2661
-
2662
- async function safeReadText(res) {
2663
- try {
2664
- return await res.text();
2665
- } catch {
2666
- return '';
2667
- }
2668
- }
2669
-
2670
- // Scheduled reminders must survive an offline device, so default to the same
2671
- // 4-week TTL the web-push npm backend applies. sendWebPush's module-level
2672
- // VAPID_DEFAULT_TTL (60s) is tuned for single-shot instant pushes; using it for
2673
- // durable schedules would drop any reminder whose device was offline > 1 min.
2674
- const SCHEDULED_DEFAULT_TTL = 2419200; // 4 weeks, in seconds
2675
-
2676
- /**
2677
- * web-push-compatible sender backed by the Web Crypto implementation above.
2678
- * message-processor calls `ctx.webpush.sendNotification(subscription, payloadString)`,
2679
- * so we only need that one method. VAPID keys are baked in at construction.
2680
- *
2681
- * @param {{ email: string, publicKey: string, privateKey: string }} [vapid]
2682
- * @param {{ ttl?: number }} [options] - Push TTL in seconds; defaults to 4 weeks
2683
- * (matches the web-push backend) so scheduled pushes outlive an offline device.
2684
- * @returns {{ sendNotification: (subscription: Object, payload: string) => Promise<any> }}
2685
- */
2686
- function createWebCryptoWebPush(vapid = {}, { ttl = SCHEDULED_DEFAULT_TTL } = {}) {
2687
- return {
2688
- async sendNotification(subscription, payload) {
2689
- return sendWebPush({
2690
- subscription,
2691
- payload,
2692
- ttl,
2693
- vapid: {
2694
- email: vapid.email,
2695
- publicKey: vapid.publicKey,
2696
- privateKey: vapid.privateKey
2697
- },
2698
- fetch: globalThis.fetch
2699
- });
2700
- }
2701
- };
2702
- }
2703
-
2704
- /**
2705
- * Cloudflare Worker factory for the single-user amsg-server.
2706
- *
2707
- * Mirrors instant's createCloudflareWorker: you pass a buildConfig(env) that
2708
- * returns the single-user config; we build the server per request (cheap) and
2709
- * dispatch. Returns { fetch, scheduled } for `export default`.
2710
- *
2711
- * Routes (server endpoints only — NO /send-notifications; cron is scheduled()):
2712
- * POST /init-tenant → build tables (idempotent)
2713
- * GET /get-user-key → derive user key
2714
- * POST /schedule-message → create task
2715
- * GET /messages → list
2716
- * PUT /update-message → patch
2717
- * DELETE /cancel-message → delete
2718
- * GET /vapid-public-key → this worker's VAPID public key (for the frontend's
2719
- * Web Push subscription); 503 if VAPID_PUBLIC_KEY unset
2720
- *
2721
- * CORS is opt-in: pass `cors: { origin }` in the config (a fixed origin, '*', or
2722
- * an (origin) => allowedOrigin function) to answer OPTIONS preflights and echo
2723
- * Access-Control-* on responses. With no `cors` the Worker stays same-origin.
2724
- */
2725
-
2726
-
2727
- function headersToObject(h) {
2728
- const out = {};
2729
- for (const [k, v] of h) out[k] = v;
2730
- return out;
2731
- }
2732
-
2733
- function jsonResponse(status, body, extraHeaders) {
2734
- return new Response(JSON.stringify(body), {
2735
- status,
2736
- headers: { 'Content-Type': 'application/json; charset=utf-8', ...(extraHeaders || {}) }
2737
- });
2738
- }
2739
-
2740
- // The custom headers the amsg-client sends; browsers preflight any request
2741
- // carrying them, so cross-origin callers need them echoed in the CORS response.
2742
- const CORS_ALLOW_HEADERS =
2743
- 'Content-Type, X-User-Id, X-Payload-Encrypted, X-Encryption-Version, X-Response-Encrypted, X-Client-Token';
2744
- const CORS_ALLOW_METHODS = 'GET, POST, PUT, DELETE, OPTIONS';
2745
-
2746
- /**
2747
- * Resolve the CORS response headers for a request, or null when CORS is off.
2748
- * Opt-in: with no `cors` config the Worker stays same-origin (no headers, and
2749
- * OPTIONS falls through to 404) — so nothing is exposed unless asked for.
2750
- *
2751
- * @param {undefined | { origin: string | ((requestOrigin: string) => string|null|undefined), allowHeaders?: string, maxAge?: number }} cors
2752
- * @param {string} requestOrigin - the request's Origin header (may be '')
2753
- */
2754
- function corsHeadersFor(cors, requestOrigin) {
2755
- if (!cors || cors.origin == null) return null;
2756
- const allowOrigin = typeof cors.origin === 'function'
2757
- ? cors.origin(requestOrigin) || null
2758
- : cors.origin; // e.g. '*' or a fixed origin like 'https://app.example.com'
2759
- if (!allowOrigin) return null;
2760
-
2761
- const headers = {
2762
- 'Access-Control-Allow-Origin': allowOrigin,
2763
- 'Access-Control-Allow-Methods': CORS_ALLOW_METHODS,
2764
- 'Access-Control-Allow-Headers': cors.allowHeaders || CORS_ALLOW_HEADERS,
2765
- 'Access-Control-Max-Age': String(cors.maxAge ?? 86400)
2766
- };
2767
- // A per-origin echo must vary the cache by Origin; '*' does not.
2768
- if (allowOrigin !== '*') headers['Vary'] = 'Origin';
2769
- return headers;
2770
- }
2771
-
2772
- function createSingleUserCloudflareWorker(buildConfig) {
2773
- async function resolveConfig(env) {
2774
- const cfg = await buildConfig(env);
2775
- if (!cfg.db) cfg.db = createD1Adapter(env.DB);
2776
- return cfg;
2777
- }
2778
-
2779
- async function fetch(request, env /* , ctx */) {
2780
- // Error boundary: a handler (or config build) may throw — e.g.
2781
- // schedule-message re-throws a non-unique DB error. Keep the client-facing
2782
- // contract consistent (a JSON envelope, not the runtime's HTML error page).
2783
- try {
2784
- const cfg = await resolveConfig(env);
2785
- const cors = corsHeadersFor(cfg.cors, request.headers.get('origin') || '');
2786
- const method = request.method.toUpperCase();
2787
-
2788
- // CORS preflight: answer OPTIONS directly when CORS is configured.
2789
- if (method === 'OPTIONS') {
2790
- return cors
2791
- ? new Response(null, { status: 204, headers: cors })
2792
- : jsonResponse(404, { success: false, error: { code: 'NOT_FOUND', message: 'Unknown route' } });
2793
- }
2794
-
2795
- const server = createSingleUserServer(cfg);
2796
-
2797
- const url = request.url;
2798
- // Strip trailing slash(es) so `/init-tenant/` routes like `/init-tenant`
2799
- // (endsWith matching is kept so a prefixed mount still resolves).
2800
- const pathname = new URL(url).pathname.replace(/\/+$/, '') || '/';
2801
- const headers = headersToObject(request.headers);
2802
-
2803
- let result;
2804
- if (method === 'POST' && pathname.endsWith('/init-tenant')) {
2805
- result = await server.handlers.init.POST(headers, await request.text());
2806
- } else if (method === 'GET' && pathname.endsWith('/get-user-key')) {
2807
- result = await server.handlers.getUserKey.GET(url, headers);
2808
- } else if (method === 'POST' && pathname.endsWith('/schedule-message')) {
2809
- result = await server.handlers.scheduleMessage.POST(headers, await request.text());
2810
- } else if (method === 'GET' && pathname.endsWith('/messages')) {
2811
- result = await server.handlers.messages.GET(url, headers);
2812
- } else if (method === 'PUT' && pathname.endsWith('/update-message')) {
2813
- result = await server.handlers.updateMessage.PUT(url, headers, await request.text());
2814
- } else if (method === 'DELETE' && pathname.endsWith('/cancel-message')) {
2815
- result = await server.handlers.cancelMessage.DELETE(url, headers);
2816
- } else if (method === 'GET' && pathname.endsWith('/vapid-public-key')) {
2817
- result = await server.handlers.vapidPublicKey.GET(url, headers);
2818
- } else {
2819
- result = { status: 404, body: { success: false, error: { code: 'NOT_FOUND', message: 'Unknown route' } } };
2820
- }
2821
-
2822
- return jsonResponse(result.status, result.body, cors);
2823
- } catch (error) {
2824
- console.error('[amsg single-user] fetch() unhandled error:', error && error.message);
2825
- return jsonResponse(500, { success: false, error: { code: 'INTERNAL_ERROR', message: '服务器内部错误' } });
2826
- }
2827
- }
2828
-
2829
- async function scheduled(event, env /* , ctx */) {
2830
- const cfg = await resolveConfig(env);
2831
- const vapid = cfg.vapid || {};
2832
- if (!cfg.webpush || !vapid.email || !vapid.publicKey || !vapid.privateKey) {
2833
- console.error('[amsg single-user] scheduled(): VAPID/webpush not configured; skipping tick');
2834
- return;
2835
- }
2836
- // Swallow tick failures: pending tasks stay pending, so the next cron tick
2837
- // retries them. Logging keeps the failure visible in the tail log.
2838
- try {
2839
- await runScheduledTick({ db: cfg.db, masterKey: cfg.masterKey, vapid, webpush: cfg.webpush });
2840
- } catch (error) {
2841
- console.error('[amsg single-user] scheduled(): tick failed:', error && error.message);
2842
- }
2843
- }
2844
-
2845
- return { fetch, scheduled };
2846
- }
2847
-
2848
- export { createCancelMessageHandler as a, createUpdateMessageHandler as b, createMessagesHandler as c, createScheduleMessageHandler as d, createGetUserKeyHandler as e, createD1Adapter as f, getHeader as g, createSingleUserCloudflareWorker as h, isValidUUIDv4 as i, createSingleUserServer as j, createWebCryptoWebPush as k, decryptFromStorage as l, decryptPayload as m, deriveUserEncryptionKey as n, encryptForStorage as o, parseJsonBody as p, isValidISO8601 as q, runScheduledTick as r, isValidUUID as s, isValidUrl as t, validateScheduleMessagePayload as u, validateLlmMessagesArray as v, validateSplitPattern as w };