@feltdb/feltkit 0.3.36 → 0.4.0
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/app.d.ts +153 -3
- package/dist/app.js +159 -7
- package/dist/app.js.map +1 -1
- package/dist/appboundry/build.js +21 -0
- package/dist/appboundry/build.js.map +1 -1
- package/dist/appboundry/guest.js +4 -0
- package/dist/appboundry/guest.js.map +1 -1
- package/dist/client/index.d.ts +189 -0
- package/dist/client/index.js +201 -0
- package/dist/client/index.js.map +1 -1
- package/dist/clock.d.ts +24 -0
- package/dist/clock.js +49 -0
- package/dist/clock.js.map +1 -0
- package/dist/dashboard/assets/index-BhxrvY37.js +15 -0
- package/dist/dashboard/assets/index-CSzYeCo_.css +1 -0
- package/dist/dashboard/index.html +2 -2
- package/dist/docs.d.ts +1 -1
- package/dist/docs.js +1 -0
- package/dist/docs.js.map +1 -1
- package/dist/event-stage.js +2 -0
- package/dist/event-stage.js.map +1 -1
- package/dist/index.d.ts +11 -1
- package/dist/index.js +1 -0
- package/dist/index.js.map +1 -1
- package/dist/policy.d.ts +9 -1
- package/dist/policy.js +16 -3
- package/dist/policy.js.map +1 -1
- package/dist/presence.d.ts +85 -0
- package/dist/presence.js +37 -0
- package/dist/presence.js.map +1 -0
- package/dist/quota.d.ts +72 -0
- package/dist/quota.js +143 -0
- package/dist/quota.js.map +1 -0
- package/dist/react/agent-control.d.ts +189 -0
- package/dist/react/agent-control.js +366 -0
- package/dist/react/agent-control.js.map +1 -0
- package/dist/react/index.d.ts +14 -1
- package/dist/react/index.js +41 -0
- package/dist/react/index.js.map +1 -1
- package/dist/runtime/activity.d.ts +8 -0
- package/dist/runtime/activity.js.map +1 -1
- package/dist/runtime/agent-control.d.ts +18 -0
- package/dist/runtime/agent-control.js +34 -1
- package/dist/runtime/agent-control.js.map +1 -1
- package/dist/runtime/agent.js +16 -4
- package/dist/runtime/agent.js.map +1 -1
- package/dist/runtime/assemble.js +1 -1
- package/dist/runtime/assemble.js.map +1 -1
- package/dist/runtime/authority.d.ts +38 -0
- package/dist/runtime/authority.js +13 -2
- package/dist/runtime/authority.js.map +1 -1
- package/dist/runtime/capabilities.js +2 -1
- package/dist/runtime/capabilities.js.map +1 -1
- package/dist/runtime/changes.d.ts +17 -0
- package/dist/runtime/changes.js +65 -2
- package/dist/runtime/changes.js.map +1 -1
- package/dist/runtime/context.d.ts +114 -0
- package/dist/runtime/contract.js +9 -3
- package/dist/runtime/contract.js.map +1 -1
- package/dist/runtime/events.js +17 -1
- package/dist/runtime/events.js.map +1 -1
- package/dist/runtime/integrations.js +7 -7
- package/dist/runtime/integrations.js.map +1 -1
- package/dist/runtime/invocations.d.ts +19 -2
- package/dist/runtime/invocations.js +16 -3
- package/dist/runtime/invocations.js.map +1 -1
- package/dist/runtime/policies.d.ts +5 -2
- package/dist/runtime/policies.js.map +1 -1
- package/dist/runtime/presence-host.d.ts +84 -0
- package/dist/runtime/presence-host.js +303 -0
- package/dist/runtime/presence-host.js.map +1 -0
- package/dist/runtime/providers.d.ts +130 -1
- package/dist/runtime/providers.js +251 -9
- package/dist/runtime/providers.js.map +1 -1
- package/dist/runtime/resource-access.d.ts +137 -0
- package/dist/runtime/resource-access.js +177 -0
- package/dist/runtime/resource-access.js.map +1 -0
- package/dist/runtime/runtime.d.ts +73 -0
- package/dist/runtime/runtime.js +594 -37
- package/dist/runtime/runtime.js.map +1 -1
- package/dist/runtime/sessions.d.ts +11 -0
- package/dist/runtime/sessions.js +15 -0
- package/dist/runtime/sessions.js.map +1 -1
- package/dist/runtime/tenancy.d.ts +59 -0
- package/dist/runtime/tenancy.js +128 -0
- package/dist/runtime/tenancy.js.map +1 -1
- package/dist/runtime/workers.d.ts +123 -0
- package/dist/runtime/workers.js +291 -0
- package/dist/runtime/workers.js.map +1 -0
- package/dist/server/admin.js +48 -1
- package/dist/server/admin.js.map +1 -1
- package/dist/server/index.d.ts +0 -19
- package/dist/server/index.js +61 -4
- package/dist/server/index.js.map +1 -1
- package/dist/server/mcp.d.ts +8 -15
- package/dist/server/mcp.js +40 -3
- package/dist/server/mcp.js.map +1 -1
- package/dist/server/project.js +6 -5
- package/dist/server/project.js.map +1 -1
- package/dist/server/tenancy.d.ts +7 -0
- package/dist/server/tenancy.js +31 -0
- package/dist/server/tenancy.js.map +1 -1
- package/dist/server/watch.d.ts +10 -0
- package/dist/server/watch.js +88 -0
- package/dist/server/watch.js.map +1 -0
- package/dist/testing/index.d.ts +3 -1
- package/dist/testing/index.js +3 -2
- package/dist/testing/index.js.map +1 -1
- package/docs/AGENT-CONTROL.md +130 -4
- package/docs/APPBOUNDRY.md +37 -0
- package/docs/ARCHITECTURE.md +6 -2
- package/docs/AUTH.md +35 -0
- package/docs/COMPONENTS.md +71 -0
- package/docs/GUARANTEES.md +4 -4
- package/docs/PRESENCE-AND-SIGNALING-PROPOSAL.md +152 -0
- package/docs/PROVIDERS.md +58 -1
- package/docs/README.md +3 -2
- package/docs/SECURITY.md +71 -3
- package/docs/TRANSACTIONS.md +48 -0
- package/docs/UPSTREAM-GAPS.md +16 -2
- package/package.json +16 -16
- package/skills/.claude-plugin/marketplace.json +1 -1
- package/skills/.claude-plugin/plugin.json +1 -1
- package/skills/feltkit-agent/SKILL.md +1 -1
- package/skills/feltkit-build/SKILL.md +11 -1
- package/skills/feltkit-data/SKILL.md +1 -1
- package/skills/feltkit-operations/SKILL.md +1 -1
- package/skills/feltkit-services/SKILL.md +1 -1
- package/dist/dashboard/assets/index-9rMS3yBm.js +0 -15
- package/dist/dashboard/assets/index-DkiYTUMR.css +0 -1
package/dist/runtime/runtime.js
CHANGED
|
@@ -13,7 +13,13 @@ import { evaluateAuthorize, evaluateOwnership } from "../authorize.js";
|
|
|
13
13
|
import { evaluatePolicies, viaCollections } from "../policy.js";
|
|
14
14
|
import { PolicyStore } from "./policies.js";
|
|
15
15
|
import { eventDefinitions, observationAuthorizer, stageEvent } from "./events.js";
|
|
16
|
-
import {
|
|
16
|
+
import { systemClock } from "../clock.js";
|
|
17
|
+
import { PresenceHost } from "./presence-host.js";
|
|
18
|
+
import { GUEST_SESSION_MAX_MS, MAX_ACCESS_TTL_MS, resourceRefusal, ResourceAccessStore, loadBoundResource } from "./resource-access.js";
|
|
19
|
+
import { presenceOf } from "../presence.js";
|
|
20
|
+
import { QuotaLimiter, rateLimited } from "../quota.js";
|
|
21
|
+
import { AppPortError, combineAuthorizers, outcomeUnknown, runEffectful, createApplication, defineCapability, createMcpBridge, delegatedAuthorityAuthorizer, errors as appportErrors, idempotencyStorageKey } from "@appport/sdk";
|
|
22
|
+
import { WorkerAuthority, WORKER_PREFIX } from "./workers.js";
|
|
17
23
|
import { grantsPermission } from "@appport/authorization";
|
|
18
24
|
import { AsyncLocalStorage } from "node:async_hooks";
|
|
19
25
|
import { AGENT_CONTROL_EXTENSION, agentControlCapabilities } from "./agent-control-capabilities.js";
|
|
@@ -21,7 +27,7 @@ import { performance } from "node:perf_hooks";
|
|
|
21
27
|
import { createHash, createHmac, randomBytes, randomUUID } from "node:crypto";
|
|
22
28
|
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
23
29
|
import { dirname, join } from "node:path";
|
|
24
|
-
import { AGENT_MAX_BACKOFF_MS } from "../app.js";
|
|
30
|
+
import { AGENT_MAX_BACKOFF_MS, uniqueField } from "../app.js";
|
|
25
31
|
import { IntegrationHost, integrationDescriptor } from "./integrations.js";
|
|
26
32
|
import { applicationAuthority } from "./application-authority.js";
|
|
27
33
|
import { verifyStorage } from "./storage-check.js";
|
|
@@ -43,13 +49,16 @@ import { applySchema, blockedHint, describePlan, MIGRATIONS_COLLECTION, planSche
|
|
|
43
49
|
import { afterCommit, newOutboxId, OUTBOX_COLLECTION, performEffect } from "./outbox.js";
|
|
44
50
|
import { claimed, isRecoverable, isSequenceConflict, outboxStore, performOutbox, rescheduled, retried, settled } from "./transactions.js";
|
|
45
51
|
import { OAuthCredentials } from "./oauth-credentials.js";
|
|
46
|
-
import { INVOCATIONS_COLLECTION, InvocationStore } from "./invocations.js";
|
|
52
|
+
import { INVOCATIONS_COLLECTION, InvocationStore, workItemScoped } from "./invocations.js";
|
|
47
53
|
import { ExecutionHost } from "./execution-host.js";
|
|
48
54
|
import { LocalAuthorityHost, applicationCapabilities, authorityAgentId } from "./local-authority.js";
|
|
49
55
|
import { authorityPrincipalOf } from "./application-authority.js";
|
|
50
56
|
import { verifyDelegation } from "./delegation.js";
|
|
51
57
|
import { credentialsFor, isCustodyError } from "./credentials.js";
|
|
52
|
-
import { AgentHost } from "./agent.js";
|
|
58
|
+
import { AgentHost, AGENT_PERMISSIONS } from "./agent.js";
|
|
59
|
+
import { AGENT_CONTROL_EVENT, agentTaskScope, defineEvent, taskIdOfAgentScope } from "@appport/sdk";
|
|
60
|
+
import { toSchema } from "@appport/schema";
|
|
61
|
+
import { SEQUENCES_COLLECTION } from "./transactions.js";
|
|
53
62
|
import { FeltDbIdempotencyStore } from "./idempotency.js";
|
|
54
63
|
import { capabilityDefinition } from "./capabilities.js";
|
|
55
64
|
import { FeltDbSessionStore, sessionRef } from "./sessions.js";
|
|
@@ -154,14 +163,48 @@ export class FeltKitRuntime {
|
|
|
154
163
|
get settings() {
|
|
155
164
|
return this.#env;
|
|
156
165
|
}
|
|
157
|
-
|
|
166
|
+
/** The clock leases and quotas read (RuntimeStartOptions.clock). */
|
|
167
|
+
clock;
|
|
168
|
+
/** Call quotas (src/quota.ts): in-process sliding windows. */
|
|
169
|
+
quotas;
|
|
170
|
+
/** Presence leases (app.presence): ctx.presence, the live view, expiry and session ends (runtime/presence-host.ts). */
|
|
171
|
+
presence;
|
|
172
|
+
/** Guest links and agent grants: access to one resource (runtime/resource-access.ts). */
|
|
173
|
+
access;
|
|
174
|
+
/** Workers, their work grants, and people's approvals of exact calls (runtime/workers.ts). */
|
|
175
|
+
workers;
|
|
176
|
+
constructor(environment, instance, logger, env = process.env, clock = systemClock) {
|
|
158
177
|
this.#env = env;
|
|
178
|
+
this.clock = clock;
|
|
179
|
+
this.quotas = new QuotaLimiter(clock);
|
|
180
|
+
this.access = new ResourceAccessStore(() => instance.handle("feltkit.access"), clock);
|
|
181
|
+
this.workers = new WorkerAuthority(() => instance.handle("feltkit.access"), clock);
|
|
182
|
+
this.presence = new PresenceHost({
|
|
183
|
+
app: () => this.app,
|
|
184
|
+
handle: () => this.instance.handle("app"),
|
|
185
|
+
resolver: () => this.#resolver,
|
|
186
|
+
clock,
|
|
187
|
+
agentEffect: (name, input, tenantId) => this.#agentEffect(name, input, null, undefined, tenantId),
|
|
188
|
+
committed: (commit, outbox) => {
|
|
189
|
+
if (commit.writes.length) {
|
|
190
|
+
this.changes.describe(commit.described);
|
|
191
|
+
void this.changes.check();
|
|
192
|
+
}
|
|
193
|
+
for (const record of outbox)
|
|
194
|
+
if (record.effect.service === "agent")
|
|
195
|
+
this.#dispatchAgent(record.id);
|
|
196
|
+
},
|
|
197
|
+
warn: (message) => this.logger.warn(message),
|
|
198
|
+
});
|
|
159
199
|
this.environment = environment;
|
|
160
200
|
this.instance = instance;
|
|
161
201
|
this.logger = logger;
|
|
162
202
|
this.sessions = new FeltDbSessionStore(instance.handle("feltkit.sessions"));
|
|
163
203
|
this.activity = new ActivityLog(instance.handle("feltkit.activity"), { mode: environment.production ? "writes" : "all", evidence: (runId) => this.#services.evidence(runId) });
|
|
164
|
-
|
|
204
|
+
// FELTKIT_CHANGE_POLL_MS: the fallback poll of the change feed (default 1 s embedded and 5 s on a server with commit
|
|
205
|
+
// notices; 150 ms and 1 s without them).
|
|
206
|
+
const pollMs = Number(env.FELTKIT_CHANGE_POLL_MS);
|
|
207
|
+
this.changes = new ChangeFeed(instance.handle("feltkit.changes"), { remote: environment.storage.kind === "remote", ...(Number.isFinite(pollMs) && pollMs >= 50 ? { intervalMs: Math.floor(pollMs) } : {}) });
|
|
165
208
|
this.idempotency = new FeltDbIdempotencyStore(instance.handle("appport.idempotency"));
|
|
166
209
|
this.models = new ModelHost(this, { env });
|
|
167
210
|
this.integrations = new IntegrationHost(this);
|
|
@@ -191,7 +234,7 @@ export class FeltKitRuntime {
|
|
|
191
234
|
const instance = factory.open(options.environment);
|
|
192
235
|
let runtime;
|
|
193
236
|
try {
|
|
194
|
-
runtime = new FeltKitRuntime(options.environment, instance, logger, options.env ?? process.env);
|
|
237
|
+
runtime = new FeltKitRuntime(options.environment, instance, logger, options.env ?? process.env, options.clock ?? systemClock);
|
|
195
238
|
await runtime.providers.sync(options.project.app.options.providers, options.project.projectDir ?? process.cwd());
|
|
196
239
|
runtime.#install(options.project);
|
|
197
240
|
// How long each startup step took: on a FeltDB server each is network round trips, and a
|
|
@@ -227,6 +270,8 @@ export class FeltKitRuntime {
|
|
|
227
270
|
step("agent");
|
|
228
271
|
runtime.changes.start();
|
|
229
272
|
runtime.#state = "ready";
|
|
273
|
+
// Leases that expired while no process ran end now; the timer is armed for the next expiry.
|
|
274
|
+
await runtime.presence.sweep();
|
|
230
275
|
// Actions an earlier process left open, settled from evidence (never re-executed).
|
|
231
276
|
// After "ready": settling may run an integration's outcome hook, which is a function call.
|
|
232
277
|
await runtime.#agent.reconcile();
|
|
@@ -473,7 +518,7 @@ export class FeltKitRuntime {
|
|
|
473
518
|
// The job, not the attempt, is the unit of effect: a re-run (lease expired after the commit) replays the
|
|
474
519
|
// first commit by its transaction id instead of committing again.
|
|
475
520
|
const jobId = runId.slice(0, runId.lastIndexOf(":") > 0 ? runId.lastIndexOf(":") : runId.length);
|
|
476
|
-
const result = await this.call(fn, payload, { principal, via: "job", requestId: `job_${runId}`, idempotencyReplayKey: `job:${jobId}` });
|
|
521
|
+
const result = await this.call(fn, payload, { principal, via: "job", internal: true, requestId: `job_${runId}`, idempotencyReplayKey: `job:${jobId}` });
|
|
477
522
|
// An earlier attempt of this job committed (its completion was lost): the job happened, once. A job's value is not kept.
|
|
478
523
|
if (!result.ok && result.error.code === "OUTCOME_UNKNOWN" && result.error.details?.committed === true) {
|
|
479
524
|
this.logger.info?.(`job ${jobId}: an earlier attempt committed; not performed again`, { requestId: `job_${runId}` });
|
|
@@ -484,7 +529,7 @@ export class FeltKitRuntime {
|
|
|
484
529
|
},
|
|
485
530
|
// An inbound webhook's handler: the declared mutation, as `integration:<provider>` (no tenant).
|
|
486
531
|
runInbound: async (fn, principal, event) => {
|
|
487
|
-
const result = await this.call(fn, { event }, { principal, via: "integration", requestId: `inbound_${String(event.integrationId)}_${String(event.eventId)}`.slice(0, 200) });
|
|
532
|
+
const result = await this.call(fn, { event }, { principal, via: "integration", internal: true, requestId: `inbound_${String(event.integrationId)}_${String(event.eventId)}`.slice(0, 200) });
|
|
488
533
|
if (!result.ok)
|
|
489
534
|
throw Object.assign(new Error(`${result.error.code}: ${result.error.message}`), { code: result.error.code });
|
|
490
535
|
return result.value;
|
|
@@ -529,8 +574,42 @@ export class FeltKitRuntime {
|
|
|
529
574
|
extensions: [AGENT_CONTROL_EXTENSION],
|
|
530
575
|
capabilities,
|
|
531
576
|
// app.event(): AppPort events; observation is authorized by roles, then feltkit({ authorize }).
|
|
532
|
-
|
|
533
|
-
|
|
577
|
+
// app.event()s, and agent control's change event (appport.agent.changed@1, spec/agent-control-1.md §7).
|
|
578
|
+
events: [...eventDefinitions(app), defineEvent({ name: AGENT_CONTROL_EVENT.name, version: 1, description: "A task's control state changed (durably): its revision, phase, mode, what changed, and a per-task sequence.", payload: toSchema(AGENT_CONTROL_EVENT.payloadSchema), authorization: [AGENT_PERMISSIONS.read] })],
|
|
579
|
+
// Workers act under work grants, and approvals bind to exact calls (runtime/workers.ts): AppPort's own delegated
|
|
580
|
+
// authority rules over FeltKit's durable records. #call checks the same records again on every surface.
|
|
581
|
+
authorizer: combineAuthorizers([
|
|
582
|
+
this.#delegatedAuthorizer(observationAuthorizer(app, authority.authorizer, () => new Reader(this.instance.handle("app"), new CollectionResolver(app.collections)))),
|
|
583
|
+
// appport.agent.changed: observed only by someone who may read the task, subscribed to that task's scope.
|
|
584
|
+
{
|
|
585
|
+
name: "agent-changed",
|
|
586
|
+
authorize: async (request) => {
|
|
587
|
+
if (request.capability?.name !== AGENT_CONTROL_EVENT.name)
|
|
588
|
+
return { allowed: true };
|
|
589
|
+
const scope = request.input?.scope;
|
|
590
|
+
const taskId = typeof scope === "string" ? taskIdOfAgentScope(scope) : undefined;
|
|
591
|
+
if (!taskId)
|
|
592
|
+
return { allowed: false, code: "FORBIDDEN", reason: `Subscribe to one task's changes: scope ${agentTaskScope("<taskId>")}.` };
|
|
593
|
+
const principal = fromAppPortPrincipal((request.principal ?? request.session?.principal));
|
|
594
|
+
if (!principal)
|
|
595
|
+
return { allowed: false, code: "UNAUTHORIZED", reason: "Sign in to observe agent tasks." };
|
|
596
|
+
try {
|
|
597
|
+
await this.agent.control.view(taskId, principal);
|
|
598
|
+
return { allowed: true };
|
|
599
|
+
}
|
|
600
|
+
catch {
|
|
601
|
+
return { allowed: false, code: "FORBIDDEN", reason: "Not a reader of this task." };
|
|
602
|
+
}
|
|
603
|
+
},
|
|
604
|
+
},
|
|
605
|
+
// A worker needs a grant for everything but the protocol's own description and its own calls' status.
|
|
606
|
+
delegatedAuthorityAuthorizer({ grants: this.workers, approvals: this.workers, require: (request) => typeof (request.principal ?? request.session?.principal)?.attributes?.feltkitWorker === "string" && !WORKER_UNGRANTED.includes(request.capability.name), now: () => this.clock.now() }),
|
|
607
|
+
]),
|
|
608
|
+
// A capability that publishes `integration.approval.required` runs only with an approval the authorizer verified.
|
|
609
|
+
enforceApprovals: true,
|
|
610
|
+
// `appport.invocation.status@1`: "what happened to my call?", the caller's own calls only, answered from the
|
|
611
|
+
// idempotency records and the external effect records (actions' ctx.effect and providers' calls, one recorder).
|
|
612
|
+
reconciliation: { calls: this.providers.effectRecorder() },
|
|
534
613
|
db: this.instance.handle("appport"),
|
|
535
614
|
sessions: this.sessions,
|
|
536
615
|
// Durable replay protection for capabilities that declare idempotency: the claim is
|
|
@@ -544,7 +623,7 @@ export class FeltKitRuntime {
|
|
|
544
623
|
// Every transport (HTTP, WebSocket, MCP) dispatches through these two methods.
|
|
545
624
|
for (const method of ["handleRequest", "handleStreamRequest"]) {
|
|
546
625
|
const original = appport[method].bind(appport);
|
|
547
|
-
appport[method] = (request, options = {}) => this.#appportCaller.run(callerScope(options?.principal ?? options?.session?.principal), () => original(request, options));
|
|
626
|
+
appport[method] = (request, options = {}) => this.#appportCaller.run({ ...callerScope(options?.principal ?? options?.session?.principal), ...(request?.invocation ? { invocation: request.invocation } : {}) }, () => original(request, options));
|
|
548
627
|
}
|
|
549
628
|
// auth.onSessionEnd: a mutation of this application; ends are recorded only when one is declared.
|
|
550
629
|
const sessionEndHook = project.app.options.auth?.onSessionEnd;
|
|
@@ -553,13 +632,16 @@ export class FeltKitRuntime {
|
|
|
553
632
|
if (!target || target.kind !== "mutation")
|
|
554
633
|
throw new FeltKitError("CONFIGURATION", `auth.onSessionEnd: ${JSON.stringify(sessionEndHook)} is not a mutation of this application (write "<module>:<export>").`);
|
|
555
634
|
}
|
|
556
|
-
|
|
635
|
+
// Presence leases end with their holder's session, so ends are recorded for them too.
|
|
636
|
+
const hasPresence = [...project.app.collections.values()].some((c) => presenceOf(c));
|
|
637
|
+
this.sessions.recordEnds = sessionEndHook !== undefined || hasPresence;
|
|
557
638
|
this.sessions.onEnd = () => void this.runSessionEnds();
|
|
558
639
|
this.#project = project;
|
|
559
640
|
this.#authority = authority;
|
|
560
641
|
this.#services = services;
|
|
561
642
|
this.#appport = appport;
|
|
562
643
|
this.#resolver = new CollectionResolver(app.collections);
|
|
644
|
+
this.presence.check();
|
|
563
645
|
this.#generation += 1;
|
|
564
646
|
}
|
|
565
647
|
/** One AuthBoundry decision as the application's executor (a person's connection: runtime/integrations.ts). Recorded like ctx.authority's. */
|
|
@@ -608,6 +690,59 @@ export class FeltKitRuntime {
|
|
|
608
690
|
functionAccess(name) {
|
|
609
691
|
return this.#project.functions.get(name)?.access;
|
|
610
692
|
}
|
|
693
|
+
/**
|
|
694
|
+
* The permissions a function requires (`access`), by the capability it publishes or, for one that publishes none (an
|
|
695
|
+
* internal job handler recording an effect), by its name; null when there is no such function.
|
|
696
|
+
*/
|
|
697
|
+
capabilityAccess(capability) {
|
|
698
|
+
const fn = [...(this.#project?.functions.values() ?? [])].find((f) => f.capability?.name === capability) ?? this.#project?.functions.get(capability);
|
|
699
|
+
return fn ? Authority.required(fn.access) : null;
|
|
700
|
+
}
|
|
701
|
+
/** Per task: the emission of appport.agent.changed events, in order, in this process. */
|
|
702
|
+
#agentEvents = new Map();
|
|
703
|
+
#agentEventId(taskId) {
|
|
704
|
+
const id = `agent-changed.${taskId}`;
|
|
705
|
+
return /^[A-Za-z0-9._-]{1,128}$/.test(id) ? id : `_agent-changed.${createHash("sha256").update(taskId).digest("hex")}`;
|
|
706
|
+
}
|
|
707
|
+
/** The `sequence` of the last appport.agent.changed event for a task (0 before any), from its durable counter. */
|
|
708
|
+
async agentChangeSequence(taskId) {
|
|
709
|
+
const record = (await this.instance.handle("feltkit.agent-events").collection(SEQUENCES_COLLECTION).get(this.#agentEventId(taskId)));
|
|
710
|
+
return typeof record?.value === "number" ? record.value : 0;
|
|
711
|
+
}
|
|
712
|
+
/**
|
|
713
|
+
* A task's control state changed durably (runtime/agent-control.ts): allocate the next per-task sequence (a durable
|
|
714
|
+
* counter, compare-and-set, so it survives restarts and never repeats) and publish appport.agent.changed@1 with the
|
|
715
|
+
* state as that change left it, scoped to the task. Emissions for one task are serialized in this process.
|
|
716
|
+
*/
|
|
717
|
+
agentChanged(taskId, changes, instructionId, state) {
|
|
718
|
+
const previous = this.#agentEvents.get(taskId) ?? Promise.resolve();
|
|
719
|
+
const next = previous.then(() => this.#emitAgentChanged(taskId, changes, instructionId, state)).catch((error) => this.logger.warn(`appport.agent.changed for ${taskId} was not published: ${error.message}`));
|
|
720
|
+
this.#agentEvents.set(taskId, next);
|
|
721
|
+
void next.finally(() => {
|
|
722
|
+
if (this.#agentEvents.get(taskId) === next)
|
|
723
|
+
this.#agentEvents.delete(taskId);
|
|
724
|
+
});
|
|
725
|
+
return next;
|
|
726
|
+
}
|
|
727
|
+
async #emitAgentChanged(taskId, changes, instructionId, state) {
|
|
728
|
+
const db = this.instance.handle("feltkit.agent-events");
|
|
729
|
+
const id = this.#agentEventId(taskId);
|
|
730
|
+
let sequence = 0;
|
|
731
|
+
for (let attempt = 0; attempt < 8 && !sequence; attempt++) {
|
|
732
|
+
const current = (await db.collection(SEQUENCES_COLLECTION).get(id));
|
|
733
|
+
const value = (current?.value ?? 0) + 1;
|
|
734
|
+
try {
|
|
735
|
+
await db.transaction({ operations: [{ collection: SEQUENCES_COLLECTION, id, ...(current ? { ifVersion: current.__version } : { requireAbsent: true }), value: { name: id, value, transactionId: `agent-changed-${randomUUID()}` } }] });
|
|
736
|
+
sequence = value;
|
|
737
|
+
}
|
|
738
|
+
catch {
|
|
739
|
+
/* another process advanced it: read again */
|
|
740
|
+
}
|
|
741
|
+
}
|
|
742
|
+
if (!sequence)
|
|
743
|
+
throw new Error("the event sequence kept changing");
|
|
744
|
+
await this.#appport.emit({ name: AGENT_CONTROL_EVENT.name, version: 1, payload: { taskId, revision: state.revision, sequence, phase: state.phase, mode: state.mode, changes: [...new Set(changes)], ...(instructionId ? { instructionId } : {}) }, scope: agentTaskScope(taskId) });
|
|
745
|
+
}
|
|
611
746
|
/** Whether `principal` holds `access` under this application's roles ("public" and "authenticated" as functions treat them). */
|
|
612
747
|
holds(principal, access) {
|
|
613
748
|
if (access === "public")
|
|
@@ -836,11 +971,16 @@ export class FeltKitRuntime {
|
|
|
836
971
|
return;
|
|
837
972
|
if (!scope.principal)
|
|
838
973
|
throw appportErrors.unauthorized("Authentication is required");
|
|
974
|
+
const name0 = [...this.#project.functions.entries()].find(([, f]) => f === fn)?.[0] ?? fn.capability?.name ?? "";
|
|
975
|
+
const hidden = fn.visibility ? visibilityRefusalFor(name0, fn.visibility, scope.principal) : null;
|
|
976
|
+
if (hidden)
|
|
977
|
+
throw hidden.code === "FORBIDDEN" ? appportErrors.forbidden(hidden.message, { visibility: fn.visibility }) : appportErrors.unauthorized(hidden.message);
|
|
839
978
|
const required = Authority.required(fn.access);
|
|
840
979
|
if (required.length && !grantsPermission(this.#authority.permissionsFor(scope.principal), required[0]))
|
|
841
980
|
throw appportErrors.forbidden(`Missing permission: ${required[0]}`);
|
|
842
981
|
const name = [...this.#project.functions.entries()].find(([, f]) => f === fn)?.[0] ?? fn.capability?.name ?? "";
|
|
843
|
-
|
|
982
|
+
// A named approval is verified by the authorizer and again at execution, against this exact input.
|
|
983
|
+
const refusal = scope.invocation?.approvalRef ? null : this.#approvalRefusal(name, fn, scope.principal);
|
|
844
984
|
if (refusal)
|
|
845
985
|
throw appportErrors.forbidden(refusal, { approval: "required" });
|
|
846
986
|
}
|
|
@@ -861,7 +1001,9 @@ export class FeltKitRuntime {
|
|
|
861
1001
|
capability: { name: exposure.name, version: exposure.version },
|
|
862
1002
|
...(context.authorizationDecision?.decisionId ? { appportDecisionId: context.authorizationDecision.decisionId } : {}),
|
|
863
1003
|
...(fn.kind === "mutation" && context.idempotencyKey ? { idempotencyReplayKey: replayKey(context, exposure, principal) } : {}),
|
|
1004
|
+
...(context.idempotencyKey ? { idempotencyKey: String(context.idempotencyKey) } : {}),
|
|
864
1005
|
...(delegation ? { delegation } : {}),
|
|
1006
|
+
...(context.invocation ? { invocation: { claimed: { ...(context.invocation.claimed ?? {}) } } } : {}),
|
|
865
1007
|
// A delegated call acts for the person under the agent's session: it binds to no session of theirs.
|
|
866
1008
|
...(!delegation && sessionRef(context.session?.id) ? { session: { ref: sessionRef(context.session?.id) } } : {}),
|
|
867
1009
|
});
|
|
@@ -923,6 +1065,22 @@ export class FeltKitRuntime {
|
|
|
923
1065
|
// An account session is resolved again on every request: the account as it is now (a
|
|
924
1066
|
// disabled or deleted account has no session; changed roles apply at once), never the copy
|
|
925
1067
|
// taken at sign-in. Dev, CLI and agent sessions carry the roles their issuer gave them.
|
|
1068
|
+
// A guest session (K4): resolved from its link on every request; a revoked or expired link ends it at once.
|
|
1069
|
+
if (attributes.kind === "guest") {
|
|
1070
|
+
const linkId = session?.attributes?.guestLink;
|
|
1071
|
+
const link = typeof linkId === "string" ? await this.access.liveGuestLink(linkId) : null;
|
|
1072
|
+
if (!link || !this.app.options.auth?.guests?.roles.includes(link.role))
|
|
1073
|
+
return null;
|
|
1074
|
+
return { id: principal.id, type: "user", roles: [link.role], ...(principal.displayName ? { displayName: principal.displayName } : {}), guest: { link: link.id, resource: { ...link.resource }, expiresAt: new Date(link.expiresAt).toISOString() } };
|
|
1075
|
+
}
|
|
1076
|
+
// A worker session: resolved from its registration on every request; a revoked or expired worker is refused at once.
|
|
1077
|
+
if (attributes.kind === "worker") {
|
|
1078
|
+
const registrationId = session?.attributes?.worker;
|
|
1079
|
+
const registration = typeof registrationId === "string" ? await this.workers.liveWorker(registrationId) : null;
|
|
1080
|
+
if (!registration || registration.principalId !== principal.id)
|
|
1081
|
+
return null;
|
|
1082
|
+
return this.withTenant({ id: principal.id, type: "agent", roles: [...(registration.roles ?? [])], ...(registration.label ? { displayName: registration.label } : {}), worker: { id: registration.id } }, registration.tenantId);
|
|
1083
|
+
}
|
|
926
1084
|
if (attributes.kind === "account") {
|
|
927
1085
|
const account = this.accounts ? await this.accounts.get(principal.id) : null;
|
|
928
1086
|
if (!account || account.disabled)
|
|
@@ -992,6 +1150,9 @@ export class FeltKitRuntime {
|
|
|
992
1150
|
return null;
|
|
993
1151
|
}
|
|
994
1152
|
async #resolveStrict(subjectId) {
|
|
1153
|
+
// A guest has no durable authority: work it queued does not run as it later.
|
|
1154
|
+
if (subjectId.startsWith("guest:"))
|
|
1155
|
+
return null;
|
|
995
1156
|
const declared = this.declaredPrincipal(subjectId);
|
|
996
1157
|
if (declared)
|
|
997
1158
|
return declared;
|
|
@@ -1298,7 +1459,7 @@ export class FeltKitRuntime {
|
|
|
1298
1459
|
* after a session ends; one pass at a time.
|
|
1299
1460
|
*/
|
|
1300
1461
|
runSessionEnds() {
|
|
1301
|
-
if (this.#state !== "ready" || this.#paused || this.
|
|
1462
|
+
if (this.#state !== "ready" || this.#paused || !this.sessions.recordEnds)
|
|
1302
1463
|
return Promise.resolve();
|
|
1303
1464
|
if (this.#sessionEnds) {
|
|
1304
1465
|
this.#sessionEndsAgain = true;
|
|
@@ -1308,19 +1469,25 @@ export class FeltKitRuntime {
|
|
|
1308
1469
|
do {
|
|
1309
1470
|
this.#sessionEndsAgain = false;
|
|
1310
1471
|
const hook = this.app.options.auth?.onSessionEnd;
|
|
1311
|
-
if (!
|
|
1472
|
+
if (!this.sessions.recordEnds)
|
|
1312
1473
|
return;
|
|
1313
1474
|
if (Date.now() - this.#lastExpirySweep >= SESSION_EXPIRY_SWEEP_MS) {
|
|
1314
1475
|
this.#lastExpirySweep = Date.now();
|
|
1315
1476
|
await this.sessions.sweepExpired();
|
|
1316
1477
|
}
|
|
1317
1478
|
for (const end of await this.sessions.pendingEnds()) {
|
|
1479
|
+
// Presence leases held under the session end with it, before the application hears of the end.
|
|
1480
|
+
await this.presence.endForSession(end.ref).catch((error) => this.logger.warn(`presence: ending leases of session ${end.ref}: ${error.message}`));
|
|
1481
|
+
if (!hook) {
|
|
1482
|
+
await this.sessions.endHandled(end);
|
|
1483
|
+
continue;
|
|
1484
|
+
}
|
|
1318
1485
|
const principal = end.principal ? fromAppPortPrincipal(end.principal) : null;
|
|
1319
1486
|
if (!principal) {
|
|
1320
1487
|
await this.sessions.endHandled(end); // nobody's session: nothing can be bound to it
|
|
1321
1488
|
continue;
|
|
1322
1489
|
}
|
|
1323
|
-
const result = await this.call(hook, { session: end.ref, reason: end.reason }, { principal, via: "runtime", requestId: `session_end_${end.ref}_${end.attempts}` });
|
|
1490
|
+
const result = await this.call(hook, { session: end.ref, reason: end.reason }, { principal, via: "runtime", internal: true, requestId: `session_end_${end.ref}_${end.attempts}` });
|
|
1324
1491
|
if (result.ok)
|
|
1325
1492
|
await this.sessions.endHandled(end);
|
|
1326
1493
|
else {
|
|
@@ -1547,6 +1714,210 @@ export class FeltKitRuntime {
|
|
|
1547
1714
|
const active = (await this.sessions.list()).find((s) => s.principal?.id === id && (s.principal.type === "agent" || s.principal.type === "service"));
|
|
1548
1715
|
return active?.principal ? { id, type: active.principal.type, ...(active.principal.displayName ? { displayName: active.principal.displayName } : {}) } : null;
|
|
1549
1716
|
}
|
|
1717
|
+
/**
|
|
1718
|
+
* Redeem a guest link (K4): a session for a guest with no account, holding the link's role, admitted to the
|
|
1719
|
+
* link's one resource, lasting until the link expires (at most GUEST_SESSION_MAX_MS). The display name is the
|
|
1720
|
+
* guest's own words, shown to others as such.
|
|
1721
|
+
*/
|
|
1722
|
+
async redeemGuestLink(token, displayName) {
|
|
1723
|
+
if (!this.app.options.auth?.guests)
|
|
1724
|
+
throw new FeltKitError("NOT_FOUND", "This application has no guests (auth.guests).");
|
|
1725
|
+
const link = await this.access.guestLinkFor(token);
|
|
1726
|
+
if (!link)
|
|
1727
|
+
throw new FeltKitError("UNAUTHORIZED", "This guest link is not valid: it was withdrawn, it expired, or it never existed.", { hint: "GUEST_LINK" });
|
|
1728
|
+
const name = typeof displayName === "string" ? displayName.replace(/[\u0000-\u001f\u007f]/g, "").trim().slice(0, 80) : "";
|
|
1729
|
+
if (!name)
|
|
1730
|
+
throw new FeltKitError("INVALID_ARGUMENT", "A guest gives a display name.");
|
|
1731
|
+
const ttlMs = Math.min(GUEST_SESSION_MAX_MS, link.expiresAt - this.clock.now());
|
|
1732
|
+
const principal = { id: `guest:${randomUUID().replace(/-/g, "").slice(0, 20)}`, type: "user", roles: [link.role], displayName: name };
|
|
1733
|
+
const session = await this.sessions.create({ applicationId: this.app.name, principal: toAppPortPrincipal(principal), ttlMs, attributes: { kind: "guest", label: `guest of ${link.resource.collection} ${link.resource.id}`, guestLink: link.id } });
|
|
1734
|
+
const resolved = (await this.principalForToken(session.id));
|
|
1735
|
+
this.recordAuth("guest.admitted", resolved, { link: link.id, resource: link.resource });
|
|
1736
|
+
return { token: session.id, principal: resolved, ...(session.expiresAt ? { expiresAt: session.expiresAt } : {}) };
|
|
1737
|
+
}
|
|
1738
|
+
/** ctx.grants for one call: guest links and agent grants for records the caller can see, issued as a person. */
|
|
1739
|
+
#grantsApi(principal, db) {
|
|
1740
|
+
const person = () => {
|
|
1741
|
+
if (!principal || principal.type !== "user" || principal.guest)
|
|
1742
|
+
throw new FeltKitError("FORBIDDEN", "Only a signed-in person (not a guest, agent or service) issues guest links and agent grants.");
|
|
1743
|
+
return principal;
|
|
1744
|
+
};
|
|
1745
|
+
const target = async (collection, id) => {
|
|
1746
|
+
const definition = collection && this.app.collections.get(collection.name);
|
|
1747
|
+
if (!definition || definition !== collection)
|
|
1748
|
+
throw new FeltKitError("INVALID_ARGUMENT", "ctx.grants: name the resource by a collection of this application and a record id.");
|
|
1749
|
+
// Through the call's own reader: another tenant's record does not exist for the caller.
|
|
1750
|
+
if (typeof id !== "string" || !(await db.get(definition, id)))
|
|
1751
|
+
throw new FeltKitError("NOT_FOUND", `No ${definition.name} ${String(id)}.`);
|
|
1752
|
+
return { collection: definition.name, id };
|
|
1753
|
+
};
|
|
1754
|
+
const ttl = (ttlMs, fallback) => {
|
|
1755
|
+
const value = ttlMs ?? fallback;
|
|
1756
|
+
if (!Number.isInteger(value) || value < 60_000 || value > MAX_ACCESS_TTL_MS)
|
|
1757
|
+
throw new FeltKitError("INVALID_ARGUMENT", "ctx.grants: ttlMs is from one minute to 30 days.");
|
|
1758
|
+
return value;
|
|
1759
|
+
};
|
|
1760
|
+
return {
|
|
1761
|
+
guestLink: async (collection, id, options = {}) => {
|
|
1762
|
+
const by = person();
|
|
1763
|
+
const guests = this.app.options.auth?.guests;
|
|
1764
|
+
if (!guests)
|
|
1765
|
+
throw new FeltKitError("CONFIGURATION", "Guest links need auth.guests (the roles a guest may hold).");
|
|
1766
|
+
const role = options.role ?? guests.roles[0];
|
|
1767
|
+
if (!guests.roles.includes(role))
|
|
1768
|
+
throw new FeltKitError("INVALID_ARGUMENT", `A guest may hold only ${guests.roles.join(", ")} (auth.guests.roles), not "${role}".`);
|
|
1769
|
+
const resource = await target(collection, id);
|
|
1770
|
+
const issued = await this.access.issueGuestLink({ resource, role, ttlMs: ttl(options.ttlMs, guests.ttlMs ?? 24 * 3_600_000), ...(options.label ? { label: options.label } : {}), by });
|
|
1771
|
+
this.recordAuth("guest.link-issued", by, { link: issued.link.id, resource, role }, "success", "runtime");
|
|
1772
|
+
return { ...issued.link, token: issued.token, url: `${this.publicUrl()}/?guest=${issued.token}` };
|
|
1773
|
+
},
|
|
1774
|
+
admitAgent: async (collection, id, agent, options = {}) => {
|
|
1775
|
+
const by = person();
|
|
1776
|
+
const resource = await target(collection, id);
|
|
1777
|
+
const known = typeof agent === "string" ? await this.knownNonPersonPrincipal(agent) : null;
|
|
1778
|
+
if (!known)
|
|
1779
|
+
throw new FeltKitError("NOT_FOUND", `No agent or service "${String(agent)}" is known here (an app.agent, or one with an operator-issued session).`);
|
|
1780
|
+
const grant = await this.access.grantAgent({ resource, agent, ttlMs: ttl(options.ttlMs, 24 * 3_600_000), ...(options.label ? { label: options.label } : {}), by });
|
|
1781
|
+
this.recordAuth("agent.admitted", by, { grant: grant.id, resource, agent }, "success", "runtime");
|
|
1782
|
+
return grant;
|
|
1783
|
+
},
|
|
1784
|
+
revoke: async (collection, id, accessId) => {
|
|
1785
|
+
const by = person();
|
|
1786
|
+
const resource = await target(collection, id);
|
|
1787
|
+
const revoked = await this.access.revoke(accessId, resource, by);
|
|
1788
|
+
if (revoked)
|
|
1789
|
+
this.recordAuth("access.revoked", by, { access: accessId, resource }, "success", "runtime");
|
|
1790
|
+
return revoked;
|
|
1791
|
+
},
|
|
1792
|
+
list: async (collection, id) => {
|
|
1793
|
+
person();
|
|
1794
|
+
return this.access.list(await target(collection, id));
|
|
1795
|
+
},
|
|
1796
|
+
...this.#workersApi(principal),
|
|
1797
|
+
};
|
|
1798
|
+
}
|
|
1799
|
+
/**
|
|
1800
|
+
* ctx.grants for workers (runtime/workers.ts): registering and revoking workers and their work grants needs
|
|
1801
|
+
* `feltkit.workers.write` (a person or a service, never a guest or a worker); approving an exact call is a person's.
|
|
1802
|
+
*/
|
|
1803
|
+
#workersApi(principal) {
|
|
1804
|
+
const manager = () => {
|
|
1805
|
+
if (!principal || principal.guest || principal.worker || principal.type === "agent")
|
|
1806
|
+
throw new FeltKitError("FORBIDDEN", "Workers and work grants are managed by a signed-in person or a service, not by a guest, an agent or a worker.");
|
|
1807
|
+
if (!grantsPermission(this.#authority.permissionsFor(principal), "feltkit.workers.write"))
|
|
1808
|
+
throw new FeltKitError("FORBIDDEN", `${principal.id} may not manage workers (needs feltkit.workers.write).`);
|
|
1809
|
+
return principal;
|
|
1810
|
+
};
|
|
1811
|
+
const workerId = (worker) => {
|
|
1812
|
+
if (typeof worker !== "string" || !worker)
|
|
1813
|
+
throw new FeltKitError("INVALID_ARGUMENT", "Name the worker by its principal id (worker:<name>) or its name.");
|
|
1814
|
+
return worker.startsWith(WORKER_PREFIX) ? worker : `${WORKER_PREFIX}${worker}`;
|
|
1815
|
+
};
|
|
1816
|
+
const capabilityAccess = (capability) => {
|
|
1817
|
+
const fn = [...this.#project.functions.values()].find((f) => f.capability?.name === capability);
|
|
1818
|
+
if (fn)
|
|
1819
|
+
return fn.access;
|
|
1820
|
+
return this.integrations.operationFor(capability)?.op.access ?? null;
|
|
1821
|
+
};
|
|
1822
|
+
return {
|
|
1823
|
+
registerWorker: async (input) => {
|
|
1824
|
+
const by = manager();
|
|
1825
|
+
const roles = Array.isArray(input?.roles) ? input.roles : [];
|
|
1826
|
+
for (const role of roles)
|
|
1827
|
+
if (typeof role !== "string" || !this.#authority.roles[role])
|
|
1828
|
+
throw new FeltKitError("INVALID_ARGUMENT", `Unknown role "${String(role)}". Declared roles: ${Object.keys(this.#authority.roles).join(", ") || "(none)"}.`);
|
|
1829
|
+
// No escalation: a worker holds nothing its registrar does not.
|
|
1830
|
+
const mine = this.#authority.permissionsFor(by);
|
|
1831
|
+
const beyond = this.#authority.permissionsFor({ id: "worker", type: "agent", roles: [...roles] }).filter((p) => !grantsPermission(mine, p));
|
|
1832
|
+
if (beyond.length)
|
|
1833
|
+
throw new FeltKitError("FORBIDDEN", `${by.id} cannot give a worker ${beyond.join(", ")}: a worker holds only what its registrar holds.`);
|
|
1834
|
+
const ttlMs = WorkerAuthority.ttl(input?.ttlMs, 30 * 24 * 3_600_000, "registerWorker");
|
|
1835
|
+
const record = await this.workers.register({ name: String(input?.name ?? ""), roles, ...(input?.displayName ? { displayName: input.displayName } : {}), ttlMs, by });
|
|
1836
|
+
const session = await this.sessions.create({ applicationId: this.app.name, principal: toAppPortPrincipal({ id: record.principalId, type: "agent", roles: [...roles], ...(record.label ? { displayName: record.label } : {}) }), ttlMs, attributes: { kind: "worker", label: `worker ${record.principalId}`, worker: record.id, ...(record.tenantId ? { tenantId: record.tenantId } : {}) } });
|
|
1837
|
+
this.recordAuth("worker.registered", by, { worker: record.principalId, registration: record.id, roles }, "success", "runtime");
|
|
1838
|
+
return { ...this.workers.workerView(record), token: session.id };
|
|
1839
|
+
},
|
|
1840
|
+
revokeWorker: async (worker) => {
|
|
1841
|
+
const by = manager();
|
|
1842
|
+
const id = workerId(worker);
|
|
1843
|
+
const changed = await this.workers.revokeWorker(id, by);
|
|
1844
|
+
await this.sessions.revokePrincipal(id);
|
|
1845
|
+
this.recordAuth("worker.revoked", by, { worker: id }, "success", "runtime");
|
|
1846
|
+
return changed;
|
|
1847
|
+
},
|
|
1848
|
+
workers: async () => {
|
|
1849
|
+
manager();
|
|
1850
|
+
return this.workers.workers();
|
|
1851
|
+
},
|
|
1852
|
+
workGrant: async (input) => {
|
|
1853
|
+
const by = manager();
|
|
1854
|
+
let actor = input?.actor;
|
|
1855
|
+
if (by.type === "user") {
|
|
1856
|
+
if (actor && actor.id !== by.id)
|
|
1857
|
+
throw new FeltKitError("FORBIDDEN", `${by.id} can grant a worker authority to act only for themselves, not for ${actor.id}.`);
|
|
1858
|
+
actor = { id: by.id, type: "user" };
|
|
1859
|
+
}
|
|
1860
|
+
else if (!actor || typeof actor.id !== "string" || !actor.id) {
|
|
1861
|
+
throw new FeltKitError("INVALID_ARGUMENT", "A service names whom the worker acts for: actor: { id, type? }.");
|
|
1862
|
+
}
|
|
1863
|
+
// A person grants only what they could call themselves.
|
|
1864
|
+
if (by.type === "user") {
|
|
1865
|
+
for (const capability of input?.capabilities ?? []) {
|
|
1866
|
+
const access = typeof capability === "string" ? capabilityAccess(capability) : null;
|
|
1867
|
+
if (access && !this.holds(by, access))
|
|
1868
|
+
throw new FeltKitError("FORBIDDEN", `${by.id} may not call ${capability} (requires ${access}), so cannot grant it to a worker.`);
|
|
1869
|
+
}
|
|
1870
|
+
}
|
|
1871
|
+
const grant = await this.workers.issueGrant({ worker: workerId(input?.worker), actor: { id: actor.id, ...(actor.type ? { type: actor.type } : {}) }, capabilities: input?.capabilities, ...(input?.workItemId !== undefined ? { workItemId: input.workItemId } : {}), ...(input?.delegationId !== undefined ? { delegationId: input.delegationId } : {}), ttlMs: WorkerAuthority.ttl(input?.ttlMs, 24 * 3_600_000, "workGrant"), by });
|
|
1872
|
+
this.recordAuth("work-grant.issued", by, { grant: grant.ref, worker: grant.worker, actor: grant.actor.id, capabilities: grant.capabilities, ...(grant.workItemId ? { workItemId: grant.workItemId } : {}) }, "success", "runtime");
|
|
1873
|
+
return grant;
|
|
1874
|
+
},
|
|
1875
|
+
revokeWorkGrant: async (ref) => {
|
|
1876
|
+
const by = manager();
|
|
1877
|
+
const changed = await this.workers.revokeGrant(ref, by);
|
|
1878
|
+
if (changed)
|
|
1879
|
+
this.recordAuth("work-grant.revoked", by, { grant: ref }, "success", "runtime");
|
|
1880
|
+
return changed;
|
|
1881
|
+
},
|
|
1882
|
+
approve: async (input) => {
|
|
1883
|
+
const by = principal;
|
|
1884
|
+
if (!by || by.type !== "user" || by.guest)
|
|
1885
|
+
throw new FeltKitError("FORBIDDEN", "Only a signed-in person approves a call; agents, services, workers and guests cannot.");
|
|
1886
|
+
const access = typeof input?.capability === "string" ? capabilityAccess(input.capability) : null;
|
|
1887
|
+
if (!access)
|
|
1888
|
+
throw new FeltKitError("NOT_FOUND", `${String(input?.capability)} is not a capability of this application.`);
|
|
1889
|
+
if (!this.holds(by, access))
|
|
1890
|
+
throw new FeltKitError("FORBIDDEN", `${by.id} may not call ${input.capability} (requires ${access}), so cannot approve it.`);
|
|
1891
|
+
const resource = input.resource ? { collection: input.resource.collection?.name, id: input.resource.id } : undefined;
|
|
1892
|
+
if (resource && (!this.app.collections.has(String(resource.collection)) || typeof resource.id !== "string"))
|
|
1893
|
+
throw new FeltKitError("INVALID_ARGUMENT", "approve: resource is { collection, id } of this application.");
|
|
1894
|
+
const approval = await this.workers.issueApproval({ capability: input.capability, input: input.input, ...(input.worker !== undefined ? { worker: workerId(input.worker) } : {}), ...(input.workItemId !== undefined ? { workItemId: input.workItemId } : {}), ...(resource ? { resource: resource } : {}), ttlMs: WorkerAuthority.ttl(input.ttlMs, 24 * 3_600_000, "approve"), by });
|
|
1895
|
+
this.recordAuth("approval.issued", by, { approval: approval.ref, capability: approval.capability, digest: approval.digest, ...(approval.worker ? { worker: approval.worker } : {}) }, "success", "runtime");
|
|
1896
|
+
return approval;
|
|
1897
|
+
},
|
|
1898
|
+
revokeApproval: async (ref) => {
|
|
1899
|
+
if (!principal || principal.guest || principal.worker)
|
|
1900
|
+
throw new FeltKitError("FORBIDDEN", "Only the person who approved, or a holder of feltkit.workers.write, withdraws an approval.");
|
|
1901
|
+
const record = await this.workers.approval(ref);
|
|
1902
|
+
if (!record)
|
|
1903
|
+
throw new FeltKitError("NOT_FOUND", `No approval ${String(ref)}.`);
|
|
1904
|
+
if (record.createdBy !== `${principal.type}:${principal.id}` && !grantsPermission(this.#authority.permissionsFor(principal), "feltkit.workers.write"))
|
|
1905
|
+
throw new FeltKitError("FORBIDDEN", `${principal.id} did not give approval ${ref}.`);
|
|
1906
|
+
const changed = await this.workers.revokeApproval(ref, principal);
|
|
1907
|
+
if (changed)
|
|
1908
|
+
this.recordAuth("approval.revoked", principal, { approval: ref }, "success", "runtime");
|
|
1909
|
+
return changed;
|
|
1910
|
+
},
|
|
1911
|
+
approval: async (ref) => {
|
|
1912
|
+
if (!principal)
|
|
1913
|
+
throw new FeltKitError("UNAUTHORIZED", "Sign in to read an approval.");
|
|
1914
|
+
const record = await this.workers.approval(ref);
|
|
1915
|
+
if (!record)
|
|
1916
|
+
throw new FeltKitError("NOT_FOUND", `No approval ${String(ref)}.`);
|
|
1917
|
+
return this.workers.approvalView(record);
|
|
1918
|
+
},
|
|
1919
|
+
};
|
|
1920
|
+
}
|
|
1550
1921
|
/** Record an authentication event (sign-in failures, revocations, membership changes) in the activity log. */
|
|
1551
1922
|
recordAuth(name, principal, detail, outcome = "success", via = "http") {
|
|
1552
1923
|
this.activity.record({ kind: "auth", name, via, requestId: `req_${randomUUID()}`, principal: principal ? pick(principal) : null, outcome, durationMs: 0, detail });
|
|
@@ -1582,7 +1953,7 @@ export class FeltKitRuntime {
|
|
|
1582
1953
|
};
|
|
1583
1954
|
const failure = (error, extra = {}) => {
|
|
1584
1955
|
const json = this.#errorJSON(error, requestId);
|
|
1585
|
-
const outcome = json.code === "UNAUTHORIZED" || json.code === "FORBIDDEN" || extra.authority?.resource?.allowed === false ? "denied" : "error";
|
|
1956
|
+
const outcome = json.code === "UNAUTHORIZED" || json.code === "FORBIDDEN" || json.code === "RATE_LIMITED" || extra.authority?.resource?.allowed === false ? "denied" : "error";
|
|
1586
1957
|
if (outcome === "error") {
|
|
1587
1958
|
this.recentErrors.unshift({ at: new Date().toISOString(), name, code: json.code, message: json.message, requestId });
|
|
1588
1959
|
this.recentErrors.length = Math.min(this.recentErrors.length, 50);
|
|
@@ -1594,6 +1965,13 @@ export class FeltKitRuntime {
|
|
|
1594
1965
|
return failure(new FeltKitError("UNAVAILABLE", `The runtime is ${this.#state}.`));
|
|
1595
1966
|
if (!fn)
|
|
1596
1967
|
return failure(new FeltKitError("FUNCTION_NOT_FOUND", `No query or mutation named "${name}".`, { hint: "Function names are \"<module>:<export>\", e.g. \"tasks:list\"." }));
|
|
1968
|
+
// Visibility, before anything else: an internal function does not exist for any surface.
|
|
1969
|
+
const visibilityRefusal = fn.visibility && !options.internal && !options.agentRun ? visibilityRefusalFor(name, fn.visibility, principal) : null;
|
|
1970
|
+
if (visibilityRefusal) {
|
|
1971
|
+
if (principal && visibilityRefusal.code !== "FUNCTION_NOT_FOUND")
|
|
1972
|
+
await this.#recordDecision({ function: name, via: String(options.via), requestId, principal: { id: principal.id, type: principal.type, roles: [...principal.roles] }, outcome: "denied", layer: "visibility", reason: visibilityRefusal.message, argKeys: argKeys(rawArgs) ?? [] });
|
|
1973
|
+
return failure(new FeltKitError(visibilityRefusal.code, visibilityRefusal.message, { details: { visibility: fn.visibility } }));
|
|
1974
|
+
}
|
|
1597
1975
|
// Never hand stored records to code that declares a different schema for them.
|
|
1598
1976
|
if (this.schema?.status === "blocked") {
|
|
1599
1977
|
return failure(new FeltKitError("CONFIGURATION", `The application's schema changed and the stored data has not been migrated: ${this.schema.plan.reason ?? "run `feltkit migrate`"}. No function runs until it is.`, { hint: blockedHint(this.schema.plan) }));
|
|
@@ -1627,14 +2005,32 @@ export class FeltKitRuntime {
|
|
|
1627
2005
|
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) ?? [] });
|
|
1628
2006
|
return failure(new FeltKitError(decision.code ?? "FORBIDDEN", decision.reason ?? "Not allowed"), { authority: authorityRecord, argKeys: argKeys(rawArgs) });
|
|
1629
2007
|
}
|
|
2008
|
+
// The invocation context (runtime/workers.ts): a worker acts only under a work grant naming this function's
|
|
2009
|
+
// capability; a named grant or approval must verify. Internal calls carry their caller's verified context.
|
|
2010
|
+
let invocation = null;
|
|
2011
|
+
const claimedInvocation = options.invocation?.claimed ?? {};
|
|
2012
|
+
if (options.internal && options.invocation?.verified) {
|
|
2013
|
+
invocation = { claimed: claimedInvocation, verified: options.invocation.verified };
|
|
2014
|
+
}
|
|
2015
|
+
else if (principal?.worker || Object.keys(claimedInvocation).length) {
|
|
2016
|
+
const checked = await this.workers.check({ principal, capability: fn.capability?.name ?? name, input: (rawArgs ?? {}), invocation: claimedInvocation, requireGrant: Boolean(principal?.worker) && !options.internal });
|
|
2017
|
+
if (!checked.ok) {
|
|
2018
|
+
if (principal)
|
|
2019
|
+
await this.#recordDecision({ function: name, via: String(options.via), requestId, principal: { id: principal.id, type: principal.type, roles: [...principal.roles] }, outcome: "denied", layer: "grant", reason: `${checked.reason}: ${checked.message}`, argKeys: argKeys(rawArgs) ?? [] });
|
|
2020
|
+
return failure(new FeltKitError("FORBIDDEN", checked.message, { details: { reason: checked.reason } }), { authority: { ...authorityRecord, allowed: false, reason: checked.reason, invocation: { claimed: claimedInvocation, verified: {} } }, argKeys: argKeys(rawArgs) });
|
|
2021
|
+
}
|
|
2022
|
+
invocation = { claimed: claimedInvocation, verified: checked.verified };
|
|
2023
|
+
}
|
|
2024
|
+
if (invocation)
|
|
2025
|
+
authorityRecord.invocation = invocation;
|
|
1630
2026
|
// The approval requirement, at the execution boundary every interface goes through (/api,
|
|
1631
2027
|
// AppPort, MCP, jobs, decisions): permission alone is not enough for a non-person caller.
|
|
1632
|
-
const approvalRefusal = this.#approvalRefusal(name, fn, principal);
|
|
2028
|
+
const approvalRefusal = invocation?.verified.approvalRef ? null : this.#approvalRefusal(name, fn, principal);
|
|
1633
2029
|
if (approvalRefusal) {
|
|
1634
2030
|
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) ?? [] });
|
|
1635
2031
|
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) });
|
|
1636
2032
|
}
|
|
1637
|
-
const approvedAction = fn.approval === "required" && principal?.type !== "user" ? this.#approvedAction.getStore() : undefined;
|
|
2033
|
+
const approvedAction = fn.approval === "required" && principal?.type !== "user" && !invocation?.verified.approvalRef ? this.#approvedAction.getStore() : undefined;
|
|
1638
2034
|
if (approvedAction)
|
|
1639
2035
|
Object.assign(authorityRecord, { approval: { taskId: approvedAction.taskId, actionId: approvedAction.actionId, approvedBy: approvedAction.approvedBy } });
|
|
1640
2036
|
const parsed = validate(fn.argsSchema, rawArgs ?? {});
|
|
@@ -1645,6 +2041,12 @@ export class FeltKitRuntime {
|
|
|
1645
2041
|
});
|
|
1646
2042
|
}
|
|
1647
2043
|
const args = parsed.value;
|
|
2044
|
+
// Quotas (K3): before the policies, the authorize hook and the handler; a refusal writes nothing.
|
|
2045
|
+
const quotaRefusal = this.#admit(name, fn, args, principal, options);
|
|
2046
|
+
if (quotaRefusal)
|
|
2047
|
+
return failure(quotaRefusal, { authority: authorityRecord, argKeys: Object.keys(args), detail: { quota: quotaRefusal.details.quota } });
|
|
2048
|
+
if (fn.kind === "action" && principal?.guest)
|
|
2049
|
+
return failure(new FeltKitError("FORBIDDEN", `${name} is not open to guests: a guest calls only queries and mutations bound to its resource.`, { hint: "GUEST" }), { authority: { ...authorityRecord, allowed: false } });
|
|
1648
2050
|
if (fn.kind === "action") {
|
|
1649
2051
|
// An action's own service effects (ctx.services.files) are the caller's while the action runs, as for a query or mutation.
|
|
1650
2052
|
const releaseAction = this.#services.enter(requestId, principal);
|
|
@@ -1656,6 +2058,7 @@ export class FeltKitRuntime {
|
|
|
1656
2058
|
}
|
|
1657
2059
|
}
|
|
1658
2060
|
const handle = this.instance.handle("app");
|
|
2061
|
+
const releaseFeed = fn.kind === "mutation" ? this.changes.hold() : null;
|
|
1659
2062
|
const release = this.#services.enter(requestId, principal);
|
|
1660
2063
|
const servicesUsed = new Set();
|
|
1661
2064
|
const enabled = this.app.options.services ?? {};
|
|
@@ -1665,7 +2068,7 @@ export class FeltKitRuntime {
|
|
|
1665
2068
|
const db = fn.kind === "mutation" ? new Writer(handle, this.#resolver) : new Reader(handle, this.#resolver);
|
|
1666
2069
|
const used = new Set();
|
|
1667
2070
|
const shared = {
|
|
1668
|
-
auth: authContext(this.#authority, principal, options.context, options.delegation ?? null, options.session ?? null),
|
|
2071
|
+
auth: authContext(this.#authority, principal, options.context, options.delegation ?? null, options.session ?? null, invocation),
|
|
1669
2072
|
tenancy: {
|
|
1670
2073
|
members: async () => {
|
|
1671
2074
|
if (!this.tenancy)
|
|
@@ -1683,7 +2086,9 @@ export class FeltKitRuntime {
|
|
|
1683
2086
|
log: this.logger,
|
|
1684
2087
|
crypto: { token: async (bytes) => randomBytes(checkTokenBytes(bytes)).toString("base64url") },
|
|
1685
2088
|
authority: this.#applicationAuthority(principal, requestId),
|
|
1686
|
-
|
|
2089
|
+
// An external call from a mutation is an effect outside its transaction: the attempt is never re-run on a
|
|
2090
|
+
// sequence conflict (as for ctx.services), so the call is not repeated. Prefer ctx.afterCommit.jobs → an action.
|
|
2091
|
+
integrations: trackedIntegrations(this.#integrationInvoker(principal), used),
|
|
1687
2092
|
};
|
|
1688
2093
|
const starts = [];
|
|
1689
2094
|
const agent = {
|
|
@@ -1735,10 +2140,55 @@ export class FeltKitRuntime {
|
|
|
1735
2140
|
}
|
|
1736
2141
|
},
|
|
1737
2142
|
};
|
|
2143
|
+
// ctx.channels (app.channel): authorized for the sender now, delivered after the commit, never stored.
|
|
2144
|
+
const channels = {
|
|
2145
|
+
send: async (channel, scope, message) => {
|
|
2146
|
+
const declared = channel && this.app.events.get(channel.name);
|
|
2147
|
+
if (!declared?.channel || declared !== channel)
|
|
2148
|
+
throw new FeltKitError("INVALID_ARGUMENT", `ctx.channels.send: ${String(channel?.name ?? channel)} is not a channel declared with app.channel().`);
|
|
2149
|
+
const config = declared.channel;
|
|
2150
|
+
if (typeof scope !== "string" || !/^[^\u0000-\u001f\u007f]{1,256}$/.test(scope))
|
|
2151
|
+
throw new FeltKitError("INVALID_ARGUMENT", `ctx.channels.send(${declared.name}): scope (the recipient) is a non-empty string of at most 256 characters.`);
|
|
2152
|
+
const checked = declared.payload.validate(message);
|
|
2153
|
+
if (!checked.ok)
|
|
2154
|
+
throw new FeltKitError("INVALID_ARGUMENT", `ctx.channels.send(${declared.name}): the message does not match its schema: ${(checked.issues ?? []).map((i) => i.message).join("; ")}`);
|
|
2155
|
+
const bytes = new TextEncoder().encode(JSON.stringify(checked.value ?? message)).length;
|
|
2156
|
+
if (bytes > config.maxBytes)
|
|
2157
|
+
throw new FeltKitError("PAYLOAD_TOO_LARGE", `ctx.channels.send(${declared.name}): the message is ${bytes} bytes; at most ${config.maxBytes}.`);
|
|
2158
|
+
const refuse = async (reason) => {
|
|
2159
|
+
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: "channel", reason, argKeys: [] });
|
|
2160
|
+
throw new FeltKitError(principal ? "FORBIDDEN" : "UNAUTHORIZED", reason, { details: { channel: declared.name } });
|
|
2161
|
+
};
|
|
2162
|
+
if (!this.holds(principal, config.send))
|
|
2163
|
+
await refuse(`${principal?.id ?? "An anonymous caller"} may not send on ${declared.name} (needs ${config.send}).`);
|
|
2164
|
+
if (config.authorize.send) {
|
|
2165
|
+
let allowed = false;
|
|
2166
|
+
try {
|
|
2167
|
+
allowed = (await config.authorize.send({ principal, scope, message: checked.value ?? message, db: scoped })) === true;
|
|
2168
|
+
}
|
|
2169
|
+
catch {
|
|
2170
|
+
allowed = false;
|
|
2171
|
+
}
|
|
2172
|
+
if (!allowed)
|
|
2173
|
+
await refuse(`${declared.name}: the channel's send rule refused this scope.`);
|
|
2174
|
+
}
|
|
2175
|
+
if (config.quota) {
|
|
2176
|
+
const admitted = this.quotas.admit(`channel:${declared.name}`, config.quota, { principalId: principal?.id ?? null, ...(options.client ? { client: options.client } : {}) });
|
|
2177
|
+
if (!admitted.ok)
|
|
2178
|
+
throw rateLimited(admitted.refusal, `${declared.name} (channel)`);
|
|
2179
|
+
}
|
|
2180
|
+
published.push({ name: declared.name, payload: checked.value ?? message, scope });
|
|
2181
|
+
},
|
|
2182
|
+
};
|
|
1738
2183
|
// Tenant-scoped collections see only the caller's tenant (the session's, never the request's).
|
|
1739
|
-
const
|
|
1740
|
-
|
|
1741
|
-
const
|
|
2184
|
+
const tenantScoped = hasTenantCollections(this.app.collections.values()) ? scopeToTenant(db, (ref) => this.#resolver.resolve(ref), principal?.tenant?.id ?? null) : applicationView(db);
|
|
2185
|
+
// Presence collections show only leases that hold now, and change only through ctx.presence.
|
|
2186
|
+
const presenceNames = this.presence.names();
|
|
2187
|
+
const scoped = presenceNames.size ? this.presence.view(tenantScoped) : tenantScoped;
|
|
2188
|
+
const presence = this.presence.api(tenantScoped, principal, options.session ?? null, fn.kind === "mutation" && db instanceof Writer ? (record) => db.stageSystem(OUTBOX_COLLECTION, record) : null, { function: name, requestId });
|
|
2189
|
+
const invocations = this.#invocationsApi(workItemScoped(principal, invocation?.verified), fn.kind === "mutation" && db instanceof Writer ? { stage: (record) => db.stageSystem(INVOCATIONS_COLLECTION, record), staged: () => db.staged.filter((r) => r.collection === INVOCATIONS_COLLECTION).map((r) => r.value.id), effects } : null, { via: String(options.via ?? "function"), requestId });
|
|
2190
|
+
const grants = this.#grantsApi(principal, scoped);
|
|
2191
|
+
const ctx = fn.kind === "mutation" ? { ...shared, presence, channels, grants, invocations, db: scoped, agent, events, afterCommit: effects, unsafe: Object.freeze({ feltdb: escapeHatch(this.instance.handle("app.unsafe"), this.app.collections) }), ...(options.agentRun ? { trigger: options.agentRun.trigger } : {}) } : { ...shared, presence, db: scoped, invocations: { get: invocations.get, list: invocations.list } };
|
|
1742
2192
|
try {
|
|
1743
2193
|
// feltkit({ authorize }): after roles and validation, with this call's own reader, so its
|
|
1744
2194
|
// reads are fenced at commit (mutations) and tracked for live queries (queries).
|
|
@@ -1795,6 +2245,10 @@ export class FeltKitRuntime {
|
|
|
1795
2245
|
if (commit.writes.length) {
|
|
1796
2246
|
this.changes.describe(commit.described);
|
|
1797
2247
|
void this.changes.check();
|
|
2248
|
+
releaseFeed?.();
|
|
2249
|
+
// A lease joined, renewed or ended: the expiry timer follows the earliest live lease.
|
|
2250
|
+
if (this.presence.names().size && commit.writes.some((w) => this.presence.names().has(w.collection)))
|
|
2251
|
+
void this.presence.arm().catch((error) => this.logger.warn(`presence: ${error.message}`));
|
|
1798
2252
|
}
|
|
1799
2253
|
// Agent work starts only once the mutation's writes are durable.
|
|
1800
2254
|
for (const start of starts)
|
|
@@ -1840,9 +2294,33 @@ export class FeltKitRuntime {
|
|
|
1840
2294
|
return failure(error, { authority: authorityRecord, argKeys: Object.keys(args), reads, ...(servicesUsed.size ? { services: [...servicesUsed] } : {}), ...(retries ? { detail: { sequenceRetries: retries } } : {}) });
|
|
1841
2295
|
}
|
|
1842
2296
|
finally {
|
|
2297
|
+
releaseFeed?.();
|
|
1843
2298
|
release();
|
|
1844
2299
|
}
|
|
1845
2300
|
}
|
|
2301
|
+
/**
|
|
2302
|
+
* Count a call against the function's quotas and the application's (K3), or refuse it. Application
|
|
2303
|
+
* agents' runs and the runtime's own calls (session ends, presence ends) are not counted: they are
|
|
2304
|
+
* the platform's, not a caller's.
|
|
2305
|
+
*/
|
|
2306
|
+
#admit(name, fn, args, principal, options) {
|
|
2307
|
+
if (options.agentRun || options.via === "runtime")
|
|
2308
|
+
return null;
|
|
2309
|
+
const caller = { principalId: principal?.id ?? null, ...(options.client ? { client: options.client } : {}) };
|
|
2310
|
+
if (fn.quota) {
|
|
2311
|
+
const admitted = this.quotas.admit(`function:${name}`, fn.quota, caller, args);
|
|
2312
|
+
if (!admitted.ok)
|
|
2313
|
+
return rateLimited(admitted.refusal, name);
|
|
2314
|
+
}
|
|
2315
|
+
const app = this.app.options.quotas;
|
|
2316
|
+
if (app) {
|
|
2317
|
+
const specs = Array.isArray(app) ? app : [app];
|
|
2318
|
+
const admitted = this.quotas.admit("application", specs, caller, args);
|
|
2319
|
+
if (!admitted.ok)
|
|
2320
|
+
return rateLimited(admitted.refusal, `${this.app.name} (every function)`);
|
|
2321
|
+
}
|
|
2322
|
+
return null;
|
|
2323
|
+
}
|
|
1846
2324
|
/**
|
|
1847
2325
|
* Run an action: no transaction and no database handle. It reads and writes only through calls
|
|
1848
2326
|
* (each authorized as the caller, each in its own transaction) and the agent's proposals, so
|
|
@@ -1865,7 +2343,7 @@ export class FeltKitRuntime {
|
|
|
1865
2343
|
if (target.kind !== kind)
|
|
1866
2344
|
throw new FeltKitError("INVALID_ARGUMENT", `${ref.name} is a ${target.kind}; use ctx.run${target.kind === "query" ? "Query" : target.kind === "mutation" ? "Mutation" : "…"}.`);
|
|
1867
2345
|
// Cancellation stops the model (ctx.signal); it does not stop the action recording what happened.
|
|
1868
|
-
const result = await this.call(ref.name, callArgs ?? {}, { principal, via: options.via, ...(options.context ? { context: options.context } : {}), ...(options.session ? { session: options.session } : {}) });
|
|
2346
|
+
const result = await this.call(ref.name, callArgs ?? {}, { principal, via: options.via, internal: true, ...(authorityRecord.invocation ? { invocation: authorityRecord.invocation } : {}), ...(options.context ? { context: options.context } : {}), ...(options.session ? { session: options.session } : {}) });
|
|
1869
2347
|
if (!result.ok)
|
|
1870
2348
|
throw new FeltKitError(result.error.code, result.error.message, { ...(result.error.details ? { details: result.error.details } : {}), ...(result.error.hint ? { hint: result.error.hint } : {}) });
|
|
1871
2349
|
return result.value;
|
|
@@ -1877,7 +2355,7 @@ export class FeltKitRuntime {
|
|
|
1877
2355
|
};
|
|
1878
2356
|
const agent = this.#agent;
|
|
1879
2357
|
const ctx = {
|
|
1880
|
-
auth: authContext(this.#authority, principal, options.context, options.delegation ?? null, options.session ?? null),
|
|
2358
|
+
auth: authContext(this.#authority, principal, options.context, options.delegation ?? null, options.session ?? null, authorityRecord.invocation ?? null),
|
|
1881
2359
|
environment: { name: this.environment.name, production: this.environment.production, storage: describeStorage(this.environment.storage) },
|
|
1882
2360
|
requestId,
|
|
1883
2361
|
log: this.logger,
|
|
@@ -1932,8 +2410,9 @@ export class FeltKitRuntime {
|
|
|
1932
2410
|
},
|
|
1933
2411
|
authority: this.#applicationAuthority(principal, requestId),
|
|
1934
2412
|
integrations: this.#integrationInvoker(principal),
|
|
2413
|
+
grants: this.#grantsApi(principal, applicationView(new Reader(this.instance.handle("app"), this.#resolver))),
|
|
1935
2414
|
services: { files: explainServiceDenials(this.#services.bind(principal, requestId, new Set(), true), name, principal, this.#authority).files },
|
|
1936
|
-
invocations: this.#invocationsApi(principal, null, { via: String(options.via ?? "function"), requestId }),
|
|
2415
|
+
invocations: this.#invocationsApi(workItemScoped(principal, authorityRecord.invocation?.verified), null, { via: String(options.via ?? "function"), requestId }),
|
|
1937
2416
|
agent: {
|
|
1938
2417
|
catalog: async () => (await agent.tools(signedIn())).map((t) => ({
|
|
1939
2418
|
name: t.name,
|
|
@@ -1970,7 +2449,32 @@ export class FeltKitRuntime {
|
|
|
1970
2449
|
try {
|
|
1971
2450
|
const reader = new Reader(this.instance.handle("app"), this.#resolver);
|
|
1972
2451
|
await this.#authorizeResource(name, fn, args, principal, options, requestId, applicationView(reader), authorityRecord);
|
|
1973
|
-
|
|
2452
|
+
// ctx.effect (AppPort's external effect lifecycle, spec §13.5): `begin()` records the effect in
|
|
2453
|
+
// _feltkit_provider_calls before it is attempted; returning is succeeded, effectFailed(...) is failed, any other
|
|
2454
|
+
// throw after begin() is unknown and never repeated. A job's attempts share one record, so a retried job never
|
|
2455
|
+
// begins its effect twice.
|
|
2456
|
+
const effectId = options.idempotencyReplayKey ? `fx_${createHash("sha256").update(options.idempotencyReplayKey).digest("hex").slice(0, 40)}` : requestId;
|
|
2457
|
+
const recorder = this.providers.effectRecorder();
|
|
2458
|
+
const value = await runEffectful({ requestId: effectId, capability: { name: fn.capability?.name ?? name, version: fn.capability?.version ?? 1 }, ...(principal ? { principal: toAppPort(principal) } : {}), ...(authorityRecord.invocation ? { invocation: authorityRecord.invocation } : {}), ...(options.idempotencyKey ? { idempotencyKey: options.idempotencyKey } : {}) }, {
|
|
2459
|
+
provider: this.app.name,
|
|
2460
|
+
providerId: this.app.name,
|
|
2461
|
+
recorder: {
|
|
2462
|
+
...recorder,
|
|
2463
|
+
started: async (call) => {
|
|
2464
|
+
try {
|
|
2465
|
+
await recorder.started(call);
|
|
2466
|
+
}
|
|
2467
|
+
catch (error) {
|
|
2468
|
+
if (await recorder.get(call.id).catch(() => null))
|
|
2469
|
+
throw outcomeUnknown(`${name} already began this external effect in an earlier attempt (${call.id}); it is not attempted again. Ask what happened (appport.invocation.status) or settle it.`, { callId: call.id });
|
|
2470
|
+
throw error;
|
|
2471
|
+
}
|
|
2472
|
+
},
|
|
2473
|
+
},
|
|
2474
|
+
onRecordError: (error, call) => this.logger.error(`${name}: the outcome of external effect ${call.id} could not be recorded`, { error: String(error), outcome: call.outcome }),
|
|
2475
|
+
}, (effect) => fn.handler({ ...ctx, effect }, args)).catch((error) => {
|
|
2476
|
+
throw error instanceof AppPortError ? providerError(error) : error;
|
|
2477
|
+
});
|
|
1974
2478
|
if (fn.returns) {
|
|
1975
2479
|
const output = validate(fn.returns, value);
|
|
1976
2480
|
if (!output.ok)
|
|
@@ -2002,6 +2506,9 @@ export class FeltKitRuntime {
|
|
|
2002
2506
|
if (rule.resource && !this.app.collections.has(rule.resource.collection)) {
|
|
2003
2507
|
throw new FeltKitError("CONFIGURATION", `Policy ${rule.id} names collection ${rule.resource.collection}, which this application does not declare.`);
|
|
2004
2508
|
}
|
|
2509
|
+
if (rule.resource?.by !== undefined && !uniqueField(this.app.collections.get(rule.resource.collection), rule.resource.by)) {
|
|
2510
|
+
throw new FeltKitError("CONFIGURATION", `Policy ${rule.id} addresses ${rule.resource.collection} by "${rule.resource.by}", which is not a unique field of it.`);
|
|
2511
|
+
}
|
|
2005
2512
|
},
|
|
2006
2513
|
});
|
|
2007
2514
|
return this.#policyStore;
|
|
@@ -2114,6 +2621,30 @@ export class FeltKitRuntime {
|
|
|
2114
2621
|
const hook = this.app.options.authorize;
|
|
2115
2622
|
const set = await this.policyStore.current();
|
|
2116
2623
|
const governed = set.rules.some((rule) => rule.functions.includes(name));
|
|
2624
|
+
// The resource gate (K4, K6): guests only on functions bound to their resource, agents only with a grant.
|
|
2625
|
+
if (principal?.guest || fn.resource?.agents === "grant") {
|
|
2626
|
+
const refusal = await resourceRefusal(fn, name, args, principal, db, this.access);
|
|
2627
|
+
if (refusal) {
|
|
2628
|
+
record.allowed = false;
|
|
2629
|
+
record.resource = { allowed: false, reason: refusal.reason };
|
|
2630
|
+
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: "resource", reason: refusal.reason, argKeys: Object.keys(args).sort() });
|
|
2631
|
+
throw new FeltKitError(refusal.code, refusal.reason, { details: { resource: refusal.resource ?? null }, hint: principal?.guest ? "GUEST" : "AGENT_GRANT" });
|
|
2632
|
+
}
|
|
2633
|
+
if (fn.resource)
|
|
2634
|
+
record.resource = { allowed: true, reason: principal?.guest ? `guest of ${principal.guest.resource.collection} ${principal.guest.resource.id}` : "agent granted" };
|
|
2635
|
+
}
|
|
2636
|
+
// A worker's grant scoped to a work item reaches only that record, on a function bound to one (runtime/workers.ts).
|
|
2637
|
+
const workItem = principal?.worker ? record.invocation?.verified.workItemId : undefined;
|
|
2638
|
+
if (workItem !== undefined && fn.resource) {
|
|
2639
|
+
const bound = await loadBoundResource(fn, args, db);
|
|
2640
|
+
if (!bound || String(bound.id) !== workItem) {
|
|
2641
|
+
const reason = `${name}: ${principal.id}'s grant covers ${fn.resource.collection.name} ${workItem} only.`;
|
|
2642
|
+
record.allowed = false;
|
|
2643
|
+
record.resource = { allowed: false, reason };
|
|
2644
|
+
await this.#recordDecision({ function: name, via: String(options.via), requestId, principal: { id: principal.id, type: principal.type, roles: [...principal.roles] }, outcome: "denied", layer: "grant", reason: `GRANT_WORK_ITEM_MISMATCH: ${reason}`, argKeys: Object.keys(args).sort() });
|
|
2645
|
+
throw new FeltKitError("FORBIDDEN", reason, { details: { reason: "GRANT_WORK_ITEM_MISMATCH" } });
|
|
2646
|
+
}
|
|
2647
|
+
}
|
|
2117
2648
|
if (!hook && !fn.owner && !governed)
|
|
2118
2649
|
return;
|
|
2119
2650
|
const evidence = (outcome, layer, reason, policy) => ({
|
|
@@ -2264,6 +2795,7 @@ export class FeltKitRuntime {
|
|
|
2264
2795
|
if (this.#state === "closed" || this.#state === "closing")
|
|
2265
2796
|
return;
|
|
2266
2797
|
this.#state = "closing";
|
|
2798
|
+
this.presence.close();
|
|
2267
2799
|
if (this.#worker)
|
|
2268
2800
|
clearInterval(this.#worker);
|
|
2269
2801
|
this.changes.stop();
|
|
@@ -2297,10 +2829,9 @@ function toAppPort(principal) {
|
|
|
2297
2829
|
*/
|
|
2298
2830
|
export const FELTKIT_APPPORT_STATUS = {
|
|
2299
2831
|
"feltkit.FAILED_PRECONDITION": statusFor("FAILED_PRECONDITION"),
|
|
2300
|
-
UPSTREAM_REJECTED: statusFor("UPSTREAM_REJECTED"),
|
|
2301
|
-
|
|
2302
|
-
|
|
2303
|
-
NOT_CONFIGURED: statusFor("CONFIGURATION"),
|
|
2832
|
+
"feltkit.UPSTREAM_REJECTED": statusFor("UPSTREAM_REJECTED"),
|
|
2833
|
+
"feltkit.UNAVAILABLE": statusFor("UNAVAILABLE"),
|
|
2834
|
+
"feltkit.NOT_CONFIGURED": statusFor("CONFIGURATION"),
|
|
2304
2835
|
};
|
|
2305
2836
|
function toAppPortError(error) {
|
|
2306
2837
|
switch (error.code) {
|
|
@@ -2327,19 +2858,23 @@ function toAppPortError(error) {
|
|
|
2327
2858
|
return appportErrors.rateLimited(error.message, (error.details ?? undefined));
|
|
2328
2859
|
// Not INTERNAL: a caller must be able to tell "may have been applied" from "failed".
|
|
2329
2860
|
case "OUTCOME_UNKNOWN":
|
|
2330
|
-
|
|
2861
|
+
// AppPort's own shape (CONFLICT, details.reason EFFECT_OUTCOME_UNKNOWN): never retried, recorded under the idempotency key.
|
|
2862
|
+
return outcomeUnknown(error.message, (error.details && typeof error.details === "object" && !Array.isArray(error.details) ? error.details : {}));
|
|
2863
|
+
// FeltKit's own codes, namespaced as AppPort requires of codes outside its standard set (`feltkit.*`).
|
|
2331
2864
|
case "UNAVAILABLE":
|
|
2332
|
-
return new AppPortError("UNAVAILABLE", error.message, { retryable: true, details: (error.details ?? null) });
|
|
2865
|
+
return new AppPortError("feltkit.UNAVAILABLE", error.message, { retryable: true, details: (error.details ?? null) });
|
|
2333
2866
|
// An external API refused the request: its identity and status survive, never retryable.
|
|
2334
2867
|
case "UPSTREAM_REJECTED":
|
|
2335
|
-
return new AppPortError("UPSTREAM_REJECTED", error.message, { retryable: false, details: (error.details ?? null) });
|
|
2868
|
+
return new AppPortError("feltkit.UPSTREAM_REJECTED", error.message, { retryable: false, details: (error.details ?? null) });
|
|
2336
2869
|
// The server lacks something an operator must provide (a credential, a URL): not retryable.
|
|
2337
2870
|
case "CONFIGURATION":
|
|
2338
|
-
return new AppPortError("NOT_CONFIGURED", error.message, { retryable: false, details: { hint: error.hint ?? null } });
|
|
2871
|
+
return new AppPortError("feltkit.NOT_CONFIGURED", error.message, { retryable: false, details: { hint: error.hint ?? null } });
|
|
2339
2872
|
default:
|
|
2340
2873
|
return appportErrors.internal(error.message);
|
|
2341
2874
|
}
|
|
2342
2875
|
}
|
|
2876
|
+
/** AppPort's own capabilities a worker reaches without a work grant: describing the application, and its own calls. */
|
|
2877
|
+
const WORKER_UNGRANTED = ["appport.manifest", "appport.ping", "appport.invocation.status"];
|
|
2343
2878
|
/** AppPort's replay key, computed exactly as AppPort scopes it (session, else principal). */
|
|
2344
2879
|
const BUILTIN_CAPABILITY_NAMES = ["appport.manifest", "appport.ping"];
|
|
2345
2880
|
function callerScope(appportPrincipal) {
|
|
@@ -2394,4 +2929,26 @@ class AttemptFailed {
|
|
|
2394
2929
|
this.error = error;
|
|
2395
2930
|
}
|
|
2396
2931
|
}
|
|
2932
|
+
/** Why `principal` may not call a function of this visibility from a surface, or null (runtime/workers.ts). */
|
|
2933
|
+
export function visibilityRefusalFor(name, visibility, principal) {
|
|
2934
|
+
if (visibility === "internal")
|
|
2935
|
+
return { code: "FUNCTION_NOT_FOUND", message: `No query or mutation named "${name}".` };
|
|
2936
|
+
if (!principal)
|
|
2937
|
+
return { code: "UNAUTHORIZED", message: `${name} is for ${visibility === "worker" ? "registered workers" : "services"} only.` };
|
|
2938
|
+
if (visibility === "worker" && !principal.worker)
|
|
2939
|
+
return { code: "FORBIDDEN", message: `${name} is called only by a registered worker under a work grant, not by a ${principal.type}.` };
|
|
2940
|
+
if (visibility === "service" && principal.type !== "service")
|
|
2941
|
+
return { code: "FORBIDDEN", message: `${name} is called only by a service (an API key, a component), not by a ${principal.type}.` };
|
|
2942
|
+
return null;
|
|
2943
|
+
}
|
|
2944
|
+
/** ctx.integrations, noting into `used` that the attempt reached outside its transaction (no sequence-conflict re-run). */
|
|
2945
|
+
function trackedIntegrations(invoker, used) {
|
|
2946
|
+
return {
|
|
2947
|
+
...invoker,
|
|
2948
|
+
invoke: (...args) => {
|
|
2949
|
+
used.add("integrations");
|
|
2950
|
+
return invoker.invoke(...args);
|
|
2951
|
+
},
|
|
2952
|
+
};
|
|
2953
|
+
}
|
|
2397
2954
|
//# sourceMappingURL=runtime.js.map
|