carlos / platform Public

console: seal secrets in the browser with the app's key

configseal.js seals with WebCrypto in appconfig's v1/v2 envelope format
and carries the value predicate; the console embeds it as template.JS.
Tests: a shared value case table run through Go and the script, node
envelopes opened by Go Open (v2 refused for another account or app),
committed test-only vectors, and fake-DOM checks that no plaintext posts.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 86ebd76b4686a0e2ed37eac21706601a6d3bce7b parent b67499d
6 files changed, +830 −0
  • internal/console/configseal.go +19 −0
  • internal/console/configseal.js +238 −0
  • internal/console/configseal_test.go +342 −0
  • internal/console/testdata/configseal_run.mjs +174 −0
  • internal/console/testdata/configseal_vectors.json +31 −0
  • internal/console/testdata/configvalue_cases.json +26 −0

Intent

Human

<task-notification> <task-id>aa7482f87801ad984</task-id> <tool-use-id>toolu_01Cwz6vYiAHArtea9ufuAMJr</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/abe35d56-e4c2-40df-9005-6e66b76b1f50/tasks/aa7482f87801ad984.output</output-file> <status>completed</status> <summary>Agent "Implement Tasks 1-2" 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>Fixed in b67499de "appconfig: an unset of keys already gone writes nothing": when nothing is set and no unset key was present, `ApplyAtVersion` returns (0, nil) once the version check passes, with no Put and no generation touch. `go test ./internal/appconfig -run 'ApplyAtVersion|GetBundle' -count=1` passes; the extended test failed on the generation touch before the change. An unset-only call on a bundle that doesn't exist still gets the existing "nothing to unset" refusal, which is checked first. My earlier `git worktree prune` probably removed a stale `wt1` entry belonging to another session. The sandbox now fails to start, so I ran the remaining commands outside it. Report: /home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-console-secrets/.superpowers/sdd/2026-11-08-console-secrets/task-1-2-report.md (fix note appended)</result> <usage><subagent_tokens>151722</subagent_tokens><tool_uses>6</tool_uses><duration_ms>86713</duration_ms></usage> </task-notification>

diff --git a/internal/console/configseal.go b/internal/console/configseal.go
new file mode 100644
index 000000000..2edd3663c
--- /dev/null
+++ b/internal/console/configseal.go
@@ -0,0 +1,19 @@
+package console
+
+import (
+ _ "embed"
+ "html/template"
+)
+
+// configSealSource is the browser sealing script (configseal.js): it seals a
+// secret with the app's public key in the envelope format appconfig opens,
+// so the settings page never posts a secret's plaintext. The page inlines it
+// because customer pages load no /static assets.
+//
+//go:embed configseal.js
+var configSealSource string
+
+// configSealJS is configSealSource typed for an inline <script> in
+// html/template. It is trusted as code because it is this package's own
+// embedded file and nothing else.
+var configSealJS = template.JS(configSealSource)
diff --git a/internal/console/configseal.js b/internal/console/configseal.js
new file mode 100644
index 000000000..e2ed70ab9
--- /dev/null
+++ b/internal/console/configseal.js
@@ -0,0 +1,238 @@
+// Seals a secret in the browser with the app's public key, so its plaintext
+// never reaches the console. The envelope is byte for byte what
+// internal/appconfig/crypto.go writes and opens:
+//
+// v1: base64(ephPub(65) || nonce(12) || ciphertext || tag(16))
+// v2: base64("CSB2" || ephPub(65) || nonce(12) || ciphertext || tag(16))
+//
+// ECDH P-256 with a fresh ephemeral key, shared secret = the X coordinate,
+// HKDF-SHA256 (empty salt, info carlos-secrets-v1 or carlos-secrets-v2),
+// AES-256-GCM. v2 authenticates the account and app as associated data:
+// each of "CSB2", account, app as a 4-byte big-endian length then its bytes.
+//
+// Plain script, no modules: the settings page inlines it (customer pages load
+// no /static assets). The page renders the secret controls disabled; this
+// script enables them, so without it no secret plaintext can be typed or sent.
+(function () {
+ "use strict";
+
+ 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."
+ };
+
+ // The same rule as appconfig.ValidVarValue, plus the empty-secret rule
+ // the CLI and the console door apply. Returns the refusal or null.
+ function validValue(s, secret) {
+ if (/[\n\u0000\\'"]/.test(s)) return MSG.chars;
+ if (secret && s === "") return MSG.empty;
+ return null;
+ }
+
+ var SECRET_NAME = ["KEY", "TOKEN", "SECRET", "PASSWORD", "PASS", "PRIVATE", "DSN"];
+ var SECRET_VALUE = ["sk_", "pk_live_", "ghp_", "github_pat_", "xox", "AKIA", "-----BEGIN"];
+
+ // A hint only: ticks the Secret box for a value that looks like a
+ // credential. The person can untick it.
+ function looksSecret(name, value) {
+ var n = String(name || "").toUpperCase(), v = String(value || ""), i;
+ for (i = 0; i < SECRET_NAME.length; i++) if (n.indexOf(SECRET_NAME[i]) >= 0) return true;
+ for (i = 0; i < SECRET_VALUE.length; i++) if (v.indexOf(SECRET_VALUE[i]) === 0) return true;
+ return /^[A-Za-z0-9+\/=_-]{32,}$/.test(v);
+ }
+
+ var utf8 = new TextEncoder();
+
+ function fromB64(s) {
+ var bin = atob(s), out = new Uint8Array(bin.length);
+ for (var i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
+ return out;
+ }
+
+ function toB64(bytes) {
+ var bin = "";
+ for (var i = 0; i < bytes.length; i += 0x8000) {
+ bin += String.fromCharCode.apply(null, bytes.subarray(i, i + 0x8000));
+ }
+ return btoa(bin);
+ }
+
+ function concat(parts) {
+ var n = 0, i;
+ for (i = 0; i < parts.length; i++) n += parts[i].length;
+ var out = new Uint8Array(n), at = 0;
+ for (i = 0; i < parts.length; i++) { out.set(parts[i], at); at += parts[i].length; }
+ return out;
+ }
+
+ // Binding.aad in crypto.go.
+ function aad(account, app) {
+ var parts = [];
+ ["CSB2", account, app].forEach(function (f) {
+ var b = utf8.encode(f), len = new Uint8Array(4);
+ new DataView(len.buffer).setUint32(0, b.length, false);
+ parts.push(len, b);
+ });
+ return concat(parts);
+ }
+
+ async function seal(pubB64, version, account, app, plaintext) {
+ var subtle = globalThis.crypto && globalThis.crypto.subtle;
+ if (!subtle) throw new Error("WebCrypto is not available");
+ if (version !== "1" && version !== "2") throw new Error("unknown seal version " + version);
+ if (version === "2" && (!account || !app)) throw new Error("v2 sealing needs an account and an app");
+ var raw = fromB64(String(pubB64).trim());
+ if (raw.length !== 65 || raw[0] !== 4) throw new Error("not an uncompressed P-256 public key");
+ var curve = {name: "ECDH", namedCurve: "P-256"};
+ var pub = await subtle.importKey("raw", raw, curve, false, []);
+ var eph = await subtle.generateKey(curve, false, ["deriveBits"]);
+ var shared = await subtle.deriveBits({name: "ECDH", public: pub}, eph.privateKey, 256);
+ var ikm = await subtle.importKey("raw", shared, "HKDF", false, ["deriveKey"]);
+ var key = await subtle.deriveKey(
+ {name: "HKDF", hash: "SHA-256", salt: new Uint8Array(0), info: utf8.encode(version === "2" ? "carlos-secrets-v2" : "carlos-secrets-v1")},
+ ikm, {name: "AES-GCM", length: 256}, false, ["encrypt"]);
+ var nonce = globalThis.crypto.getRandomValues(new Uint8Array(12));
+ var params = {name: "AES-GCM", iv: nonce, tagLength: 128};
+ if (version === "2") params.additionalData = aad(account, app);
+ var sealed = new Uint8Array(await subtle.encrypt(params, key, utf8.encode(plaintext)));
+ var ephPub = new Uint8Array(await subtle.exportKey("raw", eph.publicKey));
+ var parts = version === "2" ? [utf8.encode("CSB2")] : [];
+ parts.push(ephPub, nonce, sealed);
+ return toB64(concat(parts));
+ }
+
+ globalThis.carlosConfigSeal = {validValue: validValue, seal: seal, looksSecret: looksSecret};
+
+ 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.
+ function say(form, kind) {
+ var d = form.dataset, own = {chars: d.msgChars, empty: d.msgEmpty, seal: d.msgSeal}[kind];
+ return own || MSG[kind];
+ }
+
+ function errorFor(form, input) {
+ var el = input.id && form.querySelector('[data-seal-error="' + input.id + '"]');
+ return el || (input.parentElement && input.parentElement.querySelector("[data-seal-error]"));
+ }
+
+ function show(form, input, text) {
+ var el = errorFor(form, input);
+ if (el) { el.textContent = text; el.hidden = !text; }
+ }
+
+ // The plaintext inputs this submit must seal: every enabled
+ // [data-secret-input] still carrying a name, and the value input a
+ // ticked [data-secret-toggle] points at (data-secret-for=<id>).
+ function secretInputs(form) {
+ var out = [];
+ form.querySelectorAll("[data-secret-input]").forEach(function (el) {
+ if (!el.disabled && el.name) out.push({input: el, required: true});
+ });
+ form.querySelectorAll("[data-secret-toggle]").forEach(function (box) {
+ var el = box.checked && box.dataset.secretFor && document.getElementById(box.dataset.secretFor);
+ if (!el || el.disabled || !el.name) return;
+ var nameEl = box.dataset.nameFrom && document.getElementById(box.dataset.nameFrom);
+ // An untouched add row (no name, no value) is not a secret being set.
+ out.push({input: el, required: !!(nameEl && nameEl.value) || el.value !== ""});
+ });
+ return out;
+ }
+
+ // 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;
+ }
+ 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();
+ }
+
+ async function onSubmit(form, ev) {
+ if (form.dataset.sealed === "1") return;
+ var targets = secretInputs(form);
+ if (!targets.length) return;
+ ev.preventDefault();
+ if (form.dataset.sealBusy === "1") return;
+ var submitter = ev.submitter;
+ // 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);
+ return;
+ }
+ var bad = false;
+ targets.forEach(function (t) {
+ var v = t.input.value, msg = null;
+ if (v === "" && t.required) msg = say(form, "empty");
+ else if (v !== "") { msg = validValue(v, true); if (msg) msg = say(form, "chars"); }
+ show(form, t.input, msg || "");
+ if (msg) bad = true;
+ });
+ if (bad) return;
+ form.dataset.sealBusy = "1";
+ try {
+ var d = form.dataset, envelopes = [];
+ 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];
+ }
+ } catch (e) {
+ targets.forEach(function (t) { show(form, t.input, say(form, "seal")); });
+ return;
+ } finally {
+ delete form.dataset.sealBusy;
+ }
+ targets.forEach(function (t) { strip(t.input); });
+ resubmit(form, submitter);
+ }
+
+ function wire(form) {
+ form.addEventListener("submit", function (ev) { onSubmit(form, ev); });
+ form.querySelectorAll("[data-secret-toggle]").forEach(function (box) {
+ var valueEl = box.dataset.secretFor && document.getElementById(box.dataset.secretFor);
+ var nameEl = box.dataset.nameFrom && document.getElementById(box.dataset.nameFrom);
+ var chosen = false;
+ box.addEventListener("change", function () { chosen = true; });
+ function hint() {
+ if (!chosen && !box.checked && looksSecret(nameEl ? nameEl.value : "", valueEl ? valueEl.value : "")) box.checked = true;
+ }
+ if (valueEl) valueEl.addEventListener("input", hint);
+ if (nameEl) nameEl.addEventListener("input", hint);
+ });
+ }
+
+ function init() {
+ document.querySelectorAll("[data-secret-input], [data-secret-toggle]").forEach(function (el) { el.disabled = false; });
+ document.querySelectorAll("form[data-seal-pub]").forEach(wire);
+ }
+
+ if (document.readyState === "loading") document.addEventListener("DOMContentLoaded", init);
+ else init();
+})();
diff --git a/internal/console/configseal_test.go b/internal/console/configseal_test.go
new file mode 100644
index 000000000..178107599
--- /dev/null
+++ b/internal/console/configseal_test.go
@@ -0,0 +1,342 @@
+package console
+
+import (
+ "bytes"
+ "encoding/base64"
+ "encoding/json"
+ "flag"
+ "os"
+ "os/exec"
+ "strings"
+ "testing"
+ "unicode/utf8"
+
+ "github.com/carlosframework/platform/internal/appconfig"
+ "github.com/carlosframework/platform/internal/release"
+)
+
+var updateSealVectors = flag.Bool("update-seal-vectors", false, "rewrite testdata/configseal_vectors.json from the browser sealing script")
+
+const (
+ configValueCasesPath = "testdata/configvalue_cases.json"
+ configSealVectorPath = "testdata/configseal_vectors.json"
+)
+
+type configValueCase struct {
+ Name string `json:"name"`
+ Value string `json:"value"`
+ Repeat int `json:"repeat,omitempty"`
+ Suffix string `json:"suffix,omitempty"`
+ ValueB64 string `json:"value_b64,omitempty"`
+ Secret bool `json:"secret"`
+ Go string `json:"go"`
+ JS string `json:"js"`
+}
+
+func (c configValueCase) value(t *testing.T) string {
+ if c.ValueB64 != "" {
+ raw, err := base64.StdEncoding.DecodeString(c.ValueB64)
+ if err != nil {
+ t.Fatalf("%s: %v", c.Name, err)
+ }
+ return string(raw)
+ }
+ v := c.Value
+ if c.Repeat > 0 {
+ v = strings.Repeat(v, c.Repeat)
+ }
+ return v + c.Suffix
+}
+
+func loadConfigValueCases(t *testing.T) []configValueCase {
+ t.Helper()
+ raw, err := os.ReadFile(configValueCasesPath)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var file struct {
+ Cases []configValueCase `json:"cases"`
+ }
+ if err := json.Unmarshal(raw, &file); err != nil {
+ t.Fatal(err)
+ }
+ return file.Cases
+}
+
+// goValueVerdict is the rule both doors apply to a value before it is
+// stored: appconfig.ValidVarValue, and an empty secret refused.
+func goValueVerdict(v string, secret bool) string {
+ if appconfig.ValidVarValue(v) != nil || (secret && v == "") {
+ return "refuse"
+ }
+ return "ok"
+}
+
+func TestConfigValueCasesGo(t *testing.T) {
+ cases := loadConfigValueCases(t)
+ seen := map[string]bool{}
+ for _, c := range cases {
+ if seen[c.Name] {
+ t.Errorf("duplicate case name %q", c.Name)
+ }
+ seen[c.Name] = true
+ v := c.value(t)
+ if got := goValueVerdict(v, c.Secret); got != c.Go {
+ t.Errorf("%s: Go says %s, table says %s", c.Name, got, c.Go)
+ }
+ switch c.JS {
+ case "skip":
+ // Only a value a browser cannot type may skip the JS side.
+ if utf8.ValidString(v) {
+ t.Errorf("%s: skipped for JS but is valid UTF-8", c.Name)
+ }
+ case c.Go:
+ default:
+ t.Errorf("%s: table's js %q disagrees with its go %q", c.Name, c.JS, c.Go)
+ }
+ }
+ // The table must keep covering the edges the spec names.
+ for _, name := range []string{"empty ordinary", "empty secret", "single quote", "double quote", "backslash", "newline", "carriage return", "NUL", "tab", "emoji", "64 KiB", "200 KiB", "non-UTF-8"} {
+ if !seen[name] {
+ t.Errorf("case table lost %q", name)
+ }
+ }
+}
+
+func nodeOrSkip(t *testing.T) string {
+ t.Helper()
+ node, err := exec.LookPath("node")
+ if err != nil {
+ t.Skip("no installed node for browser sealing checks")
+ }
+ return node
+}
+
+func runConfigSeal(t *testing.T, stdin []byte, env []string, args ...string) []byte {
+ t.Helper()
+ cmd := exec.CommandContext(t.Context(), nodeOrSkip(t), append([]string{"testdata/configseal_run.mjs"}, args...)...)
+ cmd.Stdin = bytes.NewReader(stdin)
+ cmd.Env = append(os.Environ(), env...)
+ var stderr bytes.Buffer
+ cmd.Stderr = &stderr
+ out, err := cmd.Output()
+ if err != nil {
+ t.Fatalf("configseal_run.mjs %s: %v\n%s", strings.Join(args, " "), err, stderr.Bytes())
+ }
+ return out
+}
+
+func TestConfigValueCasesJS(t *testing.T) {
+ cases := loadConfigValueCases(t)
+ var got []struct{ Name, JS string }
+ if err := json.Unmarshal(runConfigSeal(t, nil, nil, "predicate", configValueCasesPath), &got); err != nil {
+ t.Fatal(err)
+ }
+ js := map[string]string{}
+ for _, g := range got {
+ js[g.Name] = g.JS
+ }
+ for _, c := range cases {
+ if c.JS == "skip" {
+ continue
+ }
+ if js[c.Name] != c.JS || js[c.Name] != goValueVerdict(c.value(t), c.Secret) {
+ t.Errorf("%s: script says %q, table says js %q go %q", c.Name, js[c.Name], c.JS, c.Go)
+ }
+ }
+}
+
+type sealVector struct {
+ Version string `json:"version"`
+ Account string `json:"account,omitempty"`
+ App string `json:"app,omitempty"`
+ Plaintext string `json:"plaintext"`
+ Envelope string `json:"envelope,omitempty"`
+}
+
+type sealVectorFile struct {
+ About string `json:"about"`
+ TestOnlyPrivateKey string `json:"test_only_private_key_never_deploy"`
+ PublicKey string `json:"public_key"`
+ Vectors []sealVector `json:"vectors"`
+}
+
+var (
+ sealRight = appconfig.Binding{Account: "bab", App: "shop"}
+ sealWrongs = []appconfig.Binding{{Account: "bdn", App: "shop"}, {Account: "bab", App: "blog"}, {Account: "babs", App: "hop"}}
+)
+
+// checkBrowserEnvelope opens env with Go exactly as a box would and checks
+// the wire layout byte for byte.
+func checkBrowserEnvelope(t *testing.T, privB64 string, v sealVector) {
+ t.Helper()
+ priv, err := appconfig.ParsePrivateKey(privB64, "test key")
+ if err != nil {
+ t.Fatal(err)
+ }
+ raw, err := base64.StdEncoding.Strict().DecodeString(v.Envelope)
+ if err != nil {
+ t.Fatalf("%q: not standard padded base64: %v", v.Plaintext, err)
+ }
+ prefix := ""
+ if v.Version == "2" {
+ prefix = "CSB2"
+ }
+ if want := len(prefix) + 65 + 12 + len(v.Plaintext) + 16; len(raw) != want {
+ t.Errorf("%q v%s: %d bytes, want %d", v.Plaintext, v.Version, len(raw), want)
+ }
+ if !bytes.HasPrefix(raw, []byte(prefix)) || raw[len(prefix)] != 0x04 {
+ t.Errorf("%q v%s: layout starts %x", v.Plaintext, v.Version, raw[:min(len(raw), 8)])
+ }
+ if err := appconfig.CheckEnvelope(v.Envelope); err != nil {
+ t.Errorf("%q v%s: CheckEnvelope: %v", v.Plaintext, v.Version, err)
+ }
+ if got := appconfig.EnvelopeBound(v.Envelope); got != (v.Version == "2") {
+ t.Errorf("%q v%s: EnvelopeBound = %v", v.Plaintext, v.Version, got)
+ }
+ pt, err := appconfig.Open(priv, sealRight, v.Envelope)
+ if err != nil || string(pt) != v.Plaintext {
+ t.Errorf("%q v%s: Open = %q, %v", v.Plaintext, v.Version, pt, err)
+ }
+ for _, b := range sealWrongs {
+ pt, err := appconfig.Open(priv, b, v.Envelope)
+ if v.Version == "1" {
+ // v1 carries no binding and opens under any config.
+ if err != nil || string(pt) != v.Plaintext {
+ t.Errorf("%q v1 under %v: Open = %q, %v", v.Plaintext, b, pt, err)
+ }
+ } else if err == nil {
+ t.Errorf("%q v2 opened under the wrong binding %v", v.Plaintext, b)
+ }
+ }
+ // The other key never opens it.
+ other, _, err := appconfig.GenerateKey()
+ if err != nil {
+ t.Fatal(err)
+ }
+ otherPriv, _ := appconfig.ParsePrivateKey(other, "other")
+ if _, err := appconfig.Open(otherPriv, sealRight, v.Envelope); err == nil {
+ t.Errorf("%q v%s opened with another key", v.Plaintext, v.Version)
+ }
+}
+
+func TestBrowserSealOpensWithGo(t *testing.T) {
+ for _, b := range append([]appconfig.Binding{sealRight}, sealWrongs...) {
+ if !release.ValidAccount(b.Account) || !release.ValidApp(b.App) {
+ t.Fatalf("binding %v is not valid, so a refusal would not prove the AAD", b)
+ }
+ }
+ priv, pub, err := appconfig.GenerateKey()
+ if err != nil {
+ t.Fatal(err)
+ }
+ var items []sealVector
+ for _, ver := range []string{"1", "2"} {
+ for _, pt := range []string{"hunter2", "key \U0001F511 café 漢字 a\tb\rc", strings.Repeat("x", 64<<10)} {
+ it := sealVector{Version: ver, Plaintext: pt}
+ if ver == "2" {
+ it.Account, it.App = sealRight.Account, sealRight.App
+ }
+ items = append(items, it)
+ }
+ }
+ in, _ := json.Marshal(map[string]any{"pub": pub, "items": items})
+ var envs []string
+ if err := json.Unmarshal(runConfigSeal(t, in, nil, "seal"), &envs); err != nil {
+ t.Fatal(err)
+ }
+ if len(envs) != len(items) {
+ t.Fatalf("%d envelopes for %d items", len(envs), len(items))
+ }
+ seen := map[string]bool{}
+ for i := range items {
+ items[i].Envelope = envs[i]
+ checkBrowserEnvelope(t, priv, items[i])
+ eph := envs[i][:min(len(envs[i]), 96)]
+ if seen[eph] {
+ t.Errorf("item %d reused an ephemeral key and nonce", i)
+ }
+ seen[eph] = true
+ }
+
+ if *updateSealVectors {
+ // Short plaintexts keep the committed file small.
+ var vecs []sealVector
+ for _, it := range items {
+ if len(it.Plaintext) < 1024 {
+ vecs = append(vecs, it)
+ }
+ }
+ out, err := json.MarshalIndent(sealVectorFile{
+ About: "Envelopes sealed by configseal.js under node WebCrypto, opened by Go in TestBrowserSealFixturesOpen. The key below is a throwaway TEST-ONLY key minted by the test; it protects nothing. Regenerate: go test ./internal/console -run TestBrowserSealOpensWithGo -update-seal-vectors",
+ TestOnlyPrivateKey: priv,
+ PublicKey: pub,
+ Vectors: vecs,
+ }, "", " ")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(configSealVectorPath, append(out, '\n'), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ t.Logf("wrote %s", configSealVectorPath)
+ }
+}
+
+func TestBrowserSealFixturesOpen(t *testing.T) {
+ raw, err := os.ReadFile(configSealVectorPath)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var f sealVectorFile
+ if err := json.Unmarshal(raw, &f); err != nil {
+ t.Fatal(err)
+ }
+ versions := map[string]int{}
+ for _, v := range f.Vectors {
+ versions[v.Version]++
+ checkBrowserEnvelope(t, f.TestOnlyPrivateKey, v)
+ }
+ if versions["1"] == 0 || versions["2"] == 0 {
+ t.Fatalf("vectors must cover v1 and v2, have %v", versions)
+ }
+}
+
+// TestBrowserSealForm drives the script's form wiring in a fake DOM: the
+// posted fields carry envelopes and never the plaintext, refusals block the
+// submit, and the envelopes it writes open with Go.
+func TestBrowserSealForm(t *testing.T) {
+ priv, pub, err := appconfig.GenerateKey()
+ if err != nil {
+ t.Fatal(err)
+ }
+ var got struct{ Plaintext, V1, V2 string }
+ if err := json.Unmarshal(runConfigSeal(t, nil, []string{"SEAL_PUB=" + pub}, "dom"), &got); err != nil {
+ t.Fatal(err)
+ }
+ checkBrowserEnvelope(t, priv, sealVector{Version: "1", Plaintext: got.Plaintext, Envelope: got.V1})
+ checkBrowserEnvelope(t, priv, sealVector{Version: "2", Plaintext: got.Plaintext, Envelope: got.V2})
+}
+
+func TestConfigSealScriptEmbeds(t *testing.T) {
+ src, err := os.ReadFile("configseal.js")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if string(configSealJS) != string(src) || configSealSource != string(src) {
+ t.Fatal("embedded script differs from configseal.js")
+ }
+ // Inlined in a <script> element: nothing in it may end or confuse one.
+ lower := strings.ToLower(configSealSource)
+ for _, bad := range []string{"</script", "<!--", "<script"} {
+ if strings.Contains(lower, bad) {
+ t.Errorf("configseal.js contains %q", bad)
+ }
+ }
+ for _, r := range configSealSource {
+ if r == '—' || r == '–' {
+ t.Error("configseal.js has an em or en dash")
+ break
+ }
+ }
+}
diff --git a/internal/console/testdata/configseal_run.mjs b/internal/console/testdata/configseal_run.mjs
new file mode 100644
index 000000000..cac3ee1b5
--- /dev/null
+++ b/internal/console/testdata/configseal_run.mjs
@@ -0,0 +1,174 @@
+// Drives the shipped configseal.js (the same file the console embeds) under
+// node's WebCrypto for configseal_test.go.
+//
+// node configseal_run.mjs predicate <cases.json> prints [{name, js}]
+// node configseal_run.mjs seal < {pub, items:[{version, account, app, plaintext}]}
+// prints [envelope]
+// SEAL_PUB=<b64> node configseal_run.mjs dom fake-DOM submit checks,
+// prints {plaintext, v1, v2}
+import assert from 'node:assert/strict';
+import {readFile} from 'node:fs/promises';
+import vm from 'node:vm';
+
+const source = await readFile(new URL('../configseal.js', import.meta.url), 'utf8');
+const mode = process.argv[2];
+
+async function stdin() {
+ const chunks = [];
+ for await (const c of process.stdin) chunks.push(c);
+ return Buffer.concat(chunks).toString('utf8');
+}
+
+if (mode === 'predicate' || mode === 'seal') {
+ assert.equal(typeof document, 'undefined');
+ vm.runInThisContext(source, {filename: 'configseal.js'});
+ const api = globalThis.carlosConfigSeal;
+ if (mode === 'predicate') {
+ const {cases} = JSON.parse(await readFile(process.argv[3], 'utf8'));
+ const out = [];
+ for (const c of cases) {
+ if (c.js === 'skip') continue;
+ const value = (c.repeat ? c.value.repeat(c.repeat) : c.value) + (c.suffix || '');
+ const r = api.validValue(value, c.secret);
+ assert(r === null || (typeof r === 'string' && r.length > 0), `${c.name}: ${r}`);
+ out.push({name: c.name, js: r === null ? 'ok' : 'refuse'});
+ }
+ process.stdout.write(JSON.stringify(out));
+ } else {
+ const {pub, items} = JSON.parse(await stdin());
+ const out = [];
+ for (const it of items) out.push(await api.seal(pub, it.version, it.account, it.app, it.plaintext));
+ process.stdout.write(JSON.stringify(out));
+ }
+} else if (mode === 'dom') {
+ process.stdout.write(JSON.stringify(await domChecks()));
+} else {
+ throw new Error('unknown mode ' + mode);
+}
+
+// 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'} = {}) {
+ const pub = process.env.SEAL_PUB;
+ function el(attrs, extra = {}) {
+ const listeners = {};
+ const e = {
+ attrs: {...attrs}, disabled: true, hidden: true, textContent: '',
+ get id() { return this.attrs.id || ''; },
+ get name() { return this.attrs.name || ''; },
+ hasAttribute(a) { return a in this.attrs; },
+ removeAttribute(a) { delete this.attrs[a]; },
+ addEventListener(t, fn) { (listeners[t] ||= []).push(fn); },
+ fire(t, ev = {}) { for (const fn of listeners[t] || []) fn(ev); },
+ };
+ Object.defineProperties(e, Object.getOwnPropertyDescriptors(extra));
+ return e;
+ }
+ const secret = el({id: 'r1', name: 'set.default.API_KEY', 'data-secret-input': ''}, {value: secretValue});
+ const secretEnv = el({'data-envelope-for': 'r1', name: 'envelope.default.API_KEY'}, {value: ''});
+ const secretErr = el({'data-seal-error': 'r1'});
+ const addNameEl = el({id: 'an', name: 'add.default.name'}, {value: addName, disabled: false});
+ const addValueEl = el({id: 'av', name: 'add.default.value'}, {value: addValue, disabled: false});
+ const toggle = el({'data-secret-toggle': '', name: 'add.default.secret'}, {checked: addTicked, dataset: {secretFor: 'av', nameFrom: 'an'}});
+ const addEnv = el({'data-envelope-for': 'av', name: 'add.default.envelope'}, {value: ''});
+ const addErr = el({'data-seal-error': 'av'});
+ const all = [secret, secretEnv, secretErr, addNameEl, addValueEl, toggle, addEnv, addErr];
+ const byId = Object.fromEntries(all.filter(e => e.id).map(e => [e.id, e]));
+ const sel = (q, e) => {
+ const m = q.match(/^\[([\w-]+)(?:="([^"]*)")?\]$/);
+ if (!m) throw new Error('selector ' + q);
+ return m[1] in e.attrs && (m[2] === undefined || e.attrs[m[1]] === m[2]);
+ };
+ const submits = [];
+ const form = el({}, {
+ 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])));
+ },
+ });
+ for (const e of all) e.form = form;
+ const document = {
+ readyState: 'complete',
+ getElementById: id => byId[id] || null,
+ querySelectorAll(q) { return q.startsWith('form') ? [form] : form.querySelectorAll(q); },
+ addEventListener() {},
+ };
+ const ctx = vm.createContext({document, TextEncoder, atob, btoa, crypto: globalThis.crypto, 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));
+ return ev;
+ }};
+}
+
+async function domChecks() {
+ // Controls enabled; a sealed save posts envelopes and no plaintext.
+ let p = fakePage({addName: 'DB_URL', addValue: 'postgres://x', addTicked: true});
+ assert.equal(p.secret.disabled, false);
+ assert.equal(p.toggle.disabled, false);
+ let ev = await p.submit();
+ assert.equal(ev.prevented, true);
+ 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(p.secretEnv.value.length > 100 && p.addEnv.value.length > 100);
+ assert.equal(p.secret.value, '');
+ assert.equal(p.secret.hasAttribute('name'), false);
+ assert.equal(p.addValueEl.hasAttribute('name'), false);
+ const v1 = p.secretEnv.value;
+
+ // A refused value blocks the submit, keeps the field, shows the error.
+ p = fakePage({secretValue: "it's"});
+ ev = await p.submit();
+ assert.equal(ev.prevented, true);
+ assert.equal(p.submits.length, 0);
+ assert.equal(p.secretEnv.value, '');
+ assert.match(p.secretErr.textContent, /quote/);
+ assert.equal(p.secretErr.hidden, false);
+
+ // An empty secret blocks with the empty text; an untouched add row does not count.
+ p = fakePage({secretValue: ''});
+ ev = await p.submit();
+ assert.equal(p.submits.length, 0);
+ assert.match(p.secretErr.textContent, /empty/);
+ p = fakePage({addName: 'TOKEN', addValue: '', addTicked: true});
+ await p.submit();
+ assert.equal(p.submits.length, 0);
+ assert.match(p.addErr.textContent, /empty/);
+
+ // 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);
+ assert.equal(p.submits.length, 1);
+ assert(!JSON.stringify(p.submits[0]).includes('s3cret'));
+ assert.equal(p.secretEnv.value, '');
+
+ // Typing a credential-shaped value ticks the Secret box, until the person chooses.
+ p = fakePage();
+ p.addNameEl.value = 'STRIPE_SECRET';
+ p.addNameEl.fire('input');
+ assert.equal(p.toggle.checked, true);
+ p = fakePage();
+ p.toggle.fire('change');
+ p.addValueEl.value = 'sk_live_abc';
+ p.addValueEl.fire('input');
+ assert.equal(p.toggle.checked, false);
+
+ // v2 sealing through the form's data attributes.
+ p = fakePage({version: '2'});
+ await p.submit();
+ assert.equal(p.submits.length, 1);
+ assert(Buffer.from(p.secretEnv.value, 'base64').subarray(0, 4).toString() === 'CSB2');
+ return {plaintext: 's3cret', v1, v2: p.secretEnv.value};
+}
diff --git a/internal/console/testdata/configseal_vectors.json b/internal/console/testdata/configseal_vectors.json
new file mode 100644
index 000000000..298193086
--- /dev/null
+++ b/internal/console/testdata/configseal_vectors.json
@@ -0,0 +1,31 @@
+{
+ "about": "Envelopes sealed by configseal.js under node WebCrypto, opened by Go in TestBrowserSealFixturesOpen. The key below is a throwaway TEST-ONLY key minted by the test; it protects nothing. Regenerate: go test ./internal/console -run TestBrowserSealOpensWithGo -update-seal-vectors",
+ "test_only_private_key_never_deploy": "xKbVxY32zPtWRkhfwugpfIdsamLLebvaWKnV9WLWQ48=",
+ "public_key": "BEAF0bE5Kiff6EDj3AgLX+pLWlu4oWEuws2vcIJ/gG5EoJUzamrBKqXN9ssGUbUzJDOWhsHvmAvEQvlRS8C8ibM=",
+ "vectors": [
+ {
+ "version": "1",
+ "plaintext": "hunter2",
+ "envelope": "BIwRVaFEc9mUZ74A07V+Pa1ZZYYhA7EBcOAd/dEA3bf39HyrfiJwdJyqMcTWzGSD+ZwPtGra/0YT105T4e8SOHZ8ujyxQKzWmTZd0lPGSH97IGLa9tRTgAoE55LI7165verckg=="
+ },
+ {
+ "version": "1",
+ "plaintext": "key 🔑 café 漢字 a\tb\rc",
+ "envelope": "BIooAQnpSd5ofrzARl1GU84aZncbZCUy/y3Se7z43bbWWvTP+p6u33S1CiF2pV1o/KapcvxB4rPEAeAA/nTXq9buCzIF7ATgMx/WW90FqnOh9cCd69pLJ/juM1EzPs3vNxUKzKr+vd/qVAKb8v0e4TcENIViaIXs"
+ },
+ {
+ "version": "2",
+ "account": "bab",
+ "app": "shop",
+ "plaintext": "hunter2",
+ "envelope": "Q1NCMgS3gjtSZ9lrUa6WeWZmvO2yTDZC79gd9Bvps48540fvimEVmAAwX+TCKPDFreAKokmP/z2D0NbTis9qoaIr1M36rGd7zy4ZYZ7y4fA89D3z+3UYz2t7X0u+YfZooci32Tsa8tY="
+ },
+ {
+ "version": "2",
+ "account": "bab",
+ "app": "shop",
+ "plaintext": "key 🔑 café 漢字 a\tb\rc",
+ "envelope": "Q1NCMgTcttPsW7GDX5o8Fpis0P0jRKgZqdoV779ucIbwKFLEkVkXLI8nQfllGdIH1MdgJmz+XsDKhNUs1MdSLLI9VrHA9tjB7Z1uQ3YojY3FF2IPMDU22YHIdGwubUsAnrsD2MO6SrbNMJBA/CsNCoDuTskKfugTriS1SA=="
+ }
+ ]
+}
diff --git a/internal/console/testdata/configvalue_cases.json b/internal/console/testdata/configvalue_cases.json
new file mode 100644
index 000000000..93491e09c
--- /dev/null
+++ b/internal/console/testdata/configvalue_cases.json
@@ -0,0 +1,26 @@
+{
+ "about": "Shared value predicate cases for appconfig.ValidVarValue (plus the empty-secret rule) and configseal.js validValue. Optional fields: repeat (value repeated n times), value_b64 (raw bytes, for a value JSON cannot carry).",
+ "cases": [
+ {"name": "empty ordinary", "value": "", "secret": false, "go": "ok", "js": "ok"},
+ {"name": "empty secret", "value": "", "secret": true, "go": "refuse", "js": "refuse"},
+ {"name": "plain", "value": "hunter2", "secret": true, "go": "ok", "js": "ok"},
+ {"name": "plain ordinary", "value": "production", "secret": false, "go": "ok", "js": "ok"},
+ {"name": "space", "value": "two words", "secret": true, "go": "ok", "js": "ok"},
+ {"name": "single space", "value": " ", "secret": true, "go": "ok", "js": "ok"},
+ {"name": "single quote", "value": "it's", "secret": true, "go": "refuse", "js": "refuse"},
+ {"name": "single quote ordinary", "value": "it's", "secret": false, "go": "refuse", "js": "refuse"},
+ {"name": "double quote", "value": "say \"hi\"", "secret": true, "go": "refuse", "js": "refuse"},
+ {"name": "backslash", "value": "C:\\path", "secret": true, "go": "refuse", "js": "refuse"},
+ {"name": "newline", "value": "line1\nline2", "secret": true, "go": "refuse", "js": "refuse"},
+ {"name": "trailing newline ordinary", "value": "value\n", "secret": false, "go": "refuse", "js": "refuse"},
+ {"name": "carriage return", "value": "a\rb", "secret": true, "go": "ok", "js": "ok"},
+ {"name": "NUL", "value": "a\u0000b", "secret": true, "go": "refuse", "js": "refuse"},
+ {"name": "tab", "value": "a\tb", "secret": true, "go": "ok", "js": "ok"},
+ {"name": "emoji", "value": "key \ud83d\udd11 caf\u00e9 \u6f22\u5b57", "secret": true, "go": "ok", "js": "ok"},
+ {"name": "dollar and backtick", "value": "$HOME `id` %s", "secret": true, "go": "ok", "js": "ok"},
+ {"name": "64 KiB", "value": "a", "repeat": 65536, "secret": true, "go": "ok", "js": "ok"},
+ {"name": "200 KiB", "value": "b", "repeat": 204800, "secret": true, "go": "ok", "js": "ok"},
+ {"name": "200 KiB ending in a quote", "value": "c", "repeat": 204800, "suffix": "'", "secret": true, "go": "refuse", "js": "refuse"},
+ {"name": "non-UTF-8", "value_b64": "YWL/YQ==", "secret": true, "go": "ok", "js": "skip"}
+ ]
+}