@tgoliveira/outpost 1.2.2 → 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.
Files changed (77) hide show
  1. package/AGENTS.md +172 -18
  2. package/README.md +17 -12
  3. package/dist/adapters/drizzle/index.cjs +194 -15
  4. package/dist/adapters/drizzle/index.cjs.map +1 -1
  5. package/dist/adapters/drizzle/index.d.cts +124 -7
  6. package/dist/adapters/drizzle/index.d.ts +124 -7
  7. package/dist/adapters/drizzle/index.js +194 -15
  8. package/dist/adapters/drizzle/index.js.map +1 -1
  9. package/dist/adapters/index.cjs +148 -38
  10. package/dist/adapters/index.cjs.map +1 -1
  11. package/dist/adapters/index.d.cts +21 -13
  12. package/dist/adapters/index.d.ts +21 -13
  13. package/dist/adapters/index.js +149 -39
  14. package/dist/adapters/index.js.map +1 -1
  15. package/dist/admin/index.cjs +10 -3
  16. package/dist/admin/index.cjs.map +1 -1
  17. package/dist/admin/index.d.cts +7 -7
  18. package/dist/admin/index.d.ts +7 -7
  19. package/dist/admin/index.js +10 -3
  20. package/dist/admin/index.js.map +1 -1
  21. package/dist/{fake-BY6t7UXb.d.cts → fake-B6OIEdod.d.ts} +6 -4
  22. package/dist/{fake-en-oOdg0.d.ts → fake-CpQc9p0N.d.cts} +6 -4
  23. package/dist/http/index.cjs.map +1 -1
  24. package/dist/http/index.d.cts +6 -6
  25. package/dist/http/index.d.ts +6 -6
  26. package/dist/http/index.js.map +1 -1
  27. package/dist/{index-c6caPsUG.d.ts → index-B4F7euCt.d.cts} +53 -21
  28. package/dist/{index-BO0GiZmP.d.cts → index-Cn1YsmGe.d.ts} +53 -21
  29. package/dist/index.cjs +509 -146
  30. package/dist/index.cjs.map +1 -1
  31. package/dist/index.d.cts +17 -15
  32. package/dist/index.d.ts +17 -15
  33. package/dist/index.js +509 -148
  34. package/dist/index.js.map +1 -1
  35. package/dist/modules/ui/index.cjs +3 -3
  36. package/dist/modules/ui/index.cjs.map +1 -1
  37. package/dist/modules/ui/index.js +3 -3
  38. package/dist/modules/ui/index.js.map +1 -1
  39. package/dist/modules/ui/pages/admin/admin-config-page.cjs +2 -2
  40. package/dist/modules/ui/pages/admin/admin-config-page.cjs.map +1 -1
  41. package/dist/modules/ui/pages/admin/admin-config-page.js +2 -2
  42. package/dist/modules/ui/pages/admin/admin-config-page.js.map +1 -1
  43. package/dist/modules/ui/pages/admin/admin-panel-page.cjs +1 -1
  44. package/dist/modules/ui/pages/admin/admin-panel-page.js +1 -1
  45. package/dist/modules/ui/pages/index.cjs +3 -3
  46. package/dist/modules/ui/pages/index.cjs.map +1 -1
  47. package/dist/modules/ui/pages/index.js +3 -3
  48. package/dist/modules/ui/pages/index.js.map +1 -1
  49. package/dist/{outpost-client-BItbgqIo.d.ts → outpost-client-BX3SsOFb.d.ts} +50 -21
  50. package/dist/{outpost-client-BlVf4gjo.d.cts → outpost-client-DhQgZY16.d.cts} +50 -21
  51. package/dist/react/index.cjs +3 -3
  52. package/dist/react/index.cjs.map +1 -1
  53. package/dist/react/index.js +3 -3
  54. package/dist/react/index.js.map +1 -1
  55. package/dist/repositories-DJYu4nGV.d.ts +322 -0
  56. package/dist/repositories-sMN6RHZJ.d.cts +322 -0
  57. package/dist/{services-CfTEsetF.d.ts → services-DZwZjDn_.d.cts} +9 -3
  58. package/dist/{services-CQINhAGo.d.cts → services-PoM2bxjP.d.ts} +9 -3
  59. package/dist/{template-DxI_p2Ny.d.cts → template-Dl1_ciRo.d.ts} +24 -4
  60. package/dist/{template-CREUq7bB.d.ts → template-Dny_7Ymi.d.cts} +24 -4
  61. package/dist/testing/index.cjs +200 -15
  62. package/dist/testing/index.cjs.map +1 -1
  63. package/dist/testing/index.d.cts +26 -7
  64. package/dist/testing/index.d.ts +26 -7
  65. package/dist/testing/index.js +200 -15
  66. package/dist/testing/index.js.map +1 -1
  67. package/dist/{webhook-kp6CiXk-.d.cts → webhook-B158Vi6p.d.cts} +20 -4
  68. package/dist/{webhook-kp6CiXk-.d.ts → webhook-B158Vi6p.d.ts} +20 -4
  69. package/dist/workers/index.cjs +471 -85
  70. package/dist/workers/index.cjs.map +1 -1
  71. package/dist/workers/index.d.cts +5 -5
  72. package/dist/workers/index.d.ts +5 -5
  73. package/dist/workers/index.js +471 -85
  74. package/dist/workers/index.js.map +1 -1
  75. package/package.json +6 -3
  76. package/dist/repositories-CHIOFGn3.d.cts +0 -182
  77. package/dist/repositories-WyhvxzyY.d.ts +0 -182
@@ -1,7 +1,7 @@
1
- export { F as FakeEmailProvider, S as SentRecord } from '../fake-BY6t7UXb.cjs';
2
- import { E as EmailProvider, P as ProviderReceipt, R as RawWebhook, a as RateLimiter, C as Clock, c as RateLimitScope, L as Logger, b as LogLevel, T as Telemetry, I as IdGenerator } from '../services-CQINhAGo.cjs';
3
- import { D as DispatchableMessage, W as WebhookEvent, S as Sealed } from '../webhook-kp6CiXk-.cjs';
4
- import { i as RecipientHasher, E as Encryptor, R as RateLimitConfig, T as TemplateRenderer, j as RenderedTemplate, M as MxResolver } from '../template-DxI_p2Ny.cjs';
1
+ export { F as FakeEmailProvider, S as SentRecord } from '../fake-CpQc9p0N.cjs';
2
+ import { E as EmailProvider, P as ProviderReceipt, R as RawWebhook, a as RateLimiter, C as Clock, c as RateLimitScope, L as Logger, b as LogLevel, T as Telemetry, I as IdGenerator } from '../services-DZwZjDn_.cjs';
3
+ import { D as DispatchableMessage, W as WebhookEvent, S as Sealed } from '../webhook-B158Vi6p.cjs';
4
+ import { i as RecipientHasher, E as Encryptor, o as SealContext, R as RateLimitConfig, T as TemplateRenderer, j as RenderedTemplate, M as MxResolver } from '../template-Dny_7Ymi.cjs';
5
5
 
6
6
  interface SmtpProviderOptions {
7
7
  /** Stable provider key. Defaults to "smtp". Use "mailpit" for the dev box. */
@@ -15,7 +15,11 @@ interface SmtpProviderOptions {
15
15
  };
16
16
  /** Default From address (e.g. "Acme <no-reply@acme.com>"). */
17
17
  readonly from: string;
18
- /** Extra options passed straight to nodemailer.createTransport. */
18
+ /**
19
+ * Extra nodemailer options. Spread first, so `host`, `port`, `secure`, and
20
+ * `auth` from this object win. A truthy `url` or `service`, and
21
+ * `tls.rejectUnauthorized: false`, are refused.
22
+ */
19
23
  readonly transportOptions?: Record<string, unknown>;
20
24
  }
21
25
  /**
@@ -61,7 +65,7 @@ declare class ResendEmailProvider implements EmailProvider {
61
65
  private readonly baseUrl;
62
66
  constructor(opts: ResendProviderOptions);
63
67
  send(msg: DispatchableMessage): Promise<ProviderReceipt>;
64
- verifyWebhook(req: RawWebhook): Promise<WebhookEvent>;
68
+ verifyWebhook(req: RawWebhook): Promise<WebhookEvent | null>;
65
69
  }
66
70
 
67
71
  /**
@@ -86,8 +90,8 @@ declare class HmacRecipientHasher implements RecipientHasher {
86
90
  /** No-op: stores base64(plaintext). Used when encryption is disabled. */
87
91
  declare class NoopEncryptor implements Encryptor {
88
92
  readonly alg = "plain";
89
- seal(plaintext: string): Promise<Sealed>;
90
- open(sealed: Sealed): Promise<string>;
93
+ seal(plaintext: string, _context?: SealContext): Promise<Sealed>;
94
+ open(sealed: Sealed, _context?: SealContext): Promise<string>;
91
95
  }
92
96
  /** Symmetric AEAD. The 32-byte key MUST come from KMS/secrets, not the DB. */
93
97
  declare class AesGcmEncryptor implements Encryptor {
@@ -95,8 +99,8 @@ declare class AesGcmEncryptor implements Encryptor {
95
99
  readonly alg = "aes-256-gcm";
96
100
  private readonly key;
97
101
  constructor(key: Buffer, keyId?: string);
98
- seal(plaintext: string): Promise<Sealed>;
99
- open(sealed: Sealed): Promise<string>;
102
+ seal(plaintext: string, context?: SealContext): Promise<Sealed>;
103
+ open(sealed: Sealed, context?: SealContext): Promise<string>;
100
104
  }
101
105
  /**
102
106
  * Seal-only encryptor for the ingestion tier. Holds ONLY the public key:
@@ -109,7 +113,7 @@ declare class HybridSealEncryptor implements Encryptor {
109
113
  private readonly keyId;
110
114
  readonly alg = "hybrid-rsa-aes-256-gcm";
111
115
  constructor(publicKeyPem: string, keyId?: string);
112
- seal(plaintext: string): Promise<Sealed>;
116
+ seal(plaintext: string, context?: SealContext): Promise<Sealed>;
113
117
  open(): Promise<string>;
114
118
  }
115
119
  /**
@@ -118,10 +122,11 @@ declare class HybridSealEncryptor implements Encryptor {
118
122
  */
119
123
  declare class HybridOpenEncryptor implements Encryptor {
120
124
  private readonly privateKeyPem;
125
+ private readonly keyId;
121
126
  readonly alg = "hybrid-rsa-aes-256-gcm";
122
- constructor(privateKeyPem: string);
127
+ constructor(privateKeyPem: string, keyId?: string);
123
128
  seal(): Promise<Sealed>;
124
- open(sealed: Sealed): Promise<string>;
129
+ open(sealed: Sealed, context?: SealContext): Promise<string>;
125
130
  }
126
131
 
127
132
  /**
@@ -141,11 +146,14 @@ declare class InMemoryRateLimiter implements RateLimiter {
141
146
  private readonly buckets;
142
147
  constructor(config: RateLimitConfig, clock: Clock);
143
148
  acquire(scope: RateLimitScope): Promise<boolean>;
149
+ acquireAll(scopes: readonly RateLimitScope[]): Promise<boolean>;
150
+ private refill;
144
151
  private budgetFor;
145
152
  }
146
153
  /** Always allows. Used when no rate limits are configured. */
147
154
  declare class UnlimitedRateLimiter implements RateLimiter {
148
155
  acquire(): Promise<boolean>;
156
+ acquireAll(): Promise<boolean>;
149
157
  }
150
158
 
151
159
  /** Structured console logger (JSON lines). The default when none is provided. */
@@ -1,7 +1,7 @@
1
- export { F as FakeEmailProvider, S as SentRecord } from '../fake-en-oOdg0.js';
2
- import { E as EmailProvider, P as ProviderReceipt, R as RawWebhook, a as RateLimiter, C as Clock, c as RateLimitScope, L as Logger, b as LogLevel, T as Telemetry, I as IdGenerator } from '../services-CfTEsetF.js';
3
- import { D as DispatchableMessage, W as WebhookEvent, S as Sealed } from '../webhook-kp6CiXk-.js';
4
- import { i as RecipientHasher, E as Encryptor, R as RateLimitConfig, T as TemplateRenderer, j as RenderedTemplate, M as MxResolver } from '../template-CREUq7bB.js';
1
+ export { F as FakeEmailProvider, S as SentRecord } from '../fake-B6OIEdod.js';
2
+ import { E as EmailProvider, P as ProviderReceipt, R as RawWebhook, a as RateLimiter, C as Clock, c as RateLimitScope, L as Logger, b as LogLevel, T as Telemetry, I as IdGenerator } from '../services-PoM2bxjP.js';
3
+ import { D as DispatchableMessage, W as WebhookEvent, S as Sealed } from '../webhook-B158Vi6p.js';
4
+ import { i as RecipientHasher, E as Encryptor, o as SealContext, R as RateLimitConfig, T as TemplateRenderer, j as RenderedTemplate, M as MxResolver } from '../template-Dl1_ciRo.js';
5
5
 
6
6
  interface SmtpProviderOptions {
7
7
  /** Stable provider key. Defaults to "smtp". Use "mailpit" for the dev box. */
@@ -15,7 +15,11 @@ interface SmtpProviderOptions {
15
15
  };
16
16
  /** Default From address (e.g. "Acme <no-reply@acme.com>"). */
17
17
  readonly from: string;
18
- /** Extra options passed straight to nodemailer.createTransport. */
18
+ /**
19
+ * Extra nodemailer options. Spread first, so `host`, `port`, `secure`, and
20
+ * `auth` from this object win. A truthy `url` or `service`, and
21
+ * `tls.rejectUnauthorized: false`, are refused.
22
+ */
19
23
  readonly transportOptions?: Record<string, unknown>;
20
24
  }
21
25
  /**
@@ -61,7 +65,7 @@ declare class ResendEmailProvider implements EmailProvider {
61
65
  private readonly baseUrl;
62
66
  constructor(opts: ResendProviderOptions);
63
67
  send(msg: DispatchableMessage): Promise<ProviderReceipt>;
64
- verifyWebhook(req: RawWebhook): Promise<WebhookEvent>;
68
+ verifyWebhook(req: RawWebhook): Promise<WebhookEvent | null>;
65
69
  }
66
70
 
67
71
  /**
@@ -86,8 +90,8 @@ declare class HmacRecipientHasher implements RecipientHasher {
86
90
  /** No-op: stores base64(plaintext). Used when encryption is disabled. */
87
91
  declare class NoopEncryptor implements Encryptor {
88
92
  readonly alg = "plain";
89
- seal(plaintext: string): Promise<Sealed>;
90
- open(sealed: Sealed): Promise<string>;
93
+ seal(plaintext: string, _context?: SealContext): Promise<Sealed>;
94
+ open(sealed: Sealed, _context?: SealContext): Promise<string>;
91
95
  }
92
96
  /** Symmetric AEAD. The 32-byte key MUST come from KMS/secrets, not the DB. */
93
97
  declare class AesGcmEncryptor implements Encryptor {
@@ -95,8 +99,8 @@ declare class AesGcmEncryptor implements Encryptor {
95
99
  readonly alg = "aes-256-gcm";
96
100
  private readonly key;
97
101
  constructor(key: Buffer, keyId?: string);
98
- seal(plaintext: string): Promise<Sealed>;
99
- open(sealed: Sealed): Promise<string>;
102
+ seal(plaintext: string, context?: SealContext): Promise<Sealed>;
103
+ open(sealed: Sealed, context?: SealContext): Promise<string>;
100
104
  }
101
105
  /**
102
106
  * Seal-only encryptor for the ingestion tier. Holds ONLY the public key:
@@ -109,7 +113,7 @@ declare class HybridSealEncryptor implements Encryptor {
109
113
  private readonly keyId;
110
114
  readonly alg = "hybrid-rsa-aes-256-gcm";
111
115
  constructor(publicKeyPem: string, keyId?: string);
112
- seal(plaintext: string): Promise<Sealed>;
116
+ seal(plaintext: string, context?: SealContext): Promise<Sealed>;
113
117
  open(): Promise<string>;
114
118
  }
115
119
  /**
@@ -118,10 +122,11 @@ declare class HybridSealEncryptor implements Encryptor {
118
122
  */
119
123
  declare class HybridOpenEncryptor implements Encryptor {
120
124
  private readonly privateKeyPem;
125
+ private readonly keyId;
121
126
  readonly alg = "hybrid-rsa-aes-256-gcm";
122
- constructor(privateKeyPem: string);
127
+ constructor(privateKeyPem: string, keyId?: string);
123
128
  seal(): Promise<Sealed>;
124
- open(sealed: Sealed): Promise<string>;
129
+ open(sealed: Sealed, context?: SealContext): Promise<string>;
125
130
  }
126
131
 
127
132
  /**
@@ -141,11 +146,14 @@ declare class InMemoryRateLimiter implements RateLimiter {
141
146
  private readonly buckets;
142
147
  constructor(config: RateLimitConfig, clock: Clock);
143
148
  acquire(scope: RateLimitScope): Promise<boolean>;
149
+ acquireAll(scopes: readonly RateLimitScope[]): Promise<boolean>;
150
+ private refill;
144
151
  private budgetFor;
145
152
  }
146
153
  /** Always allows. Used when no rate limits are configured. */
147
154
  declare class UnlimitedRateLimiter implements RateLimiter {
148
155
  acquire(): Promise<boolean>;
156
+ acquireAll(): Promise<boolean>;
149
157
  }
150
158
 
151
159
  /** Structured console logger (JSON lines). The default when none is provided. */
@@ -1,4 +1,4 @@
1
- import { createHmac, timingSafeEqual, randomBytes, createCipheriv, createDecipheriv, publicEncrypt, privateDecrypt, randomUUID, constants } from 'crypto';
1
+ import { createHmac, timingSafeEqual, randomBytes, createCipheriv, publicEncrypt, privateDecrypt, createDecipheriv, randomUUID, constants } from 'crypto';
2
2
  import { resolveMx } from 'dns/promises';
3
3
 
4
4
  // src/domain/errors.ts
@@ -68,22 +68,68 @@ var FakeEmailProvider = class {
68
68
  if (!parsed?.type || !parsed?.providerMessageId) {
69
69
  throw new WebhookVerificationError("fake webhook missing type/providerMessageId");
70
70
  }
71
+ const providerEventId = fakeProviderEventId(parsed.id);
72
+ const occurredAt = fakeOccurredAt(parsed.occurredAt);
71
73
  return {
72
74
  provider: this.name,
73
75
  type: parsed.type,
74
76
  providerMessageId: String(parsed.providerMessageId),
75
77
  recipient: parsed.recipient,
76
78
  isHardBounce: parsed.isHardBounce,
79
+ ...providerEventId !== void 0 ? { providerEventId } : {},
80
+ ...occurredAt !== void 0 ? { occurredAt } : {},
77
81
  raw: parsed
78
82
  };
79
83
  }
80
84
  };
85
+ function fakeProviderEventId(value) {
86
+ if (value === void 0 || value === null) return void 0;
87
+ if (typeof value !== "string") {
88
+ throw new WebhookVerificationError("fake webhook id must be a string");
89
+ }
90
+ return value;
91
+ }
92
+ function fakeOccurredAt(value) {
93
+ if (value === void 0 || value === null) return void 0;
94
+ if (typeof value === "number") {
95
+ if (!Number.isFinite(value)) {
96
+ throw new WebhookVerificationError("fake webhook occurredAt is invalid");
97
+ }
98
+ const at = new Date(value);
99
+ if (Number.isNaN(at.getTime())) {
100
+ throw new WebhookVerificationError("fake webhook occurredAt is invalid");
101
+ }
102
+ return at;
103
+ }
104
+ if (typeof value === "string") {
105
+ const at = new Date(value);
106
+ if (Number.isNaN(at.getTime())) {
107
+ throw new WebhookVerificationError("fake webhook occurredAt is invalid");
108
+ }
109
+ return at;
110
+ }
111
+ throw new WebhookVerificationError("fake webhook occurredAt is invalid");
112
+ }
81
113
 
82
114
  // src/adapters/providers/smtp.ts
83
115
  var SmtpEmailProvider = class {
84
116
  constructor(opts) {
85
117
  this.opts = opts;
86
118
  this.name = opts.name ?? "smtp";
119
+ if (opts.auth != null && opts.secure !== true) {
120
+ throw new Error("SmtpEmailProvider requires secure: true when SMTP auth is set");
121
+ }
122
+ const extra = opts.transportOptions;
123
+ if (extra && extra.url) {
124
+ throw new Error("SmtpEmailProvider refuses transportOptions.url");
125
+ }
126
+ if (extra && extra.service) {
127
+ throw new Error("SmtpEmailProvider refuses transportOptions.service");
128
+ }
129
+ const tls = extra?.tls;
130
+ if (tls !== null && tls !== void 0 && typeof tls === "object" && !Array.isArray(tls) && tls.rejectUnauthorized === false) {
131
+ throw new Error("SmtpEmailProvider refuses transportOptions.tls.rejectUnauthorized = false");
132
+ }
87
133
  }
88
134
  name;
89
135
  transporter;
@@ -98,11 +144,11 @@ var SmtpEmailProvider = class {
98
144
  );
99
145
  }
100
146
  this.transporter = (nodemailer.default ?? nodemailer).createTransport({
147
+ ...this.opts.transportOptions,
101
148
  host: this.opts.host,
102
149
  port: this.opts.port,
103
150
  secure: this.opts.secure ?? false,
104
- auth: this.opts.auth,
105
- ...this.opts.transportOptions
151
+ auth: this.opts.auth
106
152
  });
107
153
  return this.transporter;
108
154
  }
@@ -188,8 +234,10 @@ var ResendEmailProvider = class {
188
234
  if (!this.opts.webhookSecret) {
189
235
  throw new WebhookVerificationError("Resend webhookSecret is not configured");
190
236
  }
191
- verifySvixSignature(req, this.opts.webhookSecret);
237
+ const signed = verifySvixSignature(req, this.opts.webhookSecret);
238
+ const verifiedAt = unixSecondsToDate(signed.timestamp);
192
239
  const payload = JSON.parse(req.rawBody);
240
+ if (isIgnoredResendEvent(payload.type)) return null;
193
241
  const type = mapResendEvent(payload.type);
194
242
  if (!type) throw new WebhookVerificationError(`Unhandled Resend event "${payload.type}"`);
195
243
  const providerMessageId = payload.data?.email_id ?? payload.data?.id;
@@ -203,10 +251,15 @@ var ResendEmailProvider = class {
203
251
  recipient: payload.data?.to?.[0],
204
252
  isHardBounce: type === "bounced" ? payload.data?.bounce?.type !== "Transient" : void 0,
205
253
  occurredAt: payload.created_at ? new Date(payload.created_at) : void 0,
254
+ providerEventId: signed.id,
255
+ verifiedAt,
206
256
  raw: payload
207
257
  };
208
258
  }
209
259
  };
260
+ function isIgnoredResendEvent(type) {
261
+ return type === "email.sent" || type === "email.clicked" || type === "email.delivery_delayed";
262
+ }
210
263
  function mapResendEvent(type) {
211
264
  switch (type) {
212
265
  case "email.delivered":
@@ -223,6 +276,20 @@ function mapResendEvent(type) {
223
276
  return null;
224
277
  }
225
278
  }
279
+ function unixSecondsToDate(timestamp) {
280
+ if (!/^[0-9]+$/.test(timestamp)) {
281
+ throw new WebhookVerificationError("Svix timestamp is not a unix time");
282
+ }
283
+ const seconds = Number(timestamp);
284
+ if (!Number.isSafeInteger(seconds)) {
285
+ throw new WebhookVerificationError("Svix timestamp is not a unix time");
286
+ }
287
+ const verifiedAt = new Date(seconds * 1e3);
288
+ if (Number.isNaN(verifiedAt.getTime())) {
289
+ throw new WebhookVerificationError("Svix timestamp is not a unix time");
290
+ }
291
+ return verifiedAt;
292
+ }
226
293
  function verifySvixSignature(req, secret) {
227
294
  const id = header(req, "svix-id");
228
295
  const timestamp = header(req, "svix-timestamp");
@@ -231,6 +298,9 @@ function verifySvixSignature(req, secret) {
231
298
  throw new WebhookVerificationError("Missing Svix signature headers");
232
299
  }
233
300
  const secretBytes = Buffer.from(secret.replace(/^whsec_/, ""), "base64");
301
+ if (secretBytes.length === 0) {
302
+ throw new WebhookVerificationError("Svix webhook secret decodes to zero bytes");
303
+ }
234
304
  const signedContent = `${id}.${timestamp}.${req.rawBody}`;
235
305
  const expected = createHmac("sha256", secretBytes).update(signedContent).digest("base64");
236
306
  const provided = signatures.split(" ").map((s) => s.split(",", 2)[1] ?? s);
@@ -240,6 +310,7 @@ function verifySvixSignature(req, secret) {
240
310
  return a.length === b.length && timingSafeEqual(a, b);
241
311
  });
242
312
  if (!ok) throw new WebhookVerificationError("Svix signature mismatch");
313
+ return { id, timestamp };
243
314
  }
244
315
  function header(req, name) {
245
316
  const v = req.headers[name] ?? req.headers[name.toLowerCase()];
@@ -267,12 +338,20 @@ var HmacRecipientHasher = class {
267
338
  }
268
339
  };
269
340
  var PLAIN_ALG = "plain";
341
+ function aadBytes(context) {
342
+ return Buffer.from(`${context.messageId}:${context.column}`, "utf8");
343
+ }
344
+ function assertKeyId(sealed, keyId) {
345
+ if (sealed.keyId !== void 0 && sealed.keyId !== keyId) {
346
+ throw new Error("Sealed value keyId does not match this encryptor");
347
+ }
348
+ }
270
349
  var NoopEncryptor = class {
271
350
  alg = PLAIN_ALG;
272
- async seal(plaintext) {
351
+ async seal(plaintext, _context) {
273
352
  return { alg: PLAIN_ALG, ciphertext: Buffer.from(plaintext, "utf8").toString("base64") };
274
353
  }
275
- async open(sealed) {
354
+ async open(sealed, _context) {
276
355
  return Buffer.from(sealed.ciphertext, "base64").toString("utf8");
277
356
  }
278
357
  };
@@ -285,9 +364,10 @@ var AesGcmEncryptor = class {
285
364
  }
286
365
  alg = AES_ALG;
287
366
  key;
288
- async seal(plaintext) {
367
+ async seal(plaintext, context) {
289
368
  const iv = randomBytes(12);
290
369
  const cipher = createCipheriv(AES_ALG, this.key, iv);
370
+ if (context) cipher.setAAD(aadBytes(context));
291
371
  const ct = Buffer.concat([cipher.update(plaintext, "utf8"), cipher.final()]);
292
372
  const tag = cipher.getAuthTag();
293
373
  return {
@@ -295,19 +375,17 @@ var AesGcmEncryptor = class {
295
375
  ciphertext: ct.toString("base64"),
296
376
  iv: iv.toString("base64"),
297
377
  tag: tag.toString("base64"),
298
- keyId: this.keyId
378
+ keyId: this.keyId,
379
+ ...context ? { bound: true } : {}
299
380
  };
300
381
  }
301
- async open(sealed) {
382
+ async open(sealed, context) {
302
383
  if (sealed.alg === PLAIN_ALG) return new NoopEncryptor().open(sealed);
303
- if (!sealed.iv || !sealed.tag) throw new Error("Sealed value missing iv/tag");
304
- const decipher = createDecipheriv(AES_ALG, this.key, Buffer.from(sealed.iv, "base64"));
305
- decipher.setAuthTag(Buffer.from(sealed.tag, "base64"));
306
- const pt = Buffer.concat([
307
- decipher.update(Buffer.from(sealed.ciphertext, "base64")),
308
- decipher.final()
309
- ]);
310
- return pt.toString("utf8");
384
+ if (context) assertKeyId(sealed, this.keyId);
385
+ if (sealed.bound && !context) {
386
+ throw new Error("Sealed value is bound to a message and column");
387
+ }
388
+ return decryptAes(this.key, sealed, sealed.bound ? context : void 0);
311
389
  }
312
390
  };
313
391
  var HYBRID_ALG = "hybrid-rsa-aes-256-gcm";
@@ -320,10 +398,11 @@ var HybridSealEncryptor = class {
320
398
  this.keyId = keyId;
321
399
  }
322
400
  alg = HYBRID_ALG;
323
- async seal(plaintext) {
401
+ async seal(plaintext, context) {
324
402
  const dataKey = randomBytes(32);
325
403
  const iv = randomBytes(12);
326
404
  const cipher = createCipheriv(AES_ALG, dataKey, iv);
405
+ if (context) cipher.setAAD(aadBytes(context));
327
406
  const ct = Buffer.concat([cipher.update(plaintext, "utf8"), cipher.final()]);
328
407
  const tag = cipher.getAuthTag();
329
408
  const wrappedKey = publicEncrypt(rsaOaep(this.publicKeyPem), dataKey);
@@ -333,7 +412,8 @@ var HybridSealEncryptor = class {
333
412
  iv: iv.toString("base64"),
334
413
  tag: tag.toString("base64"),
335
414
  wrappedKey: wrappedKey.toString("base64"),
336
- keyId: this.keyId
415
+ keyId: this.keyId,
416
+ ...context ? { bound: true } : {}
337
417
  };
338
418
  }
339
419
  async open() {
@@ -343,15 +423,20 @@ var HybridSealEncryptor = class {
343
423
  }
344
424
  };
345
425
  var HybridOpenEncryptor = class {
346
- constructor(privateKeyPem) {
426
+ constructor(privateKeyPem, keyId = "default") {
347
427
  this.privateKeyPem = privateKeyPem;
428
+ this.keyId = keyId;
348
429
  }
349
430
  alg = HYBRID_ALG;
350
431
  async seal() {
351
432
  throw new Error("HybridOpenEncryptor is read-only; use HybridSealEncryptor to seal");
352
433
  }
353
- async open(sealed) {
434
+ async open(sealed, context) {
354
435
  if (sealed.alg === PLAIN_ALG) return new NoopEncryptor().open(sealed);
436
+ if (context) assertKeyId(sealed, this.keyId);
437
+ if (sealed.bound && !context) {
438
+ throw new Error("Sealed value is bound to a message and column");
439
+ }
355
440
  if (!sealed.wrappedKey || !sealed.iv || !sealed.tag) {
356
441
  throw new Error("Sealed value missing wrappedKey/iv/tag for hybrid open");
357
442
  }
@@ -359,15 +444,20 @@ var HybridOpenEncryptor = class {
359
444
  rsaOaep(this.privateKeyPem),
360
445
  Buffer.from(sealed.wrappedKey, "base64")
361
446
  );
362
- const decipher = createDecipheriv(AES_ALG, dataKey, Buffer.from(sealed.iv, "base64"));
363
- decipher.setAuthTag(Buffer.from(sealed.tag, "base64"));
364
- const pt = Buffer.concat([
365
- decipher.update(Buffer.from(sealed.ciphertext, "base64")),
366
- decipher.final()
367
- ]);
368
- return pt.toString("utf8");
447
+ return decryptAes(dataKey, sealed, sealed.bound ? context : void 0);
369
448
  }
370
449
  };
450
+ function decryptAes(key, sealed, context) {
451
+ if (!sealed.iv || !sealed.tag) throw new Error("Sealed value missing iv/tag");
452
+ const decipher = createDecipheriv(AES_ALG, key, Buffer.from(sealed.iv, "base64"));
453
+ if (context) decipher.setAAD(aadBytes(context));
454
+ decipher.setAuthTag(Buffer.from(sealed.tag, "base64"));
455
+ const pt = Buffer.concat([
456
+ decipher.update(Buffer.from(sealed.ciphertext, "base64")),
457
+ decipher.final()
458
+ ]);
459
+ return pt.toString("utf8");
460
+ }
371
461
 
372
462
  // src/adapters/rate-limit/in-memory.ts
373
463
  var InMemoryRateLimiter = class {
@@ -379,23 +469,40 @@ var InMemoryRateLimiter = class {
379
469
  async acquire(scope) {
380
470
  const budget = this.budgetFor(scope);
381
471
  if (!budget) return true;
382
- const key = `${scope.kind}:${scope.key ?? ""}`;
472
+ const bucket = this.refill(`${scope.kind}:${scope.key ?? ""}`, budget, this.clock.now().getTime());
473
+ if (bucket.tokens >= 1) {
474
+ bucket.tokens -= 1;
475
+ return true;
476
+ }
477
+ return false;
478
+ }
479
+ async acquireAll(scopes) {
383
480
  const now = this.clock.now().getTime();
384
- const refillRate = budget.max / budget.windowMs;
481
+ const ready = /* @__PURE__ */ new Map();
482
+ let allowed = true;
483
+ for (const scope of scopes) {
484
+ const budget = this.budgetFor(scope);
485
+ if (!budget) continue;
486
+ const key = `${scope.kind}:${scope.key ?? ""}`;
487
+ const bucket = this.refill(key, budget, now);
488
+ if (bucket.tokens < 1) allowed = false;
489
+ else ready.set(key, bucket);
490
+ }
491
+ if (!allowed) return false;
492
+ for (const bucket of ready.values()) bucket.tokens -= 1;
493
+ return true;
494
+ }
495
+ refill(key, budget, now) {
385
496
  let bucket = this.buckets.get(key);
386
497
  if (!bucket) {
387
498
  bucket = { tokens: budget.max, lastRefill: now };
388
499
  this.buckets.set(key, bucket);
389
- } else {
390
- const elapsed = now - bucket.lastRefill;
391
- bucket.tokens = Math.min(budget.max, bucket.tokens + elapsed * refillRate);
392
- bucket.lastRefill = now;
393
- }
394
- if (bucket.tokens >= 1) {
395
- bucket.tokens -= 1;
396
- return true;
500
+ return bucket;
397
501
  }
398
- return false;
502
+ const elapsed = now - bucket.lastRefill;
503
+ bucket.tokens = Math.min(budget.max, bucket.tokens + elapsed * (budget.max / budget.windowMs));
504
+ bucket.lastRefill = now;
505
+ return bucket;
399
506
  }
400
507
  budgetFor(scope) {
401
508
  switch (scope.kind) {
@@ -412,6 +519,9 @@ var UnlimitedRateLimiter = class {
412
519
  async acquire() {
413
520
  return true;
414
521
  }
522
+ async acquireAll() {
523
+ return true;
524
+ }
415
525
  };
416
526
 
417
527
  // src/adapters/observability/logger.ts