@capybara-hq/kernel 0.1.0-rc.130 → 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/admin/account-erasures.d.ts +37 -0
- package/dist/admin/account-erasures.js +119 -0
- package/dist/admin/admin.controller.d.ts +35 -2
- package/dist/admin/admin.controller.js +75 -18
- package/dist/admin/admin.module.js +10 -0
- package/dist/admin/admin.schemas.d.ts +51 -0
- package/dist/admin/admin.schemas.js +20 -0
- package/dist/admin/erasure-dispositions.d.ts +23 -0
- package/dist/admin/erasure-dispositions.js +76 -0
- package/dist/admin/health.service.d.ts +6 -0
- package/dist/admin/health.service.js +27 -1
- package/dist/admin/usage.service.d.ts +5 -0
- package/dist/admin/usage.service.js +21 -2
- package/dist/agents/agents.service.d.ts +1 -1
- package/dist/catalog/plugin-import.d.ts +3 -1
- package/dist/catalog/plugin-import.js +19 -15
- package/dist/channels/connections.service.d.ts +1 -1
- package/dist/client/client-reports.service.js +12 -0
- package/dist/config/schema.d.ts +9 -1
- package/dist/config/schema.js +51 -1
- package/dist/conversations/conversations.service.d.ts +9 -1
- package/dist/conversations/conversations.service.js +112 -15
- package/dist/conversations/event-log.d.ts +2 -0
- package/dist/conversations/event-log.js +77 -0
- package/dist/conversations/events.d.ts +11 -0
- package/dist/conversations/events.js +13 -1
- package/dist/conversations/prompt-suggestions.js +4 -0
- package/dist/conversations/titles.js +3 -2
- 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 +73 -12
- 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/devices/devices.service.d.ts +13 -1
- package/dist/devices/devices.service.js +122 -9
- package/dist/erasure/account-batches.d.ts +9 -0
- package/dist/erasure/account-batches.js +567 -0
- package/dist/erasure/account-files.d.ts +34 -0
- package/dist/erasure/account-files.js +217 -0
- package/dist/erasure/account-residual.d.ts +15 -0
- package/dist/erasure/account-residual.js +149 -0
- package/dist/erasure/account-worker.d.ts +32 -0
- package/dist/erasure/account-worker.js +392 -0
- package/dist/erasure/device-cleanup.d.ts +23 -0
- package/dist/erasure/device-cleanup.js +221 -0
- package/dist/erasure/erasure.module.d.ts +2 -0
- package/dist/{conversations/event-org-backfill.module.js → erasure/erasure.module.js} +6 -10
- package/dist/erasure/external-evidence.d.ts +4 -0
- package/dist/erasure/external-evidence.js +28 -0
- package/dist/erasure/jobs.d.ts +5 -0
- package/dist/erasure/jobs.js +20 -0
- package/dist/erasure/org-batches.d.ts +11 -0
- package/dist/erasure/org-batches.js +159 -0
- package/dist/erasure/org-catalog.d.ts +2 -0
- package/dist/erasure/org-catalog.js +34 -0
- package/dist/erasure/org-rules.d.ts +14 -0
- package/dist/erasure/org-rules.js +227 -0
- package/dist/erasure/org-worker.d.ts +38 -0
- package/dist/erasure/org-worker.js +501 -0
- package/dist/erasure/requests.d.ts +61 -0
- package/dist/erasure/requests.js +180 -0
- package/dist/erasure/sweep.job.d.ts +19 -0
- package/dist/erasure/sweep.job.js +130 -0
- package/dist/erasure/worker.d.ts +17 -0
- package/dist/erasure/worker.js +110 -0
- package/dist/errors.d.ts +4 -0
- package/dist/errors.js +4 -0
- package/dist/evals/judge.d.ts +5 -0
- package/dist/evals/judge.js +16 -1
- package/dist/evals/run-replay.js +12 -1
- package/dist/evals/step-replay.d.ts +5 -3
- package/dist/evals/step-replay.js +9 -5
- package/dist/evals/worker.d.ts +2 -0
- package/dist/evals/worker.js +60 -16
- 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/files/blob-objects.d.ts +7 -3
- package/dist/files/blob-objects.js +39 -22
- package/dist/files/blob-sweep.job.d.ts +11 -0
- package/dist/files/blob-sweep.job.js +67 -6
- package/dist/http/api.module.js +5 -1
- package/dist/identity/accounts.js +3 -0
- package/dist/identity/api-tokens.js +5 -0
- package/dist/identity/auth.guard.d.ts +1 -0
- package/dist/identity/auth.guard.js +1 -0
- package/dist/identity/erasure-admission.d.ts +3 -0
- package/dist/identity/erasure-admission.js +14 -0
- package/dist/identity/external.js +5 -0
- package/dist/identity/sessions.js +5 -0
- package/dist/identity/settings.d.ts +86 -1
- package/dist/identity/settings.js +38 -4
- package/dist/infra/config/kernel-config.service.js +1 -0
- package/dist/infra/metrics/kernel-metrics.d.ts +18 -0
- package/dist/infra/metrics/kernel-metrics.js +54 -0
- package/dist/infra/metrics/operational-metrics.d.ts +31 -0
- package/dist/infra/metrics/operational-metrics.js +188 -0
- package/dist/infra/outbox/registry.d.ts +23 -14
- package/dist/infra/outbox/registry.js +12 -15
- package/dist/infra/throttler/credential-throttler.js +8 -1
- package/dist/infra/throttler/named-throttlers.d.ts +6 -0
- package/dist/infra/throttler/named-throttlers.js +6 -0
- package/dist/infra/throttler/principal-throttler.guard.d.ts +10 -0
- package/dist/infra/throttler/principal-throttler.guard.js +50 -0
- package/dist/infra/throttler/redis-throttler-storage.d.ts +1 -0
- package/dist/infra/throttler/redis-throttler-storage.js +27 -5
- package/dist/infra/throttler/throttler.guard.d.ts +2 -3
- package/dist/infra/throttler/throttler.guard.js +2 -3
- package/dist/infra/throttler/throttler.module.js +3 -2
- 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/models/budget-admission.d.ts +31 -0
- package/dist/models/budget-admission.js +149 -0
- package/dist/models/budget-counters.d.ts +28 -0
- package/dist/models/budget-counters.js +117 -0
- package/dist/models/budget-policy.d.ts +88 -0
- package/dist/models/budget-policy.js +78 -0
- package/dist/models/embeddings.js +13 -2
- package/dist/models/images.js +12 -2
- package/dist/models/purposes.d.ts +5 -2
- package/dist/models/purposes.js +9 -5
- package/dist/orgs/invitations.service.d.ts +1 -1
- package/dist/orgs/members.service.d.ts +28 -1
- package/dist/orgs/members.service.js +74 -11
- package/dist/orgs/offboarding.js +4 -6
- package/dist/orgs/org-owner.d.ts +2 -0
- package/dist/orgs/org-owner.js +21 -6
- package/dist/orgs/orgs.controller.d.ts +22 -0
- package/dist/orgs/orgs.controller.js +24 -0
- package/dist/orgs/orgs.module.js +4 -0
- package/dist/orgs/orgs.schemas.js +7 -0
- package/dist/orgs/orgs.service.d.ts +5 -1
- package/dist/orgs/orgs.service.js +28 -3
- package/dist/orgs/settings.controller.js +6 -1
- package/dist/orgs/settings.service.d.ts +58 -1
- package/dist/orgs/settings.service.js +74 -9
- package/dist/platform/exclusions.js +20 -1
- package/dist/platform/ops/accounts.ops.js +58 -1
- package/dist/platform/ops/admin.ops.js +13 -5
- package/dist/platform/ops/org-settings.ops.js +11 -4
- package/dist/platform/ops/orgs.ops.js +28 -0
- package/dist/platform/ops/retention.d.ts +16 -0
- package/dist/platform/ops/retention.js +21 -0
- package/dist/retention/jobs.d.ts +21 -0
- package/dist/retention/jobs.js +48 -0
- package/dist/retention/policy.d.ts +70 -0
- package/dist/retention/policy.js +103 -0
- package/dist/retention/purge-batch.d.ts +17 -0
- package/dist/retention/purge-batch.js +355 -0
- package/dist/retention/report-obligations.d.ts +12 -0
- package/dist/retention/report-obligations.js +71 -0
- package/dist/retention/sweep.job.d.ts +17 -0
- package/dist/retention/sweep.job.js +95 -0
- package/dist/retention/worker.d.ts +29 -0
- package/dist/retention/worker.js +306 -0
- package/dist/roles/worker.module.js +12 -8
- package/dist/runtime/maintenance.d.ts +5 -3
- package/dist/runtime/maintenance.js +19 -12
- package/dist/runtime/model-call.d.ts +3 -1
- package/dist/runtime/model-call.js +25 -3
- package/dist/runtime/providers.d.ts +7 -2
- package/dist/runtime/providers.js +76 -10
- package/dist/runtime/quota.d.ts +12 -12
- package/dist/runtime/quota.js +42 -37
- package/dist/runtime/run-finish.js +2 -0
- package/dist/runtime/run-principal.d.ts +9 -0
- package/dist/runtime/run-principal.js +18 -0
- package/dist/runtime/run-worker.js +48 -10
- package/dist/runtime/usage-report-jobs.d.ts +4 -1
- package/dist/runtime/usage-report-jobs.js +36 -13
- package/dist/runtime/usage-report.d.ts +5 -3
- package/dist/runtime/usage-report.js +37 -19
- package/dist/sandbox/review/classifier.d.ts +2 -2
- package/dist/sandbox/review/classifier.js +6 -2
- package/dist/sandbox/sandbox.service.js +18 -7
- package/dist/storage/purge.js +5 -1
- package/dist/storage/storage.service.d.ts +17 -1
- package/dist/storage/storage.service.js +75 -4
- package/dist/tools/builtins/vision/read-image.js +3 -0
- package/dist/tools/builtins/web/extract.js +3 -0
- package/dist/tools/pipeline.js +5 -1
- package/package.json +3 -1
- package/src/migrations/0216_model_budget_counters.sql +24 -0
- package/src/migrations/0217_retention.sql +44 -0
- package/src/migrations/0218_data_erasure.sql +41 -0
- 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
|
@@ -83,6 +83,7 @@ export interface SandboxOperationIntentsTable {
|
|
|
83
83
|
updated_at: Ts;
|
|
84
84
|
}
|
|
85
85
|
export interface AccountsTable {
|
|
86
|
+
erasure_requested: Generated<boolean>;
|
|
86
87
|
id: string;
|
|
87
88
|
display_name: string;
|
|
88
89
|
email: string | null;
|
|
@@ -239,7 +240,7 @@ export interface InvitationsTable {
|
|
|
239
240
|
org_id: string;
|
|
240
241
|
role: "admin" | "member" | "guest";
|
|
241
242
|
token_hash: string;
|
|
242
|
-
created_by: string;
|
|
243
|
+
created_by: string | null;
|
|
243
244
|
created_at: Ts;
|
|
244
245
|
expires_at: ColumnType<Date, Date | string, Date | string>;
|
|
245
246
|
accepted_at: TsNullable;
|
|
@@ -268,7 +269,7 @@ export interface ApiTokensTable {
|
|
|
268
269
|
role: "admin" | "member" | "guest" | null;
|
|
269
270
|
name: string;
|
|
270
271
|
token_hash: string;
|
|
271
|
-
created_by: string;
|
|
272
|
+
created_by: string | null;
|
|
272
273
|
created_at: Ts;
|
|
273
274
|
last_used_at: TsNullable;
|
|
274
275
|
expires_at: TsNullable;
|
|
@@ -380,7 +381,7 @@ export interface AgentVersionsTable {
|
|
|
380
381
|
agent_id: string;
|
|
381
382
|
version: number;
|
|
382
383
|
definition: Json;
|
|
383
|
-
created_by: string;
|
|
384
|
+
created_by: string | null;
|
|
384
385
|
created_at: Ts;
|
|
385
386
|
}
|
|
386
387
|
/** 0005_agents.sql:visibility='members' 的 agent 名单。 */
|
|
@@ -518,8 +519,8 @@ export type ConversationKind = "chat" | "eval" | "subagent";
|
|
|
518
519
|
/** 0006_conversations.sql: append-only conversation event log. */
|
|
519
520
|
export interface ConversationEventsTable {
|
|
520
521
|
conversation_id: string;
|
|
521
|
-
/**
|
|
522
|
-
org_id:
|
|
522
|
+
/** Owning org, enforced by the composite foreign key to conversations. */
|
|
523
|
+
org_id: string;
|
|
523
524
|
seq: Int8;
|
|
524
525
|
type: string;
|
|
525
526
|
run_id: string | null;
|
|
@@ -707,8 +708,6 @@ export interface ConnectorToolsTable {
|
|
|
707
708
|
spec_hash: string;
|
|
708
709
|
status: "enabled" | "disabled" | "pending_review";
|
|
709
710
|
default_policy: "allow" | "ask" | "deny";
|
|
710
|
-
/** Retained for the rc.157 rollout. The next contract drops this column. */
|
|
711
|
-
declaration_policy: ColumnType<null, never, never>;
|
|
712
711
|
reviewed_at: TsNullable;
|
|
713
712
|
/** 0013:工具来源(`resources` = 内核为支持 resources 的连接器补上的两个工具)。 */
|
|
714
713
|
source: Generated<"connector" | "resources">;
|
|
@@ -884,7 +883,7 @@ export interface ChannelConnectionsTable {
|
|
|
884
883
|
* `{ guideId, version, hash, mode }`; null when unknown.
|
|
885
884
|
*/
|
|
886
885
|
guide_ack: ColumnType<GuideAckJson | null, string | null | undefined, string | null>;
|
|
887
|
-
created_by: string;
|
|
886
|
+
created_by: string | null;
|
|
888
887
|
created_at: Ts;
|
|
889
888
|
updated_at: Ts;
|
|
890
889
|
deleted_at: TsNullable;
|
|
@@ -1137,6 +1136,7 @@ type InstanceHandle = ColumnType<{
|
|
|
1137
1136
|
* instance plus a kept file system; a dial-in device's machine signs in (device_machines).
|
|
1138
1137
|
*/
|
|
1139
1138
|
export interface DevicesTable {
|
|
1139
|
+
files_destroyed_at: TsNullable;
|
|
1140
1140
|
id: string;
|
|
1141
1141
|
org_id: string;
|
|
1142
1142
|
owner_kind: "personal";
|
|
@@ -1234,7 +1234,7 @@ export interface DeviceProjectsTable {
|
|
|
1234
1234
|
name: string;
|
|
1235
1235
|
/** The project's absolute path on the device. */
|
|
1236
1236
|
path: string;
|
|
1237
|
-
created_by: string;
|
|
1237
|
+
created_by: string | null;
|
|
1238
1238
|
created_at: Ts;
|
|
1239
1239
|
}
|
|
1240
1240
|
/**
|
|
@@ -1340,7 +1340,7 @@ export interface EvalSetsTable {
|
|
|
1340
1340
|
name: string;
|
|
1341
1341
|
description: ColumnType<string, string | undefined, string>;
|
|
1342
1342
|
rubric: string | null;
|
|
1343
|
-
created_by: string;
|
|
1343
|
+
created_by: string | null;
|
|
1344
1344
|
created_at: Ts;
|
|
1345
1345
|
updated_at: Ts;
|
|
1346
1346
|
deleted_at: TsNullable;
|
|
@@ -1362,7 +1362,7 @@ export interface EvalCasesTable {
|
|
|
1362
1362
|
plan_run: Json<unknown>;
|
|
1363
1363
|
/** 用例原版本的模型(`ModelRef`);没有定义时为 null。 */
|
|
1364
1364
|
base_model: ColumnType<unknown | null, string | null | undefined, string | null>;
|
|
1365
|
-
added_by: string;
|
|
1365
|
+
added_by: string | null;
|
|
1366
1366
|
created_at: Ts;
|
|
1367
1367
|
}
|
|
1368
1368
|
export type EvalRunStatus = "queued" | "running" | "completed" | "cancelled" | "capped" | "failed";
|
|
@@ -1382,7 +1382,7 @@ export interface EvalRunsTable {
|
|
|
1382
1382
|
consecutive_errors: ColumnType<number, number | undefined, number>;
|
|
1383
1383
|
error: ColumnType<unknown | null, string | null | undefined, string | null>;
|
|
1384
1384
|
estimate: Json<unknown>;
|
|
1385
|
-
created_by: string;
|
|
1385
|
+
created_by: string | null;
|
|
1386
1386
|
created_at: Ts;
|
|
1387
1387
|
started_at: TsNullable;
|
|
1388
1388
|
finished_at: TsNullable;
|
|
@@ -1525,6 +1525,24 @@ export interface ModelDisabledTable {
|
|
|
1525
1525
|
disabled_by: string | null;
|
|
1526
1526
|
disabled_at: Ts;
|
|
1527
1527
|
}
|
|
1528
|
+
export interface ModelBudgetUsageTable {
|
|
1529
|
+
org_id: string;
|
|
1530
|
+
period_start: string;
|
|
1531
|
+
bucket: string;
|
|
1532
|
+
tokens: string;
|
|
1533
|
+
amount: string;
|
|
1534
|
+
}
|
|
1535
|
+
export interface ModelBudgetOrgUsageTable extends ModelBudgetUsageTable {
|
|
1536
|
+
shard: number;
|
|
1537
|
+
}
|
|
1538
|
+
export interface ModelBudgetMemberUsageTable extends ModelBudgetUsageTable {
|
|
1539
|
+
account_id: string;
|
|
1540
|
+
}
|
|
1541
|
+
export interface AppliedMigrationTable {
|
|
1542
|
+
name: string;
|
|
1543
|
+
checksum: string;
|
|
1544
|
+
applied_at: Ts;
|
|
1545
|
+
}
|
|
1528
1546
|
/** One model call outside a conversation, e.g. an extension's embed call (0089, spec B §5.4). */
|
|
1529
1547
|
export interface ModelUsageTable {
|
|
1530
1548
|
id: Generated<string>;
|
|
@@ -1921,7 +1939,47 @@ export interface PermissionConfigPublicationTable {
|
|
|
1921
1939
|
projection: Json<PermissionConfigProjection>;
|
|
1922
1940
|
updated_at: Ts;
|
|
1923
1941
|
}
|
|
1942
|
+
export interface UsageReportObligationsTable {
|
|
1943
|
+
org_id: string;
|
|
1944
|
+
job_id: string;
|
|
1945
|
+
}
|
|
1946
|
+
export interface DataErasureRequestsTable {
|
|
1947
|
+
id: Generated<string>;
|
|
1948
|
+
kind: "org" | "account";
|
|
1949
|
+
org_id: string | null;
|
|
1950
|
+
target_id: string | null;
|
|
1951
|
+
generation: Generated<number>;
|
|
1952
|
+
stage: Generated<"pending" | "blocked" | "roots" | "objects" | "rows" | "prefix" | "late" | "account-orgs" | "account-external" | "account-final" | "done">;
|
|
1953
|
+
scope_boundaries: Generated<"third-party-conversation-content"[]>;
|
|
1954
|
+
progress: ColumnType<Record<string, unknown> | null, string | null | undefined, string | null>;
|
|
1955
|
+
blocked_reason: NullableCol<string>;
|
|
1956
|
+
due_at: Ts;
|
|
1957
|
+
completed_at: TsNullable;
|
|
1958
|
+
}
|
|
1959
|
+
export interface RetentionWorkTable {
|
|
1960
|
+
id: Generated<string>;
|
|
1961
|
+
org_id: string | null;
|
|
1962
|
+
kind: "purge" | "org-scan" | "platform-audit";
|
|
1963
|
+
target: string;
|
|
1964
|
+
generation: Generated<number>;
|
|
1965
|
+
state: Generated<"ready" | "blocked" | "done">;
|
|
1966
|
+
cursor_id: NullableText;
|
|
1967
|
+
usage_cursor: NullableText;
|
|
1968
|
+
blocked_reason: NullableText;
|
|
1969
|
+
due_at: Ts;
|
|
1970
|
+
}
|
|
1971
|
+
export interface RetentionCoverageTable {
|
|
1972
|
+
org_id: string;
|
|
1973
|
+
usage_incomplete_since: TsNullable;
|
|
1974
|
+
runs_incomplete_since: TsNullable;
|
|
1975
|
+
usage_incomplete_through: TsNullable;
|
|
1976
|
+
runs_incomplete_through: TsNullable;
|
|
1977
|
+
}
|
|
1924
1978
|
export interface KernelDatabase {
|
|
1979
|
+
data_erasure_requests: DataErasureRequestsTable;
|
|
1980
|
+
retention_work: RetentionWorkTable;
|
|
1981
|
+
usage_report_obligations: UsageReportObligationsTable;
|
|
1982
|
+
retention_coverage: RetentionCoverageTable;
|
|
1925
1983
|
permission_authority_epochs: PermissionAuthorityEpochsTable;
|
|
1926
1984
|
accounts: AccountsTable;
|
|
1927
1985
|
account_avatar_uploads: AccountAvatarUploadsTable;
|
|
@@ -2022,6 +2080,9 @@ export interface KernelDatabase {
|
|
|
2022
2080
|
model_purpose_mappings: ModelPurposeMappingsTable;
|
|
2023
2081
|
model_disabled: ModelDisabledTable;
|
|
2024
2082
|
model_usage: ModelUsageTable;
|
|
2083
|
+
model_budget_org_usage: ModelBudgetOrgUsageTable;
|
|
2084
|
+
model_budget_member_usage: ModelBudgetMemberUsageTable;
|
|
2085
|
+
_migrations: AppliedMigrationTable;
|
|
2025
2086
|
extension_packages: ExtensionPackagesTable;
|
|
2026
2087
|
extension_blobs: ExtensionBlobsTable;
|
|
2027
2088
|
extension_installs: ExtensionInstallsTable;
|
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>;
|
package/dist/db/pool.js
CHANGED
|
@@ -27,12 +27,47 @@ export function createDb(url, poolMax, onError = (err) => console.error("[db] id
|
|
|
27
27
|
...(opts.idleTimeoutMs !== undefined && { idleTimeoutMillis: opts.idleTimeoutMs }),
|
|
28
28
|
// a client kept idle longer must notice a dead peer (a dropped VPN, a NAT timeout) by itself
|
|
29
29
|
keepAlive: true,
|
|
30
|
+
...(opts.onConnect && { onConnect: opts.onConnect }),
|
|
30
31
|
});
|
|
31
32
|
pool.on("error", onError);
|
|
32
33
|
pool.on("connect", (client) => client.on("error", opts.onClientError ?? onError));
|
|
33
34
|
const rls = opts.rls ?? "off";
|
|
34
35
|
return new Kysely({
|
|
35
|
-
dialect: new ScopedPostgresDialect({
|
|
36
|
+
dialect: new ScopedPostgresDialect({
|
|
37
|
+
pool: opts.closeActiveOnDestroy ? disposablePool(pool) : pool,
|
|
38
|
+
}, rls),
|
|
36
39
|
plugins: rls !== "off" && unscopedQueryCheck() ? [captureUnscopedQueryOrigins] : [],
|
|
37
40
|
});
|
|
38
41
|
}
|
|
42
|
+
// pg.Pool.end waits for every checkout. After the host's drain, release remaining clients with
|
|
43
|
+
// an error so PostgreSQL closes their sessions. Late transaction cleanup can release safely.
|
|
44
|
+
function disposablePool(pool) {
|
|
45
|
+
const active = new Set();
|
|
46
|
+
let closing;
|
|
47
|
+
return {
|
|
48
|
+
Client: pg.Client,
|
|
49
|
+
options: pool.options,
|
|
50
|
+
async connect() {
|
|
51
|
+
const client = await pool.connect();
|
|
52
|
+
if (closing) {
|
|
53
|
+
client.release(true);
|
|
54
|
+
throw new Error("Extension database pool is closing");
|
|
55
|
+
}
|
|
56
|
+
const release = client.release.bind(client);
|
|
57
|
+
client.release = (error) => {
|
|
58
|
+
if (active.delete(client))
|
|
59
|
+
release(error);
|
|
60
|
+
};
|
|
61
|
+
active.add(client);
|
|
62
|
+
return client;
|
|
63
|
+
},
|
|
64
|
+
end() {
|
|
65
|
+
if (!closing) {
|
|
66
|
+
closing = pool.end();
|
|
67
|
+
for (const client of active)
|
|
68
|
+
client.release(true);
|
|
69
|
+
}
|
|
70
|
+
return closing;
|
|
71
|
+
},
|
|
72
|
+
};
|
|
73
|
+
}
|
|
@@ -226,7 +226,7 @@ export declare class DevicesService {
|
|
|
226
226
|
/** Whether a dial-in device's machine is connected now. */
|
|
227
227
|
relay: Pick<DialInRelay, "online">,
|
|
228
228
|
/** Each device's provider (whether it serves its devices over the dial-in channel). */
|
|
229
|
-
providers: Pick<DeviceProviders, "forDevice">, machines: Pick<DialInMachines, "revokeActive">, ceilings: PermissionCeilingWrites, facts: Pick<PermissionFacts, "deviceSandbox" | "deviceSandboxFacts">, displayNames: Pick<ExtensionDisplayNames, "many">,
|
|
229
|
+
providers: Pick<DeviceProviders, "forDevice">, machines: Pick<DialInMachines, "revokeActive" | "revokeMachine">, ceilings: PermissionCeilingWrites, facts: Pick<PermissionFacts, "deviceSandbox" | "deviceSandboxFacts">, displayNames: Pick<ExtensionDisplayNames, "many">,
|
|
230
230
|
/** Each device's stored provider report (read only; never asks the provider). */
|
|
231
231
|
reports: Pick<DeviceReports, "read">,
|
|
232
232
|
/** The dial-in providers on in an org (a device signed in from a machine). */
|
|
@@ -403,6 +403,18 @@ export declare class DevicesService {
|
|
|
403
403
|
/** The prelude of {@link remove}: the membership, the device row, the device's write lock. */
|
|
404
404
|
private lockRemovalSubject;
|
|
405
405
|
private removeIn;
|
|
406
|
+
/** The erasure worker already holds the request and org fence. Former members have no
|
|
407
|
+
* membership to lock, so verify the disabled account and ownership on the locked row. */
|
|
408
|
+
retireForErasure(orgId: string, accountId: string, id: string): Promise<void>;
|
|
409
|
+
/** Close one remaining enrollment under the deleted org's recovery fence. */
|
|
410
|
+
revokeOrgMachine(orgId: string): Promise<boolean>;
|
|
411
|
+
/** A historical enrollment may name the erased account on a different owner's device.
|
|
412
|
+
* Revoke that credential by machine id without stopping or removing the surviving device. */
|
|
413
|
+
eraseHistoricalMachine(orgId: string, accountId: string): Promise<boolean>;
|
|
414
|
+
/** Recreate only the deterministic destruction intent when there are no handles to use.
|
|
415
|
+
* A device with an unknown historical provider needs independent reconciliation. */
|
|
416
|
+
oweErasureVerification(orgId: string, id: string): Promise<string | undefined>;
|
|
417
|
+
private retireLocked;
|
|
406
418
|
/**
|
|
407
419
|
* Starts one of the person's devices over with empty files (after
|
|
408
420
|
* `device.files_lost`): records the request (audit), then, after the commit, enqueues the
|
|
@@ -658,11 +658,120 @@ let DevicesService = class DevicesService {
|
|
|
658
658
|
async removeIn(orgId, accountId, id, actorTokenId, auditDetail) {
|
|
659
659
|
// held since the prelude (the row and the lock are the same; naming them again re-checks)
|
|
660
660
|
const before = await this.lockOwn(orgId, accountId, id);
|
|
661
|
+
await this.retireLocked(orgId, accountId, id);
|
|
662
|
+
await audit(this.db.db, {
|
|
663
|
+
actorAccountId: accountId,
|
|
664
|
+
...(actorTokenId !== undefined && { actorTokenId }),
|
|
665
|
+
orgId,
|
|
666
|
+
action: "device.deleted",
|
|
667
|
+
target: id,
|
|
668
|
+
detail: { name: before.name, isDefault: before.is_default, ...auditDetail },
|
|
669
|
+
});
|
|
670
|
+
}
|
|
671
|
+
/** The erasure worker already holds the request and org fence. Former members have no
|
|
672
|
+
* membership to lock, so verify the disabled account and ownership on the locked row. */
|
|
673
|
+
async retireForErasure(orgId, accountId, id) {
|
|
674
|
+
await this.db
|
|
675
|
+
.selectFrom("devices as d")
|
|
676
|
+
.innerJoin("accounts as a", "a.id", "d.owner_account_id")
|
|
677
|
+
.select("d.id")
|
|
678
|
+
.where("d.id", "=", id)
|
|
679
|
+
.where("d.org_id", "=", orgId)
|
|
680
|
+
.where("d.owner_kind", "=", "personal")
|
|
681
|
+
.where("d.owner_account_id", "=", accountId)
|
|
682
|
+
.where("d.deleted_at", "is", null)
|
|
683
|
+
.where("a.status", "=", "disabled")
|
|
684
|
+
.where("a.erasure_requested", "=", true)
|
|
685
|
+
.forUpdate("d")
|
|
686
|
+
.executeTakeFirstOrThrow();
|
|
687
|
+
await this.retireLocked(orgId, accountId, id);
|
|
688
|
+
}
|
|
689
|
+
/** Close one remaining enrollment under the deleted org's recovery fence. */
|
|
690
|
+
async revokeOrgMachine(orgId) {
|
|
691
|
+
const machine = await this.db
|
|
692
|
+
.selectFrom("device_machines as m")
|
|
693
|
+
.innerJoin("devices as d", "d.id", "m.device_id")
|
|
694
|
+
.innerJoin("orgs as o", "o.id", "d.org_id")
|
|
695
|
+
.select("m.device_id")
|
|
696
|
+
.where("m.org_id", "=", orgId)
|
|
697
|
+
.where("d.org_id", "=", orgId)
|
|
698
|
+
.where("o.deleted_at", "is not", null)
|
|
699
|
+
.where("m.revoked_at", "is", null)
|
|
700
|
+
.orderBy("m.id")
|
|
701
|
+
.limit(1)
|
|
702
|
+
.forUpdate("d")
|
|
703
|
+
.executeTakeFirst();
|
|
704
|
+
if (!machine)
|
|
705
|
+
return false;
|
|
706
|
+
await this.machines.revokeActive(machine.device_id, "deleted");
|
|
707
|
+
return true;
|
|
708
|
+
}
|
|
709
|
+
/** A historical enrollment may name the erased account on a different owner's device.
|
|
710
|
+
* Revoke that credential by machine id without stopping or removing the surviving device. */
|
|
711
|
+
async eraseHistoricalMachine(orgId, accountId) {
|
|
712
|
+
const machine = await this.db
|
|
713
|
+
.selectFrom("device_machines as m")
|
|
714
|
+
.innerJoin("devices as d", "d.id", "m.device_id")
|
|
715
|
+
.innerJoin("accounts as a", "a.id", "m.account_id")
|
|
716
|
+
.select(["m.id", "m.revoked_at"])
|
|
717
|
+
.where("m.org_id", "=", orgId)
|
|
718
|
+
.where("d.org_id", "=", orgId)
|
|
719
|
+
.where("a.id", "=", accountId)
|
|
720
|
+
.where("a.status", "=", "disabled")
|
|
721
|
+
.where("a.erasure_requested", "=", true)
|
|
722
|
+
.where("d.owner_account_id", "!=", accountId)
|
|
723
|
+
.orderBy("m.id")
|
|
724
|
+
.limit(1)
|
|
725
|
+
.forUpdate("d")
|
|
726
|
+
.executeTakeFirst();
|
|
727
|
+
if (!machine)
|
|
728
|
+
return false;
|
|
729
|
+
if (!machine.revoked_at) {
|
|
730
|
+
await this.machines.revokeMachine(machine.id);
|
|
731
|
+
}
|
|
732
|
+
else {
|
|
733
|
+
await this.db
|
|
734
|
+
.deleteFrom("device_machines")
|
|
735
|
+
.where("org_id", "=", orgId)
|
|
736
|
+
.where("account_id", "=", accountId)
|
|
737
|
+
.where("id", "=", machine.id)
|
|
738
|
+
.where("revoked_at", "is not", null)
|
|
739
|
+
.execute();
|
|
740
|
+
}
|
|
741
|
+
return true;
|
|
742
|
+
}
|
|
743
|
+
/** Recreate only the deterministic destruction intent when there are no handles to use.
|
|
744
|
+
* A device with an unknown historical provider needs independent reconciliation. */
|
|
745
|
+
async oweErasureVerification(orgId, id) {
|
|
746
|
+
const device = await this.db
|
|
747
|
+
.selectFrom("devices as d")
|
|
748
|
+
.innerJoin("orgs as o", "o.id", "d.org_id")
|
|
749
|
+
.select(["d.provider", "d.demoted_from_provider"])
|
|
750
|
+
.where("d.id", "=", id)
|
|
751
|
+
.where("d.org_id", "=", orgId)
|
|
752
|
+
.where("d.files_destroyed_at", "is", null)
|
|
753
|
+
.where((eb) => eb.or([eb("d.deleted_at", "is not", null), eb("o.deleted_at", "is not", null)]))
|
|
754
|
+
.forUpdate("d")
|
|
755
|
+
.executeTakeFirstOrThrow();
|
|
756
|
+
const provider = this.providers.forDevice(device.provider);
|
|
757
|
+
if (!provider || device.demoted_from_provider)
|
|
758
|
+
return "device-provider-unavailable";
|
|
759
|
+
if (servesDialIn(provider))
|
|
760
|
+
return "device-local-destruction-unverified";
|
|
761
|
+
await this.db
|
|
762
|
+
.insertInto("device_instances")
|
|
763
|
+
.values({ device_id: id, org_id: orgId, provider: provider.plugin, status: "creating" })
|
|
764
|
+
.onConflict((conflict) => conflict.column("device_id").doNothing())
|
|
765
|
+
.execute();
|
|
766
|
+
await oweDeviceDestroy(this.outbox, id, orgId);
|
|
767
|
+
return undefined;
|
|
768
|
+
}
|
|
769
|
+
async retireLocked(orgId, accountId, id) {
|
|
661
770
|
await this.ceilings.lock({ orgId, deviceId: id }, "device");
|
|
662
771
|
await this.ceilings.publishLocked({ orgId, deviceId: id }, "device", true, true);
|
|
663
772
|
await this.db
|
|
664
773
|
.updateTable("devices")
|
|
665
|
-
.set({ deleted_at: sql `now()`, updated_at: sql `now()
|
|
774
|
+
.set({ deleted_at: sql `now()`, updated_at: sql `now()`, files_destroyed_at: null })
|
|
666
775
|
.where("id", "=", id)
|
|
667
776
|
.where("org_id", "=", orgId)
|
|
668
777
|
.execute();
|
|
@@ -676,14 +785,6 @@ let DevicesService = class DevicesService {
|
|
|
676
785
|
// its loopback port grants end with it (browser loopback port grants design §4)
|
|
677
786
|
await revokeLoopbackGrantsOfDevice(this.db.db, this.outbox, { orgId, deviceId: id });
|
|
678
787
|
await revokeSiteGrantsOfDevice(this.db.db, { orgId, deviceId: id });
|
|
679
|
-
await audit(this.db.db, {
|
|
680
|
-
actorAccountId: accountId,
|
|
681
|
-
...(actorTokenId !== undefined && { actorTokenId }),
|
|
682
|
-
orgId,
|
|
683
|
-
action: "device.deleted",
|
|
684
|
-
target: id,
|
|
685
|
-
detail: { name: before.name, isDefault: before.is_default, ...auditDetail },
|
|
686
|
-
});
|
|
687
788
|
await oweDeviceDestroy(this.outbox, id, orgId);
|
|
688
789
|
}
|
|
689
790
|
/**
|
|
@@ -1062,6 +1163,18 @@ __decorate([
|
|
|
1062
1163
|
__decorate([
|
|
1063
1164
|
Transactional()
|
|
1064
1165
|
], DevicesService.prototype, "removeIn", null);
|
|
1166
|
+
__decorate([
|
|
1167
|
+
Transactional({ propagation: "mandatory" })
|
|
1168
|
+
], DevicesService.prototype, "retireForErasure", null);
|
|
1169
|
+
__decorate([
|
|
1170
|
+
Transactional({ propagation: "mandatory" })
|
|
1171
|
+
], DevicesService.prototype, "revokeOrgMachine", null);
|
|
1172
|
+
__decorate([
|
|
1173
|
+
Transactional({ propagation: "mandatory" })
|
|
1174
|
+
], DevicesService.prototype, "eraseHistoricalMachine", null);
|
|
1175
|
+
__decorate([
|
|
1176
|
+
Transactional({ propagation: "mandatory" })
|
|
1177
|
+
], DevicesService.prototype, "oweErasureVerification", null);
|
|
1065
1178
|
__decorate([
|
|
1066
1179
|
Transactional()
|
|
1067
1180
|
], DevicesService.prototype, "recordReset", null);
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { KernelSchemaDb } from "../db/kernel-schema.js";
|
|
2
|
+
type Result = {
|
|
3
|
+
removed: number;
|
|
4
|
+
blocked?: string;
|
|
5
|
+
};
|
|
6
|
+
export declare function accountRootBlocker(db: KernelSchemaDb, orgId: string, accountId: string): Promise<"account-scope" | "private-source-eval" | "shared-conversation-tree" | undefined>;
|
|
7
|
+
export declare function accountRootBatch(db: KernelSchemaDb, orgId: string, accountId: string): Promise<Result>;
|
|
8
|
+
export declare function accountErasureBatch(db: KernelSchemaDb, accountId: string, orgId: string | null): Promise<Result>;
|
|
9
|
+
export { accountResidual } from "./account-residual.js";
|