@ultimat3/action 31.57.0 → 31.59.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CLAUDE.md CHANGED
@@ -38,7 +38,7 @@ Owns the `action` + `mutator` primitives and five projections. Tier 3. The MCP t
38
38
  | `audit-subject-target.ts` | `auditSubjectTarget()`: `x_audit` as a subject-erase target — overwrites who acted and the input, never deletes the row |
39
39
  | `transition.ts` | `transition()`: a MUTATOR factory over one entity column's state machine. Declares no error code — entity's three propagate |
40
40
  | `upload-flow.ts` | `uploadFlow()`: an ACTION factory, `{ request, confirm }` over storage's `grantUpload` (pending only) and `promoteAttachment`. No code of its own |
41
- | `native-answer.ts`, `action-answer.ts` | `native:` — a form POST's 303 + one-read flash (`useActionAnswer`); HTTP projection only |
41
+ | `native-answer.ts`, `action-answer.ts` | `native:` — a form POST's 303 + one-read flash (`useActionAnswer`, `useSubmissionId`; the id is `ctx.submission.id` in the handler); HTTP projection only |
42
42
  | — | opt-in flight control is **`@ultimat3/core`**'s `client-flight.ts` + `client-wire.ts`, imported from core — `src/index.ts` re-exports only the `ClientFlight`/`ClientRetry` types. There is no local copy and must not be one |
43
43
  | `job-handle.ts` | the `.job()` projection: an action as a queueable payload. **Not** consumed by `@ultimat3/jobs` — see Invariants |
44
44
  | `contract-test.ts` | assertions `x g action` emits |
package/README.md CHANGED
@@ -242,7 +242,13 @@ the action, and for a refusal its `code` and each issue's `path`/`rule`/`params`
242
242
  The next page reads it once, in `load`, with `useActionAnswer(action | name?)` — `null` with no
243
243
  request at all (the `llms.txt` build runs `load` with none); inside a context derived from a
244
244
  request it is `X_NO_REQUEST`, never a `null` that leaves the flash set. A `fetch`, the typed
245
- client, MCP and `.job()` are answered exactly as before. A `page.tsx` form posting to an action
245
+ client, MCP and `.job()` are answered exactly as before. The post's id is handed on, so an app can
246
+ key its own per-submission state to it: `ctx.submission?.id` in `handle` (absent for any call that
247
+ is not a native post) and `refusal.submission` in `native.refusal`. When the post lands on a path on
248
+ this site the same id is the redirect's `?x_answer=<id>` and the flash cookie's suffix, and
249
+ `useSubmissionId()` reads it on the page, clearing nothing; a landing on another origin carries
250
+ neither the id nor a flash, so only the handler and the refusal see it. The page reader needs the
251
+ request's own context, as `useActionAnswer` does: inside a scope derived from it, it is `X_NO_REQUEST`. A `page.tsx` form posting to an action
246
252
  with no `native` is an `X_NATIVE_FORM_UNANSWERED` warning on `main` at `x verify` (the
247
253
  `manifest` step), a refusal planned for `next`.
248
254
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ultimat3/action",
3
- "version": "31.57.0",
3
+ "version": "31.59.0",
4
4
  "description": "The action primitive: one declaration projected to route, OpenAPI, client, MCP tool, job handle, tests",
5
5
  "keywords": [
6
6
  "ultimate",
@@ -48,13 +48,13 @@
48
48
  "test": "bun test"
49
49
  },
50
50
  "dependencies": {
51
- "@ultimat3/cache": "31.57.0",
52
- "@ultimat3/core": "31.57.0",
53
- "@ultimat3/db": "31.57.0",
54
- "@ultimat3/entity": "31.57.0",
55
- "@ultimat3/http": "31.57.0",
56
- "@ultimat3/policy": "31.57.0",
57
- "@ultimat3/schema": "31.57.0",
58
- "@ultimat3/storage": "31.57.0"
51
+ "@ultimat3/cache": "31.59.0",
52
+ "@ultimat3/core": "31.59.0",
53
+ "@ultimat3/db": "31.59.0",
54
+ "@ultimat3/entity": "31.59.0",
55
+ "@ultimat3/http": "31.59.0",
56
+ "@ultimat3/policy": "31.59.0",
57
+ "@ultimat3/schema": "31.59.0",
58
+ "@ultimat3/storage": "31.59.0"
59
59
  }
60
60
  }
@@ -1,21 +1,94 @@
1
- // The flash a native form's answer leaves for the next render: one cookie, written by the HTTP
2
- // projection (`native-answer.ts`) and read once by the page that follows (`useActionAnswer`). Both
3
- // halves live here so the wire shape has one owner: the writer and the reader cannot drift.
1
+ // The flash a native form's answer leaves for the next render: one cookie PER SUBMISSION, written
2
+ // by the HTTP projection and read once by the next page. The redirect and cookie name carry the
3
+ // submission id, so concurrent tabs read their own answers. Both halves share one wire shape here.
4
4
 
5
- import { deleteCookie, hasRequest, setCookie, useRequestCookie } from '@ultimat3/http';
5
+ import { readCookies } from '@ultimat3/core';
6
+ import {
7
+ deleteCookie,
8
+ hasRequest,
9
+ setCookie,
10
+ useRequestContext,
11
+ useRequestCookie,
12
+ useRequestHeader,
13
+ } from '@ultimat3/http';
6
14
  import type { SchemaIssueParams } from '@ultimat3/schema';
7
15
  import { issueRuleFacts } from '@ultimat3/schema';
8
16
  import type { AnyAction } from './action';
9
17
  import { actionName } from './invoke';
10
18
 
11
- /** The cookie's name. Fixed: an app reads the answer through `useActionAnswer`, never by name. */
19
+ /**
20
+ * The cookie name's prefix: each submission's flash is `x_action_answer_<id>`. An app reads the
21
+ * answer through `useActionAnswer`, never by name.
22
+ */
12
23
  export const ACTION_ANSWER_COOKIE = 'x_action_answer';
13
24
 
25
+ /** The query parameter a native answer's redirect carries: the submission's id. */
26
+ export const ACTION_ANSWER_PARAM = 'x_answer';
27
+
28
+ /**
29
+ * The shape of a submission id: 12 base64url characters. Minted from 72 random bits, so a page
30
+ * cannot guess another tab's; the reader checks the shape only, never that we minted it.
31
+ */
32
+ const SUBMISSION_ID = /^[A-Za-z0-9_-]{12}$/;
33
+
34
+ /** A new submission id, from the platform's random source. */
35
+ export function newSubmissionId(): string {
36
+ const bytes = crypto.getRandomValues(new Uint8Array(9));
37
+ return btoa(String.fromCharCode(...bytes))
38
+ .replaceAll('+', '-')
39
+ .replaceAll('/', '_');
40
+ }
41
+
42
+ const cookieOf = (id: string): string => `${ACTION_ANSWER_COOKIE}_${id}`;
43
+
44
+ /** A query pair's name, decoded as `URLSearchParams` would read it; a malformed escape is kept raw. */
45
+ const pairName = (pair: string): string => {
46
+ const raw = (pair.split('=', 1)[0] ?? '').replaceAll('+', ' ');
47
+ try {
48
+ return decodeURIComponent(raw);
49
+ } catch {
50
+ return raw;
51
+ }
52
+ };
53
+
54
+ /**
55
+ * `to` with the submission's id on it, or `undefined` when `to` is not a path on this site: a
56
+ * target on another origin cannot read this origin's cookie, so it gets neither id nor flash.
57
+ * Every other byte of `to` is kept as written, empty segments included (a signed query stays
58
+ * signed): only an `x_answer` pair already there is dropped, and the id's pair is appended before the fragment.
59
+ */
60
+ export function withSubmission(to: string, id: string): string | undefined {
61
+ if (!to.startsWith('/') || to.startsWith('//') || to.startsWith('/\\')) return undefined;
62
+ const hashAt = to.indexOf('#');
63
+ const hash = hashAt === -1 ? '' : to.slice(hashAt);
64
+ const beforeHash = hashAt === -1 ? to : to.slice(0, hashAt);
65
+ const queryAt = beforeHash.indexOf('?');
66
+ const path = queryAt === -1 ? beforeHash : beforeHash.slice(0, queryAt);
67
+ const kept =
68
+ queryAt === -1
69
+ ? []
70
+ : beforeHash
71
+ .slice(queryAt + 1)
72
+ .split('&')
73
+ .filter((pair) => pairName(pair) !== ACTION_ANSWER_PARAM);
74
+ return `${path}?${[...kept, `${ACTION_ANSWER_PARAM}=${id}`].join('&')}${hash}`;
75
+ }
76
+
14
77
  /** Seconds the flash lives unread: long enough for a 303 to be followed, short enough to forget. */
15
78
  export const ACTION_ANSWER_MAX_AGE = 60;
16
79
 
17
- /** The encoded flash stays well under a browser's 4 KiB per cookie; issues past it are dropped. */
18
- const MAX_ENCODED = 3000;
80
+ /**
81
+ * One encoded flash's octets; issues past it are dropped. A quarter of `ACTION_ANSWER_BUDGET`:
82
+ * submissions that leave one browser at once each write theirs before any sees the others, so
83
+ * the cap per flash is what keeps even several concurrent ones well under a proxy's 8 KiB header.
84
+ */
85
+ const MAX_ENCODED = 1024;
86
+
87
+ /**
88
+ * Octets every unread flash may hold together in the `Cookie` header, the new one included: one
89
+ * browser cookie's worth, so unread submissions never push the header past a proxy's 8 KiB.
90
+ */
91
+ export const ACTION_ANSWER_BUDGET = 4096;
19
92
 
20
93
  /** One field's refusal: where (`path`), and which rule with its numbers — never the value, never prose. */
21
94
  export interface ActionAnswerIssue {
@@ -60,12 +133,33 @@ export function fitAnswer(answer: ActionAnswer): ActionAnswer {
60
133
  return { ...answer, issues, truncated: true };
61
134
  }
62
135
 
63
- /** Write the flash on the response to the request in scope. */
64
- export function writeActionAnswer(answer: ActionAnswer): void {
65
- setCookie(ACTION_ANSWER_COOKIE, JSON.stringify(fitAnswer(answer)), {
66
- maxAge: ACTION_ANSWER_MAX_AGE,
67
- sameSite: 'Lax',
68
- });
136
+ const FLASH_NAME = new RegExp(`^${ACTION_ANSWER_COOKIE}_[A-Za-z0-9_-]{12}$`);
137
+
138
+ /** The unread flashes the browser sent, oldest first (the order a browser lists them), with their octets. */
139
+ const unreadFlashes = (): readonly { readonly name: string; readonly octets: number }[] =>
140
+ readCookies(useRequestHeader('cookie'))
141
+ .filter(([name]) => FLASH_NAME.test(name))
142
+ .map(([name, value]) => ({
143
+ name,
144
+ octets: name.length + 1 + encodeURIComponent(value).length,
145
+ }));
146
+
147
+ /**
148
+ * Write the submission's flash on the response to the request in scope. Unread flashes of earlier
149
+ * submissions are cleared, oldest first, until all of them together fit `ACTION_ANSWER_BUDGET`: a
150
+ * tab whose flash was cleared reads `null`, the header never grows without bound.
151
+ */
152
+ export function writeActionAnswer(answer: ActionAnswer, id: string): void {
153
+ const value = JSON.stringify(fitAnswer(answer));
154
+ let total = cookieOf(id).length + 1 + encodeURIComponent(value).length;
155
+ const unread = unreadFlashes();
156
+ for (const flash of unread) total += flash.octets;
157
+ for (const flash of unread) {
158
+ if (total <= ACTION_ANSWER_BUDGET) break;
159
+ deleteCookie(flash.name, { sameSite: 'Lax' });
160
+ total -= flash.octets;
161
+ }
162
+ setCookie(cookieOf(id), value, { maxAge: ACTION_ANSWER_MAX_AGE, sameSite: 'Lax' });
69
163
  }
70
164
 
71
165
  /** An untrusted cookie value back into an answer, or `null`: it arrived from the browser. */
@@ -91,12 +185,32 @@ export function parseActionAnswer(raw: string | null): ActionAnswer | null {
91
185
  }
92
186
 
93
187
  /**
94
- * The flash cookie of the request in scope. With no request at all (the `llms.txt` pass running a
95
- * `load`, a job, a task) nobody submitted a form: `null`. A scope derived inside a request is still
96
- * that request, so it refuses (`X_NO_REQUEST`) rather than answer `null` and leave the flash set.
188
+ * The submission this request follows: the id its URL carries, if it has an id's shape. Nothing
189
+ * proves we minted it: a URL naming an id whose cookie holds a well-formed flash reads that flash,
190
+ * so a flash is a hint for the page to draw, never an authenticated fact. With no
191
+ * request at all (the `llms.txt` pass running a `load`, a job, a task) nobody submitted a form:
192
+ * `null`. A scope derived inside a request is still that request, so it refuses (`X_NO_REQUEST`)
193
+ * rather than answer `null` and leave the flash set.
194
+ */
195
+ function submissionOf(): string | null {
196
+ if (!hasRequest()) return null;
197
+ const id = useRequestContext().url.searchParams.get(ACTION_ANSWER_PARAM);
198
+ return id !== null && SUBMISSION_ID.test(id) ? id : null;
199
+ }
200
+
201
+ /**
202
+ * The id of the native submission this page follows, or `null`: the `x_answer` its URL carries, the
203
+ * same value the handler saw as `ctx.submission.id` and `native.refusal` as `refusal.submission`.
204
+ * It is how a page reads app state keyed to a submission (a typed-values echo) without a second id
205
+ * or query parameter of its own. Unlike `useActionAnswer` it reads and clears nothing, so a page may
206
+ * ask any number of times. `null` for a URL with no id or one that is not an id's shape, and outside
207
+ * a request. It reads the request's URL, so like `useActionAnswer` it needs the request's own
208
+ * context: inside a scope derived from it (`withChildContext`) it is `X_NO_REQUEST`, not `null`. Nothing proves the framework minted the id (a URL can name any), so state keyed to it
209
+ * is a hint for the page to draw, never an authenticated fact.
97
210
  */
98
- const answerCookie = (): string | null =>
99
- hasRequest() ? useRequestCookie(ACTION_ANSWER_COOKIE) : null;
211
+ export function useSubmissionId(): string | null {
212
+ return submissionOf();
213
+ }
100
214
 
101
215
  /**
102
216
  * The answer the last native form submission left, read ONCE: the cookie is cleared on read.
@@ -107,10 +221,12 @@ const answerCookie = (): string | null =>
107
221
  * and `null` outside a request: nobody submitted a form there.
108
222
  */
109
223
  export function useActionAnswer(target?: AnyAction | string): ActionAnswer | null {
110
- const answer = parseActionAnswer(answerCookie());
224
+ const id = submissionOf();
225
+ if (id === null) return null;
226
+ const answer = parseActionAnswer(useRequestCookie(cookieOf(id)));
111
227
  if (answer === null) return null;
112
228
  const name = typeof target === 'string' || target === undefined ? target : actionName(target);
113
229
  if (name !== undefined && answer.action !== name) return null;
114
- deleteCookie(ACTION_ANSWER_COOKIE, { sameSite: 'Lax' });
230
+ deleteCookie(cookieOf(id), { sameSite: 'Lax' });
115
231
  return answer;
116
232
  }
package/src/index.ts CHANGED
@@ -41,7 +41,7 @@ export type {
41
41
  } from './action';
42
42
  export { action, describeAction, isAction } from './action';
43
43
  export type { ActionAnswer, ActionAnswerIssue } from './action-answer';
44
- export { ACTION_ANSWER_COOKIE, useActionAnswer } from './action-answer';
44
+ export { ACTION_ANSWER_COOKIE, useActionAnswer, useSubmissionId } from './action-answer';
45
45
  export type { ActionDecide, ActionDecision, ActionRowDenial } from './action-decide';
46
46
  export type {
47
47
  ActionDecideArgs,
@@ -2,11 +2,11 @@
2
2
  // to a path, the outcome left in a flash (`action-answer.ts`). Read by the HTTP projection alone —
3
3
  // the same action answers `fetch`, the typed client, MCP and `.job()` exactly as it always did.
4
4
 
5
- import type { UltimateRequest } from '@ultimat3/http';
5
+ import type { RedirectStatus, UltimateRequest } from '@ultimat3/http';
6
6
  import { acceptsHtml, factsOf, hostlessPath, redirect, takeRedirect } from '@ultimat3/http';
7
7
  import type { AnyAction } from './action';
8
- import type { ActionAnswerIssue } from './action-answer';
9
- import { answerIssues, writeActionAnswer } from './action-answer';
8
+ import type { ActionAnswer, ActionAnswerIssue } from './action-answer';
9
+ import { answerIssues, newSubmissionId, withSubmission, writeActionAnswer } from './action-answer';
10
10
  import { defOf } from './invoke';
11
11
 
12
12
  /** What a refusal's path is chosen from: the stable code, its status, the fields it named. */
@@ -14,6 +14,15 @@ export interface ActionRefusal {
14
14
  readonly code: string;
15
15
  readonly status: number;
16
16
  readonly issues: readonly ActionAnswerIssue[];
17
+ /**
18
+ * This post's submission id: the one `ctx.submission.id` holds in the handler, and, when the post
19
+ * lands on a path on this site, the redirect carries as `?x_answer=`, the flash cookie ends in,
20
+ * and `useSubmissionId()` reads on the page that follows (a landing on another origin carries
21
+ * neither the id nor a flash, and has no page of ours to read it). Always set by the framework; typed optional so an `ActionRefusal` built by hand
22
+ * (a test) need not carry one. A refusal by the input schema runs no handler, so this is the one
23
+ * place such a refusal can learn it.
24
+ */
25
+ readonly submission?: string;
17
26
  }
18
27
 
19
28
  /**
@@ -100,8 +109,14 @@ export async function answerNatively(
100
109
  native: AnyNativeAnswer,
101
110
  call: () => Promise<unknown>,
102
111
  ): Promise<Response> {
112
+ const id = newSubmissionId();
103
113
  let output: unknown;
104
114
  try {
115
+ // The handler runs as an answer to THIS post: `ctx.submission.id` is the id the redirect will
116
+ // carry. Set on the request's own context, which the handler reads, and not on a derived child:
117
+ // a child does not carry the request's slots, and `setRedirect()`, a cookie and a header read
118
+ // would all refuse inside one. Every call that is not a native post never reaches this line.
119
+ req.ctx.submission = { id };
105
120
  output = await call();
106
121
  } catch (error) {
107
122
  const facts = factsOf(error);
@@ -110,21 +125,41 @@ export async function answerNatively(
110
125
  takeRedirect(req.ctx);
111
126
  const issues =
112
127
  typeof error === 'object' && error !== null ? answerIssues(Reflect.get(error, 'issues')) : [];
113
- const chosen = native.refusal?.({ code: facts.code, status: facts.status, issues });
128
+ const chosen = native.refusal?.({
129
+ code: facts.code,
130
+ status: facts.status,
131
+ issues,
132
+ submission: id,
133
+ });
114
134
  const to = chosen === undefined ? formPage(req) : landing(chosen, req.url);
115
135
  if (to === undefined) throw error;
116
- writeActionAnswer({
136
+ return answered(to, id, 303, {
117
137
  action: name,
118
138
  outcome: 'refusal',
119
139
  code: facts.code,
120
140
  issues,
121
141
  truncated: false,
122
142
  });
123
- return redirect(to, 303);
124
143
  }
125
144
  const asked = takeRedirect(req.ctx);
126
- writeActionAnswer({ action: name, outcome: 'success' });
127
- if (asked !== undefined) return redirect(asked.location, asked.status);
145
+ const success = { action: name, outcome: 'success' } as const;
146
+ if (asked !== undefined) return answered(asked.location, id, asked.status, success);
128
147
  // Committed: an unfollowable target still answers, on the form's page, else the site's root.
129
- return redirect(landing(native.success(output), req.url) ?? formPage(req) ?? '/', 303);
148
+ return answered(
149
+ landing(native.success(output), req.url) ?? formPage(req) ?? '/',
150
+ id,
151
+ 303,
152
+ success,
153
+ );
154
+ }
155
+
156
+ /**
157
+ * The redirect carrying the submission's id, with its flash. A target that is not a path on this
158
+ * site is followed as written, with no id and no flash: no page there could read either.
159
+ */
160
+ function answered(to: string, id: string, status: RedirectStatus, answer: ActionAnswer): Response {
161
+ const tagged = withSubmission(to, id);
162
+ if (tagged === undefined) return redirect(to, status);
163
+ writeActionAnswer(answer, id);
164
+ return redirect(tagged, status);
130
165
  }