@capybara-hq/kernel 0.1.0-rc.132 → 0.1.0-rc.134
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/bootstrap.json +5 -5
- package/dist/admin/admin.module.js +3 -0
- package/dist/admin/admin.schemas.d.ts +4 -0
- package/dist/admin/health.service.d.ts +2 -2
- package/dist/admin/health.service.js +6 -2
- package/dist/admin/setup.service.js +6 -1
- package/dist/agents/agents.controller.js +3 -2
- package/dist/agents/agents.service.d.ts +2 -0
- package/dist/agents/agents.service.js +7 -0
- package/dist/automations/events/trigger-events.service.d.ts +13 -1
- package/dist/automations/events/trigger-events.service.js +27 -14
- package/dist/catalog/catalog.service.d.ts +2 -0
- package/dist/catalog/catalog.service.js +28 -5
- package/dist/catalog/marketplace-fetch.d.ts +2 -0
- package/dist/catalog/marketplace-fetch.js +15 -0
- package/dist/catalog/marketplaces.service.d.ts +4 -4
- package/dist/catalog/marketplaces.service.js +3 -2
- package/dist/catalog/owned-items.d.ts +2 -0
- package/dist/catalog/owned-items.js +30 -31
- package/dist/catalog/ownership.js +40 -38
- package/dist/catalog/plugin-import.d.ts +3 -4
- package/dist/catalog/plugin-import.js +50 -1
- package/dist/catalog/plugin-upgrade.d.ts +8 -0
- package/dist/catalog/plugin-upgrade.js +95 -7
- package/dist/catalog/publisher-policy.d.ts +9 -0
- package/dist/catalog/publisher-policy.js +12 -0
- package/dist/catalog/unshare.js +66 -58
- package/dist/client/client-access.service.js +5 -3
- package/dist/config/schema.d.ts +1 -0
- package/dist/config/schema.js +8 -1
- package/dist/conversations/conversations.controller.js +4 -14
- package/dist/conversations/conversations.service.d.ts +14 -0
- package/dist/conversations/conversations.service.js +20 -2
- package/dist/ctx/create-ctx.d.ts +15 -2
- package/dist/ctx/create-ctx.js +195 -79
- package/dist/ctx/durable-cancellation.d.ts +3 -0
- package/dist/ctx/durable-cancellation.js +8 -0
- package/dist/ctx/durable-effects.service.d.ts +81 -0
- package/dist/ctx/durable-effects.service.js +316 -0
- package/dist/ctx/durable-envelope.d.ts +24 -0
- package/dist/ctx/durable-envelope.js +80 -0
- package/dist/ctx/durable-failure.d.ts +7 -0
- package/dist/ctx/durable-failure.js +32 -0
- package/dist/ctx/durable-job.d.ts +9 -0
- package/dist/ctx/durable-job.js +2 -0
- package/dist/ctx/durable-keys.d.ts +27 -0
- package/dist/ctx/durable-keys.js +138 -0
- package/dist/ctx/durable-relay.d.ts +29 -0
- package/dist/ctx/durable-relay.js +250 -0
- package/dist/ctx/queue.d.ts +2 -0
- package/dist/ctx/queue.js +25 -15
- package/dist/db/extension-db.js +2 -0
- package/dist/db/extension-handoff-schema.d.ts +6 -0
- package/dist/db/extension-handoff-schema.js +72 -0
- package/dist/db/extension-rls-predicate.d.ts +1 -0
- package/dist/db/extension-rls-predicate.js +8 -0
- package/dist/db/extension-schema-transfer.d.ts +1 -1
- package/dist/db/extension-schema-transfer.js +18 -6
- package/dist/db/kernel-schema.d.ts +64 -0
- package/dist/db/migrator.js +6 -13
- package/dist/db/pool.d.ts +2 -2
- package/dist/db/pool.js +2 -2
- package/dist/db/sql-statements.d.ts +3 -0
- package/dist/db/sql-statements.js +15 -5
- package/dist/device-access/device-access.module.js +12 -2
- package/dist/device-access/device-access.service.d.ts +30 -2
- package/dist/device-access/device-access.service.js +38 -4
- package/dist/device-access/host-gate.d.ts +45 -0
- package/dist/device-access/host-gate.js +92 -0
- package/dist/device-access/host-service-stop-sweep.d.ts +33 -0
- package/dist/device-access/host-service-stop-sweep.js +112 -0
- package/dist/device-access/host-service-stop.d.ts +78 -0
- package/dist/device-access/host-service-stop.js +144 -0
- package/dist/device-access/host-services.d.ts +211 -0
- package/dist/device-access/host-services.js +803 -0
- package/dist/device-access/person-handles.d.ts +10 -0
- package/dist/device-access/person-handles.js +25 -0
- package/dist/device-access/service-events.d.ts +199 -0
- package/dist/device-access/service-events.js +704 -0
- package/dist/device-access/token.d.ts +5 -0
- package/dist/device-access/token.js +5 -0
- package/dist/devices/devices.service.js +3 -0
- package/dist/dial-in/access.d.ts +5 -5
- package/dist/dial-in/access.js +19 -12
- package/dist/dial-in/gateway.js +6 -2
- package/dist/dial-in/machines.d.ts +9 -2
- package/dist/dial-in/machines.js +27 -4
- package/dist/erasure/device-cleanup.js +12 -0
- package/dist/erasure/org-catalog.js +2 -2
- package/dist/erasure/org-rules.js +10 -0
- package/dist/errors.d.ts +2 -0
- package/dist/errors.js +2 -0
- package/dist/extensions/admin-ops.js +8 -2
- package/dist/extensions/deployed-snapshots.d.ts +4 -1
- package/dist/extensions/deployed-snapshots.js +7 -2
- package/dist/extensions/extensions.module.js +10 -0
- package/dist/extensions/host.d.ts +12 -2
- package/dist/extensions/host.js +44 -22
- package/dist/extensions/instance.d.ts +5 -0
- package/dist/extensions/instance.js +10 -0
- package/dist/extensions/ledger.d.ts +1 -1
- package/dist/extensions/lifecycle-hooks.js +3 -3
- package/dist/extensions/org-config.js +6 -1
- package/dist/extensions/permission-set.d.ts +7 -0
- package/dist/extensions/permission-set.js +10 -0
- package/dist/extensions/permission-view.d.ts +1 -1
- package/dist/extensions/permission-view.js +10 -1
- package/dist/extensions/sources.d.ts +1 -0
- package/dist/extensions/sources.js +9 -0
- package/dist/git/tickets.js +32 -27
- package/dist/http/app.js +5 -3
- package/dist/identity/accounts.d.ts +6 -1
- package/dist/identity/accounts.js +11 -2
- package/dist/identity/api-tokens.js +7 -6
- package/dist/identity/settings.d.ts +9 -1
- package/dist/identity/settings.js +16 -1
- package/dist/inbox/inbox-items.service.d.ts +5 -0
- package/dist/inbox/inbox-items.service.js +57 -33
- package/dist/inbox/org-notices.js +3 -2
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -0
- package/dist/infra/database/extension-effect-key-lock.d.ts +10 -0
- package/dist/infra/database/extension-effect-key-lock.js +69 -0
- package/dist/infra/database/extension-handoff.d.ts +27 -0
- package/dist/infra/database/extension-handoff.js +113 -0
- package/dist/infra/database/scoped-dialect.d.ts +3 -2
- package/dist/infra/database/scoped-dialect.js +260 -72
- package/dist/infra/database/startup-activation-transaction.d.ts +2 -0
- package/dist/infra/database/startup-activation-transaction.js +3 -2
- package/dist/infra/outbox/outbox.dispatcher.d.ts +6 -1
- package/dist/infra/outbox/outbox.dispatcher.js +64 -4
- package/dist/infra/outbox/outbox.module.js +2 -0
- package/dist/infra/outbox/registry.d.ts +40 -0
- package/dist/infra/outbox/registry.js +42 -0
- package/dist/infra/queue/queue-names.d.ts +1 -1
- package/dist/infra/queue/queue-names.js +1 -0
- package/dist/infra/queue/run-job.d.ts +4 -1
- package/dist/infra/queue/run-job.js +10 -2
- package/dist/kernel.js +1 -0
- package/dist/kernel.module.js +3 -0
- package/dist/orgs/offboarding.js +18 -9
- package/dist/orgs/orgs.service.js +16 -0
- package/dist/orgs/settings.service.js +3 -0
- package/dist/packages/npm-publish-keys.json +27 -0
- package/dist/packages/official-publisher.d.ts +19 -0
- package/dist/packages/official-publisher.js +152 -0
- package/dist/packages/provenance.d.ts +7 -0
- package/dist/packages/provenance.js +22 -19
- package/dist/packages/sigstore-trusted-root.json +126 -0
- package/dist/platform/ops/admin.ops.js +2 -1
- package/dist/platform/ops/orgs.ops.js +1 -0
- package/dist/roles/worker-role.d.ts +6 -3
- package/dist/roles/worker-role.js +12 -4
- package/dist/roles/worker.module.js +9 -0
- package/dist/runtime/maintenance.d.ts +5 -2
- package/dist/runtime/maintenance.js +18 -4
- package/dist/sandbox/device-reports.d.ts +4 -4
- package/dist/sandbox/device-reports.js +40 -30
- package/dist/sandbox/device-services.d.ts +2 -1
- package/dist/sandbox/device-services.js +5 -1
- package/dist/sandbox/permission-ceiling-writes.d.ts +8 -0
- package/dist/sandbox/permission-ceiling-writes.js +21 -0
- package/dist/sandbox/permission-config-publication.js +5 -1
- package/dist/themes/theme-state.js +24 -13
- package/dist/tools/call-scope.d.ts +6 -0
- package/dist/tools/call-scope.js +22 -0
- package/dist/tools/registry.js +20 -2
- package/dist/ui/views.js +36 -8
- package/package.json +9 -4
- package/src/migrations/0222_device_host_services.sql +27 -0
- package/src/migrations/0223_device_service_events.sql +54 -0
- package/src/migrations/0224_cache_conversation_rls_settings.sql +33 -0
- package/src/migrations/0225_extension_effect_receipts.sql +25 -0
|
@@ -68,39 +68,8 @@ let InboxItemsService = class InboxItemsService {
|
|
|
68
68
|
* `org_disabled` (the plugin is not enabled in the org).
|
|
69
69
|
*/
|
|
70
70
|
async post(source, p, opts = {}) {
|
|
71
|
-
|
|
72
|
-
throw invalid("the item must be an object");
|
|
73
|
-
const plugin = source.kind === "plugin" ? source.plugin : null;
|
|
74
|
-
const errs = validateInboxPost(p, plugin ?? "").filter((e) => plugin !== null || e !== "link_invalid");
|
|
75
|
-
if (plugin === null) {
|
|
76
|
-
if (p.link !== undefined && (typeof p.link !== "string" || !kernelLinkOk(p.link)))
|
|
77
|
-
errs.push("link_invalid");
|
|
78
|
-
if (p.actions !== undefined && p.actions.length > 0)
|
|
79
|
-
errs.push("kernel_item_actions");
|
|
80
|
-
}
|
|
81
|
-
if (errs.length > 0)
|
|
82
|
-
throw invalid(`invalid inbox item: ${errs.join(", ")}`);
|
|
71
|
+
const plugin = await this.prepare(source, p);
|
|
83
72
|
const db = this.kdb.db;
|
|
84
|
-
const org = await db
|
|
85
|
-
.selectFrom("orgs")
|
|
86
|
-
.select("id")
|
|
87
|
-
.where("id", "=", p.orgId)
|
|
88
|
-
.where("deleted_at", "is", null)
|
|
89
|
-
.executeTakeFirst();
|
|
90
|
-
if (org === undefined)
|
|
91
|
-
throw invalid(`org ${p.orgId} does not exist or is deleted`);
|
|
92
|
-
if (plugin !== null && !(await isExtensionEnabled(db, p.orgId, plugin)))
|
|
93
|
-
throw new InboxError("org_disabled", `${plugin} is not enabled in org ${p.orgId}`);
|
|
94
|
-
const member = await db
|
|
95
|
-
.selectFrom("memberships")
|
|
96
|
-
.innerJoin("accounts", "accounts.id", "memberships.account_id")
|
|
97
|
-
.select("accounts.id")
|
|
98
|
-
.where("memberships.org_id", "=", p.orgId)
|
|
99
|
-
.where("memberships.account_id", "=", p.accountId)
|
|
100
|
-
.where("accounts.status", "=", "active")
|
|
101
|
-
.executeTakeFirst();
|
|
102
|
-
if (member === undefined)
|
|
103
|
-
throw invalid(`account ${p.accountId} is not an active member of org ${p.orgId}`);
|
|
104
73
|
const dedupe = p.dedupeKey ?? null;
|
|
105
74
|
if (dedupe !== null) {
|
|
106
75
|
// an expired item with the key leaves the index's way: it is closed, a new one replaces it
|
|
@@ -127,6 +96,7 @@ let InboxItemsService = class InboxItemsService {
|
|
|
127
96
|
org_id: p.orgId,
|
|
128
97
|
account_id: p.accountId,
|
|
129
98
|
source: source.kind,
|
|
99
|
+
...(opts.resolved && { state: "resolved", resolved_at: sql `now()` }),
|
|
130
100
|
plugin,
|
|
131
101
|
kind: p.kind,
|
|
132
102
|
title: single(p.title),
|
|
@@ -148,7 +118,8 @@ let InboxItemsService = class InboxItemsService {
|
|
|
148
118
|
// the conflicting item may close between the insert and the read: then the insert runs again
|
|
149
119
|
for (let attempt = 0; attempt < 2; attempt++) {
|
|
150
120
|
if ((await insert()) !== undefined) {
|
|
151
|
-
|
|
121
|
+
if (!opts.resolved)
|
|
122
|
+
await this.push.oweInboxItem(id, p.orgId);
|
|
152
123
|
return { itemId: id };
|
|
153
124
|
}
|
|
154
125
|
if (dedupe === null)
|
|
@@ -168,6 +139,56 @@ let InboxItemsService = class InboxItemsService {
|
|
|
168
139
|
}
|
|
169
140
|
throw new Error("inbox item insert kept conflicting with a closed item");
|
|
170
141
|
}
|
|
142
|
+
/** Checks the current recipient and permissions before a durable post is prepared or delivered. */
|
|
143
|
+
async prepare(source, p) {
|
|
144
|
+
if (typeof p !== "object" || p === null)
|
|
145
|
+
throw invalid("the item must be an object");
|
|
146
|
+
const plugin = source.kind === "plugin" ? source.plugin : null;
|
|
147
|
+
const errs = validateInboxPost(p, plugin ?? "").filter((e) => plugin !== null || e !== "link_invalid");
|
|
148
|
+
if (plugin === null) {
|
|
149
|
+
if (p.link !== undefined && (typeof p.link !== "string" || !kernelLinkOk(p.link)))
|
|
150
|
+
errs.push("link_invalid");
|
|
151
|
+
if (p.actions !== undefined && p.actions.length > 0)
|
|
152
|
+
errs.push("kernel_item_actions");
|
|
153
|
+
}
|
|
154
|
+
if (errs.length > 0)
|
|
155
|
+
throw invalid(`invalid inbox item: ${errs.join(", ")}`);
|
|
156
|
+
const db = this.kdb.db;
|
|
157
|
+
const org = await db
|
|
158
|
+
.selectFrom("orgs")
|
|
159
|
+
.select("id")
|
|
160
|
+
.where("id", "=", p.orgId)
|
|
161
|
+
.where("deleted_at", "is", null)
|
|
162
|
+
.executeTakeFirst();
|
|
163
|
+
if (org === undefined)
|
|
164
|
+
throw invalid(`org ${p.orgId} does not exist or is deleted`);
|
|
165
|
+
if (plugin !== null && !(await isExtensionEnabled(db, p.orgId, plugin)))
|
|
166
|
+
throw new InboxError("org_disabled", `${plugin} is not enabled in org ${p.orgId}`);
|
|
167
|
+
const member = await db
|
|
168
|
+
.selectFrom("memberships")
|
|
169
|
+
.innerJoin("accounts", "accounts.id", "memberships.account_id")
|
|
170
|
+
.select("accounts.id")
|
|
171
|
+
.where("memberships.org_id", "=", p.orgId)
|
|
172
|
+
.where("memberships.account_id", "=", p.accountId)
|
|
173
|
+
.where("accounts.status", "=", "active")
|
|
174
|
+
.executeTakeFirst();
|
|
175
|
+
if (member === undefined)
|
|
176
|
+
throw invalid(`account ${p.accountId} is not an active member of org ${p.orgId}`);
|
|
177
|
+
return plugin;
|
|
178
|
+
}
|
|
179
|
+
/** Resolves open posts of this exact plugin, recipient and post key. */
|
|
180
|
+
async resolveForPostKey(plugin, orgId, accountId, postKey) {
|
|
181
|
+
await this.kdb.db
|
|
182
|
+
.updateTable("inbox_items")
|
|
183
|
+
.set({ state: "resolved", resolved_at: sql `now()` })
|
|
184
|
+
.where("org_id", "=", orgId)
|
|
185
|
+
.where("account_id", "=", accountId)
|
|
186
|
+
.where("source", "=", "plugin")
|
|
187
|
+
.where("plugin", "=", plugin)
|
|
188
|
+
.where("dedupe_key", "=", postKey)
|
|
189
|
+
.where("state", "=", "open")
|
|
190
|
+
.execute();
|
|
191
|
+
}
|
|
171
192
|
/** The open items of (org, account, source, plugin) with `dedupe`, closed as `expired`. */
|
|
172
193
|
sameKey(orgId, accountId, source, dedupe) {
|
|
173
194
|
const plugin = source.kind === "plugin" ? source.plugin : "";
|
|
@@ -299,6 +320,9 @@ let InboxItemsService = class InboxItemsService {
|
|
|
299
320
|
__decorate([
|
|
300
321
|
Transactional()
|
|
301
322
|
], InboxItemsService.prototype, "post", null);
|
|
323
|
+
__decorate([
|
|
324
|
+
Transactional({ propagation: "mandatory" })
|
|
325
|
+
], InboxItemsService.prototype, "resolveForPostKey", null);
|
|
302
326
|
__decorate([
|
|
303
327
|
Transactional()
|
|
304
328
|
], InboxItemsService.prototype, "resolveForPlugin", null);
|
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
// caller's transaction, so a notice exists exactly when its change does.
|
|
4
4
|
import { randomUUID } from "node:crypto";
|
|
5
5
|
import { orgsUsing, ownerOf, ownersOf } from "../catalog/ownership.js";
|
|
6
|
+
import { withOrgScope } from "../infra/database/org-scope.js";
|
|
6
7
|
/** An owned ref's display name: a plugin's (skills and agent templates have none). */
|
|
7
8
|
const refDisplayName = (db, ref) => ref.kind === "plugin" ? itemDisplayName(db, ref.id) : Promise.resolve(null);
|
|
8
9
|
/** A catalog item's display name for an upload notice (null without one, or for an unknown id). */
|
|
@@ -78,14 +79,14 @@ export async function notifySharedUpdate(db, ref, change) {
|
|
|
78
79
|
const using = await orgsUsing(db, ref, { except: row.owner_org_id });
|
|
79
80
|
const displayName = await refDisplayName(db, ref);
|
|
80
81
|
for (const o of using) {
|
|
81
|
-
await addOrgNotice(db, o.id, "shared_item_updated", {
|
|
82
|
+
await withOrgScope(o.id, () => addOrgNotice(db, o.id, "shared_item_updated", {
|
|
82
83
|
ref,
|
|
83
84
|
name: change.name,
|
|
84
85
|
displayName,
|
|
85
86
|
from: change.from,
|
|
86
87
|
to: change.to,
|
|
87
88
|
owner,
|
|
88
|
-
});
|
|
89
|
+
}));
|
|
89
90
|
}
|
|
90
91
|
return using.length;
|
|
91
92
|
}
|
package/dist/index.d.ts
CHANGED
|
@@ -71,6 +71,7 @@ export { type ContextJob, type JobWrapper, type LogContext, logContext, setJobWr
|
|
|
71
71
|
export { type Org, OrgsService } from "./orgs/orgs.service.js";
|
|
72
72
|
export type { KernelOverride } from "./overrides.js";
|
|
73
73
|
export { fetchNpmPackage, IntegrityMismatchError, type NpmFetchConfig, NpmFetchError, PackageTooLargeError, } from "./packages/npm.js";
|
|
74
|
+
export { fetchOfficialPublisher } from "./packages/official-publisher.js";
|
|
74
75
|
export { packPackageTgz } from "./packages/tgz.js";
|
|
75
76
|
export { checkInputParity, inputParity, type ParityFinding, type ParityOperation, } from "./platform/parity.js";
|
|
76
77
|
export { PLATFORM_OPERATION_PROVIDERS } from "./platform/platform-ops.module.js";
|
package/dist/index.js
CHANGED
|
@@ -67,6 +67,7 @@ export { createConfiguredLogger, loggerOptionsFromConfig } from "./log-config.js
|
|
|
67
67
|
export { logContext, setJobWrapper, setTraceContextSource, withJobContext, withLogContext, } from "./log-context.js";
|
|
68
68
|
export { OrgsService } from "./orgs/orgs.service.js";
|
|
69
69
|
export { fetchNpmPackage, IntegrityMismatchError, NpmFetchError, PackageTooLargeError, } from "./packages/npm.js";
|
|
70
|
+
export { fetchOfficialPublisher } from "./packages/official-publisher.js";
|
|
70
71
|
// The canonical tgz of a package tree; `capybara-plugin bootstrap` pins git entries with it.
|
|
71
72
|
export { packPackageTgz } from "./packages/tgz.js";
|
|
72
73
|
// Test seam: the Platform input-parity test in tools/checks (no runtime caller).
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { type Kysely, type QueryExecutorProvider } from "kysely";
|
|
2
|
+
import { type ExtensionDbIdentity } from "../../db/extension-db.js";
|
|
3
|
+
type TransactionExecutor = QueryExecutorProvider & Pick<Kysely<unknown>, "isTransaction">;
|
|
4
|
+
/** The pin must stay on the connection that will commit the envelope. */
|
|
5
|
+
export declare function pinSigningKey(db: Kysely<unknown>, keyId: string): Promise<boolean>;
|
|
6
|
+
/** A live signer keeps its key, and retirement can still collect other unused keys. */
|
|
7
|
+
export declare function tryLockRetiredKey(db: TransactionExecutor, keyId: string): Promise<boolean>;
|
|
8
|
+
/** Includes parked and unloaded extensions' envelopes. A failed scan leaves every key intact. */
|
|
9
|
+
export declare function handoffKeysInUse(db: QueryExecutorProvider, keyIds: readonly string[], identity: Pick<ExtensionDbIdentity, "resolve">): Promise<Set<string>>;
|
|
10
|
+
export {};
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import { EXTENSION_NAME_RE } from "@capybara-hq/plugin-sdk";
|
|
2
|
+
import { sql } from "kysely";
|
|
3
|
+
import { pluginSchemaName } from "../../db/extension-db.js";
|
|
4
|
+
import { EXTENSION_EFFECT_HANDOFF } from "./extension-handoff.js";
|
|
5
|
+
const signingKeyLock = (keyId) => sql `pg_catalog.hashtextextended(${`capybara.extension-effect-signing-key:${keyId}`}, 0)`;
|
|
6
|
+
/** The pin must stay on the connection that will commit the envelope. */
|
|
7
|
+
export async function pinSigningKey(db, keyId) {
|
|
8
|
+
if (!db.isTransaction)
|
|
9
|
+
throw new Error("Extension effect signing requires a local transaction");
|
|
10
|
+
const { rows } = await sql `
|
|
11
|
+
select pg_catalog.pg_try_advisory_xact_lock_shared(${signingKeyLock(keyId)}) as acquired
|
|
12
|
+
`.execute(db.withoutPlugins());
|
|
13
|
+
return rows[0]?.acquired === true;
|
|
14
|
+
}
|
|
15
|
+
/** A live signer keeps its key, and retirement can still collect other unused keys. */
|
|
16
|
+
export async function tryLockRetiredKey(db, keyId) {
|
|
17
|
+
if (!db.isTransaction)
|
|
18
|
+
throw new Error("Extension effect key retirement requires a transaction");
|
|
19
|
+
const { rows } = await sql `
|
|
20
|
+
select pg_catalog.pg_try_advisory_xact_lock(${signingKeyLock(keyId)}) as acquired
|
|
21
|
+
`.execute(db);
|
|
22
|
+
return rows[0]?.acquired === true;
|
|
23
|
+
}
|
|
24
|
+
/** Includes parked and unloaded extensions' envelopes. A failed scan leaves every key intact. */
|
|
25
|
+
export async function handoffKeysInUse(db, keyIds, identity) {
|
|
26
|
+
if (keyIds.length === 0)
|
|
27
|
+
return new Set();
|
|
28
|
+
await sql `set local lock_timeout = '500ms'`.execute(db);
|
|
29
|
+
await sql `set local statement_timeout = '1000ms'`.execute(db);
|
|
30
|
+
const prefix = "plugin_";
|
|
31
|
+
const { rows: tables } = await sql `
|
|
32
|
+
select n.nspname as schema, c.oid, c.relkind = 'r' and not c.relrowsecurity as ordinary,
|
|
33
|
+
pg_catalog.pg_get_userbyid(c.relowner) as owner, current_user as login
|
|
34
|
+
from pg_catalog.pg_class c
|
|
35
|
+
join pg_catalog.pg_namespace n on n.oid = c.relnamespace
|
|
36
|
+
where pg_catalog.left(n.nspname, ${prefix.length}) = ${prefix}
|
|
37
|
+
and c.relname = ${EXTENSION_EFFECT_HANDOFF}
|
|
38
|
+
`.execute(db);
|
|
39
|
+
const used = new Set();
|
|
40
|
+
for (const { schema, oid, ordinary, owner, login } of tables) {
|
|
41
|
+
const plugin = schema.slice(prefix.length).replaceAll("_", "-");
|
|
42
|
+
if (!EXTENSION_NAME_RE.test(plugin) || pluginSchemaName(plugin) !== schema)
|
|
43
|
+
continue;
|
|
44
|
+
const extension = identity.resolve(plugin);
|
|
45
|
+
if (!ordinary || (extension.separate ? owner === extension.login : owner !== login)) {
|
|
46
|
+
throw new Error("Cannot verify extension effect handoff owner during key retirement");
|
|
47
|
+
}
|
|
48
|
+
const table = sql.id(schema, EXTENSION_EFFECT_HANDOFF);
|
|
49
|
+
await sql `lock table only ${table} in access share mode`.execute(db);
|
|
50
|
+
const { rows } = await sql `
|
|
51
|
+
select pg_catalog.to_regclass(${`${schema}.${EXTENSION_EFFECT_HANDOFF}`}) = ${oid}::oid
|
|
52
|
+
and c.relkind = 'r' and not c.relrowsecurity
|
|
53
|
+
and pg_catalog.pg_get_userbyid(c.relowner) = ${owner} as matches
|
|
54
|
+
from pg_catalog.pg_class c
|
|
55
|
+
where c.oid = ${oid}::oid
|
|
56
|
+
`.execute(db);
|
|
57
|
+
if (!rows[0]?.matches)
|
|
58
|
+
throw new Error("Extension effect handoff changed during key retirement");
|
|
59
|
+
const references = await sql `
|
|
60
|
+
select distinct envelope->>'keyId' as id from only ${table}
|
|
61
|
+
where envelope->>'keyId' = any(${keyIds}::text[])
|
|
62
|
+
`.execute(db);
|
|
63
|
+
for (const { id } of references.rows)
|
|
64
|
+
used.add(id);
|
|
65
|
+
if (used.size === keyIds.length)
|
|
66
|
+
break;
|
|
67
|
+
}
|
|
68
|
+
return used;
|
|
69
|
+
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { type Kysely } from "kysely";
|
|
2
|
+
import type { ExtensionEffectEnvelope } from "../../ctx/durable-effects.service.js";
|
|
3
|
+
export declare const isExtensionTransaction: (db: Kysely<unknown>) => boolean;
|
|
4
|
+
export declare const EXTENSION_EFFECT_HANDOFF = "_capybara_effect_handoff";
|
|
5
|
+
export declare function handoffTable(plugin: string): string;
|
|
6
|
+
export declare function appendEffect(tx: Kysely<unknown>, plugin: string, envelope: ExtensionEffectEnvelope): Promise<void>;
|
|
7
|
+
export interface HandoffRow {
|
|
8
|
+
id: string;
|
|
9
|
+
envelope: ExtensionEffectEnvelope;
|
|
10
|
+
attempts: number;
|
|
11
|
+
created_at: Date;
|
|
12
|
+
}
|
|
13
|
+
export declare function readHandoff(db: Kysely<unknown>, plugin: string, extensionLogin: string | null, batch: number): Promise<HandoffRow[]>;
|
|
14
|
+
export declare function retryHandoff(db: Kysely<unknown>, plugin: string, extensionLogin: string | null, row: Pick<HandoffRow, "id" | "attempts">, reason: string): Promise<void>;
|
|
15
|
+
export declare function settleHandoff(db: Kysely<unknown>, plugin: string, extensionLogin: string | null, id: string): Promise<void>;
|
|
16
|
+
export interface HandoffReference {
|
|
17
|
+
plugin: string;
|
|
18
|
+
rowId: string;
|
|
19
|
+
hash: string;
|
|
20
|
+
size: number;
|
|
21
|
+
}
|
|
22
|
+
export declare function handoffReference(plugin: string, row: HandoffRow): HandoffReference;
|
|
23
|
+
export declare function readHandoffRow(db: Kysely<unknown>, plugin: string, login: string | null, id: string): Promise<HandoffRow | undefined>;
|
|
24
|
+
export declare function markHandoffParked(db: Kysely<unknown>, plugin: string, login: string | null, id: string, reason: string): Promise<void>;
|
|
25
|
+
export declare function readUnreferencedParks(db: Kysely<unknown>, plugin: string, login: string | null, batch: number): Promise<(HandoffRow & {
|
|
26
|
+
has_reference: boolean;
|
|
27
|
+
})[]>;
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { sql } from "kysely";
|
|
3
|
+
import { ExtensionEffectFailure } from "../../ctx/durable-failure.js";
|
|
4
|
+
import { pluginSchemaName } from "../../db/extension-db.js";
|
|
5
|
+
export const isExtensionTransaction = (db) => db.isTransaction;
|
|
6
|
+
export const EXTENSION_EFFECT_HANDOFF = "_capybara_effect_handoff";
|
|
7
|
+
export function handoffTable(plugin) {
|
|
8
|
+
return `${pluginSchemaName(plugin)}.${EXTENSION_EFFECT_HANDOFF}`;
|
|
9
|
+
}
|
|
10
|
+
export async function appendEffect(tx, plugin, envelope) {
|
|
11
|
+
try {
|
|
12
|
+
await sql `
|
|
13
|
+
insert into ${sql.table(handoffTable(plugin))} (id, envelope)
|
|
14
|
+
values (pg_catalog.gen_random_uuid(), cast(${JSON.stringify(envelope)} as jsonb))
|
|
15
|
+
`.execute(tx.withoutPlugins());
|
|
16
|
+
}
|
|
17
|
+
catch (error) {
|
|
18
|
+
if (typeof error === "object" && error !== null && "code" in error && error.code === "42P01") {
|
|
19
|
+
throw new Error(`Extension handoff for ${plugin} is unavailable. Run capybara migrate using the split-role schema provisioning procedure.`, { cause: error });
|
|
20
|
+
}
|
|
21
|
+
throw error;
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
async function withVerifiedHandoff(db, plugin, extensionLogin, run) {
|
|
25
|
+
const name = handoffTable(plugin);
|
|
26
|
+
return db.transaction().execute(async (tx) => {
|
|
27
|
+
await sql `set local lock_timeout = '500ms'`.execute(tx);
|
|
28
|
+
await sql `set local statement_timeout = '1000ms'`.execute(tx);
|
|
29
|
+
const relation = async () => {
|
|
30
|
+
const { rows } = await sql `
|
|
31
|
+
select c.relkind = 'r' and
|
|
32
|
+
case when ${extensionLogin}::text is null then
|
|
33
|
+
pg_catalog.pg_get_userbyid(c.relowner) = current_user
|
|
34
|
+
else
|
|
35
|
+
pg_catalog.pg_get_userbyid(c.relowner) <> ${extensionLogin}
|
|
36
|
+
end as valid
|
|
37
|
+
from pg_catalog.pg_class c where c.oid = pg_catalog.to_regclass(${name})
|
|
38
|
+
`.execute(tx);
|
|
39
|
+
return rows[0];
|
|
40
|
+
};
|
|
41
|
+
const before = await relation();
|
|
42
|
+
if (!before)
|
|
43
|
+
throw new ExtensionEffectFailure("handoff_missing", "The extension handoff table is missing");
|
|
44
|
+
if (!before.valid)
|
|
45
|
+
throw new Error("Invalid extension handoff relation");
|
|
46
|
+
await sql `lock table ${sql.table(name)} in access share mode`.execute(tx);
|
|
47
|
+
if (!(await relation())?.valid)
|
|
48
|
+
throw new Error("Invalid extension handoff relation");
|
|
49
|
+
return run(tx, name);
|
|
50
|
+
});
|
|
51
|
+
}
|
|
52
|
+
export async function readHandoff(db, plugin, extensionLogin, batch) {
|
|
53
|
+
return withVerifiedHandoff(db, plugin, extensionLogin, async (trx, name) => {
|
|
54
|
+
const result = await sql `
|
|
55
|
+
select id, envelope, attempts, created_at from ${sql.table(name)}
|
|
56
|
+
where parked_at is null and next_attempt_at <= pg_catalog.now()
|
|
57
|
+
order by next_attempt_at, id limit ${batch}
|
|
58
|
+
`.execute(trx);
|
|
59
|
+
return result.rows;
|
|
60
|
+
});
|
|
61
|
+
}
|
|
62
|
+
export async function retryHandoff(db, plugin, extensionLogin, row, reason) {
|
|
63
|
+
const delay = Math.min(300, 2 ** Math.min(9, row.attempts));
|
|
64
|
+
await withVerifiedHandoff(db, plugin, extensionLogin, async (tx, name) => {
|
|
65
|
+
await sql `
|
|
66
|
+
update ${sql.table(name)}
|
|
67
|
+
set attempts = least(19, attempts + 1), last_error = ${reason}, next_attempt_at = pg_catalog.now() + make_interval(secs => ${delay})
|
|
68
|
+
where id = ${row.id} and attempts = ${row.attempts}
|
|
69
|
+
`.execute(tx);
|
|
70
|
+
});
|
|
71
|
+
}
|
|
72
|
+
export async function settleHandoff(db, plugin, extensionLogin, id) {
|
|
73
|
+
await withVerifiedHandoff(db, plugin, extensionLogin, async (trx, name) => {
|
|
74
|
+
await sql `delete from ${sql.table(name)} where id = ${id}`.execute(trx);
|
|
75
|
+
});
|
|
76
|
+
}
|
|
77
|
+
export function handoffReference(plugin, row) {
|
|
78
|
+
const bytes = JSON.stringify(row.envelope);
|
|
79
|
+
return {
|
|
80
|
+
plugin,
|
|
81
|
+
rowId: row.id,
|
|
82
|
+
hash: createHash("sha256").update(bytes).digest("hex"),
|
|
83
|
+
size: Buffer.byteLength(bytes),
|
|
84
|
+
};
|
|
85
|
+
}
|
|
86
|
+
export async function readHandoffRow(db, plugin, login, id) {
|
|
87
|
+
return withVerifiedHandoff(db, plugin, login, async (tx, name) => (await sql `select id, envelope, attempts, created_at from ${sql.table(name)} where id = ${id}`.execute(tx)).rows[0]);
|
|
88
|
+
}
|
|
89
|
+
export async function markHandoffParked(db, plugin, login, id, reason) {
|
|
90
|
+
await withVerifiedHandoff(db, plugin, login, async (tx, name) => {
|
|
91
|
+
await sql `update ${sql.table(name)} set parked_at = pg_catalog.now(), last_error = ${reason} where id = ${id}`.execute(tx);
|
|
92
|
+
});
|
|
93
|
+
}
|
|
94
|
+
export async function readUnreferencedParks(db, plugin, login, batch) {
|
|
95
|
+
return withVerifiedHandoff(db, plugin, login, async (tx, name) => {
|
|
96
|
+
const { rows } = await sql `
|
|
97
|
+
select source.id, source.envelope, source.attempts, source.created_at,
|
|
98
|
+
job.id is not null as has_reference
|
|
99
|
+
from ${sql.table(name)} source
|
|
100
|
+
left join lateral (
|
|
101
|
+
select job.id, job.org_id from capybara.outbox job
|
|
102
|
+
where job.job_name = 'extension-effect-redrive'
|
|
103
|
+
and job.data->>'plugin' = ${plugin} and job.data->>'rowId' = source.id::text
|
|
104
|
+
limit 1
|
|
105
|
+
) job on true
|
|
106
|
+
where source.parked_at is not null and (job.id is null or (job.org_id is not null and not exists (
|
|
107
|
+
select 1 from capybara.orgs org where org.id = job.org_id and org.deleted_at is null
|
|
108
|
+
)))
|
|
109
|
+
order by source.parked_at, source.id limit ${batch}
|
|
110
|
+
`.execute(tx);
|
|
111
|
+
return rows;
|
|
112
|
+
});
|
|
113
|
+
}
|
|
@@ -2,7 +2,7 @@ import { type Driver, type KyselyPlugin, PostgresDialect, type PostgresDialectCo
|
|
|
2
2
|
/**
|
|
3
3
|
* `db.rls`: how the kernel pool carries the org scope to Postgres (RLS spec §5.2, §7).
|
|
4
4
|
* - `off`: nothing is sent; the pool is a plain Kysely pool (no extra round trip).
|
|
5
|
-
* - `scoped`: every
|
|
5
|
+
* - `scoped`: every transaction carries the scope, with `capybara.rls = off`, so the policies admit
|
|
6
6
|
* every row; for measuring the round-trip cost (§8) and for the unscoped-query check.
|
|
7
7
|
* - `enforce`: the same with `capybara.rls = enforce`: the policies filter by the scope.
|
|
8
8
|
*/
|
|
@@ -15,6 +15,7 @@ export declare const captureUnscopedQueryOrigins: KyselyPlugin;
|
|
|
15
15
|
*/
|
|
16
16
|
export declare class ScopedPostgresDialect extends PostgresDialect {
|
|
17
17
|
private readonly rls;
|
|
18
|
-
|
|
18
|
+
private readonly standaloneScope;
|
|
19
|
+
constructor(config: PostgresDialectConfig, rls: RlsMode, extendedProtocol?: boolean);
|
|
19
20
|
createDriver(): Driver;
|
|
20
21
|
}
|