@rei-standard/amsg-server 2.5.3 → 2.6.0-next.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunk-6WA3XDPP.mjs +1826 -0
- package/dist/chunk-S5DV7AUH.cjs +1826 -0
- package/dist/cloudflare-5Ryuxz10.d.cts +2775 -0
- package/dist/cloudflare-5Ryuxz10.d.ts +2775 -0
- package/dist/cloudflare.cjs +22 -0
- package/dist/cloudflare.d.cts +3 -0
- package/dist/cloudflare.d.ts +3 -0
- package/dist/cloudflare.mjs +22 -0
- package/dist/index.cjs +50 -1126
- package/dist/index.d.cts +37 -1769
- package/dist/index.d.ts +37 -1769
- package/dist/index.mjs +43 -1119
- package/package.json +9 -3
package/dist/index.d.ts
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { g as getHeader, p as parseJsonBody, i as isValidUUIDv4, r as runScheduledTick, c as createMessagesHandler, a as createCancelMessageHandler, b as createUpdateMessageHandler, d as createScheduleMessageHandler, e as createGetUserKeyHandler } from './cloudflare-5Ryuxz10.js';
|
|
2
|
+
export { f as createD1Adapter, h as createSingleUserCloudflareWorker, j as createSingleUserServer, k as createWebCryptoWebPush, l as decryptFromStorage, m as decryptPayload, n as deriveUserEncryptionKey, o as encryptForStorage, q as isValidISO8601, s as isValidUUID, t as isValidUrl, v as validateLlmMessagesArray, u as validateScheduleMessagePayload, w as validateSplitPattern } from './cloudflare-5Ryuxz10.js';
|
|
3
|
+
import { createHash, randomBytes, createCipheriv, createDecipheriv, timingSafeEqual, createHmac, randomUUID } from 'crypto';
|
|
4
|
+
import { normalizeVapidSubject } from '@rei-standard/amsg-shared';
|
|
2
5
|
export { validateAvatarUrl } from '@rei-standard/amsg-shared';
|
|
3
|
-
import { createDecipheriv, createHash, randomBytes, createCipheriv, randomUUID, timingSafeEqual, createHmac } from 'crypto';
|
|
4
6
|
|
|
5
7
|
/**
|
|
6
8
|
* Adapter Factory
|
|
@@ -54,412 +56,6 @@ async function createAdapter(config) {
|
|
|
54
56
|
}
|
|
55
57
|
}
|
|
56
58
|
|
|
57
|
-
/**
|
|
58
|
-
* Validation utility library (SDK version)
|
|
59
|
-
* ReiStandard SDK v2.0.1
|
|
60
|
-
*/
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
/**
|
|
64
|
-
* Validate ISO 8601 date string.
|
|
65
|
-
* @param {string} dateString
|
|
66
|
-
* @returns {boolean}
|
|
67
|
-
*/
|
|
68
|
-
function isValidISO8601(dateString) {
|
|
69
|
-
const date = new Date(dateString);
|
|
70
|
-
return date instanceof Date && !isNaN(date.getTime());
|
|
71
|
-
}
|
|
72
|
-
|
|
73
|
-
/**
|
|
74
|
-
* Validate URL format.
|
|
75
|
-
* @param {string} urlString
|
|
76
|
-
* @returns {boolean}
|
|
77
|
-
*/
|
|
78
|
-
function isValidUrl(urlString) {
|
|
79
|
-
try {
|
|
80
|
-
new URL(urlString);
|
|
81
|
-
return true;
|
|
82
|
-
} catch {
|
|
83
|
-
return false;
|
|
84
|
-
}
|
|
85
|
-
}
|
|
86
|
-
|
|
87
|
-
/**
|
|
88
|
-
* Validate UUID format.
|
|
89
|
-
* @param {string} uuid
|
|
90
|
-
* @returns {boolean}
|
|
91
|
-
*/
|
|
92
|
-
function isValidUUID(uuid) {
|
|
93
|
-
const uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
94
|
-
return uuidRegex.test(uuid);
|
|
95
|
-
}
|
|
96
|
-
|
|
97
|
-
/**
|
|
98
|
-
* Validate UUID v4 format.
|
|
99
|
-
* @param {string} uuid
|
|
100
|
-
* @returns {boolean}
|
|
101
|
-
*/
|
|
102
|
-
function isValidUUIDv4(uuid) {
|
|
103
|
-
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;
|
|
104
|
-
return uuidV4Regex.test(uuid);
|
|
105
|
-
}
|
|
106
|
-
|
|
107
|
-
const VALID_LLM_MESSAGE_ROLES = new Set(['system', 'user', 'assistant', 'tool']);
|
|
108
|
-
|
|
109
|
-
const SPLIT_PATTERN_MAX_LENGTH = 200;
|
|
110
|
-
const SPLIT_PATTERN_MAX_ITEMS = 10;
|
|
111
|
-
|
|
112
|
-
/**
|
|
113
|
-
* Validate the optional `splitPattern` field (amsg-server scheduled tasks
|
|
114
|
-
* only; amsg-instant 0.8.0 dropped its request-level `splitPattern`).
|
|
115
|
-
* Accepts `string`, `string[]`, or absent/null. Returns an error message
|
|
116
|
-
* string, or null when valid.
|
|
117
|
-
*
|
|
118
|
-
* Limits (per-item length ≤ 200, array ≤ 10 items, must compile via
|
|
119
|
-
* `new RegExp(item)`) are an **input-size guard**, NOT a ReDoS defense —
|
|
120
|
-
* a 6-character pattern like `(a+)+$` is enough to trigger catastrophic
|
|
121
|
-
* backtracking. The real backstop is Worker / runtime CPU limits + the
|
|
122
|
-
* fact that splitPattern is stored under the user's own encrypted task
|
|
123
|
-
* and matched against output from the user's own LLM API key, so the
|
|
124
|
-
* blast radius is self-inflicted only (no cross-tenant attack surface).
|
|
125
|
-
*
|
|
126
|
-
* @param {unknown} value
|
|
127
|
-
* @returns {string | null}
|
|
128
|
-
*/
|
|
129
|
-
function validateSplitPattern(value) {
|
|
130
|
-
if (value === undefined || value === null) return null;
|
|
131
|
-
const isArray = Array.isArray(value);
|
|
132
|
-
const items = isArray ? value : [value];
|
|
133
|
-
if (isArray && items.length === 0) return null; // empty array = use default
|
|
134
|
-
if (items.length > SPLIT_PATTERN_MAX_ITEMS) {
|
|
135
|
-
return `splitPattern 数组最多 ${SPLIT_PATTERN_MAX_ITEMS} 项`;
|
|
136
|
-
}
|
|
137
|
-
for (let i = 0; i < items.length; i++) {
|
|
138
|
-
const s = items[i];
|
|
139
|
-
const label = isArray ? `splitPattern[${i}]` : 'splitPattern';
|
|
140
|
-
if (typeof s !== 'string') return `${label} 必须是字符串`;
|
|
141
|
-
if (s.length > SPLIT_PATTERN_MAX_LENGTH) {
|
|
142
|
-
return `${label} 不能超过 ${SPLIT_PATTERN_MAX_LENGTH} 字符`;
|
|
143
|
-
}
|
|
144
|
-
try { new RegExp(s); }
|
|
145
|
-
catch (_) { return `${label} 不是有效正则表达式`; }
|
|
146
|
-
}
|
|
147
|
-
return null;
|
|
148
|
-
}
|
|
149
|
-
|
|
150
|
-
/**
|
|
151
|
-
* Validate an OpenAI-style messages array. Same shape contract as
|
|
152
|
-
* `@rei-standard/amsg-instant` (kept in lockstep on purpose — both packages
|
|
153
|
-
* end up forwarding this to the same LLM body).
|
|
154
|
-
*
|
|
155
|
-
* @param {unknown} messages
|
|
156
|
-
* @returns {string | null} Error message, or null if valid.
|
|
157
|
-
*/
|
|
158
|
-
function validateLlmMessagesArray(messages) {
|
|
159
|
-
if (!Array.isArray(messages) || messages.length === 0) {
|
|
160
|
-
return 'messages must be a non-empty array';
|
|
161
|
-
}
|
|
162
|
-
for (let i = 0; i < messages.length; i++) {
|
|
163
|
-
const m = messages[i];
|
|
164
|
-
if (!m || typeof m !== 'object' || Array.isArray(m)) {
|
|
165
|
-
return `messages[${i}] must be an object`;
|
|
166
|
-
}
|
|
167
|
-
if (!VALID_LLM_MESSAGE_ROLES.has(m.role)) {
|
|
168
|
-
return `messages[${i}].role must be one of system / user / assistant / tool`;
|
|
169
|
-
}
|
|
170
|
-
if (typeof m.content === 'string') {
|
|
171
|
-
if (!m.content) return `messages[${i}].content must be a non-empty string`;
|
|
172
|
-
} else if (Array.isArray(m.content)) {
|
|
173
|
-
if (m.content.length === 0) return `messages[${i}].content array must be non-empty`;
|
|
174
|
-
// Element schema is intentionally not enforced — passed through to LLM as-is.
|
|
175
|
-
} else {
|
|
176
|
-
return `messages[${i}].content must be a non-empty string or a non-empty array`;
|
|
177
|
-
}
|
|
178
|
-
}
|
|
179
|
-
return null;
|
|
180
|
-
}
|
|
181
|
-
|
|
182
|
-
/**
|
|
183
|
-
* Validate the schedule-message request payload.
|
|
184
|
-
*
|
|
185
|
-
* @param {Object} payload
|
|
186
|
-
* @returns {{ valid: boolean, errorCode?: string, errorMessage?: string, details?: Object }}
|
|
187
|
-
*/
|
|
188
|
-
function validateScheduleMessagePayload(payload) {
|
|
189
|
-
if (!payload.contactName || typeof payload.contactName !== 'string') {
|
|
190
|
-
return { valid: false, errorCode: 'INVALID_PARAMETERS', errorMessage: '缺少必需参数或参数格式错误', details: { missingFields: ['contactName'] } };
|
|
191
|
-
}
|
|
192
|
-
|
|
193
|
-
if (!payload.messageType || !['fixed', 'prompted', 'auto', 'instant'].includes(payload.messageType)) {
|
|
194
|
-
return { valid: false, errorCode: 'INVALID_MESSAGE_TYPE', errorMessage: '消息类型无效', details: { providedType: payload.messageType, allowedTypes: ['fixed', 'prompted', 'auto', 'instant'] } };
|
|
195
|
-
}
|
|
196
|
-
|
|
197
|
-
if (!payload.firstSendTime || !isValidISO8601(payload.firstSendTime)) {
|
|
198
|
-
return { valid: false, errorCode: 'INVALID_TIMESTAMP', errorMessage: '时间格式无效', details: { field: 'firstSendTime' } };
|
|
199
|
-
}
|
|
200
|
-
|
|
201
|
-
if (payload.firstSendTime && new Date(payload.firstSendTime) <= new Date()) {
|
|
202
|
-
return { valid: false, errorCode: 'INVALID_TIMESTAMP', errorMessage: '时间必须在未来', details: { field: 'firstSendTime', reason: 'must be in the future' } };
|
|
203
|
-
}
|
|
204
|
-
|
|
205
|
-
if (!payload.pushSubscription || typeof payload.pushSubscription !== 'object') {
|
|
206
|
-
return { valid: false, errorCode: 'INVALID_PARAMETERS', errorMessage: '缺少必需参数或参数格式错误', details: { missingFields: ['pushSubscription'] } };
|
|
207
|
-
}
|
|
208
|
-
|
|
209
|
-
if (payload.recurrenceType && !['none', 'daily', 'weekly'].includes(payload.recurrenceType)) {
|
|
210
|
-
return { valid: false, errorCode: 'INVALID_PARAMETERS', errorMessage: '缺少必需参数或参数格式错误', details: { invalidFields: ['recurrenceType'] } };
|
|
211
|
-
}
|
|
212
|
-
|
|
213
|
-
if (
|
|
214
|
-
payload.maxTokens !== undefined &&
|
|
215
|
-
payload.maxTokens !== null &&
|
|
216
|
-
(!Number.isInteger(payload.maxTokens) || payload.maxTokens <= 0)
|
|
217
|
-
) {
|
|
218
|
-
return { valid: false, errorCode: 'INVALID_PARAMETERS', errorMessage: '缺少必需参数或参数格式错误', details: { invalidFields: ['maxTokens'] } };
|
|
219
|
-
}
|
|
220
|
-
|
|
221
|
-
if (payload.messageType === 'fixed') {
|
|
222
|
-
if (!payload.userMessage) {
|
|
223
|
-
return { valid: false, errorCode: 'INVALID_PARAMETERS', errorMessage: '缺少必需参数或参数格式错误', details: { missingFields: ['userMessage (required for fixed type)'] } };
|
|
224
|
-
}
|
|
225
|
-
}
|
|
226
|
-
|
|
227
|
-
// ─── Prompt schema (shared by prompted / auto / instant AI configs) ──
|
|
228
|
-
//
|
|
229
|
-
// Callers provide *exactly one of* `completePrompt` (string) or `messages`
|
|
230
|
-
// (OpenAI-style array). Same contract as @rei-standard/amsg-instant; the
|
|
231
|
-
// server's LLM path forwards either verbatim.
|
|
232
|
-
const promptCheck = (() => {
|
|
233
|
-
const hasCompletePrompt = payload.completePrompt !== undefined && payload.completePrompt !== null && payload.completePrompt !== '';
|
|
234
|
-
const hasMessages = payload.messages !== undefined && payload.messages !== null;
|
|
235
|
-
if (hasCompletePrompt && hasMessages) {
|
|
236
|
-
return {
|
|
237
|
-
error: { code: 'INVALID_PARAMETERS', message: 'exactly one of `completePrompt` or `messages` must be provided(两者不能同时出现)', details: { invalidFields: ['completePrompt', 'messages'] } },
|
|
238
|
-
hasCompletePrompt: true, hasMessages: true,
|
|
239
|
-
};
|
|
240
|
-
}
|
|
241
|
-
if (hasMessages) {
|
|
242
|
-
const err = validateLlmMessagesArray(payload.messages);
|
|
243
|
-
if (err) {
|
|
244
|
-
return {
|
|
245
|
-
error: { code: 'INVALID_PARAMETERS', message: err, details: { invalidFields: ['messages'] } },
|
|
246
|
-
hasCompletePrompt: false, hasMessages: true,
|
|
247
|
-
};
|
|
248
|
-
}
|
|
249
|
-
}
|
|
250
|
-
return { error: null, hasCompletePrompt, hasMessages };
|
|
251
|
-
})();
|
|
252
|
-
|
|
253
|
-
if (promptCheck.error) {
|
|
254
|
-
return { valid: false, errorCode: promptCheck.error.code, errorMessage: promptCheck.error.message, details: promptCheck.error.details };
|
|
255
|
-
}
|
|
256
|
-
const hasPrompt = promptCheck.hasCompletePrompt || promptCheck.hasMessages;
|
|
257
|
-
|
|
258
|
-
if (payload.messageType === 'prompted' || payload.messageType === 'auto') {
|
|
259
|
-
const missingAiFields = [];
|
|
260
|
-
if (!hasPrompt) missingAiFields.push('completePrompt or messages');
|
|
261
|
-
if (!payload.apiUrl) missingAiFields.push('apiUrl');
|
|
262
|
-
if (!payload.apiKey) missingAiFields.push('apiKey');
|
|
263
|
-
if (!payload.primaryModel) missingAiFields.push('primaryModel');
|
|
264
|
-
if (missingAiFields.length > 0) {
|
|
265
|
-
return { valid: false, errorCode: 'INVALID_PARAMETERS', errorMessage: '缺少必需参数或参数格式错误', details: { missingFields: missingAiFields } };
|
|
266
|
-
}
|
|
267
|
-
}
|
|
268
|
-
|
|
269
|
-
if (payload.messageType === 'instant') {
|
|
270
|
-
if (payload.recurrenceType && payload.recurrenceType !== 'none') {
|
|
271
|
-
return { valid: false, errorCode: 'INVALID_PARAMETERS', errorMessage: 'instant 类型的 recurrenceType 必须为 none', details: { invalidFields: ['recurrenceType (must be "none" for instant type)'] } };
|
|
272
|
-
}
|
|
273
|
-
const hasAiConfig = hasPrompt && payload.apiUrl && payload.apiKey && payload.primaryModel;
|
|
274
|
-
const hasUserMessage = payload.userMessage;
|
|
275
|
-
if (!hasAiConfig && !hasUserMessage) {
|
|
276
|
-
return { valid: false, errorCode: 'INVALID_PARAMETERS', errorMessage: 'instant 类型必须提供 userMessage 或完整的 AI 配置', details: { missingFields: ['userMessage or ((completePrompt | messages) + apiUrl + apiKey + primaryModel)'] } };
|
|
277
|
-
}
|
|
278
|
-
}
|
|
279
|
-
|
|
280
|
-
if (
|
|
281
|
-
payload.temperature !== undefined &&
|
|
282
|
-
payload.temperature !== null &&
|
|
283
|
-
(typeof payload.temperature !== 'number' || !Number.isFinite(payload.temperature))
|
|
284
|
-
) {
|
|
285
|
-
return { valid: false, errorCode: 'INVALID_PARAMETERS', errorMessage: '缺少必需参数或参数格式错误', details: { invalidFields: ['temperature (must be a finite number)'] } };
|
|
286
|
-
}
|
|
287
|
-
|
|
288
|
-
const avatarErr = validateAvatarUrl(payload.avatarUrl);
|
|
289
|
-
if (avatarErr) {
|
|
290
|
-
// Soft-strip: a bad avatarUrl (data: URI / oversized / malformed) used to
|
|
291
|
-
// 400 the whole schedule. Avatar is cosmetic — drop the field, log, and
|
|
292
|
-
// let the rest of the task ship. See standards §6.2.
|
|
293
|
-
console.warn('[amsg-server] avatarUrl 不合法,已置空:', avatarErr);
|
|
294
|
-
payload.avatarUrl = null;
|
|
295
|
-
}
|
|
296
|
-
if (payload.uuid && !isValidUUID(payload.uuid)) {
|
|
297
|
-
return { valid: false, errorCode: 'INVALID_PARAMETERS', errorMessage: '缺少必需参数或参数格式错误', details: { invalidFields: ['uuid (invalid UUID format)'] } };
|
|
298
|
-
}
|
|
299
|
-
// messageSubtype is a free-form string tag forwarded to SW-side push payload
|
|
300
|
-
// for classification. Only the type is enforced; the taxonomy is the
|
|
301
|
-
// consumer's call (previously the enum was chat/forum/moment).
|
|
302
|
-
if (
|
|
303
|
-
payload.messageSubtype !== undefined &&
|
|
304
|
-
payload.messageSubtype !== null &&
|
|
305
|
-
typeof payload.messageSubtype !== 'string'
|
|
306
|
-
) {
|
|
307
|
-
return { valid: false, errorCode: 'INVALID_PARAMETERS', errorMessage: '缺少必需参数或参数格式错误', details: { invalidFields: ['messageSubtype'] } };
|
|
308
|
-
}
|
|
309
|
-
|
|
310
|
-
const splitErr = validateSplitPattern(payload.splitPattern);
|
|
311
|
-
if (splitErr) {
|
|
312
|
-
return { valid: false, errorCode: 'INVALID_PARAMETERS', errorMessage: splitErr, details: { invalidFields: ['splitPattern'] } };
|
|
313
|
-
}
|
|
314
|
-
|
|
315
|
-
return { valid: true };
|
|
316
|
-
}
|
|
317
|
-
|
|
318
|
-
/**
|
|
319
|
-
* Request payload utilities.
|
|
320
|
-
* Keeps body parsing and shape validation consistent across handlers.
|
|
321
|
-
*/
|
|
322
|
-
|
|
323
|
-
const REQUEST_ERRORS = {
|
|
324
|
-
INVALID_JSON: { code: 'INVALID_JSON', message: '请求体不是有效的 JSON' },
|
|
325
|
-
INVALID_REQUEST_BODY: { code: 'INVALID_REQUEST_BODY', message: '请求体格式无效' },
|
|
326
|
-
INVALID_ENCRYPTED_PAYLOAD: { code: 'INVALID_ENCRYPTED_PAYLOAD', message: '加密数据格式错误' }
|
|
327
|
-
};
|
|
328
|
-
|
|
329
|
-
/**
|
|
330
|
-
* @typedef {{ code: string, message: string }} ValidationError
|
|
331
|
-
*/
|
|
332
|
-
|
|
333
|
-
/**
|
|
334
|
-
* @typedef {{
|
|
335
|
-
* invalidJson?: ValidationError,
|
|
336
|
-
* invalidType?: ValidationError
|
|
337
|
-
* }} ParseBodyOptions
|
|
338
|
-
*/
|
|
339
|
-
|
|
340
|
-
/**
|
|
341
|
-
* @typedef {{
|
|
342
|
-
* ok: true,
|
|
343
|
-
* data: Record<string, any>
|
|
344
|
-
* } | {
|
|
345
|
-
* ok: false,
|
|
346
|
-
* error: ValidationError
|
|
347
|
-
* }} ParseBodyResult
|
|
348
|
-
*/
|
|
349
|
-
|
|
350
|
-
/**
|
|
351
|
-
* Parse body into a JSON object.
|
|
352
|
-
*
|
|
353
|
-
* @param {unknown} body
|
|
354
|
-
* @param {ParseBodyOptions} [options]
|
|
355
|
-
* @returns {ParseBodyResult}
|
|
356
|
-
*/
|
|
357
|
-
function parseBodyAsObject(body, options = {}) {
|
|
358
|
-
const invalidJson = options.invalidJson || REQUEST_ERRORS.INVALID_JSON;
|
|
359
|
-
const invalidType = options.invalidType || REQUEST_ERRORS.INVALID_REQUEST_BODY;
|
|
360
|
-
|
|
361
|
-
let parsed = body;
|
|
362
|
-
if (typeof parsed === 'string') {
|
|
363
|
-
try {
|
|
364
|
-
parsed = JSON.parse(parsed);
|
|
365
|
-
} catch {
|
|
366
|
-
return { ok: false, error: invalidJson };
|
|
367
|
-
}
|
|
368
|
-
}
|
|
369
|
-
|
|
370
|
-
if (!isPlainObject(parsed)) {
|
|
371
|
-
return { ok: false, error: invalidType };
|
|
372
|
-
}
|
|
373
|
-
|
|
374
|
-
return { ok: true, data: parsed };
|
|
375
|
-
}
|
|
376
|
-
|
|
377
|
-
/**
|
|
378
|
-
* Parse a standard JSON object body.
|
|
379
|
-
*
|
|
380
|
-
* @param {unknown} body
|
|
381
|
-
* @returns {ParseBodyResult}
|
|
382
|
-
*/
|
|
383
|
-
function parseJsonBody(body) {
|
|
384
|
-
return parseBodyAsObject(body, {
|
|
385
|
-
invalidJson: REQUEST_ERRORS.INVALID_JSON,
|
|
386
|
-
invalidType: REQUEST_ERRORS.INVALID_REQUEST_BODY
|
|
387
|
-
});
|
|
388
|
-
}
|
|
389
|
-
|
|
390
|
-
/**
|
|
391
|
-
* Check if a value is a plain object (and not null/array).
|
|
392
|
-
*
|
|
393
|
-
* @param {unknown} value
|
|
394
|
-
* @returns {value is Record<string, any>}
|
|
395
|
-
*/
|
|
396
|
-
function isPlainObject(value) {
|
|
397
|
-
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
398
|
-
}
|
|
399
|
-
|
|
400
|
-
/**
|
|
401
|
-
* Check if an object follows the encrypted payload envelope shape.
|
|
402
|
-
*
|
|
403
|
-
* @param {unknown} payload
|
|
404
|
-
* @returns {payload is { iv: string, authTag: string, encryptedData: string }}
|
|
405
|
-
*/
|
|
406
|
-
function isEncryptedEnvelope(payload) {
|
|
407
|
-
if (!isPlainObject(payload)) return false;
|
|
408
|
-
|
|
409
|
-
return (
|
|
410
|
-
typeof payload.iv === 'string' &&
|
|
411
|
-
typeof payload.authTag === 'string' &&
|
|
412
|
-
typeof payload.encryptedData === 'string'
|
|
413
|
-
);
|
|
414
|
-
}
|
|
415
|
-
|
|
416
|
-
/**
|
|
417
|
-
* Parse and validate an encrypted payload envelope.
|
|
418
|
-
*
|
|
419
|
-
* @param {unknown} body
|
|
420
|
-
* @returns {ParseBodyResult}
|
|
421
|
-
*/
|
|
422
|
-
function parseEncryptedBody(body) {
|
|
423
|
-
const parsedBody = parseBodyAsObject(body, {
|
|
424
|
-
invalidJson: REQUEST_ERRORS.INVALID_ENCRYPTED_PAYLOAD,
|
|
425
|
-
invalidType: REQUEST_ERRORS.INVALID_ENCRYPTED_PAYLOAD
|
|
426
|
-
});
|
|
427
|
-
|
|
428
|
-
if (!parsedBody.ok) {
|
|
429
|
-
return parsedBody;
|
|
430
|
-
}
|
|
431
|
-
|
|
432
|
-
if (!isEncryptedEnvelope(parsedBody.data)) {
|
|
433
|
-
return { ok: false, error: REQUEST_ERRORS.INVALID_ENCRYPTED_PAYLOAD };
|
|
434
|
-
}
|
|
435
|
-
|
|
436
|
-
return parsedBody;
|
|
437
|
-
}
|
|
438
|
-
|
|
439
|
-
/**
|
|
440
|
-
* Read a header value case-insensitively.
|
|
441
|
-
*
|
|
442
|
-
* @param {Record<string, any>} headers
|
|
443
|
-
* @param {string} name
|
|
444
|
-
* @returns {string}
|
|
445
|
-
*/
|
|
446
|
-
function getHeader(headers = {}, name) {
|
|
447
|
-
if (!headers || typeof headers !== 'object') {
|
|
448
|
-
return '';
|
|
449
|
-
}
|
|
450
|
-
|
|
451
|
-
const lowerName = String(name || '').toLowerCase();
|
|
452
|
-
if (!lowerName) return '';
|
|
453
|
-
|
|
454
|
-
for (const [key, value] of Object.entries(headers)) {
|
|
455
|
-
if (String(key).toLowerCase() === lowerName) {
|
|
456
|
-
return String(value || '').trim();
|
|
457
|
-
}
|
|
458
|
-
}
|
|
459
|
-
|
|
460
|
-
return '';
|
|
461
|
-
}
|
|
462
|
-
|
|
463
59
|
/**
|
|
464
60
|
* Handler: init-tenant
|
|
465
61
|
* ReiStandard SDK v2.0.1
|
|
@@ -597,1386 +193,58 @@ function createInitTenantHandler(ctx) {
|
|
|
597
193
|
}
|
|
598
194
|
|
|
599
195
|
/**
|
|
600
|
-
*
|
|
601
|
-
* ReiStandard SDK v2.0.1
|
|
602
|
-
*
|
|
603
|
-
* Wraps AES-256-GCM operations for request/response and storage encryption.
|
|
604
|
-
*/
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
/**
|
|
608
|
-
* Derive a user-specific encryption key from the master key.
|
|
609
|
-
*
|
|
610
|
-
* @param {string} userId - Unique user identifier.
|
|
611
|
-
* @param {string} masterKey - 64-char hex master key.
|
|
612
|
-
* @returns {string} 64-char hex key.
|
|
613
|
-
*/
|
|
614
|
-
function deriveUserEncryptionKey(userId, masterKey) {
|
|
615
|
-
return createHash('sha256')
|
|
616
|
-
.update(masterKey + userId)
|
|
617
|
-
.digest('hex')
|
|
618
|
-
.slice(0, 64);
|
|
619
|
-
}
|
|
620
|
-
|
|
621
|
-
/**
|
|
622
|
-
* Decrypt a client-encrypted request body (AES-256-GCM, base64 encoded).
|
|
623
|
-
*
|
|
624
|
-
* @param {{ iv: string, authTag: string, encryptedData: string }} encryptedPayload
|
|
625
|
-
* @param {string} encryptionKey - 64-char hex key.
|
|
626
|
-
* @returns {Object} Decrypted JSON object.
|
|
627
|
-
*/
|
|
628
|
-
function decryptPayload(encryptedPayload, encryptionKey) {
|
|
629
|
-
const { iv, authTag, encryptedData } = encryptedPayload;
|
|
630
|
-
|
|
631
|
-
const decipher = createDecipheriv(
|
|
632
|
-
'aes-256-gcm',
|
|
633
|
-
Buffer.from(encryptionKey, 'hex'),
|
|
634
|
-
Buffer.from(iv, 'base64')
|
|
635
|
-
);
|
|
636
|
-
|
|
637
|
-
decipher.setAuthTag(Buffer.from(authTag, 'base64'));
|
|
638
|
-
|
|
639
|
-
const decrypted = Buffer.concat([
|
|
640
|
-
decipher.update(Buffer.from(encryptedData, 'base64')),
|
|
641
|
-
decipher.final()
|
|
642
|
-
]);
|
|
643
|
-
|
|
644
|
-
return JSON.parse(decrypted.toString('utf8'));
|
|
645
|
-
}
|
|
646
|
-
|
|
647
|
-
/**
|
|
648
|
-
* Encrypt a JSON payload for API transfer (AES-256-GCM, base64 encoded).
|
|
649
|
-
*
|
|
650
|
-
* @param {string|Object} payload
|
|
651
|
-
* @param {string} encryptionKey - 64-char hex key.
|
|
652
|
-
* @returns {{ iv: string, authTag: string, encryptedData: string }}
|
|
653
|
-
*/
|
|
654
|
-
function encryptPayload(payload, encryptionKey) {
|
|
655
|
-
const plaintext = typeof payload === 'string' ? payload : JSON.stringify(payload);
|
|
656
|
-
const iv = randomBytes(12);
|
|
657
|
-
const cipher = createCipheriv('aes-256-gcm', Buffer.from(encryptionKey, 'hex'), iv);
|
|
658
|
-
const encrypted = Buffer.concat([cipher.update(plaintext, 'utf8'), cipher.final()]);
|
|
659
|
-
const authTag = cipher.getAuthTag();
|
|
660
|
-
|
|
661
|
-
return {
|
|
662
|
-
iv: iv.toString('base64'),
|
|
663
|
-
authTag: authTag.toString('base64'),
|
|
664
|
-
encryptedData: encrypted.toString('base64')
|
|
665
|
-
};
|
|
666
|
-
}
|
|
667
|
-
|
|
668
|
-
/**
|
|
669
|
-
* Encrypt data for database storage (hex encoded, colon-separated).
|
|
670
|
-
*
|
|
671
|
-
* @param {string} text - Plaintext string.
|
|
672
|
-
* @param {string} encryptionKey - 64-char hex key.
|
|
673
|
-
* @returns {string} Format: iv:authTag:encryptedData
|
|
674
|
-
*/
|
|
675
|
-
function encryptForStorage(text, encryptionKey) {
|
|
676
|
-
const iv = randomBytes(16);
|
|
677
|
-
const cipher = createCipheriv('aes-256-gcm', Buffer.from(encryptionKey, 'hex'), iv);
|
|
678
|
-
const encrypted = cipher.update(text, 'utf8', 'hex') + cipher.final('hex');
|
|
679
|
-
const authTag = cipher.getAuthTag();
|
|
680
|
-
return `${iv.toString('hex')}:${authTag.toString('hex')}:${encrypted}`;
|
|
681
|
-
}
|
|
682
|
-
|
|
683
|
-
/**
|
|
684
|
-
* Decrypt data from database storage format.
|
|
685
|
-
*
|
|
686
|
-
* @param {string} encryptedText - Format: iv:authTag:encryptedData
|
|
687
|
-
* @param {string} encryptionKey - 64-char hex key.
|
|
688
|
-
* @returns {string} Plaintext string.
|
|
689
|
-
*/
|
|
690
|
-
function decryptFromStorage(encryptedText, encryptionKey) {
|
|
691
|
-
const [ivHex, authTagHex, encryptedDataHex] = encryptedText.split(':');
|
|
692
|
-
const decipher = createDecipheriv(
|
|
693
|
-
'aes-256-gcm',
|
|
694
|
-
Buffer.from(encryptionKey, 'hex'),
|
|
695
|
-
Buffer.from(ivHex, 'hex')
|
|
696
|
-
);
|
|
697
|
-
decipher.setAuthTag(Buffer.from(authTagHex, 'hex'));
|
|
698
|
-
return decipher.update(encryptedDataHex, 'hex', 'utf8') + decipher.final('utf8');
|
|
699
|
-
}
|
|
700
|
-
|
|
701
|
-
/**
|
|
702
|
-
* Handler: get-user-key
|
|
196
|
+
* Handler: send-notifications
|
|
703
197
|
* ReiStandard SDK v2.0.1
|
|
704
198
|
*
|
|
705
199
|
* @param {Object} ctx - Server context.
|
|
706
|
-
* @returns {{
|
|
200
|
+
* @returns {{ POST: function }}
|
|
707
201
|
*/
|
|
708
202
|
|
|
709
203
|
|
|
710
|
-
function
|
|
711
|
-
async function
|
|
712
|
-
const
|
|
713
|
-
const
|
|
204
|
+
function createSendNotificationsHandler(ctx) {
|
|
205
|
+
async function POST(urlOrHeaders, maybeHeaders) {
|
|
206
|
+
const url = typeof urlOrHeaders === 'string' ? urlOrHeaders : '';
|
|
207
|
+
const headers = maybeHeaders || (typeof urlOrHeaders === 'object' ? urlOrHeaders : {});
|
|
208
|
+
|
|
209
|
+
const tenantResult = await ctx.tenantManager.resolveTenant(headers, {
|
|
210
|
+
allowCronToken: true,
|
|
211
|
+
url
|
|
212
|
+
});
|
|
714
213
|
if (!tenantResult.ok) {
|
|
715
214
|
return tenantResult.error;
|
|
716
215
|
}
|
|
717
216
|
|
|
718
|
-
const
|
|
719
|
-
const
|
|
720
|
-
|
|
721
|
-
if (!userId) {
|
|
722
|
-
return {
|
|
723
|
-
status: 400,
|
|
724
|
-
body: { success: false, error: { code: 'USER_ID_REQUIRED', message: '缺少用户标识符' } }
|
|
725
|
-
};
|
|
726
|
-
}
|
|
217
|
+
const tenantCtx = tenantResult.context;
|
|
218
|
+
const db = tenantCtx.db;
|
|
219
|
+
const masterKey = tenantCtx.masterKey;
|
|
727
220
|
|
|
728
|
-
if (!
|
|
221
|
+
if (!ctx.vapid.email || !ctx.vapid.publicKey || !ctx.vapid.privateKey) {
|
|
729
222
|
return {
|
|
730
|
-
status:
|
|
731
|
-
body: {
|
|
223
|
+
status: 500,
|
|
224
|
+
body: {
|
|
225
|
+
success: false,
|
|
226
|
+
error: {
|
|
227
|
+
code: 'VAPID_CONFIG_ERROR',
|
|
228
|
+
message: 'VAPID 配置缺失,无法发送推送通知',
|
|
229
|
+
details: {
|
|
230
|
+
missingKeys: [
|
|
231
|
+
!ctx.vapid.email && 'VAPID_EMAIL',
|
|
232
|
+
!ctx.vapid.publicKey && 'NEXT_PUBLIC_VAPID_PUBLIC_KEY',
|
|
233
|
+
!ctx.vapid.privateKey && 'VAPID_PRIVATE_KEY'
|
|
234
|
+
].filter(Boolean)
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
}
|
|
732
238
|
};
|
|
733
239
|
}
|
|
734
240
|
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
body: {
|
|
738
|
-
success: true,
|
|
739
|
-
data: {
|
|
740
|
-
userKey: deriveUserEncryptionKey(userId, masterKey),
|
|
741
|
-
version: 1
|
|
742
|
-
}
|
|
743
|
-
}
|
|
744
|
-
};
|
|
745
|
-
}
|
|
746
|
-
|
|
747
|
-
return { GET };
|
|
748
|
-
}
|
|
749
|
-
|
|
750
|
-
/**
|
|
751
|
-
* Database error helpers.
|
|
752
|
-
*/
|
|
753
|
-
|
|
754
|
-
/**
|
|
755
|
-
* Check whether an error is caused by a unique-constraint violation.
|
|
756
|
-
*
|
|
757
|
-
* @param {unknown} error
|
|
758
|
-
* @returns {boolean}
|
|
759
|
-
*/
|
|
760
|
-
function isUniqueViolation(error) {
|
|
761
|
-
if (!error || typeof error !== 'object') return false;
|
|
762
|
-
|
|
763
|
-
const code = error.code;
|
|
764
|
-
if (code === '23505') return true;
|
|
765
|
-
|
|
766
|
-
const message = typeof error.message === 'string' ? error.message.toLowerCase() : '';
|
|
767
|
-
return message.includes('duplicate key') || message.includes('unique constraint');
|
|
768
|
-
}
|
|
769
|
-
|
|
770
|
-
/**
|
|
771
|
-
* Message Processor (SDK version)
|
|
772
|
-
* ReiStandard amsg-server v2.4.0
|
|
773
|
-
*
|
|
774
|
-
* Handles single message content generation and Web Push delivery for
|
|
775
|
-
* scheduled tasks (`fixed` / `prompted` / `auto`) and the
|
|
776
|
-
* in-server instant path (`messageType: 'instant'`).
|
|
777
|
-
*
|
|
778
|
-
* Push wire shape comes from `@rei-standard/amsg-shared`'s
|
|
779
|
-
* discriminated union (`AmsgPush`). The SW (`@rei-standard/amsg-sw`)
|
|
780
|
-
* routes on `messageKind`. Server-driven pushes always carry
|
|
781
|
-
* `source: 'instant'` (for the in-server instant path) or
|
|
782
|
-
* `source: 'scheduled'` (for everything else).
|
|
783
|
-
*
|
|
784
|
-
* v2.4.0: when the LLM response carries non-empty
|
|
785
|
-
* `choices[0].message.reasoning_content`, the processor now emits a
|
|
786
|
-
* standalone `ReasoningPush` **before** the `ContentPush` burst.
|
|
787
|
-
* `messagesSent` in the return value continues to reflect the sentence
|
|
788
|
-
* count only (reasoning is an auxiliary push, not a sentence).
|
|
789
|
-
*/
|
|
790
|
-
|
|
791
|
-
|
|
792
|
-
const DEFAULT_SPLIT_REGEX = /([。!?!?]+)/;
|
|
793
|
-
|
|
794
|
-
// Pacing between consecutive Web Push deliveries (reasoning → content, and
|
|
795
|
-
// between content sentences) so the client renders a natural typing cadence.
|
|
796
|
-
// Kept equal to amsg-instant's SLEEP_BETWEEN_MESSAGES_MS default.
|
|
797
|
-
const SLEEP_BETWEEN_MESSAGES_MS = 1500;
|
|
798
|
-
|
|
799
|
-
/**
|
|
800
|
-
* Split a single chunk by one regex; on no-match return [chunk] so a later
|
|
801
|
-
* regex in a cascade can still take a swing at it.
|
|
802
|
-
*/
|
|
803
|
-
function splitOnceByRegex(chunk, regex) {
|
|
804
|
-
const out = chunk
|
|
805
|
-
.split(regex)
|
|
806
|
-
.reduce((acc, part, i, arr) => {
|
|
807
|
-
if (i % 2 === 0 && part.trim()) {
|
|
808
|
-
const punctuation = arr[i + 1] || '';
|
|
809
|
-
acc.push(part.trim() + punctuation);
|
|
810
|
-
}
|
|
811
|
-
return acc;
|
|
812
|
-
}, [])
|
|
813
|
-
.filter(s => s.length > 0);
|
|
814
|
-
return out.length > 0 ? out : [chunk];
|
|
815
|
-
}
|
|
816
|
-
|
|
817
|
-
/**
|
|
818
|
-
* Sentence splitter for amsg-server's scheduled `splitPattern` feature
|
|
819
|
-
* (see standards §6.1). Server-only: amsg-instant 0.8.0 dropped its
|
|
820
|
-
* request-level `splitPattern`, so there is no instant counterpart to keep
|
|
821
|
-
* in lockstep.
|
|
822
|
-
*
|
|
823
|
-
* @param {string} messageContent
|
|
824
|
-
* @param {string | string[] | null} [splitPattern=null]
|
|
825
|
-
* @returns {string[]}
|
|
826
|
-
*/
|
|
827
|
-
function splitMessageIntoSentences(messageContent, splitPattern = null) {
|
|
828
|
-
const sources =
|
|
829
|
-
splitPattern == null ? null :
|
|
830
|
-
Array.isArray(splitPattern) ? splitPattern :
|
|
831
|
-
[splitPattern];
|
|
832
|
-
|
|
833
|
-
const regexes = (sources && sources.length > 0)
|
|
834
|
-
? sources.map(s => new RegExp(s))
|
|
835
|
-
: [DEFAULT_SPLIT_REGEX];
|
|
836
|
-
|
|
837
|
-
let chunks = [messageContent];
|
|
838
|
-
for (const regex of regexes) {
|
|
839
|
-
chunks = chunks.flatMap(c => splitOnceByRegex(c, regex));
|
|
840
|
-
}
|
|
841
|
-
|
|
842
|
-
return chunks.length > 0 ? chunks : [messageContent];
|
|
843
|
-
}
|
|
844
|
-
|
|
845
|
-
/**
|
|
846
|
-
* @typedef {Object} ProcessorContext
|
|
847
|
-
* @property {Object} webpush - The web-push module instance (already VAPID-configured).
|
|
848
|
-
* @property {Object} vapid - { email, publicKey, privateKey }
|
|
849
|
-
* @property {import('../adapters/interface.js').DbAdapter} db
|
|
850
|
-
*/
|
|
851
|
-
|
|
852
|
-
/**
|
|
853
|
-
* Process a single database task row: decrypt → generate content → push.
|
|
854
|
-
*
|
|
855
|
-
* @param {import('../adapters/interface.js').TaskRow} task
|
|
856
|
-
* @param {ProcessorContext} ctx
|
|
857
|
-
* @param {string} [providedMasterKey]
|
|
858
|
-
* @returns {Promise<{ success: boolean, messagesSent: number, error?: string }>}
|
|
859
|
-
*/
|
|
860
|
-
async function processSingleMessage(task, ctx, providedMasterKey) {
|
|
861
|
-
try {
|
|
862
|
-
const masterKey = providedMasterKey || ctx.masterKey;
|
|
863
|
-
if (!masterKey) {
|
|
864
|
-
return { success: false, messagesSent: 0, error: 'TENANT_MASTER_KEY_MISSING' };
|
|
865
|
-
}
|
|
866
|
-
|
|
867
|
-
const userKey = deriveUserEncryptionKey(task.user_id, masterKey);
|
|
868
|
-
const decryptedPayload = JSON.parse(decryptFromStorage(task.encrypted_payload, userKey));
|
|
869
|
-
|
|
870
|
-
let messageContent;
|
|
871
|
-
/** @type {unknown} */
|
|
872
|
-
let llmResponse = null;
|
|
873
|
-
|
|
874
|
-
if (decryptedPayload.messageType === 'fixed') {
|
|
875
|
-
messageContent = decryptedPayload.userMessage;
|
|
876
|
-
|
|
877
|
-
} else if (decryptedPayload.messageType === 'instant') {
|
|
878
|
-
const hasPrompt = !!decryptedPayload.completePrompt
|
|
879
|
-
|| (Array.isArray(decryptedPayload.messages) && decryptedPayload.messages.length > 0);
|
|
880
|
-
if (hasPrompt && decryptedPayload.apiUrl && decryptedPayload.apiKey && decryptedPayload.primaryModel) {
|
|
881
|
-
const aiResult = await _callAI(decryptedPayload);
|
|
882
|
-
messageContent = aiResult.content;
|
|
883
|
-
llmResponse = aiResult.response;
|
|
884
|
-
} else if (decryptedPayload.userMessage) {
|
|
885
|
-
messageContent = decryptedPayload.userMessage;
|
|
886
|
-
} else {
|
|
887
|
-
throw new Error('Invalid instant message: no content source available');
|
|
888
|
-
}
|
|
889
|
-
|
|
890
|
-
} else if (decryptedPayload.messageType === 'prompted' || decryptedPayload.messageType === 'auto') {
|
|
891
|
-
const aiResult = await _callAI(decryptedPayload);
|
|
892
|
-
messageContent = aiResult.content;
|
|
893
|
-
llmResponse = aiResult.response;
|
|
894
|
-
} else {
|
|
895
|
-
throw new Error('Invalid message configuration: no content source available');
|
|
896
|
-
}
|
|
897
|
-
|
|
898
|
-
// Auto-extract reasoning BEFORE the sentence split: when reasoning
|
|
899
|
-
// came from the `<think>` fallback inside message.content, the same
|
|
900
|
-
// span is still embedded in messageContent and would otherwise leak
|
|
901
|
-
// as raw markup into ContentPush.
|
|
902
|
-
const reasoning = readReasoningContent(llmResponse);
|
|
903
|
-
if (reasoning) {
|
|
904
|
-
messageContent = stripReasoningTags(messageContent);
|
|
905
|
-
}
|
|
906
|
-
|
|
907
|
-
// Sentence splitting (mirrors @rei-standard/amsg-instant
|
|
908
|
-
// splitMessageIntoSentences — keep in lockstep; do not drift). Caller may
|
|
909
|
-
// override the default regex via decryptedPayload.splitPattern (string
|
|
910
|
-
// for a single regex, string[] for a cascade). Validation already enforces
|
|
911
|
-
// length cap + RegExp compilability upstream.
|
|
912
|
-
const messages = splitMessageIntoSentences(messageContent, decryptedPayload.splitPattern ?? null);
|
|
913
|
-
|
|
914
|
-
if (!ctx.vapid.email || !ctx.vapid.publicKey || !ctx.vapid.privateKey) {
|
|
915
|
-
throw new Error('VAPID configuration missing - push notifications cannot be sent');
|
|
916
|
-
}
|
|
917
|
-
|
|
918
|
-
const pushSubscription = decryptedPayload.pushSubscription;
|
|
919
|
-
// sessionId is shared across the optional ReasoningPush and every
|
|
920
|
-
// ContentPush from this LLM round. Pin it to the task id when
|
|
921
|
-
// available (scheduled tasks) so retries reuse the same id;
|
|
922
|
-
// otherwise mint a UUID.
|
|
923
|
-
const sessionId = task.id != null
|
|
924
|
-
? `sess_task_${task.id}`
|
|
925
|
-
: `sess_${randomUUID()}`;
|
|
926
|
-
const source = decryptedPayload.messageType === 'instant' ? 'instant' : 'scheduled';
|
|
927
|
-
const messageSubtype = decryptedPayload.messageSubtype || 'chat';
|
|
928
|
-
const avatarUrl = decryptedPayload.avatarUrl || null;
|
|
929
|
-
const metadata = decryptedPayload.metadata || {};
|
|
930
|
-
|
|
931
|
-
// `messageId` format — deterministic when we have a task.id so a
|
|
932
|
-
// retry produces the same id for the same (task, sentence) pair
|
|
933
|
-
// (downstream dedupers can key on it). Falls back to a UUID for
|
|
934
|
-
// the in-server instant path that has no row id.
|
|
935
|
-
const messageIdBase = task.id != null
|
|
936
|
-
? `msg_task_${task.id}`
|
|
937
|
-
: `msg_${randomUUID()}_instant`;
|
|
938
|
-
|
|
939
|
-
// ReasoningPush — auto-emitted before the content burst when the
|
|
940
|
-
// LLM response carried non-empty reasoning_content. `fixed` and
|
|
941
|
-
// explicit-userMessage paths produce no LLM response, so this
|
|
942
|
-
// block is naturally skipped for them (llmResponse stays null).
|
|
943
|
-
if (reasoning) {
|
|
944
|
-
const reasoningPush = buildReasoningPush({
|
|
945
|
-
messageType: decryptedPayload.messageType,
|
|
946
|
-
source,
|
|
947
|
-
messageId: `${messageIdBase}_reasoning`,
|
|
948
|
-
sessionId,
|
|
949
|
-
reasoningContent: reasoning,
|
|
950
|
-
timestamp: new Date().toISOString(),
|
|
951
|
-
title: `来自 ${decryptedPayload.contactName}`,
|
|
952
|
-
contactName: decryptedPayload.contactName,
|
|
953
|
-
avatarUrl,
|
|
954
|
-
messageSubtype,
|
|
955
|
-
metadata,
|
|
956
|
-
});
|
|
957
|
-
await ctx.webpush.sendNotification(pushSubscription, JSON.stringify(reasoningPush));
|
|
958
|
-
await new Promise(resolve => setTimeout(resolve, SLEEP_BETWEEN_MESSAGES_MS));
|
|
959
|
-
}
|
|
960
|
-
|
|
961
|
-
for (let i = 0; i < messages.length; i++) {
|
|
962
|
-
const contentPush = buildContentPush({
|
|
963
|
-
messageType: decryptedPayload.messageType,
|
|
964
|
-
source,
|
|
965
|
-
messageId: `${messageIdBase}_${i}`,
|
|
966
|
-
sessionId,
|
|
967
|
-
message: messages[i],
|
|
968
|
-
timestamp: new Date().toISOString(),
|
|
969
|
-
title: `来自 ${decryptedPayload.contactName}`,
|
|
970
|
-
contactName: decryptedPayload.contactName,
|
|
971
|
-
avatarUrl,
|
|
972
|
-
messageSubtype,
|
|
973
|
-
messageIndex: i + 1,
|
|
974
|
-
totalMessages: messages.length,
|
|
975
|
-
taskId: task.id || null,
|
|
976
|
-
metadata,
|
|
977
|
-
});
|
|
978
|
-
|
|
979
|
-
await ctx.webpush.sendNotification(pushSubscription, JSON.stringify(contentPush));
|
|
980
|
-
|
|
981
|
-
if (i < messages.length - 1) {
|
|
982
|
-
await new Promise(resolve => setTimeout(resolve, SLEEP_BETWEEN_MESSAGES_MS));
|
|
983
|
-
}
|
|
984
|
-
}
|
|
985
|
-
|
|
986
|
-
return { success: true, messagesSent: messages.length };
|
|
987
|
-
|
|
988
|
-
} catch (error) {
|
|
989
|
-
return { success: false, messagesSent: 0, error: error.message };
|
|
990
|
-
}
|
|
991
|
-
}
|
|
992
|
-
|
|
993
|
-
/**
|
|
994
|
-
* Process a single message identified by UUID (used for instant type).
|
|
995
|
-
*
|
|
996
|
-
* @param {string} uuid
|
|
997
|
-
* @param {ProcessorContext} ctx
|
|
998
|
-
* @param {number} [maxRetries=2]
|
|
999
|
-
* @param {string} [userId]
|
|
1000
|
-
* @param {string} [providedMasterKey]
|
|
1001
|
-
* @returns {Promise<{ success: boolean, messagesSent?: number, retriesUsed?: number, error?: Object }>}
|
|
1002
|
-
*/
|
|
1003
|
-
async function processMessagesByUuid(uuid, ctx, maxRetries = 2, userId, providedMasterKey) {
|
|
1004
|
-
let retryCount = 0;
|
|
1005
|
-
const masterKey = providedMasterKey || ctx.masterKey;
|
|
1006
|
-
|
|
1007
|
-
if (!masterKey) {
|
|
1008
|
-
return {
|
|
1009
|
-
success: false,
|
|
1010
|
-
error: { code: 'TENANT_MASTER_KEY_MISSING', message: '租户主密钥不存在或配置异常' }
|
|
1011
|
-
};
|
|
1012
|
-
}
|
|
1013
|
-
|
|
1014
|
-
while (retryCount <= maxRetries) {
|
|
1015
|
-
let task;
|
|
1016
|
-
try {
|
|
1017
|
-
task = userId
|
|
1018
|
-
? await ctx.db.getTaskByUuid(uuid, userId)
|
|
1019
|
-
: await ctx.db.getTaskByUuidOnly(uuid);
|
|
1020
|
-
} catch (error) {
|
|
1021
|
-
if (retryCount < maxRetries) {
|
|
1022
|
-
retryCount++;
|
|
1023
|
-
await new Promise(resolve => setTimeout(resolve, 1000 * retryCount));
|
|
1024
|
-
continue;
|
|
1025
|
-
}
|
|
1026
|
-
|
|
1027
|
-
return {
|
|
1028
|
-
success: false,
|
|
1029
|
-
error: { code: 'INTERNAL_ERROR', message: error.message, retriesAttempted: retryCount }
|
|
1030
|
-
};
|
|
1031
|
-
}
|
|
1032
|
-
|
|
1033
|
-
if (!task) {
|
|
1034
|
-
return { success: false, error: { code: 'TASK_NOT_FOUND', message: '任务不存在或已处理' } };
|
|
1035
|
-
}
|
|
1036
|
-
|
|
1037
|
-
const result = await processSingleMessage(task, ctx, masterKey);
|
|
1038
|
-
|
|
1039
|
-
if (!result.success) {
|
|
1040
|
-
if (retryCount < maxRetries) {
|
|
1041
|
-
retryCount++;
|
|
1042
|
-
await new Promise(resolve => setTimeout(resolve, 1000 * retryCount));
|
|
1043
|
-
continue;
|
|
1044
|
-
}
|
|
1045
|
-
|
|
1046
|
-
try {
|
|
1047
|
-
await ctx.db.updateTaskById(task.id, { status: 'failed', retry_count: retryCount });
|
|
1048
|
-
} catch (_updateError) {
|
|
1049
|
-
// best-effort status update; keep original processing error as primary signal
|
|
1050
|
-
}
|
|
1051
|
-
|
|
1052
|
-
return {
|
|
1053
|
-
success: false,
|
|
1054
|
-
error: { code: 'PROCESSING_ERROR', message: result.error, retriesAttempted: retryCount }
|
|
1055
|
-
};
|
|
1056
|
-
}
|
|
1057
|
-
|
|
1058
|
-
try {
|
|
1059
|
-
await ctx.db.deleteTaskById(task.id);
|
|
1060
|
-
} catch (error) {
|
|
1061
|
-
try {
|
|
1062
|
-
await ctx.db.updateTaskById(task.id, { status: 'sent', retry_count: 0 });
|
|
1063
|
-
} catch (_markSentError) {
|
|
1064
|
-
// best effort: avoid re-sending if storage mutation partially fails
|
|
1065
|
-
}
|
|
1066
|
-
|
|
1067
|
-
return {
|
|
1068
|
-
success: false,
|
|
1069
|
-
error: {
|
|
1070
|
-
code: 'POST_SEND_CLEANUP_FAILED',
|
|
1071
|
-
message: '消息已发送,但任务清理失败',
|
|
1072
|
-
details: { error: error.message }
|
|
1073
|
-
}
|
|
1074
|
-
};
|
|
1075
|
-
}
|
|
1076
|
-
|
|
1077
|
-
return { success: true, messagesSent: result.messagesSent, retriesUsed: retryCount };
|
|
1078
|
-
}
|
|
1079
|
-
}
|
|
1080
|
-
|
|
1081
|
-
/**
|
|
1082
|
-
* Call an OpenAI-compatible API.
|
|
1083
|
-
*
|
|
1084
|
-
* Returns the full response object alongside the extracted (trimmed)
|
|
1085
|
-
* `content` string. Callers that only need the text can ignore
|
|
1086
|
-
* `response`; callers that want `reasoning_content` / `tool_calls`
|
|
1087
|
-
* read from `response.choices[0].message`.
|
|
1088
|
-
*
|
|
1089
|
-
* @private
|
|
1090
|
-
* @param {Object} payload
|
|
1091
|
-
* @returns {Promise<{ response: unknown, content: string }>}
|
|
1092
|
-
*/
|
|
1093
|
-
async function _callAI(payload) {
|
|
1094
|
-
const normalizedApiUrl = normalizeAiApiUrl(payload.apiUrl);
|
|
1095
|
-
const requestBody = buildAiRequestBody(payload);
|
|
1096
|
-
|
|
1097
|
-
const aiResponse = await fetch(normalizedApiUrl, {
|
|
1098
|
-
method: 'POST',
|
|
1099
|
-
headers: {
|
|
1100
|
-
'Content-Type': 'application/json',
|
|
1101
|
-
'Authorization': `Bearer ${payload.apiKey}`
|
|
1102
|
-
},
|
|
1103
|
-
body: JSON.stringify(requestBody),
|
|
1104
|
-
signal: AbortSignal.timeout(300000)
|
|
1105
|
-
});
|
|
1106
|
-
|
|
1107
|
-
if (!aiResponse.ok) {
|
|
1108
|
-
if (aiResponse.status === 405) {
|
|
1109
|
-
throw new Error(
|
|
1110
|
-
`AI API error: 405 Method Not Allowed. ` +
|
|
1111
|
-
`apiUrl must point to a full chat endpoint (for example: /chat/completions). ` +
|
|
1112
|
-
`Received: ${normalizedApiUrl}`
|
|
1113
|
-
);
|
|
1114
|
-
}
|
|
1115
|
-
|
|
1116
|
-
throw new Error(
|
|
1117
|
-
`AI API error: ${aiResponse.status} ${aiResponse.statusText || 'Unknown Error'}. ` +
|
|
1118
|
-
`Request URL: ${normalizedApiUrl}`
|
|
1119
|
-
);
|
|
1120
|
-
}
|
|
1121
|
-
|
|
1122
|
-
const aiData = await aiResponse.json();
|
|
1123
|
-
const content = aiData?.choices?.[0]?.message?.content;
|
|
1124
|
-
if (typeof content !== 'string' || !content.trim()) {
|
|
1125
|
-
throw new Error('AI API error: response missing choices[0].message.content');
|
|
1126
|
-
}
|
|
1127
|
-
|
|
1128
|
-
return { response: aiData, content: content.trim() };
|
|
1129
|
-
}
|
|
1130
|
-
|
|
1131
|
-
/**
|
|
1132
|
-
* Build OpenAI-compatible request body.
|
|
1133
|
-
*
|
|
1134
|
-
* `max_tokens` is optional:
|
|
1135
|
-
* - include it only when payload.maxTokens is provided
|
|
1136
|
-
* - omit it when payload.maxTokens is undefined / null
|
|
1137
|
-
*
|
|
1138
|
-
* @param {Object} payload
|
|
1139
|
-
* @returns {Object}
|
|
1140
|
-
*/
|
|
1141
|
-
function buildAiRequestBody(payload) {
|
|
1142
|
-
// messages mode (added in v2.2.0): forward the caller's OpenAI-style array
|
|
1143
|
-
// verbatim — same contract as @rei-standard/amsg-instant 0.5.0+. No auto
|
|
1144
|
-
// role injection, no concatenation back to a single user message. Lets
|
|
1145
|
-
// the upstream app preserve system / multi-turn context byte-for-byte
|
|
1146
|
-
// across the schedule-message path.
|
|
1147
|
-
const llmMessages = Array.isArray(payload.messages) && payload.messages.length > 0
|
|
1148
|
-
? payload.messages
|
|
1149
|
-
: [{ role: 'user', content: payload.completePrompt }];
|
|
1150
|
-
|
|
1151
|
-
const requestBody = {
|
|
1152
|
-
model: payload.primaryModel,
|
|
1153
|
-
messages: llmMessages,
|
|
1154
|
-
};
|
|
1155
|
-
|
|
1156
|
-
// Match the instant package's behavior: only inject default temperature
|
|
1157
|
-
// for the legacy completePrompt path; messages mode forwards whatever the
|
|
1158
|
-
// upstream app set (or nothing) so behavior matches their main chat path.
|
|
1159
|
-
if (payload.temperature !== undefined && payload.temperature !== null) {
|
|
1160
|
-
requestBody.temperature = payload.temperature;
|
|
1161
|
-
} else if (!Array.isArray(payload.messages)) {
|
|
1162
|
-
requestBody.temperature = 0.8;
|
|
1163
|
-
}
|
|
1164
|
-
|
|
1165
|
-
if (payload.maxTokens === undefined || payload.maxTokens === null) {
|
|
1166
|
-
return requestBody;
|
|
1167
|
-
}
|
|
1168
|
-
|
|
1169
|
-
if (!Number.isInteger(payload.maxTokens) || payload.maxTokens <= 0) {
|
|
1170
|
-
throw new Error('Invalid maxTokens: maxTokens must be a positive integer when provided.');
|
|
1171
|
-
}
|
|
1172
|
-
|
|
1173
|
-
requestBody.max_tokens = payload.maxTokens;
|
|
1174
|
-
return requestBody;
|
|
1175
|
-
}
|
|
1176
|
-
|
|
1177
|
-
/**
|
|
1178
|
-
* Normalize AI API URL for OpenAI-compatible chat endpoints.
|
|
1179
|
-
*
|
|
1180
|
-
* **Keep in sync** with `@rei-standard/amsg-instant`'s
|
|
1181
|
-
* `src/message-processor.js` `normalizeAiApiUrl` — same rules, same
|
|
1182
|
-
* tests. The two packages share this logic but each carry their own copy
|
|
1183
|
-
* to avoid an architectural dependency (server should not depend on the
|
|
1184
|
-
* stateless worker package).
|
|
1185
|
-
*
|
|
1186
|
-
* @param {string} apiUrl
|
|
1187
|
-
* @returns {string}
|
|
1188
|
-
*/
|
|
1189
|
-
function normalizeAiApiUrl(apiUrl) {
|
|
1190
|
-
if (typeof apiUrl !== 'string' || !apiUrl.trim()) {
|
|
1191
|
-
throw new Error(
|
|
1192
|
-
'Invalid apiUrl: apiUrl is required. ' +
|
|
1193
|
-
'Please provide a chat endpoint URL ' +
|
|
1194
|
-
'(for example: https://api.openai.com or https://api.openai.com/v1/chat/completions).'
|
|
1195
|
-
);
|
|
1196
|
-
}
|
|
1197
|
-
|
|
1198
|
-
const trimmedApiUrl = apiUrl.trim();
|
|
1199
|
-
let parsedUrl;
|
|
1200
|
-
|
|
1201
|
-
try {
|
|
1202
|
-
parsedUrl = new URL(trimmedApiUrl);
|
|
1203
|
-
} catch {
|
|
1204
|
-
throw new Error(
|
|
1205
|
-
`Invalid apiUrl: "${apiUrl}". Please provide a valid absolute URL.`
|
|
1206
|
-
);
|
|
1207
|
-
}
|
|
1208
|
-
|
|
1209
|
-
let path = parsedUrl.pathname.replace(/\/+$/, '') || '/';
|
|
1210
|
-
|
|
1211
|
-
if (/\/chat\/completions$/.test(path)) ; else if (path === '/') {
|
|
1212
|
-
// Bare host → assume OpenAI shape.
|
|
1213
|
-
path = '/v1/chat/completions';
|
|
1214
|
-
} else if (/\/v\d+$/.test(path)) {
|
|
1215
|
-
// Path ends in `/v1`, `/v2`, … — caller already versioned the URL.
|
|
1216
|
-
// Append only `/chat/completions`; never re-add `/v1`.
|
|
1217
|
-
path = `${path}/chat/completions`;
|
|
1218
|
-
}
|
|
1219
|
-
// Any other custom path is left untouched on purpose.
|
|
1220
|
-
|
|
1221
|
-
parsedUrl.pathname = path;
|
|
1222
|
-
return parsedUrl.toString();
|
|
1223
|
-
}
|
|
1224
|
-
|
|
1225
|
-
/**
|
|
1226
|
-
* Handler: schedule-message
|
|
1227
|
-
* ReiStandard SDK v2.0.1
|
|
1228
|
-
*
|
|
1229
|
-
* @param {Object} ctx - Server context.
|
|
1230
|
-
* @returns {{ POST: function }}
|
|
1231
|
-
*/
|
|
1232
|
-
|
|
1233
|
-
|
|
1234
|
-
function createScheduleMessageHandler(ctx) {
|
|
1235
|
-
async function POST(headers, body) {
|
|
1236
|
-
const tenantResult = await ctx.tenantManager.resolveTenant(headers);
|
|
1237
|
-
if (!tenantResult.ok) {
|
|
1238
|
-
return tenantResult.error;
|
|
1239
|
-
}
|
|
1240
|
-
|
|
1241
|
-
const tenantCtx = tenantResult.context;
|
|
1242
|
-
const db = tenantCtx.db;
|
|
1243
|
-
const masterKey = tenantCtx.masterKey;
|
|
1244
|
-
const isEncrypted = getHeader(headers, 'x-payload-encrypted') === 'true';
|
|
1245
|
-
const encryptionVersion = getHeader(headers, 'x-encryption-version');
|
|
1246
|
-
const userId = getHeader(headers, 'x-user-id');
|
|
1247
|
-
|
|
1248
|
-
if (!isEncrypted) {
|
|
1249
|
-
return { status: 400, body: { success: false, error: { code: 'ENCRYPTION_REQUIRED', message: '请求体必须加密' } } };
|
|
1250
|
-
}
|
|
1251
|
-
if (!userId) {
|
|
1252
|
-
return { status: 400, body: { success: false, error: { code: 'USER_ID_REQUIRED', message: '缺少用户标识符' } } };
|
|
1253
|
-
}
|
|
1254
|
-
if (!isValidUUIDv4(userId)) {
|
|
1255
|
-
return { status: 400, body: { success: false, error: { code: 'INVALID_USER_ID_FORMAT', message: 'X-User-Id 必须是 UUID v4 格式' } } };
|
|
1256
|
-
}
|
|
1257
|
-
if (encryptionVersion !== '1') {
|
|
1258
|
-
return { status: 400, body: { success: false, error: { code: 'UNSUPPORTED_ENCRYPTION_VERSION', message: '加密版本不支持' } } };
|
|
1259
|
-
}
|
|
1260
|
-
|
|
1261
|
-
// Decrypt request body
|
|
1262
|
-
const parsedBody = parseEncryptedBody(body);
|
|
1263
|
-
if (!parsedBody.ok) {
|
|
1264
|
-
return { status: 400, body: { success: false, error: parsedBody.error } };
|
|
1265
|
-
}
|
|
1266
|
-
|
|
1267
|
-
const encryptedBody = parsedBody.data;
|
|
1268
|
-
|
|
1269
|
-
let payload;
|
|
1270
|
-
try {
|
|
1271
|
-
const userKey = deriveUserEncryptionKey(userId, masterKey);
|
|
1272
|
-
payload = decryptPayload(encryptedBody, userKey);
|
|
1273
|
-
} catch (error) {
|
|
1274
|
-
if (error instanceof SyntaxError) {
|
|
1275
|
-
return { status: 400, body: { success: false, error: { code: 'INVALID_PAYLOAD_FORMAT', message: '解密后的数据不是有效 JSON' } } };
|
|
1276
|
-
}
|
|
1277
|
-
|
|
1278
|
-
const message = typeof error.message === 'string' ? error.message : '';
|
|
1279
|
-
if (message.includes('auth') || message.includes('Unsupported state')) {
|
|
1280
|
-
return { status: 400, body: { success: false, error: { code: 'DECRYPTION_FAILED', message: '请求体解密失败' } } };
|
|
1281
|
-
}
|
|
1282
|
-
|
|
1283
|
-
return { status: 400, body: { success: false, error: { code: 'DECRYPTION_FAILED', message: '请求体解密失败' } } };
|
|
1284
|
-
}
|
|
1285
|
-
|
|
1286
|
-
if (!isPlainObject(payload)) {
|
|
1287
|
-
return { status: 400, body: { success: false, error: { code: 'INVALID_PAYLOAD_FORMAT', message: '解密后的数据必须是 JSON 对象' } } };
|
|
1288
|
-
}
|
|
1289
|
-
|
|
1290
|
-
// Validate
|
|
1291
|
-
const validationResult = validateScheduleMessagePayload(payload);
|
|
1292
|
-
if (!validationResult.valid) {
|
|
1293
|
-
return { status: 400, body: { success: false, error: { code: validationResult.errorCode, message: validationResult.errorMessage, details: validationResult.details } } };
|
|
1294
|
-
}
|
|
1295
|
-
|
|
1296
|
-
const taskUuid = payload.uuid || randomUUID();
|
|
1297
|
-
const userKey = deriveUserEncryptionKey(userId, masterKey);
|
|
1298
|
-
|
|
1299
|
-
const fullTaskData = {
|
|
1300
|
-
contactName: payload.contactName,
|
|
1301
|
-
avatarUrl: payload.avatarUrl || null,
|
|
1302
|
-
messageType: payload.messageType,
|
|
1303
|
-
messageSubtype: payload.messageSubtype || 'chat',
|
|
1304
|
-
userMessage: payload.userMessage || null,
|
|
1305
|
-
firstSendTime: payload.firstSendTime,
|
|
1306
|
-
recurrenceType: payload.recurrenceType || 'none',
|
|
1307
|
-
apiUrl: payload.apiUrl || null,
|
|
1308
|
-
apiKey: payload.apiKey || null,
|
|
1309
|
-
primaryModel: payload.primaryModel || null,
|
|
1310
|
-
// Prompt is one-of: legacy completePrompt (string) OR messages (OpenAI-
|
|
1311
|
-
// style array). Validation has already enforced exactly-one-of, so
|
|
1312
|
-
// exactly one of these will be non-null when an AI config is provided.
|
|
1313
|
-
completePrompt: payload.completePrompt || null,
|
|
1314
|
-
messages: Array.isArray(payload.messages) ? payload.messages : null,
|
|
1315
|
-
maxTokens: payload.maxTokens ?? null,
|
|
1316
|
-
temperature: payload.temperature ?? null,
|
|
1317
|
-
// 0.6.0+: optional caller-provided regex (string or string[]) used by
|
|
1318
|
-
// the message processor to chunk LLM output into individual pushes.
|
|
1319
|
-
// null → processor falls back to the default /([。!?!?]+)/ regex.
|
|
1320
|
-
splitPattern: payload.splitPattern ?? null,
|
|
1321
|
-
pushSubscription: payload.pushSubscription,
|
|
1322
|
-
metadata: payload.metadata || {}
|
|
1323
|
-
};
|
|
1324
|
-
|
|
1325
|
-
const encryptedPayload = encryptForStorage(JSON.stringify(fullTaskData), userKey);
|
|
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: check VAPID before creating the task to avoid orphaned rows
|
|
1344
|
-
if (payload.messageType === 'instant') {
|
|
1345
|
-
if (!ctx.vapid.email || !ctx.vapid.publicKey || !ctx.vapid.privateKey) {
|
|
1346
|
-
return {
|
|
1347
|
-
status: 500,
|
|
1348
|
-
body: {
|
|
1349
|
-
success: false,
|
|
1350
|
-
error: {
|
|
1351
|
-
code: 'VAPID_CONFIG_ERROR',
|
|
1352
|
-
message: 'VAPID 配置缺失,无法发送即时消息',
|
|
1353
|
-
details: {
|
|
1354
|
-
missingKeys: [
|
|
1355
|
-
!ctx.vapid.email && 'VAPID_EMAIL',
|
|
1356
|
-
!ctx.vapid.publicKey && 'NEXT_PUBLIC_VAPID_PUBLIC_KEY',
|
|
1357
|
-
!ctx.vapid.privateKey && 'VAPID_PRIVATE_KEY'
|
|
1358
|
-
].filter(Boolean)
|
|
1359
|
-
}
|
|
1360
|
-
}
|
|
1361
|
-
}
|
|
1362
|
-
};
|
|
1363
|
-
}
|
|
1364
|
-
}
|
|
1365
|
-
|
|
1366
|
-
// Insert into database
|
|
1367
|
-
let dbResult;
|
|
1368
|
-
try {
|
|
1369
|
-
dbResult = await db.createTask({
|
|
1370
|
-
user_id: userId,
|
|
1371
|
-
uuid: taskUuid,
|
|
1372
|
-
encrypted_payload: encryptedPayload,
|
|
1373
|
-
next_send_at: payload.firstSendTime,
|
|
1374
|
-
message_type: payload.messageType
|
|
1375
|
-
});
|
|
1376
|
-
} catch (error) {
|
|
1377
|
-
if (isUniqueViolation(error)) {
|
|
1378
|
-
return {
|
|
1379
|
-
status: 409,
|
|
1380
|
-
body: {
|
|
1381
|
-
success: false,
|
|
1382
|
-
error: {
|
|
1383
|
-
code: 'TASK_UUID_CONFLICT',
|
|
1384
|
-
message: '任务 UUID 已存在,请使用新的 uuid 重新提交'
|
|
1385
|
-
}
|
|
1386
|
-
}
|
|
1387
|
-
};
|
|
1388
|
-
}
|
|
1389
|
-
throw error;
|
|
1390
|
-
}
|
|
1391
|
-
|
|
1392
|
-
if (!dbResult) {
|
|
1393
|
-
return { status: 500, body: { success: false, error: { code: 'TASK_CREATE_FAILED', message: '创建任务失败' } } };
|
|
1394
|
-
}
|
|
1395
|
-
|
|
1396
|
-
/**
|
|
1397
|
-
* In-server instant path. Delivers an instant message through this
|
|
1398
|
-
* server's own task queue (create task → process by UUID → delete task).
|
|
1399
|
-
* The task is written to the database before processing, so delivery is
|
|
1400
|
-
* not tied to the request connection: even if the client disconnects, the
|
|
1401
|
-
* row stays and the generation keeps running (and can be retried) for as
|
|
1402
|
-
* long as it needs. Use this when you have a database and want long or
|
|
1403
|
-
* guaranteed-complete generations with no dropped messages.
|
|
1404
|
-
*
|
|
1405
|
-
* The stateless alternative is `@rei-standard/amsg-instant`: it streams
|
|
1406
|
-
* over SSE with a Web Push backup and needs no database, which makes it a
|
|
1407
|
-
* good fit for edge runtimes (e.g. Cloudflare Workers). Its work rides the
|
|
1408
|
-
* response connection, so after the client disconnects it only has the
|
|
1409
|
-
* platform's brief grace window to finish (≈20-30s observed on Deno
|
|
1410
|
-
* Deploy) — ideal for short instant messages that complete quickly.
|
|
1411
|
-
*/
|
|
1412
|
-
// Instant type: send immediately
|
|
1413
|
-
if (payload.messageType === 'instant') {
|
|
1414
|
-
try {
|
|
1415
|
-
const sendResult = await processMessagesByUuid(taskUuid, {
|
|
1416
|
-
...ctx,
|
|
1417
|
-
db,
|
|
1418
|
-
masterKey
|
|
1419
|
-
}, 2, userId, masterKey);
|
|
1420
|
-
|
|
1421
|
-
if (!sendResult.success) {
|
|
1422
|
-
return { status: 500, body: { success: false, error: { code: 'MESSAGE_SEND_FAILED', message: '消息发送失败', details: sendResult.error } } };
|
|
1423
|
-
}
|
|
1424
|
-
|
|
1425
|
-
return {
|
|
1426
|
-
status: 200,
|
|
1427
|
-
body: {
|
|
1428
|
-
success: true,
|
|
1429
|
-
data: {
|
|
1430
|
-
uuid: taskUuid,
|
|
1431
|
-
contactName: payload.contactName,
|
|
1432
|
-
messagesSent: sendResult.messagesSent,
|
|
1433
|
-
sentAt: new Date().toISOString(),
|
|
1434
|
-
status: 'sent',
|
|
1435
|
-
retriesUsed: sendResult.retriesUsed || 0
|
|
1436
|
-
}
|
|
1437
|
-
}
|
|
1438
|
-
};
|
|
1439
|
-
} catch (error) {
|
|
1440
|
-
return { status: 500, body: { success: false, error: { code: 'MESSAGE_SEND_FAILED', message: '消息发送失败', details: { error: error.message } } } };
|
|
1441
|
-
}
|
|
1442
|
-
}
|
|
1443
|
-
|
|
1444
|
-
// Non-instant: return scheduled response
|
|
1445
|
-
return {
|
|
1446
|
-
status: 201,
|
|
1447
|
-
body: {
|
|
1448
|
-
success: true,
|
|
1449
|
-
data: {
|
|
1450
|
-
id: dbResult.id,
|
|
1451
|
-
uuid: dbResult.uuid,
|
|
1452
|
-
contactName: payload.contactName,
|
|
1453
|
-
nextSendAt: dbResult.next_send_at,
|
|
1454
|
-
status: dbResult.status,
|
|
1455
|
-
createdAt: dbResult.created_at
|
|
1456
|
-
}
|
|
1457
|
-
}
|
|
1458
|
-
};
|
|
241
|
+
const data = await runScheduledTick({ ...ctx, db, masterKey });
|
|
242
|
+
return { status: 200, body: { success: true, data } };
|
|
1459
243
|
}
|
|
1460
244
|
|
|
1461
245
|
return { POST };
|
|
1462
246
|
}
|
|
1463
247
|
|
|
1464
|
-
/**
|
|
1465
|
-
* Handler: send-notifications
|
|
1466
|
-
* ReiStandard SDK v2.0.1
|
|
1467
|
-
*
|
|
1468
|
-
* @param {Object} ctx - Server context.
|
|
1469
|
-
* @returns {{ POST: function }}
|
|
1470
|
-
*/
|
|
1471
|
-
|
|
1472
|
-
|
|
1473
|
-
function createSendNotificationsHandler(ctx) {
|
|
1474
|
-
async function POST(urlOrHeaders, maybeHeaders) {
|
|
1475
|
-
const url = typeof urlOrHeaders === 'string' ? urlOrHeaders : '';
|
|
1476
|
-
const headers = maybeHeaders || (typeof urlOrHeaders === 'object' ? urlOrHeaders : {});
|
|
1477
|
-
|
|
1478
|
-
const tenantResult = await ctx.tenantManager.resolveTenant(headers, {
|
|
1479
|
-
allowCronToken: true,
|
|
1480
|
-
url
|
|
1481
|
-
});
|
|
1482
|
-
if (!tenantResult.ok) {
|
|
1483
|
-
return tenantResult.error;
|
|
1484
|
-
}
|
|
1485
|
-
|
|
1486
|
-
const tenantCtx = tenantResult.context;
|
|
1487
|
-
const db = tenantCtx.db;
|
|
1488
|
-
const masterKey = tenantCtx.masterKey;
|
|
1489
|
-
|
|
1490
|
-
if (!ctx.vapid.email || !ctx.vapid.publicKey || !ctx.vapid.privateKey) {
|
|
1491
|
-
return {
|
|
1492
|
-
status: 500,
|
|
1493
|
-
body: {
|
|
1494
|
-
success: false,
|
|
1495
|
-
error: {
|
|
1496
|
-
code: 'VAPID_CONFIG_ERROR',
|
|
1497
|
-
message: 'VAPID 配置缺失,无法发送推送通知',
|
|
1498
|
-
details: {
|
|
1499
|
-
missingKeys: [
|
|
1500
|
-
!ctx.vapid.email && 'VAPID_EMAIL',
|
|
1501
|
-
!ctx.vapid.publicKey && 'NEXT_PUBLIC_VAPID_PUBLIC_KEY',
|
|
1502
|
-
!ctx.vapid.privateKey && 'VAPID_PRIVATE_KEY'
|
|
1503
|
-
].filter(Boolean)
|
|
1504
|
-
}
|
|
1505
|
-
}
|
|
1506
|
-
}
|
|
1507
|
-
};
|
|
1508
|
-
}
|
|
1509
|
-
|
|
1510
|
-
const startTime = Date.now();
|
|
1511
|
-
const tasks = await db.getPendingTasks(50);
|
|
1512
|
-
|
|
1513
|
-
const MAX_CONCURRENT = 8;
|
|
1514
|
-
const results = {
|
|
1515
|
-
totalTasks: tasks.length,
|
|
1516
|
-
successCount: 0,
|
|
1517
|
-
failedCount: 0,
|
|
1518
|
-
deletedOnceOffTasks: 0,
|
|
1519
|
-
updatedRecurringTasks: 0,
|
|
1520
|
-
failedTasks: []
|
|
1521
|
-
};
|
|
1522
|
-
|
|
1523
|
-
async function handleDeliveryFailure(task, reason) {
|
|
1524
|
-
results.failedCount++;
|
|
1525
|
-
|
|
1526
|
-
try {
|
|
1527
|
-
if (task.retry_count >= 3) {
|
|
1528
|
-
await db.updateTaskById(task.id, { status: 'failed' });
|
|
1529
|
-
results.failedTasks.push({ taskId: task.id, reason, retryCount: task.retry_count, status: 'permanently_failed' });
|
|
1530
|
-
} else {
|
|
1531
|
-
const nextRetryTime = new Date(Date.now() + (task.retry_count + 1) * 2 * 60 * 1000);
|
|
1532
|
-
await db.updateTaskById(task.id, { next_send_at: nextRetryTime.toISOString(), retry_count: task.retry_count + 1 });
|
|
1533
|
-
results.failedTasks.push({ taskId: task.id, reason, retryCount: task.retry_count + 1, nextRetryAt: nextRetryTime.toISOString() });
|
|
1534
|
-
}
|
|
1535
|
-
} catch (updateError) {
|
|
1536
|
-
results.failedTasks.push({
|
|
1537
|
-
taskId: task.id,
|
|
1538
|
-
reason,
|
|
1539
|
-
status: 'retry_update_failed',
|
|
1540
|
-
updateError: updateError.message
|
|
1541
|
-
});
|
|
1542
|
-
}
|
|
1543
|
-
}
|
|
1544
|
-
|
|
1545
|
-
async function handlePostSendPersistenceFailure(task, reason) {
|
|
1546
|
-
results.failedCount++;
|
|
1547
|
-
|
|
1548
|
-
let markedSent = false;
|
|
1549
|
-
try {
|
|
1550
|
-
await db.updateTaskById(task.id, { status: 'sent', retry_count: 0 });
|
|
1551
|
-
markedSent = true;
|
|
1552
|
-
} catch (_markSentError) {
|
|
1553
|
-
markedSent = false;
|
|
1554
|
-
}
|
|
1555
|
-
|
|
1556
|
-
results.failedTasks.push({
|
|
1557
|
-
taskId: task.id,
|
|
1558
|
-
reason,
|
|
1559
|
-
status: markedSent ? 'post_send_cleanup_failed_marked_sent' : 'post_send_cleanup_failed',
|
|
1560
|
-
messageDelivered: true
|
|
1561
|
-
});
|
|
1562
|
-
}
|
|
1563
|
-
|
|
1564
|
-
async function processTask(task) {
|
|
1565
|
-
let sendResult;
|
|
1566
|
-
try {
|
|
1567
|
-
sendResult = await processSingleMessage(task, {
|
|
1568
|
-
...ctx,
|
|
1569
|
-
db,
|
|
1570
|
-
masterKey
|
|
1571
|
-
}, masterKey);
|
|
1572
|
-
} catch (error) {
|
|
1573
|
-
await handleDeliveryFailure(task, error.message || '消息发送失败');
|
|
1574
|
-
return;
|
|
1575
|
-
}
|
|
1576
|
-
|
|
1577
|
-
if (!sendResult.success) {
|
|
1578
|
-
await handleDeliveryFailure(task, sendResult.error || '消息发送失败');
|
|
1579
|
-
return;
|
|
1580
|
-
}
|
|
1581
|
-
|
|
1582
|
-
try {
|
|
1583
|
-
const userKey = deriveUserEncryptionKey(task.user_id, masterKey);
|
|
1584
|
-
const decryptedPayload = JSON.parse(decryptFromStorage(task.encrypted_payload, userKey));
|
|
1585
|
-
|
|
1586
|
-
if (decryptedPayload.recurrenceType === 'none') {
|
|
1587
|
-
await db.deleteTaskById(task.id);
|
|
1588
|
-
results.deletedOnceOffTasks++;
|
|
1589
|
-
} else {
|
|
1590
|
-
let nextSendAt;
|
|
1591
|
-
const currentSendAt = new Date(task.next_send_at);
|
|
1592
|
-
if (decryptedPayload.recurrenceType === 'daily') {
|
|
1593
|
-
nextSendAt = new Date(currentSendAt.getTime() + 24 * 60 * 60 * 1000);
|
|
1594
|
-
} else if (decryptedPayload.recurrenceType === 'weekly') {
|
|
1595
|
-
nextSendAt = new Date(currentSendAt.getTime() + 7 * 24 * 60 * 60 * 1000);
|
|
1596
|
-
}
|
|
1597
|
-
await db.updateTaskById(task.id, { next_send_at: nextSendAt.toISOString(), retry_count: 0 });
|
|
1598
|
-
results.updatedRecurringTasks++;
|
|
1599
|
-
}
|
|
1600
|
-
|
|
1601
|
-
results.successCount++;
|
|
1602
|
-
} catch (error) {
|
|
1603
|
-
await handlePostSendPersistenceFailure(task, error.message || '发送后状态更新失败');
|
|
1604
|
-
}
|
|
1605
|
-
}
|
|
1606
|
-
|
|
1607
|
-
// Dynamic task pool
|
|
1608
|
-
const taskQueue = [...tasks];
|
|
1609
|
-
const processing = [];
|
|
1610
|
-
|
|
1611
|
-
while (taskQueue.length > 0 || processing.length > 0) {
|
|
1612
|
-
while (processing.length < MAX_CONCURRENT && taskQueue.length > 0) {
|
|
1613
|
-
const task = taskQueue.shift();
|
|
1614
|
-
const promise = processTask(task);
|
|
1615
|
-
processing.push(promise);
|
|
1616
|
-
promise.finally(() => {
|
|
1617
|
-
const index = processing.indexOf(promise);
|
|
1618
|
-
if (index > -1) processing.splice(index, 1);
|
|
1619
|
-
});
|
|
1620
|
-
}
|
|
1621
|
-
if (processing.length > 0) {
|
|
1622
|
-
await Promise.race(processing);
|
|
1623
|
-
}
|
|
1624
|
-
}
|
|
1625
|
-
|
|
1626
|
-
// Cleanup old tasks
|
|
1627
|
-
await db.cleanupOldTasks(7);
|
|
1628
|
-
|
|
1629
|
-
const executionTime = Date.now() - startTime;
|
|
1630
|
-
|
|
1631
|
-
return {
|
|
1632
|
-
status: 200,
|
|
1633
|
-
body: {
|
|
1634
|
-
success: true,
|
|
1635
|
-
data: {
|
|
1636
|
-
totalTasks: results.totalTasks,
|
|
1637
|
-
successCount: results.successCount,
|
|
1638
|
-
failedCount: results.failedCount,
|
|
1639
|
-
processedAt: new Date().toISOString(),
|
|
1640
|
-
executionTime,
|
|
1641
|
-
details: {
|
|
1642
|
-
deletedOnceOffTasks: results.deletedOnceOffTasks,
|
|
1643
|
-
updatedRecurringTasks: results.updatedRecurringTasks,
|
|
1644
|
-
failedTasks: results.failedTasks
|
|
1645
|
-
}
|
|
1646
|
-
}
|
|
1647
|
-
}
|
|
1648
|
-
};
|
|
1649
|
-
}
|
|
1650
|
-
|
|
1651
|
-
return { POST };
|
|
1652
|
-
}
|
|
1653
|
-
|
|
1654
|
-
/**
|
|
1655
|
-
* Handler: update-message
|
|
1656
|
-
* ReiStandard SDK v2.0.1
|
|
1657
|
-
*
|
|
1658
|
-
* @param {Object} ctx - Server context.
|
|
1659
|
-
* @returns {{ PUT: function }}
|
|
1660
|
-
*/
|
|
1661
|
-
|
|
1662
|
-
|
|
1663
|
-
function createUpdateMessageHandler(ctx) {
|
|
1664
|
-
async function PUT(url, headers, body) {
|
|
1665
|
-
const tenantResult = await ctx.tenantManager.resolveTenant(headers, { url });
|
|
1666
|
-
if (!tenantResult.ok) {
|
|
1667
|
-
return tenantResult.error;
|
|
1668
|
-
}
|
|
1669
|
-
|
|
1670
|
-
const tenantCtx = tenantResult.context;
|
|
1671
|
-
const db = tenantCtx.db;
|
|
1672
|
-
const masterKey = tenantCtx.masterKey;
|
|
1673
|
-
const u = new URL(url, 'https://dummy');
|
|
1674
|
-
const taskUuid = u.searchParams.get('id');
|
|
1675
|
-
|
|
1676
|
-
if (!taskUuid) {
|
|
1677
|
-
return { status: 400, body: { success: false, error: { code: 'TASK_ID_REQUIRED', message: '缺少任务ID' } } };
|
|
1678
|
-
}
|
|
1679
|
-
|
|
1680
|
-
const userId = getHeader(headers, 'x-user-id');
|
|
1681
|
-
if (!userId) {
|
|
1682
|
-
return { status: 400, body: { success: false, error: { code: 'USER_ID_REQUIRED', message: '缺少用户标识符' } } };
|
|
1683
|
-
}
|
|
1684
|
-
if (!isValidUUIDv4(userId)) {
|
|
1685
|
-
return { status: 400, body: { success: false, error: { code: 'INVALID_USER_ID_FORMAT', message: 'X-User-Id 必须是 UUID v4 格式' } } };
|
|
1686
|
-
}
|
|
1687
|
-
|
|
1688
|
-
const isEncrypted = getHeader(headers, 'x-payload-encrypted') === 'true';
|
|
1689
|
-
const encryptionVersion = getHeader(headers, 'x-encryption-version');
|
|
1690
|
-
|
|
1691
|
-
if (!isEncrypted) {
|
|
1692
|
-
return { status: 400, body: { success: false, error: { code: 'ENCRYPTION_REQUIRED', message: '请求体必须加密' } } };
|
|
1693
|
-
}
|
|
1694
|
-
|
|
1695
|
-
if (encryptionVersion !== '1') {
|
|
1696
|
-
return { status: 400, body: { success: false, error: { code: 'UNSUPPORTED_ENCRYPTION_VERSION', message: '加密版本不支持' } } };
|
|
1697
|
-
}
|
|
1698
|
-
|
|
1699
|
-
const parsedBody = parseEncryptedBody(body);
|
|
1700
|
-
if (!parsedBody.ok) {
|
|
1701
|
-
return { status: 400, body: { success: false, error: parsedBody.error } };
|
|
1702
|
-
}
|
|
1703
|
-
|
|
1704
|
-
const encryptedBody = parsedBody.data;
|
|
1705
|
-
const userKey = deriveUserEncryptionKey(userId, masterKey);
|
|
1706
|
-
let updates;
|
|
1707
|
-
|
|
1708
|
-
try {
|
|
1709
|
-
updates = decryptPayload(encryptedBody, userKey);
|
|
1710
|
-
} catch (_error) {
|
|
1711
|
-
return { status: 400, body: { success: false, error: { code: 'DECRYPTION_FAILED', message: '请求体解密失败' } } };
|
|
1712
|
-
}
|
|
1713
|
-
|
|
1714
|
-
if (!isPlainObject(updates)) {
|
|
1715
|
-
return { status: 400, body: { success: false, error: { code: 'INVALID_UPDATE_DATA', message: '更新数据格式错误' } } };
|
|
1716
|
-
}
|
|
1717
|
-
|
|
1718
|
-
if (updates.nextSendAt && !isValidISO8601(updates.nextSendAt)) {
|
|
1719
|
-
return { status: 400, body: { success: false, error: { code: 'INVALID_UPDATE_DATA', message: '更新数据格式错误', details: { invalidFields: ['nextSendAt'] } } } };
|
|
1720
|
-
}
|
|
1721
|
-
|
|
1722
|
-
if (updates.recurrenceType && !['none', 'daily', 'weekly'].includes(updates.recurrenceType)) {
|
|
1723
|
-
return { status: 400, body: { success: false, error: { code: 'INVALID_UPDATE_DATA', message: '更新数据格式错误', details: { invalidFields: ['recurrenceType'] } } } };
|
|
1724
|
-
}
|
|
1725
|
-
|
|
1726
|
-
if (
|
|
1727
|
-
Object.prototype.hasOwnProperty.call(updates, 'maxTokens') &&
|
|
1728
|
-
updates.maxTokens !== null &&
|
|
1729
|
-
(!Number.isInteger(updates.maxTokens) || updates.maxTokens <= 0)
|
|
1730
|
-
) {
|
|
1731
|
-
return { status: 400, body: { success: false, error: { code: 'INVALID_UPDATE_DATA', message: '更新数据格式错误', details: { invalidFields: ['maxTokens'] } } } };
|
|
1732
|
-
}
|
|
1733
|
-
|
|
1734
|
-
// Reject updates that try to set both completePrompt and messages at
|
|
1735
|
-
// once. We don't enforce one-of-required here (callers may patch other
|
|
1736
|
-
// fields), but the two prompt sources are mutually exclusive and must
|
|
1737
|
-
// stay that way in storage too.
|
|
1738
|
-
if (
|
|
1739
|
-
updates.completePrompt &&
|
|
1740
|
-
updates.messages !== undefined && updates.messages !== null
|
|
1741
|
-
) {
|
|
1742
|
-
return { status: 400, body: { success: false, error: { code: 'INVALID_UPDATE_DATA', message: 'completePrompt 与 messages 不能同时更新(二选一)', details: { invalidFields: ['completePrompt', 'messages'] } } } };
|
|
1743
|
-
}
|
|
1744
|
-
if (updates.messages !== undefined && updates.messages !== null) {
|
|
1745
|
-
const msgErr = validateLlmMessagesArray(updates.messages);
|
|
1746
|
-
if (msgErr) {
|
|
1747
|
-
return { status: 400, body: { success: false, error: { code: 'INVALID_UPDATE_DATA', message: msgErr, details: { invalidFields: ['messages'] } } } };
|
|
1748
|
-
}
|
|
1749
|
-
}
|
|
1750
|
-
if (
|
|
1751
|
-
Object.prototype.hasOwnProperty.call(updates, 'temperature') &&
|
|
1752
|
-
updates.temperature !== null &&
|
|
1753
|
-
(typeof updates.temperature !== 'number' || !Number.isFinite(updates.temperature))
|
|
1754
|
-
) {
|
|
1755
|
-
return { status: 400, body: { success: false, error: { code: 'INVALID_UPDATE_DATA', message: '更新数据格式错误', details: { invalidFields: ['temperature'] } } } };
|
|
1756
|
-
}
|
|
1757
|
-
if (Object.prototype.hasOwnProperty.call(updates, 'splitPattern')) {
|
|
1758
|
-
const splitErr = validateSplitPattern(updates.splitPattern);
|
|
1759
|
-
if (splitErr) {
|
|
1760
|
-
return { status: 400, body: { success: false, error: { code: 'INVALID_UPDATE_DATA', message: splitErr, details: { invalidFields: ['splitPattern'] } } } };
|
|
1761
|
-
}
|
|
1762
|
-
}
|
|
1763
|
-
if (Object.prototype.hasOwnProperty.call(updates, 'avatarUrl')) {
|
|
1764
|
-
const avatarErr = validateAvatarUrl(updates.avatarUrl);
|
|
1765
|
-
if (avatarErr) {
|
|
1766
|
-
// Soft-strip: drop the bad avatarUrl from the patch (keeps the
|
|
1767
|
-
// existing stored avatar untouched) and continue applying the rest
|
|
1768
|
-
// of the update. See standards §6.2.
|
|
1769
|
-
console.warn('[amsg-server] update-message avatarUrl 不合法,已忽略:', avatarErr);
|
|
1770
|
-
delete updates.avatarUrl;
|
|
1771
|
-
}
|
|
1772
|
-
}
|
|
1773
|
-
|
|
1774
|
-
// Fetch existing task
|
|
1775
|
-
const existingTask = await db.getTaskByUuid(taskUuid, userId);
|
|
1776
|
-
|
|
1777
|
-
if (!existingTask) {
|
|
1778
|
-
const taskStatus = await db.getTaskStatus(taskUuid, userId);
|
|
1779
|
-
if (!taskStatus) {
|
|
1780
|
-
return { status: 404, body: { success: false, error: { code: 'TASK_NOT_FOUND', message: '指定的任务不存在或已被删除' } } };
|
|
1781
|
-
}
|
|
1782
|
-
return { status: 409, body: { success: false, error: { code: 'TASK_ALREADY_COMPLETED', message: '任务已完成或已失败,无法更新' } } };
|
|
1783
|
-
}
|
|
1784
|
-
|
|
1785
|
-
const existingData = JSON.parse(decryptFromStorage(existingTask.encrypted_payload, userKey));
|
|
1786
|
-
|
|
1787
|
-
// When the caller switches prompt source (completePrompt ↔ messages),
|
|
1788
|
-
// null out the other so storage stays one-of (matches schedule-message
|
|
1789
|
-
// shape and prevents buildAiRequestBody from accidentally seeing both).
|
|
1790
|
-
const promptUpdates = {};
|
|
1791
|
-
if (updates.completePrompt) {
|
|
1792
|
-
promptUpdates.completePrompt = updates.completePrompt;
|
|
1793
|
-
promptUpdates.messages = null;
|
|
1794
|
-
} else if (updates.messages !== undefined && updates.messages !== null) {
|
|
1795
|
-
promptUpdates.messages = updates.messages;
|
|
1796
|
-
promptUpdates.completePrompt = null;
|
|
1797
|
-
}
|
|
1798
|
-
|
|
1799
|
-
const updatedData = {
|
|
1800
|
-
...existingData,
|
|
1801
|
-
...promptUpdates,
|
|
1802
|
-
...(updates.userMessage && { userMessage: updates.userMessage }),
|
|
1803
|
-
...(updates.recurrenceType && { recurrenceType: updates.recurrenceType }),
|
|
1804
|
-
...(updates.avatarUrl && { avatarUrl: updates.avatarUrl }),
|
|
1805
|
-
...(updates.metadata && { metadata: updates.metadata }),
|
|
1806
|
-
...(Object.prototype.hasOwnProperty.call(updates, 'maxTokens') && { maxTokens: updates.maxTokens ?? null }),
|
|
1807
|
-
...(Object.prototype.hasOwnProperty.call(updates, 'temperature') && { temperature: updates.temperature ?? null }),
|
|
1808
|
-
// splitPattern: hasOwnProperty so that explicit `null` (= revert to
|
|
1809
|
-
// default) doesn't get swallowed by truthy-spread the way the optional
|
|
1810
|
-
// string fields above are.
|
|
1811
|
-
...(Object.prototype.hasOwnProperty.call(updates, 'splitPattern') && { splitPattern: updates.splitPattern ?? null })
|
|
1812
|
-
};
|
|
1813
|
-
|
|
1814
|
-
const encryptedPayload = encryptForStorage(JSON.stringify(updatedData), userKey);
|
|
1815
|
-
const extraFields = updates.nextSendAt ? { next_send_at: updates.nextSendAt } : undefined;
|
|
1816
|
-
|
|
1817
|
-
const result = await db.updateTaskByUuid(taskUuid, userId, encryptedPayload, extraFields);
|
|
1818
|
-
|
|
1819
|
-
if (!result) {
|
|
1820
|
-
return { status: 409, body: { success: false, error: { code: 'UPDATE_CONFLICT', message: '任务更新失败,任务可能已被修改或删除' } } };
|
|
1821
|
-
}
|
|
1822
|
-
|
|
1823
|
-
return {
|
|
1824
|
-
status: 200,
|
|
1825
|
-
body: {
|
|
1826
|
-
success: true,
|
|
1827
|
-
data: {
|
|
1828
|
-
uuid: taskUuid,
|
|
1829
|
-
updatedFields: Object.keys(updates),
|
|
1830
|
-
updatedAt: result.updated_at
|
|
1831
|
-
}
|
|
1832
|
-
}
|
|
1833
|
-
};
|
|
1834
|
-
}
|
|
1835
|
-
|
|
1836
|
-
return { PUT };
|
|
1837
|
-
}
|
|
1838
|
-
|
|
1839
|
-
/**
|
|
1840
|
-
* Handler: cancel-message
|
|
1841
|
-
* ReiStandard SDK v2.0.1
|
|
1842
|
-
*
|
|
1843
|
-
* @param {Object} ctx - Server context.
|
|
1844
|
-
* @returns {{ DELETE: function }}
|
|
1845
|
-
*/
|
|
1846
|
-
|
|
1847
|
-
|
|
1848
|
-
function createCancelMessageHandler(ctx) {
|
|
1849
|
-
async function DELETE(url, headers) {
|
|
1850
|
-
const tenantResult = await ctx.tenantManager.resolveTenant(headers, { url });
|
|
1851
|
-
if (!tenantResult.ok) {
|
|
1852
|
-
return tenantResult.error;
|
|
1853
|
-
}
|
|
1854
|
-
|
|
1855
|
-
const db = tenantResult.context.db;
|
|
1856
|
-
const u = new URL(url, 'https://dummy');
|
|
1857
|
-
const taskUuid = u.searchParams.get('id');
|
|
1858
|
-
|
|
1859
|
-
if (!taskUuid) {
|
|
1860
|
-
return { status: 400, body: { success: false, error: { code: 'TASK_ID_REQUIRED', message: '缺少任务ID' } } };
|
|
1861
|
-
}
|
|
1862
|
-
|
|
1863
|
-
const userId = getHeader(headers, 'x-user-id');
|
|
1864
|
-
if (!userId) {
|
|
1865
|
-
return { status: 400, body: { success: false, error: { code: 'USER_ID_REQUIRED', message: '缺少用户标识符' } } };
|
|
1866
|
-
}
|
|
1867
|
-
if (!isValidUUIDv4(userId)) {
|
|
1868
|
-
return { status: 400, body: { success: false, error: { code: 'INVALID_USER_ID_FORMAT', message: 'X-User-Id 必须是 UUID v4 格式' } } };
|
|
1869
|
-
}
|
|
1870
|
-
|
|
1871
|
-
const deleted = await db.deleteTaskByUuid(taskUuid, userId);
|
|
1872
|
-
|
|
1873
|
-
if (!deleted) {
|
|
1874
|
-
return {
|
|
1875
|
-
status: 404,
|
|
1876
|
-
body: { success: false, error: { code: 'TASK_NOT_FOUND', message: '指定的任务不存在或已被删除' } }
|
|
1877
|
-
};
|
|
1878
|
-
}
|
|
1879
|
-
|
|
1880
|
-
return {
|
|
1881
|
-
status: 200,
|
|
1882
|
-
body: {
|
|
1883
|
-
success: true,
|
|
1884
|
-
data: { uuid: taskUuid, message: '任务已成功取消', deletedAt: new Date().toISOString() }
|
|
1885
|
-
}
|
|
1886
|
-
};
|
|
1887
|
-
}
|
|
1888
|
-
|
|
1889
|
-
return { DELETE };
|
|
1890
|
-
}
|
|
1891
|
-
|
|
1892
|
-
/**
|
|
1893
|
-
* Handler: messages
|
|
1894
|
-
* ReiStandard SDK v2.0.1
|
|
1895
|
-
*
|
|
1896
|
-
* @param {Object} ctx - Server context.
|
|
1897
|
-
* @returns {{ GET: function }}
|
|
1898
|
-
*/
|
|
1899
|
-
|
|
1900
|
-
|
|
1901
|
-
function createMessagesHandler(ctx) {
|
|
1902
|
-
async function GET(url, headers) {
|
|
1903
|
-
const tenantResult = await ctx.tenantManager.resolveTenant(headers, { url });
|
|
1904
|
-
if (!tenantResult.ok) {
|
|
1905
|
-
return tenantResult.error;
|
|
1906
|
-
}
|
|
1907
|
-
|
|
1908
|
-
const tenantCtx = tenantResult.context;
|
|
1909
|
-
const db = tenantCtx.db;
|
|
1910
|
-
const masterKey = tenantCtx.masterKey;
|
|
1911
|
-
const userId = getHeader(headers, 'x-user-id');
|
|
1912
|
-
|
|
1913
|
-
if (!userId) {
|
|
1914
|
-
return {
|
|
1915
|
-
status: 400,
|
|
1916
|
-
body: { success: false, error: { code: 'USER_ID_REQUIRED', message: '必须提供 X-User-Id 请求头' } }
|
|
1917
|
-
};
|
|
1918
|
-
}
|
|
1919
|
-
if (!isValidUUIDv4(userId)) {
|
|
1920
|
-
return {
|
|
1921
|
-
status: 400,
|
|
1922
|
-
body: { success: false, error: { code: 'INVALID_USER_ID_FORMAT', message: 'X-User-Id 必须是 UUID v4 格式' } }
|
|
1923
|
-
};
|
|
1924
|
-
}
|
|
1925
|
-
|
|
1926
|
-
const u = new URL(url, 'https://dummy');
|
|
1927
|
-
const status = u.searchParams.get('status') || 'all';
|
|
1928
|
-
const limit = Math.min(parseInt(u.searchParams.get('limit') || '20', 10), 100);
|
|
1929
|
-
const offset = parseInt(u.searchParams.get('offset') || '0', 10);
|
|
1930
|
-
|
|
1931
|
-
if (isNaN(limit) || limit < 1) {
|
|
1932
|
-
return { status: 400, body: { success: false, error: { code: 'INVALID_PARAMETERS', message: 'limit 参数无效,必须为正整数' } } };
|
|
1933
|
-
}
|
|
1934
|
-
|
|
1935
|
-
if (isNaN(offset) || offset < 0) {
|
|
1936
|
-
return { status: 400, body: { success: false, error: { code: 'INVALID_PARAMETERS', message: 'offset 参数无效,必须为非负整数' } } };
|
|
1937
|
-
}
|
|
1938
|
-
|
|
1939
|
-
const { tasks, total } = await db.listTasks(userId, { status, limit, offset });
|
|
1940
|
-
|
|
1941
|
-
const userKey = deriveUserEncryptionKey(userId, masterKey);
|
|
1942
|
-
|
|
1943
|
-
const decryptedTasks = tasks.map(task => {
|
|
1944
|
-
const decrypted = JSON.parse(decryptFromStorage(task.encrypted_payload, userKey));
|
|
1945
|
-
return {
|
|
1946
|
-
id: task.id,
|
|
1947
|
-
uuid: task.uuid,
|
|
1948
|
-
contactName: decrypted.contactName,
|
|
1949
|
-
messageType: task.message_type,
|
|
1950
|
-
messageSubtype: decrypted.messageSubtype,
|
|
1951
|
-
nextSendAt: task.next_send_at,
|
|
1952
|
-
recurrenceType: decrypted.recurrenceType,
|
|
1953
|
-
status: task.status,
|
|
1954
|
-
retryCount: task.retry_count,
|
|
1955
|
-
createdAt: task.created_at,
|
|
1956
|
-
updatedAt: task.updated_at
|
|
1957
|
-
};
|
|
1958
|
-
});
|
|
1959
|
-
|
|
1960
|
-
const responsePayload = {
|
|
1961
|
-
tasks: decryptedTasks,
|
|
1962
|
-
pagination: { total, limit, offset, hasMore: offset + limit < total }
|
|
1963
|
-
};
|
|
1964
|
-
const encryptedResponse = encryptPayload(responsePayload, userKey);
|
|
1965
|
-
|
|
1966
|
-
return {
|
|
1967
|
-
status: 200,
|
|
1968
|
-
body: {
|
|
1969
|
-
success: true,
|
|
1970
|
-
encrypted: true,
|
|
1971
|
-
version: 1,
|
|
1972
|
-
data: encryptedResponse
|
|
1973
|
-
}
|
|
1974
|
-
};
|
|
1975
|
-
}
|
|
1976
|
-
|
|
1977
|
-
return { GET };
|
|
1978
|
-
}
|
|
1979
|
-
|
|
1980
248
|
const inMemoryNamespaces = new Map();
|
|
1981
249
|
|
|
1982
250
|
function base64UrlEncode$1(input) {
|
|
@@ -2536,4 +804,4 @@ async function createReiServer(config) {
|
|
|
2536
804
|
};
|
|
2537
805
|
}
|
|
2538
806
|
|
|
2539
|
-
export { createAdapter, createReiServer, createTenantToken,
|
|
807
|
+
export { createAdapter, createReiServer, createTenantToken, isValidUUIDv4, runScheduledTick, verifyTenantToken };
|