Skip to content

Commit 0cfb94e

Browse files
sh1pt-actions-fleet[bot]ralyodioclaude
authored
feat(rotation): buy automatic rotation, $29 per team per 30 days (CoinPay) (#272)
- Rotation page button + POST /api/credshare/teams/:slug/rotation/auto/checkout open a CoinPay hosted checkout (owner/admin only). - POST /api/coinpay/webhook and the page's return check settle once per checkout session (rotation_payments); paying again extends from the current end. - Hourly sweep: renewal email 3 days before, switch off when the days run out. A team switched on by hand (paid_until NULL) never expires. - Migration 012 (both dialects), CSP form-action allows coinpayportal.com. Co-authored-by: Anthony Ettinger <anthony@profullstack.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 63ecfb4 commit 0cfb94e

12 files changed

Lines changed: 521 additions & 15 deletions

‎apps/pwa/package.json‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
"version": "0.1.1",
44
"private": true,
55
"type": "module",
6-
"description": "LogicSRC credentials \u2014 Express app on Postgres (@profullstack/libsql-pg): auth + end-to-end-encrypted team credential sharing.",
6+
"description": "LogicSRC credentials — Express app on Postgres (@profullstack/libsql-pg): auth + end-to-end-encrypted team credential sharing.",
77
"scripts": {
88
"start": "bun src/server.mjs",
99
"dev": "bun --watch src/server.mjs",
@@ -12,6 +12,7 @@
1212
},
1313
"dependencies": {
1414
"@logicsrc/cli": "workspace:*",
15+
"@profullstack/coinpay-onboard": "0.3.1",
1516
"@profullstack/footer": "0.5.0",
1617
"@profullstack/libsql-pg": "^0.1.4",
1718
"@profullstack/profile": "0.1.6",

‎apps/pwa/src/lib/auto-rotation.mjs‎

Lines changed: 189 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,189 @@
1+
// Paid automatic rotation (Anthony, 2026-10-29): $29 buys one team 30 days of
2+
// rotation_auto_approve, so its due runs rotate without the approval click.
3+
//
4+
// CoinPay payments are one-off (crypto or PayPal), so nothing renews by itself:
5+
// a checkout buys a fixed term and paying again extends it from the current end.
6+
// The webhook and the Rotation page's return check both settle through
7+
// settlePayment(), which is idempotent on the checkout session id. The hourly
8+
// sweep turns the switch off when the paid days run out and emails the team's
9+
// owners and admins a renewal link 3 days before.
10+
//
11+
// rotation_auto_paid_until NULL with the switch on means it was flipped by hand
12+
// (a comp): it never expires and a payment does not cap it.
13+
import { CoinPay, readWebhook, verifyWebhook } from "@profullstack/coinpay-onboard";
14+
import { get, all, run } from "../db.mjs";
15+
import { config } from "../config.mjs";
16+
17+
export const DAY_MS = 24 * 60 * 60 * 1000;
18+
export const AUTO_ROTATION_PRICE_USD = Number(process.env.AUTO_ROTATION_PRICE_USD || 29);
19+
export const AUTO_ROTATION_DAYS = 30;
20+
export const RENEWAL_NOTICE_DAYS = 3;
21+
export const PROPERTY = "app.logicsrc.com";
22+
export const PURPOSE = "auto_rotation";
23+
24+
export { readWebhook };
25+
26+
/** Is automatic rotation on for this team right now? */
27+
export function autoRotationState(team, now = Date.now()) {
28+
const flag = Boolean(Number(team?.rotation_auto_approve));
29+
const paidUntil = team?.rotation_auto_paid_until == null ? null : Number(team.rotation_auto_paid_until);
30+
const manual = flag && paidUntil === null;
31+
const on = flag && (manual || paidUntil > now);
32+
return { on, manual, paidUntil, expired: flag && !manual && paidUntil <= now, daysLeft: on && !manual ? Math.ceil((paidUntil - now) / DAY_MS) : null };
33+
}
34+
35+
export const autoRotationOn = (team, now = Date.now()) => autoRotationState(team, now).on;
36+
37+
/** A CoinPay client on app.logicsrc.com's business key. */
38+
export function coinpayClient(env = process.env) {
39+
const token = env.COINPAY_API_KEY;
40+
if (!token) throw new Error("COINPAY_API_KEY is not configured");
41+
return new CoinPay({ token, base: env.COINPAY_API_URL || undefined });
42+
}
43+
44+
/** Open a hosted checkout for 30 days of automatic rotation on one team. */
45+
export async function createCheckout({ team, user, client = coinpayClient(), origin = config.origin }) {
46+
if (!user?.id || !user?.email) throw new Error("A signed-in user with an email is required");
47+
const back = `${origin}/teams/${encodeURIComponent(team.slug)}/rotation`;
48+
return client.createCheckoutSession({
49+
amount: AUTO_ROTATION_PRICE_USD,
50+
currency: "USD",
51+
description: `LogicSRC automatic rotation for ${team.slug}, ${AUTO_ROTATION_DAYS} days`,
52+
customerEmail: user.email,
53+
accountId: user.id,
54+
property: PROPERTY,
55+
metadata: { purpose: PURPOSE, team_id: team.id, team_slug: team.slug, user_id: user.id, days: AUTO_ROTATION_DAYS },
56+
successUrl: `${back}?checkout=success&session_id={CHECKOUT_SESSION_ID}`,
57+
cancelUrl: `${back}?checkout=cancelled`,
58+
expiresInMinutes: 60,
59+
});
60+
}
61+
62+
/** Verify X-CoinPay-Signature over the raw body. */
63+
export function verifySignature(rawBody, header, secret = process.env.COINPAY_WEBHOOK_SECRET) {
64+
if (!secret || !rawBody) return false;
65+
try { return verifyWebhook(rawBody, header, secret); } catch { return false; }
66+
}
67+
68+
/**
69+
* Grant the days a paid checkout bought. Idempotent on the checkout session (or
70+
* payment) id: the first settle extends the team, any later one (confirmed then
71+
* forwarded, a webhook retry, the return check) changes nothing.
72+
*/
73+
export async function settlePayment(payment, now = Date.now()) {
74+
const { checkoutSessionId, paymentId, teamId } = payment;
75+
const key = checkoutSessionId || paymentId;
76+
if (!key) return { handled: false, reason: "no checkout session or payment id" };
77+
if (!teamId) return { handled: false, reason: "no team_id" };
78+
// No amount check: only this site's business key can open a session, at the
79+
// server's price, and a crypto webhook's `amount` may be in the coin, not USD.
80+
const team = await get(`SELECT * FROM credshare_teams WHERE id = ?`, [teamId]);
81+
if (!team) return { handled: false, reason: "unknown team" };
82+
83+
const ins = await run(
84+
`INSERT INTO rotation_payments (checkout_session_id, payment_id, team_id, user_id, amount_usd, method, days, created_at) VALUES (?,?,?,?,?,?,?,?) ON CONFLICT (checkout_session_id) DO NOTHING`,
85+
[key, paymentId || null, teamId, payment.userId || null, payment.amountUsd ?? null, payment.method || null, AUTO_ROTATION_DAYS, now]
86+
);
87+
if (!Number(ins.rowsAffected)) return { handled: true, duplicate: true, teamId };
88+
89+
const state = autoRotationState(team, now);
90+
if (state.manual) {
91+
await run(`UPDATE rotation_payments SET paid_until = NULL WHERE checkout_session_id = ?`, [key]);
92+
return { handled: true, action: "already-on-by-hand", teamId };
93+
}
94+
const from = state.on ? state.paidUntil : now;
95+
const paidUntil = from + AUTO_ROTATION_DAYS * DAY_MS;
96+
await run(
97+
`UPDATE credshare_teams SET rotation_auto_approve = 1, rotation_auto_paid_until = ?, rotation_auto_reminded_for = NULL WHERE id = ?`,
98+
[paidUntil, teamId]
99+
);
100+
await run(`UPDATE rotation_payments SET paid_until = ? WHERE checkout_session_id = ?`, [paidUntil, key]);
101+
await run(
102+
`INSERT INTO credshare_audit (id, team_id, actor_user_id, action, key_name, created_at) VALUES (?,?,?,?,?,?)`,
103+
[`aud_${key}`, teamId, payment.userId || team.created_by, state.on ? "rotation.auto.extended" : "rotation.auto.paid", new Date(paidUntil).toISOString().slice(0, 10), now]
104+
).catch(() => {});
105+
return { handled: true, action: state.on ? "extended" : "activated", teamId, paidUntil };
106+
}
107+
108+
/** Settle from a verified webhook payload. */
109+
export async function settleWebhook(payload, now = Date.now()) {
110+
const event = readWebhook(payload);
111+
if (!event.paid) return { handled: false, type: event.type, status: event.status };
112+
if (event.property && event.property !== PROPERTY) return { handled: false, reason: "other property" };
113+
const meta = event.metadata || {};
114+
if (meta.purpose && meta.purpose !== PURPOSE) return { handled: false, reason: `purpose ${meta.purpose}` };
115+
return settlePayment({
116+
checkoutSessionId: event.checkoutSessionId,
117+
paymentId: event.paymentId,
118+
teamId: meta.team_id,
119+
userId: meta.user_id || event.accountId,
120+
amountUsd: event.amountUsd,
121+
method: event.method,
122+
}, now);
123+
}
124+
125+
/**
126+
* The Rotation page's return check: if CoinPay already marks the session paid
127+
* for this team, settle it now (the webhook may still be on its way).
128+
*/
129+
export async function reconcileReturn(sessionId, team, client = coinpayClient(), now = Date.now()) {
130+
if (!sessionId || !/^cs_[A-Za-z0-9_-]+$/.test(sessionId)) return null;
131+
const session = await client.checkoutSession(sessionId);
132+
const meta = session.metadata || {};
133+
if (meta.team_id !== team.id || (meta.purpose && meta.purpose !== PURPOSE)) return null;
134+
if (session.status === "paid") {
135+
await settlePayment({
136+
checkoutSessionId: session.id,
137+
paymentId: session.paymentId || null,
138+
teamId: team.id,
139+
userId: meta.user_id || session.accountId,
140+
amountUsd: session.amount,
141+
method: session.paidMethod || null,
142+
}, now);
143+
}
144+
return session.status;
145+
}
146+
147+
async function sendMail(to, subject, text) {
148+
if (!config.resend.apiKey || !to.length) return false;
149+
const response = await fetch("https://api.resend.com/emails", {
150+
method: "POST",
151+
headers: { authorization: `Bearer ${config.resend.apiKey}`, "content-type": "application/json" },
152+
body: JSON.stringify({ from: config.resend.from, to, subject, text }),
153+
}).catch(() => null);
154+
return Boolean(response && response.ok);
155+
}
156+
157+
async function approverEmails(teamId) {
158+
return (await all(
159+
`SELECT u.email FROM credshare_members m JOIN users u ON u.id = m.user_id WHERE m.team_id = ? AND m.status = 'active' AND m.role IN ('owner', 'admin')`,
160+
[teamId]
161+
)).map((r) => r.email).filter(Boolean);
162+
}
163+
164+
/**
165+
* The hourly sweep: turn the switch off for teams whose paid days ran out, and
166+
* email a renewal link to teams with 3 days or less left (once per paid term).
167+
*/
168+
export async function sweepAutoRotation({ now = Date.now(), send = sendMail, origin = config.origin } = {}) {
169+
const lapsed = await all(
170+
`SELECT id, slug FROM credshare_teams WHERE rotation_auto_approve = 1 AND rotation_auto_paid_until IS NOT NULL AND rotation_auto_paid_until <= ?`,
171+
[now]
172+
);
173+
for (const t of lapsed) {
174+
await run(`UPDATE credshare_teams SET rotation_auto_approve = 0 WHERE id = ? AND rotation_auto_paid_until <= ?`, [t.id, now]);
175+
await send(await approverEmails(t.id), `Automatic rotation is now off for ${t.slug}`,
176+
`The paid automatic rotation for the LogicSRC team "${t.slug}" has ended. Due keys now wait for an owner or admin to approve them again.\n\nTurn it back on ($${AUTO_ROTATION_PRICE_USD} for ${AUTO_ROTATION_DAYS} days): ${origin}/teams/${encodeURIComponent(t.slug)}/rotation`);
177+
}
178+
const ending = await all(
179+
`SELECT id, slug, rotation_auto_paid_until FROM credshare_teams WHERE rotation_auto_approve = 1 AND rotation_auto_paid_until > ? AND rotation_auto_paid_until <= ? AND (rotation_auto_reminded_for IS NULL OR rotation_auto_reminded_for <> rotation_auto_paid_until)`,
180+
[now, now + RENEWAL_NOTICE_DAYS * DAY_MS]
181+
);
182+
for (const t of ending) {
183+
const until = new Date(Number(t.rotation_auto_paid_until)).toISOString().slice(0, 10);
184+
await send(await approverEmails(t.id), `Automatic rotation for ${t.slug} ends ${until}`,
185+
`The paid automatic rotation for the LogicSRC team "${t.slug}" ends on ${until} (UTC). After that, due keys wait for an owner or admin to approve them.\n\nRenew for another ${AUTO_ROTATION_DAYS} days ($${AUTO_ROTATION_PRICE_USD}, added to the current end): ${origin}/teams/${encodeURIComponent(t.slug)}/rotation`);
186+
await run(`UPDATE credshare_teams SET rotation_auto_reminded_for = ? WHERE id = ?`, [t.rotation_auto_paid_until, t.id]);
187+
}
188+
return { expired: lapsed.map((t) => t.slug), reminded: ending.map((t) => t.slug) };
189+
}

‎apps/pwa/src/lib/security-headers.mjs‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,8 @@
88
// cannot read storage.
99
//
1010
// form-action allows the CLI's loopback login redirect (http://127.0.0.1:<port>)
11-
// and the shared footer's newsletter form (pit.world).
11+
// the shared footer's newsletter form (pit.world), and the redirect to CoinPay's
12+
// hosted checkout after the "Turn on automatic rotation" form (coinpayportal.com).
1213
export const CSP = [
1314
"default-src 'self'",
1415
"script-src 'self' 'wasm-unsafe-eval'",
@@ -22,7 +23,7 @@ export const CSP = [
2223
"base-uri 'none'",
2324
"frame-src 'none'",
2425
"frame-ancestors 'none'",
25-
"form-action 'self' http://127.0.0.1:* http://localhost:* https://pit.world"
26+
"form-action 'self' http://127.0.0.1:* http://localhost:* https://pit.world https://coinpayportal.com"
2627
].join("; ");
2728

2829
export function securityHeaders(req, res, next) {
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
-- Postgres copy of migrations/012_auto_rotation_billing.sql (INTEGER -> bigint). Additive only.
2+
-- Paid automatic rotation: a CoinPay checkout buys 30 days of rotation_auto_approve
3+
-- for one team; NULL paid_until = flipped by hand, never expires.
4+
-- No inline comments: the pg shim joins lines.
5+
ALTER TABLE credshare_teams ADD COLUMN IF NOT EXISTS rotation_auto_paid_until bigint;
6+
ALTER TABLE credshare_teams ADD COLUMN IF NOT EXISTS rotation_auto_reminded_for bigint;
7+
CREATE TABLE IF NOT EXISTS rotation_payments (
8+
checkout_session_id TEXT PRIMARY KEY,
9+
payment_id TEXT,
10+
team_id TEXT NOT NULL REFERENCES credshare_teams(id) ON DELETE CASCADE,
11+
user_id TEXT,
12+
amount_usd double precision,
13+
method TEXT,
14+
days bigint NOT NULL,
15+
paid_until bigint,
16+
created_at bigint NOT NULL
17+
);
18+
CREATE INDEX IF NOT EXISTS idx_rotation_payments_team ON rotation_payments(team_id, created_at);
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
-- Paid automatic rotation (Anthony, 2026-10-29: $29 per team per 30 days).
2+
--
3+
-- A CoinPay checkout buys 30 days of rotation_auto_approve for one team.
4+
-- rotation_auto_paid_until is when the paid days end: NULL means the switch was
5+
-- flipped by hand and never expires. The hourly sweep turns the switch off once
6+
-- that time passes, and emails the team's owners and admins a renewal link 3
7+
-- days before (rotation_auto_reminded_for = the paid_until it reminded about).
8+
-- rotation_payments is the idempotency ledger: one row per checkout session.
9+
-- Additive only.
10+
ALTER TABLE credshare_teams ADD COLUMN rotation_auto_paid_until INTEGER;
11+
ALTER TABLE credshare_teams ADD COLUMN rotation_auto_reminded_for INTEGER;
12+
CREATE TABLE IF NOT EXISTS rotation_payments (
13+
checkout_session_id TEXT PRIMARY KEY,
14+
payment_id TEXT,
15+
team_id TEXT NOT NULL REFERENCES credshare_teams(id) ON DELETE CASCADE,
16+
user_id TEXT,
17+
amount_usd REAL,
18+
method TEXT,
19+
days INTEGER NOT NULL,
20+
paid_until INTEGER,
21+
created_at INTEGER NOT NULL
22+
);
23+
CREATE INDEX IF NOT EXISTS idx_rotation_payments_team ON rotation_payments(team_id, created_at);
Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
// Buying automatic rotation ($29 / 30 days per team) through CoinPay.
2+
//
3+
// POST /teams/:slug/rotation/auto/checkout the Rotation page button: 303 to CoinPay checkout
4+
// POST /api/credshare/teams/:slug/rotation/auto/checkout the same for the CLI / MCP: {url, sessionId}
5+
// GET /api/credshare/teams/:slug/rotation/auto the switch's state
6+
// POST /api/coinpay/webhook CoinPay events (X-CoinPay-Signature over the raw body)
7+
//
8+
// Only a team owner or admin can buy (a person, never a machine key). The webhook
9+
// and the page's return check settle through lib/auto-rotation.mjs settlePayment().
10+
import { Router } from "express";
11+
import { get } from "../db.mjs";
12+
import { requireAuth } from "../lib/session.mjs";
13+
import { api, requireMember } from "./credshare.mjs";
14+
import { autoRotationState, createCheckout, settleWebhook, verifySignature, AUTO_ROTATION_PRICE_USD, AUTO_ROTATION_DAYS } from "../lib/auto-rotation.mjs";
15+
16+
export const autoRotationRouter = Router();
17+
18+
const canBuy = (member) => member?.role === "owner" || member?.role === "admin";
19+
20+
async function buyer(userId) {
21+
return get(`SELECT id, email FROM users WHERE id = ?`, [userId]);
22+
}
23+
24+
autoRotationRouter.post("/teams/:slug/rotation/auto/checkout", requireAuth, async (req, res, next) => {
25+
const team = await get(`SELECT * FROM credshare_teams WHERE slug = ?`, [req.params.slug]);
26+
const member = team && await get(`SELECT * FROM credshare_members WHERE team_id = ? AND user_id = ? AND status = 'active'`, [team.id, req.user.id]);
27+
if (!team || !member) return next();
28+
const back = `/teams/${encodeURIComponent(team.slug)}/rotation`;
29+
if (!canBuy(member)) return res.redirect(`${back}?err=${encodeURIComponent("Only a team owner or admin can turn on automatic rotation.")}`);
30+
try {
31+
const session = await createCheckout({ team, user: await buyer(req.user.id) });
32+
res.redirect(303, session.url);
33+
} catch (e) {
34+
console.error("auto-rotation checkout failed:", e.message);
35+
res.redirect(`${back}?err=${encodeURIComponent("Could not open the CoinPay checkout. Try again in a minute.")}`);
36+
}
37+
});
38+
39+
autoRotationRouter.get("/api/credshare/teams/:slug/rotation/auto", api(async (req, res, user, key) => {
40+
const ctx = await requireMember(res, req.params.slug, user.id, key); if (!ctx) return;
41+
const s = autoRotationState(ctx.team);
42+
res.json({ team: ctx.team.slug, on: s.on, manual: s.manual, paidUntil: s.paidUntil ? new Date(s.paidUntil).toISOString() : null, daysLeft: s.daysLeft, priceUsd: AUTO_ROTATION_PRICE_USD, days: AUTO_ROTATION_DAYS });
43+
}, { machine: "read" }));
44+
45+
autoRotationRouter.post("/api/credshare/teams/:slug/rotation/auto/checkout", api(async (req, res, user, key) => {
46+
const ctx = await requireMember(res, req.params.slug, user.id, key); if (!ctx) return;
47+
if (!canBuy(ctx.member)) return res.status(403).json({ error: "Only a team owner or admin can turn on automatic rotation." });
48+
const session = await createCheckout({ team: ctx.team, user: await buyer(user.id) });
49+
res.status(201).json({ sessionId: session.id, url: session.url, priceUsd: AUTO_ROTATION_PRICE_USD, days: AUTO_ROTATION_DAYS });
50+
}));
51+
52+
autoRotationRouter.post("/api/coinpay/webhook", async (req, res) => {
53+
if (!verifySignature(req.rawBody, req.get("x-coinpay-signature"))) return res.status(401).json({ error: "Invalid signature" });
54+
try {
55+
const result = await settleWebhook(req.body);
56+
console.log("coinpay webhook", JSON.stringify(result));
57+
res.json({ received: true, ...result });
58+
} catch (e) {
59+
console.error("coinpay webhook settle failed:", e);
60+
res.status(500).json({ error: "Settle failed" });
61+
}
62+
});

0 commit comments

Comments
 (0)