@jskit-ai/agent-docs 0.1.327 → 0.1.329

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 +115 -2
  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 +19 -3
  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 +3 -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 +13 -0
  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 +19 -3
  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
@@ -735,7 +826,9 @@ Apply the package migrations before running the updated server. The runtime owns
735
826
  message-ID key. The database arbitrates concurrent requests across server
736
827
  processes before provider or tool execution. A reused ID with a different request
737
828
  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.
829
+ without calling the provider or tools again, including after a process restart,
830
+ and without asking an application's turn guard again (see Turn guard above for
831
+ two simultaneous first sends).
739
832
  Pre-stream `AppError` failures retain their public code and details in the same
740
833
  request receipt. `ACTION_PERMISSION_DENIED` details remain private, and arbitrary
741
834
  non-`AppError` diagnostics are not added to the receipt. Older failure receipts
@@ -777,6 +870,11 @@ provider settings, authorization scope and action tools. Its adapter maps
777
870
  `streaming` to `inProgress`, `done` to `completed`, `error` to `failed`, and
778
871
  `canceled` to `interrupted`. Existing message IDs stay stable while text streams.
779
872
  Restored entries retain their database IDs; equal text is not a duplicate ID.
873
+ Each message's `storedId` is its saved row's ID: a restored message has it at
874
+ once, and a message sent in this view gets it when its turn completes (the
875
+ server's `done` event names the turn's two saved messages in
876
+ `storedMessageIds`). An unsaved message, such as a failed or stopped reply,
877
+ has `storedId: null`.
780
878
  Tool activity shows the existing tool name and status, never raw arguments or
781
879
  results. No provider reasoning is invented.
782
880
 
@@ -841,7 +939,22 @@ conversations are available through the Conversations dialog at every width.
841
939
  The current title remains visible. Activity opens the current tool-status list;
842
940
  setting `showToolActivity` to false hides presentation only. The
843
941
  `composer-tools` slot receives `{ runtime }` for application-owned supplementary
844
- controls. The element exposes `focus()` so a drawer owner can focus it once when
942
+ controls. The `message-actions` slot renders application-owned controls under
943
+ each assistant reply, after the reply's failed or stopped notice, and receives
944
+ `{ message }` with the reply's `id`, `storedId` and `role`:
945
+
946
+ ```vue
947
+ <AssistantSurfaceClientElement surface-id="home">
948
+ <template #message-actions="{ message }">
949
+ <v-btn v-if="message.storedId" size="small" variant="text" @click="report(message.storedId)">
950
+ {{ t("orders.assistant.report") }}
951
+ </v-btn>
952
+ </template>
953
+ </AssistantSurfaceClientElement>
954
+ ```
955
+
956
+ Act on `storedId`, which the server knows; `id` is the view's own identity for
957
+ the message. The element exposes `focus()` so a drawer owner can focus it once when
845
958
  opened and restore focus to the opener when closed.
846
959
 
847
960
  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
@@ -981,9 +981,25 @@ SHARE OF` at all, and its `LOCK IN SHARE MODE` covers every row the statement
981
981
  examines, in every table. A report that needs another
982
982
  owner's rows unchanged until it commits first locks them through that owner's
983
983
  handle or owner API with `lockMode: "share"` (by a unique key with `limit:
984
- 1`), then reads its join. A row policy is not told a read's lock mode, and
985
- never takes a lock: it says which rows a caller may see, the same for every
986
- read, and the lock call it narrows takes its own mode. Rows
984
+ 1`), then reads its join. A row policy is not told a read's lock mode and
985
+ writes no lock clause: it says which rows a caller may see, the same for every
986
+ read. In a lock (`lock`, `lockMany`, `lockWhere`, `lockPages`), json-rest-api
987
+ gives each subquery of the policy (an `ownTable` read, another owner's
988
+ `joinSource`) a shared lock, `FOR SHARE` or `LOCK IN SHARE MODE`, whatever the
989
+ lock's mode. A plain subquery there decides from a snapshot: on MySQL and
990
+ MariaDB the one the transaction's first plain read fixed, so a member removed
991
+ since would still lock the rows, and on PostgreSQL, after the lock waited for
992
+ its row, the one its statement began with. The shared lock reads the
993
+ membership and grant rows as last committed, waits for a transaction changing
994
+ them, and keeps them unchanged until commit, while other locks that read them
995
+ go on at once: exclusive locks there would make every lock that reads one
996
+ membership wait for the others. So a change to a membership waits for the
997
+ locks that read it, and work that locks through a policy and then writes a row
998
+ the policy read can deadlock with work doing the same (the database fails one,
999
+ and `withTransaction` runs it again). Give the policy's subqueries an index
1000
+ 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
1002
+ plain reads. Rows
987
1003
  of several owners are never locked in one statement over a join, which on
988
1004
  MySQL and MariaDB locks every joined row the read examines: lock each owner's
989
1005
  rows with its own `lock`, `lockMany` or `lockWhere`, the owners in one fixed
@@ -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`.