@feltdb/feltkit 0.3.16 → 0.3.18
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 +222 -5
- package/dist/app.js +178 -3
- package/dist/app.js.map +1 -1
- package/dist/appboundry/build.d.ts +57 -0
- package/dist/appboundry/build.js +54 -2
- package/dist/appboundry/build.js.map +1 -1
- package/dist/appboundry/guest.js +73 -1
- package/dist/appboundry/guest.js.map +1 -1
- package/dist/appboundry/host.d.ts +15 -0
- package/dist/appboundry/host.js +45 -1
- package/dist/appboundry/host.js.map +1 -1
- package/dist/authorize.d.ts +3 -2
- package/dist/authorize.js +5 -3
- package/dist/authorize.js.map +1 -1
- package/dist/cli/deploy-appboundry-self-hosted.d.ts +2 -0
- package/dist/cli/deploy-appboundry-self-hosted.js +1 -1
- package/dist/cli/deploy-appboundry-self-hosted.js.map +1 -1
- package/dist/cli/deploy-appboundry.js +3 -0
- package/dist/cli/deploy-appboundry.js.map +1 -1
- package/dist/cli/main.js +6 -1
- package/dist/cli/main.js.map +1 -1
- package/dist/client/index.d.ts +242 -5
- package/dist/client/index.js +413 -29
- package/dist/client/index.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/event-stage.d.ts +13 -0
- package/dist/event-stage.js +15 -0
- package/dist/event-stage.js.map +1 -0
- package/dist/index.d.ts +5 -3
- package/dist/index.js.map +1 -1
- package/dist/react/auth.d.ts +131 -0
- package/dist/react/auth.js +830 -0
- package/dist/react/auth.js.map +1 -0
- package/dist/react/context.d.ts +8 -0
- package/dist/react/context.js +14 -0
- package/dist/react/context.js.map +1 -0
- package/dist/react/index.d.ts +17 -18
- package/dist/react/index.js +21 -13
- package/dist/react/index.js.map +1 -1
- package/dist/runtime/accounts.d.ts +33 -2
- package/dist/runtime/accounts.js +167 -27
- package/dist/runtime/accounts.js.map +1 -1
- package/dist/runtime/authority.d.ts +9 -1
- package/dist/runtime/authority.js +14 -2
- package/dist/runtime/authority.js.map +1 -1
- package/dist/runtime/challenges.d.ts +51 -0
- package/dist/runtime/challenges.js +121 -0
- package/dist/runtime/challenges.js.map +1 -0
- package/dist/runtime/changes.d.ts +22 -0
- package/dist/runtime/changes.js +51 -3
- package/dist/runtime/changes.js.map +1 -1
- package/dist/runtime/content.d.ts +32 -0
- package/dist/runtime/content.js +42 -1
- package/dist/runtime/content.js.map +1 -1
- package/dist/runtime/context.d.ts +50 -0
- package/dist/runtime/contract.js +14 -3
- package/dist/runtime/contract.js.map +1 -1
- package/dist/runtime/data.d.ts +36 -2
- package/dist/runtime/data.js +56 -17
- package/dist/runtime/data.js.map +1 -1
- package/dist/runtime/events.d.ts +21 -0
- package/dist/runtime/events.js +65 -0
- package/dist/runtime/events.js.map +1 -0
- package/dist/runtime/live.d.ts +48 -0
- package/dist/runtime/live.js +154 -0
- package/dist/runtime/live.js.map +1 -0
- package/dist/runtime/outbox.js +3 -0
- package/dist/runtime/outbox.js.map +1 -1
- package/dist/runtime/runtime.d.ts +70 -5
- package/dist/runtime/runtime.js +307 -36
- package/dist/runtime/runtime.js.map +1 -1
- package/dist/runtime/search.d.ts +54 -0
- package/dist/runtime/search.js +66 -0
- package/dist/runtime/search.js.map +1 -0
- package/dist/runtime/services.d.ts +45 -0
- package/dist/runtime/services.js +90 -0
- package/dist/runtime/services.js.map +1 -1
- package/dist/runtime/sessions.d.ts +16 -2
- package/dist/runtime/sessions.js +40 -4
- package/dist/runtime/sessions.js.map +1 -1
- package/dist/runtime/tenancy.d.ts +189 -0
- package/dist/runtime/tenancy.js +376 -0
- package/dist/runtime/tenancy.js.map +1 -0
- package/dist/runtime/tenant-scope.d.ts +9 -0
- package/dist/runtime/tenant-scope.js +127 -0
- package/dist/runtime/tenant-scope.js.map +1 -0
- package/dist/runtime/transactions.d.ts +45 -2
- package/dist/runtime/transactions.js +36 -9
- package/dist/runtime/transactions.js.map +1 -1
- package/dist/schema.d.ts +2 -1
- package/dist/schema.js +1 -1
- package/dist/schema.js.map +1 -1
- package/dist/server/http.d.ts +1 -0
- package/dist/server/http.js +14 -0
- package/dist/server/http.js.map +1 -1
- package/dist/server/index.d.ts +2 -1
- package/dist/server/index.js +325 -59
- package/dist/server/index.js.map +1 -1
- package/dist/server/mcp.js +6 -3
- package/dist/server/mcp.js.map +1 -1
- package/dist/server/session-http.d.ts +48 -0
- package/dist/server/session-http.js +116 -0
- package/dist/server/session-http.js.map +1 -0
- package/dist/server/tenancy.d.ts +40 -0
- package/dist/server/tenancy.js +191 -0
- package/dist/server/tenancy.js.map +1 -0
- package/dist/testing/index.d.ts +7 -0
- package/dist/testing/index.js +7 -2
- package/dist/testing/index.js.map +1 -1
- package/docs/AGENT-OPERATIONS.md +1 -0
- package/docs/APPBOUNDRY.md +11 -1
- package/docs/ARCHITECTURE.md +4 -2
- package/docs/AUTH.md +262 -0
- package/docs/GUARANTEES.md +58 -4
- package/docs/README.md +3 -2
- package/docs/SECURITY.md +3 -2
- package/docs/TRANSACTIONS.md +98 -1
- package/docs/UPSTREAM-GAPS.md +3 -0
- package/package.json +11 -9
- package/skills/.claude-plugin/marketplace.json +1 -1
- package/skills/.claude-plugin/plugin.json +1 -1
- package/skills/feltkit-data/SKILL.md +6 -0
- package/dist/runtime/account-links.d.ts +0 -19
- package/dist/runtime/account-links.js +0 -45
- package/dist/runtime/account-links.js.map +0 -1
package/dist/runtime/runtime.js
CHANGED
|
@@ -9,6 +9,7 @@
|
|
|
9
9
|
*/
|
|
10
10
|
import { checkTokenBytes } from "./crypto-token.js";
|
|
11
11
|
import { evaluateAuthorize } from "../authorize.js";
|
|
12
|
+
import { eventDefinitions, observationAuthorizer, stageEvent } from "./events.js";
|
|
12
13
|
import { AppPortError, createApplication, defineCapability, createMcpBridge, errors as appportErrors, idempotencyStorageKey } from "@appport/sdk";
|
|
13
14
|
import { grantsPermission } from "@appport/authorization";
|
|
14
15
|
import { AsyncLocalStorage } from "node:async_hooks";
|
|
@@ -16,6 +17,7 @@ import { performance } from "node:perf_hooks";
|
|
|
16
17
|
import { createHash, randomBytes, randomUUID } from "node:crypto";
|
|
17
18
|
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
18
19
|
import { dirname, join } from "node:path";
|
|
20
|
+
import { AGENT_MAX_BACKOFF_MS } from "../app.js";
|
|
19
21
|
import { IntegrationHost, integrationDescriptor } from "./integrations.js";
|
|
20
22
|
import { verifyStorage } from "./storage-check.js";
|
|
21
23
|
import { assertNotPartiallyRestored, writeBackup } from "./backup.js";
|
|
@@ -41,7 +43,9 @@ import { FeltDbSessionStore } from "./sessions.js";
|
|
|
41
43
|
import { AccountStore } from "./accounts.js";
|
|
42
44
|
import * as appportServices from "@appport/services";
|
|
43
45
|
import { accountMail } from "./mail.js";
|
|
44
|
-
import {
|
|
46
|
+
import { ChallengeStore } from "./challenges.js";
|
|
47
|
+
import { MEMBERSHIPS_COLLECTION, TenancyStore } from "./tenancy.js";
|
|
48
|
+
import { hasTenantCollections, scopeToTenant } from "./tenant-scope.js";
|
|
45
49
|
const consoleLogger = {
|
|
46
50
|
info: (m, f) => console.log(`[feltkit] ${m}`, f ?? ""),
|
|
47
51
|
warn: (m, f) => console.warn(`[feltkit] ${m}`, f ?? ""),
|
|
@@ -64,6 +68,10 @@ export class FeltKitRuntime {
|
|
|
64
68
|
sessions;
|
|
65
69
|
/** Built-in accounts (`auth.accounts`), or null when the app does not use them. */
|
|
66
70
|
accounts = null;
|
|
71
|
+
/** Account e-mail challenges (verify, reset, magic link, address change). Null without accounts. */
|
|
72
|
+
challenges = null;
|
|
73
|
+
/** Tenants, memberships and invitations (`auth.tenant`). Null without tenancy. */
|
|
74
|
+
tenancy = null;
|
|
67
75
|
/** Account e-mail (auth.accounts.email) through Mailerport, or null (none declared, or production without MAILPORT_URL). */
|
|
68
76
|
mail = null;
|
|
69
77
|
/** This server's own URL, set by the HTTP server: development's fallback for links. */
|
|
@@ -87,6 +95,8 @@ export class FeltKitRuntime {
|
|
|
87
95
|
#resolver;
|
|
88
96
|
#state = "starting";
|
|
89
97
|
#inflight = new Set();
|
|
98
|
+
/** Application agent runs started after a commit (app.agent), awaited by close() and settleAgents(). */
|
|
99
|
+
#agentRuns = new Set();
|
|
90
100
|
/** Set while backup() reads the state: calls and the services worker wait for it. */
|
|
91
101
|
#paused = null;
|
|
92
102
|
#dispatched = new Set();
|
|
@@ -337,6 +347,9 @@ export class FeltKitRuntime {
|
|
|
337
347
|
const authority = new Authority(app.name, app.options.roles ?? {});
|
|
338
348
|
const accounts = app.options.auth?.accounts;
|
|
339
349
|
this.accounts = accounts ? new AccountStore(this.instance.handle("feltkit.accounts"), accounts) : null;
|
|
350
|
+
this.challenges = accounts ? new ChallengeStore(this.instance.handle("feltkit.accounts"), () => this.authSecret()) : null;
|
|
351
|
+
const tenant = app.options.auth?.tenant;
|
|
352
|
+
this.tenancy = tenant ? new TenancyStore(this.instance.handle("feltkit.tenancy"), tenant, () => this.authSecret()) : null;
|
|
340
353
|
this.mail = accounts?.email ? accountMail({ env: this.#env, development: !this.environment.production, from: accounts.email.from, identity: accounts.email.identity ?? "auth", logger: this.logger }) : null;
|
|
341
354
|
const config = app.options.services ?? {};
|
|
342
355
|
const store = this.accounts;
|
|
@@ -346,15 +359,38 @@ export class FeltKitRuntime {
|
|
|
346
359
|
new (emailChannelClass())({
|
|
347
360
|
transport: mail.transport,
|
|
348
361
|
identity: accounts.email.identity ?? "auth",
|
|
349
|
-
address
|
|
362
|
+
// An account's address, or (magic link for a new address, address change) the address itself.
|
|
363
|
+
address: async (n) => (n.recipient.startsWith("email:") ? n.recipient.slice(6) : (await store.get(n.recipient))?.email ?? null),
|
|
364
|
+
// Rendered when delivered, from the live challenge: the link and code are never stored.
|
|
350
365
|
render: async (n) => {
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
366
|
+
// A workspace invitation (auth.tenant): rendered from the live invitation, so a
|
|
367
|
+
// withdrawn or accepted one sends nothing, and its token is never stored.
|
|
368
|
+
if (typeof n.data?.invitation === "string") {
|
|
369
|
+
const live = this.tenancy ? await this.tenancy.tokenFor(n.data.invitation) : null;
|
|
370
|
+
if (!live)
|
|
371
|
+
return null;
|
|
372
|
+
const input = {
|
|
373
|
+
app: app.options.description ?? app.name,
|
|
374
|
+
link: this.invitationLink(live.token),
|
|
375
|
+
tenant: live.tenantName,
|
|
376
|
+
role: live.invitation.role,
|
|
377
|
+
inviter: live.invitation.inviterName ?? "",
|
|
378
|
+
word: app.options.auth?.tenant?.name ?? "workspace",
|
|
379
|
+
expiresInDays: Math.max(1, Math.round((Date.parse(live.invitation.expiresAt) - Date.now()) / 86_400_000)),
|
|
380
|
+
};
|
|
381
|
+
const template = accounts.email.templates?.invitation;
|
|
382
|
+
return template ? template(input) : invitationMessage(input);
|
|
383
|
+
}
|
|
384
|
+
const id = n.data?.challenge;
|
|
385
|
+
if (typeof id !== "string" || !this.challenges)
|
|
356
386
|
return null;
|
|
357
|
-
|
|
387
|
+
const live = await this.challenges.secretsFor(id);
|
|
388
|
+
if (!live)
|
|
389
|
+
return null; // used, superseded or expired before delivery: send nothing
|
|
390
|
+
const link = `${this.publicUrl()}/#feltkit-${live.purpose}=${live.token}`;
|
|
391
|
+
const input = { app: app.options.description ?? app.name, link, code: live.code, email: live.data.email ?? "", expiresInMinutes: Math.max(1, Math.round((live.expiresAt - Date.now()) / 60_000)) };
|
|
392
|
+
const template = accounts.email.templates?.[live.purpose];
|
|
393
|
+
return template ? template(input) : accountMessage(live.purpose, input);
|
|
358
394
|
},
|
|
359
395
|
}),
|
|
360
396
|
]
|
|
@@ -389,7 +425,9 @@ export class FeltKitRuntime {
|
|
|
389
425
|
const appport = createApplication({
|
|
390
426
|
application: { id: app.name, name: app.name, version: app.version, ...(app.options.description ? { description: app.options.description } : {}) },
|
|
391
427
|
capabilities,
|
|
392
|
-
|
|
428
|
+
// app.event(): AppPort events; observation is authorized by roles, then feltkit({ authorize }).
|
|
429
|
+
events: eventDefinitions(app),
|
|
430
|
+
authorizer: observationAuthorizer(app, authority.authorizer, () => new Reader(this.instance.handle("app"), new CollectionResolver(app.collections))),
|
|
393
431
|
db: this.instance.handle("appport"),
|
|
394
432
|
sessions: this.sessions,
|
|
395
433
|
// Durable replay protection for capabilities that declare idempotency: the claim is
|
|
@@ -405,6 +443,13 @@ export class FeltKitRuntime {
|
|
|
405
443
|
const original = appport[method].bind(appport);
|
|
406
444
|
appport[method] = (request, options = {}) => this.#appportCaller.run({ principal: fromAppPortPrincipal(options?.principal ?? options?.session?.principal) }, () => original(request, options));
|
|
407
445
|
}
|
|
446
|
+
// AppPort's HTTP event stream names every subscription `sub_sse_<index>`, and the application's
|
|
447
|
+
// event bus keys subscriptions by that id across connections: a second client's subscription
|
|
448
|
+
// replaces the first's, which then stops receiving events (docs/UPSTREAM-GAPS.md A10). Each
|
|
449
|
+
// subscription gets a bus id of its own; the connection still echoes the client's id on delivery.
|
|
450
|
+
let busSubscriptions = 0;
|
|
451
|
+
const subscribe = appport.subscribe.bind(appport);
|
|
452
|
+
appport.subscribe = (filter, listener, id) => subscribe(filter, listener, id === undefined ? id : `${id}#${++busSubscriptions}`);
|
|
408
453
|
this.#project = project;
|
|
409
454
|
this.#authority = authority;
|
|
410
455
|
this.#services = services;
|
|
@@ -555,7 +600,32 @@ export class FeltKitRuntime {
|
|
|
555
600
|
return key ? { id: key.principalId, type: "service", roles: [...this.#services.apiKeyRoles], displayName: `API key ${key.principalId.slice(0, 8)}` } : null;
|
|
556
601
|
}
|
|
557
602
|
const session = await this.sessions.get(token);
|
|
558
|
-
|
|
603
|
+
let principal = fromAppPortPrincipal(session?.principal);
|
|
604
|
+
if (!principal)
|
|
605
|
+
return null;
|
|
606
|
+
const attributes = (session?.attributes ?? {});
|
|
607
|
+
// An account session is resolved again on every request: the account as it is now (a
|
|
608
|
+
// disabled or deleted account has no session; changed roles apply at once), never the copy
|
|
609
|
+
// taken at sign-in. Dev, CLI and agent sessions carry the roles their issuer gave them.
|
|
610
|
+
if (attributes.kind === "account") {
|
|
611
|
+
const account = this.accounts ? await this.accounts.get(principal.id) : null;
|
|
612
|
+
if (!account || account.disabled)
|
|
613
|
+
return null;
|
|
614
|
+
principal = { ...principal, roles: [...account.roles], displayName: account.name ?? account.email };
|
|
615
|
+
}
|
|
616
|
+
return this.withTenant(principal, typeof attributes.tenantId === "string" ? attributes.tenantId : undefined);
|
|
617
|
+
}
|
|
618
|
+
/**
|
|
619
|
+
* The principal working in a tenant: the live membership's role joins its roles, and its claims
|
|
620
|
+
* come along. No active membership (removed, or never a member) means no tenant and no tenant role.
|
|
621
|
+
*/
|
|
622
|
+
async withTenant(principal, tenantId) {
|
|
623
|
+
if (!this.tenancy || !tenantId)
|
|
624
|
+
return principal;
|
|
625
|
+
const tenant = await this.tenancy.context(tenantId, principal.id);
|
|
626
|
+
if (!tenant)
|
|
627
|
+
return principal;
|
|
628
|
+
return { ...principal, roles: [...new Set([...principal.roles, tenant.role])], tenant };
|
|
559
629
|
}
|
|
560
630
|
/**
|
|
561
631
|
* The principal behind durable service work, as it is now: an API key that still
|
|
@@ -597,6 +667,8 @@ export class FeltKitRuntime {
|
|
|
597
667
|
* the log.
|
|
598
668
|
*/
|
|
599
669
|
async #performOutbox(record, services, principal, requestId) {
|
|
670
|
+
if (record.effect.service === "agent")
|
|
671
|
+
return this.#runAgent(record.id);
|
|
600
672
|
return performOutbox(outboxStore(this.instance.handle("app")), record.id, (claim, complete) => {
|
|
601
673
|
const effect = claim.effect;
|
|
602
674
|
// A job or webhook event is created in the transaction that records it done; a notification is sent directly.
|
|
@@ -616,9 +688,16 @@ export class FeltKitRuntime {
|
|
|
616
688
|
const store = this.instance.handle("app");
|
|
617
689
|
const outbox = store.collection(OUTBOX_COLLECTION);
|
|
618
690
|
const read = async (state) => (await readAll(store, { collection: OUTBOX_COLLECTION, where: [{ field: "state", eq: state }] }));
|
|
619
|
-
const
|
|
691
|
+
const lease = (r) => (r.effect.service === "agent" ? this.app.agents.get(r.effect.agent)?.leaseMs : undefined);
|
|
692
|
+
const stale = [...(await read("pending")), ...(await read("performing"))].filter((r) => isRecoverable(r, now, lease(r)));
|
|
620
693
|
let performed = 0;
|
|
621
694
|
for (const record of stale) {
|
|
695
|
+
// An application agent runs as itself: the caller is not resolved (nor needed).
|
|
696
|
+
if (record.effect.service === "agent") {
|
|
697
|
+
if ((await this.#runAgent(record.id)) === "done")
|
|
698
|
+
performed += 1;
|
|
699
|
+
continue;
|
|
700
|
+
}
|
|
622
701
|
const principal = await this.#resolveDurable(record.principalId);
|
|
623
702
|
if (!principal) {
|
|
624
703
|
await store
|
|
@@ -665,6 +744,11 @@ export class FeltKitRuntime {
|
|
|
665
744
|
catch {
|
|
666
745
|
throw new FeltKitError("CONFLICT", `After-commit effect ${id} changed while it was being retried. Nothing was changed; read it again.`);
|
|
667
746
|
}
|
|
747
|
+
if (record.effect.service === "agent") {
|
|
748
|
+
await this.#runAgent(id);
|
|
749
|
+
const { __version: _a, ...after } = (await outbox.get(id));
|
|
750
|
+
return after;
|
|
751
|
+
}
|
|
668
752
|
const principal = await this.#resolveDurable(record.principalId);
|
|
669
753
|
if (principal) {
|
|
670
754
|
const requestId = `outbox_${id}_retry`;
|
|
@@ -680,6 +764,72 @@ export class FeltKitRuntime {
|
|
|
680
764
|
const { __version: _v, ...after } = (await outbox.get(id));
|
|
681
765
|
return after;
|
|
682
766
|
}
|
|
767
|
+
/**
|
|
768
|
+
* The outbox effect that runs application agent `name` (`ctx.afterCommit.agent`, or an event in
|
|
769
|
+
* its `on`). It records the tenant the caller worked in; whether the agent may work there is
|
|
770
|
+
* decided when it runs, from the agent's own membership.
|
|
771
|
+
*/
|
|
772
|
+
#agentEffect(name, input, principal, event) {
|
|
773
|
+
if (!this.app.agents.has(name))
|
|
774
|
+
throw new FeltKitError("INVALID_ARGUMENT", `No application agent named "${name}".`, { hint: `Declare it with app.agent("${name}", { principal, roles, handler }).` });
|
|
775
|
+
return { service: "agent", method: "run", agent: name, input, ...(principal?.tenant ? { tenantId: principal.tenant.id } : {}), ...(event ? { event } : {}) };
|
|
776
|
+
}
|
|
777
|
+
/** Start an agent run now, without making the triggering call wait for it. */
|
|
778
|
+
#dispatchAgent(id) {
|
|
779
|
+
const run = this.#runAgent(id).catch((error) => this.logger.warn(`agent run ${id}: ${error.message}`));
|
|
780
|
+
this.#agentRuns.add(run);
|
|
781
|
+
void run.finally(() => this.#agentRuns.delete(run));
|
|
782
|
+
}
|
|
783
|
+
/** Wait for the agent runs started so far (and any they start) to finish their current attempt. */
|
|
784
|
+
async settleAgents() {
|
|
785
|
+
while (this.#agentRuns.size)
|
|
786
|
+
await Promise.allSettled([...this.#agentRuns]);
|
|
787
|
+
}
|
|
788
|
+
/**
|
|
789
|
+
* One attempt of an application agent's run (an outbox record, `effect.service === "agent"`),
|
|
790
|
+
* through the shared performer: claim (version-checked: one performer at a time; a claim older
|
|
791
|
+
* than the agent's lease is taken over), run the handler as the agent through call() (roles,
|
|
792
|
+
* access, authorize hook, activity), then done, rescheduled with backoff, or failed. The run's
|
|
793
|
+
* writes commit under a transaction id derived from the record, so a run repeated after an
|
|
794
|
+
* unrecorded success writes nothing again.
|
|
795
|
+
*/
|
|
796
|
+
#runAgent(id) {
|
|
797
|
+
const terminal = new Set(["UNAUTHORIZED", "FORBIDDEN", "INVALID_ARGUMENT", "NOT_FOUND", "FUNCTION_NOT_FOUND"]);
|
|
798
|
+
return performOutbox(outboxStore(this.instance.handle("app")), id, async (claim) => {
|
|
799
|
+
const effect = claim.effect;
|
|
800
|
+
const definition = this.app.agents.get(effect.agent);
|
|
801
|
+
if (!definition)
|
|
802
|
+
throw new FeltKitError("FUNCTION_NOT_FOUND", `Application agent "${effect.agent}" is no longer declared.`);
|
|
803
|
+
if (claim.attempts > definition.retry.maxAttempts && !claim.retriedBy)
|
|
804
|
+
throw new FeltKitError("FAILED_PRECONDITION", `Agent run abandoned: its claim expired ${claim.attempts - 1} times (lease ${definition.leaseMs} ms).`);
|
|
805
|
+
// The agent's own identity and roles; a tenant only through its own active membership.
|
|
806
|
+
const principal = await this.withTenant({ id: definition.principal.id, type: "agent", roles: [...definition.roles], ...(definition.principal.displayName ? { displayName: definition.principal.displayName } : {}) }, effect.tenantId);
|
|
807
|
+
const trigger = Object.freeze({
|
|
808
|
+
agent: definition.name,
|
|
809
|
+
idempotencyKey: claim.id,
|
|
810
|
+
attempt: claim.attempts,
|
|
811
|
+
by: Object.freeze({ principalId: claim.principalId, function: claim.function, requestId: claim.requestId }),
|
|
812
|
+
...(effect.event ? { event: effect.event } : {}),
|
|
813
|
+
...(effect.tenantId ? { requestedTenantId: effect.tenantId } : {}),
|
|
814
|
+
});
|
|
815
|
+
const requestId = `agent_${claim.id}_${claim.attempts}`;
|
|
816
|
+
const result = await this.call(`agent/${definition.name}`, effect.input ?? {}, { principal, via: "agent", requestId, idempotencyReplayKey: `agent:${claim.id}`, agentRun: { definition, trigger } });
|
|
817
|
+
if (result.ok)
|
|
818
|
+
return { requestId, ...(principal.tenant ? { tenantId: principal.tenant.id } : {}) };
|
|
819
|
+
// An earlier attempt committed (its done mark was lost): the run happened, once.
|
|
820
|
+
if (result.error.code === "OUTCOME_UNKNOWN" && result.error.details?.committed === true)
|
|
821
|
+
return { requestId, committedEarlier: true };
|
|
822
|
+
throw Object.assign(new FeltKitError(result.error.code, result.error.message), { requestId });
|
|
823
|
+
}, {
|
|
824
|
+
warn: (message) => this.logger.warn(message, { outboxId: id }),
|
|
825
|
+
retryAt: (claim, error) => {
|
|
826
|
+
const definition = claim.effect.service === "agent" ? this.app.agents.get(claim.effect.agent) : undefined;
|
|
827
|
+
if (!definition || terminal.has(error.code) || claim.attempts >= definition.retry.maxAttempts)
|
|
828
|
+
return null;
|
|
829
|
+
return Date.now() + Math.min(definition.retry.backoffMs * 2 ** Math.max(0, claim.attempts - 1), AGENT_MAX_BACKOFF_MS);
|
|
830
|
+
},
|
|
831
|
+
});
|
|
832
|
+
}
|
|
683
833
|
/** Drive durable service work once (jobs, schedules, webhook deliveries, recovered after-commit effects). */
|
|
684
834
|
runServices() {
|
|
685
835
|
if (this.#state !== "ready" || this.#paused)
|
|
@@ -771,9 +921,41 @@ export class FeltKitRuntime {
|
|
|
771
921
|
hint: "`npx feltkit vercel env` sets it from the recorded deployment.",
|
|
772
922
|
});
|
|
773
923
|
}
|
|
774
|
-
/**
|
|
775
|
-
|
|
776
|
-
|
|
924
|
+
/**
|
|
925
|
+
* Issue an account e-mail challenge and send it through AppPort Services' notifications (and
|
|
926
|
+
* Mailerport). Returns false when nothing was sent (no account e-mail, or the subject's hourly
|
|
927
|
+
* limit was reached); callers answer the same either way.
|
|
928
|
+
*/
|
|
929
|
+
/** The link that accepts an invitation: on the app's public URL (relative when that is not configured). */
|
|
930
|
+
invitationLink(token) {
|
|
931
|
+
let origin = "";
|
|
932
|
+
try {
|
|
933
|
+
origin = this.publicUrl();
|
|
934
|
+
}
|
|
935
|
+
catch {
|
|
936
|
+
origin = "";
|
|
937
|
+
}
|
|
938
|
+
return `${origin}/#feltkit-invitation=${token}`;
|
|
939
|
+
}
|
|
940
|
+
/** E-mail a workspace invitation (when the app sends account e-mail). False when nothing was sent. */
|
|
941
|
+
async sendInvitation(invitationId, email) {
|
|
942
|
+
if (!this.mail || !this.tenancy)
|
|
943
|
+
return false;
|
|
944
|
+
const live = await this.tenancy.tokenFor(invitationId);
|
|
945
|
+
if (!live)
|
|
946
|
+
return false;
|
|
947
|
+
await this.services.sendAccountMail({ recipient: `email:${email}`, type: "account.invitation", title: `Join ${live.tenantName}`, data: { invitation: invitationId }, expiresAt: live.invitation.expiresAt });
|
|
948
|
+
return true;
|
|
949
|
+
}
|
|
950
|
+
async sendChallenge(input) {
|
|
951
|
+
if (!this.challenges || !this.mail)
|
|
952
|
+
return false;
|
|
953
|
+
const challenge = await this.challenges.issue({ purpose: input.purpose, subject: input.subject, ...(input.data ? { data: input.data } : {}) });
|
|
954
|
+
if (!challenge)
|
|
955
|
+
return false;
|
|
956
|
+
const titles = { verify: "Verify your e-mail address", reset: "Reset your password", "magic-link": "Your sign-in link", "email-change": "Confirm your new e-mail address" };
|
|
957
|
+
await this.services.sendAccountMail({ recipient: input.recipient, type: `account.${input.purpose}`, title: titles[input.purpose], data: { purpose: input.purpose, challenge: challenge.id }, expiresAt: new Date(challenge.expiresAt).toISOString() });
|
|
958
|
+
return true;
|
|
777
959
|
}
|
|
778
960
|
/**
|
|
779
961
|
* The key that signs account links and sign-in provider state: FELTKIT_AUTH_SECRET, else
|
|
@@ -805,6 +987,11 @@ export class FeltKitRuntime {
|
|
|
805
987
|
/** Issue a session. Development sign-in, the CLI, and auth hooks all come through here. */
|
|
806
988
|
async issueSession(input, options) {
|
|
807
989
|
const principal = normalizePrincipal(input);
|
|
990
|
+
// A person's session starts in the tenant they used last (an explicit tenantId, or null for none, wins).
|
|
991
|
+
let tenantId = options.tenantId === undefined ? undefined : options.tenantId ?? undefined;
|
|
992
|
+
if (options.tenantId === undefined && this.tenancy && (options.kind === "account" || options.kind === "dev")) {
|
|
993
|
+
tenantId = (await this.tenancy.tenantsFor(principal.id))[0]?.id;
|
|
994
|
+
}
|
|
808
995
|
for (const role of principal.roles) {
|
|
809
996
|
if (!this.#authority.roles[role])
|
|
810
997
|
throw new FeltKitError("INVALID_ARGUMENT", `Unknown role "${role}". Declared roles: ${Object.keys(this.#authority.roles).join(", ") || "(none)"}.`);
|
|
@@ -812,6 +999,7 @@ export class FeltKitRuntime {
|
|
|
812
999
|
const session = await this.sessions.issue(this.app.name, principal, {
|
|
813
1000
|
kind: options.kind,
|
|
814
1001
|
...(options.label ? { label: options.label } : {}),
|
|
1002
|
+
...(tenantId ? { tenantId } : {}),
|
|
815
1003
|
...(options.ttlMs !== undefined ? { ttlMs: options.ttlMs } : this.app.options.auth?.sessionTtlMs ? { ttlMs: this.app.options.auth.sessionTtlMs } : {}),
|
|
816
1004
|
});
|
|
817
1005
|
this.activity.record({
|
|
@@ -822,9 +1010,31 @@ export class FeltKitRuntime {
|
|
|
822
1010
|
principal: options.actor ? pick(options.actor) : pick(principal),
|
|
823
1011
|
outcome: "success",
|
|
824
1012
|
durationMs: 0,
|
|
825
|
-
detail: { subject: principal.id, roles: principal.roles, kind: options.kind, ...(session.expiresAt ? { expiresAt: session.expiresAt } : {}) },
|
|
1013
|
+
detail: { subject: principal.id, roles: principal.roles, kind: options.kind, ...(tenantId ? { tenantId } : {}), ...(session.expiresAt ? { expiresAt: session.expiresAt } : {}) },
|
|
826
1014
|
});
|
|
827
|
-
return { token: session.id, principal, expiresAt: session.expiresAt };
|
|
1015
|
+
return { token: session.id, principal: await this.withTenant(principal, tenantId), expiresAt: session.expiresAt };
|
|
1016
|
+
}
|
|
1017
|
+
/**
|
|
1018
|
+
* An agent or service identity this app knows: one holding an active session (operator-issued:
|
|
1019
|
+
* `feltkit session create --type agent`), an application agent the app declares (`app.agent`), or a
|
|
1020
|
+
* declared development agent in development. Null for people (they join tenants by invitation) and
|
|
1021
|
+
* for unknown ids.
|
|
1022
|
+
*/
|
|
1023
|
+
async knownNonPersonPrincipal(id) {
|
|
1024
|
+
if (!id || id.startsWith("acct_"))
|
|
1025
|
+
return null;
|
|
1026
|
+
const declared = [...this.app.agents.values()].find((a) => a.principal.id === id);
|
|
1027
|
+
if (declared)
|
|
1028
|
+
return { id, type: "agent", ...(declared.principal.displayName ? { displayName: declared.principal.displayName } : {}) };
|
|
1029
|
+
const dev = this.environment.development ? this.app.options.dev?.users?.find((u) => u.id === id && (u.type === "agent" || u.type === "service")) : undefined;
|
|
1030
|
+
if (dev)
|
|
1031
|
+
return { id: dev.id, type: dev.type, ...(dev.name ? { displayName: dev.name } : {}) };
|
|
1032
|
+
const active = (await this.sessions.list()).find((s) => s.principal?.id === id && (s.principal.type === "agent" || s.principal.type === "service"));
|
|
1033
|
+
return active?.principal ? { id, type: active.principal.type, ...(active.principal.displayName ? { displayName: active.principal.displayName } : {}) } : null;
|
|
1034
|
+
}
|
|
1035
|
+
/** Record an authentication event (sign-in failures, revocations, membership changes) in the activity log. */
|
|
1036
|
+
recordAuth(name, principal, detail, outcome = "success", via = "http") {
|
|
1037
|
+
this.activity.record({ kind: "auth", name, via, requestId: `req_${randomUUID()}`, principal: principal ? pick(principal) : null, outcome, durationMs: 0, detail });
|
|
828
1038
|
}
|
|
829
1039
|
/** Run a query or mutation as `principal`. Authority is checked before the handler runs. */
|
|
830
1040
|
call(name, rawArgs, options) {
|
|
@@ -837,7 +1047,8 @@ export class FeltKitRuntime {
|
|
|
837
1047
|
const started = performance.now();
|
|
838
1048
|
const requestId = options.requestId ?? `req_${randomUUID()}`;
|
|
839
1049
|
const principal = options.principal;
|
|
840
|
-
|
|
1050
|
+
// An application agent's handler is reachable only from its run, never by name from outside.
|
|
1051
|
+
const fn = options.agentRun ? options.agentRun.definition.function : this.#project?.functions.get(name);
|
|
841
1052
|
const kind = options.capability ? "capability" : fn?.kind ?? "query";
|
|
842
1053
|
const base = {
|
|
843
1054
|
kind,
|
|
@@ -847,8 +1058,11 @@ export class FeltKitRuntime {
|
|
|
847
1058
|
principal: principal ? pick(principal) : null,
|
|
848
1059
|
...(options.capability ? { capability: options.capability } : {}),
|
|
849
1060
|
};
|
|
1061
|
+
const run = options.agentRun?.trigger;
|
|
1062
|
+
const agentDetail = run ? { agentRun: { agent: run.agent, idempotencyKey: run.idempotencyKey, attempt: run.attempt, triggeredBy: run.by.principalId, triggeredFrom: run.by.function, ...(run.event ? { event: run.event } : {}) } } : undefined;
|
|
850
1063
|
const finish = (entry) => {
|
|
851
|
-
|
|
1064
|
+
const detail = agentDetail || entry.detail ? { ...agentDetail, ...entry.detail } : undefined;
|
|
1065
|
+
this.activity.record({ ...base, durationMs: Math.round(performance.now() - started), ...entry, ...(detail ? { detail } : {}) });
|
|
852
1066
|
};
|
|
853
1067
|
const failure = (error, extra = {}) => {
|
|
854
1068
|
const json = this.#errorJSON(error, requestId);
|
|
@@ -918,6 +1132,17 @@ export class FeltKitRuntime {
|
|
|
918
1132
|
const used = new Set();
|
|
919
1133
|
const shared = {
|
|
920
1134
|
auth: authContext(this.#authority, principal),
|
|
1135
|
+
tenancy: {
|
|
1136
|
+
members: async () => {
|
|
1137
|
+
if (!this.tenancy)
|
|
1138
|
+
throw new FeltKitError("CONFIGURATION", "This app has no tenants (auth.tenant).");
|
|
1139
|
+
db.reads.add(MEMBERSHIPS_COLLECTION); // re-run live queries when memberships change
|
|
1140
|
+
const tenantId = principal?.tenant?.id;
|
|
1141
|
+
if (!tenantId)
|
|
1142
|
+
return [];
|
|
1143
|
+
return (await this.tenancy.members(tenantId)).map((m) => ({ principalId: m.principalId, type: m.principalType, role: m.role, claims: m.claims, ...(m.displayName ? { displayName: m.displayName } : {}), ...(m.email ? { email: m.email } : {}) }));
|
|
1144
|
+
},
|
|
1145
|
+
},
|
|
921
1146
|
services: explainServiceDenials(this.#services.bind(principal, requestId, db.reads, fn.kind === "mutation", used), name, principal, this.#authority),
|
|
922
1147
|
environment: { name: this.environment.name, production: this.environment.production, storage: describeStorage(this.environment.storage) },
|
|
923
1148
|
requestId,
|
|
@@ -945,13 +1170,37 @@ export class FeltKitRuntime {
|
|
|
945
1170
|
enabled: { notifications: Boolean(enabled.notifications), webhooks: Boolean(enabled.webhooks), jobs: Boolean(enabled.jobs) },
|
|
946
1171
|
stage: (record) => db.stageSystem(OUTBOX_COLLECTION, record),
|
|
947
1172
|
newId: newOutboxId,
|
|
1173
|
+
agent: (agentName, input) => this.#agentEffect(agentName, input, principal, triggeringEvent),
|
|
948
1174
|
})
|
|
949
1175
|
: null;
|
|
950
|
-
|
|
1176
|
+
// ctx.events: validated now, published only after the commit (below); never stored. An
|
|
1177
|
+
// application agent whose `on` names the event is recorded now, in this transaction.
|
|
1178
|
+
const published = [];
|
|
1179
|
+
let triggeringEvent;
|
|
1180
|
+
const events = {
|
|
1181
|
+
publish: (event, payload, options = {}) => {
|
|
1182
|
+
const staged = stageEvent(this.app, event, payload, options);
|
|
1183
|
+
published.push(staged);
|
|
1184
|
+
for (const definition of this.app.agents.values()) {
|
|
1185
|
+
if (!definition.on.includes(staged.name))
|
|
1186
|
+
continue;
|
|
1187
|
+
triggeringEvent = staged.name;
|
|
1188
|
+
try {
|
|
1189
|
+
effects.agent(definition.name, { event: staged.name, payload: staged.payload, ...(staged.scope !== undefined ? { scope: staged.scope } : {}) });
|
|
1190
|
+
}
|
|
1191
|
+
finally {
|
|
1192
|
+
triggeringEvent = undefined;
|
|
1193
|
+
}
|
|
1194
|
+
}
|
|
1195
|
+
},
|
|
1196
|
+
};
|
|
1197
|
+
// Tenant-scoped collections see only the caller's tenant (the session's, never the request's).
|
|
1198
|
+
const scoped = hasTenantCollections(this.app.collections.values()) ? scopeToTenant(db, (ref) => this.#resolver.resolve(ref), principal?.tenant?.id ?? null) : db;
|
|
1199
|
+
const ctx = fn.kind === "mutation" ? { ...shared, db: scoped, agent, events, afterCommit: effects, unsafe: { feltdb: this.instance.handle("app.unsafe") }, ...(options.agentRun ? { trigger: options.agentRun.trigger } : {}) } : { ...shared, db: scoped };
|
|
951
1200
|
try {
|
|
952
1201
|
// feltkit({ authorize }): after roles and validation, with this call's own reader, so its
|
|
953
1202
|
// reads are fenced at commit (mutations) and tracked for live queries (queries).
|
|
954
|
-
await this.#authorizeResource(name, fn, args, principal, options, requestId,
|
|
1203
|
+
await this.#authorizeResource(name, fn, args, principal, options, requestId, scoped, authorityRecord);
|
|
955
1204
|
const value = await fn.handler(ctx, args);
|
|
956
1205
|
if (fn.returns) {
|
|
957
1206
|
const output = validate(fn.returns, value);
|
|
@@ -965,7 +1214,7 @@ export class FeltKitRuntime {
|
|
|
965
1214
|
keyed: options.idempotencyReplayKey !== undefined,
|
|
966
1215
|
});
|
|
967
1216
|
}
|
|
968
|
-
return { value, db, commit, starts, used };
|
|
1217
|
+
return { value, db, commit, starts, used, published };
|
|
969
1218
|
}
|
|
970
1219
|
catch (error) {
|
|
971
1220
|
throw Object.assign(new AttemptFailed(error), { db, used });
|
|
@@ -993,21 +1242,31 @@ export class FeltKitRuntime {
|
|
|
993
1242
|
}
|
|
994
1243
|
throw error;
|
|
995
1244
|
}
|
|
996
|
-
const { value, db, commit, starts } = outcome;
|
|
1245
|
+
const { value, db, commit, starts, published } = outcome;
|
|
997
1246
|
reads = [...db.reads];
|
|
998
1247
|
if (db instanceof Writer && commit) {
|
|
999
|
-
if (commit.writes.length)
|
|
1248
|
+
if (commit.writes.length) {
|
|
1249
|
+
this.changes.describe(commit.described);
|
|
1000
1250
|
void this.changes.check();
|
|
1251
|
+
}
|
|
1001
1252
|
// Agent work starts only once the mutation's writes are durable.
|
|
1002
1253
|
for (const start of starts)
|
|
1003
1254
|
this.#agent?.startAfterCommit(start, principal);
|
|
1004
1255
|
// So do after-commit effects: performed now, as the caller, while its binding is live.
|
|
1005
1256
|
const outbox = db.staged.filter((r) => r.collection === OUTBOX_COLLECTION).map((r) => r.value);
|
|
1006
|
-
|
|
1257
|
+
// Application agents run as themselves, without holding up this call (or its services binding).
|
|
1258
|
+
for (const record of outbox)
|
|
1259
|
+
if (record.effect.service === "agent")
|
|
1260
|
+
this.#dispatchAgent(record.id);
|
|
1261
|
+
const effects = outbox.filter((record) => record.effect.service !== "agent");
|
|
1262
|
+
if (effects.length) {
|
|
1007
1263
|
const bound = explainServiceDenials(this.#services.bind(principal, requestId, new Set(), true, servicesUsed), name, principal, this.#authority);
|
|
1008
|
-
for (const record of
|
|
1264
|
+
for (const record of effects)
|
|
1009
1265
|
await this.#performOutbox(record, bound, principal, requestId);
|
|
1010
1266
|
}
|
|
1267
|
+
// Ephemeral events: at most once, to whoever is subscribed now (AppPort's event bus).
|
|
1268
|
+
for (const event of published)
|
|
1269
|
+
await this.#appport.emit({ name: event.name, version: 1, payload: event.payload, ...(event.scope !== undefined ? { scope: event.scope } : {}) }).catch((error) => this.logger.warn(`event ${event.name} was not published: ${error.message}`));
|
|
1011
1270
|
}
|
|
1012
1271
|
finish({
|
|
1013
1272
|
outcome: "success",
|
|
@@ -1025,7 +1284,8 @@ export class FeltKitRuntime {
|
|
|
1025
1284
|
}
|
|
1026
1285
|
: {}),
|
|
1027
1286
|
});
|
|
1028
|
-
|
|
1287
|
+
// `reads` for the caller: collection names, then `collection#key` per equality predicate (runtime/live.ts).
|
|
1288
|
+
return { ok: true, value: value === undefined ? null : value, reads: db.reads.report(), requestId };
|
|
1029
1289
|
}
|
|
1030
1290
|
}
|
|
1031
1291
|
catch (error) {
|
|
@@ -1147,6 +1407,9 @@ export class FeltKitRuntime {
|
|
|
1147
1407
|
clearInterval(this.#worker);
|
|
1148
1408
|
this.changes.stop();
|
|
1149
1409
|
await Promise.allSettled([...this.#inflight]);
|
|
1410
|
+
// Agent runs started before the close: their calls now answer UNAVAILABLE, so each is
|
|
1411
|
+
// rescheduled for the services worker (of this process's successor).
|
|
1412
|
+
await this.settleAgents();
|
|
1150
1413
|
await this.#appport?.close().catch(() => undefined);
|
|
1151
1414
|
await this.models.close();
|
|
1152
1415
|
await this.activity.flush();
|
|
@@ -1218,19 +1481,27 @@ function replayKey(context, exposure, principal) {
|
|
|
1218
1481
|
function idempotentTransactionId(replayKey) {
|
|
1219
1482
|
return `idem_${createHash("sha256").update(replayKey).digest("hex")}`;
|
|
1220
1483
|
}
|
|
1221
|
-
|
|
1222
|
-
|
|
1223
|
-
if (purpose === "reset") {
|
|
1224
|
-
return {
|
|
1225
|
-
subject: `Reset your ${appName} password`,
|
|
1226
|
-
text: `Someone asked to reset the password for your ${appName} account.\n\nSet a new password (the link works once, for an hour):\n${link}\n\nIf it was not you, ignore this e-mail; your password has not changed.`,
|
|
1227
|
-
};
|
|
1228
|
-
}
|
|
1484
|
+
function invitationMessage(input) {
|
|
1485
|
+
const who = input.inviter ? `${input.inviter} invited you` : "You are invited";
|
|
1229
1486
|
return {
|
|
1230
|
-
subject:
|
|
1231
|
-
text:
|
|
1487
|
+
subject: `${who} to join ${input.tenant} on ${input.app}`,
|
|
1488
|
+
text: `${who} to join the ${input.word} "${input.tenant}" on ${input.app} as ${input.role}.\n\nAccept the invitation (it works once, for ${input.expiresInDays} day${input.expiresInDays === 1 ? "" : "s"}):\n${input.link}\n\nIf you did not expect this, ignore this e-mail.`,
|
|
1232
1489
|
};
|
|
1233
1490
|
}
|
|
1491
|
+
/** The default text of an account e-mail. */
|
|
1492
|
+
function accountMessage(purpose, input) {
|
|
1493
|
+
const { app, link, code, expiresInMinutes: minutes } = input;
|
|
1494
|
+
switch (purpose) {
|
|
1495
|
+
case "reset":
|
|
1496
|
+
return { subject: `Reset your ${app} password`, text: `Someone asked to reset the password for your ${app} account.\n\nSet a new password (the link works once, for ${minutes} minutes):\n${link}\n\nIf it was not you, ignore this e-mail; your password has not changed.` };
|
|
1497
|
+
case "magic-link":
|
|
1498
|
+
return { subject: `Sign in to ${app}`, text: `Sign in to ${app} (the link works once, for ${minutes} minutes):\n${link}\n\nOr enter this code: ${code.slice(0, 4)} ${code.slice(4)}\n\nIf you did not ask to sign in, ignore this e-mail.` };
|
|
1499
|
+
case "email-change":
|
|
1500
|
+
return { subject: `Confirm your new e-mail address for ${app}`, text: `Confirm that ${input.email} is your new address for ${app} (the link works once, for ${minutes} minutes):\n${link}\n\nIf you did not ask for this, ignore this e-mail; nothing changes.` };
|
|
1501
|
+
default:
|
|
1502
|
+
return { subject: `Verify your e-mail address for ${app}`, text: `Confirm that this is your address (the link works once, for ${minutes} minutes):\n${link}\n\nIf you did not create a ${app} account, ignore this e-mail.` };
|
|
1503
|
+
}
|
|
1504
|
+
}
|
|
1234
1505
|
/**
|
|
1235
1506
|
* AppPort Services' e-mail channel (0.13.0+). Looked up when an app sends account e-mail, so an
|
|
1236
1507
|
* older AppPort Services still runs every other app, and this one says what it needs.
|