fix(rotation): one CoinPay login per run, real login errors (CLI 0.16.1) (#292)

coinpaySession() POSTed /api/auth/login from every preflight and mint of
the CoinPay API key and webhook secret rotators. A run over ~220 CoinPay
keys fired hundreds of logins from one address; coinpayportal limits
sign-in to 10/min, so all but the first few preflights failed and were
reported as "needs a CoinPay merchant session" even with correct
credentials.

- Memoize the session per base URL + email for the whole run (concurrent
  callers share one in-flight login; failures are cached too so a bad or
  throttled login is not retried per key).
- A 401 on a session call logs in again once and retries (not for
  COINPAY_ROTATE_TOKEN).
- Login failures name the cause: 401 wrong credentials, 429 rate limited,
  402 paywall throttle, otherwise status + short body. No secrets printed.

Co-authored-by: riotcoder <riotcoder@profullstack.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Anthony Ettinger 2026-11-22 02:57:37 -08:00 • committed by GitHub
parent 5716bad54e
commit d8a08c006b
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
5 changed files with 204 additions and 33 deletions

View file

@ -151,7 +151,7 @@
},
"packages/cli": {
"name": "@logicsrc/cli",
"version": "0.16.0",
"version": "0.16.1",
"bin": {
"logicsrc": "./dist/index.js",
},

View file

@ -196,7 +196,11 @@ health-check, then revoke the old one.
- Keys: `COINPAY_API_KEY`, `COINPAYPORTAL_API_KEY`, `COINPAY_*_API_KEY`,
`COINPAY_X402_KEY`.
- Needs a merchant session for the business owner: `COINPAY_ROTATE_TOKEN`, or
`COINPAY_ROTATE_EMAIL` + `COINPAY_ROTATE_PASSWORD`.
`COINPAY_ROTATE_EMAIL` + `COINPAY_ROTATE_PASSWORD`. With email + password the
CLI logs in once per run and every CoinPay key reuses that session (sign-in
is limited to 10/min per address); a 401 mid-run logs in again once. A failed
login is reported as its cause: wrong credentials (401), rate limited (429),
or the site's paywall throttle (402).
- Mint: the old key finds its business (`GET /api/businesses`), then `POST
/api/businesses/<id>/api-keys` creates a scoped key with the old key's scopes
(`*` for the legacy key). Old and new both work.

View file

@ -1,6 +1,6 @@
{
"name": "@logicsrc/cli",
"version": "0.16.0",
"version": "0.16.1",
"description": "LogicSRC CLI: every LogicSRC standard and tool as one command.",
"type": "module",
"main": "./dist/index.js",

View file

@ -1,12 +1,14 @@
import { createHash, createHmac, pbkdf2Sync } from "node:crypto";
import { describe, expect, it } from "vitest";
import { beforeEach, describe, expect, it } from "vitest";
import {
cloudflareTokenRotator,
coinpayApiKeyRotator,
coinpayLoginError,
coinpayWebhookSecretRotator,
newVapidPair,
postgresRoleRotator,
resendRotator,
resetCoinpaySessions,
rewriteUrls,
scramVerifier,
vapidRotator,
@ -127,17 +129,22 @@ describe("cloudflare-token", () => {
});
describe("coinpay", () => {
beforeEach(() => resetCoinpaySessions());
const legacy = "cp_live_legacyAAAAAAAAAAAAAAAA";
function coinpay() {
const state = { legacy, scoped: new Map<string, any>(), regenerated: 0, webhook: "whsec_old_xxxxxxxxxxxx" };
function coinpay(opts: { login?: { status: number; body?: any } } = {}) {
const state = { legacy, scoped: new Map<string, any>(), regenerated: 0, webhook: "whsec_old_xxxxxxxxxxxx", logins: 0, session: "session-jwt" };
const { fetch, calls } = fakeFetch((m, url, auth, body) => {
const p = url.pathname;
if (p === "/api/auth/login") return body.password === "pw" ? { status: 200, body: { success: true, token: "session-jwt" } } : { status: 401 };
if (p === "/api/auth/login") {
state.logins++;
if (opts.login) return opts.login;
return body.password === "pw" ? { status: 200, body: { success: true, token: state.session } } : { status: 401 };
}
if (p === "/api/businesses" && m === "GET") {
const ok = auth === state.legacy || [...state.scoped.values()].some((k) => k.raw === auth && !k.revoked_at) || auth === "session-jwt";
const ok = auth === state.legacy || [...state.scoped.values()].some((k) => k.raw === auth && !k.revoked_at) || auth === state.session;
return ok ? { status: 200, body: { success: true, businesses: [{ id: "b1", api_key: state.legacy, webhook_secret: state.webhook }] } } : { status: 401 };
}
if (auth !== "session-jwt") return { status: 401 };
if (auth !== state.session) return { status: 401 };
if (p === "/api/businesses/b1/api-keys" && m === "POST") {
const id = `k${state.scoped.size + 1}`;
state.scoped.set(id, { id, raw: `cp_live_scoped${id}BBBBBBBBBB`, scopes: body.scopes, prefix: `cp_live_scoped${id}`.slice(0, 16) });
@ -202,6 +209,81 @@ describe("coinpay", () => {
expect(state.webhook).toBe(minted.value);
expect(await minted.rollback()).toMatch(/cannot restore/);
});
it("logs in once for a whole run of many keys (preflight + mint each)", async () => {
const { state, fetch, calls } = coinpay();
let old = legacy;
for (let i = 0; i < 25; i++) {
const c = ctx({ key: `COINPAY_API_KEY_${i}`, oldValue: old, fetch, env });
expect(await coinpayApiKeyRotator.preflight(c)).toBeNull();
old = (await coinpayApiKeyRotator.mint(c)).value;
const w = ctx({ key: `COINPAY_WEBHOOK_SECRET_${i}`, oldValue: state.webhook, vaultValues: { COINPAY_API_KEY: legacy }, fetch, env });
expect(await coinpayWebhookSecretRotator.preflight(w)).toBeNull();
await coinpayWebhookSecretRotator.mint(w);
}
expect(state.logins).toBe(1);
expect(calls.filter((c) => c.path === "/api/auth/login")).toHaveLength(1);
});
it("concurrent preflights share one login", async () => {
const { state, fetch } = coinpay();
const results = await Promise.all(Array.from({ length: 50 }, () => coinpayApiKeyRotator.preflight(ctx({ oldValue: legacy, fetch, env }))));
expect(results.every((r) => r === null)).toBe(true);
expect(state.logins).toBe(1);
});
it("a 401 on the shared session logs in again once and retries", async () => {
const { state, fetch } = coinpay();
const c = ctx({ key: "COINPAY_API_KEY", oldValue: legacy, fetch, env });
expect(await coinpayApiKeyRotator.preflight(c)).toBeNull();
expect(state.logins).toBe(1);
state.session = "session-jwt-2"; // the first session expired server side
const minted = await coinpayApiKeyRotator.mint(c);
expect(minted.value).toBe("cp_live_scopedk1BBBBBBBBBB");
expect(state.logins).toBe(2);
// the refreshed session is reused by later calls
await minted.revokeOld();
await coinpayApiKeyRotator.mint(ctx({ key: "COINPAY_API_KEY", oldValue: minted.value, fetch, env }));
expect(state.logins).toBe(2);
});
it("does not re-login a COINPAY_ROTATE_TOKEN", async () => {
const { state, fetch } = coinpay();
state.session = "other";
const c = ctx({ key: "COINPAY_API_KEY", oldValue: legacy, fetch, env: { COINPAY_ROTATE_URL: "https://coinpay.test", COINPAY_ROTATE_TOKEN: "session-jwt" } });
await expect(coinpayApiKeyRotator.mint(c)).rejects.toThrow(/HTTP 401/);
expect(state.logins).toBe(0);
});
it("a failed login is reported as its real cause, once per run, without the password", async () => {
for (const [status, re] of [
[401, /CoinPay login rejected \(wrong COINPAY_ROTATE_EMAIL\/PASSWORD\)/],
[429, /rate limited.*retry later/],
[402, /throttled by the site's paywall \(rate limit/],
[503, /CoinPay login failed: HTTP 503 down for maintenance/]
] as const) {
resetCoinpaySessions();
const { state, fetch } = coinpay({ login: { status, body: { error: status === 503 ? "down for maintenance" : "nope" } } });
for (let i = 0; i < 5; i++) {
const why = await coinpayApiKeyRotator.preflight(ctx({ oldValue: legacy, fetch, env }));
expect(why).toMatch(re);
expect(why).not.toMatch(/needs a CoinPay merchant session/);
expect(why).not.toContain("pw");
const w = await coinpayWebhookSecretRotator.preflight(ctx({ vaultValues: { COINPAY_API_KEY: legacy }, fetch, env }));
expect(w).toMatch(re);
}
await expect(coinpayApiKeyRotator.mint(ctx({ oldValue: legacy, fetch, env }))).rejects.toThrow(re);
expect(state.logins).toBe(1);
}
});
it("maps login statuses to messages", () => {
expect(coinpayLoginError(401, "")).toBe("CoinPay login rejected (wrong COINPAY_ROTATE_EMAIL/PASSWORD)");
expect(coinpayLoginError(429, "")).toMatch(/rate limited, retry later|rate limited \(HTTP 429\), retry later/);
expect(coinpayLoginError(402, "")).toMatch(/paywall/);
expect(coinpayLoginError(500, "<html>\n oops </html>")).toBe("CoinPay login failed: HTTP 500 <html> oops </html>");
expect(coinpayLoginError(500, JSON.stringify({ message: "boom" }))).toBe("CoinPay login failed: HTTP 500 boom");
});
});
describe("vapid", () => {

View file

@ -205,17 +205,102 @@ function coinpayBase(ctx: RotatorContext): string {
return (ctx.env.COINPAY_ROTATE_URL || ctx.env.COINPAY_API_URL || "https://coinpayportal.com").replace(/\/+$/, "").replace(/\/api$/, "");
}
/** A merchant session: COINPAY_ROTATE_TOKEN, or log in with COINPAY_ROTATE_EMAIL + COINPAY_ROTATE_PASSWORD. */
async function coinpaySession(ctx: RotatorContext): Promise<string | null> {
if (ctx.env.COINPAY_ROTATE_TOKEN) return ctx.env.COINPAY_ROTATE_TOKEN;
if (!ctx.env.COINPAY_ROTATE_EMAIL || !ctx.env.COINPAY_ROTATE_PASSWORD) return null;
const res = await ctx.fetch(`${coinpayBase(ctx)}/api/auth/login`, {
/** Result of getting a merchant session: a bearer token, or why there is none. */
type CoinpaySession = { token: string; fromLogin: boolean } | { error: string };
const NO_SESSION = "needs a CoinPay merchant session: set COINPAY_ROTATE_TOKEN, or COINPAY_ROTATE_EMAIL + COINPAY_ROTATE_PASSWORD";
/**
* One login per run, shared by every preflight and mint (keyed by base URL +
* email). A run over a few hundred CoinPay keys used to POST /api/auth/login
* for each one; coinpayportal limits sign-in to 10/min per address, so all but
* the first few failed. Failures are cached too: retrying a rejected or
* rate-limited login per key only makes the limit worse.
*/
const coinpaySessions = new Map<string, Promise<CoinpaySession>>();
/** Forget cached CoinPay sessions (tests, or a long-lived process starting a new run). */
export function resetCoinpaySessions(): void {
coinpaySessions.clear();
}
function sessionKey(ctx: RotatorContext): string {
return `${coinpayBase(ctx)}\n${ctx.env.COINPAY_ROTATE_EMAIL ?? ""}`;
}
/** Maps a failed /api/auth/login response to a message that names the real cause. Never includes credentials. */
export function coinpayLoginError(status: number, bodyText: string): string {
if (status === 401) return "CoinPay login rejected (wrong COINPAY_ROTATE_EMAIL/PASSWORD)";
if (status === 429) return "CoinPay login rate limited (HTTP 429), retry later";
if (status === 402) return "CoinPay login throttled by the site's paywall (rate limit, HTTP 402), retry later";
let msg = "";
try {
const b = JSON.parse(bodyText);
msg = String(b?.error ?? b?.message ?? "");
} catch {
msg = bodyText;
}
msg = msg.replace(/\s+/g, " ").trim().slice(0, 160);
return `CoinPay login failed: HTTP ${status}${msg ? ` ${msg}` : ""}`;
}
async function coinpayLogin(ctx: RotatorContext): Promise<CoinpaySession> {
let res: Response;
try {
res = await ctx.fetch(`${coinpayBase(ctx)}/api/auth/login`, {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ email: ctx.env.COINPAY_ROTATE_EMAIL, password: ctx.env.COINPAY_ROTATE_PASSWORD })
});
const body = (await res.json().catch(() => null)) as any;
return res.ok && body?.token ? String(body.token) : null;
} catch (e) {
return { error: `CoinPay login failed: ${e instanceof Error ? e.message : String(e)}`.slice(0, 200) };
}
const text = await res.text().catch(() => "");
if (!res.ok) return { error: coinpayLoginError(res.status, text) };
let body: any = null;
try {
body = JSON.parse(text);
} catch {
/* handled below */
}
return body?.token ? { token: String(body.token), fromLogin: true } : { error: `CoinPay login failed: HTTP ${res.status} with no token in the response` };
}
/** A merchant session: COINPAY_ROTATE_TOKEN, or one memoized login with COINPAY_ROTATE_EMAIL + COINPAY_ROTATE_PASSWORD. */
async function coinpaySession(ctx: RotatorContext, opts: { fresh?: boolean } = {}): Promise<CoinpaySession> {
if (ctx.env.COINPAY_ROTATE_TOKEN) return { token: ctx.env.COINPAY_ROTATE_TOKEN, fromLogin: false };
if (!ctx.env.COINPAY_ROTATE_EMAIL || !ctx.env.COINPAY_ROTATE_PASSWORD) return { error: NO_SESSION };
const k = sessionKey(ctx);
let p = opts.fresh ? undefined : coinpaySessions.get(k);
if (!p) {
p = coinpayLogin(ctx);
coinpaySessions.set(k, p);
}
return p;
}
async function requireSession(ctx: RotatorContext): Promise<string> {
const s = await coinpaySession(ctx);
if ("error" in s) throw new RotatorError(s.error);
return s.token;
}
/**
* A call authenticated with the merchant session. A 401 means the shared
* session expired mid-run: log in again once (for every caller holding the
* stale token) and retry. A COINPAY_ROTATE_TOKEN is used as given.
*/
async function sessionCall(ctx: RotatorContext, url: string, init: RequestInit): Promise<{ status: number; body: any }> {
const s = await coinpaySession(ctx);
if ("error" in s) throw new RotatorError(s.error);
const r = await call(ctx, url, { ...init, token: s.token });
if (r.status !== 401 || !s.fromLogin) return r;
const k = sessionKey(ctx);
const cur = await coinpaySessions.get(k);
// Someone else may already have refreshed it; only log in again if the cache still holds the token that failed.
const next = cur && "token" in cur && cur.token !== s.token ? cur : await coinpaySession(ctx, { fresh: true });
if ("error" in next) throw new RotatorError(next.error);
return call(ctx, url, { ...init, token: next.token });
}
/** The business that owns a key: GET /api/businesses accepts the key itself and lists the owner's businesses. */
@ -238,12 +323,12 @@ export const coinpayApiKeyRotator: ProviderRotator = {
title: "CoinPay business API key",
overlap: true,
async preflight(ctx) {
if (!(await coinpaySession(ctx))) return "needs a CoinPay merchant session: set COINPAY_ROTATE_TOKEN, or COINPAY_ROTATE_EMAIL + COINPAY_ROTATE_PASSWORD (owner of the business)";
const s = await coinpaySession(ctx);
if ("error" in s) return s.error === NO_SESSION ? `${NO_SESSION} (owner of the business)` : s.error;
return null;
},
async mint(ctx) {
const session = await coinpaySession(ctx);
if (!session) throw new RotatorError("no CoinPay merchant session");
await requireSession(ctx);
const base = coinpayBase(ctx);
const r = await call(ctx, `${base}/api/businesses`, { method: "GET", token: ctx.oldValue });
if (r.status !== 200) fail("CoinPay: the old key does not authenticate", r);
@ -253,7 +338,7 @@ export const coinpayApiKeyRotator: ProviderRotator = {
if (!business) {
const prefix = ctx.oldValue.startsWith("cp_live_") ? ctx.oldValue.slice(0, 16) : "";
for (const b of businesses) {
const k = await call(ctx, `${base}/api/businesses/${b.id}/api-keys`, { method: "GET", token: session });
const k = await sessionCall(ctx, `${base}/api/businesses/${b.id}/api-keys`, { method: "GET" });
const hit = (k.body?.keys ?? []).find((x: any) => !x.revoked_at && prefix && x.prefix === prefix);
if (hit) {
business = b;
@ -264,9 +349,8 @@ export const coinpayApiKeyRotator: ProviderRotator = {
}
if (!business) throw new RotatorError("CoinPay: no business of this merchant owns the key (wrong COINPAY_ROTATE_* account?)");
const name = `logicsrc ${ctx.key.toLowerCase()} ${day(ctx.now)}`;
const created = await call(ctx, `${base}/api/businesses/${business.id}/api-keys`, {
const created = await sessionCall(ctx, `${base}/api/businesses/${business.id}/api-keys`, {
method: "POST",
token: session,
body: JSON.stringify({ name, scopes: scoped?.scopes?.length ? scoped.scopes : ["*"] })
});
if (created.status !== 201 && created.status !== 200) fail("CoinPay create scoped key", created);
@ -278,13 +362,13 @@ export const coinpayApiKeyRotator: ProviderRotator = {
state: { businessId: String(business.id), keyId: newId },
async revokeOld() {
const d = scoped
? await call(ctx, `${base}/api/businesses/${business.id}/api-keys/${scoped.id}`, { method: "DELETE", token: session })
: await call(ctx, `${base}/api/businesses/${business.id}/api-key`, { method: "POST", token: session });
? await sessionCall(ctx, `${base}/api/businesses/${business.id}/api-keys/${scoped.id}`, { method: "DELETE" })
: await sessionCall(ctx, `${base}/api/businesses/${business.id}/api-key`, { method: "POST" });
if (d.status >= 300 && d.status !== 404) fail("CoinPay revoke old key", d);
return undefined;
},
async rollback() {
const d = await call(ctx, `${base}/api/businesses/${business.id}/api-keys/${newId}`, { method: "DELETE", token: session });
const d = await sessionCall(ctx, `${base}/api/businesses/${business.id}/api-keys/${newId}`, { method: "DELETE" });
return d.status < 300 || d.status === 404 ? undefined : `revoke the new CoinPay key "${name}" by hand (HTTP ${d.status})`;
}
};
@ -301,19 +385,20 @@ export const coinpayWebhookSecretRotator: ProviderRotator = {
title: "CoinPay webhook secret",
overlap: false,
async preflight(ctx) {
if (!(await coinpaySession(ctx))) return "needs a CoinPay merchant session: set COINPAY_ROTATE_TOKEN, or COINPAY_ROTATE_EMAIL + COINPAY_ROTATE_PASSWORD";
const s = await coinpaySession(ctx);
if ("error" in s) return s.error;
if (!findApiKey(ctx)) return "no CoinPay API key in the same vault to find the business with";
return null;
},
async mint(ctx) {
const session = await coinpaySession(ctx);
const apiKey = findApiKey(ctx);
if (!session || !apiKey) throw new RotatorError("needs a CoinPay merchant session and the vault's CoinPay API key");
if (!apiKey) throw new RotatorError("needs the vault's CoinPay API key to find the business with");
await requireSession(ctx);
const base = coinpayBase(ctx);
const r = await call(ctx, `${base}/api/businesses`, { method: "GET", token: apiKey });
const business = (r.body?.businesses ?? []).find((b: any) => b.webhook_secret === ctx.oldValue);
if (!business) throw new RotatorError("CoinPay: no business has this webhook secret");
const g = await call(ctx, `${base}/api/businesses/${business.id}/webhook-secret`, { method: "POST", token: session });
const g = await sessionCall(ctx, `${base}/api/businesses/${business.id}/webhook-secret`, { method: "POST" });
if (g.status !== 200) fail("CoinPay regenerate webhook secret", g);
const value = String(g.body?.secret ?? "");
if (!value) throw new RotatorError("CoinPay regenerate webhook secret: no secret in the response");