@rei-standard/amsg-server 1.2.0 → 2.0.0-pre1

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/index.d.ts CHANGED
@@ -1,2 +1,2053 @@
1
- export { c as createAdapter, d as createReiServer, e as decryptFromStorage, f as decryptPayload, g as deriveUserEncryptionKey, h as encryptForStorage, i as isValidISO8601, j as isValidUUID, k as isValidUUIDv4, l as isValidUrl, v as validateScheduleMessagePayload } from './index-DvXRyTLZ.js';
2
- import 'crypto';
1
+ import { createDecipheriv, createHash, randomBytes, createCipheriv, randomUUID, timingSafeEqual, createHmac } from 'crypto';
2
+
3
+ /**
4
+ * Adapter Factory
5
+ * ReiStandard SDK v2.0.0-pre1
6
+ *
7
+ * Creates a database adapter instance based on the supplied configuration.
8
+ *
9
+ * @typedef {'neon'|'pg'} DriverName
10
+ *
11
+ * @typedef {Object} AdapterConfig
12
+ * @property {DriverName} driver - Which database driver to use.
13
+ * @property {string} connectionString - Database connection URL.
14
+ */
15
+
16
+ /**
17
+ * Create a database adapter.
18
+ *
19
+ * @param {AdapterConfig} config
20
+ * @returns {Promise<import('./interface.js').DbAdapter>}
21
+ */
22
+ async function createAdapter(config) {
23
+ if (!config || !config.driver) {
24
+ throw new Error(
25
+ '[rei-standard-amsg-server] "driver" is required in the db config. ' +
26
+ 'Supported drivers: neon, pg'
27
+ );
28
+ }
29
+
30
+ if (!config.connectionString) {
31
+ throw new Error(
32
+ '[rei-standard-amsg-server] "connectionString" is required in the db config.'
33
+ );
34
+ }
35
+
36
+ switch (config.driver) {
37
+ case 'neon': {
38
+ const { NeonAdapter } = await import('./neon-DyBfYFkz.d.ts');
39
+ return new NeonAdapter(config.connectionString);
40
+ }
41
+
42
+ case 'pg': {
43
+ const { PgAdapter } = await import('./pg-DJWS_HZ3.d.ts');
44
+ return new PgAdapter(config.connectionString);
45
+ }
46
+
47
+ default:
48
+ throw new Error(
49
+ `[rei-standard-amsg-server] Unsupported driver "${config.driver}". ` +
50
+ 'Supported drivers: neon, pg'
51
+ );
52
+ }
53
+ }
54
+
55
+ /**
56
+ * Validation utility library (SDK version)
57
+ * ReiStandard SDK v2.0.0-pre1
58
+ */
59
+
60
+ /**
61
+ * Validate ISO 8601 date string.
62
+ * @param {string} dateString
63
+ * @returns {boolean}
64
+ */
65
+ function isValidISO8601(dateString) {
66
+ const date = new Date(dateString);
67
+ return date instanceof Date && !isNaN(date.getTime());
68
+ }
69
+
70
+ /**
71
+ * Validate URL format.
72
+ * @param {string} urlString
73
+ * @returns {boolean}
74
+ */
75
+ function isValidUrl(urlString) {
76
+ try {
77
+ new URL(urlString);
78
+ return true;
79
+ } catch {
80
+ return false;
81
+ }
82
+ }
83
+
84
+ /**
85
+ * Validate UUID format.
86
+ * @param {string} uuid
87
+ * @returns {boolean}
88
+ */
89
+ function isValidUUID(uuid) {
90
+ const uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
91
+ return uuidRegex.test(uuid);
92
+ }
93
+
94
+ /**
95
+ * Validate UUID v4 format.
96
+ * @param {string} uuid
97
+ * @returns {boolean}
98
+ */
99
+ function isValidUUIDv4(uuid) {
100
+ 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;
101
+ return uuidV4Regex.test(uuid);
102
+ }
103
+
104
+ /**
105
+ * Validate the schedule-message request payload.
106
+ *
107
+ * @param {Object} payload
108
+ * @returns {{ valid: boolean, errorCode?: string, errorMessage?: string, details?: Object }}
109
+ */
110
+ function validateScheduleMessagePayload(payload) {
111
+ if (!payload.contactName || typeof payload.contactName !== 'string') {
112
+ return { valid: false, errorCode: 'INVALID_PARAMETERS', errorMessage: '缺少必需参数或参数格式错误', details: { missingFields: ['contactName'] } };
113
+ }
114
+
115
+ if (!payload.messageType || !['fixed', 'prompted', 'auto', 'instant'].includes(payload.messageType)) {
116
+ return { valid: false, errorCode: 'INVALID_MESSAGE_TYPE', errorMessage: '消息类型无效', details: { providedType: payload.messageType, allowedTypes: ['fixed', 'prompted', 'auto', 'instant'] } };
117
+ }
118
+
119
+ if (!payload.firstSendTime || !isValidISO8601(payload.firstSendTime)) {
120
+ return { valid: false, errorCode: 'INVALID_TIMESTAMP', errorMessage: '时间格式无效', details: { field: 'firstSendTime' } };
121
+ }
122
+
123
+ if (payload.firstSendTime && new Date(payload.firstSendTime) <= new Date()) {
124
+ return { valid: false, errorCode: 'INVALID_TIMESTAMP', errorMessage: '时间必须在未来', details: { field: 'firstSendTime', reason: 'must be in the future' } };
125
+ }
126
+
127
+ if (!payload.pushSubscription || typeof payload.pushSubscription !== 'object') {
128
+ return { valid: false, errorCode: 'INVALID_PARAMETERS', errorMessage: '缺少必需参数或参数格式错误', details: { missingFields: ['pushSubscription'] } };
129
+ }
130
+
131
+ if (payload.recurrenceType && !['none', 'daily', 'weekly'].includes(payload.recurrenceType)) {
132
+ return { valid: false, errorCode: 'INVALID_PARAMETERS', errorMessage: '缺少必需参数或参数格式错误', details: { invalidFields: ['recurrenceType'] } };
133
+ }
134
+
135
+ if (payload.messageType === 'fixed') {
136
+ if (!payload.userMessage) {
137
+ return { valid: false, errorCode: 'INVALID_PARAMETERS', errorMessage: '缺少必需参数或参数格式错误', details: { missingFields: ['userMessage (required for fixed type)'] } };
138
+ }
139
+ }
140
+
141
+ if (payload.messageType === 'prompted' || payload.messageType === 'auto') {
142
+ const missingAiFields = [];
143
+ if (!payload.completePrompt) missingAiFields.push('completePrompt');
144
+ if (!payload.apiUrl) missingAiFields.push('apiUrl');
145
+ if (!payload.apiKey) missingAiFields.push('apiKey');
146
+ if (!payload.primaryModel) missingAiFields.push('primaryModel');
147
+ if (missingAiFields.length > 0) {
148
+ return { valid: false, errorCode: 'INVALID_PARAMETERS', errorMessage: '缺少必需参数或参数格式错误', details: { missingFields: missingAiFields } };
149
+ }
150
+ }
151
+
152
+ if (payload.messageType === 'instant') {
153
+ if (payload.recurrenceType && payload.recurrenceType !== 'none') {
154
+ return { valid: false, errorCode: 'INVALID_PARAMETERS', errorMessage: 'instant 类型的 recurrenceType 必须为 none', details: { invalidFields: ['recurrenceType (must be "none" for instant type)'] } };
155
+ }
156
+ const hasAiConfig = payload.completePrompt && payload.apiUrl && payload.apiKey && payload.primaryModel;
157
+ const hasUserMessage = payload.userMessage;
158
+ if (!hasAiConfig && !hasUserMessage) {
159
+ return { valid: false, errorCode: 'INVALID_PARAMETERS', errorMessage: 'instant 类型必须提供 userMessage 或完整的 AI 配置', details: { missingFields: ['userMessage or (completePrompt + apiUrl + apiKey + primaryModel)'] } };
160
+ }
161
+ }
162
+
163
+ if (payload.avatarUrl && !isValidUrl(payload.avatarUrl)) {
164
+ return { valid: false, errorCode: 'INVALID_PARAMETERS', errorMessage: '缺少必需参数或参数格式错误', details: { invalidFields: ['avatarUrl (invalid URL format)'] } };
165
+ }
166
+ if (payload.uuid && !isValidUUID(payload.uuid)) {
167
+ return { valid: false, errorCode: 'INVALID_PARAMETERS', errorMessage: '缺少必需参数或参数格式错误', details: { invalidFields: ['uuid (invalid UUID format)'] } };
168
+ }
169
+ if (payload.messageSubtype && !['chat', 'forum', 'moment'].includes(payload.messageSubtype)) {
170
+ return { valid: false, errorCode: 'INVALID_PARAMETERS', errorMessage: '缺少必需参数或参数格式错误', details: { invalidFields: ['messageSubtype'] } };
171
+ }
172
+
173
+ return { valid: true };
174
+ }
175
+
176
+ /**
177
+ * Request payload utilities.
178
+ * Keeps body parsing and shape validation consistent across handlers.
179
+ */
180
+
181
+ const REQUEST_ERRORS = {
182
+ INVALID_JSON: { code: 'INVALID_JSON', message: '请求体不是有效的 JSON' },
183
+ INVALID_REQUEST_BODY: { code: 'INVALID_REQUEST_BODY', message: '请求体格式无效' },
184
+ INVALID_ENCRYPTED_PAYLOAD: { code: 'INVALID_ENCRYPTED_PAYLOAD', message: '加密数据格式错误' }
185
+ };
186
+
187
+ /**
188
+ * @typedef {{ code: string, message: string }} ValidationError
189
+ */
190
+
191
+ /**
192
+ * @typedef {{
193
+ * invalidJson?: ValidationError,
194
+ * invalidType?: ValidationError
195
+ * }} ParseBodyOptions
196
+ */
197
+
198
+ /**
199
+ * @typedef {{
200
+ * ok: true,
201
+ * data: Record<string, any>
202
+ * } | {
203
+ * ok: false,
204
+ * error: ValidationError
205
+ * }} ParseBodyResult
206
+ */
207
+
208
+ /**
209
+ * Parse body into a JSON object.
210
+ *
211
+ * @param {unknown} body
212
+ * @param {ParseBodyOptions} [options]
213
+ * @returns {ParseBodyResult}
214
+ */
215
+ function parseBodyAsObject(body, options = {}) {
216
+ const invalidJson = options.invalidJson || REQUEST_ERRORS.INVALID_JSON;
217
+ const invalidType = options.invalidType || REQUEST_ERRORS.INVALID_REQUEST_BODY;
218
+
219
+ let parsed = body;
220
+ if (typeof parsed === 'string') {
221
+ try {
222
+ parsed = JSON.parse(parsed);
223
+ } catch {
224
+ return { ok: false, error: invalidJson };
225
+ }
226
+ }
227
+
228
+ if (!isPlainObject(parsed)) {
229
+ return { ok: false, error: invalidType };
230
+ }
231
+
232
+ return { ok: true, data: parsed };
233
+ }
234
+
235
+ /**
236
+ * Parse a standard JSON object body.
237
+ *
238
+ * @param {unknown} body
239
+ * @returns {ParseBodyResult}
240
+ */
241
+ function parseJsonBody(body) {
242
+ return parseBodyAsObject(body, {
243
+ invalidJson: REQUEST_ERRORS.INVALID_JSON,
244
+ invalidType: REQUEST_ERRORS.INVALID_REQUEST_BODY
245
+ });
246
+ }
247
+
248
+ /**
249
+ * Check if a value is a plain object (and not null/array).
250
+ *
251
+ * @param {unknown} value
252
+ * @returns {value is Record<string, any>}
253
+ */
254
+ function isPlainObject(value) {
255
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
256
+ }
257
+
258
+ /**
259
+ * Check if an object follows the encrypted payload envelope shape.
260
+ *
261
+ * @param {unknown} payload
262
+ * @returns {payload is { iv: string, authTag: string, encryptedData: string }}
263
+ */
264
+ function isEncryptedEnvelope(payload) {
265
+ if (!isPlainObject(payload)) return false;
266
+
267
+ return (
268
+ typeof payload.iv === 'string' &&
269
+ typeof payload.authTag === 'string' &&
270
+ typeof payload.encryptedData === 'string'
271
+ );
272
+ }
273
+
274
+ /**
275
+ * Parse and validate an encrypted payload envelope.
276
+ *
277
+ * @param {unknown} body
278
+ * @returns {ParseBodyResult}
279
+ */
280
+ function parseEncryptedBody(body) {
281
+ const parsedBody = parseBodyAsObject(body, {
282
+ invalidJson: REQUEST_ERRORS.INVALID_ENCRYPTED_PAYLOAD,
283
+ invalidType: REQUEST_ERRORS.INVALID_ENCRYPTED_PAYLOAD
284
+ });
285
+
286
+ if (!parsedBody.ok) {
287
+ return parsedBody;
288
+ }
289
+
290
+ if (!isEncryptedEnvelope(parsedBody.data)) {
291
+ return { ok: false, error: REQUEST_ERRORS.INVALID_ENCRYPTED_PAYLOAD };
292
+ }
293
+
294
+ return parsedBody;
295
+ }
296
+
297
+ /**
298
+ * Read a header value case-insensitively.
299
+ *
300
+ * @param {Record<string, any>} headers
301
+ * @param {string} name
302
+ * @returns {string}
303
+ */
304
+ function getHeader(headers = {}, name) {
305
+ if (!headers || typeof headers !== 'object') {
306
+ return '';
307
+ }
308
+
309
+ const lowerName = String(name || '').toLowerCase();
310
+ if (!lowerName) return '';
311
+
312
+ for (const [key, value] of Object.entries(headers)) {
313
+ if (String(key).toLowerCase() === lowerName) {
314
+ return String(value || '').trim();
315
+ }
316
+ }
317
+
318
+ return '';
319
+ }
320
+
321
+ /**
322
+ * Handler: init-tenant
323
+ * ReiStandard SDK v2.0.0-pre1
324
+ *
325
+ * @param {Object} ctx - Server context.
326
+ * @returns {{ POST: function }}
327
+ */
328
+
329
+
330
+ function createInitTenantHandler(ctx) {
331
+ async function POST(headers, body) {
332
+ const initSecret = getHeader(headers, 'x-init-secret');
333
+
334
+ // If initSecret is configured, require a matching X-Init-Secret.
335
+ if (ctx.tenant.initSecret && initSecret !== ctx.tenant.initSecret) {
336
+ return {
337
+ status: 401,
338
+ body: {
339
+ success: false,
340
+ error: {
341
+ code: 'INVALID_INIT_AUTH',
342
+ message: '初始化鉴权失败'
343
+ }
344
+ }
345
+ };
346
+ }
347
+
348
+ const parsed = parseJsonBody(body);
349
+ if (!parsed.ok) {
350
+ return {
351
+ status: 400,
352
+ body: {
353
+ success: false,
354
+ error: parsed.error
355
+ }
356
+ };
357
+ }
358
+
359
+ const payload = parsed.data;
360
+ const tenantId = payload.tenantId || undefined;
361
+ const driver = payload.driver;
362
+ const databaseUrl = payload.databaseUrl || payload.connectionString;
363
+
364
+ if (tenantId && !isValidUUIDv4(tenantId)) {
365
+ return {
366
+ status: 400,
367
+ body: {
368
+ success: false,
369
+ error: {
370
+ code: 'INVALID_TENANT_ID',
371
+ message: 'tenantId 必须是 UUID v4 格式'
372
+ }
373
+ }
374
+ };
375
+ }
376
+
377
+ if (!databaseUrl || !driver) {
378
+ return {
379
+ status: 400,
380
+ body: {
381
+ success: false,
382
+ error: {
383
+ code: 'INVALID_PARAMETERS',
384
+ message: '缺少 driver 或 databaseUrl 参数'
385
+ }
386
+ }
387
+ };
388
+ }
389
+
390
+ try {
391
+ const result = await ctx.tenantManager.initializeTenant({
392
+ tenantId,
393
+ driver,
394
+ connectionString: databaseUrl
395
+ });
396
+
397
+ return {
398
+ status: 201,
399
+ body: {
400
+ success: true,
401
+ data: {
402
+ tenantId: result.tenantId,
403
+ tenantToken: result.tenantToken,
404
+ cronToken: result.cronToken,
405
+ cronWebhookUrl: result.cronWebhookUrl,
406
+ masterKeyFingerprint: result.masterKeyFingerprint
407
+ }
408
+ }
409
+ };
410
+ } catch (error) {
411
+ if (error.message === 'INVALID_DRIVER') {
412
+ return {
413
+ status: 400,
414
+ body: {
415
+ success: false,
416
+ error: {
417
+ code: 'INVALID_DRIVER',
418
+ message: 'driver 必须是 neon 或 pg'
419
+ }
420
+ }
421
+ };
422
+ }
423
+
424
+ if (error.message === 'INVALID_DATABASE_URL') {
425
+ return {
426
+ status: 400,
427
+ body: {
428
+ success: false,
429
+ error: {
430
+ code: 'INVALID_DATABASE_URL',
431
+ message: 'databaseUrl 不能为空'
432
+ }
433
+ }
434
+ };
435
+ }
436
+
437
+ if (error.message === 'TENANT_ALREADY_INITIALIZED') {
438
+ return {
439
+ status: 409,
440
+ body: {
441
+ success: false,
442
+ error: {
443
+ code: 'TENANT_ALREADY_INITIALIZED',
444
+ message: 'tenantId 已存在,不能重复初始化'
445
+ }
446
+ }
447
+ };
448
+ }
449
+
450
+ throw error;
451
+ }
452
+ }
453
+
454
+ return { POST };
455
+ }
456
+
457
+ /**
458
+ * Encryption utility library (SDK version)
459
+ * ReiStandard SDK v2.0.0-pre1
460
+ *
461
+ * Wraps AES-256-GCM operations for request/response and storage encryption.
462
+ */
463
+
464
+
465
+ /**
466
+ * Derive a user-specific encryption key from the master key.
467
+ *
468
+ * @param {string} userId - Unique user identifier.
469
+ * @param {string} masterKey - 64-char hex master key.
470
+ * @returns {string} 64-char hex key.
471
+ */
472
+ function deriveUserEncryptionKey(userId, masterKey) {
473
+ return createHash('sha256')
474
+ .update(masterKey + userId)
475
+ .digest('hex')
476
+ .slice(0, 64);
477
+ }
478
+
479
+ /**
480
+ * Decrypt a client-encrypted request body (AES-256-GCM, base64 encoded).
481
+ *
482
+ * @param {{ iv: string, authTag: string, encryptedData: string }} encryptedPayload
483
+ * @param {string} encryptionKey - 64-char hex key.
484
+ * @returns {Object} Decrypted JSON object.
485
+ */
486
+ function decryptPayload(encryptedPayload, encryptionKey) {
487
+ const { iv, authTag, encryptedData } = encryptedPayload;
488
+
489
+ const decipher = createDecipheriv(
490
+ 'aes-256-gcm',
491
+ Buffer.from(encryptionKey, 'hex'),
492
+ Buffer.from(iv, 'base64')
493
+ );
494
+
495
+ decipher.setAuthTag(Buffer.from(authTag, 'base64'));
496
+
497
+ const decrypted = Buffer.concat([
498
+ decipher.update(Buffer.from(encryptedData, 'base64')),
499
+ decipher.final()
500
+ ]);
501
+
502
+ return JSON.parse(decrypted.toString('utf8'));
503
+ }
504
+
505
+ /**
506
+ * Encrypt a JSON payload for API transfer (AES-256-GCM, base64 encoded).
507
+ *
508
+ * @param {string|Object} payload
509
+ * @param {string} encryptionKey - 64-char hex key.
510
+ * @returns {{ iv: string, authTag: string, encryptedData: string }}
511
+ */
512
+ function encryptPayload(payload, encryptionKey) {
513
+ const plaintext = typeof payload === 'string' ? payload : JSON.stringify(payload);
514
+ const iv = randomBytes(12);
515
+ const cipher = createCipheriv('aes-256-gcm', Buffer.from(encryptionKey, 'hex'), iv);
516
+ const encrypted = Buffer.concat([cipher.update(plaintext, 'utf8'), cipher.final()]);
517
+ const authTag = cipher.getAuthTag();
518
+
519
+ return {
520
+ iv: iv.toString('base64'),
521
+ authTag: authTag.toString('base64'),
522
+ encryptedData: encrypted.toString('base64')
523
+ };
524
+ }
525
+
526
+ /**
527
+ * Encrypt data for database storage (hex encoded, colon-separated).
528
+ *
529
+ * @param {string} text - Plaintext string.
530
+ * @param {string} encryptionKey - 64-char hex key.
531
+ * @returns {string} Format: iv:authTag:encryptedData
532
+ */
533
+ function encryptForStorage(text, encryptionKey) {
534
+ const iv = randomBytes(16);
535
+ const cipher = createCipheriv('aes-256-gcm', Buffer.from(encryptionKey, 'hex'), iv);
536
+ const encrypted = cipher.update(text, 'utf8', 'hex') + cipher.final('hex');
537
+ const authTag = cipher.getAuthTag();
538
+ return `${iv.toString('hex')}:${authTag.toString('hex')}:${encrypted}`;
539
+ }
540
+
541
+ /**
542
+ * Decrypt data from database storage format.
543
+ *
544
+ * @param {string} encryptedText - Format: iv:authTag:encryptedData
545
+ * @param {string} encryptionKey - 64-char hex key.
546
+ * @returns {string} Plaintext string.
547
+ */
548
+ function decryptFromStorage(encryptedText, encryptionKey) {
549
+ const [ivHex, authTagHex, encryptedDataHex] = encryptedText.split(':');
550
+ const decipher = createDecipheriv(
551
+ 'aes-256-gcm',
552
+ Buffer.from(encryptionKey, 'hex'),
553
+ Buffer.from(ivHex, 'hex')
554
+ );
555
+ decipher.setAuthTag(Buffer.from(authTagHex, 'hex'));
556
+ return decipher.update(encryptedDataHex, 'hex', 'utf8') + decipher.final('utf8');
557
+ }
558
+
559
+ /**
560
+ * Handler: get-user-key
561
+ * ReiStandard SDK v2.0.0-pre1
562
+ *
563
+ * @param {Object} ctx - Server context.
564
+ * @returns {{ GET: function }}
565
+ */
566
+
567
+
568
+ function createGetUserKeyHandler(ctx) {
569
+ async function GET(url, headers) {
570
+ const effectiveHeaders = headers || url || {};
571
+ const tenantResult = await ctx.tenantManager.resolveTenant(effectiveHeaders);
572
+ if (!tenantResult.ok) {
573
+ return tenantResult.error;
574
+ }
575
+
576
+ const { masterKey } = tenantResult.context;
577
+ const userId = getHeader(effectiveHeaders, 'x-user-id');
578
+
579
+ if (!userId) {
580
+ return {
581
+ status: 400,
582
+ body: { success: false, error: { code: 'USER_ID_REQUIRED', message: '缺少用户标识符' } }
583
+ };
584
+ }
585
+
586
+ if (!isValidUUIDv4(userId)) {
587
+ return {
588
+ status: 400,
589
+ body: { success: false, error: { code: 'INVALID_USER_ID_FORMAT', message: 'X-User-Id 必须是 UUID v4 格式' } }
590
+ };
591
+ }
592
+
593
+ return {
594
+ status: 200,
595
+ body: {
596
+ success: true,
597
+ data: {
598
+ userKey: deriveUserEncryptionKey(userId, masterKey),
599
+ version: 1
600
+ }
601
+ }
602
+ };
603
+ }
604
+
605
+ return { GET };
606
+ }
607
+
608
+ /**
609
+ * Database error helpers.
610
+ */
611
+
612
+ /**
613
+ * Check whether an error is caused by a unique-constraint violation.
614
+ *
615
+ * @param {unknown} error
616
+ * @returns {boolean}
617
+ */
618
+ function isUniqueViolation(error) {
619
+ if (!error || typeof error !== 'object') return false;
620
+
621
+ const code = error.code;
622
+ if (code === '23505') return true;
623
+
624
+ const message = typeof error.message === 'string' ? error.message.toLowerCase() : '';
625
+ return message.includes('duplicate key') || message.includes('unique constraint');
626
+ }
627
+
628
+ /**
629
+ * Message Processor (SDK version)
630
+ * ReiStandard SDK v2.0.0-pre1
631
+ *
632
+ * Handles single message content generation and Web Push delivery.
633
+ * Receives its dependencies (encryption helpers, webpush, VAPID config)
634
+ * via a context object so that it stays free of process.env references.
635
+ */
636
+
637
+
638
+ /**
639
+ * @typedef {Object} ProcessorContext
640
+ * @property {Object} webpush - The web-push module instance (already VAPID-configured).
641
+ * @property {Object} vapid - { email, publicKey, privateKey }
642
+ * @property {import('../adapters/interface.js').DbAdapter} db
643
+ */
644
+
645
+ /**
646
+ * Process a single database task row: decrypt → generate content → push.
647
+ *
648
+ * @param {import('../adapters/interface.js').TaskRow} task
649
+ * @param {ProcessorContext} ctx
650
+ * @param {string} [providedMasterKey]
651
+ * @returns {Promise<{ success: boolean, messagesSent: number, error?: string }>}
652
+ */
653
+ async function processSingleMessage(task, ctx, providedMasterKey) {
654
+ try {
655
+ const masterKey = providedMasterKey || ctx.masterKey;
656
+ if (!masterKey) {
657
+ return { success: false, messagesSent: 0, error: 'TENANT_MASTER_KEY_MISSING' };
658
+ }
659
+
660
+ const userKey = deriveUserEncryptionKey(task.user_id, masterKey);
661
+ const decryptedPayload = JSON.parse(decryptFromStorage(task.encrypted_payload, userKey));
662
+
663
+ let messageContent;
664
+
665
+ if (decryptedPayload.messageType === 'fixed') {
666
+ messageContent = decryptedPayload.userMessage;
667
+
668
+ } else if (decryptedPayload.messageType === 'instant') {
669
+ if (decryptedPayload.completePrompt && decryptedPayload.apiUrl && decryptedPayload.apiKey && decryptedPayload.primaryModel) {
670
+ messageContent = await _callAI(decryptedPayload);
671
+ } else if (decryptedPayload.userMessage) {
672
+ messageContent = decryptedPayload.userMessage;
673
+ } else {
674
+ throw new Error('Invalid instant message: no content source available');
675
+ }
676
+
677
+ } else if (decryptedPayload.messageType === 'prompted' || decryptedPayload.messageType === 'auto') {
678
+ messageContent = await _callAI(decryptedPayload);
679
+ } else {
680
+ throw new Error('Invalid message configuration: no content source available');
681
+ }
682
+
683
+ // Sentence splitting
684
+ const sentences = messageContent
685
+ .split(/([。!?!?]+)/)
686
+ .reduce((acc, part, i, arr) => {
687
+ if (i % 2 === 0 && part.trim()) {
688
+ const punctuation = arr[i + 1] || '';
689
+ acc.push(part.trim() + punctuation);
690
+ }
691
+ return acc;
692
+ }, [])
693
+ .filter(s => s.length > 0);
694
+
695
+ const messages = sentences.length > 0 ? sentences : [messageContent];
696
+
697
+ if (!ctx.vapid.email || !ctx.vapid.publicKey || !ctx.vapid.privateKey) {
698
+ throw new Error('VAPID configuration missing - push notifications cannot be sent');
699
+ }
700
+
701
+ const pushSubscription = decryptedPayload.pushSubscription;
702
+
703
+ for (let i = 0; i < messages.length; i++) {
704
+ const notificationPayload = {
705
+ title: `来自 ${decryptedPayload.contactName}`,
706
+ message: messages[i],
707
+ contactName: decryptedPayload.contactName,
708
+ messageId: `msg_${randomUUID()}_${task.id || 'instant'}_${i}`,
709
+ messageIndex: i + 1,
710
+ totalMessages: messages.length,
711
+ messageType: decryptedPayload.messageType,
712
+ messageSubtype: decryptedPayload.messageSubtype || 'chat',
713
+ taskId: task.id || null,
714
+ timestamp: new Date().toISOString(),
715
+ source: decryptedPayload.messageType === 'instant' ? 'instant' : 'scheduled',
716
+ avatarUrl: decryptedPayload.avatarUrl || null,
717
+ metadata: decryptedPayload.metadata || {}
718
+ };
719
+
720
+ await ctx.webpush.sendNotification(pushSubscription, JSON.stringify(notificationPayload));
721
+
722
+ if (i < messages.length - 1) {
723
+ await new Promise(resolve => setTimeout(resolve, 1500));
724
+ }
725
+ }
726
+
727
+ return { success: true, messagesSent: messages.length };
728
+
729
+ } catch (error) {
730
+ return { success: false, messagesSent: 0, error: error.message };
731
+ }
732
+ }
733
+
734
+ /**
735
+ * Process a single message identified by UUID (used for instant type).
736
+ *
737
+ * @param {string} uuid
738
+ * @param {ProcessorContext} ctx
739
+ * @param {number} [maxRetries=2]
740
+ * @param {string} [userId]
741
+ * @param {string} [providedMasterKey]
742
+ * @returns {Promise<{ success: boolean, messagesSent?: number, retriesUsed?: number, error?: Object }>}
743
+ */
744
+ async function processMessagesByUuid(uuid, ctx, maxRetries = 2, userId, providedMasterKey) {
745
+ let retryCount = 0;
746
+ const masterKey = providedMasterKey || ctx.masterKey;
747
+
748
+ if (!masterKey) {
749
+ return {
750
+ success: false,
751
+ error: { code: 'TENANT_MASTER_KEY_MISSING', message: '租户主密钥不存在或配置异常' }
752
+ };
753
+ }
754
+
755
+ while (retryCount <= maxRetries) {
756
+ let task;
757
+ try {
758
+ task = userId
759
+ ? await ctx.db.getTaskByUuid(uuid, userId)
760
+ : await ctx.db.getTaskByUuidOnly(uuid);
761
+ } catch (error) {
762
+ if (retryCount < maxRetries) {
763
+ retryCount++;
764
+ await new Promise(resolve => setTimeout(resolve, 1000 * retryCount));
765
+ continue;
766
+ }
767
+
768
+ return {
769
+ success: false,
770
+ error: { code: 'INTERNAL_ERROR', message: error.message, retriesAttempted: retryCount }
771
+ };
772
+ }
773
+
774
+ if (!task) {
775
+ return { success: false, error: { code: 'TASK_NOT_FOUND', message: '任务不存在或已处理' } };
776
+ }
777
+
778
+ const result = await processSingleMessage(task, ctx, masterKey);
779
+
780
+ if (!result.success) {
781
+ if (retryCount < maxRetries) {
782
+ retryCount++;
783
+ await new Promise(resolve => setTimeout(resolve, 1000 * retryCount));
784
+ continue;
785
+ }
786
+
787
+ try {
788
+ await ctx.db.updateTaskById(task.id, { status: 'failed', retry_count: retryCount });
789
+ } catch (_updateError) {
790
+ // best-effort status update; keep original processing error as primary signal
791
+ }
792
+
793
+ return {
794
+ success: false,
795
+ error: { code: 'PROCESSING_ERROR', message: result.error, retriesAttempted: retryCount }
796
+ };
797
+ }
798
+
799
+ try {
800
+ await ctx.db.deleteTaskById(task.id);
801
+ } catch (error) {
802
+ try {
803
+ await ctx.db.updateTaskById(task.id, { status: 'sent', retry_count: 0 });
804
+ } catch (_markSentError) {
805
+ // best effort: avoid re-sending if storage mutation partially fails
806
+ }
807
+
808
+ return {
809
+ success: false,
810
+ error: {
811
+ code: 'POST_SEND_CLEANUP_FAILED',
812
+ message: '消息已发送,但任务清理失败',
813
+ details: { error: error.message }
814
+ }
815
+ };
816
+ }
817
+
818
+ return { success: true, messagesSent: result.messagesSent, retriesUsed: retryCount };
819
+ }
820
+ }
821
+
822
+ /**
823
+ * Call an OpenAI-compatible API.
824
+ * @private
825
+ */
826
+ async function _callAI(payload) {
827
+ const aiResponse = await fetch(payload.apiUrl, {
828
+ method: 'POST',
829
+ headers: {
830
+ 'Content-Type': 'application/json',
831
+ 'Authorization': `Bearer ${payload.apiKey}`
832
+ },
833
+ body: JSON.stringify({
834
+ model: payload.primaryModel,
835
+ messages: [{ role: 'user', content: payload.completePrompt }],
836
+ max_tokens: 500,
837
+ temperature: 0.8
838
+ }),
839
+ signal: AbortSignal.timeout(300000)
840
+ });
841
+
842
+ if (!aiResponse.ok) {
843
+ throw new Error(`AI API error: ${aiResponse.status} ${aiResponse.statusText}`);
844
+ }
845
+
846
+ const aiData = await aiResponse.json();
847
+ return aiData.choices[0].message.content.trim();
848
+ }
849
+
850
+ /**
851
+ * Handler: schedule-message
852
+ * ReiStandard SDK v2.0.0-pre1
853
+ *
854
+ * @param {Object} ctx - Server context.
855
+ * @returns {{ POST: function }}
856
+ */
857
+
858
+
859
+ function createScheduleMessageHandler(ctx) {
860
+ async function POST(headers, body) {
861
+ const tenantResult = await ctx.tenantManager.resolveTenant(headers);
862
+ if (!tenantResult.ok) {
863
+ return tenantResult.error;
864
+ }
865
+
866
+ const tenantCtx = tenantResult.context;
867
+ const db = tenantCtx.db;
868
+ const masterKey = tenantCtx.masterKey;
869
+ const isEncrypted = getHeader(headers, 'x-payload-encrypted') === 'true';
870
+ const encryptionVersion = getHeader(headers, 'x-encryption-version');
871
+ const userId = getHeader(headers, 'x-user-id');
872
+
873
+ if (!isEncrypted) {
874
+ return { status: 400, body: { success: false, error: { code: 'ENCRYPTION_REQUIRED', message: '请求体必须加密' } } };
875
+ }
876
+ if (!userId) {
877
+ return { status: 400, body: { success: false, error: { code: 'USER_ID_REQUIRED', message: '缺少用户标识符' } } };
878
+ }
879
+ if (!isValidUUIDv4(userId)) {
880
+ return { status: 400, body: { success: false, error: { code: 'INVALID_USER_ID_FORMAT', message: 'X-User-Id 必须是 UUID v4 格式' } } };
881
+ }
882
+ if (encryptionVersion !== '1') {
883
+ return { status: 400, body: { success: false, error: { code: 'UNSUPPORTED_ENCRYPTION_VERSION', message: '加密版本不支持' } } };
884
+ }
885
+
886
+ // Decrypt request body
887
+ const parsedBody = parseEncryptedBody(body);
888
+ if (!parsedBody.ok) {
889
+ return { status: 400, body: { success: false, error: parsedBody.error } };
890
+ }
891
+
892
+ const encryptedBody = parsedBody.data;
893
+
894
+ let payload;
895
+ try {
896
+ const userKey = deriveUserEncryptionKey(userId, masterKey);
897
+ payload = decryptPayload(encryptedBody, userKey);
898
+ } catch (error) {
899
+ if (error instanceof SyntaxError) {
900
+ return { status: 400, body: { success: false, error: { code: 'INVALID_PAYLOAD_FORMAT', message: '解密后的数据不是有效 JSON' } } };
901
+ }
902
+
903
+ const message = typeof error.message === 'string' ? error.message : '';
904
+ if (message.includes('auth') || message.includes('Unsupported state')) {
905
+ return { status: 400, body: { success: false, error: { code: 'DECRYPTION_FAILED', message: '请求体解密失败' } } };
906
+ }
907
+
908
+ return { status: 400, body: { success: false, error: { code: 'DECRYPTION_FAILED', message: '请求体解密失败' } } };
909
+ }
910
+
911
+ if (!isPlainObject(payload)) {
912
+ return { status: 400, body: { success: false, error: { code: 'INVALID_PAYLOAD_FORMAT', message: '解密后的数据必须是 JSON 对象' } } };
913
+ }
914
+
915
+ // Validate
916
+ const validationResult = validateScheduleMessagePayload(payload);
917
+ if (!validationResult.valid) {
918
+ return { status: 400, body: { success: false, error: { code: validationResult.errorCode, message: validationResult.errorMessage, details: validationResult.details } } };
919
+ }
920
+
921
+ const taskUuid = payload.uuid || randomUUID();
922
+ const userKey = deriveUserEncryptionKey(userId, masterKey);
923
+
924
+ const fullTaskData = {
925
+ contactName: payload.contactName,
926
+ avatarUrl: payload.avatarUrl || null,
927
+ messageType: payload.messageType,
928
+ messageSubtype: payload.messageSubtype || 'chat',
929
+ userMessage: payload.userMessage || null,
930
+ firstSendTime: payload.firstSendTime,
931
+ recurrenceType: payload.recurrenceType || 'none',
932
+ apiUrl: payload.apiUrl || null,
933
+ apiKey: payload.apiKey || null,
934
+ primaryModel: payload.primaryModel || null,
935
+ completePrompt: payload.completePrompt || null,
936
+ pushSubscription: payload.pushSubscription,
937
+ metadata: payload.metadata || {}
938
+ };
939
+
940
+ const encryptedPayload = encryptForStorage(JSON.stringify(fullTaskData), userKey);
941
+
942
+ // Instant type: check VAPID before creating the task to avoid orphaned rows
943
+ if (payload.messageType === 'instant') {
944
+ if (!ctx.vapid.email || !ctx.vapid.publicKey || !ctx.vapid.privateKey) {
945
+ return {
946
+ status: 500,
947
+ body: {
948
+ success: false,
949
+ error: {
950
+ code: 'VAPID_CONFIG_ERROR',
951
+ message: 'VAPID 配置缺失,无法发送即时消息',
952
+ details: {
953
+ missingKeys: [
954
+ !ctx.vapid.email && 'VAPID_EMAIL',
955
+ !ctx.vapid.publicKey && 'NEXT_PUBLIC_VAPID_PUBLIC_KEY',
956
+ !ctx.vapid.privateKey && 'VAPID_PRIVATE_KEY'
957
+ ].filter(Boolean)
958
+ }
959
+ }
960
+ }
961
+ };
962
+ }
963
+ }
964
+
965
+ // Insert into database
966
+ let dbResult;
967
+ try {
968
+ dbResult = await db.createTask({
969
+ user_id: userId,
970
+ uuid: taskUuid,
971
+ encrypted_payload: encryptedPayload,
972
+ next_send_at: payload.firstSendTime,
973
+ message_type: payload.messageType
974
+ });
975
+ } catch (error) {
976
+ if (isUniqueViolation(error)) {
977
+ return {
978
+ status: 409,
979
+ body: {
980
+ success: false,
981
+ error: {
982
+ code: 'TASK_UUID_CONFLICT',
983
+ message: '任务 UUID 已存在,请使用新的 uuid 重新提交'
984
+ }
985
+ }
986
+ };
987
+ }
988
+ throw error;
989
+ }
990
+
991
+ if (!dbResult) {
992
+ return { status: 500, body: { success: false, error: { code: 'TASK_CREATE_FAILED', message: '创建任务失败' } } };
993
+ }
994
+
995
+ // Instant type: send immediately
996
+ if (payload.messageType === 'instant') {
997
+ try {
998
+ const sendResult = await processMessagesByUuid(taskUuid, {
999
+ ...ctx,
1000
+ db,
1001
+ masterKey
1002
+ }, 2, userId, masterKey);
1003
+
1004
+ if (!sendResult.success) {
1005
+ return { status: 500, body: { success: false, error: { code: 'MESSAGE_SEND_FAILED', message: '消息发送失败', details: sendResult.error } } };
1006
+ }
1007
+
1008
+ return {
1009
+ status: 200,
1010
+ body: {
1011
+ success: true,
1012
+ data: {
1013
+ uuid: taskUuid,
1014
+ contactName: payload.contactName,
1015
+ messagesSent: sendResult.messagesSent,
1016
+ sentAt: new Date().toISOString(),
1017
+ status: 'sent',
1018
+ retriesUsed: sendResult.retriesUsed || 0
1019
+ }
1020
+ }
1021
+ };
1022
+ } catch (error) {
1023
+ return { status: 500, body: { success: false, error: { code: 'MESSAGE_SEND_FAILED', message: '消息发送失败', details: { error: error.message } } } };
1024
+ }
1025
+ }
1026
+
1027
+ // Non-instant: return scheduled response
1028
+ return {
1029
+ status: 201,
1030
+ body: {
1031
+ success: true,
1032
+ data: {
1033
+ id: dbResult.id,
1034
+ uuid: dbResult.uuid,
1035
+ contactName: payload.contactName,
1036
+ nextSendAt: dbResult.next_send_at,
1037
+ status: dbResult.status,
1038
+ createdAt: dbResult.created_at
1039
+ }
1040
+ }
1041
+ };
1042
+ }
1043
+
1044
+ return { POST };
1045
+ }
1046
+
1047
+ /**
1048
+ * Handler: send-notifications
1049
+ * ReiStandard SDK v2.0.0-pre1
1050
+ *
1051
+ * @param {Object} ctx - Server context.
1052
+ * @returns {{ POST: function }}
1053
+ */
1054
+
1055
+
1056
+ function createSendNotificationsHandler(ctx) {
1057
+ async function POST(urlOrHeaders, maybeHeaders) {
1058
+ const url = typeof urlOrHeaders === 'string' ? urlOrHeaders : '';
1059
+ const headers = maybeHeaders || (typeof urlOrHeaders === 'object' ? urlOrHeaders : {});
1060
+
1061
+ const tenantResult = await ctx.tenantManager.resolveTenant(headers, {
1062
+ allowCronToken: true,
1063
+ url
1064
+ });
1065
+ if (!tenantResult.ok) {
1066
+ return tenantResult.error;
1067
+ }
1068
+
1069
+ const tenantCtx = tenantResult.context;
1070
+ const db = tenantCtx.db;
1071
+ const masterKey = tenantCtx.masterKey;
1072
+
1073
+ if (!ctx.vapid.email || !ctx.vapid.publicKey || !ctx.vapid.privateKey) {
1074
+ return {
1075
+ status: 500,
1076
+ body: {
1077
+ success: false,
1078
+ error: {
1079
+ code: 'VAPID_CONFIG_ERROR',
1080
+ message: 'VAPID 配置缺失,无法发送推送通知',
1081
+ details: {
1082
+ missingKeys: [
1083
+ !ctx.vapid.email && 'VAPID_EMAIL',
1084
+ !ctx.vapid.publicKey && 'NEXT_PUBLIC_VAPID_PUBLIC_KEY',
1085
+ !ctx.vapid.privateKey && 'VAPID_PRIVATE_KEY'
1086
+ ].filter(Boolean)
1087
+ }
1088
+ }
1089
+ }
1090
+ };
1091
+ }
1092
+
1093
+ const startTime = Date.now();
1094
+ const tasks = await db.getPendingTasks(50);
1095
+
1096
+ const MAX_CONCURRENT = 8;
1097
+ const results = {
1098
+ totalTasks: tasks.length,
1099
+ successCount: 0,
1100
+ failedCount: 0,
1101
+ deletedOnceOffTasks: 0,
1102
+ updatedRecurringTasks: 0,
1103
+ failedTasks: []
1104
+ };
1105
+
1106
+ async function handleDeliveryFailure(task, reason) {
1107
+ results.failedCount++;
1108
+
1109
+ try {
1110
+ if (task.retry_count >= 3) {
1111
+ await db.updateTaskById(task.id, { status: 'failed' });
1112
+ results.failedTasks.push({ taskId: task.id, reason, retryCount: task.retry_count, status: 'permanently_failed' });
1113
+ } else {
1114
+ const nextRetryTime = new Date(Date.now() + (task.retry_count + 1) * 2 * 60 * 1000);
1115
+ await db.updateTaskById(task.id, { next_send_at: nextRetryTime.toISOString(), retry_count: task.retry_count + 1 });
1116
+ results.failedTasks.push({ taskId: task.id, reason, retryCount: task.retry_count + 1, nextRetryAt: nextRetryTime.toISOString() });
1117
+ }
1118
+ } catch (updateError) {
1119
+ results.failedTasks.push({
1120
+ taskId: task.id,
1121
+ reason,
1122
+ status: 'retry_update_failed',
1123
+ updateError: updateError.message
1124
+ });
1125
+ }
1126
+ }
1127
+
1128
+ async function handlePostSendPersistenceFailure(task, reason) {
1129
+ results.failedCount++;
1130
+
1131
+ let markedSent = false;
1132
+ try {
1133
+ await db.updateTaskById(task.id, { status: 'sent', retry_count: 0 });
1134
+ markedSent = true;
1135
+ } catch (_markSentError) {
1136
+ markedSent = false;
1137
+ }
1138
+
1139
+ results.failedTasks.push({
1140
+ taskId: task.id,
1141
+ reason,
1142
+ status: markedSent ? 'post_send_cleanup_failed_marked_sent' : 'post_send_cleanup_failed',
1143
+ messageDelivered: true
1144
+ });
1145
+ }
1146
+
1147
+ async function processTask(task) {
1148
+ let sendResult;
1149
+ try {
1150
+ sendResult = await processSingleMessage(task, {
1151
+ ...ctx,
1152
+ db,
1153
+ masterKey
1154
+ }, masterKey);
1155
+ } catch (error) {
1156
+ await handleDeliveryFailure(task, error.message || '消息发送失败');
1157
+ return;
1158
+ }
1159
+
1160
+ if (!sendResult.success) {
1161
+ await handleDeliveryFailure(task, sendResult.error || '消息发送失败');
1162
+ return;
1163
+ }
1164
+
1165
+ try {
1166
+ const userKey = deriveUserEncryptionKey(task.user_id, masterKey);
1167
+ const decryptedPayload = JSON.parse(decryptFromStorage(task.encrypted_payload, userKey));
1168
+
1169
+ if (decryptedPayload.recurrenceType === 'none') {
1170
+ await db.deleteTaskById(task.id);
1171
+ results.deletedOnceOffTasks++;
1172
+ } else {
1173
+ let nextSendAt;
1174
+ const currentSendAt = new Date(task.next_send_at);
1175
+ if (decryptedPayload.recurrenceType === 'daily') {
1176
+ nextSendAt = new Date(currentSendAt.getTime() + 24 * 60 * 60 * 1000);
1177
+ } else if (decryptedPayload.recurrenceType === 'weekly') {
1178
+ nextSendAt = new Date(currentSendAt.getTime() + 7 * 24 * 60 * 60 * 1000);
1179
+ }
1180
+ await db.updateTaskById(task.id, { next_send_at: nextSendAt.toISOString(), retry_count: 0 });
1181
+ results.updatedRecurringTasks++;
1182
+ }
1183
+
1184
+ results.successCount++;
1185
+ } catch (error) {
1186
+ await handlePostSendPersistenceFailure(task, error.message || '发送后状态更新失败');
1187
+ }
1188
+ }
1189
+
1190
+ // Dynamic task pool
1191
+ const taskQueue = [...tasks];
1192
+ const processing = [];
1193
+
1194
+ while (taskQueue.length > 0 || processing.length > 0) {
1195
+ while (processing.length < MAX_CONCURRENT && taskQueue.length > 0) {
1196
+ const task = taskQueue.shift();
1197
+ const promise = processTask(task);
1198
+ processing.push(promise);
1199
+ promise.finally(() => {
1200
+ const index = processing.indexOf(promise);
1201
+ if (index > -1) processing.splice(index, 1);
1202
+ });
1203
+ }
1204
+ if (processing.length > 0) {
1205
+ await Promise.race(processing);
1206
+ }
1207
+ }
1208
+
1209
+ // Cleanup old tasks
1210
+ await db.cleanupOldTasks(7);
1211
+
1212
+ const executionTime = Date.now() - startTime;
1213
+
1214
+ return {
1215
+ status: 200,
1216
+ body: {
1217
+ success: true,
1218
+ data: {
1219
+ totalTasks: results.totalTasks,
1220
+ successCount: results.successCount,
1221
+ failedCount: results.failedCount,
1222
+ processedAt: new Date().toISOString(),
1223
+ executionTime,
1224
+ details: {
1225
+ deletedOnceOffTasks: results.deletedOnceOffTasks,
1226
+ updatedRecurringTasks: results.updatedRecurringTasks,
1227
+ failedTasks: results.failedTasks
1228
+ }
1229
+ }
1230
+ }
1231
+ };
1232
+ }
1233
+
1234
+ return { POST };
1235
+ }
1236
+
1237
+ /**
1238
+ * Handler: update-message
1239
+ * ReiStandard SDK v2.0.0-pre1
1240
+ *
1241
+ * @param {Object} ctx - Server context.
1242
+ * @returns {{ PUT: function }}
1243
+ */
1244
+
1245
+
1246
+ function createUpdateMessageHandler(ctx) {
1247
+ async function PUT(url, headers, body) {
1248
+ const tenantResult = await ctx.tenantManager.resolveTenant(headers, { url });
1249
+ if (!tenantResult.ok) {
1250
+ return tenantResult.error;
1251
+ }
1252
+
1253
+ const tenantCtx = tenantResult.context;
1254
+ const db = tenantCtx.db;
1255
+ const masterKey = tenantCtx.masterKey;
1256
+ const u = new URL(url, 'https://dummy');
1257
+ const taskUuid = u.searchParams.get('id');
1258
+
1259
+ if (!taskUuid) {
1260
+ return { status: 400, body: { success: false, error: { code: 'TASK_ID_REQUIRED', message: '缺少任务ID' } } };
1261
+ }
1262
+
1263
+ const userId = getHeader(headers, 'x-user-id');
1264
+ if (!userId) {
1265
+ return { status: 400, body: { success: false, error: { code: 'USER_ID_REQUIRED', message: '缺少用户标识符' } } };
1266
+ }
1267
+ if (!isValidUUIDv4(userId)) {
1268
+ return { status: 400, body: { success: false, error: { code: 'INVALID_USER_ID_FORMAT', message: 'X-User-Id 必须是 UUID v4 格式' } } };
1269
+ }
1270
+
1271
+ const isEncrypted = getHeader(headers, 'x-payload-encrypted') === 'true';
1272
+ const encryptionVersion = getHeader(headers, 'x-encryption-version');
1273
+
1274
+ if (!isEncrypted) {
1275
+ return { status: 400, body: { success: false, error: { code: 'ENCRYPTION_REQUIRED', message: '请求体必须加密' } } };
1276
+ }
1277
+
1278
+ if (encryptionVersion !== '1') {
1279
+ return { status: 400, body: { success: false, error: { code: 'UNSUPPORTED_ENCRYPTION_VERSION', message: '加密版本不支持' } } };
1280
+ }
1281
+
1282
+ const parsedBody = parseEncryptedBody(body);
1283
+ if (!parsedBody.ok) {
1284
+ return { status: 400, body: { success: false, error: parsedBody.error } };
1285
+ }
1286
+
1287
+ const encryptedBody = parsedBody.data;
1288
+ const userKey = deriveUserEncryptionKey(userId, masterKey);
1289
+ let updates;
1290
+
1291
+ try {
1292
+ updates = decryptPayload(encryptedBody, userKey);
1293
+ } catch (_error) {
1294
+ return { status: 400, body: { success: false, error: { code: 'DECRYPTION_FAILED', message: '请求体解密失败' } } };
1295
+ }
1296
+
1297
+ if (!isPlainObject(updates)) {
1298
+ return { status: 400, body: { success: false, error: { code: 'INVALID_UPDATE_DATA', message: '更新数据格式错误' } } };
1299
+ }
1300
+
1301
+ if (updates.nextSendAt && !isValidISO8601(updates.nextSendAt)) {
1302
+ return { status: 400, body: { success: false, error: { code: 'INVALID_UPDATE_DATA', message: '更新数据格式错误', details: { invalidFields: ['nextSendAt'] } } } };
1303
+ }
1304
+
1305
+ if (updates.recurrenceType && !['none', 'daily', 'weekly'].includes(updates.recurrenceType)) {
1306
+ return { status: 400, body: { success: false, error: { code: 'INVALID_UPDATE_DATA', message: '更新数据格式错误', details: { invalidFields: ['recurrenceType'] } } } };
1307
+ }
1308
+
1309
+ // Fetch existing task
1310
+ const existingTask = await db.getTaskByUuid(taskUuid, userId);
1311
+
1312
+ if (!existingTask) {
1313
+ const taskStatus = await db.getTaskStatus(taskUuid, userId);
1314
+ if (!taskStatus) {
1315
+ return { status: 404, body: { success: false, error: { code: 'TASK_NOT_FOUND', message: '指定的任务不存在或已被删除' } } };
1316
+ }
1317
+ return { status: 409, body: { success: false, error: { code: 'TASK_ALREADY_COMPLETED', message: '任务已完成或已失败,无法更新' } } };
1318
+ }
1319
+
1320
+ const existingData = JSON.parse(decryptFromStorage(existingTask.encrypted_payload, userKey));
1321
+
1322
+ const updatedData = {
1323
+ ...existingData,
1324
+ ...(updates.completePrompt && { completePrompt: updates.completePrompt }),
1325
+ ...(updates.userMessage && { userMessage: updates.userMessage }),
1326
+ ...(updates.recurrenceType && { recurrenceType: updates.recurrenceType }),
1327
+ ...(updates.avatarUrl && { avatarUrl: updates.avatarUrl }),
1328
+ ...(updates.metadata && { metadata: updates.metadata })
1329
+ };
1330
+
1331
+ const encryptedPayload = encryptForStorage(JSON.stringify(updatedData), userKey);
1332
+ const extraFields = updates.nextSendAt ? { next_send_at: updates.nextSendAt } : undefined;
1333
+
1334
+ const result = await db.updateTaskByUuid(taskUuid, userId, encryptedPayload, extraFields);
1335
+
1336
+ if (!result) {
1337
+ return { status: 409, body: { success: false, error: { code: 'UPDATE_CONFLICT', message: '任务更新失败,任务可能已被修改或删除' } } };
1338
+ }
1339
+
1340
+ return {
1341
+ status: 200,
1342
+ body: {
1343
+ success: true,
1344
+ data: {
1345
+ uuid: taskUuid,
1346
+ updatedFields: Object.keys(updates),
1347
+ updatedAt: result.updated_at
1348
+ }
1349
+ }
1350
+ };
1351
+ }
1352
+
1353
+ return { PUT };
1354
+ }
1355
+
1356
+ /**
1357
+ * Handler: cancel-message
1358
+ * ReiStandard SDK v2.0.0-pre1
1359
+ *
1360
+ * @param {Object} ctx - Server context.
1361
+ * @returns {{ DELETE: function }}
1362
+ */
1363
+
1364
+
1365
+ function createCancelMessageHandler(ctx) {
1366
+ async function DELETE(url, headers) {
1367
+ const tenantResult = await ctx.tenantManager.resolveTenant(headers, { url });
1368
+ if (!tenantResult.ok) {
1369
+ return tenantResult.error;
1370
+ }
1371
+
1372
+ const db = tenantResult.context.db;
1373
+ const u = new URL(url, 'https://dummy');
1374
+ const taskUuid = u.searchParams.get('id');
1375
+
1376
+ if (!taskUuid) {
1377
+ return { status: 400, body: { success: false, error: { code: 'TASK_ID_REQUIRED', message: '缺少任务ID' } } };
1378
+ }
1379
+
1380
+ const userId = getHeader(headers, 'x-user-id');
1381
+ if (!userId) {
1382
+ return { status: 400, body: { success: false, error: { code: 'USER_ID_REQUIRED', message: '缺少用户标识符' } } };
1383
+ }
1384
+ if (!isValidUUIDv4(userId)) {
1385
+ return { status: 400, body: { success: false, error: { code: 'INVALID_USER_ID_FORMAT', message: 'X-User-Id 必须是 UUID v4 格式' } } };
1386
+ }
1387
+
1388
+ const deleted = await db.deleteTaskByUuid(taskUuid, userId);
1389
+
1390
+ if (!deleted) {
1391
+ return {
1392
+ status: 404,
1393
+ body: { success: false, error: { code: 'TASK_NOT_FOUND', message: '指定的任务不存在或已被删除' } }
1394
+ };
1395
+ }
1396
+
1397
+ return {
1398
+ status: 200,
1399
+ body: {
1400
+ success: true,
1401
+ data: { uuid: taskUuid, message: '任务已成功取消', deletedAt: new Date().toISOString() }
1402
+ }
1403
+ };
1404
+ }
1405
+
1406
+ return { DELETE };
1407
+ }
1408
+
1409
+ /**
1410
+ * Handler: messages
1411
+ * ReiStandard SDK v2.0.0-pre1
1412
+ *
1413
+ * @param {Object} ctx - Server context.
1414
+ * @returns {{ GET: function }}
1415
+ */
1416
+
1417
+
1418
+ function createMessagesHandler(ctx) {
1419
+ async function GET(url, headers) {
1420
+ const tenantResult = await ctx.tenantManager.resolveTenant(headers, { url });
1421
+ if (!tenantResult.ok) {
1422
+ return tenantResult.error;
1423
+ }
1424
+
1425
+ const tenantCtx = tenantResult.context;
1426
+ const db = tenantCtx.db;
1427
+ const masterKey = tenantCtx.masterKey;
1428
+ const userId = getHeader(headers, 'x-user-id');
1429
+
1430
+ if (!userId) {
1431
+ return {
1432
+ status: 400,
1433
+ body: { success: false, error: { code: 'USER_ID_REQUIRED', message: '必须提供 X-User-Id 请求头' } }
1434
+ };
1435
+ }
1436
+ if (!isValidUUIDv4(userId)) {
1437
+ return {
1438
+ status: 400,
1439
+ body: { success: false, error: { code: 'INVALID_USER_ID_FORMAT', message: 'X-User-Id 必须是 UUID v4 格式' } }
1440
+ };
1441
+ }
1442
+
1443
+ const u = new URL(url, 'https://dummy');
1444
+ const status = u.searchParams.get('status') || 'all';
1445
+ const limit = Math.min(parseInt(u.searchParams.get('limit') || '20', 10), 100);
1446
+ const offset = parseInt(u.searchParams.get('offset') || '0', 10);
1447
+
1448
+ if (isNaN(limit) || limit < 1) {
1449
+ return { status: 400, body: { success: false, error: { code: 'INVALID_PARAMETERS', message: 'limit 参数无效,必须为正整数' } } };
1450
+ }
1451
+
1452
+ if (isNaN(offset) || offset < 0) {
1453
+ return { status: 400, body: { success: false, error: { code: 'INVALID_PARAMETERS', message: 'offset 参数无效,必须为非负整数' } } };
1454
+ }
1455
+
1456
+ const { tasks, total } = await db.listTasks(userId, { status, limit, offset });
1457
+
1458
+ const userKey = deriveUserEncryptionKey(userId, masterKey);
1459
+
1460
+ const decryptedTasks = tasks.map(task => {
1461
+ const decrypted = JSON.parse(decryptFromStorage(task.encrypted_payload, userKey));
1462
+ return {
1463
+ id: task.id,
1464
+ uuid: task.uuid,
1465
+ contactName: decrypted.contactName,
1466
+ messageType: task.message_type,
1467
+ messageSubtype: decrypted.messageSubtype,
1468
+ nextSendAt: task.next_send_at,
1469
+ recurrenceType: decrypted.recurrenceType,
1470
+ status: task.status,
1471
+ retryCount: task.retry_count,
1472
+ createdAt: task.created_at,
1473
+ updatedAt: task.updated_at
1474
+ };
1475
+ });
1476
+
1477
+ const responsePayload = {
1478
+ tasks: decryptedTasks,
1479
+ pagination: { total, limit, offset, hasMore: offset + limit < total }
1480
+ };
1481
+ const encryptedResponse = encryptPayload(responsePayload, userKey);
1482
+
1483
+ return {
1484
+ status: 200,
1485
+ body: {
1486
+ success: true,
1487
+ encrypted: true,
1488
+ version: 1,
1489
+ data: encryptedResponse
1490
+ }
1491
+ };
1492
+ }
1493
+
1494
+ return { GET };
1495
+ }
1496
+
1497
+ const inMemoryNamespaces = new Map();
1498
+
1499
+ function base64UrlEncode$1(input) {
1500
+ return Buffer.from(input)
1501
+ .toString('base64')
1502
+ .replace(/\+/g, '-')
1503
+ .replace(/\//g, '_')
1504
+ .replace(/=+$/g, '');
1505
+ }
1506
+
1507
+ function base64UrlDecode$1(input) {
1508
+ const normalized = input
1509
+ .replace(/-/g, '+')
1510
+ .replace(/_/g, '/');
1511
+ const padLength = (4 - (normalized.length % 4)) % 4;
1512
+ return Buffer.from(normalized + '='.repeat(padLength), 'base64');
1513
+ }
1514
+
1515
+ function getKekBuffer(kek) {
1516
+ const value = String(kek || '').trim();
1517
+ if (!value) {
1518
+ throw new Error('[rei-standard-amsg-server] tenant.kek is required');
1519
+ }
1520
+ return createHash('sha256').update(value).digest();
1521
+ }
1522
+
1523
+ function encryptConfig(config, kekBuffer) {
1524
+ const iv = randomBytes(12);
1525
+ const cipher = createCipheriv('aes-256-gcm', kekBuffer, iv);
1526
+ const plaintext = Buffer.from(JSON.stringify(config), 'utf8');
1527
+ const ciphertext = Buffer.concat([cipher.update(plaintext), cipher.final()]);
1528
+ const authTag = cipher.getAuthTag();
1529
+
1530
+ return `v1.${base64UrlEncode$1(iv)}.${base64UrlEncode$1(authTag)}.${base64UrlEncode$1(ciphertext)}`;
1531
+ }
1532
+
1533
+ function decryptConfig(encrypted, kekBuffer) {
1534
+ const parts = String(encrypted || '').split('.');
1535
+ if (parts.length !== 4 || parts[0] !== 'v1') {
1536
+ throw new Error('INVALID_TENANT_CONFIG');
1537
+ }
1538
+
1539
+ const iv = base64UrlDecode$1(parts[1]);
1540
+ const authTag = base64UrlDecode$1(parts[2]);
1541
+ const ciphertext = base64UrlDecode$1(parts[3]);
1542
+
1543
+ const decipher = createDecipheriv('aes-256-gcm', kekBuffer, iv);
1544
+ decipher.setAuthTag(authTag);
1545
+ const plaintext = Buffer.concat([decipher.update(ciphertext), decipher.final()]).toString('utf8');
1546
+ return JSON.parse(plaintext);
1547
+ }
1548
+
1549
+ function createInMemoryStore(namespace) {
1550
+ if (!inMemoryNamespaces.has(namespace)) {
1551
+ inMemoryNamespaces.set(namespace, new Map());
1552
+ }
1553
+
1554
+ const namespaceMap = inMemoryNamespaces.get(namespace);
1555
+
1556
+ return {
1557
+ async get(key) {
1558
+ return namespaceMap.has(key) ? namespaceMap.get(key) : null;
1559
+ },
1560
+ async set(key, value) {
1561
+ namespaceMap.set(key, value);
1562
+ },
1563
+ async delete(key) {
1564
+ namespaceMap.delete(key);
1565
+ }
1566
+ };
1567
+ }
1568
+
1569
+ async function resolveBlobStore(namespace) {
1570
+ if (globalThis.__REI_BLOB_STORE__ && typeof globalThis.__REI_BLOB_STORE__.get === 'function') {
1571
+ return globalThis.__REI_BLOB_STORE__;
1572
+ }
1573
+
1574
+ try {
1575
+ const blobModule = await import('@netlify/blobs');
1576
+ const getStore = blobModule.getStore || blobModule.default?.getStore;
1577
+ if (typeof getStore === 'function') {
1578
+ return getStore({ name: namespace });
1579
+ }
1580
+ } catch (_error) {
1581
+ // Fall back to in-memory store for local tests / non-Netlify runtimes
1582
+ }
1583
+
1584
+ return createInMemoryStore(namespace);
1585
+ }
1586
+
1587
+ /**
1588
+ * @typedef {{
1589
+ * tenantId: string,
1590
+ * db: { driver: 'neon'|'pg', connectionString: string },
1591
+ * masterKey: string,
1592
+ * createdAt: string,
1593
+ * updatedAt: string
1594
+ * }} TenantConfig
1595
+ */
1596
+
1597
+ /**
1598
+ * @param {{ namespace?: string, kek: string }} options
1599
+ */
1600
+ function createTenantBlobStore(options) {
1601
+ const namespace = String(options.namespace).trim() || 'rei-tenants';
1602
+ const kekBuffer = getKekBuffer(options.kek);
1603
+
1604
+ function getTenantKey(tenantId) {
1605
+ return `tenant/${tenantId}`;
1606
+ }
1607
+
1608
+ return {
1609
+ async getTenantConfig(tenantId) {
1610
+ const store = await resolveBlobStore(namespace);
1611
+ const encrypted = await store.get(getTenantKey(tenantId), { type: 'text' });
1612
+ if (!encrypted) return null;
1613
+ return decryptConfig(encrypted, kekBuffer);
1614
+ },
1615
+
1616
+ async setTenantConfig(config) {
1617
+ const store = await resolveBlobStore(namespace);
1618
+ const encrypted = encryptConfig(config, kekBuffer);
1619
+ await store.set(getTenantKey(config.tenantId), encrypted);
1620
+ },
1621
+
1622
+ async deleteTenantConfig(tenantId) {
1623
+ const store = await resolveBlobStore(namespace);
1624
+ await store.delete(getTenantKey(tenantId));
1625
+ }
1626
+ };
1627
+ }
1628
+
1629
+ function base64UrlEncode(input) {
1630
+ return Buffer.from(input)
1631
+ .toString('base64')
1632
+ .replace(/\+/g, '-')
1633
+ .replace(/\//g, '_')
1634
+ .replace(/=+$/g, '');
1635
+ }
1636
+
1637
+ function base64UrlDecode(input) {
1638
+ const normalized = input
1639
+ .replace(/-/g, '+')
1640
+ .replace(/_/g, '/');
1641
+ const padLength = (4 - (normalized.length % 4)) % 4;
1642
+ return Buffer.from(normalized + '='.repeat(padLength), 'base64');
1643
+ }
1644
+
1645
+ function sign(input, secret) {
1646
+ return base64UrlEncode(createHmac('sha256', secret).update(input).digest());
1647
+ }
1648
+
1649
+ function nowEpochSeconds() {
1650
+ return Math.floor(Date.now() / 1000);
1651
+ }
1652
+
1653
+ /**
1654
+ * @typedef {'tenant'|'cron'} TokenType
1655
+ */
1656
+
1657
+ /**
1658
+ * @param {{ tenantId: string, type: TokenType, expiresInSeconds?: number }} params
1659
+ * @param {string} secret
1660
+ */
1661
+ function createTenantToken(params, secret) {
1662
+ const issuedAt = nowEpochSeconds();
1663
+ const expiresInSeconds = Number(params.expiresInSeconds || 60 * 60 * 24 * 30);
1664
+ const payload = {
1665
+ tid: params.tenantId,
1666
+ typ: params.type,
1667
+ iat: issuedAt,
1668
+ exp: issuedAt + expiresInSeconds,
1669
+ v: 1
1670
+ };
1671
+
1672
+ const header = { alg: 'HS256', typ: 'JWT' };
1673
+ const encodedHeader = base64UrlEncode(JSON.stringify(header));
1674
+ const encodedPayload = base64UrlEncode(JSON.stringify(payload));
1675
+ const signingInput = `${encodedHeader}.${encodedPayload}`;
1676
+ const signature = sign(signingInput, secret);
1677
+ return `${signingInput}.${signature}`;
1678
+ }
1679
+
1680
+ /**
1681
+ * @param {string} token
1682
+ * @param {string} secret
1683
+ * @param {{ expectedTypes?: TokenType[] }} [options]
1684
+ */
1685
+ function verifyTenantToken(token, secret, options = {}) {
1686
+ if (!token || typeof token !== 'string') {
1687
+ throw new Error('INVALID_TENANT_AUTH');
1688
+ }
1689
+
1690
+ const parts = token.split('.');
1691
+ if (parts.length !== 3) {
1692
+ throw new Error('INVALID_TENANT_AUTH');
1693
+ }
1694
+
1695
+ const [encodedHeader, encodedPayload, receivedSignature] = parts;
1696
+ const signingInput = `${encodedHeader}.${encodedPayload}`;
1697
+ const expectedSignature = sign(signingInput, secret);
1698
+
1699
+ const receivedBuffer = Buffer.from(receivedSignature);
1700
+ const expectedBuffer = Buffer.from(expectedSignature);
1701
+ if (
1702
+ receivedBuffer.length !== expectedBuffer.length ||
1703
+ !timingSafeEqual(receivedBuffer, expectedBuffer)
1704
+ ) {
1705
+ throw new Error('INVALID_TENANT_AUTH');
1706
+ }
1707
+
1708
+ let payload;
1709
+ try {
1710
+ payload = JSON.parse(base64UrlDecode(encodedPayload).toString('utf8'));
1711
+ } catch {
1712
+ throw new Error('INVALID_TENANT_AUTH');
1713
+ }
1714
+
1715
+ if (!payload || typeof payload !== 'object' || payload.v !== 1) {
1716
+ throw new Error('INVALID_TENANT_AUTH');
1717
+ }
1718
+
1719
+ if (!payload.tid || !payload.typ || !payload.exp) {
1720
+ throw new Error('INVALID_TENANT_AUTH');
1721
+ }
1722
+
1723
+ if (payload.exp <= nowEpochSeconds()) {
1724
+ throw new Error('INVALID_TENANT_AUTH');
1725
+ }
1726
+
1727
+ const expectedTypes = options.expectedTypes || [];
1728
+ if (expectedTypes.length > 0 && !expectedTypes.includes(payload.typ)) {
1729
+ throw new Error('INVALID_TENANT_AUTH');
1730
+ }
1731
+
1732
+ return payload;
1733
+ }
1734
+
1735
+ /**
1736
+ * @param {Record<string, any>} headers
1737
+ * @returns {string}
1738
+ */
1739
+ function extractBearerToken(headers = {}) {
1740
+ let authorization = '';
1741
+ for (const [key, value] of Object.entries(headers || {})) {
1742
+ if (String(key).toLowerCase() === 'authorization') {
1743
+ authorization = String(value || '').trim();
1744
+ break;
1745
+ }
1746
+ }
1747
+ if (!authorization.toLowerCase().startsWith('bearer ')) {
1748
+ return '';
1749
+ }
1750
+ return authorization.slice(7).trim();
1751
+ }
1752
+
1753
+ function fingerprint(masterKey) {
1754
+ return createHash('sha256').update(masterKey).digest('hex').slice(0, 16);
1755
+ }
1756
+
1757
+ function sanitizeDbConfig(driver, connectionString) {
1758
+ const normalizedDriver = String(driver || '').trim();
1759
+ const normalizedConnectionString = String(connectionString || '').trim();
1760
+
1761
+ if (!['neon', 'pg'].includes(normalizedDriver)) {
1762
+ throw new Error('INVALID_DRIVER');
1763
+ }
1764
+ if (!normalizedConnectionString) {
1765
+ throw new Error('INVALID_DATABASE_URL');
1766
+ }
1767
+
1768
+ return {
1769
+ driver: normalizedDriver,
1770
+ connectionString: normalizedConnectionString
1771
+ };
1772
+ }
1773
+
1774
+ function parseTokenFromUrl(url) {
1775
+ if (!url || typeof url !== 'string') {
1776
+ return '';
1777
+ }
1778
+
1779
+ try {
1780
+ const parsed = new URL(url, 'https://dummy.local');
1781
+ return String(parsed.searchParams.get('token') || '').trim();
1782
+ } catch {
1783
+ return '';
1784
+ }
1785
+ }
1786
+
1787
+ /**
1788
+ * @param {{
1789
+ * tenantStore: ReturnType<import('./blob-store.js').createTenantBlobStore>,
1790
+ * tokenSigningKey: string,
1791
+ * publicBaseUrl?: string
1792
+ * }} options
1793
+ */
1794
+ function createTenantContextManager(options) {
1795
+ const tenantStore = options.tenantStore;
1796
+ const tokenSigningKey = String(options.tokenSigningKey || '').trim();
1797
+ const publicBaseUrl = String(options.publicBaseUrl || '').replace(/\/$/, '');
1798
+ const adapterFactory = options.adapterFactory || createAdapter;
1799
+ const adapterCache = new Map();
1800
+
1801
+ if (!tokenSigningKey) {
1802
+ throw new Error('[rei-standard-amsg-server] tenant.tokenSigningKey is required');
1803
+ }
1804
+
1805
+ async function getOrCreateAdapter(dbConfig) {
1806
+ const cacheKey = `${dbConfig.driver}:${dbConfig.connectionString}`;
1807
+ if (!adapterCache.has(cacheKey)) {
1808
+ const adapter = await adapterFactory(dbConfig);
1809
+ adapterCache.set(cacheKey, adapter);
1810
+ }
1811
+ return adapterCache.get(cacheKey);
1812
+ }
1813
+
1814
+ async function initializeTenant({ driver, connectionString, tenantId: providedTenantId }) {
1815
+ const dbConfig = sanitizeDbConfig(driver, connectionString);
1816
+ const tenantId = String(providedTenantId || randomUUID()).trim();
1817
+
1818
+ const existing = await tenantStore.getTenantConfig(tenantId);
1819
+ if (existing) {
1820
+ throw new Error('TENANT_ALREADY_INITIALIZED');
1821
+ }
1822
+
1823
+ const adapter = await getOrCreateAdapter(dbConfig);
1824
+ await adapter.initSchema();
1825
+
1826
+ const masterKey = randomBytes(32).toString('hex');
1827
+ const now = new Date().toISOString();
1828
+
1829
+ await tenantStore.setTenantConfig({
1830
+ tenantId,
1831
+ db: dbConfig,
1832
+ masterKey,
1833
+ createdAt: now,
1834
+ updatedAt: now
1835
+ });
1836
+
1837
+ const tenantToken = createTenantToken({ tenantId, type: 'tenant' }, tokenSigningKey);
1838
+ const cronToken = createTenantToken({ tenantId, type: 'cron' }, tokenSigningKey);
1839
+
1840
+ return {
1841
+ tenantId,
1842
+ masterKeyFingerprint: fingerprint(masterKey),
1843
+ tenantToken,
1844
+ cronToken,
1845
+ cronWebhookUrl: publicBaseUrl ? `${publicBaseUrl}/api/v1/send-notifications?token=${cronToken}` : ''
1846
+ };
1847
+ }
1848
+
1849
+ async function resolveTenant(headers, options = {}) {
1850
+ const allowCronToken = options.allowCronToken === true;
1851
+ const url = options.url || '';
1852
+
1853
+ const bearerToken = extractBearerToken(headers);
1854
+ const tokenFromQuery = allowCronToken ? parseTokenFromUrl(url) : '';
1855
+ const token = bearerToken || tokenFromQuery;
1856
+
1857
+ if (!token) {
1858
+ return {
1859
+ ok: false,
1860
+ error: {
1861
+ status: 401,
1862
+ body: { success: false, error: { code: 'INVALID_TENANT_AUTH', message: '缺少租户鉴权信息' } }
1863
+ }
1864
+ };
1865
+ }
1866
+
1867
+ let payload;
1868
+ try {
1869
+ payload = verifyTenantToken(token, tokenSigningKey, {
1870
+ expectedTypes: allowCronToken ? ['cron'] : ['tenant']
1871
+ });
1872
+ } catch (_error) {
1873
+ return {
1874
+ ok: false,
1875
+ error: {
1876
+ status: 401,
1877
+ body: { success: false, error: { code: 'INVALID_TENANT_AUTH', message: '租户令牌无效或已过期' } }
1878
+ }
1879
+ };
1880
+ }
1881
+
1882
+ const tenantConfig = await tenantStore.getTenantConfig(payload.tid);
1883
+ if (!tenantConfig) {
1884
+ return {
1885
+ ok: false,
1886
+ error: {
1887
+ status: 401,
1888
+ body: { success: false, error: { code: 'INVALID_TENANT_AUTH', message: '租户配置不存在或已失效' } }
1889
+ }
1890
+ };
1891
+ }
1892
+
1893
+ const adapter = await getOrCreateAdapter(tenantConfig.db);
1894
+
1895
+ return {
1896
+ ok: true,
1897
+ context: {
1898
+ tenantId: tenantConfig.tenantId,
1899
+ tokenType: payload.typ,
1900
+ db: adapter,
1901
+ masterKey: tenantConfig.masterKey
1902
+ }
1903
+ };
1904
+ }
1905
+
1906
+ return {
1907
+ initializeTenant,
1908
+ resolveTenant
1909
+ };
1910
+ }
1911
+
1912
+ /**
1913
+ * ReiStandard Server SDK Entry Point
1914
+ * v2.0.0-pre1
1915
+ *
1916
+ * Usage:
1917
+ * import { createReiServer } from '@rei-standard/amsg-server';
1918
+ *
1919
+ * const rei = await createReiServer({
1920
+ * vapid: {
1921
+ * email: process.env.VAPID_EMAIL,
1922
+ * publicKey: process.env.NEXT_PUBLIC_VAPID_PUBLIC_KEY,
1923
+ * privateKey: process.env.VAPID_PRIVATE_KEY,
1924
+ * },
1925
+ * tenant: {
1926
+ * blobNamespace: 'rei-tenants',
1927
+ * kek: process.env.TENANT_CONFIG_KEK,
1928
+ * tokenSigningKey: process.env.TENANT_TOKEN_SIGNING_KEY,
1929
+ * initSecret: process.env.INIT_SECRET,
1930
+ * publicBaseUrl: process.env.PUBLIC_BASE_URL
1931
+ * }
1932
+ * });
1933
+ */
1934
+
1935
+
1936
+ function normalizeVapidSubject(email) {
1937
+ const trimmedEmail = String(email || '').trim();
1938
+ if (!trimmedEmail) return '';
1939
+ return /^mailto:/i.test(trimmedEmail) ? trimmedEmail : `mailto:${trimmedEmail}`;
1940
+ }
1941
+
1942
+ /**
1943
+ * @typedef {Object} VapidConfig
1944
+ * @property {string} [email] - VAPID contact email (e.g. mailto:…).
1945
+ * @property {string} [publicKey] - VAPID public key.
1946
+ * @property {string} [privateKey] - VAPID private key.
1947
+ */
1948
+
1949
+ /**
1950
+ * @typedef {Object} TenantServerConfig
1951
+ * @property {string} [blobNamespace] - Netlify Blob namespace.
1952
+ * @property {string} kek - KEK used to encrypt tenant config in blobs.
1953
+ * @property {string} tokenSigningKey - HMAC key used to sign tenant/cron tokens.
1954
+ * @property {string} [initSecret] - Optional secret for /init-tenant bootstrap endpoint.
1955
+ * @property {string} [publicBaseUrl] - Optional base URL for generated cron webhook.
1956
+ * @property {(db: {driver:'neon'|'pg', connectionString:string}) => Promise<any>} [adapterFactory]
1957
+ * Optional adapter factory override (mainly for tests).
1958
+ */
1959
+
1960
+ /**
1961
+ * @typedef {Object} ReiServerConfig
1962
+ * @property {VapidConfig} [vapid] - VAPID keys for Web Push.
1963
+ * @property {TenantServerConfig} tenant - Tenant config & auth settings.
1964
+ */
1965
+
1966
+ /**
1967
+ * @typedef {Object} ReiHandlers
1968
+ * @property {{ POST: function }} initTenant
1969
+ * @property {{ GET: function }} getUserKey
1970
+ * @property {{ POST: function }} scheduleMessage
1971
+ * @property {{ POST: function }} sendNotifications
1972
+ * @property {{ PUT: function }} updateMessage
1973
+ * @property {{ DELETE: function }} cancelMessage
1974
+ * @property {{ GET: function }} messages
1975
+ */
1976
+
1977
+ /**
1978
+ * @typedef {Object} ReiServer
1979
+ * @property {ReiHandlers} handlers - Standard API route handler objects.
1980
+ */
1981
+
1982
+ /**
1983
+ * Initialise the ReiStandard server.
1984
+ *
1985
+ * @param {ReiServerConfig} config
1986
+ * @returns {Promise<ReiServer>}
1987
+ */
1988
+ async function createReiServer(config) {
1989
+ if (!config) throw new Error('[rei-standard-amsg-server] config is required');
1990
+ if (!config.tenant) throw new Error('[rei-standard-amsg-server] tenant config is required');
1991
+
1992
+ // web-push is a hard dependency for ReiStandard server features
1993
+ let webpushModule;
1994
+ try {
1995
+ const webpushImport = await import('web-push');
1996
+ webpushModule = webpushImport.default || webpushImport;
1997
+ } catch (_err) {
1998
+ throw new Error(
1999
+ '[rei-standard-amsg-server] web-push is required. Install it with: npm install web-push'
2000
+ );
2001
+ }
2002
+
2003
+ const vapid = config.vapid || {};
2004
+
2005
+ if (vapid.email && vapid.publicKey && vapid.privateKey) {
2006
+ webpushModule.setVapidDetails(
2007
+ normalizeVapidSubject(vapid.email),
2008
+ vapid.publicKey,
2009
+ vapid.privateKey
2010
+ );
2011
+ }
2012
+
2013
+ const tenantStore = createTenantBlobStore({
2014
+ namespace: config.tenant.blobNamespace || 'rei-tenants',
2015
+ kek: config.tenant.kek
2016
+ });
2017
+
2018
+ const tenantManager = createTenantContextManager({
2019
+ tenantStore,
2020
+ tokenSigningKey: config.tenant.tokenSigningKey,
2021
+ publicBaseUrl: config.tenant.publicBaseUrl,
2022
+ adapterFactory: config.tenant.adapterFactory
2023
+ });
2024
+
2025
+ const initSecret = String(config.tenant.initSecret || '').trim();
2026
+
2027
+ const ctx = {
2028
+ vapid: {
2029
+ email: vapid.email || '',
2030
+ publicKey: vapid.publicKey || '',
2031
+ privateKey: vapid.privateKey || ''
2032
+ },
2033
+ webpush: webpushModule,
2034
+ tenant: {
2035
+ initSecret
2036
+ },
2037
+ tenantManager
2038
+ };
2039
+
2040
+ return {
2041
+ handlers: {
2042
+ initTenant: createInitTenantHandler(ctx),
2043
+ getUserKey: createGetUserKeyHandler(ctx),
2044
+ scheduleMessage: createScheduleMessageHandler(ctx),
2045
+ sendNotifications: createSendNotificationsHandler(ctx),
2046
+ updateMessage: createUpdateMessageHandler(ctx),
2047
+ cancelMessage: createCancelMessageHandler(ctx),
2048
+ messages: createMessagesHandler(ctx)
2049
+ }
2050
+ };
2051
+ }
2052
+
2053
+ export { createAdapter, createReiServer, createTenantToken, decryptFromStorage, decryptPayload, deriveUserEncryptionKey, encryptForStorage, isValidISO8601, isValidUUID, isValidUUIDv4, isValidUrl, validateScheduleMessagePayload, verifyTenantToken };