@tgoliveira/outpost 1.2.1 → 2.0.0
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/AGENTS.md +172 -18
- package/README.md +17 -12
- package/dist/adapters/drizzle/index.cjs +194 -15
- package/dist/adapters/drizzle/index.cjs.map +1 -1
- package/dist/adapters/drizzle/index.d.cts +124 -7
- package/dist/adapters/drizzle/index.d.ts +124 -7
- package/dist/adapters/drizzle/index.js +194 -15
- package/dist/adapters/drizzle/index.js.map +1 -1
- package/dist/adapters/index.cjs +148 -38
- package/dist/adapters/index.cjs.map +1 -1
- package/dist/adapters/index.d.cts +21 -13
- package/dist/adapters/index.d.ts +21 -13
- package/dist/adapters/index.js +149 -39
- package/dist/adapters/index.js.map +1 -1
- package/dist/admin/index.cjs +10 -3
- package/dist/admin/index.cjs.map +1 -1
- package/dist/admin/index.d.cts +7 -7
- package/dist/admin/index.d.ts +7 -7
- package/dist/admin/index.js +10 -3
- package/dist/admin/index.js.map +1 -1
- package/dist/{fake-BY6t7UXb.d.cts → fake-B6OIEdod.d.ts} +6 -4
- package/dist/{fake-en-oOdg0.d.ts → fake-CpQc9p0N.d.cts} +6 -4
- package/dist/http/index.cjs.map +1 -1
- package/dist/http/index.d.cts +6 -6
- package/dist/http/index.d.ts +6 -6
- package/dist/http/index.js.map +1 -1
- package/dist/{index-c6caPsUG.d.ts → index-B4F7euCt.d.cts} +53 -21
- package/dist/{index-BO0GiZmP.d.cts → index-Cn1YsmGe.d.ts} +53 -21
- package/dist/index.cjs +509 -146
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +17 -15
- package/dist/index.d.ts +17 -15
- package/dist/index.js +509 -148
- package/dist/index.js.map +1 -1
- package/dist/modules/ui/index.cjs +38 -21
- package/dist/modules/ui/index.cjs.map +1 -1
- package/dist/modules/ui/index.js +38 -21
- package/dist/modules/ui/index.js.map +1 -1
- package/dist/modules/ui/pages/admin/admin-config-page.cjs +39 -20
- package/dist/modules/ui/pages/admin/admin-config-page.cjs.map +1 -1
- package/dist/modules/ui/pages/admin/admin-config-page.d.cts +23 -1
- package/dist/modules/ui/pages/admin/admin-config-page.d.ts +23 -1
- package/dist/modules/ui/pages/admin/admin-config-page.js +38 -20
- package/dist/modules/ui/pages/admin/admin-config-page.js.map +1 -1
- package/dist/modules/ui/pages/admin/admin-panel-page.cjs +1 -1
- package/dist/modules/ui/pages/admin/admin-panel-page.js +1 -1
- package/dist/modules/ui/pages/index.cjs +38 -21
- package/dist/modules/ui/pages/index.cjs.map +1 -1
- package/dist/modules/ui/pages/index.js +38 -21
- package/dist/modules/ui/pages/index.js.map +1 -1
- package/dist/{outpost-client-BItbgqIo.d.ts → outpost-client-BX3SsOFb.d.ts} +50 -21
- package/dist/{outpost-client-BlVf4gjo.d.cts → outpost-client-DhQgZY16.d.cts} +50 -21
- package/dist/react/index.cjs +38 -21
- package/dist/react/index.cjs.map +1 -1
- package/dist/react/index.js +38 -21
- package/dist/react/index.js.map +1 -1
- package/dist/repositories-DJYu4nGV.d.ts +322 -0
- package/dist/repositories-sMN6RHZJ.d.cts +322 -0
- package/dist/{services-CfTEsetF.d.ts → services-DZwZjDn_.d.cts} +9 -3
- package/dist/{services-CQINhAGo.d.cts → services-PoM2bxjP.d.ts} +9 -3
- package/dist/{template-DxI_p2Ny.d.cts → template-Dl1_ciRo.d.ts} +24 -4
- package/dist/{template-CREUq7bB.d.ts → template-Dny_7Ymi.d.cts} +24 -4
- package/dist/testing/index.cjs +200 -15
- package/dist/testing/index.cjs.map +1 -1
- package/dist/testing/index.d.cts +26 -7
- package/dist/testing/index.d.ts +26 -7
- package/dist/testing/index.js +200 -15
- package/dist/testing/index.js.map +1 -1
- package/dist/{webhook-kp6CiXk-.d.cts → webhook-B158Vi6p.d.cts} +20 -4
- package/dist/{webhook-kp6CiXk-.d.ts → webhook-B158Vi6p.d.ts} +20 -4
- package/dist/workers/index.cjs +471 -85
- package/dist/workers/index.cjs.map +1 -1
- package/dist/workers/index.d.cts +5 -5
- package/dist/workers/index.d.ts +5 -5
- package/dist/workers/index.js +471 -85
- package/dist/workers/index.js.map +1 -1
- package/package.json +6 -3
- package/dist/repositories-CHIOFGn3.d.cts +0 -182
- package/dist/repositories-WyhvxzyY.d.ts +0 -182
package/dist/index.cjs
CHANGED
|
@@ -22,6 +22,16 @@ function nextAttemptAt(attempts, config, jitter, now) {
|
|
|
22
22
|
return new Date(now.getTime() + backoffMs(attempts, config, jitter));
|
|
23
23
|
}
|
|
24
24
|
|
|
25
|
+
// src/domain/provider-failure.ts
|
|
26
|
+
function classifyProviderFailure(err) {
|
|
27
|
+
if (typeof err !== "object" || err === null) return void 0;
|
|
28
|
+
const errorClass = err.errorClass;
|
|
29
|
+
const code = err.code;
|
|
30
|
+
if (errorClass === "permanent" && code === "provider_permanent") return "permanent";
|
|
31
|
+
if (errorClass === "transient" && code === "provider_transient") return "transient";
|
|
32
|
+
return void 0;
|
|
33
|
+
}
|
|
34
|
+
|
|
25
35
|
// src/domain/errors.ts
|
|
26
36
|
var OutpostError = class extends Error {
|
|
27
37
|
code;
|
|
@@ -79,7 +89,7 @@ var ProviderError = class _ProviderError extends OutpostError {
|
|
|
79
89
|
}
|
|
80
90
|
};
|
|
81
91
|
function isTransient(err) {
|
|
82
|
-
return err
|
|
92
|
+
return classifyProviderFailure(err) === "transient";
|
|
83
93
|
}
|
|
84
94
|
|
|
85
95
|
// src/application/pipeline/sanitize.ts
|
|
@@ -203,11 +213,7 @@ async function validateRecipient(address, config, deps) {
|
|
|
203
213
|
const cached = deps.mxCache?.get(domain, deps.nowMs);
|
|
204
214
|
let hosts = cached;
|
|
205
215
|
if (hosts === void 0) {
|
|
206
|
-
|
|
207
|
-
hosts = await deps.mxResolver.resolveMx(domain);
|
|
208
|
-
} catch {
|
|
209
|
-
hosts = [];
|
|
210
|
-
}
|
|
216
|
+
hosts = await deps.mxResolver.resolveMx(domain);
|
|
211
217
|
deps.mxCache?.set(domain, hosts, deps.nowMs);
|
|
212
218
|
}
|
|
213
219
|
if (hosts.length === 0) {
|
|
@@ -223,8 +229,20 @@ var DEFAULT_RETENTION = {
|
|
|
223
229
|
auditTtlDays: 365,
|
|
224
230
|
redactOnPurge: true,
|
|
225
231
|
webhookWindowHours: 72,
|
|
226
|
-
batchSize: 1e3
|
|
232
|
+
batchSize: 1e3,
|
|
233
|
+
batchPauseMs: 50
|
|
227
234
|
};
|
|
235
|
+
function normalizeBatchPauseMs(ms) {
|
|
236
|
+
if (!Number.isFinite(ms) || ms <= 0) return 0;
|
|
237
|
+
return ms;
|
|
238
|
+
}
|
|
239
|
+
function waitForBatchPause(ms) {
|
|
240
|
+
const pause = normalizeBatchPauseMs(ms);
|
|
241
|
+
if (pause === 0) return Promise.resolve();
|
|
242
|
+
return new Promise((resolve) => {
|
|
243
|
+
setTimeout(resolve, pause);
|
|
244
|
+
});
|
|
245
|
+
}
|
|
228
246
|
function purgeCutoff(policy, now) {
|
|
229
247
|
const ttlCutoff = now.getTime() - policy.operationalTtlDays * 24 * 60 * 60 * 1e3;
|
|
230
248
|
const windowCutoff = now.getTime() - policy.webhookWindowHours * 60 * 60 * 1e3;
|
|
@@ -279,12 +297,14 @@ var EnqueueMessage = class {
|
|
|
279
297
|
};
|
|
280
298
|
}
|
|
281
299
|
const suppressed = await deps.suppressions.isSuppressed(recipientHmac);
|
|
300
|
+
const id = deps.ids.generate();
|
|
282
301
|
const [recipientSealed, bodySealed] = await Promise.all([
|
|
283
|
-
deps.sealEncryptor.seal(to),
|
|
284
|
-
deps.sealEncryptor.seal(JSON.stringify(cleanBody))
|
|
302
|
+
deps.sealEncryptor.seal(to, { messageId: id, column: "recipient" }),
|
|
303
|
+
deps.sealEncryptor.seal(JSON.stringify(cleanBody), { messageId: id, column: "body" })
|
|
285
304
|
]);
|
|
286
305
|
const now = deps.clock.now();
|
|
287
|
-
const
|
|
306
|
+
const draft = {
|
|
307
|
+
id,
|
|
288
308
|
idempotencyKey: input.idempotencyKey,
|
|
289
309
|
recipientHmac,
|
|
290
310
|
recipientSealed,
|
|
@@ -297,12 +317,37 @@ var EnqueueMessage = class {
|
|
|
297
317
|
state: suppressed ? "suppressed" : "queued",
|
|
298
318
|
scheduledFor: input.scheduledFor ?? null,
|
|
299
319
|
nextAttemptAt: input.scheduledFor ?? now
|
|
300
|
-
}
|
|
301
|
-
|
|
302
|
-
messageId: message.id,
|
|
320
|
+
};
|
|
321
|
+
const audit = {
|
|
303
322
|
eventType: suppressed ? "suppressed" : "enqueued",
|
|
304
323
|
actor,
|
|
305
324
|
detail: suppressed ? { reason: "recipient_on_suppression_list" } : { provider }
|
|
325
|
+
};
|
|
326
|
+
if (deps.outbox.insertWithEnqueueAudit) {
|
|
327
|
+
const written = await deps.outbox.insertWithEnqueueAudit(draft, audit);
|
|
328
|
+
if (written.deduplicated) {
|
|
329
|
+
deps.telemetry.counter("outpost.enqueue.deduplicated", 1);
|
|
330
|
+
return {
|
|
331
|
+
id: written.message.id,
|
|
332
|
+
state: written.message.state,
|
|
333
|
+
idempotencyKey: written.message.idempotencyKey,
|
|
334
|
+
deduplicated: true
|
|
335
|
+
};
|
|
336
|
+
}
|
|
337
|
+
deps.telemetry.counter(suppressed ? "outpost.enqueue.suppressed" : "outpost.enqueue.queued", 1);
|
|
338
|
+
return {
|
|
339
|
+
id: written.message.id,
|
|
340
|
+
state: written.message.state,
|
|
341
|
+
idempotencyKey: written.message.idempotencyKey,
|
|
342
|
+
deduplicated: false
|
|
343
|
+
};
|
|
344
|
+
}
|
|
345
|
+
const message = await deps.outbox.insert(draft);
|
|
346
|
+
await deps.audit.append({
|
|
347
|
+
messageId: message.id,
|
|
348
|
+
eventType: audit.eventType,
|
|
349
|
+
actor: audit.actor,
|
|
350
|
+
detail: audit.detail
|
|
306
351
|
});
|
|
307
352
|
deps.telemetry.counter(suppressed ? "outpost.enqueue.suppressed" : "outpost.enqueue.queued", 1);
|
|
308
353
|
return {
|
|
@@ -374,7 +419,8 @@ function isTerminal(state) {
|
|
|
374
419
|
return TERMINAL_SET.has(state);
|
|
375
420
|
}
|
|
376
421
|
var ALLOWED_TRANSITIONS = {
|
|
377
|
-
|
|
422
|
+
// Dead-letter is `sending` → `failed`, or a `failed` webhook from `sent`.
|
|
423
|
+
queued: ["sending", "suppressed"],
|
|
378
424
|
// `sending` can fall back to `queued` on a transient error (retry).
|
|
379
425
|
sending: ["sent", "queued", "failed", "suppressed"],
|
|
380
426
|
sent: ["delivered", "bounced", "complained", "failed"],
|
|
@@ -393,6 +439,7 @@ function shouldSuppressOn(state) {
|
|
|
393
439
|
}
|
|
394
440
|
|
|
395
441
|
// src/application/ingest-webhook.ts
|
|
442
|
+
var WEBHOOK_FRESHNESS_WINDOW_MS = 3e5;
|
|
396
443
|
var IngestWebhook = class {
|
|
397
444
|
constructor(deps) {
|
|
398
445
|
this.deps = deps;
|
|
@@ -405,13 +452,29 @@ var IngestWebhook = class {
|
|
|
405
452
|
}
|
|
406
453
|
return deps.telemetry.span("outpost.webhook.ingest", { provider: providerName }, async () => {
|
|
407
454
|
const event = await provider.verifyWebhook(raw);
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
455
|
+
if (!event) {
|
|
456
|
+
return { accepted: true, messageId: null, note: "ignored" };
|
|
457
|
+
}
|
|
458
|
+
this.assertFresh(event);
|
|
459
|
+
const duplicate = await deps.webhookEvents.findByIdentity?.(identityQuery(event));
|
|
460
|
+
if (duplicate) return this.duplicateResult(event);
|
|
413
461
|
const message = await deps.outbox.findByProviderMessageId(event.providerMessageId);
|
|
414
462
|
if (!message) {
|
|
463
|
+
const settled = event.providerEventId ? null : await deps.webhookEvents.findByIdentity?.({
|
|
464
|
+
match: "settledWithoutEventId",
|
|
465
|
+
provider: event.provider,
|
|
466
|
+
providerMessageId: event.providerMessageId,
|
|
467
|
+
type: event.type
|
|
468
|
+
});
|
|
469
|
+
if (settled) {
|
|
470
|
+
return {
|
|
471
|
+
accepted: true,
|
|
472
|
+
eventType: event.type,
|
|
473
|
+
messageId: null,
|
|
474
|
+
note: "duplicate provider event"
|
|
475
|
+
};
|
|
476
|
+
}
|
|
477
|
+
await this.store(event, "pending", providerName);
|
|
415
478
|
return {
|
|
416
479
|
accepted: true,
|
|
417
480
|
eventType: event.type,
|
|
@@ -419,25 +482,110 @@ var IngestWebhook = class {
|
|
|
419
482
|
note: "no matching message for providerMessageId"
|
|
420
483
|
};
|
|
421
484
|
}
|
|
422
|
-
const
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
485
|
+
const effect = await this.applyEffects(event, message);
|
|
486
|
+
await this.store(event, effect.disposition, providerName);
|
|
487
|
+
return effect.result;
|
|
488
|
+
});
|
|
489
|
+
}
|
|
490
|
+
/**
|
|
491
|
+
* Apply pending rows for a provider message id, oldest `receivedAt` first.
|
|
492
|
+
* No freshness check. Skips the call when the repository has no list method.
|
|
493
|
+
* Does not store another row or increment `outpost.webhook.received`.
|
|
494
|
+
*/
|
|
495
|
+
async applyPending(providerMessageId) {
|
|
496
|
+
const list = this.deps.webhookEvents.listPendingByProviderMessageId;
|
|
497
|
+
if (!list) return;
|
|
498
|
+
const rows = await list.call(this.deps.webhookEvents, providerMessageId);
|
|
499
|
+
const ordered = [...rows].sort((a, b) => a.receivedAt.getTime() - b.receivedAt.getTime());
|
|
500
|
+
for (const row of ordered) {
|
|
501
|
+
if (row.disposition !== "pending") continue;
|
|
502
|
+
const message = await this.deps.outbox.findByProviderMessageId(providerMessageId);
|
|
503
|
+
if (!message) continue;
|
|
504
|
+
const effect = await this.applyEffects(row.event, message);
|
|
505
|
+
await this.deps.webhookEvents.setDisposition?.(row.id, effect.disposition);
|
|
506
|
+
}
|
|
507
|
+
}
|
|
508
|
+
/** `verifiedAt` wins. Otherwise `occurredAt`. Neither present: do not reject. */
|
|
509
|
+
assertFresh(event) {
|
|
510
|
+
const timestamp = event.verifiedAt !== void 0 ? event.verifiedAt : event.occurredAt;
|
|
511
|
+
if (timestamp === void 0) return;
|
|
512
|
+
const skew = Math.abs(this.deps.clock.now().getTime() - timestamp.getTime());
|
|
513
|
+
if (skew > WEBHOOK_FRESHNESS_WINDOW_MS) {
|
|
514
|
+
throw new WebhookVerificationError("Webhook timestamp is stale");
|
|
515
|
+
}
|
|
516
|
+
}
|
|
517
|
+
async duplicateResult(event) {
|
|
518
|
+
const message = await this.deps.outbox.findByProviderMessageId(event.providerMessageId);
|
|
519
|
+
return {
|
|
520
|
+
accepted: true,
|
|
521
|
+
eventType: event.type,
|
|
522
|
+
messageId: message?.id ?? null,
|
|
523
|
+
note: "duplicate provider event"
|
|
524
|
+
};
|
|
525
|
+
}
|
|
526
|
+
/**
|
|
527
|
+
* State change, suppression, and one audit. Disposition is the caller's
|
|
528
|
+
* to persist: `applied` after a committed effect, `rejected` when the
|
|
529
|
+
* transition is not allowed.
|
|
530
|
+
*/
|
|
531
|
+
async applyEffects(event, message) {
|
|
532
|
+
const target = webhookToState(event.type);
|
|
533
|
+
if (target === null) {
|
|
534
|
+
await this.appendAudit(event, message.id);
|
|
535
|
+
return {
|
|
536
|
+
disposition: "applied",
|
|
537
|
+
result: { accepted: true, eventType: event.type, messageId: message.id }
|
|
538
|
+
};
|
|
539
|
+
}
|
|
540
|
+
if (!canTransition(message.state, target)) {
|
|
541
|
+
return {
|
|
542
|
+
disposition: "rejected",
|
|
543
|
+
result: {
|
|
544
|
+
accepted: true,
|
|
545
|
+
eventType: event.type,
|
|
546
|
+
messageId: message.id,
|
|
547
|
+
note: "transition rejected"
|
|
548
|
+
}
|
|
549
|
+
};
|
|
550
|
+
}
|
|
551
|
+
await this.deps.outbox.updateState(message.id, { state: target });
|
|
552
|
+
if (shouldSuppressOn(target) && this.isSuppressable(event)) {
|
|
553
|
+
const reason = target === "bounced" ? "hard_bounce" : "complaint";
|
|
554
|
+
const already = await this.deps.suppressions.get(message.recipientHmac);
|
|
555
|
+
await this.deps.suppressions.add({
|
|
556
|
+
recipientHmac: message.recipientHmac,
|
|
557
|
+
reason,
|
|
558
|
+
createdBy: `provider:${event.provider}`,
|
|
559
|
+
note: `webhook ${event.type}`
|
|
439
560
|
});
|
|
440
|
-
|
|
561
|
+
if (!already) {
|
|
562
|
+
this.deps.telemetry.counter("outpost.suppression.added", 1, { reason });
|
|
563
|
+
}
|
|
564
|
+
}
|
|
565
|
+
await this.appendAudit(event, message.id);
|
|
566
|
+
return {
|
|
567
|
+
disposition: "applied",
|
|
568
|
+
result: { accepted: true, eventType: event.type, messageId: message.id }
|
|
569
|
+
};
|
|
570
|
+
}
|
|
571
|
+
async store(event, disposition, providerName) {
|
|
572
|
+
await this.deps.webhookEvents.record(event, { disposition });
|
|
573
|
+
this.deps.telemetry.counter("outpost.webhook.received", 1, {
|
|
574
|
+
provider: providerName,
|
|
575
|
+
type: event.type
|
|
576
|
+
});
|
|
577
|
+
}
|
|
578
|
+
async appendAudit(event, messageId) {
|
|
579
|
+
const detail = {
|
|
580
|
+
type: event.type,
|
|
581
|
+
occurredAt: event.occurredAt?.toISOString() ?? null
|
|
582
|
+
};
|
|
583
|
+
if (event.providerEventId) detail.providerEventId = event.providerEventId;
|
|
584
|
+
await this.deps.audit.append({
|
|
585
|
+
messageId,
|
|
586
|
+
eventType: this.auditType(event.type),
|
|
587
|
+
actor: `provider:${event.provider}`,
|
|
588
|
+
detail
|
|
441
589
|
});
|
|
442
590
|
}
|
|
443
591
|
/** A soft bounce must not suppress; only hard bounces and complaints do. */
|
|
@@ -461,6 +609,22 @@ var IngestWebhook = class {
|
|
|
461
609
|
}
|
|
462
610
|
}
|
|
463
611
|
};
|
|
612
|
+
function identityQuery(event) {
|
|
613
|
+
if (event.providerEventId) {
|
|
614
|
+
return {
|
|
615
|
+
match: "providerEvent",
|
|
616
|
+
provider: event.provider,
|
|
617
|
+
providerEventId: event.providerEventId
|
|
618
|
+
};
|
|
619
|
+
}
|
|
620
|
+
return {
|
|
621
|
+
match: "providerMessage",
|
|
622
|
+
provider: event.provider,
|
|
623
|
+
providerMessageId: event.providerMessageId,
|
|
624
|
+
type: event.type,
|
|
625
|
+
occurredAt: event.occurredAt ?? null
|
|
626
|
+
};
|
|
627
|
+
}
|
|
464
628
|
|
|
465
629
|
// src/application/manage-suppression.ts
|
|
466
630
|
var ManageSuppression = class {
|
|
@@ -645,12 +809,22 @@ var GetMessage = class {
|
|
|
645
809
|
return toView(m);
|
|
646
810
|
}
|
|
647
811
|
};
|
|
812
|
+
var DEFAULT_LIST_LIMIT = 50;
|
|
813
|
+
var MAX_LIST_LIMIT = 100;
|
|
814
|
+
function boundedListLimit(limit) {
|
|
815
|
+
if (limit === void 0 || !Number.isFinite(limit) || limit < 1) return DEFAULT_LIST_LIMIT;
|
|
816
|
+
return Math.min(Math.floor(limit), MAX_LIST_LIMIT);
|
|
817
|
+
}
|
|
648
818
|
var ListMessages = class {
|
|
649
819
|
constructor(deps) {
|
|
650
820
|
this.deps = deps;
|
|
651
821
|
}
|
|
652
822
|
async execute(query) {
|
|
653
|
-
const messages = await this.deps.outbox.list({
|
|
823
|
+
const messages = await this.deps.outbox.list({
|
|
824
|
+
...query,
|
|
825
|
+
limit: boundedListLimit(query.limit),
|
|
826
|
+
offset: query.offset ?? 0
|
|
827
|
+
});
|
|
654
828
|
return messages.map(toView);
|
|
655
829
|
}
|
|
656
830
|
};
|
|
@@ -668,7 +842,8 @@ var ReplayMessage = class {
|
|
|
668
842
|
state: "queued",
|
|
669
843
|
attempts: 0,
|
|
670
844
|
nextAttemptAt: this.deps.clock.now(),
|
|
671
|
-
lastError: null
|
|
845
|
+
lastError: null,
|
|
846
|
+
providerMessageId: null
|
|
672
847
|
});
|
|
673
848
|
await this.deps.audit.append({
|
|
674
849
|
messageId: id,
|
|
@@ -682,13 +857,26 @@ var ReplayMessage = class {
|
|
|
682
857
|
};
|
|
683
858
|
|
|
684
859
|
// src/application/dispatch-message.ts
|
|
860
|
+
function failureReason(err) {
|
|
861
|
+
if (typeof err === "object" && err !== null) {
|
|
862
|
+
const message = err.message;
|
|
863
|
+
if (typeof message === "string") return message;
|
|
864
|
+
}
|
|
865
|
+
return String(err);
|
|
866
|
+
}
|
|
685
867
|
var DispatchMessage = class {
|
|
686
868
|
constructor(deps) {
|
|
687
869
|
this.deps = deps;
|
|
688
870
|
this.mxCache = new MxCache(deps.config.domainValidation.mxCacheTtlMs ?? 36e5);
|
|
871
|
+
this.webhooks = new IngestWebhook(deps);
|
|
689
872
|
}
|
|
690
873
|
mxCache;
|
|
874
|
+
webhooks;
|
|
691
875
|
async execute(message) {
|
|
876
|
+
const claim = { updatedAt: new Date(message.updatedAt.getTime()) };
|
|
877
|
+
if (!this.deps.outbox.updateStateWhileSending) {
|
|
878
|
+
throw new Error("OutboxRepository.updateStateWhileSending is required to dispatch");
|
|
879
|
+
}
|
|
692
880
|
const { deps } = this;
|
|
693
881
|
return deps.telemetry.span(
|
|
694
882
|
"outpost.dispatch",
|
|
@@ -698,13 +886,37 @@ var DispatchMessage = class {
|
|
|
698
886
|
if (!fresh || fresh.state !== "sending") {
|
|
699
887
|
return { kind: "skipped", reason: "no longer in sending state" };
|
|
700
888
|
}
|
|
889
|
+
try {
|
|
890
|
+
await deps.audit.append({
|
|
891
|
+
messageId: fresh.id,
|
|
892
|
+
eventType: "dispatch_started",
|
|
893
|
+
actor: "system:dispatch",
|
|
894
|
+
detail: { provider: fresh.provider }
|
|
895
|
+
});
|
|
896
|
+
} catch (err) {
|
|
897
|
+
this.logWrite("dispatch_started audit failed; dispatch continues", fresh.id, err);
|
|
898
|
+
}
|
|
899
|
+
let listed;
|
|
900
|
+
try {
|
|
901
|
+
listed = await deps.suppressions.isSuppressed(fresh.recipientHmac);
|
|
902
|
+
} catch (err) {
|
|
903
|
+
return this.handleError(fresh, claim, err);
|
|
904
|
+
}
|
|
905
|
+
if (listed) return this.suppressListed(fresh, claim);
|
|
701
906
|
const provider = deps.providers.get(fresh.provider);
|
|
702
907
|
if (!provider) {
|
|
703
|
-
return this.fail(fresh, `No provider registered for "${fresh.provider}"`);
|
|
908
|
+
return this.fail(fresh, claim, `No provider registered for "${fresh.provider}"`);
|
|
704
909
|
}
|
|
910
|
+
let receipt;
|
|
705
911
|
try {
|
|
706
|
-
const to = await deps.openEncryptor.open(fresh.recipientSealed
|
|
707
|
-
|
|
912
|
+
const to = await deps.openEncryptor.open(fresh.recipientSealed, {
|
|
913
|
+
messageId: fresh.id,
|
|
914
|
+
column: "recipient"
|
|
915
|
+
});
|
|
916
|
+
const bodyJson = await deps.openEncryptor.open(fresh.bodySealed, {
|
|
917
|
+
messageId: fresh.id,
|
|
918
|
+
column: "body"
|
|
919
|
+
});
|
|
708
920
|
const body = JSON.parse(bodyJson);
|
|
709
921
|
const cleanTo = sanitizeRecipient(to, deps.config.sanitize);
|
|
710
922
|
const cleanSubject = sanitizeSubject(fresh.subject, deps.config.sanitize);
|
|
@@ -716,7 +928,7 @@ var DispatchMessage = class {
|
|
|
716
928
|
});
|
|
717
929
|
const limited = await this.checkRateLimits(fresh.provider, cleanTo);
|
|
718
930
|
if (limited) {
|
|
719
|
-
return this.requeueRateLimited(fresh);
|
|
931
|
+
return this.requeueRateLimited(fresh, claim);
|
|
720
932
|
}
|
|
721
933
|
const dispatchable = {
|
|
722
934
|
id: fresh.id,
|
|
@@ -726,91 +938,175 @@ var DispatchMessage = class {
|
|
|
726
938
|
headers: this.buildHeaders(),
|
|
727
939
|
metadata: fresh.metadata
|
|
728
940
|
};
|
|
729
|
-
|
|
730
|
-
|
|
941
|
+
receipt = await provider.send(dispatchable);
|
|
942
|
+
} catch (err) {
|
|
943
|
+
return this.handleError(fresh, claim, err);
|
|
944
|
+
}
|
|
945
|
+
const wrote = await this.commitWhileSending(
|
|
946
|
+
fresh.id,
|
|
947
|
+
{
|
|
731
948
|
state: "sent",
|
|
732
949
|
providerMessageId: receipt.providerMessageId,
|
|
733
950
|
lastError: null
|
|
734
|
-
}
|
|
951
|
+
},
|
|
952
|
+
claim,
|
|
953
|
+
true
|
|
954
|
+
);
|
|
955
|
+
if (!wrote) return { kind: "skipped", reason: "claim lost" };
|
|
956
|
+
try {
|
|
735
957
|
await deps.audit.append({
|
|
736
958
|
messageId: fresh.id,
|
|
737
959
|
eventType: "dispatch_accepted",
|
|
738
960
|
actor: `provider:${fresh.provider}`,
|
|
739
961
|
detail: { providerMessageId: receipt.providerMessageId }
|
|
740
962
|
});
|
|
741
|
-
deps.telemetry.counter("outpost.dispatch.sent", 1, { provider: fresh.provider });
|
|
742
|
-
return { kind: "sent", providerMessageId: receipt.providerMessageId };
|
|
743
963
|
} catch (err) {
|
|
744
|
-
|
|
964
|
+
this.logWrite("dispatch audit failed after sent; message stays sent", fresh.id, err);
|
|
965
|
+
}
|
|
966
|
+
try {
|
|
967
|
+
await this.webhooks.applyPending(receipt.providerMessageId);
|
|
968
|
+
} catch (err) {
|
|
969
|
+
this.logWrite("pending webhook apply failed after sent; message stays sent", fresh.id, err);
|
|
745
970
|
}
|
|
971
|
+
deps.telemetry.counter("outpost.dispatch.sent", 1, { provider: fresh.provider });
|
|
972
|
+
return { kind: "sent", providerMessageId: receipt.providerMessageId };
|
|
746
973
|
}
|
|
747
974
|
);
|
|
748
975
|
}
|
|
749
|
-
/**
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
976
|
+
/**
|
|
977
|
+
* Recipient was listed after enqueue. `sending` → `suppressed` on the
|
|
978
|
+
* stored HMAC. Do not decrypt, call the provider, or add a suppression row.
|
|
979
|
+
* A lost claim does not audit. An audit failure leaves the row suppressed.
|
|
980
|
+
*/
|
|
981
|
+
async suppressListed(message, claim) {
|
|
982
|
+
const wrote = await this.commitWhileSending(message.id, { state: "suppressed" }, claim);
|
|
983
|
+
if (!wrote) return { kind: "skipped", reason: "claim lost" };
|
|
984
|
+
try {
|
|
985
|
+
await this.deps.audit.append({
|
|
986
|
+
messageId: message.id,
|
|
987
|
+
eventType: "suppressed",
|
|
988
|
+
actor: "system:dispatch",
|
|
989
|
+
detail: { reason: "recipient_on_suppression_list" }
|
|
990
|
+
});
|
|
991
|
+
} catch (err) {
|
|
992
|
+
this.logWrite("dispatch audit failed after suppressed; message stays suppressed", message.id, err);
|
|
993
|
+
}
|
|
994
|
+
return { kind: "skipped", reason: "recipient suppressed" };
|
|
995
|
+
}
|
|
996
|
+
/** Classify a provider or pipeline error and either retry or dead-letter. */
|
|
997
|
+
async handleError(message, claim, err) {
|
|
998
|
+
const permanent = classifyProviderFailure(err) === "permanent";
|
|
999
|
+
const reason = failureReason(err);
|
|
753
1000
|
if (permanent) {
|
|
754
|
-
return this.fail(message, reason);
|
|
1001
|
+
return this.fail(message, claim, reason);
|
|
755
1002
|
}
|
|
756
1003
|
const attempts = message.attempts + 1;
|
|
757
1004
|
if (isExhausted(attempts, this.deps.config.retry)) {
|
|
758
|
-
return this.fail(message, `Retries exhausted (${attempts}): ${reason}`, attempts);
|
|
1005
|
+
return this.fail(message, claim, `Retries exhausted (${attempts}): ${reason}`, attempts);
|
|
759
1006
|
}
|
|
760
1007
|
const delay = backoffMs(attempts, this.deps.config.retry, this.deps.random());
|
|
761
1008
|
const nextAttemptAt2 = new Date(this.deps.clock.now().getTime() + delay);
|
|
762
|
-
await this.
|
|
763
|
-
|
|
764
|
-
attempts,
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
}
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
1009
|
+
const wrote = await this.commitWhileSending(
|
|
1010
|
+
message.id,
|
|
1011
|
+
{ state: "queued", attempts, nextAttemptAt: nextAttemptAt2, lastError: reason, providerMessageId: null },
|
|
1012
|
+
claim
|
|
1013
|
+
);
|
|
1014
|
+
if (!wrote) return { kind: "skipped", reason: "claim lost" };
|
|
1015
|
+
try {
|
|
1016
|
+
await this.deps.audit.append({
|
|
1017
|
+
messageId: message.id,
|
|
1018
|
+
eventType: "retry_scheduled",
|
|
1019
|
+
actor: `provider:${message.provider}`,
|
|
1020
|
+
detail: { attempts, nextAttemptAt: nextAttemptAt2.toISOString(), reason }
|
|
1021
|
+
});
|
|
1022
|
+
} catch (auditErr) {
|
|
1023
|
+
this.logWrite("retry audit failed after requeue", message.id, auditErr);
|
|
1024
|
+
}
|
|
774
1025
|
this.deps.telemetry.counter("outpost.dispatch.retry", 1, { provider: message.provider });
|
|
775
1026
|
return { kind: "retry", nextAttemptAt: nextAttemptAt2 };
|
|
776
1027
|
}
|
|
777
1028
|
/** Move to `failed` (terminal) and record in the Dead Letter Queue. */
|
|
778
|
-
async fail(message, reason, attempts) {
|
|
779
|
-
await this.
|
|
780
|
-
|
|
781
|
-
attempts: attempts ?? message.attempts,
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
|
|
785
|
-
|
|
786
|
-
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
|
|
1029
|
+
async fail(message, claim, reason, attempts) {
|
|
1030
|
+
const wrote = await this.commitWhileSending(
|
|
1031
|
+
message.id,
|
|
1032
|
+
{ state: "failed", attempts: attempts ?? message.attempts, lastError: reason },
|
|
1033
|
+
claim
|
|
1034
|
+
);
|
|
1035
|
+
if (!wrote) return { kind: "skipped", reason: "claim lost" };
|
|
1036
|
+
try {
|
|
1037
|
+
await this.deps.audit.append({
|
|
1038
|
+
messageId: message.id,
|
|
1039
|
+
eventType: "dead_lettered",
|
|
1040
|
+
actor: `provider:${message.provider}`,
|
|
1041
|
+
detail: { reason }
|
|
1042
|
+
});
|
|
1043
|
+
} catch (auditErr) {
|
|
1044
|
+
this.logWrite("dead-letter audit failed after failed", message.id, auditErr);
|
|
1045
|
+
}
|
|
790
1046
|
this.deps.telemetry.counter("outpost.dispatch.failed", 1, { provider: message.provider });
|
|
791
1047
|
return { kind: "failed", reason };
|
|
792
1048
|
}
|
|
793
1049
|
/** Re-queue without counting a failed attempt; short, jittered backoff. */
|
|
794
|
-
async requeueRateLimited(message) {
|
|
1050
|
+
async requeueRateLimited(message, claim) {
|
|
795
1051
|
const delay = 1e3 + Math.floor(this.deps.random() * 4e3);
|
|
796
1052
|
const nextAttemptAt2 = new Date(this.deps.clock.now().getTime() + delay);
|
|
797
|
-
await this.
|
|
798
|
-
|
|
799
|
-
nextAttemptAt: nextAttemptAt2
|
|
800
|
-
|
|
1053
|
+
const wrote = await this.commitWhileSending(
|
|
1054
|
+
message.id,
|
|
1055
|
+
{ state: "queued", nextAttemptAt: nextAttemptAt2, providerMessageId: null },
|
|
1056
|
+
claim
|
|
1057
|
+
);
|
|
1058
|
+
if (!wrote) return { kind: "skipped", reason: "claim lost" };
|
|
801
1059
|
this.deps.telemetry.counter("outpost.dispatch.rate_limited", 1, { provider: message.provider });
|
|
802
1060
|
return { kind: "rate_limited", nextAttemptAt: nextAttemptAt2 };
|
|
803
1061
|
}
|
|
1062
|
+
/**
|
|
1063
|
+
* Fence write. `false` means the claim no longer owns the row, or the driver
|
|
1064
|
+
* threw. Neither path is a provider retry. When the provider may already
|
|
1065
|
+
* have accepted, the log says so and the caller leaves the row alone.
|
|
1066
|
+
*/
|
|
1067
|
+
async commitWhileSending(id, patch, claim, providerMayHaveAccepted = false) {
|
|
1068
|
+
const write = this.deps.outbox.updateStateWhileSending;
|
|
1069
|
+
if (!write) {
|
|
1070
|
+
throw new Error("OutboxRepository.updateStateWhileSending is required to dispatch");
|
|
1071
|
+
}
|
|
1072
|
+
try {
|
|
1073
|
+
const wrote = await write.call(this.deps.outbox, id, patch, claim);
|
|
1074
|
+
if (!wrote && providerMayHaveAccepted) {
|
|
1075
|
+
this.deps.logger.log(
|
|
1076
|
+
"error",
|
|
1077
|
+
"provider may already have accepted; claim lost and the row was left unchanged",
|
|
1078
|
+
{ messageId: id }
|
|
1079
|
+
);
|
|
1080
|
+
}
|
|
1081
|
+
return wrote;
|
|
1082
|
+
} catch (err) {
|
|
1083
|
+
this.logWrite(
|
|
1084
|
+
providerMayHaveAccepted ? "provider may already have accepted; state write failed and the row was left unchanged" : "dispatch state write failed and the row was left unchanged",
|
|
1085
|
+
id,
|
|
1086
|
+
err
|
|
1087
|
+
);
|
|
1088
|
+
return false;
|
|
1089
|
+
}
|
|
1090
|
+
}
|
|
1091
|
+
logWrite(message, messageId, err) {
|
|
1092
|
+
this.deps.logger.log("error", message, {
|
|
1093
|
+
messageId,
|
|
1094
|
+
error: err instanceof Error ? err.message : String(err)
|
|
1095
|
+
});
|
|
1096
|
+
}
|
|
804
1097
|
async checkRateLimits(provider, to) {
|
|
805
|
-
const
|
|
806
|
-
|
|
807
|
-
|
|
808
|
-
|
|
1098
|
+
const scopes = [
|
|
1099
|
+
{ kind: "global" },
|
|
1100
|
+
{ kind: "provider", key: provider },
|
|
1101
|
+
{ kind: "recipientDomain", key: extractDomain(to) }
|
|
809
1102
|
];
|
|
810
|
-
|
|
1103
|
+
if (this.deps.rateLimiter.acquireAll) {
|
|
1104
|
+
return !await this.deps.rateLimiter.acquireAll(scopes);
|
|
1105
|
+
}
|
|
1106
|
+
const results = await Promise.all(scopes.map((scope) => this.deps.rateLimiter.acquire(scope)));
|
|
811
1107
|
return results.some((ok) => ok === false);
|
|
812
1108
|
}
|
|
813
|
-
/**
|
|
1109
|
+
/** No headers are added. List-Unsubscribe is not set. */
|
|
814
1110
|
buildHeaders() {
|
|
815
1111
|
return {};
|
|
816
1112
|
}
|
|
@@ -899,12 +1195,20 @@ var PurgeRetention = class {
|
|
|
899
1195
|
const now = deps.clock.now();
|
|
900
1196
|
const policy = deps.config.retention;
|
|
901
1197
|
const cutoff = purgeCutoff(policy, now);
|
|
1198
|
+
const pauseMs = normalizeBatchPauseMs(policy.batchPauseMs);
|
|
1199
|
+
const redactEligible = deps.outbox.redactBatchIfEligible;
|
|
1200
|
+
const deleteEligible = deps.outbox.deleteBatchIfEligible;
|
|
1201
|
+
if (typeof redactEligible !== "function" || typeof deleteEligible !== "function") {
|
|
1202
|
+
throw new Error(
|
|
1203
|
+
"OutboxRepository must implement redactBatchIfEligible and deleteBatchIfEligible. Retention throws before it writes and does not call redactBatch or deleteBatch."
|
|
1204
|
+
);
|
|
1205
|
+
}
|
|
902
1206
|
let operationalProcessed = 0;
|
|
903
1207
|
for (; ; ) {
|
|
904
1208
|
const batch = await deps.outbox.claimTerminalForPurge(cutoff, policy.batchSize);
|
|
905
1209
|
if (batch.length === 0) break;
|
|
906
1210
|
const ids = batch.map((m) => m.id);
|
|
907
|
-
const count = policy.redactOnPurge ? await deps.outbox
|
|
1211
|
+
const count = policy.redactOnPurge ? await redactEligible.call(deps.outbox, ids, cutoff) : await deleteEligible.call(deps.outbox, ids, cutoff);
|
|
908
1212
|
operationalProcessed += count;
|
|
909
1213
|
await deps.audit.append({
|
|
910
1214
|
messageId: null,
|
|
@@ -913,14 +1217,18 @@ var PurgeRetention = class {
|
|
|
913
1217
|
detail: { count, cutoff: cutoff.toISOString() }
|
|
914
1218
|
});
|
|
915
1219
|
if (batch.length < policy.batchSize) break;
|
|
1220
|
+
await waitForBatchPause(pauseMs);
|
|
916
1221
|
}
|
|
1222
|
+
const deleteWebhooks = deps.webhookEvents.deleteOlderThan;
|
|
1223
|
+
const webhooksDeleted = typeof deleteWebhooks === "function" ? await deleteWebhooks.call(deps.webhookEvents, cutoff) : 0;
|
|
917
1224
|
const auditCutoff = new Date(now.getTime() - policy.auditTtlDays * 24 * 60 * 60 * 1e3);
|
|
918
|
-
const auditDeleted = await deps.audit.purgeOlderThan(auditCutoff, policy.batchSize);
|
|
1225
|
+
const auditDeleted = await deps.audit.purgeOlderThan(auditCutoff, policy.batchSize, pauseMs);
|
|
919
1226
|
deps.telemetry.gauge("outpost.retention.operational_processed", operationalProcessed);
|
|
920
1227
|
deps.telemetry.gauge("outpost.retention.audit_deleted", auditDeleted);
|
|
921
1228
|
deps.logger.log("info", "retention cycle complete", {
|
|
922
1229
|
operationalProcessed,
|
|
923
1230
|
auditDeleted,
|
|
1231
|
+
webhooksDeleted,
|
|
924
1232
|
redacted: policy.redactOnPurge
|
|
925
1233
|
});
|
|
926
1234
|
return { operationalProcessed, auditDeleted, redacted: policy.redactOnPurge };
|
|
@@ -938,31 +1246,44 @@ var RetentionWorker = class {
|
|
|
938
1246
|
purge;
|
|
939
1247
|
running = false;
|
|
940
1248
|
timer = null;
|
|
1249
|
+
inFlight = false;
|
|
941
1250
|
async tick() {
|
|
942
1251
|
return this.purge.execute();
|
|
943
1252
|
}
|
|
944
1253
|
start() {
|
|
945
1254
|
if (this.running) return;
|
|
946
1255
|
this.running = true;
|
|
947
|
-
|
|
948
|
-
const loop = async () => {
|
|
949
|
-
if (!this.running) return;
|
|
950
|
-
try {
|
|
951
|
-
await this.tick();
|
|
952
|
-
} catch (err) {
|
|
953
|
-
this.deps.logger.log("error", "retention worker tick failed", {
|
|
954
|
-
error: err instanceof Error ? err.message : String(err)
|
|
955
|
-
});
|
|
956
|
-
} finally {
|
|
957
|
-
if (this.running) this.timer = setTimeout(loop, interval);
|
|
958
|
-
}
|
|
959
|
-
};
|
|
960
|
-
void loop();
|
|
1256
|
+
void this.runLoopTick();
|
|
961
1257
|
}
|
|
962
1258
|
stop() {
|
|
963
1259
|
this.running = false;
|
|
964
|
-
if (this.timer)
|
|
965
|
-
|
|
1260
|
+
if (this.timer !== null) {
|
|
1261
|
+
clearTimeout(this.timer);
|
|
1262
|
+
this.timer = null;
|
|
1263
|
+
}
|
|
1264
|
+
}
|
|
1265
|
+
intervalMs() {
|
|
1266
|
+
return this.options.intervalMs ?? 60 * 60 * 1e3;
|
|
1267
|
+
}
|
|
1268
|
+
async runLoopTick() {
|
|
1269
|
+
if (this.inFlight) return;
|
|
1270
|
+
if (!this.running) return;
|
|
1271
|
+
this.inFlight = true;
|
|
1272
|
+
try {
|
|
1273
|
+
await this.tick();
|
|
1274
|
+
} catch (err) {
|
|
1275
|
+
this.deps.logger.log("error", "retention worker tick failed", {
|
|
1276
|
+
error: err instanceof Error ? err.message : String(err)
|
|
1277
|
+
});
|
|
1278
|
+
} finally {
|
|
1279
|
+
this.inFlight = false;
|
|
1280
|
+
if (this.running) {
|
|
1281
|
+
this.timer = setTimeout(() => {
|
|
1282
|
+
this.timer = null;
|
|
1283
|
+
void this.runLoopTick();
|
|
1284
|
+
}, this.intervalMs());
|
|
1285
|
+
}
|
|
1286
|
+
}
|
|
966
1287
|
}
|
|
967
1288
|
};
|
|
968
1289
|
|
|
@@ -996,7 +1317,7 @@ var Outpost = class {
|
|
|
996
1317
|
send(input, opts) {
|
|
997
1318
|
return this.enqueueMessage.execute(input, opts?.actor ?? this.defaultActor);
|
|
998
1319
|
}
|
|
999
|
-
/** Fetch
|
|
1320
|
+
/** Fetch lifecycle and metadata. The body and recipient address are omitted. */
|
|
1000
1321
|
get(id) {
|
|
1001
1322
|
return this.getMessage.execute(id);
|
|
1002
1323
|
}
|
|
@@ -1055,12 +1376,20 @@ var HmacRecipientHasher = class {
|
|
|
1055
1376
|
}
|
|
1056
1377
|
};
|
|
1057
1378
|
var PLAIN_ALG = "plain";
|
|
1379
|
+
function aadBytes(context) {
|
|
1380
|
+
return Buffer.from(`${context.messageId}:${context.column}`, "utf8");
|
|
1381
|
+
}
|
|
1382
|
+
function assertKeyId(sealed, keyId) {
|
|
1383
|
+
if (sealed.keyId !== void 0 && sealed.keyId !== keyId) {
|
|
1384
|
+
throw new Error("Sealed value keyId does not match this encryptor");
|
|
1385
|
+
}
|
|
1386
|
+
}
|
|
1058
1387
|
var NoopEncryptor = class {
|
|
1059
1388
|
alg = PLAIN_ALG;
|
|
1060
|
-
async seal(plaintext) {
|
|
1389
|
+
async seal(plaintext, _context) {
|
|
1061
1390
|
return { alg: PLAIN_ALG, ciphertext: Buffer.from(plaintext, "utf8").toString("base64") };
|
|
1062
1391
|
}
|
|
1063
|
-
async open(sealed) {
|
|
1392
|
+
async open(sealed, _context) {
|
|
1064
1393
|
return Buffer.from(sealed.ciphertext, "base64").toString("utf8");
|
|
1065
1394
|
}
|
|
1066
1395
|
};
|
|
@@ -1073,9 +1402,10 @@ var AesGcmEncryptor = class {
|
|
|
1073
1402
|
}
|
|
1074
1403
|
alg = AES_ALG;
|
|
1075
1404
|
key;
|
|
1076
|
-
async seal(plaintext) {
|
|
1405
|
+
async seal(plaintext, context) {
|
|
1077
1406
|
const iv = crypto.randomBytes(12);
|
|
1078
1407
|
const cipher = crypto.createCipheriv(AES_ALG, this.key, iv);
|
|
1408
|
+
if (context) cipher.setAAD(aadBytes(context));
|
|
1079
1409
|
const ct = Buffer.concat([cipher.update(plaintext, "utf8"), cipher.final()]);
|
|
1080
1410
|
const tag = cipher.getAuthTag();
|
|
1081
1411
|
return {
|
|
@@ -1083,19 +1413,17 @@ var AesGcmEncryptor = class {
|
|
|
1083
1413
|
ciphertext: ct.toString("base64"),
|
|
1084
1414
|
iv: iv.toString("base64"),
|
|
1085
1415
|
tag: tag.toString("base64"),
|
|
1086
|
-
keyId: this.keyId
|
|
1416
|
+
keyId: this.keyId,
|
|
1417
|
+
...context ? { bound: true } : {}
|
|
1087
1418
|
};
|
|
1088
1419
|
}
|
|
1089
|
-
async open(sealed) {
|
|
1420
|
+
async open(sealed, context) {
|
|
1090
1421
|
if (sealed.alg === PLAIN_ALG) return new NoopEncryptor().open(sealed);
|
|
1091
|
-
if (
|
|
1092
|
-
|
|
1093
|
-
|
|
1094
|
-
|
|
1095
|
-
|
|
1096
|
-
decipher.final()
|
|
1097
|
-
]);
|
|
1098
|
-
return pt.toString("utf8");
|
|
1422
|
+
if (context) assertKeyId(sealed, this.keyId);
|
|
1423
|
+
if (sealed.bound && !context) {
|
|
1424
|
+
throw new Error("Sealed value is bound to a message and column");
|
|
1425
|
+
}
|
|
1426
|
+
return decryptAes(this.key, sealed, sealed.bound ? context : void 0);
|
|
1099
1427
|
}
|
|
1100
1428
|
};
|
|
1101
1429
|
var HYBRID_ALG = "hybrid-rsa-aes-256-gcm";
|
|
@@ -1108,10 +1436,11 @@ var HybridSealEncryptor = class {
|
|
|
1108
1436
|
this.keyId = keyId;
|
|
1109
1437
|
}
|
|
1110
1438
|
alg = HYBRID_ALG;
|
|
1111
|
-
async seal(plaintext) {
|
|
1439
|
+
async seal(plaintext, context) {
|
|
1112
1440
|
const dataKey = crypto.randomBytes(32);
|
|
1113
1441
|
const iv = crypto.randomBytes(12);
|
|
1114
1442
|
const cipher = crypto.createCipheriv(AES_ALG, dataKey, iv);
|
|
1443
|
+
if (context) cipher.setAAD(aadBytes(context));
|
|
1115
1444
|
const ct = Buffer.concat([cipher.update(plaintext, "utf8"), cipher.final()]);
|
|
1116
1445
|
const tag = cipher.getAuthTag();
|
|
1117
1446
|
const wrappedKey = crypto.publicEncrypt(rsaOaep(this.publicKeyPem), dataKey);
|
|
@@ -1121,7 +1450,8 @@ var HybridSealEncryptor = class {
|
|
|
1121
1450
|
iv: iv.toString("base64"),
|
|
1122
1451
|
tag: tag.toString("base64"),
|
|
1123
1452
|
wrappedKey: wrappedKey.toString("base64"),
|
|
1124
|
-
keyId: this.keyId
|
|
1453
|
+
keyId: this.keyId,
|
|
1454
|
+
...context ? { bound: true } : {}
|
|
1125
1455
|
};
|
|
1126
1456
|
}
|
|
1127
1457
|
async open() {
|
|
@@ -1131,15 +1461,20 @@ var HybridSealEncryptor = class {
|
|
|
1131
1461
|
}
|
|
1132
1462
|
};
|
|
1133
1463
|
var HybridOpenEncryptor = class {
|
|
1134
|
-
constructor(privateKeyPem) {
|
|
1464
|
+
constructor(privateKeyPem, keyId = "default") {
|
|
1135
1465
|
this.privateKeyPem = privateKeyPem;
|
|
1466
|
+
this.keyId = keyId;
|
|
1136
1467
|
}
|
|
1137
1468
|
alg = HYBRID_ALG;
|
|
1138
1469
|
async seal() {
|
|
1139
1470
|
throw new Error("HybridOpenEncryptor is read-only; use HybridSealEncryptor to seal");
|
|
1140
1471
|
}
|
|
1141
|
-
async open(sealed) {
|
|
1472
|
+
async open(sealed, context) {
|
|
1142
1473
|
if (sealed.alg === PLAIN_ALG) return new NoopEncryptor().open(sealed);
|
|
1474
|
+
if (context) assertKeyId(sealed, this.keyId);
|
|
1475
|
+
if (sealed.bound && !context) {
|
|
1476
|
+
throw new Error("Sealed value is bound to a message and column");
|
|
1477
|
+
}
|
|
1143
1478
|
if (!sealed.wrappedKey || !sealed.iv || !sealed.tag) {
|
|
1144
1479
|
throw new Error("Sealed value missing wrappedKey/iv/tag for hybrid open");
|
|
1145
1480
|
}
|
|
@@ -1147,15 +1482,20 @@ var HybridOpenEncryptor = class {
|
|
|
1147
1482
|
rsaOaep(this.privateKeyPem),
|
|
1148
1483
|
Buffer.from(sealed.wrappedKey, "base64")
|
|
1149
1484
|
);
|
|
1150
|
-
|
|
1151
|
-
decipher.setAuthTag(Buffer.from(sealed.tag, "base64"));
|
|
1152
|
-
const pt = Buffer.concat([
|
|
1153
|
-
decipher.update(Buffer.from(sealed.ciphertext, "base64")),
|
|
1154
|
-
decipher.final()
|
|
1155
|
-
]);
|
|
1156
|
-
return pt.toString("utf8");
|
|
1485
|
+
return decryptAes(dataKey, sealed, sealed.bound ? context : void 0);
|
|
1157
1486
|
}
|
|
1158
1487
|
};
|
|
1488
|
+
function decryptAes(key, sealed, context) {
|
|
1489
|
+
if (!sealed.iv || !sealed.tag) throw new Error("Sealed value missing iv/tag");
|
|
1490
|
+
const decipher = crypto.createDecipheriv(AES_ALG, key, Buffer.from(sealed.iv, "base64"));
|
|
1491
|
+
if (context) decipher.setAAD(aadBytes(context));
|
|
1492
|
+
decipher.setAuthTag(Buffer.from(sealed.tag, "base64"));
|
|
1493
|
+
const pt = Buffer.concat([
|
|
1494
|
+
decipher.update(Buffer.from(sealed.ciphertext, "base64")),
|
|
1495
|
+
decipher.final()
|
|
1496
|
+
]);
|
|
1497
|
+
return pt.toString("utf8");
|
|
1498
|
+
}
|
|
1159
1499
|
|
|
1160
1500
|
// src/adapters/rate-limit/in-memory.ts
|
|
1161
1501
|
var InMemoryRateLimiter = class {
|
|
@@ -1167,23 +1507,40 @@ var InMemoryRateLimiter = class {
|
|
|
1167
1507
|
async acquire(scope) {
|
|
1168
1508
|
const budget = this.budgetFor(scope);
|
|
1169
1509
|
if (!budget) return true;
|
|
1170
|
-
const
|
|
1510
|
+
const bucket = this.refill(`${scope.kind}:${scope.key ?? ""}`, budget, this.clock.now().getTime());
|
|
1511
|
+
if (bucket.tokens >= 1) {
|
|
1512
|
+
bucket.tokens -= 1;
|
|
1513
|
+
return true;
|
|
1514
|
+
}
|
|
1515
|
+
return false;
|
|
1516
|
+
}
|
|
1517
|
+
async acquireAll(scopes) {
|
|
1171
1518
|
const now = this.clock.now().getTime();
|
|
1172
|
-
const
|
|
1519
|
+
const ready = /* @__PURE__ */ new Map();
|
|
1520
|
+
let allowed = true;
|
|
1521
|
+
for (const scope of scopes) {
|
|
1522
|
+
const budget = this.budgetFor(scope);
|
|
1523
|
+
if (!budget) continue;
|
|
1524
|
+
const key = `${scope.kind}:${scope.key ?? ""}`;
|
|
1525
|
+
const bucket = this.refill(key, budget, now);
|
|
1526
|
+
if (bucket.tokens < 1) allowed = false;
|
|
1527
|
+
else ready.set(key, bucket);
|
|
1528
|
+
}
|
|
1529
|
+
if (!allowed) return false;
|
|
1530
|
+
for (const bucket of ready.values()) bucket.tokens -= 1;
|
|
1531
|
+
return true;
|
|
1532
|
+
}
|
|
1533
|
+
refill(key, budget, now) {
|
|
1173
1534
|
let bucket = this.buckets.get(key);
|
|
1174
1535
|
if (!bucket) {
|
|
1175
1536
|
bucket = { tokens: budget.max, lastRefill: now };
|
|
1176
1537
|
this.buckets.set(key, bucket);
|
|
1177
|
-
|
|
1178
|
-
const elapsed = now - bucket.lastRefill;
|
|
1179
|
-
bucket.tokens = Math.min(budget.max, bucket.tokens + elapsed * refillRate);
|
|
1180
|
-
bucket.lastRefill = now;
|
|
1181
|
-
}
|
|
1182
|
-
if (bucket.tokens >= 1) {
|
|
1183
|
-
bucket.tokens -= 1;
|
|
1184
|
-
return true;
|
|
1538
|
+
return bucket;
|
|
1185
1539
|
}
|
|
1186
|
-
|
|
1540
|
+
const elapsed = now - bucket.lastRefill;
|
|
1541
|
+
bucket.tokens = Math.min(budget.max, bucket.tokens + elapsed * (budget.max / budget.windowMs));
|
|
1542
|
+
bucket.lastRefill = now;
|
|
1543
|
+
return bucket;
|
|
1187
1544
|
}
|
|
1188
1545
|
budgetFor(scope) {
|
|
1189
1546
|
switch (scope.kind) {
|
|
@@ -1200,6 +1557,9 @@ var UnlimitedRateLimiter = class {
|
|
|
1200
1557
|
async acquire() {
|
|
1201
1558
|
return true;
|
|
1202
1559
|
}
|
|
1560
|
+
async acquireAll() {
|
|
1561
|
+
return true;
|
|
1562
|
+
}
|
|
1203
1563
|
};
|
|
1204
1564
|
var SystemClock = class {
|
|
1205
1565
|
now() {
|
|
@@ -1258,7 +1618,8 @@ function createOutpost(options) {
|
|
|
1258
1618
|
attachments: options.attachments,
|
|
1259
1619
|
domainValidation: options.domainValidation,
|
|
1260
1620
|
rateLimits: options.rateLimits,
|
|
1261
|
-
sendBatchSize: options.sendBatchSize
|
|
1621
|
+
sendBatchSize: options.sendBatchSize,
|
|
1622
|
+
staleSendingLeaseMs: options.staleSendingLeaseMs
|
|
1262
1623
|
});
|
|
1263
1624
|
if (options.providers.length === 0) {
|
|
1264
1625
|
throw new Error("createOutpost requires at least one provider");
|
|
@@ -1313,7 +1674,7 @@ function resolveEncryption(enc) {
|
|
|
1313
1674
|
}
|
|
1314
1675
|
case "asymmetric": {
|
|
1315
1676
|
const seal = new HybridSealEncryptor(enc.publicKey, enc.keyId);
|
|
1316
|
-
const open = enc.privateKey ? new HybridOpenEncryptor(enc.privateKey) : seal;
|
|
1677
|
+
const open = enc.privateKey ? new HybridOpenEncryptor(enc.privateKey, enc.keyId) : seal;
|
|
1317
1678
|
return { sealEncryptor: seal, openEncryptor: open };
|
|
1318
1679
|
}
|
|
1319
1680
|
}
|
|
@@ -1371,6 +1732,7 @@ exports.isKeyActive = isKeyActive;
|
|
|
1371
1732
|
exports.isTerminal = isTerminal;
|
|
1372
1733
|
exports.isTransient = isTransient;
|
|
1373
1734
|
exports.nextAttemptAt = nextAttemptAt;
|
|
1735
|
+
exports.normalizeBatchPauseMs = normalizeBatchPauseMs;
|
|
1374
1736
|
exports.purgeCutoff = purgeCutoff;
|
|
1375
1737
|
exports.resolveConfig = resolveConfig;
|
|
1376
1738
|
exports.sanitizeHeaders = sanitizeHeaders;
|
|
@@ -1382,6 +1744,7 @@ exports.toView = toView;
|
|
|
1382
1744
|
exports.validateAttachment = validateAttachment;
|
|
1383
1745
|
exports.validateRecipient = validateRecipient;
|
|
1384
1746
|
exports.validateSyntax = validateSyntax;
|
|
1747
|
+
exports.waitForBatchPause = waitForBatchPause;
|
|
1385
1748
|
exports.webhookToState = webhookToState;
|
|
1386
1749
|
//# sourceMappingURL=index.cjs.map
|
|
1387
1750
|
//# sourceMappingURL=index.cjs.map
|