diff --git a/.env.example b/.env.example index 583d02b4d..56585a5ab 100644 --- a/.env.example +++ b/.env.example @@ -438,8 +438,6 @@ BILLING_PROVIDER=none # BOX_GOOGLE_CLIENT_SECRET= # Optional backend kill switch; unset enables connects when both keys are set. # BOX_GOOGLE_OAUTH_CONNECT=false -# Dashboard visibility, independent of backend availability. Off by default. -WARMBLY_GMAIL_OAUTH_CONNECT=false # Redirect URI: /addresses/outlook/callback # BOX_OUTLOOK_CLIENT_ID= # BOX_OUTLOOK_CLIENT_SECRET= @@ -623,6 +621,21 @@ PUBSUB_ENABLED=false # SEARCH_API_URL= # SEARCH_API_KEY= +# === Lead finder (optional) =================================================== +# +# Works with nothing set: OpenStreetMap through public Overpass servers, the +# Photon geocoder and OpenFreeMap tiles. Your own Overpass (comma-separated, tried +# in order) is far more dependable than the shared public ones. Instance keys let +# every workspace without its own key search that source, at a credit a page. +# A map style hosted elsewhere also needs its origins in WARMBLY_CSP_CONNECT_ORIGINS. +# LEAD_FINDER_OVERPASS_URL= +# LEAD_FINDER_GEOCODER_URL= +# LEAD_FINDER_MAP_STYLE_URL= +# LEAD_FINDER_MAP_STYLE_DARK_URL= +# LEAD_FINDER_GOOGLE_PLACES_API_KEY= +# LEAD_FINDER_FOURSQUARE_API_KEY= +# LEAD_FINDER_OUTSCRAPER_API_KEY= + # === Integrations (optional) ================================================== # Shared redirect URI for the CRM and messaging OAuth flows. Unset, it becomes diff --git a/.github/scripts/aws-backend-config.cjs b/.github/scripts/aws-backend-config.cjs new file mode 100644 index 000000000..d3969ff7f --- /dev/null +++ b/.github/scripts/aws-backend-config.cjs @@ -0,0 +1,167 @@ +const { + ECSClient, DescribeServicesCommand, DescribeTasksCommand, UpdateServiceCommand, +} = require("@aws-sdk/client-ecs"); +const { CloudWatchClient, DescribeAlarmsCommand } = require("@aws-sdk/client-cloudwatch"); +const { + configuration: deploymentConfiguration, describe, compareTags, register, same, waitForService, + ATTACHMENT_PROXY, ATTACHMENT_PROXY_TAG, +} = require("./aws-deploy.cjs"); + +const tagValue = (tags, key) => tags.find((t) => t.key === key)?.value; +const canonicalTags = (tags) => JSON.stringify(tags.filter((t) => !t.key.startsWith("aws:")).sort((a, b) => a.key.localeCompare(b.key))); + +function configuration(env) { + const config = deploymentConfiguration({ ...env, DEPLOY_MODE: "redeploy", DEPLOY_SERVICES: "backend", DEPLOY_FLEET: "false", DEPLOY_BAKE_SECONDS: "300" }); + if (!config.tag || !config.images || config.images.tag !== config.tag || compareTags(config.tag, "v0.6.75") < 0) { + throw new Error("A published v0.6.75 or newer release and its images.json are required"); + } + const account = config.cluster.split(":")[4]; + const expected = env.CONFIG_EXPECTED_TASK_DEFINITION || ""; + const expectedPrefix = `arn:aws:ecs:us-east-1:${account}:task-definition/${config.prefix}-backend:`; + if (!expected.startsWith(expectedPrefix) || !/^[1-9]\d*$/.test(expected.slice(expectedPrefix.length))) { + throw new Error("CONFIG_EXPECTED_TASK_DEFINITION must identify this cluster's backend revision"); + } + if (!["true", "false"].includes(env.CONFIG_ATTACHMENT_DOWNLOAD_PROXY)) throw new Error("CONFIG_ATTACHMENT_DOWNLOAD_PROXY must be true or false"); + const tasks = JSON.parse(env.CONFIG_EXPECTED_TASKS || "null"); + const taskPrefix = `arn:aws:ecs:us-east-1:${account}:task/${config.cluster.split("/").pop()}/`; + if (!Array.isArray(tasks) || !tasks.length || tasks.some((task) => typeof task !== "string" || !task.startsWith(taskPrefix) || !/^[a-f0-9]{32}$/.test(task.slice(taskPrefix.length))) || + new Set(tasks).size !== tasks.length) throw new Error("CONFIG_EXPECTED_TASKS must list unique current task ARNs from this cluster's read-only preflight"); + return { ...config, expected, tasks, value: env.CONFIG_ATTACHMENT_DOWNLOAD_PROXY }; +} + +async function service(ecs, config) { + const out = await ecs.send(new DescribeServicesCommand({ cluster: config.cluster, services: [`${config.prefix}-backend`] })); + const live = out.services?.[0]; + if (out.failures?.length || out.services?.length !== 1 || live.status !== "ACTIVE") throw new Error("Backend service is unavailable"); + return live; +} + +function stable(live, expected, count) { + if (live.taskDefinition !== expected || !Number.isInteger(live.desiredCount) || live.desiredCount < 1 || live.runningCount !== live.desiredCount || live.pendingCount !== 0 || + live.deployments?.length !== 1 || live.deployments[0].rolloutState !== "COMPLETED" || + live.deployments[0].taskDefinition !== expected || live.deployments[0].runningCount !== live.desiredCount || + live.deployments[0].desiredCount !== live.desiredCount || live.deployments[0].pendingCount !== 0 || + (count !== undefined && live.desiredCount !== count)) throw new Error("Backend must be stable on the expected revision and task count"); +} + +async function verifyTasks(ecs, config, live, definition) { + stable(live, definition.taskDefinitionArn); + const arns = config.tasks; + if (new Set(arns).size !== live.desiredCount || arns.length !== live.desiredCount) throw new Error("Every running backend task must be accounted for"); + for (let offset = 0; offset < arns.length; offset += 100) { + const batch = arns.slice(offset, offset + 100); + const out = await ecs.send(new DescribeTasksCommand({ cluster: config.cluster, tasks: batch })); + if (out.failures?.length || out.tasks?.length !== batch.length || new Set(out.tasks.map((t) => t.taskArn)).size !== batch.length) { + throw new Error("Every running backend task must be described"); + } + for (const task of out.tasks) { + if (!batch.includes(task.taskArn) || task.taskDefinitionArn !== live.taskDefinition || task.group !== `service:${live.serviceName}` || + task.lastStatus !== "RUNNING" || task.desiredStatus !== "RUNNING" || task.containers?.length !== 1 || task.containers[0].name !== "backend" || + task.containers[0].image !== definition.containerDefinitions[0].image || + (definition.containerDefinitions[0].healthCheck && task.healthStatus !== "HEALTHY") || + task.overrides?.containerOverrides?.some((c) => Object.keys(c).some((k) => k !== "name"))) { + throw new Error("Every backend task must use the verified image and unmodified service configuration"); + } + } + } +} + +async function alarms(clients, config) { + const out = await clients.cloudwatch.send(new DescribeAlarmsCommand({ AlarmNamePrefix: `${config.prefix}-backend-`, StateValue: "ALARM" })); + if (out.MetricAlarms?.length || out.CompositeAlarms?.length) throw new Error("Backend alarm fired during configuration rollout"); +} + +async function observe(clients, config, definition, count, sleep, report) { + for (let waited = 0; waited <= 300; waited += 15) { + stable(await service(clients.ecs, config), definition.taskDefinitionArn, count); + await alarms(clients, config); + if (waited < 300) await sleep(15000); + } + const current = await describe(clients.ecs, definition.taskDefinitionArn); + if (!same(current.definition, definition)) throw new Error("Backend configuration readback does not match the expected definition"); + report("Backend configuration and service counts verified after a 300s bake; independently inspect the resulting tasks and download responses"); +} + +async function configure(clients, config, sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)), report = console.log) { + const live = await service(clients.ecs, config); + stable(live, live.taskDefinition); + const source = await describe(clients.ecs, live.taskDefinition); + const definition = source.definition; + const container = definition.containerDefinitions?.[0]; + const variant = tagValue(source.tags, "warmbly-image-variant"); + if (tagValue(source.tags, "warmbly-release") !== config.tag || !["default", "kafka"].includes(variant) || + definition.family !== `${config.prefix}-backend` || definition.containerDefinitions?.length !== 1 || container.name !== "backend") { + throw new Error("Live backend must identify the selected release, family and image variant"); + } + const digest = config.images.images?.[`backend${variant === "kafka" ? "-kafka" : ""}`]; + if (config.images.registry !== "ghcr.io/warmbly/warmbly" || !/^sha256:[a-f0-9]{64}$/.test(digest || "") || + container.image !== `${config.images.registry}/backend@${digest}`) throw new Error("Live backend image must match the attested release digest"); + if (container.secrets?.some((s) => s.name === ATTACHMENT_PROXY)) throw new Error("Attachment proxy flag must not be secret-backed"); + const values = (container.environment || []).filter((e) => e.name === ATTACHMENT_PROXY); + const managed = tagValue(source.tags, ATTACHMENT_PROXY_TAG); + if (values.length > 1 || (values.length && !["true", "false"].includes(values[0].value)) || + (managed !== undefined && (values.length !== 1 || managed !== values[0].value))) throw new Error("Attachment proxy configuration is ambiguous"); + await verifyTasks(clients.ecs, config, live, definition); + await alarms(clients, config); + if ((values[0]?.value || "false") === config.value) { + if (config.value === "true" && managed === undefined) { + const latest = await describe(clients.ecs, definition.family); + const explicit = latest.definition.containerDefinitions?.[0]?.environment?.some((e) => e.name === ATTACHMENT_PROXY); + if (tagValue(latest.tags, ATTACHMENT_PROXY_TAG) === undefined && !explicit) { + throw new Error("Enabled attachment configuration requires a management tag or an explicit Terraform value before a no-change request"); + } + } + report("Backend already has the requested attachment configuration; no change"); + await observe(clients, config, definition, live.desiredCount, sleep, report); + return { taskDefinition: live.taskDefinition, previous: live.taskDefinition, changed: false }; + } + if (live.taskDefinition !== config.expected) throw new Error("Expected backend revision changed; inspect it before requesting a configuration change"); + const rendered = structuredClone(definition); + rendered.containerDefinitions[0].environment = (container.environment || []).filter((e) => e.name !== ATTACHMENT_PROXY); + rendered.containerDefinitions[0].environment.push({ name: ATTACHMENT_PROXY, value: config.value }); + const tags = source.tags.filter((t) => t.key !== ATTACHMENT_PROXY_TAG); + tags.push({ key: ATTACHMENT_PROXY_TAG, value: config.value }); + const latest = await describe(clients.ecs, definition.family); + const prepared = same(latest.definition, rendered) && canonicalTags(latest.tags) === canonicalTags(tags); + const next = prepared ? latest.definition.taskDefinitionArn : await register(clients.ecs, source, rendered, tags, config.tag, report); + stable(await service(clients.ecs, config), live.taskDefinition, live.desiredCount); + try { + // Every backend writer must use the shared deployment queue. + await clients.ecs.send(new UpdateServiceCommand({ cluster: config.cluster, service: live.serviceName, taskDefinition: next })); + await waitForService(clients.ecs, config, "backend", next, sleep); + await observe(clients, config, { ...rendered, taskDefinitionArn: next }, live.desiredCount, sleep, report); + return { taskDefinition: next, previous: live.taskDefinition, changed: true }; + } catch (error) { + try { + const current = await service(clients.ecs, config); + if (![live.taskDefinition, next].includes(current.taskDefinition) || current.desiredCount !== live.desiredCount) { + throw new Error("Backend changed concurrently; automatic rollback refused"); + } + if (current.taskDefinition === next) await clients.ecs.send(new UpdateServiceCommand({ cluster: config.cluster, service: live.serviceName, taskDefinition: live.taskDefinition })); + await waitForService(clients.ecs, config, "backend", live.taskDefinition, sleep); + stable(await service(clients.ecs, config), live.taskDefinition, live.desiredCount); + if (!same((await describe(clients.ecs, live.taskDefinition)).definition, definition)) throw new Error("Previous backend definition readback changed"); + report("Restored and verified the exact previous backend revision and service counts; independently inspect its current tasks"); + } catch { + throw new Error("Configuration rollout failed and rollback could not be verified; inspect the backend before any further change", { cause: error }); + } + throw error; + } +} + +if (require.main === module) { + const region = { region: "us-east-1", maxAttempts: 3 }; + const clients = { ecs: new ECSClient(region), cloudwatch: new CloudWatchClient(region) }; + const lines = []; + const report = (line) => { console.log(line); lines.push(line); }; + Promise.resolve().then(() => configure(clients, configuration(process.env), undefined, report)).catch((error) => { + const message = error?.$metadata ? `AWS request failed: ${error.name}` : error.message; + report(`Failed: ${message}`); + process.exitCode = 1; + }).finally(() => { + if (process.env.GITHUB_STEP_SUMMARY) require("node:fs").appendFileSync(process.env.GITHUB_STEP_SUMMARY, `### Backend configuration\n\n\`\`\`\n${lines.join("\n")}\n\`\`\`\n`); + for (const client of Object.values(clients)) client.destroy(); + }); +} + +module.exports = { configuration, configure }; diff --git a/.github/scripts/aws-backend-config.test.cjs b/.github/scripts/aws-backend-config.test.cjs new file mode 100644 index 000000000..90272788a --- /dev/null +++ b/.github/scripts/aws-backend-config.test.cjs @@ -0,0 +1,277 @@ +const { test } = require("node:test"); +const assert = require("node:assert/strict"); +const { mkdtempSync, writeFileSync, rmSync } = require("node:fs"); +const { tmpdir } = require("node:os"); +const { join } = require("node:path"); +const { configuration, configure } = require("./aws-backend-config.cjs"); +const { REGISTER_FIELDS, ATTACHMENT_PROXY, ATTACHMENT_PROXY_TAG } = require("./aws-deploy.cjs"); + +const root = "arn:aws:ecs:us-east-1:000000000000:"; +const arn = (revision) => `${root}task-definition/fixture-backend:${revision}`; +const task = (number) => `${root}task/fixture/${number.toString(16).padStart(32, "0")}`; +const runningTasks = (revision, count = 2) => Array.from({ length: count }, (_, i) => task(revision * 1000 + i + 1)); +const image = `ghcr.io/warmbly/warmbly/backend@sha256:${"a".repeat(64)}`; + +function fixture(t, options = {}) { + const count = options.taskCount || 2; + const dir = mkdtempSync(join(tmpdir(), "backend-config-")); + t.after(() => rmSync(dir, { recursive: true, force: true })); + const manifest = { tag: "v0.6.75", registry: "ghcr.io/warmbly/warmbly", images: { "backend-kafka": `sha256:${"a".repeat(64)}` } }; + writeFileSync(join(dir, "images.json"), JSON.stringify(manifest)); + const env = { AWS_ECS_CLUSTER: root + "cluster/fixture", DEPLOY_TAG: manifest.tag, DEPLOY_IMAGES_JSON: join(dir, "images.json"), + CONFIG_EXPECTED_TASK_DEFINITION: arn(1), CONFIG_EXPECTED_TASKS: JSON.stringify(runningTasks(1, count)), CONFIG_ATTACHMENT_DOWNLOAD_PROXY: "true" }; + const cfg = configuration(env); + const live = { serviceName: "fixture-backend", status: "ACTIVE", taskDefinition: arn(1), desiredCount: count, runningCount: count, pendingCount: 0, + deployments: [{ rolloutState: "COMPLETED", taskDefinition: arn(1), desiredCount: count, runningCount: count, pendingCount: 0 }] }; + const base = { family: "fixture-backend", status: "ACTIVE", revision: 1, taskDefinitionArn: arn(1), + taskRoleArn: root + "role/task", executionRoleArn: root + "role/execution", networkMode: "awsvpc", cpu: "256", memory: "512", + requiresCompatibilities: ["FARGATE"], runtimePlatform: { cpuArchitecture: "ARM64", operatingSystemFamily: "LINUX" }, + ephemeralStorage: { sizeInGiB: 30 }, volumes: [{ name: "fixture" }], + containerDefinitions: [{ name: "backend", image, stopTimeout: 120, readonlyRootFilesystem: true, + environment: [{ name: "TLS_ONLY", value: "true" }], + secrets: [{ name: "PRIMARY_DB", valueFrom: "fixture:immutable-version" }], + healthCheck: { command: ["CMD", "/app/healthcheck"], interval: 30, retries: 3 }, + logConfiguration: { logDriver: "awslogs", options: { "awslogs-group": "/fixture" } } }] }; + const tags = [{ key: "warmbly-release", value: manifest.tag }, { key: "warmbly-image-variant", value: "kafka" }, { key: "Owner", value: "fixture" }]; + const defs = new Map([[arn(1), { definition: base, tags }]]); + const calls = []; + const sleeps = []; + let latest = arn(1); + const ecs = {}; + ecs.send = async (command) => { + const name = command.constructor.name; + calls.push({ name, input: structuredClone(command.input) }); + if (options.hook) await options.hook(name, { live, defs, calls }); + switch (name) { + case "DescribeServicesCommand": return { services: [structuredClone(live)] }; + case "DescribeTaskDefinitionCommand": { + const entry = defs.get(command.input.taskDefinition === "fixture-backend" ? latest : command.input.taskDefinition); + return { taskDefinition: structuredClone(entry.definition), tags: structuredClone(entry.tags) }; + } + case "DescribeTasksCommand": return { tasks: (options.missingTask ? command.input.tasks.slice(1) : command.input.tasks).map((taskArn) => ({ + taskArn, taskDefinitionArn: options.wrongTask ? arn(99) : live.taskDefinition, + group: options.foreignGroup ? "service:fixture-foreign" : "service:fixture-backend", lastStatus: "RUNNING", + desiredStatus: options.drainingTask || !runningTasks(Number(live.taskDefinition.split(":").pop()), count).includes(taskArn) ? "STOPPED" : "RUNNING", + healthStatus: options.unhealthyTask ? "UNHEALTHY" : "HEALTHY", + containers: [{ name: "backend", image }], overrides: { containerOverrides: options.override ? [{ name: "backend", command: ["other"] }] : [{ name: "backend" }] }, + })) }; + case "RegisterTaskDefinitionCommand": { + latest = arn(defs.size + 1); + const { tags: nextTags, ...input } = structuredClone(command.input); + if (options.reorderEnvironment) input.containerDefinitions[0].environment.reverse(); + defs.set(latest, { definition: { ...input, status: "ACTIVE", taskDefinitionArn: latest }, tags: nextTags }); + return { taskDefinition: { taskDefinitionArn: latest } }; + } + case "UpdateServiceCommand": { + live.taskDefinition = command.input.taskDefinition; + live.deployments = [{ rolloutState: options.failedRoll && live.taskDefinition !== arn(1) ? "FAILED" : "COMPLETED", + taskDefinition: live.taskDefinition, desiredCount: count, runningCount: count, pendingCount: 0 }]; + return {}; + } + default: throw new Error(`Unexpected ${name}`); + } + }; + const cloudwatch = { async send(command) { + calls.push({ name: command.constructor.name, input: structuredClone(command.input) }); + return { MetricAlarms: options.alarm && live.taskDefinition !== arn(1) ? [{ AlarmName: "fixture-backend-5xx" }] : [] }; + } }; + const run = () => configure({ ecs, cloudwatch }, cfg, async (ms) => sleeps.push(ms), () => {}); + const prepare = (definition, nextTags) => { + latest = arn(defs.size + 1); + defs.set(latest, { definition: { ...structuredClone(definition), taskDefinitionArn: latest }, tags: structuredClone(nextTags) }); + }; + return { env, cfg, live, base, tags, defs, calls, sleeps, run, prepare }; +} + +const mutations = (f) => f.calls.filter((c) => ["RegisterTaskDefinitionCommand", "UpdateServiceCommand"].includes(c.name)); + +test("only the allowlisted flag and ownership tag change; every live task is checked and a full bake completes", async (t) => { + const f = fixture(t); + const previous = structuredClone(f.base); + const result = await f.run(); + assert.equal(result.changed, true); + const registration = f.calls.find((c) => c.name === "RegisterTaskDefinitionCommand").input; + for (const field of REGISTER_FIELDS.filter((field) => field !== "containerDefinitions")) assert.deepEqual(registration[field], previous[field]); + const container = structuredClone(registration.containerDefinitions[0]); + assert.deepEqual(container.environment.pop(), { name: ATTACHMENT_PROXY, value: "true" }); + assert.deepEqual(container, previous.containerDefinitions[0]); + assert.deepEqual(Object.fromEntries(registration.tags.map((tag) => [tag.key, tag.value])), + Object.fromEntries([...f.tags, { key: ATTACHMENT_PROXY_TAG, value: "true" }].map((tag) => [tag.key, tag.value]))); + assert.deepEqual(f.calls.filter((c) => c.name === "UpdateServiceCommand").map((c) => c.input), [{ cluster: f.cfg.cluster, service: "fixture-backend", taskDefinition: arn(2) }]); + assert.equal(f.sleeps.reduce((a, b) => a + b, 0), 300000); + assert.equal(f.calls.filter((c) => c.name === "DescribeAlarmsCommand").length, 22); + assert.ok(!f.calls.some((c) => c.name === "ListTasksCommand"), "the operation uses existing deployment permissions"); + const count = mutations(f).length; + await assert.rejects(f.run(), /unmodified service configuration/, "an old task snapshot must be refreshed before retrying"); + f.cfg.tasks = runningTasks(2); + assert.equal((await f.run()).changed, false); + assert.equal(mutations(f).length, count, "repeated request is a no-op even with its original expected revision"); + assert.equal(f.sleeps.reduce((a, b) => a + b, 0), 600000, "an interrupted bake is always observed afresh without rolling again"); +}); + +test("provider environment ordering preserves a successful full bake without rollback", async (t) => { + const f = fixture(t, { reorderEnvironment: true }); + assert.equal((await f.run()).changed, true); + assert.equal(f.live.taskDefinition, arn(2)); + assert.deepEqual(f.calls.filter((c) => c.name === "UpdateServiceCommand").map((c) => c.input.taskDefinition), [arn(2)]); + assert.equal(f.sleeps.reduce((a, b) => a + b, 0), 300000); +}); + +test("a prepared definition with reordered environment bindings is reused", async (t) => { + const f = fixture(t); + const prepared = structuredClone(f.base); + prepared.containerDefinitions[0].environment.unshift({ name: ATTACHMENT_PROXY, value: "true" }); + f.prepare(prepared, [...f.tags, { key: ATTACHMENT_PROXY_TAG, value: "true" }]); + assert.equal((await f.run()).taskDefinition, arn(2)); + assert.ok(!f.calls.some((c) => c.name === "RegisterTaskDefinitionCommand")); +}); + +test("disabling is explicit and preserves the remainder of the running definition", async (t) => { + const f = fixture(t); + await f.run(); + f.cfg.expected = arn(2); + f.cfg.tasks = runningTasks(2); + f.cfg.value = "false"; + await f.run(); + const current = f.defs.get(arn(3)); + assert.equal(current.definition.containerDefinitions[0].environment.find((e) => e.name === ATTACHMENT_PROXY).value, "false"); + assert.equal(current.tags.find((tag) => tag.key === ATTACHMENT_PROXY_TAG).value, "false"); +}); + +test("an enabled no-change request requires a deployment source that owns the setting", async (t) => { + const f = fixture(t); + f.prepare(f.base, f.tags); + f.base.containerDefinitions[0].environment.push({ name: ATTACHMENT_PROXY, value: "true" }); + await assert.rejects(f.run(), /requires a management tag or an explicit Terraform value/); + assert.deepEqual(mutations(f), []); + assert.deepEqual(f.sleeps, []); +}); + +for (const value of ["true", "false"]) test(`an explicit Terraform ${value} value owns an enabled no-change request`, async (t) => { + const f = fixture(t); + const template = structuredClone(f.base); + template.containerDefinitions[0].environment.push({ name: ATTACHMENT_PROXY, value }); + f.prepare(template, f.tags); + f.base.containerDefinitions[0].environment.push({ name: ATTACHMENT_PROXY, value: "true" }); + assert.equal((await f.run()).changed, false); + assert.deepEqual(mutations(f), []); + assert.equal(f.sleeps.reduce((a, b) => a + b, 0), 300000); +}); + +test("a live managed enabled setting remains owned when the latest template omits it", async (t) => { + const f = fixture(t); + f.prepare(f.base, f.tags); + f.base.containerDefinitions[0].environment.push({ name: ATTACHMENT_PROXY, value: "true" }); + f.tags.push({ key: ATTACHMENT_PROXY_TAG, value: "true" }); + assert.equal((await f.run()).changed, false); + assert.deepEqual(mutations(f), []); + assert.equal(f.sleeps.reduce((a, b) => a + b, 0), 300000); +}); + +test("an absent false setting needs no ownership change", async (t) => { + const f = fixture(t); + f.cfg.value = "false"; + assert.equal((await f.run()).changed, false); + assert.deepEqual(mutations(f), []); + assert.equal(f.sleeps.reduce((a, b) => a + b, 0), 300000); +}); + +test("every preflight task is described within the API batch limit", async (t) => { + const f = fixture(t, { taskCount: 101 }); + await f.run(); + const descriptions = f.calls.filter((c) => c.name === "DescribeTasksCommand"); + assert.deepEqual(descriptions.map((c) => c.input.tasks.length), [100, 1]); + assert.deepEqual(descriptions.flatMap((c) => c.input.tasks), f.cfg.tasks); +}); + +for (const [name, options, mutate] of [ + ["mixed task definitions", { wrongTask: true }], ["unhealthy task", { unhealthyTask: true }], ["task override", { override: true }], + ["draining task", { drainingTask: true }], + ["missing described task", { missingTask: true }], ["foreign task group", { foreignGroup: true }], + ["incomplete preflight", {}, (f) => { f.cfg.tasks.pop(); }], + ["duplicate preflight task", {}, (f) => { f.cfg.tasks[1] = f.cfg.tasks[0]; }], + ["stale expected revision", {}, (f) => { f.cfg.expected = arn(99); }], + ["wrong image", {}, (f) => { f.base.containerDefinitions[0].image += "bad"; }], + ["wrong release", {}, (f) => { f.tags[0].value = "v0.6.74"; }], + ["missing variant", {}, (f) => { f.tags.splice(1, 1); }], + ["zero tasks", {}, (f) => { f.live.desiredCount = f.live.runningCount = 0; }], + ["unknown desired count", {}, (f) => { f.live.desiredCount = f.live.runningCount = undefined; }], + ["deployment count mismatch", {}, (f) => { f.live.deployments[0].runningCount = 1; }], + ["deployment revision mismatch", {}, (f) => { f.live.deployments[0].taskDefinition = arn(99); }], + ["active rollout", {}, (f) => { f.live.deployments[0].rolloutState = "IN_PROGRESS"; }], + ["duplicate flag", {}, (f) => { f.base.containerDefinitions[0].environment.push(...["true", "false"].map((value) => ({ name: ATTACHMENT_PROXY, value }))); }], + ["secret-backed flag", {}, (f) => { f.base.containerDefinitions[0].secrets.push({ name: ATTACHMENT_PROXY, valueFrom: "secret" }); }], + ["mismatched ownership tag", {}, (f) => { f.tags.push({ key: ATTACHMENT_PROXY_TAG, value: "true" }); }], +]) test(`${name} is refused before mutations`, async (t) => { + const f = fixture(t, options); + mutate?.(f); + await assert.rejects(f.run()); + assert.deepEqual(mutations(f), []); +}); + +for (const options of [{ alarm: true }, { failedRoll: true }]) test(`${JSON.stringify(options)} restores and verifies the exact prior revision`, async (t) => { + const f = fixture(t, options); + await assert.rejects(f.run()); + assert.equal(f.live.taskDefinition, arn(1)); + assert.deepEqual(f.calls.filter((c) => c.name === "UpdateServiceCommand").map((c) => c.input.taskDefinition), [arn(2), arn(1)]); + assert.equal(f.calls.at(-1).name, "DescribeTaskDefinitionCommand"); +}); + +test("a desired-count change during rollback prevents a successful restore report", async (t) => { + const f = fixture(t, { alarm: true, hook: (name, { live, calls }) => { + if (name === "DescribeServicesCommand" && calls.filter((c) => c.name === "UpdateServiceCommand").length === 2) { + live.desiredCount = live.runningCount = 3; + live.deployments[0].desiredCount = live.deployments[0].runningCount = 3; + } + } }); + await assert.rejects(f.run(), /rollback could not be verified/); + assert.equal(f.live.taskDefinition, arn(1)); + assert.equal(f.live.desiredCount, 3, "another writer's count is preserved for operator inspection"); + assert.ok(f.calls.filter((c) => c.name === "UpdateServiceCommand").every((c) => !Object.hasOwn(c.input, "desiredCount"))); +}); + +test("a concurrent change before update is preserved", async (t) => { + const f = fixture(t, { hook: (name, { live, calls }) => { + if (name === "DescribeServicesCommand" && calls.some((c) => c.name === "RegisterTaskDefinitionCommand")) live.taskDefinition = arn(99); + } }); + await assert.rejects(f.run(), /expected revision/); + assert.equal(f.calls.filter((c) => c.name === "UpdateServiceCommand").length, 0); + assert.equal(f.live.taskDefinition, arn(99)); +}); + +test("a concurrent change during the bake is never overwritten by rollback", async (t) => { + const f = fixture(t, { hook: (name, { live, calls }) => { + if (name === "DescribeServicesCommand" && calls.some((c) => c.name === "UpdateServiceCommand")) live.taskDefinition = arn(99); + } }); + await assert.rejects(f.run(), /rollback could not be verified/); + assert.equal(f.calls.filter((c) => c.name === "UpdateServiceCommand").length, 1); + assert.equal(f.live.taskDefinition, arn(99)); +}); + +test("a prepared identical revision is reused after interruption before the service update", async (t) => { + let interrupt = true; + const f = fixture(t, { hook: (name, { calls }) => { + if (interrupt && name === "DescribeServicesCommand" && calls.some((c) => c.name === "RegisterTaskDefinitionCommand")) { + interrupt = false; + throw new Error("interrupted before update"); + } + } }); + await assert.rejects(f.run(), /interrupted/); + await f.run(); + assert.equal(f.calls.filter((c) => c.name === "RegisterTaskDefinitionCommand").length, 1); +}); + +test("configuration requires a supported release, exact backend ARN and explicit boolean", (t) => { + const f = fixture(t); + for (const overrides of [ + { DEPLOY_TAG: "v0.6.74" }, { DEPLOY_TAG: "" }, { CONFIG_ATTACHMENT_DOWNLOAD_PROXY: "yes" }, + { CONFIG_EXPECTED_TASK_DEFINITION: arn(1).replace("fixture-backend", "fixture-consumer") }, + { CONFIG_EXPECTED_TASK_DEFINITION: arn(1).replace("000000000000", "111111111111") }, + { CONFIG_EXPECTED_TASKS: "[]" }, { CONFIG_EXPECTED_TASKS: "null" }, + { CONFIG_EXPECTED_TASKS: JSON.stringify([task(1), task(1)]) }, + { CONFIG_EXPECTED_TASKS: JSON.stringify([task(1).replace("000000000000", "111111111111")]) }, + { CONFIG_EXPECTED_TASKS: JSON.stringify([task(1).replace("/fixture/", "/foreign/")]) }, + ]) assert.throws(() => configuration({ ...f.env, ...overrides })); + assert.equal(configuration({ ...f.env, DEPLOY_BAKE_SECONDS: "0", DEPLOY_FLEET: "true" }).bake, 300); + assert.equal(configuration(f.env).fleet, false); +}); diff --git a/.github/scripts/aws-deploy.cjs b/.github/scripts/aws-deploy.cjs index 6957799bc..21f50d262 100644 --- a/.github/scripts/aws-deploy.cjs +++ b/.github/scripts/aws-deploy.cjs @@ -21,6 +21,8 @@ const VARIANT_TAG = "warmbly-image-variant"; const TAG_RE = /^v(\d+)\.(\d+)\.(\d+)$/; const DIGEST_RE = /^sha256:[a-f0-9]{64}$/; const VERSION_RE = /^[A-Za-z0-9-]{32,64}$/; +const ATTACHMENT_PROXY = "CAMPAIGN_ATTACHMENT_DOWNLOAD_PROXY"; +const ATTACHMENT_PROXY_TAG = "warmbly-config-attachment-download-proxy"; function configuration(env) { const cluster = env.AWS_ECS_CLUSTER; @@ -46,8 +48,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, @@ -130,14 +134,35 @@ function repin(container, pins) { } } -function same(a, b) { - return JSON.stringify(REGISTER_FIELDS.map((f) => a[f] ?? null)) === JSON.stringify(REGISTER_FIELDS.map((f) => b[f] ?? null)); +function canonical(value) { + if (Array.isArray(value)) return value.map(canonical); + if (value && typeof value === "object") return Object.fromEntries(Object.keys(value).sort().map((key) => [key, canonical(value[key])])); + return value; } +function comparableDefinition(definition) { + return REGISTER_FIELDS.map((field) => { + let value = definition[field] ?? null; + if (field === "containerDefinitions" && value) value = value.map((container) => { + const copy = { ...container }; + // ECS may reorder named bindings; command and other array order stays significant. + for (const key of ["environment", "secrets"]) if (copy[key]) copy[key] = [...copy[key]].sort((a, b) => a.name.localeCompare(b.name)); + return copy; + }); + return canonical(value); + }); +} + +function same(a, b) { + return JSON.stringify(comparableDefinition(a)) === JSON.stringify(comparableDefinition(b)); +} + +const canonicalTags = (tags) => JSON.stringify(tags.filter((t) => !t.key.startsWith("aws:")).sort((a, b) => a.key.localeCompare(b.key))); + async function register(client, source, rendered, tags, release, report) { const carried = tags.filter((t) => t.key !== RELEASE_TAG && !t.key.startsWith("aws:")); if (release) carried.push({ key: RELEASE_TAG, value: release }); - if (same(source.definition, rendered) && tagValue(source.tags, RELEASE_TAG) === release) return source.definition.taskDefinitionArn; + if (same(source.definition, rendered) && canonicalTags(source.tags) === canonicalTags(carried)) return source.definition.taskDefinitionArn; const input = {}; for (const f of REGISTER_FIELDS) if (rendered[f] !== undefined && rendered[f] !== null) input[f] = rendered[f]; input.tags = carried; @@ -169,8 +194,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 +215,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); @@ -236,6 +271,38 @@ function imageFor(config, key, fallback) { return `${config.images.registry}/${key.replace(/-kafka$/, "")}@${digest}`; } +function preserveBackendConfiguration(source, live, rendered, release) { + const managed = tagValue(live.tags, ATTACHMENT_PROXY_TAG); + const explicitValues = source.definition.containerDefinitions[0].environment?.filter((e) => e.name === ATTACHMENT_PROXY) || []; + const explicit = explicitValues[0]; + const sourceManaged = tagValue(source.tags, ATTACHMENT_PROXY_TAG); + const current = live.definition.containerDefinitions[0].environment?.filter((e) => e.name === ATTACHMENT_PROXY) || []; + if (explicitValues.length > 1 || source.definition.containerDefinitions[0].secrets?.some((s) => s.name === ATTACHMENT_PROXY) || + (sourceManaged !== undefined && (explicitValues.length !== 1 || sourceManaged !== explicit.value))) { + throw new Error("Backend attachment source configuration is ambiguous"); + } + if (managed !== undefined) { + if (!["true", "false"].includes(managed) || current.length !== 1 || current[0].value !== managed) { + throw new Error("Backend attachment configuration tag and environment must agree"); + } + } + // An explicit Terraform value takes ownership; otherwise the live managed value survives rendering. + const value = explicit && sourceManaged === undefined ? explicit.value + : managed ?? (sourceManaged !== undefined ? current[0]?.value || "false" : undefined); + if (value !== undefined && !["true", "false"].includes(value)) throw new Error("Backend attachment configuration must be true or false"); + if (value === "true" && compareTags(release, "v0.6.75") < 0) { + throw new Error("Disable the attachment proxy explicitly before deploying a release older than v0.6.75"); + } + const tags = source.tags.filter((t) => t.key !== ATTACHMENT_PROXY_TAG); + if (value !== undefined) { + const container = rendered.containerDefinitions[0]; + container.environment = (container.environment || []).filter((e) => e.name !== ATTACHMENT_PROXY); + container.environment.push({ name: ATTACHMENT_PROXY, value }); + if (!(explicit && sourceManaged === undefined) && managed !== undefined) tags.push({ key: ATTACHMENT_PROXY_TAG, value }); + } + return tags; +} + async function deploy(clients, config, sleep = (ms) => new Promise((r) => setTimeout(r, ms)), report = console.log) { const ecs = clients.ecs; const names = SERVICES.map((s) => `${config.prefix}-${s}`); @@ -301,6 +368,7 @@ async function deploy(clients, config, sleep = (ms) => new Promise((r) => setTim }; const backendKey = deployBackend || families.includes("ops") ? `backend${variant(deployBackend ? "backend" : "ops") === "kafka" ? "-kafka" : ""}` : null; const rendered = {}; + const renderedTags = {}; for (const name of families) { const def = structuredClone(sources[name].definition); const container = def.containerDefinitions?.[0]; @@ -316,6 +384,9 @@ async function deploy(clients, config, sleep = (ms) => new Promise((r) => setTim } else if (name !== "validation") { container.image = imageFor(config, backendKey, liveDefs.backend.definition.containerDefinitions[0].image); } + renderedTags[name] = name === "backend" + ? preserveBackendConfiguration(sources[name], liveDefs.backend, def, tag) + : sources[name].tags; rendered[name] = def; } @@ -337,7 +408,7 @@ async function deploy(clients, config, sleep = (ms) => new Promise((r) => setTim } const arns = {}; - for (const name of families) arns[name] = await register(ecs, sources[name], rendered[name], sources[name].tags, tag, report); + for (const name of families) arns[name] = await register(ecs, sources[name], rendered[name], renderedTags[name], tag, report); const network = backend.networkConfiguration; if (arns.validation) await runTask(clients, config, network, arns.validation, rendered.validation, "Dependency check", sleep, report); @@ -383,10 +454,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])) }; } @@ -411,4 +482,5 @@ if (require.main === module) { }); } -module.exports = { configuration, deploy, runTask, describe, compareTags, parseRef, secretService, SERVICES }; +module.exports = { configuration, deploy, runTask, describe, compareTags, parseRef, secretService, SERVICES, + REGISTER_FIELDS, same, register, waitForService, ATTACHMENT_PROXY, ATTACHMENT_PROXY_TAG }; diff --git a/.github/scripts/aws-deploy.test.cjs b/.github/scripts/aws-deploy.test.cjs index 41c95c7b8..2528ed0de 100644 --- a/.github/scripts/aws-deploy.test.cjs +++ b/.github/scripts/aws-deploy.test.cjs @@ -3,7 +3,32 @@ 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, same, ATTACHMENT_PROXY, ATTACHMENT_PROXY_TAG } = require("./aws-deploy.cjs"); + +test("definition equality compares named bindings while preserving every value and command order", () => { + const base = { family: "fixture", containerDefinitions: [{ name: "backend", image: "fixture@sha256:fixed", + command: ["serve", "--tls"], environment: [{ name: "TLS_ONLY", value: "true" }, { name: "REGION", value: "fixture" }], + secrets: [{ name: "PRIMARY_DB", valueFrom: "database:version-one" }, { name: "AUTH_SECRET", valueFrom: "auth:version-one" }] }] }; + const reordered = structuredClone(base); + reordered.containerDefinitions[0].environment.reverse(); + reordered.containerDefinitions[0].secrets.reverse(); + reordered.containerDefinitions[0].environment = reordered.containerDefinitions[0].environment.map(({ name, value }) => ({ value, name })); + assert.ok(same(base, reordered)); + for (const mutate of [ + (c) => { c.environment[0].value = "false"; }, + (c) => { c.environment[0].name = "OTHER"; }, + (c) => { c.environment.pop(); }, + (c) => { c.environment.push({ ...c.environment[0] }); }, + (c) => { c.secrets[0].valueFrom = "database:version-two"; }, + (c) => { c.secrets.pop(); }, + (c) => { c.command.reverse(); }, + (c) => { c.image = "other@sha256:fixed"; }, + ]) { + const changed = structuredClone(base); + mutate(changed.containerDefinitions[0]); + assert.equal(same(base, changed), false); + } +}); const root = "arn:aws:ecs:us-east-1:000000000000:"; const registry = "ghcr.io/warmbly/warmbly"; @@ -149,6 +174,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/); @@ -173,6 +203,56 @@ test("a release renders from the latest revision, swaps variant digests and carr } }); +function manageAttachments(f, revision, value) { + const arn = `${root}task-definition/fixture-backend:${revision}`; + f.defs[arn].containerDefinitions[0].environment.push({ name: ATTACHMENT_PROXY, value }); + f.tagsOf[arn].push({ key: ATTACHMENT_PROXY_TAG, value }); +} + +for (const mode of ["deploy", "refresh-secrets"]) test(`${mode} preserves the live managed attachment setting`, async () => { + const f = fixture(); + manageAttachments(f, 1, "true"); + await run(f, config({ DEPLOY_MODE: mode })); + const backend = registered(f).find((r) => r.family === "fixture-backend"); + assert.deepEqual(backend.containerDefinitions[0].environment.filter((e) => e.name === ATTACHMENT_PROXY), [{ name: ATTACHMENT_PROXY, value: "true" }]); + assert.equal(backend.tags.find((t) => t.key === ATTACHMENT_PROXY_TAG).value, "true"); + assert.ok(registered(f).filter((r) => r.family !== "fixture-backend").every((r) => !r.tags.some((t) => t.key === ATTACHMENT_PROXY_TAG))); +}); + +test("an explicit Terraform attachment value takes ownership", async () => { + const f = fixture(); + manageAttachments(f, 1, "true"); + f.defs[`${root}task-definition/fixture-backend:2`].containerDefinitions[0].environment.push({ name: ATTACHMENT_PROXY, value: "false" }); + await run(f, config()); + const backend = registered(f).find((r) => r.family === "fixture-backend"); + assert.equal(backend.containerDefinitions[0].environment.find((e) => e.name === ATTACHMENT_PROXY).value, "false"); + assert.ok(!backend.tags.some((t) => t.key === ATTACHMENT_PROXY_TAG)); +}); + +test("an attachment configuration prepared but never activated is not adopted by a release", async () => { + const f = fixture(); + manageAttachments(f, 2, "true"); + await run(f, config()); + const backend = registered(f).find((r) => r.family === "fixture-backend"); + assert.equal(backend.containerDefinitions[0].environment.find((e) => e.name === ATTACHMENT_PROXY).value, "false"); + assert.ok(!backend.tags.some((t) => t.key === ATTACHMENT_PROXY_TAG)); +}); + +test("managed attachment configuration must agree with its environment", async () => { + const f = fixture(); + manageAttachments(f, 1, "true"); + f.defs[`${root}task-definition/fixture-backend:1`].containerDefinitions[0].environment.find((e) => e.name === ATTACHMENT_PROXY).value = "false"; + await assert.rejects(run(f, config()), /tag and environment must agree/); + assert.equal(registered(f).length, 0); +}); + +test("a rollback below route support requires explicitly disabling the attachment proxy", async () => { + const f = fixture({ liveTag: "v0.6.75" }); + manageAttachments(f, 1, "true"); + await assert.rejects(run(f, config({ DEPLOY_TAG: "v0.6.74", DEPLOY_MODE: "rollback" })), /Disable the attachment proxy explicitly/); + assert.equal(registered(f).length, 0); +}); + test("the newest pinned secret version wins so a stale Terraform pin cannot undo a rotation", async () => { const f = fixture(); await run(f, config()); @@ -286,10 +366,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/aws-origin-alb-workflow.test.sh b/.github/scripts/aws-origin-alb-workflow.test.sh new file mode 100644 index 000000000..0323148f6 --- /dev/null +++ b/.github/scripts/aws-origin-alb-workflow.test.sh @@ -0,0 +1,35 @@ +#!/usr/bin/env bash +set -euo pipefail +cd "$(dirname "$0")/../.." +ruby -ryaml <<'RUBY' +workflow = YAML.load_file('.github/workflows/configure-origin-alb-aws.yml') +trigger = workflow['on'] || workflow[true] +raise 'only manual execution and offline PR checks are supported' unless trigger.keys.sort == ['pull_request', 'workflow_dispatch'] +inputs = trigger.fetch('workflow_dispatch').fetch('inputs') +raise 'plan must be the default' unless inputs.dig('mode', 'default') == 'plan' && inputs.dig('mode', 'options') == ['plan', 'apply', 'rollback'] +raise 'exact plan selectors are required' unless inputs.keys.sort == ['mode', 'plan_run_id', 'plan_sha256', 'plan_version'] +jobs = workflow.fetch('jobs') +raise 'no deployment or recovery jobs belong here' unless jobs.keys.sort == ['check', 'configure'] +job = jobs.fetch('configure') +raise 'manual main workflow must follow offline checks' unless job['needs'] == 'check' && job['if'] == "github.event_name == 'workflow_dispatch'" +raise 'ordinary environment must be retained' unless job['environment'] == 'aws-infrastructure' +raise 'production serialization must be retained' unless job.dig('concurrency', 'group') == 'aws-production' && job.dig('concurrency', 'cancel-in-progress') == false +raise 'only contents and OIDC permissions are needed' unless job['permissions'] == {'contents'=>'read', 'id-token'=>'write'} +steps = job.fetch('steps') +credentials = steps.select { |s| s['uses'] == 'aws-actions/configure-aws-credentials@v4' } +raise 'one existing role with session restriction is required' unless credentials.length == 1 && credentials[0]['with'] == { + 'role-to-assume'=>'${{ vars.AWS_TERRAFORM_APPLY_ROLE_ARN }}', 'aws-region'=>'us-east-1', + 'inline-session-policy'=>'${{ steps.scope.outputs.policy }}' +} +scope = steps.index { |s| s['run'] == 'node .github/scripts/aws-origin-alb.cjs session-policy' } +raise 'scope validation must precede credentials' unless scope && scope < steps.index(credentials[0]) +raise 'no secret inheritance or protection changes are supported' if workflow.to_s.match?(/secrets|aws-infrastructure-approval|AWS_TLS_RECOVERY|AWS_TERRAFORM_ENABLED|terraform apply|deploy-aws/) +jobs.each_value do |j| + raise 'job failures must stop execution' if j['continue-on-error'] + j.fetch('steps').each do |s| + raise 'step failures must stop execution' if s['continue-on-error'] + raise 'checkout credentials must not persist' if s['uses'] == 'actions/checkout@v4' && s.dig('with', 'persist-credentials') != false + end +end +puts 'Origin ALB workflow default, ordinary environment, session scope and production queue checks passed' +RUBY diff --git a/.github/scripts/aws-origin-alb.cjs b/.github/scripts/aws-origin-alb.cjs new file mode 100644 index 000000000..259df3bc7 --- /dev/null +++ b/.github/scripts/aws-origin-alb.cjs @@ -0,0 +1,274 @@ +const { createHash } = require("node:crypto"); +const { spawnSync } = require("node:child_process"); +const { appendFileSync, mkdirSync, readFileSync, writeFileSync } = require("node:fs"); +const { join } = require("node:path"); +const { isDeepStrictEqual } = require("node:util"); + +const ACCOUNT = "925323749693"; +const REGION = "us-east-1"; +const BUCKET = `warmbly-terraform-use1-${ACCOUNT}`; +const ROLE = `arn:aws:iam::${ACCOUNT}:role/warmbly-production-terraform-apply`; +const LB = `arn:aws:elasticloadbalancing:${REGION}:${ACCOUNT}:loadbalancer/app/warmbly-production-ingress/19d5c82c1651c871`; +const LISTENER = `arn:aws:elasticloadbalancing:${REGION}:${ACCOUNT}:listener/app/warmbly-production-ingress/19d5c82c1651c871/d0898c3f7d2223ea`; +const BASELINE = "ELBSecurityPolicy-TLS13-1-2-2021-06"; +const DESIRED = "ELBSecurityPolicy-TLS13-1-2-Res-2021-06"; +const PREFIX = "warmbly/production/diagnostics/origin-alb-policy"; +const WORKFLOW = "warmbly/warmbly/.github/workflows/configure-origin-alb-aws.yml@refs/heads/main"; +const hash = (bytes) => createHash("sha256").update(bytes).digest("hex"); +const canonical = (value) => JSON.stringify(value, (_, v) => v && typeof v === "object" && !Array.isArray(v) + ? Object.fromEntries(Object.keys(v).sort().map((key) => [key, v[key]])) : v); +const same = (a, b) => isDeepStrictEqual(a, b); +const requireThat = (condition, message) => { if (!condition) throw new Error(message); }; +const planKey = (run) => `${PREFIX}/${run}/1/plan.json`; +function privateJSON(bytes) { + try { return JSON.parse(bytes); } catch { throw new Error("Private input is not valid JSON"); } +} + +function configuration(env) { + requireThat(env.GITHUB_ACTIONS === "true" && env.GITHUB_REPOSITORY === "warmbly/warmbly" && + env.GITHUB_REF === "refs/heads/main" && env.GITHUB_EVENT_NAME === "workflow_dispatch" && + env.GITHUB_WORKFLOW_REF === WORKFLOW && env.GITHUB_RUN_ATTEMPT === "1" && + /^[1-9]\d*$/.test(env.GITHUB_RUN_ID || "") && /^[a-f0-9]{40}$/.test(env.GITHUB_SHA || ""), + "A new main workflow dispatch is required; reruns are refused"); + requireThat(env.STATE_BUCKET === BUCKET && env.APPLY_ROLE === ROLE, + "Configure AWS_TERRAFORM_STATE_BUCKET and AWS_TERRAFORM_APPLY_ROLE_ARN through the normal aws-infrastructure configuration gate; no role fallback is permitted"); + const mode = env.ORIGIN_ALB_MODE || "plan"; + requireThat(["plan", "apply", "rollback"].includes(mode), "Unknown origin ALB mode"); + const run = env.ORIGIN_ALB_PLAN_RUN_ID || ""; + const version = env.ORIGIN_ALB_PLAN_VERSION || ""; + const digest = env.ORIGIN_ALB_PLAN_SHA256 || ""; + if (mode === "plan") requireThat(!run && !version && !digest, "Plan mode does not accept prior plan inputs"); + else requireThat(/^[1-9]\d*$/.test(run) && run !== env.GITHUB_RUN_ID && + /^[A-Za-z0-9_./+=-]{1,1024}$/.test(version) && version !== "null" && /^[a-f0-9]{64}$/.test(digest), + "Apply and rollback require the exact prior plan run, version and SHA-256"); + requireThat(env.WORK && env.GITHUB_OUTPUT && env.GITHUB_STEP_SUMMARY, "Private work directory and workflow output paths are required"); + return { mode, run, version, digest, source: env.GITHUB_SHA, currentRun: env.GITHUB_RUN_ID, work: env.WORK }; +} + +function sessionPolicy(config) { + const statements = [ + { Effect: "Allow", Action: ["elasticloadbalancing:Describe*", "ec2:DescribeSecurityGroups"], Resource: "*" }, + { Effect: "Allow", Action: "s3:PutObject", Resource: `arn:aws:s3:::${BUCKET}/${PREFIX}/${config.currentRun}/1/*`, + Condition: { StringEquals: { "s3:x-amz-server-side-encryption": "AES256", "s3:ResourceAccount": ACCOUNT }, + Bool: { "aws:SecureTransport": "true" }, Null: { "s3:if-none-match": "false" } } }, + ]; + if (config.mode !== "plan") statements.push( + { Effect: "Allow", Action: "s3:GetObjectVersion", Resource: `arn:aws:s3:::${BUCKET}/${planKey(config.run)}` }, + { Effect: "Allow", Action: "elasticloadbalancing:ModifyListener", Resource: LISTENER }, + ); + return { Version: "2012-10-17", Statement: statements }; +} + +function awsCLI(service, action, args = []) { + const result = spawnSync("aws", [service, action, ...args, "--region", REGION, "--output", "json", "--no-cli-pager"], + { encoding: "utf8", maxBuffer: 16 * 1024 * 1024, timeout: 60000, + env: { ...process.env, AWS_PAGER: "", AWS_CLI_AUTO_PROMPT: "off", AWS_MAX_ATTEMPTS: "1" } }); + // Provider output stays private, including failures that may contain request data. + if (result.error || result.status !== 0) throw new Error(`AWS ${service} ${action} failed; use the normal IAM/configuration gate if access is insufficient`); + return privateJSON(result.stdout); +} + +function sorted(rows, key) { + requireThat(Array.isArray(rows) && rows.every((row) => typeof row[key] === "string") && + new Set(rows.map((row) => row[key])).size === rows.length, "Incomplete or duplicate ALB response"); + return rows.sort((a, b) => a[key].localeCompare(b[key])); +} + +function sortedCertificates(rows) { + requireThat(Array.isArray(rows) && rows.every((row) => typeof row.CertificateArn === "string" && typeof row.IsDefault === "boolean") && + new Set(rows.map((row) => canonical([row.CertificateArn, row.IsDefault]))).size === rows.length, + "Incomplete or duplicate ALB certificate response"); + return rows.sort((a, b) => a.CertificateArn.localeCompare(b.CertificateArn) || Number(a.IsDefault) - Number(b.IsDefault)); +} + +async function collect(aws) { + const lb = await aws("elbv2", "describe-load-balancers", ["--load-balancer-arns", LB]); + requireThat(lb.LoadBalancers?.length === 1 && lb.LoadBalancers[0].LoadBalancerArn === LB && + lb.LoadBalancers[0].Type === "application" && lb.LoadBalancers[0].State?.Code === "active", "The exact origin ALB must be active"); + const listeners = sorted((await aws("elbv2", "describe-listeners", ["--load-balancer-arn", LB])).Listeners, "ListenerArn"); + requireThat(listeners.some((l) => l.ListenerArn === LISTENER), "The bound HTTPS listener is required"); + const listenerDetails = []; + for (const listener of listeners) { + const details = { arn: listener.ListenerArn, + attributes: sorted((await aws("elbv2", "describe-listener-attributes", ["--listener-arn", listener.ListenerArn])).Attributes, "Key"), + rules: sorted((await aws("elbv2", "describe-rules", ["--listener-arn", listener.ListenerArn])).Rules, "RuleArn") }; + if (listener.Protocol === "HTTPS") details.certificates = sortedCertificates((await aws("elbv2", "describe-listener-certificates", ["--listener-arn", listener.ListenerArn])).Certificates); + listenerDetails.push(details); + } + const targetGroups = sorted((await aws("elbv2", "describe-target-groups", ["--load-balancer-arn", LB])).TargetGroups, "TargetGroupArn"); + const targetAttributes = []; + for (const tg of targetGroups) targetAttributes.push({ arn: tg.TargetGroupArn, + attributes: sorted((await aws("elbv2", "describe-target-group-attributes", ["--target-group-arn", tg.TargetGroupArn])).Attributes, "Key") }); + const groups = lb.LoadBalancers[0].SecurityGroups; + requireThat(Array.isArray(groups) && groups.length > 0, "ALB security groups are required"); + return { loadBalancers: lb.LoadBalancers, listeners, listenerDetails, targetGroups, targetAttributes, + loadBalancerAttributes: sorted((await aws("elbv2", "describe-load-balancer-attributes", ["--load-balancer-arn", LB])).Attributes, "Key"), + securityGroups: sorted((await aws("ec2", "describe-security-groups", ["--group-ids", ...groups.slice().sort()])).SecurityGroups, "GroupId") }; +} + +function assertSnapshot(snapshot, policy) { + requireThat(Array.isArray(snapshot?.listeners), "The complete listener inventory is required"); + const listener = snapshot?.listeners?.filter((l) => l.ListenerArn === LISTENER); + requireThat(listener?.length === 1 && listener[0].LoadBalancerArn === LB && listener[0].Port === 443 && + listener[0].Protocol === "HTTPS" && listener[0].SslPolicy === policy && listener[0].Certificates?.length > 0, + "Exact listener identity, HTTPS port, certificates and policy baseline are required"); + requireThat(snapshot.loadBalancers?.length === 1 && snapshot.loadBalancers[0].LoadBalancerArn === LB && + Array.isArray(snapshot.listenerDetails) && Array.isArray(snapshot.targetGroups) && + Array.isArray(snapshot.targetAttributes) && Array.isArray(snapshot.loadBalancerAttributes) && Array.isArray(snapshot.securityGroups), + "A complete preserved origin snapshot is required"); + const ids = (rows, key) => rows.map((row) => row[key]).sort(); + requireThat(same(ids(snapshot.listeners, "ListenerArn"), ids(snapshot.listenerDetails, "arn")) && + snapshot.listenerDetails.every((d) => Array.isArray(d.attributes) && Array.isArray(d.rules)) && + snapshot.listenerDetails.find((d) => d.arn === LISTENER).certificates?.some((c) => c.IsDefault === true) && + same(ids(snapshot.targetGroups, "TargetGroupArn"), ids(snapshot.targetAttributes, "arn")) && + snapshot.targetAttributes.every((d) => Array.isArray(d.attributes)) && + snapshot.securityGroups.length > 0 && same(snapshot.loadBalancers[0].SecurityGroups.slice().sort(), ids(snapshot.securityGroups, "GroupId")), + "Every listener, certificate inventory, target group attribute set and security group must be preserved"); +} + +function makePlan(snapshot, config, now = new Date()) { + assertSnapshot(snapshot, BASELINE); + const after = structuredClone(snapshot); + after.listeners.find((l) => l.ListenerArn === LISTENER).SslPolicy = DESIRED; + return { schemaVersion: 1, repository: "warmbly/warmbly", workflow: WORKFLOW, source: config.source, + run: config.currentRun, createdAt: now.toISOString(), account: ACCOUNT, region: REGION, + changes: [{ address: "aws_lb_listener.https", action: "update", listener: LISTENER, field: "SslPolicy", before: BASELINE, after: DESIRED }], + before: snapshot, after }; +} + +function checkPlan(plan, config, now = new Date()) { + requireThat(plan?.schemaVersion === 1 && plan.repository === "warmbly/warmbly" && plan.workflow === WORKFLOW && + plan.account === ACCOUNT && plan.region === REGION && plan.source === config.source && plan.run === config.run, + "Plan must bind this workflow source, account, region and prior plan run"); + const age = now.getTime() - Date.parse(plan.createdAt); + requireThat(Number.isFinite(age) && age >= 0 && age <= 24 * 60 * 60 * 1000, "Plan must be at most 24 hours old; prepare a fresh plan"); + requireThat(same(plan, makePlan(plan.before, { source: config.source, currentRun: config.run }, new Date(plan.createdAt))), + "The complete plan may change only the bound listener SslPolicy from the exact baseline to the restricted policy"); + assertSnapshot(plan.after, DESIRED); +} + +async function health(aws, snapshot) { + const routes = snapshot.listenerDetails.find((d) => d.arn === LISTENER).rules; + const arns = new Set(); + for (const rule of routes) for (const action of rule.Actions || []) { + if (action.TargetGroupArn) arns.add(action.TargetGroupArn); + for (const tg of action.ForwardConfig?.TargetGroups || []) if ((tg.Weight ?? 1) > 0) arns.add(tg.TargetGroupArn); + } + requireThat(arns.size > 0, "HTTPS forwarding targets are required"); + const observations = []; + for (const arn of [...arns].sort()) { + const tg = snapshot.targetGroups.find((g) => g.TargetGroupArn === arn); + requireThat(tg?.Protocol === "HTTPS", "Every active HTTPS route must retain HTTPS targets"); + const result = await aws("elbv2", "describe-target-health", ["--target-group-arn", arn]); + requireThat(result.TargetHealthDescriptions?.length > 0 && result.TargetHealthDescriptions.every((t) => t.TargetHealth?.State === "healthy"), + "Every routed HTTPS target must be healthy"); + observations.push({ arn, ...result }); + } + return observations; +} + +async function put(aws, config, name, value) { + const bytes = canonical(value) + "\n"; + const path = join(config.work, name); + writeFileSync(path, bytes, { mode: 0o600, flag: "wx" }); + const checksum = createHash("sha256").update(bytes).digest("base64"); + const metadata = await aws("s3api", "put-object", ["--bucket", BUCKET, "--key", `${PREFIX}/${config.currentRun}/1/${name}`, + "--expected-bucket-owner", ACCOUNT, "--server-side-encryption", "AES256", "--if-none-match", "*", + "--checksum-algorithm", "SHA256", "--checksum-sha256", checksum, "--body", path]); + requireThat(metadata.ServerSideEncryption === "AES256" && metadata.ChecksumSHA256 === checksum && + typeof metadata.VersionId === "string" && metadata.VersionId.length > 0 && metadata.VersionId !== "null", "Encrypted versioned immutable evidence is required"); + return { sha256: hash(bytes), version: metadata.VersionId }; +} + +async function loadPlan(aws, config) { + const path = join(config.work, "reviewed-plan.json"); + const metadata = await aws("s3api", "get-object", ["--bucket", BUCKET, "--key", planKey(config.run), + "--version-id", config.version, "--expected-bucket-owner", ACCOUNT, path]); + requireThat(metadata.VersionId === config.version && metadata.DeleteMarker !== true && metadata.ServerSideEncryption === "AES256", + "The exact encrypted private plan version is required"); + const bytes = readFileSync(path); + requireThat(hash(bytes) === config.digest, "Private plan SHA-256 differs from the reviewed digest"); + const plan = privateJSON(bytes); + checkPlan(plan, config); + return plan; +} + +async function execute(aws, config, plan, evidence) { + const rollback = config.mode === "rollback"; + const before = rollback ? plan.after : plan.before; + const after = rollback ? plan.before : plan.after; + const policy = rollback ? BASELINE : DESIRED; + evidence.preflight = await collect(aws); + requireThat(same(evidence.preflight, before), "Live origin baseline drifted; prepare a new reviewed plan"); + evidence.healthBefore = await health(aws, before); + await put(aws, config, "intent.json", { mode: config.mode, source: config.source, planRun: config.run, + planVersion: config.version, planSha256: config.digest, before, after, healthBefore: evidence.healthBefore }); + // Recheck after archiving, immediately before the sole configuration write. + evidence.prewrite = await collect(aws); + requireThat(same(evidence.prewrite, before), "Live origin changed before the write; a new plan is required"); + evidence.writeAttempted = true; + evidence.response = await aws("elbv2", "modify-listener", ["--listener-arn", LISTENER, "--ssl-policy", policy]); + requireThat(evidence.response.Listeners?.length === 1 && + same(evidence.response.Listeners[0], after.listeners.find((l) => l.ListenerArn === LISTENER)), "Listener write response must match the exact desired listener"); + evidence.readback = await collect(aws); + requireThat(same(evidence.readback, after), "Origin readback differs from the exact desired snapshot; inspect private evidence before scoped rollback"); + evidence.healthAfter = await health(aws, after); +} + +async function run(aws, config, report) { + mkdirSync(config.work, { mode: 0o700 }); + const evidence = { mode: config.mode, source: config.source, run: config.currentRun, success: false, writeAttempted: false, + reviewedPlan: { run: config.run, version: config.version, sha256: config.digest } }; + let message; + let failure; + try { + const identity = await aws("sts", "get-caller-identity"); + requireThat(identity.Account === ACCOUNT && /^arn:aws:sts::925323749693:assumed-role\/warmbly-production-terraform-apply\/[^/]+$/.test(identity.Arn || ""), + "The existing ordinary Terraform apply role is required"); + evidence.identity = identity; + if (config.mode === "plan") { + evidence.readback = await collect(aws); + const plan = makePlan(evidence.readback, config); + evidence.health = await health(aws, evidence.readback); + const record = await put(aws, config, "plan.json", plan); + message = `Plan only: one in-place origin listener SslPolicy update.\n\nPlan run: ${config.currentRun}\n\nPlan version: ${record.version}\n\nComplete plan SHA-256: ${record.sha256}\n\nReview the full private plan before a separate apply dispatch. No configuration write occurred.`; + } else { + const plan = await loadPlan(aws, config); + await execute(aws, config, plan, evidence); + message = `Origin policy ${config.mode} completed. Exact listener, certificates, attributes, rules, target groups and security groups read back unchanged apart from SslPolicy; routed HTTPS targets are healthy. Retain separate authorized origin handshake evidence.`; + } + evidence.success = true; + } catch (error) { + evidence.error = error.message; + failure = error; + } + try { + await put(aws, config, "result.json", evidence); + } catch { + const archiveFailure = `Result evidence archive failed; writeAttempted=${evidence.writeAttempted}`; + if (!failure) throw new Error(archiveFailure); + console.error(archiveFailure); + } + if (failure) throw failure; + report(message); +} + +if (require.main === module) { + process.umask(0o077); + Promise.resolve().then(async () => { + const config = configuration(process.env); + const source = spawnSync("git", ["rev-parse", "HEAD"], { encoding: "utf8" }); + requireThat(source.status === 0 && source.stdout.trim() === config.source, "Checkout must match the main workflow source"); + if (process.argv[2] === "session-policy") appendFileSync(process.env.GITHUB_OUTPUT, `policy=${canonical(sessionPolicy(config))}\n`); + else { + requireThat(process.argv[2] === "configure", "Unknown origin ALB command"); + await run(awsCLI, config, (message) => { + console.log(message); + appendFileSync(process.env.GITHUB_STEP_SUMMARY, `${message}\n`); + }); + } + }).catch((error) => { console.error(`Origin ALB configuration stopped: ${error.message}`); process.exitCode = 1; }); +} + +module.exports = { ACCOUNT, BUCKET, ROLE, LB, LISTENER, BASELINE, DESIRED, PREFIX, WORKFLOW, + configuration, sessionPolicy, collect, makePlan, checkPlan, health, put, execute, run, canonical, hash }; diff --git a/.github/scripts/aws-origin-alb.test.cjs b/.github/scripts/aws-origin-alb.test.cjs new file mode 100644 index 000000000..0effdfa99 --- /dev/null +++ b/.github/scripts/aws-origin-alb.test.cjs @@ -0,0 +1,387 @@ +const { test } = require("node:test"); +const assert = require("node:assert/strict"); +const { mkdtempSync, readFileSync, writeFileSync, rmSync } = require("node:fs"); +const { tmpdir } = require("node:os"); +const { join } = require("node:path"); +const { ACCOUNT, BUCKET, ROLE, LB, LISTENER, BASELINE, DESIRED, PREFIX, WORKFLOW, + configuration, sessionPolicy, collect, makePlan, checkPlan, execute, run, canonical, hash } = require("./aws-origin-alb.cjs"); + +const SOURCE = "a".repeat(40); +const TG = `arn:aws:elasticloadbalancing:us-east-1:${ACCOUNT}:targetgroup/fixture/1234`; +const CERT = `arn:aws:acm:us-east-1:${ACCOUNT}:certificate/fixture`; + +function fixture(t) { + const dir = mkdtempSync(join(tmpdir(), "origin-alb-")); + t.after(() => rmSync(dir, { force: true, recursive: true })); + const config = { mode: "plan", source: SOURCE, currentRun: "100", work: join(dir, "plan") }; + const listener = { ListenerArn: LISTENER, LoadBalancerArn: LB, Protocol: "HTTPS", Port: 443, + SslPolicy: BASELINE, Certificates: [{ CertificateArn: CERT }], + DefaultActions: [{ Type: "forward", TargetGroupArn: TG }], MutualAuthentication: { Mode: "off" } }; + const live = { + loadBalancers: [{ LoadBalancerArn: LB, Type: "application", State: { Code: "active" }, SecurityGroups: ["sg-fixture"], DNSName: "fixture.invalid" }], + listeners: [listener, { ListenerArn: LISTENER + "-http", LoadBalancerArn: LB, Protocol: "HTTP", Port: 80, DefaultActions: [{ Type: "redirect" }] }], + listenerDetails: [{ arn: LISTENER, attributes: [{ Key: "fixture", Value: "true" }], + certificates: [{ CertificateArn: CERT, IsDefault: true }], + rules: [{ RuleArn: LISTENER + "/rule/fixture", IsDefault: true, Actions: listener.DefaultActions }] }, + { arn: LISTENER + "-http", attributes: [], rules: [] }], + targetGroups: [{ TargetGroupArn: TG, Protocol: "HTTPS", Port: 8443 }], + targetAttributes: [{ arn: TG, attributes: [{ Key: "deregistration_delay.timeout_seconds", Value: "30" }] }], + loadBalancerAttributes: [{ Key: "deletion_protection.enabled", Value: "true" }], + securityGroups: [{ GroupId: "sg-fixture", IpPermissions: [{ IpProtocol: "tcp", FromPort: 443, ToPort: 443 }] }], + }; + const calls = []; + const objects = new Map(); + let unhealthy = false; + const aws = async (service, action, args = []) => { + calls.push({ service, action, args: structuredClone(args) }); + const arg = (name) => args[args.indexOf(name) + 1]; + switch (`${service}:${action}`) { + case "sts:get-caller-identity": return { Account: ACCOUNT, Arn: `arn:aws:sts::${ACCOUNT}:assumed-role/warmbly-production-terraform-apply/fixture` }; + case "elbv2:describe-load-balancers": return { LoadBalancers: structuredClone(live.loadBalancers) }; + case "elbv2:describe-listeners": return { Listeners: structuredClone(live.listeners) }; + case "elbv2:describe-listener-attributes": return { Attributes: structuredClone(live.listenerDetails.find((d) => d.arn === arg("--listener-arn")).attributes) }; + case "elbv2:describe-listener-certificates": return { Certificates: structuredClone(live.listenerDetails.find((d) => d.arn === arg("--listener-arn")).certificates) }; + case "elbv2:describe-rules": return { Rules: structuredClone(live.listenerDetails.find((d) => d.arn === arg("--listener-arn")).rules) }; + case "elbv2:describe-target-groups": return { TargetGroups: structuredClone(live.targetGroups) }; + case "elbv2:describe-target-group-attributes": return { Attributes: structuredClone(live.targetAttributes.find((d) => d.arn === arg("--target-group-arn")).attributes) }; + case "elbv2:describe-load-balancer-attributes": return { Attributes: structuredClone(live.loadBalancerAttributes) }; + case "ec2:describe-security-groups": return { SecurityGroups: structuredClone(live.securityGroups) }; + case "elbv2:describe-target-health": return { TargetHealthDescriptions: [{ Target: { Id: "192.0.2.1", Port: 8443 }, TargetHealth: { State: unhealthy ? "unhealthy" : "healthy" } }] }; + case "elbv2:modify-listener": { + assert.deepEqual(args.slice(0, 3), ["--listener-arn", LISTENER, "--ssl-policy"]); + assert.equal(args.length, 4); + live.listeners[0].SslPolicy = arg("--ssl-policy"); + return { Listeners: [structuredClone(live.listeners[0])] }; + } + case "s3api:put-object": { + const key = arg("--key"); + assert.equal(arg("--bucket"), BUCKET); + assert.equal(arg("--expected-bucket-owner"), ACCOUNT); + assert.equal(arg("--if-none-match"), "*"); + assert.equal(arg("--server-side-encryption"), "AES256"); + assert.ok(!objects.has(key), "immutable evidence cannot be overwritten"); + const bytes = readFileSync(arg("--body")); + const metadata = { VersionId: `version-${objects.size}`, ChecksumSHA256: Buffer.from(hash(bytes), "hex").toString("base64"), ServerSideEncryption: "AES256" }; + assert.equal(arg("--checksum-sha256"), metadata.ChecksumSHA256); + objects.set(key, { bytes, metadata }); + return metadata; + } + case "s3api:get-object": { + assert.equal(arg("--bucket"), BUCKET); + assert.equal(arg("--expected-bucket-owner"), ACCOUNT); + const object = objects.get(arg("--key")); + assert.equal(arg("--version-id"), object.metadata.VersionId); + writeFileSync(args.at(-1), object.bytes); + return object.metadata; + } + default: throw new Error(`Unexpected API ${service}:${action}`); + } + }; + const writeCalls = () => calls.filter((c) => c.action === "modify-listener"); + const reports = []; + const plan = async () => { + await run(aws, config, (s) => { + assert.ok(objects.has(`${PREFIX}/100/1/result.json`)); + reports.push(s); + }); + const object = objects.get(`${PREFIX}/100/1/plan.json`); + return { mode: "apply", source: SOURCE, currentRun: "200", run: "100", version: object.metadata.VersionId, + digest: hash(object.bytes), work: join(dir, "apply") }; + }; + return { config, live, calls, objects, aws, writeCalls, reports, plan, dir, setUnhealthy: () => { unhealthy = true; } }; +} + +function env() { + return { GITHUB_ACTIONS: "true", GITHUB_REPOSITORY: "warmbly/warmbly", GITHUB_REF: "refs/heads/main", GITHUB_EVENT_NAME: "workflow_dispatch", + GITHUB_WORKFLOW_REF: WORKFLOW, GITHUB_RUN_ATTEMPT: "1", GITHUB_RUN_ID: "100", GITHUB_SHA: SOURCE, + STATE_BUCKET: BUCKET, APPLY_ROLE: ROLE, WORK: "/tmp/fixture", GITHUB_OUTPUT: "/tmp/output", GITHUB_STEP_SUMMARY: "/tmp/summary" }; +} + +test("default plan is main-only, refuses reruns, invalid scope and missing ordinary environment configuration", () => { + assert.equal(configuration(env()).mode, "plan"); + for (const changes of [{ GITHUB_REF: "refs/heads/feature" }, { GITHUB_RUN_ATTEMPT: "2" }, { GITHUB_EVENT_NAME: "push" }, + { GITHUB_WORKFLOW_REF: "other" }, { APPLY_ROLE: "" }, { STATE_BUCKET: "" }, { STATE_BUCKET: "other" }, + { ORIGIN_ALB_MODE: "apply" }, { ORIGIN_ALB_MODE: "recovery" }, { ORIGIN_ALB_PLAN_RUN_ID: "99" }]) { + assert.throws(() => configuration({ ...env(), ...changes })); + } + const apply = { ...env(), ORIGIN_ALB_MODE: "apply", ORIGIN_ALB_PLAN_RUN_ID: "99", ORIGIN_ALB_PLAN_VERSION: "version-1", ORIGIN_ALB_PLAN_SHA256: "f".repeat(64) }; + assert.equal(configuration(apply).run, "99"); + for (const changes of [{ ORIGIN_ALB_PLAN_RUN_ID: "100" }, { ORIGIN_ALB_PLAN_RUN_ID: "../other" }, + { ORIGIN_ALB_PLAN_VERSION: "null" }, { ORIGIN_ALB_PLAN_VERSION: "invalid\nvalue" }, { ORIGIN_ALB_PLAN_SHA256: "bad" }]) { + assert.throws(() => configuration({ ...apply, ...changes })); + } +}); + +test("session permissions intersect the existing role: no listener writes in plan, exact listener in apply, conditional private writes only", () => { + const config = configuration(env()); + const plan = sessionPolicy(config); + assert.ok(!canonical(plan).includes("ModifyListener")); + assert.ok(!canonical(plan).includes("GetObject")); + const apply = sessionPolicy({ ...config, mode: "apply", run: "99" }); + assert.deepEqual(apply.Statement.find((s) => s.Action === "elasticloadbalancing:ModifyListener"), + { Effect: "Allow", Action: "elasticloadbalancing:ModifyListener", Resource: LISTENER }); + const write = apply.Statement.find((s) => s.Action === "s3:PutObject"); + assert.equal(write.Resource, `arn:aws:s3:::${BUCKET}/${PREFIX}/100/1/*`); + assert.equal(write.Condition.Null["s3:if-none-match"], "false"); + assert.equal(write.Condition.StringEquals["s3:x-amz-server-side-encryption"], "AES256"); + assert.equal(apply.Statement.find((s) => s.Action === "s3:GetObjectVersion").Resource, `arn:aws:s3:::${BUCKET}/${PREFIX}/99/1/plan.json`); + const actions = apply.Statement.flatMap((s) => s.Action); + assert.ok(!/secretsmanager|iam:|ecs:|DeleteObject|ModifyRule|Create/.test(actions.join(" "))); +}); + +test("dry plan archives the complete baseline and exact change without a configuration write", async (t) => { + const f = fixture(t); + const baseline = structuredClone(f.live); + await f.plan(); + assert.deepEqual(f.live, baseline); + assert.equal(f.writeCalls().length, 0); + const plan = JSON.parse(f.objects.get(`${PREFIX}/100/1/plan.json`).bytes); + checkPlan(plan, { source: SOURCE, run: "100" }); + assert.equal(plan.before.listeners[0].SslPolicy, BASELINE); + assert.equal(plan.after.listeners[0].SslPolicy, DESIRED); + assert.ok(f.reports[0].includes("Complete plan SHA-256")); + assert.ok(f.objects.has(`${PREFIX}/100/1/result.json`)); +}); + +test("complete plan guard rejects unrelated changes, replacements, missing identity and baseline drift", async (t) => { + const f = fixture(t); + const plan = makePlan(await collect(f.aws), f.config); + const config = { source: SOURCE, run: "100" }; + for (const mutate of [ + (p) => { p.changes.push({ address: "aws_ecs_service.backend", action: "update" }); }, + (p) => { p.changes[0].action = "replace"; }, + (p) => { p.after.listeners[0].Port = 8443; }, + (p) => { p.after.listeners[0].Certificates[0].CertificateArn = "other"; }, + (p) => { p.after.listeners[0].DefaultActions = []; }, + (p) => { p.after.listeners[0].MutualAuthentication.Mode = "verify"; }, + (p) => { p.after.listeners[1].Port = 81; }, + (p) => { p.after.listenerDetails[0].rules = []; }, + (p) => { p.after.targetGroups[0].Port = 80; }, + (p) => { p.after.securityGroups[0].IpPermissions = []; }, + (p) => { p.before.listeners[0].SslPolicy = DESIRED; }, + (p) => { p.before.listeners[0].ListenerArn += "other"; }, + (p) => { p.before.listeners[0].LoadBalancerArn += "other"; }, + (p) => { p.before.listenerDetails = []; }, + (p) => { p.before.listenerDetails[0].certificates = []; }, + (p) => { p.before.targetAttributes = []; }, + (p) => { p.before.securityGroups = []; }, + (p) => { p.after.extra = "unreviewed"; }, + (p) => { p.source = "b".repeat(40); }, + (p) => { p.createdAt = "2000-01-01T00:00:00Z"; }, + (p) => { p.createdAt = "2999-01-01T00:00:00Z"; }, + ]) { + const invalid = structuredClone(plan); + mutate(invalid); + assert.throws(() => checkPlan(invalid, config)); + } +}); + +test("apply changes only ssl policy after immutable intent and verifies the entire origin configuration", async (t) => { + const f = fixture(t); + const config = await f.plan(); + const before = structuredClone(f.live); + await run(f.aws, config, (s) => { + assert.ok(f.objects.has(`${PREFIX}/200/1/result.json`)); + f.reports.push(s); + }); + const expected = structuredClone(before); + expected.listeners[0].SslPolicy = DESIRED; + assert.deepEqual(f.live, expected); + assert.deepEqual(f.writeCalls(), [{ service: "elbv2", action: "modify-listener", args: ["--listener-arn", LISTENER, "--ssl-policy", DESIRED] }]); + const intentIndex = f.calls.findIndex((c) => c.action === "put-object" && c.args.includes(`${PREFIX}/200/1/intent.json`)); + const writeIndex = f.calls.findIndex((c) => c.action === "modify-listener"); + assert.ok(intentIndex >= 0 && intentIndex < writeIndex); + assert.equal(JSON.parse(f.objects.get(`${PREFIX}/200/1/result.json`).bytes).success, true); +}); + +for (const mode of ["plan", "apply", "rollback"]) test(`${mode} completion requires a successful result archive`, async (t) => { + const f = fixture(t); + let config = f.config; + if (mode !== "plan") config = await f.plan(); + if (mode === "rollback") { + await run(f.aws, config, () => {}); + config = { ...config, mode, currentRun: "300", work: join(f.dir, "rollback") }; + } + const resultKey = `${PREFIX}/${config.currentRun}/1/result.json`; + const reports = []; + const logs = []; + let archivedEvidence; + let reportsAtArchive; + t.mock.method(console, "error", (...args) => logs.push(args)); + const aws = async (service, action, args) => { + if (action === "put-object" && args.includes(resultKey)) { + reportsAtArchive = [...reports]; + archivedEvidence = JSON.parse(readFileSync(args[args.indexOf("--body") + 1])); + throw new Error("Private archive provider response\ncredential=fixture-secret"); + } + return f.aws(service, action, args); + }; + await assert.rejects(run(aws, config, (s) => reports.push(s)), { + message: `Result evidence archive failed; writeAttempted=${mode !== "plan"}`, + }); + assert.equal(archivedEvidence.success, true); + assert.equal(archivedEvidence.writeAttempted, mode !== "plan"); + assert.deepEqual(reportsAtArchive, []); + assert.deepEqual(reports, []); + assert.deepEqual(logs, []); + assert.ok(!f.objects.has(resultKey)); + assert.equal(f.live.listeners[0].SslPolicy, mode === "apply" ? DESIRED : BASELINE); + assert.equal(f.writeCalls().length, mode === "plan" ? 0 : mode === "apply" ? 1 : 2); +}); + +for (const writeAttempted of [false, true]) test(`operation error survives result archive failure with writeAttempted=${writeAttempted}`, async (t) => { + const f = fixture(t); + const config = await f.plan(); + const resultKey = `${PREFIX}/200/1/result.json`; + const operationError = new Error("Origin policy operation failed"); + const reports = []; + const logs = []; + let archivedEvidence; + t.mock.method(console, "error", (...args) => logs.push(args)); + const aws = async (service, action, args) => { + if (!writeAttempted && action === "get-caller-identity") throw operationError; + if (action === "put-object" && args.includes(resultKey)) { + archivedEvidence = JSON.parse(readFileSync(args[args.indexOf("--body") + 1])); + throw new Error("Private archive provider response\ncredential=fixture-secret"); + } + const response = await f.aws(service, action, args); + if (action === "modify-listener") throw operationError; + return response; + }; + await assert.rejects(run(aws, config, (s) => reports.push(s)), (error) => error === operationError); + assert.equal(archivedEvidence.success, false); + assert.equal(archivedEvidence.error, operationError.message); + assert.equal(archivedEvidence.writeAttempted, writeAttempted); + assert.deepEqual(reports, []); + assert.deepEqual(logs, [[`Result evidence archive failed; writeAttempted=${writeAttempted}`]]); + assert.ok(!f.objects.has(resultKey)); + assert.equal(f.writeCalls().length, writeAttempted ? 1 : 0); +}); + +test("scoped rollback uses the same exact reviewed plan and restores only the baseline policy", async (t) => { + const f = fixture(t); + const config = await f.plan(); + const baseline = structuredClone(f.live); + await run(f.aws, config, () => {}); + await run(f.aws, { ...config, mode: "rollback", currentRun: "300", work: join(f.dir, "rollback") }, () => {}); + assert.deepEqual(f.live, baseline); + assert.deepEqual(f.writeCalls().map((c) => c.args), [["--listener-arn", LISTENER, "--ssl-policy", DESIRED], ["--listener-arn", LISTENER, "--ssl-policy", BASELINE]]); +}); + +for (const defaultFirst of [true, false]) test(`plan, apply and rollback preserve default and SNI certificate entries with default first: ${defaultFirst}`, async (t) => { + const f = fixture(t); + const certificates = [{ CertificateArn: CERT, IsDefault: false }, { CertificateArn: CERT, IsDefault: true }]; + const inventory = f.live.listenerDetails.find((d) => d.arn === LISTENER); + inventory.certificates = structuredClone(certificates); + if (defaultFirst) inventory.certificates.reverse(); + const baseline = structuredClone(f.live); + const config = await f.plan(); + assert.deepEqual(f.live, baseline); + assert.equal(f.writeCalls().length, 0); + const plan = JSON.parse(f.objects.get(`${PREFIX}/100/1/plan.json`).bytes); + checkPlan(plan, { source: SOURCE, run: "100" }); + for (const snapshot of [plan.before, plan.after]) { + assert.deepEqual(snapshot.listenerDetails.find((d) => d.arn === LISTENER).certificates, certificates); + } + for (const [mode, currentRun, policy] of [["apply", "200", DESIRED], ["rollback", "300", BASELINE]]) { + inventory.certificates.reverse(); + const expected = structuredClone(f.live); + expected.listeners[0].SslPolicy = policy; + await run(f.aws, { ...config, mode, currentRun, work: join(f.dir, mode) }, () => {}); + assert.deepEqual(f.live, expected); + const result = JSON.parse(f.objects.get(`${PREFIX}/${currentRun}/1/result.json`).bytes); + assert.equal(result.success, true); + assert.deepEqual(result.readback.listenerDetails.find((d) => d.arn === LISTENER).certificates, certificates); + } + assert.deepEqual(f.live, baseline); + assert.deepEqual(f.writeCalls().map((c) => c.args), [["--listener-arn", LISTENER, "--ssl-policy", DESIRED], ["--listener-arn", LISTENER, "--ssl-policy", BASELINE]]); +}); + +test("certificate inventory requires distinct ARN and default-status pairs with boolean status", async (t) => { + for (const status of [true, false, undefined, "true"]) { + const f = fixture(t); + f.live.listenerDetails[0].certificates = [ + { CertificateArn: CERT, IsDefault: status }, { CertificateArn: CERT, IsDefault: status }, + ]; + await assert.rejects(collect(f.aws), /Incomplete or duplicate ALB certificate response/); + assert.equal(f.writeCalls().length, 0); + } +}); + +test("certificate inventory rejects a single certificate with non-boolean default status", async (t) => { + for (const status of [undefined, "true"]) { + const f = fixture(t); + f.live.listenerDetails[0].certificates = [{ CertificateArn: CERT, IsDefault: status }]; + await assert.rejects(collect(f.aws), /Incomplete or duplicate ALB certificate response/); + assert.equal(f.writeCalls().length, 0); + } +}); + +for (const [label, drift] of [ + ["policy", (f) => { f.live.listeners[0].SslPolicy = DESIRED; }], + ["certificate", (f) => { f.live.listeners[0].Certificates = []; }], + ["HTTP listener", (f) => { f.live.listeners[1].Port = 81; }], + ["rule", (f) => { f.live.listenerDetails[0].rules[0].Actions = []; }], + ["target group", (f) => { f.live.targetGroups[0].Port = 80; }], + ["security group", (f) => { f.live.securityGroups[0].IpPermissions = []; }], + ["listener attribute", (f) => { f.live.listenerDetails[0].attributes[0].Value = "false"; }], +]) test(`apply refuses ${label} baseline drift before mutation`, async (t) => { + const f = fixture(t); + const config = await f.plan(); + drift(f); + await assert.rejects(run(f.aws, config, () => {}), /baseline drifted/); + assert.equal(f.writeCalls().length, 0); + assert.equal(JSON.parse(f.objects.get(`${PREFIX}/200/1/result.json`).bytes).success, false); +}); + +test("drift immediately after intent archival and rollback drift both refuse mutation", async (t) => { + const f = fixture(t); + const config = await f.plan(); + const plan = JSON.parse(f.objects.get(`${PREFIX}/100/1/plan.json`).bytes); + const evidence = {}; + const aws = async (service, action, args) => { + const out = await f.aws(service, action, args); + if (action === "put-object") f.live.listeners[0].Port = 8443; + return out; + }; + // execute writes its intent into an existing private runner directory. + await assert.rejects(execute(aws, { ...config, work: f.dir }, plan, evidence), /changed before the write/); + assert.equal(f.writeCalls().length, 0); + f.live.listeners[0].SslPolicy = DESIRED; + await assert.rejects(run(f.aws, { ...config, mode: "rollback", currentRun: "300", work: join(f.dir, "rollback") }, () => {}), /baseline drifted/); + assert.equal(f.writeCalls().length, 0); +}); + +test("altered plan bytes, stale source, unhealthy targets and failed immutable archive refuse writes", async (t) => { + for (const variant of ["digest", "source", "health", "archive", "versioning", "identity"]) { + const f = fixture(t); + const config = await f.plan(); + if (variant === "digest") config.digest = "f".repeat(64); + if (variant === "source") config.source = "b".repeat(40); + if (variant === "health") f.setUnhealthy(); + const aws = async (service, action, args) => { + if (variant === "archive" && action === "put-object") throw new Error("Evidence permission denied"); + const response = await f.aws(service, action, args); + if (variant === "versioning" && action === "put-object") delete response.VersionId; + if (variant === "identity" && action === "get-caller-identity") response.Account = "000000000000"; + return response; + }; + await assert.rejects(run(aws, config, () => {})); + assert.equal(f.writeCalls().length, 0); + } +}); + +test("failed postwrite verification records attempted write and does not automatically overwrite concurrent changes", async (t) => { + const f = fixture(t); + const config = await f.plan(); + const aws = async (service, action, args) => { + const out = await f.aws(service, action, args); + if (action === "modify-listener") f.live.listeners[0].Port = 8443; + return out; + }; + await assert.rejects(run(aws, config, () => {}), /readback differs/); + assert.equal(f.writeCalls().length, 1); + const result = JSON.parse(f.objects.get(`${PREFIX}/200/1/result.json`).bytes); + assert.equal(result.writeAttempted, true); + assert.equal(result.success, false); +}); diff --git a/.github/scripts/aws-origin-tls-workflow.test.sh b/.github/scripts/aws-origin-tls-workflow.test.sh new file mode 100644 index 000000000..e6e97a2c2 --- /dev/null +++ b/.github/scripts/aws-origin-tls-workflow.test.sh @@ -0,0 +1,52 @@ +#!/usr/bin/env bash +set -euo pipefail +cd "$(dirname "$0")/../.." +ruby -ryaml <<'RUBY' +workflow = YAML.load_file('.github/workflows/probe-origin-tls-aws.yml') +trigger = workflow['on'] || workflow[true] +raise 'only manual execution and offline checks are supported' unless trigger.keys.sort == ['pull_request', 'workflow_dispatch'] +raise 'no arbitrary execution inputs are supported' unless trigger['workflow_dispatch'].nil? +jobs = workflow.fetch('jobs') +raise 'only checks and a diagnostic belong here' unless jobs.keys.sort == ['check', 'probe'] +job = jobs.fetch('probe') +raise 'manual diagnostic must follow checks' unless job['needs'] == 'check' && job['if'] == "github.event_name == 'workflow_dispatch'" +raise 'ordinary environment required' unless job['environment'] == 'aws-infrastructure' +raise 'production serialization required' unless job.dig('concurrency', 'group') == 'aws-production' && job.dig('concurrency', 'cancel-in-progress') == false +raise 'bounded job required' unless job['timeout-minutes'] == 25 +raise 'only contents and OIDC permissions needed' unless job['permissions'] == {'contents'=>'read', 'id-token'=>'write'} +steps = job.fetch('steps') +credentials = steps.select { |s| s['uses'] == 'aws-actions/configure-aws-credentials@v4' } +raise 'separate probe and cleanup credentials required' unless credentials.map { |s| s['id'] } == ['credentials', 'cleanup_credentials'] +['probe', 'cleanup'].each_with_index do |phase, i| + raise 'existing role with phase policy and no credential reuse required' unless credentials[i]['with'] == { + 'role-to-assume'=>'${{ vars.AWS_TERRAFORM_APPLY_ROLE_ARN }}', 'aws-region'=>'us-east-1', + 'unset-current-credentials'=>true, + 'inline-session-policy'=>"${{ steps.scope.outputs.#{phase}_policy }}" + } +end +scope = steps.index { |s| s['run'] == 'node .github/scripts/aws-origin-tls.cjs session-policy' } +raise 'source gate must precede credentials' unless scope && steps[scope]['id'] == 'scope' && scope < steps.index(credentials[0]) +raise 'probe credentials require the successful source gate' if credentials[0]['if'] +probe = steps.find { |s| s['run'] == 'node .github/scripts/aws-origin-tls.cjs probe' } +raise 'probe requires its successful credentials and timeout' unless probe && probe['timeout-minutes'] == 10 && + probe['if'] == "success() && steps.credentials.outcome == 'success'" +raise 'probe must run once immediately after its credentials' unless steps.count { |s| s['run'] == probe['run'] } == 1 && + steps.index(probe) == steps.index(credentials[0]) + 1 +raise 'cleanup credentials must follow probe failure or credential failure after a successful source gate' unless + credentials[1]['if'] == "always() && steps.scope.outcome == 'success'" && credentials[1]['timeout-minutes'] == 2 && + steps.index(credentials[1]) == steps.index(probe) + 1 +cleanup = steps.last +raise 'bounded finalizer must require successful cleanup credentials with no earlier-session fallback' unless + cleanup['run'] == 'node .github/scripts/aws-origin-tls.cjs finish' && + cleanup['if'] == "always() && steps.cleanup_credentials.outcome == 'success'" && cleanup['timeout-minutes'] == 8 && + steps.index(cleanup) == steps.index(credentials[1]) + 1 +raise 'no secret inheritance, bypasses or public artifacts' if workflow.to_s.match?(/secrets|upload-artifact|AWS_TERRAFORM_ENABLED|AWS_TLS_RECOVERY|terraform apply|deploy-aws/) +jobs.each_value do |j| + raise 'failures must stop execution' if j['continue-on-error'] + j.fetch('steps').each do |s| + raise 'step failures must stop execution' if s['continue-on-error'] + raise 'checkout credentials must not persist' if s['uses'] == 'actions/checkout@v4' && s.dig('with', 'persist-credentials') != false + end +end +puts 'Origin TLS workflow source gate, phase credentials, failure gating, ordinary environment and bounded cleanup checks passed' +RUBY diff --git a/.github/scripts/aws-origin-tls.cjs b/.github/scripts/aws-origin-tls.cjs new file mode 100644 index 000000000..cb0a6b0ae --- /dev/null +++ b/.github/scripts/aws-origin-tls.cjs @@ -0,0 +1,306 @@ +const { spawnSync } = require("node:child_process"); +const { appendFileSync, mkdirSync, readFileSync, writeFileSync, existsSync } = require("node:fs"); +const { join } = require("node:path"); +const { ACCOUNT, BUCKET, ROLE, LB, LISTENER, DESIRED, hash, canonical } = require("./aws-origin-alb.cjs"); +const { CBC, GCM, TLS13, classify, validTargets } = require("./origin-tls-client.cjs"); + +const REGION = "us-east-1"; +const ECS = `arn:aws:ecs:${REGION}:${ACCOUNT}`; +const CLUSTER = `${ECS}:cluster/warmbly-production`; +const SERVICE = `${ECS}:service/warmbly-production/warmbly-production-backend`; +const EXECUTION = `arn:aws:iam::${ACCOUNT}:role/warmbly-production-validation-execution`; +const VPC = "vpc-038e4f0058030800b"; +const SG = "sg-0ddd1eb3234dad9e7"; +const ALB_SG = "sg-03a4f6f8010daff8d"; +const LOG = "/ecs/warmbly-production/validation"; +const PREFIX = "warmbly/production/diagnostics/origin-tls"; +// Official Node 22 bookworm ARM64 manifest, including OpenSSL and Debian public CAs. +const IMAGE = "docker.io/library/node@sha256:a288699fc0f9676950742fae6efcd015180aa7ef2bf8a6477e4b0a8cc0ab1b3f"; +const requireThat = (ok, message) => { if (!ok) throw new Error(message); }; +const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); +const originIdentity = (enis) => canonical(enis.map((e) => + [e.NetworkInterfaceId, e.PrivateIpAddress, e.AvailabilityZone, e.SubnetId]).sort()); + +function configuration(env) { + requireThat(env.GITHUB_ACTIONS === "true" && env.GITHUB_REPOSITORY === "warmbly/warmbly" && + env.GITHUB_REF === "refs/heads/main" && env.GITHUB_EVENT_NAME === "workflow_dispatch" && + env.GITHUB_WORKFLOW_REF === "warmbly/warmbly/.github/workflows/probe-origin-tls-aws.yml@refs/heads/main" && + env.GITHUB_RUN_ATTEMPT === "1" && /^[1-9]\d*$/.test(env.GITHUB_RUN_ID || "") && + /^[a-f0-9]{40}$/.test(env.GITHUB_SHA || ""), "A new main workflow dispatch is required; reruns are refused"); + requireThat(env.STATE_BUCKET === BUCKET && env.APPLY_ROLE === ROLE && env.WORK && + env.GITHUB_OUTPUT && env.GITHUB_STEP_SUMMARY, "Normal aws-infrastructure role, bucket and private paths required"); + return { run: env.GITHUB_RUN_ID, source: env.GITHUB_SHA, work: env.WORK, + family: `warmbly-production-origin-tls-${env.GITHUB_RUN_ID}`, startedBy: `origin-tls-${env.GITHUB_RUN_ID}` }; +} + +function sessionPolicy(config, phase) { + requireThat(phase === "probe" || phase === "cleanup", "Explicit diagnostic credential phase required"); + const statements = phase === "probe" ? [ + { Effect: "Allow", Action: ["elasticloadbalancing:DescribeLoadBalancers", "elasticloadbalancing:DescribeListeners", + "ec2:DescribeNetworkInterfaces", "ec2:DescribeSubnets", "ecs:RegisterTaskDefinition"], Resource: "*" }, + { Effect: "Allow", Action: "ecs:DescribeServices", Resource: SERVICE }, + { Effect: "Allow", Action: "ecs:RunTask", Resource: `${ECS}:task-definition/${config.family}:*`, + Condition: { ArnEquals: { "ecs:cluster": CLUSTER } } }, + { Effect: "Allow", Action: "ecs:DescribeTasks", Resource: `${ECS}:task/warmbly-production/*` }, + { Effect: "Allow", Action: "iam:PassRole", Resource: EXECUTION, + Condition: { StringEquals: { "iam:PassedToService": "ecs-tasks.amazonaws.com" } } }, + ] : [ + { Effect: "Allow", Action: ["ecs:ListTaskDefinitions", "ecs:ListTasks"], Resource: "*" }, + { Effect: "Allow", Action: "ecs:DeregisterTaskDefinition", Resource: "*" }, + { Effect: "Allow", Action: ["ecs:DescribeTasks", "ecs:StopTask"], Resource: `${ECS}:task/warmbly-production/*` }, + { Effect: "Allow", Action: "logs:GetLogEvents", Resource: `arn:aws:logs:${REGION}:${ACCOUNT}:log-group:${LOG}:log-stream:origin-tls-${config.run}/*` }, + ]; + return { Version: "2012-10-17", Statement: [...statements, + { Effect: "Allow", Action: "s3:PutObject", Resource: `arn:aws:s3:::${BUCKET}/${PREFIX}/${config.run}/1/*`, + Condition: { StringEquals: { "s3:x-amz-server-side-encryption": "AES256", "s3:ResourceAccount": ACCOUNT }, + Bool: { "aws:SecureTransport": "true" }, Null: { "s3:if-none-match": "false" } } }, + ] }; +} + +function awsCLI(service, action, args = []) { + const result = spawnSync("aws", [service, action, ...args, "--region", REGION, "--output", "json", "--no-cli-pager", + "--cli-connect-timeout", "5", "--cli-read-timeout", "8"], { encoding: "utf8", timeout: 15000, + maxBuffer: 4 * 1024 * 1024, env: { ...process.env, AWS_PAGER: "", AWS_CLI_AUTO_PROMPT: "off", AWS_MAX_ATTEMPTS: "1" } }); + requireThat(!result.error && result.status === 0, `AWS ${service} ${action} failed; inspect normal access/configuration prerequisites`); + try { return JSON.parse(result.stdout); } catch { throw new Error("AWS diagnostic response was not valid JSON"); } +} + +async function discover(aws) { + const lb = (await aws("elbv2", "describe-load-balancers", ["--load-balancer-arns", LB])).LoadBalancers; + requireThat(lb?.length === 1 && lb[0].LoadBalancerArn === LB && lb[0].VpcId === VPC && + lb[0].State?.Code === "active" && lb[0].Type === "application" && lb[0].IpAddressType === "ipv4" && + canonical(lb[0].SecurityGroups) === canonical([ALB_SG]), "Exact active origin ALB required"); + const listener = (await aws("elbv2", "describe-listeners", ["--listener-arns", LISTENER])).Listeners; + requireThat(listener?.length === 1 && listener[0].ListenerArn === LISTENER && listener[0].LoadBalancerArn === LB && + listener[0].Protocol === "HTTPS" && listener[0].Port === 443 && listener[0].SslPolicy === DESIRED, + "Bound HTTPS listener must have the reviewed restricted policy"); + const enis = (await aws("ec2", "describe-network-interfaces", ["--filters", + "Name=description,Values=ELB app/warmbly-production-ingress/19d5c82c1651c871", `Name=vpc-id,Values=${VPC}`])).NetworkInterfaces; + requireThat(enis?.length >= 2 && lb[0].AvailabilityZones?.length === 2 && + new Set(enis.map((e) => e.AvailabilityZone)).size === 2 && new Set(enis.map((e) => e.SubnetId)).size === 2 && + new Set(enis.map((e) => e.NetworkInterfaceId)).size === enis.length && validTargets(enis.map((e) => e.PrivateIpAddress)) && + enis.every((e) => /^eni-[a-f0-9]+$/.test(e.NetworkInterfaceId || "") && e.VpcId === VPC && e.Status === "in-use" && + e.RequesterManaged === true && e.OwnerId === ACCOUNT && e.Description === "ELB app/warmbly-production-ingress/19d5c82c1651c871" && + e.Groups?.length === 1 && e.Groups[0].GroupId === ALB_SG && + lb[0].AvailabilityZones?.some((z) => z.ZoneName === e.AvailabilityZone && z.SubnetId === e.SubnetId)), "Complete exact-ALB private ENIs required"); + const service = (await aws("ecs", "describe-services", ["--cluster", CLUSTER, "--services", SERVICE])).services; + const network = service?.[0]?.networkConfiguration?.awsvpcConfiguration; + requireThat(service?.length === 1 && service[0].serviceArn === SERVICE && service[0].status === "ACTIVE" && + network?.assignPublicIp === "ENABLED" && canonical(network.securityGroups) === canonical([SG]) && + network.subnets?.length === 2 && new Set(network.subnets).size === 2 && + enis.every((e) => network.subnets.includes(e.SubnetId)), "Existing application task network required"); + const subnets = (await aws("ec2", "describe-subnets", ["--subnet-ids", ...network.subnets])).Subnets; + requireThat(subnets?.length === 2 && new Set(subnets.map((s) => s.SubnetId)).size === 2 && + subnets.every((s) => s.VpcId === VPC && s.State === "available" && + enis.some((e) => e.SubnetId === s.SubnetId)), "Existing application/ALB subnets required"); + return { at: new Date().toISOString(), lb: lb[0], listener: listener[0], enis, network }; +} + +function definition(config, targets) { + return { family: config.family, networkMode: "awsvpc", requiresCompatibilities: ["FARGATE"], cpu: "256", memory: "512", + executionRoleArn: EXECUTION, runtimePlatform: { cpuArchitecture: "ARM64", operatingSystemFamily: "LINUX" }, + containerDefinitions: [{ name: "probe", image: IMAGE, essential: true, user: "1000:1000", readonlyRootFilesystem: true, + linuxParameters: { capabilities: { drop: ["ALL"] } }, stopTimeout: 10, + entryPoint: ["timeout", "-s", "KILL", "210", "node"], command: ["-e", readFileSync(join(__dirname, "origin-tls-client.cjs"), "utf8")], + environment: [{ name: "ORIGIN_TLS_TASK", value: "1" }, { name: "ORIGIN_TLS_TARGETS", value: JSON.stringify(targets) }], + logConfiguration: { logDriver: "awslogs", options: { "awslogs-group": LOG, "awslogs-region": REGION, + "awslogs-stream-prefix": `origin-tls-${config.run}`, mode: "blocking" } } }] }; +} + +const save = (config, evidence) => writeFileSync(join(config.work, "evidence.json"), JSON.stringify(evidence), { mode: 0o600 }); +const load = (config) => JSON.parse(readFileSync(join(config.work, "evidence.json"))); +async function archive(aws, config, name, evidence) { + const bytes = Buffer.from(JSON.stringify(evidence)); + const path = join(config.work, name); + writeFileSync(path, bytes, { mode: 0o600 }); + const checksum = Buffer.from(hash(bytes), "hex").toString("base64"); + const result = await aws("s3api", "put-object", ["--bucket", BUCKET, "--key", `${PREFIX}/${config.run}/1/${name}`, + "--expected-bucket-owner", ACCOUNT, "--server-side-encryption", "AES256", "--if-none-match", "*", + "--checksum-algorithm", "SHA256", "--checksum-sha256", checksum, "--body", path]); + requireThat(result.ServerSideEncryption === "AES256" && result.ChecksumSHA256 === checksum && + typeof result.VersionId === "string" && result.VersionId.length > 0 && result.VersionId !== "null", "Private encrypted versioned evidence required"); + return { version: result.VersionId, sha256: hash(bytes) }; +} + +async function execute(aws, config, pause = sleep) { + mkdirSync(config.work, { recursive: true, mode: 0o700 }); + const evidence = { run: config.run, source: config.source, success: false, image: IMAGE }; + save(config, evidence); + try { + const identity = await aws("sts", "get-caller-identity"); + requireThat(identity.Account === ACCOUNT && /^arn:aws:sts::925323749693:assumed-role\/warmbly-production-terraform-apply\/[^/]+$/.test(identity.Arn || ""), "Existing infrastructure apply identity required"); + evidence.before = await discover(aws); + const targets = evidence.before.enis.map((e) => e.PrivateIpAddress).sort(); + evidence.definition = definition(config, targets); + await archive(aws, config, "intent.json", evidence); + evidence.registerAttempted = true; + save(config, evidence); + const registered = await aws("ecs", "register-task-definition", ["--cli-input-json", JSON.stringify(evidence.definition)]); + evidence.definitionArn = registered.taskDefinition?.taskDefinitionArn; + requireThat(evidence.definitionArn?.startsWith(`${ECS}:task-definition/${config.family}:`), "Dedicated diagnostic definition required"); + save(config, evidence); + // Refresh immediately before launch; a changed address requires a new dispatch. + evidence.prelaunch = await discover(aws); + requireThat(originIdentity(evidence.prelaunch.enis) === originIdentity(evidence.before.enis) && + canonical(evidence.prelaunch.network) === canonical(evidence.before.network), "Origin/task network changed before launch"); + const request = { cluster: CLUSTER, taskDefinition: evidence.definitionArn, launchType: "FARGATE", platformVersion: "1.4.0", + count: 1, startedBy: config.startedBy, clientToken: config.startedBy, enableExecuteCommand: false, + networkConfiguration: { awsvpcConfiguration: evidence.before.network } }; + evidence.runAttempted = true; + save(config, evidence); + const launched = await aws("ecs", "run-task", ["--cli-input-json", JSON.stringify(request)]); + evidence.taskArn = launched.tasks?.[0]?.taskArn; + requireThat(!launched.failures?.length && launched.tasks?.length === 1 && + evidence.taskArn?.startsWith(`${ECS}:task/warmbly-production/`), "One disposable diagnostic task required"); + save(config, evidence); + for (let i = 0; i < 48; i++) { + const readback = await aws("ecs", "describe-tasks", ["--cluster", CLUSTER, "--tasks", evidence.taskArn]); + requireThat(!readback.failures?.length && readback.tasks?.length === 1, "Diagnostic task readback required"); + evidence.task = readback.tasks[0]; + requireThat(evidence.task.taskArn === evidence.taskArn && evidence.task.clusterArn === CLUSTER && + evidence.task.taskDefinitionArn === evidence.definitionArn && evidence.task.startedBy === config.startedBy && + evidence.task.launchType === "FARGATE" && evidence.task.enableExecuteCommand === false, "Exact diagnostic task identity required"); + save(config, evidence); + if (evidence.task.lastStatus === "STOPPED") break; + await pause(5000); + } + requireThat(evidence.task?.lastStatus === "STOPPED" && evidence.task.containers?.length === 1 && + evidence.task.containers[0].name === "probe" && evidence.task.containers[0].imageDigest === IMAGE.split("@")[1] && + evidence.task.containers[0].exitCode === 0, "Probe incomplete or inconclusive; inspect private evidence"); + evidence.after = await discover(aws); + requireThat(originIdentity(evidence.after.enis) === originIdentity(evidence.before.enis) && + canonical(evidence.after.network) === canonical(evidence.before.network), "Origin interfaces or task network changed during probe"); + evidence.success = true; + } catch (error) { + evidence.failure = error.message; + throw error; + } finally { save(config, evidence); } +} + +async function finish(aws, config, pause = sleep) { + if (!existsSync(join(config.work, "evidence.json"))) return; + const evidence = load(config); + evidence.cleanup = { errors: [], stopped: false, deregistered: false }; + const attempt = async (action) => { try { return await action(); } catch (error) { evidence.cleanup.errors.push(error.message); return null; } }; + // Recover identities even when a registration or launch response was lost. + const candidates = new Set([evidence.taskArn].filter(Boolean)); + if (evidence.runAttempted) { + for (let i = 0; i < 3; i++) { + const running = await attempt(() => aws("ecs", "list-tasks", ["--cluster", CLUSTER, "--started-by", config.startedBy])); + // startedBy cannot be combined with another ListTasks filter. + const stopped = await attempt(() => aws("ecs", "list-tasks", ["--cluster", CLUSTER, "--family", config.family, "--desired-status", "STOPPED"])); + for (const task of [...(running?.taskArns || []), ...(stopped?.taskArns || [])]) candidates.add(task); + if (candidates.size) break; + await pause(5000); + } + } + const tasks = [...candidates]; + const verified = new Set(); + const stopAttempted = new Set(); + evidence.cleanup.candidateTaskArns = tasks; + save(config, evidence); + if (tasks.length) { + for (let i = 0; i < 12; i++) { + const state = await attempt(() => aws("ecs", "describe-tasks", ["--cluster", CLUSTER, "--tasks", ...tasks])); + evidence.cleanup.tasks = state; + const owned = (state?.tasks || []).filter((t) => candidates.has(t.taskArn) && t.clusterArn === CLUSTER && + t.startedBy === config.startedBy && typeof evidence.definitionArn === "string" && t.taskDefinitionArn === evidence.definitionArn); + for (const task of owned) { + verified.add(task.taskArn); + if (task.lastStatus !== "STOPPED" && !stopAttempted.has(task.taskArn)) { + stopAttempted.add(task.taskArn); + await attempt(() => aws("ecs", "stop-task", ["--cluster", CLUSTER, "--task", task.taskArn, "--reason", "Bounded origin TLS diagnostic cleanup"])); + } + } + if (state && !state.failures?.length && new Set(owned.map((t) => t.taskArn)).size === tasks.length && owned.every((t) => t.lastStatus === "STOPPED")) { + evidence.cleanup.stopped = true; + break; + } + await pause(5000); + } + } else if (!evidence.runAttempted) { + evidence.cleanup.stopped = true; + } + evidence.cleanup.taskArns = [...verified]; + evidence.cleanup.recovery = !evidence.runAttempted ? "not-required" : + verified.size > 0 && verified.size === tasks.length ? "resolved" : "unresolved"; + if (evidence.cleanup.recovery === "unresolved") evidence.cleanup.errors.push("Diagnostic task identity unresolved"); + const definitionPattern = new RegExp(`^${ECS}:task-definition/${config.family}:\\d+$`); + const isRunDefinition = (arn) => typeof arn === "string" && definitionPattern.exec(arn)?.[0] === arn; + const arns = new Set([evidence.definitionArn].filter(isRunDefinition)); + let definitions; + if (evidence.registerAttempted) { + for (let i = 0; i < 3; i++) { + definitions = await attempt(async () => { + const result = await aws("ecs", "list-task-definitions", ["--family-prefix", config.family, "--status", "ACTIVE"]); + requireThat(Array.isArray(result?.taskDefinitionArns), "Diagnostic definition discovery unconfirmed"); + return result; + }); + for (const arn of (definitions?.taskDefinitionArns || []).filter(isRunDefinition)) arns.add(arn); + if (arns.size) break; + if (i < 2) await pause(5000); + } + } + evidence.cleanup.definitionArns = [...arns]; + evidence.cleanup.definitionRecovery = !evidence.registerAttempted ? "not-required" : arns.size ? "resolved" : "unresolved"; + if (evidence.cleanup.definitionRecovery === "unresolved") evidence.cleanup.errors.push("Diagnostic definition identity unresolved"); + save(config, evidence); + for (const arn of arns) { + const result = await attempt(() => aws("ecs", "deregister-task-definition", ["--task-definition", arn])); + if (result?.taskDefinition?.taskDefinitionArn !== arn || result?.taskDefinition?.status !== "INACTIVE") evidence.cleanup.errors.push("Diagnostic definition deregistration unconfirmed"); + } + evidence.cleanup.deregistered = (!evidence.registerAttempted || !!definitions && arns.size > 0) && evidence.cleanup.errors.length === 0; + evidence.logs = []; + for (const task of verified) { + let token; + for (let i = 0; i < 6; i++) { + const page = await attempt(() => aws("logs", "get-log-events", ["--log-group-name", LOG, + "--log-stream-name", `origin-tls-${config.run}/probe/${task.split("/").pop()}`, "--start-from-head", + ...(token ? ["--next-token", token] : [])])); + if (!page) break; + evidence.logs.push(...(page.events || [])); + if (page.nextForwardToken === token) { + if (verifiedLogs(evidence.logs, evidence.before?.enis?.map((e) => e.PrivateIpAddress) || [])) break; + if (i === 5) break; + await pause(5000); + evidence.logs = []; + token = undefined; + continue; + } + token = page.nextForwardToken; + } + } + const complete = verifiedLogs(evidence.logs, evidence.before?.enis?.map((e) => e.PrivateIpAddress) || []); + evidence.success = evidence.success && complete && evidence.cleanup.stopped && evidence.cleanup.deregistered && evidence.cleanup.errors.length === 0; + save(config, evidence); + const archived = await archive(aws, config, "result.json", evidence); + appendFileSync(process.env.GITHUB_STEP_SUMMARY, `Private origin TLS result: version ${archived.version}, SHA-256 ${archived.sha256}. Outcome: ${evidence.success ? "verified" : "inconclusive"}.\n`); + requireThat(evidence.success, "Diagnostic incomplete, inconclusive or cleanup failed; inspect the private result before any new dispatch"); +} + +function verifiedLogs(events, targets) { + const rows = events.map((e) => { try { return JSON.parse(e.message); } catch { return null; } }).filter(Boolean); + if (!validTargets(targets) || !rows.some((r) => r.kind === "complete" && r.success === true) || + rows.some((r) => r.kind === "handshake" && !targets.includes(r.ip))) return false; + return targets.every((ip) => { + const handshakes = rows.filter((r) => r.kind === "handshake" && r.ip === ip); + return canonical(handshakes.map((r) => r.cipher)) === canonical([GCM[0], GCM[1], TLS13, ...CBC, GCM[0], TLS13]) && + handshakes.every((r) => classify(r, r.cipher === TLS13 ? "TLSv1.3" : "TLSv1.2", r.cipher, CBC.includes(r.cipher)) === + (CBC.includes(r.cipher) ? "refused" : "trusted")); + }); +} + +if (require.main === module) { + process.umask(0o077); + Promise.resolve().then(async () => { + const config = configuration(process.env); + const source = spawnSync("git", ["rev-parse", "HEAD"], { encoding: "utf8" }); + requireThat(source.status === 0 && source.stdout.trim() === config.source, "Checkout must match main workflow source"); + if (process.argv[2] === "session-policy") { + for (const phase of ["probe", "cleanup"]) appendFileSync(process.env.GITHUB_OUTPUT, `${phase}_policy=${canonical(sessionPolicy(config, phase))}\n`); + } else if (process.argv[2] === "probe") await execute(awsCLI, config); + else if (process.argv[2] === "finish") await finish(awsCLI, config); + else throw new Error("Unknown diagnostic command"); + }).catch((error) => { console.error(`Origin TLS diagnostic stopped: ${error.message}`); process.exitCode = 1; }); +} +module.exports = { configuration, sessionPolicy, discover, definition, archive, execute, finish, verifiedLogs, IMAGE, CLUSTER, SERVICE, EXECUTION, SG, ALB_SG, VPC, ECS, LOG }; diff --git a/.github/scripts/aws-origin-tls.test.cjs b/.github/scripts/aws-origin-tls.test.cjs new file mode 100644 index 000000000..c02f77759 --- /dev/null +++ b/.github/scripts/aws-origin-tls.test.cjs @@ -0,0 +1,778 @@ +const { test } = require("node:test"); +const assert = require("node:assert/strict"); +const { spawnSync } = require("node:child_process"); +const { mkdtempSync, readFileSync, rmSync, writeFileSync } = require("node:fs"); +const { tmpdir } = require("node:os"); +const { join } = require("node:path"); +const { ACCOUNT, BUCKET, ROLE, LB, LISTENER, DESIRED } = require("./aws-origin-alb.cjs"); +const { configuration, sessionPolicy, discover, definition, execute, finish, verifiedLogs, IMAGE, CLUSTER, SERVICE, EXECUTION, SG, ALB_SG, VPC, ECS, LOG } = require("./aws-origin-tls.cjs"); +const { probe, classify, invoke, CBC, TLS13 } = require("./origin-tls-client.cjs"); +const { refused } = require("./origin-tls-client.fixture.cjs"); + +const scaledTargets = ["10.42.0.85", "10.42.1.12", "10.42.0.86", "10.42.1.13"]; + +function logFixture(targets = ["10.42.0.85", "10.42.1.12"]) { + const events = []; + probe(targets, (args) => { + if (args[0] === "version") return { status: 0, stdout: "OpenSSL fixture" }; + if (args[0] === "ciphers") return { status: 0, stdout: CBC.join(":") }; + const cipher = args.at(-1); + return { command: ["openssl", ...args], ...(CBC.includes(cipher) ? + refused(cipher) : + { status: 0, stdout: `-----BEGIN CERTIFICATE-----\nfixture\nNew, ${cipher === TLS13 ? "TLSv1.3" : "TLSv1.2"}, Cipher is ${cipher}\nVerify return code: 0 (ok)`, stderr: "" }) }; + }, (row) => events.push({ message: JSON.stringify(row) })); + return events; +} + +const env = () => ({ GITHUB_ACTIONS: "true", GITHUB_REPOSITORY: "warmbly/warmbly", GITHUB_REF: "refs/heads/main", + GITHUB_EVENT_NAME: "workflow_dispatch", GITHUB_WORKFLOW_REF: "warmbly/warmbly/.github/workflows/probe-origin-tls-aws.yml@refs/heads/main", + GITHUB_RUN_ATTEMPT: "1", GITHUB_RUN_ID: "123456", GITHUB_SHA: "a".repeat(40), STATE_BUCKET: BUCKET, APPLY_ROLE: ROLE, + WORK: "/tmp/fixture", GITHUB_OUTPUT: "/tmp/output", GITHUB_STEP_SUMMARY: "/tmp/summary" }); + +function fixture(t, change = () => {}, targets = ["10.42.0.85", "10.42.1.12"]) { + const work = mkdtempSync(join(tmpdir(), "origin-tls-test-")); + t.after(() => rmSync(work, { recursive: true, force: true })); + const config = configuration({ ...env(), WORK: work }); + const arn = `${ECS}:task-definition/${config.family}:1`; + const task = `${ECS}:task/warmbly-production/${"1".repeat(32)}`; + const calls = []; + const zones = [{ ZoneName: "us-east-1a", SubnetId: "subnet-a" }, { ZoneName: "us-east-1b", SubnetId: "subnet-b" }]; + const network = { subnets: zones.map((z) => z.SubnetId), securityGroups: [SG], assignPublicIp: "ENABLED" }; + const state = { taskArn: task, clusterArn: CLUSTER, taskDefinitionArn: arn, startedBy: config.startedBy, + launchType: "FARGATE", enableExecuteCommand: false, lastStatus: "STOPPED", + containers: [{ name: "probe", exitCode: 0, imageDigest: IMAGE.split("@")[1] }] }; + const aws = async (service, action, args = []) => { + calls.push({ service, action, args }); + let result; + switch (action) { + case "get-caller-identity": result = { Account: ACCOUNT, Arn: `arn:aws:sts::${ACCOUNT}:assumed-role/warmbly-production-terraform-apply/fixture` }; break; + case "describe-load-balancers": result = { LoadBalancers: [{ LoadBalancerArn: LB, VpcId: VPC, + Type: "application", IpAddressType: "ipv4", State: { Code: "active" }, SecurityGroups: [ALB_SG], AvailabilityZones: zones }] }; break; + case "describe-listeners": result = { Listeners: [{ ListenerArn: LISTENER, LoadBalancerArn: LB, Protocol: "HTTPS", Port: 443, SslPolicy: DESIRED }] }; break; + case "describe-network-interfaces": result = { NetworkInterfaces: targets.map((ip, i) => { + const z = zones[i % 2]; + return { Description: "ELB app/warmbly-production-ingress/19d5c82c1651c871", NetworkInterfaceId: `eni-${i + 1}`, + AvailabilityZone: z.ZoneName, SubnetId: z.SubnetId, VpcId: VPC, Status: "in-use", RequesterManaged: true, OwnerId: ACCOUNT, + PrivateIpAddress: ip, Groups: [{ GroupId: ALB_SG }] }; + }) }; break; + case "describe-services": result = { services: [{ serviceArn: SERVICE, status: "ACTIVE", networkConfiguration: { awsvpcConfiguration: network } }] }; break; + case "describe-subnets": result = { Subnets: zones.map((z) => ({ SubnetId: z.SubnetId, VpcId: VPC, State: "available" })) }; break; + case "put-object": result = { ServerSideEncryption: "AES256", ChecksumSHA256: args[args.indexOf("--checksum-sha256") + 1], VersionId: "private-version" }; break; + case "register-task-definition": result = { taskDefinition: { taskDefinitionArn: arn } }; break; + case "run-task": result = { tasks: [state] }; break; + case "describe-tasks": result = { tasks: [state] }; break; + case "list-tasks": { + assert.equal(args[1], CLUSTER); + if (args.includes("--started-by")) { + assert.deepEqual(args, ["--cluster", CLUSTER, "--started-by", config.startedBy]); + result = { taskArns: state.lastStatus === "STOPPED" ? [] : [task] }; + } else { + assert.deepEqual(args, ["--cluster", CLUSTER, "--family", config.family, "--desired-status", "STOPPED"]); + result = { taskArns: state.lastStatus === "STOPPED" ? [task] : [] }; + } + break; + } + case "stop-task": state.lastStatus = "STOPPED"; result = { task: state }; break; + case "list-task-definitions": result = { taskDefinitionArns: [arn] }; break; + case "deregister-task-definition": result = { taskDefinition: { taskDefinitionArn: arn, status: "INACTIVE" } }; break; + case "get-log-events": result = { events: args.includes("--next-token") ? [] : logFixture(targets), nextForwardToken: "end" }; break; + default: throw new Error(`Unexpected ${service} ${action}`); + } + result = structuredClone(result); + await change(action, result, calls); + return result; + }; + return { config, aws, calls, arn, task, state, evidence: () => JSON.parse(readFileSync(join(work, "evidence.json"))) }; +} + +test("only fresh main dispatches under normal infrastructure configuration are admitted", () => { + assert.equal(configuration(env()).run, "123456"); + for (const [key, value] of Object.entries({ GITHUB_ACTIONS: "false", GITHUB_REPOSITORY: "fork/warmbly", GITHUB_REF: "refs/heads/branch", + GITHUB_EVENT_NAME: "pull_request", GITHUB_WORKFLOW_REF: "other", GITHUB_RUN_ATTEMPT: "2", GITHUB_RUN_ID: "../1", + GITHUB_SHA: "bad", STATE_BUCKET: "other", APPLY_ROLE: "other", WORK: "", GITHUB_OUTPUT: "", GITHUB_STEP_SUMMARY: "" })) { + assert.throws(() => configuration({ ...env(), [key]: value }), key); + } +}); + +test("each credential phase grants exactly its required operations and resource scopes", () => { + const config = configuration(env()); + const allow = (Action, Resource, Condition) => ({ Effect: "Allow", Action, Resource, ...(Condition ? { Condition } : {}) }); + const archive = allow("s3:PutObject", `arn:aws:s3:::${BUCKET}/warmbly/production/diagnostics/origin-tls/${config.run}/1/*`, { + StringEquals: { "s3:x-amz-server-side-encryption": "AES256", "s3:ResourceAccount": ACCOUNT }, + Bool: { "aws:SecureTransport": "true" }, Null: { "s3:if-none-match": "false" }, + }); + const expected = { + probe: [ + allow(["elasticloadbalancing:DescribeLoadBalancers", "elasticloadbalancing:DescribeListeners", + "ec2:DescribeNetworkInterfaces", "ec2:DescribeSubnets", "ecs:RegisterTaskDefinition"], "*"), + allow("ecs:DescribeServices", SERVICE), + allow("ecs:RunTask", `${ECS}:task-definition/${config.family}:*`, { ArnEquals: { "ecs:cluster": CLUSTER } }), + allow("ecs:DescribeTasks", `${ECS}:task/warmbly-production/*`), + allow("iam:PassRole", EXECUTION, { StringEquals: { "iam:PassedToService": "ecs-tasks.amazonaws.com" } }), + archive, + ], + cleanup: [ + allow(["ecs:ListTaskDefinitions", "ecs:ListTasks"], "*"), + allow("ecs:DeregisterTaskDefinition", "*"), + allow(["ecs:DescribeTasks", "ecs:StopTask"], `${ECS}:task/warmbly-production/*`), + allow("logs:GetLogEvents", `arn:aws:logs:us-east-1:${ACCOUNT}:log-group:${LOG}:log-stream:origin-tls-${config.run}/*`), + archive, + ], + }; + for (const phase of ["probe", "cleanup"]) { + const policy = sessionPolicy(config, phase); + assert.deepEqual(policy, { Version: "2012-10-17", Statement: expected[phase] }); + assert.ok(JSON.stringify(policy).length < 2048); + } + for (const phase of [undefined, "", "finish", "all"]) assert.throws(() => sessionPolicy(config, phase), /credential phase/); +}); + +test("the source gate emits distinct phase policies and refuses an unverified checkout", (t) => { + const f = fixture(t); + const revision = spawnSync("git", ["rev-parse", "HEAD"], { encoding: "utf8" }); + assert.equal(revision.status, 0); + const output = join(f.config.work, "output"); + const childEnv = { ...process.env, ...env(), WORK: f.config.work, GITHUB_OUTPUT: output, GITHUB_SHA: revision.stdout.trim() }; + const run = () => spawnSync(process.execPath, [join(__dirname, "aws-origin-tls.cjs"), "session-policy"], { env: childEnv, encoding: "utf8" }); + assert.equal(run().status, 0); + const policies = Object.fromEntries(readFileSync(output, "utf8").trim().split("\n").map((line) => { + const equals = line.indexOf("="); + return [line.slice(0, equals), JSON.parse(line.slice(equals + 1))]; + })); + assert.deepEqual(policies, { probe_policy: sessionPolicy(f.config, "probe"), cleanup_policy: sessionPolicy(f.config, "cleanup") }); + writeFileSync(output, ""); + childEnv.GITHUB_SHA = "0".repeat(40); + assert.equal(run().status, 1); + assert.equal(readFileSync(output, "utf8"), ""); +}); + +function phaseAWS(f, phase) { + const actions = sessionPolicy(f.config, phase).Statement.flatMap((s) => s.Action); + return (service, action, args) => { + const prefix = { elbv2: "elasticloadbalancing", s3api: "s3" }[service] || service; + const name = action.split("-").map((word) => word[0].toUpperCase() + word.slice(1)).join(""); + if (service !== "sts" || action !== "get-caller-identity") assert.ok(actions.includes(`${prefix}:${name}`), `${phase} must permit ${service} ${action}`); + return f.aws(service, action, args); + }; +} + +for (const failure of [null, "register-task-definition", "run-task", "describe-tasks"]) { + test(`phase sessions support ${failure || "successful probe"} cleanup with one registration and launch at most`, async (t) => { + let lost = false; + const f = fixture(t, (action) => { + if (action === failure && !lost) { lost = true; throw new Error("Fixture lost response"); } + }); + const oldSummary = process.env.GITHUB_STEP_SUMMARY; + process.env.GITHUB_STEP_SUMMARY = join(f.config.work, "summary"); + t.after(() => { if (oldSummary === undefined) delete process.env.GITHUB_STEP_SUMMARY; else process.env.GITHUB_STEP_SUMMARY = oldSummary; }); + const probeRun = execute(phaseAWS(f, "probe"), f.config, async () => {}); + if (failure) await assert.rejects(probeRun, /lost response/); + else await probeRun; + const boundary = f.calls.length; + if (failure && failure !== "register-task-definition") f.state.lastStatus = "RUNNING"; + const cleanup = finish(phaseAWS(f, "cleanup"), f.config, async () => {}); + if (failure) await assert.rejects(cleanup, /incomplete/); + else await cleanup; + assert.ok(!f.calls.slice(0, boundary).some((c) => c.action === "deregister-task-definition")); + assert.ok(!f.calls.slice(boundary).some((c) => ["register-task-definition", "run-task"].includes(c.action))); + assert.equal(f.calls.filter((c) => c.action === "register-task-definition").length, 1); + assert.equal(f.calls.filter((c) => c.action === "run-task").length, failure === "register-task-definition" ? 0 : 1); + assert.equal(f.evidence().cleanup.deregistered, true); + assert.equal(f.evidence().success, !failure); + assert.equal(f.calls.at(-1).action, "put-object"); + assert.deepEqual(JSON.parse(readFileSync(join(f.config.work, "result.json"))), f.evidence()); + }); +} + +test("fresh definition contains only the official digest, hard-bounded TLS client and existing execution/log facilities", () => { + const task = definition(configuration(env()), ["10.42.0.85", "10.42.1.12"]); + assert.deepEqual(Object.keys(task).sort(), ["family", "networkMode", "requiresCompatibilities", "cpu", "memory", "executionRoleArn", "runtimePlatform", "containerDefinitions"].sort()); + assert.equal(task.executionRoleArn, EXECUTION); + assert.equal(task.runtimePlatform.cpuArchitecture, "ARM64"); + const c = task.containerDefinitions[0]; + assert.match(c.image, /^docker\.io\/library\/node@sha256:[a-f0-9]{64}$/); + assert.equal(c.secrets, undefined); + assert.equal(c.repositoryCredentials, undefined); + assert.equal(c.portMappings, undefined); + assert.equal(c.mountPoints, undefined); + assert.equal(c.readonlyRootFilesystem, true); + assert.deepEqual(c.entryPoint, ["timeout", "-s", "KILL", "210", "node"]); + assert.deepEqual(c.environment.map((e) => e.name), ["ORIGIN_TLS_TASK", "ORIGIN_TLS_TARGETS"]); + assert.equal(c.logConfiguration.options["awslogs-create-group"], undefined); +}); + +test("only the exact active ALB, restricted listener, managed private ENIs and existing task network are accepted", async (t) => { + const changes = [ + ["describe-load-balancers", (r) => { r.LoadBalancers[0].VpcId = "vpc-other"; }], + ["describe-listeners", (r) => { r.Listeners[0].SslPolicy = "other"; }], + ["describe-network-interfaces", (r) => { r.NetworkInterfaces.pop(); }], + ["describe-network-interfaces", (r) => { r.NetworkInterfaces[0].Description = "another ALB"; }], + ["describe-network-interfaces", (r) => { r.NetworkInterfaces[0].Groups[0].GroupId = SG; }], + ["describe-network-interfaces", (r) => { r.NetworkInterfaces[0].RequesterManaged = false; }], + ["describe-network-interfaces", (r) => { r.NetworkInterfaces[0].OwnerId = "000000000000"; }], + ["describe-network-interfaces", (r) => { r.NetworkInterfaces[0].VpcId = "vpc-other"; }], + ["describe-network-interfaces", (r) => { r.NetworkInterfaces[0].Status = "available"; }], + ["describe-network-interfaces", (r) => { r.NetworkInterfaces[0].SubnetId = "subnet-other"; }], + ["describe-network-interfaces", (r) => { r.NetworkInterfaces[0].AvailabilityZone = "us-east-1c"; }], + ["describe-network-interfaces", (r) => { r.NetworkInterfaces[0].NetworkInterfaceId = r.NetworkInterfaces[1].NetworkInterfaceId; }], + ["describe-network-interfaces", (r) => { r.NetworkInterfaces[0].PrivateIpAddress = r.NetworkInterfaces[1].PrivateIpAddress; }], + ["describe-network-interfaces", (r) => { delete r.NetworkInterfaces[0].NetworkInterfaceId; }], + ["describe-network-interfaces", (r) => { r.NetworkInterfaces[0].PrivateIpAddress = "10.42.0.999"; }], + ["describe-services", (r) => { r.services[0].networkConfiguration.awsvpcConfiguration.securityGroups = ["sg-worker"]; }], + ["describe-services", (r) => { r.services[0].networkConfiguration.awsvpcConfiguration.subnets = ["subnet-a", "subnet-a"]; }], + ["describe-subnets", (r) => { r.Subnets[0].VpcId = "vpc-other"; }], + ["describe-subnets", (r) => { r.Subnets[0] = r.Subnets[1]; }], + ]; + for (const [target, mutate] of changes) { + const f = fixture(t, (action, result) => { if (action === target) mutate(result); }); + await assert.rejects(discover(f.aws)); + assert.ok(!f.calls.some((c) => c.action === "run-task")); + } +}); + +test("all current ALB interfaces across both zones are pinned, verified and privately archived", async (t) => { + let reads = 0; + const f = fixture(t, (action, result) => { + if (action === "describe-network-interfaces" && ++reads % 2) result.NetworkInterfaces.reverse(); + }, scaledTargets); + const oldSummary = process.env.GITHUB_STEP_SUMMARY; + process.env.GITHUB_STEP_SUMMARY = join(f.config.work, "summary"); + t.after(() => { if (oldSummary === undefined) delete process.env.GITHUB_STEP_SUMMARY; else process.env.GITHUB_STEP_SUMMARY = oldSummary; }); + await execute(f.aws, f.config, async () => {}); + const evidence = f.evidence(); + assert.equal(evidence.before.enis.length, 4); + const targets = JSON.parse(evidence.definition.containerDefinitions[0].environment.find((e) => e.name === "ORIGIN_TLS_TARGETS").value); + assert.deepEqual(targets, [...scaledTargets].sort()); + await finish(f.aws, f.config, async () => {}); + assert.equal(f.evidence().success, true); + assert.equal(verifiedLogs(f.evidence().logs, targets), true); + for (const ip of targets) { + assert.equal(verifiedLogs(f.evidence().logs.filter((e) => JSON.parse(e.message).ip !== ip), targets), false); + } + assert.equal(verifiedLogs(f.evidence().logs, [...targets, targets[0]]), false); + assert.equal(verifiedLogs([...f.evidence().logs, ...logFixture(["10.42.0.87", "10.42.1.14"])], targets), false); +}); + +test("every interface remains stable before launch and after the diagnostic", async (t) => { + for (const phase of [2, 3]) { + for (const mutate of [ + (enis) => { enis.pop(); }, + (enis) => { enis.push({ ...enis[0], NetworkInterfaceId: "eni-a", PrivateIpAddress: "10.42.0.87" }); }, + (enis) => { enis[0].NetworkInterfaceId = "eni-b"; }, + (enis) => { enis[0].PrivateIpAddress = "10.42.0.87"; }, + ]) { + let reads = 0; + const f = fixture(t, (action, result) => { + if (action === "describe-network-interfaces" && ++reads === phase) mutate(result.NetworkInterfaces); + }, scaledTargets); + await assert.rejects(execute(f.aws, f.config, async () => {}), /changed/); + assert.equal(f.evidence().success, false); + assert.equal(f.calls.filter((c) => c.action === "run-task").length, phase === 2 ? 0 : 1); + } + } +}); + +test("archive requires encryption, checksum and a real version before admitting a task", async (t) => { + for (const mutate of [(r) => { r.VersionId = "null"; }, (r) => { r.ChecksumSHA256 = "bad"; }, (r) => { r.ServerSideEncryption = ""; }]) { + const f = fixture(t, (action, result) => { if (action === "put-object") mutate(result); }); + await assert.rejects(execute(f.aws, f.config, async () => {}), /versioned/); + assert.ok(!f.calls.some((c) => c.action === "register-task-definition")); + } +}); + +test("successful lifecycle archives intent first, launches one secretless task, confirms cleanup and retains private logs", async (t) => { + const f = fixture(t); + const oldSummary = process.env.GITHUB_STEP_SUMMARY; + process.env.GITHUB_STEP_SUMMARY = join(f.config.work, "summary"); + t.after(() => { if (oldSummary === undefined) delete process.env.GITHUB_STEP_SUMMARY; else process.env.GITHUB_STEP_SUMMARY = oldSummary; }); + await execute(f.aws, f.config, async () => {}); + await finish(f.aws, f.config, async () => {}); + assert.equal(f.evidence().success, true); + const actions = f.calls.map((c) => c.action); + assert.ok(actions.indexOf("put-object") < actions.indexOf("register-task-definition")); + assert.equal(actions.filter((a) => a === "run-task").length, 1); + const request = JSON.parse(f.calls.find((c) => c.action === "run-task").args[1]); + assert.equal(request.taskDefinition, f.arn); + assert.equal(request.enableExecuteCommand, false); + assert.equal(request.clientToken, f.config.startedBy); + assert.equal(request.overrides, undefined); + assert.deepEqual(request.networkConfiguration.awsvpcConfiguration.securityGroups, [SG]); + assert.ok(!actions.includes("stop-task")); + assert.ok(actions.indexOf("describe-tasks") < actions.indexOf("deregister-task-definition")); + assert.equal(f.evidence().cleanup.stopped, true); + assert.equal(f.evidence().cleanup.deregistered, true); + assert.ok(f.evidence().logs.length > 0); + assert.ok(!readFileSync(process.env.GITHUB_STEP_SUMMARY, "utf8").includes("10.42.")); +}); + +for (const failure of ["register-task-definition", "run-task", "describe-tasks"]) { + test(`lost ${failure} response still permits diagnostic-only recovery and private failure evidence`, async (t) => { + let lost = false; + const f = fixture(t, (action) => { if (action === failure && !lost) { lost = true; throw new Error("Fixture lost response"); } }); + const oldSummary = process.env.GITHUB_STEP_SUMMARY; + process.env.GITHUB_STEP_SUMMARY = join(f.config.work, "summary"); + t.after(() => { if (oldSummary === undefined) delete process.env.GITHUB_STEP_SUMMARY; else process.env.GITHUB_STEP_SUMMARY = oldSummary; }); + await assert.rejects(execute(f.aws, f.config, async () => {}), /lost response/); + if (failure !== "register-task-definition") f.state.lastStatus = "RUNNING"; + await assert.rejects(finish(f.aws, f.config, async () => {}), /incomplete/); + assert.ok(f.calls.some((c) => c.action === "deregister-task-definition")); + if (failure !== "register-task-definition") assert.ok(f.calls.some((c) => c.action === "stop-task")); + if (failure !== "register-task-definition") { + const stop = f.calls.findIndex((c) => c.action === "stop-task"); + assert.ok(f.calls.slice(0, stop).some((c) => c.action === "describe-tasks")); + assert.equal(f.evidence().cleanup.recovery, "resolved"); + assert.equal(f.evidence().cleanup.stopped, true); + } + assert.equal(f.evidence().success, false); + assert.equal(f.calls.filter((c) => c.action === "put-object").length, 2); + assert.equal(f.calls.filter((c) => c.action === "run-task").length, failure === "register-task-definition" ? 0 : 1); + }); +} + +test("stopped diagnostic recovery verifies exact identity and privately archives its logs", async (t) => { + const f = fixture(t, (action) => { if (action === "run-task") throw new Error("Fixture lost response"); }); + const oldSummary = process.env.GITHUB_STEP_SUMMARY; + process.env.GITHUB_STEP_SUMMARY = join(f.config.work, "summary"); + t.after(() => { if (oldSummary === undefined) delete process.env.GITHUB_STEP_SUMMARY; else process.env.GITHUB_STEP_SUMMARY = oldSummary; }); + await assert.rejects(execute(f.aws, f.config, async () => {}), /lost response/); + assert.equal(f.evidence().taskArn, undefined); + await assert.rejects(finish(f.aws, f.config, async () => {}), /incomplete/); + const evidence = f.evidence(); + assert.equal(evidence.cleanup.recovery, "resolved"); + assert.equal(evidence.cleanup.stopped, true); + assert.deepEqual(evidence.cleanup.taskArns, [f.task]); + assert.deepEqual(evidence.cleanup.tasks.tasks, [f.state]); + assert.equal(verifiedLogs(evidence.logs, evidence.before.enis.map((e) => e.PrivateIpAddress)), true); + assert.ok(!f.calls.some((c) => c.action === "stop-task")); + const described = f.calls.findIndex((c) => c.action === "describe-tasks"); + assert.ok(described < f.calls.findIndex((c) => c.action === "get-log-events")); + assert.equal(evidence.success, false); + const archived = JSON.parse(readFileSync(join(f.config.work, "result.json"))); + assert.deepEqual(archived, evidence); + assert.equal(f.calls.at(-1).action, "put-object"); +}); + +test("ambiguous diagnostic recovery retains an unresolved private outcome within its discovery budget", async (t) => { + const f = fixture(t, (action, result) => { + if (action === "run-task") throw new Error("Fixture lost response"); + if (action === "list-tasks") result.taskArns = []; + }); + const oldSummary = process.env.GITHUB_STEP_SUMMARY; + process.env.GITHUB_STEP_SUMMARY = join(f.config.work, "summary"); + t.after(() => { if (oldSummary === undefined) delete process.env.GITHUB_STEP_SUMMARY; else process.env.GITHUB_STEP_SUMMARY = oldSummary; }); + await assert.rejects(execute(f.aws, f.config, async () => {}), /lost response/); + let sleeps = 0; + await assert.rejects(finish(f.aws, f.config, async () => { sleeps++; }), /incomplete/); + const evidence = f.evidence(); + assert.equal(evidence.cleanup.recovery, "unresolved"); + assert.equal(evidence.cleanup.stopped, false); + assert.deepEqual(evidence.cleanup.taskArns, []); + assert.deepEqual(evidence.logs, []); + assert.ok(evidence.cleanup.errors.includes("Diagnostic task identity unresolved")); + assert.equal(sleeps, 3); + assert.equal(f.calls.filter((c) => c.action === "list-tasks").length, 6); + assert.ok(!f.calls.some((c) => ["describe-tasks", "stop-task", "get-log-events"].includes(c.action))); + assert.deepEqual(f.calls.filter((c) => c.action === "deregister-task-definition").map((c) => c.args[1]), [f.arn]); + assert.equal(evidence.success, false); + assert.deepEqual(JSON.parse(readFileSync(join(f.config.work, "result.json"))), evidence); + assert.equal(f.calls.at(-1).action, "put-object"); +}); + +for (const field of ["taskArn", "clusterArn", "startedBy", "taskDefinitionArn"]) { + test(`diagnostic cleanup requires exact ${field} readback before stopping or collecting logs`, async (t) => { + const f = fixture(t, (action, result) => { + if (action === "run-task") throw new Error("Fixture lost response"); + if (action === "describe-tasks") result.tasks[0][field] += "7"; + }); + const oldSummary = process.env.GITHUB_STEP_SUMMARY; + process.env.GITHUB_STEP_SUMMARY = join(f.config.work, "summary"); + t.after(() => { if (oldSummary === undefined) delete process.env.GITHUB_STEP_SUMMARY; else process.env.GITHUB_STEP_SUMMARY = oldSummary; }); + await assert.rejects(execute(f.aws, f.config, async () => {}), /lost response/); + f.state.lastStatus = "RUNNING"; + await assert.rejects(finish(f.aws, f.config, async () => {}), /incomplete/); + assert.ok(!f.calls.some((c) => ["stop-task", "get-log-events"].includes(c.action))); + assert.equal(f.calls.filter((c) => c.action === "describe-tasks").length, 12); + assert.deepEqual(f.evidence().cleanup.taskArns, []); + assert.equal(f.evidence().cleanup.stopped, false); + assert.equal(f.evidence().cleanup.recovery, "unresolved"); + assert.equal(f.calls.at(-1).action, "put-object"); + }); +} + +test("diagnostic recovery cleans and archives only verified tasks among mixed candidates", async (t) => { + const other = `${ECS}:task/warmbly-production/${"2".repeat(32)}`; + const f = fixture(t, (action, result, calls) => { + if (action === "run-task") throw new Error("Fixture lost response"); + if (action === "list-tasks" && calls.at(-1).args.includes("STOPPED")) result.taskArns.push(other); + if (action === "describe-tasks") result.tasks.push({ ...f.state, taskArn: other, startedBy: `${f.config.startedBy}7`, lastStatus: "STOPPED" }); + }); + const oldSummary = process.env.GITHUB_STEP_SUMMARY; + process.env.GITHUB_STEP_SUMMARY = join(f.config.work, "summary"); + t.after(() => { if (oldSummary === undefined) delete process.env.GITHUB_STEP_SUMMARY; else process.env.GITHUB_STEP_SUMMARY = oldSummary; }); + await assert.rejects(execute(f.aws, f.config, async () => {}), /lost response/); + f.state.lastStatus = "RUNNING"; + await assert.rejects(finish(f.aws, f.config, async () => {}), /incomplete/); + assert.deepEqual(f.calls.filter((c) => c.action === "stop-task").map((c) => c.args[3]), [f.task]); + assert.ok(f.calls.filter((c) => c.action === "get-log-events").every((c) => + c.args[3] === `origin-tls-${f.config.run}/probe/${f.task.split("/").pop()}`)); + assert.deepEqual(f.evidence().cleanup.taskArns, [f.task]); + assert.equal(verifiedLogs(f.evidence().logs, f.evidence().before.enis.map((e) => e.PrivateIpAddress)), true); + assert.equal(f.evidence().cleanup.stopped, false); + assert.equal(f.evidence().cleanup.recovery, "unresolved"); + assert.equal(f.calls.filter((c) => c.action === "stop-task").length, 1); + assert.equal(f.calls.at(-1).action, "put-object"); +}); + +test("network drift after registration prevents launch and remains eligible for cleanup", async (t) => { + let reads = 0; + const f = fixture(t, (action, result) => { if (action === "describe-network-interfaces" && ++reads > 1) result.NetworkInterfaces[0].PrivateIpAddress = "10.42.0.86"; }); + await assert.rejects(execute(f.aws, f.config, async () => {}), /changed before launch/); + assert.ok(!f.calls.some((c) => c.action === "run-task")); + assert.equal(f.evidence().registerAttempted, true); +}); + +test("bad image identity and nonzero exit never establish proof", async (t) => { + for (const mutate of [(r) => { r.tasks[0].containers[0].exitCode = 1; }, (r) => { r.tasks[0].containers[0].imageDigest = "sha256:other"; }]) { + const f = fixture(t, (action, result) => { if (action === "describe-tasks") mutate(result); }); + await assert.rejects(execute(f.aws, f.config, async () => {}), /inconclusive/); + assert.equal(f.evidence().success, false); + } +}); + +test("missing or truncated raw handshake logs cannot be rescued by a successful completion marker", () => { + const targets = ["10.42.0.85", "10.42.1.12"]; + assert.equal(verifiedLogs(logFixture(), targets), true); + assert.equal(verifiedLogs(logFixture().filter((e) => JSON.parse(e.message).kind !== "handshake"), targets), false); + assert.equal(verifiedLogs(logFixture().slice(0, -1), targets), false); + const logs = logFixture(); + logs[2].message = logs[2].message.replace("return code: 0 (ok)", "return code: 62 (hostname mismatch)"); + assert.equal(verifiedLogs(logs, targets), false); +}); + +test("private archive verification reclassifies ambiguous or altered negative evidence", () => { + const targets = ["10.42.0.85", "10.42.1.12"]; + for (const alter of [ + (r) => { r.stdout = "CONNECTED\nclosed\nno peer certificate available\nNew, (NONE), Cipher is (NONE)\n"; r.status = 0; }, + (r) => { r.stdout = r.stdout.replace("<<<", ">>>"); }, + (r) => { r.stdout = r.stdout.replace("02 28", "01 00"); }, + (r) => { r.stdout = r.stdout.replace("c0 27", "c0 2f"); }, + ]) { + const logs = logFixture(); + const index = logs.findIndex((e) => JSON.parse(e.message).negative); + const row = JSON.parse(logs[index].message); + alter(row); + assert.equal(row.outcome, "refused"); + logs[index].message = JSON.stringify(row); + assert.equal(verifiedLogs(logs, targets), false); + } +}); + +test("refusal evidence accounts for complete traces, framing and both captured streams", () => { + const targets = ["10.42.0.85", "10.42.1.12"]; + const trace = (direction, kind, name, bytes, version = "1.2") => + `${direction} TLS ${version}, ${kind} [length ${bytes.length.toString(16).padStart(4, "0")}]${name ? `, ${name}` : ""}\n` + + ` ${bytes.toString("hex").match(/../g).join(" ")}\n`; + const check = (result, cipher, expected, label) => { + assert.equal(classify(result, "TLSv1.2", cipher, true), expected ? "refused" : "inconclusive", label); + const logs = logFixture(); + const index = logs.findIndex((e) => { const row = JSON.parse(e.message); return row.negative && row.cipher === cipher; }); + const row = JSON.parse(logs[index].message); + assert.equal(row.outcome, "refused"); + logs[index].message = JSON.stringify({ ...row, ...result }); + assert.equal(verifiedLogs(logs, targets), expected, label); + }; + for (const cipher of CBC) { + for (const scsv of [false, true]) { + const suites = [0xc0, cipher === CBC[0] ? 0x27 : 0x28, ...(scsv ? [0, 0xff] : [])]; + const bytes = Buffer.from([1, 0, 0, 39 + suites.length, 3, 3, + ...Array.from({ length: 32 }, (_, i) => 0x60 + i), 0, 0, suites.length, ...suites, 1, 0]); + const hello = trace(">>>", "Handshake", "ClientHello", bytes); + const alert = trace("<<<", "Alert", "fatal handshake_failure", Buffer.from([2, 40])); + const sent = trace(">>>", "RecordHeader", "", Buffer.from([22, 3, 1, 0, bytes.length]), "1.0"); + const received = trace("<<<", "RecordHeader", "", Buffer.from([21, 3, 3, 0, 2])); + const summary = "no peer certificate available\nNew, (NONE), Cipher is (NONE)\n"; + const result = { status: 1, stdout: hello + alert + summary, stderr: "SSL_connect:reading peer alert\n" }; + check(result, cipher, true, "complete message trace"); + check({ ...result, stdout: sent + hello + received + alert + summary }, cipher, true, "complete record trace"); + for (const size of [0, 32, 33]) { + const message = Buffer.concat([bytes.subarray(0, 38), Buffer.from([size]), Buffer.alloc(size, 0x5a), bytes.subarray(39)]); + message.writeUIntBE(message.length - 4, 1, 3); + check({ ...result, stdout: trace(">>>", "Handshake", "ClientHello", message) + alert + summary }, + cipher, size <= 32, "bounded ClientHello session identifier"); + } + for (const [expected, tails] of [ + [true, [[1, 0], [1, 0, 0, 0], [1, 0, 0, 5, 0xfa, 0xce, 0, 1, 0xaa]]], + [false, [[], [0], [1], [2, 0], [1, 1], [1, 0, 0], [1, 0, 0, 1], + [1, 0, 0, 1, 0], [1, 0, 0, 5, 0xfa, 0xce, 0, 2, 0xaa], + [1, 0, 0, 8, 0xfa, 0xce, 0, 0, 0xfa, 0xce, 0, 0]]], + ]) { + for (const tail of tails) { + const message = Buffer.concat([bytes.subarray(0, -2), Buffer.from(tail)]); + message.writeUIntBE(message.length - 4, 1, 3); + check({ ...result, stdout: trace(">>>", "Handshake", "ClientHello", message) + alert + summary }, + cipher, expected, "complete ClientHello vectors"); + } + } + for (const [expected, versions] of [ + [true, [2, 3, 3]], [true, [4, 3, 4, 3, 3]], [true, [4, 3, 3, 3, 4]], + [false, []], [false, [0]], [false, [1, 3]], [false, [2, 3]], + [false, [2, 3, 4]], [false, [4, 3, 3]], [false, [2, 3, 3, 3, 4]], + ]) { + const extensions = Buffer.from([0, 43, 0, versions.length, ...versions]); + const message = Buffer.concat([bytes, Buffer.from([0, extensions.length]), extensions]); + message.writeUIntBE(message.length - 4, 1, 3); + check({ ...result, stdout: trace(">>>", "Handshake", "ClientHello", message) + alert + summary }, + cipher, expected, "ClientHello version selection includes TLS 1.2"); + } + for (const extra of [ + alert.slice(0, alert.indexOf("[length") + 3), + alert.slice(0, alert.indexOf("\n") + 1), + trace("<<<", "Handshake", "ServerHello", Buffer.from([2, 0, 0, 0])), + " 91 a2 b3\n", + "[TLS message omitted]\n", + ]) { + for (const stream of ["stdout", "stderr"]) { + for (const position of ["before", "after"]) { + const output = position === "before" ? extra + result[stream] : result[stream] + extra; + check({ ...result, [stream]: output }, cipher, false, `${stream} ${position} envelope`); + } + } + } + for (const [label, stdout] of [ + ["record count", sent + hello + alert + summary], + ["record order", sent + received + hello + alert + summary], + ["record direction", sent + hello + received.replace("<<<", ">>>") + alert + summary], + ["record content type", sent.replace("16 03", "15 03") + hello + received + alert + summary], + ["record version", sent.replace("TLS 1.0", "TLS 1.2") + hello + received + alert + summary], + ["record payload length", sent + hello + received.replace("00 02", "00 03") + alert + summary], + ["message declared length", hello + alert.replace("length 0002", "length 0003") + summary], + ["message line termination", summary + hello + alert.trimEnd()], + ["intervening message", hello + "[TLS message omitted]\n" + alert + summary], + ]) check({ ...result, stdout }, cipher, false, label); + for (const stream of ["stdout", "stderr"]) { + const ticket = trace("<<<", "Handshake", "NewSessionTicket", Buffer.from([4, 0, 0, 2, 0x95, 0xa6])); + const sanitized = invoke([], () => ({ ...result, [stream]: result[stream] + ticket })); + assert.match(sanitized[stream], /\[TLS message omitted\]/); + check(sanitized, cipher, false, `${stream} omitted message`); + } + } + } +}); + +test("delayed log delivery is retried within a fixed page budget before verification", async (t) => { + let reads = 0; + const f = fixture(t, (action, result) => { if (action === "get-log-events" && ++reads <= 2) result.events = []; }); + const oldSummary = process.env.GITHUB_STEP_SUMMARY; + process.env.GITHUB_STEP_SUMMARY = join(f.config.work, "summary"); + t.after(() => { if (oldSummary === undefined) delete process.env.GITHUB_STEP_SUMMARY; else process.env.GITHUB_STEP_SUMMARY = oldSummary; }); + await execute(f.aws, f.config, async () => {}); + await finish(f.aws, f.config, async () => {}); + assert.equal(f.evidence().success, true); + assert.equal(reads, 4); +}); + +test("a task that never stops and absent logs fail within bounded polling and preserve cleanup evidence", async (t) => { + let sleeps = 0; + const f = fixture(t, (action, result) => { + if (action === "describe-tasks") result.tasks[0].lastStatus = "RUNNING"; + if (action === "get-log-events") result.events = []; + }); + const oldSummary = process.env.GITHUB_STEP_SUMMARY; + process.env.GITHUB_STEP_SUMMARY = join(f.config.work, "summary"); + t.after(() => { if (oldSummary === undefined) delete process.env.GITHUB_STEP_SUMMARY; else process.env.GITHUB_STEP_SUMMARY = oldSummary; }); + await assert.rejects(execute(f.aws, f.config, async () => { sleeps++; }), /inconclusive/); + await assert.rejects(finish(f.aws, f.config, async () => { sleeps++; }), /cleanup failed/); + assert.equal(f.calls.filter((c) => c.action === "describe-tasks").length, 60); + assert.equal(f.calls.filter((c) => c.action === "get-log-events").length, 6); + assert.equal(sleeps, 62); + assert.equal(f.evidence().cleanup.stopped, false); + assert.equal(f.calls.at(-1).action, "put-object"); +}); + +test("definition recovery confirms exact run identities within a fixed discovery budget and archives every outcome", async (t) => { + const oldSummary = process.env.GITHUB_STEP_SUMMARY; + t.after(() => { if (oldSummary === undefined) delete process.env.GITHUB_STEP_SUMMARY; else process.env.GITHUB_STEP_SUMMARY = oldSummary; }); + for (const [name, discoveredAt, includeInvalid] of [ + ["empty discovery remains unresolved", Infinity, false], + ["neighboring and malformed identities remain unresolved", Infinity, true], + ["exact identity on second discovery is confirmed", 2, true], + ["exact identity on final discovery is confirmed", 3, true], + ]) { + await t.test(name, async (t) => { + let reads = 0; + const f = fixture(t, (action, result, calls) => { + if (action === "register-task-definition") throw new Error("Fixture registration response unavailable"); + if (action === "list-task-definitions") { + assert.deepEqual(calls.at(-1).args, ["--family-prefix", f.config.family, "--status", "ACTIVE"]); + const invalid = [ + `${ECS}:task-definition/${f.config.family}7:1`, + `${ECS}:task-definition/${f.config.family}-other:1`, + `arn:aws:ecs:us-west-2:${ACCOUNT}:task-definition/${f.config.family}:1`, + `arn:aws:ecs:us-east-1:000000000000:task-definition/${f.config.family}:1`, + `${ECS}:task-definition/${f.config.family}:latest`, + `${f.arn}/suffix`, `${f.arn}\n`, `${f.arn}\r\n`, null, 42, + ]; + result.taskDefinitionArns = [ + ...(includeInvalid ? invalid : []), ...(++reads >= discoveredAt ? [f.arn, f.arn] : []), + ]; + } + }); + process.env.GITHUB_STEP_SUMMARY = join(f.config.work, "summary"); + await assert.rejects(execute(f.aws, f.config, async () => {}), /registration response unavailable/); + const delays = []; + await assert.rejects(finish(f.aws, f.config, async (ms) => { delays.push(ms); }), /incomplete/); + const resolved = Number.isFinite(discoveredAt); + const evidence = f.evidence(); + assert.equal(reads, Math.min(discoveredAt, 3)); + assert.deepEqual(delays, Array(reads - 1).fill(5000)); + assert.deepEqual(evidence.cleanup.definitionArns, resolved ? [f.arn] : []); + assert.equal(evidence.cleanup.definitionRecovery, resolved ? "resolved" : "unresolved"); + assert.equal(evidence.cleanup.deregistered, resolved); + assert.equal(evidence.cleanup.errors.includes("Diagnostic definition identity unresolved"), !resolved); + assert.deepEqual(f.calls.filter((c) => c.action === "deregister-task-definition").map((c) => c.args), + resolved ? [["--task-definition", f.arn]] : []); + assert.equal(f.calls.filter((c) => c.action === "register-task-definition").length, 1); + assert.ok(!f.calls.some((c) => ["run-task", "stop-task", "get-log-events"].includes(c.action))); + assert.equal(evidence.success, false); + assert.deepEqual(JSON.parse(readFileSync(join(f.config.work, "result.json"))), evidence); + assert.equal(f.calls.filter((c) => c.action === "put-object").length, 2); + assert.equal(f.calls.at(-1).action, "put-object"); + }); + } +}); + +test("definition discovery errors remain inconclusive even when a later exact identity can be cleaned", async (t) => { + const oldSummary = process.env.GITHUB_STEP_SUMMARY; + t.after(() => { if (oldSummary === undefined) delete process.env.GITHUB_STEP_SUMMARY; else process.env.GITHUB_STEP_SUMMARY = oldSummary; }); + for (const malformed of [false, true]) { + let reads = 0; + const f = fixture(t, (action, result) => { + if (action === "register-task-definition") throw new Error("Fixture registration response unavailable"); + if (action === "list-task-definitions" && ++reads === 1) { + if (malformed) result.taskDefinitionArns = {}; + else throw new Error("Fixture discovery response unavailable"); + } + }); + process.env.GITHUB_STEP_SUMMARY = join(f.config.work, "summary"); + await assert.rejects(execute(f.aws, f.config, async () => {}), /registration response unavailable/); + await assert.rejects(finish(f.aws, f.config, async () => {}), /incomplete/); + assert.equal(reads, 2); + assert.equal(f.evidence().cleanup.definitionRecovery, "resolved"); + assert.equal(f.evidence().cleanup.deregistered, false); + assert.ok(f.evidence().cleanup.errors.includes(malformed ? "Diagnostic definition discovery unconfirmed" : "Fixture discovery response unavailable")); + assert.deepEqual(f.calls.filter((c) => c.action === "deregister-task-definition").map((c) => c.args[1]), [f.arn]); + assert.ok(!f.calls.some((c) => c.action === "run-task")); + assert.equal(f.evidence().success, false); + assert.deepEqual(JSON.parse(readFileSync(join(f.config.work, "result.json"))), f.evidence()); + assert.equal(f.calls.at(-1).action, "put-object"); + } +}); + +test("definition cleanup is not required when registration was never attempted", async (t) => { + const f = fixture(t, (action, result) => { if (action === "get-caller-identity") result.Account = "000000000000"; }); + const oldSummary = process.env.GITHUB_STEP_SUMMARY; + process.env.GITHUB_STEP_SUMMARY = join(f.config.work, "summary"); + t.after(() => { if (oldSummary === undefined) delete process.env.GITHUB_STEP_SUMMARY; else process.env.GITHUB_STEP_SUMMARY = oldSummary; }); + await assert.rejects(execute(f.aws, f.config, async () => {}), /identity required/); + await assert.rejects(finish(f.aws, f.config, async () => { assert.fail("No registration needs no discovery delay"); }), /incomplete/); + assert.ok(!f.calls.some((c) => ["register-task-definition", "list-task-definitions", "deregister-task-definition", "run-task"].includes(c.action))); + assert.deepEqual(f.evidence().cleanup.definitionArns, []); + assert.equal(f.evidence().cleanup.definitionRecovery, "not-required"); + assert.equal(f.evidence().cleanup.deregistered, true); + assert.equal(f.evidence().success, false); + assert.deepEqual(JSON.parse(readFileSync(join(f.config.work, "result.json"))), f.evidence()); + assert.equal(f.calls.at(-1).action, "put-object"); +}); + +test("a saved exact definition permits confirmed cleanup with empty active discovery", async (t) => { + const f = fixture(t, (action, result) => { if (action === "list-task-definitions") result.taskDefinitionArns = []; }); + const oldSummary = process.env.GITHUB_STEP_SUMMARY; + process.env.GITHUB_STEP_SUMMARY = join(f.config.work, "summary"); + t.after(() => { if (oldSummary === undefined) delete process.env.GITHUB_STEP_SUMMARY; else process.env.GITHUB_STEP_SUMMARY = oldSummary; }); + await execute(f.aws, f.config, async () => {}); + await finish(f.aws, f.config, async () => { assert.fail("Saved identity needs no discovery delay"); }); + assert.equal(f.calls.filter((c) => c.action === "list-task-definitions").length, 1); + assert.deepEqual(f.calls.filter((c) => c.action === "deregister-task-definition").map((c) => c.args[1]), [f.arn]); + assert.equal(f.evidence().cleanup.definitionRecovery, "resolved"); + assert.equal(f.evidence().cleanup.deregistered, true); + assert.equal(f.evidence().success, true); + assert.equal(f.calls.filter((c) => c.action === "run-task").length, 1); +}); + +test("definition cleanup confirms only matching inactive readbacks and privately archives unconfirmed responses", async (t) => { + const oldSummary = process.env.GITHUB_STEP_SUMMARY; + t.after(() => { if (oldSummary === undefined) delete process.env.GITHUB_STEP_SUMMARY; else process.env.GITHUB_STEP_SUMMARY = oldSummary; }); + for (const response of ["unavailable", "neighbor", "active"]) { + const f = fixture(t, (action, result) => { + if (action === "deregister-task-definition") { + if (response === "unavailable") throw new Error("Fixture deregistration response unavailable"); + if (response === "neighbor") result.taskDefinition.taskDefinitionArn = `${ECS}:task-definition/${f.config.family}7:1`; + if (response === "active") result.taskDefinition.status = "ACTIVE"; + } + }); + process.env.GITHUB_STEP_SUMMARY = join(f.config.work, "summary"); + await execute(f.aws, f.config, async () => {}); + await assert.rejects(finish(f.aws, f.config, async () => {}), /incomplete/); + assert.equal(f.evidence().cleanup.definitionRecovery, "resolved"); + assert.equal(f.evidence().cleanup.deregistered, false); + assert.ok(f.evidence().cleanup.errors.includes("Diagnostic definition deregistration unconfirmed")); + assert.equal(f.calls.filter((c) => c.action === "deregister-task-definition").length, 1); + assert.equal(f.calls.filter((c) => c.action === "register-task-definition").length, 1); + assert.equal(f.calls.filter((c) => c.action === "run-task").length, 1); + assert.equal(f.evidence().success, false); + assert.deepEqual(JSON.parse(readFileSync(join(f.config.work, "result.json"))), f.evidence()); + assert.equal(f.calls.at(-1).action, "put-object"); + } +}); + +test("deregistration validates saved and discovered definitions against the exact run family, account, region and revision", async (t) => { + const oldSummary = process.env.GITHUB_STEP_SUMMARY; + t.after(() => { if (oldSummary === undefined) delete process.env.GITHUB_STEP_SUMMARY; else process.env.GITHUB_STEP_SUMMARY = oldSummary; }); + const config = configuration(env()); + const invalid = [ + `${ECS}:task-definition/${config.family}7:1`, + `${ECS}:task-definition/${config.family}-other:1`, + `${ECS}:task-definition/warmbly-production-backend:1`, + `arn:aws:ecs:us-west-2:${ACCOUNT}:task-definition/${config.family}:1`, + `arn:aws:ecs:us-east-1:000000000000:task-definition/${config.family}:1`, + `${ECS}:task-definition/${config.family}:latest`, + `${ECS}:task-definition/${config.family}:1/suffix`, + `${ECS}:task-definition/${config.family}:1\n`, + ]; + for (const saved of invalid) { + const f = fixture(t, (action, result, calls) => { + if (action === "register-task-definition") throw new Error("Fixture lost response"); + if (action === "list-task-definitions") { + assert.deepEqual(calls.at(-1).args, ["--family-prefix", config.family, "--status", "ACTIVE"]); + result.taskDefinitionArns = [f.arn, ...invalid, `${ECS}:task-definition/${config.family}:2`, f.arn, null, 42]; + } + if (action === "deregister-task-definition") result.taskDefinition.taskDefinitionArn = calls.at(-1).args[1]; + }); + process.env.GITHUB_STEP_SUMMARY = join(f.config.work, "summary"); + await assert.rejects(execute(f.aws, f.config, async () => {}), /lost response/); + writeFileSync(join(f.config.work, "evidence.json"), JSON.stringify({ ...f.evidence(), definitionArn: saved })); + await assert.rejects(finish(f.aws, f.config, async () => {}), /incomplete/); + const expected = [f.arn, `${ECS}:task-definition/${config.family}:2`]; + assert.deepEqual(f.calls.filter((c) => c.action === "deregister-task-definition").map((c) => c.args), + expected.map((arn) => ["--task-definition", arn])); + assert.deepEqual(f.evidence().cleanup.definitionArns, expected); + assert.equal(f.evidence().cleanup.deregistered, true); + assert.equal(f.calls.at(-1).action, "put-object"); + } +}); + +test("cleanup failure stays bounded, still deregisters and archives, and never touches a neighboring family", async (t) => { + const f = fixture(t, (action, result) => { + if (action === "stop-task") throw new Error("Fixture stop denied"); + if (action === "list-task-definitions") result.taskDefinitionArns.push(`${ECS}:task-definition/${f.config.family}7:1`); + }); + const oldSummary = process.env.GITHUB_STEP_SUMMARY; + process.env.GITHUB_STEP_SUMMARY = join(f.config.work, "summary"); + t.after(() => { if (oldSummary === undefined) delete process.env.GITHUB_STEP_SUMMARY; else process.env.GITHUB_STEP_SUMMARY = oldSummary; }); + await execute(f.aws, f.config, async () => {}); + f.state.lastStatus = "RUNNING"; + await assert.rejects(finish(f.aws, f.config, async () => {}), /cleanup failed/); + assert.deepEqual(f.calls.filter((c) => c.action === "deregister-task-definition").map((c) => c.args[1]), [f.arn]); + assert.ok(f.evidence().cleanup.errors.includes("Fixture stop denied")); + assert.equal(f.calls.at(-1).action, "put-object"); +}); diff --git a/.github/scripts/origin-tls-client.cjs b/.github/scripts/origin-tls-client.cjs new file mode 100644 index 000000000..4c812cf6f --- /dev/null +++ b/.github/scripts/origin-tls-client.cjs @@ -0,0 +1,185 @@ +const { spawnSync } = require("node:child_process"); +const { existsSync } = require("node:fs"); + +const HOST = "api.warmbly.com"; +const CA = "/etc/ssl/certs/ca-certificates.crt"; +const CBC = ["ECDHE-RSA-AES128-SHA256", "ECDHE-RSA-AES256-SHA384"]; +const GCM = ["ECDHE-RSA-AES128-GCM-SHA256", "ECDHE-RSA-AES256-GCM-SHA384"]; +const TLS13 = "TLS_AES_128_GCM_SHA256"; +const TRACE_HEADER = /^(>>>|<<<) TLS (1\.[0-3]), (RecordHeader|Handshake|Alert) \[length ([a-f\d]{4})\](?:, ([^\r\n]+))?$/i; +const OMITTED_MESSAGE = "[TLS message omitted]"; +const validTargets = (targets) => Array.isArray(targets) && targets.length >= 2 && new Set(targets).size === targets.length && + targets.every((ip) => typeof ip === "string" && /^10\.42\.(?:0|1)\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4])$/.test(ip)); + +function sanitize(output) { + let session = false; + let ticket = false; + return output.split("\n").flatMap((line) => { + if (/^SSL-Session:/.test(line)) session = true; + if (/^---$/.test(line)) session = false; + if (/^(?:>>>|<<<) .*\bNewSessionTicket\b/.test(line)) { + ticket = true; + return [OMITTED_MESSAGE]; + } + if (TRACE_HEADER.test(line)) ticket = false; + if (ticket) return []; + return !session || /^\s*Verify return code:/.test(line) ? [line] : []; + }).join("\n"); +} + +function invoke(args, spawn = spawnSync) { + const result = spawn("openssl", args, { encoding: "utf8", input: "", timeout: 12000, + killSignal: "SIGKILL", maxBuffer: 128 * 1024 }); + return { at: new Date().toISOString(), command: ["openssl", ...args], status: result.status, + signal: result.signal || null, error: result.error?.code || null, + stdout: sanitize(result.stdout || ""), stderr: sanitize(result.stderr || "") }; +} + +function traceMessages(output) { + const lines = output.split("\n"); + const messages = []; + for (let i = 0; i < lines.length; i++) { + const line = lines[i]; + if (/^[ \t]*[<>]/.test(line)) { + const header = TRACE_HEADER.exec(line); + if (!header || i === lines.length - 1 || (header[3] === "RecordHeader" ? header[5] : !header[5])) return null; + let hex = ""; + while (i + 1 < lines.length && /^[ \t]+\S/.test(lines[i + 1])) { + const body = lines[++i]; + if (i === lines.length - 1 || !/^[ \t]+(?:[a-f\d]{2}[ \t]+)*[a-f\d]{2}[ \t]*$/i.test(body)) return null; + hex += body.replace(/[ \t]/g, ""); + } + const bytes = Buffer.from(hex, "hex"); + if (!bytes.length || bytes.length !== parseInt(header[4], 16)) return null; + messages.push({ direction: header[1], version: header[2], kind: header[3], name: header[5], bytes }); + } else if (line === OMITTED_MESSAGE || (/^[ \t]+\S/.test(line) && !/^[ \t]+Verify return code:/.test(line)) || + /\b(?:RecordHeader|Handshake|Alert) \[length\b/.test(line) || + /^[a-f\d]+(?:[ \t]|$)/i.test(line)) return null; + } + return messages; +} + +function completeClientHelloTail(sent, offset) { + if (offset + 2 > sent.length || sent[offset] !== 1 || sent[offset + 1] !== 0) return false; + offset += 2; + if (offset === sent.length) return true; + if (offset + 2 > sent.length || offset + 2 + sent.readUInt16BE(offset) !== sent.length) return false; + offset += 2; + const extensions = new Set(); + while (offset < sent.length) { + if (offset + 4 > sent.length) return false; + const kind = sent.readUInt16BE(offset); + const length = sent.readUInt16BE(offset + 2); + if (extensions.has(kind) || offset + 4 + length > sent.length) return false; + if (kind === 43) { + if (length < 3 || sent[offset + 4] !== length - 1 || (length - 1) % 2) return false; + let tls12 = false; + for (let at = offset + 5; at < offset + 4 + length; at += 2) { + if (sent.readUInt16BE(at) === 0x0303) tls12 = true; + } + if (!tls12) return false; + } + extensions.add(kind); + offset += 4 + length; + } + return true; +} + +function peerRefusal(stdout, stderr, cipher) { + const trace = traceMessages(stdout); + const diagnosticTrace = traceMessages(stderr); + if (!trace || !diagnosticTrace || diagnosticTrace.length) return false; + const messages = trace.filter((message) => message.kind !== "RecordHeader"); + if (messages.length !== 2 || ![2, 4].includes(trace.length)) return false; + if (trace.length === 4 && !messages.every((message, i) => { + const record = trace[i * 2]; + return trace[i * 2 + 1] === message && record.kind === "RecordHeader" && record.direction === message.direction && + record.bytes.length === 5 && record.bytes[0] === (i === 0 ? 22 : 21) && + record.bytes.readUInt16BE(1) === 0x0301 + Number(record.version.at(-1)) && + record.bytes.readUInt16BE(3) === message.bytes.length; + })) return false; + const [hello, alert] = messages; + const sent = hello.bytes; + const received = alert.bytes; + if (hello.direction !== ">>>" || hello.version !== "1.2" || hello.kind !== "Handshake" || hello.name !== "ClientHello" || + sent.length < 41 || sent[0] !== 1 || sent[38] > 32 || + sent.readUIntBE(1, 3) !== sent.length - 4 || sent.readUInt16BE(4) !== 0x0303) return false; + const offset = 39 + sent[38]; + if (offset + 2 > sent.length) return false; + const length = sent.readUInt16BE(offset); + const offers = sent.subarray(offset + 2, offset + 2 + length).toString("hex"); + const intended = { [CBC[0]]: "c027", [CBC[1]]: "c028" }[cipher]; + // The sole negotiable suite may be followed by the renegotiation signalling value. + return intended && length >= 2 && offset + 2 + length < sent.length && + completeClientHelloTail(sent, offset + 2 + length) && + (offers === intended || offers === intended + "00ff") && + alert.direction === "<<<" && alert.version === "1.2" && alert.kind === "Alert" && alert.name === "fatal handshake_failure" && + received.equals(Buffer.from([2, 40])); +} + +function classify(result, version, cipher, negative = false) { + const output = result.stdout + result.stderr; + const negotiated = /New, (TLSv1\.[23]), Cipher is ([^\s]+)/.exec(output); + if (negative) { + if (/certificate verify failed|Verification error|verify error|no cipher match|unexpected eof|reset by peer|connect:errno/i.test(output)) return "inconclusive"; + const deadline = result.error === "ETIMEDOUT" && result.status === null && (!result.signal || result.signal === "SIGKILL"); + if (negotiated && negotiated[2] !== "(NONE)" && negotiated[2] !== "0000" && + ((!result.error && !result.signal) || deadline)) return "accepted"; + if (result.error || result.signal) return "inconclusive"; + return result.status === 1 && peerRefusal(result.stdout || "", result.stderr || "", cipher) && + !/-----BEGIN CERTIFICATE-----/.test(output) && /no peer certificate available/.test(output) && + /New, \(NONE\), Cipher is \(NONE\)/.test(output) ? "refused" : "inconclusive"; + } + if (result.error || result.signal) return "inconclusive"; + return result.status === 0 && negotiated?.[1] === version && negotiated[2] === cipher && + /Verify return code: 0 \(ok\)/.test(output) && /-----BEGIN CERTIFICATE-----/.test(output) ? "trusted" : "inconclusive"; +} + +function probe(targets, run = invoke, emit = (row) => console.log(JSON.stringify(row)), now = () => performance.now()) { + if (!validTargets(targets)) throw new Error("Unique pinned origin IPv4 targets required"); + const started = now(); + const bounded = (args) => { + // Reserve one 12-second invocation within 180 seconds and the outer 210-second task limit. + if (now() - started >= 168000) throw new Error("Origin TLS client runtime budget exhausted"); + return run(args); + }; + const version = bounded(["version", "-a"]); + emit({ kind: "client", ...version }); + if (version.status !== 0 || version.error || version.signal) throw new Error("OpenSSL unavailable"); + const support = bounded(["ciphers", "-s", "-tls1_2", CBC.join(":")]); + emit({ kind: "support", ...support }); + if (support.status !== 0 || support.error || support.signal || + support.stdout.trim().split(":").sort().join(":") !== [...CBC].sort().join(":")) throw new Error("Both CBC offers must be locally supported"); + let success = true; + for (const ip of targets) { + const handshake = (cipher, negative = false) => { + const tls13 = cipher === TLS13; + const result = bounded(["s_client", "-connect", `${ip}:443`, "-servername", HOST, "-verify_hostname", HOST, + "-verify_return_error", "-CAfile", CA, "-showcerts", "-no_ticket", + ...(negative ? ["-ign_eof", "-state", "-msg"] : []), tls13 ? "-tls1_3" : "-tls1_2", + tls13 ? "-ciphersuites" : "-cipher", cipher]); + const outcome = classify(result, tls13 ? "TLSv1.3" : "TLSv1.2", cipher, negative); + emit({ kind: "handshake", ip, cipher, negative, outcome, ...result }); + return outcome; + }; + const before = [handshake(GCM[0]), handshake(GCM[1]), handshake(TLS13)]; + const negatives = CBC.map((cipher) => handshake(cipher, true)); + const after = [handshake(GCM[0]), handshake(TLS13)]; + const passed = [...before, ...after].every((v) => v === "trusted") && negatives.every((v) => v === "refused"); + emit({ kind: "target", ip, outcome: passed ? "verified" : "inconclusive" }); + success = success && passed; + } + emit({ kind: "complete", success, at: new Date().toISOString() }); + return success; +} + +if (process.env.ORIGIN_TLS_TASK === "1") { + try { + if (!existsSync(CA)) throw new Error("System public CA bundle missing"); + process.exitCode = probe(JSON.parse(process.env.ORIGIN_TLS_TARGETS)) ? 0 : 1; + } catch (error) { + console.log(JSON.stringify({ kind: "inconclusive", message: error.message })); + process.exitCode = 1; + } +} +module.exports = { HOST, CA, CBC, GCM, TLS13, invoke, classify, probe, validTargets }; diff --git a/.github/scripts/origin-tls-client.fixture.cjs b/.github/scripts/origin-tls-client.fixture.cjs new file mode 100644 index 000000000..41867387c --- /dev/null +++ b/.github/scripts/origin-tls-client.fixture.cjs @@ -0,0 +1,15 @@ +const { CBC } = require("./origin-tls-client.cjs"); + +function refused(cipher = CBC[0]) { + const suite = cipher === CBC[0] ? "c0 27" : "c0 28"; + const hello = `01 00 00 2b 03 03 ${"00 ".repeat(32)}00 00 04 ${suite} 00 ff 01 00`; + return { status: 1, stdout: `>>> TLS 1.2, Handshake [length 002f], ClientHello + ${hello} +<<< TLS 1.2, Alert [length 0002], fatal handshake_failure + 02 28 +no peer certificate available +New, (NONE), Cipher is (NONE) +`, stderr: "SSL_connect:SSLv3/TLS write client hello\nSSL3 alert read:fatal:handshake failure\n" }; +} + +module.exports = { refused }; diff --git a/.github/scripts/origin-tls-client.test.cjs b/.github/scripts/origin-tls-client.test.cjs new file mode 100644 index 000000000..95b514d9c --- /dev/null +++ b/.github/scripts/origin-tls-client.test.cjs @@ -0,0 +1,294 @@ +const { test } = require("node:test"); +const assert = require("node:assert/strict"); +const { spawnSync } = require("node:child_process"); +const { mkdtempSync, readFileSync, rmSync } = require("node:fs"); +const { tmpdir } = require("node:os"); +const { join } = require("node:path"); +const { Worker } = require("node:worker_threads"); +const { CBC, GCM, TLS13, HOST, CA, invoke, classify, probe } = require("./origin-tls-client.cjs"); +const { refused } = require("./origin-tls-client.fixture.cjs"); +const trusted = (cipher = GCM[0]) => ({ status: 0, stdout: `-----BEGIN CERTIFICATE-----\nfixture chain\n-----END CERTIFICATE-----\nNew, ${cipher === TLS13 ? "TLSv1.3" : "TLSv1.2"}, Cipher is ${cipher}\nVerify return code: 0 (ok)\n`, stderr: "" }); + +test("positive proof requires exact negotiation, chain, verification and successful bounded execution", () => { + assert.equal(classify(trusted(), "TLSv1.2", GCM[0]), "trusted"); + for (const result of [ + { ...trusted(), status: 1 }, { ...trusted(), error: "ETIMEDOUT" }, { ...trusted(), signal: "SIGKILL" }, + { ...trusted(), stdout: trusted().stdout.replace("return code: 0 (ok)", "return code: 62 (hostname mismatch)") }, + { ...trusted(), stdout: trusted().stdout.replace("-----BEGIN CERTIFICATE-----", "") }, + trusted(GCM[1]), trusted(TLS13), + ]) assert.equal(classify(result, "TLSv1.2", GCM[0]), "inconclusive"); +}); + +test("only an explicit peer handshake refusal without negotiation establishes a negative", () => { + assert.equal(classify(refused(), "TLSv1.2", CBC[0], true), "refused"); + assert.equal(classify(trusted(CBC[0]), "TLSv1.2", CBC[0], true), "accepted"); + for (const result of [ + { ...refused(), signal: "SIGTERM" }, { ...refused(), error: "ETIMEDOUT" }, + { status: 1, stdout: "", stderr: "Connection reset by peer" }, + { status: 1, stdout: "", stderr: "connect:errno=110" }, + { status: 1, stdout: "", stderr: "no cipher match" }, + { status: 1, stdout: "", stderr: "certificate verify failed" }, + { status: 1, stdout: "", stderr: "tlsv1 alert protocol version:SSL alert number 70" }, + { ...refused(), stdout: "", status: 0 }, + ]) assert.equal(classify(result, "TLSv1.2", CBC[0], true), "inconclusive"); +}); + +function fixture(change = () => {}) { + const rows = []; + let handshakes = 0; + const run = (args) => { + if (args[0] === "version") return { status: 0, stdout: "OpenSSL 3.0 fixture", stderr: "" }; + if (args[0] === "ciphers") return { status: 0, stdout: CBC.join(":"), stderr: "" }; + handshakes++; + const cipher = args.at(-1); + const result = { ...(CBC.includes(cipher) ? refused(cipher) : trusted(cipher)), command: ["openssl", ...args] }; + change(result, handshakes); + return result; + }; + return { rows, run }; +} + +test("completed negative negotiations retain their outcome at the process deadline", () => { + for (const cipher of CBC) { + const negotiated = { ...trusted(cipher), status: null, error: "ETIMEDOUT", signal: "SIGKILL" }; + assert.equal(classify(negotiated, "TLSv1.2", cipher, true), "accepted"); + assert.equal(classify({ ...negotiated, signal: null }, "TLSv1.2", cipher, true), "accepted"); + for (const altered of [ + { ...negotiated, error: "ENOBUFS" }, { ...negotiated, error: "EIO" }, + { ...negotiated, error: null }, { ...negotiated, signal: "SIGTERM" }, { ...negotiated, status: 0 }, + { ...negotiated, stderr: "certificate verify failed" }, + { ...negotiated, stdout: refused(cipher).stdout }, + ]) assert.equal(classify(altered, "TLSv1.2", cipher, true), "inconclusive"); + assert.equal(classify(negotiated, "TLSv1.2", cipher), "inconclusive"); + } + const f = fixture((row, index) => { + if (index === 4) Object.assign(row, trusted(CBC[0]), { status: null, error: "ETIMEDOUT", signal: "SIGKILL" }); + }); + assert.equal(probe(["10.42.0.85", "10.42.1.12"], f.run, (row) => f.rows.push(row)), false); + assert.equal(f.rows.find((row) => row.kind === "handshake" && row.negative).outcome, "accepted"); + assert.equal(f.rows.at(-1).success, false); +}); + +test("every private target has fresh trusted positives around both explicit CBC offers", () => { + const f = fixture(); + assert.equal(probe(["10.42.0.85", "10.42.1.12"], f.run, (row) => f.rows.push(row)), true); + const hs = f.rows.filter((r) => r.kind === "handshake"); + assert.equal(hs.length, 14); + for (const ip of ["10.42.0.85", "10.42.1.12"]) { + const own = hs.filter((r) => r.ip === ip); + assert.deepEqual(own.map((r) => r.cipher), [GCM[0], GCM[1], TLS13, ...CBC, GCM[0], TLS13]); + for (const row of own) { + const args = row.command; + for (const [flag, value] of [["-connect", `${ip}:443`], ["-servername", HOST], ["-verify_hostname", HOST], ["-CAfile", CA]]) { + assert.equal(args[args.indexOf(flag) + 1], value); + } + assert.ok(args.includes("-verify_return_error")); + assert.ok(args.includes("-showcerts")); + assert.ok(args.includes("-no_ticket")); + for (const flag of ["-ign_eof", "-state", "-msg"]) assert.equal(args.includes(flag), row.negative); + assert.ok(args.includes(row.cipher === TLS13 ? "-tls1_3" : "-tls1_2")); + } + } + assert.deepEqual(f.rows.at(-1).success, true); +}); + +test("all current private interfaces receive the full handshake sequence", () => { + const targets = ["10.42.0.85", "10.42.1.12", "10.42.0.86", "10.42.1.13"]; + const f = fixture(); + assert.equal(probe(targets, f.run, (row) => f.rows.push(row)), true); + const handshakes = f.rows.filter((r) => r.kind === "handshake"); + assert.equal(handshakes.length, 28); + for (const ip of targets) { + assert.deepEqual(handshakes.filter((r) => r.ip === ip).map((r) => r.cipher), + [GCM[0], GCM[1], TLS13, ...CBC, GCM[0], TLS13]); + } + assert.equal(f.rows.at(-1).success, true); +}); + +test("larger target sets share one fixed runtime budget and cannot complete with partial evidence", () => { + const f = fixture(); + let elapsed = 0; + let calls = 0; + const run = (args) => { + calls++; + elapsed += 12000; + return f.run(args); + }; + assert.throws(() => probe(["10.42.0.85", "10.42.1.12", "10.42.0.86", "10.42.1.13"], + run, (row) => f.rows.push(row), () => elapsed), /runtime budget exhausted/); + assert.equal(calls, 14); + assert.equal(elapsed, 168000); + assert.ok(!f.rows.some((r) => r.kind === "complete")); +}); + +test("timeout or broken trailing positive makes the whole run inconclusive", () => { + for (const index of [4, 6, 14]) { + const f = fixture((result, n) => { if (n === index) result.error = "ETIMEDOUT"; }); + assert.equal(probe(["10.42.0.85", "10.42.1.12"], f.run, (row) => f.rows.push(row)), false); + assert.equal(f.rows.at(-1).success, false); + } +}); + +test("local CBC support is checked before network traffic and arbitrary destinations are refused", () => { + const f = fixture(); + assert.throws(() => probe(["1.1.1.1", "10.42.1.12"], f.run), /pinned/); + assert.throws(() => probe(["10.42.0.85", "10.42.0.85"], f.run), /pinned/); + assert.throws(() => probe(["10.42.0.85", "10.42.1.12"], (args) => ({ status: 0, stdout: args[0] === "version" ? "OpenSSL" : CBC[0] }), () => {}), /Both CBC/); +}); + +test("OpenSSL processes get empty stdin, a hard timeout, bounded output and no shell", () => { + const result = invoke(["version"], (command, args, options) => { + assert.equal(command, "openssl"); + assert.deepEqual(args, ["version"]); + assert.equal(options.input, ""); + assert.equal(options.timeout, 12000); + assert.equal(options.killSignal, "SIGKILL"); + assert.equal(options.shell, undefined); + assert.equal(options.maxBuffer, 128 * 1024); + return { status: null, error: { code: "ETIMEDOUT" }, signal: "SIGKILL" }; + }); + assert.equal(result.error, "ETIMEDOUT"); + assert.equal(result.signal, "SIGKILL"); +}); + +test("negative proof binds inbound alert bytes to the sole transmitted CBC suite", () => { + for (const cipher of CBC) assert.equal(classify(refused(cipher), "TLSv1.2", cipher, true), "refused"); + for (const change of [ + (s) => s.replace("<<<", ">>>"), + (s) => s.replace("02 28", "01 00"), + (s) => s.replace("fatal handshake_failure", "warning close_notify"), + (s) => s.replace("c0 27", "c0 28"), + (s) => s.replace("c0 27", "c0 2f"), + (s) => s.replace("00 04 c0 27 00 ff", "00 04 c0 27 c0 2f"), + (s) => s.replace("length 002f", "length 0030"), + (s) => s.replace("01 00 00 2b", "01 00 00 2c"), + (s) => s.replace("New, (NONE)", "-----BEGIN CERTIFICATE-----\nNew, (NONE)"), + (s) => s.replace("no peer certificate available", ""), + (s) => s + "Connection reset by peer\n", + (s) => s + "unexpected eof while reading\n", + (s) => s + "<<< TLS 1.2, Handshake [length 0004], ServerHello\n 02 00 00 00\n", + (s) => s.replace(/>>>[\s\S]*?<<< /, "<<< "), + ]) assert.equal(classify({ ...refused(), stdout: change(refused().stdout) }, "TLSv1.2", CBC[0], true), "inconclusive"); + for (const status of [0, null, 2]) assert.equal(classify({ ...refused(), status }, "TLSv1.2", CBC[0], true), "inconclusive"); + for (const stdout of ["CONNECTED\nclosed\nno peer certificate available\nNew, (NONE), Cipher is (NONE)\n", + "SSL handshake has read 7 bytes\nNew, (NONE), Cipher is (NONE)\n"]) { + assert.equal(classify({ status: 0, stdout, stderr: "" }, "TLSv1.2", CBC[0], true), "inconclusive"); + } +}); + +test("archived output retains certificate and refusal evidence without session secrets or ticket bodies", () => { + const proof = trusted().stdout + refused().stdout; + const session = "SSL-Session:\n Protocol : TLSv1.2\n Master-Key: SECRET_KEY\n Resumption PSK: SECRET_PSK\n TLS session ticket:\n 0000 - ab cd ef ...\n Verify return code: 0 (ok)\n---\n"; + const ticket = "<<< TLS 1.2, Handshake [length 0004], NewSessionTicket\n 04 00 00 00\n"; + const result = invoke(["version"], () => ({ status: 0, stdout: proof + session + ticket + refused().stdout, stderr: session })); + assert.ok(result.stdout.includes(proof)); + assert.ok(result.stdout.includes("Verify return code: 0 (ok)")); + assert.ok(result.stdout.endsWith(refused().stdout)); + assert.doesNotMatch(result.stdout + result.stderr, /SECRET|Master-Key|Resumption PSK|session ticket|NewSessionTicket|04 00 00 00|ab cd ef/); +}); + +test("captured ticket and session regions retain only approved evidence at every cutoff", () => { + const prefix = trusted().stdout; + const header = "<<< TLS 1.2, Handshake [length 000e], NewSessionTicket\n"; + const body = " 04 00 00 0a 71 82 93 a4\n b5 c6 d7 e8 f9 0a\ncapture-tail"; + const resumed = "<<< TLS 1.2, Alert [length 0002], warning close_notify\n 01 00\n"; + const session = "SSL-Session:\n Master-Key: SYNTHETIC_MAPLE\n Resumption PSK: SYNTHETIC_BIRCH\n"; + for (const stream of ["stdout", "stderr"]) { + for (const execution of [{ status: 0 }, { status: null, error: { code: "ENOBUFS" } }, + { status: null, error: { code: "ETIMEDOUT" }, signal: "SIGKILL" }]) { + const capture = (output) => invoke([], () => ({ stdout: "", stderr: "", ...execution, [stream]: output })); + for (let cutoff = 0; cutoff <= body.length; cutoff++) { + const output = prefix + header + body.slice(0, cutoff); + assert.equal(capture(output)[stream], prefix + "[TLS message omitted]", `${stream} ticket cutoff ${cutoff}`); + assert.equal(capture(output + "\n" + resumed)[stream], prefix + "[TLS message omitted]\n" + resumed, + `${stream} trace recovery ${cutoff}`); + } + for (let cutoff = 0; cutoff <= session.length; cutoff++) { + const output = prefix + session.slice(0, cutoff); + if (cutoff < "SSL-Session:\n".length) continue; + assert.equal(capture(output)[stream], prefix.trimEnd(), `${stream} session cutoff ${cutoff}`); + } + const verification = " Verify return code: 0 (ok)\n"; + assert.equal(capture(prefix + session + verification + "---\n" + resumed)[stream], + prefix + verification + "---\n" + resumed); + assert.equal(classify(capture(prefix + session + verification), "TLSv1.2", GCM[0]), + execution.status === 0 ? "trusted" : "inconclusive"); + } + } +}); + +test("loopback TLS and alert peers preserve strict refusal and trusted positive behavior", { timeout: 20000 }, async (t) => { + const dir = mkdtempSync(join(tmpdir(), "origin-tls-local-")); + t.after(() => rmSync(dir, { recursive: true, force: true })); + const cert = join(dir, "cert.pem"); + const key = join(dir, "key.pem"); + const generated = spawnSync("openssl", ["req", "-x509", "-newkey", "rsa:2048", "-nodes", "-keyout", key, + "-out", cert, "-days", "1", "-subj", "/CN=localhost", "-addext", "subjectAltName=DNS:localhost"], { timeout: 10000, encoding: "utf8" }); + assert.equal(generated.status, 0, generated.stderr); + const f = fixture(); + probe(["10.42.0.85", "10.42.1.12"], f.run, (row) => f.rows.push(row)); + for (const mode of ["tls", "tls_held", "fatal", "close_notify", "eof", "reset", "silent"]) { + await t.test(mode, async () => { + const worker = new Worker(` + const { parentPort, workerData: d } = require("node:worker_threads"); + const net = require("node:net"); + const tls = require("node:tls"); + const server = d.mode.startsWith("tls") ? tls.createServer({ key: d.key, cert: d.cert, + minVersion: "TLSv1.2", maxVersion: "TLSv1.2", ciphers: d.cipher }, (s) => { + s.on("error", () => {}); + if (d.mode === "tls") s.end(); + }) : net.createServer((s) => { + let input = Buffer.alloc(0); + s.on("error", () => {}); + s.on("data", (b) => { + input = Buffer.concat([input, b]); + if (input.length < 5 || input.length < 5 + input.readUInt16BE(3)) return; + if (d.mode === "silent") return; + if (d.mode === "reset") { s.resetAndDestroy(); return; } + setTimeout(() => s.end(d.mode === "eof" ? Buffer.alloc(0) : + Buffer.from([21, 3, 3, 0, 2, ...(d.mode === "fatal" ? [2, 40] : [1, 0])])), 50); + }); + }); + server.on("tlsClientError", () => {}); + server.listen(0, "127.0.0.1", () => parentPort.postMessage(server.address().port)); + `, { eval: true, workerData: { mode, key: readFileSync(key), cert: readFileSync(cert), cipher: mode === "tls_held" ? CBC.join(":") : GCM[0] } }); + try { + const port = await new Promise((resolve, reject) => { worker.once("message", resolve); worker.once("error", reject); }); + const localArgs = (cipher) => { + const args = f.rows.find((r) => r.kind === "handshake" && r.cipher === cipher).command.slice(1); + for (const [flag, value] of [["-connect", `127.0.0.1:${port}`], ["-servername", "localhost"], + ["-verify_hostname", "localhost"], ["-CAfile", cert]]) args[args.indexOf(flag) + 1] = value; + return args; + }; + for (const cipher of CBC) { + const result = invoke(localArgs(cipher), (command, args, options) => spawnSync(command, args, + { ...options, timeout: mode === "tls_held" ? 500 : mode === "silent" ? 300 : options.timeout })); + assert.equal(classify(result, "TLSv1.2", cipher, true), mode === "tls_held" ? "accepted" : ["tls", "fatal"].includes(mode) ? "refused" : "inconclusive", + JSON.stringify(result)); + if (mode === "tls_held") { + assert.equal(result.error, "ETIMEDOUT"); + assert.equal(result.signal, "SIGKILL"); + assert.ok(result.stdout.includes(`New, TLSv1.2, Cipher is ${cipher}`)); + assert.match(result.stdout, /Verify return code: 0 \(ok\)/); + } + if (mode === "close_notify") { + assert.match(result.stdout, /<<< TLS 1.2, Alert \[length 0002\], warning close_notify\n\s+01 00/); + const summaryOnly = invoke(localArgs(cipher).filter((arg) => !["-ign_eof", "-state", "-msg"].includes(arg))); + assert.equal(summaryOnly.status, 0); + assert.match(summaryOnly.stdout, /SSL handshake has read 7 bytes/); + assert.equal(classify(summaryOnly, "TLSv1.2", cipher, true), "inconclusive"); + } + if (mode === "silent") assert.equal(result.error, "ETIMEDOUT"); + assert.doesNotMatch(result.stdout + result.stderr, /Master-Key|Resumption PSK|TLS session ticket:/); + } + if (mode === "tls") { + const positive = invoke(localArgs(GCM[0])); + assert.equal(classify(positive, "TLSv1.2", GCM[0]), "trusted", JSON.stringify(positive)); + const accepted = invoke([...localArgs(CBC[0]).slice(0, -1), GCM[0]]); + assert.equal(classify(accepted, "TLSv1.2", CBC[0], true), "accepted"); + assert.doesNotMatch(positive.stdout + positive.stderr + accepted.stdout + accepted.stderr, /Master-Key|Resumption PSK|TLS session ticket:/); + } + } finally { await worker.terminate(); } + }); + } +}); 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/pages-production-config.test.mjs b/.github/scripts/pages-production-config.test.mjs index d177ab3b7..e049d4b23 100644 --- a/.github/scripts/pages-production-config.test.mjs +++ b/.github/scripts/pages-production-config.test.mjs @@ -107,7 +107,6 @@ test("renders the imported production settings with the real dashboard entrypoin runInNewContext(readFileSync(output, "utf8"), { window }); assert.equal(window.__WARMBLY_ENV__.API_URL, "production-WARMBLY_API_URL"); assert.equal(window.__WARMBLY_ENV__.TURNSTILE_KEY, "production-WARMBLY_TURNSTILE_KEY"); - assert.equal(window.__WARMBLY_ENV__.GMAIL_OAUTH_CONNECT, "production-WARMBLY_GMAIL_OAUTH_CONNECT"); assert.equal(window.__WARMBLY_ENV__.COMPANY_LOGOS, 'logos "quoted"\\path'); } finally { rmSync(work, { recursive: true, force: true }); diff --git a/.github/scripts/pages-static-assets.mjs b/.github/scripts/pages-static-assets.mjs new file mode 100644 index 000000000..b5d1de4b4 --- /dev/null +++ b/.github/scripts/pages-static-assets.mjs @@ -0,0 +1,88 @@ +import { appendFileSync, cpSync, existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs"; +import { resolve, join } from "node:path"; +import { fileURLToPath } from "node:url"; +import { deploymentMatrix } from "./pages-projects.mjs"; + +export function staticAssetsMatrix(projects, targets) { + const pages = deploymentMatrix(projects).include; + const configured = JSON.parse(targets || "[]"); + if (!Array.isArray(configured) || configured.length > pages.length) throw new Error("Invalid static asset targets"); + const seenProjects = new Set(); + const seenWorkers = new Set(); + const seenDomains = new Set(); + return { include: configured.map((target) => { + if (!target || Object.keys(target).some((key) => !["project", "worker", "domains"].includes(key))) throw new Error("Invalid static asset target"); + const page = pages.find((entry) => entry.project === target.project); + if (!page || typeof target.worker !== "string" || !/^[a-z0-9][a-z0-9-]{0,62}$/.test(target.worker)) throw new Error("Unknown project or invalid Worker name"); + if (!Array.isArray(target.domains) || target.domains.length > 10) throw new Error("Explicit domains required"); + for (const domain of target.domains) { + if (typeof domain !== "string" || domain.length > 253 || !/^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/.test(domain) || seenDomains.has(domain)) throw new Error("Invalid or duplicate custom domain"); + seenDomains.add(domain); + } + if (seenProjects.has(target.project) || seenWorkers.has(target.worker)) throw new Error("Duplicate static asset target"); + seenProjects.add(target.project); + seenWorkers.add(target.worker); + return { ...page, worker: target.worker, domains: target.domains }; + }) }; +} + +export function prepareStaticAssets({ target, sourceRoot, destination, sourceSha, release }) { + if (!/^[a-f0-9]{40}$/.test(sourceSha) || !/^v\d+\.\d+\.\d+$/.test(release)) throw new Error("Exact release identity required"); + const output = resolve(sourceRoot, target.output_dir); + const dest = resolve(destination); + if (existsSync(dest)) throw new Error("Use a new artifact directory"); + let files = 0; + function check(path) { + const stat = lstatSync(path); + if (stat.isSymbolicLink()) throw new Error("Static artifacts must not contain symlinks"); + if (stat.isDirectory()) { + for (const entry of readdirSync(path)) check(join(path, entry)); + } else if (!stat.isFile() || stat.size > 25 * 1024 * 1024 || ++files > 19999) { + throw new Error("Artifact exceeds Workers Free asset limits"); + } + } + check(output); + const isRegularFile = (name) => existsSync(join(output, name)) && lstatSync(join(output, name)).isFile(); + if (!isRegularFile("index.html") || !isRegularFile("_headers")) throw new Error("Frontend index and response headers required"); + if (existsSync(join(output, "_worker.js")) || existsSync(join(output, "_routes.json"))) throw new Error("Only static artifacts are supported"); + mkdirSync(dest, { recursive: true }); + cpSync(output, join(dest, "assets"), { recursive: true }); + if (target.app === "admin") { + const redirects = join(dest, "assets", "_redirects"); + if (existsSync(redirects)) { + const rules = readFileSync(redirects, "utf8").split("\n").map((line) => line.trim()).filter((line) => line && !line.startsWith("#")); + if (rules.length !== 1 || !/^\/\*\s+\/index\.html\s+200$/.test(rules[0])) throw new Error("Review changed admin redirect rules before publishing static assets"); + // The asset platform's SPA mode replaces the Pages-only catch-all rewrite. + rmSync(redirects); + } + } + mkdirSync(join(dest, "assets", ".well-known"), { recursive: true }); + writeFileSync(join(dest, "assets", ".well-known", "warmbly-release.json"), JSON.stringify({ release, sourceSha, app: target.app, project: target.project }) + "\n"); + const config = { + name: target.worker, + compatibility_date: "2025-10-11", + workers_dev: false, + preview_urls: false, + assets: { directory: "./assets", html_handling: "auto-trailing-slash", not_found_handling: target.app === "admin" ? "single-page-application" : "404-page" }, + routes: target.domains.map((pattern) => ({ pattern, custom_domain: true })), + }; + writeFileSync(join(dest, "wrangler.json"), JSON.stringify(config, null, 2) + "\n"); + return config; +} + +if (process.argv[1] === fileURLToPath(import.meta.url)) { + try { + const matrix = staticAssetsMatrix(process.env.CLOUDFLARE_PAGES_PROJECTS, process.env.CLOUDFLARE_STATIC_ASSETS_TARGETS); + if (["prepare", "prepare-if-configured"].includes(process.argv[2])) { + const target = matrix.include.find((entry) => entry.project === process.env.CLOUDFLARE_PAGES_PROJECT_NAME); + if (!target && process.argv[2] === "prepare") throw new Error("Project is not configured for static assets"); + if (process.env.GITHUB_OUTPUT) appendFileSync(process.env.GITHUB_OUTPUT, `enabled=${Boolean(target)}\n`); + if (target) prepareStaticAssets({ target, sourceRoot: process.cwd(), destination: process.env.STATIC_ASSETS_ARTIFACT_DIR, sourceSha: process.env.SOURCE_SHA, release: process.env.RELEASE_TAG }); + } else { + appendFileSync(process.env.GITHUB_OUTPUT, `matrix=${JSON.stringify(matrix)}\nenabled=${matrix.include.length > 0}\n`); + } + } catch { + console.error("::error::Invalid static asset configuration or artifact. Require unique configured Pages projects, Worker names, explicit domains and an exact release identity."); + process.exitCode = 1; + } +} diff --git a/.github/scripts/pages-static-assets.test.mjs b/.github/scripts/pages-static-assets.test.mjs new file mode 100644 index 000000000..1e10a23be --- /dev/null +++ b/.github/scripts/pages-static-assets.test.mjs @@ -0,0 +1,86 @@ +import assert from "node:assert/strict"; +import { cpSync, existsSync, mkdtempSync, mkdirSync, readFileSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { test } from "node:test"; +import { staticAssetsMatrix, prepareStaticAssets } from "./pages-static-assets.mjs"; + +const projects = JSON.stringify([{ app: "web", project: "dashboard" }, { app: "admin", project: "admin" }, { app: "docs", project: "docs" }]); +const configured = [{ project: "dashboard", worker: "warmbly-dashboard", domains: ["stage.warmbly.com"] }]; +const sha = "a".repeat(40); + +test("static assets are disabled unless exact Pages projects are configured", () => { + assert.deepEqual(staticAssetsMatrix(projects), { include: [] }); + const target = staticAssetsMatrix(projects, JSON.stringify(configured)).include[0]; + assert.equal(target.output_dir, "web/dist"); + assert.equal(target.environment, "dashboard-production"); + assert.equal(target.worker, "warmbly-dashboard"); + assert.deepEqual(target.domains, ["stage.warmbly.com"]); +}); + +test("rejects unknown projects, paths, domains, duplicate mappings and overrides", () => { + for (const value of [null, {}, [null], [{ ...configured[0], project: "unknown" }], [{ ...configured[0], output_dir: "/tmp" }], [{ ...configured[0], worker: "../worker" }], [{ ...configured[0], domains: ["*.warmbly.com"] }], [{ ...configured[0], domains: ["stage.warmbly.com/path"] }], [{ ...configured[0], domains: ["stage.warmbly.com", "stage.warmbly.com"] }], [configured[0], configured[0]], [configured[0], { project: "admin", worker: "admin", domains: ["stage.warmbly.com"] }]]) { + assert.throws(() => staticAssetsMatrix(projects, JSON.stringify(value))); + } +}); + +function fixture(app, fn) { + const root = mkdtempSync(join(tmpdir(), "static-assets-")); + try { + const target = staticAssetsMatrix(projects, JSON.stringify([{ project: app === "web" ? "dashboard" : app, worker: "fixture", domains: [] }])).include[0]; + const output = join(root, target.output_dir); + mkdirSync(output, { recursive: true }); + writeFileSync(join(output, "index.html"), "

Warmbly fixture

"); + for (const name of ["_headers", "_redirects", "404.html"]) { + try { cpSync(new URL(`../../${app}/public/${name}`, import.meta.url), join(output, name)); } catch (error) { if (error.code !== "ENOENT") throw error; } + } + fn({ root, target, output, destination: join(root, "artifact") }); + } finally { rmSync(root, { recursive: true, force: true }); } +} + +test("publishes only assets and preserves exact route/header/404 files and release identity", () => { + fixture("web", ({ root, target, output, destination }) => { + const config = prepareStaticAssets({ target, sourceRoot: root, destination, sourceSha: sha, release: "v0.6.74" }); + assert.equal(config.main, undefined); + assert.equal(config.workers_dev, false); + assert.equal(config.preview_urls, false); + assert.equal(config.assets.not_found_handling, "404-page"); + assert.deepEqual(config.routes, []); + for (const name of ["index.html", "_headers", "_redirects", "404.html"]) assert.deepEqual(readFileSync(join(output, name)), readFileSync(join(destination, "assets", name))); + assert.deepEqual(JSON.parse(readFileSync(join(destination, "assets/.well-known/warmbly-release.json"))), { release: "v0.6.74", sourceSha: sha, app: "web", project: "dashboard" }); + assert.throws(() => prepareStaticAssets({ target, sourceRoot: root, destination, sourceSha: sha, release: "v0.6.74" })); + }); +}); + +test("admin preserves its SPA fallback and domains are explicit custom-domain bindings", () => { + fixture("admin", ({ root, target, destination }) => { + const config = prepareStaticAssets({ target: { ...target, domains: ["admin-stage.warmbly.com"] }, sourceRoot: root, destination, sourceSha: sha, release: "v0.6.74" }); + assert.equal(config.assets.not_found_handling, "single-page-application"); + assert.equal(existsSync(join(destination, "assets", "_redirects")), false); + assert.deepEqual(config.routes, [{ pattern: "admin-stage.warmbly.com", custom_domain: true }]); + }); +}); + +test("refuses unpinned releases, executable Pages functions and symlink artifacts", () => { + for (const kind of ["sha", "tag", "function", "symlink"]) fixture("web", ({ root, target, output, destination }) => { + if (kind === "function") writeFileSync(join(output, "_worker.js"), "export default {}"); + if (kind === "symlink") symlinkSync("/etc/hosts", join(output, "outside")); + assert.throws(() => prepareStaticAssets({ target, sourceRoot: root, destination, sourceSha: kind === "sha" ? "main" : sha, release: kind === "tag" ? "latest" : "v0.6.74" })); + }); +}); + +test("changed admin redirect behavior requires explicit review", () => { + fixture("admin", ({ root, target, output, destination }) => { + writeFileSync(join(output, "_redirects"), "/old /new 301\n"); + assert.throws(() => prepareStaticAssets({ target, sourceRoot: root, destination, sourceSha: sha, release: "v0.6.74" })); + }); +}); + +test("requires regular frontend entrypoint and response header files", () => { + for (const name of ["index.html", "_headers"]) fixture("web", ({ root, target, output, destination }) => { + rmSync(join(output, name)); + mkdirSync(join(output, name)); + assert.throws(() => prepareStaticAssets({ target, sourceRoot: root, destination, sourceSha: sha, release: "v0.6.74" }), /Frontend index and response headers required/); + assert.equal(existsSync(destination), false); + }); +}); diff --git a/.github/scripts/runtime-tls-recovery-archive.sh b/.github/scripts/runtime-tls-recovery-archive.sh new file mode 100755 index 000000000..ed233c2fb --- /dev/null +++ b/.github/scripts/runtime-tls-recovery-archive.sh @@ -0,0 +1,23 @@ +#!/usr/bin/env bash +# Preserve recovery raw evidence only in the dedicated private diagnostic prefix. +set -euo pipefail +[ "${GITHUB_ACTIONS:-}" = true ] && [ "${GITHUB_REPOSITORY:-}" = warmbly/warmbly ] && + [ "${GITHUB_REF:-}" = refs/heads/main ] && [ "${GITHUB_RUN_ATTEMPT:-}" = 1 ] && + [[ "${GITHUB_RUN_ID:-}" =~ ^[1-9][0-9]*$ ]] || exit 1 +phase=${1:?} +[[ "$phase" = plan || "$phase" = apply || "$phase" = verify ]] +: "${WORK:?}" +[ -d "$WORK" ] && [ ! -e "$WORK.evidence.tgz" ] +umask 077 +aws sts get-caller-identity --region us-east-1 >"$WORK/archive-identity.json" +jq -e '.Account == "925323749693" and (.Arn | test("^arn:aws:sts::925323749693:assumed-role/warmbly-production-tls-recovery-evidence/[^/]+$"))' \ + "$WORK/archive-identity.json" >/dev/null +tar -czf "$WORK.evidence.tgz" -C "$WORK" . +checksum=$(openssl dgst -sha256 -binary "$WORK.evidence.tgz" | openssl base64 -A) +aws s3api put-object --region us-east-1 --bucket warmbly-terraform-use1-925323749693 \ + --key "warmbly/production/diagnostics/runtime-tls-recovery/$GITHUB_RUN_ID/1/$phase.tgz" \ + --expected-bucket-owner 925323749693 --server-side-encryption AES256 --if-none-match '*' \ + --checksum-algorithm SHA256 --checksum-sha256 "$checksum" --body "$WORK.evidence.tgz" >"$WORK.evidence-metadata.json" +jq -e --arg checksum "$checksum" '.ServerSideEncryption == "AES256" and .ChecksumSHA256 == $checksum and + (.VersionId | type == "string" and length > 0 and . != "null")' "$WORK.evidence-metadata.json" >/dev/null +echo 'Full recovery evidence preserved in the private versioned diagnostic object' diff --git a/.github/scripts/runtime-tls-recovery-archive.test.sh b/.github/scripts/runtime-tls-recovery-archive.test.sh new file mode 100755 index 000000000..e62c0cd13 --- /dev/null +++ b/.github/scripts/runtime-tls-recovery-archive.test.sh @@ -0,0 +1,37 @@ +#!/usr/bin/env bash +set -euo pipefail +cd "$(dirname "$0")/../.." +work=$(mktemp -d) +trap 'rm -rf "$work"' EXIT +mkdir "$work/bin" +cat >"$work/bin/aws" <<'SH' +#!/usr/bin/env bash +set -euo pipefail +if [ "$1 $2" = 'sts get-caller-identity' ]; then + jq -n --arg mode "${MODE:-}" '{Account:"925323749693",Arn:("arn:aws:sts::925323749693:assumed-role/"+(if $mode=="role" then "other" else "warmbly-production-tls-recovery-evidence" end)+"/fixture")}' + exit +fi +[ "$1 $2" = 's3api put-object' ] +[[ "$*" == *'--expected-bucket-owner 925323749693'* && "$*" == *'--server-side-encryption AES256'* && "$*" == *'--if-none-match *'* ]] +[[ "$*" == *'warmbly/production/diagnostics/runtime-tls-recovery/999/1/plan.tgz'* ]] +checksum= body= +while [ "$#" -gt 0 ]; do + case "$1" in --checksum-sha256) checksum=$2; shift 2 ;; --body) body=$2; shift 2 ;; *) shift ;; esac +done +[ "$checksum" = "$(openssl dgst -sha256 -binary "$body" | openssl base64 -A)" ] +tar -tzf "$body" | grep -Fx './full-raw.json' >/dev/null +if [ "${MODE:-}" = upload ]; then exit 1; fi +jq -n --arg checksum "$checksum" --arg mode "${MODE:-}" '{VersionId:"evidence-version",ServerSideEncryption:"AES256",ChecksumSHA256:(if $mode=="checksum" then "other" else $checksum end)}' +SH +chmod +x "$work/bin/aws" +export PATH="$work/bin:$PATH" GITHUB_ACTIONS=true GITHUB_REPOSITORY=warmbly/warmbly GITHUB_REF=refs/heads/main GITHUB_RUN_ATTEMPT=1 GITHUB_RUN_ID=999 +guard=.github/scripts/runtime-tls-recovery-archive.sh +for mode in good role upload checksum; do + mkdir "$work/$mode" + printf '{"raw":"private fixture"}\n' >"$work/$mode/full-raw.json" + if [ "$mode" = good ]; then WORK="$work/$mode" bash "$guard" plan + elif WORK="$work/$mode" MODE=$mode bash "$guard" plan 2>/dev/null; then echo "Archive accepted $mode" >&2; exit 1; fi +done +if WORK="$work/good" bash "$guard" plan 2>/dev/null; then echo 'Archive overwrote prior evidence' >&2; exit 1; fi +if WORK="$work/unused" GITHUB_RUN_ATTEMPT=2 bash "$guard" plan 2>/dev/null; then echo 'Archive accepted a rerun' >&2; exit 1; fi +echo 'Private evidence archive identity, prefix, encryption, integrity and overwrite checks passed' diff --git a/.github/scripts/runtime-tls-recovery-execute.sh b/.github/scripts/runtime-tls-recovery-execute.sh new file mode 100755 index 000000000..52c05df0b --- /dev/null +++ b/.github/scripts/runtime-tls-recovery-execute.sh @@ -0,0 +1,132 @@ +#!/usr/bin/env bash +# Keep partial cleanup separate from normal route, drain and ON transitions. +set -euo pipefail +scripts=$(cd "$(dirname "$0")" && pwd) + +check_contract() { + bash "$scripts/runtime-tls-recovery-inputs.sh" check-contract "$1" + jq -e ' + .schemaVersion == 1 and .repository == "warmbly/warmbly" and .release.tag == .snapshot.releaseTag and + (.release.imagesSha256 | type == "string" and test("^[a-f0-9]{64}$")) and + (.planChangesSha256 | type == "string" and test("^[a-f0-9]{64}$")) + ' "$1" >/dev/null || { echo 'Recovery must bind the current release artifact and reviewed complete plan changes' >&2; return 1; } +} + +check_context() { + if [ "${GITHUB_ACTIONS:-}" = true ] && [ "${GITHUB_REPOSITORY:-}" = warmbly/warmbly ] && + [ "${GITHUB_REF:-}" = refs/heads/main ] && [ "${GITHUB_EVENT_NAME:-}" = workflow_dispatch ] && + [ "${GITHUB_WORKFLOW_REF:-}" = warmbly/warmbly/.github/workflows/runtime-tls-recovery.yml@refs/heads/main ] && + [ "${GITHUB_RUN_ATTEMPT:-}" = 1 ] && [[ "${GITHUB_RUN_ID:-}" =~ ^[1-9][0-9]*$ ]]; then + [ "${GITHUB_SHA:?}" = "$(git rev-parse HEAD)" ] + return + fi + echo 'Recovery execution requires a new protected main workflow run; reruns are refused' >&2 + return 1 +} + +check_approval_environment() { + gh api repos/warmbly/warmbly/environments/aws-infrastructure-approval | + jq -e '.can_admins_bypass == false and + any(.protection_rules[]; .type == "required_reviewers" and .prevent_self_review == true and (.reviewers | length > 0))' >/dev/null || { + echo 'Recovery requires a separate protected reviewer without self-review or administrator bypass' >&2; return 1; + } +} + +check_final_state() { + jq -e --slurpfile before "$2" ' + .version == 4 and .lineage == $before[0].lineage and + (.serial | type == "number" and floor == .) and .serial > $before[0].serial and + ([.resources[] | select(.mode == "managed" and .type == "aws_lb_target_group" and .name == "service")] | length == 0) and + (.resources | sort_by([.module,.mode,.type,.name])) == + ($before[0].resources | map(select((.mode == "managed" and .type == "aws_lb_target_group" and .name == "service") | not)) | sort_by([.module,.mode,.type,.name])) + ' "$1" >/dev/null || { echo 'Post-cleanup state must preserve all other reviewed resources' >&2; return 1; } +} + +prepare() { + : "${WORK:?}" "${CONTRACT_KEY:?}" "${CONTRACT_VERSION:?}" "${CONTRACT_SHA256:?}" + [[ "$CONTRACT_KEY" =~ ^warmbly/production/vars/runtime-tls-recovery/[a-z0-9][a-z0-9-]{1,63}\.contract\.json$ ]] + [[ "$CONTRACT_SHA256" =~ ^[a-f0-9]{64}$ && "$CONTRACT_VERSION" != null && -n "$CONTRACT_VERSION" && "$CONTRACT_VERSION" != *$'\n'* ]] + umask 077 + mkdir "$WORK" + export AWS_PAGER="" + aws sts get-caller-identity --region us-east-1 >"$WORK/account.json" + jq -e '.Account == "925323749693"' "$WORK/account.json" >/dev/null + aws s3api get-object --region us-east-1 --bucket warmbly-terraform-use1-925323749693 --key "$CONTRACT_KEY" \ + --version-id "$CONTRACT_VERSION" --expected-bucket-owner 925323749693 "$WORK/contract.json" >"$WORK/contract-metadata.json" + jq -e --arg version "$CONTRACT_VERSION" '.VersionId == $version and .DeleteMarker != true and + (.ServerSideEncryption == "AES256" or .ServerSideEncryption == "aws:kms")' "$WORK/contract-metadata.json" >/dev/null + [ "$(sha256sum "$WORK/contract.json" | cut -d' ' -f1)" = "$CONTRACT_SHA256" ] + check_contract "$WORK/contract.json" + check_approval_environment + bash "$scripts/runtime-tls-recovery-lineage.sh" collect "$WORK/contract.json" "$WORK/lineage" . >"$WORK/lineage.log" 2>&1 + local input_action=collect + if [ "$1" = verify ]; then input_action=collect-archived; fi + bash "$scripts/runtime-tls-recovery-inputs.sh" "$input_action" "$WORK/contract.json" "$WORK/inputs" >"$WORK/inputs.log" 2>&1 + local release key digest + release=$(jq -r '.release.tag' "$WORK/contract.json") + gh release view "$release" --repo warmbly/warmbly --json tagName,isDraft,isPrerelease >"$WORK/release.json" + jq -e --arg release "$release" '.tagName == $release and .isDraft == false and .isPrerelease == false' "$WORK/release.json" >/dev/null + gh release download "$release" --repo warmbly/warmbly --pattern images.json --dir "$WORK/inputs" + [ "$(sha256sum "$WORK/inputs/images.json" | cut -d' ' -f1)" = "$(jq -r '.release.imagesSha256' "$WORK/contract.json")" ] + jq -e --arg release "$release" '.tag == $release and .registry == "ghcr.io/warmbly/warmbly"' "$WORK/inputs/images.json" >/dev/null + for key in backend backend-kafka consumer consumer-kafka worker worker-kafka forms tracking tracking-kafka realtime; do + digest=$(jq -er --arg key "$key" '.images[$key] | select(type == "string" and test("^sha256:[a-f0-9]{64}$"))' "$WORK/inputs/images.json") + gh attestation verify "oci://ghcr.io/warmbly/warmbly/${key%-kafka}@$digest" --repo warmbly/warmbly \ + --signer-workflow warmbly/warmbly/.github/workflows/release.yml --source-ref "refs/tags/$release" \ + --source-digest "$(jq -r '.release.source' "$WORK/contract.json")" >>"$WORK/provenance.log" 2>&1 + done +} + +verify_final() { + aws s3api get-object --region us-east-1 --bucket warmbly-terraform-use1-925323749693 \ + --key warmbly/production/runtime.tfstate --expected-bucket-owner 925323749693 "$WORK/final-state.json" >"$WORK/final-state-metadata.json" + jq -e '.DeleteMarker != true and (.VersionId | type == "string" and length > 0 and . != "null") and + (.ServerSideEncryption == "AES256" or .ServerSideEncryption == "aws:kms")' "$WORK/final-state-metadata.json" >/dev/null + check_final_state "$WORK/final-state.json" "$WORK/inputs/state.json" + bash "$scripts/runtime-tls-recovery-live.sh" collect-final "$WORK/contract.json" "$WORK/inputs" "$WORK/final-live" >"$WORK/final-live.log" 2>&1 + aws s3api head-object --region us-east-1 --bucket warmbly-terraform-use1-925323749693 \ + --key warmbly/production/runtime.tfstate --expected-bucket-owner 925323749693 >"$WORK/final-state-head.json" + jq -e --slurpfile metadata "$WORK/final-state-metadata.json" '.VersionId == $metadata[0].VersionId' "$WORK/final-state-head.json" >/dev/null +} + +main() { + local action=${1:-} + if [ "$action" = check-contract ]; then check_contract "${2:?}"; return; fi + if [ "$action" = check-final-state ]; then check_final_state "${2:?}" "${3:?}"; return; fi + case "$action" in plan|apply|verify) ;; *) echo 'Unknown partial TLS recovery action' >&2; return 1 ;; esac + check_context + prepare "$action" + if [ "$action" = verify ]; then verify_final; echo 'Final recovery state and effective live checks passed'; return; fi + bash "$scripts/runtime-tls-recovery-live.sh" collect "$WORK/contract.json" "$WORK/inputs" "$WORK/live" >"$WORK/live.log" 2>&1 + local dir=deploy/terraform/aws/runtime changes digest + terraform -chdir="$dir" init -input=false -no-color -backend-config=bucket=warmbly-terraform-use1-925323749693 >"$WORK/terraform.log" 2>&1 + terraform -chdir="$dir" plan -input=false -no-color -lock-timeout=5m -var-file="$WORK/inputs/snapshot.json" \ + -var=state_bucket=warmbly-terraform-use1-925323749693 -target=aws_lb_target_group.service \ + -out="$WORK/recovery.tfplan" >>"$WORK/terraform.log" 2>&1 + terraform -chdir="$dir" show -json "$WORK/recovery.tfplan" >"$WORK/plan.json" + bash "$scripts/runtime-tls-recovery.sh" check-plan "$WORK/plan.json" "$WORK/contract.json" + changes=$(jq -cS '{resource_changes:(.resource_changes | sort_by(.address)),resource_drift:(.resource_drift // [] | sort_by(.address))}' \ + "$WORK/plan.json" | sha256sum | cut -d' ' -f1) + [ "$changes" = "$(jq -r '.planChangesSha256' "$WORK/contract.json")" ] || { + echo 'The complete recovery changes differ from the privately reviewed plan; prepare a new contract' >&2; return 1; + } + digest=$(jq -cnS --arg contract "$CONTRACT_SHA256" --arg source "$GITHUB_SHA" --arg changes "$changes" \ + '{contract:$contract,workflowSource:$source,changes:$changes}' | sha256sum | cut -d' ' -f1) + aws s3api head-object --region us-east-1 --bucket warmbly-terraform-use1-925323749693 \ + --key warmbly/production/runtime.tfstate --expected-bucket-owner 925323749693 >"$WORK/preapply-state-head.json" + jq -e --slurpfile contract "$WORK/contract.json" '.VersionId == $contract[0].state.versionId' "$WORK/preapply-state-head.json" >/dev/null + if [ "$action" = plan ]; then + printf 'digest=%s\nrelease=%s\n' "$digest" "$(jq -r '.release.tag' "$WORK/contract.json")" >>"${GITHUB_OUTPUT:?}" + printf 'Partial TLS cleanup: exactly four reviewed HTTP target-group deletions.\n\nContract SHA-256: %s\n\nComplete changes SHA-256: %s\n\nApproval digest: %s\n\nReview the matching complete private plan before approving.\n' \ + "$CONTRACT_SHA256" "$changes" "$digest" >>"${GITHUB_STEP_SUMMARY:?}" + return + fi + [ "$digest" = "${APPROVED_DIGEST:?}" ] || { echo 'Recovery approval digest changed; a new reviewed run is required' >&2; return 1; } + bash "$scripts/runtime-tls-recovery-live.sh" collect "$WORK/contract.json" "$WORK/inputs" "$WORK/preapply-live" >"$WORK/preapply-live.log" 2>&1 + terraform -chdir="$dir" apply -input=false -no-color -lock-timeout=5m "$WORK/recovery.tfplan" >>"$WORK/terraform.log" 2>&1 || { + echo 'Partial cleanup failed; inspect private state before preparing any new recovery contract' >&2; return 1; + } + verify_final + echo 'Reviewed partial cleanup and effective checks passed; attested same-release redeploy is still required' +} +main "$@" diff --git a/.github/scripts/runtime-tls-recovery-execute.test.sh b/.github/scripts/runtime-tls-recovery-execute.test.sh new file mode 100755 index 000000000..2cf4d73f7 --- /dev/null +++ b/.github/scripts/runtime-tls-recovery-execute.test.sh @@ -0,0 +1,166 @@ +#!/usr/bin/env bash +set -euo pipefail +cd "$(dirname "$0")/../.." +work=$(mktemp -d) +trap 'rm -rf "$work"' EXIT +mkdir -p "$work/repository/.github/scripts" "$work/bin" +cp .github/scripts/runtime-tls-recovery{,-inputs,-lineage,-execute}.sh "$work/repository/.github/scripts/" +git -C "$work/repository" init -q +git -C "$work/repository" config user.name 'Recovery fixture' +git -C "$work/repository" config user.email 'fixture@example.invalid' +git -C "$work/repository" commit -qm 'feat: establish recovery drain fixture' --allow-empty +drain=$(git -C "$work/repository" rev-parse HEAD) +git -C "$work/repository" commit -qm 'feat: establish recovery ON fixture' --allow-empty +on=$(git -C "$work/repository" rev-parse HEAD) +git -C "$work/repository" commit -qm 'feat: establish recovery release fixture' --allow-empty +release=$(git -C "$work/repository" rev-parse HEAD) +git -C "$work/repository" tag v1.2.3 +jq -n --arg digest "sha256:$(printf fixture | sha256sum | cut -d' ' -f1)" \ + -f .github/scripts/runtime-tls-recovery-live.fixture.jq >"$work/fixture.json" +jq '.state' "$work/fixture.json" >"$work/state.json" +jq '.state | .serial+=1 | .resources |= map(select(.type != "aws_lb_target_group" or .name != "service"))' "$work/fixture.json" >"$work/final-state.json" +jq '.vars' "$work/fixture.json" >"$work/snapshot.json" +jq '.images | .images += {"backend-kafka":.images.backend,"consumer-kafka":.images.consumer,"worker":.images.backend,"worker-kafka":.images.backend,"tracking-kafka":.images.tracking}' \ + "$work/fixture.json" >"$work/images.json" +jq '.baseline | {resource_changes:[.httpGroups[] | {address:("aws_lb_target_group.service[\""+(.TargetGroupName|ltrimstr("warmbly-production-"))+"\"]"), + change:{actions:["delete"],after:null,before:{arn:.TargetGroupArn,id:.TargetGroupArn,name:.TargetGroupName,protocol:.Protocol,port:.Port,vpc_id:.VpcId}}}]}' \ + "$work/fixture.json" >"$work/plan.json" +changes=$(jq -cS '{resource_changes:(.resource_changes|sort_by(.address)),resource_drift:[]}' "$work/plan.json" | sha256sum | cut -d' ' -f1) +jq --arg drain "$drain" --arg on "$on" --arg release "$release" --arg changes "$changes" \ + --arg state "$(sha256sum "$work/state.json" | cut -d' ' -f1)" --arg vars "$(sha256sum "$work/snapshot.json" | cut -d' ' -f1)" \ + --arg images "$(sha256sum "$work/images.json" | cut -d' ' -f1)" ' + .baseline + {schemaVersion:1,repository:"warmbly/warmbly",bucket:"warmbly-terraform-use1-925323749693", + release:{tag:"v1.2.3",source:$release,runId:101,attempt:1,imagesSha256:$images}, + drain:{tag:"v1.2.2",source:$drain,runId:102,attempt:1},failedOn:{tag:"v1.2.2",source:$on,runId:103,attempt:1},planChangesSha256:$changes} | + .state += {key:"warmbly/production/runtime.tfstate",sha256:$state} | + .snapshot += {key:"warmbly/production/vars/runtime-tls-recovery/fixture.tfvars.json",versionId:"vars-version",sha256:$vars}' \ + "$work/fixture.json" >"$work/contract.json" +jq ' + def run($path;$event;$branch;$conclusion): {id:.runId,run_attempt:.attempt,head_sha:.source,repository:{full_name:"warmbly/warmbly"}, + path:$path,event:$event,head_branch:$branch,status:"completed",conclusion:$conclusion}; + {runs:{release:(.release|run(".github/workflows/release.yml";"push";.tag;"success")), + drain:(.drain|run(".github/workflows/runtime-tls.yml";"workflow_dispatch";"main";"success")+{display_title:("Runtime TLS drain "+.tag)}), + failedOn:(.failedOn|run(".github/workflows/runtime-tls.yml";"workflow_dispatch";"main";"failure")+{display_title:("Runtime TLS on "+.tag)})}, + failedOnJobs:[{id:1,run_id:103,run_attempt:1,status:"completed",name:"apply",conclusion:"success"}, + {id:2,run_id:103,run_attempt:1,status:"completed",name:"redeploy / fixture",conclusion:"failure"}]}' \ + "$work/contract.json" >"$work/lineage.json" +cat >"$work/repository/.github/scripts/runtime-tls-recovery-live.sh" <<'SH' +#!/usr/bin/env bash +set -euo pipefail +echo "live $1" >>"$FIXTURES/requests.log" +[ "${MODE:-}" != live ] || exit 1 +mkdir "$4" +echo '{}' >"$4/live.json" +SH +cat >"$work/bin/aws" <<'SH' +#!/usr/bin/env bash +set -euo pipefail +echo "aws $*" >>"$FIXTURES/requests.log" +service=$1 operation=$2 +shift 2 +key= version= owner= bucket= region= output= +while [ "$#" -gt 0 ]; do + case "$1" in + --key) key=$2; shift 2 ;; --version-id) version=$2; shift 2 ;; --expected-bucket-owner) owner=$2; shift 2 ;; + --region) region=$2; shift 2 ;; --bucket) bucket=$2; shift 2 ;; *) output=$1; shift ;; + esac +done +[ "$region" = us-east-1 ] +case "$service $operation" in + 'sts get-caller-identity') echo '{"Account":"925323749693"}' ;; + 's3api get-object') + [ "$owner" = 925323749693 ] && [ "$bucket" = warmbly-terraform-use1-925323749693 ] + case "$key" in + */fixture.contract.json) kind=contract ;; + */fixture.tfvars.json) kind=snapshot ;; + */runtime.tfstate) kind=state ;; + *) exit 1 ;; + esac + if [ -z "$version" ]; then kind=final-state; version=final-version; fi + cp "$FIXTURES/$kind.json" "$output" + jq -n --arg version "$version" '{VersionId:$version,ServerSideEncryption:"AES256"}' ;; + 's3api head-object') + version=state-version + if [ -e "$FIXTURES/applied" ] || [ "${MODE:-}" = advanced ]; then version=final-version; fi + jq -n --arg version "$version" '{VersionId:$version}' ;; + *) exit 1 ;; +esac +SH +cat >"$work/bin/gh" <<'SH' +#!/usr/bin/env bash +set -euo pipefail +echo "gh $*" >>"$FIXTURES/requests.log" +case "$1 $2" in + 'api repos/warmbly/warmbly/environments/aws-infrastructure-approval') + jq -n --arg mode "${MODE:-}" '{can_admins_bypass:($mode=="bypass"),protection_rules:[{type:"required_reviewers",prevent_self_review:($mode!="self-review"),reviewers:[{type:"User"}]}]}' ;; + 'api repos/warmbly/warmbly/actions/runs/101/attempts/1') jq '.runs.release' "$FIXTURES/lineage.json" ;; + 'api repos/warmbly/warmbly/actions/runs/102/attempts/1') jq '.runs.drain' "$FIXTURES/lineage.json" ;; + 'api repos/warmbly/warmbly/actions/runs/103/attempts/1') jq '.runs.failedOn' "$FIXTURES/lineage.json" ;; + 'api repos/warmbly/warmbly/actions/runs/103/attempts/1/jobs?per_page=100') jq '[{total_count:2,jobs:.failedOnJobs}]' "$FIXTURES/lineage.json" ;; + 'release view') echo '{"tagName":"v1.2.3","isDraft":false,"isPrerelease":false}' ;; + 'release download') + while [ "$1" != --dir ]; do shift; done + cp "$FIXTURES/images.json" "$2/images.json" + if [ "${MODE:-}" = artifact ]; then printf '\n' >>"$2/images.json"; fi ;; + 'attestation verify') [ "${MODE:-}" != provenance ] ;; + *) exit 1 ;; +esac +SH +cat >"$work/bin/terraform" <<'SH' +#!/usr/bin/env bash +set -euo pipefail +echo "terraform $*" >>"$FIXTURES/requests.log" +case "$2" in + init) ;; + plan) [[ "$*" == *'-target=aws_lb_target_group.service'* && "$*" != *'-target=aws_ecs'* ]] ;; + show) + case "${MODE:-}" in + scope) jq '.resource_changes|=.[1:]' "$FIXTURES/plan.json" ;; + changes) jq '.resource_changes[0].change.before.tags={new:"tag"}' "$FIXTURES/plan.json" ;; + *) cat "$FIXTURES/plan.json" ;; + esac ;; + apply) [ "${MODE:-}" != apply-failure ] && touch "$FIXTURES/applied" ;; + *) exit 1 ;; +esac +SH +chmod +x "$work/bin/"* +export FIXTURES="$work" PATH="$work/bin:$PATH" +export GITHUB_ACTIONS=true GITHUB_REPOSITORY=warmbly/warmbly GITHUB_REF=refs/heads/main GITHUB_EVENT_NAME=workflow_dispatch +export GITHUB_WORKFLOW_REF=warmbly/warmbly/.github/workflows/runtime-tls-recovery.yml@refs/heads/main +export GITHUB_RUN_ATTEMPT=1 GITHUB_RUN_ID=999 GITHUB_SHA="$release" +export CONTRACT_KEY=warmbly/production/vars/runtime-tls-recovery/fixture.contract.json CONTRACT_VERSION=contract-version +CONTRACT_SHA256=$(sha256sum "$work/contract.json" | cut -d' ' -f1) +export CONTRACT_SHA256 +export GITHUB_OUTPUT="$work/output" GITHUB_STEP_SUMMARY="$work/summary" +guard="$work/repository/.github/scripts/runtime-tls-recovery-execute.sh" +cd "$work/repository" +WORK="$work/plan" bash "$guard" plan +approved=$(sed -n 's/^digest=//p' "$GITHUB_OUTPUT") +[ -n "$approved" ] +for mode in bypass self-review artifact provenance live advanced scope changes; do + : >"$work/requests.log" + if WORK="$work/$mode" MODE=$mode APPROVED_DIGEST="$approved" bash "$guard" apply 2>/dev/null; then + echo "Recovery applied incompatible evidence: $mode" >&2; exit 1 + fi + if grep -q '^terraform .* apply ' "$work/requests.log"; then echo "Recovery reached apply for $mode" >&2; exit 1; fi +done +if WORK="$work/wrong-approval" APPROVED_DIGEST=other bash "$guard" apply 2>/dev/null; then echo 'Recovery accepted another approval digest' >&2; exit 1; fi +if WORK="$work/retry" GITHUB_RUN_ATTEMPT=2 bash "$guard" plan 2>/dev/null; then echo 'Recovery accepted a rerun' >&2; exit 1; fi +if WORK="$work/local" GITHUB_ACTIONS=false bash "$guard" plan 2>/dev/null; then echo 'Recovery accepted local execution' >&2; exit 1; fi +: >"$work/requests.log" +if WORK="$work/apply-failure" MODE=apply-failure APPROVED_DIGEST="$approved" bash "$guard" apply 2>/dev/null; then + echo 'Recovery continued after an apply failure' >&2; exit 1 +fi +[ ! -e "$work/applied" ] +if grep -q '^live collect-final$' "$work/requests.log"; then echo 'Recovery verified a failed apply as complete' >&2; exit 1; fi +: >"$work/requests.log" +WORK="$work/apply" APPROVED_DIGEST="$approved" bash "$guard" apply +[ "$(grep -c '^live collect$' "$work/requests.log")" = 2 ] +[ "$(grep -c '^live collect-final$' "$work/requests.log")" = 1 ] +[ "$(grep -c '^gh attestation verify ' "$work/requests.log")" = 10 ] +WORK="$work/verify" bash "$guard" verify +jq '.resources[0].instances[0].attributes.arn="different"' "$work/final-state.json" >"$work/changed-state.json" +if bash "$guard" check-final-state "$work/changed-state.json" "$work/state.json" 2>/dev/null; then + echo 'Recovery accepted an unrelated retained-state change' >&2; exit 1 +fi +echo 'Protected recovery plan, approval binding, apply and final-state orchestration checks passed' diff --git a/.github/scripts/runtime-tls-recovery-inputs.sh b/.github/scripts/runtime-tls-recovery-inputs.sh new file mode 100644 index 000000000..fbe4df0b3 --- /dev/null +++ b/.github/scripts/runtime-tls-recovery-inputs.sh @@ -0,0 +1,66 @@ +#!/usr/bin/env bash +# Bind private recovery inputs to their reviewed S3 versions and file hashes. +set -euo pipefail +guard="$(dirname "$0")/runtime-tls-recovery.sh" + +check_contract() { + bash "$guard" check-baseline "$1" + jq -e ' + .bucket == "warmbly-terraform-use1-925323749693" and + .state.key == "warmbly/production/runtime.tfstate" and + (.snapshot.key | type == "string" and test("^warmbly/production/vars/runtime-tls-recovery/[a-z0-9][a-z0-9-]{1,63}\\.tfvars\\.json$")) and + (.snapshot.versionId | type == "string" and length > 0 and . != "null" and (test("[\\r\\n]") | not)) and + (.snapshot.sha256 | type == "string" and test("^[a-f0-9]{64}$")) and + (.snapshot.releaseTag | type == "string" and test("^v[0-9]+\\.[0-9]+\\.[0-9]+$")) + ' "$1" >/dev/null || { echo 'Recovery requires separately versioned private state and cleanup inputs' >&2; return 1; } +} + +collect_inputs() { + local baseline=$1 work=$2 require_latest=${3:-true} bucket key version digest kind + check_contract "$baseline" + umask 077 + mkdir "$work" + cp "$baseline" "$work/baseline.json" + baseline="$work/baseline.json" + bucket=$(jq -r '.bucket' "$baseline") + aws sts get-caller-identity --region us-east-1 >"$work/identity.json" + jq -e '.Account == "925323749693"' "$work/identity.json" >/dev/null || { + echo 'Recovery input collection requires the reviewed AWS account' >&2; return 1; + } + for kind in state snapshot; do + key=$(jq -r --arg kind "$kind" '.[$kind].key' "$baseline") + version=$(jq -r --arg kind "$kind" '.[$kind].versionId' "$baseline") + aws s3api get-object --region us-east-1 --bucket "$bucket" --key "$key" \ + --version-id "$version" --expected-bucket-owner 925323749693 "$work/$kind.json" >"$work/$kind-metadata.json" + jq -e --arg version "$version" ' + .VersionId == $version and .DeleteMarker != true and + (.ServerSideEncryption == "AES256" or .ServerSideEncryption == "aws:kms") + ' "$work/$kind-metadata.json" >/dev/null || { + echo 'Recovery object metadata differs from the reviewed version' >&2; return 1; + } + digest=$(sha256sum "$work/$kind.json" | cut -d' ' -f1) + [ "$digest" = "$(jq -r --arg kind "$kind" '.[$kind].sha256' "$baseline")" ] || { + echo 'Recovery object bytes differ from the reviewed hash' >&2; return 1; + } + done + bash "$guard" check-state "$work/state.json" "$baseline" + jq -e '.target_tls == "on" and .name == "warmbly-production"' "$work/snapshot.json" >/dev/null || { + echo 'Recovery vars must select the reviewed production cleanup stage' >&2; return 1; + } + if [ "$require_latest" = true ]; then + aws s3api head-object --region us-east-1 --bucket "$bucket" --key warmbly/production/runtime.tfstate \ + --expected-bucket-owner 925323749693 >"$work/latest-state.json" + jq -e --slurpfile baseline "$baseline" '.VersionId == $baseline[0].state.versionId' "$work/latest-state.json" >/dev/null || { + echo 'Recovery state advanced beyond the reviewed version' >&2; return 1; + } + fi + jq '{account,region,bucket,state:{key:.state.key,versionId:.state.versionId,sha256:.state.sha256,lineage:.state.lineage,serial:.state.serial},snapshot}' \ + "$baseline" >"$work/inputs.json" +} + +case "${1:-}" in + check-contract) check_contract "${2:?}" ;; + collect) collect_inputs "${2:?}" "${3:?}" ;; + collect-archived) collect_inputs "${2:?}" "${3:?}" false ;; + *) echo 'Only read-only recovery input validation and collection are supported' >&2; exit 1 ;; +esac diff --git a/.github/scripts/runtime-tls-recovery-inputs.test.sh b/.github/scripts/runtime-tls-recovery-inputs.test.sh new file mode 100644 index 000000000..49765f569 --- /dev/null +++ b/.github/scripts/runtime-tls-recovery-inputs.test.sh @@ -0,0 +1,117 @@ +#!/usr/bin/env bash +set -euo pipefail +cd "$(dirname "$0")/../.." +work=$(mktemp -d) +trap 'rm -rf "$work"' EXIT +guard=.github/scripts/runtime-tls-recovery-inputs.sh +jq -n ' + ["backend","forms","tracking","realtime"] | map({ + TargetGroupName:("warmbly-production-" + .), + TargetGroupArn:("arn:aws:elasticloadbalancing:us-east-1:925323749693:targetgroup/warmbly-production-" + . + "/0123456789abcdef"), + Protocol:"HTTP",Port:8080,VpcId:"vpc-0123456789abcdef0",LoadBalancerArns:[],targets:[]}) as $groups | + {account:"925323749693",region:"us-east-1",bucket:"warmbly-terraform-use1-925323749693",httpGroups:$groups, + state:{key:"warmbly/production/runtime.tfstate",versionId:"reviewed-state",lineage:"01234567-89ab-cdef-0123-456789abcdef",serial:1,httpGroups:$groups}, + snapshot:{key:"warmbly/production/vars/runtime-tls-recovery/reviewed-cleanup.tfvars.json",versionId:"reviewed-vars",releaseTag:"v1.0.1"}} +' >"$work/baseline.json" +jq '{version:4,lineage:.state.lineage,serial:.state.serial,resources:[{mode:"managed",type:"aws_lb_target_group",name:"service", + instances:[.httpGroups[] | {index_key:(.TargetGroupName | ltrimstr("warmbly-production-")),attributes:{ + id:.TargetGroupArn,arn:.TargetGroupArn,name:.TargetGroupName,protocol:.Protocol,port:.Port,vpc_id:.VpcId}}]}]}' \ + "$work/baseline.json" >"$work/state.json" +printf '%s\n' '{"name":"warmbly-production","target_tls":"on"}' >"$work/snapshot.json" +state_digest=$(sha256sum "$work/state.json" | cut -d' ' -f1) +vars_digest=$(sha256sum "$work/snapshot.json" | cut -d' ' -f1) +jq --arg state "$state_digest" --arg vars "$vars_digest" '.state.sha256=$state | .snapshot.sha256=$vars' \ + "$work/baseline.json" >"$work/reviewed.json" +bash "$guard" check-contract "$work/reviewed.json" +for change in '.bucket="other-bucket"' '.state.key="other/state"' \ + '.snapshot.key="warmbly/production/vars/runtime-tls.tfvars.json"' \ + '.snapshot.key="warmbly/production/vars/runtime-tls-recovery/../default.tfvars.json"' \ + '.snapshot.versionId="null"' '.snapshot.sha256=""' '.snapshot.releaseTag="main"'; do + jq "$change" "$work/reviewed.json" >"$work/changed.json" + if bash "$guard" check-contract "$work/changed.json" 2>/dev/null; then + echo "Recovery accepted an unbound input contract: $change" >&2; exit 1 + fi +done +mkdir "$work/bin" +cat >"$work/bin/aws" <<'SH' +#!/usr/bin/env bash +set -euo pipefail +printf '%s\n' "$*" >>"$FIXTURES/requests.log" +service=$1 operation=$2 +shift 2 +bucket= key= version= owner= region= output= +while [ "$#" -gt 0 ]; do + case "$1" in + --bucket) bucket=$2; shift 2 ;; + --key) key=$2; shift 2 ;; + --version-id) version=$2; shift 2 ;; + --expected-bucket-owner) owner=$2; shift 2 ;; + --region) region=$2; shift 2 ;; + *) output=$1; shift ;; + esac +done +[ "$region" = us-east-1 ] +case "$service $operation" in + 'sts get-caller-identity') + if [ "${MODE:-}" = account ]; then echo '{"Account":"123456789012"}'; else echo '{"Account":"925323749693"}'; fi ;; + 's3api get-object') + [ "$bucket" = warmbly-terraform-use1-925323749693 ] && [ "$owner" = 925323749693 ] + case "$key $version" in + 'warmbly/production/runtime.tfstate reviewed-state') kind=state ;; + 'warmbly/production/vars/runtime-tls-recovery/reviewed-cleanup.tfvars.json reviewed-vars') kind=snapshot ;; + *) exit 1 ;; + esac + [ "${MODE:-}" != api-failure ] || exit 1 + cp "$FIXTURES/$kind.json" "$output" + if [ "${MODE:-}" = hash ]; then printf '\n' >>"$output"; fi + if [ "${MODE:-}" = version ]; then version=other-version; fi + encryption=AES256 + if [ "${MODE:-}" = kms ]; then encryption=aws:kms; fi + if [ "${MODE:-}" = encryption ]; then encryption=none; fi + jq -n --arg version "$version" --arg encryption "$encryption" --arg mode "${MODE:-}" \ + '{VersionId:$version,ServerSideEncryption:$encryption,DeleteMarker:($mode=="deleted")}' ;; + 's3api head-object') + [ "$bucket" = warmbly-terraform-use1-925323749693 ] && [ "$owner" = 925323749693 ] + [ "$key" = warmbly/production/runtime.tfstate ] + version=reviewed-state + if [ "${MODE:-}" = advanced ]; then version=advanced-state; fi + jq -n --arg version "$version" '{VersionId:$version}' ;; + *) echo 'Unexpected AWS operation' >&2; exit 1 ;; +esac +SH +chmod +x "$work/bin/aws" +PATH="$work/bin:$PATH" FIXTURES="$work" bash "$guard" collect "$work/reviewed.json" "$work/collected" +jq -e --arg state "$state_digest" --arg vars "$vars_digest" '.state.sha256==$state and .snapshot.sha256==$vars' "$work/collected/inputs.json" >/dev/null +PATH="$work/bin:$PATH" FIXTURES="$work" MODE=kms bash "$guard" collect "$work/reviewed.json" "$work/kms" +for mode in account api-failure hash version encryption deleted advanced; do + if PATH="$work/bin:$PATH" FIXTURES="$work" MODE=$mode bash "$guard" collect "$work/reviewed.json" "$work/$mode" 2>/dev/null; then + echo "Recovery accepted incompatible collected inputs: $mode" >&2; exit 1 + fi + [ ! -e "$work/$mode/inputs.json" ] +done +PATH="$work/bin:$PATH" FIXTURES="$work" MODE=advanced bash "$guard" collect-archived "$work/reviewed.json" "$work/archived" +cmp "$work/state.json" "$work/archived/state.json" +[ ! -e "$work/archived/latest-state.json" ] +if PATH="$work/bin:$PATH" FIXTURES="$work" bash "$guard" collect "$work/reviewed.json" "$work/collected" 2>/dev/null; then + echo 'Recovery overwrote an existing input collection' >&2; exit 1 +fi +printf '%s\n' '{"name":"other-deployment","target_tls":"on"}' >"$work/snapshot.json" +digest=$(sha256sum "$work/snapshot.json" | cut -d' ' -f1) +jq --arg digest "$digest" '.snapshot.sha256=$digest' "$work/reviewed.json" >"$work/changed.json" +if PATH="$work/bin:$PATH" FIXTURES="$work" bash "$guard" collect "$work/changed.json" "$work/wrong-deployment" 2>/dev/null; then + echo 'Recovery accepted vars for a different deployment' >&2; exit 1 +fi +for stage in drain route; do + printf '%s\n' '{"name":"warmbly-production","target_tls":"on"}' >"$work/snapshot.json" + jq --arg stage "$stage" '.target_tls=$stage' "$work/snapshot.json" >"$work/changed-vars.json" + cp "$work/changed-vars.json" "$work/snapshot.json" + digest=$(sha256sum "$work/snapshot.json" | cut -d' ' -f1) + jq --arg digest "$digest" '.snapshot.sha256=$digest' "$work/reviewed.json" >"$work/changed.json" + if PATH="$work/bin:$PATH" FIXTURES="$work" bash "$guard" collect "$work/changed.json" "$work/$stage" 2>/dev/null; then + echo 'Recovery accepted vars for a different transition stage' >&2; exit 1 + fi +done +if bash "$guard" apply 2>/dev/null; then + echo 'Recovery input collector accepted an execution action' >&2; exit 1 +fi +echo 'Read-only recovery S3 input collection and checks passed' diff --git a/.github/scripts/runtime-tls-recovery-lineage.sh b/.github/scripts/runtime-tls-recovery-lineage.sh new file mode 100644 index 000000000..58276f7da --- /dev/null +++ b/.github/scripts/runtime-tls-recovery-lineage.sh @@ -0,0 +1,81 @@ +#!/usr/bin/env bash +# Preserve historical workflow identities when collecting recovery evidence. +set -euo pipefail + +check_contract() { + jq -e ' + .schemaVersion == 1 and .repository == "warmbly/warmbly" and + all(.release, .drain, .failedOn; + (.tag | type == "string" and test("^v[0-9]+\\.[0-9]+\\.[0-9]+$")) and + (.source | type == "string" and test("^[a-f0-9]{40}$")) and + (.runId | type == "number" and . > 0 and floor == .) and + (.attempt | type == "number" and . > 0 and floor == .)) and + ([.release.runId, .drain.runId, .failedOn.runId] | unique | length == 3) and + .drain.tag == .failedOn.tag and .release.tag != .drain.tag + ' "$1" >/dev/null || { echo 'Recovery requires explicit current and historical workflow identities' >&2; return 1; } +} + +check_lineage() { + local evidence=$1 contract=$2 repository=$3 tag source + check_contract "$contract" + jq -e --slurpfile contract "$contract" ' + $contract[0] as $expected | + def run_matches($identity; $path; $event; $branch; $conclusion): + .id == $identity.runId and .run_attempt == $identity.attempt and + .head_sha == $identity.source and .repository.full_name == $expected.repository and + .path == $path and .event == $event and .head_branch == $branch and + .status == "completed" and .conclusion == $conclusion; + (.runs.release | run_matches($expected.release; ".github/workflows/release.yml"; "push"; $expected.release.tag; "success")) and + (.runs.drain | run_matches($expected.drain; ".github/workflows/runtime-tls.yml"; "workflow_dispatch"; "main"; "success") and + .display_title == ("Runtime TLS drain " + $expected.drain.tag)) and + (.runs.failedOn | run_matches($expected.failedOn; ".github/workflows/runtime-tls.yml"; "workflow_dispatch"; "main"; "failure") and + .display_title == ("Runtime TLS on " + $expected.failedOn.tag)) and + (.failedOnJobs | type == "array" and length > 0) and + ([.failedOnJobs[].id] | unique | length) == (.failedOnJobs | length) and + all(.failedOnJobs[]; + .run_id == $expected.failedOn.runId and .run_attempt == $expected.failedOn.attempt and + .status == "completed") and + ([.failedOnJobs[] | select(.name == "apply")] | length == 1) and + any(.failedOnJobs[]; .name == "apply" and .conclusion == "success") and + any(.failedOnJobs[]; (.name | startswith("redeploy / ")) and .conclusion == "failure") + ' "$evidence" >/dev/null || { echo 'Recovery workflow evidence differs from the reviewed lineage' >&2; return 1; } + tag=$(jq -r '.release.tag' "$contract") + source=$(git -C "$repository" rev-parse --verify "refs/tags/$tag^{commit}") + [ "$source" = "$(jq -r '.release.source' "$contract")" ] || { echo 'Recovery release tag differs from its reviewed source' >&2; return 1; } + git -C "$repository" merge-base --is-ancestor "$(jq -r '.drain.source' "$contract")" "$(jq -r '.failedOn.source' "$contract")" || { + echo 'Recovery ON source does not descend from the reviewed drain source' >&2; return 1; + } + git -C "$repository" merge-base --is-ancestor "$(jq -r '.failedOn.source' "$contract")" "$source" || { + echo 'Recovery release does not descend from the reviewed ON source' >&2; return 1; + } +} + +collect_lineage() { + local contract=$1 work=$2 repository=$3 repo identity run attempt + check_contract "$contract" + umask 077 + mkdir "$work" + repo=$(jq -r '.repository' "$contract") + for identity in release drain failedOn; do + run=$(jq -r --arg identity "$identity" '.[$identity].runId' "$contract") + attempt=$(jq -r --arg identity "$identity" '.[$identity].attempt' "$contract") + gh api "repos/$repo/actions/runs/$run/attempts/$attempt" >"$work/$identity.json" + done + run=$(jq -r '.failedOn.runId' "$contract") + attempt=$(jq -r '.failedOn.attempt' "$contract") + gh api "repos/$repo/actions/runs/$run/attempts/$attempt/jobs?per_page=100" --paginate --slurp >"$work/job-pages.json" + jq -e '.[0].total_count == ([.[].jobs[]] | length)' "$work/job-pages.json" >/dev/null || { + echo 'Recovery requires the complete failed ON job inventory' >&2; return 1; + } + jq -n --slurpfile release "$work/release.json" --slurpfile drain "$work/drain.json" \ + --slurpfile failedOn "$work/failedOn.json" --slurpfile jobs "$work/job-pages.json" \ + '{runs:{release:$release[0],drain:$drain[0],failedOn:$failedOn[0]},failedOnJobs:[$jobs[0][].jobs[]]}' >"$work/candidate.json" + check_lineage "$work/candidate.json" "$contract" "$repository" + mv "$work/candidate.json" "$work/lineage.json" +} + +case "${1:-}" in + check) check_lineage "${2:?}" "${3:?}" "${4:?}" ;; + collect) collect_lineage "${2:?}" "${3:?}" "${4:?}" ;; + *) echo 'Only read-only recovery lineage check and collection are supported' >&2; exit 1 ;; +esac diff --git a/.github/scripts/runtime-tls-recovery-lineage.test.sh b/.github/scripts/runtime-tls-recovery-lineage.test.sh new file mode 100644 index 000000000..7974d4e0b --- /dev/null +++ b/.github/scripts/runtime-tls-recovery-lineage.test.sh @@ -0,0 +1,109 @@ +#!/usr/bin/env bash +set -euo pipefail +cd "$(dirname "$0")/../.." +work=$(mktemp -d) +trap 'rm -rf "$work"' EXIT +guard=.github/scripts/runtime-tls-recovery-lineage.sh +mkdir "$work/repository" +git -C "$work/repository" init -q +git -C "$work/repository" config user.name 'Recovery fixture' +git -C "$work/repository" config user.email 'fixture@example.invalid' +git -C "$work/repository" commit -qm 'feat: establish drain fixture' --allow-empty +drain=$(git -C "$work/repository" rev-parse HEAD) +git -C "$work/repository" commit -qm 'feat: establish ON fixture' --allow-empty +on=$(git -C "$work/repository" rev-parse HEAD) +git -C "$work/repository" commit -qm 'feat: establish release fixture' --allow-empty +release=$(git -C "$work/repository" rev-parse HEAD) +git -C "$work/repository" tag v1.0.1 +jq -n --arg drain "$drain" --arg on "$on" --arg release "$release" ' + {schemaVersion:1,repository:"warmbly/warmbly", + release:{tag:"v1.0.1",source:$release,runId:101,attempt:1}, + drain:{tag:"v1.0.0",source:$drain,runId:102,attempt:1}, + failedOn:{tag:"v1.0.0",source:$on,runId:103,attempt:1}} +' >"$work/contract.json" +jq ' + def run($path; $event; $branch; $conclusion): + {id:.runId,run_attempt:.attempt,head_sha:.source,repository:{full_name:"warmbly/warmbly"}, + path:$path,event:$event,head_branch:$branch,status:"completed",conclusion:$conclusion}; + {runs:{ + release:(.release | run(".github/workflows/release.yml";"push";.tag;"success")), + drain:(.drain | run(".github/workflows/runtime-tls.yml";"workflow_dispatch";"main";"success") + {display_title:("Runtime TLS drain " + .tag)}), + failedOn:(.failedOn | run(".github/workflows/runtime-tls.yml";"workflow_dispatch";"main";"failure") + {display_title:("Runtime TLS on " + .tag)})}, + failedOnJobs:[{id:1,run_id:103,run_attempt:1,status:"completed",name:"apply",conclusion:"success"}, + {id:2,run_id:103,run_attempt:1,status:"completed",name:"redeploy / redeploy v1.0.0",conclusion:"failure"}]} +' "$work/contract.json" >"$work/evidence.json" +bash "$guard" check "$work/evidence.json" "$work/contract.json" "$work/repository" +for change in '.schemaVersion=2' '.repository="other/repo"' '.release.runId=.drain.runId' \ + '.drain.tag=.release.tag' '.failedOn.tag="v0.9.0"' '.release.tag="main"' \ + '.failedOn.attempt=0' '.drain.source="unknown"'; do + jq "$change" "$work/contract.json" >"$work/changed.json" + if bash "$guard" check "$work/evidence.json" "$work/changed.json" "$work/repository" 2>/dev/null; then + echo "Recovery accepted a different lineage contract: $change" >&2; exit 1 + fi +done +for change in '.runs.release.id=104' '.runs.release.head_sha=.runs.drain.head_sha' \ + '.runs.release.repository.full_name="other/repo"' '.runs.release.head_branch="main"' \ + '.runs.release.path=".github/workflows/deploy-aws.yml"' '.runs.release.conclusion="failure"' \ + '.runs.release.event="workflow_dispatch"' '.runs.release.status="in_progress"' \ + '.runs.drain.run_attempt=2' '.runs.drain.conclusion="failure"' \ + '.runs.drain.display_title="Runtime TLS drain v1.0.1"' \ + '.runs.failedOn.display_title="Runtime TLS on v1.0.1"' '.runs.failedOn.conclusion="success"' \ + '.failedOnJobs=[]' '.failedOnJobs += [.failedOnJobs[0]]' '.failedOnJobs[0].conclusion="failure"' \ + '.failedOnJobs[1].conclusion="success"' '.failedOnJobs[0].run_id=104' \ + '.failedOnJobs[0].run_attempt=2' '.failedOnJobs[1].status="in_progress"'; do + jq "$change" "$work/evidence.json" >"$work/changed.json" + if bash "$guard" check "$work/changed.json" "$work/contract.json" "$work/repository" 2>/dev/null; then + echo "Recovery accepted different workflow evidence: $change" >&2; exit 1 + fi +done +git -C "$work/repository" tag -f v1.0.1 "$drain" >/dev/null +if bash "$guard" check "$work/evidence.json" "$work/contract.json" "$work/repository" 2>/dev/null; then + echo 'Recovery accepted a release tag on a different source' >&2; exit 1 +fi +git -C "$work/repository" tag -f v1.0.1 "$release" >/dev/null +jq --arg source "$release" '.drain.source=$source' "$work/contract.json" >"$work/reversed-contract.json" +jq --arg source "$release" '.runs.drain.head_sha=$source' "$work/evidence.json" >"$work/reversed-evidence.json" +if bash "$guard" check "$work/reversed-evidence.json" "$work/reversed-contract.json" "$work/repository" 2>/dev/null; then + echo 'Recovery accepted reversed drain and ON ancestry' >&2; exit 1 +fi +jq --arg source "$drain" '.release.source=$source' "$work/contract.json" >"$work/reversed-contract.json" +jq --arg source "$drain" '.runs.release.head_sha=$source' "$work/evidence.json" >"$work/reversed-evidence.json" +git -C "$work/repository" tag -f v1.0.1 "$drain" >/dev/null +if bash "$guard" check "$work/reversed-evidence.json" "$work/reversed-contract.json" "$work/repository" 2>/dev/null; then + echo 'Recovery accepted a release that predates the ON source' >&2; exit 1 +fi +git -C "$work/repository" tag -f v1.0.1 "$release" >/dev/null +mkdir "$work/bin" +cat >"$work/bin/gh" <<'SH' +#!/usr/bin/env bash +set -euo pipefail +printf '%s\n' "$*" >>"$FIXTURES/requests.log" +[ "${API_FAIL:-false}" = false ] || exit 1 +case "$2" in + */runs/101/attempts/1) jq '.runs.release' "$FIXTURES/evidence.json" ;; + */runs/102/attempts/1) jq '.runs.drain' "$FIXTURES/evidence.json" ;; + */runs/103/attempts/1) jq '.runs.failedOn' "$FIXTURES/evidence.json" ;; + */runs/103/attempts/1/jobs\?per_page=100) + [ "$3 $4" = '--paginate --slurp' ] + jq --arg mode "${JOB_MODE:-complete}" '[{total_count:2,jobs:(if $mode == "partial" then .failedOnJobs[:1] else .failedOnJobs end)}]' "$FIXTURES/evidence.json" ;; + *) exit 1 ;; +esac +SH +chmod +x "$work/bin/gh" +PATH="$work/bin:$PATH" FIXTURES="$work" bash "$guard" collect "$work/contract.json" "$work/collected" "$work/repository" +cmp "$work/evidence.json" "$work/collected/lineage.json" +if PATH="$work/bin:$PATH" FIXTURES="$work" JOB_MODE=partial bash "$guard" collect "$work/contract.json" "$work/partial" "$work/repository" 2>/dev/null; then + echo 'Recovery accepted an incomplete job collection' >&2; exit 1 +fi +[ ! -e "$work/partial/lineage.json" ] +if PATH="$work/bin:$PATH" FIXTURES="$work" API_FAIL=true bash "$guard" collect "$work/contract.json" "$work/api-failure" "$work/repository" 2>/dev/null; then + echo 'Recovery accepted a failed GitHub API read' >&2; exit 1 +fi +[ ! -e "$work/api-failure/lineage.json" ] +if PATH="$work/bin:$PATH" FIXTURES="$work" bash "$guard" collect "$work/contract.json" "$work/collected" "$work/repository" 2>/dev/null; then + echo 'Recovery overwrote an existing lineage collection' >&2; exit 1 +fi +if bash "$guard" apply 2>/dev/null; then + echo 'Recovery lineage collector accepted an execution action' >&2; exit 1 +fi +echo 'Read-only recovery workflow lineage collection and checks passed' diff --git a/.github/scripts/runtime-tls-recovery-live.fixture.jq b/.github/scripts/runtime-tls-recovery-live.fixture.jq new file mode 100644 index 000000000..c3b8b9de2 --- /dev/null +++ b/.github/scripts/runtime-tls-recovery-live.fixture.jq @@ -0,0 +1,56 @@ +def services: ["backend", "consumer", "forms", "tracking", "realtime"]; +def public_services: ["backend", "forms", "tracking", "realtime"]; +def arn($kind; $id): "arn:aws:elasticloadbalancing:us-east-1:925323749693:" + $kind + "/" + $id; +def http($name): arn("targetgroup"; "warmbly-production-"+$name+"/0123456789abcdef"); +def tls($name): arn("targetgroup"; "warmbly-production-"+$name+"-tls/1123456789abcdef"); +def service($name): "arn:aws:ecs:us-east-1:925323749693:service/warmbly-production/warmbly-production-"+$name; +def definition($name): "arn:aws:ecs:us-east-1:925323749693:task-definition/warmbly-production-"+$name+":47"; +def image($name): "ghcr.io/warmbly/warmbly/"+$name+"@"+$digest; +"arn:aws:ecs:us-east-1:925323749693:cluster/warmbly-production" as $cluster | +arn("loadbalancer"; "app/warmbly-production/0123456789abcdef") as $lb | +arn("listener"; "app/warmbly-production/0123456789abcdef/0123456789abcdef") as $listener | +"vpc-0123456789abcdef0" as $vpc | "sg-0123456789abcdef0" as $sg | +"-----BEGIN CERTIFICATE-----\nfixture\n-----END CERTIFICATE-----" as $cert | +([range(9) | . as $i | {arn:arn("listener-rule"; "app/warmbly-production/0123456789abcdef/0123456789abcdef/"+($i|tostring)), + hosts:["host"+($i|tostring)+".example.com"],target:tls(public_services[$i%4])}]) as $routes | +(public_services | map({TargetGroupName:("warmbly-production-"+.),TargetGroupArn:http(.),Protocol:"HTTP",Port:8080,VpcId:$vpc,LoadBalancerArns:[],targets:[]})) as $http | +{baseline:{account:"925323749693",region:"us-east-1",httpGroups:$http, + state:{lineage:"01234567-89ab-cdef-0123-456789abcdef",serial:64,versionId:"state-version",sha256:("a"*64),httpGroups:$http}, + snapshot:{sha256:("b"*64),releaseTag:"v1.2.3"}}, + vars:{name:"warmbly-production",target_tls:"on",backend_internal_certificate:$cert}, + images:{tag:"v1.2.3",registry:"ghcr.io/warmbly/warmbly",images:(services|map({key:.,value:$digest})|from_entries)}, + state:{version:4,lineage:"01234567-89ab-cdef-0123-456789abcdef",serial:64,resources:[ + {mode:"managed",type:"aws_lb_target_group",name:"service",instances:[$http[]|{ + index_key:(.TargetGroupName|ltrimstr("warmbly-production-")),attributes:{arn:.TargetGroupArn,id:.TargetGroupArn,name:.TargetGroupName,protocol:.Protocol,port:.Port,vpc_id:.VpcId}}]}, + {mode:"managed",type:"aws_lb_target_group",name:"service_tls",instances:[public_services[]|{index_key:.,attributes:{arn:tls(.),name:("warmbly-production-"+.+"-tls"),protocol:"HTTPS",port:8443,vpc_id:$vpc}}]}, + {mode:"managed",type:"aws_ecs_service",name:"service",instances:[services[]|{index_key:.,attributes:{id:service(.),cluster:$cluster,network_configuration:[{security_groups:[$sg]}]}}]}, + {mode:"managed",type:"aws_lb",name:"main",instances:[{attributes:{arn:$lb}}]}, + {mode:"managed",type:"aws_lb_listener",name:"https",instances:[{attributes:{arn:$listener}}]}, + {mode:"managed",type:"aws_lb_listener_rule",name:"service",instances:[$routes[]|{attributes:{arn:.arn,condition:[{host_header:[{values:.hosts}]}],action:[{target_group_arn:.target}]}}]} + ]}, + live:{account:{Account:"925323749693"},services:{failures:[],services:[services[]|. as $name|{ + serviceName:("warmbly-production-"+.),serviceArn:service(.),clusterArn:$cluster,taskDefinition:definition(.),status:"ACTIVE",desiredCount:1,runningCount:1,pendingCount:0, + deployments:[{status:"PRIMARY",rolloutState:"COMPLETED",taskDefinition:definition(.)}], + networkConfiguration:{awsvpcConfiguration:{securityGroups:[$sg]}}, + loadBalancers:(if .=="consumer" then [] else [{containerName:.,containerPort:8443,targetGroupArn:tls(.)}] end)}]}, + definitions:[services[]|. as $name|{taskDefinition:{taskDefinitionArn:definition(.),runtimePlatform:{cpuArchitecture:"X86_64"},containerDefinitions:[{ + name:.,image:image(.),environment:([ + {name:"SERVE_TLS",value:(if .=="backend" then "supplied" else "self-signed" end)}, + {name:"SERVE_TLS_PORT",value:"8443"},{name:"SERVE_HTTP_LOOPBACK_ONLY",value:"true"}]+ + (if .=="backend" then [{name:"SERVE_TLS_CERT",value:$cert}] elif .=="forms" or .=="tracking" then + [{name:"BACKEND_INTERNAL_URL",value:"https://backend.warmbly.internal:8443"},{name:"BACKEND_INTERNAL_CA",value:$cert}] else [] end))}]}, + tags:[{key:"warmbly-release",value:"v1.2.3"},{key:"warmbly-image-variant",value:"default"}]}], + tasks:[services[]|{taskArn:("task-"+.),group:("service:warmbly-production-"+.),taskDefinitionArn:definition(.),clusterArn:$cluster, + lastStatus:"RUNNING",desiredStatus:"RUNNING",healthStatus:(if .=="consumer" then "UNKNOWN" else "HEALTHY" end),overrides:{containerOverrides:[]}, + containers:[{name:.,image:image(.),imageDigest:$digest,lastStatus:"RUNNING",healthStatus:(if .=="consumer" then "UNKNOWN" else "HEALTHY" end),networkInterfaces:[{privateIpv4Address:"10.0.0.1"}]}]}], + manifests:[services[]|{image:image(.),digest:$digest,document:{schemaVersion:2}}], + httpsGroups:[public_services[]|{TargetGroupArn:tls(.),TargetGroupName:("warmbly-production-"+.+"-tls"),Protocol:"HTTPS",Port:8443,HealthCheckProtocol:"HTTPS",VpcId:$vpc,LoadBalancerArns:[$lb], + targets:[{Target:{Id:"10.0.0.1",Port:8443},TargetHealth:{State:"healthy"}}]}],httpGroups:$http, + listeners:[{ListenerArn:$listener,LoadBalancerArn:$lb,Port:443,Protocol:"HTTPS"}], + rules:([$routes[]|{RuleArn:.arn,IsDefault:false,Conditions:[{Field:"host-header",HostHeaderConfig:{Values:.hosts}}],Actions:[{Type:"forward",TargetGroupArn:.target}]}]+ + [{IsDefault:true,Actions:[{Type:"fixed-response",Order:1,FixedResponseConfig:{StatusCode:"404",ContentType:"text/plain",MessageBody:"Not found"}}]}]), + securityGroups:[{GroupId:$sg,VpcId:$vpc,IpPermissions:[{IpProtocol:"tcp",FromPort:8443,ToPort:8443}]}], + alarms:{CompositeAlarms:[],MetricAlarms:[public_services[] as $name|["target-5xx-rate","unhealthy-hosts"][]| + {AlarmName:("warmbly-production-"+$name+"-"+.),StateValue:"OK",ActionsEnabled:true, + Dimensions:[{Name:"TargetGroup",Value:(tls($name)|split(":")[-1])},{Name:"LoadBalancer",Value:($lb|split(":")[-1]|ltrimstr("loadbalancer/"))}]}]}, + public:(["https://api.warmbly.com/health","https://api.warmbly.com/v1/auth/config","https://forms.warmbly.com/health","https://realtime.warmbly.com/health","https://track.monitorably.com/health"]|map({url:.,status:200}))}} diff --git a/.github/scripts/runtime-tls-recovery-live.jq b/.github/scripts/runtime-tls-recovery-live.jq new file mode 100644 index 000000000..c2d4db18f --- /dev/null +++ b/.github/scripts/runtime-tls-recovery-live.jq @@ -0,0 +1,131 @@ +def public_services: ["backend", "forms", "tracking", "realtime"]; +def services: ["backend", "consumer", "forms", "tracking", "realtime"]; +def instances($type; $name): + [$state[0].resources[] | select(.mode == "managed" and .module == null and .type == $type and .name == $name) | .instances[]]; +def identity: {TargetGroupName,TargetGroupArn,Protocol,Port,VpcId}; +def environment: .environment | map({key:.name,value:.value}) | from_entries; +def targets: + [.Actions[] | select(.Type == "forward") | + .TargetGroupArn?, .ForwardConfig.TargetGroups[]?.TargetGroupArn | select(. != null)] | unique; + +$baseline[0] as $b | $vars[0] as $v | $images[0] as $images | +instances("aws_ecs_service"; "service") as $expectedServices | +instances("aws_lb_target_group"; "service_tls") as $tls | +(instances("aws_lb"; "main") | map(.attributes.arn)) as $lbs | +(instances("aws_lb_listener"; "https") | map(.attributes.arn)) as $listeners | +([instances("aws_lb_listener_rule"; "service")[], instances("aws_lb_listener_rule"; "tracking_alias")[]] | + map({arn:.attributes.arn, hosts:([.attributes.condition[].host_header[].values[]] | sort), + target:.attributes.action[0].target_group_arn})) as $routes | +($expectedServices | map(.attributes.network_configuration[].security_groups[]) | unique) as $sgs | +($v.target_tls_port // 8443) as $port | +. as $live | +.account.Account == "925323749693" and +($images.tag == $b.snapshot.releaseTag and $images.registry == "ghcr.io/warmbly/warmbly") and +($expectedServices | map(.index_key) | sort) == (services | sort) and +($tls | map(.index_key) | sort) == (public_services | sort) and +($lbs | length == 1) and ($listeners | length == 1) and +($routes | length == 9) and ($routes | map(.arn) | unique | length == 9) and +all($routes[]; .hosts | length > 0) and +all($tls[]; .attributes.protocol == "HTTPS" and .attributes.port == $port and + .attributes.vpc_id == $b.httpGroups[0].VpcId) and +all($routes[]; .target as $target | any($tls[]; .attributes.arn == $target)) and +(.services.failures | length == 0) and +(.services.services | map(.serviceName) | sort) == (services | map("warmbly-production-" + .) | sort) and +all(.services.services[]; + . as $s | (.serviceName | ltrimstr("warmbly-production-")) as $name | + any($expectedServices[]; .index_key == $name and .attributes.id == $s.serviceArn and .attributes.cluster == $s.clusterArn) and + .status == "ACTIVE" and .desiredCount > 0 and .runningCount == .desiredCount and .pendingCount == 0 and + (.deployments | length == 1) and .deployments[0].status == "PRIMARY" and + .deployments[0].rolloutState == "COMPLETED" and .deployments[0].taskDefinition == .taskDefinition and + (.networkConfiguration.awsvpcConfiguration.securityGroups | sort) == $sgs and + (if $name == "consumer" then (.loadBalancers | length == 0) else + (.loadBalancers | length == 1) and .loadBalancers[0].containerName == $name and + .loadBalancers[0].containerPort == $port and + any($tls[]; .index_key == $name and .attributes.arn == $s.loadBalancers[0].targetGroupArn) end) and + ([$live.definitions[] | select(.taskDefinition.taskDefinitionArn == $s.taskDefinition)] | length == 1) and + ([$live.definitions[] | select(.taskDefinition.taskDefinitionArn == $s.taskDefinition)][0] as $d | + ([$d.tags[] | select(.key == "warmbly-image-variant") | .value]) as $variant | + ($name + (if $variant == ["kafka"] then "-kafka" else "" end)) as $key | + ($images.registry + "/" + $name + "@" + $images.images[$key]) as $image | + (if $name == "consumer" and $d.taskDefinition.containerDefinitions[0].healthCheck == null then "UNKNOWN" else "HEALTHY" end) as $health | + ([$d.tags[] | select(.key == "warmbly-release") | .value] == [$images.tag]) and + ($variant == ["default"] or $variant == ["kafka"]) and + ($images.images[$key] | type == "string" and test("^sha256:[a-f0-9]{64}$")) and + ($d.taskDefinition.containerDefinitions | length == 1) and + (["X86_64", "ARM64"] | index($d.taskDefinition.runtimePlatform.cpuArchitecture // "X86_64") != null) and + ($d.taskDefinition.runtimePlatform.operatingSystemFamily // "LINUX") == "LINUX" and + ($d.taskDefinition.containerDefinitions[0] as $c | + ($c | environment) as $env | + $c.name == $name and $c.image == $image and + ($c.environment | map(.name) | unique | length) == ($c.environment | length) and + ($c.environmentFiles // [] | length == 0) and + all($c.secrets[]?; .name | test("^(SERVE_TLS|SERVE_TLS_PORT|SERVE_TLS_CERT|SERVE_HTTP_LOOPBACK_ONLY|BACKEND_INTERNAL_URL|BACKEND_INTERNAL_CA)$") | not) and + (if $name == "consumer" then true else + $env.SERVE_TLS == (if $name == "backend" then "supplied" else "self-signed" end) and + $env.SERVE_TLS_PORT == ($port | tostring) and $env.SERVE_HTTP_LOOPBACK_ONLY == "true" and + (if $name == "backend" then $env.SERVE_TLS_CERT == $v.backend_internal_certificate else true end) and + (if $name == "forms" or $name == "tracking" then + $env.BACKEND_INTERNAL_URL == ("https://backend." + ($v.namespace // "warmbly.internal") + ":" + ($port | tostring)) and + $env.BACKEND_INTERNAL_CA == $v.backend_internal_certificate else true end) end)) and + ([$live.tasks[] | select(.group == ("service:" + $s.serviceName))] as $tasks | + ($tasks | length) == $s.desiredCount and + all($tasks[]; .taskDefinitionArn == $s.taskDefinition and .clusterArn == $s.clusterArn and + .lastStatus == "RUNNING" and .desiredStatus == "RUNNING" and .healthStatus == $health and + (.overrides.containerOverrides | all(.[]; (.environment // [] | length == 0) and (.command // [] | length == 0) and (.environmentFiles // [] | length == 0))) and + (.containers | length == 1) and .containers[0].name == $name and .containers[0].image == $image and + .containers[0].lastStatus == "RUNNING" and .containers[0].healthStatus == $health and + (.containers[0].imageDigest as $digest | + any($live.manifests[]; .image == $image and .digest == ($image | split("@")[1]) and + (if .document.manifests then + .digest as $index | + any(.document.manifests[]; (.digest == $digest or $index == $digest) and .platform.os == "linux" and + .platform.architecture == (if ($d.taskDefinition.runtimePlatform.cpuArchitecture // "X86_64") == "ARM64" then "arm64" else "amd64" end)) + else .digest == $digest end))))))) and +(.tasks | map(.taskArn) | unique | length) == (.tasks | length) and +(.tasks | length) == ([.services.services[].desiredCount] | add) and +(.definitions | length == 5) and +(.httpsGroups | map(.TargetGroupArn) | sort) == ($tls | map(.attributes.arn) | sort) and +all(.httpsGroups[]; + . as $g | .Protocol == "HTTPS" and .Port == $port and .HealthCheckProtocol == "HTTPS" and + .VpcId == $b.httpGroups[0].VpcId and .LoadBalancerArns == $lbs and + (.targets | length > 0) and all(.targets[]; .TargetHealth.State == "healthy" and .Target.Port == $port) and + ([.targets[].Target.Id] | sort) == + ([$live.tasks[] | select(.group == ("service:" + ($g.TargetGroupName | rtrimstr("-tls")))) | + .containers[0].networkInterfaces[].privateIpv4Address] | sort) and + any($tls[]; .attributes.arn == $g.TargetGroupArn and .attributes.name == $g.TargetGroupName)) and +(if $phase == "after" then .httpGroups == [] else + (.httpGroups | map(identity) | sort_by(.TargetGroupArn)) == ($b.httpGroups | map(identity) | sort_by(.TargetGroupArn)) end) and +all(.httpGroups[]; .LoadBalancerArns == [] and .targets == []) and +(.listeners | length == 1) and .listeners[0].ListenerArn == $listeners[0] and +.listeners[0].LoadBalancerArn == $lbs[0] and .listeners[0].Port == 443 and .listeners[0].Protocol == "HTTPS" and +(.rules | length == 10) and +([.rules[] | select(.IsDefault == true)] | length == 1) and +all(.rules[] | select(.IsDefault == true); .Actions == [{Type:"fixed-response",Order:1,FixedResponseConfig:{StatusCode:"404",ContentType:"text/plain",MessageBody:"Not found"}}]) and +([.rules[] | select(.IsDefault == false) | .RuleArn] | sort) == ($routes | map(.arn) | sort) and +all(.rules[] | select(.IsDefault == false); + . as $rule | (.Transforms // [] | length == 0) and (.Conditions | length == 1) and + .Conditions[0].Field == "host-header" and (.Actions | length == 1) and .Actions[0].Type == "forward" and + all(.Actions[0].ForwardConfig.TargetGroups[]?; (.Weight // 1) > 0) and + any($routes[]; .arn == $rule.RuleArn and + .hosts == ($rule.Conditions[0].HostHeaderConfig.Values | sort) and ($rule | targets) == [.target])) and +(.securityGroups | map(.GroupId) | sort) == ($sgs | sort) and ($sgs | length > 0) and +all(.securityGroups[]; .VpcId == $b.httpGroups[0].VpcId and + all(.IpPermissions[]; . as $permission | + .IpProtocol != "-1" and + (if .IpProtocol == "tcp" or .IpProtocol == "6" then + (.FromPort | type == "number") and (.ToPort | type == "number") and + all($b.httpGroups[]; .Port < $permission.FromPort or .Port > $permission.ToPort) else true end))) and +(.alarms.CompositeAlarms | length == 0) and +(.alarms.MetricAlarms | map(.AlarmName) | sort) == + ([public_services[] as $name | ["target-5xx-rate", "unhealthy-hosts"][] | "warmbly-production-" + $name + "-" + .] | sort) and +all(.alarms.MetricAlarms[]; + . as $alarm | .StateValue == "OK" and .ActionsEnabled == true and + any($tls[]; + . as $group | ($alarm.AlarmName | startswith("warmbly-production-" + $group.index_key + "-")) and + ([$alarm.Dimensions[]?, $alarm.Metrics[]?.MetricStat.Metric.Dimensions[]? | select(.Name == "TargetGroup") | .Value] | unique) == + [($group.attributes.arn | split(":")[-1])] and + ([$alarm.Dimensions[]?, $alarm.Metrics[]?.MetricStat.Metric.Dimensions[]? | select(.Name == "LoadBalancer") | .Value] | unique) == + [($lbs[0] | split(":")[-1] | ltrimstr("loadbalancer/"))])) and +(.public | map(.url) | sort) == (["https://api.warmbly.com/health", "https://api.warmbly.com/v1/auth/config", + "https://forms.warmbly.com/health", "https://realtime.warmbly.com/health", "https://track.monitorably.com/health"] | sort) and +all(.public[]; .status == 200) diff --git a/.github/scripts/runtime-tls-recovery-live.sh b/.github/scripts/runtime-tls-recovery-live.sh new file mode 100755 index 000000000..f230cd5be --- /dev/null +++ b/.github/scripts/runtime-tls-recovery-live.sh @@ -0,0 +1,96 @@ +#!/usr/bin/env bash +# Collect fresh read-only service and traffic evidence from reviewed state identities. +set -euo pipefail +scripts=$(cd "$(dirname "$0")" && pwd) + +check_live() { + local evidence=$1 baseline=$2 vars=$3 state=$4 images=$5 phase=${6:-before} + bash "$scripts/runtime-tls-recovery.sh" check-state "$state" "$baseline" + [ "$(sha256sum "$vars" | cut -d' ' -f1)" = "$(jq -r '.snapshot.sha256' "$baseline")" ] + jq -e '.name == "warmbly-production" and .target_tls == "on" and + (.backend_internal_certificate | type == "string" and startswith("-----BEGIN CERTIFICATE-----"))' "$vars" >/dev/null + jq -e --arg phase "$phase" --slurpfile baseline "$baseline" --slurpfile vars "$vars" --slurpfile state "$state" --slurpfile images "$images" \ + -f "$scripts/runtime-tls-recovery-live.jq" "$evidence" >/dev/null || { + echo 'Recovery live service, TLS, traffic or health evidence does not match the reviewed inputs' >&2; return 1; + } +} + +collect_live() { + local baseline=$1 inputs=$2 work=$3 phase=${4:-before} cluster definition arn name image digest url status + bash "$scripts/runtime-tls-recovery.sh" check-state "$inputs/state.json" "$baseline" + umask 077 + mkdir "$work" + export AWS_PAGER="" + aws sts get-caller-identity --region us-east-1 >"$work/account.json" + jq -e '.Account == "925323749693"' "$work/account.json" >/dev/null + cluster=$(jq -er '[.resources[] | select(.mode=="managed" and .module==null and .type=="aws_ecs_service" and .name=="service") | + .instances[].attributes.cluster] | unique | if length==1 then .[0] else error("cluster identity") end' "$inputs/state.json") + aws ecs describe-services --region us-east-1 --cluster "$cluster" --services \ + warmbly-production-backend warmbly-production-consumer warmbly-production-forms warmbly-production-tracking warmbly-production-realtime >"$work/services.json" + : >"$work/definitions.jsonl" + : >"$work/tasks.jsonl" + while IFS= read -r definition; do + aws ecs describe-task-definition --region us-east-1 --task-definition "$definition" --include TAGS >>"$work/definitions.jsonl" + done < <(jq -r '.services[].taskDefinition' "$work/services.json") + while IFS= read -r name; do + aws ecs list-tasks --region us-east-1 --cluster "$cluster" --service-name "$name" --desired-status RUNNING >"$work/task-list.json" + while IFS= read -r arn; do + aws ecs describe-tasks --region us-east-1 --cluster "$cluster" --tasks "$arn" >"$work/task.json" + jq -e '.failures == [] and (.tasks | length == 1)' "$work/task.json" >/dev/null + jq -c '.tasks[]' "$work/task.json" >>"$work/tasks.jsonl" + done < <(jq -r '.taskArns[]' "$work/task-list.json") + done < <(jq -r '.services[].serviceName' "$work/services.json") + : >"$work/manifests.jsonl" + while IFS= read -r image; do + [[ "$image" =~ ^ghcr.io/warmbly/warmbly/(backend|consumer|forms|tracking|realtime)@sha256:[a-f0-9]{64}$ ]] + docker buildx imagetools inspect "$image" --raw >"$work/manifest.json" + digest="sha256:$(sha256sum "$work/manifest.json" | cut -d' ' -f1)" + [ "$digest" = "${image##*@}" ] || { echo 'Registry manifest bytes differ from the pinned image' >&2; return 1; } + jq -n --arg image "$image" --arg digest "$digest" --slurpfile document "$work/manifest.json" \ + '{image:$image,digest:$digest,document:$document[0]}' >>"$work/manifests.jsonl" + done < <(jq -r '.taskDefinition.containerDefinitions[].image' "$work/definitions.jsonl" | sort -u) + aws elbv2 describe-target-groups --region us-east-1 >"$work/all-groups.json" + : >"$work/groups.jsonl" + while IFS= read -r arn; do + aws elbv2 describe-target-health --region us-east-1 --target-group-arn "$arn" >"$work/health.json" + jq -c --arg arn "$arn" --slurpfile health "$work/health.json" \ + '.TargetGroups[] | select(.TargetGroupArn == $arn) | . + {targets:$health[0].TargetHealthDescriptions}' \ + "$work/all-groups.json" >>"$work/groups.jsonl" + done < <(jq -r '.TargetGroups[] | select(.TargetGroupName | test("^warmbly-production-(backend|forms|tracking|realtime)(-tls)?$")) | .TargetGroupArn' "$work/all-groups.json") + arn=$(jq -er '[.resources[] | select(.mode=="managed" and .module==null and .type=="aws_lb" and .name=="main") | + .instances[].attributes.arn] | if length==1 then .[0] else error("load balancer identity") end' "$inputs/state.json") + aws elbv2 describe-listeners --region us-east-1 --load-balancer-arn "$arn" >"$work/listeners.json" + : >"$work/rules.jsonl" + while IFS= read -r arn; do + aws elbv2 describe-rules --region us-east-1 --listener-arn "$arn" | jq -c '.Rules[]' >>"$work/rules.jsonl" + done < <(jq -r '.Listeners[].ListenerArn' "$work/listeners.json") + : >"$work/security-groups.jsonl" + while IFS= read -r arn; do + aws ec2 describe-security-groups --region us-east-1 --group-ids "$arn" | jq -c '.SecurityGroups[]' >>"$work/security-groups.jsonl" + done < <(jq -r '.services[].networkConfiguration.awsvpcConfiguration.securityGroups[]' "$work/services.json" | sort -u) + aws cloudwatch describe-alarms --region us-east-1 --alarm-name-prefix warmbly-production- >"$work/alarms.json" + : >"$work/public.jsonl" + for url in https://api.warmbly.com/health https://api.warmbly.com/v1/auth/config https://forms.warmbly.com/health \ + https://realtime.warmbly.com/health https://track.monitorably.com/health; do + status=$(curl --silent --show-error --proto '=https' --tlsv1.2 --connect-timeout 10 --max-time 30 --output /dev/null --write-out '%{http_code}' "$url") + jq -n --arg url "$url" --argjson status "$status" '{url:$url,status:$status}' >>"$work/public.jsonl" + done + jq -n --slurpfile account "$work/account.json" --slurpfile services "$work/services.json" \ + --slurpfile definitions "$work/definitions.jsonl" --slurpfile tasks "$work/tasks.jsonl" \ + --slurpfile manifests "$work/manifests.jsonl" --slurpfile groups "$work/groups.jsonl" \ + --slurpfile listeners "$work/listeners.json" --slurpfile rules "$work/rules.jsonl" \ + --slurpfile securityGroups "$work/security-groups.jsonl" --slurpfile alarms "$work/alarms.json" --slurpfile public "$work/public.jsonl" \ + '{account:$account[0],services:$services[0],definitions:$definitions,tasks:$tasks,manifests:$manifests, + httpsGroups:[$groups[]|select(.Protocol=="HTTPS")],httpGroups:[$groups[]|select(.Protocol=="HTTP")], + listeners:$listeners[0].Listeners,rules:$rules,securityGroups:$securityGroups,alarms:$alarms[0],public:$public}' >"$work/candidate.json" + check_live "$work/candidate.json" "$baseline" "$inputs/snapshot.json" "$inputs/state.json" "$inputs/images.json" "$phase" + mv "$work/candidate.json" "$work/live.json" +} + +case "${1:-}" in + check) check_live "${2:?}" "${3:?}" "${4:?}" "${5:?}" "${6:?}" ;; + check-final) check_live "${2:?}" "${3:?}" "${4:?}" "${5:?}" "${6:?}" after ;; + collect) collect_live "${2:?}" "${3:?}" "${4:?}" ;; + collect-final) collect_live "${2:?}" "${3:?}" "${4:?}" after ;; + *) echo 'Only read-only recovery live checks and collection are supported' >&2; exit 1 ;; +esac diff --git a/.github/scripts/runtime-tls-recovery-live.test.sh b/.github/scripts/runtime-tls-recovery-live.test.sh new file mode 100755 index 000000000..c1d527edf --- /dev/null +++ b/.github/scripts/runtime-tls-recovery-live.test.sh @@ -0,0 +1,137 @@ +#!/usr/bin/env bash +set -euo pipefail +cd "$(dirname "$0")/../.." +work=$(mktemp -d) +trap 'rm -rf "$work"' EXIT +guard=.github/scripts/runtime-tls-recovery-live.sh +printf '{"schemaVersion":2}\n' >"$work/manifest.json" +digest="sha256:$(sha256sum "$work/manifest.json" | cut -d' ' -f1)" +jq -n --arg digest "$digest" -f .github/scripts/runtime-tls-recovery-live.fixture.jq >"$work/fixture.json" +for kind in baseline state vars images live; do jq ".$kind" "$work/fixture.json" >"$work/$kind.json"; done +state_hash=$(sha256sum "$work/state.json" | cut -d' ' -f1) +vars_hash=$(sha256sum "$work/vars.json" | cut -d' ' -f1) +jq --arg state "$state_hash" --arg vars "$vars_hash" '.state.sha256=$state | .snapshot.sha256=$vars' "$work/baseline.json" >"$work/reviewed.json" +check() { bash "$guard" check "$1" "$work/reviewed.json" "$work/vars.json" "$work/state.json" "$work/images.json"; } +check "$work/live.json" +for change in \ + '.account.Account="123456789012"' '.services.failures=[{}]' '.services.services|=.[1:]' \ + '.services.services[0].clusterArn="other-cluster"' '.services.services[0].serviceArn="other-service"' \ + '.services.services[0].desiredCount=0' '.services.services[0].runningCount=0' '.services.services[0].pendingCount=1' \ + '.services.services[0].deployments[0].rolloutState="IN_PROGRESS"' '.services.services[0].deployments+=.services.services[0].deployments' \ + '.services.services[0].loadBalancers[0].targetGroupArn="other-group"' \ + '.services.services[0].networkConfiguration.awsvpcConfiguration.securityGroups+=["sg-extra"]' \ + '.definitions[0].tags[0].value="v1.2.2"' '.definitions[0].taskDefinition.containerDefinitions[0].image="other-image"' \ + '.definitions[0].taskDefinition.containerDefinitions[0].secrets=[{name:"SERVE_TLS",valueFrom:"other"}]' \ + '.definitions[0].taskDefinition.containerDefinitions[0].environmentFiles=[{value:"other"}]' \ + '.definitions[0].taskDefinition.containerDefinitions[0].environment[2].value="false"' \ + '.definitions[0].taskDefinition.containerDefinitions[0].environment[0].value="self-signed"' \ + '.definitions[0].taskDefinition.containerDefinitions[0].environment[3].value="other-cert"' \ + '.definitions[2].taskDefinition.containerDefinitions[0].environment[4].value="other-ca"' \ + '.definitions[2].taskDefinition.containerDefinitions[0].environment[3].value="http://backend.warmbly.internal:8080"' \ + '.tasks|=.[1:]' '.tasks+=.tasks' '.tasks[0].taskDefinitionArn="older-definition"' \ + '.tasks[0].healthStatus="UNHEALTHY"' '.tasks[0].containers[0].imageDigest="sha256:other"' \ + '.tasks[1].healthStatus="UNHEALTHY"' '.tasks[1].containers[0].lastStatus="STOPPED"' \ + '.tasks[0].overrides.containerOverrides=[{environment:[{name:"SERVE_TLS",value:"off"}]}]' \ + '.httpsGroups|=.[1:]' '.httpsGroups[0].Protocol="HTTP"' '.httpsGroups[0].targets=[]' \ + '.httpsGroups[0].targets[0].TargetHealth.State="unhealthy"' '.httpsGroups[0].LoadBalancerArns=[]' \ + '.httpsGroups[0].targets[0].Target.Id="10.0.0.2"' \ + '.httpGroups[0].targets=[{}]' '.httpGroups[0].LoadBalancerArns=["other-lb"]' '.httpGroups[0].TargetGroupArn="other-group"' \ + '.listeners[0].Protocol="HTTP"' '.listeners[0].Port=80' '.rules|=.[1:]' \ + '.rules[0].Actions[0].TargetGroupArn=.httpGroups[0].TargetGroupArn' \ + '.rules[0].Actions[0].ForwardConfig.TargetGroups=[{TargetGroupArn:.httpGroups[0].TargetGroupArn,Weight:0}]' \ + '.rules[0].Conditions[0].HostHeaderConfig.Values=["other.example.com"]' \ + '.rules[0].Transforms=[{}]' '.securityGroups=[]' \ + '.securityGroups[0].IpPermissions+=[{IpProtocol:"tcp",FromPort:8080,ToPort:8080}]' \ + '.securityGroups[0].IpPermissions+=[{IpProtocol:"-1"}]' \ + '.alarms.MetricAlarms|=.[1:]' '.alarms.MetricAlarms[0].StateValue="ALARM"' \ + '.alarms.MetricAlarms[0].StateValue="INSUFFICIENT_DATA"' '.public[0].status=503' '.public|=.[1:]'; do + jq "$change" "$work/live.json" >"$work/changed.json" + if check "$work/changed.json" 2>/dev/null; then + echo "Recovery accepted incompatible live evidence: $change" >&2; exit 1 + fi +done +jq '.alarms.MetricAlarms[0].Dimensions[0].Value="targetgroup/old-http/0000000000000000"' "$work/live.json" >"$work/changed.json" +if check "$work/changed.json" 2>/dev/null; then echo 'Recovery accepted an alarm on a different target group' >&2; exit 1; fi +jq '.alarms.MetricAlarms[] |= (.Metrics=[{MetricStat:{Metric:{Dimensions:.Dimensions}}}] | del(.Dimensions))' "$work/live.json" >"$work/metric-math.json" +check "$work/metric-math.json" +jq --arg digest "$digest" '.tasks[].containers[0].imageDigest="sha256:platform" | + .manifests[].document={manifests:[{digest:"sha256:platform",platform:{os:"linux",architecture:"amd64"}}]}' \ + "$work/live.json" >"$work/multiarch.json" +check "$work/multiarch.json" +jq --arg digest "$digest" '.tasks[].containers[0].imageDigest=$digest' "$work/multiarch.json" >"$work/index-reported.json" +check "$work/index-reported.json" +jq '.manifests[].document.manifests[0].platform.architecture="arm64"' "$work/multiarch.json" >"$work/changed.json" +if check "$work/changed.json" 2>/dev/null; then echo 'Recovery accepted another platform manifest' >&2; exit 1; fi +jq '.httpGroups=[]' "$work/live.json" >"$work/final.json" +bash "$guard" check-final "$work/final.json" "$work/reviewed.json" "$work/vars.json" "$work/state.json" "$work/images.json" +if bash "$guard" check-final "$work/live.json" "$work/reviewed.json" "$work/vars.json" "$work/state.json" "$work/images.json" 2>/dev/null; then + echo 'Recovery final check accepted retained HTTP groups' >&2; exit 1 +fi +mkdir "$work/bin" "$work/inputs" +cp "$work/state.json" "$work/images.json" "$work/inputs/" +cp "$work/vars.json" "$work/inputs/snapshot.json" +cat >"$work/bin/aws" <<'SH' +#!/usr/bin/env bash +set -euo pipefail +printf '%s\n' "$*" >>"$FIXTURES/requests.log" +service=$1 operation=$2 +shift 2 +region= definition= name= arn= +while [ "$#" -gt 0 ]; do + case "$1" in + --region) region=$2; shift 2 ;; + --task-definition) definition=$2; shift 2 ;; + --service-name) name=$2; shift 2 ;; + --tasks|--target-group-arn) arn=$2; shift 2 ;; + *) shift ;; + esac +done +[ "$region" = us-east-1 ] +[ "${MODE:-}" != api-failure ] || [ "$service $operation" != 'ecs describe-tasks' ] || exit 1 +case "$service $operation" in + 'sts get-caller-identity') + if [ "${MODE:-}" = account ]; then echo '{"Account":"123456789012"}'; else jq '.account' "$FIXTURES/live.json"; fi ;; + 'ecs describe-services') jq '.services' "$FIXTURES/live.json" ;; + 'ecs describe-task-definition') jq --arg definition "$definition" '.definitions[] | select(.taskDefinition.taskDefinitionArn==$definition)' "$FIXTURES/live.json" ;; + 'ecs list-tasks') jq --arg name "$name" '{taskArns:[.tasks[]|select(.group==("service:"+$name))|.taskArn]}' "$FIXTURES/live.json" ;; + 'ecs describe-tasks') jq --arg arn "$arn" '{failures:[],tasks:[.tasks[]|select(.taskArn==$arn)]}' "$FIXTURES/live.json" ;; + 'elbv2 describe-target-groups') + if [ "${MODE:-}" = final ]; then jq '{TargetGroups:.httpsGroups}' "$FIXTURES/live.json" + else jq '{TargetGroups:(.httpsGroups+.httpGroups)}' "$FIXTURES/live.json"; fi ;; + 'elbv2 describe-target-health') + jq --arg arn "$arn" '{TargetHealthDescriptions:[(.httpsGroups+.httpGroups)[]|select(.TargetGroupArn==$arn)|.targets[]]}' "$FIXTURES/live.json" ;; + 'elbv2 describe-listeners') jq '{Listeners:.listeners}' "$FIXTURES/live.json" ;; + 'elbv2 describe-rules') jq '{Rules:.rules}' "$FIXTURES/live.json" ;; + 'ec2 describe-security-groups') jq '{SecurityGroups:.securityGroups}' "$FIXTURES/live.json" ;; + 'cloudwatch describe-alarms') jq '.alarms' "$FIXTURES/live.json" ;; + *) echo 'Unexpected AWS operation in read-only collector' >&2; exit 1 ;; +esac +SH +cat >"$work/bin/docker" <<'SH' +#!/usr/bin/env bash +set -euo pipefail +[[ "$*" == 'buildx imagetools inspect ghcr.io/warmbly/warmbly/'*' --raw' ]] +cat "$FIXTURES/manifest.json" +if [ "${MODE:-}" = manifest ]; then printf '\n'; fi +SH +cat >"$work/bin/curl" <<'SH' +#!/usr/bin/env bash +set -euo pipefail +[[ "$*" == *"--proto =https --tlsv1.2"* && "$*" != *insecure* ]] +if [ "${MODE:-}" = public ]; then printf '503'; else printf '200'; fi +SH +chmod +x "$work/bin/aws" "$work/bin/docker" "$work/bin/curl" +PATH="$work/bin:$PATH" FIXTURES="$work" bash "$guard" collect "$work/reviewed.json" "$work/inputs" "$work/collected" +check "$work/collected/live.json" +PATH="$work/bin:$PATH" FIXTURES="$work" MODE=final bash "$guard" collect-final "$work/reviewed.json" "$work/inputs" "$work/final-collected" +for mode in account api-failure manifest public; do + if PATH="$work/bin:$PATH" FIXTURES="$work" MODE=$mode bash "$guard" collect "$work/reviewed.json" "$work/inputs" "$work/$mode" 2>/dev/null; then + echo "Recovery collector accepted failed read-only evidence: $mode" >&2; exit 1 + fi + [ ! -e "$work/$mode/live.json" ] +done +if PATH="$work/bin:$PATH" FIXTURES="$work" bash "$guard" collect "$work/reviewed.json" "$work/inputs" "$work/collected" 2>/dev/null; then + echo 'Recovery collector overwrote an earlier collection' >&2; exit 1 +fi +if bash "$guard" apply 2>/dev/null; then echo 'Live collector accepted execution' >&2; exit 1; fi +echo 'Recovery live service, TLS, traffic, health and platform checks passed' diff --git a/.github/scripts/runtime-tls-recovery-workflow.test.sh b/.github/scripts/runtime-tls-recovery-workflow.test.sh new file mode 100755 index 000000000..dd64c8379 --- /dev/null +++ b/.github/scripts/runtime-tls-recovery-workflow.test.sh @@ -0,0 +1,31 @@ +#!/usr/bin/env bash +set -euo pipefail +cd "$(dirname "$0")/../.." +ruby -ryaml <<'RUBY' +workflow = YAML.load_file('.github/workflows/runtime-tls-recovery.yml') +jobs = workflow.fetch('jobs') +plan, apply, redeploy, verify = jobs.values_at('plan', 'apply', 'redeploy', 'verify') +raise 'plan must be manual and depend on offline checks' unless plan['if'] == "github.event_name == 'workflow_dispatch'" && plan['needs'] == 'check' +raise 'plan must use the read-only environment' unless plan['environment'] == 'aws-infrastructure-plan' +entry = plan.fetch('steps').first +raise 'explicit enablement and new main run are required' unless entry.fetch('run').include?('[ "$RECOVERY_ENABLED" = true ]') && entry.fetch('run').include?('[ "$GITHUB_RUN_ATTEMPT" = 1 ]') && entry.fetch('run').include?('[ "$GITHUB_REF" = refs/heads/main ]') +raise 'apply must follow plan approval' unless apply['needs'] == 'plan' && apply['environment'] == 'aws-infrastructure-approval' +raise 'apply must compare the exact plan approval digest' unless apply['steps'].any? { |s| s.dig('env', 'APPROVED_DIGEST') == '${{ needs.plan.outputs.digest }}' } +[apply, verify].each do |job| + raise 'production serialization must be retained' unless job.dig('concurrency', 'group') == 'aws-production' && job.dig('concurrency', 'cancel-in-progress') == false +end +raise 'redeploy must follow both plan and apply' unless redeploy['needs'].sort == ['apply', 'plan'] +raise 'redeploy must use the normal local workflow' unless redeploy['uses'] == './.github/workflows/deploy-aws.yml' +expected = {'tag'=>'${{ needs.plan.outputs.release }}', 'mode'=>'redeploy', 'services'=>'all', 'fleet'=>false, 'require_attestation'=>true, 'bake_seconds'=>'300'} +raise 'same release, all services, provenance and full bakes are required without fleet or secret-drop overrides' unless redeploy['with'] == expected +raise 'final verification must follow redeploy' unless verify['needs'] == 'redeploy' && verify['environment'] == 'aws-infrastructure-plan' +jobs.each_value do |job| + raise 'recovery cannot ignore job failures' if job['continue-on-error'] + (job['steps'] || []).each { |step| raise 'recovery cannot ignore step failures' if step['continue-on-error'] } +end +deploy = YAML.load_file('.github/workflows/deploy-aws.yml') +call = (deploy['on'] || deploy[true]).fetch('workflow_call') +raise 'existing deployment defaults must be retained' unless call.dig('inputs', 'bake_seconds', 'default') == '' +raise 'dropped-secret allowance remains disabled by default' if call.fetch('inputs').key?('allow_dropped_secrets') +puts 'Recovery workflow approval, sequencing, deployment and default compatibility checks passed' +RUBY diff --git a/.github/scripts/runtime-tls-recovery.sh b/.github/scripts/runtime-tls-recovery.sh new file mode 100755 index 000000000..af515e486 --- /dev/null +++ b/.github/scripts/runtime-tls-recovery.sh @@ -0,0 +1,89 @@ +#!/usr/bin/env bash +# Read-only validators for a separately reviewed hosted TLS cleanup recovery. +set -euo pipefail + +check_baseline() { + jq -e ' + def group_identity: {TargetGroupName, TargetGroupArn, Protocol, Port, VpcId}; + . as $baseline | + .account == "925323749693" and .region == "us-east-1" and + (.state.lineage | type == "string" and test("^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$")) and + (.state.serial | type == "number" and . >= 0 and floor == .) and + (.state.versionId | type == "string" and length > 0 and . != "null" and (test("[\\r\\n]") | not)) and + (.state.sha256 | type == "string" and test("^[a-f0-9]{64}$")) and + (.httpGroups | type == "array" and length == 4) and + ([.httpGroups[].TargetGroupName] | sort) == + (["backend", "forms", "tracking", "realtime"] | map("warmbly-production-" + .) | sort) and + ([.httpGroups[].TargetGroupArn] | unique | length == 4) and + ([.httpGroups[].VpcId] | unique | length == 1) and + all(.httpGroups[]; + .Protocol == "HTTP" and + (.Port | type == "number" and . > 0 and . <= 65535 and floor == .) and + (.VpcId | type == "string" and test("^vpc-[a-f0-9]+$")) and + .TargetGroupArn == ("arn:aws:elasticloadbalancing:us-east-1:925323749693:targetgroup/" + .TargetGroupName + "/" + (.TargetGroupArn | split("/")[-1])) and + (.TargetGroupArn | split("/")[-1] | test("^[a-f0-9]{16}$")) and + (.LoadBalancerArns | type == "array" and length == 0) and + (.targets | type == "array" and length == 0)) and + (.state.httpGroups | type == "array" and length == 4) and + (.state.httpGroups | map(group_identity) | sort_by(.TargetGroupName)) == + ($baseline.httpGroups | map(group_identity) | sort_by(.TargetGroupName)) + ' "$1" >/dev/null || { echo 'Recovery requires four identified, drained HTTP groups matching reviewed state' >&2; return 1; } +} + +check_state() { + check_baseline "$2" + local digest + digest=$(sha256sum "$1" | cut -d' ' -f1) + [ "$digest" = "$(jq -r '.state.sha256' "$2")" ] || { echo 'Recovery state bytes differ from the reviewed hash' >&2; return 1; } + jq -e --slurpfile baseline "$2" ' + .version == 4 and .lineage == $baseline[0].state.lineage and .serial == $baseline[0].state.serial and + ([.resources[] | select(.mode == "managed" and .type == "aws_lb_target_group" and .name == "service")] as $resources | + [$resources[].instances[] | { + key:.index_key, deposed:.deposed, status:.status, + id:.attributes.id, TargetGroupArn:.attributes.arn, TargetGroupName:.attributes.name, + Protocol:.attributes.protocol, Port:.attributes.port, VpcId:.attributes.vpc_id + }] as $groups | + ($resources | length == 1) and + all($resources[]; (.module == null) and (.instances | type == "array" and length == 4)) and + ($groups | map(.key) | sort) == (["backend", "forms", "tracking", "realtime"] | sort) and + all($groups[]; + . as $group | .deposed == null and .status == null and .id == .TargetGroupArn and + any($baseline[0].state.httpGroups[]; + .TargetGroupName == ("warmbly-production-" + $group.key) and + .TargetGroupArn == $group.TargetGroupArn and .TargetGroupName == $group.TargetGroupName and + .Protocol == $group.Protocol and .Port == $group.Port and .VpcId == $group.VpcId))) + ' "$1" >/dev/null || { echo 'Recovery state identity differs from the reviewed baseline' >&2; return 1; } +} + +check_plan() { + check_baseline "$2" + jq -e --slurpfile baseline "$2" ' + (.resource_changes | type == "array") and + ( + [.resource_changes[]? | select(.change.actions != ["no-op"] and .change.actions != ["read"])] as $changes | + ($baseline[0].httpGroups | map({ + address:("aws_lb_target_group.service[\"" + (.TargetGroupName | ltrimstr("warmbly-production-")) + "\"]"), + group:. + })) as $expected | + ($changes | map(.address) | sort) == ($expected | map(.address) | sort) and + all($changes[]; + . as $change | + .change.actions == ["delete"] and (.change | has("after")) and .change.after == null and + any($expected[]; + .address == $change.address and + $change.change.before.arn == .group.TargetGroupArn and + $change.change.before.id == .group.TargetGroupArn and + $change.change.before.name == .group.TargetGroupName and + $change.change.before.protocol == .group.Protocol and + $change.change.before.port == .group.Port and + $change.change.before.vpc_id == .group.VpcId)) and + ([.resource_drift[]? | select(.change.actions != ["no-op"])] | length == 0)) + ' "$1" >/dev/null || { echo 'Recovery plan must contain only the four reviewed HTTP group deletions without drift' >&2; return 1; } +} + +case "${1:-}" in + check-baseline) check_baseline "${2:?}" ;; + check-state) check_state "${2:?}" "${3:?}" ;; + check-plan) check_plan "${2:?}" "${3:?}" ;; + *) echo 'Only read-only recovery validation is supported' >&2; exit 1 ;; +esac diff --git a/.github/scripts/runtime-tls-recovery.test.sh b/.github/scripts/runtime-tls-recovery.test.sh new file mode 100755 index 000000000..a172b1e78 --- /dev/null +++ b/.github/scripts/runtime-tls-recovery.test.sh @@ -0,0 +1,115 @@ +#!/usr/bin/env bash +set -euo pipefail +cd "$(dirname "$0")/../.." +work=$(mktemp -d) +trap 'rm -rf "$work"' EXIT +guard=.github/scripts/runtime-tls-recovery.sh +jq -n ' + ["backend", "forms", "tracking", "realtime"] | + map({TargetGroupName:("warmbly-production-" + .), + TargetGroupArn:("arn:aws:elasticloadbalancing:us-east-1:925323749693:targetgroup/warmbly-production-" + . + "/0123456789abcdef"), + Protocol:"HTTP",Port:8080,VpcId:"vpc-0123456789abcdef0",LoadBalancerArns:[],targets:[]}) as $groups | + {account:"925323749693",region:"us-east-1",httpGroups:$groups, + state:{lineage:"01234567-89ab-cdef-0123-456789abcdef",serial:1,versionId:"reviewed-version",sha256:("a"*64),httpGroups:$groups}} +' >"$work/baseline.json" +jq '{resource_changes:[.httpGroups[] | { + address:("aws_lb_target_group.service[\"" + (.TargetGroupName | ltrimstr("warmbly-production-")) + "\"]"), + change:{actions:["delete"],after:null,before:{arn:.TargetGroupArn,id:.TargetGroupArn,name:.TargetGroupName,protocol:.Protocol,port:.Port,vpc_id:.VpcId}} +}]}' "$work/baseline.json" >"$work/plan.json" +bash "$guard" check-baseline "$work/baseline.json" +bash "$guard" check-plan "$work/plan.json" "$work/baseline.json" +jq '.httpGroups |= reverse' "$work/baseline.json" >"$work/reordered-baseline.json" +jq '.resource_changes |= reverse | + .resource_changes += [{address:"data.aws_caller_identity.current",change:{actions:["read"]}}]' "$work/plan.json" >"$work/reordered-plan.json" +bash "$guard" check-plan "$work/reordered-plan.json" "$work/reordered-baseline.json" +jq '{version:4,lineage:.state.lineage,serial:.state.serial,resources:[{ + mode:"managed",type:"aws_lb_target_group",name:"service",instances:[.state.httpGroups[] | { + index_key:(.TargetGroupName | ltrimstr("warmbly-production-")), + attributes:{arn:.TargetGroupArn,id:.TargetGroupArn,name:.TargetGroupName,protocol:.Protocol,port:.Port,vpc_id:.VpcId} + }] +}]}' "$work/baseline.json" >"$work/state.json" +digest=$(sha256sum "$work/state.json" | cut -d' ' -f1) +jq --arg digest "$digest" '.state.sha256=$digest' "$work/baseline.json" >"$work/state-baseline.json" +bash "$guard" check-state "$work/state.json" "$work/state-baseline.json" +jq -c . "$work/state.json" >"$work/reformatted-state.json" +if bash "$guard" check-state "$work/reformatted-state.json" "$work/state-baseline.json" 2>/dev/null; then + echo 'Recovery accepted changed state bytes under the original hash' >&2 + exit 1 +fi +jq '.resources[0].instances |= reverse | + .resources += [{mode:"managed",type:"aws_ecs_service",name:"service",instances:[]}]' \ + "$work/state.json" >"$work/reordered-state.json" +digest=$(sha256sum "$work/reordered-state.json" | cut -d' ' -f1) +jq --arg digest "$digest" '.state.sha256=$digest' "$work/baseline.json" >"$work/reordered-state-baseline.json" +bash "$guard" check-state "$work/reordered-state.json" "$work/reordered-state-baseline.json" +if bash "$guard" check-state "$work/state.json" "$work/baseline.json" 2>/dev/null; then + echo 'Recovery accepted state bytes with a different reviewed hash' >&2 + exit 1 +fi +for change in '.version=3' '.lineage="11111111-89ab-cdef-0123-456789abcdef"' '.serial+=1' \ + '.resources=[]' '.resources+=.resources' \ + '.resources[0].module="module.other"' '.resources[0].mode="data"' \ + '.resources[0].instances|=.[1:]' \ + '.resources[0].instances[0]=.resources[0].instances[1]' \ + '.resources[0].instances[0].index_key="other"' \ + '.resources[0].instances[0].deposed="old"' '.resources[0].instances[0].status="tainted"' \ + '.resources[0].instances[0].attributes.id="different"' \ + '.resources[0].instances[0].attributes.arn="different"' \ + '.resources[0].instances[0].attributes.name="different"' \ + '.resources[0].instances[0].attributes.protocol="HTTPS"' \ + '.resources[0].instances[0].attributes.port=465' \ + '.resources[0].instances[0].attributes.vpc_id="vpc-11111111"'; do + jq "$change" "$work/state.json" >"$work/changed-state.json" + digest=$(sha256sum "$work/changed-state.json" | cut -d' ' -f1) + jq --arg digest "$digest" '.state.sha256=$digest' "$work/baseline.json" >"$work/changed-state-baseline.json" + if bash "$guard" check-state "$work/changed-state.json" "$work/changed-state-baseline.json" 2>/dev/null; then + echo "Recovery accepted different state identities despite a matching file hash: $change" >&2 + exit 1 + fi +done +for change in '.account="123456789012"' '.region="us-west-2"' \ + '.httpGroups|=.[1:]' '.httpGroups[0]=.httpGroups[1]' \ + '.httpGroups[0].LoadBalancerArns=["still-referenced"]' \ + '.httpGroups[0].targets=[{Target:{Id:"still-registered"}}]' \ + '.httpGroups[0].Protocol="HTTPS"' '.httpGroups[0].Port=0' \ + '.httpGroups[0].VpcId="vpc-11111111"' \ + '.httpGroups[0].TargetGroupArn="arn:aws:elasticloadbalancing:us-east-1:123456789012:targetgroup/warmbly-production-backend/0123456789abcdef"' \ + '.httpGroups[0].targets=null' '.httpGroups[0].LoadBalancerArns=null' \ + '.state.httpGroups[0].TargetGroupArn="changed"' '.state.httpGroups|=.[1:]' \ + '.state.versionId=""' '.state.versionId="null"' '.state.sha256=""' \ + '.state.lineage=null' '.state.lineage=("-"*36)' '.state.serial=-1'; do + jq "$change" "$work/baseline.json" >"$work/changed.json" + if bash "$guard" check-plan "$work/plan.json" "$work/changed.json" 2>/dev/null; then + echo "Recovery accepted an invalid baseline: $change" >&2 + exit 1 + fi +done +for change in '.resource_changes=[]' '.resource_changes|=.[1:]' \ + '.resource_changes[0]=.resource_changes[1]' \ + '.resource_changes[0].change.actions=["no-op"]' \ + '.resource_changes[0].change.actions=["delete","create"]' \ + '.resource_changes[0].change.after={}' \ + 'del(.resource_changes[0].change.after)' \ + '.resource_changes[0].change.before.arn="changed"' \ + '.resource_changes[0].change.before.id="changed"' \ + '.resource_changes[0].change.before.port=465' \ + '.resource_changes[0].change.before.protocol="HTTPS"' \ + '.resource_changes[0].change.before.name="different"' \ + '.resource_changes[0].change.before.vpc_id="vpc-11111111"' \ + '.resource_changes[0].address="aws_lb_target_group.service[\"consumer\"]"' \ + '.resource_changes += [{address:"aws_ecs_service.service[\"backend\"]",change:{actions:["update"]}}]' \ + '.resource_changes += [{address:"aws_vpc_security_group_ingress_rule.internal_backend[0]",change:{actions:["delete"]}}]' \ + '.resource_drift=[{address:"aws_lb_target_group.service[\"backend\"]",change:{actions:["update"]}}]'; do + jq "$change" "$work/plan.json" >"$work/changed.json" + if bash "$guard" check-plan "$work/changed.json" "$work/baseline.json" 2>/dev/null; then + echo "Recovery accepted a different cleanup plan: $change" >&2 + exit 1 + fi +done +for action in plan apply delete; do + if bash "$guard" "$action" 2>/dev/null; then + echo 'Read-only recovery validator accepted an execution action' >&2 + exit 1 + fi +done +echo 'Read-only TLS recovery identity and scope guards passed' diff --git a/.github/scripts/runtime-tls.sh b/.github/scripts/runtime-tls.sh new file mode 100755 index 000000000..f90c105f2 --- /dev/null +++ b/.github/scripts/runtime-tls.sh @@ -0,0 +1,198 @@ +#!/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 http_groups: + ["backend", "forms", "tracking", "realtime"] | + map("aws_lb_target_group.service[\"" + . + "\"]") | sort; + 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 | + ($stage != "on" or + ([$changes[] | select(.change.actions == ["delete"] and + (.address | test("^aws_lb_target_group\\.service" + service + "$"))) | .address] | sort) == http_groups) and + 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_lb_target_group.service \ + -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..c538b2b06 --- /dev/null +++ b/.github/scripts/runtime-tls.test.sh @@ -0,0 +1,143 @@ +#!/usr/bin/env bash +set -euo pipefail +cd "$(dirname "$0")/../.." +work=$(mktemp -d) +trap 'rm -rf "$work"' EXIT +complete_cleanup() { + jq ' + [.resource_changes[].address] as $present | + .resource_changes += [ ["backend", "forms", "tracking", "realtime"][] | + {address:("aws_lb_target_group.service[\"" + . + "\"]"),change:{actions:["delete"]}} | + select(.address as $address | $present | index($address) == null)] + ' "$1" >"$work/complete.json" + mv "$work/complete.json" "$1" +} +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 [ "$stage" = on ]; then complete_cleanup "$work/plan.json"; fi + 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 + cp "$work/plan.json" "$work/registration-$stage.json" + if [ "$stage" = on ]; then complete_cleanup "$work/registration-$stage.json"; fi + if bash .github/scripts/runtime-tls.sh check-plan "$work/registration-$stage.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/loopback-only.json" +cp "$work/loopback-only.json" "$work/plan.json" +complete_cleanup "$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/loopback-only.json" route 2>/dev/null; then + echo 'Loopback-only listener accepted before HTTP registrations drained' >&2 + exit 1 +fi +jq '.resource_changes |= map(select(.address | startswith("aws_ecs_task_definition"))) | + .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 +jq -n '{resource_changes:[]}' >"$work/deletions.json" +complete_cleanup "$work/deletions.json" +bash .github/scripts/runtime-tls.sh check-plan "$work/deletions.json" on +for change in '.resource_changes=[]' '.resource_changes|=.[1:]' \ + '.resource_changes[0].change.actions=["no-op"]' \ + '.resource_changes[0].change.actions=["delete","create"]' \ + '.resource_changes[0].address="aws_lb_target_group.service[\"consumer\"]"'; do + jq "$change" "$work/deletions.json" >"$work/changed.json" + if bash .github/scripts/runtime-tls.sh check-plan "$work/changed.json" on 2>/dev/null; then + echo 'ON accepted without the exact four HTTP group deletions' >&2 + exit 1 + fi +done +echo 'Runtime TLS plan guards passed' diff --git a/.github/scripts/terraform-stack.sh b/.github/scripts/terraform-stack.sh index f321467ee..5165ad581 100755 --- a/.github/scripts/terraform-stack.sh +++ b/.github/scripts/terraform-stack.sh @@ -10,13 +10,15 @@ # # plan writes $WORK/.summary (one "action address" per line) and prints # safe, gated or none. Safe means only creates, in-place updates, and new -# revisions of task definitions, which keep their old revision. +# revisions of task definitions, excluding protected recovery evidence IAM changes. set -euo pipefail classify() { jq -r ' [.resource_changes[]? | select(.change.actions != ["no-op"] and .change.actions != ["read"])] as $c | if ($c | length) == 0 then "none" + elif any($c[]; .name == "tls_recovery_evidence" and + (.type == "aws_iam_role" or .type == "aws_iam_role_policy")) then "gated" elif any($c[]; (.change.actions | index("delete")) and ((.type == "aws_ecs_task_definition" and (.change.actions | length) == 2) | not)) then "gated" else "safe" end' "$1" diff --git a/.github/scripts/terraform-stack.test.sh b/.github/scripts/terraform-stack.test.sh new file mode 100755 index 000000000..d7f978dc8 --- /dev/null +++ b/.github/scripts/terraform-stack.test.sh @@ -0,0 +1,31 @@ +#!/usr/bin/env bash +set -euo pipefail +cd "$(dirname "$0")/../.." +work=$(mktemp -d) +trap 'rm -rf "$work"' EXIT +classifier=${CLASSIFIER:-.github/scripts/terraform-stack.sh} + +check() { + local expected=$1 type=$2 name=$3 actions=$4 + jq -n --arg type "$type" --arg name "$name" --argjson actions "$actions" \ + '{resource_changes:[{address:($type+"."+$name+"[0]"),type:$type,name:$name,change:{actions:$actions}}]}' >"$work/plan.json" + local actual + actual=$(bash "$classifier" classify "$work/plan.json") + if [ "$actual" != "$expected" ]; then + echo "Expected $expected for $type.$name $actions, received $actual" >&2 + exit 1 + fi +} + +for type in aws_iam_role aws_iam_role_policy; do + for actions in '["create"]' '["update"]' '["delete"]' '["delete","create"]'; do + check gated "$type" tls_recovery_evidence "$actions" + done + check none "$type" tls_recovery_evidence '["no-op"]' + check none "$type" tls_recovery_evidence '["read"]' +done +check safe aws_iam_role existing_role '["create"]' +check safe aws_ecs_task_definition service '["delete","create"]' +check gated aws_lb_target_group service '["delete"]' +check safe aws_cloudwatch_metric_alarm service '["update"]' +echo 'Protected evidence IAM changes require approval; existing plan classifications remain unchanged' diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index d49ec3d31..d69f402be 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1,8 +1,8 @@ name: CI +# main only receives what the merge queue already tested at the same commit, +# so the merge_group run is the gate and nothing reruns it after the merge. on: - push: - branches: [main] pull_request: branches: [main] merge_group: @@ -69,8 +69,10 @@ jobs: aws-deployment: - '.github/workflows/ci.yml' - '.github/workflows/deploy-aws.yml' + - '.github/workflows/configure-backend-aws.yml' - '.github/workflows/rotate-keys.yml' - '.github/scripts/aws-deploy*.cjs' + - '.github/scripts/aws-backend-config*.cjs' - '.github/scripts/aws-rotate*.cjs' - '.github/aws-deploy/**' - 'deploy/terraform/aws/runtime/rotate/**' @@ -109,6 +111,8 @@ jobs: - 'scripts/check-cli-installer.sh' - 'scripts/build-cli.sh' pages: + - '.github/workflows/static-assets.yml' + - 'deploy/cloudflare/**' - '.github/scripts/pages-*' - '.github/workflows/release.yml' - '.github/workflows/ci.yml' @@ -131,7 +135,7 @@ jobs: with: node-version: "22" - name: Check production configuration import - run: node --test .github/scripts/pages-*.test.mjs + run: node --test .github/scripts/pages-*.test.mjs deploy/cloudflare/static-edge.test.mjs migrations-ci: name: Migrations @@ -223,10 +227,9 @@ jobs: if: matrix.suite == 'lint' run: go build -tags kafka ./... - - name: Run tests with coverage + - name: Run tests if: matrix.suite == 'unit' - run: | - go test -race -coverprofile=coverage.out -covermode=atomic ./... + run: go test -race ./... - name: Prepare regression database if: startsWith(matrix.suite, 'live-') @@ -241,8 +244,8 @@ jobs: WARMBLY_TEST_DB: postgres://warmbly:warmbly@127.0.0.1:5432/warmbly_test?sslmode=disable run: | set -o pipefail - go test -race -v -p 1 ./internal/repository ./internal/app/analytics -run '^TestLive(WarmupPartnerCountsMatchIndividualCandidates|WarmupSummariesMatchIndividualReads|LinkedMailboxStatusBatchPreservesDetails|WarmupPartnerWeekCacheMatchesExactReadAndKeepsTheCapLive|WarmupPartnerWeekCacheRefreshesDetachedAndServesStale|WarmupPartnerCandidatesCarryReciprocityAndHonourTheCap|AccountStatusPageMatchesSingleReadsInBoundedQueries|WarmupOffMailboxReceivesNothing|WarmupPauseRetiresIncomingWork|WarmupInboxHasRoomMatchesTheReservation)$' -count=1 | tee linked-mailbox-batch.log - for test in TestLiveWarmupPartnerCountsMatchIndividualCandidates TestLiveWarmupSummariesMatchIndividualReads TestLiveLinkedMailboxStatusBatchPreservesDetails TestLiveWarmupPartnerWeekCacheMatchesExactReadAndKeepsTheCapLive TestLiveWarmupPartnerWeekCacheRefreshesDetachedAndServesStale TestLiveWarmupPartnerCandidatesCarryReciprocityAndHonourTheCap TestLiveAccountStatusPageMatchesSingleReadsInBoundedQueries TestLiveWarmupOffMailboxReceivesNothing TestLiveWarmupPauseRetiresIncomingWork TestLiveWarmupInboxHasRoomMatchesTheReservation; do + go test -race -v -p 1 ./internal/repository ./internal/app/analytics -run '^TestLive(WarmupPartnerCountsMatchIndividualCandidates|WarmupSummariesMatchIndividualReads|LinkedMailboxStatusBatchPreservesDetails|WarmupPartnerWeekCacheMatchesExactReadAndKeepsTheCapLive|WarmupPartnerWeekCacheRefreshesDetachedAndServesStale|WarmupPartnerCandidatesCarryReciprocityAndHonourTheCap|AccountStatusPageMatchesSingleReadsInBoundedQueries|WarmupOffMailboxReceivesNothing|WarmupPauseRetiresIncomingWork|WarmupReservationHoldsEachTierToItsShare|WarmupReplyIsAdmittedToAFullInbox|WarmupRepliesLeaveTheNewThreadCapUntouched|OwedRepliesContinueTheDeepestConversationFirst)$' -count=1 | tee linked-mailbox-batch.log + for test in TestLiveWarmupPartnerCountsMatchIndividualCandidates TestLiveWarmupSummariesMatchIndividualReads TestLiveLinkedMailboxStatusBatchPreservesDetails TestLiveWarmupPartnerWeekCacheMatchesExactReadAndKeepsTheCapLive TestLiveWarmupPartnerWeekCacheRefreshesDetachedAndServesStale TestLiveWarmupPartnerCandidatesCarryReciprocityAndHonourTheCap TestLiveAccountStatusPageMatchesSingleReadsInBoundedQueries TestLiveWarmupOffMailboxReceivesNothing TestLiveWarmupPauseRetiresIncomingWork TestLiveWarmupReservationHoldsEachTierToItsShare TestLiveWarmupReplyIsAdmittedToAFullInbox TestLiveWarmupRepliesLeaveTheNewThreadCapUntouched TestLiveOwedRepliesContinueTheDeepestConversationFirst; do grep -q -- "--- PASS: $test " linked-mailbox-batch.log done if grep -q -- '--- SKIP:' linked-mailbox-batch.log; then exit 1; fi @@ -258,6 +261,18 @@ jobs: grep -q '^--- PASS: TestLiveCampaignLoadingLogsKeepHistoryWithoutCustomerAlerts ' campaign-reconnect.log if grep -q -- '--- SKIP:' campaign-reconnect.log; then exit 1; fi + - name: Mailbox push channels and fleet usage (PostgreSQL) + if: matrix.suite == 'live-1' + env: + WARMBLY_TEST_DB: postgres://warmbly:warmbly@127.0.0.1:5432/warmbly_test?sslmode=disable + run: | + set -o pipefail + go test -race -v -p 1 ./internal/repository ./internal/app/fleetmetrics -run '^TestLive(MailboxPushChannelsRoundTripAndScopeToTheOwner|WakeTargetsSkipWorkersThatCannotActOnAWake|ReadTakesMemoryFromHeartbeats)$' -count=1 | tee mailbox-push.log + for test in TestLiveMailboxPushChannelsRoundTripAndScopeToTheOwner TestLiveWakeTargetsSkipWorkersThatCannotActOnAWake TestLiveReadTakesMemoryFromHeartbeats; do + grep -q -- "--- PASS: $test " mailbox-push.log + done + if grep -q -- '--- SKIP:' mailbox-push.log; then exit 1; fi + - name: Contact campaign empty-step regression (PostgreSQL) if: matrix.suite == 'live-1' env: @@ -283,6 +298,13 @@ jobs: run: | go test -race -p 1 ./internal/repository ./internal/scheduler ./internal/tasks -run '^TestLive(MailboxSendClaim(AdmitsOnePerGap|WaitsOutAReservedSend)|BookedSendsLeaveOutCampaignWakeups|ParkedCampaignDoesNotThrottleItsPoolMate|BookedSendsStillSpaceTheCampaign|ClaimedMailboxIsPassedOver|CampaignsSharingAMailboxSendOncePerGap|LostMailboxClaimReschedulesWithoutSending)$' -count=1 + - name: Postgres queue claim regressions (PostgreSQL) + if: matrix.suite == 'live-3' + env: + WARMBLY_TEST_DB: postgres://warmbly:warmbly@127.0.0.1:5432/warmbly_test?sslmode=disable + run: | + go test -race -p 1 ./internal/repository -run '^TestLive(ConcurrentDispatchersNeverClaimTheSameTask|SendResultEffectsBatchClaimsDeliverEachEffectOnce|CRMClaimTakesDueAndLapsedJobsOnce)$' -count=1 + - name: Invited signup atomic provisioning regressions (PostgreSQL) if: matrix.suite == 'live-1' env: @@ -345,8 +367,8 @@ jobs: WARMBLY_TEST_DB: postgres://warmbly:warmbly@127.0.0.1:5432/warmbly_test?sslmode=disable run: | set -o pipefail - go test -race ./internal/repository -run '^TestLive(Monitoring|LastWarmupSendFailure|PersistentMailboxLoadingFailure|DispatchRetry|LineageQueueRevisions|AdminPlatformOverview|WarmupRecoversOldPreparation|WarmupPreparationRecoveryRetains|WarmupFilingRequiresAcknowledgement|WarmupFilingAuthority|WarmupTimeWindow|WarmupInvalidWindow|StoppedRecipientIsNeverAddressed)' -count=1 - go test -race -v ./internal/tasks -run '^Test(LiveWarmup(SafetyHoldReschedules|Recovery|UnknownRetirement|TaskDoesNotApplyResults|DispatchDefersInvalidHours)|WarmupSenderDistinguishes)' -count=1 | tee warmup-recovery.log + go test -race ./internal/repository -run '^TestLive(Monitoring|LastWarmupSendFailure|PersistentMailboxLoadingFailure|DispatchRetry|LineageQueueRevisions|ReplyShare|AdminPlatformOverview|WarmupRecoversOldPreparation|WarmupPreparationRecoveryRetains|WarmupFilingRequiresAcknowledgement|WarmupFilingAuthority|WarmupTimeWindow|WarmupInvalidWindow|StoppedRecipientIsNeverAddressed)' -count=1 + go test -race -v ./internal/tasks -run '^Test(LiveWarmup(SafetyHoldReschedules|Recovery|UnknownRetirement|TaskDoesNotApplyResults|DispatchDefersInvalidHours|ReplyShare)|WarmupSenderDistinguishes)' -count=1 | tee warmup-recovery.log if grep -q -- '--- SKIP: TestLiveWarmupUnknownRetirement' warmup-recovery.log; then exit 1; fi for test in TestLiveWarmupUnknownRetirementPreservesEvidenceAndFencesReplayOnce TestLiveWarmupUnknownRetirementAllowsDistinctNewSendAndKeepsCooldown TestLiveWarmupUnknownRetirementAndDefinitiveResultSerialize TestLiveWarmupUnknownRetirementSkipsProtectedRowsWithoutStarvingLaterMailboxes TestLiveWarmupUnknownRetirementReconcilerSeedsOnceAndClearsActiveWarnings; do grep -q -- "--- PASS: $test " warmup-recovery.log || exit 1 @@ -558,6 +580,8 @@ jobs: grep -q "^--- PASS: $test " mailbox-transport-runtime.log done if grep -q -- '--- SKIP:' mailbox-transport-runtime.log; then exit 1; fi + go test -race -v -p 1 ./internal/repository -run '^TestLiveAuthenticatorStepRequiresActiveEnrollment$' -count=1 | tee authenticator-verification.log + grep -q '^--- PASS: TestLiveAuthenticatorStepRequiresActiveEnrollment ' authenticator-verification.log grep -q '^--- PASS: TestLiveImportMailTransportWholeArchiveSendResultLockOrder ' mailbox-transport-runtime.log for logfile in mailbox-transport-upgrade.log mailbox-transport-runtime.log; do test "$(grep -c '^=== RUN' "$logfile")" -gt 0 @@ -621,7 +645,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' @@ -633,17 +657,6 @@ jobs: if: matrix.suite == 'live-2' run: go test -race -tags kafka ./internal/infrastructure/codec/ ./internal/infrastructure/kafka/ ./internal/infrastructure/eventbus/ - # fail_ci_if_error does not cover the uploader crashing before it runs - # (a TLS handshake failure to Codecov failed jobs whose tests passed). - - name: Upload coverage - if: matrix.suite == 'unit' - uses: codecov/codecov-action@v4 - continue-on-error: true - with: - files: coverage.out - flags: go - fail_ci_if_error: false - web-ci: name: Web CI needs: changes @@ -1016,7 +1029,7 @@ jobs: - name: Check deploy, rollback and rotation gates env: NODE_PATH: ${{ github.workspace }}/.github/aws-deploy/node_modules - run: node --test .github/scripts/aws-deploy.test.cjs .github/scripts/aws-rotate.test.cjs deploy/terraform/aws/runtime/rotate/rotate.test.cjs + run: node --test .github/scripts/aws-deploy.test.cjs .github/scripts/aws-backend-config.test.cjs .github/scripts/aws-rotate.test.cjs deploy/terraform/aws/runtime/rotate/rotate.test.cjs ci-status: name: CI Status diff --git a/.github/workflows/configure-backend-aws.yml b/.github/workflows/configure-backend-aws.yml new file mode 100644 index 000000000..07657c851 --- /dev/null +++ b/.github/workflows/configure-backend-aws.yml @@ -0,0 +1,89 @@ +name: Configure AWS backend + +on: + workflow_dispatch: + inputs: + tag: + description: Published stable release already running on every backend (v0.6.75 or newer) + required: true + type: string + expected_task_definition: + description: Exact currently running backend task definition ARN + required: true + type: string + expected_backend_tasks: + description: JSON array of every current RUNNING backend task ARN from the read-only preflight + required: true + type: string + attachment_download_proxy: + description: Serve private campaign attachments through the backend download route + required: true + type: boolean + +permissions: + contents: read + +jobs: + configure: + runs-on: ubuntu-latest + timeout-minutes: 45 + environment: aws-production + concurrency: + group: aws-production + cancel-in-progress: false + permissions: + contents: read + attestations: read + id-token: write + steps: + - uses: actions/checkout@v4 + with: + persist-credentials: false + fetch-depth: 0 + - name: Verify main and the published release provenance + env: + GH_TOKEN: ${{ github.token }} + TAG: ${{ inputs.tag }} + ENABLED: ${{ vars.AWS_DEPLOY_ENABLED }} + run: | + set -euo pipefail + [ "$GITHUB_REF" = refs/heads/main ] && [ "$ENABLED" = true ] || { + echo "::error::Backend configuration requires main and AWS_DEPLOY_ENABLED=true"; exit 1; } + printf '%s\n' "$TAG" | grep -Eq '^v[0-9]+\.[0-9]+\.[0-9]+$' || { + echo "::error::A stable release tag is required"; exit 1; } + git merge-base --is-ancestor "refs/tags/$TAG^{commit}" origin/main + state=$(gh release view "$TAG" --json isDraft,isPrerelease --jq '"\(.isDraft) \(.isPrerelease)"') + [ "$state" = "false false" ] || { echo "::error::A published stable release is required"; exit 1; } + mkdir -p /tmp/backend-config-release + gh release download "$TAG" --pattern images.json --dir /tmp/backend-config-release + manifest=/tmp/backend-config-release/images.json + jq -e --arg tag "$TAG" '.tag == $tag and .registry == "ghcr.io/warmbly/warmbly"' "$manifest" >/dev/null + registry=$(jq -r .registry "$manifest") + for key in backend backend-kafka consumer consumer-kafka worker worker-kafka forms tracking tracking-kafka realtime; do + digest=$(jq -er --arg key "$key" '.images[$key] | select(test("^sha256:[a-f0-9]{64}$"))' "$manifest") + gh attestation verify "oci://$registry/${key%-kafka}@$digest" \ + --repo "$GITHUB_REPOSITORY" \ + --signer-workflow "$GITHUB_REPOSITORY/.github/workflows/release.yml" \ + --source-ref "refs/tags/$TAG" >/dev/null + echo "verified provenance of $key" + done + - uses: actions/setup-node@v4 + with: + node-version: "22" + - name: Install deployment client + run: npm ci --prefix .github/aws-deploy --omit=dev --ignore-scripts --no-audit --no-fund + - uses: aws-actions/configure-aws-credentials@v4 + with: + role-to-assume: ${{ vars.AWS_DEPLOY_ROLE_ARN }} + aws-region: us-east-1 + - name: Configure and bake the backend + env: + NODE_PATH: ${{ github.workspace }}/.github/aws-deploy/node_modules + AWS_ECS_CLUSTER: ${{ vars.AWS_ECS_CLUSTER }} + AWS_ECS_SERVICE_PREFIX: ${{ vars.AWS_ECS_SERVICE_PREFIX }} + DEPLOY_TAG: ${{ inputs.tag }} + DEPLOY_IMAGES_JSON: /tmp/backend-config-release/images.json + CONFIG_EXPECTED_TASK_DEFINITION: ${{ inputs.expected_task_definition }} + CONFIG_EXPECTED_TASKS: ${{ inputs.expected_backend_tasks }} + CONFIG_ATTACHMENT_DOWNLOAD_PROXY: ${{ inputs.attachment_download_proxy }} + run: node .github/scripts/aws-backend-config.cjs diff --git a/.github/workflows/configure-origin-alb-aws.yml b/.github/workflows/configure-origin-alb-aws.yml new file mode 100644 index 000000000..56cb34b3d --- /dev/null +++ b/.github/workflows/configure-origin-alb-aws.yml @@ -0,0 +1,82 @@ +name: Configure AWS origin ALB policy + +on: + pull_request: + paths: + - '.github/workflows/configure-origin-alb-aws.yml' + - '.github/scripts/aws-origin-alb*' + workflow_dispatch: + inputs: + mode: + description: Plan only by default; apply or rollback consumes an exact private plan + type: choice + options: [plan, apply, rollback] + default: plan + required: true + plan_run_id: + description: Run ID that produced the reviewed private plan (apply and rollback only) + type: string + plan_version: + description: Exact private S3 plan version ID (apply and rollback only) + type: string + plan_sha256: + description: SHA-256 of the complete reviewed private plan (apply and rollback only) + type: string + +permissions: + contents: read + +jobs: + check: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + with: + persist-credentials: false + - uses: actions/setup-node@v4 + with: + node-version: "22" + - run: node --test .github/scripts/aws-origin-alb.test.cjs + - run: shellcheck .github/scripts/aws-origin-alb-workflow.test.sh + - run: bash .github/scripts/aws-origin-alb-workflow.test.sh + + configure: + needs: check + if: github.event_name == 'workflow_dispatch' + runs-on: ubuntu-latest + timeout-minutes: 15 + environment: aws-infrastructure + concurrency: + group: aws-production + cancel-in-progress: false + permissions: + contents: read + id-token: write + env: + ORIGIN_ALB_MODE: ${{ inputs.mode }} + ORIGIN_ALB_PLAN_RUN_ID: ${{ inputs.plan_run_id }} + ORIGIN_ALB_PLAN_VERSION: ${{ inputs.plan_version }} + ORIGIN_ALB_PLAN_SHA256: ${{ inputs.plan_sha256 }} + STATE_BUCKET: ${{ vars.AWS_TERRAFORM_STATE_BUCKET }} + APPLY_ROLE: ${{ vars.AWS_TERRAFORM_APPLY_ROLE_ARN }} + steps: + - uses: actions/checkout@v4 + with: + persist-credentials: false + - uses: actions/setup-node@v4 + with: + node-version: "22" + - name: Check main, ordinary role configuration and exact input scope + id: scope + env: + WORK: ${{ runner.temp }}/origin-alb-policy + run: node .github/scripts/aws-origin-alb.cjs session-policy + - uses: aws-actions/configure-aws-credentials@v4 + with: + role-to-assume: ${{ vars.AWS_TERRAFORM_APPLY_ROLE_ARN }} + aws-region: us-east-1 + inline-session-policy: ${{ steps.scope.outputs.policy }} + - name: Plan or execute the exact listener policy change + env: + WORK: ${{ runner.temp }}/origin-alb-policy + run: node .github/scripts/aws-origin-alb.cjs configure diff --git a/.github/workflows/coolify.yml b/.github/workflows/coolify.yml index 4d956cba5..f6e61a23b 100644 --- a/.github/workflows/coolify.yml +++ b/.github/workflows/coolify.yml @@ -12,8 +12,6 @@ on: - deploy/docker-compose.coolify.yml - deploy/check-coolify.sh - .github/workflows/coolify.yml - merge_group: - types: [checks_requested] permissions: contents: read diff --git a/.github/workflows/deploy-aws.yml b/.github/workflows/deploy-aws.yml index d83535e04..77ef77af1 100644 --- a/.github/workflows/deploy-aws.yml +++ b/.github/workflows/deploy-aws.yml @@ -22,6 +22,14 @@ 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 + bake_seconds: + description: Optional explicit service bake duration; empty retains the configured default + default: "" + type: string workflow_dispatch: inputs: tag: @@ -41,6 +49,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 +151,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/probe-origin-tls-aws.yml b/.github/workflows/probe-origin-tls-aws.yml new file mode 100644 index 000000000..c48f5d026 --- /dev/null +++ b/.github/workflows/probe-origin-tls-aws.yml @@ -0,0 +1,84 @@ +name: Probe AWS origin TLS + +on: + pull_request: + paths: + - '.github/workflows/probe-origin-tls-aws.yml' + - '.github/scripts/aws-origin-tls*' + - '.github/scripts/origin-tls-client*' + - '.github/scripts/aws-origin-alb.cjs' + workflow_dispatch: + +permissions: + contents: read + +jobs: + check: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + with: + persist-credentials: false + - uses: actions/setup-node@v4 + with: + node-version: "22" + - run: node --test .github/scripts/aws-origin-tls.test.cjs .github/scripts/origin-tls-client.test.cjs + - run: shellcheck .github/scripts/aws-origin-tls-workflow.test.sh + - run: bash .github/scripts/aws-origin-tls-workflow.test.sh + + probe: + needs: check + if: github.event_name == 'workflow_dispatch' + runs-on: ubuntu-latest + timeout-minutes: 25 + environment: aws-infrastructure + concurrency: + group: aws-production + cancel-in-progress: false + permissions: + contents: read + id-token: write + env: + STATE_BUCKET: ${{ vars.AWS_TERRAFORM_STATE_BUCKET }} + APPLY_ROLE: ${{ vars.AWS_TERRAFORM_APPLY_ROLE_ARN }} + steps: + - uses: actions/checkout@v4 + with: + persist-credentials: false + - uses: actions/setup-node@v4 + with: + node-version: "22" + - name: Check main and ordinary infrastructure configuration + id: scope + env: + WORK: ${{ runner.temp }}/origin-tls + run: node .github/scripts/aws-origin-tls.cjs session-policy + - uses: aws-actions/configure-aws-credentials@v4 + id: credentials + with: + role-to-assume: ${{ vars.AWS_TERRAFORM_APPLY_ROLE_ARN }} + aws-region: us-east-1 + unset-current-credentials: true + inline-session-policy: ${{ steps.scope.outputs.probe_policy }} + - name: Run disposable secretless TLS diagnostic + if: success() && steps.credentials.outcome == 'success' + timeout-minutes: 10 + env: + WORK: ${{ runner.temp }}/origin-tls + run: node .github/scripts/aws-origin-tls.cjs probe + - name: Acquire cleanup-only diagnostic credentials + if: always() && steps.scope.outcome == 'success' + timeout-minutes: 2 + uses: aws-actions/configure-aws-credentials@v4 + id: cleanup_credentials + with: + role-to-assume: ${{ vars.AWS_TERRAFORM_APPLY_ROLE_ARN }} + aws-region: us-east-1 + unset-current-credentials: true + inline-session-policy: ${{ steps.scope.outputs.cleanup_policy }} + - name: Stop, deregister and privately archive diagnostic evidence + if: always() && steps.cleanup_credentials.outcome == 'success' + timeout-minutes: 8 + env: + WORK: ${{ runner.temp }}/origin-tls + run: node .github/scripts/aws-origin-tls.cjs finish diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index d8645eac6..6ceaea378 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -657,3 +657,34 @@ jobs: --branch "$CLOUDFLARE_PAGES_PRODUCTION_BRANCH" \ --commit-hash "$GITHUB_SHA" \ --commit-message "$RELEASE_TAG" + + - name: Prepare optional static asset mirror + id: static-assets + if: vars.CLOUDFLARE_STATIC_ASSETS_DEPLOY_ENABLED == 'true' + env: + CLOUDFLARE_PAGES_PROJECTS: ${{ vars.CLOUDFLARE_PAGES_PROJECTS }} + CLOUDFLARE_STATIC_ASSETS_TARGETS: ${{ vars.CLOUDFLARE_STATIC_ASSETS_TARGETS }} + SOURCE_SHA: ${{ github.sha }} + RELEASE_TAG: ${{ github.ref_name }} + run: | + export STATIC_ASSETS_ARTIFACT_DIR="$RUNNER_TEMP/static-assets" + node .github/scripts/pages-static-assets.mjs prepare-if-configured + + - name: Publish the same artifact to the configured static asset host + if: steps.static-assets.outputs.enabled == 'true' + env: + CLOUDFLARE_ACCOUNT_ID: ${{ vars.CLOUDFLARE_STATIC_ASSETS_ACCOUNT_ID }} + CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_STATIC_ASSETS_API_TOKEN }} + WRANGLER_SEND_METRICS: "false" + run: | + test -n "$CLOUDFLARE_ACCOUNT_ID" + test -n "$CLOUDFLARE_API_TOKEN" + pnpm dlx wrangler@4.45.0 deploy --config "$RUNNER_TEMP/static-assets/wrangler.json" + + - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4 + if: steps.static-assets.outputs.enabled == 'true' + with: + name: static-assets-${{ matrix.project }}-${{ github.ref_name }}-${{ github.run_id }} + path: ${{ runner.temp }}/static-assets + include-hidden-files: true + retention-days: 30 diff --git a/.github/workflows/runtime-tls-recovery.yml b/.github/workflows/runtime-tls-recovery.yml new file mode 100644 index 000000000..2509b3771 --- /dev/null +++ b/.github/workflows/runtime-tls-recovery.yml @@ -0,0 +1,199 @@ +name: Recover partial runtime TLS cleanup +run-name: Reviewed partial runtime TLS cleanup + +on: + pull_request: + paths: + - '.github/workflows/runtime-tls-recovery.yml' + - '.github/workflows/deploy-aws.yml' + - '.github/scripts/runtime-tls*' + workflow_dispatch: + inputs: + contract_key: + description: New private reviewed recovery contract key under runtime-tls-recovery/ + required: true + type: string + contract_version: + description: Exact version ID of the reviewed contract + required: true + type: string + contract_sha256: + description: SHA-256 of the exact reviewed contract bytes + required: true + type: string + +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 + - run: | + for suite in .github/scripts/runtime-tls*.test.sh; do + bash "$suite" + done + + plan: + needs: check + if: github.event_name == 'workflow_dispatch' + runs-on: ubuntu-latest + environment: aws-infrastructure-plan + permissions: + contents: read + actions: read + attestations: read + id-token: write + outputs: + digest: ${{ steps.plan.outputs.digest }} + release: ${{ steps.plan.outputs.release }} + steps: + - name: Require an explicitly enabled new main run + env: + RECOVERY_ENABLED: ${{ vars.AWS_TLS_RECOVERY_ENABLED }} + EVIDENCE_ROLE: ${{ vars.AWS_TLS_RECOVERY_EVIDENCE_ROLE_ARN }} + run: | + [ "$GITHUB_REF" = refs/heads/main ] + [ "$GITHUB_RUN_ATTEMPT" = 1 ] + [ "$RECOVERY_ENABLED" = true ] + [ "$EVIDENCE_ROLE" = arn:aws:iam::925323749693:role/warmbly-production-tls-recovery-evidence ] + - uses: actions/checkout@v4 + with: + persist-credentials: false + fetch-depth: 0 + - 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: + WORK: ${{ runner.temp }}/runtime-tls-recovery-plan + CONTRACT_KEY: ${{ inputs.contract_key }} + CONTRACT_VERSION: ${{ inputs.contract_version }} + CONTRACT_SHA256: ${{ inputs.contract_sha256 }} + GH_TOKEN: ${{ github.token }} + run: bash .github/scripts/runtime-tls-recovery-execute.sh plan + - uses: aws-actions/configure-aws-credentials@v4 + if: always() && steps.plan.outcome != 'skipped' + with: + role-to-assume: ${{ vars.AWS_TLS_RECOVERY_EVIDENCE_ROLE_ARN }} + aws-region: us-east-1 + - name: Preserve full private plan evidence + if: always() && steps.plan.outcome != 'skipped' + env: + WORK: ${{ runner.temp }}/runtime-tls-recovery-plan + run: bash .github/scripts/runtime-tls-recovery-archive.sh plan + + apply: + needs: plan + runs-on: ubuntu-latest + environment: aws-infrastructure-approval + concurrency: + group: aws-production + cancel-in-progress: false + permissions: + contents: read + actions: read + attestations: read + id-token: write + steps: + - uses: actions/checkout@v4 + with: + persist-credentials: false + fetch-depth: 0 + - 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 + - id: apply + env: + WORK: ${{ runner.temp }}/runtime-tls-recovery-apply + CONTRACT_KEY: ${{ inputs.contract_key }} + CONTRACT_VERSION: ${{ inputs.contract_version }} + CONTRACT_SHA256: ${{ inputs.contract_sha256 }} + APPROVED_DIGEST: ${{ needs.plan.outputs.digest }} + GH_TOKEN: ${{ github.token }} + run: bash .github/scripts/runtime-tls-recovery-execute.sh apply + - uses: aws-actions/configure-aws-credentials@v4 + if: always() && steps.apply.outcome != 'skipped' + with: + role-to-assume: ${{ vars.AWS_TLS_RECOVERY_EVIDENCE_ROLE_ARN }} + aws-region: us-east-1 + - name: Preserve full private apply evidence + if: always() && steps.apply.outcome != 'skipped' + env: + WORK: ${{ runner.temp }}/runtime-tls-recovery-apply + run: bash .github/scripts/runtime-tls-recovery-archive.sh apply + + redeploy: + needs: [plan, apply] + permissions: + contents: read + id-token: write + attestations: read + uses: ./.github/workflows/deploy-aws.yml + with: + tag: ${{ needs.plan.outputs.release }} + mode: redeploy + services: all + fleet: false + require_attestation: true + bake_seconds: "300" + secrets: inherit + + verify: + needs: redeploy + runs-on: ubuntu-latest + environment: aws-infrastructure-plan + concurrency: + group: aws-production + cancel-in-progress: false + permissions: + contents: read + actions: read + attestations: read + id-token: write + steps: + - uses: actions/checkout@v4 + with: + persist-credentials: false + fetch-depth: 0 + - uses: aws-actions/configure-aws-credentials@v4 + with: + role-to-assume: ${{ vars.AWS_TERRAFORM_PLAN_ROLE_ARN }} + aws-region: us-east-1 + - id: verify + env: + WORK: ${{ runner.temp }}/runtime-tls-recovery-verify + CONTRACT_KEY: ${{ inputs.contract_key }} + CONTRACT_VERSION: ${{ inputs.contract_version }} + CONTRACT_SHA256: ${{ inputs.contract_sha256 }} + GH_TOKEN: ${{ github.token }} + run: bash .github/scripts/runtime-tls-recovery-execute.sh verify + - uses: aws-actions/configure-aws-credentials@v4 + if: always() && steps.verify.outcome != 'skipped' + with: + role-to-assume: ${{ vars.AWS_TLS_RECOVERY_EVIDENCE_ROLE_ARN }} + aws-region: us-east-1 + - name: Preserve full private final evidence + if: always() && steps.verify.outcome != 'skipped' + env: + WORK: ${{ runner.temp }}/runtime-tls-recovery-verify + run: bash .github/scripts/runtime-tls-recovery-archive.sh verify diff --git a/.github/workflows/runtime-tls.yml b/.github/workflows/runtime-tls.yml new file mode 100644 index 000000000..100154fbc --- /dev/null +++ b/.github/workflows/runtime-tls.yml @@ -0,0 +1,135 @@ +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 + - run: shellcheck .github/scripts/runtime-tls-recovery.sh .github/scripts/runtime-tls-recovery.test.sh + - run: bash .github/scripts/runtime-tls-recovery.test.sh + - run: shellcheck .github/scripts/runtime-tls-recovery-lineage.sh .github/scripts/runtime-tls-recovery-lineage.test.sh + - run: bash .github/scripts/runtime-tls-recovery-lineage.test.sh + - run: shellcheck .github/scripts/runtime-tls-recovery-inputs.sh .github/scripts/runtime-tls-recovery-inputs.test.sh + - run: bash .github/scripts/runtime-tls-recovery-inputs.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/static-assets.yml b/.github/workflows/static-assets.yml new file mode 100644 index 000000000..37833c8b9 --- /dev/null +++ b/.github/workflows/static-assets.yml @@ -0,0 +1,125 @@ +name: Publish released static assets + +on: + workflow_dispatch: + inputs: + release_tag: + description: Existing stable release tag to rebuild (no new release) + required: true + type: string + expected_sha: + description: Full commit SHA of that release + required: true + type: string + +permissions: + contents: read + +concurrency: + group: release + cancel-in-progress: false + +jobs: + targets: + if: github.ref == 'refs/heads/main' && vars.CLOUDFLARE_STATIC_ASSETS_DEPLOY_ENABLED == 'true' + runs-on: ubuntu-latest + outputs: + matrix: ${{ steps.targets.outputs.matrix }} + enabled: ${{ steps.targets.outputs.enabled }} + 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 + - id: targets + env: + CLOUDFLARE_PAGES_PROJECTS: ${{ vars.CLOUDFLARE_PAGES_PROJECTS }} + CLOUDFLARE_STATIC_ASSETS_TARGETS: ${{ vars.CLOUDFLARE_STATIC_ASSETS_TARGETS }} + run: node .github/scripts/pages-static-assets.mjs + + publish: + needs: targets + if: needs.targets.outputs.enabled == 'true' + strategy: + fail-fast: false + matrix: ${{ fromJSON(needs.targets.outputs.matrix) }} + runs-on: ubuntu-latest + timeout-minutes: 30 + environment: ${{ matrix.environment }} + env: + PAGES_APP: ${{ matrix.app }} + CLOUDFLARE_PAGES_PROJECT_NAME: ${{ matrix.project }} + SOURCE_SHA: ${{ inputs.expected_sha }} + RELEASE_TAG: ${{ inputs.release_tag }} + WRANGLER_SEND_METRICS: "false" + steps: + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + with: + fetch-depth: 0 + persist-credentials: false + - name: Pin the existing release source + env: + GH_TOKEN: ${{ github.token }} + run: | + [[ "$RELEASE_TAG" =~ ^v[0-9]+\.[0-9]+\.[0-9]+$ ]] + [[ "$SOURCE_SHA" =~ ^[0-9a-f]{40}$ ]] + gh release view "$RELEASE_TAG" --json isDraft,isPrerelease,publishedAt \ + | jq -e '.isDraft == false and .isPrerelease == false and .publishedAt != null' >/dev/null + test "$(git rev-parse "refs/tags/$RELEASE_TAG^{commit}")" = "$SOURCE_SHA" + git merge-base --is-ancestor "$SOURCE_SHA" origin/main + if ! git cat-file -e "$SOURCE_SHA:.github/scripts/pages-production-config.mjs"; then + echo '::error::Release does not support public Pages configuration import; select a supported release.' + exit 1 + fi + git worktree add --detach "$RUNNER_TEMP/frontend-source" "$SOURCE_SHA" + - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4 + with: + node-version: "22" + - name: Load existing public frontend configuration + env: + CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }} + CLOUDFLARE_PAGES_ACCOUNT_ID: ${{ vars.CLOUDFLARE_ACCOUNT_ID }} + run: | + test -n "$CLOUDFLARE_API_TOKEN" + test -n "$CLOUDFLARE_PAGES_ACCOUNT_ID" + curl --fail --silent --show-error \ + --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \ + "https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_PAGES_ACCOUNT_ID/pages/projects/$CLOUDFLARE_PAGES_PROJECT_NAME" \ + | node "$RUNNER_TEMP/frontend-source/.github/scripts/pages-production-config.mjs" + - uses: pnpm/action-setup@b906affcce14559ad1aafd4ab0e942779e9f58b1 # v4 + with: + version: "11.9.0" + - name: Build the released frontend artifact + env: + APP_DIRECTORY: ${{ matrix.directory }} + BUILD_SCRIPT: ${{ matrix.build_script }} + VITE_SENTRY_RELEASE: ${{ inputs.release_tag }} + run: | + cd "$RUNNER_TEMP/frontend-source/$APP_DIRECTORY" + pnpm install --frozen-lockfile + pnpm run "$BUILD_SCRIPT" + - name: Prepare the configured static asset deployment + env: + CLOUDFLARE_PAGES_PROJECTS: ${{ vars.CLOUDFLARE_PAGES_PROJECTS }} + CLOUDFLARE_STATIC_ASSETS_TARGETS: ${{ vars.CLOUDFLARE_STATIC_ASSETS_TARGETS }} + run: | + export STATIC_ASSETS_ARTIFACT_DIR="$RUNNER_TEMP/static-assets" + cd "$RUNNER_TEMP/frontend-source" + node "$GITHUB_WORKSPACE/.github/scripts/pages-static-assets.mjs" prepare + - name: Publish assets without a request Worker + env: + CLOUDFLARE_ACCOUNT_ID: ${{ vars.CLOUDFLARE_STATIC_ASSETS_ACCOUNT_ID }} + CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_STATIC_ASSETS_API_TOKEN }} + run: | + test -n "$CLOUDFLARE_ACCOUNT_ID" + test -n "$CLOUDFLARE_API_TOKEN" + pnpm dlx wrangler@4.45.0 deploy --config "$RUNNER_TEMP/static-assets/wrangler.json" + - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4 + with: + name: static-assets-${{ matrix.project }}-${{ inputs.release_tag }}-${{ github.run_id }} + path: ${{ runner.temp }}/static-assets + include-hidden-files: true + retention-days: 30 diff --git a/.github/workflows/terraform-aws.yml b/.github/workflows/terraform-aws.yml index 5de0ce85d..7c8de54ba 100644 --- a/.github/workflows/terraform-aws.yml +++ b/.github/workflows/terraform-aws.yml @@ -1,21 +1,21 @@ name: Terraform AWS # Pull requests get a plan summary comment. On main, a stack whose plan only -# creates or updates applies on its own; one that replaces or destroys waits in -# the aws-infrastructure-approval environment. Var files live in the private +# creates or updates applies on its own; destructive or protected evidence IAM +# changes wait in aws-infrastructure-approval. Var files live in the private # state bucket, and no plan body ever reaches a log, a comment or an artifact. on: pull_request: paths: - 'deploy/terraform/aws/**' - '.github/workflows/terraform-aws.yml' - - '.github/scripts/terraform-stack.sh' + - '.github/scripts/terraform-stack*.sh' push: branches: [main] paths: - 'deploy/terraform/aws/**' - '.github/workflows/terraform-aws.yml' - - '.github/scripts/terraform-stack.sh' + - '.github/scripts/terraform-stack*.sh' workflow_dispatch: permissions: @@ -42,11 +42,16 @@ jobs: - name: Validate run: | set -euo pipefail - for stack in bootstrap foundation runtime workers; do + for stack in bootstrap foundation runtime workers nats; do terraform -chdir="deploy/terraform/aws/$stack" init -backend=false -input=false >/dev/null terraform -chdir="deploy/terraform/aws/$stack" validate -no-color done - - run: shellcheck .github/scripts/terraform-stack.sh + # Mocked provider: no credentials, nothing created. + - run: terraform -chdir=deploy/terraform/aws/runtime test -no-color + - run: terraform -chdir=deploy/terraform/aws/workers test -no-color + - run: node --test deploy/terraform/aws/runtime/checks/credentials.test.cjs + - run: shellcheck .github/scripts/terraform-stack*.sh + - run: bash .github/scripts/terraform-stack.test.sh plan: name: Plan summary @@ -90,7 +95,7 @@ jobs: case "$class" in none) echo "**$stack**: no changes" ;; safe) echo "**$stack**: applies on merge" ;; - gated) echo "**$stack**: replaces or destroys, so it waits for approval in aws-infrastructure-approval" ;; + gated) echo "**$stack**: destructive or protected IAM changes wait for approval in aws-infrastructure-approval" ;; esac if [ "$class" != none ]; then echo '```' diff --git a/.golangci.yml b/.golangci.yml index d970055fe..a51062bfc 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -32,6 +32,12 @@ linters-settings: issues: exclude-rules: + # Keep the pinned upstream reader tests byte-for-byte. + - path: ^internal/pkg/boundedcsv/reader_test\.go$ + text: 'deepequalerrors: avoid using reflect\.DeepEqual with errors' + linters: + - govet + - path: _test\.go linters: - errcheck diff --git a/AGENTS.md b/AGENTS.md index 245662afc..32271d28f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -255,7 +255,7 @@ Record proof only for a UI change a reviewer should actually see; most changes n ## Security And Compliance Invariants -Warmbly's Google OAuth client is assessed against **ADA CASA v2.1.1 at Assurance Level 1**, which maps to OWASP ASVS 4.0.3. The evidence pack is a claim about the code on `main`: a change that breaks one of the invariants below does not just introduce a bug, it makes a submitted statement untrue and puts the OAuth client's verification at risk. Treat them as constraints on every change, not as a checklist run before an audit. +Warmbly's security invariants are written against **ADA CASA v2.1.1 at Assurance Level 1**, which maps to OWASP ASVS 4.0.3. The Google OAuth client is in production but unverified and has not been assessed: it is held to Google's 100-new-user cap, except on Workspace domains whose admin marks it Trusted, which is how Workspace and reseller mailboxes connect. The evidence pack is a claim about the code on `main`: a change that breaks one of the invariants below does not just introduce a bug, it makes the pack untrue and puts any future verification at risk. Treat them as constraints on every change, not as a checklist run before an audit. **The pack is not in this repository and must not be added to it.** It maps every control to the file that implements it and lists the advisories still open with the exact conditions under which each is reachable. That is a reconnaissance document for anyone attacking a self-hosted instance that has not updated, which is the same reason the disclosure rule below exists. It lives outside the tree, at `CASA_EVIDENCE_DIR` (default `~/warmbly-casa-private/casa`), and `make casa-evidence` refuses to write anywhere inside the repository. @@ -557,7 +557,7 @@ Migration 000156 guarantees exactly one pool per type on every instance, under ` Crossing tiers is an exchange and lives in one place: `WarmupPartnerCandidates` in `pg_warmup.go` returns a sender's own tier plus, when the sender has fewer recipients outside its own workspace than `max(WarmupPoolTierFallbackFloor, warmup_max)`, that many proven free mailboxes from other workspaces (healthy, never blocked, members for `WarmupPoolFallbackMinAgeDays`, workspace not restricted or suspended), best first (Google or Microsoft, then members for `WarmupPoolBorrowSeasonedDays`, then actively sending; random within a rank), and for a free sender that meets the same bar, the premium mailboxes that verifiably wrote to it within `WarmupPoolReturnVisitDays`. Siblings never count toward the floor: a customer with many mailboxes and few premium peers otherwise never borrows and warms against itself. `models.WarmupPoolBorrowsFrom` and `models.WarmupPoolReturnsTo` are the two directions and mirror each other, so nothing unsolicited from the free tier reaches a paying inbox: the paying side always opens the exchange. Before this half existed a thin premium tier sent into the free tier and received almost nothing (#633). Every candidate carries the pool it was drawn from (`PoolType`) and how it got there (`Origin`); the selector and the scheduler both read that one method, so they cannot disagree about who is reachable. A routing rule of weight 0 is an exclusion, not a weight: the candidate is dropped before the draw (and refused on the reply-back path), so a pool of one cannot smuggle it back, and a tick with nothing left ends in `errAllPartnersExcluded` rather than mailing an excluded address (#501). The selector draws its own tier's fresh partners before a borrowed one, but a return visit ranks with the own tier, or a free mailbox with a hundred fresh siblings would never pay a paying inbox back. Every candidate is gated with `CanParticipate` pinned to the pool it was drawn from; gating a borrowed recipient against the sender's pool is what made borrowing dead for months (#495). The reply-back (`directedWarmupPartner`) crosses tiers on the same terms (a free mailbox answers a paid one only while healthy, the bar the return cohort holds it to) and is refused when the free workspace is restricted. It crosses on `CanParticipate`'s `not_in_pool`, so that reason must stay distinct from an ineligible member, or every cross-tier reply is closed unsent. -Reciprocity is a weight and a cap, both read off the candidate. Each carries its verified sends and arrivals over seven days; `Starvation` (how far behind an inbox is on what it sent) multiplies its draw weight by up to `1 + reciprocityBoostK`, fading to nothing at parity, so the pool's traffic flows to whoever is owed the most and settles there instead of overshooting. `InboundDailyCap` (`WarmupInboundDailyMultiple` times daily sends, between `WarmupInboundDailyFloor` and `WarmupInboundDailyCeiling`) is applied inside `WarmupPartnerCandidates`, and a free sender sees every inbox as full at `WarmupFreeInboundSharePercent` of it, so the rest of each inbox's day is kept for premium senders. A recipient at its cap is offered to nobody for the rest of the day and the scheduler's per-day volume cap (`min(target, len(candidates))`) sees the same set. A sender with nobody left to write to sends nothing that tick and rechecks later; do not add a fallback that mails somebody anyway. +Reciprocity is a weight and a cap, both read off the candidate. Each carries its verified sends and arrivals over seven days; `Starvation` (how far behind an inbox is on what it sent) multiplies its draw weight by up to `1 + reciprocityBoostK`, fading to nothing at parity, so the pool's traffic flows to whoever is owed the most and settles there instead of overshooting. `InboundDailyCap` (`WarmupInboundDailyMultiple` times daily sends, between `WarmupInboundDailyFloor` and `WarmupInboundDailyCeiling`) is applied inside `WarmupPartnerCandidates`, and a free sender sees every inbox as full at `WarmupFreeInboundSharePercent` of it, so the rest of each inbox's day is kept for premium senders. The cap counts new threads only: a reply answers mail its recipient sent, so it is neither refused by the cap nor counted against it (`newThreadSQL`), and a reply to a full inbox is sent, not closed. A recipient at its cap is offered to nobody for the rest of the day and the scheduler's per-day volume cap (`min(target, len(candidates))`) sees the same set. A sender with nobody left to write to sends nothing that tick and rechecks later; do not add a fallback that mails somebody anyway. Reachability is read off the same candidate: `Delivered7d` is the pool's handed-off warmup mail to it (past `config.WarmupRecipientArrivalGraceHours`) and `Arrived7d` what its own sync verified (`warmup_tokens.consumed_at`). The draw multiplies by `ArrivalRate`, and `models.WarmupRecipientUnreachable` (none arrived, at least `WarmupRecipientUnreachableMinDelivered` from at least `WarmupRecipientUnreachableMinSenderOrgs` workspaces) drops the candidate in `capPartnerCandidates`, so the selector, the scheduler and the counts agree, and the Advisor's `warmup_mail_not_arriving` reads the same rule. A send the sender's provider accepted and later bounced looks like success to the worker, so arrival, not the send result, is the evidence. Keep the two-workspace floor: without it one broken sender takes its recipients out of the pool. 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/auth/DeviceApprovalPage.tsx b/admin/src/app/auth/DeviceApprovalPage.tsx index 3dc06b817..4450ec0ca 100644 --- a/admin/src/app/auth/DeviceApprovalPage.tsx +++ b/admin/src/app/auth/DeviceApprovalPage.tsx @@ -6,7 +6,7 @@ import { Input } from "@/components/ui/input"; import { Label } from "@/components/ui/label"; import { Callout, Panel, Property, PropertyList, StatusBadge } from "@/components/ui/kit"; import { ErrorState } from "@/components/ErrorState"; -import { APIError, promptForReauth } from "@/lib/api/client"; +import { APIError, promptForReauth, ReauthCancelledError } from "@/lib/api/client"; import { describeAdminDevice, decideAdminDevice, type DeviceDescription } from "@/lib/api/client/admin/device"; import { API_URL } from "@/lib/env"; import { AdminPerm } from "@/lib/auth/permissions"; @@ -90,7 +90,7 @@ export default function DeviceApprovalPage() { try { await promptForReauth(); if (mounted.current) setNeedsReauth(false); - } catch (err) { if (mounted.current) setError(err); } + } catch (err) { if (mounted.current && !(err instanceof ReauthCancelledError)) setError(err); } finally { inFlight.current = false; if (mounted.current) setBusy(false); } } diff --git a/admin/src/app/dashboard/AuditPage.tsx b/admin/src/app/dashboard/AuditPage.tsx index 028798f97..068a48774 100644 --- a/admin/src/app/dashboard/AuditPage.tsx +++ b/admin/src/app/dashboard/AuditPage.tsx @@ -270,7 +270,8 @@ function FilterField({ label, children }: { label: string; children: React.React function Row({ row }: { row: AdminAuditLog }) { const [open, setOpen] = useState(false); const hasDetails = row.details && Object.keys(row.details).length > 0; - const systemActor = row.admin_user_id === NIL_UUID; + // The actor's id is cleared when their account is deleted. + const deletedActor = row.admin_user_id === NIL_UUID; const tone = ACTION_TONE[row.action] ?? "neutral"; return ( <> @@ -290,8 +291,8 @@ function Row({ row }: { row: AdminAuditLog }) { {new Date(row.created_at).toLocaleString()} - {systemActor ? ( - system + {deletedActor ? ( + Deleted account ) : row.admin_user ? (
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 && ( + + )} + } + > + onChange({ ...usage, markup: v })} + valid={markupValid} + error={`Enter a whole number between ${MARKUP_MIN} and ${MARKUP_MAX}.`} + /> +
+
Models
+
+ Dollars per million input and output tokens. A model is priced by the row with + its exact name, then by the longest row its name starts with, then by{" "} + *, which prices every model + without a row of its own and cannot be removed. +
+
+ Model + Input / Mtok + Output / Mtok + +
+
+ {usage.models.map((m) => { + const isAny = m.model === ANY_MODEL; + const nameError = isAny ? undefined : modelNameError(usage.models, m); + const inputOk = priceValid(m.input); + const outputOk = priceValid(m.output); + const chargedIn = withMarkup(m.input, usage.markup); + const chargedOut = withMarkup(m.output, usage.markup); + return ( +
+
+ setModel(m.id, { model: e.target.value })} + aria-invalid={!!nameError} + className={cn("font-mono text-[12.5px]", isAny && "text-muted-foreground")} + /> + +
+ setModel(m.id, { input: e.target.value })} + aria-invalid={!inputOk} + className="text-right tabular-nums" + /> + setModel(m.id, { output: e.target.value })} + aria-invalid={!outputOk} + className="text-right tabular-nums" + /> +
+
+
+ {chargedIn && chargedOut + ? `charged ${chargedIn} / ${chargedOut} per million tokens` + : null} +
+ {(nameError || !inputOk || !outputOk) && ( +

+ {nameError ?? "Enter a price of zero or more, in dollars."} +

+ )} +
+ ); + })} +
+
+ {unitKeys(usage.units).map((key) => { + const raw = usage.units[key]; + const charged = withMarkup(raw, usage.markup); + const meta = UNIT_LABELS[key]; + return ( + onChange({ ...usage, units: { ...usage.units, [key]: v } })} + valid={priceValid(raw)} + error="Enter a price of zero or more, in dollars." + inputMode="decimal" + /> + ); + })} + + ); +} + +// One numeric setting: the field sits on the right, the range under the help. function NumberRow({ id, label, @@ -786,6 +1158,7 @@ function NumberRow({ valid, error, disabled, + inputMode = "numeric", }: { id: string; label: string; @@ -796,6 +1169,7 @@ function NumberRow({ valid: boolean; error: string; disabled?: boolean; + inputMode?: "numeric" | "decimal"; }) { return ( onChange(e.target.value)} diff --git a/admin/src/components/ReauthDialog.test.tsx b/admin/src/components/ReauthDialog.test.tsx new file mode 100644 index 000000000..cb4d26333 --- /dev/null +++ b/admin/src/components/ReauthDialog.test.tsx @@ -0,0 +1,56 @@ +import { act } from "react"; +import { createRoot, type Root } from "react-dom/client"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { APIError } from "@/lib/api/client"; +import { ReauthDialog } from "./ReauthDialog"; + +const api = vi.hoisted(() => ({ reauth: vi.fn(), methods: vi.fn() })); +vi.mock("@/lib/api/client/auth", () => ({ reauth: api.reauth, reauthMethods: api.methods })); +vi.mock("@/lib/env", () => ({ API_URL: "http://localhost:8080" })); + +let root: Root; +let host: HTMLDivElement; +beforeEach(() => { + vi.clearAllMocks(); + vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true); + api.methods.mockResolvedValue({ password: false, totp: true }); + host = document.createElement("div"); + document.body.append(host); + root = createRoot(host); +}); +afterEach(async () => { + await act(async () => root.unmount()); + host.remove(); + vi.unstubAllGlobals(); +}); + +describe("ReauthDialog", () => { + it.each([ + ["two_fa_code_used", "Wait for a new authenticator code, then try again."], + ["internal_error", "We couldn't verify your confirmation right now. Try again shortly."], + ["service_unavailable", "We couldn't verify your confirmation right now. Try again shortly."], + [undefined, "We couldn't verify your confirmation right now. Try again shortly."], + ["credentials", "That did not match. Try again."], + ])("explains %s without confirming the waiting action", async (code, message) => { + api.reauth.mockRejectedValue(code ? new APIError("Failure", 400, { code }) : new Error("offline")); + const resolve = vi.fn(); + const reject = vi.fn(); + await act(async () => root.render()); + await act(async () => window.dispatchEvent(new CustomEvent("reauth-required", { detail: { resolve, reject } }))); + const input = document.querySelector('input[autocomplete="one-time-code"]'); + if (!(input instanceof HTMLInputElement)) throw new Error("Missing code field"); + const setter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")?.set; + if (!setter) throw new Error("Missing input setter"); + await act(async () => { + setter.call(input, "123456"); + input.dispatchEvent(new Event("input", { bubbles: true })); + }); + const form = input.closest("form"); + if (!form) throw new Error("Missing confirmation form"); + await act(async () => form.dispatchEvent(new Event("submit", { bubbles: true, cancelable: true }))); + expect(document.querySelector('[role="alert"]')?.textContent).toBe(message); + expect(api.reauth).toHaveBeenCalledWith({ password: undefined, code: "123456" }); + expect(resolve).not.toHaveBeenCalled(); + expect(reject).not.toHaveBeenCalled(); + }); +}); diff --git a/admin/src/components/ReauthDialog.tsx b/admin/src/components/ReauthDialog.tsx index 453d20b9d..1cbf21d72 100644 --- a/admin/src/components/ReauthDialog.tsx +++ b/admin/src/components/ReauthDialog.tsx @@ -56,12 +56,16 @@ export function ReauthDialog() { pending.resolve(); setPending(null); } catch (err) { - // One message for both factors; which one matched is not worth saying. - setError( - err instanceof APIError && (err.code === "reauth_no_factor" || err.code === "reauth_limited") - ? err.message - : "That did not match. Try again.", - ); + const errCode = err instanceof APIError ? err.code : undefined; + if (err instanceof APIError && (errCode === "reauth_no_factor" || errCode === "reauth_limited" || errCode === "attempt_check_unavailable")) { + setError(err.message); + } else if (errCode === "two_fa_code_used") { + setError("Wait for a new authenticator code, then try again."); + } else if (!errCode || errCode === "internal_error" || errCode === "service_unavailable") { + setError("We couldn't verify your confirmation right now. Try again shortly."); + } else { + setError("That did not match. Try again."); + } setBusy(false); } } @@ -128,7 +132,7 @@ export function ReauthDialog() { )}

) : null} - {error &&

{error}

} + {error &&

{error}

}
- -
-
- - Next invoice -
-
-
Grow$89.00
-
Referral credit−$89.00
-
Amount due$0.00
-
-
- diff --git a/site/src/components/scenes/referral/SettingsScene.astro b/site/src/components/scenes/referral/SettingsScene.astro deleted file mode 100644 index b2c314b16..000000000 --- a/site/src/components/scenes/referral/SettingsScene.astro +++ /dev/null @@ -1,181 +0,0 @@ ---- -import ScaledStage from '../../ScaledStage.astro'; -import AppShellMock from '../../AppShellMock.astro'; -import Glyph from '../Glyph.astro'; -import Ico from '../about/Ico.astro'; -import { WINDOW, FLOAT, EYEBROW, TOPBAR } from '../../../lib/scene'; - -/** - * Settings > Refer & earn (web/src/app/app/settings/referral/page.tsx) in - * the app shell: the settings rail, the how-it-works note, the share link - * and code, the earnings cards, and the referrals table, where a qualified - * team turns rewarded and the credit lands on a loop. - */ -const rail = [ - { label: 'Account', items: [['user', 'Profile'], ['bell', 'Notifications'], ['shield', 'Security']] }, - { label: 'Workspace', items: [['users', 'Members'], ['users', 'Teams'], ['shieldCheck', 'Roles & access'], ['briefcase', 'Workspace'], ['send', 'Sending'], ['globe', 'Website tracking'], ['tag', 'Inbox tagging'], ['sparkles', 'AI skills'], ['creditCard', 'Billing'], ['gift', 'Refer & earn'], ['gauge', 'Limits']] }, - { label: 'Developers', items: [['webhook', 'Webhooks']] }, -] as const; -const glyphs = new Set(['user', 'shieldCheck', 'send', 'globe', 'tag', 'sparkles', 'gauge']); -const shell = 'px-8 py-5'; -const h3 = 'text-[12.5px] font-semibold text-slate-900 tracking-tight'; -const desc = 'text-[11.5px] text-slate-500 leading-relaxed'; -const chip = 'h-7 w-[280px] px-2.5 rounded-md border border-slate-200 bg-slate-50 font-mono text-[12px] text-slate-700 flex items-center truncate'; -const copy = 'h-7 px-2.5 rounded-md bg-slate-900 text-white text-[12px] font-medium inline-flex items-center gap-1.5'; -const badge = 'inline-flex items-center text-[10px] uppercase tracking-[0.08em] font-semibold rounded-sm px-1.5 py-0.5 border'; -const referrals = [ - { id: '7c1e…a04', status: 'rewarded', reward: '$89.00', date: 'Sep 12' }, - { id: '3f9a…c21', status: 'live', reward: '$89.00', date: 'Oct 6' }, - { id: 'b2d8…19e', status: 'rewarded', reward: '$29.00', date: 'Aug 28' }, - { id: 'e45c…7b3', status: 'qualified', reward: '—', date: 'Oct 7' }, - { id: '91aa…f62', status: 'pending', reward: '—', date: 'Oct 8' }, -]; -const tones = { - pending: 'bg-slate-100 text-slate-500 border-slate-200', - qualified: 'bg-sky-50 text-sky-700 border-sky-100', - rewarded: 'bg-emerald-50 text-emerald-700 border-emerald-100', -} as const; ---- - -
-
- -
-
- Settings - - Invite teams and earn account credit. -
-
- - -
-
-

Refer & earn

-

Invite other teams to Warmbly and earn account credit on your invoices.

-
-
-
-

How it works

-

Share your link, they save, you earn.

-
- -
-
Give 10%, get a month of credit
-

Anyone who signs up with your link gets 10% off for their first 3 months. Once they're a paying customer you earn account credit equal to one month of their plan, applied automatically to your invoices.

-
-
-
- -
-

Your link

-

Share this link or code. New signups are attributed to you automatically.

-
-
-
Share link
A direct signup link with your code attached.
-
https://app.warmbly.com/auth/register?ref=NORTHWIND
Copy link
-
-
-
Referral code
For anyone entering a code manually at signup.
-
northwind
Copy code
-
-
-
- -
-

Earnings

-

Credit you've earned. Balance is applied to your invoices automatically.

-
-
-
Available credit
-
$118.00$207.00
-
-
-
Lifetime earned
-
$207.00$296.00
-
-
-
Total referred
-
7
-
-
-
Rewarded
-
23
-
-
-
- Pending3 - Qualified21  - Rewarded23  -
-
-
-
-
-
-
-
-
- - -
-
-
Your referrals
-
Teams that signed up with your link and where they are in the reward flow.
-
- - - - - - - - - - - {referrals.map((r) => ( - - - - - - - ))} - -
Referred orgStatusRewardDate
Referred org {r.id} - {r.status === 'live' ? ( - - Qualified - Rewarded - - ) : {r.status}} - - {r.status === 'live' ? —{r.reward}  : r.reward} - {r.date}
-
-
- - diff --git a/site/src/components/scenes/referral/SettleScene.astro b/site/src/components/scenes/referral/SettleScene.astro deleted file mode 100644 index 9293632ae..000000000 --- a/site/src/components/scenes/referral/SettleScene.astro +++ /dev/null @@ -1,68 +0,0 @@ ---- -import ScaledStage from '../../ScaledStage.astro'; -import Glyph from '../Glyph.astro'; -import { WINDOW, FLOAT, EYEBROW } from '../../../lib/scene'; - -/** - * The 30-day clawback (docs/content/docs/guides/referral-program.mdx): the - * earnings history, where a reversed reward is a negative row, and over it - * two rewards on the same window, one that settles and one refunded inside it. - */ -const ledger = [ - ['Referral reward', '+$89.00', '$207.00', 'Oct 6', 'text-emerald-600'], - ['Applied to invoice', '−$89.00', '$118.00', 'Oct 1', 'text-slate-500'], - ['Referral reward reversed', '−$29.00', '$207.00', 'Sep 20', 'text-rose-600'], - ['Referral reward', '+$89.00', '$236.00', 'Sep 12', 'text-emerald-600'], - ['Referral reward', '+$29.00', '$147.00', 'Sep 8', 'text-emerald-600'], - ['Referral reward', '+$89.00', '$118.00', 'Aug 21', 'text-emerald-600'], - ['Referral reward', '+$29.00', '$29.00', 'Aug 2', 'text-emerald-600'], -]; -const lanes = [ - { org: '3f9a…c21', plan: 'Grow', amount: '$89.00', end: 100, ok: true, note: 'Day 30 · settled' }, - { org: 'd07b…5e8', plan: 'Starter', amount: '$29.00', end: 40, ok: false, note: 'Day 12 · refunded' }, -]; -const cols = 'grid grid-cols-[1fr_96px_96px_72px] gap-3'; ---- - -
-
-
Earnings history
-
Every credit and adjustment applied to your balance.
-
-
- ReasonAmountBalanceDate -
- {ledger.map(([r, a, b, d, c]) => ( -
- {r}{a}{b}{d} -
- ))} -
- -
-
- The 30-day window - day 0 to day 30 -
-
- {lanes.map((l, i) => ( -
-
- Referred org{l.org} - ·{l.plan} - +{l.amount} -
-
-
-
- -
-
- Day 0 · reward - {l.note} -
-
- ))} -
-
-
diff --git a/site/src/components/scenes/referral/ShareStep.astro b/site/src/components/scenes/referral/ShareStep.astro deleted file mode 100644 index dafceaadd..000000000 --- a/site/src/components/scenes/referral/ShareStep.astro +++ /dev/null @@ -1,33 +0,0 @@ ---- -import ScaledStage from '../../ScaledStage.astro'; -import Glyph from '../Glyph.astro'; -import Ico from '../about/Ico.astro'; -import { WINDOW, FLOAT } from '../../../lib/scene'; - -/** Step one: the share link copied from Settings > Refer & earn, pasted into an email. */ ---- - -
-
- - New message -
-
-
Fromalex@northwind.dev
-
Todana@helio.gen
-
SubjectWhat we run our outreach on
-
-
- Dana, this is the tool behind our cold email. Your first three months are 10% off with this link: -
app.warmbly.com/auth/register?ref=NORTHWIND
-
-
- -
-
-
…/register?ref=NORTHWIND
- Copied -
-
Settings, Refer & earn
-
-
diff --git a/site/src/content/blog/open-source-cold-email-platform.mdx b/site/src/content/blog/open-source-cold-email-platform.mdx index 274c1e557..91da60c49 100644 --- a/site/src/content/blog/open-source-cold-email-platform.mdx +++ b/site/src/content/blog/open-source-cold-email-platform.mdx @@ -50,8 +50,8 @@ You own the domains and their auth. SPF has a 10 DNS-lookup limit, and going ove You own deliverability monitoring. Warmbly runs its own [open and click tracking](/analytics/) and reports the signals, but you decide what to do when complaint rate climbs toward Amazon SES's 0.1% review line or Google's 0.10% reported-spam threshold. The product's defaults help: a 50 emails/mailbox/day cold cap (hard max 100), a minimum 600 seconds between sends from one mailbox, and warmup that starts at 10/day and ramps +1/day to a 40/day ceiling. A brand-new mailbox typically takes 3 to 6 weeks to reach a stable warmed state. Those numbers ship in the code. Whether your IPs and domains can sustain them is your call. See [how many mailboxes and domains you need](/blog/how-many-mailboxes-and-domains-cold-email/) and [budgets, not server settings](/blog/mailbox-budgets-not-server-settings/). - - A warmup pool works by pairing your mailboxes with other participants so providers see two-way conversation. A single self-hosted instance is one organization, so on its own its mailboxes can only talk to each other, which providers learn to recognize. The pool mechanics (partner selection, recent partners excluded, verification tokens, health-band quarantine) are in the code, but the network effect needs many organizations. So a self-hosted instance will link to Warmbly Cloud instead, once it launches: you approve a one-time code, pick the mailboxes to enroll, and Warmbly runs their warmup in the shared pool while everything else stays on your server. Free for up to 10 mailboxes, $15 a month for unlimited. [How it works](https://docs.warmbly.com/guides/warmbly-cloud/). + + A warmup pool works by pairing your mailboxes with other participants so providers see two-way conversation. A single self-hosted instance is one organization, so on its own its mailboxes can only talk to each other, which providers learn to recognize. The pool mechanics (partner selection, recent partners excluded, verification tokens, health-band quarantine) are in the code, but the network effect needs many organizations. So the pool runs on Warmbly Cloud, once it launches, for mailboxes connected to a hosted workspace. Self-hosted instances do not link to it. Warmup on a self-hosted instance still runs between its own mailboxes; it just is not effective. ## How the encryption model keeps credentials and message content private @@ -69,11 +69,11 @@ Two properties matter for self-hosting. First, workers never open a Postgres con | Who runs the six services? | You | Warmbly | | Who owns the IPs and domains? | You | You (mailboxes), Warmbly (sending infra) | | Who holds the KMS key? | You | Warmbly | -| Shared warmup pool? | Yes, by linking the instance once the cloud launches (free for 10 mailboxes, $15/month unlimited) | Yes, cross-org pool | +| Shared warmup pool? | No. Warmup only pairs your own mailboxes, and a self-hosted instance does not link to the cloud pool | Yes, cross-org pool | | Deliverability monitoring? | You watch and react | Managed with the same thresholds | | Best fit | You want full data custody and control, and can run infra | You want to send without operating Kafka and IP pools | -Neither is strictly better. If you can run distributed infrastructure and you want your data and campaign credentials to stay on keys you hold, self-host: it is free, and once the cloud launches, linking the instance gets you the real warmup pool too. The [cloud waitlist](https://app.warmbly.com) is open. If you want sending plus warmup without operating any of it, a hosted workspace on the [pricing page](/pricing/) starts free with 10 mailboxes and warmup, no credit card. +Neither is strictly better. If you can run distributed infrastructure and you want your data and campaign credentials to stay on keys you hold, self-host: it is free and fully functional on its own, though its warmup only pairs your own mailboxes. Self-hosting suits experienced operators: Warmbly does not provide support for self-hosted instances, and help comes from the community on [Discord](https://dc.warmbly.com). The [cloud waitlist](https://app.warmbly.com) is open. If you want the shared warmup pool, or sending plus warmup without operating any of it, a hosted workspace on the [pricing page](/pricing/) starts free with 10 mailboxes and warmup, no credit card. ## Where the code lives and what Apache 2.0 lets you do diff --git a/site/src/layouts/Layout.astro b/site/src/layouts/Layout.astro index 0c072e23f..081a541f1 100644 --- a/site/src/layouts/Layout.astro +++ b/site/src/layouts/Layout.astro @@ -226,14 +226,39 @@ const websiteJsonLd = { var isSdkTimeout = function (type, value) { return type === 'AbortError' && typeof value === 'string' && value.indexOf('PostHog request timed out') === 0; }; + // Thrown into the page by wallets, extensions and in-app browsers; a frame in our /_astro/ bundle keeps the report. + var foreign = [ + /window\.ethereum\.selectedAddress = undefined/, + /^Can't find variable: (CONFIG|currentInset)$/, + /^No Listener: tabs:/, + /^Could not establish connection\. Receiving end does not exist\.$/, + ]; + var isForeign = function (exception) { + var frames = (exception && exception.stacktrace && exception.stacktrace.frames) || []; + var fromExtension = false; + for (var f = 0; f < frames.length; f++) { + var source = frames[f] && (frames[f].filename || frames[f].abs_path); + if (typeof source !== 'string') continue; + if (/^(?:[a-z]+:\/\/[^/]+)?\/_astro\//i.test(source)) return false; + if (/^(?:(?:chrome|moz|safari|safari-web|ms-browser)-extension:|webkit-masked-url:)/.test(source)) fromExtension = true; + } + if (fromExtension) return true; + var text = exception && (exception.value || exception.$exception_value); + if (typeof text !== 'string') return false; + for (var p = 0; p < foreign.length; p++) if (foreign[p].test(text)) return true; + return false; + }; var exceptions = event.properties && event.properties.$exception_list; if (Array.isArray(exceptions)) { + var allForeign = exceptions.length > 0; for (var i = 0; i < exceptions.length; i++) { var value = exceptions[i] && (exceptions[i].value || exceptions[i].$exception_value); if (isNoise(value)) return null; var type = exceptions[i] && (exceptions[i].type || exceptions[i].$exception_type); if (isSdkTimeout(type, value)) return null; + if (!isForeign(exceptions[i])) allForeign = false; } + if (allForeign) return null; } var message = event.properties && event.properties.$exception_message; if (isNoise(message)) return null; diff --git a/site/src/pages/about.astro b/site/src/pages/about.astro index cedff20a1..22e71b973 100644 --- a/site/src/pages/about.astro +++ b/site/src/pages/about.astro @@ -227,5 +227,5 @@ let n = 0; - + diff --git a/site/src/pages/analytics.astro b/site/src/pages/analytics.astro index 387170003..162bdb171 100644 --- a/site/src/pages/analytics.astro +++ b/site/src/pages/analytics.astro @@ -58,7 +58,7 @@ const bentoText = 'mt-2 max-w-xl text-[16px] md:text-[17px] leading-[1.55] text-

- Start free + Get started What gets counted diff --git a/site/src/pages/changelog.astro b/site/src/pages/changelog.astro index 169c842cf..655e432d4 100644 --- a/site/src/pages/changelog.astro +++ b/site/src/pages/changelog.astro @@ -99,7 +99,7 @@ const counts = { ))} - + diff --git a/site/src/pages/sending.astro b/site/src/pages/sending.astro index 41fee0b5d..45118e3fa 100644 --- a/site/src/pages/sending.astro +++ b/site/src/pages/sending.astro @@ -73,7 +73,7 @@ const faq: [string, string][] = [

- Start free + Get started Read the guide diff --git a/site/src/pages/use-cases/agencies.astro b/site/src/pages/use-cases/agencies.astro index a1289478d..e2829fcc3 100644 --- a/site/src/pages/use-cases/agencies.astro +++ b/site/src/pages/use-cases/agencies.astro @@ -56,7 +56,7 @@ const faq: [string, string][] = [ @@ -167,5 +167,5 @@ const faq: [string, string][] = [ - + diff --git a/site/src/pages/use-cases/founders.astro b/site/src/pages/use-cases/founders.astro index 3d6947886..e47a84168 100644 --- a/site/src/pages/use-cases/founders.astro +++ b/site/src/pages/use-cases/founders.astro @@ -68,7 +68,7 @@ const faq: [string, string][] = [

Cold email for founders, without risking founder@.

You are the best person to sell what you’re building, but your own inbox is too valuable to burn. This is the setup that keeps it safe and still sends about 150 emails a weekday.

diff --git a/site/src/pages/use-cases/recruiters.astro b/site/src/pages/use-cases/recruiters.astro index 12887db1d..8e8d3a67d 100644 --- a/site/src/pages/use-cases/recruiters.astro +++ b/site/src/pages/use-cases/recruiters.astro @@ -51,7 +51,7 @@ const faq: [string, string][] = [

Candidate outreach that reads like a person wrote it.

Every recruiter sends from their own warmed mailbox, in plain text, with a short sequence that stops the moment a candidate answers.

diff --git a/site/src/pages/use-cases/sales.astro b/site/src/pages/use-cases/sales.astro index f44d8e0e0..92eaaa161 100644 --- a/site/src/pages/use-cases/sales.astro +++ b/site/src/pages/use-cases/sales.astro @@ -47,7 +47,7 @@ const faq: [string, string][] = [

Outreach your whole sales team can share.

Every rep sends from their own mailbox, the volume is shared across the team, and each reply goes back to the person who wrote. Everyone sees who is working on what, live.

diff --git a/site/src/pages/warmup.astro b/site/src/pages/warmup.astro index f972ea489..923872197 100644 --- a/site/src/pages/warmup.astro +++ b/site/src/pages/warmup.astro @@ -43,9 +43,9 @@ const faq: [string, string][] = [ ['How long does warmup take?', 'Most new mailboxes need three to six weeks. At the default ramp a mailbox reaches 40 emails a day after about a month, and inbox placement usually settles over the same stretch.'], ['Should warmup keep running once my campaigns start?', 'Yes. Warmup runs alongside cold sending at up to five messages a day, so a dip in reputation shows up in the warmup numbers and gets corrected before your campaigns feel it.'], ['What gets a mailbox taken out of the pool?', 'High complaint or bounce rates: 0.10% complaints or 5% bounces pause it for 7 days, 0.30% or 10% for 30. Spam placement on its own never removes a mailbox; it only slows warmup down until placement recovers.'], - ['Do the free and premium pools mix?', 'Only on proven terms. A paying mailbox can also write to free mailboxes from other workspaces that have been healthy pool members for at least three days, and a free mailbox may only write back to a paying inbox that wrote to it in the last two weeks.'], + ['Do the free and premium pools mix?', 'Only on proven terms. The free pool holds the mailboxes of workspaces in their free trial and of workspaces that kept the free plan after it closed to new workspaces. A paying mailbox can also write to those mailboxes once they have been healthy pool members for at least three days, and a free mailbox may only write back to a paying inbox that wrote to it in the last two weeks.'], ['Which providers does placement count at?', 'Gmail, Outlook and Yahoo. They filter on sender reputation, which is what cold email is judged on. Smaller mail hosts run their own filters, so their spam folder is never held against you.'], - ['Can I warm up a self-hosted instance?', 'Yes, by linking it to Warmbly Cloud once it launches: up to 10 mailboxes free, or unlimited for $15 a month. Everything else stays on your own servers.'], + ['Can I warm up a self-hosted instance?', 'Only between the mailboxes on that instance. There is no shared pool, so it does far less for deliverability than warming on Warmbly Cloud. Self-hosted instances do not link to the Cloud pool; to warm in it, connect those mailboxes to a hosted workspace, free for two mailboxes during the 14-day trial on an owner\u2019s first workspace and on a paid plan after that.'], ]; const sceneTitle = 'mt-6 text-[21px] md:text-[23px] tracking-[-0.02em] text-slate-900'; @@ -153,7 +153,7 @@ const link = 'group mt-6 inline-flex items-center gap-2 text-[16px] md:text-[17p
- +

Every draw favours the inbox that is owed the most mail, up to four times as often, and no inbox receives more than about twice what it sends in a day.

diff --git a/skills/warmbly-ops/SKILL.md b/skills/warmbly-ops/SKILL.md index 62b2fe0cd..42ebb2ce4 100644 --- a/skills/warmbly-ops/SKILL.md +++ b/skills/warmbly-ops/SKILL.md @@ -44,6 +44,7 @@ for. Prefer parsing that over reasoning from the prose. | Back the instance up | `warmblyctl backup --out /data/blobs/warmbly.tar.gz`, then copy it out and delete it | | Restore one onto this instance | `warmblyctl restore --file /data/blobs/warmbly.tar.gz` | | See which key opens each stored secret | `warmblyctl keys status [--json]` | +| See what the database is busy with: connections by service, costliest queries, largest tables | `warmblyctl db load [--limit N] [--json]` | | Move secrets onto a new primary key | `warmblyctl keys reseal` (dry run), then `keys reseal --apply` | | Mint replacement keys and tokens | `warmblyctl keys generate [NAME...]` | 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/nats.rs b/tracking/src/nats.rs index df79148ed..d97effb45 100644 --- a/tracking/src/nats.rs +++ b/tracking/src/nats.rs @@ -1,6 +1,7 @@ use async_nats::jetstream; use base64::engine::general_purpose::STANDARD as BASE64; use base64::Engine as _; +use rustls::pki_types::{pem::PemObject, CertificateDer}; use crate::config::Config; use crate::events::TrackingEvent; @@ -21,7 +22,12 @@ impl NatsProducer { pub async fn new(config: &Config) -> Result> { // async-nats ignores credentials in the URL, so lift `user:pass@` or // `token@` into the options the way the Go client does on its own. - let addr: async_nats::ServerAddr = config.nats_url.parse()?; + let addresses: Vec = config + .nats_url + .split(',') + .map(|address| address.trim().parse()) + .collect::>()?; + let addr = addresses.first().ok_or("NATS_URL requires a server")?; let mut opts = async_nats::ConnectOptions::new(); if let Some(user) = addr.username() { opts = match addr.password() { @@ -45,7 +51,25 @@ impl NatsProducer { } } - let client = opts.connect(addr).await?; + if let Ok(raw) = std::env::var("NATS_TLS_CA_B64") { + if !raw.trim().is_empty() { + let pem = BASE64.decode(raw.trim())?; + let mut roots = rustls::RootCertStore::empty(); + for certificate in CertificateDer::pem_slice_iter(&pem) { + roots.add(certificate?)?; + } + if roots.is_empty() { + return Err("NATS_TLS_CA_B64 contains no certificates".into()); + } + opts = opts.require_tls(true).tls_client_config( + rustls::ClientConfig::builder() + .with_root_certificates(roots) + .with_no_client_auth(), + ); + } + } + + let client = opts.connect(addresses).await?; let js = jetstream::new(client); let subject = format!("{}.{}", config.nats_subject_prefix, config.kafka_topic); tracing::info!( 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/.env.example b/web/.env.example index f9b2ed7b4..451bc99ac 100644 --- a/web/.env.example +++ b/web/.env.example @@ -1,4 +1,3 @@ VITE_APP_URL="http://localhost:5173" VITE_API_URL="http://localhost:8080" VITE_TURNSTILE_KEY="1x00000000000000000000AA" -VITE_GMAIL_OAUTH_CONNECT="false" diff --git a/web/docker-entrypoint.sh b/web/docker-entrypoint.sh index b672c5256..c3cd08cb8 100644 --- a/web/docker-entrypoint.sh +++ b/web/docker-entrypoint.sh @@ -23,7 +23,6 @@ window.__WARMBLY_ENV__ = { API_URL: "$(js "${WARMBLY_API_URL:-}")", APP_URL: "$(js "${WARMBLY_APP_URL:-}")", TURNSTILE_KEY: "$(js "${WARMBLY_TURNSTILE_KEY:-}")", - GMAIL_OAUTH_CONNECT: "$(js "${WARMBLY_GMAIL_OAUTH_CONNECT:-}")", BETA_NOTICE: "$(js "${WARMBLY_BETA_NOTICE:-}")", SENTRY_DSN: "$(js "${WARMBLY_SENTRY_DSN:-}")", SENTRY_ENVIRONMENT: "$(js "${WARMBLY_SENTRY_ENVIRONMENT:-}")", diff --git a/web/package.json b/web/package.json index a5e3b8033..78b2fbd81 100644 --- a/web/package.json +++ b/web/package.json @@ -51,6 +51,7 @@ "@tanstack/react-query": "^5.104.1", "@tanstack/react-query-devtools": "^5.104.1", "@tanstack/react-router": "^1.170.41", + "@tanstack/react-virtual": "^3.14.26", "@tiptap/core": "^3.31.3", "@tiptap/extension-bold": "^3.31.3", "@tiptap/extension-color": "^3.31.3", @@ -89,6 +90,7 @@ "immer": "^11.1.18", "input-otp": "^1.5.0", "lucide-react": "^0.563.0", + "maplibre-gl": "^5.24.0", "motion": "^12.43.0", "next-themes": "^0.4.6", "papaparse": "^5.7.0", diff --git a/web/pnpm-lock.yaml b/web/pnpm-lock.yaml index 913b65214..bae155d83 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: @@ -117,6 +117,9 @@ importers: '@tanstack/react-router': specifier: ^1.170.41 version: 1.170.41(react-dom@19.3.0(react@19.3.0))(react@19.3.0) + '@tanstack/react-virtual': + specifier: ^3.14.26 + version: 3.14.26(react-dom@19.3.0(react@19.3.0))(react@19.3.0) '@tiptap/core': specifier: ^3.31.3 version: 3.31.3(@tiptap/pm@3.31.3) @@ -200,7 +203,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 @@ -231,6 +234,9 @@ importers: lucide-react: specifier: ^0.563.0 version: 0.563.0(react@19.3.0) + maplibre-gl: + specifier: ^5.24.0 + version: 5.24.0 motion: specifier: ^12.43.0 version: 12.43.0(react-dom@19.3.0(react@19.3.0))(react@19.3.0) @@ -285,7 +291,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 +309,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 +336,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: @@ -861,6 +867,42 @@ packages: peerDependencies: solid-js: ^1.8.8 + '@mapbox/jsonlint-lines-primitives@2.0.3': + resolution: {integrity: sha512-0SElaV0uMxEnxzBhhX9WTuPyUeMsAN/SS0i16tjuba4/mio63MG9khjC1a0JAiPGXAwvwm4UfHJURCN7nyudQg==} + engines: {node: '>= 22'} + + '@mapbox/point-geometry@1.1.0': + resolution: {integrity: sha512-YGcBz1cg4ATXDCM/71L9xveh4dynfGmcLDqufR+nQQy3fKwsAZsWd/x4621/6uJaeB9mwOHE6hPeDgXz9uViUQ==} + + '@mapbox/tiny-sdf@2.3.0': + resolution: {integrity: sha512-gBvcNDBBB66bgQYvnaJ6Jk+VCaMmVq5+IZR2kWPisT88Z8s0kBQt6hfVi8QgRW8Vpg0UWZzBA4ZSyzHHC+VeRA==} + + '@mapbox/unitbezier@0.0.1': + resolution: {integrity: sha512-nMkuDXFv60aBr9soUG5q+GvZYL+2KZHVvsqFCzqnkGEf46U2fvmytHaEVc1/YZbiLn8X+eR3QzX1+dwDO1lxlw==} + + '@mapbox/unitbezier@1.0.0': + resolution: {integrity: sha512-fqd515fjBmANKGGsQ286E2Wvj/XvDFpGzwJxq4CI6jMQue6Oy04uCKp+JWKF00xRTmk6cEu1jPJ9p3xqH8YWqQ==} + + '@mapbox/vector-tile@2.0.5': + resolution: {integrity: sha512-pXj8m7KTsqZt+1jsE0xIpGvqTSbblfkuEJL/NJmNePMtEwxO8V3XMDo9WMSfDeqHvCtBI9Lmt4mGcGR10zecmw==} + + '@mapbox/whoots-js@3.1.0': + resolution: {integrity: sha512-Es6WcD0nO5l+2BOQS4uLfNPYQaNDfbot3X1XUoloz+x0mPDS3eeORZJl06HXjwBG1fOGwCRnzK88LMdxKRrd6Q==} + engines: {node: '>=6.0.0'} + + '@maplibre/geojson-vt@6.3.0': + resolution: {integrity: sha512-3Zw2jsU9pIJG3G2CQFbLjWj2MlAHodhD7cSY+15iywUuLmmkgzcKRnueVRZ4AcC/5wOtfhidcJAAzBpoBNs3Xg==} + + '@maplibre/maplibre-gl-style-spec@24.10.0': + resolution: {integrity: sha512-lichxSiagMEBBrqHF0trtMQH9RKh+9jUlIJl0qW0QHvt2H/tbvUWdE+ZzI2Jd0/pT7j/iavLonlPu7EQ/ixTOw==} + hasBin: true + + '@maplibre/mlt@1.3.0': + resolution: {integrity: sha512-7M2O7ABM80Oi8XPkfkrjKB8mOBIxGoVgkA52Mu4RMWoBvvMdagQ522+WxVYujZsMpqIr3BpzrTbXrm4k8lCzCQ==} + + '@maplibre/vt-pbf@4.3.3': + resolution: {integrity: sha512-dEe5XUd64RQbxNxy2OzIkJnwNDWjVmSXjCd0A7zLirm7QJ/WWbmtDFIkfsiM4yt1cplqzG6oSivRYeWx1SM1yg==} + '@napi-rs/lzma-linux-x64-gnu@1.5.1': resolution: {integrity: sha512-oTXEIha4SsuXdTA4Iyskj0kpdx2yVXdhd75c2v3xGrHFfVMsbhTPZU/nMPL4sWKo4pBHm3aucLaqGlF696dTyQ==} engines: {node: ^22.20 || ^24.12 || >=25} @@ -1860,6 +1902,12 @@ packages: react: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 react-dom: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 + '@tanstack/react-virtual@3.14.26': + resolution: {integrity: sha512-HUDlfsrYH6ko5xH56L62Mcl/uzT+AGVNMHFuDNqDJMdZWc1AQa2oeVKNUvZ/RWBZQ4TYtyQerFrNvLnp39h65A==} + peerDependencies: + react: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 + react-dom: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 + '@tanstack/router-core@1.171.34': resolution: {integrity: sha512-X+19pGuuLVPvvAvPYw9v/+ktRk5cCll8AtfpBpOhDRmVgUMrfqze0467xtq8YRVVs/mmo5rVtWn/7Tp32RDBKw==} engines: {node: '>=20.19'} @@ -1867,6 +1915,9 @@ packages: '@tanstack/store@0.11.2': resolution: {integrity: sha512-sJ4mjol8uQsHV0gOJzzjwXfh2Fwm+Sz0+8deqiTm4jGbMdjzNSW+xZCFm0kUa870uhd8yi+DpKnZb5Kc4apa0Q==} + '@tanstack/virtual-core@3.19.11': + resolution: {integrity: sha512-/5iHb0RHBvj8Di59FDs4ESNm45jls33aZAi4zccVXZjc/6ZvwQP6nzEYeT6weXjTf9E6/vrp2JhYWRyO+ZP13A==} + '@testing-library/dom@10.4.1': resolution: {integrity: sha512-o4PXJQidqJl82ckFaXUeoAW+XysPLauYI43Abki5hABd853iMhitooc6znOnczgbTYmEP6U6/y1ZyKAIsvMKGg==} engines: {node: '>=18'} @@ -2054,6 +2105,9 @@ packages: '@types/estree@1.0.9': resolution: {integrity: sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==} + '@types/geojson@7946.0.16': + resolution: {integrity: sha512-6C8nqWur3j98U6+lXDfTUWIfgvZU+EumvpHKcYjujKH7woYyLj2sUmff0tRhrqM7BohUw7Pz3ZB1jj2gW9Fvmg==} + '@types/json-schema@7.0.15': resolution: {integrity: sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA==} @@ -2407,6 +2461,9 @@ packages: resolution: {integrity: sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==} engines: {node: '>= 0.4'} + earcut@3.2.4: + resolution: {integrity: sha512-FHc6yNpnTORB0tM5kmZ03iD2mDuNakDE2lvf4Hw1XkfxtEHIGVi01B/GqUSwx+NcC1WGjidAfpTXzeALtPtfpg==} + electron-to-chromium@1.5.431: resolution: {integrity: sha512-AAVihz2YwJeOdAynX8MUtqpvjY0gaiARp/7+r4kwqgzqXMrfG1qDN7vwT80uxAoOQRPcZH8t73EI+CA/1OJN8A==} @@ -2559,8 +2616,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: '*' @@ -2610,6 +2667,9 @@ packages: resolution: {integrity: sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==} engines: {node: '>= 0.4'} + gl-matrix@3.4.4: + resolution: {integrity: sha512-latSnyDNt/8zYUB6VIJ6PCh2jBjJX6gnDsoCZ7LyW7GkqrD51EWwa9qCoGixj8YqBtETQK/xY7OmpTF8xz1DdQ==} + glob-parent@6.0.2: resolution: {integrity: sha512-XxwI8EOhVQgWp6iDL+3b0r86f4d6AX6zSU55HfB4ydCEuXLXc5FcYeOu+nnGftS4TEju/11rt4KJPTMgbfmv4A==} engines: {node: '>=10.13.0'} @@ -2772,11 +2832,17 @@ packages: json-stable-stringify-without-jsonify@1.0.1: resolution: {integrity: sha512-Bdboy+l7tA3OGW6FjyFHWkP5LuByj1Tk33Ljyq0axyzdk9//JSi2u3fP1QSmd1KNwq6VOKYGlAu87CisVir6Pw==} + json-stringify-pretty-compact@4.0.0: + resolution: {integrity: sha512-3CNZ2DnrpByG9Nqj6Xo8vqbjT4F6N+tb4Gb28ESAZjYZ5yqvmc56J+/kuIwkaAMOyblTQhUW7PxMkUb8Q36N3Q==} + json5@2.2.3: resolution: {integrity: sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg==} engines: {node: '>=6'} hasBin: true + kdbush@4.1.0: + resolution: {integrity: sha512-e9vurzrXJQrFX6ckpHP3bvj5l+9CnYzkxDNnNQ1h2QTqdWsUAJgXiKdGNcOa1EY85dU8KbQ+z/FdQdB7P+9yfQ==} + keyv@4.5.4: resolution: {integrity: sha512-oxVHkHR/EJf2CNXnWxRLW6mg7JyCCUcG0DtEGmL2ctUo1PNTin1PUil+r/+4r5MpVgC/fn1kjsx7mjSujKqIpw==} @@ -2894,6 +2960,10 @@ packages: resolution: {integrity: sha512-hXdUTZYIVOt1Ex//jAQi+wTZZpUpwBj/0QsOzqegb3rGMMeJiSEu5xLHnYfBrRV4RH2+OCSOO95Is/7x1WJ4bw==} engines: {node: '>=10'} + maplibre-gl@5.24.0: + resolution: {integrity: sha512-ALyFxgtd5R+65UqZ/++lOqwWcC0SNho9c27fYSyLmG7AfnAul2o46F05aDJGPbFU57wos9dgcIySHs0Xe6ia3A==} + engines: {node: '>=16.14.0', npm: '>=8.1.0'} + math-intrinsics@1.1.0: resolution: {integrity: sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==} engines: {node: '>= 0.4'} @@ -2920,6 +2990,9 @@ packages: minimatch@3.1.5: resolution: {integrity: sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w==} + minimist@1.2.8: + resolution: {integrity: sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==} + minipass@7.1.3: resolution: {integrity: sha512-tEBHqDnIoM/1rXME1zgka9g6Q2lcoCkxHLuc7ODJ5BxbP5d4c2Z5cGgtXAku59200Cx7diuHTOYfSBD8n6mm8A==} engines: {node: '>=16 || 14 >=14.17'} @@ -2947,6 +3020,9 @@ packages: ms@2.1.3: resolution: {integrity: sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==} + murmurhash-js@1.0.0: + resolution: {integrity: sha512-TvmkNhkv8yct0SVBSy+o8wYzXjE4Zz3PCesbfs8HiCXXdcTuocApFv11UWlNFWKYsP2okqrhb7JNlSm9InBhIw==} + nanoid@3.3.20: resolution: {integrity: sha512-uKdg2G3GNCKQn9byYOpxbGqrT2fGO5KRt5J/8b3pok8rT6qxGWF6hxMyJiEYtAf+FVyYuD9hRaDqX5uPFYJ4ZQ==} engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1} @@ -3018,6 +3094,14 @@ packages: pathe@2.0.3: resolution: {integrity: sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==} + pbf@4.0.2: + resolution: {integrity: sha512-J0ajxARhZfpUEebxYs1vhMGMuLSXtBe1e+fFPDrf2uA2hgo+UshKfNUWOz92HJNz6/NFEXseQPddnHkTreWRqg==} + hasBin: true + + pbf@5.1.2: + resolution: {integrity: sha512-mnvGdvOrIvJOBGUEdGkrVXjN8E/VkIJCkf2eS1DH2yv82ORUlLttmDt0rWY38yYZmVwciZwBUvHM20qxBZf40w==} + hasBin: true + picocolors@1.1.1: resolution: {integrity: sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==} @@ -3040,6 +3124,9 @@ packages: react: optional: true + potpack@2.1.0: + resolution: {integrity: sha512-pcaShQc1Shq0y+E7GqJqvZj8DTthWV1KeHGdi0Z6IAin2Oi3JnLCOfwnCo84qc+HAp52wT9nK9H7FAJp5a44GQ==} + preact@10.29.8: resolution: {integrity: sha512-ej2aVZ+vZ8WO7tvlQWRM9N63A0KzF9q4mWJfDUHgYaIofWY9hu74QdnQrjoPMmZi2/nZ5gN0bJCQF49xQqx09Q==} peerDependencies: @@ -3099,6 +3186,9 @@ packages: prosemirror-view@1.42.4: resolution: {integrity: sha512-H/LErnE8Vms1GYkvhfj6G3K9rc2p+o5EHGmTwvPOl0f21wPPxlMVRB8ICOseH+COb2oPKFEoufbgY6yet/dR4w==} + protocol-buffers-schema@3.6.1: + resolution: {integrity: sha512-VG2K63Igkiv9p76tk1lilczEK1cT+kCjKtkdhw1dQZV3k3IXJbd3o6Ho8b9zJZaHSnT2hKe4I+ObmX9w6m5SmQ==} + proxy-from-env@1.1.0: resolution: {integrity: sha512-D+zkORCbA9f1tdWRK0RaCR3GPv50cMxcrz4X8k5LTSUD1Dkw47mKJEZQNunItRTkWwgtaUSo1RVFRIG9ZXiFYg==} @@ -3118,6 +3208,9 @@ packages: query-selector-shadow-dom@1.0.1: resolution: {integrity: sha512-lT5yCqEBgfoMYpf3F2xQRK7zEr1rhIIZuceDK6+xRkJQ4NMbHTwXqk4NkwDwQMNqXgG9r9fyHnzwNVs6zV5KRw==} + quickselect@3.0.0: + resolution: {integrity: sha512-XdjUArbK4Bm5fLLvlm5KpTFOiOThgfWWI4axAZDWg4E/0mKdZyI9tNEfds27qCi1ze/vwTR16kvmmGhRra3c2g==} + react-dom@19.3.0: resolution: {integrity: sha512-JDk8dgif51OjFoDE70+OT9ICyYr+69HlmihNwp1+Nsfbna3t5sIiCa9ZJktDmQ4/1b/rn26hIAR2uYXDMr5r0Q==} peerDependencies: @@ -3205,6 +3298,9 @@ packages: resolution: {integrity: sha512-pb/MYmXstAkysRFx8piNI1tGFNQIFA3vkE3Gq4EuA1dF6gHp/+vgZqsCGJapvy8N3Q+4o7FwvquPJcnZ7RYy4g==} engines: {node: '>=4'} + resolve-protobuf-schema@2.1.0: + resolution: {integrity: sha512-kI5ffTiZWmJaS/huM8wZfEMer1eRd7oJQhDuxeCLe3t7N7mX3z94CN0xPxBQxFYQTSNz9T0i+v6inKqSdK8xrQ==} + rollup@4.65.0: resolution: {integrity: sha512-QVCvQUTGDN6JRwi3jVGCY3H4aTHvi9rX0LyoBMkGUvdh/Z6O51CzcLz85BWZaTCDGhl6ySGqYZs+xI1jmPqGcw==} engines: {node: '>=18.0.0', npm: '>=8.0.0'} @@ -3233,17 +3329,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==} @@ -3338,6 +3434,9 @@ packages: resolution: {integrity: sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==} engines: {node: '>=12.0.0'} + tinyqueue@3.0.0: + resolution: {integrity: sha512-gRa9gwYU3ECmQYv3lslts5hxuIa90veaEcxDYuu3QGOIAEM2mOZkVHp48ANJuu1CURtRdHKUBY5Lm1tHV+sD4g==} + tinyrainbow@3.1.1: resolution: {integrity: sha512-yau8yJdTt989Mm0Bd/236QnzEiPf2xLLTqUZRUJOo/3CB078LSwzei343DgtJVmfJKJE3TMINY1u42SQsP6mXw==} engines: {node: '>=14.0.0'} @@ -3634,20 +3733,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 +3771,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 +3804,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 +3824,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 +3832,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 +3975,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 +3998,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 @@ -4012,6 +4111,47 @@ snapshots: '@solid-primitives/utils': 6.4.1(solid-js@1.9.15) solid-js: 1.9.15 + '@mapbox/jsonlint-lines-primitives@2.0.3': {} + + '@mapbox/point-geometry@1.1.0': {} + + '@mapbox/tiny-sdf@2.3.0': {} + + '@mapbox/unitbezier@0.0.1': {} + + '@mapbox/unitbezier@1.0.0': {} + + '@mapbox/vector-tile@2.0.5': + dependencies: + '@mapbox/point-geometry': 1.1.0 + '@types/geojson': 7946.0.16 + pbf: 4.0.2 + + '@mapbox/whoots-js@3.1.0': {} + + '@maplibre/geojson-vt@6.3.0': + dependencies: + kdbush: 4.1.0 + + '@maplibre/maplibre-gl-style-spec@24.10.0': + dependencies: + '@mapbox/jsonlint-lines-primitives': 2.0.3 + '@mapbox/unitbezier': 1.0.0 + json-stringify-pretty-compact: 4.0.0 + minimist: 1.2.8 + quickselect: 3.0.0 + tinyqueue: 3.0.0 + + '@maplibre/mlt@1.3.0': + dependencies: + '@mapbox/point-geometry': 1.1.0 + + '@maplibre/vt-pbf@4.3.3': + dependencies: + '@mapbox/point-geometry': 1.1.0 + '@types/geojson': 7946.0.16 + pbf: 5.1.2 + '@napi-rs/lzma-linux-x64-gnu@1.5.1': optional: true @@ -4669,10 +4809,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 +4848,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 +4895,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 @@ -4964,15 +5104,23 @@ snapshots: react-dom: 19.3.0(react@19.3.0) use-sync-external-store: 1.7.0(react@19.3.0) + '@tanstack/react-virtual@3.14.26(react-dom@19.3.0(react@19.3.0))(react@19.3.0)': + dependencies: + '@tanstack/virtual-core': 3.19.11 + react: 19.3.0 + react-dom: 19.3.0(react@19.3.0) + '@tanstack/router-core@1.171.34': 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': {} + '@tanstack/virtual-core@3.19.11': {} + '@testing-library/dom@10.4.1': dependencies: '@babel/code-frame': 7.29.7 @@ -5174,6 +5322,8 @@ snapshots: '@types/estree@1.0.9': {} + '@types/geojson@7946.0.16': {} + '@types/json-schema@7.0.15': {} '@types/node@24.13.5': @@ -5197,15 +5347,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 +5363,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 +5393,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 +5407,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 +5422,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 +5438,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 +5462,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 +5519,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 +5564,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 +5684,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: {} @@ -5566,6 +5718,8 @@ snapshots: es-errors: 1.3.0 gopd: 1.2.0 + earcut@3.2.4: {} + electron-to-chromium@1.5.431: {} enhanced-resolve@5.25.1: @@ -5625,13 +5779,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 +5798,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 +5815,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 +5895,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: @@ -5787,6 +5943,8 @@ snapshots: dunder-proto: 1.0.1 es-object-atoms: 1.1.2 + gl-matrix@3.4.4: {} + glob-parent@6.0.2: dependencies: is-glob: 4.0.3 @@ -5831,24 +5989,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 +6065,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 +6074,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 @@ -5943,8 +6101,12 @@ snapshots: json-stable-stringify-without-jsonify@1.0.1: {} + json-stringify-pretty-compact@4.0.0: {} + json5@2.2.3: {} + kdbush@4.1.0: {} + keyv@4.5.4: dependencies: json-buffer: 3.0.1 @@ -6037,6 +6199,28 @@ snapshots: dependencies: semver: 7.8.5 + maplibre-gl@5.24.0: + dependencies: + '@mapbox/jsonlint-lines-primitives': 2.0.3 + '@mapbox/point-geometry': 1.1.0 + '@mapbox/tiny-sdf': 2.3.0 + '@mapbox/unitbezier': 0.0.1 + '@mapbox/vector-tile': 2.0.5 + '@mapbox/whoots-js': 3.1.0 + '@maplibre/geojson-vt': 6.3.0 + '@maplibre/maplibre-gl-style-spec': 24.10.0 + '@maplibre/mlt': 1.3.0 + '@maplibre/vt-pbf': 4.3.3 + '@types/geojson': 7946.0.16 + earcut: 3.2.4 + gl-matrix: 3.4.4 + kdbush: 4.1.0 + murmurhash-js: 1.0.0 + pbf: 4.0.2 + potpack: 2.1.0 + quickselect: 3.0.0 + tinyqueue: 3.0.0 + math-intrinsics@1.1.0: {} mdn-data@2.27.1: {} @@ -6057,6 +6241,8 @@ snapshots: dependencies: brace-expansion: 1.1.21 + minimist@1.2.8: {} + minipass@7.1.3: {} motion-dom@12.43.0: @@ -6075,6 +6261,8 @@ snapshots: ms@2.1.3: {} + murmurhash-js@1.0.0: {} + nanoid@3.3.20: {} natural-compare@1.4.0: {} @@ -6132,6 +6320,14 @@ snapshots: pathe@2.0.3: {} + pbf@4.0.2: + dependencies: + resolve-protobuf-schema: 2.1.0 + + pbf@5.1.2: + dependencies: + resolve-protobuf-schema: 2.1.0 + picocolors@1.1.1: {} picomatch@4.0.7: {} @@ -6160,6 +6356,8 @@ snapshots: transitivePeerDependencies: - preact-render-to-string + potpack@2.1.0: {} + preact@10.29.8: {} prelude-ls@1.2.1: {} @@ -6246,6 +6444,8 @@ snapshots: prosemirror-state: 1.4.4 prosemirror-transform: 1.12.1 + protocol-buffers-schema@3.6.1: {} + proxy-from-env@1.1.0: {} proxy-from-env@2.1.0: {} @@ -6258,6 +6458,8 @@ snapshots: query-selector-shadow-dom@1.0.1: {} + quickselect@3.0.0: {} + react-dom@19.3.0(react@19.3.0): dependencies: react: 19.3.0 @@ -6326,6 +6528,10 @@ snapshots: resolve-from@4.0.0: {} + resolve-protobuf-schema@2.1.0: + dependencies: + protocol-buffers-schema: 3.6.1 + rollup@4.65.0: dependencies: '@types/estree': 1.0.9 @@ -6370,15 +6576,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 +6597,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: @@ -6456,6 +6662,8 @@ snapshots: fdir: 6.5.0(picomatch@4.0.7) picomatch: 4.0.7 + tinyqueue@3.0.0: {} + tinyrainbow@3.1.1: {} tldts-core@7.4.13: {} @@ -6486,13 +6694,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 +6752,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 +6777,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/securityHeaders.ts b/web/securityHeaders.ts index f3a97984a..f5272d611 100644 --- a/web/securityHeaders.ts +++ b/web/securityHeaders.ts @@ -1,5 +1,8 @@ export const mailPreviewCsp = "default-src 'none'; script-src 'none'; object-src 'none'; base-uri 'none'; form-action 'none'; frame-ancestors 'self'; style-src 'unsafe-inline'; img-src data: https: http:; font-src data: https:; media-src https:"; +// The lead finder map's default tiles, styles, sprites and glyphs all come from here. +export const mapTileOrigin = "https://tiles.openfreemap.org"; + export function dashboardCsp({ scripts = [], styles = [], nonce = "", connections = [], analytics = [], images = [] }: { scripts?: string[]; styles?: string[]; @@ -15,7 +18,7 @@ export function dashboardCsp({ scripts = [], styles = [], nonce = "", connection "script-src-attr 'none'", `style-src 'self' ${[...authorization, ...styles].join(" ")}`, "style-src-attr 'unsafe-inline'", - `connect-src 'self' ${[...connections, ...analytics].join(" ")}`, + `connect-src 'self' ${mapTileOrigin} ${[...connections, ...analytics].join(" ")}`, `img-src 'self' data: blob: ${images.join(" ")}`, "font-src 'self'", "frame-src 'self' https://challenges.cloudflare.com", diff --git a/web/src/app/app/analytics/page.tsx b/web/src/app/app/analytics/page.tsx index fe958bc11..d36515343 100644 --- a/web/src/app/app/analytics/page.tsx +++ b/web/src/app/app/analytics/page.tsx @@ -33,6 +33,7 @@ import AnalyticsShareButton from "@/components/app/analytics/AnalyticsShareButto import CampaignScopePicker from "@/components/app/analytics/CampaignScopePicker"; import { ALL_CAMPAIGNS, isScoped, scopeLabel } from "@/components/app/analytics/campaignScope"; import useDashboard from "@/lib/api/hooks/app/analytics/useDashboard"; +import { periodWindow } from "@/lib/campaignPeriod"; import DirectMailSection from "@/components/app/analytics/DirectMailSection"; import OriginBadge from "@/components/app/engagement/OriginBadge"; import type { DashboardCampaignFilter, RecentActivityItem } from "@/lib/api/models/app/analytics/DashboardOverview"; @@ -98,6 +99,7 @@ export default function AnalyticsPage() { return [...cur, k]; }); + const chartRange = useMemo(() => periodWindow({ key: range }), [range]); const trend = useMemo(() => { const rows = d?.daily_trend ?? []; const series: TrendSeries[] = METRICS.filter((m) => !hiddenMetrics.includes(m.key)).map((m) => ({ @@ -185,6 +187,8 @@ export default function AnalyticsPage() { diff --git a/web/src/app/app/campaigns/[id]/page.tsx b/web/src/app/app/campaigns/[id]/page.tsx index c0865d077..95c730fa4 100644 --- a/web/src/app/app/campaigns/[id]/page.tsx +++ b/web/src/app/app/campaigns/[id]/page.tsx @@ -266,6 +266,8 @@ export default function CampaignOverview() { (null); - const canManage = usePermission("MANAGE_CAMPAIGNS"); + // Creating, drafting and filing campaigns reach past a restricted member's grants. + const restricted = useAccessRestricted(); + const canManage = usePermission("MANAGE_CAMPAIGNS") && !restricted; const [launchTarget, setLaunchTarget] = useState(null); async function toggleCampaign(id: string, currentStatus: string) { @@ -332,19 +334,23 @@ export default function CampaignsPage() { : `${campaigns.length} ${campaigns.length === 1 ? "campaign" : "campaigns"}` } > - } - onClick={() => p.setFoldersEdit(true)} - > - Folders - - } - onClick={() => setNewOpen(true)} - > - New campaign - + {!restricted && ( + <> + } + onClick={() => p.setFoldersEdit(true)} + > + Folders + + } + onClick={() => setNewOpen(true)} + > + New campaign + + + )} @@ -489,12 +495,14 @@ export default function CampaignsPage() { title="No campaigns yet" body="Create your first sequence to start reaching prospects." cta={ - } - onClick={() => setNewOpen(true)} - > - New campaign - + restricted ? undefined : ( + } + onClick={() => setNewOpen(true)} + > + New campaign + + ) } /> ) : ( @@ -560,7 +568,7 @@ export default function CampaignsPage() { }) : "—"} - + {!restricted && }
{/* Too narrow for the metric columns: the same readings, labelled, under the address. */}
- + Warmup {cloudStatusPending ? statusPending ? "Checking…" : "Unavailable" : warmupCell} @@ -1143,8 +1225,8 @@ function MailboxRow({ Health - {historicalIssue && Last observed} - {status?.health?.score ?? historicalIssue?.status.health?.score ?? "—"} + {(historicalIssue || stale) && Last observed} + {displayedHealth?.health?.score ?? "—"}
@@ -1155,18 +1237,18 @@ function MailboxRow({
- + - {status?.daily_usage ? ( + {dailyUsage ? ( 0 ? "text-sky-700" : "text-slate-500"}`} - title={`${status.daily_usage.campaign_sent} of ${status.daily_usage.campaign_limit || box.campaign_limit} campaign emails sent today`} + className={`inline-flex items-center gap-1.5 font-mono text-[12px] tabular-nums ${dailyUsage.campaign_sent > 0 ? "text-sky-700" : "text-slate-500"}`} + title={`${dailyUsage.campaign_sent} of ${dailyUsage.campaign_limit || box.campaign_limit} campaign emails sent today`} > - - /{status.daily_usage.campaign_limit || box.campaign_limit} + + /{dailyUsage.campaign_limit || box.campaign_limit} ) : ( @@ -1192,10 +1274,10 @@ function MailboxRow({ type="button" onClick={(e) => { e.stopPropagation(); onOpen(box.id, "overview"); }} className={`inline-flex items-center gap-1.5 text-[11px] font-medium max-w-full ${tone.text}`} - title={historicalIssue ? `Last observed ${new Date(historicalIssue.observedAt).toLocaleString()}. Current health unavailable.` : status?.health?.issues?.join("\n") || "View mailbox health"} + title={historicalIssue ? `Last observed ${new Date(historicalIssue.observedAt).toLocaleString()}. Current health unavailable.` : stale ? "Last known measurements. Current status is unconfirmed until a successful refresh." : status?.health?.issues?.join("\n") || "View mailbox health"} > - + e.stopPropagation()}> @@ -1205,7 +1287,7 @@ function MailboxRow({ + +
+ + = 9 ? view.center : null} + provider={provider} + onProvider={pickProvider} + area={area} + onClearArea={() => { + setArea(null); + setSearched(null); + }} + onTool={(t) => { + setTool(t); + setSideOpen(false); + }} + searching={search.isPending} + onSearch={runSearch} + blockedReason={blockedReason} + /> + + + { + openSearch(s); + setSideOpen(false); + }} + onDelete={(id) => id === searchId && clearSearch()} + /> + +
+ + ); + + return ( +
+
+ + +

Lead finder

+
+ {currentSearch ? ( + + {currentSearch.name} + + + ) : ( + All leads + )} + {currentSearch?.has_more && ( + + )} +
+ {( + [ + ["map", "Map", MapIcon], + ["split", "Split", Columns2Icon], + ["list", "List", ListIcon], + ] as const + ).map(([key, label, Icon]) => ( + + ))} +
+
+ +
+ + {sideOpen &&
{sidebar}
} + +
+ + {!showList && } + {showMap && ( +
+ setTool("pan")} + onArea={setArea} + onLasso={onLasso} + onPick={pickPoint} + onView={(v) => { + setView(v); + patchPrefs({ view: { center: v.center, zoom: v.zoom } }); + }} + /> + + controls.current?.zoomBy(d)} + onFit={() => { + const pts = points.data?.data ?? []; + if (pts.length) flyTo({ bounds: boundsOf(pts.map((p) => ({ lat: p.latitude, lng: p.longitude }))) }); + else if (shownArea) flyTo({ bounds: shownArea.bounds }); + }} + /> + {tool !== "pan" && setTool("pan")} />} + {tool === "pan" && !blockedReason && ( +
+ +
+ )} + + {points.isFetching && ( +
+ + Updating pins +
+ )} + {!searchId && (points.data?.data.length ?? 0) === 0 && !points.isPending && } +
+ )} + {showList && ( +
+ list.refetch()} + hasMore={!!list.hasNextPage} + loadingMore={list.isFetchingNextPage} + onMore={() => list.fetchNextPage()} + sort={sort} + onSort={setSort} + selected={selected} + allMatching={allMatching} + onToggle={toggle} + onTogglePage={(on) => { + setAllMatching(false); + setSelected(on ? new Set(leads.map((l) => l.id)) : new Set()); + }} + onSelectAllMatching={() => setAllMatching(true)} + activeId={activeId} + onOpen={(id) => { + setActiveId(id); + const l = leads.find((x) => x.id === id); + if (l && showMap) flyTo({ center: { lat: l.latitude, lng: l.longitude }, zoom: 15 }); + }} + onHover={setHoverId} + banner={} + /> +
+ )} + setActiveId(null)} + onAddToContacts={(id) => setDialog({ kind: "contacts", selection: { lead_ids: [id] }, count: 1 })} + /> +
+
+ + startEnrich(selection)} + onAddToContacts={() => setDialog({ kind: "contacts", selection, count: selectedCount })} + onExport={() => setDialog({ kind: "export", selection, count: selectedCount })} + onStatus={setStatus} + onTag={addTag} + onDelete={deleteSelected} + onClear={clearSelection} + /> + setDialog(null)} + selection={dialog?.selection ?? {}} + count={dialog?.count ?? 0} + suggestedSegment={currentSearch?.name} + /> + setDialog(null)} selection={dialog?.selection ?? {}} count={dialog?.count ?? 0} config={config} /> +
+ ); +} + +const TOOLS: { id: MapTool; label: string; icon: React.ReactNode }[] = [ + { id: "pan", label: "Move the map", icon: }, + { id: "rect", label: "Draw a rectangle to search", icon: }, + { id: "circle", label: "Draw a circle to search", icon: }, + { id: "polygon", label: "Draw a shape to search", icon: }, + { id: "lasso", label: "Lasso leads to select them", icon: }, +]; + +function MapToolbar({ tool, onTool }: { tool: MapTool; onTool: (t: MapTool) => void }) { + return ( +
+ {TOOLS.map((t) => ( + + ))} +
+ ); +} + +const HINTS: Record, string> = { + rect: "Drag to draw a rectangle", + circle: "Drag from the center outwards", + polygon: "Click to add corners; double-click or Enter to finish", + lasso: "Drag around the leads you want to select", +}; + +function ToolHint({ tool, onCancel }: { tool: Exclude; onCancel: () => void }) { + return ( +
+ {HINTS[tool]} + +
+ ); +} + +function MapControlsBar({ prefs, onPrefs, onZoom, onFit }: { prefs: Prefs; onPrefs: (p: Partial) => void; onZoom: (d: number) => void; onFit: () => void }) { + const btn = "size-7 rounded-md inline-flex items-center justify-center text-slate-600 hover:bg-slate-100 hover:text-slate-900"; + const check = (on: boolean) => (on ? : undefined); + return ( +
+
+ + + + + + Show leads as + onPrefs({ layer: "pins" })} trailing={check(prefs.layer === "pins")}> + Pins + + onPrefs({ layer: "heat" })} trailing={check(prefs.layer === "heat")}> + Heatmap + + + Color pins by + {( + [ + ["reach", "Reachability"], + ["status", "Status"], + ["score", "Score"], + ["rating", "Rating"], + ] as const + ).map(([id, label]) => ( + onPrefs({ colorBy: id })} trailing={check(prefs.colorBy === id)}> + {label} + + ))} + + Map style + {( + [ + ["auto", "Match the dashboard"], + ["light", "Light"], + ["dark", "Dark"], + ["streets", "Streets"], + ] as const + ).map(([id, label]) => ( + onPrefs({ style: id })} trailing={check(prefs.style === id)}> + {label} + + ))} + + + + +
+
+ + +
+
+ ); +} + +function Legend({ colorBy, layer, count, truncated }: { colorBy: ColorBy; layer: MapLayerMode; count: number; truncated: boolean }) { + return ( +
+ + {count.toLocaleString()} + {truncated ? "+" : ""} on map + + {layer === "pins" && + LEGEND[colorBy].map((l) => ( + + + {l.label} + + ))} + {layer === "heat" && Brighter where leads are denser and better} +
+ ); +} + +function EmptyHint() { + return ( +
+
+ +

Find businesses on the map

+

+ Pick a category, go to a city, then search the view or draw the exact area. Find people and emails reads each business's own website for who runs it and how to reach them. +

+
+
+ ); +} diff --git a/web/src/app/app/placement/[id]/page.tsx b/web/src/app/app/placement/[id]/page.tsx index ead0e6524..c357b1521 100644 --- a/web/src/app/app/placement/[id]/page.tsx +++ b/web/src/app/app/placement/[id]/page.tsx @@ -40,6 +40,7 @@ import { resolvedCount, } from "@/components/app/placement/tests/placementTests"; import { cn } from "@/lib/utils"; +import { fmtUsdCost } from "@/lib/money"; export default function PlacementTestPage() { const { id = "" } = useParams({ from: "/app/placement/$id" }); @@ -112,11 +113,11 @@ function Detail({ test }: { test: PlacementTestDetail }) { {test.finished_at && Finished {fmtDate(test.finished_at)}} {test.origin !== "manual" && test.origin !== "batch" && {ORIGIN_LABEL[test.origin] ?? test.origin}} {test.pace === "quick" && Quick pace} - {test.credits_charged > 0 && ( - 0 ? "No copy was delivered, so the credits came back." : "Paid past the month's free tests."}> - {test.credits_refunded > 0 - ? `${test.credits_refunded} of ${test.credits_charged} credits refunded` - : `Paid ${test.credits_charged} credits`} + {test.charged_usd > 0 && ( + 0 ? "No copy was delivered, so the charge was refunded." : "Paid past the month's free tests."}> + {test.refunded_usd > 0 + ? `${fmtUsdCost(test.refunded_usd)} of ${fmtUsdCost(test.charged_usd)} refunded` + : `Paid ${fmtUsdCost(test.charged_usd)}`} )} {test.campaign_id && ( diff --git a/web/src/app/app/placement/batches/[id]/page.tsx b/web/src/app/app/placement/batches/[id]/page.tsx index 99d4c443d..549efba66 100644 --- a/web/src/app/app/placement/batches/[id]/page.tsx +++ b/web/src/app/app/placement/batches/[id]/page.tsx @@ -43,6 +43,7 @@ import { scopeSummary, } from "@/components/app/placement/batches/placementBatches"; import { cn } from "@/lib/utils"; +import { fmtUsdCost } from "@/lib/money"; type Tab = "mailboxes" | "domains" | "providers" | "recipients"; @@ -151,7 +152,7 @@ function Detail({ batch }: { batch: PlacementBatchDetail }) { {scopeSummary(batch)} {batch.started_at ? `Started ${fmtDate(batch.started_at)}` : `Queued ${fmtDate(batch.created_at)}`} {batch.finished_at && Finished {fmtDate(batch.finished_at)}} - {batch.credits_spent > 0 && Paid {batch.credits_spent.toLocaleString()} credits} + {batch.spent_usd > 0 && Paid {fmtUsdCost(batch.spent_usd)}} {batch.campaign_id && ( {campaign.data?.name ?? "Campaign"} diff --git a/web/src/app/app/placement/page.tsx b/web/src/app/app/placement/page.tsx index 516ee7cdf..e80eedc6d 100644 --- a/web/src/app/app/placement/page.tsx +++ b/web/src/app/app/placement/page.tsx @@ -35,6 +35,7 @@ import { } from "@/components/app/placement/tests/PlacementParts"; import { ORIGIN_LABEL, fmtDate, fmtRate, rateTone, usageLabel } from "@/components/app/placement/tests/placementTests"; import { cn } from "@/lib/utils"; +import { fmtUsdCost } from "@/lib/money"; type Tab = "tests" | "batches" | "seeds"; @@ -90,8 +91,8 @@ export default function PlacementPage() { > {exhausted && ( - {usage.credits_per_test > 0 - ? `More tests cost ${usage.credits_per_test} credits each. Your own seed inboxes are always free.` + {usage.price_per_test_usd > 0 + ? `More tests cost ${fmtUsdCost(usage.price_per_test_usd)} each. Your own seed inboxes are always free.` : "Your own seed inboxes are never counted."} )} diff --git a/web/src/app/app/settings/_components/SectionShell.tsx b/web/src/app/app/settings/_components/SectionShell.tsx index 5af4d13ae..3761153d6 100644 --- a/web/src/app/app/settings/_components/SectionShell.tsx +++ b/web/src/app/app/settings/_components/SectionShell.tsx @@ -169,10 +169,13 @@ export function Toggle({ on, onChange, disabled, + label, }: { on: boolean; onChange: (next: boolean) => void; disabled?: boolean; + /** Accessible name for the switch, usually the row's label. */ + label?: string; }) { return ( - - Buy a pack automatically with the card on file when credits run low - - - - {form.autoEnabled && ( - -
-
- - setForm({ ...form, autoPack: v })} - options={packs.map((p) => ({ value: p.key, label: `${p.credits.toLocaleString()} credits` }))} - className="w-full" - fullWidth - /> -
-
- - setForm({ ...form, autoThreshold: Math.max(0, Math.round(n)) })} - min={0} - max={1000000} - className="w-full" - /> -
-
- - setForm({ ...form, autoMax: Math.max(0, Math.min(100, Math.round(n))) })} - min={0} - max={100} - className="w-full" - /> -
-
-
- )} -
+

+ Sent once until money is added, and not while automatic reload covers it. +

@@ -347,7 +252,7 @@ export default function AIUsageCard() { className="sticky bottom-4 z-10 flex justify-center" >
- Unsaved spend controls + Unsaved limits
@@ -431,7 +336,7 @@ function Breakdown({ } function fmtCompact(n: number): string { - return n >= 1000 ? `${n % 1000 === 0 ? n / 1000 : (n / 1000).toFixed(1)}k` : String(n); + return n >= 1000 ? `$${n % 1000 === 0 ? n / 1000 : (n / 1000).toFixed(1)}k` : fmtUsdTrim(n); } // RangeToggle switches the usage graph window (the backend serves 1-90 days). @@ -457,8 +362,8 @@ function RangeToggle({ range, onChange }: { range: RangeDays; onChange: (r: Rang ); } -// InlineNumber renders a value as editable text (no input chrome): click to -// type an exact amount, Enter/blur commits, digits only. +// InlineNumber renders a dollar value as editable text (no input chrome): +// click to type an exact amount, Enter/blur commits. function InlineNumber({ value, onCommit, @@ -468,21 +373,23 @@ function InlineNumber({ onCommit: (n: number) => void; className?: string; }) { - const [text, setText] = React.useState(String(value)); + const show = (n: number) => (Number.isInteger(n) ? String(n) : n.toFixed(2)); + const [text, setText] = React.useState(show(value)); React.useEffect(() => { - setText(String(value)); + setText(Number.isInteger(value) ? String(value) : value.toFixed(2)); }, [value]); const commit = () => { - const n = Math.max(1, Math.round(Number(text) || value)); - setText(String(n)); + const n = Math.max(0.01, parseUsd(text) ?? value); + setText(show(n)); if (n !== value) onCommit(n); }; return ( setText(e.target.value.replace(/[^\d]/g, ""))} + onChange={(e) => setText(e.target.value.replace(/[^\d.,]/g, ""))} onFocus={(e) => e.currentTarget.select()} onBlur={commit} onKeyDown={(e) => { @@ -515,7 +422,7 @@ function LimitCell({ const on = value !== null; const presets = WINDOW_PRESETS[windowKey]; const sliderMax = Math.max(WINDOW_SLIDER_MAX[windowKey], value ?? 0); - const pct = on && spent !== undefined ? Math.min(100, Math.round((spent / Math.max(1, value)) * 100)) : null; + const pct = on && spent !== undefined ? Math.min(100, Math.round((spent / Math.max(0.01, value)) * 100)) : null; return (
@@ -548,13 +455,13 @@ function LimitCell({ className="overflow-hidden" >
-
+
+ $ onChange(n)} className="text-[17px] font-semibold text-slate-900 tabular-nums" /> - credits
{spentLabel} - {spent.toLocaleString()} / {(value ?? 0).toLocaleString()} + {fmtUsd(spent)} / {fmtUsdTrim(value ?? 0)}
diff --git a/web/src/app/app/settings/billing/AutoReloadSection.tsx b/web/src/app/app/settings/billing/AutoReloadSection.tsx new file mode 100644 index 000000000..344070893 --- /dev/null +++ b/web/src/app/app/settings/billing/AutoReloadSection.tsx @@ -0,0 +1,294 @@ +// Automatic reload: the switch saves at once; stepper edits save together after +// a short pause. Both are optimistic and roll back on error. The three amounts +// bound each other so the server's 422s cannot happen. + +import React from "react"; +import { useQueryClient } from "@tanstack/react-query"; +import { CreditCardIcon, Loader2Icon, RefreshCwIcon } from "lucide-react"; +import { Toggle } from "@/components/app/campaigns/preferences/components/CampaignPreferenceBoolBox"; +import UsdStepper from "@/components/app/billing/UsdStepper"; +import { RELOAD_FAILURE_COPY, fmtClock, fmtDay } from "@/components/app/billing/balanceModel"; +import { updateAutoReload } from "@/lib/api/client/app/subscription/balance"; +import type { AppError } from "@/lib/api/client/normalizeError"; +import { + RESUME_AUTO_RELOAD_KEY, + balanceQuery, + useAddPaymentMethod, + useUpdateAutoReload, +} from "@/lib/api/hooks/app/subscription/useBalance"; +import type { AutoReload, AutoReloadPatch, Balance } from "@/lib/api/models/app/subscription/Credits"; +import buildError from "@/lib/helper/buildError"; +import { MAX_TOP_UP_USD, MIN_TOP_UP_USD, fmtUsd, fmtUsdTrim, roundCents } from "@/lib/money"; +import toast from "react-hot-toast/headless"; +import { cn } from "@/lib/utils"; +import { Row, Section } from "../_components/SectionShell"; + +const SAVE_DELAY = 600; +const LIMIT_MAX = 50_000; +const THRESHOLD_MAX = 1_000; + +type Draft = Partial>; + +export default function AutoReloadSection({ balance }: { balance: Balance }) { + const qc = useQueryClient(); + const save = useUpdateAutoReload(); + const addCard = useAddPaymentMethod(); + const [needsCard, setNeedsCard] = React.useState(false); + const [draft, setDraft] = React.useState({}); + const pending = React.useRef({}); + const timer = React.useRef | undefined>(undefined); + const latest = React.useRef(balance.auto_reload); + latest.current = balance.auto_reload; + + // Leaving the page within the pause still saves the last edit. + React.useEffect( + () => () => { + clearTimeout(timer.current); + const p = pending.current; + const ar = latest.current; + if (!ar || Object.keys(p).length === 0) return; + pending.current = {}; + void updateAutoReload(toPatch(ar, p)) + .then((next) => qc.setQueryData(balanceQuery.queryKey, next)) + .catch(() => qc.invalidateQueries({ queryKey: balanceQuery.queryKey })); + }, + [qc], + ); + + const ar = balance.auto_reload; + if (!ar) return null; + const v: AutoReload = { ...ar, ...draft }; + const pm = balance.payment_method ?? null; + + const send = (patch: AutoReloadPatch) => + save.mutate(patch, { + onError: (e) => { + const err = e as unknown as AppError; + if (err?.code === "payment_method_required") setNeedsCard(true); + else toast.error(buildError(err)); + }, + }); + + const flush = (enabled?: boolean) => { + clearTimeout(timer.current); + const p = pending.current; + pending.current = {}; + setDraft({}); + if (enabled === undefined && Object.keys(p).length === 0) return; + send({ ...toPatch(ar, p), ...(enabled === undefined ? {} : { enabled }) }); + }; + const edit = (patch: Draft) => { + pending.current = { ...pending.current, ...patch }; + setDraft(pending.current); + clearTimeout(timer.current); + timer.current = setTimeout(() => flush(), SAVE_DELAY); + }; + const goAddCard = (resume: boolean) => { + if (resume) { + try { + sessionStorage.setItem(RESUME_AUTO_RELOAD_KEY, JSON.stringify({ ...toPatch(ar, pending.current), enabled: true })); + } catch { + /* private mode: turned on again by hand after the card is saved */ + } + } + addCard.mutate(); + }; + const toggle = (enabled: boolean) => { + if (enabled && !pm) { + goAddCard(true); + return; + } + if (!enabled) setNeedsCard(false); + flush(enabled); + }; + + // One reload must lift the balance back above the threshold and fit the monthly limit. + const maxThreshold = Math.max(0.01, Math.min(THRESHOLD_MAX, roundCents(v.amount_usd - 0.01))); + const minAmount = Math.min(MAX_TOP_UP_USD, Math.max(MIN_TOP_UP_USD, Math.floor(v.threshold_usd) + 1)); + const maxAmount = Math.max(minAmount, Math.min(MAX_TOP_UP_USD, v.monthly_limit_usd)); + const minLimit = Math.max(MIN_TOP_UP_USD, v.amount_usd); + const failure = !v.enabled && ar.failure_code ? ar.failure_code : null; + const retryAt = v.enabled && ar.retry_at ? new Date(ar.retry_at) : null; + const last = ar.last_reload; + + return ( +
+
+ {addCard.isPending ? : v.enabled ? "On" : "Off"} + +
+ } + > + {failure && ( + goAddCard(true)} pending={addCard.isPending}> + {pm ? "Update card" : "Add a card"} + + ) : undefined + } + /> + )} + {retryAt && ( + goAddCard(false)} pending={addCard.isPending}> + Update card + + } + /> + )} + {needsCard && !v.enabled && !failure && ( + goAddCard(true)} pending={addCard.isPending}> + Add a card + + } + /> + )} + + + edit({ threshold_usd })} + min={0.01} + max={maxThreshold} + step={1} + ariaLabel="Reload below" + className="w-[132px]" + /> + + + edit({ amount_usd })} + min={minAmount} + max={maxAmount} + step={5} + ariaLabel="Reload amount" + className="w-[132px]" + /> + + + edit({ monthly_limit_usd })} + min={minLimit} + max={LIMIT_MAX} + step={25} + ariaLabel="Monthly limit" + className="w-[132px]" + /> + + +
+ + + + {last + ? `Last reload ${fmtDay(last.at)}: ${fmtUsd(last.amount_usd)}` + : v.enabled + ? "No reloads yet" + : "While it's off, the billing team gets a notice when the balance runs low."} + + + {v.enabled && ( + + {fmtUsd(ar.reloaded_this_month_usd)} of {fmtUsdTrim(v.monthly_limit_usd)} this month + + )} +
+
+ + ); +} + +function toPatch(ar: AutoReload, p: Draft): AutoReloadPatch { + return { + enabled: ar.enabled, + threshold_usd: p.threshold_usd ?? ar.threshold_usd, + amount_usd: p.amount_usd ?? ar.amount_usd, + monthly_limit_usd: p.monthly_limit_usd ?? ar.monthly_limit_usd, + }; +} + +function Callout({ + tone, + title, + body, + action, +}: { + tone: "red" | "amber"; + title: string; + body: string; + action?: React.ReactNode; +}) { + return ( +
+ +
+
{title}
+
{body}
+
+ {action &&
{action}
} +
+ ); +} + +function CalloutButton({ + onClick, + pending, + primary, + children, +}: { + onClick: () => void; + pending: boolean; + primary?: boolean; + children: React.ReactNode; +}) { + return ( + + ); +} diff --git a/web/src/app/app/settings/billing/BalanceActivity.tsx b/web/src/app/app/settings/billing/BalanceActivity.tsx new file mode 100644 index 000000000..5d0c2db5a --- /dev/null +++ b/web/src/app/app/settings/billing/BalanceActivity.tsx @@ -0,0 +1,105 @@ +// What the balance was spent on and added from, newest first, paged. + +import { Loader2Icon } from "lucide-react"; +import useCreditTransactions from "@/lib/api/hooks/app/subscription/useCreditTransactions"; +import type { CreditTransaction } from "@/lib/api/models/app/subscription/Credits"; +import { fmtUsd, fmtUsdCost } from "@/lib/money"; +import { reasonLabel } from "@/components/app/billing/balanceModel"; +import { Section, TableSurface } from "../_components/SectionShell"; + +export default function BalanceActivity() { + const txns = useCreditTransactions(25); + const rows: CreditTransaction[] = txns.data?.pages.flatMap((p) => p.data) ?? []; + + return ( +
+ {txns.isPending ? ( +
+ ) : rows.length === 0 ? ( +

No activity yet.

+ ) : ( + <> + + + + + + + + + + + + {rows.map((t) => ( + + ))} + +
ActivityAmountBalanceWhen
+
+ {txns.hasNextPage && ( + + )} + + )} +
+ ); +} + +function ActivityRow({ row }: { row: CreditTransaction }) { + const positive = row.amount_usd > 0; + const tokens = (row.input_tokens ?? 0) + (row.output_tokens ?? 0); + const context = describeContext(row); + return ( + + + {reasonLabel(row.reason)} + {row.model_used && {row.model_used}} + {tokens > 0 && ( + + {tokens.toLocaleString()} tok + + )} + {row.quantity > 1 && ×{row.quantity}} + {context &&
{context}
} + + + {positive ? `+${fmtUsd(row.amount_usd)}` : `-${fmtUsdCost(Math.abs(row.amount_usd))}`} + + + {fmtUsd(row.balance_after_usd)} + + {formatWhen(row.created_at)} + + ); +} + +// What ran and who triggered it, from the context recorded with the charge. +function describeContext(row: CreditTransaction): string { + const c = row.context ?? {}; + const parts: string[] = []; + if (c.campaign_name || c.campaign_id) parts.push(`Campaign “${c.campaign_name || c.campaign_id}”`); + if (c.contact_email) parts.push(c.contact_email); + if (c.automation_name || c.automation_id) parts.push(`Automation “${c.automation_name || c.automation_id}”`); + if (c.thread_id) parts.push(`thread ${c.thread_id.slice(0, 8)}`); + if (c.session_id) parts.push("Remie session"); + if (c.detail) parts.push(c.detail); + if (row.actor_user_id) parts.push("by a teammate"); + return parts.join(" · "); +} + +function formatWhen(value: string | Date): string { + const d = new Date(value); + if (Number.isNaN(d.getTime())) return ""; + return d.toLocaleDateString("en-US", { month: "short", day: "numeric", hour: "numeric", minute: "2-digit" }); +} diff --git a/web/src/app/app/settings/billing/BalanceTab.tsx b/web/src/app/app/settings/billing/BalanceTab.tsx new file mode 100644 index 000000000..4801c794a --- /dev/null +++ b/web/src/app/app/settings/billing/BalanceTab.tsx @@ -0,0 +1,298 @@ +// Billing > Balance: what is left, adding money, automatic reload, the saved +// card, spend controls, activity and invoices. Returning from Stripe Checkout +// lands here (?top_up=, ?payment_method=) and is confirmed when the balance moves. + +import React from "react"; +import { useQueryClient, type QueryClient } from "@tanstack/react-query"; +import { AlertTriangleIcon, CreditCardIcon, Loader2Icon } from "lucide-react"; +import toast from "react-hot-toast/headless"; +import { useSearchParams } from "@/hooks/useSearchParams"; +import { DitherMeter } from "@/components/ui/dither"; +import AnimatedNumber from "@/components/ui/AnimatedNumber"; +import TopUpPanel from "@/components/app/billing/TopUpPanel"; +import { balanceAlert, expiresSoon, fmtDay, paymentMethodExpiry, paymentMethodLabel, reloadCovers } from "@/components/app/billing/balanceModel"; +import { updateAutoReload } from "@/lib/api/client/app/subscription/balance"; +import type { AppError } from "@/lib/api/client/normalizeError"; +import { + RESUME_AUTO_RELOAD_KEY, + balanceInvoicesQuery, + balanceQuery, + useAddPaymentMethod, + useBalance, +} from "@/lib/api/hooks/app/subscription/useBalance"; +import type { AutoReloadPatch, Balance } from "@/lib/api/models/app/subscription/Credits"; +import buildError from "@/lib/helper/buildError"; +import { fmtUsd } from "@/lib/money"; +import { cn } from "@/lib/utils"; +import { Row, Section } from "../_components/SectionShell"; +import AutoReloadSection from "./AutoReloadSection"; +import AIUsageCard from "./AIUsageCard"; +import BalanceActivity from "./BalanceActivity"; +import InvoicesSection from "./InvoicesSection"; + +export default function BalanceTab({ isPaid }: { isPaid: boolean }) { + const balance = useBalance(); + const confirming = useCheckoutReturn(balance.data); + const b = balance.data; + const ready = !!b && !b.unlimited; + + // The banner and header link to #auto-reload and #ai-spend; scroll once the sections exist. + React.useEffect(() => { + if (!ready) return; + const id = window.location.hash.slice(1); + if (!id) return; + const t = setTimeout(() => document.getElementById(id)?.scrollIntoView({ behavior: "smooth", block: "start" }), 200); + return () => clearTimeout(t); + }, [ready]); + + if (balance.isPending) { + return ( +
+
+
+ ); + } + if (!b) { + return ( +
+

The balance could not be loaded right now.

+
+ ); + } + if (b.unlimited) { + return ( +
+ +
+ ); + } + + return ( + <> +
+
+ {confirming && ( +
+ + Payment received. Adding it to the balance, this usually takes a few seconds. +
+ )} + + +
+
+ + +
+ +
+ + + + ); +} + +function BalanceSummary({ b }: { b: Balance }) { + const alert = balanceAlert(b); + const covered = reloadCovers(b); + const allowance = b.monthly_allowance_usd; + const frac = allowance > 0 ? Math.max(0, Math.min(1, b.monthly_usd / allowance)) : 0; + return ( +
+
+
+ Available + {alert && ( + + + {alert === "out" ? "Used up, AI is paused" : covered ? "Low, reloads automatically" : "Running low"} + + )} +
+ fmtUsd(n)} + className={cn( + "mt-1 block text-[28px] leading-none font-semibold tracking-tight tabular-nums", + alert === "out" ? "text-red-600" : "text-slate-900", + )} + /> +
+
+
+
+ Included this cycle + + {fmtUsd(b.monthly_usd)} + of {fmtUsd(allowance)} + +
+ +
+ {fmtUsd(b.monthly_used_usd)} used{b.next_reset_at ? `, resets ${fmtDay(b.next_reset_at)}` : ""} +
+
+
+
+ Added money + {fmtUsd(b.purchased_usd)} +
+
Never expires. Spent after the included usage.
+
+
+
+ ); +} + +function PaymentMethodSection({ b }: { b: Balance }) { + const addCard = useAddPaymentMethod(); + const pm = b.payment_method ?? null; + const exp = pm ? paymentMethodExpiry(pm) : null; + const soon = pm ? expiresSoon(pm) : false; + return ( +
+ + + {paymentMethodLabel(pm)} + + ) : ( + "No card saved" + ) + } + description={ + pm ? ( + soon ? ( + + + Expires {exp}. Replace it before a reload fails. + + ) : exp ? ( + `Expires ${exp}` + ) : undefined + ) : ( + "Add one to pay in one click and to turn on automatic reload." + ) + } + > + + +
+ ); +} + +/** Handles ?top_up= and ?payment_method=, then waits for the balance to rise. */ +function useCheckoutReturn(b: Balance | undefined): boolean { + const qc = useQueryClient(); + const [params, setParams] = useSearchParams(); + const topUp = params.get("top_up"); + const pmParam = params.get("payment_method"); + const [confirming, setConfirming] = React.useState(false); + const base = React.useRef(null); + const handled = React.useRef(false); + + React.useEffect(() => { + if (handled.current || (!topUp && !pmParam)) return; + handled.current = true; + if (topUp === "success") { + base.current = qc.getQueryData(balanceQuery.queryKey)?.purchased_usd ?? null; + setConfirming(true); + } else if (topUp === "canceled") { + toast("Checkout canceled. Nothing was charged."); + } + if (pmParam) resumeAutoReload(pmParam === "success", qc); + const next = new URLSearchParams(params); + next.delete("top_up"); + next.delete("payment_method"); + setParams(next, { replace: true }); + }, [topUp, pmParam, params, setParams, qc]); + + // The webhook may land after the person is back; realtime refreshes the balance when it does. + React.useEffect(() => { + if (!confirming || !b) return; + if (base.current === null) { + base.current = b.purchased_usd; + return; + } + if (b.purchased_usd > base.current) { + toast.success(`Added ${fmtUsd(b.purchased_usd - base.current)} to the balance`); + void qc.invalidateQueries({ queryKey: balanceInvoicesQuery.queryKey }); + base.current = null; + setConfirming(false); + } + }, [b, confirming, qc]); + + // A safety net for a missed realtime event, then give up quietly. + React.useEffect(() => { + if (!confirming) return; + const refetch = [4_000, 12_000].map((ms) => + setTimeout(() => void qc.invalidateQueries({ queryKey: balanceQuery.queryKey }), ms), + ); + const stop = setTimeout(() => setConfirming(false), 30_000); + return () => { + refetch.forEach(clearTimeout); + clearTimeout(stop); + }; + }, [confirming, qc]); + + return confirming; +} + +/** Back from saving a card: turn on automatic reload with the settings chosen before leaving. */ +function resumeAutoReload(saved: boolean, qc: QueryClient) { + let patch: AutoReloadPatch | null = null; + try { + patch = JSON.parse(sessionStorage.getItem(RESUME_AUTO_RELOAD_KEY) ?? "null") as AutoReloadPatch | null; + sessionStorage.removeItem(RESUME_AUTO_RELOAD_KEY); + } catch { + patch = null; + } + if (!saved) { + toast("No card was added."); + return; + } + void qc.invalidateQueries({ queryKey: balanceQuery.queryKey }); + if (!patch) { + toast.success("Card saved"); + return; + } + const body = { ...patch, enabled: true }; + // Stripe's webhook attaches the card; give it a moment when the first try beats it. + const attempt = (left: number) => + updateAutoReload(body) + .then((next) => { + qc.setQueryData(balanceQuery.queryKey, next); + toast.success("Automatic reload is on"); + }) + .catch((e: AppError) => { + if (e?.code === "payment_method_required" && left > 0) { + setTimeout(() => void attempt(left - 1), 2_500); + return; + } + toast.error(buildError(e)); + }); + void attempt(3); +} diff --git a/web/src/app/app/settings/billing/CreditsCard.tsx b/web/src/app/app/settings/billing/CreditsCard.tsx deleted file mode 100644 index 97c9271ef..000000000 --- a/web/src/app/app/settings/billing/CreditsCard.tsx +++ /dev/null @@ -1,306 +0,0 @@ -// AI credits card for the billing page: a balance ring (monthly pool vs plan -// allowance), the purchased top-up pool, next reset date, top-up pack buttons -// that redirect to Stripe Checkout, and the paged transaction log. -// -// Fulfillment of a purchase is webhook-only; on return from Stripe the balance -// refreshes via the realtime spine (credit_purchase / credit_grant). - -import React from "react"; -import toast from "react-hot-toast/headless"; -import { Loader2Icon, SparklesIcon, PlusIcon } from "lucide-react"; -import useCredits from "@/lib/api/hooks/app/subscription/useCredits"; -import useCreditTransactions from "@/lib/api/hooks/app/subscription/useCreditTransactions"; -import useCreateCreditCheckout from "@/lib/api/hooks/app/subscription/useCreateCreditCheckout"; -import type { AppError } from "@/lib/api/client/normalizeError"; -import type { CreditTransaction } from "@/lib/api/models/app/subscription/Credits"; -import buildError from "@/lib/helper/buildError"; -import { AnimatedNumber, DitherRing } from "@/components/ui/dither"; -import { Section, TableSurface } from "../_components/SectionShell"; - -export default function CreditsCard({ isPaid }: { isPaid: boolean }) { - const credits = useCredits(); - const checkout = useCreateCreditCheckout(); - const [buying, setBuying] = React.useState(null); - - async function buyPack(pack: string) { - setBuying(pack); - try { - const base = `${window.location.origin}/app/settings/billing/ai-credits`; - const { checkout_url } = await toast.promise( - checkout.mutateAsync({ - pack, - success_url: `${base}?topup=success`, - cancel_url: `${base}?topup=cancel`, - }), - { - loading: "Starting checkout…", - success: "Redirecting to checkout…", - error: (e: AppError) => buildError(e), - }, - ); - window.location.assign(checkout_url); - } catch { - /* surfaced via toast */ - } finally { - setBuying(null); - } - } - - const data = credits.data; - const allowance = data?.monthly_allowance ?? 0; - const monthly = data?.monthly_balance ?? 0; - const purchased = data?.purchased_balance ?? 0; - const total = data?.balance ?? 0; - const packs = data?.packs ?? []; - - return ( -
- {credits.isPending ? ( -
- ) : ( -
- -
-
- - credits available -
-
- - - - -
-
-
- )} - - {/* Top-up packs */} -
-
- Buy more credits -
- {!isPaid ? ( -

- Credit top-ups are available on paid plans. Upgrade above to buy packs. -

- ) : packs.length === 0 ? ( -

- Credit packs aren't configured for this workspace yet. -

- ) : ( -
- {packs.map((p) => ( - - ))} -
- )} -
- - {/* Transaction log */} - -
- ); -} - -function Stat({ label, value }: { label: string; value: string }) { - return ( -
- {label} - {value} -
- ); -} - -// BalanceRing draws a dithered donut of monthly-pool remaining vs the plan -// allowance, animating the sweep as the balance changes. -function BalanceRing({ monthly, allowance }: { monthly: number; allowance: number }) { - const pct = allowance > 0 ? Math.max(0, Math.min(1, monthly / allowance)) : 0; - const low = pct <= 0.15; - return ( - - - - ); -} - -function TransactionTable() { - const txns = useCreditTransactions(25); - const rows: CreditTransaction[] = txns.data?.pages.flatMap((p) => p.data) ?? []; - - return ( -
-
- Transactions -
- {txns.isPending ? ( -
- ) : rows.length === 0 ? ( -

- No credit activity yet. -

- ) : ( - <> - - - - - - - - - - - - {rows.map((t) => ( - - ))} - -
ActivityAmountBalanceWhen
-
- {txns.hasNextPage && ( - - )} - - )} -
- ); -} - -function TransactionRow({ row }: { row: CreditTransaction }) { - const positive = row.amount >= 0; - return ( - - - {describeReason(row.reason)} - {row.model_used && ( - - {row.model_used} - - )} - {row.tokens_used > 0 && ( - - {row.tokens_used.toLocaleString()} tok - - )} - {describeContext(row) && ( -
- {describeContext(row)} -
- )} - - - {positive ? "+" : ""} - {row.amount.toLocaleString()} - - - {(row.balance_after + row.purchased_balance_after).toLocaleString()} - - - {formatWhen(row.created_at)} - - - ); -} - -// describeContext renders the charge's attribution: exactly what ran and who -// triggered it, from the structured context recorded with the transaction. -function describeContext(row: CreditTransaction): string { - const c = row.context ?? {}; - const parts: string[] = []; - if (c.campaign_name || c.campaign_id) parts.push(`Campaign “${c.campaign_name || c.campaign_id}”`); - if (c.contact_email) parts.push(c.contact_email); - if (c.automation_name || c.automation_id) parts.push(`Automation “${c.automation_name || c.automation_id}”`); - if (c.thread_id) parts.push(`thread ${c.thread_id.slice(0, 8)}`); - if (c.session_id) parts.push("Remie session"); - if (c.detail) parts.push(c.detail); - if (row.actor_user_id) parts.push("triggered by a teammate"); - return parts.join(" · "); -} - -// describeReason maps a ledger reason code to a short human label. -function describeReason(reason: string): string { - const map: Record = { - writing_assistant: "Writing assistant", - writing_assistant_refund: "Writing assistant refund", - writing_edit: "Selection edit", - writing_edit_refund: "Selection edit refund", - agent_iteration: "Remie", - reply_draft: "Reply draft", - research_run: "Contact research", - automation_ai: "Automation AI step", - automation_ai_refund: "Automation AI refund", - campaign_ai: "Campaign switch", - campaign_ai_refund: "Campaign switch refund", - campaign_ai_search: "Campaign switch web search", - reply_draft_refund: "Reply draft refund", - agent_iteration_refund: "Remie refund", - inbox_agent_draft: "Inbox agent", - spam_analysis: "Spam analysis", - spam_analysis_refund: "Spam analysis refund", - placement_test: "Placement test", - placement_test_refund: "Placement test refund", - credit_topup: "Top-up purchase", - credit_auto_topup: "Auto top-up", - monthly_reset: "Monthly allowance", - trial_grant: "Trial credits", - }; - return map[reason] ?? reason.replace(/_/g, " "); -} - -function formatReset(value: string | Date | null | undefined): string { - if (!value) return "on renewal"; - const d = new Date(value); - if (Number.isNaN(d.getTime())) return "on renewal"; - return d.toLocaleDateString("en-US", { month: "short", day: "numeric" }); -} - -function formatWhen(value: string | Date): string { - const d = new Date(value); - if (Number.isNaN(d.getTime())) return "—"; - return d.toLocaleDateString("en-US", { - month: "short", - day: "numeric", - hour: "numeric", - minute: "2-digit", - }); -} diff --git a/web/src/app/app/settings/billing/InvoicesSection.tsx b/web/src/app/app/settings/billing/InvoicesSection.tsx new file mode 100644 index 000000000..6559ed7c8 --- /dev/null +++ b/web/src/app/app/settings/billing/InvoicesSection.tsx @@ -0,0 +1,111 @@ +// Stripe invoices for the workspace: the plan, money added, automatic reloads. + +import { ExternalLinkIcon, FileDownIcon } from "lucide-react"; +import { useBalanceInvoices } from "@/lib/api/hooks/app/subscription/useBalance"; +import type { BalanceInvoice } from "@/lib/api/models/app/subscription/Credits"; +import { Section, TableSurface } from "../_components/SectionShell"; + +const KIND: Record = { + subscription: "Plan", + top_up: "Money added", + auto_reload: "Automatic reload", +}; + +export default function InvoicesSection({ description }: { description?: string }) { + const invoices = useBalanceInvoices(); + const rows = invoices.data?.data ?? []; + return ( +
+ {invoices.isPending ? ( +
+ ) : invoices.isError ? ( +

Invoices could not be loaded right now.

+ ) : rows.length === 0 ? ( +

No invoices yet.

+ ) : ( + + + + + + + + + + + + + {rows.map((inv) => ( + + ))} + +
DateForAmountStatus + Links +
+
+ )} +
+ ); +} + +function InvoiceRow({ inv }: { inv: BalanceInvoice }) { + const amount = new Intl.NumberFormat("en-US", { style: "currency", currency: (inv.currency || "usd").toUpperCase() }).format( + inv.amount_cents / 100, + ); + return ( + + + {new Date(inv.created_at).toLocaleDateString("en-US", { month: "short", day: "numeric", year: "numeric" })} + + + {KIND[inv.kind] ?? "Invoice"} + {inv.number && {inv.number}} + + {amount} + + + + +
+ {inv.hosted_url && ( + + + + )} + {inv.pdf_url && ( + + + + )} +
+ + + ); +} + +function StatusPill({ status }: { status: string }) { + const s = (status ?? "").toLowerCase(); + const cls = + s === "paid" + ? "bg-emerald-50 text-emerald-700 border-emerald-100" + : s === "open" + ? "bg-amber-50 text-amber-700 border-amber-100" + : "bg-slate-100 text-slate-500 border-slate-200"; + return ( + + {status || "unknown"} + + ); +} diff --git a/web/src/app/app/settings/billing/OverviewTab.tsx b/web/src/app/app/settings/billing/OverviewTab.tsx index ecc7d5805..5ba717c6d 100644 --- a/web/src/app/app/settings/billing/OverviewTab.tsx +++ b/web/src/app/app/settings/billing/OverviewTab.tsx @@ -4,7 +4,7 @@ // Everything here reads real server state rather than the marketing catalog: // limits, counts, the mailbox allowance and storage come from // /organization/current/limits, capability flags from /subscription/features, -// the trial countdown from /subscription/trial. The catalog is only used for +// the trial countdown from the subscription's trial end. The catalog is only used for // labels and colours. import React from "react"; @@ -17,7 +17,6 @@ import { CheckIcon, CreditCardIcon, FileTextIcon, - FlameIcon, GiftIcon, InfoIcon, Loader2Icon, @@ -26,14 +25,13 @@ import { SparklesIcon, XIcon, } from "lucide-react"; -import useFeatureAccess from "@/hooks/useFeatureAccess"; +import useFeatureAccess, { useTrialDaysLeft } from "@/hooks/useFeatureAccess"; import useUpgradeFlow from "@/hooks/useUpgradeFlow"; import { useConfirm } from "@/hooks/context/confirm"; import useSubscription from "@/lib/api/hooks/app/subscription/useSubscription"; import usePlanOffers from "@/lib/api/hooks/app/subscription/usePlanOffers"; import type PlanOffer from "@/lib/api/models/app/subscription/PlanOffer"; import OfferedPlanDialog from "@/components/app/billing/OfferedPlanDialog"; -import useTrialStatus from "@/lib/api/hooks/app/subscription/useTrialStatus"; import useCancelSubscription from "@/lib/api/hooks/app/subscription/useCancelSubscription"; import useOrganizationLimits from "@/lib/api/hooks/app/organizations/useOrganizationLimits"; import useUsageOverview from "@/lib/api/hooks/app/analytics/useUsageOverview"; @@ -47,10 +45,10 @@ import { PLAN_ACCENT_CLASSES, getPlan } from "@/lib/plans"; import type OrganizationLimits from "@/lib/api/models/app/organizations/OrganizationLimits"; import { Section } from "../_components/SectionShell"; -export default function OverviewTab({ onChangePlan, onWarmupPlan }: { onChangePlan: () => void; onWarmupPlan: () => void }) { +export default function OverviewTab({ onChangePlan }: { onChangePlan: () => void }) { const access = useFeatureAccess(); + const trialDays = useTrialDaysLeft(access.trial ? access.trialEndsAt : null); const sub = useSubscription(); - const trial = useTrialStatus(); const orgLimits = useOrganizationLimits(); const limits = orgLimits.data?.limits; const counts = orgLimits.data?.counts; @@ -78,7 +76,6 @@ export default function OverviewTab({ onChangePlan, onWarmupPlan }: { onChangePl // Free and the Warmup plan both warm without sending, so neither has // send, contact, campaign or seat limits worth metering. const sends = !access.locked; - const warmupPlan = getPlan("warmup"); const yearly = isYearly(sub.data, periodEnd); const serverPlan = sub.data?.plan; const yearlyPrice = @@ -133,13 +130,13 @@ export default function OverviewTab({ onChangePlan, onWarmupPlan }: { onChangePl action={{ label: cancel.isPending ? "Resuming…" : "Resume subscription", onClick: resume }} /> )} - {trial.data?.is_trial && (trial.data.days_remaining ?? 0) >= 0 && ( + {access.trial && access.trialEndsAt && ( )} @@ -161,12 +158,16 @@ export default function OverviewTab({ onChangePlan, onWarmupPlan }: { onChangePl
- {plan.label} + {access.trial ? "Free trial" : plan.label}

- {plan.description} + {access.trial + ? "Two mailboxes warming in the free pool, 20 sends a day, the unified inbox, contacts and campaigns." + : access.trialEnded + ? "Your trial has ended. Sending and warmup are paused until you choose a plan; your mailboxes and campaigns are kept." + : plan.description}

@@ -187,11 +188,15 @@ export default function OverviewTab({ onChangePlan, onWarmupPlan }: { onChangePl : "per month" } /> - + {access.trial && !periodEnd ? ( + + ) : ( + + )} {access.warmupOnly ? ( )} - {/* Only warming, no sending: the one plan that is not in the - grid. Free workspaces only; anything paid already has it. */} - {!sub.isPending && onFreeTier && ( - - )} - {/* Private plans Warmbly offered this workspace; not in the grid. */} {!sub.isPending && visibleOffers.map((o) => ( @@ -363,7 +345,7 @@ export default function OverviewTab({ onChangePlan, onWarmupPlan }: { onChangePl
- {access.warmupOnly ? `The ${plan.label} plan` : "A free workspace"} warms mailboxes and does not send. + {access.warmupOnly + ? `The ${plan.label} plan warms mailboxes and does not send.` + : access.keptFreeWarmup + ? "Your free plan warms mailboxes and does not send." + : "Without a plan, this workspace connects no mailboxes and does not send."} Campaigns, contacts, the unified inbox and the team come with a{" "} - + )}
setSalesOpen(false)} /> - setPoolOpen(false)} /> ); } diff --git a/web/src/app/app/settings/layout.tsx b/web/src/app/app/settings/layout.tsx index 91ae89e43..c726a32ca 100644 --- a/web/src/app/app/settings/layout.tsx +++ b/web/src/app/app/settings/layout.tsx @@ -20,7 +20,6 @@ import { CloudIcon, DatabaseIcon, GaugeIcon, - GiftIcon, Loader2Icon, PlugIcon, ShieldCheckIcon, @@ -38,6 +37,7 @@ import { useAccessRestricted, usePermission, type PermissionKey } from "@/hooks/ import { Page, PageTopbar } from "@/components/layout/Page"; import useFeatureAccess from "@/hooks/useFeatureAccess"; import useAuthConfig from "@/lib/api/hooks/auth/useAuthConfig"; +import { useCloudLinkStatus, usePoolLinkInstances } from "@/lib/api/hooks/app/cloudlink/useCloudLink"; interface SectionDef { path: string; @@ -80,8 +80,7 @@ const GROUPS: SectionGroup[] = [ { path: "tracking", label: "Website tracking", icon: GlobeIcon, description: "Page views on your site, in the contact timeline.", permission: "MANAGE_SETTINGS" }, { path: "inbox-tagging", label: "Inbox tagging", icon: TagsIcon, description: "Label and score inbound mail automatically.", permission: "VIEW_ANALYTICS" }, { path: "ai-skills", label: "AI skills", icon: SparklesIcon, description: "Playbooks your AI features follow.", permission: "MANAGE_SETTINGS" }, - { path: "billing", label: "Billing", icon: CreditCardIcon, description: "Plan, payment, invoices.", ownerOnly: true, billingOnly: true }, - { path: "referral", label: "Refer & earn", icon: GiftIcon, description: "Invite teams and earn account credit.", ownerOnly: true, billingOnly: true }, + { path: "billing", label: "Billing", icon: CreditCardIcon, description: "Plan, balance, invoices.", permission: "MANAGE_BILLING", billingOnly: true }, { path: "limits", label: "Limits", icon: GaugeIcon, description: "Ask for a higher cap on mailboxes, contacts, seats or sends.", ownerOnly: true }, ], }, @@ -114,10 +113,18 @@ export default function SettingsLayout() { function SettingsLayoutInner() { const pathname = useLocation({ select: (l) => l.pathname }); const access = useFeatureAccess(); - const hosted = useAuthConfig().data?.self_hosted === false; + const selfHosted = useAuthConfig().data?.self_hosted; + const hosted = selfHosted === false; const canManageApiKeys = usePermission("MANAGE_API_KEYS"); const canManageSettings = usePermission("MANAGE_SETTINGS"); + // Warmbly Cloud only shows where a link exists: an instance linked to it, or a hosted workspace with linked instances. + const cloudStatus = useCloudLinkStatus(selfHosted === true && canManageSettings); + const linkedInstances = usePoolLinkInstances(hosted && canManageSettings); + const hasCloudLink = hosted + ? (linkedInstances.data?.data ?? []).some((i) => !i.revoked_at) + : !!(cloudStatus.data?.connected || cloudStatus.data?.legacy_connected); const canViewAnalytics = usePermission("VIEW_ANALYTICS"); + const canManageBilling = usePermission("MANAGE_BILLING"); const restricted = useAccessRestricted(); const navRef = React.useRef(null); const unsaved = useUnsavedRegistry(); @@ -181,9 +188,11 @@ function SettingsLayoutInner() { (!restricted || s.scoped) && (!s.ownerOnly || access.isOwner) && (!s.billingOnly || access.billing) && + (s.path !== "warmbly-cloud" || hasCloudLink) && (s.permission !== "MANAGE_API_KEYS" || canManageApiKeys) && (s.permission !== "MANAGE_SETTINGS" || canManageSettings) && - (s.permission !== "VIEW_ANALYTICS" || canViewAnalytics), + (s.permission !== "VIEW_ANALYTICS" || canViewAnalytics) && + (s.permission !== "MANAGE_BILLING" || canManageBilling || access.isOwner), ) .map((s) => hosted && s.hostedLabel diff --git a/web/src/app/app/settings/members/MemberAccessDialog.tsx b/web/src/app/app/settings/members/MemberAccessDialog.tsx index bc67ff5b0..41edf6b4a 100644 --- a/web/src/app/app/settings/members/MemberAccessDialog.tsx +++ b/web/src/app/app/settings/members/MemberAccessDialog.tsx @@ -1,5 +1,5 @@ // Which resources a member's roles apply to: the entire workspace, or only -// the campaign folders, campaigns and mailboxes chosen here, read-only. +// the campaign folders, campaigns and mailboxes chosen here, for a client. import React from "react"; import { createPortal } from "react-dom"; @@ -18,6 +18,9 @@ import { useSuggestedSenders } from "@/lib/api/hooks/app/organizations/useMember import type MemberAccess from "@/lib/api/models/app/organizations/MemberAccess"; import { WORKSPACE_ACCESS } from "@/lib/api/models/app/organizations/MemberAccess"; import { cn } from "@/lib/utils"; +import { CLIENT_ROLE_PRESETS, presetForRole, type ClientRolePreset } from "@/lib/accessScope"; + +type PresetKey = ClientRolePreset["key"]; /** One-line summary of a scope, for the roster and the invite form. */ function accessSummary(access?: MemberAccess | null): string { @@ -84,6 +87,7 @@ export default function MemberAccessDialog({ subject, initial, saveLabel = "Save access", + currentRoles, onSave, onClose, }: { @@ -92,14 +96,23 @@ export default function MemberAccessDialog({ subject: string; initial?: MemberAccess | null; saveLabel?: string; - onSave: (access: MemberAccess) => Promise; + /** The roles held now; a client preset among them starts selected. */ + currentRoles?: { name: string }[]; + /** preset is the client role to give them, or null to keep their roles. */ + onSave: (access: MemberAccess, preset: ClientRolePreset | null) => Promise; onClose: () => void; }) { const confirm = useConfirm(); const start = React.useMemo(() => normalize(initial), [initial]); + const startPreset = React.useMemo(() => { + if (start.scope !== "restricted" || currentRoles?.length !== 1) return null; + return presetForRole(currentRoles[0])?.key ?? null; + }, [start.scope, currentRoles]); const [access, setAccess] = React.useState(start); + const [preset, setPreset] = React.useState(startPreset); const [saving, setSaving] = React.useState(false); - const dirty = !sameAccess(access, start); + const restricted = access.scope === "restricted"; + const dirty = !sameAccess(access, start) || (restricted && preset !== startPreset); const requestClose = React.useCallback(() => { if (dirty && !saving) { @@ -122,7 +135,8 @@ export default function MemberAccessDialog({ async function save() { setSaving(true); try { - await onSave(access.scope === "restricted" ? access : WORKSPACE_ACCESS); + const chosen = restricted ? (CLIENT_ROLE_PRESETS.find((p) => p.key === preset) ?? null) : null; + await onSave(restricted ? access : WORKSPACE_ACCESS, chosen); onClose(); } catch { // The caller surfaced it; the dialog stays open with the draft. @@ -168,7 +182,13 @@ export default function MemberAccessDialog({
- + 0} + />
@@ -208,8 +228,20 @@ function normalize(a?: MemberAccess | null): MemberAccess { }; } -/** The scope choice and, for a restricted scope, the three resource pickers. */ -export function AccessEditor({ value, onChange }: { value: MemberAccess; onChange: (next: MemberAccess) => void }) { +/** The scope choice and, for a client, their role and the three resource pickers. */ +export function AccessEditor({ + value, + onChange, + preset, + onPreset, + canKeepRoles, +}: { + value: MemberAccess; + onChange: (next: MemberAccess) => void; + preset: PresetKey | null; + onPreset: (next: PresetKey | null) => void; + canKeepRoles: boolean; +}) { const restricted = value.scope === "restricted"; const { user } = useUserProfile(); const campaigns = useCampaigns({ query: "", folder: "", enabled: restricted }); @@ -240,8 +272,8 @@ export function AccessEditor({ value, onChange }: { value: MemberAccess; onChang
{( [ - ["workspace", "Entire workspace", "Everything the roles allow", GlobeIcon], - ["restricted", "Selected resources", "Only what you choose, read-only", LockIcon], + ["workspace", "Full workspace", "Everything the roles allow", GlobeIcon], + ["restricted", "Client", "Only the campaigns and mailboxes you share", LockIcon], ] as const ).map(([scope, label, sub, Icon]) => ( + ); + })} +
+

+ A preset is added to Roles the first time you use it, so you can rename or adjust it there. +

+
+ ); +} + /** Mailboxes the chosen campaigns send from, offered for review, never granted on their own. */ function SuggestedSenders({ campaignIds, diff --git a/web/src/app/app/settings/members/page.tsx b/web/src/app/app/settings/members/page.tsx index e8f20d9d2..640a713d9 100644 --- a/web/src/app/app/settings/members/page.tsx +++ b/web/src/app/app/settings/members/page.tsx @@ -37,6 +37,7 @@ import type { AppError } from "@/lib/api/client/normalizeError"; import buildError from "@/lib/helper/buildError"; import getInvitationLink from "@/lib/api/client/app/organizations/getInvitationLink"; import { useSetMemberAccess } from "@/lib/api/hooks/app/organizations/useMemberAccess"; +import useEnsureClientRole from "@/lib/api/hooks/app/organizations/useEnsureClientRole"; import type MemberAccess from "@/lib/api/models/app/organizations/MemberAccess"; import { WORKSPACE_ACCESS } from "@/lib/api/models/app/organizations/MemberAccess"; import type OrganizationMember from "@/lib/api/models/app/organizations/OrganizationMember"; @@ -67,6 +68,7 @@ export default function MembersSettingsPage() { const setAccess = useSetMemberAccess(); const [editingAccess, setEditingAccess] = React.useState(null); const customRoles = useRoles(); + const clientRoles = useEnsureClientRole(); const { config: authConfig, ready: authConfigReady } = useAuthConfig(); const currentUserId = useAppStore((s) => s.user?.id); const currentOrg = useAppStore((s) => s.currentOrganization); @@ -171,7 +173,7 @@ export default function MembersSettingsPage() { {access.canManage && (
setEditingAccess(null)} - onSave={async (next) => { - await toast.promise(setAccess.mutateAsync({ userId: editingAccess.user_id, access: next }), { + onSave={async (next, preset) => { + // Scope first, then the client role, so the member never holds more than either allows. + const save = async () => { + await setAccess.mutateAsync({ userId: editingAccess.user_id, access: next }); + if (preset) { + const roleId = await clientRoles.ensure(preset); + await updateRole.mutateAsync({ id: editingAccess.user_id, data: { role_ids: [roleId] } }); + } + }; + await toast.promise(save(), { loading: "Saving…", success: "Access updated", error: (e: AppError) => buildError(e), @@ -468,6 +479,7 @@ function InviteFlow({ const [roleIds, setRoleIds] = React.useState([]); const [inviteAccess, setInviteAccess] = React.useState(WORKSPACE_ACCESS); const [editingAccess, setEditingAccess] = React.useState(false); + const clientRoles = useEnsureClientRole(); // Default to the seeded Viewer (least privilege), else the first role. const defaultRole = customRoles.find((r) => r.name === "Viewer") ?? customRoles[0]; const effectiveRoleIds = roleIds.length > 0 ? roleIds : defaultRole ? [defaultRole.id] : []; @@ -644,7 +656,17 @@ function InviteFlow({ initial={inviteAccess} saveLabel="Use this access" onClose={() => setEditingAccess(false)} - onSave={async (next) => setInviteAccess(next)} + onSave={async (next, preset) => { + if (preset) { + try { + setRoleIds([await clientRoles.ensure(preset)]); + } catch (e) { + toast.error(buildError(e as AppError)); + throw e; + } + } + setInviteAccess(next); + }} /> )} diff --git a/web/src/app/app/settings/oauth-apps/parts.tsx b/web/src/app/app/settings/oauth-apps/parts.tsx index 1c657e112..6eab020b1 100644 --- a/web/src/app/app/settings/oauth-apps/parts.tsx +++ b/web/src/app/app/settings/oauth-apps/parts.tsx @@ -49,14 +49,16 @@ export function EventPicker({ const filtered = React.useMemo(() => { const needle = q.trim().toLowerCase(); - if (!needle) return catalog; - return catalog.filter( + // A deprecated event is never delivered, so it is offered only to untick. + const offered = catalog.filter((d) => !d.deprecated || value.includes(d.type)); + if (!needle) return offered; + return offered.filter( (d) => d.type.toLowerCase().includes(needle) || d.category.toLowerCase().includes(needle) || d.description.toLowerCase().includes(needle), ); - }, [catalog, q]); + }, [catalog, q, value]); const grouped = React.useMemo(() => { const g: Record = {}; diff --git a/web/src/app/app/settings/referral/page.tsx b/web/src/app/app/settings/referral/page.tsx deleted file mode 100644 index 9d1537bd6..000000000 --- a/web/src/app/app/settings/referral/page.tsx +++ /dev/null @@ -1,500 +0,0 @@ -// Referral program — owner-only, organization-scoped. -// -// Invitees get a discount for a few months; the referrer earns account credit -// equal to one month of the invitee's plan, applied to their invoices. This -// page surfaces the share link + code, the running balance, and the two -// ledgers (referrals + earnings history). - -import React from "react"; -import { - CheckIcon, - CopyIcon, - GiftIcon, - Loader2Icon, - LockIcon, -} from "lucide-react"; -import toast from "react-hot-toast/headless"; -import { Navigate } from "@tanstack/react-router"; -import useFeatureAccess from "@/hooks/useFeatureAccess"; -import useReferral from "@/lib/api/hooks/app/subscription/useReferral"; -import useReferralAttributions from "@/lib/api/hooks/app/subscription/useReferralAttributions"; -import useReferralEarnings from "@/lib/api/hooks/app/subscription/useReferralEarnings"; -import type { - ReferralAttribution, - ReferralAttributionStatus, - ReferralEarningsTransaction, -} from "@/lib/api/models/app/subscription/Referral"; -import { Row, Section, SectionShell, TableSurface } from "../_components/SectionShell"; - -export default function ReferralSettingsPage() { - const access = useFeatureAccess(); - const referral = useReferral(); - const summary = referral.data; - const currency = summary?.currency ?? "usd"; - - // Referral credit is billing credit; without a billing provider it has no meaning. - if (!access.billing) { - return ; - } - - if (!access.loading && !access.isOwner) { - return ( - -
-
-
- -
-
-
- Only the workspace owner can manage referrals -
-

- Referral credit is applied to this workspace's invoices, so the - program is scoped to the owner role. Ask your owner to share the - link if you'd like to refer someone. -

-
-
-
-
- ); - } - - return ( - -
-
-
-
- -
-
-
- Give {summary?.invitee_percent_off ?? 0}%, get a month of credit -
-

- Anyone who signs up with your link gets{" "} - - {summary?.invitee_percent_off ?? 0}% off - {" "} - for their first{" "} - - {summary?.invitee_months ?? 0}{" "} - {(summary?.invitee_months ?? 0) === 1 ? "month" : "months"} - - . Once they're a paying customer you earn account credit equal to - one month of their plan, applied automatically to your invoices. -

-
-
-
-
- -
- {referral.isPending ? ( -
- ) : referral.isError || !summary ? ( -

- Couldn't load your referral link. Reload the page to try again. -

- ) : ( - <> - - - - - - - - )} -
- -
-
- - - - -
-
- - - -
-
- -
- -
- -
- -
-
- ); -} - -// CopyChip renders a value in a bordered chip with a copy-to-clipboard button. -function CopyChip({ - value, - label, - mono, - uppercase, -}: { - value: string; - label: string; - mono?: boolean; - uppercase?: boolean; -}) { - const [copied, setCopied] = React.useState(false); - function copy() { - navigator.clipboard.writeText(value).then( - () => { - setCopied(true); - toast.success("Copied to clipboard"); - setTimeout(() => setCopied(false), 2000); - }, - () => toast.error("Couldn't copy to clipboard"), - ); - } - return ( -
-
- {value} -
- -
- ); -} - -function StatCard({ - label, - value, - loading, - accent, -}: { - label: string; - value: string; - loading?: boolean; - accent?: boolean; -}) { - return ( -
-
- {label} -
- {loading ? ( -
- ) : ( -
- {value} -
- )} -
- ); -} - -function CountPill({ - label, - value, - tone, -}: { - label: string; - value: number; - tone: "muted" | "sky" | "emerald"; -}) { - const dot = - tone === "emerald" - ? "bg-emerald-500" - : tone === "sky" - ? "bg-sky-500" - : "bg-slate-300"; - return ( - - - {label} - {value} - - ); -} - -function AttributionsTable({ currency }: { currency: string }) { - const query = useReferralAttributions(); - const rows = query.attributions; - - if (query.isPending) { - return
; - } - if (rows.length === 0) { - return ( -

- No referrals yet. Share your link to get started. -

- ); - } - - return ( - <> - - - - - - - - - - - - {rows.map((r) => ( - - ))} - -
Referred orgStatusRewardDate
-
- - - ); -} - -function AttributionRow({ - row, - fallbackCurrency, -}: { - row: ReferralAttribution; - fallbackCurrency: string; -}) { - return ( - - - - Referred org - - {shortId(row.invitee_org_id)} - - - - - - - - {row.reward_cents > 0 - ? formatMoney(row.reward_cents, row.reward_currency || fallbackCurrency) - : "—"} - - - {formatDate(row.rewarded_at ?? row.qualified_at ?? row.created_at)} - - - ); -} - -function AttributionStatusBadge({ status }: { status: ReferralAttributionStatus }) { - const map: Record = { - pending: { label: "Pending", cls: "bg-slate-100 text-slate-500 border-slate-200" }, - qualified: { label: "Qualified", cls: "bg-sky-50 text-sky-700 border-sky-100" }, - rewarded: { label: "Rewarded", cls: "bg-emerald-50 text-emerald-700 border-emerald-100" }, - void: { label: "Void", cls: "bg-slate-100 text-slate-400 border-slate-200" }, - }; - const { label, cls } = map[status]; - return ( - - {label} - - ); -} - -function EarningsTable({ currency }: { currency: string }) { - const query = useReferralEarnings(); - const rows = query.earnings; - - if (query.isPending) { - return
; - } - if (rows.length === 0) { - return ( -

- No earnings yet. Credit shows up here once a referral is rewarded. -

- ); - } - - return ( - <> - - - - - - - - - - - - {rows.map((t) => ( - - ))} - -
ReasonAmountBalanceDate
-
- - - ); -} - -function EarningsRow({ - row, - fallbackCurrency, -}: { - row: ReferralEarningsTransaction; - fallbackCurrency: string; -}) { - const positive = row.amount_cents >= 0; - const cur = row.currency || fallbackCurrency; - return ( - - {humanizeReason(row.reason)} - - {positive ? "+" : "−"} - {formatMoney(Math.abs(row.amount_cents), cur)} - - - {formatMoney(row.balance_after_cents, cur)} - - - {formatDate(row.created_at)} - - - ); -} - -function LoadMore({ - query, -}: { - query: { - hasNextPage: boolean; - isFetchingNextPage: boolean; - fetchNextPage: () => void; - }; -}) { - if (!query.hasNextPage) return null; - return ( - - ); -} - -// shortId masks an org id to a short, non-PII reference. -function shortId(id: string): string { - if (!id) return "—"; - const trimmed = id.replace(/-/g, ""); - return `#${trimmed.slice(0, 6)}`; -} - -function humanizeReason(reason: string): string { - if (!reason) return "Adjustment"; - return reason - .replace(/[_-]+/g, " ") - .replace(/\b\w/g, (c) => c.toUpperCase()); -} - -// formatMoney renders minor units (cents) as a localized currency string. -function formatMoney(cents: number, currency: string): string { - try { - return new Intl.NumberFormat("en-US", { - style: "currency", - currency: (currency || "usd").toUpperCase(), - }).format(cents / 100); - } catch { - return `${(cents / 100).toFixed(2)} ${(currency || "usd").toUpperCase()}`; - } -} - -function formatDate(value?: string | Date): string { - if (!value) return "—"; - const d = new Date(value); - if (Number.isNaN(d.getTime())) return "—"; - return d.toLocaleDateString("en-US", { - month: "short", - day: "numeric", - year: "numeric", - }); -} diff --git a/web/src/app/app/settings/roles/RolesSection.tsx b/web/src/app/app/settings/roles/RolesSection.tsx index 0127633d4..9d20b6557 100644 --- a/web/src/app/app/settings/roles/RolesSection.tsx +++ b/web/src/app/app/settings/roles/RolesSection.tsx @@ -20,6 +20,9 @@ import { ROLE_TEMPLATES, } from "@/lib/permissions"; import { roleColor } from "../_components/RoleSelect"; +import { Toggle } from "@/components/app/campaigns/preferences/components/CampaignPreferenceBoolBox"; +import { CLIENT_ROLE_PRESETS, roleScopeSafe, SCOPE_ACTION_PERMISSIONS, SCOPE_READ_PERMISSIONS } from "@/lib/accessScope"; +import useEnsureClientRole from "@/lib/api/hooks/app/organizations/useEnsureClientRole"; // Ownership transfer can never live in a role (the API rejects it). const EDITABLE_PERMISSIONS = PERMISSION_CATALOG.filter( @@ -67,6 +70,7 @@ export default function RolesSection({ canManage }: { canManage: boolean }) { style={{ backgroundColor: roleColor(role) }} /> {role.name} +

{role.description || `${countBits(role.permissions)} permissions`} @@ -99,6 +103,8 @@ export default function RolesSection({ canManage }: { canManage: boolean }) { ))}

+ {canManage && } + {canManage && ( +
+

+ For clients restricted to selected campaigns and mailboxes. They work only inside what you share with them. +

+
    + {missing.map((p) => ( +
  • + + + {p.name} + . {p.summary} + +
  • + ))} +
+
+ ); +} + function countBits(mask: number) { let n = 0; for (let b = mask; b; b >>= 1) n += b & 1; @@ -137,7 +209,9 @@ function RoleEditor({ role, onClose }: { role: OrganizationRole | null; onClose: const [permissions, setPermissions] = React.useState( role?.permissions ?? PRESETS.find((p) => p.id === "viewer")?.permissions ?? 0, ); + const [actsInScope, setActsInScope] = React.useState(!!role?.acts_in_scope); const pending = create.isPending || update.isPending; + const clientReach = permissions & (actsInScope ? SCOPE_ACTION_PERMISSIONS : SCOPE_READ_PERMISSIONS); const toggle = (bit: number) => setPermissions((p) => p ^ bit); @@ -149,8 +223,8 @@ function RoleEditor({ role, onClose }: { role: OrganizationRole | null; onClose: try { await toast.promise( role - ? update.mutateAsync({ id: role.id, data: { name: name.trim(), description, color, permissions } }) - : create.mutateAsync({ name: name.trim(), description, color, permissions }), + ? update.mutateAsync({ id: role.id, data: { name: name.trim(), description, color, permissions, acts_in_scope: actsInScope } }) + : create.mutateAsync({ name: name.trim(), description, color, permissions, acts_in_scope: actsInScope }), { loading: "Saving…", success: role ? "Role updated" : "Role created", @@ -262,6 +336,25 @@ function RoleEditor({ role, onClose }: { role: OrganizationRole | null; onClose: +
+
+ Clients can act inside what is shared with them + + + +
+

+ For a member restricted to selected campaigns and mailboxes. Off, the role only lets them read. + On, they can also use this role's inbox, campaign editing and start or pause permissions on + what is shared with them. Team, billing, settings, contacts and mailbox settings never apply to them. +

+

+ {clientReach === 0 + ? "A client with this role sees nothing." + : `A client with this role: ${EDITABLE_PERMISSIONS.filter((p) => (clientReach & p.bit) === p.bit).map((p) => p.label.toLowerCase()).join(", ")}.`} +

+
+ {CATEGORIES.map((cat) => { const perms = EDITABLE_PERMISSIONS.filter((p) => p.category === cat); if (perms.length === 0) return null; 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/app/settings/sending/page.tsx b/web/src/app/app/settings/sending/page.tsx index 7c4c1097c..b60ca6c56 100644 --- a/web/src/app/app/settings/sending/page.tsx +++ b/web/src/app/app/settings/sending/page.tsx @@ -127,6 +127,20 @@ function SendingSettings() { [], ); + const patchABTesting = React.useCallback( + (next: Partial) => { + setDraft((prev) => (prev ? { ...prev, ab_testing: { ...prev.ab_testing, ...next } } : prev)); + }, + [], + ); + + const patchBouncePipeline = React.useCallback( + (next: Partial) => { + setDraft((prev) => (prev ? { ...prev, bounce_pipeline: { ...prev.bounce_pipeline, ...next } } : prev)); + }, + [], + ); + const patch = React.useCallback( (next: Partial>) => { setDraft((prev) => @@ -259,6 +273,45 @@ function SendingSettings() { )} +
+ {isLoading || !draft ? ( +
+ ) : ( + + patchABTesting({ auto_promote_winner: on })} + /> + + )} +
+ +
+ {isLoading || !draft ? ( +
+ ) : ( + + patchBouncePipeline({ auto_suppress_on_bounce: on })} + label="Suppress addresses that bounce as invalid" + /> + + )} +
+
+
+ {isLoading || !draft ? ( +
+ ) : ( + + patchReplyIntent({ stop_all_campaigns_on_reply: on })} + label="Hold the contact in every other campaign" + /> + + )} +
+
({ x: dir * 28, opacity: 0 }), - center: { x: 0, opacity: 1 }, - exit: (dir: 1 | -1) => ({ x: dir * -28, opacity: 0 }), -}; - -export default function ConnectFlow({ - status, - onFinished, -}: { - status: CloudLinkStatus; - onFinished: () => void; -}) { - const [step, setStep] = React.useState(status.connected ? 1 : 0); - const [direction, setDirection] = React.useState<1 | -1>(1); - const [nudged, setNudged] = React.useState(false); - const [linked, setLinked] = React.useState(status.connected); - const [enrolledCount, setEnrolledCount] = React.useState(0); - // The status prop was read before the handshake, so the workspace name has - // to come from the poll that completed it. - const [orgName, setOrgName] = React.useState(status.link?.organization_name ?? ""); - - const sourceBusy = useMailboxSourceBusy(); - const issue = sourceBusy ? "Wait for the current mailbox connections to finish" : step === 0 && !linked ? "Approve the code on Warmbly Cloud first" : null; - React.useEffect(() => { - if (!issue) setNudged(false); - }, [issue]); - - const canReach = React.useCallback((target: Step) => (target === 0 ? true : linked), [linked]); - const goTo = React.useCallback( - (target: Step) => { - if (sourceBusy) { setNudged(true); return; } - if (target === step) return; - if (target > step && !canReach(target)) { - setNudged(true); - return; - } - setDirection(target > step ? 1 : -1); - setNudged(false); - setStep(target); - }, - [step, canReach, sourceBusy], - ); - - return ( -
-
- -
- - - {step === 0 && ( - { - setOrgName(name); - setLinked(true); - setTimeout(() => goTo(1), 650); - }} - /> - )} - {step === 1 && } - {step === 2 && } - - -
-
goTo((step - 1) as Step)} - onNext={() => { - if (issue) { - setNudged(true); - return; - } - if (step < 2) goTo((step + 1) as Step); - else onFinished(); - }} - /> -
-
- ); -} - -function Stepper({ step, canReach, goTo }: { step: Step; canReach: (s: Step) => boolean; goTo: (s: Step) => void }) { - return ( -
- {STEPS.map((s, idx) => { - const i = idx as Step; - const done = i < step; - const active = i === step; - const reachable = i <= step || canReach(i); - return ( - - - {idx < STEPS.length - 1 && ( - - - - )} - - ); - })} -
- ); -} - -function Footer({ step, issue, nudged, onBack, onNext }: { step: Step; issue: string | null; nudged: boolean; onBack: () => void; onNext: () => void }) { - return ( -
-
- - {nudged && issue && ( - - {issue} - - )} - -
- {step > 0 && ( - - )} - -
- ); -} - -// Step 1: the shared link card. -function LinkStep({ status, linked, orgName, onLinked }: { status: CloudLinkStatus; linked: boolean; orgName: string; onLinked: (orgName: string) => void }) { - return ; -} - -// Step 2: pick mailboxes. -function MailboxesStep({ onCountChange }: { onCountChange: (n: number) => void }) { - const rows = useCloudLinkMailboxes(); - const enroll = useEnrollCloudLinkMailbox(); - const unenroll = useUnenrollCloudLinkMailbox(); - const [busy, setBusy] = React.useState(null); - - React.useEffect(() => { - onCountChange((rows.data ?? []).filter((r) => r.enrolled).length); - }, [rows.data, onCountChange]); - - const flip = async (row: CloudLinkMailboxRow) => { - setBusy(row.id); - try { - if (row.enrolled) { - await unenroll.mutateAsync(row.id); - toast.success(`${row.email} removed from the pool`); - } else { - await enroll.mutateAsync(row.id); - toast.success(`${row.email} is now warming in the pool`); - } - } catch (e) { - if (!cloudMailboxPickerOpened(e)) toast.error(buildError(e as AppError)); - } finally { - setBusy(null); - } - }; - - return ( -
-
-

Choose the mailboxes to warm

-

- Each enrolled mailbox is warmed by Warmbly Cloud from now on. Its local warmup stops; campaigns keep sending from here as usual. -

-
- - {rows.isLoading ? ( -
- -
- ) : (rows.data ?? []).length === 0 ? ( -

No active mailboxes yet. Connect one under Mailboxes, then come back here.

- ) : ( -
    - {(rows.data ?? []).map((row, i) => { - const supported = providerSupported(row.provider); - return ( - -
    -

    {row.email}

    -

    - {providerLabel(row.provider)} - {!supported && " · connect with SMTP/IMAP to enroll"} -

    -
    - {busy === row.id ? ( - - ) : ( - void flip(row)} /> - )} -
    - ); - })} -
- )} -

- Enrolling sends the mailbox's SMTP/IMAP credential to Warmbly Cloud, sealed in transit and at rest, and used only to send and read warmup mail. - Nothing else in the mailbox is stored. -

-
- ); -} - -function DoneStep({ orgName, enrolledCount }: { orgName: string; enrolledCount: number }) { - return ( -
- - - -
-

- {enrolledCount === 0 ? "You are all set" : `${enrolledCount} mailbox${enrolledCount === 1 ? "" : "es"} warming in the pool`} -

-

- {orgName ? `Linked to ${orgName}. ` : ""} - Warmup starts on the first slot of each mailbox's window and ramps daily. Health and volume show up on this page as they arrive. -

-
-
- ); -} diff --git a/web/src/app/app/settings/warmbly-cloud/LinkedInstances.tsx b/web/src/app/app/settings/warmbly-cloud/LinkedInstances.tsx index 6371e6a22..b08686cb1 100644 --- a/web/src/app/app/settings/warmbly-cloud/LinkedInstances.tsx +++ b/web/src/app/app/settings/warmbly-cloud/LinkedInstances.tsx @@ -2,6 +2,7 @@ // workspace and the pool allowance they share. import React from "react"; +import { Navigate } from "@tanstack/react-router"; import toast from "react-hot-toast/headless"; import { Loader2Icon, ServerIcon } from "lucide-react"; import type { AppError } from "@/lib/api/client/normalizeError"; @@ -24,6 +25,8 @@ export default function LinkedInstances() { } const list = q.data?.data ?? []; const plan = q.data?.plan; + // Linking is closed, so a workspace with no live link has nothing to manage here. + if (q.isSuccess && !list.some((i) => !i.revoked_at)) return ; return (
@@ -31,50 +34,46 @@ export default function LinkedInstances() {

{plan.mailbox_limit === null ? `Unlimited mailboxes · ${plan.enrolled} warming` - : `${plan.enrolled} of ${plan.mailbox_limit} free mailboxes used, counting the ones connected here and through instances`} + : plan.subscription_required + ? "Linked instances keep the mailboxes they already enrolled. Adding mailboxes through one needs a paid plan." + : `${plan.enrolled} of ${plan.mailbox_limit} free mailboxes used, counting the ones connected here and through instances`}

)} - {list.length === 0 ? ( -

- No self-hosted instance is linked. On your instance, open Settings, Warmbly Cloud and press Connect; approve the code at /connect here. -

- ) : ( - -
    - {list.map((inst) => ( -
  • - - - -
    -

    {inst.name}

    -

    - {inst.mailbox_count} mailbox{inst.mailbox_count === 1 ? "" : "es"} - {inst.version && ` · v${inst.version}`} - {inst.last_seen_at && ` · seen ${new Date(inst.last_seen_at).toLocaleString()}`} -

    -
    - -
  • - ))} -
-
- )} + +
    + {list.map((inst) => ( +
  • + + + +
    +

    {inst.name}

    +

    + {inst.mailbox_count} mailbox{inst.mailbox_count === 1 ? "" : "es"} + {inst.version && ` · v${inst.version}`} + {inst.last_seen_at && ` · seen ${new Date(inst.last_seen_at).toLocaleString()}`} +

    +
    + +
  • + ))} +
+
); } diff --git a/web/src/app/app/settings/warmbly-cloud/page.test.tsx b/web/src/app/app/settings/warmbly-cloud/page.test.tsx index f7eed0188..100d9a628 100644 --- a/web/src/app/app/settings/warmbly-cloud/page.test.tsx +++ b/web/src/app/app/settings/warmbly-cloud/page.test.tsx @@ -26,8 +26,8 @@ vi.mock("@/lib/api/hooks/app/cloudlink/useCloudLink", () => ({ useUnenrollCloudLinkMailbox: () => ({ mutateAsync: vi.fn() }), useCloudLinkMailboxLifecycle: () => ({ mutateAsync: vi.fn() }), })); -vi.mock("./ConnectFlow", () => ({ default: () =>
Connection setup
})); vi.mock("./LinkedInstances", () => ({ default: () => null })); +vi.mock("@tanstack/react-router", () => ({ Navigate: ({ to }: { to: string }) =>
Redirected to {to}
})); vi.mock("@/components/app/emails/CloudMailboxPicker", () => ({ default: () =>
Existing Cloud mailboxes
})); describe("existing Cloud connections", () => { @@ -59,7 +59,6 @@ describe("existing Cloud connections", () => { expect(screen.getByText("Existing Cloud mailboxes")).toBeInTheDocument(); expect(screen.queryByText(/legacy/i)).not.toBeInTheDocument(); expect(screen.queryByText("Connect this workspace")).not.toBeInTheDocument(); - expect(screen.queryByText("Connection setup")).not.toBeInTheDocument(); expect(screen.getByRole("switch")).toBeEnabled(); fireEvent.click(screen.getByRole("switch")); await waitFor(() => expect(fixture.enroll).toHaveBeenCalledWith("mailbox")); @@ -84,7 +83,6 @@ describe("existing Cloud connections", () => { fixture.status.link!.organization_id = "local"; render(); expect(screen.queryByText(/legacy/i)).not.toBeInTheDocument(); - expect(screen.queryByText("Connection setup")).not.toBeInTheDocument(); fireEvent.click(screen.getByRole("button", { name: "Disconnect" })); expect(fixture.confirm.mock.calls[0][0]).toContain("this workspace"); await fixture.confirm.mock.calls[0][1](); @@ -95,11 +93,11 @@ describe("existing Cloud connections", () => { expect(fixture.disconnect).toHaveBeenLastCalledWith(true); }); - it("only offers connection setup when disconnected", () => { + it("has no page for an instance that is not linked, since Cloud links no new instances", () => { fixture.status.connected = false; fixture.status.legacy_connected = false; fixture.status.link = null; render(); - expect(screen.getByText("Connection setup")).toBeInTheDocument(); + expect(screen.getByText("Redirected to /app/settings/profile")).toBeInTheDocument(); }); }); diff --git a/web/src/app/app/settings/warmbly-cloud/page.tsx b/web/src/app/app/settings/warmbly-cloud/page.tsx index f2f607b87..1ef943a21 100644 --- a/web/src/app/app/settings/warmbly-cloud/page.tsx +++ b/web/src/app/app/settings/warmbly-cloud/page.tsx @@ -5,7 +5,8 @@ // instances linked to this workspace (GET /pool-link/instances). import React from "react"; -import { AnimatePresence, motion } from "framer-motion"; +import { Navigate } from "@tanstack/react-router"; +import { motion } from "framer-motion"; import toast from "react-hot-toast/headless"; import { CheckIcon, CloudIcon, ExternalLinkIcon, Loader2Icon, RefreshCwIcon, SparklesIcon } from "lucide-react"; import { useInstanceAdmin, usePermission } from "@/hooks/usePermission"; @@ -18,8 +19,8 @@ import buildError from "@/lib/helper/buildError"; import { useCloudLinkStatus, useDisconnectCloudLink } from "@/lib/api/hooks/app/cloudlink/useCloudLink"; import type { PoolLinkPlan } from "@/lib/api/models/app/cloudlink/CloudLink"; import { WARMUP_PLAN_BENEFITS, WARMUP_PLAN_PITCH } from "@/lib/plans"; +import { cloudAddsNeedSubscription } from "@/lib/cloudPlan"; import { Row, Section, SectionShell } from "../_components/SectionShell"; -import ConnectFlow from "./ConnectFlow"; import MailboxTable from "./MailboxTable"; import CloudMailboxPicker from "@/components/app/emails/CloudMailboxPicker"; import LinkedInstances from "./LinkedInstances"; @@ -59,11 +60,6 @@ function SelfHostedCloud() { const status = useCloudLinkStatus(); const disconnect = useDisconnectCloudLink(); const confirm = useConfirm(); - // The step flow stays up after linking until the user finishes it, so a - // fresh link walks through mailbox selection instead of dropping into the - // steady-state table. - const [flow, setFlow] = React.useState(null); - const showFlow = flow ?? (status.data ? !status.data.connected : false); if (status.isLoading || !status.data) { return ( @@ -75,6 +71,8 @@ function SelfHostedCloud() { ); } const st = status.data; + // Warmbly Cloud links no new instances, so an unlinked one has no page here. + if (!st.connected && !st.legacy_connected) return ; const plan = st.info?.plan; const serverWide = st.connected && !st.link?.organization_id; @@ -95,90 +93,75 @@ function SelfHostedCloud() { ) : undefined } > - - {showFlow ? ( - - { - setFlow(false); - void status.refetch(); - }} - /> - - ) : ( - -
- - - - - {st.link?.organization_name || "Warmbly Cloud"} - - } - description={ - st.reachable ? ( - Connected{st.link?.connected_at ? ` since ${new Date(st.link.connected_at).toLocaleDateString()}` : ""} - ) : ( - Cloud unreachable{st.error ? `: ${st.error}` : ""} - ) - } - /> -
- {plan && ( -
- -
- )} -
- - -
-
- - - - {st.legacy_connected && !serverWide && ( - - - - )} -
-
+ +
+ + + + + {st.link?.organization_name || "Warmbly Cloud"} + + } + description={ + st.reachable ? ( + Connected{st.link?.connected_at ? ` since ${new Date(st.link.connected_at).toLocaleDateString()}` : ""} + ) : ( + Cloud unreachable{st.error ? `: ${st.error}` : ""} + ) + } + /> +
+ {plan && ( +
+ +
)} -
+
+ + +
+
+ + + + {st.legacy_connected && !serverWide && ( + + + + )} +
+ ); } @@ -189,7 +172,8 @@ function SelfHostedCloud() { function PlanCard({ plan }: { plan: PoolLinkPlan }) { const premium = plan.tier === "paid"; const limit = plan.mailbox_limit; - const atLimit = !premium && limit !== null && plan.enrolled >= limit; + const closed = cloudAddsNeedSubscription(plan); + const atLimit = !premium && (closed || (limit !== null && plan.enrolled >= limit)); return (
@@ -202,13 +186,15 @@ function PlanCard({ plan }: { plan: PoolLinkPlan }) { - {premium ? "Unlimited" : limit === null ? "Unlimited" : `${plan.enrolled} of ${limit} mailboxes`} + {premium ? "Unlimited" : closed ? `${plan.enrolled} kept, no new` : limit === null ? "Unlimited" : `${plan.enrolled} of ${limit} mailboxes`}

{premium ? "Your mailboxes warm in the premium pool, built for inbox placement, with reputation protection and priority matching." - : atLimit + : closed + ? "Mailboxes already in Warmbly Cloud keep warming. New ones warm on this instance, which is not effective, unless the workspace moves to a paid plan. Self-hosted instances get no support from Warmbly." + : atLimit ? `Every free pool mailbox is in use. ${WARMUP_PLAN_PITCH}` : `Up to ${limit ?? 10} mailboxes in the free pool. ${WARMUP_PLAN_PITCH}`}

@@ -235,7 +221,7 @@ function PlanCard({ plan }: { plan: PoolLinkPlan }) { rel="noreferrer" className="h-7 px-2.5 rounded-md bg-sky-600 hover:bg-sky-700 text-white text-[12px] font-medium inline-flex items-center gap-1.5 transition-colors" > - Premium for ${plan.price_usd}/mo + See plans )} diff --git a/web/src/app/app/settings/webhooks/page.tsx b/web/src/app/app/settings/webhooks/page.tsx index 4adc550d5..4198b12d5 100644 --- a/web/src/app/app/settings/webhooks/page.tsx +++ b/web/src/app/app/settings/webhooks/page.tsx @@ -121,14 +121,16 @@ function EventPicker({ const filtered = React.useMemo(() => { const needle = q.trim().toLowerCase(); - if (!needle) return catalog; - return catalog.filter( + // A deprecated event is never delivered, so it is offered only to untick. + const offered = catalog.filter((d) => !d.deprecated || value.includes(d.type)); + if (!needle) return offered; + return offered.filter( (d) => d.type.toLowerCase().includes(needle) || d.category.toLowerCase().includes(needle) || d.description.toLowerCase().includes(needle), ); - }, [catalog, q]); + }, [catalog, q, value]); const grouped = React.useMemo(() => { const g: Record = {}; diff --git a/web/src/app/app/settings/workspace/page.tsx b/web/src/app/app/settings/workspace/page.tsx index fa409d815..f5592141b 100644 --- a/web/src/app/app/settings/workspace/page.tsx +++ b/web/src/app/app/settings/workspace/page.tsx @@ -18,6 +18,8 @@ import { useRegisterUnsaved } from "@/hooks/context/unsaved"; import useCurrentOrganization from "@/lib/api/hooks/app/organizations/useCurrentOrganization"; import { usePermission } from "@/hooks/usePermission"; import useAiMetered from "@/hooks/useAiMetered"; +import { fmtUsdAbout } from "@/lib/money"; +import { AI_ESTIMATE_USD } from "@/lib/aiEstimates"; import AdvisorSettingsSection from "@/components/app/advisor/AdvisorSettingsSection"; import RemieToolPolicies from "../_components/RemieToolPolicies"; @@ -299,7 +301,7 @@ function WorkspaceSettings({ org: currentOrg }: { org: StoreOrganization | null
s.emails); - const tagAccountIds = React.useMemo( - () => - scope.kind === "tag" - ? storeEmails - .filter((m) => (m.tags ?? []).includes(scope.tagId)) - .map((m) => m.id) - : null, - [scope, storeEmails], - ); // A premade view resolves to the workspace's label rows by slug, so the // filter is recomputed once the overview has loaded them. const viewCategoriesData = overview.data?.categories; @@ -334,10 +324,7 @@ export default function UniboxPage() { next.automated = false; break; case "tag": - // Tag→mailbox membership resolves through the store's - // mailbox directory (populated by DataSyncProvider); the - // server only knows accountIds. - next.accountIds = tagAccountIds ?? []; + // The server resolves the tag to its mailboxes (tag_ids). next.tagId = scope.tagId; next.automated = false; break; @@ -371,11 +358,11 @@ export default function UniboxPage() { } return next; }, - [scope, tagAccountIds, viewCategoriesData], + [scope, viewCategoriesData], ); const scopeBase = React.useMemo(() => paramsForScope("newest"), [paramsForScope]); const { params, baseParams, setParams, search, setSearch, keepSearch } = - useInboxBrowseState(scopeKey(scope), scopeBase, storeEmails); + useInboxBrowseState(scopeKey(scope), scopeBase); // ── Scope label for header chip ──────────────────────────────── const overviewData = overview.data; diff --git a/web/src/app/app/unibox/uniboxBulkArchive.test.tsx b/web/src/app/app/unibox/uniboxBulkArchive.test.tsx index c5ff398df..276411663 100644 --- a/web/src/app/app/unibox/uniboxBulkArchive.test.tsx +++ b/web/src/app/app/unibox/uniboxBulkArchive.test.tsx @@ -2,8 +2,9 @@ // // The fake server below keeps real folder state and pages like the backend, so // what the list shows after each round is what a reload would show. The rows -// are counted in the DOM, including any still mounted after their exit, which -// is how a stalled exit shows up: the archived rows stay on screen. +// are read from the DOM, including any still mounted after their exit, which +// is how a stalled exit shows up: the archived rows stay on screen. The list +// is virtualized, so only the rows near the viewport are mounted. import React from "react"; import { describe, it, expect, vi, beforeAll, beforeEach } from "vitest"; @@ -89,6 +90,8 @@ vi.mock("@/hooks/context/socket", async (orig) => { }; }); +const index = (threadId: string | null) => Number(threadId?.slice("thread-".length)); + const visible = () => [...document.querySelectorAll("[data-thread-id]")].map((e) => e.getAttribute("data-thread-id")); @@ -113,17 +116,20 @@ describe("bulk archive from the selection bar", SUITE, () => { await mount("/app/unibox/inbox"); for (let i = 0; i < 4; i++) await settle(); const first = visible(); - expect(first).toHaveLength(50); + expect(first.length).toBeGreaterThan(0); + expect(first.every((id) => index(id) < 50)).toBe(true); await archiveAll(); const second = visible(); - // The next fifty, and nothing from the first round left mounted. - expect(second).toHaveLength(50); + // The next page, and nothing from the first round left mounted. + expect(second.length).toBeGreaterThan(0); + expect(second.every((id) => index(id) >= 50 && index(id) < 100)).toBe(true); expect(second.filter((id) => first.includes(id))).toEqual([]); await archiveAll(); const third = visible(); - expect(third).toHaveLength(30); + expect(third.length).toBeGreaterThan(0); + expect(third.every((id) => index(id) >= 100)).toBe(true); expect(third.filter((id) => first.includes(id) || second.includes(id))).toEqual([]); const archived = server.rows.filter((r) => r.folder === "archive").length; diff --git a/web/src/app/app/unibox/uniboxHarness.tsx b/web/src/app/app/unibox/uniboxHarness.tsx index 1ca35cc7e..affb7aa55 100644 --- a/web/src/app/app/unibox/uniboxHarness.tsx +++ b/web/src/app/app/unibox/uniboxHarness.tsx @@ -136,8 +136,9 @@ export function route(url: string): unknown { } if (url.startsWith("/organization")) return [{ id: "org-1", name: "Org", slug: "org", role: "owner" }]; if (url.startsWith("/subscription/credits")) { - return { monthly_balance: 100, monthly_allowance: 100, purchased_balance: 0, spent_today: 0, spent_week: 0, spent_month: 0 }; + return { monthly_balance: 100, monthly_allowance: 100, purchased_balance: 0, spent_today: 0, spent_week: 0, spent_month: 0, balance_usd: 1, monthly_usd: 1, purchased_usd: 0, monthly_allowance_usd: 1 }; } + if (url.startsWith("/subscription/balance")) return { unlimited: true }; if (url.startsWith("/subscription")) return { plan: { name: "Pro" }, status: "active" }; if (url.startsWith("/unibox/overview")) { return { total: ROWS.length, unread: 0, awaiting_reply: 0, snoozed: 0, today: 0, week: 0, mailboxes: [], tags: [], categories: [], folders: [] }; diff --git a/web/src/app/app/unibox/uniboxSearch.test.tsx b/web/src/app/app/unibox/uniboxSearch.test.tsx index ea44e902e..0f1cdfcee 100644 --- a/web/src/app/app/unibox/uniboxSearch.test.tsx +++ b/web/src/app/app/unibox/uniboxSearch.test.tsx @@ -86,11 +86,15 @@ describe("unibox search", SUITE, () => { useAppStore.setState({ selectedThreadId: null, navCollapsed: false }); }); - it("does not broaden an explicit tag with no matching mailboxes into an all-mail request", async () => { + it("asks the server for an explicit tag instead of broadening it into an all-mail request", async () => { await mount("/app/unibox/tag?ref=unassigned-tag"); await settle(); - expect(searchRequests).toEqual([]); - expect(screen.queryByText("Subject 3")).toBeNull(); + expect(searchRequests.length).toBeGreaterThan(0); + for (const url of searchRequests) { + const params = new URL(url, "https://test.local").searchParams; + expect(params.get("tag_ids")).toBe("unassigned-tag"); + expect(params.get("email_ids")).toBeNull(); + } }); it("sends what was typed as the free-text param", async () => { diff --git a/web/src/app/app/unibox/useInboxBrowseState.test.tsx b/web/src/app/app/unibox/useInboxBrowseState.test.tsx index 8938bf1d5..feece8753 100644 --- a/web/src/app/app/unibox/useInboxBrowseState.test.tsx +++ b/web/src/app/app/unibox/useInboxBrowseState.test.tsx @@ -14,9 +14,9 @@ function Owner({ children }: { children: ReactNode }) { } const key = `${BROWSE_STORAGE_PREFIX}user:workspace:unibox.list.browsing`; const all: UniboxSearchParams = { includeArchived: true }; -const mount = (scope = "all", base = all, accounts: { id: string; tags?: string[] }[] = []) => renderHook( - (props) => useInboxBrowseState(props.scope, props.base, props.accounts), - { wrapper: Owner, initialProps: { scope, base, accounts } }, +const mount = (scope = "all", base = all) => renderHook( + (props) => useInboxBrowseState(props.scope, props.base), + { wrapper: Owner, initialProps: { scope, base } }, ); beforeEach(() => { @@ -46,16 +46,14 @@ describe("inbox canonical browsing", () => { expect(stored.value.filters).not.toHaveProperty("includeArchived"); }); - it("recomposes a selected tag from current membership instead of saving mailbox ids", () => { - const page = mount("all", all, [{ id: "old", tags: ["tag"] }]); + it("keeps a selected tag as the tag instead of saving or sending mailbox ids", () => { + const page = mount("all", all); act(() => page.result.current.setParams((previous) => ({ ...previous, tagId: "tag", accountIds: ["old"] }))); expect(JSON.parse(sessionStorage.getItem(key)!).value.filters).toEqual({ tagId: "tag" }); page.unmount(); - const refreshed = mount("all", all, [{ id: "new", tags: ["tag"] }]); - expect(refreshed.result.current.params.accountIds).toEqual(["new"]); - refreshed.rerender({ scope: "all", base: all, accounts: [] }); + const refreshed = mount("all", all); expect(refreshed.result.current.params.tagId).toBe("tag"); - expect(refreshed.result.current.params.accountIds).toEqual([]); + expect(refreshed.result.current.params.accountIds).toBeUndefined(); }); it("metadata arriving for tag and premade-view scopes does not reset restored extra filters", () => { @@ -63,12 +61,12 @@ describe("inbox canonical browsing", () => { act(() => { page.result.current.setParams((previous) => ({ ...previous, from: "sender", sortBy: "oldest" })); page.result.current.setSearch("subject"); }); page.unmount(); const refreshed = mount("tag:tag", { accountIds: [], tagId: "tag" }); - refreshed.rerender({ scope: "tag:tag", base: { accountIds: ["loaded"], tagId: "tag" }, accounts: [] }); + refreshed.rerender({ scope: "tag:tag", base: { accountIds: ["loaded"], tagId: "tag" } }); expect(refreshed.result.current.params).toMatchObject({ from: "sender", sortBy: "oldest", accountIds: ["loaded"] }); expect(refreshed.result.current.search).toBe("subject"); - refreshed.rerender({ scope: "view:interested", base: { categoryIds: [] }, accounts: [] }); + refreshed.rerender({ scope: "view:interested", base: { categoryIds: [] } }); act(() => refreshed.result.current.setParams((previous) => ({ ...previous, from: "view-sender" }))); - refreshed.rerender({ scope: "view:interested", base: { categoryIds: ["current-category"] }, accounts: [] }); + refreshed.rerender({ scope: "view:interested", base: { categoryIds: ["current-category"] } }); expect(refreshed.result.current.params).toMatchObject({ from: "view-sender", categoryIds: ["current-category"] }); }); @@ -82,9 +80,9 @@ describe("inbox canonical browsing", () => { expect(linked.result.current.search).toBe(""); act(() => linked.result.current.setSearch("across scopes")); linked.result.current.keepSearch.current = true; - linked.rerender({ scope: "all", base: all, accounts: [] }); + linked.rerender({ scope: "all", base: all }); expect(linked.result.current.search).toBe("across scopes"); - linked.rerender({ scope: "folder:sent", base: { folder: "sent" }, accounts: [] }); + linked.rerender({ scope: "folder:sent", base: { folder: "sent" } }); expect(linked.result.current.search).toBe(""); expect(linked.result.current.params.sortBy).toBe("oldest"); }); @@ -99,7 +97,7 @@ describe("inbox canonical browsing", () => { vi.setSystemTime(new Date("2026-10-09T12:00:00Z")); const refreshed = mount("today", { since: inboxPresetDate("today") }); expect(refreshed.result.current.params.since).toEqual(inboxPresetDate("today")); - refreshed.rerender({ scope: "all", base: all, accounts: [] }); + refreshed.rerender({ scope: "all", base: all }); act(() => refreshed.result.current.setParams((previous) => ({ ...previous, since: inboxPresetDate("week"), datePreset: "week" }))); expect(JSON.parse(sessionStorage.getItem(key)!).value.filters).toEqual({ datePreset: "week" }); refreshed.unmount(); diff --git a/web/src/app/app/unibox/useInboxBrowseState.ts b/web/src/app/app/unibox/useInboxBrowseState.ts index 075a6a069..280f34bb4 100644 --- a/web/src/app/app/unibox/useInboxBrowseState.ts +++ b/web/src/app/app/unibox/useInboxBrowseState.ts @@ -3,7 +3,7 @@ import useBrowseState from "@/hooks/useBrowseState"; import { composeInboxParams, inboxListSchema, inboxUserOverrides, type InboxListState } from "@/lib/browse-inbox"; import type { UniboxSearchParams } from "@/lib/api/models/app/unibox/UniboxSearch"; -export default function useInboxBrowseState(scope: string, base: UniboxSearchParams, accounts: { id: string; tags?: string[] }[]) { +export default function useInboxBrowseState(scope: string, base: UniboxSearchParams) { const [saved, setSaved] = useBrowseState("unibox.list.browsing", () => ({ scope, search: "", sortBy: "newest", filters: {} }), inboxListSchema); const keepSearch = useRef(false); let current = saved; @@ -13,11 +13,11 @@ export default function useInboxBrowseState(scope: string, base: UniboxSearchPar setSaved(current); } const baseParams = { ...base, sortBy: current.sortBy }; - const params = composeInboxParams(baseParams, current.filters, accounts); + const params = composeInboxParams(baseParams, current.filters); const setParams = useCallback>>((action) => { setSaved((previous) => { const previousBase = { ...base, sortBy: previous.sortBy }; - const previousParams = composeInboxParams(previousBase, previous.filters, accounts); + const previousParams = composeInboxParams(previousBase, previous.filters); const next = typeof action === "function" ? action(previousParams) : action; if (next === previousParams) return previous; const filters = inboxUserOverrides(next, previousBase); @@ -25,7 +25,7 @@ export default function useInboxBrowseState(scope: string, base: UniboxSearchPar if (sortBy === previous.sortBy && JSON.stringify(filters) === JSON.stringify(previous.filters)) return previous; return { ...previous, sortBy, filters }; }); - }, [base, accounts, setSaved]); + }, [base, setSaved]); const setSearch = useCallback((search: string) => setSaved((previous) => previous.search === search ? previous : { ...previous, search }), [setSaved]); return { params, baseParams, setParams, search: current.search, setSearch, keepSearch }; } 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..6c93ca966 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"; @@ -30,7 +31,7 @@ import type { SSOLinkChallenge } from "@/lib/api/models/auth/LoginResult"; import beginSSO from "@/lib/api/client/auth/beginSSO"; import type { AppError } from "@/lib/api/client/normalizeError"; import buildError from "@/lib/helper/buildError"; -import { postAuthNext } from "@/lib/helper/safeNext"; +import { postAuthNext, rememberSSONext } from "@/lib/helper/safeNext"; import { hrefTarget } from "@/lib/routerSearch"; import { captureException } from "@/lib/observability"; import { isEmpty, readAcquisition } from "@/lib/acquisition"; @@ -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 || @@ -555,6 +559,7 @@ export default function LoginPage() { const handleProvider = useCallback(async (provider: string) => { try { const { url } = await beginSSO(provider); + rememberSSONext(new URLSearchParams(window.location.search).get("next")); window.location.href = url; } catch (e) { toast.error(buildError(e as AppError)); @@ -579,6 +584,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 +720,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 +922,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/app/auth/sso/page.tsx b/web/src/app/auth/sso/page.tsx index eac7c8880..b45bb3738 100644 --- a/web/src/app/auth/sso/page.tsx +++ b/web/src/app/auth/sso/page.tsx @@ -16,6 +16,8 @@ import { takeSSOBinding } from "@/lib/api/client/auth/beginSSO"; import getUser from "@/lib/api/client/auth/getUser"; import { saveTokens } from "@/lib/auth"; import buildError from "@/lib/helper/buildError"; +import { postAuthNext, takeSSONext } from "@/lib/helper/safeNext"; +import { hrefTarget } from "@/lib/routerSearch"; import type { AppError } from "@/lib/api/client/normalizeError"; export default function SSOCallbackPage() { @@ -38,6 +40,7 @@ export default function SSOCallbackPage() { } (async () => { + const next = takeSSONext(); try { const session = await exchangeSSO(code, takeSSOBinding()); @@ -50,7 +53,7 @@ export default function SSOCallbackPage() { setError("Two-factor authentication is required, but the challenge did not arrive. Try signing in again."); return; } - navigate({ to: "/auth/login", replace: true, state: { two_fa_pending: session.pending_token } }); + navigate({ to: "/auth/login", search: { next }, replace: true, state: { two_fa_pending: session.pending_token } }); return; } // The provider's address already belongs to an account with a @@ -63,6 +66,7 @@ export default function SSOCallbackPage() { } navigate({ to: "/auth/login", + search: { next }, replace: true, state: { sso_link: { @@ -86,7 +90,7 @@ export default function SSOCallbackPage() { } catch { // UserProvider retries and redirects on a genuine failure. } - navigate({ to: "/app/emails", replace: true }); + navigate({ ...hrefTarget(postAuthNext(next)), replace: true }); } catch (err) { setError(buildError(err as AppError)); } diff --git a/web/src/app/connect/page.tsx b/web/src/app/connect/page.tsx index 2ebab6e68..1841775b4 100644 --- a/web/src/app/connect/page.tsx +++ b/web/src/app/connect/page.tsx @@ -1,113 +1,13 @@ import { DashboardImage } from "@/components/ui/dashboard-image"; -// app.warmbly.com/connect?code=XXXX-XXXX — a signed-in member approves a -// self-hosted instance's request to warm its mailboxes in this workspace. -// Standalone on the auth screen's sky: enter code, review, done. +// app.warmbly.com/connect: where older self-hosted instances still send people to approve a link. Warmbly Cloud links no new instances. -import React from "react"; -import { Link, Navigate } from "@tanstack/react-router"; -import { useSearchParams } from "@/hooks/useSearchParams"; -import { AnimatePresence, motion } from "framer-motion"; -import { REGEXP_ONLY_DIGITS_AND_CHARS } from "input-otp"; -import toast from "react-hot-toast/headless"; -import { - ArrowLeftIcon, - ArrowRightIcon, - BuildingIcon, - CheckIcon, - CloudIcon, - ExternalLinkIcon, - FlameIcon, - Loader2Icon, - LockIcon, - ServerIcon, - XIcon, -} from "lucide-react"; -import { InputOTP, InputOTPGroup, InputOTPSlot } from "@/components/ui/input-otp"; +import { Link } from "@tanstack/react-router"; +import { motion } from "framer-motion"; +import { ArrowRightIcon, CloudIcon } from "lucide-react"; import BrandMark from "@/components/shared/BrandMark"; -import ReauthModal from "@/components/app/modals/ReauthModal"; -import getToken from "@/lib/helper/getToken"; -import type { AppError } from "@/lib/api/client/normalizeError"; -import buildError from "@/lib/helper/buildError"; -import type Organization from "@/lib/api/models/app/organizations/Organization"; -import useOrganizations from "@/lib/api/hooks/app/organizations/useOrganizations"; -import { useApprovePoolLinkCode, useDenyPoolLinkCode, usePoolLinkCode } from "@/lib/api/hooks/app/cloudlink/useCloudLink"; - -const CODE_LENGTH = 8; - -function clean(raw: string): string { - return raw.toUpperCase().replace(/[^A-Z0-9]/g, "").slice(0, CODE_LENGTH); -} - -function dashed(code: string): string { - return code.length > 4 ? `${code.slice(0, 4)}-${code.slice(4)}` : code; -} - -const slide = { - enter: (dir: number) => ({ opacity: 0, x: dir > 0 ? 28 : -28 }), - center: { opacity: 1, x: 0 }, - exit: (dir: number) => ({ opacity: 0, x: dir > 0 ? -28 : 28 }), -}; -const slideTransition = { duration: 0.28, ease: [0.16, 1, 0.3, 1] as const }; export default function ConnectPage() { - if (!getToken()) { - const next = window.location.pathname + window.location.search; - return ; - } - // Outside the /app layout, so approving (which needs a fresh confirmation) brings its own prompt. - return ( - <> - - - - ); -} - -function ConnectInner() { - const [params] = useSearchParams(); - const [code, setCode] = React.useState(() => clean(params.get("code") ?? "")); - const complete = code.length === CODE_LENGTH; - const lookup = usePoolLinkCode(dashed(code)); - const orgs = useOrganizations(); - const approve = useApprovePoolLinkCode(); - const deny = useDenyPoolLinkCode(); - const [orgId, setOrgId] = React.useState(""); - const [outcome, setOutcome] = React.useState<"approved" | "denied" | null>(null); - const [dir, setDir] = React.useState(1); - - React.useEffect(() => { - if (!orgId && orgs.data && orgs.data.length > 0) setOrgId(orgs.data[0].id); - }, [orgs.data, orgId]); - - const info = complete ? lookup.data : undefined; - const step: "code" | "review" | "done" = outcome ? "done" : info ? "review" : "code"; - - const reset = () => { - setDir(-1); - setCode(""); - setOutcome(null); - }; - - const doApprove = async () => { - try { - setDir(1); - await approve.mutateAsync({ code: dashed(code), organizationId: orgId }); - setOutcome("approved"); - } catch (e) { - toast.error(buildError(e as AppError)); - } - }; - const doDeny = async () => { - try { - setDir(1); - await deny.mutateAsync(dashed(code)); - setOutcome("denied"); - } catch (e) { - toast.error(buildError(e as AppError)); - } - }; - return (
); diff --git a/web/src/app/select-org/page.tsx b/web/src/app/select-org/page.tsx index e891bc7ca..ac7fa6afd 100644 --- a/web/src/app/select-org/page.tsx +++ b/web/src/app/select-org/page.tsx @@ -32,6 +32,8 @@ import { Logo } from "@/components/svg"; import { NewWorkspaceDialog } from "@/components/app/organizations/NewWorkspaceDialog"; import type { AppError } from "@/lib/api/client/normalizeError"; import buildError from "@/lib/helper/buildError"; +import { postAuthNext } from "@/lib/helper/safeNext"; +import { hrefTarget } from "@/lib/routerSearch"; function relativeAge(d: Date | string): string { const date = typeof d === "string" ? new Date(d) : d; @@ -125,7 +127,7 @@ function SelectOrgPageInner() { await switchOrg.mutateAsync(orgId); const org = orgList.find((o) => o.id === orgId); if (org) setCurrentOrganization(org); - navigate({ to: "/app/emails", replace: true }); + navigate({ ...hrefTarget(postAuthNext(new URLSearchParams(window.location.search).get("next"))), replace: true }); } catch (e) { toast.error(buildError(e as AppError)); } diff --git a/web/src/components/app/advisor/AdvisorSettingsSection.tsx b/web/src/components/app/advisor/AdvisorSettingsSection.tsx index 26f11e830..d7b9dd5ab 100644 --- a/web/src/components/app/advisor/AdvisorSettingsSection.tsx +++ b/web/src/components/app/advisor/AdvisorSettingsSection.tsx @@ -64,7 +64,7 @@ export default function AdvisorSettingsSection({ canManage }: { canManage: boole return (
{!activeTab?.freeModel && metered && - activeTab?.credits != null && ( + activeTab?.balanceUsd != null && ( - {activeTab.credits.toLocaleString()} credits + {fmtUsd(activeTab.balanceUsd)} balance )}
diff --git a/web/src/components/app/agent/agentDemo.ts b/web/src/components/app/agent/agentDemo.ts index 606b46766..cfa643594 100644 --- a/web/src/components/app/agent/agentDemo.ts +++ b/web/src/components/app/agent/agentDemo.ts @@ -35,43 +35,43 @@ function tool(name: string, args: string, result: string, ms: number): DemoStep[ ]; } -function iteration(n: number, credits: number): DemoStep { +function iteration(n: number, balanceUsd: number): DemoStep { return { wait: 200, - ev: { type: "iteration", iteration: n, budget: 12, credits_remaining: credits }, + ev: { type: "iteration", iteration: n, budget: 12, balance_usd: balanceUsd }, }; } export function demoRun(part: "open" | "approve" | "deny"): DemoStep[] { if (part === "approve") { return [ - iteration(4, 479), + iteration(4, 4.79), ...tool("set_campaign_status", `${CAMPAIGN}, status: "paused"`, "Paused Agency re-engagement", 1100), { wait: 700, ev: { type: "iteration", iteration: 5, budget: 12 } }, ...say( "Done. **Agency re-engagement** is paused and nothing else was changed. Resume it from the campaign page once the list is cleaned.", ), - { wait: 100, ev: { type: "done", credits_remaining: 478 } }, + { wait: 100, ev: { type: "done", balance_usd: 4.78 } }, ]; } if (part === "deny") { return [ - iteration(4, 479), + iteration(4, 4.79), ...say( "Okay, I left it running. Keep an eye on its bounce rate: at 10% the sending mailbox can be blocked from the warmup pool.", ), - { wait: 100, ev: { type: "done", credits_remaining: 479 } }, + { wait: 100, ev: { type: "done", balance_usd: 4.79 } }, ]; } return [ - { wait: 900, ev: { type: "iteration", iteration: 1, budget: 12, credits_remaining: 482 } }, + { wait: 900, ev: { type: "iteration", iteration: 1, budget: 12, balance_usd: 4.82 } }, ...tool("list_campaigns", "status: active", "4 active campaigns", 1100), - iteration(2, 481), + iteration(2, 4.81), ...tool("get_campaign_stats", 'campaign: "Q4 founder outreach"', "41% opened, 6.2% replied, 0.4% bounced", 1200), ...tool("get_campaign_stats", CAMPAIGN, "9% opened, 0.3% replied, 7.8% bounced", 1000), ...tool("get_mailbox", 'mailbox: "sam@getacme.io"', "warmup throttled, 22% spam placement", 900), ...tool("get_advisor_summary", "", "2 open recommendations", 800), - iteration(3, 480), + iteration(3, 4.80), { wait: 1200, ev: { type: "iteration", iteration: 3, budget: 12 } }, ...say( [ diff --git a/web/src/components/app/ai/AIDraftBar.tsx b/web/src/components/app/ai/AIDraftBar.tsx index ed27be87b..6c4d59701 100644 --- a/web/src/components/app/ai/AIDraftBar.tsx +++ b/web/src/components/app/ai/AIDraftBar.tsx @@ -21,17 +21,15 @@ import { Trash2Icon, XIcon, } from "lucide-react"; -import toast from "react-hot-toast/headless"; -import type { AppError } from "@/lib/api/client/normalizeError"; -import buildError from "@/lib/helper/buildError"; import useTypewriter from "./useTypewriter"; import formatUsage from "./usage"; +import { reportAIError } from "./reportAIError"; import AIBusyStatus, { AI_PILL_CLASS } from "./AIBusyStatus"; export interface AIDraftController { phase: "idle" | "busy" | "review" | "question"; // What the last draft actually cost (usage-based settle), when metered. - usage: { charged: number; tokens: number } | null; + usage: { chargedUsd: number; tokens: number } | null; // Clarifying question the generator asked instead of drafting (grounded // endpoints ask when they can't tell what the email is for). question: string | null; @@ -61,8 +59,8 @@ interface GenerateResult { text?: string; question?: string; grounding?: AIDraftGrounding; - credits_remaining: number; - credits_charged?: number; + // What the call cost in dollars. + charged_usd?: number; tokens_used?: number; } @@ -76,7 +74,7 @@ interface UseAIDraftOptions { export function useAIDraft({ value, onChange, generate, maxLen }: UseAIDraftOptions): AIDraftController { const typewriter = useTypewriter(); const [phase, setPhase] = React.useState<"idle" | "busy" | "review" | "question">("idle"); - const [usage, setUsage] = React.useState<{ charged: number; tokens: number } | null>(null); + const [usage, setUsage] = React.useState<{ chargedUsd: number; tokens: number } | null>(null); const [question, setQuestion] = React.useState(null); const [grounding, setGrounding] = React.useState(null); @@ -105,7 +103,7 @@ export function useAIDraft({ value, onChange, generate, maxLen }: UseAIDraftOpti .then((res) => { if (runId.current !== id) return; setUsage({ - charged: res.credits_charged ?? 0, + chargedUsd: res.charged_usd ?? 0, tokens: res.tokens_used ?? 0, }); setGrounding(res.grounding ?? null); @@ -124,12 +122,7 @@ export function useAIDraft({ value, onChange, generate, maxLen }: UseAIDraftOpti }) .catch((e) => { if (runId.current !== id) return; - const err = e as AppError; - if (err?.status === 402) { - toast.error("You're out of AI credits. Upgrade or purchase more to keep drafting."); - } else { - toast.error(buildError(err)); - } + reportAIError(e); setPhase("idle"); }); }, @@ -227,7 +220,7 @@ export default function AIDraftBar({ ctrl.adjust(text); }; - const usageText = ctrl.usage ? formatUsage(ctrl.usage.charged, ctrl.usage.tokens) : ""; + const usageText = ctrl.usage ? formatUsage(ctrl.usage.chargedUsd, ctrl.usage.tokens) : ""; // Floats over the bottom of the body area; the wrapper is pointer-inert so // the textarea stays clickable around the card. diff --git a/web/src/components/app/ai/AIEditPopover.tsx b/web/src/components/app/ai/AIEditPopover.tsx index 898c06125..5ceaba872 100644 --- a/web/src/components/app/ai/AIEditPopover.tsx +++ b/web/src/components/app/ai/AIEditPopover.tsx @@ -81,7 +81,7 @@ interface AIEditPopoverProps { // reads as a rewrite that never reached the body (issue #432). changed?: boolean; // What the last run actually cost (usage-based settle), when metered. - usage: { charged: number; tokens: number } | null; + usage: { chargedUsd: number; tokens: number } | null; onRun: (instruction: string) => void; onUndo: () => void; onRetry: () => void; @@ -119,7 +119,7 @@ export default function AIEditPopover({ } if (phase === "applied") { - const usageText = usage ? formatUsage(usage.charged, usage.tokens) : ""; + const usageText = usage ? formatUsage(usage.chargedUsd, usage.tokens) : ""; const footer = changed ? usageText : ["The model returned the passage as it was.", usageText].filter(Boolean).join(" · "); diff --git a/web/src/components/app/ai/AIRunCard.tsx b/web/src/components/app/ai/AIRunCard.tsx index 09a34ca22..28eeba4d2 100644 --- a/web/src/components/app/ai/AIRunCard.tsx +++ b/web/src/components/app/ai/AIRunCard.tsx @@ -59,7 +59,7 @@ function ReviewMenu({ run, refinements }: { run: EditorAIRun; refinements: AIRef else items[active]?.act(); }; - const usage = run.usage ? formatUsage(run.usage.charged, run.usage.tokens) : ""; + const usage = run.usage ? formatUsage(run.usage.chargedUsd, run.usage.tokens) : ""; const summary = run.changed ? `${run.words} word${run.words === 1 ? "" : "s"} written` : "No change: it came back as it was"; diff --git a/web/src/components/app/ai/RichTextAICaret.tsx b/web/src/components/app/ai/RichTextAICaret.tsx index 0a2e1a546..262ee6fa2 100644 --- a/web/src/components/app/ai/RichTextAICaret.tsx +++ b/web/src/components/app/ai/RichTextAICaret.tsx @@ -24,6 +24,8 @@ import useClickOutside from "@/hooks/useClickOutside"; import useEditorSheen from "./useEditorSheen"; import useEditorAIRun from "./useEditorAIRun"; import AIRunCard from "./AIRunCard"; +import { fmtUsdAbout } from "@/lib/money"; +import { AI_ESTIMATE_USD } from "@/lib/aiEstimates"; import { AI_CARD_CLASS, WRITE_REFINEMENTS, aiRunCardClass } from "./aiCard"; const CONTEXT_WINDOW = 1500; @@ -252,7 +254,7 @@ export default function RichTextAICaret({ editor }: { editor: Editor }) { > Continue writing - {metered && from 1 credit} + {metered && {fmtUsdAbout(AI_ESTIMATE_USD.writingAssistant)}}
diff --git a/web/src/components/app/ai/TextareaAICaret.tsx b/web/src/components/app/ai/TextareaAICaret.tsx index e3026da86..f7acb4fee 100644 --- a/web/src/components/app/ai/TextareaAICaret.tsx +++ b/web/src/components/app/ai/TextareaAICaret.tsx @@ -21,16 +21,16 @@ import { SparklesIcon, Undo2Icon, } from "lucide-react"; -import toast from "react-hot-toast/headless"; import useGenerateWrite from "@/lib/api/hooks/app/generation/useGenerateWrite"; import { usePermission } from "@/hooks/usePermission"; import useAiMetered from "@/hooks/useAiMetered"; -import type { AppError } from "@/lib/api/client/normalizeError"; -import buildError from "@/lib/helper/buildError"; import ShortcutTooltip, { Kbd } from "@/components/ui/shortcut-tooltip"; import textareaRangeRect, { type RangeRect } from "./textareaRange"; import useTypewriter from "./useTypewriter"; import formatUsage from "./usage"; +import { reportAIError } from "./reportAIError"; +import { fmtUsdAbout } from "@/lib/money"; +import { AI_ESTIMATE_USD } from "@/lib/aiEstimates"; import AgentMark from "@/components/app/agent/AgentMark"; // Context window around the caret sent with freeform prompts, so long drafts @@ -78,7 +78,7 @@ export default function TextareaAICaret({ onChange, onDraftReply, draftLabel = "Draft a reply from this thread", - draftCost = "from 2 credits", + draftCost = fmtUsdAbout(AI_ESTIMATE_USD.replyDraft), contextHint, maxLen, }: TextareaAICaretProps) { @@ -101,7 +101,7 @@ export default function TextareaAICaret({ } | null>(null); const [open, setOpen] = React.useState(false); const [phase, setPhase] = React.useState("idle"); - const [usage, setUsage] = React.useState<{ charged: number; tokens: number } | null>(null); + const [usage, setUsage] = React.useState<{ chargedUsd: number; tokens: number } | null>(null); const [instruction, setInstruction] = React.useState(""); const rootRef = React.useRef(null); @@ -247,7 +247,7 @@ export default function TextareaAICaret({ onSuccess: (res) => { if (!openRef.current) return; setUsage({ - charged: res.credits_charged ?? 0, + chargedUsd: res.charged_usd ?? 0, tokens: res.tokens_used ?? 0, }); const before = prevValue.slice(0, pos); @@ -278,12 +278,7 @@ export default function TextareaAICaret({ ); }, onError: (e) => { - const err = e as unknown as AppError; - if (err?.status === 402) { - toast.error("You're out of AI credits. Upgrade or purchase more to keep writing with AI."); - } else { - toast.error(buildError(err)); - } + reportAIError(e); setPhase("idle"); }, }, @@ -397,9 +392,9 @@ export default function TextareaAICaret({ Inserted - {usage && formatUsage(usage.charged, usage.tokens) && ( + {usage && formatUsage(usage.chargedUsd, usage.tokens) && ( - · {formatUsage(usage.charged, usage.tokens)} + · {formatUsage(usage.chargedUsd, usage.tokens)} )} @@ -482,7 +477,7 @@ export default function TextareaAICaret({ > Continue writing - {metered && from 1 credit} + {metered && {fmtUsdAbout(AI_ESTIMATE_USD.writingAssistant)}}
diff --git a/web/src/components/app/ai/TextareaAIEdit.tsx b/web/src/components/app/ai/TextareaAIEdit.tsx index 726422337..1fe139020 100644 --- a/web/src/components/app/ai/TextareaAIEdit.tsx +++ b/web/src/components/app/ai/TextareaAIEdit.tsx @@ -13,10 +13,7 @@ import useClickOutside from "@/hooks/useClickOutside"; import { createPortal } from "react-dom"; import { AnimatePresence, motion } from "framer-motion"; import { SparklesIcon } from "lucide-react"; -import toast from "react-hot-toast/headless"; import useGenerateEdit from "@/lib/api/hooks/app/generation/useGenerateEdit"; -import type { AppError } from "@/lib/api/client/normalizeError"; -import buildError from "@/lib/helper/buildError"; import { Kbd } from "@/components/ui/shortcut-tooltip"; import AIEditPopover, { type AIEditPhase } from "./AIEditPopover"; import { AI_PILL_CLASS } from "./AIBusyStatus"; @@ -28,6 +25,7 @@ import textareaRangeRect, { type RangeRect, } from "./textareaRange"; import useTypewriter from "./useTypewriter"; +import { reportAIError } from "./reportAIError"; interface Selection { start: number; @@ -70,7 +68,7 @@ export default function TextareaAIEdit({ const [open, setOpen] = React.useState(false); const [phase, setPhase] = React.useState("idle"); const [changed, setChanged] = React.useState(true); - const [usage, setUsage] = React.useState<{ charged: number; tokens: number } | null>(null); + const [usage, setUsage] = React.useState<{ chargedUsd: number; tokens: number } | null>(null); const rootRef = React.useRef(null); // The selection being edited, frozen when the popover opens. @@ -213,10 +211,10 @@ export default function TextareaAIEdit({ prevValue: string, instruction: string, text: string, - charged: number, + chargedUsd: number, tokens: number, ) => { - setUsage({ charged, tokens }); + setUsage({ chargedUsd, tokens }); // The server returns its answer trimmed, so the author's own edges // go back on before anything is written or compared: what lands in // the box IS what "did it change?" is answered from (issue #432). @@ -285,17 +283,12 @@ export default function TextareaAIEdit({ prevValue, instruction, res.text, - res.credits_charged ?? 0, + res.charged_usd ?? 0, res.tokens_used ?? 0, ); }, onError: (e) => { - const err = e as unknown as AppError; - if (err?.status === 402) { - toast.error("You're out of AI credits. Upgrade or purchase more to keep editing with AI."); - } else { - toast.error(buildError(err)); - } + reportAIError(e); setPhase("idle"); }, }, diff --git a/web/src/components/app/ai/reportAIError.ts b/web/src/components/app/ai/reportAIError.ts index 2b531ba95..71aba1885 100644 --- a/web/src/components/app/ai/reportAIError.ts +++ b/web/src/components/app/ai/reportAIError.ts @@ -1,11 +1,14 @@ import toast from "react-hot-toast/headless"; import type { AppError } from "@/lib/api/client/normalizeError"; import buildError from "@/lib/helper/buildError"; +import { isInsufficientBalance, openInsufficientBalance } from "@/lib/insufficientBalance"; -// reportAIError toasts a failed AI call, naming the fix when credits ran out. +// reportAIError reports a failed AI call. A balance that ran out opens the +// add-money dialog instead of a toast. export function reportAIError(e: unknown) { - const err = e as AppError; - toast.error( - err?.status === 402 ? "You're out of AI credits. Upgrade or purchase more to keep writing with AI." : buildError(err), - ); + if (isInsufficientBalance(e)) { + openInsufficientBalance(); + return; + } + toast.error(buildError(e as AppError)); } diff --git a/web/src/components/app/ai/richTextAIEdit.test.tsx b/web/src/components/app/ai/richTextAIEdit.test.tsx index 708e46a2b..20c90d61b 100644 --- a/web/src/components/app/ai/richTextAIEdit.test.tsx +++ b/web/src/components/app/ai/richTextAIEdit.test.tsx @@ -48,9 +48,9 @@ vi.mock("@/hooks/context/confirm", () => ({ useConfirm: () => ({ show: (_: string, onSubmit: () => void) => onSubmit() }), })); -let reply = { text: "", credits_charged: 1, tokens_used: 1700 }; +let reply = { text: "", charged_usd: 0.01, tokens_used: 1700 }; let sent: { text: string; instruction: string; context?: string } | null = null; -let written = { text: "", credits_charged: 1, tokens_used: 10 }; +let written = { text: "", charged_usd: 0.01, tokens_used: 10 }; // Both endpoints stream: the answer arrives in two pieces, then done. // With hold set, the model writes only the first half and keeps going until stopped. let hold = false; @@ -124,12 +124,12 @@ describe("Edit with AI in the campaign body", () => { beforeEach(() => { captured = null; sent = null; - reply = { text: "", credits_charged: 1, tokens_used: 1700 }; + reply = { text: "", charged_usd: 0.01, tokens_used: 1700 }; }); it("sends the passage with its merge variables and its paragraph breaks", async () => { const { editor } = mountBody('

Hi {{.FirstName}}, quick one.

Saw your ads.

'); - reply = { text: "Rewritten.", credits_charged: 1, tokens_used: 10 }; + reply = { text: "Rewritten.", charged_usd: 0.01, tokens_used: 10 }; await select(editor, 1, editor.state.doc.content.size - 1); await rewrite(); expect(sent?.text).toBe("Hi {{.FirstName}}, quick one.\n\nSaw your ads."); @@ -140,7 +140,7 @@ describe("Edit with AI in the campaign body", () => { '

Please opt out if this misses.

', ); // The model keeps the markdown it was given and rewords around it. - reply = { text: "Or [opt out]({{.UnsubscribeLink}}) any time.", credits_charged: 1, tokens_used: 10 }; + reply = { text: "Or [opt out]({{.UnsubscribeLink}}) any time.", charged_usd: 0.01, tokens_used: 10 }; await select(editor, 1, editor.state.doc.content.size - 1); await rewrite("make it shorter"); expect(sent?.text).toBe("Please [opt out]({{.UnsubscribeLink}}) if this misses."); @@ -154,7 +154,7 @@ describe("Edit with AI in the campaign body", () => { it("wraps a destination the plain markdown form cannot hold", async () => { const url = "https://en.wikipedia.org/wiki/Foo_(bar)"; const { editor } = mountBody(`

See the page.

`); - reply = { text: "unused", credits_charged: 1, tokens_used: 10 }; + reply = { text: "unused", charged_usd: 0.01, tokens_used: 10 }; await select(editor, 1, editor.state.doc.content.size - 1); await rewrite(); expect(sent?.text).toBe(`See [the page](<${url}>).`); @@ -162,7 +162,7 @@ describe("Edit with AI in the campaign body", () => { it("replaces the whole selection and reports the new body upward", async () => { const { editor, saved } = mountBody("

Original one.

Original two.

"); - reply = { text: "New one.\n\nNew two.", credits_charged: 1, tokens_used: 10 }; + reply = { text: "New one.\n\nNew two.", charged_usd: 0.01, tokens_used: 10 }; await select(editor, 1, editor.state.doc.content.size - 1); await rewrite(); expect(editor.getHTML()).toBe("

New one.

New two.

"); @@ -172,7 +172,7 @@ describe("Edit with AI in the campaign body", () => { it("rewrites a phrase in place instead of splitting the paragraph around it", async () => { const { editor, saved } = mountBody("

One two three four.

"); - reply = { text: "TWO AND THREE", credits_charged: 1, tokens_used: 10 }; + reply = { text: "TWO AND THREE", charged_usd: 0.01, tokens_used: 10 }; await select(editor, 5, 14); // "two three" await rewrite(); expect(editor.getHTML()).toBe("

One TWO AND THREE four.

"); @@ -181,7 +181,7 @@ describe("Edit with AI in the campaign body", () => { it("brings a merge variable back as a chip, with the body value in step", async () => { const { editor, saved } = mountBody("

Hello there.

"); - reply = { text: "Hi {{.FirstName}}, quick one.", credits_charged: 1, tokens_used: 10 }; + reply = { text: "Hi {{.FirstName}}, quick one.", charged_usd: 0.01, tokens_used: 10 }; await select(editor, 1, editor.state.doc.content.size - 1); await rewrite(); expect(editor.getHTML()).toBe('

Hi {{.FirstName}}, quick one.

'); @@ -193,7 +193,7 @@ describe("Edit with AI in the campaign body", () => { it("keeps an AI block's configuration when the model echoes its token", async () => { const config = encodeConfig({ name: "opener", mode: "instant", prompt: "a warm opener", tone: "", web_search: false }); const { editor } = mountBody(`

Hi [[ai:abc]] there.

`); - reply = { text: "Hey [[ai:abc]] there.", credits_charged: 1, tokens_used: 10 }; + reply = { text: "Hey [[ai:abc]] there.", charged_usd: 0.01, tokens_used: 10 }; await select(editor, 1, editor.state.doc.content.size - 1); expect(sent).toBeNull(); await rewrite(); @@ -211,7 +211,7 @@ describe("Edit with AI in the campaign body", () => { it("says so when the model hands the passage back untouched", async () => { const { editor } = mountBody("

Already fine.

"); - reply = { text: "Already fine.", credits_charged: 1, tokens_used: 10 }; + reply = { text: "Already fine.", charged_usd: 0.01, tokens_used: 10 }; await select(editor, 1, editor.state.doc.content.size - 1); await rewrite("fix grammar"); await screen.findByText(/No change/, {}, { timeout: 5000 }); @@ -221,7 +221,7 @@ describe("Edit with AI in the campaign body", () => { it("gives back the space the selection ended on", async () => { const { editor } = mountBody("

One two three four.

"); // "two three " including the trailing space; the server trims its answer. - reply = { text: "TWO AND THREE", credits_charged: 1, tokens_used: 10 }; + reply = { text: "TWO AND THREE", charged_usd: 0.01, tokens_used: 10 }; await select(editor, 5, 15); await rewrite(); expect(editor.getHTML()).toBe("

One TWO AND THREE four.

"); @@ -229,7 +229,7 @@ describe("Edit with AI in the campaign body", () => { it("joins the paragraphs a selection ran across, without inventing a blank one", async () => { const { editor, saved } = mountBody("

One two

Three four.

"); - reply = { text: "TWO!", credits_charged: 1, tokens_used: 10 }; + reply = { text: "TWO!", charged_usd: 0.01, tokens_used: 10 }; await select(editor, 5, 10); // mid paragraph one to the start of paragraph two await rewrite(); expect(editor.getHTML()).toBe("

One TWO!Three four.

"); @@ -238,7 +238,7 @@ describe("Edit with AI in the campaign body", () => { it("discards the rewrite back to the body that was there", async () => { const { editor, saved } = mountBody("

Original one.

"); - reply = { text: "New one.", credits_charged: 1, tokens_used: 10 }; + reply = { text: "New one.", charged_usd: 0.01, tokens_used: 10 }; await select(editor, 1, editor.state.doc.content.size - 1); await rewrite(); await act(async () => { @@ -250,10 +250,10 @@ describe("Edit with AI in the campaign body", () => { it("discards with Escape, and a second change refines the rewrite rather than the original", async () => { const { editor, saved } = mountBody("

Original one.

"); - reply = { text: "New one.", credits_charged: 1, tokens_used: 10 }; + reply = { text: "New one.", charged_usd: 0.01, tokens_used: 10 }; await select(editor, 1, editor.state.doc.content.size - 1); await rewrite(); - reply = { text: "Newer.", credits_charged: 1, tokens_used: 10 }; + reply = { text: "Newer.", charged_usd: 0.01, tokens_used: 10 }; await act(async () => { fireEvent.click(screen.getByText("Make it shorter")); }); @@ -269,7 +269,7 @@ describe("Edit with AI in the campaign body", () => { it("keeps the rewrite as one undo step", async () => { const { editor } = mountBody("

Original one.

"); - reply = { text: "New one.", credits_charged: 1, tokens_used: 10 }; + reply = { text: "New one.", charged_usd: 0.01, tokens_used: 10 }; await select(editor, 1, editor.state.doc.content.size - 1); await rewrite(); await act(async () => { @@ -291,7 +291,7 @@ describe("Write with AI at the caret", () => { beforeEach(() => { captured = null; hold = false; - written = { text: "", credits_charged: 1, tokens_used: 10 }; + written = { text: "", charged_usd: 0.01, tokens_used: 10 }; }); async function writeAtCaret(editor: Editor, pos: number, instruction: string) { @@ -309,7 +309,7 @@ describe("Write with AI at the caret", () => { it("extends the sentence it was asked to write into", async () => { const { editor, saved } = mountBody("

One four.

"); - written = { text: "two three", credits_charged: 1, tokens_used: 10 }; + written = { text: "two three", charged_usd: 0.01, tokens_used: 10 }; await writeAtCaret(editor, 5, "add the middle"); expect(editor.getHTML()).toBe("

One two threefour.

"); expect(saved.html).toBe(editor.getHTML()); @@ -317,7 +317,7 @@ describe("Write with AI at the caret", () => { it("leaves the caret after what it wrote, not in front of it", async () => { const { editor } = mountBody("

One four.

"); - written = { text: "two three ", credits_charged: 1, tokens_used: 10 }; + written = { text: "two three ", charged_usd: 0.01, tokens_used: 10 }; await writeAtCaret(editor, 5, "add the middle"); expect(editor.getHTML()).toBe("

One two three four.

"); // Continuing to type has to continue the sentence, which it cannot do @@ -328,7 +328,7 @@ describe("Write with AI at the caret", () => { it("lands the merge variable it was told to use as a chip", async () => { const { editor } = mountBody("

Hello.

"); - written = { text: "Hi {{.FirstName}}.", credits_charged: 1, tokens_used: 10 }; + written = { text: "Hi {{.FirstName}}.", charged_usd: 0.01, tokens_used: 10 }; await writeAtCaret(editor, 1, "greet them"); expect(editor.getHTML()).toBe('

Hi {{.FirstName}}.Hello.

'); }); @@ -336,7 +336,7 @@ describe("Write with AI at the caret", () => { it("shows the words as they arrive, and Escape stops it keeping what was written", async () => { hold = true; const { editor, saved } = mountBody("

Hello.

"); - written = { text: "Quick note for you. ", credits_charged: 1, tokens_used: 10 }; + written = { text: "Quick note for you. ", charged_usd: 0.01, tokens_used: 10 }; await act(async () => { editor.commands.setTextSelection(1); fireEvent.keyDown(editor.view.dom, { key: "j", metaKey: true }); diff --git a/web/src/components/app/ai/textareaAIEdit.test.tsx b/web/src/components/app/ai/textareaAIEdit.test.tsx index fff6af52a..a53cd542c 100644 --- a/web/src/components/app/ai/textareaAIEdit.test.tsx +++ b/web/src/components/app/ai/textareaAIEdit.test.tsx @@ -8,7 +8,7 @@ import { describe, it, expect, vi, beforeEach } from "vitest"; import { render, screen, act, fireEvent, waitFor } from "@testing-library/react"; import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; -let reply = { text: "", credits_charged: 1, tokens_used: 10 }; +let reply = { text: "", charged_usd: 0.01, tokens_used: 10 }; let sent: { text: string; instruction: string } | null = null; vi.mock("@/lib/api/hooks/app/generation/useGenerateEdit", () => ({ default: () => ({ @@ -57,7 +57,7 @@ function Host({ initial, max = MAX }: { initial: string; max?: number }) { describe("TextareaAIEdit against the composer's length cap", () => { beforeEach(() => { - reply = { text: "", credits_charged: 1, tokens_used: 10 }; + reply = { text: "", charged_usd: 0.01, tokens_used: 10 }; sent = null; }); @@ -76,7 +76,7 @@ describe("TextareaAIEdit against the composer's length cap", () => { ta.setSelectionRange(4, 7); document.dispatchEvent(new Event("selectionchange")); }); - reply = { text: "TWO IS MUCH LONGER", credits_charged: 1, tokens_used: 10 }; + reply = { text: "TWO IS MUCH LONGER", charged_usd: 0.01, tokens_used: 10 }; await act(async () => { fireEvent.mouseDown(await screen.findByText("Edit with AI")); }); @@ -115,7 +115,7 @@ describe("TextareaAIEdit against the composer's length cap", () => { document.dispatchEvent(new Event("selectionchange")); }); // Everything this adds lands past the cap, so the body cannot move. - reply = { text: "fg extra", credits_charged: 1, tokens_used: 10 }; + reply = { text: "fg extra", charged_usd: 0.01, tokens_used: 10 }; await act(async () => { fireEvent.mouseDown(await screen.findByText("Edit with AI")); }); @@ -154,7 +154,7 @@ describe("TextareaAIEdit against the composer's length cap", () => { ta.setSelectionRange(4, 7); document.dispatchEvent(new Event("selectionchange")); }); - reply = { text: "TWO IS MUCH LONGER", credits_charged: 1, tokens_used: 10 }; + reply = { text: "TWO IS MUCH LONGER", charged_usd: 0.01, tokens_used: 10 }; await act(async () => { fireEvent.mouseDown(await screen.findByText("Edit with AI")); }); diff --git a/web/src/components/app/ai/usage.ts b/web/src/components/app/ai/usage.ts index 2dea6659d..11e8711b0 100644 --- a/web/src/components/app/ai/usage.ts +++ b/web/src/components/app/ai/usage.ts @@ -1,9 +1,11 @@ +import { fmtUsdCost } from "@/lib/money"; + // formatUsage renders what an AI call actually cost, from the usage-based -// settle: "2 credits · 1.4k tok". Empty on unmetered (local model) setups so -// the UI shows nothing instead of "0 credits". -export default function formatUsage(charged: number, tokens: number): string { - if (charged <= 0) return ""; +// settle: "$0.0094 · 1.4k tok". Empty on unmetered (local model) setups so +// the UI shows nothing instead of "$0.00". +export default function formatUsage(chargedUsd: number | null | undefined, tokens: number): string { + if (!chargedUsd || chargedUsd <= 0) return ""; const t = tokens >= 1000 ? `${(tokens / 1000).toFixed(1)}k` : String(tokens); - const credits = `${charged} credit${charged === 1 ? "" : "s"}`; - return tokens > 0 ? `${credits} · ${t} tok` : credits; + const cost = fmtUsdCost(chargedUsd); + return tokens > 0 ? `${cost} · ${t} tok` : cost; } diff --git a/web/src/components/app/ai/useEditorAIRun.ts b/web/src/components/app/ai/useEditorAIRun.ts index 711af2d90..ae18bcfb3 100644 --- a/web/src/components/app/ai/useEditorAIRun.ts +++ b/web/src/components/app/ai/useEditorAIRun.ts @@ -29,7 +29,7 @@ export interface EditorAIRunSpec { export interface EditorAIRun { phase: EditorAIPhase; - usage: { charged: number; tokens: number } | null; + usage: { chargedUsd: number; tokens: number } | null; // Words in the passage under review, and whether the last run changed it. words: number; changed: boolean; @@ -140,7 +140,7 @@ export default function useEditorAIRun(editor: Editor, onSettle?: () => void): E .then((res) => { if (runId.current !== id) return; editor.setEditable(true, false); - setUsage({ charged: res.credits_charged ?? 0, tokens: res.tokens_used ?? 0 }); + setUsage({ chargedUsd: res.charged_usd ?? 0, tokens: res.tokens_used ?? 0 }); land(shape(spec, res.text)); }) .catch((e) => { diff --git a/web/src/components/app/analytics/DirectMailSection.tsx b/web/src/components/app/analytics/DirectMailSection.tsx index 4b84aa403..03effade3 100644 --- a/web/src/components/app/analytics/DirectMailSection.tsx +++ b/web/src/components/app/analytics/DirectMailSection.tsx @@ -16,7 +16,7 @@ import { EyeIcon, InboxIcon, MailIcon, ReplyIcon } from "lucide-react"; import { EmptyBlock, SectionBar, Stat, StatStrip } from "@/components/layout/Page"; import { MultiTrend, type TrendSeries } from "@/components/ui/charts"; -import { utcDay } from "@/lib/campaignPeriod"; +import { periodWindow, utcDay, type CampaignPeriodPreset } from "@/lib/campaignPeriod"; import useDirectMail from "@/lib/api/hooks/app/analytics/useDirectMail"; import type DirectMailAnalytics from "@/lib/api/models/app/analytics/DirectMailAnalytics"; @@ -52,7 +52,7 @@ function SkeletonRows({ rows = 3 }: { rows?: number }) { } // unfiltered marks the section while the page is narrowed to campaigns: direct mail belongs to none. -export default function DirectMailSection({ period, unfiltered = false }: { period: string; unfiltered?: boolean }) { +export default function DirectMailSection({ period, unfiltered = false }: { period: CampaignPeriodPreset; unfiltered?: boolean }) { const q = useDirectMail(period); const d: DirectMailAnalytics | undefined = q.data; const vol = d?.volume; @@ -124,6 +124,7 @@ export default function DirectMailSection({ period, unfiltered = false }: { peri diff --git a/web/src/components/app/automations/AutomationEditors.tsx b/web/src/components/app/automations/AutomationEditors.tsx index 7ebc9f82c..4aec7db6f 100644 --- a/web/src/components/app/automations/AutomationEditors.tsx +++ b/web/src/components/app/automations/AutomationEditors.tsx @@ -53,6 +53,8 @@ import { useAutomations } from "@/lib/api/hooks/app/automations/useAutomations"; import { useUserProfile } from "@/hooks/context/user"; import { actionGlyph, defaultConfigForAction } from "./automationActions"; import { cn } from "@/lib/utils"; +import { fmtUsdAbout } from "@/lib/money"; +import { AI_ESTIMATE_USD } from "@/lib/aiEstimates"; // InboundUrlField shows the automation's unique inbound-webhook URL (read-only) // with a copy button. The stored value is a path; we prefix the API origin so @@ -177,7 +179,7 @@ export function ConditionEditor({ )}

AI reads the event data and answers your question: yes follows the Yes branch, no follows No. If AI - can't answer, the No branch runs. Costs 1 credit each time this branch is evaluated. + can't answer, the No branch runs. Costs {fmtUsdAbout(AI_ESTIMATE_USD.aiNode)} each time this branch is evaluated.

) : isExpression ? ( @@ -1070,7 +1072,7 @@ function AIClassifyFields({ defaultName="ai_class" />

- The model picks exactly one label. Add at least two. Costs 1 credit each time it runs. + The model picks exactly one label. Add at least two. Costs {fmtUsdAbout(AI_ESTIMATE_USD.aiNode)} each time it runs.

); @@ -1101,7 +1103,7 @@ function AIExtractFields({ addLabel="Add key" />

- Each key becomes a variable ( {`{{.company_size}}`} ). A field the model can't find is empty. Costs 1 credit. + Each key becomes a variable ( {`{{.company_size}}`} ). A field the model can't find is empty. Costs {fmtUsdAbout(AI_ESTIMATE_USD.aiNode)}.

); @@ -1129,7 +1131,7 @@ function AIGenerateFields({ defaultName="ai_text" />

- The result is stored, not sent. Use it in a later step (a Slack message, a task). Costs 1 credit. + The result is stored, not sent. Use it in a later step (a Slack message, a task). Costs {fmtUsdAbout(AI_ESTIMATE_USD.aiNode)}.

); @@ -1377,8 +1379,8 @@ function AIAgentFields({ )}

The agent decides which of these to use for each event, writes any task or deal details itself, and - can chain several. It only takes these reversible actions — it never sends or replies. Billed 1 - credit per step it takes. + can chain several. It only takes these reversible actions and never sends or replies. Each step it + takes is charged to the workspace balance by what it uses, usually {fmtUsdAbout(AI_ESTIMATE_USD.agentIteration)}.

@@ -1404,7 +1406,7 @@ function AISwitchFields({
{( [ - { ai: true, Icon: SparklesIcon, title: "AI prompt", detail: "A model reads the event and picks a case. 1 credit." }, + { ai: true, Icon: SparklesIcon, title: "AI prompt", detail: `A model reads the event and picks a case. ${fmtUsdAbout(AI_ESTIMATE_USD.aiNode)}.` }, { ai: false, Icon: BracesIcon, title: "Value", detail: "A field or template is matched to the cases. Free." }, ] as const ).map(({ ai, Icon, title, detail }) => { @@ -1444,7 +1446,7 @@ function AISwitchFields({
patchConfig({ web_search: !config.web_search })} /> @@ -1464,7 +1466,7 @@ function AISwitchFields({

Rendered against the event and matched to the case names. Matching ignores casing and extra spaces; wrap a case in slashes for a regex, e.g. /^(vip|enterprise)/. - First match wins. No model call, no credits. + First match wins. No model call, no charge.

)} diff --git a/web/src/components/app/automations/ExpressionReference.tsx b/web/src/components/app/automations/ExpressionReference.tsx index a365fd240..4019b71f2 100644 --- a/web/src/components/app/automations/ExpressionReference.tsx +++ b/web/src/components/app/automations/ExpressionReference.tsx @@ -26,7 +26,7 @@ const SECTIONS: Section[] = [ title: "Variables", blurb: "Email: dotted PascalCase. Automations: the event key with a leading dot ({{.key}}).", entries: [ - { code: "{{.FirstName}}", label: "Contact field (email)", note: "Standard: .FirstName .LastName .Email .Company .Phone. Lowercase {{.firstname}} does NOT work for email merge fields." }, + { code: "{{.FirstName}}", label: "Contact field (email)", note: "Standard: .FirstName .LastName .Email .Company .Phone. Campaign email also accepts first_name, firstName and firstname spellings." }, { code: "{{.role}}", label: "Custom field by key", note: "Any key works, including names with spaces or dashes (e.g. {{.job title}}), in {{if}} and helpers too." }, { code: "{{.contact_email}}", label: "Automation event variable", note: "Standard dotted field access — the leading dot is required. Unknown keys render empty." }, { code: "{{.confidence}}", label: "Reply confidence (reply trigger)", note: "Stays numeric in both conditions and action values, so native gt/lt/eq work. Use gtf only when a value might arrive as text." }, diff --git a/web/src/components/app/automations/automationActions.tsx b/web/src/components/app/automations/automationActions.tsx index 44c5a138e..d78f4485b 100644 --- a/web/src/components/app/automations/automationActions.tsx +++ b/web/src/components/app/automations/automationActions.tsx @@ -19,6 +19,8 @@ import { } from "lucide-react"; import { triggerVariables } from "@/lib/api/models/app/automations/meta"; import { cn } from "@/lib/utils"; +import { fmtUsdAbout } from "@/lib/money"; +import { AI_ESTIMATE_USD } from "@/lib/aiEstimates"; // Fresh config for a newly-created action node: agent mode for the AI step, two // starter cases for the AI switch (so its case branches show at once), else empty. @@ -54,8 +56,8 @@ export const ACTION_VISUAL: Record, tone: "amber", kicker: "If / else", title: conditionLabel(c), summary: kind }; } if (n.type === "stop") return { icon: , tone: "rose", kicker: "End", title: "End", summary: "" }; @@ -117,12 +119,12 @@ export function stepView(n: AutomationNode, ctx: StepContext): StepView { tone: "purple", kicker: value ? "Value switch" : "AI switch", title: value ? `Match ${clip(String(cfg.switch_value ?? "").trim() || "a value", 32)}` : clip(instruction) || "New AI switch", - summary: `${plural(cases, "case")}${value ? "" : " · 1 credit"}`, + summary: `${plural(cases, "case")}${value ? "" : ` · ${fmtUsdAbout(AI_ESTIMATE_USD.aiNode)}`}`, }; } if (isAIAction(action)) { const mode = AI_MODES[String(cfg.mode ?? "agent")] ?? "Agent"; - return { icon: , tone: "purple", kicker: "AI step", title: clip(instruction) || "New AI step", summary: `${mode} · billed in credits` }; + return { icon: , tone: "purple", kicker: "AI step", title: clip(instruction) || "New AI step", summary: `${mode} · charged by usage` }; } if (isNativeAction(action)) { return { icon: actionIcon(action), tone: actionTone(action), kicker: "Action", title: actionLabel(action), summary: nativeSummary(action, cfg, ctx) }; diff --git a/web/src/components/app/billing/BalanceBanner.tsx b/web/src/components/app/billing/BalanceBanner.tsx new file mode 100644 index 000000000..74de544b2 --- /dev/null +++ b/web/src/components/app/billing/BalanceBanner.tsx @@ -0,0 +1,95 @@ +// A strip above the header when the balance is used up or running low and +// automatic reload will not refill it. Billing managers only; dismissed per +// workspace, state and cycle; hidden on the billing page, which says the same. +// Only on a paid plan, the only kind that can add money. + +import React from "react"; +import { Link, useRouterState } from "@tanstack/react-router"; +import { WalletIcon, XIcon } from "lucide-react"; +import { usePermission } from "@/hooks/usePermission"; +import useFeatureAccess from "@/hooks/useFeatureAccess"; +import { useBalance } from "@/lib/api/hooks/app/subscription/useBalance"; +import { fmtUsd } from "@/lib/money"; +import { cn } from "@/lib/utils"; +import { useAppStore } from "@/stores"; +import { balanceBanner } from "./balanceModel"; + +function wasDismissed(key: string) { + try { + return localStorage.getItem(key) === "1"; + } catch { + return false; + } +} + +export default function BalanceBanner() { + const canManage = usePermission("MANAGE_BILLING"); + // Money can be added on a paid plan only; a banner nobody can act on is noise. + const { billing, paid } = useFeatureAccess(); + const metered = billing && paid; + const orgId = useAppStore((s) => s.currentOrganization?.id); + const onBilling = useRouterState({ select: (s) => s.location.pathname.startsWith("/app/settings/billing") }); + const { data: b } = useBalance(canManage && metered); + const [dismissed, setDismissed] = React.useState(null); + + const kind = canManage && metered && b?.can_add_money !== false ? balanceBanner(b) : null; + if (!kind || !b || onBilling) return null; + const period = b.next_reset_at ? new Date(b.next_reset_at).toISOString().slice(0, 10) : new Date().toISOString().slice(0, 7); + const key = `warmbly.balance-banner:${orgId}:${kind}:${period}`; + if (dismissed === key || wasDismissed(key)) return null; + + const ar = b.auto_reload; + const dismiss = () => { + setDismissed(key); + try { + localStorage.setItem(key, "1"); + } catch { + /* private mode: hidden until reload */ + } + }; + const out = kind === "out"; + + return ( +
+ +

+ {out ? "The balance is used up." : "The balance is running low."}{" "} + {out ? "AI features are paused until money is added." : `${fmtUsd(b.balance_usd)} left. AI features pause when it runs out.`} + {ar?.failure_code && !ar.enabled ? " Automatic reload turned off after a failed payment." : ""} +

+
+ + Add money + + {ar && ( + + {ar.enabled ? "Reload settings" : "Turn on automatic reload"} + + )} + +
+
+ ); +} diff --git a/web/src/components/app/billing/InsufficientBalanceDialog.tsx b/web/src/components/app/billing/InsufficientBalanceDialog.tsx new file mode 100644 index 000000000..72569c3e3 --- /dev/null +++ b/web/src/components/app/billing/InsufficientBalanceDialog.tsx @@ -0,0 +1,169 @@ +// The app-wide answer to a 402 for a balance that ran out: what is left, and +// a way to add money right here (one click on the saved card, otherwise Stripe +// Checkout). A member who cannot manage billing is told who can. + +import React from "react"; +import { AnimatePresence, motion } from "framer-motion"; +import { Link } from "@tanstack/react-router"; +import { CreditCardIcon, Loader2Icon, WalletIcon, XIcon } from "lucide-react"; +import { usePermission } from "@/hooks/usePermission"; +import useFeatureAccess from "@/hooks/useFeatureAccess"; +import { useUpgradeDialog } from "@/hooks/context/upgrade"; +import { useBalance, useBalanceCheckout, useTopUp } from "@/lib/api/hooks/app/subscription/useBalance"; +import { onInsufficientBalance } from "@/lib/insufficientBalance"; +import { DEFAULT_TOP_UP_USD, fmtUsd, fmtUsdTrim } from "@/lib/money"; +import { fmtDay, paymentMethodLabel } from "./balanceModel"; + +export default function InsufficientBalanceDialog() { + const [open, setOpen] = React.useState(false); + React.useEffect(() => onInsufficientBalance(() => setOpen(true)), []); + return {open && setOpen(false)} />}; +} + +function DialogBody({ onClose }: { onClose: () => void }) { + const canManage = usePermission("MANAGE_BILLING"); + const access = useFeatureAccess(); + const upgrade = useUpgradeDialog(); + const balance = useBalance(canManage && access.billing); + const pay = useTopUp(); + const checkout = useBalanceCheckout(); + const b = balance.data; + const canBuy = canManage && access.billing && (b?.can_add_money ?? access.paid); + const amount = b?.top_up?.default_usd ?? DEFAULT_TOP_UP_USD; + const pm = b?.payment_method ?? null; + const busy = pay.isPending || checkout.isPending; + + React.useEffect(() => { + const onKey = (e: KeyboardEvent) => { + if (e.key !== "Escape") return; + // The confirm dialog or the reauth prompt on top takes Escape first. + if (document.querySelector('[role="alertdialog"]')) return; + onClose(); + }; + document.addEventListener("keydown", onKey); + return () => document.removeEventListener("keydown", onKey); + }, [onClose]); + + const addMoney = () => { + if (pm) pay.mutate(amount, { onSuccess: (r) => r && onClose() }); + else checkout.mutate(amount); + }; + + const body = !b + ? "There isn't enough left on the workspace balance for this." + : `${fmtUsd(b.balance_usd)} is left, not enough for this.${ + b.next_reset_at && b.monthly_allowance_usd > 0 ? ` The included usage resets ${fmtDay(b.next_reset_at)}.` : "" + }`; + + return ( + { + if (e.target === e.currentTarget && !busy) onClose(); + }} + > + +
+
+ +
+ Balance +
+ + The balance is too low + + +
+ +
+

{body}

+ {canBuy ? ( +

+ Add money to keep going now. It never expires. + {!b?.auto_reload?.enabled && " Automatic reload can keep this from happening again."} +

+ ) : canManage && access.billing ? ( +

Adding money needs an active paid plan.

+ ) : ( +

+ Ask the workspace owner or a billing admin to add money. +

+ )} +
+ +
+ {canBuy ? ( + <> + + Other amounts + + + + ) : canManage && access.billing ? ( + <> + + + + ) : ( + + )} +
+ + + ); +} diff --git a/web/src/components/app/billing/TopUpPanel.tsx b/web/src/components/app/billing/TopUpPanel.tsx new file mode 100644 index 000000000..292fcd039 --- /dev/null +++ b/web/src/components/app/billing/TopUpPanel.tsx @@ -0,0 +1,150 @@ +// Add money: a few presets or a typed amount. With a saved card it is paid in +// place after one confirm; without one, or when the bank wants to confirm, it +// carries on in Stripe Checkout. + +import React from "react"; +import { CreditCardIcon, Loader2Icon } from "lucide-react"; +import { useConfirm } from "@/hooks/context/confirm"; +import { TextInput } from "@/components/ui/field"; +import { useBalanceCheckout, useTopUp } from "@/lib/api/hooks/app/subscription/useBalance"; +import type { Balance } from "@/lib/api/models/app/subscription/Credits"; +import { DEFAULT_TOP_UP_USD, MAX_TOP_UP_USD, MIN_TOP_UP_USD, TOP_UP_PRESETS, fmtUsd, fmtUsdTrim, parseUsd, validTopUp } from "@/lib/money"; +import { cn } from "@/lib/utils"; +import { paymentMethodLabel } from "./balanceModel"; + +type Choice = number | "custom"; + +export default function TopUpPanel({ balance, canBuy }: { balance: Balance; canBuy: boolean }) { + const confirm = useConfirm(); + const pay = useTopUp(); + const checkout = useBalanceCheckout(); + const presets = balance.top_up?.presets_usd?.length ? balance.top_up.presets_usd : [...TOP_UP_PRESETS]; + const initial = balance.top_up?.default_usd ?? DEFAULT_TOP_UP_USD; + const [choice, setChoice] = React.useState(presets.includes(initial) ? initial : "custom"); + const [custom, setCustom] = React.useState(presets.includes(initial) ? "" : String(initial)); + + const pm = balance.payment_method ?? null; + const usd = choice === "custom" ? parseUsd(custom) : choice; + const valid = validTopUp(usd); + const typedWrong = choice === "custom" && custom.trim() !== "" && !valid; + const inFlight = !!balance.charge_in_progress; + const busy = pay.isPending || checkout.isPending; + const disabled = !canBuy || !valid || busy || inFlight; + + const buy = () => { + if (disabled) return; + if (!pm) { + checkout.mutate(usd); + return; + } + confirm.show( + `Charge ${fmtUsd(usd)} to ${paymentMethodLabel(pm)} now? It goes on the workspace balance and never expires.`, + // The hook reports a failure itself; the dialog just closes. + () => pay.mutateAsync(usd).then(() => undefined, () => undefined), + undefined, + { title: `Add ${fmtUsd(usd)} to the balance?`, confirmLabel: `Pay ${fmtUsd(usd)}`, tone: "primary" }, + ); + }; + + const summary = !canBuy + ? "Adding money needs an active paid plan." + : inFlight + ? "A payment is still going through. This updates when it lands." + : typedWrong + ? `Enter an amount from ${fmtUsdTrim(MIN_TOP_UP_USD)} to ${fmtUsdTrim(MAX_TOP_UP_USD)}.` + : valid + ? `Adds ${fmtUsd(usd)} to the balance.` + : "Enter an amount."; + + return ( +
+
+
Add money
+
Dollar for dollar. Never expires.
+
+
+ {presets.map((v) => ( + setChoice(v)}> + {fmtUsdTrim(v)} + + ))} + setChoice("custom")}> + Other + + {choice === "custom" && ( +
+ $ + setCustom(v.replace(/[^\d.,$\s]/g, ""))} + onKeyDown={(e) => { + if (e.key === "Enter") buy(); + }} + placeholder={String(DEFAULT_TOP_UP_USD)} + invalid={typedWrong} + title="Amount in US dollars" + className="w-[112px] pl-5 tabular-nums" + /> +
+ )} +
+
+

+ {summary} +

+
+ {pm && ( + + )} + +
+
+ {pm && ( +

Charged to {paymentMethodLabel(pm)}

+ )} +
+ ); +} + +function Chip({ active, onClick, children }: { active: boolean; onClick: () => void; children: React.ReactNode }) { + return ( + + ); +} diff --git a/web/src/components/app/billing/UsdStepper.tsx b/web/src/components/app/billing/UsdStepper.tsx new file mode 100644 index 000000000..86fe8185f --- /dev/null +++ b/web/src/components/app/billing/UsdStepper.tsx @@ -0,0 +1,111 @@ +// A dollar field with themed steppers. Typing is free until the field is left +// (or Enter), then the amount is parsed and clamped, so mutually bounded fields +// never fight mid-keystroke the way a per-keystroke clamp does. + +import React from "react"; +import { ChevronDownIcon, ChevronUpIcon } from "lucide-react"; +import { parseUsd, roundCents } from "@/lib/money"; +import { cn } from "@/lib/utils"; + +const show = (n: number) => (Number.isInteger(n) ? String(n) : n.toFixed(2)); + +export default function UsdStepper({ + value, + onCommit, + min, + max, + step = 1, + disabled, + ariaLabel, + className, +}: { + value: number; + onCommit: (n: number) => void; + min: number; + max: number; + step?: number; + disabled?: boolean; + ariaLabel: string; + className?: string; +}) { + const [text, setText] = React.useState(show(value)); + const [focused, setFocused] = React.useState(false); + React.useEffect(() => { + if (!focused) setText(show(value)); + }, [value, focused]); + + const clamp = (n: number) => roundCents(Math.min(max, Math.max(min, n))); + const commit = (n: number | null) => { + const next = n === null ? value : clamp(n); + setText(show(next)); + if (next !== value) onCommit(next); + }; + // A step lands on the step grid, so $5.50 + $5 goes to $10, not $10.50. + const bump = (dir: 1 | -1) => { + if (disabled) return; + const base = dir === 1 ? Math.floor(value / step) * step + step : Math.ceil(value / step) * step - step; + commit(base); + }; + + return ( +
+ $ + { + setFocused(true); + e.currentTarget.select(); + }} + onChange={(e) => setText(e.target.value.replace(/[^\d.,$\s]/g, ""))} + onBlur={() => { + setFocused(false); + commit(parseUsd(text)); + }} + onKeyDown={(e) => { + if (e.key === "Enter") e.currentTarget.blur(); + if (e.key === "ArrowUp") { + e.preventDefault(); + bump(1); + } + if (e.key === "ArrowDown") { + e.preventDefault(); + bump(-1); + } + }} + className="w-full min-w-0 h-full bg-transparent outline-none pl-1 pr-2 text-[16px] md:text-[12.5px] text-slate-900 tabular-nums disabled:text-slate-400" + /> +
+ + +
+
+ ); +} diff --git a/web/src/components/app/billing/WarmupPlanDialog.tsx b/web/src/components/app/billing/WarmupPlanDialog.tsx deleted file mode 100644 index a462c2439..000000000 --- a/web/src/components/app/billing/WarmupPlanDialog.tsx +++ /dev/null @@ -1,296 +0,0 @@ -// The warmup plan checkout: the premium pool, with no mailbox cap, for a -// workspace that only warms. A customer arrives here from the mailboxes page, -// the billing overview, or the Upgrade button on a linked self-hosted -// instance, so they have already chosen: this confirms what they are buying, -// which workspace it applies to, and how often they are billed. -// -// The plan is not in the public plan list, so it has no card in the plans grid -// and its price comes from /pool-link/offer rather than the static catalog. -// The layout is the same anatomy as a PlanCard in the chooser (name, blurb, -// price, bullets) so it reads as one more plan, not a promotion. - -import React from "react"; -import { createPortal } from "react-dom"; -import { AnimatePresence, motion } from "framer-motion"; -import toast from "react-hot-toast/headless"; -import { ArrowRightIcon, CheckIcon, Loader2Icon, MinusIcon, XIcon } from "lucide-react"; -import { useAppStore } from "@/stores"; -import { usePoolLinkInstances, usePoolLinkOffer, useStartPoolLinkCheckout } from "@/lib/api/hooks/app/cloudlink/useCloudLink"; -import type { AppError } from "@/lib/api/client/normalizeError"; -import buildError from "@/lib/helper/buildError"; -import BillingIntervalToggle from "@/components/app/billing/BillingIntervalToggle"; -import { DitherMeter } from "@/components/ui/dither"; -import { PLAN_ACCENT_CLASSES, WARMUP_PLAN_BENEFITS, WARMUP_PLAN_PITCH, getPlan } from "@/lib/plans"; - -type Interval = "month" | "year"; - -// Free against Premium, row by row. Each cell is a rule the pool enforces. -const COMPARISON: { label: string; free: string | false; premium: string | true }[] = [ - { label: "Warmup pool", free: "Free pool", premium: "Premium pool" }, - { label: "Partner matching", free: "After Premium", premium: "First" }, - { label: "Mailboxes", free: "10", premium: "No limit" }, - { label: "Spam-prone partners removed", free: "Yes", premium: true }, - { label: "Replies and spam rescue", free: "Yes", premium: true }, -]; - -export default function WarmupPlanDialog({ open, onClose }: { open: boolean; onClose: () => void }) { - const orgName = useAppStore((s) => s.currentOrganization?.name); - const offer = usePoolLinkOffer(open); - // The workspace's own allowance, so the right column shows why to upgrade - // rather than a made-up chart. Hidden when it cannot be read. - const instances = usePoolLinkInstances(open); - const allowance = instances.data?.plan; - const checkout = useStartPoolLinkCheckout(); - const [interval, setInterval] = React.useState("year"); - - // Yearly is the better default, but only where it exists. Applied once per - // opening: a background refetch must not move the choice under someone who - // has already picked the other period. - const defaulted = React.useRef(false); - React.useEffect(() => { - if (!open) { - defaulted.current = false; - return; - } - if (defaulted.current || !offer.data) return; - defaulted.current = true; - setInterval(offer.data.yearly_available ? "year" : "month"); - }, [open, offer.data]); - - const cardRef = React.useRef(null); - React.useEffect(() => { - if (!open) return; - const previous = document.activeElement as HTMLElement | null; - cardRef.current?.focus(); - const onKey = (e: KeyboardEvent) => { - if (e.key === "Escape" && !checkout.isPending) { - e.stopPropagation(); - onClose(); - } - }; - document.addEventListener("keydown", onKey, true); - return () => { - document.removeEventListener("keydown", onKey, true); - previous?.focus?.(); - }; - }, [open, checkout.isPending, onClose]); - - const data = offer.data; - const available = data?.available === true; - const monthly = data?.monthly_usd ?? 0; - const yearly = data?.yearly_usd ?? 0; - const annual = interval === "year" && data?.yearly_available === true; - // Only worth showing when it is actually a saving. - const yearlySaving = monthly > 0 && yearly > 0 ? Math.max(0, monthly * 12 - yearly) : 0; - const accent = PLAN_ACCENT_CLASSES[getPlan("warmup").accent]; - - async function start() { - if (checkout.isPending || !available) return; - try { - const res = await checkout.mutateAsync(interval); - if (!res.checkout_url) throw new Error("no checkout url"); - window.location.href = res.checkout_url; - } catch (e) { - toast.error(buildError(e as AppError)); - } - } - - return createPortal( - - {open && ( - { - if (e.target === e.currentTarget && !checkout.isPending) onClose(); - }} - className="fixed inset-0 z-[160] flex items-center justify-center bg-slate-900/40 backdrop-blur-[2px] px-4" - > - e.stopPropagation()} - className="w-full max-w-[720px] max-h-[calc(100dvh-3rem)] overflow-y-auto rounded-lg bg-white border border-slate-200 shadow-[0_24px_48px_-12px_rgba(15,23,42,0.18)]" - > -
- Warmup plan -
- - Premium warmup pool - - -
- -
- {/* Left: the plan, in the chooser's anatomy. */} -
-
- Premium - {!offer.isLoading && available && data?.yearly_available && data?.monthly_available && ( -
- setInterval(i === "annual" ? "year" : "month")} - /> -
- )} -
-

{WARMUP_PLAN_PITCH}

- -
- {offer.isLoading ? ( - - ) : ( - <> - - ${annual ? Math.round(yearly / 12) : monthly} - - / mo - - )} -
-
- {annual ? ( - <> - billed ${yearly} annually - {yearlySaving > 0 && ( - - save ${yearlySaving} / yr - - )} - - ) : ( - "billed monthly" - )} -
- -
    - {WARMUP_PLAN_BENEFITS.map((b) => ( -
  • -
  • - ))} -
- - {!offer.isLoading && !available && ( -
-

- {offer.isError - ? "The price could not be loaded. Try again in a moment." - : "This instance has no price set for the warmup plan yet, so it cannot be bought here."} -

-
- )} - -

- Applies to {orgName || "this workspace"} and any instance - linked to it. Billed through Stripe. Cancel anytime. -

-
- - {/* Right: where this workspace stands, and what changes. */} - -
- -
- - -
- - - )} - , - document.body, - ); -} diff --git a/web/src/components/app/billing/balanceModel.ts b/web/src/components/app/billing/balanceModel.ts new file mode 100644 index 000000000..18109e35a --- /dev/null +++ b/web/src/components/app/billing/balanceModel.ts @@ -0,0 +1,117 @@ +// Shared rules for the balance surfaces: when to warn, and how to name a card. + +import type { AutoReload, Balance, PaymentMethod } from "@/lib/api/models/app/subscription/Credits"; +import { MIN_TOP_UP_USD, OUT_OF_BALANCE_BELOW, roundCents } from "@/lib/money"; + +export type BalanceAlert = "out" | "low"; + +/** Out (AI paused) or running low; null when there is nothing to say. */ +export function balanceAlert(b: Balance | null | undefined): BalanceAlert | null { + if (!b || b.unlimited) return null; + if (b.balance_usd < OUT_OF_BALANCE_BELOW) return "out"; + const lowAt = b.auto_reload?.enabled ? b.auto_reload.threshold_usd : (b.low_balance_usd ?? 0); + return b.balance_usd < lowAt ? "low" : null; +} + +/** Automatic reload is on, has a card and room left this month, so a low balance refills itself. */ +export function reloadCovers(b: Balance | null | undefined): boolean { + const ar = b?.auto_reload; + if (!ar?.enabled || !b?.payment_method) return false; + return roundCents(ar.monthly_limit_usd - ar.reloaded_this_month_usd) >= MIN_TOP_UP_USD; +} + +/** The app-wide banner: out or low, and automatic reload will not refill it. */ +export function balanceBanner(b: Balance | null | undefined): BalanceAlert | null { + const alert = balanceAlert(b); + if (!alert || reloadCovers(b)) return null; + return alert; +} + +const BRANDS: Record = { + visa: "Visa", + mastercard: "Mastercard", + amex: "American Express", + discover: "Discover", + diners: "Diners Club", + jcb: "JCB", + unionpay: "UnionPay", + cartes_bancaires: "Cartes Bancaires", + link: "Link", + sepa_debit: "SEPA Direct Debit", + us_bank_account: "Bank account", +}; + +const WALLETS: Record = { apple_pay: "Apple Pay", google_pay: "Google Pay", link: "Link" }; + +/** "Visa •••• 4242", "Apple Pay (Visa •••• 4242)". */ +export function paymentMethodLabel(pm: PaymentMethod): string { + const brand = BRANDS[pm.brand] ?? pm.brand.replace(/_/g, " ").replace(/^./, (c) => c.toUpperCase()); + const card = pm.last4 ? `${brand} •••• ${pm.last4}` : brand; + const wallet = pm.wallet ? WALLETS[pm.wallet] : undefined; + return wallet ? `${wallet} (${card})` : card; +} + +/** "08/30", or null when it does not expire. */ +export function paymentMethodExpiry(pm: PaymentMethod): string | null { + if (!pm.exp_month || !pm.exp_year) return null; + return `${String(pm.exp_month).padStart(2, "0")}/${String(pm.exp_year % 100).padStart(2, "0")}`; +} + +/** Expires before the end of next month: worth replacing before a reload fails. */ +export function expiresSoon(pm: PaymentMethod, now = new Date()): boolean { + if (!pm.exp_month || !pm.exp_year) return false; + const months = (pm.exp_year - now.getFullYear()) * 12 + (pm.exp_month - (now.getMonth() + 1)); + return months <= 1; +} + +export const RELOAD_FAILURE_COPY: Record, string> = { + card_declined: "The card was declined, so nothing was charged. Update the card, then turn it back on.", + authentication_required: "The bank asked to confirm the payment, which can't happen automatically. Use another card, then turn it back on.", + no_payment_method: "There's no saved card. Add one, then turn it back on.", + payment_failed: "The payment didn't go through. Update the card, then turn it back on.", + unavailable: "Adding money isn't available right now. Try again later.", +}; + +export function fmtDay(value: Date | string | null | undefined): string { + if (!value) return ""; + const d = new Date(value); + if (Number.isNaN(d.getTime())) return ""; + return d.toLocaleDateString("en-US", { month: "short", day: "numeric" }); +} + +export function fmtClock(value: Date | string): string { + return new Date(value).toLocaleTimeString("en-US", { hour: "numeric", minute: "2-digit" }); +} + +// Ledger reason codes as people read them. +const REASONS: Record = { + writing_assistant: "Writing assistant", + writing_edit: "Selection edit", + agent_iteration: "Remie", + reply_draft: "Reply draft", + compose_draft: "Compose draft", + research_run: "Contact research", + automation_ai: "Automation AI step", + campaign_ai: "Campaign switch", + campaign_ai_search: "Campaign switch web search", + inbox_agent_draft: "Inbox agent", + spam_analysis: "Spam analysis", + placement_test: "Placement test", + ai_variable: "AI variable", + advisor_fix: "Advisor fix", + balance_top_up: "Money added", + credit_topup: "Money added", + auto_reload: "Automatic reload", + credit_auto_topup: "Automatic reload", + monthly_reset: "Monthly included usage", + trial_grant: "Trial balance", + tester_grant: "Test balance", +}; + +export function reasonLabel(reason: string): string { + if (REASONS[reason]) return REASONS[reason]; + const refund = reason.match(/^(.*)_(refund|release)$/); + if (refund && REASONS[refund[1]]) return `${REASONS[refund[1]]} refund`; + const s = reason.replace(/_/g, " "); + return s.charAt(0).toUpperCase() + s.slice(1); +} diff --git a/web/src/components/app/campaigns/CampaignActionsMenu.tsx b/web/src/components/app/campaigns/CampaignActionsMenu.tsx index 7cfc8946d..fb451e0bb 100644 --- a/web/src/components/app/campaigns/CampaignActionsMenu.tsx +++ b/web/src/components/app/campaigns/CampaignActionsMenu.tsx @@ -23,6 +23,7 @@ import { import { cn } from "@/lib/utils"; import type Campaign from "@/lib/api/models/app/campaigns/Campaign"; import { canStartCampaign, gate, useCampaignActions } from "./useCampaignActions"; +import { useAccessRestricted } from "@/hooks/usePermission"; interface Props { campaign: Campaign; @@ -41,6 +42,9 @@ export default function CampaignActionsMenu({ campaign, variant, onToggle, after const status = campaign.status ?? "draft"; const isActive = status === "active"; const showToggle = onToggle !== undefined && (isActive || canStartCampaign(status)); + // Settings, copies and deletion reach past a restricted member's grants; they keep start and pause. + const restricted = useAccessRestricted(); + if (restricted && !showToggle) return null; return ( @@ -60,19 +64,23 @@ export default function CampaignActionsMenu({ campaign, variant, onToggle, after - navigate({ to: "/app/campaigns/$id/preferences", params: { id: campaign.id } })} - icon={} - > - {variant === "row" ? "Edit" : "Edit settings"} - - actions.duplicateAndOpen(campaign))} - disabled={actions.duplicating} - icon={} - > - Duplicate - + {!restricted && ( + <> + navigate({ to: "/app/campaigns/$id/preferences", params: { id: campaign.id } })} + icon={} + > + {variant === "row" ? "Edit" : "Edit settings"} + + actions.duplicateAndOpen(campaign))} + disabled={actions.duplicating} + icon={} + > + Duplicate + + + )} {showToggle && ( onToggle?.())} @@ -87,15 +95,19 @@ export default function CampaignActionsMenu({ campaign, variant, onToggle, after {isActive ? "Pause" : "Start"} )} - - actions.requestDelete(campaign, { afterDelete }))} - disabled={actions.deleting} - icon={} - > - Delete - + {!restricted && ( + <> + + actions.requestDelete(campaign, { afterDelete }))} + disabled={actions.deleting} + icon={} + > + Delete + + + )} ); diff --git a/web/src/components/app/campaigns/ContentScore.tsx b/web/src/components/app/campaigns/ContentScore.tsx index 4853a4d86..db5c442cc 100644 --- a/web/src/components/app/campaigns/ContentScore.tsx +++ b/web/src/components/app/campaigns/ContentScore.tsx @@ -4,8 +4,8 @@ // composer's preview uses. Each issue carries where it is (subject or // body) and the exact fragments that caused it, so the panel points at the // words instead of restating the rule; -// - the AI pass (/templates/analyze), on an explicit click because it spends -// credits. It quotes the sentence a filter will object to and says what to +// - the AI pass (/templates/analyze), on an explicit click because it is +// charged to the balance. It quotes the sentence a filter will object to and says what to // write instead, and returns the rules pass with it so both halves of the // panel are scored from one reading of the copy. // @@ -41,6 +41,9 @@ import type { AppError } from "@/lib/api/client/normalizeError"; import buildError from "@/lib/helper/buildError"; import { usePermission } from "@/hooks/usePermission"; import useAiMetered from "@/hooks/useAiMetered"; +import { isInsufficientBalance, openInsufficientBalance } from "@/lib/insufficientBalance"; +import { fmtUsd, fmtUsdAbout, fmtUsdCost } from "@/lib/money"; +import { AI_ESTIMATE_USD } from "@/lib/aiEstimates"; import { Loading } from "@/components/loader"; import { cn } from "@/lib/utils"; import { DitherMeter, type DitherTone } from "@/components/ui/dither"; @@ -368,8 +371,8 @@ export default function ContentScore({ }, onError: (e) => { const err = e as unknown as AppError; - if (err?.status === 402) { - toast.error("You're out of AI credits. Add more to keep using AI analysis."); + if (isInsufficientBalance(err)) { + openInsufficientBalance(); } else if (err?.code === "ai_not_configured") { // Permanent for this deployment, unlike a provider // outage, so the button goes away rather than staying @@ -469,7 +472,7 @@ export default function ContentScore({ > Analyze with AI - {metered && 2 credits} + {metered && {fmtUsdAbout(AI_ESTIMATE_USD.spamAnalysis)}}

Reads the copy and names the words and sentences that hurt deliverability, in the subject and in @@ -574,10 +577,9 @@ export default function ContentScore({

)} - {metered && analysis.credits_charged > 0 && ( + {metered && analysis.charged_usd > 0 && (

- {analysis.credits_charged} credit{analysis.credits_charged === 1 ? "" : "s"} spent,{" "} - {analysis.credits_remaining} left + {fmtUsdCost(analysis.charged_usd)} spent, {fmtUsd(analysis.balance_usd)} left

)}
diff --git a/web/src/components/app/campaigns/LaunchCampaignDialog.tsx b/web/src/components/app/campaigns/LaunchCampaignDialog.tsx index e98b1c45b..0e6da211f 100644 --- a/web/src/components/app/campaigns/LaunchCampaignDialog.tsx +++ b/web/src/components/app/campaigns/LaunchCampaignDialog.tsx @@ -32,6 +32,7 @@ import { preflightFailures } from "@/lib/api/models/app/campaigns/Preflight"; import { isIdleCampaign } from "@/components/app/campaigns/status"; import { entryDelayLabel } from "@/components/app/campaigns/schedule/entryDelay"; import type { StartCampaignResult } from "@/lib/api/client/app/campaigns/startCampaign"; +import { useAccessRestricted } from "@/hooks/usePermission"; type Phase = "idle" | "launching" | "done"; @@ -122,7 +123,9 @@ export default function LaunchCampaignDialog({ // The platform's own pre-send checks, run fresh each time the dialog opens. // Advisory: a failure is shown, never used to disable Launch, because the // backend owns what actually blocks a start. - const preflight = usePreflight(campaign?.id ?? "", !!campaign); + // The checks read the workspace's mailboxes, so a restricted member launches without them. + const restricted = useAccessRestricted(); + const preflight = usePreflight(campaign?.id ?? "", !!campaign && !restricted); const issues = preflightFailures(preflight.data); // Reset to a clean state whenever a new campaign is opened. diff --git a/web/src/components/app/campaigns/new/EstimateInsights.tsx b/web/src/components/app/campaigns/new/EstimateInsights.tsx index da3cc800e..0ee49b07f 100644 --- a/web/src/components/app/campaigns/new/EstimateInsights.tsx +++ b/web/src/components/app/campaigns/new/EstimateInsights.tsx @@ -30,7 +30,7 @@ export function WarmupNote({ e, className }: { e: CampaignEstimateResult; classN Warmup keeps running on {plural(w.mailboxes, "mailbox", "mailboxes")} {without > now ? `, down from about ${without} to ${now} a day each` : `, about ${now} a day each`} while this runs. - {w.reply_rate ? ` Pool partners reply to at least ${w.reply_rate}% of it.` : ""} + {w.reply_rate ? " Pool partners prioritize replies to it within their own reply settings." : ""}

); @@ -99,7 +99,7 @@ export function MailboxMix({ e, limit, className }: { e: CampaignEstimateResult; {!!w.reply_rate && ( - Pool partners reply to at least {w.reply_rate}% of that warmup (where the partner allows replies) and read, rescue from spam + Pool partners answer that warmup before other warmup mail (within each partner's own reply rate) and read, rescue from spam and mark more of it important, so each mailbox keeps getting replies while most cold leads do not answer. Those replies use the partner's own warmup sends, so they add no volume. diff --git a/web/src/components/app/campaigns/new/draft.ts b/web/src/components/app/campaigns/new/draft.ts index f232673bd..bb1dd5157 100644 --- a/web/src/components/app/campaigns/new/draft.ts +++ b/web/src/components/app/campaigns/new/draft.ts @@ -36,6 +36,7 @@ export type Draft = { emailTagIds: string[]; dailyLimit: number; stopOnReply: boolean; + stopOnMeeting: boolean; openTracking: boolean; linkTracking: boolean; utmTracking: boolean; @@ -83,6 +84,7 @@ export const initialDraft = (timezone: string): Draft => ({ emailTagIds: [], dailyLimit: 50, stopOnReply: true, + stopOnMeeting: true, openTracking: true, linkTracking: true, utmTracking: true, @@ -201,6 +203,7 @@ export function toCreateInput(d: Draft, name: string): CreateCampaignInput { name, description: d.description.trim(), stop_on_reply: d.stopOnReply, + stop_on_meeting: d.stopOnMeeting, timezone: d.timezone, days: d.days, start_time: d.startTime, @@ -264,9 +267,15 @@ export function plural(n: number, one: string, many = `${one}s`): string { return `${n.toLocaleString()} ${n === 1 ? one : many}`; } +// The stop rules that are on, joined for the sentence they end ("replied or booked a meeting"). +export function stopRulePhrase(d: Draft, reply: string, meeting: string): string { + return [d.stopOnReply && reply, d.stopOnMeeting && meeting].filter(Boolean).join(" or "); +} + export function trackingSummary(d: Draft): string { const on = [ d.stopOnReply && "stop on reply", + d.stopOnMeeting && "stop on meeting", d.openTracking && "opens", d.linkTracking && "clicks", d.utmTracking && "UTM", diff --git a/web/src/components/app/campaigns/new/fields.tsx b/web/src/components/app/campaigns/new/fields.tsx index 594f80dae..410239592 100644 --- a/web/src/components/app/campaigns/new/fields.tsx +++ b/web/src/components/app/campaigns/new/fields.tsx @@ -185,7 +185,7 @@ export function SwitchRow({

{description}

e.stopPropagation()} className="shrink-0 mt-0.5 inline-flex"> - + ); diff --git a/web/src/components/app/campaigns/new/serverDraft.test.ts b/web/src/components/app/campaigns/new/serverDraft.test.ts index 8ee31f74b..5b94694f6 100644 --- a/web/src/components/app/campaigns/new/serverDraft.test.ts +++ b/web/src/components/app/campaigns/new/serverDraft.test.ts @@ -85,6 +85,7 @@ const campaign = { sender_strategy: "tags", daily_limit: 50, stop_on_reply: true, + stop_on_meeting: true, open_tracking: true, link_tracking: true, utm_tracking: true, diff --git a/web/src/components/app/campaigns/new/serverDraft.ts b/web/src/components/app/campaigns/new/serverDraft.ts index 937e4d1a0..04d0f92c0 100644 --- a/web/src/components/app/campaigns/new/serverDraft.ts +++ b/web/src/components/app/campaigns/new/serverDraft.ts @@ -112,6 +112,7 @@ export async function loadServerDraft(id: string): Promise { emailTagIds: campaign.email_tags ?? [], dailyLimit: campaign.daily_limit || base.dailyLimit, stopOnReply: campaign.stop_on_reply, + stopOnMeeting: campaign.stop_on_meeting ?? base.stopOnMeeting, openTracking: campaign.open_tracking, linkTracking: campaign.link_tracking, utmTracking: campaign.utm_tracking, @@ -152,6 +153,7 @@ export async function saveServerDraft( name, description: d.description.trim(), stop_on_reply: d.stopOnReply, + stop_on_meeting: d.stopOnMeeting, open_tracking: d.openTracking, link_tracking: d.linkTracking, utm_tracking: d.utmTracking, diff --git a/web/src/components/app/campaigns/new/steps.tsx b/web/src/components/app/campaigns/new/steps.tsx index 42fef3614..cc3ded13b 100644 --- a/web/src/components/app/campaigns/new/steps.tsx +++ b/web/src/components/app/campaigns/new/steps.tsx @@ -40,6 +40,7 @@ import { newEmail, plural, scheduledDate, + stopRulePhrase, trackingSummary, writtenEmails, type Draft, @@ -311,6 +312,8 @@ function EmailsEditor({ setSelected(1); }; const totalDays = draft.emails.slice(1).reduce((n, e) => n + Math.max(0, e.wait_after), 0); + const stopsFor = stopRulePhrase(draft, "replies", "books a meeting"); + const notYet = stopRulePhrase(draft, "replied", "booked a meeting"); return (
@@ -385,7 +388,7 @@ function EmailsEditor({ {draft.emails.length > 1 && (

{plural(draft.emails.length, "email")} over {plural(totalDays, "day")} - {draft.stopOnReply ? ", stopping for anyone who replies." : "."} + {stopsFor ? `, stopping for anyone who ${stopsFor}.` : "."}

)}
@@ -402,7 +405,7 @@ function EmailsEditor({ /> day{email.wait_after === 1 ? "" : "s"} after the previous email - {draft.stopOnReply ? ", if they have not replied" : ""}. + {notYet ? `, if they have not ${notYet}` : ""}. diff --git a/web/src/components/app/campaigns/sequences/StepEmailArms.tsx b/web/src/components/app/campaigns/sequences/StepEmailArms.tsx index 05f153062..ede21242c 100644 --- a/web/src/components/app/campaigns/sequences/StepEmailArms.tsx +++ b/web/src/components/app/campaigns/sequences/StepEmailArms.tsx @@ -12,12 +12,14 @@ import { Loader2Icon, Trash2Icon, TrophyIcon, PauseIcon, PlayIcon, SplitIcon } f import toast from "react-hot-toast/headless"; import type Sequence from "@/lib/api/models/app/campaigns/sequences/Sequence"; import type ABVariant from "@/lib/api/models/app/campaigns/ABVariant"; -import type { ABVariantStats } from "@/lib/api/models/app/campaigns/ABVariant"; +import type { ABStepArmStats } from "@/lib/api/models/app/campaigns/ABVariant"; import { Label, TextInput } from "@/components/ui/field"; import EmailContentEditor from "./EmailContentEditor"; import { htmlToPlain } from "./emailPreview"; import SequenceView from "./SequenceView"; import StepSplitAllocator, { type SplitArm } from "./StepSplitAllocator"; +import StepArmResults from "./StepArmResults"; +import StepWarmupPlacement from "./StepWarmupPlacement"; import { openerArmSubjects, type ArmSubject } from "./threading"; import type { EarlierEmail } from "./emailAIPrompt"; import { @@ -73,12 +75,18 @@ export default function StepEmailArms({ const busy = create.isPending || update.isPending || del.isPending; const { data: analysis } = useCampaignABAnalysis(campaignId, (all ?? []).length > 0); - const statsById = React.useMemo(() => { - const m = new Map(); - for (const s of analysis?.variants ?? []) m.set(s.variant_id, s); + const stepAnalysis = analysis?.steps?.find((s) => s.step_id === sequence.id) ?? null; + const statsByKey = React.useMemo(() => { + const m = new Map(); + for (const a of stepAnalysis?.arms ?? []) m.set(a.variant_id ?? "original", a); return m; - }, [analysis]); - const winnerId = analysis?.winner_id ?? null; + }, [stepAnalysis]); + const winner = stepAnalysis?.winner ?? null; + const winnerKey = winner ? (winner.variant_id ?? "original") : null; + const promotedRow = stepRows.find((v) => v.promoted_at) ?? null; + const promoted = promotedRow?.promoted_at + ? { name: promotedRow.is_control ? "Original" : promotedRow.name, at: promotedRow.promoted_at } + : null; const [selected, setSelected] = React.useState("original"); React.useEffect(() => { @@ -87,16 +95,18 @@ export default function StepEmailArms({ } }, [variants, selected]); + // A control row paused (by hand or by promoting a variant) takes the Original out of the split. + const originalActive = controlRow ? controlRow.is_active : true; const originalWeight = controlRow ? controlRow.weight : CONTROL_WEIGHT; const arms: SplitArm[] = [ - { key: "original", name: "Original", weight: originalWeight, active: true, isOriginal: true }, + { key: "original", name: "Original", weight: originalWeight, active: originalActive, isOriginal: true, winner: winnerKey === "original" }, ...variants.map((v, i) => ({ key: v.id, name: v.name || `Variant ${LETTERS[i] ?? i + 1}`, weight: v.weight, active: v.is_active, isOriginal: false, - winner: winnerId === v.id, + winner: winnerKey === v.id, })), ]; @@ -136,7 +146,7 @@ export default function StepEmailArms({ }; const evenSplit = () => { - const keys = ["original", ...variants.filter((v) => v.is_active).map((v) => v.id)]; + const keys = [...(originalActive ? ["original"] : []), ...variants.filter((v) => v.is_active).map((v) => v.id)]; const n = keys.length; if (n < 2) return; const base = Math.floor(100 / n); @@ -149,6 +159,9 @@ export default function StepEmailArms({ const togglePause = (variantId: string, active: boolean) => { update.mutate({ variantId, input: { is_active: active } }, { onError: err }); }; + const resumeOriginal = () => { + if (controlRow) togglePause(controlRow.id, true); + }; const deleteArm = (variantId: string) => { const v = variants.find((x) => x.id === variantId); @@ -203,6 +216,23 @@ export default function StepEmailArms({ busy={busy} /> )} + {variants.length > 0 && ( + + )} + arms.find((a) => a.key === key)?.name} + /> {selected === "original" || !selectedVariant ? ( togglePause(selectedVariant.id, active)} onDelete={() => deleteArm(selectedVariant.id)} @@ -263,7 +293,7 @@ function VariantEditor({ }: { campaignId: string; variant: ABVariant; - stats?: ABVariantStats; + stats?: ABStepArmStats; isWinner?: boolean; sharePct: number; onTogglePause: (active: boolean) => void; @@ -343,17 +373,17 @@ function VariantEditor({ - {stats && stats.total_sent > 0 && ( + {stats && stats.sent > 0 && (
{isWinner && ( Winner )} - + - +
)} diff --git a/web/src/components/app/campaigns/sequences/StepWarmupPlacement.test.tsx b/web/src/components/app/campaigns/sequences/StepWarmupPlacement.test.tsx new file mode 100644 index 000000000..a40d6d6bd --- /dev/null +++ b/web/src/components/app/campaigns/sequences/StepWarmupPlacement.test.tsx @@ -0,0 +1,59 @@ +import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; +import { cleanup, render, screen } from "@testing-library/react"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import StepWarmupPlacement from "./StepWarmupPlacement"; + +const api = vi.hoisted(() => ({ get: vi.fn() })); +vi.mock("@/lib/api/client/app/campaigns/getCampaignWarmupPlacement", () => ({ default: api.get })); + +const group = (g: string, reported: number, inbox: number, spam: number) => ({ group: g, sent: reported, reported, inbox, tabs: 0, spam, rescued: 0 }); + +describe("StepWarmupPlacement", () => { + beforeEach(() => api.get.mockReset()); + afterEach(cleanup); + + const draw = (armName: (k: string) => string | undefined = (k) => (k === "original" ? "Original" : "Variant B")) => + render( + + + , + ); + + it("stays hidden until an arm has enough receipts to read", async () => { + api.get.mockResolvedValue({ days: 30, data: [{ sequence_id: "s1", variant_id: null, placement: { sent: 30, reported: 19, inbox: 10, tabs: 0, spam: 9, rescued: 0 }, by_group: [group("google", 19, 10, 9)] }] }); + const { container } = draw(); + await vi.waitFor(() => expect(api.get).toHaveBeenCalled()); + await new Promise((r) => setTimeout(r, 0)); + expect(container.textContent).toBe(""); + }); + + it("shows each arm's headline and business inbox split for this step only", async () => { + api.get.mockResolvedValue({ + days: 30, + data: [ + { sequence_id: "s1", variant_id: null, placement: { sent: 20, reported: 20, inbox: 18, tabs: 0, spam: 2, rescued: 2 }, by_group: [group("google", 10, 10, 0), group("microsoft", 10, 8, 2)] }, + { sequence_id: "s1", variant_id: "v1", placement: { sent: 25, reported: 25, inbox: 25, tabs: 0, spam: 0, rescued: 0 }, by_group: [group("google", 21, 21, 0), group("microsoft", 4, 4, 0)] }, + { sequence_id: "s2", variant_id: null, placement: { sent: 29, reported: 29, inbox: 0, tabs: 0, spam: 29, rescued: 0 }, by_group: [] }, + ], + }); + draw(); + expect(await screen.findByText("Warmup placement")).toBeTruthy(); + expect(screen.getByText("Original")).toBeTruthy(); + expect(screen.getByText("Variant B")).toBeTruthy(); + expect(screen.getByText("90%")).toBeTruthy(); + expect(screen.getByText("80%")).toBeTruthy(); + expect(screen.getByText("20 checked")).toBeTruthy(); + expect(screen.getByText("25 checked")).toBeTruthy(); + expect(screen.queryByText("29 checked")).toBeNull(); + // Microsoft 365 shows for the Original's ten receipts and not for Variant B's four. + expect(screen.getAllByText(/Microsoft 365/)).toHaveLength(2); + }); + + it("drops a row for an arm no longer on the step", async () => { + api.get.mockResolvedValue({ days: 30, data: [{ sequence_id: "s1", variant_id: "gone", placement: { sent: 25, reported: 25, inbox: 25, tabs: 0, spam: 0, rescued: 0 }, by_group: [] }] }); + const { container } = draw((k) => (k === "original" ? "Original" : undefined)); + await vi.waitFor(() => expect(api.get).toHaveBeenCalled()); + await new Promise((r) => setTimeout(r, 0)); + expect(container.textContent).toBe(""); + }); +}); diff --git a/web/src/components/app/campaigns/sequences/StepWarmupPlacement.tsx b/web/src/components/app/campaigns/sequences/StepWarmupPlacement.tsx new file mode 100644 index 000000000..4e4e2455f --- /dev/null +++ b/web/src/components/app/campaigns/sequences/StepWarmupPlacement.tsx @@ -0,0 +1,101 @@ +// Where this step's copy landed at business inboxes when its senders' warmup +// carried it. Warmup opens some of its threads with a running campaign's copy +// on its own; this strip only reports, and stays hidden until an arm has +// enough receipts for its rate to mean something. + +import type { WarmupCopyPlacement, WarmupStepPlacement } from "@/lib/api/models/app/campaigns/WarmupPlacement"; +import { useCampaignWarmupPlacement } from "@/lib/api/hooks/app/campaigns/useCampaignWarmupPlacement"; + +const PROVIDERS: { group: string; label: string }[] = [ + { group: "google", label: "Google Workspace" }, + { group: "microsoft", label: "Microsoft 365" }, +]; + +// Receipts an arm needs before its rates show, and a provider before its own does. +const MIN_ARM_CHECKED = 20; +const MIN_PROVIDER_CHECKED = 10; + +const rate = (n: number, of: number) => Math.round((n / of) * 100); + +function inboxTone(pct: number) { + if (pct >= 90) return "text-emerald-600"; + if (pct >= 75) return "text-amber-600"; + return "text-rose-600"; +} + +export default function StepWarmupPlacement({ + campaignId, + stepId, + armName, +}: { + campaignId: string; + stepId: string; + // Display name of an arm by key ("original" or a variant id); undefined hides a row for an arm no longer on the step. + armName: (key: string) => string | undefined; +}) { + const { data } = useCampaignWarmupPlacement(campaignId); + const rows = (data?.data ?? []) + .filter((r) => r.sequence_id === stepId && r.placement.reported >= MIN_ARM_CHECKED) + .map((r) => ({ row: r, name: armName(r.variant_id ?? "original") })) + .filter((r): r is { row: WarmupStepPlacement; name: string } => r.name !== undefined); + if (rows.length === 0) return null; + const named = rows.length > 1 || rows[0].row.variant_id !== null; + + return ( +
+
+ Warmup placement + last {data?.days ?? 30} days +
+ {rows.map(({ row, name }) => ( +
+ {named && {name}} + + + {PROVIDERS.map(({ group, label }) => { + const g = row.by_group.find((x) => x.group === group); + if (!g || g.reported < MIN_PROVIDER_CHECKED) return null; + const pct = rate(g.inbox + g.tabs, g.reported); + return ( + + {label} {pct}% + + ); + })} + + {row.placement.reported.toLocaleString()} checked +
+ ))} +

+ Where this copy landed when your mailboxes' warmup sent it to business inboxes on Google Workspace and Microsoft 365. +

+
+ ); +} + +function Headline({ p }: { p: WarmupCopyPlacement }) { + const inbox = rate(p.inbox, p.reported); + const tabs = rate(p.tabs, p.reported); + const spam = rate(p.spam, p.reported); + return ( + + + {inbox}% + inbox + + {tabs > 0 && ( + + {tabs}% + tabs + + )} + + 10 ? "text-rose-600" : "text-slate-600"}`}>{spam}% + spam + + + ); +} diff --git a/web/src/components/app/campaigns/sequences/nodes/AIVariableNode.tsx b/web/src/components/app/campaigns/sequences/nodes/AIVariableNode.tsx index b5d3bbf42..02d3d266b 100644 --- a/web/src/components/app/campaigns/sequences/nodes/AIVariableNode.tsx +++ b/web/src/components/app/campaigns/sequences/nodes/AIVariableNode.tsx @@ -18,9 +18,7 @@ import { Node as TiptapNode, mergeAttributes } from "@tiptap/core"; import { ReactNodeViewRenderer, NodeViewWrapper, type NodeViewProps } from "@tiptap/react"; import { AnimatePresence, motion } from "framer-motion"; import { SparklesIcon, GlobeIcon, TrashIcon } from "lucide-react"; -import toast from "react-hot-toast/headless"; -import type { AppError } from "@/lib/api/client/normalizeError"; -import buildError from "@/lib/helper/buildError"; +import { reportAIError } from "@/components/app/ai/reportAIError"; import useGenerateAIVariable from "@/lib/api/hooks/app/generation/useGenerateAIVariable"; import useTypewriter from "@/components/app/ai/useTypewriter"; import formatUsage from "@/components/app/ai/usage"; @@ -209,7 +207,7 @@ function AIVariableConfigBody({ const [draft, setDraft] = React.useState(config); const [preview, setPreview] = React.useState(""); - const [usage, setUsage] = React.useState<{ charged: number; tokens: number } | null>(null); + const [usage, setUsage] = React.useState<{ chargedUsd: number; tokens: number } | null>(null); // Surrounding email, captured when the modal opens (the body isn't edited while open). const [ctx] = React.useState(getContext); @@ -245,17 +243,10 @@ function AIVariableConfigBody({ }, { onSuccess: (res) => { - setUsage({ charged: res.credits_charged ?? 0, tokens: res.tokens_used ?? 0 }); + setUsage({ chargedUsd: res.charged_usd ?? 0, tokens: res.tokens_used ?? 0 }); typewriter.run(res.text, (partial) => setPreview(partial)); }, - onError: (e) => { - const err = e as unknown as AppError; - if (err?.status === 402) { - toast.error("You're out of AI credits. Upgrade or purchase more to preview AI blocks."); - } else { - toast.error(buildError(err)); - } - }, + onError: (e) => reportAIError(e), }, ); }; @@ -408,8 +399,8 @@ function AIVariableConfigBody({

Your snippet appears here.

)} - {usage && preview && formatUsage(usage.charged, usage.tokens) && ( -

{formatUsage(usage.charged, usage.tokens)}

+ {usage && preview && formatUsage(usage.chargedUsd, usage.tokens) && ( +

{formatUsage(usage.chargedUsd, usage.tokens)}

)} diff --git a/web/src/components/app/campaigns/sequences/useEmailAIWriter.ts b/web/src/components/app/campaigns/sequences/useEmailAIWriter.ts index 95a6bbde4..a697691b5 100644 --- a/web/src/components/app/campaigns/sequences/useEmailAIWriter.ts +++ b/web/src/components/app/campaigns/sequences/useEmailAIWriter.ts @@ -88,7 +88,7 @@ export function useEmailAIWriter({ }, ); if (runId.current !== id) return; - setUsage({ charged: res.credits_charged ?? 0, tokens: res.tokens_used ?? 0 }); + setUsage({ chargedUsd: res.charged_usd ?? 0, tokens: res.tokens_used ?? 0 }); const draft = parseDraft(res.text); if (!draft.body) { restore(); diff --git a/web/src/components/app/cloud/CloudConnectDialog.tsx b/web/src/components/app/cloud/CloudConnectDialog.tsx deleted file mode 100644 index 4446d46e1..000000000 --- a/web/src/components/app/cloud/CloudConnectDialog.tsx +++ /dev/null @@ -1,132 +0,0 @@ -// Modal wrapper around CloudLinkCard for surfaces outside Settings (the -// mailboxes page, sending domains). Same overlay anatomy as NewCampaignDialog. -// Portaled and layered above drawers, which a transformed parent would trap. - -import React from "react"; -import { createPortal } from "react-dom"; -import { AnimatePresence, motion } from "framer-motion"; -import { LockIcon, XIcon } from "lucide-react"; -import { useQueryClient } from "@tanstack/react-query"; -import CloudLinkCard from "./CloudLinkCard"; -import { CLOUD_LINK_KEY } from "@/lib/api/hooks/app/cloudlink/useCloudLink"; -import { usePermission } from "@/hooks/usePermission"; - -export default function CloudConnectDialog({ - open, - onClose, - cloudUrl, - intro, - autoStart = false, - doneLabel = "Pick mailboxes", - onDone, -}: { - open: boolean; - onClose: () => void; - cloudUrl?: string; - /** Why the link is asked for here, shown above the code in place of the warmup pitch. */ - intro?: React.ReactNode; - /** Ask for a code straight away. */ - autoStart?: boolean; - doneLabel?: string; - /** What the button after linking does; closing is the default. */ - onDone?: () => void; -}) { - const qc = useQueryClient(); - const canLink = usePermission("MANAGE_SETTINGS"); - const [linked, setLinked] = React.useState(false); - const [orgName, setOrgName] = React.useState(""); - - React.useEffect(() => { - if (!open) { - setLinked(false); - setOrgName(""); - } - }, [open]); - - React.useEffect(() => { - if (!open) return; - const onKey = (e: KeyboardEvent) => { - if (e.key !== "Escape") return; - if (document.querySelector("[data-floating]:not([data-cloud-connect]), [role='alertdialog']")) return; - e.preventDefault(); - onClose(); - }; - document.addEventListener("keydown", onKey); - return () => document.removeEventListener("keydown", onKey); - }, [open, onClose]); - - return createPortal( - - {open && ( - { - e.stopPropagation(); - onClose(); - }} - className="fixed inset-0 z-[120] flex items-center justify-center bg-slate-900/30 backdrop-blur-[2px] px-4" - > - e.stopPropagation()} - className="w-full max-w-[520px] rounded-lg bg-white border border-slate-200 shadow-[0_24px_48px_-12px_rgba(15,23,42,0.18)] overflow-hidden" - > -
- Warmbly Cloud - -
-
- {intro && !linked &&
{intro}
} - {canLink ? ( - { - setOrgName(name); - setLinked(true); - void qc.invalidateQueries({ queryKey: CLOUD_LINK_KEY }); - }} - /> - ) : ( -

- - Connecting this instance to Warmbly Cloud is a settings change. Ask a teammate who manages settings to connect it. -

- )} -
- {linked && ( -
- -
- )} -
-
- )} -
, - document.body, - ); -} diff --git a/web/src/components/app/cloud/CloudLinkCard.tsx b/web/src/components/app/cloud/CloudLinkCard.tsx deleted file mode 100644 index 9c81c4b6a..000000000 --- a/web/src/components/app/cloud/CloudLinkCard.tsx +++ /dev/null @@ -1,276 +0,0 @@ -// The link handshake as one reusable card: pitch, then the code with a -// countdown and a live "waiting" pulse, then a linked confirmation. Used by -// Settings > Warmbly Cloud, the onboarding step and the mailboxes-page dialog. - -import React from "react"; -import { motion } from "framer-motion"; -import toast from "react-hot-toast/headless"; -import { CheckIcon, CloudIcon, CopyIcon, ExternalLinkIcon, FlameIcon, GlobeIcon, InboxIcon, Loader2Icon, LockIcon, ShieldCheckIcon } from "lucide-react"; -import type { AppError } from "@/lib/api/client/normalizeError"; -import buildError from "@/lib/helper/buildError"; -import type { CloudLinkPendingConnect } from "@/lib/api/models/app/cloudlink/CloudLink"; -import { usePollCloudLinkConnect, useStartCloudLinkConnect } from "@/lib/api/hooks/app/cloudlink/useCloudLink"; - -export default function CloudLinkCard({ - linked, - orgName, - cloudUrl, - onLinked, - compact = false, - autoStart = false, - minimal = false, - startSignal = 0, -}: { - linked: boolean; - orgName?: string; - cloudUrl?: string; - onLinked: (orgName: string) => void; - /** Tighter layout for dialogs and onboarding (no side illustration). */ - compact?: boolean; - /** Request a code immediately instead of showing the pitch first. */ - autoStart?: boolean; - /** Short pitch, no heading or button: the host owns the primary action. */ - minimal?: boolean; - /** Increment to request a code from outside (the host's primary button). */ - startSignal?: number; -}) { - const start = useStartCloudLinkConnect(); - const poll = usePollCloudLinkConnect(); - const [pending, setPending] = React.useState(null); - const [copied, setCopied] = React.useState(false); - const started = React.useRef(false); - - const begin = React.useCallback(async () => { - try { - const p = await start.mutateAsync(undefined); - setPending(p); - } catch (e) { - toast.error(buildError(e as AppError)); - } - }, [start]); - - React.useEffect(() => { - if (autoStart && !linked && !pending && !started.current) { - started.current = true; - void begin(); - } - }, [autoStart, linked, pending, begin]); - - React.useEffect(() => { - if (startSignal > 0 && !linked && !pending) void begin(); - // eslint-disable-next-line react-hooks/exhaustive-deps - }, [startSignal]); - - // Poll on the cloud's interval while a code is out. - React.useEffect(() => { - if (!pending || linked) return; - let stopped = false; - const tick = async () => { - if (stopped) return; - try { - const res = await poll.mutateAsync(); - if (res.status === "approved") { - onLinked(res.link?.organization_name ?? res.info?.organization.name ?? ""); - return; - } - } catch (e) { - const err = e as AppError; - if (err.code === "cloud_link_code_expired" || err.code === "pool_link_denied" || err.code === "pool_link_code_not_found") { - toast.error(err.message); - setPending(null); - return; - } - } - if (!stopped) window.setTimeout(tick, Math.max(2, pending.interval) * 1000); - }; - const t = window.setTimeout(tick, Math.max(2, pending.interval) * 1000); - return () => { - stopped = true; - window.clearTimeout(t); - }; - // eslint-disable-next-line react-hooks/exhaustive-deps - }, [pending, linked]); - - const copy = async () => { - if (!pending) return; - try { - await navigator.clipboard.writeText(pending.user_code); - setCopied(true); - window.setTimeout(() => setCopied(false), 1500); - } catch { - toast.error("Could not copy"); - } - }; - - if (linked) { - return ( - - - - -
-

Linked{orgName ? ` to ${orgName}` : ""}

-

This instance can now warm mailboxes in the Warmbly pool.

-
-
- ); - } - - if (!pending && minimal) { - return ( -
- - - -
-

Warmbly warms your mailboxes for you.

-

- Free for 10 mailboxes. Google and Microsoft sign-in without OAuth setup, and domain redirects without proxy setup. Your data stays on - this server; only warmup runs in the cloud. -

- {start.isPending && ( -

- Getting a code -

- )} -
-
- ); - } - - if (!pending) { - return ( -
-
-
-

Warm your mailboxes with the Warmbly pool

-

- Link this instance to a Warmbly Cloud workspace. Warmbly runs warmup for the mailboxes you choose, using thousands of real - mailboxes, while everything else stays on this server. -

-
-
    - Free for up to 10 mailboxes. Premium, $15 a month, brings better deliverability to every mailbox. - Sign in Google and Microsoft mailboxes through Warmbly's own apps: no OAuth client setup on this server. - Have the cloud serve your sending domains' website redirects, with no proxy or certificate setup on this server. - - Only mailbox sign-ins live on the cloud, encrypted, for warmup and sending, plus the domain and website of any redirect you hand it. - Campaigns, contacts and inbox never leave here. - - You can remove a mailbox or disconnect at any time; the cloud forgets it immediately. -
- - {cloudUrl &&

Connecting to {cloudUrl}

} -
- {!compact && } -
- ); - } - - return ( -
-

Enter this code on Warmbly Cloud to approve the link.

- - {pending.user_code} - - {copied ? : } - - - - Open Warmbly Cloud - - -
- - - - - Waiting for approval - -
-

- No Warmbly account yet? The link takes you to sign up first; it is free. This tab keeps waiting. -

-
- ); -} - -function Countdown({ until }: { until: Date }) { - const [left, setLeft] = React.useState(() => Math.max(0, Math.floor((new Date(until).getTime() - Date.now()) / 1000))); - React.useEffect(() => { - const t = window.setInterval(() => setLeft(Math.max(0, Math.floor((new Date(until).getTime() - Date.now()) / 1000))), 1000); - return () => window.clearInterval(t); - }, [until]); - const m = Math.floor(left / 60); - const s = left % 60; - return ( - - · code expires in {m}:{s.toString().padStart(2, "0")} - - ); -} - -function Bullet({ icon: Icon, children }: { icon: React.ComponentType<{ className?: string }>; children: React.ReactNode }) { - return ( -
  • - - {children} -
  • - ); -} - -// A small animated diagram: this server, the cloud, and mail flowing between. -function Illustration() { - return ( -
    -
    - - - - You -
    -
    - - - - Pool -
    -
    - {[0, 1, 2].map((i) => ( - - ))} -
    - ); -} diff --git a/web/src/components/app/contacts/AddFromContactsDialog.tsx b/web/src/components/app/contacts/AddFromContactsDialog.tsx index c1a645ed4..29489370a 100644 --- a/web/src/components/app/contacts/AddFromContactsDialog.tsx +++ b/web/src/components/app/contacts/AddFromContactsDialog.tsx @@ -21,6 +21,7 @@ import { } from "lucide-react"; import toast from "react-hot-toast/headless"; import { SearchInput } from "@/components/ui/field"; +import { Checkbox } from "@/components/ui/checkbox"; import CategoryPicker from "./CategoryPicker"; import useSearchContacts from "@/lib/api/hooks/app/contacts/useSearchContacts"; import useUpdateContactsBulk from "@/lib/api/hooks/app/contacts/useUpdateContactsBulk"; @@ -74,6 +75,7 @@ export default function AddFromContactsDialog({ open, onClose, campaign: campaig // Ticked rows, or the search itself minus what was unticked after it; the // same two shapes the contacts table uses (./selection). const [rowSel, setRowSel] = React.useState(rowSelection.emptySelection); + const [skipActive, setSkipActive] = React.useState(false); // Debounce the query so a fast typist does not fire a search per keystroke. const debounced = useBrowseDebouncedValue(query.trim(), browseName, 200); @@ -96,6 +98,7 @@ export default function AddFromContactsDialog({ open, onClose, campaign: campaig React.useEffect(() => { if (!open) { setRowSel(rowSelection.emptySelection); + setSkipActive(false); } }, [open]); @@ -135,9 +138,14 @@ export default function AddFromContactsDialog({ open, onClose, campaign: campaig ...selection, add_campaigns: [target.campaign.id], remove_campaigns: [], + skip_active_in_other_campaigns: skipActive || undefined, fields: [], }); - toast.success(`Added ${count.toLocaleString()} lead${count === 1 ? "" : "s"} to ${target.campaign.name}`); + toast.success( + skipActive + ? `Added to ${target.campaign.name}, leaving out anyone running in another campaign` + : `Added ${count.toLocaleString()} lead${count === 1 ? "" : "s"} to ${target.campaign.name}`, + ); } else { const added = await members.mutateAsync({ id: target.segment.id, selection, mode: "include" }); toast.success(`Added ${added.toLocaleString()} contact${added === 1 ? "" : "s"} to ${target.segment.name}`); @@ -377,11 +385,19 @@ export default function AddFromContactsDialog({ open, onClose, campaign: campaig
    - - {target.kind === "campaign" - ? "Contacts already in this campaign are skipped." - : "Added contacts stay in the segment whatever its conditions say."} - + {target.kind === "campaign" ? ( + + ) : ( + + Added contacts stay in the segment whatever its conditions say. + + )} {canBuy && ( - + + Premium pool on a paid plan + )} -
    - Running Warmbly on your own server? It can warm its mailboxes here too:{" "} - - link your instance - - . -
    - {dialog} ); } @@ -108,18 +93,18 @@ export default function CloudPathsPanel({ mailboxCount, onAdd }: { mailboxCount: {(linkedLabel || (free && canBuy)) && ( {linkedLabel} - {free && canBuy ? ` Premium gives every mailbox better deliverability, $${warmup.priceMonthly}/mo.` : ""} + {free && canBuy ? " Paid plans warm every mailbox in the premium pool." : ""} )} {canBuy && ( - + )} {linked > 0 && ( @@ -127,7 +112,6 @@ export default function CloudPathsPanel({ mailboxCount, onAdd }: { mailboxCount: )} - {dialog} ); } diff --git a/web/src/components/app/emails/CloudPoolBanner.tsx b/web/src/components/app/emails/CloudPoolBanner.tsx index 7392b5874..a16d843df 100644 --- a/web/src/components/app/emails/CloudPoolBanner.tsx +++ b/web/src/components/app/emails/CloudPoolBanner.tsx @@ -1,57 +1,51 @@ -// Mailboxes page strip for self-hosted instances: invites an unlinked -// instance to connect, and shows a linked one how many mailboxes are in the -// pool. Dismissal of the invite is remembered locally. Once linked the strip -// stays quiet: one line of state, and the Premium nudge only when the free -// allowance is actually used up. +// Mailboxes page strip for self-hosted instances. Unlinked: local warmup is not +// effective and self-hosting is unsupported, so it points at Warmbly Cloud. +// Linked on a free workspace: what it enrolled keeps warming, new mailboxes +// warm here unless the workspace pays. Linked and paid: one line of state. import React from "react"; import { Link } from "@tanstack/react-router"; -import { ArrowRightIcon, CloudIcon, ExternalLinkIcon, MailCheckIcon, TrendingUpIcon, XIcon } from "lucide-react"; +import { ArrowRightIcon, CloudIcon, ExternalLinkIcon, MessagesSquareIcon, ServerIcon, XIcon } from "lucide-react"; import useCloudPool from "@/hooks/useCloudPool"; +import { CLOUD_APP_URL, COMMUNITY_URL, cloudAddsNeedSubscription } from "@/lib/cloudPlan"; -const DISMISS_KEY = "warmbly.cloud-pool-banner.dismissed"; +// A new key, so instances that dismissed the old free offer see this notice once. +const DISMISS_KEY = "warmbly.selfHostNotice.dismissed"; -export default function CloudPoolBanner({ onConnect, mailboxCount }: { onConnect: () => void; mailboxCount: number }) { +export default function CloudPoolBanner({ mailboxCount }: { mailboxCount: number }) { const pool = useCloudPool(); const [dismissed, setDismissed] = React.useState(() => localStorage.getItem(DISMISS_KEY) === "1"); if (!pool.manageable || pool.loading) return null; - if (pool.connected && !pool.workspaceConnected) { - return
    Existing Cloud mailboxes keep warming. Connect this workspace to add more.
    ; - } if (pool.connected) { const plan = pool.plan; - const limit = plan?.mailbox_limit ?? null; const premium = plan?.tier === "paid"; - // The allowance is per cloud workspace, so the cloud's count is the - // one that decides, not this instance's own enrolled count. - const used = plan?.enrolled ?? pool.enrolledCount; - const atLimit = !premium && limit !== null && used >= limit && mailboxCount > pool.enrolledCount; - if (atLimit && plan?.upgrade_url) { + const closed = cloudAddsNeedSubscription(plan); + const subscribeURL = plan?.upgrade_url || plan?.manage_url; + if (closed && mailboxCount > pool.enrolledCount) { return ( -
    -
    - -
    - - Give every mailbox better deliverability.{" "} - - All {limit} free pool mailboxes are in use. Premium warms the rest in the premium pool, built for inbox placement, for ${plan.price_usd} a month. - - - - Upgrade to Premium - - -
    -
    -
    + + {pool.enrolledCount > 0 ? `The ${pool.enrolledCount} already in Warmbly Cloud keep warming there. ` : ""} + Adding more to the Cloud pool needs a paid Warmbly Cloud plan. Self-hosted instances get no support from Warmbly. + + } + actions={ + <> + {subscribeURL && ( + + See plans + + + )} + + + } + /> ); } return ( @@ -64,9 +58,7 @@ export default function CloudPoolBanner({ onConnect, mailboxCount }: { onConnect ? "No mailbox is warming in Warmbly Cloud yet." : `${pool.enrolledCount} of ${mailboxCount} mailboxes warm in Warmbly Cloud.`} {" "} - - {premium ? "Premium pool." : limit === null ? "Unlimited." : `${used} of ${limit} free.`} - + {premium ? "Premium pool." : closed ? "Free, no new mailboxes." : "Free pool."} Manage @@ -78,43 +70,82 @@ export default function CloudPoolBanner({ onConnect, mailboxCount }: { onConnect if (dismissed) return null; + return ( + + It only pairs your own mailboxes, which providers learn to recognise. Warmbly Cloud warms mailboxes in a pool of thousands of real + ones. To move, pick a plan on Warmbly Cloud, then bring this workspace over with an export from{" "} + + Settings > Data + + . Warmbly does not provide support for self-hosting. + + } + actions={ + <> + + Upgrade on Warmbly Cloud + + + + + } + onDismiss={() => { + localStorage.setItem(DISMISS_KEY, "1"); + setDismissed(true); + }} + /> + ); +} + +// Opens the plan chooser once the account exists; the sign-up page also signs existing users in. +const CLOUD_PLANS_PATH = "/app/settings/billing?pool=1"; + +const PRIMARY = "shrink-0 h-7 px-2.5 rounded-md bg-sky-600 hover:bg-sky-700 text-white text-[12px] font-medium inline-flex items-center gap-1.5 transition-colors"; + +function Notice({ icon, title, body, actions, onDismiss }: { icon: React.ComponentType<{ className?: string }>; title: string; body: React.ReactNode; actions: React.ReactNode; onDismiss?: () => void }) { return (
    - +
    - Get these mailboxes into the inbox, not spam.{" "} - - Warm them in Warmbly Cloud's large, active pool to build sender reputation, with replies and spam rescue handled for you. - Free for 10 mailboxes, set up in a minute, and your data stays here. - + {title} {body} +
    {actions}
    +
    + {onDismiss && ( -
    - + )}
    ); } +function CommunityLink() { + return ( + + + Community on Discord + + ); +} + // A soft round badge: tinted fill and a hairline ring, lighter than a solid tile. function SoftIcon({ icon: Icon }: { icon: React.ComponentType<{ className?: string }> }) { return ( diff --git a/web/src/components/app/emails/CloudWarmupCard.tsx b/web/src/components/app/emails/CloudWarmupCard.tsx index 3f068df29..d11e155a9 100644 --- a/web/src/components/app/emails/CloudWarmupCard.tsx +++ b/web/src/components/app/emails/CloudWarmupCard.tsx @@ -3,7 +3,6 @@ // pause/resume/remove, or the way in when it is not enrolled yet. import React from "react"; -import { Link } from "@tanstack/react-router"; import toast from "react-hot-toast/headless"; import { CloudIcon, Loader2Icon, PauseIcon, PlayIcon } from "lucide-react"; import type { AppError } from "@/lib/api/client/normalizeError"; @@ -21,6 +20,7 @@ import { setCloudLinkParticipation } from "@/lib/api/client/app/cloudlink/cloudL import type { DiagnosticParticipation } from "@/lib/api/models/app/cloudlink/CloudLink"; import { Toggle } from "@/components/app/campaigns/preferences/components/CampaignPreferenceBoolBox"; import { cloudMailboxPickerOpened } from "@/lib/cloudMailboxConnect"; +import { cloudAddsNeedSubscription } from "@/lib/cloudPlan"; export default function CloudWarmupCard({ mailboxId, email, provider }: { mailboxId: string; email: string; provider: string }) { const pool = useCloudPool(); @@ -43,23 +43,28 @@ export default function CloudWarmupCard({ mailboxId, email, provider }: { mailbo } }; - if (!pool.connected) { - return ( -
    - - Warm this mailbox in the Warmbly pool instead, free for up to 10 mailboxes. - - Connect Warmbly Cloud - -
    - ); - } + if (!pool.connected) return null; const row = pool.rowFor(mailboxId); const cloud = row?.cloud; const sendFailure = cloudSendFailure(cloud); const supported = providerSupported(provider); + const subscribeURL = pool.plan?.upgrade_url || pool.plan?.manage_url; + if (!row?.enrolled && cloudAddsNeedSubscription(pool.plan)) { + return ( +
    + + This mailbox warms on this instance, which is not effective. Adding it to the Warmbly Cloud pool needs a paid plan. + {subscribeURL && ( + + See plans + + )} +
    + ); + } + if (!row?.enrolled) { return (
    @@ -119,13 +124,14 @@ export default function CloudWarmupCard({ mailboxId, email, provider }: { mailbo disabled={busy} onClick={() => confirm.show( - row.managed + (row.managed ? `Remove ${email} from this instance and stop its Cloud warmup sending and receiving? Its mailbox, sign-in and history stay in your Warmbly Cloud workspace. You can restart warmup there.` : row.independent_smtp || cloud?.managed ? `Disconnect Cloud warmup for ${email}? Its Cloud mailbox, credentials and warmup history stay on Cloud. Campaigns here keep their existing app-password connection. Cloud warmup sending and receiving stop until you restart them there.` : row.executor === "instance" ? `Stop warming ${email} in the Warmbly pool? Its credential never left this server, and local warmup takes over.` - : `Stop warming ${email} in the Warmbly pool? The cloud deletes its credential right away and local warmup takes over.`, + : `Stop warming ${email} in the Warmbly pool? The cloud deletes its credential right away and local warmup takes over.`) + + (cloudAddsNeedSubscription(pool.plan) ? " A free workspace cannot add it back without a paid plan." : ""), async () => { await run(() => unenroll.mutateAsync(mailboxId), row.managed ? `${email} removed from this instance` : `${email} removed from the pool`); }, diff --git a/web/src/components/app/emails/GmailAppPasswordPanel.tsx b/web/src/components/app/emails/GmailAppPasswordPanel.tsx index b8a55f7bf..38cd2d433 100644 --- a/web/src/components/app/emails/GmailAppPasswordPanel.tsx +++ b/web/src/components/app/emails/GmailAppPasswordPanel.tsx @@ -49,10 +49,13 @@ function normalizeAppPassword(raw: string): string { export default function GmailAppPasswordPanel({ onDone, onError, + initialEmail = "", }: { onDone: () => void; /** A refused connect (a full allowance) gets its own dialog upstairs. */ onError: (e: unknown) => void; + /** An address typed earlier, e.g. a personal Gmail steered here from Google sign-in. */ + initialEmail?: string; }) { const [step, setStep] = React.useState(0); const [dir, setDir] = React.useState<1 | -1>(1); @@ -82,7 +85,7 @@ export default function GmailAppPasswordPanel({ > {step === 0 && go(1)} />} {step === 1 && go(0)} onNext={() => go(2)} />} - {step === 2 && go(1)} onDone={onDone} onError={onError} />} + {step === 2 && go(1)} onDone={onDone} onError={onError} initialEmail={initialEmail} />}
    @@ -178,13 +181,15 @@ function ConnectStep({ onBack, onDone, onError, + initialEmail, }: { onBack: () => void; onDone: () => void; onError: (e: unknown) => void; + initialEmail: string; }) { const [name, setName] = React.useState(""); - const [email, setEmail] = React.useState(""); + const [email, setEmail] = React.useState(initialEmail); const [password, setPassword] = React.useState(""); const [submitting, setSubmitting] = React.useState(false); diff --git a/web/src/components/app/emails/GoogleWorkspaceSigninPanel.tsx b/web/src/components/app/emails/GoogleWorkspaceSigninPanel.tsx new file mode 100644 index 000000000..410dcf1b9 --- /dev/null +++ b/web/src/components/app/emails/GoogleWorkspaceSigninPanel.tsx @@ -0,0 +1,226 @@ +// GoogleWorkspaceSigninPanel: one Google Workspace mailbox through Google sign-in. +// +// The domain's administrator marks Warmbly's OAuth client Trusted once, which is +// what lets mailboxes on that domain sign in to it; then each mailbox signs in +// on its own. A personal Gmail address goes to the app-password walkthrough. + +import React from "react"; +import { motion } from "framer-motion"; +import { CheckIcon, ExternalLinkIcon, KeyRoundIcon, Loader2Icon, ShieldAlertIcon, ShieldCheckIcon } from "lucide-react"; + +import { Google } from "@/components/svg"; +import { TextInput } from "@/components/ui/field"; +import { CopyValue } from "@/components/app/emails/import/parts"; +import { Crumbs, Instruction } from "@/components/app/emails/import/grants/GrantSetupSteps"; +import { isPersonalGmail } from "@/lib/mailHost"; + +/** Admin console > Security > Access and data control > API controls > Manage Third-Party App Access. */ +export const GOOGLE_THIRD_PARTY_APPS_URL = "https://admin.google.com/ac/owl/list?tab=configuredApps"; + +const THIRD_PARTY_PATH = ["Security", "Access and data control", "API controls", "Manage Third-Party App Access"]; + +const ADDRESS_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; + +export default function GoogleWorkspaceSigninPanel({ + busy, + viaCloud, + clientId, + unfinished, + onConnect, + onPersonalGmail, + onUseAppPassword, +}: { + busy: boolean; + viaCloud: boolean; + /** The OAuth client a Workspace admin trusts; absent when the instance did not report one. */ + clientId?: string; + /** The last sign-in window closed or was denied without connecting. */ + unfinished: boolean; + onConnect: (address: string) => void; + onPersonalGmail: (address: string) => void; + onUseAppPassword: (address: string) => void; +}) { + const [address, setAddress] = React.useState(""); + const trimmed = address.trim(); + const personal = isPersonalGmail(trimmed); + const valid = ADDRESS_RE.test(trimmed); + // Brokered through Warmbly Cloud, the consent runs on the cloud's client, not this one. + const showAdmin = !viaCloud; + + function submit() { + if (busy || !valid) return; + if (personal) onPersonalGmail(trimmed); + else onConnect(trimmed); + } + + return ( +
    +
    +
    + +
    +
    +
    Sign in a Google Workspace mailbox
    +
    + {viaCloud + ? "Warmbly Cloud opens the Google window on its own app. Approve and you're done." + : "Your Workspace admin trusts Warmbly once, then each mailbox signs in with Google."} +
    +
    +
    + + {showAdmin && ( +
    +
    + Step 1 + Your Workspace admin trusts Warmbly, once per domain +
    +

    + Marking Warmbly as a trusted app is what lets mailboxes on your domain connect. Without it, Google can show + “Access blocked” when a mailbox signs in. Already done for this domain? Go on to step 2. +

    + +
    + )} + +
    + {showAdmin && ( +
    + Step 2 + Sign in the mailbox +
    + )} + { + if (e.key === "Enter") submit(); + }} + /> + {personal && ( +
    + +

    + This is a personal Gmail address. Personal Gmail connects with an app password over IMAP and SMTP, not with Google + sign-in. Continue and Warmbly walks you through it. +

    +
    + )} +
    + +
      + Send and read mail on the mailbox's behalf + Track replies and deliveries + Refresh tokens are stored encrypted; revoke any time +
    + +
    + + {busy ? : personal ? : } + {busy ? "Waiting for authorization…" : personal ? "Continue with an app password" : "Continue with Google"} + + {!valid && !busy &&

    Enter the mailbox's address to continue.

    } +
    + + {unfinished && !viaCloud && } + +

    + Prefer not to use Google sign-in?{" "} + +

    +
    + ); +} + +/** The Admin console steps that mark Warmbly's OAuth client Trusted for a Workspace domain. */ +export function TrustedAppSteps({ clientId }: { clientId?: string }) { + return ( +
      + +

      + Sign in to admin.google.com as an administrator. +

      + + + Open Google Admin + +
      + +

      Go to

      + +

      + and click Configure new app (or{" "} + Add app > OAuth App Name or Client ID). +

      +
      + +

      Search by this client ID and select Warmbly.

      + {clientId ? ( + + ) : ( +

      This instance did not report its client ID. Ask the operator for it.

      + )} +
      + +

      + Choose All users (or the organizational unit that holds the + mailboxes), then Trusted, and finish. +

      +
      +
    + ); +} + +/** Shown after a sign-in window closed without connecting: the usual cause on Workspace is an untrusted app. */ +export function BlockedByAdminHint({ clientId }: { clientId?: string }) { + return ( + +
    + +
    +
    Google said the app is blocked by your admin?
    +

    + Your Workspace admin has to add Warmbly's client ID as a trusted app under Manage Third-Party App Access, for All + users, then the mailbox can sign in again. +

    +
    +
    + {clientId && } +
    + ); +} + +function Scope({ children }: { children: React.ReactNode }) { + return ( +
  • + + {children} +
  • + ); +} diff --git a/web/src/components/app/emails/InboxDetails.tsx b/web/src/components/app/emails/InboxDetails.tsx index c98dcbd82..4adb5d2a5 100644 --- a/web/src/components/app/emails/InboxDetails.tsx +++ b/web/src/components/app/emails/InboxDetails.tsx @@ -61,6 +61,7 @@ import type AccountStatusModel from "@/lib/api/models/app/analytics/AccountStatu import type { AccountError } from "@/lib/api/models/app/analytics/AccountStatus"; import useAccountStatus from "@/lib/api/hooks/app/analytics/useAccountStatus"; import useWarmupAnalytics from "@/lib/api/hooks/app/analytics/useWarmupAnalytics"; +import type WarmupAnalytics from "@/lib/api/models/app/analytics/WarmupAnalytics"; import useUpdateEmail from "@/lib/api/hooks/app/emails/useUpdateEmail"; import useRemoveEmail from "@/lib/api/hooks/app/emails/useRemoveEmail"; import useWarmupLifecycle from "@/lib/api/hooks/app/emails/useWarmupLifecycle"; @@ -87,7 +88,7 @@ import { mailboxConnectionLabel, mailHostLogo } from "@/lib/mailHost"; import { useGrants } from "@/lib/api/hooks/app/emails/useMailboxGrants"; import { domainOf, grantFor, grantName, vendorLabel, type GrantProvider } from "@/lib/api/models/app/emails/MailboxSources"; import MailboxGrantDialog from "./import/grants/MailboxGrantDialog"; -import SigninRetiringNotice from "./migration/SigninRetiringNotice"; +import MailboxSigninSection, { SigninPrompt } from "./migration/MailboxSigninSection"; import ProviderLogo from "./ProviderLogo"; import MailboxSourceChip from "./MailboxSourceChip"; import { mailboxSource } from "@/lib/mailboxSource"; @@ -99,8 +100,9 @@ import SendingBehaviorTab from "./SendingBehaviorTab"; import { useUserProfile } from "@/hooks/context/user"; import useCurrentOrganization from "@/lib/api/hooks/app/organizations/useCurrentOrganization"; import { timezoneOptions } from "@/lib/timezone"; -import { utcDay } from "@/lib/campaignPeriod"; +import { utcDay, utcToday } from "@/lib/campaignPeriod"; import SyncStatusCard from "./SyncStatusCard"; +import SendPauseNotice from "./SendPauseNotice"; import ServerCertificatesCard from "./ServerCertificatesCard"; import CloudWarmupCard from "./CloudWarmupCard"; import WarmupPartnerDiversity from "./WarmupPartnerDiversity"; @@ -111,13 +113,13 @@ import { Toggle } from "@/components/app/campaigns/preferences/components/Campai import setDirectTracking from "@/lib/api/client/app/emails/setDirectTracking"; import useSendingBehavior from "@/lib/api/hooks/app/emails/useSendingBehavior"; import useSendingPlan from "@/lib/api/hooks/app/emails/useSendingPlan"; -import { minutesToClock, secondsToLabel } from "@/lib/api/models/app/emails/SendingBehavior"; +import { clockToMinutes, minutesToClock, secondsToLabel } from "@/lib/api/models/app/emails/SendingBehavior"; import TagSelector from "../popup/select/TagSelector"; import { useAppStore } from "@/stores"; import { repliesGoTo } from "@/lib/unibox/replyInbox"; import TimeSelect from "@/components/ui/TimeSelect"; import { DitherBarChart } from "@/components/ui/dither"; -import WeekdayBitmask from "../campaigns/schedule/WeekdayBitmask"; +import WarmupDaysPicker from "./WarmupDaysPicker"; import { Loading } from "@/components/loader"; import { NumberInput, TextInput } from "@/components/ui/field"; import { clampWarmupRetentionDays } from "@/lib/warmupRetention"; @@ -424,12 +426,14 @@ function Detail({ mailbox, onClose, initialTab, tabIntentKey, onTabIntentConsume } }, [initialTab, tabIntentKey, onTabIntentConsumed, setTab]); const [form, setForm] = useState(mailbox); + const [daysToApply, setDaysToApply] = useState(null); // Fields the user has edited since the last save; a refresh never overwrites them. const touched = React.useRef(new Set()); const update = (patch: Partial) => { - // A field put back to the stored value is untouched again, so a refresh can still reach it. + // Choosing warmup days reapplies the schedule even when the saved selection is unchanged. + if (patch.warmup_days !== undefined) setDaysToApply(patch.warmup_days); for (const k of Object.keys(patch) as (keyof Inbox)[]) { - if (JSON.stringify(patch[k]) === JSON.stringify(mailbox[k])) touched.current.delete(k); + if (k !== "warmup_days" && JSON.stringify(patch[k]) === JSON.stringify(mailbox[k])) touched.current.delete(k); else touched.current.add(k); } setForm((f) => ({ ...f, ...patch })); @@ -448,26 +452,23 @@ function Detail({ mailbox, onClose, initialTab, tabIntentKey, onTabIntentConsume }, [mailbox]); const discard = () => { touched.current.clear(); + setDaysToApply(null); setForm(mailbox); }; usePresenceResource(mailbox.id ? `mailbox:${mailbox.id}` : null, "editing"); const status = useAccountStatus(mailbox.id); - const { from, to } = useMemo(() => { - const end = new Date(); - const start = new Date(); - start.setDate(start.getDate() - 29); - const fmt = (d: Date) => d.toISOString().slice(0, 10); - return { from: fmt(start), to: fmt(end) }; - }, []); + // Recomputed each render so a drawer left open past UTC midnight moves on to the new day. + const to = utcToday(); + const from = utcDay(new Date(Date.now() - 29 * 86_400_000)); const warmup = useWarmupAnalytics(mailbox.id, from, to); const pool = useCloudPool(); const mutation = useUpdateEmail(mailbox.id, pool.connected && pool.isEnrolled(mailbox.id) ? cloudOwnedWarmupFields : undefined); const dirty = useMemo( - () => EDITABLE.some((k) => JSON.stringify(form[k]) !== JSON.stringify(mailbox[k])), - [form, mailbox], + () => daysToApply !== null || EDITABLE.some((k) => JSON.stringify(form[k]) !== JSON.stringify(mailbox[k])), + [daysToApply, form, mailbox], ); const save = async () => { @@ -477,8 +478,10 @@ function Detail({ mailbox, onClose, initialTab, tabIntentKey, onTabIntentConsume (patch as Record)[k] = form[k]; } } + if (daysToApply !== null) patch.warmup_days = daysToApply; try { const saved = await mutation.mutateAsync(patch); + setDaysToApply((current) => current === patch.warmup_days ? null : current); // The answer is what was stored (for a Cloud mailbox, what Warmbly Cloud applied). setForm((f) => { const next = { ...f } as Record; @@ -569,9 +572,9 @@ function Detail({ mailbox, onClose, initialTab, tabIntentKey, onTabIntentConsume {/* Body */}
    - {tab === "overview" && } + {tab === "overview" && setTab("settings")} />} {tab === "deliverability" && } - {tab === "analytics" && void warmup.refetch()} />} + {tab === "analytics" && void warmup.refetch()} />} {tab === "warmup" && } {tab === "sending" && } {tab === "settings" && } @@ -730,10 +733,11 @@ function DelegatedGrantNotice({ mailbox, inError = false }: { mailbox: Inbox; in ); } -function OverviewTab({ status, loading, mailbox }: { status?: import("@/lib/api/models/app/analytics/AccountStatus").default; loading: boolean; mailbox: Inbox }) { +function OverviewTab({ status, loading, mailbox, warmup, onOpenSignin }: { status?: import("@/lib/api/models/app/analytics/AccountStatus").default; loading: boolean; mailbox: Inbox; warmup?: WarmupAnalytics; onOpenSignin: () => void }) { const health = status?.health; const usage = status?.daily_usage; const ws = status?.warmup_status; + const replyShare = weekReplyShare(warmup); // When a sending-behaviour profile is on, TODAY'S rolled plan is the real // ceiling and spacing — not the mailbox's fixed cap and gap. Showing the @@ -758,7 +762,7 @@ function OverviewTab({ status, loading, mailbox }: { status?: import("@/lib/api/ return (
    {mailbox.status === "inactive" && } - {mailbox.provider === "gmail" && mailbox.auth_method !== "delegated" && } + {/* Whatever the Advisor has on this mailbox, above the numbers that produced it. This is where a row flag and a deep link both land. */} )} {/* A login refused at send time can hold sending while sync still works, so no credential error carries the button. */} - {status?.send_recovery_reason === "authentication" && !firstCredentialErrorId && + {status?.send_recovery_reason === "authentication" && !firstCredentialErrorId && !status.send_pause && (mailbox.auth_method === "delegated" ? : )}
    + {status?.send_pause && ( + : )} + /> + )} + {/* Sync: import progress and fair-use status */} @@ -813,14 +826,14 @@ function OverviewTab({ status, loading, mailbox }: { status?: import("@/lib/api/ today ? today.is_working_day ? `of ${today.daily_limit} rolled for today` - : "not a sending day" + : "not a campaign sending day" : usage ? `of ${usage.campaign_limit}/day cap` : undefined } /> - +
    @@ -834,20 +847,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" ? ( + + ) : ( + + ))} +
    + ); + })}
    )} @@ -907,9 +923,21 @@ function OverviewTab({ status, loading, mailbox }: { status?: import("@/lib/api/ ); } +// The reply target is held over the last seven UTC days, so that window is the one to compare it with. +function weekReplyShare(warmup?: WarmupAnalytics): number | null { + const since = utcDay(new Date(Date.now() - 6 * 86_400_000)); + let sent = 0, replied = 0; + for (const d of warmup?.daily_stats ?? []) { + if (d.date < since) continue; + sent += d.emails_sent; + replied += d.emails_replied; + } + return sent > 0 ? Math.round((replied / sent) * 100) : null; +} + /* ── Analytics ─────────────────────── */ -function AnalyticsTab({ warmup, loading, failed, retry }: { warmup?: import("@/lib/api/models/app/analytics/WarmupAnalytics").default; loading: boolean; failed: boolean; retry: () => void }) { +function AnalyticsTab({ warmup, replyTarget, loading, failed, retry }: { warmup?: WarmupAnalytics; replyTarget: number; loading: boolean; failed: boolean; retry: () => void }) { // Tap affordance for touch devices, where the native title tooltip never fires. const [selectedDay, setSelectedDay] = useState(null); if (loading) { @@ -936,6 +964,11 @@ function AnalyticsTab({ warmup, loading, failed, retry }: { warmup?: import("@/l ); } const s = warmup.summary; + // The range runs 30 days but the target is held over 7, so the share is read against the target on that window. + const weekShare = weekReplyShare(warmup); + const replySub = weekShare === null + ? `${s.reply_rate.toFixed(1)}% reply rate` + : replyTarget > 0 ? `${weekShare}% last 7d · target ${replyTarget}%` : `${weekShare}% last 7 days`; const chartData = warmup.daily_stats.map((d) => ({ key: d.date, value: d.emails_sent, @@ -951,7 +984,7 @@ function AnalyticsTab({ warmup, loading, failed, retry }: { warmup?: import("@/l
    - +
    @@ -994,7 +1027,12 @@ function AnalyticsTab({ warmup, loading, failed, retry }: { warmup?: import("@/l /* ── Warmup (editable) ─────────────────────── */ -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" }, @@ -1298,7 +1336,9 @@ function WarmupTab({ form, update, status, mailbox, canWarmup = true }: { form: 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 workspaceZone = useCurrentOrganization().data?.timezone; + const behaviorOn = !!persona?.enabled; const inCampaign = status?.in_campaign; // Warmup on/off is a lifecycle action (immediate), not a saved form field — @@ -1317,6 +1357,10 @@ function WarmupTab({ form, update, status, mailbox, canWarmup = true }: { form: const cloudRow = inCloud ? pool.rowFor(mailbox.id) : undefined; // Warmbly Cloud skips a 0 sent from an instance, so the form does not offer one. const cloudMin = inCloud ? 1 : 0; + const startMinute = clockToMinutes(form.warmup_start_time || "08:00"); + const endMinute = clockToMinutes(form.warmup_end_time || "20:00"); + const noOverlap = !inCloud && persona?.enabled && startMinute !== null && endMinute !== null && + (startMinute >= persona.work_end_max || endMinute <= persona.work_start_min); const run = (action: "start" | "pause" | "resume" | "stop", verb: string) => { const execute = () => life.mutate(action, { @@ -1461,7 +1505,7 @@ function WarmupTab({ form, update, status, mailbox, canWarmup = true }: { form: Today
    Sending {ws.current_volume} of {ws.target_volume} · day {ws.days_active} - {ws.next_send_at && · next {nextSlotLabel(ws.next_send_at)}} + {ws.next_send_at && · next {nextSlotLabel(ws.next_send_at, undefined, mailbox.timezone || workspaceZone || "UTC")}}
    @@ -1549,7 +1593,7 @@ function WarmupTab({ form, update, status, mailbox, canWarmup = true }: { form: {baseOverMax && (

    Starting volume can't exceed the maximum.

    )} - + update({ warmup_reply_rate: v })} suffix="%" min={cloudMin} /> {/* Warmbly Cloud writes its own content, so the segment only applies to warmup sent from here. */} @@ -1575,10 +1619,12 @@ function WarmupTab({ form, update, status, mailbox, canWarmup = true }: { form: {/* Schedule */}
    Sending window - {behaviorOn && ( + {behaviorOn && !inCloud && (

    - Sending behaviour is on for this mailbox, so warmup only sends when both this window and the workday on the Sending tab - allow it. Switch it to Fixed schedule there to use these hours alone. + Sending behaviour is on. Warmup uses the overlap between these hours and the varied workday on the Sending tab, + including its break. The workday starts between {minutesToClock(persona.work_start_min)} and {minutesToClock(persona.work_start_max)} and + ends between {minutesToClock(persona.work_end_min)} and {minutesToClock(persona.work_end_max)}. + Switch to Fixed schedule on the Sending tab to use these hours alone.

    )}
    @@ -1589,14 +1635,19 @@ function WarmupTab({ form, update, status, mailbox, canWarmup = true }: { form: update({ warmup_end_time: v })} />
    - -
    - update({ warmup_days: v })} - /> -
    + {noOverlap && ( +

    + These hours do not overlap the sending plan, so warmup has no time to send. Extend this window or switch + to Fixed schedule on the Sending tab. +

    + )} + + update({ warmup_days })} + inheritedDays={persona ? (persona.enabled ? persona.weekdays : 127) : undefined} + allowFollow={!inCloud} + />
    @@ -2347,6 +2398,7 @@ function SettingsTab({ form, update, mailbox, onDisconnected }: { form: Inbox; u ); return (
    +
    Sender profile diff --git a/web/src/components/app/emails/MailboxAllowanceDialog.tsx b/web/src/components/app/emails/MailboxAllowanceDialog.tsx index ef629cbb3..39905568b 100644 --- a/web/src/components/app/emails/MailboxAllowanceDialog.tsx +++ b/web/src/components/app/emails/MailboxAllowanceDialog.tsx @@ -30,6 +30,7 @@ import { XIcon, } from "lucide-react"; import { useUpgradeDialog } from "@/hooks/context/upgrade"; +import useFeatureAccess from "@/hooks/useFeatureAccess"; import { useConfirm } from "@/hooks/context/confirm"; import { useCurrentOrg } from "@/stores/useAppStore"; import { DitherMeter, type DitherTone } from "@/components/ui/dither"; @@ -185,6 +186,7 @@ function Body({ onClose: () => void; }) { const upgrade = useUpgradeDialog(); + const trial = useFeatureAccess().trial; const cap = a.allowance; const full = cap != null && (a.remaining ?? 0) <= 0; const pct = cap ? Math.min(100, Math.round((a.used / cap) * 100)) : 0; @@ -192,7 +194,11 @@ function Body({ const planLabel = a.plan_name || getPlan(currentPlan).label; const next = a.paid ? nextPlanWithMore(a, currentPlan) : null; - const title = reached + // A workspace without a plan that never had the free allowance holds none. + const needsPlan = !a.paid && cap === 0; + const title = needsPlan + ? "Mailboxes start with a plan" + : reached ? full ? "You've reached your mailbox allowance" : "This connect would pass your mailbox allowance" @@ -218,11 +224,11 @@ function Body({

    {title}

    - +

    - {cap != null && ( + {cap != null && !needsPlan && (
    Connected mailboxes @@ -238,7 +244,9 @@ function Body({ : a.basis === "override" ? "Raised for this workspace by an approved request" : a.basis === "free" - ? "Free workspace" + ? trial + ? "Free trial" + : "Free plan" : `Set by ${planLabel}`}
    @@ -267,7 +275,11 @@ function Body({ openPlans( "More mailboxes", "starter", - `A free workspace holds ${cap?.toLocaleString() ?? "10"} mailboxes. A paid plan holds one for every send a day it includes, and more on request.`, + needsPlan + ? "A paid plan holds one mailbox for every send a day it includes, and more on request. Every plan warms its mailboxes in the premium pool." + : trial + ? `Your trial holds ${cap?.toLocaleString() ?? "2"} mailboxes. A paid plan holds one for every send a day it includes, and more on request.` + : `Your free plan holds ${cap?.toLocaleString() ?? "10"} mailboxes. A paid plan holds one for every send a day it includes, and more on request.`, ) } className="mt-2.5 h-7 px-3 rounded-md bg-slate-900 hover:bg-slate-800 text-white text-[12px] font-medium inline-flex items-center gap-1.5 transition-colors" @@ -329,16 +341,26 @@ function Body({ ); } -function Explanation({ a, planLabel }: { a: MailboxAllowance; planLabel: string }) { +function Explanation({ a, planLabel, trial }: { a: MailboxAllowance; planLabel: string; trial: boolean }) { switch (a.basis) { case "unlimited": return <>There is no cap on mailboxes here. Connect as many as you need.; case "free": - return ( + if (trial) { + return ( + <> + Your free trial holds up to {a.allowance?.toLocaleString()} mailboxes, warming in the free pool. A + paid plan holds more and warms them in the premium pool. + + ); + } + return a.allowance ? ( <> - A free workspace holds up to {a.allowance?.toLocaleString()} mailboxes for warmup. Sending, and mailboxes + Your free plan holds up to {a.allowance.toLocaleString()} mailboxes for warmup. Sending, and mailboxes without a fixed cap, come with a plan. + ) : ( + <>Connecting and warming mailboxes starts with a plan. Every plan warms its mailboxes in the premium pool. ); case "override": return ( diff --git a/web/src/components/app/emails/SendPauseNotice.tsx b/web/src/components/app/emails/SendPauseNotice.tsx new file mode 100644 index 000000000..fc35b74d0 --- /dev/null +++ b/web/src/components/app/emails/SendPauseNotice.tsx @@ -0,0 +1,73 @@ +import { Link } from "@tanstack/react-router"; +import toast from "react-hot-toast/headless"; +import { GlobeIcon, PauseCircleIcon, PlayIcon } from "lucide-react"; +import type React from "react"; +import type { SendPause } from "@/lib/api/models/app/analytics/AccountStatus"; +import useResumeSending from "@/lib/api/hooks/app/emails/useResumeSending"; +import type { AppError } from "@/lib/api/client/normalizeError"; +import buildError from "@/lib/helper/buildError"; +import { usePermission } from "@/hooks/usePermission"; +import { relativeTime } from "@/lib/unibox/messageDetails"; +import { sendPauseCopy, sendPauseResumesAt } from "@/lib/sendPause"; + +// The drawer's account of a provider pause: why, until when, the provider's words and the one action that helps. +export default function SendPauseNotice({ mailboxId, address, pause, reconnect }: { mailboxId: string; address: string; pause: SendPause; reconnect?: React.ReactNode }) { + const copy = sendPauseCopy(pause); + const canManage = usePermission("MANAGE_EMAILS"); + const resume = useResumeSending(mailboxId); + const at = sendPauseResumesAt(pause); + const domain = address.split("@")[1]?.toLowerCase(); + const onResume = () => + resume.mutate(undefined, { + onSuccess: (r) => toast.success(r.hold_released || r.cooldown_cleared ? "Sending resumed" : "Sending was not paused anymore"), + onError: (e) => toast.error(buildError(e as unknown as AppError)), + }); + + return ( +
    +
    + +
    +

    {copy.title}

    + {at && ( +

    + {pause.held ? "Next automatic try " : "Paused until "} + {at.toLocaleString()} ({relativeTime(at)}) +

    + )} +

    {copy.body}

    + {pause.provider_message && ( +

    + The provider said: + {pause.provider_message} +

    + )} + {(copy.action === "fix_dns" || (pause.resumable && canManage)) && ( +
    + {copy.action === "fix_dns" && domain && ( + + Fix DNS for {domain} + + )} + {pause.resumable && canManage && ( + + )} +
    + )} + {copy.action === "reconnect" && reconnect} +
    +
    +
    + ); +} diff --git a/web/src/components/app/emails/SendingBehaviorTab.tsx b/web/src/components/app/emails/SendingBehaviorTab.tsx index 3429a23a0..7f7a0679b 100644 --- a/web/src/components/app/emails/SendingBehaviorTab.tsx +++ b/web/src/components/app/emails/SendingBehaviorTab.tsx @@ -356,7 +356,7 @@ export default function SendingBehaviorTab({ mailboxId, timezone }: { mailboxId: setValue={(v) => update({ weekdays: v })} />

    - Days this mailbox sends anything at all, cold outreach and warmup alike. + Campaign working days. Warmup follows these only when its Sending days is set to Follow sending plan.

    diff --git a/web/src/components/app/emails/WarmupDaysPicker.test.tsx b/web/src/components/app/emails/WarmupDaysPicker.test.tsx new file mode 100644 index 000000000..ad34c2031 --- /dev/null +++ b/web/src/components/app/emails/WarmupDaysPicker.test.tsx @@ -0,0 +1,35 @@ +import { useState } from "react"; +import { fireEvent, render, screen } from "@testing-library/react"; +import { describe, expect, it } from "vitest"; +import WarmupDaysPicker from "./WarmupDaysPicker"; + +function Picker() { + const [days, setDays] = useState(0); + return ; +} + +describe("warmup day selection", () => { + it("shows inherited days and lets the customer add weekends without changing campaign days", () => { + render(); + expect(screen.getByText("Following sending plan: Monday to Friday.")).toBeInTheDocument(); + expect(screen.getByRole("button", { name: "Monday" })).toHaveAttribute("aria-pressed", "true"); + expect(screen.getByRole("button", { name: "Saturday" })).toHaveAttribute("aria-pressed", "false"); + fireEvent.click(screen.getByRole("button", { name: "Saturday" })); + expect(screen.getByRole("button", { name: "Saturday" })).toHaveAttribute("aria-pressed", "true"); + expect(screen.getByRole("button", { name: "Follow sending plan" })).toHaveAttribute("aria-pressed", "false"); + expect(screen.getByText(/Campaign working days stay separate/)).toBeInTheDocument(); + fireEvent.click(screen.getByRole("button", { name: "Follow sending plan" })); + expect(screen.getByRole("button", { name: "Saturday" })).toHaveAttribute("aria-pressed", "false"); + }); + + it("selects every day explicitly and keeps at least one selected day", () => { + render(); + fireEvent.click(screen.getByRole("button", { name: "Every day" })); + for (const day of ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]) { + expect(screen.getByRole("button", { name: day })).toHaveAttribute("aria-pressed", "true"); + fireEvent.click(screen.getByRole("button", { name: day })); + } + expect(screen.getByRole("button", { name: "Sunday" })).toHaveAttribute("aria-pressed", "true"); + expect(screen.getByRole("button", { name: "Follow sending plan" })).toHaveAttribute("aria-pressed", "false"); + }); +}); diff --git a/web/src/components/app/emails/WarmupDaysPicker.tsx b/web/src/components/app/emails/WarmupDaysPicker.tsx new file mode 100644 index 000000000..93ad21ad5 --- /dev/null +++ b/web/src/components/app/emails/WarmupDaysPicker.tsx @@ -0,0 +1,51 @@ +import { warmupDaysLabel } from "@/lib/warmupSchedule"; +import WeekdayBitmask from "@/components/app/campaigns/schedule/WeekdayBitmask"; + +const WEEKDAYS = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]; + +export default function WarmupDaysPicker({ value, onChange, inheritedDays, allowFollow = true }: { + value: number; + onChange: (days: number) => void; + inheritedDays?: number; + allowFollow?: boolean; +}) { + const effectiveDays = value || inheritedDays; + return ( +
    +
    + {[ + { days: 0, label: "Follow sending plan" }, + { days: 127, label: "Every day" }, + { days: 31, label: "Weekdays" }, + ].filter(({ days }) => allowFollow || days !== 0).map(({ days, label }) => ( + + ))} +
    + {effectiveDays !== undefined && ( + { if (days !== 0) onChange(days); }} + /> + )} +

    + {value === 0 + ? inheritedDays === undefined + ? "Uses sending-plan days, or every day with Fixed schedule." + : `Following sending plan: ${warmupDaysLabel(inheritedDays)}.` + : `Warmup days: ${warmupDaysLabel(value)}. Every selected day applies, including weekends. Campaign working days stay separate.`} +

    +

    + Select at least one day. Sending-plan hours and breaks still apply while the plan is on. +

    +
    + ); +} diff --git a/web/src/components/app/emails/domains/BulkSetupDialog.tsx b/web/src/components/app/emails/domains/BulkSetupDialog.tsx index 5915489b1..ebbe21aad 100644 --- a/web/src/components/app/emails/domains/BulkSetupDialog.tsx +++ b/web/src/components/app/emails/domains/BulkSetupDialog.tsx @@ -21,7 +21,6 @@ import { Chip } from "./parts"; import { PerDomainList, type DomainOverride, type PerDomainRow } from "./PerDomainList"; import { ServedByPicker } from "./RedirectServing"; import { defaultServer, useCloudServing } from "./cloudServing"; -import CloudConnectDialog from "@/components/app/cloud/CloudConnectDialog"; export interface BulkSetupIntent { domains: string[]; @@ -68,7 +67,6 @@ function Dialog({ const [url, setUrl] = React.useState(website); const cloud = useCloudServing(); const [servedPick, setServedPick] = React.useState(null); - const [connecting, setConnecting] = React.useState(false); // A Cloud pick Cloud can no longer take falls back, so what is shown is what is sent. const server = servedPick === "cloud" && !cloud.canServe ? "instance" : (servedPick ?? defaultServer(cloud)); const [phase, setPhase] = React.useState("form"); @@ -348,7 +346,7 @@ function Dialog({ {up && url.trim() !== "" &&

    {up}

    }

    {OWN_DOMAIN_HINT}

    {cloud.choosable && ( - setConnecting(true)} cloud={cloud} /> + )} {keeping > 0 && (

    @@ -529,17 +527,6 @@ function Dialog({ )}

    - setConnecting(false)} - autoStart - intro="Link this instance to a Warmbly Cloud workspace, free to create, and Cloud serves these redirects and their certificates. Nothing on your server changes: you only point each domain's DNS at Cloud. Approve the code below on Warmbly Cloud to finish." - doneLabel="Use Warmbly Cloud" - onDone={() => { - setConnecting(false); - setServedPick("cloud"); - }} - /> ); } diff --git a/web/src/components/app/emails/domains/RedirectRescue.tsx b/web/src/components/app/emails/domains/RedirectRescue.tsx index f9e3951ce..e6a609a3b 100644 --- a/web/src/components/app/emails/domains/RedirectRescue.tsx +++ b/web/src/components/app/emails/domains/RedirectRescue.tsx @@ -8,7 +8,6 @@ import { useSetDomainRedirect } from "@/lib/api/hooks/app/emails/useSendingDomai import { useConfirm } from "@/hooks/context/confirm"; import type { AppError } from "@/lib/api/client/normalizeError"; import buildError from "@/lib/helper/buildError"; -import CloudConnectDialog from "@/components/app/cloud/CloudConnectDialog"; import { PROXY_NAMES, redirectBlocked } from "./rules"; import { useCloudServing } from "./cloudServing"; @@ -18,7 +17,6 @@ export default function RedirectRescue({ all, onOpenDomain }: { all: SendingDoma const cloud = useCloudServing(); const confirm = useConfirm(); const save = useSetDomainRedirect(); - const [connecting, setConnecting] = React.useState(false); const [moving, setMoving] = React.useState<{ done: number; of: number } | null>(null); const [hidden, setHidden] = React.useState(() => localStorage.getItem(DISMISS_KEY) ?? ""); @@ -115,19 +113,17 @@ export default function RedirectRescue({ all, onOpenDomain }: { all: SendingDoma > Fix on my server - {(cloud.canServe || !cloud.connected) && ( + {cloud.canServe && ( )}
    - setConnecting(false)} - autoStart - intro={ - <> - Link this instance to a Warmbly Cloud workspace, free to create, and Cloud serves{" "} - {n === 1 ? {stuck[0].domain} : `these ${n} redirects`} and{" "} - {n === 1 ? "its certificate" : "their certificates"}. Nothing on your server changes: you only point the DNS at Cloud. Approve - the code below on Warmbly Cloud to finish. - - } - doneLabel={n === 1 ? `Serve ${stuck[0].domain} from Warmbly Cloud` : `Serve ${n} redirects from Warmbly Cloud`} - onDone={() => { - setConnecting(false); - void moveAll(stuck); - }} - /> ); } diff --git a/web/src/components/app/emails/domains/RedirectServing.tsx b/web/src/components/app/emails/domains/RedirectServing.tsx index 59cc1e779..df5856d8b 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 type { DomainRedirect, RedirectServer } from "@/lib/api/models/app/emails/SendingDomain"; +import { + AlertTriangleIcon, + CheckCircle2Icon, + CircleDashedIcon, + CloudIcon, + ExternalLinkIcon, + Loader2Icon, + RefreshCwIcon, + ServerIcon, + ZapIcon, +} from "lucide-react"; +import type { DNSRecordPurpose, 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, type RecordRow } from "./parts"; +import { PROXY_NAMES, redirectBlocked, shortUrl } from "./rules"; import type { CloudServing } from "./cloudServing"; /* ── Served from ─────────────────────── */ @@ -15,43 +25,23 @@ export function ServedByPicker({ value, current, onChange, - onConnect, cloud, }: { value: RedirectServer; /** Where it is served today, so an existing Cloud redirect stays selectable at the limit. */ current?: RedirectServer; onChange: (v: RedirectServer) => void; - /** Opens the link to Warmbly Cloud in place. */ - onConnect: () => void; cloud: CloudServing; }) { // A redirect already on Cloud stays selectable at the limit, never once the link or the offer is gone. const cloudOpen = cloud.canServe || (current === "cloud" && cloud.connected && !!cloud.offer?.available); let cloudBody: React.ReactNode; - if (!cloud.connected) { - cloudBody = ( - <> - Link this instance to a free Warmbly Cloud workspace and it serves the redirect, with nothing to set up here. - - - - - ); - } else if (!cloud.offer?.available) { + 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 +121,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. +

    + )}
    ); } @@ -272,6 +378,10 @@ function initialProxy(proxy?: string): ProxyKey { return proxy === "nginx" || proxy === "caddy" ? proxy : "traefik"; } +function recordRows(redirect: DomainRedirect, purpose: DNSRecordPurpose): RecordRow[] { + return redirect.records.filter((r) => r.purpose === purpose).map((r, i) => ({ key: `${purpose}-${i}`, type: r.type, name: r.name, value: r.value })); +} + function CodeLine({ code }: { code: string }) { return (
    @@ -289,15 +399,12 @@ export function ReachFix({ redirect, cloud, onServeFromCloud, - onConnect, switching, }: { domain: string; redirect: DomainRedirect; cloud: CloudServing; onServeFromCloud: () => void; - /** Opens the link to Warmbly Cloud in place; serving from it follows. */ - onConnect: () => void; switching: boolean; }) { const reach = redirect.reach; @@ -307,9 +414,22 @@ export function ReachFix({ const host = redirect.serve_host || "your tracking host"; const www = redirect.include_www; const named = reach.proxy ? PROXY_NAMES[reach.proxy] : ""; + const edge = reach.hint === "edge_record" || reach.hint === "edge_inactive"; let intro: React.ReactNode; let showProxies = true; - if (redirect.served_by === "cloud") { + // The records to add in place of what Cloudflare refused, shown without the state of the records they replace. + let fixRecords: RecordRow[] = []; + if (reach.hint === "edge_record") { + intro = `Cloudflare refuses ${domain} because its A or AAAA records point straight at Cloudflare's own addresses. Delete every A and AAAA record on ${domain}, then add what is listed here, set to DNS only (grey cloud):`; + fixRecords = [...recordRows(redirect, "root"), ...recordRows(redirect, "edge")]; + showProxies = false; + } else if (reach.hint === "edge_inactive") { + fixRecords = recordRows(redirect, "edge"); + intro = fixRecords.length + ? `Cloudflare receives visits to ${domain} but has not activated it yet, because it could not confirm the domain points here. Add this record and it activates within a few minutes:` + : null; + showProxies = false; + } else if (redirect.served_by === "cloud") { intro = `Warmbly Cloud serves ${domain}, but the check did not reach it. Make sure the root records point only at the addresses below, and remove any other A or AAAA record for ${domain}.`; showProxies = false; } else { @@ -344,7 +464,8 @@ export function ReachFix({
    How to fix it
    -

    {intro}

    + {intro &&

    {intro}

    } + {fixRecords.length > 0 && } {reach.hint === "host_header" && redirect.served_by !== "cloud" && } {showProxies && ( <> @@ -389,37 +510,22 @@ export function ReachFix({ )}

    After changing it, press Check now. Warmbly also checks again every 10 minutes.

    - {redirect.served_by !== "cloud" && cloud.choosable && (cloud.canServe || !cloud.connected) && ( + {redirect.served_by !== "cloud" && cloud.canServe && !edge && (

    Or skip the proxy work

    -

    - {cloud.canServe - ? "Warmbly Cloud can serve this redirect and its certificate. You replace the root records; nothing changes on your server." - : "Link this instance to a free Warmbly Cloud workspace and it can serve this redirect and its certificate, with nothing to change on your server. It takes about a minute."} -

    +

    Warmbly Cloud can serve this redirect and its certificate. You replace the root records; nothing changes on your server.

    - {cloud.canServe ? ( - - ) : ( - - )} +
    diff --git a/web/src/components/app/emails/domains/SendingDomainDrawer.tsx b/web/src/components/app/emails/domains/SendingDomainDrawer.tsx index 5ea27a4e7..3b3717c0c 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,9 +52,8 @@ 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 { OWN_DOMAIN_HINT, REDIRECT_NOT_OWN_DOMAIN, @@ -61,8 +68,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 }[] = [ @@ -71,7 +90,7 @@ const TABS: { key: DomainTab; label: string; icon: typeof GlobeIcon }[] = [ { key: "redirect", label: "Redirect", icon: GlobeIcon }, ]; -const PURPOSE_LABEL: Record = { ownership: "Ownership", root: "Root", www: "www" }; +const PURPOSE_LABEL: Record = { ownership: "Ownership", root: "Root", www: "www", edge: "Activation" }; const paneVariants = { enter: (dir: 1 | -1) => ({ x: dir * 24, opacity: 0 }), @@ -998,13 +1017,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(""); - // "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); + // 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); const url = urlDraft ?? redirect?.target_url ?? ""; const www = wwwDraft ?? redirect?.include_www ?? true; @@ -1019,7 +1037,7 @@ function DnsRedirect({ const toCloud = server === "cloud"; function resetDrafts() { - setRefused(""); + setProof(null); setUrlDraft(null); setWwwDraft(null); setServedDraft(null); @@ -1033,7 +1051,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 +1065,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. @@ -1078,27 +1111,13 @@ function DnsRedirect({ ); } - // Once linked, the dialog's own button is the go-ahead. - async function afterLinked() { - const why = connecting; - setConnecting(null); - if (!redirect || why !== "serve") { - setServedDraft("cloud"); - return; - } - try { - await persist(redirect.target_url, redirect.include_www, "cloud"); - } catch (e) { - toast.error(buildError(e as AppError)); - } - } - async function checkNow() { if (verify.isPending) return; 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 +1142,72 @@ 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={ + + } + /> )}
    + {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}
    @@ -1182,7 +1220,6 @@ function DnsRedirect({ value={server} current={redirect?.served_by} onChange={setServedDraft} - onConnect={() => setConnecting("pick")} cloud={cloud} /> )} @@ -1190,11 +1227,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.`}

    + {redirect.records.some((r) => r.purpose === "root" && r.type === "CNAME") && ( +

    + A root CNAME works where your DNS provider flattens it, as Cloudflare does on its own. Elsewhere, add it as an ALIAS or ANAME record. If your provider has neither, use its domain forwarding to send {domain.domain} to your website instead. +

    + )} + {redirect.records.some((r) => r.purpose === "edge") && ( +

    + The activation record is only needed while it is listed. It goes away once the domain is live. +

    + )}
    )} @@ -1244,21 +1288,6 @@ function DnsRedirect({
    )} - - setConnecting(null)} - autoStart - intro={ - <> - Link this instance to a Warmbly Cloud workspace, free to create, and Cloud serves{" "} - {domain.domain}'s redirect and its certificate. Nothing on your - server changes: you only point the domain's DNS at Cloud. Approve the code below on Warmbly Cloud to finish. - - } - doneLabel={redirect && connecting === "serve" ? `Serve ${domain.domain} from Warmbly Cloud` : "Use Warmbly Cloud"} - onDone={() => void afterLinked()} - />
    ); } diff --git a/web/src/components/app/emails/domains/cloudServing.ts b/web/src/components/app/emails/domains/cloudServing.ts index c7872c13f..807d50aaf 100644 --- a/web/src/components/app/emails/domains/cloudServing.ts +++ b/web/src/components/app/emails/domains/cloudServing.ts @@ -6,7 +6,7 @@ import type { PoolLinkRedirectOffer } from "@/lib/api/models/app/cloudlink/Cloud import type { RedirectServer } from "@/lib/api/models/app/emails/SendingDomain"; export interface CloudServing { - /** Only a self-hosted instance's administrator picks, since it forwards credentials off the server; Warmbly Cloud always serves its own. */ + /** Only an already-linked self-hosted instance's administrator picks; Warmbly Cloud always serves its own. */ choosable: boolean; connected: boolean; offer: PoolLinkRedirectOffer | null; @@ -17,12 +17,13 @@ export interface CloudServing { export function useCloudServing(): CloudServing { const auth = useAuthConfig(); const instanceAdmin = useInstanceAdmin(); - const choosable = !!auth.data?.self_hosted && instanceAdmin.allowed; - const status = useCloudLinkStatus(choosable, 60_000); - const offer = choosable ? (status.data?.info?.redirects ?? null) : null; - const connected = choosable && !!status.data?.connected; + const admin = !!auth.data?.self_hosted && instanceAdmin.allowed; + const status = useCloudLinkStatus(admin, 60_000); + const connected = admin && !!status.data?.connected; + const offer = connected ? (status.data?.info?.redirects ?? null) : null; return { - choosable, + // Only an existing link serves redirects; Warmbly Cloud links no new instances. + choosable: connected, connected, offer, canServe: connected && !!status.data?.link?.organization_id && !!offer?.available && offer.used < offer.limit, 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/emails/import/MailboxImportsMenu.tsx b/web/src/components/app/emails/import/MailboxImportsMenu.tsx index e3249f4b9..c3753e22e 100644 --- a/web/src/components/app/emails/import/MailboxImportsMenu.tsx +++ b/web/src/components/app/emails/import/MailboxImportsMenu.tsx @@ -65,7 +65,7 @@ function jobState(job: MailboxImport): JobState { if (authorizing > 0) { return { text: `Authorizing ${plural(authorizing, "mailbox", "mailboxes")}`, - hint: `${vendorLabel(job.vendor) || "The inbox vendor"} is approving Warmbly. This can take up to an hour and they connect on their own; open it to connect them sooner.`, + hint: `${vendorLabel(job.vendor) || "The inbox vendor"} is approving Warmbly, signing in to each Google mailbox where it can. This can take up to an hour and they connect on their own; open it to connect them sooner.`, tone: "waiting", }; } diff --git a/web/src/components/app/emails/import/ReviewStep.tsx b/web/src/components/app/emails/import/ReviewStep.tsx index 58eb19386..7779574bf 100644 --- a/web/src/components/app/emails/import/ReviewStep.tsx +++ b/web/src/components/app/emails/import/ReviewStep.tsx @@ -151,7 +151,7 @@ export default function ReviewStep({ - +
    ); } diff --git a/web/src/components/app/emails/import/RowFixEditor.tsx b/web/src/components/app/emails/import/RowFixEditor.tsx index 4d6e9734c..0fcdb15ff 100644 --- a/web/src/components/app/emails/import/RowFixEditor.tsx +++ b/web/src/components/app/emails/import/RowFixEditor.tsx @@ -1,4 +1,4 @@ -// RowFixEditor: a failed row's new password or servers, saved with PATCH +// RowFixEditor: a failed or sign-in row's new password or servers, saved with PATCH // /emails/imports/:id/rows/:line, which re-seals the row and queues it again. import React from "react"; import { AnimatePresence, motion } from "framer-motion"; @@ -14,6 +14,7 @@ import type { AppError } from "@/lib/api/client/normalizeError"; import buildError from "@/lib/helper/buildError"; import { mailHostLabel } from "@/lib/mailHost"; import { cn } from "@/lib/utils"; +import { isGoogleServer, looksLikeGoogleAppPassword } from "./importFields"; // Hosts that take only an app password over IMAP and SMTP. const APP_PASSWORD_HOSTS = new Set(["google_workspace", "gmail", "yahoo", "aol", "icloud", "fastmail", "yandex"]); @@ -62,9 +63,11 @@ export default function RowFixEditor({ if (smtpFix) body.smtp = smtpFix; if (imapFix) body.imap = imapFix; const empty = Object.keys(body).length === 0; + const googleRow = smtp.host.trim() ? isGoogleServer(smtp.host) : row.mail_host === "google_workspace" || row.mail_host === "gmail"; + const notAppPassword = googleRow && !!secret && !looksLikeGoogleAppPassword(secret); async function save() { - if (empty || fix.isPending) return; + if (empty || notAppPassword || fix.isPending) return; try { await fix.mutateAsync({ line: row.line, fix: body }); toast.success(`${row.email || `Line ${row.line}`} is queued again`); @@ -154,8 +157,12 @@ export default function RowFixEditor({
    - - {empty ? "Enter a new password or change a server to retry this row." : "The row is checked again right after saving."} + + {notAppPassword + ? "Google needs the 16-letter app password, not the account password." + : empty + ? "Enter a new password or change a server to retry this row." + : "The row is checked again right after saving."} )} + {passwordCause && canRetry && notAppPassword && ( +

    Google needs the 16-letter app password, not the account password.

    + )}
    ); } diff --git a/web/src/components/app/emails/import/SettingsSection.tsx b/web/src/components/app/emails/import/SettingsSection.tsx index cafe3c8c3..349b208b6 100644 --- a/web/src/components/app/emails/import/SettingsSection.tsx +++ b/web/src/components/app/emails/import/SettingsSection.tsx @@ -7,7 +7,7 @@ import type { MailboxImportSettings, OnExisting } from "@/lib/api/models/app/ema import { Label, NumberInput, TextInput } from "@/components/ui/field"; import { SelectMenu, type SelectOption } from "@/components/ui/select-menu"; import TagSelector from "@/components/app/popup/select/TagSelector"; -import { OptionSelect, Toggle } from "@/components/app/campaigns/preferences/components/CampaignPreferenceBoolBox"; +import { OptionSelect } from "@/components/app/campaigns/preferences/components/CampaignPreferenceBoolBox"; import useFeatureStatus from "@/lib/api/hooks/app/subscription/useFeatureStatus"; import { useUserProfile } from "@/hooks/context/user"; import { cn } from "@/lib/utils"; @@ -23,6 +23,8 @@ const DEFAULTS = { warmup_reply_rate: 30, }; +type WarmupChoice = "rows" | "on" | "off"; + // What "update" replaces depends on what the rows carry. const UPDATE_COPY: Record<"file" | "vendor" | "grant", { label: string; hint: string }> = { file: { label: "Update password and settings", hint: "The row's password, servers and settings replace the stored ones." }, @@ -61,11 +63,14 @@ export function SettingsSection({ settings, setSettings, note, + fromFile = false, }: { settings: MailboxImportSettings; setSettings: React.Dispatch>; /** A line under the header, e.g. what wins over these values. */ note?: string; + /** The rows come from a file whose columns can carry their own settings. */ + fromFile?: boolean; }) { const [open, setOpen] = React.useState(false); const profile = useUserProfile(); @@ -82,7 +87,9 @@ export function SettingsSection({ const tagIds = settings.tag_ids ?? []; const dailyLimit = settings.daily_limit ?? DEFAULTS.daily_limit; const minutes = Math.round((settings.min_wait ?? DEFAULTS.min_wait) / 60); - const warmup = canWarmup && (settings.warmup ?? true); + // Unset leaves each row's own warmup value (or the mailbox) as it is; an explicit off wins over every row. + const warmupChoice: WarmupChoice = settings.warmup === undefined ? "rows" : settings.warmup ? "on" : "off"; + const warmup = canWarmup && warmupChoice !== "off"; const changed = Object.keys(settings).length; const timezoneOptions = React.useMemo( @@ -141,15 +148,27 @@ export function SettingsSection({
    -
    -
    -
    Warmup
    -
    - {canWarmup ? "Starts on every new mailbox and ramps up slowly." : "Warmup is available on paid plans."} -
    -
    - set("warmup", v)} disabled={!canWarmup} ariaLabel="Warmup" /> +
    +
    Warmup
    + {!canWarmup &&
    Warmup is available on paid plans.
    }
    + {canWarmup && ( + + value={warmupChoice} + onChange={(v) => set("warmup", v === "rows" ? undefined : v === "on")} + cols={3} + aria-label="Warmup" + options={[ + { + value: "rows", + label: fromFile ? "As each row says" : "Leave as it is", + hint: fromFile ? "A row's warmup column decides. Without one, warmup is left as it is." : "New mailboxes start without warmup; connected ones keep theirs.", + }, + { value: "on", label: "On", hint: fromFile ? "Starts and ramps up slowly, unless a row turns it off." : "Starts on every mailbox and ramps up slowly." }, + { value: "off", label: "Off", hint: fromFile ? "Off on every mailbox the import touches, whatever a row says." : "Off on every mailbox the import touches." }, + ]} + /> + )} {warmup && (
    diff --git a/web/src/components/app/emails/import/grants/GrantAdminStep.tsx b/web/src/components/app/emails/import/grants/GrantAdminStep.tsx index fde6d5e65..7efc847d6 100644 --- a/web/src/components/app/emails/import/grants/GrantAdminStep.tsx +++ b/web/src/components/app/emails/import/grants/GrantAdminStep.tsx @@ -1,6 +1,6 @@ // Admin grant, the first step when the workspace already holds grants for the -// provider: pick one to connect its mailboxes, check or remove it, or start -// the guided setup of another (GrantSetupSteps). +// provider: pick one to connect its mailboxes, check or remove it, or (Microsoft +// only) start the setup of another (GrantSetupSteps). import toast from "react-hot-toast/headless"; import { ChevronRightIcon, MoreHorizontalIcon, PlusIcon, RefreshCwIcon, SettingsIcon, Trash2Icon } from "lucide-react"; import { @@ -59,8 +59,8 @@ export default function GrantAdminStep({ selectedId: string | null; /** A picked grant; `advance` moves to its users. */ onSelect: (grant: DomainGrant | null, advance: boolean) => void; - /** Starts the guided setup of another grant. */ - onAddNew: () => void; + /** Starts the setup of another grant; absent for Google, whose new grants are retired. */ + onAddNew?: () => void; }) { const enabled = provider === "google" ? config?.google_enabled === true : config?.microsoft_enabled === true; const noun = provider === "google" ? "domain" : "organization"; @@ -75,7 +75,7 @@ export default function GrantAdminStep({ return (
    - {!enabled && } + {!enabled && (provider === "microsoft" || grants.length > 0) && } {grants.length > 0 && (
    @@ -96,7 +96,9 @@ export default function GrantAdminStep({
    )} - {enabled && ( + {provider === "google" && } + + {enabled && onAddNew && ( - )} - - - {dnsOnly ? ( -

    - This instance proves domains with a DNS record. Add the record below, then check it. -

    - ) : ( - - )} - - - {(dnsOpen || dnsOnly) && live && ( - -
    - DNS record -

    - Add this TXT record at the DNS provider for {live.domain}. It is unique to this workspace, and you can remove it - once the domain is connected. -

    - - - -
    -
    - )} -
    - - - {error && ( - - {error.code === DELEGATION_UNAUTHORIZED ? ( - - Google has not applied the authorization yet, or the scopes do not match. Check step 1, wait a few minutes, - then try again.{" "} - - - ) : ( - - {error.text} - - )} - - )} - -
    - ); -} - /** The one step of a Microsoft organization: a Global Administrator approves Warmbly. */ export function MicrosoftConsentStep({ consent, diff --git a/web/src/components/app/emails/import/grants/MailboxGrantDialog.tsx b/web/src/components/app/emails/import/grants/MailboxGrantDialog.tsx index db2bf2de4..8a85eb909 100644 --- a/web/src/components/app/emails/import/grants/MailboxGrantDialog.tsx +++ b/web/src/components/app/emails/import/grants/MailboxGrantDialog.tsx @@ -1,7 +1,6 @@ // MailboxGrantDialog: the admin grant view opened from a mailbox connected // through one, with that grant picked: its status, Check again, removal, and -// its directory for connecting more mailboxes. The sign-in migration opens it -// on the setup of a new domain instead. +// its directory for connecting more mailboxes. import ProviderLogo from "@/components/app/emails/ProviderLogo"; import { GRANT_PROVIDER_LABELS, type GrantProvider } from "@/lib/api/models/app/emails/MailboxSources"; import ImportDialogShell from "../ImportDialogShell"; @@ -11,14 +10,11 @@ export default function MailboxGrantDialog({ open, provider, grantId, - initialDomain, onClose, }: { open: boolean; provider: GrantProvider; grantId?: string; - /** Opens the setup of a new domain with this one filled in. */ - initialDomain?: string; onClose: () => void; }) { return ( @@ -31,10 +27,9 @@ export default function MailboxGrantDialog({ > {({ onAllowance, setDirty }) => ( void; - admin: string; - setAdmin: (v: string) => void; - tried: boolean; - setTried: (v: boolean) => void; - /** The proof belongs to the domain and admin it was asked for. */ - proof: (GoogleGrantStart & { domain: string; admin: string }) | null; - setProof: (p: GoogleDraft["proof"]) => void; - dnsOpen: boolean; - setDnsOpen: (v: boolean) => void; - error: GrantError | null; - setError: (e: GrantError | null) => void; - dirty: boolean; - reset: () => void; -} - -export function useGoogleDraft(initialDomain = ""): GoogleDraft { - const [domain, setDomain] = React.useState(initialDomain); - const [admin, setAdmin] = React.useState(""); - const [tried, setTried] = React.useState(false); - const [proof, setProof] = React.useState(null); - const [dnsOpen, setDnsOpen] = React.useState(false); - const [error, setError] = React.useState(null); - const reset = React.useCallback(() => { - setDomain(""); - setAdmin(""); - setTried(false); - setProof(null); - setDnsOpen(false); - setError(null); - }, []); - const dirty = domain.trim() !== initialDomain.trim() || admin.trim() !== ""; - return { domain, setDomain, admin, setAdmin, tried, setTried, proof, setProof, dnsOpen, setDnsOpen, error, setError, dirty, reset }; -} diff --git a/web/src/components/app/emails/import/importFields.ts b/web/src/components/app/emails/import/importFields.ts index 6c373f143..f6cbc6995 100644 --- a/web/src/components/app/emails/import/importFields.ts +++ b/web/src/components/app/emails/import/importFields.ts @@ -142,7 +142,7 @@ export const ROW_STATUS: Record cancelled: { label: "Cancelled", cls: "text-slate-500 bg-slate-100" }, }; -// A needs_signin row parked while the inbox vendor authorizes Warmbly on its domain; it resumes on its own. +// A needs_signin row parked while the inbox vendor authorizes Warmbly on its domain or signs in as the mailbox; it resumes on its own. export const VENDOR_AUTHORIZING = "vendor_authorizing"; export const AUTHORIZING_STATUS = { label: "Authorizing", cls: "text-sky-700 bg-sky-50" }; @@ -159,6 +159,16 @@ export function isSigninCause(cause: string): boolean { return SIGNIN_CAUSE.test(cause); } +/** Mirrors mailhost.LooksLikeGoogleAppPassword: 16 letters, ends trimmed, spaces ignored. */ +export function looksLikeGoogleAppPassword(s: string): boolean { + return /^[a-z]{16}$/i.test(s.trim().replace(/ /g, "")); +} + +/** Mirrors mailhost.FromServer for Google's servers. */ +export function isGoogleServer(host: string): boolean { + return /(^|\.)(google|gmail|googlemail)\.com\.?$/i.test(host.trim()); +} + /** "3, 7, 9 and 12 more" for a list of line numbers. */ export function linesText(lines: number[], total: number, shown = 6): string { const head = lines.slice(0, shown).join(", "); diff --git a/web/src/components/app/emails/import/vendors/VendorAccountStep.tsx b/web/src/components/app/emails/import/vendors/VendorAccountStep.tsx index 4ca447655..37a157924 100644 --- a/web/src/components/app/emails/import/vendors/VendorAccountStep.tsx +++ b/web/src/components/app/emails/import/vendors/VendorAccountStep.tsx @@ -13,6 +13,7 @@ import { MoreHorizontalIcon, PlugIcon, PlusIcon, + RefreshCwIcon, Trash2Icon, } from "lucide-react"; import { Label, TextInput } from "@/components/ui/field"; @@ -24,13 +25,16 @@ import { PopoverMenuTrigger, } from "@/components/ui/popover-menu"; import { useConfirm } from "@/hooks/context/confirm"; +import { useGrantConfig } from "@/lib/api/hooks/app/emails/useMailboxGrants"; import { useCreateVendorConnection, useDeleteVendorConnection, + useStartVendorReconnect, useUpdateVendorConnection, + useVendorReconnect, } from "@/lib/api/hooks/app/emails/useMailboxVendors"; import type { VendorCatalogEntry, VendorConnection } from "@/lib/api/models/app/emails/MailboxSources"; -import { vendorLabel } from "@/lib/api/models/app/emails/MailboxSources"; +import { reconnectOpen, vendorLabel } from "@/lib/api/models/app/emails/MailboxSources"; import type { AppError } from "@/lib/api/client/normalizeError"; import buildError from "@/lib/helper/buildError"; import timeAgo from "@/lib/helper/timeAgo"; @@ -68,6 +72,8 @@ export default function VendorAccountStep({ onDirtyChange: (dirty: boolean) => void; }) { const confirm = useConfirm(); + // A vendor reconnect ends in a Google sign-in, which needs the instance's Google client. + const googleSignin = !!useGrantConfig(true).data?.google_mailbox_client_id; const [mode, setMode] = React.useState(null); // With nothing saved yet, the vendor grid is the first screen. const current: Mode = mode ?? (connections.length > 0 ? { kind: "list" } : { kind: "vendors" }); @@ -77,6 +83,7 @@ export default function VendorAccountStep({ }, [current.kind, formDirty, onDirtyChange]); const del = useDeleteVendorConnection(); + const reconnect = useStartVendorReconnect(); const leaveForm = (to: Mode) => { if (current.kind === "form" && formDirty) { @@ -115,6 +122,21 @@ export default function VendorAccountStep({ ); }; + const reconnectAll = (conn: VendorConnection) => { + const name = vendorLabel(conn.vendor); + confirm.show( + `Have ${name} sign in again as every Google mailbox imported from ${conn.label}? Each one is reconnected in place with full mail access, keeping its history, campaigns and warmup. A mailbox ${name} cannot sign in to keeps working as it is.`, + async () => { + try { + const out = await reconnect.mutateAsync({ id: conn.id }); + toast.success(`${name} is reconnecting ${plural(out.data.length, "mailbox", "mailboxes")}`); + } catch (e) { + toast.error(buildError(e as AppError)); + } + }, + ); + }; + if (loading) { return (
    @@ -142,6 +164,8 @@ export default function VendorAccountStep({ v.id === conn.vendor)?.signs_in} + onReconnect={() => reconnectAll(conn)} active={conn.id === selectedId} onOpen={() => { if (conn.status === "invalid") { @@ -248,18 +272,28 @@ export default function VendorAccountStep({ function ConnectionRow({ conn, + signsIn, active, onOpen, onUpdate, onRemove, + onReconnect, }: { conn: VendorConnection; + /** The vendor can reconnect its Google mailboxes in place. */ + signsIn: boolean; active: boolean; onOpen: () => void; onUpdate: () => void; onRemove: () => void; + onReconnect: () => void; }) { const invalid = conn.status === "invalid"; + const canReconnect = signsIn && !invalid && conn.mailboxes > 0; + const progress = useVendorReconnect(conn.id, canReconnect).data?.data ?? []; + const pending = progress.filter((m) => reconnectOpen(m.status)).length; + const failed = progress.filter((m) => m.status === "failed").length; + const done = progress.filter((m) => m.status === "connected").length; return (
    )} + {canReconnect && progress.length > 0 && ( +

    0 ? "text-sky-700" : failed > 0 ? "text-rose-700" : "text-emerald-700")}> + {pending > 0 && } + {pending > 0 + ? `Reconnecting ${plural(pending, "Google mailbox", "Google mailboxes")}` + : `Reconnected ${done} of ${progress.length}`} + {failed > 0 && `, ${failed} could not be. Their drawers say why.`} +

    + )}
    {invalid && ( @@ -324,6 +367,11 @@ function ConnectionRow({ } onSelect={onUpdate}> Update key + {canReconnect && ( + } onSelect={onReconnect}> + Reconnect all Google mailboxes + + )} } onSelect={onRemove}> Remove diff --git a/web/src/components/app/emails/migration/MailboxSigninSection.tsx b/web/src/components/app/emails/migration/MailboxSigninSection.tsx new file mode 100644 index 000000000..bcba83fbe --- /dev/null +++ b/web/src/components/app/emails/migration/MailboxSigninSection.tsx @@ -0,0 +1,348 @@ +// The mailbox drawer's Sign-in section: how the mailbox signs in now, and only +// the switches the server says can succeed for it. Every switch keeps the +// mailbox, its history, campaigns and warmup. +import React from "react"; +import toast from "react-hot-toast/headless"; +import { AnimatePresence, motion } from "framer-motion"; +import { + AlertCircleIcon, + ArrowRightIcon, + CheckCircle2Icon, + ChevronDownIcon, + KeyRoundIcon, + Loader2Icon, + RefreshCwIcon, + ShieldCheckIcon, + SparklesIcon, +} from "lucide-react"; +import ProviderLogo from "@/components/app/emails/ProviderLogo"; +import useMailboxSignin from "@/lib/api/hooks/app/emails/useMailboxSignin"; +import { useStartVendorReconnect } from "@/lib/api/hooks/app/emails/useMailboxVendors"; +import { MoveError, useMoveToGrant } from "@/lib/api/hooks/app/emails/useMailboxGrants"; +import { reconnectOpen, vendorLabel, type MailboxSignin, type ReconnectStatus } from "@/lib/api/models/app/emails/MailboxSources"; +import type { AppError } from "@/lib/api/client/normalizeError"; +import buildError from "@/lib/helper/buildError"; +import timeAgo from "@/lib/helper/timeAgo"; +import { cn } from "@/lib/utils"; +import MailboxImportDialog from "../import/MailboxImportDialog"; +import { BlockedByAdminHint, TrustedAppSteps } from "../GoogleWorkspaceSigninPanel"; +import AppPasswordSwitchForm from "./AppPasswordSwitchForm"; +import useGoogleReconnect from "./useGoogleReconnect"; +import { useConfirm } from "@/hooks/context/confirm"; + +type Mailbox = { id: string; email: string }; + +const STATUS_COPY: Record = { + queued: "is about to start", + trusting: "is adding Warmbly as a trusted app on the domain", + signing_in: "is signing in as the mailbox", + connected: "reconnected it", + failed: "could not reconnect it", +}; + +/** What the mailbox signs in with, in a line a person can read. */ +function methodCopy(s: MailboxSignin): { title: string; detail: string; tone: "ok" | "older" | "plain" } { + switch (s.method) { + case "google_signin": + if (s.full_mail_access) { + return { title: "Google sign-in", detail: "Signed in on its own with full mail access, so warmup engagement runs over IMAP.", tone: "ok" }; + } + return { + title: "Google sign-in, older permissions", + detail: "Signed in on its own with the permissions Warmbly asked for before. It keeps working; warmup engagement runs through the Gmail API.", + tone: "older", + }; + case "google_grant": + return { + title: "Domain grant (legacy)", + detail: "Reached through an administrator's domain-wide grant. It keeps working; new grants are no longer offered.", + tone: "older", + }; + case "app_password": + return { title: "App password", detail: "Signs in to Gmail's IMAP and SMTP with an app password.", tone: "plain" }; + } + return { title: "", detail: "", tone: "plain" }; +} + +/** The live standing of the mailbox's last vendor reconnect. */ +function SwitchStatus({ s }: { s: MailboxSignin }) { + const sw = s.switch; + if (!sw) return null; + const vendor = vendorLabel(s.options.vendor?.vendor) || "The vendor"; + const open = reconnectOpen(sw.status); + // A finished reconnect says so for a day; the method line carries it after that. + if (sw.status === "connected" && Date.now() - new Date(sw.at).getTime() > 86_400_000) return null; + return ( +
    + {open && } + {sw.status === "failed" && } + {sw.status === "connected" && } +
    +

    + {vendor} {STATUS_COPY[sw.status]} + {sw.automatic ? ", on its own" : ""}. {timeAgo(sw.at)} +

    + {sw.status === "failed" && ( +

    + {sw.message || "The vendor gave no reason."} The mailbox keeps working on its current sign-in. + {sw.automatic ? " Warmbly tries again in a week." : ""} +

    + )} +
    +
    + ); +} + +function OptionRow({ + icon, + title, + detail, + action, + children, +}: { + icon: React.ReactNode; + title: string; + detail: React.ReactNode; + action: React.ReactNode; + children?: React.ReactNode; +}) { + return ( +
    +
    +
    + {icon} +
    +
    {title}
    +
    {detail}
    +
    +
    +
    {action}
    +
    + {children} +
    + ); +} + +const primary = "h-7 px-2.5 rounded-md bg-slate-900 hover:bg-slate-800 text-white text-[12px] font-medium inline-flex items-center gap-1.5 transition-colors"; +const secondary = "h-7 px-2.5 rounded-md border text-[12px] font-medium inline-flex items-center gap-1.5 transition-colors"; + +function Expand({ open, children }: { open: boolean; children: React.ReactNode }) { + return ( + + {open && ( + + {children} + + )} + + ); +} + +export default function MailboxSigninSection({ mailbox }: { mailbox: Mailbox }) { + const q = useMailboxSignin(mailbox.id); + const vendorStart = useStartVendorReconnect(); + const move = useMoveToGrant(); + const google = useGoogleReconnect(); + const [open, setOpen] = React.useState<"google" | "password" | null>(null); + const confirm = useConfirm(); + const [passwordDirty, setPasswordDirty] = React.useState(false); + // Leaving a typed app password asks first; the password is not kept anywhere. + const toggle = (which: "google" | "password") => { + const next = open === which ? null : which; + if (open === "password" && passwordDirty) { + confirm.show("Discard the app password you typed?", async () => setOpen(next)); + return; + } + setOpen(next); + }; + const [importId, setImportId] = React.useState(null); + const s = q.data; + // The dialog outlives the move, which changes what the section shows. + const dialog = setImportId(null)} />; + if (!s || s.method === "other") return dialog; + + const m = methodCopy(s); + const o = s.options; + const vendor = o.vendor ? vendorLabel(o.vendor.vendor) || o.vendor.label : ""; + const switching = reconnectOpen(s.switch?.status); + const anything = !!(o.vendor || o.google_signin || o.grant || o.app_password); + + async function viaVendor() { + if (!o.vendor || switching || vendorStart.isPending) return; + try { + await vendorStart.mutateAsync({ id: o.vendor.connection_id, emailAccountIds: [mailbox.id] }); + toast.success(`${vendor} is reconnecting ${mailbox.email}`); + } catch (e) { + toast.error(buildError(e as AppError)); + } + } + + async function moveIt() { + if (!o.grant || move.isPending) return; + try { + const out = await move.mutateAsync({ grantId: o.grant.id, emails: [mailbox.email] }); + toast.success(`Moving ${mailbox.email} onto the admin grant`); + setImportId(out.job.id); + } catch (e) { + toast.error(e instanceof MoveError ? e.message : buildError(e as AppError)); + } + } + + const reconnecting = google.busy === mailbox.id; + + return ( +
    +
    Sign-in
    +
    + +
    +
    + {m.title} + {m.tone === "ok" && ( + + Full mail access + + )} +
    +

    {m.detail}

    +
    +
    + + + + {s.managed &&

    Warmbly Cloud holds this mailbox's sign-in, so it is changed there.

    } + + {s.auto_switch && !s.switch && ( +

    + + {vendor} reconnects it with full mail access on its own, soon. Nothing to do here. +

    + )} + + {anything && ( +
    + {o.vendor && ( + } + title={`Reconnect through ${vendor}`} + detail={`${vendor} adds Warmbly as a trusted app on the domain and signs in as the mailbox for you. Nothing to click at Google.`} + action={ + + } + /> + )} + {o.google_signin && ( + } + title="Reconnect with Google" + detail="Sign in again with full mail access, once your Workspace admin has marked Warmbly trusted for the domain." + action={ + + } + > + +
    +

    First, your Workspace admin trusts Warmbly, once per domain

    + + + {google.unfinished === mailbox.id && } +
    +
    +
    + )} + {o.grant && ( + } + title={`Move onto the admin grant for ${o.grant.domain}`} + detail="The domain already has an active grant, so the mailbox can connect through it." + action={ + + } + /> + )} + {o.app_password && ( + } + title="Switch to an app password" + detail="Gmail checks the password first; if it is refused, nothing changes." + action={ + + } + > + + setOpen(null)} /> + + + )} +
    + )} + {dialog} +
    + ); +} + +/** The Overview tab's pointer to the Sign-in section, shown only when there is something to see or do. */ +export function SigninPrompt({ mailbox, onOpen }: { mailbox: Mailbox; onOpen: () => void }) { + const s = useMailboxSignin(mailbox.id).data; + if (!s || s.managed) return null; + const sw = s.switch; + const older = (s.method === "google_signin" && !s.full_mail_access) || s.method === "google_grant"; + const live = reconnectOpen(sw?.status) || sw?.status === "failed"; + if (!live && !(older && (s.auto_switch || s.options.vendor || s.options.google_signin || s.options.app_password))) return null; + const vendor = vendorLabel(s.options.vendor?.vendor) || "The vendor"; + let text = "This mailbox uses the older Google sign-in. It keeps working, and you can change how it signs in without losing anything."; + if (s.method === "google_grant") text = "This mailbox connects through a legacy domain grant. It keeps working, and you can change how it signs in without losing anything."; + if (s.auto_switch && !sw) text = `${vendor} reconnects this mailbox with full mail access on its own.`; + if (reconnectOpen(sw?.status)) text = `${vendor} ${sw ? STATUS_COPY[sw.status] : ""}.`; + if (sw?.status === "failed") text = `${vendor} could not reconnect this mailbox. It keeps working on its current sign-in.`; + return ( +
    + +

    + {text}{" "} + +

    +
    + ); +} diff --git a/web/src/components/app/emails/migration/SigninMigrationBanner.tsx b/web/src/components/app/emails/migration/SigninMigrationBanner.tsx index 8c875bfde..8590f3b55 100644 --- a/web/src/components/app/emails/migration/SigninMigrationBanner.tsx +++ b/web/src/components/app/emails/migration/SigninMigrationBanner.tsx @@ -2,11 +2,33 @@ // their own, with optional ways to switch their connection method. // "Later" hides it for a week, per workspace. import React from "react"; -import { AlertTriangleIcon, ArrowRightIcon } from "lucide-react"; +import toast from "react-hot-toast/headless"; +import { AlertTriangleIcon, ArrowRightIcon, Loader2Icon, RefreshCwIcon } from "lucide-react"; import { useCurrentOrg } from "@/stores/useAppStore"; import ProviderLogo from "@/components/app/emails/ProviderLogo"; +import { useStartVendorReconnect } from "@/lib/api/hooks/app/emails/useMailboxVendors"; +import { vendorLabel, type SigninMigration } from "@/lib/api/models/app/emails/MailboxSources"; +import type { AppError } from "@/lib/api/client/normalizeError"; +import buildError from "@/lib/helper/buildError"; import { cn } from "@/lib/utils"; +/** The listed mailboxes a healthy vendor connection can reconnect, one entry per connection. */ +function vendorGroups(groups: SigninMigration[] | undefined) { + const by = new Map(); + for (const g of groups ?? []) { + for (const m of g.mailboxes) { + if (!m.vendor_connection_id || !m.vendor) continue; + const e = by.get(m.vendor_connection_id) ?? { connectionId: m.vendor_connection_id, vendor: m.vendor, ids: [] }; + e.ids.push(m.id); + by.set(m.vendor_connection_id, e); + } + } + return [...by.values()]; +} + +// The server reconnects up to this many mailboxes per request. +const RECONNECT_BATCH = 1000; + const LATER_MS = 7 * 24 * 60 * 60 * 1000; function laterKey(orgId: string) { @@ -21,10 +43,13 @@ function readLater(orgId: string): number { } } -export default function SigninMigrationBanner({ total, onOpen }: { total: number; onOpen: () => void }) { +export default function SigninMigrationBanner({ total, groups, onOpen }: { total: number; groups?: SigninMigration[]; onOpen: () => void }) { const orgId = useCurrentOrg()?.id ?? ""; const [hiddenUntil, setHiddenUntil] = React.useState(() => readLater(orgId)); React.useEffect(() => setHiddenUntil(readLater(orgId)), [orgId]); + const vendors = React.useMemo(() => vendorGroups(groups), [groups]); + const reconnect = useStartVendorReconnect(); + const [busy, setBusy] = React.useState(null); if (total <= 0 || hiddenUntil > Date.now()) return null; @@ -38,16 +63,49 @@ export default function SigninMigrationBanner({ total, onOpen }: { total: number setHiddenUntil(until); }; + async function viaVendor(v: { connectionId: string; vendor: string; ids: string[] }) { + if (busy) return; + setBusy(v.connectionId); + try { + let n = 0; + for (let i = 0; i < v.ids.length; i += RECONNECT_BATCH) { + const out = await reconnect.mutateAsync({ id: v.connectionId, emailAccountIds: v.ids.slice(i, i + RECONNECT_BATCH) }); + n += out.data.length; + } + toast.success(`${vendorLabel(v.vendor)} is reconnecting ${n === 1 ? "1 mailbox" : `${n} mailboxes`}. Each one drops off this list once it is done.`); + } catch (e) { + toast.error(buildError(e as AppError)); + } finally { + setBusy(null); + } + } + return (

    - {total === 1 ? "1 mailbox connects" : `${total.toLocaleString()} mailboxes connect`} with Google sign-in. - You can optionally switch to an admin grant or an app password without losing history. + {total === 1 ? "1 mailbox connects" : `${total.toLocaleString()} mailboxes connect`} with the older Google sign-in. + You can reconnect with the new Google sign-in once your Workspace admin trusts Warmbly, or switch to an app + password, without losing history.

    -
    +
    + {vendors.map((v) => ( + + ))}
    @@ -77,7 +135,7 @@ export function SigninRetiringChip({ onClick, className }: { onClick: () => void e.stopPropagation(); onClick(); }} - title="This mailbox uses Google sign-in. You can optionally switch its connection method." + title="This mailbox uses the older Google sign-in. You can reconnect it with the new Google sign-in or switch to an app password." aria-label="Google sign-in: switch connection method" className={cn( "inline-flex items-center gap-1 h-[18px] pl-0.5 pr-0.5 md:pr-1.5 rounded-full border border-amber-200 bg-amber-50 text-amber-700 hover:bg-amber-100 transition-colors shrink-0", diff --git a/web/src/components/app/emails/migration/SigninMigrationDialog.tsx b/web/src/components/app/emails/migration/SigninMigrationDialog.tsx index 80623a569..57fa17ef5 100644 --- a/web/src/components/app/emails/migration/SigninMigrationDialog.tsx +++ b/web/src/components/app/emails/migration/SigninMigrationDialog.tsx @@ -1,14 +1,15 @@ -// SigninMigrationDialog: every mailbox still on per-mailbox Google sign-in, -// by domain, with the move that fits it. A domain with an admin grant moves -// in one click (an import, shown with the import result screen); a Workspace -// domain without one is set up first; a personal address switches to an app -// password. Every move keeps the mailbox, its history, campaigns and warmup. +// SigninMigrationDialog: every mailbox still on the older per-mailbox Google +// sign-in, by domain, with the move that fits it. A Workspace mailbox +// reconnects with the new Google sign-in once its admin trusts Warmbly, or +// switches to an app password; a domain that already holds an admin grant +// moves onto it in one click; a personal address switches to an app password. +// Every move keeps the mailbox, its history, campaigns and warmup. import React from "react"; import { createPortal } from "react-dom"; import { AnimatePresence, motion } from "framer-motion"; import toast from "react-hot-toast/headless"; import { useIsMutating } from "@tanstack/react-query"; -import { ArrowLeftIcon, ArrowRightIcon, Building2Icon, CheckCircle2Icon, KeyRoundIcon, Loader2Icon, XIcon } from "lucide-react"; +import { ArrowLeftIcon, ArrowRightIcon, CheckCircle2Icon, CheckIcon, KeyRoundIcon, Loader2Icon, RefreshCwIcon, XIcon } from "lucide-react"; import ProviderLogo from "@/components/app/emails/ProviderLogo"; import { useConfirm } from "@/hooks/context/confirm"; import { @@ -27,23 +28,23 @@ import { plural } from "../import/importFields"; import RunStep from "../import/RunStep"; import AppPasswordSwitchForm from "./AppPasswordSwitchForm"; import { migrationRoute, type MigrationRoute } from "./migrationRoute"; +import useGoogleReconnect from "./useGoogleReconnect"; +import { BlockedByAdminHint, TrustedAppSteps } from "../GoogleWorkspaceSigninPanel"; import { SkeletonCards } from "@/components/app/emails/import/Discovering"; export default function SigninMigrationDialog({ open, focusDomain, onClose, - onSetUpDomain, }: { open: boolean; /** Scrolled to and marked, e.g. from one mailbox's row. */ focusDomain?: string | null; onClose: () => void; - /** Opens the whole-domain setup; the dialog closes first. */ - onSetUpDomain: (domain: string) => void; }) { const migration = useSigninMigration(open); - const googleGrants = useGrantConfig(open).data?.google_enabled === true; + const clientId = useGrantConfig(open).data?.google_mailbox_client_id; + const google = useGoogleReconnect(); const confirm = useConfirm(); const [run, setRun] = React.useState<{ importId: string; domain: string } | null>(null); const [dirty, setDirty] = React.useState>(() => new Set()); @@ -95,6 +96,7 @@ export default function SigninMigrationDialog({ return [...all].sort((a, b) => Number(b.domain === focusDomain) - Number(a.domain === focusDomain)); }, [migration.data, focusDomain]); const total = migration.data?.total ?? 0; + const signinGroups = groups.some((g) => migrationRoute(g, !!clientId) === "signin"); return createPortal( @@ -191,17 +193,27 @@ export default function SigninMigrationDialog({ ) : (

    - Switching from Google sign-in is optional. Moving keeps each mailbox, with its history, - campaigns and warmup. + Switching from the older Google sign-in is optional. Reconnecting with the new Google sign-in + moves a mailbox's warmup engagement to IMAP; an app password works too. Either way each mailbox + keeps its history, campaigns and warmup.

    + {signinGroups && ( +
    +

    + Before reconnecting, your Workspace admin trusts Warmbly, once per domain +

    + +
    + )} + {google.unfinished && } {groups.map((g) => ( setRun({ importId, domain: g.domain })} - onSetUp={() => onSetUpDomain(g.domain)} + google={google} setRowDirty={setRowDirty} /> ))} @@ -223,14 +235,14 @@ function GroupCard({ route, focused, onMoved, - onSetUp, + google, setRowDirty, }: { group: SigninMigration; route: MigrationRoute; focused: boolean; onMoved: (importId: string) => void; - onSetUp: () => void; + google: GoogleReconnect; setRowDirty: (id: string, dirty: boolean) => void; }) { const ref = React.useRef(null); @@ -257,12 +269,10 @@ function GroupCard({ const sub = route === "grant" - ? "This domain has an admin grant. Moving signs each mailbox in through it." - : route === "setup" - ? "Set up the whole domain once, then move these mailboxes onto it." - : g.kind === "personal" - ? "A personal address moves to an app password, one mailbox at a time." - : "Admin grants are not set up on this instance, so each mailbox moves to an app password."; + ? "This domain already has an admin grant. Moving signs each mailbox in through it." + : route === "signin" + ? "Reconnect each mailbox with the new Google sign-in once your admin trusts Warmbly, or switch it to an app password." + : "A personal address moves to an app password, one mailbox at a time."; return (
    )} - {route === "setup" && ( - - )}
    {g.mailboxes.map((m) => ( - + ))}
    ); } +type GoogleReconnect = ReturnType; + function MailboxLine({ mailbox: m, appPassword, + google, setRowDirty, }: { mailbox: MigrationMailbox; appPassword: boolean; + /** Offered when the mailbox can reconnect with the new Google sign-in. */ + google?: GoogleReconnect; setRowDirty: (id: string, dirty: boolean) => void; }) { const [open, setOpen] = React.useState(false); const onDirty = React.useCallback((d: boolean) => setRowDirty(m.id, d), [m.id, setRowDirty]); + const reconnected = google?.done.has(m.id) === true; + const reconnecting = google?.busy === m.id; return (
    @@ -338,7 +351,28 @@ function MailboxLine({ {m.status.replace(/_/g, " ")} )} - {appPassword && ( + {reconnected && ( + + + Reconnected + + )} + {google && !reconnected && ( + + )} + {appPassword && !reconnected && ( - )} - {route === "setup" && ( -
    - - Then pick this mailbox under Mailboxes to move it. -
    - )} - {route === "app_password" && } -
    - {dialogs} -
    - ); -} diff --git a/web/src/components/app/emails/migration/migrationRoute.ts b/web/src/components/app/emails/migration/migrationRoute.ts index dcec68d35..4aa49d3da 100644 --- a/web/src/components/app/emails/migration/migrationRoute.ts +++ b/web/src/components/app/emails/migration/migrationRoute.ts @@ -1,10 +1,11 @@ import type { SigninMigration } from "@/lib/api/models/app/emails/MailboxSources"; -/** What a group of mailboxes moves to. */ -export type MigrationRoute = "grant" | "setup" | "app_password"; +/** What a group of mailboxes moves to: a domain's existing grant, the new Google sign-in, or an app password. */ +export type MigrationRoute = "grant" | "signin" | "app_password"; -export function migrationRoute(group: SigninMigration, googleGrants: boolean): MigrationRoute { +/** canSignIn is whether this instance has a Google sign-in client; without one only an app password can work. */ +export function migrationRoute(group: SigninMigration, canSignIn: boolean): MigrationRoute { if (group.kind === "personal") return "app_password"; if (group.grant_id) return "grant"; - return googleGrants ? "setup" : "app_password"; + return canSignIn ? "signin" : "app_password"; } diff --git a/web/src/components/app/emails/migration/useGoogleReconnect.ts b/web/src/components/app/emails/migration/useGoogleReconnect.ts new file mode 100644 index 000000000..1e3558df1 --- /dev/null +++ b/web/src/components/app/emails/migration/useGoogleReconnect.ts @@ -0,0 +1,46 @@ +// useGoogleReconnect: renews a Google sign-in mailbox's consent in place, the +// move off the older Google sign-in once the Workspace admin trusts Warmbly. +import React from "react"; +import toast from "react-hot-toast/headless"; +import { useQueryClient } from "@tanstack/react-query"; +import reauthEmailOAuth from "@/lib/api/client/app/emails/reauthEmailOAuth"; +import onboardOAuthFinish from "@/lib/api/client/app/emails/onboardOAuthFinish"; +import { authorizeEmailInPopup } from "@/lib/emails/emailOAuthPopup"; +import { SIGNIN_MIGRATION_KEY } from "@/lib/api/hooks/app/emails/useMailboxGrants"; +import { MAILBOX_SIGNIN_KEY } from "@/lib/api/hooks/app/emails/useMailboxSignin"; +import type { AppError } from "@/lib/api/client/normalizeError"; +import buildError from "@/lib/helper/buildError"; + +export default function useGoogleReconnect() { + const qc = useQueryClient(); + const [busy, setBusy] = React.useState(null); + // The last reconnect that did not finish, so the caller can explain a Workspace block. + const [unfinished, setUnfinished] = React.useState(null); + const [done, setDone] = React.useState>(() => new Set()); + + // Call it straight from the click: the window opens before the start request. + const reconnect = React.useCallback( + async (mailboxId: string) => { + if (busy) return; + setBusy(mailboxId); + setUnfinished(null); + try { + const { code, state } = await authorizeEmailInPopup(() => reauthEmailOAuth(mailboxId)); + await onboardOAuthFinish(code, state); + toast.success("Reconnected with the new Google sign-in"); + setDone((prev) => new Set(prev).add(mailboxId)); + qc.invalidateQueries({ queryKey: ["emails", "list"] }); + qc.invalidateQueries({ queryKey: MAILBOX_SIGNIN_KEY }); + qc.invalidateQueries({ queryKey: SIGNIN_MIGRATION_KEY }); + } catch (e) { + setUnfinished(mailboxId); + toast.error(e instanceof Error ? e.message : buildError(e as AppError)); + } finally { + setBusy(null); + } + }, + [busy, qc], + ); + + return { busy, unfinished, done, reconnect }; +} diff --git a/web/src/components/app/emails/useMailboxRowActions.ts b/web/src/components/app/emails/useMailboxRowActions.ts new file mode 100644 index 000000000..d0d90caf2 --- /dev/null +++ b/web/src/components/app/emails/useMailboxRowActions.ts @@ -0,0 +1,59 @@ +import { useMemo } from "react"; +import { useMutationState, useQueryClient } from "@tanstack/react-query"; +import toast from "react-hot-toast/headless"; +import { useConfirm } from "@/hooks/context/confirm"; +import { switchOffPrompt } from "@/components/app/emails/useMailboxSwitch"; +import runMutation from "@/lib/api/hooks/runMutation"; +import { warmupLifecycleOptions } from "@/lib/api/hooks/app/emails/useWarmupLifecycle"; +import { removeEmailOptions } from "@/lib/api/hooks/app/emails/useRemoveEmail"; +import { updateEmailOptions } from "@/lib/api/hooks/app/emails/useUpdateEmail"; +import { useEnrollCloudLinkMailbox, useUnenrollCloudLinkMailbox, useCloudLinkMailboxLifecycle } from "@/lib/api/hooks/app/cloudlink/useCloudLink"; +import useCurrentOrganization from "@/lib/api/hooks/app/organizations/useCurrentOrganization"; +import type { WarmupAction } from "@/lib/api/client/app/emails/warmupLifecycle"; +import type { AppError } from "@/lib/api/client/normalizeError"; +import buildError from "@/lib/helper/buildError"; + +// The mailbox list's row actions, held once by the page instead of a set of +// mutation hooks per row. Each write runs under the same per-mailbox key the +// single-mailbox hooks use, so overlapping writes still settle in order. +export default function useMailboxRowActions() { + const queryClient = useQueryClient(); + const confirm = useConfirm(); + const workspaceZone = useCurrentOrganization().data?.timezone; + const { mutateAsync: enroll } = useEnrollCloudLinkMailbox(); + const { mutateAsync: unenroll } = useUnenrollCloudLinkMailbox(); + const { mutateAsync: setCloudLifecycle } = useCloudLinkMailboxLifecycle(); + + // Mailboxes with a warmup change in flight, for the row's menu trigger. + const warmupKeys = useMutationState({ + filters: { status: "pending", predicate: (m) => m.options.mutationKey?.[0] === "emails" && m.options.mutationKey?.[2] === "warmup" }, + select: (m) => String(m.options.mutationKey?.[1]), + }); + const warmupPending = useMemo(() => new Set(warmupKeys), [warmupKeys]); + + return useMemo(() => { + const setPower = async (id: string, email: string, on: boolean) => { + try { + await runMutation(queryClient, updateEmailOptions(queryClient, id), { status: on ? "active" : "inactive" }); + void queryClient.invalidateQueries({ queryKey: ["analytics", "accounts"] }); + toast.success(on ? `${email} is back on` : `${email} switched off`); + } catch (e) { + toast.error(buildError(e as AppError)); + } + }; + return { + confirm, + workspaceZone, + warmupPending, + warmup: (id: string, action: WarmupAction) => runMutation(queryClient, warmupLifecycleOptions(queryClient, id), action), + remove: (id: string) => runMutation(queryClient, removeEmailOptions(queryClient, id), undefined), + switchOn: (id: string, email: string) => void setPower(id, email, true), + switchOff: (id: string, email: string) => confirm.show(switchOffPrompt(email), () => setPower(id, email, false)), + cloudEnroll: (id: string) => enroll(id), + cloudUnenroll: (id: string) => unenroll(id), + cloudLifecycle: (id: string, action: "pause" | "resume") => setCloudLifecycle({ id, action }), + }; + }, [queryClient, confirm, workspaceZone, warmupPending, enroll, unenroll, setCloudLifecycle]); +} + +export type MailboxRowActions = ReturnType; 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/leads/AddToContactsDialog.tsx b/web/src/components/app/leads/AddToContactsDialog.tsx new file mode 100644 index 000000000..f39801235 --- /dev/null +++ b/web/src/components/app/leads/AddToContactsDialog.tsx @@ -0,0 +1,283 @@ +import { useRef, useState } from "react"; +import toast from "react-hot-toast/headless"; +import { Link } from "@tanstack/react-router"; +import { ArrowRightIcon, BuildingIcon, FolderTreeIcon, Loader2Icon, type LucideIcon, MegaphoneIcon, TagsIcon, UserPlusIcon, UsersIcon } from "lucide-react"; +import CategoryPicker from "@/components/app/contacts/CategoryPicker"; +import { CampaignMultiPicker, SegmentMultiPicker } from "@/components/app/segments/SegmentPickers"; +import { Toggle } from "@/components/app/campaigns/preferences/components/CampaignPreferenceBoolBox"; +import { Checkbox } from "@/components/ui/checkbox"; +import type { AppError } from "@/lib/api/client/normalizeError"; +import { useAddLeadsToContacts } from "@/lib/api/hooks/app/leads/useLeads"; +import type { AddLeadsToContactsResult, LeadContactsWho, LeadSelection } from "@/lib/api/models/app/leads/Lead"; +import buildError from "@/lib/helper/buildError"; +import { cn } from "@/lib/utils"; +import LeadDialog from "./LeadDialog"; + +const WHO: { id: LeadContactsWho; label: string; hint: string; icon: LucideIcon }[] = [ + { id: "business", label: "The business", hint: "Each business's own address", icon: BuildingIcon }, + { id: "people", label: "The people", hint: "Owners, managers and staff found there", icon: UsersIcon }, + { id: "both", label: "Both", hint: "People first, then the business", icon: UserPlusIcon }, +]; + +export default function AddToContactsDialog({ + open, + onClose, + selection, + count, + suggestedSegment, +}: { + open: boolean; + onClose: () => void; + selection: LeadSelection; + count: number; + // Offered as the name of a new segment, usually the search's own name. + suggestedSegment?: string; +}) { + const add = useAddLeadsToContacts(); + const [who, setWho] = useState("business"); + const [segmentIds, setSegmentIds] = useState([]); + const [categoryIds, setCategoryIds] = useState([]); + const [campaignIds, setCampaignIds] = useState([]); + const [skipActive, setSkipActive] = useState(true); + const [verifiedOnly, setVerifiedOnly] = useState(false); + const [includeGuessed, setIncludeGuessed] = useState(false); + const [keepExisting, setKeepExisting] = useState(false); + const [result, setResult] = useState(null); + + // Bumped on close, so an import that finishes after it does not show its result. + const attempt = useRef(0); + const close = () => { + attempt.current++; + setResult(null); + onClose(); + }; + + const submit = async () => { + const mine = ++attempt.current; + try { + const res = await add.mutateAsync({ + ...selection, + who, + segment_ids: segmentIds, + category_ids: categoryIds, + campaign_ids: campaignIds, + skip_active_in_other_campaigns: campaignIds.length > 0 && skipActive, + verified_only: verifiedOnly, + include_guessed: includeGuessed, + keep_existing: keepExisting, + }); + if (mine === attempt.current) setResult(res); + const n = res.imported + res.updated; + if (n > 0) toast.success(`${n.toLocaleString()} contact${n === 1 ? "" : "s"} added`); + } catch (e) { + toast.error(buildError(e as AppError)); + } + }; + + return ( + } + eyebrow="Add to contacts" + title={`${count.toLocaleString()} lead${count === 1 ? "" : "s"}`} + footer={ + result ? ( + <> + + Open contacts + + + + + ) : ( + <> + + + + ) + } + > + {result ? ( + + ) : ( +
    +
    + Who to add +
    + {WHO.map((w) => { + const on = who === w.id; + return ( + + ); + })} +
    +

    + {who === "business" + ? "The business name becomes the company, with its website, address, rating and socials as fields." + : "Each person comes in with their name, title and LinkedIn, and the business as their company."}{" "} + Leads without an email stay in the finder. +

    +
    + +
    +
    +

    Add them to

    +

    Optional. Every contact made from this selection gets these.

    +
    + + + + + + + + + {campaignIds.length > 0 && ( + + )} + +
    + +
    + + {who !== "business" && !verifiedOnly && ( + + )} + +
    +
    + )} +
    + ); +} + +function Outcome({ result, who, keepExisting }: { result: AddLeadsToContactsResult; who: LeadContactsWho; keepExisting: boolean }) { + const added = result.imported + result.updated; + return ( +
    +
    +
    + +
    +
    +
    + {added.toLocaleString()} contact{added === 1 ? "" : "s"} added +
    +
    + {result.imported.toLocaleString()} new, {result.updated.toLocaleString()} updated +
    +
    +
    +
    + + + {who !== "business" && } + + + {result.failed > 0 && } +
    + {result.no_email > 0 && ( +

    Anyone without an email stays in the finder. Run Find people and emails on them, then add them again.

    + )} +
    + ); +} + +function SectionLabel({ children }: { children: React.ReactNode }) { + return
    {children}
    ; +} + +function Row({ icon: Icon, label, hint, children }: { icon: LucideIcon; label: string; hint: string; children: React.ReactNode }) { + return ( +
    +
    + +
    +

    {label}

    +

    {hint}

    +
    +
    +
    {children}
    +
    + ); +} + +function Option({ title, hint, children }: { title: string; hint: string; children: React.ReactNode }) { + return ( +
    +
    +
    {title}
    +
    {hint}
    +
    + {children} +
    + ); +} + +function Stat({ label, value, tone }: { label: string; value: number; tone?: string }) { + return ( +
    +
    {label}
    +
    {value.toLocaleString()}
    +
    + ); +} diff --git a/web/src/components/app/leads/EnrichmentProgress.tsx b/web/src/components/app/leads/EnrichmentProgress.tsx new file mode 100644 index 000000000..d1388d5d6 --- /dev/null +++ b/web/src/components/app/leads/EnrichmentProgress.tsx @@ -0,0 +1,124 @@ +import { useEffect, useMemo, useRef, useState } from "react"; +import { AnimatePresence, motion } from "framer-motion"; +import { useQueryClient } from "@tanstack/react-query"; +import { CheckCircle2Icon, TriangleAlertIcon, XIcon } from "lucide-react"; +import { LEADS_KEY, runActive } from "@/lib/api/hooks/app/leads/useLeads"; +import type { LeadEnrichmentRun } from "@/lib/api/models/app/leads/Lead"; +import { cn } from "@/lib/utils"; +import { fmtUsdCost } from "@/lib/money"; + +// The strip on top of the leads list: a search in flight, the website runs +// going in the background, and how each one ended. +export default function EnrichmentProgress({ runs, searching }: { runs: LeadEnrichmentRun[]; searching: string | null }) { + const qc = useQueryClient(); + const seen = useRef(new Map()); + const [finished, setFinished] = useState([]); + + // A run finishing refreshes the leads it touched and stays on screen a moment. + useEffect(() => { + const ended: LeadEnrichmentRun[] = []; + for (const r of runs) { + const before = seen.current.get(r.id); + if (before && before !== r.status && !runActive(r)) ended.push(r); + seen.current.set(r.id, r.status); + } + if (!ended.length) return; + qc.invalidateQueries({ queryKey: LEADS_KEY }); + setFinished((cur) => [...ended, ...cur].slice(0, 2)); + }, [runs, qc]); + + useEffect(() => { + if (!finished.length) return; + const t = setTimeout(() => setFinished((cur) => cur.slice(0, -1)), 9_000); + return () => clearTimeout(t); + }, [finished]); + + const active = useMemo(() => runs.filter(runActive), [runs]); + const total = active.reduce((n, r) => n + r.total, 0); + const processed = active.reduce((n, r) => n + r.processed, 0); + const emails = active.reduce((n, r) => n + r.emails_found, 0); + const people = active.reduce((n, r) => n + r.people_found, 0); + const pct = total ? Math.round((processed / total) * 100) : 0; + + return ( + + {searching && ( + + + {searching} + + + + + )} + {active.length > 0 && ( + + + Finding people and emails + + {processed.toLocaleString()} of {total.toLocaleString()} businesses + {emails > 0 && ` · ${emails.toLocaleString()} with an email`} + {people > 0 && ` · ${people.toLocaleString()} ${people === 1 ? "person" : "people"}`} + + Keeps going if you leave + {pct}% + + + + + + )} + {finished.map((r) => { + const failed = r.status === "error"; + return ( + + {failed ? : } + {failed ? "Stopped early" : "Done"} + + {failed && r.last_error + ? r.last_error + : `${r.emails_found.toLocaleString()} with an email${r.people ? `, ${r.people_found.toLocaleString()} ${r.people_found === 1 ? "person" : "people"}` : ""} from ${r.total.toLocaleString()} business${r.total === 1 ? "" : "es"}`} + {r.charged_usd > 0 && ` · ${fmtUsdCost(r.charged_usd)}`} + + + + ); + })} + + ); +} + +function Strip({ children, tone = "sky" }: { children: React.ReactNode; tone?: "sky" | "emerald" | "amber" }) { + return ( + +
    + {children} +
    +
    + ); +} + +function Track({ children }: { children: React.ReactNode }) { + return
    {children}
    ; +} diff --git a/web/src/components/app/leads/ExportDialog.tsx b/web/src/components/app/leads/ExportDialog.tsx new file mode 100644 index 000000000..624a8bf8b --- /dev/null +++ b/web/src/components/app/leads/ExportDialog.tsx @@ -0,0 +1,154 @@ +import { useEffect, useState } from "react"; +import toast from "react-hot-toast/headless"; +import { DownloadIcon, Loader2Icon } from "lucide-react"; +import { Checkbox } from "@/components/ui/checkbox"; +import type { AppError } from "@/lib/api/client/normalizeError"; +import { downloadBlob } from "@/lib/api/client/app/contacts/exportContacts"; +import { exportLeads } from "@/lib/api/client/app/leads/leads"; +import type { LeadExportFormat, LeadExportRows, LeadFinderConfig, LeadSelection } from "@/lib/api/models/app/leads/Lead"; +import buildError from "@/lib/helper/buildError"; +import { cn } from "@/lib/utils"; +import LeadDialog from "./LeadDialog"; + +const FORMATS: { id: LeadExportFormat; label: string; hint: string }[] = [ + { id: "csv", label: "CSV", hint: "Any spreadsheet or CRM" }, + { id: "xlsx", label: "Excel", hint: "Frozen header, numbers as numbers" }, + { id: "json", label: "JSON", hint: "For scripts and tools" }, +]; + +const ROWS: { id: LeadExportRows; label: string; hint: string }[] = [ + { id: "leads", label: "One row per business", hint: "Its own address, with the people in one column" }, + { id: "people", label: "One row per person", hint: "Name, title and address, then the business" }, +]; + +export default function ExportDialog({ + open, + onClose, + selection, + count, + config, +}: { + open: boolean; + onClose: () => void; + selection: LeadSelection; + count: number; + config: LeadFinderConfig; +}) { + const [format, setFormat] = useState("csv"); + const [rows, setRows] = useState("leads"); + const [columns, setColumns] = useState(config.default_export_columns); + const [busy, setBusy] = useState(false); + useEffect(() => { + if (open) setColumns(config.default_export_columns); + }, [open, config.default_export_columns]); + + // The people column only exists in per-business rows. + const sent = rows === "people" ? columns.filter((k) => k !== "people") : columns; + const toggle = (k: string) => setColumns((c) => (c.includes(k) ? c.filter((x) => x !== k) : [...config.export_columns.map((x) => x.key).filter((x) => c.includes(x) || x === k)])); + + const run = async () => { + setBusy(true); + try { + const blob = await exportLeads({ ...selection, format, columns: sent, rows }); + downloadBlob(blob, `${rows === "people" ? "lead-people" : "leads"}-${new Date().toISOString().slice(0, 10)}.${format}`); + toast.success(`Exported ${count.toLocaleString()} lead${count === 1 ? "" : "s"}`); + onClose(); + } catch (e) { + toast.error(buildError(e as AppError)); + } finally { + setBusy(false); + } + }; + + return ( + } + eyebrow="Export" + title={`${count.toLocaleString()} lead${count === 1 ? "" : "s"}`} + width={560} + footer={ + <> + + {rows === "people" ? `${config.person_columns.length} person columns + ${sent.length}` : `${sent.length} columns`} + + + + + } + > +
    +
    + {ROWS.map((r) => ( + + ))} +
    +
    + {FORMATS.map((f) => ( + + ))} +
    +
    +
    + {rows === "people" ? "Business columns" : "Columns"} + + · + +
    +
    + {config.export_columns.filter((c) => rows === "leads" || c.key !== "people").map((c) => ( + + ))} +
    + {rows === "people" && ( +

    + Each row starts with {config.person_columns.map((c) => c.label.toLowerCase()).slice(0, 4).join(", ")} and more. Businesses with nobody found are left out. +

    + )} +
    +
    +
    + ); +} diff --git a/web/src/components/app/leads/FilterPanel.tsx b/web/src/components/app/leads/FilterPanel.tsx new file mode 100644 index 000000000..3751ff828 --- /dev/null +++ b/web/src/components/app/leads/FilterPanel.tsx @@ -0,0 +1,167 @@ +import { RotateCcwIcon } from "lucide-react"; +import { NumberInput } from "@/components/ui/field"; +import { Toggle } from "@/components/app/campaigns/preferences/components/CampaignPreferenceBoolBox"; +import type { LeadFacets, LeadStatus } from "@/lib/api/models/app/leads/Lead"; +import { cn } from "@/lib/utils"; +import { EMPTY_REFINE, refineCount, type ReachFilter, type Refine } from "./refine"; + +const REACH: { id: ReachFilter; label: string }[] = [ + { id: "email", label: "Has email" }, + { id: "people", label: "Has people" }, + { id: "website", label: "Has website" }, + { id: "phone", label: "Has phone" }, + { id: "socials", label: "Has socials" }, + { id: "no_website", label: "No website" }, +]; + +const STATUSES: { id: LeadStatus; label: string }[] = [ + { id: "new", label: "New" }, + { id: "saved", label: "Saved" }, + { id: "contacted", label: "Contacted" }, + { id: "dismissed", label: "Dismissed" }, +]; + +const RATINGS: { v: number | null; label: string }[] = [ + { v: null, label: "Any" }, + { v: 3, label: "3+" }, + { v: 4, label: "4+" }, + { v: 4.5, label: "4.5+" }, +]; + +export default function FilterPanel({ value, onChange, facets }: { value: Refine; onChange: (r: Refine) => void; facets?: LeadFacets }) { + const set = (k: K, v: Refine[K]) => onChange({ ...value, [k]: v }); + const toggle = (list: T[], v: T) => (list.includes(v) ? list.filter((x) => x !== v) : [...list, v]); + const count = refineCount(value); + return ( +
    +
    + Refine results + {count > 0 && ( + + )} +
    + + {REACH.map((r) => ( + { + let next = toggle(value.reach, r.id); + if (r.id === "no_website") next = next.filter((x) => x !== "website"); + if (r.id === "website") next = next.filter((x) => x !== "no_website"); + set("reach", next); + }}> + {r.label} + + ))} + + +
    + {RATINGS.map((r) => ( + + ))} +
    +
    +
    + set("minReviews", v)} /> + set("maxReviews", v)} /> + set("minScore", Math.min(100, v))} /> +
    + + {STATUSES.map((s) => ( + set("statuses", toggle(value.statuses, s.id))}> + {s.label} + + ))} + + {facets && facets.categories.length > 1 && ( + + {facets.categories.slice(0, 12).map((c) => ( + set("category", value.category === c.value ? "" : c.value)}> + {c.value} + {c.count} + + ))} + + )} + {facets && facets.tags.length > 0 && ( + + {facets.tags.map((t) => ( + set("tag", value.tag === t.value ? "" : t.value)}> + {t.value} + {t.count} + + ))} + + )} +
    + set("inView", v)} /> + set("hideContacts", v)} /> + set("excludeChains", v)} /> + 0} + onChange={(v) => set("hideDismissed", v)} + /> +
    +
    + ); +} + +function Group({ label, children }: { label: string; children: React.ReactNode }) { + return ( +
    +
    {label}
    +
    {children}
    +
    + ); +} + +function Pill({ on, onClick, children }: { on: boolean; onClick: () => void; children: React.ReactNode }) { + return ( + + ); +} + +function NumField({ label, value, onChange }: { label: string; value: number; onChange: (v: number) => void }) { + return ( + + ); +} + +function Switch({ label, value, onChange, disabled }: { label: string; value: boolean; onChange: (v: boolean) => void; disabled?: boolean }) { + return ( +
    + {label} + +
    + ); +} diff --git a/web/src/components/app/leads/LeadDialog.tsx b/web/src/components/app/leads/LeadDialog.tsx new file mode 100644 index 000000000..cf7b33a9c --- /dev/null +++ b/web/src/components/app/leads/LeadDialog.tsx @@ -0,0 +1,82 @@ +import { AnimatePresence, motion } from "framer-motion"; +import { XIcon } from "lucide-react"; +import { useEffect } from "react"; + +// The card every lead finder dialog sits in; closes on backdrop and Escape. +export default function LeadDialog({ + open, + onClose, + icon, + eyebrow, + title, + children, + footer, + width = 520, +}: { + open: boolean; + onClose: () => void; + icon: React.ReactNode; + eyebrow: string; + title: string; + children: React.ReactNode; + footer: React.ReactNode; + width?: number; +}) { + useEffect(() => { + if (!open) return; + const key = (e: KeyboardEvent) => { + if (e.key !== "Escape") return; + if (document.querySelector("[data-floating]") || document.querySelector('[role="alertdialog"]')) return; + onClose(); + }; + window.addEventListener("keydown", key); + return () => window.removeEventListener("keydown", key); + }, [open, onClose]); + + return ( + + {open && ( + + e.stopPropagation()} + style={{ maxWidth: width }} + className="w-full rounded-lg bg-white border border-slate-200 shadow-[0_24px_48px_-12px_rgba(15,23,42,0.18),0_8px_16px_-8px_rgba(15,23,42,0.1)] overflow-hidden flex flex-col max-h-[85dvh]" + > +
    +
    {icon}
    + {eyebrow} +
    + {title} + +
    +
    {children}
    +
    {footer}
    +
    +
    + )} +
    + ); +} diff --git a/web/src/components/app/leads/LeadDrawer.tsx b/web/src/components/app/leads/LeadDrawer.tsx new file mode 100644 index 000000000..77975b25e --- /dev/null +++ b/web/src/components/app/leads/LeadDrawer.tsx @@ -0,0 +1,572 @@ +import { useEffect, useRef, useState } from "react"; +import { AnimatePresence, motion } from "framer-motion"; +import toast from "react-hot-toast/headless"; +import { + BuildingIcon, + CheckIcon, + ClockIcon, + CopyIcon, + ExternalLinkIcon, + FileTextIcon, + GlobeIcon, + InfoIcon, + Loader2Icon, + LockIcon, + MailIcon, + MapIcon, + MapPinIcon, + PhoneIcon, + SparklesIcon, + StarIcon, + TagIcon, + UserPlusIcon, + UsersIcon, + XIcon, +} from "lucide-react"; +import { Link } from "@tanstack/react-router"; +import ResourceViewers from "@/components/app/presence/ResourceViewers"; +import ScrollStrip from "@/components/ui/scroll-strip"; +import { usePresenceResource } from "@/hooks/PresenceProvider"; +import type { AppError } from "@/lib/api/client/normalizeError"; +import { useEnrichLeads, useLead, useUpdateLead } from "@/lib/api/hooks/app/leads/useLeads"; +import type { Lead, LeadFinderConfig, LeadStatus } from "@/lib/api/models/app/leads/Lead"; +import buildError from "@/lib/helper/buildError"; +import timeAgo from "@/lib/helper/timeAgo"; +import { cn } from "@/lib/utils"; +import PeopleTab from "./PeopleTab"; +import { ScoreBar } from "./badges"; +import { STATUS_LABEL, emailVerdict } from "./verdict"; + +type Tab = "overview" | "people" | "website" | "notes"; + +const SOCIAL_LABEL: Record = { + facebook: "Facebook", + instagram: "Instagram", + linkedin: "LinkedIn", + twitter: "X", + tiktok: "TikTok", + youtube: "YouTube", + pinterest: "Pinterest", + yelp: "Yelp", +}; + +export default function LeadDrawer({ + id, + config, + onClose, + onAddToContacts, +}: { + id: string | null; + config: LeadFinderConfig; + onClose: () => void; + onAddToContacts: (id: string) => void; +}) { + const lead = useLead(id); + const [tab, setTab] = useState("overview"); + usePresenceResource(id ? `lead:${id}` : null, "viewing"); + + useEffect(() => { + if (!id) return; + const key = (e: KeyboardEvent) => { + if (e.key !== "Escape" || document.querySelector("[data-floating]") || document.querySelector('[role="dialog"],[role="alertdialog"]')) return; + onClose(); + }; + window.addEventListener("keydown", key); + return () => window.removeEventListener("keydown", key); + }, [id, onClose]); + + return ( + + {id && ( + + {!lead.data ? ( +
    + {lead.isError ? ( +

    This lead is no longer here.

    + ) : ( + + )} +
    + ) : ( + + )} +
    + )} +
    + ); +} + +function Body({ + lead, + config, + tab, + onTab, + onClose, + onAddToContacts, +}: { + lead: Lead; + config: LeadFinderConfig; + tab: Tab; + onTab: (t: Tab) => void; + onClose: () => void; + onAddToContacts: (id: string) => void; +}) { + const update = useUpdateLead(); + const enrich = useEnrichLeads(); + const provider = config.providers.find((p) => p.id === lead.provider)?.name ?? lead.provider; + const reachable = !!lead.email || (lead.people ?? []).some((p) => p.email && p.email_status !== "suppressed" && p.email_status !== "invalid"); + const setStatus = (status: LeadStatus) => + update.mutate({ id: lead.id, patch: { status } }, { onError: (e) => toast.error(buildError(e as unknown as AppError)) }); + + const findEmails = async () => { + try { + await enrich.mutateAsync({ lead_ids: [lead.id], verify: true, people: true }); + toast.success(lead.website ? `Reading ${lead.domain || "the website"} for people and contact details` : `Looking for ${lead.name}'s website`); + } catch (e) { + toast.error(buildError(e as AppError)); + } + }; + + return ( + <> +
    +
    +
    + +
    +
    +

    {lead.name}

    +

    {[lead.category, lead.city].filter(Boolean).join(" · ") || provider}

    +
    + + +
    +
    +
    + {(["new", "saved", "contacted", "dismissed"] as LeadStatus[]).map((s) => ( + + ))} +
    +
    + +
    +
    +
    + + {lead.contact_id ? ( + + + In contacts + + ) : ( + + )} + {lead.website && ( + + + Site + + )} + {lead.maps_url && ( + + + Map + + )} +
    +
    + + {( + [ + ["overview", "Overview", InfoIcon], + ["people", "People", UsersIcon], + ["website", "Website", GlobeIcon], + ["notes", "Notes", FileTextIcon], + ] as const + ).map(([key, label, Icon]) => ( + + ))} + +
    + {tab === "overview" && onTab("people")} />} + {tab === "people" && } + {tab === "website" && } + {tab === "notes" && } +
    + + ); +} + +function Section({ title, children }: { title: string; children: React.ReactNode }) { + return ( +
    +

    {title}

    + {children} +
    + ); +} + +function copy(v: string) { + navigator.clipboard?.writeText(v).then( + () => toast.success("Copied"), + () => toast.error("Could not copy"), + ); +} + +function Overview({ lead, provider, onPeople }: { lead: Lead; provider: string; onPeople: () => void }) { + const socials = Object.entries(lead.socials ?? {}); + const deciders = (lead.people ?? []).filter((p) => p.seniority !== "staff").slice(0, 3); + return ( + <> + {deciders.length > 0 && ( +
    + +
    + )} +
    + {lead.emails.length === 0 ? ( +

    + {lead.enrichment_status === "no_website" + ? "The listing has no website, and none could be confirmed from the business's name." + : lead.enrichment_status === "done" + ? "The website lists no email address." + : lead.enrichment_status === "failed" + ? `The website could not be read${lead.site.error ? `: ${lead.site.error}` : "."}` + : "Not looked for yet. Find people and emails reads the business's own site."} +

    + ) : ( +
      + {lead.emails.map((e) => { + const v = emailVerdict(e); + return ( +
    • + +
      +
      + {e.email} + {e.email === lead.email && Primary} +
      +
      + + {v.icon} + {v.label} + + · + {e.source === "website" ? "From the website" : `From ${provider}`} + {e.domain_match && · On their domain} +
      +
      + +
    • + ); + })} +
    + )} +
    +
    +
    + {lead.phone && ( + }> + + {lead.phone} + + + )} + {lead.website && ( + }> + + {lead.domain || lead.website} + + + {lead.site.found_website && Found from the name, confirmed on the site} + + )} + {lead.address && ( + }> + {lead.address} + + )} + {(lead.rating != null || lead.review_count != null) && ( + }> + + {lead.rating != null ? `${lead.rating.toFixed(1)} stars` : "No rating"} + {lead.review_count != null && from {lead.review_count.toLocaleString()} reviews} + {lead.price_level != null && · {"$".repeat(lead.price_level)}} + + + )} + {lead.business_status && lead.business_status !== "operational" && ( + }> + {lead.business_status === "closed" ? "Permanently closed" : "Temporarily closed"} + + )} + {lead.chain && ( + }> + Part of {lead.chain} + + )} +
    + {lead.description &&

    {lead.description}

    } +
    + {socials.length > 0 && ( +
    +
    + {socials.map(([kind, url]) => ( + + {SOCIAL_LABEL[kind] ?? kind} + + + ))} +
    +
    + )} + {lead.hours.length > 0 && ( +
    +
      + {lead.hours.map((h) => ( +
    • + + {h} +
    • + ))} +
    +
    + )} + {lead.categories.length > 0 && ( +
    +
    + {lead.categories.map((c) => ( + + {c} + + ))} +
    +
    + )} +

    + From {provider} · first found {timeAgo(lead.first_seen_at)} +

    + + ); +} + +function Fact({ icon, children }: { icon: React.ReactNode; children: React.ReactNode }) { + return ( +
    + {icon} +
    {children}
    +
    + ); +} + +function Website({ lead }: { lead: Lead }) { + const s = lead.site; + if (!lead.website) + return ( +

    + {lead.enrichment_status === "no_website" + ? "No website could be found for this business. That alone can be the reason to reach out." + : "The listing has no website. Find people and emails looks for one from the business's name first."} +

    + ); + if (!s.checked_at) return

    Not read yet. Find people and emails reads the site and reports what it runs on.

    ; + if (!s.reachable) return

    The website could not be read{s.error ? `: ${s.error}` : "."}

    ; + return ( + <> +
    +
    + : }> + {s.https ? "Served over HTTPS" : "No HTTPS"} + + {s.platform && ( + }> + Built with {s.platform} + + )} + }> + + {s.pages ?? 1} page{(s.pages ?? 1) === 1 ? "" : "s"} read {timeAgo(s.checked_at)} + + +
    + {(s.title || s.description) && ( +
    + {s.title &&

    {s.title}

    } + {s.description &&

    {s.description}

    } +
    + )} +
    + {s.signals && s.signals.length > 0 && ( +
    +
    + {s.signals.map((sig) => { + const gap = /^No |Not |Outdated/.test(sig); + return ( + + {sig} + + ); + })} +
    +

    Amber marks a gap you could offer to fix.

    +
    + )} + + ); +} + +function Notes({ lead }: { lead: Lead }) { + const update = useUpdateLead(); + const [notes, setNotes] = useState(lead.notes); + // A teammate's save must not overwrite what is being typed here. + const dirty = useRef(false); + const [tag, setTag] = useState(""); + useEffect(() => { + if (!dirty.current) setNotes(lead.notes); + }, [lead.notes]); + const save = (patch: Parameters[0]["patch"]) => + update.mutate({ id: lead.id, patch }, { onError: (e) => toast.error(buildError(e as unknown as AppError)) }); + const addTag = () => { + const t = tag.trim(); + setTag(""); + if (!t || lead.tags.includes(t)) return; + save({ tags: [...lead.tags, t] }); + }; + return ( + <> +
    +
    + {lead.tags.map((t) => ( + + + {t} + + + ))} + setTag(e.target.value)} + onKeyDown={(e) => { + if (e.key === "Enter" || e.key === ",") { + e.preventDefault(); + addTag(); + } + }} + onBlur={addTag} + placeholder="Add a tag…" + className="h-6 min-w-[100px] flex-1 rounded-md border border-transparent px-1.5 text-[12px] outline-none focus:border-slate-200" + /> +
    +
    +
    +