@capybara-hq/kernel 0.1.0-rc.133 → 0.1.0-rc.135

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 (69) hide show
  1. package/bootstrap.json +1 -1
  2. package/dist/automations/events/trigger-events.service.d.ts +13 -1
  3. package/dist/automations/events/trigger-events.service.js +27 -14
  4. package/dist/catalog/marketplaces.service.d.ts +1 -1
  5. package/dist/config/schema.d.ts +8 -0
  6. package/dist/config/schema.js +67 -2
  7. package/dist/ctx/create-ctx.d.ts +4 -0
  8. package/dist/ctx/create-ctx.js +74 -27
  9. package/dist/ctx/durable-cancellation.d.ts +3 -0
  10. package/dist/ctx/durable-cancellation.js +8 -0
  11. package/dist/ctx/durable-effects.service.d.ts +81 -0
  12. package/dist/ctx/durable-effects.service.js +316 -0
  13. package/dist/ctx/durable-envelope.d.ts +24 -0
  14. package/dist/ctx/durable-envelope.js +80 -0
  15. package/dist/ctx/durable-failure.d.ts +7 -0
  16. package/dist/ctx/durable-failure.js +32 -0
  17. package/dist/ctx/durable-job.d.ts +9 -0
  18. package/dist/ctx/durable-job.js +2 -0
  19. package/dist/ctx/durable-keys.d.ts +27 -0
  20. package/dist/ctx/durable-keys.js +138 -0
  21. package/dist/ctx/durable-relay.d.ts +29 -0
  22. package/dist/ctx/durable-relay.js +250 -0
  23. package/dist/ctx/queue.d.ts +2 -0
  24. package/dist/ctx/queue.js +22 -15
  25. package/dist/db/extension-db.d.ts +8 -3
  26. package/dist/db/extension-db.js +109 -7
  27. package/dist/db/extension-handoff-schema.d.ts +6 -0
  28. package/dist/db/extension-handoff-schema.js +72 -0
  29. package/dist/db/extension-role-provision.d.ts +9 -0
  30. package/dist/db/extension-role-provision.js +89 -0
  31. package/dist/db/extension-schema-transfer.d.ts +2 -1
  32. package/dist/db/extension-schema-transfer.js +114 -18
  33. package/dist/db/kernel-schema.d.ts +16 -0
  34. package/dist/db/migrator.d.ts +2 -0
  35. package/dist/db/migrator.js +4 -3
  36. package/dist/erasure/org-catalog.js +2 -2
  37. package/dist/erasure/org-rules.js +1 -0
  38. package/dist/extensions/admin-ops.js +17 -1
  39. package/dist/extensions/extensions.module.js +10 -0
  40. package/dist/extensions/host.d.ts +6 -0
  41. package/dist/extensions/host.js +35 -21
  42. package/dist/extensions/instance.d.ts +2 -0
  43. package/dist/extensions/instance.js +6 -0
  44. package/dist/extensions/migrate-lock.js +1 -0
  45. package/dist/extensions/sources.d.ts +1 -0
  46. package/dist/extensions/sources.js +9 -0
  47. package/dist/inbox/inbox-items.service.d.ts +5 -0
  48. package/dist/inbox/inbox-items.service.js +57 -33
  49. package/dist/index.d.ts +3 -1
  50. package/dist/index.js +3 -1
  51. package/dist/infra/database/extension-effect-key-lock.d.ts +10 -0
  52. package/dist/infra/database/extension-effect-key-lock.js +69 -0
  53. package/dist/infra/database/extension-handoff.d.ts +27 -0
  54. package/dist/infra/database/extension-handoff.js +113 -0
  55. package/dist/infra/database/rls-role.d.ts +4 -11
  56. package/dist/infra/database/rls-role.js +71 -27
  57. package/dist/infra/outbox/outbox.dispatcher.d.ts +6 -1
  58. package/dist/infra/outbox/outbox.dispatcher.js +64 -4
  59. package/dist/infra/outbox/outbox.module.js +2 -0
  60. package/dist/infra/outbox/registry.d.ts +12 -0
  61. package/dist/infra/outbox/registry.js +12 -0
  62. package/dist/kernel.d.ts +2 -0
  63. package/dist/kernel.js +12 -1
  64. package/dist/lifecycle/kernel-lifecycle.js +2 -3
  65. package/dist/orgs/orgs.service.js +16 -0
  66. package/dist/roles/worker.module.js +2 -0
  67. package/package.json +3 -3
  68. package/src/migrations/0225_extension_effect_receipts.sql +25 -0
  69. package/src/migrations/0226_enable_kernel_rls.sql +30 -0
@@ -0,0 +1,316 @@
1
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6
+ };
7
+ var __param = (this && this.__param) || function (paramIndex, decorator) {
8
+ return function (target, key) { decorator(target, key, paramIndex); }
9
+ };
10
+ import { Inject, Injectable } from "@nestjs/common";
11
+ import { sql } from "kysely";
12
+ import { TriggerEventsService, } from "../automations/events/trigger-events.service.js";
13
+ import { isExtensionEnabled } from "../extensions/enabled.js";
14
+ import { ExtensionRegistry } from "../extensions/registry.js";
15
+ import { InboxItemsService } from "../inbox/inbox-items.service.js";
16
+ import { KernelDb } from "../infra/database/kernel-db.js";
17
+ import { asPlatform } from "../infra/database/org-scope.js";
18
+ import { TransactionHost } from "../infra/database/transaction-host.js";
19
+ import { Transactional } from "../infra/database/transactional.decorator.js";
20
+ import { XactLock } from "../infra/database/xact-lock.js";
21
+ import { OutboxService } from "../infra/outbox/outbox.service.js";
22
+ import { MAINTENANCE_QUEUE_NAME } from "../runtime/maintenance-queue.js";
23
+ import { cancelDeletedOrgEffect } from "./durable-cancellation.js";
24
+ import { effectHash, InvalidExtensionEnvelope, signEnvelope, verifyEnvelope, } from "./durable-envelope.js";
25
+ import { ExtensionEffectFailure } from "./durable-failure.js";
26
+ import { EXTENSION_EFFECT_REDRIVE_JOB, EXTENSION_QUEUE_EFFECT_JOB, } from "./durable-job.js";
27
+ import { ExtensionEffectKeys } from "./durable-keys.js";
28
+ const MAX_KEY_BYTES = 256;
29
+ const RUN_AT = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{3})?(?:Z|[+-]\d{2}:\d{2})$/;
30
+ export function assertEffectKey(key) {
31
+ if (typeof key !== "string" || !key.trim() || Buffer.byteLength(key) > MAX_KEY_BYTES) {
32
+ throw new Error("An extension effect requires an idempotency key of 1 to 256 bytes");
33
+ }
34
+ }
35
+ let ExtensionEffects = class ExtensionEffects {
36
+ kdb;
37
+ txHost;
38
+ lock;
39
+ registry;
40
+ triggers;
41
+ inbox;
42
+ outbox;
43
+ keys;
44
+ constructor(kdb, txHost, lock, registry, triggers, inbox, outbox, keys) {
45
+ this.kdb = kdb;
46
+ this.txHost = txHost;
47
+ this.lock = lock;
48
+ this.registry = registry;
49
+ this.triggers = triggers;
50
+ this.inbox = inbox;
51
+ this.outbox = outbox;
52
+ this.keys = keys;
53
+ }
54
+ instance(plugin) {
55
+ const instance = this.registry.current(plugin);
56
+ if (!instance)
57
+ throw new ExtensionEffectFailure("extension_unavailable", "The extension is unavailable");
58
+ return instance;
59
+ }
60
+ async normalize(plugin, orgId, effect) {
61
+ const instance = this.instance(plugin);
62
+ const permissions = instance.permissions.permissions;
63
+ switch (effect.kind) {
64
+ case "trigger": {
65
+ const cause = await this.triggers.prepare(plugin, permissions?.triggers?.emit ?? [], effect.data);
66
+ const { cause: _original, ...data } = effect.data;
67
+ return { kind: "trigger", data, cause };
68
+ }
69
+ case "inbox.post":
70
+ if (!permissions?.inbox)
71
+ throw new ExtensionEffectFailure("permission_revoked", "The extension no longer has inbox permission");
72
+ await this.inbox.prepare({ kind: "plugin", plugin }, effect.data);
73
+ return effect;
74
+ case "inbox.resolve":
75
+ if (!permissions?.inbox)
76
+ throw new ExtensionEffectFailure("permission_revoked", "The extension no longer has inbox permission");
77
+ assertEffectKey(effect.postKey);
78
+ if (typeof effect.accountId !== "string" || !effect.accountId) {
79
+ throw new Error("An inbox resolution requires a recipient");
80
+ }
81
+ break;
82
+ case "queue":
83
+ if (!instance.hasEffectQueue(effect.queue)) {
84
+ throw new ExtensionEffectFailure("queue_unavailable", "The extension effect queue is not registered");
85
+ }
86
+ if (effect.runAt !== undefined &&
87
+ (!RUN_AT.test(effect.runAt) || !Number.isFinite(Date.parse(effect.runAt)))) {
88
+ throw new Error("Extension effect runAt must be an absolute time");
89
+ }
90
+ break;
91
+ }
92
+ if (!(await isExtensionEnabled(this.kdb.db, orgId, plugin))) {
93
+ throw new ExtensionEffectFailure("org_disabled", "The extension is disabled in this organization");
94
+ }
95
+ return effect;
96
+ }
97
+ async prepare(plugin, orgId, key, effect, extensionTx) {
98
+ const normalized = await this.normalize(plugin, orgId, effect);
99
+ const causeWindow = normalized.kind === "trigger" ? normalized.cause.causeWindow : undefined;
100
+ const ring = await this.keys.forSigning(extensionTx);
101
+ const envelope = signEnvelope(ring, {
102
+ plugin,
103
+ principal: { kind: "extension", name: plugin },
104
+ orgId,
105
+ key,
106
+ effect: normalized,
107
+ payloadHash: effectHash(normalized),
108
+ issuedAt: Date.now(),
109
+ ...(causeWindow && { causeWindow }),
110
+ });
111
+ verifyEnvelope(ring, envelope);
112
+ return envelope;
113
+ }
114
+ async verify(envelope, ring) {
115
+ const body = verifyEnvelope(ring ?? (await this.keys.forVerification()), envelope);
116
+ if (body.principal.kind !== "extension" ||
117
+ body.principal.name !== body.plugin ||
118
+ body.payloadHash !== effectHash(body.effect)) {
119
+ throw new InvalidExtensionEnvelope("Invalid extension effect payload hash");
120
+ }
121
+ return body;
122
+ }
123
+ async commit(plugin, orgId, key, effect) {
124
+ const normalized = await this.normalize(plugin, orgId, effect);
125
+ return this.apply(plugin, orgId, key ?? `legacy-${effectHash(normalized)}`, normalized, key === undefined);
126
+ }
127
+ async deliver(body) {
128
+ if (await this.cancelIfDeleted(body))
129
+ return;
130
+ return this.apply(body.plugin, body.orgId, body.key, body.effect);
131
+ }
132
+ async cancelIfDeleted(body) {
133
+ await this.lock.admitOrgShared(body.orgId);
134
+ if (await this.activeOrg(body.orgId))
135
+ return false;
136
+ await cancelDeletedOrgEffect(this.kdb.db, body.plugin, effectHash([body.orgId, body.plugin, body.effect.kind, body.key]));
137
+ return true;
138
+ }
139
+ async activeOrg(orgId) {
140
+ return ((await this.kdb.db
141
+ .selectFrom("orgs")
142
+ .select("id")
143
+ .where("id", "=", orgId)
144
+ .where("deleted_at", "is", null)
145
+ .executeTakeFirst()) !== undefined);
146
+ }
147
+ async apply(plugin, orgId, key, effect, legacy = false) {
148
+ await this.lock.admitOrgShared(orgId);
149
+ if (!(await this.activeOrg(orgId)))
150
+ throw new Error("Extension effect org is no longer active");
151
+ const payloadHash = effectHash(effect);
152
+ const receipt = this.kdb.db
153
+ .selectFrom("extension_effect_receipts")
154
+ .select(["result", "payload_hash"])
155
+ .where("org_id", "=", orgId)
156
+ .where("plugin", "=", plugin)
157
+ .where("kind", "=", effect.kind)
158
+ .where("effect_key", "=", key);
159
+ const inserted = await this.kdb.db
160
+ .insertInto("extension_effect_receipts")
161
+ .values({
162
+ org_id: orgId,
163
+ plugin,
164
+ kind: effect.kind,
165
+ effect_key: key,
166
+ payload_hash: payloadHash,
167
+ })
168
+ .onConflict((conflict) => conflict.doNothing())
169
+ .returning("effect_key")
170
+ .executeTakeFirst();
171
+ if (inserted === undefined) {
172
+ const existing = await receipt.executeTakeFirstOrThrow();
173
+ if (existing.payload_hash !== payloadHash) {
174
+ throw new ExtensionEffectFailure("idempotency_conflict", "Extension effect idempotency key was reused with a different payload");
175
+ }
176
+ if (effect.kind === "trigger") {
177
+ return { ...existing.result, duplicate: true };
178
+ }
179
+ return existing.result;
180
+ }
181
+ const instance = this.instance(plugin);
182
+ if (!(await isExtensionEnabled(this.kdb.db, orgId, plugin))) {
183
+ throw new ExtensionEffectFailure("org_disabled", "The extension is disabled in this organization");
184
+ }
185
+ const permissions = instance.permissions.permissions;
186
+ const result = await this.applyNew(plugin, orgId, key, effect, permissions, legacy);
187
+ await this.kdb.db
188
+ .updateTable("extension_effect_receipts")
189
+ .set({ result: JSON.stringify(result ?? null) })
190
+ .where("org_id", "=", orgId)
191
+ .where("plugin", "=", plugin)
192
+ .where("kind", "=", effect.kind)
193
+ .where("effect_key", "=", key)
194
+ .execute();
195
+ return result;
196
+ }
197
+ async applyNew(plugin, orgId, key, effect, permissions, legacy) {
198
+ switch (effect.kind) {
199
+ case "trigger":
200
+ return this.triggers.emit(plugin, permissions?.triggers?.emit ?? [], effect.data, effect.cause);
201
+ case "inbox.post": {
202
+ if (!permissions?.inbox)
203
+ throw new ExtensionEffectFailure("permission_revoked", "The extension no longer has inbox permission");
204
+ if (legacy && effect.data.dedupeKey === undefined) {
205
+ return this.inbox.post({ kind: "plugin", plugin }, effect.data);
206
+ }
207
+ const postKey = effect.data.dedupeKey ?? key;
208
+ const resolved = await this.inboxKeyIsResolved(plugin, orgId, effect.data.accountId, postKey);
209
+ return this.inbox.post({ kind: "plugin", plugin }, { ...effect.data, dedupeKey: postKey }, { resolved });
210
+ }
211
+ case "inbox.resolve": {
212
+ if (!permissions?.inbox)
213
+ throw new ExtensionEffectFailure("permission_revoked", "The extension no longer has inbox permission");
214
+ await this.inboxKeyIsResolved(plugin, orgId, effect.accountId, effect.postKey, true);
215
+ return this.inbox.resolveForPostKey(plugin, orgId, effect.accountId, effect.postKey);
216
+ }
217
+ case "queue": {
218
+ if (!this.instance(plugin).hasEffectQueue(effect.queue)) {
219
+ throw new ExtensionEffectFailure("queue_unavailable", "The extension effect queue is not registered");
220
+ }
221
+ const jobId = `extension-effect-${effectHash([plugin, orgId, key])}`;
222
+ return this.outbox.add({
223
+ queue: MAINTENANCE_QUEUE_NAME,
224
+ jobId,
225
+ name: EXTENSION_QUEUE_EFFECT_JOB,
226
+ orgId,
227
+ data: {
228
+ orgId,
229
+ plugin,
230
+ queue: effect.queue,
231
+ jobId,
232
+ data: effect.data,
233
+ },
234
+ ...(effect.runAt !== undefined && { runAt: new Date(effect.runAt) }),
235
+ });
236
+ }
237
+ }
238
+ }
239
+ async park(orgId, jobId, data, reason, attempts) {
240
+ const name = EXTENSION_EFFECT_REDRIVE_JOB;
241
+ await this.lock.lock(`extension-effect-dead-${data.plugin}`);
242
+ // org-filter: The immutable job ID is kernel-issued; unverified envelopes have no org.
243
+ return asPlatform("Bound parked extension effects per plugin and deduplicate by dispatch ID", async () => {
244
+ const existing = await this.kdb.db
245
+ .selectFrom("outbox")
246
+ .select("id")
247
+ .where("queue", "=", MAINTENANCE_QUEUE_NAME)
248
+ .where("job_id", "=", jobId)
249
+ .executeTakeFirst();
250
+ if (existing)
251
+ return true;
252
+ const taken = await this.kdb.db
253
+ .selectFrom("outbox")
254
+ .select("id")
255
+ .where("job_name", "=", EXTENSION_EFFECT_REDRIVE_JOB)
256
+ .where(sql `data->>'plugin' = ${data.plugin}`)
257
+ .limit(128)
258
+ .execute();
259
+ if (taken.length >= 128)
260
+ return false;
261
+ await this.outbox.addDead({
262
+ ...(orgId && { orgId }),
263
+ jobId,
264
+ queue: MAINTENANCE_QUEUE_NAME,
265
+ name,
266
+ data,
267
+ }, attempts, reason);
268
+ return true;
269
+ });
270
+ }
271
+ async inboxKeyIsResolved(plugin, orgId, accountId, postKey, resolve = false) {
272
+ const effectKey = effectHash([accountId, postKey]);
273
+ await this.lock.lock(`extension-inbox-${effectHash([orgId, plugin, effectKey])}`);
274
+ const kind = "inbox.resolved-key";
275
+ if (resolve) {
276
+ await this.kdb.db
277
+ .insertInto("extension_effect_receipts")
278
+ .values({ org_id: orgId, plugin, kind, effect_key: effectKey, payload_hash: effectKey })
279
+ .onConflict((conflict) => conflict.doNothing())
280
+ .execute();
281
+ return true;
282
+ }
283
+ return !!(await this.kdb.db
284
+ .selectFrom("extension_effect_receipts")
285
+ .select("effect_key")
286
+ .where("org_id", "=", orgId)
287
+ .where("plugin", "=", plugin)
288
+ .where("kind", "=", kind)
289
+ .where("effect_key", "=", effectKey)
290
+ .executeTakeFirst());
291
+ }
292
+ };
293
+ __decorate([
294
+ Transactional({ propagation: "requires_new" })
295
+ ], ExtensionEffects.prototype, "commit", null);
296
+ __decorate([
297
+ Transactional({ propagation: "requires_new" })
298
+ ], ExtensionEffects.prototype, "deliver", null);
299
+ __decorate([
300
+ Transactional()
301
+ ], ExtensionEffects.prototype, "cancelIfDeleted", null);
302
+ __decorate([
303
+ Transactional({ propagation: "requires_new" })
304
+ ], ExtensionEffects.prototype, "park", null);
305
+ ExtensionEffects = __decorate([
306
+ Injectable(),
307
+ __param(0, Inject(KernelDb)),
308
+ __param(1, Inject(TransactionHost)),
309
+ __param(2, Inject(XactLock)),
310
+ __param(3, Inject(ExtensionRegistry)),
311
+ __param(4, Inject(TriggerEventsService)),
312
+ __param(5, Inject(InboxItemsService)),
313
+ __param(6, Inject(OutboxService)),
314
+ __param(7, Inject(ExtensionEffectKeys))
315
+ ], ExtensionEffects);
316
+ export { ExtensionEffects };
@@ -0,0 +1,24 @@
1
+ export declare class InvalidExtensionEnvelope extends Error {
2
+ }
3
+ export declare class ExtensionEnvelopeClockSkew extends Error {
4
+ }
5
+ export interface EnvelopeKeyring {
6
+ active: string;
7
+ keys: Readonly<Record<string, string>>;
8
+ }
9
+ interface EnvelopeBody {
10
+ issuedAt: number;
11
+ causeWindow?: {
12
+ createdAt: number;
13
+ expiresAt: number;
14
+ };
15
+ }
16
+ export interface SignedEnvelope<T extends EnvelopeBody> {
17
+ keyId: string;
18
+ body: T;
19
+ signature: string;
20
+ }
21
+ export declare function effectHash(value: unknown): string;
22
+ export declare function signEnvelope<T extends EnvelopeBody>(ring: EnvelopeKeyring, body: T): SignedEnvelope<T>;
23
+ export declare function verifyEnvelope<T extends EnvelopeBody>(ring: EnvelopeKeyring, envelope: SignedEnvelope<T>, now?: number): T;
24
+ export {};
@@ -0,0 +1,80 @@
1
+ import { createHash, createHmac, timingSafeEqual } from "node:crypto";
2
+ const MAX_ENVELOPE_BYTES = 128 * 1024;
3
+ const MAX_DEPTH = 32;
4
+ const CLOCK_SKEW_MS = 1000;
5
+ export class InvalidExtensionEnvelope extends Error {
6
+ }
7
+ export class ExtensionEnvelopeClockSkew extends Error {
8
+ }
9
+ function canonicalize(value, depth) {
10
+ if (depth > MAX_DEPTH)
11
+ throw new Error("Extension effect is nested too deeply");
12
+ if (value === null || typeof value === "boolean" || typeof value === "string")
13
+ return value;
14
+ if (typeof value === "number" && Number.isFinite(value))
15
+ return value;
16
+ if (Array.isArray(value))
17
+ return value.map((part) => canonicalize(part, depth + 1));
18
+ if (typeof value === "object" &&
19
+ value !== null &&
20
+ Object.getPrototypeOf(value) === Object.prototype) {
21
+ return Object.fromEntries(Object.entries(value)
22
+ .filter(([, part]) => part !== undefined)
23
+ .sort(([a], [b]) => (a === b ? 0 : a < b ? -1 : 1))
24
+ .map(([key, part]) => [key, canonicalize(part, depth + 1)]));
25
+ }
26
+ throw new Error("Extension effects must use plain JSON values");
27
+ }
28
+ function canonicalJson(value) {
29
+ const result = JSON.stringify(canonicalize(value, 0));
30
+ if (Buffer.byteLength(result) > MAX_ENVELOPE_BYTES) {
31
+ throw new Error("Extension effect exceeds the size limit");
32
+ }
33
+ return result;
34
+ }
35
+ export function effectHash(value) {
36
+ return createHash("sha256").update(canonicalJson(value)).digest("hex");
37
+ }
38
+ function signatureOf(ring, keyId, body) {
39
+ const key = Object.hasOwn(ring.keys, keyId)
40
+ ? Buffer.from(ring.keys[keyId] ?? "", "base64url")
41
+ : null;
42
+ if (key?.length !== 32)
43
+ throw new InvalidExtensionEnvelope("Unknown extension effect signature key");
44
+ return createHmac("sha256", key)
45
+ .update("capybara:extension-outbox:v1\0")
46
+ .update(canonicalJson({ keyId, body }))
47
+ .digest();
48
+ }
49
+ export function signEnvelope(ring, body) {
50
+ const keyId = ring.active;
51
+ return { keyId, body, signature: signatureOf(ring, keyId, body).toString("base64url") };
52
+ }
53
+ export function verifyEnvelope(ring, envelope, now = Date.now()) {
54
+ try {
55
+ const expected = signatureOf(ring, envelope.keyId, envelope.body);
56
+ const provided = Buffer.from(envelope.signature, "base64url");
57
+ if (provided.length !== expected.length || !timingSafeEqual(expected, provided)) {
58
+ throw new InvalidExtensionEnvelope("Invalid extension effect signature");
59
+ }
60
+ }
61
+ catch (error) {
62
+ if (error instanceof InvalidExtensionEnvelope)
63
+ throw error;
64
+ throw new InvalidExtensionEnvelope("Malformed extension effect signature");
65
+ }
66
+ const { issuedAt, causeWindow } = envelope.body;
67
+ if (!Number.isSafeInteger(issuedAt) ||
68
+ issuedAt < 0 ||
69
+ (causeWindow !== undefined &&
70
+ (!Number.isSafeInteger(causeWindow.createdAt) ||
71
+ !Number.isSafeInteger(causeWindow.expiresAt) ||
72
+ issuedAt < causeWindow.createdAt ||
73
+ issuedAt >= causeWindow.expiresAt))) {
74
+ throw new InvalidExtensionEnvelope("Invalid extension effect issuance time");
75
+ }
76
+ if (issuedAt > now + CLOCK_SKEW_MS) {
77
+ throw new ExtensionEnvelopeClockSkew("Extension effect issuance is ahead of the relay clock");
78
+ }
79
+ return envelope.body;
80
+ }
@@ -0,0 +1,7 @@
1
+ export type EffectFailureCode = "signature_invalid" | "scope_mismatch" | "handoff_missing" | "handoff_changed" | "org_disabled" | "permission_revoked" | "extension_unavailable" | "queue_unavailable" | "idempotency_conflict" | "recipient_invalid" | "trigger_invalid" | "delivery_failed";
2
+ export declare class ExtensionEffectFailure extends Error {
3
+ readonly code: EffectFailureCode;
4
+ constructor(code: EffectFailureCode, message: string);
5
+ }
6
+ export declare function classifyEffectFailure(error: unknown): ExtensionEffectFailure;
7
+ export declare function effectFailureMessage(failure: ExtensionEffectFailure): string;
@@ -0,0 +1,32 @@
1
+ import { InboxError, TriggerError } from "@capybara-hq/plugin-sdk";
2
+ import { InvalidExtensionEnvelope } from "./durable-envelope.js";
3
+ export class ExtensionEffectFailure extends Error {
4
+ code;
5
+ constructor(code, message) {
6
+ super(message);
7
+ this.code = code;
8
+ }
9
+ }
10
+ export function classifyEffectFailure(error) {
11
+ if (error instanceof ExtensionEffectFailure)
12
+ return error;
13
+ if (error instanceof InvalidExtensionEnvelope) {
14
+ return new ExtensionEffectFailure("signature_invalid", "The handoff signature is invalid");
15
+ }
16
+ if ((error instanceof InboxError || error instanceof TriggerError) &&
17
+ error.code === "org_disabled") {
18
+ return new ExtensionEffectFailure("org_disabled", "The extension is disabled in this organization");
19
+ }
20
+ if (error instanceof InboxError) {
21
+ return new ExtensionEffectFailure("recipient_invalid", "The inbox item or its recipient is invalid");
22
+ }
23
+ if (error instanceof TriggerError) {
24
+ return error.code === "type_not_declared"
25
+ ? new ExtensionEffectFailure("permission_revoked", "The extension may no longer emit this event type")
26
+ : new ExtensionEffectFailure("trigger_invalid", "The trigger event or its cause is invalid");
27
+ }
28
+ return new ExtensionEffectFailure("delivery_failed", "The kernel could not deliver the extension effect");
29
+ }
30
+ export function effectFailureMessage(failure) {
31
+ return `${failure.code}: ${failure.message}`;
32
+ }
@@ -0,0 +1,9 @@
1
+ export declare const EXTENSION_QUEUE_EFFECT_JOB = "extension-queue-effect";
2
+ export declare const EXTENSION_EFFECT_REDRIVE_JOB = "extension-effect-redrive";
3
+ export interface ExtensionQueueEffectJob {
4
+ orgId: string;
5
+ plugin: string;
6
+ queue: string;
7
+ jobId: string;
8
+ data: unknown;
9
+ }
@@ -0,0 +1,2 @@
1
+ export const EXTENSION_QUEUE_EFFECT_JOB = "extension-queue-effect";
2
+ export const EXTENSION_EFFECT_REDRIVE_JOB = "extension-effect-redrive";
@@ -0,0 +1,27 @@
1
+ import type { Kysely } from "kysely";
2
+ import { type ExtensionDbIdentity } from "../db/extension-db.js";
3
+ import { KernelDb } from "../infra/database/kernel-db.js";
4
+ import { TransactionHost } from "../infra/database/transaction-host.js";
5
+ import { XactLock } from "../infra/database/xact-lock.js";
6
+ import type { EnvelopeKeyring } from "./durable-envelope.js";
7
+ import { type Keyring } from "./secrets.js";
8
+ export declare class ExtensionEffectKeys {
9
+ private readonly kdb;
10
+ readonly txHost: TransactionHost;
11
+ private readonly lock;
12
+ private readonly masterKeys;
13
+ private readonly identity;
14
+ constructor(kdb: KernelDb, txHost: TransactionHost, lock: XactLock, masterKeys: Keyring, identity: ExtensionDbIdentity);
15
+ private store;
16
+ private read;
17
+ forSigning(extensionTx?: Kysely<unknown>): Promise<EnvelopeKeyring>;
18
+ forVerification(): Promise<EnvelopeKeyring>;
19
+ /**
20
+ * The key and its active ID are published in one shared transaction. Readers load the
21
+ * current record per operation. Old IDs remain usable for previously signed obligations.
22
+ */
23
+ rotate({ staleBefore }?: {
24
+ staleBefore?: number;
25
+ }): Promise<EnvelopeKeyring>;
26
+ retireUnused(): Promise<void>;
27
+ }
@@ -0,0 +1,138 @@
1
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6
+ };
7
+ var __param = (this && this.__param) || function (paramIndex, decorator) {
8
+ return function (target, key) { decorator(target, key, paramIndex); }
9
+ };
10
+ import { randomBytes, randomUUID } from "node:crypto";
11
+ import { Inject, Injectable } from "@nestjs/common";
12
+ import { ConfiguredExtensionDbIdentity } from "../db/extension-db.js";
13
+ import { DEPLOYMENT_SECRETS_ORG, SECRETS_NAMESPACE, } from "../extensions/deployment-config-store.js";
14
+ import { handoffKeysInUse, pinSigningKey, tryLockRetiredKey, } from "../infra/database/extension-effect-key-lock.js";
15
+ import { KernelDb } from "../infra/database/kernel-db.js";
16
+ import { asPlatform } from "../infra/database/org-scope.js";
17
+ import { TransactionHost } from "../infra/database/transaction-host.js";
18
+ import { Transactional } from "../infra/database/transactional.decorator.js";
19
+ import { XactLock } from "../infra/database/xact-lock.js";
20
+ import { KEYRING } from "../infra/tokens.js";
21
+ import { createSecrets } from "./secrets.js";
22
+ const SECRET = "extension-outbox-signing-key";
23
+ const KEY_LIFETIME_MS = 30 * 24 * 60 * 60 * 1000;
24
+ const EMPTY_KEYRING = { active: "", keys: {} };
25
+ let ExtensionEffectKeys = class ExtensionEffectKeys {
26
+ kdb;
27
+ txHost;
28
+ lock;
29
+ masterKeys;
30
+ identity;
31
+ constructor(kdb, txHost, lock, masterKeys, identity) {
32
+ this.kdb = kdb;
33
+ this.txHost = txHost;
34
+ this.lock = lock;
35
+ this.masterKeys = masterKeys;
36
+ this.identity = identity;
37
+ }
38
+ store(db) {
39
+ return createSecrets(db, this.masterKeys, SECRETS_NAMESPACE);
40
+ }
41
+ read(db = this.kdb.db) {
42
+ return asPlatform("Read the kernel extension-effect signing keyring", async () => {
43
+ const stored = await this.store(db).get(DEPLOYMENT_SECRETS_ORG, SECRET);
44
+ return stored === null ? undefined : JSON.parse(stored);
45
+ });
46
+ }
47
+ async forSigning(extensionTx) {
48
+ const staleBefore = Date.now() - KEY_LIFETIME_MS;
49
+ const previous = await this.read(this.kdb.pool);
50
+ const ring = previous && previous.activeSince >= staleBefore
51
+ ? previous
52
+ : await this.rotate({ staleBefore });
53
+ if (!extensionTx)
54
+ return ring;
55
+ // Rotation can race the first read. Recheck the committed active ID after taking its pin.
56
+ let candidate = ring;
57
+ for (;;) {
58
+ const pinned = await pinSigningKey(extensionTx, candidate.active);
59
+ const current = await this.read(this.kdb.pool);
60
+ if (!current || !Object.hasOwn(current.keys, current.active)) {
61
+ throw new Error("The active extension effect signing key is unavailable");
62
+ }
63
+ if (current.active !== candidate.active) {
64
+ candidate = current;
65
+ continue;
66
+ }
67
+ if (!pinned)
68
+ throw new Error("The active extension effect signing key could not be pinned");
69
+ return current;
70
+ }
71
+ }
72
+ async forVerification() {
73
+ return (await this.read(this.kdb.pool)) ?? EMPTY_KEYRING;
74
+ }
75
+ /**
76
+ * The key and its active ID are published in one shared transaction. Readers load the
77
+ * current record per operation. Old IDs remain usable for previously signed obligations.
78
+ */
79
+ async rotate({ staleBefore } = {}) {
80
+ return asPlatform("Update the kernel extension-effect signing keyring", async () => {
81
+ await this.lock.lock(SECRET);
82
+ const previous = await this.read();
83
+ if (previous && staleBefore !== undefined && previous.activeSince >= staleBefore) {
84
+ return previous;
85
+ }
86
+ const active = randomUUID();
87
+ const next = {
88
+ active,
89
+ activeSince: Date.now(),
90
+ keys: { ...previous?.keys, [active]: randomBytes(32).toString("base64url") },
91
+ };
92
+ await this.store(this.kdb.db).set(DEPLOYMENT_SECRETS_ORG, SECRET, JSON.stringify(next));
93
+ return next;
94
+ });
95
+ }
96
+ async retireUnused() {
97
+ const ring = await this.read();
98
+ if (!ring || Object.keys(ring.keys).length < 2)
99
+ return;
100
+ await asPlatform("Retire unused extension-effect signing keys", async () => {
101
+ await this.lock.lock(SECRET);
102
+ const current = await this.read();
103
+ if (!current)
104
+ return;
105
+ const candidates = new Set();
106
+ for (const id of Object.keys(current.keys)) {
107
+ if (id !== current.active && (await tryLockRetiredKey(this.kdb.db, id)))
108
+ candidates.add(id);
109
+ }
110
+ if (candidates.size === 0)
111
+ return;
112
+ // Every successful pin precedes its append and lasts through commit or rollback.
113
+ // READ COMMITTED makes appends visible to the scan once the exclusive lock succeeds.
114
+ const referenced = await handoffKeysInUse(this.kdb.db, [...candidates], this.identity);
115
+ for (const id of referenced)
116
+ candidates.delete(id);
117
+ if (candidates.size === 0)
118
+ return;
119
+ const keys = Object.fromEntries(Object.entries(current.keys).filter(([id]) => !candidates.has(id)));
120
+ await this.store(this.kdb.db).set(DEPLOYMENT_SECRETS_ORG, SECRET, JSON.stringify({ ...current, keys }));
121
+ });
122
+ }
123
+ };
124
+ __decorate([
125
+ Transactional({ propagation: "requires_new", isolationLevel: "read committed" })
126
+ ], ExtensionEffectKeys.prototype, "rotate", null);
127
+ __decorate([
128
+ Transactional({ propagation: "requires_new", isolationLevel: "read committed" })
129
+ ], ExtensionEffectKeys.prototype, "retireUnused", null);
130
+ ExtensionEffectKeys = __decorate([
131
+ Injectable(),
132
+ __param(0, Inject(KernelDb)),
133
+ __param(1, Inject(TransactionHost)),
134
+ __param(2, Inject(XactLock)),
135
+ __param(3, Inject(KEYRING)),
136
+ __param(4, Inject(ConfiguredExtensionDbIdentity))
137
+ ], ExtensionEffectKeys);
138
+ export { ExtensionEffectKeys };
@@ -0,0 +1,29 @@
1
+ import { type ExtensionDbIdentity } from "../db/extension-db.js";
2
+ import { ExtensionRegistry } from "../extensions/registry.js";
3
+ import { ReplicaStatusStore } from "../extensions/sources.js";
4
+ import { KernelConfigService } from "../infra/config/kernel-config.service.js";
5
+ import { KernelDb } from "../infra/database/kernel-db.js";
6
+ import { LockService } from "../infra/lock/lock.service.js";
7
+ import { OutboxDispatcher } from "../infra/outbox/outbox.dispatcher.js";
8
+ import type { KernelLogger } from "../log.js";
9
+ import { ExtensionEffects } from "./durable-effects.service.js";
10
+ import { ExtensionEffectKeys } from "./durable-keys.js";
11
+ export declare class ExtensionEffectRelay {
12
+ private readonly dispatcher;
13
+ private readonly effects;
14
+ private readonly keys;
15
+ private readonly identity;
16
+ private readonly registry;
17
+ private readonly status;
18
+ private readonly db;
19
+ readonly config: KernelConfigService;
20
+ readonly lockService: LockService;
21
+ readonly log: KernelLogger;
22
+ constructor(dispatcher: OutboxDispatcher, effects: ExtensionEffects, keys: ExtensionEffectKeys, identity: ExtensionDbIdentity, registry: ExtensionRegistry, status: ReplicaStatusStore, db: KernelDb, config: KernelConfigService, lockService: LockService, log: KernelLogger);
23
+ relay(signal?: AbortSignal): Promise<void>;
24
+ retireKeys(): Promise<void>;
25
+ relayOnce(signal?: AbortSignal): Promise<void>;
26
+ private redrive;
27
+ private ingest;
28
+ private cleanup;
29
+ }