@feltdb/feltkit 0.3.30 → 0.3.32

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 (157) hide show
  1. package/dist/app.d.ts +67 -11
  2. package/dist/app.js +58 -2
  3. package/dist/app.js.map +1 -1
  4. package/dist/appboundry/build.js +2 -0
  5. package/dist/appboundry/build.js.map +1 -1
  6. package/dist/appboundry/guest.js +23 -1
  7. package/dist/appboundry/guest.js.map +1 -1
  8. package/dist/authorize.d.ts +24 -3
  9. package/dist/authorize.js.map +1 -1
  10. package/dist/broker/assertion.d.ts +68 -0
  11. package/dist/broker/assertion.js +104 -0
  12. package/dist/broker/assertion.js.map +1 -0
  13. package/dist/broker/keys.d.ts +9 -0
  14. package/dist/broker/keys.js +47 -0
  15. package/dist/broker/keys.js.map +1 -0
  16. package/dist/broker/server.d.ts +54 -0
  17. package/dist/broker/server.js +305 -0
  18. package/dist/broker/server.js.map +1 -0
  19. package/dist/cli/broker.d.ts +11 -0
  20. package/dist/cli/broker.js +72 -0
  21. package/dist/cli/broker.js.map +1 -0
  22. package/dist/cli/deploy.js +6 -0
  23. package/dist/cli/deploy.js.map +1 -1
  24. package/dist/cli/main.js +123 -0
  25. package/dist/cli/main.js.map +1 -1
  26. package/dist/client/index.d.ts +8 -2
  27. package/dist/client/index.js +45 -1
  28. package/dist/client/index.js.map +1 -1
  29. package/dist/docs.d.ts +1 -1
  30. package/dist/docs.js +3 -0
  31. package/dist/docs.js.map +1 -1
  32. package/dist/extension/build.d.ts +50 -0
  33. package/dist/extension/build.js +205 -0
  34. package/dist/extension/build.js.map +1 -0
  35. package/dist/extension/client-shim.d.ts +7 -0
  36. package/dist/extension/client-shim.js +13 -0
  37. package/dist/extension/client-shim.js.map +1 -0
  38. package/dist/extension/connect-ui.d.ts +24 -0
  39. package/dist/extension/connect-ui.js +67 -0
  40. package/dist/extension/connect-ui.js.map +1 -0
  41. package/dist/extension/connection.d.ts +109 -0
  42. package/dist/extension/connection.js +190 -0
  43. package/dist/extension/connection.js.map +1 -0
  44. package/dist/extension/host-core.d.ts +36 -0
  45. package/dist/extension/host-core.js +50 -0
  46. package/dist/extension/host-core.js.map +1 -0
  47. package/dist/extension/host.d.ts +1 -0
  48. package/dist/extension/host.js +8 -0
  49. package/dist/extension/host.js.map +1 -0
  50. package/dist/extension/icons.d.ts +13 -0
  51. package/dist/extension/icons.js +75 -0
  52. package/dist/extension/icons.js.map +1 -0
  53. package/dist/extension/identity.d.ts +40 -0
  54. package/dist/extension/identity.js +110 -0
  55. package/dist/extension/identity.js.map +1 -0
  56. package/dist/extension/options.d.ts +1 -0
  57. package/dist/extension/options.js +57 -0
  58. package/dist/extension/options.js.map +1 -0
  59. package/dist/extension/service-worker.d.ts +1 -0
  60. package/dist/extension/service-worker.js +38 -0
  61. package/dist/extension/service-worker.js.map +1 -0
  62. package/dist/extension/validate.d.ts +7 -0
  63. package/dist/extension/validate.js +143 -0
  64. package/dist/extension/validate.js.map +1 -0
  65. package/dist/extension/zip.d.ts +7 -0
  66. package/dist/extension/zip.js +94 -0
  67. package/dist/extension/zip.js.map +1 -0
  68. package/dist/index.d.ts +6 -2
  69. package/dist/index.js +1 -0
  70. package/dist/index.js.map +1 -1
  71. package/dist/policy.d.ts +179 -0
  72. package/dist/policy.js +311 -0
  73. package/dist/policy.js.map +1 -0
  74. package/dist/runtime/activity.d.ts +16 -0
  75. package/dist/runtime/activity.js.map +1 -1
  76. package/dist/runtime/application-authority.d.ts +22 -3
  77. package/dist/runtime/application-authority.js +94 -20
  78. package/dist/runtime/application-authority.js.map +1 -1
  79. package/dist/runtime/assemble.d.ts +13 -0
  80. package/dist/runtime/assemble.js +29 -1
  81. package/dist/runtime/assemble.js.map +1 -1
  82. package/dist/runtime/authority-contract.d.ts +55 -0
  83. package/dist/runtime/authority-contract.js +60 -0
  84. package/dist/runtime/authority-contract.js.map +1 -0
  85. package/dist/runtime/content.d.ts +50 -0
  86. package/dist/runtime/content.js +98 -1
  87. package/dist/runtime/content.js.map +1 -1
  88. package/dist/runtime/context.d.ts +86 -11
  89. package/dist/runtime/contract.js +11 -2
  90. package/dist/runtime/contract.js.map +1 -1
  91. package/dist/runtime/data.d.ts +25 -0
  92. package/dist/runtime/data.js +92 -8
  93. package/dist/runtime/data.js.map +1 -1
  94. package/dist/runtime/image-variants.d.ts +48 -0
  95. package/dist/runtime/image-variants.js +295 -0
  96. package/dist/runtime/image-variants.js.map +1 -0
  97. package/dist/runtime/integrations.d.ts +2 -0
  98. package/dist/runtime/integrations.js +10 -7
  99. package/dist/runtime/integrations.js.map +1 -1
  100. package/dist/runtime/invocations.d.ts +3 -0
  101. package/dist/runtime/invocations.js +1 -1
  102. package/dist/runtime/invocations.js.map +1 -1
  103. package/dist/runtime/live.d.ts +10 -7
  104. package/dist/runtime/live.js +24 -12
  105. package/dist/runtime/live.js.map +1 -1
  106. package/dist/runtime/local-authority.d.ts +80 -5
  107. package/dist/runtime/local-authority.js +259 -14
  108. package/dist/runtime/local-authority.js.map +1 -1
  109. package/dist/runtime/policies.d.ts +89 -0
  110. package/dist/runtime/policies.js +152 -0
  111. package/dist/runtime/policies.js.map +1 -0
  112. package/dist/runtime/readiness.js +31 -1
  113. package/dist/runtime/readiness.js.map +1 -1
  114. package/dist/runtime/runtime.d.ts +21 -1
  115. package/dist/runtime/runtime.js +200 -7
  116. package/dist/runtime/runtime.js.map +1 -1
  117. package/dist/runtime/services-rules.d.ts +9 -0
  118. package/dist/runtime/services-rules.js +47 -1
  119. package/dist/runtime/services-rules.js.map +1 -1
  120. package/dist/runtime/services.d.ts +117 -9
  121. package/dist/runtime/services.js +154 -13
  122. package/dist/runtime/services.js.map +1 -1
  123. package/dist/server/admin.d.ts +21 -0
  124. package/dist/server/admin.js +114 -0
  125. package/dist/server/admin.js.map +1 -1
  126. package/dist/server/index.js +33 -6
  127. package/dist/server/index.js.map +1 -1
  128. package/dist/server/oauth.d.ts +32 -2
  129. package/dist/server/oauth.js +130 -23
  130. package/dist/server/oauth.js.map +1 -1
  131. package/dist/server/operators.d.ts +1 -0
  132. package/dist/server/operators.js +1 -1
  133. package/dist/server/operators.js.map +1 -1
  134. package/dist/server/project.d.ts +3 -0
  135. package/dist/server/project.js +2 -2
  136. package/dist/server/project.js.map +1 -1
  137. package/dist/testing/index.d.ts +11 -0
  138. package/dist/testing/index.js +7 -0
  139. package/dist/testing/index.js.map +1 -1
  140. package/docs/AGENT-OPERATIONS.md +1 -1
  141. package/docs/ARCHITECTURE.md +2 -1
  142. package/docs/CONNECTIONS.md +10 -3
  143. package/docs/EXTENSION-HOSTS.md +64 -5
  144. package/docs/GUARANTEES.md +82 -6
  145. package/docs/LOCAL-AUTHORITY.md +118 -0
  146. package/docs/POLICIES.md +121 -0
  147. package/docs/README.md +5 -2
  148. package/docs/SECURITY.md +69 -0
  149. package/docs/SIGN-IN-BROKER.md +77 -0
  150. package/docs/TRANSACTIONS.md +4 -0
  151. package/package.json +13 -9
  152. package/skills/.claude-plugin/marketplace.json +1 -1
  153. package/skills/.claude-plugin/plugin.json +1 -1
  154. package/skills/feltkit-agent/SKILL.md +1 -1
  155. package/skills/feltkit-build/SKILL.md +10 -0
  156. package/skills/feltkit-data/SKILL.md +13 -1
  157. package/skills/feltkit-services/SKILL.md +14 -1
@@ -10,6 +10,8 @@
10
10
  import { JOB_CONTEXTS_COLLECTION, jobIdOfRun } from "./job-context.js";
11
11
  import { checkTokenBytes } from "./crypto-token.js";
12
12
  import { evaluateAuthorize, evaluateOwnership } from "../authorize.js";
13
+ import { evaluatePolicies, viaCollections } from "../policy.js";
14
+ import { PolicyStore } from "./policies.js";
13
15
  import { eventDefinitions, observationAuthorizer, stageEvent } from "./events.js";
14
16
  import { AppPortError, createApplication, defineCapability, createMcpBridge, errors as appportErrors, idempotencyStorageKey } from "@appport/sdk";
15
17
  import { grantsPermission } from "@appport/authorization";
@@ -31,7 +33,7 @@ import { Authority, authContext, fromAppPortPrincipal, normalizePrincipal, toApp
31
33
  import { ChangeFeed } from "./changes.js";
32
34
  import { generationDigest } from "./generation.js";
33
35
  import { ModelHost } from "./decisions.js";
34
- import { CollectionResolver, Reader, Writer, applicationView, ensureCollectionMarkers, feltdbRefusalJSON, readAll } from "./data.js";
36
+ import { CollectionResolver, Reader, Writer, applicationView, ensureCollectionMarkers, ensureOrderedIndexes, feltdbRefusalJSON, readAll } from "./data.js";
35
37
  import { describeStorage } from "./environment.js";
36
38
  import { defaultInstanceFactory } from "./instance.js";
37
39
  import { explainServiceDenials, ServicesHost } from "./services.js";
@@ -117,6 +119,7 @@ export class FeltKitRuntime {
117
119
  startedAt = new Date().toISOString();
118
120
  #project;
119
121
  #authority;
122
+ #policyStore;
120
123
  #services;
121
124
  #appport;
122
125
  #resolver;
@@ -137,6 +140,10 @@ export class FeltKitRuntime {
137
140
  /** The settings this runtime reads (RuntimeStartOptions.env). */
138
141
  #env = process.env;
139
142
  recentErrors = [];
143
+ /** The settings this runtime reads (where the authority's address resolves, for one). */
144
+ get settings() {
145
+ return this.#env;
146
+ }
140
147
  constructor(environment, instance, logger, env = process.env) {
141
148
  this.#env = env;
142
149
  this.environment = environment;
@@ -194,6 +201,7 @@ export class FeltKitRuntime {
194
201
  await runtime.#ensureSchema(options.project.app, "start");
195
202
  step("schema");
196
203
  await ensureCollectionMarkers(instance.handle("feltkit.runtime"), options.project.app.collections.keys());
204
+ await runtime.#orderedIndexes(options.project.app);
197
205
  step("markers");
198
206
  await runtime.#services.check();
199
207
  step("services");
@@ -362,6 +370,14 @@ export class FeltKitRuntime {
362
370
  this.logger.info(`Schema ${from} → v${applied.to.version} applied${what.length ? `: ${what.join(", ")}` : " (FeltDB now enforces it)"}`);
363
371
  }
364
372
  }
373
+ /** Indexes with a "desc" direction, declared to an embedded FeltDB (a FeltDB server has the contract's). */
374
+ async #orderedIndexes(app) {
375
+ if (this.environment.storage.kind === "remote")
376
+ return;
377
+ const declared = await ensureOrderedIndexes(this.instance.handle("feltkit.runtime"), app.collections.values());
378
+ if (declared.length)
379
+ this.logger.info(`Ordered indexes declared: ${declared.join(", ")}`);
380
+ }
365
381
  async reload(project) {
366
382
  this.#assertReady();
367
383
  if (project.app.name !== this.#project.app.name) {
@@ -371,6 +387,7 @@ export class FeltKitRuntime {
371
387
  const previous = this.#appport;
372
388
  this.#install(project);
373
389
  await this.#ensureSchema(project.app, "reload");
390
+ await this.#orderedIndexes(project.app);
374
391
  this.#agent?.define();
375
392
  await previous.close().catch(() => undefined);
376
393
  for (const listener of this.#reloadListeners)
@@ -517,9 +534,12 @@ export class FeltKitRuntime {
517
534
  appName: this.app.name,
518
535
  env: this.#env,
519
536
  localUrl: () => this.localAuthority.url(),
537
+ localState: () => this.localAuthority.status.state,
520
538
  grants: this.localAuthority.grantsFor(principal, requestId),
521
- record: async ({ capability, executor, onBehalfOf, decision, durationMs }) => {
522
- await this.invocations.noteDecision(requestId, { capability, onBehalfOf, outcome: decision.outcome, decisionId: decision.decisionId, delegationId: decision.delegationId, executor: decision.executorProof });
539
+ agents: this.localAuthority.agentsFor(principal, requestId),
540
+ agentFor: (requested) => this.localAuthority.agentDecision(principal, requested),
541
+ record: async ({ capability, executor, onBehalfOf, decision, durationMs, authorityMode }) => {
542
+ await this.invocations.noteDecision(requestId, { capability, onBehalfOf, outcome: decision.outcome, decisionId: decision.decisionId, delegationId: decision.delegationId, executor: decision.executorProof, authorityMode });
523
543
  this.activity.record({
524
544
  kind: "auth",
525
545
  name: "authority.decide",
@@ -528,7 +548,7 @@ export class FeltKitRuntime {
528
548
  principal: principal ? { id: principal.id, type: principal.type, roles: principal.roles } : null,
529
549
  outcome: decision.allowed ? "success" : decision.outcome === "deny" ? "denied" : "error",
530
550
  durationMs,
531
- detail: { capability, executor, onBehalfOf, outcome: decision.outcome, decisionId: decision.decisionId, delegationId: decision.delegationId, reason: decision.reason, executorProof: decision.executorProof },
551
+ detail: { capability, executor, onBehalfOf, outcome: decision.outcome, decisionId: decision.decisionId, delegationId: decision.delegationId, reason: decision.reason, executorProof: decision.executorProof, authorityMode },
532
552
  });
533
553
  },
534
554
  });
@@ -611,7 +631,9 @@ export class FeltKitRuntime {
611
631
  if (!parsed.ok) {
612
632
  throw new FeltKitError("INVALID_ARGUMENT", `Invalid input for ${capability}: ${parsed.issues.map((i) => `${i.path}: ${i.message}`).join("; ")}`, { details: { issues: parsed.issues } });
613
633
  }
614
- return this.integrations.invoke(capability, parsed.value, { principal, via: "function", ...(options.idempotencyKey ? { idempotencyKey: options.idempotencyKey } : {}), ...(options.onBehalfOf !== undefined ? { onBehalfOf: options.onBehalfOf } : {}) });
634
+ const requestId = `req_${randomUUID()}`;
635
+ await this.#authorizeIntegration(capability, found.op, parsed.value, principal, "function", requestId);
636
+ return this.integrations.invoke(capability, parsed.value, { principal, via: "function", requestId, ...(options.idempotencyKey ? { idempotencyKey: options.idempotencyKey } : {}), ...(options.onBehalfOf !== undefined ? { onBehalfOf: options.onBehalfOf } : {}) });
615
637
  },
616
638
  };
617
639
  }
@@ -632,6 +654,7 @@ export class FeltKitRuntime {
632
654
  const principal = fromAppPortPrincipal(context.principal ?? context.session?.principal);
633
655
  this.#dispatched.add(context.requestId);
634
656
  try {
657
+ await this.#authorizeIntegration(op.capability, op, input, principal, String(context.transport ?? "appport"), context.requestId);
635
658
  return await this.integrations.invoke(op.capability, input, {
636
659
  principal,
637
660
  requestId: context.requestId,
@@ -1406,12 +1429,16 @@ export class FeltKitRuntime {
1406
1429
  ...(options.appportDecisionId ? { appportDecisionId: options.appportDecisionId } : {}),
1407
1430
  };
1408
1431
  if (!decision.allowed) {
1432
+ // Durable evidence for a signed-in caller's refusal (an anonymous caller refused before sign-in is in the activity log only).
1433
+ if (principal)
1434
+ await this.#recordDecision({ function: name, via: String(options.via), requestId, principal: { id: principal.id, type: principal.type, roles: [...principal.roles] }, ...(principal.tenant ? { tenant: { id: principal.tenant.id, role: principal.tenant.role } } : {}), outcome: "denied", layer: "role", reason: decision.reason ?? `requires ${decision.required}`, argKeys: argKeys(rawArgs) ?? [] });
1409
1435
  return failure(new FeltKitError(decision.code ?? "FORBIDDEN", decision.reason ?? "Not allowed"), { authority: authorityRecord, argKeys: argKeys(rawArgs) });
1410
1436
  }
1411
1437
  // The approval requirement, at the execution boundary every interface goes through (/api,
1412
1438
  // AppPort, MCP, jobs, decisions): permission alone is not enough for a non-person caller.
1413
1439
  const approvalRefusal = this.#approvalRefusal(name, fn, principal);
1414
1440
  if (approvalRefusal) {
1441
+ await this.#recordDecision({ function: name, via: String(options.via), requestId, principal: principal ? { id: principal.id, type: principal.type, roles: [...principal.roles] } : null, outcome: "denied", layer: "approval", reason: approvalRefusal, argKeys: argKeys(rawArgs) ?? [] });
1415
1442
  return failure(new FeltKitError("FORBIDDEN", approvalRefusal, { details: { approval: "required" }, hint: "Ask a person to run it, or propose it and wait for their approval." }), { authority: { ...authorityRecord, allowed: false, reason: "approval required" }, argKeys: argKeys(rawArgs) });
1416
1443
  }
1417
1444
  const approvedAction = fn.approval === "required" && principal?.type !== "user" ? this.#approvedAction.getStore() : undefined;
@@ -1751,17 +1778,178 @@ export class FeltKitRuntime {
1751
1778
  return failure(error, { authority: authorityRecord, argKeys: Object.keys(args) });
1752
1779
  }
1753
1780
  }
1781
+ /** Managed policies and decision evidence (runtime/policies.ts), in the application's FeltDB instance. */
1782
+ get policyStore() {
1783
+ this.#policyStore ??= new PolicyStore({
1784
+ db: () => this.instance.handle("feltkit.policies"),
1785
+ code: () => this.#project?.policies ?? [],
1786
+ validate: (rule) => {
1787
+ for (const fn of rule.functions) {
1788
+ // A function, or (managed policies only, by capability name) an integration operation.
1789
+ if (!this.#project?.functions.has(fn) && !(rule.source === "managed" && this.integrations.operationFor(fn))) {
1790
+ throw new FeltKitError("CONFIGURATION", `Policy ${rule.id} names ${fn}, which this application does not define.`);
1791
+ }
1792
+ }
1793
+ for (const via of (rule.when ?? []).flatMap(viaCollections)) {
1794
+ if (typeof via !== "string" || !this.app.collections.has(via))
1795
+ throw new FeltKitError("CONFIGURATION", `Policy ${rule.id} reads owner.via from ${typeof via === "string" ? via : via.name}, which this application does not declare.`);
1796
+ }
1797
+ if (rule.resource && !this.app.collections.has(rule.resource.collection)) {
1798
+ throw new FeltKitError("CONFIGURATION", `Policy ${rule.id} names collection ${rule.resource.collection}, which this application does not declare.`);
1799
+ }
1800
+ },
1801
+ });
1802
+ return this.#policyStore;
1803
+ }
1804
+ /**
1805
+ * Evaluate the policies for a call without running it (no handler, no writes, no evidence): what a
1806
+ * policy permits, for whom, and why. Reads the real records the policy would read. A delegation
1807
+ * condition asks AuthBoundry, as the call would.
1808
+ */
1809
+ async simulatePolicy(input) {
1810
+ if (!this.#project?.functions.has(input.function) && !this.integrations.operationFor(input.function))
1811
+ throw new FeltKitError("FUNCTION_NOT_FOUND", `No function or integration operation named "${input.function}".`);
1812
+ const requestId = input.requestId ?? `sim_${randomUUID()}`;
1813
+ const db = this.#readerFor(input.principal);
1814
+ return evaluatePolicies(await this.policyStore.current(), this.#policyRequest(input.function, input.principal, input.args ?? {}, db, requestId));
1815
+ }
1816
+ /** A read-only view of the application's data for a decision made outside a function's own transaction. */
1817
+ #readerFor(principal) {
1818
+ const reader = new Reader(this.instance.handle("app"), this.#resolver);
1819
+ return hasTenantCollections(this.app.collections.values()) ? scopeToTenant(reader, (ref) => this.#resolver.resolve(ref), principal?.tenant?.id ?? null) : applicationView(reader);
1820
+ }
1821
+ /**
1822
+ * An integration operation's authorization beyond its role `access`, on every path that reaches
1823
+ * it (its AppPort/MCP capability, `ctx.integrations.invoke`, verification probes): the managed
1824
+ * policies that name its capability, then `feltkit({ authorize })` with `kind: "integration"`.
1825
+ * Refusals are durable evidence, as for functions.
1826
+ */
1827
+ async #authorizeIntegration(capability, op, input, principal, via, requestId) {
1828
+ const hook = this.app.options.authorize;
1829
+ const set = await this.policyStore.current();
1830
+ const governed = set.rules.some((rule) => rule.functions.includes(capability));
1831
+ if (!hook && !governed)
1832
+ return;
1833
+ const db = this.#readerFor(principal);
1834
+ const evidence = (outcome, layer, reason, policy) => ({
1835
+ function: capability,
1836
+ via,
1837
+ requestId,
1838
+ principal: principal ? { id: principal.id, type: principal.type, roles: [...principal.roles] } : null,
1839
+ ...(principal?.tenant ? { tenant: { id: principal.tenant.id, role: principal.tenant.role } } : {}),
1840
+ outcome,
1841
+ layer,
1842
+ reason,
1843
+ ...(policy ? { policyVersion: policy.policyVersion, matched: policy.matched, unmet: policy.unmet, delegations: policy.delegations } : {}),
1844
+ argKeys: Object.keys(input).sort(),
1845
+ });
1846
+ let policy;
1847
+ if (governed) {
1848
+ policy = await evaluatePolicies(set, this.#policyRequest(capability, principal, input, db, requestId));
1849
+ if (!policy.allowed) {
1850
+ await this.#recordDecision(evidence("denied", "policy", policy.reason, policy));
1851
+ throw new FeltKitError(principal ? "FORBIDDEN" : "UNAUTHORIZED", policy.reason, { details: { policy: "denied", matched: policy.matched, unmet: policy.unmet } });
1852
+ }
1853
+ if (policy.durable)
1854
+ await this.#recordDecision(evidence("allowed", "policy", policy.reason, policy));
1855
+ }
1856
+ if (!hook)
1857
+ return;
1858
+ try {
1859
+ await evaluateAuthorize(hook, {
1860
+ function: capability,
1861
+ kind: "integration",
1862
+ access: op.access,
1863
+ capability: { name: capability, version: 1 },
1864
+ principal,
1865
+ args: input,
1866
+ transport: via,
1867
+ requestId,
1868
+ db,
1869
+ ...(policy?.governed ? { policy: { allowed: policy.allowed, matched: policy.matched, version: policy.policyVersion } } : {}),
1870
+ });
1871
+ }
1872
+ catch (error) {
1873
+ if (isFeltKitError(error) && (error.code === "FORBIDDEN" || error.code === "UNAUTHORIZED" || error.code === "NOT_FOUND"))
1874
+ await this.#recordDecision(evidence("denied", "authorize", error.message));
1875
+ throw error;
1876
+ }
1877
+ }
1878
+ #policyRequest(name, principal, args, db, requestId) {
1879
+ return {
1880
+ function: name,
1881
+ principal,
1882
+ args,
1883
+ db,
1884
+ collection: (collection) => this.app.collections.get(collection),
1885
+ delegate: async ({ capability, onBehalfOf }) => {
1886
+ // A bare id in a record or argument names a person (AuthBoundry's "user:<id>").
1887
+ const person = onBehalfOf.includes(":") ? onBehalfOf : `user:${onBehalfOf}`;
1888
+ const decision = await this.#applicationAuthority(principal, requestId).decide({ capability, onBehalfOf: person });
1889
+ return { allowed: decision.allowed, decisionId: decision.decisionId, delegationId: decision.delegationId, authorityMode: decision.authorityMode, ...(decision.reason ? { reason: decision.reason } : {}) };
1890
+ },
1891
+ };
1892
+ }
1893
+ /**
1894
+ * Durable decision evidence. A refusal is recorded before the caller sees it; if the record cannot
1895
+ * be written the refusal still stands (it is logged). An allow that requires durable evidence is
1896
+ * refused when its record cannot be written: the effect never runs without its evidence.
1897
+ */
1898
+ async #recordDecision(entry) {
1899
+ try {
1900
+ await this.policyStore.record(entry);
1901
+ }
1902
+ catch (error) {
1903
+ if (entry.outcome === "allowed")
1904
+ throw new FeltKitError("UNAVAILABLE", `The decision for ${entry.function} could not be recorded, so it does not run: ${error.message}`);
1905
+ this.logger.error(`Decision evidence for a refusal of ${entry.function} could not be recorded: ${error.message}`);
1906
+ }
1907
+ }
1754
1908
  async #authorizeResource(name, fn, args, principal, options, requestId, db, record) {
1755
1909
  const hook = this.app.options.authorize;
1756
- if (!hook && !fn.owner)
1910
+ const set = await this.policyStore.current();
1911
+ const governed = set.rules.some((rule) => rule.functions.includes(name));
1912
+ if (!hook && !fn.owner && !governed)
1757
1913
  return;
1914
+ const evidence = (outcome, layer, reason, policy) => ({
1915
+ function: name,
1916
+ via: String(options.via),
1917
+ requestId,
1918
+ principal: principal ? { id: principal.id, type: principal.type, roles: [...principal.roles] } : null,
1919
+ ...(principal?.tenant ? { tenant: { id: principal.tenant.id, role: principal.tenant.role } } : {}),
1920
+ outcome,
1921
+ layer,
1922
+ reason,
1923
+ ...(policy ? { policyVersion: policy.policyVersion, matched: policy.matched, unmet: policy.unmet, delegations: policy.delegations } : {}),
1924
+ argKeys: Object.keys(args).sort(),
1925
+ });
1926
+ let layer = "owner";
1927
+ let recorded = false;
1758
1928
  try {
1759
- // The function's declared ownership first (fails closed), then the application's hook.
1929
+ // The function's declared ownership first (fails closed), then the policies, then the hook.
1760
1930
  const owned = await evaluateOwnership(fn, { function: name, principal, args, db });
1761
1931
  if (owned)
1762
1932
  record.resource = owned;
1933
+ let policy;
1934
+ if (governed) {
1935
+ layer = "policy";
1936
+ policy = await evaluatePolicies(set, this.#policyRequest(name, principal, args, db, requestId));
1937
+ record.policy = { version: policy.policyVersion, matched: [...policy.matched], ...(policy.unmet.length ? { unmet: [...policy.unmet] } : {}), ...(policy.delegations.length ? { delegations: [...policy.delegations] } : {}) };
1938
+ if (!policy.allowed) {
1939
+ await this.#recordDecision(evidence("denied", "policy", policy.reason, policy));
1940
+ recorded = true;
1941
+ throw new FeltKitError(principal ? "FORBIDDEN" : "UNAUTHORIZED", policy.reason, { details: { policy: "denied", matched: policy.matched, unmet: policy.unmet } });
1942
+ }
1943
+ if (policy.governed)
1944
+ record.resource = { allowed: true, reason: policy.reason };
1945
+ if (policy.durable)
1946
+ await this.#recordDecision(evidence("allowed", "policy", policy.reason, policy));
1947
+ }
1763
1948
  if (!hook)
1764
1949
  return;
1950
+ layer = "authorize";
1951
+ const run = options.agentRun?.trigger;
1952
+ const approved = fn.approval === "required" && principal?.type !== "user" ? this.#approvedAction.getStore() : undefined;
1765
1953
  const decision = await evaluateAuthorize(hook, {
1766
1954
  function: name,
1767
1955
  definition: fn,
@@ -1773,6 +1961,9 @@ export class FeltKitRuntime {
1773
1961
  transport: options.via,
1774
1962
  requestId,
1775
1963
  db,
1964
+ ...(policy?.governed ? { policy: { allowed: policy.allowed, matched: policy.matched, version: policy.policyVersion } } : {}),
1965
+ ...(run ? { agentRun: { agent: run.agent, triggeredBy: run.by.principalId } } : {}),
1966
+ ...(approved ? { approval: { taskId: approved.taskId, actionId: approved.actionId, approvedBy: approved.approvedBy } } : {}),
1776
1967
  });
1777
1968
  if (decision)
1778
1969
  record.resource = decision;
@@ -1782,6 +1973,8 @@ export class FeltKitRuntime {
1782
1973
  if (isFeltKitError(error) && (error.code === "FORBIDDEN" || error.code === "UNAUTHORIZED" || error.code === "NOT_FOUND")) {
1783
1974
  record.allowed = false;
1784
1975
  record.resource = { allowed: false, reason: error.message };
1976
+ if (!recorded)
1977
+ await this.#recordDecision(evidence("denied", layer, error.message));
1785
1978
  }
1786
1979
  throw error;
1787
1980
  }