@capybara-hq/kernel 0.1.0-rc.144 → 0.1.0-rc.146

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/dist/agents/admin-agents.d.ts +20 -3
  2. package/dist/agents/admin-agents.js +38 -7
  3. package/dist/catalog/marketplace-fetch.d.ts +2 -0
  4. package/dist/catalog/marketplace-fetch.js +7 -2
  5. package/dist/catalog/marketplaces.service.d.ts +1 -1
  6. package/dist/catalog/provenance.d.ts +69 -0
  7. package/dist/catalog/provenance.js +108 -0
  8. package/dist/ctx/create-ctx.d.ts +16 -0
  9. package/dist/ctx/create-ctx.js +269 -34
  10. package/dist/errors.d.ts +1 -1
  11. package/dist/errors.js +2 -2
  12. package/dist/extensions/execution-realm.d.ts +96 -0
  13. package/dist/extensions/execution-realm.js +141 -0
  14. package/dist/extensions/extensions.module.js +3 -0
  15. package/dist/extensions/grant-epoch.d.ts +4 -2
  16. package/dist/extensions/grant-epoch.js +4 -2
  17. package/dist/extensions/host.d.ts +26 -3
  18. package/dist/extensions/host.js +135 -10
  19. package/dist/extensions/instance.d.ts +2 -0
  20. package/dist/extensions/instance.js +1 -0
  21. package/dist/extensions/isolated/admission.d.ts +6 -0
  22. package/dist/extensions/isolated/admission.js +17 -0
  23. package/dist/extensions/isolated/tier.d.ts +14 -0
  24. package/dist/extensions/isolated/tier.js +27 -0
  25. package/dist/extensions/ledger.d.ts +5 -0
  26. package/dist/extensions/ledger.js +16 -0
  27. package/dist/extensions/permission-view.d.ts +2 -2
  28. package/dist/extensions/publisher-proof.job.d.ts +39 -0
  29. package/dist/extensions/publisher-proof.job.js +160 -0
  30. package/dist/extensions/registry.d.ts +6 -0
  31. package/dist/extensions/registry.js +8 -0
  32. package/dist/extensions/review-hash.d.ts +114 -0
  33. package/dist/extensions/review-hash.js +145 -0
  34. package/dist/extensions/revision-grants.d.ts +10 -0
  35. package/dist/extensions/revocation-leases.d.ts +273 -0
  36. package/dist/extensions/revocation-leases.js +533 -0
  37. package/dist/extensions/revocation.d.ts +78 -0
  38. package/dist/extensions/revocation.js +202 -0
  39. package/dist/index.d.ts +6 -2
  40. package/dist/index.js +6 -2
  41. package/dist/lifecycle/kernel-lifecycle.d.ts +3 -1
  42. package/dist/lifecycle/kernel-lifecycle.js +24 -18
  43. package/dist/overrides.d.ts +5 -1
  44. package/dist/overrides.js +2 -0
  45. package/dist/packages/official-publisher.d.ts +44 -0
  46. package/dist/packages/official-publisher.js +147 -48
  47. package/dist/packages/provenance.d.ts +6 -0
  48. package/dist/packages/provenance.js +26 -9
  49. package/dist/platform/ops/admin-items.ops.js +1 -1
  50. package/dist/roles/worker.module.js +3 -0
  51. package/package.json +2 -2
@@ -1,4 +1,4 @@
1
- import { CONVERSATION_TARGET_EXTENSION_POINT, CtxReadError, DEVICE_PROVIDER_EXTENSION_POINT, DeviceAccessError, ExtensionPermissionError, FILE_PREVIEW_EXTENSION_POINT, InboxError, resolveUiSlots, SETUP_CHECK_ID_RE, SETUP_GUIDE_PLACES, TriggerError, validateFilePreviewProvider, validateToolSpec, } from "@capybara-hq/plugin-sdk";
1
+ import { AGENTS_KEY, CONVERSATION_TARGET_EXTENSION_POINT, CONVERSATIONS_KEY, CtxReadError, DEVICE_ACCESS_KEY_PREFIX, DEVICE_HOST_KEY_PREFIX, DEVICE_LOOPBACK_PORTS_KEY, DEVICE_PROVIDER_EXTENSION_POINT, DEVICE_SITE_ACCESS_KEY, DeviceAccessError, DIAL_IN_KEY_PREFIX, ExtensionPermissionError, FILE_PREVIEW_EXTENSION_POINT, INBOX_KEY, InboxError, PEOPLE_KEY, POLICY_HOOK_KEY_PREFIX, resolveUiSlots, SETUP_CHECK_ID_RE, SETUP_CHECK_KEY_PREFIX, SETUP_GUIDE_PLACES, TRIGGERS_KEY_PREFIX, TriggerError, UI_COMPONENT_KEY_PREFIX, UI_VIEW_KEY_PREFIX, validateFilePreviewProvider, validateToolSpec, } from "@capybara-hq/plugin-sdk";
2
2
  import { conversationTopic } from "../conversations/event-log.js";
3
3
  import { checkExternalText } from "../conversations/external/external-calls.js";
4
4
  import { pluginSchemaName } from "../db/extension-db.js";
@@ -226,35 +226,85 @@ identity = { sha256: null }) {
226
226
  audits.add(p);
227
227
  throw new ExtensionPermissionError(name, item);
228
228
  };
229
+ // Revocation (plan task 1.3e): the lease of this instance's revision grant. Once enforcing (plan
230
+ // task 1.5a), a capability key the grant no longer serves is refused (ExtensionPermissionError,
231
+ // audited like any denial) and the handles opened under it are aborted; unaffected keys keep
232
+ // serving. In shadow mode the lease only reports what it would refuse and never waits.
233
+ const lease = deps.leases?.open({
234
+ plugin: name,
235
+ sha256: identity.sha256,
236
+ inProcess: identity.inProcess ?? true,
237
+ });
238
+ const revoked = async (key) => {
239
+ if (lease && !(await lease.check(key)))
240
+ deny(`revoked ${key}`);
241
+ };
242
+ /** Refused only when every one of `keys` is refused (a call that may use any of them). */
243
+ const revokedAll = async (keys, item) => {
244
+ if (!lease || keys.length === 0)
245
+ return;
246
+ for (const key of keys)
247
+ if (await lease.check(key))
248
+ return;
249
+ deny(`revoked ${item}`);
250
+ };
251
+ /** The instance's signal, also aborted when `key` is revoked or the lease is fenced. */
252
+ const leaseSignal = (key) => lease ? AbortSignal.any([lifecycle.signal, lease.signal(key)]) : lifecycle.signal;
253
+ /** Every async method of `api` checks its key first. */
254
+ const leased = (api, key) => lease
255
+ ? new Proxy(api, {
256
+ get(target, prop, receiver) {
257
+ const value = Reflect.get(target, prop, receiver);
258
+ if (typeof value !== "function")
259
+ return value;
260
+ return async (...args) => {
261
+ await revoked(key);
262
+ return value.apply(target, args);
263
+ };
264
+ },
265
+ })
266
+ : api;
229
267
  // 只暴露插件契约中的 get / set(KernelSecrets 的 delete 仅供内核使用)
230
268
  const secretsApi = perms.secrets
231
- ? (({ get, set }) => ({ get, set }))(createSecrets(deps.db, deps.keyring, name))
269
+ ? leased((({ get, set }) => ({ get, set }))(createSecrets(deps.db, deps.keyring, name)), "permissions.secrets")
232
270
  : undefined;
233
271
  // ctx.storage:经已加载的 object-store@1 提供方(按调用时取;依赖排序保证提供方先于本插件 setup),
234
272
  // 键加前缀 plugins/<name>/<orgId>/。没有提供方时各方法 reject storage.unavailable
235
273
  // (宿主不会加载这样的插件,见 approvals.ts;单独构造 ctx 的测试会走到这里)
236
274
  const storageApi = perms.storage
237
- ? new PrefixedStorage({
275
+ ? leased(new PrefixedStorage({
238
276
  provider: objectStore,
239
277
  plugins: async () => [name],
240
- }).forPlugin(name)
278
+ }).forPlugin(name), "permissions.storage")
241
279
  : undefined;
242
280
  // ctx.models: only with permissions.models; each broker accepts only the purposes declared there
243
281
  // with its kind (embedding: spec B §5.4; image_generation: image generation spec §5.5), aborted
244
282
  // by this instance's signal
245
283
  // a frozen copy: the approved manifest, not an object the extension could change later
246
284
  const declaredModels = Object.freeze(structuredClone(perms.models ?? []).map((m) => Object.freeze(m)));
285
+ /** The permission key of a declared model purpose (undefined: not declared, the broker refuses). */
286
+ const modelKey = (req) => {
287
+ const purpose = req?.purpose;
288
+ const declared = declaredModels.find((d) => d.purpose === purpose);
289
+ return declared ? `permissions.models:${declared.purpose} (${declared.kind})` : undefined;
290
+ };
247
291
  const modelsApi = declaredModels.length > 0
248
292
  ? {
249
293
  embed: async (req) => {
250
294
  if (!deps.models)
251
295
  throw new Error(`plugin ${name}: ctx.models is not available`);
252
- return deps.models.embeddings.embed(name, declaredModels, req, lifecycle.signal, deps.hooks);
296
+ const key = modelKey(req);
297
+ if (key !== undefined)
298
+ await revoked(key);
299
+ return deps.models.embeddings.embed(name, declaredModels, req, key === undefined ? lifecycle.signal : leaseSignal(key), deps.hooks);
253
300
  },
254
301
  generateImage: async (req) => {
255
302
  if (!deps.models)
256
303
  throw new Error(`plugin ${name}: ctx.models is not available`);
257
- return deps.models.images.generateForExtension(name, declaredModels, req, lifecycle.signal, deps.hooks);
304
+ const key = modelKey(req);
305
+ if (key !== undefined)
306
+ await revoked(key);
307
+ return deps.models.images.generateForExtension(name, declaredModels, req, key === undefined ? lifecycle.signal : leaseSignal(key), deps.hooks);
258
308
  },
259
309
  // by the declared purpose's kind; an undeclared purpose has none, so its refusal
260
310
  // (model.purpose_unknown) names no kind
@@ -271,6 +321,9 @@ identity = { sha256: null }) {
271
321
  if (typeof orgId !== "string" || orgId === "" || typeof purpose !== "string") {
272
322
  throw new ApiError("validation_failed", "describe needs orgId and purpose strings");
273
323
  }
324
+ const key = modelKey(req);
325
+ if (key !== undefined)
326
+ await revoked(key);
274
327
  const target = { orgId, purpose };
275
328
  return withOrgScope(orgId, () => kind === "image_generation"
276
329
  ? models.images.describeForExtension(name, declaredModels, target)
@@ -285,9 +338,11 @@ identity = { sha256: null }) {
285
338
  const dialInApi = perms.dialIn
286
339
  ? (() => {
287
340
  const access = deps.dialIn;
341
+ const dialInKey = `${DIAL_IN_KEY_PREFIX}${perms.dialIn?.protocol}`;
288
342
  const inServedOrg = async (deviceId, run) => {
289
343
  if (!access)
290
344
  throw new Error(`plugin ${name}: ctx.dialIn is not available`);
345
+ await revoked(dialInKey);
291
346
  const orgId = typeof deviceId === "string" ? await access.servedOrg(name, deviceId) : undefined;
292
347
  if (orgId === undefined) {
293
348
  const item = `dialIn:device ${String(deviceId)}`;
@@ -302,8 +357,8 @@ identity = { sha256: null }) {
302
357
  return {
303
358
  request: (deviceId, frame, opts) => inServedOrg(deviceId, (dialIn) => {
304
359
  const signal = opts?.signal
305
- ? AbortSignal.any([lifecycle.signal, opts.signal])
306
- : lifecycle.signal;
360
+ ? AbortSignal.any([leaseSignal(dialInKey), opts.signal])
361
+ : leaseSignal(dialInKey);
307
362
  // Only the options an extension may pass, excluding the kernel's connection fences.
308
363
  return dialIn.request(deviceId, frame, {
309
364
  timeoutMs: Number(opts?.timeoutMs),
@@ -322,14 +377,16 @@ identity = { sha256: null }) {
322
377
  openStream: (deviceId, body, opts) => inServedOrg(deviceId, async (dialIn) => {
323
378
  if (!(opts?.signal instanceof AbortSignal))
324
379
  throw new TypeError(`plugin ${name}: ctx.dialIn.openStream needs opts.signal`);
325
- const signal = AbortSignal.any([lifecycle.signal, opts.signal]);
380
+ // the stream closes when the instance stops or its dial-in permission is revoked
381
+ const held = leaseSignal(dialInKey);
382
+ const signal = AbortSignal.any([held, opts.signal]);
326
383
  const stream = await dialIn.openStream(deviceId, body, signal);
327
- const onEnd = () => stream.close("extension stopped");
328
- if (lifecycle.signal.aborted)
384
+ const onEnd = () => stream.close(lifecycle.signal.aborted ? "extension stopped" : "extension permission revoked");
385
+ if (held.aborted)
329
386
  onEnd();
330
387
  else {
331
- lifecycle.signal.addEventListener("abort", onEnd, { once: true });
332
- void stream.closed.then(() => lifecycle.signal.removeEventListener("abort", onEnd));
388
+ held.addEventListener("abort", onEnd, { once: true });
389
+ void stream.closed.then(() => held.removeEventListener("abort", onEnd));
333
390
  }
334
391
  return stream;
335
392
  }),
@@ -405,24 +462,73 @@ identity = { sha256: null }) {
405
462
  throw new DeviceAccessError("capability_missing", "Device services are not available in this process.");
406
463
  return b;
407
464
  };
465
+ // revocation: a call naming a service needs that service's key; the others need any of
466
+ // the services still granted (plan task 1.3e)
467
+ const serviceKeys = caller.services.map((svc) => `${DEVICE_ACCESS_KEY_PREFIX}${svc}`);
468
+ const service = (svc) => revoked(`${DEVICE_ACCESS_KEY_PREFIX}${String(svc)}`);
469
+ const host = (svc) => revoked(`${DEVICE_HOST_KEY_PREFIX}${String(svc)}`);
470
+ const anyService = () => revokedAll(serviceKeys, "permissions.deviceaccess");
471
+ const nameOf = (spec) => spec?.name;
472
+ const serviceOf = (req) => req?.service;
408
473
  return {
409
- ensureService: async (call, spec) => backend().ensureService(caller, call, spec),
410
- request: async (call, req) => backend().request(caller, call, req),
411
- reportBlockedHosts: (call, hosts, opts) => backend().reportBlockedHosts(caller, call, hosts, opts),
412
- streamTicket: async (scope) => backend().streamTicket(caller, scope),
413
- addNetworkHosts: async (scope) => backend().addNetworkHosts(caller, scope),
414
- answerHandoff: async (scope) => backend().answerHandoff(caller, scope),
415
- grantLoopbackPort: async (scope) => backend().grantLoopbackPort(caller, scope),
474
+ ensureService: async (call, spec) => {
475
+ await service(nameOf(spec));
476
+ return backend().ensureService(caller, call, spec);
477
+ },
478
+ request: async (call, req) => {
479
+ await service(serviceOf(req));
480
+ return backend().request(caller, call, req);
481
+ },
482
+ reportBlockedHosts: async (call, hosts, opts) => {
483
+ await anyService();
484
+ return backend().reportBlockedHosts(caller, call, hosts, opts);
485
+ },
486
+ streamTicket: async (scope) => {
487
+ await anyService();
488
+ return backend().streamTicket(caller, scope);
489
+ },
490
+ addNetworkHosts: async (scope) => {
491
+ await anyService();
492
+ return backend().addNetworkHosts(caller, scope);
493
+ },
494
+ answerHandoff: async (scope) => {
495
+ await anyService();
496
+ return backend().answerHandoff(caller, scope);
497
+ },
498
+ grantLoopbackPort: async (scope) => {
499
+ await revoked(DEVICE_LOOPBACK_PORTS_KEY);
500
+ return backend().grantLoopbackPort(caller, scope);
501
+ },
502
+ // withdrawing a grant stays possible after the permission is revoked
416
503
  revokeLoopbackPort: async (scope) => backend().revokeLoopbackPort(caller, scope),
417
- loopbackPorts: async (scope) => backend().loopbackPorts(caller, scope),
418
- requestSiteAccess: (call, ask) => backend().requestSiteAccess(caller, call, ask),
419
- siteGrants: async (scope) => backend().siteGrants(caller, scope),
504
+ loopbackPorts: async (scope) => {
505
+ await revoked(DEVICE_LOOPBACK_PORTS_KEY);
506
+ return backend().loopbackPorts(caller, scope);
507
+ },
508
+ requestSiteAccess: async (call, ask) => {
509
+ await revoked(DEVICE_SITE_ACCESS_KEY);
510
+ return backend().requestSiteAccess(caller, call, ask);
511
+ },
512
+ siteGrants: async (scope) => {
513
+ await revoked(DEVICE_SITE_ACCESS_KEY);
514
+ return backend().siteGrants(caller, scope);
515
+ },
420
516
  revokeSiteGrant: async (scope) => backend().revokeSiteGrant(caller, scope),
421
517
  // host services: the approved manifest's hostServices, on the person's own machine
422
- ensureHostService: async (at, spec) => backend().ensureHostService(caller, at, spec),
423
- hostRequest: async (at, req) => backend().hostRequest(caller, at, req),
518
+ ensureHostService: async (at, spec) => {
519
+ await host(nameOf(spec));
520
+ return backend().ensureHostService(caller, at, spec);
521
+ },
522
+ hostRequest: async (at, req) => {
523
+ await host(serviceOf(req));
524
+ return backend().hostRequest(caller, at, req);
525
+ },
526
+ // stopping stays possible after the permission is revoked
424
527
  stopHostService: async (at, service) => backend().stopHostService(caller, at, service),
425
- personalDevices: async (args) => backend().personalDevices(caller, args),
528
+ personalDevices: async (args) => {
529
+ await anyService();
530
+ return backend().personalDevices(caller, args);
531
+ },
426
532
  // during setup only, for a host service of the approved manifest: the deliveries
427
533
  // (ServiceEvents, worker role) call it on whichever replica takes the job
428
534
  onServiceEvent: (service, handler) => {
@@ -481,6 +587,7 @@ identity = { sha256: null }) {
481
587
  return { status: "staged", idempotencyKey: key };
482
588
  };
483
589
  const addOutbox = (async (effect, options) => {
590
+ await revoked("permissions.outbox");
484
591
  const snapshot = structuredClone(effect);
485
592
  if (!snapshot?.orgId || typeof snapshot.orgId !== "string") {
486
593
  throw new Error("An extension outbox effect requires an org id");
@@ -505,6 +612,7 @@ identity = { sha256: null }) {
505
612
  const snap = snapshotTriggerEvent(event);
506
613
  if (typeof snap.orgId !== "string" || snap.orgId === "")
507
614
  throw new TriggerError("invalid_event", "invalid event: missing_org_id");
615
+ await revoked(`${TRIGGERS_KEY_PREFIX}${String(snap.type)}`);
508
616
  return durable(snap.orgId, { kind: "trigger", data: snap }, options);
509
617
  }),
510
618
  // a handle bound to this extension and the call's run, in the call's org (the service
@@ -513,6 +621,7 @@ identity = { sha256: null }) {
513
621
  const b = deps.triggers?.();
514
622
  if (!b)
515
623
  throw new Error("Trigger events are not available in this process.");
624
+ await revokedAll((perms.triggers?.emit ?? []).map((type) => `${TRIGGERS_KEY_PREFIX}${type}`), "permissions.triggers");
516
625
  const orgId = typeof call === "object" && call !== null ? call.orgId : "";
517
626
  if (typeof orgId !== "string" || orgId === "")
518
627
  throw new TriggerError("invalid_event", "causeOf takes the tool call context the kernel passed to the handler");
@@ -528,6 +637,7 @@ identity = { sha256: null }) {
528
637
  const inboxApi = perms.inbox
529
638
  ? {
530
639
  post: (async (p, options) => {
640
+ await revoked(INBOX_KEY);
531
641
  let snap;
532
642
  try {
533
643
  snap = structuredClone(p);
@@ -546,6 +656,7 @@ identity = { sha256: null }) {
546
656
  const b = deps.inbox?.();
547
657
  if (!b)
548
658
  throw new Error("The inbox is not available in this process.");
659
+ await revoked(INBOX_KEY);
549
660
  const orgId = args?.orgId;
550
661
  const itemId = args?.itemId;
551
662
  if (typeof orgId !== "string" || orgId === "" || typeof itemId !== "string")
@@ -571,6 +682,7 @@ identity = { sha256: null }) {
571
682
  const agentsApi = perms.agents
572
683
  ? {
573
684
  usableBy: async (args) => {
685
+ await revoked(AGENTS_KEY);
574
686
  const a = readArgs(args);
575
687
  if (typeof a.accountId !== "string" || a.accountId === "")
576
688
  throw new CtxReadError("invalid_args", "accountId is required");
@@ -596,6 +708,7 @@ identity = { sha256: null }) {
596
708
  bySubject: async (args) => {
597
709
  if (!perms.conversations)
598
710
  deny("permissions.conversations");
711
+ await revoked(CONVERSATIONS_KEY);
599
712
  const a = readArgs(args);
600
713
  const s = a.subject;
601
714
  if (typeof s !== "object" ||
@@ -641,6 +754,7 @@ identity = { sha256: null }) {
641
754
  const peopleApi = perms.people
642
755
  ? {
643
756
  get: async (args) => {
757
+ await revoked(PEOPLE_KEY);
644
758
  const a = readArgs(args);
645
759
  const ids = a.accountIds;
646
760
  if (!Array.isArray(ids))
@@ -648,6 +762,7 @@ identity = { sha256: null }) {
648
762
  return withOrgScope(a.orgId, () => readsBackend().peopleGet(name, a.orgId, [...ids]));
649
763
  },
650
764
  search: async (args) => {
765
+ await revoked(PEOPLE_KEY);
651
766
  const a = readArgs(args);
652
767
  return withOrgScope(a.orgId, () => readsBackend().peopleSearch(name, a.orgId, a.query, a.limit));
653
768
  },
@@ -710,20 +825,129 @@ identity = { sha256: null }) {
710
825
  };
711
826
  /** Ids of the extension's `platform.page` contributions (their invalidate takes no orgId). */
712
827
  const platformUi = new Set([...uiSlots].filter(([, s]) => s.id === "platform.page").map(([id]) => id));
828
+ /**
829
+ * Withdraws what revoked keys back (plan task 1.3e; called only once revocation is enforced,
830
+ * plan task 1.5a). Registrations: new dispatch finds them gone, and the registry's change
831
+ * listeners (the HTTP dispatcher, the gateway's channel supervisor and webhook cache) refresh.
832
+ * Their ledger entries stay (their dispose is then a no-op). A policy hook on a mount whose
833
+ * policy or observe key is revoked stays registered and denies every call, so a required policy
834
+ * mount fails closed and the hook sees no payload. Handles held under a revoked capability (bus
835
+ * subscriptions, queue workers, `ctx.lock` leases) are disposed from the ledger.
836
+ */
837
+ const withdraw = (keys) => {
838
+ let changed = false;
839
+ const drop = (list, match) => {
840
+ for (let i = list.length - 1; i >= 0; i--) {
841
+ if (match(list[i])) {
842
+ list.splice(i, 1);
843
+ changed = true;
844
+ }
845
+ }
846
+ };
847
+ const remove = (map, key) => {
848
+ if (map.delete(key))
849
+ changed = true;
850
+ };
851
+ // The mount stays expected until the admin disables the extension: the hook stays registered
852
+ // and denies every call (a loaded plugin without the hook would be skipped, failing open).
853
+ const denyPolicy = (mount) => {
854
+ for (const hook of registeredHooks) {
855
+ if (hook.mount !== mount || hook.mode !== "policy")
856
+ continue;
857
+ hook.handler = (async () => ({
858
+ deny: `The ${name} hook permission on ${mount} was revoked`,
859
+ }));
860
+ changed = true;
861
+ }
862
+ };
863
+ const disposals = [];
864
+ for (const key of keys) {
865
+ const http = /^permissions\.http(?:\.[a-z]+)?:(\S+) (.+)$/.exec(key);
866
+ if (http) {
867
+ const [, method, path] = http;
868
+ const access = declaredRoutes.get(`${method} ${path}`);
869
+ const full = access === "member" || access === "admin"
870
+ ? `/plugins/${name}/orgs/:orgId${path}`
871
+ : `/plugins/${name}${path}`;
872
+ drop(routes, (r) => r.method === method && r.path === full);
873
+ }
874
+ else if (key.startsWith("permissions.tools:")) {
875
+ const tool = key.slice("permissions.tools:".length);
876
+ drop(registeredTools, (t) => t.spec.name === tool);
877
+ }
878
+ else if (key.startsWith(POLICY_HOOK_KEY_PREFIX)) {
879
+ denyPolicy(key.slice(POLICY_HOOK_KEY_PREFIX.length));
880
+ }
881
+ else if (key.startsWith("permissions.hooks:")) {
882
+ // a hook on the mount, of either mode, needs this key: observe hooks go, a policy hook
883
+ // denies (the mount stays expected)
884
+ const mount = key.slice("permissions.hooks:".length);
885
+ drop(registeredHooks, (h) => h.mount === mount && h.mode !== "policy");
886
+ denyPolicy(mount);
887
+ }
888
+ else if (key === "permissions.bus" ||
889
+ key === "permissions.queue" ||
890
+ key === "permissions.lock") {
891
+ const kind = key === "permissions.bus" ? "bus" : key === "permissions.queue" ? "queue" : "lease";
892
+ disposals.push(ledger.disposeKind(kind, (r, err) => deps.log.warn("disposing a revoked extension handle failed", {
893
+ plugin: name,
894
+ kind: r.kind,
895
+ key: r.key,
896
+ err,
897
+ })));
898
+ }
899
+ else if (key.startsWith(UI_VIEW_KEY_PREFIX) || key.startsWith(UI_COMPONENT_KEY_PREFIX)) {
900
+ const id = key.slice(key.indexOf(":") + 1);
901
+ remove(uiReg.views, id);
902
+ remove(uiReg.actions, id);
903
+ remove(uiReg.queries, id);
904
+ }
905
+ else if (key.startsWith("ui.query:")) {
906
+ remove(uiReg.queries, key.slice("ui.query:".length));
907
+ }
908
+ else if (key.startsWith("ui.action:")) {
909
+ remove(uiReg.actions, key.slice("ui.action:".length));
910
+ }
911
+ else if (key.startsWith(SETUP_CHECK_KEY_PREFIX)) {
912
+ remove(setupChecks, key.slice(SETUP_CHECK_KEY_PREFIX.length));
913
+ }
914
+ else if (key.startsWith("provides:")) {
915
+ remove(provided, key.slice("provides:".length));
916
+ }
917
+ else if (key.startsWith(DEVICE_HOST_KEY_PREFIX)) {
918
+ remove(serviceEventHandlers, key.slice(DEVICE_HOST_KEY_PREFIX.length));
919
+ }
920
+ }
921
+ if (changed) {
922
+ deps.log.warn("extension registrations withdrawn: their permission was revoked", {
923
+ plugin: name,
924
+ keys: [...keys],
925
+ });
926
+ deps.registrationsChanged?.(name);
927
+ }
928
+ void Promise.all(disposals);
929
+ };
930
+ // Registrations made during setup are withdrawn at seal time if already revoked; later
931
+ // revocations withdraw as the lease sees them.
932
+ lease?.onRefused((keys) => {
933
+ if (toolsSealed)
934
+ withdraw(keys);
935
+ });
713
936
  const ctx = {
714
- kv: createKv(deps.redis, name),
937
+ kv: leased(createKv(deps.redis, name), "permissions.kv"),
715
938
  lock: {
716
939
  // 取到的租约记账:实例撤销时释放仍持有的;插件自己 release 时销账
717
940
  async acquire(key, opts) {
718
- const lease = await lock.acquire(key, opts);
719
- if (!lease)
941
+ await revoked("permissions.lock");
942
+ const held = await lock.acquire(key, opts);
943
+ if (!held)
720
944
  return null;
721
- const settle = ledger.add({ kind: "lease", key, dispose: () => lease.release() });
945
+ const settle = ledger.add({ kind: "lease", key, dispose: () => held.release() });
722
946
  return {
723
- renew: () => lease.renew(),
947
+ renew: () => held.renew(),
724
948
  async release() {
725
949
  settle();
726
- await lease.release();
950
+ await held.release();
727
951
  },
728
952
  };
729
953
  },
@@ -738,8 +962,12 @@ identity = { sha256: null }) {
738
962
  },
739
963
  },
740
964
  bus: {
741
- publish: bus.publish,
965
+ async publish(topic, payload) {
966
+ await revoked("permissions.bus");
967
+ return bus.publish(topic, payload);
968
+ },
742
969
  async subscribe(topic, handler) {
970
+ await revoked("permissions.bus");
743
971
  const closedError = () => new Error(`plugin ${name}: ctx is closed; bus.subscribe is not allowed after close`);
744
972
  if (closing || ledger.sealed)
745
973
  throw closedError();
@@ -765,7 +993,11 @@ identity = { sha256: null }) {
765
993
  dispose: () => queue.stopWorker(qname, drainDeadline),
766
994
  });
767
995
  },
768
- add: queue.add,
996
+ // ctx/queue.ts's own add (a free function), behind the revocation check
997
+ add: ((enqueue) => (async (...args) => {
998
+ await revoked("permissions.queue");
999
+ return enqueue(...args);
1000
+ }))(queue.add),
769
1001
  },
770
1002
  db: guardDb((identity.db ?? deps.db).withSchema(pluginSchemaName(name)), name, effectTransactions),
771
1003
  hasEffectQueue: queue.hasDefined,
@@ -1034,12 +1266,15 @@ identity = { sha256: null }) {
1034
1266
  sealTools() {
1035
1267
  toolsSealed = true;
1036
1268
  uiReg.seal();
1269
+ if (lease?.enforced)
1270
+ withdraw(lease.refusedKeys());
1037
1271
  },
1038
1272
  /** 幂等:重复 / 并发调用共享同一次关闭。 */
1039
1273
  close() {
1040
1274
  closing ??= (async () => {
1041
1275
  if (!lifecycle.signal.aborted)
1042
1276
  lifecycle.abort();
1277
+ lease?.close();
1043
1278
  await ledger.disposeAll((r, err) => deps.log.warn("plugin registration dispose failed", {
1044
1279
  plugin: name,
1045
1280
  kind: r.kind,
package/dist/errors.d.ts CHANGED
@@ -803,7 +803,7 @@ export type ErrorCode = keyof typeof ERROR_CODES;
803
803
  export declare class ApiError extends Error {
804
804
  readonly code: ErrorCode;
805
805
  readonly details?: unknown[] | undefined;
806
- constructor(code: ErrorCode, message: string, details?: unknown[] | undefined);
806
+ constructor(code: ErrorCode, message: string, details?: unknown[] | undefined, options?: ErrorOptions);
807
807
  get status(): number;
808
808
  }
809
809
  /** 错误信封的 body。 */
package/dist/errors.js CHANGED
@@ -802,8 +802,8 @@ export const ERROR_CODES = {
802
802
  export class ApiError extends Error {
803
803
  code;
804
804
  details;
805
- constructor(code, message, details) {
806
- super(message);
805
+ constructor(code, message, details, options) {
806
+ super(message, options);
807
807
  this.code = code;
808
808
  this.details = details;
809
809
  this.name = "ApiError";
@@ -0,0 +1,96 @@
1
+ import { type ExecutionRealm } from "./revision-grants.js";
2
+ /**
3
+ * The catalog-driven execution decision (extension permission model spec, "Purpose and boundary";
4
+ * plan task 1.2e). Pure: from a revision's canonical permission keys, whether it has server and
5
+ * client code, and the host's isolation state, it decides where each part runs and which
6
+ * declarations force full access in which realm. Review (1.3a), bootstrap review (1.3c), the
7
+ * tier selector (1.3b) and `capybara-plugin check` all read this one decision.
8
+ *
9
+ * - No server and no client code: declarative assets only, no extension process.
10
+ * - Every server declaration has an isolated contract and the supervisor is available: isolated.
11
+ * - A server declaration without an isolated contract: in-process server only under a full-access
12
+ * grant for the server realm; every such declaration is a forcing key (a provider contract's own
13
+ * `execution.provider.unsupported:<point>` key for a provided point).
14
+ * - A host configured without isolation: the kernel adds `host.no-isolation` to the server realm.
15
+ * - A supervisor configured but failing: a revision that would run isolated is unavailable (fail
16
+ * closed, never an in-process fallback); one already forced into the server realm is unaffected.
17
+ * - A client entry runs in the isolated client realm when it declares `isolated` and the kernel
18
+ * provides that realm (`ISOLATED_CLIENT_REALM_AVAILABLE`); otherwise it needs browser full
19
+ * access, forced by its client declarations.
20
+ * - A deployment config schema outside the isolated tier's declarative subset forces server full
21
+ * access through the kernel's `execution.config.unsupported` key, whether or not it declares a
22
+ * field.
23
+ * - A service declared to run outside the device sandbox forces device full access.
24
+ *
25
+ * A key no catalog row matches exactly once is unknown: it is reported, and treated as forcing
26
+ * server full access (fail closed) so it is never silently isolated.
27
+ */
28
+ /** The host's isolation supervisor, as the kernel sees it. */
29
+ export type HostIsolation = "available" | "not_configured" | "failing";
30
+ /** The realm a client entry declares (`client.realm`); undeclared counts as `inPage`. */
31
+ export type ClientRealm = "isolated" | "inPage";
32
+ export declare const HOST_NO_ISOLATION_KEY = "host.no-isolation";
33
+ export interface ExecutionInput {
34
+ /** The canonical permission keys of the reviewed revision (`permissionKeys`). */
35
+ keys: readonly string[];
36
+ /** The revision carries server code (an extension entry). */
37
+ server: boolean;
38
+ /** The revision carries a client entry, with its declared realm. */
39
+ client?: {
40
+ realm?: ClientRealm;
41
+ } | undefined;
42
+ host: HostIsolation;
43
+ /**
44
+ * Whether the deployment config schema fits the isolated tier's declarative subset
45
+ * (`deploymentConfigIsolatable`); a schema outside it forces server full access through
46
+ * {@link CONFIG_SCHEMA_UNSUPPORTED_KEY}. Defaults to true (no config, or a supported schema).
47
+ */
48
+ configSchemaIsolatable?: boolean;
49
+ }
50
+ export type RealmPlacement =
51
+ /** Nothing runs in this realm. */
52
+ {
53
+ mode: "none";
54
+ }
55
+ /** It runs in the realm's isolated form. */
56
+ | {
57
+ mode: "isolated";
58
+ }
59
+ /** It runs with the realm's privileges, only under a grant covering these forcing keys. */
60
+ | {
61
+ mode: "full-access";
62
+ forcingKeys: string[];
63
+ }
64
+ /** It would run isolated, but the isolation supervisor is failing: unavailable, fail closed. */
65
+ | {
66
+ mode: "unavailable";
67
+ reason: "isolation_unavailable";
68
+ };
69
+ export interface ExecutionDecision {
70
+ kind: "declarative" | "code";
71
+ server: RealmPlacement;
72
+ browser: RealmPlacement;
73
+ device: RealmPlacement;
74
+ /**
75
+ * The full-access realms a grant must cover, each with its forcing keys: the `realms` of a
76
+ * revision grant, whose `execution.full-access:<realm>` keys come from {@link fullAccessKeys}.
77
+ */
78
+ fullAccess: Partial<Record<ExecutionRealm, string[]>>;
79
+ /** Keys no catalog row matches exactly once: the review shows and refuses them. */
80
+ unknownKeys: string[];
81
+ /**
82
+ * False when there is an unknown key, whatever the revision carries (a declarative-only or
83
+ * client-only revision included): such a decision can never be confirmed.
84
+ */
85
+ confirmable: boolean;
86
+ }
87
+ /**
88
+ * The kernel's forcing key of a deployment config schema outside the isolated subset. The config
89
+ * field keys stay what they are (each fits isolation); the schema itself is what forces.
90
+ */
91
+ export declare const CONFIG_SCHEMA_UNSUPPORTED_KEY = "execution.config.unsupported";
92
+ export declare function executionDecision(input: ExecutionInput): ExecutionDecision;
93
+ /** The kernel-generated `execution.full-access:<realm>` keys a decision's grant must carry. */
94
+ export declare function fullAccessKeys(decision: Pick<ExecutionDecision, "fullAccess">): string[];
95
+ /** A one-line summary for review lists and `capybara-plugin check`. */
96
+ export declare function describeExecution(decision: ExecutionDecision): string;