@sudoke/kernel 0.0.0-stage → 0.3.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/package.json +29 -4
- package/src/auth.ts +125 -0
- package/src/gate.ts +710 -0
- package/src/index.ts +26 -0
- package/src/mcp.ts +154 -0
- package/src/policy.ts +60 -0
- package/src/projections.ts +115 -0
- package/src/protocol.ts +51 -0
- package/src/queries.ts +176 -0
- package/src/registry.ts +235 -0
- package/src/state.ts +135 -0
- package/src/storage.ts +208 -0
- package/src/types.ts +121 -0
- package/src/visibility.ts +97 -0
- package/README.md +0 -3
package/src/gate.ts
ADDED
|
@@ -0,0 +1,710 @@
|
|
|
1
|
+
import { ZodError } from 'zod'
|
|
2
|
+
import { createHmac } from 'node:crypto'
|
|
3
|
+
import { currentIdentityOf } from './auth.js'
|
|
4
|
+
import { maskSecrets, storageOf } from './storage.js'
|
|
5
|
+
import { appPolicy } from './policy.js'
|
|
6
|
+
import { applyDomainEvent } from './projections.js'
|
|
7
|
+
import { completeAssembly, errorCodeOf, eventContractOf, lookupCommand, transitionRulesOf } from './registry.js'
|
|
8
|
+
import { delegationScopeEntries, roleAllowsCommand } from './visibility.js'
|
|
9
|
+
import type { PolicyRefusal } from './policy.js'
|
|
10
|
+
import { GateError, type CommandDefinition, type DomainEvent, type Identity, type RecoveryHint } from './types.js'
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Decision-time table (2026-10-22 time-axis audit) — which read each gate judgment is based on.
|
|
14
|
+
* Any change to this table is committed together with the affected time-point cases in smoke·policy-test.
|
|
15
|
+
*
|
|
16
|
+
* - 1 identify (token→identity) : re-read from the DB on every request (loadIdentity — role changes·deactivation apply immediately)
|
|
17
|
+
* - 2 delegation scope : request (static) + just before execution (reauthorize) — revocation·expiry are also blocked at execution time
|
|
18
|
+
* - 3 role·business scope : request (static) + just before execution (reauthorize) — business interpretation of scope belongs to the app policy
|
|
19
|
+
* - 4 schema : once per request (state-independent; must also pass before replay)
|
|
20
|
+
* - 5 preconditions·6 invariants·7 transitions : just before execution, inside the transaction
|
|
21
|
+
* (an earlier command's changes in a batch are reflected)
|
|
22
|
+
* - 8~9 execute·audit : inside the transaction — events·projections·idempotency·audit commit/roll back together
|
|
23
|
+
* - idempotent replay (requestKey) : right after the static (1~4) checks, immediately. It is a 'redelivery' of an already-committed
|
|
24
|
+
* result, so execution-time rechecks are skipped by design (re-checking only adds false negatives;
|
|
25
|
+
* there is no new result). Re-enabling rechecks is a deliberate policy change.
|
|
26
|
+
* Each redelivery still leaves exactly one 'replay' audit row (I8 — every attempt is recorded).
|
|
27
|
+
* - idempotency SELECT→INSERT : split outside/inside the transaction — on conflict, roll back, re-read, and return the stored result (settleConcurrentRetry)
|
|
28
|
+
* - command·transition·contract registration : once at boot (catalogConsistencyErrors checks for contradictions) — immutable during
|
|
29
|
+
* execution; the registries are sealed after assembly, so late registration fails
|
|
30
|
+
*/
|
|
31
|
+
/** Success shape — the result·events of execution, with the replayed/dry-run markers */
|
|
32
|
+
export interface ExecutionSuccess {
|
|
33
|
+
ok: true
|
|
34
|
+
result?: unknown
|
|
35
|
+
events?: string[]
|
|
36
|
+
/** dryRun:true request — passed validation (1~7) but execution (8) was skipped */
|
|
37
|
+
dryRun?: boolean
|
|
38
|
+
/** Same requestKey resent — the stored result was returned as-is */
|
|
39
|
+
replayed?: boolean
|
|
40
|
+
/** Batch execution — per-command results */
|
|
41
|
+
results?: unknown[]
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** Refusal shape — a first-class result; the code·recovery contract is always machine-usable */
|
|
45
|
+
export interface ExecutionRefusal {
|
|
46
|
+
ok: false
|
|
47
|
+
stage: number
|
|
48
|
+
stageName: string
|
|
49
|
+
reason: string
|
|
50
|
+
/** Stable error code — stays stable even as the sentence (reason) changes. An identifier of the registry (errorCodes) */
|
|
51
|
+
code?: string
|
|
52
|
+
/** Next-step guidance — an action classification (refresh·fix_input·reauthenticate·retry·stop) plus an optional query */
|
|
53
|
+
recovery?: RecoveryHint
|
|
54
|
+
/** Marks a warning refusal that can be overridden with a force:true retry */
|
|
55
|
+
canForce?: boolean
|
|
56
|
+
/** Which command (index) failed in a batch */
|
|
57
|
+
index?: number
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** One attempt's outcome — success and refusal are the two shapes every surface distinguishes by ok */
|
|
61
|
+
export type ExecutionResult = ExecutionSuccess | ExecutionRefusal
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* Delegation scope check — the acting radius of an agent token.
|
|
65
|
+
* Scope syntax (kernel contract): '*' | 'commandName' | 'commandName:target' — what a target refers to is defined by the app policy.
|
|
66
|
+
* Target restrictions reflect only 'entries attached to this command' — so target ranges of other commands never mix in (G-05).
|
|
67
|
+
*/
|
|
68
|
+
async function delegationAllows(
|
|
69
|
+
del: NonNullable<Identity['delegation']>,
|
|
70
|
+
commandName: string,
|
|
71
|
+
def: CommandDefinition<any>,
|
|
72
|
+
input: unknown,
|
|
73
|
+
): Promise<boolean> {
|
|
74
|
+
// Entry selection is shared with the catalog visibility derivation (visibility.ts) — one predicate, no drift
|
|
75
|
+
const entries = delegationScopeEntries(del.scopes, commandName)
|
|
76
|
+
if (entries.length === 0) return false
|
|
77
|
+
if (entries.some((sc) => !sc.includes(':'))) return true
|
|
78
|
+
const targetId = def.scope !== 'none' ? def.targetOf?.(input as any) : undefined
|
|
79
|
+
if (!targetId) return false
|
|
80
|
+
const targets = entries.map((sc) => sc.slice(sc.indexOf(':') + 1))
|
|
81
|
+
return await appPolicy().delegationCovers(targetId, targets)
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** Common protocol options (requestKey·dryRun) ride beside the business input but are not part of it — stripped
|
|
85
|
+
* before the schema so even a .strict() business schema never sees them, and excluded from permission targets
|
|
86
|
+
* and the idempotency hash (the same business request hashes identically however the options were spelled). */
|
|
87
|
+
function splitProtocolOptions(raw: unknown): { requestKey?: string; dryRun: boolean; body: unknown } {
|
|
88
|
+
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return { dryRun: false, body: raw }
|
|
89
|
+
const { requestKey, dryRun, ...body } = raw as Record<string, unknown>
|
|
90
|
+
return {
|
|
91
|
+
requestKey: typeof requestKey === 'string' && requestKey.length > 0 ? requestKey.slice(0, 100) : undefined,
|
|
92
|
+
dryRun: dryRun === true,
|
|
93
|
+
body,
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** Common fallback codes for unclassified dynamic-stage errors — a refusal without a code breaks the
|
|
98
|
+
* machine-usable contract, so every refusal carries one (the domain-declared code remains the good path) */
|
|
99
|
+
const STAGE_FALLBACK_CODES: Record<number, string> = {
|
|
100
|
+
5: 'gate.precondition_error',
|
|
101
|
+
6: 'gate.invariant_error',
|
|
102
|
+
8: 'gate.execution_failed',
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
const toGateError = (err: unknown, stage: number, stageName: string) => {
|
|
106
|
+
if (err instanceof GateError) {
|
|
107
|
+
if (err.code || !STAGE_FALLBACK_CODES[stage]) return err
|
|
108
|
+
// a GateError constructed without a code still breaks the machine-usable contract — stamp the stage's fallback
|
|
109
|
+
return new GateError(err.stage, err.stageName, err.message, { code: STAGE_FALLBACK_CODES[stage], recovery: err.recovery })
|
|
110
|
+
}
|
|
111
|
+
return new GateError(stage, stageName, err instanceof Error ? err.message : String(err), {
|
|
112
|
+
code: STAGE_FALLBACK_CODES[stage],
|
|
113
|
+
})
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/** Assembles the machine-usable contract of a refusal — merges the error-code definition (recovery action·force-ability)
|
|
117
|
+
* with throw-site hints (query). An unregistered code is still carried; recovery·canForce stay empty (the audit leaves an unregistered trace). */
|
|
118
|
+
function refusalMeta(err: GateError): Pick<ExecutionRefusal, 'code' | 'recovery' | 'canForce'> {
|
|
119
|
+
const def = err.code ? errorCodeOf(err.code) : undefined
|
|
120
|
+
const action = err.recovery?.action ?? def?.recovery
|
|
121
|
+
const query = err.recovery?.query
|
|
122
|
+
const recovery: RecoveryHint | undefined = action || query ? { ...(action ? { action } : {}), ...(query ? { query } : {}) } : undefined
|
|
123
|
+
return {
|
|
124
|
+
...(err.code ? { code: err.code } : {}),
|
|
125
|
+
...(recovery ? { recovery } : {}),
|
|
126
|
+
...(def?.canForce ? { canForce: true } : {}),
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/** Audit subject — for human access act/del are blanks; for agent access the acting subject is recorded */
|
|
131
|
+
const auditSubjectOf = (identity: Identity) => ({
|
|
132
|
+
userId: identity.userId,
|
|
133
|
+
name: identity.name,
|
|
134
|
+
role: identity.role,
|
|
135
|
+
act: identity.act ?? null,
|
|
136
|
+
del: identity.delegation?.id ?? null,
|
|
137
|
+
})
|
|
138
|
+
|
|
139
|
+
/** Ledger append (domain event) — gate-internal only, never exported: there is no public API for writing
|
|
140
|
+
* the ledger, so events reach it only through command execution. The format contract is checked here:
|
|
141
|
+
* unregistered types and violations are never written (exception → stage-8 refusal·rollback). Replay
|
|
142
|
+
* (reads) skips validation for past-format compatibility — the contract is the source of truth for what
|
|
143
|
+
* is written *now*. */
|
|
144
|
+
async function appendEvent(e: DomainEvent): Promise<{ seq: number; ts: string }> {
|
|
145
|
+
const contract = eventContractOf(e.type)
|
|
146
|
+
if (!contract)
|
|
147
|
+
throw new GateError(8, 'execute', `No event contract registered for type: ${e.type} — register it with registerEventContracts`, {
|
|
148
|
+
code: 'gate.event_contract_violation',
|
|
149
|
+
})
|
|
150
|
+
const checked = contract.safeParse(e.payload)
|
|
151
|
+
if (!checked.success)
|
|
152
|
+
throw new GateError(
|
|
153
|
+
8,
|
|
154
|
+
'execute',
|
|
155
|
+
`Event violates its format contract: ${e.type} — ${checked.error.issues
|
|
156
|
+
.map((i) => `${i.path.join('.')}: ${i.message}`)
|
|
157
|
+
.join('; ')}`,
|
|
158
|
+
{ code: 'gate.event_contract_violation' },
|
|
159
|
+
)
|
|
160
|
+
// ts is fixed once so storage and projection use the same value — the recorded time, not the replay time, stays in business data
|
|
161
|
+
const ts = new Date().toISOString()
|
|
162
|
+
const seq = await storageOf().appendDomainRow(e, ts)
|
|
163
|
+
return { seq, ts }
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/** Audit append — gate-internal only, never exported: the audit trail records gate attempts and nothing else */
|
|
167
|
+
async function appendAudit(payload: Record<string, unknown>): Promise<void> {
|
|
168
|
+
await storageOf().appendAuditRow(JSON.stringify(payload))
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/** Audit record assembly — one place for the common ok·dry-run·refused·replay shape (subject·input masking
|
|
172
|
+
* via the shared secret-field rule maskSecrets included). Refusals also carry the error code·recovery·force-ability
|
|
173
|
+
* — an unregistered code leaves a trace (no double refusal). */
|
|
174
|
+
async function recordAudit(
|
|
175
|
+
command: string,
|
|
176
|
+
identity: Identity,
|
|
177
|
+
result: 'ok' | 'dry-run' | 'refused' | 'replay',
|
|
178
|
+
rawInput: unknown,
|
|
179
|
+
refusal?: GateError,
|
|
180
|
+
): Promise<void> {
|
|
181
|
+
await appendAudit({
|
|
182
|
+
command,
|
|
183
|
+
subject: auditSubjectOf(identity),
|
|
184
|
+
result,
|
|
185
|
+
input: maskSecrets(rawInput),
|
|
186
|
+
...(refusal
|
|
187
|
+
? {
|
|
188
|
+
stage: refusal.stage,
|
|
189
|
+
stageName: refusal.stageName,
|
|
190
|
+
reason: refusal.message,
|
|
191
|
+
...refusalMeta(refusal),
|
|
192
|
+
...(refusal.code && !errorCodeOf(refusal.code) ? { codeUnregistered: true } : {}),
|
|
193
|
+
}
|
|
194
|
+
: {}),
|
|
195
|
+
})
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
/** Out-of-transaction audit write (refusal·replay·dry-run) — the one guarded helper. The caller's result
|
|
199
|
+
* always wins over the recording: on failure (disk·lock) a single stderr JSON line carries the diagnosis —
|
|
200
|
+
* a stable code, the audit kind, the command, the stage, a limited error classification; never the raw
|
|
201
|
+
* input, never the error text (messages may embed input values). stdout is never touched (MCP stdio owns it).
|
|
202
|
+
* The success audit is NOT routed here: it lives inside the business transaction, where a failed insert
|
|
203
|
+
* rolls the command back (stage-8 refusal — I8's split guarantee). */
|
|
204
|
+
async function tryRecordOutsideTx(
|
|
205
|
+
kind: 'refused' | 'replay' | 'dry-run',
|
|
206
|
+
command: string,
|
|
207
|
+
identity: Identity,
|
|
208
|
+
rawInput: unknown,
|
|
209
|
+
refusal?: GateError,
|
|
210
|
+
): Promise<void> {
|
|
211
|
+
try {
|
|
212
|
+
await recordAudit(command, identity, kind, rawInput, refusal)
|
|
213
|
+
} catch (err) {
|
|
214
|
+
console.error(
|
|
215
|
+
JSON.stringify({
|
|
216
|
+
code: 'audit.write_failed',
|
|
217
|
+
auditKind: kind,
|
|
218
|
+
command,
|
|
219
|
+
...(refusal ? { stage: refusal.stage } : {}),
|
|
220
|
+
errorClass: err instanceof Error ? err.constructor.name : typeof err,
|
|
221
|
+
ts: new Date().toISOString(),
|
|
222
|
+
}),
|
|
223
|
+
)
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
/** Concurrent-retry settlement audit — a settled replay is a redelivery (kind 'replay'), a settled key
|
|
228
|
+
* conflict is a refusal; both are attempts under I8 and never pass silently. */
|
|
229
|
+
async function auditSettled(command: string, identity: Identity, rawInput: unknown, settled: ExecutionResult): Promise<void> {
|
|
230
|
+
if (settled.ok) {
|
|
231
|
+
await tryRecordOutsideTx('replay', command, identity, rawInput)
|
|
232
|
+
return
|
|
233
|
+
}
|
|
234
|
+
await tryRecordOutsideTx(
|
|
235
|
+
'refused',
|
|
236
|
+
command,
|
|
237
|
+
identity,
|
|
238
|
+
rawInput,
|
|
239
|
+
new GateError(settled.stage ?? 8, settled.stageName ?? 'execute', settled.reason ?? 'settled refusal', {
|
|
240
|
+
...(settled.code ? { code: settled.code } : {}),
|
|
241
|
+
...(settled.recovery ? { recovery: settled.recovery } : {}),
|
|
242
|
+
}),
|
|
243
|
+
)
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
/** Refusal assembly — the single exit every refusal passes through: the attempt is recorded (the
|
|
247
|
+
* out-of-transaction helper — masked input, code·recovery carried) and the canonical ExecutionRefusal is
|
|
248
|
+
* built in one place. A batch prefix states which item failed in the audited sentence; index marks it in
|
|
249
|
+
* the response. Routing every refusal through here is what makes 'a refusal without its audit' structurally
|
|
250
|
+
* impossible rather than a matter of discipline at ~10 call sites. */
|
|
251
|
+
async function refuse(
|
|
252
|
+
command: string,
|
|
253
|
+
identity: Identity,
|
|
254
|
+
rawInput: unknown,
|
|
255
|
+
err: GateError,
|
|
256
|
+
opts: { index?: number; prefix?: string } = {},
|
|
257
|
+
): Promise<ExecutionRefusal> {
|
|
258
|
+
const marked = opts.prefix ? withPrefix(err, opts.prefix) : err
|
|
259
|
+
await tryRecordOutsideTx('refused', command, identity, rawInput, marked)
|
|
260
|
+
return {
|
|
261
|
+
ok: false,
|
|
262
|
+
...(opts.index === undefined ? {} : { index: opts.index }),
|
|
263
|
+
stage: marked.stage,
|
|
264
|
+
stageName: marked.stageName,
|
|
265
|
+
reason: marked.message,
|
|
266
|
+
...refusalMeta(marked),
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
/** Copies a refusal with a reason prefix — audit and response carry the same sentence stating which batch item failed.
|
|
271
|
+
* The error code·recovery hints are copied too (the machine-usable contract survives the prefix). */
|
|
272
|
+
const withPrefix = (refusal: GateError, prefix: string) =>
|
|
273
|
+
prefix
|
|
274
|
+
? new GateError(refusal.stage, refusal.stageName, `${prefix}${refusal.message}`, { code: refusal.code, recovery: refusal.recovery })
|
|
275
|
+
: refusal
|
|
276
|
+
|
|
277
|
+
/** Wraps an app-policy scope refusal into a GateError — a plain string gets the kernel common code (policy.denied);
|
|
278
|
+
* an object carries the app-declared code·recovery action as-is (error codes are never inferred from sentences). */
|
|
279
|
+
const policyRefusalOf = (refusal: string | PolicyRefusal, prefix = '') => {
|
|
280
|
+
const reason = `${prefix}${typeof refusal === 'string' ? refusal : refusal.reason}`
|
|
281
|
+
return typeof refusal === 'string'
|
|
282
|
+
? new GateError(3, 'policy', reason, { code: 'policy.denied' })
|
|
283
|
+
: new GateError(3, 'policy', reason, {
|
|
284
|
+
code: refusal.code,
|
|
285
|
+
...(refusal.recovery ? { recovery: { action: refusal.recovery } } : {}),
|
|
286
|
+
})
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
/**
|
|
290
|
+
* Static checks — once per request, independent of state changes, and must pass before replay of retries.
|
|
291
|
+
* Of stages 1~4 this function checks 2~4 (delegation·policy·schema) — stage 1 identify happens in the server layer before entry.
|
|
292
|
+
*/
|
|
293
|
+
async function validateStatic(def: CommandDefinition<any>, name: string, rawInput: unknown, identity: Identity): Promise<any> {
|
|
294
|
+
// 4 schema is parsed first so permission decisions (2~3) read the *normalized* input — targetOf promises the
|
|
295
|
+
// parsed shape, and normalization (trim·default·transform) must not split what policy approved from what runs.
|
|
296
|
+
// Stage precedence is unchanged: a parse failure is held back and surfaces as stage 4 only after 2~3 passed
|
|
297
|
+
// (until then the raw value stands in for target extraction, exactly as before).
|
|
298
|
+
let parsed: any
|
|
299
|
+
let schemaFailure: unknown
|
|
300
|
+
try {
|
|
301
|
+
parsed = def.input.parse(rawInput)
|
|
302
|
+
} catch (err) {
|
|
303
|
+
schemaFailure = err
|
|
304
|
+
}
|
|
305
|
+
const authInput = schemaFailure === undefined ? parsed : rawInput
|
|
306
|
+
|
|
307
|
+
// 2 delegation — agent (act) tokens move only inside the intersection of delegation scopes (command × target)
|
|
308
|
+
if (identity.delegation && !(await delegationAllows(identity.delegation, name, def, authInput)))
|
|
309
|
+
throw new GateError(
|
|
310
|
+
2,
|
|
311
|
+
'delegation',
|
|
312
|
+
`Out of delegation scope — this token's scopes: ${identity.delegation.scopes.join(', ')}`,
|
|
313
|
+
{ code: 'gate.delegation_denied' },
|
|
314
|
+
)
|
|
315
|
+
|
|
316
|
+
// 3 policy: role × scope — business interpretation of scope (hierarchy·inheritance included) is left to the app policy (S-01).
|
|
317
|
+
// The role predicate is shared with the catalog visibility derivation (visibility.ts)
|
|
318
|
+
if (!roleAllowsCommand(def, identity.role))
|
|
319
|
+
throw new GateError(3, 'policy', `Only roles [${def.allowedRoles.join('/')}] may run this command (current role: ${identity.role})`, {
|
|
320
|
+
code: 'gate.role_denied',
|
|
321
|
+
})
|
|
322
|
+
if (def.scope !== 'none') {
|
|
323
|
+
const refusal = await appPolicy().authorize(identity, def.scope, def.targetOf?.(authInput as any))
|
|
324
|
+
if (refusal) throw policyRefusalOf(refusal)
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
// 4 schema — the held-back parse failure (ZodError → contract refusal; anything else propagates as-is)
|
|
328
|
+
if (schemaFailure !== undefined) {
|
|
329
|
+
if (schemaFailure instanceof ZodError)
|
|
330
|
+
throw new GateError(4, 'schema', schemaFailure.issues.map((i) => `${i.path.join('.')}: ${i.message}`).join('; '), {
|
|
331
|
+
code: 'gate.schema_invalid',
|
|
332
|
+
})
|
|
333
|
+
throw schemaFailure
|
|
334
|
+
}
|
|
335
|
+
return parsed
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
/**
|
|
339
|
+
* Execution-time permission recheck — refuses just before execution when user status·role·delegation·business scope
|
|
340
|
+
* changed after the request started (token verification·static checks). In a batch, an earlier command that changes
|
|
341
|
+
* scope state (e.g. an assignment) is also caught here. The users·delegations tables are kernel-owned so current values
|
|
342
|
+
* can be re-read; business interpretation of scope still belongs to the app policy. targetOf sees the schema-parsed
|
|
343
|
+
* input — the same normalized value the static checks and execution act on. Returns the current identity for execution·audit.
|
|
344
|
+
*/
|
|
345
|
+
async function reauthorize(def: CommandDefinition<any>, name: string, input: any, identity: Identity): Promise<Identity> {
|
|
346
|
+
const current = await currentIdentityOf(identity)
|
|
347
|
+
if (!current) {
|
|
348
|
+
if (identity.delegation)
|
|
349
|
+
throw new GateError(2, 'delegation', 'Delegation is invalid at execution time — revoked, expired, not owned by this account, or the delegating account is inactive', {
|
|
350
|
+
code: 'gate.delegation_denied',
|
|
351
|
+
})
|
|
352
|
+
throw new GateError(3, 'policy', 'User is inactive at execution time — log in again', {
|
|
353
|
+
code: 'auth.relogin_required',
|
|
354
|
+
})
|
|
355
|
+
}
|
|
356
|
+
// 2 delegation — re-decides with the scopes of the currently valid delegation
|
|
357
|
+
if (current.delegation && !(await delegationAllows(current.delegation, name, def, input)))
|
|
358
|
+
throw new GateError(2, 'delegation', `Delegation recheck failed at execution time — this token's scopes: ${current.delegation.scopes.join(', ')}`, {
|
|
359
|
+
code: 'gate.delegation_denied',
|
|
360
|
+
})
|
|
361
|
+
// 3 role·scope — the assignment scope (scopes) used for the decision is also recalculated with current values
|
|
362
|
+
// (an assignment revoked after the request applies immediately). Calculated only for scoped commands — pulling in
|
|
363
|
+
// unscoped commands would entangle the minimal policy-free assembly test. Role predicate shared with visibility.ts
|
|
364
|
+
if (!roleAllowsCommand(def, current.role))
|
|
365
|
+
throw new GateError(3, 'policy', `Role recheck failed at execution time — allowed: [${def.allowedRoles.join('/')}] (current: ${current.role})`, {
|
|
366
|
+
code: 'gate.role_denied',
|
|
367
|
+
})
|
|
368
|
+
if (def.scope !== 'none') {
|
|
369
|
+
const nowScopes: Identity = { ...current, scopes: await appPolicy().scopesFor(current.role, current.userId) }
|
|
370
|
+
const refusal = await appPolicy().authorize(nowScopes, def.scope, def.targetOf?.(input as any))
|
|
371
|
+
if (refusal) throw policyRefusalOf(refusal, 'Scope recheck failed at execution time — ')
|
|
372
|
+
}
|
|
373
|
+
return current
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
/**
|
|
377
|
+
* Dynamic checks (5~7) — depend on current state, so they run just before execution.
|
|
378
|
+
* In a batch, when an earlier command changes state, later commands are re-checked against the changed state (bank-balance analogy).
|
|
379
|
+
*/
|
|
380
|
+
async function validateDynamic(def: CommandDefinition<any>, input: any, identity: Identity): Promise<void> {
|
|
381
|
+
// 5 preconditions
|
|
382
|
+
try {
|
|
383
|
+
await def.precondition?.(input)
|
|
384
|
+
} catch (err) {
|
|
385
|
+
throw toGateError(err, 5, 'precondition')
|
|
386
|
+
}
|
|
387
|
+
// 6 invariants
|
|
388
|
+
try {
|
|
389
|
+
await def.invariants?.(input, identity)
|
|
390
|
+
} catch (err) {
|
|
391
|
+
throw toGateError(err, 6, 'invariant')
|
|
392
|
+
}
|
|
393
|
+
// 7 state transition — enforced against the registry's transition table. An unregistered table is a refusal (no silent pass)
|
|
394
|
+
if (def.transition) {
|
|
395
|
+
const cur = await def.transition.current(input)
|
|
396
|
+
const rows = transitionRulesOf(def.transition.machine).filter(
|
|
397
|
+
(r) => r.command === def.transition!.command && r.from === cur.status,
|
|
398
|
+
)
|
|
399
|
+
if (rows.length === 0)
|
|
400
|
+
throw new GateError(7, 'transition', `This command cannot run from current status '${cur.status}'`, {
|
|
401
|
+
code: 'gate.transition_denied',
|
|
402
|
+
})
|
|
403
|
+
const requestedTo = (input as any).to
|
|
404
|
+
const row = rows.find((r) => !requestedTo || r.to === requestedTo)
|
|
405
|
+
if (!row)
|
|
406
|
+
throw new GateError(7, 'transition', `'${requestedTo}' is not a valid target from status '${cur.status}' (valid: ${rows.map((r) => r.to).join(', ')})`, {
|
|
407
|
+
code: 'gate.transition_denied',
|
|
408
|
+
})
|
|
409
|
+
}
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
/** Command execution (event append + projection apply + audit) — always called inside a transaction */
|
|
413
|
+
async function runCommand(def: CommandDefinition<any>, name: string, input: any, rawInput: unknown, identity: Identity) {
|
|
414
|
+
const { events, result } = await def.execute(input, identity)
|
|
415
|
+
// Output contract — the result shape is checked before commit (the same place as the event contract).
|
|
416
|
+
// A violation is a stage-8 refusal with a full rollback.
|
|
417
|
+
const checked = def.output.safeParse(result)
|
|
418
|
+
if (!checked.success)
|
|
419
|
+
throw new GateError(
|
|
420
|
+
8,
|
|
421
|
+
'execute',
|
|
422
|
+
`Command output violates its contract: ${name} — ${checked.error.issues.map((i) => `${i.path.join('.')}: ${i.message}`).join('; ')}`,
|
|
423
|
+
{ code: 'gate.output_contract_violation' },
|
|
424
|
+
)
|
|
425
|
+
const eventTypes: string[] = []
|
|
426
|
+
for (const e of events) {
|
|
427
|
+
// The recording timestamp is fixed once so storage and projection use the same value — replay and live produce the same state
|
|
428
|
+
const { seq, ts } = await appendEvent(e)
|
|
429
|
+
await applyDomainEvent(e, { seq, ts })
|
|
430
|
+
eventTypes.push(e.type)
|
|
431
|
+
}
|
|
432
|
+
// The success audit is part of the business transaction — a failed insert propagates and rolls the whole
|
|
433
|
+
// command back (stage-8 refusal). It is never routed through the out-of-transaction helper.
|
|
434
|
+
await recordAudit(name, identity, 'ok', rawInput)
|
|
435
|
+
return { result, eventTypes }
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
/** Idempotency lookup — retries are decided before business checks (structure 2) */
|
|
439
|
+
function findIdempotency(identity: Identity, command: string, requestKey: string) {
|
|
440
|
+
return storageOf().findIdempotency(identity.userId, identity.act ?? '', command, requestKey)
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
/** Idempotency decision — the current hash form only: the stored hash must equal the input's hash, byte
|
|
444
|
+
* for byte. A row whose stored hash is not in the current form (written by an older algorithm, or with an
|
|
445
|
+
* empty hash) never matches — the resend is refused as a key conflict (fail safe) instead of risking a
|
|
446
|
+
* replay of a different request. The replayed result is exempt from the current output contract — the
|
|
447
|
+
* contract is the source of truth for what is written *now* (the same principle as event replay). */
|
|
448
|
+
function storedResultOf(hit: { inputHash: string; resultJson: string }, requestKey: string, body: unknown): ExecutionResult {
|
|
449
|
+
if (hit.inputHash !== inputHashOf(body))
|
|
450
|
+
throw new GateError(6, 'invariant', `A different request was sent with the same requestKey ('${requestKey}') — use a new key`, {
|
|
451
|
+
code: 'gate.idempotency_key_conflict',
|
|
452
|
+
})
|
|
453
|
+
const stored = JSON.parse(hit.resultJson)
|
|
454
|
+
return { ok: true, result: stored.result, events: stored.events, replayed: true }
|
|
455
|
+
}
|
|
456
|
+
|
|
457
|
+
/** Canonical JSON — object keys sorted at every depth, so the same business request hashes identically no matter
|
|
458
|
+
* the field order (agents rebuild JSON on retries; only array order is meaningfully part of a request). */
|
|
459
|
+
function canonicalJson(v: unknown): string {
|
|
460
|
+
if (Array.isArray(v)) return `[${v.map(canonicalJson).join(',')}]`
|
|
461
|
+
if (v && typeof v === 'object') {
|
|
462
|
+
const entries = Object.entries(v as Record<string, unknown>).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
|
|
463
|
+
return `{${entries.map(([k, val]) => `${JSON.stringify(k)}:${canonicalJson(val)}`).join(',')}}`
|
|
464
|
+
}
|
|
465
|
+
return JSON.stringify(v) ?? 'null'
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
/** Idempotency input hash — a keyed digest (version-prefixed) of the canonicalized business input (protocol
|
|
469
|
+
* options stripped, keys sorted). A bare SHA-256 would leave offline-verifiable password material in the
|
|
470
|
+
* idempotency table whenever a request carries one — the same premise under which audit input is masked (G-01).
|
|
471
|
+
* The JWT secret keys it, with a domain-separation prefix so the same key never signs two meanings. */
|
|
472
|
+
const inputHashOf = (body: unknown) =>
|
|
473
|
+
'h2:' + createHmac('sha256', storageOf().jwtSecret()).update('idempotency-input\0' + canonicalJson(body)).digest('hex')
|
|
474
|
+
|
|
475
|
+
async function replayOrReject(identity: Identity, command: string, requestKey: string, body: unknown): Promise<ExecutionResult | null> {
|
|
476
|
+
const hit = await findIdempotency(identity, command, requestKey)
|
|
477
|
+
if (!hit) return null
|
|
478
|
+
return storedResultOf(hit, requestKey, body)
|
|
479
|
+
}
|
|
480
|
+
|
|
481
|
+
/**
|
|
482
|
+
* Concurrent-retry settlement — after rolling back on a lock or duplicate-key conflict during execution,
|
|
483
|
+
* if another process already committed with the same key, the stored result is returned (no double apply).
|
|
484
|
+
* A different input keeps the existing rule (same key·different input refused); if the recheck itself fails,
|
|
485
|
+
* null is returned so the caller proceeds with the original error.
|
|
486
|
+
*/
|
|
487
|
+
async function settleConcurrentRetry(identity: Identity, command: string, requestKey: string, body: unknown): Promise<ExecutionResult | null> {
|
|
488
|
+
try {
|
|
489
|
+
const hit = await findIdempotency(identity, command, requestKey)
|
|
490
|
+
if (!hit) return null
|
|
491
|
+
try {
|
|
492
|
+
return storedResultOf(hit, requestKey, body)
|
|
493
|
+
} catch (err) {
|
|
494
|
+
const refusal = toGateError(err, 6, 'invariant')
|
|
495
|
+
return { ok: false, stage: refusal.stage, stageName: refusal.stageName, reason: refusal.message, ...refusalMeta(refusal) }
|
|
496
|
+
}
|
|
497
|
+
} catch {
|
|
498
|
+
return null // recheck failed (lock etc.) — the original error is reported as-is
|
|
499
|
+
}
|
|
500
|
+
}
|
|
501
|
+
|
|
502
|
+
async function storeIdempotency(identity: Identity, command: string, requestKey: string, body: unknown, result: unknown, events: string[]) {
|
|
503
|
+
await storageOf().insertIdempotency({
|
|
504
|
+
subjectId: identity.userId,
|
|
505
|
+
act: identity.act ?? '',
|
|
506
|
+
command,
|
|
507
|
+
requestKey,
|
|
508
|
+
inputHash: inputHashOf(body),
|
|
509
|
+
resultJson: JSON.stringify({ result, events }),
|
|
510
|
+
createdAt: new Date().toISOString(),
|
|
511
|
+
})
|
|
512
|
+
}
|
|
513
|
+
|
|
514
|
+
/**
|
|
515
|
+
* The write kernel (gatekeeper) — the single path every write passes through.
|
|
516
|
+
* 1 identify 2 delegation 3 policy 4 schema (static) 5 preconditions 6 invariants 7 transitions (dynamic, just before execution) 8 execute 9 audit.
|
|
517
|
+
* Refusals are first-class results: the stage and reason remain as audit events — early refusals such as
|
|
518
|
+
* unregistered commands are no exception. Common options: requestKey (idempotent replay — decided before business
|
|
519
|
+
* checks), dryRun (validation only).
|
|
520
|
+
*/
|
|
521
|
+
export async function executeCommand(name: string, rawInput: unknown, identity: Identity): Promise<ExecutionResult> {
|
|
522
|
+
completeAssembly()
|
|
523
|
+
return executeCommandInner(name, rawInput, identity)
|
|
524
|
+
}
|
|
525
|
+
|
|
526
|
+
async function executeCommandInner(name: string, rawInput: unknown, identity: Identity): Promise<ExecutionResult> {
|
|
527
|
+
const def = lookupCommand(name)
|
|
528
|
+
if (!def)
|
|
529
|
+
return await refuse(name, identity, rawInput, new GateError(0, 'registry', `Unknown command: ${name}`, { code: 'gate.unknown_command' }))
|
|
530
|
+
|
|
531
|
+
const { requestKey, dryRun, body } = splitProtocolOptions(rawInput)
|
|
532
|
+
try {
|
|
533
|
+
const input = await validateStatic(def, name, body, identity)
|
|
534
|
+
|
|
535
|
+
// Idempotent replay — a resend of the same request that passed connection·permissions·format (1~4) returns the stored result.
|
|
536
|
+
// Decided before business checks so a state-changed retry (e.g. version conflict) never overwrites the original success.
|
|
537
|
+
if (requestKey && !dryRun) {
|
|
538
|
+
const replayed = await replayOrReject(identity, name, requestKey, body)
|
|
539
|
+
if (replayed) {
|
|
540
|
+
await tryRecordOutsideTx('replay', name, identity, rawInput)
|
|
541
|
+
return replayed
|
|
542
|
+
}
|
|
543
|
+
}
|
|
544
|
+
|
|
545
|
+
// dry-run — side-effect-free validation. Runs dynamic checks up to (and including) the execution-time permission recheck.
|
|
546
|
+
// A failed dry-run audit record does NOT change the result (the validation passed and wrote nothing):
|
|
547
|
+
// the loss is diagnosed on stderr by the shared out-of-transaction helper.
|
|
548
|
+
if (dryRun) {
|
|
549
|
+
const current = await reauthorize(def, name, input, identity)
|
|
550
|
+
await validateDynamic(def, input, current)
|
|
551
|
+
await tryRecordOutsideTx('dry-run', name, identity, rawInput)
|
|
552
|
+
return { ok: true, dryRun: true, result: { validated: true, note: 'stages 1-7 passed — stage 8 (execute) was not run' } }
|
|
553
|
+
}
|
|
554
|
+
|
|
555
|
+
// 8~9 execution + audit — permissions (2~3) are re-checked against current state just before execution
|
|
556
|
+
// (refused when role·delegation·scope changed after the request), and events·projections·idempotency·audit
|
|
557
|
+
// are handled atomically in one write-lock transaction (the physical layer takes the write lock up front —
|
|
558
|
+
// see the capability contract on the storage port).
|
|
559
|
+
let out: { result: unknown; eventTypes: string[] }
|
|
560
|
+
try {
|
|
561
|
+
out = await storageOf().immediate(async () => {
|
|
562
|
+
const current = await reauthorize(def, name, input, identity)
|
|
563
|
+
await validateDynamic(def, input, current)
|
|
564
|
+
const r = await runCommand(def, name, input, rawInput, current)
|
|
565
|
+
if (requestKey) await storeIdempotency(identity, name, requestKey, body, r.result, r.eventTypes)
|
|
566
|
+
return r
|
|
567
|
+
})
|
|
568
|
+
} catch (err) {
|
|
569
|
+
// concurrent retry — if another process committed first with the same key, the stored result is returned
|
|
570
|
+
if (requestKey) {
|
|
571
|
+
const settled = await settleConcurrentRetry(identity, name, requestKey, body)
|
|
572
|
+
if (settled) {
|
|
573
|
+
await auditSettled(name, identity, rawInput, settled)
|
|
574
|
+
return settled
|
|
575
|
+
}
|
|
576
|
+
}
|
|
577
|
+
throw toGateError(err, 8, 'execute')
|
|
578
|
+
}
|
|
579
|
+
|
|
580
|
+
return { ok: true, result: out.result, events: out.eventTypes }
|
|
581
|
+
} catch (err) {
|
|
582
|
+
// A failure here includes a failed success-audit insert — the transaction already rolled the command back
|
|
583
|
+
return await refuse(name, identity, rawInput, toGateError(err, 8, 'execute'))
|
|
584
|
+
}
|
|
585
|
+
}
|
|
586
|
+
|
|
587
|
+
/**
|
|
588
|
+
* Batch execution — after all static checks (1~4) pass, 'permission recheck → dynamic checks → execution'
|
|
589
|
+
* repeats per command just before it executes, inside one transaction (an earlier command's changes are reflected
|
|
590
|
+
* in later commands' permission·state checks). A single refusal rolls the whole batch back and only the refusal
|
|
591
|
+
* record remains. A requestKey identifying the whole batch is also supported. Batch items carry no protocol
|
|
592
|
+
* options (requestKey·dryRun) — those are refused clearly (gate.option_not_supported).
|
|
593
|
+
*/
|
|
594
|
+
export async function executeBatch(
|
|
595
|
+
items: { name: string; input?: unknown }[],
|
|
596
|
+
identity: Identity,
|
|
597
|
+
batchRequestKey?: string,
|
|
598
|
+
batchDryRun?: boolean,
|
|
599
|
+
): Promise<ExecutionResult> {
|
|
600
|
+
completeAssembly()
|
|
601
|
+
return executeBatchInner(items, identity, batchRequestKey, batchDryRun)
|
|
602
|
+
}
|
|
603
|
+
|
|
604
|
+
async function executeBatchInner(
|
|
605
|
+
items: { name: string; input?: unknown }[],
|
|
606
|
+
identity: Identity,
|
|
607
|
+
batchRequestKey?: string,
|
|
608
|
+
batchDryRun?: boolean,
|
|
609
|
+
): Promise<ExecutionResult> {
|
|
610
|
+
// Unsupported protocol option — dry-run is for single commands; a batch is atomic execution
|
|
611
|
+
if (batchDryRun)
|
|
612
|
+
return await refuse(
|
|
613
|
+
'batch',
|
|
614
|
+
identity,
|
|
615
|
+
items,
|
|
616
|
+
new GateError(
|
|
617
|
+
4,
|
|
618
|
+
'schema',
|
|
619
|
+
'dryRun is not supported for batches — dry-run each command individually, or send the batch without it',
|
|
620
|
+
{ code: 'gate.option_not_supported' },
|
|
621
|
+
),
|
|
622
|
+
)
|
|
623
|
+
|
|
624
|
+
if (!Array.isArray(items) || items.length === 0 || items.length > 20)
|
|
625
|
+
return await refuse('batch', identity, items, new GateError(4, 'schema', 'commands must be an array of 1 to 20 items', { code: 'gate.schema_invalid' }))
|
|
626
|
+
|
|
627
|
+
const validated: { def: CommandDefinition<any>; name: string; input: any; rawInput: unknown }[] = []
|
|
628
|
+
for (let i = 0; i < items.length; i++) {
|
|
629
|
+
const it = items[i] ?? {}
|
|
630
|
+
const def = lookupCommand(it.name)
|
|
631
|
+
if (!def)
|
|
632
|
+
return await refuse('batch', identity, items, new GateError(0, 'registry', `Unknown command: ${it.name}`, { code: 'gate.unknown_command' }), {
|
|
633
|
+
index: i,
|
|
634
|
+
prefix: `#${i} ${it.name}: `,
|
|
635
|
+
})
|
|
636
|
+
// Protocol options are batch-level, not item-level — an item carrying one is a clear refusal, never silent execution
|
|
637
|
+
const { requestKey: itemKey, dryRun: itemDry, body: itemBody } = splitProtocolOptions(it.input ?? {})
|
|
638
|
+
if (itemKey || itemDry)
|
|
639
|
+
return await refuse(
|
|
640
|
+
'batch',
|
|
641
|
+
identity,
|
|
642
|
+
items,
|
|
643
|
+
new GateError(
|
|
644
|
+
4,
|
|
645
|
+
'schema',
|
|
646
|
+
`Protocol option '${itemKey ? 'requestKey' : 'dryRun'}' is not supported inside a batch item — identify the whole batch with the top-level requestKey, and dry-run each command individually`,
|
|
647
|
+
{ code: 'gate.option_not_supported' },
|
|
648
|
+
),
|
|
649
|
+
{ index: i, prefix: `#${i} ${it.name}: ` },
|
|
650
|
+
)
|
|
651
|
+
try {
|
|
652
|
+
validated.push({ def, name: it.name, input: await validateStatic(def, it.name, itemBody, identity), rawInput: it.input })
|
|
653
|
+
} catch (err) {
|
|
654
|
+
return await refuse('batch', identity, items, toGateError(err, 8, 'execute'), { index: i, prefix: `#${i} ${it.name}: ` })
|
|
655
|
+
}
|
|
656
|
+
}
|
|
657
|
+
|
|
658
|
+
if (batchRequestKey) {
|
|
659
|
+
let replayed: ExecutionResult | null = null
|
|
660
|
+
try {
|
|
661
|
+
replayed = await replayOrReject(identity, 'batch', batchRequestKey, items)
|
|
662
|
+
} catch (err) {
|
|
663
|
+
return await refuse('batch', identity, items, toGateError(err, 6, 'invariant'))
|
|
664
|
+
}
|
|
665
|
+
if (replayed) {
|
|
666
|
+
await tryRecordOutsideTx('replay', 'batch', identity, items)
|
|
667
|
+
return replayed.ok ? { ...replayed, results: (replayed.result as any)?.results } : replayed
|
|
668
|
+
}
|
|
669
|
+
}
|
|
670
|
+
|
|
671
|
+
// One write-lock transaction for the whole batch (the BEGIN and lock waits follow the storage port's
|
|
672
|
+
// capability contract — see the single-command note above). The BEGIN is inside the try, so a lock-wait
|
|
673
|
+
// timeout also reaches the common handling below and returns the canonical refusal·audit.
|
|
674
|
+
try {
|
|
675
|
+
const results = await storageOf().immediate(async () => {
|
|
676
|
+
const rs = []
|
|
677
|
+
for (let i = 0; i < validated.length; i++) {
|
|
678
|
+
const v = validated[i]
|
|
679
|
+
try {
|
|
680
|
+
const current = await reauthorize(v.def, v.name, v.input, identity) // execution-time permissions — earlier command scope changes are caught here
|
|
681
|
+
await validateDynamic(v.def, v.input, current) // current-state checks just before execution
|
|
682
|
+
const r = await runCommand(v.def, v.name, v.input, v.rawInput, current)
|
|
683
|
+
rs.push({ name: v.name, ok: true, result: r.result, events: r.eventTypes })
|
|
684
|
+
} catch (err) {
|
|
685
|
+
;(err as any).batchIndex = i // carries which command (index) failed into the refusal response
|
|
686
|
+
throw err
|
|
687
|
+
}
|
|
688
|
+
}
|
|
689
|
+
if (batchRequestKey) await storeIdempotency(identity, 'batch', batchRequestKey, items, { results: rs }, rs.flatMap((r) => r.events))
|
|
690
|
+
return rs
|
|
691
|
+
})
|
|
692
|
+
return { ok: true, results }
|
|
693
|
+
} catch (err) {
|
|
694
|
+
// A failure here includes a failed success-audit insert — the transaction already rolled the whole batch back
|
|
695
|
+
const i = (err as any).batchIndex as number | undefined
|
|
696
|
+
// concurrent retry — if another process committed first with the same key, the stored result is returned
|
|
697
|
+
if (batchRequestKey) {
|
|
698
|
+
const settled = await settleConcurrentRetry(identity, 'batch', batchRequestKey, items)
|
|
699
|
+
if (settled) {
|
|
700
|
+
await auditSettled('batch', identity, items, settled)
|
|
701
|
+
return settled.ok
|
|
702
|
+
? { ...settled, ...(i === undefined ? {} : { index: i }), results: (settled.result as any)?.results }
|
|
703
|
+
: { ...settled, ...(i === undefined ? {} : { index: i }) }
|
|
704
|
+
}
|
|
705
|
+
}
|
|
706
|
+
return await refuse('batch', identity, items, toGateError(err, 8, 'execute'), {
|
|
707
|
+
...(i === undefined ? {} : { index: i, prefix: `#${i} ${items[i]?.name ?? ''}: ` }),
|
|
708
|
+
})
|
|
709
|
+
}
|
|
710
|
+
}
|