@ancientpantheon/khronoton-core 0.2.0 → 0.4.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.
@@ -0,0 +1,363 @@
1
+ import { ReactNode } from 'react';
2
+ import { b as CodexTxConfig, c as CodexGasPayer, d as CodexSigner, S as ScheduleMode, e as ScheduleConfig, C as CodexCronotonRow, a as CodexCronotonFireRow, M as ManualBatchView } from './types-u_nUX1Bg.js';
3
+
4
+ /** A validated bag of runtime args — every value is a string (Pact `read-string`). */
5
+ type RuntimeArgs = Record<string, string>;
6
+
7
+ /**
8
+ * The framework-agnostic HTTP contract for `@ancientpantheon/khronoton-core/handlers`.
9
+ *
10
+ * A handler never imports an HTTP framework object. The CONSUMER adapts its
11
+ * framework's request/response (Next route handler, Express, Fastify, a test
12
+ * driver, …) into {@link HandlerRequest} / {@link HandlerResponse} at the call
13
+ * boundary: read `params`/`query`/`body` off the incoming request, set the
14
+ * consumer's confirm signal on `confirmed`, then write the returned
15
+ * `{ status, body }` back onto its native response.
16
+ *
17
+ * This module owns the error contract too: {@link mapStoreError} translates the
18
+ * typed store errors from `/server` into the HTTP status the route surface
19
+ * promises, and {@link json} / {@link errorBody} shape a response body. The
20
+ * signer descriptor seam ({@link SignerSource} + {@link CodexSignerDescriptor})
21
+ * lives here as a shared, secret-free contract the read handlers consume.
22
+ */
23
+
24
+ /**
25
+ * A framework-neutral request. The consumer populates it from its own request
26
+ * object: `params` from the route match, `query` from the URL search params,
27
+ * `body` from the parsed JSON payload, and `confirmed` from whatever fresh-admin
28
+ * -confirm signal the consumer's auth flow produced (the auth seam interprets it).
29
+ */
30
+ interface HandlerRequest {
31
+ params?: Record<string, string>;
32
+ query?: Record<string, string | string[] | undefined>;
33
+ body?: unknown;
34
+ /** The consumer's signal that a fresh admin-confirm accompanied this request. */
35
+ confirmed?: boolean;
36
+ }
37
+ /** A framework-neutral response the consumer writes back onto its native response. */
38
+ interface HandlerResponse {
39
+ status: number;
40
+ body: unknown;
41
+ }
42
+ /**
43
+ * A secret-free signer projection: only the public key and a coarse provenance
44
+ * label. NEVER carries key material — this is the invariant every
45
+ * {@link SignerSource} implementation must uphold regardless of how much
46
+ * provenance it knows.
47
+ */
48
+ interface CodexSignerDescriptor {
49
+ publicKey: string;
50
+ display: "derived" | "foreign";
51
+ }
52
+ /** Enumerates the signer descriptors the consumer's key store can sign for. */
53
+ interface SignerSource {
54
+ listSignerDescriptors(): Promise<CodexSignerDescriptor[]>;
55
+ }
56
+
57
+ /**
58
+ * Cronoton-lifecycle handlers: the confirm-gated commit/edit/pause/resume/delete
59
+ * half of the codex-cronoton route surface.
60
+ *
61
+ * Each handler is a thin, framework-agnostic adapter over the `/server` store: it
62
+ * runs behind the CONFIRM gate ({@link withConfirm} — every operation here mutates,
63
+ * so a fresh admin-confirm is demanded), shapes the normalized request body into
64
+ * the store's input, and lets the store's typed errors flow back through
65
+ * {@link mapStoreError} (a `not found` → 404, any other validation → 400, a
66
+ * terminal row → 409). The store functions are imported under `store*` aliases so
67
+ * these handlers can carry the canonical contract names.
68
+ *
69
+ * Two invariants live in this layer rather than the store:
70
+ * - **Shape validation (REQ-H01):** a malformed commit/edit body is a CLIENT error
71
+ * (400), so the body adapters throw {@link CodexCronotonValidationError} for a
72
+ * missing envelope/schedule instead of letting a `TypeError` become a 500.
73
+ * - **Server-resolver delete-lock (REQ-H05):** a row bound to a server resolver is
74
+ * a system cronoton that must be paused, never deleted — the delete handler
75
+ * loads the row FIRST and refuses with 409 before the store's unconditional
76
+ * delete would run.
77
+ *
78
+ * Commit and delete emit an audit event through `ctx.onAudit` (the store does not
79
+ * audit these transitions, so there is no double-audit); edit/pause/resume carry
80
+ * no audit here.
81
+ */
82
+
83
+ /**
84
+ * The transaction envelope half of a {@link CommitBody}: everything that
85
+ * describes WHAT fires, independent of WHEN. Maps 1:1 onto the store input's
86
+ * definition fields.
87
+ */
88
+ interface CommitEnvelope {
89
+ pactCode: string;
90
+ config: CodexTxConfig;
91
+ payload?: Record<string, unknown>;
92
+ gasPayer: CodexGasPayer;
93
+ signers: CodexSigner[];
94
+ serverResolver?: string;
95
+ externalFireable?: boolean;
96
+ runtimeArgKeys?: string[];
97
+ }
98
+ /** The schedule half of a {@link CommitBody}: mode + its config. */
99
+ interface CommitSchedule {
100
+ mode: ScheduleMode;
101
+ config: ScheduleConfig;
102
+ }
103
+ /** The client-facing commit payload the route accepts (POST body). */
104
+ interface CommitBody {
105
+ name: string;
106
+ description?: string | null;
107
+ envelope: CommitEnvelope;
108
+ schedule: CommitSchedule;
109
+ }
110
+
111
+ /**
112
+ * The **KhronotonAdapter seam** — the CLIENT side of the Phase-C handler
113
+ * contract. It is exactly one async method per handler operation, returning each
114
+ * handler's response **body** (the `{ ok, ... }` payload) rather than the
115
+ * `{ status, body }` envelope: an adapter implementation unwraps the status
116
+ * itself (2xx → resolve with the body; non-2xx → throw). This keeps the seam
117
+ * framework-neutral — the reference fetch adapter (T4.3) and the in-process
118
+ * MemoryAdapter (T4.4) both satisfy this one interface, and the provider/hooks
119
+ * consume it without knowing whether the backend is HTTP or an in-memory handler
120
+ * context.
121
+ *
122
+ * ── The needs-confirm signal ──────────────────────────────────────────────────
123
+ * Every mutating operation runs behind the handlers' CONFIRM gate, which passes
124
+ * only when the request carried a fresh admin-confirm (`req.confirmed === true`).
125
+ * The gate lives in the provider/hook layer (`runGated`, T4.5); the adapter just
126
+ * CARRIES the signal. Each confirm-gated method therefore takes a trailing
127
+ * optional {@link ConfirmOpts} — the provider calls the method with
128
+ * `{ confirmed: true }` once the confirm-gate resolves. If the backend's gate
129
+ * still refuses (a stale confirm), the adapter throws {@link NeedsConfirmError}
130
+ * so `runGated` re-prompts and retries exactly once. The fetch adapter maps that
131
+ * signal onto its request (a header/body flag the host route reads back into
132
+ * `req.confirmed`); the MemoryAdapter sets `req.confirmed = opts?.confirmed`.
133
+ *
134
+ * ── 200-on-`ok:false` (REQ-H04) ───────────────────────────────────────────────
135
+ * `simulate`/`executeNow`/`trigger` resolve at HTTP 200 EVEN when the body's own
136
+ * `ok` is false (a chain/build failure rides in the body). The adapter returns
137
+ * that body untouched; callers branch on `result.ok`. Only a real transport
138
+ * error (or the confirm gate) is a thrown/rejected path.
139
+ */
140
+
141
+ /**
142
+ * The fresh-confirm carrier threaded to every mutating method. `confirmed:true`
143
+ * means "a fresh admin-confirm accompanied this call" — the provider's
144
+ * confirm-gate sets it after the host's confirm resolves.
145
+ */
146
+ interface ConfirmOpts {
147
+ confirmed?: boolean;
148
+ }
149
+ /** Optional filters for the cronoton list (all default in the read handler). */
150
+ interface ListCronotonsQuery {
151
+ limit?: number;
152
+ offset?: number;
153
+ status?: CodexCronotonRow["status"];
154
+ }
155
+ /** The fire-history page request: which cronoton + the offset window. */
156
+ interface FiresQuery {
157
+ id: string;
158
+ limit?: number;
159
+ offset?: number;
160
+ }
161
+ /** An at-next-fire edit patch — the mutable subset of a {@link CommitBody}. */
162
+ type EditPatch = Partial<CommitBody>;
163
+ /**
164
+ * A simulate envelope: the tx parts to preview (`pactCode`, `config`, `payload`,
165
+ * `gasPayer`, `signers`, `scheduleKind`, `serverResolver`). Left structurally
166
+ * loose to mirror the handler, which reads the envelope defensively and fills
167
+ * neutral defaults for any missing optional.
168
+ */
169
+ type SimulateEnvelope = Record<string, unknown>;
170
+ /** `GET /` body. */
171
+ interface ListCronotonsView {
172
+ ok: true;
173
+ codexCronotons: CodexCronotonRow[];
174
+ }
175
+ /** `GET /[id]` body. */
176
+ interface GetCronotonView {
177
+ ok: true;
178
+ codexCronoton: CodexCronotonRow;
179
+ }
180
+ /** `GET /[id]/fires` body — offset-paged, echoing the queried window. */
181
+ interface FiresView {
182
+ ok: true;
183
+ fires: CodexCronotonFireRow[];
184
+ total: number;
185
+ limit: number;
186
+ offset: number;
187
+ }
188
+ /** `GET /signers` body — secret-free descriptors. */
189
+ interface SignersView {
190
+ ok: true;
191
+ signers: CodexSignerDescriptor[];
192
+ }
193
+ /** `POST /` body — the new id + its first scheduled fire. */
194
+ interface CommitView {
195
+ ok: true;
196
+ codexCronotonId: string;
197
+ nextFireAt: string | null;
198
+ }
199
+ /** `PATCH /[id]` body — the recomputed next fire after the at-next-fire edit. */
200
+ interface EditView {
201
+ ok: true;
202
+ nextFireAt: string | null;
203
+ }
204
+ /** `PATCH /[id]/pause` + `PATCH /[id]/resume` body — the settled lifecycle state. */
205
+ interface ToggleView {
206
+ ok: true;
207
+ status: CodexCronotonRow["status"];
208
+ nextFireAt: string | null;
209
+ }
210
+ /** `DELETE /[id]` body. A delete-locked system row is a non-2xx (409) → thrown. */
211
+ interface DeleteView {
212
+ ok: true;
213
+ }
214
+ /**
215
+ * `POST /simulate` body — the full simulate union (REQ-H11). `ok:false` still
216
+ * resolves at 200 (a chain/build failure rides in `error`); callers read `ok`.
217
+ */
218
+ interface SimulateView {
219
+ ok: boolean;
220
+ calibratedGasLimit?: number;
221
+ gasUsed?: number;
222
+ error?: string;
223
+ rawResult?: unknown;
224
+ postponed?: boolean;
225
+ plannedCount?: number;
226
+ chainData?: unknown;
227
+ }
228
+ /**
229
+ * `POST /[id]/execute` + `POST /[id]/trigger` body. `ok:false` resolves at 200
230
+ * (the fire failed but was recorded); `queued:true` is the 202 multi-tx path
231
+ * (the row was handed to the consumer's async orchestrator, REQ-H06).
232
+ */
233
+ interface ExecuteView {
234
+ ok: boolean;
235
+ fireId?: string;
236
+ requestKey?: string;
237
+ error?: string;
238
+ queued?: boolean;
239
+ }
240
+ /** `POST /[id]/execute-batch` body — the freshly-started batch. */
241
+ interface StartBatchView {
242
+ ok: true;
243
+ batch: ManualBatchView;
244
+ }
245
+ /** `GET /[id]/execute-batch` body — the active batch, or null when idle. */
246
+ interface GetBatchView {
247
+ ok: true;
248
+ batch: ManualBatchView | null;
249
+ }
250
+ /** `DELETE /[id]/execute-batch` body — `cancelled:false` when already inactive. */
251
+ interface CancelBatchView {
252
+ ok: true;
253
+ cancelled: boolean;
254
+ }
255
+ /** `POST /[id]/fires/[fireId]/recover` body — the reconciled fire + its key. */
256
+ interface RecoverView {
257
+ ok: true;
258
+ fireId: string;
259
+ requestKey: string;
260
+ }
261
+ /**
262
+ * The consumer-facing data seam: one method per Phase-C handler operation. Read
263
+ * methods take no confirm; every mutating method takes a trailing
264
+ * {@link ConfirmOpts} the provider threads the fresh-confirm signal through.
265
+ * A method rejects with {@link NeedsConfirmError} when the backend's confirm gate
266
+ * refuses, and with a plain `Error` for any other non-2xx (the fetch adapter
267
+ * defaults the message to `body.error ?? 'HTTP {status}'`).
268
+ */
269
+ interface KhronotonAdapter {
270
+ list(query?: ListCronotonsQuery): Promise<ListCronotonsView>;
271
+ get(id: string): Promise<GetCronotonView>;
272
+ fires(query: FiresQuery): Promise<FiresView>;
273
+ signers(): Promise<SignersView>;
274
+ commit(body: CommitBody, opts?: ConfirmOpts): Promise<CommitView>;
275
+ edit(id: string, patch: EditPatch, opts?: ConfirmOpts): Promise<EditView>;
276
+ pause(id: string, opts?: ConfirmOpts): Promise<ToggleView>;
277
+ resume(id: string, opts?: ConfirmOpts): Promise<ToggleView>;
278
+ delete(id: string, opts?: ConfirmOpts): Promise<DeleteView>;
279
+ simulate(envelope: SimulateEnvelope, opts?: ConfirmOpts): Promise<SimulateView>;
280
+ executeNow(id: string, opts?: ConfirmOpts): Promise<ExecuteView>;
281
+ trigger(id: string, args: RuntimeArgs, opts?: ConfirmOpts): Promise<ExecuteView>;
282
+ startBatch(id: string, count: number, opts?: ConfirmOpts): Promise<StartBatchView>;
283
+ getBatch(id: string): Promise<GetBatchView>;
284
+ cancelBatch(id: string): Promise<CancelBatchView>;
285
+ recover(id: string, fireId: string, requestKey: string, opts?: ConfirmOpts): Promise<RecoverView>;
286
+ }
287
+ /**
288
+ * Runtime guard the provider (T4.5) runs on its `adapter` prop before mounting:
289
+ * throws a clear, method-named error if `x` is not an object carrying all 16
290
+ * operations as functions — so a host that forgot a method fails loudly at
291
+ * mount, not silently at the first call.
292
+ */
293
+ declare function assertAdapter(x: unknown): asserts x is KhronotonAdapter;
294
+ /**
295
+ * The in-memory seed the MemoryAdapter (T4.4) builds a fresh backend from.
296
+ * Khronoton has no local persisted snapshot like Codex — the backing store is a
297
+ * DB — so the seed is just the cronoton definitions to commit into an empty DB
298
+ * (empty = a blank backend; a demo passes definitions to pre-populate one).
299
+ */
300
+ interface KhronotonSnapshot {
301
+ cronotons: CommitBody[];
302
+ }
303
+ /** A fresh, independent empty seed (safe to mutate — never aliases a prior call). */
304
+ declare function emptySnapshot(): KhronotonSnapshot;
305
+
306
+ /** Default explorer base — the StoaChain transactions view (REQ-G02). */
307
+ declare const DEFAULT_EXPLORER_BASE = "https://explorer.stoachain.com/transactions";
308
+ /** Default fire-history page size (REQ-PH04, REQ-G08). */
309
+ declare const DEFAULT_PAGE_SIZE = 50;
310
+ /** Default poller cadence in ms (REQ-PH06) — the two 5s pollers read this. */
311
+ declare const DEFAULT_POLL_CADENCE_MS = 5000;
312
+ /** A registry-driven server-resolver dropdown option. */
313
+ interface ServerResolverOption {
314
+ value: string;
315
+ label: string;
316
+ /** Optional gold side-note shown in the builder when this resolver is selected. */
317
+ note?: string;
318
+ }
319
+ /** A pluggable multi-tx breakdown renderer (the Hub's pool-payout is one impl). */
320
+ type RenderMultiTx = (fire: CodexCronotonFireRow) => ReactNode;
321
+ /**
322
+ * The host re-confirm gate: resolves `true` when the user re-confirms after an
323
+ * expired admin-confirm (driving `runGated`'s single retry), `false` on cancel.
324
+ */
325
+ type ConfirmGate = () => Promise<boolean>;
326
+ /** The resolved config every consumer reads — all defaults already applied. */
327
+ interface KhronotonConfig {
328
+ explorerBase: string;
329
+ showMode: boolean;
330
+ renderMultiTx?: RenderMultiTx;
331
+ serverResolverOptions: ServerResolverOption[];
332
+ pageSize: number;
333
+ pollCadenceMs: number;
334
+ onNeedConfirm?: ConfirmGate;
335
+ }
336
+ /** The `<KhronotonProvider>` props: a required adapter + optional config. */
337
+ interface KhronotonProviderProps {
338
+ /** REQUIRED — the consumer data seam; validated by `assertAdapter` at mount. */
339
+ adapter: KhronotonAdapter;
340
+ explorerBase?: string;
341
+ onNeedConfirm?: ConfirmGate;
342
+ showMode?: boolean;
343
+ renderMultiTx?: RenderMultiTx;
344
+ serverResolverOptions?: ServerResolverOption[];
345
+ pageSize?: number;
346
+ pollCadenceMs?: number;
347
+ children?: ReactNode;
348
+ }
349
+ /** The public `useKhronoton()` result: readiness + the resolved seam/config. */
350
+ interface UseKhronotonResult {
351
+ ready: boolean;
352
+ error: Error | null;
353
+ adapter: KhronotonAdapter;
354
+ config: KhronotonConfig;
355
+ }
356
+ /**
357
+ * The top-level consumer hook (mirrors Codex's `useCodex`): `ready` flips true
358
+ * after the browser-only init, `error` holds an init failure, and `config` +
359
+ * `adapter` are the resolved seam the UI reads.
360
+ */
361
+ declare function useKhronoton(): UseKhronotonResult;
362
+
363
+ export { emptySnapshot as A, type CommitBody as C, type DeleteView as D, type EditPatch as E, type FiresQuery as F, type GetBatchView as G, type HandlerRequest as H, type KhronotonProviderProps as K, type ListCronotonsQuery as L, type RecoverView as R, type SimulateEnvelope as S, type ToggleView as T, type UseKhronotonResult as U, type CommitView as a, type EditView as b, type CancelBatchView as c, type ExecuteView as d, type SimulateView as e, type StartBatchView as f, type RuntimeArgs as g, type HandlerResponse as h, type KhronotonAdapter as i, type SignerSource as j, type CodexSignerDescriptor as k, type ConfirmGate as l, type ConfirmOpts as m, DEFAULT_EXPLORER_BASE as n, DEFAULT_PAGE_SIZE as o, DEFAULT_POLL_CADENCE_MS as p, type FiresView as q, type GetCronotonView as r, type KhronotonConfig as s, type KhronotonSnapshot as t, useKhronoton as u, type ListCronotonsView as v, type RenderMultiTx as w, type ServerResolverOption as x, type SignersView as y, assertAdapter as z };
@@ -0,0 +1,21 @@
1
+ import { type HandlerContext } from "./context.js";
2
+ import { type HandlerRequest, type HandlerResponse } from "./http.js";
3
+ /**
4
+ * POST `/[id]/execute-batch` — start a manual batch of `body.count` fires.
5
+ * Confirm-gated. The store validates the count bounds (config-driven 2–60),
6
+ * that the parent cronoton exists + is active + is not one-time, and that no
7
+ * batch is already running; its typed errors map to 400/404/409.
8
+ */
9
+ export declare function startExecuteBatch(ctx: HandlerContext, req: HandlerRequest): Promise<HandlerResponse>;
10
+ /**
11
+ * GET `/[id]/execute-batch` — the active batch for a cronoton, or null.
12
+ * Read-gated (confirm-free): polled while a batch runs, so it never demands a
13
+ * fresh confirm.
14
+ */
15
+ export declare function getExecuteBatch(ctx: HandlerContext, req: HandlerRequest): Promise<HandlerResponse>;
16
+ /**
17
+ * DELETE `/[id]/execute-batch` — stop the running batch. Read-gated
18
+ * (deliberately confirm-FREE — one-click stop, REQ-H09) and idempotent:
19
+ * `cancelled` is false when the batch was already inactive.
20
+ */
21
+ export declare function cancelExecuteBatch(ctx: HandlerContext, req: HandlerRequest): Promise<HandlerResponse>;
@@ -0,0 +1,57 @@
1
+ /**
2
+ * Manual-batch handlers — the "Execute ×N" lifecycle (start / observe / stop).
3
+ *
4
+ * The tier split is the whole point of this group (REQ-H09): STARTING a batch is
5
+ * a mutation that spends chain gas up to N times, so it runs the CONFIRM gate and
6
+ * demands a fresh admin-confirm. OBSERVING and STOPPING a batch are deliberately
7
+ * confirm-FREE — they run the READ gate so an operator can watch progress or halt
8
+ * a runaway batch with a single click, without a confirm round-trip standing
9
+ * between them and the stop button. The count-bounds / already-active / not-active
10
+ * guards live in the store (`createManualBatch`) and surface here as its typed
11
+ * errors, mapped to 400/404/409 by the kernel's `mapStoreError`.
12
+ */
13
+ import { createManualBatch, getActiveManualBatchForCronoton, cancelManualBatch, manualBatchView, } from "../server/index.js";
14
+ import { withConfirm, withRead } from "./context.js";
15
+ import { json } from "./http.js";
16
+ /**
17
+ * POST `/[id]/execute-batch` — start a manual batch of `body.count` fires.
18
+ * Confirm-gated. The store validates the count bounds (config-driven 2–60),
19
+ * that the parent cronoton exists + is active + is not one-time, and that no
20
+ * batch is already running; its typed errors map to 400/404/409.
21
+ */
22
+ export async function startExecuteBatch(ctx, req) {
23
+ return withConfirm(ctx, req, async (identity) => {
24
+ const cronotonId = req.params?.id ?? "";
25
+ const count = req.body?.count;
26
+ const row = createManualBatch({ cronotonId, total: count, createdBy: identity?.email ?? identity?.id ?? "unknown" }, { db: ctx.db, config: ctx.config });
27
+ return json(200, { ok: true, batch: manualBatchView(row) });
28
+ });
29
+ }
30
+ /**
31
+ * GET `/[id]/execute-batch` — the active batch for a cronoton, or null.
32
+ * Read-gated (confirm-free): polled while a batch runs, so it never demands a
33
+ * fresh confirm.
34
+ */
35
+ export async function getExecuteBatch(ctx, req) {
36
+ return withRead(ctx, req, async () => {
37
+ const cronotonId = req.params?.id ?? "";
38
+ const batch = getActiveManualBatchForCronoton(cronotonId, { db: ctx.db });
39
+ return json(200, { ok: true, batch: batch ? manualBatchView(batch) : null });
40
+ });
41
+ }
42
+ /**
43
+ * DELETE `/[id]/execute-batch` — stop the running batch. Read-gated
44
+ * (deliberately confirm-FREE — one-click stop, REQ-H09) and idempotent:
45
+ * `cancelled` is false when the batch was already inactive.
46
+ */
47
+ export async function cancelExecuteBatch(ctx, req) {
48
+ return withRead(ctx, req, async () => {
49
+ // The route param is the CRONOTON id (same `/[id]/execute-batch` path as
50
+ // start/get). Resolve the active batch for that cronoton, then cancel by its
51
+ // own UUID — `cancelManualBatch` filters on the batch PK, not the cronoton.
52
+ const cronotonId = req.params?.id ?? "";
53
+ const active = getActiveManualBatchForCronoton(cronotonId, { db: ctx.db });
54
+ const cancelled = active ? cancelManualBatch(active.id, { db: ctx.db }).ok : false;
55
+ return json(200, { ok: true, cancelled });
56
+ });
57
+ }
@@ -0,0 +1,94 @@
1
+ /**
2
+ * The per-request handler context + the injectable auth/confirm seam + the two
3
+ * gate wrappers.
4
+ *
5
+ * The consumer supplies a {@link HandlerContext} on every call: the injected DB
6
+ * handle, chain runtime, key resolver, and the seams the store/executor already
7
+ * defined in `/server` (all re-exported below so a consumer imports the whole
8
+ * handler contract from one entry — never redeclared here). The {@link AuthSeam}
9
+ * genericizes the Hub's role + fresh-confirm model into two gates: a READ gate
10
+ * (list/get/fires/signers + the batch stop path) and a CONFIRM gate (every
11
+ * mutating handler). {@link withRead} / {@link withConfirm} run the appropriate
12
+ * gate, short-circuit on denial, otherwise invoke the handler body and translate
13
+ * any thrown store error through {@link mapStoreError}.
14
+ */
15
+ import { type HandlerRequest, type HandlerResponse, type SignerSource } from "./http.js";
16
+ import type { ChainRuntime, Config, Database, KeyResolver, OnAudit, ResolveFireMode } from "../server/index.js";
17
+ export type { ChainRuntime, Config, Database, KeyResolver, OnAudit, ResolveFireMode, } from "../server/index.js";
18
+ /** The (optional) identity a passing gate attaches for the handler body to attribute writes to. */
19
+ export interface AuthIdentity {
20
+ id?: string;
21
+ email?: string;
22
+ }
23
+ /**
24
+ * A gate outcome: either a pass carrying an optional identity, or a block
25
+ * carrying the exact {@link HandlerResponse} the wrapper returns verbatim (a 401
26
+ * `admin_confirm_required` for a stale/absent confirm, a 403 for a non-admin).
27
+ */
28
+ export type AuthResult = {
29
+ ok: true;
30
+ identity?: AuthIdentity;
31
+ } | {
32
+ ok: false;
33
+ response: HandlerResponse;
34
+ };
35
+ /**
36
+ * The injectable auth/confirm contract. A trusted single-tenant consumer uses
37
+ * {@link defaultOpenAuth}; a stricter consumer implements both gates against its
38
+ * own role + confirm-modal flow. Each gate may be sync or async.
39
+ */
40
+ export interface AuthSeam {
41
+ /** Read tier: list/get/fires/signers + the batch get/cancel stop path. */
42
+ requireRead(req: HandlerRequest): AuthResult | Promise<AuthResult>;
43
+ /** Mutate tier: demands a fresh admin-confirm; blocks with 401/403 otherwise. */
44
+ requireConfirm(req: HandlerRequest): AuthResult | Promise<AuthResult>;
45
+ }
46
+ /**
47
+ * A sentinel a strict consumer's confirm gate (or a handler body) may THROW to
48
+ * signal a stale/absent confirm; the gate wrappers translate it to the canonical
49
+ * 401 `admin_confirm_required`. The gate may equally RETURN a blocking
50
+ * {@link AuthResult} — this class is the throw-based alternative.
51
+ */
52
+ export declare class NeedsConfirmError extends Error {
53
+ readonly code = "admin_confirm_required";
54
+ constructor(message?: string);
55
+ }
56
+ /**
57
+ * The trusted single-tenant default: the read gate always passes; the confirm
58
+ * gate passes only when `req.confirmed === true`, else it blocks with 401
59
+ * `admin_confirm_required` so the consumer's confirm flow still round-trips.
60
+ */
61
+ export declare const defaultOpenAuth: AuthSeam;
62
+ /**
63
+ * Everything a handler needs, injected per request. Store calls receive `{ db }`;
64
+ * executor calls receive `{ runtime, resolver, config }`; fire-recording receives
65
+ * `{ db, resolveFireMode }`. `auth` is required (use {@link defaultOpenAuth} for
66
+ * a trusted single-tenant); the rest of the automaton seams carry their
67
+ * documented `/server` defaults when omitted.
68
+ */
69
+ export interface HandlerContext {
70
+ db: Database;
71
+ runtime: ChainRuntime;
72
+ resolver: KeyResolver;
73
+ resolveFireMode?: ResolveFireMode;
74
+ onAudit?: OnAudit;
75
+ config?: Partial<Config>;
76
+ auth: AuthSeam;
77
+ signers?: SignerSource;
78
+ }
79
+ /** A framework-agnostic route handler over the injected {@link HandlerContext}. */
80
+ export type Handler = (ctx: HandlerContext, req: HandlerRequest) => Promise<HandlerResponse>;
81
+ type HandlerBody = (identity: AuthIdentity | undefined) => Promise<HandlerResponse>;
82
+ /**
83
+ * Run `fn` behind the READ gate: short-circuit with the gate's response on
84
+ * denial, otherwise invoke `fn(identity)` and translate any thrown store error
85
+ * through {@link mapStoreError} (an unexpected throw becomes a 500).
86
+ */
87
+ export declare function withRead(ctx: HandlerContext, req: HandlerRequest, fn: HandlerBody): Promise<HandlerResponse>;
88
+ /**
89
+ * Run `fn` behind the CONFIRM gate: a stale/absent confirm short-circuits with
90
+ * the gate's 401 `admin_confirm_required` (or a 403 for a non-admin) before `fn`
91
+ * runs; a passing gate invokes `fn(identity)` and translates a thrown store error
92
+ * through {@link mapStoreError}.
93
+ */
94
+ export declare function withConfirm(ctx: HandlerContext, req: HandlerRequest, fn: HandlerBody): Promise<HandlerResponse>;
@@ -0,0 +1,75 @@
1
+ /**
2
+ * The per-request handler context + the injectable auth/confirm seam + the two
3
+ * gate wrappers.
4
+ *
5
+ * The consumer supplies a {@link HandlerContext} on every call: the injected DB
6
+ * handle, chain runtime, key resolver, and the seams the store/executor already
7
+ * defined in `/server` (all re-exported below so a consumer imports the whole
8
+ * handler contract from one entry — never redeclared here). The {@link AuthSeam}
9
+ * genericizes the Hub's role + fresh-confirm model into two gates: a READ gate
10
+ * (list/get/fires/signers + the batch stop path) and a CONFIRM gate (every
11
+ * mutating handler). {@link withRead} / {@link withConfirm} run the appropriate
12
+ * gate, short-circuit on denial, otherwise invoke the handler body and translate
13
+ * any thrown store error through {@link mapStoreError}.
14
+ */
15
+ import { json, mapStoreError, } from "./http.js";
16
+ /**
17
+ * A sentinel a strict consumer's confirm gate (or a handler body) may THROW to
18
+ * signal a stale/absent confirm; the gate wrappers translate it to the canonical
19
+ * 401 `admin_confirm_required`. The gate may equally RETURN a blocking
20
+ * {@link AuthResult} — this class is the throw-based alternative.
21
+ */
22
+ export class NeedsConfirmError extends Error {
23
+ constructor(message = "admin_confirm_required") {
24
+ super(message);
25
+ this.code = "admin_confirm_required";
26
+ this.name = "NeedsConfirmError";
27
+ }
28
+ }
29
+ /**
30
+ * The trusted single-tenant default: the read gate always passes; the confirm
31
+ * gate passes only when `req.confirmed === true`, else it blocks with 401
32
+ * `admin_confirm_required` so the consumer's confirm flow still round-trips.
33
+ */
34
+ export const defaultOpenAuth = {
35
+ requireRead() {
36
+ return { ok: true, identity: {} };
37
+ },
38
+ requireConfirm(req) {
39
+ if (req.confirmed === true) {
40
+ return { ok: true, identity: {} };
41
+ }
42
+ return { ok: false, response: json(401, { error: "admin_confirm_required" }) };
43
+ },
44
+ };
45
+ async function runGated(gate, fn) {
46
+ if (!gate.ok) {
47
+ return gate.response;
48
+ }
49
+ try {
50
+ return await fn(gate.identity);
51
+ }
52
+ catch (error) {
53
+ if (error instanceof NeedsConfirmError) {
54
+ return json(401, { error: error.code });
55
+ }
56
+ return mapStoreError(error);
57
+ }
58
+ }
59
+ /**
60
+ * Run `fn` behind the READ gate: short-circuit with the gate's response on
61
+ * denial, otherwise invoke `fn(identity)` and translate any thrown store error
62
+ * through {@link mapStoreError} (an unexpected throw becomes a 500).
63
+ */
64
+ export async function withRead(ctx, req, fn) {
65
+ return runGated(await ctx.auth.requireRead(req), fn);
66
+ }
67
+ /**
68
+ * Run `fn` behind the CONFIRM gate: a stale/absent confirm short-circuits with
69
+ * the gate's 401 `admin_confirm_required` (or a 403 for a non-admin) before `fn`
70
+ * runs; a passing gate invokes `fn(identity)` and translates a thrown store error
71
+ * through {@link mapStoreError}.
72
+ */
73
+ export async function withConfirm(ctx, req, fn) {
74
+ return runGated(await ctx.auth.requireConfirm(req), fn);
75
+ }