diff --git a/.changeset/automation-variable-keys-reserved-segments.md b/.changeset/automation-variable-keys-reserved-segments.md new file mode 100644 index 00000000000..6c8e69c1ce0 --- /dev/null +++ b/.changeset/automation-variable-keys-reserved-segments.md @@ -0,0 +1,25 @@ +--- +'@objectstack/service-automation': minor +'@objectstack/spec': patch +'@objectstack/runtime': patch +--- + +fix(service-automation)!: automation variable keys cannot use reserved object segments, and one run's writes never change a flow's defaults + +Clause-②: no (narrowing) +Metadata-protocol: narrowed + + + +- **BREAKING: a flow variable key may not use `__proto__`, `constructor` or `prototype` as its name or as any dot-separated part of it.** Registration (and `os migrate meta --stored`, which previews it) judges every key a flow names, in every graph it holds: each node's `id` (it heads every key the node's output is stored under), each declared variable's `name`, each `assignment` node's targets in every shape, each node's `outputVariable`, `iteratorVariable`, `indexVariable`, `errorVariable` and `idVariable`, and each `screen` field's `name`. A name is judged with surrounding whitespace trimmed. + - FROM: a flow naming such a key registered. + - TO: the flow is refused at registration, and the refusal names every such key and where it sits. A name that only contains one of the three words (`constructor_name`, `prototype_count`) is unaffected. + - The fix: rename the key, for example `constructor` to `constructor_name`, and save the flow again. +- **BREAKING: a resume signal may not carry such a key.** Each key of a caller's `output` and `inputs` is judged, a signal handed on to a paused subflow child included; the engine's own continuations (a `map` item handing back, a subflow child finishing) are not, so a run paused before this release still completes. + - FROM: such a key in `output` was accepted; in `inputs` on a screen with declared fields it answered 400 under `INVALID_SCREEN_INPUT`. + - TO: the resume answers `INVALID_SIGNAL` before anything reads the submitted values; nothing is applied, and the run stays paused for a valid submission. + - The fix: send the screen's declared field names, and `output` keys without those segments. +- **BREAKING: one run's writes never change a flow's defaults, another run's values, or the record the run was handed.** Each run binds its own copy of a declared variable's object or list default, and of the trigger record (`record` and `$record`). A dotted write whose head names a value the run holds (`cfg.mode` over a declared `cfg`, `record.x` over the trigger record) is read back by the run's expressions (conditions and CEL values); the value itself keeps what it was, and a text hole (`{{ cfg.mode }}`) and `$record` read the value. With no durable suspended-run store, a resumed run works on its own copy of its variables, as a stored run does. + - FROM: such a write also changed the value it named: a text hole and `$record` read the write, the next run of the flow started from the changed default, and a node that changed the record in place changed the trigger's object. + - TO: only the run's expressions read the write; text holes, `$record`, the flow's default, the next run and the trigger's object do not. + - The fix: to show or keep a value a run computed, assign it to a variable of its own (`assignments: { mode_now: { dialect: 'cel', source: 'cfg.mode' } }`) and read that variable in the text hole or the later step. diff --git a/content/docs/automation/flows.mdx b/content/docs/automation/flows.mdx index fd4aeb94bd2..0d287366b09 100644 --- a/content/docs/automation/flows.mdx +++ b/content/docs/automation/flows.mdx @@ -1476,6 +1476,15 @@ key. A reserved name answers **400**, nothing is applied (not even legitimate keys sent alongside it), and the run stays parked. Ordinary author variables are unaffected, `$` mid-name (`price$`) included. +A third: **no signal key, nor any dot-separated part of one, may be `__proto__`, +`constructor` or `prototype`** — the rule a flow's own variable keys follow (see +[Variables](#variables)). It covers both signal fields of a caller's signal, +one handed on to a paused subflow child included, and is judged before anything +else reads the submitted values: such a key answers **400** `INVALID_SIGNAL`, +nothing is applied, and the run stays parked. The engine's own continuations (a +`map` item handing back, a subflow child finishing) are not judged, so a run +paused before this rule still completes. + ### A `screen` resume is checked against the declared fields A screen node's `config.fields` is a **contract**, not just a rendering hint: @@ -2242,6 +2251,23 @@ variables: [ | `defaultValue` | `unknown` | Bound at run start when no parameter supplies one — this is what makes the declaration a guarantee. Optional | | `objectName` | `string` | **Planned.** On an input only (refused at parse on any other variable): the input is the id of a record of this object. No start door reads it yet. See [a start input that is a record id](#a-start-input-that-is-a-record-id). Optional | +A variable key — a node's `id` (it heads every key the node's output is stored +under), a declared `name`, an `assignment` target, a node's `outputVariable` / +`iteratorVariable` / `indexVariable` / `errorVariable` / `idVariable`, a +`screen` field's `name` — may not be `__proto__`, `constructor` or `prototype`, +nor have one as any dot-separated part (`cfg.prototype`), judged with +surrounding whitespace trimmed. Registration refuses such a flow and names each +key; a name that only contains one of the words (`constructor_name`) is fine. + +Each run starts from its own copy of a declared object or list `defaultValue` +and of the trigger record (`record` and `$record`). A dotted write under a value +the run holds (`cfg.mode`, `record.x`) is read back by the run's expressions — +conditions and CEL values — and leaves the value itself as it was, so a text +hole (`{{ cfg.mode }}`) and `$record` read the value, not the write. To show or +keep a computed value, assign it to a variable of its own and read that. One run +never changes the flow's default, the next run's values, or the object the +trigger handed over. + ### `defaultValue` — declaring a variable is not the same as binding it Without `defaultValue`, a declaration is documentation. The engine binds an diff --git a/packages/qa/dogfood/test/flow-condition-scope-keys.dogfood.test.ts b/packages/qa/dogfood/test/flow-condition-scope-keys.dogfood.test.ts index b0a10866060..2fd1f873c87 100644 --- a/packages/qa/dogfood/test/flow-condition-scope-keys.dogfood.test.ts +++ b/packages/qa/dogfood/test/flow-condition-scope-keys.dogfood.test.ts @@ -8,7 +8,9 @@ // The doors, each with its own probe name: // • the record that starts a record-triggered flow (`POST` / `PATCH /data`); // • a flow trigger's `params` bag (`POST /automation/:name/trigger`); -// • a screen resume's `inputs` and `output` (`POST …/runs/:runId/resume`). +// • a screen resume's `inputs` and `output` (`POST …/runs/:runId/resume`), +// where a key with a reserved segment is refused (`INVALID_SIGNAL`) and the +// run stays paused for a valid submission. // // Control: an ordinary dotted key (`.`, a resumed screen's output) // still nests, and a condition after the screen still reads it. @@ -214,16 +216,24 @@ describe('a flow condition scope: no variable key reaches a prototype', () => { const runId = await pause(); const res = await resume(runId, { inputs: { note: 'fcsk-in', '__proto__.fcsk_resume_inputs': true } }); expect(res.status, await res.clone().text()).toBe(400); - expect(((await res.json()) as any).error?.code).toBe('INVALID_SCREEN_INPUT'); + expect(((await res.json()) as any).error?.code).toBe('INVALID_SIGNAL'); expect(inherited('fcsk_resume_inputs')).toBeUndefined(); + // Nothing was applied: the pause is live, and the valid submission lands. + const ok = await resume(runId, { inputs: { note: 'fcsk-in' }, output: { tag: 'go' } }); + expect(ok.status, await ok.clone().text()).toBeLessThan(300); + expect(await marks('fcsk-in')).toBe(1); }); it('its output bag', async () => { const runId = await pause(); const res = await resume(runId, { inputs: { note: 'fcsk-out' }, output: { tag: 'go', '__proto__.fcsk_resume_output': true } }); expect(inherited('fcsk_resume_output')).toBeUndefined(); - // The rest of the bag still nests: the condition after the screen read `ask.tag`. - expect(res.status, await res.clone().text()).toBeLessThan(300); + expect(res.status, await res.clone().text()).toBe(400); + expect(((await res.json()) as any).error?.code).toBe('INVALID_SIGNAL'); + expect(await marks('fcsk-out')).toBe(0); + // Nothing was applied: the pause is live, and the valid submission lands. + const ok = await resume(runId, { inputs: { note: 'fcsk-out' }, output: { tag: 'go' } }); + expect(ok.status, await ok.clone().text()).toBeLessThan(300); expect(await marks('fcsk-out')).toBe(1); }); diff --git a/packages/runtime/src/domains/automation.ts b/packages/runtime/src/domains/automation.ts index a534be5a840..bbf54b85e66 100644 --- a/packages/runtime/src/domains/automation.ts +++ b/packages/runtime/src/domains/automation.ts @@ -4813,7 +4813,9 @@ export async function handleAutomationRequest(deps: DomainHandlerDeps, path: str // resume ran and the flow failed"): // PERMISSION_DENIED → 403, the suspension is service-owned (#3801) // INVALID_SIGNAL → 400, the signal wrote the engine's `$` variable - // namespace (#3853 follow-up) + // namespace (#3853 follow-up), or named a key + // whose name or any dot-separated part of it is + // `__proto__`, `constructor` or `prototype` // INVALID_SCREEN_INPUT → 400, the bag violates the suspended screen's // declared field contract — a required field the // caller was asked for is missing, or an diff --git a/packages/services/service-automation/src/dag-traversal.ts b/packages/services/service-automation/src/dag-traversal.ts index 636168f6a3b..7901903250f 100644 --- a/packages/services/service-automation/src/dag-traversal.ts +++ b/packages/services/service-automation/src/dag-traversal.ts @@ -68,7 +68,7 @@ import { readPartialSteps } from './partial-steps.js'; import { isRegionSuspensionRefusal, refuseRegionSuspension } from './region-suspension-refusal.js'; import { stampFlowRunSlot } from './flow-slots.js'; import { stampRootRun } from './root-run.js'; -import { isSkippedScopeKey, scopeContainer } from './scope-key-segments.js'; +import { copyForScopeDescent, copyHeldValue, isSkippedScopeKey, scopeContainer } from './scope-key-segments.js'; /** * The value the flow CEL scope binds as `current_user` for a run (#19939 — @@ -1052,17 +1052,28 @@ export function celScope( ): { extra: Record } { // No variable key reaches a prototype (`./scope-key-segments.ts`): // prototype-free containers, and a key with a skipped segment binds - // nothing. A dotted tail whose head names a value the run holds is still - // written into that value. + // nothing. And no key writes into a value the run holds: a dotted tail + // whose head names one descends into a copy the scope owns + // (`copyForScopeDescent`), so the scope reads the write and the held + // value — a flow's default, the trigger's record, a value `$record` + // shares — keeps what it was. const vars = scopeContainer(); + const owned = new WeakSet([vars]); for (const [key, value] of variables) { // Convert "step.result" keys into nested object paths. const segs = key.split('.'); if (isSkippedScopeKey(segs)) continue; let cursor = vars; for (let i = 0; i < segs.length - 1; i++) { - if (typeof cursor[segs[i]] !== 'object' || cursor[segs[i]] === null) { - cursor[segs[i]] = scopeContainer(); + const next = cursor[segs[i]]; + if (typeof next !== 'object' || next === null) { + const container = scopeContainer(); + owned.add(container); + cursor[segs[i]] = container; + } else if (!owned.has(next)) { + const copy = copyForScopeDescent(next); + owned.add(copy); + cursor[segs[i]] = copy; } cursor = cursor[segs[i]] as Record; } @@ -1262,7 +1273,10 @@ export function seedDeclaredVariables( if (supplied !== undefined) { variables.set(v.name, supplied); } else if (v.defaultValue !== undefined) { - variables.set(v.name, v.defaultValue); + // The default is the registered flow's; the run gets its own copy + // (`copyHeldValue`), so nothing one run does to it — a node that + // changes it in place included — reaches the flow or the next run. + variables.set(v.name, copyHeldValue(v.defaultValue)); } } return variables; @@ -1278,9 +1292,13 @@ export function seedRunVariables( ): Map { const variables = this.seedDeclaredVariables(flow, context); if (context?.record) { - variables.set('$record', context.record); - variables.set('record', context.record); - for (const [k, v] of Object.entries(context.record)) { + // The run's own copy of the record it was handed (`copyHeldValue`): + // nothing the run does to `record` / `$record` — a node that changes + // it in place included — reaches the trigger's object. + const record = copyHeldValue(context.record) as Record; + variables.set('$record', record); + variables.set('record', record); + for (const [k, v] of Object.entries(record)) { if (!variables.has(k)) variables.set(k, v); } } @@ -1378,7 +1396,6 @@ export async function executeWithoutRetry( // to its author — and a pausing node on a retry attempt had no `$runId` // to map its external state back to this run with (ADR-0019). const runId = this.nextRunId(); - const variables = this.seedRunVariables(flow, flowName, context, runId); const startedAt = new Date().toISOString(); const steps: StepLogEntry[] = []; @@ -1387,6 +1404,10 @@ export async function executeWithoutRetry( // `flowRunId` is stamped here too (#3456). [#31696] And the slot, as // `execute()` stamps it. const runContext = await this.resolveRunContext(flow, context, runId); + // Seeded AFTER the context resolves: the run takes its own copy of the + // trigger record, so the lookups the start node declares (`expand`, grafted + // while the context resolves) must already be on it. + const variables = this.seedRunVariables(flow, flowName, context, runId); stampFlowRunSlot(runContext, flowName, runPackage); // [ADR-0162 item 7] Each attempt is a run of its own, and its own root // when it has no parent, as `execute()` stamps it. diff --git a/packages/services/service-automation/src/dry-run.ts b/packages/services/service-automation/src/dry-run.ts index f19901efd9e..4c456f80858 100644 --- a/packages/services/service-automation/src/dry-run.ts +++ b/packages/services/service-automation/src/dry-run.ts @@ -796,9 +796,11 @@ export async function dryRun(this: DryRunHost, definition: unknown, options: Flo ...(options.params !== undefined ? { params: options.params } : {}), ...(options.locale !== undefined ? { locale: options.locale } : {}), }; + const runContext = await this.resolveRunContext({ ...flow, runAs: 'user' }, start); + // Seeded after the context resolves, as a run is: the run's own copy of the + // record carries the lookups its start node declares. const variables: Map = this.seedRunVariables(flow, flow.name, start, ''); variables.delete('$runId'); - const runContext = await this.resolveRunContext({ ...flow, runAs: 'user' }, start); const startNode = flow.nodes.find((n) => n.type === 'start')!; const condition = (startNode.config as { condition?: unknown } | undefined)?.condition; diff --git a/packages/services/service-automation/src/engine.ts b/packages/services/service-automation/src/engine.ts index fdf17c45f90..7ba0d5f1176 100644 --- a/packages/services/service-automation/src/engine.ts +++ b/packages/services/service-automation/src/engine.ts @@ -65,6 +65,7 @@ export const DEFAULT_BRANCH_LABEL = 'default'; import { runTriggerUserId, type SeededRunContext } from './runtime-identity.js'; import { flowContentChecksum } from './flow-identity.js'; +import { hasReservedVariableKeySegment } from './scope-key-segments.js'; import { carriedRefusalOfResult, readCarriedRefusal, type CarriedRefusal } from './inner-refusal.js'; import { summarizeRun } from './run-summary.js'; import { withDroppedFields } from './run-dropped-fields.js'; @@ -1726,6 +1727,34 @@ function isEngineVariable(name: string): boolean { return name.startsWith('$') || name.includes('.$'); } +/** + * The keys of a resume signal with a reserved segment — the resume door of + * {@link RESERVED_VARIABLE_KEY_SEGMENTS} (`./scope-key-segments.ts`): each + * key of `output` and of `variables` (a screen's submitted inputs), as the + * caller spelled it, `output` keys prefixed `output.`. A CALLER's signal only: + * a signal the engine built itself ({@link ENGINE_BUILT_SIGNAL} — the `map` + * item handoff, the cancelled-item continuation, the subflow up-bubble) is + * exempt, as it is from the `$` rule, so a run parked before this rule, or + * under a key the door did not judge then, still completes. + * + * `resume` asks this FIRST — before the screen contract reads the submitted + * values (a `visibleWhen` is evaluated over them) and before + * {@link applyResumeSignal} folds anything — so a refused signal folds + * nothing and the pause stays live. {@link applyResumeSignal} refuses the same + * keys too, so no caller of the chokepoint can fold one. + */ +export function reservedResumeSignalKeys(signal: ResumeSignal): string[] { + if ((signal as Record)[ENGINE_BUILT_SIGNAL] === true) return []; + const keys: string[] = []; + for (const key of Object.keys(signal.output ?? {})) { + if (hasReservedVariableKeySegment(key)) keys.push(`output.${key}`); + } + for (const key of Object.keys(signal.variables ?? {})) { + if (hasReservedVariableKeySegment(key)) keys.push(key); + } + return keys; +} + /** * Fold a resume signal into a run's variable map — **the one place a signal * reaches those variables** (#3853 follow-up). @@ -1769,6 +1798,9 @@ export function applyResumeSignal( for (const [name] of writes) { if (!trusted && isEngineVariable(name)) rejected.push(name); } + // No key with a reserved segment from a caller's signal (see + // {@link reservedResumeSignalKeys}, which `resume` asks first). + rejected.push(...reservedResumeSignalKeys(signal)); // Reject as a whole — never a partial application. if (rejected.length) return rejected; @@ -8277,7 +8309,6 @@ export class AutomationEngine implements IAutomationService { // (no counter to advance), and nothing between the old call site and // this one reads or mints one. const runId = this.nextRunId(); - const variables = this.seedRunVariables(flow, flowName, context, runId); const startedAt = new Date().toISOString(); const steps: StepLogEntry[] = []; @@ -8289,6 +8320,10 @@ export class AutomationEngine implements IAutomationService { // Also stamps `flowRunId` so this run's data writes are attributable to it // (#3456). const runContext = await this.resolveRunContext(flow, context, runId); + // Seeded AFTER the context resolves: the run takes its own copy of the + // trigger record, so the lookups the start node declares (`expand`, + // grafted while the context resolves) must already be on it. + const variables = this.seedRunVariables(flow, flowName, context, runId); stampFlowRunSlot(runContext, flowName, runPackage); // [ADR-0162 item 7] The run's root run: itself, or its parent's. stampRootRun(runContext, { runId, flowName, startedAt }); @@ -9260,7 +9295,13 @@ export class AutomationEngine implements IAutomationService { * before `traverseNext` and {@link forgetSuspendedRun} is untouched — * the #13937 shape-4 ruling (maintainer 2026-09-01) keeps that order, for * exactly-once across a crash. This changes only WHICH suspension is - * read, never when it is consumed. */ + * read, never when it is consumed. + * + * A run read out of {@link suspendedRuns} (no store, or a run the store + * never accepted) is handed out as a store hands a row: the same record + * with its own copy of `variables`. So a resume that writes into its + * values changes neither the held pause nor a value the parked run + * shares (the trigger's record, the paused log entry). */ private loadSuspendedRunStrict(runId: string): Promise { // The body lives in ./run-resume.ts (#25222). const readStore = () => this.store; @@ -9269,6 +9310,7 @@ export class AutomationEngine implements IAutomationService { suspendedRuns: this.suspendedRuns, cacheOnlySuspensions: this.cacheOnlySuspensions, evictConsumedSuspension: (...a) => this.evictConsumedSuspension(...a), + logger: this.logger, }; return loadSuspendedRunStrict.call(host, runId); } @@ -11622,13 +11664,20 @@ export class AutomationEngine implements IAutomationService { * ## No variable key reaches a prototype * * Every container the builder creates has no prototype, and a key with a - * `__proto__` segment binds nothing here — skipped, not refused (a dotted - * tail whose head names a value the run holds is still written into that - * value); + * `__proto__` segment binds nothing here — skipped, not refused; * `./scope-key-segments.ts` states the rule and why `constructor` and - * `prototype` stay ordinary keys. The text-hole scope + * `prototype` stay ordinary keys in the scope (the doors refuse them as + * names a flow or a resume signal writes). The text-hole scope * (`textTemplateScope`) follows the same rule. * + * ## No variable key writes into a value the run holds + * + * A dotted tail whose head names a value the run holds (`cfg.mode` over a + * declared `cfg`, `record.x` over the trigger record) is written into a + * copy the scope owns, never into the value: the expression reads the + * write, and the value — a flow's default, the trigger's record, the + * object `record` and `$record` share — keeps what it was. + * * ## `current_user` — the run's user, or `null` (#19939) * * The scope also binds `current_user`, ADR-0068's canonical user root, from @@ -12047,6 +12096,11 @@ export class AutomationEngine implements IAutomationService { * declarations. A declaration with no `defaultValue` behaves exactly as * before — existing flows are untouched. * + * Each run binds its OWN copy of an object or list default (arrays and + * plain objects copied at every depth): the default is the registered + * flow's, and a run that changed it in place would change it for the flow + * and for every later run in the process. + * * Seeding happens BEFORE the trigger record is flattened to top-level * names, and that flattening skips names already present. So a declared * variable — bound from a param or from its default — shadows a record @@ -12077,7 +12131,9 @@ export class AutomationEngine implements IAutomationService { * `{record.title}` / `record.status`, plus the record's own fields * flattened to top-level names so bare references (`status`, `budget`) * resolve in start conditions and edge predicates — WITHOUT clobbering - * anything already bound; + * anything already bound. All three read the run's OWN copy of the + * record (arrays and plain objects at every depth), so nothing the run + * does to it reaches the object the trigger handed over; * 3. `previous`, bound ALWAYS — to `null` on the create/insert leg, since * there is no prior row — so a start condition can DISCRIMINATE create * from update on a `record-after-write` flow: `previous == null` is the diff --git a/packages/services/service-automation/src/flow-registration-checks.ts b/packages/services/service-automation/src/flow-registration-checks.ts index 902d7ee43e9..a48c98d62e0 100644 --- a/packages/services/service-automation/src/flow-registration-checks.ts +++ b/packages/services/service-automation/src/flow-registration-checks.ts @@ -46,6 +46,7 @@ import type { ExprValidationCode } from '@objectstack/formula'; // refuses to register is refused at publish, in the same words. import { findUndeclaredFlowCycle } from '@objectstack/metadata-core'; import type { AutomationEngine } from './engine.js'; +import { RESERVED_VARIABLE_KEY_REFUSAL, hasReservedVariableKeySegment } from './scope-key-segments.js'; /** * The slice of a descriptor's JSON-Schema `configSchema` that the undeclared-key @@ -227,6 +228,10 @@ export function registrationChecks( // so the author learns at the save rather than at the first trigger. // A plain function, not an engine member: it reads no engine state. (flowName, flow) => validateStartNode(flowName, flow), + // No variable key the flow names — declared, assigned or bound by a + // node — has a reserved segment (`./scope-key-segments.ts`). A plain + // function: it reads no engine state. + (flowName, flow) => validateVariableKeySegments(flowName, flow), // #4277 — config keys the node's descriptor does not declare (the // tightened #4059 warning; a `visibleIf` typo used to register in // silence), with per-key prescriptions: see validateNodeConfigKeys @@ -323,6 +328,104 @@ export function validateStartNode(flowName: string, flow: FlowParsed): Registrat }; } +/** + * The positions at which {@link validateVariableKeySegments} judges a variable + * key: the spec's binding positions (`FLOW_BINDING_KEYS` in + * `@objectstack/spec`'s `flow-bound-variable-name.ts`, held equal by + * `variable-key-reserved-segments.test.ts`) plus `nodeId`, because a node's id + * heads every key its output is stored under. + */ +export const VARIABLE_KEY_POSITIONS = [ + 'nodeId', + 'variableName', + 'outputVariable', + 'errorVariable', + 'iteratorVariable', + 'indexVariable', + 'idVariable', + 'screenFieldName', + 'assignmentTarget', +] as const; + +export type VariableKeyPosition = (typeof VARIABLE_KEY_POSITIONS)[number]; + +/** The node config keys whose value names a variable the node binds, with the position each is. */ +const NODE_BINDING_CONFIG_KEYS: ReadonlyArray<[string, VariableKeyPosition]> = [ + ['outputVariable', 'outputVariable'], + ['errorVariable', 'errorVariable'], + ['iteratorVariable', 'iteratorVariable'], + ['indexVariable', 'indexVariable'], + ['idVariable', 'idVariable'], +]; + +/** + * Refuse a flow that names a variable key with a reserved segment — the + * authoring door of {@link RESERVED_VARIABLE_KEY_SEGMENTS} + * (`./scope-key-segments.ts`). Judged at every {@link VARIABLE_KEY_POSITIONS} + * position, in every graph the flow holds (region graphs included): each + * node's `id`; each declared variable's `name`; each `assignment` node's + * targets, in the shape the executor binds (the `assignments` map's keys, the + * legacy array's `variable` / `name` / `key`, or, with no `assignments`, the + * config's own keys); each node's `outputVariable` / `errorVariable` / + * `iteratorVariable` / `indexVariable` / `idVariable`; and each `screen` + * field's `name`. A name is judged TRIMMED, because executors trim some of + * them before binding (`script`'s `outputVariable`, `screen`'s `idVariable`). + * Every site is listed, so one save names them all. + */ +export function validateVariableKeySegments(flowName: string, flow: FlowParsed): RegistrationCheckRefusal | undefined { + const sites: RegistrationCheckSite[] = []; + const judge = (key: unknown, path: string, position: VariableKeyPosition): void => { + if (typeof key !== 'string' || !hasReservedVariableKeySegment(key.trim())) return; + sites.push({ path, from: JSON.stringify(key), detail: `the variable key \`${key}\` (${position}) at ${path}` }); + }; + const declared = (flow as { variables?: unknown }).variables; + if (Array.isArray(declared)) { + declared.forEach((v, i) => { + if (v && typeof v === 'object') judge((v as { name?: unknown }).name, `${STORED_FLOW_PATH}.variables[${i}].name`, 'variableName'); + }); + } + for (const graph of collectFlowGraphs(flow)) { + graph.nodes.forEach((node, index) => { + if (!node || typeof node !== 'object') return; + const nodePath = storedGraphMemberPath(graph, 'nodes', index); + judge(node.id, `${nodePath}.id`, 'nodeId'); + const config = node.config; + if (!config || typeof config !== 'object' || Array.isArray(config)) return; + const cfg = config as Record; + const at = `${nodePath}.config`; + for (const [key, position] of NODE_BINDING_CONFIG_KEYS) judge(cfg[key], `${at}.${key}`, position); + if (node.type === 'assignment') { + const raw = cfg.assignments; + if (Array.isArray(raw)) { + raw.forEach((item, i) => { + if (!item || typeof item !== 'object') return; + const entry = item as Record; + const nameKey = ASSIGNMENT_ENTRY_NAME_KEYS.find((k) => typeof entry[k] === 'string' && entry[k]); + if (nameKey) judge(entry[nameKey], `${at}.assignments[${i}].${nameKey}`, 'assignmentTarget'); + }); + } else if (raw && typeof raw === 'object') { + for (const key of Object.keys(raw)) judge(key, `${at}.assignments[${JSON.stringify(key)}]`, 'assignmentTarget'); + } else { + for (const key of Object.keys(cfg)) judge(key, `${at}[${JSON.stringify(key)}]`, 'assignmentTarget'); + } + } + if (node.type === 'screen' && Array.isArray(cfg.fields)) { + cfg.fields.forEach((field, i) => { + if (field && typeof field === 'object') judge((field as { name?: unknown }).name, `${at}.fields[${i}].name`, 'screenFieldName'); + }); + } + }); + } + if (sites.length === 0) return undefined; + const why = + `${RESERVED_VARIABLE_KEY_REFUSAL} Found: ${sites.map((s) => s.detail).join('; ')}. ` + + 'Rename each one (for example `constructor` to `constructor_name`); a name that only contains one of the three words is fine.'; + return { + message: `Flow '${flowName}' rejected: ${why}`, + sites: sites.map((site) => ({ ...site, detail: `${RESERVED_VARIABLE_KEY_REFUSAL} Rename ${site.detail}.` })), + }; +} + /** * The start-node `triggerType` tokens that run a flow AFTER a record change: * the record-change trigger's own grammar (`triggerTypeToHookEvents` in diff --git a/packages/services/service-automation/src/run-resume.ts b/packages/services/service-automation/src/run-resume.ts index b02af9fb775..3252eaaec0a 100644 --- a/packages/services/service-automation/src/run-resume.ts +++ b/packages/services/service-automation/src/run-resume.ts @@ -28,10 +28,11 @@ import { carriedRefusalOfResult, readCarriedRefusal } from './inner-refusal.js'; import { summarizeRun } from './run-summary.js'; import { dropEventsOf, foldDropEvents } from './run-dropped-fields.js'; import { noteTenantCurrencyReadFault } from './builtin/template.js'; +import { HeldValueCycleError, RESERVED_VARIABLE_KEY_REFUSAL, copyHeldValue } from './scope-key-segments.js'; import { mapItemCancelledVariable, type MapItemCancelledMarker } from './builtin/map-node.js'; // The values below (`buildRunTrigger`, `FlowRefusalSignal`, `isRefusalSignal`, // `isSuspendSignal`, `isRetryableResumeRefusal`, `carriesSubflowChildOutput`, -// `applyResumeSignal`, `engineBuilt`, `activeMsAtPause` and `waitOfPausedRun`) are read only inside the function bodies, at call +// `applyResumeSignal`, `reservedResumeSignalKeys`, `engineBuilt`, `activeMsAtPause` and `waitOfPausedRun`) are read only inside the function bodies, at call // time, never while a module is evaluating, so the import cycle with // ./engine.js is safe under ESM live bindings; the tsup bundle is one file and // has no cycle. @@ -44,6 +45,7 @@ import { isRetryableResumeRefusal, carriesSubflowChildOutput, applyResumeSignal, + reservedResumeSignalKeys, engineBuilt, waitOfPausedRun, type AutomationEngine, @@ -803,9 +805,38 @@ export async function loadSuspendedRun(this: Pick, runId: string): Promise { - if (!this.store) return this.suspendedRuns.get(runId) ?? null; +export async function loadSuspendedRunStrict(this: Pick, runId: string): Promise { + // With no durable answer the in-memory entry IS the run, and it is handed + // out as a store hands a row: with variables of its own + // (`heldSuspensionCopy`), so a resume — or any reader — that writes into + // them changes neither the held pause nor a value it shares with the run + // that parked (the trigger's record, the paused log entry). + if (!this.store) return heldSuspensionCopy(this.suspendedRuns.get(runId), this.logger); const stored = await this.store.load(runId); if (stored) return stored; // The store has no row. For every run it ever accepted that IS the @@ -815,7 +846,7 @@ export async function loadSuspendedRunStrict(this: Pick ({ dialect: 'cel', source }); + +function makeEngine(store?: SuspendedRunStore): AutomationEngine { + const engine = new AutomationEngine(silentLogger(), store); + installBuiltinNodes(engine, { logger: silentLogger(), getService() { return undefined; } } as any); + engine.registerNodeExecutor({ + type: 'hold', + descriptor: defineActionDescriptor({ type: 'hold', version: '1.0.0', name: 'hold', supportsPause: true, resumeAuthority: 'any' }), + async execute() { return { success: true, suspend: true, correlation: 'approval:req_1' }; }, + } as never); + // A plugin node that changes a held value in place — the executor API + // hands it the run's variable map, so nothing stops it. + engine.registerNodeExecutor({ + type: 'touch', + descriptor: defineActionDescriptor({ type: 'touch', version: '1.0.0', name: 'touch' }), + async execute(node: any, variables: Map) { + const target = variables.get(node.config?.target as string) as Record | unknown[]; + if (Array.isArray(target)) target.push('touched'); + else if (target && typeof target === 'object') (target as Record).mode = 'touched'; + return { success: true }; + }, + } as never); + // A plugin node that binds a value containing itself. + engine.registerNodeExecutor({ + type: 'loopback', + descriptor: defineActionDescriptor({ type: 'loopback', version: '1.0.0', name: 'loopback' }), + async execute(_node: any, variables: Map) { + const ring: Record = { label: 'ring' }; + ring.self = ring; + variables.set('ring', ring); + return { success: true }; + }, + } as never); + return engine; +} + +/** start → each step in order → end. */ +function chain(name: string, steps: Array>, variables: unknown[]) { + const nodes = [ + { id: 'start', type: 'start', label: 'Start' }, + ...steps.map((s, i) => ({ id: `n${i + 1}`, label: `N${i + 1}`, ...s })), + { id: 'end', type: 'end', label: 'End' }, + ]; + const edges = nodes.slice(1).map((n, i) => ({ id: `e${i + 1}`, source: nodes[i]!.id, target: n.id })); + return { name, label: name, type: 'autolaunched', variables, nodes, edges } as any; +} + +const assign = (assignments: Record) => ({ type: 'assignment', config: { assignments } }); + +/** Each case: the declared default, the dotted write under it, the read, what run 1 reads after the write, what run 2 reads first. */ +const DEFAULT_CASES: ReadonlyArray<[string, unknown, string, unknown, string, unknown]> = [ + ['case 1 (object default)', { mode: 'a', n: 1 }, 'cfg.mode', 'b', 'cfg.mode', 'a'], + ['case 2 (object default, nested)', { inner: { mode: 'a' } }, 'cfg.inner.mode', 'b', 'cfg.inner.mode', 'a'], + ['case 3 (list default, index)', ['a', 'b'], 'cfg.0', 'z', 'cfg[0]', 'a'], + ['case 4 (list default, length)', ['a', 'b'], 'cfg.length', 0, 'size(cfg)', 2], +]; + +describe('one run never changes the flow\'s defaults', () => { + it.each(DEFAULT_CASES)('%s: a dotted write is read back in its run, and the next run reads the default', async (_t, def, key, value, read, original) => { + const engine = makeEngine(); + const flow = chain('iso_defaults', [ + assign({ first: cel(read) }), + assign({ [key]: value }), + assign({ after: cel(read) }), + ], [ + { name: 'cfg', type: Array.isArray(def) ? 'list' : 'object', defaultValue: def }, + { name: 'first', type: 'text', isOutput: true }, + { name: 'after', type: 'text', isOutput: true }, + ]); + engine.registerFlow('iso_defaults', flow); + + const run1 = await engine.execute('iso_defaults'); + expect(run1.success, JSON.stringify(run1)).toBe(true); + expect((run1.output as any).first).toEqual(original); + expect((run1.output as any).after).toEqual(value); + + const run2 = await engine.execute('iso_defaults'); + expect(run2.success, JSON.stringify(run2)).toBe(true); + expect((run2.output as any).first).toEqual(original); + expect((await engine.getFlow('iso_defaults'))!.variables![0]!.defaultValue).toEqual(def); + }); + + it('a dotted write is still read back by the run that wrote it', async () => { + const engine = makeEngine(); + engine.registerFlow('iso_readback', chain('iso_readback', [ + assign({ 'cfg.mode': 'b' }), + assign({ after: cel('cfg.mode'), kept: cel('cfg.n') }), + ], [ + { name: 'cfg', type: 'object', defaultValue: { mode: 'a', n: 1 } }, + { name: 'after', type: 'text', isOutput: true }, + { name: 'kept', type: 'number', isOutput: true }, + ])); + const run = await engine.execute('iso_readback'); + expect(run.success, JSON.stringify(run)).toBe(true); + expect(run.output).toMatchObject({ after: 'b', kept: 1 }); + }); + + it.each([ + ['case 1 (object default)', { mode: 'a' }, 'cfg.mode', 'a'], + ['case 2 (list default)', ['a'], 'size(cfg)', 1], + ] as const)('%s: a node that changes the value in place leaves the next run reading the default', async (_t, def, read, original) => { + const engine = makeEngine(); + engine.registerFlow('iso_inplace', chain('iso_inplace', [ + assign({ first: cel(read) }), + { type: 'touch', config: { target: 'cfg' } }, + ], [ + { name: 'cfg', type: Array.isArray(def) ? 'list' : 'object', defaultValue: def }, + { name: 'first', type: 'text', isOutput: true }, + ])); + await engine.execute('iso_inplace'); + const run2 = await engine.execute('iso_inplace'); + expect(run2.success, JSON.stringify(run2)).toBe(true); + expect((run2.output as any).first).toEqual(original); + expect((await engine.getFlow('iso_inplace'))!.variables![0]!.defaultValue).toEqual(def); + }); +}); + +describe('a record write is the run\'s own value', () => { + it('a record.x write does not change $record.x or the trigger\'s object', async () => { + const engine = makeEngine(); + engine.registerFlow('iso_record', chain('iso_record', [ + assign({ 'record.x': 2 }), + assign({ seen_record: cel('record.x'), seen_trigger: cel("vars['$record'].x"), seen_other: cel('record.y') }), + ], [ + { name: 'seen_record', type: 'number', isOutput: true }, + { name: 'seen_trigger', type: 'number', isOutput: true }, + { name: 'seen_other', type: 'number', isOutput: true }, + ])); + const trigger = { x: 1, y: 7 }; + const run = await engine.execute('iso_record', { record: trigger } as any); + expect(run.success, JSON.stringify(run)).toBe(true); + expect(run.output).toMatchObject({ seen_record: 2, seen_trigger: 1, seen_other: 7 }); + expect(trigger).toEqual({ x: 1, y: 7 }); + }); +}); + +describe('a paused run\'s resume works on its own values', () => { + it.each([ + ['case 1 (no store)', undefined], + ['case 2 (a store)', () => new InMemorySuspendedRunStore()], + ] as const)('%s: a node after the pause that changes a value in place leaves the trigger\'s object as handed', async (_t, makeStore) => { + const engine = makeEngine(makeStore?.()); + engine.registerFlow('iso_pause', chain('iso_pause', [ + { type: 'hold' }, + { type: 'touch', config: { target: 'record' } }, + assign({ seen: cel('record.mode') }), + ], [{ name: 'seen', type: 'text', isOutput: true }])); + const trigger = { mode: 'a' }; + const paused = await engine.execute('iso_pause', { record: trigger } as any); + expect(paused.status).toBe('paused'); + const done = await engine.resume(paused.runId!, { output: { decision: 'approved' } }); + expect(done.success, JSON.stringify(done)).toBe(true); + expect((done.output as any).seen).toBe('touched'); + expect(trigger).toEqual({ mode: 'a' }); + }); +}); + +describe('the trigger record is the run\'s own copy', () => { + it('a node before any pause that changes the record in place leaves the trigger\'s object as handed', async () => { + const engine = makeEngine(); + engine.registerFlow('iso_prepause', chain('iso_prepause', [ + { type: 'touch', config: { target: 'record' } }, + assign({ seen: cel('record.mode'), seen_trigger: cel("vars['$record'].mode") }), + ], [{ name: 'seen', type: 'text', isOutput: true }, { name: 'seen_trigger', type: 'text', isOutput: true }])); + const trigger = { mode: 'a', nested: { n: 1 } }; + const run = await engine.execute('iso_prepause', { record: trigger } as any); + expect(run.success, JSON.stringify(run)).toBe(true); + expect(run.output).toMatchObject({ seen: 'touched', seen_trigger: 'touched' }); + expect(trigger).toEqual({ mode: 'a', nested: { n: 1 } }); + }); +}); + +describe('a value that contains itself', () => { + it('is refused by the copy with a named error', () => { + const ring: Record = { label: 'ring' }; + ring.self = ring; + let thrown: unknown; + try { copyHeldValue({ wrap: [ring] }); } catch (err) { thrown = err; } + expect(thrown).toBeInstanceOf(HeldValueCycleError); + expect((thrown as Error).name).toBe('HeldValueCycleError'); + // A value reached twice without containing itself is copied, not refused. + const shared = { n: 1 }; + const copy = copyHeldValue({ a: shared, b: shared }) as any; + expect(copy).toEqual({ a: { n: 1 }, b: { n: 1 } }); + expect(copy.a).not.toBe(shared); + }); + + it('held by a paused run with no store: the resume still completes, never answered as an unreachable store', async () => { + const engine = makeEngine(); + engine.registerFlow('iso_ring', chain('iso_ring', [ + { type: 'loopback' }, + { type: 'hold' }, + assign({ seen: cel('ring.label') }), + ], [{ name: 'seen', type: 'text', isOutput: true }])); + const paused = await engine.execute('iso_ring'); + expect(paused.status).toBe('paused'); + const done = await engine.resume(paused.runId!, { output: { decision: 'approved' } }); + expect(done.code).not.toBe('STORE_UNAVAILABLE'); + expect(done.success, JSON.stringify({ code: done.code, error: done.error })).toBe(true); + expect((done.output as any).seen).toBe('ring'); + }); +}); diff --git a/packages/services/service-automation/src/scope-key-segments.ts b/packages/services/service-automation/src/scope-key-segments.ts index 9469d3440f7..149c61e7de0 100644 --- a/packages/services/service-automation/src/scope-key-segments.ts +++ b/packages/services/service-automation/src/scope-key-segments.ts @@ -15,20 +15,23 @@ * value is a plain object, such as `record`): that object keeps its * prototype, and `__proto__` is the one segment that names it. * - * What the rule does NOT say: that a key only ever lands in a container the - * builder made. The CEL scope walk still writes a dotted key's tail into a - * value the run holds when the key's head names that value; it never reaches a - * prototype doing so. (`textTemplateScope` writes into fresh containers only.) + * And a third, for a walk that meets a value the run holds: * - * **Why `__proto__` alone.** `constructor` and `prototype` cannot reach a + * 3. **No key writes into a value the run holds.** When a dotted key's head + * names one (a declared variable's object, the trigger record), the CEL + * scope walk descends into a copy it owns ({@link copyForScopeDescent}), + * so the scope reads the write and the held value keeps what it was. + * (`textTemplateScope` writes into fresh containers only.) + * + * **Why `__proto__` alone here.** `constructor` and `prototype` cannot reach a * prototype under these two halves: in a container the builder made they are * ordinary own keys, and the walk only descends into a slot holding an object * (`typeof === 'object'`), so an inherited `constructor` (a function) is never - * walked into, and a plain object has no `prototype` slot to walk. Both are - * also legal flow-variable names (the spec's `assignments` key schema refuses - * only `__proto__`), and a variable named `prototype` is read as - * `vars["prototype"]`, the remedy the retired template dialect's refusal - * prints (`value-slot-template-grammar.test.ts`). + * walked into, and a plain object has no `prototype` slot to walk. The scope + * still binds them, because a run is handed keys no door judges (a trigger + * record's own field names), and a field named `prototype` is read as + * `record.prototype` or `vars["prototype"]`. What an author or a resume caller + * may NAME is the doors' rule below ({@link RESERVED_VARIABLE_KEY_SEGMENTS}). * * **Skipped, not refused.** A refusal (a throw) would fail every evaluation of * the run, including predicates and values that never read the key, so one @@ -48,3 +51,93 @@ export function isSkippedScopeKey(segments: readonly string[]): boolean { export function scopeContainer(): Record { return Object.create(null) as Record; } + + +/** + * The segments no flow variable key may have — as its whole name or as any + * dot-separated part of it — at the two doors that take a key from outside the + * engine: + * + * - **the authoring door** (`registerFlow`, and the stored pass that previews + * it): a declared variable's `name`, an `assignment` node's targets in each + * of their shapes, a node's `outputVariable` / `iteratorVariable` / + * `indexVariable` / `errorVariable`, and a `screen` field's `name`; + * - **the resume door** (`resume`): each key of a signal's `output` and + * `variables` (a screen's submitted `inputs`), refused before anything reads + * the submitted values, so a refused signal folds nothing and the pause stays + * live. + * + * A superset of {@link SCOPE_KEY_SKIPPED_SEGMENTS}: the scope builder skips the + * one segment that names a prototype; the doors refuse all three names that + * spell one, so no key a flow names or a caller sends is one. + */ +export const RESERVED_VARIABLE_KEY_SEGMENTS: ReadonlySet = new Set(['__proto__', 'constructor', 'prototype']); + +/** The sentence both doors open their refusal with. */ +export const RESERVED_VARIABLE_KEY_REFUSAL = + 'A flow variable key may not use `__proto__`, `constructor` or `prototype` as its name or as any dot-separated part of it.'; + +/** Whether a key, split on `.`, has a segment {@link RESERVED_VARIABLE_KEY_SEGMENTS} names. */ +export function hasReservedVariableKeySegment(key: string): boolean { + return key.split('.').some((segment) => RESERVED_VARIABLE_KEY_SEGMENTS.has(segment)); +} + +/** + * The copy the CEL scope walk descends into when a dotted key's head names a + * value the run holds (rule 3 above): one level, so a deeper descent copies + * the next level the same way. A list stays a list (an index or `length` + * write lands in the copy); any other object becomes a prototype-free + * container holding the same own keys. + */ +export function copyForScopeDescent(value: object): Record { + if (Array.isArray(value)) return value.slice() as unknown as Record; + return Object.assign(scopeContainer(), value); +} + +/** + * Thrown by {@link copyHeldValue} for a value that contains itself: a copy at + * every depth of such a value has no end, so it is refused by name instead of + * recursing until the stack overflows (an overflow reads as any other failure + * of the caller, an unreachable store included). + */ +export class HeldValueCycleError extends Error { + constructor() { + super('A flow run value contains itself (a list or object that holds itself at some depth), so the run cannot take its own copy of it.'); + this.name = 'HeldValueCycleError'; + } +} + +/** + * A run's own copy of a value it is seeded with from somewhere it must not + * write back to (a flow variable's declared default, the trigger record, a + * paused run's held variables): arrays and plain objects (`Object.prototype` + * or `null` prototype) copied at every depth, every other value — a string, a + * number, a `Date`, a class instance — as it is, the rule `copyLiteral` + * (`./builtin/value-slot-map.ts`) follows for a node's config. Each key is + * DEFINED on the copy, never assigned, so an own key named `__proto__` stays + * an own key. A value that contains itself throws {@link HeldValueCycleError} + * (a value reached twice without containing itself is copied twice). + */ +export function copyHeldValue(value: unknown): unknown { + return copyHeldValueWithin(value, new WeakMap()); +} + +function copyHeldValueWithin(value: unknown, open: WeakMap): unknown { + if (value === null || typeof value !== 'object') return value; + if (!Array.isArray(value)) { + const proto = Object.getPrototypeOf(value); + if (proto !== Object.prototype && proto !== null) return value; + } + if (open.has(value)) throw new HeldValueCycleError(); + open.set(value, true); + try { + if (Array.isArray(value)) return value.map((entry) => copyHeldValueWithin(entry, open)); + const out: Record = Object.getPrototypeOf(value) === null ? scopeContainer() : {}; + for (const [key, entry] of Object.entries(value)) { + Object.defineProperty(out, key, { value: copyHeldValueWithin(entry, open), enumerable: true, writable: true, configurable: true }); + } + return out; + } finally { + open.delete(value); + } +} diff --git a/packages/services/service-automation/src/variable-key-reserved-segments.test.ts b/packages/services/service-automation/src/variable-key-reserved-segments.test.ts new file mode 100644 index 00000000000..561a6fd4e1d --- /dev/null +++ b/packages/services/service-automation/src/variable-key-reserved-segments.test.ts @@ -0,0 +1,399 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * No flow variable key, nor any dot-separated part of one, is `__proto__`, + * `constructor` or `prototype` (`./scope-key-segments.ts` states the rule). + * + * Two doors hold it: + * + * - **the authoring door** — `registerFlow` (and the stored pass that + * previews it) refuses a flow that declares, assigns or binds such a key, + * naming the key and where it sits; + * - **the resume door** — `resume` refuses a signal whose `output` or `inputs` + * carry such a key, before anything reads the submitted values, so nothing + * is folded into the run and the pause stays live. + * + * The controls hold that an ordinary dotted key, and a name that merely + * contains one of the three words, still registers and resumes. + */ + +import { readFileSync } from 'node:fs'; +import { dirname, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; + +import { describe, expect, it, vi } from 'vitest'; + +import { defineActionDescriptor } from '@objectstack/spec/automation'; + +import { AutomationEngine, applyResumeSignal, engineBuilt, reservedResumeSignalKeys } from './engine.js'; +import { VARIABLE_KEY_POSITIONS, validateVariableKeySegments } from './flow-registration-checks.js'; +import { installBuiltinNodes } from './builtin/index.js'; +import { RESERVED_VARIABLE_KEY_REFUSAL, RESERVED_VARIABLE_KEY_SEGMENTS, hasReservedVariableKeySegment } from './scope-key-segments.js'; + +function silentLogger(): any { + return { info() {}, warn() {}, error() {}, debug() {}, child() { return silentLogger(); } }; +} + +function makeEngine(): AutomationEngine { + const engine = new AutomationEngine(silentLogger()); + installBuiltinNodes(engine, { logger: silentLogger(), getService() { return undefined; } } as any); + engine.registerNodeExecutor({ + type: 'hold', + descriptor: defineActionDescriptor({ type: 'hold', version: '1.0.0', name: 'hold', supportsPause: true, resumeAuthority: 'any' }), + async execute() { return { success: true, suspend: true, correlation: 'approval:req_1' }; }, + } as never); + return engine; +} + +/** start → `middle` → end, with `variables` declared. */ +function flowWith(middle: Record, variables: unknown[] = []) { + return { + name: 'vk_flow', label: 'vk_flow', type: 'autolaunched', + variables, + nodes: [ + { id: 'start', type: 'start', label: 'Start' }, + { id: 'mid', label: 'Middle', ...middle }, + { id: 'end', type: 'end', label: 'End' }, + ], + edges: [ + { id: 'e1', source: 'start', target: 'mid' }, + { id: 'e2', source: 'mid', target: 'end' }, + ], + } as any; +} + +const assign = (assignments: Record) => ({ type: 'assignment', config: { assignments } }); + +/** Each case: a flow, and the key its refusal must name. Titles are numbered; the data is the sample. */ +const AUTHORING_CASES: ReadonlyArray<[string, () => any, string]> = [ + ['case 1 (declared variable)', () => flowWith(assign({ v: 1 }), [{ name: 'constructor', type: 'text' }]), 'constructor'], + ['case 2 (declared variable, dotted)', () => flowWith(assign({ v: 1 }), [{ name: 'cfg.prototype', type: 'text' }]), 'cfg.prototype'], + ['case 3 (declared variable)', () => flowWith(assign({ v: 1 }), [JSON.parse('{"name":"__proto__","type":"text"}')]), '__proto__'], + ['case 4 (assignment map key)', () => flowWith(assign({ 'step.constructor': 1 })), 'step.constructor'], + ['case 5 (assignment map key)', () => flowWith(assign({ 'step.__proto__.x': 1 })), 'step.__proto__.x'], + ['case 6 (assignment map key)', () => flowWith(assign({ prototype: 1 })), 'prototype'], + ['case 7 (bare assignment config key)', () => flowWith({ type: 'assignment', config: { 'a.prototype': 1 } }), 'a.prototype'], + ['case 8 (node output variable)', () => flowWith({ type: 'get_record', config: { objectName: 'crm_account', outputVariable: 'found.constructor' } }), 'found.constructor'], + ['case 9 (screen field)', () => flowWith({ type: 'screen', config: { title: 'T', fields: [{ name: 'prototype', label: 'P', type: 'text' }] } }), 'prototype'], +]; + +describe('the authoring door refuses a variable key with a reserved segment', () => { + it('the reserved set names exactly the three segments, so the cases below cannot run empty', () => { + expect([...RESERVED_VARIABLE_KEY_SEGMENTS].sort()).toEqual(['__proto__', 'constructor', 'prototype']); + }); + + it.each(AUTHORING_CASES)('%s is refused at registration, naming the key', (_title, build, key) => { + const engine = makeEngine(); + let thrown: unknown; + try { + engine.registerFlow('vk_flow', build()); + } catch (err) { + thrown = err; + } + expect(thrown, 'registerFlow must refuse').toBeInstanceOf(Error); + const message = (thrown as Error).message; + expect(message).toContain(RESERVED_VARIABLE_KEY_REFUSAL); + expect(message).toContain(`\`${key}\``); + expect(engine.getFlowSlots('vk_flow')).toEqual([]); + }); + + it.each(AUTHORING_CASES)('%s is listed by the stored pass, which registers nothing', (_title, build, key) => { + const engine = makeEngine(); + const { todos } = engine.canonicalizeStoredFlow('vk_flow', build()); + const listed = todos.map((t) => JSON.stringify(t)).join('\n'); + expect(listed).toContain(RESERVED_VARIABLE_KEY_REFUSAL); + expect(listed).toContain(key); + expect(engine.getFlowSlots('vk_flow')).toEqual([]); + }); + + it('control: ordinary dotted keys, and names that only contain a reserved word, still register and run', async () => { + const engine = makeEngine(); + engine.registerFlow('vk_flow', flowWith( + assign({ + 'step.result': 5, + constructor_name: 'c', + prototype_count: { dialect: 'cel', source: 'step.result + 1' }, + out: { dialect: 'cel', source: "string(prototype_count) + constructor_name" }, + }), + [{ name: 'out', type: 'text', isOutput: true }, { name: 'my_prototype', type: 'text' }], + )); + const result = await engine.execute('vk_flow'); + expect(result.success, JSON.stringify(result)).toBe(true); + expect((result.output as { out?: unknown }).out).toBe('6c'); + }); +}); + +/** start → screen (one required field, one conditional field) → end. */ +const SCREEN_FLOW = { + name: 'vk_screen', label: 'vk_screen', type: 'screen', + nodes: [ + { id: 'start', type: 'start', label: 'Start' }, + { + id: 'collect', type: 'screen', label: 'Collect', + config: { + title: 'Collect', + fields: [ + { name: 'full_name', label: 'Name', type: 'text', required: true }, + { name: 'note', label: 'Note', type: 'text', required: true, visibleWhen: "full_name == 'show'" }, + ], + }, + }, + { id: 'end', type: 'end', label: 'End' }, + ], + edges: [ + { id: 'e1', source: 'start', target: 'collect' }, + { id: 'e2', source: 'collect', target: 'end' }, + ], +} as any; + +/** start → hold (a pause whose node declares no input contract) → end. */ +const HOLD_FLOW = { + name: 'vk_hold', label: 'vk_hold', type: 'autolaunched', + nodes: [ + { id: 'start', type: 'start', label: 'Start' }, + { id: 'hold', type: 'hold', label: 'Hold' }, + { id: 'end', type: 'end', label: 'End' }, + ], + edges: [ + { id: 'e1', source: 'start', target: 'hold' }, + { id: 'e2', source: 'hold', target: 'end' }, + ], +} as any; + +/** Each case: the signal field and its JSON (so a `__proto__` key is an own key, as a transport hands it). */ +const RESUME_CASES: ReadonlyArray<[string, 'output' | 'variables', string]> = [ + ['case 1 (inputs)', 'variables', '{"full_name":"show","note":"n","constructor":1}'], + ['case 2 (inputs, dotted)', 'variables', '{"full_name":"show","note":"n","a.prototype":1}'], + ['case 3 (inputs)', 'variables', '{"full_name":"show","note":"n","__proto__":{"x":1}}'], + ['case 4 (output)', 'output', '{"prototype":1}'], + ['case 5 (output, dotted)', 'output', '{"decision.constructor":1}'], + ['case 6 (output)', 'output', '{"__proto__":{"x":1}}'], +]; + +function signalOf(field: 'output' | 'variables', json: string, base: Record = {}) { + return { ...base, [field]: JSON.parse(json) }; +} + +describe('the resume door refuses a signal key with a reserved segment', () => { + it.each(RESUME_CASES)('%s on a screen: refused before the submitted values are read, nothing folded', async (_title, field, json) => { + const engine = makeEngine(); + engine.registerFlow('vk_screen', SCREEN_FLOW); + const paused = await engine.execute('vk_screen'); + expect(paused.status).toBe('paused'); + const runId = paused.runId!; + const before = JSON.stringify(((await (engine as any).loadSuspendedRun(runId)) as { variables: unknown }).variables); + + const evaluate = vi.spyOn(engine as any, 'evaluateCondition'); + const base = field === 'output' ? { variables: { full_name: 'show', note: 'n' } } : {}; + const refused = await engine.resume(runId, signalOf(field, json, base)); + expect(refused.success).toBe(false); + expect(refused.code).toBe('INVALID_SIGNAL'); + expect(refused.error).toContain(RESERVED_VARIABLE_KEY_REFUSAL); + // The `visibleWhen` path never ran: nothing read the submitted bag. + expect(evaluate).not.toHaveBeenCalled(); + evaluate.mockRestore(); + + // Nothing folded, and the pause is still live for the real submission. + expect(await engine.hasSuspendedRun(runId)).toBe(true); + const after = JSON.stringify(((await (engine as any).loadSuspendedRun(runId)) as { variables: unknown }).variables); + expect(after).toBe(before); + const done = await engine.resume(runId, { variables: { full_name: 'show', note: 'n' } }); + expect(done.success, JSON.stringify(done)).toBe(true); + }); + + it.each(RESUME_CASES)('%s on a pause with no input contract: refused, nothing folded', async (_title, field, json) => { + const engine = makeEngine(); + engine.registerFlow('vk_hold', HOLD_FLOW); + const paused = await engine.execute('vk_hold'); + expect(paused.status).toBe('paused'); + const runId = paused.runId!; + + const refused = await engine.resume(runId, signalOf(field, json)); + expect(refused.success).toBe(false); + expect(refused.code).toBe('INVALID_SIGNAL'); + expect(await engine.hasSuspendedRun(runId)).toBe(true); + + const done = await engine.resume(runId, { output: { decision: 'approved' } }); + expect(done.success, JSON.stringify(done)).toBe(true); + }); + + it('control: ordinary output and input keys, dotted included, still resume', async () => { + const engine = makeEngine(); + engine.registerFlow('vk_hold', HOLD_FLOW); + const paused = await engine.execute('vk_hold'); + const done = await engine.resume(paused.runId!, { + output: { decision: 'approved', 'detail.constructor_name': 'c' }, + variables: { prototype_count: 1, 'step.result': 2 }, + }); + expect(done.success, JSON.stringify(done)).toBe(true); + }); +}); + +describe('the resume chokepoint refuses the same keys, whoever calls it', () => { + it.each(RESUME_CASES)('%s: rejected as a whole, nothing folded', (_title, field, json) => { + const variables = new Map([['kept', 1]]); + const rejected = applyResumeSignal(variables, signalOf(field, json, { variables: { fine: 2 } }) as any, 'n1'); + expect(rejected.length).toBeGreaterThan(0); + expect([...variables.keys()]).toEqual(['kept']); + }); + + it('control: ordinary keys are folded', () => { + const variables = new Map(); + expect(applyResumeSignal(variables, { output: { decision: 'ok' }, variables: { 'step.result': 1 } }, 'n1')).toEqual([]); + expect([...variables.keys()].sort()).toEqual(['n1.decision', 'step.result']); + }); +}); + +// ── Every position the door judges ────────────────────────────────────────── + +const HERE = dirname(fileURLToPath(import.meta.url)); +/** The spec's binding-position vocabulary, read from its source (the module is package-internal). */ +const SPEC_BINDING_MODULE = resolve(HERE, '../../../spec/src/automation/flow-bound-variable-name.ts'); + +function specBindingKeys(): string[] { + const text = readFileSync(SPEC_BINDING_MODULE, 'utf8'); + const block = /const BINDING_CLAUSES = \{([\s\S]*?)\n\} as const;/.exec(text); + if (!block) throw new Error('BINDING_CLAUSES not found in the spec module'); + return [...block[1]!.matchAll(/^ ([A-Za-z]+):/gm)].map((m) => m[1]!); +} + +/** A parsed-shape flow around `nodes` (the door walks the parsed flow; no parse here, so every shape is reachable). */ +function parsedFlow(nodes: any[], variables: any[] = []): any { + return { name: 'vk_pos', nodes: [{ id: 'start', type: 'start' }, ...nodes], edges: [], variables }; +} + +/** One case per judged position: the flow, and the path suffix its refusal names. */ +const POSITION_CASES: Record any, string]> = { + nodeId: [() => parsedFlow([{ id: 'step.constructor', type: 'assignment', config: { assignments: { v: 1 } } }]), 'nodes[1].id'], + variableName: [() => parsedFlow([], [{ name: 'prototype', type: 'text' }]), 'variables[0].name'], + outputVariable: [() => parsedFlow([{ id: 'run', type: 'script', config: { function: 'f', outputVariable: ' constructor' } }]), 'nodes[1].config.outputVariable'], + errorVariable: [() => parsedFlow([{ id: 'guard', type: 'try_catch', config: { try: { nodes: [], edges: [] }, errorVariable: 'caught.prototype' } }]), 'nodes[1].config.errorVariable'], + iteratorVariable: [() => parsedFlow([{ id: 'each', type: 'loop', config: { collection: [1], iteratorVariable: 'row.__proto__', body: { nodes: [], edges: [] } } }]), 'nodes[1].config.iteratorVariable'], + indexVariable: [() => parsedFlow([{ id: 'each', type: 'loop', config: { collection: [1], iteratorVariable: 'row', indexVariable: 'constructor', body: { nodes: [], edges: [] } } }]), 'nodes[1].config.indexVariable'], + idVariable: [() => parsedFlow([{ id: 'form', type: 'screen', config: { objectName: 'crm_account', idVariable: ' cfg.prototype ' } }]), 'nodes[1].config.idVariable'], + screenFieldName: [() => parsedFlow([{ id: 'ask', type: 'screen', config: { fields: [{ name: 'constructor', type: 'text' }] } }]), 'nodes[1].config.fields[0].name'], + assignmentTarget: [() => parsedFlow([{ id: 'set', type: 'assignment', config: { assignments: { 'a.prototype': 1 } } }]), 'nodes[1].config.assignments["a.prototype"]'], +}; + +describe('the authoring door judges every binding position the spec names, and node ids', () => { + it('its positions are the spec\'s binding positions plus the node id', () => { + expect([...VARIABLE_KEY_POSITIONS].sort()).toEqual([...specBindingKeys(), 'nodeId'].sort()); + }); + + it('the cases below cover every judged position, one each', () => { + expect(Object.keys(POSITION_CASES).sort()).toEqual([...VARIABLE_KEY_POSITIONS].sort()); + }); + + it.each(Object.entries(POSITION_CASES))('position %s: refused, naming the site', (position, [build, suffix]) => { + const refusal = validateVariableKeySegments('vk_pos', build()); + expect(refusal, 'the door must refuse').toBeDefined(); + expect(refusal!.message).toContain(RESERVED_VARIABLE_KEY_REFUSAL); + expect(refusal!.sites.some((site) => site.path.endsWith(suffix) && site.detail.includes(`(${position})`)), JSON.stringify(refusal!.sites)).toBe(true); + }); + + it.each([ + ['case 1 (assignment map)', { assignments: { 'x.constructor': 1 } }, 'assignments["x.constructor"]'], + ['case 2 (legacy array, variable)', { assignments: [{ variable: 'x.prototype', value: 1 }] }, 'assignments[0].variable'], + ['case 3 (legacy array, name)', { assignments: [{ name: 'constructor', value: 1 }] }, 'assignments[0].name'], + ['case 4 (legacy array, key)', { assignments: [{ key: '__proto__', value: 1 }] }, 'assignments[0].key'], + ['case 5 (bare config)', { 'y.prototype': 1 }, 'config["y.prototype"]'], + ])('%s: every assignment shape is judged', (_title, config, suffix) => { + const refusal = validateVariableKeySegments('vk_pos', parsedFlow([{ id: 'set', type: 'assignment', config }])); + expect(refusal?.sites.some((site) => site.path.endsWith(suffix)), JSON.stringify(refusal?.sites)).toBe(true); + }); + + it('a key inside a nested graph is judged where it sits', () => { + const inner = { id: 'inner', type: 'assignment', config: { assignments: { 'z.constructor': 1 } } }; + const refusal = validateVariableKeySegments('vk_pos', parsedFlow([ + { id: 'each', type: 'loop', config: { collection: [1], iteratorVariable: 'row', body: { nodes: [inner], edges: [] } } }, + ])); + expect(refusal?.sites.map((site) => site.path)).toEqual(['flows[0].nodes[1].config.body.nodes[0].config.assignments["z.constructor"]']); + }); + + it.each([ + ['case 1', ' constructor'], + ['case 2', ' cfg.prototype '], + ['case 3', ' __proto__'], + ])('%s: a name an executor trims is judged trimmed', (_title, name) => { + expect(validateVariableKeySegments('vk_pos', parsedFlow([{ id: 'run', type: 'script', config: { function: 'f', outputVariable: name } }]))).toBeDefined(); + expect(validateVariableKeySegments('vk_pos', parsedFlow([{ id: 'form', type: 'screen', config: { objectName: 'o', idVariable: name } }]))).toBeDefined(); + }); + + it('a map node whose id has a reserved part is refused at registration', () => { + const engine = makeEngine(); + const flow = flowWith({ type: 'map', config: { flowName: 'child', collection: [1], iteratorVariable: 'item' } }); + flow.nodes[1].id = 'batch.prototype'; + flow.edges[0].target = 'batch.prototype'; + flow.edges[1].source = 'batch.prototype'; + expect(() => engine.registerFlow('vk_flow', flow)).toThrow(RESERVED_VARIABLE_KEY_REFUSAL); + }); + + it('control: every position with an ordinary name passes', () => { + expect(validateVariableKeySegments('vk_pos', parsedFlow([ + { id: 'step_constructor', type: 'script', config: { function: 'f', outputVariable: ' result ' } }, + { id: 'form', type: 'screen', config: { objectName: 'o', idVariable: 'saved.id' } }, + { id: 'set', type: 'assignment', config: { assignments: [{ variable: 'prototype_count', value: 1 }] } }, + ], [{ name: 'cfg.mode', type: 'text' }]))).toBeUndefined(); + }); +}); + +// ── Resume: delegated signals, and the engine's own continuations ─────────── + +/** A child screen flow, and a parent that calls it through a `subflow` node. */ +function subflowPair(engine: AutomationEngine, outputVariable = 'child_out') { + engine.registerFlow('vk_child', { + name: 'vk_child', label: 'vk_child', type: 'screen', + variables: [{ name: 'note', type: 'text', isOutput: true }], + nodes: [ + { id: 'start', type: 'start', label: 'Start' }, + { id: 'ask', type: 'screen', label: 'Ask', config: { title: 'Ask', fields: [{ name: 'note', label: 'Note', type: 'text', required: true }] } }, + { id: 'end', type: 'end', label: 'End' }, + ], + edges: [{ id: 'e1', source: 'start', target: 'ask' }, { id: 'e2', source: 'ask', target: 'end' }], + } as any); + engine.registerFlow('vk_parent', { + name: 'vk_parent', label: 'vk_parent', type: 'autolaunched', + nodes: [ + { id: 'start', type: 'start', label: 'Start' }, + { id: 'call', type: 'subflow', label: 'Call', config: { flowName: 'vk_child', outputVariable } }, + { id: 'end', type: 'end', label: 'End' }, + ], + edges: [{ id: 'e1', source: 'start', target: 'call' }, { id: 'e2', source: 'call', target: 'end' }], + } as any); +} + +describe('resume: a delegated signal is judged, an engine-built one is not', () => { + it.each(RESUME_CASES)('%s delegated to a subflow child: refused, both runs stay paused', async (_title, field, json) => { + const engine = makeEngine(); + subflowPair(engine); + const paused = await engine.execute('vk_parent'); + expect(paused.status).toBe('paused'); + const base = field === 'output' ? { variables: { note: 'n' } } : {}; + const body = field === 'variables' ? { variables: { note: 'n', ...JSON.parse(json) } } : signalOf(field, json, base); + const refused = await engine.resume(paused.runId!, body as any); + expect(refused.success).toBe(false); + expect(refused.code).toBe('INVALID_SIGNAL'); + const done = await engine.resume(paused.runId!, { variables: { note: 'n' } }); + expect(done.success, JSON.stringify(done)).toBe(true); + }); + + it.each(RESUME_CASES)('%s in an engine-built signal: not judged, so the continuation is folded', (_title, field, json) => { + const signal = engineBuilt(signalOf(field, json) as any); + expect(reservedResumeSignalKeys(signal)).toEqual([]); + const variables = new Map(); + expect(applyResumeSignal(variables, signal, 'n1')).toEqual([]); + expect([...variables.keys()].some((key) => hasReservedVariableKeySegment(key))).toBe(true); + }); + + it('an engine-built continuation under a key the door would now refuse still completes the parent', async () => { + const engine = makeEngine(); + subflowPair(engine); + // A parent held from before the rule: its output variable is a key the door now refuses. + const held = await engine.getFlow('vk_parent'); + (held!.nodes.find((n: any) => n.id === 'call') as any).config.outputVariable = 'child.constructor'; + const paused = await engine.execute('vk_parent'); + expect(paused.status).toBe('paused'); + const done = await engine.resume(paused.runId!, { variables: { note: 'n' } }); + expect(done.success, JSON.stringify(done)).toBe(true); + }); +}); diff --git a/packages/spec/src/automation/builtin-node-config.zod.ts b/packages/spec/src/automation/builtin-node-config.zod.ts index d59c69e5a2e..9ac94c78567 100644 --- a/packages/spec/src/automation/builtin-node-config.zod.ts +++ b/packages/spec/src/automation/builtin-node-config.zod.ts @@ -1776,10 +1776,12 @@ export const AssignmentConfigSchema = lazySchema(() => refuseCatchallProtoKey(z. }), // [objectstack#18847] `__proto__` ONLY. This slot's key type carries no // grammar beyond the `$` rule (`flowBoundVariableNameSchema(…).min(1)`), - // so `constructor` and `prototype` are legal flow-variable names today and - // are left legal — only `__proto__` is structurally unreachable by any key - // schema (see `refuseRecordProtoKey`'s docblock), so it alone is refused - // here. + // so this schema accepts `constructor` and `prototype` — only `__proto__` + // is structurally unreachable by any key schema (see + // `refuseRecordProtoKey`'s docblock), so it alone is refused here. A flow + // is judged at its own door as well: the automation engine's registration + // refuses a variable key whose name, or any dot-separated part of it, is + // `__proto__`, `constructor` or `prototype`. 'assignments', ).optional() .describe('Variables to set: each key is a variable name, each value a CEL value envelope or a literal'), @@ -1807,9 +1809,11 @@ export const AssignmentConfigSchema = lazySchema(() => refuseCatchallProtoKey(z. // `if (key === "__proto__") continue;` runs above `_catchall.run`, so no // catchall schema can ever see the key. `constructor`, `prototype` and // every other reserved-looking name reach the catchall unskipped and - // round-trip intact (measured), so they stay legal top-level variable - // names — nothing here narrows this surface's accept set beyond the one - // name zod makes unrepresentable. + // round-trip intact (measured), so this schema accepts them — nothing here + // narrows this surface's accept set beyond the one name zod makes + // unrepresentable. The automation engine's registration refuses a variable + // key whose name, or any dot-separated part of it, is `__proto__`, + // `constructor` or `prototype`, so a flow naming one does not register. 'an `assignment` node config', )); diff --git a/packages/spec/src/contracts/automation-service.ts b/packages/spec/src/contracts/automation-service.ts index c7e1ad2ebd3..f8c365be903 100644 --- a/packages/spec/src/contracts/automation-service.ts +++ b/packages/spec/src/contracts/automation-service.ts @@ -600,8 +600,10 @@ export interface AutomationResult { * **403**. * - `'INVALID_SIGNAL'` — the resume signal tried to write variables the * flow engine reserves for itself (a `$…` name, or one carrying a `.$` - * segment: `$runId`, `.$mapItemDone`, …). A transport maps it to - * **400**. + * segment: `$runId`, `.$mapItemDone`, …), or named a key in + * `output` or `variables` whose name, or any dot-separated part of it, + * is `__proto__`, `constructor` or `prototype`. Nothing is applied and + * the run stays suspended. A transport maps it to **400**. * - `'RUN_NOT_FOUND'` — no suspension exists for the run id, in the hot * cache or the durable store. The run is unresumable *for good*: it * already resumed, was cancelled, or paused in a process whose state was diff --git a/packages/spec/src/migrations/entries/semantic/19.flow-variable-key-reserved-segment-refused.ts b/packages/spec/src/migrations/entries/semantic/19.flow-variable-key-reserved-segment-refused.ts new file mode 100644 index 00000000000..12d77391041 --- /dev/null +++ b/packages/spec/src/migrations/entries/semantic/19.flow-variable-key-reserved-segment-refused.ts @@ -0,0 +1,29 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import type { SemanticMigration } from '../../types.js'; + +export const entry: SemanticMigration = { + id: 'flow-variable-key-reserved-segment-refused', + surface: + 'automation.Flow registered by the automation engine (a package load, a boot, a save or publish through the ' + + 'metadata doors, os migrate meta --stored): a variable key the flow names in any of its graphs — a node\'s id, a ' + + 'declared variable\'s name, an assignment node\'s target, a node\'s outputVariable / iteratorVariable / ' + + 'indexVariable / errorVariable / idVariable, or a screen field\'s name — whose name, trimmed, or any ' + + 'dot-separated part of it, is __proto__, constructor or prototype; ' + + 'and the same key in a resume signal\'s output or inputs (POST /api/v1/automation/NAME/runs/RUN/resume)', + replacement: + 'Rename the key to one that is none of the three words and has none of them as a dot-separated part (for ' + + 'example constructor to constructor_name, cfg.prototype to cfg.prototype_value, a node id step.constructor to ' + + 'step_constructor), update every expression, edge and text hole that reads it, and send a screen\'s declared ' + + 'field names on resume', + reason: + 'A flow variable key may not use __proto__, constructor or prototype as its name or as any dot-separated part ' + + 'of it. Registration refuses a flow that names one, listing each key and where it sits, and a resume signal ' + + 'carrying one from a caller answers 400 INVALID_SIGNAL with nothing applied and the run still paused (the ' + + 'engine\'s own continuations are not judged, so a run paused before the rule completes). A name that only ' + + 'contains one of the words (constructor_name) is unaffected. There is no mechanical rewrite: the new name, ' + + 'and every reader of the old one, is the author\'s choice.', + acceptanceCriteria: + 'os migrate meta --stored lists no flow with such a key; every flow registers at boot with no registration ' + + 'refusal naming a variable key; a screen run resumed with its declared field names answers 2xx.', +};