@ultimat3/action 31.56.0 → 31.58.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/README.md CHANGED
@@ -386,8 +386,8 @@ no `.def`. A second authz path cannot be written without deleting that store.
386
386
  | parse output | `X_OUTPUT_INVALID` — and fields the schema never declared are dropped |
387
387
 
388
388
  **Who before what (`As of 2026-09`).** The actor half is the part of the policy that reads no
389
- input: `can(p)` with no predicate, `allow()`, `deny()`, their combinators, and `can(p, pred)` for
390
- an actor without `p`. It is decided before the parse — `decideBeforeInput` in `@ultimat3/policy`,
389
+ input: `can(p)` with no predicate, `canActor(p, pred)` (a predicate typed to read only the actor),
390
+ `allow()`, `deny()`, their combinators, and `can(p, pred)` for an actor without `p`. It is decided before the parse — `decideBeforeInput` in `@ultimat3/policy`,
391
391
  exact rather than a heuristic — so `can('refund:issue')` answers a customer's `{}` with 403, and a
392
392
  staff caller's `{}` with the 400 naming each missing field. A predicate over `input` or `row` still
393
393
  runs after the parse, on the parsed value. Same on HTTP, MCP (including the `invalid-args`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ultimat3/action",
3
- "version": "31.56.0",
3
+ "version": "31.58.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.56.0",
52
- "@ultimat3/core": "31.56.0",
53
- "@ultimat3/db": "31.56.0",
54
- "@ultimat3/entity": "31.56.0",
55
- "@ultimat3/http": "31.56.0",
56
- "@ultimat3/policy": "31.56.0",
57
- "@ultimat3/schema": "31.56.0",
58
- "@ultimat3/storage": "31.56.0"
51
+ "@ultimat3/cache": "31.58.0",
52
+ "@ultimat3/core": "31.58.0",
53
+ "@ultimat3/db": "31.58.0",
54
+ "@ultimat3/entity": "31.58.0",
55
+ "@ultimat3/http": "31.58.0",
56
+ "@ultimat3/policy": "31.58.0",
57
+ "@ultimat3/schema": "31.58.0",
58
+ "@ultimat3/storage": "31.58.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,18 @@ 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.
97
194
  */
98
- const answerCookie = (): string | null =>
99
- hasRequest() ? useRequestCookie(ACTION_ANSWER_COOKIE) : null;
195
+ const 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
+ };
100
200
 
101
201
  /**
102
202
  * The answer the last native form submission left, read ONCE: the cookie is cleared on read.
@@ -107,10 +207,12 @@ const answerCookie = (): string | null =>
107
207
  * and `null` outside a request: nobody submitted a form there.
108
208
  */
109
209
  export function useActionAnswer(target?: AnyAction | string): ActionAnswer | null {
110
- const answer = parseActionAnswer(answerCookie());
210
+ const id = submissionOf();
211
+ if (id === null) return null;
212
+ const answer = parseActionAnswer(useRequestCookie(cookieOf(id)));
111
213
  if (answer === null) return null;
112
214
  const name = typeof target === 'string' || target === undefined ? target : actionName(target);
113
215
  if (name !== undefined && answer.action !== name) return null;
114
- deleteCookie(ACTION_ANSWER_COOKIE, { sameSite: 'Lax' });
216
+ deleteCookie(cookieOf(id), { sameSite: 'Lax' });
115
217
  return answer;
116
218
  }
@@ -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. */
@@ -100,6 +100,7 @@ export async function answerNatively(
100
100
  native: AnyNativeAnswer,
101
101
  call: () => Promise<unknown>,
102
102
  ): Promise<Response> {
103
+ const id = newSubmissionId();
103
104
  let output: unknown;
104
105
  try {
105
106
  output = await call();
@@ -113,18 +114,33 @@ export async function answerNatively(
113
114
  const chosen = native.refusal?.({ code: facts.code, status: facts.status, issues });
114
115
  const to = chosen === undefined ? formPage(req) : landing(chosen, req.url);
115
116
  if (to === undefined) throw error;
116
- writeActionAnswer({
117
+ return answered(to, id, 303, {
117
118
  action: name,
118
119
  outcome: 'refusal',
119
120
  code: facts.code,
120
121
  issues,
121
122
  truncated: false,
122
123
  });
123
- return redirect(to, 303);
124
124
  }
125
125
  const asked = takeRedirect(req.ctx);
126
- writeActionAnswer({ action: name, outcome: 'success' });
127
- if (asked !== undefined) return redirect(asked.location, asked.status);
126
+ const success = { action: name, outcome: 'success' } as const;
127
+ if (asked !== undefined) return answered(asked.location, id, asked.status, success);
128
128
  // 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);
129
+ return answered(
130
+ landing(native.success(output), req.url) ?? formPage(req) ?? '/',
131
+ id,
132
+ 303,
133
+ success,
134
+ );
135
+ }
136
+
137
+ /**
138
+ * The redirect carrying the submission's id, with its flash. A target that is not a path on this
139
+ * site is followed as written, with no id and no flash: no page there could read either.
140
+ */
141
+ function answered(to: string, id: string, status: RedirectStatus, answer: ActionAnswer): Response {
142
+ const tagged = withSubmission(to, id);
143
+ if (tagged === undefined) return redirect(to, status);
144
+ writeActionAnswer(answer, id);
145
+ return redirect(tagged, status);
130
146
  }