cratefield-module-waitlist 0.1.1

Factory Zero module: per-product waitlist with confirm, position, referral codes
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
//! HTTP handlers for `/v1/waitlist` (architecture section 6, issue
//! #11). Positions are assigned atomically inside `Database::batch`
//! (see [`crate::store::confirm_entry`]); the POST answers the same
//! `202 {"ok":true}` bytes whatever the row state.

use axum::extract::{Query, State};
use axum::http::{HeaderMap, StatusCode, header};
use axum::response::{IntoResponse, Response};
use axum::routing::{get, post};
use cratefield_core::{
    Action, Audience, Captcha, Clock, Column, Decision, IdGen, Json, Kid, ModuleConfig,
    ModuleContext, Outcome, Payload, Problem, RateLimiter, SLUGS, Scope, SendOutcome, Signer,
    Surface, SystemClock, UlidIdGen, View, client_ip, csv_row, hint_field, invalid_email_problem,
    normalize_email, rate_limit_keys, rate_limited, require_admin, validation_error,
};
use schemars::JsonSchema;
use serde::Deserialize;
use serde_json::{Value, json};
use std::sync::Arc;
use time::format_description::well_known::Rfc3339;

use crate::mail::{self, ConfirmMailData, OutgoingMail, TEMPLATE_CONFIRM, TEMPLATE_CONFIRMED};
use crate::store::{self, STATUS_CONFIRMED, WaitlistRow};

pub(crate) const PURPOSE_CONFIRM: &str = "waitlist.confirm";
pub(crate) const PURPOSE_STATUS: &str = "waitlist.status";

pub(crate) const EVENT_JOINED: &str = "waitlist.joined";
pub(crate) const EVENT_CONFIRMED: &str = "waitlist.confirmed";

/// One confirmation mail per address+product per hour, mirroring
/// `module-email-signup`'s throttle.
pub(crate) const REMAIL_AFTER_SECS: i64 = 3600;

/// How the allowed product set is configured.
#[derive(Debug, Clone)]
pub(crate) enum Products {
    /// `.any_product()`: every product slug is accepted.
    Any,
    /// `.products([..])`: exactly these slugs (config `WAITLIST_PRODUCTS`
    /// overrides at runtime; `*` means any).
    List(Vec<String>),
}

/// The builder's compile-time settings, cloned into the router state.
#[derive(Clone)]
pub(crate) struct Settings {
    pub products: Products,
    pub confirm_ttl_days: u32,
    pub retention_days_pending: u32,
    pub status_redirect: Option<String>,
    pub referrals: bool,
    pub answers_schema: crate::AnswersSchema,
}

pub(crate) struct ModuleState {
    pub ctx: Arc<ModuleContext>,
    pub settings: Settings,
}

pub(crate) fn router(ctx: Arc<ModuleContext>, settings: Settings) -> axum::Router {
    let state = Arc::new(ModuleState { ctx, settings });
    axum::Router::new()
        .route("/", post(join))
        .route("/confirm", get(confirm))
        .route("/status", get(status))
        .route("/admin/export.csv", get(admin_export))
        .with_state(state)
}

pub(crate) fn now_iso() -> String {
    SystemClock
        .now()
        .replace_nanosecond(0)
        .expect("truncation stays in range")
        .format(&Rfc3339)
        .unwrap_or_default()
}

pub(crate) fn iso_ago(secs: i64) -> String {
    SystemClock
        .now()
        .replace_nanosecond(0)
        .expect("truncation stays in range")
        .saturating_sub(time::Duration::seconds(secs))
        .format(&Rfc3339)
        .unwrap_or_default()
}

fn unix_now() -> u64 {
    u64::try_from(SystemClock.now().unix_timestamp().max(0)).unwrap_or(0)
}

fn accepted() -> Response {
    (StatusCode::ACCEPTED, Json(json!({ "ok": true }))).into_response()
}

fn see_other(location: String) -> Response {
    (StatusCode::SEE_OTHER, [(header::LOCATION, location)]).into_response()
}

fn internal(scope: &Scope) -> Problem {
    Problem::internal().instance(&scope.request_id)
}

/// Where confirm lands by default: with the UI mounted (ADR 0010) on its
/// pages, otherwise on pages the venture site provides. Config and
/// builder settings still win over either.
fn landing_defaults(cfg: &ModuleConfig<'_>, ctx: &ModuleContext) -> (String, String) {
    if ctx.ui_mounted {
        let base = api_base(cfg, ctx);
        (
            format!("{base}/ui/waitlist/status"),
            format!("{base}/ui/waitlist/confirm/expired"),
        )
    } else {
        (
            format!("{}/waitlist/status", ctx.venture.public_url),
            format!("{}/confirm-expired", ctx.venture.public_url),
        )
    }
}

fn api_base(cfg: &ModuleConfig<'_>, ctx: &ModuleContext) -> String {
    cfg.get_opt("API_BASE")
        .unwrap_or_else(|| format!("https://api.{}", ctx.venture.domain))
}

fn configured_or_default(
    cfg: &ModuleConfig<'_>,
    key: &str,
    builder: Option<&String>,
    default: String,
) -> String {
    cfg.get_opt(key)
        .or_else(|| builder.cloned())
        .unwrap_or(default)
}

fn effective_products(cfg: &ModuleConfig<'_>, settings: &Settings) -> Products {
    match cfg.get_opt("PRODUCTS").as_deref() {
        Some("*") => Products::Any,
        Some(list) => Products::List(
            list.split(',')
                .map(str::trim)
                .filter(|slug| !slug.is_empty())
                .map(str::to_owned)
                .collect(),
        ),
        None => settings.products.clone(),
    }
}

fn product_allowed(products: &Products, product: &str) -> bool {
    match products {
        Products::Any => true,
        Products::List(list) => list.iter().any(|allowed| allowed == product),
    }
}

/// See `module-email-signup::handlers::rate_limit`: fails open with a
/// warning when the limiter is unreachable.
async fn rate_limit(
    state: &ModuleState,
    headers: &HeaderMap,
    email: Option<&str>,
) -> Option<Response> {
    let limiter: Arc<dyn RateLimiter> = state.ctx.ports.rate_limiter.clone()?;
    let ip = client_ip(headers);
    for key in rate_limit_keys(ip.as_deref(), email) {
        match limiter.limit(&key).await {
            Ok(Decision { ok: true, .. }) => {}
            Ok(Decision {
                ok: false,
                retry_after,
            }) => return Some(rate_limited(retry_after)),
            Err(err) => {
                tracing::warn!(error = %err, key = %key, "rate limiter unavailable; allowing");
            }
        }
    }
    None
}

async fn check_captcha(
    state: &ModuleState,
    headers: &HeaderMap,
    token: Option<&str>,
    scope: &Scope,
) -> Result<(), Problem> {
    let Some(captcha): Option<Arc<dyn Captcha>> = state.ctx.ports.captcha.clone() else {
        return Ok(());
    };
    let Some(token) = token else {
        return Err(Problem::new(&SLUGS.captcha_failed).instance(&scope.request_id));
    };
    let ip = client_ip(headers);
    match captcha.verify(token, ip.as_deref()).await {
        Ok(verdict) if verdict.ok => Ok(()),
        _ => Err(Problem::new(&SLUGS.captcha_failed).instance(&scope.request_id)),
    }
}

fn sanitize_locale(raw: Option<String>) -> String {
    fn is_tag(tag: &str) -> bool {
        let mut parts = tag.split('-');
        let language_ok = parts.next().is_some_and(|part| {
            (2..=3).contains(&part.len()) && part.chars().all(|c| c.is_ascii_alphabetic())
        });
        let region_ok = parts.next().is_none_or(|part| {
            (2..=4).contains(&part.len()) && part.chars().all(|c| c.is_ascii_alphabetic())
        });
        language_ok && region_ok && parts.next().is_none()
    }
    match raw {
        Some(tag) if is_tag(&tag) => tag,
        _ => "en".to_owned(),
    }
}

/// 8-char Crockford base32 from `IdGen`. A ULID's **last** 8 chars are
/// its random part; the first 8 are timestamp-dominated and consecutive
/// confirms inside one ~256 ms window would collide on the UNIQUE
/// constraint. Collisions on the random tail are backstopped by a
/// bounded retry in [`confirm_with_code`].
pub(crate) fn referral_code() -> String {
    let ulid = UlidIdGen.ulid();
    ulid.chars()
        .rev()
        .take(8)
        .collect::<String>()
        .to_lowercase()
}

fn unique_code_violation(err: &cratefield_core::DbError) -> bool {
    let detail = match err {
        cratefield_core::DbError::Batch(detail) | cratefield_core::DbError::Execute(detail) => {
            detail
        }
        cratefield_core::DbError::Query(_) => return false,
    };
    detail.contains("UNIQUE constraint failed") && detail.contains("referral_code")
}

/// Runs the confirm batch with up to three fresh referral codes; the
/// whole batch (position included) rolls back on a code collision, so a
/// retry assigns cleanly.
async fn confirm_with_code(
    db: &dyn cratefield_core::Database,
    row: &store::WaitlistRow,
    now: &str,
) -> Result<bool, cratefield_core::DbError> {
    let mut last_err = None;
    for _ in 0..3 {
        let code = referral_code();
        match store::confirm_entry(db, row, now, &code).await {
            Ok(flipped) => return Ok(flipped),
            Err(err) if unique_code_violation(&err) => {
                tracing::warn!("referral code collision; retrying with a fresh code");
                last_err = Some(err);
            }
            Err(err) => return Err(err),
        }
    }
    Err(last_err.expect("at least one attempt"))
}

#[derive(Deserialize, JsonSchema)]
struct JoinBody {
    #[schemars(extend(
        "x-cf-label" = "Email",
        "x-cf-widget" = "email",
        "x-cf-placeholder" = "you@example.com"
    ))]
    email: String,
    // Configured slugs become a `select` in [`surface`]; with
    // `.any_product()` it stays a text input.
    #[schemars(extend("x-cf-label" = "Product"))]
    product: String,
    // Referral code from the share link; the page supplies it.
    #[schemars(extend("x-cf-hidden" = true))]
    #[serde(rename = "ref")]
    referral: Option<String>,
    // Free-form answers; nested, so not form-renderable until a later
    // issue adds question rendering.
    #[schemars(extend("x-cf-hidden" = true))]
    answers: Option<Value>,
    #[schemars(extend("x-cf-hidden" = true))]
    locale: Option<String>,
    #[schemars(extend("x-cf-hidden" = true))]
    #[serde(rename = "captchaToken")]
    captcha_token: Option<String>,
}

/// The module's UI surface (ADR 0010, issue #71): the join form (product
/// as a `select` over the configured list), the confirm link, the status
/// page, and the admin export as a table.
pub(crate) fn surface(settings: &Settings) -> Surface {
    let mut join = cratefield_core::schema_for::<JoinBody>();
    if let Products::List(products) = &settings.products {
        hint_field(&mut join, "product", "enum", json!(products));
        hint_field(&mut join, "product", "x-cf-widget", json!("select"));
    }
    Surface::new()
        .action(
            Action::post("join", "/")
                .input_schema(join)
                .captcha()
                .accepted("Check your inbox to confirm your spot."),
        )
        .action(Action::get("confirm", "/confirm").input::<TokenQuery>())
        .action(
            Action::get("status", "/status")
                .input::<TokenQuery>()
                .outcome(Outcome::Json),
        )
        .action(
            Action::get("export", "/admin/export.csv")
                .audience(Audience::Admin)
                .input::<ExportQuery>()
                .outcome(Outcome::Json),
        )
        .view(View::form("join"))
        .view(View::status("status"))
        .view(View::table(
            "export",
            [
                ("id", "Id"),
                ("email", "Email"),
                ("product", "Product"),
                ("status", "Status"),
                ("position", "Position"),
                ("referral_code", "Referral code"),
                ("referred_by", "Referred by"),
                ("referrals", "Referrals"),
                ("created_at", "Created"),
                ("confirmed_at", "Confirmed"),
            ]
            .into_iter()
            .map(|(key, label)| Column::new(key, label))
            .collect(),
        ))
}

async fn join(
    scope: Scope,
    State(state): State<Arc<ModuleState>>,
    headers: HeaderMap,
    Json(body): Json<JoinBody>,
) -> Result<Response, Problem> {
    if let Some(denied) = rate_limit(&state, &headers, Some(&body.email)).await {
        return Ok(denied);
    }
    check_captcha(&state, &headers, body.captcha_token.as_deref(), &scope).await?;

    let cfg = ModuleConfig::new("waitlist", &*state.ctx.config);
    let normalized = validate_join(&state, &scope, &cfg, &body)?;

    let Some(db) = state.ctx.ports.db.clone() else {
        return Err(internal(&scope));
    };
    let Some(signer): Option<Arc<dyn Signer>> = state.ctx.ports.signer.clone() else {
        return Err(internal(&scope));
    };

    let existing = store::find_by_email_and_product(&*db, &normalized, &body.product).await?;
    if existing
        .as_ref()
        .is_some_and(|row| row.status == STATUS_CONFIRMED)
    {
        return Ok(accepted());
    }
    if existing
        .as_ref()
        .is_some_and(|row| row.created_at > iso_ago(REMAIL_AFTER_SECS))
    {
        return Ok(accepted());
    }

    let locale = sanitize_locale(body.locale);
    let answers_text = body.answers.as_ref().map(ToString::to_string);
    let referred_by = match body.referral.as_deref() {
        Some(code) if state.settings.referrals => {
            store::find_confirmed_by_referral_code(&*db, &body.product, code)
                .await?
                .map(|referrer| referrer.id)
        }
        _ => None,
    };

    let ttl_days = cfg.get_u32("CONFIRM_TTL_DAYS", state.settings.confirm_ttl_days);
    let id = existing
        .as_ref()
        .map_or_else(|| UlidIdGen.ulid(), |row| row.id.clone());
    let now = now_iso();
    send_join_confirmation(
        &state,
        &scope,
        &signer,
        &cfg,
        JoinMail {
            id: id.clone(),
            normalized: normalized.clone(),
            product: body.product.clone(),
            locale: locale.clone(),
            ttl_days,
            now: now.clone(),
        },
    )
    .await?;

    if let Some(row) = &existing {
        store::refresh_pending(
            &*db,
            &row.id,
            answers_text.as_deref(),
            referred_by.as_deref(),
            &now,
        )
        .await?;
    } else {
        store::insert_row(
            &*db,
            &WaitlistRow {
                id: id.clone(),
                email: body.email.trim().to_owned(),
                email_normalized: normalized.clone(),
                product: body.product.clone(),
                status: store::STATUS_PENDING.to_owned(),
                position: None,
                referral_code: None,
                referred_by,
                referrals: 0,
                answers: answers_text,
                created_at: now.clone(),
                confirmed_at: None,
            },
        )
        .await?;
        state.ctx.events.emit_in(
            &scope,
            EVENT_JOINED,
            json!({
                "entry_id": id,
                "email": normalized,
                "product": body.product,
            }),
        );
    }
    Ok(accepted())
}

/// Normalises the address and enforces the product allowlist and the
/// venture's answers schema; `Err` carries the matching problem.
fn validate_join(
    state: &ModuleState,
    scope: &Scope,
    cfg: &ModuleConfig<'_>,
    body: &JoinBody,
) -> Result<String, Problem> {
    let normalized = normalize_email(&body.email);
    if let Some(reason) = validation_error(&normalized) {
        return Err(invalid_email_problem(reason).instance(&scope.request_id));
    }
    let products = effective_products(cfg, &state.settings);
    if !product_allowed(&products, &body.product) {
        return Err(Problem::new(&SLUGS.unknown_product).instance(&scope.request_id));
    }
    if let Some(answers) = &body.answers
        && let Err(detail) = (state.settings.answers_schema)(answers)
    {
        return Err(
            Problem::validation_failed(format!("answers: {detail}")).instance(&scope.request_id)
        );
    }
    Ok(normalized)
}

/// Everything [`send_join_confirmation`] needs for one address.
struct JoinMail {
    id: String,
    normalized: String,
    product: String,
    locale: String,
    ttl_days: u32,
    now: String,
}

/// Signs the confirm token, renders and sends the join mail. Mail before
/// write (as in module-email-signup): a failed send leaves no row behind
/// the hourly throttle.
async fn send_join_confirmation(
    state: &ModuleState,
    scope: &Scope,
    signer: &Arc<dyn Signer>,
    cfg: &ModuleConfig<'_>,
    mail: JoinMail,
) -> Result<(), Problem> {
    let confirm_token = signer.sign(&Payload {
        purpose: PURPOSE_CONFIRM.to_owned(),
        subject: mail.id.clone(),
        exp: Some(unix_now().saturating_add(u64::from(mail.ttl_days) * 86_400)),
        kid: Kid::Cur,
    });
    let base = api_base(cfg, &state.ctx);
    let data = json!(ConfirmMailData {
        venture: state.ctx.venture.name.clone(),
        product: mail.product,
        email: mail.normalized.clone(),
        confirm_url: format!("{base}/v1/waitlist/confirm?token={confirm_token}"),
        brand: state.ctx.venture.brand.clone(),
    });
    match mail::send(
        &state.ctx,
        &OutgoingMail {
            to: mail.normalized.clone(),
            template_id: TEMPLATE_CONFIRM,
            data,
            locale: mail.locale,
            idempotency_key: format!("waitlist:{}:{}", mail.id, mail.now),
        },
    )
    .await
    {
        Ok(SendOutcome::Sent { .. }) => Ok(()),
        Ok(SendOutcome::NotConfigured) => {
            Err(Problem::new(&SLUGS.mail_not_configured).instance(&scope.request_id))
        }
        Err(err) => {
            tracing::error!(error = %err, "waitlist confirmation mail failed");
            Err(internal(scope))
        }
    }
}

#[derive(Deserialize, JsonSchema)]
struct TokenQuery {
    #[schemars(extend("x-cf-hidden" = true))]
    token: String,
}

async fn confirm(
    scope: Scope,
    State(state): State<Arc<ModuleState>>,
    headers: HeaderMap,
    Query(query): Query<TokenQuery>,
) -> Response {
    if let Some(denied) = rate_limit(&state, &headers, None).await {
        return denied;
    }
    let Some(signer): Option<Arc<dyn Signer>> = state.ctx.ports.signer.clone() else {
        return internal(&scope).into_response();
    };
    let Some(db) = state.ctx.ports.db.clone() else {
        return internal(&scope).into_response();
    };

    let cfg = ModuleConfig::new("waitlist", &*state.ctx.config);
    let (status_default, expired_default) = landing_defaults(&cfg, &state.ctx);
    let status_base = configured_or_default(
        &cfg,
        "STATUS_REDIRECT",
        state.settings.status_redirect.as_ref(),
        status_default,
    );
    let expired_target = configured_or_default(&cfg, "EXPIRED_REDIRECT", None, expired_default);

    let Some(payload) = signer.verify(&query.token, PURPOSE_CONFIRM) else {
        return see_other(expired_target);
    };
    let Ok(Some(row)) = store::find_by_id(&*db, &payload.subject).await else {
        return see_other(expired_target);
    };

    if row.status != STATUS_CONFIRMED {
        let now = now_iso();
        let flipped = match confirm_with_code(&*db, &row, &now).await {
            Ok(flipped) => flipped,
            Err(err) => {
                tracing::error!(error = %err, "waitlist confirm batch failed");
                return internal(&scope).into_response();
            }
        };
        if flipped {
            let fresh = store::find_by_id(&*db, &row.id)
                .await
                .ok()
                .flatten()
                .unwrap_or(row);
            let status_token = signer.sign(&Payload {
                purpose: PURPOSE_STATUS.to_owned(),
                subject: fresh.id.clone(),
                exp: None,
                kid: Kid::Cur,
            });
            state.ctx.events.emit_in(
                &scope,
                EVENT_CONFIRMED,
                json!({
                    "entry_id": fresh.id,
                    "email": fresh.email,
                    "product": fresh.product,
                    "position": fresh.position,
                    "referral_code": fresh.referral_code,
                }),
            );
            let base = api_base(&cfg, &state.ctx);
            let mail = OutgoingMail {
                to: fresh.email_normalized.clone(),
                template_id: TEMPLATE_CONFIRMED,
                data: json!(mail::ConfirmedMailData {
                    venture: state.ctx.venture.name.clone(),
                    product: fresh.product.clone(),
                    email: fresh.email.clone(),
                    position: fresh.position.unwrap_or(0),
                    status_url: format!("{base}/v1/waitlist/status?token={status_token}"),
                    brand: state.ctx.venture.brand.clone(),
                }),
                locale: "en".to_owned(),
                idempotency_key: format!(
                    "waitlist-confirmed:{}:{}",
                    fresh.id,
                    fresh.confirmed_at.as_deref().unwrap_or(&now)
                ),
            };
            scope
                .defer
                .wait_until(mail::spawn_deferred(Arc::clone(&state.ctx), mail));
            return see_other(format!("{status_base}?token={status_token}"));
        }
    }

    // Replay (or a lost race): the entry already holds a position.
    let status_token = signer.sign(&Payload {
        purpose: PURPOSE_STATUS.to_owned(),
        subject: row.id.clone(),
        exp: None,
        kid: Kid::Cur,
    });
    see_other(format!("{status_base}?token={status_token}"))
}

async fn status(
    scope: Scope,
    State(state): State<Arc<ModuleState>>,
    headers: HeaderMap,
    Query(query): Query<TokenQuery>,
) -> Result<Response, Problem> {
    if let Some(denied) = rate_limit(&state, &headers, None).await {
        let _ = denied;
        return Err(Problem::new(&SLUGS.rate_limited).instance(&scope.request_id));
    }
    let Some(signer): Option<Arc<dyn Signer>> = state.ctx.ports.signer.clone() else {
        return Err(internal(&scope));
    };
    let Some(db) = state.ctx.ports.db.clone() else {
        return Err(internal(&scope));
    };
    let Some(payload) = signer.verify(&query.token, PURPOSE_STATUS) else {
        return Err(Problem::new(&SLUGS.invalid_token).instance(&scope.request_id));
    };
    let Some(row) = store::find_by_id(&*db, &payload.subject).await? else {
        return Err(Problem::not_found().instance(&scope.request_id));
    };
    let code = row.referral_code.clone().unwrap_or_default();
    Ok(Json(json!({
        "product": row.product,
        "position": row.position,
        "referrals": row.referrals,
        "referralCode": code,
        "shareUrl": format!(
            "{}/waitlist/{}?ref={}",
            state.ctx.venture.public_url, row.product, code
        ),
    }))
    .into_response())
}

#[derive(Deserialize, Default, JsonSchema)]
struct ExportQuery {
    #[schemars(extend("x-cf-label" = "Product"))]
    product: Option<String>,
}

async fn admin_export(
    scope: Scope,
    State(state): State<Arc<ModuleState>>,
    headers: HeaderMap,
    Query(query): Query<ExportQuery>,
) -> Result<Response, Problem> {
    require_admin(&*state.ctx.config, &headers)
        .map_err(|problem| problem.instance(&scope.request_id))?;
    let Some(db) = state.ctx.ports.db.clone() else {
        return Err(internal(&scope));
    };
    let rows = store::list_for_export(&*db, query.product.as_deref()).await?;
    let mut body = String::from(
        "id,email,product,status,position,referral_code,referred_by,referrals,created_at,confirmed_at\n",
    );
    for row in &rows {
        let cells = [
            row.id.as_str(),
            row.email.as_str(),
            row.product.as_str(),
            row.status.as_str(),
            &row.position.map_or_else(String::new, |p| p.to_string()),
            row.referral_code.as_deref().unwrap_or(""),
            row.referred_by.as_deref().unwrap_or(""),
            &row.referrals.to_string(),
            row.created_at.as_str(),
            row.confirmed_at.as_deref().unwrap_or(""),
        ];
        body.push_str(&csv_row(&cells));
    }
    Ok((
        StatusCode::OK,
        [(header::CONTENT_TYPE, "text/csv; charset=utf-8")],
        body,
    )
        .into_response())
}