@nanobpm/urban 0.97.0 → 0.98.1
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 +28 -0
- package/dist/runtime/core/modules/formjs.gen.js +1 -1
- package/dist/runtime/core/modules/forms.d.ts +20 -0
- package/dist/runtime/core/modules/forms.js +47 -0
- package/dist/runtime/core/modules/pages.js +12 -1
- package/dist/runtime/core/modules/runtime.gen.js +1 -1
- package/dist/runtime/core/modules/surfaces.js +57 -4
- package/package.json +2 -2
- package/src/runtime/browser/fake-dom.test-utils.ts +16 -1
- package/src/runtime/browser/formjs.browser.js +258 -7
- package/src/runtime/browser/formjs.browser.test.ts +690 -0
- package/src/runtime/browser/runtime.browser.js +25 -3
- package/src/runtime/browser/runtime.engineform.test.ts +203 -0
- package/src/runtime/core/modules/formjs.gen.ts +1 -1
- package/src/runtime/core/modules/forms.ts +47 -0
- package/src/runtime/core/modules/pages.test.ts +21 -0
- package/src/runtime/core/modules/pages.ts +13 -1
- package/src/runtime/core/modules/runtime.gen.ts +1 -1
- package/src/runtime/core/modules/surfaces.test.ts +308 -0
- package/src/runtime/core/modules/surfaces.ts +58 -4
|
@@ -1939,7 +1939,10 @@ function buildDetailForm(f, row, onSuccess) {
|
|
|
1939
1939
|
//
|
|
1940
1940
|
// `cfg.formKeyField` (default "form_key") names the row column carrying the engine
|
|
1941
1941
|
// formKey; `cfg.userTaskKeyField` (default "user_task_key") names the column
|
|
1942
|
-
// carrying the user-task key to complete.
|
|
1942
|
+
// carrying the user-task key to complete; `cfg.processInstanceKeyField` (default
|
|
1943
|
+
// "process_instance_key", falling back to a camelCase `processInstanceKey` column)
|
|
1944
|
+
// names the column carrying the process-instance key whose variables become the
|
|
1945
|
+
// renderer's context (#603). A row with no formKey degrades to a bare
|
|
1943
1946
|
// "Complete" button (empty variables), matching taskInbox's no-form fallback.
|
|
1944
1947
|
/** @param {any} cfg
|
|
1945
1948
|
* @param {Record<string, any>} row
|
|
@@ -1994,8 +1997,22 @@ function buildEngineForm(cfg, row, onSuccess) {
|
|
|
1994
1997
|
return box;
|
|
1995
1998
|
}
|
|
1996
1999
|
box.append(el("p", { class: "njf-text" }, "loading form\u2026"));
|
|
1997
|
-
|
|
1998
|
-
|
|
2000
|
+
// Load the row's task variables alongside the form (#603): they are the
|
|
2001
|
+
// renderer's context — `{{name}}` text templating, `=varName` image sources,
|
|
2002
|
+
// and keyed-input prefill — so the drawer shows the reviewer what they are
|
|
2003
|
+
// reviewing, exactly like the taskInbox surface. The row column naming the
|
|
2004
|
+
// process-instance key is `cfg.processInstanceKeyField` (default
|
|
2005
|
+
// "process_instance_key", falling back to a camelCase `processInstanceKey`
|
|
2006
|
+
// column); a row without one (or a failed fetch) degrades to an empty context
|
|
2007
|
+
// rather than blocking the form.
|
|
2008
|
+
const pikField = cfg.processInstanceKeyField || "process_instance_key";
|
|
2009
|
+
const pik = row[pikField] != null ? row[pikField] : row.processInstanceKey;
|
|
2010
|
+
const varsP =
|
|
2011
|
+
pik != null && pik !== ""
|
|
2012
|
+
? getJSON("/app/actions/variables?processInstanceKey=" + encodeURIComponent(String(pik))).catch(() => ({}))
|
|
2013
|
+
: Promise.resolve({});
|
|
2014
|
+
Promise.all([getJSON("/app/actions/form?formKey=" + encodeURIComponent(String(formKey))), varsP])
|
|
2015
|
+
.then(([f, context]) => {
|
|
1999
2016
|
box.replaceChildren();
|
|
2000
2017
|
const renderer = /** @type {any} */ (globalThis).NanoFormJs;
|
|
2001
2018
|
if (!f || !f.schema || !renderer) {
|
|
@@ -2005,6 +2022,11 @@ function buildEngineForm(cfg, row, onSuccess) {
|
|
|
2005
2022
|
box.append(
|
|
2006
2023
|
renderer.renderForm(f.schema, {
|
|
2007
2024
|
submitLabel: "Complete",
|
|
2025
|
+
context: context || {},
|
|
2026
|
+
// Rebase root-relative image sources ("/app/…") onto the app mount root,
|
|
2027
|
+
// exactly like every page fetch — otherwise they escape the console's
|
|
2028
|
+
// path-prefixed proxy (/console/app-view/<name>/) and 404.
|
|
2029
|
+
resolveUrl: apiUrl,
|
|
2008
2030
|
/** @param {Record<string, any>} variables */
|
|
2009
2031
|
onSubmit: (variables) => {
|
|
2010
2032
|
msg.className = "njf-msg";
|
|
@@ -256,3 +256,206 @@ test("buildEngineForm treats a whitespace-only completePath as absent", async (t
|
|
|
256
256
|
assert.ok(completeReq, "a whitespace-only completePath still targets the default /app/actions/complete seam");
|
|
257
257
|
assert.equal(completeReq!.body.userTaskKey, "ut-e");
|
|
258
258
|
});
|
|
259
|
+
|
|
260
|
+
test("buildEngineForm loads the row's task variables and renders {{title}} + an =img1 image with them (#603)", async (t) => {
|
|
261
|
+
// The acceptance scenario end to end through the pages drawer: a task whose
|
|
262
|
+
// variables include `title` and `img1`, with a form using {{title}} and an
|
|
263
|
+
// image with source "=img1", renders both — and prefills the keyed input.
|
|
264
|
+
const created: FakeElement[] = [];
|
|
265
|
+
const calls: FetchCall[] = [];
|
|
266
|
+
t.after(installFakeDom(created));
|
|
267
|
+
t.after(
|
|
268
|
+
installFakeFetch((url) => {
|
|
269
|
+
if (url.includes("/app/actions/form")) {
|
|
270
|
+
return {
|
|
271
|
+
status: 200,
|
|
272
|
+
json: {
|
|
273
|
+
schema: {
|
|
274
|
+
components: [
|
|
275
|
+
{ type: "text", text: "Reviewing {{title}}" },
|
|
276
|
+
{ type: "image", source: "=img1", alt: "Proposed thumbnail" },
|
|
277
|
+
{ type: "textfield", key: "title" },
|
|
278
|
+
],
|
|
279
|
+
},
|
|
280
|
+
},
|
|
281
|
+
};
|
|
282
|
+
}
|
|
283
|
+
if (url.includes("/app/actions/variables")) {
|
|
284
|
+
return { status: 200, json: { title: "Draft v2", img1: "https://cdn.example.com/t1.png" } };
|
|
285
|
+
}
|
|
286
|
+
return { status: 200, json: { ok: true } };
|
|
287
|
+
}, calls),
|
|
288
|
+
);
|
|
289
|
+
const box = buildEngineForm(
|
|
290
|
+
CFG,
|
|
291
|
+
{ form_key: "form-v", user_task_key: "ut-v", process_instance_key: "pi-v" },
|
|
292
|
+
() => {},
|
|
293
|
+
);
|
|
294
|
+
assert.ok(box);
|
|
295
|
+
await new Promise((r) => setTimeout(r, 0));
|
|
296
|
+
const varsReq = calls.find((c) => c.url.includes("/app/actions/variables"));
|
|
297
|
+
assert.ok(varsReq, "the row's variables are fetched alongside the form");
|
|
298
|
+
assert.match(varsReq!.url, /processInstanceKey=pi-v/, "fetched by the row's process-instance key");
|
|
299
|
+
const p = created.find((n) => n.tagName === "P" && n.className.includes("njf-text") && n.textContent.includes("Reviewing"));
|
|
300
|
+
assert.ok(p, "the text component rendered");
|
|
301
|
+
assert.equal(p!.textContent, "Reviewing Draft v2", "{{title}} templated from the task's variables");
|
|
302
|
+
const img = created.find((n) => n.tagName === "IMG");
|
|
303
|
+
assert.ok(img, "the image component rendered");
|
|
304
|
+
assert.equal(img!.getAttribute("src"), "https://cdn.example.com/t1.png", "=img1 resolved from the task's variables");
|
|
305
|
+
assert.equal(img!.getAttribute("alt"), "Proposed thumbnail");
|
|
306
|
+
const input = created.find((n) => n.tagName === "INPUT");
|
|
307
|
+
assert.equal(input!.value, "Draft v2", "the keyed input is prefilled from the same context");
|
|
308
|
+
});
|
|
309
|
+
|
|
310
|
+
test("buildEngineForm rebases a root-relative image source through the pages resolver — revalidated, fail-closed off http(s)", async (t) => {
|
|
311
|
+
// Behind the console proxy the app is mounted at /console/app-view/<name>/, so a
|
|
312
|
+
// form image source of /app/thumb.png is rebased through the same mount-aware
|
|
313
|
+
// resolver apiUrl uses — otherwise the <img> requests the console's
|
|
314
|
+
// /app/thumb.png and app-served thumbnails 404. The renderer REVALIDATES the
|
|
315
|
+
// resolver's output (round 5): it must come back an http(s)/protocol-relative
|
|
316
|
+
// URL or a same-origin path. Under this Node runner the module base is file://,
|
|
317
|
+
// so apiUrl's rebase yields file://… — refused (fail closed: a non-http(s)
|
|
318
|
+
// origin is not a fetchable image). In a browser the same code yields
|
|
319
|
+
// https://… and renders (the http(s) pass side is pinned in
|
|
320
|
+
// formjs.browser.test.ts with an https-mount resolver).
|
|
321
|
+
const created: FakeElement[] = [];
|
|
322
|
+
const calls: FetchCall[] = [];
|
|
323
|
+
t.after(installFakeDom(created));
|
|
324
|
+
t.after(
|
|
325
|
+
installFakeFetch((url) => {
|
|
326
|
+
if (url.includes("/app/actions/form")) {
|
|
327
|
+
return {
|
|
328
|
+
status: 200,
|
|
329
|
+
json: {
|
|
330
|
+
schema: {
|
|
331
|
+
components: [
|
|
332
|
+
{ type: "image", source: "/app/thumb.png", alt: "literal" },
|
|
333
|
+
{ type: "image", source: "=img1", alt: "from variable" },
|
|
334
|
+
],
|
|
335
|
+
},
|
|
336
|
+
},
|
|
337
|
+
};
|
|
338
|
+
}
|
|
339
|
+
if (url.includes("/app/actions/variables")) {
|
|
340
|
+
return { status: 200, json: { img1: "/app/var-thumb.png" } };
|
|
341
|
+
}
|
|
342
|
+
return { status: 200, json: { ok: true } };
|
|
343
|
+
}, calls),
|
|
344
|
+
);
|
|
345
|
+
const box = buildEngineForm(
|
|
346
|
+
CFG,
|
|
347
|
+
{ form_key: "form-v", user_task_key: "ut-v", process_instance_key: "pi-v" },
|
|
348
|
+
() => {},
|
|
349
|
+
);
|
|
350
|
+
assert.ok(box);
|
|
351
|
+
await new Promise((r) => setTimeout(r, 0));
|
|
352
|
+
const srcs = created.filter((n) => n.tagName === "IMG").map((n) => n.getAttribute("src"));
|
|
353
|
+
assert.equal(srcs.length, 0, "file://-rebased sources are refused under Node; https:// ones render in a browser");
|
|
354
|
+
for (const src of srcs) {
|
|
355
|
+
assert.ok(!src!.startsWith("/app/"), "never the root-relative form that would hit the console's /app/");
|
|
356
|
+
}
|
|
357
|
+
});
|
|
358
|
+
|
|
359
|
+
test("buildEngineForm still renders the form when the variables fetch fails (#603 degradation)", async (t) => {
|
|
360
|
+
const created: FakeElement[] = [];
|
|
361
|
+
t.after(installFakeDom(created));
|
|
362
|
+
t.after(
|
|
363
|
+
installFakeFetch((url) => {
|
|
364
|
+
if (url.includes("/app/actions/form")) {
|
|
365
|
+
return { status: 200, json: { schema: { components: [{ type: "textfield", key: "note" }] } } };
|
|
366
|
+
}
|
|
367
|
+
return { status: 500 }; // variables fetch fails
|
|
368
|
+
}, []),
|
|
369
|
+
);
|
|
370
|
+
const box = buildEngineForm(CFG, { form_key: "form-x", user_task_key: "ut-x", process_instance_key: "pi-x" }, () => {});
|
|
371
|
+
assert.ok(box);
|
|
372
|
+
await new Promise((r) => setTimeout(r, 0));
|
|
373
|
+
const form = created.find((n) => n.tagName === "FORM");
|
|
374
|
+
assert.ok(form, "a variables-fetch failure does not block the form");
|
|
375
|
+
const input = created.find((n) => n.tagName === "INPUT");
|
|
376
|
+
assert.equal(input!.value, "", "no context → no prefill");
|
|
377
|
+
});
|
|
378
|
+
|
|
379
|
+
test("buildEngineForm honours a camelCase processInstanceKey column and a custom processInstanceKeyField", async (t) => {
|
|
380
|
+
const created: FakeElement[] = [];
|
|
381
|
+
const calls: FetchCall[] = [];
|
|
382
|
+
t.after(installFakeDom(created));
|
|
383
|
+
t.after(
|
|
384
|
+
installFakeFetch((url) => {
|
|
385
|
+
if (url.includes("/app/actions/form")) {
|
|
386
|
+
return { status: 200, json: { schema: { components: [] } } };
|
|
387
|
+
}
|
|
388
|
+
return { status: 200, json: {} };
|
|
389
|
+
}, calls),
|
|
390
|
+
);
|
|
391
|
+
buildEngineForm(CFG, { form_key: "f", user_task_key: "u", processInstanceKey: "pi-camel" }, () => {});
|
|
392
|
+
await new Promise((r) => setTimeout(r, 0));
|
|
393
|
+
assert.ok(
|
|
394
|
+
calls.some((c) => c.url.includes("processInstanceKey=pi-camel")),
|
|
395
|
+
"a camelCase processInstanceKey column is picked up when process_instance_key is absent",
|
|
396
|
+
);
|
|
397
|
+
calls.length = 0;
|
|
398
|
+
buildEngineForm(
|
|
399
|
+
{ ...CFG, processInstanceKeyField: "pi" },
|
|
400
|
+
{ form_key: "f", user_task_key: "u", pi: "pi-custom" },
|
|
401
|
+
() => {},
|
|
402
|
+
);
|
|
403
|
+
await new Promise((r) => setTimeout(r, 0));
|
|
404
|
+
assert.ok(
|
|
405
|
+
calls.some((c) => c.url.includes("processInstanceKey=pi-custom")),
|
|
406
|
+
"cfg.processInstanceKeyField names a custom column",
|
|
407
|
+
);
|
|
408
|
+
});
|
|
409
|
+
|
|
410
|
+
// ── PR #604 round 5: the pages resolver (apiUrl) cannot launder a forbidden scheme ──
|
|
411
|
+
|
|
412
|
+
test("buildEngineForm rejects a root-prefixed forbidden-scheme image source through the pages resolver", async (t) => {
|
|
413
|
+
// apiUrl strips the leading slash before `new URL(u.slice(1), APP_BASE)`, so a
|
|
414
|
+
// source of "/javascript:alert(1)" — accepted by the allowlist as an
|
|
415
|
+
// app-relative path — resolves to the forbidden-scheme URL
|
|
416
|
+
// "javascript:alert(1)". The renderer must revalidate the RESOLVED URL: no
|
|
417
|
+
// <img> with a non-http(s)/data-image src may be set, for a literal source or
|
|
418
|
+
// a variable-backed one.
|
|
419
|
+
const created: FakeElement[] = [];
|
|
420
|
+
const calls: FetchCall[] = [];
|
|
421
|
+
t.after(installFakeDom(created));
|
|
422
|
+
t.after(
|
|
423
|
+
installFakeFetch((url) => {
|
|
424
|
+
if (url.includes("/app/actions/form")) {
|
|
425
|
+
return {
|
|
426
|
+
status: 200,
|
|
427
|
+
json: {
|
|
428
|
+
schema: {
|
|
429
|
+
components: [
|
|
430
|
+
{ type: "image", source: "/javascript:alert(1)", alt: "literal" },
|
|
431
|
+
{ type: "image", source: "=evil", alt: "from variable" },
|
|
432
|
+
{ type: "image", source: "/app/legit.png", alt: "legit" },
|
|
433
|
+
],
|
|
434
|
+
},
|
|
435
|
+
},
|
|
436
|
+
};
|
|
437
|
+
}
|
|
438
|
+
if (url.includes("/app/actions/variables")) {
|
|
439
|
+
return { status: 200, json: { evil: "/data:text/html;base64,PGI+" } };
|
|
440
|
+
}
|
|
441
|
+
return { status: 200, json: { ok: true } };
|
|
442
|
+
}, calls),
|
|
443
|
+
);
|
|
444
|
+
const box = buildEngineForm(
|
|
445
|
+
CFG,
|
|
446
|
+
{ form_key: "form-v", user_task_key: "ut-v", process_instance_key: "pi-v" },
|
|
447
|
+
() => {},
|
|
448
|
+
);
|
|
449
|
+
assert.ok(box);
|
|
450
|
+
await new Promise((r) => setTimeout(r, 0));
|
|
451
|
+
const srcs = created.filter((n) => n.tagName === "IMG").map((n) => n.getAttribute("src"));
|
|
452
|
+
// Under this Node runner apiUrl's rebase lands on file://, so the renderer's
|
|
453
|
+
// fail-closed revalidation refuses even the legitimate source — in a browser
|
|
454
|
+
// the same resolver yields https:// and the legitimate image renders (the
|
|
455
|
+
// pass side is pinned in formjs.browser.test.ts with an https-mount resolver).
|
|
456
|
+
// The security property this test pins: no laundered forbidden-scheme src.
|
|
457
|
+
assert.equal(srcs.length, 0, "no laundered (or file://-rebased) source rendered");
|
|
458
|
+
for (const src of srcs) {
|
|
459
|
+
assert.ok(!/^(javascript|data|vbscript):/i.test(src!), "no forbidden-scheme src was set");
|
|
460
|
+
}
|
|
461
|
+
});
|
|
@@ -3,4 +3,4 @@
|
|
|
3
3
|
// form-js renderer). Regenerate with `npm run gen:runtime`; CI enforces this file
|
|
4
4
|
// is byte-identical to a fresh generation via `git diff --exit-code` (npm run check:runtime).
|
|
5
5
|
|
|
6
|
-
export const FORMJS_JS: string = "// @ts-check\n// ── Shared, XSS-safe form-js schema renderer (ADR 0026, extended by #457) ─────\n// This is the ONE client implementation of \"render a deployed `.form`'s form-js\n// schema and collect its field values\", shared verbatim by BOTH:\n// • the `taskInbox` surface (surfaces.ts `inboxPage`), and\n// • the pages `dataGrid` engine-form detail (runtime.browser.js).\n// It used to live inline in surfaces.ts; factoring it here means the two surfaces\n// can never fork the renderer or drift on how a form-js component maps to an input\n// and its submitted value.\n//\n// Like the rest of the browser runtime it is authored/type-checked/linted/tested\n// as real source and served as a generated string artifact (formjs.gen.ts, emitted\n// by scripts/gen-runtime.mjs). It performs NO DOM access at load — every DOM touch\n// is inside a function — so it is import-safe under Node/Deno for unit testing.\n//\n// SECURITY: every value the engine returns is placed via textContent / setAttribute\n// (never innerHTML), so nothing in the form schema can inject markup. The submitted\n// `variables` bag is null-prototype so an engine-supplied component key of\n// `__proto__`/`constructor` lands as a plain own property and can never mutate a\n// prototype (prototype-pollution class).\n\n/** Create an element, setting attributes via setAttribute and text via textContent only.\n * @param {string} tag\n * @param {Record<string, string>} [attrs]\n * @param {string} [text]\n * @returns {any}\n */\nfunction fjEl(tag, attrs, text) {\n const e = document.createElement(tag);\n if (attrs) for (const k in attrs) e.setAttribute(k, attrs[k]);\n if (text != null) e.textContent = text;\n return e;\n}\n\n/** A plain type=\"button\" with an optional click handler.\n * @param {string} label\n * @param {(() => void) | null} [onClick]\n * @returns {any}\n */\nfunction fjBtn(label, onClick) {\n const b = document.createElement(\"button\");\n b.type = \"button\";\n b.textContent = label;\n if (onClick) b.addEventListener(\"click\", onClick);\n return b;\n}\n\n/** Build one form-js component into its field element and (for keyed inputs) a reader\n * that returns the entered `{ key, value }` or null when blank. Static (keyless)\n * components render as inert text; layout-only components are skipped (null).\n * @param {any} c\n * @returns {{ field: any, read?: () => ({ key: string, value: any } | null) } | null}\n */\nfunction buildField(c) {\n const type = c && c.type;\n // Static (keyless) components: show text as a paragraph, ignore layout-only ones.\n if (type === \"text\") {\n return { field: fjEl(\"p\", { class: \"njf-text\" }, typeof c.text === \"string\" ? c.text : \"\") };\n }\n const key = c && c.key;\n if (!key) return null;\n const wrap = fjEl(\"div\", { class: \"njf-field\" });\n const label = typeof c.label === \"string\" && c.label ? c.label : key;\n if (type === \"checkbox\") {\n const input = document.createElement(\"input\");\n input.type = \"checkbox\";\n const lab = fjEl(\"label\", {});\n lab.appendChild(input);\n lab.appendChild(document.createTextNode(\" \" + label));\n wrap.appendChild(lab);\n return { field: wrap, read: () => ({ key, value: input.checked }) };\n }\n const labelEl = fjEl(\"label\", {}, label);\n wrap.appendChild(labelEl);\n let input;\n if (type === \"textarea\") {\n input = document.createElement(\"textarea\");\n } else if (type === \"select\") {\n input = document.createElement(\"select\");\n input.appendChild(fjEl(\"option\", { value: \"\" }, \"\\u2014\"));\n for (const o of Array.isArray(c.values) ? c.values : []) {\n input.appendChild(fjEl(\"option\", { value: String(o.value) }, String(o.label != null ? o.label : o.value)));\n }\n } else if (type === \"radio\") {\n const name = \"r\" + Math.random().toString(36).slice(2);\n const group = fjEl(\"div\", {});\n for (const o of Array.isArray(c.values) ? c.values : []) {\n const rlab = fjEl(\"label\", {});\n const r = document.createElement(\"input\");\n r.type = \"radio\";\n r.name = name;\n r.value = String(o.value);\n rlab.appendChild(r);\n rlab.appendChild(document.createTextNode(\" \" + String(o.label != null ? o.label : o.value)));\n group.appendChild(rlab);\n }\n wrap.appendChild(group);\n return {\n field: wrap,\n read: () => {\n const sel = group.querySelector(\"input:checked\");\n return sel ? { key, value: sel.value } : null;\n },\n };\n } else {\n input = document.createElement(\"input\");\n input.type = type === \"number\" ? \"number\" : type === \"datetime\" ? \"datetime-local\" : \"text\";\n }\n // Associate the label with the input (for/id) so screen readers announce it on focus.\n const fieldId = \"f\" + Math.random().toString(36).slice(2);\n input.id = fieldId;\n labelEl.setAttribute(\"for\", fieldId);\n wrap.appendChild(input);\n const isNumber = type === \"number\";\n return {\n field: wrap,\n read: () => {\n const raw = input.value;\n if (raw === \"\" || raw == null) return null;\n if (isNumber) {\n const n = Number(raw);\n // A non-numeric value in a number field is only reachable via tampering (the browser\n // blanks invalid type=number input). Treat it as absent rather than silently submitting\n // NaN, which JSON.stringify serializes as null — quietly changing the submitted value.\n return Number.isFinite(n) ? { key, value: n } : null;\n }\n return { key, value: raw };\n },\n };\n}\n\n/**\n * Render a form-js schema into a `<form>` element with a submit + optional cancel.\n * On submit it assembles every keyed field's value into one null-prototype\n * `variables` bag and calls `opts.onSubmit(variables)`; a rejected submit re-enables\n * the button so the operator can retry. `opts.onCancel`, when supplied, wires a\n * cancel button.\n * @param {any} schema the parsed form-js document (`{ components: [...] }`)\n * @param {{ heading?: string, submitLabel?: string, cancelLabel?: string,\n * onSubmit: (variables: Record<string, any>) => (void | Promise<void>),\n * onCancel?: () => void }} opts\n * @returns {any} the built <form> element\n */\nfunction renderForm(schema, opts) {\n const form = document.createElement(\"form\");\n form.className = \"njf-form\";\n if (opts.heading) form.appendChild(fjEl(\"h2\", { class: \"njf-heading\" }, opts.heading));\n const components = schema && Array.isArray(schema.components) ? schema.components : [];\n /** @type {Array<() => ({ key: string, value: any } | null)>} */\n const inputs = [];\n for (const c of components) {\n const built = buildField(c);\n if (!built) continue;\n form.appendChild(built.field);\n if (built.read) inputs.push(built.read);\n }\n const submit = fjBtn(opts.submitLabel || \"Submit\", null);\n submit.type = \"submit\";\n const bar = fjEl(\"div\", { class: \"njf-actions\" });\n bar.appendChild(submit);\n if (opts.onCancel) bar.appendChild(fjBtn(opts.cancelLabel || \"Cancel\", opts.onCancel));\n form.appendChild(bar);\n form.addEventListener(\"submit\", (e) => {\n e.preventDefault();\n // Null-prototype: field keys come from the engine-supplied form schema. A component\n // keyed '__proto__'/'constructor' must land as a plain own property (and round-trip\n // through JSON), never mutate a prototype — no prototype pollution in the page runtime.\n const variables = Object.create(null);\n for (const read of inputs) {\n const kv = read();\n if (kv) variables[kv.key] = kv.value;\n }\n submit.disabled = true;\n Promise.resolve()\n .then(() => opts.onSubmit(variables))\n .catch(() => {\n submit.disabled = false;\n });\n });\n return form;\n}\n\n\n// Expose the renderer as a browser global so both self-contained page bundles can\n// reach the ONE implementation without importing it: the taskInbox page embeds this\n// module inline and the pages shell does the same before loading the ES-module\n// runtime, which reads `globalThis.NanoFormJs` lazily when it renders an engine form.\n// Guarded so importing under Node/Deno for tests is a harmless no-op-ish assignment.\nif (typeof globalThis !== \"undefined\") {\n /** @type {any} */ (globalThis).NanoFormJs = { buildField, renderForm };\n}\n";
|
|
6
|
+
export const FORMJS_JS: string = "// @ts-check\n// ── Shared, XSS-safe form-js schema renderer (ADR 0026, extended by #457) ─────\n// This is the ONE client implementation of \"render a deployed `.form`'s form-js\n// schema and collect its field values\", shared verbatim by BOTH:\n// • the `taskInbox` surface (surfaces.ts `inboxPage`), and\n// • the pages `dataGrid` engine-form detail (runtime.browser.js).\n// It used to live inline in surfaces.ts; factoring it here means the two surfaces\n// can never fork the renderer or drift on how a form-js component maps to an input\n// and its submitted value.\n//\n// Like the rest of the browser runtime it is authored/type-checked/linted/tested\n// as real source and served as a generated string artifact (formjs.gen.ts, emitted\n// by scripts/gen-runtime.mjs). It performs NO DOM access at load — every DOM touch\n// is inside a function — so it is import-safe under Node/Deno for unit testing.\n//\n// SECURITY: every value the engine returns is placed via textContent / setAttribute\n// (never innerHTML), so nothing in the form schema can inject markup. The submitted\n// `variables` bag is null-prototype so an engine-supplied component key of\n// `__proto__`/`constructor` lands as a plain own property and can never mutate a\n// prototype (prototype-pollution class).\n//\n// VARIABLES CONTEXT (#603): both surfaces pass the task's variables as the render\n// `context`. `text` components interpolate `{{name}}` against it (textContent-only,\n// never markup), `image` components resolve a `=varName` source from it, and a\n// keyed input whose key is present is prefilled — the form-js/Camunda Tasklist\n// behaviour, so a reviewer sees what they are reviewing.\n\n/** Create an element, setting attributes via setAttribute and text via textContent only.\n * @param {string} tag\n * @param {Record<string, string>} [attrs]\n * @param {string} [text]\n * @returns {any}\n */\nfunction fjEl(tag, attrs, text) {\n const e = document.createElement(tag);\n if (attrs) for (const k in attrs) e.setAttribute(k, attrs[k]);\n if (text != null) e.textContent = text;\n return e;\n}\n\n/** A plain type=\"button\" with an optional click handler.\n * @param {string} label\n * @param {(() => void) | null} [onClick]\n * @returns {any}\n */\nfunction fjBtn(label, onClick) {\n const b = document.createElement(\"button\");\n b.type = \"button\";\n b.textContent = label;\n if (onClick) b.addEventListener(\"click\", onClick);\n return b;\n}\n\n/** Interpolate `{{name}}` placeholders in a `text` component against the render\n * context (the task's variables), following form-js/Camunda Tasklist. A present\n * value is stringified (objects/arrays as JSON); an unknown name becomes the empty\n * string. The result is placed via textContent only — a variable holding markup\n * (`<img onerror=…>`) renders as literal text, never as HTML (the XSS rule holds\n * for templated text exactly as for static text).\n * @param {string} text\n * @param {Record<string, any>} context\n * @returns {string}\n */\nfunction fjTemplate(text, context) {\n return text.replace(/\\{\\{\\s*([^{}\\s]+)\\s*\\}\\}/g, (_m, name) => {\n const v = context[name];\n if (v == null) return \"\";\n return typeof v === \"string\" ? v : JSON.stringify(v);\n });\n}\n\n/** Copy only the context's OWN enumerable properties into a null-prototype\n * dictionary, so lookups like `ctx[\"constructor\"]` or `ctx[\"__proto__\"]` never\n * resolve to inherited members (which would template/prefill bogus values), while\n * an explicitly supplied own value with such a name is still honoured.\n * @param {any} context\n * @returns {Record<string, any>}\n */\nfunction fjOwnContext(context) {\n /** @type {Record<string, any>} */\n const out = Object.create(null);\n if (context == null || typeof context !== \"object\") return out;\n for (const k of Object.keys(context)) {\n Object.defineProperty(out, k, { value: context[k], enumerable: true, writable: true, configurable: true });\n }\n return out;\n}\n\n/** The image-source allowlist, applied to BOTH the raw source and — when a\n * `resolveUrl` rewrote it — the RESOLVED URL. A resolver is same-origin trusted\n * code, but it TRANSFORMS the string (the pages runtime's `apiUrl` strips the\n * leading slash before `new URL(...)`), and a transformation can mint a forbidden\n * shape from an accepted one: a root-prefixed script-scheme path passes below as\n * an app-relative path (the leading slash defeats the scheme check), then\n * resolves to the bare forbidden-scheme URL. Re-running the allowlist on the\n * resolver's result closes that laundering class at the single choke point every\n * surface flows through, so no resolver — present or future — can widen the\n * accepted set.\n * @param {string} url\n * @returns {string | null} the URL when allowed, null when rejected\n */\nfunction fjAllowImageUrl(url) {\n // Browsers strip/normalise whitespace and control characters and treat `\\` as\n // `/` before interpreting a URL, so `java\\tscript:` or ` data:image/svg+xml` or\n // `/\\\\host` could slip past the allowlist below. Fail closed on any of them.\n if (/[\\s\\u0000-\\u001f\\u007f\\\\]/.test(url)) return null;\n // data:image — RFC 2397 lets the mediatype be followed directly by `,`\n // (parameters and `;base64` are both optional), so accept `;` OR `,` after the\n // subtype or a percent-encoded payload silently never renders.\n if (/^data:image\\/(png|jpeg|gif|webp)[;,]/i.test(url)) return url;\n if (/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(url)) {\n // A scheme: only http(s) is allowed (javascript:/data-text-html/etc. rejected).\n return /^https?:\\/\\//i.test(url) ? url : null;\n }\n if (url.startsWith(\"//\")) return null; // protocol-relative → off-origin, reject\n return url; // app-relative path\n}\n\n/** Resolve an `image` component's `source` to a URL the renderer will put on the\n * <img>, or null to reject it. `source` is either a literal URL or `=varName` — a\n * PLAIN variable reference into the render context (full FEEL is intentionally not\n * supported: anything after `=` that is not a bare identifier is rejected). Only\n * `http(s):` URLs, app-relative paths (no scheme, no `//host` protocol-relative),\n * and `data:image/(png|jpeg|gif|webp)` URLs are allowed — never `javascript:` or\n * any other scheme. The URL is set with setAttribute (never innerHTML).\n * `resolveUrl`, when supplied, rewrites an ACCEPTED URL just before it is set —\n * both surfaces pass their app-mount-aware resolver (the pages runtime's `apiUrl`,\n * the inbox page's mount prefix) so a root-relative `/app/…` source requests the\n * app's own path even behind the console's path-prefixed proxy. The allowlist runs\n * on the raw source AND again on the resolver's result (see fjAllowImageUrl), so a\n * resolver can never launder a rejected URL — including one it minted itself by\n * rebasing a disguised path.\n * @param {any} source\n * @param {Record<string, any>} context\n * @param {(url: string) => string} [resolveUrl]\n * @returns {string | null}\n */\nfunction fjImageSrc(source, context, resolveUrl) {\n let url = source;\n if (typeof url === \"string\" && url.startsWith(\"=\")) {\n const name = url.slice(1).trim();\n // A plain variable reference only — reject anything that isn't a bare\n // identifier (a FEEL expression, a call, a path) rather than evaluating it.\n if (!/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(name)) return null;\n url = context[name];\n }\n if (typeof url !== \"string\" || url === \"\") return null;\n const allowed = fjAllowImageUrl(url);\n if (allowed == null) return null;\n // App-relative path. A root-relative one (\"/app/…\") is only correct when the app\n // is served at the origin root; behind the console's path-prefixed proxy it must\n // be rebased onto the app mount (the resolver both surfaces pass). Absolute\n // http(s)/data: URLs pass through untouched (the resolvers only rewrite\n // single-leading-slash paths), but revalidate the result regardless — a resolver\n // that strips the leading slash (the pages `apiUrl`) turns \"/javascript:…\" into\n // a forbidden-scheme URL, which must not reach the <img>.\n if (!resolveUrl) return allowed;\n // A resolver can THROW on an allowlist-accepted source: the pages `apiUrl`\n // strips the leading slash and calls `new URL(...)`, which throws `Invalid URL`\n // on a path that is not URL-path-shaped (e.g. \"/http://\"). Uncaught, that\n // exception escapes buildField and the WHOLE task form fails to render. A\n // failed resolution rejects just this image (null), exactly like a resolver\n // that returned a rejected URL.\n let resolved;\n try {\n resolved = resolveUrl(allowed);\n } catch {\n return null;\n }\n if (typeof resolved !== \"string\" || resolved === \"\") return null;\n // Re-run the SAME allowlist on the resolver's output (one source of truth):\n // app-relative paths, http(s) and data:image survive; a forbidden scheme the\n // resolver minted (e.g. \"/javascript:…\" stripped to \"javascript:…\"), a file:\n // URL, or a protocol-relative URL is rejected.\n return fjAllowImageUrl(resolved);\n}\n\n/** The value a keyed input is prefilled with when its key is present in the render\n * context (form-js prefill semantics): strings as-is, other scalars stringified,\n * objects/arrays as JSON. `undefined`/`null` mean \"no prefill\".\n * @param {Record<string, any>} context\n * @param {string} key\n * @returns {string | undefined}\n */\nfunction fjPrefill(context, key) {\n const v = context[key];\n if (v == null) return undefined;\n return typeof v === \"string\" ? v : typeof v === \"object\" ? JSON.stringify(v) : String(v);\n}\n\n/** The prefill pair for a keyed input: `display` is the string the control shows\n * (fjPrefill's rendering); `original` is the context value itself, captured at\n * prefill time. An UNTOUCHED control — one that still shows exactly `display` —\n * submits `original`, never `display`: the completion endpoint forwards submitted\n * values verbatim, so forwarding the stringified rendering would retype the\n * variable (a prefilled `{ approved: true }` textarea would overwrite the object\n * with the STRING '{\"approved\":true}'; a numeric select/radio prefill would\n * overwrite the number with \"1\"). Once the operator changes the control away\n * from `display` the edited string (or its number coercion) submits instead.\n * @param {Record<string, any>} context\n * @param {string} key\n * @returns {{ display: string, original: any } | undefined}\n */\nfunction fjPrefillPair(context, key) {\n const display = fjPrefill(context, key);\n return display === undefined ? undefined : { display, original: context[key] };\n}\n\n/** Build one form-js component into its field element and (for keyed inputs) a reader\n * that returns the entered `{ key, value }` or null when blank. Static (keyless)\n * components render as inert text; layout-only components are skipped (null).\n * `context` carries the task's variables: `text` components interpolate `{{name}}`\n * against it, `image` components resolve a `=varName` source from it, and a keyed\n * input whose key is present is prefilled with its value.\n * @param {any} c\n * @param {Record<string, any>} [context]\n * @param {{ resolveUrl?: (url: string) => string }} [opts]\n * @returns {{ field: any, read?: () => ({ key: string, value: any } | null) } | null}\n */\nfunction buildField(c, context, opts) {\n const ctx = fjOwnContext(context);\n const type = c && c.type;\n // Static (keyless) components: show text as a paragraph, ignore layout-only ones.\n if (type === \"text\") {\n const raw = typeof c.text === \"string\" ? c.text : \"\";\n return { field: fjEl(\"p\", { class: \"njf-text\" }, fjTemplate(raw, ctx)) };\n }\n // An image component (form-js `{ type: \"image\", source, alt }`) — keyless, renders\n // an <img> whose src is resolved + scheme-gated by fjImageSrc. A rejected/absent\n // source renders nothing (null) rather than a broken or unsafe <img>.\n if (type === \"image\") {\n const src = fjImageSrc(c.source, ctx, opts && opts.resolveUrl);\n if (src == null) return null;\n const attrs = { class: \"njf-image\", src, alt: typeof c.alt === \"string\" ? c.alt : \"\" };\n return { field: fjEl(\"img\", attrs) };\n }\n const key = c && c.key;\n if (!key) return null;\n const wrap = fjEl(\"div\", { class: \"njf-field\" });\n const label = typeof c.label === \"string\" && c.label ? c.label : key;\n if (type === \"checkbox\") {\n const input = document.createElement(\"input\");\n input.type = \"checkbox\";\n // Prefill: a boolean context value checks the box.\n if (ctx[key] === true) input.checked = true;\n const lab = fjEl(\"label\", {});\n lab.appendChild(input);\n lab.appendChild(document.createTextNode(\" \" + label));\n wrap.appendChild(lab);\n return { field: wrap, read: () => ({ key, value: input.checked }) };\n }\n const labelEl = fjEl(\"label\", {}, label);\n wrap.appendChild(labelEl);\n let input;\n // Was this field prefilled from the context — AND did the control ACCEPT the\n // value? Only a successful prefill counts: a prefilled field the operator CLEARS\n // (empties the text input, picks the blank select option) must submit an empty\n // string — returning null would omit the key and silently leave the original\n // variable unchanged. But a REJECTED prefill (a select value matching no option,\n // a timezone-bearing timestamp a datetime-local control blanks) leaves the\n // control empty through no operator action; treating that as prefilled would\n // submit \"\" from an untouched form and overwrite the original variable. A\n // rejected prefill behaves like no prefill: blank means \"not entered\", so the\n // key is omitted.\n let prefilled = false;\n /** @type {{ display: string, original: any } | undefined} */\n let prefillPair;\n if (type === \"textarea\") {\n input = document.createElement(\"textarea\");\n prefillPair = fjPrefillPair(ctx, key);\n if (prefillPair !== undefined) {\n input.value = prefillPair.display;\n prefilled = true;\n }\n } else if (type === \"select\") {\n input = document.createElement(\"select\");\n input.appendChild(fjEl(\"option\", { value: \"\" }, \"\\u2014\"));\n prefillPair = fjPrefillPair(ctx, key);\n const pre = prefillPair === undefined ? undefined : prefillPair.display;\n for (const o of Array.isArray(c.values) ? c.values : []) {\n const opt = fjEl(\"option\", { value: String(o.value) }, String(o.label != null ? o.label : o.value));\n // Prefill: mark the option matching the context value as selected.\n if (pre !== undefined && String(o.value) === pre) opt.setAttribute(\"selected\", \"\");\n input.appendChild(opt);\n }\n if (pre !== undefined) {\n input.value = pre;\n // The select ACCEPTS the prefill only when it matches a declared option —\n // otherwise the DOM snaps the value back to \"\" and the control sits blank.\n // Check acceptance structurally (against the option list), not by reading\n // the value back: the control must not be treated as prefilled when it\n // could not take the value, or an untouched submit would overwrite the\n // original variable with \"\".\n const accepted = (Array.isArray(c.values) ? c.values : []).some((/** @type {any} */ o) => String(o.value) === pre);\n prefilled = pre !== \"\" && accepted;\n if (!prefilled) prefillPair = undefined; // a rejected prefill is not a prefill\n }\n } else if (type === \"radio\") {\n const name = \"r\" + Math.random().toString(36).slice(2);\n const prefillRadio = fjPrefillPair(ctx, key);\n const pre = prefillRadio === undefined ? undefined : prefillRadio.display;\n const group = fjEl(\"div\", {});\n for (const o of Array.isArray(c.values) ? c.values : []) {\n const rlab = fjEl(\"label\", {});\n const r = document.createElement(\"input\");\n r.type = \"radio\";\n r.name = name;\n r.value = String(o.value);\n // Prefill: check the option matching the context value.\n if (pre !== undefined && r.value === pre) r.checked = true;\n rlab.appendChild(r);\n rlab.appendChild(document.createTextNode(\" \" + String(o.label != null ? o.label : o.value)));\n group.appendChild(rlab);\n }\n wrap.appendChild(group);\n return {\n field: wrap,\n read: () => {\n const sel = group.querySelector(\"input:checked\");\n if (!sel) return null;\n // Untouched (the checked option is still the prefill's): submit the\n // ORIGINAL value so a numeric prefill stays a number — the completion\n // endpoint forwards submitted values verbatim, and a radio option's\n // value is always a string.\n if (prefillRadio !== undefined && sel.value === prefillRadio.display) return { key, value: prefillRadio.original };\n return { key, value: sel.value };\n },\n };\n } else {\n input = document.createElement(\"input\");\n input.type = type === \"number\" ? \"number\" : type === \"datetime\" ? \"datetime-local\" : \"text\";\n prefillPair = fjPrefillPair(ctx, key);\n if (prefillPair !== undefined) {\n input.value = prefillPair.display;\n // A typed control (number/datetime-local) sanitizes a value it cannot hold\n // to \"\" — e.g. a timezone-bearing timestamp assigned to datetime-local. Only\n // a value that survived counts as a successful prefill.\n prefilled = input.value !== \"\";\n if (!prefilled) prefillPair = undefined; // a rejected prefill is not a prefill\n }\n }\n // Associate the label with the input (for/id) so screen readers announce it on focus.\n const fieldId = \"f\" + Math.random().toString(36).slice(2);\n input.id = fieldId;\n labelEl.setAttribute(\"for\", fieldId);\n wrap.appendChild(input);\n const isNumber = type === \"number\";\n return {\n field: wrap,\n read: () => {\n const raw = input.value;\n // A prefilled field the operator cleared submits an empty string (an explicit\n // \"set this variable to empty\"), never an omission that would leave the\n // original value in place. A never-prefilled blank field is still omitted.\n if (raw === \"\" || raw == null) return prefilled ? { key, value: \"\" } : null;\n // Untouched (the control still shows exactly the prefill's rendering):\n // submit the ORIGINAL context value, never the stringified display — the\n // completion endpoint forwards submitted values verbatim, so the string\n // would retype the variable (an object prefill would become its JSON\n // string; a numeric prefill would become \"3\"). Once the operator changes\n // the control away from the prefill, the edited value submits below.\n if (prefillPair !== undefined && raw === prefillPair.display) return { key, value: prefillPair.original };\n if (isNumber) {\n const n = Number(raw);\n // A non-numeric value in a number field is only reachable via tampering (the browser\n // blanks invalid type=number input). Treat it as absent rather than silently submitting\n // NaN, which JSON.stringify serializes as null — quietly changing the submitted value.\n return Number.isFinite(n) ? { key, value: n } : null;\n }\n return { key, value: raw };\n },\n };\n}\n\n/**\n * Render a form-js schema into a `<form>` element with a submit + optional cancel.\n * On submit it assembles every keyed field's value into one null-prototype\n * `variables` bag and calls `opts.onSubmit(variables)`; a rejected submit re-enables\n * the button so the operator can retry. `opts.onCancel`, when supplied, wires a\n * cancel button. `opts.context` carries the task's variables — `{{name}}` text\n * templating, `=varName` image sources, and keyed-input prefill all resolve\n * against it (see buildField). `opts.resolveUrl`, when supplied, rewrites each\n * ACCEPTED image source before it is set — both surfaces pass their app-mount-aware\n * resolver so a root-relative `/app/…` image survives the console's path-prefixed\n * proxy (see fjImageSrc).\n * @param {any} schema the parsed form-js document (`{ components: [...] }`)\n * @param {{ heading?: string, submitLabel?: string, cancelLabel?: string,\n * context?: Record<string, any>,\n * resolveUrl?: (url: string) => string,\n * onSubmit: (variables: Record<string, any>) => (void | Promise<void>),\n * onCancel?: () => void }} opts\n * @returns {any} the built <form> element\n */\nfunction renderForm(schema, opts) {\n const form = document.createElement(\"form\");\n form.className = \"njf-form\";\n if (opts.heading) form.appendChild(fjEl(\"h2\", { class: \"njf-heading\" }, opts.heading));\n const context = fjOwnContext(opts.context);\n const components = schema && Array.isArray(schema.components) ? schema.components : [];\n /** @type {Array<() => ({ key: string, value: any } | null)>} */\n const inputs = [];\n for (const c of components) {\n const built = buildField(c, context, { resolveUrl: opts.resolveUrl });\n if (!built) continue;\n form.appendChild(built.field);\n if (built.read) inputs.push(built.read);\n }\n const submit = fjBtn(opts.submitLabel || \"Submit\", null);\n submit.type = \"submit\";\n const bar = fjEl(\"div\", { class: \"njf-actions\" });\n bar.appendChild(submit);\n if (opts.onCancel) bar.appendChild(fjBtn(opts.cancelLabel || \"Cancel\", opts.onCancel));\n form.appendChild(bar);\n form.addEventListener(\"submit\", (e) => {\n e.preventDefault();\n // Null-prototype: field keys come from the engine-supplied form schema. A component\n // keyed '__proto__'/'constructor' must land as a plain own property (and round-trip\n // through JSON), never mutate a prototype — no prototype pollution in the page runtime.\n const variables = Object.create(null);\n for (const read of inputs) {\n const kv = read();\n if (kv) variables[kv.key] = kv.value;\n }\n submit.disabled = true;\n Promise.resolve()\n .then(() => opts.onSubmit(variables))\n .catch(() => {\n submit.disabled = false;\n });\n });\n return form;\n}\n\n\n// Expose the renderer as a browser global so both self-contained page bundles can\n// reach the ONE implementation without importing it: the taskInbox page embeds this\n// module inline and the pages shell does the same before loading the ES-module\n// runtime, which reads `globalThis.NanoFormJs` lazily when it renders an engine form.\n// Guarded so importing under Node/Deno for tests is a harmless no-op-ish assignment.\nif (typeof globalThis !== \"undefined\") {\n /** @type {any} */ (globalThis).NanoFormJs = { buildField, renderForm };\n}\n";
|
|
@@ -65,3 +65,50 @@ export async function completeUserTaskResponse(
|
|
|
65
65
|
await engine.completeUserTask(userTaskKey, variables);
|
|
66
66
|
return json({ ok: true });
|
|
67
67
|
}
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* The shared task-variables endpoint (#603). Responds with the variables of one
|
|
71
|
+
* process instance as a plain `{ name: value }` object — the render context both
|
|
72
|
+
* form surfaces (taskInbox, pages `dataGrid` engine-form detail) pass to the
|
|
73
|
+
* shared form-js renderer for `{{name}}` text templating, `=varName` image
|
|
74
|
+
* sources, and keyed-input prefill. Sourced from `EngineClient.searchVariables`
|
|
75
|
+
* (the engine's user-task/process variables search), so the two surfaces can
|
|
76
|
+
* never drift on where the context comes from.
|
|
77
|
+
*
|
|
78
|
+
* Each `VariableSummary.value` is the variable's serialized JSON (a string); it
|
|
79
|
+
* is `JSON.parse`d here so the client receives real values (numbers, objects),
|
|
80
|
+
* not double-encoded strings. A value that fails to parse is passed through as
|
|
81
|
+
* the raw string rather than failing the whole read. Only PROCESS-level variables
|
|
82
|
+
* (`scopeKey === processInstanceKey`) are included — task-local variables of other
|
|
83
|
+
* element instances never leak into the context — and truncated previews
|
|
84
|
+
* (`isTruncated`) are omitted so they can never be prefilled and resubmitted over
|
|
85
|
+
* the full value. A missing/blank
|
|
86
|
+
* `processInstanceKey` 400s — without it there is no well-defined scope to read.
|
|
87
|
+
*/
|
|
88
|
+
export async function taskVariablesResponse(
|
|
89
|
+
engine: Pick<EngineClient, "searchVariables">,
|
|
90
|
+
processInstanceKey: string | undefined,
|
|
91
|
+
): Promise<HttpResponse> {
|
|
92
|
+
const key = processInstanceKey?.trim();
|
|
93
|
+
if (!key) return json({ error: "processInstanceKey required" }, 400);
|
|
94
|
+
const rows = await engine.searchVariables({ processInstanceKey: key });
|
|
95
|
+
// A null-prototype bag: a variable named `__proto__` (or `constructor`) is stored
|
|
96
|
+
// as an own data property instead of invoking an inherited setter, so every
|
|
97
|
+
// variable name round-trips through `json()` as data.
|
|
98
|
+
const variables: Record<string, unknown> = Object.create(null);
|
|
99
|
+
for (const row of rows) {
|
|
100
|
+
// Process-level scope only: a row whose scopeKey is an element instance is a
|
|
101
|
+
// task-LOCAL variable of some (possibly sibling) task. Flattening those by name
|
|
102
|
+
// would let another task's value win, so they are excluded outright.
|
|
103
|
+
if (row.scopeKey !== key) continue;
|
|
104
|
+
// A truncated row's `value` is a preview, not the variable. Prefilling it would
|
|
105
|
+
// let an untouched form submit clipped text over the original — omit it.
|
|
106
|
+
if (row.isTruncated) continue;
|
|
107
|
+
try {
|
|
108
|
+
variables[row.name] = JSON.parse(row.value);
|
|
109
|
+
} catch {
|
|
110
|
+
variables[row.name] = row.value;
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
return json(variables);
|
|
114
|
+
}
|
|
@@ -2043,6 +2043,27 @@ test("GET /app/actions/form 204s when the form can't be resolved (client falls b
|
|
|
2043
2043
|
assert.equal(res.body ?? "", "");
|
|
2044
2044
|
});
|
|
2045
2045
|
|
|
2046
|
+
test("GET /app/actions/variables returns the row's task variables as the render context (#603)", async () => {
|
|
2047
|
+
const { engine } = fakeEngine();
|
|
2048
|
+
let seenFilter: unknown;
|
|
2049
|
+
const withVars: EngineClient = {
|
|
2050
|
+
...engine,
|
|
2051
|
+
async searchVariables(filter) {
|
|
2052
|
+
seenFilter = filter;
|
|
2053
|
+
return [
|
|
2054
|
+
{ variableKey: "v1", name: "title", value: JSON.stringify("Draft v2"), scopeKey: "pi-9", processInstanceKey: "pi-9", isTruncated: false },
|
|
2055
|
+
{ variableKey: "v2", name: "img1", value: JSON.stringify("https://cdn.example.com/t1.png"), scopeKey: "pi-9", processInstanceKey: "pi-9", isTruncated: false },
|
|
2056
|
+
];
|
|
2057
|
+
},
|
|
2058
|
+
};
|
|
2059
|
+
const res = await formRouter(withVars)(req("GET", "/app/actions/variables", { query: "processInstanceKey=pi-9" }));
|
|
2060
|
+
assert.equal(res.status, 200);
|
|
2061
|
+
assert.deepEqual(seenFilter, { processInstanceKey: "pi-9" });
|
|
2062
|
+
assert.deepEqual(JSON.parse(res.body ?? "{}"), { title: "Draft v2", img1: "https://cdn.example.com/t1.png" });
|
|
2063
|
+
const missing = await formRouter(withVars)(req("GET", "/app/actions/variables"));
|
|
2064
|
+
assert.equal(missing.status, 400, "a missing processInstanceKey 400s");
|
|
2065
|
+
});
|
|
2066
|
+
|
|
2046
2067
|
test("POST /app/actions/complete completes the row's user task with the submitted variables", async () => {
|
|
2047
2068
|
const { engine, completeCalls } = formEngine();
|
|
2048
2069
|
const res = await formRouter(engine)(
|
|
@@ -32,7 +32,7 @@ import { html, json, type Route } from "../router.ts";
|
|
|
32
32
|
import { cancelInstanceReconciling, type CancelInstanceResult } from "./cancel.ts";
|
|
33
33
|
import { apiDocsPath } from "./api.ts";
|
|
34
34
|
import { FORMJS_JS } from "./formjs.gen.ts";
|
|
35
|
-
import { completeUserTaskResponse, resolveFormResponse } from "./forms.ts";
|
|
35
|
+
import { completeUserTaskResponse, resolveFormResponse, taskVariablesResponse } from "./forms.ts";
|
|
36
36
|
import { quoteIdent } from "./gateway.ts";
|
|
37
37
|
import { RENDERER_JS } from "./runtime.gen.ts";
|
|
38
38
|
import { isSqlIdentifier } from "../read-model.ts";
|
|
@@ -627,6 +627,17 @@ export function createPagesRoutes(opts: PagesOptions, deps: PagesDeps): Route[]
|
|
|
627
627
|
source: "surface:pages",
|
|
628
628
|
handler: async (req) => completeUserTaskResponse(engine, await req.text()),
|
|
629
629
|
});
|
|
630
|
+
// The selected row's task variables (#603) — the render context the engineForm
|
|
631
|
+
// drawer passes to the shared form-js renderer (text `{{name}}` templating,
|
|
632
|
+
// `=varName` image sources, keyed-input prefill). The SAME seam the taskInbox
|
|
633
|
+
// surface uses, reused via forms.ts so the context source can't drift.
|
|
634
|
+
routes.push({
|
|
635
|
+
method: "GET",
|
|
636
|
+
path: "/app/actions/variables",
|
|
637
|
+
source: "surface:pages",
|
|
638
|
+
handler: async (req) =>
|
|
639
|
+
taskVariablesResponse(engine, req.query.get("processInstanceKey") ?? undefined),
|
|
640
|
+
});
|
|
630
641
|
|
|
631
642
|
// ── nested (multi-appView) sidecars (#442) ──────────────────────────────
|
|
632
643
|
// An app with more than one `appView` cannot share the four FLAT sidecar names above:
|
|
@@ -910,6 +921,7 @@ body { margin:0; font:15px/1.5 system-ui,sans-serif; padding:2rem; max-width:64r
|
|
|
910
921
|
.njf-form { display:flex; flex-direction:column; gap:.4rem; margin-top:.5rem; }
|
|
911
922
|
.njf-heading { font-size:1rem; margin:0 0 .25rem; }
|
|
912
923
|
.njf-text { color:var(--nano-text-muted); margin:.25rem 0; }
|
|
924
|
+
.njf-image { display:block; max-width:100%; height:auto; margin:.4rem 0; }
|
|
913
925
|
.njf-field { display:flex; flex-direction:column; gap:.25rem; }
|
|
914
926
|
.njf-field label { font-size:.8rem; color:var(--nano-text-muted); }
|
|
915
927
|
.njf-field input:not([type=checkbox]):not([type=radio]), .njf-field textarea, .njf-field select { padding:.5rem .6rem; border:1px solid var(--nano-edge); border-radius:.4rem; font:inherit; background:var(--nano-inset); color:var(--nano-text); max-width:24rem; }
|