diff --git a/.github/scripts/aws-deploy.cjs b/.github/scripts/aws-deploy.cjs index 6957799bc..b344e098a 100644 --- a/.github/scripts/aws-deploy.cjs +++ b/.github/scripts/aws-deploy.cjs @@ -46,8 +46,10 @@ function configuration(env) { } const bake = Number(String(env.DEPLOY_BAKE_SECONDS ?? "").trim() || 300); if (!Number.isInteger(bake) || bake < 0 || bake > 3600) throw new Error("DEPLOY_BAKE_SECONDS must be 0 through 3600"); + const fleetBake = Number(String(env.DEPLOY_FLEET_BAKE_SECONDS ?? "").trim() || 300); + if (!Number.isInteger(fleetBake) || fleetBake < 300 || fleetBake > 3600) throw new Error("DEPLOY_FLEET_BAKE_SECONDS must be 300 through 3600"); return { - cluster, prefix, mode, tag, services, allServices: raw === "all", secretVersions, bake, + cluster, prefix, mode, tag, services, allServices: raw === "all", secretVersions, bake, fleetBake, fleet: env.DEPLOY_FLEET !== "false", allowDroppedSecrets: env.DEPLOY_ALLOW_DROPPED_SECRETS === "true", images: env.DEPLOY_IMAGES_JSON ? JSON.parse(readFileSync(env.DEPLOY_IMAGES_JSON, "utf8")) : null, @@ -169,8 +171,9 @@ async function logTail(clients, definition, task, report, quiet) { // runTask runs a one-off task to completion; capture may be a predicate the log tail must meet. async function runTask(clients, config, network, arn, definition, label, sleep, report, options = {}) { - const { command, environment, capture } = Array.isArray(options) ? { command: options } : options; - const token = createHash("sha256").update(`${config.run}/${arn}/${label}/${JSON.stringify(command || [])}/${JSON.stringify(environment || [])}`).digest("hex"); + const { command, environment, capture, imagePullRetries = 0, pullAttempt = 0 } = Array.isArray(options) ? { command: options } : options; + const identity = `${config.run}/${arn}/${label}/${JSON.stringify(command || [])}/${JSON.stringify(environment || [])}`; + const token = createHash("sha256").update(identity + (pullAttempt ? `/pull-retry-${pullAttempt}` : "")).digest("hex"); const name = definition.containerDefinitions[0].name; const override = { name, ...(command ? { command } : {}), ...(environment ? { environment } : {}) }; const started = assertResponse(await clients.ecs.send(new RunTaskCommand({ @@ -189,7 +192,16 @@ async function runTask(clients, config, network, arn, definition, label, sleep, const container = status.containers?.find((c) => c.name === name); const ok = status.stopCode === "EssentialContainerExited" && container?.exitCode === 0; let lines = !ok || command || capture ? await logTail(clients, definition, task, report, ok && capture) : []; - if (!ok) throw new Error(`${label} failed; its log tail is above`); + if (!ok) { + const neverStarted = !status.startedAt && status.containers?.length > 0 && status.containers.every((c) => c.exitCode === undefined); + const pullFailure = status.stopCode === "TaskFailedToStart" && /^CannotPullContainerError:/.test(status.stoppedReason || ""); + if (neverStarted && pullFailure && pullAttempt < imagePullRetries) { + report(`${label} image pull failed before execution; retry ${pullAttempt + 1}/${imagePullRetries} with the same definition and overrides`); + await sleep(30000 * (pullAttempt + 1)); + return runTask(clients, config, network, arn, definition, label, sleep, report, { ...options, pullAttempt: pullAttempt + 1 }); + } + throw new Error(`${label} failed (${status.stopCode || "unknown stop code"}); inspect stopped task ${task}; its log tail is above`); + } // Log delivery can trail the task stopping by a few seconds. for (let retry = 0; typeof capture === "function" && !capture(lines) && retry < 6; retry++) { await sleep(5000); @@ -383,10 +395,10 @@ async function deploy(clients, config, sleep = (ms) => new Promise((r) => setTim const digests = ["worker", "worker-kafka", "consumer", "consumer-kafka"] .filter((k) => DIGEST_RE.test(config.images.images?.[k] || "")) .map((k) => `${k}=${config.images.images[k]}`); - const command = ["fleet", "rollout", "start", tag, "--canary", "1", "--waves", "100", "--bake", "30m"]; + const command = ["fleet", "rollout", "start", tag, "--canary", "1", "--waves", "100", "--bake", `${config.fleetBake}s`]; if (digests.length) command.push("--digests", digests.join(",")); - await runTask(clients, config, network, arns.ops, rendered.ops, "Fleet rollout", sleep, report, { command }); - report(`Workers move to ${tag} in canary waves; follow with \`warmblyctl fleet rollout status\``); + await runTask(clients, config, network, arns.ops, rendered.ops, "Fleet rollout", sleep, report, { command, imagePullRetries: 2 }); + report(`Workers move to ${tag}: one canary, then all remaining hosts, with ${config.fleetBake}s of healthy uptime per stage plus update time; follow with \`warmblyctl fleet rollout status\``); } return { tag, arns, pins: Object.fromEntries(Object.entries(pins).map(([arn, v]) => [secretService(arn, config.prefix) || arn, v])) }; } diff --git a/.github/scripts/aws-deploy.test.cjs b/.github/scripts/aws-deploy.test.cjs index 41c95c7b8..3609b4964 100644 --- a/.github/scripts/aws-deploy.test.cjs +++ b/.github/scripts/aws-deploy.test.cjs @@ -3,7 +3,7 @@ const assert = require("node:assert/strict"); const { mkdtempSync, writeFileSync } = require("node:fs"); const { join } = require("node:path"); const { tmpdir } = require("node:os"); -const { configuration, deploy, compareTags, parseRef } = require("./aws-deploy.cjs"); +const { configuration, deploy, runTask, compareTags, parseRef } = require("./aws-deploy.cjs"); const root = "arn:aws:ecs:us-east-1:000000000000:"; const registry = "ghcr.io/warmbly/warmbly"; @@ -149,6 +149,11 @@ const valueFrom = (def, key) => def.containerDefinitions[0].secrets.find((s) => test("configuration refuses prereleases, bad modes and secret pins outside refresh-secrets", () => { assert.throws(() => config({ DEPLOY_TAG: "v1.3.0-rc.1" }), /prereleases never deploy/); assert.throws(() => config({ DEPLOY_MODE: "yolo" }), /DEPLOY_MODE/); + for (const value of ["0", "299", "3601", "NaN", "300.5"]) { + assert.throws(() => config({ DEPLOY_FLEET_BAKE_SECONDS: value }), /DEPLOY_FLEET_BAKE_SECONDS/); + } + assert.equal(config().fleetBake, 300); + assert.equal(config({ DEPLOY_FLEET_BAKE_SECONDS: "1800" }).fleetBake, 1800); assert.throws(() => config({ DEPLOY_SERVICES: "backend,worker" }), /DEPLOY_SERVICES/); assert.throws(() => config({ DEPLOY_SECRET_VERSIONS: JSON.stringify({ backend: "a".repeat(36) }) }), /refresh-secrets/); assert.throws(() => config({ DEPLOY_MODE: "refresh-secrets", DEPLOY_SECRET_VERSIONS: JSON.stringify({ backend: "x" }) }), /secret version id/); @@ -286,10 +291,66 @@ test("the fleet rollout gets the worker and consumer digests per variant", async const ops = runs(f).find((r) => r.overrides); const command = ops.overrides.containerOverrides[0].command; assert.deepEqual(command.slice(0, 4), ["fleet", "rollout", "start", "v1.3.0"]); + assert.equal(command[command.indexOf("--bake") + 1], "300s"); assert.equal(command[command.indexOf("--digests") + 1], `worker=${d("b")},worker-kafka=${d("c")},consumer=${d("b")},consumer-kafka=${d("c")}`); assert.equal(ops.overrides.containerOverrides[0].name, "ops"); }); +test("hosted fleet rollout carries a configured longer bake", async () => { + const f = fixture(); + await run(f, config({ DEPLOY_FLEET_BAKE_SECONDS: "1800" })); + const command = runs(f).find((r) => r.overrides).overrides.containerOverrides[0].command; + assert.equal(command[command.indexOf("--bake") + 1], "1800s"); +}); + +test("fleet startup retries only confirmed image-pull failures before execution, with stable retry tokens", async () => { + const pullFailure = { lastStatus: "STOPPED", stopCode: "TaskFailedToStart", stoppedReason: "CannotPullContainerError: manifest not found", containers: [{ name: "ops", runtimeId: "allocated-before-pull" }] }; + const success = { lastStatus: "STOPPED", stopCode: "EssentialContainerExited", containers: [{ name: "ops", exitCode: 0 }] }; + async function attempt(statuses, options = {}) { + const requests = [], sleeps = []; + const clients = { + ecs: { async send(command) { + if (command.constructor.name === "RunTaskCommand") { + requests.push(command.input); + return { tasks: [{ taskArn: `${root}task/fixture/${requests.length}` }] }; + } + return { tasks: [statuses[Math.min(requests.length - 1, statuses.length - 1)]] }; + } }, + logs: { async send() { return { events: [] }; } }, + }; + const execute = () => runTask(clients, config(), {}, "fixture-ops:3", definition("ops", 3, {}), "Fleet rollout", async (ms) => sleeps.push(ms), () => {}, { command: ["fleet", "rollout", "start", "v1.3.0"], imagePullRetries: 2, ...options }); + return { execute, requests, sleeps }; + } + const recovered = await attempt([pullFailure, success]); + await recovered.execute(); + assert.equal(recovered.requests.length, 2); + assert.deepEqual(recovered.sleeps, [30000]); + assert.deepEqual(recovered.requests[0].overrides, recovered.requests[1].overrides); + assert.equal(recovered.requests[0].taskDefinition, recovered.requests[1].taskDefinition); + assert.notEqual(recovered.requests[0].clientToken, recovered.requests[1].clientToken); + const replay = await attempt([pullFailure, success]); + await replay.execute(); + assert.deepEqual(replay.requests.map((r) => r.clientToken), recovered.requests.map((r) => r.clientToken)); + const exhausted = await attempt([pullFailure]); + await assert.rejects(exhausted.execute(), /Fleet rollout failed/); + assert.equal(exhausted.requests.length, 3); + assert.deepEqual(exhausted.sleeps, [30000, 60000]); + for (const failure of [ + { ...success, containers: [{ name: "ops", exitCode: 1 }] }, + { ...pullFailure, startedAt: new Date() }, + { ...pullFailure, containers: [{ name: "ops", exitCode: 1 }] }, + { ...pullFailure, containers: [] }, + { ...pullFailure, stoppedReason: "ResourceInitializationError: unavailable" }, + ]) { + const failed = await attempt([failure]); + await assert.rejects(failed.execute(), /Fleet rollout failed/); + assert.equal(failed.requests.length, 1); + } + const migration = await attempt([pullFailure], { imagePullRetries: 0 }); + await assert.rejects(migration.execute(), /failed/); + assert.equal(migration.requests.length, 1); +}); + test("an unchanged definition reuses its revision and redeploy forces a fresh deployment", async () => { const f = fixture(); await run(f, config({ DEPLOY_SERVICES: "forms", DEPLOY_FLEET: "false" })); diff --git a/.github/scripts/live-tests-summary.mjs b/.github/scripts/live-tests-summary.mjs new file mode 100644 index 000000000..62d8ed5fb --- /dev/null +++ b/.github/scripts/live-tests-summary.mjs @@ -0,0 +1,65 @@ +import { appendFileSync, existsSync, readFileSync } from "node:fs"; +import { pathToFileURL } from "node:url"; + +export function summarizeLiveTests(input, outcome) { + const tests = new Map(); + const subtests = new Map(); + const failedPackages = new Set(); + for (const line of input.split("\n")) { + let event; + try { + event = JSON.parse(line); + } catch { + continue; // Compiler diagnostics can be plain text alongside go test JSON. + } + if (!event || typeof event !== "object") continue; + if (event.Action === "fail" && typeof event.Package === "string" && !event.Test) { + failedPackages.add(event.Package); + } + if (typeof event.Test !== "string" || !event.Test.startsWith("TestLive")) continue; + if (!["pass", "fail", "skip"].includes(event.Action)) continue; + const results = event.Test.includes("/") ? subtests : tests; + results.set(`${event.Package}/${event.Test}`, event.Action); + } + const names = (action) => [...tests].filter(([, result]) => result === action).map(([name]) => name).sort(); + const passed = names("pass"); + const failed = names("fail"); + const skipped = names("skip"); + const skippedSubtests = [...subtests].filter(([, result]) => result === "skip").map(([name]) => name).sort(); + const list = (heading, entries) => [ + `### ${heading}`, + "", + ...(entries.length ? entries.slice(0, 200).map((name) => `- \`${name.replaceAll("`", "\\`")}\``) : ["None recorded."]), + ...(entries.length > 200 ? ["", "Showing the first 200 entries; see the complete output artifact."] : []), + "", + ]; + return { + needsAttention: outcome !== "success" || tests.size === 0 || failed.length > 0 || skipped.length > 0 || skippedSubtests.length > 0 || failedPackages.size > 0, + markdown: [ + "## PostgreSQL catch-all (advisory)", + "", + `Test step outcome: **${outcome || "not started"}**. This job is outside the required CI Status aggregate while #1078 is triaged.`, + "", + "| Top-level TestLive results | Count |", + "| --- | ---: |", + `| Passed | ${passed.length} |`, + `| Failed | ${failed.length} |`, + `| Skipped | ${skipped.length} |`, + "", + ...(tests.size === 0 ? ["No completed TestLive results were recorded. Check setup, compilation and timeouts.", ""] : []), + ...list("Failed packages (including setup or build failures)", [...failedPackages].sort()), + ...list("Failed tests", failed), + ...list("Skipped tests and subtests", [...skipped, ...skippedSubtests]), + "Full JSON events and compiler output are retained in the postgres-live-advisory artifact. Subtests are included there; counts above include each top-level test once.", + "", + ].join("\n"), + }; +} + +if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { + const file = process.argv[2]; + const report = summarizeLiveTests(file && existsSync(file) ? readFileSync(file, "utf8") : "", process.env.LIVE_TEST_OUTCOME); + if (process.env.GITHUB_STEP_SUMMARY) appendFileSync(process.env.GITHUB_STEP_SUMMARY, report.markdown); + else process.stdout.write(report.markdown); + if (report.needsAttention) console.log("::warning::Advisory PostgreSQL coverage needs triage. See the job summary and complete output artifact."); +} diff --git a/.github/scripts/live-tests-summary.test.mjs b/.github/scripts/live-tests-summary.test.mjs new file mode 100644 index 000000000..cd6d6a5a4 --- /dev/null +++ b/.github/scripts/live-tests-summary.test.mjs @@ -0,0 +1,49 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { summarizeLiveTests } from "./live-tests-summary.mjs"; + +const events = (...rows) => rows.map((row) => JSON.stringify(row)).join("\n"); + +test("reports failures, skips and failed packages without counting subtests twice", () => { + const report = summarizeLiveTests(events( + { Action: "pass", Package: "app", Test: "TestLivePassed/child" }, + { Action: "pass", Package: "app", Test: "TestLivePassed" }, + { Action: "fail", Package: "repository", Test: "TestLiveFailed/child" }, + { Action: "fail", Package: "repository", Test: "TestLiveFailed" }, + { Action: "fail", Package: "repository" }, + { Action: "skip", Package: "app", Test: "TestLiveSkipped" }, + { Action: "pass", Package: "app", Test: "TestOther" }, + ), "failure"); + assert.equal(report.needsAttention, true); + assert.match(report.markdown, /\| Passed \| 1 \|/); + assert.match(report.markdown, /\| Failed \| 1 \|/); + assert.match(report.markdown, /\| Skipped \| 1 \|/); + assert.match(report.markdown, /`repository\/TestLiveFailed`/); + assert.match(report.markdown, /`app\/TestLiveSkipped`/); + assert.doesNotMatch(report.markdown, /\/child/); +}); + +test("empty, interrupted and compile-only output cannot look like passing coverage", () => { + for (const input of ["", "# app\ncompiler error", 'null\n{"Action":"fail","Package":"app"}']) { + const report = summarizeLiveTests(input, "failure"); + assert.equal(report.needsAttention, true); + assert.match(report.markdown, /No completed TestLive results/); + } + assert.equal(summarizeLiveTests(events({ Action: "pass", Package: "app", Test: "TestLiveOK" }), "cancelled").needsAttention, true); +}); + +test("successful coverage is clean only when completed tests contain no skips", () => { + assert.equal(summarizeLiveTests(events({ Action: "pass", Package: "app", Test: "TestLiveOK" }), "success").needsAttention, false); + assert.equal(summarizeLiveTests(events({ Action: "skip", Package: "app", Test: "TestLiveSkipped" }), "success").needsAttention, true); +}); + +test("a skipped subtest is actionable even when its parent passes", () => { + const report = summarizeLiveTests(events( + { Action: "skip", Package: "app", Test: "TestLiveExample/needs-fixture" }, + { Action: "pass", Package: "app", Test: "TestLiveExample" }, + ), "success"); + assert.equal(report.needsAttention, true); + assert.match(report.markdown, /\| Passed \| 1 \|/); + assert.match(report.markdown, /\| Skipped \| 0 \|/); + assert.match(report.markdown, /`app\/TestLiveExample\/needs-fixture`/); +}); diff --git a/.github/scripts/pages-marketing-preview.mjs b/.github/scripts/pages-marketing-preview.mjs new file mode 100644 index 000000000..9a9051d79 --- /dev/null +++ b/.github/scripts/pages-marketing-preview.mjs @@ -0,0 +1,45 @@ +import assert from 'node:assert/strict'; +import { readFile } from 'node:fs/promises'; +import { fileURLToPath } from 'node:url'; + +export function previewURL(entries, project, sha) { + const matches = entries.filter(deployment => deployment.type === 'pages-deploy-detailed' + && deployment.version === 1 + && deployment.pages_project === project + && deployment.environment === 'preview' + && deployment.deployment_trigger?.metadata?.commit_hash === sha + && typeof deployment.deployment_id === 'string' && deployment.deployment_id.length > 0); + assert.equal(matches.length, 1, 'Require one Wrangler preview receipt for this project and commit'); + const url = new URL(matches[0].url); + assert.equal(url.protocol, 'https:'); + assert.ok(url.hostname.endsWith(`.${project}.pages.dev`), 'Require the configured Pages project'); + assert.ok(!url.username && !url.password && url.pathname === '/' && !url.search && !url.hash); + return url; +} + +export async function verifyPreview(url, policy, request = fetch, directory = new URL('../../site/dist/', import.meta.url)) { + for (const [path, status, type] of [ + ['/', 200, 'text/html'], ['/terms/', 200, 'text/html'], ['/privacy/', 200, 'text/html'], + ['/marketing-csp-missing-page', 404, 'text/html'], + ['/install.sh', 200, null], ['/cli.sh', 200, null], + ]) { + const response = await request(new URL(path, url), { redirect: 'error', signal: AbortSignal.timeout(30000) }); + assert.equal(response.status, status, `Unexpected preview status for ${path}`); + assert.equal(response.headers.get('content-security-policy'), policy, `Unexpected preview CSP for ${path}`); + assert.equal(response.headers.get('x-content-type-options'), 'nosniff'); + if (type) assert.ok(response.headers.get('content-type')?.startsWith(type)); + else assert.equal(await response.text(), await readFile(new URL(path.slice(1), directory), 'utf8')); + } +} + +if (process.argv[1] === fileURLToPath(import.meta.url)) { + const { CLOUDFLARE_PAGES_PROJECT_NAME: project, WRANGLER_OUTPUT_FILE_PATH: receipt, GITHUB_SHA: sha } = process.env; + assert.ok(project && receipt && sha, 'Require preview deployment configuration'); + const entries = (await readFile(receipt, 'utf8')).split(/\r?\n/).filter(line => line.trim()).map(line => JSON.parse(line)); + const url = previewURL(entries, project, sha); + const headers = await readFile(new URL('../../site/dist/_headers', import.meta.url), 'utf8'); + const policies = [...headers.matchAll(/^\s+Content-Security-Policy: (.+)$/gm)]; + assert.equal(policies.length, 1, 'Require one built policy'); + await verifyPreview(url, policies[0][1]); + console.log('Marketing preview headers, routes and published installers verified'); +} diff --git a/.github/scripts/pages-marketing-preview.test.mjs b/.github/scripts/pages-marketing-preview.test.mjs new file mode 100644 index 000000000..34ad9640d --- /dev/null +++ b/.github/scripts/pages-marketing-preview.test.mjs @@ -0,0 +1,57 @@ +import assert from 'node:assert/strict'; +import { mkdtemp, rm, writeFile } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { pathToFileURL } from 'node:url'; +import { test } from 'node:test'; +import { previewURL, verifyPreview } from './pages-marketing-preview.mjs'; + +test('accepts only a versioned Wrangler preview receipt for the reviewed commit and project', () => { + const deployment = { type: 'pages-deploy-detailed', version: 1, pages_project: 'marketing', + deployment_id: 'deployment-id', environment: 'preview', url: 'https://abc.marketing.pages.dev', + deployment_trigger: { metadata: { commit_hash: 'sha' } } }; + const select = value => previewURL([value], 'marketing', 'sha'); + assert.equal(select(deployment).origin, 'https://abc.marketing.pages.dev'); + for (const override of [ + { environment: 'production' }, { url: 'https://abc.other.pages.dev' }, + { type: 'pages-deploy' }, { version: 2 }, { pages_project: 'other' }, { deployment_id: null }, + { deployment_trigger: { metadata: { commit_hash: 'old' } } }, + ]) assert.throws(() => select({ ...deployment, ...override })); + assert.throws(() => previewURL([deployment, deployment], 'marketing', 'sha')); + assert.equal(previewURL([{ type: 'pages-deploy' }, deployment], 'marketing', 'sha').origin, 'https://abc.marketing.pages.dev'); +}); + +test('verifies page, error and byte-identical installer responses with the built policy', async () => { + const root = await mkdtemp(join(tmpdir(), 'marketing-preview-')); + try { + for (const file of ['install.sh', 'cli.sh']) await writeFile(join(root, file), `# ${file}\n`); + const paths = []; + const request = async url => { + paths.push(url.pathname); + const script = url.pathname.endsWith('.sh'); + return new Response(script ? `# ${url.pathname.slice(1)}\n` : 'Page', { + status: url.pathname.includes('missing-page') ? 404 : 200, + headers: { 'content-security-policy': 'policy', 'x-content-type-options': 'nosniff', + 'content-type': script ? 'text/plain' : 'text/html; charset=utf-8' }, + }); + }; + await verifyPreview('https://abc.marketing.pages.dev', 'policy', request, pathToFileURL(`${root}/`)); + assert.deepEqual(paths, ['/', '/terms/', '/privacy/', '/marketing-csp-missing-page', '/install.sh', '/cli.sh']); + await writeFile(join(root, 'cli.sh'), 'different bytes'); + await assert.rejects(verifyPreview('https://abc.marketing.pages.dev', 'policy', request, pathToFileURL(`${root}/`))); + } finally { + await rm(root, { recursive: true, force: true }); + } +}); + +test('blocks promotion for absent or different policy, redirects and unexpected responses', async () => { + for (const response of [ + new Response('', { status: 200 }), + new Response('', { status: 200, headers: { 'content-security-policy': 'other' } }), + new Response('', { status: 503 }), + ]) await assert.rejects(verifyPreview('https://abc.marketing.pages.dev', 'policy', async () => response)); + await assert.rejects(verifyPreview('https://abc.marketing.pages.dev', 'policy', async (url, options) => { + assert.equal(options.redirect, 'error'); + throw new Error('redirect refused'); + }), /redirect refused/); +}); diff --git a/.github/scripts/runtime-tls.sh b/.github/scripts/runtime-tls.sh new file mode 100755 index 000000000..1860aaec0 --- /dev/null +++ b/.github/scripts/runtime-tls.sh @@ -0,0 +1,191 @@ +#!/usr/bin/env bash +# Finalize runtime TLS through the protected environment using a versioned private snapshot. +set -euo pipefail + +check_plan() { + local stage=${2:-route} + [[ "$stage" = route || "$stage" = drain || "$stage" = on ]] + jq -e --arg stage "$stage" ' + def service: "\\[\\\"(backend|forms|tracking|realtime)\\\"\\]"; + def normalize: + map(.mountPoints //= [] | .systemControls //= [] | .volumesFrom //= [] | + .portMappings = ((.portMappings // []) | map(.hostPort //= .containerPort))); + def same_except($keys): + (.change.before | delpaths($keys | map([.]))) == (.change.after | delpaths($keys | map([.]))); + def normalize_empty_description: + .change.actions == ["update"] and same_except(["description"]) and + .change.before.description == "" and .change.after.description == null; + def normalize_registration: + if .elb_name == "" then .elb_name = null else . end; + def task_settings: + del(.arn, .arn_without_revision, .id, .revision, .container_definitions) | + .enable_fault_injection //= false | .ipc_mode //= "" | .pid_mode //= ""; + def same_task_settings: + (.change.before | task_settings) == (.change.after | task_settings); + def same_container_except_loopback: + (.change.before.container_definitions | fromjson | normalize) as $before | + (.change.after.container_definitions | fromjson | normalize) as $after | + ($after | map(.environment |= map(select(.name != "SERVE_HTTP_LOOPBACK_ONLY")))) == + ($before | map(.environment |= map(select(.name != "SERVE_HTTP_LOOPBACK_ONLY")))) and + all($after[]; if $stage == "on" then + any(.environment[]; .name == "SERVE_HTTP_LOOPBACK_ONLY" and .value == "true") + else all(.environment[]; .name != "SERVE_HTTP_LOOPBACK_ONLY") end); + [.resource_changes[]? | select(.change.actions != ["no-op"] and .change.actions != ["read"])] as $changes | + all($changes[]; + if (.address | test("^aws_ecs_task_definition\\.service" + service + "$")) then + .change.actions == ["delete", "create"] and same_container_except_loopback and same_task_settings + elif (.address | test("^aws_ecs_service\\.service" + service + "$")) then + .change.actions == ["update"] and same_except(["load_balancer"]) and + ($stage == "drain") and + (.change.before.load_balancer | length == 2) and + (.change.after.load_balancer | length == 1) and + ((.change.after.load_balancer[0] | normalize_registration) as $tls | + ($tls.target_group_arn | contains("-tls/")) and + (.change.before.load_balancer | map(normalize_registration) | index($tls) != null)) + elif (.address | test("^aws_cloudwatch_metric_alarm\\.target_5xx" + service + "$")) then + .change.actions == ["update"] and same_except(["metric_query"]) + elif (.address | test("^aws_cloudwatch_metric_alarm\\.unhealthy_hosts" + service + "$")) then + .change.actions == ["update"] and same_except(["dimensions"]) + elif (.address | test("^aws_lb_listener_rule\\.(service" + service + "|tracking_alias\\[\\\"[0-9]+\\\"\\])$")) then + .change.actions == ["update"] and same_except(["action"]) + elif (.address | test("^aws_lb_target_group\\.service" + service + "$")) then + $stage == "on" and .change.actions == ["delete"] + elif (.address | test("^aws_vpc_security_group_ingress_rule\\.service" + service + "$")) or + .address == "aws_vpc_security_group_ingress_rule.internal_backend[0]" then + ($stage == "on" and .change.actions == ["delete"]) or normalize_empty_description + else false end) + ' "$1" >/dev/null || { echo 'Plan contains changes outside the runtime TLS switch' >&2; return 1; } +} + +check_live() { + jq -e --arg stage "$2" --arg release "$3" --arg port "$4" --arg prefix "$5" ' + . as $live | + (.services.failures | length == 0) and + ([.services.services[].serviceName] | sort) == + (["backend", "forms", "tracking", "realtime"] | map($prefix + "-" + .) | sort) and + all(.services.services[]; + . as $service | + .desiredCount > 0 and .runningCount == .desiredCount and .pendingCount == 0 and + (.deployments | length == 1) and .deployments[0].rolloutState == "COMPLETED" and + (.loadBalancers | length == (if $stage == "on" then 1 else 2 end)) and + any(.loadBalancers[]; .containerPort == ($port | tonumber) and + (.targetGroupArn | contains("-tls/"))) and + any($live.definitions[]; + .taskDefinition.taskDefinitionArn == $service.taskDefinition and + any(.tags[]; .key == "warmbly-release" and .value == $release) and + (.taskDefinition.containerDefinitions | length > 0) and + all(.taskDefinition.containerDefinitions[]; + (.environment | map({key:.name,value:.value}) | from_entries) as $env | + ($env.SERVE_TLS == "supplied" or $env.SERVE_TLS == "self-signed") and + $env.SERVE_TLS_PORT == $port and $env.SERVE_HTTP_LOOPBACK_ONLY != "true"))) + ' "$1" >/dev/null || { echo 'Live services must be stable on the expected release with compatible TLS listeners and registrations' >&2; return 1; } +} + +check_cleanup() { + jq -e ' + (.tlsPort // 8443) as $port | + (.services | length == 4) and (.httpGroups | length == 4) and + all(.services[]; (.loadBalancers | length > 0) and + all(.loadBalancers[]; .containerPort == $port and (.targetGroupArn | contains("-tls/")))) and + all(.httpGroups[]; (.LoadBalancerArns | length == 0) and (.targets | length == 0)) + ' "$1" >/dev/null || { echo 'HTTP listeners and registrations must be drained before cleanup' >&2; return 1; } +} + +main() { + local action=${1:?} + if [ "$action" = check-plan ]; then check_plan "${2:?}" "${3:-route}"; return; fi + if [ "$action" = check-live ]; then check_live "${2:?}" "${3:?}" "${4:?}" "${5:?}" "${6:?}"; return; fi + if [ "$action" = check-cleanup ]; then check_cleanup "${2:?}"; return; fi + case "$action" in plan|apply) ;; *) echo 'Unknown action' >&2; return 1 ;; esac + : "${STATE_BUCKET:?}" "${WORK:?}" "${VARS_VERSION:?}" "${RELEASE:?}" + : "${STAGE:?}" + [[ "$STAGE" = route || "$STAGE" = drain || "$STAGE" = on ]] + [[ "$VARS_VERSION" != null && "$VARS_VERSION" != *$'\n'* && "$RELEASE" =~ ^v[0-9]+\.[0-9]+\.[0-9]+$ ]] + mkdir -p "$WORK" + chmod 700 "$WORK" + umask 077 + local dir=deploy/terraform/aws/runtime vars="$WORK/runtime.tfvars.json" log="$WORK/runtime.log" + aws s3api get-object --bucket "$STATE_BUCKET" --key warmbly/production/vars/runtime-tls.tfvars.json \ + --version-id "$VARS_VERSION" "$vars" >/dev/null + local previous=both + case "$STAGE" in drain) previous=route ;; on) previous=drain ;; esac + jq -e --arg previous "$previous" '.target_tls == $previous' "$vars" >/dev/null + jq -r '.. | strings | select(length >= 6)' "$vars" | while IFS= read -r line; do + printf '::add-mask::%s\n' "$line" >&2 + done + local account cluster prefix definition port + account=$(aws sts get-caller-identity --query Account --output text) + [ "$account" = 925323749693 ] + cluster=$(jq -r '.name // "warmbly-production"' "$vars") + prefix=$cluster + port=$(jq -r '.target_tls_port // 8443' "$vars") + aws ecs describe-services --cluster "$cluster" --services \ + "$prefix-backend" "$prefix-forms" "$prefix-tracking" "$prefix-realtime" >"$WORK/services.json" + : >"$WORK/definitions.jsonl" + while IFS= read -r definition; do + aws ecs describe-task-definition --task-definition "$definition" --include TAGS >>"$WORK/definitions.jsonl" + done < <(jq -r '.services[].taskDefinition' "$WORK/services.json") + jq -n --slurpfile services "$WORK/services.json" --slurpfile definitions "$WORK/definitions.jsonl" \ + '{services:$services[0],definitions:$definitions}' >"$WORK/live.json" + check_live "$WORK/live.json" "$STAGE" "$RELEASE" "$port" "$prefix" + local service arn count + for service in backend forms tracking realtime; do + arn=$(aws elbv2 describe-target-groups --names "$prefix-$service-tls" --query 'TargetGroups[0].TargetGroupArn' --output text) + count=$(aws elbv2 describe-target-health --target-group-arn "$arn" --query 'TargetHealthDescriptions' --output json | + jq 'if length > 0 and all(.[]; .TargetHealth.State == "healthy") then length else 0 end') + [ "$count" -gt 0 ] || { echo "HTTPS targets are not healthy for $service" >&2; return 1; } + if [ "$STAGE" = route ]; then + arn=$(aws elbv2 describe-target-groups --names "$prefix-$service" --query 'TargetGroups[0].TargetGroupArn' --output text) + count=$(aws elbv2 describe-target-health --target-group-arn "$arn" --query 'TargetHealthDescriptions' --output json | + jq 'if length > 0 and all(.[]; .TargetHealth.State == "healthy") then length else 0 end') + [ "$count" -gt 0 ] || { echo "HTTP fallback is not healthy for $service" >&2; return 1; } + fi + done + if [ "$STAGE" != route ]; then + : "${PREVIOUS_RUN:?}" "${GITHUB_REPOSITORY:?}" + [[ "$PREVIOUS_RUN" =~ ^[0-9]+$ ]] + gh api "repos/$GITHUB_REPOSITORY/actions/runs/$PREVIOUS_RUN" | + jq -e --arg title "Runtime TLS $previous $RELEASE" ' + .conclusion == "success" and .head_branch == "main" and + .path == ".github/workflows/runtime-tls.yml" and .display_title == $title + ' >/dev/null || { echo 'The preceding stage workflow and its release bakes must succeed first' >&2; return 1; } + fi + if [ "$STAGE" = on ]; then + aws elbv2 describe-target-groups --names "$prefix-backend" "$prefix-forms" \ + "$prefix-tracking" "$prefix-realtime" >"$WORK/http-groups.json" + : >"$WORK/http-health.jsonl" + while IFS= read -r arn; do + aws elbv2 describe-target-health --target-group-arn "$arn" | + jq --arg arn "$arn" '{arn:$arn,targets:.TargetHealthDescriptions}' >>"$WORK/http-health.jsonl" + done < <(jq -r '.TargetGroups[].TargetGroupArn' "$WORK/http-groups.json") + jq -n --slurpfile services "$WORK/services.json" --slurpfile groups "$WORK/http-groups.json" \ + --argjson port "$(jq '.target_tls_port // 8443' "$vars")" \ + --slurpfile health "$WORK/http-health.jsonl" '{tlsPort:$port,services:$services[0].services,httpGroups:[ + $groups[0].TargetGroups[] | . as $group | . + {targets:[$health[] | select(.arn == $group.TargetGroupArn) | .targets[]]}]}' >"$WORK/cleanup.json" + check_cleanup "$WORK/cleanup.json" + fi + terraform -chdir="$dir" init -input=false -no-color -backend-config="bucket=$STATE_BUCKET" >"$log" 2>&1 + terraform -chdir="$dir" plan -input=false -no-color -lock-timeout=5m -var-file="$vars" \ + -var="state_bucket=$STATE_BUCKET" -var="target_tls=$STAGE" \ + -target=aws_ecs_service.service -target=aws_lb_listener_rule.tracking_alias \ + -target=aws_vpc_security_group_ingress_rule.service -target=aws_vpc_security_group_ingress_rule.internal_backend \ + -out="$WORK/runtime.tfplan" >>"$log" 2>&1 || { echo 'Runtime TLS plan failed; inspect the private runner log' >&2; return 1; } + terraform -chdir="$dir" show -json "$WORK/runtime.tfplan" >"$WORK/runtime.json" + check_plan "$WORK/runtime.json" "$STAGE" + local digest + digest=$(jq -cS '[.resource_changes[]? | select(.change.actions != ["no-op"] and .change.actions != ["read"])] | sort_by(.address)' "$WORK/runtime.json" | sha256sum | cut -d' ' -f1) + if [ "$action" = plan ]; then + printf 'digest=%s\n' "$digest" >>"${GITHUB_OUTPUT:?}" + jq -r '.resource_changes[]? | select(.change.actions != ["no-op"] and .change.actions != ["read"]) | "\(.change.actions | join("/")) \(.address)"' "$WORK/runtime.json" >>"${GITHUB_STEP_SUMMARY:?}" + else + [ "$digest" = "${APPROVED_DIGEST:?}" ] || { echo 'Runtime TLS plan changed; start a new approval run' >&2; return 1; } + if ! terraform -chdir="$dir" apply -input=false -no-color -lock-timeout=5m "$WORK/runtime.tfplan" >>"$log" 2>&1; then + local diagnostic="warmbly/production/diagnostics/runtime-tls/${GITHUB_RUN_ID:?}/${GITHUB_RUN_ATTEMPT:?}/apply.log" + aws s3 cp "$log" "s3://$STATE_BUCKET/$diagnostic" --only-show-errors || echo 'Private diagnostic upload failed' >&2 + echo "Runtime TLS apply failed; inspect state and private diagnostic $diagnostic before retrying" >&2 + return 1 + fi + echo 'Runtime TLS apply completed' + fi +} +main "$@" diff --git a/.github/scripts/runtime-tls.test.sh b/.github/scripts/runtime-tls.test.sh new file mode 100755 index 000000000..4c39feb22 --- /dev/null +++ b/.github/scripts/runtime-tls.test.sh @@ -0,0 +1,115 @@ +#!/usr/bin/env bash +set -euo pipefail +cd "$(dirname "$0")/../.." +work=$(mktemp -d) +trap 'rm -rf "$work"' EXIT +expect() { + local want=$1 address=$2 actions=$3 stage=${4:-route} + jq -n --arg address "$address" --argjson actions "$actions" '{resource_changes:[{address:$address,change:{actions:$actions}}]}' >"$work/plan.json" + if bash .github/scripts/runtime-tls.sh check-plan "$work/plan.json" "$stage" 2>/dev/null; then + [ "$want" = pass ] + else + [ "$want" = fail ] + fi +} +expect fail 'aws_lb_target_group.service["backend"]' '["delete"]' +expect pass 'aws_lb_target_group.service["backend"]' '["delete"]' on +expect fail 'aws_ecs_service.service["forms"]' '["update"]' +expect fail 'aws_vpc_security_group_ingress_rule.internal_backend[0]' '["delete"]' +expect pass 'aws_vpc_security_group_ingress_rule.internal_backend[0]' '["delete"]' on +expect fail 'aws_vpc_security_group_ingress_rule.service["backend"]' '["delete"]' +expect pass 'aws_vpc_security_group_ingress_rule.service["backend"]' '["delete"]' on +expect fail 'aws_ecs_task_definition.validation' '["delete","create"]' +expect fail 'aws_s3_bucket.data' '["delete"]' +expect fail 'aws_ecs_service.service["consumer"]' '["update"]' +expect fail 'aws_lb_target_group.service["backend"]' '["delete","create"]' +expect fail 'aws_lb_target_group.service["backend"]' '["delete"]' drain +expect fail 'aws_vpc_security_group_ingress_rule.internal_backend[0]' '["delete"]' drain +jq -n '{resource_changes:[{address:"aws_ecs_service.service[\"forms\"]",change:{actions:["update"], + before:{load_balancer:[{target_group_arn:"forms/1",container_port:8090},{target_group_arn:"forms-tls/2",container_port:8443}]}, + after:{load_balancer:[{target_group_arn:"forms-tls/2",container_port:8443}]}}}]}' >"$work/plan.json" +bash .github/scripts/runtime-tls.sh check-plan "$work/plan.json" drain +for stage in route on; do + if bash .github/scripts/runtime-tls.sh check-plan "$work/plan.json" "$stage" 2>/dev/null; then + echo 'Registration detached outside the drain stage' >&2 + exit 1 + fi +done +jq '.resource_changes[0].change |= ( + .before.load_balancer |= map(. + {elb_name:"",advanced_configuration:[]}) | + .after.load_balancer |= map(. + {elb_name:null,advanced_configuration:[]}))' "$work/plan.json" >"$work/normalized.json" +bash .github/scripts/runtime-tls.sh check-plan "$work/normalized.json" drain +for change in '.after.load_balancer[0].elb_name="classic-lb"' \ + '.before.load_balancer[1].elb_name="classic-lb"' \ + '.after.load_balancer[0].container_port=9443' \ + '.after.load_balancer[0].container_name="other"' \ + '.after.load_balancer[0].target_group_arn="other-tls/3"' \ + '.after.load_balancer[0].advanced_configuration=[{alternate_target_group_arn:"other-tls/3"}]'; do + jq ".resource_changes[0].change |= ($change)" "$work/normalized.json" >"$work/changed.json" + if bash .github/scripts/runtime-tls.sh check-plan "$work/changed.json" drain 2>/dev/null; then + echo 'Changed HTTPS registration accepted as empty ELB name normalization' >&2 + exit 1 + fi +done +jq -n '{resource_changes:[{address:"aws_vpc_security_group_ingress_rule.service[\"backend\"]",change:{actions:["update"], + before:{description:"",from_port:8080},after:{description:null,from_port:8080}}}]}' >"$work/plan.json" +bash .github/scripts/runtime-tls.sh check-plan "$work/plan.json" route +jq '.resource_changes[0].change.after.from_port=8443' "$work/plan.json" >"$work/changed.json" +if bash .github/scripts/runtime-tls.sh check-plan "$work/changed.json" route 2>/dev/null; then + echo 'Network change accepted as metadata normalization' >&2 + exit 1 +fi +jq -n '{resource_changes:[{address:"aws_ecs_task_definition.service[\"backend\"]",change:{actions:["delete","create"],before:{container_definitions:([{image:"pinned",environment:[]}]|tojson)},after:{container_definitions:([{image:"pinned",environment:[{name:"SERVE_HTTP_LOOPBACK_ONLY",value:"true"}]}]|tojson)}}}]}' >"$work/plan.json" +bash .github/scripts/runtime-tls.sh check-plan "$work/plan.json" on +if bash .github/scripts/runtime-tls.sh check-plan "$work/plan.json" route 2>/dev/null; then + echo 'Loopback-only listener accepted before HTTP registrations drained' >&2 + exit 1 +fi +jq '.resource_changes[0].change |= ({actions:.actions,before:.after,after:.before})' "$work/plan.json" >"$work/route.json" +bash .github/scripts/runtime-tls.sh check-plan "$work/route.json" route +jq '.resource_changes[0].change.after.container_definitions |= (fromjson | .[0].image = "changed" | tojson)' "$work/plan.json" >"$work/changed.json" +if bash .github/scripts/runtime-tls.sh check-plan "$work/changed.json" on 2>/dev/null; then + echo 'Changed image was accepted' >&2 + exit 1 +fi +jq '.resource_changes[0].change.before.cpu = "512" | .resource_changes[0].change.after.cpu = "1024"' "$work/plan.json" >"$work/changed.json" +if bash .github/scripts/runtime-tls.sh check-plan "$work/changed.json" on 2>/dev/null; then + echo 'Changed task settings were accepted' >&2 + exit 1 +fi +jq -n '{resource_changes:[{address:"aws_ecs_service.service[\"backend\"]",change:{actions:["update"],before:{network_configuration:[]},after:{network_configuration:[{subnets:["other"]}]}}}]}' >"$work/changed.json" +if bash .github/scripts/runtime-tls.sh check-plan "$work/changed.json" 2>/dev/null; then + echo 'Changed service network was accepted' >&2 + exit 1 +fi +jq -n '{services:[range(4) | {loadBalancers:[{containerPort:8443,targetGroupArn:"service-tls/123"}]}], + httpGroups:[range(4) | {LoadBalancerArns:[],targets:[]}]}' >"$work/cleanup.json" +bash .github/scripts/runtime-tls.sh check-cleanup "$work/cleanup.json" +for change in '.services[0].loadBalancers[0].containerPort=8080' \ + '.httpGroups[0].LoadBalancerArns=["listener"]' '.httpGroups[0].targets=[{Id:"still-draining"}]' \ + '.services=[]'; do + jq "$change" "$work/cleanup.json" >"$work/changed.json" + if bash .github/scripts/runtime-tls.sh check-cleanup "$work/changed.json" 2>/dev/null; then + echo 'HTTP cleanup accepted before all references drained' >&2 + exit 1 + fi +done +jq -n ' + ["backend","forms","tracking","realtime"] as $names | + {services:{failures:[],services:[$names[] | {serviceName:("test-"+.),taskDefinition:.,desiredCount:1,runningCount:1,pendingCount:0, + deployments:[{rolloutState:"COMPLETED"}],loadBalancers:[{containerPort:8080,targetGroupArn:(.+"/1")},{containerPort:8443,targetGroupArn:(.+"-tls/2")}]}]}, + definitions:[$names[] | {tags:[{key:"warmbly-release",value:"v0.6.70"}],taskDefinition:{taskDefinitionArn:.,containerDefinitions:[{ + environment:[{name:"SERVE_TLS",value:"supplied"},{name:"SERVE_TLS_PORT",value:"8443"}]}]}}]}' >"$work/live.json" +bash .github/scripts/runtime-tls.sh check-live "$work/live.json" route v0.6.70 8443 test +for change in '.services.services[0].pendingCount=1' '.services.services[0].deployments[0].rolloutState="IN_PROGRESS"' \ + '.services.services[0].loadBalancers|=.[0:1]' '.definitions[0].tags[0].value="v0.6.69"' \ + '.definitions[0].taskDefinition.containerDefinitions[0].environment=[]' \ + '.definitions[0].taskDefinition.containerDefinitions[0].environment += [{name:"SERVE_HTTP_LOOPBACK_ONLY",value:"true"}]' \ + '.services.services|=.[0:3]'; do + jq "$change" "$work/live.json" >"$work/changed.json" + if bash .github/scripts/runtime-tls.sh check-live "$work/changed.json" route v0.6.70 8443 test 2>/dev/null; then + echo 'Incompatible or unstable live services accepted' >&2 + exit 1 + fi +done +echo 'Runtime TLS plan guards passed' diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 334d88cd9..a9597e969 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -49,6 +49,7 @@ jobs: filters: | go-services: - '.github/workflows/ci.yml' + - '.github/scripts/live-tests-summary*.mjs' - 'go.mod' - 'go.sum' - 'internal/**' @@ -212,6 +213,10 @@ jobs: if: matrix.suite == 'lint' run: make lint + - name: Check live-test reporting + if: matrix.suite == 'lint' + run: node --test .github/scripts/live-tests-summary.test.mjs + - name: Verify protobuf files are up to date if: matrix.suite == 'lint' run: make check-proto @@ -417,6 +422,32 @@ jobs: grep -q "^--- PASS: $test " monitoring-clock.log done + - name: Approved warmup content and queued source regressions (PostgreSQL) + if: matrix.suite == 'live-2' + env: + WARMBLY_TEST_DB: postgres://warmbly:warmbly@127.0.0.1:5432/warmbly_test?sslmode=disable + run: | + set -euo pipefail + go test -race -v ./internal/repository -run '^TestLiveContentPool' -count=1 | tee content-pool.log + go test -race -v ./internal/tasks -run '^TestLiveWarmupDispatchRechecksOpeningSourceAndExactRecipient$' -count=1 | tee -a content-pool.log + if grep -q -- '--- SKIP:' content-pool.log; then + echo "Warmup content and queued source regressions must execute without skips" + exit 1 + fi + for test in TestLiveContentPoolRejectsDuplicateBatchContentUnderConcurrency \ + TestLiveContentPoolRetryReservesOnceAndReplenishesForExposedMailboxes \ + TestLiveContentPoolPreservesPlansForFutureDistinctMailboxes \ + TestLiveContentPoolConcurrentPairsAlwaysReceiveContent \ + TestLiveContentPoolPrefersLessUsedEligiblePlans \ + TestLiveContentPoolPrefersWhatNeitherMailboxSawRecently \ + TestLiveContentPoolExhaustedPairRepeatsTheLeastRecentlySeen \ + TestLiveContentPoolTokenCleanupKeepsExposure \ + TestLiveContentPoolStaticRowsOnlyFromTheCurrentLibrary \ + TestLiveContentPoolDemandCountsPlansRatherThanReplies \ + TestLiveWarmupDispatchRechecksOpeningSourceAndExactRecipient; do + grep -q "^--- PASS: $test " content-pool.log + done + - name: Warmup generic execution authority regressions (PostgreSQL) if: matrix.suite == 'live-2' env: @@ -431,7 +462,8 @@ jobs: TestLiveWarmupGenericCancellationPreservesOtherHolds \ TestLiveWarmupGenericStartAndLateResult \ TestLiveWarmupGenericStartAfterCompatibleOverwrite \ - TestLiveWarmupGenericCannotRepeatStartedWarmupClaim; do + TestLiveWarmupGenericCannotRepeatStartedWarmupClaim \ + TestLiveWarmupGenericDeniesHistoricalDiagnosticContent; do grep -q "^--- PASS: $test " warmup-generic-execution.log done @@ -594,7 +626,7 @@ jobs: if: matrix.suite == 'live-1' env: WARMBLY_TEST_DB: postgres://warmbly:warmbly@127.0.0.1:5432/warmbly_test?sslmode=disable - run: go test -race -v -p 1 ./internal/repository ./internal/infrastructure/db -run '^TestLiveUnibox(Search|ReadStream|SearchUpgrade|GetBySender)' -count=1 + run: go test -race -v -p 1 ./internal/repository ./internal/infrastructure/db -run '^TestLiveUnibox(Search|ReadStream|SearchUpgrade|GetBySender|ScopeDraftsCount)' -count=1 - name: Notification digest authorization retries (Redis) if: matrix.suite == 'live-3' @@ -617,6 +649,70 @@ jobs: flags: go fail_ci_if_error: false + # Keep advisory coverage separate until #1078's failure inventory is resolved. + go-live-advisory: + name: PostgreSQL catch-all (advisory) + needs: changes + if: needs.changes.outputs.go-services == 'true' + runs-on: ubuntu-latest + timeout-minutes: 45 + continue-on-error: true + services: + postgres: + image: postgres:16 + env: + POSTGRES_USER: warmbly + POSTGRES_PASSWORD: warmbly + POSTGRES_DB: warmbly_test + ports: + - 5432:5432 + options: >- + --health-cmd "pg_isready -U warmbly -d warmbly_test" + --health-interval 10s + --health-timeout 5s + --health-retries 5 + redis: + image: redis:7-alpine + ports: + - 6379:6379 + options: >- + --health-cmd "redis-cli ping" + --health-interval 10s + --health-timeout 5s + --health-retries 5 + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-go@v5 + with: + go-version-file: go.mod + cache: true + - name: Prepare isolated regression database + env: + PRIMARY_DB: postgres://warmbly:warmbly@127.0.0.1:5432/warmbly_test?sslmode=disable + run: go run ./cmd/migrate + - name: Run every TestLive test + id: live + timeout-minutes: 35 + env: + WARMBLY_TEST_DB: postgres://warmbly:warmbly@127.0.0.1:5432/warmbly_test?sslmode=disable + WARMBLY_TEST_REDIS: redis://127.0.0.1:6379/15 + run: | + set -o pipefail + go test -json -race -p 1 -timeout 10m -count=1 -run '^TestLive' ./... 2>&1 | tee live-tests.jsonl + - name: Summarize advisory results + if: always() + env: + LIVE_TEST_OUTCOME: ${{ steps.live.outcome }} + run: node .github/scripts/live-tests-summary.mjs live-tests.jsonl + - name: Retain complete live-test output + if: always() + uses: actions/upload-artifact@v4 + with: + name: postgres-live-advisory-${{ github.run_attempt }} + path: live-tests.jsonl + if-no-files-found: warn + retention-days: 14 + web-ci: name: Web CI needs: changes diff --git a/.github/workflows/deploy-aws.yml b/.github/workflows/deploy-aws.yml index d83535e04..b2fcf3528 100644 --- a/.github/workflows/deploy-aws.yml +++ b/.github/workflows/deploy-aws.yml @@ -22,6 +22,10 @@ on: description: Start a canary rollout of the workers and consumers after the services default: true type: boolean + require_attestation: + description: Refuse images without build provenance (only releases before provenance need false) + default: true + type: boolean workflow_dispatch: inputs: tag: @@ -41,6 +45,10 @@ on: description: Seconds each service is watched against its alarms after it is stable default: "300" type: string + fleet_bake_seconds: + description: Healthy uptime per worker rollout stage (300 through 3600 seconds) + default: "300" + type: string fleet: description: Start a canary rollout of the workers and consumers after the services default: true @@ -139,6 +147,7 @@ jobs: DEPLOY_MODE: ${{ inputs.mode || 'deploy' }} DEPLOY_SERVICES: ${{ inputs.services || 'all' }} DEPLOY_BAKE_SECONDS: ${{ inputs.bake_seconds || vars.AWS_DEPLOY_BAKE_SECONDS || '300' }} + DEPLOY_FLEET_BAKE_SECONDS: ${{ inputs.fleet_bake_seconds || vars.AWS_FLEET_BAKE_SECONDS || '300' }} DEPLOY_FLEET: ${{ inputs.fleet != false }} DEPLOY_ALLOW_DROPPED_SECRETS: ${{ inputs.allow_dropped_secrets == true }} DEPLOY_IMAGES_JSON: ${{ steps.release.outputs.images }} diff --git a/.github/workflows/marketing-pages.yml b/.github/workflows/marketing-pages.yml new file mode 100644 index 000000000..368bec519 --- /dev/null +++ b/.github/workflows/marketing-pages.yml @@ -0,0 +1,120 @@ +name: Deploy marketing Pages + +on: + pull_request: + paths: + - '.github/workflows/marketing-pages.yml' + - '.github/scripts/pages-*' + workflow_dispatch: + inputs: + expected_sha: + description: Reviewed main commit to deploy (full SHA) + required: true + type: string + +permissions: + contents: read + +concurrency: + group: ${{ github.event_name == 'workflow_dispatch' && 'release' || format('marketing-pages-check-{0}', github.ref) }} + cancel-in-progress: false + +jobs: + check: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + with: + persist-credentials: false + - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4 + with: + node-version: "22" + - run: node --test .github/scripts/pages-*.test.mjs + + deploy: + needs: check + if: github.event_name == 'workflow_dispatch' && github.ref == 'refs/heads/main' && vars.CLOUDFLARE_PAGES_DEPLOY_ENABLED == 'true' + runs-on: ubuntu-latest + timeout-minutes: 30 + environment: site-production + env: + CLOUDFLARE_ACCOUNT_ID: ${{ vars.CLOUDFLARE_ACCOUNT_ID }} + PAGES_APP: site + WRANGLER_SEND_METRICS: "false" + steps: + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + with: + ref: ${{ github.sha }} + persist-credentials: false + - name: Require the reviewed main commit + env: + EXPECTED_SHA: ${{ inputs.expected_sha }} + run: test "$EXPECTED_SHA" = "$GITHUB_SHA" + - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4 + with: + node-version: "22" + - name: Select only the configured marketing project + env: + CLOUDFLARE_PAGES_PROJECTS: ${{ vars.CLOUDFLARE_PAGES_PROJECTS }} + run: | + node --input-type=module <<'JS' + import { appendFileSync } from 'node:fs'; + import { deploymentMatrix } from './.github/scripts/pages-projects.mjs'; + const sites = deploymentMatrix(process.env.CLOUDFLARE_PAGES_PROJECTS).include.filter(target => target.app === 'site'); + if (sites.length !== 1) throw new Error('Configure exactly one marketing Pages project'); + appendFileSync(process.env.GITHUB_ENV, `CLOUDFLARE_PAGES_PROJECT_NAME=${sites[0].project}\n`); + JS + - name: Load existing marketing production configuration + id: config + env: + CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }} + run: | + for name in CLOUDFLARE_API_TOKEN CLOUDFLARE_ACCOUNT_ID CLOUDFLARE_PAGES_PROJECT_NAME; do + test -n "${!name}" + done + curl --fail --silent --show-error \ + --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \ + "https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/pages/projects/$CLOUDFLARE_PAGES_PROJECT_NAME" \ + | node .github/scripts/pages-production-config.mjs + - uses: pnpm/action-setup@b906affcce14559ad1aafd4ab0e942779e9f58b1 # v4 + with: + version: "11.9.0" + - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4 + with: + node-version: "22" + cache: pnpm + cache-dependency-path: site/pnpm-lock.yaml + - name: Install marketing dependencies + working-directory: site + run: pnpm install --frozen-lockfile + - name: Check marketing behavior and CSP + working-directory: site + run: pnpm test + - name: Build marketing with production configuration + working-directory: site + run: pnpm build + - name: Deploy an isolated preview + env: + CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }} + PREVIEW_BRANCH: marketing-check-${{ github.run_id }}-${{ github.run_attempt }} + PRODUCTION_BRANCH: ${{ steps.config.outputs.production_branch }} + WRANGLER_OUTPUT_FILE_PATH: ${{ runner.temp }}/marketing-preview-${{ github.run_id }}-${{ github.run_attempt }}.ndjson + run: | + test "$PREVIEW_BRANCH" != "$PRODUCTION_BRANCH" + test ! -e "$WRANGLER_OUTPUT_FILE_PATH" + pnpm dlx wrangler@4.45.0 pages deploy site/dist \ + --project-name "$CLOUDFLARE_PAGES_PROJECT_NAME" \ + --branch "$PREVIEW_BRANCH" --commit-hash "$GITHUB_SHA" + - name: Verify preview responses before production + env: + WRANGLER_OUTPUT_FILE_PATH: ${{ runner.temp }}/marketing-preview-${{ github.run_id }}-${{ github.run_attempt }}.ndjson + run: node .github/scripts/pages-marketing-preview.mjs + - name: Publish the verified marketing artifact + env: + CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }} + PRODUCTION_BRANCH: ${{ steps.config.outputs.production_branch }} + run: | + pnpm dlx wrangler@4.45.0 pages deploy site/dist \ + --project-name "$CLOUDFLARE_PAGES_PROJECT_NAME" \ + --branch "$PRODUCTION_BRANCH" --commit-hash "$GITHUB_SHA" \ + --commit-message "Marketing $GITHUB_SHA" diff --git a/.github/workflows/runtime-tls.yml b/.github/workflows/runtime-tls.yml new file mode 100644 index 000000000..a57cc1ffc --- /dev/null +++ b/.github/workflows/runtime-tls.yml @@ -0,0 +1,129 @@ +name: Finalize runtime TLS +run-name: Runtime TLS ${{ inputs.stage }} ${{ inputs.release }} + +on: + workflow_dispatch: + inputs: + vars_version: + description: S3 version ID of the reviewed runtime-tls.tfvars.json snapshot at the previous stage + required: true + type: string + stage: + description: Advance one verified stage while preserving the previous traffic path + required: true + default: route + type: choice + options: ["route", "drain", "on"] + previous_run: + description: Successful preceding stage workflow run ID (required for drain and on) + required: false + type: string + release: + description: Currently deployed release, retained for the service redeploy + required: true + type: string + pull_request: + paths: + - '.github/workflows/runtime-tls.yml' + - '.github/scripts/runtime-tls*' + +permissions: + contents: read + +env: + AWS_REGION: us-east-1 + TF_IN_AUTOMATION: "1" + TF_INPUT: "0" + +jobs: + check: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + with: + persist-credentials: false + - run: shellcheck .github/scripts/runtime-tls.sh .github/scripts/runtime-tls.test.sh + - run: bash .github/scripts/runtime-tls.test.sh + + plan: + needs: check + if: github.event_name == 'workflow_dispatch' && github.ref == 'refs/heads/main' + runs-on: ubuntu-latest + environment: aws-infrastructure-plan + permissions: + contents: read + id-token: write + actions: read + outputs: + digest: ${{ steps.plan.outputs.digest }} + steps: + - uses: actions/checkout@v4 + with: + persist-credentials: false + - uses: hashicorp/setup-terraform@v3 + with: + terraform_version: "1.16.5" + terraform_wrapper: false + - uses: aws-actions/configure-aws-credentials@v4 + with: + role-to-assume: ${{ vars.AWS_TERRAFORM_PLAN_ROLE_ARN }} + aws-region: us-east-1 + - id: plan + env: + STATE_BUCKET: ${{ vars.AWS_TERRAFORM_STATE_BUCKET }} + WORK: ${{ runner.temp }}/runtime-tls + VARS_VERSION: ${{ inputs.vars_version }} + RELEASE: ${{ inputs.release }} + STAGE: ${{ inputs.stage }} + PREVIOUS_RUN: ${{ inputs.previous_run }} + GH_TOKEN: ${{ github.token }} + run: .github/scripts/runtime-tls.sh plan + + apply: + needs: plan + runs-on: ubuntu-latest + environment: aws-infrastructure-approval + concurrency: + group: aws-production + cancel-in-progress: false + permissions: + contents: read + id-token: write + actions: read + steps: + - uses: actions/checkout@v4 + with: + persist-credentials: false + - uses: hashicorp/setup-terraform@v3 + with: + terraform_version: "1.16.5" + terraform_wrapper: false + - uses: aws-actions/configure-aws-credentials@v4 + with: + role-to-assume: ${{ vars.AWS_TERRAFORM_APPLY_ROLE_ARN }} + aws-region: us-east-1 + - env: + STATE_BUCKET: ${{ vars.AWS_TERRAFORM_STATE_BUCKET }} + WORK: ${{ runner.temp }}/runtime-tls + VARS_VERSION: ${{ inputs.vars_version }} + RELEASE: ${{ inputs.release }} + APPROVED_DIGEST: ${{ needs.plan.outputs.digest }} + STAGE: ${{ inputs.stage }} + PREVIOUS_RUN: ${{ inputs.previous_run }} + GH_TOKEN: ${{ github.token }} + run: .github/scripts/runtime-tls.sh apply + + redeploy: + needs: apply + permissions: + contents: read + id-token: write + attestations: read + uses: ./.github/workflows/deploy-aws.yml + with: + tag: ${{ inputs.release }} + mode: redeploy + services: backend,forms,tracking,realtime + fleet: false + require_attestation: true + secrets: inherit diff --git a/.github/workflows/terraform-aws.yml b/.github/workflows/terraform-aws.yml index 5de0ce85d..33f097da4 100644 --- a/.github/workflows/terraform-aws.yml +++ b/.github/workflows/terraform-aws.yml @@ -46,6 +46,8 @@ jobs: terraform -chdir="deploy/terraform/aws/$stack" init -backend=false -input=false >/dev/null terraform -chdir="deploy/terraform/aws/$stack" validate -no-color done + # Mocked provider: no credentials, nothing created. + - run: terraform -chdir=deploy/terraform/aws/runtime test -no-color - run: shellcheck .github/scripts/terraform-stack.sh plan: diff --git a/AGENTS.md b/AGENTS.md index 3fbe4af37..245662afc 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -24,6 +24,14 @@ store lives, what is kept and for how long, how it is backed up. The script is ## Working In This Repo +### Warmup content and deliverability + +- Warmup mail reads as ordinary correspondence and never describes itself. `generation.ValidateWarmupWording` refuses any outgoing turn that calls itself simulated, diagnostic, hypothetical, fictional, automated, generated, a test message or a warmup; generation, review and the hand-written library all have to pass it. No fixed phrases, shared subject prefixes or repeated footers. +- Content never runs out. New threads draw from the hand-written library (`internal/tasks/warmup_library_*.go`) and the AI bank together, preferring what neither mailbox saw in `repository.WarmupContentRepeatWindow`, then the least recently seen. Do not add a path that defers sending for lack of fresh content, and do not reintroduce a lifetime per-mailbox exclusion. +- A library thread's ID is derived from its theme and opening, so editing one retires it and threads in flight on it close. Keep the library above the floor `TestStaticLibraryReadsAsOrdinaryMail` enforces. +- Do not add random strings, fabricated reply prefixes, invented relationships or other cosmetic variation to disguise repetition. Content variation never bypasses mailbox consent, authentication checks, provider limits, suppression or pacing. +- Do not claim that wording or local checks guarantee inbox placement, improve reputation or prevent provider suspensions. + CI is strict. `go build ./...` succeeding is not enough — `golangci-lint` runs `gofmt` as part of its checks, and a single unformatted import block or mis-indented doc comment will fail the PR even when the code compiles cleanly. Before declaring any Go change done: - run `gofmt -w` on every Go file you touched (or `gofmt -w internal/ cmd/` to be safe) diff --git a/Makefile b/Makefile index 96da2830c..8d9144267 100644 --- a/Makefile +++ b/Makefile @@ -697,10 +697,16 @@ consumer: # # The worker reads encrypted DEKs through the backend's /internal/dek # endpoint (the prod `http` provider, no worker DB), so `make backend` -# must be running and INTERNAL_API_TOKEN must match. +# must be running and INTERNAL_API_TOKEN must match. The seeded dev worker +# also presents its own NODE_CREDENTIAL (internal/seed.DevNodeCredential), so it +# keeps working with NODE_REQUIRE_NODE_CREDENTIAL=true on the backend. +DEV_WORKER_ID := 10c8f5e4-1c39-5b2a-9c8b-3d2f0a8b1a01 +NODE_CREDENTIAL_DEV := dev-node-credential-not-for-production +WORKER_ID ?= $(DEV_WORKER_ID) worker: $(WORKER_DEV_ENV) \ - WORKER_ID=10c8f5e4-1c39-5b2a-9c8b-3d2f0a8b1a01 \ + WORKER_ID=$(WORKER_ID) \ + $(if $(filter $(DEV_WORKER_ID),$(WORKER_ID)),NODE_CREDENTIAL=$(NODE_CREDENTIAL_DEV),) \ ENCRYPTED_KEYS_PROVIDER=http \ ENCRYPTED_KEYS_BACKEND_URL=http://localhost:8080 \ ENCRYPTED_KEYS_WORKER_TOKEN=local-dev-internal-token \ diff --git a/admin/pnpm-lock.yaml b/admin/pnpm-lock.yaml index b4d3e2af2..35e91512c 100644 --- a/admin/pnpm-lock.yaml +++ b/admin/pnpm-lock.yaml @@ -9,8 +9,8 @@ overrides: js-yaml: ^4.3.1 nanoid: ^3.3.17 dompurify: ^3.4.17 - follow-redirects: ^1.16.1 - seroval: ^1.6.3 + follow-redirects: ^1.16.2 + seroval: ^1.6.11 source-map-js: ^1.2.2 importers: @@ -67,7 +67,7 @@ importers: version: 5.103.1(@tanstack/react-query@5.103.1(react@19.3.0))(@types/react@19.3.0)(csstype@3.2.3)(react@19.3.0) axios: specifier: ^1.20.0 - version: 1.20.0 + version: 1.20.0(debug@4.4.3(supports-color@7.2.0))(supports-color@7.2.0) class-variance-authority: specifier: ^0.7.1 version: 0.7.1 @@ -119,7 +119,7 @@ importers: version: 9.39.5 '@sentry/vite-plugin': specifier: ^5.4.0 - version: 5.4.0(rollup@4.65.0) + version: 5.4.0(rollup@4.65.0)(supports-color@7.2.0) '@types/node': specifier: ^24.13.5 version: 24.13.5 @@ -131,22 +131,22 @@ importers: version: 19.3.0(@types/react@19.3.0) '@vitejs/plugin-react': specifier: ^5.2.0 - version: 5.2.0(vite@7.3.7(@types/node@24.13.5)(jiti@2.7.0)(lightningcss@1.32.0)) + version: 5.2.0(supports-color@7.2.0)(vite@7.3.7(@types/node@24.13.5)(jiti@2.7.0)(lightningcss@1.32.0)) eslint: specifier: ^9.39.5 - version: 9.39.5(jiti@2.7.0) + version: 9.39.5(jiti@2.7.0)(supports-color@7.2.0) eslint-plugin-react-hooks: specifier: ^5.2.0 - version: 5.2.0(eslint@9.39.5(jiti@2.7.0)) + version: 5.2.0(eslint@9.39.5(jiti@2.7.0)(supports-color@7.2.0)) eslint-plugin-react-refresh: specifier: ^0.4.26 - version: 0.4.26(eslint@9.39.5(jiti@2.7.0)) + version: 0.4.26(eslint@9.39.5(jiti@2.7.0)(supports-color@7.2.0)) globals: specifier: ^16.5.0 version: 16.5.0 jsdom: specifier: ^27.4.0 - version: 27.4.0 + version: 27.4.0(supports-color@7.2.0) tw-animate-css: specifier: ^1.4.0 version: 1.4.0 @@ -155,13 +155,13 @@ importers: version: 5.9.3 typescript-eslint: specifier: ^8.70.0 - version: 8.70.0(eslint@9.39.5(jiti@2.7.0))(typescript@5.9.3) + version: 8.70.0(eslint@9.39.5(jiti@2.7.0)(supports-color@7.2.0))(supports-color@7.2.0)(typescript@5.9.3) vite: specifier: ^7.3.7 version: 7.3.7(@types/node@24.13.5)(jiti@2.7.0)(lightningcss@1.32.0) vitest: specifier: ^4.1.11 - version: 4.1.11(@types/node@24.13.5)(jsdom@27.4.0)(vite@7.3.7(@types/node@24.13.5)(jiti@2.7.0)(lightningcss@1.32.0)) + version: 4.1.11(@types/node@24.13.5)(jsdom@27.4.0(supports-color@7.2.0))(vite@7.3.7(@types/node@24.13.5)(jiti@2.7.0)(lightningcss@1.32.0)) packages: @@ -1889,8 +1889,8 @@ packages: flatted@3.4.4: resolution: {integrity: sha512-5+ybhBZANEJxaH3X5evAFatUxLfEHSr7n6kYJ+1Qd0mUqr4eu9gIf6GDbWHf8RJijHrjjO8G+la14SlL2SeS1Q==} - follow-redirects@1.16.1: - resolution: {integrity: sha512-FNvFGzoMLWmE6Yj9spb/zjd7yiNCHiAW9/Tg9CXrQ8wuu32HtlJOwWO11OJafl5FfY3DxTdQ0vj42zU1kvv5jg==} + follow-redirects@1.16.2: + resolution: {integrity: sha512-/kVP2U8z596Ia0gwFrwyIeo74ta5aVmSeU1FfAUMAmcEP5EP7zydmag3SLiN64NaRKef3lxsq7i/g7ltJQDGow==} engines: {node: '>=4.0'} peerDependencies: debug: '*' @@ -2440,11 +2440,11 @@ packages: resolution: {integrity: sha512-HXuLAX2pu/UByPpaeo/TaMfvMIi+1QqIoPJYCcAtU8QkVNwgR6MPlGuCQTErV1JwraaMbYaWVIBX7mppzGLATQ==} engines: {node: '>=10'} peerDependencies: - seroval: ^1.6.3 + seroval: ^1.6.11 - seroval@1.6.8: - resolution: {integrity: sha512-HlSgSAkTk4EqHcje1ptJjfZi1YDv5KbhVJ/d3P7T/nAXua2VmDu+AKDX5VTdFfZf48nDkWB2TKYt0DrCSa+3wg==} - engines: {node: '>=10'} + seroval@1.7.5: + resolution: {integrity: sha512-UdNgpHdq0gVpme5JdQF+S3jNscnjFr4NTwUWOc1qcOa8OuWZmbV0+YX2hsqxkUZshBpHnpxDZfAKVZG2ugbrJA==} + engines: {node: '>=20'} set-cookie-parser@2.7.2: resolution: {integrity: sha512-oeM1lpU/UvhTxw+g3cIfxXHyJRc/uidd3yK1P242gzHds0udQBYzs3y8j4gCCW+ZJ7ad0yctld8RYO+bdurlvw==} @@ -2800,20 +2800,20 @@ snapshots: '@babel/compat-data@7.29.7': {} - '@babel/core@7.29.7': + '@babel/core@7.29.7(supports-color@7.2.0)': dependencies: '@babel/code-frame': 7.29.7 '@babel/generator': 7.29.8 '@babel/helper-compilation-targets': 7.29.7 - '@babel/helper-module-transforms': 7.29.7(@babel/core@7.29.7) + '@babel/helper-module-transforms': 7.29.7(@babel/core@7.29.7(supports-color@7.2.0))(supports-color@7.2.0) '@babel/helpers': 7.29.7 '@babel/parser': 7.29.8 '@babel/template': 7.29.7 - '@babel/traverse': 7.29.8 + '@babel/traverse': 7.29.8(supports-color@7.2.0) '@babel/types': 7.29.8 '@jridgewell/remapping': 2.3.5 convert-source-map: 2.0.0 - debug: 4.4.3 + debug: 4.4.3(supports-color@7.2.0) gensync: 1.0.0-beta.2 json5: 2.2.3 semver: 6.3.1 @@ -2838,19 +2838,19 @@ snapshots: '@babel/helper-globals@7.29.7': {} - '@babel/helper-module-imports@7.29.7': + '@babel/helper-module-imports@7.29.7(supports-color@7.2.0)': dependencies: - '@babel/traverse': 7.29.8 + '@babel/traverse': 7.29.8(supports-color@7.2.0) '@babel/types': 7.29.8 transitivePeerDependencies: - supports-color - '@babel/helper-module-transforms@7.29.7(@babel/core@7.29.7)': + '@babel/helper-module-transforms@7.29.7(@babel/core@7.29.7(supports-color@7.2.0))(supports-color@7.2.0)': dependencies: - '@babel/core': 7.29.7 - '@babel/helper-module-imports': 7.29.7 + '@babel/core': 7.29.7(supports-color@7.2.0) + '@babel/helper-module-imports': 7.29.7(supports-color@7.2.0) '@babel/helper-validator-identifier': 7.29.7 - '@babel/traverse': 7.29.8 + '@babel/traverse': 7.29.8(supports-color@7.2.0) transitivePeerDependencies: - supports-color @@ -2871,14 +2871,14 @@ snapshots: dependencies: '@babel/types': 7.29.8 - '@babel/plugin-transform-react-jsx-self@7.29.7(@babel/core@7.29.7)': + '@babel/plugin-transform-react-jsx-self@7.29.7(@babel/core@7.29.7(supports-color@7.2.0))': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@7.2.0) '@babel/helper-plugin-utils': 7.29.7 - '@babel/plugin-transform-react-jsx-source@7.29.7(@babel/core@7.29.7)': + '@babel/plugin-transform-react-jsx-source@7.29.7(@babel/core@7.29.7(supports-color@7.2.0))': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@7.2.0) '@babel/helper-plugin-utils': 7.29.7 '@babel/template@7.29.7': @@ -2887,7 +2887,7 @@ snapshots: '@babel/parser': 7.29.8 '@babel/types': 7.29.8 - '@babel/traverse@7.29.8': + '@babel/traverse@7.29.8(supports-color@7.2.0)': dependencies: '@babel/code-frame': 7.29.7 '@babel/generator': 7.29.8 @@ -2895,7 +2895,7 @@ snapshots: '@babel/parser': 7.29.8 '@babel/template': 7.29.7 '@babel/types': 7.29.8 - debug: 4.4.3 + debug: 4.4.3(supports-color@7.2.0) transitivePeerDependencies: - supports-color @@ -3011,17 +3011,17 @@ snapshots: '@esbuild/win32-x64@0.28.2': optional: true - '@eslint-community/eslint-utils@4.10.1(eslint@9.39.5(jiti@2.7.0))': + '@eslint-community/eslint-utils@4.10.1(eslint@9.39.5(jiti@2.7.0)(supports-color@7.2.0))': dependencies: - eslint: 9.39.5(jiti@2.7.0) + eslint: 9.39.5(jiti@2.7.0)(supports-color@7.2.0) eslint-visitor-keys: 3.4.3 '@eslint-community/regexpp@4.12.2': {} - '@eslint/config-array@0.21.2': + '@eslint/config-array@0.21.2(supports-color@7.2.0)': dependencies: '@eslint/object-schema': 2.1.7 - debug: 4.4.3 + debug: 4.4.3(supports-color@7.2.0) minimatch: 3.1.5 transitivePeerDependencies: - supports-color @@ -3034,10 +3034,10 @@ snapshots: dependencies: '@types/json-schema': 7.0.15 - '@eslint/eslintrc@3.3.7': + '@eslint/eslintrc@3.3.7(supports-color@7.2.0)': dependencies: ajv: 6.15.0 - debug: 4.4.3 + debug: 4.4.3(supports-color@7.2.0) espree: 10.4.0 globals: 14.0.0 ignore: 5.3.2 @@ -3656,10 +3656,10 @@ snapshots: '@sentry/replay': 10.75.0 '@sentry/replay-canvas': 10.75.0 - '@sentry/bundler-plugins@10.75.0(rollup@4.65.0)': + '@sentry/bundler-plugins@10.75.0(rollup@4.65.0)(supports-color@7.2.0)': dependencies: - '@babel/core': 7.29.7 - '@sentry/cli': 2.58.6 + '@babel/core': 7.29.7(supports-color@7.2.0) + '@sentry/cli': 2.58.6(supports-color@7.2.0) '@sentry/core': 10.75.0 dotenv: 17.4.2 find-up: 5.0.0 @@ -3695,9 +3695,9 @@ snapshots: '@sentry/cli-win32-x64@2.58.6': optional: true - '@sentry/cli@2.58.6': + '@sentry/cli@2.58.6(supports-color@7.2.0)': dependencies: - https-proxy-agent: 5.0.1 + https-proxy-agent: 5.0.1(supports-color@7.2.0) node-fetch: 2.7.0 progress: 2.0.3 proxy-from-env: 1.1.0 @@ -3742,9 +3742,9 @@ snapshots: '@sentry/browser-utils': 10.75.0 '@sentry/core': 10.75.0 - '@sentry/vite-plugin@5.4.0(rollup@4.65.0)': + '@sentry/vite-plugin@5.4.0(rollup@4.65.0)(supports-color@7.2.0)': dependencies: - '@sentry/bundler-plugins': 10.75.0(rollup@4.65.0) + '@sentry/bundler-plugins': 10.75.0(rollup@4.65.0)(supports-color@7.2.0) transitivePeerDependencies: - encoding - rollup @@ -3976,15 +3976,15 @@ snapshots: '@types/trusted-types@2.0.7': optional: true - '@typescript-eslint/eslint-plugin@8.70.0(@typescript-eslint/parser@8.70.0(eslint@9.39.5(jiti@2.7.0))(typescript@5.9.3))(eslint@9.39.5(jiti@2.7.0))(typescript@5.9.3)': + '@typescript-eslint/eslint-plugin@8.70.0(@typescript-eslint/parser@8.70.0(eslint@9.39.5(jiti@2.7.0)(supports-color@7.2.0))(supports-color@7.2.0)(typescript@5.9.3))(eslint@9.39.5(jiti@2.7.0)(supports-color@7.2.0))(supports-color@7.2.0)(typescript@5.9.3)': dependencies: '@eslint-community/regexpp': 4.12.2 - '@typescript-eslint/parser': 8.70.0(eslint@9.39.5(jiti@2.7.0))(typescript@5.9.3) + '@typescript-eslint/parser': 8.70.0(eslint@9.39.5(jiti@2.7.0)(supports-color@7.2.0))(supports-color@7.2.0)(typescript@5.9.3) '@typescript-eslint/scope-manager': 8.70.0 - '@typescript-eslint/type-utils': 8.70.0(eslint@9.39.5(jiti@2.7.0))(typescript@5.9.3) - '@typescript-eslint/utils': 8.70.0(eslint@9.39.5(jiti@2.7.0))(typescript@5.9.3) + '@typescript-eslint/type-utils': 8.70.0(eslint@9.39.5(jiti@2.7.0)(supports-color@7.2.0))(supports-color@7.2.0)(typescript@5.9.3) + '@typescript-eslint/utils': 8.70.0(eslint@9.39.5(jiti@2.7.0)(supports-color@7.2.0))(supports-color@7.2.0)(typescript@5.9.3) '@typescript-eslint/visitor-keys': 8.70.0 - eslint: 9.39.5(jiti@2.7.0) + eslint: 9.39.5(jiti@2.7.0)(supports-color@7.2.0) ignore: 7.0.9 natural-compare: 1.4.0 ts-api-utils: 2.5.0(typescript@5.9.3) @@ -3992,23 +3992,23 @@ snapshots: transitivePeerDependencies: - supports-color - '@typescript-eslint/parser@8.70.0(eslint@9.39.5(jiti@2.7.0))(typescript@5.9.3)': + '@typescript-eslint/parser@8.70.0(eslint@9.39.5(jiti@2.7.0)(supports-color@7.2.0))(supports-color@7.2.0)(typescript@5.9.3)': dependencies: '@typescript-eslint/scope-manager': 8.70.0 '@typescript-eslint/types': 8.70.0 - '@typescript-eslint/typescript-estree': 8.70.0(typescript@5.9.3) + '@typescript-eslint/typescript-estree': 8.70.0(supports-color@7.2.0)(typescript@5.9.3) '@typescript-eslint/visitor-keys': 8.70.0 - debug: 4.4.3 - eslint: 9.39.5(jiti@2.7.0) + debug: 4.4.3(supports-color@7.2.0) + eslint: 9.39.5(jiti@2.7.0)(supports-color@7.2.0) typescript: 5.9.3 transitivePeerDependencies: - supports-color - '@typescript-eslint/project-service@8.70.0(typescript@5.9.3)': + '@typescript-eslint/project-service@8.70.0(supports-color@7.2.0)(typescript@5.9.3)': dependencies: '@typescript-eslint/tsconfig-utils': 8.70.0(typescript@5.9.3) '@typescript-eslint/types': 8.70.0 - debug: 4.4.3 + debug: 4.4.3(supports-color@7.2.0) typescript: 5.9.3 transitivePeerDependencies: - supports-color @@ -4022,13 +4022,13 @@ snapshots: dependencies: typescript: 5.9.3 - '@typescript-eslint/type-utils@8.70.0(eslint@9.39.5(jiti@2.7.0))(typescript@5.9.3)': + '@typescript-eslint/type-utils@8.70.0(eslint@9.39.5(jiti@2.7.0)(supports-color@7.2.0))(supports-color@7.2.0)(typescript@5.9.3)': dependencies: '@typescript-eslint/types': 8.70.0 - '@typescript-eslint/typescript-estree': 8.70.0(typescript@5.9.3) - '@typescript-eslint/utils': 8.70.0(eslint@9.39.5(jiti@2.7.0))(typescript@5.9.3) - debug: 4.4.3 - eslint: 9.39.5(jiti@2.7.0) + '@typescript-eslint/typescript-estree': 8.70.0(supports-color@7.2.0)(typescript@5.9.3) + '@typescript-eslint/utils': 8.70.0(eslint@9.39.5(jiti@2.7.0)(supports-color@7.2.0))(supports-color@7.2.0)(typescript@5.9.3) + debug: 4.4.3(supports-color@7.2.0) + eslint: 9.39.5(jiti@2.7.0)(supports-color@7.2.0) ts-api-utils: 2.5.0(typescript@5.9.3) typescript: 5.9.3 transitivePeerDependencies: @@ -4036,13 +4036,13 @@ snapshots: '@typescript-eslint/types@8.70.0': {} - '@typescript-eslint/typescript-estree@8.70.0(typescript@5.9.3)': + '@typescript-eslint/typescript-estree@8.70.0(supports-color@7.2.0)(typescript@5.9.3)': dependencies: - '@typescript-eslint/project-service': 8.70.0(typescript@5.9.3) + '@typescript-eslint/project-service': 8.70.0(supports-color@7.2.0)(typescript@5.9.3) '@typescript-eslint/tsconfig-utils': 8.70.0(typescript@5.9.3) '@typescript-eslint/types': 8.70.0 '@typescript-eslint/visitor-keys': 8.70.0 - debug: 4.4.3 + debug: 4.4.3(supports-color@7.2.0) minimatch: 10.2.6 semver: 7.8.5 tinyglobby: 0.2.17 @@ -4051,13 +4051,13 @@ snapshots: transitivePeerDependencies: - supports-color - '@typescript-eslint/utils@8.70.0(eslint@9.39.5(jiti@2.7.0))(typescript@5.9.3)': + '@typescript-eslint/utils@8.70.0(eslint@9.39.5(jiti@2.7.0)(supports-color@7.2.0))(supports-color@7.2.0)(typescript@5.9.3)': dependencies: - '@eslint-community/eslint-utils': 4.10.1(eslint@9.39.5(jiti@2.7.0)) + '@eslint-community/eslint-utils': 4.10.1(eslint@9.39.5(jiti@2.7.0)(supports-color@7.2.0)) '@typescript-eslint/scope-manager': 8.70.0 '@typescript-eslint/types': 8.70.0 - '@typescript-eslint/typescript-estree': 8.70.0(typescript@5.9.3) - eslint: 9.39.5(jiti@2.7.0) + '@typescript-eslint/typescript-estree': 8.70.0(supports-color@7.2.0)(typescript@5.9.3) + eslint: 9.39.5(jiti@2.7.0)(supports-color@7.2.0) typescript: 5.9.3 transitivePeerDependencies: - supports-color @@ -4067,11 +4067,11 @@ snapshots: '@typescript-eslint/types': 8.70.0 eslint-visitor-keys: 5.0.1 - '@vitejs/plugin-react@5.2.0(vite@7.3.7(@types/node@24.13.5)(jiti@2.7.0)(lightningcss@1.32.0))': + '@vitejs/plugin-react@5.2.0(supports-color@7.2.0)(vite@7.3.7(@types/node@24.13.5)(jiti@2.7.0)(lightningcss@1.32.0))': dependencies: - '@babel/core': 7.29.7 - '@babel/plugin-transform-react-jsx-self': 7.29.7(@babel/core@7.29.7) - '@babel/plugin-transform-react-jsx-source': 7.29.7(@babel/core@7.29.7) + '@babel/core': 7.29.7(supports-color@7.2.0) + '@babel/plugin-transform-react-jsx-self': 7.29.7(@babel/core@7.29.7(supports-color@7.2.0)) + '@babel/plugin-transform-react-jsx-source': 7.29.7(@babel/core@7.29.7(supports-color@7.2.0)) '@rolldown/pluginutils': 1.0.0-rc.3 '@types/babel__core': 7.20.5 react-refresh: 0.18.0 @@ -4126,9 +4126,9 @@ snapshots: acorn@8.18.0: {} - agent-base@6.0.2: + agent-base@6.0.2(supports-color@7.2.0): dependencies: - debug: 4.4.3 + debug: 4.4.3(supports-color@7.2.0) transitivePeerDependencies: - supports-color @@ -4155,11 +4155,11 @@ snapshots: asynckit@0.4.0: {} - axios@1.20.0: + axios@1.20.0(debug@4.4.3(supports-color@7.2.0))(supports-color@7.2.0): dependencies: - follow-redirects: 1.16.1 + follow-redirects: 1.16.2(debug@4.4.3(supports-color@7.2.0)) form-data: 4.0.6 - https-proxy-agent: 5.0.1 + https-proxy-agent: 5.0.1(supports-color@7.2.0) proxy-from-env: 2.1.0 transitivePeerDependencies: - debug @@ -4273,9 +4273,11 @@ snapshots: date-fns@4.4.0: {} - debug@4.4.3: + debug@4.4.3(supports-color@7.2.0): dependencies: ms: 2.1.3 + optionalDependencies: + supports-color: 7.2.0 decimal.js@10.6.0: {} @@ -4358,13 +4360,13 @@ snapshots: escape-string-regexp@4.0.0: {} - eslint-plugin-react-hooks@5.2.0(eslint@9.39.5(jiti@2.7.0)): + eslint-plugin-react-hooks@5.2.0(eslint@9.39.5(jiti@2.7.0)(supports-color@7.2.0)): dependencies: - eslint: 9.39.5(jiti@2.7.0) + eslint: 9.39.5(jiti@2.7.0)(supports-color@7.2.0) - eslint-plugin-react-refresh@0.4.26(eslint@9.39.5(jiti@2.7.0)): + eslint-plugin-react-refresh@0.4.26(eslint@9.39.5(jiti@2.7.0)(supports-color@7.2.0)): dependencies: - eslint: 9.39.5(jiti@2.7.0) + eslint: 9.39.5(jiti@2.7.0)(supports-color@7.2.0) eslint-scope@8.4.0: dependencies: @@ -4377,14 +4379,14 @@ snapshots: eslint-visitor-keys@5.0.1: {} - eslint@9.39.5(jiti@2.7.0): + eslint@9.39.5(jiti@2.7.0)(supports-color@7.2.0): dependencies: - '@eslint-community/eslint-utils': 4.10.1(eslint@9.39.5(jiti@2.7.0)) + '@eslint-community/eslint-utils': 4.10.1(eslint@9.39.5(jiti@2.7.0)(supports-color@7.2.0)) '@eslint-community/regexpp': 4.12.2 - '@eslint/config-array': 0.21.2 + '@eslint/config-array': 0.21.2(supports-color@7.2.0) '@eslint/config-helpers': 0.4.2 '@eslint/core': 0.17.0 - '@eslint/eslintrc': 3.3.7 + '@eslint/eslintrc': 3.3.7(supports-color@7.2.0) '@eslint/js': 9.39.5 '@eslint/plugin-kit': 0.4.1 '@humanfs/node': 0.16.8 @@ -4394,7 +4396,7 @@ snapshots: ajv: 6.15.0 chalk: 4.1.2 cross-spawn: 7.0.6 - debug: 4.4.3 + debug: 4.4.3(supports-color@7.2.0) escape-string-regexp: 4.0.0 eslint-scope: 8.4.0 eslint-visitor-keys: 4.2.1 @@ -4470,7 +4472,9 @@ snapshots: flatted@3.4.4: {} - follow-redirects@1.16.1: {} + follow-redirects@1.16.2(debug@4.4.3(supports-color@7.2.0)): + optionalDependencies: + debug: 4.4.3(supports-color@7.2.0) form-data@4.0.6: dependencies: @@ -4556,24 +4560,24 @@ snapshots: transitivePeerDependencies: - '@noble/hashes' - http-proxy-agent@7.0.2: + http-proxy-agent@7.0.2(supports-color@7.2.0): dependencies: agent-base: 7.1.4 - debug: 4.4.3 + debug: 4.4.3(supports-color@7.2.0) transitivePeerDependencies: - supports-color - https-proxy-agent@5.0.1: + https-proxy-agent@5.0.1(supports-color@7.2.0): dependencies: - agent-base: 6.0.2 - debug: 4.4.3 + agent-base: 6.0.2(supports-color@7.2.0) + debug: 4.4.3(supports-color@7.2.0) transitivePeerDependencies: - supports-color - https-proxy-agent@7.0.6: + https-proxy-agent@7.0.6(supports-color@7.2.0): dependencies: agent-base: 7.1.4 - debug: 4.4.3 + debug: 4.4.3(supports-color@7.2.0) transitivePeerDependencies: - supports-color @@ -4611,7 +4615,7 @@ snapshots: dependencies: argparse: 2.0.1 - jsdom@27.4.0: + jsdom@27.4.0(supports-color@7.2.0): dependencies: '@acemir/cssom': 0.9.31 '@asamuzakjp/dom-selector': 6.8.1 @@ -4620,8 +4624,8 @@ snapshots: data-urls: 6.0.1 decimal.js: 10.6.0 html-encoding-sniffer: 6.0.0 - http-proxy-agent: 7.0.2 - https-proxy-agent: 7.0.6 + http-proxy-agent: 7.0.2(supports-color@7.2.0) + https-proxy-agent: 7.0.6(supports-color@7.2.0) is-potential-custom-element-name: 1.0.1 parse5: 8.0.1 saxes: 6.0.0 @@ -4956,11 +4960,11 @@ snapshots: semver@7.8.5: {} - seroval-plugins@1.5.6(seroval@1.6.8): + seroval-plugins@1.5.6(seroval@1.7.5): dependencies: - seroval: 1.6.8 + seroval: 1.7.5 - seroval@1.6.8: {} + seroval@1.7.5: {} set-cookie-parser@2.7.2: {} @@ -4975,8 +4979,8 @@ snapshots: solid-js@1.9.15: dependencies: csstype: 3.2.3 - seroval: 1.6.8 - seroval-plugins: 1.5.6(seroval@1.6.8) + seroval: 1.7.5 + seroval-plugins: 1.5.6(seroval@1.7.5) solid-presence@0.2.0(solid-js@1.9.15): dependencies: @@ -5064,13 +5068,13 @@ snapshots: dependencies: prelude-ls: 1.2.1 - typescript-eslint@8.70.0(eslint@9.39.5(jiti@2.7.0))(typescript@5.9.3): + typescript-eslint@8.70.0(eslint@9.39.5(jiti@2.7.0)(supports-color@7.2.0))(supports-color@7.2.0)(typescript@5.9.3): dependencies: - '@typescript-eslint/eslint-plugin': 8.70.0(@typescript-eslint/parser@8.70.0(eslint@9.39.5(jiti@2.7.0))(typescript@5.9.3))(eslint@9.39.5(jiti@2.7.0))(typescript@5.9.3) - '@typescript-eslint/parser': 8.70.0(eslint@9.39.5(jiti@2.7.0))(typescript@5.9.3) - '@typescript-eslint/typescript-estree': 8.70.0(typescript@5.9.3) - '@typescript-eslint/utils': 8.70.0(eslint@9.39.5(jiti@2.7.0))(typescript@5.9.3) - eslint: 9.39.5(jiti@2.7.0) + '@typescript-eslint/eslint-plugin': 8.70.0(@typescript-eslint/parser@8.70.0(eslint@9.39.5(jiti@2.7.0)(supports-color@7.2.0))(supports-color@7.2.0)(typescript@5.9.3))(eslint@9.39.5(jiti@2.7.0)(supports-color@7.2.0))(supports-color@7.2.0)(typescript@5.9.3) + '@typescript-eslint/parser': 8.70.0(eslint@9.39.5(jiti@2.7.0)(supports-color@7.2.0))(supports-color@7.2.0)(typescript@5.9.3) + '@typescript-eslint/typescript-estree': 8.70.0(supports-color@7.2.0)(typescript@5.9.3) + '@typescript-eslint/utils': 8.70.0(eslint@9.39.5(jiti@2.7.0)(supports-color@7.2.0))(supports-color@7.2.0)(typescript@5.9.3) + eslint: 9.39.5(jiti@2.7.0)(supports-color@7.2.0) typescript: 5.9.3 transitivePeerDependencies: - supports-color @@ -5118,7 +5122,7 @@ snapshots: jiti: 2.7.0 lightningcss: 1.32.0 - vitest@4.1.11(@types/node@24.13.5)(jsdom@27.4.0)(vite@7.3.7(@types/node@24.13.5)(jiti@2.7.0)(lightningcss@1.32.0)): + vitest@4.1.11(@types/node@24.13.5)(jsdom@27.4.0(supports-color@7.2.0))(vite@7.3.7(@types/node@24.13.5)(jiti@2.7.0)(lightningcss@1.32.0)): dependencies: '@vitest/expect': 4.1.11 '@vitest/mocker': 4.1.11(vite@7.3.7(@types/node@24.13.5)(jiti@2.7.0)(lightningcss@1.32.0)) @@ -5142,7 +5146,7 @@ snapshots: why-is-node-running: 2.3.0 optionalDependencies: '@types/node': 24.13.5 - jsdom: 27.4.0 + jsdom: 27.4.0(supports-color@7.2.0) transitivePeerDependencies: - msw diff --git a/admin/pnpm-workspace.yaml b/admin/pnpm-workspace.yaml index 0f9721193..d8c27bd41 100644 --- a/admin/pnpm-workspace.yaml +++ b/admin/pnpm-workspace.yaml @@ -20,6 +20,6 @@ overrides: js-yaml: ^4.3.1 nanoid: ^3.3.17 dompurify: ^3.4.17 - follow-redirects: ^1.16.1 - seroval: ^1.6.3 + follow-redirects: ^1.16.2 + seroval: ^1.6.11 source-map-js: ^1.2.2 diff --git a/admin/src/app/dashboard/TestersPage.test.tsx b/admin/src/app/dashboard/TestersPage.test.tsx index 69e468a3d..a6d7ff0b4 100644 --- a/admin/src/app/dashboard/TestersPage.test.tsx +++ b/admin/src/app/dashboard/TestersPage.test.tsx @@ -3,6 +3,7 @@ import { renderToStaticMarkup } from "react-dom/server"; import { MemoryRouter } from "react-router-dom"; import { beforeEach, describe, expect, it, vi } from "vitest"; import type { LoginCodeExemption } from "@/lib/api/models/admin"; +import { ConfirmProvider } from "@/components/ConfirmDialog"; import TestersPage from "./TestersPage"; const access = vi.hoisted(() => ({ canManage: true })); @@ -15,12 +16,24 @@ function render(tester: Partial) { client.setQueryData(["admin", "testers"], { data: [{ user_id: "reviewer", email: "reviewer@example.test", password_expires_at: "2100-01-01T00:00:00Z", ...tester }], }); - const html = renderToStaticMarkup(); + const html = renderToStaticMarkup(); client.clear(); const document = new DOMParser().parseFromString(html, "text/html"); return document; } +describe("tester password re-issue", () => { + beforeEach(() => { access.canManage = true; }); + + it("offers a new password only on accounts created as testers, to managers", () => { + const selector = 'button[aria-label^="Issue new password for"]'; + expect(render({ created_as_tester: true }).querySelector(selector)).not.toBeNull(); + expect(render({ created_as_tester: false }).querySelector(selector)).toBeNull(); + access.canManage = false; + expect(render({ created_as_tester: true }).querySelector(selector)).toBeNull(); + }); +}); + describe("tester sample-data controls", () => { beforeEach(() => { access.canManage = true; }); diff --git a/admin/src/app/dashboard/TestersPage.tsx b/admin/src/app/dashboard/TestersPage.tsx index 0a98b7bc8..c3ca32730 100644 --- a/admin/src/app/dashboard/TestersPage.tsx +++ b/admin/src/app/dashboard/TestersPage.tsx @@ -18,7 +18,7 @@ import { useState } from "react"; import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; import { toast } from "sonner"; -import { AlertTriangle, CopyIcon, FlaskConicalIcon, RotateCw, TrashIcon } from "lucide-react"; +import { AlertTriangle, CopyIcon, FlaskConicalIcon, KeyRoundIcon, RotateCw, TrashIcon } from "lucide-react"; import { PageHeader } from "@/components/layout/PageHeader"; import { Button } from "@/components/ui/button"; import { Input } from "@/components/ui/input"; @@ -29,10 +29,11 @@ import { Callout, EmptyState, Panel, Segmented, StatusBadge } from "@/components import { cn } from "@/lib/utils"; import { useAdminPerm } from "@/hooks/useAdminPerm"; import { AdminPerm } from "@/lib/auth/permissions"; -import { createTester, listTesters, listOrganizationRoles, revokeTester, seedTesterWorkspace } from "@/lib/api/client/admin/testers"; +import { createTester, listTesters, listOrganizationRoles, reissueTesterPassword, revokeTester, seedTesterWorkspace } from "@/lib/api/client/admin/testers"; +import { useConfirm } from "@/components/ConfirmDialog"; import { listOrganizations } from "@/lib/api/client/admin/organizations"; import { DASHBOARD_URL } from "@/lib/env"; -import type { AdminOrgListItem, CreatedTester } from "@/lib/api/models/admin"; +import type { AdminOrgListItem, CreatedTester, ReissuedTesterPassword } from "@/lib/api/models/admin"; function fmt(ts?: string | null) { if (!ts) return "—"; @@ -54,6 +55,9 @@ export default function TestersPage() { // Held in state, never refetched: the server returns it once and cannot // produce it again. const [created, setCreated] = useState(null); + // Same rule for a re-issued password: shown once, from state only. + const [reissued, setReissued] = useState<(ReissuedTesterPassword & { email: string }) | null>(null); + const confirm = useConfirm(); const [sampleTarget, setSampleTarget] = useState<{ organizationID: string; email: string } | null>(null); const testers = useQuery({ @@ -116,6 +120,27 @@ export default function TestersPage() { onError: (e: Error) => toast.error(e.message || "Could not revoke the exemption"), }); + const reissue = useMutation({ + mutationFn: (t: { id: string; email: string }) => reissueTesterPassword(t.id), + onSuccess: (r, t) => { + setReissued({ ...r, email: t.email }); + qc.invalidateQueries({ queryKey: ["admin", "testers"] }); + toast.success("New initial password issued; every session was signed out"); + }, + onError: (e: Error) => toast.error(e.message || "Could not issue a new password"), + }); + + async function onReissue(id: string, email: string) { + const ok = await confirm({ + title: `Issue a new password for ${email}?`, + description: + "The account's current password stops working and every session it holds is signed out. The new password is shown once, is valid for 48 hours and must be changed at first sign-in.", + confirmLabel: "Issue new password", + destructive: true, + }); + if (ok) await reissue.mutateAsync({ id, email }).catch(() => undefined); + } + const seed = useMutation({ mutationFn: (orgID: string) => seedTesterWorkspace(orgID), onSuccess: (result) => { @@ -156,8 +181,9 @@ export default function TestersPage() { holder cannot read this instance's mail, and arrives with onboarding complete. Authentication still requires the password, the captcha and the sign-in risk assessment. A tester either gets a workspace of its own or joins one that already exists. A new Test workspace includes paid-feature access and 100 test credits until the password expires. - An existing workspace keeps its plan and the role you select. Its password stops working on the date you choose, and - revoking it ends the password and signs out every session at once. + An existing workspace keeps its plan and the role you select. The password it is issued is an initial password: valid + for at most 48 hours, it cannot be extended, and the holder must replace it with their own at first sign-in. + Revoking a tester ends its password, issued or chosen, and signs out every session at once. Use Add sample data on an active dedicated Test workspace to populate contacts, a draft campaign, templates and CRM examples. Mailboxes must be connected separately. @@ -177,6 +203,10 @@ export default function TestersPage() { ? "This account is a member of an existing workspace and will land in it on sign-in." : "This account owns a new Test workspace with paid-feature access and 100 test credits until the password expires."} +
+ This is an initial password. It is valid until {fmt(created.password_expires_at)} (48 hours at most) and + must be changed at first sign-in, when the holder is asked to choose their own. +
+ +
+ {[ + ["Email", reissued.email], + ["Password", reissued.password], + ["Valid until", fmt(reissued.password_expires_at)], + ].map(([k, v]) => ( +
+
{k}
+
+ {v} +
+ +
+ ))} +
+ + )} +

@@ -292,7 +362,7 @@ export default function TestersPage() { dot={expired} className="hidden sm:inline-flex" > - Password {expired ? "expired" : "expires"} {fmt(t.password_expires_at)} + Initial password {expired ? "expired" : "valid until"} {fmt(t.password_expires_at)} )} {canManage && ( @@ -308,6 +378,17 @@ export default function TestersPage() { {t.sample_data_seeded_at ? "Sample data added" : "Add sample data"} )} + {t.created_as_tester && ( + + )} '), /inline handlers/); +}); + +test('restricts executable sources while preserving configured analytics and inline presentation', () => { + const directives = new Map(contentSecurityPolicy(new Set(["'sha256-known'"]), 'https://eu.i.posthog.com') + .split('; ').map((value) => { const [name, ...sources] = value.split(' '); return [name, sources]; })); + assert.deepEqual(directives.get('default-src'), ["'none'"]); + assert.deepEqual(directives.get('script-src-attr'), ["'none'"]); + assert.deepEqual(directives.get('frame-ancestors'), ["'none'"]); + const scripts = directives.get('script-src'); + assert.ok(scripts.includes("'sha256-known'")); + assert.ok(scripts.includes('https://eu-assets.i.posthog.com')); + assert.ok(!scripts.includes("'unsafe-inline'") && !scripts.includes("'unsafe-eval'")); + assert.ok(directives.get('style-src').includes("'unsafe-inline'")); + assert.ok(!contentSecurityPolicy(new Set()).includes('posthog')); + assert.throws(() => contentSecurityPolicy(new Set(), 'http://analytics.example.com'), /HTTPS/); + assert.throws(() => contentSecurityPolicy(new Set(), 'https://user:password@example.com'), /HTTPS/); +}); + +test('emits one catch-all header from every generated page and refuses oversized or duplicate policies', async () => { + const root = await mkdtemp(join(tmpdir(), 'marketing-csp-')); + const dir = pathToFileURL(`${root}/`); + const inherited = Object.entries(process.env).filter(([name]) => name.startsWith('PUBLIC_POSTHOG_')); + for (const [name] of inherited) delete process.env[name]; + try { + await writeFile(join(root, '.env.production'), 'PUBLIC_POSTHOG_KEY=test\nPUBLIC_POSTHOG_HOST=https://analytics.example.com/ingest\n'); + await mkdir(join(root, 'terms')); + await writeFile(join(root, 'index.html'), ''); + await writeFile(join(root, 'terms/index.html'), ''); + const baseline = '/*\n X-Frame-Options: DENY\n/_astro/*\n Cache-Control: public\n'; + await writeFile(join(root, '_headers'), baseline); + const { hooks } = integration(); + let vite; + hooks['astro:config:setup']({ updateConfig: config => { vite = config.vite; } }); + vite.plugins[0].configResolved({ mode: 'production', envDir: root }); + const build = () => hooks['astro:build:done']({ dir, logger: { info() {} } }); + await build(); + const headers = await readFile(join(root, '_headers'), 'utf8'); + assert.ok(headers.startsWith('/*\n Content-Security-Policy:')); + for (const code of ['window.home=true', 'window.legal=true']) { + assert.ok(headers.includes(createHash('sha256').update(code).digest('base64'))); + } + assert.ok(headers.includes('https://analytics.example.com')); + assert.ok(headers.includes('X-Frame-Options: DENY')); + assert.ok(headers.includes('/_astro/*\n Cache-Control: public')); + await assert.rejects(build(), /already configured/); + const assetsOnly = '/_astro/*\n Cache-Control: public\n'; + await writeFile(join(root, '_headers'), assetsOnly); + await assert.rejects(build(), /catch-all rule/); + assert.equal(await readFile(join(root, '_headers'), 'utf8'), assetsOnly); + const reordered = '/_astro/*\r\n Cache-Control: public\r\n/* \t\r\n X-Frame-Options: DENY\r\n'; + await writeFile(join(root, '_headers'), reordered); + await build(); + const reorderedHeaders = await readFile(join(root, '_headers'), 'utf8'); + assert.ok(reorderedHeaders.startsWith('/_astro/*\r\n Cache-Control: public\r\n/* \t\r\n Content-Security-Policy:')); + assert.ok(reorderedHeaders.includes('\r\n X-Frame-Options: DENY\r\n')); + await mkdir(join(root, 'config')); + await writeFile(join(root, 'config/.env.staging'), 'PUBLIC_POSTHOG_KEY=test\nPUBLIC_POSTHOG_HOST=https://staging-analytics.example.com\n'); + vite.plugins[0].configResolved({ mode: 'staging', envDir: join(root, 'config') }); + await writeFile(join(root, '_headers'), baseline); + await build(); + const stagingHeaders = await readFile(join(root, '_headers'), 'utf8'); + assert.ok(stagingHeaders.includes('https://staging-analytics.example.com')); + assert.ok(!stagingHeaders.includes('https://analytics.example.com')); + process.env.PUBLIC_POSTHOG_KEY = 'test'; + process.env.PUBLIC_POSTHOG_HOST = 'https://configured-analytics.example.com'; + vite.plugins[0].configResolved({ mode: 'production', envDir: root }); + await writeFile(join(root, '_headers'), baseline); + await build(); + assert.ok((await readFile(join(root, '_headers'), 'utf8')).includes('https://configured-analytics.example.com')); + await writeFile(join(root, '_headers'), baseline); + await writeFile(join(root, 'index.html'), Array.from({ length: 40 }, (_, i) => ``).join('')); + await assert.rejects(build(), /header limit/); + assert.equal(await readFile(join(root, '_headers'), 'utf8'), baseline); + } finally { + for (const name of Object.keys(process.env).filter(name => name.startsWith('PUBLIC_POSTHOG_'))) delete process.env[name]; + for (const [name, value] of inherited) process.env[name] = value; + await rm(root, { recursive: true, force: true }); + } +}); diff --git a/site/src/components/scenes/warmup/ConversationScene.astro b/site/src/components/scenes/warmup/ConversationScene.astro index 6824a7552..05fbf32d7 100644 --- a/site/src/components/scenes/warmup/ConversationScene.astro +++ b/site/src/components/scenes/warmup/ConversationScene.astro @@ -5,9 +5,8 @@ import Ico from './Ico.astro'; import { WINDOW, FLOAT, EYEBROW } from '../../../lib/scene'; /** - * A warmup thread as a pool partner's own mail client shows it: plain text, - * labelled as a simulated diagnostic (the content bank in - * internal/tasks/template.go), filed in the Warmbly folder. The card shows + * A warmup thread as a pool partner's own mail client shows it: plain text + * from the conversation library (internal/tasks/warmup_library_*.go), filed in the Warmbly folder. The card shows * what Warmbly checked when the copy arrived, one step at a time. */ const folders = [ @@ -20,12 +19,12 @@ const folders = [ { icon: 'folder', name: 'Warmbly', n: '6', active: true }, ] as const; const threads = [ - { who: 'Alex Kim', n: 3, subject: 'Simulated diagnostic: fictional clock', preview: 'Agreed. The example is closed; no real meeting was scheduled.', time: '2:41 PM', active: true }, - { who: 'Ravi Shah', n: 2, subject: 'Simulated diagnostic: sample count', preview: 'There are 5 cards in the hypothetical sample: 3 blue and 2 green.', time: '1:58 PM' }, - { who: 'me, Lena', n: 2, subject: 'Simulated diagnostic: conditional wording', preview: 'The hypothetical status is pending review: no approval exists…', time: '11:20 AM' }, - { who: 'Max Weber', n: 1, subject: 'Simulated diagnostic: summary correction', preview: 'A fictional checklist has 12 items: 9 marked complete and 3…', time: 'Oct 8' }, - { who: 'me, Kai', n: 3, subject: 'Simulated diagnostic: plaintext label review', preview: 'Yes. Status: unknown and Next step: review are written in the…', time: 'Oct 8' }, - { who: 'Sam Ortiz', n: 1, subject: 'Simulated diagnostic: fixed-offset date note', preview: 'On 2026-10-08 the fictional clock reads 09:00 UTC, or 11:00…', time: 'Oct 7' }, + { who: 'Alex Kim', n: 3, subject: 'Podcasts for long drives', preview: 'The craftspeople one is exactly my kind of thing. I will load a…', time: '2:41 PM', active: true }, + { who: 'Ravi Shah', n: 2, subject: 'Picking a body font', preview: "I've narrowed it down to a serif and a sans serif, and I like…", time: '1:58 PM' }, + { who: 'me, Lena', n: 2, subject: 'Shorter meetings', preview: 'We cut our standing team meeting from an hour to thirty minutes…', time: '11:20 AM' }, + { who: 'Max Weber', n: 1, subject: 'Switching to tea', preview: 'Lately I have been trying to cut back on coffee and have started…', time: 'Oct 8' }, + { who: 'me, Kai', n: 3, subject: 'Weekend trail suggestions', preview: 'We are thinking about a day hike this weekend, something moderate…', time: 'Oct 8' }, + { who: 'Sam Ortiz', n: 1, subject: 'Finally sorted my backups', preview: 'I finally sorted out backups for my work files after a scare…', time: 'Oct 7' }, ] as const; const checks = [ { k: 'Token', v: 'Matched, now spent', icon: 'key' }, @@ -76,7 +75,7 @@ const checks = [
- Simulated diagnostic: fictional clock + Podcasts for long drives Warmbly
@@ -87,7 +86,7 @@ const checks = [ alex@northwind.dev 10:12 AM
-

Simulated diagnostic. In this fictional example, the clock reads 14:00, not 15:00. Which time does the example use?

+

Got a long drive coming up and I am tired of my usual playlist. What podcasts are you into these days?

@@ -96,16 +95,16 @@ const checks = [ to Alex 12:47 PM
-

The fictional example uses 14:00, not 15:00.

+

Mostly history ones. There is a show that takes one strange historical episode and spends a whole season on it. I also like an interview series with craftspeople talking about how they learned their trade.

AK Alex Kim - Re: Simulated diagnostic: fictional clock + Re: Podcasts for long drives 2:41 PM
-

Agreed. The example is closed; no real meeting was scheduled.

+

The craftspeople one is exactly my kind of thing. I will load a few episodes before I leave.

text/plain no tracking pixel diff --git a/site/src/pages/warmup.astro b/site/src/pages/warmup.astro index 68efeb5bb..f972ea489 100644 --- a/site/src/pages/warmup.astro +++ b/site/src/pages/warmup.astro @@ -107,9 +107,9 @@ const link = 'group mt-6 inline-flex items-center gap-2 text-[16px] md:text-[17p
- +

- Each message is plain text with no tracking pixel and opens with "Simulated diagnostic", so nobody mistakes it for a real conversation. Partners write back on their own schedule, about three times in ten by default, and each thread closes after a few turns. + Each message is plain text with no tracking pixel, on everyday topics that vary in tone and length, and conversations rotate so the same mailbox rarely gets the same one twice. Partners write back on their own schedule, about three times in ten by default, and each thread closes after a few turns.

diff --git a/tracking/Cargo.lock b/tracking/Cargo.lock index ab384392a..9cb431094 100644 --- a/tracking/Cargo.lock +++ b/tracking/Cargo.lock @@ -82,6 +82,45 @@ dependencies = [ "rustversion", ] +[[package]] +name = "asn1-rs" +version = "0.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7f43a50ac4fdca5df8e885c21b835997f0a1cdee65494a6847694a98652d9d8" +dependencies = [ + "asn1-rs-derive", + "asn1-rs-impl", + "displaydoc", + "nom", + "num-traits", + "rusticata-macros", + "thiserror", + "time", +] + +[[package]] +name = "asn1-rs-derive" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3109e49b1e4909e9db6515a30c633684d68cdeaa252f215214cb4fa1a5bfee2c" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", + "synstructure 0.13.2", +] + +[[package]] +name = "asn1-rs-impl" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b18050c2cd6fe86c3a76584ef5e0baf286d038cda203eb6223df2cc413565f7" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "async-lock" version = "3.4.2" @@ -659,6 +698,28 @@ dependencies = [ "tracing", ] +[[package]] +name = "axum-server" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1df331683d982a0b9492b38127151e6453639cd34926eb9c07d4cd8c6d22bfc" +dependencies = [ + "arc-swap", + "bytes", + "either", + "fs-err", + "http 1.5.0", + "http-body 1.1.0", + "hyper", + "hyper-util", + "pin-project-lite", + "rustls", + "rustls-pki-types", + "tokio", + "tokio-rustls", + "tower-service", +] + [[package]] name = "backtrace" version = "0.3.76" @@ -722,6 +783,15 @@ dependencies = [ "serde", ] +[[package]] +name = "bit-vec" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b71798fca2c1fe1086445a7258a4bc81e6e49dcd24c8d0dd9a1e57395b603f51" +dependencies = [ + "serde", +] + [[package]] name = "bitflags" version = "2.13.2" @@ -1125,6 +1195,20 @@ dependencies = [ "zeroize", ] +[[package]] +name = "der-parser" +version = "10.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "07da5016415d5a3c4dd39b11ed26f915f52fc4e0dc197d87908bc916e51bc1a6" +dependencies = [ + "asn1-rs", + "displaydoc", + "nom", + "num-bigint", + "num-traits", + "rusticata-macros", +] + [[package]] name = "deranged" version = "0.5.8" @@ -1316,6 +1400,16 @@ dependencies = [ "percent-encoding", ] +[[package]] +name = "fs-err" +version = "3.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b5c95b673b8f6f7235229ae11c5642d81b04c2e64c1e2fb417bc0cf73ca45f29" +dependencies = [ + "autocfg", + "tokio", +] + [[package]] name = "fs_extra" version = "1.3.0" @@ -1934,9 +2028,9 @@ checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981" [[package]] name = "libz-sys" -version = "1.1.29" +version = "1.1.31" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "85bc9657773828b90eeb625adff10eeac83cc21bbfd8e23a03eaa8a33c9e28d9" +checksum = "ff20308ecabd635a2dc1dd5834a86c462cca20efba1d5d3ddab1f8aea3455cb2" dependencies = [ "cc", "libc", @@ -2016,6 +2110,12 @@ version = "0.3.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a" +[[package]] +name = "minimal-lexical" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a" + [[package]] name = "miniz_oxide" version = "0.8.9" @@ -2110,6 +2210,16 @@ dependencies = [ "signatory", ] +[[package]] +name = "nom" +version = "7.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a" +dependencies = [ + "memchr", + "minimal-lexical", +] + [[package]] name = "nu-ansi-term" version = "0.50.3" @@ -2353,6 +2463,15 @@ dependencies = [ "memchr", ] +[[package]] +name = "oid-registry" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12f40cff3dde1b6087cc5d5f5d4d65712f34016a03ed60e9c08dcc392736b5b7" +dependencies = [ + "asn1-rs", +] + [[package]] name = "once_cell" version = "1.21.4" @@ -2453,6 +2572,16 @@ dependencies = [ "windows-link", ] +[[package]] +name = "pem" +version = "4.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d354a98a3d1251555de99e8fdd8afda05573c31b82f59063a7b0a29b5527f120" +dependencies = [ + "base64 0.23.1", + "serde_core", +] + [[package]] name = "pem-rfc7468" version = "0.7.0" @@ -2743,6 +2872,20 @@ dependencies = [ "rand_core 0.10.1", ] +[[package]] +name = "rcgen" +version = "0.14.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8774e05a7d0de114588e6a28fe7e71694b82614ed569d86d8b389dfbc98b8ad8" +dependencies = [ + "pem", + "ring", + "rustls-pki-types", + "time", + "x509-parser", + "yasna", +] + [[package]] name = "rdkafka" version = "0.36.2" @@ -2936,6 +3079,15 @@ dependencies = [ "semver", ] +[[package]] +name = "rusticata-macros" +version = "4.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "faf0c4a6ece9950b9abdb62b1cfcf2a68b3b67a10ba445b3bb85be2a293d0632" +dependencies = [ + "nom", +] + [[package]] name = "rustix" version = "1.1.5" @@ -3500,6 +3652,17 @@ dependencies = [ "futures-core", ] +[[package]] +name = "synstructure" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "synstructure" version = "0.14.0" @@ -3875,12 +4038,14 @@ dependencies = [ "aws-sdk-secretsmanager", "aws-sdk-ssm", "axum", + "axum-server", "base64 0.21.7", "chrono", "flate2", "ipnet", "maxminddb", "moka", + "rcgen", "rdkafka", "reqwest 0.12.28", "rustls", @@ -4342,6 +4507,24 @@ version = "0.6.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" +[[package]] +name = "x509-parser" +version = "0.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d43b0f71ce057da06bc0851b23ee24f3f86190b07203dd8f567d0b706a185202" +dependencies = [ + "asn1-rs", + "data-encoding", + "der-parser", + "lazy_static", + "nom", + "oid-registry", + "ring", + "rusticata-macros", + "thiserror", + "time", +] + [[package]] name = "xattr" version = "1.6.1" @@ -4358,6 +4541,16 @@ version = "0.13.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "66fee0b777b0f5ac1c69bb06d361268faafa61cd4682ae064a171c16c433e9e4" +[[package]] +name = "yasna" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b5f6765e852b9b4dc8e2a76843e4d64d1cea8e79bcde0b6901aea8e7c7f08282" +dependencies = [ + "bit-vec", + "time", +] + [[package]] name = "yoke" version = "0.8.3" @@ -4378,7 +4571,7 @@ dependencies = [ "proc-macro2", "quote", "syn 3.0.6", - "synstructure", + "synstructure 0.14.0", ] [[package]] @@ -4419,7 +4612,7 @@ dependencies = [ "proc-macro2", "quote", "syn 3.0.6", - "synstructure", + "synstructure 0.14.0", ] [[package]] diff --git a/tracking/Cargo.toml b/tracking/Cargo.toml index b82cb99e1..e60baeaa4 100644 --- a/tracking/Cargo.toml +++ b/tracking/Cargo.toml @@ -45,6 +45,12 @@ schema_registry_converter = { version = "4.0", features = ["avro", "blocking"], # OpenSSL system libraries. reqwest = { version = "0.12", default-features = false, features = ["blocking", "json", "rustls-tls"] } +# Opt-in TLS listener (SERVE_TLS). No provider feature: main installs ring, +# so aws-lc-rs is not pulled in for it. rcgen makes the in-memory self-signed +# certificate, on ring for the same reason. +axum-server = { version = "0.8", default-features = false, features = ["tls-rustls-no-provider"] } +rcgen = { version = "0.14", default-features = false, features = ["crypto", "pem", "ring"] } + # Utils uuid = { version = "1", features = ["v4", "serde"] } serde = { version = "1", features = ["derive"] } diff --git a/tracking/Dockerfile b/tracking/Dockerfile index 291ce2f67..1220cc86c 100644 --- a/tracking/Dockerfile +++ b/tracking/Dockerfile @@ -58,6 +58,7 @@ USER tracking EXPOSE 3000 # 127.0.0.1, not localhost: busybox wget tries ::1 first but the server binds IPv4. +# SERVE_TLS adds a TLS listener and keeps this plain one, on loopback at least. HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \ CMD wget --no-verbose --tries=1 --spider http://127.0.0.1:3000/health || exit 1 diff --git a/tracking/src/hits.rs b/tracking/src/hits.rs index 26082199e..e76bb75b9 100644 --- a/tracking/src/hits.rs +++ b/tracking/src/hits.rs @@ -150,7 +150,7 @@ pub struct HitForwarder { impl HitForwarder { pub fn new(backend_url: String, internal_token: String) -> Self { Self { - http: reqwest::Client::builder() + http: crate::serve_tls::backend_client() .timeout(Duration::from_secs(3)) .build() .expect("reqwest client"), diff --git a/tracking/src/links.rs b/tracking/src/links.rs index 8ea1c7335..7ac2f2516 100644 --- a/tracking/src/links.rs +++ b/tracking/src/links.rs @@ -82,7 +82,7 @@ pub struct LinkResolver { impl LinkResolver { pub fn new(backend_url: String, internal_token: String) -> Self { Self { - http: reqwest::Client::builder() + http: crate::serve_tls::backend_client() .timeout(Duration::from_secs(3)) .build() .expect("reqwest client"), diff --git a/tracking/src/main.rs b/tracking/src/main.rs index b82115a65..735479fae 100644 --- a/tracking/src/main.rs +++ b/tracking/src/main.rs @@ -14,6 +14,7 @@ mod posthog; mod producer; mod redirects; mod scanners; +mod serve_tls; mod unsubscribe; mod unsubscribe_i18n; @@ -106,6 +107,21 @@ async fn main() { .with(tracing_subscriber::fmt::layer()) .init(); + let listeners = match serve_tls::Listeners::from_env(|k| std::env::var(k).ok()) { + Ok(l) => l, + Err(e) => { + observability::report_issue("Invalid TLS listener setting", &e); + std::process::exit(1); + } + }; + match serve_tls::load_backend_roots(|k| std::env::var(k).ok()) { + Ok(roots) => serve_tls::init_backend_roots(roots), + Err(e) => { + observability::report_issue("Invalid BACKEND_INTERNAL_CA", &e); + std::process::exit(1); + } + } + // Load configuration with env-first approach let config = match Config::load().await { Ok(c) => c, @@ -188,7 +204,8 @@ async fn main() { .with_state(state); // Start server - let addr: SocketAddr = match config.addr().parse() { + let plain_addr = format!("{}:{}", listeners.plain_host(&config.host), config.port); + let addr: SocketAddr = match plain_addr.parse() { Ok(a) => a, Err(e) => { observability::report_issue("Invalid tracking listen address", &e.to_string()); @@ -207,15 +224,49 @@ async fn main() { } }; + let secure = match &listeners.tls { + Some(tls) => match tls.rustls_config().await { + Ok(rustls) => { + let tls_addr = SocketAddr::from(([0, 0, 0, 0], tls.port)); + info!("Tracking service listening with TLS on {}", tls_addr); + let service = app + .clone() + .into_make_service_with_connect_info::(); + Some(tokio::spawn(async move { + axum_server::bind_rustls(tls_addr, rustls) + .serve(service) + .await + })) + } + Err(e) => { + observability::report_issue("TLS listener", &e); + observability::flush(); + std::process::exit(1); + } + }, + None => None, + }; + // Connect info carries the socket peer, which is the client unless it is a // trusted proxy (TRACKING_TRUSTED_PROXIES). - if let Err(e) = axum::serve( + let plain = axum::serve( listener, app.into_make_service_with_connect_info::(), - ) - .await - { - observability::report_issue("Tracking server terminated unexpectedly", &e.to_string()); + ); + let failure = match secure { + // Either listener ending takes the service down, so the orchestrator replaces it. + Some(secure) => Some(tokio::select! { + r = plain => r.err().map_or_else(|| "plain listener stopped".to_string(), |e| e.to_string()), + r = secure => match r { + Ok(Ok(())) => "TLS listener stopped".to_string(), + Ok(Err(e)) => e.to_string(), + Err(e) => e.to_string(), + }, + }), + None => plain.await.err().map(|e| e.to_string()), + }; + if let Some(e) = failure { + observability::report_issue("Tracking server terminated unexpectedly", &e); observability::flush(); std::process::exit(1); } diff --git a/tracking/src/redirects.rs b/tracking/src/redirects.rs index ffee097bb..e27e05d5d 100644 --- a/tracking/src/redirects.rs +++ b/tracking/src/redirects.rs @@ -68,7 +68,7 @@ pub fn normalize_host(raw: &str) -> Option { impl RedirectResolver { pub fn new(backend_url: String, internal_token: String) -> Self { Self { - http: reqwest::Client::builder() + http: crate::serve_tls::backend_client() .timeout(Duration::from_secs(3)) .redirect(reqwest::redirect::Policy::none()) .build() diff --git a/tracking/src/serve_tls.rs b/tracking/src/serve_tls.rs new file mode 100644 index 000000000..29bed93c1 --- /dev/null +++ b/tracking/src/serve_tls.rs @@ -0,0 +1,328 @@ +//! Opt-in TLS listener beside the plain one, and pinned trust for the backend; unset, nothing changes. + +use std::sync::OnceLock; + +use axum_server::tls_rustls::RustlsConfig; + +/// Where a PEM value comes from: the variable itself, or a file it names. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Pem { + Inline(String), + File(String), +} + +impl Pem { + fn read(&self) -> Result, String> { + match self { + Pem::Inline(v) => Ok(v.clone().into_bytes()), + Pem::File(p) => std::fs::read(p).map_err(|e| format!("cannot read {p}: {e}")), + } + } +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Mode { + SelfSigned, + Supplied { cert: Pem, key: Pem }, +} + +/// The TLS listener read from SERVE_TLS and its companions. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ServeTls { + pub mode: Mode, + pub port: u16, +} + +/// The listener shape: the TLS half, if any, and whether the plain half is loopback only. +#[derive(Clone, Debug, PartialEq, Eq, Default)] +pub struct Listeners { + pub tls: Option, + pub http_loopback_only: bool, +} + +fn pem_from(get: &impl Fn(&str) -> Option, name: &str) -> Result { + let inline = get(name).filter(|v| !v.trim().is_empty()); + let file = get(&format!("{name}_FILE")) + .map(|v| v.trim().to_string()) + .filter(|v| !v.is_empty()); + match (inline, file) { + (Some(v), None) => Ok(Pem::Inline(v)), + (None, Some(p)) => Ok(Pem::File(p)), + _ => Err(format!( + "SERVE_TLS=supplied needs exactly one of {name} and {name}_FILE" + )), + } +} + +impl Listeners { + pub fn from_env(get: impl Fn(&str) -> Option) -> Result { + let trimmed = |k: &str| { + get(k) + .map(|v| v.trim().to_string()) + .filter(|v| !v.is_empty()) + }; + let http_loopback_only = match trimmed("SERVE_HTTP_LOOPBACK_ONLY").as_deref() { + None | Some("false") | Some("0") => false, + Some("true") | Some("1") => true, + Some(other) => { + return Err(format!( + "SERVE_HTTP_LOOPBACK_ONLY must be true or false, got {other:?}" + )) + } + }; + let mode = match trimmed("SERVE_TLS") + .map(|v| v.to_ascii_lowercase()) + .as_deref() + { + None | Some("off") | Some("false") => { + if http_loopback_only { + return Err("SERVE_HTTP_LOOPBACK_ONLY=true needs SERVE_TLS, or nothing outside the container can reach the service".into()); + } + return Ok(Self::default()); + } + Some("self-signed") => Mode::SelfSigned, + Some("supplied") => Mode::Supplied { + cert: pem_from(&get, "SERVE_TLS_CERT")?, + key: pem_from(&get, "SERVE_TLS_KEY")?, + }, + Some(other) => { + return Err(format!( + "SERVE_TLS must be self-signed or supplied, got {other:?}" + )) + } + }; + let port = trimmed("SERVE_TLS_PORT") + .and_then(|v| v.parse::().ok()) + .filter(|p| *p != 0) + .ok_or("SERVE_TLS needs SERVE_TLS_PORT set to a port number")?; + Ok(Self { + tls: Some(ServeTls { mode, port }), + http_loopback_only, + }) + } + + /// The plain listener's host, moved to loopback when confined. + pub fn plain_host<'a>(&self, host: &'a str) -> &'a str { + if self.http_loopback_only { + "127.0.0.1" + } else { + host + } + } +} + +/// An in-memory ECDSA P-256 certificate; a load balancer does not validate its targets'. +pub fn self_signed_pem() -> Result<(String, String), String> { + let key = + rcgen::KeyPair::generate_for(&rcgen::PKCS_ECDSA_P256_SHA256).map_err(|e| e.to_string())?; + let mut params = + rcgen::CertificateParams::new(vec!["localhost".to_string()]).map_err(|e| e.to_string())?; + params.extended_key_usages = vec![rcgen::ExtendedKeyUsagePurpose::ServerAuth]; + let cert = params.self_signed(&key).map_err(|e| e.to_string())?; + Ok((cert.pem(), key.serialize_pem())) +} + +impl ServeTls { + /// The server configuration; rustls speaks nothing older than TLS 1.2. + pub async fn rustls_config(&self) -> Result { + let (cert, key) = match &self.mode { + Mode::SelfSigned => { + let (c, k) = self_signed_pem()?; + (c.into_bytes(), k.into_bytes()) + } + Mode::Supplied { cert, key } => (cert.read()?, key.read()?), + }; + RustlsConfig::from_pem(cert, key) + .await + .map_err(|_| "the TLS certificate and key are not a matching PEM pair".to_string()) + } +} + +static BACKEND_ROOTS: OnceLock> = OnceLock::new(); + +/// Reads BACKEND_INTERNAL_CA (or its _FILE), the only trust the backend's certificate is verified against. +pub fn load_backend_roots( + get: impl Fn(&str) -> Option, +) -> Result, String> { + let inline = get("BACKEND_INTERNAL_CA").filter(|v| !v.trim().is_empty()); + let file = get("BACKEND_INTERNAL_CA_FILE") + .map(|v| v.trim().to_string()) + .filter(|v| !v.is_empty()); + let pem = match (inline, file) { + (None, None) => return Ok(Vec::new()), + (Some(v), None) => Pem::Inline(v), + (None, Some(p)) => Pem::File(p), + _ => return Err("set one of BACKEND_INTERNAL_CA and BACKEND_INTERNAL_CA_FILE".into()), + }; + let certs = reqwest::Certificate::from_pem_bundle(&pem.read()?) + .map_err(|_| "BACKEND_INTERNAL_CA holds no readable PEM certificate".to_string())?; + if certs.is_empty() { + return Err("BACKEND_INTERNAL_CA holds no PEM certificate".into()); + } + Ok(certs) +} + +/// Records the backend trust for every client built afterwards; call once at boot. +pub fn init_backend_roots(roots: Vec) { + let _ = BACKEND_ROOTS.set(roots); +} + +/// A client builder for the backend's internal API, pinned to BACKEND_INTERNAL_CA when it is set. +pub fn backend_client() -> reqwest::ClientBuilder { + with_roots( + reqwest::Client::builder(), + BACKEND_ROOTS.get().map(Vec::as_slice).unwrap_or_default(), + ) +} + +fn with_roots( + mut builder: reqwest::ClientBuilder, + roots: &[reqwest::Certificate], +) -> reqwest::ClientBuilder { + if roots.is_empty() { + return builder; + } + builder = builder.tls_built_in_root_certs(false); + for cert in roots { + builder = builder.add_root_certificate(cert.clone()); + } + builder +} + +#[cfg(test)] +mod tests { + use super::*; + use std::collections::HashMap; + use std::net::SocketAddr; + + fn env(pairs: &[(&str, &str)]) -> impl Fn(&str) -> Option { + let map: HashMap = pairs + .iter() + .map(|(k, v)| (k.to_string(), v.to_string())) + .collect(); + move |k: &str| map.get(k).cloned() + } + + #[test] + fn unset_is_plain() { + assert_eq!(Listeners::from_env(env(&[])).unwrap(), Listeners::default()); + assert_eq!( + Listeners::from_env(env(&[("SERVE_TLS", "off")])).unwrap(), + Listeners::default() + ); + assert_eq!(Listeners::default().plain_host("0.0.0.0"), "0.0.0.0"); + } + + #[test] + fn reads_each_mode() { + let l = Listeners::from_env(env(&[ + ("SERVE_TLS", "self-signed"), + ("SERVE_TLS_PORT", "8443"), + ("SERVE_HTTP_LOOPBACK_ONLY", "true"), + ])) + .unwrap(); + assert_eq!( + l.tls, + Some(ServeTls { + mode: Mode::SelfSigned, + port: 8443 + }) + ); + assert_eq!(l.plain_host("0.0.0.0"), "127.0.0.1"); + let l = Listeners::from_env(env(&[ + ("SERVE_TLS", "supplied"), + ("SERVE_TLS_PORT", "443"), + ("SERVE_TLS_CERT", "c"), + ("SERVE_TLS_KEY_FILE", "/k"), + ])) + .unwrap(); + assert_eq!( + l.tls.unwrap().mode, + Mode::Supplied { + cert: Pem::Inline("c".into()), + key: Pem::File("/k".into()) + } + ); + } + + #[test] + fn refuses_incomplete_settings() { + for pairs in [ + vec![("SERVE_TLS", "self-signed")], + vec![("SERVE_TLS", "self-signed"), ("SERVE_TLS_PORT", "0")], + vec![("SERVE_TLS", "yes"), ("SERVE_TLS_PORT", "8443")], + vec![ + ("SERVE_TLS", "supplied"), + ("SERVE_TLS_PORT", "8443"), + ("SERVE_TLS_CERT", "c"), + ], + vec![ + ("SERVE_TLS", "supplied"), + ("SERVE_TLS_PORT", "8443"), + ("SERVE_TLS_CERT", "c"), + ("SERVE_TLS_CERT_FILE", "/c"), + ("SERVE_TLS_KEY", "k"), + ], + vec![("SERVE_HTTP_LOOPBACK_ONLY", "true")], + vec![("SERVE_HTTP_LOOPBACK_ONLY", "maybe")], + ] { + assert!( + Listeners::from_env(env(&pairs)).is_err(), + "{pairs:?} was accepted" + ); + } + } + + #[test] + fn backend_roots() { + assert!(load_backend_roots(env(&[])).unwrap().is_empty()); + assert!(load_backend_roots(env(&[("BACKEND_INTERNAL_CA", "not pem")])).is_err()); + let (cert, _) = self_signed_pem().unwrap(); + assert_eq!( + load_backend_roots(env(&[("BACKEND_INTERNAL_CA", &cert)])) + .unwrap() + .len(), + 1 + ); + } + + #[tokio::test] + async fn pinned_client_reaches_a_self_signed_listener() { + let _ = rustls::crypto::ring::default_provider().install_default(); + let (cert, key) = self_signed_pem().unwrap(); + let tls = ServeTls { + mode: Mode::Supplied { + cert: Pem::Inline(cert.clone()), + key: Pem::Inline(key), + }, + port: 1, + }; + let config = tls.rustls_config().await.unwrap(); + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let addr: SocketAddr = listener.local_addr().unwrap(); + let app = axum::Router::new().route("/health", axum::routing::get(|| async { "ok" })); + listener.set_nonblocking(true).unwrap(); + let server = axum_server::from_tcp_rustls(listener, config).unwrap(); + tokio::spawn(server.serve(app.into_make_service())); + + let roots = load_backend_roots(env(&[("BACKEND_INTERNAL_CA", &cert)])).unwrap(); + let url = format!("https://localhost:{}/health", addr.port()); + let pinned = with_roots(reqwest::Client::builder(), &roots) + .build() + .unwrap(); + assert_eq!( + pinned.get(&url).send().await.unwrap().text().await.unwrap(), + "ok" + ); + + let (stranger, _) = self_signed_pem().unwrap(); + let other = load_backend_roots(env(&[("BACKEND_INTERNAL_CA", &stranger)])).unwrap(); + let untrusting = with_roots(reqwest::Client::builder(), &other) + .build() + .unwrap(); + assert!( + untrusting.get(&url).send().await.is_err(), + "an untrusted certificate was accepted" + ); + } +} diff --git a/tracking/src/unsubscribe.rs b/tracking/src/unsubscribe.rs index ec5972d1b..8728a8b51 100644 --- a/tracking/src/unsubscribe.rs +++ b/tracking/src/unsubscribe.rs @@ -45,7 +45,7 @@ pub struct UnsubscribeProxy { impl UnsubscribeProxy { pub fn new(backend_url: String) -> Self { Self { - http: reqwest::Client::builder() + http: crate::serve_tls::backend_client() .timeout(Duration::from_secs(5)) // A redirect would take the recipient off this host; the // backend's own pages are same-path forms, so there is diff --git a/web/pnpm-lock.yaml b/web/pnpm-lock.yaml index 913b65214..a228b753a 100644 --- a/web/pnpm-lock.yaml +++ b/web/pnpm-lock.yaml @@ -10,8 +10,8 @@ overrides: js-yaml: ^4.3.1 nanoid: ^3.3.17 dompurify: ^3.4.17 - follow-redirects: ^1.16.1 - seroval: ^1.6.3 + follow-redirects: ^1.16.2 + seroval: ^1.6.11 source-map-js: ^1.2.2 importers: @@ -200,7 +200,7 @@ importers: version: 3.0.2 axios: specifier: ^1.20.0 - version: 1.20.0 + version: 1.20.0(debug@4.4.3(supports-color@7.2.0))(supports-color@7.2.0) class-variance-authority: specifier: ^0.7.1 version: 0.7.1 @@ -285,7 +285,7 @@ importers: version: 9.39.5 '@sentry/vite-plugin': specifier: ^5.4.0 - version: 5.4.0(rollup@4.65.0) + version: 5.4.0(rollup@4.65.0)(supports-color@7.2.0) '@testing-library/jest-dom': specifier: ^6.10.0 version: 6.10.0(@testing-library/dom@10.4.1) @@ -303,25 +303,25 @@ importers: version: 19.3.0(@types/react@19.3.0) '@vitejs/plugin-react': specifier: ^5.2.0 - version: 5.2.0(vite@7.3.7(@types/node@24.13.5)(jiti@2.7.0)(lightningcss@1.32.0)) + version: 5.2.0(supports-color@7.2.0)(vite@7.3.7(@types/node@24.13.5)(jiti@2.7.0)(lightningcss@1.32.0)) '@vitest/coverage-v8': specifier: ^4.1.11 version: 4.1.11(vitest@4.1.11) eslint: specifier: ^9.39.5 - version: 9.39.5(jiti@2.7.0) + version: 9.39.5(jiti@2.7.0)(supports-color@7.2.0) eslint-plugin-react-hooks: specifier: ^5.2.0 - version: 5.2.0(eslint@9.39.5(jiti@2.7.0)) + version: 5.2.0(eslint@9.39.5(jiti@2.7.0)(supports-color@7.2.0)) eslint-plugin-react-refresh: specifier: ^0.4.26 - version: 0.4.26(eslint@9.39.5(jiti@2.7.0)) + version: 0.4.26(eslint@9.39.5(jiti@2.7.0)(supports-color@7.2.0)) globals: specifier: ^16.5.0 version: 16.5.0 jsdom: specifier: ^27.4.0 - version: 27.4.0 + version: 27.4.0(supports-color@7.2.0) tw-animate-css: specifier: ^1.4.0 version: 1.4.0 @@ -330,13 +330,13 @@ importers: version: 5.9.3 typescript-eslint: specifier: ^8.70.0 - version: 8.70.0(eslint@9.39.5(jiti@2.7.0))(typescript@5.9.3) + version: 8.70.0(eslint@9.39.5(jiti@2.7.0)(supports-color@7.2.0))(supports-color@7.2.0)(typescript@5.9.3) vite: specifier: ^7.3.7 version: 7.3.7(@types/node@24.13.5)(jiti@2.7.0)(lightningcss@1.32.0) vitest: specifier: ^4.1.11 - version: 4.1.11(@types/node@24.13.5)(@vitest/coverage-v8@4.1.11)(jsdom@27.4.0)(vite@7.3.7(@types/node@24.13.5)(jiti@2.7.0)(lightningcss@1.32.0)) + version: 4.1.11(@types/node@24.13.5)(@vitest/coverage-v8@4.1.11)(jsdom@27.4.0(supports-color@7.2.0))(vite@7.3.7(@types/node@24.13.5)(jiti@2.7.0)(lightningcss@1.32.0)) packages: @@ -2559,8 +2559,8 @@ packages: flatted@3.4.4: resolution: {integrity: sha512-5+ybhBZANEJxaH3X5evAFatUxLfEHSr7n6kYJ+1Qd0mUqr4eu9gIf6GDbWHf8RJijHrjjO8G+la14SlL2SeS1Q==} - follow-redirects@1.16.1: - resolution: {integrity: sha512-FNvFGzoMLWmE6Yj9spb/zjd7yiNCHiAW9/Tg9CXrQ8wuu32HtlJOwWO11OJafl5FfY3DxTdQ0vj42zU1kvv5jg==} + follow-redirects@1.16.2: + resolution: {integrity: sha512-/kVP2U8z596Ia0gwFrwyIeo74ta5aVmSeU1FfAUMAmcEP5EP7zydmag3SLiN64NaRKef3lxsq7i/g7ltJQDGow==} engines: {node: '>=4.0'} peerDependencies: debug: '*' @@ -3233,17 +3233,17 @@ packages: resolution: {integrity: sha512-HXuLAX2pu/UByPpaeo/TaMfvMIi+1QqIoPJYCcAtU8QkVNwgR6MPlGuCQTErV1JwraaMbYaWVIBX7mppzGLATQ==} engines: {node: '>=10'} peerDependencies: - seroval: ^1.6.3 + seroval: ^1.6.11 seroval-plugins@1.6.8: resolution: {integrity: sha512-N7mWAMydj89EnYTHtRpS3LBrAz3J9O6oVrqpuXuvlAHfAUG8WEKqtbAd7SBiJNY5NfCAFhSdyAh7wI4Shjqy4g==} engines: {node: '>=10'} peerDependencies: - seroval: ^1.6.3 + seroval: ^1.6.11 - seroval@1.6.8: - resolution: {integrity: sha512-HlSgSAkTk4EqHcje1ptJjfZi1YDv5KbhVJ/d3P7T/nAXua2VmDu+AKDX5VTdFfZf48nDkWB2TKYt0DrCSa+3wg==} - engines: {node: '>=10'} + seroval@1.7.5: + resolution: {integrity: sha512-UdNgpHdq0gVpme5JdQF+S3jNscnjFr4NTwUWOc1qcOa8OuWZmbV0+YX2hsqxkUZshBpHnpxDZfAKVZG2ugbrJA==} + engines: {node: '>=20'} shebang-command@2.0.0: resolution: {integrity: sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==} @@ -3634,20 +3634,20 @@ snapshots: '@babel/compat-data@7.29.7': {} - '@babel/core@7.29.7': + '@babel/core@7.29.7(supports-color@7.2.0)': dependencies: '@babel/code-frame': 7.29.7 '@babel/generator': 7.29.8 '@babel/helper-compilation-targets': 7.29.7 - '@babel/helper-module-transforms': 7.29.7(@babel/core@7.29.7) + '@babel/helper-module-transforms': 7.29.7(@babel/core@7.29.7(supports-color@7.2.0))(supports-color@7.2.0) '@babel/helpers': 7.29.7 '@babel/parser': 7.29.8 '@babel/template': 7.29.7 - '@babel/traverse': 7.29.8 + '@babel/traverse': 7.29.8(supports-color@7.2.0) '@babel/types': 7.29.8 '@jridgewell/remapping': 2.3.5 convert-source-map: 2.0.0 - debug: 4.4.3 + debug: 4.4.3(supports-color@7.2.0) gensync: 1.0.0-beta.2 json5: 2.2.3 semver: 6.3.1 @@ -3672,19 +3672,19 @@ snapshots: '@babel/helper-globals@7.29.7': {} - '@babel/helper-module-imports@7.29.7': + '@babel/helper-module-imports@7.29.7(supports-color@7.2.0)': dependencies: - '@babel/traverse': 7.29.8 + '@babel/traverse': 7.29.8(supports-color@7.2.0) '@babel/types': 7.29.8 transitivePeerDependencies: - supports-color - '@babel/helper-module-transforms@7.29.7(@babel/core@7.29.7)': + '@babel/helper-module-transforms@7.29.7(@babel/core@7.29.7(supports-color@7.2.0))(supports-color@7.2.0)': dependencies: - '@babel/core': 7.29.7 - '@babel/helper-module-imports': 7.29.7 + '@babel/core': 7.29.7(supports-color@7.2.0) + '@babel/helper-module-imports': 7.29.7(supports-color@7.2.0) '@babel/helper-validator-identifier': 7.29.7 - '@babel/traverse': 7.29.8 + '@babel/traverse': 7.29.8(supports-color@7.2.0) transitivePeerDependencies: - supports-color @@ -3705,14 +3705,14 @@ snapshots: dependencies: '@babel/types': 7.29.8 - '@babel/plugin-transform-react-jsx-self@7.29.7(@babel/core@7.29.7)': + '@babel/plugin-transform-react-jsx-self@7.29.7(@babel/core@7.29.7(supports-color@7.2.0))': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@7.2.0) '@babel/helper-plugin-utils': 7.29.7 - '@babel/plugin-transform-react-jsx-source@7.29.7(@babel/core@7.29.7)': + '@babel/plugin-transform-react-jsx-source@7.29.7(@babel/core@7.29.7(supports-color@7.2.0))': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@7.2.0) '@babel/helper-plugin-utils': 7.29.7 '@babel/runtime@7.29.10': {} @@ -3725,7 +3725,7 @@ snapshots: '@babel/parser': 7.29.8 '@babel/types': 7.29.8 - '@babel/traverse@7.29.8': + '@babel/traverse@7.29.8(supports-color@7.2.0)': dependencies: '@babel/code-frame': 7.29.7 '@babel/generator': 7.29.8 @@ -3733,7 +3733,7 @@ snapshots: '@babel/parser': 7.29.8 '@babel/template': 7.29.7 '@babel/types': 7.29.8 - debug: 4.4.3 + debug: 4.4.3(supports-color@7.2.0) transitivePeerDependencies: - supports-color @@ -3876,17 +3876,17 @@ snapshots: '@esbuild/win32-x64@0.28.2': optional: true - '@eslint-community/eslint-utils@4.10.1(eslint@9.39.5(jiti@2.7.0))': + '@eslint-community/eslint-utils@4.10.1(eslint@9.39.5(jiti@2.7.0)(supports-color@7.2.0))': dependencies: - eslint: 9.39.5(jiti@2.7.0) + eslint: 9.39.5(jiti@2.7.0)(supports-color@7.2.0) eslint-visitor-keys: 3.4.3 '@eslint-community/regexpp@4.12.2': {} - '@eslint/config-array@0.21.2': + '@eslint/config-array@0.21.2(supports-color@7.2.0)': dependencies: '@eslint/object-schema': 2.1.7 - debug: 4.4.3 + debug: 4.4.3(supports-color@7.2.0) minimatch: 3.1.5 transitivePeerDependencies: - supports-color @@ -3899,10 +3899,10 @@ snapshots: dependencies: '@types/json-schema': 7.0.15 - '@eslint/eslintrc@3.3.7': + '@eslint/eslintrc@3.3.7(supports-color@7.2.0)': dependencies: ajv: 6.15.0 - debug: 4.4.3 + debug: 4.4.3(supports-color@7.2.0) espree: 10.4.0 globals: 14.0.0 ignore: 5.3.2 @@ -4669,10 +4669,10 @@ snapshots: '@sentry/replay': 10.75.0 '@sentry/replay-canvas': 10.75.0 - '@sentry/bundler-plugins@10.75.0(rollup@4.65.0)': + '@sentry/bundler-plugins@10.75.0(rollup@4.65.0)(supports-color@7.2.0)': dependencies: - '@babel/core': 7.29.7 - '@sentry/cli': 2.58.6 + '@babel/core': 7.29.7(supports-color@7.2.0) + '@sentry/cli': 2.58.6(supports-color@7.2.0) '@sentry/core': 10.75.0 dotenv: 17.4.2 find-up: 5.0.0 @@ -4708,9 +4708,9 @@ snapshots: '@sentry/cli-win32-x64@2.58.6': optional: true - '@sentry/cli@2.58.6': + '@sentry/cli@2.58.6(supports-color@7.2.0)': dependencies: - https-proxy-agent: 5.0.1 + https-proxy-agent: 5.0.1(supports-color@7.2.0) node-fetch: 2.7.0 progress: 2.0.3 proxy-from-env: 1.1.0 @@ -4755,9 +4755,9 @@ snapshots: '@sentry/browser-utils': 10.75.0 '@sentry/core': 10.75.0 - '@sentry/vite-plugin@5.4.0(rollup@4.65.0)': + '@sentry/vite-plugin@5.4.0(rollup@4.65.0)(supports-color@7.2.0)': dependencies: - '@sentry/bundler-plugins': 10.75.0(rollup@4.65.0) + '@sentry/bundler-plugins': 10.75.0(rollup@4.65.0)(supports-color@7.2.0) transitivePeerDependencies: - encoding - rollup @@ -4968,8 +4968,8 @@ snapshots: dependencies: '@tanstack/history': 1.162.4 cookie-es: 3.1.1 - seroval: 1.6.8 - seroval-plugins: 1.6.8(seroval@1.6.8) + seroval: 1.7.5 + seroval-plugins: 1.6.8(seroval@1.7.5) '@tanstack/store@0.11.2': {} @@ -5197,15 +5197,15 @@ snapshots: '@types/use-sync-external-store@0.0.6': {} - '@typescript-eslint/eslint-plugin@8.70.0(@typescript-eslint/parser@8.70.0(eslint@9.39.5(jiti@2.7.0))(typescript@5.9.3))(eslint@9.39.5(jiti@2.7.0))(typescript@5.9.3)': + '@typescript-eslint/eslint-plugin@8.70.0(@typescript-eslint/parser@8.70.0(eslint@9.39.5(jiti@2.7.0)(supports-color@7.2.0))(supports-color@7.2.0)(typescript@5.9.3))(eslint@9.39.5(jiti@2.7.0)(supports-color@7.2.0))(supports-color@7.2.0)(typescript@5.9.3)': dependencies: '@eslint-community/regexpp': 4.12.2 - '@typescript-eslint/parser': 8.70.0(eslint@9.39.5(jiti@2.7.0))(typescript@5.9.3) + '@typescript-eslint/parser': 8.70.0(eslint@9.39.5(jiti@2.7.0)(supports-color@7.2.0))(supports-color@7.2.0)(typescript@5.9.3) '@typescript-eslint/scope-manager': 8.70.0 - '@typescript-eslint/type-utils': 8.70.0(eslint@9.39.5(jiti@2.7.0))(typescript@5.9.3) - '@typescript-eslint/utils': 8.70.0(eslint@9.39.5(jiti@2.7.0))(typescript@5.9.3) + '@typescript-eslint/type-utils': 8.70.0(eslint@9.39.5(jiti@2.7.0)(supports-color@7.2.0))(supports-color@7.2.0)(typescript@5.9.3) + '@typescript-eslint/utils': 8.70.0(eslint@9.39.5(jiti@2.7.0)(supports-color@7.2.0))(supports-color@7.2.0)(typescript@5.9.3) '@typescript-eslint/visitor-keys': 8.70.0 - eslint: 9.39.5(jiti@2.7.0) + eslint: 9.39.5(jiti@2.7.0)(supports-color@7.2.0) ignore: 7.0.9 natural-compare: 1.4.0 ts-api-utils: 2.5.0(typescript@5.9.3) @@ -5213,23 +5213,23 @@ snapshots: transitivePeerDependencies: - supports-color - '@typescript-eslint/parser@8.70.0(eslint@9.39.5(jiti@2.7.0))(typescript@5.9.3)': + '@typescript-eslint/parser@8.70.0(eslint@9.39.5(jiti@2.7.0)(supports-color@7.2.0))(supports-color@7.2.0)(typescript@5.9.3)': dependencies: '@typescript-eslint/scope-manager': 8.70.0 '@typescript-eslint/types': 8.70.0 - '@typescript-eslint/typescript-estree': 8.70.0(typescript@5.9.3) + '@typescript-eslint/typescript-estree': 8.70.0(supports-color@7.2.0)(typescript@5.9.3) '@typescript-eslint/visitor-keys': 8.70.0 - debug: 4.4.3 - eslint: 9.39.5(jiti@2.7.0) + debug: 4.4.3(supports-color@7.2.0) + eslint: 9.39.5(jiti@2.7.0)(supports-color@7.2.0) typescript: 5.9.3 transitivePeerDependencies: - supports-color - '@typescript-eslint/project-service@8.70.0(typescript@5.9.3)': + '@typescript-eslint/project-service@8.70.0(supports-color@7.2.0)(typescript@5.9.3)': dependencies: '@typescript-eslint/tsconfig-utils': 8.70.0(typescript@5.9.3) '@typescript-eslint/types': 8.70.0 - debug: 4.4.3 + debug: 4.4.3(supports-color@7.2.0) typescript: 5.9.3 transitivePeerDependencies: - supports-color @@ -5243,13 +5243,13 @@ snapshots: dependencies: typescript: 5.9.3 - '@typescript-eslint/type-utils@8.70.0(eslint@9.39.5(jiti@2.7.0))(typescript@5.9.3)': + '@typescript-eslint/type-utils@8.70.0(eslint@9.39.5(jiti@2.7.0)(supports-color@7.2.0))(supports-color@7.2.0)(typescript@5.9.3)': dependencies: '@typescript-eslint/types': 8.70.0 - '@typescript-eslint/typescript-estree': 8.70.0(typescript@5.9.3) - '@typescript-eslint/utils': 8.70.0(eslint@9.39.5(jiti@2.7.0))(typescript@5.9.3) - debug: 4.4.3 - eslint: 9.39.5(jiti@2.7.0) + '@typescript-eslint/typescript-estree': 8.70.0(supports-color@7.2.0)(typescript@5.9.3) + '@typescript-eslint/utils': 8.70.0(eslint@9.39.5(jiti@2.7.0)(supports-color@7.2.0))(supports-color@7.2.0)(typescript@5.9.3) + debug: 4.4.3(supports-color@7.2.0) + eslint: 9.39.5(jiti@2.7.0)(supports-color@7.2.0) ts-api-utils: 2.5.0(typescript@5.9.3) typescript: 5.9.3 transitivePeerDependencies: @@ -5257,13 +5257,13 @@ snapshots: '@typescript-eslint/types@8.70.0': {} - '@typescript-eslint/typescript-estree@8.70.0(typescript@5.9.3)': + '@typescript-eslint/typescript-estree@8.70.0(supports-color@7.2.0)(typescript@5.9.3)': dependencies: - '@typescript-eslint/project-service': 8.70.0(typescript@5.9.3) + '@typescript-eslint/project-service': 8.70.0(supports-color@7.2.0)(typescript@5.9.3) '@typescript-eslint/tsconfig-utils': 8.70.0(typescript@5.9.3) '@typescript-eslint/types': 8.70.0 '@typescript-eslint/visitor-keys': 8.70.0 - debug: 4.4.3 + debug: 4.4.3(supports-color@7.2.0) minimatch: 10.2.6 semver: 7.8.5 tinyglobby: 0.2.17 @@ -5272,13 +5272,13 @@ snapshots: transitivePeerDependencies: - supports-color - '@typescript-eslint/utils@8.70.0(eslint@9.39.5(jiti@2.7.0))(typescript@5.9.3)': + '@typescript-eslint/utils@8.70.0(eslint@9.39.5(jiti@2.7.0)(supports-color@7.2.0))(supports-color@7.2.0)(typescript@5.9.3)': dependencies: - '@eslint-community/eslint-utils': 4.10.1(eslint@9.39.5(jiti@2.7.0)) + '@eslint-community/eslint-utils': 4.10.1(eslint@9.39.5(jiti@2.7.0)(supports-color@7.2.0)) '@typescript-eslint/scope-manager': 8.70.0 '@typescript-eslint/types': 8.70.0 - '@typescript-eslint/typescript-estree': 8.70.0(typescript@5.9.3) - eslint: 9.39.5(jiti@2.7.0) + '@typescript-eslint/typescript-estree': 8.70.0(supports-color@7.2.0)(typescript@5.9.3) + eslint: 9.39.5(jiti@2.7.0)(supports-color@7.2.0) typescript: 5.9.3 transitivePeerDependencies: - supports-color @@ -5288,11 +5288,11 @@ snapshots: '@typescript-eslint/types': 8.70.0 eslint-visitor-keys: 5.0.1 - '@vitejs/plugin-react@5.2.0(vite@7.3.7(@types/node@24.13.5)(jiti@2.7.0)(lightningcss@1.32.0))': + '@vitejs/plugin-react@5.2.0(supports-color@7.2.0)(vite@7.3.7(@types/node@24.13.5)(jiti@2.7.0)(lightningcss@1.32.0))': dependencies: - '@babel/core': 7.29.7 - '@babel/plugin-transform-react-jsx-self': 7.29.7(@babel/core@7.29.7) - '@babel/plugin-transform-react-jsx-source': 7.29.7(@babel/core@7.29.7) + '@babel/core': 7.29.7(supports-color@7.2.0) + '@babel/plugin-transform-react-jsx-self': 7.29.7(@babel/core@7.29.7(supports-color@7.2.0)) + '@babel/plugin-transform-react-jsx-source': 7.29.7(@babel/core@7.29.7(supports-color@7.2.0)) '@rolldown/pluginutils': 1.0.0-rc.3 '@types/babel__core': 7.20.5 react-refresh: 0.18.0 @@ -5312,7 +5312,7 @@ snapshots: obug: 2.2.1 std-env: 4.2.0 tinyrainbow: 3.1.1 - vitest: 4.1.11(@types/node@24.13.5)(@vitest/coverage-v8@4.1.11)(jsdom@27.4.0)(vite@7.3.7(@types/node@24.13.5)(jiti@2.7.0)(lightningcss@1.32.0)) + vitest: 4.1.11(@types/node@24.13.5)(@vitest/coverage-v8@4.1.11)(jsdom@27.4.0(supports-color@7.2.0))(vite@7.3.7(@types/node@24.13.5)(jiti@2.7.0)(lightningcss@1.32.0)) '@vitest/expect@4.1.11': dependencies: @@ -5369,9 +5369,9 @@ snapshots: acorn@8.18.0: {} - agent-base@6.0.2: + agent-base@6.0.2(supports-color@7.2.0): dependencies: - debug: 4.4.3 + debug: 4.4.3(supports-color@7.2.0) transitivePeerDependencies: - supports-color @@ -5414,11 +5414,11 @@ snapshots: asynckit@0.4.0: {} - axios@1.20.0: + axios@1.20.0(debug@4.4.3(supports-color@7.2.0))(supports-color@7.2.0): dependencies: - follow-redirects: 1.16.1 + follow-redirects: 1.16.2(debug@4.4.3(supports-color@7.2.0)) form-data: 4.0.6 - https-proxy-agent: 5.0.1 + https-proxy-agent: 5.0.1(supports-color@7.2.0) proxy-from-env: 2.1.0 transitivePeerDependencies: - debug @@ -5534,9 +5534,11 @@ snapshots: date-fns@4.4.0: {} - debug@4.4.3: + debug@4.4.3(supports-color@7.2.0): dependencies: ms: 2.1.3 + optionalDependencies: + supports-color: 7.2.0 decimal.js@10.6.0: {} @@ -5625,13 +5627,13 @@ snapshots: escape-string-regexp@4.0.0: {} - eslint-plugin-react-hooks@5.2.0(eslint@9.39.5(jiti@2.7.0)): + eslint-plugin-react-hooks@5.2.0(eslint@9.39.5(jiti@2.7.0)(supports-color@7.2.0)): dependencies: - eslint: 9.39.5(jiti@2.7.0) + eslint: 9.39.5(jiti@2.7.0)(supports-color@7.2.0) - eslint-plugin-react-refresh@0.4.26(eslint@9.39.5(jiti@2.7.0)): + eslint-plugin-react-refresh@0.4.26(eslint@9.39.5(jiti@2.7.0)(supports-color@7.2.0)): dependencies: - eslint: 9.39.5(jiti@2.7.0) + eslint: 9.39.5(jiti@2.7.0)(supports-color@7.2.0) eslint-scope@8.4.0: dependencies: @@ -5644,14 +5646,14 @@ snapshots: eslint-visitor-keys@5.0.1: {} - eslint@9.39.5(jiti@2.7.0): + eslint@9.39.5(jiti@2.7.0)(supports-color@7.2.0): dependencies: - '@eslint-community/eslint-utils': 4.10.1(eslint@9.39.5(jiti@2.7.0)) + '@eslint-community/eslint-utils': 4.10.1(eslint@9.39.5(jiti@2.7.0)(supports-color@7.2.0)) '@eslint-community/regexpp': 4.12.2 - '@eslint/config-array': 0.21.2 + '@eslint/config-array': 0.21.2(supports-color@7.2.0) '@eslint/config-helpers': 0.4.2 '@eslint/core': 0.17.0 - '@eslint/eslintrc': 3.3.7 + '@eslint/eslintrc': 3.3.7(supports-color@7.2.0) '@eslint/js': 9.39.5 '@eslint/plugin-kit': 0.4.1 '@humanfs/node': 0.16.8 @@ -5661,7 +5663,7 @@ snapshots: ajv: 6.15.0 chalk: 4.1.2 cross-spawn: 7.0.6 - debug: 4.4.3 + debug: 4.4.3(supports-color@7.2.0) escape-string-regexp: 4.0.0 eslint-scope: 8.4.0 eslint-visitor-keys: 4.2.1 @@ -5741,7 +5743,9 @@ snapshots: flatted@3.4.4: {} - follow-redirects@1.16.1: {} + follow-redirects@1.16.2(debug@4.4.3(supports-color@7.2.0)): + optionalDependencies: + debug: 4.4.3(supports-color@7.2.0) form-data@4.0.6: dependencies: @@ -5831,24 +5835,24 @@ snapshots: html-to-image@1.11.13: {} - http-proxy-agent@7.0.2: + http-proxy-agent@7.0.2(supports-color@7.2.0): dependencies: agent-base: 7.1.4 - debug: 4.4.3 + debug: 4.4.3(supports-color@7.2.0) transitivePeerDependencies: - supports-color - https-proxy-agent@5.0.1: + https-proxy-agent@5.0.1(supports-color@7.2.0): dependencies: - agent-base: 6.0.2 - debug: 4.4.3 + agent-base: 6.0.2(supports-color@7.2.0) + debug: 4.4.3(supports-color@7.2.0) transitivePeerDependencies: - supports-color - https-proxy-agent@7.0.6: + https-proxy-agent@7.0.6(supports-color@7.2.0): dependencies: agent-base: 7.1.4 - debug: 4.4.3 + debug: 4.4.3(supports-color@7.2.0) transitivePeerDependencies: - supports-color @@ -5907,7 +5911,7 @@ snapshots: dependencies: argparse: 2.0.1 - jsdom@27.4.0: + jsdom@27.4.0(supports-color@7.2.0): dependencies: '@acemir/cssom': 0.9.31 '@asamuzakjp/dom-selector': 6.8.1 @@ -5916,8 +5920,8 @@ snapshots: data-urls: 6.0.1 decimal.js: 10.6.0 html-encoding-sniffer: 6.0.0 - http-proxy-agent: 7.0.2 - https-proxy-agent: 7.0.6 + http-proxy-agent: 7.0.2(supports-color@7.2.0) + https-proxy-agent: 7.0.6(supports-color@7.2.0) is-potential-custom-element-name: 1.0.1 parse5: 8.0.1 saxes: 6.0.0 @@ -6370,15 +6374,15 @@ snapshots: semver@7.8.5: {} - seroval-plugins@1.5.6(seroval@1.6.8): + seroval-plugins@1.5.6(seroval@1.7.5): dependencies: - seroval: 1.6.8 + seroval: 1.7.5 - seroval-plugins@1.6.8(seroval@1.6.8): + seroval-plugins@1.6.8(seroval@1.7.5): dependencies: - seroval: 1.6.8 + seroval: 1.7.5 - seroval@1.6.8: {} + seroval@1.7.5: {} shebang-command@2.0.0: dependencies: @@ -6391,8 +6395,8 @@ snapshots: solid-js@1.9.15: dependencies: csstype: 3.2.3 - seroval: 1.6.8 - seroval-plugins: 1.5.6(seroval@1.6.8) + seroval: 1.7.5 + seroval-plugins: 1.5.6(seroval@1.7.5) solid-presence@0.2.0(solid-js@1.9.15): dependencies: @@ -6486,13 +6490,13 @@ snapshots: dependencies: prelude-ls: 1.2.1 - typescript-eslint@8.70.0(eslint@9.39.5(jiti@2.7.0))(typescript@5.9.3): + typescript-eslint@8.70.0(eslint@9.39.5(jiti@2.7.0)(supports-color@7.2.0))(supports-color@7.2.0)(typescript@5.9.3): dependencies: - '@typescript-eslint/eslint-plugin': 8.70.0(@typescript-eslint/parser@8.70.0(eslint@9.39.5(jiti@2.7.0))(typescript@5.9.3))(eslint@9.39.5(jiti@2.7.0))(typescript@5.9.3) - '@typescript-eslint/parser': 8.70.0(eslint@9.39.5(jiti@2.7.0))(typescript@5.9.3) - '@typescript-eslint/typescript-estree': 8.70.0(typescript@5.9.3) - '@typescript-eslint/utils': 8.70.0(eslint@9.39.5(jiti@2.7.0))(typescript@5.9.3) - eslint: 9.39.5(jiti@2.7.0) + '@typescript-eslint/eslint-plugin': 8.70.0(@typescript-eslint/parser@8.70.0(eslint@9.39.5(jiti@2.7.0)(supports-color@7.2.0))(supports-color@7.2.0)(typescript@5.9.3))(eslint@9.39.5(jiti@2.7.0)(supports-color@7.2.0))(supports-color@7.2.0)(typescript@5.9.3) + '@typescript-eslint/parser': 8.70.0(eslint@9.39.5(jiti@2.7.0)(supports-color@7.2.0))(supports-color@7.2.0)(typescript@5.9.3) + '@typescript-eslint/typescript-estree': 8.70.0(supports-color@7.2.0)(typescript@5.9.3) + '@typescript-eslint/utils': 8.70.0(eslint@9.39.5(jiti@2.7.0)(supports-color@7.2.0))(supports-color@7.2.0)(typescript@5.9.3) + eslint: 9.39.5(jiti@2.7.0)(supports-color@7.2.0) typescript: 5.9.3 transitivePeerDependencies: - supports-color @@ -6544,7 +6548,7 @@ snapshots: jiti: 2.7.0 lightningcss: 1.32.0 - vitest@4.1.11(@types/node@24.13.5)(@vitest/coverage-v8@4.1.11)(jsdom@27.4.0)(vite@7.3.7(@types/node@24.13.5)(jiti@2.7.0)(lightningcss@1.32.0)): + vitest@4.1.11(@types/node@24.13.5)(@vitest/coverage-v8@4.1.11)(jsdom@27.4.0(supports-color@7.2.0))(vite@7.3.7(@types/node@24.13.5)(jiti@2.7.0)(lightningcss@1.32.0)): dependencies: '@vitest/expect': 4.1.11 '@vitest/mocker': 4.1.11(vite@7.3.7(@types/node@24.13.5)(jiti@2.7.0)(lightningcss@1.32.0)) @@ -6569,7 +6573,7 @@ snapshots: optionalDependencies: '@types/node': 24.13.5 '@vitest/coverage-v8': 4.1.11(vitest@4.1.11) - jsdom: 27.4.0 + jsdom: 27.4.0(supports-color@7.2.0) transitivePeerDependencies: - msw diff --git a/web/pnpm-workspace.yaml b/web/pnpm-workspace.yaml index 7693ac87e..29ebf3dec 100644 --- a/web/pnpm-workspace.yaml +++ b/web/pnpm-workspace.yaml @@ -23,6 +23,6 @@ overrides: js-yaml: ^4.3.1 nanoid: ^3.3.17 dompurify: ^3.4.17 - follow-redirects: ^1.16.1 - seroval: ^1.6.3 + follow-redirects: ^1.16.2 + seroval: ^1.6.11 source-map-js: ^1.2.2 diff --git a/web/src/app/app/emails/page.test.tsx b/web/src/app/app/emails/page.test.tsx index bc5d1b667..447f9c3a0 100644 --- a/web/src/app/app/emails/page.test.tsx +++ b/web/src/app/app/emails/page.test.tsx @@ -6,11 +6,13 @@ import type Inbox from "@/lib/api/models/app/emails/Inbox"; import type Tag from "@/lib/api/models/app/Tag"; import type * as UserModule from "@/hooks/context/user"; import type AccountStatus from "@/lib/api/models/app/analytics/AccountStatus"; +import type { CloudLinkMailboxRow } from "@/lib/api/models/app/cloudlink/CloudLink"; import AddressesPage from "./page"; -const { tags, rows, statusState, confirm } = vi.hoisted(() => ({ +const { tags, rows, statusState, confirm, cloudRows } = vi.hoisted(() => ({ confirm: vi.fn(), - statusState: { data: [] as AccountStatus[], observations: [] as { status: AccountStatus; observedAt: number; current: boolean }[], isLoading: false, isFetching: false, isError: false, cloudLoading: false, cloudUnavailable: false, emailsLoading: false, emailsError: false, emailsIncomplete: false }, + cloudRows: new Map(), + statusState: { data: [] as AccountStatus[], observations: [] as { status: AccountStatus; observedAt: number; current: boolean }[], isLoading: false, isFetching: false, isError: false, cloudConnected: false, cloudLoading: false, cloudUnavailable: false, emailsLoading: false, emailsError: false, emailsIncomplete: false }, tags: [ { id: "sending", title: "Sending account", color: "#0088cc", position: 0 }, { id: "serveblink", title: "Serveblink.com", color: "#008800", position: 1 }, @@ -38,7 +40,7 @@ vi.mock("@/lib/api/hooks/app/subscription/useFeatureStatus", () => ({ default: ( vi.mock("@/lib/api/hooks/auth/useAuthConfig", () => ({ default: () => ({ data: {}, isLoading: false }) })); vi.mock("@/lib/api/hooks/app/emails/useMailboxGrants", () => ({ useSigninMigration: () => ({ data: { data: [] } }) })); vi.mock("@/lib/api/hooks/app/advisor/useAdvisor", () => ({ useAdvisorEntityIndex: () => ({ get: () => [] }) })); -vi.mock("@/hooks/useCloudPool", () => ({ default: () => ({ selfHosted: false, connected: false, loading: statusState.cloudLoading, unavailable: statusState.cloudUnavailable, observedAt: 0, rowFor: () => undefined }) })); +vi.mock("@/hooks/useCloudPool", () => ({ default: () => ({ selfHosted: false, connected: statusState.cloudConnected, loading: statusState.cloudLoading, unavailable: statusState.cloudUnavailable, observedAt: 0, rowFor: (id: string) => cloudRows.get(id) }) })); vi.mock("@/lib/api/hooks/app/cloudlink/useCloudLink", () => ({ useEnrollCloudLinkMailbox: () => ({}), useUnenrollCloudLinkMailbox: () => ({}), useCloudLinkMailboxLifecycle: () => ({}), })); @@ -77,6 +79,11 @@ function measuredStatus(row: Inbox): AccountStatus { return { id: row.id, email: row.email, provider: "gmail", status: "active", last_synced_at: null, health: { status: "healthy", score: 100 }, errors: [], daily_usage: { date: "2026-10-09", campaign_sent: 0, campaign_limit: 50 }, in_campaign: false }; } +beforeEach(() => { + statusState.cloudConnected = false; + cloudRows.clear(); +}); + describe("mailbox ordering with a tag filter", () => { beforeEach(() => { confirm.mockReset(); @@ -169,6 +176,31 @@ describe("mailbox status while account and Cloud checks settle", () => { }); afterEach(() => { cleanup(); vi.restoreAllMocks(); }); + it("keeps reported Cloud and local health visible when another Cloud mailbox has no report", async () => { + statusState.cloudConnected = true; + statusState.data = rows.map(measuredStatus); + for (const row of rows.slice(0, 2)) { + cloudRows.set(row.id, { id: row.id, email: row.email, name: row.name, provider: row.provider, status: "active", enrolled: true, managed: false }); + } + const reported = cloudRows.get(rows[1].id)!; + reported.cloud = { + remote_id: "reported-cloud-mailbox", email_account_id: reported.id, email: reported.email, + name: reported.name, provider: reported.provider, status: "active", enrolled_at: new Date(), + managed: false, sent_today: 7, sent_7d: 7, replied_7d: 0, spam_placed_7d: 0, auth_state: "active", + warmup: { enabled: true, paused: false, started_at: new Date(), current_volume: 7, target_volume: 20, max_volume: 40, reply_rate: 30, days_active: 1 }, + health: { state: "healthy", score: 100, spam_score: 0 }, + settings: { base: 20, max: 40, increase: 2, reply_rate: 30, start_time: "09:00", end_time: "17:00", days: 31, timezone: "UTC" }, + }; + await renderPage(); + const mailboxRow = (email: string) => screen.getAllByRole("row").find((row) => row.textContent?.includes(email))!; + expect(within(mailboxRow(rows[0].email)).getAllByText("Unavailable").length).toBeGreaterThan(0); + expect(within(mailboxRow(rows[0].email)).queryByText("Healthy 100")).not.toBeInTheDocument(); + expect(within(mailboxRow(rows[1].email)).getByText("Healthy 100")).toBeInTheDocument(); + expect(within(mailboxRow(rows[1].email)).getAllByTitle("7 of 20 warmup emails sent today by Warmbly Cloud").length).toBeGreaterThan(0); + expect(within(mailboxRow(rows[2].email)).getByText("Healthy 100")).toBeInTheDocument(); + expect(screen.getAllByText("Unavailable").length).toBeGreaterThan(1); + }); + it("keeps summary measurements pending until the mailbox inventory loads", async () => { statusState.emailsLoading = true; await renderPage(); diff --git a/web/src/app/app/emails/page.tsx b/web/src/app/app/emails/page.tsx index 84ad6d0b3..8e6cb8d50 100644 --- a/web/src/app/app/emails/page.tsx +++ b/web/src/app/app/emails/page.tsx @@ -1470,7 +1470,9 @@ function MailboxTh({ col, sort, onSort }: { col: MailboxColumn; sort: MailboxSor // compact spells a problem out, since it is the one reading a phone must not miss. function MailboxStatusPill({ box, status, historicalIssue, warming, compact = false, pending = false }: { box: Inbox; status?: AccountStatus; historicalIssue?: { status: AccountStatus; observedAt: number }; warming: boolean; compact?: boolean; pending?: boolean }) { if (!status && historicalIssue && box.status === "active") return Last reported issue; - const error = status?.errors?.[0]; + const critical = status?.errors?.find((e) => e.severity?.toUpperCase() === "CRITICAL"); + const error = critical ?? status?.errors?.[0]; + const stopped = !!critical || status?.health?.status === "error"; const lifecycle = status?.send_lifecycle; const inCampaign = !!status?.in_campaign; const { resting, sending } = mailboxColdActivity(status); @@ -1478,7 +1480,13 @@ function MailboxStatusPill({ box, status, historicalIssue, warming, compact = fa let problem: { label: string; text: string; Icon: LucideIcon; title: string } | null = null; if (box.status === "revoked") problem = { label: "Reconnect", text: "text-rose-600", Icon: UnplugIcon, title: "Access was revoked at the provider. Reconnect the mailbox to send and warm again." }; else if (box.status !== "active") problem = { label: "Off", text: "text-slate-500", Icon: CircleSlashIcon, title: "Switched off: it neither sends, warms nor syncs. Switch it back on from the row's menu or its Settings tab." }; - else if (error) problem = { label: "Error", text: "text-rose-600", Icon: AlertTriangleIcon, title: error.action_required ? `${error.title}. ${error.action_required}` : error.title }; + else if (error) { + const title = error.action_required ? `${error.title}. ${error.action_required}` : error.title; + // Only a critical report stops the mailbox; a warning (a dropped connection, a busy server) is retried on its own. + problem = stopped + ? { label: "Error", text: "text-rose-600", Icon: AlertTriangleIcon, title } + : { label: "Retrying", text: "text-amber-600", Icon: RotateCcwIcon, title }; + } if (problem) { const { Icon } = problem; return ( diff --git a/web/src/app/app/settings/security/PasskeyManager.tsx b/web/src/app/app/settings/security/PasskeyManager.tsx index 652305dfa..606b1d806 100644 --- a/web/src/app/app/settings/security/PasskeyManager.tsx +++ b/web/src/app/app/settings/security/PasskeyManager.tsx @@ -9,6 +9,8 @@ import useDeletePasskey from "@/lib/api/hooks/auth/useDeletePasskey"; import useRenamePasskey from "@/lib/api/hooks/auth/useRenamePasskey"; import { registerPasskey, passkeySupported, PasskeyCancelled } from "@/lib/passkey"; import type Passkey from "@/lib/api/models/auth/Passkey"; +import type { AppError } from "@/lib/api/client/normalizeError"; +import buildError from "@/lib/helper/buildError"; const fmt = (d: Date | string) => new Date(d).toLocaleDateString(undefined, { month: "short", day: "numeric", year: "numeric" }); @@ -63,8 +65,9 @@ export default function PasskeyManager() { try { await del.mutateAsync(p.id); toast.success("Passkey removed"); - } catch { - toast.error("Couldn't remove passkey."); + } catch (err) { + // The server refuses removing the last way to sign in, and says so. + toast.error(buildError(err as AppError) || "Couldn't remove passkey."); } }); }; diff --git a/web/src/app/app/settings/security/PasswordSection.tsx b/web/src/app/app/settings/security/PasswordSection.tsx new file mode 100644 index 000000000..0e5c97eb8 --- /dev/null +++ b/web/src/app/app/settings/security/PasswordSection.tsx @@ -0,0 +1,63 @@ +import { useState } from "react"; +import toast from "react-hot-toast/headless"; +import { RowLink, Section } from "../_components/SectionShell"; +import { useUserProfile } from "@/hooks/context/user"; +import useReauthMethods from "@/lib/api/hooks/auth/useReauthMethods"; +import useAuthConfig from "@/lib/api/hooks/auth/useAuthConfig"; +import sendPasswordLink from "@/lib/api/client/auth/sendPasswordLink"; +import type { AppError } from "@/lib/api/client/normalizeError"; +import buildError from "@/lib/helper/buildError"; +import ChangePasswordDialog from "./ChangePasswordDialog"; + +// An account created through Google, Apple or SSO has no password; it sets one +// through an emailed link instead of the change dialog. +export default function PasswordSection() { + const { user } = useUserProfile(); + const { config } = useAuthConfig(); + const { data: methods, isLoading } = useReauthMethods(); + const [dialogOpen, setDialogOpen] = useState(false); + const [sending, setSending] = useState(false); + const [sentTo, setSentTo] = useState(null); + + if (!config.password_login) return null; + + const sendLink = async () => { + if (sending) return; + setSending(true); + try { + await sendPasswordLink(); + setSentTo(user.email); + toast.success(`Link sent to ${user.email}`); + } catch (err) { + toast.error(buildError(err as AppError)); + } finally { + setSending(false); + } + }; + + return ( +
+ {isLoading ? null : methods?.password !== false ? ( + setDialogOpen(true)} + /> + ) : ( + + )} + setDialogOpen(false)} /> +
+ ); +} diff --git a/web/src/app/app/settings/security/SignInMethods.tsx b/web/src/app/app/settings/security/SignInMethods.tsx new file mode 100644 index 000000000..c19795384 --- /dev/null +++ b/web/src/app/app/settings/security/SignInMethods.tsx @@ -0,0 +1,75 @@ +import toast from "react-hot-toast/headless"; +import { Link2, Trash2 } from "lucide-react"; +import { Section } from "../_components/SectionShell"; +import { Loading } from "@/components/loader"; +import { useConfirm } from "@/hooks/context/confirm"; +import useLinkedIdentities from "@/lib/api/hooks/auth/useLinkedIdentities"; +import useUnlinkIdentity from "@/lib/api/hooks/auth/useUnlinkIdentity"; +import type LinkedIdentity from "@/lib/api/models/auth/LinkedIdentity"; +import type { AppError } from "@/lib/api/client/normalizeError"; +import buildError from "@/lib/helper/buildError"; + +const fmt = (d: string) => + new Date(d).toLocaleDateString(undefined, { month: "short", day: "numeric", year: "numeric" }); + +// Google, Apple and single sign-on linked to this account. Hidden when none are. +export default function SignInMethods() { + const { data: identities, isLoading } = useLinkedIdentities(); + const unlink = useUnlinkIdentity(); + const confirm = useConfirm(); + + if (!isLoading && !identities?.length) return null; + + const remove = (id: LinkedIdentity) => { + confirm.show( + `Stop signing in with ${id.label}? Other devices that signed in with ${id.label} are signed out. Your workspaces and connected mailboxes are not affected.`, + async () => { + try { + await unlink.mutateAsync(id.provider); + toast.success(`${id.label} removed`); + } catch (err) { + toast.error(buildError(err as AppError)); + } + }, + ); + }; + + return ( +
+ {isLoading ? ( +
+ Loading sign-in methods… +
+ ) : ( +
+ {identities?.map((id) => ( +
+
+ +
+
+
{id.label}
+
+ {id.email ? `${id.email} · ` : ""}Linked {fmt(id.created_at)} + {id.last_login_at ? ` · Last used ${fmt(id.last_login_at)}` : ""} +
+
+ +
+ ))} +
+ )} +
+ ); +} diff --git a/web/src/app/app/settings/security/page.tsx b/web/src/app/app/settings/security/page.tsx index af1c4062d..73a0b85a7 100644 --- a/web/src/app/app/settings/security/page.tsx +++ b/web/src/app/app/settings/security/page.tsx @@ -1,13 +1,12 @@ -import React from "react"; import { useNavigate } from "@tanstack/react-router"; import { RowLink, Section, SectionShell } from "../_components/SectionShell"; import PasskeyManager from "./PasskeyManager"; import SessionManager from "./SessionManager"; import TwoFactorManager from "./TwoFactorManager"; -import ChangePasswordDialog from "./ChangePasswordDialog"; +import PasswordSection from "./PasswordSection"; +import SignInMethods from "./SignInMethods"; export default function SecuritySettingsPage() { - const [pwOpen, setPwOpen] = React.useState(false); const navigate = useNavigate(); return ( @@ -15,14 +14,9 @@ export default function SecuritySettingsPage() { -
- setPwOpen(true)} - /> -
+ + + @@ -62,7 +56,6 @@ export default function SecuritySettingsPage() { onClick={() => (window.location.href = "/app/api-keys")} />
- setPwOpen(false)} /> ); } diff --git a/web/src/app/auth/hooks/useResetPasswordConfirmForm.ts b/web/src/app/auth/hooks/useResetPasswordConfirmForm.ts index 74ff30201..b175a1d49 100644 --- a/web/src/app/auth/hooks/useResetPasswordConfirmForm.ts +++ b/web/src/app/auth/hooks/useResetPasswordConfirmForm.ts @@ -1,6 +1,7 @@ import type React from "react"; import { useState, useEffect } from "react"; import { useNavigate } from "@tanstack/react-router"; +import { useQueryClient } from "@tanstack/react-query"; import { useSearchParams } from "@/hooks/useSearchParams"; import useResetPasswordConfirm from "@/lib/api/hooks/auth/useResetPasswordConfirm"; import { usePasswordStrength } from "@/hooks/usePasswordStrength"; @@ -9,15 +10,19 @@ import type { AppError } from "@/lib/api/client/normalizeError"; import buildError from "@/lib/helper/buildError"; import resetPasswordSession from "@/lib/api/client/auth/resetPasswordSession"; import { resetLinkToken } from "@/lib/resetLinkToken"; +import getToken from "@/lib/helper/getToken"; +import { TOKENS } from "@/lib/auth"; +import { clearClientSession } from "@/lib/session"; export function useResetPasswordConfirmForm() { // The link token is exchanged for a reset session held in memory, and cleared from the address bar. - const [params, setParams] = useSearchParams(); + const [, setParams] = useSearchParams(); const navigate = useNavigate(); + const queryClient = useQueryClient(); const resetConfirm = useResetPasswordConfirm(); const { evaluate } = usePasswordStrength(); - const [linkToken] = useState(() => resetLinkToken(window.location.hash, params)); + const [linkToken] = useState(() => resetLinkToken(window.location.hash)); const [session, setSession] = useState(""); const [linkState, setLinkState] = useState<"checking" | "ready" | "invalid">(linkToken ? "checking" : "invalid"); const isValidToken = linkState !== "invalid"; @@ -67,6 +72,8 @@ export function useResetPasswordConfirmForm() { resetConfirm.mutateAsync({ session, password, turnstile: turnstileToken }), { loading: "Loading...", success: "Password successfully changed", error: (err: AppError) => buildError(err) } ); + // The reset ended every session, this browser's included. + if (getToken() || TOKENS.some((key) => localStorage.getItem(key))) clearClientSession(queryClient); navigate({ to: "/auth/login", search: { action: "1" } }); } catch (err) { // The link died meanwhile (used, expired, or the password changed): show the request-a-new-one screen. diff --git a/web/src/app/auth/layout.tsx b/web/src/app/auth/layout.tsx index 645d8e2aa..e116b713b 100644 --- a/web/src/app/auth/layout.tsx +++ b/web/src/app/auth/layout.tsx @@ -34,7 +34,9 @@ export default function AuthLayout({ return () => window.removeEventListener("message", receiveMessage); }, [navigate]); - if (redirectIfAuthenticated && getToken()) { + // A reset link is opened from mail, often in the browser that is signed in. + const opensSignedIn = pathname.startsWith("/auth/reset-password"); + if (redirectIfAuthenticated && !opensSignedIn && getToken()) { return ; } diff --git a/web/src/app/auth/login/page.tsx b/web/src/app/auth/login/page.tsx index 8f7e39267..edc72960f 100644 --- a/web/src/app/auth/login/page.tsx +++ b/web/src/app/auth/login/page.tsx @@ -18,6 +18,7 @@ import useLogin from "@/lib/api/hooks/auth/useLogin"; import useLoginConfirm from "@/lib/api/hooks/auth/useLoginConfirm"; import { useTwoFactorVerify } from "@/lib/api/hooks/auth/useTwoFactor"; import useLinkSSO from "@/lib/api/hooks/auth/useLinkSSO"; +import useSetInitialPassword from "@/lib/api/hooks/auth/useSetInitialPassword"; import useRegister from "@/lib/api/hooks/auth/useRegister"; import useRegisterConfirm from "@/lib/api/hooks/auth/useRegisterConfirm"; import { saveTokens, takeSessionEndedNotice, SESSION_ENDED_MESSAGE } from "@/lib/auth"; @@ -158,7 +159,7 @@ function useCountdown(seconds: number) { Main multi-step auth page ═══════════════════════════════════════════ */ -type Step = "email" | "signin" | "signup" | "verify" | "2fa" | "link"; +type Step = "email" | "signin" | "signup" | "verify" | "2fa" | "link" | "initial"; type PasskeyStatus = "preparing" | "ready" | "waiting" | "timeout" | "not-found" | "error"; // Why a signup cannot proceed. Either read off /auth/config before the form is // shown, or returned by the API when the policy changed mid-session. @@ -275,6 +276,8 @@ export default function LoginPage() { const [password, setPassword] = useState(""); const [session, setSession] = useState(""); const [pendingToken, setPendingToken] = useState(ssoTwoFA); + // The single-use challenge a sign-in with an issued initial password returns. + const [initialToken, setInitialToken] = useState(""); const [direction, setDirection] = useState(0); const pendingRef = useRef<((token: string) => void) | null>(null); const tokenRef = useRef(""); @@ -288,6 +291,7 @@ export default function LoginPage() { const loginConfirmMutation = useLoginConfirm(); const verify2FAMutation = useTwoFactorVerify(); const linkMutation = useLinkSSO(); + const initialPasswordMutation = useSetInitialPassword(); const registerConfirmMutation = useRegisterConfirm(); const pending = captchaLoading || @@ -579,6 +583,17 @@ export default function LoginPage() { turnstile: token, device_token: getTrustedDevice(email), }); + // An issued initial password opens nothing until the holder + // chooses their own; the sign-in continues from that step. + if (res.password_change_required) { + if (!res.pending_token) { + toast.error("Something went wrong, please try again."); + return; + } + setInitialToken(res.pending_token); + goTo("initial"); + return; + } // A deployment with the login code turned off, or a device this // account has used before, completes here: there is nothing to // confirm and nothing was emailed. @@ -704,6 +719,37 @@ export default function LoginPage() { } }; + /* ── Initial password: replace an issued password, then continue ── */ + // No captcha: sign-in already spent one, and the single-use challenge it + // returned is the proof. What follows is the normal sign-in. + const handleInitialPassword = async (newPassword: string) => { + if (!initialToken) return; + try { + const res = await initialPasswordMutation.mutateAsync({ + pending_token: initialToken, + password: newPassword, + device_token: getTrustedDevice(email) || undefined, + }); + setInitialToken(""); + // A resent code signs in again, now with the chosen password. + setPassword(newPassword); + if (res.code_required) { + toast.success("Password saved. Verification code sent!"); + setSession(res.session ?? ""); + goTo("verify"); + return; + } + await finishDirectLogin(res); + } catch (e) { + toast.error(buildError(e as AppError)); + // The challenge is spent or expired: only a new sign-in can continue. + if ((e as AppError).code === "password_change_expired") { + setInitialToken(""); + goTo("signin", -1); + } + } + }; + /* ── Link step: a provider sign-in on an existing password account ── */ // No captcha: the pending token is the proof of a completed provider // flow, and a wrong password is metered server-side like a sign-in. @@ -875,6 +921,20 @@ export default function LoginPage() { )} + {!signupGate && !showSignupUnavailable && step === "initial" && ( + + { + setInitialToken(""); + goTo("signin", -1); + }} + onSubmit={handleInitialPassword} + /> + + )} + {!signupGate && !showSignupUnavailable && step === "link" && linkChallenge && ( d.password === d.confirmPassword, { + message: "Passwords don't match", + path: ["confirmPassword"], +}); + +function InitialPasswordStep({ + email, + pending, + onBack, + onSubmit, +}: { + email: string; + pending: boolean; + onBack: () => void; + onSubmit: (password: string) => void; +}) { + const { register, handleSubmit, watch, setError, formState: { errors } } = useForm>({ + resolver: zodResolver(initialPasswordSchema), + defaultValues: { password: "", confirmPassword: "" }, + }); + const pw = watch("password"); + const { evaluate } = usePasswordStrength(); + const [strength, setStrength] = useState<{ score: 0 | 1 | 2 | 3 | 4; warning: string }>({ score: 0, warning: "" }); + + useEffect(() => { + if (!pw) { setStrength({ score: 0, warning: "" }); return; } + let cancelled = false; + evaluate(pw).then((r) => { if (!cancelled) setStrength({ score: r.score, warning: r.warning }); }); + return () => { cancelled = true; }; + }, [pw, evaluate]); + + const onFormSubmit = handleSubmit(async (data) => { + const result = await evaluate(data.password); + if (result.score < 2) { + setError("password", { message: result.warning || "Please choose a stronger password." }); + return; + } + onSubmit(data.password); + }); + + return ( +
+
+ +

Choose your password

+

+ The password you signed in with was issued to you and only works for a first sign-in. + Choose your own to continue; the issued one stops working once you do. +

+
+ +
+
+ + + + {pw && ( +
+ +
+ )} +
+ +
+ + + +
+ +
+ Save password and continue +
+
+ +

+ Every other session on this account is signed out when you save it. +

+
+ ); +} + /* ── Sign-up step ─────────────────────── */ function SignUpStep({ diff --git a/web/src/components/app/emails/InboxDetails.tsx b/web/src/components/app/emails/InboxDetails.tsx index c98dcbd82..3e15512e8 100644 --- a/web/src/components/app/emails/InboxDetails.tsx +++ b/web/src/components/app/emails/InboxDetails.tsx @@ -110,6 +110,7 @@ import useAuthConfig from "@/lib/api/hooks/auth/useAuthConfig"; import { Toggle } from "@/components/app/campaigns/preferences/components/CampaignPreferenceBoolBox"; import setDirectTracking from "@/lib/api/client/app/emails/setDirectTracking"; import useSendingBehavior from "@/lib/api/hooks/app/emails/useSendingBehavior"; +import useUpdateSendingBehavior from "@/lib/api/hooks/app/emails/useUpdateSendingBehavior"; import useSendingPlan from "@/lib/api/hooks/app/emails/useSendingPlan"; import { minutesToClock, secondsToLabel } from "@/lib/api/models/app/emails/SendingBehavior"; import TagSelector from "../popup/select/TagSelector"; @@ -834,20 +835,23 @@ function OverviewTab({ status, loading, mailbox }: { status?: import("@/lib/api/
Needs attention
- {status.errors.map((e: AccountError) => ( -
-
{e.title}
-
Reported {new Date(e.created_at).toLocaleString()}{e.operation === "send" ? " · Sending" : e.operation === "sync" ? " · Mailbox sync" : ""}
-
{e.message}
- {e.action_required &&
{e.action_required}
} - {e.id === firstCredentialErrorId && - (mailbox.auth_method === "delegated" ? ( - - ) : ( - - ))} -
- ))} + {status.errors.map((e: AccountError) => { + const tone = e.severity?.toUpperCase() === "CRITICAL" ? errorTone.critical : errorTone.warning; + return ( +
+
{e.title}
+
Reported {new Date(e.created_at).toLocaleString()}{e.operation === "send" ? " · Sending" : e.operation === "sync" ? " · Mailbox sync" : ""}
+
{e.message}
+ {e.action_required &&
{e.action_required}
} + {e.id === firstCredentialErrorId && + (mailbox.auth_method === "delegated" ? ( + + ) : ( + + ))} +
+ ); + })}
)} @@ -996,6 +1000,12 @@ function AnalyticsTab({ warmup, loading, failed, retry }: { warmup?: import("@/l const WEEKDAYS = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]; +// A critical report stops the mailbox; a warning is retried on its own, so it reads as amber, not red. +const errorTone = { + critical: { box: "border-rose-200 bg-rose-50", title: "text-rose-800", meta: "text-rose-700/80", body: "text-rose-700/90", action: "text-rose-900" }, + warning: { box: "border-amber-200 bg-amber-50", title: "text-amber-900", meta: "text-amber-700/80", body: "text-amber-800/90", action: "text-amber-900" }, +}; + const warmupStateTone: Record = { healthy: { text: "text-emerald-600", bar: "bg-emerald-500", label: "Healthy" }, watch: { text: "text-amber-600", bar: "bg-amber-500", label: "Watch" }, @@ -1294,11 +1304,65 @@ function AuthCheckPanel({ mailbox }: { mailbox: Inbox }) { ); } +const ALL_DAYS = 127; + +const listDays = (mask: number) => { + const names = WEEKDAYS.filter((_, i) => (mask & (1 << i)) !== 0); + return names.length > 1 ? `${names.slice(0, -1).join(", ")} and ${names[names.length - 1]}` : names.join(""); +}; + +// Warmup sends only on days both calendars allow, so a day ticked here that the persona does not work is silently skipped. +function WarmupDaysNotice({ mailboxId, warmupDays, personaDays }: { mailboxId: string; warmupDays: number; personaDays: number }) { + const wanted = warmupDays || ALL_DAYS; + const skipped = wanted & ~personaDays; + const canManage = usePermission("MANAGE_EMAILS"); + const queryClient = useQueryClient(); + const mutation = useUpdateSendingBehavior(mailboxId); + if (skipped === 0) return null; + + const workDays = async () => { + try { + await mutation.mutateAsync({ weekdays: personaDays | skipped }); + await queryClient.invalidateQueries({ queryKey: ["analytics", "accounts"] }); + toast.success(`Warmup now sends on ${listDays(skipped)} too`); + } catch (e) { + toast.error(buildError(e as unknown as AppError)); + } + }; + + return ( +
+ +
+

+ {(wanted & personaDays) === 0 ? "Warmup has no day to send on" : `Warmup skips ${listDays(skipped)}`} +

+

+ Sending behaviour only works {personaDays ? listDays(personaDays) : "no days"}, and warmup follows its workdays as well as the + days picked here. +

+ {canManage && ( + + )} +
+
+ ); +} + function WarmupTab({ form, update, status, mailbox, canWarmup = true }: { form: Inbox; update: (p: Partial) => void; status?: AccountStatusModel; mailbox: Inbox; canWarmup?: boolean }) { const ws = status?.warmup_status; const wh = status?.warmup_health; const whUnavailable = cloudStandingUnavailable(wh); - const behaviorOn = !!useSendingBehavior(mailbox.id).data?.enabled; + const persona = useSendingBehavior(mailbox.id).data; + const behaviorOn = !!persona?.enabled; const inCampaign = status?.in_campaign; // Warmup on/off is a lifecycle action (immediate), not a saved form field — @@ -1598,6 +1662,9 @@ function WarmupTab({ form, update, status, mailbox, canWarmup = true }: { form: />
+ {behaviorOn && persona && ( + + )}

); diff --git a/web/src/components/app/emails/domains/RedirectServing.tsx b/web/src/components/app/emails/domains/RedirectServing.tsx index 59cc1e779..9a5348995 100644 --- a/web/src/components/app/emails/domains/RedirectServing.tsx +++ b/web/src/components/app/emails/domains/RedirectServing.tsx @@ -1,12 +1,22 @@ // Where a root redirect is served from, whether visitors get it, and how to fix it (or hand it to Warmbly Cloud) when they do not. import React from "react"; import { AnimatePresence, motion } from "framer-motion"; -import { AlertTriangleIcon, CheckCircle2Icon, CloudIcon, ExternalLinkIcon, Loader2Icon, ServerIcon, ZapIcon } from "lucide-react"; +import { + AlertTriangleIcon, + CheckCircle2Icon, + CircleDashedIcon, + CloudIcon, + ExternalLinkIcon, + Loader2Icon, + RefreshCwIcon, + ServerIcon, + ZapIcon, +} from "lucide-react"; import type { DomainRedirect, RedirectServer } from "@/lib/api/models/app/emails/SendingDomain"; import timeAgo from "@/lib/helper/timeAgo"; import { cn } from "@/lib/utils"; -import { CopyButton } from "./parts"; -import { PROXY_NAMES, redirectBlocked } from "./rules"; +import { CopyButton, DnsRecordsTable } from "./parts"; +import { PROXY_NAMES, redirectBlocked, shortUrl } from "./rules"; import type { CloudServing } from "./cloudServing"; /* ── Served from ─────────────────────── */ @@ -50,8 +60,10 @@ export function ServedByPicker({ ); } else if (!cloud.offer?.available) { cloudBody = "Warmbly Cloud does not serve redirects for this instance right now."; - } else if (!cloudOpen) { + } else if (!cloudOpen && cloud.offer.used >= cloud.offer.limit) { cloudBody = `Warmbly Cloud serves up to ${cloud.offer.limit} redirects for one instance, and this one has reached it.`; + } else if (!cloudOpen) { + cloudBody = "The Warmbly Cloud link is not tied to this workspace. Reconnect Warmbly Cloud from this workspace to serve redirects there."; } else { cloudBody = "Point the domain at Warmbly Cloud. It serves the redirect and its certificate, with nothing to set up on your server."; } @@ -131,89 +143,205 @@ function ServerOption({ ); } -/* ── Status ─────────────────────── */ +/* ── Progress ─────────────────────── */ -/** The redirect's state as a visitor would meet it: waiting for DNS, live, or in place but not reaching them. */ -export function RedirectStatusBanner({ domain, redirect }: { domain: string; redirect: DomainRedirect }) { +type StepState = "done" | "todo" | "blocked" | "waiting"; + +interface ProgressStep { + key: string; + state: StepState; + title: string; + body?: React.ReactNode; +} + +function StepMark({ state, n }: { state: StepState; n: number }) { + if (state === "done") return ; + if (state === "blocked") return ; + if (state === "waiting") return ; + return ( + + {n} + + ); +} + +/** What stands between the redirect and a visitor, one step at a time, with the fix for the step that is missing. */ +export function RedirectProgress({ + domain, + redirect, + fix, + onCheck, + checking, +}: { + domain: string; + redirect: DomainRedirect; + /** Shown under the visitor step when DNS is right but visitors do not get the redirect. */ + fix: React.ReactNode; + onCheck: () => void; + checking: boolean; +}) { const reach = redirect.reach ?? null; - const blocked = redirectBlocked(redirect); - const live = redirect.verified && !blocked; const cloud = redirect.served_by === "cloud"; - const tone = live ? "emerald" : "amber"; + const site = redirect.website?.record ? redirect.website : null; + const siteOk = redirect.target_active !== false; + const blocked = redirectBlocked(redirect); + const live = redirect.verified && siteOk && !blocked; const checkedAt = redirect.last_checked_at ?? reach?.checked_at; + const where = cloud ? "Warmbly Cloud" : "this server"; - let title: string; - let body: React.ReactNode; - if (!redirect.verified) { - title = "Waiting for DNS"; - body = redirect.last_error || (cloud ? "Add the records below to point the domain at Warmbly Cloud." : "Add the records below at your DNS provider."); - } else if (blocked) { - title = "DNS is in place, but visitors do not get the redirect"; - body = reach?.detail || `Opening ${domain} does not reach the redirect yet.`; - } else { - title = "Live"; - body = ( - <> - {domain} - {redirect.include_www ? ` and www.${domain}` : ""} redirect to{" "} - - {redirect.target_url} - - - . - + const steps: ProgressStep[] = []; + steps.push( + redirect.verified + ? { key: "dns", state: "done", title: `${domain} points at ${where}` } + : cloud && !siteOk + ? { key: "dns", state: "waiting", title: `${domain} points at ${where}`, body: "Warmbly Cloud checks the records once the website is confirmed." } + : { + key: "dns", + state: "todo", + title: `Point ${domain} at ${where}`, + body: redirect.last_error || "Add the DNS records listed below at your DNS provider.", + }, + ); + if (site) { + steps.push( + site.verified + ? { key: "site", state: "done", title: `${site.domain} is confirmed as your website` } + : { + key: "site", + state: "todo", + title: `Confirm ${site.domain} is your website`, + body: ( +
+

+ Redirects only send visitors to websites this workspace controls. Add this TXT record where{" "} + {site.domain}'s DNS is managed (not {domain}'s), then + press Check now. It does not change your website. +

+ +
+ ), + }, ); } + if (live) { + steps.push({ + key: "visit", + state: "done", + title: "Visitors get the redirect", + body: + reach?.status === "unreachable" ? ( + reach.hint === "no_listener" ? ( + <> + This server could not open {domain} to double-check, which some networks do not allow.{" "} + + Open it + {" "} + to confirm. + + ) : ( + reach.detail + ) + ) : undefined, + }); + } else if (blocked && siteOk) { + steps.push({ + key: "visit", + state: "blocked", + title: "Visitors do not get the redirect yet", + body: ( +
+

{reach?.detail || `Opening ${domain} does not reach the redirect yet.`}

+ {fix} +
+ ), + }); + } else { + steps.push({ key: "visit", state: "waiting", title: "Visitors get the redirect", body: "Checked by opening the domain once the steps above are done." }); + } + + const left = steps.filter((st) => st.state === "todo").length; + const headline = live + ? "Live" + : blocked && siteOk + ? "DNS is in place, but visitors do not get the redirect" + : left > 0 + ? `${left} ${left === 1 ? "step" : "steps"} left` + : "Almost there"; + let n = 0; return ( -
- {live ? ( - - ) : blocked ? ( - - ) : ( - - )} -
-
-

{title}

- {cloud && ( - - - Warmbly Cloud - - )} -
-

{body}

- {live && reach?.status === "unreachable" && reach.hint !== "no_listener" && reach.detail && ( -

{reach.detail}

- )} - {live && reach?.status === "unreachable" && reach.hint === "no_listener" && ( -

- This server could not open {domain} to double-check, which some networks do not allow.{" "} +

+
+
+
+

{headline}

+ {cloud && ( + + + Warmbly Cloud + + )} +
+

+ {domain} + {redirect.include_www ? ` and www.${domain}` : ""} →{" "} - Open it - {" "} - to confirm. + {shortUrl(redirect.target_url)} + +

- )} - {checkedAt &&

Last checked {timeAgo(checkedAt)}

} +
+
+
    + {steps.map((st) => { + if (st.state === "todo") n++; + return ( +
  1. + + + +
    +

    + {st.title} +

    + {st.body &&
    {st.body}
    } +
    +
  2. + ); + })} +
+ {checkedAt && ( +

+ Last checked {timeAgo(checkedAt)}. Warmbly also checks by itself. +

+ )}
); } diff --git a/web/src/components/app/emails/domains/SendingDomainDrawer.tsx b/web/src/components/app/emails/domains/SendingDomainDrawer.tsx index 5ea27a4e7..64766f19b 100644 --- a/web/src/components/app/emails/domains/SendingDomainDrawer.tsx +++ b/web/src/components/app/emails/domains/SendingDomainDrawer.tsx @@ -18,12 +18,19 @@ import { Loader2Icon, MinusIcon, MousePointerClickIcon, - RefreshCwIcon, + ShieldCheckIcon, Trash2Icon, XIcon, ZapIcon, } from "lucide-react"; -import type { SendingDomain, DNSRecord, DomainRedirect, RedirectServer, VendorDomainLink } from "@/lib/api/models/app/emails/SendingDomain"; +import type { + SendingDomain, + DNSRecord, + DomainRedirect, + RedirectServer, + RedirectWebsite, + VendorDomainLink, +} from "@/lib/api/models/app/emails/SendingDomain"; import type TrackingDomain from "@/lib/api/models/app/emails/TrackingDomain"; import { useDeleteDomainRedirect, @@ -33,6 +40,7 @@ import { useSetVendorTracking, useTrackingSuggestion, useVerifyDomainRedirect, + useVerifyRedirectWebsite, } from "@/lib/api/hooks/app/emails/useSendingDomains"; import { vendorLabel } from "@/lib/api/models/app/emails/MailboxSources"; import { Label, TextInput } from "@/components/ui/field"; @@ -44,7 +52,7 @@ import buildError from "@/lib/helper/buildError"; import { mailHostLabel } from "@/lib/mailHost"; import { cn } from "@/lib/utils"; import { DnsRecordsTable, StatusPill, VendorChip, type RecordRow } from "./parts"; -import { ReachFix, RedirectStatusBanner, ServedByPicker } from "./RedirectServing"; +import { ReachFix, RedirectProgress, ServedByPicker } from "./RedirectServing"; import { defaultServer, useCloudServing } from "./cloudServing"; import CloudConnectDialog from "@/components/app/cloud/CloudConnectDialog"; import { @@ -61,8 +69,20 @@ import { trackingRecord, trackingState, vendorCanCname, + websiteUnproved, } from "./rules"; +/** The lower-case host of a typed website address, or "". */ +function hostOf(raw: string): string { + const t = raw.trim(); + if (!t) return ""; + try { + return new URL(t.includes("://") ? t : `https://${t}`).hostname.toLowerCase(); + } catch { + return ""; + } +} + export type DomainTab = "overview" | "tracking" | "redirect"; const TABS: { key: DomainTab; label: string; icon: typeof GlobeIcon }[] = [ @@ -998,11 +1018,12 @@ function DnsRedirect({ const save = useSetDomainRedirect(); const verify = useVerifyDomainRedirect(); const remove = useDeleteDomainRedirect(); + const proveSite = useVerifyRedirectWebsite(); const cloud = useCloudServing(); const [checked, setChecked] = React.useState(null); const [tried, setTried] = React.useState(false); - // The API's refusal of the destination, shown under the field until it is edited. - const [refused, setRefused] = React.useState(""); + // The record that confirms the typed website is the workspace's, once a save was refused for lack of it. + const [proof, setProof] = React.useState(null); // "serve" came from a redirect visitors do not reach, so linking moves it; "pick" only selects Cloud. const [connecting, setConnecting] = React.useState<"pick" | "serve" | null>(null); @@ -1019,7 +1040,7 @@ function DnsRedirect({ const toCloud = server === "cloud"; function resetDrafts() { - setRefused(""); + setProof(null); setUrlDraft(null); setWwwDraft(null); setServedDraft(null); @@ -1033,7 +1054,7 @@ function DnsRedirect({ }); setChecked(r); resetDrafts(); - if (r.verified && !redirectBlocked(r)) toast.success("Redirect saved and live"); + if (r.verified && r.target_active !== false && !redirectBlocked(r)) toast.success("Redirect saved and live"); else if (r.verified) toast("Saved. DNS is in place, but visitors do not reach the redirect yet."); else if (r.served_by === "cloud") toast.success("Saved. Add the records below to point the domain at Warmbly Cloud."); else toast.success("Redirect saved. Add the DNS records below to switch it on."); @@ -1047,8 +1068,23 @@ function DnsRedirect({ await persist(url.trim(), www, server); } catch (e) { const err = e as AppError; - if (err.code === REDIRECT_NOT_OWN_DOMAIN) setRefused(err.message); - toast.error(buildError(err)); + if (err.code !== REDIRECT_NOT_OWN_DOMAIN) { + toast.error(buildError(err)); + return; + } + // Not refused for good: the website only has to carry the workspace's TXT record. + try { + const w = await proveSite.mutateAsync({ domain: domain.domain, url: url.trim() }); + if (w.verified) { + await persist(url.trim(), www, server); + return; + } + // A second press means the record was asked for already and is still not there. + if (proof) toast(`The TXT record for ${w.domain} is not visible yet. It can take a few minutes to appear.`); + setProof(w); + } catch (pe) { + toast.error(buildError(pe as AppError)); + } } }; // Moving a redirect changes its records, so a live one stops until the new ones are in place. @@ -1098,7 +1134,8 @@ function DnsRedirect({ try { const r = await verify.mutateAsync(domain.domain); setChecked(r); - if (r.verified && !redirectBlocked(r)) toast.success("The redirect is live."); + if (websiteUnproved(r)) toast(`The TXT record for ${r.website!.domain} is not visible yet. It can take a few minutes to appear.`); + else if (r.verified && !redirectBlocked(r)) toast.success("The redirect is live."); else if (r.verified) toast("DNS is in place, but visitors do not reach the redirect yet."); else toast("Not every record is visible yet. It keeps checking by itself."); } catch (e) { @@ -1123,53 +1160,73 @@ function DnsRedirect({ }); } + // A proof card for a website other than the one now typed would ask for the wrong record. + const typedHost = hostOf(url); + const shownProof = proof && (typedHost === proof.domain || typedHost.endsWith(`.${proof.domain}`)) ? proof : null; + const savedUnproved = websiteUnproved(redirect); + return (
{redirect && ( -
- - setConnecting("serve")} - switching={save.isPending} - /> -
+ void checkNow()} + checking={verify.isPending} + fix={ + setConnecting("serve")} + switching={save.isPending} + /> + } + /> )}
+ {redirect && Settings}
- + { - setRefused(""); - setUrlDraft(v); - }} + onChange={setUrlDraft} placeholder="https://yourcompany.com" className="w-full" - invalid={(tried && !!problem) || refused !== ""} + invalid={tried && !!problem} onKeyDown={(e) => { if (e.key === "Enter") void submit(); }} /> {tried && problem ? (

{problem}

- ) : refused ? ( -

- {refused} -

- ) : redirect?.target_active === false && url.trim() === redirect.target_url ? ( -

- {redirect.target_inactive_reason || - "Not in use: the destination is no longer on one of this workspace's own domains, so visitors get the domain's default page instead. This happens when the mailbox or verified domain it relied on was removed; point it at one of your own domains or reconnect that domain."} -

+ ) : redirect?.target_active === false && !savedUnproved && url.trim() === redirect.target_url ? ( +

{redirect.target_inactive_reason}

) : null} -

{OWN_DOMAIN_HINT}

+ {!shownProof &&

{OWN_DOMAIN_HINT}

}
+ {shownProof?.record && !shownProof.verified && ( +
+
+ +
+

Confirm {shownProof.domain} is your website

+

+ Redirects only send visitors to websites this workspace controls. Add this TXT record where {shownProof.domain} + 's DNS is managed, then save again. It does not change your website, and you only do it once for every + domain that redirects there. +

+
+
+ +
+ )}
Include www.{domain.domain}
@@ -1190,11 +1247,19 @@ function DnsRedirect({ {redirect && changed && ( -
+ DNS records for {domain.domain}

{redirect.served_by === "cloud" - ? `The root records point ${domain.domain} at Warmbly Cloud and replace whatever it serves today. New records can take from a few minutes to a few hours to appear. Warmbly Cloud checks by itself every 10 minutes and switches the redirect on once the ownership and root records are in place.` - : `The root records replace whatever ${domain.domain} serves today. New records can take from a few minutes to a few hours to appear. Warmbly checks by itself every 10 minutes and switches the redirect on once the ownership and root records are in place, then opens the domain to make sure visitors get it.`} + ? `These point ${domain.domain} at Warmbly Cloud and replace whatever it serves today. New records can take a few minutes to a few hours to show up.` + : `These point ${domain.domain} at this server and replace whatever it serves today. New records can take a few minutes to a few hours to show up.`}

)} diff --git a/web/src/components/app/emails/domains/rules.ts b/web/src/components/app/emails/domains/rules.ts index 79e37eb12..75ed03740 100644 --- a/web/src/components/app/emails/domains/rules.ts +++ b/web/src/components/app/emails/domains/rules.ts @@ -63,6 +63,8 @@ export function redirectBlocked(r: DomainRedirect | null | undefined): boolean { } export function redirectState(d: SendingDomain): RedirectState { + // A destination not yet the workspace's is not served, whatever DNS says. + if (d.redirect?.target_active === false) return "pending"; if (d.redirect?.verified) return redirectBlocked(d.redirect) ? "blocked" : "live"; if (d.vendor_domain?.forwarding) return "vendor"; if (d.redirect) return "pending"; @@ -158,9 +160,18 @@ export const REDIRECT_NOT_OWN_DOMAIN = "redirect_target_not_own_domain"; /** Where a redirect may point, shown under every destination field. */ export const OWN_DOMAIN_HINT = - "Must be a page on one of your workspace's own domains: a domain you have a mailbox on (not gmail.com or another shared provider), your verified tracking domain, your verified forms domain, or a subdomain of one."; + "Usually your main website. If you do not send from its domain, Warmbly asks for one TXT record there once, to confirm the website is yours."; + +/** The redirect waits for its website's TXT record before it is served. */ +export function websiteUnproved(r: DomainRedirect | null | undefined): boolean { + return !!r && r.target_active === false && !!r.website?.record && !r.website.verified; +} export function redirectPill(d: SendingDomain): PillInfo { + if (websiteUnproved(d.redirect)) { + const site = d.redirect!.website!.domain; + return { tone: "amber", label: "Confirm website", title: `Add the TXT record for ${site} to confirm the website is this workspace's.` }; + } if (d.redirect && d.redirect.target_active === false) { return { tone: "amber", diff --git a/web/src/components/app/forms/SettingsPanel.tsx b/web/src/components/app/forms/SettingsPanel.tsx index d75c0699a..46b171562 100644 --- a/web/src/components/app/forms/SettingsPanel.tsx +++ b/web/src/components/app/forms/SettingsPanel.tsx @@ -99,7 +99,8 @@ export default function SettingsPanel({

Must be a page on one of your workspace's own domains: a domain you have a mailbox on (not gmail.com or another shared provider), your verified tracking domain, your verified forms - domain, or a subdomain of one. Leave empty to show the success message instead. + domain, a website confirmed under Sending domains, or a subdomain of one. Leave empty to show + the success message instead.

diff --git a/web/src/components/app/unibox/AgentDraftCard.tsx b/web/src/components/app/unibox/AgentDraftCard.tsx index 7fe02f03e..05639659f 100644 --- a/web/src/components/app/unibox/AgentDraftCard.tsx +++ b/web/src/components/app/unibox/AgentDraftCard.tsx @@ -30,6 +30,7 @@ export default function AgentDraftCard({ threadId }: { threadId: string }) { const refresh = () => { void queryClient.invalidateQueries({ queryKey: ["unibox", "agent-drafts"] }); void queryClient.invalidateQueries({ queryKey: ["unibox", "overview"] }); + void queryClient.invalidateQueries({ queryKey: ["unibox", "search"] }); void queryClient.invalidateQueries({ queryKey: ["unibox", "thread", threadId] }); }; diff --git a/web/src/components/app/unibox/ConversationList.tsx b/web/src/components/app/unibox/ConversationList.tsx index ea99d0f2b..b87a7fc29 100644 --- a/web/src/components/app/unibox/ConversationList.tsx +++ b/web/src/components/app/unibox/ConversationList.tsx @@ -32,15 +32,18 @@ import { cn } from "@/lib/utils"; import type { UniboxSearchParams } from "@/lib/api/models/app/unibox/UniboxSearch"; import { Checkbox } from "@/components/ui/checkbox"; -type Bucket = "today" | "yesterday" | "week" | "earlier"; +type Bucket = "agent" | "today" | "yesterday" | "week" | "earlier"; const BUCKET_LABELS: Record = { + agent: "Agent drafts", today: "Today", yesterday: "Yesterday", week: "This week", earlier: "Earlier", }; +const NO_ROWS: ReturnType["emails"] = []; + // Views where an empty list means the work is done rather than that nothing // ever landed there. const CAUGHT_UP_SCOPES = new Set(["folder:inbox", "unread", "awaiting", "all"]); @@ -121,7 +124,26 @@ export function ConversationList({ const emptyScope = params.accountIds?.length === 0 || params.categoryIds?.length === 0; const result = useUniboxSearch(merged, scopeKey, !emptyScope); const q = emptyScope ? { ...result, emails: [], isPending: false, isFetching: false, hasNextPage: false } : result; - const emails = q.emails; + + // Drafts lists threads with a pending inbox-agent draft above the mailbox's own drafts. + const draftsFolder = params.folder === "drafts" && !emptyScope; + const agentParams = React.useMemo( + () => ({ ...merged, folder: undefined, agentDrafts: true }), + [merged], + ); + const agent = useUniboxSearch(agentParams, `${scopeKey}:agent`, draftsFolder); + const agentRows = draftsFolder ? agent.emails : NO_ROWS; + const agentKeys = React.useMemo( + () => new Set(agentRows.map((r) => r.thread_id || r.id)), + [agentRows], + ); + const emails = React.useMemo( + () => + agentRows.length === 0 + ? q.emails + : [...agentRows, ...q.emails.filter((r) => !agentKeys.has(r.thread_id || r.id))], + [agentRows, agentKeys, q.emails], + ); const totalShown = emails.length; const activeFilters = countUserFilters(params, baseParams); @@ -208,9 +230,13 @@ export function ConversationList({ // a bar along the top and the stale rows dimmed. Background refetches from // realtime events do not qualify, so nothing flickers while reading. The // bar waits 150ms so a fast response never shows it at all. - const stale = q.isPlaceholderData && q.isFetching; + const stale = (q.isPlaceholderData && q.isFetching) || + (draftsFolder && agent.isPlaceholderData && agent.isFetching); const showProgress = useDelayed(stale, 150); - const firstLoad = (q.isPending || q.isPlaceholderData) && emails.length === 0; + const firstLoad = (q.isPending || q.isPlaceholderData || + (draftsFolder && (agent.isPending || agent.isPlaceholderData))) && emails.length === 0; + const failedQuery = q.isError && !q.isFetchNextPageError ? q : + draftsFolder && agent.isError && !agent.isFetchNextPageError ? agent : undefined; // Where this exact list was left. Opening a thread keeps the page mounted // (see the route's stableParams in main.tsx), so this covers what that @@ -225,13 +251,17 @@ export function ConversationList({ // data is on screen, which lags the request key for as long as the previous // rows are standing in, so the swap remounts rather than animates. const shownKey = React.useRef(listKey); - if (!q.isPlaceholderData) shownKey.current = listKey; + if (!q.isPlaceholderData && (!draftsFolder || !agent.isPlaceholderData)) shownKey.current = listKey; // Infinite scroll: reaching the end of the list loads the next page instead // of asking for a click. The button below stays as the manual fallback, and // isFetchingNextPage is a dependency so a page landing re-arms the observer: // a sentinel still on screen keeps pulling instead of stalling one page in. - const { hasNextPage, isFetchingNextPage, isFetchNextPageError, fetchNextPage } = q; + // Page agent drafts first, using the same bounded scroll and retry behavior as mailbox drafts. + const nextQuery = draftsFolder && agent.hasNextPage && + (!agent.isFetchNextPageError || !q.hasNextPage) ? agent : q; + const { isFetchingNextPage, isFetchNextPageError, fetchNextPage } = nextQuery; + const hasNextPage = q.hasNextPage || (draftsFolder && agent.hasNextPage); React.useEffect(() => { const root = listRef.current; // A page that failed stays failed until the user asks again; re-arming on @@ -265,13 +295,13 @@ export function ConversationList({ )[] = []; let last: Bucket | null = null; for (const e of emails) { - const b = bucketFor(new Date(e.internal_date)); + const b = agentKeys.has(rowKey(e)) ? "agent" : bucketFor(new Date(e.internal_date)); if (b !== last) out.push({ kind: "header", key: `bucket:${b}`, bucket: b }); last = b; out.push({ kind: "row", key: rowKey(e), row: e }); } return out; - }, [emails, rowKey]); + }, [emails, rowKey, agentKeys]); // Which items were on screen last time, and a generation per key that // left. A key that comes back gets a fresh presence key: AnimatePresence @@ -537,17 +567,17 @@ export function ConversationList({ > {firstLoad ? ( - ) : q.isError && emails.length === 0 ? ( + ) : failedQuery && emails.length === 0 ? (

Couldn't load inbox

- {q.error?.message ?? "Request failed"} + {failedQuery.error?.message ?? "Request failed"}

) : ( + {draftsFolder && agent.isFetchNextPageError && nextQuery !== agent && ( +
+ Couldn't load more agent drafts.{" "} + +
+ )} + {failedQuery && ( +
+ Some conversations couldn't load.{" "} + +
+ )} {items.map((item) => item.kind === "header" ? ( @@ -620,7 +666,7 @@ export function ConversationList({ ones can still animate out when an action empties the list. It waits for them before it appears. */} - {emails.length === 0 && !hasNextPage && ( + {emails.length === 0 && !hasNextPage && !failedQuery && ( { const counts = folderCounts.get(folder); - // Drafts reads better as a total; everywhere else the number is unread. - const count = folder === "drafts" ? counts?.total : counts?.unread; + // Drafts reads better as a total, pending agent drafts included; everywhere else the number is unread. + const agentDrafts = folder === "drafts" ? (data?.awaiting_agent_draft ?? 0) : 0; + const count = folder === "drafts" ? (data?.drafts ?? counts?.total) : counts?.unread; return { key: `folder:${folder}`, label, icon, count: count || undefined, - accent: folder !== "drafts" && !!count, + accent: folder === "drafts" ? agentDrafts > 0 : !!count, noun: "folder", onOpen: () => onChange({ kind: "folder", folder }), onMarkAllRead: readOnly ? undefined : () => markSeen.mutate({ folder, seen: true }), diff --git a/web/src/components/app/unibox/conversationListDrafts.test.tsx b/web/src/components/app/unibox/conversationListDrafts.test.tsx new file mode 100644 index 000000000..d8ce2032d --- /dev/null +++ b/web/src/components/app/unibox/conversationListDrafts.test.tsx @@ -0,0 +1,209 @@ +// The Drafts folder lists threads with a pending inbox-agent draft above the mailbox's own drafts. + +import React from "react"; +import { afterEach, expect, it, vi } from "vitest"; +import { cleanup, fireEvent, render, screen } from "@testing-library/react"; +import type { UniboxSearchParams } from "@/lib/api/models/app/unibox/UniboxSearch"; +import { ConversationList } from "./ConversationList"; + +const search = vi.hoisted(() => ({ + calls: [] as { params: UniboxSearchParams; enabled: boolean }[], + agentHasMore: false, + agentPageFailed: false, + mailboxHasMore: false, + agentNextPage: [] as string[], + agentPending: false, + agentFailed: false, + agentRefetches: 0, + mailboxEmpty: false, +})); + +function row(id: string, thread: string, subject: string) { + return { + id, + thread_id: thread, + email_id: "m1", + from_addr: ["Lead "], + to_addr: ["me@example.com"], + subject, + snippet: subject, + internal_date: new Date().toISOString(), + has_unread: false, + message_count: 1, + labels: [], + }; +} + +vi.mock("@/lib/api/hooks/app/unibox/useUniboxSearch", () => ({ + default: (params: UniboxSearchParams, _scopeKey: string, enabled = true) => { + search.calls.push({ params, enabled }); + const emails = !enabled + ? [] + : params.agentDrafts + ? search.agentPending || search.agentFailed ? [] : [row("a1", "t-agent", "Agent reply to a lead"), row("a2", "t-both", "Agent reply on a drafted thread")] + : search.mailboxEmpty ? [] : [row("d1", "t-mine", "My own draft"), row("d2", "t-both", "Provider copy of a drafted thread")]; + return { + emails, + isPending: !!params.agentDrafts && search.agentPending, + isFetching: false, + isPlaceholderData: false, + isError: !!params.agentDrafts && search.agentFailed, + error: search.agentFailed ? new Error("Draft request failed") : null, + hasNextPage: enabled && (params.agentDrafts ? search.agentHasMore : search.mailboxHasMore), + isFetchingNextPage: false, + isFetchNextPageError: !!params.agentDrafts && search.agentPageFailed, + fetchNextPage: () => { + search.agentNextPage.push(params.agentDrafts ? "agent" : "mailbox"); + return Promise.resolve(); + }, + refetch: () => { + if (params.agentDrafts) search.agentRefetches++; + return Promise.resolve(); + }, + }; + }, +})); +vi.mock("./ConversationItem", () => ({ + ConversationItem: ({ email }: { email: { subject: string } }) =>
{email.subject}
, +})); +vi.mock("./AnimatedRow", () => ({ + AnimatedRow: ({ children }: { children: React.ReactNode }) => <>{children}, +})); +vi.mock("./SelectionBar", () => ({ SelectionBar: () => null })); +vi.mock("./UniboxFilterPopover", () => ({ + countUserFilters: () => 0, + UniboxFilterButton: () => null, + UniboxFilterChips: () => null, +})); +vi.mock("@/components/app/unibox/compose/ComposeButton", () => ({ default: () => null })); +vi.mock("@/hooks/useConversationActions", () => ({ useConversationActions: () => ({}) })); +vi.mock("@/hooks/useShortcutActions", () => ({ useShortcutActions: () => {} })); +vi.mock("@/hooks/usePermission", () => ({ useAccessRestricted: () => false })); +vi.mock("@/hooks/useBrowseDebouncedValue", () => ({ default: (v: unknown) => v })); +vi.mock("@/hooks/useScrollMemory", () => ({ useScrollMemory: () => {} })); +vi.mock("framer-motion", async (importOriginal) => ({ + ...(await importOriginal>()), + AnimatePresence: ({ children }: { children: React.ReactNode }) => <>{children}, +})); + +afterEach(() => { + cleanup(); + search.calls = []; + search.agentHasMore = false; + search.agentPageFailed = false; + search.mailboxHasMore = false; + search.agentNextPage = []; + search.agentPending = false; + search.agentFailed = false; + search.agentRefetches = 0; + search.mailboxEmpty = false; +}); + +function mount(params: UniboxSearchParams, scopeKey: string) { + return render( + {}} + search="" + setSearch={() => {}} + />, + ); +} + +it("lists pending agent drafts first under their own header, then the mailbox drafts", () => { + mount({ sortBy: "newest", folder: "drafts" }, "folder:drafts"); + + expect(screen.getByText("Agent drafts")).toBeTruthy(); + expect(screen.getAllByTestId("row").map((r) => r.textContent)).toEqual([ + "Agent reply to a lead", + "Agent reply on a drafted thread", + "My own draft", + ]); + const agent = search.calls.find((c) => c.params.agentDrafts); + expect(agent?.enabled).toBe(true); + expect(agent?.params.folder).toBeUndefined(); +}); + +it("leaves every other folder alone", () => { + mount({ sortBy: "newest", folder: "inbox", automated: false }, "folder:inbox"); + + expect(screen.queryByText("Agent drafts")).toBeNull(); + expect(search.calls.filter((c) => c.params.agentDrafts).every((c) => !c.enabled)).toBe(true); + expect(screen.getAllByTestId("row")).toHaveLength(2); +}); + +it("pages pending agent drafts through Load more without eagerly fetching every page", () => { + search.agentHasMore = true; + mount({ sortBy: "newest", folder: "drafts" }, "folder:drafts"); + + expect(search.agentNextPage).toEqual([]); + fireEvent.click(screen.getByRole("button", { name: "Load more" })); + expect(search.agentNextPage).toEqual(["agent"]); + expect(search.agentNextPage).not.toContain("mailbox"); +}); + +it("does not claim Drafts is empty while agent drafts are still loading", () => { + search.agentPending = true; + search.mailboxEmpty = true; + const { container } = mount({ sortBy: "newest", folder: "drafts" }, "folder:drafts"); + + expect(container.querySelector(".animate-pulse")).toBeTruthy(); + expect(screen.queryByText(/No conversations/)).toBeNull(); +}); + +it("offers a retry when agent drafts fail while keeping mailbox drafts visible", () => { + search.agentFailed = true; + mount({ sortBy: "newest", folder: "drafts" }, "folder:drafts"); + + expect(screen.getByRole("alert").textContent).toContain("couldn't load"); + expect(screen.getByText("My own draft")).toBeTruthy(); + fireEvent.click(screen.getByRole("button", { name: "Try again" })); + expect(search.agentRefetches).toBe(1); +}); + +it("shows a retry instead of an empty folder when the agent request fails", () => { + search.agentFailed = true; + search.mailboxEmpty = true; + mount({ sortBy: "newest", folder: "drafts" }, "folder:drafts"); + + expect(screen.getByText("Couldn't load inbox")).toBeTruthy(); + fireEvent.click(screen.getByRole("button", { name: "Try again" })); + expect(search.agentRefetches).toBe(1); +}); + +it("preserves mailbox, category and search filters for agent drafts", () => { + mount({ sortBy: "newest", folder: "drafts", accountIds: ["mailbox"], categoryIds: ["category"], query: "proposal" }, "folder:drafts"); + + expect(search.calls.find((c) => c.params.agentDrafts)?.params).toMatchObject({ + accountIds: ["mailbox"], categoryIds: ["category"], query: "proposal", + }); +}); + +it("keeps an explicitly empty mailbox scope empty", () => { + mount({ sortBy: "newest", folder: "drafts", accountIds: [] }, "folder:drafts"); + + expect(search.calls.every((c) => !c.enabled)).toBe(true); + expect(screen.queryAllByTestId("row")).toHaveLength(0); +}); + +it("never pages agent drafts outside the Drafts folder", () => { + search.agentHasMore = true; + mount({ sortBy: "newest", folder: "inbox", automated: false }, "folder:inbox"); + + expect(search.agentNextPage).toEqual([]); +}); + +it("keeps mailbox pagination and a separate agent retry reachable after an agent-page failure", () => { + search.agentHasMore = true; + search.agentPageFailed = true; + search.mailboxHasMore = true; + mount({ sortBy: "newest", folder: "drafts" }, "folder:drafts"); + + fireEvent.click(screen.getByRole("button", { name: "Load more" })); + expect(search.agentNextPage).toEqual(["mailbox"]); + fireEvent.click(screen.getByRole("button", { name: "Retry agent drafts" })); + expect(search.agentNextPage).toEqual(["mailbox", "agent"]); +}); diff --git a/web/src/components/app/unibox/scopeRail.test.tsx b/web/src/components/app/unibox/scopeRail.test.tsx index d18a055cd..ddc0e1b6a 100644 --- a/web/src/components/app/unibox/scopeRail.test.tsx +++ b/web/src/components/app/unibox/scopeRail.test.tsx @@ -34,6 +34,7 @@ const overview = vi.hoisted(() => ({ automated: 0, automated_unread: 0, awaiting_agent_draft: 0, + drafts: undefined as number | undefined, scheduled_pending: 0, scheduled_pending_max: 100, folders: [ @@ -1139,3 +1140,32 @@ describe("sanitizeUniboxRailFavorites", () => { } }); }); + +it("counts pending agent drafts on Drafts and highlights them", () => { + const saved = overview.data; + overview.data = { + ...saved, + awaiting_agent_draft: 3, + drafts: 3, + folders: [...saved.folders, { folder: "drafts", unread: 0, total: 1 }], + }; + try { + mountRail(); + const rows = Array.from(document.querySelectorAll("[data-rail-row]")).map((r) => r.textContent ?? ""); + expect(rows.find((r) => r.startsWith("Drafts"))).toBe("Drafts3"); + } finally { + overview.data = saved; + } +}); + +it("keeps the mailbox Drafts count when connected to an older backend", () => { + const saved = overview.data; + overview.data = { ...saved, awaiting_agent_draft: 3, folders: [...saved.folders, { folder: "drafts", unread: 0, total: 1 }] }; + try { + mountRail(); + const rows = Array.from(document.querySelectorAll("[data-rail-row]")).map((r) => r.textContent ?? ""); + expect(rows.find((r) => r.startsWith("Drafts"))).toBe("Drafts1"); + } finally { + overview.data = saved; + } +}); diff --git a/web/src/lib/api/client/app/emails/sendingDomains.ts b/web/src/lib/api/client/app/emails/sendingDomains.ts index 84030b052..116901c11 100644 --- a/web/src/lib/api/client/app/emails/sendingDomains.ts +++ b/web/src/lib/api/client/app/emails/sendingDomains.ts @@ -4,6 +4,7 @@ import type { BulkDomainResult, BulkDomainSetupRequest, DomainRedirect, + RedirectWebsite, SendingDomain, SetDomainRedirectRequest, SetDomainTrackingResult, @@ -48,6 +49,17 @@ export async function setDomainRedirect(domain: string, body: SetDomainRedirectR }); } +// Looks for the TXT record that makes the destination's website the workspace's, now. +export async function verifyRedirectWebsite(domain: string, targetUrl: string): Promise { + return await Request({ + method: "POST", + url: `${base(domain)}/redirect/website`, + data: { target_url: targetUrl }, + authorization: true, + timeout: 15_000, + }); +} + // Checks DNS now instead of waiting for the background check. export async function verifyDomainRedirect(domain: string): Promise { return await Request({ diff --git a/web/src/lib/api/client/auth/identities/list.ts b/web/src/lib/api/client/auth/identities/list.ts new file mode 100644 index 000000000..e8f48b373 --- /dev/null +++ b/web/src/lib/api/client/auth/identities/list.ts @@ -0,0 +1,12 @@ +import Request from "../../Request"; +import type LinkedIdentity from "@/lib/api/models/auth/LinkedIdentity"; + +export default async function listLinkedIdentities(signal?: AbortSignal): Promise { + const res = await Request<{ data: LinkedIdentity[] }>({ + method: "GET", + url: "/auth/me/identities", + authorization: true, + signal, + }); + return res.data; +} diff --git a/web/src/lib/api/client/auth/identities/unlink.ts b/web/src/lib/api/client/auth/identities/unlink.ts new file mode 100644 index 000000000..c81555069 --- /dev/null +++ b/web/src/lib/api/client/auth/identities/unlink.ts @@ -0,0 +1,10 @@ +import Request from "../../Request"; + +// Needs a fresh confirmation; the client prompts for it on reauth_required. +export default async function unlinkIdentity(provider: string): Promise { + await Request({ + method: "DELETE", + url: `/auth/me/identities/${encodeURIComponent(provider)}`, + authorization: true, + }); +} diff --git a/web/src/lib/api/client/auth/logout.ts b/web/src/lib/api/client/auth/logout.ts index d6afef646..93a13972c 100644 --- a/web/src/lib/api/client/auth/logout.ts +++ b/web/src/lib/api/client/auth/logout.ts @@ -1,9 +1,11 @@ import Request from "../Request"; -export default async function logout(): Promise { +// device_tokens names the remembered-device tokens this browser holds, so the server forgets them too. +export default async function logout(deviceTokens: string[] = []): Promise { await Request({ method: "POST", url: "/auth/logout", authorization: true, + data: deviceTokens.length ? { device_tokens: deviceTokens } : undefined, }); } diff --git a/web/src/lib/api/client/auth/sendPasswordLink.ts b/web/src/lib/api/client/auth/sendPasswordLink.ts new file mode 100644 index 000000000..d8adf9227 --- /dev/null +++ b/web/src/lib/api/client/auth/sendPasswordLink.ts @@ -0,0 +1,10 @@ +import Request from "../Request"; + +// Emails the signed-in user a single-use link to set a password. +export default async function sendPasswordLink(): Promise { + await Request({ + method: "POST", + url: "/auth/me/password/link", + authorization: true, + }); +} diff --git a/web/src/lib/api/client/auth/setInitialPassword.ts b/web/src/lib/api/client/auth/setInitialPassword.ts new file mode 100644 index 000000000..340e8cd1d --- /dev/null +++ b/web/src/lib/api/client/auth/setInitialPassword.ts @@ -0,0 +1,15 @@ +import type Session from "../../models/auth/Session"; +import Request from "../Request"; + +/** + * Answers a sign-in that came back `password_change_required`: the password + * was an issued initial one, and this replaces it with the holder's own. The + * result continues the sign-in in the same shape POST /auth/login returns. + */ +export default async function setInitialPassword(pending_token: string, password: string, device_token?: string): Promise { + return await Request({ + method: "POST", + url: "/auth/login/initial-password", + data: { pending_token, password, device_token }, + }); +} diff --git a/web/src/lib/api/hooks/app/emails/useSendingDomains.ts b/web/src/lib/api/hooks/app/emails/useSendingDomains.ts index c0d54810a..079c67c6a 100644 --- a/web/src/lib/api/hooks/app/emails/useSendingDomains.ts +++ b/web/src/lib/api/hooks/app/emails/useSendingDomains.ts @@ -11,6 +11,7 @@ import { setDomainVendorForwarding, setDomainVendorTracking, verifyDomainRedirect, + verifyRedirectWebsite, } from "@/lib/api/client/app/emails/sendingDomains"; import type { BulkDomainResult, @@ -101,6 +102,17 @@ export function useVerifyDomainRedirect() { }); } +// A website that verifies changes which redirects are served, so the list is read again. +export function useVerifyRedirectWebsite() { + const qc = useQueryClient(); + return useMutation({ + mutationFn: ({ domain, url }: { domain: string; url: string }) => verifyRedirectWebsite(domain, url), + onSuccess: (w) => { + if (w.verified) qc.invalidateQueries({ queryKey: SENDING_DOMAINS_KEY }); + }, + }); +} + export function useDeleteDomainRedirect() { const qc = useQueryClient(); const store = useStoreRedirect(); diff --git a/web/src/lib/api/hooks/auth/useLinkedIdentities.ts b/web/src/lib/api/hooks/auth/useLinkedIdentities.ts new file mode 100644 index 000000000..aff930bbc --- /dev/null +++ b/web/src/lib/api/hooks/auth/useLinkedIdentities.ts @@ -0,0 +1,9 @@ +import { useQuery } from "@tanstack/react-query"; +import listLinkedIdentities from "@/lib/api/client/auth/identities/list"; + +export default function useLinkedIdentities() { + return useQuery({ + queryKey: ["auth", "identities"], + queryFn: ({ signal }) => listLinkedIdentities(signal), + }); +} diff --git a/web/src/lib/api/hooks/auth/useLogout.ts b/web/src/lib/api/hooks/auth/useLogout.ts index 596550aaf..768aaa829 100644 --- a/web/src/lib/api/hooks/auth/useLogout.ts +++ b/web/src/lib/api/hooks/auth/useLogout.ts @@ -1,6 +1,7 @@ import { useMutation, useQueryClient } from "@tanstack/react-query"; import logout from "../../client/auth/logout"; import { clearClientSession } from "@/lib/session"; +import { allTrustedDevices, forgetAllTrustedDevices } from "@/lib/trustedDevice"; // Single source of truth for "log this user out fully". Order matters: // @@ -24,7 +25,7 @@ export default function useLogout() { return useMutation({ mutationFn: async () => { try { - await logout(); + await logout(allTrustedDevices()); } catch { // Server revoke best-effort. We still clear locally so // the user isn't stuck in a "logged in" state because @@ -33,6 +34,9 @@ export default function useLogout() { }, // Shared with the session-expiry paths, so signing out and being signed // out leave the browser in the same state. - onSettled: () => clearClientSession(queryClient), + onSettled: () => { + forgetAllTrustedDevices(); + clearClientSession(queryClient); + }, }); } diff --git a/web/src/lib/api/hooks/auth/useReauthMethods.ts b/web/src/lib/api/hooks/auth/useReauthMethods.ts new file mode 100644 index 000000000..b53d9c4c7 --- /dev/null +++ b/web/src/lib/api/hooks/auth/useReauthMethods.ts @@ -0,0 +1,9 @@ +import { useQuery } from "@tanstack/react-query"; +import getReauthMethods from "@/lib/api/client/auth/reauth/methods"; + +export default function useReauthMethods() { + return useQuery({ + queryKey: ["auth", "reauth-methods"], + queryFn: ({ signal }) => getReauthMethods(signal), + }); +} diff --git a/web/src/lib/api/hooks/auth/useSetInitialPassword.ts b/web/src/lib/api/hooks/auth/useSetInitialPassword.ts new file mode 100644 index 000000000..87e8f7735 --- /dev/null +++ b/web/src/lib/api/hooks/auth/useSetInitialPassword.ts @@ -0,0 +1,9 @@ +import { useMutation } from "@tanstack/react-query"; +import setInitialPassword from "../../client/auth/setInitialPassword"; + +export default function useSetInitialPassword() { + return useMutation({ + mutationFn: ({ pending_token, password, device_token }: { pending_token: string; password: string; device_token?: string }) => + setInitialPassword(pending_token, password, device_token), + }); +} diff --git a/web/src/lib/api/hooks/auth/useUnlinkIdentity.ts b/web/src/lib/api/hooks/auth/useUnlinkIdentity.ts new file mode 100644 index 000000000..9ab0b8636 --- /dev/null +++ b/web/src/lib/api/hooks/auth/useUnlinkIdentity.ts @@ -0,0 +1,15 @@ +import { useMutation, useQueryClient } from "@tanstack/react-query"; +import unlinkIdentity from "@/lib/api/client/auth/identities/unlink"; + +// Not optimistic: the server refuses removing the last way to sign in. +export default function useUnlinkIdentity() { + const queryClient = useQueryClient(); + return useMutation({ + mutationFn: (provider: string) => unlinkIdentity(provider), + onSettled: () => { + queryClient.invalidateQueries({ queryKey: ["auth", "identities"] }); + queryClient.invalidateQueries({ queryKey: ["auth", "reauth-methods"] }); + queryClient.invalidateQueries({ queryKey: ["sessions"] }); + }, + }); +} diff --git a/web/src/lib/api/models/app/emails/SendingDomain.ts b/web/src/lib/api/models/app/emails/SendingDomain.ts index 7b6dc5c92..f31dd477f 100644 --- a/web/src/lib/api/models/app/emails/SendingDomain.ts +++ b/web/src/lib/api/models/app/emails/SendingDomain.ts @@ -11,7 +11,7 @@ export interface TrackingDomainUse { mailboxes: number; } -export type DNSRecordPurpose = "ownership" | "root" | "www"; +export type DNSRecordPurpose = "ownership" | "root" | "www" | "website"; /** One record to add at the DNS provider, and whether it is in place. */ export interface DNSRecord { @@ -62,6 +62,16 @@ export interface DomainRedirect { target_active?: boolean; /** Why the saved destination is not in use, when target_active is false. */ target_inactive_reason?: string; + /** Set when the destination is the workspace's only once its website carries the workspace's TXT record. */ + website?: RedirectWebsite | null; +} + +/** A destination website and the TXT record, at the website's own DNS, that proves it is the workspace's. */ +export interface RedirectWebsite { + domain: string; + verified: boolean; + /** Absent when the website is already one of the workspace's domains. */ + record?: DNSRecord | null; } export interface SendingDomain { diff --git a/web/src/lib/api/models/app/unibox/UniboxOverview.ts b/web/src/lib/api/models/app/unibox/UniboxOverview.ts index b4d47446a..05968c9f2 100644 --- a/web/src/lib/api/models/app/unibox/UniboxOverview.ts +++ b/web/src/lib/api/models/app/unibox/UniboxOverview.ts @@ -46,6 +46,8 @@ export default interface UniboxOverview { automated_unread: number; /** Threads with a pending inbox-agent draft awaiting human review. */ awaiting_agent_draft: number; + /** Distinct conversations across mailbox drafts and visible pending agent replies; absent on older servers. */ + drafts?: number; /** Pending outbound email tasks queued from the workspace's mailboxes. */ scheduled_pending: number; /** diff --git a/web/src/lib/api/models/auth/LinkedIdentity.ts b/web/src/lib/api/models/auth/LinkedIdentity.ts new file mode 100644 index 000000000..42954434d --- /dev/null +++ b/web/src/lib/api/models/auth/LinkedIdentity.ts @@ -0,0 +1,8 @@ +// GET /auth/me/identities: a provider the account can sign in with. +export default interface LinkedIdentity { + provider: "google" | "apple" | "oidc"; + label: string; + email?: string; + created_at: string; + last_login_at?: string; +} diff --git a/web/src/lib/api/models/auth/Session.ts b/web/src/lib/api/models/auth/Session.ts index a482a44bc..2a4fb32df 100644 --- a/web/src/lib/api/models/auth/Session.ts +++ b/web/src/lib/api/models/auth/Session.ts @@ -15,4 +15,7 @@ export default interface Session { two_fa_required?: boolean; pending_token?: string; expires_in?: number; + /** The password was an issued initial one: post `pending_token` and a new + * password to /auth/login/initial-password before anything else. */ + password_change_required?: boolean; } diff --git a/web/src/lib/resetLinkToken.test.ts b/web/src/lib/resetLinkToken.test.ts index 0e53d8eb9..e125c5f4a 100644 --- a/web/src/lib/resetLinkToken.test.ts +++ b/web/src/lib/resetLinkToken.test.ts @@ -3,18 +3,11 @@ import { resetLinkToken } from "./resetLinkToken"; describe("resetLinkToken", () => { it("reads the token from the fragment", () => { - expect(resetLinkToken("#session=a.b.c", new URLSearchParams())).toBe("a.b.c"); + expect(resetLinkToken("#session=a.b.c")).toBe("a.b.c"); }); - it("still reads a link that carries it in the query", () => { - expect(resetLinkToken("", new URLSearchParams("session=a.b.c"))).toBe("a.b.c"); - }); - - it("prefers the fragment when both are present", () => { - expect(resetLinkToken("#session=frag", new URLSearchParams("session=query"))).toBe("frag"); - }); - - it("is empty without a token", () => { - expect(resetLinkToken("#other=1", new URLSearchParams("to=x"))).toBe(""); + it("is empty without a token in the fragment", () => { + expect(resetLinkToken("#other=1")).toBe(""); + expect(resetLinkToken("")).toBe(""); }); }); diff --git a/web/src/lib/resetLinkToken.ts b/web/src/lib/resetLinkToken.ts index ccb87aedc..18d39142f 100644 --- a/web/src/lib/resetLinkToken.ts +++ b/web/src/lib/resetLinkToken.ts @@ -1,5 +1,4 @@ -// The emailed reset link carries its token in the fragment; mail sent before that carries it in the query. -export function resetLinkToken(hash: string, search: URLSearchParams): string { - const fromHash = new URLSearchParams(hash.replace(/^#/, "")).get("session"); - return fromHash || search.get("session") || ""; +// The emailed reset link carries its token in the fragment, which never reaches a server; nothing else is read. +export function resetLinkToken(hash: string): string { + return new URLSearchParams(hash.replace(/^#/, "")).get("session") ?? ""; } diff --git a/web/src/lib/trustedDevice.ts b/web/src/lib/trustedDevice.ts index 0b89d693d..526717442 100644 --- a/web/src/lib/trustedDevice.ts +++ b/web/src/lib/trustedDevice.ts @@ -3,7 +3,7 @@ // sign-in skip that code; the server still asks for the password, TOTP and, // when the sign-in looks unusual, the code anyway. // -// It belongs to the browser rather than the session, so signing out keeps it. +// Signing out forgets the tokens this browser holds, on the server and here. // The server forgets every token when the password changes or the user signs // out everywhere. const KEY = "warmbly-trusted-devices"; @@ -45,3 +45,11 @@ export function forgetTrustedDevice(email: string) { delete store[accountKey(email)]; write(store); } + +export function allTrustedDevices(): string[] { + return Object.values(read()).filter((tok): tok is string => typeof tok === "string" && tok !== ""); +} + +export function forgetAllTrustedDevices() { + write({}); +}