Archived
Take the donation here, on FlameNet's own account
Two things, and the second is why the first had to change. The money was landing on the wrong account. `FN_DONATE_SECRET` is a Stripe platform key, and a call that does not name a connected account is answered against the platform itself — with a 200, a receipt and a charge, so nothing about the page looks wrong and the only symptom is which balance it turns up in. `FN_DONATE_ACCOUNT` is now sent as `Stripe-Account` when the session is created, making the charge a direct one on FlameNet: its balance, its fees, its payout, FLAMENET on the statement. Unset stays valid and still means "charge whatever account this key belongs to", which is what a self-hoster with their own key wants — and boot now says which of the two it is doing, because the wrong one is otherwise silent. Taking the payment on the page is the other half. The session is created with `ui_mode=embedded_page` and mounted on `/donate`, so nobody is sent to Stripe's site and returned. The card fields are still Stripe's own, in a frame this server cannot read, which is what keeps this out of PCI scope — `js.stripe.com` is the price of that and cannot be self-hosted. ⚠️ `ui_mode=embedded` — the documented value when this was written — is now REJECTED: "The ui_mode value `embedded` is no longer supported. Use `embedded_page` instead." Nothing pins a Stripe-Version, so the account's default decides, and a rename on their side arrives as a 400 on a live donate page rather than as a build failure here. `Environment.value` comes with it, because the controller needs "blank means absent": Compose sets every `VAR: ${VAR:-}` to the empty string and `Environment.get` hands that back, so a plain `!= nil` reads an unconfigured deployment as a configured one — which is how a page offers payment with no processor behind it. The refusal is now specific: a missing publishable key, a test secret paired with a live publishable key, or an `FN_DONATE_ACCOUNT` that is not an account id each name themselves rather than rendering a form that cannot work. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5
parent
784ba853c8
commit
6f704cfb72
@@ -62,6 +62,14 @@ LOG_LEVEL=info
|
||||
# cached and indexed long before it can be rotated.
|
||||
FN_DONATE_PROVIDER=stripe
|
||||
FN_DONATE_SECRET=
|
||||
# The connected account donations are charged on, if the key above belongs to a
|
||||
# Stripe platform rather than to the account meant to receive the money. Blank
|
||||
# charges the key's own account, which is what a self-hoster wants.
|
||||
FN_DONATE_ACCOUNT=
|
||||
# Public by design, and handed to the browser: the embedded form cannot mount
|
||||
# without it. With FN_DONATE_ACCOUNT set this is the PLATFORM's pk_, not the
|
||||
# connected account's.
|
||||
FN_DONATE_PUBLISHABLE_KEY=
|
||||
|
||||
# Where "read the code" points. Change it if you run a fork — sending your users
|
||||
# to our repository to read code you have modified would be misleading.
|
||||
|
||||
@@ -51,7 +51,7 @@
|
||||
</p>
|
||||
|
||||
#if(enabled):
|
||||
<form class="donate" method="post" action="/donate/checkout">
|
||||
<form class="donate" id="donate-form">
|
||||
<fieldset class="donate-freq">
|
||||
<legend>How often</legend>
|
||||
<label><input type="radio" name="frequency" value="once" checked> Once</label>
|
||||
@@ -72,16 +72,101 @@
|
||||
</label>
|
||||
</fieldset>
|
||||
|
||||
<button class="btn btn-primary" type="submit">Continue to payment</button>
|
||||
<button class="btn btn-primary" type="submit" id="donate-continue">Continue to payment</button>
|
||||
<p class="fineprint" style="margin:16px 0 0">
|
||||
Payment is handled by Stripe on their own pages. Your card details never
|
||||
touch this server, and we never see them.
|
||||
The payment form opens on this page — you are not sent anywhere else.
|
||||
Card details go straight to Stripe from your browser and never touch this
|
||||
server, which is what keeps us out of them.
|
||||
</p>
|
||||
<noscript>
|
||||
<p class="donate-error" style="margin-top:16px">
|
||||
The payment form needs JavaScript, because that is what keeps the card
|
||||
fields inside Stripe's own frame rather than in a form this server
|
||||
could read.
|
||||
</p>
|
||||
</noscript>
|
||||
</form>
|
||||
|
||||
<div class="donate-error" id="donate-failed" hidden></div>
|
||||
|
||||
<!-- Filled in by Stripe once an amount is chosen. Empty until then: a
|
||||
session is a real object on their side, and opening one per page view
|
||||
would create a pile of abandoned ones. -->
|
||||
<div id="donate-checkout"></div>
|
||||
<p class="fineprint" id="donate-back" hidden style="margin:18px 0 0">
|
||||
<a href="/donate">Choose a different amount</a>
|
||||
</p>
|
||||
|
||||
<script src="https://js.stripe.com/v3/"></script>
|
||||
<script>
|
||||
(function () {
|
||||
var form = document.getElementById("donate-form");
|
||||
var mount = document.getElementById("donate-checkout");
|
||||
var failed = document.getElementById("donate-failed");
|
||||
var back = document.getElementById("donate-back");
|
||||
var button = document.getElementById("donate-continue");
|
||||
var checkout = null;
|
||||
|
||||
function fail(message) {
|
||||
failed.textContent = message;
|
||||
failed.hidden = false;
|
||||
button.disabled = false;
|
||||
button.textContent = "Continue to payment";
|
||||
}
|
||||
|
||||
form.addEventListener("submit", async function (event) {
|
||||
event.preventDefault();
|
||||
failed.hidden = true;
|
||||
button.disabled = true;
|
||||
button.textContent = "One moment\u2026";
|
||||
|
||||
// Only ever one live session on the page. Submitting twice otherwise
|
||||
// leaves the first frame mounted underneath the second.
|
||||
if (checkout) { checkout.destroy(); checkout = null; }
|
||||
|
||||
var data = new URLSearchParams(new FormData(form));
|
||||
var response;
|
||||
try {
|
||||
response = await fetch("/donate/session", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
||||
body: data.toString()
|
||||
});
|
||||
} catch (error) {
|
||||
return fail("Could not reach the server. Nothing was charged.");
|
||||
}
|
||||
|
||||
var body = await response.json().catch(function () { return {}; });
|
||||
if (!response.ok) {
|
||||
// Vapor puts the sentence in `reason`, and it is written to be read.
|
||||
return fail(body.reason || "Could not start a payment. Nothing was charged.");
|
||||
}
|
||||
|
||||
try {
|
||||
// Scoped to the connected account when there is one. A session opened
|
||||
// on that account cannot be mounted by a Stripe built without it —
|
||||
// and the failure is a frame that never appears, not an error anyone
|
||||
// reads.
|
||||
var account = "#(stripeAccount)";
|
||||
var stripe = account
|
||||
? Stripe("#(publishableKey)", { stripeAccount: account })
|
||||
: Stripe("#(publishableKey)");
|
||||
checkout = await stripe.initEmbeddedCheckout({ clientSecret: body.clientSecret });
|
||||
form.hidden = true;
|
||||
back.hidden = false;
|
||||
checkout.mount(mount);
|
||||
mount.scrollIntoView({ behavior: "smooth", block: "start" });
|
||||
} catch (error) {
|
||||
fail("Could not open the payment form. Nothing was charged.");
|
||||
}
|
||||
});
|
||||
})();
|
||||
</script>
|
||||
#else:
|
||||
<div class="donate-error">
|
||||
Donations aren't configured on this server. If you are self-hosting, set
|
||||
<code>FN_DONATE_PROVIDER</code> and <code>FN_DONATE_SECRET</code>.
|
||||
<code>FN_DONATE_PROVIDER</code>, <code>FN_DONATE_SECRET</code> and
|
||||
<code>FN_DONATE_PUBLISHABLE_KEY</code>.
|
||||
</div>
|
||||
#endif
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
import Vapor
|
||||
|
||||
extension Environment {
|
||||
/// A configuration value, where blank means absent.
|
||||
///
|
||||
/// `Environment.get` answers `""` for a variable that is set to nothing,
|
||||
/// and Compose sets every `VAR: ${VAR:-}` to exactly that rather than
|
||||
/// leaving it out. So a plain `!= nil` check reads an unconfigured
|
||||
/// deployment as a configured one — which is how a page offering payment
|
||||
/// renders with no payment processor behind it, and how a server announces
|
||||
/// a bucket it has no credentials for.
|
||||
static func value(_ name: String) -> String? {
|
||||
guard let raw = Environment.get(name) else { return nil }
|
||||
let trimmed = raw.trimmingCharacters(in: .whitespaces)
|
||||
return trimmed.isEmpty ? nil : trimmed
|
||||
}
|
||||
}
|
||||
@@ -13,13 +13,95 @@ import Vapor
|
||||
///
|
||||
/// Deliberately no Stripe SDK. One form-encoded POST is the whole integration,
|
||||
/// and a dependency that ships its own HTTP stack is not worth the surface.
|
||||
///
|
||||
/// The payment form is *embedded*: the session is created with `ui_mode=embedded`
|
||||
/// and mounted on `/donate`, so nobody is sent to a different site to pay and
|
||||
/// then bounced back. Card details still never reach this server — they are
|
||||
/// typed into a Stripe-hosted frame, which is what keeps this out of PCI scope.
|
||||
/// `js.stripe.com` is therefore a script this page loads, and the one part of
|
||||
/// the flow that cannot be served from here: Stripe does not permit that file to
|
||||
/// be self-hosted, and collecting raw card numbers ourselves to avoid it would
|
||||
/// trade a third-party script for full card-data liability.
|
||||
struct DonateController: RouteCollection {
|
||||
static let minAmount = 1
|
||||
static let maxAmount = 5_000
|
||||
|
||||
static var provider: String? { Environment.get("FN_DONATE_PROVIDER") }
|
||||
static var secret: String? { Environment.get("FN_DONATE_SECRET") }
|
||||
static var isEnabled: Bool { provider != nil && secret != nil }
|
||||
static var provider: String? { Environment.value("FN_DONATE_PROVIDER") }
|
||||
static var secret: String? { Environment.value("FN_DONATE_SECRET") }
|
||||
|
||||
/// Safe to put in the page — that is what it is for. Still configuration
|
||||
/// rather than a constant, because it differs per deployment and a
|
||||
/// self-hoster donating to themselves is not a case worth hard-coding.
|
||||
static var publishableKey: String? { Environment.value("FN_DONATE_PUBLISHABLE_KEY") }
|
||||
|
||||
/// The Stripe **connected account** donations are taken on, or nil to take
|
||||
/// them on whichever account the secret key itself authenticates as.
|
||||
///
|
||||
/// Set to an `acct_…` id and the session is created under that account — a
|
||||
/// *direct* charge, so the money, the fees, the receipt and the statement
|
||||
/// descriptor are its own rather than the platform's. Unset is not an
|
||||
/// error: a self-hoster with their own key wants exactly that. But with a
|
||||
/// platform key and no account, Stripe still answers 200 and the donation
|
||||
/// lands on the platform, which is the one failure here that never shows up
|
||||
/// on the page.
|
||||
///
|
||||
/// The publishable key stays the **platform's**: a direct charge is
|
||||
/// confirmed by the platform key scoped with `stripeAccount`, and the
|
||||
/// connected account's own key would be the wrong half of that pair.
|
||||
static var account: String? { Environment.value("FN_DONATE_ACCOUNT") }
|
||||
|
||||
/// Embedded checkout needs the publishable key as well: without it the form
|
||||
/// cannot render, and offering a button that fails on click is worse than
|
||||
/// saying donations are not configured.
|
||||
static var isEnabled: Bool { provider != nil && secret != nil && configurationProblem == nil }
|
||||
|
||||
enum Mode: String {
|
||||
case test, live
|
||||
}
|
||||
|
||||
/// Which Stripe account a key belongs to, read off its prefix.
|
||||
///
|
||||
/// Stripe encodes this in the key itself, which is the only reason it can
|
||||
/// be checked here at all — nothing is asked of the network.
|
||||
static func mode(of key: String) -> Mode? {
|
||||
if key.hasPrefix("sk_test_") || key.hasPrefix("pk_test_") { return .test }
|
||||
if key.hasPrefix("sk_live_") || key.hasPrefix("pk_live_") { return .live }
|
||||
return nil
|
||||
}
|
||||
|
||||
/// The mode donations are actually running in, or nil if it cannot be told.
|
||||
static var mode: Mode? { secret.flatMap(mode(of:)) }
|
||||
|
||||
/// Why donations are switched off, in a sentence, or nil if they are fine.
|
||||
///
|
||||
/// Every one of these is a configuration that *looks* like it works. A
|
||||
/// missing publishable key renders a form that cannot mount; a test secret
|
||||
/// on a live site takes payment details and collects nothing. Both are
|
||||
/// silent, and both are only ever noticed by the money not arriving — so
|
||||
/// they are turned into a refusal and a log line instead.
|
||||
static var configurationProblem: String? {
|
||||
guard provider != nil, let secret else { return nil }
|
||||
guard let publishableKey else {
|
||||
return "FN_DONATE_SECRET is set but FN_DONATE_PUBLISHABLE_KEY is not. "
|
||||
+ "The embedded payment form cannot render without it."
|
||||
}
|
||||
let secretMode = mode(of: secret)
|
||||
let publishableMode = mode(of: publishableKey)
|
||||
if secretMode != nil, publishableMode != nil, secretMode != publishableMode {
|
||||
return "FN_DONATE_SECRET is a \(secretMode!.rawValue) key and "
|
||||
+ "FN_DONATE_PUBLISHABLE_KEY is a \(publishableMode!.rawValue) key. "
|
||||
+ "They must be from the same Stripe account and mode."
|
||||
}
|
||||
if let account, !account.hasPrefix("acct_") {
|
||||
return "FN_DONATE_ACCOUNT is not a Stripe account id. "
|
||||
+ "It is the connected account donations are charged on and starts with acct_."
|
||||
}
|
||||
if publishableKey.hasPrefix("sk_") {
|
||||
return "FN_DONATE_PUBLISHABLE_KEY looks like a secret key. "
|
||||
+ "The publishable key starts with pk_ and is the one safe to put in a page."
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
struct Form: Content {
|
||||
let amount: String?
|
||||
@@ -34,7 +116,7 @@ struct DonateController: RouteCollection {
|
||||
error: request.query[String.self, at: "error"]
|
||||
))
|
||||
}
|
||||
routes.post("donate", "checkout", use: checkout)
|
||||
routes.post("donate", "session", use: session)
|
||||
}
|
||||
|
||||
struct DonateContext: Encodable {
|
||||
@@ -45,54 +127,81 @@ struct DonateController: RouteCollection {
|
||||
let appURL = SiteController.appURL
|
||||
let sourceURL = SiteController.sourceURL
|
||||
let enabled = DonateController.isEnabled
|
||||
let publishableKey = DonateController.publishableKey
|
||||
/// Empty rather than nil, so the page can test it as a string. Leaf
|
||||
/// renders an absent optional as nothing useful.
|
||||
let stripeAccount = DonateController.account ?? ""
|
||||
let minAmount = DonateController.minAmount
|
||||
let maxAmount = DonateController.maxAmount
|
||||
let thanks: Bool
|
||||
let error: String?
|
||||
}
|
||||
|
||||
func checkout(request: Request) async throws -> Response {
|
||||
guard let provider = Self.provider, let secret = Self.secret else {
|
||||
return request.redirect(to: "/donate?error=unavailable", redirectType: .normal)
|
||||
struct SessionResponse: Content {
|
||||
let clientSecret: String
|
||||
}
|
||||
|
||||
/// Opens a payment session and hands its client secret back to the page.
|
||||
///
|
||||
/// Answers JSON rather than redirecting, because the form it serves is
|
||||
/// mounted in place: a redirect here would be the exact thing this flow
|
||||
/// exists to avoid. Errors come back as a status and a sentence the page
|
||||
/// shows next to the form.
|
||||
func session(request: Request) async throws -> SessionResponse {
|
||||
guard let provider = Self.provider, let secret = Self.secret, Self.publishableKey != nil else {
|
||||
throw Abort(.serviceUnavailable, reason: "Donations aren't available right now. Nothing was charged.")
|
||||
}
|
||||
guard provider.lowercased() == "stripe" else {
|
||||
request.logger.error("unknown donate provider", metadata: ["provider": .string(provider)])
|
||||
throw Abort(.serviceUnavailable, reason: "Donations aren't available right now. Nothing was charged.")
|
||||
}
|
||||
|
||||
let form = try request.content.decode(Form.self)
|
||||
|
||||
// Resolve the amount before talking to anyone: an invalid one should
|
||||
// fail here, not after a redirect the person has to come back from.
|
||||
// Resolved before anyone is contacted: an invalid amount should fail
|
||||
// here, against the form the person is still looking at.
|
||||
let raw = (form.amount == "custom" ? form.custom_amount : form.amount) ?? ""
|
||||
guard let dollars = Int(raw.trimmingCharacters(in: .whitespaces)),
|
||||
dollars >= Self.minAmount, dollars <= Self.maxAmount
|
||||
else {
|
||||
return request.redirect(to: "/donate?error=amount", redirectType: .normal)
|
||||
throw Abort(.badRequest, reason: "Please enter an amount between $\(Self.minAmount) and $\(Self.maxAmount).")
|
||||
}
|
||||
|
||||
guard provider.lowercased() == "stripe" else {
|
||||
request.logger.error("unknown donate provider", metadata: ["provider": .string(provider)])
|
||||
return request.redirect(to: "/donate?error=unavailable", redirectType: .normal)
|
||||
}
|
||||
|
||||
let url = try await stripeSession(
|
||||
let clientSecret = try await stripeSession(
|
||||
dollars: dollars,
|
||||
recurring: (form.frequency ?? "once") == "monthly",
|
||||
secret: secret,
|
||||
request: request
|
||||
)
|
||||
// 303 so the browser follows with GET: refreshing the result page must
|
||||
// not re-post the form and open a second session.
|
||||
return request.redirect(to: url, redirectType: .normal)
|
||||
return SessionResponse(clientSecret: clientSecret)
|
||||
}
|
||||
|
||||
private func stripeSession(
|
||||
dollars: Int, recurring: Bool, secret: String, request: Request
|
||||
) async throws -> String {
|
||||
let scheme = request.headers.first(name: .init("X-Forwarded-Proto")) ?? "https"
|
||||
let host = request.headers.first(name: .host) ?? "localhost"
|
||||
let base = "\(scheme)://\(host)"
|
||||
// The deployment's own declared address, in preference to guessing one
|
||||
// from the request. Reconstructing it from the Host header meant
|
||||
// defaulting the scheme to https whenever no proxy set
|
||||
// `X-Forwarded-Proto`, which sends a donor on a plain-http server to an
|
||||
// https URL that does not answer — after they have paid, which is the
|
||||
// worst moment to hand somebody a dead page.
|
||||
let base = SiteController.siteURL.hasSuffix("/")
|
||||
? String(SiteController.siteURL.dropLast())
|
||||
: SiteController.siteURL
|
||||
|
||||
var fields: [String: String] = [
|
||||
"mode": recurring ? "subscription" : "payment",
|
||||
"success_url": "\(base)/donate?thanks=1",
|
||||
"cancel_url": "\(base)/donate",
|
||||
// ⚠️ `embedded`, the value this was written against, is REJECTED by
|
||||
// the current API version: "The ui_mode value `embedded` is no
|
||||
// longer supported. Use `embedded_page` instead." Nothing pins a
|
||||
// Stripe-Version here, so the account's default decides, and the
|
||||
// rename arrived as a 400 on a live donate page rather than at
|
||||
// build time.
|
||||
"ui_mode": "embedded_page",
|
||||
// Stripe sends the browser here itself once the payment completes,
|
||||
// and it is this site. There is no cancel_url in embedded mode:
|
||||
// there is nowhere to come back *from*.
|
||||
"return_url": "\(base)/donate?thanks=1",
|
||||
"line_items[0][quantity]": "1",
|
||||
"line_items[0][price_data][currency]": "usd",
|
||||
"line_items[0][price_data][unit_amount]": String(dollars * 100),
|
||||
@@ -113,6 +222,12 @@ struct DonateController: RouteCollection {
|
||||
var headers = HTTPHeaders()
|
||||
headers.add(name: .authorization, value: "Bearer \(secret)")
|
||||
headers.add(name: .contentType, value: "application/x-www-form-urlencoded")
|
||||
// Open the session *on the connected account*, not on the platform the
|
||||
// key authenticates as. One header is the whole of it. Omitting it is
|
||||
// not an error Stripe reports — it succeeds, against the wrong account.
|
||||
if let account = Self.account {
|
||||
headers.add(name: "Stripe-Account", value: account)
|
||||
}
|
||||
|
||||
// Spelled as a URI rather than a bare literal: SQLKit is in scope in
|
||||
// this target and its string-literal conformance otherwise wins.
|
||||
@@ -125,7 +240,7 @@ struct DonateController: RouteCollection {
|
||||
guard response.status == .ok,
|
||||
let data = response.body.flatMap({ Data(buffer: $0) }),
|
||||
let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
|
||||
let url = json["url"] as? String
|
||||
let clientSecret = json["client_secret"] as? String
|
||||
else {
|
||||
// The processor's own error text is written for a developer and may
|
||||
// name the account, so it is logged and not shown.
|
||||
@@ -133,6 +248,6 @@ struct DonateController: RouteCollection {
|
||||
metadata: ["status": .string(response.status.description)])
|
||||
throw Abort(.badGateway, reason: "Could not start a payment session. Please try again later.")
|
||||
}
|
||||
return url
|
||||
return clientSecret
|
||||
}
|
||||
}
|
||||
|
||||
@@ -71,6 +71,22 @@ func configure(_ app: Application) async throws {
|
||||
try await RLSGuard.assertRowLevelSecurityApplies(app)
|
||||
}
|
||||
|
||||
// MARK: donations
|
||||
//
|
||||
// Which Stripe account the money lands on, said out loud. A platform key
|
||||
// without a connected account takes real payments onto the wrong account
|
||||
// and reports nothing — the only symptom is the balance.
|
||||
if DonateController.secret != nil {
|
||||
switch DonateController.account {
|
||||
case .some(let account) where account.hasPrefix("acct_"):
|
||||
app.logger.notice("donations are taken on connected account \(account)")
|
||||
case .some(let account):
|
||||
app.logger.critical("FN_DONATE_ACCOUNT is not a Stripe account id (\(account)) — every donation will fail at the processor.")
|
||||
case .none:
|
||||
app.logger.warning("FN_DONATE_ACCOUNT is unset — donations land on whichever account FN_DONATE_SECRET belongs to, which on a platform key is the platform itself.")
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: uploads
|
||||
// Ciphertext only, but still worth a ceiling.
|
||||
app.routes.defaultMaxBodySize = "64mb"
|
||||
|
||||
@@ -121,6 +121,11 @@ services:
|
||||
ENCLAVE_APP_URL: ${ENCLAVE_APP_URL:-/app}
|
||||
FN_DONATE_PROVIDER: ${FN_DONATE_PROVIDER:-}
|
||||
FN_DONATE_SECRET: ${FN_DONATE_SECRET:-}
|
||||
# The connected account the donation is charged on, and the publishable
|
||||
# key the browser mounts the form with. Without the first, the same key
|
||||
# charges the platform account and Stripe reports no error.
|
||||
FN_DONATE_ACCOUNT: ${FN_DONATE_ACCOUNT:-}
|
||||
FN_DONATE_PUBLISHABLE_KEY: ${FN_DONATE_PUBLISHABLE_KEY:-}
|
||||
LOG_LEVEL: ${LOG_LEVEL:-info}
|
||||
volumes:
|
||||
# Ciphertext blobs. Without this the files themselves live only in the
|
||||
|
||||
Reference in New Issue
Block a user