@capybara-hq/kernel 0.1.0-rc.131 → 0.1.0-rc.132
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/catalog/plugin-import.d.ts +3 -1
- package/dist/catalog/plugin-import.js +19 -15
- package/dist/config/schema.d.ts +1 -0
- package/dist/config/schema.js +8 -0
- package/dist/ctx/create-ctx.d.ts +3 -2
- package/dist/ctx/create-ctx.js +10 -7
- package/dist/db/extension-db.d.ts +30 -0
- package/dist/db/extension-db.js +91 -0
- package/dist/db/extension-schema-transfer.d.ts +6 -0
- package/dist/db/extension-schema-transfer.js +141 -0
- package/dist/db/kernel-schema.d.ts +2 -4
- package/dist/db/migrator.d.ts +6 -0
- package/dist/db/migrator.js +39 -4
- package/dist/db/pool.d.ts +4 -0
- package/dist/db/pool.js +36 -1
- package/dist/erasure/org-catalog.js +2 -2
- package/dist/extensions/admin-ops.d.ts +3 -1
- package/dist/extensions/admin-ops.js +11 -7
- package/dist/extensions/extensions.module.js +3 -0
- package/dist/extensions/host.d.ts +4 -1
- package/dist/extensions/host.js +29 -6
- package/dist/extensions/instance.d.ts +3 -0
- package/dist/extensions/instance.js +3 -1
- package/dist/extensions/migrate-lock.d.ts +4 -1
- package/dist/extensions/migrate-lock.js +19 -2
- package/dist/infra/outbox/registry.d.ts +0 -14
- package/dist/infra/outbox/registry.js +0 -15
- package/dist/kernel.js +4 -0
- package/dist/lifecycle/kernel-lifecycle.d.ts +3 -1
- package/dist/lifecycle/kernel-lifecycle.js +26 -21
- package/dist/roles/worker.module.js +0 -6
- package/dist/runtime/maintenance.d.ts +1 -3
- package/dist/runtime/maintenance.js +3 -14
- package/package.json +1 -1
- package/src/migrations/0219_event_org_constraint_check.sql +29 -0
- package/src/migrations/0220_require_event_org.sql +18 -0
- package/src/migrations/0221_drop_connector_declaration_policy.sql +2 -0
- package/dist/conversations/event-org-backfill.d.ts +0 -111
- package/dist/conversations/event-org-backfill.js +0 -264
- package/dist/conversations/event-org-backfill.module.d.ts +0 -3
- package/dist/conversations/event-org-backfill.module.js +0 -18
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { type AgentTemplate, type AgentTemplateTier, type LocalizedName, type PluginManifest, type ThemeScheme } from "@capybara-hq/plugin-sdk";
|
|
2
|
+
import { type ExtensionDbIdentity } from "../db/extension-db.js";
|
|
2
3
|
import { ApiError } from "../errors.js";
|
|
3
4
|
import { ExtensionAdminOps } from "../extensions/admin-ops.js";
|
|
4
5
|
import { ExtensionAdmin } from "../extensions/admin-view.js";
|
|
@@ -411,6 +412,7 @@ export declare class PluginImport {
|
|
|
411
412
|
private readonly approveLock;
|
|
412
413
|
private readonly itemLock;
|
|
413
414
|
private readonly config;
|
|
415
|
+
private readonly extensionDbIdentity;
|
|
414
416
|
private readonly installs;
|
|
415
417
|
private readonly ops;
|
|
416
418
|
private readonly admin;
|
|
@@ -436,7 +438,7 @@ export declare class PluginImport {
|
|
|
436
438
|
/** The super admin lock (identity/super-admin.ts): joins the caller's transaction. */
|
|
437
439
|
adminLock: SuperAdminLock,
|
|
438
440
|
/** The owner org's lock: an org upload re-checks its admin under it (ruling P3-7). */
|
|
439
|
-
orgLock: OrgLock, installLock: PluginInstallLock, approveLock: PluginApproveLock, itemLock: CatalogItemLock, config: KernelConfigService, storage: StorageService, installs: ExtensionInstalls, ops: ExtensionAdminOps, admin: ExtensionAdmin,
|
|
441
|
+
orgLock: OrgLock, installLock: PluginInstallLock, approveLock: PluginApproveLock, itemLock: CatalogItemLock, config: KernelConfigService, extensionDbIdentity: ExtensionDbIdentity, storage: StorageService, installs: ExtensionInstalls, ops: ExtensionAdminOps, admin: ExtensionAdmin,
|
|
440
442
|
/** Reads a package from the package store (confirm recomputes the permission set). */
|
|
441
443
|
blobs: ExtensionBlobs,
|
|
442
444
|
/** Config-declared names, loaded connectors and extension versions (the extension registry). */
|
|
@@ -13,6 +13,7 @@ import { Inject, Injectable } from "@nestjs/common";
|
|
|
13
13
|
import { sql } from "kysely";
|
|
14
14
|
import semver from "semver";
|
|
15
15
|
import { checkClientFiles } from "../client/client-files.js";
|
|
16
|
+
import { ConfiguredExtensionDbIdentity } from "../db/extension-db.js";
|
|
16
17
|
import { ApiError } from "../errors.js";
|
|
17
18
|
import { ExtensionAdminOps } from "../extensions/admin-ops.js";
|
|
18
19
|
import { ExtensionAdmin } from "../extensions/admin-view.js";
|
|
@@ -150,6 +151,7 @@ let PluginImport = class PluginImport {
|
|
|
150
151
|
approveLock;
|
|
151
152
|
itemLock;
|
|
152
153
|
config;
|
|
154
|
+
extensionDbIdentity;
|
|
153
155
|
installs;
|
|
154
156
|
ops;
|
|
155
157
|
admin;
|
|
@@ -171,7 +173,7 @@ let PluginImport = class PluginImport {
|
|
|
171
173
|
/** The super admin lock (identity/super-admin.ts): joins the caller's transaction. */
|
|
172
174
|
adminLock,
|
|
173
175
|
/** The owner org's lock: an org upload re-checks its admin under it (ruling P3-7). */
|
|
174
|
-
orgLock, installLock, approveLock, itemLock, config, storage, installs, ops, admin,
|
|
176
|
+
orgLock, installLock, approveLock, itemLock, config, extensionDbIdentity, storage, installs, ops, admin,
|
|
175
177
|
/** Reads a package from the package store (confirm recomputes the permission set). */
|
|
176
178
|
blobs,
|
|
177
179
|
/** Config-declared names, loaded connectors and extension versions (the extension registry). */
|
|
@@ -187,6 +189,7 @@ let PluginImport = class PluginImport {
|
|
|
187
189
|
this.approveLock = approveLock;
|
|
188
190
|
this.itemLock = itemLock;
|
|
189
191
|
this.config = config;
|
|
192
|
+
this.extensionDbIdentity = extensionDbIdentity;
|
|
190
193
|
this.installs = installs;
|
|
191
194
|
this.ops = ops;
|
|
192
195
|
this.admin = admin;
|
|
@@ -393,7 +396,7 @@ let PluginImport = class PluginImport {
|
|
|
393
396
|
let extension;
|
|
394
397
|
if (ext) {
|
|
395
398
|
extension = await this.reviewExtension(ext, await this.extensionState(m.name, packageName));
|
|
396
|
-
await assertDowngradable(this.db, extension, ext.migrationSql);
|
|
399
|
+
await assertDowngradable(this.db, extension, ext.migrationSql, this.extensionDbIdentity, this.config.get().db.connectTimeoutMs);
|
|
397
400
|
}
|
|
398
401
|
// Display files go to PG with the staging row; skills and templates need object storage, which a
|
|
399
402
|
// bootstrap import never has (the object store may be a bootstrap plugin itself). A file that is
|
|
@@ -850,7 +853,7 @@ let PluginImport = class PluginImport {
|
|
|
850
853
|
// A foreseeable deploy failure (a downgrade to a version with unrun migrations) is refused
|
|
851
854
|
// before anything is written
|
|
852
855
|
if (now.action === "upgrade" && stored) {
|
|
853
|
-
await assertDowngradable(t, now, stored.migrationSql);
|
|
856
|
+
await assertDowngradable(t, now, stored.migrationSql, this.extensionDbIdentity, this.config.get().db.connectTimeoutMs);
|
|
854
857
|
}
|
|
855
858
|
if (now.action === "install" || now.action === "upgrade") {
|
|
856
859
|
previous = await this.approve(actor, review, staged, now, stored, opts);
|
|
@@ -1587,16 +1590,17 @@ PluginImport = __decorate([
|
|
|
1587
1590
|
__param(4, Inject(PluginApproveLock)),
|
|
1588
1591
|
__param(5, Inject(CatalogItemLock)),
|
|
1589
1592
|
__param(6, Inject(KernelConfigService)),
|
|
1590
|
-
__param(7, Inject(
|
|
1591
|
-
__param(8, Inject(
|
|
1592
|
-
__param(9, Inject(
|
|
1593
|
-
__param(10, Inject(
|
|
1594
|
-
__param(11, Inject(
|
|
1595
|
-
__param(12, Inject(
|
|
1596
|
-
__param(13, Inject(
|
|
1597
|
-
__param(14, Inject(
|
|
1598
|
-
__param(15, Inject(
|
|
1599
|
-
__param(16, Inject(
|
|
1593
|
+
__param(7, Inject(ConfiguredExtensionDbIdentity)),
|
|
1594
|
+
__param(8, Inject(StorageService)),
|
|
1595
|
+
__param(9, Inject(ExtensionInstalls)),
|
|
1596
|
+
__param(10, Inject(ExtensionAdminOps)),
|
|
1597
|
+
__param(11, Inject(ExtensionAdmin)),
|
|
1598
|
+
__param(12, Inject(ExtensionBlobs)),
|
|
1599
|
+
__param(13, Inject(ExtensionRegistry)),
|
|
1600
|
+
__param(14, Inject(KERNEL_LOGGER)),
|
|
1601
|
+
__param(15, Inject(TransactionHost)),
|
|
1602
|
+
__param(16, Inject(PlatformComponents)),
|
|
1603
|
+
__param(17, Inject(OutboxService))
|
|
1600
1604
|
], PluginImport);
|
|
1601
1605
|
export { PluginImport };
|
|
1602
1606
|
/**
|
|
@@ -1729,12 +1733,12 @@ function reviewClient(pkg) {
|
|
|
1729
1733
|
* rule as `ExtensionAdminOps.install`: extension migrations are expand-only, a downgrade can only go
|
|
1730
1734
|
* back to a version whose migrations have all run).
|
|
1731
1735
|
*/
|
|
1732
|
-
async function assertDowngradable(db, p, migrationSql) {
|
|
1736
|
+
async function assertDowngradable(db, p, migrationSql, identity, connectTimeoutMs) {
|
|
1733
1737
|
if (p.action !== "upgrade" || p.currentVersion === null)
|
|
1734
1738
|
return;
|
|
1735
1739
|
if (!semver.valid(p.currentVersion) || !semver.lt(p.version, p.currentVersion))
|
|
1736
1740
|
return;
|
|
1737
|
-
const unrun = await unrunMigrations(db, p.name, migrationSql);
|
|
1741
|
+
const unrun = await unrunMigrations(db, p.name, migrationSql, identity.resolve(p.name), connectTimeoutMs);
|
|
1738
1742
|
if (unrun.length > 0) {
|
|
1739
1743
|
throw new ApiError("extension.downgrade_unsupported", `The plugin's extension ${p.name} ${p.version} is older than the installed ${p.currentVersion}, and that version has migrations that were never run here (${unrun.join(", ")}); extension migrations only expand, so this downgrade is not possible`, unrun.map((file) => ({ file })));
|
|
1740
1744
|
}
|
package/dist/config/schema.d.ts
CHANGED
|
@@ -69,6 +69,7 @@ export declare const KernelConfigSchema: z.ZodObject<{
|
|
|
69
69
|
url: z.ZodString;
|
|
70
70
|
migrationUrl: z.ZodOptional<z.ZodString>;
|
|
71
71
|
extensionsUrl: z.ZodOptional<z.ZodString>;
|
|
72
|
+
extensionPoolMax: z.ZodDefault<z.ZodNumber>;
|
|
72
73
|
poolMax: z.ZodDefault<z.ZodNumber>;
|
|
73
74
|
connectTimeoutMs: z.ZodDefault<z.ZodNumber>;
|
|
74
75
|
idleTimeoutMs: z.ZodDefault<z.ZodNumber>;
|
package/dist/config/schema.js
CHANGED
|
@@ -344,6 +344,14 @@ export const KernelConfigSchema = z.strictObject({
|
|
|
344
344
|
secret: true,
|
|
345
345
|
description: "PostgreSQL connection URL for the shared extension login",
|
|
346
346
|
})),
|
|
347
|
+
extensionPoolMax: z
|
|
348
|
+
.number()
|
|
349
|
+
.int()
|
|
350
|
+
.positive()
|
|
351
|
+
.default(2)
|
|
352
|
+
.meta(meta({
|
|
353
|
+
description: "Maximum PostgreSQL connections per active extension instance with a separate login",
|
|
354
|
+
})),
|
|
347
355
|
poolMax: z
|
|
348
356
|
.number()
|
|
349
357
|
.int()
|
package/dist/ctx/create-ctx.d.ts
CHANGED
|
@@ -2,6 +2,7 @@ import { type EmbedClaims, type ExtensionContext, type ExtensionManifest, type E
|
|
|
2
2
|
import type { Redis } from "ioredis";
|
|
3
3
|
import { Kysely } from "kysely";
|
|
4
4
|
import type { TriggerEventsService } from "../automations/events/trigger-events.service.js";
|
|
5
|
+
import { pluginSchemaName } from "../db/extension-db.js";
|
|
5
6
|
import type { DeviceAccessService } from "../device-access/device-access.service.js";
|
|
6
7
|
import type { DialInAccess } from "../dial-in/access.js";
|
|
7
8
|
import { type RegisteredHook } from "../extensions/hooks.js";
|
|
@@ -20,6 +21,7 @@ import { type UiActionHandler, type UiQueryHandler, type UiRender } from "../ui/
|
|
|
20
21
|
import { type BusSubscriber } from "./bus.js";
|
|
21
22
|
import { type ExtensionNetServices } from "./net.js";
|
|
22
23
|
import { type Keyring } from "./secrets.js";
|
|
24
|
+
export { pluginSchemaName };
|
|
23
25
|
/** 内核提供给插件宿主的共享依赖。 */
|
|
24
26
|
export interface KernelDeps {
|
|
25
27
|
db: Kysely<any>;
|
|
@@ -184,8 +186,6 @@ export declare function currentOrgRole(db: KernelDeps["db"], plugin: string, org
|
|
|
184
186
|
* token and the platform refresh stream re-check.
|
|
185
187
|
*/
|
|
186
188
|
export declare function currentPlatformAccount(db: KernelDeps["db"], accountId: string): Promise<boolean>;
|
|
187
|
-
/** 插件的 PG schema 名:`plugin_<name>`,name 中的 `-` 换成 `_`。 */
|
|
188
|
-
export declare function pluginSchemaName(name: string): string;
|
|
189
189
|
/** What {@link resolveUiSlots} returns for a manifest. */
|
|
190
190
|
export type UiResolution = ReturnType<typeof resolveUiSlots>;
|
|
191
191
|
/** 内核视角的插件 ctx:插件契约之外还带宿主要用的登记信息与关闭方法。 */
|
|
@@ -272,4 +272,5 @@ export declare function createExtensionContext(deps: KernelDeps, manifest: Exten
|
|
|
272
272
|
/** The package this instance was loaded from (null: not from an install record). */
|
|
273
273
|
identity?: {
|
|
274
274
|
sha256: string | null;
|
|
275
|
+
db?: Kysely<any>;
|
|
275
276
|
}): KernelExtensionContext;
|
package/dist/ctx/create-ctx.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { CtxReadError, DEVICE_PROVIDER_EXTENSION_POINT, DeviceAccessError, EXTENSION_POINTS, ExtensionPermissionError, ExtensionPointUnavailableError, FILE_PREVIEW_EXTENSION_POINT, InboxError, OBJECT_STORE_EXTENSION_POINT, parseExtensionPoint, resolveUiSlots, SETUP_CHECK_ID_RE, SETUP_GUIDE_PLACES, TriggerError, validateFilePreviewProvider, validateToolSpec, } from "@capybara-hq/plugin-sdk";
|
|
2
2
|
import { Command, ConnectionBuilder, ControlledTransactionBuilder, Kysely, TransactionBuilder, } from "kysely";
|
|
3
3
|
import { conversationTopic } from "../conversations/event-log.js";
|
|
4
|
+
import { pluginSchemaName } from "../db/extension-db.js";
|
|
4
5
|
import { kernelDb } from "../db/kernel-schema.js";
|
|
5
6
|
import { ApiError } from "../errors.js";
|
|
6
7
|
import { enabledExtensionsQuery, isExtensionEnabled } from "../extensions/enabled.js";
|
|
@@ -18,6 +19,7 @@ import { createLock } from "./lock.js";
|
|
|
18
19
|
import { createExtensionNet } from "./net.js";
|
|
19
20
|
import { createQueue } from "./queue.js";
|
|
20
21
|
import { createSecrets } from "./secrets.js";
|
|
22
|
+
export { pluginSchemaName };
|
|
21
23
|
/**
|
|
22
24
|
* A plain-data copy of an emitted event, taken once at the ctx boundary (check-then-use): every
|
|
23
25
|
* own enumerable field is read once (a getter cannot change a value after it was validated),
|
|
@@ -138,10 +140,6 @@ async function recordDenial(deps, plugin, item) {
|
|
|
138
140
|
deps.log.warn("plugin permission denial audit failed", { plugin, item, err: e });
|
|
139
141
|
}
|
|
140
142
|
}
|
|
141
|
-
/** 插件的 PG schema 名:`plugin_<name>`,name 中的 `-` 换成 `_`。 */
|
|
142
|
-
export function pluginSchemaName(name) {
|
|
143
|
-
return `plugin_${name.replaceAll("-", "_")}`;
|
|
144
|
-
}
|
|
145
143
|
/**
|
|
146
144
|
* 包装插件拿到的 Kysely:`destroy`(及 `Symbol.asyncDispose`)换成抛错的函数(连接池归内核所有,插件销毁会拖垮整个进程的 DB 访问),
|
|
147
145
|
* 其余属性透传。方法绑定到原对象(Kysely 用私有字段,以 Proxy 作 this 调用会失败)。
|
|
@@ -763,7 +761,7 @@ identity = { sha256: null }) {
|
|
|
763
761
|
},
|
|
764
762
|
add: queue.add,
|
|
765
763
|
},
|
|
766
|
-
db: guardDb(deps.db.withSchema(pluginSchemaName(name)), name),
|
|
764
|
+
db: guardDb((identity.db ?? deps.db).withSchema(pluginSchemaName(name)), name),
|
|
767
765
|
http: {
|
|
768
766
|
route(method, path, handler) {
|
|
769
767
|
if (typeof path !== "string" || !path.startsWith("/")) {
|
|
@@ -1037,8 +1035,13 @@ identity = { sha256: null }) {
|
|
|
1037
1035
|
key: r.key,
|
|
1038
1036
|
err,
|
|
1039
1037
|
}));
|
|
1040
|
-
|
|
1041
|
-
|
|
1038
|
+
try {
|
|
1039
|
+
await queue.close();
|
|
1040
|
+
await Promise.allSettled([...audits]);
|
|
1041
|
+
}
|
|
1042
|
+
finally {
|
|
1043
|
+
await identity.db?.destroy();
|
|
1044
|
+
}
|
|
1042
1045
|
})();
|
|
1043
1046
|
return closing;
|
|
1044
1047
|
},
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import pg from "pg";
|
|
2
|
+
import type { KernelConfig } from "../config/schema.js";
|
|
3
|
+
import { KernelConfigService } from "../infra/config/kernel-config.service.js";
|
|
4
|
+
export type ExtensionDbConnection = {
|
|
5
|
+
login: string;
|
|
6
|
+
url: string;
|
|
7
|
+
separate: boolean;
|
|
8
|
+
};
|
|
9
|
+
/** Kernel-owned credentials, resolved from the canonical extension name. */
|
|
10
|
+
export interface ExtensionDbIdentity {
|
|
11
|
+
resolve(name: string): ExtensionDbConnection;
|
|
12
|
+
readonly sharedLogin?: string | undefined;
|
|
13
|
+
}
|
|
14
|
+
export declare class ConfiguredExtensionDbIdentity implements ExtensionDbIdentity {
|
|
15
|
+
private readonly identity;
|
|
16
|
+
constructor(config: KernelConfigService);
|
|
17
|
+
get sharedLogin(): string | undefined;
|
|
18
|
+
resolve(name: string): ExtensionDbConnection;
|
|
19
|
+
}
|
|
20
|
+
export declare function extensionDbIdentity(db: Pick<KernelConfig["db"], "url" | "extensionsUrl">): ExtensionDbIdentity;
|
|
21
|
+
export declare function pluginSchemaName(name: string): string;
|
|
22
|
+
export declare function assertExtensionSession(client: pg.ClientBase, login: string): Promise<void>;
|
|
23
|
+
/** A missing schema is normal before a plugin's first migration. */
|
|
24
|
+
export declare function assertExtensionSchemaOwner(client: pg.ClientBase, schema: string, login: string): Promise<void>;
|
|
25
|
+
/** One small, scope-aware pool per active extension instance. The host owns its lifetime. */
|
|
26
|
+
export declare function extensionDbPool(identity: ExtensionDbConnection, name: string, config: {
|
|
27
|
+
connectTimeoutMs?: number | undefined;
|
|
28
|
+
rls: KernelConfig["db"]["rls"];
|
|
29
|
+
extensionPoolMax: number;
|
|
30
|
+
}, onError?: (error: Error) => void): import("kysely").Kysely<any>;
|
|
@@ -0,0 +1,91 @@
|
|
|
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 pg from "pg";
|
|
12
|
+
import { KernelConfigService } from "../infra/config/kernel-config.service.js";
|
|
13
|
+
import { createDb } from "./pool.js";
|
|
14
|
+
let ConfiguredExtensionDbIdentity = class ConfiguredExtensionDbIdentity {
|
|
15
|
+
identity;
|
|
16
|
+
constructor(config) {
|
|
17
|
+
this.identity = extensionDbIdentity(config.get().db);
|
|
18
|
+
}
|
|
19
|
+
get sharedLogin() {
|
|
20
|
+
return this.identity.sharedLogin;
|
|
21
|
+
}
|
|
22
|
+
resolve(name) {
|
|
23
|
+
return this.identity.resolve(name);
|
|
24
|
+
}
|
|
25
|
+
};
|
|
26
|
+
ConfiguredExtensionDbIdentity = __decorate([
|
|
27
|
+
Injectable(),
|
|
28
|
+
__param(0, Inject(KernelConfigService))
|
|
29
|
+
], ConfiguredExtensionDbIdentity);
|
|
30
|
+
export { ConfiguredExtensionDbIdentity };
|
|
31
|
+
export function extensionDbIdentity(db) {
|
|
32
|
+
const url = db.extensionsUrl ?? db.url;
|
|
33
|
+
const separate = db.extensionsUrl !== undefined;
|
|
34
|
+
let login;
|
|
35
|
+
try {
|
|
36
|
+
login = new pg.Client({ connectionString: url }).user;
|
|
37
|
+
}
|
|
38
|
+
catch {
|
|
39
|
+
throw new Error("Invalid PostgreSQL connection URL for extensions");
|
|
40
|
+
}
|
|
41
|
+
if (!login)
|
|
42
|
+
throw new Error("PostgreSQL connection needs a login");
|
|
43
|
+
return { sharedLogin: separate ? login : undefined, resolve: () => ({ login, url, separate }) };
|
|
44
|
+
}
|
|
45
|
+
export function pluginSchemaName(name) {
|
|
46
|
+
return `plugin_${name.replaceAll("-", "_")}`;
|
|
47
|
+
}
|
|
48
|
+
const extensionLoginCheck = `
|
|
49
|
+
select r.rolcanlogin and not (r.rolsuper or r.rolbypassrls or r.rolcreaterole or r.rolreplication or r.rolcreatedb)
|
|
50
|
+
and not exists (select from pg_catalog.pg_auth_members where member = r.oid)
|
|
51
|
+
and not coalesce((
|
|
52
|
+
select pg_catalog.has_schema_privilege(r.oid, n.oid, 'USAGE,CREATE')
|
|
53
|
+
from pg_catalog.pg_namespace n where n.nspname = 'capybara'
|
|
54
|
+
), true)
|
|
55
|
+
and not coalesce((
|
|
56
|
+
select pg_catalog.has_schema_privilege(r.oid, n.oid, 'CREATE')
|
|
57
|
+
from pg_catalog.pg_namespace n where n.nspname = 'public'
|
|
58
|
+
), false) as isolated
|
|
59
|
+
from pg_catalog.pg_roles r where r.rolname = $1
|
|
60
|
+
`;
|
|
61
|
+
export async function assertExtensionSession(client, login) {
|
|
62
|
+
const { rows: [actual], } = await client.query("select current_user as login");
|
|
63
|
+
const { rows: [role], } = await client.query(extensionLoginCheck, [login]);
|
|
64
|
+
if (actual?.login !== login || !role?.isolated) {
|
|
65
|
+
throw new Error("db.extensionsUrl must authenticate as a restricted extension login with no access to capybara");
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
/** A missing schema is normal before a plugin's first migration. */
|
|
69
|
+
export async function assertExtensionSchemaOwner(client, schema, login) {
|
|
70
|
+
const { rows: [namespace], } = await client.query(`select pg_catalog.pg_get_userbyid(nspowner) as owner
|
|
71
|
+
from pg_catalog.pg_namespace where nspname = $1`, [schema]);
|
|
72
|
+
if (namespace && namespace.owner !== login) {
|
|
73
|
+
throw new Error(`Extension schema ${schema} is owned by ${namespace.owner}, expected ${login}. Run capybara migrate with the owner URL to transfer plugin schemas.`);
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
/** One small, scope-aware pool per active extension instance. The host owns its lifetime. */
|
|
77
|
+
export function extensionDbPool(identity, name, config, onError) {
|
|
78
|
+
// Names come from validated manifests. Quote regardless so review and maintenance paths are safe too.
|
|
79
|
+
const schema = pluginSchemaName(name);
|
|
80
|
+
const searchPath = `"${schema.replaceAll('"', '""')}", public`;
|
|
81
|
+
return createDb(identity.url, config.extensionPoolMax, onError, {
|
|
82
|
+
connectTimeoutMs: config.connectTimeoutMs,
|
|
83
|
+
rls: config.rls,
|
|
84
|
+
closeActiveOnDestroy: true,
|
|
85
|
+
onConnect: async (client) => {
|
|
86
|
+
await assertExtensionSession(client, identity.login);
|
|
87
|
+
await assertExtensionSchemaOwner(client, schema, identity.login);
|
|
88
|
+
await client.query("select pg_catalog.set_config('search_path', $1, false)", [searchPath]);
|
|
89
|
+
},
|
|
90
|
+
});
|
|
91
|
+
}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import { type ExtensionDbIdentity } from "./extension-db.js";
|
|
2
|
+
/**
|
|
3
|
+
* One-shot cutover. The URL authenticates the bootstrap/legacy login, which must be able
|
|
4
|
+
* to transfer ownership. Run before starting replicas with the new extension identity.
|
|
5
|
+
*/
|
|
6
|
+
export declare function transferKnownExtensionSchemas(bootstrapUrl: string, identity: ExtensionDbIdentity, declaredNames: Iterable<string>, connectTimeoutMs?: number): Promise<void>;
|
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
import { EXTENSION_NAME_RE } from "@capybara-hq/plugin-sdk";
|
|
2
|
+
import pg from "pg";
|
|
3
|
+
import { assertExtensionSession, pluginSchemaName, } from "./extension-db.js";
|
|
4
|
+
import { assertSameMigrationDatabase, lockMigrationSchema } from "./migrator.js";
|
|
5
|
+
import { pgConnectOptions } from "./pool.js";
|
|
6
|
+
async function transferExtensionSchema(client, schema, target, sources) {
|
|
7
|
+
await lockMigrationSchema(client, schema, "transaction");
|
|
8
|
+
const { rows: [namespace], } = await client.query(`select oid, pg_catalog.pg_get_userbyid(nspowner) as owner
|
|
9
|
+
from pg_catalog.pg_namespace where nspname = $1`, [schema]);
|
|
10
|
+
if (!namespace)
|
|
11
|
+
return;
|
|
12
|
+
if (namespace.owner !== target && !sources.has(namespace.owner)) {
|
|
13
|
+
throw new Error(`Unexpected owner ${namespace.owner} for extension schema ${schema}`);
|
|
14
|
+
}
|
|
15
|
+
const { rows: objects } = await client.query(`
|
|
16
|
+
with objects(classid, objid) as (
|
|
17
|
+
select 'pg_class'::regclass::oid, oid from pg_class
|
|
18
|
+
where relnamespace = $1::oid and relkind in ('r', 'p', 'v', 'm', 'S', 'f')
|
|
19
|
+
union
|
|
20
|
+
select 'pg_proc'::regclass::oid, oid from pg_proc where pronamespace = $1::oid
|
|
21
|
+
union
|
|
22
|
+
select d.classid, d.objid from pg_depend d
|
|
23
|
+
where d.refclassid = 'pg_namespace'::regclass and d.refobjid = $1::oid
|
|
24
|
+
and d.objsubid = 0 and d.deptype = 'n' and d.classid <> 'pg_extension'::regclass
|
|
25
|
+
)
|
|
26
|
+
select object.identity,
|
|
27
|
+
case
|
|
28
|
+
when c.relkind in ('r', 'p') then 'TABLE'
|
|
29
|
+
when c.relkind = 'v' then 'VIEW'
|
|
30
|
+
when c.relkind = 'm' then 'MATERIALIZED VIEW'
|
|
31
|
+
when c.relkind = 'f' then 'FOREIGN TABLE'
|
|
32
|
+
when c.relkind = 'S' then 'SEQUENCE'
|
|
33
|
+
when p.oid is not null then 'ROUTINE'
|
|
34
|
+
when t.typtype = 'd' then 'DOMAIN'
|
|
35
|
+
when t.oid is not null then 'TYPE'
|
|
36
|
+
end as kind,
|
|
37
|
+
pg_get_userbyid(coalesce(c.relowner, p.proowner, t.typowner)) as owner,
|
|
38
|
+
c.relkind = 'S' and exists (
|
|
39
|
+
select from pg_depend d where d.classid = 'pg_class'::regclass and d.objid = c.oid
|
|
40
|
+
and d.refclassid = 'pg_class'::regclass and d.deptype in ('a', 'i')
|
|
41
|
+
) as attached_sequence,
|
|
42
|
+
exists (
|
|
43
|
+
select from pg_depend d where d.classid = o.classid and d.objid = o.objid
|
|
44
|
+
and d.objsubid = 0 and d.refclassid = 'pg_extension'::regclass and d.deptype = 'e'
|
|
45
|
+
) as extension_member
|
|
46
|
+
from objects o
|
|
47
|
+
cross join lateral pg_identify_object(o.classid, o.objid, 0) object
|
|
48
|
+
left join pg_class c on o.classid = 'pg_class'::regclass and c.oid = o.objid
|
|
49
|
+
left join pg_proc p on o.classid = 'pg_proc'::regclass and p.oid = o.objid
|
|
50
|
+
left join pg_type t on o.classid = 'pg_type'::regclass and t.oid = o.objid
|
|
51
|
+
order by object.identity
|
|
52
|
+
`, [namespace.oid]);
|
|
53
|
+
const unexpected = objects.filter((object) => !object.kind ||
|
|
54
|
+
object.extension_member ||
|
|
55
|
+
(object.owner !== target && object.owner !== namespace.owner));
|
|
56
|
+
if (unexpected.length) {
|
|
57
|
+
const names = unexpected.map((object) => `${object.identity} (owner ${object.owner ?? "unknown"})`);
|
|
58
|
+
throw new Error(`Unexpected objects in extension schema ${schema}: ${names.join(", ")}`);
|
|
59
|
+
}
|
|
60
|
+
const quotedTarget = pg.escapeIdentifier(target);
|
|
61
|
+
if (namespace.owner !== target) {
|
|
62
|
+
await client.query(`alter schema ${pg.escapeIdentifier(schema)} owner to ${quotedTarget}`);
|
|
63
|
+
}
|
|
64
|
+
// PostgreSQL moves table-owned sequences, row types and indexes with their parent table.
|
|
65
|
+
for (const object of objects) {
|
|
66
|
+
if (object.kind && object.owner !== target && !object.attached_sequence) {
|
|
67
|
+
// Kind is from the fixed catalog mapping. PostgreSQL returns the quoted object identity.
|
|
68
|
+
await client.query(`alter ${object.kind} ${object.identity} owner to ${quotedTarget}`);
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
async function confirmTargetDatabase(owner, target, connectTimeoutMs) {
|
|
73
|
+
const client = new pg.Client({
|
|
74
|
+
connectionString: target.url,
|
|
75
|
+
...pgConnectOptions({ connectTimeoutMs }),
|
|
76
|
+
});
|
|
77
|
+
client.on("error", () => { });
|
|
78
|
+
try {
|
|
79
|
+
await client.connect();
|
|
80
|
+
await assertExtensionSession(client, target.login);
|
|
81
|
+
await assertSameMigrationDatabase(owner, client);
|
|
82
|
+
}
|
|
83
|
+
catch (cause) {
|
|
84
|
+
throw new Error(`Cannot verify extension database login ${target.login}. Check db.extensionsUrl and use the same database as db.url.`, { cause });
|
|
85
|
+
}
|
|
86
|
+
finally {
|
|
87
|
+
await client.end();
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
/**
|
|
91
|
+
* One-shot cutover. The URL authenticates the bootstrap/legacy login, which must be able
|
|
92
|
+
* to transfer ownership. Run before starting replicas with the new extension identity.
|
|
93
|
+
*/
|
|
94
|
+
export async function transferKnownExtensionSchemas(bootstrapUrl, identity, declaredNames, connectTimeoutMs) {
|
|
95
|
+
const owner = new pg.Client({
|
|
96
|
+
connectionString: bootstrapUrl,
|
|
97
|
+
...pgConnectOptions({ connectTimeoutMs }),
|
|
98
|
+
});
|
|
99
|
+
owner.on("error", () => { });
|
|
100
|
+
try {
|
|
101
|
+
await owner.connect();
|
|
102
|
+
await owner.query("begin");
|
|
103
|
+
try {
|
|
104
|
+
await owner.query("set local search_path = pg_catalog");
|
|
105
|
+
await owner.query("set local lock_timeout = '30s'");
|
|
106
|
+
const { rows: [legacy], } = await owner.query("select current_user as login");
|
|
107
|
+
if (!legacy)
|
|
108
|
+
throw new Error("Could not verify the schema transfer login");
|
|
109
|
+
const { rows: registered } = await owner.query(`select name from capybara.extension_name_owners
|
|
110
|
+
union select name from capybara.extension_installs`);
|
|
111
|
+
const names = new Set([...declaredNames, ...registered.map((row) => row.name)]);
|
|
112
|
+
const resolved = [...names].sort().map((name) => {
|
|
113
|
+
if (!EXTENSION_NAME_RE.test(name))
|
|
114
|
+
throw new Error(`Invalid extension name: ${name}`);
|
|
115
|
+
return { schema: pluginSchemaName(name), target: identity.resolve(name) };
|
|
116
|
+
});
|
|
117
|
+
const sources = new Set([legacy.login, ...resolved.map(({ target }) => target.login)]);
|
|
118
|
+
if (identity.sharedLogin !== undefined)
|
|
119
|
+
sources.add(identity.sharedLogin);
|
|
120
|
+
const targets = resolved.filter(({ target }) => target.separate);
|
|
121
|
+
const validated = new Set();
|
|
122
|
+
for (const { target } of targets) {
|
|
123
|
+
if (validated.has(target.url))
|
|
124
|
+
continue;
|
|
125
|
+
await confirmTargetDatabase(owner, target, connectTimeoutMs);
|
|
126
|
+
validated.add(target.url);
|
|
127
|
+
}
|
|
128
|
+
for (const { schema, target } of targets) {
|
|
129
|
+
await transferExtensionSchema(owner, schema, target.login, sources);
|
|
130
|
+
}
|
|
131
|
+
await owner.query("commit");
|
|
132
|
+
}
|
|
133
|
+
catch (error) {
|
|
134
|
+
await owner.query("rollback").catch(() => { });
|
|
135
|
+
throw error;
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
finally {
|
|
139
|
+
await owner.end();
|
|
140
|
+
}
|
|
141
|
+
}
|
|
@@ -519,8 +519,8 @@ export type ConversationKind = "chat" | "eval" | "subagent";
|
|
|
519
519
|
/** 0006_conversations.sql: append-only conversation event log. */
|
|
520
520
|
export interface ConversationEventsTable {
|
|
521
521
|
conversation_id: string;
|
|
522
|
-
/**
|
|
523
|
-
org_id:
|
|
522
|
+
/** Owning org, enforced by the composite foreign key to conversations. */
|
|
523
|
+
org_id: string;
|
|
524
524
|
seq: Int8;
|
|
525
525
|
type: string;
|
|
526
526
|
run_id: string | null;
|
|
@@ -708,8 +708,6 @@ export interface ConnectorToolsTable {
|
|
|
708
708
|
spec_hash: string;
|
|
709
709
|
status: "enabled" | "disabled" | "pending_review";
|
|
710
710
|
default_policy: "allow" | "ask" | "deny";
|
|
711
|
-
/** Retained for the rc.157 rollout. The next contract drops this column. */
|
|
712
|
-
declaration_policy: ColumnType<null, never, never>;
|
|
713
711
|
reviewed_at: TsNullable;
|
|
714
712
|
/** 0013:工具来源(`resources` = 内核为支持 resources 的连接器补上的两个工具)。 */
|
|
715
713
|
source: Generated<"connector" | "resources">;
|
package/dist/db/migrator.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { type QueryExecutorProvider } from "kysely";
|
|
2
|
+
import pg from "pg";
|
|
2
3
|
/** 迁移文件名:`NNNN_<snake_desc>.sql`(其他文件忽略)。 */
|
|
3
4
|
export declare const MIGRATION_FILE_RE: RegExp;
|
|
4
5
|
/** 迁移器所有者:目标 schema 与迁移文件目录。 */
|
|
@@ -6,6 +7,9 @@ export interface MigrationOwner {
|
|
|
6
7
|
schema: string;
|
|
7
8
|
dir: string;
|
|
8
9
|
}
|
|
10
|
+
export declare function lockMigrationSchema(client: pg.ClientBase, schema: string, scope: "session" | "transaction"): Promise<void>;
|
|
11
|
+
/** A held two-key lock conflicts only with sessions in the same database. */
|
|
12
|
+
export declare function assertSameMigrationDatabase(owner: pg.ClientBase, extension: pg.ClientBase): Promise<void>;
|
|
9
13
|
export declare function canMigrateKernel(db: QueryExecutorProvider): Promise<boolean>;
|
|
10
14
|
/** Verify the files expected by this binary without taking a migration lock or writing the journal.
|
|
11
15
|
* Extra entries are valid when a newer release has already migrated a shared database.
|
|
@@ -25,6 +29,8 @@ export declare function verifyMigrations(db: QueryExecutorProvider, { schema, di
|
|
|
25
29
|
export declare function migrate(connectionString: string, owner: MigrationOwner, opts?: {
|
|
26
30
|
connectTimeoutMs?: number | undefined;
|
|
27
31
|
signal?: AbortSignal | undefined;
|
|
32
|
+
/** Verify the effective PostgreSQL role before running an isolated extension migration. */
|
|
33
|
+
extensionLogin?: string | undefined;
|
|
28
34
|
/** 迁移会话的 `statement_timeout`(毫秒);不给不设。 */
|
|
29
35
|
statementTimeoutMs?: number | undefined;
|
|
30
36
|
/** 迁移会话的 `lock_timeout`(毫秒,含按 schema 的咨询锁);不给不设。 */
|
package/dist/db/migrator.js
CHANGED
|
@@ -1,13 +1,38 @@
|
|
|
1
|
-
import { createHash } from "node:crypto";
|
|
1
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
2
2
|
import { readdir, readFile } from "node:fs/promises";
|
|
3
3
|
import { join } from "node:path";
|
|
4
4
|
import { sql } from "kysely";
|
|
5
5
|
import pg from "pg";
|
|
6
|
+
import { assertExtensionSchemaOwner, assertExtensionSession } from "./extension-db.js";
|
|
6
7
|
import { pgConnectOptions } from "./pool.js";
|
|
7
8
|
/** 迁移文件名:`NNNN_<snake_desc>.sql`(其他文件忽略)。 */
|
|
8
9
|
export const MIGRATION_FILE_RE = /^\d{4}_[a-z0-9_]+\.sql$/;
|
|
10
|
+
// Keep this local to each extension schema so its login never needs USAGE on capybara.
|
|
11
|
+
const extensionRlsPredicate = `
|
|
12
|
+
create or replace function rls_admits(row_org text) returns boolean
|
|
13
|
+
language sql stable parallel safe as $$
|
|
14
|
+
select coalesce(pg_catalog.current_setting('capybara.rls', true), '') <> 'enforce'
|
|
15
|
+
or pg_catalog.current_setting('capybara.scope', true) = 'platform'
|
|
16
|
+
or row_org = pg_catalog.current_setting('capybara.org_id', true)
|
|
17
|
+
$$
|
|
18
|
+
`;
|
|
9
19
|
const ident = (s) => `"${s.replaceAll('"', '""')}"`;
|
|
10
20
|
const num = (name) => Number.parseInt(name.slice(0, 4), 10);
|
|
21
|
+
export async function lockMigrationSchema(client, schema, scope) {
|
|
22
|
+
const lock = scope === "session" ? "pg_advisory_lock" : "pg_advisory_xact_lock";
|
|
23
|
+
await client.query(`select pg_catalog.${lock}(pg_catalog.hashtext($1))`, [
|
|
24
|
+
`capybara-migrate:${schema}`,
|
|
25
|
+
]);
|
|
26
|
+
}
|
|
27
|
+
/** A held two-key lock conflicts only with sessions in the same database. */
|
|
28
|
+
export async function assertSameMigrationDatabase(owner, extension) {
|
|
29
|
+
const challenge = randomBytes(8);
|
|
30
|
+
const keys = [challenge.readInt32BE(0), challenge.readInt32BE(4)];
|
|
31
|
+
await owner.query("select pg_catalog.pg_advisory_xact_lock($1::int, $2::int)", keys);
|
|
32
|
+
const { rows: [lock], } = await extension.query("select pg_catalog.pg_try_advisory_xact_lock($1::int, $2::int) as acquired", keys);
|
|
33
|
+
if (lock?.acquired !== false)
|
|
34
|
+
throw new Error("The extension URL points to another database");
|
|
35
|
+
}
|
|
11
36
|
async function migrationFiles(dir) {
|
|
12
37
|
const names = (await readdir(dir)).filter((file) => MIGRATION_FILE_RE.test(file)).sort();
|
|
13
38
|
return Promise.all(names.map(async (name) => {
|
|
@@ -121,15 +146,18 @@ export async function migrate(connectionString, owner, opts = {}) {
|
|
|
121
146
|
signal?.addEventListener("abort", onAbort, { once: true });
|
|
122
147
|
try {
|
|
123
148
|
await client.connect();
|
|
149
|
+
if (opts.extensionLogin !== undefined)
|
|
150
|
+
await assertExtensionSession(client, opts.extensionLogin);
|
|
124
151
|
if (opts.statementTimeoutMs !== undefined) {
|
|
125
152
|
await client.query(`set statement_timeout = ${Math.max(1, Math.floor(opts.statementTimeoutMs))}`);
|
|
126
153
|
}
|
|
127
154
|
if (opts.lockTimeoutMs !== undefined) {
|
|
128
155
|
await client.query(`set lock_timeout = ${Math.max(1, Math.floor(opts.lockTimeoutMs))}`);
|
|
129
156
|
}
|
|
130
|
-
await client
|
|
131
|
-
|
|
132
|
-
|
|
157
|
+
await lockMigrationSchema(client, schema, "session");
|
|
158
|
+
if (opts.extensionLogin !== undefined) {
|
|
159
|
+
await assertExtensionSchemaOwner(client, schema, opts.extensionLogin);
|
|
160
|
+
}
|
|
133
161
|
if (schema === "capybara") {
|
|
134
162
|
const { rows: [privileges], } = await client.query(kernelMigrationPrivileges);
|
|
135
163
|
if (privileges?.has_owner_role && !privileges.owns_schema) {
|
|
@@ -163,6 +191,13 @@ export async function migrate(connectionString, owner, opts = {}) {
|
|
|
163
191
|
try {
|
|
164
192
|
await client.query("begin");
|
|
165
193
|
await client.query(`set local search_path to ${ident(schema)}, public`);
|
|
194
|
+
if (opts.extensionLogin !== undefined) {
|
|
195
|
+
await client.query(`select pg_catalog.set_config('capybara.scope', 'platform', true),
|
|
196
|
+
pg_catalog.set_config('capybara.org_id', '', true),
|
|
197
|
+
pg_catalog.set_config('capybara.rls', 'off', true)`);
|
|
198
|
+
if (applied.length === 0)
|
|
199
|
+
await client.query(extensionRlsPredicate);
|
|
200
|
+
}
|
|
166
201
|
await client.query(f.content);
|
|
167
202
|
await client.query(`insert into ${table} (name, checksum) values ($1, $2)`, [
|
|
168
203
|
f.name,
|
package/dist/db/pool.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { Kysely } from "kysely";
|
|
2
|
+
import pg from "pg";
|
|
2
3
|
import { type RlsMode } from "../infra/database/scoped-dialect.js";
|
|
3
4
|
/** 内核连接池的 PG `application_name`(便于在 pg_stat_activity 中识别)。 */
|
|
4
5
|
export declare const KERNEL_APPLICATION_NAME = "capybara-kernel";
|
|
@@ -34,4 +35,7 @@ export declare function createDb(url: string, poolMax: number, onError?: (err: E
|
|
|
34
35
|
* `scoped-dialect.ts`). Unset = `off`, a plain pool.
|
|
35
36
|
*/
|
|
36
37
|
rls?: RlsMode | undefined;
|
|
38
|
+
onConnect?: (client: pg.ClientBase) => Promise<void>;
|
|
39
|
+
/** The owner has already drained callers and may close any connection they still hold. */
|
|
40
|
+
closeActiveOnDestroy?: boolean;
|
|
37
41
|
}): Kysely<any>;
|