console: seal a form submit as one frozen transaction
Astra round 1 on Task 6. The script snapshots values before the first await and seals exactly those, freezes the form (inert) while sealing, cancels if anything changed, refuses to submit while any selected secret still has named plaintext, and defers every resubmit until the original submit event has finished, so Remove and Discard post on the first click. Tests: delayed-crypto fake-DOM regressions and a headless Chromium run.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
internal/console/configseal.js+96 −42internal/console/configseal_test.go+118 −0internal/console/testdata/configseal_browser.mjs+76 −0internal/console/testdata/configseal_run.mjs+92 −16
Intent
<task-notification> <task-id>addaddeb7f77aa259</task-id> <tool-use-id>toolu_016Fj9anprGxXhHfwknT7M1r</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/abe35d56-e4c2-40df-9005-6e66b76b1f50/tasks/addaddeb7f77aa259.output</output-file> <status>completed</status> <summary>Agent "Implement Task 4 shared validation" finished</summary> <note>A task-notification fires each time this agent stops with no live background children of its own. The user can send it another message and resume it, so the same task-id may notify more than once.</note> <result>Status: DONE. Task 4 is built and committed. The JSON door's answers (status and body) are unchanged, and the guard tests pass before and after. Commits: e5c8cdab `console: one config write check for every door`. It includes `apiconfig.go`, `configwrite.go`, `configwrite_test.go` and `teamcreds_test.go`. Tests: the guard set passed before (44s) and after (148s, with the new `TestCheckConfigSetsCodes`, `TestCheckConfigSetsBuildsFieldByField` and `TestWriteConfigNeverEchoesContent`). One mutation check failed as it should. gofmt and vet are clean. Concerns: - I edited one test outside the brief's files. `TestApplyCallersAreTheKnownWalks` failed once the store writes moved into `configwrite.go`. I added that file to its pinned list, and the check now also watches `ApplyAtVersion` so a new writer can't get past the pin through it. - `TestCheckConfigSetsCodes` compares the door with the shared function, but both now come from the same code, so it mostly checks how refusals are rendered. The tests that check the exact wording are the existing ones (`TestAPIConfigPutRefusals`, `TestConfigPut*`), and they passed unchanged. - One small change: when a store write fails, the account lock is now released just before the error response is written instead of just after. Nobody can see the difference. - I didn't touch or commit the other sessions' uncommitted configseal files. Report: `/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-console-secrets/.superpowers/sdd/2026-11-08-console-secrets/task-4-report.md`</result> <usage><subagent_tokens>129265</subagent_tokens><tool_uses>33</tool_uses><duration_ms>954597</duration_ms></usage> </task-notification>
Attributed to this commit: 28.0 g CO₂e (3,455,941 tokens). This is an attribution, not a measurement — usage counted from this commit's own marker forward to the next one on design-console-secrets, never backward from it. A turn that produced more than one commit books all of its tokens to the last one, and a concurrent session on this branch can add to the same figure. Some of it was priced using the shared default rate, because no model-specific factor row exists yet for at least one model involved. The Carbon view has the repo total, which is never derived from this attribution.
diff --git a/internal/console/configseal.js b/internal/console/configseal.js| index e2ed70ab9..cc2b53b15 100644 |
| --- a/internal/console/configseal.js |
| +++ b/internal/console/configseal.js |
| @@ -19,7 +19,8 @@ |
| var MSG = { |
| chars: "A value can't contain a backslash, a quote, a newline or a NUL character.", |
| empty: "A secret can't be empty.", |
| - seal: "Your browser couldn't seal this value, so nothing was sent." |
| + seal: "Your browser couldn't seal this value, so nothing was sent.", |
| + changed: "The form changed while sealing, so nothing was sent. Check it and save again." |
| }; |
| // The same rule as appconfig.ValidVarValue, plus the empty-secret rule |
| @@ -106,10 +107,11 @@ |
| if (typeof document === "undefined") return; |
| - // The page may word the refusals itself (data-msg-chars, -empty, -seal on |
| - // the form); these defaults stand in otherwise. |
| + // The page may word the refusals itself (data-msg-chars, -empty, -seal, |
| + // -changed on the form); these defaults stand in otherwise. |
| function say(form, kind) { |
| - var d = form.dataset, own = {chars: d.msgChars, empty: d.msgEmpty, seal: d.msgSeal}[kind]; |
| + var d = form.dataset; |
| + var own = {chars: d.msgChars, empty: d.msgEmpty, seal: d.msgSeal, changed: d.msgChanged}[kind]; |
| return own || MSG[kind]; |
| } |
| @@ -141,76 +143,128 @@ |
| return out; |
| } |
| + // Whether any control the page marks secret would post plaintext now. |
| + function plaintextLeft(form) { |
| + return secretInputs(form).some(function (t) { return t.input.value !== ""; }); |
| + } |
| + |
| + // Every control's state, to prove nothing moved while sealing. The |
| + // envelope fields are ours to write, so they are left out. |
| + function snapshot(form) { |
| + var out = []; |
| + Array.prototype.forEach.call(form.elements, function (el) { |
| + if (el.hasAttribute && el.hasAttribute("data-envelope-for")) return; |
| + out.push([el, el.name, el.value, !!el.checked, !!el.disabled]); |
| + }); |
| + return out; |
| + } |
| + |
| + function unchanged(form, snap) { |
| + var now = snapshot(form); |
| + if (now.length !== snap.length) return false; |
| + for (var i = 0; i < snap.length; i++) { |
| + for (var k = 0; k < 5; k++) if (now[i][k] !== snap[i][k]) return false; |
| + } |
| + return true; |
| + } |
| + |
| // Never let plaintext travel: blank it and drop its name. |
| function strip(input) { |
| input.value = ""; |
| input.removeAttribute("name"); |
| } |
| - // The submit event this fires runs synchronously, so the pass-through |
| - // flag never outlives it (not even when constraint validation stops it). |
| - function resubmit(form, submitter) { |
| - if (form.requestSubmit) { |
| - form.dataset.sealed = "1"; |
| - try { |
| - form.requestSubmit(submitter && submitter.form === form ? submitter : undefined); |
| - } finally { |
| - delete form.dataset.sealed; |
| + // Edits are frozen while a submit seals: the form is inert, so a click or |
| + // keystroke cannot change what was validated. The snapshot check catches |
| + // anything that gets through anyway (a script, a browser without inert). |
| + function freeze(form) { form.dataset.sealBusy = "1"; form.inert = true; } |
| + function thaw(form) { delete form.dataset.sealBusy; form.inert = false; } |
| + |
| + function refuse(form, targets, kind) { |
| + targets.forEach(function (t) { show(form, t.input, say(form, kind)); }); |
| + } |
| + |
| + // Submits again once the cancelled submit event has finished dispatching: |
| + // a browser ignores requestSubmit while that form's submit event is still |
| + // firing. The pass-through flag lives only for the synchronous dispatch |
| + // requestSubmit starts. |
| + function resubmit(form, submitter, targets) { |
| + setTimeout(function () { |
| + thaw(form); |
| + if (plaintextLeft(form)) { refuse(form, targets, "changed"); return; } |
| + if (form.requestSubmit) { |
| + form.dataset.sealed = "1"; |
| + try { |
| + form.requestSubmit(submitter && submitter.form === form ? submitter : undefined); |
| + } finally { |
| + delete form.dataset.sealed; |
| + } |
| + return; |
| } |
| - return; |
| - } |
| - if (submitter && submitter.name) { |
| - var h = document.createElement("input"); |
| - h.type = "hidden"; h.name = submitter.name; h.value = submitter.value; |
| - form.appendChild(h); |
| - } |
| - form.submit(); |
| + if (submitter && submitter.name) { |
| + var h = document.createElement("input"); |
| + h.type = "hidden"; h.name = submitter.name; h.value = submitter.value; |
| + form.appendChild(h); |
| + } |
| + form.submit(); |
| + }, 0); |
| } |
| async function onSubmit(form, ev) { |
| - if (form.dataset.sealed === "1") return; |
| + if (form.dataset.sealed === "1") { |
| + // Our own resubmit: let it through only if no plaintext would go. |
| + if (plaintextLeft(form)) ev.preventDefault(); |
| + return; |
| + } |
| + if (form.dataset.sealBusy === "1") { ev.preventDefault(); return; } |
| var targets = secretInputs(form); |
| if (!targets.length) return; |
| ev.preventDefault(); |
| - if (form.dataset.sealBusy === "1") return; |
| var submitter = ev.submitter; |
| + freeze(form); |
| // A control that saves nothing (Remove, Discard) marks itself |
| // data-seal-skip: no check, and the plaintext stays behind. |
| if (submitter && submitter.hasAttribute("data-seal-skip")) { |
| targets.forEach(function (t) { strip(t.input); }); |
| - resubmit(form, submitter); |
| + resubmit(form, submitter, targets); |
| return; |
| } |
| + // One transaction: these values are what is validated and what is |
| + // sealed, and the form must still match this snapshot at the end. |
| + var snap = snapshot(form); |
| + var values = targets.map(function (t) { return t.input.value; }); |
| var bad = false; |
| - targets.forEach(function (t) { |
| - var v = t.input.value, msg = null; |
| + targets.forEach(function (t, i) { |
| + var v = values[i], msg = null; |
| if (v === "" && t.required) msg = say(form, "empty"); |
| - else if (v !== "") { msg = validValue(v, true); if (msg) msg = say(form, "chars"); } |
| + else if (v !== "" && validValue(v, true)) msg = say(form, "chars"); |
| show(form, t.input, msg || ""); |
| if (msg) bad = true; |
| }); |
| - if (bad) return; |
| - form.dataset.sealBusy = "1"; |
| + if (bad) { thaw(form); return; } |
| + var envelopes = []; |
| try { |
| - var d = form.dataset, envelopes = []; |
| + var d = form.dataset; |
| for (var i = 0; i < targets.length; i++) { |
| - var input = targets[i].input; |
| - if (input.value === "") continue; |
| - envelopes.push([input, await seal(d.sealPub, d.sealVersion, d.account, d.app, input.value)]); |
| - } |
| - for (var j = 0; j < envelopes.length; j++) { |
| - var hidden = form.querySelector('[data-envelope-for="' + envelopes[j][0].id + '"]'); |
| - if (!hidden) throw new Error("no envelope field for " + envelopes[j][0].id); |
| - hidden.value = envelopes[j][1]; |
| + if (values[i] === "") continue; |
| + var hidden = form.querySelector('[data-envelope-for="' + targets[i].input.id + '"]'); |
| + if (!hidden) throw new Error("no envelope field for " + targets[i].input.id); |
| + envelopes.push([hidden, await seal(d.sealPub, d.sealVersion, d.account, d.app, values[i])]); |
| } |
| } catch (e) { |
| - targets.forEach(function (t) { show(form, t.input, say(form, "seal")); }); |
| + thaw(form); |
| + refuse(form, targets, "seal"); |
| + return; |
| + } |
| + if (!unchanged(form, snap)) { |
| + thaw(form); |
| + refuse(form, targets, "changed"); |
| return; |
| - } finally { |
| - delete form.dataset.sealBusy; |
| } |
| + envelopes.forEach(function (e) { e[0].value = e[1]; }); |
| targets.forEach(function (t) { strip(t.input); }); |
| - resubmit(form, submitter); |
| + if (plaintextLeft(form)) { thaw(form); refuse(form, targets, "changed"); return; } |
| + resubmit(form, submitter, targets); |
| } |
| function wire(form) { |
diff --git a/internal/console/configseal_test.go b/internal/console/configseal_test.go| index 178107599..6a7d83e9a 100644 |
| --- a/internal/console/configseal_test.go |
| +++ b/internal/console/configseal_test.go |
| @@ -2,13 +2,20 @@ package console |
| import ( |
| "bytes" |
| + "context" |
| "encoding/base64" |
| "encoding/json" |
| "flag" |
| + "html/template" |
| + "net/http" |
| + "net/http/httptest" |
| + "net/url" |
| "os" |
| "os/exec" |
| "strings" |
| + "sync" |
| "testing" |
| + "time" |
| "unicode/utf8" |
| "github.com/carlosframework/platform/internal/appconfig" |
| @@ -340,3 +347,114 @@ func TestConfigSealScriptEmbeds(t *testing.T) { |
| } |
| } |
| } |
| + |
| +// TestConfigSealChromium runs the embedded script in a real browser, where |
| +// requestSubmit is suppressed while a submit event is still firing: a |
| +// first-click Remove or Discard and a normal save each post exactly once, and |
| +// a save posts envelopes and no plaintext. |
| +func TestConfigSealChromium(t *testing.T) { |
| + chromium, err := exec.LookPath("chromium") |
| + if err != nil { |
| + t.Skip("no installed headless browser") |
| + } |
| + node := nodeOrSkip(t) |
| + priv, pub, err := appconfig.GenerateKey() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + page := `<!doctype html><meta charset="utf-8"><title>seal</title> |
| +<form method="post" action="/post?s={{.Scene}}" data-seal-pub="` + pub + `" data-seal-version="2" data-account="bab" data-app="shop"> |
| +<input id="r1" name="set.default.API_KEY" data-secret-input disabled> |
| +<span data-seal-error="r1" hidden></span> |
| +<input type="hidden" data-envelope-for="r1" name="envelope.default.API_KEY"> |
| +<input id="an" name="add.default.name"><input id="av" name="add.default.value"> |
| +<input type="checkbox" id="as" name="add.default.secret" value="1" data-secret-toggle data-secret-for="av" data-name-from="an" disabled> |
| +<input type="hidden" data-envelope-for="av" name="add.default.envelope"> |
| +<span data-seal-error="av" hidden></span> |
| +<button name="op" value="save">Save</button> |
| +<button name="op" value="remove" data-seal-skip>Remove</button> |
| +<button name="op" value="discard" data-seal-skip>Discard</button> |
| +</form> |
| +<script>{{.Script}}</script>` |
| + tmpl := template.Must(template.New("p").Parse(page)) |
| + |
| + var mu sync.Mutex |
| + posts := map[string][]url.Values{} |
| + mux := http.NewServeMux() |
| + mux.HandleFunc("GET /page", func(w http.ResponseWriter, r *http.Request) { |
| + w.Header().Set("Content-Type", "text/html; charset=utf-8") |
| + if err := tmpl.Execute(w, map[string]any{"Scene": r.URL.Query().Get("s"), "Script": configSealJS}); err != nil { |
| + t.Error(err) |
| + } |
| + }) |
| + mux.HandleFunc("POST /post", func(w http.ResponseWriter, r *http.Request) { |
| + if err := r.ParseForm(); err != nil { |
| + t.Error(err) |
| + } |
| + mu.Lock() |
| + posts[r.URL.Query().Get("s")] = append(posts[r.URL.Query().Get("s")], r.PostForm) |
| + mu.Unlock() |
| + http.Redirect(w, r, "/posted", http.StatusSeeOther) |
| + }) |
| + mux.HandleFunc("GET /posted", func(w http.ResponseWriter, r *http.Request) { _, _ = w.Write([]byte("posted")) }) |
| + ts := httptest.NewServer(mux) // 127.0.0.1 |
| + defer ts.Close() |
| + |
| + const secret, added = "s3cret-value", "postgres://user:pw@db/x" |
| + fill := map[string]string{"r1": secret, "an": "DB_URL", "av": added} |
| + type scene struct { |
| + URL string `json:"url"` |
| + Fill map[string]string `json:"fill"` |
| + Tick []string `json:"tick"` |
| + Click string `json:"click"` |
| + } |
| + scenes := []scene{ |
| + {ts.URL + "/page?s=remove", fill, []string{"as"}, "remove"}, |
| + {ts.URL + "/page?s=discard", fill, nil, "discard"}, |
| + {ts.URL + "/page?s=save", fill, []string{"as"}, "save"}, |
| + } |
| + payload, _ := json.Marshal(scenes) |
| + ctx, cancel := context.WithTimeout(t.Context(), 90*time.Second) |
| + defer cancel() |
| + cmd := exec.CommandContext(ctx, node, "testdata/configseal_browser.mjs", chromium, t.TempDir(), string(payload)) |
| + if out, err := cmd.CombinedOutput(); err != nil { |
| + t.Fatalf("browser: %v\n%s", err, out) |
| + } |
| + |
| + mu.Lock() |
| + defer mu.Unlock() |
| + for _, s := range []string{"remove", "discard", "save"} { |
| + got := posts[s] |
| + if len(got) != 1 { |
| + t.Fatalf("%s: %d posts, want exactly 1: %v", s, len(got), got) |
| + } |
| + f := got[0] |
| + if f.Get("op") != s { |
| + t.Errorf("%s: op = %q", s, f.Get("op")) |
| + } |
| + for k, vs := range f { |
| + for _, v := range vs { |
| + if strings.Contains(v, secret) || (s == "save" && strings.Contains(v, added)) { |
| + t.Errorf("%s: field %s carries plaintext", s, k) |
| + } |
| + } |
| + } |
| + if _, ok := f["set.default.API_KEY"]; ok { |
| + t.Errorf("%s: the plaintext field was posted", s) |
| + } |
| + } |
| + save := posts["save"][0] |
| + if _, ok := save["add.default.value"]; ok { |
| + t.Error("save: the add row's plaintext field was posted") |
| + } |
| + if save.Get("add.default.secret") != "1" { |
| + t.Errorf("save: Secret box = %q, want 1", save.Get("add.default.secret")) |
| + } |
| + for _, k := range []string{"envelope.default.API_KEY", "add.default.envelope"} { |
| + want := secret |
| + if k == "add.default.envelope" { |
| + want = added |
| + } |
| + checkBrowserEnvelope(t, priv, sealVector{Version: "2", Account: "bab", App: "shop", Plaintext: want, Envelope: save.Get(k)}) |
| + } |
| +} |
diff --git a/internal/console/testdata/configseal_browser.mjs b/internal/console/testdata/configseal_browser.mjs| new file mode 100644 |
| index 000000000..774a75ad5 |
| --- /dev/null |
| +++ b/internal/console/testdata/configseal_browser.mjs |
| @@ -0,0 +1,76 @@ |
| +// Drives headless Chromium over CDP against configseal_test.go's local |
| +// server: for each scene it loads the page, fills the fields, clicks one |
| +// button and waits for the post to land. The Go side counts the posts. |
| +// |
| +// node configseal_browser.mjs <chromium> <profile dir> <scenes JSON> |
| +// scene: {url, fill: {id: value}, tick: [id], click: <button value>} |
| +import {spawn} from 'node:child_process'; |
| +import assert from 'node:assert/strict'; |
| + |
| +const [binary, profile, scenesJSON] = process.argv.slice(2); |
| +const chrome = spawn(binary, ['--headless', '--no-sandbox', '--disable-gpu', |
| + '--disable-dev-shm-usage', '--disable-background-networking', '--disable-component-update', |
| + '--disable-default-apps', '--disable-extensions', '--disable-sync', '--no-proxy-server', |
| + '--no-first-run', '--no-default-browser-check', '--remote-debugging-pipe', |
| + '--user-data-dir=' + profile], {stdio: ['ignore', 'ignore', 'ignore', 'pipe', 'pipe']}); |
| +let sequence = 0, buffered = '', session; |
| +const pending = new Map(); |
| +chrome.stdio[4].on('data', bytes => { |
| + buffered += bytes.toString(); |
| + let end; |
| + while ((end = buffered.indexOf('\0')) !== -1) { |
| + const message = JSON.parse(buffered.slice(0, end)); |
| + buffered = buffered.slice(end + 1); |
| + const resolve = pending.get(message.id); |
| + if (resolve) { pending.delete(message.id); resolve(message); } |
| + } |
| +}); |
| +async function call(method, params = {}, attached = true) { |
| + const id = ++sequence; |
| + const result = new Promise(resolve => pending.set(id, resolve)); |
| + chrome.stdio[3].write(JSON.stringify({id, method, params, ...(attached && session ? {sessionId: session} : {})}) + '\0'); |
| + const message = await result; |
| + assert.equal(message.error, undefined, JSON.stringify(message.error)); |
| + return message.result; |
| +} |
| +async function evaluate(expression) { |
| + const result = await call('Runtime.evaluate', {expression, returnByValue: true, awaitPromise: true}); |
| + assert.equal(result.exceptionDetails, undefined, JSON.stringify(result.exceptionDetails)); |
| + return result.result.value; |
| +} |
| +async function until(expression) { |
| + for (let i = 0; i < 100; i++) { |
| + try { if (await evaluate(expression)) return; } catch {} |
| + await new Promise(r => setTimeout(r, 50)); |
| + } |
| + throw Error('browser_condition_timeout: ' + expression); |
| +} |
| + |
| +const timer = setTimeout(() => { chrome.kill('SIGKILL'); process.exitCode = 1; }, 60000); |
| +try { |
| + const created = await call('Target.createTarget', {url: 'about:blank'}, false); |
| + session = (await call('Target.attachToTarget', {targetId: created.targetId, flatten: true}, false)).sessionId; |
| + await call('Page.enable'); |
| + for (const scene of JSON.parse(scenesJSON)) { |
| + await call('Page.navigate', {url: scene.url}); |
| + await until('document.readyState === "complete" && !!document.querySelector("form[data-seal-pub]")'); |
| + assert.equal(await evaluate('[...document.querySelectorAll("[data-secret-input],[data-secret-toggle]")].every(e => !e.disabled)'), true); |
| + assert.equal(await evaluate('window.isSecureContext && !!crypto.subtle'), true); |
| + await evaluate(`(() => { |
| + const fill = ${JSON.stringify(scene.fill || {})}, tick = ${JSON.stringify(scene.tick || [])}; |
| + for (const [id, v] of Object.entries(fill)) document.getElementById(id).value = v; |
| + for (const id of tick) document.getElementById(id).checked = true; |
| + document.querySelector('button[value="${scene.click}"]').click(); |
| + })()`); |
| + await until('location.pathname === "/posted"'); |
| + // Leave time for a stray second submit to show up on the Go side. |
| + await new Promise(r => setTimeout(r, 300)); |
| + } |
| +} finally { |
| + clearTimeout(timer); |
| + // SIGTERM and wait, so Chromium is done with the profile before the Go |
| + // test removes it. |
| + const closed = new Promise(resolve => chrome.exitCode !== null ? resolve() : chrome.once('exit', resolve)); |
| + chrome.kill('SIGTERM'); |
| + await closed; |
| +} |
diff --git a/internal/console/testdata/configseal_run.mjs b/internal/console/testdata/configseal_run.mjs| index cac3ee1b5..47bfa4db4 100644 |
| --- a/internal/console/testdata/configseal_run.mjs |
| +++ b/internal/console/testdata/configseal_run.mjs |
| @@ -48,8 +48,22 @@ if (mode === 'predicate' || mode === 'seal') { |
| // A minimal fake DOM: one form with an always-secret input, an add row whose |
| // Secret box names its value input, and their envelope fields. |
| -function fakePage({secretValue = 's3cret', addName = '', addValue = '', addTicked = false, version = '1'} = {}) { |
| +// Its form models the browser's rule that requestSubmit does nothing while |
| +// that form's submit event is still being dispatched. gated holds the first |
| +// AES-GCM encrypt until release() is called, to edit the form mid-seal. |
| +function fakePage({secretValue = 's3cret', addName = '', addValue = '', addTicked = false, version = '1', gated = false} = {}) { |
| const pub = process.env.SEAL_PUB; |
| + const gate = {calls: 0, release: null}; |
| + const subtle = new Proxy(globalThis.crypto.subtle, {get(t, k) { |
| + const v = t[k]; |
| + if (typeof v !== 'function') return v; |
| + if (k !== 'encrypt' || !gated) return v.bind(t); |
| + return async (...a) => { |
| + if (++gate.calls === 1) await new Promise(r => { gate.release = r; }); |
| + return v.apply(t, a); |
| + }; |
| + }}); |
| + const cryptoFor = {subtle, getRandomValues: a => globalThis.crypto.getRandomValues(a)}; |
| function el(attrs, extra = {}) { |
| const listeners = {}; |
| const e = { |
| @@ -80,15 +94,27 @@ function fakePage({secretValue = 's3cret', addName = '', addValue = '', addTicke |
| return m[1] in e.attrs && (m[2] === undefined || e.attrs[m[1]] === m[2]); |
| }; |
| const submits = []; |
| + let firing = false; |
| + function dispatch(s) { |
| + const ev = {submitter: s, prevented: false, preventDefault() { this.prevented = true; }}; |
| + if (firing) return ev; // native: no nested submit while one is firing |
| + firing = true; |
| + try { form.fire('submit', ev); } finally { firing = false; } |
| + if (!ev.prevented) { |
| + const fields = Object.fromEntries(controls.filter(e => e.name).map(e => [e.name, e.checked ?? e.value])); |
| + if (s && s.name) fields[s.name] = s.value; |
| + submits.push(fields); |
| + } |
| + return ev; |
| + } |
| + const controls = all.filter(e => !e.hasAttribute('data-seal-error')); |
| const form = el({}, { |
| + inert: false, |
| + get elements() { return controls; }, |
| dataset: version === '2' ? {sealPub: pub, sealVersion: '2', account: 'bab', app: 'shop'} : {sealPub: pub, sealVersion: '1'}, |
| querySelectorAll(q) { return q.split(/,\s*/).flatMap(p => all.filter(e => sel(p, e))); }, |
| querySelector(q) { return this.querySelectorAll(q)[0] || null; }, |
| - requestSubmit(s) { |
| - const ev = {submitter: s, prevented: false, preventDefault() { this.prevented = true; }}; |
| - form.fire('submit', ev); |
| - if (!ev.prevented) submits.push(Object.fromEntries(all.filter(e => e.name && !e.hasAttribute('data-seal-error')).map(e => [e.name, e.checked ?? e.value]))); |
| - }, |
| + requestSubmit(s) { dispatch(s); }, |
| }); |
| for (const e of all) e.form = form; |
| const document = { |
| @@ -97,17 +123,26 @@ function fakePage({secretValue = 's3cret', addName = '', addValue = '', addTicke |
| querySelectorAll(q) { return q.startsWith('form') ? [form] : form.querySelectorAll(q); }, |
| addEventListener() {}, |
| }; |
| - const ctx = vm.createContext({document, TextEncoder, atob, btoa, crypto: globalThis.crypto, console}); |
| + const ctx = vm.createContext({document, TextEncoder, atob, btoa, crypto: cryptoFor, setTimeout, console}); |
| ctx.globalThis = ctx; |
| vm.runInContext(source, ctx); |
| - const save = el({name: 'op', value: 'save'}, {form}); |
| - return {form, secret, secretEnv, secretErr, addValueEl, addNameEl, addEnv, addErr, toggle, submits, save, |
| - async submit(submitter = save) { |
| - const ev = {submitter, prevented: false, preventDefault() { this.prevented = true; }}; |
| - form.fire('submit', ev); |
| - for (let i = 0; i < 50 && !submits.length; i++) await new Promise(r => setTimeout(r, 10)); |
| + const save = el({name: 'op'}, {form, value: 'save'}); |
| + const button = (value, attrs = {}) => el({name: 'op', ...attrs}, {form, value}); |
| + return {form, secret, secretEnv, secretErr, addValueEl, addNameEl, addEnv, addErr, toggle, submits, save, button, gate, |
| + // Like a click: fires submit, then waits for the script's deferred resubmit. |
| + async submit(submitter = save, wait = true) { |
| + const ev = dispatch(submitter); |
| + if (wait) await settle(); |
| return ev; |
| + }, |
| + async whenHeld() { |
| + for (let i = 0; i < 200 && !gate.release; i++) await new Promise(r => setTimeout(r, 5)); |
| + assert(gate.release, 'encrypt never started'); |
| }}; |
| + async function settle() { |
| + for (let i = 0; i < 50 && !submits.length; i++) await new Promise(r => setTimeout(r, 10)); |
| + await new Promise(r => setTimeout(r, 20)); |
| + } |
| } |
| async function domChecks() { |
| @@ -120,7 +155,7 @@ async function domChecks() { |
| assert.equal(p.submits.length, 1); |
| const posted = JSON.stringify(p.submits[0]); |
| assert(!posted.includes('s3cret') && !posted.includes('postgres://x'), posted); |
| - assert.equal(p.submits[0].op, undefined); // op rides on the submitter, not a field |
| + assert.equal(p.submits[0].op, 'save'); |
| assert(p.secretEnv.value.length > 100 && p.addEnv.value.length > 100); |
| assert.equal(p.secret.value, ''); |
| assert.equal(p.secret.hasAttribute('name'), false); |
| @@ -148,9 +183,9 @@ async function domChecks() { |
| // A skip control strips the plaintext and submits without sealing. |
| p = fakePage(); |
| - const remove = {name: 'op', value: 'remove', form: p.form, hasAttribute: a => a === 'data-seal-skip'}; |
| - await p.submit(remove); |
| + await p.submit(p.button('remove', {'data-seal-skip': ''})); |
| assert.equal(p.submits.length, 1); |
| + assert.equal(p.submits[0].op, 'remove'); |
| assert(!JSON.stringify(p.submits[0]).includes('s3cret')); |
| assert.equal(p.secretEnv.value, ''); |
| @@ -165,6 +200,47 @@ async function domChecks() { |
| p.addValueEl.fire('input'); |
| assert.equal(p.toggle.checked, false); |
| + // A second click while sealing joins nothing: exactly one post. |
| + p = fakePage({gated: true}); |
| + await p.submit(p.save, false); |
| + await p.whenHeld(); |
| + assert.equal((await p.submit(p.save, false)).prevented, true); |
| + p.gate.release(); |
| + await new Promise(r => setTimeout(r, 300)); |
| + assert.equal(p.submits.length, 1, JSON.stringify(p.submits)); |
| + assert.equal(p.gate.calls, 1); |
| + |
| + // Ticking Secret on the add row while the first field seals: nothing is |
| + // sent, the plaintext stays home, and the person is told why. |
| + p = fakePage({addName: 'CUSTOM', addValue: 'sensitive-new-value', gated: true}); |
| + await p.submit(p.save, false); |
| + await p.whenHeld(); |
| + assert.equal(p.form.inert, true); |
| + assert.equal(p.form.dataset.sealBusy, '1'); |
| + const again = await p.submit(p.save, false); // a second click while busy |
| + assert.equal(again.prevented, true); |
| + p.toggle.checked = true; |
| + p.gate.release(); |
| + await new Promise(r => setTimeout(r, 300)); |
| + assert.equal(p.submits.length, 0, JSON.stringify(p.submits)); |
| + assert.match(p.secretErr.textContent, /changed/); |
| + assert.equal(p.form.inert, false); |
| + assert.equal(p.addValueEl.value, 'sensitive-new-value'); |
| + |
| + // Editing a later value to a forbidden one mid-seal: nothing is sent, and |
| + // saving again refuses the edited value rather than sealing it. |
| + p = fakePage({addName: 'X', addValue: 'initially-safe', addTicked: true, gated: true}); |
| + await p.submit(p.save, false); |
| + await p.whenHeld(); |
| + p.addValueEl.value = "now'forbidden"; |
| + p.gate.release(); |
| + await new Promise(r => setTimeout(r, 300)); |
| + assert.equal(p.submits.length, 0, JSON.stringify(p.submits)); |
| + assert.equal(p.addEnv.value, ''); |
| + await p.submit(); |
| + assert.equal(p.submits.length, 0); |
| + assert.match(p.addErr.textContent, /quote/); |
| + |
| // v2 sealing through the form's data attributes. |
| p = fakePage({version: '2'}); |
| await p.submit(); |