@ultimat3/action 31.10.0 → 31.11.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 +6 -2
- package/README.md +80 -1
- package/package.json +9 -8
- package/src/action-answer.ts +107 -0
- package/src/action.ts +8 -0
- package/src/adapter.ts +10 -4
- package/src/audit-batch.ts +152 -0
- package/src/audit-input.ts +16 -2
- package/src/audit-postgres-row.ts +93 -0
- package/src/audit-postgres.ts +60 -62
- package/src/http.ts +8 -0
- package/src/index.ts +16 -0
- package/src/native-answer.ts +130 -0
- package/src/upload-flow.ts +208 -0
package/CLAUDE.md
CHANGED
|
@@ -5,7 +5,7 @@ Owns the `action` + `mutator` primitives and five projections. Tier 3. The MCP t
|
|
|
5
5
|
|
|
6
6
|
## Boundary
|
|
7
7
|
|
|
8
|
-
- May import: `core`, `schema` (t0), `cache`, `db`, `i18n`, `time` (t1), `entity`, `policy`, `http` (t2).
|
|
8
|
+
- May import: `core`, `schema` (t0), `cache`, `db`, `i18n`, `storage`, `time` (t1), `entity`, `policy`, `http` (t2).
|
|
9
9
|
`entity` through `record-wire.ts`; `db` through **`tx-scope.ts` only**. Full rule: `docs/history/action.md`.
|
|
10
10
|
- Never import: `query`, `jobs`, `realtime` (sideways), or any tier 4-5 package.
|
|
11
11
|
- Never re-implement authz, validation or caching — call `policy`, `schema`, `cache`.
|
|
@@ -37,6 +37,8 @@ Owns the `action` + `mutator` primitives and five projections. Tier 3. The MCP t
|
|
|
37
37
|
| `http-stream.ts` | `accept: text/event-stream` → `event: chunk`… then ONE `done` or `error`; a refusal before the handler is the ordinary problem response |
|
|
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
|
+
| `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 |
|
|
40
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 |
|
|
41
43
|
| `job-handle.ts` | the `.job()` projection: an action as a queueable payload. **Not** consumed by `@ultimat3/jobs` — see Invariants |
|
|
42
44
|
| `contract-test.ts` | assertions `x g action` emits |
|
|
@@ -62,7 +64,9 @@ Owns the `action` + `mutator` primitives and five projections. Tier 3. The MCP t
|
|
|
62
64
|
| `request-deadline.ts` | `requestDeadlineMs` — the app's `requestTimeoutMs`, resolved by http's own `defineHttpConfig` |
|
|
63
65
|
| `audit.ts` | the audit seam's TYPES, re-exported from `@ultimat3/core` (shared with `query`); the slot (`installAuditSink`, `@ultimat3/core/adapter`) is core's alone |
|
|
64
66
|
| `audit-memory.ts` | the process default: a bounded ring that DROPS, and counts what it dropped |
|
|
65
|
-
| `audit-postgres.ts` | the DURABLE sink —
|
|
67
|
+
| `audit-postgres.ts` | the DURABLE sink — append-only `x_audit`; one insert per record, or per batch (`groupCommit`) |
|
|
68
|
+
| `audit-postgres-row.ts` | a record as its row — the ONE projection both inserts bind |
|
|
69
|
+
| `audit-batch.ts` | `batchedAuditSink`: group commit, per-write verdict, flush on drain |
|
|
66
70
|
| `audit-input.ts` | what may be written DOWN: an `input` redacted through core's table and made JSON-representable on every path |
|
|
67
71
|
| `audit-gate.ts` | **the only** file that calls a sink, and where the two failure policies live |
|
|
68
72
|
| `type-pins.ts` | compile-time assertions `tsc` checks — what the erased view projects, and why `client()` is not part of it |
|
package/README.md
CHANGED
|
@@ -189,6 +189,31 @@ a stream. A chunk its schema refuses, or `stream:` beside a handle that is not a
|
|
|
189
189
|
aborts `ctx.signal`. Every typed-client method carries `.stream`, because the name-only `rpc` proxy
|
|
190
190
|
cannot see a declaration: +2,064 B per island that uses `rpc` (measured 2026-11-06).
|
|
191
191
|
|
|
192
|
+
## `native:` — a browser form's answer
|
|
193
|
+
|
|
194
|
+
A `<form method="post">` (scripting off, or the client router's submit) to an action declaring
|
|
195
|
+
`native` is answered `303` to `success(output)`, or — refused with a 4xx other than
|
|
196
|
+
`X_UNAUTHENTICATED`, which keeps the sign-in redirect — to
|
|
197
|
+
`refusal(refusal)`, else a `Referer` on this host. The outcome rides in a one-read flash cookie:
|
|
198
|
+
the action, and for a refusal its `code` and each issue's `path`/`rule`/`params`, never a value.
|
|
199
|
+
The next page reads it once, in `load`, with `useActionAnswer(action | name?)`. A `fetch`, the typed
|
|
200
|
+
client, MCP and `.job()` are answered exactly as before. A `page.tsx` form posting to an action
|
|
201
|
+
with no `native` is an `X_NATIVE_FORM_UNANSWERED` warning on `main` at `x verify` (the
|
|
202
|
+
`manifest` step), a refusal planned for `next`.
|
|
203
|
+
|
|
204
|
+
```ts
|
|
205
|
+
import { action, t } from '@ultimat3/action';
|
|
206
|
+
import { can } from '@ultimat3/policy';
|
|
207
|
+
|
|
208
|
+
export const createPost = action({
|
|
209
|
+
input: t.object({ title: t.string.min(3) }),
|
|
210
|
+
output: t.object({ id: t.string }),
|
|
211
|
+
policy: can('post:create'),
|
|
212
|
+
native: { success: (post) => `/posts/${post.id}`, refusal: () => '/posts/new' },
|
|
213
|
+
handle: async ({ input }) => ({ id: input.title }),
|
|
214
|
+
});
|
|
215
|
+
```
|
|
216
|
+
|
|
192
217
|
## Path derivation
|
|
193
218
|
|
|
194
219
|
One rule per app, declared once — `defineApi({ http: { pathStyle } })` — plus a per-action pin.
|
|
@@ -448,6 +473,47 @@ await moveOrder({ id, from: 'pending', to: 'paid' }, { ctx });
|
|
|
448
473
|
`table` is typed structurally (`TransitionTarget`), not imported — a real `Table` satisfies the
|
|
449
474
|
seam as written.
|
|
450
475
|
|
|
476
|
+
## `uploadFlow()` — an upload as one declaration
|
|
477
|
+
|
|
478
|
+
`As of 2026-11-12`. A direct upload is two writes, and an app used to write both: the grant and the
|
|
479
|
+
attach. `uploadFlow()` **returns the pair** — two `action`s, one `PRIMITIVE_FACTORIES` row — so each
|
|
480
|
+
half gets its route, typed client and contract tests, and `uploadFile({ file, grant: client.<request> })`
|
|
481
|
+
from `@ultimat3/storage` drives the browser half unchanged.
|
|
482
|
+
|
|
483
|
+
```ts
|
|
484
|
+
import { uploadFlow } from '@ultimat3/action';
|
|
485
|
+
import { can } from '@ultimat3/policy';
|
|
486
|
+
|
|
487
|
+
declare function postAuthor(postId: string): Promise<string | null>;
|
|
488
|
+
declare function setPostCover(postId: string, key: string): Promise<void>;
|
|
489
|
+
|
|
490
|
+
export const { request: requestPostCover, confirm: confirmPostCover } = uploadFlow({
|
|
491
|
+
name: 'cover', // the field: org/<org>/post/<id>/cover/…
|
|
492
|
+
// Both halves' `row:` loader — the policy judges what this returns, confirm lands on it.
|
|
493
|
+
target: async ({ id }) => ({
|
|
494
|
+
entity: 'post',
|
|
495
|
+
id: id ?? '',
|
|
496
|
+
authorId: id === undefined ? null : await postAuthor(id),
|
|
497
|
+
}),
|
|
498
|
+
accept: ['image/png', 'image/jpeg', 'image/webp'],
|
|
499
|
+
maxBytes: 5 * 1024 * 1024,
|
|
500
|
+
policy: can<unknown, { readonly authorId: string | null }>(
|
|
501
|
+
'post:update',
|
|
502
|
+
({ actor, row }) => row !== null && actor !== null && row.authorId === actor.id,
|
|
503
|
+
),
|
|
504
|
+
attached: ({ target, object }) => setPostCover(target.id, object.key), // idempotent: may re-run
|
|
505
|
+
});
|
|
506
|
+
```
|
|
507
|
+
|
|
508
|
+
| Rule | Why |
|
|
509
|
+
|---|---|
|
|
510
|
+
| `request` grants under `pending/`, **never** onto the row's key | a targeted grant puts unsniffed bytes where a row reads them, and is refused outright with an `uploadScanner` (`X_STORAGE_TARGET_UNSCANNED`) |
|
|
511
|
+
| `confirm` is `promoteAttachment` | the stored object is measured against `maxBytes`, its head **sniffed against `accept`** (`X_STORAGE_TYPE_REJECTED`, left pending) and scanned when a scanner is installed — the check a presigned s3 PUT cannot make |
|
|
512
|
+
| the org is the **actor's** | an actor with none is `X_TENANCY_ACTOR_ORG_REQUIRED` before anything is signed |
|
|
513
|
+
| `target` is both halves' `row:` loader | the `policy` judges the row the `id` names, once per call, before anything is signed or moved. A rule over the permission alone (`can('post:update')`) lets any holder attach to any post an `id` names: carry the column the rule reads (`authorId`) and check it |
|
|
514
|
+
| one `policy` for both halves | whoever may not attach to this row may not upload for it either |
|
|
515
|
+
| a doubled `confirm` answers the attached object | `X_STORAGE_ALREADY_PROMOTED` is caught and the object it names returned — only ever this row's key. `attached` runs on **every** successful confirm, a retry included, so a first call whose bytes moved but whose row write failed is completed by the retry: keep it idempotent |
|
|
516
|
+
|
|
451
517
|
## Determinism + idempotency
|
|
452
518
|
|
|
453
519
|
`serializeOpenApi(buildOpenApi())` sorts keys at every depth, iterates the registry
|
|
@@ -813,6 +879,7 @@ one would make three of them wrong.
|
|
|
813
879
|
|---|---|---|
|
|
814
880
|
| `memoryAuditSink({ maxRecords })` | the newest `DEFAULT_MAX_AUDIT_RECORDS` (1,000) records, verbatim. **It DROPS** — `dropped` counts what it discarded | `x dev`, tests |
|
|
815
881
|
| `postgresAuditSink({ executor })` | one append-only `x_audit` row per attempt. Drops nothing | anything that has to keep its trail |
|
|
882
|
+
| `postgresAuditSink({ executor, groupCommit: true })` | the same rows; concurrent attempts share one insert (`maxRecords` 256, `maxDelayMs` 5 by default, or pass `{ maxRecords, maxDelayMs }`) | a pod whose audited calls each wait on their own `INSERT` round trip |
|
|
816
883
|
|
|
817
884
|
The memory sink is bounded because a record pins a whole `Ctx`: at 50 audited writes a second an
|
|
818
885
|
unbounded array is 4.3M immortal records a day and the pod dies holding the trail it was
|
|
@@ -838,6 +905,14 @@ apply its own schema. Installing a sink stays your one line, deliberately: there
|
|
|
838
905
|
into a ring. `executor` is a client that already speaks `(text, values)` — never `Bun.sql`, whose
|
|
839
906
|
`.query` is `undefined`.
|
|
840
907
|
|
|
908
|
+
**Group commit is opt-in, and changes no failure policy.** `groupCommit` queues each record for up
|
|
909
|
+
to `maxDelayMs` (or until `maxRecords` are queued) and writes the batch as ONE
|
|
910
|
+
`insert … select … from jsonb_to_recordset($1)`; each `write()` resolves or rejects with its own
|
|
911
|
+
batch, so a failed statement is `X_AUDIT_SINK_FAILED` (or `X_QUERY_AUDIT_SINK_FAILED`) on every
|
|
912
|
+
call it carried — none succeeds silently. The queue flushes on drain, in the `inflight` phase,
|
|
913
|
+
before the pool closes. A sink of your own with a `writeMany(records)` gets the same through
|
|
914
|
+
`batchedAuditSink(sink, { maxRecords, maxDelayMs })` from `@ultimat3/action/adapter`.
|
|
915
|
+
|
|
841
916
|
`x_audit` carries the framework's own facts as columns — the action, the surface, the outcome,
|
|
842
917
|
the actor, the correlation ids, the idempotency key — and the parsed `input` as `jsonb`, redacted
|
|
843
918
|
through **core's own** `isRedactedKey` table, the one `defineEnv({ secret: true })` extends. So a
|
|
@@ -968,6 +1043,10 @@ The boot's installers live here, never on the `.` barrel: `installIdempotencySto
|
|
|
968
1043
|
`resetIdempotency()` / `resetMeterStore()`, the port types and the errors a store throws. An app
|
|
969
1044
|
swaps a store with `idempotencyStore:` / `meterStore:` in `apps/<app>/runtime.ts`.
|
|
970
1045
|
|
|
1046
|
+
`batchedAuditSink(sink, { maxRecords?, maxDelayMs? })` is group commit for any `BatchAuditSink`
|
|
1047
|
+
(an `AuditSink` with `writeMany`): `flush()`, `close()` (flush, then drop its drain hook) and
|
|
1048
|
+
`pending`. `postgresAuditSink({ groupCommit })` is this over the Postgres sink.
|
|
1049
|
+
|
|
971
1050
|
`overrideHandler(action, handle | undefined)` puts a test double where `handle` is, on every
|
|
972
1051
|
surface — a direct call, `.as()`, HTTP, MCP, `.job()`, `.stream()` (the drain reads it per call).
|
|
973
1052
|
The policy, the rate limit, the input parse, the meter, idempotency and the output parse still run
|
|
@@ -1040,7 +1119,7 @@ a job boundary the class is gone and the `code` is what survives — match on th
|
|
|
1040
1119
|
|
|
1041
1120
|
## Boundaries
|
|
1042
1121
|
|
|
1043
|
-
Tier 3. Imports `@ultimat3/core`, `schema`, `cache`, `db`, `entity`, `policy`, `http`. Never imports
|
|
1122
|
+
Tier 3. Imports `@ultimat3/core`, `schema`, `cache`, `db`, `storage`, `entity`, `policy`, `http`. Never imports
|
|
1044
1123
|
`query`, `jobs`, `realtime` (same tier) or anything above it — those import *this*.
|
|
1045
1124
|
|
|
1046
1125
|
## Supporting exports
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ultimat3/action",
|
|
3
|
-
"version": "31.
|
|
3
|
+
"version": "31.11.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,12 +48,13 @@
|
|
|
48
48
|
"test": "bun test"
|
|
49
49
|
},
|
|
50
50
|
"dependencies": {
|
|
51
|
-
"@ultimat3/cache": "31.
|
|
52
|
-
"@ultimat3/core": "31.
|
|
53
|
-
"@ultimat3/db": "31.
|
|
54
|
-
"@ultimat3/entity": "31.
|
|
55
|
-
"@ultimat3/http": "31.
|
|
56
|
-
"@ultimat3/policy": "31.
|
|
57
|
-
"@ultimat3/schema": "31.
|
|
51
|
+
"@ultimat3/cache": "31.11.0",
|
|
52
|
+
"@ultimat3/core": "31.11.0",
|
|
53
|
+
"@ultimat3/db": "31.11.0",
|
|
54
|
+
"@ultimat3/entity": "31.11.0",
|
|
55
|
+
"@ultimat3/http": "31.11.0",
|
|
56
|
+
"@ultimat3/policy": "31.11.0",
|
|
57
|
+
"@ultimat3/schema": "31.11.0",
|
|
58
|
+
"@ultimat3/storage": "31.11.0"
|
|
58
59
|
}
|
|
59
60
|
}
|
|
@@ -0,0 +1,107 @@
|
|
|
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.
|
|
4
|
+
|
|
5
|
+
import { deleteCookie, setCookie, useRequestCookie } from '@ultimat3/http';
|
|
6
|
+
import type { SchemaIssueParams } from '@ultimat3/schema';
|
|
7
|
+
import { issueRuleFacts } from '@ultimat3/schema';
|
|
8
|
+
import type { AnyAction } from './action';
|
|
9
|
+
import { actionName } from './invoke';
|
|
10
|
+
|
|
11
|
+
/** The cookie's name. Fixed: an app reads the answer through `useActionAnswer`, never by name. */
|
|
12
|
+
export const ACTION_ANSWER_COOKIE = 'x_action_answer';
|
|
13
|
+
|
|
14
|
+
/** Seconds the flash lives unread: long enough for a 303 to be followed, short enough to forget. */
|
|
15
|
+
export const ACTION_ANSWER_MAX_AGE = 60;
|
|
16
|
+
|
|
17
|
+
/** The encoded flash stays well under a browser's 4 KiB per cookie; issues past it are dropped. */
|
|
18
|
+
const MAX_ENCODED = 3000;
|
|
19
|
+
|
|
20
|
+
/** One field's refusal: where (`path`), and which rule with its numbers — never the value, never prose. */
|
|
21
|
+
export interface ActionAnswerIssue {
|
|
22
|
+
readonly path: string;
|
|
23
|
+
readonly rule?: string;
|
|
24
|
+
readonly params?: SchemaIssueParams;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export type ActionAnswer =
|
|
28
|
+
| { readonly action: string; readonly outcome: 'success' }
|
|
29
|
+
| {
|
|
30
|
+
readonly action: string;
|
|
31
|
+
readonly outcome: 'refusal';
|
|
32
|
+
readonly code: string;
|
|
33
|
+
readonly issues: readonly ActionAnswerIssue[];
|
|
34
|
+
/** `true` when issues were dropped to keep the cookie under its size. */
|
|
35
|
+
readonly truncated: boolean;
|
|
36
|
+
};
|
|
37
|
+
|
|
38
|
+
/** The issues a refusal carries, read member by member off whatever the error held. */
|
|
39
|
+
export function answerIssues(issues: unknown): readonly ActionAnswerIssue[] {
|
|
40
|
+
if (!Array.isArray(issues)) return [];
|
|
41
|
+
const out: ActionAnswerIssue[] = [];
|
|
42
|
+
for (const issue of issues as readonly unknown[]) {
|
|
43
|
+
const path = typeof issue === 'object' && issue !== null ? Reflect.get(issue, 'path') : null;
|
|
44
|
+
if (typeof path !== 'string') continue;
|
|
45
|
+
out.push({ path, ...issueRuleFacts(issue) });
|
|
46
|
+
}
|
|
47
|
+
return out;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
const encodedLength = (answer: ActionAnswer): number =>
|
|
51
|
+
encodeURIComponent(JSON.stringify(answer)).length;
|
|
52
|
+
|
|
53
|
+
/** The flash, cut to fit: whole issues dropped from the end, never a half-written one. */
|
|
54
|
+
export function fitAnswer(answer: ActionAnswer): ActionAnswer {
|
|
55
|
+
if (answer.outcome === 'success' || encodedLength(answer) <= MAX_ENCODED) return answer;
|
|
56
|
+
let issues = answer.issues;
|
|
57
|
+
while (issues.length > 0 && encodedLength({ ...answer, issues }) > MAX_ENCODED) {
|
|
58
|
+
issues = issues.slice(0, -1);
|
|
59
|
+
}
|
|
60
|
+
return { ...answer, issues, truncated: true };
|
|
61
|
+
}
|
|
62
|
+
|
|
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
|
+
});
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** An untrusted cookie value back into an answer, or `null`: it arrived from the browser. */
|
|
72
|
+
export function parseActionAnswer(raw: string | null): ActionAnswer | null {
|
|
73
|
+
if (raw === null || raw.length > MAX_ENCODED * 2) return null;
|
|
74
|
+
let value: unknown;
|
|
75
|
+
try {
|
|
76
|
+
value = JSON.parse(raw);
|
|
77
|
+
} catch {
|
|
78
|
+
return null;
|
|
79
|
+
}
|
|
80
|
+
if (typeof value !== 'object' || value === null) return null;
|
|
81
|
+
const action = Reflect.get(value, 'action');
|
|
82
|
+
const outcome = Reflect.get(value, 'outcome');
|
|
83
|
+
if (typeof action !== 'string' || action === '') return null;
|
|
84
|
+
if (outcome === 'success') return { action, outcome };
|
|
85
|
+
const code = Reflect.get(value, 'code');
|
|
86
|
+
if (outcome !== 'refusal' || typeof code !== 'string' || !/^X_[A-Z0-9_]+$/.test(code)) {
|
|
87
|
+
return null;
|
|
88
|
+
}
|
|
89
|
+
const issues = answerIssues(Reflect.get(value, 'issues'));
|
|
90
|
+
return { action, outcome, code, issues, truncated: Reflect.get(value, 'truncated') === true };
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* The answer the last native form submission left, read ONCE: the cookie is cleared on read.
|
|
95
|
+
* Call it from a route's `load` — a header after a stream's first flush is refused. Given an
|
|
96
|
+
* action, only that action's answer: two forms on one page do not read each other's outcome. A
|
|
97
|
+
* page that may not import the action (`app/` → `api/`) names it: `'createPost' satisfies keyof
|
|
98
|
+
* Api['actions']`. `null` on a `static`/`isr` page, which is rendered as nobody and sees no cookie.
|
|
99
|
+
*/
|
|
100
|
+
export function useActionAnswer(target?: AnyAction | string): ActionAnswer | null {
|
|
101
|
+
const answer = parseActionAnswer(useRequestCookie(ACTION_ANSWER_COOKIE));
|
|
102
|
+
if (answer === null) return null;
|
|
103
|
+
const name = typeof target === 'string' || target === undefined ? target : actionName(target);
|
|
104
|
+
if (name !== undefined && answer.action !== name) return null;
|
|
105
|
+
deleteCookie(ACTION_ANSWER_COOKIE, { sameSite: 'Lax' });
|
|
106
|
+
return answer;
|
|
107
|
+
}
|
package/src/action.ts
CHANGED
|
@@ -27,6 +27,7 @@ import type { JsonSchemaObject } from './json-schema';
|
|
|
27
27
|
import { jsonSchemaOf } from './json-schema';
|
|
28
28
|
import type { ActionMeter, ActionMeterFact, ResolvedLimit } from './meter';
|
|
29
29
|
import { assertMeterDeclaration, meterFact } from './meter';
|
|
30
|
+
import type { AnyNativeAnswer, NativeAnswer } from './native-answer';
|
|
30
31
|
import type { ActionPolicy, Surface } from './policy-gate';
|
|
31
32
|
import { fixedRateLimit } from './rate-limit-gate';
|
|
32
33
|
|
|
@@ -112,6 +113,12 @@ export interface ActionDef<
|
|
|
112
113
|
* source for one. The OpenAPI operation and the MCP tool publish it. Absent: today's open contract.
|
|
113
114
|
*/
|
|
114
115
|
readonly errors?: readonly string[];
|
|
116
|
+
/**
|
|
117
|
+
* The page a browser's own `<form method="post">` lands on: a 303 to `success(output)`, or to
|
|
118
|
+
* `refusal(refusal)` (else the form's page) with the code and field issues in a one-read flash
|
|
119
|
+
* (`useActionAnswer`). Read by the HTTP projection for a form POST alone (`native-answer.ts`).
|
|
120
|
+
*/
|
|
121
|
+
readonly native?: NativeAnswer<InferOutput<TOutput>>;
|
|
115
122
|
/**
|
|
116
123
|
* Record every attempt at this action through the installed `AuditSink` — allowed, denied and
|
|
117
124
|
* failed alike. Opt-in per declaration and never a global switch: a login and a price change
|
|
@@ -252,6 +259,7 @@ export interface AnyActionDef {
|
|
|
252
259
|
readonly deprecated?: Deprecation;
|
|
253
260
|
readonly idempotent?: boolean;
|
|
254
261
|
readonly errors?: readonly string[];
|
|
262
|
+
readonly native?: AnyNativeAnswer;
|
|
255
263
|
readonly audit?: boolean;
|
|
256
264
|
readonly stream?: StandardSchemaV1;
|
|
257
265
|
row?(args: { readonly input: unknown; readonly ctx: Ctx }): unknown;
|
package/src/adapter.ts
CHANGED
|
@@ -1,8 +1,14 @@
|
|
|
1
|
-
// `@ultimat3/action/adapter` — what an idempotency or
|
|
2
|
-
// port interfaces, the errors a store throws,
|
|
3
|
-
// the `.` barrel: an app swaps a store
|
|
4
|
-
// `
|
|
1
|
+
// `@ultimat3/action/adapter` — what an idempotency, meter or audit store is built and installed
|
|
2
|
+
// from: the port interfaces, the errors a store throws, the boot's installers with their resets,
|
|
3
|
+
// and group commit for a sink author's own `writeMany`. Never the `.` barrel: an app swaps a store
|
|
4
|
+
// in `apps/<app>/runtime.ts`, so the callers here are the cli boot, `@ultimat3/testing` and authors.
|
|
5
5
|
|
|
6
|
+
export type { BatchAuditSink, BatchedAuditSink, BatchedAuditSinkOptions } from './audit-batch';
|
|
7
|
+
export {
|
|
8
|
+
batchedAuditSink,
|
|
9
|
+
DEFAULT_AUDIT_BATCH_MAX_DELAY_MS,
|
|
10
|
+
DEFAULT_AUDIT_BATCH_MAX_RECORDS,
|
|
11
|
+
} from './audit-batch';
|
|
6
12
|
export {
|
|
7
13
|
IdempotencyReservationLostError,
|
|
8
14
|
IdempotencyStatusUnknownError,
|
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Group commit for an audit sink: concurrent audited calls share one `writeMany`, so a pod doing
|
|
3
|
+
* 200 audited writes a second pays a handful of round trips instead of 200. Each `write()` settles
|
|
4
|
+
* with ITS record — a refused batch is retried singly — so the audit gate's two failure policies
|
|
5
|
+
* see exactly what they saw before.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import { finiteCount, MAX_TIMER_MS, onShutdown } from '@ultimat3/core';
|
|
9
|
+
import type { AuditRecord, AuditSink } from './audit';
|
|
10
|
+
|
|
11
|
+
/** Records per batch, by default: one statement's worth, well under any driver's message limit. */
|
|
12
|
+
export const DEFAULT_AUDIT_BATCH_MAX_RECORDS = 256;
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* The longest a record waits for company, by default. It is latency every audited call pays when
|
|
16
|
+
* traffic is light, so it is a few milliseconds — about one Postgres round trip — and not more.
|
|
17
|
+
*/
|
|
18
|
+
export const DEFAULT_AUDIT_BATCH_MAX_DELAY_MS = 5;
|
|
19
|
+
|
|
20
|
+
/** A sink that can write several records in one round trip — what group commit needs underneath. */
|
|
21
|
+
export interface BatchAuditSink extends AuditSink {
|
|
22
|
+
writeMany(records: readonly AuditRecord[]): Promise<void>;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export interface BatchedAuditSinkOptions {
|
|
26
|
+
/** A full batch is sent at once, without waiting out `maxDelayMs`. A whole number ≥ 1. */
|
|
27
|
+
readonly maxRecords?: number | undefined;
|
|
28
|
+
/** How long the first record of a batch waits for more. A whole number ≥ 0; 0 is one tick. */
|
|
29
|
+
readonly maxDelayMs?: number | undefined;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export interface BatchedAuditSink extends BatchAuditSink {
|
|
33
|
+
/** Resolves when this record is stored; rejects with the sink's error when it is not. */
|
|
34
|
+
write(record: AuditRecord): Promise<void>;
|
|
35
|
+
/** Send what is queued now and wait for every batch in flight. Never rejects: the waiters do. */
|
|
36
|
+
flush(): Promise<void>;
|
|
37
|
+
/** `flush()`, then unregister the drain hook. A sink built per test or per boot calls it. */
|
|
38
|
+
close(): Promise<void>;
|
|
39
|
+
/** Records queued and not yet sent — at most `maxRecords`. */
|
|
40
|
+
readonly pending: number;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
interface Waiter {
|
|
44
|
+
readonly record: AuditRecord;
|
|
45
|
+
readonly resolve: () => void;
|
|
46
|
+
readonly reject: (error: unknown) => void;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Every waiter gets ITS record's verdict. A failed `writeMany` is retried one record at a time,
|
|
51
|
+
* because one record the store refuses (a byte `jsonb` cannot hold, a value over a column's
|
|
52
|
+
* limit) fails the whole statement, and that must fail ONE call, not every call it carried. A
|
|
53
|
+
* store that is down rejects each single too, so every waiter still gets an error, by IDENTITY
|
|
54
|
+
* of what its own write threw: `auditSettled` wraps it into `X_AUDIT_SINK_FAILED` per call. Never
|
|
55
|
+
* rejects itself — the waiters are where the failure belongs, and a rejection here would be an
|
|
56
|
+
* unhandled one on the timer.
|
|
57
|
+
*/
|
|
58
|
+
async function commit(sink: BatchAuditSink, batch: readonly Waiter[]): Promise<void> {
|
|
59
|
+
try {
|
|
60
|
+
await sink.writeMany(batch.map((waiter) => waiter.record));
|
|
61
|
+
} catch (error) {
|
|
62
|
+
if (batch.length === 1) batch[0]?.reject(error);
|
|
63
|
+
else await Promise.all(batch.map(single(sink)));
|
|
64
|
+
return;
|
|
65
|
+
}
|
|
66
|
+
for (const waiter of batch) waiter.resolve();
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
const single =
|
|
70
|
+
(sink: BatchAuditSink) =>
|
|
71
|
+
async (waiter: Waiter): Promise<void> => {
|
|
72
|
+
try {
|
|
73
|
+
await sink.write(waiter.record);
|
|
74
|
+
} catch (error) {
|
|
75
|
+
waiter.reject(error);
|
|
76
|
+
return;
|
|
77
|
+
}
|
|
78
|
+
waiter.resolve();
|
|
79
|
+
};
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* Wrap a `BatchAuditSink` so concurrent writes become one `writeMany`. The queue is bounded by
|
|
83
|
+
* `maxRecords` — a full queue is sent, never grown — so a record pins its `Ctx` for at most
|
|
84
|
+
* `maxDelayMs` plus one round trip.
|
|
85
|
+
*
|
|
86
|
+
* **Flushes on drain**: an `inflight`-phase shutdown hook, which runs after in-flight requests end
|
|
87
|
+
* and before the `close` phase shuts the pool the sink writes through. `postgresAuditSink({
|
|
88
|
+
* groupCommit: true })` is this over the Postgres sink; a custom sink with a `writeMany` wraps here.
|
|
89
|
+
*/
|
|
90
|
+
export function batchedAuditSink(
|
|
91
|
+
sink: BatchAuditSink,
|
|
92
|
+
options: BatchedAuditSinkOptions = {},
|
|
93
|
+
): BatchedAuditSink {
|
|
94
|
+
const maxRecords = finiteCount(
|
|
95
|
+
'batchedAuditSink',
|
|
96
|
+
'maxRecords',
|
|
97
|
+
options.maxRecords ?? DEFAULT_AUDIT_BATCH_MAX_RECORDS,
|
|
98
|
+
1,
|
|
99
|
+
);
|
|
100
|
+
const maxDelayMs = Math.min(
|
|
101
|
+
finiteCount(
|
|
102
|
+
'batchedAuditSink',
|
|
103
|
+
'maxDelayMs',
|
|
104
|
+
options.maxDelayMs ?? DEFAULT_AUDIT_BATCH_MAX_DELAY_MS,
|
|
105
|
+
),
|
|
106
|
+
MAX_TIMER_MS,
|
|
107
|
+
);
|
|
108
|
+
let queue: Waiter[] = [];
|
|
109
|
+
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
110
|
+
const inFlight = new Set<Promise<void>>();
|
|
111
|
+
|
|
112
|
+
const send = (): void => {
|
|
113
|
+
if (timer !== undefined) clearTimeout(timer);
|
|
114
|
+
timer = undefined;
|
|
115
|
+
if (queue.length === 0) return;
|
|
116
|
+
const batch = queue;
|
|
117
|
+
queue = [];
|
|
118
|
+
const settled = commit(sink, batch);
|
|
119
|
+
inFlight.add(settled);
|
|
120
|
+
void settled.then(() => inFlight.delete(settled));
|
|
121
|
+
};
|
|
122
|
+
|
|
123
|
+
const write = (record: AuditRecord): Promise<void> =>
|
|
124
|
+
new Promise<void>((resolve, reject) => {
|
|
125
|
+
queue.push({ record, resolve, reject });
|
|
126
|
+
if (queue.length >= maxRecords) send();
|
|
127
|
+
// Ref'd on purpose: a queued record is an audit row owed, and the process stays up to pay it.
|
|
128
|
+
else if (timer === undefined) timer = setTimeout(send, maxDelayMs);
|
|
129
|
+
});
|
|
130
|
+
|
|
131
|
+
const flush = async (): Promise<void> => {
|
|
132
|
+
send();
|
|
133
|
+
await Promise.all([...inFlight]);
|
|
134
|
+
};
|
|
135
|
+
|
|
136
|
+
const unregister = onShutdown('audit.batch', () => flush(), { phase: 'inflight' });
|
|
137
|
+
|
|
138
|
+
return {
|
|
139
|
+
write,
|
|
140
|
+
async writeMany(records: readonly AuditRecord[]): Promise<void> {
|
|
141
|
+
await Promise.all(records.map(write));
|
|
142
|
+
},
|
|
143
|
+
flush,
|
|
144
|
+
async close(): Promise<void> {
|
|
145
|
+
unregister();
|
|
146
|
+
await flush();
|
|
147
|
+
},
|
|
148
|
+
get pending(): number {
|
|
149
|
+
return queue.length;
|
|
150
|
+
},
|
|
151
|
+
};
|
|
152
|
+
}
|
package/src/audit-input.ts
CHANGED
|
@@ -44,7 +44,8 @@ export function auditableInput(value: unknown): unknown {
|
|
|
44
44
|
function walk(value: unknown, depth: number, ancestors: Set<object>): unknown {
|
|
45
45
|
if (value === null) return null;
|
|
46
46
|
const kind = typeof value;
|
|
47
|
-
if (kind === 'string'
|
|
47
|
+
if (kind === 'string') return storable(value as string) ? value : UNREPRESENTABLE;
|
|
48
|
+
if (kind === 'boolean') return value;
|
|
48
49
|
if (kind === 'number') return Number.isFinite(value) ? value : UNREPRESENTABLE;
|
|
49
50
|
// `bigint`, `function`, `symbol`, and `undefined` reached through an array hole.
|
|
50
51
|
if (kind !== 'object') return UNREPRESENTABLE;
|
|
@@ -68,7 +69,8 @@ function walk(value: unknown, depth: number, ancestors: Set<object>): unknown {
|
|
|
68
69
|
// The key decides before the value does, so a credential under a redacted name is never
|
|
69
70
|
// walked at all — `isRedactedKey` is core's, the same table `defineEnv({ secret: true })`
|
|
70
71
|
// extends, so a value that is `[redacted]` in a log line cannot be plaintext in a table.
|
|
71
|
-
if (
|
|
72
|
+
if (!storable(key)) out[UNREPRESENTABLE] = UNREPRESENTABLE;
|
|
73
|
+
else if (isRedactedKey(key)) out[key] = REDACTED;
|
|
72
74
|
else if (item !== undefined) out[key] = walk(item, depth + 1, ancestors);
|
|
73
75
|
}
|
|
74
76
|
return out;
|
|
@@ -76,3 +78,15 @@ function walk(value: unknown, depth: number, ancestors: Set<object>): unknown {
|
|
|
76
78
|
ancestors.delete(object);
|
|
77
79
|
}
|
|
78
80
|
}
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* Can Postgres hold this string? Not with a NUL — `jsonb` refuses `\u0000` (22P05) and `text`
|
|
84
|
+
* refuses the byte (22021) — and not with a lone surrogate, which is not UTF-8 at all. Named, not
|
|
85
|
+
* stripped: an altered string would be a row claiming the caller sent something they did not.
|
|
86
|
+
*/
|
|
87
|
+
function storable(value: string): boolean {
|
|
88
|
+
return !value.includes('\u0000') && !LONE_SURROGATE.test(value);
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** Under `u`, a surrogate PAIR is one code point, so `\p{Cs}` matches only a lone half. */
|
|
92
|
+
const LONE_SURROGATE = /\p{Cs}/u;
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
// One `AuditRecord` as its `x_audit` row: the allow-list projection both the one-row insert and
|
|
2
|
+
// group commit's many-row insert bind, so the two statements cannot drift apart on a column.
|
|
3
|
+
|
|
4
|
+
import type { Actor } from '@ultimat3/core';
|
|
5
|
+
import { uuidV7 } from '@ultimat3/core';
|
|
6
|
+
import type { AuditRecord } from './audit';
|
|
7
|
+
import { auditableInput } from './audit-input';
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* The columns a row binds, in `SQL_AUDIT_INSERT`'s parameter order (`audit-postgres.ts`) — and the keys of a
|
|
11
|
+
* `writeMany` row, so the one-row and the many-row statement read ONE projection (`rowOf`).
|
|
12
|
+
*/
|
|
13
|
+
export const AUDIT_COLUMNS = [
|
|
14
|
+
'id',
|
|
15
|
+
'at',
|
|
16
|
+
'action',
|
|
17
|
+
'mutator',
|
|
18
|
+
'surface',
|
|
19
|
+
'outcome',
|
|
20
|
+
'replayed',
|
|
21
|
+
'idempotency_key',
|
|
22
|
+
'failure_code',
|
|
23
|
+
'actor_id',
|
|
24
|
+
'actor_kind',
|
|
25
|
+
'org_id',
|
|
26
|
+
'on_behalf_of_id',
|
|
27
|
+
'on_behalf_of_kind',
|
|
28
|
+
'request_id',
|
|
29
|
+
'trace_id',
|
|
30
|
+
'locale',
|
|
31
|
+
'tz',
|
|
32
|
+
'build_id',
|
|
33
|
+
'role',
|
|
34
|
+
'input',
|
|
35
|
+
'primitive',
|
|
36
|
+
] as const;
|
|
37
|
+
|
|
38
|
+
export type AuditRow = Readonly<Record<(typeof AUDIT_COLUMNS)[number], unknown>>;
|
|
39
|
+
|
|
40
|
+
/** One record as its row, keyed and ordered as `AUDIT_COLUMNS` — both statements bind this. */
|
|
41
|
+
export function rowOf(record: AuditRecord): AuditRow {
|
|
42
|
+
const actor = record.ctx.actor;
|
|
43
|
+
const at = record.at instanceof Date && !Number.isNaN(record.at.getTime()) ? record.at : null;
|
|
44
|
+
const onBehalfOf = onBehalfOfOf(actor);
|
|
45
|
+
const input = auditableInput(record.input);
|
|
46
|
+
return {
|
|
47
|
+
id: uuidV7(),
|
|
48
|
+
at: at === null ? null : at.toISOString(),
|
|
49
|
+
// `name`, into the column the seam named before reads were audited: renaming it is a data
|
|
50
|
+
// migration for every installed table, and the value it holds is the same.
|
|
51
|
+
action: record.name,
|
|
52
|
+
mutator: record.mutator,
|
|
53
|
+
surface: record.surface,
|
|
54
|
+
outcome: record.outcome,
|
|
55
|
+
replayed: record.replayed,
|
|
56
|
+
idempotency_key: record.idempotencyKey,
|
|
57
|
+
failure_code: record.failure?.code ?? null,
|
|
58
|
+
actor_id: actor.id,
|
|
59
|
+
actor_kind: actor.kind,
|
|
60
|
+
org_id: actor.orgId ?? null,
|
|
61
|
+
on_behalf_of_id: onBehalfOf?.actorId ?? null,
|
|
62
|
+
on_behalf_of_kind: onBehalfOf?.actorKind ?? null,
|
|
63
|
+
request_id: record.ctx.requestId,
|
|
64
|
+
trace_id: record.ctx.traceId,
|
|
65
|
+
locale: record.ctx.locale,
|
|
66
|
+
tz: record.ctx.tz,
|
|
67
|
+
build_id: record.ctx.buildId,
|
|
68
|
+
role: record.ctx.role,
|
|
69
|
+
// `undefined` in means a parse that never produced an input, which is a NULL column and
|
|
70
|
+
// not the four characters `JSON.stringify(undefined)` does not produce either.
|
|
71
|
+
input: input === undefined ? null : JSON.stringify(input),
|
|
72
|
+
primitive: record.primitive,
|
|
73
|
+
};
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* Both halves of an impersonation, recorded and interpreted as NEITHER. `actor_id` is who the
|
|
78
|
+
* framework ran the attempt as and `on_behalf_of_*` is what `impersonate()` recorded; which of
|
|
79
|
+
* them an app calls "who did this" is the convention four apps model four ways, so the row carries
|
|
80
|
+
* the two facts and takes no position between them.
|
|
81
|
+
*
|
|
82
|
+
* Read through a guard rather than off the type: `Actor.onBehalfOf` is optional, and an actor
|
|
83
|
+
* minted by an app's own `resolveToken` is a plain object nothing in this package validated.
|
|
84
|
+
*/
|
|
85
|
+
function onBehalfOfOf(actor: Actor): { actorId: string; actorKind: string } | null {
|
|
86
|
+
const origin: unknown = actor.onBehalfOf;
|
|
87
|
+
if (typeof origin !== 'object' || origin === null) return null;
|
|
88
|
+
const record = origin as Record<string, unknown>;
|
|
89
|
+
const actorId = record['actorId'];
|
|
90
|
+
const actorKind = record['actorKind'];
|
|
91
|
+
if (typeof actorId !== 'string' || typeof actorKind !== 'string') return null;
|
|
92
|
+
return { actorId, actorKind };
|
|
93
|
+
}
|
package/src/audit-postgres.ts
CHANGED
|
@@ -1,14 +1,14 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* The durable audit sink: one append-only Postgres table, one
|
|
3
|
-
*
|
|
4
|
-
*
|
|
5
|
-
* production. Statements are spelled out so an agent can run the exact one it saw in a log.
|
|
2
|
+
* The durable audit sink: one append-only Postgres table, one row per record — an insert each, or
|
|
3
|
+
* one per batch under `groupCommit`. Without it the shortest edit clearing `X_AUDIT_SINK_MISSING`
|
|
4
|
+
* is `memoryAuditSink()`, a ring that DROPS. Statements are spelled out so an agent can run them.
|
|
6
5
|
*/
|
|
7
6
|
|
|
8
|
-
import type {
|
|
9
|
-
import {
|
|
10
|
-
import type {
|
|
11
|
-
import {
|
|
7
|
+
import type { PgExecutor } from '@ultimat3/core';
|
|
8
|
+
import type { AuditRecord } from './audit';
|
|
9
|
+
import type { BatchAuditSink, BatchedAuditSink, BatchedAuditSinkOptions } from './audit-batch';
|
|
10
|
+
import { batchedAuditSink } from './audit-batch';
|
|
11
|
+
import { rowOf } from './audit-postgres-row';
|
|
12
12
|
|
|
13
13
|
/**
|
|
14
14
|
* Applied by the boot, never by an app migration — the rule `SQL_IDEMPOTENCY_TABLE` follows, and
|
|
@@ -93,11 +93,43 @@ insert into x_audit (
|
|
|
93
93
|
)
|
|
94
94
|
`;
|
|
95
95
|
|
|
96
|
+
/**
|
|
97
|
+
* Group commit's statement: N rows in one round trip, as ONE `jsonb` parameter unpacked by
|
|
98
|
+
* `jsonb_to_recordset`. Not `unnest($1::uuid[], …)`: `PgExecutor` is structural, and how a JS
|
|
99
|
+
* array binds is the driver's business — a JSON text binds the same through every one of them.
|
|
100
|
+
* `input` travels as the text `write` binds and is cast here, so a JSON `null` input stays the
|
|
101
|
+
* jsonb `null` it is in a single-row insert and only an unparsed input is a SQL NULL.
|
|
102
|
+
*/
|
|
103
|
+
export const SQL_AUDIT_INSERT_MANY = `
|
|
104
|
+
insert into x_audit (
|
|
105
|
+
id, at, action, mutator, surface, outcome, replayed, idempotency_key, failure_code,
|
|
106
|
+
actor_id, actor_kind, org_id, on_behalf_of_id, on_behalf_of_kind,
|
|
107
|
+
request_id, trace_id, locale, tz, build_id, role, input, primitive
|
|
108
|
+
)
|
|
109
|
+
select
|
|
110
|
+
id, at, action, mutator, surface, outcome, replayed, idempotency_key, failure_code,
|
|
111
|
+
actor_id, actor_kind, org_id, on_behalf_of_id, on_behalf_of_kind,
|
|
112
|
+
request_id, trace_id, locale, tz, build_id, role, input::jsonb, primitive
|
|
113
|
+
from jsonb_to_recordset($1::jsonb) as r (
|
|
114
|
+
id uuid, at timestamptz, action text, mutator boolean, surface text, outcome text,
|
|
115
|
+
replayed boolean, idempotency_key text, failure_code text,
|
|
116
|
+
actor_id text, actor_kind text, org_id text, on_behalf_of_id text, on_behalf_of_kind text,
|
|
117
|
+
request_id text, trace_id text, locale text, tz text, build_id text, role text,
|
|
118
|
+
input text, primitive text
|
|
119
|
+
)
|
|
120
|
+
`;
|
|
121
|
+
|
|
96
122
|
export interface PostgresAuditSinkOptions {
|
|
97
123
|
readonly executor: PgExecutor;
|
|
124
|
+
/**
|
|
125
|
+
* Group commit: concurrent writes share one `SQL_AUDIT_INSERT_MANY`, and each `write()` still
|
|
126
|
+
* settles with its own batch (`batchedAuditSink`). `true` takes the defaults; an object sets
|
|
127
|
+
* `maxRecords` / `maxDelayMs`. Absent: one insert per record, as before.
|
|
128
|
+
*/
|
|
129
|
+
readonly groupCommit?: boolean | BatchedAuditSinkOptions | undefined;
|
|
98
130
|
}
|
|
99
131
|
|
|
100
|
-
export interface PostgresAuditSink extends
|
|
132
|
+
export interface PostgresAuditSink extends BatchAuditSink {
|
|
101
133
|
write(record: AuditRecord): Promise<void>;
|
|
102
134
|
}
|
|
103
135
|
|
|
@@ -119,62 +151,28 @@ export interface PostgresAuditSink extends AuditSink {
|
|
|
119
151
|
* `Cookie` headers — so a projection that walked it would write an app's database clients and its
|
|
120
152
|
* caller's credentials into an audit table. An app that wants more columns writes its own
|
|
121
153
|
* `AuditSink`; the seam is one method, and that is the extension point.
|
|
154
|
+
*
|
|
155
|
+
* `groupCommit` trades up to `maxDelayMs` of latency per audited call for one round trip per batch
|
|
156
|
+
* instead of per call; the sink then flushes on drain, before the pool closes.
|
|
122
157
|
*/
|
|
123
|
-
export function postgresAuditSink(
|
|
158
|
+
export function postgresAuditSink(
|
|
159
|
+
options: PostgresAuditSinkOptions & { readonly groupCommit: true | BatchedAuditSinkOptions },
|
|
160
|
+
): BatchedAuditSink;
|
|
161
|
+
export function postgresAuditSink(options: PostgresAuditSinkOptions): PostgresAuditSink;
|
|
162
|
+
export function postgresAuditSink(
|
|
163
|
+
options: PostgresAuditSinkOptions,
|
|
164
|
+
): PostgresAuditSink | BatchedAuditSink {
|
|
124
165
|
const exec = options.executor;
|
|
125
|
-
|
|
166
|
+
const sink: PostgresAuditSink = {
|
|
126
167
|
async write(record: AuditRecord): Promise<void> {
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
await exec.query(
|
|
132
|
-
uuidV7(),
|
|
133
|
-
at === null ? null : at.toISOString(),
|
|
134
|
-
// `name`, into the column the seam named before reads were audited: renaming it is a data
|
|
135
|
-
// migration for every installed table, and the value it holds is the same.
|
|
136
|
-
record.name,
|
|
137
|
-
record.mutator,
|
|
138
|
-
record.surface,
|
|
139
|
-
record.outcome,
|
|
140
|
-
record.replayed,
|
|
141
|
-
record.idempotencyKey,
|
|
142
|
-
record.failure?.code ?? null,
|
|
143
|
-
actor.id,
|
|
144
|
-
actor.kind,
|
|
145
|
-
actor.orgId ?? null,
|
|
146
|
-
onBehalfOf?.actorId ?? null,
|
|
147
|
-
onBehalfOf?.actorKind ?? null,
|
|
148
|
-
record.ctx.requestId,
|
|
149
|
-
record.ctx.traceId,
|
|
150
|
-
record.ctx.locale,
|
|
151
|
-
record.ctx.tz,
|
|
152
|
-
record.ctx.buildId,
|
|
153
|
-
record.ctx.role,
|
|
154
|
-
// `undefined` in means a parse that never produced an input, which is a NULL column and
|
|
155
|
-
// not the four characters `JSON.stringify(undefined)` does not produce either.
|
|
156
|
-
input === undefined ? null : JSON.stringify(input),
|
|
157
|
-
record.primitive,
|
|
158
|
-
]);
|
|
168
|
+
await exec.query(SQL_AUDIT_INSERT, Object.values(rowOf(record)));
|
|
169
|
+
},
|
|
170
|
+
async writeMany(records: readonly AuditRecord[]): Promise<void> {
|
|
171
|
+
if (records.length === 0) return;
|
|
172
|
+
await exec.query(SQL_AUDIT_INSERT_MANY, [JSON.stringify(records.map(rowOf))]);
|
|
159
173
|
},
|
|
160
174
|
};
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
* Both halves of an impersonation, recorded and interpreted as NEITHER. `actor_id` is who the
|
|
165
|
-
* framework ran the attempt as and `on_behalf_of_*` is what `impersonate()` recorded; which of
|
|
166
|
-
* them an app calls "who did this" is the convention four apps model four ways, so the row carries
|
|
167
|
-
* the two facts and takes no position between them.
|
|
168
|
-
*
|
|
169
|
-
* Read through a guard rather than off the type: `Actor.onBehalfOf` is optional, and an actor
|
|
170
|
-
* minted by an app's own `resolveToken` is a plain object nothing in this package validated.
|
|
171
|
-
*/
|
|
172
|
-
function onBehalfOfOf(actor: Actor): { actorId: string; actorKind: string } | null {
|
|
173
|
-
const origin: unknown = actor.onBehalfOf;
|
|
174
|
-
if (typeof origin !== 'object' || origin === null) return null;
|
|
175
|
-
const record = origin as Record<string, unknown>;
|
|
176
|
-
const actorId = record['actorId'];
|
|
177
|
-
const actorKind = record['actorKind'];
|
|
178
|
-
if (typeof actorId !== 'string' || typeof actorKind !== 'string') return null;
|
|
179
|
-
return { actorId, actorKind };
|
|
175
|
+
const group = options.groupCommit;
|
|
176
|
+
if (group === undefined || group === false) return sink;
|
|
177
|
+
return batchedAuditSink(sink, group === true ? {} : group);
|
|
180
178
|
}
|
package/src/http.ts
CHANGED
|
@@ -40,6 +40,7 @@ import {
|
|
|
40
40
|
schemaRef,
|
|
41
41
|
toOperationId,
|
|
42
42
|
} from './naming';
|
|
43
|
+
import { answerNatively, isNativeFormPost } from './native-answer';
|
|
43
44
|
import { withDeclaredErrors } from './openapi-errors';
|
|
44
45
|
import { assertActionRateLimit, fixedRateLimit } from './rate-limit-gate';
|
|
45
46
|
import { carriesRecords, recordResponse } from './record-wire';
|
|
@@ -151,6 +152,13 @@ function projectRoute(
|
|
|
151
152
|
if (streams && wantsEventStream(req.header('accept'))) {
|
|
152
153
|
return streamAnswer(def, (sink) => withChunkSink(sink, call));
|
|
153
154
|
}
|
|
155
|
+
// A browser's own form, to an action that declared where it lands: a 303 and a flash, the
|
|
156
|
+
// refusal included. Everything above — the policy, the idempotency, the write — is the same.
|
|
157
|
+
if (def.native !== undefined && isNativeFormPost(req)) {
|
|
158
|
+
const answered = await answerNatively(req, name, def.native, call);
|
|
159
|
+
if (key !== null) answered.headers.set(REPLAYED_HEADER, replayed ? '1' : '0');
|
|
160
|
+
return answered;
|
|
161
|
+
}
|
|
154
162
|
const result = await call();
|
|
155
163
|
// The one thing an action's return value cannot say. `setRedirect()` inside the handler
|
|
156
164
|
// is how a `<form method="post">` gets an answer a browser follows — a `Location` on the
|
package/src/index.ts
CHANGED
|
@@ -40,6 +40,8 @@ export type {
|
|
|
40
40
|
StreamActionDef,
|
|
41
41
|
} from './action';
|
|
42
42
|
export { action, describeAction, isAction } from './action';
|
|
43
|
+
export type { ActionAnswer, ActionAnswerIssue } from './action-answer';
|
|
44
|
+
export { ACTION_ANSWER_COOKIE, useActionAnswer } from './action-answer';
|
|
43
45
|
export { chunksRead } from './action-stream';
|
|
44
46
|
/**
|
|
45
47
|
* The app's API as a whole — `defineApi({ http: { pathStyle, mounts }, openapi })` — read back by
|
|
@@ -207,6 +209,8 @@ export type {
|
|
|
207
209
|
export { custom, isMutator, mutator } from './mutator';
|
|
208
210
|
export type { ActionPath } from './naming';
|
|
209
211
|
export { derivePath, inputSchemaName } from './naming';
|
|
212
|
+
export type { ActionRefusal, NativeAnswer } from './native-answer';
|
|
213
|
+
export { answersNatively } from './native-answer';
|
|
210
214
|
export type { BuildOpenApiOptions, OpenApiDocument, OpenApiInfo } from './openapi';
|
|
211
215
|
export { buildOpenApi, serializeOpenApi } from './openapi';
|
|
212
216
|
export { completeOpenApi, mountOpenApi } from './openapi-complete';
|
|
@@ -257,6 +261,18 @@ export {
|
|
|
257
261
|
*/
|
|
258
262
|
export type { TransitionDef, TransitionInput, TransitionTarget } from './transition';
|
|
259
263
|
export { transition } from './transition';
|
|
264
|
+
/**
|
|
265
|
+
* A direct upload as one declaration: `request` grants a pending PUT under the actor's org,
|
|
266
|
+
* `confirm` attaches it once storage has measured, sniffed and scanned it. A factory over `action`.
|
|
267
|
+
*/
|
|
268
|
+
export type {
|
|
269
|
+
UploadFlow,
|
|
270
|
+
UploadFlowAttached,
|
|
271
|
+
UploadFlowGrant,
|
|
272
|
+
UploadFlowOptions,
|
|
273
|
+
UploadFlowTarget,
|
|
274
|
+
} from './upload-flow';
|
|
275
|
+
export { uploadFlow } from './upload-flow';
|
|
260
276
|
/**
|
|
261
277
|
* `invoke`'s input parse and its `X_INPUT_INVALID` refusal, alone. Exported so a caller that must
|
|
262
278
|
* hold something else to an action's input — an agent eval's tool double (`@ultimat3/ai`) — runs
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
// The answer a browser's own `<form method="post">` gets from an action declaring `native`: a 303
|
|
2
|
+
// to a path, the outcome left in a flash (`action-answer.ts`). Read by the HTTP projection alone —
|
|
3
|
+
// the same action answers `fetch`, the typed client, MCP and `.job()` exactly as it always did.
|
|
4
|
+
|
|
5
|
+
import type { UltimateRequest } from '@ultimat3/http';
|
|
6
|
+
import { acceptsHtml, factsOf, hostlessPath, redirect, takeRedirect } from '@ultimat3/http';
|
|
7
|
+
import type { AnyAction } from './action';
|
|
8
|
+
import type { ActionAnswerIssue } from './action-answer';
|
|
9
|
+
import { answerIssues, writeActionAnswer } from './action-answer';
|
|
10
|
+
import { defOf } from './invoke';
|
|
11
|
+
|
|
12
|
+
/** What a refusal's path is chosen from: the stable code, its status, the fields it named. */
|
|
13
|
+
export interface ActionRefusal {
|
|
14
|
+
readonly code: string;
|
|
15
|
+
readonly status: number;
|
|
16
|
+
readonly issues: readonly ActionAnswerIssue[];
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* `native:` on an action. `success` names the page a submission lands on; `refusal` the page a
|
|
21
|
+
* refused one lands on — omitted, the form's own page (the same-origin `Referer`).
|
|
22
|
+
*/
|
|
23
|
+
export interface NativeAnswer<TOutput> {
|
|
24
|
+
readonly success: (output: TOutput) => string;
|
|
25
|
+
readonly refusal?: (refusal: ActionRefusal) => string;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** The schema-erased view `AnyActionDef` holds; method syntax keeps the parameter bivariant. */
|
|
29
|
+
export interface AnyNativeAnswer {
|
|
30
|
+
success(output: unknown): string;
|
|
31
|
+
refusal?(refusal: ActionRefusal): string;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
const FORM_TYPES = ['application/x-www-form-urlencoded', 'multipart/form-data'];
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* A browser's form submission — its own, or the client router's on its behalf: it asks for a
|
|
38
|
+
* page (`text/html`, the sniff `@ultimat3/http`'s error page answers on) and sends a form body.
|
|
39
|
+
* A `fetch` of JSON is neither, so the typed client is never answered with a redirect.
|
|
40
|
+
*/
|
|
41
|
+
export function isNativeFormPost(req: UltimateRequest): boolean {
|
|
42
|
+
if (!acceptsHtml(req.raw)) return false;
|
|
43
|
+
const type = (req.header('content-type') ?? '').toLowerCase();
|
|
44
|
+
return FORM_TYPES.some((form) => type.startsWith(form));
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** Does this action declare `native`? The `manifest` step's question, without the definition. */
|
|
48
|
+
export function answersNatively(target: AnyAction): boolean {
|
|
49
|
+
return defOf(target).native !== undefined;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* Where a 303 may go, or `undefined`. A target on this origin is its path, query and fragment,
|
|
54
|
+
* never starting `//` (`hostlessPath`). A SCHEME-LESS target that resolves to another origin —
|
|
55
|
+
* `//evil.test`, `/\evil.test`, `\\evil.test`, a leading space — is a path built from a request
|
|
56
|
+
* value that a browser reads as a host: never followed. An absolute `http(s):` URL is the app's own
|
|
57
|
+
* explicit choice (an OAuth client's callback) and kept as written; any other scheme is refused.
|
|
58
|
+
*/
|
|
59
|
+
function landing(to: string, here: URL): string | undefined {
|
|
60
|
+
if (!URL.canParse(to, here)) return undefined;
|
|
61
|
+
const resolved = new URL(to, here);
|
|
62
|
+
if (resolved.protocol !== 'http:' && resolved.protocol !== 'https:') return undefined;
|
|
63
|
+
if (resolved.origin === here.origin) {
|
|
64
|
+
return `${hostlessPath(resolved.pathname)}${resolved.search}${resolved.hash}`;
|
|
65
|
+
}
|
|
66
|
+
return URL.canParse(to) ? to : undefined;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* The form's own page: the `Referer`'s path and query, on THIS host only — a header the browser
|
|
71
|
+
* sent is never a place to send it elsewhere. A same-host Referer whose path reads as a host
|
|
72
|
+
* (`http://dev.test//evil.test`) is refused by `landing` like any other scheme-less target.
|
|
73
|
+
* `undefined` sends the refusal down the error path.
|
|
74
|
+
*/
|
|
75
|
+
function formPage(req: UltimateRequest): string | undefined {
|
|
76
|
+
const referer = req.header('referer');
|
|
77
|
+
if (referer === null || !URL.canParse(referer)) return undefined;
|
|
78
|
+
const from = new URL(referer);
|
|
79
|
+
if (from.host !== req.url.host || (from.protocol !== 'http:' && from.protocol !== 'https:')) {
|
|
80
|
+
return undefined;
|
|
81
|
+
}
|
|
82
|
+
return landing(`${from.pathname}${from.search}`, req.url);
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* A refusal a form can show: a 4xx. `X_UNAUTHENTICATED` alone keeps the sign-in redirect — it is
|
|
87
|
+
* the one code that redirect answers — so a sign-in's own 401 (a wrong password) lands back on its
|
|
88
|
+
* form with its code. A 5xx is a defect.
|
|
89
|
+
*/
|
|
90
|
+
const isRefusal = (facts: { readonly code: string; readonly status: number }): boolean =>
|
|
91
|
+
facts.status >= 400 && facts.status < 500 && facts.code !== 'X_UNAUTHENTICATED';
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* Run the call and answer the browser. A `setRedirect()` inside `handle` still wins for success —
|
|
95
|
+
* the one per-request fact `success(output)` cannot see (a sign-in's `next`).
|
|
96
|
+
*/
|
|
97
|
+
export async function answerNatively(
|
|
98
|
+
req: UltimateRequest,
|
|
99
|
+
name: string,
|
|
100
|
+
native: AnyNativeAnswer,
|
|
101
|
+
call: () => Promise<unknown>,
|
|
102
|
+
): Promise<Response> {
|
|
103
|
+
let output: unknown;
|
|
104
|
+
try {
|
|
105
|
+
output = await call();
|
|
106
|
+
} catch (error) {
|
|
107
|
+
const facts = factsOf(error);
|
|
108
|
+
if (!isRefusal(facts)) throw error;
|
|
109
|
+
// A refused handler may have asked for a redirect before it threw; it never gets it.
|
|
110
|
+
takeRedirect(req.ctx);
|
|
111
|
+
const issues =
|
|
112
|
+
typeof error === 'object' && error !== null ? answerIssues(Reflect.get(error, 'issues')) : [];
|
|
113
|
+
const chosen = native.refusal?.({ code: facts.code, status: facts.status, issues });
|
|
114
|
+
const to = chosen === undefined ? formPage(req) : landing(chosen, req.url);
|
|
115
|
+
if (to === undefined) throw error;
|
|
116
|
+
writeActionAnswer({
|
|
117
|
+
action: name,
|
|
118
|
+
outcome: 'refusal',
|
|
119
|
+
code: facts.code,
|
|
120
|
+
issues,
|
|
121
|
+
truncated: false,
|
|
122
|
+
});
|
|
123
|
+
return redirect(to, 303);
|
|
124
|
+
}
|
|
125
|
+
const asked = takeRedirect(req.ctx);
|
|
126
|
+
writeActionAnswer({ action: name, outcome: 'success' });
|
|
127
|
+
if (asked !== undefined) return redirect(asked.location, asked.status);
|
|
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);
|
|
130
|
+
}
|
|
@@ -0,0 +1,208 @@
|
|
|
1
|
+
// Single responsibility: a direct upload as ONE declaration — a factory over `action` that returns
|
|
2
|
+
// the pair every upload slice wrote by hand: `request` (a presigned PUT under the actor's org and
|
|
3
|
+
// `pending/`) and `confirm` (`promoteAttachment` onto the row: measured, sniffed against `accept`,
|
|
4
|
+
// scanned). Never a targeted grant: the bytes reach the row's key only after they were looked at.
|
|
5
|
+
|
|
6
|
+
import type { Ctx } from '@ultimat3/core';
|
|
7
|
+
import { tenancyActorOrgRequired } from '@ultimat3/entity';
|
|
8
|
+
import type { Infer } from '@ultimat3/schema';
|
|
9
|
+
import { t } from '@ultimat3/schema';
|
|
10
|
+
import type { StorageDriver, StorageObject, UploadPolicy } from '@ultimat3/storage';
|
|
11
|
+
import {
|
|
12
|
+
disk as defaultDisk,
|
|
13
|
+
grantUpload,
|
|
14
|
+
isStorageError,
|
|
15
|
+
promoteAttachment,
|
|
16
|
+
uploadPolicy,
|
|
17
|
+
} from '@ultimat3/storage';
|
|
18
|
+
import type { Action } from './action';
|
|
19
|
+
import { action } from './action';
|
|
20
|
+
import type { ActionPolicy } from './policy-gate';
|
|
21
|
+
|
|
22
|
+
/** The row a confirmed upload belongs to; the flow's `name` is the field segment. */
|
|
23
|
+
export interface UploadFlowTarget {
|
|
24
|
+
readonly entity: string;
|
|
25
|
+
readonly id: string;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* `TRule` is the row shape the policy reads, `TRow` what `target` returns: each inferred from its
|
|
30
|
+
* own option, and `TRow` must carry everything `TRule` names — else the `target` is the error.
|
|
31
|
+
*/
|
|
32
|
+
export interface UploadFlowOptions<
|
|
33
|
+
TRule = unknown,
|
|
34
|
+
TRow extends UploadFlowTarget & TRule = UploadFlowTarget & TRule,
|
|
35
|
+
> {
|
|
36
|
+
/** The field the file belongs to: the key is `org/<org>/<entity>/<id>/<name>/<opaque>`. */
|
|
37
|
+
readonly name: string;
|
|
38
|
+
/**
|
|
39
|
+
* The row, from the context and the `id` the call named (absent when it named none). It is BOTH
|
|
40
|
+
* halves' `row:` loader: `policy` decides about what this returns — carry the columns the rule
|
|
41
|
+
* reads (an `authorId`) — and `confirm` lands the bytes on that same row. Loaded once per call.
|
|
42
|
+
*/
|
|
43
|
+
readonly target: (args: {
|
|
44
|
+
readonly ctx: Ctx;
|
|
45
|
+
readonly id: string | undefined;
|
|
46
|
+
}) => TRow | Promise<TRow>;
|
|
47
|
+
/** The content types the grant signs and `confirm` holds the stored bytes to. */
|
|
48
|
+
readonly accept: readonly string[];
|
|
49
|
+
readonly maxBytes: number;
|
|
50
|
+
/**
|
|
51
|
+
* One rule for both halves, judged against `target`'s row: whoever may not attach to THIS row
|
|
52
|
+
* may not upload for it either. A rule over the permission alone lets any holder attach to any
|
|
53
|
+
* row an `id` names.
|
|
54
|
+
*/
|
|
55
|
+
readonly policy: ActionPolicy<TRule>;
|
|
56
|
+
/** Absent: the app's default disk, resolved per call. */
|
|
57
|
+
readonly disk?: (() => StorageDriver) | undefined;
|
|
58
|
+
/**
|
|
59
|
+
* Write `object.key` to the row here. Runs on EVERY successful confirm — a retry of one whose
|
|
60
|
+
* bytes already moved runs it again with the same key — until one succeeds, so it must be
|
|
61
|
+
* idempotent (a plain `update … set cover = key` is).
|
|
62
|
+
*/
|
|
63
|
+
readonly attached?:
|
|
64
|
+
| ((args: {
|
|
65
|
+
readonly ctx: Ctx;
|
|
66
|
+
readonly target: TRow;
|
|
67
|
+
readonly object: StorageObject;
|
|
68
|
+
}) => void | Promise<void>)
|
|
69
|
+
| undefined;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
const requestInput = t.object({
|
|
73
|
+
/** Used for its extension and nothing else — the stored name is opaque. */
|
|
74
|
+
filename: t.string.max(255),
|
|
75
|
+
contentType: t.string.max(255),
|
|
76
|
+
/** The file's size: the URL holds the upload to it, at the disk. */
|
|
77
|
+
size: t.number.int().min(1),
|
|
78
|
+
id: t.string.max(255).optional(),
|
|
79
|
+
});
|
|
80
|
+
|
|
81
|
+
const grantOutput = t.object({
|
|
82
|
+
key: t.string,
|
|
83
|
+
url: t.string,
|
|
84
|
+
method: t.enumerated('PUT'),
|
|
85
|
+
contentType: t.string,
|
|
86
|
+
maxBytes: t.number.int(),
|
|
87
|
+
/** Epoch ms. The grant's view of the window; the signature is what enforces it. */
|
|
88
|
+
expiresAt: t.number.int(),
|
|
89
|
+
});
|
|
90
|
+
|
|
91
|
+
const confirmInput = t.object({
|
|
92
|
+
/** The `pending/` key `request` answered. Anything else is refused by storage. */
|
|
93
|
+
key: t.string.max(1024),
|
|
94
|
+
id: t.string.max(255).optional(),
|
|
95
|
+
});
|
|
96
|
+
|
|
97
|
+
const attachedOutput = t.object({ key: t.string, contentType: t.string, size: t.number.int() });
|
|
98
|
+
|
|
99
|
+
export type UploadFlowGrant = Infer<typeof grantOutput>;
|
|
100
|
+
export type UploadFlowAttached = Infer<typeof attachedOutput>;
|
|
101
|
+
|
|
102
|
+
/** The pair, each exported by the app under its own name: `export const { request: … } = …`. */
|
|
103
|
+
export interface UploadFlow {
|
|
104
|
+
readonly request: Action<typeof requestInput, typeof grantOutput>;
|
|
105
|
+
readonly confirm: Action<typeof confirmInput, typeof attachedOutput>;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** The actor's tenant: an org read off the request is the bypass `grantUpload` exists to stop. */
|
|
109
|
+
function orgOf(ctx: Ctx, name: string, operation: string): string {
|
|
110
|
+
const orgId = ctx.actor.orgId;
|
|
111
|
+
if (orgId !== undefined) return orgId;
|
|
112
|
+
throw tenancyActorOrgRequired({
|
|
113
|
+
entityName: `uploadFlow(${name})`,
|
|
114
|
+
operation,
|
|
115
|
+
actorId: ctx.actor.id,
|
|
116
|
+
actorKind: ctx.actor.kind,
|
|
117
|
+
});
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
const answer = (object: StorageObject): UploadFlowAttached => ({
|
|
121
|
+
key: object.key,
|
|
122
|
+
contentType: object.contentType,
|
|
123
|
+
size: object.size,
|
|
124
|
+
});
|
|
125
|
+
|
|
126
|
+
/**
|
|
127
|
+
* A retried confirm whose first call moved the bytes is told where they are
|
|
128
|
+
* (`X_STORAGE_ALREADY_PROMOTED`, `meta.attachedKey`) and answers that object, `attached` run
|
|
129
|
+
* again: the first call may have moved the bytes and then failed to write the row. Gone since (a
|
|
130
|
+
* later upload replaced it): the refusal stands.
|
|
131
|
+
*/
|
|
132
|
+
async function promotedBefore(
|
|
133
|
+
error: unknown,
|
|
134
|
+
disk: StorageDriver,
|
|
135
|
+
): Promise<StorageObject | undefined> {
|
|
136
|
+
if (!isStorageError(error) || error.code !== 'X_STORAGE_ALREADY_PROMOTED') return undefined;
|
|
137
|
+
const attachedKey = error.meta?.['attachedKey'];
|
|
138
|
+
return typeof attachedKey === 'string' ? disk.stat(attachedKey) : undefined;
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
export function uploadFlow<TRow extends UploadFlowTarget & TRule, TRule = unknown>(
|
|
142
|
+
options: UploadFlowOptions<TRule, TRow>,
|
|
143
|
+
): UploadFlow {
|
|
144
|
+
const policy: UploadPolicy = uploadPolicy({
|
|
145
|
+
maxBytes: options.maxBytes,
|
|
146
|
+
allowedContentTypes: options.accept,
|
|
147
|
+
});
|
|
148
|
+
const diskOf = options.disk ?? (() => defaultDisk());
|
|
149
|
+
// The row the rule judged, handed to `handle`: `invoke` passes ONE input object to `row` and
|
|
150
|
+
// `handle` by reference (#702), so it keys the load without a second one.
|
|
151
|
+
const judged = new WeakMap<object, TRow>();
|
|
152
|
+
const row = async ({
|
|
153
|
+
input,
|
|
154
|
+
ctx,
|
|
155
|
+
}: {
|
|
156
|
+
readonly input: { readonly id?: string | undefined };
|
|
157
|
+
readonly ctx: Ctx;
|
|
158
|
+
}) => {
|
|
159
|
+
const loaded = await options.target({ ctx, id: input.id });
|
|
160
|
+
judged.set(input, loaded);
|
|
161
|
+
return loaded;
|
|
162
|
+
};
|
|
163
|
+
const rowOf = (input: { readonly id?: string | undefined }, ctx: Ctx): TRow | Promise<TRow> =>
|
|
164
|
+
judged.get(input) ?? options.target({ ctx, id: input.id });
|
|
165
|
+
|
|
166
|
+
const request = action({
|
|
167
|
+
input: requestInput,
|
|
168
|
+
output: grantOutput,
|
|
169
|
+
policy: options.policy,
|
|
170
|
+
row,
|
|
171
|
+
async handle({ input, ctx }) {
|
|
172
|
+
const orgId = orgOf(ctx, options.name, 'request');
|
|
173
|
+
const { filename, contentType, size } = input;
|
|
174
|
+
return grantUpload({
|
|
175
|
+
disk: diskOf(),
|
|
176
|
+
orgId,
|
|
177
|
+
request: { filename, contentType, size },
|
|
178
|
+
policy,
|
|
179
|
+
clock: ctx.clock,
|
|
180
|
+
});
|
|
181
|
+
},
|
|
182
|
+
});
|
|
183
|
+
|
|
184
|
+
const confirm = action({
|
|
185
|
+
input: confirmInput,
|
|
186
|
+
output: attachedOutput,
|
|
187
|
+
policy: options.policy,
|
|
188
|
+
row,
|
|
189
|
+
async handle({ input, ctx }) {
|
|
190
|
+
const orgId = orgOf(ctx, options.name, 'confirm');
|
|
191
|
+
const loaded = await rowOf(input, ctx);
|
|
192
|
+
const target = { entity: loaded.entity, id: loaded.id, field: options.name };
|
|
193
|
+
const disk = diskOf();
|
|
194
|
+
let object: StorageObject;
|
|
195
|
+
try {
|
|
196
|
+
object = await promoteAttachment({ disk, key: input.key, orgId, target, policy });
|
|
197
|
+
} catch (error) {
|
|
198
|
+
const earlier = await promotedBefore(error, disk);
|
|
199
|
+
if (earlier === undefined) throw error;
|
|
200
|
+
object = earlier;
|
|
201
|
+
}
|
|
202
|
+
await options.attached?.({ ctx, target: loaded, object });
|
|
203
|
+
return answer(object);
|
|
204
|
+
},
|
|
205
|
+
});
|
|
206
|
+
|
|
207
|
+
return { request, confirm };
|
|
208
|
+
}
|