@feltdb/feltkit 0.3.32 → 0.3.34
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 +15 -0
- package/dist/app.js +2 -0
- package/dist/app.js.map +1 -1
- package/dist/appboundry/build.js +3 -0
- package/dist/appboundry/build.js.map +1 -1
- package/dist/appboundry/runtime.d.ts +1 -1
- package/dist/appboundry/runtime.js +1 -1
- package/dist/appboundry/runtime.js.map +1 -1
- package/dist/cli/deploy-appboundry-self-hosted.js +10 -4
- package/dist/cli/deploy-appboundry-self-hosted.js.map +1 -1
- package/dist/cli/main.js +1 -1
- package/dist/cli/main.js.map +1 -1
- package/dist/client/index.d.ts +8 -0
- package/dist/client/index.js +7 -0
- package/dist/client/index.js.map +1 -1
- package/dist/component.js +1 -1
- package/dist/component.js.map +1 -1
- package/dist/docs.d.ts +1 -1
- package/dist/docs.js +1 -0
- package/dist/docs.js.map +1 -1
- package/dist/measure/index.js +17 -0
- package/dist/measure/index.js.map +1 -1
- package/dist/providers.d.ts +23 -0
- package/dist/providers.js +29 -0
- package/dist/providers.js.map +1 -0
- package/dist/runtime/access-grants.d.ts +25 -0
- package/dist/runtime/access-grants.js +78 -0
- package/dist/runtime/access-grants.js.map +1 -0
- package/dist/runtime/activity.d.ts +2 -0
- package/dist/runtime/activity.js.map +1 -1
- package/dist/runtime/authority.d.ts +16 -1
- package/dist/runtime/authority.js +3 -1
- package/dist/runtime/authority.js.map +1 -1
- package/dist/runtime/backup.js +2 -1
- package/dist/runtime/backup.js.map +1 -1
- package/dist/runtime/context.d.ts +8 -0
- package/dist/runtime/contract.js +10 -1
- package/dist/runtime/contract.js.map +1 -1
- package/dist/runtime/delegation.d.ts +47 -0
- package/dist/runtime/delegation.js +55 -0
- package/dist/runtime/delegation.js.map +1 -0
- package/dist/runtime/loader.js +2 -1
- package/dist/runtime/loader.js.map +1 -1
- package/dist/runtime/providers.d.ts +72 -0
- package/dist/runtime/providers.js +252 -0
- package/dist/runtime/providers.js.map +1 -0
- package/dist/runtime/runtime.d.ts +35 -1
- package/dist/runtime/runtime.js +204 -10
- package/dist/runtime/runtime.js.map +1 -1
- package/dist/runtime/sessions.d.ts +41 -1
- package/dist/runtime/sessions.js +74 -7
- package/dist/runtime/sessions.js.map +1 -1
- package/dist/server/admin.js +6 -1
- package/dist/server/admin.js.map +1 -1
- package/dist/server/index.d.ts +1 -0
- package/dist/server/index.js +60 -6
- package/dist/server/index.js.map +1 -1
- package/dist/server/mcp.d.ts +5 -0
- package/dist/server/mcp.js +42 -1
- package/dist/server/mcp.js.map +1 -1
- package/dist/server/project.d.ts +8 -0
- package/dist/server/project.js +10 -1
- package/dist/server/project.js.map +1 -1
- package/dist/server/tenancy.js +1 -1
- package/dist/server/tenancy.js.map +1 -1
- package/docs/AUTH.md +40 -0
- package/docs/LOCAL-AUTHORITY.md +37 -0
- package/docs/MEASURE.md +8 -1
- package/docs/PROVIDERS.md +103 -0
- package/docs/README.md +3 -2
- package/package.json +11 -10
- package/skills/.claude-plugin/marketplace.json +1 -1
- package/skills/.claude-plugin/plugin.json +1 -1
package/dist/runtime/runtime.js
CHANGED
|
@@ -29,6 +29,7 @@ import { backupMeta, remoteBackupRefusal } from "./backup-environment.js";
|
|
|
29
29
|
import { FeltKitError, isFeltKitError, statusFor } from "../errors.js";
|
|
30
30
|
import { validate } from "../schema.js";
|
|
31
31
|
import { ActivityLog, errorSummary } from "./activity.js";
|
|
32
|
+
import { ProviderHost, providerError } from "./providers.js";
|
|
32
33
|
import { Authority, authContext, fromAppPortPrincipal, normalizePrincipal, toAppPortPrincipal } from "./authority.js";
|
|
33
34
|
import { ChangeFeed } from "./changes.js";
|
|
34
35
|
import { generationDigest } from "./generation.js";
|
|
@@ -43,12 +44,14 @@ import { claimed, isRecoverable, isSequenceConflict, outboxStore, performOutbox,
|
|
|
43
44
|
import { OAuthCredentials } from "./oauth-credentials.js";
|
|
44
45
|
import { INVOCATIONS_COLLECTION, InvocationStore } from "./invocations.js";
|
|
45
46
|
import { ExecutionHost } from "./execution-host.js";
|
|
46
|
-
import { LocalAuthorityHost } from "./local-authority.js";
|
|
47
|
+
import { LocalAuthorityHost, applicationCapabilities, authorityAgentId } from "./local-authority.js";
|
|
48
|
+
import { authorityPrincipalOf } from "./application-authority.js";
|
|
49
|
+
import { verifyDelegation } from "./delegation.js";
|
|
47
50
|
import { credentialsFor, isCustodyError } from "./credentials.js";
|
|
48
51
|
import { AgentHost } from "./agent.js";
|
|
49
52
|
import { FeltDbIdempotencyStore } from "./idempotency.js";
|
|
50
53
|
import { capabilityDefinition } from "./capabilities.js";
|
|
51
|
-
import { FeltDbSessionStore } from "./sessions.js";
|
|
54
|
+
import { FeltDbSessionStore, sessionRef } from "./sessions.js";
|
|
52
55
|
import { escapeHatch } from "./escape-hatch.js";
|
|
53
56
|
import { AUDIT_COLLECTION, auditRecord, readAudit } from "./audit.js";
|
|
54
57
|
import { AccountStore } from "./accounts.js";
|
|
@@ -63,6 +66,10 @@ const NODE_TENANCY_CRYPTO = {
|
|
|
63
66
|
randomBase64url: (bytes) => randomBytes(bytes).toString("base64url"),
|
|
64
67
|
hmacBase64url: (key, data) => createHmac("sha256", key).update(data).digest("base64url"),
|
|
65
68
|
};
|
|
69
|
+
/** How often expired sessions are ended for auth.onSessionEnd: the bound on noticing an expiry. */
|
|
70
|
+
export const SESSION_EXPIRY_SWEEP_MS = 5_000;
|
|
71
|
+
/** Attempts at running auth.onSessionEnd for one ended session before it is kept as failed. */
|
|
72
|
+
export const SESSION_END_MAX_ATTEMPTS = 10;
|
|
66
73
|
const consoleLogger = {
|
|
67
74
|
info: (m, f) => console.log(`[feltkit] ${m}`, f ?? ""),
|
|
68
75
|
warn: (m, f) => console.warn(`[feltkit] ${m}`, f ?? ""),
|
|
@@ -105,6 +112,8 @@ export class FeltKitRuntime {
|
|
|
105
112
|
models;
|
|
106
113
|
/** HTTP integrations declared with app.integration() (runtime/integrations.ts). */
|
|
107
114
|
integrations;
|
|
115
|
+
/** AppPort providers the application declared (`feltkit({ providers })`): started, registered, recorded, stopped. */
|
|
116
|
+
providers;
|
|
108
117
|
/** OAuth 2.0 grants of integrations: renewed, rotated, disconnected (runtime/oauth-credentials.ts). */
|
|
109
118
|
oauth;
|
|
110
119
|
/** Durable invocations from registered surfaces: lifecycle, dispatch, recovery (runtime/invocations.ts). */
|
|
@@ -155,6 +164,7 @@ export class FeltKitRuntime {
|
|
|
155
164
|
this.idempotency = new FeltDbIdempotencyStore(instance.handle("appport.idempotency"));
|
|
156
165
|
this.models = new ModelHost(this, { env });
|
|
157
166
|
this.integrations = new IntegrationHost(this);
|
|
167
|
+
this.providers = new ProviderHost(this);
|
|
158
168
|
this.oauth = new OAuthCredentials(this);
|
|
159
169
|
this.invocations = new InvocationStore(this);
|
|
160
170
|
this.localAuthority = new LocalAuthorityHost(this);
|
|
@@ -181,6 +191,7 @@ export class FeltKitRuntime {
|
|
|
181
191
|
let runtime;
|
|
182
192
|
try {
|
|
183
193
|
runtime = new FeltKitRuntime(options.environment, instance, logger, options.env ?? process.env);
|
|
194
|
+
await runtime.providers.sync(options.project.app.options.providers, options.project.projectDir ?? process.cwd());
|
|
184
195
|
runtime.#install(options.project);
|
|
185
196
|
// How long each startup step took: on a FeltDB server each is network round trips, and a
|
|
186
197
|
// platform that waits for the port (Vercel: ~28 s) needs to know which one is slow.
|
|
@@ -385,6 +396,7 @@ export class FeltKitRuntime {
|
|
|
385
396
|
}
|
|
386
397
|
await ensureCollectionMarkers(this.instance.handle("feltkit.runtime"), project.app.collections.keys());
|
|
387
398
|
const previous = this.#appport;
|
|
399
|
+
await this.providers.sync(project.app.options.providers, project.projectDir ?? process.cwd());
|
|
388
400
|
this.#install(project);
|
|
389
401
|
await this.#ensureSchema(project.app, "reload");
|
|
390
402
|
await this.#orderedIndexes(project.app);
|
|
@@ -492,12 +504,18 @@ export class FeltKitRuntime {
|
|
|
492
504
|
if ((op.expose ?? integration.expose ?? true) !== false)
|
|
493
505
|
capabilities.push(this.#integrationCapability(integration, op));
|
|
494
506
|
}
|
|
507
|
+
// AppPort providers (feltkit({ providers })): their capabilities beside the application's own, one registry.
|
|
508
|
+
for (const capability of this.providers.capabilities()) {
|
|
509
|
+
if (capabilities.some((c) => c.name === capability.name))
|
|
510
|
+
throw new FeltKitError("CONFIGURATION", `Capability ${capability.name} is published both by the application and by provider ${String(capability.attributes?.providerInstance)}.`, { hint: "Rename the application's capability or remove the provider." });
|
|
511
|
+
capabilities.push(capability);
|
|
512
|
+
}
|
|
495
513
|
const appport = createApplication({
|
|
496
514
|
application: { id: app.name, name: app.name, version: app.version, ...(app.options.description ? { description: app.options.description } : {}) },
|
|
497
515
|
capabilities,
|
|
498
516
|
// app.event(): AppPort events; observation is authorized by roles, then feltkit({ authorize }).
|
|
499
517
|
events: eventDefinitions(app),
|
|
500
|
-
authorizer: observationAuthorizer(app, authority.authorizer, () => new Reader(this.instance.handle("app"), new CollectionResolver(app.collections))),
|
|
518
|
+
authorizer: this.#delegatedAuthorizer(observationAuthorizer(app, authority.authorizer, () => new Reader(this.instance.handle("app"), new CollectionResolver(app.collections)))),
|
|
501
519
|
db: this.instance.handle("appport"),
|
|
502
520
|
sessions: this.sessions,
|
|
503
521
|
// Durable replay protection for capabilities that declare idempotency: the claim is
|
|
@@ -511,8 +529,17 @@ export class FeltKitRuntime {
|
|
|
511
529
|
// Every transport (HTTP, WebSocket, MCP) dispatches through these two methods.
|
|
512
530
|
for (const method of ["handleRequest", "handleStreamRequest"]) {
|
|
513
531
|
const original = appport[method].bind(appport);
|
|
514
|
-
appport[method] = (request, options = {}) => this.#appportCaller.run(
|
|
532
|
+
appport[method] = (request, options = {}) => this.#appportCaller.run(callerScope(options?.principal ?? options?.session?.principal), () => original(request, options));
|
|
533
|
+
}
|
|
534
|
+
// auth.onSessionEnd: a mutation of this application; ends are recorded only when one is declared.
|
|
535
|
+
const sessionEndHook = project.app.options.auth?.onSessionEnd;
|
|
536
|
+
if (sessionEndHook !== undefined) {
|
|
537
|
+
const target = typeof sessionEndHook === "string" ? project.functions.get(sessionEndHook) : undefined;
|
|
538
|
+
if (!target || target.kind !== "mutation")
|
|
539
|
+
throw new FeltKitError("CONFIGURATION", `auth.onSessionEnd: ${JSON.stringify(sessionEndHook)} is not a mutation of this application (write "<module>:<export>").`);
|
|
515
540
|
}
|
|
541
|
+
this.sessions.recordEnds = sessionEndHook !== undefined;
|
|
542
|
+
this.sessions.onEnd = () => void this.runSessionEnds();
|
|
516
543
|
this.#project = project;
|
|
517
544
|
this.#authority = authority;
|
|
518
545
|
this.#services = services;
|
|
@@ -617,6 +644,11 @@ export class FeltKitRuntime {
|
|
|
617
644
|
},
|
|
618
645
|
},
|
|
619
646
|
invoke: async (capability, input, options = {}) => {
|
|
647
|
+
if (this.providers.provides(capability)) {
|
|
648
|
+
if (options.onBehalfOf !== undefined)
|
|
649
|
+
throw new FeltKitError("INVALID_ARGUMENT", `${capability} is a provider capability; onBehalfOf applies to a person's integration connection.`);
|
|
650
|
+
return this.invokeCapability(capability, input, principal, { via: "function", ...(options.idempotencyKey ? { idempotencyKey: options.idempotencyKey } : {}) });
|
|
651
|
+
}
|
|
620
652
|
const found = this.integrations.operationFor(capability);
|
|
621
653
|
if (!found)
|
|
622
654
|
throw new FeltKitError("NOT_FOUND", `${capability} is not an integration operation.`);
|
|
@@ -637,6 +669,20 @@ export class FeltKitRuntime {
|
|
|
637
669
|
},
|
|
638
670
|
};
|
|
639
671
|
}
|
|
672
|
+
/**
|
|
673
|
+
* Any published AppPort capability (the application's own, an integration's, a provider's), called as `principal`
|
|
674
|
+
* through the application's AppPort pipeline: validation, roles, idempotency, and effect recording apply exactly as
|
|
675
|
+
* for any AppPort client. Application code reaches it through ctx.integrations.invoke; browsers through
|
|
676
|
+
* POST /api/capability/<name> (client.invoke).
|
|
677
|
+
*/
|
|
678
|
+
async invokeCapability(capability, input, principal, options) {
|
|
679
|
+
if (!principal)
|
|
680
|
+
throw new FeltKitError("UNAUTHORIZED", `${capability} needs an authenticated caller.`);
|
|
681
|
+
const response = (await this.appport.handleRequest({ protocol: "appport/1", type: "request", requestId: `req_${randomUUID()}`, capability: { name: capability, version: options.version ?? 1 }, input, ...(options.idempotencyKey ? { idempotencyKey: options.idempotencyKey } : {}), metadata: { transport: options.via } }, { principal: toAppPort(principal), transport: options.via }));
|
|
682
|
+
if (response.ok)
|
|
683
|
+
return response.output;
|
|
684
|
+
throw providerError(response.error);
|
|
685
|
+
}
|
|
640
686
|
/** An integration operation as an AppPort capability: AppPort validates and authorizes; IntegrationHost calls and records. */
|
|
641
687
|
#integrationCapability(integration, op) {
|
|
642
688
|
return defineCapability({
|
|
@@ -651,6 +697,8 @@ export class FeltKitRuntime {
|
|
|
651
697
|
integration: integrationDescriptor(integration, op),
|
|
652
698
|
attributes: { feltkitIntegration: integration.name },
|
|
653
699
|
handler: async (input, context) => {
|
|
700
|
+
if (this.#appportCaller.getStore()?.onBehalfOf)
|
|
701
|
+
throw appportErrors.forbidden("An agent invokes only published functions on behalf of a person.");
|
|
654
702
|
const principal = fromAppPortPrincipal(context.principal ?? context.session?.principal);
|
|
655
703
|
this.#dispatched.add(context.requestId);
|
|
656
704
|
try {
|
|
@@ -673,6 +721,68 @@ export class FeltKitRuntime {
|
|
|
673
721
|
}
|
|
674
722
|
/** The caller of the AppPort request being dispatched (see #gate). */
|
|
675
723
|
#appportCaller = new AsyncLocalStorage();
|
|
724
|
+
/**
|
|
725
|
+
* AppPort's authorizer, extended for an agent working for a person (runtime/delegation.ts). A request
|
|
726
|
+
* without a person is decided by `inner` unchanged. One with a person is decided here, before AppPort
|
|
727
|
+
* claims an idempotency key or runs anything: one AuthBoundry decision as the proven agent for exactly
|
|
728
|
+
* this capability on behalf of that person, then the person's own roles for the capability's
|
|
729
|
+
* permission. The verified delegation is kept in the request's scope for the handler.
|
|
730
|
+
*/
|
|
731
|
+
#delegatedAuthorizer(inner) {
|
|
732
|
+
return {
|
|
733
|
+
name: inner.name,
|
|
734
|
+
authorize: async (request) => {
|
|
735
|
+
const scope = this.#appportCaller.getStore();
|
|
736
|
+
if (!scope?.onBehalfOf)
|
|
737
|
+
return inner.authorize(request);
|
|
738
|
+
const deny = (reason, code = "FORBIDDEN") => ({ allowed: false, code, reason });
|
|
739
|
+
const agent = scope.principal;
|
|
740
|
+
if (!agent || agent.type !== "agent")
|
|
741
|
+
return deny("Only an authenticated agent acts on behalf of a person.", "UNAUTHORIZED");
|
|
742
|
+
const capability = String(request.capability?.name ?? "");
|
|
743
|
+
// The protocol's own capabilities (manifest, ping) describe the application, not the person: the agent's own.
|
|
744
|
+
if (BUILTIN_CAPABILITY_NAMES.includes(capability))
|
|
745
|
+
return inner.authorize(request);
|
|
746
|
+
const fn = [...this.#project.functions.values()].find((f) => f.capability?.name === capability && f.capability.version === request.capability?.version);
|
|
747
|
+
if (!fn)
|
|
748
|
+
return deny(`${capability} is not a published function: an agent invokes only those on behalf of a person.`);
|
|
749
|
+
if (fn.approval === "required")
|
|
750
|
+
return deny(`${capability} requires a person's approval: an agent cannot run it on a person's behalf.`);
|
|
751
|
+
const config = this.app.options.authority;
|
|
752
|
+
if (!config || !applicationCapabilities(this).includes(capability))
|
|
753
|
+
return deny(`${capability} is not delegable: the application does not list it in authority.capabilities.`);
|
|
754
|
+
const person = await this.#delegator(scope.onBehalfOf);
|
|
755
|
+
if (!person)
|
|
756
|
+
return deny(`No person ${scope.onBehalfOf} in this application.`);
|
|
757
|
+
const requestId = String(request.requestId ?? `req_${randomUUID()}`);
|
|
758
|
+
const agentAuthority = authorityAgentId(agent.id);
|
|
759
|
+
const onBehalfOf = authorityPrincipalOf(config, person.id);
|
|
760
|
+
const decision = await this.decideAsExecutor(agent, requestId, { capability, onBehalfOf: { person: person.id } });
|
|
761
|
+
const verified = verifyDelegation(decision, { agent: agent.id, agentAuthority, person: person.id, onBehalfOf, capability });
|
|
762
|
+
if ("refused" in verified)
|
|
763
|
+
return deny(`No delegation from ${person.id} to ${agentAuthority} for ${capability}: ${verified.refused}`);
|
|
764
|
+
const own = await inner.authorize({ ...request, principal: toAppPortPrincipal(person), session: undefined });
|
|
765
|
+
if (!own.allowed)
|
|
766
|
+
return deny(`${person.id} does not hold ${capability} themselves, so no delegation can grant it.`);
|
|
767
|
+
scope.delegation = verified;
|
|
768
|
+
scope.person = person;
|
|
769
|
+
return {
|
|
770
|
+
allowed: true,
|
|
771
|
+
decision: { decisionId: verified.decisionId, authorizer: "authboundry", capability: request.capability, principalId: agent.id, evidenceId: verified.delegationId, ...(request.session?.id ? { sessionId: request.session.id } : {}) },
|
|
772
|
+
};
|
|
773
|
+
},
|
|
774
|
+
};
|
|
775
|
+
}
|
|
776
|
+
/** The person a delegation is for, as they are now: an account (not disabled), else their current identity. Never an agent or a service. */
|
|
777
|
+
async #delegator(id) {
|
|
778
|
+
if (this.accounts) {
|
|
779
|
+
const account = await this.accounts.get(id).catch(() => null);
|
|
780
|
+
if (account)
|
|
781
|
+
return account.disabled ? null : { id, type: "user", roles: [...account.roles], ...(account.name ? { displayName: account.name } : {}) };
|
|
782
|
+
}
|
|
783
|
+
const found = await this.resolvePrincipal(id, { devUsers: true });
|
|
784
|
+
return found?.type === "user" ? { id: found.id, type: "user", roles: [...found.roles], ...(found.displayName ? { displayName: found.displayName } : {}) } : null;
|
|
785
|
+
}
|
|
676
786
|
/**
|
|
677
787
|
* The approved agent action being executed (agent.ts #execute), in this process only: the
|
|
678
788
|
* one way a non-person principal runs an `approval: "required"` mutation. Nothing a caller
|
|
@@ -706,6 +816,9 @@ export class FeltKitRuntime {
|
|
|
706
816
|
const scope = this.#appportCaller.getStore();
|
|
707
817
|
if (!scope || fn.access === "public")
|
|
708
818
|
return;
|
|
819
|
+
// On behalf of a person: decided by the authorizer, from the delegation and the person's own roles.
|
|
820
|
+
if (scope.onBehalfOf)
|
|
821
|
+
return;
|
|
709
822
|
if (!scope.principal)
|
|
710
823
|
throw appportErrors.unauthorized("Authentication is required");
|
|
711
824
|
const required = Authority.required(fn.access);
|
|
@@ -719,7 +832,11 @@ export class FeltKitRuntime {
|
|
|
719
832
|
#capabilityFor(name, fn) {
|
|
720
833
|
const exposure = fn.capability;
|
|
721
834
|
return capabilityDefinition(name, fn, async (input, context) => {
|
|
722
|
-
const
|
|
835
|
+
const scope = this.#appportCaller.getStore();
|
|
836
|
+
const delegation = scope?.onBehalfOf ? scope.delegation : undefined;
|
|
837
|
+
if (scope?.onBehalfOf && (!delegation || !scope.person || delegation.capability !== exposure.name))
|
|
838
|
+
throw appportErrors.forbidden("No verified delegation for this capability.");
|
|
839
|
+
const principal = delegation ? scope.person : fromAppPortPrincipal(context.principal ?? context.session?.principal);
|
|
723
840
|
this.#dispatched.add(context.requestId);
|
|
724
841
|
const transport = context.metadata?.transport === "mcp" ? "mcp" : context.metadata?.transport === "agent" ? "agent" : "appport";
|
|
725
842
|
const result = await this.call(name, input, {
|
|
@@ -729,6 +846,9 @@ export class FeltKitRuntime {
|
|
|
729
846
|
capability: { name: exposure.name, version: exposure.version },
|
|
730
847
|
...(context.authorizationDecision?.decisionId ? { appportDecisionId: context.authorizationDecision.decisionId } : {}),
|
|
731
848
|
...(fn.kind === "mutation" && context.idempotencyKey ? { idempotencyReplayKey: replayKey(context, exposure, principal) } : {}),
|
|
849
|
+
...(delegation ? { delegation } : {}),
|
|
850
|
+
// A delegated call acts for the person under the agent's session: it binds to no session of theirs.
|
|
851
|
+
...(!delegation && sessionRef(context.session?.id) ? { session: { ref: sessionRef(context.session?.id) } } : {}),
|
|
732
852
|
});
|
|
733
853
|
if (result.ok)
|
|
734
854
|
return result.value;
|
|
@@ -1152,6 +1272,59 @@ export class FeltKitRuntime {
|
|
|
1152
1272
|
});
|
|
1153
1273
|
}
|
|
1154
1274
|
/** Drive durable service work once (jobs, schedules, webhook deliveries, recovered after-commit effects). */
|
|
1275
|
+
#sessionEnds;
|
|
1276
|
+
#sessionEndsAgain = false;
|
|
1277
|
+
#lastExpirySweep = 0;
|
|
1278
|
+
/**
|
|
1279
|
+
* Hand ended sessions to the application's `auth.onSessionEnd` (docs/AUTH.md, "When a session ends"): end
|
|
1280
|
+
* expired sessions (at most every SESSION_EXPIRY_SWEEP_MS), then run the hook for each recorded end, as the
|
|
1281
|
+
* session's principal, and forget the end once it succeeds. A failed run is retried on the next pass and
|
|
1282
|
+
* kept as failed, with its error, after SESSION_END_MAX_ATTEMPTS. Runs on every services tick and right
|
|
1283
|
+
* after a session ends; one pass at a time.
|
|
1284
|
+
*/
|
|
1285
|
+
runSessionEnds() {
|
|
1286
|
+
if (this.#state !== "ready" || this.#paused || this.app.options.auth?.onSessionEnd === undefined)
|
|
1287
|
+
return Promise.resolve();
|
|
1288
|
+
if (this.#sessionEnds) {
|
|
1289
|
+
this.#sessionEndsAgain = true;
|
|
1290
|
+
return this.#sessionEnds;
|
|
1291
|
+
}
|
|
1292
|
+
const pass = async () => {
|
|
1293
|
+
do {
|
|
1294
|
+
this.#sessionEndsAgain = false;
|
|
1295
|
+
const hook = this.app.options.auth?.onSessionEnd;
|
|
1296
|
+
if (!hook)
|
|
1297
|
+
return;
|
|
1298
|
+
if (Date.now() - this.#lastExpirySweep >= SESSION_EXPIRY_SWEEP_MS) {
|
|
1299
|
+
this.#lastExpirySweep = Date.now();
|
|
1300
|
+
await this.sessions.sweepExpired();
|
|
1301
|
+
}
|
|
1302
|
+
for (const end of await this.sessions.pendingEnds()) {
|
|
1303
|
+
const principal = end.principal ? fromAppPortPrincipal(end.principal) : null;
|
|
1304
|
+
if (!principal) {
|
|
1305
|
+
await this.sessions.endHandled(end); // nobody's session: nothing can be bound to it
|
|
1306
|
+
continue;
|
|
1307
|
+
}
|
|
1308
|
+
const result = await this.call(hook, { session: end.ref, reason: end.reason }, { principal, via: "runtime", requestId: `session_end_${end.ref}_${end.attempts}` });
|
|
1309
|
+
if (result.ok)
|
|
1310
|
+
await this.sessions.endHandled(end);
|
|
1311
|
+
else {
|
|
1312
|
+
this.logger.warn(`auth.onSessionEnd (${hook}) failed for session ${end.ref}: ${result.error.code}: ${result.error.message}`);
|
|
1313
|
+
await this.sessions.endAttemptFailed(end, `${result.error.code}: ${result.error.message}`, SESSION_END_MAX_ATTEMPTS);
|
|
1314
|
+
}
|
|
1315
|
+
}
|
|
1316
|
+
} while (this.#sessionEndsAgain);
|
|
1317
|
+
};
|
|
1318
|
+
const run = pass()
|
|
1319
|
+
.catch((error) => this.logger.warn(`session ends: ${error.message}`))
|
|
1320
|
+
.finally(() => {
|
|
1321
|
+
this.#sessionEnds = undefined;
|
|
1322
|
+
this.#inflight.delete(run);
|
|
1323
|
+
});
|
|
1324
|
+
this.#sessionEnds = run;
|
|
1325
|
+
this.#inflight.add(run);
|
|
1326
|
+
return run;
|
|
1327
|
+
}
|
|
1155
1328
|
runServices() {
|
|
1156
1329
|
if (this.#state !== "ready" || this.#paused)
|
|
1157
1330
|
return Promise.resolve({ jobs: 0, deliveries: 0, scheduled: 0, failed: { jobs: 0, deliveries: 0 } });
|
|
@@ -1159,6 +1332,7 @@ export class FeltKitRuntime {
|
|
|
1159
1332
|
return this.#ticking;
|
|
1160
1333
|
const run = Promise.all([
|
|
1161
1334
|
this.#services.tick(this.workerId),
|
|
1335
|
+
this.runSessionEnds(),
|
|
1162
1336
|
this.recoverOutbox().catch((error) => {
|
|
1163
1337
|
this.logger.warn(`after-commit recovery: ${error.message}`);
|
|
1164
1338
|
return 0;
|
|
@@ -1427,7 +1601,11 @@ export class FeltKitRuntime {
|
|
|
1427
1601
|
policyVersion: decision.policyVersion,
|
|
1428
1602
|
...(decision.reason ? { reason: decision.reason } : {}),
|
|
1429
1603
|
...(options.appportDecisionId ? { appportDecisionId: options.appportDecisionId } : {}),
|
|
1604
|
+
...(options.delegation ? { delegation: { ...options.delegation } } : {}),
|
|
1430
1605
|
};
|
|
1606
|
+
if (options.delegation && (options.delegation.person !== principal?.id || fn.approval === "required")) {
|
|
1607
|
+
return failure(new FeltKitError("FORBIDDEN", "A delegated call runs only as the verified person, and never an approval-required function."), { authority: { ...authorityRecord, allowed: false } });
|
|
1608
|
+
}
|
|
1431
1609
|
if (!decision.allowed) {
|
|
1432
1610
|
// Durable evidence for a signed-in caller's refusal (an anonymous caller refused before sign-in is in the activity log only).
|
|
1433
1611
|
if (principal)
|
|
@@ -1452,8 +1630,16 @@ export class FeltKitRuntime {
|
|
|
1452
1630
|
});
|
|
1453
1631
|
}
|
|
1454
1632
|
const args = parsed.value;
|
|
1455
|
-
if (fn.kind === "action")
|
|
1456
|
-
|
|
1633
|
+
if (fn.kind === "action") {
|
|
1634
|
+
// An action's own service effects (ctx.services.files) are the caller's while the action runs, as for a query or mutation.
|
|
1635
|
+
const releaseAction = this.#services.enter(requestId, principal);
|
|
1636
|
+
try {
|
|
1637
|
+
return await this.#runAction(name, fn, args, principal, options, requestId, authorityRecord, finish, failure);
|
|
1638
|
+
}
|
|
1639
|
+
finally {
|
|
1640
|
+
releaseAction();
|
|
1641
|
+
}
|
|
1642
|
+
}
|
|
1457
1643
|
const handle = this.instance.handle("app");
|
|
1458
1644
|
const release = this.#services.enter(requestId, principal);
|
|
1459
1645
|
const servicesUsed = new Set();
|
|
@@ -1464,7 +1650,7 @@ export class FeltKitRuntime {
|
|
|
1464
1650
|
const db = fn.kind === "mutation" ? new Writer(handle, this.#resolver) : new Reader(handle, this.#resolver);
|
|
1465
1651
|
const used = new Set();
|
|
1466
1652
|
const shared = {
|
|
1467
|
-
auth: authContext(this.#authority, principal, options.context),
|
|
1653
|
+
auth: authContext(this.#authority, principal, options.context, options.delegation ?? null, options.session ?? null),
|
|
1468
1654
|
tenancy: {
|
|
1469
1655
|
members: async () => {
|
|
1470
1656
|
if (!this.tenancy)
|
|
@@ -1664,7 +1850,7 @@ export class FeltKitRuntime {
|
|
|
1664
1850
|
if (target.kind !== kind)
|
|
1665
1851
|
throw new FeltKitError("INVALID_ARGUMENT", `${ref.name} is a ${target.kind}; use ctx.run${target.kind === "query" ? "Query" : target.kind === "mutation" ? "Mutation" : "…"}.`);
|
|
1666
1852
|
// Cancellation stops the model (ctx.signal); it does not stop the action recording what happened.
|
|
1667
|
-
const result = await this.call(ref.name, callArgs ?? {}, { principal, via: options.via, ...(options.context ? { context: options.context } : {}) });
|
|
1853
|
+
const result = await this.call(ref.name, callArgs ?? {}, { principal, via: options.via, ...(options.context ? { context: options.context } : {}), ...(options.session ? { session: options.session } : {}) });
|
|
1668
1854
|
if (!result.ok)
|
|
1669
1855
|
throw new FeltKitError(result.error.code, result.error.message, { ...(result.error.details ? { details: result.error.details } : {}), ...(result.error.hint ? { hint: result.error.hint } : {}) });
|
|
1670
1856
|
return result.value;
|
|
@@ -1676,7 +1862,7 @@ export class FeltKitRuntime {
|
|
|
1676
1862
|
};
|
|
1677
1863
|
const agent = this.#agent;
|
|
1678
1864
|
const ctx = {
|
|
1679
|
-
auth: authContext(this.#authority, principal, options.context),
|
|
1865
|
+
auth: authContext(this.#authority, principal, options.context, options.delegation ?? null, options.session ?? null),
|
|
1680
1866
|
environment: { name: this.environment.name, production: this.environment.production, storage: describeStorage(this.environment.storage) },
|
|
1681
1867
|
requestId,
|
|
1682
1868
|
log: this.logger,
|
|
@@ -1730,6 +1916,7 @@ export class FeltKitRuntime {
|
|
|
1730
1916
|
},
|
|
1731
1917
|
authority: this.#applicationAuthority(principal, requestId),
|
|
1732
1918
|
integrations: this.#integrationInvoker(principal),
|
|
1919
|
+
services: { files: explainServiceDenials(this.#services.bind(principal, requestId, new Set(), true), name, principal, this.#authority).files },
|
|
1733
1920
|
invocations: this.#invocationsApi(principal, null, { via: String(options.via ?? "function"), requestId }),
|
|
1734
1921
|
agent: {
|
|
1735
1922
|
catalog: async () => (await agent.tools(signedIn())).map((t) => ({
|
|
@@ -2067,6 +2254,7 @@ export class FeltKitRuntime {
|
|
|
2067
2254
|
// rescheduled for the services worker (of this process's successor).
|
|
2068
2255
|
await this.settleAgents();
|
|
2069
2256
|
await this.#appport?.close().catch(() => undefined);
|
|
2257
|
+
await this.providers.close();
|
|
2070
2258
|
await this.models.close();
|
|
2071
2259
|
await this.localAuthority.close().catch(() => undefined);
|
|
2072
2260
|
await this.activity.flush();
|
|
@@ -2134,6 +2322,12 @@ function toAppPortError(error) {
|
|
|
2134
2322
|
}
|
|
2135
2323
|
}
|
|
2136
2324
|
/** AppPort's replay key, computed exactly as AppPort scopes it (session, else principal). */
|
|
2325
|
+
const BUILTIN_CAPABILITY_NAMES = ["appport.manifest", "appport.ping"];
|
|
2326
|
+
function callerScope(appportPrincipal) {
|
|
2327
|
+
const principal = fromAppPortPrincipal(appportPrincipal);
|
|
2328
|
+
const named = appportPrincipal?.attributes?.feltkitOnBehalfOf;
|
|
2329
|
+
return { principal, onBehalfOf: typeof named === "string" ? named : null };
|
|
2330
|
+
}
|
|
2137
2331
|
function replayKey(context, exposure, principal) {
|
|
2138
2332
|
const scope = context.session?.id ?? (principal ? `principal:${principal.id}` : undefined);
|
|
2139
2333
|
return idempotencyStorageKey({ key: String(context.idempotencyKey), capability: exposure.name, version: exposure.version, ...(scope ? { sessionId: scope } : {}) });
|