@sudoke/kernel 0.3.1 → 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.
- package/README.md +221 -0
- package/package.json +5 -4
- package/src/canonical.ts +18 -0
- package/src/catalog.ts +282 -0
- package/src/contract-shape.ts +531 -0
- package/src/execution-core.ts +115 -0
- package/src/gate-audit.ts +131 -0
- package/src/gate-results.ts +93 -0
- package/src/gate.ts +333 -386
- package/src/idempotency.ts +133 -0
- package/src/index.ts +7 -1
- package/src/mcp.ts +183 -29
- package/src/permissions.ts +92 -0
- package/src/projections.ts +16 -2
- package/src/protocol.ts +7 -1
- package/src/queries.ts +5 -0
- package/src/registry.ts +130 -6
- package/src/releases.ts +527 -0
- package/src/state.ts +33 -1
- package/src/storage.ts +44 -2
- package/src/types.ts +195 -0
- package/src/undo.ts +671 -0
package/src/gate.ts
CHANGED
|
@@ -1,70 +1,52 @@
|
|
|
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
1
|
/**
|
|
13
|
-
*
|
|
14
|
-
*
|
|
2
|
+
* The write kernel (gatekeeper) — the single path every write passes through.
|
|
3
|
+
* 1 identify 2 delegation 3 policy 4 schema (static) 5 preconditions 6 invariants 7 transitions (dynamic, just before execution) 8 execute 9 audit.
|
|
4
|
+
* Refusals are first-class results: the stage and reason remain as audit events — early refusals such as
|
|
5
|
+
* unregistered commands are no exception. Common options: requestKey (idempotent replay — decided before business
|
|
6
|
+
* checks), dryRun (validation only).
|
|
15
7
|
*
|
|
16
|
-
*
|
|
17
|
-
*
|
|
18
|
-
*
|
|
19
|
-
*
|
|
20
|
-
*
|
|
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
|
|
8
|
+
* This module holds the ENTRY POINTS and the check sequence (checks·replay·transaction·execution
|
|
9
|
+
* order reads here); the machinery lives in dedicated internal modules: gate-results (the refusal
|
|
10
|
+
* vocabulary), gate-audit (audit recording and the single refusal exit), idempotency (stored
|
|
11
|
+
* results and settlement), execution-core (the in-transaction command pipeline), permissions
|
|
12
|
+
* (the shared permission judgments).
|
|
30
13
|
*/
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
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
|
|
14
|
+
import { ZodError } from 'zod'
|
|
15
|
+
import { randomUUID } from 'node:crypto'
|
|
16
|
+
import { storageOf } from './storage.js'
|
|
17
|
+
import { appPolicy } from './policy.js'
|
|
18
|
+
import { completeAssembly, kernelOptions, lookupCommand, transitionRulesOf } from './registry.js'
|
|
19
|
+
import { commandRevisionOf, PROTOCOL_VERSION, responseMetaOf } from './catalog.js'
|
|
20
|
+
import { roleAllowsCommand } from './visibility.js'
|
|
21
|
+
import { GateError, type CommandDefinition, type ContractMeta, type Identity } from './types.js'
|
|
22
|
+
import { canonicalJson } from './canonical.js'
|
|
23
|
+
import {
|
|
24
|
+
assertLiveRoleAllows,
|
|
25
|
+
assertRecordedDelegationCovers,
|
|
26
|
+
delegationAllowsRecorded,
|
|
27
|
+
judgedIdentityOf,
|
|
28
|
+
liveIdentityOf,
|
|
29
|
+
policyRefusalGateError,
|
|
30
|
+
unprovableRefusal,
|
|
31
|
+
} from './permissions.js'
|
|
32
|
+
import { toGateError } from './gate-results.js'
|
|
33
|
+
import type { ExecutionResult, ExecutionRefusal, ExecutionSuccess } from './gate-results.js'
|
|
34
|
+
import { auditSettled, refuse, tryRecordOutsideTx } from './gate-audit.js'
|
|
35
|
+
import { batchProducerOf, producerOf, replayOrReject, settleConcurrentRetry, storeIdempotency } from './idempotency.js'
|
|
36
|
+
import { runCommand, type OperationContext } from './execution-core.js'
|
|
37
|
+
|
|
38
|
+
/** Contract metadata on every success response — the CURRENT revisions, distinguished from the result
|
|
39
|
+
* itself: a replayed result was produced by an older contract, and the meta says what is true now. */
|
|
40
|
+
export type { ContractResponseMeta } from './types.js'
|
|
41
|
+
export type { ExecutionSuccess, ExecutionRefusal, ExecutionResult } from './gate-results.js'
|
|
62
42
|
|
|
63
43
|
/**
|
|
64
44
|
* Delegation scope check — the acting radius of an agent token.
|
|
65
45
|
* Scope syntax (kernel contract): '*' | 'commandName' | 'commandName:target' — what a target refers to is defined by the app policy.
|
|
66
46
|
* Target restrictions reflect only 'entries attached to this command' — so target ranges of other commands never mix in (G-05).
|
|
67
47
|
*/
|
|
48
|
+
/** The delegation verdict on RECORDED material (a removed command's redelivery): same entry
|
|
49
|
+
* selection and same target logic as the live check below — one predicate, no drift. */
|
|
68
50
|
async function delegationAllows(
|
|
69
51
|
del: NonNullable<Identity['delegation']>,
|
|
70
52
|
commandName: string,
|
|
@@ -72,225 +54,50 @@ async function delegationAllows(
|
|
|
72
54
|
input: unknown,
|
|
73
55
|
): Promise<boolean> {
|
|
74
56
|
// 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
57
|
const targetId = def.scope !== 'none' ? def.targetOf?.(input as any) : undefined
|
|
79
|
-
|
|
80
|
-
const targets = entries.map((sc) => sc.slice(sc.indexOf(':') + 1))
|
|
81
|
-
return await appPolicy().delegationCovers(targetId, targets)
|
|
58
|
+
return delegationAllowsRecorded(del, commandName, def.scope, targetId)
|
|
82
59
|
}
|
|
83
60
|
|
|
84
|
-
/** Common protocol options (requestKey·dryRun) ride beside the business input but are not part
|
|
85
|
-
* before the schema so even a .strict() business schema never sees them, and excluded
|
|
86
|
-
*
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
61
|
+
/** Common protocol options (requestKey·dryRun·contract) ride beside the business input but are not part
|
|
62
|
+
* of it — stripped before the schema so even a .strict() business schema never sees them, and excluded
|
|
63
|
+
* from permission targets (the same business request hashes identically however the options were spelled).
|
|
64
|
+
* The idempotency hash DOES include the contract identity when one was sent: a resend under the same key
|
|
65
|
+
* must carry the same contract — a new contract on a stored key is an input conflict, never a replay. */
|
|
66
|
+
function splitProtocolOptions(raw: unknown): {
|
|
67
|
+
requestKey?: string
|
|
68
|
+
dryRun: boolean
|
|
69
|
+
contract?: ContractMeta
|
|
70
|
+
/** the contract field was present but malformed — refused as contract_required, never silently ignored */
|
|
71
|
+
contractMalformed: boolean
|
|
72
|
+
body: unknown
|
|
73
|
+
} {
|
|
74
|
+
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return { dryRun: false, contractMalformed: false, body: raw }
|
|
75
|
+
const { requestKey, dryRun, contract, ...body } = raw as Record<string, unknown>
|
|
76
|
+
const wellFormed =
|
|
77
|
+
!!contract &&
|
|
78
|
+
typeof contract === 'object' &&
|
|
79
|
+
typeof (contract as Record<string, unknown>).commandVersion === 'string' &&
|
|
80
|
+
typeof (contract as Record<string, unknown>).commandRevision === 'string' &&
|
|
81
|
+
typeof (contract as Record<string, unknown>).protocolVersion === 'string'
|
|
90
82
|
return {
|
|
91
83
|
requestKey: typeof requestKey === 'string' && requestKey.length > 0 ? requestKey.slice(0, 100) : undefined,
|
|
92
84
|
dryRun: dryRun === true,
|
|
85
|
+
...(wellFormed ? { contract: contract as ContractMeta } : {}),
|
|
86
|
+
contractMalformed: contract !== undefined && !wellFormed,
|
|
93
87
|
body,
|
|
94
88
|
}
|
|
95
89
|
}
|
|
96
90
|
|
|
97
|
-
/**
|
|
98
|
-
*
|
|
99
|
-
const
|
|
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
|
-
}
|
|
91
|
+
/** The value the idempotency hash covers — the business input plus the contract identity when sent.
|
|
92
|
+
* canonicalJson sorts keys, so option spelling and field order never change the hash. */
|
|
93
|
+
const hashBodyOf = (body: unknown, contract?: ContractMeta): unknown => (contract ? { contract, body } : body)
|
|
288
94
|
|
|
289
95
|
/**
|
|
290
96
|
* Static checks — once per request, independent of state changes, and must pass before replay of retries.
|
|
291
97
|
* Of stages 1~4 this function checks 2~4 (delegation·policy·schema) — stage 1 identify happens in the server layer before entry.
|
|
98
|
+
* Exported for undo.ts — a compensation passes the identical checks (no bypass lane).
|
|
292
99
|
*/
|
|
293
|
-
async function validateStatic(def: CommandDefinition<any>, name: string, rawInput: unknown, identity: Identity): Promise<any> {
|
|
100
|
+
export async function validateStatic(def: CommandDefinition<any>, name: string, rawInput: unknown, identity: Identity): Promise<any> {
|
|
294
101
|
// 4 schema is parsed first so permission decisions (2~3) read the *normalized* input — targetOf promises the
|
|
295
102
|
// parsed shape, and normalization (trim·default·transform) must not split what policy approved from what runs.
|
|
296
103
|
// Stage precedence is unchanged: a parse failure is held back and surfaces as stage 4 only after 2~3 passed
|
|
@@ -321,7 +128,7 @@ async function validateStatic(def: CommandDefinition<any>, name: string, rawInpu
|
|
|
321
128
|
})
|
|
322
129
|
if (def.scope !== 'none') {
|
|
323
130
|
const refusal = await appPolicy().authorize(identity, def.scope, def.targetOf?.(authInput as any))
|
|
324
|
-
if (refusal) throw
|
|
131
|
+
if (refusal) throw policyRefusalGateError(refusal, '', { carryRecovery: true })
|
|
325
132
|
}
|
|
326
133
|
|
|
327
134
|
// 4 schema — the held-back parse failure (ZodError → contract refusal; anything else propagates as-is)
|
|
@@ -341,18 +148,16 @@ async function validateStatic(def: CommandDefinition<any>, name: string, rawInpu
|
|
|
341
148
|
* scope state (e.g. an assignment) is also caught here. The users·delegations tables are kernel-owned so current values
|
|
342
149
|
* can be re-read; business interpretation of scope still belongs to the app policy. targetOf sees the schema-parsed
|
|
343
150
|
* input — the same normalized value the static checks and execution act on. Returns the current identity for execution·audit.
|
|
151
|
+
* Exported for undo.ts — the compensation re-authorizes identically.
|
|
344
152
|
*/
|
|
345
|
-
async function reauthorize(def: CommandDefinition<any>, name: string, input: any, identity: Identity): Promise<Identity> {
|
|
346
|
-
const current = await
|
|
347
|
-
if (!current) {
|
|
153
|
+
export async function reauthorize(def: CommandDefinition<any>, name: string, input: any, identity: Identity): Promise<Identity> {
|
|
154
|
+
const current = await liveIdentityOf(identity, () => {
|
|
348
155
|
if (identity.delegation)
|
|
349
156
|
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
157
|
code: 'gate.delegation_denied',
|
|
351
158
|
})
|
|
352
|
-
throw new GateError(3, 'policy', 'User is inactive at execution time — log in again', {
|
|
353
|
-
|
|
354
|
-
})
|
|
355
|
-
}
|
|
159
|
+
throw new GateError(3, 'policy', 'User is inactive at execution time — log in again', { code: 'auth.relogin_required' })
|
|
160
|
+
})
|
|
356
161
|
// 2 delegation — re-decides with the scopes of the currently valid delegation
|
|
357
162
|
if (current.delegation && !(await delegationAllows(current.delegation, name, def, input)))
|
|
358
163
|
throw new GateError(2, 'delegation', `Delegation recheck failed at execution time — this token's scopes: ${current.delegation.scopes.join(', ')}`, {
|
|
@@ -361,14 +166,11 @@ async function reauthorize(def: CommandDefinition<any>, name: string, input: any
|
|
|
361
166
|
// 3 role·scope — the assignment scope (scopes) used for the decision is also recalculated with current values
|
|
362
167
|
// (an assignment revoked after the request applies immediately). Calculated only for scoped commands — pulling in
|
|
363
168
|
// unscoped commands would entangle the minimal policy-free assembly test. Role predicate shared with visibility.ts
|
|
364
|
-
|
|
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
|
-
})
|
|
169
|
+
assertLiveRoleAllows(def, current.role, `Role recheck failed at execution time — allowed: [${def.allowedRoles.join('/')}] (current: ${current.role})`)
|
|
368
170
|
if (def.scope !== 'none') {
|
|
369
|
-
const nowScopes
|
|
171
|
+
const nowScopes = await judgedIdentityOf(current)
|
|
370
172
|
const refusal = await appPolicy().authorize(nowScopes, def.scope, def.targetOf?.(input as any))
|
|
371
|
-
if (refusal) throw
|
|
173
|
+
if (refusal) throw policyRefusalGateError(refusal, 'Scope recheck failed at execution time — ', { carryRecovery: true })
|
|
372
174
|
}
|
|
373
175
|
return current
|
|
374
176
|
}
|
|
@@ -376,8 +178,9 @@ async function reauthorize(def: CommandDefinition<any>, name: string, input: any
|
|
|
376
178
|
/**
|
|
377
179
|
* Dynamic checks (5~7) — depend on current state, so they run just before execution.
|
|
378
180
|
* In a batch, when an earlier command changes state, later commands are re-checked against the changed state (bank-balance analogy).
|
|
181
|
+
* Exported for undo.ts — the compensation runs them inside the same transaction.
|
|
379
182
|
*/
|
|
380
|
-
async function validateDynamic(def: CommandDefinition<any>, input: any, identity: Identity): Promise<void> {
|
|
183
|
+
export async function validateDynamic(def: CommandDefinition<any>, input: any, identity: Identity): Promise<void> {
|
|
381
184
|
// 5 preconditions
|
|
382
185
|
try {
|
|
383
186
|
await def.precondition?.(input)
|
|
@@ -409,106 +212,72 @@ async function validateDynamic(def: CommandDefinition<any>, input: any, identity
|
|
|
409
212
|
}
|
|
410
213
|
}
|
|
411
214
|
|
|
412
|
-
/**
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
215
|
+
/** Permission precheck without schema parsing — the strict replay-first path uses it where the resent
|
|
216
|
+
* input may no longer parse under the current schema. Role needs no input; delegation target extraction
|
|
217
|
+
* reads the raw body (a plain field read in practice). The app-policy scope check (parsed-input
|
|
218
|
+
* dependent) is not repeated for a redelivery — there is no new effect to authorize. */
|
|
219
|
+
export async function quickPermissionCheck(def: CommandDefinition<any>, name: string, input: unknown, identity: Identity): Promise<void> {
|
|
220
|
+
if (!roleAllowsCommand(def, identity.role))
|
|
221
|
+
throw new GateError(3, 'policy', `Only roles [${def.allowedRoles.join('/')}] may run this command (current role: ${identity.role})`, {
|
|
222
|
+
code: 'gate.role_denied',
|
|
223
|
+
})
|
|
224
|
+
if (identity.delegation && !(await delegationAllows(identity.delegation, name, def, input)))
|
|
419
225
|
throw new GateError(
|
|
420
|
-
|
|
421
|
-
'
|
|
422
|
-
`
|
|
423
|
-
{ code: 'gate.
|
|
226
|
+
2,
|
|
227
|
+
'delegation',
|
|
228
|
+
`Out of delegation scope — this token's scopes: ${identity.delegation.scopes.join(', ')}`,
|
|
229
|
+
{ code: 'gate.delegation_denied' },
|
|
424
230
|
)
|
|
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
231
|
}
|
|
442
232
|
|
|
443
|
-
/**
|
|
444
|
-
*
|
|
445
|
-
*
|
|
446
|
-
*
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
if (
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
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)
|
|
233
|
+
/** Strict-mode contract check — the write is refused before execution when the caller's contract view is
|
|
234
|
+
* stale. The revision match is exact: within one MAJOR, description·warning·behavior changes must be
|
|
235
|
+
* re-confirmed too. Only THIS command's revision matters — other commands changing never refuses here
|
|
236
|
+
* (their revisions did not move). */
|
|
237
|
+
export function checkContract(def: CommandDefinition<any>, contract: ContractMeta | undefined, malformed: boolean): void {
|
|
238
|
+
if (malformed || !contract)
|
|
239
|
+
throw new GateError(
|
|
240
|
+
4,
|
|
241
|
+
'schema',
|
|
242
|
+
'This kernel runs in strict contract mode — send contract:{commandVersion,commandRevision,protocolVersion} beside the business input (read them from the catalog)',
|
|
243
|
+
{ code: 'gate.contract_required' },
|
|
244
|
+
)
|
|
245
|
+
const diffs: string[] = []
|
|
246
|
+
if (contract.commandVersion !== (def.version ?? ''))
|
|
247
|
+
diffs.push(`commandVersion ${contract.commandVersion} → ${def.version ?? '(undeclared)'}`)
|
|
248
|
+
if (contract.commandRevision !== (commandRevisionOf(def.name) ?? '')) diffs.push('commandRevision changed')
|
|
249
|
+
if (contract.protocolVersion !== PROTOCOL_VERSION) diffs.push(`protocolVersion ${contract.protocolVersion} → ${PROTOCOL_VERSION}`)
|
|
250
|
+
if (diffs.length > 0)
|
|
251
|
+
throw new GateError(
|
|
252
|
+
4,
|
|
253
|
+
'schema',
|
|
254
|
+
`The command contract changed since this request was built (${diffs.join(', ')}) — read the catalog status and what changed, re-learn the fields, then resend with the current contract`,
|
|
255
|
+
{ code: 'gate.contract_changed', recovery: { action: 'refresh' } },
|
|
256
|
+
)
|
|
479
257
|
}
|
|
480
258
|
|
|
481
|
-
/**
|
|
482
|
-
*
|
|
483
|
-
*
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
259
|
+
/** Re-proves each item's recorded rights for a stored batch result — the strict replay probe and the
|
|
260
|
+
* concurrent-retry settlement share this (a batch redelivery is a fresh READ of every item). Returns
|
|
261
|
+
* the refusal response, or null when the whole batch is still provable. */
|
|
262
|
+
async function batchRightsRefusal(items: { name: string }[], identity: Identity, producedBy: unknown): Promise<ExecutionResult | null> {
|
|
263
|
+
const perItem = (producedBy as { items?: unknown[] } | undefined)?.items
|
|
264
|
+
if (!Array.isArray(perItem) || perItem.length !== items.length)
|
|
265
|
+
return await refuse(
|
|
266
|
+
'batch',
|
|
267
|
+
identity,
|
|
268
|
+
items,
|
|
269
|
+
new GateError(3, 'policy', 'The stored batch predates per-item rights tracking — the rights cannot be re-proven, so the result is refused', {
|
|
270
|
+
code: 'policy.denied',
|
|
271
|
+
}),
|
|
272
|
+
)
|
|
273
|
+
for (let i = 0; i < items.length; i++) {
|
|
491
274
|
try {
|
|
492
|
-
|
|
275
|
+
await assertReplayRights(String((perItem[i] as { commandName?: string })?.commandName ?? items[i]?.name), identity, perItem[i])
|
|
493
276
|
} catch (err) {
|
|
494
|
-
|
|
495
|
-
return { ok: false, stage: refusal.stage, stageName: refusal.stageName, reason: refusal.message, ...refusalMeta(refusal) }
|
|
277
|
+
return await refuse('batch', identity, items, toGateError(err, 3, 'policy'), { index: i, prefix: `#${i} ${items[i]?.name ?? ''}: ` })
|
|
496
278
|
}
|
|
497
|
-
} catch {
|
|
498
|
-
return null // recheck failed (lock etc.) — the original error is reported as-is
|
|
499
279
|
}
|
|
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
|
-
})
|
|
280
|
+
return null
|
|
512
281
|
}
|
|
513
282
|
|
|
514
283
|
/**
|
|
@@ -523,22 +292,128 @@ export async function executeCommand(name: string, rawInput: unknown, identity:
|
|
|
523
292
|
return executeCommandInner(name, rawInput, identity)
|
|
524
293
|
}
|
|
525
294
|
|
|
295
|
+
/** A redelivery is a fresh READ of a stored outcome — the RECORDED producer material decides whether
|
|
296
|
+
* the current identity may still see it. One rule shared by every replay site (removed commands,
|
|
297
|
+
* still-registered commands, undo compensations, batch items): the recorded role must still match,
|
|
298
|
+
* the rights material must exist (its absence is unprovable — a row predating rights tracking —
|
|
299
|
+
* never a read of "no restriction"), the current delegation must still cover the recorded
|
|
300
|
+
* command×target, and scoped commands are re-authorized by the CURRENT app policy against the
|
|
301
|
+
* recorded normalized target. Throws a stage-3 GateError on refusal. */
|
|
302
|
+
export async function verifyReplayRights(name: string, current: Identity, producedBy: unknown): Promise<void> {
|
|
303
|
+
// the assignment scopes (business targets) are RE-COMPUTED for the verdict — currentIdentityOf
|
|
304
|
+
// preserves the request-start scopes, but a redelivery is judged like any fresh read: an assignment
|
|
305
|
+
// revoked mid-request must refuse the replay exactly as it refuses a new request (the same refresh
|
|
306
|
+
// reauthorize applies before execution)
|
|
307
|
+
const judged = await judgedIdentityOf(current)
|
|
308
|
+
const by = producedBy as { role?: string; rights?: { scope: string; target?: string } } | { unknown: true } | undefined
|
|
309
|
+
if (!by || !('role' in by) || by.role !== current.role)
|
|
310
|
+
throw new GateError(
|
|
311
|
+
3,
|
|
312
|
+
'policy',
|
|
313
|
+
`The stored result was produced under a different role (current: '${current.role}') — a redelivery is returned only while the recorded rights still match`,
|
|
314
|
+
{ code: 'gate.role_denied' },
|
|
315
|
+
)
|
|
316
|
+
const rights = 'rights' in (by ?? {}) ? (by as { rights?: { scope: string; target?: string } }).rights : undefined
|
|
317
|
+
if (!rights)
|
|
318
|
+
throw unprovableRefusal('The stored result predates rights tracking — the right cannot be re-proven, so the result is refused')
|
|
319
|
+
// a still-valid delegation may have been NARROWED: the current command×target range is judged on
|
|
320
|
+
// the recorded material (delegation validity itself was re-read by the caller via currentIdentityOf)
|
|
321
|
+
if (current.delegation) await assertRecordedDelegationCovers(current.delegation, name, rights.scope, rights.target, 3)
|
|
322
|
+
// scoped commands: the CURRENT app policy judges the recorded normalized target with CURRENT scopes
|
|
323
|
+
if (rights.scope !== 'none') {
|
|
324
|
+
if (rights.target === undefined)
|
|
325
|
+
throw unprovableRefusal('The stored result carries no recorded target — the right cannot be re-proven, so the result is refused')
|
|
326
|
+
const refusal = await appPolicy().authorize(judged, rights.scope, rights.target)
|
|
327
|
+
// a replay verdict keeps the ERROR-CODE default guidance — the policy's momentary recovery hint
|
|
328
|
+
// never travels with a stored result's re-proof (review F1)
|
|
329
|
+
if (refusal) throw policyRefusalGateError(refusal)
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
/** Replay-site guard — re-reads the live identity (inactive accounts never receive stored results),
|
|
334
|
+
* then re-proves the recorded rights. Callers already holding the current identity may call
|
|
335
|
+
* verifyReplayRights directly. */
|
|
336
|
+
async function assertReplayRights(name: string, identity: Identity, producedBy: unknown): Promise<void> {
|
|
337
|
+
const current = await liveIdentityOf(identity, () =>
|
|
338
|
+
new GateError(3, 'policy', 'User is inactive at replay time — stored results are not returned to inactive accounts', { code: 'auth.relogin_required' }))
|
|
339
|
+
// a STILL-REGISTERED command's LIVE role grant: the account role may be unchanged while the
|
|
340
|
+
// definition narrowed its allowedRoles since — a redelivery respects the CURRENT permission set
|
|
341
|
+
// (a removed command has no live definition; its recorded material remains the only basis)
|
|
342
|
+
const def = lookupCommand(name)
|
|
343
|
+
if (def)
|
|
344
|
+
assertLiveRoleAllows(def, current.role, `Role no longer allowed for this command — allowed: [${def.allowedRoles.join('/')}] (current: ${current.role})`)
|
|
345
|
+
await verifyReplayRights(name, current, producedBy)
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
/** Replay probe for a command the registry no longer knows (strict) — a resend for a removed command:
|
|
349
|
+
* when the stored provenance (same subject, same requestKey, same hashed request) says this caller
|
|
350
|
+
* already succeeded, the stored result MAY be returned. The account must be valid NOW, and the
|
|
351
|
+
* rights must still be provable (verifyReplayRights). Null when nothing is stored for this
|
|
352
|
+
* caller·key·request. */
|
|
353
|
+
export async function replayStoredCommand(identity: Identity, name: string, rawInput: unknown): Promise<ExecutionResult | null> {
|
|
354
|
+
const current = await liveIdentityOf(identity, () =>
|
|
355
|
+
new GateError(3, 'policy', 'User is inactive at replay time — stored results are not returned to inactive accounts', { code: 'auth.relogin_required' }))
|
|
356
|
+
if (!rawInput || typeof rawInput !== 'object' || Array.isArray(rawInput)) return null
|
|
357
|
+
const { requestKey, dryRun, contract, body } = splitProtocolOptions(rawInput)
|
|
358
|
+
if (!requestKey || dryRun) return null
|
|
359
|
+
const replayed = await replayOrReject(identity, name, requestKey, hashBodyOf(body, contract))
|
|
360
|
+
if (replayed?.ok) await verifyReplayRights(name, current, replayed.producedBy)
|
|
361
|
+
return replayed
|
|
362
|
+
}
|
|
363
|
+
|
|
526
364
|
async function executeCommandInner(name: string, rawInput: unknown, identity: Identity): Promise<ExecutionResult> {
|
|
365
|
+
const strict = kernelOptions().mode === 'strict'
|
|
527
366
|
const def = lookupCommand(name)
|
|
528
|
-
if (!def)
|
|
367
|
+
if (!def) {
|
|
368
|
+
if (strict) {
|
|
369
|
+
try {
|
|
370
|
+
const replayed = await replayStoredCommand(identity, name, rawInput)
|
|
371
|
+
if (replayed) {
|
|
372
|
+
await tryRecordOutsideTx('replay', name, identity, rawInput)
|
|
373
|
+
return replayed.ok ? { ...replayed, meta: responseMetaOf(undefined, identity) } : replayed
|
|
374
|
+
}
|
|
375
|
+
} catch (err) {
|
|
376
|
+
return await refuse(name, identity, rawInput, toGateError(err, 3, 'policy'))
|
|
377
|
+
}
|
|
378
|
+
}
|
|
529
379
|
return await refuse(name, identity, rawInput, new GateError(0, 'registry', `Unknown command: ${name}`, { code: 'gate.unknown_command' }))
|
|
380
|
+
}
|
|
530
381
|
|
|
531
|
-
const { requestKey, dryRun, body } = splitProtocolOptions(rawInput)
|
|
382
|
+
const { requestKey, dryRun, contract, contractMalformed, body } = splitProtocolOptions(rawInput)
|
|
383
|
+
const hashValue = hashBodyOf(body, contract)
|
|
532
384
|
try {
|
|
385
|
+
// strict — the replay probe precedes the schema·contract checks: a stored success is returned even
|
|
386
|
+
// when today's schema or contract would refuse the resent input (the result already exists;
|
|
387
|
+
// re-validating it against today's contract adds false negatives, never safety). The stored row is
|
|
388
|
+
// found FIRST — judging the resent raw input through TODAY'S targetOf would refuse legitimate
|
|
389
|
+
// redeliveries whose input field names moved (the recorded rights material is the verdict, never a
|
|
390
|
+
// re-extraction from the past input). A HIT is a fresh READ: the recorded rights are re-proven
|
|
391
|
+
// (role·delegation·policy target·current scopes), so a redelivery never widens permissions. A MISS
|
|
392
|
+
// is a NEW request — the current definition judges everything from here.
|
|
393
|
+
if (strict && requestKey && !dryRun && contract) {
|
|
394
|
+
const replayed = await replayOrReject(identity, name, requestKey, hashValue)
|
|
395
|
+
if (replayed) {
|
|
396
|
+
if (replayed.ok) await assertReplayRights(name, identity, replayed.producedBy)
|
|
397
|
+
await tryRecordOutsideTx('replay', name, identity, rawInput)
|
|
398
|
+
return replayed.ok ? { ...replayed, meta: responseMetaOf(name, identity) } : replayed
|
|
399
|
+
}
|
|
400
|
+
await quickPermissionCheck(def, name, body, identity)
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
// strict — the contract the call was built against must be declared and current BEFORE the business
|
|
404
|
+
// schema judges the input: a caller working from a stale contract is told to re-learn the contract,
|
|
405
|
+
// not lectured on schema details of fields they have never seen
|
|
406
|
+
if (strict) checkContract(def, contract, contractMalformed)
|
|
407
|
+
|
|
533
408
|
const input = await validateStatic(def, name, body, identity)
|
|
534
409
|
|
|
535
410
|
// Idempotent replay — a resend of the same request that passed connection·permissions·format (1~4) returns the stored result.
|
|
536
411
|
// Decided before business checks so a state-changed retry (e.g. version conflict) never overwrites the original success.
|
|
537
412
|
if (requestKey && !dryRun) {
|
|
538
|
-
const replayed = await replayOrReject(identity, name, requestKey,
|
|
413
|
+
const replayed = await replayOrReject(identity, name, requestKey, hashValue)
|
|
539
414
|
if (replayed) {
|
|
540
415
|
await tryRecordOutsideTx('replay', name, identity, rawInput)
|
|
541
|
-
return replayed
|
|
416
|
+
return replayed.ok ? { ...replayed, meta: responseMetaOf(name, identity) } : replayed
|
|
542
417
|
}
|
|
543
418
|
}
|
|
544
419
|
|
|
@@ -555,29 +430,38 @@ async function executeCommandInner(name: string, rawInput: unknown, identity: Id
|
|
|
555
430
|
// 8~9 execution + audit — permissions (2~3) are re-checked against current state just before execution
|
|
556
431
|
// (refused when role·delegation·scope changed after the request), and events·projections·idempotency·audit
|
|
557
432
|
// 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).
|
|
433
|
+
// see the capability contract on the storage port). Each execution is one operation: every event it
|
|
434
|
+
// appends carries the operation envelope when the engine supports it.
|
|
559
435
|
let out: { result: unknown; eventTypes: string[] }
|
|
560
436
|
try {
|
|
561
437
|
out = await storageOf().immediate(async () => {
|
|
562
438
|
const current = await reauthorize(def, name, input, identity)
|
|
563
439
|
await validateDynamic(def, input, current)
|
|
564
|
-
const
|
|
565
|
-
|
|
440
|
+
const op: OperationContext = {
|
|
441
|
+
operationId: 'op_' + randomUUID(),
|
|
442
|
+
commandName: name,
|
|
443
|
+
...(def.version ? { commandVersion: def.version } : {}),
|
|
444
|
+
...(commandRevisionOf(name) ? { commandRevision: commandRevisionOf(name)! } : {}),
|
|
445
|
+
}
|
|
446
|
+
const r = await runCommand(def, name, input, rawInput, current, op)
|
|
447
|
+
if (requestKey) await storeIdempotency(identity, name, requestKey, hashValue, r.result, r.eventTypes, producerOf(name, def, current.role, input))
|
|
566
448
|
return r
|
|
567
449
|
})
|
|
568
450
|
} catch (err) {
|
|
569
451
|
// concurrent retry — if another process committed first with the same key, the stored result is returned
|
|
570
452
|
if (requestKey) {
|
|
571
|
-
const settled = await settleConcurrentRetry(identity, name, requestKey,
|
|
453
|
+
const settled = await settleConcurrentRetry(identity, name, requestKey, hashValue)
|
|
572
454
|
if (settled) {
|
|
455
|
+
// a settled success is a redelivery too — strict mode re-proves the recorded rights
|
|
456
|
+
if (settled.ok && kernelOptions().mode === 'strict') await assertReplayRights(name, identity, (settled as { producedBy?: unknown }).producedBy)
|
|
573
457
|
await auditSettled(name, identity, rawInput, settled)
|
|
574
|
-
return settled
|
|
458
|
+
return settled.ok ? { ...settled, meta: responseMetaOf(name, identity) } : settled
|
|
575
459
|
}
|
|
576
460
|
}
|
|
577
461
|
throw toGateError(err, 8, 'execute')
|
|
578
462
|
}
|
|
579
463
|
|
|
580
|
-
return { ok: true, result: out.result, events: out.eventTypes }
|
|
464
|
+
return { ok: true, result: out.result, events: out.eventTypes, meta: responseMetaOf(name, identity) }
|
|
581
465
|
} catch (err) {
|
|
582
466
|
// A failure here includes a failed success-audit insert — the transaction already rolled the command back
|
|
583
467
|
return await refuse(name, identity, rawInput, toGateError(err, 8, 'execute'))
|
|
@@ -624,6 +508,45 @@ async function executeBatchInner(
|
|
|
624
508
|
if (!Array.isArray(items) || items.length === 0 || items.length > 20)
|
|
625
509
|
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
510
|
|
|
511
|
+
const strict = kernelOptions().mode === 'strict'
|
|
512
|
+
|
|
513
|
+
// strict — the batch replay probe precedes the per-item checks, on the same principle as the single
|
|
514
|
+
// command: a stored batch success is returned even when today's item schemas/contracts would refuse.
|
|
515
|
+
// The stored row is found FIRST (today's targetOf never re-extracts targets from resent raw items —
|
|
516
|
+
// the recorded per-item material is the verdict); a HIT re-proves every item's recorded rights,
|
|
517
|
+
// including items whose command has since been removed. A MISS falls through to the current
|
|
518
|
+
// definitions' full checks below.
|
|
519
|
+
if (strict && batchRequestKey) {
|
|
520
|
+
let replayed: ExecutionResult | null = null
|
|
521
|
+
try {
|
|
522
|
+
replayed = await replayOrReject(identity, 'batch', batchRequestKey, items)
|
|
523
|
+
} catch (err) {
|
|
524
|
+
return await refuse('batch', identity, items, toGateError(err, 6, 'invariant'))
|
|
525
|
+
}
|
|
526
|
+
if (replayed) {
|
|
527
|
+
if (replayed.ok) {
|
|
528
|
+
const refused = await batchRightsRefusal(items, identity, (replayed as { producedBy?: unknown }).producedBy)
|
|
529
|
+
if (refused) return refused
|
|
530
|
+
}
|
|
531
|
+
await tryRecordOutsideTx('replay', 'batch', identity, items)
|
|
532
|
+
return replayed.ok ? { ...replayed, meta: responseMetaOf(undefined, identity), results: (replayed.result as any)?.results } : replayed
|
|
533
|
+
}
|
|
534
|
+
// a miss is a NEW batch — still-registered items get the early clear role·delegation refusal
|
|
535
|
+
// (removed commands have no definition; the validation loop below refuses them by index)
|
|
536
|
+
for (let i = 0; i < items.length; i++) {
|
|
537
|
+
const it = items[i] ?? {}
|
|
538
|
+
const def = lookupCommand(it.name)
|
|
539
|
+
if (!def) continue
|
|
540
|
+
const { requestKey: itemKey, dryRun: itemDry, body: itemBody } = splitProtocolOptions(it.input ?? {})
|
|
541
|
+
if (itemKey || itemDry) continue // refused below with the canonical option refusal
|
|
542
|
+
try {
|
|
543
|
+
await quickPermissionCheck(def, it.name, itemBody, identity)
|
|
544
|
+
} catch (err) {
|
|
545
|
+
return await refuse('batch', identity, items, toGateError(err, 3, 'policy'), { index: i, prefix: `#${i} ${it.name}: ` })
|
|
546
|
+
}
|
|
547
|
+
}
|
|
548
|
+
}
|
|
549
|
+
|
|
627
550
|
const validated: { def: CommandDefinition<any>; name: string; input: any; rawInput: unknown }[] = []
|
|
628
551
|
for (let i = 0; i < items.length; i++) {
|
|
629
552
|
const it = items[i] ?? {}
|
|
@@ -633,8 +556,10 @@ async function executeBatchInner(
|
|
|
633
556
|
index: i,
|
|
634
557
|
prefix: `#${i} ${it.name}: `,
|
|
635
558
|
})
|
|
636
|
-
// Protocol options are batch-level, not item-level — an item carrying one is a clear refusal, never
|
|
637
|
-
|
|
559
|
+
// Protocol options are batch-level, not item-level — an item carrying one is a clear refusal, never
|
|
560
|
+
// silent execution. (contract is the exception: in strict mode every item CARRIES a contract — it is
|
|
561
|
+
// checked per item below; the batch requestKey hash covers the items as sent, contract included.)
|
|
562
|
+
const { requestKey: itemKey, dryRun: itemDry, contract: itemContract, contractMalformed: itemMalformed, body: itemBody } = splitProtocolOptions(it.input ?? {})
|
|
638
563
|
if (itemKey || itemDry)
|
|
639
564
|
return await refuse(
|
|
640
565
|
'batch',
|
|
@@ -649,7 +574,12 @@ async function executeBatchInner(
|
|
|
649
574
|
{ index: i, prefix: `#${i} ${it.name}: ` },
|
|
650
575
|
)
|
|
651
576
|
try {
|
|
652
|
-
|
|
577
|
+
// the caller's contract view is judged before the business schema — the same order as single
|
|
578
|
+
// commands (a stale-contract caller is told to re-learn the contract, not lectured on fields
|
|
579
|
+
// they have never seen)
|
|
580
|
+
if (strict) checkContract(def, itemContract, itemMalformed)
|
|
581
|
+
const input = await validateStatic(def, it.name, itemBody, identity)
|
|
582
|
+
validated.push({ def, name: it.name, input, rawInput: it.input })
|
|
653
583
|
} catch (err) {
|
|
654
584
|
return await refuse('batch', identity, items, toGateError(err, 8, 'execute'), { index: i, prefix: `#${i} ${it.name}: ` })
|
|
655
585
|
}
|
|
@@ -664,32 +594,44 @@ async function executeBatchInner(
|
|
|
664
594
|
}
|
|
665
595
|
if (replayed) {
|
|
666
596
|
await tryRecordOutsideTx('replay', 'batch', identity, items)
|
|
667
|
-
return replayed.ok
|
|
597
|
+
return replayed.ok
|
|
598
|
+
? { ...replayed, meta: responseMetaOf(undefined, identity), results: (replayed.result as any)?.results }
|
|
599
|
+
: replayed
|
|
668
600
|
}
|
|
669
601
|
}
|
|
670
602
|
|
|
671
603
|
// One write-lock transaction for the whole batch (the BEGIN and lock waits follow the storage port's
|
|
672
604
|
// 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.
|
|
605
|
+
// timeout also reaches the common handling below and returns the canonical refusal·audit. Every item is
|
|
606
|
+
// its own operation (its own operationId) grouped under one batchId — undo compensates items, not batches.
|
|
674
607
|
try {
|
|
675
608
|
const results = await storageOf().immediate(async () => {
|
|
676
609
|
const rs = []
|
|
610
|
+
const batchId = 'batch_' + randomUUID()
|
|
677
611
|
for (let i = 0; i < validated.length; i++) {
|
|
678
612
|
const v = validated[i]
|
|
679
613
|
try {
|
|
680
614
|
const current = await reauthorize(v.def, v.name, v.input, identity) // execution-time permissions — earlier command scope changes are caught here
|
|
681
615
|
await validateDynamic(v.def, v.input, current) // current-state checks just before execution
|
|
682
|
-
const
|
|
616
|
+
const op: OperationContext = {
|
|
617
|
+
operationId: 'op_' + randomUUID(),
|
|
618
|
+
batchId,
|
|
619
|
+
commandName: v.name,
|
|
620
|
+
...(v.def.version ? { commandVersion: v.def.version } : {}),
|
|
621
|
+
...(commandRevisionOf(v.name) ? { commandRevision: commandRevisionOf(v.name)! } : {}),
|
|
622
|
+
}
|
|
623
|
+
const r = await runCommand(v.def, v.name, v.input, v.rawInput, current, op)
|
|
683
624
|
rs.push({ name: v.name, ok: true, result: r.result, events: r.eventTypes })
|
|
684
625
|
} catch (err) {
|
|
685
626
|
;(err as any).batchIndex = i // carries which command (index) failed into the refusal response
|
|
686
627
|
throw err
|
|
687
628
|
}
|
|
688
629
|
}
|
|
689
|
-
if (batchRequestKey)
|
|
630
|
+
if (batchRequestKey)
|
|
631
|
+
await storeIdempotency(identity, 'batch', batchRequestKey, items, { results: rs }, rs.flatMap((r) => r.events), batchProducerOf(validated, identity.role))
|
|
690
632
|
return rs
|
|
691
633
|
})
|
|
692
|
-
return { ok: true, results }
|
|
634
|
+
return { ok: true, results, meta: responseMetaOf(undefined, identity) }
|
|
693
635
|
} catch (err) {
|
|
694
636
|
// A failure here includes a failed success-audit insert — the transaction already rolled the whole batch back
|
|
695
637
|
const i = (err as any).batchIndex as number | undefined
|
|
@@ -697,9 +639,14 @@ async function executeBatchInner(
|
|
|
697
639
|
if (batchRequestKey) {
|
|
698
640
|
const settled = await settleConcurrentRetry(identity, 'batch', batchRequestKey, items)
|
|
699
641
|
if (settled) {
|
|
642
|
+
// a settled success is a redelivery too — strict mode re-proves every item's recorded rights
|
|
643
|
+
if (settled.ok && kernelOptions().mode === 'strict') {
|
|
644
|
+
const refused = await batchRightsRefusal(items, identity, (settled as { producedBy?: unknown }).producedBy)
|
|
645
|
+
if (refused) return refused
|
|
646
|
+
}
|
|
700
647
|
await auditSettled('batch', identity, items, settled)
|
|
701
648
|
return settled.ok
|
|
702
|
-
? { ...settled, ...(i === undefined ? {} : { index: i }), results: (settled.result as any)?.results }
|
|
649
|
+
? { ...settled, ...(i === undefined ? {} : { index: i }), meta: responseMetaOf(undefined, identity), results: (settled.result as any)?.results }
|
|
703
650
|
: { ...settled, ...(i === undefined ? {} : { index: i }) }
|
|
704
651
|
}
|
|
705
652
|
}
|