@feltdb/feltkit 0.3.12 → 0.3.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (108) hide show
  1. package/README.md +4 -3
  2. package/dist/app.d.ts +27 -1
  3. package/dist/app.js +22 -0
  4. package/dist/app.js.map +1 -1
  5. package/dist/appboundry/build.js +10 -2
  6. package/dist/appboundry/build.js.map +1 -1
  7. package/dist/appboundry/host.js +2 -2
  8. package/dist/appboundry/host.js.map +1 -1
  9. package/dist/cli/deploy.js +9 -3
  10. package/dist/cli/deploy.js.map +1 -1
  11. package/dist/cli/main.d.ts +5 -0
  12. package/dist/cli/main.js +141 -40
  13. package/dist/cli/main.js.map +1 -1
  14. package/dist/client/index.d.ts +3 -0
  15. package/dist/client/index.js +3 -0
  16. package/dist/client/index.js.map +1 -1
  17. package/dist/dashboard/assets/{index-91I1zDK-.css → index-BXTNQAg1.css} +1 -1
  18. package/dist/dashboard/assets/index-DnIOVGF-.js +15 -0
  19. package/dist/dashboard/index.html +3 -3
  20. package/dist/docs.d.ts +12 -0
  21. package/dist/docs.js +43 -0
  22. package/dist/docs.js.map +1 -0
  23. package/dist/errors.d.ts +15 -0
  24. package/dist/errors.js +9 -0
  25. package/dist/errors.js.map +1 -1
  26. package/dist/index.d.ts +1 -0
  27. package/dist/platform/changes.js +4 -2
  28. package/dist/platform/changes.js.map +1 -1
  29. package/dist/platform/deployments.js +8 -6
  30. package/dist/platform/deployments.js.map +1 -1
  31. package/dist/runtime/activity.d.ts +25 -0
  32. package/dist/runtime/activity.js +38 -12
  33. package/dist/runtime/activity.js.map +1 -1
  34. package/dist/runtime/agent.d.ts +16 -0
  35. package/dist/runtime/agent.js +97 -30
  36. package/dist/runtime/agent.js.map +1 -1
  37. package/dist/runtime/backup-environment.d.ts +8 -1
  38. package/dist/runtime/backup-environment.js +44 -12
  39. package/dist/runtime/backup-environment.js.map +1 -1
  40. package/dist/runtime/backup.d.ts +45 -3
  41. package/dist/runtime/backup.js +237 -68
  42. package/dist/runtime/backup.js.map +1 -1
  43. package/dist/runtime/capabilities.js +4 -2
  44. package/dist/runtime/capabilities.js.map +1 -1
  45. package/dist/runtime/changes.js +2 -2
  46. package/dist/runtime/changes.js.map +1 -1
  47. package/dist/runtime/contract.d.ts +10 -0
  48. package/dist/runtime/contract.js +37 -15
  49. package/dist/runtime/contract.js.map +1 -1
  50. package/dist/runtime/data.d.ts +30 -3
  51. package/dist/runtime/data.js +136 -32
  52. package/dist/runtime/data.js.map +1 -1
  53. package/dist/runtime/decisions.d.ts +41 -3
  54. package/dist/runtime/decisions.js +159 -1
  55. package/dist/runtime/decisions.js.map +1 -1
  56. package/dist/runtime/integrations.js +14 -6
  57. package/dist/runtime/integrations.js.map +1 -1
  58. package/dist/runtime/loader.js +22 -2
  59. package/dist/runtime/loader.js.map +1 -1
  60. package/dist/runtime/readiness.js +6 -1
  61. package/dist/runtime/readiness.js.map +1 -1
  62. package/dist/runtime/runtime.d.ts +24 -6
  63. package/dist/runtime/runtime.js +77 -20
  64. package/dist/runtime/runtime.js.map +1 -1
  65. package/dist/runtime/services.d.ts +19 -5
  66. package/dist/runtime/services.js +14 -4
  67. package/dist/runtime/services.js.map +1 -1
  68. package/dist/runtime/sessions.js +4 -3
  69. package/dist/runtime/sessions.js.map +1 -1
  70. package/dist/runtime/state-contract.js +3 -3
  71. package/dist/runtime/state-contract.js.map +1 -1
  72. package/dist/runtime/targets.d.ts +6 -1
  73. package/dist/runtime/targets.js +8 -0
  74. package/dist/runtime/targets.js.map +1 -1
  75. package/dist/server/admin.d.ts +2 -2
  76. package/dist/server/admin.js +37 -12
  77. package/dist/server/admin.js.map +1 -1
  78. package/dist/server/index.d.ts +2 -1
  79. package/dist/server/index.js +45 -8
  80. package/dist/server/index.js.map +1 -1
  81. package/dist/server/mcp.js +1 -1
  82. package/dist/server/mcp.js.map +1 -1
  83. package/dist/testing/index.d.ts +6 -2
  84. package/dist/testing/index.js +28 -4
  85. package/dist/testing/index.js.map +1 -1
  86. package/docs/AGENT-OPERATIONS.md +515 -0
  87. package/docs/APPBOUNDRY.md +240 -0
  88. package/docs/ARCHITECTURE.md +126 -0
  89. package/docs/BACKUP.md +115 -0
  90. package/docs/GUARANTEES.md +460 -0
  91. package/docs/PATH-TO-PRODUCTION.md +117 -0
  92. package/docs/README.md +16 -0
  93. package/docs/RESOLVER.md +167 -0
  94. package/docs/SECURITY.md +182 -0
  95. package/docs/TRANSACTIONS.md +216 -0
  96. package/docs/UPSTREAM-GAPS.md +270 -0
  97. package/docs/WHY-FELTKIT.md +64 -0
  98. package/docs/assets/feltkit-logo-dark.png +0 -0
  99. package/docs/assets/feltkit-logo.png +0 -0
  100. package/package.json +11 -8
  101. package/skills/.claude-plugin/marketplace.json +1 -1
  102. package/skills/.claude-plugin/plugin.json +3 -3
  103. package/skills/feltkit-agent/SKILL.md +9 -5
  104. package/skills/feltkit-build/SKILL.md +10 -1
  105. package/skills/feltkit-data/SKILL.md +9 -3
  106. package/skills/feltkit-services/SKILL.md +8 -4
  107. package/dist/dashboard/assets/index-BhFOquA7.js +0 -15
  108. package/dist/dashboard/theme.js +0 -11
@@ -0,0 +1,167 @@
1
+ # Model references with Resolver
2
+
3
+ Change the model a deployed FeltKit app uses without changing, rebuilding or redeploying the
4
+ app. The app names a stable reference, `ref://prod/chat/model`. [Resolver](https://www.npmjs.com/package/@appport/resolver)
5
+ decides what it points to, now and after every change.
6
+
7
+ ```ts
8
+ // feltkit/app.ts
9
+ export const app = feltkit({
10
+ name: "acme",
11
+ agent: { model: { production: "ref://prod/chat/model", development: "ref://dev/chat/model" } },
12
+ // …
13
+ });
14
+ ```
15
+
16
+ ```bash
17
+ # An operator, in Resolver (the app is not touched):
18
+ resolver set ref://prod/chat/model --value '{"provider":"anthropic","model":"claude-sonnet-5-5","credential":"ref://prod/llm/anthropic-key"}' --reason "cost review"
19
+ ```
20
+
21
+ The agent's next decision runs on the new target, and its record says which revision it used.
22
+
23
+ ## What is in this release
24
+
25
+ The agent's model decisions (`ctx.agent.start`, `playbook: "decide"`) are the one reference type
26
+ supported. Other kinds (endpoints, credentials for integrations, agents, configuration values)
27
+ are listed under [Not yet](#not-yet).
28
+
29
+ ## Who owns what
30
+
31
+ | | Owns | Here |
32
+ |---|---|---|
33
+ | **Resolver** | references, bindings, revisions, history, rollback, grants, secret material (its vault), change notifications | the source of truth for what `ref://…` means; FeltKit never stores a copy of a binding |
34
+ | **FeltKit** | which reference an environment uses (`agent.model`), calling the model, recording what each decision used | `ModelHost` resolves through `@appport/resolver-client`, executes with its OpenAI-chat or Anthropic runtime, records the receipt |
35
+ | **FeltDB** | the app's durable state | the decision record (agent memory) holds the receipt next to the choice |
36
+ | **AppPort** | capabilities and authority | Resolver is an AppPort service; the client calls `resolver.resolve` with this deployment's key, checked by Resolver's own grants |
37
+ | **AppPort Services** | the Intelligence catalog | Resolver checks a model's provider against it when a binding is written; FeltKit picks the protocol and default endpoint from it |
38
+
39
+ There is no second store, permission system or secret vault. Resolver authorizes every
40
+ resolution with its own grants; FeltKit's roles still decide who may start agent work.
41
+
42
+ ## Setting it up
43
+
44
+ 1. **Run Resolver** (`npm install -g @appport/resolver`; `resolver init`, then `resolver serve`).
45
+ See its README for state, vault and multi-instance options.
46
+ 2. **Bind the reference** (as an operator, with an admin key):
47
+ ```bash
48
+ resolver set ref://prod/llm/anthropic-key --kind secret --secret-stdin # the key, on stdin
49
+ resolver set ref://prod/chat/model --kind model --value '{"provider":"anthropic","model":"claude-sonnet-5-5","credential":"ref://prod/llm/anthropic-key"}'
50
+ ```
51
+ The provider must be in the AppPort Services Intelligence catalog (`openai`, `anthropic`,
52
+ `opencode`, `ollama`, `custom`). Resolver refuses a binding that names an unknown provider or
53
+ model, a missing credential, or a credential placed in `options`.
54
+ 3. **Give the deployment its own key**, allowed to read the reference and reveal its credential, and
55
+ nothing else:
56
+ ```bash
57
+ resolver keys create acme-production --grant read:ref://prod/chat/model --grant read,reveal:ref://prod/llm/*
58
+ ```
59
+ 4. **Configure the app**: `agent.model` in `feltkit({ … })`, and in the deployment's environment
60
+ `RESOLVER_URL` (the origin) and `RESOLVER_API_KEY` (the key from step 3). `feltkit deploy` lists
61
+ both in the artifact's `.env.example` and contract when the app names a reference. The values
62
+ are never in the artifact.
63
+
64
+ ## Seeing what is in use
65
+
66
+ - `feltkit model show --env production`: the provider and model the reference resolves to now, the
67
+ reference, its revision and credential reference, and what to fix if it does not resolve.
68
+ - Studio → Models: the same, with the source shown as Resolver.
69
+ - Each agent decision's checkpoint reads `anthropic/claude-sonnet-5-5 (ref://prod/chat/model r7) chose …`,
70
+ in Studio and over MCP (`feltkit_agent_get`). The decision's memory record, cited as evidence,
71
+ holds the full receipt: `ref`, `revision`, `label` (for weighted bindings), `provider`, `model`,
72
+ `endpoint`, `credential` (the reference, never the key), `credentialRevision`, `resolvedAt`.
73
+ - History, diffs and rollback are Resolver's: `resolver history ref://prod/chat/model`.
74
+
75
+ `feltkit model set` and Studio's model picker refuse to change an environment that a reference
76
+ governs (the choice would be stored and never used), and name the `resolver set` command instead.
77
+
78
+ ## When a change takes effect
79
+
80
+ FeltKit connects to Resolver on first use and subscribes to the reference. What the guarantee is:
81
+
82
+ - **Through the change stream.** Resolver notifies connected clients of a change (name and revision
83
+ only). The cached result is dropped, and the next decision resolves again. Measured in the tests:
84
+ within seconds, with a 300 s TTL, across separate processes.
85
+ - **At the latest, the reference's TTL** (`--ttl`, default 30 s). A missed notification (a reconnect,
86
+ another Resolver instance, which polls every second) is bounded by it.
87
+ - **Per decision, one resolution.** A decision's target, credential and receipt come from one answer,
88
+ so a change landing during a call cannot mix two revisions. The call in progress finishes on the
89
+ revision it started with; the receipt says which.
90
+ - **Resolver unreachable:** a result resolved earlier is served for up to 5 minutes, then decisions
91
+ fail. A not-found, revoked or forbidden answer is never covered over: it evicts the cache.
92
+
93
+ A decision that is already running is not interrupted by a change.
94
+
95
+ ## Failure behavior
96
+
97
+ Nothing falls back to another model or to the Intelligence selection. Each failure blocks the
98
+ agent task with what to fix (`problem` in the error's details):
99
+
100
+ | Problem | When |
101
+ |---|---|
102
+ | `not_configured` | `RESOLVER_URL` or `RESOLVER_API_KEY` is not set |
103
+ | `reference_missing` | the reference does not exist or was revoked |
104
+ | `reference_forbidden` | this deployment's key has no `read` grant on it (or `reveal` on its credential) |
105
+ | `reference_invalid` | not a model reference, a provider outside the catalog, or no endpoint |
106
+ | `credential_missing` | the provider needs a key and the binding names no credential |
107
+ | `resolver_unavailable` | Resolver cannot be reached and no cached result is left |
108
+
109
+ ## Secrets
110
+
111
+ The provider key is a `secret` reference held in Resolver's vault. FeltKit's process receives the
112
+ material for one call, in memory (Resolver's client keeps it for at most the reference's TTL), and
113
+ passes it to the provider's API. It is not written to FeltDB, decision records, activity, logs,
114
+ status views, errors, prompts or the deploy artifact. The receipt names the credential's reference
115
+ and revision, never its value. The acceptance test checks every one of those places for the key.
116
+
117
+ An app with `reveal` holds the material in memory while it uses it (Resolver's README, Limits).
118
+ Keep the grant narrow: `reveal` on the provider keys the app uses, not `*`.
119
+
120
+ ## Environments
121
+
122
+ `agent.model` maps environment names to references. An environment it does not name keeps the
123
+ Intelligence selection, so a test environment cannot reach a production reference by accident.
124
+ Use one Resolver key per deployment, granted only its environment's references
125
+ (`ref://prod/*` for production). Resolver tenants and grants keep environments apart. FeltKit
126
+ never rewrites a reference name.
127
+
128
+ ## Proven by
129
+
130
+ - `packages/sdk/test/resolver-model.test.ts`, run against the real Resolver in-process:
131
+ - provider A, then provider B with a credential, with no restart;
132
+ - the change arrives through the change stream, not by TTL expiry;
133
+ - receipts, and the durable decision record;
134
+ - each failure above;
135
+ - per-environment references;
136
+ - the refused `feltkit model set`.
137
+ - `tests/e2e/resolver-switch.test.mjs`:
138
+ - a starter app deployed once (`--target container`);
139
+ - Resolver as its own process (its CLI);
140
+ - A → B with no rebuild, redeploy or restart;
141
+ - the first decision still names A at r1;
142
+ - a restart keeps resolving;
143
+ - the key is in no decision, process output, artifact or state file.
144
+
145
+ The two providers are loopback OpenAI-compatible servers (`ollama`, `custom`); everything else
146
+ is the real software.
147
+
148
+ ## Not yet
149
+
150
+ - **Other reference kinds.** Integration endpoints (`endpoint` refs for `app.integration`),
151
+ integration credentials (`secret` refs in place of `FELTKIT_CREDENTIAL_<ID>`), AppPort agents
152
+ (`agent` refs) and configuration values (`value` refs) all need the same treatment:
153
+ - a typed declaration;
154
+ - resolution inside the existing call path;
155
+ - a receipt.
156
+ - **Weighted bindings with a stable key.** Steering works (the receipt has `label`), but FeltKit
157
+ passes no `key`, so a canary split is per call, not sticky per user or tenant.
158
+ - **Pinning a revision** (`resolve(ref, { revision })`) from the app is not exposed.
159
+ - **Credential custody outside the app process.** The key enters FeltKit's process for the call.
160
+ A provider proxy that holds the key would avoid that; none exists yet.
161
+ - **Managing references from Studio.** Studio shows the reference and its revision. Changes are made
162
+ in Resolver (its CLI or management pages), which owns their authorization and history.
163
+ - **Resolver's own pins.** `@appport/resolver` 0.2.0 pins `@feltdb/core` 0.21.0 and
164
+ `@appport/services` 0.15.0, the same versions FeltKit uses. It is a separate service, so the
165
+ versions never mix in the app; the app depends only on `@appport/resolver-client`. The tests install it the
166
+ same way, outside the workspace (`test/fixtures/resolver-service.mjs`), so FeltKit keeps exactly
167
+ one `@feltdb/core` (the release check).
@@ -0,0 +1,182 @@
1
+ # Security model
2
+
3
+ ## Boundaries
4
+
5
+ | Boundary | Enforcement |
6
+ |---|---|
7
+ | HTTP functions (`/api/query`, `/api/mutation`) | Arguments validated, then AppPort's authorizer evaluates the caller's roles against the function's `access`, before the handler runs |
8
+ | AppPort (`/appport`) and MCP (`/mcp`) | AppPort's dispatch pipeline: input validation → the same authorizer → handler (which re-checks) → output validation |
9
+ | AppPort Services | `ServiceGateway` asks FeltKit's policy (`ServiceAuthorizer`) before every effect. A live effect needs a bound FeltKit invocation of the same principal; durable work (jobs, deliveries) is re-authorized each attempt as its creator's current principal. Refusals are recorded as evidence |
10
+ | Studio's Services screens | AppPort Services' own management routes (`createManagementRouter`, `includeUi: false`) inside the admin API at `/_feltkit/api/services/manage`, development only. Identity: the admin token, then a declared dev identity named in `x-feltkit-as`. Authorization: the services' gateway. Successful reads are not recorded as activity (Studio refreshes on activity) |
11
+ | Services console | AppPort Services' own pages and routes on a separate loopback origin, development only. Identity: a FeltKit session in an HttpOnly, SameSite=Strict cookie, minted from a one-time 60-second ticket for a declared dev identity. Authorization: the services' gateway. Cross-origin and non-JSON writes refused; non-loopback `Host` refused |
12
+ | Agent | Every agent operation needs `feltkit.agent.read` / `feltkit.agent.write`; every action runs as the task owner through AppPort; consequential actions need a person who may perform them; results redacted |
13
+ | Data | `ctx.db` reaches only collections the application declared; platform collections are unreachable from application code |
14
+ | Dashboard / admin API (development) | Separate admin token (`.feltkit/<env>/admin-token`, 0600), constant-time comparison; application sessions do not grant it |
15
+ | Studio / admin API (production) | A verified operator only: an operator session (from a one-time signed grant) or the application's `auth.authenticate` hook. The admin token, `as`, dev users, and non-operator sessions grant nothing. Every route checks a permission server-side (`feltkit.operations.read` / `.write`, plus the action's own permission); writes need JSON, a same-origin `Origin`, a session-bound CSRF value, and `x-feltkit-environment` naming this environment |
16
+
17
+ ## Identity
18
+
19
+ - Identity comes from a FeltKit session token (opaque, 256-bit, stored as a SHA-256
20
+ digest) or from the application's `auth.authenticate` hook. Request bodies and
21
+ headers never name the caller; a forged or expired token is rejected, not downgraded
22
+ to anonymous.
23
+ - Development sign-in (`/api/auth/dev`) exists only in `development` and `test`, and
24
+ only for identities declared in `feltkit({ dev: { users } })`.
25
+ - The dashboard can act only as declared dev users, through the normal authorization
26
+ path. It cannot invent principals.
27
+
28
+ ## Development server
29
+
30
+ - Binds `127.0.0.1` and refuses requests whose `Host` is not loopback (DNS rebinding).
31
+ - The dashboard is served with `X-Frame-Options: DENY` and a restrictive CSP.
32
+ - The admin token travels in a header (or the URL fragment once, removed on load), never
33
+ in query strings or the frontend bundle.
34
+
35
+ ## Production
36
+
37
+ - No Studio unless `FELTKIT_DASHBOARD=1`. With it, Studio answers only verified operators
38
+ (below) and offers only the operations listed in docs/GUARANTEES.md ("Production
39
+ operations"). Data browsing and edits, function runs, capability invocation, sessions,
40
+ task creation, the services console, and webhook replay are not served.
41
+ - No development sign-in.
42
+ - Errors from application code are sanitized to `Internal error (request …)`; details
43
+ go to the server log.
44
+ - `FELTDB_TOKEN` is read from the environment and never written to disk or logs.
45
+ `inspect` and the dashboard show storage locations, never credentials.
46
+ - `feltkit build` scans the frontend bundle and fails if it contains session or admin
47
+ tokens, `FELTDB_TOKEN`, or FeltDB/AppPort Services server code.
48
+
49
+ ## Production operators
50
+
51
+ - **Grant.** `feltkit operator grant --id <id> --role <role>` on the host signs
52
+ { application, environment, subject, roles, expiry ≤ 24 h (default 10 min), nonce } with
53
+ HMAC-SHA256 under the environment's operator key: `FELTKIT_OPERATOR_KEY` (≥ 32 bytes,
54
+ base64url) or `.feltkit/<env>/operator-key` (0600). The root of trust is whoever can
55
+ read that key: the host operator. Roles must be declared by the application.
56
+ - **Exchange.** Studio posts the grant once; FeltKit verifies the signature, application,
57
+ environment, and expiry, records the nonce (a reused grant is refused), and issues a
58
+ FeltKit session of kind `operator` (8 h) in a `feltkit_operator_<env>` cookie:
59
+ HttpOnly, Secure, SameSite=Strict, Path=/_feltkit. The token is never in a response body.
60
+ - **Identity hook.** If the application defines `auth.authenticate`, a `user` principal it
61
+ returns for a Studio request is also an operator; its writes still need the Origin,
62
+ CSRF, and environment checks.
63
+ - **Authority.** An operator's permissions come from their roles. Reads need
64
+ `feltkit.operations.read`; actions need `feltkit.operations.write` and then whatever
65
+ the operation itself needs (the action's capability permission and `feltkit.agent.write`
66
+ for agent actions; the services' `jobs.retry` for job retry).
67
+ - **Not supported:** OIDC/SAML or any external identity provider integration (use the
68
+ `auth.authenticate` hook with your own verification), operator session listing or
69
+ revocation from Studio (sessions expire; rotating the operator key invalidates unused
70
+ grants, not existing sessions — revoke with `feltkit session revoke` while the server is
71
+ stopped), and MFA.
72
+ - TLS is assumed to terminate in front of FeltKit (reverse proxy or platform). The cookie
73
+ is `Secure`, so production Studio must be served over HTTPS (browsers also accept it
74
+ on `localhost`). Behind a proxy, `Host` (or `X-Forwarded-Host`) must be the public
75
+ host so the Origin check matches.
76
+
77
+ ## Request hygiene
78
+
79
+ - Every executing POST (`/api/*`, `/appport`, `/mcp`) must be `Content-Type:
80
+ application/json`. Browsers cannot send JSON cross-site without a CORS preflight,
81
+ which FeltKit never answers, so no other site can drive these endpoints — including
82
+ for apps whose `auth.authenticate` hook reads a cookie.
83
+ - A credential that does not verify (unknown, expired, revoked, signed out) is a 401
84
+ on every interface. It is never treated as anonymous, even for public functions.
85
+ - The change stream (`/api/events`) requires a session unless the application has a
86
+ public query.
87
+
88
+ ## Audit (2026-10-27)
89
+
90
+ Every entry point was exercised by `packages/sdk/test/auth.test.ts`.
91
+
92
+ | Entry point | Finding | Status |
93
+ |---|---|---|
94
+ | `/appport` | A forged or expired token fell back to anonymous, so a public capability ran without the caller's identity | Fixed: 401 |
95
+ | `/appport` | AppPort accepts `text/plain` and form bodies: cross-site request forgery for cookie-authenticated apps | Fixed: JSON required |
96
+ | `/mcp` | Same body-type exposure (bearer-only, so not exploitable) | Fixed: JSON required |
97
+ | `/api/events` | Change notifications streamed to anonymous callers | Fixed: session required unless a public query exists |
98
+ | AppPort Services notifications | Any principal with `notifications.read` could list or open another principal's notifications | Fixed: FeltKit's Services authorizer allows read/update/delete only to the recipient; no override permission |
99
+ | `/api/*` | Missing, forged, expired, revoked, and signed-out tokens; client-asserted identity; role enforcement | Verified |
100
+ | AppPort / MCP | Role enforcement for agents; revocation takes effect immediately | Verified |
101
+ | AppPort Services | Effects require a live invocation of the same principal in the application's tenant; refusals evidenced | Verified |
102
+ | CLI sessions | Unknown roles rejected; tokens shown once and never listed | Verified |
103
+ | Admin API (development) | Token required; app sessions do not grant it | Verified |
104
+ | Admin API (production) | Unauthenticated → 401 on every route; admin token, `as`, dev users, non-operator sessions, forged/expired/reused/other-environment grants refused; read-only operators refused on every write; cross-origin, non-JSON, wrong-CSRF, wrong-environment writes refused with nothing changed; secrets, session tokens, and the admin token absent from responses, activity, and process output | Verified (`production-ops.test.ts`) |
105
+ | `auth.authenticate` | Used only without a token; a bad token is not rescued by it; its principals pass through the same roles | Verified |
106
+ | Services console | Unauthenticated and under-privileged requests refused by the package's routes; cross-origin, non-JSON, and DNS-rebinding requests refused; tickets single-use | Verified (`console.test.ts`) |
107
+ | Durable service work | Runs as its creator; refused after the creator's sessions are revoked | Verified (`console.test.ts`) |
108
+ | API keys | Accepted only while active; revoked key → 401; secret never in lists, logs, or explorer | Verified (`console.test.ts`) |
109
+ | Agent | Agents cannot approve; approvers must be authorized; owner's authority bounds every action; secrets redacted (mutation-tested) | Verified (`agent.test.ts`) |
110
+ | Credential custody | Stored key absent from every FeltDB collection (raw), activity, evidence, configuration export, server output, admin responses, and the dashboard bundle; vault not plaintext and 0600; viewer and agent roles refused; production without opt-in → `CUSTODY_READ_ONLY`; environment variable overrides the vault; Models Test sends the stored key to a local fake provider that checks it | Verified (`credentials.test.ts`, `credential-custody.test.ts`) |
111
+
112
+ ### Credentials and API keys
113
+
114
+ - Service credentials are references (`credential-ref:<id>`) resolved only inside the
115
+ effect that needs them, from `FELTKIT_CREDENTIAL_<ID>` when it is set, else (development
116
+ and test) from the environment's encrypted vault. Studio shows whether each reference is
117
+ set, where, and its version, never a value.
118
+ - **Credential vault** (`.feltkit/<env>/credentials.vault`, key in `credentials.key`): the
119
+ whole document is AES-256-GCM-encrypted with a random 32-byte key and bound (associated
120
+ data) to the application and environment; a modified file or another environment's
121
+ vault fails to decrypt and is refused, not partly read. Both files are 0600 in a 0700
122
+ directory, written atomically under a lock file. Anyone who can read both files can
123
+ read the values: it protects against values leaking into FeltDB, git, builds, logs, and
124
+ screenshots, not against a compromised developer account. Earlier values are not kept.
125
+ - **Production** keeps credentials in the host's environment only; `credential.store`
126
+ refuses with `CUSTODY_READ_ONLY`. The vault is opt-in (`FELTKIT_CREDENTIAL_VAULT=1`) and
127
+ then needs `FELTKIT_CREDENTIAL_VAULT_KEY` from the host's secret manager (never written
128
+ to disk by FeltKit); without a valid key the runtime does not start.
129
+ - **Entering a value**: Studio (Models, Integrations, Services → Credentials) sends it once
130
+ in a password field over the admin API, clears the field, and never renders it back; the
131
+ server stores it through AppPort Services' `credential.store` as the chosen dev identity
132
+ (development) or the signed-in operator (production, opt-in vault only). The CLI reads it
133
+ from a hidden prompt or stdin; `--value`, `--api-key`, and a key-shaped argument are
134
+ refused, so it never lands in shell history or process listings. A reference field
135
+ holding a key is refused without echoing it.
136
+ - API keys are HMACs under a server-held key: `FELTKIT_API_KEY_VERIFIER_KEY` in
137
+ production (≥ 32 bytes; required), `.feltkit/<env>/api-key-verifier` (0600) in
138
+ development. The plaintext is returned once. The data explorer does not expose
139
+ `api_keys`.
140
+
141
+ ### Models and integrations
142
+
143
+ - Model and integration credentials are the same references, resolved inside the request
144
+ that needs them (`credentials.withSecret`). They are never in the model selection, an
145
+ integration's published contract, call records, checkpoints, activity, responses, or
146
+ logs; an upstream error that echoes one is redacted. `--credential` and Studio's
147
+ reference field accept only a `credential-ref:` reference; the key goes in the API key
148
+ field or `--api-key-stdin`.
149
+ - The browser never talks to a model or an integration: decisions and calls run on the
150
+ server, and `feltkit build` fails a bundle containing server code.
151
+ - Discovery is not authority. Every integration operation requires a declared permission
152
+ (`public` is refused at definition time); AppPort and MCP list the contract and still
153
+ authorize each invocation. A model can only choose among options the task owner may
154
+ perform, and its choice is a proposal that consequential effects wait on.
155
+ - FeltKit reads and writes the Intelligence selection as a **system principal**: an object
156
+ held in a module-private `WeakMap`, allowed only the Intelligence operations it needs
157
+ (read for decisions, write for `feltkit model set` and development Studio). It cannot be
158
+ constructed from a request, a token, or a role.
159
+ - Production does not serve `POST /_feltkit/api/models` (model selection); it is selected
160
+ on the host. Verification probes run as the caller, who must hold the probe's
161
+ permission. Tests: `decisions.test.ts` (no key in status, tasks, decision records, activity),
162
+ `integrations.test.ts` (discovery without authority, no credential in records),
163
+ `platform.test.ts` (production routes).
164
+
165
+ ## Known gaps
166
+
167
+ - No rate limiting on FeltKit's own endpoints. Put a reverse proxy in front of
168
+ production deployments.
169
+ - Session tokens in the browser are kept in `localStorage`; an XSS in your frontend can
170
+ read them.
171
+ - CORS is not enabled: the API is same-origin. Cross-origin clients need a proxy.
172
+ - Request bodies are limited to 2 MiB.
173
+ - The services console has no CSRF token: it relies on SameSite=Strict cookies, an
174
+ Origin check, and JSON-only writes on a loopback origin.
175
+ - Studio acts as declared dev identities without their sessions (development only):
176
+ anyone with the admin token can act as any of them, as before. None of this applies in
177
+ production.
178
+ - Production operator sessions cannot be listed or revoked from Studio; there is no MFA
179
+ and no external identity-provider integration beyond the `auth.authenticate` hook.
180
+ - Production Studio has no rate limiting of its own, like every FeltKit endpoint.
181
+
182
+ Report vulnerabilities privately to the repository owner.
@@ -0,0 +1,216 @@
1
+ # Transactional sequences and after-commit effects: the contract
2
+
3
+ Status: **settled and implemented** (FeltKit 0.3.12, AppBoundry 1.5.0). This document was
4
+ written before the code: it records what `ctx.db.sequence` and `ctx.afterCommit` did on
5
+ FeltKit's runtime, measured rather than assumed, the contract both runtimes (FeltKit's Node
6
+ runtime and AppBoundry artifacts) now meet, the decisions the owner made (§5), and the evidence
7
+ (§7).
8
+
9
+ ## 1. What existed (FeltKit 0.3.11, Node runtime)
10
+
11
+ ### `ctx.db.sequence(name)` (`src/runtime/data.ts`)
12
+
13
+ - **Storage.** There is one record per name in `_feltkit_sequences` (`{ id: name, value, transactionId }`).
14
+ - **Allocation.** The mutation reads the record and hands out `value + 1, + 2, ...` in call order.
15
+ - **Commit.** The new value is written in the mutation's own FeltDB transaction, guarded by the
16
+ version it read (`ifVersion`, or `requireAbsent` for a new name).
17
+ - **Concurrency.** Two mutations that drew from the same name: the second commit fails with
18
+ `PRECONDITION_FAILED`, which reaches the caller as `CONFLICT` with nothing written. There is
19
+ no retry.
20
+ - **Failure.** A handler that throws, or a refused commit, writes nothing, so it consumes
21
+ no numbers.
22
+
23
+ The documented API (`DatabaseWriter.sequence`) promises the following:
24
+
25
+ - values increase in commit order, across processes, and in call order within a mutation;
26
+ - there are no gaps;
27
+ - concurrent use of one sequence serializes and the later commit gets `CONFLICT`;
28
+ - "name a sequence per stream (e.g. `audit:<invoiceId>`)" so unrelated writers don't contend.
29
+
30
+ ### `ctx.afterCommit` (`src/runtime/outbox.ts`)
31
+
32
+ - **Staging.** `notifications.send`, `webhooks.emit` and `jobs.enqueue` stage an
33
+ `_feltkit_outbox` record (`pending`) in the mutation's transaction (`Writer.stageSystem`).
34
+ - **After commit.** The runtime claims the record (`pending → performing`, version-checked),
35
+ performs the effect as the caller, and records `done` or `failed` with the error.
36
+ - **Recovery.** The services worker recovers records left `pending` for more than 30 s, or
37
+ `performing` for more than 300 s, as the caller's current principal.
38
+ - **Inspection.** The records are listed in the admin collection registry, and Studio shows them.
39
+
40
+ ## 2. What was measured
41
+
42
+ `node --test` probe, 10 concurrent mutations on one runtime, each inserting one `events` record
43
+ (`stream`, `seq`, `what`):
44
+
45
+ | Mutation | Result |
46
+ |---|---|
47
+ | insert, no sequence | 10 ok |
48
+ | one shared stream, `sequence("audit")` | **1 ok, 9 `CONFLICT`** (SupplyDesk's result) |
49
+ | a stream per mutation, `sequence("inv-<n>")` | 10 ok |
50
+ | per stream, plus an equality read of its own stream (`find(events, { stream })`) | 10 ok |
51
+ | per stream, plus an unfiltered read of the collection (`find(events, {})`) | 1 ok, 9 `CONFLICT` |
52
+ | a stream per mutation, named as documented: `sequence("inv:<n>")` | **10 `INTERNAL`** |
53
+
54
+ Findings:
55
+
56
+ 1. **Independent streams already don't contend.** The sequence record is per name, and the
57
+ collection markers are written unguarded. SupplyDesk's audit trail used one global stream,
58
+ so its mutations serialized as documented.
59
+ 2. **An unfiltered read conflicts for the right reason.** The 1/9 result for a full read is the
60
+ read fence (serializability of what the handler read), not the sequence.
61
+ 3. **Bug: the documented per-stream naming fails.** FeltDB record ids must match
62
+ `[A-Za-z0-9._-]{1,128}`. FeltKit accepts `:` in sequence names and uses the name as the
63
+ record id, so FeltDB refuses the transaction (`INVALID_REQUEST`) and callers see `INTERNAL`.
64
+ Every name containing `:` has always failed, so no stored record uses one, and encoding
65
+ such names is backward compatible.
66
+ 4. **`failed` effects are terminal.** You can inspect them, but nothing can retry them.
67
+ 5. **Recovered jobs and webhook events can be duplicated.** Notifications are deduplicated by
68
+ the outbox id. `@appport/services` `jobs.enqueue` and `emitWebhookEvent` take no
69
+ idempotency key, so a crash between performing an effect and recording `done` can enqueue
70
+ or emit twice.
71
+
72
+ ## 3. FeltDB review
73
+
74
+ - **Atomicity.** `db.transaction({ operations, preconditions, fences })` commits application
75
+ writes, sequence records and outbox records together, or none of them. AppBoundry's
76
+ `CollectionTransaction.commit(transactionId, extra)` already commits `extra` operations in
77
+ the application's transaction. **No second transaction system is needed, and nothing is
78
+ missing upstream for atomicity.**
79
+ - **Durability and restart.** Outbox records are ordinary FeltDB records in the state
80
+ directory or managed environment, so they survive restarts.
81
+ - **`db.allocateSequence({ scope, scopeId })` is not usable here.** It allocates outside the
82
+ transaction (a failed mutation would consume a number), and only the file backend has it.
83
+ - **No in-transaction increment.** FeltDB has no operation whose value is assigned at commit
84
+ and visible to other operations in the same transaction. With one, a single stream could be
85
+ allocated without conflicts. It is an optional upstream enhancement, recorded in
86
+ `UPSTREAM-GAPS.md`; this contract doesn't need it.
87
+ - **Transactional services exist upstream, but can't be used yet.** `@appport/services` has a
88
+ transaction context (`queueJob`, `queueWebhookDeliveries`) that creates jobs and webhook
89
+ deliveries inside a FeltDB transaction, and it accepts FeltKit's outbox `done` write in the
90
+ same transaction. Implemented and tried (decision C): 0.13.0's transaction context writes audit
91
+ fields its own `servicesContract` doesn't declare (`job_audit_events.jobType`,
92
+ `webhook_audit_events.eventType`), so FeltDB refuses the transaction under an enforced
93
+ contract. Recorded as UPSTREAM-GAPS S11; the fallback applies (§5 C).
94
+
95
+ ## 4. The contract (both runtimes)
96
+
97
+ | Guarantee | Behavior |
98
+ |---|---|
99
+ | Sequence allocation | Atomic with the mutation and durable. A number is consumed only by a committed mutation. |
100
+ | Ordering | Per stream (the sequence name): strictly increasing, gapless, in commit order. Within one mutation, in call order. **No ordering between different streams.** |
101
+ | Independent streams | Mutations on different streams never conflict on the sequence. |
102
+ | Same stream, concurrent | Serializable: at most one of two concurrent writers commits from the same value (see Decision A for what the other one gets). |
103
+ | Transaction failure | No sequence advance, no outbox record, no effect. |
104
+ | Outbox creation | The record commits in the mutation's transaction, or not at all. |
105
+ | Rollback | No after-commit effect. |
106
+ | Restart | `pending` and stale `performing` records are recovered by the runtime's worker. |
107
+ | Duplicate processing | Claiming is version-checked, so two workers never perform one record concurrently. A job or webhook delivery is created in the transaction that records the effect done: once per committed effect (Decision C). Notifications are idempotent (key = outbox id). |
108
+ | Failed delivery | Recorded with its error, inspectable, and retryable (Decision B). |
109
+ | Delivery | Creation is exactly once. A job's run and a webhook's delivery to its endpoint are AppPort Services' own: at least once. **No exactly-once claim for external systems.** |
110
+
111
+ **Sequence names.** A name is 1–128 characters from `[A-Za-z0-9_.:-]`, starting with a letter
112
+ or digit (unchanged). A name that is a valid FeltDB id stays the record id, so existing data
113
+ is untouched. Any other name (one containing `:`) is stored under a derived id: `_` plus a hash
114
+ of the name, which no valid name can produce. The record keeps the name.
115
+
116
+ **One implementation in FeltKit.** The guest-side `afterCommit` API and its record shape, the
117
+ sequence name rule and encoding, and the outbox state machine and recovery policy move to a
118
+ shared module with no Node imports. FeltKit's runtime and the artifact guest (through the
119
+ host) both use it.
120
+
121
+ **AppBoundry: host interface `transactions@1`.** It is required only by artifacts that use
122
+ these features:
123
+
124
+ - `db.sequence { name }` → the next number, tracked in the host's transaction and committed
125
+ with it (the same guard as FeltKit's runtime);
126
+ - `effect.stage { effect }` → `{ outboxId }`, an outbox record committed with the mutation;
127
+ - after commit, the host performs staged effects through its services as the caller and
128
+ records `done` or `failed`. Its job worker recovers stale records, so they survive restarts;
129
+ - the records go in host-owned collections (`_appboundry_sequences`, `_appboundry_outbox`)
130
+ with the record shapes above, so the host stays producer-neutral;
131
+ - `appboundry admin outbox list | retry <id>` lets an operator inspect and retry;
132
+ - a host without `transactions@1` refuses such an artifact when it loads, and FeltKit's
133
+ compatibility check names the release that provides it.
134
+
135
+ ## 5. Decisions (settled by the owner, 2026-11-03)
136
+
137
+ **A. Same-stream contention: default unchanged, opt-in retry.** The later writer still gets
138
+ `CONFLICT`. A mutation may declare `retry: { sequenceConflicts: n }` (1–10). The runtime then
139
+ re-runs its handler, at most `n` more times, when the commit was refused on a sequence record
140
+ (FeltDB's conflict detail names the first failing precondition) and the attempt used no
141
+ `ctx.services`. `ctx.afterCommit` is part of the transaction, so it doesn't count. Opting in
142
+ states that the handler is safe to run again, which FeltKit can't check for effects outside
143
+ FeltKit. The policy travels in the artifact's manifest (`functions[].retry`), so AppBoundry
144
+ applies it the same way. Re-runs are recorded: activity `detail.sequenceRetries` on FeltKit,
145
+ `retries` on AppBoundry's call result.
146
+
147
+ **B. Retrying a failed effect: operator action only.** `feltkit outbox list | retry <id>`
148
+ (through a running server's admin API, else the environment directly) and
149
+ `appboundry admin outbox list | retry <id>` (a running runtime performs it at once; a stopped
150
+ state moves it to `pending` for the runtime's worker) move `failed → pending`. They keep the
151
+ attempts and last error and record who retried. There is no automatic retry schedule.
152
+
153
+ **C. Jobs and webhook deliveries: created exactly once per committed effect.** The performer
154
+ claims the record (`pending → performing`, version-checked). It then creates the job, or the
155
+ deliveries to the endpoints subscribed to the event, through AppPort Services' transaction
156
+ context (`tx.queueJob`, `tx.queueWebhookDeliveries`). The record's done write, guarded on the
157
+ claim's version, goes in that same FeltDB transaction:
158
+ - both commit, or neither does;
159
+ - a refused creation leaves no job and no done mark, and the record is `failed` with the error;
160
+ - a process that stops before the transaction committed nothing, so recovery creates the effect
161
+ once.
162
+
163
+ This needs `@appport/services` 0.13.1. Its 0.13.0 wrote audit fields its own contract didn't
164
+ declare (UPSTREAM-GAPS S11, fixed by rkendel1/appport-services#42); until then this was
165
+ at-least-once. Notifications don't repeat either, because the outbox id is their idempotency key.
166
+ Creation, not execution: a job's run and a webhook's delivery to its endpoint stay at least once.
167
+
168
+ ## 6. Acceptance tests (real persisted state, real concurrency)
169
+
170
+ - Two independent streams advance concurrently (N concurrent mutations, N streams, all ok).
171
+ - One stream: strictly increasing, gapless numbers across concurrent and sequential mutations.
172
+ - Failed mutations (a throw, or a refused commit) consume no numbers.
173
+ - Application writes and outbox records commit together. A failed transaction leaves no
174
+ outbox record and no effect.
175
+ - A restart preserves pending outbox records, and the worker performs them once.
176
+ - Reprocessing a claimed or done record doesn't repeat its outcome.
177
+ - A failed delivery is inspectable and retryable.
178
+ - A name containing `:` works, and existing names keep their records.
179
+ - The same artifact gives identical outcomes and records on FeltKit's runtime, AppBoundry's
180
+ source build and the packed package (extending `tests/e2e/state-contract-parity.test.mjs`).
181
+ - Existing applications keep their ordering: `test/sequence.test.ts` passes unchanged.
182
+
183
+ ## 7. Evidence
184
+
185
+ - `packages/sdk/test/transactions.test.ts` (FeltKit runtime, local state directory) covers:
186
+ - 10 concurrent streams, 3 rounds, all committed and each `[1, 2, 3]`;
187
+ - one stream without opt-in: losers get `CONFLICT`, committed numbers gapless;
188
+ - with opt-in: all 10 commit, numbers gapless, re-runs recorded;
189
+ - with a service used: not re-run;
190
+ - a failed mutation consumes nothing;
191
+ - `:` names work, and existing names keep their record ids;
192
+ - outbox records commit with the mutation, and none exist for a failed one;
193
+ - a restart preserves pending records, and two concurrent recoveries perform each once;
194
+ - a failed effect is inspectable, never retried on its own, and retried by an operator
195
+ after the cause is fixed;
196
+ - `feltkit outbox list` / `retry` from the CLI.
197
+ - `packages/sdk/test/appboundry.test.ts`:
198
+ - an artifact using these features requires `transactions@1`, and its manifest carries
199
+ the retry policy;
200
+ - sequences and after-commit effects give the same results in an artifact as on a FeltKit
201
+ server (createArtifactTestApp).
202
+ - AppBoundry `packages/appboundry-host/test/transactions.test.ts` covers the same contract on
203
+ the host:
204
+ - concurrent streams, the opt-in retry, failed mutations and `:` names;
205
+ - outbox commit and performance after it, restart recovery, and operator retry on a stopped
206
+ state and on a running one (after a fixed artifact is deployed);
207
+ - an artifact that doesn't require the interface is refused the operations, and an
208
+ unsupported interface version is refused when the artifact loads.
209
+ - `tests/e2e/outbox-lifecycle.test.mjs` runs the outbox lifecycle on FeltKit's runtime, AppBoundry's
210
+ source build and its package, each on persisted state with the contract enforced, and compares
211
+ what FeltDB holds after each phase. The phases: a mutation's job, webhook delivery and
212
+ notification; a job FeltDB refuses (no job, no done mark); a stop with an effect claimed but not
213
+ created; recovery creating it once; another restart creating nothing.
214
+ - `tests/e2e/transactions-parity.test.mjs` runs one FeltKit application on FeltKit's runtime,
215
+ AppBoundry's source build and the packed 1.5.0, each on persisted state, with concurrent calls
216
+ and a restart. All three must give the same results.