@jskit-ai/agent-docs 0.1.328 → 0.1.330

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 (34) hide show
  1. package/guide/agent/app-extras/assistant.md +122 -5
  2. package/guide/agent/app-setup/authentication.md +16 -0
  3. package/guide/agent/app-setup/package-with-nix.md +118 -0
  4. package/guide/agent/app-setup/upgrading-jskit.md +21 -2
  5. package/guide/agent/framework/data-access.md +67 -6
  6. package/guide/agent/framework/security-pass.md +136 -0
  7. package/guide/agent/framework/speed-pass.md +194 -0
  8. package/guide/agent/framework/ux-pass.md +116 -0
  9. package/guide/agent/index.md +11 -0
  10. package/package.json +1 -1
  11. package/patterns/minimal-foundation/example/package.json +2 -2
  12. package/patterns/shell-foundation/example/package.json +3 -3
  13. package/reference/autogen/PATTERN_INDEX.md +33 -33
  14. package/reference/autogen/packages/assistant-core.md +5 -3
  15. package/reference/autogen/packages/assistant-runtime.md +18 -3
  16. package/reference/autogen/packages/auth-provider-local-core.md +11 -4
  17. package/reference/autogen/packages/workspaces-core.md +9 -1
  18. package/reference/autogen/tooling/jskit-catalog.md +33 -0
  19. package/skills/jskit/SKILL.md +9 -4
  20. package/skills/jskit/references/data-access.md +67 -6
  21. package/skills/jskit/references/package-with-nix.md +113 -0
  22. package/skills/jskit/references/pattern-index.md +33 -33
  23. package/skills/jskit/references/patterns/app/minimal-foundation/example/package.json +2 -2
  24. package/skills/jskit/references/patterns/app/shell-foundation/example/package.json +3 -3
  25. package/skills/jskit/references/patterns/auth/accounts-hub/example/package.json +1 -1
  26. package/skills/jskit/references/patterns/auth/oidc-sign-in/example/package.json +2 -2
  27. package/skills/jskit/references/patterns/connectors/calendar-cli/example/package.json +2 -2
  28. package/skills/jskit/references/patterns/crud/crud-feature-package/example/packages/books/package.json +1 -1
  29. package/skills/jskit/references/patterns/realtime/realtime-application/example/package.json +2 -2
  30. package/skills/jskit/references/patterns/users/user-administration-server/example/packages/users/package.json +2 -2
  31. package/skills/jskit/references/patterns/users/user-administration-server/example/packages/users-workspace/package.json +4 -4
  32. package/skills/jskit/references/security-pass.md +131 -0
  33. package/skills/jskit/references/speed-pass.md +189 -0
  34. package/skills/jskit/references/ux-pass.md +111 -0
@@ -457,6 +457,97 @@ The supplied conversation routes open a conversation without a configuration,
457
457
  so the host notices a change where it opens the conversation for the person, or
458
458
  configures the person's open conversations when their profile changes.
459
459
 
460
+ ### Turn guard
461
+
462
+ An application can decide each new turn of the database-backed assistant before
463
+ anything is saved or sent, such as a topic check that answers off-topic
464
+ questions itself or a weekly message limit, by providing the optional
465
+ `assistant.turnGuard` capability from one of its features. Its `admit` returns
466
+ the decision for the person's message:
467
+
468
+ ```js
469
+ // src/server/MessageLimitFeature.js
470
+ import { defineFeature } from "@jskit-ai/kernel/server/features";
471
+ import { createTurnGuard } from "./turnGuard.js";
472
+
473
+ const MessageLimitFeature = defineFeature({
474
+ id: "messages.limit",
475
+ requires: {
476
+ usage: "messages.usage"
477
+ },
478
+ provides: {
479
+ turnGuard: "assistant.turnGuard"
480
+ },
481
+ /** @param {{ usage: import("./types.js").MessageUsage }} capabilities */
482
+ setup({ usage }) {
483
+ return { turnGuard: createTurnGuard({ usage }) };
484
+ }
485
+ });
486
+
487
+ export { MessageLimitFeature };
488
+
489
+ // src/server/turnGuard.js
490
+ import { resolveActor } from "@jskit-ai/kernel/server/actions/actionContributorHelpers";
491
+ import { AppError } from "@jskit-ai/kernel/server/runtime";
492
+ import { isOnTopic } from "./topics.js";
493
+
494
+ /** @param {{ usage: import("./types.js").MessageUsage }} dependencies */
495
+ function createTurnGuard({ usage }) {
496
+ /** @param {{ targetSurfaceId: string, context: object, input: string, conversationId: string | null, messageId: string }} request */
497
+ async function admit({ context, input, messageId }) {
498
+ // Counted once per message ID: a resent message is not counted again.
499
+ const week = await usage.countMessage({ userId: resolveActor(context).id, messageId });
500
+ if (week.count > week.limit) {
501
+ throw new AppError(429, "You have used this week's messages.", {
502
+ code: "weekly_limit",
503
+ details: { resetsOn: week.resetsOn }
504
+ });
505
+ }
506
+ if (!isOnTopic(input)) return { reply: "I can only help with questions about your orders." };
507
+ return { allowed: true };
508
+ }
509
+
510
+ return Object.freeze({
511
+ admit
512
+ });
513
+ }
514
+
515
+ export { createTurnGuard };
516
+ ```
517
+
518
+ `admit({ targetSurfaceId, context, input, conversationId, messageId })`
519
+ receives the surface, the request context with its actor, the message's text,
520
+ the conversation it continues (`null` for a new one) and the message's ID. It
521
+ returns one of two decisions, or a promise of one:
522
+
523
+ - **`{ allowed: true }`** runs the turn as usual.
524
+ - **`{ reply }`** answers the turn with that text instead of the model. The
525
+ message and the reply are saved as one completed turn and streamed like any
526
+ other answer, so they appear in the conversation's history, are restored with
527
+ it and are part of what the model reads on later turns. The model is never
528
+ called, and the turn resolves no AI connection, so it works even while none
529
+ is configured. The turn saves the message's text; files attached to it are
530
+ not read or saved.
531
+ - **A thrown `AppError` refuses the turn** with its status, code and details,
532
+ as the route's error response, before any stream starts. Nothing is saved,
533
+ so the same message sent again is a new turn that `admit` decides again. The
534
+ example's limit answers 429 with code `weekly_limit` and `{ resetsOn }`.
535
+ - **Anything else is a programming error.** Another value, such as
536
+ `{ allowed: false }` or an empty reply, fails the turn with a 500, and the
537
+ server logs an error naming the value it returned.
538
+
539
+ Each new turn asks `admit` once, after its message ID is checked for a replay
540
+ and before the turn is claimed. A replayed message ID answers from its saved
541
+ turn and never calls `admit` again. Two simultaneous requests with the same new
542
+ message ID can both pass the replay check and both call `admit`; only one of
543
+ them then claims the turn, and the other answers as a replay of it. A guard that
544
+ counts messages therefore counts each `messageId` once, for example with a
545
+ unique key on it.
546
+
547
+ Without `assistant.turnGuard`, every turn runs as before. An application that
548
+ supplies its own `assistant.conversations` decides its turns where it sends
549
+ them, so `AssistantFeature` does not read `assistant.turnGuard` there.
550
+
460
551
  ### Database surface action tools
461
552
 
462
553
  The assistant reads automation-capable actions from `runtime.actions`. It keeps
@@ -698,9 +789,13 @@ answer in the existing chat rows.
698
789
 
699
790
  Replies run on the agent engine (`@jskit-ai/agent`), up to 40 steps by default, so
700
791
  catalog search, contract lookup and execution can complete in one turn. A failed
701
- action reaches the model as its error: a refusal with its message and, for a
702
- validation error, the field errors a person would see on screen, so the model can
703
- say what to fix; an internal failure only as `Tool call failed.` A reply that runs
792
+ action reaches the model as its error: a refusal the application raised with its
793
+ message and, for a validation error, the field errors a person would see on screen,
794
+ so the model can say what to fix; a refusal json-rest-api raises itself, whose
795
+ developer text names internal resource types and ids, with its status and
796
+ `Tool call failed.`; an internal failure only as `Tool call failed.` To have the
797
+ model explain a refused write, refuse it in the action, in the application's own
798
+ words, before the write runs. A reply that runs
704
799
  out of steps ends with the model's own account of what it did and what is left.
705
800
  The engine's checks send a reply back once when it leaks markup, stops at
706
801
  announcing its next step (“Let me query…”), or claims an action no tool
@@ -735,7 +830,9 @@ Apply the package migrations before running the updated server. The runtime owns
735
830
  message-ID key. The database arbitrates concurrent requests across server
736
831
  processes before provider or tool execution. A reused ID with a different request
737
832
  returns a conflict. An identical retry replays the recorded answer or failure
738
- without calling the provider or tools again, including after a process restart.
833
+ without calling the provider or tools again, including after a process restart,
834
+ and without asking an application's turn guard again (see Turn guard above for
835
+ two simultaneous first sends).
739
836
  Pre-stream `AppError` failures retain their public code and details in the same
740
837
  request receipt. `ACTION_PERMISSION_DENIED` details remain private, and arbitrary
741
838
  non-`AppError` diagnostics are not added to the receipt. Older failure receipts
@@ -777,6 +874,11 @@ provider settings, authorization scope and action tools. Its adapter maps
777
874
  `streaming` to `inProgress`, `done` to `completed`, `error` to `failed`, and
778
875
  `canceled` to `interrupted`. Existing message IDs stay stable while text streams.
779
876
  Restored entries retain their database IDs; equal text is not a duplicate ID.
877
+ Each message's `storedId` is its saved row's ID: a restored message has it at
878
+ once, and a message sent in this view gets it when its turn completes (the
879
+ server's `done` event names the turn's two saved messages in
880
+ `storedMessageIds`). An unsaved message, such as a failed or stopped reply,
881
+ has `storedId: null`.
780
882
  Tool activity shows the existing tool name and status, never raw arguments or
781
883
  results. No provider reasoning is invented.
782
884
 
@@ -841,7 +943,22 @@ conversations are available through the Conversations dialog at every width.
841
943
  The current title remains visible. Activity opens the current tool-status list;
842
944
  setting `showToolActivity` to false hides presentation only. The
843
945
  `composer-tools` slot receives `{ runtime }` for application-owned supplementary
844
- controls. The element exposes `focus()` so a drawer owner can focus it once when
946
+ controls. The `message-actions` slot renders application-owned controls under
947
+ each assistant reply, after the reply's failed or stopped notice, and receives
948
+ `{ message }` with the reply's `id`, `storedId` and `role`:
949
+
950
+ ```vue
951
+ <AssistantSurfaceClientElement surface-id="home">
952
+ <template #message-actions="{ message }">
953
+ <v-btn v-if="message.storedId" size="small" variant="text" @click="report(message.storedId)">
954
+ {{ t("orders.assistant.report") }}
955
+ </v-btn>
956
+ </template>
957
+ </AssistantSurfaceClientElement>
958
+ ```
959
+
960
+ Act on `storedId`, which the server knows; `id` is the view's own identity for
961
+ the message. The element exposes `focus()` so a drawer owner can focus it once when
845
962
  opened and restore focus to the opener when closed.
846
963
 
847
964
  Page layout fills the viewport below its actual position, reserving the Vuetify
@@ -692,6 +692,22 @@ URL. Without a sender, production recovery is disabled; explicit development
692
692
  output remains available for local testing. A sender failure never falls back
693
693
  to development output. The generic recovery delivery capability is `email`.
694
694
 
695
+ The sender runs after the request has answered. Asking for a password reset
696
+ answers at once, and the same, whether or not the email has an account, so
697
+ neither the answer nor its time tells anyone which emails have accounts: local
698
+ auth looks the account up, makes its link and calls the sender only once the
699
+ request has answered. When the sender rejects, local auth logs the failure
700
+ with the address (never the link), and the person sees the same answer as for
701
+ any email; a delivery failure someone must act on belongs in the sender's own
702
+ monitoring, since an answer that reported it would say the account exists. A
703
+ stopping server waits up to 10 seconds for the emails still being sent. Asking
704
+ for a new confirmation link (`resendRegisterConfirmation`) and the
705
+ `auth.local.confirmation-sender` work the same way; a new registration's link
706
+ is still sent before its answer, which already says whether the email is
707
+ taken. A test that composes the library directly and reads the sent email
708
+ waits for it: it passes `deliveries: createLocalDeliveries({ logger })` to
709
+ `createLocalAuthService()` and awaits `deliveries.settled()`.
710
+
695
711
  Production is `NODE_ENV=production`; anything else, unset included, is
696
712
  development, so the host that serves the application sets it. A production
697
713
  server with `AUTH_LOCAL_RECOVERY_DEV_OUTPUT` set refuses to start and names the
@@ -0,0 +1,118 @@
1
+ <!-- Generated by `npm run agent-docs:build` from `packages/agent-docs/site/guide/app-setup/package-with-nix.md`. Do not edit manually. -->
2
+
3
+ ---
4
+ title: Package an App with Nix
5
+ description: Build a JSKIT app as one Nix package with no network access, for a host that runs apps only as Nix packages, without writing Nix.
6
+ ---
7
+
8
+ # Package an App with Nix
9
+
10
+ A host that runs apps only as Nix packages builds each one in Nix's sandbox,
11
+ with no network access, and runs nothing an app would install for itself.
12
+ JSKIT writes that packaging for every JSKIT app; nobody writes Nix for one.
13
+
14
+ ## Write package.nix
15
+
16
+ ```bash
17
+ npx jskit package nix
18
+ ```
19
+
20
+ It writes `package.nix` at the app's root. Commit it with the app. The file is
21
+ the same for every JSKIT app: it reads `package.json` and `package-lock.json`
22
+ while Nix evaluates it, so a changed lock file needs no change to it and there
23
+ is no hash to keep up to date. Each npm download is fetched by the integrity
24
+ hash `package-lock.json` gives it, as a fixed-output fetch, before the build;
25
+ the build itself has no network.
26
+
27
+ The command writes nothing, and says why, when:
28
+
29
+ - `package-lock.json` names a dependency a build cannot fetch by its hash: one
30
+ from git, a local file (`file:`), one with no integrity hash, or a link to a
31
+ folder outside the app. Publish such a package to a registry, or make it one
32
+ of the app's workspaces;
33
+ - `package.json` has no `name` or no `start` script;
34
+ - the app has no `package-lock.json`, or one npm 6 wrote (`lockfileVersion` 1);
35
+ - a `package.nix` it did not write is there. It never overwrites one.
36
+
37
+ Plain `jskit check`, and so the app's `npm run verify`, checks a `package.nix`
38
+ the command wrote: it must be the one the installed JSKIT writes
39
+ (`package/nix-current`: run the command again after `npm run jskit:update`),
40
+ and the app must still build with it (`package/nix-manifest`,
41
+ `package/nix-offline`). An app with no `package.nix`, or its own, is left
42
+ alone.
43
+
44
+ ## What the build does
45
+
46
+ `package.nix` is a function `{ pkgs }:` of the host's Nixpkgs that returns one
47
+ package:
48
+
49
+ 1. Node.js is the major version `engines.node` names first (`26.x` is
50
+ `pkgs.nodejs_26`), else Nixpkgs' default Node.js.
51
+ 2. The sources are the app's folder without `node_modules`, `.git`, and, at the
52
+ root, `dist`, `.jskit`, `coverage`, test results, `result` links and the
53
+ `.env` files (`.env.example` stays).
54
+ 3. npm installs `package-lock.json` (`npm ci`) offline, from a cache holding
55
+ exactly the tarballs Nix fetched, then runs the install scripts
56
+ (`npm rebuild`) as `npm ci` would: only those the root `package.json`'s
57
+ `allowScripts` approves, when npm asks for approval. A native addon compiles
58
+ there with node-gyp, against this Node's headers, with Python and a C
59
+ compiler from Nixpkgs. A prebuilt addon, inside its package or a package of
60
+ its own (a `-linux-x64` optional dependency), is a download like any other.
61
+ An install script that downloads something fails, as there is no network.
62
+ 4. `npm run build` runs when `package.json` has a `build` script (`vite build`
63
+ in a JSKIT app).
64
+ 5. The dev dependencies leave (`npm prune --omit=dev`), and the app's folder,
65
+ with `dist` and its production `node_modules`, becomes `lib/<name>` in the
66
+ package. Whatever the app runs while it runs must be a dependency, not a
67
+ devDependency: `db:migrate`'s `knex`, for one.
68
+
69
+ The package is named after `package.json`'s `name` without its scope, as a
70
+ program name (`@acme/shop_app` is `shop-app`), with its `version`. On a machine
71
+ with Nix:
72
+
73
+ ```bash
74
+ nix build --impure --expr 'import ./package.nix { pkgs = import <nixpkgs> { }; }'
75
+ ```
76
+
77
+ ## Its programs
78
+
79
+ The package's `bin/` holds the app's programs. Each takes `--env FILE`, a file
80
+ of environment variables in Node's `.env` format whose values win over the
81
+ environment's. The option is not called `--env-file` because Node reads an
82
+ `--env-file` anywhere on its command line, even after the script.
83
+
84
+ | Program | What it does |
85
+ | --- | --- |
86
+ | `<name> [--env FILE] [--migrate]` | Runs the app's `start` script as `npm start` would, without npm, in place of itself: from `lib/<name>`, with `node_modules/.bin` and Node first on `PATH`, and `NODE_ENV=production` unless the environment or the file says otherwise. With `--migrate`, runs `db:migrate` first and starts nothing when it fails. |
87
+ | `<name>-migrate [--env FILE]` | Runs the `db:migrate` script the same way. Only an app with one has it. |
88
+ | `<name>-check [--env FILE] [--wait SECONDS]` | Exits 0 once `GET /api/health` answers 200 on `HOST`:`PORT` (127.0.0.1 when `HOST` is unset or any address; port 3000 when `PORT` is unset), and 1 after `--wait` seconds (60). |
89
+ | `<name>-prepare --settings JSON --env FILE [--user NAME]` | Writes the settings, one JSON object of environment variables (each a string, a number or `true`/`false`), as `FILE`, mode 0600, owned by `NAME` (`chown NAME:`). It is for a host that hands an app's settings to a step run as root before its services start. |
90
+
91
+ ## Running it
92
+
93
+ - The app's folder is read-only. A JSKIT package that writes files keeps them
94
+ under the app's folder unless told otherwise, so point those at a writable
95
+ data folder in the settings: `JSKIT_STORAGE_FS_BASE_PATH` (uploads and
96
+ `runtime.storage`; `data/storage` by default) and `AUTH_LOCAL_STORE_DIR`
97
+ (local sign-in's files, such as the first account's setup code;
98
+ `.jskit/auth` by default).
99
+ - Secrets come at run time, in the env file or the service's environment,
100
+ never in the package: anyone who can read the Nix store can read a package.
101
+ - The server listens where its `server.js` says: in a JSKIT app, `HOST`
102
+ (0.0.0.0) and `PORT` (3000).
103
+ - The database comes from the app's own settings: `DATABASE_URL`, or
104
+ `DB_CLIENT`, `DB_HOST`, `DB_NAME` and the rest, as the
105
+ [database layer](/guide/app-setup/database-layer) guide says.
106
+ - Migrations run with `<name>-migrate` before the release starts, or with
107
+ `<name> --migrate` where the host has no such step. When several instances
108
+ start at once, Knex's migration lock lets one run them; the others fail and
109
+ start again once it is done, as a service restarted on failure does.
110
+
111
+ A host that runs apps as Nix packages typically runs the app `shop` as:
112
+
113
+ - a step run as root at each start, before the service:
114
+ `bin/shop-prepare --settings <the host's settings file> --env /run/shop/env --user shop`;
115
+ - one service, run as the user `shop`:
116
+ `bin/shop --env /run/shop/env --migrate`, on port 3000, healthy when
117
+ `/api/health` answers 200;
118
+ - a check after it starts: `bin/shop-check --env /run/shop/env`.
@@ -71,8 +71,10 @@ package, it refuses and names the import to use instead.
71
71
  and npm workspaces, and preflights every declared `@jskit-ai/*` package. It then
72
72
  updates all matching dependency, development-dependency, peer-dependency, and
73
73
  optional-dependency declarations as one validated manifest set. Non-JSKIT
74
- dependencies are unchanged. It installs once from the root and checks the new
75
- `package-lock.json` before succeeding.
74
+ dependencies are unchanged, except a direct `json-rest-api` pin, which moves to
75
+ the version JSKIT's packages require ([One json-rest-api](#one-json-rest-api)).
76
+ It installs once from the root and checks the new `package-lock.json` before
77
+ succeeding.
76
78
 
77
79
  During installation, the updater preserves non-JSKIT lockfile pins, removes the
78
80
  old JSKIT installation records from the candidate lock, and keeps the previous
@@ -176,6 +178,9 @@ The check fails when:
176
178
  - a JSKIT override tries to force a private graph;
177
179
  - a root/workspace declaration has no lockfile installation, or the lockfile is missing;
178
180
  - installed package versions or root/workspace declarations disagree with the lockfile.
181
+ - the app pins `json-rest-api` itself at another version than JSKIT's packages
182
+ require, or the lockfile installs more than one copy of it
183
+ ([One json-rest-api](#one-json-rest-api)).
179
184
  - a package script runs tests outside the machine's test budget (`test/*`, see
180
185
  [Test files run in parallel](/guide/framework/typed-features#test-files-run-in-parallel)).
181
186
  - an application package's manifest (`jskit.capabilities`) misses a capability
@@ -188,6 +193,20 @@ realtime runtime, and assistant runtime use exact peer dependencies where they
188
193
  must share application state. A partial upgrade can therefore fail during npm
189
194
  installation instead of silently nesting a second client stack.
190
195
 
196
+ ## One json-rest-api
197
+
198
+ `@jskit-ai/resource-runtime` and `@jskit-ai/crud-core` require `json-rest-api`
199
+ at one exact version, and json-rest-api knows its transactions by identity. An
200
+ app that also depends on `json-rest-api` at another version installs a second
201
+ copy, and every write its own `api.transaction` reaches inside JSKIT fails with
202
+ `RestApiWriteError: transaction must be an active transaction from
203
+ api.transaction; raw transactions and savepoints cannot own library writes`.
204
+ After an upgrade, or any change to the app's own `json-rest-api` declaration,
205
+ check that one copy is installed: `npm ls json-rest-api` shows one version, the
206
+ others marked deduped. `jskit check` refuses a direct pin at another version
207
+ and a second copy in the lockfile, naming the version to pin;
208
+ `npm run jskit:update` moves a direct pin with the catalog.
209
+
191
210
  ## Run tests within the test budget
192
211
 
193
212
  Plain `jskit check` fails a test run that ignores the machine's test budget
@@ -90,6 +90,7 @@ the filters match.
90
90
  | system scope | Why a feature works across every workspace and user, declared with `systemScope`. |
91
91
  | system context | The context of that work, from `systemContext(reason)`; `forWorkspace`, `forUser` and `forWorkspaceUser` narrow it. |
92
92
  | member context | The context of work done as one member of one workspace, from `workspaces.memberContext({ workspaceId, userId }, { context: systemContext(reason) })`: resolved as the member's request is, and signed in as them. |
93
+ | role context | The context of installer or seed work done in one workspace as a user in a role of the catalog they are not given there, from `workspaces.roleContext({ workspaceId, userId, role, reason }, { context: systemContext(reason) })`: a member context's shape, with an unsaved membership in that role and the reason. |
93
94
  | `txOptions` | What `withTransaction(options, work)` hands `work`: only the call's context and its transaction, `{ context, trx }`, passed to every call inside. |
94
95
  | record | What a handle answers: `{ id, ...fields }`, relationships as ids, included records nested. |
95
96
 
@@ -469,7 +470,8 @@ never loads everything the subject was ever linked to into an `IN` list, and
469
470
  never calls another owner's check once per item: it runs on every read, write
470
471
  read-back and lookup, so every request pays what it costs. A policy is told
471
472
  who the call runs for as `caller`: `{ kind: "user", userId }` for a signed-in
472
- request, `{ kind: "anonymous" }` for one by no one, and `{ kind: "system" }` or
473
+ request (and for a role context, with its `reason`, which grants nothing),
474
+ `{ kind: "anonymous" }` for one by no one, and `{ kind: "system" }` or
473
475
  `{ kind: "job" }` (a context `forWorkspace` and its kin derived), each with its
474
476
  `reason`, for background work. A job names a user only as `actorId`, the
475
477
  person it works for ([below](#background-work)), so never read a missing actor
@@ -831,7 +833,11 @@ match while it waited; with a `limit` it stops once it holds that many. A
831
833
  `limit` outside 1 to 1,000, or a `sort` on no stored field, is refused before
832
834
  any statement.
833
835
 
834
- A lock answers the rows it locks, with the fields `fields` names. Its
836
+ A lock answers the rows it locks, with the fields `fields` names. A belongs-to
837
+ field among them is checked against its target as last committed, as the lock
838
+ sees its own rows (on MySQL and MariaDB with a shared lock of the target until
839
+ commit), so a link to a target saved after the transaction's first plain read
840
+ shows, and a link to a target the caller may not see reads null. Its
835
841
  `include` names belongs-to relationships (`include: ["customer"]`, or
836
842
  `"batch.yard"` a level further): after its own rows, the lock locks the
837
843
  records they name through each related table's own handle (its scope, its row
@@ -852,7 +858,9 @@ sees what had committed when it began, so that read is current. On MySQL and
852
858
  MariaDB a plain read inside a transaction sees the snapshot of the
853
859
  transaction's first plain read, and a lock that waited does not move it. So
854
860
  take the lock before any plain read in the transaction: the reads after it then
855
- see what the lock's previous holder committed. A related row the work decides
861
+ see what the lock's previous holder committed. On MySQL and MariaDB a
862
+ `createMany` with `onConflict` reads its keys plainly first, so it counts as a
863
+ plain read here: lock, then upsert. A related row the work decides
856
864
  on (is this seat already booked?) is locked itself, through the lock's
857
865
  `include` or a lock of its own, or read after a lock that every writer of it
858
866
  takes first.
@@ -920,7 +928,16 @@ the sort's columns, ascending, and then nothing but the id, and the sort's
920
928
  fields go one way (all ascending or all descending). A unique key the filters
921
929
  fix whole, as a membership's workspace and user are, needs nothing more.
922
930
  `lockPages` locks in id order, so its index holds nothing after the ownership
923
- columns and the columns the filters fix but the id.
931
+ columns and the columns the filters fix but the id. In id order it walks the
932
+ owner's rows by id, so on MySQL and MariaDB a lock of the rows of a list
933
+ (every link of the listed actions) holds every row of the owner it passes too.
934
+ Name the list filter in `pageBy` (a filter whose search entry says
935
+ `filterOperator: "in"`, on the table's own column) and the pages follow that
936
+ column, then the id: `lockPages({ actionIds }, { ...txOptions, pageBy:
937
+ "actionIds" })` reads through an index that holds the column after the
938
+ ownership columns and the filters' other fixed columns, and holds the listed
939
+ values' rows alone. Give the values as the column stores them; the statements
940
+ still follow the pages, not the rows.
924
941
 
925
942
  A worker taking the next job uses `claim({ filters, sort, take }, txOptions)`,
926
943
  which skips rows another worker holds. A record that serializes work on a key
@@ -930,7 +947,15 @@ it locks the record, creating it from the row first when it is missing, and
930
947
  runs `work(record, txOptions)` in the same transaction, so failed work leaves
931
948
  no record behind. On its own it runs work once, so work may call a provider:
932
949
  two first uses of one id at once can collide on the insert, and the loser runs
933
- again before its work starts.
950
+ again before its work starts. On MySQL and MariaDB first uses of neighbouring
951
+ ids collide too: the lock of an id no row holds locks the gap where it would
952
+ go, and two such locks in one gap make both inserts wait for each other, a
953
+ deadlock the database ends by failing one. It locks before it inserts all the
954
+ same, since an upsert reads its keys plainly, and a plain read before the lock
955
+ would leave the work reading the rows as they stood before the record's
956
+ previous holder committed. In a transaction of its own it runs the loser
957
+ again; in the caller's, the caller's `withTransaction` runs the unit again when
958
+ it opened the transaction.
934
959
 
935
960
  Every lock takes `FOR UPDATE`, as `patchWhere` does for the rows it selects,
936
961
  which also keeps out another transaction's insert of a row that references the
@@ -998,7 +1023,13 @@ locks that read it, and work that locks through a policy and then writes a row
998
1023
  the policy read can deadlock with work doing the same (the database fails one,
999
1024
  and `withTransaction` runs it again). Give the policy's subqueries an index
1000
1025
  that finds the deciding rows directly, since on MySQL and MariaDB a locking
1001
- subquery locks every row it examines. `claim` keeps its policy's subqueries
1026
+ subquery locks every row it examines. The rows a subquery examines are the
1027
+ rows its plan walks, not the rows it returns: one that reads through another
1028
+ table by a link (a module's definition by its id) and narrows to the caller's
1029
+ owner after the walk locks the rows of every owner its index range crosses.
1030
+ Give each nested read a filter on the owner's columns that an index leads
1031
+ with, or keep the walk out of the lock: lock the rows, then check the linked
1032
+ rows with a read of their own. `claim` keeps its policy's subqueries
1002
1033
  plain reads. Rows
1003
1034
  of several owners are never locked in one statement over a join, which on
1004
1035
  MySQL and MariaDB locks every joined row the read examines: lock each owner's
@@ -1425,6 +1456,36 @@ const SettlementFeature = defineFeature({
1425
1456
  account its auth provider refuses at sign-in (a local account marked
1426
1457
  disabled) is still resolved; a job that must skip such people asks the
1427
1458
  provider first.
1459
+ - Installer and seed work the platform does in a workspace for a person who
1460
+ is no member there, or a member in another role (the required records a
1461
+ workspace gets for the platform's owner, a seed's starter data), acts in a
1462
+ role of the catalog with `workspaces.roleContext`, never with a hand-built
1463
+ membership:
1464
+
1465
+ ```js
1466
+ // requires: { workspaces: "workspaces.core" }; the feature declares systemScope
1467
+ const installer = await workspaces.roleContext(
1468
+ { workspaceId, userId: platformOwnerId, role: "owner", reason: "install the workspace's required records" },
1469
+ { context: systemContext("install each workspace's required records") }
1470
+ );
1471
+ ```
1472
+
1473
+ It has exactly a member context's shape: the user is its actor, its
1474
+ `membership` is `{ workspaceId, userId, roleSid, status: "active" }` in that
1475
+ role, never saved and replacing any membership the user has there, and its
1476
+ `permissions` are the role's, so a permission check and a row policy decide
1477
+ as for a member in that role, and an action it runs keeps that membership.
1478
+ It is no system context and no job: request row limits apply and other
1479
+ owners' hidden fields stay hidden. It records its `reason`, which a row
1480
+ policy reads as `caller.reason` and which grants nothing. Only a system
1481
+ context makes one, with a reason: any other context, a missing reason, ids
1482
+ that are no record ids and a role the catalog lacks are a TypeError before
1483
+ any statement; a missing or deleted workspace is 404
1484
+ `workspaces.workspace.notFound` and a user id naming no one 404
1485
+ `users.profile.notFound`. It reads the user, the workspace and its settings,
1486
+ and writes nothing. Work done as a real member takes `memberContext`, which
1487
+ refuses anyone who is not one; `roleContext` is for installer and seed work
1488
+ only, where the person is not given that role in the workspace.
1428
1489
  - A job finds its units with an `aggregate` grouped by the ownership field,
1429
1490
  which a system context may group by (and count distinct) even when the table
1430
1491
  hides it, then runs each unit scoped to it. It reads the units in pages, all
@@ -0,0 +1,136 @@
1
+ <!-- Generated by `npm run agent-docs:build` from `packages/agent-docs/site/guide/framework/security-pass.md`. Do not edit manually. -->
2
+
3
+ ---
4
+ title: Security pass
5
+ description: Where a JSKIT app decides who may do what, scopes rows to a workspace or a user, limits repeated requests, keeps sessions and secrets, and runs as production, and how to try each one.
6
+ ---
7
+
8
+ # Security pass
9
+
10
+ A security pass makes an app refuse what it should. Genesis's security pass
11
+ skill (`genesis-security-pass`) holds the method: map every way in, work
12
+ through authorization, sign-in, input, secrets, production settings and
13
+ dependencies, prove each finding by sending the input that breaks it, and keep
14
+ a test that fails without each fix. This page says where each of those lives in
15
+ a JSKIT app. The rules it applies are already in [Typed features](/guide/framework/typed-features),
16
+ [Data access](/guide/framework/data-access), [Authentication](/guide/app-setup/authentication),
17
+ [Workspace tenancy](/guide/app-setup/multi-homing) and the [sanity checks](/guide/framework/sanity-checks).
18
+
19
+ ## Who may call each route and action
20
+
21
+ - A route's `auth` is `"public"` unless it says otherwise, so a route
22
+ registered without `auth` answers anyone. List every `/api` route with its
23
+ `auth` (`"required"`, or `"own"` with `ownerParam` naming the route parameter
24
+ that must be the signed-in user's id) and its `permission`, and keep each
25
+ public route public on purpose.
26
+ - A workspace route registers under `/api/w/:workspaceSlug/...` with
27
+ `contextPolicy: "required"`: the server resolves the workspace and the
28
+ caller's membership from the slug and the session, and answers 404 or 403
29
+ before the handler runs
30
+ ([Workspace-scoped features and routes](/guide/app-setup/multi-homing#workspace-scoped-features-and-routes)).
31
+ - A surface's access policy guards pages in the browser only; the server reads
32
+ just `requireWorkspaceMembership: false` from it. A page hidden by
33
+ `requireAnyPermissions`, or a command whose `useCommand({ runPermissions })`
34
+ is false, still needs the route's own `auth` and `permission`.
35
+ - An action's `permission` is checked by the kernel before its input. A route
36
+ that bypasses actions, reading with `await request.callOptions()`, runs no
37
+ action permission, so its own `auth` and `permission` are its only gate
38
+ ([Layer 1](/guide/framework/data-access#layer-1-the-table-resource)).
39
+ An action on the `automation` channel is a tool the assistant may call as
40
+ the typing user.
41
+ - A rule that depends on the role reads `hasPermission(context.permissions, …)`,
42
+ never `includes()`, which misses `*` and `bookings.*` grants, and lists the
43
+ permission in `roleCatalog.customPermissions`
44
+ ([Role permissions](/guide/app-setup/multi-homing#role-permissions)).
45
+
46
+ ## Rows stay in their workspace
47
+
48
+ - A table resource's `ownership` (`workspace`, `user`, `workspace_user`,
49
+ `workspace_or_shared`, `system` or `public`) and its row policy scope every
50
+ handle call to the call's `options.context`, and only the owner feature
51
+ reaches the table ([The resource is the only door](/guide/framework/data-access#the-resource-is-the-only-door)).
52
+ Knex past the handle, a repository that drops the call's `options`, or a
53
+ context built by hand skips that scope: search for each. Confirm every
54
+ `public` table is meant to be read by anyone.
55
+ - Who acts is `resolveActor(context)`; the workspace comes from the context
56
+ only, never from the body or another input
57
+ ([Request context](/guide/framework/typed-features#request-context)). A row
58
+ policy decides from `caller` and the server-resolved `context.workspace`,
59
+ `context.membership` and `context.permissions`, never from request input.
60
+ - Jobs declare `systemScope` and narrow `systemContext(reason)` with
61
+ `forWorkspace`, `forUser` or `forWorkspaceUser`; work done as one member runs
62
+ in `workspaces.memberContext(…)`, which refuses a removed member as their
63
+ request would ([Background work](/guide/framework/data-access#background-work)).
64
+ - `expectScoped()` from `@jskit-ai/resource-runtime/test` runs a path as owner
65
+ A before and after seeding owner B, and fails when B's rows change A's answer
66
+ or B's rows change ([Tests](/guide/framework/data-access#tests)). Give each
67
+ workspace path one.
68
+
69
+ ## Sign-in, sessions and limits
70
+
71
+ - Auth's routes are limited per client address, and local auth makes an
72
+ account wait after repeated failures; both are on by default.
73
+ `config.auth.rateLimits` changes a limit and `false` removes one: a removed
74
+ limit is a finding unless the person chose it. Behind a proxy,
75
+ `TRUSTED_PROXIES` names it, or every client shares one count
76
+ ([Sign-in protection](/guide/app-setup/authentication#sign-in-protection)).
77
+ - Any other route that repetition can abuse (sending email or codes,
78
+ invitations, costly reads, calls to a paid service) declares
79
+ `rateLimit: { max, timeWindow }`, refused with 429 `kernel.http.rateLimited`.
80
+ Each limit gets a test expecting the 429.
81
+ - Sign-in cookies are httpOnly, and in production `Secure` with the `__Host-`
82
+ prefix; `AUTH_COOKIE_SAME_SITE` is `lax` or `strict`
83
+ ([Sign-in cookies and SameSite](/guide/app-setup/authentication#sign-in-cookies-and-samesite)).
84
+ Every unsafe `/api` method checks its CSRF token unless the route sets
85
+ `csrfProtection: false`; each route that does must authenticate its request
86
+ another way, as the pass sign-in route does with its signed pass.
87
+ - A dangerous action asks for a recent second factor with `secondFactor`
88
+ where the app uses one, and password-only sign-in sets
89
+ `AUTH_LOCAL_PASSWORD_MIN_LENGTH=15`
90
+ ([Second factor](/guide/app-setup/authentication#second-factor-local-auth)).
91
+ - Password recovery and a new confirmation link answer the same whether or not
92
+ an account exists. Give the app's own invitation, lookup and sign-up routes
93
+ the same answer.
94
+
95
+ ## Production settings and secrets
96
+
97
+ - `NODE_ENV=production`, set by the Deployment's Serve step, is JSKIT's only
98
+ production switch. There local auth requires `AUTH_LOCAL_SESSION_SECRET`,
99
+ refuses `AUTH_DEV_BYPASS_ENABLED` and `AUTH_LOCAL_RECOVERY_DEV_OUTPUT`, and
100
+ refuses to start without a confirmation sender while anyone may register
101
+ ([Production settings](/guide/framework/sanity-checks#production-settings)).
102
+ - On an empty production database the first account needs the setup code
103
+ (403 `auth.local.setup.codeRequired`), so whoever reaches a new deployment
104
+ first cannot own it. A registration or admin bootstrap of the app's own
105
+ needs the same protection
106
+ ([The first account in production](/guide/app-setup/authentication#the-first-account-in-production-local-auth)).
107
+ - `AUTH_LOCAL_SESSION_SECRET` and every other secret live in private Env, read
108
+ on the server, and the Deployment generates the session secret. Nothing
109
+ secret goes in `config/public.js`, which the browser imports, or in a
110
+ committed `.env` file or example.
111
+ - An internal failure is a plain `Error`, which the caller sees as "Internal
112
+ server error."; an `AppError`'s message is shown at any status, so it never
113
+ carries internals
114
+ ([Internal failures are plain errors](/guide/framework/typed-features#internal-failures-are-plain-errors)).
115
+ - `config.securityHeaders` sets the security headers. Production adds
116
+ transport security, framing protection and a content security policy that is
117
+ reported, not enforced, by default; enforce it once the pages run without
118
+ violations, and read the headers on a production build
119
+ ([Security headers](/guide/app-setup/initial-scaffolding#security-headers)).
120
+
121
+ ## Try each refusal
122
+
123
+ - Boot the server in a route test and sign each person in over `app.inject`,
124
+ one cookie jar each, sending the session's `csrfToken` as `csrf-token` with
125
+ every write ([Tests](/guide/framework/data-access#tests)).
126
+ - Send each attack and expect its refusal: no session (401
127
+ `auth.session.required`), a member without the route's permission (403), a
128
+ slug of a workspace the caller is not in (403), another workspace's record id
129
+ and `workspaceId` in the body (refused, or answered in the caller's own
130
+ workspace), a write without `csrf-token`, and one request past each
131
+ `rateLimit` (429). A body that does not validate, sent without a session,
132
+ must get the refusal, not field errors.
133
+ - Production settings: start the server with `NODE_ENV=production` and the
134
+ test database, and check that it stops without `AUTH_LOCAL_SESSION_SECRET`,
135
+ that registering asks for the setup code, and the response headers.
136
+ - Run `npm audit` and `npm run verify`.